diff --git a/CHANGELOG.md b/CHANGELOG.md index eecdb8ba..457e6337 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,79 @@ [TOC] -## 15.1.0 (2018-03-29) +## 15.2.0 (2019-06-28) + +Features: + - Updated the included OEMCrypto headers and reference code to v15.2. + - This is the first version of the CE CDM that supports OEMCrypto v15.2. Due + to changes in the threading guarantees in OEMCrypto v15.2, earlier + Widevine CE CDM 15.x releases are not safe to use with OEMCrypto v15.2 + implementations. + - The OEMCrypto build information is now reported in the license request. This + information can help with debugging integration issues. Content providers + can use this information to choose what licenses to return. + - The OEMCrypto tests have been expanded and cleaned up. + +Documentation: + - Clarified what integrators should return from `IStorage::size()` when there + is an error. All integrators should verify that their `IStorage::size()` + implementations adhere to the new requirements. + - The headers and documentation have been updated to emphasize that + `Cdm::removeUsageTable()` is rarely the correct method to use. Apps will + generally want to use `Cdm::deleteUsageRecord()` or + `Cdm::deleteAllUsageRecords()`. + - Expanded the documentation of the `oemcrypto_lib` property in the GYP files. + - Updated some product names in the + [OEMCrypto Version Compatibility][oec-version-compat] document. + - Previous releases incorrectly labelled the Widevine CE CDM 15.x releases as + being released in 2018. The documentation has been updated to correctly + reflect that they have been released in *2019*. + +Dependency Updates: + - Widevine CE CDM now requires jsmn [v1.0.0][jsmn-1.0.0]. Previous releases + did not specify a version requirement. However, recent updates to jsmn have + made versions after v1.0.0 incompatible with Widevine CE CDM. + - The included version of jsmn is v1.0.0. + - The bundled version of Protobuf has been updated to [v3.8.0][proto-3.8.0]. + Note that, as before, Widevine CE CDM will work with any version of Protobuf + back to 2.6. However, we provide the version of Protobuf that we test with + internally as a default. + - The bundled version of BoringSSL has been updated to commit + [`c0b4c72b6d4c6f4828a373ec454bd646390017d4`][boringssl-c0b4c7]. + +[jsmn-1.0.0]: https://github.com/zserge/jsmn/releases/tag/v1.0.0 +[proto-3.8.0]: https://github.com/protocolbuffers/protobuf/releases/tag/v3.8.0 +[boringssl-c0b4c7]: https://boringssl.googlesource.com/boringssl/+/c0b4c72b6d4c6f4828a373ec454bd646390017d4 + +Bugfixes: + - Fixed a bug that would cause decrypt to fail when using entitled key + rotation and having multiple entitlement keys loaded at the same time. + - Replaced `std::stringstream` with `std::to_string()` where possible. + - Fixed the clock-change test so that it compiles on Windows. + - Fixed a bug where the CDM would treat empty file paths as always existing, + which could result in attempts to delete an empty filename. + - Relaxed the OEMCrypto `UsageTableTest.GenerateReportWrongPST` test. + Previously, it would flag valid results with unusual buffer sizes as + failures. + - Made `OEMCryptoSessionTests.SelectKeyNotThereAPI15` more tolerant of + platforms where the error code is delayed. + - Fixed a bug where key status might be reported incorrectly because the key + container security level was not being taken into account when calculating + the key status to notify to the app. Note that this does not affect the + actual usability of the keys; the error was only in the status reported to + the app. + - The parallel execution tests now time out after 30 seconds rather than 10, + in order to be more forgiving of lower-powered devices. + - Fixed a case where the OEMCrypto Reference Implementation was accessing + the IStorage implementation before it was set when running the tests. This + was benign but could cause problems with other OEMCrypto implementations. + - To help catch cases like this in the future, debug builds of the CE CDM + now assert anytime `FileSystem::_impl` is `NULL`, rather than only when + it is constructed from a passed-in pointer. + - The sample `x86-64` platform files now include a define needed to enable GDB + to debug libstdc++ objects. + +## 15.1.0 (2019-03-29) Features: - It is now possible to use opaque handles even when the OEMCrypto integration @@ -59,7 +131,7 @@ Bugfixes: devices without SRM support. - Reworded some code that was tripping up the MSVC compiler. -## 15.0.0 (2018-02-28) +## 15.0.0 (2019-02-28) Features: - Widevine CE CDM 15.0.0 supports and requires OEMCrypto v15.1. The OEMCrypto diff --git a/README.md b/README.md index 384ec194..9a6c5f3f 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,20 @@ -# Widevine CE CDM 15.1.0 +# Widevine CE CDM 15.2.0 -Released 2018-03-29 +Released 2019-06-28 ## Getting started This project contains the sources for building a Widevine CDM module. Read the following to learn more about the contents of this project and how to use them: -[Widevine_CE_CDM_IntegrationGuide_15.1.0.pdf][integration-guide]\ +[Widevine_CE_CDM_IntegrationGuide_15.2.0.pdf][integration-guide]\ Documents the CDM API and describes how to integrate the CDM into a system. [CHANGELOG.md][changelog]\ Lists the major changes for each release. -[integration-guide]: ./Widevine_CE_CDM_IntegrationGuide_15.1.0.pdf +[integration-guide]: ./Widevine_CE_CDM_IntegrationGuide_15.2.0.pdf [changelog]: ./CHANGELOG.md ## Reference OEMCrypto Implementation diff --git a/Widevine_CE_CDM_IntegrationGuide_15.1.0.pdf b/Widevine_CE_CDM_IntegrationGuide_15.2.0.pdf similarity index 66% rename from Widevine_CE_CDM_IntegrationGuide_15.1.0.pdf rename to Widevine_CE_CDM_IntegrationGuide_15.2.0.pdf index 6548e050..f22de354 100644 Binary files a/Widevine_CE_CDM_IntegrationGuide_15.1.0.pdf and b/Widevine_CE_CDM_IntegrationGuide_15.2.0.pdf differ diff --git a/cdm/cdm_unittests.gyp b/cdm/cdm_unittests.gyp index ac311a01..809bb2b2 100644 --- a/cdm/cdm_unittests.gyp +++ b/cdm/cdm_unittests.gyp @@ -8,9 +8,31 @@ 'variables': { # Label as 'static' or 'dynamic' to use the respective OEMCrypto adapter. 'oemcrypto_adapter%': 'static', - # Choose type of OEMCrypto library to compile in (ref, level3, vendor). - # Production Level 1 systems should use vendor. + # Choose type of OEMCrypto library to compile in. Valid values are: + # + # 'vendor' - Production Level 1 systems should use 'vendor' to indicate that + # they are providing their own OEMCrypto library and the Widevine + # CE CDM build system is not responsible for building anything. + # + # 'ref' - The default value of 'ref' builds the OEMCrypto reference code, in + # order to allow the CE CDM to build without a vendor integration. + # This setting should *NEVER* be used in production systems and is + # for testing purposes only. + # + # 'level3' - Partners who have received a Widevine-generated Level 3 library + # should use 'level3' to indicate that the Widevine CE CDM build + # system should include it in the build. + # + # 'target' - If your vendor OEMCrypto is built using GYP and you would like + # the Widevine CE CDM build system to build it as part of the CE + # CDM build process, you can use 'target' and also set the + # variable 'oemcrypto_gyp_target' below. Most vendors will want + # to use 'vendor', above, instead. This setting exists primarily + # for Google's internal testing. 'oemcrypto_lib%': 'ref', + # You only need to set this value if you set 'oemcrypto_lib' to 'target' + # above. + 'oemcrypto_gyp_target%': '', # Override this for the location to the BoringSSL gyp file. 'boringssl_dependency%': '../third_party/boringssl/boringssl.gyp:ssl', # Directory where OEMCrypto header, test, and reference files lives. @@ -67,22 +89,27 @@ }], ['oemcrypto_lib=="level3"', { 'sources': [ - # The test impl of OEMCrypto_Level3FileSystem and its factory. - 'test/level3_file_system_ce_test.h', - 'test/level3_file_system_ce_test.cpp', - 'test/level3_file_system_ce_test_factory.cpp', - ], - 'conditions': [ + # The test impl of OEMCrypto_Level3FileSystem and its factory. + 'test/level3_file_system_ce_test.h', + 'test/level3_file_system_ce_test.cpp', + 'test/level3_file_system_ce_test_factory.cpp', + ], + 'conditions': [ ['oemcrypto_adapter=="static"', { - 'dependencies': [ - '../oemcrypto/level3/oec_level3.gyp:oec_level3_static', - ], + 'dependencies': [ + '../oemcrypto/level3/oec_level3.gyp:oec_level3_static', + ], }, { - 'dependencies': [ - '../oemcrypto/level3/oec_level3.gyp:oec_level3_dynamic', - ], - }], - ], + 'dependencies': [ + '../oemcrypto/level3/oec_level3.gyp:oec_level3_dynamic', + ], + }], + ], + }], + ['oemcrypto_lib=="target"', { + 'dependencies': [ + '<(oemcrypto_gyp_target)', + ], }], ], }, diff --git a/cdm/include/cdm.h b/cdm/include/cdm.h index 8fa7d5df..cb5eb35e 100644 --- a/cdm/include/cdm.h +++ b/cdm/include/cdm.h @@ -246,9 +246,12 @@ class CDM_EXPORT Cdm : public ITimerClient { virtual bool write(const std::string& name, const std::string& data) = 0; virtual bool exists(const std::string& name) = 0; virtual bool remove(const std::string& name) = 0; + + // Returns the size of the given file. If the file does not exist or any + // other error occurs, this should return a negative number. virtual int32_t size(const std::string& name) = 0; - // populates |file_names| with the name of each file in the file system. + // Populates |file_names| with the name of each file in the file system. // This is assumed to be a flat filename space (top level directory is // unnamed, and there are no subdirectories). virtual bool list(std::vector* file_names) = 0; @@ -444,10 +447,6 @@ class CDM_EXPORT Cdm : public ITimerClient { // determined by the CDM's current IStorage object. virtual Status removeProvisioning() = 0; - // Remove the device's usage table. - // This calls on OEMCrypto to delete its usage records. - virtual Status removeUsageTable() = 0; - // Get the current list of offline licenses on the system. // License storage is origin-specific, and the origin is determined by the // CDM's current IStorage object. @@ -554,6 +553,14 @@ class CDM_EXPORT Cdm : public ITimerClient { // should require a release request, as is done by the remove() method. virtual Status forceRemove(const std::string& session_id) = 0; + // Wipe the device's usage table. + // This calls on OEMCrypto to delete its usage records. + // This method deletes *all* of the usage records on the device. Generally, + // you do not want to call this method. You probably want to call + // deleteUsageRecord() or deleteAllUsageRecords(), which only operate on the + // current origin. + virtual Status removeUsageTable() = 0; + // Describes a repeating pattern as defined by the CENC 3.0 standard. A // CENC 3.0 pattern consists of a number of encrypted blocks followed by a // number of clear blocks, after which it repeats. diff --git a/cdm/include/cdm_version.h b/cdm/include/cdm_version.h index 1d446ee6..520edc1d 100644 --- a/cdm/include/cdm_version.h +++ b/cdm/include/cdm_version.h @@ -1,3 +1,5 @@ // Widevine CE CDM Version -#define CDM_VERSION "15.1.0" +#ifndef CDM_VERSION +# define CDM_VERSION "15.2.0-non-prod" +#endif #define EME_VERSION "https://www.w3.org/TR/2017/REC-encrypted-media-20170918" diff --git a/cdm/src/cdm.cpp b/cdm/src/cdm.cpp index ef97050f..91fccef9 100644 --- a/cdm/src/cdm.cpp +++ b/cdm/src/cdm.cpp @@ -1413,7 +1413,7 @@ void CdmImpl::OnSessionKeysChange(const CdmSessionId& session_id, switch (it->second) { case kKeyStatusUsable: map[it->first] = kUsable; - break; + continue; case kKeyStatusExpired: { KeyStatusMap::const_iterator it_old = map.find(it->first); if (it_old != map.end() && it_old->second == kReleased) { @@ -1422,22 +1422,28 @@ void CdmImpl::OnSessionKeysChange(const CdmSessionId& session_id, } else { map[it->first] = kExpired; } - break; + continue; } case kKeyStatusOutputNotAllowed: map[it->first] = kOutputRestricted; - break; + continue; + case kKeyStatusUsableInFuture: case kKeyStatusPending: map[it->first] = kStatusPending; - break; + continue; + case kKeyStatusKeyUnknown: case kKeyStatusInternalError: map[it->first] = kInternalError; - break; - default: - LOGE("Unrecognized key status: %d", it->second); - map[it->first] = kInternalError; - break; + continue; } + + // If we get this far, the switch statement fell through, which is an error. + // We do this instead of having a default case in the switch so that the + // compiler will flag if someone fails to add a case for new enum members, + // while still handling the possibility of an invalid value sneaking into + // the map at runtime. + LOGE("Invalid key status %d. Reporting internal error.", it->second); + map[it->first] = kInternalError; } listener_->onKeyStatusesChange(session_id, has_new_usable_key); @@ -1629,7 +1635,10 @@ class FileSystem::Impl { widevine::Cdm::IStorage* storage_; }; -FileSystem::FileSystem() : impl_(new Impl()) { impl_->storage_ = host.storage; } +FileSystem::FileSystem() : impl_(new Impl()) { + assert(nullptr != host.storage); + impl_->storage_ = host.storage; +} FileSystem::FileSystem(const std::string& origin, void* extra_data) : impl_(new Impl()), origin_(origin) { @@ -1656,7 +1665,7 @@ std::unique_ptr FileSystem::Open(const std::string& file_path, bool FileSystem::Exists(const std::string& file_path) { if (!impl_) return false; - return file_path.empty() || impl_->storage_->exists(file_path); + return !file_path.empty() && impl_->storage_->exists(file_path); } bool FileSystem::Remove(const std::string& file_path) { diff --git a/cdm/src/properties_ce.cpp b/cdm/src/properties_ce.cpp index 7016c229..c514ac78 100644 --- a/cdm/src/properties_ce.cpp +++ b/cdm/src/properties_ce.cpp @@ -86,6 +86,7 @@ void Properties::InitOnce() { oem_crypto_use_userspace_buffers_ = use_userspace_buffers_; provisioning_messages_are_binary_ = set_provisioning_messages_to_binary_; allow_service_certificate_requests_ = false; + device_files_is_a_real_filesystem_ = false; session_property_set_.reset(new CdmClientPropertySetMap()); } diff --git a/cdm/test/cdm_test_main.cpp b/cdm/test/cdm_test_main.cpp index c5682894..c8412b65 100644 --- a/cdm/test/cdm_test_main.cpp +++ b/cdm/test/cdm_test_main.cpp @@ -24,12 +24,9 @@ int main(int argc, char** argv) { // Init gtest and let it consume arguments. ::testing::InitGoogleTest(&argc, argv); - if (!wvcdm::WvCdmTestBase::Initialize(argc, argv)) return 0; - - // Set up a Host so that tests and initialize the library. This makes these - // services available to the tests. We would do this in the test suite - // itself, but the core & OEMCrypto tests don't know they depend on this - // for storage. + // Set up a Host and initialize the library. This makes these services + // available to the tests. We would do this in the test suite itself, but the + // core & OEMCrypto tests don't know they depend on this for storage. g_host = new TestHost(); Cdm::ClientInfo client_info; // Set client info that denotes this as the test suite: @@ -55,5 +52,9 @@ int main(int argc, char** argv) { (void)status; // status is now used when assertions are turned off. assert(status == Cdm::kSuccess); + // This must take place after the call to Cdm::initialize() because it may + // make calls that are only valid after the library is initialized. + if (!wvcdm::WvCdmTestBase::Initialize(argc, argv)) return 0; + return RUN_ALL_TESTS(); } diff --git a/core/include/buffer_reader.h b/core/include/buffer_reader.h index 0ccac377..38ccfcaf 100644 --- a/core/include/buffer_reader.h +++ b/core/include/buffer_reader.h @@ -6,6 +6,7 @@ #define WVCDM_CORE_BUFFER_READER_H_ #include + #include #include diff --git a/core/include/cdm_client_property_set.h b/core/include/cdm_client_property_set.h index 9f7ca553..38398ebe 100644 --- a/core/include/cdm_client_property_set.h +++ b/core/include/cdm_client_property_set.h @@ -6,6 +6,7 @@ #define WVCDM_CORE_CDM_CLIENT_PROPERTY_SET_H_ #include + #include #include diff --git a/core/include/cdm_engine.h b/core/include/cdm_engine.h index 05ed5bd0..309e72f7 100644 --- a/core/include/cdm_engine.h +++ b/core/include/cdm_engine.h @@ -33,30 +33,31 @@ class UsagePropertySet; class WvCdmEventListener; // Keep expiration time for each key set -typedef std::map > CdmReleaseKeySetMap; +using CdmReleaseKeySetMap = + std::map >; class CdmEngine { public: virtual ~CdmEngine(); // Session related methods - virtual CdmResponseType OpenSession( - const CdmKeySystem& key_system, CdmClientPropertySet* property_set, - const CdmSessionId& forced_session_id, - WvCdmEventListener* event_listener); + virtual CdmResponseType OpenSession(const CdmKeySystem& key_system, + CdmClientPropertySet* property_set, + const CdmSessionId& forced_session_id, + WvCdmEventListener* event_listener); - virtual CdmResponseType OpenSession( - const CdmKeySystem& key_system, CdmClientPropertySet* property_set, - WvCdmEventListener* event_listener, CdmSessionId* session_id); + virtual CdmResponseType OpenSession(const CdmKeySystem& key_system, + CdmClientPropertySet* property_set, + WvCdmEventListener* event_listener, + CdmSessionId* session_id); virtual CdmResponseType CloseSession(const CdmSessionId& session_id); virtual bool IsOpenSession(const CdmSessionId& session_id); - virtual CdmResponseType OpenKeySetSession( - const CdmKeySetId& key_set_id, CdmClientPropertySet* property_set, - WvCdmEventListener* event_listener); + virtual CdmResponseType OpenKeySetSession(const CdmKeySetId& key_set_id, + CdmClientPropertySet* property_set, + WvCdmEventListener* event_listener); virtual CdmResponseType CloseKeySetSession(const CdmKeySetId& key_set_id); @@ -129,8 +130,8 @@ class CdmEngine { virtual CdmResponseType RemoveLicense(const CdmSessionId& session_id); // Construct valid renewal request for the current session keys. - virtual CdmResponseType GenerateRenewalRequest( - const CdmSessionId& session_id, CdmKeyRequest* key_request); + virtual CdmResponseType GenerateRenewalRequest(const CdmSessionId& session_id, + CdmKeyRequest* key_request); // Accept renewal response and update key info. virtual CdmResponseType RenewKey(const CdmSessionId& session_id, @@ -174,8 +175,8 @@ class CdmEngine { // Generate and return a valid provisioning request. virtual CdmResponseType GetProvisioningRequest( CdmCertificateType cert_type, const std::string& cert_authority, - const std::string& service_certificate, - CdmProvisioningRequest* request, std::string* default_url); + const std::string& service_certificate, CdmProvisioningRequest* request, + std::string* default_url); // Verify and process a provisioning response. virtual CdmResponseType HandleProvisioningResponse( @@ -214,14 +215,12 @@ class CdmEngine { // Get offline license status: active, release or unknown virtual CdmResponseType GetOfflineLicenseState( - const std::string& key_set_id, - CdmSecurityLevel security_level, + const std::string& key_set_id, CdmSecurityLevel security_level, CdmOfflineLicenseState* license_state); // Remove offline license with the given key_set_id - virtual CdmResponseType RemoveOfflineLicense( - const std::string& key_set_id, - CdmSecurityLevel security_level); + virtual CdmResponseType RemoveOfflineLicense(const std::string& key_set_id, + CdmSecurityLevel security_level); // Usage related methods for streaming licenses // Retrieve a random usage info from the list of all usage infos for this app @@ -249,8 +248,7 @@ class CdmEngine { virtual CdmResponseType RemoveAllUsageInfo(const std::string& app_id); virtual CdmResponseType RemoveUsageInfo( - const std::string& app_id, - const CdmSecureStopId& secure_stop_id); + const std::string& app_id, const CdmSecureStopId& secure_stop_id); virtual CdmResponseType ReleaseUsageInfo( const CdmUsageInfoReleaseMessage& message); @@ -266,16 +264,20 @@ class CdmEngine { // application can use outside of content stream processing // Encrypts a buffer of app-level data. - virtual CdmResponseType GenericEncrypt( - const std::string& session_id, const std::string& in_buffer, - const std::string& key_id, const std::string& iv, - CdmEncryptionAlgorithm algorithm, std::string* out_buffer); + virtual CdmResponseType GenericEncrypt(const std::string& session_id, + const std::string& in_buffer, + const std::string& key_id, + const std::string& iv, + CdmEncryptionAlgorithm algorithm, + std::string* out_buffer); // Decrypts a buffer of app-level data. - virtual CdmResponseType GenericDecrypt( - const std::string& session_id, const std::string& in_buffer, - const std::string& key_id, const std::string& iv, - CdmEncryptionAlgorithm algorithm, std::string* out_buffer); + virtual CdmResponseType GenericDecrypt(const std::string& session_id, + const std::string& in_buffer, + const std::string& key_id, + const std::string& iv, + CdmEncryptionAlgorithm algorithm, + std::string* out_buffer); // Computes the signature for a message. virtual CdmResponseType GenericSign(const std::string& session_id, @@ -336,16 +338,14 @@ class CdmEngine { virtual void SetAppPackageName(const std::string& app_package_name) { app_package_name_ = app_package_name; } - virtual const std::string& GetAppPackageName() { - return app_package_name_; - } + virtual const std::string& GetAppPackageName() { return app_package_name_; } protected: friend class CdmEngineFactory; friend class ParallelCdmTest; friend class WvCdmEnginePreProvTest; friend class WvCdmTestBase; - friend class WvGenericOperationsTest; + friend class WvGenericCryptoTest; friend class TestLicenseHolder; CdmEngine(FileSystem* file_system, @@ -354,17 +354,17 @@ class CdmEngine { private: // private methods - CdmResponseType OpenSession( - const CdmKeySystem& key_system, CdmClientPropertySet* property_set, - WvCdmEventListener* event_listener, const CdmSessionId* forced_session_id, - CdmSessionId* session_id); + CdmResponseType OpenSession(const CdmKeySystem& key_system, + CdmClientPropertySet* property_set, + WvCdmEventListener* event_listener, + const CdmSessionId* forced_session_id, + CdmSessionId* session_id); void DeleteAllUsageReportsUponFactoryReset(); bool ValidateKeySystem(const CdmKeySystem& key_system); CdmResponseType GetUsageInfo(const std::string& app_id, SecurityLevel requested_security_level, - int* error_detail, - CdmUsageInfo* usage_info); + int* error_detail, CdmUsageInfo* usage_info); void OnKeyReleaseEvent(const CdmKeySetId& key_set_id); diff --git a/core/include/cdm_engine_metrics_decorator.h b/core/include/cdm_engine_metrics_decorator.h index e4e3053a..44a11f81 100644 --- a/core/include/cdm_engine_metrics_decorator.h +++ b/core/include/cdm_engine_metrics_decorator.h @@ -39,7 +39,7 @@ class WvCdmEventListener; // FileSystem* file_system; // Construction of FileSystem object not shown. // std::shared_ptr metrics(new EngineMetrics); // CdmEngine* e = new CdmEngineMetricsImpl(file_system, metrics); -template +template class CdmEngineMetricsImpl : public T { public: // This constructor initializes the instance and takes ownership of |metrics|. @@ -52,37 +52,37 @@ class CdmEngineMetricsImpl : public T { : T(file_system, metrics, spoid), metrics_(metrics) { metrics_->cdm_engine_creation_time_millis_.Record(clock_.GetCurrentTime()); std::string cdm_version; - if(Properties::GetWVCdmVersion(&cdm_version)) { + if (Properties::GetWVCdmVersion(&cdm_version)) { metrics_->cdm_engine_cdm_version_.Record(cdm_version); } else { metrics_->cdm_engine_cdm_version_.SetError(false); } } - ~CdmEngineMetricsImpl() override {}; + ~CdmEngineMetricsImpl() override{}; - bool GetMetricsSnapshot(drm_metrics::WvCdmMetrics *metrics) override { + bool GetMetricsSnapshot(drm_metrics::WvCdmMetrics* metrics) override { if (metrics == nullptr) return false; metrics_->Serialize(metrics); return true; } - CdmResponseType OpenSession( - const CdmKeySystem& key_system, CdmClientPropertySet* property_set, - const CdmSessionId& forced_session_id, WvCdmEventListener* event_listener) - override { - CdmResponseType sts = T::OpenSession( - key_system, property_set, forced_session_id, event_listener); + CdmResponseType OpenSession(const CdmKeySystem& key_system, + CdmClientPropertySet* property_set, + const CdmSessionId& forced_session_id, + WvCdmEventListener* event_listener) override { + CdmResponseType sts = T::OpenSession(key_system, property_set, + forced_session_id, event_listener); metrics_->cdm_engine_open_session_.Increment(sts); return sts; } - CdmResponseType OpenSession( - const CdmKeySystem& key_system, CdmClientPropertySet* property_set, - WvCdmEventListener* event_listener, CdmSessionId* session_id) - override { - CdmResponseType sts = T::OpenSession( - key_system, property_set, event_listener, session_id); + CdmResponseType OpenSession(const CdmKeySystem& key_system, + CdmClientPropertySet* property_set, + WvCdmEventListener* event_listener, + CdmSessionId* session_id) override { + CdmResponseType sts = + T::OpenSession(key_system, property_set, event_listener, session_id); metrics_->cdm_engine_open_session_.Increment(sts); return sts; } @@ -96,27 +96,30 @@ class CdmEngineMetricsImpl : public T { CdmResponseType OpenKeySetSession( const CdmKeySetId& key_set_id, CdmClientPropertySet* property_set, WvCdmEventListener* event_listener) override { - CdmResponseType sts = T::OpenKeySetSession(key_set_id, property_set, - event_listener); + CdmResponseType sts = + T::OpenKeySetSession(key_set_id, property_set, event_listener); metrics_->cdm_engine_open_key_set_session_.Increment(sts); return sts; } - CdmResponseType GenerateKeyRequest( - const CdmSessionId& session_id, const CdmKeySetId& key_set_id, - const InitializationData& init_data, const CdmLicenseType license_type, - CdmAppParameterMap& app_parameters, CdmKeyRequest* key_request) override { + CdmResponseType GenerateKeyRequest(const CdmSessionId& session_id, + const CdmKeySetId& key_set_id, + const InitializationData& init_data, + const CdmLicenseType license_type, + CdmAppParameterMap& app_parameters, + CdmKeyRequest* key_request) override { CdmResponseType sts; - M_TIME(sts = T::GenerateKeyRequest(session_id, key_set_id, init_data, - license_type, app_parameters, - key_request), - metrics_, cdm_engine_generate_key_request_, sts, license_type); + M_TIME( + sts = T::GenerateKeyRequest(session_id, key_set_id, init_data, + license_type, app_parameters, key_request), + metrics_, cdm_engine_generate_key_request_, sts, license_type); return sts; } - CdmResponseType AddKey( - const CdmSessionId& session_id, const CdmKeyResponse& key_data, - CdmLicenseType* license_type, CdmKeySetId* key_set_id) override { + CdmResponseType AddKey(const CdmSessionId& session_id, + const CdmKeyResponse& key_data, + CdmLicenseType* license_type, + CdmKeySetId* key_set_id) override { if (license_type == nullptr) { LOGE("CdmEngine::AddKey: license_type cannot be null."); return PARAMETER_NULL; @@ -128,12 +131,11 @@ class CdmEngineMetricsImpl : public T { return sts; } - CdmResponseType RestoreKey(const CdmSessionId& session_id, const CdmKeySetId& key_set_id) override { CdmResponseType sts; - M_TIME(sts = T::RestoreKey(session_id, key_set_id), - metrics_, cdm_engine_restore_key_, sts); + M_TIME(sts = T::RestoreKey(session_id, key_set_id), metrics_, + cdm_engine_restore_key_, sts); return sts; } @@ -146,19 +148,20 @@ class CdmEngineMetricsImpl : public T { CdmResponseType QueryKeyStatus(const CdmSessionId& session_id, CdmQueryMap* query_response) override { CdmResponseType sts; - M_TIME(sts = T::QueryKeyStatus(session_id, query_response), - metrics_, cdm_engine_query_key_status_, sts); + M_TIME(sts = T::QueryKeyStatus(session_id, query_response), metrics_, + cdm_engine_query_key_status_, sts); return sts; } - CdmResponseType GetProvisioningRequest( - CdmCertificateType cert_type, const std::string& cert_authority, - const std::string& service_certificate, - CdmProvisioningRequest* request, std::string* default_url) override { + CdmResponseType GetProvisioningRequest(CdmCertificateType cert_type, + const std::string& cert_authority, + const std::string& service_certificate, + CdmProvisioningRequest* request, + std::string* default_url) override { CdmResponseType sts; M_TIME(sts = T::GetProvisioningRequest(cert_type, cert_authority, - service_certificate, - request, default_url), + service_certificate, request, + default_url), metrics_, cdm_engine_get_provisioning_request_, sts); return sts; } @@ -167,21 +170,18 @@ class CdmEngineMetricsImpl : public T { const CdmProvisioningResponse& response, std::string* cert, std::string* wrapped_key) override { CdmResponseType sts; - M_TIME( - sts = T::HandleProvisioningResponse(response, cert, wrapped_key), - metrics_, cdm_engine_handle_provisioning_response_, sts); + M_TIME(sts = T::HandleProvisioningResponse(response, cert, wrapped_key), + metrics_, cdm_engine_handle_provisioning_response_, sts); return sts; } - CdmResponseType Unprovision(CdmSecurityLevel security_level) override { CdmResponseType sts = T::Unprovision(security_level); metrics_->cdm_engine_unprovision_.Increment(sts, security_level); return sts; } - CdmResponseType GetUsageInfo(const std::string& app_id, - int* error_detail, + CdmResponseType GetUsageInfo(const std::string& app_id, int* error_detail, CdmUsageInfo* usage_info) override { CdmResponseType sts; int error_detail_alt; @@ -193,10 +193,8 @@ class CdmEngineMetricsImpl : public T { return sts; } - CdmResponseType GetUsageInfo(const std::string& app_id, - const CdmSecureStopId& ssid, - int* error_detail, + const CdmSecureStopId& ssid, int* error_detail, CdmUsageInfo* usage_info) override { CdmResponseType sts; int error_detail_alt; @@ -222,15 +220,15 @@ class CdmEngineMetricsImpl : public T { } CdmResponseType RemoveUsageInfo( - const std::string& app_id, const CdmSecureStopId& secure_stop_id) - override { + const std::string& app_id, + const CdmSecureStopId& secure_stop_id) override { CdmResponseType sts = T::RemoveUsageInfo(app_id, secure_stop_id); metrics_->cdm_engine_remove_usage_info_.Increment(sts); return sts; } - CdmResponseType ReleaseUsageInfo(const CdmUsageInfoReleaseMessage& message) - override { + CdmResponseType ReleaseUsageInfo( + const CdmUsageInfoReleaseMessage& message) override { CdmResponseType sts = T::ReleaseUsageInfo(message); metrics_->cdm_engine_release_usage_info_.Increment(sts); return sts; @@ -240,17 +238,15 @@ class CdmEngineMetricsImpl : public T { const std::string& app_id, CdmSecurityLevel security_level, std::vector* ksids, std::vector* provider_session_tokens) override { - CdmResponseType sts = T::ListUsageIds(app_id, security_level, - ksids, provider_session_tokens); + CdmResponseType sts = + T::ListUsageIds(app_id, security_level, ksids, provider_session_tokens); metrics_->cdm_engine_get_secure_stop_ids_.Increment(sts); return sts; } - - bool FindSessionForKey(const KeyId& key_id, CdmSessionId* session_id) - override { - bool status = - T::FindSessionForKey(key_id, session_id); + bool FindSessionForKey(const KeyId& key_id, + CdmSessionId* session_id) override { + bool status = T::FindSessionForKey(key_id, session_id); metrics_->cdm_engine_find_session_for_key_.Increment(status); return status; } @@ -258,8 +254,8 @@ class CdmEngineMetricsImpl : public T { CdmResponseType Decrypt(const CdmSessionId& session_id, const CdmDecryptionParameters& parameters) override { CdmResponseType sts; - M_TIME(sts = T::Decrypt(session_id, parameters), - metrics_, cdm_engine_decrypt_, sts, + M_TIME(sts = T::Decrypt(session_id, parameters), metrics_, + cdm_engine_decrypt_, sts, metrics::Pow2Bucket(parameters.encrypt_length)); return sts; } @@ -269,5 +265,5 @@ class CdmEngineMetricsImpl : public T { Clock clock_; }; -} // wvcdm namespace +} // namespace wvcdm #endif // WVCDM_CORE_CDM_ENGINE_METRICS_DECORATOR_H_ diff --git a/core/include/cdm_session.h b/core/include/cdm_session.h index dff41844..11d8eee6 100644 --- a/core/include/cdm_session.h +++ b/core/include/cdm_session.h @@ -64,16 +64,15 @@ class CdmSession { // |license_type|. The |error_detail| will be filled with an internal error // code. The |error_detail| may be a CdmResponseType or other error code type. // It is only suitable for additional logging or debugging. - virtual CdmResponseType RestoreOfflineSession( - const CdmKeySetId& key_set_id, CdmLicenseType license_type, - int* error_detail); + virtual CdmResponseType RestoreOfflineSession(const CdmKeySetId& key_set_id, + CdmLicenseType license_type, + int* error_detail); // Restores an usage session from the provided |usage_data|. // The |error_detail| will be filled with an internal error code. The // |error_detail| may be a CdmResponseType or other error code type. It is // only suitable for additional logging or debugging. virtual CdmResponseType RestoreUsageSession( - const DeviceFiles::CdmUsageData& usage_data, - int* error_detail); + const DeviceFiles::CdmUsageData& usage_data, int* error_detail); virtual const CdmSessionId& session_id() { return session_id_; } virtual const CdmKeySetId& key_set_id() { return key_set_id_; } @@ -153,11 +152,12 @@ class CdmSession { virtual bool license_received() { return license_received_; } virtual bool has_provider_session_token() { return (license_parser_.get() != NULL && - license_parser_->provider_session_token().size() > 0); + license_parser_->provider_session_token().size() > 0); } - virtual CdmUsageSupportType get_usage_support_type() - { return usage_support_type_; } + virtual CdmUsageSupportType get_usage_support_type() { + return usage_support_type_; + } // This method will remove keys by resetting crypto resources and // policy information. This renders the session mostly useless and it is @@ -218,8 +218,7 @@ class CdmSession { CdmResponseType StoreLicense(); - bool StoreLicense(DeviceFiles::LicenseState state, - int* error_detail); + bool StoreLicense(DeviceFiles::LicenseState state, int* error_detail); bool UpdateUsageInfo(); diff --git a/core/include/cdm_session_map.h b/core/include/cdm_session_map.h index a52a553a..74b54906 100644 --- a/core/include/cdm_session_map.h +++ b/core/include/cdm_session_map.h @@ -15,7 +15,7 @@ namespace wvcdm { -typedef std::list > CdmSessionList; +using CdmSessionList = std::list >; // TODO(rfrias): Concurrency protection for this class has moved to CdmEngine. // Add it back when locks to control access to session usage and destruction @@ -43,8 +43,8 @@ class CdmSessionMap { void GetSessionList(CdmSessionList& sessions); private: - typedef std::map > - CdmIdToSessionMap; + using CdmIdToSessionMap = + std::map >; bool FindSessionNoLock(const CdmSessionId& session_id, std::shared_ptr* session); diff --git a/core/include/certificate_provisioning.h b/core/include/certificate_provisioning.h index d97256b4..10f7ad8b 100644 --- a/core/include/certificate_provisioning.h +++ b/core/include/certificate_provisioning.h @@ -25,21 +25,23 @@ class ServiceCertificate; class CertificateProvisioning { public: - CertificateProvisioning(metrics::CryptoMetrics* metrics) : - crypto_session_(CryptoSession::MakeCryptoSession(metrics)), - cert_type_(kCertificateWidevine), - service_certificate_(new ServiceCertificate()) {} + CertificateProvisioning(metrics::CryptoMetrics* metrics) + : crypto_session_(CryptoSession::MakeCryptoSession(metrics)), + cert_type_(kCertificateWidevine), + service_certificate_(new ServiceCertificate()) {} ~CertificateProvisioning() {} CdmResponseType Init(const std::string& service_certificate); // Construct a valid provisioning request. // The request will be sent to the provisioning server. - CdmResponseType GetProvisioningRequest( - SecurityLevel requested_security_level, CdmCertificateType cert_type, - const std::string& cert_authority, const std::string& origin, - const std::string& spoid, CdmProvisioningRequest* request, - std::string* default_url); + CdmResponseType GetProvisioningRequest(SecurityLevel requested_security_level, + CdmCertificateType cert_type, + const std::string& cert_authority, + const std::string& origin, + const std::string& spoid, + CdmProvisioningRequest* request, + std::string* default_url); // Process the provisioning response. CdmResponseType HandleProvisioningResponse( @@ -48,12 +50,11 @@ class CertificateProvisioning { private: CdmResponseType SetSpoidParameter( - const std::string& origin, - const std::string& spoid, + const std::string& origin, const std::string& spoid, video_widevine::ProvisioningRequest* request); video_widevine::SignedProvisioningMessage::ProtocolVersion - GetProtocolVersion(); + GetProtocolVersion(); std::unique_ptr crypto_session_; CdmCertificateType cert_type_; diff --git a/core/include/crypto_key.h b/core/include/crypto_key.h index a239e6ce..9614e597 100644 --- a/core/include/crypto_key.h +++ b/core/include/crypto_key.h @@ -11,15 +11,15 @@ namespace wvcdm { class CryptoKey { public: - CryptoKey() {}; - ~CryptoKey() {}; + CryptoKey(){}; + ~CryptoKey(){}; const std::string& key_id() const { return key_id_; } const std::string& key_data() const { return key_data_; } const std::string& key_data_iv() const { return key_data_iv_; } const std::string& key_control() const { return key_control_; } const std::string& key_control_iv() const { return key_control_iv_; } - const std::string& entitlement_key_id() const {return entitlement_key_id_;} + const std::string& entitlement_key_id() const { return entitlement_key_id_; } const std::string& track_label() const { return track_label_; } CdmCipherMode cipher_mode() const { return cipher_mode_; } void set_key_id(const std::string& key_id) { key_id_ = key_id; } diff --git a/core/include/crypto_session.h b/core/include/crypto_session.h index 0d0230a5..6de7d0fe 100644 --- a/core/include/crypto_session.h +++ b/core/include/crypto_session.h @@ -26,7 +26,7 @@ namespace wvcdm { class CryptoKey; class UsageTableHeader; -typedef std::map CryptoKeyMap; +using CryptoKeyMap = std::map; // Crypto session utility functions used by KeySession implementations. void GenerateMacContext(const std::string& input_context, @@ -43,7 +43,7 @@ class CryptoSessionFactory; class CryptoSession { public: - typedef OEMCrypto_HDCP_Capability HdcpCapability; + using HdcpCapability = OEMCrypto_HDCP_Capability; typedef enum { kUsageDurationsInvalid = 0, kUsageDurationPlaybackNotBegun = 1, @@ -96,32 +96,31 @@ class CryptoSession { std::string* signature); virtual CdmResponseType PrepareRenewalRequest(const std::string& message, std::string* signature); - virtual CdmResponseType LoadKeys( - const std::string& message, const std::string& signature, - const std::string& mac_key_iv, const std::string& mac_key, - const std::vector& key_array, - const std::string& provider_session_token, - const std::string& srm_requirement, - CdmLicenseKeyType key_type); + virtual CdmResponseType LoadKeys(const std::string& message, + const std::string& signature, + const std::string& mac_key_iv, + const std::string& mac_key, + const std::vector& key_array, + const std::string& provider_session_token, + const std::string& srm_requirement, + CdmLicenseKeyType key_type); virtual CdmResponseType LoadEntitledContentKeys( const std::vector& key_array); virtual CdmResponseType LoadCertificatePrivateKey(std::string& wrapped_key); virtual CdmResponseType RefreshKeys(const std::string& message, const std::string& signature, - int num_keys, - const CryptoKey* key_array); + int num_keys, const CryptoKey* key_array); virtual CdmResponseType GenerateNonce(uint32_t* nonce); virtual CdmResponseType GenerateDerivedKeys(const std::string& message); virtual CdmResponseType GenerateDerivedKeys(const std::string& message, const std::string& session_key); - virtual CdmResponseType RewrapCertificate( - const std::string& signed_message, - const std::string& signature, - const std::string& nonce, - const std::string& private_key, - const std::string& iv, - const std::string& wrapping_key, - std::string* wrapped_private_key); + virtual CdmResponseType RewrapCertificate(const std::string& signed_message, + const std::string& signature, + const std::string& nonce, + const std::string& private_key, + const std::string& iv, + const std::string& wrapping_key, + std::string* wrapped_private_key); // Media data path virtual CdmResponseType Decrypt(const CdmDecryptionParameters& params); @@ -177,6 +176,7 @@ class CryptoSession { virtual bool GetBuildInformation(SecurityLevel security_level, std::string* info); + virtual bool GetBuildInformation(std::string* info); virtual uint32_t IsDecryptHashSupported(SecurityLevel security_level); @@ -236,8 +236,7 @@ class CryptoSession { virtual metrics::CryptoMetrics* GetCryptoMetrics() { return metrics_; } virtual CdmResponseType GetProvisioningMethod( - SecurityLevel requested_security_level, - CdmClientTokenType* token_type); + SecurityLevel requested_security_level, CdmClientTokenType* token_type); protected: // Creates an instance of CryptoSession with the given |crypto_metrics|. @@ -268,8 +267,8 @@ class CryptoSession { static bool ExtractSystemIdFromOemCert(const std::string& oem_cert, uint32_t* system_id); CdmResponseType GetSystemIdInternal(uint32_t* system_id); - CdmResponseType GenerateSignature( - const std::string& message, std::string* signature); + CdmResponseType GenerateSignature(const std::string& message, + std::string* signature); CdmResponseType GenerateRsaSignature(const std::string& message, std::string* signature); diff --git a/core/include/device_files.h b/core/include/device_files.h index 737e7700..3e9a0a13 100644 --- a/core/include/device_files.h +++ b/core/include/device_files.h @@ -79,21 +79,17 @@ class DeviceFiles { virtual bool HasCertificate(); virtual bool RemoveCertificate(); - virtual bool StoreLicense(const std::string& key_set_id, - const LicenseState state, - const CdmInitData& pssh_data, - const CdmKeyMessage& key_request, - const CdmKeyResponse& key_response, - const CdmKeyMessage& key_renewal_request, - const CdmKeyResponse& key_renewal_response, - const std::string& release_server_url, - int64_t playback_start_time, - int64_t last_playback_time, - int64_t grace_period_end_time, - const CdmAppParameterMap& app_parameters, - const CdmUsageEntry& usage_entry, - uint32_t usage_entry_number, - ResponseType* result); + virtual bool StoreLicense( + const std::string& key_set_id, const LicenseState state, + const CdmInitData& pssh_data, const CdmKeyMessage& key_request, + const CdmKeyResponse& key_response, + const CdmKeyMessage& key_renewal_request, + const CdmKeyResponse& key_renewal_response, + const std::string& release_server_url, int64_t playback_start_time, + int64_t last_playback_time, int64_t grace_period_end_time, + const CdmAppParameterMap& app_parameters, + const CdmUsageEntry& usage_entry, uint32_t usage_entry_number, + ResponseType* result); virtual bool RetrieveLicense( const std::string& key_set_id, LicenseState* state, @@ -135,10 +131,9 @@ class DeviceFiles { // Retrieve usage identifying information stored on the file system. // The caller needs to specify at least one of |ksids| or // |provider_session_tokens| - virtual bool ListUsageIds( - const std::string& app_id, - std::vector* ksids, - std::vector* provider_session_tokens); + virtual bool ListUsageIds(const std::string& app_id, + std::vector* ksids, + std::vector* provider_session_tokens); // Get the provider session token for the given key_set_id. virtual bool GetProviderSessionToken(const std::string& app_id, @@ -173,12 +168,9 @@ class DeviceFiles { // Retrieve the usage info entry specified by |key_set_id|. // Returns false if the entry could not be found. virtual bool RetrieveUsageInfoByKeySetId( - const std::string& usage_info_file_name, - const std::string& key_set_id, - std::string* provider_session_token, - CdmKeyMessage* license_request, - CdmKeyResponse* license_response, - CdmUsageEntry* usage_entry, + const std::string& usage_info_file_name, const std::string& key_set_id, + std::string* provider_session_token, CdmKeyMessage* license_request, + CdmKeyResponse* license_response, CdmUsageEntry* usage_entry, uint32_t* usage_entry_number); // These APIs support upgrading from usage tables to usage tabler header + @@ -218,8 +210,7 @@ class DeviceFiles { private: // Extract serial number and system ID from DRM Device certificate bool ExtractDeviceInfo(const std::string& device_certificate, - std::string* serial_number, - uint32_t* system_id); + std::string* serial_number, uint32_t* system_id); // Helpers that wrap the File interface and automatically handle hashing, as // well as adding the device files base path to to the file name. diff --git a/core/include/initialization_data.h b/core/include/initialization_data.h index 4252c1fb..90c37fe1 100644 --- a/core/include/initialization_data.h +++ b/core/include/initialization_data.h @@ -34,16 +34,15 @@ class InitializationData { CdmHlsMethod hls_method() const { return hls_method_; } std::vector ExtractWrappedKeys() const; + bool contains_entitled_keys() const { return contains_entitled_keys_; } private: bool SelectWidevinePssh(const CdmInitData& init_data, - bool prefer_entitlements, - CdmInitData* output); + bool prefer_entitlements, CdmInitData* output); // Helpers used by SelectWidevinePssh(). bool ExtractWidevinePsshs(const CdmInitData& init_data, std::vector* psshs); - bool ExtractWidevinePsshData(const uint8_t* data, - size_t length, + bool ExtractWidevinePsshData(const uint8_t* data, size_t length, CdmInitData* output); bool ExtractHlsAttributes(const std::string& attribute_list, @@ -86,6 +85,7 @@ class InitializationData { bool is_hls_; bool is_webm_; bool is_audio_; + bool contains_entitled_keys_; std::vector hls_iv_; CdmHlsMethod hls_method_; diff --git a/core/include/key_session.h b/core/include/key_session.h index 84744210..52e98136 100644 --- a/core/include/key_session.h +++ b/core/include/key_session.h @@ -7,8 +7,8 @@ #include -#include "metrics_collections.h" #include "OEMCryptoCENC.h" +#include "metrics_collections.h" #include "wv_cdm_types.h" namespace wvcdm { @@ -25,8 +25,7 @@ class KeySession { virtual KeySessionType Type() = 0; virtual OEMCryptoResult GenerateDerivedKeys(const std::string& message) = 0; virtual OEMCryptoResult GenerateDerivedKeys( - const std::string& message, - const std::string& session_key) = 0; + const std::string& message, const std::string& session_key) = 0; virtual OEMCryptoResult LoadKeys(const std::string& message, const std::string& signature, const std::string& mac_key_iv, diff --git a/core/include/license_key_status.h b/core/include/license_key_status.h index a3a7ad8a..1c0d46f1 100644 --- a/core/include/license_key_status.h +++ b/core/include/license_key_status.h @@ -21,7 +21,8 @@ using video_widevine::WidevinePsshData_EntitledKey; // Holds all content and operator session keys for a session. class LicenseKeys { public: - LicenseKeys() {} + LicenseKeys(CdmSecurityLevel security_level) + : security_level_(security_level) {} virtual ~LicenseKeys() { Clear(); } virtual bool Empty() { return key_statuses_.empty(); } @@ -54,6 +55,9 @@ class LicenseKeys { // to the key, returns true. virtual bool MeetsConstraints(const KeyId& key_id); + // Indicates whether specified key can be used for the sessions security level + virtual bool MeetsSecurityLevelConstraints(const KeyId& key_id); + // Applies a resolution and/or hdcp change to each key, updating their // useability under their constraints. virtual void ApplyConstraints(uint32_t new_resolution, @@ -67,10 +71,15 @@ class LicenseKeys { virtual void SetEntitledKeys( const std::vector& keys); + // For test use: Sets the OEMCrypto security level + virtual void SetSecurityLevelForTest(CdmSecurityLevel security_level) { + security_level_ = security_level; + } + private: - typedef ::video_widevine::License::KeyContainer KeyContainer; - typedef std::map::const_iterator - LicenseKeyStatusIterator; + using KeyContainer = ::video_widevine::License::KeyContainer; + using LicenseKeyStatusIterator = + std::map::const_iterator; void Clear(); @@ -83,6 +92,8 @@ class LicenseKeys { // key status from |key_statuses_| when using entitlement key licensing. std::map content_keyid_to_entitlement_key_id_; + CdmSecurityLevel security_level_; + CORE_DISALLOW_COPY_AND_ASSIGN(LicenseKeys); }; @@ -114,25 +125,30 @@ class LicenseKeyStatus { // Note: this will return true until the first call to ApplyConstraints(). virtual bool MeetsConstraints() const { return meets_constraints_; } + // Indicates whether a key can be used for a given security level + virtual bool MeetsSecurityLevelConstraints() const { + return meets_security_level_constraints_; + } + // Applies the given changes in resolution or HDCP settings. virtual void ApplyConstraints(uint32_t new_resolution, CryptoSession::HdcpCapability new_hdcp_level); protected: - typedef ::video_widevine::License::KeyContainer KeyContainer; - typedef KeyContainer::OperatorSessionKeyPermissions - OperatorSessionKeyPermissions; - typedef KeyContainer::OutputProtection OutputProtection; - typedef KeyContainer::VideoResolutionConstraint VideoResolutionConstraint; - typedef ::google::protobuf::RepeatedPtrField - ConstraintList; + using KeyContainer = ::video_widevine::License::KeyContainer; + using OperatorSessionKeyPermissions = + KeyContainer::OperatorSessionKeyPermissions; + using OutputProtection = KeyContainer::OutputProtection; + using VideoResolutionConstraint = KeyContainer::VideoResolutionConstraint; + using ConstraintList = + ::google::protobuf::RepeatedPtrField; - LicenseKeyStatus(const KeyContainer& key); + LicenseKeyStatus(const KeyContainer& key, const CdmSecurityLevel level); virtual ~LicenseKeyStatus() {} private: - void ParseContentKey(const KeyContainer& key); + void ParseContentKey(const KeyContainer& key, CdmSecurityLevel level); void ParseOperatorSessionKey(const KeyContainer& key); bool HasConstraints() { return is_content_key_ && constraints_.size() != 0; } @@ -142,6 +158,7 @@ class LicenseKeyStatus { bool is_content_key_; CdmKeyStatus key_status_; bool meets_constraints_; + bool meets_security_level_constraints_; CdmKeyAllowedUsage allowed_usage_; CryptoSession::HdcpCapability default_hdcp_level_; ConstraintList constraints_; diff --git a/core/include/oemcrypto_adapter.h b/core/include/oemcrypto_adapter.h index e72563b2..bf7ab4fd 100644 --- a/core/include/oemcrypto_adapter.h +++ b/core/include/oemcrypto_adapter.h @@ -47,11 +47,11 @@ OEMCryptoResult OEMCrypto_ShrinkUsageTableHeader(SecurityLevel level, uint32_t new_table_size, uint8_t* header_buffer, size_t* header_buffer_length); -OEMCryptoResult OEMCrypto_CreateOldUsageEntry(SecurityLevel level, - uint64_t time_since_license_received, uint64_t time_since_first_decrypt, - uint64_t time_since_last_decrypt, OEMCrypto_Usage_Entry_Status status, - uint8_t* server_mac_key, uint8_t* client_mac_key, const uint8_t* pst, - size_t pst_length); +OEMCryptoResult OEMCrypto_CreateOldUsageEntry( + SecurityLevel level, uint64_t time_since_license_received, + uint64_t time_since_first_decrypt, uint64_t time_since_last_decrypt, + OEMCrypto_Usage_Entry_Status status, uint8_t* server_mac_key, + uint8_t* client_mac_key, const uint8_t* pst, size_t pst_length); uint32_t OEMCrypto_GetAnalogOutputFlags(SecurityLevel level); const char* OEMCrypto_BuildInformation(SecurityLevel level); uint32_t OEMCrypto_ResourceRatingTier(SecurityLevel level); @@ -107,7 +107,7 @@ OEMCryptoResult OEMCrypto_LoadKeys_Back_Compat( OEMCryptoResult OEMCrypto_UpdateUsageTable(); OEMCryptoResult OEMCrypto_DeactivateUsageEntry_V12(const uint8_t* pst, - size_t pst_length); + size_t pst_length); OEMCryptoResult OEMCrypto_DeleteUsageEntry( OEMCrypto_SESSION session, const uint8_t* pst, size_t pst_length, const uint8_t* message, size_t message_length, const uint8_t* signature, diff --git a/core/include/policy_engine.h b/core/include/policy_engine.h index b40f42ad..d0a6759d 100644 --- a/core/include/policy_engine.h +++ b/core/include/policy_engine.h @@ -45,8 +45,7 @@ class PolicyEngine { // Verifies whether the policy allows use of the specified key of // a given security level for content decryption. - virtual bool CanUseKeyForSecurityLevel(const KeyId& key_id, - CdmSecurityLevel security_level); + virtual bool CanUseKeyForSecurityLevel(const KeyId& key_id); // OnTimerEvent is called when a timer fires. It notifies the Policy Engine // that the timer has fired and dispatches the relevant events through @@ -167,10 +166,12 @@ class PolicyEngine { // Guard against clock rollbacks int64_t GetCurrentTime(); - // set_clock() is for testing only. It alters ownership of the - // passed-in pointer. + // Test only methods + // set_clock alters ownership of the passed-in pointer. void set_clock(Clock* clock); + void SetSecurityLevelForTest(CdmSecurityLevel security_level); + LicenseState license_state_; // This is the current policy information for this license. This gets updated diff --git a/core/include/privacy_crypto.h b/core/include/privacy_crypto.h index 02e8c9aa..0ba6ba5e 100644 --- a/core/include/privacy_crypto.h +++ b/core/include/privacy_crypto.h @@ -68,7 +68,6 @@ class RsaPublicKey { CORE_DISALLOW_COPY_AND_ASSIGN(RsaPublicKey); }; - /** * Extracts an integer value from the extensions in a certificate. * @param cert A PKCS7 encoded X.509 certificate chain. diff --git a/core/include/properties.h b/core/include/properties.h index 22efdfb6..fa207cc6 100644 --- a/core/include/properties.h +++ b/core/include/properties.h @@ -20,8 +20,7 @@ namespace wvcdm { -typedef std::map - CdmClientPropertySetMap; +using CdmClientPropertySetMap = std::map; // This class saves information about features and properties enabled // for a given platform. At initialization it initializes properties from @@ -53,6 +52,9 @@ class Properties { static inline bool allow_service_certificate_requests() { return allow_service_certificate_requests_; } + static inline bool device_files_is_a_real_filesystem() { + return device_files_is_a_real_filesystem_; + } static void set_provisioning_messages_are_binary(bool flag) { provisioning_messages_are_binary_ = flag; } @@ -63,11 +65,14 @@ class Properties { static bool GetProductName(std::string* product_name); static bool GetBuildInfo(std::string* build_info); static bool GetWVCdmVersion(std::string* version); + // Gets the base path for the device non-secure storage. Note that, depending + // on the value of device_files_is_a_real_filesystem, this may or may not be + // a real filesystem path. static bool GetDeviceFilesBasePath(CdmSecurityLevel security_level, std::string* base_path); static bool GetFactoryKeyboxPath(std::string* keybox); static bool GetOEMCryptoPath(std::string* library_name); - static bool GetSandboxId(std::string *sandbox_id); + static bool GetSandboxId(std::string* sandbox_id); static bool AlwaysUseKeySetIds(); static bool UseProviderIdInProvisioningRequest(); @@ -137,6 +142,7 @@ class Properties { static bool use_certificates_as_identification_; static bool provisioning_messages_are_binary_; static bool allow_service_certificate_requests_; + static bool device_files_is_a_real_filesystem_; static std::unique_ptr session_property_set_; CORE_DISALLOW_COPY_AND_ASSIGN(Properties); diff --git a/core/include/service_certificate.h b/core/include/service_certificate.h index b11ee3d1..75f2eec5 100644 --- a/core/include/service_certificate.h +++ b/core/include/service_certificate.h @@ -56,8 +56,8 @@ class ServiceCertificate { static bool GetRequest(CdmKeyMessage* request); static CdmResponseType ParseResponse(const std::string& response, std::string* signed_certificate); - private: + private: // Encrypt data using RSA with OAEP padding. // |plaintext| is the data to be encrypted. |ciphertext| is a pointer to a // string to contain the decrypted data on return, and may not be null. diff --git a/core/include/usage_table_header.h b/core/include/usage_table_header.h index f1aadac1..2a41572a 100644 --- a/core/include/usage_table_header.h +++ b/core/include/usage_table_header.h @@ -59,8 +59,8 @@ class UsageTableHeader { const std::string& usage_info_filename, uint32_t* usage_entry_number); virtual CdmResponseType LoadEntry(CryptoSession* crypto_session, - const CdmUsageEntry& usage_entry, - uint32_t usage_entry_number); + const CdmUsageEntry& usage_entry, + uint32_t usage_entry_number); virtual CdmResponseType UpdateEntry(CryptoSession* crypto_session, CdmUsageEntry* usage_entry); diff --git a/core/include/wv_cdm_constants.h b/core/include/wv_cdm_constants.h index c04e2149..6864aeb3 100644 --- a/core/include/wv_cdm_constants.h +++ b/core/include/wv_cdm_constants.h @@ -39,36 +39,34 @@ static const char KEY_SET_ID_PREFIX[] = "ksid"; static const char KEY_SYSTEM[] = "com.widevine"; // define query keys, values here -static const std::string QUERY_KEY_LICENSE_TYPE = "LicenseType"; - // "Streaming", "Offline" -static const std::string QUERY_KEY_PLAY_ALLOWED = "PlayAllowed"; - // "True", "False" -static const std::string QUERY_KEY_PERSIST_ALLOWED = "PersistAllowed"; - // "True", "False" -static const std::string QUERY_KEY_RENEW_ALLOWED = "RenewAllowed"; - // "True", "False" +static const std::string QUERY_KEY_LICENSE_TYPE = + "LicenseType"; // "Streaming", "Offline" +static const std::string QUERY_KEY_PLAY_ALLOWED = + "PlayAllowed"; // "True", "False" +static const std::string QUERY_KEY_PERSIST_ALLOWED = + "PersistAllowed"; // "True", "False" +static const std::string QUERY_KEY_RENEW_ALLOWED = + "RenewAllowed"; // "True", "False" static const std::string QUERY_KEY_LICENSE_DURATION_REMAINING = - "LicenseDurationRemaining"; // non-negative integer denoting seconds + "LicenseDurationRemaining"; // non-negative integer denoting seconds static const std::string QUERY_KEY_PLAYBACK_DURATION_REMAINING = - "PlaybackDurationRemaining"; // non-negative integer denoting seconds -static const std::string QUERY_KEY_RENEWAL_SERVER_URL = "RenewalServerUrl"; - // url -static const std::string QUERY_KEY_OEMCRYPTO_SESSION_ID = "OemCryptoSessionId"; - // session id -static const std::string QUERY_KEY_SECURITY_LEVEL = "SecurityLevel"; - // "L1", "L3" -static const std::string QUERY_KEY_DEVICE_ID = "DeviceID"; - // device unique id -static const std::string QUERY_KEY_SYSTEM_ID = "SystemID"; - // system id -static const std::string QUERY_KEY_PROVISIONING_ID = "ProvisioningID"; - // provisioning unique id -static const std::string QUERY_KEY_CURRENT_HDCP_LEVEL = "HdcpLevel"; - // current HDCP level -static const std::string QUERY_KEY_MAX_HDCP_LEVEL = "MaxHdcpLevel"; - // maximum supported HDCP level -static const std::string QUERY_KEY_USAGE_SUPPORT = "UsageSupport"; - // whether usage reporting is supported + "PlaybackDurationRemaining"; // non-negative integer denoting seconds +static const std::string QUERY_KEY_RENEWAL_SERVER_URL = + "RenewalServerUrl"; // url +static const std::string QUERY_KEY_OEMCRYPTO_SESSION_ID = + "OemCryptoSessionId"; // session id +static const std::string QUERY_KEY_SECURITY_LEVEL = + "SecurityLevel"; // "L1", "L3" +static const std::string QUERY_KEY_DEVICE_ID = "DeviceID"; // device unique id +static const std::string QUERY_KEY_SYSTEM_ID = "SystemID"; // system id +static const std::string QUERY_KEY_PROVISIONING_ID = + "ProvisioningID"; // provisioning unique id +static const std::string QUERY_KEY_CURRENT_HDCP_LEVEL = + "HdcpLevel"; // current HDCP level +static const std::string QUERY_KEY_MAX_HDCP_LEVEL = + "MaxHdcpLevel"; // maximum supported HDCP level +static const std::string QUERY_KEY_USAGE_SUPPORT = + "UsageSupport"; // whether usage reporting is supported static const std::string QUERY_KEY_NUMBER_OF_OPEN_SESSIONS = "NumberOfOpenSessions"; static const std::string QUERY_KEY_MAX_NUMBER_OF_SESSIONS = @@ -76,14 +74,14 @@ static const std::string QUERY_KEY_MAX_NUMBER_OF_SESSIONS = static const std::string QUERY_KEY_OEMCRYPTO_API_VERSION = "OemCryptoApiVersion"; static const std::string QUERY_KEY_CURRENT_SRM_VERSION = "CurrentSRMVersion"; -static const std::string QUERY_KEY_SRM_UPDATE_SUPPORT = "SRMUpdateSupport"; - // whether OEM supports SRM update +static const std::string QUERY_KEY_SRM_UPDATE_SUPPORT = + "SRMUpdateSupport"; // whether OEM supports SRM update static const std::string QUERY_KEY_WVCDM_VERSION = "WidevineCdmVersion"; static const std::string QUERY_KEY_RESOURCE_RATING_TIER = "ResourceRatingTier"; static const std::string QUERY_KEY_OEMCRYPTO_BUILD_INFORMATION = "OemCryptoBuildInformation"; -static const std::string QUERY_KEY_DECRYPT_HASH_SUPPORT = - "DecryptHashSupport"; +static const std::string QUERY_KEY_DECRYPT_HASH_SUPPORT = "DecryptHashSupport"; +static const std::string QUERY_KEY_PROVISIONING_MODEL = "ProvisioningModel"; static const std::string QUERY_VALUE_TRUE = "True"; static const std::string QUERY_VALUE_FALSE = "False"; @@ -103,6 +101,9 @@ static const std::string QUERY_VALUE_HDCP_V2_1 = "HDCP-2.1"; static const std::string QUERY_VALUE_HDCP_V2_2 = "HDCP-2.2"; static const std::string QUERY_VALUE_HDCP_V2_3 = "HDCP-2.3"; static const std::string QUERY_VALUE_HDCP_LEVEL_UNKNOWN = "HDCP-LevelUnknown"; +static const std::string QUERY_VALUE_DRM_CERTIFICATE = "DrmCertificate"; +static const std::string QUERY_VALUE_KEYBOX = "Keybox"; +static const std::string QUERY_VALUE_OEM_CERTIFICATE = "OEMCertificate"; static const std::string ISO_BMFF_VIDEO_MIME_TYPE = "video/mp4"; static const std::string ISO_BMFF_AUDIO_MIME_TYPE = "audio/mp4"; @@ -125,7 +126,7 @@ static const std::string HLS_URI_ATTRIBUTE = "URI"; static const char EMPTY_ORIGIN[] = ""; static const char EMPTY_SPOID[] = ""; -//Policy engine HDCP enforcement +// Policy engine HDCP enforcement static const uint32_t HDCP_UNSPECIFIED_VIDEO_RESOLUTION = 0; static const int64_t HDCP_DEVICE_CHECK_INTERVAL = 10; static const char EMPTY_APP_PACKAGE_NAME[] = ""; diff --git a/core/include/wv_cdm_types.h b/core/include/wv_cdm_types.h index 066cadbe..88c26046 100644 --- a/core/include/wv_cdm_types.h +++ b/core/include/wv_cdm_types.h @@ -5,39 +5,42 @@ #ifndef WVCDM_CORE_WV_CDM_TYPES_H_ #define WVCDM_CORE_WV_CDM_TYPES_H_ -#include #include + +#include #include #include #include namespace wvcdm { -typedef std::string CdmKeySystem; -typedef std::string CdmInitData; -typedef std::string CdmKeyMessage; -typedef std::string CdmKeyResponse; -typedef std::string KeyId; -typedef std::string CdmSecureStopId; -typedef std::string CdmSessionId; -typedef std::string CdmKeySetId; -typedef std::string RequestId; -typedef uint32_t CryptoResult; -typedef uint32_t CryptoSessionId; -typedef std::map CdmAppParameterMap; -typedef std::map CdmQueryMap; -typedef std::vector CdmUsageInfo; -typedef std::string CdmUsageInfoReleaseMessage; -typedef std::string CdmProvisioningRequest; -typedef std::string CdmProvisioningResponse; -typedef std::string CdmUsageTableHeader; -typedef std::string CdmUsageEntry; +using CdmKeySystem = std::string; +using CdmInitData = std::string; +using CdmKeyMessage = std::string; +using CdmKeyResponse = std::string; +using KeyId = std::string; +using CdmSecureStopId = std::string; +using CdmSessionId = std::string; +using CdmKeySetId = std::string; +using RequestId = std::string; +using CryptoResult = uint32_t; +using CryptoSessionId = uint32_t; +using CdmAppParameterMap = std::map; +using CdmQueryMap = std::map; +using CdmUsageInfo = std::vector; +using CdmUsageInfoReleaseMessage = std::string; +using CdmProvisioningRequest = std::string; +using CdmProvisioningResponse = std::string; +using CdmUsageTableHeader = std::string; +using CdmUsageEntry = std::string; enum CdmKeyRequestType { kKeyRequestTypeUnknown, kKeyRequestTypeInitial, kKeyRequestTypeRenewal, kKeyRequestTypeRelease, + kKeyRequestTypeNone, // Keys are loaded and no license request is necessary + kKeyRequestTypeUpdate, }; enum CdmOfflineLicenseState { @@ -395,6 +398,7 @@ enum CdmResponseType { REWRAP_DEVICE_RSA_KEY_ERROR = 344, REWRAP_DEVICE_RSA_KEY_30_ERROR = 345, INVALID_SRM_LIST = 346, + KEYSET_ID_NOT_FOUND_4 = 347, // Don't forget to add new values to ../test/test_printers.cpp. }; @@ -405,8 +409,9 @@ enum CdmKeyStatus { kKeyStatusOutputNotAllowed, kKeyStatusPending, kKeyStatusInternalError, + kKeyStatusUsableInFuture, }; -typedef std::map CdmKeyStatusMap; +using CdmKeyStatusMap = std::map; enum CdmLicenseType { kLicenseTypeOffline, diff --git a/core/src/buffer_reader.cpp b/core/src/buffer_reader.cpp index 0b5492b3..b3423676 100644 --- a/core/src/buffer_reader.cpp +++ b/core/src/buffer_reader.cpp @@ -11,14 +11,16 @@ namespace wvcdm { bool BufferReader::Read1(uint8_t* v) { if (v == NULL) { - LOGE("BufferReader::Read1 : Failure during parse: Null output parameter " - "when expecting non-null"); + LOGE( + "BufferReader::Read1 : Failure during parse: Null output parameter " + "when expecting non-null"); return false; } if (!HasBytes(1)) { - LOGV("BufferReader::Read1 : Failure while parsing: " - "Not enough bytes (1)"); + LOGV( + "BufferReader::Read1 : Failure while parsing: " + "Not enough bytes (1)"); return false; } @@ -30,14 +32,18 @@ bool BufferReader::Read1(uint8_t* v) { template bool BufferReader::Read(T* v) { if (v == NULL) { - LOGE("BufferReader::Read : Failure during parse: Null output parameter " - "when expecting non-null (%s)", __PRETTY_FUNCTION__); + LOGE( + "BufferReader::Read : Failure during parse: Null output parameter " + "when expecting non-null (%s)", + __PRETTY_FUNCTION__); return false; } if (!HasBytes(sizeof(T))) { - LOGV("BufferReader::Read : Failure during parse: " - "Not enough bytes (%u)", sizeof(T)); + LOGV( + "BufferReader::Read : Failure during parse: " + "Not enough bytes (%u)", + sizeof(T)); return false; } @@ -59,14 +65,17 @@ bool BufferReader::Read8s(int64_t* v) { return Read(v); } bool BufferReader::ReadString(std::string* str, size_t count) { if (str == NULL) { - LOGE("BufferReader::ReadString : Failure during parse: Null output " - "parameter when expecting non-null"); + LOGE( + "BufferReader::ReadString : Failure during parse: Null output " + "parameter when expecting non-null"); return false; } if (!HasBytes(count)) { - LOGV("BufferReader::ReadString : Parse Failure: " - "Not enough bytes (%d)", count); + LOGV( + "BufferReader::ReadString : Parse Failure: " + "Not enough bytes (%d)", + count); return false; } @@ -77,14 +86,17 @@ bool BufferReader::ReadString(std::string* str, size_t count) { bool BufferReader::ReadVec(std::vector* vec, size_t count) { if (vec == NULL) { - LOGE("BufferReader::ReadVec : Failure during parse: Null output parameter " - "when expecting non-null"); + LOGE( + "BufferReader::ReadVec : Failure during parse: Null output parameter " + "when expecting non-null"); return false; } if (!HasBytes(count)) { - LOGV("BufferReader::ReadVec : Parse Failure: " - "Not enough bytes (%d)", count); + LOGV( + "BufferReader::ReadVec : Parse Failure: " + "Not enough bytes (%d)", + count); return false; } @@ -96,8 +108,10 @@ bool BufferReader::ReadVec(std::vector* vec, size_t count) { bool BufferReader::SkipBytes(size_t bytes) { if (!HasBytes(bytes)) { - LOGV("BufferReader::SkipBytes : Parse Failure: " - "Not enough bytes (%d)", bytes); + LOGV( + "BufferReader::SkipBytes : Parse Failure: " + "Not enough bytes (%d)", + bytes); return false; } @@ -107,8 +121,9 @@ bool BufferReader::SkipBytes(size_t bytes) { bool BufferReader::Read4Into8(uint64_t* v) { if (v == NULL) { - LOGE("BufferReader::Read4Into8 : Failure during parse: Null output " - "parameter when expecting non-null"); + LOGE( + "BufferReader::Read4Into8 : Failure during parse: Null output " + "parameter when expecting non-null"); return false; } @@ -122,8 +137,9 @@ bool BufferReader::Read4Into8(uint64_t* v) { bool BufferReader::Read4sInto8s(int64_t* v) { if (v == NULL) { - LOGE("BufferReader::Read4sInto8s : Failure during parse: Null output " - "parameter when expecting non-null"); + LOGE( + "BufferReader::Read4sInto8s : Failure during parse: Null output " + "parameter when expecting non-null"); return false; } diff --git a/core/src/cdm_engine.cpp b/core/src/cdm_engine.cpp index 74b9501a..abea390c 100644 --- a/core/src/cdm_engine.cpp +++ b/core/src/cdm_engine.cpp @@ -24,7 +24,7 @@ #include "wv_cdm_event_listener.h" namespace { -const uint64_t kReleaseSessionTimeToLive = 60; // seconds +const uint64_t kReleaseSessionTimeToLive = 60; // seconds const uint32_t kUpdateUsageInformationPeriod = 60; // seconds const size_t kUsageReportsPerRequest = 1; @@ -96,23 +96,27 @@ CdmEngine::~CdmEngine() { session_map_.Terminate(); } -CdmResponseType CdmEngine::OpenSession( - const CdmKeySystem& key_system, CdmClientPropertySet* property_set, - const CdmSessionId& forced_session_id, WvCdmEventListener* event_listener) { +CdmResponseType CdmEngine::OpenSession(const CdmKeySystem& key_system, + CdmClientPropertySet* property_set, + const CdmSessionId& forced_session_id, + WvCdmEventListener* event_listener) { return OpenSession(key_system, property_set, event_listener, &forced_session_id, NULL); } -CdmResponseType CdmEngine::OpenSession( - const CdmKeySystem& key_system, CdmClientPropertySet* property_set, - WvCdmEventListener* event_listener, CdmSessionId* session_id) { - return OpenSession(key_system, property_set, event_listener, NULL, session_id); +CdmResponseType CdmEngine::OpenSession(const CdmKeySystem& key_system, + CdmClientPropertySet* property_set, + WvCdmEventListener* event_listener, + CdmSessionId* session_id) { + return OpenSession(key_system, property_set, event_listener, NULL, + session_id); } -CdmResponseType CdmEngine::OpenSession( - const CdmKeySystem& key_system, CdmClientPropertySet* property_set, - WvCdmEventListener* event_listener, const CdmSessionId* forced_session_id, - CdmSessionId* session_id) { +CdmResponseType CdmEngine::OpenSession(const CdmKeySystem& key_system, + CdmClientPropertySet* property_set, + WvCdmEventListener* event_listener, + const CdmSessionId* forced_session_id, + CdmSessionId* session_id) { LOGI("CdmEngine::OpenSession"); if (!ValidateKeySystem(key_system)) { @@ -135,15 +139,14 @@ CdmResponseType CdmEngine::OpenSession( std::unique_ptr new_session( new CdmSession(file_system_, metrics_->AddSession())); - CdmResponseType sts = new_session->Init(property_set, forced_session_id, - event_listener); + CdmResponseType sts = + new_session->Init(property_set, forced_session_id, event_listener); if (sts != NO_ERROR) { if (sts == NEED_PROVISIONING) { cert_provisioning_requested_security_level_ = new_session->GetRequestedSecurityLevel(); // Reserve a session ID so the CDM can return success. - if (session_id) - *session_id = new_session->GenerateSessionId(); + if (session_id) *session_id = new_session->GenerateSessionId(); } else { LOGE("CdmEngine::OpenSession: bad session init: %d", sts); } @@ -176,8 +179,7 @@ CdmResponseType CdmEngine::OpenKeySetSession( key_set_in_use = release_key_sets_.find(key_set_id) != release_key_sets_.end(); } - if (key_set_in_use) - CloseKeySetSession(key_set_id); + if (key_set_in_use) CloseKeySetSession(key_set_id); CdmSessionId session_id; CdmResponseType sts = OpenSession(KEY_SYSTEM, property_set, event_listener, @@ -186,8 +188,8 @@ CdmResponseType CdmEngine::OpenKeySetSession( if (sts != NO_ERROR) return sts; std::unique_lock lock(release_key_sets_lock_); - release_key_sets_[key_set_id] = std::make_pair(session_id, - clock_.GetCurrentTime() + kReleaseSessionTimeToLive); + release_key_sets_[key_set_id] = std::make_pair( + session_id, clock_.GetCurrentTime() + kReleaseSessionTimeToLive); return NO_ERROR; } @@ -283,16 +285,17 @@ CdmResponseType CdmEngine::GenerateKeyRequest( key_request->message.clear(); - if (license_type == kLicenseTypeRelease && - !session->license_received()) { + if (license_type == kLicenseTypeRelease && !session->license_received()) { int error_detail = NO_ERROR; sts = session->RestoreOfflineSession(key_set_id, kLicenseTypeRelease, &error_detail); session->GetMetrics()->cdm_session_restore_offline_session_.Increment( sts, error_detail); if (sts != KEY_ADDED) { - LOGE("CdmEngine::GenerateKeyRequest: key release restoration failed," - "sts = %d", static_cast(sts)); + LOGE( + "CdmEngine::GenerateKeyRequest: key release restoration failed," + "sts = %d", + static_cast(sts)); return sts; } } @@ -307,8 +310,10 @@ CdmResponseType CdmEngine::GenerateKeyRequest( cert_provisioning_requested_security_level_ = session->GetRequestedSecurityLevel(); } - LOGE("CdmEngine::GenerateKeyRequest: key request generation failed, " - "sts = %d", static_cast(sts)); + LOGE( + "CdmEngine::GenerateKeyRequest: key request generation failed, " + "sts = %d", + static_cast(sts)); return sts; } @@ -325,8 +330,8 @@ CdmResponseType CdmEngine::AddKey(const CdmSessionId& session_id, CdmKeySetId* key_set_id) { LOGI("CdmEngine::AddKey: %s", session_id.c_str()); if (license_type == nullptr) { - LOGE("CdmEngine::AddKey: license_type cannot be null."); - return PARAMETER_NULL; + LOGE("CdmEngine::AddKey: license_type cannot be null."); + return PARAMETER_NULL; } CdmSessionId id = session_id; @@ -364,7 +369,6 @@ CdmResponseType CdmEngine::AddKey(const CdmSessionId& session_id, return EMPTY_KEY_DATA_1; } - CdmResponseType sts = (session->AddKey(key_data)); if (sts == KEY_ADDED) { @@ -380,8 +384,8 @@ CdmResponseType CdmEngine::AddKey(const CdmSessionId& session_id, } if (key_set_id) { - if ((session->is_offline() || - session->has_provider_session_token()) && !license_type_release) { + if ((session->is_offline() || session->has_provider_session_token()) && + !license_type_release) { *key_set_id = session->key_set_id(); LOGI("CdmEngine::AddKey: key set ID: %s", key_set_id->c_str()); } else { @@ -508,12 +512,8 @@ CdmResponseType CdmEngine::RenewKey(const CdmSessionId& session_id, } CdmResponseType sts; - M_TIME( - sts = session->RenewKey( - key_data), - session->GetMetrics(), - cdm_session_renew_key_, - sts); + M_TIME(sts = session->RenewKey(key_data), session->GetMetrics(), + cdm_session_renew_key_, sts); if (KEY_ADDED != sts) { LOGE("CdmEngine::RenewKey: keys not added, sts=%d", static_cast(sts)); @@ -571,24 +571,23 @@ CdmResponseType CdmEngine::QueryStatus(SecurityLevel security_level, LOGW("CdmEngine::QueryStatus: GetHdcpCapabilities failed: %d", status); return status; } - *query_response = - MapHdcpVersion(query_token == QUERY_KEY_CURRENT_HDCP_LEVEL ? - current_hdcp : max_hdcp); + *query_response = MapHdcpVersion( + query_token == QUERY_KEY_CURRENT_HDCP_LEVEL ? current_hdcp : max_hdcp); return NO_ERROR; } else if (query_token == QUERY_KEY_USAGE_SUPPORT) { bool supports_usage_reporting; bool got_info = crypto_session->UsageInformationSupport( - security_level, - &supports_usage_reporting); + security_level, &supports_usage_reporting); if (!got_info) { LOGW("CdmEngine::QueryStatus: UsageInformationSupport failed"); - metrics_->GetCryptoMetrics()->crypto_session_usage_information_support_ - .SetError(got_info); + metrics_->GetCryptoMetrics() + ->crypto_session_usage_information_support_.SetError(got_info); return UNKNOWN_ERROR; } - metrics_->GetCryptoMetrics()->crypto_session_usage_information_support_ - .Record(supports_usage_reporting); + metrics_->GetCryptoMetrics() + ->crypto_session_usage_information_support_.Record( + supports_usage_reporting); *query_response = supports_usage_reporting ? QUERY_VALUE_TRUE : QUERY_VALUE_FALSE; @@ -607,9 +606,8 @@ CdmResponseType CdmEngine::QueryStatus(SecurityLevel security_level, return NO_ERROR; } else if (query_token == QUERY_KEY_MAX_NUMBER_OF_SESSIONS) { size_t maximum_number_of_sessions = 0; - status = - crypto_session->GetMaxNumberOfSessions(security_level, - &maximum_number_of_sessions); + status = crypto_session->GetMaxNumberOfSessions( + security_level, &maximum_number_of_sessions); if (status != NO_ERROR) { LOGW("CdmEngine::QueryStatus: GetMaxNumberOfOpenSessions failed: %d", @@ -671,18 +669,41 @@ CdmResponseType CdmEngine::QueryStatus(SecurityLevel security_level, } return NO_ERROR; } else if (query_token == QUERY_KEY_DECRYPT_HASH_SUPPORT) { - *query_response = std::to_string(crypto_session->IsDecryptHashSupported( - security_level)); + *query_response = + std::to_string(crypto_session->IsDecryptHashSupported(security_level)); + return NO_ERROR; + } else if (query_token == QUERY_KEY_PROVISIONING_MODEL) { + CdmClientTokenType token_type = kClientTokenUninitialized; + status = crypto_session->GetProvisioningMethod(security_level, &token_type); + if (status != NO_ERROR) { + LOGW("CdmEngine::QueryStatus: GetProvisioningMethod failed: %d", status); + return status; + } + switch (token_type) { + case kClientTokenDrmCert: + *query_response = QUERY_VALUE_DRM_CERTIFICATE; + break; + case kClientTokenKeybox: + *query_response = QUERY_VALUE_KEYBOX; + break; + case kClientTokenOemCert: + *query_response = QUERY_VALUE_OEM_CERTIFICATE; + break; + case kClientTokenUninitialized: + default: + LOGW( + "CdmEngine::QueryStatus: GetProvisioningMethod returns invalid " + "token type: %d", + token_type); + return GET_PROVISIONING_METHOD_ERROR; + break; + } return NO_ERROR; } - M_TIME( - status = crypto_session->Open( - security_level), - metrics_->GetCryptoMetrics(), - crypto_session_open_, - status, - security_level); + M_TIME(status = crypto_session->Open(security_level), + metrics_->GetCryptoMetrics(), crypto_session_open_, status, + security_level); if (status != NO_ERROR) return status; @@ -690,8 +711,8 @@ CdmResponseType CdmEngine::QueryStatus(SecurityLevel security_level, if (query_token == QUERY_KEY_DEVICE_ID) { std::string deviceId; status = crypto_session->GetExternalDeviceUniqueId(&deviceId); - metrics_->GetCryptoMetrics()->crypto_session_get_device_unique_id_ - .Increment(status); + metrics_->GetCryptoMetrics() + ->crypto_session_get_device_unique_id_.Increment(status); if (status != NO_ERROR) return status; *query_response = deviceId; @@ -800,8 +821,8 @@ CdmResponseType CdmEngine::QueryKeyAllowedUsage(const std::string& key_id, CdmSessionList sessions; session_map_.GetSessionList(sessions); - for (CdmSessionList::iterator iter = sessions.begin(); - iter != sessions.end(); ++iter) { + for (CdmSessionList::iterator iter = sessions.begin(); iter != sessions.end(); + ++iter) { session_sts = (*iter)->QueryKeyAllowedUsage(key_id, &found_in_this_session); if (session_sts == NO_ERROR) { if (found) { @@ -844,8 +865,8 @@ bool CdmEngine::IsSecurityLevelSupported(CdmSecurityLevel level) { switch (level) { case kSecurityLevelL1: - return - crypto_session->GetSecurityLevel(kLevelDefault) == kSecurityLevelL1; + return crypto_session->GetSecurityLevel(kLevelDefault) == + kSecurityLevelL1; case kSecurityLevelL3: return crypto_session->GetSecurityLevel(kLevel3) == kSecurityLevelL3; default: @@ -917,8 +938,9 @@ CdmResponseType CdmEngine::HandleProvisioningResponse( return INVALID_PROVISIONING_PARAMETERS_1; } if (wrapped_key == NULL) { - LOGE("CdmEngine::HandleProvisioningResponse: invalid wrapped key " - "destination"); + LOGE( + "CdmEngine::HandleProvisioningResponse: invalid wrapped key " + "destination"); cert_provisioning_.reset(NULL); return INVALID_PROVISIONING_PARAMETERS_2; } @@ -928,13 +950,10 @@ CdmResponseType CdmEngine::HandleProvisioningResponse( std::unique_ptr crypto_session( CryptoSession::MakeCryptoSession(metrics_->GetCryptoMetrics())); CdmResponseType status; - M_TIME( - status = crypto_session->Open( - cert_provisioning_requested_security_level_), - metrics_->GetCryptoMetrics(), - crypto_session_open_, - status, - cert_provisioning_requested_security_level_); + M_TIME(status = crypto_session->Open( + cert_provisioning_requested_security_level_), + metrics_->GetCryptoMetrics(), crypto_session_open_, status, + cert_provisioning_requested_security_level_); if (NO_ERROR != status) { LOGE( "CdmEngine::HandleProvisioningResponse: provisioning object " @@ -967,7 +986,7 @@ bool CdmEngine::IsProvisioned(CdmSecurityLevel security_level) { // attempts to load it. If this fails, initialization will return an error. UsagePropertySet property_set; property_set.set_security_level( - security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault); + security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault); CdmSession session(file_system_, metrics_->AddSession()); @@ -986,8 +1005,8 @@ CdmResponseType CdmEngine::Unprovision(CdmSecurityLevel security_level) { CryptoSession::MakeCryptoSession(metrics_->GetCryptoMetrics())); CdmClientTokenType token_type = kClientTokenUninitialized; CdmResponseType res = crypto_session->GetProvisioningMethod( - security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault, - &token_type); + security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault, + &token_type); if (res != NO_ERROR) { return res; } else if (token_type == kClientTokenDrmCert) { @@ -1020,23 +1039,18 @@ CdmResponseType CdmEngine::DeleteUsageTable(CdmSecurityLevel security_level) { std::unique_ptr crypto_session( CryptoSession::MakeCryptoSession(metrics_->GetCryptoMetrics())); CdmResponseType status; - M_TIME( - status = crypto_session->Open( - security_level == kSecurityLevelL3 ? - kLevel3 : - kLevelDefault), - metrics_->GetCryptoMetrics(), - crypto_session_open_, - status, - security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault); + M_TIME(status = crypto_session->Open( + security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault), + metrics_->GetCryptoMetrics(), crypto_session_open_, status, + security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault); if (NO_ERROR != status) { LOGE("CdmEngine::DeleteUsageTable: error opening crypto session: %d", - status); + status); return UNPROVISION_ERROR_4; } status = crypto_session->DeleteAllUsageReports(); - metrics_->GetCryptoMetrics()->crypto_session_delete_all_usage_reports_ - .Increment(status); + metrics_->GetCryptoMetrics() + ->crypto_session_delete_all_usage_reports_.Increment(status); if (status != NO_ERROR) { LOGE("CdmEngine::DeleteUsageTable: error deleteing usage reports: %d", status); @@ -1063,8 +1077,7 @@ CdmResponseType CdmEngine::ListStoredLicenses( } CdmResponseType CdmEngine::ListUsageIds( - const std::string& app_id, - CdmSecurityLevel security_level, + const std::string& app_id, CdmSecurityLevel security_level, std::vector* ksids, std::vector* provider_session_tokens) { DeviceFiles handle(file_system_); @@ -1105,8 +1118,7 @@ CdmResponseType CdmEngine::DeleteUsageRecord(const std::string& app_id, } CdmResponseType CdmEngine::GetOfflineLicenseState( - const CdmKeySetId &key_set_id, - CdmSecurityLevel security_level, + const CdmKeySetId& key_set_id, CdmSecurityLevel security_level, CdmOfflineLicenseState* license_state) { DeviceFiles handle(file_system_); if (!handle.Init(security_level)) { @@ -1132,33 +1144,31 @@ CdmResponseType CdmEngine::GetOfflineLicenseState( uint32_t usage_entry_number; DeviceFiles::ResponseType sub_error_code = DeviceFiles::kNoError; - if (handle.RetrieveLicense(key_set_id, &state, &offline_init_data, - &key_request, &key_response, + if (handle.RetrieveLicense( + key_set_id, &state, &offline_init_data, &key_request, &key_response, &offline_key_renewal_request, &offline_key_renewal_response, - &offline_release_server_url, - &playback_start_time, &last_playback_time, &grace_period_end_time, - &app_parameters, &usage_entry, &usage_entry_number, - &sub_error_code)) { - *license_state = MapDeviceFilesLicenseState(state); + &offline_release_server_url, &playback_start_time, + &last_playback_time, &grace_period_end_time, &app_parameters, + &usage_entry, &usage_entry_number, &sub_error_code)) { + *license_state = MapDeviceFilesLicenseState(state); } else { - LOGE("CdmEngine::GetOfflineLicenseState:: failed to retrieve license state " - "key set id = %s", - key_set_id.c_str()); - return GET_OFFLINE_LICENSE_STATE_ERROR_2; + LOGE( + "CdmEngine::GetOfflineLicenseState:: failed to retrieve license state " + "key set id = %s", + key_set_id.c_str()); + return GET_OFFLINE_LICENSE_STATE_ERROR_2; } return NO_ERROR; } CdmResponseType CdmEngine::RemoveOfflineLicense( - const CdmKeySetId &key_set_id, - CdmSecurityLevel security_level) { - + const CdmKeySetId& key_set_id, CdmSecurityLevel security_level) { UsagePropertySet property_set; property_set.set_security_level( security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault); DeviceFiles handle(file_system_); - CdmResponseType sts = OpenKeySetSession(key_set_id, - &property_set, nullptr /* event listener */); + CdmResponseType sts = OpenKeySetSession(key_set_id, &property_set, + nullptr /* event listener */); if (sts != NO_ERROR) { if (!handle.Init(security_level)) { LOGE("CdmEngine::RemoveOfflineLicense: cannot initialize device files"); @@ -1173,7 +1183,7 @@ CdmResponseType CdmEngine::RemoveOfflineLicense( CdmKeyRequest key_request; // Calling with no session_id is okay sts = GenerateKeyRequest(session_id, key_set_id, dummy_init_data, - kLicenseTypeRelease, dummy_app_params, &key_request); + kLicenseTypeRelease, dummy_app_params, &key_request); if (sts == KEY_MESSAGE) { std::unique_lock lock(release_key_sets_lock_); CdmReleaseKeySetMap::iterator iter = release_key_sets_.find(key_set_id); @@ -1226,8 +1236,8 @@ CdmResponseType CdmEngine::GetUsageInfo(const std::string& app_id, CdmKeyResponse license_response; std::string usage_entry; DeviceFiles::CdmUsageData usage_data; - if (!handle.RetrieveUsageInfo(DeviceFiles::GetUsageInfoFileName(app_id), - ssid, &usage_data)) { + if (!handle.RetrieveUsageInfo(DeviceFiles::GetUsageInfoFileName(app_id), ssid, + &usage_data)) { usage_property_set_->set_security_level(kLevel3); usage_property_set_->set_app_id(app_id); usage_session_.reset(new CdmSession(file_system_, metrics_->AddSession())); @@ -1376,8 +1386,8 @@ CdmResponseType CdmEngine::GetUsageInfo(const std::string& app_id, CdmResponseType CdmEngine::RemoveAllUsageInfo( const std::string& app_id, CdmSecurityLevel cdm_security_level) { - LOGI("CdmEngine::RemoveAllUsageInfo: %s, security level: %d", - app_id.c_str(), cdm_security_level); + LOGI("CdmEngine::RemoveAllUsageInfo: %s, security level: %d", app_id.c_str(), + cdm_security_level); if (usage_property_set_.get() == nullptr) { usage_property_set_.reset(new UsagePropertySet()); } @@ -1400,36 +1410,38 @@ CdmResponseType CdmEngine::RemoveAllUsageInfo( // might cause other entries to be shifted and information updated. do { if (!handle.RetrieveUsageInfo( - DeviceFiles::GetUsageInfoFileName(app_id), - &usage_data)) { - LOGW("CdmEngine::RemoveAllUsageInfo: failed to retrieve usage info"); + DeviceFiles::GetUsageInfoFileName(app_id), &usage_data)) { + LOGW( + "CdmEngine::RemoveAllUsageInfo: failed to retrieve usage info"); break; } if (usage_data.empty()) break; CdmResponseType res = usage_session_->DeleteUsageEntry( - usage_data[0].usage_entry_number); + usage_data[0].usage_entry_number); if (res != NO_ERROR) { - LOGW("CdmEngine::RemoveAllUsageInfo: failed to delete usage " - "entry: error: %d", res); + LOGW( + "CdmEngine::RemoveAllUsageInfo: failed to delete usage " + "entry: error: %d", + res); break; } - if (!handle.DeleteUsageInfo( - DeviceFiles::GetUsageInfoFileName(app_id), - usage_data[0].provider_session_token)) { - LOGW("CdmEngine::RemoveAllUsageInfo: failed to delete usage " - "info"); + if (!handle.DeleteUsageInfo(DeviceFiles::GetUsageInfoFileName(app_id), + usage_data[0].provider_session_token)) { + LOGW( + "CdmEngine::RemoveAllUsageInfo: failed to delete usage " + "info"); break; } } while (!usage_data.empty()); std::vector provider_session_tokens; if (!handle.DeleteAllUsageInfoForApp( - DeviceFiles::GetUsageInfoFileName(app_id), - &provider_session_tokens)) { + DeviceFiles::GetUsageInfoFileName(app_id), + &provider_session_tokens)) { status = REMOVE_ALL_USAGE_INFO_ERROR_5; } break; @@ -1437,14 +1449,17 @@ CdmResponseType CdmEngine::RemoveAllUsageInfo( case kUsageTableSupport: { std::vector provider_session_tokens; if (!handle.DeleteAllUsageInfoForApp( - DeviceFiles::GetUsageInfoFileName(app_id), - &provider_session_tokens)) { - LOGE("CdmEngine::RemoveAllUsageInfo: failed to delete %d secure" - "stops", cdm_security_level); + DeviceFiles::GetUsageInfoFileName(app_id), + &provider_session_tokens)) { + LOGE( + "CdmEngine::RemoveAllUsageInfo: failed to delete %d secure" + "stops", + cdm_security_level); status = REMOVE_ALL_USAGE_INFO_ERROR_1; } else { - CdmResponseType status2 = usage_session_-> - DeleteMultipleUsageInformation(provider_session_tokens); + CdmResponseType status2 = + usage_session_->DeleteMultipleUsageInformation( + provider_session_tokens); if (status2 != NO_ERROR) status = status2; } break; @@ -1468,8 +1483,7 @@ CdmResponseType CdmEngine::RemoveAllUsageInfo(const std::string& app_id) { } CdmResponseType CdmEngine::RemoveUsageInfo( - const std::string& app_id, - const CdmSecureStopId& provider_session_token) { + const std::string& app_id, const CdmSecureStopId& provider_session_token) { LOGI("CdmEngine::RemoveUsageInfo: %s, PST: %s", app_id.c_str(), provider_session_token.c_str()); if (NULL == usage_property_set_.get()) { @@ -1482,11 +1496,11 @@ CdmResponseType CdmEngine::RemoveUsageInfo( DeviceFiles handle(file_system_); if (handle.Init(static_cast(j))) { SecurityLevel security_level = - static_cast(j) == kSecurityLevelL3 - ? kLevel3 - : kLevelDefault; + static_cast(j) == kSecurityLevelL3 ? kLevel3 + : kLevelDefault; usage_property_set_->set_security_level(security_level); - usage_session_.reset(new CdmSession(file_system_, metrics_->AddSession())); + usage_session_.reset( + new CdmSession(file_system_, metrics_->AddSession())); usage_session_->Init(usage_property_set_.get()); std::vector usage_data; @@ -1495,10 +1509,10 @@ CdmResponseType CdmEngine::RemoveUsageInfo( CdmUsageEntry usage_entry; uint32_t usage_entry_number; - if (!handle.RetrieveUsageInfo( - DeviceFiles::GetUsageInfoFileName(app_id), provider_session_token, - &license_request, &license_response, &usage_entry, - &usage_entry_number)) { + if (!handle.RetrieveUsageInfo(DeviceFiles::GetUsageInfoFileName(app_id), + provider_session_token, &license_request, + &license_response, &usage_entry, + &usage_entry_number)) { // Try other security level continue; } @@ -1507,24 +1521,23 @@ CdmResponseType CdmEngine::RemoveUsageInfo( case kUsageEntrySupport: { status = usage_session_->DeleteUsageEntry(usage_entry_number); - if (!handle.DeleteUsageInfo( - DeviceFiles::GetUsageInfoFileName(app_id), - provider_session_token)) { - status = REMOVE_USAGE_INFO_ERROR_1; + if (!handle.DeleteUsageInfo(DeviceFiles::GetUsageInfoFileName(app_id), + provider_session_token)) { + status = REMOVE_USAGE_INFO_ERROR_1; } usage_session_.reset(NULL); return status; } case kUsageTableSupport: { std::vector provider_session_tokens; - handle.DeleteUsageInfo( - DeviceFiles::GetUsageInfoFileName(app_id), - provider_session_token); + handle.DeleteUsageInfo(DeviceFiles::GetUsageInfoFileName(app_id), + provider_session_token); std::unique_ptr crypto_session( CryptoSession::MakeCryptoSession(metrics_->GetCryptoMetrics())); - status = crypto_session->Open( - static_cast(j) == kSecurityLevelL3 - ? kLevel3 : kLevelDefault); + status = crypto_session->Open(static_cast(j) == + kSecurityLevelL3 + ? kLevel3 + : kLevelDefault); if (status == NO_ERROR) { crypto_session->UpdateUsageInformation(); status = @@ -1598,19 +1611,18 @@ CdmResponseType CdmEngine::LoadUsageSession(const CdmKeySetId& key_set_id, DeviceFiles::CdmUsageData usage_data; if (!handle.RetrieveUsageInfoByKeySetId( - DeviceFiles::GetUsageInfoFileName(app_id), key_set_id, - &(usage_data.provider_session_token), - &(usage_data.license_request), - &(usage_data.license), &(usage_data.usage_entry), - &(usage_data.usage_entry_number))) { + DeviceFiles::GetUsageInfoFileName(app_id), key_set_id, + &(usage_data.provider_session_token), &(usage_data.license_request), + &(usage_data.license), &(usage_data.usage_entry), + &(usage_data.usage_entry_number))) { LOGE("CdmEngine::LoadUsageSession: unable to find usage information"); return LOAD_USAGE_INFO_MISSING; } int error_detail = NO_ERROR; usage_data.key_set_id = key_set_id; - CdmResponseType status = session->RestoreUsageSession(usage_data, - &error_detail); + CdmResponseType status = + session->RestoreUsageSession(usage_data, &error_detail); session->GetMetrics()->cdm_session_restore_usage_session_.Increment( status, error_detail); if (KEY_ADDED != status) { @@ -1698,10 +1710,12 @@ CdmResponseType CdmEngine::Decrypt(const CdmSessionId& session_id, return session->Decrypt(parameters); } -CdmResponseType CdmEngine::GenericEncrypt( - const std::string& session_id, const std::string& in_buffer, - const std::string& key_id, const std::string& iv, - CdmEncryptionAlgorithm algorithm, std::string* out_buffer) { +CdmResponseType CdmEngine::GenericEncrypt(const std::string& session_id, + const std::string& in_buffer, + const std::string& key_id, + const std::string& iv, + CdmEncryptionAlgorithm algorithm, + std::string* out_buffer) { if (out_buffer == NULL) { LOGE("CdmEngine::GenericEncrypt: no out_buffer provided"); return PARAMETER_NULL; @@ -1715,11 +1729,12 @@ CdmResponseType CdmEngine::GenericEncrypt( return session->GenericEncrypt(in_buffer, key_id, iv, algorithm, out_buffer); } -CdmResponseType CdmEngine::GenericDecrypt( - const std::string& session_id, const std::string& in_buffer, - const std::string& key_id, const std::string& iv, - CdmEncryptionAlgorithm algorithm, - std::string* out_buffer) { +CdmResponseType CdmEngine::GenericDecrypt(const std::string& session_id, + const std::string& in_buffer, + const std::string& key_id, + const std::string& iv, + CdmEncryptionAlgorithm algorithm, + std::string* out_buffer) { if (out_buffer == NULL) { LOGE("CdmEngine::GenericDecrypt: no out_buffer provided"); return PARAMETER_NULL; @@ -1733,10 +1748,11 @@ CdmResponseType CdmEngine::GenericDecrypt( return session->GenericDecrypt(in_buffer, key_id, iv, algorithm, out_buffer); } -CdmResponseType CdmEngine::GenericSign( - const std::string& session_id, const std::string& message, - const std::string& key_id, CdmSigningAlgorithm algorithm, - std::string* signature) { +CdmResponseType CdmEngine::GenericSign(const std::string& session_id, + const std::string& message, + const std::string& key_id, + CdmSigningAlgorithm algorithm, + std::string* signature) { if (signature == NULL) { LOGE("CdmEngine::GenericSign: no signature buffer provided"); return PARAMETER_NULL; @@ -1750,10 +1766,11 @@ CdmResponseType CdmEngine::GenericSign( return session->GenericSign(message, key_id, algorithm, signature); } -CdmResponseType CdmEngine::GenericVerify( - const std::string& session_id, const std::string& message, - const std::string& key_id, CdmSigningAlgorithm algorithm, - const std::string& signature) { +CdmResponseType CdmEngine::GenericVerify(const std::string& session_id, + const std::string& message, + const std::string& key_id, + CdmSigningAlgorithm algorithm, + const std::string& signature) { std::shared_ptr session; if (!session_map_.FindSession(session_id, &session)) { LOGE("CdmEngine::GenericVerify: session_id not found = %s ", @@ -1764,10 +1781,8 @@ CdmResponseType CdmEngine::GenericVerify( } CdmResponseType CdmEngine::ParseDecryptHashString( - const std::string& hash_string, - CdmSessionId* session_id, - uint32_t* frame_number, - std::string* hash) { + const std::string& hash_string, CdmSessionId* session_id, + uint32_t* frame_number, std::string* hash) { if (session_id == nullptr) { LOGE("CdmEngine::ParseDecryptHashString: |session_id| was not provided"); return PARAMETER_NULL; @@ -1788,16 +1803,19 @@ CdmResponseType CdmEngine::ParseDecryptHashString( tokens.push_back(token); } if (tokens.size() != 3) { - LOGE("CdmEngine::ParseDecryptHashString: |hash_string| has invalid format, " - "unexpected number of tokens: %d (%s)", - tokens.size(), hash_string.c_str()); + LOGE( + "CdmEngine::ParseDecryptHashString: |hash_string| has invalid format, " + "unexpected number of tokens: %d (%s)", + tokens.size(), hash_string.c_str()); return INVALID_DECRYPT_HASH_FORMAT; } for (size_t i = 0; i < tokens.size(); ++i) { if (tokens[i].empty()) { - LOGE("CdmEngine::ParseDecryptHashString: |hash_string| has invalid " - "format, token %d of length 0: %s", i, hash_string.c_str()); + LOGE( + "CdmEngine::ParseDecryptHashString: |hash_string| has invalid " + "format, token %d of length 0: %s", + i, hash_string.c_str()); return INVALID_DECRYPT_HASH_FORMAT; } } @@ -1805,8 +1823,10 @@ CdmResponseType CdmEngine::ParseDecryptHashString( *session_id = tokens[0]; std::istringstream iss(tokens[1]); if (!(iss >> *frame_number)) { - LOGE("CdmEngine::ParseDecryptHashString: error while trying to convert " - "frame number to a numeric format: %s", hash_string.c_str()); + LOGE( + "CdmEngine::ParseDecryptHashString: error while trying to convert " + "frame number to a numeric format: %s", + hash_string.c_str()); return INVALID_DECRYPT_HASH_FORMAT; } @@ -1820,10 +1840,9 @@ CdmResponseType CdmEngine::ParseDecryptHashString( return NO_ERROR; } -CdmResponseType CdmEngine::SetDecryptHash( - const CdmSessionId& session_id, - uint32_t frame_number, - const std::string& hash) { +CdmResponseType CdmEngine::SetDecryptHash(const CdmSessionId& session_id, + uint32_t frame_number, + const std::string& hash) { LOGI("CdmEngine::SetDecryptHash: %s", session_id.c_str()); std::shared_ptr session; if (!session_map_.FindSession(session_id, &session)) { @@ -1832,9 +1851,8 @@ CdmResponseType CdmEngine::SetDecryptHash( return session->SetDecryptHash(frame_number, hash); } -CdmResponseType CdmEngine::GetDecryptHashError( - const CdmSessionId& session_id, - std::string* error_string) { +CdmResponseType CdmEngine::GetDecryptHashError(const CdmSessionId& session_id, + std::string* error_string) { LOGI("CdmEngine::GetDecryptHashError: %s", session_id.c_str()); std::shared_ptr session; if (!session_map_.FindSession(session_id, &session)) { @@ -1847,8 +1865,8 @@ CdmResponseType CdmEngine::GetDecryptHashError( bool CdmEngine::IsKeyLoaded(const KeyId& key_id) { CdmSessionList sessions; session_map_.GetSessionList(sessions); - for (CdmSessionList::iterator iter = sessions.begin(); - iter != sessions.end(); ++iter) { + for (CdmSessionList::iterator iter = sessions.begin(); iter != sessions.end(); + ++iter) { if ((*iter)->IsKeyLoaded(key_id)) { return true; } @@ -1872,8 +1890,8 @@ bool CdmEngine::FindSessionForKey(const KeyId& key_id, CdmSessionList::iterator session_iter = sessions.end(); int64_t seconds_remaining = 0; - for (CdmSessionList::iterator iter = sessions.begin(); - iter != sessions.end(); ++iter) { + for (CdmSessionList::iterator iter = sessions.begin(); iter != sessions.end(); + ++iter) { CdmSessionId id = (*iter)->session_id(); if (Properties::GetSessionSharingId(id) == session_sharing_id) { if ((*iter)->IsKeyLoaded(key_id)) { @@ -1927,9 +1945,8 @@ void CdmEngine::OnTimerEvent() { session_map_.GetSessionList(sessions); while (!sessions.empty()) { - is_initial_usage_update = - is_initial_usage_update || - sessions.front()->is_initial_usage_update(); + is_initial_usage_update = is_initial_usage_update || + sessions.front()->is_initial_usage_update(); is_usage_update_needed = is_usage_update_needed || sessions.front()->is_usage_update_needed(); @@ -1990,8 +2007,7 @@ CdmResponseType CdmEngine::ValidateServiceCertificate(const std::string& cert) { return certificate.Init(cert); } -std::string CdmEngine::MapHdcpVersion( - CryptoSession::HdcpCapability version) { +std::string CdmEngine::MapHdcpVersion(CryptoSession::HdcpCapability version) { switch (version) { case HDCP_NONE: return QUERY_VALUE_HDCP_NONE; @@ -2048,27 +2064,26 @@ void CdmEngine::DeleteAllUsageReportsUponFactoryReset() { std::unique_ptr crypto_session( CryptoSession::MakeCryptoSession(metrics_->GetCryptoMetrics())); CdmResponseType status; - M_TIME( - status = crypto_session->Open( - cert_provisioning_requested_security_level_), - metrics_->GetCryptoMetrics(), - crypto_session_open_, - status, - cert_provisioning_requested_security_level_); + M_TIME(status = crypto_session->Open( + cert_provisioning_requested_security_level_), + metrics_->GetCryptoMetrics(), crypto_session_open_, status, + cert_provisioning_requested_security_level_); if (NO_ERROR == status) { status = crypto_session->DeleteAllUsageReports(); - metrics_->GetCryptoMetrics()->crypto_session_delete_all_usage_reports_ - .Increment(status); + metrics_->GetCryptoMetrics() + ->crypto_session_delete_all_usage_reports_.Increment(status); if (NO_ERROR != status) { LOGW( "CdmEngine::DeleteAllUsageReportsUponFactoryReset: " - "Fails to delete usage reports: %d", status); + "Fails to delete usage reports: %d", + status); } } else { LOGW( "CdmEngine::DeleteAllUsageReportsUponFactoryReset: " "Fails to open crypto session: error=%d.\n" - "Usage reports are not removed after factory reset.", status); + "Usage reports are not removed after factory reset.", + status); } } } diff --git a/core/src/cdm_engine_factory.cpp b/core/src/cdm_engine_factory.cpp index ca9b2949..28363fc4 100644 --- a/core/src/cdm_engine_factory.cpp +++ b/core/src/cdm_engine_factory.cpp @@ -6,6 +6,7 @@ #include #include + #include "cdm_engine.h" #include "cdm_engine_metrics_decorator.h" #include "clock.h" diff --git a/core/src/cdm_session.cpp b/core/src/cdm_session.cpp index 2b0dcc94..9e3ee8e6 100644 --- a/core/src/cdm_session.cpp +++ b/core/src/cdm_session.cpp @@ -7,8 +7,7 @@ #include #include -#include -#include +#include #include "cdm_engine.h" #include "clock.h" @@ -24,7 +23,7 @@ namespace { const size_t kKeySetIdLength = 14; // Helper function for setting the error detail value. -template +template void SetErrorDetail(int* error_detail, T error_code) { if (error_detail != nullptr) { *error_detail = error_code; @@ -64,8 +63,7 @@ CdmSession::CdmSession(FileSystem* file_system, CdmSession::~CdmSession() { if (usage_support_type_ == kUsageEntrySupport && - has_provider_session_token() && - usage_table_header_ != NULL && + has_provider_session_token() && usage_table_header_ != NULL && !is_release_) { UpdateUsageEntryInformation(); } @@ -108,8 +106,8 @@ CdmResponseType CdmSession::Init(CdmClientPropertySet* cdm_client_property_set, security_level_ = crypto_session_->GetSecurityLevel(); crypto_metrics_->crypto_session_security_level_.Record(security_level_); std::string oemcrypto_build; - if(crypto_session_->GetBuildInformation(requested_security_level_, - &oemcrypto_build)) { + if (crypto_session_->GetBuildInformation(requested_security_level_, + &oemcrypto_build)) { metrics_->oemcrypto_build_info_.Record(oemcrypto_build); } else { metrics_->oemcrypto_build_info_.SetError(false); @@ -153,7 +151,8 @@ CdmResponseType CdmSession::Init(CdmClientPropertySet* cdm_client_property_set, crypto_metrics_, crypto_session_load_certificate_private_key_, load_cert_sts); switch (load_cert_sts) { - case NO_ERROR: break; + case NO_ERROR: + break; case SESSION_LOST_STATE_ERROR: case SYSTEM_INVALIDATED_ERROR: return load_cert_sts; @@ -208,9 +207,9 @@ CdmResponseType CdmSession::Init(CdmClientPropertySet* cdm_client_property_set, return NO_ERROR; } -CdmResponseType CdmSession::RestoreOfflineSession( - const CdmKeySetId& key_set_id, CdmLicenseType license_type, - int* error_detail) { +CdmResponseType CdmSession::RestoreOfflineSession(const CdmKeySetId& key_set_id, + CdmLicenseType license_type, + int* error_detail) { if (!initialized_) { LOGE("CdmSession::RestoreOfflineSession: not initialized"); return NOT_INITIALIZED_ERROR; @@ -238,7 +237,8 @@ CdmResponseType CdmSession::RestoreOfflineSession( "sub error: %d, key set id = %s", sub_error_code, key_set_id.c_str()); SetErrorDetail(error_detail, sub_error_code); - return GET_LICENSE_ERROR; + return sub_error_code == DeviceFiles::kFileNotFound ? KEYSET_ID_NOT_FOUND_4 + : GET_LICENSE_ERROR; } // Attempts to restore a released offline license are treated as a release @@ -340,8 +340,8 @@ CdmResponseType CdmSession::RestoreUsageSession( CdmResponseType sts = NO_ERROR; if (usage_support_type_ == kUsageEntrySupport && usage_table_header_ != NULL) { - sts = usage_table_header_->LoadEntry( - crypto_session_.get(), usage_entry_, usage_entry_number_); + sts = usage_table_header_->LoadEntry(crypto_session_.get(), usage_entry_, + usage_entry_number_); crypto_metrics_->usage_table_header_load_entry_.Increment(sts); if (sts != NO_ERROR) { LOGE("CdmSession::RestoreUsageSession: failed to load usage entry = %d", @@ -390,16 +390,14 @@ CdmResponseType CdmSession::GenerateKeyRequest( // for calling GenerateReleaseRequest and GenerateRenewalRequest. if (result == KEY_MESSAGE) { key_request_type_ = key_request->type; - license_request_latency_.Start(); // Start or restart timer. + license_request_latency_.Start(); // Start or restart timer. } return result; } CdmResponseType CdmSession::GenerateKeyRequestInternal( const InitializationData& init_data, CdmLicenseType license_type, - const CdmAppParameterMap& app_parameters, - CdmKeyRequest* key_request) { - + const CdmAppParameterMap& app_parameters, CdmKeyRequest* key_request) { if (!initialized_) { LOGE("CdmSession::GenerateKeyRequest: not initialized"); return NOT_INITIALIZED_ERROR; @@ -423,10 +421,12 @@ CdmResponseType CdmSession::GenerateKeyRequestInternal( case kLicenseTypeRelease: is_release_ = true; break; - // TODO(jfore): CdmSession assumes a call to this method once a license has - // been received is a call to generate a license renewal message. Use of - // this enum differentiates the two calls. See "else if (license_received_)" - // below. + // TODO(b/132071885): Once a license has been received, CdmSession assumes + // that a call to this method is to generate a license renewal/release + // or key rotation. Key rotation can be indicated by specifing a license + // type kLicenseTypeEmbeddedKeyData or interrogating the PSSH + // (See "else if (license_received_)" below). b/132071885 is to evaluate + // whether both mechanisms are needed. case kLicenseTypeEmbeddedKeyData: return license_parser_->HandleEmbeddedKeyData(init_data); default: @@ -437,8 +437,17 @@ CdmResponseType CdmSession::GenerateKeyRequestInternal( if (is_release_) { return GenerateReleaseRequest(key_request); - } else if (license_received_) { // renewal - return GenerateRenewalRequest(key_request); + } else if (license_received_) { + // A call to GenerateKeyRequest after the initial license has been received + // is either a renewal/release request or a key rotation event + if (init_data.contains_entitled_keys()) { + key_request->message.clear(); + key_request->type = kKeyRequestTypeNone; + key_request->url.clear(); + return license_parser_->HandleEmbeddedKeyData(init_data); + } else { + return GenerateRenewalRequest(key_request); + } } else { key_request->type = kKeyRequestTypeInitial; @@ -515,7 +524,8 @@ CdmResponseType CdmSession::AddKeyInternal(const CdmKeyResponse& key_response) { // Update the license sdk and service versions. const VersionInfo& version_info = license_parser_->GetServiceVersion(); metrics_->license_sdk_version_.Record(version_info.license_sdk_version()); - metrics_->license_sdk_version_.Record(version_info.license_service_version()); + metrics_->license_sdk_version_.Record( + version_info.license_service_version()); // Update or delete entry if usage table header+entries are supported if (usage_support_type_ == kUsageEntrySupport && @@ -605,9 +615,8 @@ CdmResponseType CdmSession::QueryOemCryptoSessionId( return NOT_INITIALIZED_ERROR; } - std::stringstream ss; - ss << crypto_session_->oec_session_id(); - (*query_response)[QUERY_KEY_OEMCRYPTO_SESSION_ID] = ss.str(); + (*query_response)[QUERY_KEY_OEMCRYPTO_SESSION_ID] = + std::to_string(crypto_session_->oec_session_id()); return NO_ERROR; } @@ -628,8 +637,7 @@ CdmResponseType CdmSession::Decrypt(const CdmDecryptionParameters& params) { return INSUFFICIENT_OUTPUT_PROTECTION; return NEED_KEY; } - if (!policy_engine_->CanUseKeyForSecurityLevel(*params.key_id, - security_level_)) { + if (!policy_engine_->CanUseKeyForSecurityLevel(*params.key_id)) { return KEY_PROHIBITED_FOR_SECURITY_LEVEL; } } @@ -674,7 +682,7 @@ CdmResponseType CdmSession::GenerateRenewalRequest(CdmKeyRequest* key_request) { offline_key_renewal_request_ = key_request->message; } key_request_type_ = key_request->type; - license_request_latency_.Start(); // Start or restart timer. + license_request_latency_.Start(); // Start or restart timer. return KEY_MESSAGE; } @@ -740,7 +748,7 @@ CdmResponseType CdmSession::GenerateReleaseRequest(CdmKeyRequest* key_request) { } key_request_type_ = key_request->type; - license_request_latency_.Start(); // Start or restart timer. + license_request_latency_.Start(); // Start or restart timer. return KEY_MESSAGE; } @@ -795,8 +803,8 @@ CdmResponseType CdmSession::DeleteUsageEntry(uint32_t usage_entry_number) { return INCORRECT_USAGE_SUPPORT_TYPE_1; } - sts = usage_table_header_->DeleteEntry(usage_entry_number, - file_handle_.get(), crypto_metrics_); + sts = usage_table_header_->DeleteEntry(usage_entry_number, file_handle_.get(), + crypto_metrics_); crypto_metrics_->usage_table_header_delete_entry_.Increment(sts); return sts; } @@ -825,8 +833,8 @@ bool CdmSession::GenerateKeySetId(CdmKeySetId* key_set_id) { (kKeySetIdLength - sizeof(KEY_SET_ID_PREFIX)) / 2, 0); while (key_set_id->empty()) { - if (crypto_session_->GetRandom(random_data.size(), &random_data[0]) - != NO_ERROR) { + if (crypto_session_->GetRandom(random_data.size(), &random_data[0]) != + NO_ERROR) { return false; } @@ -896,8 +904,7 @@ CdmResponseType CdmSession::StoreLicense() { } std::vector provider_session_tokens; file_handle_->DeleteAllUsageInfoForApp( - DeviceFiles::GetUsageInfoFileName(app_id), - &provider_session_tokens); + DeviceFiles::GetUsageInfoFileName(app_id), &provider_session_tokens); return STORE_USAGE_INFO_ERROR; } @@ -924,21 +931,16 @@ CdmResponseType CdmSession::RemoveKeys() { CdmResponseType sts; crypto_session_.reset(CryptoSession::MakeCryptoSession(crypto_metrics_)); // Ignore errors - M_TIME( - sts = crypto_session_->Open(requested_security_level_), - crypto_metrics_, - crypto_session_open_, - sts, - requested_security_level_); - policy_engine_.reset(new PolicyEngine( - session_id_, NULL, crypto_session_.get())); + M_TIME(sts = crypto_session_->Open(requested_security_level_), + crypto_metrics_, crypto_session_open_, sts, requested_security_level_); + policy_engine_.reset( + new PolicyEngine(session_id_, NULL, crypto_session_.get())); return NO_ERROR; } CdmResponseType CdmSession::RemoveLicense() { CdmResponseType sts = NO_ERROR; if (is_offline_ || has_provider_session_token()) { - if (usage_support_type_ == kUsageEntrySupport && has_provider_session_token()) { sts = DeleteUsageEntry(usage_entry_number_); @@ -1048,7 +1050,8 @@ CdmResponseType CdmSession::UpdateUsageEntryInformation() { if (is_offline_) StoreLicense(is_release_ ? DeviceFiles::kLicenseStateReleasing - : DeviceFiles::kLicenseStateActive, nullptr); + : DeviceFiles::kLicenseStateActive, + nullptr); else if (!usage_provider_session_token_.empty()) UpdateUsageInfo(); @@ -1122,8 +1125,7 @@ CdmResponseType CdmSession::SetDecryptHash(uint32_t frame_number, return crypto_session_->SetDecryptHash(frame_number, hash); } -CdmResponseType CdmSession::GetDecryptHashError( - std::string* error_string) { +CdmResponseType CdmSession::GetDecryptHashError(std::string* error_string) { return crypto_session_->GetDecryptHashError(error_string); } diff --git a/core/src/cdm_session_map.cpp b/core/src/cdm_session_map.cpp index 5cf4eae2..c2ddad3a 100644 --- a/core/src/cdm_session_map.cpp +++ b/core/src/cdm_session_map.cpp @@ -11,13 +11,11 @@ namespace wvcdm { -CdmSessionMap::~CdmSessionMap() { - Terminate(); -} +CdmSessionMap::~CdmSessionMap() { Terminate(); } void CdmSessionMap::Terminate() { - for (CdmIdToSessionMap::iterator i = sessions_.begin(); - i != sessions_.end(); ++i) { + for (CdmIdToSessionMap::iterator i = sessions_.begin(); i != sessions_.end(); + ++i) { i->second->Close(); i->second.reset(); } diff --git a/core/src/certificate_provisioning.cpp b/core/src/certificate_provisioning.cpp index bf0a23bb..019547df 100644 --- a/core/src/certificate_provisioning.cpp +++ b/core/src/certificate_provisioning.cpp @@ -3,6 +3,7 @@ // License Agreement. #include "certificate_provisioning.h" + #include "client_identification.h" #include "device_files.h" #include "file_store.h" @@ -110,9 +111,9 @@ using video_widevine::SignedProvisioningMessage; CdmResponseType CertificateProvisioning::Init( const std::string& service_certificate) { - - std::string certificate = service_certificate.empty() ? - kCpProductionServiceCertificate : service_certificate; + std::string certificate = service_certificate.empty() + ? kCpProductionServiceCertificate + : service_certificate; return service_certificate_->Init(certificate); } @@ -126,8 +127,9 @@ CdmResponseType CertificateProvisioning::SetSpoidParameter( const std::string& origin, const std::string& spoid, ProvisioningRequest* request) { if (!request) { - LOGE("CertificateProvisioning::SetSpoidParameter: No request buffer " - "passed to method."); + LOGE( + "CertificateProvisioning::SetSpoidParameter: No request buffer " + "passed to method."); return PARAMETER_NULL; } if (!spoid.empty()) { @@ -137,8 +139,9 @@ CdmResponseType CertificateProvisioning::SetSpoidParameter( if (!service_certificate_->provider_id().empty()) { request->set_provider_id(service_certificate_->provider_id()); } else { - LOGE("CertificateProvisioning::SetSpoidParameter: Failure getting " - "provider ID"); + LOGE( + "CertificateProvisioning::SetSpoidParameter: Failure getting " + "provider ID"); return SERVICE_CERTIFICATE_PROVIDER_ID_EMPTY; } } else if (origin != EMPTY_ORIGIN) { @@ -148,8 +151,9 @@ CdmResponseType CertificateProvisioning::SetSpoidParameter( crypto_session_->GetInternalDeviceUniqueId(&device_unique_id); if (status != NO_ERROR) { - LOGE("CertificateProvisioning::SetSpoidParameter: Failure getting " - "device unique ID"); + LOGE( + "CertificateProvisioning::SetSpoidParameter: Failure getting " + "device unique ID"); return status; } request->set_stable_id(device_unique_id + origin); @@ -162,7 +166,7 @@ CdmResponseType CertificateProvisioning::SetSpoidParameter( * support for OEM certificates. */ SignedProvisioningMessage::ProtocolVersion - CertificateProvisioning::GetProtocolVersion() { +CertificateProvisioning::GetProtocolVersion() { if (crypto_session_->GetPreProvisionTokenType() == kClientTokenOemCert) return SignedProvisioningMessage::VERSION_3; else @@ -209,8 +213,9 @@ CdmResponseType CertificateProvisioning::GetProvisioningRequest( if (status != NO_ERROR) return status; if (!service_certificate_->has_certificate()) { - LOGE("CertificateProvisioning::GetProvisioningRequest: Service " - "Certificate not staged"); + LOGE( + "CertificateProvisioning::GetProvisioningRequest: Service " + "Certificate not staged"); return CERT_PROVISIONING_EMPTY_SERVICE_CERTIFICATE; } @@ -226,8 +231,9 @@ CdmResponseType CertificateProvisioning::GetProvisioningRequest( if (status != NO_ERROR) { LOGE("GetProvisioningRequest: fails to generate a nonce: %d", status); - return status == NONCE_GENERATION_ERROR ? - CERT_PROVISIONING_NONCE_GENERATION_ERROR : status; + return status == NONCE_GENERATION_ERROR + ? CERT_PROVISIONING_NONCE_GENERATION_ERROR + : status; } // The provisioning server does not convert the nonce to uint32_t, it just @@ -303,7 +309,6 @@ CdmResponseType CertificateProvisioning::GetProvisioningRequest( CdmResponseType CertificateProvisioning::HandleProvisioningResponse( FileSystem* file_system, const CdmProvisioningResponse& response_message, std::string* cert, std::string* wrapped_key) { - if (response_message.empty()) { LOGE("HandleProvisioningResponse: response message is empty."); return CERT_PROVISIONING_RESPONSE_ERROR_1; @@ -317,8 +322,9 @@ CdmResponseType CertificateProvisioning::HandleProvisioningResponse( // Extract it and decode it. On error return an empty string. ExtractAndDecodeSignedMessage(response_message, &response); if (response.empty()) { - LOGE("HandleProvisioningResponse: response message is " - "an invalid JSON/base64 string."); + LOGE( + "HandleProvisioningResponse: response message is " + "an invalid JSON/base64 string."); return CERT_PROVISIONING_RESPONSE_ERROR_1; } } @@ -362,8 +368,8 @@ CdmResponseType CertificateProvisioning::HandleProvisioningResponse( // If Provisioning 3.0 (OEM Cert provisioned), verify that the // message is properly signed. if (crypto_session_->GetPreProvisionTokenType() == kClientTokenOemCert) { - if (service_certificate_->VerifySignedMessage(signed_message, signature) - != NO_ERROR) { + if (service_certificate_->VerifySignedMessage(signed_message, signature) != + NO_ERROR) { // TODO(b/69562876): if the cert is bad, request a new one. LOGE("HandleProvisioningResponse: message not properly signed"); return CERT_PROVISIONING_RESPONSE_ERROR_6; @@ -374,15 +380,15 @@ CdmResponseType CertificateProvisioning::HandleProvisioningResponse( const std::string& nonce = provisioning_response.nonce(); const std::string& iv = provisioning_response.device_rsa_key_iv(); - const std::string& wrapping_key = (provisioning_response.has_wrapping_key()) ? - provisioning_response.wrapping_key() : std::string(); + const std::string& wrapping_key = (provisioning_response.has_wrapping_key()) + ? provisioning_response.wrapping_key() + : std::string(); std::string wrapped_private_key; - CdmResponseType status = - crypto_session_->RewrapCertificate(signed_message, signature, nonce, - new_private_key, iv, wrapping_key, - &wrapped_private_key); + CdmResponseType status = crypto_session_->RewrapCertificate( + signed_message, signature, nonce, new_private_key, iv, wrapping_key, + &wrapped_private_key); if (status != NO_ERROR) { LOGE("HandleProvisioningResponse: RewrapCertificate fails"); diff --git a/core/src/client_identification.cpp b/core/src/client_identification.cpp index 1a1d864f..30c6719c 100644 --- a/core/src/client_identification.cpp +++ b/core/src/client_identification.cpp @@ -4,7 +4,7 @@ #include "client_identification.h" -#include +#include #include "crypto_session.h" #include "license_protocol.pb.h" @@ -24,6 +24,8 @@ const std::string kKeyDeviceId = "device_id"; const std::string kKeyWvCdmVersion = "widevine_cdm_version"; const std::string kKeyOemCryptoSecurityPatchLevel = "oem_crypto_security_patch_level"; +const std::string kKeyOemCryptoBuildInformation = + "oem_crypto_build_information"; } // unnamed namespace namespace wvcdm { @@ -75,7 +77,6 @@ CdmResponseType ClientIdentification::Prepare( const CdmAppParameterMap& app_parameters, const std::string& provider_client_token, video_widevine::ClientIdentification* client_id) { - if (is_license_request_) { client_id->set_type( video_widevine::ClientIdentification::DRM_DEVICE_CERTIFICATE); @@ -83,8 +84,9 @@ CdmResponseType ClientIdentification::Prepare( } else { video_widevine::ClientIdentification::TokenType token_type; if (!GetProvisioningTokenType(&token_type)) { - LOGE("ClientIdentification::Prepare: failure getting provisioning token " - "type"); + LOGE( + "ClientIdentification::Prepare: failure getting provisioning token " + "type"); return CLIENT_IDENTIFICATION_TOKEN_ERROR_1; } client_id->set_type(token_type); @@ -92,8 +94,10 @@ CdmResponseType ClientIdentification::Prepare( std::string token; CdmResponseType status = crypto_session_->GetProvisioningToken(&token); if (status != NO_ERROR) { - LOGE("ClientIdentification::Prepare: failure getting provisioning token: " - "%d", status); + LOGE( + "ClientIdentification::Prepare: failure getting provisioning token: " + "%d", + status); return status; } client_id->set_token(token); @@ -146,10 +150,14 @@ CdmResponseType ClientIdentification::Prepare( } client_info = client_id->add_client_info(); client_info->set_name(kKeyOemCryptoSecurityPatchLevel); - std::stringstream ss; - ss << (uint32_t)crypto_session_->GetSecurityPatchLevel(); - client_info->set_value(ss.str()); - + client_info->set_value( + std::to_string((uint32_t)crypto_session_->GetSecurityPatchLevel())); + std::string oec_build_info; + if (crypto_session_->GetBuildInformation(&oec_build_info)) { + client_info = client_id->add_client_info(); + client_info->set_name(kKeyOemCryptoBuildInformation); + client_info->set_value(oec_build_info); + } if (!provider_client_token.empty()) { client_id->set_provider_client_token(provider_client_token); } @@ -217,7 +225,8 @@ CdmResponseType ClientIdentification::Prepare( default: LOGW( "ClientIdentification::PrepareClientId: unexpected HDCP max " - "capability version %d", max_version); + "capability version %d", + max_version); } } } @@ -246,23 +255,27 @@ CdmResponseType ClientIdentification::Prepare( bool can_support_output; bool can_disable_output; bool can_support_cgms_a; - if (crypto_session_->GetAnalogOutputCapabilities(&can_support_output, - &can_disable_output, - &can_support_cgms_a)) { + if (crypto_session_->GetAnalogOutputCapabilities( + &can_support_output, &can_disable_output, &can_support_cgms_a)) { video_widevine::ClientIdentification_ClientCapabilities_AnalogOutputCapabilities - capabilities = video_widevine::ClientIdentification_ClientCapabilities_AnalogOutputCapabilities_ANALOG_OUTPUT_NONE; + capabilities = video_widevine:: + ClientIdentification_ClientCapabilities_AnalogOutputCapabilities_ANALOG_OUTPUT_NONE; if (can_support_output) { if (can_support_cgms_a) { - capabilities = video_widevine::ClientIdentification_ClientCapabilities_AnalogOutputCapabilities_ANALOG_OUTPUT_SUPPORTS_CGMS_A; + capabilities = video_widevine:: + ClientIdentification_ClientCapabilities_AnalogOutputCapabilities_ANALOG_OUTPUT_SUPPORTS_CGMS_A; } else { - capabilities = video_widevine::ClientIdentification_ClientCapabilities_AnalogOutputCapabilities_ANALOG_OUTPUT_SUPPORTED; + capabilities = video_widevine:: + ClientIdentification_ClientCapabilities_AnalogOutputCapabilities_ANALOG_OUTPUT_SUPPORTED; } } client_capabilities->set_analog_output_capabilities(capabilities); client_capabilities->set_can_disable_analog_output(can_disable_output); } else { - client_capabilities->set_analog_output_capabilities(video_widevine::ClientIdentification_ClientCapabilities_AnalogOutputCapabilities_ANALOG_OUTPUT_UNKNOWN); + client_capabilities->set_analog_output_capabilities( + video_widevine:: + ClientIdentification_ClientCapabilities_AnalogOutputCapabilities_ANALOG_OUTPUT_UNKNOWN); } uint32_t version, tier; @@ -291,8 +304,10 @@ bool ClientIdentification::GetProvisioningTokenType( case kClientTokenDrmCert: default: // shouldn't happen - LOGE("CertificateProvisioning::GetProvisioningTokenType: unexpected " - "provisioning type: %d", token); + LOGE( + "CertificateProvisioning::GetProvisioningTokenType: unexpected " + "provisioning type: %d", + token); return false; } } diff --git a/core/src/content_key_session.cpp b/core/src/content_key_session.cpp index 11431a74..5eb010c6 100644 --- a/core/src/content_key_session.cpp +++ b/core/src/content_key_session.cpp @@ -3,6 +3,7 @@ // License Agreement. #include "content_key_session.h" + #include "crypto_key.h" #include "crypto_session.h" #include "log.h" @@ -36,8 +37,7 @@ OEMCryptoResult ContentKeySession::GenerateDerivedKeys( // Generate Derived Keys (from session key) for ContentKeySession OEMCryptoResult ContentKeySession::GenerateDerivedKeys( - const std::string& message, - const std::string& session_key) { + const std::string& message, const std::string& session_key) { std::string mac_deriv_message; std::string enc_deriv_message; GenerateMacContext(message, &mac_deriv_message); diff --git a/core/src/crypto_session.cpp b/core/src/crypto_session.cpp index 3576fec5..2e462a77 100644 --- a/core/src/crypto_session.cpp +++ b/core/src/crypto_session.cpp @@ -8,6 +8,7 @@ #include "crypto_session.h" #include + #include #include #include @@ -129,17 +130,16 @@ OEMCrypto_LicenseType OEMCryptoLicenseType(CdmLicenseKeyType cdm_license_type) { } OEMCryptoCipherMode ToOEMCryptoCipherMode(CdmCipherMode cipher_mode) { - return cipher_mode == kCipherModeCtr - ? OEMCrypto_CipherMode_CTR : OEMCrypto_CipherMode_CBC; + return cipher_mode == kCipherModeCtr ? OEMCrypto_CipherMode_CTR + : OEMCrypto_CipherMode_CBC; } // This maps a few common OEMCryptoResult to CdmResponseType. Many mappings // are not universal but are OEMCrypto method specific. Those will be // specified in the CryptoSession method rather than here. -CdmResponseType MapOEMCryptoResult( - OEMCryptoResult result, - CdmResponseType default_status, - const char* error_string) { +CdmResponseType MapOEMCryptoResult(OEMCryptoResult result, + CdmResponseType default_status, + const char* error_string) { if (result != OEMCrypto_SUCCESS) { LOGE("%s: error %d", error_string, result); } @@ -187,8 +187,7 @@ CryptoSession::~CryptoSession() { } CdmResponseType CryptoSession::GetProvisioningMethod( - SecurityLevel requested_security_level, - CdmClientTokenType* token_type) { + SecurityLevel requested_security_level, CdmClientTokenType* token_type) { OEMCrypto_ProvisioningMethod method; WithOecReadLock("GetProvisioningMethod", [&] { method = OEMCrypto_GetProvisioningMethod(requested_security_level); @@ -252,9 +251,7 @@ void CryptoSession::Terminate() { } if (session_count_ > 0 || !initialized_) return; OEMCryptoResult sts; - WithOecWriteLock("Terminate", [&] { - sts = OEMCrypto_Terminate(); - }); + WithOecWriteLock("Terminate", [&] { sts = OEMCrypto_Terminate(); }); if (OEMCrypto_SUCCESS != sts) { LOGE("OEMCrypto_Terminate failed: %d", sts); } @@ -283,19 +280,18 @@ CdmResponseType CryptoSession::GetTokenFromKeybox(std::string* token) { OEMCryptoResult status; WithOecReadLock("GetTokenFromKeybox", [&] { - M_TIME( - status = - OEMCrypto_GetKeyData(buf, &buf_size, requested_security_level_), - metrics_, oemcrypto_get_key_data_, status, - metrics::Pow2Bucket(buf_size)); + M_TIME(status = + OEMCrypto_GetKeyData(buf, &buf_size, requested_security_level_), + metrics_, oemcrypto_get_key_data_, status, + metrics::Pow2Bucket(buf_size)); }); if (OEMCrypto_SUCCESS == status) { token->swap(temp_buffer); } - return MapOEMCryptoResult( - status, GET_TOKEN_FROM_KEYBOX_ERROR, "GetTokenFromKeybox"); + return MapOEMCryptoResult(status, GET_TOKEN_FROM_KEYBOX_ERROR, + "GetTokenFromKeybox"); } CdmResponseType CryptoSession::GetTokenFromOemCert(std::string* token) { @@ -314,8 +310,8 @@ CdmResponseType CryptoSession::GetTokenFromOemCert(std::string* token) { size_t buf_size = temp_buffer.size(); uint8_t* buf = reinterpret_cast(&temp_buffer[0]); WithOecSessionLock("GetTokenFromOemCert", [&] { - status = OEMCrypto_GetOEMPublicCertificate(oec_session_id_, buf, - &buf_size); + status = + OEMCrypto_GetOEMPublicCertificate(oec_session_id_, buf, &buf_size); }); metrics_->oemcrypto_get_oem_public_certificate_.Increment(status); @@ -332,8 +328,8 @@ CdmResponseType CryptoSession::GetTokenFromOemCert(std::string* token) { continue; } - return MapOEMCryptoResult( - status, GET_TOKEN_FROM_OEM_CERT_ERROR, "GetTokenFromOemCert"); + return MapOEMCryptoResult(status, GET_TOKEN_FROM_OEM_CERT_ERROR, + "GetTokenFromOemCert"); } } @@ -345,7 +341,8 @@ CdmResponseType CryptoSession::GetProvisioningToken(std::string* token) { } if (!IsInitialized()) { - metrics_->crypto_session_get_token_.Increment(CRYPTO_SESSION_NOT_INITIALIZED); + metrics_->crypto_session_get_token_.Increment( + CRYPTO_SESSION_NOT_INITIALIZED); return CRYPTO_SESSION_NOT_INITIALIZED; } @@ -431,8 +428,8 @@ CdmResponseType CryptoSession::GetInternalDeviceUniqueId( if (sts == OEMCrypto_ERROR_SHORT_BUFFER) { id.resize(id_length); WithOecReadLock("GetInternalDeviceUniqueId Attempt 2", [&] { - sts = OEMCrypto_GetDeviceID(&id[0], &id_length, - requested_security_level_); + sts = + OEMCrypto_GetDeviceID(&id[0], &id_length, requested_security_level_); }); metrics_->oemcrypto_get_device_id_.Increment(sts); } @@ -451,8 +448,8 @@ CdmResponseType CryptoSession::GetInternalDeviceUniqueId( device_id->assign(reinterpret_cast(&id[0]), id_length); } - return MapOEMCryptoResult( - sts, GET_DEVICE_ID_ERROR, "GetInternalDeviceUniqueId"); + return MapOEMCryptoResult(sts, GET_DEVICE_ID_ERROR, + "GetInternalDeviceUniqueId"); } } @@ -507,9 +504,8 @@ bool CryptoSession::GetApiVersion(SecurityLevel security_level, return false; } - WithOecReadLock("GetApiVersion", [&] { - *version = OEMCrypto_APIVersion(security_level); - }); + WithOecReadLock("GetApiVersion", + [&] { *version = OEMCrypto_APIVersion(security_level); }); // Record the version into the metrics. metrics_->oemcrypto_api_version_.Record(*version); @@ -544,7 +540,7 @@ CdmResponseType CryptoSession::GetSystemIdInternal(uint32_t* system_id) { if (status != NO_ERROR) return status; - if (token.size() < 2*sizeof(uint32_t)) { + if (token.size() < 2 * sizeof(uint32_t)) { LOGE("CryptoSession::GetSystemIdInternal: Keybox token too small: %d", token.size()); return KEYBOX_TOKEN_TOO_SHORT; @@ -568,13 +564,15 @@ CdmResponseType CryptoSession::GetSystemIdInternal(uint32_t* system_id) { return NO_ERROR; - // TODO(blueeyes): Support loading the system id from a pre-provisioned - // Drm certificate. + // TODO(blueeyes): Support loading the system id from a pre-provisioned + // Drm certificate. } else if (pre_provision_token_type_ == kClientTokenDrmCert) { return NO_ERROR; } else { - LOGE("CryptoSession::GetSystemIdInternal: " - "Unsupported pre-provision token type %d", pre_provision_token_type_); + LOGE( + "CryptoSession::GetSystemIdInternal: " + "Unsupported pre-provision token type %d", + pre_provision_token_type_); return UNKNOWN_CLIENT_TOKEN_TYPE; } } @@ -647,9 +645,8 @@ CdmResponseType CryptoSession::Open(SecurityLevel requested_security_level) { if (!IsInitialized()) return UNKNOWN_ERROR; if (open_) return NO_ERROR; - CdmResponseType result = - GetProvisioningMethod(requested_security_level, - &pre_provision_token_type_); + CdmResponseType result = GetProvisioningMethod(requested_security_level, + &pre_provision_token_type_); if (result != NO_ERROR) return result; OEMCrypto_SESSION sid; @@ -661,8 +658,7 @@ CdmResponseType CryptoSession::Open(SecurityLevel requested_security_level) { if (sts != OEMCrypto_SUCCESS) { WithStaticFieldReadLock( - "Open() reporting OEMCrypto_OpenSession Failure", - [&] { + "Open() reporting OEMCrypto_OpenSession Failure", [&] { LOGE("OEMCrypto_Open failed: %d, open sessions: %ld, initialized: %d", sts, session_count_, (int)initialized_); }); @@ -757,9 +753,8 @@ void CryptoSession::Close() { OEMCryptoResult close_sts; bool update_usage_table = false; - WithOecWriteLock("Close", [&] { - close_sts = OEMCrypto_CloseSession(oec_session_id_); - }); + WithOecWriteLock( + "Close", [&] { close_sts = OEMCrypto_CloseSession(oec_session_id_); }); metrics_->oemcrypto_close_session_.Increment(close_sts); if (OEMCrypto_SUCCESS == close_sts) open_ = false; update_usage_table = update_usage_table_after_close_session_; @@ -816,9 +811,9 @@ CdmResponseType CryptoSession::LoadKeys( } LOGV("LoadKeys: id=%lu", oec_session_id_); - sts = key_session_->LoadKeys( - message, signature, mac_key_iv, mac_key, keys, provider_session_token, - &cipher_mode_, srm_requirement); + sts = key_session_->LoadKeys(message, signature, mac_key_iv, mac_key, keys, + provider_session_token, &cipher_mode_, + srm_requirement); }); if (sts != OEMCrypto_SUCCESS) { @@ -896,8 +891,7 @@ CdmResponseType CryptoSession::LoadCertificatePrivateKey( LOGV("LoadDeviceRSAKey: id=%lu", oec_session_id_); WithOecSessionLock( - "LoadCertificatePrivateKey() calling OEMCrypto_LoadDeviceRSAKey()", - [&] { + "LoadCertificatePrivateKey() calling OEMCrypto_LoadDeviceRSAKey()", [&] { M_TIME(sts = OEMCrypto_LoadDeviceRSAKey( oec_session_id_, reinterpret_cast(wrapped_key.data()), @@ -905,8 +899,8 @@ CdmResponseType CryptoSession::LoadCertificatePrivateKey( metrics_, oemcrypto_load_device_rsa_key_, sts); }); - return MapOEMCryptoResult( - sts, LOAD_DEVICE_RSA_KEY_ERROR, "LoadCertificatePrivateKey"); + return MapOEMCryptoResult(sts, LOAD_DEVICE_RSA_KEY_ERROR, + "LoadCertificatePrivateKey"); } CdmResponseType CryptoSession::RefreshKeys(const std::string& message, @@ -937,16 +931,14 @@ CdmResponseType CryptoSession::RefreshKeys(const std::string& message, if (refresh_sts == OEMCrypto_SUCCESS) return KEY_ADDED; - return MapOEMCryptoResult( - refresh_sts, REFRESH_KEYS_ERROR, "RefreshKeys"); + return MapOEMCryptoResult(refresh_sts, REFRESH_KEYS_ERROR, "RefreshKeys"); } CdmResponseType CryptoSession::SelectKey(const std::string& key_id, CdmCipherMode cipher_mode) { OEMCryptoResult sts; - WithOecSessionLock("SelectKey", [&] { - sts = key_session_->SelectKey(key_id, cipher_mode); - }); + WithOecSessionLock( + "SelectKey", [&] { sts = key_session_->SelectKey(key_id, cipher_mode); }); switch (sts) { case OEMCrypto_SUCCESS: @@ -982,12 +974,11 @@ CdmResponseType CryptoSession::SelectKey(const std::string& key_id, CdmResponseType CryptoSession::GenerateDerivedKeys(const std::string& message) { OEMCryptoResult sts; - WithOecSessionLock("GenerateDerivedKeys without session_key", [&] { - sts = key_session_->GenerateDerivedKeys(message); - }); + WithOecSessionLock("GenerateDerivedKeys without session_key", + [&] { sts = key_session_->GenerateDerivedKeys(message); }); - return MapOEMCryptoResult( - sts, GENERATE_DERIVED_KEYS_ERROR_2, "GenerateDerivedKeys"); + return MapOEMCryptoResult(sts, GENERATE_DERIVED_KEYS_ERROR_2, + "GenerateDerivedKeys"); } CdmResponseType CryptoSession::GenerateDerivedKeys( @@ -997,8 +988,8 @@ CdmResponseType CryptoSession::GenerateDerivedKeys( sts = key_session_->GenerateDerivedKeys(message, session_key); }); - return MapOEMCryptoResult( - sts, GENERATE_DERIVED_KEYS_ERROR, "GenerateDerivedKeys"); + return MapOEMCryptoResult(sts, GENERATE_DERIVED_KEYS_ERROR, + "GenerateDerivedKeys"); } CdmResponseType CryptoSession::GenerateSignature(const std::string& message, @@ -1016,15 +1007,14 @@ CdmResponseType CryptoSession::GenerateSignature(const std::string& message, // The first attempt may fail due to buffer too short for (int i = 0; i < 2; ++i) { WithOecSessionLock("GenerateSignature", [&] { - M_TIME(sts = OEMCrypto_GenerateSignature( - oec_session_id_, - reinterpret_cast(message.data()), - message.size(), - reinterpret_cast( - const_cast(signature->data())), - &length), - metrics_, oemcrypto_generate_signature_, sts, - metrics::Pow2Bucket(length)); + M_TIME( + sts = OEMCrypto_GenerateSignature( + oec_session_id_, reinterpret_cast(message.data()), + message.size(), + reinterpret_cast(const_cast(signature->data())), + &length), + metrics_, oemcrypto_generate_signature_, sts, + metrics::Pow2Bucket(length)); }); if (OEMCrypto_SUCCESS == sts) { // Trim signature buffer and done @@ -1039,8 +1029,7 @@ CdmResponseType CryptoSession::GenerateSignature(const std::string& message, signature->resize(length); } - return MapOEMCryptoResult( - sts, GENERATE_SIGNATURE_ERROR, "GenerateSignature"); + return MapOEMCryptoResult(sts, GENERATE_SIGNATURE_ERROR, "GenerateSignature"); } CdmResponseType CryptoSession::GenerateRsaSignature(const std::string& message, @@ -1059,15 +1048,14 @@ CdmResponseType CryptoSession::GenerateRsaSignature(const std::string& message, // The first attempt may fail due to buffer too short for (int i = 0; i < 2; ++i) { WithOecSessionLock("GenerateRsaSignature", [&] { - M_TIME(sts = OEMCrypto_GenerateRSASignature( - oec_session_id_, - reinterpret_cast(message.data()), - message.size(), - reinterpret_cast( - const_cast(signature->data())), - &length, kSign_RSASSA_PSS), - metrics_, oemcrypto_generate_rsa_signature_, sts, - metrics::Pow2Bucket(length)); + M_TIME( + sts = OEMCrypto_GenerateRSASignature( + oec_session_id_, reinterpret_cast(message.data()), + message.size(), + reinterpret_cast(const_cast(signature->data())), + &length, kSign_RSASSA_PSS), + metrics_, oemcrypto_generate_rsa_signature_, sts, + metrics::Pow2Bucket(length)); }); if (OEMCrypto_SUCCESS == sts) { @@ -1083,8 +1071,8 @@ CdmResponseType CryptoSession::GenerateRsaSignature(const std::string& message, signature->resize(length); } - return MapOEMCryptoResult( - sts, RSA_SIGNATURE_GENERATION_ERROR, "OEMCrypto_GenerateRSASignature"); + return MapOEMCryptoResult(sts, RSA_SIGNATURE_GENERATION_ERROR, + "OEMCrypto_GenerateRSASignature"); } CdmResponseType CryptoSession::Decrypt(const CdmDecryptionParameters& params) { @@ -1125,10 +1113,9 @@ CdmResponseType CryptoSession::Decrypt(const CdmDecryptionParameters& params) { params.subsample_flags == (OEMCrypto_FirstSubsample | OEMCrypto_LastSubsample)) { WithOecSessionLock("Decrypt() calling CopyBuffer", [&] { - M_TIME(sts = OEMCrypto_CopyBuffer(oec_session_id_, params.encrypt_buffer, - params.encrypt_length, - &buffer_descriptor, - params.subsample_flags), + M_TIME(sts = OEMCrypto_CopyBuffer( + oec_session_id_, params.encrypt_buffer, params.encrypt_length, + &buffer_descriptor, params.subsample_flags), metrics_, oemcrypto_copy_buffer_, sts, metrics::Pow2Bucket(params.encrypt_length)); }); @@ -1157,8 +1144,8 @@ CdmResponseType CryptoSession::Decrypt(const CdmDecryptionParameters& params) { } WithOecSessionLock("Decrypt() calling key_session_->Decrypt()", [&] { - sts = key_session_->Decrypt(params, buffer_descriptor, - pattern_descriptor); + sts = + key_session_->Decrypt(params, buffer_descriptor, pattern_descriptor); }); if (sts == OEMCrypto_ERROR_BUFFER_TOO_LARGE) { @@ -1232,8 +1219,7 @@ bool CryptoSession::UsageInformationSupport(SecurityLevel security_level, } CdmResponseType CryptoSession::UpdateUsageInformation() { - LOGV("CryptoSession::UpdateUsageInformation: id=%lu", - oec_session_id_); + LOGV("CryptoSession::UpdateUsageInformation: id=%lu", oec_session_id_); if (!IsInitialized()) return UNKNOWN_ERROR; if (usage_table_header_ != NULL) { @@ -1242,9 +1228,8 @@ CdmResponseType CryptoSession::UpdateUsageInformation() { } OEMCryptoResult status; - WithOecWriteLock("UpdateUsageInformation", [&] { - status = OEMCrypto_UpdateUsageTable(); - }); + WithOecWriteLock("UpdateUsageInformation", + [&] { status = OEMCrypto_UpdateUsageTable(); }); metrics_->oemcrypto_update_usage_table_.Increment(status); if (status != OEMCrypto_SUCCESS) { LOGE("CryptoSession::UpdateUsageInformation: error=%ld", status); @@ -1263,8 +1248,8 @@ CdmResponseType CryptoSession::DeactivateUsageInformation( // TODO(fredgc or rfrias): make sure oec_session_id_ is valid. OEMCryptoResult status; WithOecWriteLock("DeactivateUsageInformation", [&] { - status = OEMCrypto_DeactivateUsageEntry( - oec_session_id_, pst, provider_session_token.length()); + status = OEMCrypto_DeactivateUsageEntry(oec_session_id_, pst, + provider_session_token.length()); }); metrics_->oemcrypto_deactivate_usage_entry_.Increment(status); @@ -1303,15 +1288,15 @@ CdmResponseType CryptoSession::GenerateUsageReport( size_t usage_length = 0; OEMCryptoResult status; WithOecWriteLock("GenerateUsageReport Attempt 1", [&] { - status = OEMCrypto_ReportUsage( - oec_session_id_, pst, provider_session_token.length(), NULL, - &usage_length); + status = OEMCrypto_ReportUsage(oec_session_id_, pst, + provider_session_token.length(), NULL, + &usage_length); }); metrics_->oemcrypto_report_usage_.Increment(status); if (status != OEMCrypto_SUCCESS && status != OEMCrypto_ERROR_SHORT_BUFFER) { - return MapOEMCryptoResult( - status, GENERATE_USAGE_REPORT_ERROR, "GenerateUsageReport"); + return MapOEMCryptoResult(status, GENERATE_USAGE_REPORT_ERROR, + "GenerateUsageReport"); } std::vector buffer(usage_length); @@ -1324,8 +1309,8 @@ CdmResponseType CryptoSession::GenerateUsageReport( metrics_->oemcrypto_report_usage_.Increment(status); if (status != OEMCrypto_SUCCESS) { - return MapOEMCryptoResult( - status, GENERATE_USAGE_REPORT_ERROR, "OEMCrypto_ReportUsage"); + return MapOEMCryptoResult(status, GENERATE_USAGE_REPORT_ERROR, + "OEMCrypto_ReportUsage"); } if (usage_length != buffer.size()) { @@ -1458,9 +1443,8 @@ CdmResponseType CryptoSession::DeleteMultipleUsageInformation( CdmResponseType CryptoSession::DeleteAllUsageReports() { LOGV("DeleteAllUsageReports"); OEMCryptoResult status; - WithOecWriteLock("DeleteAllUsageReports", [&] { - status = OEMCrypto_DeleteOldUsageTable(); - }); + WithOecWriteLock("DeleteAllUsageReports", + [&] { status = OEMCrypto_DeleteOldUsageTable(); }); metrics_->oemcrypto_delete_usage_table_.Increment(status); if (OEMCrypto_SUCCESS != status) { LOGE( @@ -1489,7 +1473,7 @@ CdmResponseType CryptoSession::GenerateNonce(uint32_t* nonce) { } OEMCryptoResult result; - WithOecSessionLock("GenerateNonce", [&] { + WithOecWriteLock("GenerateNonce", [&] { result = OEMCrypto_GenerateNonce(oec_session_id_, nonce); }); metrics_->oemcrypto_generate_nonce_.Increment(result); @@ -1513,12 +1497,9 @@ bool CryptoSession::SetDestinationBufferType() { } CdmResponseType CryptoSession::RewrapCertificate( - const std::string& signed_message, - const std::string& signature, - const std::string& nonce, - const std::string& private_key, - const std::string& iv, - const std::string& wrapping_key, + const std::string& signed_message, const std::string& signature, + const std::string& nonce, const std::string& private_key, + const std::string& iv, const std::string& wrapping_key, std::string* wrapped_private_key) { LOGV("CryptoSession::RewrapCertificate, session id=%lu", oec_session_id_); @@ -1540,12 +1521,9 @@ CdmResponseType CryptoSession::RewrapCertificate( } CdmResponseType CryptoSession::RewrapDeviceRSAKey( - const std::string& message, - const std::string& signature, - const std::string& nonce, - const std::string& enc_rsa_key, - const std::string& rsa_key_iv, - std::string* wrapped_rsa_key) { + const std::string& message, const std::string& signature, + const std::string& nonce, const std::string& enc_rsa_key, + const std::string& rsa_key_iv, std::string* wrapped_rsa_key) { LOGV("CryptoSession::RewrapDeviceRSAKey, session id=%lu", oec_session_id_); const uint8_t* signed_msg = reinterpret_cast(message.data()); @@ -1573,37 +1551,33 @@ CdmResponseType CryptoSession::RewrapDeviceRSAKey( }); if (status != OEMCrypto_ERROR_SHORT_BUFFER) { - return MapOEMCryptoResult( - status, REWRAP_DEVICE_RSA_KEY_ERROR, "RewrapDeviceRSAKey"); + return MapOEMCryptoResult(status, REWRAP_DEVICE_RSA_KEY_ERROR, + "RewrapDeviceRSAKey"); } wrapped_rsa_key->resize(wrapped_rsa_key_length); WithOecSessionLock("RewrapDeviceRSAKey Attempt 2", [&] { - M_TIME(status = OEMCrypto_RewrapDeviceRSAKey( - oec_session_id_, signed_msg, message.size(), - reinterpret_cast(signature.data()), - signature.size(), msg_nonce, msg_rsa_key, enc_rsa_key.size(), - msg_rsa_key_iv, - reinterpret_cast(&(*wrapped_rsa_key)[0]), - &wrapped_rsa_key_length), - metrics_, oemcrypto_rewrap_device_rsa_key_, status); + M_TIME( + status = OEMCrypto_RewrapDeviceRSAKey( + oec_session_id_, signed_msg, message.size(), + reinterpret_cast(signature.data()), + signature.size(), msg_nonce, msg_rsa_key, enc_rsa_key.size(), + msg_rsa_key_iv, reinterpret_cast(&(*wrapped_rsa_key)[0]), + &wrapped_rsa_key_length), + metrics_, oemcrypto_rewrap_device_rsa_key_, status); }); wrapped_rsa_key->resize(wrapped_rsa_key_length); - return MapOEMCryptoResult( - status, REWRAP_DEVICE_RSA_KEY_ERROR, "RewrapDeviceRSAKey"); + return MapOEMCryptoResult(status, REWRAP_DEVICE_RSA_KEY_ERROR, + "RewrapDeviceRSAKey"); } CdmResponseType CryptoSession::RewrapDeviceRSAKey30( - const std::string& message, - const std::string& nonce, - const std::string& private_key, - const std::string& iv, - const std::string& wrapping_key, - std::string* wrapped_private_key) { - LOGV("CryptoSession::RewrapDeviceRSAKey30, session id=%lu", - oec_session_id_); + const std::string& message, const std::string& nonce, + const std::string& private_key, const std::string& iv, + const std::string& wrapping_key, std::string* wrapped_private_key) { + LOGV("CryptoSession::RewrapDeviceRSAKey30, session id=%lu", oec_session_id_); const uint8_t* signed_msg = reinterpret_cast(message.data()); const uint8_t* msg_private_key = NULL; @@ -1623,38 +1597,32 @@ CdmResponseType CryptoSession::RewrapDeviceRSAKey30( size_t wrapped_private_key_length = 0; OEMCryptoResult status; WithOecSessionLock("RewrapDeviceRSAKey30 Attempt 1", [&] { - M_TIME( - status = OEMCrypto_RewrapDeviceRSAKey30( - oec_session_id_, msg_nonce, msg_wrapping_key, wrapping_key.size(), - msg_private_key, private_key.size(), msg_iv, NULL, - &wrapped_private_key_length), - metrics_, - oemcrypto_rewrap_device_rsa_key_30_, - status); + M_TIME(status = OEMCrypto_RewrapDeviceRSAKey30( + oec_session_id_, msg_nonce, msg_wrapping_key, + wrapping_key.size(), msg_private_key, private_key.size(), msg_iv, + NULL, &wrapped_private_key_length), + metrics_, oemcrypto_rewrap_device_rsa_key_30_, status); }); if (status != OEMCrypto_ERROR_SHORT_BUFFER) { - return MapOEMCryptoResult( - status, REWRAP_DEVICE_RSA_KEY_30_ERROR, "RewrapDeviceRSAKey30"); + return MapOEMCryptoResult(status, REWRAP_DEVICE_RSA_KEY_30_ERROR, + "RewrapDeviceRSAKey30"); } wrapped_private_key->resize(wrapped_private_key_length); WithOecSessionLock("RewrapDeviceRSAKey30 Attempt 2", [&] { - M_TIME( - status = OEMCrypto_RewrapDeviceRSAKey30( - oec_session_id_, msg_nonce, msg_wrapping_key, wrapping_key.size(), - msg_private_key, private_key.size(), msg_iv, - reinterpret_cast(&(*wrapped_private_key)[0]), - &wrapped_private_key_length), - metrics_, - oemcrypto_rewrap_device_rsa_key_30_, - status); + M_TIME(status = OEMCrypto_RewrapDeviceRSAKey30( + oec_session_id_, msg_nonce, msg_wrapping_key, + wrapping_key.size(), msg_private_key, private_key.size(), msg_iv, + reinterpret_cast(&(*wrapped_private_key)[0]), + &wrapped_private_key_length), + metrics_, oemcrypto_rewrap_device_rsa_key_30_, status); }); wrapped_private_key->resize(wrapped_private_key_length); - return MapOEMCryptoResult( - status, REWRAP_DEVICE_RSA_KEY_30_ERROR, "RewrapDeviceRSAKey30"); + return MapOEMCryptoResult(status, REWRAP_DEVICE_RSA_KEY_30_ERROR, + "RewrapDeviceRSAKey30"); } CdmResponseType CryptoSession::GetHdcpCapabilities(HdcpCapability* current, @@ -1694,8 +1662,8 @@ CdmResponseType CryptoSession::GetHdcpCapabilities(SecurityLevel security_level, metrics_->oemcrypto_max_hdcp_capability_.SetError(status); } - return MapOEMCryptoResult( - status, GET_HDCP_CAPABILITY_FAILED, "GetHDCPCapability"); + return MapOEMCryptoResult(status, GET_HDCP_CAPABILITY_FAILED, + "GetHDCPCapability"); } bool CryptoSession::GetSupportedCertificateTypes( @@ -1726,17 +1694,15 @@ CdmResponseType CryptoSession::GetRandom(size_t data_length, return PARAMETER_NULL; } OEMCryptoResult sts; - WithOecReadLock("GetRandom", [&] { - sts = OEMCrypto_GetRandom(random_data, data_length); - }); + WithOecReadLock("GetRandom", + [&] { sts = OEMCrypto_GetRandom(random_data, data_length); }); metrics_->oemcrypto_get_random_.Increment(sts); return MapOEMCryptoResult(sts, RANDOM_GENERATION_ERROR, "GetRandom"); } CdmResponseType CryptoSession::GetNumberOfOpenSessions( - SecurityLevel security_level, - size_t* count) { + SecurityLevel security_level, size_t* count) { LOGV("GetNumberOfOpenSessions"); if (!IsInitialized()) { LOGW("CryptoSession::GetNumberOfOpenSessions: not initialized"); @@ -1760,13 +1726,12 @@ CdmResponseType CryptoSession::GetNumberOfOpenSessions( metrics_->oemcrypto_number_of_open_sessions_.SetError(status); } - return MapOEMCryptoResult( - status, GET_NUMBER_OF_OPEN_SESSIONS_ERROR, "GetNumberOfOpenSessions"); + return MapOEMCryptoResult(status, GET_NUMBER_OF_OPEN_SESSIONS_ERROR, + "GetNumberOfOpenSessions"); } CdmResponseType CryptoSession::GetMaxNumberOfSessions( - SecurityLevel security_level, - size_t* max) { + SecurityLevel security_level, size_t* max) { LOGV("GetMaxNumberOfSessions"); if (!IsInitialized()) { LOGW("CryptoSession::GetMaxNumberOfSessions: not initialized"); @@ -1811,21 +1776,21 @@ CdmResponseType CryptoSession::GetSrmVersion(uint16_t* srm_version) { // SRM is an optional feature. Whether it is implemented is up to the // discretion of OEMs if (status == OEMCrypto_ERROR_NOT_IMPLEMENTED) { - LOGV("CryptoSession::GetSrmVersion: OEMCrypto_GetCurrentSRMVersion not " - "implemented"); + LOGV( + "CryptoSession::GetSrmVersion: OEMCrypto_GetCurrentSRMVersion not " + "implemented"); return NOT_IMPLEMENTED_ERROR; } - return MapOEMCryptoResult( - status, GET_SRM_VERSION_ERROR, "GetCurrentSRMVersion"); + return MapOEMCryptoResult(status, GET_SRM_VERSION_ERROR, + "GetCurrentSRMVersion"); } bool CryptoSession::IsSrmUpdateSupported() { LOGV("IsSrmUpdateSupported"); if (!IsInitialized()) return false; - return WithOecReadLock("IsSrmUpdateSupported", [&] { - return OEMCrypto_IsSRMUpdateSupported(); - }); + return WithOecReadLock("IsSrmUpdateSupported", + [&] { return OEMCrypto_IsSRMUpdateSupported(); }); } CdmResponseType CryptoSession::LoadSrm(const std::string& srm) { @@ -1838,8 +1803,8 @@ CdmResponseType CryptoSession::LoadSrm(const std::string& srm) { OEMCryptoResult status; WithOecWriteLock("LoadSrm", [&] { - status = OEMCrypto_LoadSRM( - reinterpret_cast(srm.data()), srm.size()); + status = OEMCrypto_LoadSRM(reinterpret_cast(srm.data()), + srm.size()); }); return MapOEMCryptoResult(status, LOAD_SRM_ERROR, "LoadSRM"); @@ -1880,6 +1845,15 @@ bool CryptoSession::GetResourceRatingTier(SecurityLevel security_level, return true; } +bool CryptoSession::GetBuildInformation(std::string* info) { + LOGV("CryptoSession::GetBuildInformation"); + if (!open_) { + LOGW("CryptoSession::GetBuildInformation: session not open"); + return false; + } + return GetBuildInformation(requested_security_level_, info); +} + bool CryptoSession::GetBuildInformation(SecurityLevel security_level, std::string* info) { LOGV("GetBuildInformation"); @@ -1929,9 +1903,8 @@ uint32_t CryptoSession::IsDecryptHashSupported(SecurityLevel security_level) { return secure_decrypt_support; } -CdmResponseType CryptoSession::SetDecryptHash( - uint32_t frame_number, - const std::string& hash) { +CdmResponseType CryptoSession::SetDecryptHash(uint32_t frame_number, + const std::string& hash) { LOGV("SetDecryptHash"); OEMCryptoResult sts; WithOecSessionLock("SetDecryptHash", [&] { @@ -2477,9 +2450,9 @@ CdmResponseType CryptoSession::ShrinkUsageTableHeader( size_t usage_table_header_len = 0; OEMCryptoResult result; WithOecWriteLock("ShrinkUsageTableHeader Attempt 1", [&] { - result = OEMCrypto_ShrinkUsageTableHeader( - requested_security_level_, new_entry_count, NULL, - &usage_table_header_len); + result = OEMCrypto_ShrinkUsageTableHeader(requested_security_level_, + new_entry_count, NULL, + &usage_table_header_len); metrics_->oemcrypto_shrink_usage_table_header_.Increment(result); }); @@ -2513,8 +2486,8 @@ CdmResponseType CryptoSession::MoveUsageEntry(uint32_t new_entry_number) { metrics_->oemcrypto_move_entry_.Increment(result); }); - return MapOEMCryptoResult( - result, MOVE_USAGE_ENTRY_UNKNOWN_ERROR, "MoveUsageEntry"); + return MapOEMCryptoResult(result, MOVE_USAGE_ENTRY_UNKNOWN_ERROR, + "MoveUsageEntry"); } bool CryptoSession::CreateOldUsageEntry( @@ -2583,8 +2556,8 @@ CdmResponseType CryptoSession::CopyOldUsageEntry( metrics_->oemcrypto_copy_old_usage_entry_.Increment(result); }); - return MapOEMCryptoResult( - result, COPY_OLD_USAGE_ENTRY_UNKNOWN_ERROR, "CopyOldUsageEntry"); + return MapOEMCryptoResult(result, COPY_OLD_USAGE_ENTRY_UNKNOWN_ERROR, + "CopyOldUsageEntry"); } bool CryptoSession::GetAnalogOutputCapabilities(bool* can_support_output, diff --git a/core/src/device_files.cpp b/core/src/device_files.cpp index 781493f9..1d59c8e4 100644 --- a/core/src/device_files.cpp +++ b/core/src/device_files.cpp @@ -5,6 +5,7 @@ #include "device_files.h" #include + #include #include "file_store.h" @@ -31,20 +32,20 @@ using video_widevine_client::sdk::UsageTableInfo; using video_widevine_client::sdk::UsageTableInfo_UsageEntryInfo; using video_widevine_client::sdk:: UsageTableInfo_UsageEntryInfo_UsageEntryStorage_LICENSE; -using video_widevine_client::sdk:: - UsageTableInfo_UsageEntryInfo_UsageEntryStorage_USAGE_INFO; using video_widevine_client::sdk:: UsageTableInfo_UsageEntryInfo_UsageEntryStorage_UNKNOWN; +using video_widevine_client::sdk:: + UsageTableInfo_UsageEntryInfo_UsageEntryStorage_USAGE_INFO; -using video_widevine::SignedDrmDeviceCertificate; using video_widevine::DrmDeviceCertificate; +using video_widevine::SignedDrmDeviceCertificate; #define RETURN_FALSE_IF_NULL(PARAM) \ -if (PARAM == nullptr) { \ - LOGE("|PARAM| not provided"); \ - *result = kParameterNull; \ - return false; \ -} + if (PARAM == nullptr) { \ + LOGE("|PARAM| not provided"); \ + *result = kParameterNull; \ + return false; \ + } namespace { @@ -107,8 +108,8 @@ bool DeviceFiles::StoreCertificate(const std::string& certificate, std::string serialized_file; file.SerializeToString(&serialized_file); - return - StoreFileWithHash(GetCertificateFileName(), serialized_file) == kNoError; + return StoreFileWithHash(GetCertificateFileName(), serialized_file) == + kNoError; } bool DeviceFiles::RetrieveCertificate(std::string* certificate, @@ -161,8 +162,9 @@ bool DeviceFiles::ExtractDeviceInfo(const std::string& device_certificate, SignedDrmDeviceCertificate signed_drm_device_certificate; if (!signed_drm_device_certificate.ParseFromString(device_certificate) || !signed_drm_device_certificate.has_drm_certificate()) { - LOGE("DeviceFiles::ExtractDeviceInfo: fails parsing signed drm device " - "certificate."); + LOGE( + "DeviceFiles::ExtractDeviceInfo: fails parsing signed drm device " + "certificate."); return false; } DrmDeviceCertificate drm_device_certificate; @@ -170,8 +172,9 @@ bool DeviceFiles::ExtractDeviceInfo(const std::string& device_certificate, signed_drm_device_certificate.drm_certificate()) || (drm_device_certificate.type() != video_widevine::DrmDeviceCertificate::DRM_USER_DEVICE)) { - LOGE("DeviceFiles::ExtractDeviceInfo: fails parsing drm device " - "certificate message."); + LOGE( + "DeviceFiles::ExtractDeviceInfo: fails parsing drm device " + "certificate message."); return false; } if (serial_number != NULL) { @@ -209,10 +212,8 @@ bool DeviceFiles::StoreLicense( const CdmKeyResponse& license_renewal, const std::string& release_server_url, int64_t playback_start_time, int64_t last_playback_time, int64_t grace_period_end_time, - const CdmAppParameterMap& app_parameters, - const CdmUsageEntry& usage_entry, - const uint32_t usage_entry_number, - ResponseType* result) { + const CdmAppParameterMap& app_parameters, const CdmUsageEntry& usage_entry, + const uint32_t usage_entry_number, ResponseType* result) { if (result == nullptr) { LOGE("DeviceFiles::StoreLicense: |result| not provided"); return false; @@ -492,8 +493,7 @@ bool DeviceFiles::StoreUsageInfo(const std::string& provider_session_token, } bool DeviceFiles::ListUsageIds( - const std::string& app_id, - std::vector* ksids, + const std::string& app_id, std::vector* ksids, std::vector* provider_session_tokens) { if (!initialized_) { LOGW("DeviceFiles::ListUsageIds: not initialized"); @@ -718,12 +718,9 @@ bool DeviceFiles::RetrieveUsageInfo(const std::string& usage_info_file_name, } bool DeviceFiles::RetrieveUsageInfoByKeySetId( - const std::string& usage_info_file_name, - const std::string& key_set_id, - std::string* provider_session_token, - CdmKeyMessage* license_request, - CdmKeyResponse* license_response, - std::string* usage_entry, + const std::string& usage_info_file_name, const std::string& key_set_id, + std::string* provider_session_token, CdmKeyMessage* license_request, + CdmKeyResponse* license_response, std::string* usage_entry, uint32_t* usage_entry_number) { if (!initialized_) { LOGW("DeviceFiles::RetrieveUsageInfoByKeySetId: not initialized"); @@ -798,7 +795,6 @@ bool DeviceFiles::UpdateUsageInfo(const std::string& usage_info_file_name, return false; } - if (RetrieveHashedFile(usage_info_file_name, &file) != kNoError) { LOGW("DeviceFiles::UpdateUsageInfo: Unable to retrieve file"); return false; @@ -818,8 +814,8 @@ bool DeviceFiles::UpdateUsageInfo(const std::string& usage_info_file_name, std::string serialized_file; file.SerializeToString(&serialized_file); - return - StoreFileWithHash(usage_info_file_name, serialized_file) == kNoError; + return StoreFileWithHash(usage_info_file_name, serialized_file) == + kNoError; } } @@ -860,7 +856,7 @@ bool DeviceFiles::RetrieveUsageInfo(const std::string& usage_info_file_name, (*usage_data)[i].key_set_id = file.usage_info().sessions(i).key_set_id(); (*usage_data)[i].usage_entry = file.usage_info().sessions(i).usage_entry(); (*usage_data)[i].usage_entry_number = - file.usage_info().sessions(i).usage_entry_number(); + file.usage_info().sessions(i).usage_entry_number(); } return true; @@ -928,8 +924,7 @@ bool DeviceFiles::ListUsageInfoFiles( std::string* name = &filenames[i]; std::size_t pos_prefix = name->find(kUsageInfoFileNamePrefix); std::size_t pos_suffix = name->find(kUsageInfoFileNameExt); - if (pos_prefix == std::string::npos || - pos_suffix == std::string::npos) { + if (pos_prefix == std::string::npos || pos_suffix == std::string::npos) { // Skip this file - extension does not match continue; } @@ -1080,8 +1075,8 @@ bool DeviceFiles::StoreUsageTableInfo( std::string serialized_file; file.SerializeToString(&serialized_file); - return - StoreFileWithHash(GetUsageTableFileName(), serialized_file) == kNoError; + return StoreFileWithHash(GetUsageTableFileName(), serialized_file) == + kNoError; } bool DeviceFiles::RetrieveUsageTableInfo( @@ -1160,8 +1155,7 @@ bool DeviceFiles::DeleteUsageTableInfo() { } DeviceFiles::ResponseType DeviceFiles::StoreFileWithHash( - const std::string& name, - const std::string& serialized_file) { + const std::string& name, const std::string& serialized_file) { std::string hash = Sha256Hash(serialized_file); // Fill in hashed file data @@ -1176,8 +1170,7 @@ DeviceFiles::ResponseType DeviceFiles::StoreFileWithHash( } DeviceFiles::ResponseType DeviceFiles::StoreFileRaw( - const std::string& name, - const std::string& serialized_file) { + const std::string& name, const std::string& serialized_file) { std::string path; if (!Properties::GetDeviceFilesBasePath(security_level_, &path)) { LOGW("DeviceFiles::StoreFileRaw: Unable to get base path"); @@ -1335,9 +1328,7 @@ std::string DeviceFiles::GetCertificateFileName() { return kCertificateFileName; } -std::string DeviceFiles::GetUsageTableFileName() { - return kUsageTableFileName; -} +std::string DeviceFiles::GetUsageTableFileName() { return kUsageTableFileName; } std::string DeviceFiles::GetHlsAttributesFileNameExtension() { return kHlsAttributesFileNameExt; diff --git a/core/src/entitlement_key_session.cpp b/core/src/entitlement_key_session.cpp index 504a6b05..82eea314 100644 --- a/core/src/entitlement_key_session.cpp +++ b/core/src/entitlement_key_session.cpp @@ -8,7 +8,6 @@ #include "crypto_session.h" #include "log.h" - namespace wvcdm { EntitlementKeySession::EntitlementKeySession(CryptoSessionId oec_session_id, metrics::CryptoMetrics* metrics) @@ -51,8 +50,8 @@ OEMCryptoResult EntitlementKeySession::SelectKey(const std::string& key_id, } CryptoKey entitled_content_key = entitled_keys_[key_id]; - if (current_loaded_content_keys_[entitled_content_key - .entitlement_key_id()] != key_id) { + if (current_loaded_content_keys_[entitled_content_key.entitlement_key_id()] != + key_id) { // Before the key can be selected, it must be loaded under its associated // entitlement key. This could, in theory, be done ahead of time during // LoadEntitledContentKeys(), but OEMCrypto v14 only supports one content @@ -75,11 +74,8 @@ OEMCryptoResult EntitlementKeySession::SelectKey(const std::string& key_id, current_loaded_content_keys_[entitled_content_key.entitlement_key_id()] = key_id; - - return ContentKeySession::SelectKey(key_id, cipher_mode); - } else { - return OEMCrypto_SUCCESS; } + return ContentKeySession::SelectKey(key_id, cipher_mode); } OEMCrypto_EntitledContentKeyObject EntitlementKeySession::MakeOecEntitledKey( diff --git a/core/src/initialization_data.cpp b/core/src/initialization_data.cpp index 662c353c..8969583f 100644 --- a/core/src/initialization_data.cpp +++ b/core/src/initialization_data.cpp @@ -5,7 +5,8 @@ #include "initialization_data.h" #include -#include + +#include #include "buffer_reader.h" #include "cdm_engine.h" @@ -56,6 +57,7 @@ InitializationData::InitializationData(const std::string& type, is_hls_(false), is_webm_(false), is_audio_(false), + contains_entitled_keys_(false), hls_method_(kHlsMethodNone) { if (type == ISO_BMFF_VIDEO_MIME_TYPE || type == ISO_BMFF_AUDIO_MIME_TYPE || type == CENC_INIT_DATA_FORMAT) { @@ -125,19 +127,20 @@ bool InitializationData::SelectWidevinePssh(const CdmInitData& init_data, return false; } - // If there are multiple PSSHs to choose from and this device prefers - // entitlements, find the first |ENTITLED_KEY| PSSH, if present, and - // select it. - if (prefer_entitlements && pssh_payloads.size() > 1) { + // If this device prefers entitlements, search through available PSSHs. + // If present, select the first |ENTITLED_KEY| PSSH. + if (prefer_entitlements && !pssh_payloads.empty()) { for (size_t i = 0; i < pssh_payloads.size(); ++i) { WidevinePsshData pssh; if (!pssh.ParseFromString(pssh_payloads[i])) { LOGE( "InitializationData::SelectWidevinePssh: Unable to parse PSSH data " - "%lu into a protobuf.", i); + "%lu into a protobuf.", + i); continue; } if (pssh.type() == WidevinePsshData_Type_ENTITLED_KEY) { + contains_entitled_keys_ = true; *output = pssh_payloads[i]; return true; } @@ -163,8 +166,8 @@ bool InitializationData::SelectWidevinePssh(const CdmInitData& init_data, // 4 byte size of PSSH data, exclusive. (N) // N byte PSSH data. -bool InitializationData::ExtractWidevinePsshs( - const CdmInitData& init_data, std::vector* psshs) { +bool InitializationData::ExtractWidevinePsshs(const CdmInitData& init_data, + std::vector* psshs) { if (psshs == NULL) { LOGE("InitializationData::ExtractWidevinePsshs: NULL psshs parameter"); return false; @@ -172,7 +175,8 @@ bool InitializationData::ExtractWidevinePsshs( psshs->clear(); psshs->reserve(2); // We expect 1 or 2 Widevine PSSHs - const uint8_t* data_start = reinterpret_cast(init_data.data()); + const uint8_t* data_start = + reinterpret_cast(init_data.data()); BufferReader reader(data_start, init_data.length()); while (!reader.IsEOF()) { @@ -242,8 +246,9 @@ bool InitializationData::ExtractWidevinePsshs( // Checks if the given reader contains a Widevine PSSH. If so, it extracts the // data from the box. Returns true if a PSSH was extracted, false if there was // an error or if the data is not a Widevine PSSH. -bool InitializationData::ExtractWidevinePsshData( - const uint8_t* data, size_t length, CdmInitData* output) { +bool InitializationData::ExtractWidevinePsshData(const uint8_t* data, + size_t length, + CdmInitData* output) { BufferReader reader(data, length); // Read the 32-bit size only so we can check if we need to expect a 64-bit @@ -266,8 +271,7 @@ bool InitializationData::ExtractWidevinePsshData( return false; } if (memcmp(&atom_type[0], "pssh", 4) != 0) { - LOGV( - "InitializationData::ExtractWidevinePsshData: Atom type is not PSSH."); + LOGV("InitializationData::ExtractWidevinePsshData: Atom type is not PSSH."); return false; } @@ -312,9 +316,8 @@ bool InitializationData::ExtractWidevinePsshData( "system ID."); return false; } - if (memcmp(&system_id[0], - kWidevineSystemId, - sizeof(kWidevineSystemId)) != 0) { + if (memcmp(&system_id[0], kWidevineSystemId, sizeof(kWidevineSystemId)) != + 0) { LOGV( "InitializationData::ExtractWidevinePsshData: Found a non-Widevine " "PSSH."); @@ -721,13 +724,7 @@ bool InitializationData::DetectEntitlementPreference( if (oec_version_string.empty()) { return false; } - - uint32_t oec_version_int = 0; - std::istringstream parse_int; - parse_int.str(oec_version_string); - parse_int >> oec_version_int; - - return oec_version_int >= 14; + return std::stoul(oec_version_string) >= 14; } } // namespace wvcdm diff --git a/core/src/license.cpp b/core/src/license.cpp index 1dbdd755..d7dcd761 100644 --- a/core/src/license.cpp +++ b/core/src/license.cpp @@ -411,9 +411,8 @@ CdmResponseType CdmLicense::PrepareKeyUpdateRequest( license_request.set_request_time(clock_->GetCurrentTime()); if (renew_with_client_id_) { - CdmResponseType status = - PrepareClientId(app_parameters, provider_client_token_, - &license_request); + CdmResponseType status = PrepareClientId( + app_parameters, provider_client_token_, &license_request); if (NO_ERROR != status) return status; } @@ -567,9 +566,8 @@ CdmResponseType CdmLicense::HandleKeyResponse( LOGE("CdmLicense::HandleKeyResponse: no session keys present"); return SESSION_KEYS_NOT_FOUND; } - CdmResponseType status = - crypto_session_->GenerateDerivedKeys(key_request_, - signed_response.session_key()); + CdmResponseType status = crypto_session_->GenerateDerivedKeys( + key_request_, signed_response.session_key()); if (status != NO_ERROR) return status; @@ -726,10 +724,9 @@ CdmResponseType CdmLicense::HandleKeyUpdateResponse( std::vector key_array = ExtractContentKeys(license); - CdmResponseType status = - crypto_session_->RefreshKeys(signed_response.msg(), - signed_response.signature(), - key_array.size(), &key_array[0]); + CdmResponseType status = crypto_session_->RefreshKeys( + signed_response.msg(), signed_response.signature(), key_array.size(), + &key_array[0]); if (status == KEY_ADDED) { policy_engine_->UpdateLicense(license); @@ -983,8 +980,7 @@ CdmResponseType CdmLicense::HandleKeyErrorResponse( CdmResponseType CdmLicense::PrepareClientId( const CdmAppParameterMap& app_parameters, - const std::string& provider_client_token, - LicenseRequest* license_request) { + const std::string& provider_client_token, LicenseRequest* license_request) { wvcdm::ClientIdentification id; CdmResponseType status = id.Init(client_token_, device_id_, crypto_session_); if (status != NO_ERROR) return status; diff --git a/core/src/license_key_status.cpp b/core/src/license_key_status.cpp index b2485a07..ec8240dc 100644 --- a/core/src/license_key_status.cpp +++ b/core/src/license_key_status.cpp @@ -11,11 +11,11 @@ namespace { // License protocol aliases -typedef ::video_widevine::License::KeyContainer KeyContainer; -typedef KeyContainer::OutputProtection OutputProtection; -typedef KeyContainer::VideoResolutionConstraint VideoResolutionConstraint; -typedef ::google::protobuf::RepeatedPtrField - ConstraintList; +using KeyContainer = ::video_widevine::License::KeyContainer; +using OutputProtection = KeyContainer::OutputProtection; +using VideoResolutionConstraint = KeyContainer::VideoResolutionConstraint; +using ConstraintList = + ::google::protobuf::RepeatedPtrField; // Map the HDCP protection associated with a key in the license to // an equivalent OEMCrypto HDCP protection level @@ -49,7 +49,7 @@ wvcdm::CryptoSession::HdcpCapability ProtobufHdcpToOemCryptoHdcp( // specified resolution, or null if none match VideoResolutionConstraint* GetConstraintForRes( uint32_t res, ConstraintList& constraints_from_key) { - typedef ConstraintList::pointer_iterator Iterator; + using Iterator = ConstraintList::pointer_iterator; for (Iterator i = constraints_from_key.pointer_begin(); i != constraints_from_key.pointer_end(); ++i) { VideoResolutionConstraint* constraint = *i; @@ -152,6 +152,16 @@ bool LicenseKeys::MeetsConstraints(const KeyId& key_id) { } } +bool LicenseKeys::MeetsSecurityLevelConstraints(const KeyId& key_id) { + if (key_statuses_.count(key_id) > 0) { + return key_statuses_[key_id]->MeetsSecurityLevelConstraints(); + } else { + // If a Key ID is unknown to us, we don't know of any constraints for it, + // so never block decryption. + return true; + } +} + void LicenseKeys::ApplyConstraints( uint32_t new_resolution, CryptoSession::HdcpCapability new_hdcp_level) { for (LicenseKeyStatusIterator i = key_statuses_.begin(); @@ -168,7 +178,7 @@ void LicenseKeys::SetFromLicense(const video_widevine::License& license) { key.type() == KeyContainer::OPERATOR_SESSION || key.type() == KeyContainer::ENTITLEMENT)) { const KeyId& key_id = key.id(); - key_statuses_[key_id] = new LicenseKeyStatus(key); + key_statuses_[key_id] = new LicenseKeyStatus(key, security_level_); } } } @@ -190,23 +200,26 @@ void LicenseKeys::SetEntitledKeys( } } -LicenseKeyStatus::LicenseKeyStatus(const KeyContainer& key) +LicenseKeyStatus::LicenseKeyStatus(const KeyContainer& key, + const CdmSecurityLevel security_level) : is_content_key_(false), key_status_(kKeyStatusInternalError), meets_constraints_(true), + meets_security_level_constraints_(true), default_hdcp_level_(HDCP_NONE) { allowed_usage_.Clear(); constraints_.Clear(); if (key.type() == KeyContainer::CONTENT || key.type() == KeyContainer::ENTITLEMENT) { - ParseContentKey(key); + ParseContentKey(key, security_level); } else if (key.type() == KeyContainer::OPERATOR_SESSION) { ParseOperatorSessionKey(key); } } -void LicenseKeyStatus::ParseContentKey(const KeyContainer& key) { +void LicenseKeyStatus::ParseContentKey(const KeyContainer& key, + CdmSecurityLevel security_level) { is_content_key_ = true; if (key.has_level() && ((key.level() == KeyContainer::HW_SECURE_DECODE) || (key.level() == KeyContainer::HW_SECURE_ALL))) { @@ -238,8 +251,34 @@ void LicenseKeyStatus::ParseContentKey(const KeyContainer& key) { allowed_usage_.key_security_level_ = kKeySecurityLevelUnknown; break; } + + switch (security_level) { + case kSecurityLevelL1: + meets_security_level_constraints_ = true; + break; + case kSecurityLevelL2: + case kSecurityLevelL3: + switch (key.level()) { + case KeyContainer::SW_SECURE_CRYPTO: + case KeyContainer::SW_SECURE_DECODE: + meets_security_level_constraints_ = true; + break; + case KeyContainer::HW_SECURE_CRYPTO: + meets_security_level_constraints_ = + security_level == kSecurityLevelL2; + break; + default: + meets_security_level_constraints_ = false; + break; + } + break; + default: + meets_security_level_constraints_ = false; + break; + } } else { allowed_usage_.key_security_level_ = kKeySecurityLevelUnset; + meets_security_level_constraints_ = true; } allowed_usage_.SetValid(); @@ -301,7 +340,7 @@ bool LicenseKeyStatus::ApplyStatusChange(CdmKeyStatus new_status, } CdmKeyStatus updated_status = new_status; if (updated_status == kKeyStatusUsable) { - if (!MeetsConstraints()) { + if (!MeetsConstraints() || !MeetsSecurityLevelConstraints()) { updated_status = kKeyStatusOutputNotAllowed; } } diff --git a/core/src/oemcrypto_adapter_static.cpp b/core/src/oemcrypto_adapter_static.cpp index c0787096..a664d5af 100644 --- a/core/src/oemcrypto_adapter_static.cpp +++ b/core/src/oemcrypto_adapter_static.cpp @@ -100,23 +100,15 @@ OEMCryptoResult OEMCrypto_ShrinkUsageTableHeader(SecurityLevel level, header_buffer_length); } -OEMCryptoResult OEMCrypto_CreateOldUsageEntry(SecurityLevel level, - uint64_t time_since_license_received, - uint64_t time_since_first_decrypt, - uint64_t time_since_last_decrypt, - OEMCrypto_Usage_Entry_Status status, - uint8_t *server_mac_key, - uint8_t *client_mac_key, - const uint8_t* pst, - size_t pst_length) { - return ::OEMCrypto_CreateOldUsageEntry(time_since_license_received, - time_since_first_decrypt, - time_since_last_decrypt, - status, - server_mac_key, - client_mac_key, - pst, - pst_length); +OEMCryptoResult OEMCrypto_CreateOldUsageEntry( + SecurityLevel level, uint64_t time_since_license_received, + uint64_t time_since_first_decrypt, uint64_t time_since_last_decrypt, + OEMCrypto_Usage_Entry_Status status, uint8_t* server_mac_key, + uint8_t* client_mac_key, const uint8_t* pst, size_t pst_length) { + return ::OEMCrypto_CreateOldUsageEntry( + time_since_license_received, time_since_first_decrypt, + time_since_last_decrypt, status, server_mac_key, client_mac_key, pst, + pst_length); } uint32_t OEMCrypto_GetAnalogOutputFlags(SecurityLevel) { diff --git a/core/src/oemcrypto_adapter_static_v10.cpp b/core/src/oemcrypto_adapter_static_v10.cpp index 74c614f3..ccd0f73b 100644 --- a/core/src/oemcrypto_adapter_static_v10.cpp +++ b/core/src/oemcrypto_adapter_static_v10.cpp @@ -39,16 +39,14 @@ extern "C" OEMCryptoResult OEMCrypto_GetHDCPCapability( if (current == NULL) return OEMCrypto_ERROR_UNKNOWN_FAILURE; if (maximum == NULL) return OEMCrypto_ERROR_UNKNOWN_FAILURE; uint8_t current_byte, maximum_byte; - OEMCryptoResult sts = OEMCrypto_GetHDCPCapability_V9(¤t_byte, - &maximum_byte); + OEMCryptoResult sts = + OEMCrypto_GetHDCPCapability_V9(¤t_byte, &maximum_byte); *current = static_cast(current_byte); *maximum = static_cast(maximum_byte); return sts; } -extern "C" bool OEMCrypto_IsAntiRollbackHwPresent() { - return false; -} +extern "C" bool OEMCrypto_IsAntiRollbackHwPresent() { return false; } extern "C" OEMCryptoResult OEMCrypto_GetNumberOfOpenSessions(size_t* count) { return OEMCrypto_ERROR_NOT_IMPLEMENTED; @@ -58,7 +56,7 @@ extern "C" OEMCryptoResult OEMCrypto_GetMaxNumberOfSessions(size_t* max) { return OEMCrypto_ERROR_NOT_IMPLEMENTED; } -extern "C" OEMCryptoResult OEMCrypto_ForceDeleteUsageEntry( - const uint8_t* pst, size_t pst_length) { +extern "C" OEMCryptoResult OEMCrypto_ForceDeleteUsageEntry(const uint8_t* pst, + size_t pst_length) { return OEMCrypto_ERROR_NOT_IMPLEMENTED; } diff --git a/core/src/oemcrypto_adapter_static_v11.cpp b/core/src/oemcrypto_adapter_static_v11.cpp index 33b07882..8d1da40a 100644 --- a/core/src/oemcrypto_adapter_static_v11.cpp +++ b/core/src/oemcrypto_adapter_static_v11.cpp @@ -18,13 +18,13 @@ extern "C" OEMCryptoResult OEMCrypto_DecryptCTR_V10( const OEMCrypto_DestBufferDesc* out_buffer, uint8_t subsample_flags); typedef struct { - const uint8_t* key_id; - size_t key_id_length; - const uint8_t* key_data_iv; - const uint8_t* key_data; - size_t key_data_length; - const uint8_t* key_control_iv; - const uint8_t* key_control; + const uint8_t* key_id; + size_t key_id_length; + const uint8_t* key_data_iv; + const uint8_t* key_data; + size_t key_data_length; + const uint8_t* key_control_iv; + const uint8_t* key_control; } OEMCrypto_KeyObject_V9; extern "C" OEMCryptoResult OEMCrypto_LoadKeys_V9_or_V10( diff --git a/core/src/oemcrypto_adapter_static_v12.cpp b/core/src/oemcrypto_adapter_static_v12.cpp index 7736866f..ed4ab081 100644 --- a/core/src/oemcrypto_adapter_static_v12.cpp +++ b/core/src/oemcrypto_adapter_static_v12.cpp @@ -24,9 +24,8 @@ extern "C" OEMCryptoResult OEMCrypto_GetOEMPublicCertificate( extern "C" OEMCryptoResult OEMCrypto_RewrapDeviceRSAKey30( OEMCrypto_SESSION, const uint32_t* /* nonce */, const uint8_t* /* encrypted_message_key */, - size_t /* encrypted_message_key_length */, - const uint8_t* /* enc_rsa_key */, size_t /* enc_rsa_key_length */, - const uint8_t* /* enc_rsa_key_iv */, uint8_t* /* wrapped_rsa_key */, - size_t* /* wrapped_rsa_key_length */) { + size_t /* encrypted_message_key_length */, const uint8_t* /* enc_rsa_key */, + size_t /* enc_rsa_key_length */, const uint8_t* /* enc_rsa_key_iv */, + uint8_t* /* wrapped_rsa_key */, size_t* /* wrapped_rsa_key_length */) { return OEMCrypto_ERROR_NOT_IMPLEMENTED; } diff --git a/core/src/oemcrypto_adapter_static_v13.cpp b/core/src/oemcrypto_adapter_static_v13.cpp index a14645aa..41aaa00d 100644 --- a/core/src/oemcrypto_adapter_static_v13.cpp +++ b/core/src/oemcrypto_adapter_static_v13.cpp @@ -20,9 +20,7 @@ uint32_t OEMCrypto_SupportedCertificates() { } // SRM support is not available before v13. -bool OEMCrypto_IsSRMUpdateSupported() { - return false; -} +bool OEMCrypto_IsSRMUpdateSupported() { return false; } OEMCryptoResult OEMCrypto_GetCurrentSRMVersion(uint16_t*) { return OEMCrypto_ERROR_NOT_IMPLEMENTED; @@ -54,8 +52,8 @@ OEMCryptoResult OEMCrypto_LoadUsageEntry(OEMCrypto_SESSION, uint32_t, return OEMCrypto_ERROR_NOT_IMPLEMENTED; } -OEMCryptoResult OEMCrypto_UpdateUsageEntry(OEMCrypto_SESSION, uint8_t*, - size_t*, uint8_t*, size_t*) { +OEMCryptoResult OEMCrypto_UpdateUsageEntry(OEMCrypto_SESSION, uint8_t*, size_t*, + uint8_t*, size_t*) { return OEMCrypto_ERROR_NOT_IMPLEMENTED; } @@ -73,23 +71,23 @@ OEMCryptoResult OEMCrypto_LoadKeys( const uint8_t* enc_mac_keys_iv, const uint8_t* enc_mac_keys, size_t num_keys, const OEMCrypto_KeyObject* key_array, const uint8_t* pst, size_t pst_length, const uint8_t* /* srm_requirement */) { - return OEMCrypto_LoadKeys_V11_or_V12( - session, message, message_length, signature, signature_length, - enc_mac_keys_iv, enc_mac_keys, num_keys, key_array, pst, pst_length); + session, message, message_length, signature, signature_length, + enc_mac_keys_iv, enc_mac_keys, num_keys, key_array, pst, pst_length); } -OEMCryptoResult OEMCrypto_CreateOldUsageEntry( - uint64_t, uint64_t, uint64_t, OEMCrypto_Usage_Entry_Status, - uint8_t*, uint8_t*, const uint8_t*, size_t) { +OEMCryptoResult OEMCrypto_CreateOldUsageEntry(uint64_t, uint64_t, uint64_t, + OEMCrypto_Usage_Entry_Status, + uint8_t*, uint8_t*, + const uint8_t*, size_t) { return OEMCrypto_ERROR_NOT_IMPLEMENTED; } // NOTE: OEMCrypto_DeleteOldUsageTable() uses OEMCrypto_DeleteUsageTable() // entry point. -OEMCryptoResult OEMCrypto_CopyOldUsageEntry( - OEMCrypto_SESSION, const uint8_t*pst, size_t) { +OEMCryptoResult OEMCrypto_CopyOldUsageEntry(OEMCrypto_SESSION, + const uint8_t* pst, size_t) { return OEMCrypto_ERROR_NOT_IMPLEMENTED; } diff --git a/core/src/oemcrypto_adapter_static_v14.cpp b/core/src/oemcrypto_adapter_static_v14.cpp index 5416f3b6..bc763347 100644 --- a/core/src/oemcrypto_adapter_static_v14.cpp +++ b/core/src/oemcrypto_adapter_static_v14.cpp @@ -18,12 +18,12 @@ OEMCryptoResult OEMCrypto_LoadKeys_V13( OEMCrypto_SESSION session, const uint8_t* message, size_t message_length, const uint8_t* signature, size_t signature_length, const uint8_t* enc_mac_keys_iv, const uint8_t* enc_mac_keys, - size_t num_keys, const OEMCrypto_KeyObject_V13* key_array, const uint8_t* pst, - size_t pst_length, const uint8_t* srm_requirement); + size_t num_keys, const OEMCrypto_KeyObject_V13* key_array, + const uint8_t* pst, size_t pst_length, const uint8_t* srm_requirement); OEMCryptoResult OEMCrypto_SelectKey_V13(OEMCrypto_SESSION session, - const uint8_t* content_key_id, - size_t content_key_id_length); + const uint8_t* content_key_id, + size_t content_key_id_length); OEMCryptoResult OEMCrypto_LoadTestKeybox_V13(); @@ -34,14 +34,13 @@ OEMCryptoResult OEMCrypto_LoadKeys( size_t num_keys, const OEMCrypto_KeyObject* key_array, const uint8_t* pst, size_t pst_length, const uint8_t* srm_requirement, OEMCrypto_LicenseType license_type) { - if (license_type != OEMCrypto_ContentLicense) { return OEMCrypto_ERROR_NOT_IMPLEMENTED; } - return OEMCrypto_LoadKeys_V13( - session, message, message_length, signature, signature_length, - enc_mac_keys_iv, enc_mac_keys, num_keys, key_array, pst, pst_length, - srm_requirement); + return OEMCrypto_LoadKeys_V13(session, message, message_length, signature, + signature_length, enc_mac_keys_iv, enc_mac_keys, + num_keys, key_array, pst, pst_length, + srm_requirement); } OEMCryptoResult OEMCrypto_SelectKey(OEMCrypto_SESSION session, @@ -52,8 +51,7 @@ OEMCryptoResult OEMCrypto_SelectKey(OEMCrypto_SESSION session, content_key_id_length); } -OEMCryptoResult OEMCrypto_LoadTestKeybox(const uint8_t *buffer, - size_t length) { +OEMCryptoResult OEMCrypto_LoadTestKeybox(const uint8_t* buffer, size_t length) { return OEMCrypto_LoadTestKeybox_V13(); } @@ -68,8 +66,7 @@ uint32_t OEMCrypto_GetAnalogOutputFlags() { } OEMCryptoResult OEMCrypto_LoadEntitledContentKeys( - OEMCrypto_SESSION session, - size_t num_keys, + OEMCrypto_SESSION session, size_t num_keys, const OEMCrypto_EntitledContentKeyObject* key_array) { return OEMCrypto_ERROR_NOT_IMPLEMENTED; } diff --git a/core/src/oemcrypto_adapter_static_v15.cpp b/core/src/oemcrypto_adapter_static_v15.cpp index ca28ee58..9f005750 100644 --- a/core/src/oemcrypto_adapter_static_v15.cpp +++ b/core/src/oemcrypto_adapter_static_v15.cpp @@ -9,11 +9,10 @@ // Defines APIs introduced in newer version (v15) that are not available in v14. // This allows an older oemcrypto implementation to be linked with CDM. -#include "oemcrypto_adapter.h" - #include #include "OEMCryptoCENC.h" +#include "oemcrypto_adapter.h" // Used for backwards compatibility. If the length is 0, this denotes a NULL // pointer for OEMCrypto v15. diff --git a/core/src/oemcrypto_adapter_static_v9.cpp b/core/src/oemcrypto_adapter_static_v9.cpp index 87c8a488..c4ffb571 100644 --- a/core/src/oemcrypto_adapter_static_v9.cpp +++ b/core/src/oemcrypto_adapter_static_v9.cpp @@ -54,8 +54,8 @@ extern "C" OEMCryptoResult OEMCrypto_UpdateUsageTable() { return OEMCrypto_ERROR_NOT_IMPLEMENTED; } -extern "C" OEMCryptoResult OEMCrypto_DeactivateUsageEntry_V12(const uint8_t* pst, - size_t pst_length) { +extern "C" OEMCryptoResult OEMCrypto_DeactivateUsageEntry_V12( + const uint8_t* pst, size_t pst_length) { return OEMCrypto_ERROR_NOT_IMPLEMENTED; } @@ -74,6 +74,6 @@ extern "C" OEMCryptoResult OEMCrypto_DeleteUsageEntry( return OEMCrypto_ERROR_NOT_IMPLEMENTED; } -extern "C" OEMCryptoResult OEMCrypto_DeleteOldUsageTable(){ +extern "C" OEMCryptoResult OEMCrypto_DeleteOldUsageTable() { return OEMCrypto_ERROR_NOT_IMPLEMENTED; } diff --git a/core/src/policy_engine.cpp b/core/src/policy_engine.cpp index c78cacb8..54c281d5 100644 --- a/core/src/policy_engine.cpp +++ b/core/src/policy_engine.cpp @@ -5,7 +5,8 @@ #include "policy_engine.h" #include -#include + +#include #include "clock.h" #include "log.h" @@ -40,7 +41,7 @@ PolicyEngine::PolicyEngine(CdmSessionId session_id, last_recorded_current_time_(0), session_id_(session_id), event_listener_(event_listener), - license_keys_(new LicenseKeys), + license_keys_(new LicenseKeys(crypto_session->GetSecurityLevel())), clock_(new Clock) { InitDevice(crypto_session); } @@ -226,7 +227,7 @@ void PolicyEngine::UpdateLicense(const License& license) { NotifyKeysChange(kKeyStatusUsable); } else { license_state_ = kLicenseStatePending; - NotifyKeysChange(kKeyStatusPending); + NotifyKeysChange(kKeyStatusUsableInFuture); } NotifyExpirationUpdate(current_time); } @@ -253,8 +254,7 @@ bool PolicyEngine::BeginDecryption() { default: return false; } - } - else { + } else { return true; } } @@ -271,7 +271,6 @@ void PolicyEngine::NotifySessionExpiration() { } CdmResponseType PolicyEngine::Query(CdmQueryMap* query_response) { - std::stringstream ss; int64_t current_time = GetCurrentTime(); if (license_state_ == kLicenseStateInitial) { @@ -288,11 +287,10 @@ CdmResponseType PolicyEngine::Query(CdmQueryMap* query_response) { policy_.can_persist() ? QUERY_VALUE_TRUE : QUERY_VALUE_FALSE; (*query_response)[QUERY_KEY_RENEW_ALLOWED] = policy_.can_renew() ? QUERY_VALUE_TRUE : QUERY_VALUE_FALSE; - ss << GetLicenseOrRentalDurationRemaining(current_time); - (*query_response)[QUERY_KEY_LICENSE_DURATION_REMAINING] = ss.str(); - ss.str(""); - ss << GetPlaybackDurationRemaining(current_time); - (*query_response)[QUERY_KEY_PLAYBACK_DURATION_REMAINING] = ss.str(); + (*query_response)[QUERY_KEY_LICENSE_DURATION_REMAINING] = + std::to_string(GetLicenseOrRentalDurationRemaining(current_time)); + (*query_response)[QUERY_KEY_PLAYBACK_DURATION_REMAINING] = + std::to_string(GetPlaybackDurationRemaining(current_time)); (*query_response)[QUERY_KEY_RENEWAL_SERVER_URL] = policy_.renewal_server_url(); @@ -311,30 +309,8 @@ CdmResponseType PolicyEngine::QueryKeyAllowedUsage( return KEY_NOT_FOUND_1; } -bool PolicyEngine::CanUseKeyForSecurityLevel( - const KeyId& key_id, - CdmSecurityLevel security_level) { - - if (security_level == kSecurityLevelL1) return true; - - CdmKeyAllowedUsage key_usage; - CdmResponseType status = QueryKeyAllowedUsage(key_id, &key_usage); - - if (status != NO_ERROR) return false; - - // L1 has already been addressed so verify that L2/3 are allowed - switch (key_usage.key_security_level_) { - case kKeySecurityLevelUnset: - return true; - case kSoftwareSecureCrypto: - case kSoftwareSecureDecode: - return security_level == kSecurityLevelL2 || - security_level == kSecurityLevelL3; - case kHardwareSecureCrypto: - return security_level == kSecurityLevelL2; - default: - return false; - } +bool PolicyEngine::CanUseKeyForSecurityLevel(const KeyId& key_id) { + return license_keys_->MeetsSecurityLevelConstraints(key_id); } bool PolicyEngine::GetSecondsSinceStarted(int64_t* seconds_since_started) { @@ -525,4 +501,8 @@ int64_t PolicyEngine::GetCurrentTime() { void PolicyEngine::set_clock(Clock* clock) { clock_.reset(clock); } +void PolicyEngine::SetSecurityLevelForTest(CdmSecurityLevel security_level) { + license_keys_->SetSecurityLevelForTest(security_level); +} + } // namespace wvcdm diff --git a/core/src/privacy_crypto_apple.cpp b/core/src/privacy_crypto_apple.cpp index d498668c..36d6e77b 100644 --- a/core/src/privacy_crypto_apple.cpp +++ b/core/src/privacy_crypto_apple.cpp @@ -11,24 +11,27 @@ // files, setting privacy_crypto_impl to "apple" with use this file rather // than the openssl version. +// clang-format off #include "privacy_crypto.h" +// clang-format on + +#include #include #include #include -#include -#include #include +#include -#include "string_conversions.h" #include "log.h" +#include "string_conversions.h" namespace { const int kPssSaltLength = 20; const int kOaepMinPadding = 2 * CC_SHA1_DIGEST_LENGTH + 1; -template +template struct CFDeleter { void operator()(T arg) { if (arg) { @@ -37,7 +40,7 @@ struct CFDeleter { } }; -template +template using CF = std::unique_ptr::type, CFDeleter>; CF ImportPublicKey(const std::string& key) { @@ -47,8 +50,8 @@ CF ImportPublicKey(const std::string& key) { CF key_size( CFNumberCreate(nullptr, kCFNumberIntType, &key_size_raw)); - CF attributes(CFDictionaryCreateMutable( - nullptr, 0, nullptr, nullptr)); + CF attributes( + CFDictionaryCreateMutable(nullptr, 0, nullptr, nullptr)); CFDictionarySetValue(attributes.get(), kSecAttrKeyType, kSecAttrKeyTypeRSA); CFDictionarySetValue(attributes.get(), kSecAttrKeySizeInBits, key_size.get()); CFDictionarySetValue(attributes.get(), kSecAttrKeyClass, @@ -60,14 +63,14 @@ CF ImportPublicKey(const std::string& key) { // Apply a custom mask generation function (MGF) using the hash function SHA1, // this is from OpenSSL. -void ApplyMGF1_SHA1(uint8_t *output, size_t outputLength, - const uint8_t* seed, size_t seedLength) { +void ApplyMGF1_SHA1(uint8_t* output, size_t outputLength, const uint8_t* seed, + size_t seedLength) { size_t outputIndex = 0; for (int i = 0; outputIndex < outputLength; i++) { uint8_t extra[4]; extra[0] = (uint8_t)((i >> 24) & 0xFF); extra[1] = (uint8_t)((i >> 16) & 0xFF); - extra[2] = (uint8_t)((i >> 8) & 0xFF); + extra[2] = (uint8_t)((i >> 8) & 0xFF); extra[3] = (uint8_t)(i & 0xFF); CC_SHA1_CTX ctx; @@ -87,10 +90,9 @@ void ApplyMGF1_SHA1(uint8_t *output, size_t outputLength, } std::string ApplyOAEPPadding(const std::string& messageStr, size_t rsaSize) { - if (messageStr.length() > rsaSize - kOaepMinPadding ) { + if (messageStr.length() > rsaSize - kOaepMinPadding) { LOGE("RsaPublicKey::Encrypt: message too large to be encrypted (actual %d", - " max allowed %d)", messageStr.size(), - rsaSize - kOaepMinPadding ); + " max allowed %d)", messageStr.size(), rsaSize - kOaepMinPadding); return ""; } @@ -107,13 +109,13 @@ std::string ApplyOAEPPadding(const std::string& messageStr, size_t rsaSize) { ret.resize(rsaSize); size_t messageLength = messageStr.length(); size_t paddingLength = rsaSize - messageLength; - const uint8_t *message = reinterpret_cast(messageStr.data()); - uint8_t *result = reinterpret_cast(&ret[0]); - uint8_t *seed = result + 1; - uint8_t *db = result + CC_SHA1_DIGEST_LENGTH + 1; + const uint8_t* message = reinterpret_cast(messageStr.data()); + uint8_t* result = reinterpret_cast(&ret[0]); + uint8_t* seed = result + 1; + uint8_t* db = result + CC_SHA1_DIGEST_LENGTH + 1; // Initialize db and message - CC_SHA1(NULL, 0, db); // Hash of empty string. + CC_SHA1(NULL, 0, db); // Hash of empty string. result[rsaSize - messageLength - 1] = 0x1; memcpy(result + paddingLength, message, messageLength); @@ -141,8 +143,8 @@ std::string ApplyOAEPPadding(const std::string& messageStr, size_t rsaSize) { return ret; } -bool PSSVerify(const uint8_t *message, size_t messageLength, - const uint8_t *encodedMessage, size_t encodedMessageLength) { +bool PSSVerify(const uint8_t* message, size_t messageLength, + const uint8_t* encodedMessage, size_t encodedMessageLength) { // https://tools.ietf.org/html/rfc3447#section-9.1.2 // // M' @@ -169,9 +171,9 @@ bool PSSVerify(const uint8_t *message, size_t messageLength, return false; } - const uint8_t *maskedDb = encodedMessage; + const uint8_t* maskedDb = encodedMessage; size_t dbLength = encodedMessageLength - CC_SHA1_DIGEST_LENGTH - 1; - const uint8_t *H = maskedDb + dbLength; + const uint8_t* H = maskedDb + dbLength; // Decode db std::vector dbMask; @@ -192,14 +194,14 @@ bool PSSVerify(const uint8_t *message, size_t messageLength, return false; } - uint8_t *salt = dbMask.data() + (dbLength - kPssSaltLength); + uint8_t* salt = dbMask.data() + (dbLength - kPssSaltLength); uint8_t mHash[CC_SHA1_DIGEST_LENGTH]; CC_SHA1(message, messageLength, mHash); // Create our version of the message data (M') std::vector dataVec; dataVec.resize(8 + CC_SHA1_DIGEST_LENGTH + kPssSaltLength); - uint8_t *data = dataVec.data(); + uint8_t* data = dataVec.data(); memcpy(data + 8, mHash, CC_SHA1_DIGEST_LENGTH); memcpy(data + 8 + CC_SHA1_DIGEST_LENGTH, salt, kPssSaltLength); @@ -234,9 +236,10 @@ bool AesCbcKey::Encrypt(const std::string& in, std::string* out, std::string temp; temp.resize(in.length() + kCCBlockSizeAES128); size_t length; - CCCryptorStatus result = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, - kCCOptionPKCS7Padding, key_.c_str(), key_.length(), iv->c_str(), - in.c_str(), in.length(), &temp[0], temp.size(), &length); + CCCryptorStatus result = + CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, + key_.c_str(), key_.length(), iv->c_str(), in.c_str(), in.length(), + &temp[0], temp.size(), &length); if (result != kCCSuccess) { LOGE("AesCbcKey::Encrypt: Encryption failure: %d", result); @@ -277,10 +280,10 @@ bool RsaPublicKey::Encrypt(const std::string& clear_message, size_t size = paddedMessage.length(); std::string buffer; buffer.resize(size); - OSStatus status = SecKeyEncrypt(key.get(), kSecPaddingNone, + OSStatus status = SecKeyEncrypt( + key.get(), kSecPaddingNone, reinterpret_cast(paddedMessage.c_str()), - paddedMessage.length(), - reinterpret_cast(&buffer[0]), &size); + paddedMessage.length(), reinterpret_cast(&buffer[0]), &size); if (status != errSecSuccess) { LOGE("RsaPublicKey::Encrypt: Unable to encrypt data %d", status); return false; @@ -307,20 +310,19 @@ bool RsaPublicKey::VerifySignature(const std::string& message, std::vector buffer; buffer.resize(signature.length()); size_t size = buffer.size(); - OSStatus status = SecKeyEncrypt(key.get(), kSecPaddingNone, - reinterpret_cast(signature.c_str()), - signature.length(), - buffer.data(), &size); + OSStatus status = + SecKeyEncrypt(key.get(), kSecPaddingNone, + reinterpret_cast(signature.c_str()), + signature.length(), buffer.data(), &size); if (status != errSecSuccess) { LOGE("RsaPublicKey::VerifySignature: Unable to decrypt signature %d", - status); + status); return false; } // Verify the signature if (!PSSVerify(reinterpret_cast(message.c_str()), - message.length(), - buffer.data(), buffer.size())) { + message.length(), buffer.data(), buffer.size())) { LOGE("RsaPublicKey::VerifySignature: Unable to verify signature %d", status); return false; @@ -328,7 +330,6 @@ bool RsaPublicKey::VerifySignature(const std::string& message, return true; } - bool ExtractExtensionValueFromCertificate(const std::string& cert, const std::string& extension_oid, size_t cert_index, uint32_t* value) { diff --git a/core/src/privacy_crypto_boringssl.cpp b/core/src/privacy_crypto_boringssl.cpp index 5fb83e2a..ec9b58b1 100644 --- a/core/src/privacy_crypto_boringssl.cpp +++ b/core/src/privacy_crypto_boringssl.cpp @@ -7,7 +7,9 @@ // for signature verification and encryption and decryption. // +// clang-format off #include "privacy_crypto.h" +// clang-format on #include #include @@ -68,7 +70,7 @@ class boringssl_ptr { CORE_DISALLOW_COPY_AND_ASSIGN(boringssl_ptr); }; -void DeleteX509Stack(STACK_OF(X509)* stack) { +void DeleteX509Stack(STACK_OF(X509) * stack) { sk_X509_pop_free(stack, X509_free); } @@ -224,17 +226,18 @@ bool RsaPublicKey::Encrypt(const std::string& clear_message, return true; } -// LogBoringSSLError is a callback from BoringSSL which is called with each error -// in the thread's error queue. -static int LogBoringSSLError(const char* msg, size_t /* len */, void* /* ctx */) { +// LogBoringSSLError is a callback from BoringSSL which is called with each +// error in the thread's error queue. +static int LogBoringSSLError(const char* msg, size_t /* len */, + void* /* ctx */) { LOGE(" %s", msg); return 1; } -static bool VerifyPSSSignature(EVP_PKEY *pkey, const std::string &message, - const std::string &signature) { +static bool VerifyPSSSignature(EVP_PKEY* pkey, const std::string& message, + const std::string& signature) { EVP_MD_CTX* evp_md_ctx = EVP_MD_CTX_new(); - EVP_PKEY_CTX *pctx = NULL; + EVP_PKEY_CTX* pctx = NULL; if (EVP_DigestVerifyInit(evp_md_ctx, &pctx, EVP_sha1(), NULL /* no ENGINE */, pkey) != 1) { @@ -242,8 +245,8 @@ static bool VerifyPSSSignature(EVP_PKEY *pkey, const std::string &message, goto err; } - if (EVP_PKEY_CTX_set_signature_md(pctx, - const_cast(EVP_sha1())) != 1) { + if (EVP_PKEY_CTX_set_signature_md(pctx, const_cast(EVP_sha1())) != + 1) { LOGE("EVP_PKEY_CTX_set_signature_md failed in VerifyPSSSignature"); goto err; } @@ -264,8 +267,9 @@ static bool VerifyPSSSignature(EVP_PKEY *pkey, const std::string &message, } if (EVP_DigestVerifyFinal( - evp_md_ctx, const_cast( - reinterpret_cast(signature.data())), + evp_md_ctx, + const_cast( + reinterpret_cast(signature.data())), signature.size()) != 1) { LOGE( "EVP_DigestVerifyFinal failed in VerifyPSSSignature. (Probably a bad " @@ -273,7 +277,7 @@ static bool VerifyPSSSignature(EVP_PKEY *pkey, const std::string &message, goto err; } - EVP_MD_CTX_free(evp_md_ctx); + EVP_MD_CTX_free(evp_md_ctx); return true; err: @@ -297,7 +301,7 @@ bool RsaPublicKey::VerifySignature(const std::string& message, // Error already logged by GetKey. return false; } - EVP_PKEY *pkey = EVP_PKEY_new(); + EVP_PKEY* pkey = EVP_PKEY_new(); if (pkey == NULL) { LOGE("RsaPublicKey::VerifySignature: EVP_PKEY allocation failed"); FreeKey(rsa_key); @@ -322,7 +326,6 @@ bool RsaPublicKey::VerifySignature(const std::string& message, return true; } - bool ExtractExtensionValueFromCertificate(const std::string& cert, const std::string& extension_oid, size_t cert_index, uint32_t* value) { @@ -330,16 +333,18 @@ bool ExtractExtensionValueFromCertificate(const std::string& cert, const boringssl_ptr x509_stack( sk_X509_new_null()); if (x509_stack.get() == NULL) { - LOGE("ExtractExtensionValueFromCertificate: " - "Unable to allocate X509 Stack."); + LOGE( + "ExtractExtensionValueFromCertificate: " + "Unable to allocate X509 Stack."); return false; } CBS pkcs7; CBS_init(&pkcs7, reinterpret_cast(cert.data()), cert.size()); if (!PKCS7_get_certificates(x509_stack.get(), &pkcs7)) { - LOGE("ExtractExtensionValueFromCertificate: " - "Error getting certificate chain."); + LOGE( + "ExtractExtensionValueFromCertificate: " + "Error getting certificate chain."); return false; } @@ -347,16 +352,18 @@ bool ExtractExtensionValueFromCertificate(const std::string& cert, // Find the desired certificate from the stack. if (sk_X509_num(certs) <= cert_index) { - LOGE("ExtractExtensionValueFromCertificate: " - "Expected at least %zu certificates in chain, got %d", - cert_index + 1, sk_X509_num(certs)); + LOGE( + "ExtractExtensionValueFromCertificate: " + "Expected at least %zu certificates in chain, got %d", + cert_index + 1, sk_X509_num(certs)); return false; } X509* const intermediate_cert = sk_X509_value(certs, cert_index); if (!intermediate_cert) { - LOGE("ExtractExtensionValueFromCertificate: " - "Unable to get intermediate cert."); + LOGE( + "ExtractExtensionValueFromCertificate: " + "Unable to get intermediate cert."); return false; } @@ -365,8 +372,10 @@ bool ExtractExtensionValueFromCertificate(const std::string& cert, for (int i = 0; i < extension_count; ++i) { X509_EXTENSION* const extension = X509_get_ext(intermediate_cert, i); if (!extension) { - LOGE("ExtractExtensionValueFromCertificate: " - "Unable to get cert extension %d", i); + LOGE( + "ExtractExtensionValueFromCertificate: " + "Unable to get cert extension %d", + i); continue; } @@ -378,31 +387,35 @@ bool ExtractExtensionValueFromCertificate(const std::string& cert, ASN1_OCTET_STRING* const octet_str = X509_EXTENSION_get_data(extension); if (!octet_str) { - LOGE("ExtractExtensionValueFromCertificate: " - "Unable to get data of extension."); + LOGE( + "ExtractExtensionValueFromCertificate: " + "Unable to get data of extension."); return false; } const unsigned char* data = octet_str->data; if (!data) { - LOGE("ExtractExtensionValueFromCertificate: " - "Null data in extension."); + LOGE( + "ExtractExtensionValueFromCertificate: " + "Null data in extension."); return false; } ASN1_INTEGER* const asn1_integer = d2i_ASN1_INTEGER(NULL, &data, octet_str->length); if (!asn1_integer) { - LOGE("ExtractExtensionValueFromCertificate: " - "Unable to decode data in extension."); + LOGE( + "ExtractExtensionValueFromCertificate: " + "Unable to decode data in extension."); return false; } const long system_id_long = ASN1_INTEGER_get(asn1_integer); ASN1_INTEGER_free(asn1_integer); if (system_id_long == -1) { - LOGE("ExtractExtensionValueFromCertificate: " - "Unable to decode ASN integer in extension."); + LOGE( + "ExtractExtensionValueFromCertificate: " + "Unable to decode ASN integer in extension."); return false; } diff --git a/core/src/privacy_crypto_dummy.cpp b/core/src/privacy_crypto_dummy.cpp index a5f89f7a..dda72439 100644 --- a/core/src/privacy_crypto_dummy.cpp +++ b/core/src/privacy_crypto_dummy.cpp @@ -7,18 +7,17 @@ // can't tolerate BoringSSL or OpenSSL as a dependency. // +#include "log.h" #include "privacy_crypto.h" -#include "log.h" - #ifdef __APPLE__ -# include -# define SHA256 CC_SHA256 -# define SHA256_DIGEST_LENGTH CC_SHA256_DIGEST_LENGTH -# define MD5 CC_MD5 -# define MD5_DIGEST_LENGTH CC_MD5_DIGEST_LENGTH +#include +#define SHA256 CC_SHA256 +#define SHA256_DIGEST_LENGTH CC_SHA256_DIGEST_LENGTH +#define MD5 CC_MD5 +#define MD5_DIGEST_LENGTH CC_MD5_DIGEST_LENGTH #else -# error "No hash algorithm known for this platform." +#error "No hash algorithm known for this platform." #endif namespace wvcdm { @@ -50,7 +49,6 @@ bool RsaPublicKey::VerifySignature(const std::string& message, return false; } - bool ExtractExtensionValueFromCertificate(const std::string& cert, const std::string& extension_oid, size_t cert_index, uint32_t* value) { diff --git a/core/src/properties.cpp b/core/src/properties.cpp index e6f685c3..d49a7e03 100644 --- a/core/src/properties.cpp +++ b/core/src/properties.cpp @@ -2,8 +2,9 @@ // source code may only be used and distributed under the Widevine Master // License Agreement. -#include "log.h" #include "properties.h" + +#include "log.h" #include "wv_cdm_constants.h" namespace { @@ -18,17 +19,18 @@ bool Properties::oem_crypto_use_fifo_; bool Properties::oem_crypto_use_userspace_buffers_; bool Properties::provisioning_messages_are_binary_; bool Properties::allow_service_certificate_requests_; +bool Properties::device_files_is_a_real_filesystem_; std::unique_ptr Properties::session_property_set_; -bool Properties::AddSessionPropertySet( - const CdmSessionId& session_id, CdmClientPropertySet* property_set) { +bool Properties::AddSessionPropertySet(const CdmSessionId& session_id, + CdmClientPropertySet* property_set) { if (NULL == session_property_set_.get()) { return false; } std::pair result = session_property_set_->insert( - std::pair( - session_id, property_set)); + std::pair(session_id, + property_set)); return result.second; } @@ -75,8 +77,7 @@ bool Properties::GetServiceCertificate(const CdmSessionId& session_id, bool Properties::SetServiceCertificate(const CdmSessionId& session_id, const std::string& service_certificate) { - CdmClientPropertySet* property_set = - GetCdmClientPropertySet(session_id); + CdmClientPropertySet* property_set = GetCdmClientPropertySet(session_id); if (property_set == NULL) { return false; } diff --git a/core/src/service_certificate.cpp b/core/src/service_certificate.cpp index e839e674..b4db2981 100644 --- a/core/src/service_certificate.cpp +++ b/core/src/service_certificate.cpp @@ -16,6 +16,8 @@ namespace { // Root certificate for all Google/Widevine certificates. I.e. all service // certificates and DRM certificates are signed by this cert, or have this cert // as the root of a signing chain. + +// clang-format off static const unsigned char kRootCertForProd[] = { 0x0a, 0x9c, 0x03, 0x08, 0x00, 0x12, 0x01, 0x00, 0x18, 0xdd, 0x94, 0x88, 0x8b, 0x05, 0x22, 0x8e, @@ -119,6 +121,7 @@ static const unsigned char kRootCertForProd[] = { 0xa2, 0xe6, 0x80, 0x74, 0x55, 0x06, 0x49, 0xd5, 0x02, 0x0c }; +// clang-format on } // namespace @@ -228,23 +231,22 @@ CdmResponseType ServiceCertificate::EncryptClientId( std::string iv(KEY_IV_SIZE, 0); std::string key(SERVICE_KEY_SIZE, 0); - CdmResponseType status = - crypto_session->GetRandom(key.size(), - reinterpret_cast(&key[0])); + CdmResponseType status = crypto_session->GetRandom( + key.size(), reinterpret_cast(&key[0])); if (status != NO_ERROR) { LOGE("ServiceCertificate::EncryptClientId: GetRandom error: %d", status); - return status == RANDOM_GENERATION_ERROR ? - CLIENT_ID_GENERATE_RANDOM_ERROR : status; + return status == RANDOM_GENERATION_ERROR ? CLIENT_ID_GENERATE_RANDOM_ERROR + : status; } - status = crypto_session->GetRandom(iv.size(), - reinterpret_cast(&iv[0])); + status = + crypto_session->GetRandom(iv.size(), reinterpret_cast(&iv[0])); if (status != NO_ERROR) { LOGE("ServiceCertificate::EncryptClientId: GetRandom error: %d", status); - return status == RANDOM_GENERATION_ERROR ? - CLIENT_ID_GENERATE_RANDOM_ERROR : status; + return status == RANDOM_GENERATION_ERROR ? CLIENT_ID_GENERATE_RANDOM_ERROR + : status; } std::string id, enc_id, enc_key; clear_client_id->SerializeToString(&id); @@ -254,8 +256,7 @@ CdmResponseType ServiceCertificate::EncryptClientId( if (!aes.Encrypt(id, &enc_id, &iv)) return CLIENT_ID_AES_ENCRYPT_ERROR; CdmResponseType encrypt_result = EncryptRsaOaep(key, &enc_key); - if (encrypt_result != NO_ERROR) - return encrypt_result; + if (encrypt_result != NO_ERROR) return encrypt_result; encrypted_client_id->set_encrypted_client_id_iv(iv); encrypted_client_id->set_encrypted_privacy_key(enc_key); @@ -274,8 +275,8 @@ bool ServiceCertificate::GetRequest(CdmKeyMessage* request) { return true; } -CdmResponseType ServiceCertificate::ParseResponse( - const std::string& response, std::string* certificate) { +CdmResponseType ServiceCertificate::ParseResponse(const std::string& response, + std::string* certificate) { if (response.empty()) { LOGE("ServiceCertificate::ParseResponse: empty response"); return EMPTY_RESPONSE_ERROR_1; @@ -312,6 +313,4 @@ CdmResponseType ServiceCertificate::ParseResponse( return NO_ERROR; } - - } // namespace wvcdm diff --git a/core/src/usage_table_header.cpp b/core/src/usage_table_header.cpp index 1fe88e92..3f4430bb 100644 --- a/core/src/usage_table_header.cpp +++ b/core/src/usage_table_header.cpp @@ -21,7 +21,7 @@ std::string kOldUsageEntryServerMacKey(wvcdm::MAC_KEY_SIZE, 0); std::string kOldUsageEntryClientMacKey(wvcdm::MAC_KEY_SIZE, 0); std::string kOldUsageEntryPoviderSessionToken = "nahZ6achSheiqua3TohQuei0ahwohv"; -} +} // namespace namespace wvcdm { @@ -65,7 +65,7 @@ bool UsageTableHeader::Init(CdmSecurityLevel security_level, if (metrics == NULL) metrics = &alternate_crypto_metrics_; if (file_handle_->RetrieveUsageTableInfo(&usage_table_header_, - &usage_entry_info_)) { + &usage_entry_info_)) { LOGI("UsageTableHeader::Init: number of usage entries: %d", usage_entry_info_.size()); status = crypto_session->LoadUsageTableHeader(usage_table_header_); @@ -93,17 +93,17 @@ bool UsageTableHeader::Init(CdmSecurityLevel security_level, result = local_crypto_session->Open(requested_security_level_); if (result == NO_ERROR) { - result = AddEntry(local_crypto_session, true, - kDummyKeySetId, kEmptyString, - &temporary_usage_entry_number); + result = AddEntry(local_crypto_session, true, kDummyKeySetId, + kEmptyString, &temporary_usage_entry_number); } } if (result == NO_ERROR) { - result = DeleteEntry(temporary_usage_entry_number, - file_handle_.get(), metrics); + result = DeleteEntry(temporary_usage_entry_number, file_handle_.get(), + metrics); } if (result != NO_ERROR) { - LOGE("UsageTableHeader::Init: Unable to create/delete new entry. " + LOGE( + "UsageTableHeader::Init: Unable to create/delete new entry. " "Clear usage entries, security level: %d, usage entries: %d", security_level, usage_entry_info_.size()); status = result; @@ -150,12 +150,10 @@ CdmResponseType UsageTableHeader::AddEntry( // If usage entry creation fails due to insufficient resources, release a // random entry and try again. - for (uint32_t retry_count = 0; - retry_count < kMaxCryptoRetries && - status == INSUFFICIENT_CRYPTO_RESOURCES_3; + for (uint32_t retry_count = 0; retry_count < kMaxCryptoRetries && + status == INSUFFICIENT_CRYPTO_RESOURCES_3; ++retry_count) { - int64_t entry_number_to_delete = - GetRandomInRange(usage_entry_info_.size()); + int64_t entry_number_to_delete = GetRandomInRange(usage_entry_info_.size()); if (entry_number_to_delete < 0) break; DeleteEntry(entry_number_to_delete, file_handle_.get(), metrics); @@ -222,9 +220,8 @@ CdmResponseType UsageTableHeader::LoadEntry(CryptoSession* crypto_session, // If loading a usage entry fails due to insufficient resources, release a // random entry different from |usage_entry_number| and try again. If there // are no more entries to release, we fail. - for (uint32_t retry_count = 0; - retry_count < kMaxCryptoRetries && - status == INSUFFICIENT_CRYPTO_RESOURCES_3; + for (uint32_t retry_count = 0; retry_count < kMaxCryptoRetries && + status == INSUFFICIENT_CRYPTO_RESOURCES_3; ++retry_count) { // Get a random entry from the other entries. int64_t entry_number_to_delete = GetRandomInRangeWithExclusion( @@ -257,8 +254,10 @@ CdmResponseType UsageTableHeader::DeleteEntry(uint32_t usage_entry_number, usage_entry_number); std::unique_lock auto_lock(usage_table_header_lock_); if (usage_entry_number >= usage_entry_info_.size()) { - LOGE("UsageTableHeader::DeleteEntry: usage entry number %d larger than " - "usage entry size %d", usage_entry_number, usage_entry_info_.size()); + LOGE( + "UsageTableHeader::DeleteEntry: usage entry number %d larger than " + "usage entry size %d", + usage_entry_number, usage_entry_info_.size()); return USAGE_INVALID_PARAMETERS_1; } @@ -510,8 +509,8 @@ CdmResponseType UsageTableHeader::Shrink( if (usage_entry_info_.size() < number_of_usage_entries_to_delete) { LOGW( "UsageTableHeader::Shrink: cannot delete %d entries when usage entry " - "table size is %d", number_of_usage_entries_to_delete, - usage_entry_info_.size()); + "table size is %d", + number_of_usage_entries_to_delete, usage_entry_info_.size()); return NO_ERROR; } @@ -581,7 +580,8 @@ bool UsageTableHeader::UpgradeLicensesFromUsageTable( &usage_entry_number, &sub_error_code)) { LOGW( "UsageTableHeader::UpgradeLicensesFromUsageTable: Failed to " - "retrieve license, %d", sub_error_code); + "retrieve license, %d", + sub_error_code); continue; } @@ -634,7 +634,8 @@ bool UsageTableHeader::UpgradeLicensesFromUsageTable( app_parameters, usage_entry, usage_entry_number, &sub_error_code)) { LOGE( "UsageTableHeader::UpgradeLicensesFromUsageTable: Failed to store " - "license, %d", sub_error_code); + "license, %d", + sub_error_code); continue; } } @@ -737,8 +738,7 @@ int64_t UsageTableHeader::GetRandomInRange(size_t upper_bound_exclusive) { int64_t UsageTableHeader::GetRandomInRangeWithExclusion( size_t upper_bound_exclusive, size_t exclude) { - if ((upper_bound_exclusive <= 1) || - (exclude >= upper_bound_exclusive)) { + if ((upper_bound_exclusive <= 1) || (exclude >= upper_bound_exclusive)) { LOGE( "upper_bound_exclusive must be > 1 and exclude must be < " "upper_bound_exclusive."); @@ -752,13 +752,10 @@ int64_t UsageTableHeader::GetRandomInRangeWithExclusion( // TODO(fredgc): remove when b/65730828 is addressed bool UsageTableHeader::CreateDummyOldUsageEntry(CryptoSession* crypto_session) { return crypto_session->CreateOldUsageEntry( - kOldUsageEntryTimeSinceLicenseReceived, - kOldUsageEntryTimeSinceFirstDecrypt, - kOldUsageEntryTimeSinceLastDecrypt, - CryptoSession::kUsageDurationsInvalid, - kOldUsageEntryServerMacKey, - kOldUsageEntryClientMacKey, - kOldUsageEntryPoviderSessionToken); + kOldUsageEntryTimeSinceLicenseReceived, + kOldUsageEntryTimeSinceFirstDecrypt, kOldUsageEntryTimeSinceLastDecrypt, + CryptoSession::kUsageDurationsInvalid, kOldUsageEntryServerMacKey, + kOldUsageEntryClientMacKey, kOldUsageEntryPoviderSessionToken); } // Test only method. @@ -766,9 +763,10 @@ void UsageTableHeader::DeleteEntryForTest(uint32_t usage_entry_number) { LOGV("UsageTableHeader::DeleteEntryForTest: usage_entry_number: %d", usage_entry_number); if (usage_entry_number >= usage_entry_info_.size()) { - LOGE("UsageTableHeader::DeleteEntryForTest: usage entry number %d larger " - "than usage entry size %d", usage_entry_number, - usage_entry_info_.size()); + LOGE( + "UsageTableHeader::DeleteEntryForTest: usage entry number %d larger " + "than usage entry size %d", + usage_entry_number, usage_entry_info_.size()); return; } // Move last entry into deleted location and shrink usage entries diff --git a/core/test/cdm_session_unittest.cpp b/core/test/cdm_session_unittest.cpp index 6633bf43..23efa9e6 100644 --- a/core/test/cdm_session_unittest.cpp +++ b/core/test/cdm_session_unittest.cpp @@ -19,6 +19,7 @@ #include "wv_cdm_constants.h" using ::testing::_; +using ::testing::DoAll; using ::testing::Eq; using ::testing::Invoke; using ::testing::NiceMock; @@ -152,7 +153,8 @@ class MockCryptoSession : public TestCryptoSession { class MockPolicyEngine : public PolicyEngine { public: - MockPolicyEngine() : PolicyEngine("mock_session_id", NULL, NULL) {} + MockPolicyEngine(CryptoSession* crypto_session) + : PolicyEngine("mock_session_id", NULL, crypto_session) {} // Leaving a place-holder for when PolicyEngine methods need to be mocked }; @@ -181,7 +183,7 @@ class CdmSessionTest : public WvCdmTestBase { cdm_session_->set_license_parser(license_parser_); crypto_session_ = new NiceMock(&crypto_metrics_); cdm_session_->set_crypto_session(crypto_session_); - policy_engine_ = new MockPolicyEngine(); + policy_engine_ = new MockPolicyEngine(crypto_session_); cdm_session_->set_policy_engine(policy_engine_); file_handle_ = new MockDeviceFiles(); cdm_session_->set_file_handle(file_handle_); diff --git a/core/test/generic_crypto_unittest.cpp b/core/test/generic_crypto_unittest.cpp index 0c882974..2a51ab9e 100644 --- a/core/test/generic_crypto_unittest.cpp +++ b/core/test/generic_crypto_unittest.cpp @@ -29,9 +29,9 @@ namespace wvcdm { -class WvGenericOperationsTest : public WvCdmTestBase { +class WvGenericCryptoTest : public WvCdmTestBase { public: - WvGenericOperationsTest() + WvGenericCryptoTest() : dummy_engine_metrics_(new metrics::EngineMetrics), cdm_engine_(&file_system_, dummy_engine_metrics_), holder_(&cdm_engine_) {} @@ -95,11 +95,11 @@ class WvGenericOperationsTest : public WvCdmTestBase { std::string iv_; }; -TEST_F(WvGenericOperationsTest, LoadSpecialKeys) { +TEST_F(WvGenericCryptoTest, LoadSpecialKeys) { holder_.SignAndLoadLicense(); } -TEST_F(WvGenericOperationsTest, GenericEncryptGood) { +TEST_F(WvGenericCryptoTest, GenericEncryptGood) { CdmResponseType cdm_sts; std::string encrypted = Aes128CbcEncrypt(ency_key_, in_vector_, iv_vector_); std::string out_buffer; @@ -113,7 +113,7 @@ TEST_F(WvGenericOperationsTest, GenericEncryptGood) { EXPECT_EQ(encrypted, out_buffer); } -TEST_F(WvGenericOperationsTest, GenericEncryptNoKey) { +TEST_F(WvGenericCryptoTest, GenericEncryptNoKey) { CdmResponseType cdm_sts; std::string encrypted = Aes128CbcEncrypt(ency_key_, in_vector_, iv_vector_); std::string out_buffer; @@ -127,7 +127,7 @@ TEST_F(WvGenericOperationsTest, GenericEncryptNoKey) { EXPECT_NE(encrypted, out_buffer); } -TEST_F(WvGenericOperationsTest, GenericEncryptKeyNotAllowed) { +TEST_F(WvGenericCryptoTest, GenericEncryptKeyNotAllowed) { CdmResponseType cdm_sts; // Trying to use Decrypt key to encrypt, which is not allowed. KeyId key_id = dency_id_; @@ -142,7 +142,7 @@ TEST_F(WvGenericOperationsTest, GenericEncryptKeyNotAllowed) { EXPECT_NE(encrypted, out_buffer); } -TEST_F(WvGenericOperationsTest, GenericDecryptGood) { +TEST_F(WvGenericCryptoTest, GenericDecryptGood) { CdmResponseType cdm_sts; std::string decrypted = Aes128CbcDecrypt(dency_key_, in_vector_, iv_vector_); std::string out_buffer; @@ -156,7 +156,7 @@ TEST_F(WvGenericOperationsTest, GenericDecryptGood) { EXPECT_EQ(decrypted, out_buffer); } -TEST_F(WvGenericOperationsTest, GenericDecryptNoKey) { +TEST_F(WvGenericCryptoTest, GenericDecryptNoKey) { CdmResponseType cdm_sts; std::string decrypted = Aes128CbcDecrypt(dency_key_, in_vector_, iv_vector_); std::string out_buffer; @@ -170,7 +170,7 @@ TEST_F(WvGenericOperationsTest, GenericDecryptNoKey) { EXPECT_NE(decrypted, out_buffer); } -TEST_F(WvGenericOperationsTest, GenericDecryptKeyNotAllowed) { +TEST_F(WvGenericCryptoTest, GenericDecryptKeyNotAllowed) { CdmResponseType cdm_sts; // Trying to use Encrypt key to decrypt, which is not allowed. KeyId key_id = ency_id_; @@ -185,7 +185,7 @@ TEST_F(WvGenericOperationsTest, GenericDecryptKeyNotAllowed) { EXPECT_NE(decrypted, out_buffer); } -TEST_F(WvGenericOperationsTest, GenericSignKeyNotAllowed) { +TEST_F(WvGenericCryptoTest, GenericSignKeyNotAllowed) { CdmResponseType cdm_sts; // Wrong key std::string key_id = vou_id_; @@ -200,7 +200,7 @@ TEST_F(WvGenericOperationsTest, GenericSignKeyNotAllowed) { EXPECT_NE(signature, out_buffer); } -TEST_F(WvGenericOperationsTest, GenericSignGood) { +TEST_F(WvGenericCryptoTest, GenericSignGood) { CdmResponseType cdm_sts; std::string out_buffer; std::string signature = SignHMAC(in_buffer_, siggy_key_); @@ -213,7 +213,7 @@ TEST_F(WvGenericOperationsTest, GenericSignGood) { EXPECT_EQ(signature, out_buffer); } -TEST_F(WvGenericOperationsTest, GenericVerifyKeyNotAllowed) { +TEST_F(WvGenericCryptoTest, GenericVerifyKeyNotAllowed) { CdmResponseType cdm_sts; // Wrong key std::string key_id = siggy_id_; @@ -226,7 +226,7 @@ TEST_F(WvGenericOperationsTest, GenericVerifyKeyNotAllowed) { EXPECT_EQ(UNKNOWN_ERROR, cdm_sts); } -TEST_F(WvGenericOperationsTest, GenericVerifyBadSignautre) { +TEST_F(WvGenericCryptoTest, GenericVerifyBadSignautre) { CdmResponseType cdm_sts; std::string signature(MAC_KEY_SIZE, 's'); @@ -238,7 +238,7 @@ TEST_F(WvGenericOperationsTest, GenericVerifyBadSignautre) { EXPECT_EQ(UNKNOWN_ERROR, cdm_sts); } -TEST_F(WvGenericOperationsTest, GenericVerifyGood) { +TEST_F(WvGenericCryptoTest, GenericVerifyGood) { CdmResponseType cdm_sts; std::string signature = SignHMAC(in_buffer_, vou_key_); @@ -249,7 +249,7 @@ TEST_F(WvGenericOperationsTest, GenericVerifyGood) { EXPECT_EQ(NO_ERROR, cdm_sts); } -TEST_F(WvGenericOperationsTest, GenericEncryptDecrypt) { +TEST_F(WvGenericCryptoTest, GenericEncryptDecrypt) { CdmResponseType cdm_sts; std::string out_buffer; std::string clear_buffer; @@ -276,7 +276,7 @@ TEST_F(WvGenericOperationsTest, GenericEncryptDecrypt) { EXPECT_EQ(in_buffer_, clear_buffer); } -TEST_F(WvGenericOperationsTest, GenericSignVerify) { +TEST_F(WvGenericCryptoTest, GenericSignVerify) { CdmResponseType cdm_sts; std::string signature_buffer; diff --git a/core/test/initialization_data_unittest.cpp b/core/test/initialization_data_unittest.cpp index b67d6d95..5ecfcef0 100644 --- a/core/test/initialization_data_unittest.cpp +++ b/core/test/initialization_data_unittest.cpp @@ -524,12 +524,14 @@ TEST_F(InitializationDataTest, HandlesMultipleWidevinePsshs) { kOemCryptoWithoutEntitlements); EXPECT_FALSE(single_init_data.IsEmpty()); EXPECT_EQ(kSingleKeyWidevinePsshBoxData, single_init_data.data()); + EXPECT_FALSE(single_init_data.contains_entitled_keys()); InitializationData entitled_init_data(ISO_BMFF_VIDEO_MIME_TYPE, kMultipleWidevinePsshBox, kOemCryptoWithEntitlements); EXPECT_FALSE(entitled_init_data.IsEmpty()); EXPECT_EQ(kEntitledKeysWidevinePsshBoxData, entitled_init_data.data()); + EXPECT_TRUE(entitled_init_data.contains_entitled_keys()); } TEST_P(HlsKeyFormatVersionsExtractionTest, ExtractKeyFormatVersions) { diff --git a/core/test/license_keys_unittest.cpp b/core/test/license_keys_unittest.cpp index 2dc00dc1..dcb7ca0e 100644 --- a/core/test/license_keys_unittest.cpp +++ b/core/test/license_keys_unittest.cpp @@ -67,8 +67,8 @@ using video_widevine::LicenseIdentification; using video_widevine::STREAMING; using video_widevine::OFFLINE; -typedef ::video_widevine::License::KeyContainer KeyContainer; -typedef KeyContainer::VideoResolutionConstraint VideoResolutionConstraint; +using KeyContainer = ::video_widevine::License::KeyContainer; +using VideoResolutionConstraint = KeyContainer::VideoResolutionConstraint; class LicenseKeysTest : public ::testing::Test { protected: @@ -98,6 +98,7 @@ class LicenseKeysTest : public ::testing::Test { static const KeyFlag kContentClearTrue = kKeyFlagTrue; void SetUp() override { + license_keys_.reset(new LicenseKeys(kSecurityLevelL1)); LicenseIdentification* id = license_.mutable_id(); id->set_version(1); id->set_type(STREAMING); @@ -217,7 +218,7 @@ class LicenseKeysTest : public ::testing::Test { content_key_count_++; AddContentKey(ck_hw_secure, true, KeyContainer::HW_SECURE_ALL); content_key_count_++; - license_keys_.SetFromLicense(license_); + license_keys_->SetFromLicense(license_); } virtual void StageOperatorSessionKeys() { @@ -235,7 +236,7 @@ class LicenseKeysTest : public ::testing::Test { kEncryptNull, kDecryptNull, kSignTrue, kVerifyTrue); AddOperatorSessionKey(osk_all, true, kEncryptTrue, kDecryptTrue, kSignTrue, kVerifyTrue); - license_keys_.SetFromLicense(license_); + license_keys_->SetFromLicense(license_); } virtual void StageHdcpKeys() { @@ -276,7 +277,7 @@ class LicenseKeysTest : public ::testing::Test { KeyContainer::HW_SECURE_ALL, true, KeyContainer::OutputProtection::HDCP_NO_DIGITAL_OUTPUT); content_key_count_++; - license_keys_.SetFromLicense(license_); + license_keys_->SetFromLicense(license_); } virtual void AddConstraint( @@ -348,7 +349,7 @@ class LicenseKeysTest : public ::testing::Test { &constraints); content_key_count_++; - license_keys_.SetFromLicense(license_); + license_keys_->SetFromLicense(license_); } virtual void ExpectKeyStatusesEqual(CdmKeyStatusMap& key_status_map, @@ -372,19 +373,19 @@ class LicenseKeysTest : public ::testing::Test { size_t content_key_count_; - LicenseKeys license_keys_; + std::unique_ptr license_keys_; License license_; }; TEST_F(LicenseKeysTest, Empty) { - EXPECT_TRUE(license_keys_.Empty()); + EXPECT_TRUE(license_keys_->Empty()); } TEST_F(LicenseKeysTest, NotEmpty) { const KeyId c_key = "content_key"; AddContentKey(c_key); - license_keys_.SetFromLicense(license_); - EXPECT_FALSE(license_keys_.Empty()); + license_keys_->SetFromLicense(license_); + EXPECT_FALSE(license_keys_->Empty()); } TEST_F(LicenseKeysTest, BadKeyId) { @@ -394,11 +395,12 @@ TEST_F(LicenseKeysTest, BadKeyId) { CdmKeyAllowedUsage allowed_usage; AddContentKey(c_key); AddOperatorSessionKey(os_key); - license_keys_.SetFromLicense(license_); - EXPECT_FALSE(license_keys_.IsContentKey(unk_key)); - EXPECT_FALSE(license_keys_.CanDecryptContent(unk_key)); - EXPECT_TRUE(license_keys_.MeetsConstraints(unk_key)); - EXPECT_FALSE(license_keys_.GetAllowedUsage(unk_key, &allowed_usage)); + license_keys_->SetFromLicense(license_); + EXPECT_FALSE(license_keys_->IsContentKey(unk_key)); + EXPECT_FALSE(license_keys_->CanDecryptContent(unk_key)); + EXPECT_TRUE(license_keys_->MeetsConstraints(unk_key)); + EXPECT_TRUE(license_keys_->MeetsSecurityLevelConstraints(unk_key)); + EXPECT_FALSE(license_keys_->GetAllowedUsage(unk_key, &allowed_usage)); } TEST_F(LicenseKeysTest, SigningKey) { @@ -409,81 +411,82 @@ TEST_F(LicenseKeysTest, SigningKey) { AddSigningKey(sign_key); AddContentKey(c_key); AddOperatorSessionKey(os_key); - license_keys_.SetFromLicense(license_); - EXPECT_FALSE(license_keys_.IsContentKey(sign_key)); - EXPECT_FALSE(license_keys_.CanDecryptContent(sign_key)); - EXPECT_TRUE(license_keys_.MeetsConstraints(sign_key)); - EXPECT_FALSE(license_keys_.GetAllowedUsage(sign_key, &allowed_usage)); + license_keys_->SetFromLicense(license_); + EXPECT_FALSE(license_keys_->IsContentKey(sign_key)); + EXPECT_FALSE(license_keys_->CanDecryptContent(sign_key)); + EXPECT_TRUE(license_keys_->MeetsConstraints(sign_key)); + EXPECT_TRUE(license_keys_->MeetsSecurityLevelConstraints(sign_key)); + EXPECT_FALSE(license_keys_->GetAllowedUsage(sign_key, &allowed_usage)); } TEST_F(LicenseKeysTest, ContentKey) { const KeyId c_key = "content_key"; AddContentKey(c_key); - EXPECT_FALSE(license_keys_.IsContentKey(c_key)); + EXPECT_FALSE(license_keys_->IsContentKey(c_key)); - license_keys_.SetFromLicense(license_); - EXPECT_TRUE(license_keys_.IsContentKey(c_key)); + license_keys_->SetFromLicense(license_); + EXPECT_TRUE(license_keys_->IsContentKey(c_key)); } TEST_F(LicenseKeysTest, EntitlementKey) { const KeyId e_key = "entitlement_key"; const KeyId c_key = "content_key"; AddEntitlementKey(e_key); - EXPECT_FALSE(license_keys_.IsContentKey(e_key)); + EXPECT_FALSE(license_keys_->IsContentKey(e_key)); - license_keys_.SetFromLicense(license_); + license_keys_->SetFromLicense(license_); // TODO(juce, rfrias): For simplicity entitlement keys are indicated as // content keys. It doesn't break anything, but CanDecryptContent returns true // for and entitlement key id. - EXPECT_TRUE(license_keys_.IsContentKey(e_key)); + EXPECT_TRUE(license_keys_->IsContentKey(e_key)); std::vector entitled_keys(1); entitled_keys[0].set_entitlement_key_id(e_key); entitled_keys[0].set_key_id(c_key); - EXPECT_FALSE(license_keys_.IsContentKey(c_key)); - license_keys_.SetEntitledKeys(entitled_keys); - EXPECT_TRUE(license_keys_.IsContentKey(c_key)); + EXPECT_FALSE(license_keys_->IsContentKey(c_key)); + license_keys_->SetEntitledKeys(entitled_keys); + EXPECT_TRUE(license_keys_->IsContentKey(c_key)); } TEST_F(LicenseKeysTest, OperatorSessionKey) { const KeyId os_key = "op_sess_key"; - EXPECT_FALSE(license_keys_.IsContentKey(os_key)); + EXPECT_FALSE(license_keys_->IsContentKey(os_key)); AddOperatorSessionKey(os_key); - license_keys_.SetFromLicense(license_); - EXPECT_FALSE(license_keys_.IsContentKey(os_key)); + license_keys_->SetFromLicense(license_); + EXPECT_FALSE(license_keys_->IsContentKey(os_key)); } TEST_F(LicenseKeysTest, CanDecrypt) { const KeyId os_key = "op_sess_key"; const KeyId c_key = "content_key"; const KeyId e_key = "entitlement_key"; - EXPECT_FALSE(license_keys_.CanDecryptContent(c_key)); - EXPECT_FALSE(license_keys_.CanDecryptContent(os_key)); - EXPECT_FALSE(license_keys_.CanDecryptContent(e_key)); + EXPECT_FALSE(license_keys_->CanDecryptContent(c_key)); + EXPECT_FALSE(license_keys_->CanDecryptContent(os_key)); + EXPECT_FALSE(license_keys_->CanDecryptContent(e_key)); AddOperatorSessionKey(os_key); AddContentKey(c_key); AddEntitlementKey(e_key); - license_keys_.SetFromLicense(license_); - EXPECT_FALSE(license_keys_.CanDecryptContent(c_key)); - EXPECT_FALSE(license_keys_.CanDecryptContent(os_key)); - EXPECT_FALSE(license_keys_.CanDecryptContent(e_key)); + license_keys_->SetFromLicense(license_); + EXPECT_FALSE(license_keys_->CanDecryptContent(c_key)); + EXPECT_FALSE(license_keys_->CanDecryptContent(os_key)); + EXPECT_FALSE(license_keys_->CanDecryptContent(e_key)); bool new_usable_keys = false; bool any_change = false; - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_TRUE(new_usable_keys); - EXPECT_TRUE(license_keys_.CanDecryptContent(c_key)); - EXPECT_FALSE(license_keys_.CanDecryptContent(os_key)); + EXPECT_TRUE(license_keys_->CanDecryptContent(c_key)); + EXPECT_FALSE(license_keys_->CanDecryptContent(os_key)); - any_change = license_keys_.ApplyStatusChange(kKeyStatusExpired, + any_change = license_keys_->ApplyStatusChange(kKeyStatusExpired, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_FALSE(new_usable_keys); - EXPECT_FALSE(license_keys_.CanDecryptContent(c_key)); - EXPECT_FALSE(license_keys_.CanDecryptContent(os_key)); - EXPECT_FALSE(license_keys_.CanDecryptContent(e_key)); + EXPECT_FALSE(license_keys_->CanDecryptContent(c_key)); + EXPECT_FALSE(license_keys_->CanDecryptContent(os_key)); + EXPECT_FALSE(license_keys_->CanDecryptContent(e_key)); } TEST_F(LicenseKeysTest, AllowedUsageNull) { @@ -495,22 +498,22 @@ TEST_F(LicenseKeysTest, AllowedUsageNull) { AddContentKey(c_key); AddSigningKey(sign_key); AddEntitlementKey(e_key); - license_keys_.SetFromLicense(license_); + license_keys_->SetFromLicense(license_); CdmKeyAllowedUsage usage_1; - EXPECT_FALSE(license_keys_.GetAllowedUsage(sign_key, &usage_1)); + EXPECT_FALSE(license_keys_->GetAllowedUsage(sign_key, &usage_1)); CdmKeyAllowedUsage usage_2; - EXPECT_TRUE(license_keys_.GetAllowedUsage(c_key, &usage_2)); + EXPECT_TRUE(license_keys_->GetAllowedUsage(c_key, &usage_2)); ExpectAllowedUsageContent(usage_2, kContentClearTrue, kContentSecureTrue, kKeySecurityLevelUnset); CdmKeyAllowedUsage usage_3; - EXPECT_TRUE(license_keys_.GetAllowedUsage(os_key, &usage_3)); + EXPECT_TRUE(license_keys_->GetAllowedUsage(os_key, &usage_3)); ExpectAllowedUsageContent(usage_3, kContentClearFalse, kContentSecureFalse, kKeySecurityLevelUnset); CdmKeyAllowedUsage usage_4; - EXPECT_TRUE(license_keys_.GetAllowedUsage(os_key, &usage_4)); + EXPECT_TRUE(license_keys_->GetAllowedUsage(os_key, &usage_4)); ExpectAllowedUsageContent(usage_4, kContentClearFalse, kContentSecureFalse, kKeySecurityLevelUnset); } @@ -518,27 +521,27 @@ TEST_F(LicenseKeysTest, AllowedUsageNull) { TEST_F(LicenseKeysTest, AllowedUsageContent) { StageContentKeys(); CdmKeyAllowedUsage u_sw_crypto; - EXPECT_TRUE(license_keys_.GetAllowedUsage(ck_sw_crypto, &u_sw_crypto)); + EXPECT_TRUE(license_keys_->GetAllowedUsage(ck_sw_crypto, &u_sw_crypto)); ExpectAllowedUsageContent(u_sw_crypto, kContentSecureTrue, kContentClearTrue, kSoftwareSecureCrypto); CdmKeyAllowedUsage u_sw_decode; - EXPECT_TRUE(license_keys_.GetAllowedUsage(ck_sw_decode, &u_sw_decode)); + EXPECT_TRUE(license_keys_->GetAllowedUsage(ck_sw_decode, &u_sw_decode)); ExpectAllowedUsageContent(u_sw_decode, kContentSecureTrue, kContentClearTrue, kSoftwareSecureDecode); CdmKeyAllowedUsage u_hw_crypto; - EXPECT_TRUE(license_keys_.GetAllowedUsage(ck_hw_crypto, &u_hw_crypto)); + EXPECT_TRUE(license_keys_->GetAllowedUsage(ck_hw_crypto, &u_hw_crypto)); ExpectAllowedUsageContent(u_hw_crypto, kContentSecureTrue, kContentClearTrue, kHardwareSecureCrypto); CdmKeyAllowedUsage u_hw_decode; - EXPECT_TRUE(license_keys_.GetAllowedUsage(ck_hw_decode, &u_hw_decode)); + EXPECT_TRUE(license_keys_->GetAllowedUsage(ck_hw_decode, &u_hw_decode)); ExpectAllowedUsageContent(u_hw_decode, kContentSecureTrue, kContentClearFalse, kHardwareSecureDecode); CdmKeyAllowedUsage u_hw_secure; - EXPECT_TRUE(license_keys_.GetAllowedUsage(ck_hw_secure, &u_hw_secure)); + EXPECT_TRUE(license_keys_->GetAllowedUsage(ck_hw_secure, &u_hw_secure)); ExpectAllowedUsageContent(u_hw_secure, kContentSecureTrue, kContentClearFalse, kHardwareSecureAll); } @@ -546,38 +549,38 @@ TEST_F(LicenseKeysTest, AllowedUsageContent) { TEST_F(LicenseKeysTest, AllowedUsageOperatorSession) { StageOperatorSessionKeys(); CdmKeyAllowedUsage u_encrypt; - EXPECT_TRUE(license_keys_.GetAllowedUsage(osk_encrypt, &u_encrypt)); + EXPECT_TRUE(license_keys_->GetAllowedUsage(osk_encrypt, &u_encrypt)); ExpectAllowedUsageOperator(u_encrypt, kEncryptTrue, kDecryptFalse, kSignFalse, kVerifyFalse); CdmKeyAllowedUsage u_decrypt; - EXPECT_TRUE(license_keys_.GetAllowedUsage(osk_decrypt, &u_decrypt)); + EXPECT_TRUE(license_keys_->GetAllowedUsage(osk_decrypt, &u_decrypt)); ExpectAllowedUsageOperator(u_decrypt, kEncryptFalse, kDecryptTrue, kSignFalse, kVerifyFalse); CdmKeyAllowedUsage u_sign; - EXPECT_TRUE(license_keys_.GetAllowedUsage(osk_sign, &u_sign)); + EXPECT_TRUE(license_keys_->GetAllowedUsage(osk_sign, &u_sign)); ExpectAllowedUsageOperator(u_sign, kEncryptFalse, kDecryptFalse, kSignTrue, kVerifyFalse); CdmKeyAllowedUsage u_verify; - EXPECT_TRUE(license_keys_.GetAllowedUsage(osk_verify, &u_verify)); + EXPECT_TRUE(license_keys_->GetAllowedUsage(osk_verify, &u_verify)); ExpectAllowedUsageOperator(u_verify, kEncryptFalse, kDecryptFalse, kSignFalse, kVerifyTrue); CdmKeyAllowedUsage u_encrypt_decrypt; - EXPECT_TRUE(license_keys_.GetAllowedUsage(osk_encrypt_decrypt, + EXPECT_TRUE(license_keys_->GetAllowedUsage(osk_encrypt_decrypt, &u_encrypt_decrypt)); ExpectAllowedUsageOperator(u_encrypt_decrypt, kEncryptTrue, kDecryptTrue, kSignFalse, kVerifyFalse); CdmKeyAllowedUsage u_sign_verify; - EXPECT_TRUE(license_keys_.GetAllowedUsage(osk_sign_verify, &u_sign_verify)); + EXPECT_TRUE(license_keys_->GetAllowedUsage(osk_sign_verify, &u_sign_verify)); ExpectAllowedUsageOperator(u_sign_verify, kEncryptFalse, kDecryptFalse, kSignTrue, kVerifyTrue); CdmKeyAllowedUsage u_all; - EXPECT_TRUE(license_keys_.GetAllowedUsage(osk_all, &u_all)); + EXPECT_TRUE(license_keys_->GetAllowedUsage(osk_all, &u_all)); ExpectAllowedUsageOperator(u_all, kEncryptTrue, kDecryptTrue, kSignTrue, kVerifyTrue); } @@ -585,10 +588,10 @@ TEST_F(LicenseKeysTest, AllowedUsageOperatorSession) { TEST_F(LicenseKeysTest, ExtractKeyStatuses) { CdmKeyStatusMap key_status_map; StageOperatorSessionKeys(); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); EXPECT_EQ(0u, key_status_map.size()); StageContentKeys(); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); EXPECT_EQ(content_key_count_, key_status_map.size()); ExpectKeyStatusesEqual(key_status_map, kKeyStatusInternalError); } @@ -600,67 +603,67 @@ TEST_F(LicenseKeysTest, KeyStatusChanges) { StageOperatorSessionKeys(); StageContentKeys(); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); EXPECT_EQ(content_key_count_, key_status_map.size()); ExpectKeyStatusesEqual(key_status_map, kKeyStatusInternalError); // change to pending - any_change = license_keys_.ApplyStatusChange(kKeyStatusPending, + any_change = license_keys_->ApplyStatusChange(kKeyStatusPending, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_FALSE(new_usable_keys); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); EXPECT_EQ(content_key_count_, key_status_map.size()); ExpectKeyStatusesEqual(key_status_map, kKeyStatusPending); - // change to pending (again) - any_change = license_keys_.ApplyStatusChange(kKeyStatusPending, + // change to usable in future + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsableInFuture, &new_usable_keys); - EXPECT_FALSE(any_change); + EXPECT_TRUE(any_change); EXPECT_FALSE(new_usable_keys); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); EXPECT_EQ(content_key_count_, key_status_map.size()); - ExpectKeyStatusesEqual(key_status_map, kKeyStatusPending); + ExpectKeyStatusesEqual(key_status_map, kKeyStatusUsableInFuture); // change to usable - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_TRUE(new_usable_keys); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); EXPECT_EQ(content_key_count_, key_status_map.size()); ExpectKeyStatusesEqual(key_status_map, kKeyStatusUsable); // change to usable (again) - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_FALSE(any_change); EXPECT_FALSE(new_usable_keys); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); EXPECT_EQ(content_key_count_, key_status_map.size()); ExpectKeyStatusesEqual(key_status_map, kKeyStatusUsable); // change to expired - any_change = license_keys_.ApplyStatusChange(kKeyStatusExpired, + any_change = license_keys_->ApplyStatusChange(kKeyStatusExpired, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_FALSE(new_usable_keys); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); EXPECT_EQ(content_key_count_, key_status_map.size()); ExpectKeyStatusesEqual(key_status_map, kKeyStatusExpired); } @@ -671,61 +674,61 @@ TEST_F(LicenseKeysTest, HdcpChanges) { CdmKeyStatusMap key_status_map; StageHdcpKeys(); - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_TRUE(new_usable_keys); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_NO_HDCP)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_NO_HDCP)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_2)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_2)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_3)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_3)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_NO_OUTPUT)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_NO_HDCP)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_NO_HDCP)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_2)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_2)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_3)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_3)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_NO_OUTPUT)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_NO_HDCP)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_NO_HDCP)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_2)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_2)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_3)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_3)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_NO_OUTPUT)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_NO_HDCP)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_NO_HDCP)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_2)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_2)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_3)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_3)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_NO_OUTPUT)); - license_keys_.ApplyConstraints(100, HDCP_NONE); - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + license_keys_->ApplyConstraints(100, HDCP_NONE); + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_FALSE(new_usable_keys); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_NO_HDCP)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_NO_HDCP)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_1)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_1)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_NO_OUTPUT)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_NO_HDCP)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_NO_HDCP)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_1)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_1)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_NO_OUTPUT)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_NO_OUTPUT)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_NO_HDCP)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_NO_HDCP)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_1)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_1)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_NO_OUTPUT)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_NO_HDCP)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_NO_HDCP)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_1)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_1)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_NO_OUTPUT)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_NO_OUTPUT)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_hw_secure_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_HDCP_V2_1, @@ -745,35 +748,35 @@ TEST_F(LicenseKeysTest, HdcpChanges) { ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_HDCP_NO_OUTPUT, kKeyStatusOutputNotAllowed); - license_keys_.ApplyConstraints(100, HDCP_V1); - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + license_keys_->ApplyConstraints(100, HDCP_V1); + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_FALSE(any_change); EXPECT_FALSE(new_usable_keys); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_NO_HDCP)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_NO_HDCP)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_1)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_1)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_NO_OUTPUT)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_NO_HDCP)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_NO_HDCP)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_1)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_1)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_NO_OUTPUT)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_NO_OUTPUT)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_NO_HDCP)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_NO_HDCP)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_1)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_1)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_NO_OUTPUT)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_NO_HDCP)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_NO_HDCP)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_1)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_1)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_NO_OUTPUT)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_NO_OUTPUT)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_hw_secure_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_HDCP_V2_1, @@ -793,35 +796,35 @@ TEST_F(LicenseKeysTest, HdcpChanges) { ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_HDCP_NO_OUTPUT, kKeyStatusOutputNotAllowed); - license_keys_.ApplyConstraints(100, HDCP_V2_1); - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + license_keys_->ApplyConstraints(100, HDCP_V2_1); + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_TRUE(new_usable_keys); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_NO_HDCP)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_NO_HDCP)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_1)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_NO_OUTPUT)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_NO_HDCP)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_NO_HDCP)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_1)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_NO_OUTPUT)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_NO_OUTPUT)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_NO_HDCP)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_NO_HDCP)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_1)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_NO_OUTPUT)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_NO_HDCP)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_NO_HDCP)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_1)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_NO_OUTPUT)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_NO_OUTPUT)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_hw_secure_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_HDCP_V2_1, @@ -841,35 +844,35 @@ TEST_F(LicenseKeysTest, HdcpChanges) { ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_HDCP_NO_OUTPUT, kKeyStatusOutputNotAllowed); - license_keys_.ApplyConstraints(100, HDCP_V2_2); - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + license_keys_->ApplyConstraints(100, HDCP_V2_2); + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_TRUE(new_usable_keys); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_NO_HDCP)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_NO_HDCP)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_2)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_NO_OUTPUT)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_NO_HDCP)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_NO_HDCP)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_2)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_NO_OUTPUT)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_NO_OUTPUT)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_NO_HDCP)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_NO_HDCP)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_2)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_NO_OUTPUT)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_NO_HDCP)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_NO_HDCP)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_2)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_NO_OUTPUT)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_NO_OUTPUT)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_hw_secure_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_HDCP_V2_1, @@ -889,35 +892,35 @@ TEST_F(LicenseKeysTest, HdcpChanges) { ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_HDCP_NO_OUTPUT, kKeyStatusOutputNotAllowed); - license_keys_.ApplyConstraints(100, HDCP_V2_3); - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + license_keys_->ApplyConstraints(100, HDCP_V2_3); + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_TRUE(new_usable_keys); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_NO_HDCP)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_NO_HDCP)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_2)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_2)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_3)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_NO_OUTPUT)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_NO_HDCP)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_NO_HDCP)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_2)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_2)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_3)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_NO_OUTPUT)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_NO_OUTPUT)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_NO_HDCP)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_NO_HDCP)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_2)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_2)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_3)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_NO_OUTPUT)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_NO_HDCP)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_NO_HDCP)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_2)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_2)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_3)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_NO_OUTPUT)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_NO_OUTPUT)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_hw_secure_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_HDCP_V2_1, @@ -937,27 +940,27 @@ TEST_F(LicenseKeysTest, HdcpChanges) { ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_HDCP_NO_OUTPUT, kKeyStatusOutputNotAllowed); - license_keys_.ApplyConstraints(100, HDCP_NO_DIGITAL_OUTPUT); - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + license_keys_->ApplyConstraints(100, HDCP_NO_DIGITAL_OUTPUT); + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_TRUE(new_usable_keys); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_NO_HDCP)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_NO_HDCP)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_NO_OUTPUT)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_NO_HDCP)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_NO_HDCP)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_NO_OUTPUT)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_NO_HDCP)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_NO_HDCP)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_1)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_NO_OUTPUT)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_NO_HDCP)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_NO_HDCP)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_1)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_NO_OUTPUT)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_hw_secure_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_HDCP_V2_1, @@ -977,35 +980,35 @@ TEST_F(LicenseKeysTest, HdcpChanges) { ExpectKeyStatusEqual(key_status_map, ck_hw_secure_HDCP_NO_OUTPUT, kKeyStatusUsable); - license_keys_.ApplyConstraints(100, HDCP_NONE); - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + license_keys_->ApplyConstraints(100, HDCP_NONE); + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_FALSE(new_usable_keys); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_sw_crypto_NO_HDCP)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_hw_secure_NO_HDCP)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_1)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_1)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_sw_crypto_HDCP_NO_OUTPUT)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_hw_secure_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_sw_crypto_NO_HDCP)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_hw_secure_NO_HDCP)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_1)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_1)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto_HDCP_NO_OUTPUT)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure_HDCP_NO_OUTPUT)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_sw_crypto_NO_HDCP)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_hw_secure_NO_HDCP)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_1)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_1)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_2)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_V2_3)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_sw_crypto_HDCP_NO_OUTPUT)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_hw_secure_HDCP_NO_OUTPUT)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_sw_crypto_NO_HDCP)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_hw_secure_NO_HDCP)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_1)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_1)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_2)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_V2_3)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_sw_crypto_HDCP_NO_OUTPUT)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_hw_secure_HDCP_NO_OUTPUT)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_hw_secure_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_HDCP_V2_1, @@ -1033,46 +1036,46 @@ TEST_F(LicenseKeysTest, ConstraintChanges) { StageConstraintKeys(); // No constraints set by device - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_TRUE(new_usable_keys); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_NO_HDCP_lo_res)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_HDCP_NO_OUTPUT_hi_res)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_HDCP_V2_1_hi_res)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_HDCP_V2_2_max_res)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_HDCP_V2_3_max_res)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_NO_HDCP_dual_res)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_NO_HDCP_lo_res)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_HDCP_NO_OUTPUT_hi_res)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_HDCP_V2_1_hi_res)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_HDCP_V2_2_max_res)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_HDCP_V2_3_max_res)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_NO_HDCP_dual_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_NO_HDCP_lo_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_HDCP_NO_OUTPUT_hi_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_HDCP_V2_1_hi_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_HDCP_V2_2_max_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_HDCP_V2_3_max_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_NO_HDCP_dual_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_NO_HDCP_lo_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_HDCP_NO_OUTPUT_hi_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_HDCP_V2_1_hi_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_HDCP_V2_2_max_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_HDCP_V2_3_max_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_NO_HDCP_dual_res)); // Low-res device, no HDCP support - license_keys_.ApplyConstraints(dev_lo_res, HDCP_NONE); - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + license_keys_->ApplyConstraints(dev_lo_res, HDCP_NONE); + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_FALSE(new_usable_keys); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_NO_HDCP_lo_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_NO_OUTPUT_hi_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_V2_1_hi_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_V2_2_max_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_V2_3_max_res)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_NO_HDCP_dual_res)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_NO_HDCP_lo_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_NO_OUTPUT_hi_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_V2_1_hi_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_V2_2_max_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_V2_3_max_res)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_NO_HDCP_dual_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_NO_HDCP_lo_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_NO_OUTPUT_hi_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_V2_1_hi_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_V2_2_max_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_V2_3_max_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_NO_HDCP_dual_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_NO_HDCP_lo_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_NO_OUTPUT_hi_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_V2_1_hi_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_V2_2_max_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_V2_3_max_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_NO_HDCP_dual_res)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_hw_secure_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_HDCP_V2_1, @@ -1093,27 +1096,27 @@ TEST_F(LicenseKeysTest, ConstraintChanges) { kKeyStatusOutputNotAllowed); // Hi-res device, HDCP_V1 support - license_keys_.ApplyConstraints(dev_hi_res, HDCP_V1); - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + license_keys_->ApplyConstraints(dev_hi_res, HDCP_V1); + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_TRUE(new_usable_keys); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_NO_HDCP_lo_res)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_HDCP_NO_OUTPUT_hi_res)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_HDCP_V2_1_hi_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_V2_2_max_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_V2_3_max_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_NO_HDCP_dual_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_NO_HDCP_lo_res)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_HDCP_NO_OUTPUT_hi_res)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_HDCP_V2_1_hi_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_V2_2_max_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_V2_3_max_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_NO_HDCP_dual_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_NO_HDCP_lo_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_HDCP_NO_OUTPUT_hi_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_HDCP_V2_1_hi_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_V2_2_max_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_V2_3_max_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_NO_HDCP_dual_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_NO_HDCP_lo_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_HDCP_NO_OUTPUT_hi_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_HDCP_V2_1_hi_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_V2_2_max_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_V2_3_max_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_NO_HDCP_dual_res)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_hw_secure_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_HDCP_V2_1, @@ -1134,27 +1137,27 @@ TEST_F(LicenseKeysTest, ConstraintChanges) { kKeyStatusOutputNotAllowed); // Lo-res device, HDCP V2.2 support - license_keys_.ApplyConstraints(dev_lo_res, HDCP_V2_2); - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + license_keys_->ApplyConstraints(dev_lo_res, HDCP_V2_2); + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_TRUE(new_usable_keys); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_NO_HDCP_lo_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_NO_OUTPUT_hi_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_V2_1_hi_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_V2_2_max_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_V2_3_max_res)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_NO_HDCP_dual_res)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_NO_HDCP_lo_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_NO_OUTPUT_hi_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_V2_1_hi_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_V2_2_max_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_V2_3_max_res)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_NO_HDCP_dual_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_NO_HDCP_lo_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_NO_OUTPUT_hi_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_V2_1_hi_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_V2_2_max_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_V2_3_max_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_NO_HDCP_dual_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_NO_HDCP_lo_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_NO_OUTPUT_hi_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_V2_1_hi_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_V2_2_max_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_V2_3_max_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_NO_HDCP_dual_res)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_HDCP_V2_1, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_hw_secure_HDCP_V2_1, @@ -1173,27 +1176,27 @@ TEST_F(LicenseKeysTest, ConstraintChanges) { kKeyStatusOutputNotAllowed); // Hi-res device, Maximal HDCP support - license_keys_.ApplyConstraints(dev_hi_res, HDCP_NO_DIGITAL_OUTPUT); - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + license_keys_->ApplyConstraints(dev_hi_res, HDCP_NO_DIGITAL_OUTPUT); + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_TRUE(new_usable_keys); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_NO_HDCP_lo_res)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_HDCP_NO_OUTPUT_hi_res)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_HDCP_V2_1_hi_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_V2_2_max_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_V2_3_max_res)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_NO_HDCP_dual_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_NO_HDCP_lo_res)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_HDCP_NO_OUTPUT_hi_res)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_HDCP_V2_1_hi_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_V2_2_max_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_V2_3_max_res)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_NO_HDCP_dual_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_NO_HDCP_lo_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_HDCP_NO_OUTPUT_hi_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_HDCP_V2_1_hi_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_V2_2_max_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_V2_3_max_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_NO_HDCP_dual_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_NO_HDCP_lo_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_HDCP_NO_OUTPUT_hi_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_HDCP_V2_1_hi_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_V2_2_max_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_V2_3_max_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_NO_HDCP_dual_res)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_HDCP_V2_1, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_hw_secure_HDCP_V2_1, @@ -1212,29 +1215,29 @@ TEST_F(LicenseKeysTest, ConstraintChanges) { kKeyStatusUsable); // Lo-res device, no HDCP support - license_keys_.ApplyConstraints(dev_lo_res, HDCP_NONE); - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + license_keys_->ApplyConstraints(dev_lo_res, HDCP_NONE); + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_TRUE(new_usable_keys); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_NO_HDCP_lo_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_NO_OUTPUT_hi_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_V2_1_hi_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_V2_2_max_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_V2_3_max_res)); - EXPECT_TRUE(license_keys_.CanDecryptContent(ck_NO_HDCP_dual_res)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_NO_HDCP_lo_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_NO_OUTPUT_hi_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_V2_1_hi_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_V2_2_max_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_V2_3_max_res)); + EXPECT_TRUE(license_keys_->CanDecryptContent(ck_NO_HDCP_dual_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_NO_HDCP_lo_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_NO_OUTPUT_hi_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_V2_1_hi_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_V2_2_max_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_V2_3_max_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_NO_HDCP_dual_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_NO_HDCP_dual_res)); - EXPECT_TRUE(license_keys_.MeetsConstraints(ck_NO_HDCP_dual_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_NO_HDCP_lo_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_NO_OUTPUT_hi_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_V2_1_hi_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_V2_2_max_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_V2_3_max_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_NO_HDCP_dual_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_NO_HDCP_dual_res)); + EXPECT_TRUE(license_keys_->MeetsConstraints(ck_NO_HDCP_dual_res)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_hw_secure_NO_HDCP, @@ -1257,27 +1260,27 @@ TEST_F(LicenseKeysTest, ConstraintChanges) { kKeyStatusOutputNotAllowed); // Too-high-res -- all keys rejected - license_keys_.ApplyConstraints(dev_top_res, HDCP_NONE); - any_change = license_keys_.ApplyStatusChange(kKeyStatusUsable, + license_keys_->ApplyConstraints(dev_top_res, HDCP_NONE); + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, &new_usable_keys); EXPECT_TRUE(any_change); EXPECT_FALSE(new_usable_keys); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_NO_HDCP_lo_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_NO_OUTPUT_hi_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_V2_1_hi_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_V2_2_max_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_HDCP_V2_3_max_res)); - EXPECT_FALSE(license_keys_.CanDecryptContent(ck_NO_HDCP_dual_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_NO_HDCP_lo_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_NO_OUTPUT_hi_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_V2_1_hi_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_V2_2_max_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_HDCP_V2_3_max_res)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_NO_HDCP_dual_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_NO_HDCP_lo_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_NO_OUTPUT_hi_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_V2_1_hi_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_V2_2_max_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_HDCP_V2_3_max_res)); - EXPECT_FALSE(license_keys_.MeetsConstraints(ck_NO_HDCP_dual_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_NO_HDCP_lo_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_NO_OUTPUT_hi_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_V2_1_hi_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_V2_2_max_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_HDCP_V2_3_max_res)); + EXPECT_FALSE(license_keys_->MeetsConstraints(ck_NO_HDCP_dual_res)); - license_keys_.ExtractKeyStatuses(&key_status_map); + license_keys_->ExtractKeyStatuses(&key_status_map); ExpectKeyStatusEqual(key_status_map, ck_sw_crypto_NO_HDCP, kKeyStatusUsable); ExpectKeyStatusEqual(key_status_map, ck_hw_secure_NO_HDCP, @@ -1300,4 +1303,156 @@ TEST_F(LicenseKeysTest, ConstraintChanges) { kKeyStatusOutputNotAllowed); } +struct KeySecurityLevelParams { + CdmSecurityLevel security_level; + bool expect_usable_keys; + bool expect_can_use_sw_crypto_key; + bool expect_can_use_sw_decode_key; + bool expect_can_use_hw_crypto_key; + bool expect_can_use_hw_decode_key; + bool expect_can_use_hw_secure_key; +}; + +KeySecurityLevelParams key_security_level_test_vectors[] = { + { kSecurityLevelUninitialized, false, false, false, false, false, false}, + { kSecurityLevelL1, true, true, true, true, true, true}, + { kSecurityLevelL2, true, true, true, true, false, false}, + { kSecurityLevelL3, true, true, true, false, false, false}, + { kSecurityLevelUnknown, false, false, false, false, false, false}, +}; + +class LicenseKeysSecurityLevelConstraintsTest + : public LicenseKeysTest, + public ::testing::WithParamInterface {}; + +TEST_P(LicenseKeysSecurityLevelConstraintsTest, KeyStatusChange) { + bool new_usable_keys = false; + bool any_change = false; + CdmKeyStatusMap key_status_map; + + KeySecurityLevelParams* config = GetParam(); + license_keys_->SetSecurityLevelForTest(config->security_level); + StageContentKeys(); + + license_keys_->ExtractKeyStatuses(&key_status_map); + EXPECT_EQ(content_key_count_, key_status_map.size()); + ExpectKeyStatusesEqual(key_status_map, kKeyStatusInternalError); + + // change to pending + any_change = license_keys_->ApplyStatusChange(kKeyStatusPending, + &new_usable_keys); + EXPECT_TRUE(any_change); + EXPECT_FALSE(new_usable_keys); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_decode)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_crypto)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_decode)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure)); + + license_keys_->ExtractKeyStatuses(&key_status_map); + EXPECT_EQ(content_key_count_, key_status_map.size()); + ExpectKeyStatusesEqual(key_status_map, kKeyStatusPending); + + // change to usable in future + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsableInFuture, + &new_usable_keys); + EXPECT_TRUE(any_change); + EXPECT_FALSE(new_usable_keys); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_decode)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_crypto)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_decode)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure)); + + license_keys_->ExtractKeyStatuses(&key_status_map); + EXPECT_EQ(content_key_count_, key_status_map.size()); + ExpectKeyStatusesEqual(key_status_map, kKeyStatusUsableInFuture); + + // change to usable + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, + &new_usable_keys); + EXPECT_TRUE(any_change); + EXPECT_EQ(config->expect_usable_keys, new_usable_keys); + EXPECT_EQ(config->expect_can_use_sw_crypto_key, + license_keys_->CanDecryptContent(ck_sw_crypto)); + EXPECT_EQ(config->expect_can_use_sw_decode_key, + license_keys_->CanDecryptContent(ck_sw_decode)); + EXPECT_EQ(config->expect_can_use_hw_crypto_key, + license_keys_->CanDecryptContent(ck_hw_crypto)); + EXPECT_EQ(config->expect_can_use_hw_decode_key, + license_keys_->CanDecryptContent(ck_hw_decode)); + EXPECT_EQ(config->expect_can_use_hw_secure_key, + license_keys_->CanDecryptContent(ck_hw_secure)); + + license_keys_->ExtractKeyStatuses(&key_status_map); + EXPECT_EQ(content_key_count_, key_status_map.size()); + + EXPECT_EQ(config->expect_can_use_sw_crypto_key + ? kKeyStatusUsable : kKeyStatusOutputNotAllowed, + key_status_map[ck_sw_crypto]); + EXPECT_EQ(config->expect_can_use_sw_decode_key + ? kKeyStatusUsable : kKeyStatusOutputNotAllowed, + key_status_map[ck_sw_decode]); + EXPECT_EQ(config->expect_can_use_hw_crypto_key + ? kKeyStatusUsable : kKeyStatusOutputNotAllowed, + key_status_map[ck_hw_crypto]); + EXPECT_EQ(config->expect_can_use_hw_decode_key + ? kKeyStatusUsable : kKeyStatusOutputNotAllowed, + key_status_map[ck_hw_decode]); + EXPECT_EQ(config->expect_can_use_hw_secure_key + ? kKeyStatusUsable : kKeyStatusOutputNotAllowed, + key_status_map[ck_hw_secure]); + + // change to usable (again) + any_change = license_keys_->ApplyStatusChange(kKeyStatusUsable, + &new_usable_keys); + EXPECT_FALSE(any_change); + EXPECT_FALSE(new_usable_keys); + EXPECT_EQ(config->expect_can_use_sw_crypto_key, + license_keys_->CanDecryptContent(ck_sw_crypto)); + EXPECT_EQ(config->expect_can_use_sw_decode_key, + license_keys_->CanDecryptContent(ck_sw_decode)); + EXPECT_EQ(config->expect_can_use_hw_crypto_key, + license_keys_->CanDecryptContent(ck_hw_crypto)); + EXPECT_EQ(config->expect_can_use_hw_decode_key, + license_keys_->CanDecryptContent(ck_hw_decode)); + EXPECT_EQ(config->expect_can_use_hw_secure_key, + license_keys_->CanDecryptContent(ck_hw_secure)); + + license_keys_->ExtractKeyStatuses(&key_status_map); + EXPECT_EQ(content_key_count_, key_status_map.size()); + EXPECT_EQ(config->expect_can_use_sw_crypto_key + ? kKeyStatusUsable : kKeyStatusOutputNotAllowed, + key_status_map[ck_sw_crypto]); + EXPECT_EQ(config->expect_can_use_sw_decode_key + ? kKeyStatusUsable : kKeyStatusOutputNotAllowed, + key_status_map[ck_sw_decode]); + EXPECT_EQ(config->expect_can_use_hw_crypto_key + ? kKeyStatusUsable : kKeyStatusOutputNotAllowed, + key_status_map[ck_hw_crypto]); + EXPECT_EQ(config->expect_can_use_hw_decode_key + ? kKeyStatusUsable : kKeyStatusOutputNotAllowed, + key_status_map[ck_hw_decode]); + EXPECT_EQ(config->expect_can_use_hw_secure_key + ? kKeyStatusUsable : kKeyStatusOutputNotAllowed, + key_status_map[ck_hw_secure]); + + // change to expired + any_change = license_keys_->ApplyStatusChange(kKeyStatusExpired, + &new_usable_keys); + EXPECT_TRUE(any_change); + EXPECT_FALSE(new_usable_keys); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_sw_crypto)); + EXPECT_FALSE(license_keys_->CanDecryptContent(ck_hw_secure)); + + license_keys_->ExtractKeyStatuses(&key_status_map); + EXPECT_EQ(content_key_count_, key_status_map.size()); + ExpectKeyStatusesEqual(key_status_map, kKeyStatusExpired); +} + +INSTANTIATE_TEST_CASE_P(KeyStatusChange, + LicenseKeysSecurityLevelConstraintsTest, + ::testing::Range(&key_security_level_test_vectors[0], + &key_security_level_test_vectors[5])); + } // namespace wvcdm diff --git a/core/test/license_unittest.cpp b/core/test/license_unittest.cpp index d730eb20..ea387fb1 100644 --- a/core/test/license_unittest.cpp +++ b/core/test/license_unittest.cpp @@ -186,6 +186,7 @@ using video_widevine::WidevinePsshData_EntitledKey; // gmock methods using ::testing::_; +using ::testing::DoAll; using ::testing::Eq; using ::testing::NotNull; using ::testing::PrintToStringParamName; diff --git a/core/test/parallel_operations_test.cpp b/core/test/parallel_operations_test.cpp index 33deaa55..bac72af8 100644 --- a/core/test/parallel_operations_test.cpp +++ b/core/test/parallel_operations_test.cpp @@ -35,7 +35,7 @@ namespace { constexpr const int kHttpOk = 200; const std::string kCencMimeType = "cenc"; -constexpr const auto kMaxThreadExecutionTime = std::chrono::seconds(10); +constexpr const auto kMaxThreadExecutionTime = std::chrono::seconds(30); constexpr const auto kMinimumWait = std::chrono::nanoseconds(1); constexpr const int kRepetitions = 10; diff --git a/core/test/policy_engine_constraints_unittest.cpp b/core/test/policy_engine_constraints_unittest.cpp index 1f5c1c6d..853b1b30 100644 --- a/core/test/policy_engine_constraints_unittest.cpp +++ b/core/test/policy_engine_constraints_unittest.cpp @@ -24,15 +24,15 @@ using video_widevine::STREAMING; namespace wvcdm { -typedef ::video_widevine::License License; -typedef ::video_widevine::License::KeyContainer KeyContainer; -typedef ::video_widevine::License::KeyContainer::OutputProtection - OutputProtection; -typedef ::video_widevine::License::KeyContainer:: - VideoResolutionConstraint VideoResolutionConstraint; -typedef ::google::protobuf::RepeatedPtrField KeyList; -typedef ::google::protobuf::RepeatedPtrField - ConstraintList; +using License = ::video_widevine::License; +using KeyContainer = ::video_widevine::License::KeyContainer; +using OutputProtection = + ::video_widevine::License::KeyContainer::OutputProtection; +using VideoResolutionConstraint = + ::video_widevine::License::KeyContainer::VideoResolutionConstraint; +using KeyList = ::google::protobuf::RepeatedPtrField; +using ConstraintList = + ::google::protobuf::RepeatedPtrField; using namespace testing; diff --git a/core/test/policy_engine_unittest.cpp b/core/test/policy_engine_unittest.cpp index f346cd86..99eccea1 100644 --- a/core/test/policy_engine_unittest.cpp +++ b/core/test/policy_engine_unittest.cpp @@ -6,7 +6,7 @@ #include #include -#include +#include #include #include @@ -51,13 +51,6 @@ int64_t GetLicenseRenewalDelay(int64_t license_duration) { : 0; } -int64_t ParseInt(const std::string& str) { - std::stringstream ss(str); - int64_t ret; - ss >> ret; - return ret; -} - class HdcpOnlyMockCryptoSession : public TestCryptoSession { public: HdcpOnlyMockCryptoSession(metrics::CryptoMetrics* metrics) : @@ -182,6 +175,10 @@ class PolicyEngineTest : public WvCdmTestBase { expected_has_new_usable_key)); } + void SetCdmSecurityLevel(CdmSecurityLevel security_level) { + policy_engine_->SetSecurityLevelForTest(security_level); + } + metrics::CryptoMetrics dummy_metrics_; NiceMock crypto_session_; StrictMock mock_event_listener_; @@ -902,7 +899,7 @@ TEST_F(PolicyEngineTest, PlaybackOk_LicenseWithFutureStartTime) { Return(GET_HDCP_CAPABILITY_FAILED))); InSequence s; - ExpectSessionKeysChange(kKeyStatusPending, false); + ExpectSessionKeysChange(kKeyStatusUsableInFuture, false); EXPECT_CALL(mock_event_listener_, OnExpirationUpdate(_, kLicenseStartTime + kRentalDuration)); ExpectSessionKeysChange(kKeyStatusUsable, true); @@ -1050,7 +1047,7 @@ TEST_F(PolicyEngineTest, PlaybackOk_RenewSuccess_WithFutureStartTime) { EXPECT_CALL(check_, Call(1)); EXPECT_CALL(mock_event_listener_, OnSessionRenewalNeeded(_)); EXPECT_CALL(check_, Call(2)); - ExpectSessionKeysChange(kKeyStatusPending, false); + ExpectSessionKeysChange(kKeyStatusUsableInFuture, false); EXPECT_CALL(mock_event_listener_, OnExpirationUpdate(_, new_license_start_time + kLowDuration)); EXPECT_CALL(check_, Call(3)); @@ -1725,20 +1722,29 @@ TEST_P(PolicyEngineKeySecurityLevelTest, CanUseKeyForSecurityLevel) { ExpectSessionKeysChange(kKeyStatusUsable, true); EXPECT_CALL(mock_event_listener_, OnExpirationUpdate(_, _)); + SetCdmSecurityLevel(kSecurityLevelL1); policy_engine_->SetLicense(license_); EXPECT_EQ(param->expect_can_L1_use_key, - policy_engine_->CanUseKeyForSecurityLevel(kKeyId, - kSecurityLevelL1)); + policy_engine_->CanUseKeyForSecurityLevel(kKeyId)); + + SetCdmSecurityLevel(kSecurityLevelL2); + policy_engine_->SetLicense(license_); + EXPECT_EQ(param->expect_can_L2_use_key, - policy_engine_->CanUseKeyForSecurityLevel(kKeyId, - kSecurityLevelL2)); + policy_engine_->CanUseKeyForSecurityLevel(kKeyId)); + + SetCdmSecurityLevel(kSecurityLevelL3); + policy_engine_->SetLicense(license_); + EXPECT_EQ(param->expect_can_L3_use_key, - policy_engine_->CanUseKeyForSecurityLevel(kKeyId, - kSecurityLevelL3)); + policy_engine_->CanUseKeyForSecurityLevel(kKeyId)); + + SetCdmSecurityLevel(kSecurityLevelUnknown); + policy_engine_->SetLicense(license_); + EXPECT_EQ(param->expect_can_level_unknown_use_key, - policy_engine_->CanUseKeyForSecurityLevel(kKeyId, - kSecurityLevelUnknown)); + policy_engine_->CanUseKeyForSecurityLevel(kKeyId)); } INSTANTIATE_TEST_CASE_P( @@ -1859,6 +1865,8 @@ TEST_F(PolicyEngineKeyAllowedUsageTest, AllowedUsageBasic) { content_key->set_id(kKeyId); content_key->set_level(License::KeyContainer::HW_SECURE_ALL); + SetCdmSecurityLevel(kSecurityLevelL1); + // generic operator session key (sign) AddOperatorSessionKey(kGenericKeyId, kEncryptNull, kDecryptNull, kSignTrue, kVerifyNull); @@ -1917,6 +1925,8 @@ TEST_F(PolicyEngineKeyAllowedUsageTest, AllowedUsageGeneric) { another_content_key->set_id(kAnotherKeyId); another_content_key->set_level(License::KeyContainer::HW_SECURE_CRYPTO); + SetCdmSecurityLevel(kSecurityLevelL1); + // generic operator session keys AddOperatorSessionKey(kGenericSignKeyId, kEncryptNull, kDecryptNull, kSignTrue, kVerifyNull); @@ -2017,9 +2027,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(kLowDuration - 100, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2044,9 +2054,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_PlaybackNotBegun) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(kLowDuration - 100, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); EXPECT_EQ(NO_ERROR, policy_engine_->Query(&query_info)); @@ -2056,9 +2066,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_PlaybackNotBegun) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(kLowDuration - 200, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2085,9 +2095,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_PlaybackBegun) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(kLowDuration - 50, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); policy_engine_->BeginDecryption(); @@ -2102,9 +2112,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_PlaybackBegun) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(kLowDuration - 200, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration - 100, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2144,9 +2154,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_Offline) { EXPECT_EQ(QUERY_VALUE_FALSE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(kRentalDuration - 300, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration - 100, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2170,9 +2180,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_InitialRentalDurationExpired) { EXPECT_EQ(QUERY_VALUE_FALSE, query_info[QUERY_KEY_PERSIST_ALLOWED]); EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); - EXPECT_EQ(0, ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + EXPECT_EQ(0, std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2192,9 +2202,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_InitialLicenseDurationExpired) { EXPECT_EQ(QUERY_VALUE_FALSE, query_info[QUERY_KEY_PERSIST_ALLOWED]); EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); - EXPECT_EQ(0, ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + EXPECT_EQ(0, std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2232,9 +2242,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_CanPlayFalse) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(kLowDuration - 100, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2274,9 +2284,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_RentalDurationExpired) { EXPECT_EQ(QUERY_VALUE_FALSE, query_info[QUERY_KEY_PERSIST_ALLOWED]); EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); - EXPECT_EQ(0, ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + EXPECT_EQ(0, std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration - kLowDuration, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2317,8 +2327,8 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_PlaybackDurationExpired) { EXPECT_EQ(QUERY_VALUE_FALSE, query_info[QUERY_KEY_PERSIST_ALLOWED]); EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); - EXPECT_EQ(0, ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); - EXPECT_EQ(0, ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + EXPECT_EQ(0, std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + EXPECT_EQ(0, std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2356,9 +2366,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_LicenseDurationExpired) { EXPECT_EQ(QUERY_VALUE_FALSE, query_info[QUERY_KEY_PERSIST_ALLOWED]); EXPECT_EQ(QUERY_VALUE_FALSE, query_info[QUERY_KEY_RENEW_ALLOWED]); - EXPECT_EQ(0, ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + EXPECT_EQ(0, std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration - kLowDuration, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2399,9 +2409,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_RentalDuration0) { EXPECT_EQ(QUERY_VALUE_FALSE, query_info[QUERY_KEY_PERSIST_ALLOWED]); EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); - EXPECT_EQ(0, ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + EXPECT_EQ(0, std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration - kLowDuration, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2444,9 +2454,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_PlaybackDuration0) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(0, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(LLONG_MAX, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); for (int i = 3; i <= 4; ++i) { @@ -2462,9 +2472,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_PlaybackDuration0) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(0, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(LLONG_MAX, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2502,8 +2512,8 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_LicenseDuration0) { EXPECT_EQ(QUERY_VALUE_FALSE, query_info[QUERY_KEY_PERSIST_ALLOWED]); EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); - EXPECT_EQ(0, ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); - EXPECT_EQ(0, ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + EXPECT_EQ(0, std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + EXPECT_EQ(0, std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2536,9 +2546,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_PlaybackAndRental0) { EXPECT_EQ(QUERY_VALUE_FALSE, query_info[QUERY_KEY_PERSIST_ALLOWED]); EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); - EXPECT_EQ(10, ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + EXPECT_EQ(10, std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(LLONG_MAX, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); policy_engine_->OnTimerEvent(); @@ -2549,9 +2559,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_PlaybackAndRental0) { EXPECT_EQ(QUERY_VALUE_FALSE, query_info[QUERY_KEY_PERSIST_ALLOWED]); EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); - EXPECT_EQ(0, ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + EXPECT_EQ(0, std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(LLONG_MAX, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2588,9 +2598,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_PlaybackAndLicense0_WithoutPlayback) EXPECT_EQ(QUERY_VALUE_FALSE, query_info[QUERY_KEY_PERSIST_ALLOWED]); EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); - EXPECT_EQ(10, ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + EXPECT_EQ(10, std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(LLONG_MAX, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); policy_engine_->OnTimerEvent(); @@ -2604,9 +2614,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_PlaybackAndLicense0_WithoutPlayback) EXPECT_EQ(QUERY_VALUE_FALSE, query_info[QUERY_KEY_PERSIST_ALLOWED]); EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); - EXPECT_EQ(0, ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + EXPECT_EQ(0, std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(LLONG_MAX, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2642,9 +2652,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_PlaybackAndLicense0_WithPlayback) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(kRentalDuration - kPlaybackDuration + 10, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(LLONG_MAX, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); policy_engine_->OnTimerEvent(); @@ -2659,9 +2669,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_PlaybackAndLicense0_WithPlayback) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(kRentalDuration - kPlaybackDuration - 10, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(LLONG_MAX, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); policy_engine_->OnTimerEvent(); @@ -2675,9 +2685,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_PlaybackAndLicense0_WithPlayback) { EXPECT_EQ(QUERY_VALUE_FALSE, query_info[QUERY_KEY_PERSIST_ALLOWED]); EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); - EXPECT_EQ(0, ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + EXPECT_EQ(0, std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(LLONG_MAX, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2709,9 +2719,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_RentalAndLicense0_WithoutPlayback) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(LLONG_MAX, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); policy_engine_->OnTimerEvent(); @@ -2726,9 +2736,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_RentalAndLicense0_WithoutPlayback) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(LLONG_MAX, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2764,9 +2774,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_RentalAndLicense0_WithPlayback) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(LLONG_MAX, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration - 10, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); policy_engine_->OnTimerEvent(); @@ -2781,9 +2791,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_RentalAndLicense0_WithPlayback) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(LLONG_MAX, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(10, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); policy_engine_->OnTimerEvent(); @@ -2798,9 +2808,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_RentalAndLicense0_WithPlayback) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(0, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(0, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2841,9 +2851,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_Durations0) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(LLONG_MAX, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(LLONG_MAX, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2874,9 +2884,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_LicenseWithFutureStartTime) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(kLowDuration, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); EXPECT_FALSE(policy_engine_->CanDecryptContent(kKeyId)); @@ -2892,9 +2902,9 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_LicenseWithFutureStartTime) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(kLowDuration - 25, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration - 15, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -2945,10 +2955,10 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_Renew) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(kLowDuration - kLicenseRenewalRetryInterval, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration + 5 - license_renewal_delay - kLicenseRenewalRetryInterval - 15, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } @@ -3003,10 +3013,10 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_RenewWithFutureStartTime) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(kLowDuration, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration + 5 - license_renewal_delay - kLicenseRenewalRetryInterval - 20, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); policy_engine_->OnTimerEvent(); @@ -3019,10 +3029,10 @@ TEST_F(PolicyEngineQueryTest, QuerySuccess_RenewWithFutureStartTime) { EXPECT_EQ(QUERY_VALUE_TRUE, query_info[QUERY_KEY_RENEW_ALLOWED]); EXPECT_EQ(kLowDuration - 20, - ParseInt(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_LICENSE_DURATION_REMAINING])); EXPECT_EQ(kPlaybackDuration + 5 - license_renewal_delay - kLicenseRenewalRetryInterval - 40, - ParseInt(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); + std::stoll(query_info[QUERY_KEY_PLAYBACK_DURATION_REMAINING])); EXPECT_EQ(kRenewalServerUrl, query_info[QUERY_KEY_RENEWAL_SERVER_URL]); } diff --git a/core/test/test_base.cpp b/core/test/test_base.cpp index e4aeebc5..570bed46 100644 --- a/core/test/test_base.cpp +++ b/core/test/test_base.cpp @@ -11,7 +11,6 @@ #include #include -#include #include #include @@ -39,7 +38,7 @@ void show_menu(char* prog_name) { std::cout << " e.g. adb shell '" << prog_name << " --server=\"url\"'" << std::endl; - std::cout << " --verbose" << std::endl; + std::cout << " --verbose or -v" << std::endl; std::cout << " increase logging verbosity (may be repeated)" << std::endl << std::endl; @@ -226,10 +225,10 @@ void WvCdmTestBase::SetUp() { // dynamically using an environment variable. The model name will show up in // the license server logs as the part of the device idenfication as // "model_name". - std::stringstream ss; - ss << test_info->test_case_name() << "." << test_info->name(); + std::string model_name = + std::string(test_info->test_case_name()) + "." + test_info->name(); int overwrite = 1; // Set value even if already set. - setenv("MODEL_NAME", ss.str().c_str(), overwrite); + setenv("MODEL_NAME", model_name.c_str(), overwrite); CryptoSession::SetCryptoSessionFactory(new TestCryptoSessionFactory()); // TODO(fredgc): Add a test version of DeviceFiles. } @@ -355,7 +354,7 @@ bool WvCdmTestBase::Initialize(int argc, char **argv) { // Skip the first element, which is the program name. const std::vector args(argv + 1, argv + argc); for (const std::string& arg : args) { - if (arg == "--verbose") { + if (arg == "--verbose" || arg == "-v") { ++verbosity; } else if (arg == "--no_filter") { filter_tests = false; diff --git a/core/test/test_printers.cpp b/core/test/test_printers.cpp index fe30366d..c7af0f8c 100644 --- a/core/test/test_printers.cpp +++ b/core/test/test_printers.cpp @@ -247,6 +247,9 @@ void PrintTo(const enum CdmResponseType& value, ::std::ostream* os) { case KEYSET_ID_NOT_FOUND_3: *os << "KEYSET_ID_NOT_FOUND_3"; break; + case KEYSET_ID_NOT_FOUND_4: + *os << "KEYSET_ID_NOT_FOUND_4"; + break; case LICENSE_ID_NOT_FOUND: *os << "LICENSE_ID_NOT_FOUND"; break; diff --git a/core/test/usage_table_header_unittest.cpp b/core/test/usage_table_header_unittest.cpp index 42a258df..c8da9ac6 100644 --- a/core/test/usage_table_header_unittest.cpp +++ b/core/test/usage_table_header_unittest.cpp @@ -290,6 +290,7 @@ class MockUsageTableHeader : public UsageTableHeader { using ::testing::_; using ::testing::AllOf; using ::testing::AtMost; +using ::testing::DoAll; using ::testing::ElementsAreArray; using ::testing::Ge; using ::testing::Invoke; diff --git a/oemcrypto/include/OEMCryptoCENC.h b/oemcrypto/include/OEMCryptoCENC.h index f7a560c7..fffb93a9 100644 --- a/oemcrypto/include/OEMCryptoCENC.h +++ b/oemcrypto/include/OEMCryptoCENC.h @@ -8,7 +8,7 @@ * Reference APIs needed to support Widevine's crypto algorithms. * * See the document "WV Modular DRM Security Integration Guide for Common - * Encryption (CENC) -- version 15" for a description of this API. You + * Encryption (CENC) -- version 15.2" for a description of this API. You * can find this document in the widevine repository as * docs/WidevineModularDRMSecurityIntegrationGuideforCENC_v15.pdf * Changes between different versions of this API are documented in the files @@ -339,9 +339,9 @@ typedef enum OEMCrypto_Clock_Security_Level { typedef uint8_t RSA_Padding_Scheme; // RSASSA-PSS with SHA1. -const RSA_Padding_Scheme kSign_RSASSA_PSS = 0x1; +#define kSign_RSASSA_PSS ((RSA_Padding_Scheme)0x1) // PKCS1 with block type 1 padding (only). -const RSA_Padding_Scheme kSign_PKCS1_Block1 = 0x2; +#define kSign_PKCS1_Block1 ((RSA_Padding_Scheme)0x2) /* * OEMCrypto_HDCP_Capability is used in the key control block to enforce HDCP @@ -376,9 +376,9 @@ typedef enum OEMCrypto_ProvisioningMethod { /* * Flags indicating full decrypt path hash supported. */ -const uint32_t OEMCrypto_Hash_Not_Supported = 0; -const uint32_t OEMCrypto_CRC_Clear_Buffer = 1; -const uint32_t OEMCrypto_Partner_Defined_Hash = 2; +#define OEMCrypto_Hash_Not_Supported 0 +#define OEMCrypto_CRC_Clear_Buffer 1 +#define OEMCrypto_Partner_Defined_Hash 2 /* * Return values from OEMCrypto_GetAnalogOutputFlags. @@ -800,13 +800,17 @@ OEMCryptoResult OEMCrypto_DeriveKeysFromSessionKey( * before requesting more nonces, then OEMCrypto will reset the error * condition and generate valid nonces again. * + * To prevent Birthday Paradox attacks, OEMCrypto shall verify that the value + * generated is not in this session's nonce table, and that it is not in the + * nonce table of any other session. + * * Parameters: * [in] session: handle for the session to be used. * [out] nonce: pointer to memory to receive the computed nonce. * * Results: - * nonce: the nonce is also stored in secure memory. At least 4 nonces should - * be stored for each session. + * nonce: the nonce is also stored in secure memory. Each session should + * store 4 nonces. * * Returns: * OEMCrypto_SUCCESS success @@ -817,11 +821,9 @@ OEMCryptoResult OEMCrypto_DeriveKeysFromSessionKey( * OEMCrypto_ERROR_SYSTEM_INVALIDATED * * Threading: - * This is a "Session Function" and may be called simultaneously with session - * functions for other sessions but not simultaneously with other functions - * for this session. It will not be called simultaneously with initialization - * or usage table functions. It is as if the CDM holds a write lock for this - * session, and a read lock on the OEMCrypto system. + * This is a "Session Initialization Function" and will not be called + * simultaneously with any other function, as if the CDM holds a write lock + * on the OEMCrypto system. * * Version: * This method changed in API version 5. @@ -1049,6 +1051,9 @@ OEMCryptoResult OEMCrypto_LoadSRM(const uint8_t* buffer, size_t buffer_length); * entry is marked as "inactive" (either kInactiveUsed or * kInactiveUnused), then the keys are not loaded, and the error * OEMCrypto_ERROR_LICENSE_INACTIVE is returned. + * 12. The data in enc_mac_keys_iv is not identical to the 16 bytes before + * enc_mac_keys. If it is, return OEMCrypto_ERROR_INVALID_CONTEXT. + * * Usage Table and Provider Session Token (pst) * * If a key control block has a nonzero value for Replay_Control, then all @@ -1627,8 +1632,8 @@ OEMCryptoResult OEMCrypto_SelectKey(OEMCrypto_SESSION session, * 6. If the current session has an entry in the Usage Table, and the * status of that entry is either kInactiveUsed or kInactiveUnused, then * return the error OEMCrypto_ERROR_LICENSE_INACTIVE. - * 7. If an Decrypt Hash has been initialized via OEMCrypto_SetDecryptHash, - * and the current key's control block does not have the + * 7. If a Decrypt Hash has been initialized via OEMCrypto_SetDecryptHash, + * and the current key's control block does not have the * Allow_Hash_Verification bit set, then do not compute a hash and * return OEMCrypto_ERROR_UNKNOWN_FAILURE. * If the flag is_encrypted is false, then no verification is performed. This @@ -2201,7 +2206,7 @@ OEMCryptoResult OEMCrypto_InstallKeyboxOrOEMCert(const uint8_t* rot, * Version: * This method is new API version 12. */ -OEMCrypto_ProvisioningMethod OEMCrypto_GetProvisioningMethod(); +OEMCrypto_ProvisioningMethod OEMCrypto_GetProvisioningMethod(void); /* * OEMCrypto_IsKeyboxOrOEMCertValid @@ -2257,7 +2262,7 @@ OEMCryptoResult OEMCrypto_IsKeyboxOrOEMCertValid(void); * system upgrade. * * This function is optional but recommended for Provisioning 3.0 in API v15. - * It may be required for future version of this API. + * It may be required for a future version of this API. * * Parameters: * [out] deviceId - pointer to the buffer that receives the Device ID @@ -2459,7 +2464,7 @@ OEMCryptoResult OEMCrypto_GetRandom(uint8_t* randomData, size_t dataLength); * Version: * This method changed in each API version. */ -uint32_t OEMCrypto_APIVersion(); +uint32_t OEMCrypto_APIVersion(void); /* * OEMCrypto_BuildInformation @@ -2497,7 +2502,7 @@ uint32_t OEMCrypto_APIVersion(); * Version: * This method changed in each API version. */ -const char* OEMCrypto_BuildInformation(); +const char* OEMCrypto_BuildInformation(void); /* * OEMCrypto_Security_Patch_Level @@ -2524,7 +2529,7 @@ const char* OEMCrypto_BuildInformation(); * Version: * This method was introduced in API version 11. */ -uint8_t OEMCrypto_Security_Patch_Level(); +uint8_t OEMCrypto_Security_Patch_Level(void); /* * OEMCrypto_SecurityLevel @@ -2550,7 +2555,7 @@ uint8_t OEMCrypto_Security_Patch_Level(); * Version: * This method changed in API version 6. */ -const char* OEMCrypto_SecurityLevel(); +const char* OEMCrypto_SecurityLevel(void); /* * OEMCrypto_GetHDCPCapability @@ -2565,12 +2570,6 @@ const char* OEMCrypto_SecurityLevel(); * instead of HDMI output. Notice that HDCP must use flag Type 1: all * downstream devices will also use the same version or higher. * - * The current HDCP should be the minimum value of any display currently - * connected through any channel, either through HDMI or a supported wireless - * format. The current value can be used by the application or server to - * decide which license can currently be used. If the key control block - * requires the current HDCP level, we expect the key to be usable. - * * The maximum HDCP level should be the maximum value that the device can * enforce. For example, if the device has an HDCP 1.0 port and an HDCP 2.0 * port, and the first port can be disabled, then the maximum is HDCP 2.0. If @@ -2581,6 +2580,30 @@ const char* OEMCrypto_SecurityLevel(); * user intends to view the content on a local display. The user will want to * download the higher quality content. * + * The current HDCP level should be the level of HDCP currently negotiated + * with any connected receivers or repeaters either through HDMI or a + * supported wireless format. If multiple ports are connected, the current + * level should be the minimum HDCP level of all ports. If the key control + * block requires an HDCP level equal to or lower than the current HDCP + * level, the key is expected to be usable. If the key control block requires + * a higher HDCP level, the key is expected to be forbidden. + * + * When a key has version HDCP_V2_3 required in the key control block, the + * transmitter must have HDCP version 2.3 and have negotiated a connection + * with a version 2.3 receiver or repeater. The transmitter must configure + * the content stream to be Type 1. Since the transmitter cannot distinguish + * between 2.2 and 2.3 downstream receivers when connected to a repeater, it + * may transmit to both 2.2 and 2.3 receivers, but not 2.1 receivers. + * + * For example, if the transmitter is 2.3, and is connected to a receiver + * that supports 2.3 then the current level is HDCP_V2_3. If the transmitter + * is 2.3 and is connected to a 2.3 repeater, the current level is HDCP_V2_3 + * even though the repeater can negotiate a connection with a 2.2 downstream + * receiver for a Type 1 Content Stream. + * + * As another example, if the transmitter can support 2.3, but a receiver + * supports 2.0, then the current level is HDCP_V2. + * * When a license requires HDCP, a device may use a wireless protocol to * connect to a display only if that protocol supports the version of HDCP as * required by the license. Both WirelessHD (formerly WiFi Display) and @@ -2633,7 +2656,7 @@ OEMCryptoResult OEMCrypto_GetHDCPCapability(OEMCrypto_HDCP_Capability* current, * Version: * This method changed in API version 9. */ -bool OEMCrypto_SupportsUsageTable(); +bool OEMCrypto_SupportsUsageTable(void); /* * OEMCrypto_IsAntiRollbackHwPresent @@ -2661,7 +2684,7 @@ bool OEMCrypto_SupportsUsageTable(); * Version: * This method is new in API version 10. */ -bool OEMCrypto_IsAntiRollbackHwPresent(); +bool OEMCrypto_IsAntiRollbackHwPresent(void); /* * OEMCrypto_GetNumberOfOpenSessions @@ -2762,7 +2785,7 @@ OEMCryptoResult OEMCrypto_GetMaxNumberOfSessions(size_t* max); * Version: * This method changed in API version 13. */ -uint32_t OEMCrypto_SupportedCertificates(); +uint32_t OEMCrypto_SupportedCertificates(void); /* * OEMCrypto_IsSRMUpdateSupported @@ -2789,7 +2812,7 @@ uint32_t OEMCrypto_SupportedCertificates(); * Version: * This method changed in API version 13. */ -bool OEMCrypto_IsSRMUpdateSupported(); +bool OEMCrypto_IsSRMUpdateSupported(void); /* * OEMCrypto_GetCurrentSRMVersion @@ -2856,7 +2879,7 @@ OEMCryptoResult OEMCrypto_GetCurrentSRMVersion(uint16_t* version); * Version: * This method is new in API version 14. */ -uint32_t OEMCrypto_GetAnalogOutputFlags(); +uint32_t OEMCrypto_GetAnalogOutputFlags(void); /* * OEMCrypto_ResourceRatingTier @@ -2865,7 +2888,7 @@ uint32_t OEMCrypto_GetAnalogOutputFlags(); * This function returns a positive number indicating which resource rating * it supports. This value will bubble up to the application level as a * property. This will allow applications to estimate what resolution and - * bandwidth the device expects to support. + * bandwidth the device is expected to support. * * OEMCrypto unit tests and Android GTS tests will verify that devices do * support the resource values specified in the table below at the tier @@ -2925,8 +2948,6 @@ uint32_t OEMCrypto_GetAnalogOutputFlags(); * +-----------------------------------+-----------+------------+-----------+ * |Number of keys per session |4 |20 |20 | * +-----------------------------------+-----------+------------+-----------+ - * |Simultaneous secure playback |1 |2 |2 | - * +-----------------------------------+-----------+------------+-----------+ * |Decrypted Frames per Second |30 fps SD |30 fps HD |60 fps HD | * +-----------------------------------+-----------+------------+-----------+ * @@ -2945,7 +2966,7 @@ uint32_t OEMCrypto_GetAnalogOutputFlags(); * Version: * This method is new in API version 15. */ -uint32_t OEMCrypto_ResourceRatingTier(); +uint32_t OEMCrypto_ResourceRatingTier(void); /* * OEMCrypto_RewrapDeviceRSAKey30 @@ -3306,7 +3327,7 @@ OEMCryptoResult OEMCrypto_LoadDeviceRSAKey(OEMCrypto_SESSION session, * Version: * This method is new in API version 10. */ -OEMCryptoResult OEMCrypto_LoadTestRSAKey(); +OEMCryptoResult OEMCrypto_LoadTestRSAKey(void); /* * OEMCrypto_GenerateRSASignature @@ -3648,8 +3669,10 @@ OEMCryptoResult OEMCrypto_UpdateUsageEntry(OEMCrypto_SESSION session, * means that the state of the usage entry is changed to InactiveUsed if it * was Active, or InactiveUnused if it was Unused. This also increments the * entry's generation number, and the header's master generation number. The - * entry's flag ForbidReport will be set. This flag prevents an application - * from generating a report of a deactivated license without first saving the + * corresponding generation number in the usage table header is also + * incremented so that it matches the one in the entry. The entry's flag + * ForbidReport will be set. This flag prevents an application from + * generating a report of a deactivated license without first saving the * entry. * * It is allowed to call this function multiple times. If the state is @@ -3954,14 +3977,14 @@ OEMCryptoResult OEMCrypto_CopyOldUsageEntry(OEMCrypto_SESSION session, * Version: * This method is new in API version 13. */ -OEMCryptoResult OEMCrypto_DeleteOldUsageTable(); +OEMCryptoResult OEMCrypto_DeleteOldUsageTable(void); /* * OEMCrypto_RemoveSRM * * Description: - * Delete the current SRM. Any valid SRM, regardless of version number, will - * be installable after this via OEMCrypto_LoadSRM. + * Delete the current SRM. Any valid SRM, regardless of its version number, + * will be installable after this via OEMCrypto_LoadSRM. * * This function should not be implemented on production devices, and will * only be used to verify unit tests on a test device. @@ -3981,7 +4004,7 @@ OEMCryptoResult OEMCrypto_DeleteOldUsageTable(); * Version: * This method is new in API version 13. */ -OEMCryptoResult OEMCrypto_RemoveSRM(); +OEMCryptoResult OEMCrypto_RemoveSRM(void); /* * OEMCrypto_CreateOldUsageEntry @@ -4027,7 +4050,7 @@ OEMCryptoResult OEMCrypto_CreateOldUsageEntry(uint64_t time_since_license_receiv * supported. OEMCrypto is not required by Google to support this feature, * but support will greatly improve automated testing. A hash type of * OEMCrypto_CRC_Clear_Buffer = 1 means the device will be able to compute - * the CRC32 checksum of the decrypted content in the secure buffer after a + * the CRC 32 checksum of the decrypted content in the secure buffer after a * call to OEMCrypto_DecryptCENC. Google intends to provide test applications * on some platforms, such as Android, that will automate decryption testing * using the CRC 32 checksum of all frames in some test content. @@ -4055,7 +4078,7 @@ OEMCryptoResult OEMCrypto_CreateOldUsageEntry(uint64_t time_since_license_receiv * Version: * This method is new in API version 15. */ -uint32_t OEMCrypto_SupportsDecryptHash(); +uint32_t OEMCrypto_SupportsDecryptHash(void); /* * OEMCrypto_SetDecryptHash diff --git a/oemcrypto/test/oec_device_features.cpp b/oemcrypto/test/oec_device_features.cpp index bad4c55a..98eae18e 100644 --- a/oemcrypto/test/oec_device_features.cpp +++ b/oemcrypto/test/oec_device_features.cpp @@ -7,8 +7,13 @@ #include "oec_device_features.h" #include -#include -#include + +#ifdef _WIN32 +# include +#else +# include +# include +#endif #include @@ -18,6 +23,43 @@ namespace wvoec { DeviceFeatures global_features; +bool CanChangeTime() { +#ifdef _WIN32 + LUID desired_id; + if (!LookupPrivilegeValue(nullptr, SE_SYSTEMTIME_NAME, &desired_id)) + return false; + HANDLE token; + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &token)) + return false; + std::unique_ptr safe_token(token, &CloseHandle); + + // This queries all the permissions given to the token to determine if we can + // change the system time. Note this is subtly different from PrivilegeCheck + // as that only checks "enabled" privileges; even with admin rights, the + // privilege is default disabled, even when granted. + + DWORD size = 0; + // Determine how big we need to allocate first. + GetTokenInformation(token, TokenPrivileges, nullptr, 0, &size); + // Since TOKEN_PRIVILEGES uses a variable-length array, we need to use malloc + std::unique_ptr privileges( + (TOKEN_PRIVILEGES*)malloc(size), &free); + if (privileges && GetTokenInformation(token, TokenPrivileges, + privileges.get(), size, &size)) { + for (int i = 0; i < privileges->PrivilegeCount; i++) { + if (privileges->Privileges[i].Luid.HighPart == desired_id.HighPart && + privileges->Privileges[i].Luid.LowPart == desired_id.LowPart) { + return true; + } + } + } + + return false; +#else + return getuid() == 0; +#endif +} + void DeviceFeatures::Initialize(bool is_cast_receiver, bool force_load_test_keybox) { cast_receiver = is_cast_receiver; @@ -153,37 +195,16 @@ std::string DeviceFeatures::RestrictFilter(const std::string& initial_filter) { if (provisioning_method != OEMCrypto_OEMCertificate) FilterOut(&filter, "*Prov30*"); if (!supports_rsa_3072) FilterOut(&filter, "*RSAKey3072*"); - if (api_version < 14) { - // Because API 13 uses an old hard coded test keybox, none of these tests - // will pass. Partners who wish to test with a v13 OEMCrypto should use - // code on an older v13 branch. - printf("These unit tests are designed for OEMCrypto API 15 and above.\n"); - printf("This device has an OEMCrypto with API version %d.\n", api_version); - printf("To verify correctness, please build unit tests from a " - "compatible branch.\n"); - FilterOut(&filter, "*API09*"); - FilterOut(&filter, "*API10*"); - FilterOut(&filter, "*API11*"); - FilterOut(&filter, "*API12*"); - FilterOut(&filter, "*API13*"); - FilterOut(&filter, "*API14*"); - FilterOut(&filter, "*TestKeyboxTest*"); - FilterOut(&filter, "*SessionTest*"); - FilterOut(&filter, "*UsageTable*"); - FilterOut(&filter, "*GenericCrypto*"); - FilterOut(&filter, "*LoadsCertificate*"); - FilterOut(&filter, "*UsesCertificate*"); - // We also expect some CDM tests to fail without a new test keybox: - FilterOut(&filter, "*WvCdmRequestLicenseTest*"); - FilterOut(&filter, "*WvGenericOperations*"); - FilterOut(&filter, "*WvCdmEngine*"); - FilterOut(&filter, "*Cdm/WvCdm*"); - FilterOut(&filter, "*Cdm/WvHls*"); - } + if (api_version < 9) FilterOut(&filter, "*API09*"); + if (api_version < 10) FilterOut(&filter, "*API10*"); + if (api_version < 11) FilterOut(&filter, "*API11*"); + if (api_version < 12) FilterOut(&filter, "*API12*"); + if (api_version < 13) FilterOut(&filter, "*API13*"); + if (api_version < 14) FilterOut(&filter, "*API14*"); if (api_version < 15) FilterOut(&filter, "*API15*"); // Some tests may require root access. If user is not root, filter these tests // out. - if (getuid()) { + if (!CanChangeTime()) { FilterOut(&filter, "UsageTableTest.TimeRollbackPrevention"); } // Performance tests take a long time. Filter them out if they are not diff --git a/oemcrypto/test/oec_session_util.cpp b/oemcrypto/test/oec_session_util.cpp index 4ed98c50..b041a034 100644 --- a/oemcrypto/test/oec_session_util.cpp +++ b/oemcrypto/test/oec_session_util.cpp @@ -22,7 +22,6 @@ #include #include #include -#include #include #include "OEMCryptoCENC.h" @@ -539,6 +538,7 @@ void Session::FillSimpleMessage(uint32_t duration, uint32_t control, uint32_t nonce, const std::string& pst) { EXPECT_EQ( 1, GetRandBytes(license_.mac_key_iv, sizeof(license_.mac_key_iv))); + memset(license_.padding, 0, sizeof(license_.padding)); EXPECT_EQ(1, GetRandBytes(license_.mac_keys, sizeof(license_.mac_keys))); for (unsigned int i = 0; i < num_keys_; i++) { memset(license_.keys[i].key_id, 0, kTestKeyIdMaxLength); @@ -554,9 +554,9 @@ void Session::FillSimpleMessage(uint32_t duration, uint32_t control, if (global_features.api_version >= 12) { // For version 12 and above, we require OEMCrypto to handle kcNN for all // licenses. - std::stringstream stream; - stream << "kc" << global_features.api_version; - memcpy(license_.keys[i].control.verification, stream.str().c_str(), 4); + std::string kcVersion = + "kc" + std::to_string(global_features.api_version); + memcpy(license_.keys[i].control.verification, kcVersion.c_str(), 4); } else if (control & wvoec::kControlSecurityPatchLevelMask) { // For versions before 12, we require the special key control block only // when there are newer features present. @@ -598,9 +598,9 @@ void Session::FillSimpleEntitlementMessage( if (global_features.api_version >= 12) { // For version 12 and above, we require OEMCrypto to handle kcNN for all // licenses. - std::stringstream stream; - stream << "kc" << global_features.api_version; - memcpy(license_.keys[i].control.verification, stream.str().c_str(), 4); + std::string kcVersion = + "kc" + std::to_string(global_features.api_version); + memcpy(license_.keys[i].control.verification, kcVersion.c_str(), 4); } else if (control & wvoec::kControlSecurityPatchLevelMask) { // For versions before 12, we require the special key control block only // when there are newer features present. @@ -631,10 +631,10 @@ void Session::FillRefreshMessage(size_t key_count, uint32_t control_bits, if (global_features.api_version >= 12) { // For version 12 and above, we require OEMCrypto to handle kcNN for all // licenses. - std::stringstream stream; - stream << "kc" << global_features.api_version; + std::string kcVersion = + "kc" + std::to_string(global_features.api_version); memcpy(encrypted_license().keys[i].control.verification, - stream.str().c_str(), 4); + kcVersion.c_str(), 4); } else { // For versions before 12, we require the special key control block only // when there are newer features present. @@ -1268,7 +1268,6 @@ void Session::GenerateReport(const std::string& pst, ASSERT_EQ(OEMCrypto_ERROR_SHORT_BUFFER, sts); } if (sts == OEMCrypto_ERROR_SHORT_BUFFER) { - ASSERT_EQ(wvcdm::Unpacked_PST_Report::report_size(pst.length()), length); pst_report_buffer_.assign(length, 0xFF); // Fill with garbage values. } sts = OEMCrypto_ReportUsage(session_id(), @@ -1278,7 +1277,7 @@ void Session::GenerateReport(const std::string& pst, if (expected_result != OEMCrypto_SUCCESS) { return; } - ASSERT_EQ(pst_report_buffer_.size(), length); + EXPECT_EQ(wvcdm::Unpacked_PST_Report::report_size(pst.length()), length); vector computed_signature(SHA_DIGEST_LENGTH); unsigned int sig_len = SHA_DIGEST_LENGTH; HMAC(EVP_sha1(), mac_key_client_.data(), mac_key_client_.size(), @@ -1359,6 +1358,9 @@ void Session::GenerateVerifyReport(const std::string& pst, Test_PST_Report expected(pst, status); ASSERT_NO_FATAL_FAILURE(VerifyReport(expected, time_license_received, time_first_decrypt, time_last_decrypt)); + // The PST report was signed above. Below we verify that the entire message + // that is sent to the server will be signed by the right mac keys. + ASSERT_NO_FATAL_FAILURE(VerifyClientSignature()); } void Session::CreateOldEntry(const Test_PST_Report& report) { diff --git a/oemcrypto/test/oec_session_util.h b/oemcrypto/test/oec_session_util.h index 4f1ab1b7..f1627601 100644 --- a/oemcrypto/test/oec_session_util.h +++ b/oemcrypto/test/oec_session_util.h @@ -81,6 +81,7 @@ typedef struct { struct MessageData { MessageKeyData keys[kMaxNumKeys]; uint8_t mac_key_iv[KEY_IV_SIZE]; + uint8_t padding[KEY_IV_SIZE]; uint8_t mac_keys[2 * MAC_KEY_SIZE]; uint8_t pst[kMaxPSTLength]; }; diff --git a/oemcrypto/test/oemcrypto_test.cpp b/oemcrypto/test/oemcrypto_test.cpp index 21da261c..480149d9 100644 --- a/oemcrypto/test/oemcrypto_test.cpp +++ b/oemcrypto/test/oemcrypto_test.cpp @@ -13,16 +13,20 @@ #include #include #include -#include #include +#ifdef _WIN32 +# include +#else +# include +#endif + #include #include #include #include #include #include -#include #include #include @@ -87,6 +91,37 @@ int GetRandBytes(unsigned char* buf, int num) { // returns 1 on success, -1 if not supported, or 0 if other failure. return RAND_bytes(buf, num); } + +/** @return The Unix time of the given time point. */ +template +uint64_t UnixTime(const std::chrono::time_point& point) { + return point.time_since_epoch() / std::chrono::seconds(1); +} + +#ifdef _WIN32 +using NativeTime = SYSTEMTIME; +#else +using NativeTime = timeval; +#endif + +void AddNativeTime(int64_t delta_seconds, NativeTime* time) { +#ifdef _WIN32 + // See remarks from this for why this series is used. + // https://msdn.microsoft.com/en-us/f77cdf86-0f97-4a89-b565-95b46fa7d65b + FILETIME file_time; + ASSERT_TRUE(SystemTimeToFileTime(time, &file_time)); + uint64_t long_time = static_cast(file_time.dwLowDateTime) | + (static_cast(file_time.dwHighDateTime) << 32); + long_time += delta_seconds * 1e7; // long_time is in 100-nanosecond intervals. + file_time.dwLowDateTime = long_time & ((1ull << 32) - 1); + file_time.dwHighDateTime = long_time >> 32; + ASSERT_TRUE(FileTimeToSystemTime(&file_time, time)); +#else + time->tv_sec += delta_seconds; +#endif +} + } // namespace class OEMCryptoClientTest : public ::testing::Test, public SessionUtil { @@ -95,7 +130,6 @@ class OEMCryptoClientTest : public ::testing::Test, public SessionUtil { void SetUp() override { ::testing::Test::SetUp(); - wvcdm::g_cutoff = wvcdm::LOG_INFO; const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info(); LOGD("Running test %s.%s", test_info->test_case_name(), test_info->name()); @@ -871,6 +905,24 @@ TEST_F(OEMCryptoSessionTests, LoadKeyNoNonce) { ASSERT_NO_FATAL_FAILURE(s.LoadTestKeys()); } +// Verify that a second license may be not be loaded in a session. +TEST_F(OEMCryptoSessionTests, LoadKeyNoNonceTwice) { + Session s; + ASSERT_NO_FATAL_FAILURE(s.open()); + ASSERT_NO_FATAL_FAILURE(InstallTestSessionKeys(&s)); + ASSERT_NO_FATAL_FAILURE(s.FillSimpleMessage(kDuration, 0, 42)); + ASSERT_NO_FATAL_FAILURE(s.EncryptAndSign()); + ASSERT_NO_FATAL_FAILURE(s.LoadTestKeys()); + ASSERT_NO_FATAL_FAILURE(s.EncryptAndSign()); + ASSERT_NE( + OEMCrypto_SUCCESS, + OEMCrypto_LoadKeys(s.session_id(), s.message_ptr(), s.message_size(), + s.signature().data(), s.signature().size(), + s.enc_mac_keys_iv_substr(), s.enc_mac_keys_substr(), + s.num_keys(), s.key_array(), s.pst_substr(), + GetSubstring(), OEMCrypto_ContentLicense)); +} + // Verify that a license may be loaded with a nonce. TEST_F(OEMCryptoSessionTests, LoadKeyWithNonce) { Session s; @@ -882,6 +934,24 @@ TEST_F(OEMCryptoSessionTests, LoadKeyWithNonce) { ASSERT_NO_FATAL_FAILURE(s.LoadTestKeys()); } +// Verify that a second license may be not be loaded in a session. +TEST_F(OEMCryptoSessionTests, LoadKeyWithNonceTwice) { + Session s; + ASSERT_NO_FATAL_FAILURE(s.open()); + ASSERT_NO_FATAL_FAILURE(InstallTestSessionKeys(&s)); + ASSERT_NO_FATAL_FAILURE( + s.FillSimpleMessage(0, wvoec::kControlNonceEnabled, s.get_nonce())); + ASSERT_NO_FATAL_FAILURE(s.EncryptAndSign()); + ASSERT_NO_FATAL_FAILURE(s.LoadTestKeys()); + ASSERT_NE( + OEMCrypto_SUCCESS, + OEMCrypto_LoadKeys(s.session_id(), s.message_ptr(), s.message_size(), + s.signature().data(), s.signature().size(), + s.enc_mac_keys_iv_substr(), s.enc_mac_keys_substr(), + s.num_keys(), s.key_array(), s.pst_substr(), + GetSubstring(), OEMCrypto_ContentLicense)); +} + // This asks for several nonce. This simulates several license requests being // lost. OEMCrypto is required to keep up to four nonce in the nonce table. TEST_F(OEMCryptoSessionTests, LoadKeySeveralNonce) { @@ -1179,6 +1249,27 @@ TEST_F(OEMCryptoSessionTests, LoadKeyWithBadRange7) { ASSERT_NE(OEMCrypto_SUCCESS, sts); } +// The IV should not be identical to the data right before the encrypted mac +// keys. +TEST_F(OEMCryptoSessionTests, LoadKeyWithSuspiciousIV) { + Session s; + ASSERT_NO_FATAL_FAILURE(s.open()); + ASSERT_NO_FATAL_FAILURE(InstallTestSessionKeys(&s)); + ASSERT_NO_FATAL_FAILURE(s.FillSimpleMessage(0, 0, 0)); + // This is suspicious: the data right before the mac keys is identical to the + // iv. + memcpy(s.license().padding, s.license().mac_key_iv, + sizeof(s.license().padding)); + ASSERT_NO_FATAL_FAILURE(s.EncryptAndSign()); + + OEMCryptoResult sts = OEMCrypto_LoadKeys( + s.session_id(), s.message_ptr(), s.message_size(), s.signature().data(), + s.signature().size(), s.enc_mac_keys_iv_substr(), s.enc_mac_keys_substr(), + s.num_keys(), s.key_array(), GetSubstring(), GetSubstring(), + OEMCrypto_ContentLicense); + ASSERT_NE(OEMCrypto_SUCCESS, sts); +} + // Test that LoadKeys fails when a key is loaded with no key control block. TEST_F(OEMCryptoSessionTests, LoadKeyWithNullKeyControl) { Session s; @@ -1483,10 +1574,36 @@ TEST_F(OEMCryptoSessionTests, SelectKeyNotThereAPI15) { ASSERT_NO_FATAL_FAILURE(s.EncryptAndSign()); ASSERT_NO_FATAL_FAILURE(s.LoadTestKeys()); const char* key_id = "no_key"; - ASSERT_EQ(OEMCrypto_ERROR_NO_CONTENT_KEY, - OEMCrypto_SelectKey( - s.session_id(), reinterpret_cast(key_id), - strlen(key_id), OEMCrypto_CipherMode_CTR)); + OEMCryptoResult sts = OEMCrypto_SelectKey( + s.session_id(), reinterpret_cast(key_id), strlen(key_id), + OEMCrypto_CipherMode_CTR); + if (sts != OEMCrypto_SUCCESS) { + EXPECT_EQ(OEMCrypto_ERROR_NO_CONTENT_KEY, sts); + } else { + // Delayed error code. If select key was a success, then we should + // eventually see the error when we decrypt. + vector in_buffer(256); + for (size_t i = 0; i < in_buffer.size(); i++) in_buffer[i] = i % 256; + vector encryptionIv(AES_BLOCK_SIZE); + EXPECT_EQ(1, GetRandBytes(encryptionIv.data(), AES_BLOCK_SIZE)); + // Describe the output + vector out_buffer(in_buffer.size()); + const bool is_encrypted = true; + OEMCrypto_DestBufferDesc destBuffer; + destBuffer.type = OEMCrypto_BufferType_Clear; + destBuffer.buffer.clear.address = out_buffer.data(); + destBuffer.buffer.clear.max_length = out_buffer.size(); + OEMCrypto_CENCEncryptPatternDesc pattern; + pattern.encrypt = 0; + pattern.skip = 0; + pattern.offset = 0; + // Decrypt the data + sts = OEMCrypto_DecryptCENC( + s.session_id(), in_buffer.data(), in_buffer.size(), is_encrypted, + encryptionIv.data(), 0, &destBuffer, &pattern, + OEMCrypto_FirstSubsample | OEMCrypto_LastSubsample); + EXPECT_EQ(OEMCrypto_ERROR_NO_CONTENT_KEY, sts); + } } // After loading keys, we should be able to query the key control block. If we @@ -1952,6 +2069,18 @@ class OEMCryptoSessionTestsDecryptTests pattern_ = ::testing::get<0>(GetParam()); cipher_mode_ = ::testing::get<1>(GetParam()); decrypt_inplace_ = ::testing::get<2>(GetParam()); + verify_crc_ = global_features.supports_crc; + // Pick a random key. + EXPECT_EQ(1, GetRandBytes(key_, AES_BLOCK_SIZE)); + // Pick a random starting iv. Some tests override this before using it. + starting_iv_.resize(AES_BLOCK_SIZE); + EXPECT_EQ(1, GetRandBytes(starting_iv_.data(), starting_iv_.size())); + total_size_ = -1; + } + + virtual void TearDown() { + ASSERT_NO_FATAL_FAILURE(session_.close()); + OEMCryptoSessionTests::TearDown(); } void FindTotalSize() { @@ -1962,24 +2091,47 @@ class OEMCryptoSessionTestsDecryptTests } } - void EncryptData(const vector& key, - const vector& starting_iv, - const vector& in_buffer, - vector* out_buffer) { + // Set up the input buffer and output buffer. + // This should be called after FindTotalSize(). + void MakeBuffers() { + ASSERT_GT(total_size_, 0u); + encrypted_buffer_.resize(total_size_); + truth_buffer_.resize(total_size_); + for (size_t i = 0; i < total_size_; i++) truth_buffer_[i] = i % 256; + output_descriptor_.type = OEMCrypto_BufferType_Clear; + if (decrypt_inplace_) { + output_descriptor_.buffer.clear.address = encrypted_buffer_.data(); + } else { + // Add some padding to verify there is no overrun. + clear_buffer_.resize(total_size_ + 16, 0xaa); + output_descriptor_.buffer.clear.address = clear_buffer_.data(); + } + output_descriptor_.buffer.clear.max_length = total_size_; + } + + void UpdateOutputOffset(size_t offset) { + if (decrypt_inplace_) { + output_descriptor_.buffer.clear.address = + encrypted_buffer_.data() + offset; + } else { + output_descriptor_.buffer.clear.address = clear_buffer_.data() + offset; + } + output_descriptor_.buffer.clear.max_length = total_size_ - offset; + } + + void EncryptData() { AES_KEY aes_key; - AES_set_encrypt_key(key.data(), AES_BLOCK_SIZE * 8, &aes_key); - out_buffer->resize(in_buffer.size()); + AES_set_encrypt_key(key_, AES_BLOCK_SIZE * 8, &aes_key); uint8_t iv[AES_BLOCK_SIZE]; // Current iv. - - memcpy(iv, starting_iv.data(), AES_BLOCK_SIZE); + memcpy(iv, starting_iv_.data(), AES_BLOCK_SIZE); size_t buffer_index = 0; // byte index into in and out. size_t block_offset = 0; // byte index into current block. for (size_t i = 0; i < subsample_size_.size(); i++) { // Copy clear content. if (subsample_size_[i].clear_size > 0) { - memcpy(&(*out_buffer)[buffer_index], &in_buffer[buffer_index], + memcpy(&encrypted_buffer_[buffer_index], &truth_buffer_[buffer_index], subsample_size_[i].clear_size); buffer_index += subsample_size_[i].clear_size; } @@ -2006,15 +2158,17 @@ class OEMCryptoSessionTestsDecryptTests // can put whatever we want in the output buffer. if (skip_block || ((cipher_mode_ == OEMCrypto_CipherMode_CBC) && (size < AES_BLOCK_SIZE))) { - memcpy(&(*out_buffer)[buffer_index], &in_buffer[buffer_index], size); + memcpy(&encrypted_buffer_[buffer_index], &truth_buffer_[buffer_index], + size); block_offset = 0; // Next block should be complete. } else { if (cipher_mode_ == OEMCrypto_CipherMode_CTR) { uint8_t aes_output[AES_BLOCK_SIZE]; AES_encrypt(iv, aes_output, &aes_key); for (size_t n = 0; n < size; n++) { - (*out_buffer)[buffer_index + n] = - aes_output[n + block_offset] ^ in_buffer[buffer_index + n]; + encrypted_buffer_[buffer_index + n] = + aes_output[n + block_offset] ^ + truth_buffer_[buffer_index + n]; } if (size + block_offset < AES_BLOCK_SIZE) { // Partial block. Don't increment iv. Compute next block offset. @@ -2029,10 +2183,10 @@ class OEMCryptoSessionTestsDecryptTests } else { uint8_t aes_input[AES_BLOCK_SIZE]; for (size_t n = 0; n < size; n++) { - aes_input[n] = in_buffer[buffer_index + n] ^ iv[n]; + aes_input[n] = truth_buffer_[buffer_index + n] ^ iv[n]; } - AES_encrypt(aes_input, &(*out_buffer)[buffer_index], &aes_key); - memcpy(iv, &(*out_buffer)[buffer_index], AES_BLOCK_SIZE); + AES_encrypt(aes_input, &encrypted_buffer_[buffer_index], &aes_key); + memcpy(iv, &encrypted_buffer_[buffer_index], AES_BLOCK_SIZE); // CBC mode should always start on block boundary. block_offset = 0; } @@ -2042,73 +2196,58 @@ class OEMCryptoSessionTestsDecryptTests } } - void TestDecryptCENC(const vector& key, - const vector& /* encryptionIv */, - const vector& encryptedData, - const vector& unencryptedData) { + void LoadLicense() { + // First we open a session and load a license. + ASSERT_NO_FATAL_FAILURE(session_.open()); + ASSERT_NO_FATAL_FAILURE(InstallTestSessionKeys(&session_)); + uint32_t control = 0; + if (verify_crc_) control |= kControlAllowHashVerification; + ASSERT_NO_FATAL_FAILURE(session_.FillSimpleMessage( + kDuration, control, 0)); + memcpy(session_.license().keys[0].key_data, key_, sizeof(key_)); + session_.license().keys[0].cipher_mode = cipher_mode_; + ASSERT_NO_FATAL_FAILURE(session_.EncryptAndSign()); + ASSERT_NO_FATAL_FAILURE(session_.LoadTestKeys()); + ASSERT_EQ(OEMCrypto_SUCCESS, + OEMCrypto_SelectKey( + session_.session_id(), session_.license().keys[0].key_id, + session_.license().keys[0].key_id_length, cipher_mode_)); + } + + void TestDecryptCENC() { OEMCryptoResult sts; - Session s; - ASSERT_NO_FATAL_FAILURE(s.open()); - ASSERT_NO_FATAL_FAILURE(InstallTestSessionKeys(&s)); - ASSERT_NO_FATAL_FAILURE( - s.FillSimpleMessage(kDuration, kControlAllowHashVerification, 0)); - memcpy(s.license().keys[0].key_data, key.data(), key.size()); - s.license().keys[0].cipher_mode = cipher_mode_; - ASSERT_NO_FATAL_FAILURE(s.EncryptAndSign()); - ASSERT_NO_FATAL_FAILURE(s.LoadTestKeys()); - if (global_features.supports_crc) { - uint32_t hash = - wvcrc32(unencryptedData.data(), unencryptedData.size()); + // If supported, initialize the decrypt hash. + if (verify_crc_) { + uint32_t hash = wvcrc32(truth_buffer_.data(), truth_buffer_.size()); ASSERT_EQ(OEMCrypto_SUCCESS, OEMCrypto_SetDecryptHash( - s.session_id(), 1, reinterpret_cast(&hash), - sizeof(hash))); - } - sts = OEMCrypto_SelectKey(s.session_id(), s.license().keys[0].key_id, - s.license().keys[0].key_id_length, - cipher_mode_); - ASSERT_EQ(OEMCrypto_SUCCESS, sts); - // We decrypt each subsample. - vector output_buffer(total_size_ + 16, 0xaa); - const uint8_t *input_buffer = NULL; - if (decrypt_inplace_) { // Use same buffer for input and output. - // Copy the useful data from encryptedData to output_buffer, which - // will be the same as input_buffer. Leave the 0xaa padding at the end. - for(size_t i=0; i < total_size_; i++) output_buffer[i] = encryptedData[i]; - // Now let input_buffer point to the same data. - input_buffer = output_buffer.data(); - } else { - input_buffer = encryptedData.data(); + session_.session_id(), 1, + reinterpret_cast(&hash), sizeof(hash))); } size_t buffer_offset = 0; for (size_t i = 0; i < subsample_size_.size(); i++) { OEMCrypto_CENCEncryptPatternDesc pattern = pattern_; pattern.offset = 0; // Final CENC spec says pattern offset always 0. bool is_encrypted = false; - OEMCrypto_DestBufferDesc destBuffer; size_t block_offset = 0; uint8_t subsample_flags = 0; if (subsample_size_[i].clear_size > 0) { - destBuffer.type = OEMCrypto_BufferType_Clear; - destBuffer.buffer.clear.address = &output_buffer[buffer_offset]; - destBuffer.buffer.clear.max_length = total_size_ - buffer_offset; + ASSERT_NO_FATAL_FAILURE(UpdateOutputOffset(buffer_offset)); if (i == 0) subsample_flags |= OEMCrypto_FirstSubsample; if ((i == subsample_size_.size() - 1) && (subsample_size_[i].encrypted_size == 0)) { subsample_flags |= OEMCrypto_LastSubsample; } - sts = - OEMCrypto_DecryptCENC(s.session_id(), input_buffer + buffer_offset, - subsample_size_[i].clear_size, is_encrypted, - sample_init_data_[i].iv, block_offset, - &destBuffer, &pattern, subsample_flags); + sts = OEMCrypto_DecryptCENC( + session_.session_id(), &encrypted_buffer_[buffer_offset], + subsample_size_[i].clear_size, is_encrypted, + sample_init_data_[i].iv, block_offset, &output_descriptor_, + &pattern, subsample_flags); ASSERT_EQ(OEMCrypto_SUCCESS, sts); buffer_offset += subsample_size_[i].clear_size; } if (subsample_size_[i].encrypted_size > 0) { - destBuffer.type = OEMCrypto_BufferType_Clear; - destBuffer.buffer.clear.address = &output_buffer[buffer_offset]; - destBuffer.buffer.clear.max_length = total_size_ - buffer_offset; + ASSERT_NO_FATAL_FAILURE(UpdateOutputOffset(buffer_offset)); is_encrypted = true; block_offset = sample_init_data_[i].block_offset; subsample_flags = 0; @@ -2119,10 +2258,10 @@ class OEMCryptoSessionTestsDecryptTests subsample_flags |= OEMCrypto_LastSubsample; } sts = OEMCrypto_DecryptCENC( - s.session_id(), input_buffer + buffer_offset, + session_.session_id(), &encrypted_buffer_[buffer_offset], subsample_size_[i].encrypted_size, is_encrypted, - sample_init_data_[i].iv, block_offset, &destBuffer, &pattern, - subsample_flags); + sample_init_data_[i].iv, block_offset, &output_descriptor_, + &pattern, subsample_flags); // CBC mode should not accept a block offset. if ((block_offset > 0) && (cipher_mode_ == OEMCrypto_CipherMode_CBC)) { ASSERT_EQ(OEMCrypto_ERROR_INVALID_CONTEXT, sts) @@ -2133,14 +2272,23 @@ class OEMCryptoSessionTestsDecryptTests buffer_offset += subsample_size_[i].encrypted_size; } } - EXPECT_EQ(0xaa, output_buffer[total_size_]) << "Buffer overrun."; - output_buffer.resize(total_size_); - EXPECT_EQ(unencryptedData, output_buffer); + if (output_descriptor_.type == OEMCrypto_BufferType_Clear) { + if (decrypt_inplace_) { + // We expect encrypted buffer to have been changed by OEMCrypto. + EXPECT_EQ(encrypted_buffer_, truth_buffer_); + } else { + // If we are not decrypting in place, then look at the one byte just + // after the data that was written. It should not have changed from the + // original 0xaa that we set in MakeBuffersession_. + EXPECT_EQ(0xaa, clear_buffer_[total_size_]) << "Buffer overrun."; + clear_buffer_.resize(total_size_); // Remove padding. + EXPECT_EQ(clear_buffer_, truth_buffer_); + } + } if (global_features.supports_crc) { uint32_t frame; ASSERT_EQ(OEMCrypto_SUCCESS, - OEMCrypto_GetHashErrorCode(s.session_id(), &frame)); - + OEMCrypto_GetHashErrorCode(session_.session_id(), &frame)); } } @@ -2149,7 +2297,17 @@ class OEMCryptoSessionTestsDecryptTests bool decrypt_inplace_; // If true, input and output buffers are the same. vector subsample_size_; size_t total_size_; + bool verify_crc_; vector sample_init_data_; +// Encrypted data -- this is input to OEMCrypto, and output from EncryptData. + std::vector encrypted_buffer_; + std::vector clear_buffer_; // OEMCrypto store clear output here. + void* secure_handle_; // OEMCrypto stores secure output here. + std::vector truth_buffer_; // Truth data for clear text. + OEMCrypto_DestBufferDesc output_descriptor_; + uint8_t key_[AES_BLOCK_SIZE]; // Encryption Key. + std::vector starting_iv_; // Starting IV. + Session session_; }; // Tests that generate partial ending blocks. These tests should not be used @@ -2163,15 +2321,10 @@ TEST_P(OEMCryptoSessionTestsDecryptTests, SingleLargeSubsample) { // full patterns if we have more than 320 -- round up to 400. subsample_size_.push_back(SampleSize(0, 400)); FindTotalSize(); - vector unencryptedData(total_size_); - vector encryptedData(total_size_); - vector encryptionIv(AES_BLOCK_SIZE); - vector key(AES_BLOCK_SIZE); - EXPECT_EQ(1, GetRandBytes(encryptionIv.data(), AES_BLOCK_SIZE)); - EXPECT_EQ(1, GetRandBytes(key.data(), AES_BLOCK_SIZE)); - for (size_t i = 0; i < total_size_; i++) unencryptedData[i] = i % 256; - EncryptData(key, encryptionIv, unencryptedData, &encryptedData); - TestDecryptCENC(key, encryptionIv, encryptedData, unencryptedData); + ASSERT_NO_FATAL_FAILURE(MakeBuffers()); + ASSERT_NO_FATAL_FAILURE(LoadLicense()); + ASSERT_NO_FATAL_FAILURE(EncryptData()); + ASSERT_NO_FATAL_FAILURE(TestDecryptCENC()); } // When the pattern length is 10 blocks, there is a discrepancy between the @@ -2181,30 +2334,20 @@ TEST_P(OEMCryptoSessionTestsDecryptTests, SingleLargeSubsample) { TEST_P(OEMCryptoSessionTestsDecryptTests, PatternPlusOneBlock) { subsample_size_.push_back(SampleSize(0, 160 + 16)); FindTotalSize(); - vector unencryptedData(total_size_); - vector encryptedData(total_size_); - vector encryptionIv(AES_BLOCK_SIZE); - vector key(AES_BLOCK_SIZE); - EXPECT_EQ(1, GetRandBytes(encryptionIv.data(), AES_BLOCK_SIZE)); - EXPECT_EQ(1, GetRandBytes(key.data(), AES_BLOCK_SIZE)); - for (size_t i = 0; i < total_size_; i++) unencryptedData[i] = i % 256; - EncryptData(key, encryptionIv, unencryptedData, &encryptedData); - TestDecryptCENC(key, encryptionIv, encryptedData, unencryptedData); + ASSERT_NO_FATAL_FAILURE(MakeBuffers()); + ASSERT_NO_FATAL_FAILURE(LoadLicense()); + ASSERT_NO_FATAL_FAILURE(EncryptData()); + ASSERT_NO_FATAL_FAILURE(TestDecryptCENC()); } // Test that a single block can be decrypted. TEST_P(OEMCryptoSessionTestsDecryptTests, OneBlock) { subsample_size_.push_back(SampleSize(0, 16)); FindTotalSize(); - vector unencryptedData(total_size_); - vector encryptedData(total_size_); - vector encryptionIv(AES_BLOCK_SIZE); - vector key(AES_BLOCK_SIZE); - EXPECT_EQ(1, GetRandBytes(encryptionIv.data(), AES_BLOCK_SIZE)); - EXPECT_EQ(1, GetRandBytes(key.data(), AES_BLOCK_SIZE)); - for (size_t i = 0; i < total_size_; i++) unencryptedData[i] = i % 256; - EncryptData(key, encryptionIv, unencryptedData, &encryptedData); - TestDecryptCENC(key, encryptionIv, encryptedData, unencryptedData); + ASSERT_NO_FATAL_FAILURE(MakeBuffers()); + ASSERT_NO_FATAL_FAILURE(LoadLicense()); + ASSERT_NO_FATAL_FAILURE(EncryptData()); + ASSERT_NO_FATAL_FAILURE(TestDecryptCENC()); } // This tests the ability to decrypt multiple subsamples with no offset. @@ -2215,41 +2358,36 @@ TEST_P(OEMCryptoSessionTestsDecryptTests, NoOffset) { subsample_size_.push_back(SampleSize(50, 256)); subsample_size_.push_back(SampleSize(25, 160)); FindTotalSize(); - vector unencryptedData(total_size_); - vector encryptedData(total_size_); - vector encryptionIv(AES_BLOCK_SIZE); - vector key(AES_BLOCK_SIZE); - EXPECT_EQ(1, GetRandBytes(encryptionIv.data(), AES_BLOCK_SIZE)); - EXPECT_EQ(1, GetRandBytes(key.data(), AES_BLOCK_SIZE)); - for (size_t i = 0; i < total_size_; i++) unencryptedData[i] = i % 256; - EncryptData(key, encryptionIv, unencryptedData, &encryptedData); - TestDecryptCENC(key, encryptionIv, encryptedData, unencryptedData); + ASSERT_NO_FATAL_FAILURE(MakeBuffers()); + ASSERT_NO_FATAL_FAILURE(LoadLicense()); + ASSERT_NO_FATAL_FAILURE(EncryptData()); + ASSERT_NO_FATAL_FAILURE(TestDecryptCENC()); } // This tests an offset into the block for the second encrypted subsample. // This should only work for CTR mode, for CBC mode an error is expected in // the decrypt step. -// If this test fails for CTR mode, then it is probably handleing the +// If this test fails for CTR mode, then it is probably handling the // block_offset incorrectly. TEST_P(OEMCryptoSessionTestsPartialBlockTests, EvenOffset) { subsample_size_.push_back(SampleSize(25, 8)); subsample_size_.push_back(SampleSize(25, 32)); subsample_size_.push_back(SampleSize(25, 50)); FindTotalSize(); - vector unencryptedData(total_size_); - vector encryptedData(total_size_); - vector encryptionIv(AES_BLOCK_SIZE); - vector key(AES_BLOCK_SIZE); - EXPECT_EQ(1, GetRandBytes(key.data(), AES_BLOCK_SIZE)); + ASSERT_NO_FATAL_FAILURE(MakeBuffers()); + ASSERT_NO_FATAL_FAILURE(LoadLicense()); // CTR Mode is self-inverse -- i.e. We can pick the encrypted data and // compute the unencrypted data. By picking the encrypted data to be all 0, // it is easier to re-encrypt the data and debug problems. Similarly, we // pick an iv = 0. - EncryptData(key, encryptionIv, encryptedData, &unencryptedData); - // Run EncryptData again to correctly compute intermediate IV vectors. - // For CBC mode, this also computes the real encrypted data. - EncryptData(key, encryptionIv, unencryptedData, &encryptedData); - TestDecryptCENC(key, encryptionIv, encryptedData, unencryptedData); + starting_iv_.assign(AES_BLOCK_SIZE, 0); + truth_buffer_.assign(total_size_, 0); + ASSERT_NO_FATAL_FAILURE(EncryptData()); + truth_buffer_ = encrypted_buffer_; // truth_buffer_ = encrypted zero buffer. + // Run EncryptData to re-encrypt this buffer. For CTR mode, we should get + // back to zeros. + ASSERT_NO_FATAL_FAILURE(EncryptData()); + ASSERT_NO_FATAL_FAILURE(TestDecryptCENC()); } // If the EvenOffset test passes, but this one doesn't, then DecryptCTR might @@ -2264,15 +2402,10 @@ TEST_P(OEMCryptoSessionTestsPartialBlockTests, OddOffset) { subsample_size_.push_back(SampleSize(10, 75)); subsample_size_.push_back(SampleSize(10, 25)); FindTotalSize(); - vector unencryptedData(total_size_); - vector encryptedData(total_size_); - vector encryptionIv(AES_BLOCK_SIZE); - vector key(AES_BLOCK_SIZE); - EXPECT_EQ(1, GetRandBytes(encryptionIv.data(), AES_BLOCK_SIZE)); - EXPECT_EQ(1, GetRandBytes(key.data(), AES_BLOCK_SIZE)); - for (size_t i = 0; i < total_size_; i++) unencryptedData[i] = i % 256; - EncryptData(key, encryptionIv, unencryptedData, &encryptedData); - TestDecryptCENC(key, encryptionIv, encryptedData, unencryptedData); + ASSERT_NO_FATAL_FAILURE(MakeBuffers()); + ASSERT_NO_FATAL_FAILURE(LoadLicense()); + ASSERT_NO_FATAL_FAILURE(EncryptData()); + ASSERT_NO_FATAL_FAILURE(TestDecryptCENC()); } // This tests that the algorithm used to increment the counter for @@ -2286,17 +2419,13 @@ TEST_P(OEMCryptoSessionTestsPartialBlockTests, OddOffset) { // If you start with an IV of 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE, after you // increment twice, you should get 0xFFFFFFFFFFFFFFFF0000000000000000. TEST_P(OEMCryptoSessionTestsDecryptTests, DecryptWithNearWrap) { + starting_iv_ = wvcdm::a2b_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE"); subsample_size_.push_back(SampleSize(0, 256)); FindTotalSize(); - vector unencryptedData(total_size_); - vector encryptedData(total_size_); - vector encryptionIv(AES_BLOCK_SIZE); - vector key(AES_BLOCK_SIZE); - EXPECT_EQ(1, GetRandBytes(key.data(), AES_BLOCK_SIZE)); - encryptionIv = wvcdm::a2b_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE"); - for (size_t i = 0; i < total_size_; i++) unencryptedData[i] = i % 256; - EncryptData(key, encryptionIv, unencryptedData, &encryptedData); - TestDecryptCENC(key, encryptionIv, encryptedData, unencryptedData); + ASSERT_NO_FATAL_FAILURE(MakeBuffers()); + ASSERT_NO_FATAL_FAILURE(LoadLicense()); + ASSERT_NO_FATAL_FAILURE(EncryptData()); + ASSERT_NO_FATAL_FAILURE(TestDecryptCENC()); } // This tests the case where an encrypted sample is not an even number of @@ -2308,15 +2437,10 @@ TEST_P(OEMCryptoSessionTestsPartialBlockTests, PartialBlock) { // other tests, e.g. (7, 3). 3*16 < 50 and 7*16 > 50. subsample_size_.push_back(SampleSize(0, 50)); FindTotalSize(); - vector unencryptedData(total_size_); - vector encryptedData(total_size_); - vector encryptionIv(AES_BLOCK_SIZE); - vector key(AES_BLOCK_SIZE); - EXPECT_EQ(1, GetRandBytes(encryptionIv.data(), AES_BLOCK_SIZE)); - EXPECT_EQ(1, GetRandBytes(key.data(), AES_BLOCK_SIZE)); - for (size_t i = 0; i < total_size_; i++) unencryptedData[i] = i % 256; - EncryptData(key, encryptionIv, unencryptedData, &encryptedData); - TestDecryptCENC(key, encryptionIv, encryptedData, unencryptedData); + ASSERT_NO_FATAL_FAILURE(MakeBuffers()); + ASSERT_NO_FATAL_FAILURE(LoadLicense()); + ASSERT_NO_FATAL_FAILURE(EncryptData()); + ASSERT_NO_FATAL_FAILURE(TestDecryptCENC()); } // Based on the resource rating, oemcrypto should handle at least @@ -2333,15 +2457,10 @@ TEST_P(OEMCryptoSessionTestsDecryptTests, DecryptMaxSample) { subsample_size_.push_back(SampleSize(0, max_subsample_size)); } FindTotalSize(); - vector unencryptedData(total_size_); - vector encryptedData(total_size_); - vector encryptionIv(AES_BLOCK_SIZE); - vector key(AES_BLOCK_SIZE); - EXPECT_EQ(1, GetRandBytes(encryptionIv.data(), AES_BLOCK_SIZE)); - EXPECT_EQ(1, GetRandBytes(key.data(), AES_BLOCK_SIZE)); - for (size_t i = 0; i < total_size_; i++) unencryptedData[i] = i % 256; - EncryptData(key, encryptionIv, unencryptedData, &encryptedData); - TestDecryptCENC(key, encryptionIv, encryptedData, unencryptedData); + ASSERT_NO_FATAL_FAILURE(MakeBuffers()); + ASSERT_NO_FATAL_FAILURE(LoadLicense()); + ASSERT_NO_FATAL_FAILURE(EncryptData()); + ASSERT_NO_FATAL_FAILURE(TestDecryptCENC()); } // This tests that we can decrypt the required maximum number of subsamples. @@ -2350,30 +2469,20 @@ TEST_P(OEMCryptoSessionTestsDecryptTests, DecryptMaxSubsample) { subsample_size_.push_back(SampleSize(max_subsample_size, 0)); subsample_size_.push_back(SampleSize(0, max_subsample_size)); FindTotalSize(); - vector unencryptedData(total_size_); - vector encryptedData(total_size_); - vector encryptionIv(AES_BLOCK_SIZE); - vector key(AES_BLOCK_SIZE); - EXPECT_EQ(1, GetRandBytes(encryptionIv.data(), AES_BLOCK_SIZE)); - EXPECT_EQ(1, GetRandBytes(key.data(), AES_BLOCK_SIZE)); - for (size_t i = 0; i < total_size_; i++) unencryptedData[i] = i % 256; - EncryptData(key, encryptionIv, unencryptedData, &encryptedData); - TestDecryptCENC(key, encryptionIv, encryptedData, unencryptedData); + ASSERT_NO_FATAL_FAILURE(MakeBuffers()); + ASSERT_NO_FATAL_FAILURE(LoadLicense()); + ASSERT_NO_FATAL_FAILURE(EncryptData()); + ASSERT_NO_FATAL_FAILURE(TestDecryptCENC()); } // There are probably no frames this small, but we should handle them anyway. TEST_P(OEMCryptoSessionTestsDecryptTests, DecryptSmallBuffer) { subsample_size_.push_back(SampleSize(5, 5)); FindTotalSize(); - vector unencryptedData(total_size_); - vector encryptedData(total_size_); - vector encryptionIv(AES_BLOCK_SIZE); - vector key(AES_BLOCK_SIZE); - EXPECT_EQ(1, GetRandBytes(encryptionIv.data(), AES_BLOCK_SIZE)); - EXPECT_EQ(1, GetRandBytes(key.data(), AES_BLOCK_SIZE)); - for (size_t i = 0; i < total_size_; i++) unencryptedData[i] = i % 256; - EncryptData(key, encryptionIv, unencryptedData, &encryptedData); - TestDecryptCENC(key, encryptionIv, encryptedData, unencryptedData); + ASSERT_NO_FATAL_FAILURE(MakeBuffers()); + ASSERT_NO_FATAL_FAILURE(LoadLicense()); + ASSERT_NO_FATAL_FAILURE(EncryptData()); + ASSERT_NO_FATAL_FAILURE(TestDecryptCENC()); } // Test the case where there is only a clear subsample and no encrypted @@ -2381,47 +2490,25 @@ TEST_P(OEMCryptoSessionTestsDecryptTests, DecryptSmallBuffer) { TEST_P(OEMCryptoSessionTestsDecryptTests, DecryptUnencrypted) { subsample_size_.push_back(SampleSize(256, 0)); FindTotalSize(); - vector unencryptedData(total_size_); - vector encryptedData(total_size_); - vector encryptionIv(AES_BLOCK_SIZE); - vector key(AES_BLOCK_SIZE); - EXPECT_EQ(1, GetRandBytes(encryptionIv.data(), AES_BLOCK_SIZE)); - EXPECT_EQ(1, GetRandBytes(key.data(), AES_BLOCK_SIZE)); - for (size_t i = 0; i < total_size_; i++) unencryptedData[i] = i % 256; - EncryptData(key, encryptionIv, unencryptedData, &encryptedData); - TestDecryptCENC(key, encryptionIv, encryptedData, unencryptedData); + ASSERT_NO_FATAL_FAILURE(MakeBuffers()); + ASSERT_NO_FATAL_FAILURE(LoadLicense()); + ASSERT_NO_FATAL_FAILURE(EncryptData()); + ASSERT_NO_FATAL_FAILURE(TestDecryptCENC()); } -TEST_F(OEMCryptoSessionTests, DecryptUnencryptedNoKey) { - OEMCryptoResult sts; - Session s; - ASSERT_NO_FATAL_FAILURE(s.open()); - // Clear data should be copied even if there is no key selected. - // Set up our expected input and output - // This is dummy decrypted data. - vector in_buffer(256); - for (size_t i = 0; i < in_buffer.size(); i++) in_buffer[i] = i % 256; - vector encryptionIv(AES_BLOCK_SIZE); - EXPECT_EQ(1, GetRandBytes(encryptionIv.data(), AES_BLOCK_SIZE)); - // Describe the output - vector out_buffer(in_buffer.size()); - OEMCrypto_DestBufferDesc destBuffer; - destBuffer.type = OEMCrypto_BufferType_Clear; - destBuffer.buffer.clear.address = out_buffer.data(); - destBuffer.buffer.clear.max_length = out_buffer.size(); - OEMCrypto_CENCEncryptPatternDesc pattern; - pattern.encrypt = 0; - pattern.skip = 0; - pattern.offset = 0; - - // Decrypt the data - sts = - OEMCrypto_DecryptCENC(s.session_id(), in_buffer.data(), in_buffer.size(), - false, encryptionIv.data(), 0, &destBuffer, - &pattern, - OEMCrypto_FirstSubsample | OEMCrypto_LastSubsample); - ASSERT_EQ(OEMCrypto_SUCCESS, sts); - ASSERT_EQ(in_buffer, out_buffer); +TEST_P(OEMCryptoSessionTestsDecryptTests, DecryptUnencryptedNoKey) { + ASSERT_NO_FATAL_FAILURE(session_.open()); + // Single clear subsample + subsample_size_.push_back(SampleSize(400, 0)); + // Do not try to compute the CRC because we have not loaded a license. + verify_crc_ = false; + FindTotalSize(); + ASSERT_NO_FATAL_FAILURE(MakeBuffers()); + // Clear data should be copied even if there is no key selected, and no + // license loaded. + // ASSERT_NO_FATAL_FAILURE(LoadLicense()); + ASSERT_NO_FATAL_FAILURE(EncryptData()); + ASSERT_NO_FATAL_FAILURE(TestDecryptCENC()); } // Used to construct a specific pattern. @@ -4882,6 +4969,22 @@ class UsageTableTest : public GenericCryptoTest { void SetUp() override { GenericCryptoTest::SetUp(); new_mac_keys_ = true; + did_change_system_time_ = false; + test_start_steady_ = steady_clock_.now(); +#ifdef _WIN32 + GetSystemTime(&test_start_wall_); +#else + ASSERT_EQ(0, gettimeofday(&test_start_wall_, nullptr)); +#endif + } + + void TearDown() override { + if (did_change_system_time_) { + const auto delta = steady_clock_.now() - test_start_steady_; + const int64_t delta_sec = delta / std::chrono::seconds(1); + ASSERT_NO_FATAL_FAILURE(SetWallTimeDelta(delta_sec)); + } + GenericCryptoTest::TearDown(); } virtual void ShutDown() { @@ -4926,7 +5029,26 @@ class UsageTableTest : public GenericCryptoTest { } protected: + /** + * Sets the current wall-clock time to a delta based on the start of the + * test. + */ + void SetWallTimeDelta(int64_t delta_seconds) { + did_change_system_time_ = true; + NativeTime time = test_start_wall_; + ASSERT_NO_FATAL_FAILURE(AddNativeTime(delta_seconds, &time)); +#ifdef _WIN32 + ASSERT_TRUE(SetSystemTime(&time)); +#else + ASSERT_EQ(0, settimeofday(&time, nullptr)); +#endif + } + bool new_mac_keys_; + bool did_change_system_time_; + std::chrono::steady_clock steady_clock_; + std::chrono::time_point test_start_steady_; + NativeTime test_start_wall_; }; // Some usage tables we want to check a license either with or without a @@ -5396,9 +5518,9 @@ TEST_P(UsageTableTestWithMAC, ReloadOfflineLicenseWithRefresh) { ASSERT_NO_FATAL_FAILURE(s.close()); } -// Verify that a license that has been we can still reload an offline license -// after OEMCrypto_Terminate and Initialize are called. This is as close to a -// reboot as we can do in a unit test. +// Verify that we can still reload an offline license after OEMCrypto_Terminate +// and Initialize are called. This is as close to a reboot as we can do in a +// unit test. TEST_P(UsageTableTestWithMAC, ReloadOfflineLicenseWithTerminate) { std::string pst = "my_pst"; Session s; @@ -5856,9 +5978,7 @@ TEST_F(UsageTableDefragTest, ReloadUsageEntryBadData) { } static std::string MakePST(size_t n) { - std::stringstream stream; - stream << "pst-" << n; - return stream.str(); + return "pst-" + std::to_string(n); } // This verifies we can actually create two hundered usage table entries. @@ -6287,23 +6407,19 @@ TEST_F(UsageTableTest, TimeRollbackPrevention) { cout << "This test temporarily rolls back the system time in order to verify " << "that the usage report accounts for the change. It then rolls " << "the time back forward to the absolute time." << endl; - // We use clock_gettime(CLOCK_REALTIME, ...) over time(...) so we can easily - // set the time using clock_settime. - timespec current_time; - ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, ¤t_time)); - time_t loaded = current_time.tv_sec; + std::chrono::system_clock wall_clock; + std::chrono::steady_clock monotonic_clock; + const auto loaded = wall_clock.now(); ASSERT_NO_FATAL_FAILURE(LoadOfflineLicense(s1, pst)); ASSERT_NO_FATAL_FAILURE(s1.open()); ASSERT_NO_FATAL_FAILURE(s1.ReloadUsageEntry()); ASSERT_NO_FATAL_FAILURE(InstallTestSessionKeys(&s1)); ASSERT_NO_FATAL_FAILURE(s1.LoadTestKeys(pst, new_mac_keys_)); - ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, ¤t_time)); - time_t first_decrypt = current_time.tv_sec; + const auto first_decrypt = wall_clock.now(); // Monotonic clock can't be changed. We use this since system clock will be // unreliable. - ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, ¤t_time)); - time_t first_decrypt_monotonic = current_time.tv_sec; + const auto first_decrypt_monotonic = monotonic_clock.now(); ASSERT_NO_FATAL_FAILURE(s1.TestDecryptCTR()); ASSERT_NO_FATAL_FAILURE(s1.UpdateUsageEntry(&encrypted_usage_header_)); ASSERT_NO_FATAL_FAILURE(s1.close()); @@ -6319,20 +6435,17 @@ TEST_F(UsageTableTest, TimeRollbackPrevention) { ASSERT_NO_FATAL_FAILURE(s1.UpdateUsageEntry(&encrypted_usage_header_)); ASSERT_NO_FATAL_FAILURE(s1.close()); - ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, ¤t_time)); // Rollback the wall clock time. cout << "Rolling the system time back..." << endl; - timeval current_time_of_day = {}; - current_time_of_day.tv_sec = current_time.tv_sec - kLongDuration * 10; - ASSERT_EQ(0, settimeofday(¤t_time_of_day, NULL)); + ASSERT_NO_FATAL_FAILURE(SetWallTimeDelta( + -static_cast(kLongDuration) * 10)); // Try to playback again. ASSERT_NO_FATAL_FAILURE(s1.open()); ASSERT_NO_FATAL_FAILURE(s1.ReloadUsageEntry()); ASSERT_NO_FATAL_FAILURE(InstallTestSessionKeys(&s1)); ASSERT_NO_FATAL_FAILURE(s1.LoadTestKeys(pst, new_mac_keys_)); - ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, ¤t_time)); - time_t third_decrypt = current_time.tv_sec; + const auto third_decrypt_monotonic = monotonic_clock.now(); ASSERT_NO_FATAL_FAILURE(s1.TestDecryptCTR()); ASSERT_NO_FATAL_FAILURE(s1.UpdateUsageEntry(&encrypted_usage_header_)); ASSERT_NO_FATAL_FAILURE(s1.GenerateReport(pst)); @@ -6340,18 +6453,18 @@ TEST_F(UsageTableTest, TimeRollbackPrevention) { // Restore wall clock to its original position to verify that OEMCrypto does // not report negative times. - ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, ¤t_time)); - current_time_of_day.tv_sec = - first_decrypt + current_time.tv_sec - first_decrypt_monotonic; + const auto test_duration = third_decrypt_monotonic - first_decrypt_monotonic; cout << "Rolling the system time forward to the absolute time..." << endl; - ASSERT_EQ(0, settimeofday(¤t_time_of_day, NULL)); + ASSERT_NO_FATAL_FAILURE(SetWallTimeDelta( + test_duration / std::chrono::seconds(1))); // Need to update time created since the verification checks the time of PST // report creation. - expected.time_created = current_time_of_day.tv_sec; + expected.time_created = UnixTime(wall_clock.now()); + const auto end_time = first_decrypt + test_duration; ASSERT_NO_FATAL_FAILURE( - s1.VerifyReport(expected, loaded, first_decrypt, - first_decrypt + third_decrypt - first_decrypt_monotonic)); + s1.VerifyReport(expected, UnixTime(loaded), UnixTime(first_decrypt), + UnixTime(end_time))); ASSERT_NO_FATAL_FAILURE(s1.close()); } diff --git a/oemcrypto/test/oemcrypto_test_android.cpp b/oemcrypto/test/oemcrypto_test_android.cpp index 7dd33845..e0739ea6 100644 --- a/oemcrypto/test/oemcrypto_test_android.cpp +++ b/oemcrypto/test/oemcrypto_test_android.cpp @@ -50,6 +50,11 @@ TEST_F(OEMCryptoAndroidLMPTest, ValidKeybox) { } } +TEST_F(OEMCryptoAndroidLMPTest, MinVersionNumber9) { + uint32_t version = OEMCrypto_APIVersion(); + ASSERT_LE(9u, version); +} + TEST_F(OEMCryptoAndroidLMPTest, ValidKeyboxTest) { ASSERT_EQ(OEMCrypto_SUCCESS, OEMCrypto_IsKeyboxValid()); } @@ -108,6 +113,11 @@ TEST_F(OEMCryptoAndroidLMPTest, Level1Required) { // These tests are required for M Android devices. class OEMCryptoAndroidMNCTest : public OEMCryptoAndroidLMPTest {}; +TEST_F(OEMCryptoAndroidMNCTest, MinVersionNumber10) { + uint32_t version = OEMCrypto_APIVersion(); + ASSERT_GE(version, 10u); +} + // Android devices using Provisioning 2.0 must be able to load a test keybox. // If they are not using Provisioning 2.0, then they must use Provisioning 3.0. TEST_F(OEMCryptoAndroidMNCTest, LoadsTestKeyboxImplemented) { @@ -135,4 +145,28 @@ TEST_F(OEMCryptoAndroidMNCTest, QueryKeyControlImplemented) { OEMCrypto_QueryKeyControl(0, NULL, 0, NULL, NULL)); } +// These tests are required for N Android devices. +class OEMCryptoAndroidNYCTest : public OEMCryptoAndroidMNCTest {}; + +TEST_F(OEMCryptoAndroidNYCTest, MinVersionNumber11) { + uint32_t version = OEMCrypto_APIVersion(); + ASSERT_GE(version, 11u); +} + +// These tests are required for O MR1 Android devices. +class OEMCryptoAndroidOCTest : public OEMCryptoAndroidNYCTest {}; + +TEST_F(OEMCryptoAndroidOCTest, MinVersionNumber13) { + uint32_t version = OEMCrypto_APIVersion(); + ASSERT_GE(version, 13u); +} + +// These tests are required for Q Android devices. +class OEMCryptoAndroidQTest : public OEMCryptoAndroidOCTest {}; + +TEST_F(OEMCryptoAndroidQTest, MinVersionNumber14) { + uint32_t version = OEMCrypto_APIVersion(); + ASSERT_GE(version, 15u); +} + } // namespace wvoec diff --git a/oemcrypto/test/oemcrypto_test_main.cpp b/oemcrypto/test/oemcrypto_test_main.cpp index baf839b9..cedd9537 100644 --- a/oemcrypto/test/oemcrypto_test_main.cpp +++ b/oemcrypto/test/oemcrypto_test_main.cpp @@ -17,12 +17,14 @@ static void acknowledge_cast() { // Also, the test filter is updated based on the feature list. int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); - wvcdm::g_cutoff = wvcdm::LOG_INFO; bool is_cast_receiver = false; bool force_load_test_keybox = false; bool filter_tests = true; + int verbosity = 0; for (int i = 0; i < argc; i++) { - if (!strcmp(argv[i], "--cast")) { + if (arg == "--verbose" || arg == "-v") { + ++verbosity; + } else if (!strcmp(argv[i], "--cast")) { acknowledge_cast(); is_cast_receiver = true; } @@ -33,6 +35,7 @@ int main(int argc, char** argv) { filter_tests = false; } } + wvcdm::g_cutoff = static_cast(verbosity); wvoec::global_features.Initialize(is_cast_receiver, force_load_test_keybox); // If the user requests --no_filter, we don't change the filter, otherwise, we // filter out features that are not supported. diff --git a/oemcrypto/test/oemcrypto_unittests.gyp b/oemcrypto/test/oemcrypto_unittests.gyp index 714aa936..fac3f71b 100644 --- a/oemcrypto/test/oemcrypto_unittests.gyp +++ b/oemcrypto/test/oemcrypto_unittests.gyp @@ -3,14 +3,14 @@ { 'variables': { # Override the variables below for the location of various gyp files. - # Alternatively, set the environment variable CDM_DIR to point to a recent - # version of the source CDM. - 'boringssl_dependency%': ' +#endif +.text + +.globl _gcm_init_neon +.private_extern _gcm_init_neon + +.align 4 +_gcm_init_neon: + // This function is adapted from gcm_init_v8. xC2 is t3. + ld1 {v17.2d}, [x1] // load H + movi v19.16b, #0xe1 + shl v19.2d, v19.2d, #57 // 0xc2.0 + ext v3.16b, v17.16b, v17.16b, #8 + ushr v18.2d, v19.2d, #63 + dup v17.4s, v17.s[1] + ext v16.16b, v18.16b, v19.16b, #8 // t0=0xc2....01 + ushr v18.2d, v3.2d, #63 + sshr v17.4s, v17.4s, #31 // broadcast carry bit + and v18.16b, v18.16b, v16.16b + shl v3.2d, v3.2d, #1 + ext v18.16b, v18.16b, v18.16b, #8 + and v16.16b, v16.16b, v17.16b + orr v3.16b, v3.16b, v18.16b // H<<<=1 + eor v5.16b, v3.16b, v16.16b // twisted H + st1 {v5.2d}, [x0] // store Htable[0] + ret + + +.globl _gcm_gmult_neon +.private_extern _gcm_gmult_neon + +.align 4 +_gcm_gmult_neon: + ld1 {v3.16b}, [x0] // load Xi + ld1 {v5.1d}, [x1], #8 // load twisted H + ld1 {v6.1d}, [x1] + adrp x9, Lmasks@PAGE // load constants + add x9, x9, Lmasks@PAGEOFF + ld1 {v24.2d, v25.2d}, [x9] + rev64 v3.16b, v3.16b // byteswap Xi + ext v3.16b, v3.16b, v3.16b, #8 + eor v7.8b, v5.8b, v6.8b // Karatsuba pre-processing + + mov x3, #16 + b Lgmult_neon + + +.globl _gcm_ghash_neon +.private_extern _gcm_ghash_neon + +.align 4 +_gcm_ghash_neon: + ld1 {v0.16b}, [x0] // load Xi + ld1 {v5.1d}, [x1], #8 // load twisted H + ld1 {v6.1d}, [x1] + adrp x9, Lmasks@PAGE // load constants + add x9, x9, Lmasks@PAGEOFF + ld1 {v24.2d, v25.2d}, [x9] + rev64 v0.16b, v0.16b // byteswap Xi + ext v0.16b, v0.16b, v0.16b, #8 + eor v7.8b, v5.8b, v6.8b // Karatsuba pre-processing + +Loop_neon: + ld1 {v3.16b}, [x2], #16 // load inp + rev64 v3.16b, v3.16b // byteswap inp + ext v3.16b, v3.16b, v3.16b, #8 + eor v3.16b, v3.16b, v0.16b // inp ^= Xi + +Lgmult_neon: + // Split the input into v3 and v4. (The upper halves are unused, + // so it is okay to leave them alone.) + ins v4.d[0], v3.d[1] + ext v16.8b, v5.8b, v5.8b, #1 // A1 + pmull v16.8h, v16.8b, v3.8b // F = A1*B + ext v0.8b, v3.8b, v3.8b, #1 // B1 + pmull v0.8h, v5.8b, v0.8b // E = A*B1 + ext v17.8b, v5.8b, v5.8b, #2 // A2 + pmull v17.8h, v17.8b, v3.8b // H = A2*B + ext v19.8b, v3.8b, v3.8b, #2 // B2 + pmull v19.8h, v5.8b, v19.8b // G = A*B2 + ext v18.8b, v5.8b, v5.8b, #3 // A3 + eor v16.16b, v16.16b, v0.16b // L = E + F + pmull v18.8h, v18.8b, v3.8b // J = A3*B + ext v0.8b, v3.8b, v3.8b, #3 // B3 + eor v17.16b, v17.16b, v19.16b // M = G + H + pmull v0.8h, v5.8b, v0.8b // I = A*B3 + + // Here we diverge from the 32-bit version. It computes the following + // (instructions reordered for clarity): + // + // veor $t0#lo, $t0#lo, $t0#hi @ t0 = P0 + P1 (L) + // vand $t0#hi, $t0#hi, $k48 + // veor $t0#lo, $t0#lo, $t0#hi + // + // veor $t1#lo, $t1#lo, $t1#hi @ t1 = P2 + P3 (M) + // vand $t1#hi, $t1#hi, $k32 + // veor $t1#lo, $t1#lo, $t1#hi + // + // veor $t2#lo, $t2#lo, $t2#hi @ t2 = P4 + P5 (N) + // vand $t2#hi, $t2#hi, $k16 + // veor $t2#lo, $t2#lo, $t2#hi + // + // veor $t3#lo, $t3#lo, $t3#hi @ t3 = P6 + P7 (K) + // vmov.i64 $t3#hi, #0 + // + // $kN is a mask with the bottom N bits set. AArch64 cannot compute on + // upper halves of SIMD registers, so we must split each half into + // separate registers. To compensate, we pair computations up and + // parallelize. + + ext v19.8b, v3.8b, v3.8b, #4 // B4 + eor v18.16b, v18.16b, v0.16b // N = I + J + pmull v19.8h, v5.8b, v19.8b // K = A*B4 + + // This can probably be scheduled more efficiently. For now, we just + // pair up independent instructions. + zip1 v20.2d, v16.2d, v17.2d + zip1 v22.2d, v18.2d, v19.2d + zip2 v21.2d, v16.2d, v17.2d + zip2 v23.2d, v18.2d, v19.2d + eor v20.16b, v20.16b, v21.16b + eor v22.16b, v22.16b, v23.16b + and v21.16b, v21.16b, v24.16b + and v23.16b, v23.16b, v25.16b + eor v20.16b, v20.16b, v21.16b + eor v22.16b, v22.16b, v23.16b + zip1 v16.2d, v20.2d, v21.2d + zip1 v18.2d, v22.2d, v23.2d + zip2 v17.2d, v20.2d, v21.2d + zip2 v19.2d, v22.2d, v23.2d + + ext v16.16b, v16.16b, v16.16b, #15 // t0 = t0 << 8 + ext v17.16b, v17.16b, v17.16b, #14 // t1 = t1 << 16 + pmull v0.8h, v5.8b, v3.8b // D = A*B + ext v19.16b, v19.16b, v19.16b, #12 // t3 = t3 << 32 + ext v18.16b, v18.16b, v18.16b, #13 // t2 = t2 << 24 + eor v16.16b, v16.16b, v17.16b + eor v18.16b, v18.16b, v19.16b + eor v0.16b, v0.16b, v16.16b + eor v0.16b, v0.16b, v18.16b + eor v3.8b, v3.8b, v4.8b // Karatsuba pre-processing + ext v16.8b, v7.8b, v7.8b, #1 // A1 + pmull v16.8h, v16.8b, v3.8b // F = A1*B + ext v1.8b, v3.8b, v3.8b, #1 // B1 + pmull v1.8h, v7.8b, v1.8b // E = A*B1 + ext v17.8b, v7.8b, v7.8b, #2 // A2 + pmull v17.8h, v17.8b, v3.8b // H = A2*B + ext v19.8b, v3.8b, v3.8b, #2 // B2 + pmull v19.8h, v7.8b, v19.8b // G = A*B2 + ext v18.8b, v7.8b, v7.8b, #3 // A3 + eor v16.16b, v16.16b, v1.16b // L = E + F + pmull v18.8h, v18.8b, v3.8b // J = A3*B + ext v1.8b, v3.8b, v3.8b, #3 // B3 + eor v17.16b, v17.16b, v19.16b // M = G + H + pmull v1.8h, v7.8b, v1.8b // I = A*B3 + + // Here we diverge from the 32-bit version. It computes the following + // (instructions reordered for clarity): + // + // veor $t0#lo, $t0#lo, $t0#hi @ t0 = P0 + P1 (L) + // vand $t0#hi, $t0#hi, $k48 + // veor $t0#lo, $t0#lo, $t0#hi + // + // veor $t1#lo, $t1#lo, $t1#hi @ t1 = P2 + P3 (M) + // vand $t1#hi, $t1#hi, $k32 + // veor $t1#lo, $t1#lo, $t1#hi + // + // veor $t2#lo, $t2#lo, $t2#hi @ t2 = P4 + P5 (N) + // vand $t2#hi, $t2#hi, $k16 + // veor $t2#lo, $t2#lo, $t2#hi + // + // veor $t3#lo, $t3#lo, $t3#hi @ t3 = P6 + P7 (K) + // vmov.i64 $t3#hi, #0 + // + // $kN is a mask with the bottom N bits set. AArch64 cannot compute on + // upper halves of SIMD registers, so we must split each half into + // separate registers. To compensate, we pair computations up and + // parallelize. + + ext v19.8b, v3.8b, v3.8b, #4 // B4 + eor v18.16b, v18.16b, v1.16b // N = I + J + pmull v19.8h, v7.8b, v19.8b // K = A*B4 + + // This can probably be scheduled more efficiently. For now, we just + // pair up independent instructions. + zip1 v20.2d, v16.2d, v17.2d + zip1 v22.2d, v18.2d, v19.2d + zip2 v21.2d, v16.2d, v17.2d + zip2 v23.2d, v18.2d, v19.2d + eor v20.16b, v20.16b, v21.16b + eor v22.16b, v22.16b, v23.16b + and v21.16b, v21.16b, v24.16b + and v23.16b, v23.16b, v25.16b + eor v20.16b, v20.16b, v21.16b + eor v22.16b, v22.16b, v23.16b + zip1 v16.2d, v20.2d, v21.2d + zip1 v18.2d, v22.2d, v23.2d + zip2 v17.2d, v20.2d, v21.2d + zip2 v19.2d, v22.2d, v23.2d + + ext v16.16b, v16.16b, v16.16b, #15 // t0 = t0 << 8 + ext v17.16b, v17.16b, v17.16b, #14 // t1 = t1 << 16 + pmull v1.8h, v7.8b, v3.8b // D = A*B + ext v19.16b, v19.16b, v19.16b, #12 // t3 = t3 << 32 + ext v18.16b, v18.16b, v18.16b, #13 // t2 = t2 << 24 + eor v16.16b, v16.16b, v17.16b + eor v18.16b, v18.16b, v19.16b + eor v1.16b, v1.16b, v16.16b + eor v1.16b, v1.16b, v18.16b + ext v16.8b, v6.8b, v6.8b, #1 // A1 + pmull v16.8h, v16.8b, v4.8b // F = A1*B + ext v2.8b, v4.8b, v4.8b, #1 // B1 + pmull v2.8h, v6.8b, v2.8b // E = A*B1 + ext v17.8b, v6.8b, v6.8b, #2 // A2 + pmull v17.8h, v17.8b, v4.8b // H = A2*B + ext v19.8b, v4.8b, v4.8b, #2 // B2 + pmull v19.8h, v6.8b, v19.8b // G = A*B2 + ext v18.8b, v6.8b, v6.8b, #3 // A3 + eor v16.16b, v16.16b, v2.16b // L = E + F + pmull v18.8h, v18.8b, v4.8b // J = A3*B + ext v2.8b, v4.8b, v4.8b, #3 // B3 + eor v17.16b, v17.16b, v19.16b // M = G + H + pmull v2.8h, v6.8b, v2.8b // I = A*B3 + + // Here we diverge from the 32-bit version. It computes the following + // (instructions reordered for clarity): + // + // veor $t0#lo, $t0#lo, $t0#hi @ t0 = P0 + P1 (L) + // vand $t0#hi, $t0#hi, $k48 + // veor $t0#lo, $t0#lo, $t0#hi + // + // veor $t1#lo, $t1#lo, $t1#hi @ t1 = P2 + P3 (M) + // vand $t1#hi, $t1#hi, $k32 + // veor $t1#lo, $t1#lo, $t1#hi + // + // veor $t2#lo, $t2#lo, $t2#hi @ t2 = P4 + P5 (N) + // vand $t2#hi, $t2#hi, $k16 + // veor $t2#lo, $t2#lo, $t2#hi + // + // veor $t3#lo, $t3#lo, $t3#hi @ t3 = P6 + P7 (K) + // vmov.i64 $t3#hi, #0 + // + // $kN is a mask with the bottom N bits set. AArch64 cannot compute on + // upper halves of SIMD registers, so we must split each half into + // separate registers. To compensate, we pair computations up and + // parallelize. + + ext v19.8b, v4.8b, v4.8b, #4 // B4 + eor v18.16b, v18.16b, v2.16b // N = I + J + pmull v19.8h, v6.8b, v19.8b // K = A*B4 + + // This can probably be scheduled more efficiently. For now, we just + // pair up independent instructions. + zip1 v20.2d, v16.2d, v17.2d + zip1 v22.2d, v18.2d, v19.2d + zip2 v21.2d, v16.2d, v17.2d + zip2 v23.2d, v18.2d, v19.2d + eor v20.16b, v20.16b, v21.16b + eor v22.16b, v22.16b, v23.16b + and v21.16b, v21.16b, v24.16b + and v23.16b, v23.16b, v25.16b + eor v20.16b, v20.16b, v21.16b + eor v22.16b, v22.16b, v23.16b + zip1 v16.2d, v20.2d, v21.2d + zip1 v18.2d, v22.2d, v23.2d + zip2 v17.2d, v20.2d, v21.2d + zip2 v19.2d, v22.2d, v23.2d + + ext v16.16b, v16.16b, v16.16b, #15 // t0 = t0 << 8 + ext v17.16b, v17.16b, v17.16b, #14 // t1 = t1 << 16 + pmull v2.8h, v6.8b, v4.8b // D = A*B + ext v19.16b, v19.16b, v19.16b, #12 // t3 = t3 << 32 + ext v18.16b, v18.16b, v18.16b, #13 // t2 = t2 << 24 + eor v16.16b, v16.16b, v17.16b + eor v18.16b, v18.16b, v19.16b + eor v2.16b, v2.16b, v16.16b + eor v2.16b, v2.16b, v18.16b + ext v16.16b, v0.16b, v2.16b, #8 + eor v1.16b, v1.16b, v0.16b // Karatsuba post-processing + eor v1.16b, v1.16b, v2.16b + eor v1.16b, v1.16b, v16.16b // Xm overlaps Xh.lo and Xl.hi + ins v0.d[1], v1.d[0] // Xh|Xl - 256-bit result + // This is a no-op due to the ins instruction below. + // ins v2.d[0], v1.d[1] + + // equivalent of reduction_avx from ghash-x86_64.pl + shl v17.2d, v0.2d, #57 // 1st phase + shl v18.2d, v0.2d, #62 + eor v18.16b, v18.16b, v17.16b // + shl v17.2d, v0.2d, #63 + eor v18.16b, v18.16b, v17.16b // + // Note Xm contains {Xl.d[1], Xh.d[0]}. + eor v18.16b, v18.16b, v1.16b + ins v0.d[1], v18.d[0] // Xl.d[1] ^= t2.d[0] + ins v2.d[0], v18.d[1] // Xh.d[0] ^= t2.d[1] + + ushr v18.2d, v0.2d, #1 // 2nd phase + eor v2.16b, v2.16b,v0.16b + eor v0.16b, v0.16b,v18.16b // + ushr v18.2d, v18.2d, #6 + ushr v0.2d, v0.2d, #1 // + eor v0.16b, v0.16b, v2.16b // + eor v0.16b, v0.16b, v18.16b // + + subs x3, x3, #16 + bne Loop_neon + + rev64 v0.16b, v0.16b // byteswap Xi and write + ext v0.16b, v0.16b, v0.16b, #8 + st1 {v0.16b}, [x0] + + ret + + +.section __TEXT,__const +.align 4 +Lmasks: +.quad 0x0000ffffffffffff // k48 +.quad 0x00000000ffffffff // k32 +.quad 0x000000000000ffff // k16 +.quad 0x0000000000000000 // k0 +.byte 71,72,65,83,72,32,102,111,114,32,65,82,77,118,56,44,32,100,101,114,105,118,101,100,32,102,114,111,109,32,65,82,77,118,52,32,118,101,114,115,105,111,110,32,98,121,32,60,97,112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103,62,0 +.align 2 +.align 2 +#endif // !OPENSSL_NO_ASM diff --git a/third_party/boringssl/kit/ios-aarch64/crypto/fipsmodule/vpaes-armv8.S b/third_party/boringssl/kit/ios-aarch64/crypto/fipsmodule/vpaes-armv8.S new file mode 100644 index 00000000..0ad9bbf3 --- /dev/null +++ b/third_party/boringssl/kit/ios-aarch64/crypto/fipsmodule/vpaes-armv8.S @@ -0,0 +1,1212 @@ +// This file is generated from a similarly-named Perl script in the BoringSSL +// source tree. Do not edit by hand. + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) +#define OPENSSL_NO_ASM +#endif +#endif + +#if !defined(OPENSSL_NO_ASM) +#if defined(BORINGSSL_PREFIX) +#include +#endif +.section __TEXT,__const + + +.align 7 // totally strategic alignment +_vpaes_consts: +Lk_mc_forward: // mc_forward +.quad 0x0407060500030201, 0x0C0F0E0D080B0A09 +.quad 0x080B0A0904070605, 0x000302010C0F0E0D +.quad 0x0C0F0E0D080B0A09, 0x0407060500030201 +.quad 0x000302010C0F0E0D, 0x080B0A0904070605 +Lk_mc_backward: // mc_backward +.quad 0x0605040702010003, 0x0E0D0C0F0A09080B +.quad 0x020100030E0D0C0F, 0x0A09080B06050407 +.quad 0x0E0D0C0F0A09080B, 0x0605040702010003 +.quad 0x0A09080B06050407, 0x020100030E0D0C0F +Lk_sr: // sr +.quad 0x0706050403020100, 0x0F0E0D0C0B0A0908 +.quad 0x030E09040F0A0500, 0x0B06010C07020D08 +.quad 0x0F060D040B020900, 0x070E050C030A0108 +.quad 0x0B0E0104070A0D00, 0x0306090C0F020508 + +// +// "Hot" constants +// +Lk_inv: // inv, inva +.quad 0x0E05060F0D080180, 0x040703090A0B0C02 +.quad 0x01040A060F0B0780, 0x030D0E0C02050809 +Lk_ipt: // input transform (lo, hi) +.quad 0xC2B2E8985A2A7000, 0xCABAE09052227808 +.quad 0x4C01307D317C4D00, 0xCD80B1FCB0FDCC81 +Lk_sbo: // sbou, sbot +.quad 0xD0D26D176FBDC700, 0x15AABF7AC502A878 +.quad 0xCFE474A55FBB6A00, 0x8E1E90D1412B35FA +Lk_sb1: // sb1u, sb1t +.quad 0x3618D415FAE22300, 0x3BF7CCC10D2ED9EF +.quad 0xB19BE18FCB503E00, 0xA5DF7A6E142AF544 +Lk_sb2: // sb2u, sb2t +.quad 0x69EB88400AE12900, 0xC2A163C8AB82234A +.quad 0xE27A93C60B712400, 0x5EB7E955BC982FCD + +// +// Decryption stuff +// +Lk_dipt: // decryption input transform +.quad 0x0F505B040B545F00, 0x154A411E114E451A +.quad 0x86E383E660056500, 0x12771772F491F194 +Lk_dsbo: // decryption sbox final output +.quad 0x1387EA537EF94000, 0xC7AA6DB9D4943E2D +.quad 0x12D7560F93441D00, 0xCA4B8159D8C58E9C +Lk_dsb9: // decryption sbox output *9*u, *9*t +.quad 0x851C03539A86D600, 0xCAD51F504F994CC9 +.quad 0xC03B1789ECD74900, 0x725E2C9EB2FBA565 +Lk_dsbd: // decryption sbox output *D*u, *D*t +.quad 0x7D57CCDFE6B1A200, 0xF56E9B13882A4439 +.quad 0x3CE2FAF724C6CB00, 0x2931180D15DEEFD3 +Lk_dsbb: // decryption sbox output *B*u, *B*t +.quad 0xD022649296B44200, 0x602646F6B0F2D404 +.quad 0xC19498A6CD596700, 0xF3FF0C3E3255AA6B +Lk_dsbe: // decryption sbox output *E*u, *E*t +.quad 0x46F2929626D4D000, 0x2242600464B4F6B0 +.quad 0x0C55A6CDFFAAC100, 0x9467F36B98593E32 + +// +// Key schedule constants +// +Lk_dksd: // decryption key schedule: invskew x*D +.quad 0xFEB91A5DA3E44700, 0x0740E3A45A1DBEF9 +.quad 0x41C277F4B5368300, 0x5FDC69EAAB289D1E +Lk_dksb: // decryption key schedule: invskew x*B +.quad 0x9A4FCA1F8550D500, 0x03D653861CC94C99 +.quad 0x115BEDA7B6FC4A00, 0xD993256F7E3482C8 +Lk_dkse: // decryption key schedule: invskew x*E + 0x63 +.quad 0xD5031CCA1FC9D600, 0x53859A4C994F5086 +.quad 0xA23196054FDC7BE8, 0xCD5EF96A20B31487 +Lk_dks9: // decryption key schedule: invskew x*9 +.quad 0xB6116FC87ED9A700, 0x4AED933482255BFC +.quad 0x4576516227143300, 0x8BB89FACE9DAFDCE + +Lk_rcon: // rcon +.quad 0x1F8391B9AF9DEEB6, 0x702A98084D7C7D81 + +Lk_opt: // output transform +.quad 0xFF9F4929D6B66000, 0xF7974121DEBE6808 +.quad 0x01EDBD5150BCEC00, 0xE10D5DB1B05C0CE0 +Lk_deskew: // deskew tables: inverts the sbox's "skew" +.quad 0x07E4A34047A4E300, 0x1DFEB95A5DBEF91A +.quad 0x5F36B5DC83EA6900, 0x2841C2ABF49D1E77 + +.byte 86,101,99,116,111,114,32,80,101,114,109,117,116,97,116,105,111,110,32,65,69,83,32,102,111,114,32,65,82,77,118,56,44,32,77,105,107,101,32,72,97,109,98,117,114,103,32,40,83,116,97,110,102,111,114,100,32,85,110,105,118,101,114,115,105,116,121,41,0 +.align 2 + +.align 6 + +.text +## +## _aes_preheat +## +## Fills register %r10 -> .aes_consts (so you can -fPIC) +## and %xmm9-%xmm15 as specified below. +## + +.align 4 +_vpaes_encrypt_preheat: + adrp x10, Lk_inv@PAGE + add x10, x10, Lk_inv@PAGEOFF + movi v17.16b, #0x0f + ld1 {v18.2d,v19.2d}, [x10],#32 // Lk_inv + ld1 {v20.2d,v21.2d,v22.2d,v23.2d}, [x10],#64 // Lk_ipt, Lk_sbo + ld1 {v24.2d,v25.2d,v26.2d,v27.2d}, [x10] // Lk_sb1, Lk_sb2 + ret + + +## +## _aes_encrypt_core +## +## AES-encrypt %xmm0. +## +## Inputs: +## %xmm0 = input +## %xmm9-%xmm15 as in _vpaes_preheat +## (%rdx) = scheduled keys +## +## Output in %xmm0 +## Clobbers %xmm1-%xmm5, %r9, %r10, %r11, %rax +## Preserves %xmm6 - %xmm8 so you get some local vectors +## +## + +.align 4 +_vpaes_encrypt_core: + mov x9, x2 + ldr w8, [x2,#240] // pull rounds + adrp x11, Lk_mc_forward@PAGE+16 + add x11, x11, Lk_mc_forward@PAGEOFF+16 + // vmovdqa .Lk_ipt(%rip), %xmm2 # iptlo + ld1 {v16.2d}, [x9], #16 // vmovdqu (%r9), %xmm5 # round0 key + and v1.16b, v7.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 + ushr v0.16b, v7.16b, #4 // vpsrlb $4, %xmm0, %xmm0 + tbl v1.16b, {v20.16b}, v1.16b // vpshufb %xmm1, %xmm2, %xmm1 + // vmovdqa .Lk_ipt+16(%rip), %xmm3 # ipthi + tbl v2.16b, {v21.16b}, v0.16b // vpshufb %xmm0, %xmm3, %xmm2 + eor v0.16b, v1.16b, v16.16b // vpxor %xmm5, %xmm1, %xmm0 + eor v0.16b, v0.16b, v2.16b // vpxor %xmm2, %xmm0, %xmm0 + b Lenc_entry + +.align 4 +Lenc_loop: + // middle of middle round + add x10, x11, #0x40 + tbl v4.16b, {v25.16b}, v2.16b // vpshufb %xmm2, %xmm13, %xmm4 # 4 = sb1u + ld1 {v1.2d}, [x11], #16 // vmovdqa -0x40(%r11,%r10), %xmm1 # Lk_mc_forward[] + tbl v0.16b, {v24.16b}, v3.16b // vpshufb %xmm3, %xmm12, %xmm0 # 0 = sb1t + eor v4.16b, v4.16b, v16.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = sb1u + k + tbl v5.16b, {v27.16b}, v2.16b // vpshufb %xmm2, %xmm15, %xmm5 # 4 = sb2u + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = A + tbl v2.16b, {v26.16b}, v3.16b // vpshufb %xmm3, %xmm14, %xmm2 # 2 = sb2t + ld1 {v4.2d}, [x10] // vmovdqa (%r11,%r10), %xmm4 # Lk_mc_backward[] + tbl v3.16b, {v0.16b}, v1.16b // vpshufb %xmm1, %xmm0, %xmm3 # 0 = B + eor v2.16b, v2.16b, v5.16b // vpxor %xmm5, %xmm2, %xmm2 # 2 = 2A + tbl v0.16b, {v0.16b}, v4.16b // vpshufb %xmm4, %xmm0, %xmm0 # 3 = D + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 # 0 = 2A+B + tbl v4.16b, {v3.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm4 # 0 = 2B+C + eor v0.16b, v0.16b, v3.16b // vpxor %xmm3, %xmm0, %xmm0 # 3 = 2A+B+D + and x11, x11, #~(1<<6) // and $0x30, %r11 # ... mod 4 + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = 2A+3B+C+D + sub w8, w8, #1 // nr-- + +Lenc_entry: + // top of round + and v1.16b, v0.16b, v17.16b // vpand %xmm0, %xmm9, %xmm1 # 0 = k + ushr v0.16b, v0.16b, #4 // vpsrlb $4, %xmm0, %xmm0 # 1 = i + tbl v5.16b, {v19.16b}, v1.16b // vpshufb %xmm1, %xmm11, %xmm5 # 2 = a/k + eor v1.16b, v1.16b, v0.16b // vpxor %xmm0, %xmm1, %xmm1 # 0 = j + tbl v3.16b, {v18.16b}, v0.16b // vpshufb %xmm0, %xmm10, %xmm3 # 3 = 1/i + tbl v4.16b, {v18.16b}, v1.16b // vpshufb %xmm1, %xmm10, %xmm4 # 4 = 1/j + eor v3.16b, v3.16b, v5.16b // vpxor %xmm5, %xmm3, %xmm3 # 3 = iak = 1/i + a/k + eor v4.16b, v4.16b, v5.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = jak = 1/j + a/k + tbl v2.16b, {v18.16b}, v3.16b // vpshufb %xmm3, %xmm10, %xmm2 # 2 = 1/iak + tbl v3.16b, {v18.16b}, v4.16b // vpshufb %xmm4, %xmm10, %xmm3 # 3 = 1/jak + eor v2.16b, v2.16b, v1.16b // vpxor %xmm1, %xmm2, %xmm2 # 2 = io + eor v3.16b, v3.16b, v0.16b // vpxor %xmm0, %xmm3, %xmm3 # 3 = jo + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm5 + cbnz w8, Lenc_loop + + // middle of last round + add x10, x11, #0x80 + // vmovdqa -0x60(%r10), %xmm4 # 3 : sbou .Lk_sbo + // vmovdqa -0x50(%r10), %xmm0 # 0 : sbot .Lk_sbo+16 + tbl v4.16b, {v22.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbou + ld1 {v1.2d}, [x10] // vmovdqa 0x40(%r11,%r10), %xmm1 # Lk_sr[] + tbl v0.16b, {v23.16b}, v3.16b // vpshufb %xmm3, %xmm0, %xmm0 # 0 = sb1t + eor v4.16b, v4.16b, v16.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = sb1u + k + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = A + tbl v0.16b, {v0.16b}, v1.16b // vpshufb %xmm1, %xmm0, %xmm0 + ret + + +.globl _vpaes_encrypt +.private_extern _vpaes_encrypt + +.align 4 +_vpaes_encrypt: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + + ld1 {v7.16b}, [x0] + bl _vpaes_encrypt_preheat + bl _vpaes_encrypt_core + st1 {v0.16b}, [x1] + + ldp x29,x30,[sp],#16 + ret + + + +.align 4 +_vpaes_encrypt_2x: + mov x9, x2 + ldr w8, [x2,#240] // pull rounds + adrp x11, Lk_mc_forward@PAGE+16 + add x11, x11, Lk_mc_forward@PAGEOFF+16 + // vmovdqa .Lk_ipt(%rip), %xmm2 # iptlo + ld1 {v16.2d}, [x9], #16 // vmovdqu (%r9), %xmm5 # round0 key + and v1.16b, v14.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 + ushr v0.16b, v14.16b, #4 // vpsrlb $4, %xmm0, %xmm0 + and v9.16b, v15.16b, v17.16b + ushr v8.16b, v15.16b, #4 + tbl v1.16b, {v20.16b}, v1.16b // vpshufb %xmm1, %xmm2, %xmm1 + tbl v9.16b, {v20.16b}, v9.16b + // vmovdqa .Lk_ipt+16(%rip), %xmm3 # ipthi + tbl v2.16b, {v21.16b}, v0.16b // vpshufb %xmm0, %xmm3, %xmm2 + tbl v10.16b, {v21.16b}, v8.16b + eor v0.16b, v1.16b, v16.16b // vpxor %xmm5, %xmm1, %xmm0 + eor v8.16b, v9.16b, v16.16b + eor v0.16b, v0.16b, v2.16b // vpxor %xmm2, %xmm0, %xmm0 + eor v8.16b, v8.16b, v10.16b + b Lenc_2x_entry + +.align 4 +Lenc_2x_loop: + // middle of middle round + add x10, x11, #0x40 + tbl v4.16b, {v25.16b}, v2.16b // vpshufb %xmm2, %xmm13, %xmm4 # 4 = sb1u + tbl v12.16b, {v25.16b}, v10.16b + ld1 {v1.2d}, [x11], #16 // vmovdqa -0x40(%r11,%r10), %xmm1 # Lk_mc_forward[] + tbl v0.16b, {v24.16b}, v3.16b // vpshufb %xmm3, %xmm12, %xmm0 # 0 = sb1t + tbl v8.16b, {v24.16b}, v11.16b + eor v4.16b, v4.16b, v16.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = sb1u + k + eor v12.16b, v12.16b, v16.16b + tbl v5.16b, {v27.16b}, v2.16b // vpshufb %xmm2, %xmm15, %xmm5 # 4 = sb2u + tbl v13.16b, {v27.16b}, v10.16b + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = A + eor v8.16b, v8.16b, v12.16b + tbl v2.16b, {v26.16b}, v3.16b // vpshufb %xmm3, %xmm14, %xmm2 # 2 = sb2t + tbl v10.16b, {v26.16b}, v11.16b + ld1 {v4.2d}, [x10] // vmovdqa (%r11,%r10), %xmm4 # Lk_mc_backward[] + tbl v3.16b, {v0.16b}, v1.16b // vpshufb %xmm1, %xmm0, %xmm3 # 0 = B + tbl v11.16b, {v8.16b}, v1.16b + eor v2.16b, v2.16b, v5.16b // vpxor %xmm5, %xmm2, %xmm2 # 2 = 2A + eor v10.16b, v10.16b, v13.16b + tbl v0.16b, {v0.16b}, v4.16b // vpshufb %xmm4, %xmm0, %xmm0 # 3 = D + tbl v8.16b, {v8.16b}, v4.16b + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 # 0 = 2A+B + eor v11.16b, v11.16b, v10.16b + tbl v4.16b, {v3.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm4 # 0 = 2B+C + tbl v12.16b, {v11.16b},v1.16b + eor v0.16b, v0.16b, v3.16b // vpxor %xmm3, %xmm0, %xmm0 # 3 = 2A+B+D + eor v8.16b, v8.16b, v11.16b + and x11, x11, #~(1<<6) // and $0x30, %r11 # ... mod 4 + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = 2A+3B+C+D + eor v8.16b, v8.16b, v12.16b + sub w8, w8, #1 // nr-- + +Lenc_2x_entry: + // top of round + and v1.16b, v0.16b, v17.16b // vpand %xmm0, %xmm9, %xmm1 # 0 = k + ushr v0.16b, v0.16b, #4 // vpsrlb $4, %xmm0, %xmm0 # 1 = i + and v9.16b, v8.16b, v17.16b + ushr v8.16b, v8.16b, #4 + tbl v5.16b, {v19.16b},v1.16b // vpshufb %xmm1, %xmm11, %xmm5 # 2 = a/k + tbl v13.16b, {v19.16b},v9.16b + eor v1.16b, v1.16b, v0.16b // vpxor %xmm0, %xmm1, %xmm1 # 0 = j + eor v9.16b, v9.16b, v8.16b + tbl v3.16b, {v18.16b},v0.16b // vpshufb %xmm0, %xmm10, %xmm3 # 3 = 1/i + tbl v11.16b, {v18.16b},v8.16b + tbl v4.16b, {v18.16b},v1.16b // vpshufb %xmm1, %xmm10, %xmm4 # 4 = 1/j + tbl v12.16b, {v18.16b},v9.16b + eor v3.16b, v3.16b, v5.16b // vpxor %xmm5, %xmm3, %xmm3 # 3 = iak = 1/i + a/k + eor v11.16b, v11.16b, v13.16b + eor v4.16b, v4.16b, v5.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = jak = 1/j + a/k + eor v12.16b, v12.16b, v13.16b + tbl v2.16b, {v18.16b},v3.16b // vpshufb %xmm3, %xmm10, %xmm2 # 2 = 1/iak + tbl v10.16b, {v18.16b},v11.16b + tbl v3.16b, {v18.16b},v4.16b // vpshufb %xmm4, %xmm10, %xmm3 # 3 = 1/jak + tbl v11.16b, {v18.16b},v12.16b + eor v2.16b, v2.16b, v1.16b // vpxor %xmm1, %xmm2, %xmm2 # 2 = io + eor v10.16b, v10.16b, v9.16b + eor v3.16b, v3.16b, v0.16b // vpxor %xmm0, %xmm3, %xmm3 # 3 = jo + eor v11.16b, v11.16b, v8.16b + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm5 + cbnz w8, Lenc_2x_loop + + // middle of last round + add x10, x11, #0x80 + // vmovdqa -0x60(%r10), %xmm4 # 3 : sbou .Lk_sbo + // vmovdqa -0x50(%r10), %xmm0 # 0 : sbot .Lk_sbo+16 + tbl v4.16b, {v22.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbou + tbl v12.16b, {v22.16b}, v10.16b + ld1 {v1.2d}, [x10] // vmovdqa 0x40(%r11,%r10), %xmm1 # Lk_sr[] + tbl v0.16b, {v23.16b}, v3.16b // vpshufb %xmm3, %xmm0, %xmm0 # 0 = sb1t + tbl v8.16b, {v23.16b}, v11.16b + eor v4.16b, v4.16b, v16.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = sb1u + k + eor v12.16b, v12.16b, v16.16b + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = A + eor v8.16b, v8.16b, v12.16b + tbl v0.16b, {v0.16b},v1.16b // vpshufb %xmm1, %xmm0, %xmm0 + tbl v1.16b, {v8.16b},v1.16b + ret + + + +.align 4 +_vpaes_decrypt_preheat: + adrp x10, Lk_inv@PAGE + add x10, x10, Lk_inv@PAGEOFF + movi v17.16b, #0x0f + adrp x11, Lk_dipt@PAGE + add x11, x11, Lk_dipt@PAGEOFF + ld1 {v18.2d,v19.2d}, [x10],#32 // Lk_inv + ld1 {v20.2d,v21.2d,v22.2d,v23.2d}, [x11],#64 // Lk_dipt, Lk_dsbo + ld1 {v24.2d,v25.2d,v26.2d,v27.2d}, [x11],#64 // Lk_dsb9, Lk_dsbd + ld1 {v28.2d,v29.2d,v30.2d,v31.2d}, [x11] // Lk_dsbb, Lk_dsbe + ret + + +## +## Decryption core +## +## Same API as encryption core. +## + +.align 4 +_vpaes_decrypt_core: + mov x9, x2 + ldr w8, [x2,#240] // pull rounds + + // vmovdqa .Lk_dipt(%rip), %xmm2 # iptlo + lsl x11, x8, #4 // mov %rax, %r11; shl $4, %r11 + eor x11, x11, #0x30 // xor $0x30, %r11 + adrp x10, Lk_sr@PAGE + add x10, x10, Lk_sr@PAGEOFF + and x11, x11, #0x30 // and $0x30, %r11 + add x11, x11, x10 + adrp x10, Lk_mc_forward@PAGE+48 + add x10, x10, Lk_mc_forward@PAGEOFF+48 + + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm4 # round0 key + and v1.16b, v7.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 + ushr v0.16b, v7.16b, #4 // vpsrlb $4, %xmm0, %xmm0 + tbl v2.16b, {v20.16b}, v1.16b // vpshufb %xmm1, %xmm2, %xmm2 + ld1 {v5.2d}, [x10] // vmovdqa Lk_mc_forward+48(%rip), %xmm5 + // vmovdqa .Lk_dipt+16(%rip), %xmm1 # ipthi + tbl v0.16b, {v21.16b}, v0.16b // vpshufb %xmm0, %xmm1, %xmm0 + eor v2.16b, v2.16b, v16.16b // vpxor %xmm4, %xmm2, %xmm2 + eor v0.16b, v0.16b, v2.16b // vpxor %xmm2, %xmm0, %xmm0 + b Ldec_entry + +.align 4 +Ldec_loop: +// +// Inverse mix columns +// + // vmovdqa -0x20(%r10),%xmm4 # 4 : sb9u + // vmovdqa -0x10(%r10),%xmm1 # 0 : sb9t + tbl v4.16b, {v24.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sb9u + tbl v1.16b, {v25.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sb9t + eor v0.16b, v4.16b, v16.16b // vpxor %xmm4, %xmm0, %xmm0 + // vmovdqa 0x00(%r10),%xmm4 # 4 : sbdu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + // vmovdqa 0x10(%r10),%xmm1 # 0 : sbdt + + tbl v4.16b, {v26.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbdu + tbl v0.16b, {v0.16b}, v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v1.16b, {v27.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbdt + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + // vmovdqa 0x20(%r10), %xmm4 # 4 : sbbu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + // vmovdqa 0x30(%r10), %xmm1 # 0 : sbbt + + tbl v4.16b, {v28.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbbu + tbl v0.16b, {v0.16b}, v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v1.16b, {v29.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbbt + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + // vmovdqa 0x40(%r10), %xmm4 # 4 : sbeu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + // vmovdqa 0x50(%r10), %xmm1 # 0 : sbet + + tbl v4.16b, {v30.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbeu + tbl v0.16b, {v0.16b}, v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v1.16b, {v31.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbet + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + ext v5.16b, v5.16b, v5.16b, #12 // vpalignr $12, %xmm5, %xmm5, %xmm5 + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + sub w8, w8, #1 // sub $1,%rax # nr-- + +Ldec_entry: + // top of round + and v1.16b, v0.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 # 0 = k + ushr v0.16b, v0.16b, #4 // vpsrlb $4, %xmm0, %xmm0 # 1 = i + tbl v2.16b, {v19.16b}, v1.16b // vpshufb %xmm1, %xmm11, %xmm2 # 2 = a/k + eor v1.16b, v1.16b, v0.16b // vpxor %xmm0, %xmm1, %xmm1 # 0 = j + tbl v3.16b, {v18.16b}, v0.16b // vpshufb %xmm0, %xmm10, %xmm3 # 3 = 1/i + tbl v4.16b, {v18.16b}, v1.16b // vpshufb %xmm1, %xmm10, %xmm4 # 4 = 1/j + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 # 3 = iak = 1/i + a/k + eor v4.16b, v4.16b, v2.16b // vpxor %xmm2, %xmm4, %xmm4 # 4 = jak = 1/j + a/k + tbl v2.16b, {v18.16b}, v3.16b // vpshufb %xmm3, %xmm10, %xmm2 # 2 = 1/iak + tbl v3.16b, {v18.16b}, v4.16b // vpshufb %xmm4, %xmm10, %xmm3 # 3 = 1/jak + eor v2.16b, v2.16b, v1.16b // vpxor %xmm1, %xmm2, %xmm2 # 2 = io + eor v3.16b, v3.16b, v0.16b // vpxor %xmm0, %xmm3, %xmm3 # 3 = jo + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm0 + cbnz w8, Ldec_loop + + // middle of last round + // vmovdqa 0x60(%r10), %xmm4 # 3 : sbou + tbl v4.16b, {v22.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbou + // vmovdqa 0x70(%r10), %xmm1 # 0 : sbot + ld1 {v2.2d}, [x11] // vmovdqa -0x160(%r11), %xmm2 # Lk_sr-Lk_dsbd=-0x160 + tbl v1.16b, {v23.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sb1t + eor v4.16b, v4.16b, v16.16b // vpxor %xmm0, %xmm4, %xmm4 # 4 = sb1u + k + eor v0.16b, v1.16b, v4.16b // vpxor %xmm4, %xmm1, %xmm0 # 0 = A + tbl v0.16b, {v0.16b}, v2.16b // vpshufb %xmm2, %xmm0, %xmm0 + ret + + +.globl _vpaes_decrypt +.private_extern _vpaes_decrypt + +.align 4 +_vpaes_decrypt: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + + ld1 {v7.16b}, [x0] + bl _vpaes_decrypt_preheat + bl _vpaes_decrypt_core + st1 {v0.16b}, [x1] + + ldp x29,x30,[sp],#16 + ret + + +// v14-v15 input, v0-v1 output + +.align 4 +_vpaes_decrypt_2x: + mov x9, x2 + ldr w8, [x2,#240] // pull rounds + + // vmovdqa .Lk_dipt(%rip), %xmm2 # iptlo + lsl x11, x8, #4 // mov %rax, %r11; shl $4, %r11 + eor x11, x11, #0x30 // xor $0x30, %r11 + adrp x10, Lk_sr@PAGE + add x10, x10, Lk_sr@PAGEOFF + and x11, x11, #0x30 // and $0x30, %r11 + add x11, x11, x10 + adrp x10, Lk_mc_forward@PAGE+48 + add x10, x10, Lk_mc_forward@PAGEOFF+48 + + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm4 # round0 key + and v1.16b, v14.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 + ushr v0.16b, v14.16b, #4 // vpsrlb $4, %xmm0, %xmm0 + and v9.16b, v15.16b, v17.16b + ushr v8.16b, v15.16b, #4 + tbl v2.16b, {v20.16b},v1.16b // vpshufb %xmm1, %xmm2, %xmm2 + tbl v10.16b, {v20.16b},v9.16b + ld1 {v5.2d}, [x10] // vmovdqa Lk_mc_forward+48(%rip), %xmm5 + // vmovdqa .Lk_dipt+16(%rip), %xmm1 # ipthi + tbl v0.16b, {v21.16b},v0.16b // vpshufb %xmm0, %xmm1, %xmm0 + tbl v8.16b, {v21.16b},v8.16b + eor v2.16b, v2.16b, v16.16b // vpxor %xmm4, %xmm2, %xmm2 + eor v10.16b, v10.16b, v16.16b + eor v0.16b, v0.16b, v2.16b // vpxor %xmm2, %xmm0, %xmm0 + eor v8.16b, v8.16b, v10.16b + b Ldec_2x_entry + +.align 4 +Ldec_2x_loop: +// +// Inverse mix columns +// + // vmovdqa -0x20(%r10),%xmm4 # 4 : sb9u + // vmovdqa -0x10(%r10),%xmm1 # 0 : sb9t + tbl v4.16b, {v24.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sb9u + tbl v12.16b, {v24.16b}, v10.16b + tbl v1.16b, {v25.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sb9t + tbl v9.16b, {v25.16b}, v11.16b + eor v0.16b, v4.16b, v16.16b // vpxor %xmm4, %xmm0, %xmm0 + eor v8.16b, v12.16b, v16.16b + // vmovdqa 0x00(%r10),%xmm4 # 4 : sbdu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + eor v8.16b, v8.16b, v9.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + // vmovdqa 0x10(%r10),%xmm1 # 0 : sbdt + + tbl v4.16b, {v26.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbdu + tbl v12.16b, {v26.16b}, v10.16b + tbl v0.16b, {v0.16b},v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v8.16b, {v8.16b},v5.16b + tbl v1.16b, {v27.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbdt + tbl v9.16b, {v27.16b}, v11.16b + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + eor v8.16b, v8.16b, v12.16b + // vmovdqa 0x20(%r10), %xmm4 # 4 : sbbu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + eor v8.16b, v8.16b, v9.16b + // vmovdqa 0x30(%r10), %xmm1 # 0 : sbbt + + tbl v4.16b, {v28.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbbu + tbl v12.16b, {v28.16b}, v10.16b + tbl v0.16b, {v0.16b},v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v8.16b, {v8.16b},v5.16b + tbl v1.16b, {v29.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbbt + tbl v9.16b, {v29.16b}, v11.16b + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + eor v8.16b, v8.16b, v12.16b + // vmovdqa 0x40(%r10), %xmm4 # 4 : sbeu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + eor v8.16b, v8.16b, v9.16b + // vmovdqa 0x50(%r10), %xmm1 # 0 : sbet + + tbl v4.16b, {v30.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbeu + tbl v12.16b, {v30.16b}, v10.16b + tbl v0.16b, {v0.16b},v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v8.16b, {v8.16b},v5.16b + tbl v1.16b, {v31.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbet + tbl v9.16b, {v31.16b}, v11.16b + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + eor v8.16b, v8.16b, v12.16b + ext v5.16b, v5.16b, v5.16b, #12 // vpalignr $12, %xmm5, %xmm5, %xmm5 + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + eor v8.16b, v8.16b, v9.16b + sub w8, w8, #1 // sub $1,%rax # nr-- + +Ldec_2x_entry: + // top of round + and v1.16b, v0.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 # 0 = k + ushr v0.16b, v0.16b, #4 // vpsrlb $4, %xmm0, %xmm0 # 1 = i + and v9.16b, v8.16b, v17.16b + ushr v8.16b, v8.16b, #4 + tbl v2.16b, {v19.16b},v1.16b // vpshufb %xmm1, %xmm11, %xmm2 # 2 = a/k + tbl v10.16b, {v19.16b},v9.16b + eor v1.16b, v1.16b, v0.16b // vpxor %xmm0, %xmm1, %xmm1 # 0 = j + eor v9.16b, v9.16b, v8.16b + tbl v3.16b, {v18.16b},v0.16b // vpshufb %xmm0, %xmm10, %xmm3 # 3 = 1/i + tbl v11.16b, {v18.16b},v8.16b + tbl v4.16b, {v18.16b},v1.16b // vpshufb %xmm1, %xmm10, %xmm4 # 4 = 1/j + tbl v12.16b, {v18.16b},v9.16b + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 # 3 = iak = 1/i + a/k + eor v11.16b, v11.16b, v10.16b + eor v4.16b, v4.16b, v2.16b // vpxor %xmm2, %xmm4, %xmm4 # 4 = jak = 1/j + a/k + eor v12.16b, v12.16b, v10.16b + tbl v2.16b, {v18.16b},v3.16b // vpshufb %xmm3, %xmm10, %xmm2 # 2 = 1/iak + tbl v10.16b, {v18.16b},v11.16b + tbl v3.16b, {v18.16b},v4.16b // vpshufb %xmm4, %xmm10, %xmm3 # 3 = 1/jak + tbl v11.16b, {v18.16b},v12.16b + eor v2.16b, v2.16b, v1.16b // vpxor %xmm1, %xmm2, %xmm2 # 2 = io + eor v10.16b, v10.16b, v9.16b + eor v3.16b, v3.16b, v0.16b // vpxor %xmm0, %xmm3, %xmm3 # 3 = jo + eor v11.16b, v11.16b, v8.16b + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm0 + cbnz w8, Ldec_2x_loop + + // middle of last round + // vmovdqa 0x60(%r10), %xmm4 # 3 : sbou + tbl v4.16b, {v22.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbou + tbl v12.16b, {v22.16b}, v10.16b + // vmovdqa 0x70(%r10), %xmm1 # 0 : sbot + tbl v1.16b, {v23.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sb1t + tbl v9.16b, {v23.16b}, v11.16b + ld1 {v2.2d}, [x11] // vmovdqa -0x160(%r11), %xmm2 # Lk_sr-Lk_dsbd=-0x160 + eor v4.16b, v4.16b, v16.16b // vpxor %xmm0, %xmm4, %xmm4 # 4 = sb1u + k + eor v12.16b, v12.16b, v16.16b + eor v0.16b, v1.16b, v4.16b // vpxor %xmm4, %xmm1, %xmm0 # 0 = A + eor v8.16b, v9.16b, v12.16b + tbl v0.16b, {v0.16b},v2.16b // vpshufb %xmm2, %xmm0, %xmm0 + tbl v1.16b, {v8.16b},v2.16b + ret + +######################################################## +## ## +## AES key schedule ## +## ## +######################################################## + +.align 4 +_vpaes_key_preheat: + adrp x10, Lk_inv@PAGE + add x10, x10, Lk_inv@PAGEOFF + movi v16.16b, #0x5b // Lk_s63 + adrp x11, Lk_sb1@PAGE + add x11, x11, Lk_sb1@PAGEOFF + movi v17.16b, #0x0f // Lk_s0F + ld1 {v18.2d,v19.2d,v20.2d,v21.2d}, [x10] // Lk_inv, Lk_ipt + adrp x10, Lk_dksd@PAGE + add x10, x10, Lk_dksd@PAGEOFF + ld1 {v22.2d,v23.2d}, [x11] // Lk_sb1 + adrp x11, Lk_mc_forward@PAGE + add x11, x11, Lk_mc_forward@PAGEOFF + ld1 {v24.2d,v25.2d,v26.2d,v27.2d}, [x10],#64 // Lk_dksd, Lk_dksb + ld1 {v28.2d,v29.2d,v30.2d,v31.2d}, [x10],#64 // Lk_dkse, Lk_dks9 + ld1 {v8.2d}, [x10] // Lk_rcon + ld1 {v9.2d}, [x11] // Lk_mc_forward[0] + ret + + + +.align 4 +_vpaes_schedule_core: + stp x29, x30, [sp,#-16]! + add x29,sp,#0 + + bl _vpaes_key_preheat // load the tables + + ld1 {v0.16b}, [x0],#16 // vmovdqu (%rdi), %xmm0 # load key (unaligned) + + // input transform + mov v3.16b, v0.16b // vmovdqa %xmm0, %xmm3 + bl _vpaes_schedule_transform + mov v7.16b, v0.16b // vmovdqa %xmm0, %xmm7 + + adrp x10, Lk_sr@PAGE // lea Lk_sr(%rip),%r10 + add x10, x10, Lk_sr@PAGEOFF + + add x8, x8, x10 + cbnz w3, Lschedule_am_decrypting + + // encrypting, output zeroth round key after transform + st1 {v0.2d}, [x2] // vmovdqu %xmm0, (%rdx) + b Lschedule_go + +Lschedule_am_decrypting: + // decrypting, output zeroth round key after shiftrows + ld1 {v1.2d}, [x8] // vmovdqa (%r8,%r10), %xmm1 + tbl v3.16b, {v3.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm3 + st1 {v3.2d}, [x2] // vmovdqu %xmm3, (%rdx) + eor x8, x8, #0x30 // xor $0x30, %r8 + +Lschedule_go: + cmp w1, #192 // cmp $192, %esi + b.hi Lschedule_256 + b.eq Lschedule_192 + // 128: fall though + +## +## .schedule_128 +## +## 128-bit specific part of key schedule. +## +## This schedule is really simple, because all its parts +## are accomplished by the subroutines. +## +Lschedule_128: + mov x0, #10 // mov $10, %esi + +Loop_schedule_128: + sub x0, x0, #1 // dec %esi + bl _vpaes_schedule_round + cbz x0, Lschedule_mangle_last + bl _vpaes_schedule_mangle // write output + b Loop_schedule_128 + +## +## .aes_schedule_192 +## +## 192-bit specific part of key schedule. +## +## The main body of this schedule is the same as the 128-bit +## schedule, but with more smearing. The long, high side is +## stored in %xmm7 as before, and the short, low side is in +## the high bits of %xmm6. +## +## This schedule is somewhat nastier, however, because each +## round produces 192 bits of key material, or 1.5 round keys. +## Therefore, on each cycle we do 2 rounds and produce 3 round +## keys. +## +.align 4 +Lschedule_192: + sub x0, x0, #8 + ld1 {v0.16b}, [x0] // vmovdqu 8(%rdi),%xmm0 # load key part 2 (very unaligned) + bl _vpaes_schedule_transform // input transform + mov v6.16b, v0.16b // vmovdqa %xmm0, %xmm6 # save short part + eor v4.16b, v4.16b, v4.16b // vpxor %xmm4, %xmm4, %xmm4 # clear 4 + ins v6.d[0], v4.d[0] // vmovhlps %xmm4, %xmm6, %xmm6 # clobber low side with zeros + mov x0, #4 // mov $4, %esi + +Loop_schedule_192: + sub x0, x0, #1 // dec %esi + bl _vpaes_schedule_round + ext v0.16b, v6.16b, v0.16b, #8 // vpalignr $8,%xmm6,%xmm0,%xmm0 + bl _vpaes_schedule_mangle // save key n + bl _vpaes_schedule_192_smear + bl _vpaes_schedule_mangle // save key n+1 + bl _vpaes_schedule_round + cbz x0, Lschedule_mangle_last + bl _vpaes_schedule_mangle // save key n+2 + bl _vpaes_schedule_192_smear + b Loop_schedule_192 + +## +## .aes_schedule_256 +## +## 256-bit specific part of key schedule. +## +## The structure here is very similar to the 128-bit +## schedule, but with an additional "low side" in +## %xmm6. The low side's rounds are the same as the +## high side's, except no rcon and no rotation. +## +.align 4 +Lschedule_256: + ld1 {v0.16b}, [x0] // vmovdqu 16(%rdi),%xmm0 # load key part 2 (unaligned) + bl _vpaes_schedule_transform // input transform + mov x0, #7 // mov $7, %esi + +Loop_schedule_256: + sub x0, x0, #1 // dec %esi + bl _vpaes_schedule_mangle // output low result + mov v6.16b, v0.16b // vmovdqa %xmm0, %xmm6 # save cur_lo in xmm6 + + // high round + bl _vpaes_schedule_round + cbz x0, Lschedule_mangle_last + bl _vpaes_schedule_mangle + + // low round. swap xmm7 and xmm6 + dup v0.4s, v0.s[3] // vpshufd $0xFF, %xmm0, %xmm0 + movi v4.16b, #0 + mov v5.16b, v7.16b // vmovdqa %xmm7, %xmm5 + mov v7.16b, v6.16b // vmovdqa %xmm6, %xmm7 + bl _vpaes_schedule_low_round + mov v7.16b, v5.16b // vmovdqa %xmm5, %xmm7 + + b Loop_schedule_256 + +## +## .aes_schedule_mangle_last +## +## Mangler for last round of key schedule +## Mangles %xmm0 +## when encrypting, outputs out(%xmm0) ^ 63 +## when decrypting, outputs unskew(%xmm0) +## +## Always called right before return... jumps to cleanup and exits +## +.align 4 +Lschedule_mangle_last: + // schedule last round key from xmm0 + adrp x11, Lk_deskew@PAGE // lea Lk_deskew(%rip),%r11 # prepare to deskew + add x11, x11, Lk_deskew@PAGEOFF + + cbnz w3, Lschedule_mangle_last_dec + + // encrypting + ld1 {v1.2d}, [x8] // vmovdqa (%r8,%r10),%xmm1 + adrp x11, Lk_opt@PAGE // lea Lk_opt(%rip), %r11 # prepare to output transform + add x11, x11, Lk_opt@PAGEOFF + add x2, x2, #32 // add $32, %rdx + tbl v0.16b, {v0.16b}, v1.16b // vpshufb %xmm1, %xmm0, %xmm0 # output permute + +Lschedule_mangle_last_dec: + ld1 {v20.2d,v21.2d}, [x11] // reload constants + sub x2, x2, #16 // add $-16, %rdx + eor v0.16b, v0.16b, v16.16b // vpxor Lk_s63(%rip), %xmm0, %xmm0 + bl _vpaes_schedule_transform // output transform + st1 {v0.2d}, [x2] // vmovdqu %xmm0, (%rdx) # save last key + + // cleanup + eor v0.16b, v0.16b, v0.16b // vpxor %xmm0, %xmm0, %xmm0 + eor v1.16b, v1.16b, v1.16b // vpxor %xmm1, %xmm1, %xmm1 + eor v2.16b, v2.16b, v2.16b // vpxor %xmm2, %xmm2, %xmm2 + eor v3.16b, v3.16b, v3.16b // vpxor %xmm3, %xmm3, %xmm3 + eor v4.16b, v4.16b, v4.16b // vpxor %xmm4, %xmm4, %xmm4 + eor v5.16b, v5.16b, v5.16b // vpxor %xmm5, %xmm5, %xmm5 + eor v6.16b, v6.16b, v6.16b // vpxor %xmm6, %xmm6, %xmm6 + eor v7.16b, v7.16b, v7.16b // vpxor %xmm7, %xmm7, %xmm7 + ldp x29, x30, [sp],#16 + ret + + +## +## .aes_schedule_192_smear +## +## Smear the short, low side in the 192-bit key schedule. +## +## Inputs: +## %xmm7: high side, b a x y +## %xmm6: low side, d c 0 0 +## %xmm13: 0 +## +## Outputs: +## %xmm6: b+c+d b+c 0 0 +## %xmm0: b+c+d b+c b a +## + +.align 4 +_vpaes_schedule_192_smear: + movi v1.16b, #0 + dup v0.4s, v7.s[3] + ins v1.s[3], v6.s[2] // vpshufd $0x80, %xmm6, %xmm1 # d c 0 0 -> c 0 0 0 + ins v0.s[0], v7.s[2] // vpshufd $0xFE, %xmm7, %xmm0 # b a _ _ -> b b b a + eor v6.16b, v6.16b, v1.16b // vpxor %xmm1, %xmm6, %xmm6 # -> c+d c 0 0 + eor v1.16b, v1.16b, v1.16b // vpxor %xmm1, %xmm1, %xmm1 + eor v6.16b, v6.16b, v0.16b // vpxor %xmm0, %xmm6, %xmm6 # -> b+c+d b+c b a + mov v0.16b, v6.16b // vmovdqa %xmm6, %xmm0 + ins v6.d[0], v1.d[0] // vmovhlps %xmm1, %xmm6, %xmm6 # clobber low side with zeros + ret + + +## +## .aes_schedule_round +## +## Runs one main round of the key schedule on %xmm0, %xmm7 +## +## Specifically, runs subbytes on the high dword of %xmm0 +## then rotates it by one byte and xors into the low dword of +## %xmm7. +## +## Adds rcon from low byte of %xmm8, then rotates %xmm8 for +## next rcon. +## +## Smears the dwords of %xmm7 by xoring the low into the +## second low, result into third, result into highest. +## +## Returns results in %xmm7 = %xmm0. +## Clobbers %xmm1-%xmm4, %r11. +## + +.align 4 +_vpaes_schedule_round: + // extract rcon from xmm8 + movi v4.16b, #0 // vpxor %xmm4, %xmm4, %xmm4 + ext v1.16b, v8.16b, v4.16b, #15 // vpalignr $15, %xmm8, %xmm4, %xmm1 + ext v8.16b, v8.16b, v8.16b, #15 // vpalignr $15, %xmm8, %xmm8, %xmm8 + eor v7.16b, v7.16b, v1.16b // vpxor %xmm1, %xmm7, %xmm7 + + // rotate + dup v0.4s, v0.s[3] // vpshufd $0xFF, %xmm0, %xmm0 + ext v0.16b, v0.16b, v0.16b, #1 // vpalignr $1, %xmm0, %xmm0, %xmm0 + + // fall through... + + // low round: same as high round, but no rotation and no rcon. +_vpaes_schedule_low_round: + // smear xmm7 + ext v1.16b, v4.16b, v7.16b, #12 // vpslldq $4, %xmm7, %xmm1 + eor v7.16b, v7.16b, v1.16b // vpxor %xmm1, %xmm7, %xmm7 + ext v4.16b, v4.16b, v7.16b, #8 // vpslldq $8, %xmm7, %xmm4 + + // subbytes + and v1.16b, v0.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 # 0 = k + ushr v0.16b, v0.16b, #4 // vpsrlb $4, %xmm0, %xmm0 # 1 = i + eor v7.16b, v7.16b, v4.16b // vpxor %xmm4, %xmm7, %xmm7 + tbl v2.16b, {v19.16b}, v1.16b // vpshufb %xmm1, %xmm11, %xmm2 # 2 = a/k + eor v1.16b, v1.16b, v0.16b // vpxor %xmm0, %xmm1, %xmm1 # 0 = j + tbl v3.16b, {v18.16b}, v0.16b // vpshufb %xmm0, %xmm10, %xmm3 # 3 = 1/i + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 # 3 = iak = 1/i + a/k + tbl v4.16b, {v18.16b}, v1.16b // vpshufb %xmm1, %xmm10, %xmm4 # 4 = 1/j + eor v7.16b, v7.16b, v16.16b // vpxor Lk_s63(%rip), %xmm7, %xmm7 + tbl v3.16b, {v18.16b}, v3.16b // vpshufb %xmm3, %xmm10, %xmm3 # 2 = 1/iak + eor v4.16b, v4.16b, v2.16b // vpxor %xmm2, %xmm4, %xmm4 # 4 = jak = 1/j + a/k + tbl v2.16b, {v18.16b}, v4.16b // vpshufb %xmm4, %xmm10, %xmm2 # 3 = 1/jak + eor v3.16b, v3.16b, v1.16b // vpxor %xmm1, %xmm3, %xmm3 # 2 = io + eor v2.16b, v2.16b, v0.16b // vpxor %xmm0, %xmm2, %xmm2 # 3 = jo + tbl v4.16b, {v23.16b}, v3.16b // vpshufb %xmm3, %xmm13, %xmm4 # 4 = sbou + tbl v1.16b, {v22.16b}, v2.16b // vpshufb %xmm2, %xmm12, %xmm1 # 0 = sb1t + eor v1.16b, v1.16b, v4.16b // vpxor %xmm4, %xmm1, %xmm1 # 0 = sbox output + + // add in smeared stuff + eor v0.16b, v1.16b, v7.16b // vpxor %xmm7, %xmm1, %xmm0 + eor v7.16b, v1.16b, v7.16b // vmovdqa %xmm0, %xmm7 + ret + + +## +## .aes_schedule_transform +## +## Linear-transform %xmm0 according to tables at (%r11) +## +## Requires that %xmm9 = 0x0F0F... as in preheat +## Output in %xmm0 +## Clobbers %xmm1, %xmm2 +## + +.align 4 +_vpaes_schedule_transform: + and v1.16b, v0.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 + ushr v0.16b, v0.16b, #4 // vpsrlb $4, %xmm0, %xmm0 + // vmovdqa (%r11), %xmm2 # lo + tbl v2.16b, {v20.16b}, v1.16b // vpshufb %xmm1, %xmm2, %xmm2 + // vmovdqa 16(%r11), %xmm1 # hi + tbl v0.16b, {v21.16b}, v0.16b // vpshufb %xmm0, %xmm1, %xmm0 + eor v0.16b, v0.16b, v2.16b // vpxor %xmm2, %xmm0, %xmm0 + ret + + +## +## .aes_schedule_mangle +## +## Mangle xmm0 from (basis-transformed) standard version +## to our version. +## +## On encrypt, +## xor with 0x63 +## multiply by circulant 0,1,1,1 +## apply shiftrows transform +## +## On decrypt, +## xor with 0x63 +## multiply by "inverse mixcolumns" circulant E,B,D,9 +## deskew +## apply shiftrows transform +## +## +## Writes out to (%rdx), and increments or decrements it +## Keeps track of round number mod 4 in %r8 +## Preserves xmm0 +## Clobbers xmm1-xmm5 +## + +.align 4 +_vpaes_schedule_mangle: + mov v4.16b, v0.16b // vmovdqa %xmm0, %xmm4 # save xmm0 for later + // vmovdqa .Lk_mc_forward(%rip),%xmm5 + cbnz w3, Lschedule_mangle_dec + + // encrypting + eor v4.16b, v0.16b, v16.16b // vpxor Lk_s63(%rip), %xmm0, %xmm4 + add x2, x2, #16 // add $16, %rdx + tbl v4.16b, {v4.16b}, v9.16b // vpshufb %xmm5, %xmm4, %xmm4 + tbl v1.16b, {v4.16b}, v9.16b // vpshufb %xmm5, %xmm4, %xmm1 + tbl v3.16b, {v1.16b}, v9.16b // vpshufb %xmm5, %xmm1, %xmm3 + eor v4.16b, v4.16b, v1.16b // vpxor %xmm1, %xmm4, %xmm4 + ld1 {v1.2d}, [x8] // vmovdqa (%r8,%r10), %xmm1 + eor v3.16b, v3.16b, v4.16b // vpxor %xmm4, %xmm3, %xmm3 + + b Lschedule_mangle_both +.align 4 +Lschedule_mangle_dec: + // inverse mix columns + // lea .Lk_dksd(%rip),%r11 + ushr v1.16b, v4.16b, #4 // vpsrlb $4, %xmm4, %xmm1 # 1 = hi + and v4.16b, v4.16b, v17.16b // vpand %xmm9, %xmm4, %xmm4 # 4 = lo + + // vmovdqa 0x00(%r11), %xmm2 + tbl v2.16b, {v24.16b}, v4.16b // vpshufb %xmm4, %xmm2, %xmm2 + // vmovdqa 0x10(%r11), %xmm3 + tbl v3.16b, {v25.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm3 + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 + tbl v3.16b, {v3.16b}, v9.16b // vpshufb %xmm5, %xmm3, %xmm3 + + // vmovdqa 0x20(%r11), %xmm2 + tbl v2.16b, {v26.16b}, v4.16b // vpshufb %xmm4, %xmm2, %xmm2 + eor v2.16b, v2.16b, v3.16b // vpxor %xmm3, %xmm2, %xmm2 + // vmovdqa 0x30(%r11), %xmm3 + tbl v3.16b, {v27.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm3 + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 + tbl v3.16b, {v3.16b}, v9.16b // vpshufb %xmm5, %xmm3, %xmm3 + + // vmovdqa 0x40(%r11), %xmm2 + tbl v2.16b, {v28.16b}, v4.16b // vpshufb %xmm4, %xmm2, %xmm2 + eor v2.16b, v2.16b, v3.16b // vpxor %xmm3, %xmm2, %xmm2 + // vmovdqa 0x50(%r11), %xmm3 + tbl v3.16b, {v29.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm3 + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 + + // vmovdqa 0x60(%r11), %xmm2 + tbl v2.16b, {v30.16b}, v4.16b // vpshufb %xmm4, %xmm2, %xmm2 + tbl v3.16b, {v3.16b}, v9.16b // vpshufb %xmm5, %xmm3, %xmm3 + // vmovdqa 0x70(%r11), %xmm4 + tbl v4.16b, {v31.16b}, v1.16b // vpshufb %xmm1, %xmm4, %xmm4 + ld1 {v1.2d}, [x8] // vmovdqa (%r8,%r10), %xmm1 + eor v2.16b, v2.16b, v3.16b // vpxor %xmm3, %xmm2, %xmm2 + eor v3.16b, v4.16b, v2.16b // vpxor %xmm2, %xmm4, %xmm3 + + sub x2, x2, #16 // add $-16, %rdx + +Lschedule_mangle_both: + tbl v3.16b, {v3.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm3 + add x8, x8, #64-16 // add $-16, %r8 + and x8, x8, #~(1<<6) // and $0x30, %r8 + st1 {v3.2d}, [x2] // vmovdqu %xmm3, (%rdx) + ret + + +.globl _vpaes_set_encrypt_key +.private_extern _vpaes_set_encrypt_key + +.align 4 +_vpaes_set_encrypt_key: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + stp d8,d9,[sp,#-16]! // ABI spec says so + + lsr w9, w1, #5 // shr $5,%eax + add w9, w9, #5 // $5,%eax + str w9, [x2,#240] // mov %eax,240(%rdx) # AES_KEY->rounds = nbits/32+5; + + mov w3, #0 // mov $0,%ecx + mov x8, #0x30 // mov $0x30,%r8d + bl _vpaes_schedule_core + eor x0, x0, x0 + + ldp d8,d9,[sp],#16 + ldp x29,x30,[sp],#16 + ret + + +.globl _vpaes_set_decrypt_key +.private_extern _vpaes_set_decrypt_key + +.align 4 +_vpaes_set_decrypt_key: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + stp d8,d9,[sp,#-16]! // ABI spec says so + + lsr w9, w1, #5 // shr $5,%eax + add w9, w9, #5 // $5,%eax + str w9, [x2,#240] // mov %eax,240(%rdx) # AES_KEY->rounds = nbits/32+5; + lsl w9, w9, #4 // shl $4,%eax + add x2, x2, #16 // lea 16(%rdx,%rax),%rdx + add x2, x2, x9 + + mov w3, #1 // mov $1,%ecx + lsr w8, w1, #1 // shr $1,%r8d + and x8, x8, #32 // and $32,%r8d + eor x8, x8, #32 // xor $32,%r8d # nbits==192?0:32 + bl _vpaes_schedule_core + + ldp d8,d9,[sp],#16 + ldp x29,x30,[sp],#16 + ret + +.globl _vpaes_cbc_encrypt +.private_extern _vpaes_cbc_encrypt + +.align 4 +_vpaes_cbc_encrypt: + cbz x2, Lcbc_abort + cmp w5, #0 // check direction + b.eq vpaes_cbc_decrypt + + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + + mov x17, x2 // reassign + mov x2, x3 // reassign + + ld1 {v0.16b}, [x4] // load ivec + bl _vpaes_encrypt_preheat + b Lcbc_enc_loop + +.align 4 +Lcbc_enc_loop: + ld1 {v7.16b}, [x0],#16 // load input + eor v7.16b, v7.16b, v0.16b // xor with ivec + bl _vpaes_encrypt_core + st1 {v0.16b}, [x1],#16 // save output + subs x17, x17, #16 + b.hi Lcbc_enc_loop + + st1 {v0.16b}, [x4] // write ivec + + ldp x29,x30,[sp],#16 +Lcbc_abort: + ret + + + +.align 4 +vpaes_cbc_decrypt: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + stp d8,d9,[sp,#-16]! // ABI spec says so + stp d10,d11,[sp,#-16]! + stp d12,d13,[sp,#-16]! + stp d14,d15,[sp,#-16]! + + mov x17, x2 // reassign + mov x2, x3 // reassign + ld1 {v6.16b}, [x4] // load ivec + bl _vpaes_decrypt_preheat + tst x17, #16 + b.eq Lcbc_dec_loop2x + + ld1 {v7.16b}, [x0], #16 // load input + bl _vpaes_decrypt_core + eor v0.16b, v0.16b, v6.16b // xor with ivec + orr v6.16b, v7.16b, v7.16b // next ivec value + st1 {v0.16b}, [x1], #16 + subs x17, x17, #16 + b.ls Lcbc_dec_done + +.align 4 +Lcbc_dec_loop2x: + ld1 {v14.16b,v15.16b}, [x0], #32 + bl _vpaes_decrypt_2x + eor v0.16b, v0.16b, v6.16b // xor with ivec + eor v1.16b, v1.16b, v14.16b + orr v6.16b, v15.16b, v15.16b + st1 {v0.16b,v1.16b}, [x1], #32 + subs x17, x17, #32 + b.hi Lcbc_dec_loop2x + +Lcbc_dec_done: + st1 {v6.16b}, [x4] + + ldp d14,d15,[sp],#16 + ldp d12,d13,[sp],#16 + ldp d10,d11,[sp],#16 + ldp d8,d9,[sp],#16 + ldp x29,x30,[sp],#16 + ret + +.globl _vpaes_ctr32_encrypt_blocks +.private_extern _vpaes_ctr32_encrypt_blocks + +.align 4 +_vpaes_ctr32_encrypt_blocks: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + stp d8,d9,[sp,#-16]! // ABI spec says so + stp d10,d11,[sp,#-16]! + stp d12,d13,[sp,#-16]! + stp d14,d15,[sp,#-16]! + + cbz x2, Lctr32_done + + // Note, unlike the other functions, x2 here is measured in blocks, + // not bytes. + mov x17, x2 + mov x2, x3 + + // Load the IV and counter portion. + ldr w6, [x4, #12] + ld1 {v7.16b}, [x4] + + bl _vpaes_encrypt_preheat + tst x17, #1 + rev w6, w6 // The counter is big-endian. + b.eq Lctr32_prep_loop + + // Handle one block so the remaining block count is even for + // _vpaes_encrypt_2x. + ld1 {v6.16b}, [x0], #16 // Load input ahead of time + bl _vpaes_encrypt_core + eor v0.16b, v0.16b, v6.16b // XOR input and result + st1 {v0.16b}, [x1], #16 + subs x17, x17, #1 + // Update the counter. + add w6, w6, #1 + rev w7, w6 + mov v7.s[3], w7 + b.ls Lctr32_done + +Lctr32_prep_loop: + // _vpaes_encrypt_core takes its input from v7, while _vpaes_encrypt_2x + // uses v14 and v15. + mov v15.16b, v7.16b + mov v14.16b, v7.16b + add w6, w6, #1 + rev w7, w6 + mov v15.s[3], w7 + +Lctr32_loop: + ld1 {v6.16b,v7.16b}, [x0], #32 // Load input ahead of time + bl _vpaes_encrypt_2x + eor v0.16b, v0.16b, v6.16b // XOR input and result + eor v1.16b, v1.16b, v7.16b // XOR input and result (#2) + st1 {v0.16b,v1.16b}, [x1], #32 + subs x17, x17, #2 + // Update the counter. + add w7, w6, #1 + add w6, w6, #2 + rev w7, w7 + mov v14.s[3], w7 + rev w7, w6 + mov v15.s[3], w7 + b.hi Lctr32_loop + +Lctr32_done: + ldp d14,d15,[sp],#16 + ldp d12,d13,[sp],#16 + ldp d10,d11,[sp],#16 + ldp d8,d9,[sp],#16 + ldp x29,x30,[sp],#16 + ret + +#endif // !OPENSSL_NO_ASM diff --git a/third_party/boringssl/kit/ios-aarch64/crypto/test/trampoline-armv8.S b/third_party/boringssl/kit/ios-aarch64/crypto/test/trampoline-armv8.S new file mode 100644 index 00000000..95a41fe5 --- /dev/null +++ b/third_party/boringssl/kit/ios-aarch64/crypto/test/trampoline-armv8.S @@ -0,0 +1,684 @@ +// This file is generated from a similarly-named Perl script in the BoringSSL +// source tree. Do not edit by hand. + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) +#define OPENSSL_NO_ASM +#endif +#endif + +#if !defined(OPENSSL_NO_ASM) +#if defined(BORINGSSL_PREFIX) +#include +#endif +.text + +// abi_test_trampoline loads callee-saved registers from |state|, calls |func| +// with |argv|, then saves the callee-saved registers into |state|. It returns +// the result of |func|. The |unwind| argument is unused. +// uint64_t abi_test_trampoline(void (*func)(...), CallerState *state, +// const uint64_t *argv, size_t argc, +// uint64_t unwind); + +.globl _abi_test_trampoline +.private_extern _abi_test_trampoline +.align 4 +_abi_test_trampoline: +Labi_test_trampoline_begin: + // Stack layout (low to high addresses) + // x29,x30 (16 bytes) + // d8-d15 (64 bytes) + // x19-x28 (80 bytes) + // x1 (8 bytes) + // padding (8 bytes) + stp x29, x30, [sp, #-176]! + mov x29, sp + + // Saved callee-saved registers and |state|. + stp d8, d9, [sp, #16] + stp d10, d11, [sp, #32] + stp d12, d13, [sp, #48] + stp d14, d15, [sp, #64] + stp x19, x20, [sp, #80] + stp x21, x22, [sp, #96] + stp x23, x24, [sp, #112] + stp x25, x26, [sp, #128] + stp x27, x28, [sp, #144] + str x1, [sp, #160] + + // Load registers from |state|, with the exception of x29. x29 is the + // frame pointer and also callee-saved, but AAPCS64 allows platforms to + // mandate that x29 always point to a frame. iOS64 does so, which means + // we cannot fill x29 with entropy without violating ABI rules + // ourselves. x29 is tested separately below. + ldp d8, d9, [x1], #16 + ldp d10, d11, [x1], #16 + ldp d12, d13, [x1], #16 + ldp d14, d15, [x1], #16 + ldp x19, x20, [x1], #16 + ldp x21, x22, [x1], #16 + ldp x23, x24, [x1], #16 + ldp x25, x26, [x1], #16 + ldp x27, x28, [x1], #16 + + // Move parameters into temporary registers. + mov x9, x0 + mov x10, x2 + mov x11, x3 + + // Load parameters into registers. + cbz x11, Largs_done + ldr x0, [x10], #8 + subs x11, x11, #1 + b.eq Largs_done + ldr x1, [x10], #8 + subs x11, x11, #1 + b.eq Largs_done + ldr x2, [x10], #8 + subs x11, x11, #1 + b.eq Largs_done + ldr x3, [x10], #8 + subs x11, x11, #1 + b.eq Largs_done + ldr x4, [x10], #8 + subs x11, x11, #1 + b.eq Largs_done + ldr x5, [x10], #8 + subs x11, x11, #1 + b.eq Largs_done + ldr x6, [x10], #8 + subs x11, x11, #1 + b.eq Largs_done + ldr x7, [x10], #8 + +Largs_done: + blr x9 + + // Reload |state| and store registers. + ldr x1, [sp, #160] + stp d8, d9, [x1], #16 + stp d10, d11, [x1], #16 + stp d12, d13, [x1], #16 + stp d14, d15, [x1], #16 + stp x19, x20, [x1], #16 + stp x21, x22, [x1], #16 + stp x23, x24, [x1], #16 + stp x25, x26, [x1], #16 + stp x27, x28, [x1], #16 + + // |func| is required to preserve x29, the frame pointer. We cannot load + // random values into x29 (see comment above), so compare it against the + // expected value and zero the field of |state| if corrupted. + mov x9, sp + cmp x29, x9 + b.eq Lx29_ok + str xzr, [x1] + +Lx29_ok: + // Restore callee-saved registers. + ldp d8, d9, [sp, #16] + ldp d10, d11, [sp, #32] + ldp d12, d13, [sp, #48] + ldp d14, d15, [sp, #64] + ldp x19, x20, [sp, #80] + ldp x21, x22, [sp, #96] + ldp x23, x24, [sp, #112] + ldp x25, x26, [sp, #128] + ldp x27, x28, [sp, #144] + + ldp x29, x30, [sp], #176 + ret + + +.globl _abi_test_clobber_x0 +.private_extern _abi_test_clobber_x0 +.align 4 +_abi_test_clobber_x0: + mov x0, xzr + ret + + +.globl _abi_test_clobber_x1 +.private_extern _abi_test_clobber_x1 +.align 4 +_abi_test_clobber_x1: + mov x1, xzr + ret + + +.globl _abi_test_clobber_x2 +.private_extern _abi_test_clobber_x2 +.align 4 +_abi_test_clobber_x2: + mov x2, xzr + ret + + +.globl _abi_test_clobber_x3 +.private_extern _abi_test_clobber_x3 +.align 4 +_abi_test_clobber_x3: + mov x3, xzr + ret + + +.globl _abi_test_clobber_x4 +.private_extern _abi_test_clobber_x4 +.align 4 +_abi_test_clobber_x4: + mov x4, xzr + ret + + +.globl _abi_test_clobber_x5 +.private_extern _abi_test_clobber_x5 +.align 4 +_abi_test_clobber_x5: + mov x5, xzr + ret + + +.globl _abi_test_clobber_x6 +.private_extern _abi_test_clobber_x6 +.align 4 +_abi_test_clobber_x6: + mov x6, xzr + ret + + +.globl _abi_test_clobber_x7 +.private_extern _abi_test_clobber_x7 +.align 4 +_abi_test_clobber_x7: + mov x7, xzr + ret + + +.globl _abi_test_clobber_x8 +.private_extern _abi_test_clobber_x8 +.align 4 +_abi_test_clobber_x8: + mov x8, xzr + ret + + +.globl _abi_test_clobber_x9 +.private_extern _abi_test_clobber_x9 +.align 4 +_abi_test_clobber_x9: + mov x9, xzr + ret + + +.globl _abi_test_clobber_x10 +.private_extern _abi_test_clobber_x10 +.align 4 +_abi_test_clobber_x10: + mov x10, xzr + ret + + +.globl _abi_test_clobber_x11 +.private_extern _abi_test_clobber_x11 +.align 4 +_abi_test_clobber_x11: + mov x11, xzr + ret + + +.globl _abi_test_clobber_x12 +.private_extern _abi_test_clobber_x12 +.align 4 +_abi_test_clobber_x12: + mov x12, xzr + ret + + +.globl _abi_test_clobber_x13 +.private_extern _abi_test_clobber_x13 +.align 4 +_abi_test_clobber_x13: + mov x13, xzr + ret + + +.globl _abi_test_clobber_x14 +.private_extern _abi_test_clobber_x14 +.align 4 +_abi_test_clobber_x14: + mov x14, xzr + ret + + +.globl _abi_test_clobber_x15 +.private_extern _abi_test_clobber_x15 +.align 4 +_abi_test_clobber_x15: + mov x15, xzr + ret + + +.globl _abi_test_clobber_x16 +.private_extern _abi_test_clobber_x16 +.align 4 +_abi_test_clobber_x16: + mov x16, xzr + ret + + +.globl _abi_test_clobber_x17 +.private_extern _abi_test_clobber_x17 +.align 4 +_abi_test_clobber_x17: + mov x17, xzr + ret + + +.globl _abi_test_clobber_x19 +.private_extern _abi_test_clobber_x19 +.align 4 +_abi_test_clobber_x19: + mov x19, xzr + ret + + +.globl _abi_test_clobber_x20 +.private_extern _abi_test_clobber_x20 +.align 4 +_abi_test_clobber_x20: + mov x20, xzr + ret + + +.globl _abi_test_clobber_x21 +.private_extern _abi_test_clobber_x21 +.align 4 +_abi_test_clobber_x21: + mov x21, xzr + ret + + +.globl _abi_test_clobber_x22 +.private_extern _abi_test_clobber_x22 +.align 4 +_abi_test_clobber_x22: + mov x22, xzr + ret + + +.globl _abi_test_clobber_x23 +.private_extern _abi_test_clobber_x23 +.align 4 +_abi_test_clobber_x23: + mov x23, xzr + ret + + +.globl _abi_test_clobber_x24 +.private_extern _abi_test_clobber_x24 +.align 4 +_abi_test_clobber_x24: + mov x24, xzr + ret + + +.globl _abi_test_clobber_x25 +.private_extern _abi_test_clobber_x25 +.align 4 +_abi_test_clobber_x25: + mov x25, xzr + ret + + +.globl _abi_test_clobber_x26 +.private_extern _abi_test_clobber_x26 +.align 4 +_abi_test_clobber_x26: + mov x26, xzr + ret + + +.globl _abi_test_clobber_x27 +.private_extern _abi_test_clobber_x27 +.align 4 +_abi_test_clobber_x27: + mov x27, xzr + ret + + +.globl _abi_test_clobber_x28 +.private_extern _abi_test_clobber_x28 +.align 4 +_abi_test_clobber_x28: + mov x28, xzr + ret + + +.globl _abi_test_clobber_x29 +.private_extern _abi_test_clobber_x29 +.align 4 +_abi_test_clobber_x29: + mov x29, xzr + ret + + +.globl _abi_test_clobber_d0 +.private_extern _abi_test_clobber_d0 +.align 4 +_abi_test_clobber_d0: + fmov d0, xzr + ret + + +.globl _abi_test_clobber_d1 +.private_extern _abi_test_clobber_d1 +.align 4 +_abi_test_clobber_d1: + fmov d1, xzr + ret + + +.globl _abi_test_clobber_d2 +.private_extern _abi_test_clobber_d2 +.align 4 +_abi_test_clobber_d2: + fmov d2, xzr + ret + + +.globl _abi_test_clobber_d3 +.private_extern _abi_test_clobber_d3 +.align 4 +_abi_test_clobber_d3: + fmov d3, xzr + ret + + +.globl _abi_test_clobber_d4 +.private_extern _abi_test_clobber_d4 +.align 4 +_abi_test_clobber_d4: + fmov d4, xzr + ret + + +.globl _abi_test_clobber_d5 +.private_extern _abi_test_clobber_d5 +.align 4 +_abi_test_clobber_d5: + fmov d5, xzr + ret + + +.globl _abi_test_clobber_d6 +.private_extern _abi_test_clobber_d6 +.align 4 +_abi_test_clobber_d6: + fmov d6, xzr + ret + + +.globl _abi_test_clobber_d7 +.private_extern _abi_test_clobber_d7 +.align 4 +_abi_test_clobber_d7: + fmov d7, xzr + ret + + +.globl _abi_test_clobber_d8 +.private_extern _abi_test_clobber_d8 +.align 4 +_abi_test_clobber_d8: + fmov d8, xzr + ret + + +.globl _abi_test_clobber_d9 +.private_extern _abi_test_clobber_d9 +.align 4 +_abi_test_clobber_d9: + fmov d9, xzr + ret + + +.globl _abi_test_clobber_d10 +.private_extern _abi_test_clobber_d10 +.align 4 +_abi_test_clobber_d10: + fmov d10, xzr + ret + + +.globl _abi_test_clobber_d11 +.private_extern _abi_test_clobber_d11 +.align 4 +_abi_test_clobber_d11: + fmov d11, xzr + ret + + +.globl _abi_test_clobber_d12 +.private_extern _abi_test_clobber_d12 +.align 4 +_abi_test_clobber_d12: + fmov d12, xzr + ret + + +.globl _abi_test_clobber_d13 +.private_extern _abi_test_clobber_d13 +.align 4 +_abi_test_clobber_d13: + fmov d13, xzr + ret + + +.globl _abi_test_clobber_d14 +.private_extern _abi_test_clobber_d14 +.align 4 +_abi_test_clobber_d14: + fmov d14, xzr + ret + + +.globl _abi_test_clobber_d15 +.private_extern _abi_test_clobber_d15 +.align 4 +_abi_test_clobber_d15: + fmov d15, xzr + ret + + +.globl _abi_test_clobber_d16 +.private_extern _abi_test_clobber_d16 +.align 4 +_abi_test_clobber_d16: + fmov d16, xzr + ret + + +.globl _abi_test_clobber_d17 +.private_extern _abi_test_clobber_d17 +.align 4 +_abi_test_clobber_d17: + fmov d17, xzr + ret + + +.globl _abi_test_clobber_d18 +.private_extern _abi_test_clobber_d18 +.align 4 +_abi_test_clobber_d18: + fmov d18, xzr + ret + + +.globl _abi_test_clobber_d19 +.private_extern _abi_test_clobber_d19 +.align 4 +_abi_test_clobber_d19: + fmov d19, xzr + ret + + +.globl _abi_test_clobber_d20 +.private_extern _abi_test_clobber_d20 +.align 4 +_abi_test_clobber_d20: + fmov d20, xzr + ret + + +.globl _abi_test_clobber_d21 +.private_extern _abi_test_clobber_d21 +.align 4 +_abi_test_clobber_d21: + fmov d21, xzr + ret + + +.globl _abi_test_clobber_d22 +.private_extern _abi_test_clobber_d22 +.align 4 +_abi_test_clobber_d22: + fmov d22, xzr + ret + + +.globl _abi_test_clobber_d23 +.private_extern _abi_test_clobber_d23 +.align 4 +_abi_test_clobber_d23: + fmov d23, xzr + ret + + +.globl _abi_test_clobber_d24 +.private_extern _abi_test_clobber_d24 +.align 4 +_abi_test_clobber_d24: + fmov d24, xzr + ret + + +.globl _abi_test_clobber_d25 +.private_extern _abi_test_clobber_d25 +.align 4 +_abi_test_clobber_d25: + fmov d25, xzr + ret + + +.globl _abi_test_clobber_d26 +.private_extern _abi_test_clobber_d26 +.align 4 +_abi_test_clobber_d26: + fmov d26, xzr + ret + + +.globl _abi_test_clobber_d27 +.private_extern _abi_test_clobber_d27 +.align 4 +_abi_test_clobber_d27: + fmov d27, xzr + ret + + +.globl _abi_test_clobber_d28 +.private_extern _abi_test_clobber_d28 +.align 4 +_abi_test_clobber_d28: + fmov d28, xzr + ret + + +.globl _abi_test_clobber_d29 +.private_extern _abi_test_clobber_d29 +.align 4 +_abi_test_clobber_d29: + fmov d29, xzr + ret + + +.globl _abi_test_clobber_d30 +.private_extern _abi_test_clobber_d30 +.align 4 +_abi_test_clobber_d30: + fmov d30, xzr + ret + + +.globl _abi_test_clobber_d31 +.private_extern _abi_test_clobber_d31 +.align 4 +_abi_test_clobber_d31: + fmov d31, xzr + ret + + +.globl _abi_test_clobber_v8_upper +.private_extern _abi_test_clobber_v8_upper +.align 4 +_abi_test_clobber_v8_upper: + fmov v8.d[1], xzr + ret + + +.globl _abi_test_clobber_v9_upper +.private_extern _abi_test_clobber_v9_upper +.align 4 +_abi_test_clobber_v9_upper: + fmov v9.d[1], xzr + ret + + +.globl _abi_test_clobber_v10_upper +.private_extern _abi_test_clobber_v10_upper +.align 4 +_abi_test_clobber_v10_upper: + fmov v10.d[1], xzr + ret + + +.globl _abi_test_clobber_v11_upper +.private_extern _abi_test_clobber_v11_upper +.align 4 +_abi_test_clobber_v11_upper: + fmov v11.d[1], xzr + ret + + +.globl _abi_test_clobber_v12_upper +.private_extern _abi_test_clobber_v12_upper +.align 4 +_abi_test_clobber_v12_upper: + fmov v12.d[1], xzr + ret + + +.globl _abi_test_clobber_v13_upper +.private_extern _abi_test_clobber_v13_upper +.align 4 +_abi_test_clobber_v13_upper: + fmov v13.d[1], xzr + ret + + +.globl _abi_test_clobber_v14_upper +.private_extern _abi_test_clobber_v14_upper +.align 4 +_abi_test_clobber_v14_upper: + fmov v14.d[1], xzr + ret + + +.globl _abi_test_clobber_v15_upper +.private_extern _abi_test_clobber_v15_upper +.align 4 +_abi_test_clobber_v15_upper: + fmov v15.d[1], xzr + ret + +#endif // !OPENSSL_NO_ASM diff --git a/third_party/boringssl/kit/ios-aarch64/crypto/third_party/sike/asm/fp-armv8.S b/third_party/boringssl/kit/ios-aarch64/crypto/third_party/sike/asm/fp-armv8.S new file mode 100644 index 00000000..09dc51a6 --- /dev/null +++ b/third_party/boringssl/kit/ios-aarch64/crypto/third_party/sike/asm/fp-armv8.S @@ -0,0 +1,1193 @@ +// This file is generated from a similarly-named Perl script in the BoringSSL +// source tree. Do not edit by hand. + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) +#define OPENSSL_NO_ASM +#endif +#endif + +#if !defined(OPENSSL_NO_ASM) +#if defined(BORINGSSL_PREFIX) +#include +#endif +.section __TEXT,__const + +Lp503p1_nz_s8: +.quad 0x085BDA2211E7A0AC, 0x9BF6C87B7E7DAF13 +.quad 0x45C6BDDA77A4D01B, 0x4066F541811E1E60 + +Lp503x2: +.quad 0xFFFFFFFFFFFFFFFE, 0xFFFFFFFFFFFFFFFF +.quad 0x57FFFFFFFFFFFFFF, 0x2610B7B44423CF41 +.quad 0x3737ED90F6FCFB5E, 0xC08B8D7BB4EF49A0 +.quad 0x0080CDEA83023C3C + +.text +.globl _sike_mpmul +.private_extern _sike_mpmul +.align 4 +_sike_mpmul: + stp x29, x30, [sp,#-96]! + add x29, sp, #0 + stp x19, x20, [sp,#16] + stp x21, x22, [sp,#32] + stp x23, x24, [sp,#48] + stp x25, x26, [sp,#64] + stp x27, x28, [sp,#80] + + ldp x3, x4, [x0] + ldp x5, x6, [x0,#16] + ldp x7, x8, [x0,#32] + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + ldp x15, x16, [x1,#32] + ldp x17, x19, [x1,#48] + + // x3-x7 <- AH + AL, x7 <- carry + adds x3, x3, x7 + adcs x4, x4, x8 + adcs x5, x5, x9 + adcs x6, x6, x10 + adc x7, xzr, xzr + + // x11-x14 <- BH + BL, x8 <- carry + adds x11, x11, x15 + adcs x12, x12, x16 + adcs x13, x13, x17 + adcs x14, x14, x19 + adc x8, xzr, xzr + + // x9 <- combined carry + and x9, x7, x8 + // x7-x8 <- mask + sub x7, xzr, x7 + sub x8, xzr, x8 + + + // x15-x19 <- masked (BH + BL) + and x15, x11, x7 + and x16, x12, x7 + and x17, x13, x7 + and x19, x14, x7 + + // x20-x23 <- masked (AH + AL) + and x20, x3, x8 + and x21, x4, x8 + and x22, x5, x8 + and x23, x6, x8 + + // x15-x19, x7 <- masked (AH+AL) + masked (BH+BL), step 1 + adds x15, x15, x20 + adcs x16, x16, x21 + adcs x17, x17, x22 + adcs x19, x19, x23 + adc x7, x9, xzr + + // x8-x10,x20-x24 <- (AH+AL) x (BH+BL), low part + stp x3, x4, [x2,#0] + // A0-A1 <- AH + AL, T0 <- mask + adds x3, x3, x5 + adcs x4, x4, x6 + adc x25, xzr, xzr + + // C6, T1 <- BH + BL, C7 <- mask + adds x23, x11, x13 + adcs x26, x12, x14 + adc x24, xzr, xzr + + // C0-C1 <- masked (BH + BL) + sub x10, xzr, x25 + sub x20, xzr, x24 + and x8, x23, x10 + and x9, x26, x10 + + // C4-C5 <- masked (AH + AL), T0 <- combined carry + and x21, x3, x20 + and x22, x4, x20 + mul x10, x3, x23 + mul x20, x3, x26 + and x25, x25, x24 + + // C0-C1, T0 <- (AH+AL) x (BH+BL), part 1 + adds x8, x21, x8 + umulh x21, x3, x26 + adcs x9, x22, x9 + umulh x22, x3, x23 + adc x25, x25, xzr + + // C2-C5 <- (AH+AL) x (BH+BL), low part + mul x3, x4, x23 + umulh x23, x4, x23 + adds x20, x20, x22 + adc x21, x21, xzr + + mul x24, x4, x26 + umulh x26, x4, x26 + adds x20, x20, x3 + adcs x21, x21, x23 + adc x22, xzr, xzr + + adds x21, x21, x24 + adc x22, x22, x26 + + ldp x3, x4, [x2,#0] + + // C2-C5, T0 <- (AH+AL) x (BH+BL), final part + adds x21, x8, x21 + umulh x24, x3, x11 + umulh x26, x3, x12 + adcs x22, x9, x22 + mul x8, x3, x11 + mul x9, x3, x12 + adc x25, x25, xzr + + // C0-C1, T1, C7 <- AL x BL + mul x3, x4, x11 + umulh x11, x4, x11 + adds x9, x9, x24 + adc x26, x26, xzr + + mul x23, x4, x12 + umulh x12, x4, x12 + adds x9, x9, x3 + adcs x26, x26, x11 + adc x24, xzr, xzr + + adds x26, x26, x23 + adc x24, x24, x12 + + + // C2-C5, T0 <- (AH+AL) x (BH+BL) - ALxBL + mul x3, x5, x13 + umulh x11, x5, x13 + subs x10, x10, x8 + sbcs x20, x20, x9 + sbcs x21, x21, x26 + mul x4, x5, x14 + umulh x23, x5, x14 + sbcs x22, x22, x24 + sbc x25, x25, xzr + + // A0, A1, C6, B0 <- AH x BH + mul x5, x6, x13 + umulh x13, x6, x13 + adds x4, x4, x11 + adc x23, x23, xzr + + mul x12, x6, x14 + umulh x14, x6, x14 + adds x4, x4, x5 + adcs x23, x23, x13 + adc x11, xzr, xzr + + adds x23, x23, x12 + adc x11, x11, x14 + + + // C2-C5, T0 <- (AH+AL) x (BH+BL) - ALxBL - AHxBH + subs x10, x10, x3 + sbcs x20, x20, x4 + sbcs x21, x21, x23 + sbcs x22, x22, x11 + sbc x25, x25, xzr + + adds x10, x10, x26 + adcs x20, x20, x24 + adcs x21, x21, x3 + adcs x22, x22, x4 + adcs x23, x25, x23 + adc x24, x11, xzr + + + // x15-x19, x7 <- (AH+AL) x (BH+BL), final step + adds x15, x15, x21 + adcs x16, x16, x22 + adcs x17, x17, x23 + adcs x19, x19, x24 + adc x7, x7, xzr + + // Load AL + ldp x3, x4, [x0] + ldp x5, x6, [x0,#16] + // Load BL + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + + // Temporarily store x8,x9 in x2 + stp x8,x9, [x2,#0] + // x21-x28 <- AL x BL + // A0-A1 <- AH + AL, T0 <- mask + adds x3, x3, x5 + adcs x4, x4, x6 + adc x8, xzr, xzr + + // C6, T1 <- BH + BL, C7 <- mask + adds x27, x11, x13 + adcs x9, x12, x14 + adc x28, xzr, xzr + + // C0-C1 <- masked (BH + BL) + sub x23, xzr, x8 + sub x24, xzr, x28 + and x21, x27, x23 + and x22, x9, x23 + + // C4-C5 <- masked (AH + AL), T0 <- combined carry + and x25, x3, x24 + and x26, x4, x24 + mul x23, x3, x27 + mul x24, x3, x9 + and x8, x8, x28 + + // C0-C1, T0 <- (AH+AL) x (BH+BL), part 1 + adds x21, x25, x21 + umulh x25, x3, x9 + adcs x22, x26, x22 + umulh x26, x3, x27 + adc x8, x8, xzr + + // C2-C5 <- (AH+AL) x (BH+BL), low part + mul x3, x4, x27 + umulh x27, x4, x27 + adds x24, x24, x26 + adc x25, x25, xzr + + mul x28, x4, x9 + umulh x9, x4, x9 + adds x24, x24, x3 + adcs x25, x25, x27 + adc x26, xzr, xzr + + adds x25, x25, x28 + adc x26, x26, x9 + + ldp x3, x4, [x0,#0] + + // C2-C5, T0 <- (AH+AL) x (BH+BL), final part + adds x25, x21, x25 + umulh x28, x3, x11 + umulh x9, x3, x12 + adcs x26, x22, x26 + mul x21, x3, x11 + mul x22, x3, x12 + adc x8, x8, xzr + + // C0-C1, T1, C7 <- AL x BL + mul x3, x4, x11 + umulh x11, x4, x11 + adds x22, x22, x28 + adc x9, x9, xzr + + mul x27, x4, x12 + umulh x12, x4, x12 + adds x22, x22, x3 + adcs x9, x9, x11 + adc x28, xzr, xzr + + adds x9, x9, x27 + adc x28, x28, x12 + + + // C2-C5, T0 <- (AH+AL) x (BH+BL) - ALxBL + mul x3, x5, x13 + umulh x11, x5, x13 + subs x23, x23, x21 + sbcs x24, x24, x22 + sbcs x25, x25, x9 + mul x4, x5, x14 + umulh x27, x5, x14 + sbcs x26, x26, x28 + sbc x8, x8, xzr + + // A0, A1, C6, B0 <- AH x BH + mul x5, x6, x13 + umulh x13, x6, x13 + adds x4, x4, x11 + adc x27, x27, xzr + + mul x12, x6, x14 + umulh x14, x6, x14 + adds x4, x4, x5 + adcs x27, x27, x13 + adc x11, xzr, xzr + + adds x27, x27, x12 + adc x11, x11, x14 + + + // C2-C5, T0 <- (AH+AL) x (BH+BL) - ALxBL - AHxBH + subs x23, x23, x3 + sbcs x24, x24, x4 + sbcs x25, x25, x27 + sbcs x26, x26, x11 + sbc x8, x8, xzr + + adds x23, x23, x9 + adcs x24, x24, x28 + adcs x25, x25, x3 + adcs x26, x26, x4 + adcs x27, x8, x27 + adc x28, x11, xzr + + // Restore x8,x9 + ldp x8,x9, [x2,#0] + + // x8-x10,x20,x15-x17,x19 <- maskd (AH+AL) x (BH+BL) - ALxBL + subs x8, x8, x21 + sbcs x9, x9, x22 + sbcs x10, x10, x23 + sbcs x20, x20, x24 + sbcs x15, x15, x25 + sbcs x16, x16, x26 + sbcs x17, x17, x27 + sbcs x19, x19, x28 + sbc x7, x7, xzr + + // Store ALxBL, low + stp x21, x22, [x2] + stp x23, x24, [x2,#16] + + // Load AH + ldp x3, x4, [x0,#32] + ldp x5, x6, [x0,#48] + // Load BH + ldp x11, x12, [x1,#32] + ldp x13, x14, [x1,#48] + + adds x8, x8, x25 + adcs x9, x9, x26 + adcs x10, x10, x27 + adcs x20, x20, x28 + adc x1, xzr, xzr + + add x0, x0, #32 + // Temporarily store x8,x9 in x2 + stp x8,x9, [x2,#32] + // x21-x28 <- AH x BH + // A0-A1 <- AH + AL, T0 <- mask + adds x3, x3, x5 + adcs x4, x4, x6 + adc x8, xzr, xzr + + // C6, T1 <- BH + BL, C7 <- mask + adds x27, x11, x13 + adcs x9, x12, x14 + adc x28, xzr, xzr + + // C0-C1 <- masked (BH + BL) + sub x23, xzr, x8 + sub x24, xzr, x28 + and x21, x27, x23 + and x22, x9, x23 + + // C4-C5 <- masked (AH + AL), T0 <- combined carry + and x25, x3, x24 + and x26, x4, x24 + mul x23, x3, x27 + mul x24, x3, x9 + and x8, x8, x28 + + // C0-C1, T0 <- (AH+AL) x (BH+BL), part 1 + adds x21, x25, x21 + umulh x25, x3, x9 + adcs x22, x26, x22 + umulh x26, x3, x27 + adc x8, x8, xzr + + // C2-C5 <- (AH+AL) x (BH+BL), low part + mul x3, x4, x27 + umulh x27, x4, x27 + adds x24, x24, x26 + adc x25, x25, xzr + + mul x28, x4, x9 + umulh x9, x4, x9 + adds x24, x24, x3 + adcs x25, x25, x27 + adc x26, xzr, xzr + + adds x25, x25, x28 + adc x26, x26, x9 + + ldp x3, x4, [x0,#0] + + // C2-C5, T0 <- (AH+AL) x (BH+BL), final part + adds x25, x21, x25 + umulh x28, x3, x11 + umulh x9, x3, x12 + adcs x26, x22, x26 + mul x21, x3, x11 + mul x22, x3, x12 + adc x8, x8, xzr + + // C0-C1, T1, C7 <- AL x BL + mul x3, x4, x11 + umulh x11, x4, x11 + adds x22, x22, x28 + adc x9, x9, xzr + + mul x27, x4, x12 + umulh x12, x4, x12 + adds x22, x22, x3 + adcs x9, x9, x11 + adc x28, xzr, xzr + + adds x9, x9, x27 + adc x28, x28, x12 + + + // C2-C5, T0 <- (AH+AL) x (BH+BL) - ALxBL + mul x3, x5, x13 + umulh x11, x5, x13 + subs x23, x23, x21 + sbcs x24, x24, x22 + sbcs x25, x25, x9 + mul x4, x5, x14 + umulh x27, x5, x14 + sbcs x26, x26, x28 + sbc x8, x8, xzr + + // A0, A1, C6, B0 <- AH x BH + mul x5, x6, x13 + umulh x13, x6, x13 + adds x4, x4, x11 + adc x27, x27, xzr + + mul x12, x6, x14 + umulh x14, x6, x14 + adds x4, x4, x5 + adcs x27, x27, x13 + adc x11, xzr, xzr + + adds x27, x27, x12 + adc x11, x11, x14 + + + // C2-C5, T0 <- (AH+AL) x (BH+BL) - ALxBL - AHxBH + subs x23, x23, x3 + sbcs x24, x24, x4 + sbcs x25, x25, x27 + sbcs x26, x26, x11 + sbc x8, x8, xzr + + adds x23, x23, x9 + adcs x24, x24, x28 + adcs x25, x25, x3 + adcs x26, x26, x4 + adcs x27, x8, x27 + adc x28, x11, xzr + + // Restore x8,x9 + ldp x8,x9, [x2,#32] + + neg x1, x1 + + // x8-x10,x20,x15-x17,x19 <- (AH+AL) x (BH+BL) - ALxBL - AHxBH + subs x8, x8, x21 + sbcs x9, x9, x22 + sbcs x10, x10, x23 + sbcs x20, x20, x24 + sbcs x15, x15, x25 + sbcs x16, x16, x26 + sbcs x17, x17, x27 + sbcs x19, x19, x28 + sbc x7, x7, xzr + + // Store (AH+AL) x (BH+BL) - ALxBL - AHxBH, low + stp x8, x9, [x2,#32] + stp x10, x20, [x2,#48] + + adds x1, x1, #1 + adcs x15, x15, x21 + adcs x16, x16, x22 + adcs x17, x17, x23 + adcs x19, x19, x24 + adcs x25, x7, x25 + adcs x26, x26, xzr + adcs x27, x27, xzr + adc x28, x28, xzr + + stp x15, x16, [x2,#64] + stp x17, x19, [x2,#80] + stp x25, x26, [x2,#96] + stp x27, x28, [x2,#112] + + ldp x19, x20, [x29,#16] + ldp x21, x22, [x29,#32] + ldp x23, x24, [x29,#48] + ldp x25, x26, [x29,#64] + ldp x27, x28, [x29,#80] + ldp x29, x30, [sp],#96 + ret +.globl _sike_fprdc +.private_extern _sike_fprdc +.align 4 +_sike_fprdc: + stp x29, x30, [sp, #-112]! + add x29, sp, #0 + stp x19, x20, [sp,#16] + stp x21, x22, [sp,#32] + stp x23, x24, [sp,#48] + stp x25, x26, [sp,#64] + stp x27, x28, [sp,#80] + str x1, [sp,#96] + + ldp x2, x3, [x0,#0] // a[0-1] + + // Load the prime constant + adrp x23, Lp503p1_nz_s8@PAGE + add x23, x23, Lp503p1_nz_s8@PAGEOFF + ldp x24, x25, [x23, #0] + ldp x26, x27, [x23, #16] + + // a[0-1] x .Lp503p1_nz_s8 --> result: x4:x9 + mul x4, x2, x24 // a[0] x Lp503p1_nz_s8[0] + umulh x7, x2, x24 + mul x5, x2, x25 // a[0] x Lp503p1_nz_s8[1] + umulh x6, x2, x25 + + mul x1, x3, x24 + umulh x10, x3, x24 + adds x5, x5, x7 + adc x6, x6, xzr + + mul x11, x2, x26 + umulh x19, x2, x26 + adds x5, x5, x1 + adcs x6, x6, x10 + adc x7, xzr, xzr + + mul x1, x3, x25 + umulh x10, x3, x25 + adds x6, x6, x11 + adcs x7, x7, x19 + adc x8, xzr, xzr + + mul x11, x2, x27 + umulh x19, x2, x27 + adds x6, x6, x1 + adcs x7, x7, x10 + adc x8, x8, xzr + + mul x1, x3, x26 + umulh x10, x3, x26 + adds x7, x7, x11 + adcs x8, x8, x19 + adc x9, xzr, xzr + + mul x11, x3, x27 + umulh x19, x3, x27 + adds x7, x7, x1 + adcs x8, x8, x10 + adc x9, x9, xzr + adds x8, x8, x11 + adc x9, x9, x19 + + + + ldp x2, x3, [x0,#16] // a[2] + ldp x12, x13, [x0,#32] + ldp x14, x15, [x0,#48] + + orr x10, xzr, x9, lsr #8 + lsl x9, x9, #56 + orr x9, x9, x8, lsr #8 + lsl x8, x8, #56 + orr x8, x8, x7, lsr #8 + lsl x7, x7, #56 + orr x7, x7, x6, lsr #8 + lsl x6, x6, #56 + orr x6, x6, x5, lsr #8 + lsl x5, x5, #56 + orr x5, x5, x4, lsr #8 + lsl x4, x4, #56 + + adds x3, x4, x3 // a[3] + adcs x12, x5, x12 // a[4] + adcs x13, x6, x13 + adcs x14, x7, x14 + adcs x15, x8, x15 + ldp x16, x17, [x0,#64] + ldp x28, x30, [x0,#80] + mul x4, x2, x24 // a[2] x Lp503p1_nz_s8[0] + umulh x7, x2, x24 + adcs x16, x9, x16 + adcs x17, x10, x17 + adcs x28, xzr, x28 + adcs x30, xzr, x30 + ldp x20, x21, [x0,#96] + ldp x22, x23, [x0,#112] + mul x5, x2, x25 // a[2] x Lp503p1_nz_s8[1] + umulh x6, x2, x25 + adcs x20, xzr, x20 + adcs x21, xzr, x21 + adcs x22, xzr, x22 + adc x23, xzr, x23 + + // a[2-3] x .Lp503p1_nz_s8 --> result: x4:x9 + mul x1, x3, x24 + umulh x10, x3, x24 + adds x5, x5, x7 + adc x6, x6, xzr + + mul x11, x2, x26 + umulh x19, x2, x26 + adds x5, x5, x1 + adcs x6, x6, x10 + adc x7, xzr, xzr + + mul x1, x3, x25 + umulh x10, x3, x25 + adds x6, x6, x11 + adcs x7, x7, x19 + adc x8, xzr, xzr + + mul x11, x2, x27 + umulh x19, x2, x27 + adds x6, x6, x1 + adcs x7, x7, x10 + adc x8, x8, xzr + + mul x1, x3, x26 + umulh x10, x3, x26 + adds x7, x7, x11 + adcs x8, x8, x19 + adc x9, xzr, xzr + + mul x11, x3, x27 + umulh x19, x3, x27 + adds x7, x7, x1 + adcs x8, x8, x10 + adc x9, x9, xzr + adds x8, x8, x11 + adc x9, x9, x19 + + + + orr x10, xzr, x9, lsr #8 + lsl x9, x9, #56 + orr x9, x9, x8, lsr #8 + lsl x8, x8, #56 + orr x8, x8, x7, lsr #8 + lsl x7, x7, #56 + orr x7, x7, x6, lsr #8 + lsl x6, x6, #56 + orr x6, x6, x5, lsr #8 + lsl x5, x5, #56 + orr x5, x5, x4, lsr #8 + lsl x4, x4, #56 + + adds x13, x4, x13 // a[5] + adcs x14, x5, x14 // a[6] + adcs x15, x6, x15 + adcs x16, x7, x16 + mul x4, x12, x24 // a[4] x Lp503p1_nz_s8[0] + umulh x7, x12, x24 + adcs x17, x8, x17 + adcs x28, x9, x28 + adcs x30, x10, x30 + adcs x20, xzr, x20 + mul x5, x12, x25 // a[4] x Lp503p1_nz_s8[1] + umulh x6, x12, x25 + adcs x21, xzr, x21 + adcs x22, xzr, x22 + adc x23, xzr, x23 + + // a[4-5] x .Lp503p1_nz_s8 --> result: x4:x9 + mul x1, x13, x24 + umulh x10, x13, x24 + adds x5, x5, x7 + adc x6, x6, xzr + + mul x11, x12, x26 + umulh x19, x12, x26 + adds x5, x5, x1 + adcs x6, x6, x10 + adc x7, xzr, xzr + + mul x1, x13, x25 + umulh x10, x13, x25 + adds x6, x6, x11 + adcs x7, x7, x19 + adc x8, xzr, xzr + + mul x11, x12, x27 + umulh x19, x12, x27 + adds x6, x6, x1 + adcs x7, x7, x10 + adc x8, x8, xzr + + mul x1, x13, x26 + umulh x10, x13, x26 + adds x7, x7, x11 + adcs x8, x8, x19 + adc x9, xzr, xzr + + mul x11, x13, x27 + umulh x19, x13, x27 + adds x7, x7, x1 + adcs x8, x8, x10 + adc x9, x9, xzr + adds x8, x8, x11 + adc x9, x9, x19 + + + + orr x10, xzr, x9, lsr #8 + lsl x9, x9, #56 + orr x9, x9, x8, lsr #8 + lsl x8, x8, #56 + orr x8, x8, x7, lsr #8 + lsl x7, x7, #56 + orr x7, x7, x6, lsr #8 + lsl x6, x6, #56 + orr x6, x6, x5, lsr #8 + lsl x5, x5, #56 + orr x5, x5, x4, lsr #8 + lsl x4, x4, #56 + + adds x15, x4, x15 // a[7] + adcs x16, x5, x16 // a[8] + adcs x17, x6, x17 + adcs x28, x7, x28 + mul x4, x14, x24 // a[6] x Lp503p1_nz_s8[0] + umulh x7, x14, x24 + adcs x30, x8, x30 + adcs x20, x9, x20 + adcs x21, x10, x21 + mul x5, x14, x25 // a[6] x Lp503p1_nz_s8[1] + umulh x6, x14, x25 + adcs x22, xzr, x22 + adc x23, xzr, x23 + + // a[6-7] x .Lp503p1_nz_s8 --> result: x4:x9 + mul x1, x15, x24 + umulh x10, x15, x24 + adds x5, x5, x7 + adc x6, x6, xzr + + mul x11, x14, x26 + umulh x19, x14, x26 + adds x5, x5, x1 + adcs x6, x6, x10 + adc x7, xzr, xzr + + mul x1, x15, x25 + umulh x10, x15, x25 + adds x6, x6, x11 + adcs x7, x7, x19 + adc x8, xzr, xzr + + mul x11, x14, x27 + umulh x19, x14, x27 + adds x6, x6, x1 + adcs x7, x7, x10 + adc x8, x8, xzr + + mul x1, x15, x26 + umulh x10, x15, x26 + adds x7, x7, x11 + adcs x8, x8, x19 + adc x9, xzr, xzr + + mul x11, x15, x27 + umulh x19, x15, x27 + adds x7, x7, x1 + adcs x8, x8, x10 + adc x9, x9, xzr + adds x8, x8, x11 + adc x9, x9, x19 + + + + orr x10, xzr, x9, lsr #8 + lsl x9, x9, #56 + orr x9, x9, x8, lsr #8 + lsl x8, x8, #56 + orr x8, x8, x7, lsr #8 + lsl x7, x7, #56 + orr x7, x7, x6, lsr #8 + lsl x6, x6, #56 + orr x6, x6, x5, lsr #8 + lsl x5, x5, #56 + orr x5, x5, x4, lsr #8 + lsl x4, x4, #56 + + adds x17, x4, x17 + adcs x28, x5, x28 + ldr x1, [sp,#96] + adcs x30, x6, x30 + adcs x20, x7, x20 + stp x16, x17, [x1,#0] // Final result + stp x28, x30, [x1,#16] + adcs x21, x8, x21 + adcs x22, x9, x22 + adc x23, x10, x23 + stp x20, x21, [x1,#32] + stp x22, x23, [x1,#48] + + ldp x19, x20, [x29,#16] + ldp x21, x22, [x29,#32] + ldp x23, x24, [x29,#48] + ldp x25, x26, [x29,#64] + ldp x27, x28, [x29,#80] + ldp x29, x30, [sp],#112 + ret + +.globl _sike_fpadd +.private_extern _sike_fpadd +.align 4 +_sike_fpadd: + stp x29,x30, [sp,#-16]! + add x29, sp, #0 + + ldp x3, x4, [x0,#0] + ldp x5, x6, [x0,#16] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + + // Add a + b + adds x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x13 + adcs x6, x6, x14 + ldp x7, x8, [x0,#32] + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#32] + ldp x13, x14, [x1,#48] + adcs x7, x7, x11 + adcs x8, x8, x12 + adcs x9, x9, x13 + adc x10, x10, x14 + + // Subtract 2xp503 + adrp x17, Lp503x2@PAGE + add x17, x17, Lp503x2@PAGEOFF + ldp x11, x12, [x17, #0] + ldp x13, x14, [x17, #16] + subs x3, x3, x11 + sbcs x4, x4, x12 + sbcs x5, x5, x12 + sbcs x6, x6, x13 + sbcs x7, x7, x14 + + ldp x15, x16, [x17, #32] + ldr x17, [x17, #48] + sbcs x8, x8, x15 + sbcs x9, x9, x16 + sbcs x10, x10, x17 + sbc x0, xzr, xzr // x0 can be reused now + + // Add 2xp503 anded with the mask in x0 + and x11, x11, x0 + and x12, x12, x0 + and x13, x13, x0 + and x14, x14, x0 + and x15, x15, x0 + and x16, x16, x0 + and x17, x17, x0 + + adds x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x12 + adcs x6, x6, x13 + adcs x7, x7, x14 + adcs x8, x8, x15 + adcs x9, x9, x16 + adc x10, x10, x17 + + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + + ldp x29, x30, [sp],#16 + ret + +.globl _sike_fpsub +.private_extern _sike_fpsub +.align 4 +_sike_fpsub: + stp x29, x30, [sp,#-16]! + add x29, sp, #0 + + ldp x3, x4, [x0,#0] + ldp x5, x6, [x0,#16] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + + // Subtract a - b + subs x3, x3, x11 + sbcs x4, x4, x12 + sbcs x5, x5, x13 + sbcs x6, x6, x14 + ldp x7, x8, [x0,#32] + ldp x11, x12, [x1,#32] + sbcs x7, x7, x11 + sbcs x8, x8, x12 + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#48] + sbcs x9, x9, x11 + sbcs x10, x10, x12 + sbc x17, xzr, xzr + + // Add 2xp503 anded with the mask in x17 + adrp x16, Lp503x2@PAGE + add x16, x16, Lp503x2@PAGEOFF + + // First half + ldp x11, x12, [x16, #0] + ldp x13, x14, [x16, #16] + and x11, x11, x17 + and x12, x12, x17 + and x13, x13, x17 + adds x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x12 + adcs x6, x6, x13 + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + + // Second half + ldp x11, x12, [x16, #32] + ldr x13, [x16, #48] + and x14, x14, x17 + and x11, x11, x17 + and x12, x12, x17 + and x13, x13, x17 + adcs x7, x7, x14 + adcs x8, x8, x11 + adcs x9, x9, x12 + adc x10, x10, x13 + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + + ldp x29, x30, [sp],#16 + ret +.globl _sike_mpadd_asm +.private_extern _sike_mpadd_asm +.align 4 +_sike_mpadd_asm: + stp x29, x30, [sp,#-16]! + add x29, sp, #0 + + ldp x3, x4, [x0,#0] + ldp x5, x6, [x0,#16] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + + adds x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x13 + adcs x6, x6, x14 + ldp x7, x8, [x0,#32] + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#32] + ldp x13, x14, [x1,#48] + adcs x7, x7, x11 + adcs x8, x8, x12 + adcs x9, x9, x13 + adc x10, x10, x14 + + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + + ldp x29, x30, [sp],#16 + ret +.globl _sike_mpadd503x2_asm +.private_extern _sike_mpadd503x2_asm +.align 4 +_sike_mpadd503x2_asm: + stp x29, x30, [sp,#-16]! + add x29, sp, #0 + + ldp x3, x4, [x0,#0] + ldp x5, x6, [x0,#16] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + adds x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x13 + adcs x6, x6, x14 + ldp x7, x8, [x0,#32] + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#32] + ldp x13, x14, [x1,#48] + adcs x7, x7, x11 + adcs x8, x8, x12 + adcs x9, x9, x13 + adcs x10, x10, x14 + + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + + ldp x3, x4, [x0,#64] + ldp x5, x6, [x0,#80] + ldp x11, x12, [x1,#64] + ldp x13, x14, [x1,#80] + adcs x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x13 + adcs x6, x6, x14 + ldp x7, x8, [x0,#96] + ldp x9, x10, [x0,#112] + ldp x11, x12, [x1,#96] + ldp x13, x14, [x1,#112] + adcs x7, x7, x11 + adcs x8, x8, x12 + adcs x9, x9, x13 + adc x10, x10, x14 + + stp x3, x4, [x2,#64] + stp x5, x6, [x2,#80] + stp x7, x8, [x2,#96] + stp x9, x10, [x2,#112] + + ldp x29, x30, [sp],#16 + ret +.globl _sike_mpsubx2_asm +.private_extern _sike_mpsubx2_asm +.align 4 +_sike_mpsubx2_asm: + stp x29, x30, [sp,#-16]! + add x29, sp, #0 + + ldp x3, x4, [x0,#0] + ldp x5, x6, [x0,#16] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + subs x3, x3, x11 + sbcs x4, x4, x12 + sbcs x5, x5, x13 + sbcs x6, x6, x14 + ldp x7, x8, [x0,#32] + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#32] + ldp x13, x14, [x1,#48] + sbcs x7, x7, x11 + sbcs x8, x8, x12 + sbcs x9, x9, x13 + sbcs x10, x10, x14 + + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + + ldp x3, x4, [x0,#64] + ldp x5, x6, [x0,#80] + ldp x11, x12, [x1,#64] + ldp x13, x14, [x1,#80] + sbcs x3, x3, x11 + sbcs x4, x4, x12 + sbcs x5, x5, x13 + sbcs x6, x6, x14 + ldp x7, x8, [x0,#96] + ldp x9, x10, [x0,#112] + ldp x11, x12, [x1,#96] + ldp x13, x14, [x1,#112] + sbcs x7, x7, x11 + sbcs x8, x8, x12 + sbcs x9, x9, x13 + sbcs x10, x10, x14 + sbc x0, xzr, xzr + + stp x3, x4, [x2,#64] + stp x5, x6, [x2,#80] + stp x7, x8, [x2,#96] + stp x9, x10, [x2,#112] + + ldp x29, x30, [sp],#16 + ret +.globl _sike_mpdblsubx2_asm +.private_extern _sike_mpdblsubx2_asm +.align 4 +_sike_mpdblsubx2_asm: + stp x29, x30, [sp, #-64]! + add x29, sp, #0 + + stp x20, x21, [sp, #16] + stp x22, x23, [sp, #32] + str x24, [sp, #48] + + ldp x3, x4, [x2,#0] + ldp x5, x6, [x2,#16] + ldp x7, x8, [x2,#32] + ldp x9, x10, [x2,#48] + ldp x11, x12, [x2,#64] + ldp x13, x14, [x2,#80] + ldp x15, x16, [x2,#96] + ldp x17, x24, [x2,#112] + + ldp x20, x21, [x0,#0] + ldp x22, x23, [x0,#16] + subs x3, x3, x20 + sbcs x4, x4, x21 + sbcs x5, x5, x22 + sbcs x6, x6, x23 + ldp x20, x21, [x0,#32] + ldp x22, x23, [x0,#48] + sbcs x7, x7, x20 + sbcs x8, x8, x21 + sbcs x9, x9, x22 + sbcs x10, x10, x23 + ldp x20, x21, [x0,#64] + ldp x22, x23, [x0,#80] + sbcs x11, x11, x20 + sbcs x12, x12, x21 + sbcs x13, x13, x22 + sbcs x14, x14, x23 + ldp x20, x21, [x0,#96] + ldp x22, x23, [x0,#112] + sbcs x15, x15, x20 + sbcs x16, x16, x21 + sbcs x17, x17, x22 + sbc x24, x24, x23 + + ldp x20, x21, [x1,#0] + ldp x22, x23, [x1,#16] + subs x3, x3, x20 + sbcs x4, x4, x21 + sbcs x5, x5, x22 + sbcs x6, x6, x23 + ldp x20, x21, [x1,#32] + ldp x22, x23, [x1,#48] + sbcs x7, x7, x20 + sbcs x8, x8, x21 + sbcs x9, x9, x22 + sbcs x10, x10, x23 + ldp x20, x21, [x1,#64] + ldp x22, x23, [x1,#80] + sbcs x11, x11, x20 + sbcs x12, x12, x21 + sbcs x13, x13, x22 + sbcs x14, x14, x23 + ldp x20, x21, [x1,#96] + ldp x22, x23, [x1,#112] + sbcs x15, x15, x20 + sbcs x16, x16, x21 + sbcs x17, x17, x22 + sbc x24, x24, x23 + + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + stp x11, x12, [x2,#64] + stp x13, x14, [x2,#80] + stp x15, x16, [x2,#96] + stp x17, x24, [x2,#112] + + ldp x20, x21, [x29,#16] + ldp x22, x23, [x29,#32] + ldr x24, [x29,#48] + + ldp x29, x30, [sp],#64 + ret +#endif // !OPENSSL_NO_ASM diff --git a/third_party/boringssl/kit/ios-arm/crypto/fipsmodule/bsaes-armv7.S b/third_party/boringssl/kit/ios-arm/crypto/fipsmodule/bsaes-armv7.S index d997c6cb..dffc0c24 100644 --- a/third_party/boringssl/kit/ios-arm/crypto/fipsmodule/bsaes-armv7.S +++ b/third_party/boringssl/kit/ios-arm/crypto/fipsmodule/bsaes-armv7.S @@ -1086,9 +1086,6 @@ Lkey_loop: @ don't save last round key bx lr - - - .globl _bsaes_cbc_encrypt .private_extern _bsaes_cbc_encrypt #ifdef __thumb2__ @@ -1096,16 +1093,8 @@ Lkey_loop: #endif .align 5 _bsaes_cbc_encrypt: -#ifndef __KERNEL__ - cmp r2, #128 -#ifndef __thumb__ - blo _AES_cbc_encrypt -#else - bhs 1f - b _AES_cbc_encrypt -1: -#endif -#endif + @ In OpenSSL, this function had a fallback to aes_nohw_cbc_encrypt for + @ short inputs. We patch this out, using bsaes for all input sizes. @ it is up to the caller to make sure we are called with enc == 0 @@ -1203,10 +1192,7 @@ Lcbc_dec_loop_finish: adds r2, r2, #8 beq Lcbc_dec_done - vld1.8 {q0}, [r0]! @ load input - cmp r2, #2 - blo Lcbc_dec_one - vld1.8 {q1}, [r0]! + @ Set up most parameters for the _bsaes_decrypt8 call. #ifndef BSAES_ASM_EXTENDED_KEY mov r4, sp @ pass the key #else @@ -1214,6 +1200,11 @@ Lcbc_dec_loop_finish: #endif mov r5, r10 vstmia r9, {q15} @ put aside IV + + vld1.8 {q0}, [r0]! @ load input + cmp r2, #2 + blo Lcbc_dec_one + vld1.8 {q1}, [r0]! beq Lcbc_dec_two vld1.8 {q2}, [r0]! cmp r2, #4 @@ -1331,16 +1322,11 @@ Lcbc_dec_two: .align 4 Lcbc_dec_one: sub r0, r0, #0x10 - mov r10, r1 @ save original out pointer - mov r1, r9 @ use the iv scratch space as out buffer - mov r2, r3 - vmov q4,q15 @ just in case ensure that IV - vmov q5,q0 @ and input are preserved - bl _AES_decrypt - vld1.8 {q0}, [r9] @ load result - veor q0, q0, q4 @ ^= IV - vmov q15, q5 @ q5 holds input - vst1.8 {q0}, [r10] @ write output + bl _bsaes_decrypt8 + vldmia r9, {q14} @ reload IV + vld1.8 {q15}, [r0]! @ reload input + veor q0, q0, q14 @ ^= IV + vst1.8 {q0}, [r1]! @ write output Lcbc_dec_done: #ifndef BSAES_ASM_EXTENDED_KEY @@ -1358,7 +1344,6 @@ Lcbc_dec_bzero:@ wipe key schedule [if any] VFP_ABI_POP ldmia sp!, {r4,r5,r6,r7,r8,r9,r10, pc} - .globl _bsaes_ctr32_encrypt_blocks .private_extern _bsaes_ctr32_encrypt_blocks #ifdef __thumb2__ @@ -1366,9 +1351,8 @@ Lcbc_dec_bzero:@ wipe key schedule [if any] #endif .align 5 _bsaes_ctr32_encrypt_blocks: - cmp r2, #8 @ use plain AES for - blo Lctr_enc_short @ small sizes - + @ In OpenSSL, short inputs fall back to aes_nohw_* here. We patch this + @ out to retain a constant-time implementation. mov ip, sp stmdb sp!, {r4,r5,r6,r7,r8,r9,r10, lr} VFP_ABI_PUSH @@ -1544,1046 +1528,8 @@ Lctr_enc_bzero:@ wipe key schedule [if any] VFP_ABI_POP ldmia sp!, {r4,r5,r6,r7,r8,r9,r10, pc} @ return -.align 4 -Lctr_enc_short: - ldr ip, [sp] @ ctr pointer is passed on stack - stmdb sp!, {r4,r5,r6,r7,r8, lr} - - mov r4, r0 @ copy arguments - mov r5, r1 - mov r6, r2 - mov r7, r3 - ldr r8, [ip, #12] @ load counter LSW - vld1.8 {q1}, [ip] @ load whole counter value -#ifdef __ARMEL__ - rev r8, r8 -#endif - sub sp, sp, #0x10 - vst1.8 {q1}, [sp] @ copy counter value - sub sp, sp, #0x10 - -Lctr_enc_short_loop: - add r0, sp, #0x10 @ input counter value - mov r1, sp @ output on the stack - mov r2, r7 @ key - - bl _AES_encrypt - - vld1.8 {q0}, [r4]! @ load input - vld1.8 {q1}, [sp] @ load encrypted counter - add r8, r8, #1 -#ifdef __ARMEL__ - rev r0, r8 - str r0, [sp, #0x1c] @ next counter value -#else - str r8, [sp, #0x1c] @ next counter value -#endif - veor q0,q0,q1 - vst1.8 {q0}, [r5]! @ store output - subs r6, r6, #1 - bne Lctr_enc_short_loop - - vmov.i32 q0, #0 - vmov.i32 q1, #0 - vstmia sp!, {q0,q1} - - ldmia sp!, {r4,r5,r6,r7,r8, pc} - -.globl _bsaes_xts_encrypt -.private_extern _bsaes_xts_encrypt -#ifdef __thumb2__ -.thumb_func _bsaes_xts_encrypt -#endif -.align 4 -_bsaes_xts_encrypt: - mov ip, sp - stmdb sp!, {r4,r5,r6,r7,r8,r9,r10, lr} @ 0x20 - VFP_ABI_PUSH - mov r6, sp @ future r3 - - mov r7, r0 - mov r8, r1 - mov r9, r2 - mov r10, r3 - - sub r0, sp, #0x10 @ 0x10 - bic r0, #0xf @ align at 16 bytes - mov sp, r0 - -#ifdef XTS_CHAIN_TWEAK - ldr r0, [ip] @ pointer to input tweak -#else - @ generate initial tweak - ldr r0, [ip, #4] @ iv[] - mov r1, sp - ldr r2, [ip, #0] @ key2 - bl _AES_encrypt - mov r0,sp @ pointer to initial tweak -#endif - - ldr r1, [r10, #240] @ get # of rounds - mov r3, r6 -#ifndef BSAES_ASM_EXTENDED_KEY - @ allocate the key schedule on the stack - sub r12, sp, r1, lsl#7 @ 128 bytes per inner round key - @ add r12, #96 @ size of bit-sliced key schedule - sub r12, #48 @ place for tweak[9] - - @ populate the key schedule - mov r4, r10 @ pass key - mov r5, r1 @ pass # of rounds - mov sp, r12 - add r12, #0x90 @ pass key schedule - bl _bsaes_key_convert - veor q7, q7, q15 @ fix up last round key - vstmia r12, {q7} @ save last round key -#else - ldr r12, [r10, #244] - eors r12, #1 - beq 0f - - str r12, [r10, #244] - mov r4, r10 @ pass key - mov r5, r1 @ pass # of rounds - add r12, r10, #248 @ pass key schedule - bl _bsaes_key_convert - veor q7, q7, q15 @ fix up last round key - vstmia r12, {q7} - -.align 2 - sub sp, #0x90 @ place for tweak[9] -#endif - - vld1.8 {q8}, [r0] @ initial tweak - adr r2, Lxts_magic - - subs r9, #0x80 - blo Lxts_enc_short - b Lxts_enc_loop - -.align 4 -Lxts_enc_loop: - vldmia r2, {q5} @ load XTS magic - vshr.s64 q6, q8, #63 - mov r0, sp - vand q6, q6, q5 - vadd.u64 q9, q8, q8 - vst1.64 {q8}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q9, #63 - veor q9, q9, q6 - vand q7, q7, q5 - vadd.u64 q10, q9, q9 - vst1.64 {q9}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q10, #63 - veor q10, q10, q7 - vand q6, q6, q5 - vld1.8 {q0}, [r7]! - vadd.u64 q11, q10, q10 - vst1.64 {q10}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q11, #63 - veor q11, q11, q6 - vand q7, q7, q5 - vld1.8 {q1}, [r7]! - veor q0, q0, q8 - vadd.u64 q12, q11, q11 - vst1.64 {q11}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q12, #63 - veor q12, q12, q7 - vand q6, q6, q5 - vld1.8 {q2}, [r7]! - veor q1, q1, q9 - vadd.u64 q13, q12, q12 - vst1.64 {q12}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q13, #63 - veor q13, q13, q6 - vand q7, q7, q5 - vld1.8 {q3}, [r7]! - veor q2, q2, q10 - vadd.u64 q14, q13, q13 - vst1.64 {q13}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q14, #63 - veor q14, q14, q7 - vand q6, q6, q5 - vld1.8 {q4}, [r7]! - veor q3, q3, q11 - vadd.u64 q15, q14, q14 - vst1.64 {q14}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q15, #63 - veor q15, q15, q6 - vand q7, q7, q5 - vld1.8 {q5}, [r7]! - veor q4, q4, q12 - vadd.u64 q8, q15, q15 - vst1.64 {q15}, [r0,:128]! - vswp d15,d14 - veor q8, q8, q7 - vst1.64 {q8}, [r0,:128] @ next round tweak - - vld1.8 {q6,q7}, [r7]! - veor q5, q5, q13 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q6, q6, q14 - mov r5, r1 @ pass rounds - veor q7, q7, q15 - mov r0, sp - - bl _bsaes_encrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - vld1.64 {q12,q13}, [r0,:128]! - veor q1, q1, q9 - veor q8, q4, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q6, q11 - vld1.64 {q14,q15}, [r0,:128]! - veor q10, q3, q12 - vst1.8 {q8,q9}, [r8]! - veor q11, q7, q13 - veor q12, q2, q14 - vst1.8 {q10,q11}, [r8]! - veor q13, q5, q15 - vst1.8 {q12,q13}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - - subs r9, #0x80 - bpl Lxts_enc_loop - -Lxts_enc_short: - adds r9, #0x70 - bmi Lxts_enc_done - - vldmia r2, {q5} @ load XTS magic - vshr.s64 q7, q8, #63 - mov r0, sp - vand q7, q7, q5 - vadd.u64 q9, q8, q8 - vst1.64 {q8}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q9, #63 - veor q9, q9, q7 - vand q6, q6, q5 - vadd.u64 q10, q9, q9 - vst1.64 {q9}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q10, #63 - veor q10, q10, q6 - vand q7, q7, q5 - vld1.8 {q0}, [r7]! - subs r9, #0x10 - bmi Lxts_enc_1 - vadd.u64 q11, q10, q10 - vst1.64 {q10}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q11, #63 - veor q11, q11, q7 - vand q6, q6, q5 - vld1.8 {q1}, [r7]! - subs r9, #0x10 - bmi Lxts_enc_2 - veor q0, q0, q8 - vadd.u64 q12, q11, q11 - vst1.64 {q11}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q12, #63 - veor q12, q12, q6 - vand q7, q7, q5 - vld1.8 {q2}, [r7]! - subs r9, #0x10 - bmi Lxts_enc_3 - veor q1, q1, q9 - vadd.u64 q13, q12, q12 - vst1.64 {q12}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q13, #63 - veor q13, q13, q7 - vand q6, q6, q5 - vld1.8 {q3}, [r7]! - subs r9, #0x10 - bmi Lxts_enc_4 - veor q2, q2, q10 - vadd.u64 q14, q13, q13 - vst1.64 {q13}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q14, #63 - veor q14, q14, q6 - vand q7, q7, q5 - vld1.8 {q4}, [r7]! - subs r9, #0x10 - bmi Lxts_enc_5 - veor q3, q3, q11 - vadd.u64 q15, q14, q14 - vst1.64 {q14}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q15, #63 - veor q15, q15, q7 - vand q6, q6, q5 - vld1.8 {q5}, [r7]! - subs r9, #0x10 - bmi Lxts_enc_6 - veor q4, q4, q12 - sub r9, #0x10 - vst1.64 {q15}, [r0,:128] @ next round tweak - - vld1.8 {q6}, [r7]! - veor q5, q5, q13 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q6, q6, q14 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_encrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - vld1.64 {q12,q13}, [r0,:128]! - veor q1, q1, q9 - veor q8, q4, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q6, q11 - vld1.64 {q14}, [r0,:128]! - veor q10, q3, q12 - vst1.8 {q8,q9}, [r8]! - veor q11, q7, q13 - veor q12, q2, q14 - vst1.8 {q10,q11}, [r8]! - vst1.8 {q12}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b Lxts_enc_done -.align 4 -Lxts_enc_6: - veor q4, q4, q12 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q5, q5, q13 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_encrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - vld1.64 {q12,q13}, [r0,:128]! - veor q1, q1, q9 - veor q8, q4, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q6, q11 - veor q10, q3, q12 - vst1.8 {q8,q9}, [r8]! - veor q11, q7, q13 - vst1.8 {q10,q11}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b Lxts_enc_done - -@ put this in range for both ARM and Thumb mode adr instructions -.align 5 -Lxts_magic: -.quad 1, 0x87 - -.align 5 -Lxts_enc_5: - veor q3, q3, q11 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q4, q4, q12 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_encrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - vld1.64 {q12}, [r0,:128]! - veor q1, q1, q9 - veor q8, q4, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q6, q11 - veor q10, q3, q12 - vst1.8 {q8,q9}, [r8]! - vst1.8 {q10}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b Lxts_enc_done -.align 4 -Lxts_enc_4: - veor q2, q2, q10 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q3, q3, q11 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_encrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - veor q1, q1, q9 - veor q8, q4, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q6, q11 - vst1.8 {q8,q9}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b Lxts_enc_done -.align 4 -Lxts_enc_3: - veor q1, q1, q9 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q2, q2, q10 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_encrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10}, [r0,:128]! - veor q0, q0, q8 - veor q1, q1, q9 - veor q8, q4, q10 - vst1.8 {q0,q1}, [r8]! - vst1.8 {q8}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b Lxts_enc_done -.align 4 -Lxts_enc_2: - veor q0, q0, q8 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q1, q1, q9 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_encrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - veor q0, q0, q8 - veor q1, q1, q9 - vst1.8 {q0,q1}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b Lxts_enc_done -.align 4 -Lxts_enc_1: - mov r0, sp - veor q0, q0, q8 - mov r1, sp - vst1.8 {q0}, [sp,:128] - mov r2, r10 - mov r4, r3 @ preserve fp - - bl _AES_encrypt - - vld1.8 {q0}, [sp,:128] - veor q0, q0, q8 - vst1.8 {q0}, [r8]! - mov r3, r4 - - vmov q8, q9 @ next round tweak - -Lxts_enc_done: -#ifndef XTS_CHAIN_TWEAK - adds r9, #0x10 - beq Lxts_enc_ret - sub r6, r8, #0x10 - -Lxts_enc_steal: - ldrb r0, [r7], #1 - ldrb r1, [r8, #-0x10] - strb r0, [r8, #-0x10] - strb r1, [r8], #1 - - subs r9, #1 - bhi Lxts_enc_steal - - vld1.8 {q0}, [r6] - mov r0, sp - veor q0, q0, q8 - mov r1, sp - vst1.8 {q0}, [sp,:128] - mov r2, r10 - mov r4, r3 @ preserve fp - - bl _AES_encrypt - - vld1.8 {q0}, [sp,:128] - veor q0, q0, q8 - vst1.8 {q0}, [r6] - mov r3, r4 -#endif - -Lxts_enc_ret: - bic r0, r3, #0xf - vmov.i32 q0, #0 - vmov.i32 q1, #0 -#ifdef XTS_CHAIN_TWEAK - ldr r1, [r3, #0x20+VFP_ABI_FRAME] @ chain tweak -#endif -Lxts_enc_bzero:@ wipe key schedule [if any] - vstmia sp!, {q0,q1} - cmp sp, r0 - bne Lxts_enc_bzero - - mov sp, r3 -#ifdef XTS_CHAIN_TWEAK - vst1.8 {q8}, [r1] -#endif - VFP_ABI_POP - ldmia sp!, {r4,r5,r6,r7,r8,r9,r10, pc} @ return - - - -.globl _bsaes_xts_decrypt -.private_extern _bsaes_xts_decrypt -#ifdef __thumb2__ -.thumb_func _bsaes_xts_decrypt -#endif -.align 4 -_bsaes_xts_decrypt: - mov ip, sp - stmdb sp!, {r4,r5,r6,r7,r8,r9,r10, lr} @ 0x20 - VFP_ABI_PUSH - mov r6, sp @ future r3 - - mov r7, r0 - mov r8, r1 - mov r9, r2 - mov r10, r3 - - sub r0, sp, #0x10 @ 0x10 - bic r0, #0xf @ align at 16 bytes - mov sp, r0 - -#ifdef XTS_CHAIN_TWEAK - ldr r0, [ip] @ pointer to input tweak -#else - @ generate initial tweak - ldr r0, [ip, #4] @ iv[] - mov r1, sp - ldr r2, [ip, #0] @ key2 - bl _AES_encrypt - mov r0, sp @ pointer to initial tweak -#endif - - ldr r1, [r10, #240] @ get # of rounds - mov r3, r6 -#ifndef BSAES_ASM_EXTENDED_KEY - @ allocate the key schedule on the stack - sub r12, sp, r1, lsl#7 @ 128 bytes per inner round key - @ add r12, #96 @ size of bit-sliced key schedule - sub r12, #48 @ place for tweak[9] - - @ populate the key schedule - mov r4, r10 @ pass key - mov r5, r1 @ pass # of rounds - mov sp, r12 - add r12, #0x90 @ pass key schedule - bl _bsaes_key_convert - add r4, sp, #0x90 - vldmia r4, {q6} - vstmia r12, {q15} @ save last round key - veor q7, q7, q6 @ fix up round 0 key - vstmia r4, {q7} -#else - ldr r12, [r10, #244] - eors r12, #1 - beq 0f - - str r12, [r10, #244] - mov r4, r10 @ pass key - mov r5, r1 @ pass # of rounds - add r12, r10, #248 @ pass key schedule - bl _bsaes_key_convert - add r4, r10, #248 - vldmia r4, {q6} - vstmia r12, {q15} @ save last round key - veor q7, q7, q6 @ fix up round 0 key - vstmia r4, {q7} - -.align 2 - sub sp, #0x90 @ place for tweak[9] -#endif - vld1.8 {q8}, [r0] @ initial tweak - adr r2, Lxts_magic - -#ifndef XTS_CHAIN_TWEAK - tst r9, #0xf @ if not multiple of 16 - it ne @ Thumb2 thing, sanity check in ARM - subne r9, #0x10 @ subtract another 16 bytes -#endif - subs r9, #0x80 - - blo Lxts_dec_short - b Lxts_dec_loop - -.align 4 -Lxts_dec_loop: - vldmia r2, {q5} @ load XTS magic - vshr.s64 q6, q8, #63 - mov r0, sp - vand q6, q6, q5 - vadd.u64 q9, q8, q8 - vst1.64 {q8}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q9, #63 - veor q9, q9, q6 - vand q7, q7, q5 - vadd.u64 q10, q9, q9 - vst1.64 {q9}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q10, #63 - veor q10, q10, q7 - vand q6, q6, q5 - vld1.8 {q0}, [r7]! - vadd.u64 q11, q10, q10 - vst1.64 {q10}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q11, #63 - veor q11, q11, q6 - vand q7, q7, q5 - vld1.8 {q1}, [r7]! - veor q0, q0, q8 - vadd.u64 q12, q11, q11 - vst1.64 {q11}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q12, #63 - veor q12, q12, q7 - vand q6, q6, q5 - vld1.8 {q2}, [r7]! - veor q1, q1, q9 - vadd.u64 q13, q12, q12 - vst1.64 {q12}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q13, #63 - veor q13, q13, q6 - vand q7, q7, q5 - vld1.8 {q3}, [r7]! - veor q2, q2, q10 - vadd.u64 q14, q13, q13 - vst1.64 {q13}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q14, #63 - veor q14, q14, q7 - vand q6, q6, q5 - vld1.8 {q4}, [r7]! - veor q3, q3, q11 - vadd.u64 q15, q14, q14 - vst1.64 {q14}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q15, #63 - veor q15, q15, q6 - vand q7, q7, q5 - vld1.8 {q5}, [r7]! - veor q4, q4, q12 - vadd.u64 q8, q15, q15 - vst1.64 {q15}, [r0,:128]! - vswp d15,d14 - veor q8, q8, q7 - vst1.64 {q8}, [r0,:128] @ next round tweak - - vld1.8 {q6,q7}, [r7]! - veor q5, q5, q13 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q6, q6, q14 - mov r5, r1 @ pass rounds - veor q7, q7, q15 - mov r0, sp - - bl _bsaes_decrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - vld1.64 {q12,q13}, [r0,:128]! - veor q1, q1, q9 - veor q8, q6, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q4, q11 - vld1.64 {q14,q15}, [r0,:128]! - veor q10, q2, q12 - vst1.8 {q8,q9}, [r8]! - veor q11, q7, q13 - veor q12, q3, q14 - vst1.8 {q10,q11}, [r8]! - veor q13, q5, q15 - vst1.8 {q12,q13}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - - subs r9, #0x80 - bpl Lxts_dec_loop - -Lxts_dec_short: - adds r9, #0x70 - bmi Lxts_dec_done - - vldmia r2, {q5} @ load XTS magic - vshr.s64 q7, q8, #63 - mov r0, sp - vand q7, q7, q5 - vadd.u64 q9, q8, q8 - vst1.64 {q8}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q9, #63 - veor q9, q9, q7 - vand q6, q6, q5 - vadd.u64 q10, q9, q9 - vst1.64 {q9}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q10, #63 - veor q10, q10, q6 - vand q7, q7, q5 - vld1.8 {q0}, [r7]! - subs r9, #0x10 - bmi Lxts_dec_1 - vadd.u64 q11, q10, q10 - vst1.64 {q10}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q11, #63 - veor q11, q11, q7 - vand q6, q6, q5 - vld1.8 {q1}, [r7]! - subs r9, #0x10 - bmi Lxts_dec_2 - veor q0, q0, q8 - vadd.u64 q12, q11, q11 - vst1.64 {q11}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q12, #63 - veor q12, q12, q6 - vand q7, q7, q5 - vld1.8 {q2}, [r7]! - subs r9, #0x10 - bmi Lxts_dec_3 - veor q1, q1, q9 - vadd.u64 q13, q12, q12 - vst1.64 {q12}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q13, #63 - veor q13, q13, q7 - vand q6, q6, q5 - vld1.8 {q3}, [r7]! - subs r9, #0x10 - bmi Lxts_dec_4 - veor q2, q2, q10 - vadd.u64 q14, q13, q13 - vst1.64 {q13}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q14, #63 - veor q14, q14, q6 - vand q7, q7, q5 - vld1.8 {q4}, [r7]! - subs r9, #0x10 - bmi Lxts_dec_5 - veor q3, q3, q11 - vadd.u64 q15, q14, q14 - vst1.64 {q14}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q15, #63 - veor q15, q15, q7 - vand q6, q6, q5 - vld1.8 {q5}, [r7]! - subs r9, #0x10 - bmi Lxts_dec_6 - veor q4, q4, q12 - sub r9, #0x10 - vst1.64 {q15}, [r0,:128] @ next round tweak - - vld1.8 {q6}, [r7]! - veor q5, q5, q13 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q6, q6, q14 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_decrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - vld1.64 {q12,q13}, [r0,:128]! - veor q1, q1, q9 - veor q8, q6, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q4, q11 - vld1.64 {q14}, [r0,:128]! - veor q10, q2, q12 - vst1.8 {q8,q9}, [r8]! - veor q11, q7, q13 - veor q12, q3, q14 - vst1.8 {q10,q11}, [r8]! - vst1.8 {q12}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b Lxts_dec_done -.align 4 -Lxts_dec_6: - vst1.64 {q14}, [r0,:128] @ next round tweak - - veor q4, q4, q12 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q5, q5, q13 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_decrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - vld1.64 {q12,q13}, [r0,:128]! - veor q1, q1, q9 - veor q8, q6, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q4, q11 - veor q10, q2, q12 - vst1.8 {q8,q9}, [r8]! - veor q11, q7, q13 - vst1.8 {q10,q11}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b Lxts_dec_done -.align 4 -Lxts_dec_5: - veor q3, q3, q11 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q4, q4, q12 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_decrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - vld1.64 {q12}, [r0,:128]! - veor q1, q1, q9 - veor q8, q6, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q4, q11 - veor q10, q2, q12 - vst1.8 {q8,q9}, [r8]! - vst1.8 {q10}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b Lxts_dec_done -.align 4 -Lxts_dec_4: - veor q2, q2, q10 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q3, q3, q11 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_decrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - veor q1, q1, q9 - veor q8, q6, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q4, q11 - vst1.8 {q8,q9}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b Lxts_dec_done -.align 4 -Lxts_dec_3: - veor q1, q1, q9 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q2, q2, q10 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_decrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10}, [r0,:128]! - veor q0, q0, q8 - veor q1, q1, q9 - veor q8, q6, q10 - vst1.8 {q0,q1}, [r8]! - vst1.8 {q8}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b Lxts_dec_done -.align 4 -Lxts_dec_2: - veor q0, q0, q8 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q1, q1, q9 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_decrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - veor q0, q0, q8 - veor q1, q1, q9 - vst1.8 {q0,q1}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b Lxts_dec_done -.align 4 -Lxts_dec_1: - mov r0, sp - veor q0, q0, q8 - mov r1, sp - vst1.8 {q0}, [sp,:128] - mov r5, r2 @ preserve magic - mov r2, r10 - mov r4, r3 @ preserve fp - - bl _AES_decrypt - - vld1.8 {q0}, [sp,:128] - veor q0, q0, q8 - vst1.8 {q0}, [r8]! - mov r3, r4 - mov r2, r5 - - vmov q8, q9 @ next round tweak - -Lxts_dec_done: -#ifndef XTS_CHAIN_TWEAK - adds r9, #0x10 - beq Lxts_dec_ret - - @ calculate one round of extra tweak for the stolen ciphertext - vldmia r2, {q5} - vshr.s64 q6, q8, #63 - vand q6, q6, q5 - vadd.u64 q9, q8, q8 - vswp d13,d12 - veor q9, q9, q6 - - @ perform the final decryption with the last tweak value - vld1.8 {q0}, [r7]! - mov r0, sp - veor q0, q0, q9 - mov r1, sp - vst1.8 {q0}, [sp,:128] - mov r2, r10 - mov r4, r3 @ preserve fp - - bl _AES_decrypt - - vld1.8 {q0}, [sp,:128] - veor q0, q0, q9 - vst1.8 {q0}, [r8] - - mov r6, r8 -Lxts_dec_steal: - ldrb r1, [r8] - ldrb r0, [r7], #1 - strb r1, [r8, #0x10] - strb r0, [r8], #1 - - subs r9, #1 - bhi Lxts_dec_steal - - vld1.8 {q0}, [r6] - mov r0, sp - veor q0, q8 - mov r1, sp - vst1.8 {q0}, [sp,:128] - mov r2, r10 - - bl _AES_decrypt - - vld1.8 {q0}, [sp,:128] - veor q0, q0, q8 - vst1.8 {q0}, [r6] - mov r3, r4 -#endif - -Lxts_dec_ret: - bic r0, r3, #0xf - vmov.i32 q0, #0 - vmov.i32 q1, #0 -#ifdef XTS_CHAIN_TWEAK - ldr r1, [r3, #0x20+VFP_ABI_FRAME] @ chain tweak -#endif -Lxts_dec_bzero:@ wipe key schedule [if any] - vstmia sp!, {q0,q1} - cmp sp, r0 - bne Lxts_dec_bzero - - mov sp, r3 -#ifdef XTS_CHAIN_TWEAK - vst1.8 {q8}, [r1] -#endif - VFP_ABI_POP - ldmia sp!, {r4,r5,r6,r7,r8,r9,r10, pc} @ return - + @ OpenSSL contains aes_nohw_* fallback code here. We patch this + @ out to retain a constant-time implementation. #endif #endif // !OPENSSL_NO_ASM diff --git a/third_party/boringssl/kit/ios-arm/crypto/fipsmodule/ghash-armv4.S b/third_party/boringssl/kit/ios-arm/crypto/fipsmodule/ghash-armv4.S index 2f4370ea..1fbc5356 100644 --- a/third_party/boringssl/kit/ios-arm/crypto/fipsmodule/ghash-armv4.S +++ b/third_party/boringssl/kit/ios-arm/crypto/fipsmodule/ghash-armv4.S @@ -21,6 +21,8 @@ .text #if defined(__thumb2__) || defined(__clang__) .syntax unified +#define ldrplb ldrbpl +#define ldrneb ldrbne #endif #if defined(__thumb2__) .thumb @@ -28,11 +30,6 @@ .code 32 #endif -#ifdef __clang__ -#define ldrplb ldrbpl -#define ldrneb ldrbne -#endif - .align 5 rem_4bit: diff --git a/third_party/boringssl/kit/ios-arm/crypto/test/trampoline-armv4.S b/third_party/boringssl/kit/ios-arm/crypto/test/trampoline-armv4.S new file mode 100644 index 00000000..b8e851f5 --- /dev/null +++ b/third_party/boringssl/kit/ios-arm/crypto/test/trampoline-armv4.S @@ -0,0 +1,376 @@ +// This file is generated from a similarly-named Perl script in the BoringSSL +// source tree. Do not edit by hand. + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) +#define OPENSSL_NO_ASM +#endif +#endif + +#if !defined(OPENSSL_NO_ASM) +#if defined(BORINGSSL_PREFIX) +#include +#endif +.syntax unified + + + + +.text + +@ abi_test_trampoline loads callee-saved registers from |state|, calls |func| +@ with |argv|, then saves the callee-saved registers into |state|. It returns +@ the result of |func|. The |unwind| argument is unused. +@ uint32_t abi_test_trampoline(void (*func)(...), CallerState *state, +@ const uint32_t *argv, size_t argc, +@ int unwind); + +.globl _abi_test_trampoline +.private_extern _abi_test_trampoline +.align 4 +_abi_test_trampoline: +Labi_test_trampoline_begin: + @ Save parameters and all callee-saved registers. For convenience, we + @ save r9 on iOS even though it's volatile. + vstmdb sp!, {d8,d9,d10,d11,d12,d13,d14,d15} + stmdb sp!, {r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,lr} + + @ Reserve stack space for six (10-4) stack parameters, plus an extra 4 + @ bytes to keep it 8-byte-aligned (see AAPCS, section 5.3). + sub sp, sp, #28 + + @ Every register in AAPCS is either non-volatile or a parameter (except + @ r9 on iOS), so this code, by the actual call, loses all its scratch + @ registers. First fill in stack parameters while there are registers + @ to spare. + cmp r3, #4 + bls Lstack_args_done + mov r4, sp @ r4 is the output pointer. + add r5, r2, r3, lsl #2 @ Set r5 to the end of argv. + add r2, r2, #16 @ Skip four arguments. +Lstack_args_loop: + ldr r6, [r2], #4 + cmp r2, r5 + str r6, [r4], #4 + bne Lstack_args_loop + +Lstack_args_done: + @ Load registers from |r1|. + vldmia r1!, {d8,d9,d10,d11,d12,d13,d14,d15} +#if defined(__APPLE__) + @ r9 is not volatile on iOS. + ldmia r1!, {r4,r5,r6,r7,r8,r10-r11} +#else + ldmia r1!, {r4,r5,r6,r7,r8,r9,r10,r11} +#endif + + @ Load register parameters. This uses up our remaining registers, so we + @ repurpose lr as scratch space. + ldr r3, [sp, #40] @ Reload argc. + ldr lr, [sp, #36] @ Load argv into lr. + cmp r3, #3 + bhi Larg_r3 + beq Larg_r2 + cmp r3, #1 + bhi Larg_r1 + beq Larg_r0 + b Largs_done + +Larg_r3: + ldr r3, [lr, #12] @ argv[3] +Larg_r2: + ldr r2, [lr, #8] @ argv[2] +Larg_r1: + ldr r1, [lr, #4] @ argv[1] +Larg_r0: + ldr r0, [lr] @ argv[0] +Largs_done: + + @ With every other register in use, load the function pointer into lr + @ and call the function. + ldr lr, [sp, #28] + blx lr + + @ r1-r3 are free for use again. The trampoline only supports + @ single-return functions. Pass r4-r11 to the caller. + ldr r1, [sp, #32] + vstmia r1!, {d8,d9,d10,d11,d12,d13,d14,d15} +#if defined(__APPLE__) + @ r9 is not volatile on iOS. + stmia r1!, {r4,r5,r6,r7,r8,r10-r11} +#else + stmia r1!, {r4,r5,r6,r7,r8,r9,r10,r11} +#endif + + @ Unwind the stack and restore registers. + add sp, sp, #44 @ 44 = 28+16 + ldmia sp!, {r4,r5,r6,r7,r8,r9,r10,r11,lr} @ Skip r0-r3 (see +16 above). + vldmia sp!, {d8,d9,d10,d11,d12,d13,d14,d15} + + bx lr + + +.globl _abi_test_clobber_r0 +.private_extern _abi_test_clobber_r0 +.align 4 +_abi_test_clobber_r0: + mov r0, #0 + bx lr + + +.globl _abi_test_clobber_r1 +.private_extern _abi_test_clobber_r1 +.align 4 +_abi_test_clobber_r1: + mov r1, #0 + bx lr + + +.globl _abi_test_clobber_r2 +.private_extern _abi_test_clobber_r2 +.align 4 +_abi_test_clobber_r2: + mov r2, #0 + bx lr + + +.globl _abi_test_clobber_r3 +.private_extern _abi_test_clobber_r3 +.align 4 +_abi_test_clobber_r3: + mov r3, #0 + bx lr + + +.globl _abi_test_clobber_r4 +.private_extern _abi_test_clobber_r4 +.align 4 +_abi_test_clobber_r4: + mov r4, #0 + bx lr + + +.globl _abi_test_clobber_r5 +.private_extern _abi_test_clobber_r5 +.align 4 +_abi_test_clobber_r5: + mov r5, #0 + bx lr + + +.globl _abi_test_clobber_r6 +.private_extern _abi_test_clobber_r6 +.align 4 +_abi_test_clobber_r6: + mov r6, #0 + bx lr + + +.globl _abi_test_clobber_r7 +.private_extern _abi_test_clobber_r7 +.align 4 +_abi_test_clobber_r7: + mov r7, #0 + bx lr + + +.globl _abi_test_clobber_r8 +.private_extern _abi_test_clobber_r8 +.align 4 +_abi_test_clobber_r8: + mov r8, #0 + bx lr + + +.globl _abi_test_clobber_r9 +.private_extern _abi_test_clobber_r9 +.align 4 +_abi_test_clobber_r9: + mov r9, #0 + bx lr + + +.globl _abi_test_clobber_r10 +.private_extern _abi_test_clobber_r10 +.align 4 +_abi_test_clobber_r10: + mov r10, #0 + bx lr + + +.globl _abi_test_clobber_r11 +.private_extern _abi_test_clobber_r11 +.align 4 +_abi_test_clobber_r11: + mov r11, #0 + bx lr + + +.globl _abi_test_clobber_r12 +.private_extern _abi_test_clobber_r12 +.align 4 +_abi_test_clobber_r12: + mov r12, #0 + bx lr + + +.globl _abi_test_clobber_d0 +.private_extern _abi_test_clobber_d0 +.align 4 +_abi_test_clobber_d0: + mov r0, #0 + vmov s0, r0 + vmov s1, r0 + bx lr + + +.globl _abi_test_clobber_d1 +.private_extern _abi_test_clobber_d1 +.align 4 +_abi_test_clobber_d1: + mov r0, #0 + vmov s2, r0 + vmov s3, r0 + bx lr + + +.globl _abi_test_clobber_d2 +.private_extern _abi_test_clobber_d2 +.align 4 +_abi_test_clobber_d2: + mov r0, #0 + vmov s4, r0 + vmov s5, r0 + bx lr + + +.globl _abi_test_clobber_d3 +.private_extern _abi_test_clobber_d3 +.align 4 +_abi_test_clobber_d3: + mov r0, #0 + vmov s6, r0 + vmov s7, r0 + bx lr + + +.globl _abi_test_clobber_d4 +.private_extern _abi_test_clobber_d4 +.align 4 +_abi_test_clobber_d4: + mov r0, #0 + vmov s8, r0 + vmov s9, r0 + bx lr + + +.globl _abi_test_clobber_d5 +.private_extern _abi_test_clobber_d5 +.align 4 +_abi_test_clobber_d5: + mov r0, #0 + vmov s10, r0 + vmov s11, r0 + bx lr + + +.globl _abi_test_clobber_d6 +.private_extern _abi_test_clobber_d6 +.align 4 +_abi_test_clobber_d6: + mov r0, #0 + vmov s12, r0 + vmov s13, r0 + bx lr + + +.globl _abi_test_clobber_d7 +.private_extern _abi_test_clobber_d7 +.align 4 +_abi_test_clobber_d7: + mov r0, #0 + vmov s14, r0 + vmov s15, r0 + bx lr + + +.globl _abi_test_clobber_d8 +.private_extern _abi_test_clobber_d8 +.align 4 +_abi_test_clobber_d8: + mov r0, #0 + vmov s16, r0 + vmov s17, r0 + bx lr + + +.globl _abi_test_clobber_d9 +.private_extern _abi_test_clobber_d9 +.align 4 +_abi_test_clobber_d9: + mov r0, #0 + vmov s18, r0 + vmov s19, r0 + bx lr + + +.globl _abi_test_clobber_d10 +.private_extern _abi_test_clobber_d10 +.align 4 +_abi_test_clobber_d10: + mov r0, #0 + vmov s20, r0 + vmov s21, r0 + bx lr + + +.globl _abi_test_clobber_d11 +.private_extern _abi_test_clobber_d11 +.align 4 +_abi_test_clobber_d11: + mov r0, #0 + vmov s22, r0 + vmov s23, r0 + bx lr + + +.globl _abi_test_clobber_d12 +.private_extern _abi_test_clobber_d12 +.align 4 +_abi_test_clobber_d12: + mov r0, #0 + vmov s24, r0 + vmov s25, r0 + bx lr + + +.globl _abi_test_clobber_d13 +.private_extern _abi_test_clobber_d13 +.align 4 +_abi_test_clobber_d13: + mov r0, #0 + vmov s26, r0 + vmov s27, r0 + bx lr + + +.globl _abi_test_clobber_d14 +.private_extern _abi_test_clobber_d14 +.align 4 +_abi_test_clobber_d14: + mov r0, #0 + vmov s28, r0 + vmov s29, r0 + bx lr + + +.globl _abi_test_clobber_d15 +.private_extern _abi_test_clobber_d15 +.align 4 +_abi_test_clobber_d15: + mov r0, #0 + vmov s30, r0 + vmov s31, r0 + bx lr + +#endif // !OPENSSL_NO_ASM diff --git a/third_party/boringssl/kit/linux-aarch64/crypto/fipsmodule/ghash-neon-armv8.S b/third_party/boringssl/kit/linux-aarch64/crypto/fipsmodule/ghash-neon-armv8.S new file mode 100644 index 00000000..1cfbec29 --- /dev/null +++ b/third_party/boringssl/kit/linux-aarch64/crypto/fipsmodule/ghash-neon-armv8.S @@ -0,0 +1,339 @@ +// This file is generated from a similarly-named Perl script in the BoringSSL +// source tree. Do not edit by hand. + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) +#define OPENSSL_NO_ASM +#endif +#endif + +#if !defined(OPENSSL_NO_ASM) +#if defined(__aarch64__) +#if defined(BORINGSSL_PREFIX) +#include +#endif +.text + +.globl gcm_init_neon +.hidden gcm_init_neon +.type gcm_init_neon,%function +.align 4 +gcm_init_neon: + // This function is adapted from gcm_init_v8. xC2 is t3. + ld1 {v17.2d}, [x1] // load H + movi v19.16b, #0xe1 + shl v19.2d, v19.2d, #57 // 0xc2.0 + ext v3.16b, v17.16b, v17.16b, #8 + ushr v18.2d, v19.2d, #63 + dup v17.4s, v17.s[1] + ext v16.16b, v18.16b, v19.16b, #8 // t0=0xc2....01 + ushr v18.2d, v3.2d, #63 + sshr v17.4s, v17.4s, #31 // broadcast carry bit + and v18.16b, v18.16b, v16.16b + shl v3.2d, v3.2d, #1 + ext v18.16b, v18.16b, v18.16b, #8 + and v16.16b, v16.16b, v17.16b + orr v3.16b, v3.16b, v18.16b // H<<<=1 + eor v5.16b, v3.16b, v16.16b // twisted H + st1 {v5.2d}, [x0] // store Htable[0] + ret +.size gcm_init_neon,.-gcm_init_neon + +.globl gcm_gmult_neon +.hidden gcm_gmult_neon +.type gcm_gmult_neon,%function +.align 4 +gcm_gmult_neon: + ld1 {v3.16b}, [x0] // load Xi + ld1 {v5.1d}, [x1], #8 // load twisted H + ld1 {v6.1d}, [x1] + adrp x9, .Lmasks // load constants + add x9, x9, :lo12:.Lmasks + ld1 {v24.2d, v25.2d}, [x9] + rev64 v3.16b, v3.16b // byteswap Xi + ext v3.16b, v3.16b, v3.16b, #8 + eor v7.8b, v5.8b, v6.8b // Karatsuba pre-processing + + mov x3, #16 + b .Lgmult_neon +.size gcm_gmult_neon,.-gcm_gmult_neon + +.globl gcm_ghash_neon +.hidden gcm_ghash_neon +.type gcm_ghash_neon,%function +.align 4 +gcm_ghash_neon: + ld1 {v0.16b}, [x0] // load Xi + ld1 {v5.1d}, [x1], #8 // load twisted H + ld1 {v6.1d}, [x1] + adrp x9, .Lmasks // load constants + add x9, x9, :lo12:.Lmasks + ld1 {v24.2d, v25.2d}, [x9] + rev64 v0.16b, v0.16b // byteswap Xi + ext v0.16b, v0.16b, v0.16b, #8 + eor v7.8b, v5.8b, v6.8b // Karatsuba pre-processing + +.Loop_neon: + ld1 {v3.16b}, [x2], #16 // load inp + rev64 v3.16b, v3.16b // byteswap inp + ext v3.16b, v3.16b, v3.16b, #8 + eor v3.16b, v3.16b, v0.16b // inp ^= Xi + +.Lgmult_neon: + // Split the input into v3 and v4. (The upper halves are unused, + // so it is okay to leave them alone.) + ins v4.d[0], v3.d[1] + ext v16.8b, v5.8b, v5.8b, #1 // A1 + pmull v16.8h, v16.8b, v3.8b // F = A1*B + ext v0.8b, v3.8b, v3.8b, #1 // B1 + pmull v0.8h, v5.8b, v0.8b // E = A*B1 + ext v17.8b, v5.8b, v5.8b, #2 // A2 + pmull v17.8h, v17.8b, v3.8b // H = A2*B + ext v19.8b, v3.8b, v3.8b, #2 // B2 + pmull v19.8h, v5.8b, v19.8b // G = A*B2 + ext v18.8b, v5.8b, v5.8b, #3 // A3 + eor v16.16b, v16.16b, v0.16b // L = E + F + pmull v18.8h, v18.8b, v3.8b // J = A3*B + ext v0.8b, v3.8b, v3.8b, #3 // B3 + eor v17.16b, v17.16b, v19.16b // M = G + H + pmull v0.8h, v5.8b, v0.8b // I = A*B3 + + // Here we diverge from the 32-bit version. It computes the following + // (instructions reordered for clarity): + // + // veor $t0#lo, $t0#lo, $t0#hi @ t0 = P0 + P1 (L) + // vand $t0#hi, $t0#hi, $k48 + // veor $t0#lo, $t0#lo, $t0#hi + // + // veor $t1#lo, $t1#lo, $t1#hi @ t1 = P2 + P3 (M) + // vand $t1#hi, $t1#hi, $k32 + // veor $t1#lo, $t1#lo, $t1#hi + // + // veor $t2#lo, $t2#lo, $t2#hi @ t2 = P4 + P5 (N) + // vand $t2#hi, $t2#hi, $k16 + // veor $t2#lo, $t2#lo, $t2#hi + // + // veor $t3#lo, $t3#lo, $t3#hi @ t3 = P6 + P7 (K) + // vmov.i64 $t3#hi, #0 + // + // $kN is a mask with the bottom N bits set. AArch64 cannot compute on + // upper halves of SIMD registers, so we must split each half into + // separate registers. To compensate, we pair computations up and + // parallelize. + + ext v19.8b, v3.8b, v3.8b, #4 // B4 + eor v18.16b, v18.16b, v0.16b // N = I + J + pmull v19.8h, v5.8b, v19.8b // K = A*B4 + + // This can probably be scheduled more efficiently. For now, we just + // pair up independent instructions. + zip1 v20.2d, v16.2d, v17.2d + zip1 v22.2d, v18.2d, v19.2d + zip2 v21.2d, v16.2d, v17.2d + zip2 v23.2d, v18.2d, v19.2d + eor v20.16b, v20.16b, v21.16b + eor v22.16b, v22.16b, v23.16b + and v21.16b, v21.16b, v24.16b + and v23.16b, v23.16b, v25.16b + eor v20.16b, v20.16b, v21.16b + eor v22.16b, v22.16b, v23.16b + zip1 v16.2d, v20.2d, v21.2d + zip1 v18.2d, v22.2d, v23.2d + zip2 v17.2d, v20.2d, v21.2d + zip2 v19.2d, v22.2d, v23.2d + + ext v16.16b, v16.16b, v16.16b, #15 // t0 = t0 << 8 + ext v17.16b, v17.16b, v17.16b, #14 // t1 = t1 << 16 + pmull v0.8h, v5.8b, v3.8b // D = A*B + ext v19.16b, v19.16b, v19.16b, #12 // t3 = t3 << 32 + ext v18.16b, v18.16b, v18.16b, #13 // t2 = t2 << 24 + eor v16.16b, v16.16b, v17.16b + eor v18.16b, v18.16b, v19.16b + eor v0.16b, v0.16b, v16.16b + eor v0.16b, v0.16b, v18.16b + eor v3.8b, v3.8b, v4.8b // Karatsuba pre-processing + ext v16.8b, v7.8b, v7.8b, #1 // A1 + pmull v16.8h, v16.8b, v3.8b // F = A1*B + ext v1.8b, v3.8b, v3.8b, #1 // B1 + pmull v1.8h, v7.8b, v1.8b // E = A*B1 + ext v17.8b, v7.8b, v7.8b, #2 // A2 + pmull v17.8h, v17.8b, v3.8b // H = A2*B + ext v19.8b, v3.8b, v3.8b, #2 // B2 + pmull v19.8h, v7.8b, v19.8b // G = A*B2 + ext v18.8b, v7.8b, v7.8b, #3 // A3 + eor v16.16b, v16.16b, v1.16b // L = E + F + pmull v18.8h, v18.8b, v3.8b // J = A3*B + ext v1.8b, v3.8b, v3.8b, #3 // B3 + eor v17.16b, v17.16b, v19.16b // M = G + H + pmull v1.8h, v7.8b, v1.8b // I = A*B3 + + // Here we diverge from the 32-bit version. It computes the following + // (instructions reordered for clarity): + // + // veor $t0#lo, $t0#lo, $t0#hi @ t0 = P0 + P1 (L) + // vand $t0#hi, $t0#hi, $k48 + // veor $t0#lo, $t0#lo, $t0#hi + // + // veor $t1#lo, $t1#lo, $t1#hi @ t1 = P2 + P3 (M) + // vand $t1#hi, $t1#hi, $k32 + // veor $t1#lo, $t1#lo, $t1#hi + // + // veor $t2#lo, $t2#lo, $t2#hi @ t2 = P4 + P5 (N) + // vand $t2#hi, $t2#hi, $k16 + // veor $t2#lo, $t2#lo, $t2#hi + // + // veor $t3#lo, $t3#lo, $t3#hi @ t3 = P6 + P7 (K) + // vmov.i64 $t3#hi, #0 + // + // $kN is a mask with the bottom N bits set. AArch64 cannot compute on + // upper halves of SIMD registers, so we must split each half into + // separate registers. To compensate, we pair computations up and + // parallelize. + + ext v19.8b, v3.8b, v3.8b, #4 // B4 + eor v18.16b, v18.16b, v1.16b // N = I + J + pmull v19.8h, v7.8b, v19.8b // K = A*B4 + + // This can probably be scheduled more efficiently. For now, we just + // pair up independent instructions. + zip1 v20.2d, v16.2d, v17.2d + zip1 v22.2d, v18.2d, v19.2d + zip2 v21.2d, v16.2d, v17.2d + zip2 v23.2d, v18.2d, v19.2d + eor v20.16b, v20.16b, v21.16b + eor v22.16b, v22.16b, v23.16b + and v21.16b, v21.16b, v24.16b + and v23.16b, v23.16b, v25.16b + eor v20.16b, v20.16b, v21.16b + eor v22.16b, v22.16b, v23.16b + zip1 v16.2d, v20.2d, v21.2d + zip1 v18.2d, v22.2d, v23.2d + zip2 v17.2d, v20.2d, v21.2d + zip2 v19.2d, v22.2d, v23.2d + + ext v16.16b, v16.16b, v16.16b, #15 // t0 = t0 << 8 + ext v17.16b, v17.16b, v17.16b, #14 // t1 = t1 << 16 + pmull v1.8h, v7.8b, v3.8b // D = A*B + ext v19.16b, v19.16b, v19.16b, #12 // t3 = t3 << 32 + ext v18.16b, v18.16b, v18.16b, #13 // t2 = t2 << 24 + eor v16.16b, v16.16b, v17.16b + eor v18.16b, v18.16b, v19.16b + eor v1.16b, v1.16b, v16.16b + eor v1.16b, v1.16b, v18.16b + ext v16.8b, v6.8b, v6.8b, #1 // A1 + pmull v16.8h, v16.8b, v4.8b // F = A1*B + ext v2.8b, v4.8b, v4.8b, #1 // B1 + pmull v2.8h, v6.8b, v2.8b // E = A*B1 + ext v17.8b, v6.8b, v6.8b, #2 // A2 + pmull v17.8h, v17.8b, v4.8b // H = A2*B + ext v19.8b, v4.8b, v4.8b, #2 // B2 + pmull v19.8h, v6.8b, v19.8b // G = A*B2 + ext v18.8b, v6.8b, v6.8b, #3 // A3 + eor v16.16b, v16.16b, v2.16b // L = E + F + pmull v18.8h, v18.8b, v4.8b // J = A3*B + ext v2.8b, v4.8b, v4.8b, #3 // B3 + eor v17.16b, v17.16b, v19.16b // M = G + H + pmull v2.8h, v6.8b, v2.8b // I = A*B3 + + // Here we diverge from the 32-bit version. It computes the following + // (instructions reordered for clarity): + // + // veor $t0#lo, $t0#lo, $t0#hi @ t0 = P0 + P1 (L) + // vand $t0#hi, $t0#hi, $k48 + // veor $t0#lo, $t0#lo, $t0#hi + // + // veor $t1#lo, $t1#lo, $t1#hi @ t1 = P2 + P3 (M) + // vand $t1#hi, $t1#hi, $k32 + // veor $t1#lo, $t1#lo, $t1#hi + // + // veor $t2#lo, $t2#lo, $t2#hi @ t2 = P4 + P5 (N) + // vand $t2#hi, $t2#hi, $k16 + // veor $t2#lo, $t2#lo, $t2#hi + // + // veor $t3#lo, $t3#lo, $t3#hi @ t3 = P6 + P7 (K) + // vmov.i64 $t3#hi, #0 + // + // $kN is a mask with the bottom N bits set. AArch64 cannot compute on + // upper halves of SIMD registers, so we must split each half into + // separate registers. To compensate, we pair computations up and + // parallelize. + + ext v19.8b, v4.8b, v4.8b, #4 // B4 + eor v18.16b, v18.16b, v2.16b // N = I + J + pmull v19.8h, v6.8b, v19.8b // K = A*B4 + + // This can probably be scheduled more efficiently. For now, we just + // pair up independent instructions. + zip1 v20.2d, v16.2d, v17.2d + zip1 v22.2d, v18.2d, v19.2d + zip2 v21.2d, v16.2d, v17.2d + zip2 v23.2d, v18.2d, v19.2d + eor v20.16b, v20.16b, v21.16b + eor v22.16b, v22.16b, v23.16b + and v21.16b, v21.16b, v24.16b + and v23.16b, v23.16b, v25.16b + eor v20.16b, v20.16b, v21.16b + eor v22.16b, v22.16b, v23.16b + zip1 v16.2d, v20.2d, v21.2d + zip1 v18.2d, v22.2d, v23.2d + zip2 v17.2d, v20.2d, v21.2d + zip2 v19.2d, v22.2d, v23.2d + + ext v16.16b, v16.16b, v16.16b, #15 // t0 = t0 << 8 + ext v17.16b, v17.16b, v17.16b, #14 // t1 = t1 << 16 + pmull v2.8h, v6.8b, v4.8b // D = A*B + ext v19.16b, v19.16b, v19.16b, #12 // t3 = t3 << 32 + ext v18.16b, v18.16b, v18.16b, #13 // t2 = t2 << 24 + eor v16.16b, v16.16b, v17.16b + eor v18.16b, v18.16b, v19.16b + eor v2.16b, v2.16b, v16.16b + eor v2.16b, v2.16b, v18.16b + ext v16.16b, v0.16b, v2.16b, #8 + eor v1.16b, v1.16b, v0.16b // Karatsuba post-processing + eor v1.16b, v1.16b, v2.16b + eor v1.16b, v1.16b, v16.16b // Xm overlaps Xh.lo and Xl.hi + ins v0.d[1], v1.d[0] // Xh|Xl - 256-bit result + // This is a no-op due to the ins instruction below. + // ins v2.d[0], v1.d[1] + + // equivalent of reduction_avx from ghash-x86_64.pl + shl v17.2d, v0.2d, #57 // 1st phase + shl v18.2d, v0.2d, #62 + eor v18.16b, v18.16b, v17.16b // + shl v17.2d, v0.2d, #63 + eor v18.16b, v18.16b, v17.16b // + // Note Xm contains {Xl.d[1], Xh.d[0]}. + eor v18.16b, v18.16b, v1.16b + ins v0.d[1], v18.d[0] // Xl.d[1] ^= t2.d[0] + ins v2.d[0], v18.d[1] // Xh.d[0] ^= t2.d[1] + + ushr v18.2d, v0.2d, #1 // 2nd phase + eor v2.16b, v2.16b,v0.16b + eor v0.16b, v0.16b,v18.16b // + ushr v18.2d, v18.2d, #6 + ushr v0.2d, v0.2d, #1 // + eor v0.16b, v0.16b, v2.16b // + eor v0.16b, v0.16b, v18.16b // + + subs x3, x3, #16 + bne .Loop_neon + + rev64 v0.16b, v0.16b // byteswap Xi and write + ext v0.16b, v0.16b, v0.16b, #8 + st1 {v0.16b}, [x0] + + ret +.size gcm_ghash_neon,.-gcm_ghash_neon + +.section .rodata +.align 4 +.Lmasks: +.quad 0x0000ffffffffffff // k48 +.quad 0x00000000ffffffff // k32 +.quad 0x000000000000ffff // k16 +.quad 0x0000000000000000 // k0 +.byte 71,72,65,83,72,32,102,111,114,32,65,82,77,118,56,44,32,100,101,114,105,118,101,100,32,102,114,111,109,32,65,82,77,118,52,32,118,101,114,115,105,111,110,32,98,121,32,60,97,112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103,62,0 +.align 2 +.align 2 +#endif +#endif // !OPENSSL_NO_ASM diff --git a/third_party/boringssl/kit/linux-aarch64/crypto/fipsmodule/vpaes-armv8.S b/third_party/boringssl/kit/linux-aarch64/crypto/fipsmodule/vpaes-armv8.S new file mode 100644 index 00000000..02b16b67 --- /dev/null +++ b/third_party/boringssl/kit/linux-aarch64/crypto/fipsmodule/vpaes-armv8.S @@ -0,0 +1,1214 @@ +// This file is generated from a similarly-named Perl script in the BoringSSL +// source tree. Do not edit by hand. + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) +#define OPENSSL_NO_ASM +#endif +#endif + +#if !defined(OPENSSL_NO_ASM) +#if defined(__aarch64__) +#if defined(BORINGSSL_PREFIX) +#include +#endif +.section .rodata + +.type _vpaes_consts,%object +.align 7 // totally strategic alignment +_vpaes_consts: +.Lk_mc_forward: // mc_forward +.quad 0x0407060500030201, 0x0C0F0E0D080B0A09 +.quad 0x080B0A0904070605, 0x000302010C0F0E0D +.quad 0x0C0F0E0D080B0A09, 0x0407060500030201 +.quad 0x000302010C0F0E0D, 0x080B0A0904070605 +.Lk_mc_backward: // mc_backward +.quad 0x0605040702010003, 0x0E0D0C0F0A09080B +.quad 0x020100030E0D0C0F, 0x0A09080B06050407 +.quad 0x0E0D0C0F0A09080B, 0x0605040702010003 +.quad 0x0A09080B06050407, 0x020100030E0D0C0F +.Lk_sr: // sr +.quad 0x0706050403020100, 0x0F0E0D0C0B0A0908 +.quad 0x030E09040F0A0500, 0x0B06010C07020D08 +.quad 0x0F060D040B020900, 0x070E050C030A0108 +.quad 0x0B0E0104070A0D00, 0x0306090C0F020508 + +// +// "Hot" constants +// +.Lk_inv: // inv, inva +.quad 0x0E05060F0D080180, 0x040703090A0B0C02 +.quad 0x01040A060F0B0780, 0x030D0E0C02050809 +.Lk_ipt: // input transform (lo, hi) +.quad 0xC2B2E8985A2A7000, 0xCABAE09052227808 +.quad 0x4C01307D317C4D00, 0xCD80B1FCB0FDCC81 +.Lk_sbo: // sbou, sbot +.quad 0xD0D26D176FBDC700, 0x15AABF7AC502A878 +.quad 0xCFE474A55FBB6A00, 0x8E1E90D1412B35FA +.Lk_sb1: // sb1u, sb1t +.quad 0x3618D415FAE22300, 0x3BF7CCC10D2ED9EF +.quad 0xB19BE18FCB503E00, 0xA5DF7A6E142AF544 +.Lk_sb2: // sb2u, sb2t +.quad 0x69EB88400AE12900, 0xC2A163C8AB82234A +.quad 0xE27A93C60B712400, 0x5EB7E955BC982FCD + +// +// Decryption stuff +// +.Lk_dipt: // decryption input transform +.quad 0x0F505B040B545F00, 0x154A411E114E451A +.quad 0x86E383E660056500, 0x12771772F491F194 +.Lk_dsbo: // decryption sbox final output +.quad 0x1387EA537EF94000, 0xC7AA6DB9D4943E2D +.quad 0x12D7560F93441D00, 0xCA4B8159D8C58E9C +.Lk_dsb9: // decryption sbox output *9*u, *9*t +.quad 0x851C03539A86D600, 0xCAD51F504F994CC9 +.quad 0xC03B1789ECD74900, 0x725E2C9EB2FBA565 +.Lk_dsbd: // decryption sbox output *D*u, *D*t +.quad 0x7D57CCDFE6B1A200, 0xF56E9B13882A4439 +.quad 0x3CE2FAF724C6CB00, 0x2931180D15DEEFD3 +.Lk_dsbb: // decryption sbox output *B*u, *B*t +.quad 0xD022649296B44200, 0x602646F6B0F2D404 +.quad 0xC19498A6CD596700, 0xF3FF0C3E3255AA6B +.Lk_dsbe: // decryption sbox output *E*u, *E*t +.quad 0x46F2929626D4D000, 0x2242600464B4F6B0 +.quad 0x0C55A6CDFFAAC100, 0x9467F36B98593E32 + +// +// Key schedule constants +// +.Lk_dksd: // decryption key schedule: invskew x*D +.quad 0xFEB91A5DA3E44700, 0x0740E3A45A1DBEF9 +.quad 0x41C277F4B5368300, 0x5FDC69EAAB289D1E +.Lk_dksb: // decryption key schedule: invskew x*B +.quad 0x9A4FCA1F8550D500, 0x03D653861CC94C99 +.quad 0x115BEDA7B6FC4A00, 0xD993256F7E3482C8 +.Lk_dkse: // decryption key schedule: invskew x*E + 0x63 +.quad 0xD5031CCA1FC9D600, 0x53859A4C994F5086 +.quad 0xA23196054FDC7BE8, 0xCD5EF96A20B31487 +.Lk_dks9: // decryption key schedule: invskew x*9 +.quad 0xB6116FC87ED9A700, 0x4AED933482255BFC +.quad 0x4576516227143300, 0x8BB89FACE9DAFDCE + +.Lk_rcon: // rcon +.quad 0x1F8391B9AF9DEEB6, 0x702A98084D7C7D81 + +.Lk_opt: // output transform +.quad 0xFF9F4929D6B66000, 0xF7974121DEBE6808 +.quad 0x01EDBD5150BCEC00, 0xE10D5DB1B05C0CE0 +.Lk_deskew: // deskew tables: inverts the sbox's "skew" +.quad 0x07E4A34047A4E300, 0x1DFEB95A5DBEF91A +.quad 0x5F36B5DC83EA6900, 0x2841C2ABF49D1E77 + +.byte 86,101,99,116,111,114,32,80,101,114,109,117,116,97,116,105,111,110,32,65,69,83,32,102,111,114,32,65,82,77,118,56,44,32,77,105,107,101,32,72,97,109,98,117,114,103,32,40,83,116,97,110,102,111,114,100,32,85,110,105,118,101,114,115,105,116,121,41,0 +.align 2 +.size _vpaes_consts,.-_vpaes_consts +.align 6 + +.text +## +## _aes_preheat +## +## Fills register %r10 -> .aes_consts (so you can -fPIC) +## and %xmm9-%xmm15 as specified below. +## +.type _vpaes_encrypt_preheat,%function +.align 4 +_vpaes_encrypt_preheat: + adrp x10, .Lk_inv + add x10, x10, :lo12:.Lk_inv + movi v17.16b, #0x0f + ld1 {v18.2d,v19.2d}, [x10],#32 // .Lk_inv + ld1 {v20.2d,v21.2d,v22.2d,v23.2d}, [x10],#64 // .Lk_ipt, .Lk_sbo + ld1 {v24.2d,v25.2d,v26.2d,v27.2d}, [x10] // .Lk_sb1, .Lk_sb2 + ret +.size _vpaes_encrypt_preheat,.-_vpaes_encrypt_preheat + +## +## _aes_encrypt_core +## +## AES-encrypt %xmm0. +## +## Inputs: +## %xmm0 = input +## %xmm9-%xmm15 as in _vpaes_preheat +## (%rdx) = scheduled keys +## +## Output in %xmm0 +## Clobbers %xmm1-%xmm5, %r9, %r10, %r11, %rax +## Preserves %xmm6 - %xmm8 so you get some local vectors +## +## +.type _vpaes_encrypt_core,%function +.align 4 +_vpaes_encrypt_core: + mov x9, x2 + ldr w8, [x2,#240] // pull rounds + adrp x11, .Lk_mc_forward+16 + add x11, x11, :lo12:.Lk_mc_forward+16 + // vmovdqa .Lk_ipt(%rip), %xmm2 # iptlo + ld1 {v16.2d}, [x9], #16 // vmovdqu (%r9), %xmm5 # round0 key + and v1.16b, v7.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 + ushr v0.16b, v7.16b, #4 // vpsrlb $4, %xmm0, %xmm0 + tbl v1.16b, {v20.16b}, v1.16b // vpshufb %xmm1, %xmm2, %xmm1 + // vmovdqa .Lk_ipt+16(%rip), %xmm3 # ipthi + tbl v2.16b, {v21.16b}, v0.16b // vpshufb %xmm0, %xmm3, %xmm2 + eor v0.16b, v1.16b, v16.16b // vpxor %xmm5, %xmm1, %xmm0 + eor v0.16b, v0.16b, v2.16b // vpxor %xmm2, %xmm0, %xmm0 + b .Lenc_entry + +.align 4 +.Lenc_loop: + // middle of middle round + add x10, x11, #0x40 + tbl v4.16b, {v25.16b}, v2.16b // vpshufb %xmm2, %xmm13, %xmm4 # 4 = sb1u + ld1 {v1.2d}, [x11], #16 // vmovdqa -0x40(%r11,%r10), %xmm1 # .Lk_mc_forward[] + tbl v0.16b, {v24.16b}, v3.16b // vpshufb %xmm3, %xmm12, %xmm0 # 0 = sb1t + eor v4.16b, v4.16b, v16.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = sb1u + k + tbl v5.16b, {v27.16b}, v2.16b // vpshufb %xmm2, %xmm15, %xmm5 # 4 = sb2u + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = A + tbl v2.16b, {v26.16b}, v3.16b // vpshufb %xmm3, %xmm14, %xmm2 # 2 = sb2t + ld1 {v4.2d}, [x10] // vmovdqa (%r11,%r10), %xmm4 # .Lk_mc_backward[] + tbl v3.16b, {v0.16b}, v1.16b // vpshufb %xmm1, %xmm0, %xmm3 # 0 = B + eor v2.16b, v2.16b, v5.16b // vpxor %xmm5, %xmm2, %xmm2 # 2 = 2A + tbl v0.16b, {v0.16b}, v4.16b // vpshufb %xmm4, %xmm0, %xmm0 # 3 = D + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 # 0 = 2A+B + tbl v4.16b, {v3.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm4 # 0 = 2B+C + eor v0.16b, v0.16b, v3.16b // vpxor %xmm3, %xmm0, %xmm0 # 3 = 2A+B+D + and x11, x11, #~(1<<6) // and $0x30, %r11 # ... mod 4 + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = 2A+3B+C+D + sub w8, w8, #1 // nr-- + +.Lenc_entry: + // top of round + and v1.16b, v0.16b, v17.16b // vpand %xmm0, %xmm9, %xmm1 # 0 = k + ushr v0.16b, v0.16b, #4 // vpsrlb $4, %xmm0, %xmm0 # 1 = i + tbl v5.16b, {v19.16b}, v1.16b // vpshufb %xmm1, %xmm11, %xmm5 # 2 = a/k + eor v1.16b, v1.16b, v0.16b // vpxor %xmm0, %xmm1, %xmm1 # 0 = j + tbl v3.16b, {v18.16b}, v0.16b // vpshufb %xmm0, %xmm10, %xmm3 # 3 = 1/i + tbl v4.16b, {v18.16b}, v1.16b // vpshufb %xmm1, %xmm10, %xmm4 # 4 = 1/j + eor v3.16b, v3.16b, v5.16b // vpxor %xmm5, %xmm3, %xmm3 # 3 = iak = 1/i + a/k + eor v4.16b, v4.16b, v5.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = jak = 1/j + a/k + tbl v2.16b, {v18.16b}, v3.16b // vpshufb %xmm3, %xmm10, %xmm2 # 2 = 1/iak + tbl v3.16b, {v18.16b}, v4.16b // vpshufb %xmm4, %xmm10, %xmm3 # 3 = 1/jak + eor v2.16b, v2.16b, v1.16b // vpxor %xmm1, %xmm2, %xmm2 # 2 = io + eor v3.16b, v3.16b, v0.16b // vpxor %xmm0, %xmm3, %xmm3 # 3 = jo + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm5 + cbnz w8, .Lenc_loop + + // middle of last round + add x10, x11, #0x80 + // vmovdqa -0x60(%r10), %xmm4 # 3 : sbou .Lk_sbo + // vmovdqa -0x50(%r10), %xmm0 # 0 : sbot .Lk_sbo+16 + tbl v4.16b, {v22.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbou + ld1 {v1.2d}, [x10] // vmovdqa 0x40(%r11,%r10), %xmm1 # .Lk_sr[] + tbl v0.16b, {v23.16b}, v3.16b // vpshufb %xmm3, %xmm0, %xmm0 # 0 = sb1t + eor v4.16b, v4.16b, v16.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = sb1u + k + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = A + tbl v0.16b, {v0.16b}, v1.16b // vpshufb %xmm1, %xmm0, %xmm0 + ret +.size _vpaes_encrypt_core,.-_vpaes_encrypt_core + +.globl vpaes_encrypt +.hidden vpaes_encrypt +.type vpaes_encrypt,%function +.align 4 +vpaes_encrypt: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + + ld1 {v7.16b}, [x0] + bl _vpaes_encrypt_preheat + bl _vpaes_encrypt_core + st1 {v0.16b}, [x1] + + ldp x29,x30,[sp],#16 + ret +.size vpaes_encrypt,.-vpaes_encrypt + +.type _vpaes_encrypt_2x,%function +.align 4 +_vpaes_encrypt_2x: + mov x9, x2 + ldr w8, [x2,#240] // pull rounds + adrp x11, .Lk_mc_forward+16 + add x11, x11, :lo12:.Lk_mc_forward+16 + // vmovdqa .Lk_ipt(%rip), %xmm2 # iptlo + ld1 {v16.2d}, [x9], #16 // vmovdqu (%r9), %xmm5 # round0 key + and v1.16b, v14.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 + ushr v0.16b, v14.16b, #4 // vpsrlb $4, %xmm0, %xmm0 + and v9.16b, v15.16b, v17.16b + ushr v8.16b, v15.16b, #4 + tbl v1.16b, {v20.16b}, v1.16b // vpshufb %xmm1, %xmm2, %xmm1 + tbl v9.16b, {v20.16b}, v9.16b + // vmovdqa .Lk_ipt+16(%rip), %xmm3 # ipthi + tbl v2.16b, {v21.16b}, v0.16b // vpshufb %xmm0, %xmm3, %xmm2 + tbl v10.16b, {v21.16b}, v8.16b + eor v0.16b, v1.16b, v16.16b // vpxor %xmm5, %xmm1, %xmm0 + eor v8.16b, v9.16b, v16.16b + eor v0.16b, v0.16b, v2.16b // vpxor %xmm2, %xmm0, %xmm0 + eor v8.16b, v8.16b, v10.16b + b .Lenc_2x_entry + +.align 4 +.Lenc_2x_loop: + // middle of middle round + add x10, x11, #0x40 + tbl v4.16b, {v25.16b}, v2.16b // vpshufb %xmm2, %xmm13, %xmm4 # 4 = sb1u + tbl v12.16b, {v25.16b}, v10.16b + ld1 {v1.2d}, [x11], #16 // vmovdqa -0x40(%r11,%r10), %xmm1 # .Lk_mc_forward[] + tbl v0.16b, {v24.16b}, v3.16b // vpshufb %xmm3, %xmm12, %xmm0 # 0 = sb1t + tbl v8.16b, {v24.16b}, v11.16b + eor v4.16b, v4.16b, v16.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = sb1u + k + eor v12.16b, v12.16b, v16.16b + tbl v5.16b, {v27.16b}, v2.16b // vpshufb %xmm2, %xmm15, %xmm5 # 4 = sb2u + tbl v13.16b, {v27.16b}, v10.16b + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = A + eor v8.16b, v8.16b, v12.16b + tbl v2.16b, {v26.16b}, v3.16b // vpshufb %xmm3, %xmm14, %xmm2 # 2 = sb2t + tbl v10.16b, {v26.16b}, v11.16b + ld1 {v4.2d}, [x10] // vmovdqa (%r11,%r10), %xmm4 # .Lk_mc_backward[] + tbl v3.16b, {v0.16b}, v1.16b // vpshufb %xmm1, %xmm0, %xmm3 # 0 = B + tbl v11.16b, {v8.16b}, v1.16b + eor v2.16b, v2.16b, v5.16b // vpxor %xmm5, %xmm2, %xmm2 # 2 = 2A + eor v10.16b, v10.16b, v13.16b + tbl v0.16b, {v0.16b}, v4.16b // vpshufb %xmm4, %xmm0, %xmm0 # 3 = D + tbl v8.16b, {v8.16b}, v4.16b + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 # 0 = 2A+B + eor v11.16b, v11.16b, v10.16b + tbl v4.16b, {v3.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm4 # 0 = 2B+C + tbl v12.16b, {v11.16b},v1.16b + eor v0.16b, v0.16b, v3.16b // vpxor %xmm3, %xmm0, %xmm0 # 3 = 2A+B+D + eor v8.16b, v8.16b, v11.16b + and x11, x11, #~(1<<6) // and $0x30, %r11 # ... mod 4 + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = 2A+3B+C+D + eor v8.16b, v8.16b, v12.16b + sub w8, w8, #1 // nr-- + +.Lenc_2x_entry: + // top of round + and v1.16b, v0.16b, v17.16b // vpand %xmm0, %xmm9, %xmm1 # 0 = k + ushr v0.16b, v0.16b, #4 // vpsrlb $4, %xmm0, %xmm0 # 1 = i + and v9.16b, v8.16b, v17.16b + ushr v8.16b, v8.16b, #4 + tbl v5.16b, {v19.16b},v1.16b // vpshufb %xmm1, %xmm11, %xmm5 # 2 = a/k + tbl v13.16b, {v19.16b},v9.16b + eor v1.16b, v1.16b, v0.16b // vpxor %xmm0, %xmm1, %xmm1 # 0 = j + eor v9.16b, v9.16b, v8.16b + tbl v3.16b, {v18.16b},v0.16b // vpshufb %xmm0, %xmm10, %xmm3 # 3 = 1/i + tbl v11.16b, {v18.16b},v8.16b + tbl v4.16b, {v18.16b},v1.16b // vpshufb %xmm1, %xmm10, %xmm4 # 4 = 1/j + tbl v12.16b, {v18.16b},v9.16b + eor v3.16b, v3.16b, v5.16b // vpxor %xmm5, %xmm3, %xmm3 # 3 = iak = 1/i + a/k + eor v11.16b, v11.16b, v13.16b + eor v4.16b, v4.16b, v5.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = jak = 1/j + a/k + eor v12.16b, v12.16b, v13.16b + tbl v2.16b, {v18.16b},v3.16b // vpshufb %xmm3, %xmm10, %xmm2 # 2 = 1/iak + tbl v10.16b, {v18.16b},v11.16b + tbl v3.16b, {v18.16b},v4.16b // vpshufb %xmm4, %xmm10, %xmm3 # 3 = 1/jak + tbl v11.16b, {v18.16b},v12.16b + eor v2.16b, v2.16b, v1.16b // vpxor %xmm1, %xmm2, %xmm2 # 2 = io + eor v10.16b, v10.16b, v9.16b + eor v3.16b, v3.16b, v0.16b // vpxor %xmm0, %xmm3, %xmm3 # 3 = jo + eor v11.16b, v11.16b, v8.16b + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm5 + cbnz w8, .Lenc_2x_loop + + // middle of last round + add x10, x11, #0x80 + // vmovdqa -0x60(%r10), %xmm4 # 3 : sbou .Lk_sbo + // vmovdqa -0x50(%r10), %xmm0 # 0 : sbot .Lk_sbo+16 + tbl v4.16b, {v22.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbou + tbl v12.16b, {v22.16b}, v10.16b + ld1 {v1.2d}, [x10] // vmovdqa 0x40(%r11,%r10), %xmm1 # .Lk_sr[] + tbl v0.16b, {v23.16b}, v3.16b // vpshufb %xmm3, %xmm0, %xmm0 # 0 = sb1t + tbl v8.16b, {v23.16b}, v11.16b + eor v4.16b, v4.16b, v16.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = sb1u + k + eor v12.16b, v12.16b, v16.16b + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = A + eor v8.16b, v8.16b, v12.16b + tbl v0.16b, {v0.16b},v1.16b // vpshufb %xmm1, %xmm0, %xmm0 + tbl v1.16b, {v8.16b},v1.16b + ret +.size _vpaes_encrypt_2x,.-_vpaes_encrypt_2x + +.type _vpaes_decrypt_preheat,%function +.align 4 +_vpaes_decrypt_preheat: + adrp x10, .Lk_inv + add x10, x10, :lo12:.Lk_inv + movi v17.16b, #0x0f + adrp x11, .Lk_dipt + add x11, x11, :lo12:.Lk_dipt + ld1 {v18.2d,v19.2d}, [x10],#32 // .Lk_inv + ld1 {v20.2d,v21.2d,v22.2d,v23.2d}, [x11],#64 // .Lk_dipt, .Lk_dsbo + ld1 {v24.2d,v25.2d,v26.2d,v27.2d}, [x11],#64 // .Lk_dsb9, .Lk_dsbd + ld1 {v28.2d,v29.2d,v30.2d,v31.2d}, [x11] // .Lk_dsbb, .Lk_dsbe + ret +.size _vpaes_decrypt_preheat,.-_vpaes_decrypt_preheat + +## +## Decryption core +## +## Same API as encryption core. +## +.type _vpaes_decrypt_core,%function +.align 4 +_vpaes_decrypt_core: + mov x9, x2 + ldr w8, [x2,#240] // pull rounds + + // vmovdqa .Lk_dipt(%rip), %xmm2 # iptlo + lsl x11, x8, #4 // mov %rax, %r11; shl $4, %r11 + eor x11, x11, #0x30 // xor $0x30, %r11 + adrp x10, .Lk_sr + add x10, x10, :lo12:.Lk_sr + and x11, x11, #0x30 // and $0x30, %r11 + add x11, x11, x10 + adrp x10, .Lk_mc_forward+48 + add x10, x10, :lo12:.Lk_mc_forward+48 + + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm4 # round0 key + and v1.16b, v7.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 + ushr v0.16b, v7.16b, #4 // vpsrlb $4, %xmm0, %xmm0 + tbl v2.16b, {v20.16b}, v1.16b // vpshufb %xmm1, %xmm2, %xmm2 + ld1 {v5.2d}, [x10] // vmovdqa .Lk_mc_forward+48(%rip), %xmm5 + // vmovdqa .Lk_dipt+16(%rip), %xmm1 # ipthi + tbl v0.16b, {v21.16b}, v0.16b // vpshufb %xmm0, %xmm1, %xmm0 + eor v2.16b, v2.16b, v16.16b // vpxor %xmm4, %xmm2, %xmm2 + eor v0.16b, v0.16b, v2.16b // vpxor %xmm2, %xmm0, %xmm0 + b .Ldec_entry + +.align 4 +.Ldec_loop: +// +// Inverse mix columns +// + // vmovdqa -0x20(%r10),%xmm4 # 4 : sb9u + // vmovdqa -0x10(%r10),%xmm1 # 0 : sb9t + tbl v4.16b, {v24.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sb9u + tbl v1.16b, {v25.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sb9t + eor v0.16b, v4.16b, v16.16b // vpxor %xmm4, %xmm0, %xmm0 + // vmovdqa 0x00(%r10),%xmm4 # 4 : sbdu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + // vmovdqa 0x10(%r10),%xmm1 # 0 : sbdt + + tbl v4.16b, {v26.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbdu + tbl v0.16b, {v0.16b}, v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v1.16b, {v27.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbdt + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + // vmovdqa 0x20(%r10), %xmm4 # 4 : sbbu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + // vmovdqa 0x30(%r10), %xmm1 # 0 : sbbt + + tbl v4.16b, {v28.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbbu + tbl v0.16b, {v0.16b}, v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v1.16b, {v29.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbbt + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + // vmovdqa 0x40(%r10), %xmm4 # 4 : sbeu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + // vmovdqa 0x50(%r10), %xmm1 # 0 : sbet + + tbl v4.16b, {v30.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbeu + tbl v0.16b, {v0.16b}, v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v1.16b, {v31.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbet + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + ext v5.16b, v5.16b, v5.16b, #12 // vpalignr $12, %xmm5, %xmm5, %xmm5 + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + sub w8, w8, #1 // sub $1,%rax # nr-- + +.Ldec_entry: + // top of round + and v1.16b, v0.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 # 0 = k + ushr v0.16b, v0.16b, #4 // vpsrlb $4, %xmm0, %xmm0 # 1 = i + tbl v2.16b, {v19.16b}, v1.16b // vpshufb %xmm1, %xmm11, %xmm2 # 2 = a/k + eor v1.16b, v1.16b, v0.16b // vpxor %xmm0, %xmm1, %xmm1 # 0 = j + tbl v3.16b, {v18.16b}, v0.16b // vpshufb %xmm0, %xmm10, %xmm3 # 3 = 1/i + tbl v4.16b, {v18.16b}, v1.16b // vpshufb %xmm1, %xmm10, %xmm4 # 4 = 1/j + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 # 3 = iak = 1/i + a/k + eor v4.16b, v4.16b, v2.16b // vpxor %xmm2, %xmm4, %xmm4 # 4 = jak = 1/j + a/k + tbl v2.16b, {v18.16b}, v3.16b // vpshufb %xmm3, %xmm10, %xmm2 # 2 = 1/iak + tbl v3.16b, {v18.16b}, v4.16b // vpshufb %xmm4, %xmm10, %xmm3 # 3 = 1/jak + eor v2.16b, v2.16b, v1.16b // vpxor %xmm1, %xmm2, %xmm2 # 2 = io + eor v3.16b, v3.16b, v0.16b // vpxor %xmm0, %xmm3, %xmm3 # 3 = jo + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm0 + cbnz w8, .Ldec_loop + + // middle of last round + // vmovdqa 0x60(%r10), %xmm4 # 3 : sbou + tbl v4.16b, {v22.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbou + // vmovdqa 0x70(%r10), %xmm1 # 0 : sbot + ld1 {v2.2d}, [x11] // vmovdqa -0x160(%r11), %xmm2 # .Lk_sr-.Lk_dsbd=-0x160 + tbl v1.16b, {v23.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sb1t + eor v4.16b, v4.16b, v16.16b // vpxor %xmm0, %xmm4, %xmm4 # 4 = sb1u + k + eor v0.16b, v1.16b, v4.16b // vpxor %xmm4, %xmm1, %xmm0 # 0 = A + tbl v0.16b, {v0.16b}, v2.16b // vpshufb %xmm2, %xmm0, %xmm0 + ret +.size _vpaes_decrypt_core,.-_vpaes_decrypt_core + +.globl vpaes_decrypt +.hidden vpaes_decrypt +.type vpaes_decrypt,%function +.align 4 +vpaes_decrypt: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + + ld1 {v7.16b}, [x0] + bl _vpaes_decrypt_preheat + bl _vpaes_decrypt_core + st1 {v0.16b}, [x1] + + ldp x29,x30,[sp],#16 + ret +.size vpaes_decrypt,.-vpaes_decrypt + +// v14-v15 input, v0-v1 output +.type _vpaes_decrypt_2x,%function +.align 4 +_vpaes_decrypt_2x: + mov x9, x2 + ldr w8, [x2,#240] // pull rounds + + // vmovdqa .Lk_dipt(%rip), %xmm2 # iptlo + lsl x11, x8, #4 // mov %rax, %r11; shl $4, %r11 + eor x11, x11, #0x30 // xor $0x30, %r11 + adrp x10, .Lk_sr + add x10, x10, :lo12:.Lk_sr + and x11, x11, #0x30 // and $0x30, %r11 + add x11, x11, x10 + adrp x10, .Lk_mc_forward+48 + add x10, x10, :lo12:.Lk_mc_forward+48 + + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm4 # round0 key + and v1.16b, v14.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 + ushr v0.16b, v14.16b, #4 // vpsrlb $4, %xmm0, %xmm0 + and v9.16b, v15.16b, v17.16b + ushr v8.16b, v15.16b, #4 + tbl v2.16b, {v20.16b},v1.16b // vpshufb %xmm1, %xmm2, %xmm2 + tbl v10.16b, {v20.16b},v9.16b + ld1 {v5.2d}, [x10] // vmovdqa .Lk_mc_forward+48(%rip), %xmm5 + // vmovdqa .Lk_dipt+16(%rip), %xmm1 # ipthi + tbl v0.16b, {v21.16b},v0.16b // vpshufb %xmm0, %xmm1, %xmm0 + tbl v8.16b, {v21.16b},v8.16b + eor v2.16b, v2.16b, v16.16b // vpxor %xmm4, %xmm2, %xmm2 + eor v10.16b, v10.16b, v16.16b + eor v0.16b, v0.16b, v2.16b // vpxor %xmm2, %xmm0, %xmm0 + eor v8.16b, v8.16b, v10.16b + b .Ldec_2x_entry + +.align 4 +.Ldec_2x_loop: +// +// Inverse mix columns +// + // vmovdqa -0x20(%r10),%xmm4 # 4 : sb9u + // vmovdqa -0x10(%r10),%xmm1 # 0 : sb9t + tbl v4.16b, {v24.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sb9u + tbl v12.16b, {v24.16b}, v10.16b + tbl v1.16b, {v25.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sb9t + tbl v9.16b, {v25.16b}, v11.16b + eor v0.16b, v4.16b, v16.16b // vpxor %xmm4, %xmm0, %xmm0 + eor v8.16b, v12.16b, v16.16b + // vmovdqa 0x00(%r10),%xmm4 # 4 : sbdu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + eor v8.16b, v8.16b, v9.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + // vmovdqa 0x10(%r10),%xmm1 # 0 : sbdt + + tbl v4.16b, {v26.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbdu + tbl v12.16b, {v26.16b}, v10.16b + tbl v0.16b, {v0.16b},v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v8.16b, {v8.16b},v5.16b + tbl v1.16b, {v27.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbdt + tbl v9.16b, {v27.16b}, v11.16b + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + eor v8.16b, v8.16b, v12.16b + // vmovdqa 0x20(%r10), %xmm4 # 4 : sbbu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + eor v8.16b, v8.16b, v9.16b + // vmovdqa 0x30(%r10), %xmm1 # 0 : sbbt + + tbl v4.16b, {v28.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbbu + tbl v12.16b, {v28.16b}, v10.16b + tbl v0.16b, {v0.16b},v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v8.16b, {v8.16b},v5.16b + tbl v1.16b, {v29.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbbt + tbl v9.16b, {v29.16b}, v11.16b + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + eor v8.16b, v8.16b, v12.16b + // vmovdqa 0x40(%r10), %xmm4 # 4 : sbeu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + eor v8.16b, v8.16b, v9.16b + // vmovdqa 0x50(%r10), %xmm1 # 0 : sbet + + tbl v4.16b, {v30.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbeu + tbl v12.16b, {v30.16b}, v10.16b + tbl v0.16b, {v0.16b},v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v8.16b, {v8.16b},v5.16b + tbl v1.16b, {v31.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbet + tbl v9.16b, {v31.16b}, v11.16b + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + eor v8.16b, v8.16b, v12.16b + ext v5.16b, v5.16b, v5.16b, #12 // vpalignr $12, %xmm5, %xmm5, %xmm5 + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + eor v8.16b, v8.16b, v9.16b + sub w8, w8, #1 // sub $1,%rax # nr-- + +.Ldec_2x_entry: + // top of round + and v1.16b, v0.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 # 0 = k + ushr v0.16b, v0.16b, #4 // vpsrlb $4, %xmm0, %xmm0 # 1 = i + and v9.16b, v8.16b, v17.16b + ushr v8.16b, v8.16b, #4 + tbl v2.16b, {v19.16b},v1.16b // vpshufb %xmm1, %xmm11, %xmm2 # 2 = a/k + tbl v10.16b, {v19.16b},v9.16b + eor v1.16b, v1.16b, v0.16b // vpxor %xmm0, %xmm1, %xmm1 # 0 = j + eor v9.16b, v9.16b, v8.16b + tbl v3.16b, {v18.16b},v0.16b // vpshufb %xmm0, %xmm10, %xmm3 # 3 = 1/i + tbl v11.16b, {v18.16b},v8.16b + tbl v4.16b, {v18.16b},v1.16b // vpshufb %xmm1, %xmm10, %xmm4 # 4 = 1/j + tbl v12.16b, {v18.16b},v9.16b + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 # 3 = iak = 1/i + a/k + eor v11.16b, v11.16b, v10.16b + eor v4.16b, v4.16b, v2.16b // vpxor %xmm2, %xmm4, %xmm4 # 4 = jak = 1/j + a/k + eor v12.16b, v12.16b, v10.16b + tbl v2.16b, {v18.16b},v3.16b // vpshufb %xmm3, %xmm10, %xmm2 # 2 = 1/iak + tbl v10.16b, {v18.16b},v11.16b + tbl v3.16b, {v18.16b},v4.16b // vpshufb %xmm4, %xmm10, %xmm3 # 3 = 1/jak + tbl v11.16b, {v18.16b},v12.16b + eor v2.16b, v2.16b, v1.16b // vpxor %xmm1, %xmm2, %xmm2 # 2 = io + eor v10.16b, v10.16b, v9.16b + eor v3.16b, v3.16b, v0.16b // vpxor %xmm0, %xmm3, %xmm3 # 3 = jo + eor v11.16b, v11.16b, v8.16b + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm0 + cbnz w8, .Ldec_2x_loop + + // middle of last round + // vmovdqa 0x60(%r10), %xmm4 # 3 : sbou + tbl v4.16b, {v22.16b}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbou + tbl v12.16b, {v22.16b}, v10.16b + // vmovdqa 0x70(%r10), %xmm1 # 0 : sbot + tbl v1.16b, {v23.16b}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sb1t + tbl v9.16b, {v23.16b}, v11.16b + ld1 {v2.2d}, [x11] // vmovdqa -0x160(%r11), %xmm2 # .Lk_sr-.Lk_dsbd=-0x160 + eor v4.16b, v4.16b, v16.16b // vpxor %xmm0, %xmm4, %xmm4 # 4 = sb1u + k + eor v12.16b, v12.16b, v16.16b + eor v0.16b, v1.16b, v4.16b // vpxor %xmm4, %xmm1, %xmm0 # 0 = A + eor v8.16b, v9.16b, v12.16b + tbl v0.16b, {v0.16b},v2.16b // vpshufb %xmm2, %xmm0, %xmm0 + tbl v1.16b, {v8.16b},v2.16b + ret +.size _vpaes_decrypt_2x,.-_vpaes_decrypt_2x +######################################################## +## ## +## AES key schedule ## +## ## +######################################################## +.type _vpaes_key_preheat,%function +.align 4 +_vpaes_key_preheat: + adrp x10, .Lk_inv + add x10, x10, :lo12:.Lk_inv + movi v16.16b, #0x5b // .Lk_s63 + adrp x11, .Lk_sb1 + add x11, x11, :lo12:.Lk_sb1 + movi v17.16b, #0x0f // .Lk_s0F + ld1 {v18.2d,v19.2d,v20.2d,v21.2d}, [x10] // .Lk_inv, .Lk_ipt + adrp x10, .Lk_dksd + add x10, x10, :lo12:.Lk_dksd + ld1 {v22.2d,v23.2d}, [x11] // .Lk_sb1 + adrp x11, .Lk_mc_forward + add x11, x11, :lo12:.Lk_mc_forward + ld1 {v24.2d,v25.2d,v26.2d,v27.2d}, [x10],#64 // .Lk_dksd, .Lk_dksb + ld1 {v28.2d,v29.2d,v30.2d,v31.2d}, [x10],#64 // .Lk_dkse, .Lk_dks9 + ld1 {v8.2d}, [x10] // .Lk_rcon + ld1 {v9.2d}, [x11] // .Lk_mc_forward[0] + ret +.size _vpaes_key_preheat,.-_vpaes_key_preheat + +.type _vpaes_schedule_core,%function +.align 4 +_vpaes_schedule_core: + stp x29, x30, [sp,#-16]! + add x29,sp,#0 + + bl _vpaes_key_preheat // load the tables + + ld1 {v0.16b}, [x0],#16 // vmovdqu (%rdi), %xmm0 # load key (unaligned) + + // input transform + mov v3.16b, v0.16b // vmovdqa %xmm0, %xmm3 + bl _vpaes_schedule_transform + mov v7.16b, v0.16b // vmovdqa %xmm0, %xmm7 + + adrp x10, .Lk_sr // lea .Lk_sr(%rip),%r10 + add x10, x10, :lo12:.Lk_sr + + add x8, x8, x10 + cbnz w3, .Lschedule_am_decrypting + + // encrypting, output zeroth round key after transform + st1 {v0.2d}, [x2] // vmovdqu %xmm0, (%rdx) + b .Lschedule_go + +.Lschedule_am_decrypting: + // decrypting, output zeroth round key after shiftrows + ld1 {v1.2d}, [x8] // vmovdqa (%r8,%r10), %xmm1 + tbl v3.16b, {v3.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm3 + st1 {v3.2d}, [x2] // vmovdqu %xmm3, (%rdx) + eor x8, x8, #0x30 // xor $0x30, %r8 + +.Lschedule_go: + cmp w1, #192 // cmp $192, %esi + b.hi .Lschedule_256 + b.eq .Lschedule_192 + // 128: fall though + +## +## .schedule_128 +## +## 128-bit specific part of key schedule. +## +## This schedule is really simple, because all its parts +## are accomplished by the subroutines. +## +.Lschedule_128: + mov x0, #10 // mov $10, %esi + +.Loop_schedule_128: + sub x0, x0, #1 // dec %esi + bl _vpaes_schedule_round + cbz x0, .Lschedule_mangle_last + bl _vpaes_schedule_mangle // write output + b .Loop_schedule_128 + +## +## .aes_schedule_192 +## +## 192-bit specific part of key schedule. +## +## The main body of this schedule is the same as the 128-bit +## schedule, but with more smearing. The long, high side is +## stored in %xmm7 as before, and the short, low side is in +## the high bits of %xmm6. +## +## This schedule is somewhat nastier, however, because each +## round produces 192 bits of key material, or 1.5 round keys. +## Therefore, on each cycle we do 2 rounds and produce 3 round +## keys. +## +.align 4 +.Lschedule_192: + sub x0, x0, #8 + ld1 {v0.16b}, [x0] // vmovdqu 8(%rdi),%xmm0 # load key part 2 (very unaligned) + bl _vpaes_schedule_transform // input transform + mov v6.16b, v0.16b // vmovdqa %xmm0, %xmm6 # save short part + eor v4.16b, v4.16b, v4.16b // vpxor %xmm4, %xmm4, %xmm4 # clear 4 + ins v6.d[0], v4.d[0] // vmovhlps %xmm4, %xmm6, %xmm6 # clobber low side with zeros + mov x0, #4 // mov $4, %esi + +.Loop_schedule_192: + sub x0, x0, #1 // dec %esi + bl _vpaes_schedule_round + ext v0.16b, v6.16b, v0.16b, #8 // vpalignr $8,%xmm6,%xmm0,%xmm0 + bl _vpaes_schedule_mangle // save key n + bl _vpaes_schedule_192_smear + bl _vpaes_schedule_mangle // save key n+1 + bl _vpaes_schedule_round + cbz x0, .Lschedule_mangle_last + bl _vpaes_schedule_mangle // save key n+2 + bl _vpaes_schedule_192_smear + b .Loop_schedule_192 + +## +## .aes_schedule_256 +## +## 256-bit specific part of key schedule. +## +## The structure here is very similar to the 128-bit +## schedule, but with an additional "low side" in +## %xmm6. The low side's rounds are the same as the +## high side's, except no rcon and no rotation. +## +.align 4 +.Lschedule_256: + ld1 {v0.16b}, [x0] // vmovdqu 16(%rdi),%xmm0 # load key part 2 (unaligned) + bl _vpaes_schedule_transform // input transform + mov x0, #7 // mov $7, %esi + +.Loop_schedule_256: + sub x0, x0, #1 // dec %esi + bl _vpaes_schedule_mangle // output low result + mov v6.16b, v0.16b // vmovdqa %xmm0, %xmm6 # save cur_lo in xmm6 + + // high round + bl _vpaes_schedule_round + cbz x0, .Lschedule_mangle_last + bl _vpaes_schedule_mangle + + // low round. swap xmm7 and xmm6 + dup v0.4s, v0.s[3] // vpshufd $0xFF, %xmm0, %xmm0 + movi v4.16b, #0 + mov v5.16b, v7.16b // vmovdqa %xmm7, %xmm5 + mov v7.16b, v6.16b // vmovdqa %xmm6, %xmm7 + bl _vpaes_schedule_low_round + mov v7.16b, v5.16b // vmovdqa %xmm5, %xmm7 + + b .Loop_schedule_256 + +## +## .aes_schedule_mangle_last +## +## Mangler for last round of key schedule +## Mangles %xmm0 +## when encrypting, outputs out(%xmm0) ^ 63 +## when decrypting, outputs unskew(%xmm0) +## +## Always called right before return... jumps to cleanup and exits +## +.align 4 +.Lschedule_mangle_last: + // schedule last round key from xmm0 + adrp x11, .Lk_deskew // lea .Lk_deskew(%rip),%r11 # prepare to deskew + add x11, x11, :lo12:.Lk_deskew + + cbnz w3, .Lschedule_mangle_last_dec + + // encrypting + ld1 {v1.2d}, [x8] // vmovdqa (%r8,%r10),%xmm1 + adrp x11, .Lk_opt // lea .Lk_opt(%rip), %r11 # prepare to output transform + add x11, x11, :lo12:.Lk_opt + add x2, x2, #32 // add $32, %rdx + tbl v0.16b, {v0.16b}, v1.16b // vpshufb %xmm1, %xmm0, %xmm0 # output permute + +.Lschedule_mangle_last_dec: + ld1 {v20.2d,v21.2d}, [x11] // reload constants + sub x2, x2, #16 // add $-16, %rdx + eor v0.16b, v0.16b, v16.16b // vpxor .Lk_s63(%rip), %xmm0, %xmm0 + bl _vpaes_schedule_transform // output transform + st1 {v0.2d}, [x2] // vmovdqu %xmm0, (%rdx) # save last key + + // cleanup + eor v0.16b, v0.16b, v0.16b // vpxor %xmm0, %xmm0, %xmm0 + eor v1.16b, v1.16b, v1.16b // vpxor %xmm1, %xmm1, %xmm1 + eor v2.16b, v2.16b, v2.16b // vpxor %xmm2, %xmm2, %xmm2 + eor v3.16b, v3.16b, v3.16b // vpxor %xmm3, %xmm3, %xmm3 + eor v4.16b, v4.16b, v4.16b // vpxor %xmm4, %xmm4, %xmm4 + eor v5.16b, v5.16b, v5.16b // vpxor %xmm5, %xmm5, %xmm5 + eor v6.16b, v6.16b, v6.16b // vpxor %xmm6, %xmm6, %xmm6 + eor v7.16b, v7.16b, v7.16b // vpxor %xmm7, %xmm7, %xmm7 + ldp x29, x30, [sp],#16 + ret +.size _vpaes_schedule_core,.-_vpaes_schedule_core + +## +## .aes_schedule_192_smear +## +## Smear the short, low side in the 192-bit key schedule. +## +## Inputs: +## %xmm7: high side, b a x y +## %xmm6: low side, d c 0 0 +## %xmm13: 0 +## +## Outputs: +## %xmm6: b+c+d b+c 0 0 +## %xmm0: b+c+d b+c b a +## +.type _vpaes_schedule_192_smear,%function +.align 4 +_vpaes_schedule_192_smear: + movi v1.16b, #0 + dup v0.4s, v7.s[3] + ins v1.s[3], v6.s[2] // vpshufd $0x80, %xmm6, %xmm1 # d c 0 0 -> c 0 0 0 + ins v0.s[0], v7.s[2] // vpshufd $0xFE, %xmm7, %xmm0 # b a _ _ -> b b b a + eor v6.16b, v6.16b, v1.16b // vpxor %xmm1, %xmm6, %xmm6 # -> c+d c 0 0 + eor v1.16b, v1.16b, v1.16b // vpxor %xmm1, %xmm1, %xmm1 + eor v6.16b, v6.16b, v0.16b // vpxor %xmm0, %xmm6, %xmm6 # -> b+c+d b+c b a + mov v0.16b, v6.16b // vmovdqa %xmm6, %xmm0 + ins v6.d[0], v1.d[0] // vmovhlps %xmm1, %xmm6, %xmm6 # clobber low side with zeros + ret +.size _vpaes_schedule_192_smear,.-_vpaes_schedule_192_smear + +## +## .aes_schedule_round +## +## Runs one main round of the key schedule on %xmm0, %xmm7 +## +## Specifically, runs subbytes on the high dword of %xmm0 +## then rotates it by one byte and xors into the low dword of +## %xmm7. +## +## Adds rcon from low byte of %xmm8, then rotates %xmm8 for +## next rcon. +## +## Smears the dwords of %xmm7 by xoring the low into the +## second low, result into third, result into highest. +## +## Returns results in %xmm7 = %xmm0. +## Clobbers %xmm1-%xmm4, %r11. +## +.type _vpaes_schedule_round,%function +.align 4 +_vpaes_schedule_round: + // extract rcon from xmm8 + movi v4.16b, #0 // vpxor %xmm4, %xmm4, %xmm4 + ext v1.16b, v8.16b, v4.16b, #15 // vpalignr $15, %xmm8, %xmm4, %xmm1 + ext v8.16b, v8.16b, v8.16b, #15 // vpalignr $15, %xmm8, %xmm8, %xmm8 + eor v7.16b, v7.16b, v1.16b // vpxor %xmm1, %xmm7, %xmm7 + + // rotate + dup v0.4s, v0.s[3] // vpshufd $0xFF, %xmm0, %xmm0 + ext v0.16b, v0.16b, v0.16b, #1 // vpalignr $1, %xmm0, %xmm0, %xmm0 + + // fall through... + + // low round: same as high round, but no rotation and no rcon. +_vpaes_schedule_low_round: + // smear xmm7 + ext v1.16b, v4.16b, v7.16b, #12 // vpslldq $4, %xmm7, %xmm1 + eor v7.16b, v7.16b, v1.16b // vpxor %xmm1, %xmm7, %xmm7 + ext v4.16b, v4.16b, v7.16b, #8 // vpslldq $8, %xmm7, %xmm4 + + // subbytes + and v1.16b, v0.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 # 0 = k + ushr v0.16b, v0.16b, #4 // vpsrlb $4, %xmm0, %xmm0 # 1 = i + eor v7.16b, v7.16b, v4.16b // vpxor %xmm4, %xmm7, %xmm7 + tbl v2.16b, {v19.16b}, v1.16b // vpshufb %xmm1, %xmm11, %xmm2 # 2 = a/k + eor v1.16b, v1.16b, v0.16b // vpxor %xmm0, %xmm1, %xmm1 # 0 = j + tbl v3.16b, {v18.16b}, v0.16b // vpshufb %xmm0, %xmm10, %xmm3 # 3 = 1/i + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 # 3 = iak = 1/i + a/k + tbl v4.16b, {v18.16b}, v1.16b // vpshufb %xmm1, %xmm10, %xmm4 # 4 = 1/j + eor v7.16b, v7.16b, v16.16b // vpxor .Lk_s63(%rip), %xmm7, %xmm7 + tbl v3.16b, {v18.16b}, v3.16b // vpshufb %xmm3, %xmm10, %xmm3 # 2 = 1/iak + eor v4.16b, v4.16b, v2.16b // vpxor %xmm2, %xmm4, %xmm4 # 4 = jak = 1/j + a/k + tbl v2.16b, {v18.16b}, v4.16b // vpshufb %xmm4, %xmm10, %xmm2 # 3 = 1/jak + eor v3.16b, v3.16b, v1.16b // vpxor %xmm1, %xmm3, %xmm3 # 2 = io + eor v2.16b, v2.16b, v0.16b // vpxor %xmm0, %xmm2, %xmm2 # 3 = jo + tbl v4.16b, {v23.16b}, v3.16b // vpshufb %xmm3, %xmm13, %xmm4 # 4 = sbou + tbl v1.16b, {v22.16b}, v2.16b // vpshufb %xmm2, %xmm12, %xmm1 # 0 = sb1t + eor v1.16b, v1.16b, v4.16b // vpxor %xmm4, %xmm1, %xmm1 # 0 = sbox output + + // add in smeared stuff + eor v0.16b, v1.16b, v7.16b // vpxor %xmm7, %xmm1, %xmm0 + eor v7.16b, v1.16b, v7.16b // vmovdqa %xmm0, %xmm7 + ret +.size _vpaes_schedule_round,.-_vpaes_schedule_round + +## +## .aes_schedule_transform +## +## Linear-transform %xmm0 according to tables at (%r11) +## +## Requires that %xmm9 = 0x0F0F... as in preheat +## Output in %xmm0 +## Clobbers %xmm1, %xmm2 +## +.type _vpaes_schedule_transform,%function +.align 4 +_vpaes_schedule_transform: + and v1.16b, v0.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 + ushr v0.16b, v0.16b, #4 // vpsrlb $4, %xmm0, %xmm0 + // vmovdqa (%r11), %xmm2 # lo + tbl v2.16b, {v20.16b}, v1.16b // vpshufb %xmm1, %xmm2, %xmm2 + // vmovdqa 16(%r11), %xmm1 # hi + tbl v0.16b, {v21.16b}, v0.16b // vpshufb %xmm0, %xmm1, %xmm0 + eor v0.16b, v0.16b, v2.16b // vpxor %xmm2, %xmm0, %xmm0 + ret +.size _vpaes_schedule_transform,.-_vpaes_schedule_transform + +## +## .aes_schedule_mangle +## +## Mangle xmm0 from (basis-transformed) standard version +## to our version. +## +## On encrypt, +## xor with 0x63 +## multiply by circulant 0,1,1,1 +## apply shiftrows transform +## +## On decrypt, +## xor with 0x63 +## multiply by "inverse mixcolumns" circulant E,B,D,9 +## deskew +## apply shiftrows transform +## +## +## Writes out to (%rdx), and increments or decrements it +## Keeps track of round number mod 4 in %r8 +## Preserves xmm0 +## Clobbers xmm1-xmm5 +## +.type _vpaes_schedule_mangle,%function +.align 4 +_vpaes_schedule_mangle: + mov v4.16b, v0.16b // vmovdqa %xmm0, %xmm4 # save xmm0 for later + // vmovdqa .Lk_mc_forward(%rip),%xmm5 + cbnz w3, .Lschedule_mangle_dec + + // encrypting + eor v4.16b, v0.16b, v16.16b // vpxor .Lk_s63(%rip), %xmm0, %xmm4 + add x2, x2, #16 // add $16, %rdx + tbl v4.16b, {v4.16b}, v9.16b // vpshufb %xmm5, %xmm4, %xmm4 + tbl v1.16b, {v4.16b}, v9.16b // vpshufb %xmm5, %xmm4, %xmm1 + tbl v3.16b, {v1.16b}, v9.16b // vpshufb %xmm5, %xmm1, %xmm3 + eor v4.16b, v4.16b, v1.16b // vpxor %xmm1, %xmm4, %xmm4 + ld1 {v1.2d}, [x8] // vmovdqa (%r8,%r10), %xmm1 + eor v3.16b, v3.16b, v4.16b // vpxor %xmm4, %xmm3, %xmm3 + + b .Lschedule_mangle_both +.align 4 +.Lschedule_mangle_dec: + // inverse mix columns + // lea .Lk_dksd(%rip),%r11 + ushr v1.16b, v4.16b, #4 // vpsrlb $4, %xmm4, %xmm1 # 1 = hi + and v4.16b, v4.16b, v17.16b // vpand %xmm9, %xmm4, %xmm4 # 4 = lo + + // vmovdqa 0x00(%r11), %xmm2 + tbl v2.16b, {v24.16b}, v4.16b // vpshufb %xmm4, %xmm2, %xmm2 + // vmovdqa 0x10(%r11), %xmm3 + tbl v3.16b, {v25.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm3 + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 + tbl v3.16b, {v3.16b}, v9.16b // vpshufb %xmm5, %xmm3, %xmm3 + + // vmovdqa 0x20(%r11), %xmm2 + tbl v2.16b, {v26.16b}, v4.16b // vpshufb %xmm4, %xmm2, %xmm2 + eor v2.16b, v2.16b, v3.16b // vpxor %xmm3, %xmm2, %xmm2 + // vmovdqa 0x30(%r11), %xmm3 + tbl v3.16b, {v27.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm3 + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 + tbl v3.16b, {v3.16b}, v9.16b // vpshufb %xmm5, %xmm3, %xmm3 + + // vmovdqa 0x40(%r11), %xmm2 + tbl v2.16b, {v28.16b}, v4.16b // vpshufb %xmm4, %xmm2, %xmm2 + eor v2.16b, v2.16b, v3.16b // vpxor %xmm3, %xmm2, %xmm2 + // vmovdqa 0x50(%r11), %xmm3 + tbl v3.16b, {v29.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm3 + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 + + // vmovdqa 0x60(%r11), %xmm2 + tbl v2.16b, {v30.16b}, v4.16b // vpshufb %xmm4, %xmm2, %xmm2 + tbl v3.16b, {v3.16b}, v9.16b // vpshufb %xmm5, %xmm3, %xmm3 + // vmovdqa 0x70(%r11), %xmm4 + tbl v4.16b, {v31.16b}, v1.16b // vpshufb %xmm1, %xmm4, %xmm4 + ld1 {v1.2d}, [x8] // vmovdqa (%r8,%r10), %xmm1 + eor v2.16b, v2.16b, v3.16b // vpxor %xmm3, %xmm2, %xmm2 + eor v3.16b, v4.16b, v2.16b // vpxor %xmm2, %xmm4, %xmm3 + + sub x2, x2, #16 // add $-16, %rdx + +.Lschedule_mangle_both: + tbl v3.16b, {v3.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm3 + add x8, x8, #64-16 // add $-16, %r8 + and x8, x8, #~(1<<6) // and $0x30, %r8 + st1 {v3.2d}, [x2] // vmovdqu %xmm3, (%rdx) + ret +.size _vpaes_schedule_mangle,.-_vpaes_schedule_mangle + +.globl vpaes_set_encrypt_key +.hidden vpaes_set_encrypt_key +.type vpaes_set_encrypt_key,%function +.align 4 +vpaes_set_encrypt_key: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + stp d8,d9,[sp,#-16]! // ABI spec says so + + lsr w9, w1, #5 // shr $5,%eax + add w9, w9, #5 // $5,%eax + str w9, [x2,#240] // mov %eax,240(%rdx) # AES_KEY->rounds = nbits/32+5; + + mov w3, #0 // mov $0,%ecx + mov x8, #0x30 // mov $0x30,%r8d + bl _vpaes_schedule_core + eor x0, x0, x0 + + ldp d8,d9,[sp],#16 + ldp x29,x30,[sp],#16 + ret +.size vpaes_set_encrypt_key,.-vpaes_set_encrypt_key + +.globl vpaes_set_decrypt_key +.hidden vpaes_set_decrypt_key +.type vpaes_set_decrypt_key,%function +.align 4 +vpaes_set_decrypt_key: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + stp d8,d9,[sp,#-16]! // ABI spec says so + + lsr w9, w1, #5 // shr $5,%eax + add w9, w9, #5 // $5,%eax + str w9, [x2,#240] // mov %eax,240(%rdx) # AES_KEY->rounds = nbits/32+5; + lsl w9, w9, #4 // shl $4,%eax + add x2, x2, #16 // lea 16(%rdx,%rax),%rdx + add x2, x2, x9 + + mov w3, #1 // mov $1,%ecx + lsr w8, w1, #1 // shr $1,%r8d + and x8, x8, #32 // and $32,%r8d + eor x8, x8, #32 // xor $32,%r8d # nbits==192?0:32 + bl _vpaes_schedule_core + + ldp d8,d9,[sp],#16 + ldp x29,x30,[sp],#16 + ret +.size vpaes_set_decrypt_key,.-vpaes_set_decrypt_key +.globl vpaes_cbc_encrypt +.hidden vpaes_cbc_encrypt +.type vpaes_cbc_encrypt,%function +.align 4 +vpaes_cbc_encrypt: + cbz x2, .Lcbc_abort + cmp w5, #0 // check direction + b.eq vpaes_cbc_decrypt + + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + + mov x17, x2 // reassign + mov x2, x3 // reassign + + ld1 {v0.16b}, [x4] // load ivec + bl _vpaes_encrypt_preheat + b .Lcbc_enc_loop + +.align 4 +.Lcbc_enc_loop: + ld1 {v7.16b}, [x0],#16 // load input + eor v7.16b, v7.16b, v0.16b // xor with ivec + bl _vpaes_encrypt_core + st1 {v0.16b}, [x1],#16 // save output + subs x17, x17, #16 + b.hi .Lcbc_enc_loop + + st1 {v0.16b}, [x4] // write ivec + + ldp x29,x30,[sp],#16 +.Lcbc_abort: + ret +.size vpaes_cbc_encrypt,.-vpaes_cbc_encrypt + +.type vpaes_cbc_decrypt,%function +.align 4 +vpaes_cbc_decrypt: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + stp d8,d9,[sp,#-16]! // ABI spec says so + stp d10,d11,[sp,#-16]! + stp d12,d13,[sp,#-16]! + stp d14,d15,[sp,#-16]! + + mov x17, x2 // reassign + mov x2, x3 // reassign + ld1 {v6.16b}, [x4] // load ivec + bl _vpaes_decrypt_preheat + tst x17, #16 + b.eq .Lcbc_dec_loop2x + + ld1 {v7.16b}, [x0], #16 // load input + bl _vpaes_decrypt_core + eor v0.16b, v0.16b, v6.16b // xor with ivec + orr v6.16b, v7.16b, v7.16b // next ivec value + st1 {v0.16b}, [x1], #16 + subs x17, x17, #16 + b.ls .Lcbc_dec_done + +.align 4 +.Lcbc_dec_loop2x: + ld1 {v14.16b,v15.16b}, [x0], #32 + bl _vpaes_decrypt_2x + eor v0.16b, v0.16b, v6.16b // xor with ivec + eor v1.16b, v1.16b, v14.16b + orr v6.16b, v15.16b, v15.16b + st1 {v0.16b,v1.16b}, [x1], #32 + subs x17, x17, #32 + b.hi .Lcbc_dec_loop2x + +.Lcbc_dec_done: + st1 {v6.16b}, [x4] + + ldp d14,d15,[sp],#16 + ldp d12,d13,[sp],#16 + ldp d10,d11,[sp],#16 + ldp d8,d9,[sp],#16 + ldp x29,x30,[sp],#16 + ret +.size vpaes_cbc_decrypt,.-vpaes_cbc_decrypt +.globl vpaes_ctr32_encrypt_blocks +.hidden vpaes_ctr32_encrypt_blocks +.type vpaes_ctr32_encrypt_blocks,%function +.align 4 +vpaes_ctr32_encrypt_blocks: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + stp d8,d9,[sp,#-16]! // ABI spec says so + stp d10,d11,[sp,#-16]! + stp d12,d13,[sp,#-16]! + stp d14,d15,[sp,#-16]! + + cbz x2, .Lctr32_done + + // Note, unlike the other functions, x2 here is measured in blocks, + // not bytes. + mov x17, x2 + mov x2, x3 + + // Load the IV and counter portion. + ldr w6, [x4, #12] + ld1 {v7.16b}, [x4] + + bl _vpaes_encrypt_preheat + tst x17, #1 + rev w6, w6 // The counter is big-endian. + b.eq .Lctr32_prep_loop + + // Handle one block so the remaining block count is even for + // _vpaes_encrypt_2x. + ld1 {v6.16b}, [x0], #16 // .Load input ahead of time + bl _vpaes_encrypt_core + eor v0.16b, v0.16b, v6.16b // XOR input and result + st1 {v0.16b}, [x1], #16 + subs x17, x17, #1 + // Update the counter. + add w6, w6, #1 + rev w7, w6 + mov v7.s[3], w7 + b.ls .Lctr32_done + +.Lctr32_prep_loop: + // _vpaes_encrypt_core takes its input from v7, while _vpaes_encrypt_2x + // uses v14 and v15. + mov v15.16b, v7.16b + mov v14.16b, v7.16b + add w6, w6, #1 + rev w7, w6 + mov v15.s[3], w7 + +.Lctr32_loop: + ld1 {v6.16b,v7.16b}, [x0], #32 // .Load input ahead of time + bl _vpaes_encrypt_2x + eor v0.16b, v0.16b, v6.16b // XOR input and result + eor v1.16b, v1.16b, v7.16b // XOR input and result (#2) + st1 {v0.16b,v1.16b}, [x1], #32 + subs x17, x17, #2 + // Update the counter. + add w7, w6, #1 + add w6, w6, #2 + rev w7, w7 + mov v14.s[3], w7 + rev w7, w6 + mov v15.s[3], w7 + b.hi .Lctr32_loop + +.Lctr32_done: + ldp d14,d15,[sp],#16 + ldp d12,d13,[sp],#16 + ldp d10,d11,[sp],#16 + ldp d8,d9,[sp],#16 + ldp x29,x30,[sp],#16 + ret +.size vpaes_ctr32_encrypt_blocks,.-vpaes_ctr32_encrypt_blocks +#endif +#endif // !OPENSSL_NO_ASM diff --git a/third_party/boringssl/kit/linux-aarch64/crypto/test/trampoline-armv8.S b/third_party/boringssl/kit/linux-aarch64/crypto/test/trampoline-armv8.S new file mode 100644 index 00000000..56c79c43 --- /dev/null +++ b/third_party/boringssl/kit/linux-aarch64/crypto/test/trampoline-armv8.S @@ -0,0 +1,686 @@ +// This file is generated from a similarly-named Perl script in the BoringSSL +// source tree. Do not edit by hand. + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) +#define OPENSSL_NO_ASM +#endif +#endif + +#if !defined(OPENSSL_NO_ASM) +#if defined(__aarch64__) +#if defined(BORINGSSL_PREFIX) +#include +#endif +.text + +// abi_test_trampoline loads callee-saved registers from |state|, calls |func| +// with |argv|, then saves the callee-saved registers into |state|. It returns +// the result of |func|. The |unwind| argument is unused. +// uint64_t abi_test_trampoline(void (*func)(...), CallerState *state, +// const uint64_t *argv, size_t argc, +// uint64_t unwind); +.type abi_test_trampoline, %function +.globl abi_test_trampoline +.hidden abi_test_trampoline +.align 4 +abi_test_trampoline: +.Labi_test_trampoline_begin: + // Stack layout (low to high addresses) + // x29,x30 (16 bytes) + // d8-d15 (64 bytes) + // x19-x28 (80 bytes) + // x1 (8 bytes) + // padding (8 bytes) + stp x29, x30, [sp, #-176]! + mov x29, sp + + // Saved callee-saved registers and |state|. + stp d8, d9, [sp, #16] + stp d10, d11, [sp, #32] + stp d12, d13, [sp, #48] + stp d14, d15, [sp, #64] + stp x19, x20, [sp, #80] + stp x21, x22, [sp, #96] + stp x23, x24, [sp, #112] + stp x25, x26, [sp, #128] + stp x27, x28, [sp, #144] + str x1, [sp, #160] + + // Load registers from |state|, with the exception of x29. x29 is the + // frame pointer and also callee-saved, but AAPCS64 allows platforms to + // mandate that x29 always point to a frame. iOS64 does so, which means + // we cannot fill x29 with entropy without violating ABI rules + // ourselves. x29 is tested separately below. + ldp d8, d9, [x1], #16 + ldp d10, d11, [x1], #16 + ldp d12, d13, [x1], #16 + ldp d14, d15, [x1], #16 + ldp x19, x20, [x1], #16 + ldp x21, x22, [x1], #16 + ldp x23, x24, [x1], #16 + ldp x25, x26, [x1], #16 + ldp x27, x28, [x1], #16 + + // Move parameters into temporary registers. + mov x9, x0 + mov x10, x2 + mov x11, x3 + + // Load parameters into registers. + cbz x11, .Largs_done + ldr x0, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x1, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x2, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x3, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x4, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x5, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x6, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x7, [x10], #8 + +.Largs_done: + blr x9 + + // Reload |state| and store registers. + ldr x1, [sp, #160] + stp d8, d9, [x1], #16 + stp d10, d11, [x1], #16 + stp d12, d13, [x1], #16 + stp d14, d15, [x1], #16 + stp x19, x20, [x1], #16 + stp x21, x22, [x1], #16 + stp x23, x24, [x1], #16 + stp x25, x26, [x1], #16 + stp x27, x28, [x1], #16 + + // |func| is required to preserve x29, the frame pointer. We cannot load + // random values into x29 (see comment above), so compare it against the + // expected value and zero the field of |state| if corrupted. + mov x9, sp + cmp x29, x9 + b.eq .Lx29_ok + str xzr, [x1] + +.Lx29_ok: + // Restore callee-saved registers. + ldp d8, d9, [sp, #16] + ldp d10, d11, [sp, #32] + ldp d12, d13, [sp, #48] + ldp d14, d15, [sp, #64] + ldp x19, x20, [sp, #80] + ldp x21, x22, [sp, #96] + ldp x23, x24, [sp, #112] + ldp x25, x26, [sp, #128] + ldp x27, x28, [sp, #144] + + ldp x29, x30, [sp], #176 + ret +.size abi_test_trampoline,.-abi_test_trampoline +.type abi_test_clobber_x0, %function +.globl abi_test_clobber_x0 +.hidden abi_test_clobber_x0 +.align 4 +abi_test_clobber_x0: + mov x0, xzr + ret +.size abi_test_clobber_x0,.-abi_test_clobber_x0 +.type abi_test_clobber_x1, %function +.globl abi_test_clobber_x1 +.hidden abi_test_clobber_x1 +.align 4 +abi_test_clobber_x1: + mov x1, xzr + ret +.size abi_test_clobber_x1,.-abi_test_clobber_x1 +.type abi_test_clobber_x2, %function +.globl abi_test_clobber_x2 +.hidden abi_test_clobber_x2 +.align 4 +abi_test_clobber_x2: + mov x2, xzr + ret +.size abi_test_clobber_x2,.-abi_test_clobber_x2 +.type abi_test_clobber_x3, %function +.globl abi_test_clobber_x3 +.hidden abi_test_clobber_x3 +.align 4 +abi_test_clobber_x3: + mov x3, xzr + ret +.size abi_test_clobber_x3,.-abi_test_clobber_x3 +.type abi_test_clobber_x4, %function +.globl abi_test_clobber_x4 +.hidden abi_test_clobber_x4 +.align 4 +abi_test_clobber_x4: + mov x4, xzr + ret +.size abi_test_clobber_x4,.-abi_test_clobber_x4 +.type abi_test_clobber_x5, %function +.globl abi_test_clobber_x5 +.hidden abi_test_clobber_x5 +.align 4 +abi_test_clobber_x5: + mov x5, xzr + ret +.size abi_test_clobber_x5,.-abi_test_clobber_x5 +.type abi_test_clobber_x6, %function +.globl abi_test_clobber_x6 +.hidden abi_test_clobber_x6 +.align 4 +abi_test_clobber_x6: + mov x6, xzr + ret +.size abi_test_clobber_x6,.-abi_test_clobber_x6 +.type abi_test_clobber_x7, %function +.globl abi_test_clobber_x7 +.hidden abi_test_clobber_x7 +.align 4 +abi_test_clobber_x7: + mov x7, xzr + ret +.size abi_test_clobber_x7,.-abi_test_clobber_x7 +.type abi_test_clobber_x8, %function +.globl abi_test_clobber_x8 +.hidden abi_test_clobber_x8 +.align 4 +abi_test_clobber_x8: + mov x8, xzr + ret +.size abi_test_clobber_x8,.-abi_test_clobber_x8 +.type abi_test_clobber_x9, %function +.globl abi_test_clobber_x9 +.hidden abi_test_clobber_x9 +.align 4 +abi_test_clobber_x9: + mov x9, xzr + ret +.size abi_test_clobber_x9,.-abi_test_clobber_x9 +.type abi_test_clobber_x10, %function +.globl abi_test_clobber_x10 +.hidden abi_test_clobber_x10 +.align 4 +abi_test_clobber_x10: + mov x10, xzr + ret +.size abi_test_clobber_x10,.-abi_test_clobber_x10 +.type abi_test_clobber_x11, %function +.globl abi_test_clobber_x11 +.hidden abi_test_clobber_x11 +.align 4 +abi_test_clobber_x11: + mov x11, xzr + ret +.size abi_test_clobber_x11,.-abi_test_clobber_x11 +.type abi_test_clobber_x12, %function +.globl abi_test_clobber_x12 +.hidden abi_test_clobber_x12 +.align 4 +abi_test_clobber_x12: + mov x12, xzr + ret +.size abi_test_clobber_x12,.-abi_test_clobber_x12 +.type abi_test_clobber_x13, %function +.globl abi_test_clobber_x13 +.hidden abi_test_clobber_x13 +.align 4 +abi_test_clobber_x13: + mov x13, xzr + ret +.size abi_test_clobber_x13,.-abi_test_clobber_x13 +.type abi_test_clobber_x14, %function +.globl abi_test_clobber_x14 +.hidden abi_test_clobber_x14 +.align 4 +abi_test_clobber_x14: + mov x14, xzr + ret +.size abi_test_clobber_x14,.-abi_test_clobber_x14 +.type abi_test_clobber_x15, %function +.globl abi_test_clobber_x15 +.hidden abi_test_clobber_x15 +.align 4 +abi_test_clobber_x15: + mov x15, xzr + ret +.size abi_test_clobber_x15,.-abi_test_clobber_x15 +.type abi_test_clobber_x16, %function +.globl abi_test_clobber_x16 +.hidden abi_test_clobber_x16 +.align 4 +abi_test_clobber_x16: + mov x16, xzr + ret +.size abi_test_clobber_x16,.-abi_test_clobber_x16 +.type abi_test_clobber_x17, %function +.globl abi_test_clobber_x17 +.hidden abi_test_clobber_x17 +.align 4 +abi_test_clobber_x17: + mov x17, xzr + ret +.size abi_test_clobber_x17,.-abi_test_clobber_x17 +.type abi_test_clobber_x19, %function +.globl abi_test_clobber_x19 +.hidden abi_test_clobber_x19 +.align 4 +abi_test_clobber_x19: + mov x19, xzr + ret +.size abi_test_clobber_x19,.-abi_test_clobber_x19 +.type abi_test_clobber_x20, %function +.globl abi_test_clobber_x20 +.hidden abi_test_clobber_x20 +.align 4 +abi_test_clobber_x20: + mov x20, xzr + ret +.size abi_test_clobber_x20,.-abi_test_clobber_x20 +.type abi_test_clobber_x21, %function +.globl abi_test_clobber_x21 +.hidden abi_test_clobber_x21 +.align 4 +abi_test_clobber_x21: + mov x21, xzr + ret +.size abi_test_clobber_x21,.-abi_test_clobber_x21 +.type abi_test_clobber_x22, %function +.globl abi_test_clobber_x22 +.hidden abi_test_clobber_x22 +.align 4 +abi_test_clobber_x22: + mov x22, xzr + ret +.size abi_test_clobber_x22,.-abi_test_clobber_x22 +.type abi_test_clobber_x23, %function +.globl abi_test_clobber_x23 +.hidden abi_test_clobber_x23 +.align 4 +abi_test_clobber_x23: + mov x23, xzr + ret +.size abi_test_clobber_x23,.-abi_test_clobber_x23 +.type abi_test_clobber_x24, %function +.globl abi_test_clobber_x24 +.hidden abi_test_clobber_x24 +.align 4 +abi_test_clobber_x24: + mov x24, xzr + ret +.size abi_test_clobber_x24,.-abi_test_clobber_x24 +.type abi_test_clobber_x25, %function +.globl abi_test_clobber_x25 +.hidden abi_test_clobber_x25 +.align 4 +abi_test_clobber_x25: + mov x25, xzr + ret +.size abi_test_clobber_x25,.-abi_test_clobber_x25 +.type abi_test_clobber_x26, %function +.globl abi_test_clobber_x26 +.hidden abi_test_clobber_x26 +.align 4 +abi_test_clobber_x26: + mov x26, xzr + ret +.size abi_test_clobber_x26,.-abi_test_clobber_x26 +.type abi_test_clobber_x27, %function +.globl abi_test_clobber_x27 +.hidden abi_test_clobber_x27 +.align 4 +abi_test_clobber_x27: + mov x27, xzr + ret +.size abi_test_clobber_x27,.-abi_test_clobber_x27 +.type abi_test_clobber_x28, %function +.globl abi_test_clobber_x28 +.hidden abi_test_clobber_x28 +.align 4 +abi_test_clobber_x28: + mov x28, xzr + ret +.size abi_test_clobber_x28,.-abi_test_clobber_x28 +.type abi_test_clobber_x29, %function +.globl abi_test_clobber_x29 +.hidden abi_test_clobber_x29 +.align 4 +abi_test_clobber_x29: + mov x29, xzr + ret +.size abi_test_clobber_x29,.-abi_test_clobber_x29 +.type abi_test_clobber_d0, %function +.globl abi_test_clobber_d0 +.hidden abi_test_clobber_d0 +.align 4 +abi_test_clobber_d0: + fmov d0, xzr + ret +.size abi_test_clobber_d0,.-abi_test_clobber_d0 +.type abi_test_clobber_d1, %function +.globl abi_test_clobber_d1 +.hidden abi_test_clobber_d1 +.align 4 +abi_test_clobber_d1: + fmov d1, xzr + ret +.size abi_test_clobber_d1,.-abi_test_clobber_d1 +.type abi_test_clobber_d2, %function +.globl abi_test_clobber_d2 +.hidden abi_test_clobber_d2 +.align 4 +abi_test_clobber_d2: + fmov d2, xzr + ret +.size abi_test_clobber_d2,.-abi_test_clobber_d2 +.type abi_test_clobber_d3, %function +.globl abi_test_clobber_d3 +.hidden abi_test_clobber_d3 +.align 4 +abi_test_clobber_d3: + fmov d3, xzr + ret +.size abi_test_clobber_d3,.-abi_test_clobber_d3 +.type abi_test_clobber_d4, %function +.globl abi_test_clobber_d4 +.hidden abi_test_clobber_d4 +.align 4 +abi_test_clobber_d4: + fmov d4, xzr + ret +.size abi_test_clobber_d4,.-abi_test_clobber_d4 +.type abi_test_clobber_d5, %function +.globl abi_test_clobber_d5 +.hidden abi_test_clobber_d5 +.align 4 +abi_test_clobber_d5: + fmov d5, xzr + ret +.size abi_test_clobber_d5,.-abi_test_clobber_d5 +.type abi_test_clobber_d6, %function +.globl abi_test_clobber_d6 +.hidden abi_test_clobber_d6 +.align 4 +abi_test_clobber_d6: + fmov d6, xzr + ret +.size abi_test_clobber_d6,.-abi_test_clobber_d6 +.type abi_test_clobber_d7, %function +.globl abi_test_clobber_d7 +.hidden abi_test_clobber_d7 +.align 4 +abi_test_clobber_d7: + fmov d7, xzr + ret +.size abi_test_clobber_d7,.-abi_test_clobber_d7 +.type abi_test_clobber_d8, %function +.globl abi_test_clobber_d8 +.hidden abi_test_clobber_d8 +.align 4 +abi_test_clobber_d8: + fmov d8, xzr + ret +.size abi_test_clobber_d8,.-abi_test_clobber_d8 +.type abi_test_clobber_d9, %function +.globl abi_test_clobber_d9 +.hidden abi_test_clobber_d9 +.align 4 +abi_test_clobber_d9: + fmov d9, xzr + ret +.size abi_test_clobber_d9,.-abi_test_clobber_d9 +.type abi_test_clobber_d10, %function +.globl abi_test_clobber_d10 +.hidden abi_test_clobber_d10 +.align 4 +abi_test_clobber_d10: + fmov d10, xzr + ret +.size abi_test_clobber_d10,.-abi_test_clobber_d10 +.type abi_test_clobber_d11, %function +.globl abi_test_clobber_d11 +.hidden abi_test_clobber_d11 +.align 4 +abi_test_clobber_d11: + fmov d11, xzr + ret +.size abi_test_clobber_d11,.-abi_test_clobber_d11 +.type abi_test_clobber_d12, %function +.globl abi_test_clobber_d12 +.hidden abi_test_clobber_d12 +.align 4 +abi_test_clobber_d12: + fmov d12, xzr + ret +.size abi_test_clobber_d12,.-abi_test_clobber_d12 +.type abi_test_clobber_d13, %function +.globl abi_test_clobber_d13 +.hidden abi_test_clobber_d13 +.align 4 +abi_test_clobber_d13: + fmov d13, xzr + ret +.size abi_test_clobber_d13,.-abi_test_clobber_d13 +.type abi_test_clobber_d14, %function +.globl abi_test_clobber_d14 +.hidden abi_test_clobber_d14 +.align 4 +abi_test_clobber_d14: + fmov d14, xzr + ret +.size abi_test_clobber_d14,.-abi_test_clobber_d14 +.type abi_test_clobber_d15, %function +.globl abi_test_clobber_d15 +.hidden abi_test_clobber_d15 +.align 4 +abi_test_clobber_d15: + fmov d15, xzr + ret +.size abi_test_clobber_d15,.-abi_test_clobber_d15 +.type abi_test_clobber_d16, %function +.globl abi_test_clobber_d16 +.hidden abi_test_clobber_d16 +.align 4 +abi_test_clobber_d16: + fmov d16, xzr + ret +.size abi_test_clobber_d16,.-abi_test_clobber_d16 +.type abi_test_clobber_d17, %function +.globl abi_test_clobber_d17 +.hidden abi_test_clobber_d17 +.align 4 +abi_test_clobber_d17: + fmov d17, xzr + ret +.size abi_test_clobber_d17,.-abi_test_clobber_d17 +.type abi_test_clobber_d18, %function +.globl abi_test_clobber_d18 +.hidden abi_test_clobber_d18 +.align 4 +abi_test_clobber_d18: + fmov d18, xzr + ret +.size abi_test_clobber_d18,.-abi_test_clobber_d18 +.type abi_test_clobber_d19, %function +.globl abi_test_clobber_d19 +.hidden abi_test_clobber_d19 +.align 4 +abi_test_clobber_d19: + fmov d19, xzr + ret +.size abi_test_clobber_d19,.-abi_test_clobber_d19 +.type abi_test_clobber_d20, %function +.globl abi_test_clobber_d20 +.hidden abi_test_clobber_d20 +.align 4 +abi_test_clobber_d20: + fmov d20, xzr + ret +.size abi_test_clobber_d20,.-abi_test_clobber_d20 +.type abi_test_clobber_d21, %function +.globl abi_test_clobber_d21 +.hidden abi_test_clobber_d21 +.align 4 +abi_test_clobber_d21: + fmov d21, xzr + ret +.size abi_test_clobber_d21,.-abi_test_clobber_d21 +.type abi_test_clobber_d22, %function +.globl abi_test_clobber_d22 +.hidden abi_test_clobber_d22 +.align 4 +abi_test_clobber_d22: + fmov d22, xzr + ret +.size abi_test_clobber_d22,.-abi_test_clobber_d22 +.type abi_test_clobber_d23, %function +.globl abi_test_clobber_d23 +.hidden abi_test_clobber_d23 +.align 4 +abi_test_clobber_d23: + fmov d23, xzr + ret +.size abi_test_clobber_d23,.-abi_test_clobber_d23 +.type abi_test_clobber_d24, %function +.globl abi_test_clobber_d24 +.hidden abi_test_clobber_d24 +.align 4 +abi_test_clobber_d24: + fmov d24, xzr + ret +.size abi_test_clobber_d24,.-abi_test_clobber_d24 +.type abi_test_clobber_d25, %function +.globl abi_test_clobber_d25 +.hidden abi_test_clobber_d25 +.align 4 +abi_test_clobber_d25: + fmov d25, xzr + ret +.size abi_test_clobber_d25,.-abi_test_clobber_d25 +.type abi_test_clobber_d26, %function +.globl abi_test_clobber_d26 +.hidden abi_test_clobber_d26 +.align 4 +abi_test_clobber_d26: + fmov d26, xzr + ret +.size abi_test_clobber_d26,.-abi_test_clobber_d26 +.type abi_test_clobber_d27, %function +.globl abi_test_clobber_d27 +.hidden abi_test_clobber_d27 +.align 4 +abi_test_clobber_d27: + fmov d27, xzr + ret +.size abi_test_clobber_d27,.-abi_test_clobber_d27 +.type abi_test_clobber_d28, %function +.globl abi_test_clobber_d28 +.hidden abi_test_clobber_d28 +.align 4 +abi_test_clobber_d28: + fmov d28, xzr + ret +.size abi_test_clobber_d28,.-abi_test_clobber_d28 +.type abi_test_clobber_d29, %function +.globl abi_test_clobber_d29 +.hidden abi_test_clobber_d29 +.align 4 +abi_test_clobber_d29: + fmov d29, xzr + ret +.size abi_test_clobber_d29,.-abi_test_clobber_d29 +.type abi_test_clobber_d30, %function +.globl abi_test_clobber_d30 +.hidden abi_test_clobber_d30 +.align 4 +abi_test_clobber_d30: + fmov d30, xzr + ret +.size abi_test_clobber_d30,.-abi_test_clobber_d30 +.type abi_test_clobber_d31, %function +.globl abi_test_clobber_d31 +.hidden abi_test_clobber_d31 +.align 4 +abi_test_clobber_d31: + fmov d31, xzr + ret +.size abi_test_clobber_d31,.-abi_test_clobber_d31 +.type abi_test_clobber_v8_upper, %function +.globl abi_test_clobber_v8_upper +.hidden abi_test_clobber_v8_upper +.align 4 +abi_test_clobber_v8_upper: + fmov v8.d[1], xzr + ret +.size abi_test_clobber_v8_upper,.-abi_test_clobber_v8_upper +.type abi_test_clobber_v9_upper, %function +.globl abi_test_clobber_v9_upper +.hidden abi_test_clobber_v9_upper +.align 4 +abi_test_clobber_v9_upper: + fmov v9.d[1], xzr + ret +.size abi_test_clobber_v9_upper,.-abi_test_clobber_v9_upper +.type abi_test_clobber_v10_upper, %function +.globl abi_test_clobber_v10_upper +.hidden abi_test_clobber_v10_upper +.align 4 +abi_test_clobber_v10_upper: + fmov v10.d[1], xzr + ret +.size abi_test_clobber_v10_upper,.-abi_test_clobber_v10_upper +.type abi_test_clobber_v11_upper, %function +.globl abi_test_clobber_v11_upper +.hidden abi_test_clobber_v11_upper +.align 4 +abi_test_clobber_v11_upper: + fmov v11.d[1], xzr + ret +.size abi_test_clobber_v11_upper,.-abi_test_clobber_v11_upper +.type abi_test_clobber_v12_upper, %function +.globl abi_test_clobber_v12_upper +.hidden abi_test_clobber_v12_upper +.align 4 +abi_test_clobber_v12_upper: + fmov v12.d[1], xzr + ret +.size abi_test_clobber_v12_upper,.-abi_test_clobber_v12_upper +.type abi_test_clobber_v13_upper, %function +.globl abi_test_clobber_v13_upper +.hidden abi_test_clobber_v13_upper +.align 4 +abi_test_clobber_v13_upper: + fmov v13.d[1], xzr + ret +.size abi_test_clobber_v13_upper,.-abi_test_clobber_v13_upper +.type abi_test_clobber_v14_upper, %function +.globl abi_test_clobber_v14_upper +.hidden abi_test_clobber_v14_upper +.align 4 +abi_test_clobber_v14_upper: + fmov v14.d[1], xzr + ret +.size abi_test_clobber_v14_upper,.-abi_test_clobber_v14_upper +.type abi_test_clobber_v15_upper, %function +.globl abi_test_clobber_v15_upper +.hidden abi_test_clobber_v15_upper +.align 4 +abi_test_clobber_v15_upper: + fmov v15.d[1], xzr + ret +.size abi_test_clobber_v15_upper,.-abi_test_clobber_v15_upper +#endif +#endif // !OPENSSL_NO_ASM diff --git a/third_party/boringssl/kit/linux-aarch64/crypto/third_party/sike/asm/fp-armv8.S b/third_party/boringssl/kit/linux-aarch64/crypto/third_party/sike/asm/fp-armv8.S new file mode 100644 index 00000000..f2245c15 --- /dev/null +++ b/third_party/boringssl/kit/linux-aarch64/crypto/third_party/sike/asm/fp-armv8.S @@ -0,0 +1,1195 @@ +// This file is generated from a similarly-named Perl script in the BoringSSL +// source tree. Do not edit by hand. + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) +#define OPENSSL_NO_ASM +#endif +#endif + +#if !defined(OPENSSL_NO_ASM) +#if defined(__aarch64__) +#if defined(BORINGSSL_PREFIX) +#include +#endif +.section .rodata + +.Lp503p1_nz_s8: +.quad 0x085BDA2211E7A0AC, 0x9BF6C87B7E7DAF13 +.quad 0x45C6BDDA77A4D01B, 0x4066F541811E1E60 + +.Lp503x2: +.quad 0xFFFFFFFFFFFFFFFE, 0xFFFFFFFFFFFFFFFF +.quad 0x57FFFFFFFFFFFFFF, 0x2610B7B44423CF41 +.quad 0x3737ED90F6FCFB5E, 0xC08B8D7BB4EF49A0 +.quad 0x0080CDEA83023C3C + +.text +.globl sike_mpmul +.hidden sike_mpmul +.align 4 +sike_mpmul: + stp x29, x30, [sp,#-96]! + add x29, sp, #0 + stp x19, x20, [sp,#16] + stp x21, x22, [sp,#32] + stp x23, x24, [sp,#48] + stp x25, x26, [sp,#64] + stp x27, x28, [sp,#80] + + ldp x3, x4, [x0] + ldp x5, x6, [x0,#16] + ldp x7, x8, [x0,#32] + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + ldp x15, x16, [x1,#32] + ldp x17, x19, [x1,#48] + + // x3-x7 <- AH + AL, x7 <- carry + adds x3, x3, x7 + adcs x4, x4, x8 + adcs x5, x5, x9 + adcs x6, x6, x10 + adc x7, xzr, xzr + + // x11-x14 <- BH + BL, x8 <- carry + adds x11, x11, x15 + adcs x12, x12, x16 + adcs x13, x13, x17 + adcs x14, x14, x19 + adc x8, xzr, xzr + + // x9 <- combined carry + and x9, x7, x8 + // x7-x8 <- mask + sub x7, xzr, x7 + sub x8, xzr, x8 + + + // x15-x19 <- masked (BH + BL) + and x15, x11, x7 + and x16, x12, x7 + and x17, x13, x7 + and x19, x14, x7 + + // x20-x23 <- masked (AH + AL) + and x20, x3, x8 + and x21, x4, x8 + and x22, x5, x8 + and x23, x6, x8 + + // x15-x19, x7 <- masked (AH+AL) + masked (BH+BL), step 1 + adds x15, x15, x20 + adcs x16, x16, x21 + adcs x17, x17, x22 + adcs x19, x19, x23 + adc x7, x9, xzr + + // x8-x10,x20-x24 <- (AH+AL) x (BH+BL), low part + stp x3, x4, [x2,#0] + // A0-A1 <- AH + AL, T0 <- mask + adds x3, x3, x5 + adcs x4, x4, x6 + adc x25, xzr, xzr + + // C6, T1 <- BH + BL, C7 <- mask + adds x23, x11, x13 + adcs x26, x12, x14 + adc x24, xzr, xzr + + // C0-C1 <- masked (BH + BL) + sub x10, xzr, x25 + sub x20, xzr, x24 + and x8, x23, x10 + and x9, x26, x10 + + // C4-C5 <- masked (AH + AL), T0 <- combined carry + and x21, x3, x20 + and x22, x4, x20 + mul x10, x3, x23 + mul x20, x3, x26 + and x25, x25, x24 + + // C0-C1, T0 <- (AH+AL) x (BH+BL), part 1 + adds x8, x21, x8 + umulh x21, x3, x26 + adcs x9, x22, x9 + umulh x22, x3, x23 + adc x25, x25, xzr + + // C2-C5 <- (AH+AL) x (BH+BL), low part + mul x3, x4, x23 + umulh x23, x4, x23 + adds x20, x20, x22 + adc x21, x21, xzr + + mul x24, x4, x26 + umulh x26, x4, x26 + adds x20, x20, x3 + adcs x21, x21, x23 + adc x22, xzr, xzr + + adds x21, x21, x24 + adc x22, x22, x26 + + ldp x3, x4, [x2,#0] + + // C2-C5, T0 <- (AH+AL) x (BH+BL), final part + adds x21, x8, x21 + umulh x24, x3, x11 + umulh x26, x3, x12 + adcs x22, x9, x22 + mul x8, x3, x11 + mul x9, x3, x12 + adc x25, x25, xzr + + // C0-C1, T1, C7 <- AL x BL + mul x3, x4, x11 + umulh x11, x4, x11 + adds x9, x9, x24 + adc x26, x26, xzr + + mul x23, x4, x12 + umulh x12, x4, x12 + adds x9, x9, x3 + adcs x26, x26, x11 + adc x24, xzr, xzr + + adds x26, x26, x23 + adc x24, x24, x12 + + + // C2-C5, T0 <- (AH+AL) x (BH+BL) - ALxBL + mul x3, x5, x13 + umulh x11, x5, x13 + subs x10, x10, x8 + sbcs x20, x20, x9 + sbcs x21, x21, x26 + mul x4, x5, x14 + umulh x23, x5, x14 + sbcs x22, x22, x24 + sbc x25, x25, xzr + + // A0, A1, C6, B0 <- AH x BH + mul x5, x6, x13 + umulh x13, x6, x13 + adds x4, x4, x11 + adc x23, x23, xzr + + mul x12, x6, x14 + umulh x14, x6, x14 + adds x4, x4, x5 + adcs x23, x23, x13 + adc x11, xzr, xzr + + adds x23, x23, x12 + adc x11, x11, x14 + + + // C2-C5, T0 <- (AH+AL) x (BH+BL) - ALxBL - AHxBH + subs x10, x10, x3 + sbcs x20, x20, x4 + sbcs x21, x21, x23 + sbcs x22, x22, x11 + sbc x25, x25, xzr + + adds x10, x10, x26 + adcs x20, x20, x24 + adcs x21, x21, x3 + adcs x22, x22, x4 + adcs x23, x25, x23 + adc x24, x11, xzr + + + // x15-x19, x7 <- (AH+AL) x (BH+BL), final step + adds x15, x15, x21 + adcs x16, x16, x22 + adcs x17, x17, x23 + adcs x19, x19, x24 + adc x7, x7, xzr + + // Load AL + ldp x3, x4, [x0] + ldp x5, x6, [x0,#16] + // Load BL + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + + // Temporarily store x8,x9 in x2 + stp x8,x9, [x2,#0] + // x21-x28 <- AL x BL + // A0-A1 <- AH + AL, T0 <- mask + adds x3, x3, x5 + adcs x4, x4, x6 + adc x8, xzr, xzr + + // C6, T1 <- BH + BL, C7 <- mask + adds x27, x11, x13 + adcs x9, x12, x14 + adc x28, xzr, xzr + + // C0-C1 <- masked (BH + BL) + sub x23, xzr, x8 + sub x24, xzr, x28 + and x21, x27, x23 + and x22, x9, x23 + + // C4-C5 <- masked (AH + AL), T0 <- combined carry + and x25, x3, x24 + and x26, x4, x24 + mul x23, x3, x27 + mul x24, x3, x9 + and x8, x8, x28 + + // C0-C1, T0 <- (AH+AL) x (BH+BL), part 1 + adds x21, x25, x21 + umulh x25, x3, x9 + adcs x22, x26, x22 + umulh x26, x3, x27 + adc x8, x8, xzr + + // C2-C5 <- (AH+AL) x (BH+BL), low part + mul x3, x4, x27 + umulh x27, x4, x27 + adds x24, x24, x26 + adc x25, x25, xzr + + mul x28, x4, x9 + umulh x9, x4, x9 + adds x24, x24, x3 + adcs x25, x25, x27 + adc x26, xzr, xzr + + adds x25, x25, x28 + adc x26, x26, x9 + + ldp x3, x4, [x0,#0] + + // C2-C5, T0 <- (AH+AL) x (BH+BL), final part + adds x25, x21, x25 + umulh x28, x3, x11 + umulh x9, x3, x12 + adcs x26, x22, x26 + mul x21, x3, x11 + mul x22, x3, x12 + adc x8, x8, xzr + + // C0-C1, T1, C7 <- AL x BL + mul x3, x4, x11 + umulh x11, x4, x11 + adds x22, x22, x28 + adc x9, x9, xzr + + mul x27, x4, x12 + umulh x12, x4, x12 + adds x22, x22, x3 + adcs x9, x9, x11 + adc x28, xzr, xzr + + adds x9, x9, x27 + adc x28, x28, x12 + + + // C2-C5, T0 <- (AH+AL) x (BH+BL) - ALxBL + mul x3, x5, x13 + umulh x11, x5, x13 + subs x23, x23, x21 + sbcs x24, x24, x22 + sbcs x25, x25, x9 + mul x4, x5, x14 + umulh x27, x5, x14 + sbcs x26, x26, x28 + sbc x8, x8, xzr + + // A0, A1, C6, B0 <- AH x BH + mul x5, x6, x13 + umulh x13, x6, x13 + adds x4, x4, x11 + adc x27, x27, xzr + + mul x12, x6, x14 + umulh x14, x6, x14 + adds x4, x4, x5 + adcs x27, x27, x13 + adc x11, xzr, xzr + + adds x27, x27, x12 + adc x11, x11, x14 + + + // C2-C5, T0 <- (AH+AL) x (BH+BL) - ALxBL - AHxBH + subs x23, x23, x3 + sbcs x24, x24, x4 + sbcs x25, x25, x27 + sbcs x26, x26, x11 + sbc x8, x8, xzr + + adds x23, x23, x9 + adcs x24, x24, x28 + adcs x25, x25, x3 + adcs x26, x26, x4 + adcs x27, x8, x27 + adc x28, x11, xzr + + // Restore x8,x9 + ldp x8,x9, [x2,#0] + + // x8-x10,x20,x15-x17,x19 <- maskd (AH+AL) x (BH+BL) - ALxBL + subs x8, x8, x21 + sbcs x9, x9, x22 + sbcs x10, x10, x23 + sbcs x20, x20, x24 + sbcs x15, x15, x25 + sbcs x16, x16, x26 + sbcs x17, x17, x27 + sbcs x19, x19, x28 + sbc x7, x7, xzr + + // Store ALxBL, low + stp x21, x22, [x2] + stp x23, x24, [x2,#16] + + // Load AH + ldp x3, x4, [x0,#32] + ldp x5, x6, [x0,#48] + // Load BH + ldp x11, x12, [x1,#32] + ldp x13, x14, [x1,#48] + + adds x8, x8, x25 + adcs x9, x9, x26 + adcs x10, x10, x27 + adcs x20, x20, x28 + adc x1, xzr, xzr + + add x0, x0, #32 + // Temporarily store x8,x9 in x2 + stp x8,x9, [x2,#32] + // x21-x28 <- AH x BH + // A0-A1 <- AH + AL, T0 <- mask + adds x3, x3, x5 + adcs x4, x4, x6 + adc x8, xzr, xzr + + // C6, T1 <- BH + BL, C7 <- mask + adds x27, x11, x13 + adcs x9, x12, x14 + adc x28, xzr, xzr + + // C0-C1 <- masked (BH + BL) + sub x23, xzr, x8 + sub x24, xzr, x28 + and x21, x27, x23 + and x22, x9, x23 + + // C4-C5 <- masked (AH + AL), T0 <- combined carry + and x25, x3, x24 + and x26, x4, x24 + mul x23, x3, x27 + mul x24, x3, x9 + and x8, x8, x28 + + // C0-C1, T0 <- (AH+AL) x (BH+BL), part 1 + adds x21, x25, x21 + umulh x25, x3, x9 + adcs x22, x26, x22 + umulh x26, x3, x27 + adc x8, x8, xzr + + // C2-C5 <- (AH+AL) x (BH+BL), low part + mul x3, x4, x27 + umulh x27, x4, x27 + adds x24, x24, x26 + adc x25, x25, xzr + + mul x28, x4, x9 + umulh x9, x4, x9 + adds x24, x24, x3 + adcs x25, x25, x27 + adc x26, xzr, xzr + + adds x25, x25, x28 + adc x26, x26, x9 + + ldp x3, x4, [x0,#0] + + // C2-C5, T0 <- (AH+AL) x (BH+BL), final part + adds x25, x21, x25 + umulh x28, x3, x11 + umulh x9, x3, x12 + adcs x26, x22, x26 + mul x21, x3, x11 + mul x22, x3, x12 + adc x8, x8, xzr + + // C0-C1, T1, C7 <- AL x BL + mul x3, x4, x11 + umulh x11, x4, x11 + adds x22, x22, x28 + adc x9, x9, xzr + + mul x27, x4, x12 + umulh x12, x4, x12 + adds x22, x22, x3 + adcs x9, x9, x11 + adc x28, xzr, xzr + + adds x9, x9, x27 + adc x28, x28, x12 + + + // C2-C5, T0 <- (AH+AL) x (BH+BL) - ALxBL + mul x3, x5, x13 + umulh x11, x5, x13 + subs x23, x23, x21 + sbcs x24, x24, x22 + sbcs x25, x25, x9 + mul x4, x5, x14 + umulh x27, x5, x14 + sbcs x26, x26, x28 + sbc x8, x8, xzr + + // A0, A1, C6, B0 <- AH x BH + mul x5, x6, x13 + umulh x13, x6, x13 + adds x4, x4, x11 + adc x27, x27, xzr + + mul x12, x6, x14 + umulh x14, x6, x14 + adds x4, x4, x5 + adcs x27, x27, x13 + adc x11, xzr, xzr + + adds x27, x27, x12 + adc x11, x11, x14 + + + // C2-C5, T0 <- (AH+AL) x (BH+BL) - ALxBL - AHxBH + subs x23, x23, x3 + sbcs x24, x24, x4 + sbcs x25, x25, x27 + sbcs x26, x26, x11 + sbc x8, x8, xzr + + adds x23, x23, x9 + adcs x24, x24, x28 + adcs x25, x25, x3 + adcs x26, x26, x4 + adcs x27, x8, x27 + adc x28, x11, xzr + + // Restore x8,x9 + ldp x8,x9, [x2,#32] + + neg x1, x1 + + // x8-x10,x20,x15-x17,x19 <- (AH+AL) x (BH+BL) - ALxBL - AHxBH + subs x8, x8, x21 + sbcs x9, x9, x22 + sbcs x10, x10, x23 + sbcs x20, x20, x24 + sbcs x15, x15, x25 + sbcs x16, x16, x26 + sbcs x17, x17, x27 + sbcs x19, x19, x28 + sbc x7, x7, xzr + + // Store (AH+AL) x (BH+BL) - ALxBL - AHxBH, low + stp x8, x9, [x2,#32] + stp x10, x20, [x2,#48] + + adds x1, x1, #1 + adcs x15, x15, x21 + adcs x16, x16, x22 + adcs x17, x17, x23 + adcs x19, x19, x24 + adcs x25, x7, x25 + adcs x26, x26, xzr + adcs x27, x27, xzr + adc x28, x28, xzr + + stp x15, x16, [x2,#64] + stp x17, x19, [x2,#80] + stp x25, x26, [x2,#96] + stp x27, x28, [x2,#112] + + ldp x19, x20, [x29,#16] + ldp x21, x22, [x29,#32] + ldp x23, x24, [x29,#48] + ldp x25, x26, [x29,#64] + ldp x27, x28, [x29,#80] + ldp x29, x30, [sp],#96 + ret +.globl sike_fprdc +.hidden sike_fprdc +.align 4 +sike_fprdc: + stp x29, x30, [sp, #-112]! + add x29, sp, #0 + stp x19, x20, [sp,#16] + stp x21, x22, [sp,#32] + stp x23, x24, [sp,#48] + stp x25, x26, [sp,#64] + stp x27, x28, [sp,#80] + str x1, [sp,#96] + + ldp x2, x3, [x0,#0] // a[0-1] + + // Load the prime constant + adrp x23, .Lp503p1_nz_s8 + add x23, x23, :lo12:.Lp503p1_nz_s8 + ldp x24, x25, [x23, #0] + ldp x26, x27, [x23, #16] + + // a[0-1] x .Lp503p1_nz_s8 --> result: x4:x9 + mul x4, x2, x24 // a[0] x .Lp503p1_nz_s8[0] + umulh x7, x2, x24 + mul x5, x2, x25 // a[0] x .Lp503p1_nz_s8[1] + umulh x6, x2, x25 + + mul x1, x3, x24 + umulh x10, x3, x24 + adds x5, x5, x7 + adc x6, x6, xzr + + mul x11, x2, x26 + umulh x19, x2, x26 + adds x5, x5, x1 + adcs x6, x6, x10 + adc x7, xzr, xzr + + mul x1, x3, x25 + umulh x10, x3, x25 + adds x6, x6, x11 + adcs x7, x7, x19 + adc x8, xzr, xzr + + mul x11, x2, x27 + umulh x19, x2, x27 + adds x6, x6, x1 + adcs x7, x7, x10 + adc x8, x8, xzr + + mul x1, x3, x26 + umulh x10, x3, x26 + adds x7, x7, x11 + adcs x8, x8, x19 + adc x9, xzr, xzr + + mul x11, x3, x27 + umulh x19, x3, x27 + adds x7, x7, x1 + adcs x8, x8, x10 + adc x9, x9, xzr + adds x8, x8, x11 + adc x9, x9, x19 + + + + ldp x2, x3, [x0,#16] // a[2] + ldp x12, x13, [x0,#32] + ldp x14, x15, [x0,#48] + + orr x10, xzr, x9, lsr #8 + lsl x9, x9, #56 + orr x9, x9, x8, lsr #8 + lsl x8, x8, #56 + orr x8, x8, x7, lsr #8 + lsl x7, x7, #56 + orr x7, x7, x6, lsr #8 + lsl x6, x6, #56 + orr x6, x6, x5, lsr #8 + lsl x5, x5, #56 + orr x5, x5, x4, lsr #8 + lsl x4, x4, #56 + + adds x3, x4, x3 // a[3] + adcs x12, x5, x12 // a[4] + adcs x13, x6, x13 + adcs x14, x7, x14 + adcs x15, x8, x15 + ldp x16, x17, [x0,#64] + ldp x28, x30, [x0,#80] + mul x4, x2, x24 // a[2] x .Lp503p1_nz_s8[0] + umulh x7, x2, x24 + adcs x16, x9, x16 + adcs x17, x10, x17 + adcs x28, xzr, x28 + adcs x30, xzr, x30 + ldp x20, x21, [x0,#96] + ldp x22, x23, [x0,#112] + mul x5, x2, x25 // a[2] x .Lp503p1_nz_s8[1] + umulh x6, x2, x25 + adcs x20, xzr, x20 + adcs x21, xzr, x21 + adcs x22, xzr, x22 + adc x23, xzr, x23 + + // a[2-3] x .Lp503p1_nz_s8 --> result: x4:x9 + mul x1, x3, x24 + umulh x10, x3, x24 + adds x5, x5, x7 + adc x6, x6, xzr + + mul x11, x2, x26 + umulh x19, x2, x26 + adds x5, x5, x1 + adcs x6, x6, x10 + adc x7, xzr, xzr + + mul x1, x3, x25 + umulh x10, x3, x25 + adds x6, x6, x11 + adcs x7, x7, x19 + adc x8, xzr, xzr + + mul x11, x2, x27 + umulh x19, x2, x27 + adds x6, x6, x1 + adcs x7, x7, x10 + adc x8, x8, xzr + + mul x1, x3, x26 + umulh x10, x3, x26 + adds x7, x7, x11 + adcs x8, x8, x19 + adc x9, xzr, xzr + + mul x11, x3, x27 + umulh x19, x3, x27 + adds x7, x7, x1 + adcs x8, x8, x10 + adc x9, x9, xzr + adds x8, x8, x11 + adc x9, x9, x19 + + + + orr x10, xzr, x9, lsr #8 + lsl x9, x9, #56 + orr x9, x9, x8, lsr #8 + lsl x8, x8, #56 + orr x8, x8, x7, lsr #8 + lsl x7, x7, #56 + orr x7, x7, x6, lsr #8 + lsl x6, x6, #56 + orr x6, x6, x5, lsr #8 + lsl x5, x5, #56 + orr x5, x5, x4, lsr #8 + lsl x4, x4, #56 + + adds x13, x4, x13 // a[5] + adcs x14, x5, x14 // a[6] + adcs x15, x6, x15 + adcs x16, x7, x16 + mul x4, x12, x24 // a[4] x .Lp503p1_nz_s8[0] + umulh x7, x12, x24 + adcs x17, x8, x17 + adcs x28, x9, x28 + adcs x30, x10, x30 + adcs x20, xzr, x20 + mul x5, x12, x25 // a[4] x .Lp503p1_nz_s8[1] + umulh x6, x12, x25 + adcs x21, xzr, x21 + adcs x22, xzr, x22 + adc x23, xzr, x23 + + // a[4-5] x .Lp503p1_nz_s8 --> result: x4:x9 + mul x1, x13, x24 + umulh x10, x13, x24 + adds x5, x5, x7 + adc x6, x6, xzr + + mul x11, x12, x26 + umulh x19, x12, x26 + adds x5, x5, x1 + adcs x6, x6, x10 + adc x7, xzr, xzr + + mul x1, x13, x25 + umulh x10, x13, x25 + adds x6, x6, x11 + adcs x7, x7, x19 + adc x8, xzr, xzr + + mul x11, x12, x27 + umulh x19, x12, x27 + adds x6, x6, x1 + adcs x7, x7, x10 + adc x8, x8, xzr + + mul x1, x13, x26 + umulh x10, x13, x26 + adds x7, x7, x11 + adcs x8, x8, x19 + adc x9, xzr, xzr + + mul x11, x13, x27 + umulh x19, x13, x27 + adds x7, x7, x1 + adcs x8, x8, x10 + adc x9, x9, xzr + adds x8, x8, x11 + adc x9, x9, x19 + + + + orr x10, xzr, x9, lsr #8 + lsl x9, x9, #56 + orr x9, x9, x8, lsr #8 + lsl x8, x8, #56 + orr x8, x8, x7, lsr #8 + lsl x7, x7, #56 + orr x7, x7, x6, lsr #8 + lsl x6, x6, #56 + orr x6, x6, x5, lsr #8 + lsl x5, x5, #56 + orr x5, x5, x4, lsr #8 + lsl x4, x4, #56 + + adds x15, x4, x15 // a[7] + adcs x16, x5, x16 // a[8] + adcs x17, x6, x17 + adcs x28, x7, x28 + mul x4, x14, x24 // a[6] x .Lp503p1_nz_s8[0] + umulh x7, x14, x24 + adcs x30, x8, x30 + adcs x20, x9, x20 + adcs x21, x10, x21 + mul x5, x14, x25 // a[6] x .Lp503p1_nz_s8[1] + umulh x6, x14, x25 + adcs x22, xzr, x22 + adc x23, xzr, x23 + + // a[6-7] x .Lp503p1_nz_s8 --> result: x4:x9 + mul x1, x15, x24 + umulh x10, x15, x24 + adds x5, x5, x7 + adc x6, x6, xzr + + mul x11, x14, x26 + umulh x19, x14, x26 + adds x5, x5, x1 + adcs x6, x6, x10 + adc x7, xzr, xzr + + mul x1, x15, x25 + umulh x10, x15, x25 + adds x6, x6, x11 + adcs x7, x7, x19 + adc x8, xzr, xzr + + mul x11, x14, x27 + umulh x19, x14, x27 + adds x6, x6, x1 + adcs x7, x7, x10 + adc x8, x8, xzr + + mul x1, x15, x26 + umulh x10, x15, x26 + adds x7, x7, x11 + adcs x8, x8, x19 + adc x9, xzr, xzr + + mul x11, x15, x27 + umulh x19, x15, x27 + adds x7, x7, x1 + adcs x8, x8, x10 + adc x9, x9, xzr + adds x8, x8, x11 + adc x9, x9, x19 + + + + orr x10, xzr, x9, lsr #8 + lsl x9, x9, #56 + orr x9, x9, x8, lsr #8 + lsl x8, x8, #56 + orr x8, x8, x7, lsr #8 + lsl x7, x7, #56 + orr x7, x7, x6, lsr #8 + lsl x6, x6, #56 + orr x6, x6, x5, lsr #8 + lsl x5, x5, #56 + orr x5, x5, x4, lsr #8 + lsl x4, x4, #56 + + adds x17, x4, x17 + adcs x28, x5, x28 + ldr x1, [sp,#96] + adcs x30, x6, x30 + adcs x20, x7, x20 + stp x16, x17, [x1,#0] // Final result + stp x28, x30, [x1,#16] + adcs x21, x8, x21 + adcs x22, x9, x22 + adc x23, x10, x23 + stp x20, x21, [x1,#32] + stp x22, x23, [x1,#48] + + ldp x19, x20, [x29,#16] + ldp x21, x22, [x29,#32] + ldp x23, x24, [x29,#48] + ldp x25, x26, [x29,#64] + ldp x27, x28, [x29,#80] + ldp x29, x30, [sp],#112 + ret + +.globl sike_fpadd +.hidden sike_fpadd +.align 4 +sike_fpadd: + stp x29,x30, [sp,#-16]! + add x29, sp, #0 + + ldp x3, x4, [x0,#0] + ldp x5, x6, [x0,#16] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + + // Add a + b + adds x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x13 + adcs x6, x6, x14 + ldp x7, x8, [x0,#32] + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#32] + ldp x13, x14, [x1,#48] + adcs x7, x7, x11 + adcs x8, x8, x12 + adcs x9, x9, x13 + adc x10, x10, x14 + + // Subtract 2xp503 + adrp x17, .Lp503x2 + add x17, x17, :lo12:.Lp503x2 + ldp x11, x12, [x17, #0] + ldp x13, x14, [x17, #16] + subs x3, x3, x11 + sbcs x4, x4, x12 + sbcs x5, x5, x12 + sbcs x6, x6, x13 + sbcs x7, x7, x14 + + ldp x15, x16, [x17, #32] + ldr x17, [x17, #48] + sbcs x8, x8, x15 + sbcs x9, x9, x16 + sbcs x10, x10, x17 + sbc x0, xzr, xzr // x0 can be reused now + + // Add 2xp503 anded with the mask in x0 + and x11, x11, x0 + and x12, x12, x0 + and x13, x13, x0 + and x14, x14, x0 + and x15, x15, x0 + and x16, x16, x0 + and x17, x17, x0 + + adds x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x12 + adcs x6, x6, x13 + adcs x7, x7, x14 + adcs x8, x8, x15 + adcs x9, x9, x16 + adc x10, x10, x17 + + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + + ldp x29, x30, [sp],#16 + ret + +.globl sike_fpsub +.hidden sike_fpsub +.align 4 +sike_fpsub: + stp x29, x30, [sp,#-16]! + add x29, sp, #0 + + ldp x3, x4, [x0,#0] + ldp x5, x6, [x0,#16] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + + // Subtract a - b + subs x3, x3, x11 + sbcs x4, x4, x12 + sbcs x5, x5, x13 + sbcs x6, x6, x14 + ldp x7, x8, [x0,#32] + ldp x11, x12, [x1,#32] + sbcs x7, x7, x11 + sbcs x8, x8, x12 + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#48] + sbcs x9, x9, x11 + sbcs x10, x10, x12 + sbc x17, xzr, xzr + + // Add 2xp503 anded with the mask in x17 + adrp x16, .Lp503x2 + add x16, x16, :lo12:.Lp503x2 + + // First half + ldp x11, x12, [x16, #0] + ldp x13, x14, [x16, #16] + and x11, x11, x17 + and x12, x12, x17 + and x13, x13, x17 + adds x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x12 + adcs x6, x6, x13 + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + + // Second half + ldp x11, x12, [x16, #32] + ldr x13, [x16, #48] + and x14, x14, x17 + and x11, x11, x17 + and x12, x12, x17 + and x13, x13, x17 + adcs x7, x7, x14 + adcs x8, x8, x11 + adcs x9, x9, x12 + adc x10, x10, x13 + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + + ldp x29, x30, [sp],#16 + ret +.globl sike_mpadd_asm +.hidden sike_mpadd_asm +.align 4 +sike_mpadd_asm: + stp x29, x30, [sp,#-16]! + add x29, sp, #0 + + ldp x3, x4, [x0,#0] + ldp x5, x6, [x0,#16] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + + adds x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x13 + adcs x6, x6, x14 + ldp x7, x8, [x0,#32] + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#32] + ldp x13, x14, [x1,#48] + adcs x7, x7, x11 + adcs x8, x8, x12 + adcs x9, x9, x13 + adc x10, x10, x14 + + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + + ldp x29, x30, [sp],#16 + ret +.globl sike_mpadd503x2_asm +.hidden sike_mpadd503x2_asm +.align 4 +sike_mpadd503x2_asm: + stp x29, x30, [sp,#-16]! + add x29, sp, #0 + + ldp x3, x4, [x0,#0] + ldp x5, x6, [x0,#16] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + adds x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x13 + adcs x6, x6, x14 + ldp x7, x8, [x0,#32] + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#32] + ldp x13, x14, [x1,#48] + adcs x7, x7, x11 + adcs x8, x8, x12 + adcs x9, x9, x13 + adcs x10, x10, x14 + + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + + ldp x3, x4, [x0,#64] + ldp x5, x6, [x0,#80] + ldp x11, x12, [x1,#64] + ldp x13, x14, [x1,#80] + adcs x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x13 + adcs x6, x6, x14 + ldp x7, x8, [x0,#96] + ldp x9, x10, [x0,#112] + ldp x11, x12, [x1,#96] + ldp x13, x14, [x1,#112] + adcs x7, x7, x11 + adcs x8, x8, x12 + adcs x9, x9, x13 + adc x10, x10, x14 + + stp x3, x4, [x2,#64] + stp x5, x6, [x2,#80] + stp x7, x8, [x2,#96] + stp x9, x10, [x2,#112] + + ldp x29, x30, [sp],#16 + ret +.globl sike_mpsubx2_asm +.hidden sike_mpsubx2_asm +.align 4 +sike_mpsubx2_asm: + stp x29, x30, [sp,#-16]! + add x29, sp, #0 + + ldp x3, x4, [x0,#0] + ldp x5, x6, [x0,#16] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + subs x3, x3, x11 + sbcs x4, x4, x12 + sbcs x5, x5, x13 + sbcs x6, x6, x14 + ldp x7, x8, [x0,#32] + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#32] + ldp x13, x14, [x1,#48] + sbcs x7, x7, x11 + sbcs x8, x8, x12 + sbcs x9, x9, x13 + sbcs x10, x10, x14 + + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + + ldp x3, x4, [x0,#64] + ldp x5, x6, [x0,#80] + ldp x11, x12, [x1,#64] + ldp x13, x14, [x1,#80] + sbcs x3, x3, x11 + sbcs x4, x4, x12 + sbcs x5, x5, x13 + sbcs x6, x6, x14 + ldp x7, x8, [x0,#96] + ldp x9, x10, [x0,#112] + ldp x11, x12, [x1,#96] + ldp x13, x14, [x1,#112] + sbcs x7, x7, x11 + sbcs x8, x8, x12 + sbcs x9, x9, x13 + sbcs x10, x10, x14 + sbc x0, xzr, xzr + + stp x3, x4, [x2,#64] + stp x5, x6, [x2,#80] + stp x7, x8, [x2,#96] + stp x9, x10, [x2,#112] + + ldp x29, x30, [sp],#16 + ret +.globl sike_mpdblsubx2_asm +.hidden sike_mpdblsubx2_asm +.align 4 +sike_mpdblsubx2_asm: + stp x29, x30, [sp, #-64]! + add x29, sp, #0 + + stp x20, x21, [sp, #16] + stp x22, x23, [sp, #32] + str x24, [sp, #48] + + ldp x3, x4, [x2,#0] + ldp x5, x6, [x2,#16] + ldp x7, x8, [x2,#32] + ldp x9, x10, [x2,#48] + ldp x11, x12, [x2,#64] + ldp x13, x14, [x2,#80] + ldp x15, x16, [x2,#96] + ldp x17, x24, [x2,#112] + + ldp x20, x21, [x0,#0] + ldp x22, x23, [x0,#16] + subs x3, x3, x20 + sbcs x4, x4, x21 + sbcs x5, x5, x22 + sbcs x6, x6, x23 + ldp x20, x21, [x0,#32] + ldp x22, x23, [x0,#48] + sbcs x7, x7, x20 + sbcs x8, x8, x21 + sbcs x9, x9, x22 + sbcs x10, x10, x23 + ldp x20, x21, [x0,#64] + ldp x22, x23, [x0,#80] + sbcs x11, x11, x20 + sbcs x12, x12, x21 + sbcs x13, x13, x22 + sbcs x14, x14, x23 + ldp x20, x21, [x0,#96] + ldp x22, x23, [x0,#112] + sbcs x15, x15, x20 + sbcs x16, x16, x21 + sbcs x17, x17, x22 + sbc x24, x24, x23 + + ldp x20, x21, [x1,#0] + ldp x22, x23, [x1,#16] + subs x3, x3, x20 + sbcs x4, x4, x21 + sbcs x5, x5, x22 + sbcs x6, x6, x23 + ldp x20, x21, [x1,#32] + ldp x22, x23, [x1,#48] + sbcs x7, x7, x20 + sbcs x8, x8, x21 + sbcs x9, x9, x22 + sbcs x10, x10, x23 + ldp x20, x21, [x1,#64] + ldp x22, x23, [x1,#80] + sbcs x11, x11, x20 + sbcs x12, x12, x21 + sbcs x13, x13, x22 + sbcs x14, x14, x23 + ldp x20, x21, [x1,#96] + ldp x22, x23, [x1,#112] + sbcs x15, x15, x20 + sbcs x16, x16, x21 + sbcs x17, x17, x22 + sbc x24, x24, x23 + + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + stp x11, x12, [x2,#64] + stp x13, x14, [x2,#80] + stp x15, x16, [x2,#96] + stp x17, x24, [x2,#112] + + ldp x20, x21, [x29,#16] + ldp x22, x23, [x29,#32] + ldr x24, [x29,#48] + + ldp x29, x30, [sp],#64 + ret +#endif +#endif // !OPENSSL_NO_ASM diff --git a/third_party/boringssl/kit/linux-arm/crypto/fipsmodule/bsaes-armv7.S b/third_party/boringssl/kit/linux-arm/crypto/fipsmodule/bsaes-armv7.S index 38a02902..0ad56bc7 100644 --- a/third_party/boringssl/kit/linux-arm/crypto/fipsmodule/bsaes-armv7.S +++ b/third_party/boringssl/kit/linux-arm/crypto/fipsmodule/bsaes-armv7.S @@ -1081,24 +1081,13 @@ _bsaes_key_convert: @ don't save last round key bx lr .size _bsaes_key_convert,.-_bsaes_key_convert - - - .globl bsaes_cbc_encrypt .hidden bsaes_cbc_encrypt .type bsaes_cbc_encrypt,%function .align 5 bsaes_cbc_encrypt: -#ifndef __KERNEL__ - cmp r2, #128 -#ifndef __thumb__ - blo AES_cbc_encrypt -#else - bhs 1f - b AES_cbc_encrypt -1: -#endif -#endif + @ In OpenSSL, this function had a fallback to aes_nohw_cbc_encrypt for + @ short inputs. We patch this out, using bsaes for all input sizes. @ it is up to the caller to make sure we are called with enc == 0 @@ -1196,10 +1185,7 @@ bsaes_cbc_encrypt: adds r2, r2, #8 beq .Lcbc_dec_done - vld1.8 {q0}, [r0]! @ load input - cmp r2, #2 - blo .Lcbc_dec_one - vld1.8 {q1}, [r0]! + @ Set up most parameters for the _bsaes_decrypt8 call. #ifndef BSAES_ASM_EXTENDED_KEY mov r4, sp @ pass the key #else @@ -1207,6 +1193,11 @@ bsaes_cbc_encrypt: #endif mov r5, r10 vstmia r9, {q15} @ put aside IV + + vld1.8 {q0}, [r0]! @ load input + cmp r2, #2 + blo .Lcbc_dec_one + vld1.8 {q1}, [r0]! beq .Lcbc_dec_two vld1.8 {q2}, [r0]! cmp r2, #4 @@ -1324,16 +1315,11 @@ bsaes_cbc_encrypt: .align 4 .Lcbc_dec_one: sub r0, r0, #0x10 - mov r10, r1 @ save original out pointer - mov r1, r9 @ use the iv scratch space as out buffer - mov r2, r3 - vmov q4,q15 @ just in case ensure that IV - vmov q5,q0 @ and input are preserved - bl AES_decrypt - vld1.8 {q0}, [r9] @ load result - veor q0, q0, q4 @ ^= IV - vmov q15, q5 @ q5 holds input - vst1.8 {q0}, [r10] @ write output + bl _bsaes_decrypt8 + vldmia r9, {q14} @ reload IV + vld1.8 {q15}, [r0]! @ reload input + veor q0, q0, q14 @ ^= IV + vst1.8 {q0}, [r1]! @ write output .Lcbc_dec_done: #ifndef BSAES_ASM_EXTENDED_KEY @@ -1351,15 +1337,13 @@ bsaes_cbc_encrypt: VFP_ABI_POP ldmia sp!, {r4,r5,r6,r7,r8,r9,r10, pc} .size bsaes_cbc_encrypt,.-bsaes_cbc_encrypt - .globl bsaes_ctr32_encrypt_blocks .hidden bsaes_ctr32_encrypt_blocks .type bsaes_ctr32_encrypt_blocks,%function .align 5 bsaes_ctr32_encrypt_blocks: - cmp r2, #8 @ use plain AES for - blo .Lctr_enc_short @ small sizes - + @ In OpenSSL, short inputs fall back to aes_nohw_* here. We patch this + @ out to retain a constant-time implementation. mov ip, sp stmdb sp!, {r4,r5,r6,r7,r8,r9,r10, lr} VFP_ABI_PUSH @@ -1535,1043 +1519,9 @@ bsaes_ctr32_encrypt_blocks: VFP_ABI_POP ldmia sp!, {r4,r5,r6,r7,r8,r9,r10, pc} @ return -.align 4 -.Lctr_enc_short: - ldr ip, [sp] @ ctr pointer is passed on stack - stmdb sp!, {r4,r5,r6,r7,r8, lr} - - mov r4, r0 @ copy arguments - mov r5, r1 - mov r6, r2 - mov r7, r3 - ldr r8, [ip, #12] @ load counter .LSW - vld1.8 {q1}, [ip] @ load whole counter value -#ifdef __ARMEL__ - rev r8, r8 -#endif - sub sp, sp, #0x10 - vst1.8 {q1}, [sp] @ copy counter value - sub sp, sp, #0x10 - -.Lctr_enc_short_loop: - add r0, sp, #0x10 @ input counter value - mov r1, sp @ output on the stack - mov r2, r7 @ key - - bl AES_encrypt - - vld1.8 {q0}, [r4]! @ load input - vld1.8 {q1}, [sp] @ load encrypted counter - add r8, r8, #1 -#ifdef __ARMEL__ - rev r0, r8 - str r0, [sp, #0x1c] @ next counter value -#else - str r8, [sp, #0x1c] @ next counter value -#endif - veor q0,q0,q1 - vst1.8 {q0}, [r5]! @ store output - subs r6, r6, #1 - bne .Lctr_enc_short_loop - - vmov.i32 q0, #0 - vmov.i32 q1, #0 - vstmia sp!, {q0,q1} - - ldmia sp!, {r4,r5,r6,r7,r8, pc} + @ OpenSSL contains aes_nohw_* fallback code here. We patch this + @ out to retain a constant-time implementation. .size bsaes_ctr32_encrypt_blocks,.-bsaes_ctr32_encrypt_blocks -.globl bsaes_xts_encrypt -.hidden bsaes_xts_encrypt -.type bsaes_xts_encrypt,%function -.align 4 -bsaes_xts_encrypt: - mov ip, sp - stmdb sp!, {r4,r5,r6,r7,r8,r9,r10, lr} @ 0x20 - VFP_ABI_PUSH - mov r6, sp @ future r3 - - mov r7, r0 - mov r8, r1 - mov r9, r2 - mov r10, r3 - - sub r0, sp, #0x10 @ 0x10 - bic r0, #0xf @ align at 16 bytes - mov sp, r0 - -#ifdef XTS_CHAIN_TWEAK - ldr r0, [ip] @ pointer to input tweak -#else - @ generate initial tweak - ldr r0, [ip, #4] @ iv[] - mov r1, sp - ldr r2, [ip, #0] @ key2 - bl AES_encrypt - mov r0,sp @ pointer to initial tweak -#endif - - ldr r1, [r10, #240] @ get # of rounds - mov r3, r6 -#ifndef BSAES_ASM_EXTENDED_KEY - @ allocate the key schedule on the stack - sub r12, sp, r1, lsl#7 @ 128 bytes per inner round key - @ add r12, #96 @ size of bit-sliced key schedule - sub r12, #48 @ place for tweak[9] - - @ populate the key schedule - mov r4, r10 @ pass key - mov r5, r1 @ pass # of rounds - mov sp, r12 - add r12, #0x90 @ pass key schedule - bl _bsaes_key_convert - veor q7, q7, q15 @ fix up last round key - vstmia r12, {q7} @ save last round key -#else - ldr r12, [r10, #244] - eors r12, #1 - beq 0f - - str r12, [r10, #244] - mov r4, r10 @ pass key - mov r5, r1 @ pass # of rounds - add r12, r10, #248 @ pass key schedule - bl _bsaes_key_convert - veor q7, q7, q15 @ fix up last round key - vstmia r12, {q7} - -.align 2 - sub sp, #0x90 @ place for tweak[9] -#endif - - vld1.8 {q8}, [r0] @ initial tweak - adr r2, .Lxts_magic - - subs r9, #0x80 - blo .Lxts_enc_short - b .Lxts_enc_loop - -.align 4 -.Lxts_enc_loop: - vldmia r2, {q5} @ load XTS magic - vshr.s64 q6, q8, #63 - mov r0, sp - vand q6, q6, q5 - vadd.u64 q9, q8, q8 - vst1.64 {q8}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q9, #63 - veor q9, q9, q6 - vand q7, q7, q5 - vadd.u64 q10, q9, q9 - vst1.64 {q9}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q10, #63 - veor q10, q10, q7 - vand q6, q6, q5 - vld1.8 {q0}, [r7]! - vadd.u64 q11, q10, q10 - vst1.64 {q10}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q11, #63 - veor q11, q11, q6 - vand q7, q7, q5 - vld1.8 {q1}, [r7]! - veor q0, q0, q8 - vadd.u64 q12, q11, q11 - vst1.64 {q11}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q12, #63 - veor q12, q12, q7 - vand q6, q6, q5 - vld1.8 {q2}, [r7]! - veor q1, q1, q9 - vadd.u64 q13, q12, q12 - vst1.64 {q12}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q13, #63 - veor q13, q13, q6 - vand q7, q7, q5 - vld1.8 {q3}, [r7]! - veor q2, q2, q10 - vadd.u64 q14, q13, q13 - vst1.64 {q13}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q14, #63 - veor q14, q14, q7 - vand q6, q6, q5 - vld1.8 {q4}, [r7]! - veor q3, q3, q11 - vadd.u64 q15, q14, q14 - vst1.64 {q14}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q15, #63 - veor q15, q15, q6 - vand q7, q7, q5 - vld1.8 {q5}, [r7]! - veor q4, q4, q12 - vadd.u64 q8, q15, q15 - vst1.64 {q15}, [r0,:128]! - vswp d15,d14 - veor q8, q8, q7 - vst1.64 {q8}, [r0,:128] @ next round tweak - - vld1.8 {q6,q7}, [r7]! - veor q5, q5, q13 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q6, q6, q14 - mov r5, r1 @ pass rounds - veor q7, q7, q15 - mov r0, sp - - bl _bsaes_encrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - vld1.64 {q12,q13}, [r0,:128]! - veor q1, q1, q9 - veor q8, q4, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q6, q11 - vld1.64 {q14,q15}, [r0,:128]! - veor q10, q3, q12 - vst1.8 {q8,q9}, [r8]! - veor q11, q7, q13 - veor q12, q2, q14 - vst1.8 {q10,q11}, [r8]! - veor q13, q5, q15 - vst1.8 {q12,q13}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - - subs r9, #0x80 - bpl .Lxts_enc_loop - -.Lxts_enc_short: - adds r9, #0x70 - bmi .Lxts_enc_done - - vldmia r2, {q5} @ load XTS magic - vshr.s64 q7, q8, #63 - mov r0, sp - vand q7, q7, q5 - vadd.u64 q9, q8, q8 - vst1.64 {q8}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q9, #63 - veor q9, q9, q7 - vand q6, q6, q5 - vadd.u64 q10, q9, q9 - vst1.64 {q9}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q10, #63 - veor q10, q10, q6 - vand q7, q7, q5 - vld1.8 {q0}, [r7]! - subs r9, #0x10 - bmi .Lxts_enc_1 - vadd.u64 q11, q10, q10 - vst1.64 {q10}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q11, #63 - veor q11, q11, q7 - vand q6, q6, q5 - vld1.8 {q1}, [r7]! - subs r9, #0x10 - bmi .Lxts_enc_2 - veor q0, q0, q8 - vadd.u64 q12, q11, q11 - vst1.64 {q11}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q12, #63 - veor q12, q12, q6 - vand q7, q7, q5 - vld1.8 {q2}, [r7]! - subs r9, #0x10 - bmi .Lxts_enc_3 - veor q1, q1, q9 - vadd.u64 q13, q12, q12 - vst1.64 {q12}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q13, #63 - veor q13, q13, q7 - vand q6, q6, q5 - vld1.8 {q3}, [r7]! - subs r9, #0x10 - bmi .Lxts_enc_4 - veor q2, q2, q10 - vadd.u64 q14, q13, q13 - vst1.64 {q13}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q14, #63 - veor q14, q14, q6 - vand q7, q7, q5 - vld1.8 {q4}, [r7]! - subs r9, #0x10 - bmi .Lxts_enc_5 - veor q3, q3, q11 - vadd.u64 q15, q14, q14 - vst1.64 {q14}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q15, #63 - veor q15, q15, q7 - vand q6, q6, q5 - vld1.8 {q5}, [r7]! - subs r9, #0x10 - bmi .Lxts_enc_6 - veor q4, q4, q12 - sub r9, #0x10 - vst1.64 {q15}, [r0,:128] @ next round tweak - - vld1.8 {q6}, [r7]! - veor q5, q5, q13 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q6, q6, q14 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_encrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - vld1.64 {q12,q13}, [r0,:128]! - veor q1, q1, q9 - veor q8, q4, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q6, q11 - vld1.64 {q14}, [r0,:128]! - veor q10, q3, q12 - vst1.8 {q8,q9}, [r8]! - veor q11, q7, q13 - veor q12, q2, q14 - vst1.8 {q10,q11}, [r8]! - vst1.8 {q12}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b .Lxts_enc_done -.align 4 -.Lxts_enc_6: - veor q4, q4, q12 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q5, q5, q13 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_encrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - vld1.64 {q12,q13}, [r0,:128]! - veor q1, q1, q9 - veor q8, q4, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q6, q11 - veor q10, q3, q12 - vst1.8 {q8,q9}, [r8]! - veor q11, q7, q13 - vst1.8 {q10,q11}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b .Lxts_enc_done - -@ put this in range for both ARM and Thumb mode adr instructions -.align 5 -.Lxts_magic: -.quad 1, 0x87 - -.align 5 -.Lxts_enc_5: - veor q3, q3, q11 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q4, q4, q12 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_encrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - vld1.64 {q12}, [r0,:128]! - veor q1, q1, q9 - veor q8, q4, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q6, q11 - veor q10, q3, q12 - vst1.8 {q8,q9}, [r8]! - vst1.8 {q10}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b .Lxts_enc_done -.align 4 -.Lxts_enc_4: - veor q2, q2, q10 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q3, q3, q11 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_encrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - veor q1, q1, q9 - veor q8, q4, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q6, q11 - vst1.8 {q8,q9}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b .Lxts_enc_done -.align 4 -.Lxts_enc_3: - veor q1, q1, q9 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q2, q2, q10 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_encrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10}, [r0,:128]! - veor q0, q0, q8 - veor q1, q1, q9 - veor q8, q4, q10 - vst1.8 {q0,q1}, [r8]! - vst1.8 {q8}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b .Lxts_enc_done -.align 4 -.Lxts_enc_2: - veor q0, q0, q8 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q1, q1, q9 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_encrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - veor q0, q0, q8 - veor q1, q1, q9 - vst1.8 {q0,q1}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b .Lxts_enc_done -.align 4 -.Lxts_enc_1: - mov r0, sp - veor q0, q0, q8 - mov r1, sp - vst1.8 {q0}, [sp,:128] - mov r2, r10 - mov r4, r3 @ preserve fp - - bl AES_encrypt - - vld1.8 {q0}, [sp,:128] - veor q0, q0, q8 - vst1.8 {q0}, [r8]! - mov r3, r4 - - vmov q8, q9 @ next round tweak - -.Lxts_enc_done: -#ifndef XTS_CHAIN_TWEAK - adds r9, #0x10 - beq .Lxts_enc_ret - sub r6, r8, #0x10 - -.Lxts_enc_steal: - ldrb r0, [r7], #1 - ldrb r1, [r8, #-0x10] - strb r0, [r8, #-0x10] - strb r1, [r8], #1 - - subs r9, #1 - bhi .Lxts_enc_steal - - vld1.8 {q0}, [r6] - mov r0, sp - veor q0, q0, q8 - mov r1, sp - vst1.8 {q0}, [sp,:128] - mov r2, r10 - mov r4, r3 @ preserve fp - - bl AES_encrypt - - vld1.8 {q0}, [sp,:128] - veor q0, q0, q8 - vst1.8 {q0}, [r6] - mov r3, r4 -#endif - -.Lxts_enc_ret: - bic r0, r3, #0xf - vmov.i32 q0, #0 - vmov.i32 q1, #0 -#ifdef XTS_CHAIN_TWEAK - ldr r1, [r3, #0x20+VFP_ABI_FRAME] @ chain tweak -#endif -.Lxts_enc_bzero:@ wipe key schedule [if any] - vstmia sp!, {q0,q1} - cmp sp, r0 - bne .Lxts_enc_bzero - - mov sp, r3 -#ifdef XTS_CHAIN_TWEAK - vst1.8 {q8}, [r1] -#endif - VFP_ABI_POP - ldmia sp!, {r4,r5,r6,r7,r8,r9,r10, pc} @ return - -.size bsaes_xts_encrypt,.-bsaes_xts_encrypt - -.globl bsaes_xts_decrypt -.hidden bsaes_xts_decrypt -.type bsaes_xts_decrypt,%function -.align 4 -bsaes_xts_decrypt: - mov ip, sp - stmdb sp!, {r4,r5,r6,r7,r8,r9,r10, lr} @ 0x20 - VFP_ABI_PUSH - mov r6, sp @ future r3 - - mov r7, r0 - mov r8, r1 - mov r9, r2 - mov r10, r3 - - sub r0, sp, #0x10 @ 0x10 - bic r0, #0xf @ align at 16 bytes - mov sp, r0 - -#ifdef XTS_CHAIN_TWEAK - ldr r0, [ip] @ pointer to input tweak -#else - @ generate initial tweak - ldr r0, [ip, #4] @ iv[] - mov r1, sp - ldr r2, [ip, #0] @ key2 - bl AES_encrypt - mov r0, sp @ pointer to initial tweak -#endif - - ldr r1, [r10, #240] @ get # of rounds - mov r3, r6 -#ifndef BSAES_ASM_EXTENDED_KEY - @ allocate the key schedule on the stack - sub r12, sp, r1, lsl#7 @ 128 bytes per inner round key - @ add r12, #96 @ size of bit-sliced key schedule - sub r12, #48 @ place for tweak[9] - - @ populate the key schedule - mov r4, r10 @ pass key - mov r5, r1 @ pass # of rounds - mov sp, r12 - add r12, #0x90 @ pass key schedule - bl _bsaes_key_convert - add r4, sp, #0x90 - vldmia r4, {q6} - vstmia r12, {q15} @ save last round key - veor q7, q7, q6 @ fix up round 0 key - vstmia r4, {q7} -#else - ldr r12, [r10, #244] - eors r12, #1 - beq 0f - - str r12, [r10, #244] - mov r4, r10 @ pass key - mov r5, r1 @ pass # of rounds - add r12, r10, #248 @ pass key schedule - bl _bsaes_key_convert - add r4, r10, #248 - vldmia r4, {q6} - vstmia r12, {q15} @ save last round key - veor q7, q7, q6 @ fix up round 0 key - vstmia r4, {q7} - -.align 2 - sub sp, #0x90 @ place for tweak[9] -#endif - vld1.8 {q8}, [r0] @ initial tweak - adr r2, .Lxts_magic - -#ifndef XTS_CHAIN_TWEAK - tst r9, #0xf @ if not multiple of 16 - it ne @ Thumb2 thing, sanity check in ARM - subne r9, #0x10 @ subtract another 16 bytes -#endif - subs r9, #0x80 - - blo .Lxts_dec_short - b .Lxts_dec_loop - -.align 4 -.Lxts_dec_loop: - vldmia r2, {q5} @ load XTS magic - vshr.s64 q6, q8, #63 - mov r0, sp - vand q6, q6, q5 - vadd.u64 q9, q8, q8 - vst1.64 {q8}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q9, #63 - veor q9, q9, q6 - vand q7, q7, q5 - vadd.u64 q10, q9, q9 - vst1.64 {q9}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q10, #63 - veor q10, q10, q7 - vand q6, q6, q5 - vld1.8 {q0}, [r7]! - vadd.u64 q11, q10, q10 - vst1.64 {q10}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q11, #63 - veor q11, q11, q6 - vand q7, q7, q5 - vld1.8 {q1}, [r7]! - veor q0, q0, q8 - vadd.u64 q12, q11, q11 - vst1.64 {q11}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q12, #63 - veor q12, q12, q7 - vand q6, q6, q5 - vld1.8 {q2}, [r7]! - veor q1, q1, q9 - vadd.u64 q13, q12, q12 - vst1.64 {q12}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q13, #63 - veor q13, q13, q6 - vand q7, q7, q5 - vld1.8 {q3}, [r7]! - veor q2, q2, q10 - vadd.u64 q14, q13, q13 - vst1.64 {q13}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q14, #63 - veor q14, q14, q7 - vand q6, q6, q5 - vld1.8 {q4}, [r7]! - veor q3, q3, q11 - vadd.u64 q15, q14, q14 - vst1.64 {q14}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q15, #63 - veor q15, q15, q6 - vand q7, q7, q5 - vld1.8 {q5}, [r7]! - veor q4, q4, q12 - vadd.u64 q8, q15, q15 - vst1.64 {q15}, [r0,:128]! - vswp d15,d14 - veor q8, q8, q7 - vst1.64 {q8}, [r0,:128] @ next round tweak - - vld1.8 {q6,q7}, [r7]! - veor q5, q5, q13 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q6, q6, q14 - mov r5, r1 @ pass rounds - veor q7, q7, q15 - mov r0, sp - - bl _bsaes_decrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - vld1.64 {q12,q13}, [r0,:128]! - veor q1, q1, q9 - veor q8, q6, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q4, q11 - vld1.64 {q14,q15}, [r0,:128]! - veor q10, q2, q12 - vst1.8 {q8,q9}, [r8]! - veor q11, q7, q13 - veor q12, q3, q14 - vst1.8 {q10,q11}, [r8]! - veor q13, q5, q15 - vst1.8 {q12,q13}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - - subs r9, #0x80 - bpl .Lxts_dec_loop - -.Lxts_dec_short: - adds r9, #0x70 - bmi .Lxts_dec_done - - vldmia r2, {q5} @ load XTS magic - vshr.s64 q7, q8, #63 - mov r0, sp - vand q7, q7, q5 - vadd.u64 q9, q8, q8 - vst1.64 {q8}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q9, #63 - veor q9, q9, q7 - vand q6, q6, q5 - vadd.u64 q10, q9, q9 - vst1.64 {q9}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q10, #63 - veor q10, q10, q6 - vand q7, q7, q5 - vld1.8 {q0}, [r7]! - subs r9, #0x10 - bmi .Lxts_dec_1 - vadd.u64 q11, q10, q10 - vst1.64 {q10}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q11, #63 - veor q11, q11, q7 - vand q6, q6, q5 - vld1.8 {q1}, [r7]! - subs r9, #0x10 - bmi .Lxts_dec_2 - veor q0, q0, q8 - vadd.u64 q12, q11, q11 - vst1.64 {q11}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q12, #63 - veor q12, q12, q6 - vand q7, q7, q5 - vld1.8 {q2}, [r7]! - subs r9, #0x10 - bmi .Lxts_dec_3 - veor q1, q1, q9 - vadd.u64 q13, q12, q12 - vst1.64 {q12}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q13, #63 - veor q13, q13, q7 - vand q6, q6, q5 - vld1.8 {q3}, [r7]! - subs r9, #0x10 - bmi .Lxts_dec_4 - veor q2, q2, q10 - vadd.u64 q14, q13, q13 - vst1.64 {q13}, [r0,:128]! - vswp d13,d12 - vshr.s64 q7, q14, #63 - veor q14, q14, q6 - vand q7, q7, q5 - vld1.8 {q4}, [r7]! - subs r9, #0x10 - bmi .Lxts_dec_5 - veor q3, q3, q11 - vadd.u64 q15, q14, q14 - vst1.64 {q14}, [r0,:128]! - vswp d15,d14 - vshr.s64 q6, q15, #63 - veor q15, q15, q7 - vand q6, q6, q5 - vld1.8 {q5}, [r7]! - subs r9, #0x10 - bmi .Lxts_dec_6 - veor q4, q4, q12 - sub r9, #0x10 - vst1.64 {q15}, [r0,:128] @ next round tweak - - vld1.8 {q6}, [r7]! - veor q5, q5, q13 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q6, q6, q14 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_decrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - vld1.64 {q12,q13}, [r0,:128]! - veor q1, q1, q9 - veor q8, q6, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q4, q11 - vld1.64 {q14}, [r0,:128]! - veor q10, q2, q12 - vst1.8 {q8,q9}, [r8]! - veor q11, q7, q13 - veor q12, q3, q14 - vst1.8 {q10,q11}, [r8]! - vst1.8 {q12}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b .Lxts_dec_done -.align 4 -.Lxts_dec_6: - vst1.64 {q14}, [r0,:128] @ next round tweak - - veor q4, q4, q12 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q5, q5, q13 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_decrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - vld1.64 {q12,q13}, [r0,:128]! - veor q1, q1, q9 - veor q8, q6, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q4, q11 - veor q10, q2, q12 - vst1.8 {q8,q9}, [r8]! - veor q11, q7, q13 - vst1.8 {q10,q11}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b .Lxts_dec_done -.align 4 -.Lxts_dec_5: - veor q3, q3, q11 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q4, q4, q12 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_decrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - vld1.64 {q12}, [r0,:128]! - veor q1, q1, q9 - veor q8, q6, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q4, q11 - veor q10, q2, q12 - vst1.8 {q8,q9}, [r8]! - vst1.8 {q10}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b .Lxts_dec_done -.align 4 -.Lxts_dec_4: - veor q2, q2, q10 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q3, q3, q11 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_decrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10,q11}, [r0,:128]! - veor q0, q0, q8 - veor q1, q1, q9 - veor q8, q6, q10 - vst1.8 {q0,q1}, [r8]! - veor q9, q4, q11 - vst1.8 {q8,q9}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b .Lxts_dec_done -.align 4 -.Lxts_dec_3: - veor q1, q1, q9 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q2, q2, q10 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_decrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - vld1.64 {q10}, [r0,:128]! - veor q0, q0, q8 - veor q1, q1, q9 - veor q8, q6, q10 - vst1.8 {q0,q1}, [r8]! - vst1.8 {q8}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b .Lxts_dec_done -.align 4 -.Lxts_dec_2: - veor q0, q0, q8 -#ifndef BSAES_ASM_EXTENDED_KEY - add r4, sp, #0x90 @ pass key schedule -#else - add r4, r10, #248 @ pass key schedule -#endif - veor q1, q1, q9 - mov r5, r1 @ pass rounds - mov r0, sp - - bl _bsaes_decrypt8 - - vld1.64 {q8,q9}, [r0,:128]! - veor q0, q0, q8 - veor q1, q1, q9 - vst1.8 {q0,q1}, [r8]! - - vld1.64 {q8}, [r0,:128] @ next round tweak - b .Lxts_dec_done -.align 4 -.Lxts_dec_1: - mov r0, sp - veor q0, q0, q8 - mov r1, sp - vst1.8 {q0}, [sp,:128] - mov r5, r2 @ preserve magic - mov r2, r10 - mov r4, r3 @ preserve fp - - bl AES_decrypt - - vld1.8 {q0}, [sp,:128] - veor q0, q0, q8 - vst1.8 {q0}, [r8]! - mov r3, r4 - mov r2, r5 - - vmov q8, q9 @ next round tweak - -.Lxts_dec_done: -#ifndef XTS_CHAIN_TWEAK - adds r9, #0x10 - beq .Lxts_dec_ret - - @ calculate one round of extra tweak for the stolen ciphertext - vldmia r2, {q5} - vshr.s64 q6, q8, #63 - vand q6, q6, q5 - vadd.u64 q9, q8, q8 - vswp d13,d12 - veor q9, q9, q6 - - @ perform the final decryption with the last tweak value - vld1.8 {q0}, [r7]! - mov r0, sp - veor q0, q0, q9 - mov r1, sp - vst1.8 {q0}, [sp,:128] - mov r2, r10 - mov r4, r3 @ preserve fp - - bl AES_decrypt - - vld1.8 {q0}, [sp,:128] - veor q0, q0, q9 - vst1.8 {q0}, [r8] - - mov r6, r8 -.Lxts_dec_steal: - ldrb r1, [r8] - ldrb r0, [r7], #1 - strb r1, [r8, #0x10] - strb r0, [r8], #1 - - subs r9, #1 - bhi .Lxts_dec_steal - - vld1.8 {q0}, [r6] - mov r0, sp - veor q0, q8 - mov r1, sp - vst1.8 {q0}, [sp,:128] - mov r2, r10 - - bl AES_decrypt - - vld1.8 {q0}, [sp,:128] - veor q0, q0, q8 - vst1.8 {q0}, [r6] - mov r3, r4 -#endif - -.Lxts_dec_ret: - bic r0, r3, #0xf - vmov.i32 q0, #0 - vmov.i32 q1, #0 -#ifdef XTS_CHAIN_TWEAK - ldr r1, [r3, #0x20+VFP_ABI_FRAME] @ chain tweak -#endif -.Lxts_dec_bzero:@ wipe key schedule [if any] - vstmia sp!, {q0,q1} - cmp sp, r0 - bne .Lxts_dec_bzero - - mov sp, r3 -#ifdef XTS_CHAIN_TWEAK - vst1.8 {q8}, [r1] -#endif - VFP_ABI_POP - ldmia sp!, {r4,r5,r6,r7,r8,r9,r10, pc} @ return - -.size bsaes_xts_decrypt,.-bsaes_xts_decrypt #endif #endif #endif // !OPENSSL_NO_ASM diff --git a/third_party/boringssl/kit/linux-arm/crypto/fipsmodule/ghash-armv4.S b/third_party/boringssl/kit/linux-arm/crypto/fipsmodule/ghash-armv4.S index 459ee82e..16a52831 100644 --- a/third_party/boringssl/kit/linux-arm/crypto/fipsmodule/ghash-armv4.S +++ b/third_party/boringssl/kit/linux-arm/crypto/fipsmodule/ghash-armv4.S @@ -22,6 +22,8 @@ .text #if defined(__thumb2__) || defined(__clang__) .syntax unified +#define ldrplb ldrbpl +#define ldrneb ldrbne #endif #if defined(__thumb2__) .thumb @@ -29,11 +31,6 @@ .code 32 #endif -#ifdef __clang__ -#define ldrplb ldrbpl -#define ldrneb ldrbne -#endif - .type rem_4bit,%object .align 5 rem_4bit: diff --git a/third_party/boringssl/kit/linux-arm/crypto/test/trampoline-armv4.S b/third_party/boringssl/kit/linux-arm/crypto/test/trampoline-armv4.S new file mode 100644 index 00000000..83e8aeeb --- /dev/null +++ b/third_party/boringssl/kit/linux-arm/crypto/test/trampoline-armv4.S @@ -0,0 +1,378 @@ +// This file is generated from a similarly-named Perl script in the BoringSSL +// source tree. Do not edit by hand. + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) +#define OPENSSL_NO_ASM +#endif +#endif + +#if !defined(OPENSSL_NO_ASM) +#if defined(__arm__) +#if defined(BORINGSSL_PREFIX) +#include +#endif +.syntax unified + +.arch armv7-a +.fpu vfp + +.text + +@ abi_test_trampoline loads callee-saved registers from |state|, calls |func| +@ with |argv|, then saves the callee-saved registers into |state|. It returns +@ the result of |func|. The |unwind| argument is unused. +@ uint32_t abi_test_trampoline(void (*func)(...), CallerState *state, +@ const uint32_t *argv, size_t argc, +@ int unwind); +.type abi_test_trampoline, %function +.globl abi_test_trampoline +.hidden abi_test_trampoline +.align 4 +abi_test_trampoline: +.Labi_test_trampoline_begin: + @ Save parameters and all callee-saved registers. For convenience, we + @ save r9 on iOS even though it's volatile. + vstmdb sp!, {d8,d9,d10,d11,d12,d13,d14,d15} + stmdb sp!, {r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,lr} + + @ Reserve stack space for six (10-4) stack parameters, plus an extra 4 + @ bytes to keep it 8-byte-aligned (see AAPCS, section 5.3). + sub sp, sp, #28 + + @ Every register in AAPCS is either non-volatile or a parameter (except + @ r9 on iOS), so this code, by the actual call, loses all its scratch + @ registers. First fill in stack parameters while there are registers + @ to spare. + cmp r3, #4 + bls .Lstack_args_done + mov r4, sp @ r4 is the output pointer. + add r5, r2, r3, lsl #2 @ Set r5 to the end of argv. + add r2, r2, #16 @ Skip four arguments. +.Lstack_args_loop: + ldr r6, [r2], #4 + cmp r2, r5 + str r6, [r4], #4 + bne .Lstack_args_loop + +.Lstack_args_done: + @ Load registers from |r1|. + vldmia r1!, {d8,d9,d10,d11,d12,d13,d14,d15} +#if defined(__APPLE__) + @ r9 is not volatile on iOS. + ldmia r1!, {r4,r5,r6,r7,r8,r10-r11} +#else + ldmia r1!, {r4,r5,r6,r7,r8,r9,r10,r11} +#endif + + @ Load register parameters. This uses up our remaining registers, so we + @ repurpose lr as scratch space. + ldr r3, [sp, #40] @ Reload argc. + ldr lr, [sp, #36] @ .Load argv into lr. + cmp r3, #3 + bhi .Larg_r3 + beq .Larg_r2 + cmp r3, #1 + bhi .Larg_r1 + beq .Larg_r0 + b .Largs_done + +.Larg_r3: + ldr r3, [lr, #12] @ argv[3] +.Larg_r2: + ldr r2, [lr, #8] @ argv[2] +.Larg_r1: + ldr r1, [lr, #4] @ argv[1] +.Larg_r0: + ldr r0, [lr] @ argv[0] +.Largs_done: + + @ With every other register in use, load the function pointer into lr + @ and call the function. + ldr lr, [sp, #28] + blx lr + + @ r1-r3 are free for use again. The trampoline only supports + @ single-return functions. Pass r4-r11 to the caller. + ldr r1, [sp, #32] + vstmia r1!, {d8,d9,d10,d11,d12,d13,d14,d15} +#if defined(__APPLE__) + @ r9 is not volatile on iOS. + stmia r1!, {r4,r5,r6,r7,r8,r10-r11} +#else + stmia r1!, {r4,r5,r6,r7,r8,r9,r10,r11} +#endif + + @ Unwind the stack and restore registers. + add sp, sp, #44 @ 44 = 28+16 + ldmia sp!, {r4,r5,r6,r7,r8,r9,r10,r11,lr} @ Skip r0-r3 (see +16 above). + vldmia sp!, {d8,d9,d10,d11,d12,d13,d14,d15} + + bx lr +.size abi_test_trampoline,.-abi_test_trampoline +.type abi_test_clobber_r0, %function +.globl abi_test_clobber_r0 +.hidden abi_test_clobber_r0 +.align 4 +abi_test_clobber_r0: + mov r0, #0 + bx lr +.size abi_test_clobber_r0,.-abi_test_clobber_r0 +.type abi_test_clobber_r1, %function +.globl abi_test_clobber_r1 +.hidden abi_test_clobber_r1 +.align 4 +abi_test_clobber_r1: + mov r1, #0 + bx lr +.size abi_test_clobber_r1,.-abi_test_clobber_r1 +.type abi_test_clobber_r2, %function +.globl abi_test_clobber_r2 +.hidden abi_test_clobber_r2 +.align 4 +abi_test_clobber_r2: + mov r2, #0 + bx lr +.size abi_test_clobber_r2,.-abi_test_clobber_r2 +.type abi_test_clobber_r3, %function +.globl abi_test_clobber_r3 +.hidden abi_test_clobber_r3 +.align 4 +abi_test_clobber_r3: + mov r3, #0 + bx lr +.size abi_test_clobber_r3,.-abi_test_clobber_r3 +.type abi_test_clobber_r4, %function +.globl abi_test_clobber_r4 +.hidden abi_test_clobber_r4 +.align 4 +abi_test_clobber_r4: + mov r4, #0 + bx lr +.size abi_test_clobber_r4,.-abi_test_clobber_r4 +.type abi_test_clobber_r5, %function +.globl abi_test_clobber_r5 +.hidden abi_test_clobber_r5 +.align 4 +abi_test_clobber_r5: + mov r5, #0 + bx lr +.size abi_test_clobber_r5,.-abi_test_clobber_r5 +.type abi_test_clobber_r6, %function +.globl abi_test_clobber_r6 +.hidden abi_test_clobber_r6 +.align 4 +abi_test_clobber_r6: + mov r6, #0 + bx lr +.size abi_test_clobber_r6,.-abi_test_clobber_r6 +.type abi_test_clobber_r7, %function +.globl abi_test_clobber_r7 +.hidden abi_test_clobber_r7 +.align 4 +abi_test_clobber_r7: + mov r7, #0 + bx lr +.size abi_test_clobber_r7,.-abi_test_clobber_r7 +.type abi_test_clobber_r8, %function +.globl abi_test_clobber_r8 +.hidden abi_test_clobber_r8 +.align 4 +abi_test_clobber_r8: + mov r8, #0 + bx lr +.size abi_test_clobber_r8,.-abi_test_clobber_r8 +.type abi_test_clobber_r9, %function +.globl abi_test_clobber_r9 +.hidden abi_test_clobber_r9 +.align 4 +abi_test_clobber_r9: + mov r9, #0 + bx lr +.size abi_test_clobber_r9,.-abi_test_clobber_r9 +.type abi_test_clobber_r10, %function +.globl abi_test_clobber_r10 +.hidden abi_test_clobber_r10 +.align 4 +abi_test_clobber_r10: + mov r10, #0 + bx lr +.size abi_test_clobber_r10,.-abi_test_clobber_r10 +.type abi_test_clobber_r11, %function +.globl abi_test_clobber_r11 +.hidden abi_test_clobber_r11 +.align 4 +abi_test_clobber_r11: + mov r11, #0 + bx lr +.size abi_test_clobber_r11,.-abi_test_clobber_r11 +.type abi_test_clobber_r12, %function +.globl abi_test_clobber_r12 +.hidden abi_test_clobber_r12 +.align 4 +abi_test_clobber_r12: + mov r12, #0 + bx lr +.size abi_test_clobber_r12,.-abi_test_clobber_r12 +.type abi_test_clobber_d0, %function +.globl abi_test_clobber_d0 +.hidden abi_test_clobber_d0 +.align 4 +abi_test_clobber_d0: + mov r0, #0 + vmov s0, r0 + vmov s1, r0 + bx lr +.size abi_test_clobber_d0,.-abi_test_clobber_d0 +.type abi_test_clobber_d1, %function +.globl abi_test_clobber_d1 +.hidden abi_test_clobber_d1 +.align 4 +abi_test_clobber_d1: + mov r0, #0 + vmov s2, r0 + vmov s3, r0 + bx lr +.size abi_test_clobber_d1,.-abi_test_clobber_d1 +.type abi_test_clobber_d2, %function +.globl abi_test_clobber_d2 +.hidden abi_test_clobber_d2 +.align 4 +abi_test_clobber_d2: + mov r0, #0 + vmov s4, r0 + vmov s5, r0 + bx lr +.size abi_test_clobber_d2,.-abi_test_clobber_d2 +.type abi_test_clobber_d3, %function +.globl abi_test_clobber_d3 +.hidden abi_test_clobber_d3 +.align 4 +abi_test_clobber_d3: + mov r0, #0 + vmov s6, r0 + vmov s7, r0 + bx lr +.size abi_test_clobber_d3,.-abi_test_clobber_d3 +.type abi_test_clobber_d4, %function +.globl abi_test_clobber_d4 +.hidden abi_test_clobber_d4 +.align 4 +abi_test_clobber_d4: + mov r0, #0 + vmov s8, r0 + vmov s9, r0 + bx lr +.size abi_test_clobber_d4,.-abi_test_clobber_d4 +.type abi_test_clobber_d5, %function +.globl abi_test_clobber_d5 +.hidden abi_test_clobber_d5 +.align 4 +abi_test_clobber_d5: + mov r0, #0 + vmov s10, r0 + vmov s11, r0 + bx lr +.size abi_test_clobber_d5,.-abi_test_clobber_d5 +.type abi_test_clobber_d6, %function +.globl abi_test_clobber_d6 +.hidden abi_test_clobber_d6 +.align 4 +abi_test_clobber_d6: + mov r0, #0 + vmov s12, r0 + vmov s13, r0 + bx lr +.size abi_test_clobber_d6,.-abi_test_clobber_d6 +.type abi_test_clobber_d7, %function +.globl abi_test_clobber_d7 +.hidden abi_test_clobber_d7 +.align 4 +abi_test_clobber_d7: + mov r0, #0 + vmov s14, r0 + vmov s15, r0 + bx lr +.size abi_test_clobber_d7,.-abi_test_clobber_d7 +.type abi_test_clobber_d8, %function +.globl abi_test_clobber_d8 +.hidden abi_test_clobber_d8 +.align 4 +abi_test_clobber_d8: + mov r0, #0 + vmov s16, r0 + vmov s17, r0 + bx lr +.size abi_test_clobber_d8,.-abi_test_clobber_d8 +.type abi_test_clobber_d9, %function +.globl abi_test_clobber_d9 +.hidden abi_test_clobber_d9 +.align 4 +abi_test_clobber_d9: + mov r0, #0 + vmov s18, r0 + vmov s19, r0 + bx lr +.size abi_test_clobber_d9,.-abi_test_clobber_d9 +.type abi_test_clobber_d10, %function +.globl abi_test_clobber_d10 +.hidden abi_test_clobber_d10 +.align 4 +abi_test_clobber_d10: + mov r0, #0 + vmov s20, r0 + vmov s21, r0 + bx lr +.size abi_test_clobber_d10,.-abi_test_clobber_d10 +.type abi_test_clobber_d11, %function +.globl abi_test_clobber_d11 +.hidden abi_test_clobber_d11 +.align 4 +abi_test_clobber_d11: + mov r0, #0 + vmov s22, r0 + vmov s23, r0 + bx lr +.size abi_test_clobber_d11,.-abi_test_clobber_d11 +.type abi_test_clobber_d12, %function +.globl abi_test_clobber_d12 +.hidden abi_test_clobber_d12 +.align 4 +abi_test_clobber_d12: + mov r0, #0 + vmov s24, r0 + vmov s25, r0 + bx lr +.size abi_test_clobber_d12,.-abi_test_clobber_d12 +.type abi_test_clobber_d13, %function +.globl abi_test_clobber_d13 +.hidden abi_test_clobber_d13 +.align 4 +abi_test_clobber_d13: + mov r0, #0 + vmov s26, r0 + vmov s27, r0 + bx lr +.size abi_test_clobber_d13,.-abi_test_clobber_d13 +.type abi_test_clobber_d14, %function +.globl abi_test_clobber_d14 +.hidden abi_test_clobber_d14 +.align 4 +abi_test_clobber_d14: + mov r0, #0 + vmov s28, r0 + vmov s29, r0 + bx lr +.size abi_test_clobber_d14,.-abi_test_clobber_d14 +.type abi_test_clobber_d15, %function +.globl abi_test_clobber_d15 +.hidden abi_test_clobber_d15 +.align 4 +abi_test_clobber_d15: + mov r0, #0 + vmov s30, r0 + vmov s31, r0 + bx lr +.size abi_test_clobber_d15,.-abi_test_clobber_d15 +#endif +#endif // !OPENSSL_NO_ASM diff --git a/third_party/boringssl/kit/linux-ppc64le/crypto/fipsmodule/aesp8-ppc.S b/third_party/boringssl/kit/linux-ppc64le/crypto/fipsmodule/aesp8-ppc.S index 42b69c15..911d6383 100644 --- a/third_party/boringssl/kit/linux-ppc64le/crypto/fipsmodule/aesp8-ppc.S +++ b/third_party/boringssl/kit/linux-ppc64le/crypto/fipsmodule/aesp8-ppc.S @@ -1778,7 +1778,7 @@ _aesp8_ctr32_encrypt8x: .long 0x7E082799 .long 0x7E3A2799 addi 4,4,0x30 - b .Lcbc_dec8x_done + b .Lctr32_enc8x_done .align 5 .Lctr32_enc8x_two: @@ -1790,7 +1790,7 @@ _aesp8_ctr32_encrypt8x: .long 0x7DE02799 .long 0x7E082799 addi 4,4,0x20 - b .Lcbc_dec8x_done + b .Lctr32_enc8x_done .align 5 .Lctr32_enc8x_one: diff --git a/third_party/boringssl/kit/linux-x86/crypto/fipsmodule/aesni-x86.S b/third_party/boringssl/kit/linux-x86/crypto/fipsmodule/aesni-x86.S index b193966e..bd0f2715 100644 --- a/third_party/boringssl/kit/linux-x86/crypto/fipsmodule/aesni-x86.S +++ b/third_party/boringssl/kit/linux-x86/crypto/fipsmodule/aesni-x86.S @@ -6,12 +6,26 @@ #include #endif .text +#ifndef NDEBUG +#endif .globl aes_hw_encrypt .hidden aes_hw_encrypt .type aes_hw_encrypt,@function .align 16 aes_hw_encrypt: .L_aes_hw_encrypt_begin: +#ifndef NDEBUG + pushl %ebx + pushl %edx + call .L000pic +.L000pic: + popl %ebx + leal BORINGSSL_function_hit+1-.L000pic(%ebx),%ebx + movl $1,%edx + movb %dl,(%ebx) + popl %edx + popl %ebx +#endif movl 4(%esp),%eax movl 12(%esp),%edx movups (%eax),%xmm2 @@ -21,12 +35,12 @@ aes_hw_encrypt: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -.L000enc1_loop_1: +.L001enc1_loop_1: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz .L000enc1_loop_1 + jnz .L001enc1_loop_1 .byte 102,15,56,221,209 pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 @@ -49,12 +63,12 @@ aes_hw_decrypt: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -.L001dec1_loop_2: +.L002dec1_loop_2: .byte 102,15,56,222,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz .L001dec1_loop_2 + jnz .L002dec1_loop_2 .byte 102,15,56,223,209 pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 @@ -75,7 +89,7 @@ _aesni_encrypt2: leal 32(%edx,%ecx,1),%edx negl %ecx addl $16,%ecx -.L002enc2_loop: +.L003enc2_loop: .byte 102,15,56,220,209 .byte 102,15,56,220,217 movups (%edx,%ecx,1),%xmm1 @@ -83,7 +97,7 @@ _aesni_encrypt2: .byte 102,15,56,220,208 .byte 102,15,56,220,216 movups -16(%edx,%ecx,1),%xmm0 - jnz .L002enc2_loop + jnz .L003enc2_loop .byte 102,15,56,220,209 .byte 102,15,56,220,217 .byte 102,15,56,221,208 @@ -103,7 +117,7 @@ _aesni_decrypt2: leal 32(%edx,%ecx,1),%edx negl %ecx addl $16,%ecx -.L003dec2_loop: +.L004dec2_loop: .byte 102,15,56,222,209 .byte 102,15,56,222,217 movups (%edx,%ecx,1),%xmm1 @@ -111,7 +125,7 @@ _aesni_decrypt2: .byte 102,15,56,222,208 .byte 102,15,56,222,216 movups -16(%edx,%ecx,1),%xmm0 - jnz .L003dec2_loop + jnz .L004dec2_loop .byte 102,15,56,222,209 .byte 102,15,56,222,217 .byte 102,15,56,223,208 @@ -132,7 +146,7 @@ _aesni_encrypt3: leal 32(%edx,%ecx,1),%edx negl %ecx addl $16,%ecx -.L004enc3_loop: +.L005enc3_loop: .byte 102,15,56,220,209 .byte 102,15,56,220,217 .byte 102,15,56,220,225 @@ -142,7 +156,7 @@ _aesni_encrypt3: .byte 102,15,56,220,216 .byte 102,15,56,220,224 movups -16(%edx,%ecx,1),%xmm0 - jnz .L004enc3_loop + jnz .L005enc3_loop .byte 102,15,56,220,209 .byte 102,15,56,220,217 .byte 102,15,56,220,225 @@ -165,7 +179,7 @@ _aesni_decrypt3: leal 32(%edx,%ecx,1),%edx negl %ecx addl $16,%ecx -.L005dec3_loop: +.L006dec3_loop: .byte 102,15,56,222,209 .byte 102,15,56,222,217 .byte 102,15,56,222,225 @@ -175,7 +189,7 @@ _aesni_decrypt3: .byte 102,15,56,222,216 .byte 102,15,56,222,224 movups -16(%edx,%ecx,1),%xmm0 - jnz .L005dec3_loop + jnz .L006dec3_loop .byte 102,15,56,222,209 .byte 102,15,56,222,217 .byte 102,15,56,222,225 @@ -200,7 +214,7 @@ _aesni_encrypt4: negl %ecx .byte 15,31,64,0 addl $16,%ecx -.L006enc4_loop: +.L007enc4_loop: .byte 102,15,56,220,209 .byte 102,15,56,220,217 .byte 102,15,56,220,225 @@ -212,7 +226,7 @@ _aesni_encrypt4: .byte 102,15,56,220,224 .byte 102,15,56,220,232 movups -16(%edx,%ecx,1),%xmm0 - jnz .L006enc4_loop + jnz .L007enc4_loop .byte 102,15,56,220,209 .byte 102,15,56,220,217 .byte 102,15,56,220,225 @@ -239,7 +253,7 @@ _aesni_decrypt4: negl %ecx .byte 15,31,64,0 addl $16,%ecx -.L007dec4_loop: +.L008dec4_loop: .byte 102,15,56,222,209 .byte 102,15,56,222,217 .byte 102,15,56,222,225 @@ -251,7 +265,7 @@ _aesni_decrypt4: .byte 102,15,56,222,224 .byte 102,15,56,222,232 movups -16(%edx,%ecx,1),%xmm0 - jnz .L007dec4_loop + jnz .L008dec4_loop .byte 102,15,56,222,209 .byte 102,15,56,222,217 .byte 102,15,56,222,225 @@ -282,13 +296,13 @@ _aesni_encrypt6: pxor %xmm0,%xmm7 movups (%edx,%ecx,1),%xmm0 addl $16,%ecx - jmp .L008_aesni_encrypt6_inner + jmp .L009_aesni_encrypt6_inner .align 16 -.L009enc6_loop: +.L010enc6_loop: .byte 102,15,56,220,209 .byte 102,15,56,220,217 .byte 102,15,56,220,225 -.L008_aesni_encrypt6_inner: +.L009_aesni_encrypt6_inner: .byte 102,15,56,220,233 .byte 102,15,56,220,241 .byte 102,15,56,220,249 @@ -302,7 +316,7 @@ _aesni_encrypt6: .byte 102,15,56,220,240 .byte 102,15,56,220,248 movups -16(%edx,%ecx,1),%xmm0 - jnz .L009enc6_loop + jnz .L010enc6_loop .byte 102,15,56,220,209 .byte 102,15,56,220,217 .byte 102,15,56,220,225 @@ -337,13 +351,13 @@ _aesni_decrypt6: pxor %xmm0,%xmm7 movups (%edx,%ecx,1),%xmm0 addl $16,%ecx - jmp .L010_aesni_decrypt6_inner + jmp .L011_aesni_decrypt6_inner .align 16 -.L011dec6_loop: +.L012dec6_loop: .byte 102,15,56,222,209 .byte 102,15,56,222,217 .byte 102,15,56,222,225 -.L010_aesni_decrypt6_inner: +.L011_aesni_decrypt6_inner: .byte 102,15,56,222,233 .byte 102,15,56,222,241 .byte 102,15,56,222,249 @@ -357,7 +371,7 @@ _aesni_decrypt6: .byte 102,15,56,222,240 .byte 102,15,56,222,248 movups -16(%edx,%ecx,1),%xmm0 - jnz .L011dec6_loop + jnz .L012dec6_loop .byte 102,15,56,222,209 .byte 102,15,56,222,217 .byte 102,15,56,222,225 @@ -388,14 +402,14 @@ aes_hw_ecb_encrypt: movl 32(%esp),%edx movl 36(%esp),%ebx andl $-16,%eax - jz .L012ecb_ret + jz .L013ecb_ret movl 240(%edx),%ecx testl %ebx,%ebx - jz .L013ecb_decrypt + jz .L014ecb_decrypt movl %edx,%ebp movl %ecx,%ebx cmpl $96,%eax - jb .L014ecb_enc_tail + jb .L015ecb_enc_tail movdqu (%esi),%xmm2 movdqu 16(%esi),%xmm3 movdqu 32(%esi),%xmm4 @@ -404,9 +418,9 @@ aes_hw_ecb_encrypt: movdqu 80(%esi),%xmm7 leal 96(%esi),%esi subl $96,%eax - jmp .L015ecb_enc_loop6_enter + jmp .L016ecb_enc_loop6_enter .align 16 -.L016ecb_enc_loop6: +.L017ecb_enc_loop6: movups %xmm2,(%edi) movdqu (%esi),%xmm2 movups %xmm3,16(%edi) @@ -421,12 +435,12 @@ aes_hw_ecb_encrypt: leal 96(%edi),%edi movdqu 80(%esi),%xmm7 leal 96(%esi),%esi -.L015ecb_enc_loop6_enter: +.L016ecb_enc_loop6_enter: call _aesni_encrypt6 movl %ebp,%edx movl %ebx,%ecx subl $96,%eax - jnc .L016ecb_enc_loop6 + jnc .L017ecb_enc_loop6 movups %xmm2,(%edi) movups %xmm3,16(%edi) movups %xmm4,32(%edi) @@ -435,18 +449,18 @@ aes_hw_ecb_encrypt: movups %xmm7,80(%edi) leal 96(%edi),%edi addl $96,%eax - jz .L012ecb_ret -.L014ecb_enc_tail: + jz .L013ecb_ret +.L015ecb_enc_tail: movups (%esi),%xmm2 cmpl $32,%eax - jb .L017ecb_enc_one + jb .L018ecb_enc_one movups 16(%esi),%xmm3 - je .L018ecb_enc_two + je .L019ecb_enc_two movups 32(%esi),%xmm4 cmpl $64,%eax - jb .L019ecb_enc_three + jb .L020ecb_enc_three movups 48(%esi),%xmm5 - je .L020ecb_enc_four + je .L021ecb_enc_four movups 64(%esi),%xmm6 xorps %xmm7,%xmm7 call _aesni_encrypt6 @@ -455,49 +469,49 @@ aes_hw_ecb_encrypt: movups %xmm4,32(%edi) movups %xmm5,48(%edi) movups %xmm6,64(%edi) - jmp .L012ecb_ret + jmp .L013ecb_ret .align 16 -.L017ecb_enc_one: +.L018ecb_enc_one: movups (%edx),%xmm0 movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -.L021enc1_loop_3: +.L022enc1_loop_3: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz .L021enc1_loop_3 + jnz .L022enc1_loop_3 .byte 102,15,56,221,209 movups %xmm2,(%edi) - jmp .L012ecb_ret + jmp .L013ecb_ret .align 16 -.L018ecb_enc_two: +.L019ecb_enc_two: call _aesni_encrypt2 movups %xmm2,(%edi) movups %xmm3,16(%edi) - jmp .L012ecb_ret + jmp .L013ecb_ret .align 16 -.L019ecb_enc_three: +.L020ecb_enc_three: call _aesni_encrypt3 movups %xmm2,(%edi) movups %xmm3,16(%edi) movups %xmm4,32(%edi) - jmp .L012ecb_ret + jmp .L013ecb_ret .align 16 -.L020ecb_enc_four: +.L021ecb_enc_four: call _aesni_encrypt4 movups %xmm2,(%edi) movups %xmm3,16(%edi) movups %xmm4,32(%edi) movups %xmm5,48(%edi) - jmp .L012ecb_ret + jmp .L013ecb_ret .align 16 -.L013ecb_decrypt: +.L014ecb_decrypt: movl %edx,%ebp movl %ecx,%ebx cmpl $96,%eax - jb .L022ecb_dec_tail + jb .L023ecb_dec_tail movdqu (%esi),%xmm2 movdqu 16(%esi),%xmm3 movdqu 32(%esi),%xmm4 @@ -506,9 +520,9 @@ aes_hw_ecb_encrypt: movdqu 80(%esi),%xmm7 leal 96(%esi),%esi subl $96,%eax - jmp .L023ecb_dec_loop6_enter + jmp .L024ecb_dec_loop6_enter .align 16 -.L024ecb_dec_loop6: +.L025ecb_dec_loop6: movups %xmm2,(%edi) movdqu (%esi),%xmm2 movups %xmm3,16(%edi) @@ -523,12 +537,12 @@ aes_hw_ecb_encrypt: leal 96(%edi),%edi movdqu 80(%esi),%xmm7 leal 96(%esi),%esi -.L023ecb_dec_loop6_enter: +.L024ecb_dec_loop6_enter: call _aesni_decrypt6 movl %ebp,%edx movl %ebx,%ecx subl $96,%eax - jnc .L024ecb_dec_loop6 + jnc .L025ecb_dec_loop6 movups %xmm2,(%edi) movups %xmm3,16(%edi) movups %xmm4,32(%edi) @@ -537,18 +551,18 @@ aes_hw_ecb_encrypt: movups %xmm7,80(%edi) leal 96(%edi),%edi addl $96,%eax - jz .L012ecb_ret -.L022ecb_dec_tail: + jz .L013ecb_ret +.L023ecb_dec_tail: movups (%esi),%xmm2 cmpl $32,%eax - jb .L025ecb_dec_one + jb .L026ecb_dec_one movups 16(%esi),%xmm3 - je .L026ecb_dec_two + je .L027ecb_dec_two movups 32(%esi),%xmm4 cmpl $64,%eax - jb .L027ecb_dec_three + jb .L028ecb_dec_three movups 48(%esi),%xmm5 - je .L028ecb_dec_four + je .L029ecb_dec_four movups 64(%esi),%xmm6 xorps %xmm7,%xmm7 call _aesni_decrypt6 @@ -557,43 +571,43 @@ aes_hw_ecb_encrypt: movups %xmm4,32(%edi) movups %xmm5,48(%edi) movups %xmm6,64(%edi) - jmp .L012ecb_ret + jmp .L013ecb_ret .align 16 -.L025ecb_dec_one: +.L026ecb_dec_one: movups (%edx),%xmm0 movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -.L029dec1_loop_4: +.L030dec1_loop_4: .byte 102,15,56,222,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz .L029dec1_loop_4 + jnz .L030dec1_loop_4 .byte 102,15,56,223,209 movups %xmm2,(%edi) - jmp .L012ecb_ret + jmp .L013ecb_ret .align 16 -.L026ecb_dec_two: +.L027ecb_dec_two: call _aesni_decrypt2 movups %xmm2,(%edi) movups %xmm3,16(%edi) - jmp .L012ecb_ret + jmp .L013ecb_ret .align 16 -.L027ecb_dec_three: +.L028ecb_dec_three: call _aesni_decrypt3 movups %xmm2,(%edi) movups %xmm3,16(%edi) movups %xmm4,32(%edi) - jmp .L012ecb_ret + jmp .L013ecb_ret .align 16 -.L028ecb_dec_four: +.L029ecb_dec_four: call _aesni_decrypt4 movups %xmm2,(%edi) movups %xmm3,16(%edi) movups %xmm4,32(%edi) movups %xmm5,48(%edi) -.L012ecb_ret: +.L013ecb_ret: pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 pxor %xmm2,%xmm2 @@ -649,7 +663,7 @@ aes_hw_ccm64_encrypt_blocks: leal 32(%edx,%ecx,1),%edx subl %ecx,%ebx .byte 102,15,56,0,253 -.L030ccm64_enc_outer: +.L031ccm64_enc_outer: movups (%ebp),%xmm0 movl %ebx,%ecx movups (%esi),%xmm6 @@ -658,7 +672,7 @@ aes_hw_ccm64_encrypt_blocks: xorps %xmm6,%xmm0 xorps %xmm0,%xmm3 movups 32(%ebp),%xmm0 -.L031ccm64_enc2_loop: +.L032ccm64_enc2_loop: .byte 102,15,56,220,209 .byte 102,15,56,220,217 movups (%edx,%ecx,1),%xmm1 @@ -666,7 +680,7 @@ aes_hw_ccm64_encrypt_blocks: .byte 102,15,56,220,208 .byte 102,15,56,220,216 movups -16(%edx,%ecx,1),%xmm0 - jnz .L031ccm64_enc2_loop + jnz .L032ccm64_enc2_loop .byte 102,15,56,220,209 .byte 102,15,56,220,217 paddq 16(%esp),%xmm7 @@ -679,7 +693,7 @@ aes_hw_ccm64_encrypt_blocks: movups %xmm6,(%edi) .byte 102,15,56,0,213 leal 16(%edi),%edi - jnz .L030ccm64_enc_outer + jnz .L031ccm64_enc_outer movl 48(%esp),%esp movl 40(%esp),%edi movups %xmm3,(%edi) @@ -739,12 +753,12 @@ aes_hw_ccm64_decrypt_blocks: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -.L032enc1_loop_5: +.L033enc1_loop_5: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz .L032enc1_loop_5 + jnz .L033enc1_loop_5 .byte 102,15,56,221,209 shll $4,%ebx movl $16,%ecx @@ -754,16 +768,16 @@ aes_hw_ccm64_decrypt_blocks: subl %ebx,%ecx leal 32(%ebp,%ebx,1),%edx movl %ecx,%ebx - jmp .L033ccm64_dec_outer + jmp .L034ccm64_dec_outer .align 16 -.L033ccm64_dec_outer: +.L034ccm64_dec_outer: xorps %xmm2,%xmm6 movdqa %xmm7,%xmm2 movups %xmm6,(%edi) leal 16(%edi),%edi .byte 102,15,56,0,213 subl $1,%eax - jz .L034ccm64_dec_break + jz .L035ccm64_dec_break movups (%ebp),%xmm0 movl %ebx,%ecx movups 16(%ebp),%xmm1 @@ -771,7 +785,7 @@ aes_hw_ccm64_decrypt_blocks: xorps %xmm0,%xmm2 xorps %xmm6,%xmm3 movups 32(%ebp),%xmm0 -.L035ccm64_dec2_loop: +.L036ccm64_dec2_loop: .byte 102,15,56,220,209 .byte 102,15,56,220,217 movups (%edx,%ecx,1),%xmm1 @@ -779,7 +793,7 @@ aes_hw_ccm64_decrypt_blocks: .byte 102,15,56,220,208 .byte 102,15,56,220,216 movups -16(%edx,%ecx,1),%xmm0 - jnz .L035ccm64_dec2_loop + jnz .L036ccm64_dec2_loop movups (%esi),%xmm6 paddq 16(%esp),%xmm7 .byte 102,15,56,220,209 @@ -787,9 +801,9 @@ aes_hw_ccm64_decrypt_blocks: .byte 102,15,56,221,208 .byte 102,15,56,221,216 leal 16(%esi),%esi - jmp .L033ccm64_dec_outer + jmp .L034ccm64_dec_outer .align 16 -.L034ccm64_dec_break: +.L035ccm64_dec_break: movl 240(%ebp),%ecx movl %ebp,%edx movups (%edx),%xmm0 @@ -797,12 +811,12 @@ aes_hw_ccm64_decrypt_blocks: xorps %xmm0,%xmm6 leal 32(%edx),%edx xorps %xmm6,%xmm3 -.L036enc1_loop_6: +.L037enc1_loop_6: .byte 102,15,56,220,217 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz .L036enc1_loop_6 + jnz .L037enc1_loop_6 .byte 102,15,56,221,217 movl 48(%esp),%esp movl 40(%esp),%edi @@ -831,6 +845,18 @@ aes_hw_ctr32_encrypt_blocks: pushl %ebx pushl %esi pushl %edi +#ifndef NDEBUG + pushl %ebx + pushl %edx + call .L038pic +.L038pic: + popl %ebx + leal BORINGSSL_function_hit+0-.L038pic(%ebx),%ebx + movl $1,%edx + movb %dl,(%ebx) + popl %edx + popl %ebx +#endif movl 20(%esp),%esi movl 24(%esp),%edi movl 28(%esp),%eax @@ -841,7 +867,7 @@ aes_hw_ctr32_encrypt_blocks: andl $-16,%esp movl %ebp,80(%esp) cmpl $1,%eax - je .L037ctr32_one_shortcut + je .L039ctr32_one_shortcut movdqu (%ebx),%xmm7 movl $202182159,(%esp) movl $134810123,4(%esp) @@ -879,7 +905,7 @@ aes_hw_ctr32_encrypt_blocks: pshufd $192,%xmm0,%xmm2 pshufd $128,%xmm0,%xmm3 cmpl $6,%eax - jb .L038ctr32_tail + jb .L040ctr32_tail pxor %xmm6,%xmm7 shll $4,%ecx movl $16,%ebx @@ -888,9 +914,9 @@ aes_hw_ctr32_encrypt_blocks: subl %ecx,%ebx leal 32(%edx,%ecx,1),%edx subl $6,%eax - jmp .L039ctr32_loop6 + jmp .L041ctr32_loop6 .align 16 -.L039ctr32_loop6: +.L041ctr32_loop6: pshufd $64,%xmm0,%xmm4 movdqa 32(%esp),%xmm0 pshufd $192,%xmm1,%xmm5 @@ -944,27 +970,27 @@ aes_hw_ctr32_encrypt_blocks: leal 96(%edi),%edi pshufd $128,%xmm0,%xmm3 subl $6,%eax - jnc .L039ctr32_loop6 + jnc .L041ctr32_loop6 addl $6,%eax - jz .L040ctr32_ret + jz .L042ctr32_ret movdqu (%ebp),%xmm7 movl %ebp,%edx pxor 32(%esp),%xmm7 movl 240(%ebp),%ecx -.L038ctr32_tail: +.L040ctr32_tail: por %xmm7,%xmm2 cmpl $2,%eax - jb .L041ctr32_one + jb .L043ctr32_one pshufd $64,%xmm0,%xmm4 por %xmm7,%xmm3 - je .L042ctr32_two + je .L044ctr32_two pshufd $192,%xmm1,%xmm5 por %xmm7,%xmm4 cmpl $4,%eax - jb .L043ctr32_three + jb .L045ctr32_three pshufd $128,%xmm1,%xmm6 por %xmm7,%xmm5 - je .L044ctr32_four + je .L046ctr32_four por %xmm7,%xmm6 call _aesni_encrypt6 movups (%esi),%xmm1 @@ -982,29 +1008,29 @@ aes_hw_ctr32_encrypt_blocks: movups %xmm4,32(%edi) movups %xmm5,48(%edi) movups %xmm6,64(%edi) - jmp .L040ctr32_ret + jmp .L042ctr32_ret .align 16 -.L037ctr32_one_shortcut: +.L039ctr32_one_shortcut: movups (%ebx),%xmm2 movl 240(%edx),%ecx -.L041ctr32_one: +.L043ctr32_one: movups (%edx),%xmm0 movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -.L045enc1_loop_7: +.L047enc1_loop_7: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz .L045enc1_loop_7 + jnz .L047enc1_loop_7 .byte 102,15,56,221,209 movups (%esi),%xmm6 xorps %xmm2,%xmm6 movups %xmm6,(%edi) - jmp .L040ctr32_ret + jmp .L042ctr32_ret .align 16 -.L042ctr32_two: +.L044ctr32_two: call _aesni_encrypt2 movups (%esi),%xmm5 movups 16(%esi),%xmm6 @@ -1012,9 +1038,9 @@ aes_hw_ctr32_encrypt_blocks: xorps %xmm6,%xmm3 movups %xmm2,(%edi) movups %xmm3,16(%edi) - jmp .L040ctr32_ret + jmp .L042ctr32_ret .align 16 -.L043ctr32_three: +.L045ctr32_three: call _aesni_encrypt3 movups (%esi),%xmm5 movups 16(%esi),%xmm6 @@ -1025,9 +1051,9 @@ aes_hw_ctr32_encrypt_blocks: xorps %xmm7,%xmm4 movups %xmm3,16(%edi) movups %xmm4,32(%edi) - jmp .L040ctr32_ret + jmp .L042ctr32_ret .align 16 -.L044ctr32_four: +.L046ctr32_four: call _aesni_encrypt4 movups (%esi),%xmm6 movups 16(%esi),%xmm7 @@ -1041,7 +1067,7 @@ aes_hw_ctr32_encrypt_blocks: xorps %xmm0,%xmm5 movups %xmm4,32(%edi) movups %xmm5,48(%edi) -.L040ctr32_ret: +.L042ctr32_ret: pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 pxor %xmm2,%xmm2 @@ -1078,12 +1104,12 @@ aes_hw_xts_encrypt: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -.L046enc1_loop_8: +.L048enc1_loop_8: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz .L046enc1_loop_8 + jnz .L048enc1_loop_8 .byte 102,15,56,221,209 movl 20(%esp),%esi movl 24(%esp),%edi @@ -1107,14 +1133,14 @@ aes_hw_xts_encrypt: movl %edx,%ebp movl %ecx,%ebx subl $96,%eax - jc .L047xts_enc_short + jc .L049xts_enc_short shll $4,%ecx movl $16,%ebx subl %ecx,%ebx leal 32(%edx,%ecx,1),%edx - jmp .L048xts_enc_loop6 + jmp .L050xts_enc_loop6 .align 16 -.L048xts_enc_loop6: +.L050xts_enc_loop6: pshufd $19,%xmm0,%xmm2 pxor %xmm0,%xmm0 movdqa %xmm1,(%esp) @@ -1203,23 +1229,23 @@ aes_hw_xts_encrypt: pcmpgtd %xmm1,%xmm0 pxor %xmm2,%xmm1 subl $96,%eax - jnc .L048xts_enc_loop6 + jnc .L050xts_enc_loop6 movl 240(%ebp),%ecx movl %ebp,%edx movl %ecx,%ebx -.L047xts_enc_short: +.L049xts_enc_short: addl $96,%eax - jz .L049xts_enc_done6x + jz .L051xts_enc_done6x movdqa %xmm1,%xmm5 cmpl $32,%eax - jb .L050xts_enc_one + jb .L052xts_enc_one pshufd $19,%xmm0,%xmm2 pxor %xmm0,%xmm0 paddq %xmm1,%xmm1 pand %xmm3,%xmm2 pcmpgtd %xmm1,%xmm0 pxor %xmm2,%xmm1 - je .L051xts_enc_two + je .L053xts_enc_two pshufd $19,%xmm0,%xmm2 pxor %xmm0,%xmm0 movdqa %xmm1,%xmm6 @@ -1228,7 +1254,7 @@ aes_hw_xts_encrypt: pcmpgtd %xmm1,%xmm0 pxor %xmm2,%xmm1 cmpl $64,%eax - jb .L052xts_enc_three + jb .L054xts_enc_three pshufd $19,%xmm0,%xmm2 pxor %xmm0,%xmm0 movdqa %xmm1,%xmm7 @@ -1238,7 +1264,7 @@ aes_hw_xts_encrypt: pxor %xmm2,%xmm1 movdqa %xmm5,(%esp) movdqa %xmm6,16(%esp) - je .L053xts_enc_four + je .L055xts_enc_four movdqa %xmm7,32(%esp) pshufd $19,%xmm0,%xmm7 movdqa %xmm1,48(%esp) @@ -1270,9 +1296,9 @@ aes_hw_xts_encrypt: movups %xmm5,48(%edi) movups %xmm6,64(%edi) leal 80(%edi),%edi - jmp .L054xts_enc_done + jmp .L056xts_enc_done .align 16 -.L050xts_enc_one: +.L052xts_enc_one: movups (%esi),%xmm2 leal 16(%esi),%esi xorps %xmm5,%xmm2 @@ -1280,20 +1306,20 @@ aes_hw_xts_encrypt: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -.L055enc1_loop_9: +.L057enc1_loop_9: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz .L055enc1_loop_9 + jnz .L057enc1_loop_9 .byte 102,15,56,221,209 xorps %xmm5,%xmm2 movups %xmm2,(%edi) leal 16(%edi),%edi movdqa %xmm5,%xmm1 - jmp .L054xts_enc_done + jmp .L056xts_enc_done .align 16 -.L051xts_enc_two: +.L053xts_enc_two: movaps %xmm1,%xmm6 movups (%esi),%xmm2 movups 16(%esi),%xmm3 @@ -1307,9 +1333,9 @@ aes_hw_xts_encrypt: movups %xmm3,16(%edi) leal 32(%edi),%edi movdqa %xmm6,%xmm1 - jmp .L054xts_enc_done + jmp .L056xts_enc_done .align 16 -.L052xts_enc_three: +.L054xts_enc_three: movaps %xmm1,%xmm7 movups (%esi),%xmm2 movups 16(%esi),%xmm3 @@ -1327,9 +1353,9 @@ aes_hw_xts_encrypt: movups %xmm4,32(%edi) leal 48(%edi),%edi movdqa %xmm7,%xmm1 - jmp .L054xts_enc_done + jmp .L056xts_enc_done .align 16 -.L053xts_enc_four: +.L055xts_enc_four: movaps %xmm1,%xmm6 movups (%esi),%xmm2 movups 16(%esi),%xmm3 @@ -1351,28 +1377,28 @@ aes_hw_xts_encrypt: movups %xmm5,48(%edi) leal 64(%edi),%edi movdqa %xmm6,%xmm1 - jmp .L054xts_enc_done + jmp .L056xts_enc_done .align 16 -.L049xts_enc_done6x: +.L051xts_enc_done6x: movl 112(%esp),%eax andl $15,%eax - jz .L056xts_enc_ret + jz .L058xts_enc_ret movdqa %xmm1,%xmm5 movl %eax,112(%esp) - jmp .L057xts_enc_steal + jmp .L059xts_enc_steal .align 16 -.L054xts_enc_done: +.L056xts_enc_done: movl 112(%esp),%eax pxor %xmm0,%xmm0 andl $15,%eax - jz .L056xts_enc_ret + jz .L058xts_enc_ret pcmpgtd %xmm1,%xmm0 movl %eax,112(%esp) pshufd $19,%xmm0,%xmm5 paddq %xmm1,%xmm1 pand 96(%esp),%xmm5 pxor %xmm1,%xmm5 -.L057xts_enc_steal: +.L059xts_enc_steal: movzbl (%esi),%ecx movzbl -16(%edi),%edx leal 1(%esi),%esi @@ -1380,7 +1406,7 @@ aes_hw_xts_encrypt: movb %dl,(%edi) leal 1(%edi),%edi subl $1,%eax - jnz .L057xts_enc_steal + jnz .L059xts_enc_steal subl 112(%esp),%edi movl %ebp,%edx movl %ebx,%ecx @@ -1390,16 +1416,16 @@ aes_hw_xts_encrypt: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -.L058enc1_loop_10: +.L060enc1_loop_10: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz .L058enc1_loop_10 + jnz .L060enc1_loop_10 .byte 102,15,56,221,209 xorps %xmm5,%xmm2 movups %xmm2,-16(%edi) -.L056xts_enc_ret: +.L058xts_enc_ret: pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 pxor %xmm2,%xmm2 @@ -1439,12 +1465,12 @@ aes_hw_xts_decrypt: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -.L059enc1_loop_11: +.L061enc1_loop_11: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz .L059enc1_loop_11 + jnz .L061enc1_loop_11 .byte 102,15,56,221,209 movl 20(%esp),%esi movl 24(%esp),%edi @@ -1473,14 +1499,14 @@ aes_hw_xts_decrypt: pcmpgtd %xmm1,%xmm0 andl $-16,%eax subl $96,%eax - jc .L060xts_dec_short + jc .L062xts_dec_short shll $4,%ecx movl $16,%ebx subl %ecx,%ebx leal 32(%edx,%ecx,1),%edx - jmp .L061xts_dec_loop6 + jmp .L063xts_dec_loop6 .align 16 -.L061xts_dec_loop6: +.L063xts_dec_loop6: pshufd $19,%xmm0,%xmm2 pxor %xmm0,%xmm0 movdqa %xmm1,(%esp) @@ -1569,23 +1595,23 @@ aes_hw_xts_decrypt: pcmpgtd %xmm1,%xmm0 pxor %xmm2,%xmm1 subl $96,%eax - jnc .L061xts_dec_loop6 + jnc .L063xts_dec_loop6 movl 240(%ebp),%ecx movl %ebp,%edx movl %ecx,%ebx -.L060xts_dec_short: +.L062xts_dec_short: addl $96,%eax - jz .L062xts_dec_done6x + jz .L064xts_dec_done6x movdqa %xmm1,%xmm5 cmpl $32,%eax - jb .L063xts_dec_one + jb .L065xts_dec_one pshufd $19,%xmm0,%xmm2 pxor %xmm0,%xmm0 paddq %xmm1,%xmm1 pand %xmm3,%xmm2 pcmpgtd %xmm1,%xmm0 pxor %xmm2,%xmm1 - je .L064xts_dec_two + je .L066xts_dec_two pshufd $19,%xmm0,%xmm2 pxor %xmm0,%xmm0 movdqa %xmm1,%xmm6 @@ -1594,7 +1620,7 @@ aes_hw_xts_decrypt: pcmpgtd %xmm1,%xmm0 pxor %xmm2,%xmm1 cmpl $64,%eax - jb .L065xts_dec_three + jb .L067xts_dec_three pshufd $19,%xmm0,%xmm2 pxor %xmm0,%xmm0 movdqa %xmm1,%xmm7 @@ -1604,7 +1630,7 @@ aes_hw_xts_decrypt: pxor %xmm2,%xmm1 movdqa %xmm5,(%esp) movdqa %xmm6,16(%esp) - je .L066xts_dec_four + je .L068xts_dec_four movdqa %xmm7,32(%esp) pshufd $19,%xmm0,%xmm7 movdqa %xmm1,48(%esp) @@ -1636,9 +1662,9 @@ aes_hw_xts_decrypt: movups %xmm5,48(%edi) movups %xmm6,64(%edi) leal 80(%edi),%edi - jmp .L067xts_dec_done + jmp .L069xts_dec_done .align 16 -.L063xts_dec_one: +.L065xts_dec_one: movups (%esi),%xmm2 leal 16(%esi),%esi xorps %xmm5,%xmm2 @@ -1646,20 +1672,20 @@ aes_hw_xts_decrypt: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -.L068dec1_loop_12: +.L070dec1_loop_12: .byte 102,15,56,222,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz .L068dec1_loop_12 + jnz .L070dec1_loop_12 .byte 102,15,56,223,209 xorps %xmm5,%xmm2 movups %xmm2,(%edi) leal 16(%edi),%edi movdqa %xmm5,%xmm1 - jmp .L067xts_dec_done + jmp .L069xts_dec_done .align 16 -.L064xts_dec_two: +.L066xts_dec_two: movaps %xmm1,%xmm6 movups (%esi),%xmm2 movups 16(%esi),%xmm3 @@ -1673,9 +1699,9 @@ aes_hw_xts_decrypt: movups %xmm3,16(%edi) leal 32(%edi),%edi movdqa %xmm6,%xmm1 - jmp .L067xts_dec_done + jmp .L069xts_dec_done .align 16 -.L065xts_dec_three: +.L067xts_dec_three: movaps %xmm1,%xmm7 movups (%esi),%xmm2 movups 16(%esi),%xmm3 @@ -1693,9 +1719,9 @@ aes_hw_xts_decrypt: movups %xmm4,32(%edi) leal 48(%edi),%edi movdqa %xmm7,%xmm1 - jmp .L067xts_dec_done + jmp .L069xts_dec_done .align 16 -.L066xts_dec_four: +.L068xts_dec_four: movaps %xmm1,%xmm6 movups (%esi),%xmm2 movups 16(%esi),%xmm3 @@ -1717,20 +1743,20 @@ aes_hw_xts_decrypt: movups %xmm5,48(%edi) leal 64(%edi),%edi movdqa %xmm6,%xmm1 - jmp .L067xts_dec_done + jmp .L069xts_dec_done .align 16 -.L062xts_dec_done6x: +.L064xts_dec_done6x: movl 112(%esp),%eax andl $15,%eax - jz .L069xts_dec_ret + jz .L071xts_dec_ret movl %eax,112(%esp) - jmp .L070xts_dec_only_one_more + jmp .L072xts_dec_only_one_more .align 16 -.L067xts_dec_done: +.L069xts_dec_done: movl 112(%esp),%eax pxor %xmm0,%xmm0 andl $15,%eax - jz .L069xts_dec_ret + jz .L071xts_dec_ret pcmpgtd %xmm1,%xmm0 movl %eax,112(%esp) pshufd $19,%xmm0,%xmm2 @@ -1740,7 +1766,7 @@ aes_hw_xts_decrypt: pand %xmm3,%xmm2 pcmpgtd %xmm1,%xmm0 pxor %xmm2,%xmm1 -.L070xts_dec_only_one_more: +.L072xts_dec_only_one_more: pshufd $19,%xmm0,%xmm5 movdqa %xmm1,%xmm6 paddq %xmm1,%xmm1 @@ -1754,16 +1780,16 @@ aes_hw_xts_decrypt: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -.L071dec1_loop_13: +.L073dec1_loop_13: .byte 102,15,56,222,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz .L071dec1_loop_13 + jnz .L073dec1_loop_13 .byte 102,15,56,223,209 xorps %xmm5,%xmm2 movups %xmm2,(%edi) -.L072xts_dec_steal: +.L074xts_dec_steal: movzbl 16(%esi),%ecx movzbl (%edi),%edx leal 1(%esi),%esi @@ -1771,7 +1797,7 @@ aes_hw_xts_decrypt: movb %dl,16(%edi) leal 1(%edi),%edi subl $1,%eax - jnz .L072xts_dec_steal + jnz .L074xts_dec_steal subl 112(%esp),%edi movl %ebp,%edx movl %ebx,%ecx @@ -1781,16 +1807,16 @@ aes_hw_xts_decrypt: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -.L073dec1_loop_14: +.L075dec1_loop_14: .byte 102,15,56,222,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz .L073dec1_loop_14 + jnz .L075dec1_loop_14 .byte 102,15,56,223,209 xorps %xmm6,%xmm2 movups %xmm2,(%edi) -.L069xts_dec_ret: +.L071xts_dec_ret: pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 pxor %xmm2,%xmm2 @@ -1831,7 +1857,7 @@ aes_hw_cbc_encrypt: movl 32(%esp),%edx movl 36(%esp),%ebp testl %eax,%eax - jz .L074cbc_abort + jz .L076cbc_abort cmpl $0,40(%esp) xchgl %esp,%ebx movups (%ebp),%xmm7 @@ -1839,14 +1865,14 @@ aes_hw_cbc_encrypt: movl %edx,%ebp movl %ebx,16(%esp) movl %ecx,%ebx - je .L075cbc_decrypt + je .L077cbc_decrypt movaps %xmm7,%xmm2 cmpl $16,%eax - jb .L076cbc_enc_tail + jb .L078cbc_enc_tail subl $16,%eax - jmp .L077cbc_enc_loop + jmp .L079cbc_enc_loop .align 16 -.L077cbc_enc_loop: +.L079cbc_enc_loop: movups (%esi),%xmm7 leal 16(%esi),%esi movups (%edx),%xmm0 @@ -1854,25 +1880,25 @@ aes_hw_cbc_encrypt: xorps %xmm0,%xmm7 leal 32(%edx),%edx xorps %xmm7,%xmm2 -.L078enc1_loop_15: +.L080enc1_loop_15: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz .L078enc1_loop_15 + jnz .L080enc1_loop_15 .byte 102,15,56,221,209 movl %ebx,%ecx movl %ebp,%edx movups %xmm2,(%edi) leal 16(%edi),%edi subl $16,%eax - jnc .L077cbc_enc_loop + jnc .L079cbc_enc_loop addl $16,%eax - jnz .L076cbc_enc_tail + jnz .L078cbc_enc_tail movaps %xmm2,%xmm7 pxor %xmm2,%xmm2 - jmp .L079cbc_ret -.L076cbc_enc_tail: + jmp .L081cbc_ret +.L078cbc_enc_tail: movl %eax,%ecx .long 2767451785 movl $16,%ecx @@ -1883,20 +1909,20 @@ aes_hw_cbc_encrypt: movl %ebx,%ecx movl %edi,%esi movl %ebp,%edx - jmp .L077cbc_enc_loop + jmp .L079cbc_enc_loop .align 16 -.L075cbc_decrypt: +.L077cbc_decrypt: cmpl $80,%eax - jbe .L080cbc_dec_tail + jbe .L082cbc_dec_tail movaps %xmm7,(%esp) subl $80,%eax - jmp .L081cbc_dec_loop6_enter + jmp .L083cbc_dec_loop6_enter .align 16 -.L082cbc_dec_loop6: +.L084cbc_dec_loop6: movaps %xmm0,(%esp) movups %xmm7,(%edi) leal 16(%edi),%edi -.L081cbc_dec_loop6_enter: +.L083cbc_dec_loop6_enter: movdqu (%esi),%xmm2 movdqu 16(%esi),%xmm3 movdqu 32(%esi),%xmm4 @@ -1926,28 +1952,28 @@ aes_hw_cbc_encrypt: movups %xmm6,64(%edi) leal 80(%edi),%edi subl $96,%eax - ja .L082cbc_dec_loop6 + ja .L084cbc_dec_loop6 movaps %xmm7,%xmm2 movaps %xmm0,%xmm7 addl $80,%eax - jle .L083cbc_dec_clear_tail_collected + jle .L085cbc_dec_clear_tail_collected movups %xmm2,(%edi) leal 16(%edi),%edi -.L080cbc_dec_tail: +.L082cbc_dec_tail: movups (%esi),%xmm2 movaps %xmm2,%xmm6 cmpl $16,%eax - jbe .L084cbc_dec_one + jbe .L086cbc_dec_one movups 16(%esi),%xmm3 movaps %xmm3,%xmm5 cmpl $32,%eax - jbe .L085cbc_dec_two + jbe .L087cbc_dec_two movups 32(%esi),%xmm4 cmpl $48,%eax - jbe .L086cbc_dec_three + jbe .L088cbc_dec_three movups 48(%esi),%xmm5 cmpl $64,%eax - jbe .L087cbc_dec_four + jbe .L089cbc_dec_four movups 64(%esi),%xmm6 movaps %xmm7,(%esp) movups (%esi),%xmm2 @@ -1974,26 +2000,26 @@ aes_hw_cbc_encrypt: movaps %xmm6,%xmm2 pxor %xmm6,%xmm6 subl $80,%eax - jmp .L088cbc_dec_tail_collected + jmp .L090cbc_dec_tail_collected .align 16 -.L084cbc_dec_one: +.L086cbc_dec_one: movups (%edx),%xmm0 movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -.L089dec1_loop_16: +.L091dec1_loop_16: .byte 102,15,56,222,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz .L089dec1_loop_16 + jnz .L091dec1_loop_16 .byte 102,15,56,223,209 xorps %xmm7,%xmm2 movaps %xmm6,%xmm7 subl $16,%eax - jmp .L088cbc_dec_tail_collected + jmp .L090cbc_dec_tail_collected .align 16 -.L085cbc_dec_two: +.L087cbc_dec_two: call _aesni_decrypt2 xorps %xmm7,%xmm2 xorps %xmm6,%xmm3 @@ -2003,9 +2029,9 @@ aes_hw_cbc_encrypt: leal 16(%edi),%edi movaps %xmm5,%xmm7 subl $32,%eax - jmp .L088cbc_dec_tail_collected + jmp .L090cbc_dec_tail_collected .align 16 -.L086cbc_dec_three: +.L088cbc_dec_three: call _aesni_decrypt3 xorps %xmm7,%xmm2 xorps %xmm6,%xmm3 @@ -2018,9 +2044,9 @@ aes_hw_cbc_encrypt: leal 32(%edi),%edi movups 32(%esi),%xmm7 subl $48,%eax - jmp .L088cbc_dec_tail_collected + jmp .L090cbc_dec_tail_collected .align 16 -.L087cbc_dec_four: +.L089cbc_dec_four: call _aesni_decrypt4 movups 16(%esi),%xmm1 movups 32(%esi),%xmm0 @@ -2038,21 +2064,21 @@ aes_hw_cbc_encrypt: movaps %xmm5,%xmm2 pxor %xmm5,%xmm5 subl $64,%eax - jmp .L088cbc_dec_tail_collected + jmp .L090cbc_dec_tail_collected .align 16 -.L083cbc_dec_clear_tail_collected: +.L085cbc_dec_clear_tail_collected: pxor %xmm3,%xmm3 pxor %xmm4,%xmm4 pxor %xmm5,%xmm5 pxor %xmm6,%xmm6 -.L088cbc_dec_tail_collected: +.L090cbc_dec_tail_collected: andl $15,%eax - jnz .L090cbc_dec_tail_partial + jnz .L092cbc_dec_tail_partial movups %xmm2,(%edi) pxor %xmm0,%xmm0 - jmp .L079cbc_ret + jmp .L081cbc_ret .align 16 -.L090cbc_dec_tail_partial: +.L092cbc_dec_tail_partial: movaps %xmm2,(%esp) pxor %xmm0,%xmm0 movl $16,%ecx @@ -2060,14 +2086,14 @@ aes_hw_cbc_encrypt: subl %eax,%ecx .long 2767451785 movdqa %xmm2,(%esp) -.L079cbc_ret: +.L081cbc_ret: movl 16(%esp),%esp movl 36(%esp),%ebp pxor %xmm2,%xmm2 pxor %xmm1,%xmm1 movups %xmm7,(%ebp) pxor %xmm7,%xmm7 -.L074cbc_abort: +.L076cbc_abort: popl %edi popl %esi popl %ebx @@ -2081,13 +2107,13 @@ _aesni_set_encrypt_key: pushl %ebp pushl %ebx testl %eax,%eax - jz .L091bad_pointer + jz .L093bad_pointer testl %edx,%edx - jz .L091bad_pointer - call .L092pic -.L092pic: + jz .L093bad_pointer + call .L094pic +.L094pic: popl %ebx - leal .Lkey_const-.L092pic(%ebx),%ebx + leal .Lkey_const-.L094pic(%ebx),%ebx leal OPENSSL_ia32cap_P-.Lkey_const(%ebx),%ebp movups (%eax),%xmm0 xorps %xmm4,%xmm4 @@ -2095,45 +2121,45 @@ _aesni_set_encrypt_key: leal 16(%edx),%edx andl $268437504,%ebp cmpl $256,%ecx - je .L09314rounds + je .L09514rounds cmpl $192,%ecx - je .L09412rounds + je .L09612rounds cmpl $128,%ecx - jne .L095bad_keybits + jne .L097bad_keybits .align 16 -.L09610rounds: +.L09810rounds: cmpl $268435456,%ebp - je .L09710rounds_alt + je .L09910rounds_alt movl $9,%ecx movups %xmm0,-16(%edx) .byte 102,15,58,223,200,1 - call .L098key_128_cold + call .L100key_128_cold .byte 102,15,58,223,200,2 - call .L099key_128 + call .L101key_128 .byte 102,15,58,223,200,4 - call .L099key_128 + call .L101key_128 .byte 102,15,58,223,200,8 - call .L099key_128 + call .L101key_128 .byte 102,15,58,223,200,16 - call .L099key_128 + call .L101key_128 .byte 102,15,58,223,200,32 - call .L099key_128 + call .L101key_128 .byte 102,15,58,223,200,64 - call .L099key_128 + call .L101key_128 .byte 102,15,58,223,200,128 - call .L099key_128 + call .L101key_128 .byte 102,15,58,223,200,27 - call .L099key_128 + call .L101key_128 .byte 102,15,58,223,200,54 - call .L099key_128 + call .L101key_128 movups %xmm0,(%edx) movl %ecx,80(%edx) - jmp .L100good_key + jmp .L102good_key .align 16 -.L099key_128: +.L101key_128: movups %xmm0,(%edx) leal 16(%edx),%edx -.L098key_128_cold: +.L100key_128_cold: shufps $16,%xmm0,%xmm4 xorps %xmm4,%xmm0 shufps $140,%xmm0,%xmm4 @@ -2142,13 +2168,13 @@ _aesni_set_encrypt_key: xorps %xmm1,%xmm0 ret .align 16 -.L09710rounds_alt: +.L09910rounds_alt: movdqa (%ebx),%xmm5 movl $8,%ecx movdqa 32(%ebx),%xmm4 movdqa %xmm0,%xmm2 movdqu %xmm0,-16(%edx) -.L101loop_key128: +.L103loop_key128: .byte 102,15,56,0,197 .byte 102,15,56,221,196 pslld $1,%xmm4 @@ -2164,7 +2190,7 @@ _aesni_set_encrypt_key: movdqu %xmm0,-16(%edx) movdqa %xmm0,%xmm2 decl %ecx - jnz .L101loop_key128 + jnz .L103loop_key128 movdqa 48(%ebx),%xmm4 .byte 102,15,56,0,197 .byte 102,15,56,221,196 @@ -2192,41 +2218,41 @@ _aesni_set_encrypt_key: movdqu %xmm0,16(%edx) movl $9,%ecx movl %ecx,96(%edx) - jmp .L100good_key + jmp .L102good_key .align 16 -.L09412rounds: +.L09612rounds: movq 16(%eax),%xmm2 cmpl $268435456,%ebp - je .L10212rounds_alt + je .L10412rounds_alt movl $11,%ecx movups %xmm0,-16(%edx) .byte 102,15,58,223,202,1 - call .L103key_192a_cold + call .L105key_192a_cold .byte 102,15,58,223,202,2 - call .L104key_192b + call .L106key_192b .byte 102,15,58,223,202,4 - call .L105key_192a + call .L107key_192a .byte 102,15,58,223,202,8 - call .L104key_192b + call .L106key_192b .byte 102,15,58,223,202,16 - call .L105key_192a + call .L107key_192a .byte 102,15,58,223,202,32 - call .L104key_192b + call .L106key_192b .byte 102,15,58,223,202,64 - call .L105key_192a + call .L107key_192a .byte 102,15,58,223,202,128 - call .L104key_192b + call .L106key_192b movups %xmm0,(%edx) movl %ecx,48(%edx) - jmp .L100good_key + jmp .L102good_key .align 16 -.L105key_192a: +.L107key_192a: movups %xmm0,(%edx) leal 16(%edx),%edx .align 16 -.L103key_192a_cold: +.L105key_192a_cold: movaps %xmm2,%xmm5 -.L106key_192b_warm: +.L108key_192b_warm: shufps $16,%xmm0,%xmm4 movdqa %xmm2,%xmm3 xorps %xmm4,%xmm0 @@ -2240,21 +2266,21 @@ _aesni_set_encrypt_key: pxor %xmm3,%xmm2 ret .align 16 -.L104key_192b: +.L106key_192b: movaps %xmm0,%xmm3 shufps $68,%xmm0,%xmm5 movups %xmm5,(%edx) shufps $78,%xmm2,%xmm3 movups %xmm3,16(%edx) leal 32(%edx),%edx - jmp .L106key_192b_warm + jmp .L108key_192b_warm .align 16 -.L10212rounds_alt: +.L10412rounds_alt: movdqa 16(%ebx),%xmm5 movdqa 32(%ebx),%xmm4 movl $8,%ecx movdqu %xmm0,-16(%edx) -.L107loop_key192: +.L109loop_key192: movq %xmm2,(%edx) movdqa %xmm2,%xmm1 .byte 102,15,56,0,213 @@ -2276,54 +2302,54 @@ _aesni_set_encrypt_key: pxor %xmm3,%xmm2 movdqu %xmm0,-16(%edx) decl %ecx - jnz .L107loop_key192 + jnz .L109loop_key192 movl $11,%ecx movl %ecx,32(%edx) - jmp .L100good_key + jmp .L102good_key .align 16 -.L09314rounds: +.L09514rounds: movups 16(%eax),%xmm2 leal 16(%edx),%edx cmpl $268435456,%ebp - je .L10814rounds_alt + je .L11014rounds_alt movl $13,%ecx movups %xmm0,-32(%edx) movups %xmm2,-16(%edx) .byte 102,15,58,223,202,1 - call .L109key_256a_cold + call .L111key_256a_cold .byte 102,15,58,223,200,1 - call .L110key_256b + call .L112key_256b .byte 102,15,58,223,202,2 - call .L111key_256a + call .L113key_256a .byte 102,15,58,223,200,2 - call .L110key_256b + call .L112key_256b .byte 102,15,58,223,202,4 - call .L111key_256a + call .L113key_256a .byte 102,15,58,223,200,4 - call .L110key_256b + call .L112key_256b .byte 102,15,58,223,202,8 - call .L111key_256a + call .L113key_256a .byte 102,15,58,223,200,8 - call .L110key_256b + call .L112key_256b .byte 102,15,58,223,202,16 - call .L111key_256a + call .L113key_256a .byte 102,15,58,223,200,16 - call .L110key_256b + call .L112key_256b .byte 102,15,58,223,202,32 - call .L111key_256a + call .L113key_256a .byte 102,15,58,223,200,32 - call .L110key_256b + call .L112key_256b .byte 102,15,58,223,202,64 - call .L111key_256a + call .L113key_256a movups %xmm0,(%edx) movl %ecx,16(%edx) xorl %eax,%eax - jmp .L100good_key + jmp .L102good_key .align 16 -.L111key_256a: +.L113key_256a: movups %xmm2,(%edx) leal 16(%edx),%edx -.L109key_256a_cold: +.L111key_256a_cold: shufps $16,%xmm0,%xmm4 xorps %xmm4,%xmm0 shufps $140,%xmm0,%xmm4 @@ -2332,7 +2358,7 @@ _aesni_set_encrypt_key: xorps %xmm1,%xmm0 ret .align 16 -.L110key_256b: +.L112key_256b: movups %xmm0,(%edx) leal 16(%edx),%edx shufps $16,%xmm2,%xmm4 @@ -2343,14 +2369,14 @@ _aesni_set_encrypt_key: xorps %xmm1,%xmm2 ret .align 16 -.L10814rounds_alt: +.L11014rounds_alt: movdqa (%ebx),%xmm5 movdqa 32(%ebx),%xmm4 movl $7,%ecx movdqu %xmm0,-32(%edx) movdqa %xmm2,%xmm1 movdqu %xmm2,-16(%edx) -.L112loop_key256: +.L114loop_key256: .byte 102,15,56,0,213 .byte 102,15,56,221,212 movdqa %xmm0,%xmm3 @@ -2364,7 +2390,7 @@ _aesni_set_encrypt_key: pxor %xmm2,%xmm0 movdqu %xmm0,(%edx) decl %ecx - jz .L113done_key256 + jz .L115done_key256 pshufd $255,%xmm0,%xmm2 pxor %xmm3,%xmm3 .byte 102,15,56,221,211 @@ -2379,11 +2405,11 @@ _aesni_set_encrypt_key: movdqu %xmm2,16(%edx) leal 32(%edx),%edx movdqa %xmm2,%xmm1 - jmp .L112loop_key256 -.L113done_key256: + jmp .L114loop_key256 +.L115done_key256: movl $13,%ecx movl %ecx,16(%edx) -.L100good_key: +.L102good_key: pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 pxor %xmm2,%xmm2 @@ -2395,13 +2421,13 @@ _aesni_set_encrypt_key: popl %ebp ret .align 4 -.L091bad_pointer: +.L093bad_pointer: movl $-1,%eax popl %ebx popl %ebp ret .align 4 -.L095bad_keybits: +.L097bad_keybits: pxor %xmm0,%xmm0 movl $-2,%eax popl %ebx @@ -2414,6 +2440,18 @@ _aesni_set_encrypt_key: .align 16 aes_hw_set_encrypt_key: .L_aes_hw_set_encrypt_key_begin: +#ifndef NDEBUG + pushl %ebx + pushl %edx + call .L116pic +.L116pic: + popl %ebx + leal BORINGSSL_function_hit+3-.L116pic(%ebx),%ebx + movl $1,%edx + movb %dl,(%ebx) + popl %edx + popl %ebx +#endif movl 4(%esp),%eax movl 8(%esp),%ecx movl 12(%esp),%edx @@ -2433,7 +2471,7 @@ aes_hw_set_decrypt_key: movl 12(%esp),%edx shll $4,%ecx testl %eax,%eax - jnz .L114dec_key_ret + jnz .L117dec_key_ret leal 16(%edx,%ecx,1),%eax movups (%edx),%xmm0 movups (%eax),%xmm1 @@ -2441,7 +2479,7 @@ aes_hw_set_decrypt_key: movups %xmm1,(%edx) leal 16(%edx),%edx leal -16(%eax),%eax -.L115dec_key_inverse: +.L118dec_key_inverse: movups (%edx),%xmm0 movups (%eax),%xmm1 .byte 102,15,56,219,192 @@ -2451,14 +2489,14 @@ aes_hw_set_decrypt_key: movups %xmm0,16(%eax) movups %xmm1,-16(%edx) cmpl %edx,%eax - ja .L115dec_key_inverse + ja .L118dec_key_inverse movups (%edx),%xmm0 .byte 102,15,56,219,192 movups %xmm0,(%edx) pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 xorl %eax,%eax -.L114dec_key_ret: +.L117dec_key_ret: ret .size aes_hw_set_decrypt_key,.-.L_aes_hw_set_decrypt_key_begin .align 64 diff --git a/third_party/boringssl/kit/linux-x86/crypto/fipsmodule/ghash-ssse3-x86.S b/third_party/boringssl/kit/linux-x86/crypto/fipsmodule/ghash-ssse3-x86.S new file mode 100644 index 00000000..7aa0ea52 --- /dev/null +++ b/third_party/boringssl/kit/linux-x86/crypto/fipsmodule/ghash-ssse3-x86.S @@ -0,0 +1,293 @@ +# This file is generated from a similarly-named Perl script in the BoringSSL +# source tree. Do not edit by hand. + +#if defined(__i386__) +#if defined(BORINGSSL_PREFIX) +#include +#endif +.text +.globl gcm_gmult_ssse3 +.hidden gcm_gmult_ssse3 +.type gcm_gmult_ssse3,@function +.align 16 +gcm_gmult_ssse3: +.L_gcm_gmult_ssse3_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 20(%esp),%edi + movl 24(%esp),%esi + movdqu (%edi),%xmm0 + call .L000pic_point +.L000pic_point: + popl %eax + movdqa .Lreverse_bytes-.L000pic_point(%eax),%xmm7 + movdqa .Llow4_mask-.L000pic_point(%eax),%xmm2 +.byte 102,15,56,0,199 + movdqa %xmm2,%xmm1 + pandn %xmm0,%xmm1 + psrld $4,%xmm1 + pand %xmm2,%xmm0 + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + movl $5,%eax +.L001loop_row_1: + movdqa (%esi),%xmm4 + leal 16(%esi),%esi + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + pxor %xmm5,%xmm2 + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + subl $1,%eax + jnz .L001loop_row_1 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movl $5,%eax +.L002loop_row_2: + movdqa (%esi),%xmm4 + leal 16(%esi),%esi + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + pxor %xmm5,%xmm2 + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + subl $1,%eax + jnz .L002loop_row_2 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movl $6,%eax +.L003loop_row_3: + movdqa (%esi),%xmm4 + leal 16(%esi),%esi + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + pxor %xmm5,%xmm2 + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + subl $1,%eax + jnz .L003loop_row_3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 +.byte 102,15,56,0,215 + movdqu %xmm2,(%edi) + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + pxor %xmm4,%xmm4 + pxor %xmm5,%xmm5 + pxor %xmm6,%xmm6 + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size gcm_gmult_ssse3,.-.L_gcm_gmult_ssse3_begin +.globl gcm_ghash_ssse3 +.hidden gcm_ghash_ssse3 +.type gcm_ghash_ssse3,@function +.align 16 +gcm_ghash_ssse3: +.L_gcm_ghash_ssse3_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 20(%esp),%edi + movl 24(%esp),%esi + movl 28(%esp),%edx + movl 32(%esp),%ecx + movdqu (%edi),%xmm0 + call .L004pic_point +.L004pic_point: + popl %ebx + movdqa .Lreverse_bytes-.L004pic_point(%ebx),%xmm7 + andl $-16,%ecx +.byte 102,15,56,0,199 + pxor %xmm3,%xmm3 +.L005loop_ghash: + movdqa .Llow4_mask-.L004pic_point(%ebx),%xmm2 + movdqu (%edx),%xmm1 +.byte 102,15,56,0,207 + pxor %xmm1,%xmm0 + movdqa %xmm2,%xmm1 + pandn %xmm0,%xmm1 + psrld $4,%xmm1 + pand %xmm2,%xmm0 + pxor %xmm2,%xmm2 + movl $5,%eax +.L006loop_row_4: + movdqa (%esi),%xmm4 + leal 16(%esi),%esi + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + pxor %xmm5,%xmm2 + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + subl $1,%eax + jnz .L006loop_row_4 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movl $5,%eax +.L007loop_row_5: + movdqa (%esi),%xmm4 + leal 16(%esi),%esi + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + pxor %xmm5,%xmm2 + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + subl $1,%eax + jnz .L007loop_row_5 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movl $6,%eax +.L008loop_row_6: + movdqa (%esi),%xmm4 + leal 16(%esi),%esi + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + pxor %xmm5,%xmm2 + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + subl $1,%eax + jnz .L008loop_row_6 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movdqa %xmm2,%xmm0 + leal -256(%esi),%esi + leal 16(%edx),%edx + subl $16,%ecx + jnz .L005loop_ghash +.byte 102,15,56,0,199 + movdqu %xmm0,(%edi) + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + pxor %xmm4,%xmm4 + pxor %xmm5,%xmm5 + pxor %xmm6,%xmm6 + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size gcm_ghash_ssse3,.-.L_gcm_ghash_ssse3_begin +.align 16 +.Lreverse_bytes: +.byte 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 +.align 16 +.Llow4_mask: +.long 252645135,252645135,252645135,252645135 +#endif diff --git a/third_party/boringssl/kit/linux-x86/crypto/fipsmodule/vpaes-x86.S b/third_party/boringssl/kit/linux-x86/crypto/fipsmodule/vpaes-x86.S index b2c63e57..4ea92ed0 100644 --- a/third_party/boringssl/kit/linux-x86/crypto/fipsmodule/vpaes-x86.S +++ b/third_party/boringssl/kit/linux-x86/crypto/fipsmodule/vpaes-x86.S @@ -6,6 +6,8 @@ #include #endif .text +#ifndef NDEBUG +#endif .align 64 .L_vpaes_consts: .long 218628480,235210255,168496130,67568393 @@ -483,6 +485,18 @@ vpaes_set_encrypt_key: pushl %ebx pushl %esi pushl %edi +#ifndef NDEBUG + pushl %ebx + pushl %edx + call .L016pic +.L016pic: + popl %ebx + leal BORINGSSL_function_hit+5-.L016pic(%ebx),%ebx + movl $1,%edx + movb %dl,(%ebx) + popl %edx + popl %ebx +#endif movl 20(%esp),%esi leal -56(%esp),%ebx movl 24(%esp),%eax @@ -496,9 +510,9 @@ vpaes_set_encrypt_key: movl %ebx,240(%edx) movl $48,%ecx movl $0,%edi - leal .L_vpaes_consts+0x30-.L016pic_point,%ebp + leal .L_vpaes_consts+0x30-.L017pic_point,%ebp call _vpaes_schedule_core -.L016pic_point: +.L017pic_point: movl 48(%esp),%esp xorl %eax,%eax popl %edi @@ -535,9 +549,9 @@ vpaes_set_decrypt_key: shrl $1,%ecx andl $32,%ecx xorl $32,%ecx - leal .L_vpaes_consts+0x30-.L017pic_point,%ebp + leal .L_vpaes_consts+0x30-.L018pic_point,%ebp call _vpaes_schedule_core -.L017pic_point: +.L018pic_point: movl 48(%esp),%esp xorl %eax,%eax popl %edi @@ -556,9 +570,21 @@ vpaes_encrypt: pushl %ebx pushl %esi pushl %edi - leal .L_vpaes_consts+0x30-.L018pic_point,%ebp +#ifndef NDEBUG + pushl %ebx + pushl %edx + call .L019pic +.L019pic: + popl %ebx + leal BORINGSSL_function_hit+4-.L019pic(%ebx),%ebx + movl $1,%edx + movb %dl,(%ebx) + popl %edx + popl %ebx +#endif + leal .L_vpaes_consts+0x30-.L020pic_point,%ebp call _vpaes_preheat -.L018pic_point: +.L020pic_point: movl 20(%esp),%esi leal -56(%esp),%ebx movl 24(%esp),%edi @@ -586,9 +612,9 @@ vpaes_decrypt: pushl %ebx pushl %esi pushl %edi - leal .L_vpaes_consts+0x30-.L019pic_point,%ebp + leal .L_vpaes_consts+0x30-.L021pic_point,%ebp call _vpaes_preheat -.L019pic_point: +.L021pic_point: movl 20(%esp),%esi leal -56(%esp),%ebx movl 24(%esp),%edi @@ -621,7 +647,7 @@ vpaes_cbc_encrypt: movl 28(%esp),%eax movl 32(%esp),%edx subl $16,%eax - jc .L020cbc_abort + jc .L022cbc_abort leal -56(%esp),%ebx movl 36(%esp),%ebp andl $-16,%ebx @@ -634,14 +660,14 @@ vpaes_cbc_encrypt: movl %edx,4(%esp) movl %ebp,8(%esp) movl %eax,%edi - leal .L_vpaes_consts+0x30-.L021pic_point,%ebp + leal .L_vpaes_consts+0x30-.L023pic_point,%ebp call _vpaes_preheat -.L021pic_point: +.L023pic_point: cmpl $0,%ecx - je .L022cbc_dec_loop - jmp .L023cbc_enc_loop + je .L024cbc_dec_loop + jmp .L025cbc_enc_loop .align 16 -.L023cbc_enc_loop: +.L025cbc_enc_loop: movdqu (%esi),%xmm0 pxor %xmm1,%xmm0 call _vpaes_encrypt_core @@ -651,10 +677,10 @@ vpaes_cbc_encrypt: movdqu %xmm0,(%ebx,%esi,1) leal 16(%esi),%esi subl $16,%edi - jnc .L023cbc_enc_loop - jmp .L024cbc_done + jnc .L025cbc_enc_loop + jmp .L026cbc_done .align 16 -.L022cbc_dec_loop: +.L024cbc_dec_loop: movdqu (%esi),%xmm0 movdqa %xmm1,16(%esp) movdqa %xmm0,32(%esp) @@ -666,12 +692,12 @@ vpaes_cbc_encrypt: movdqu %xmm0,(%ebx,%esi,1) leal 16(%esi),%esi subl $16,%edi - jnc .L022cbc_dec_loop -.L024cbc_done: + jnc .L024cbc_dec_loop +.L026cbc_done: movl 8(%esp),%ebx movl 48(%esp),%esp movdqu %xmm1,(%ebx) -.L020cbc_abort: +.L022cbc_abort: popl %edi popl %esi popl %ebx diff --git a/third_party/boringssl/kit/linux-x86/crypto/test/trampoline-x86.S b/third_party/boringssl/kit/linux-x86/crypto/test/trampoline-x86.S new file mode 100644 index 00000000..2222347a --- /dev/null +++ b/third_party/boringssl/kit/linux-x86/crypto/test/trampoline-x86.S @@ -0,0 +1,205 @@ +# This file is generated from a similarly-named Perl script in the BoringSSL +# source tree. Do not edit by hand. + +#if defined(__i386__) +#if defined(BORINGSSL_PREFIX) +#include +#endif +.text +.globl abi_test_trampoline +.hidden abi_test_trampoline +.type abi_test_trampoline,@function +.align 16 +abi_test_trampoline: +.L_abi_test_trampoline_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 24(%esp),%ecx + movl (%ecx),%esi + movl 4(%ecx),%edi + movl 8(%ecx),%ebx + movl 12(%ecx),%ebp + subl $44,%esp + movl 72(%esp),%eax + xorl %ecx,%ecx +.L000loop: + cmpl 76(%esp),%ecx + jae .L001loop_done + movl (%eax,%ecx,4),%edx + movl %edx,(%esp,%ecx,4) + addl $1,%ecx + jmp .L000loop +.L001loop_done: + call *64(%esp) + addl $44,%esp + movl 24(%esp),%ecx + movl %esi,(%ecx) + movl %edi,4(%ecx) + movl %ebx,8(%ecx) + movl %ebp,12(%ecx) + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size abi_test_trampoline,.-.L_abi_test_trampoline_begin +.globl abi_test_get_and_clear_direction_flag +.hidden abi_test_get_and_clear_direction_flag +.type abi_test_get_and_clear_direction_flag,@function +.align 16 +abi_test_get_and_clear_direction_flag: +.L_abi_test_get_and_clear_direction_flag_begin: + pushfl + popl %eax + andl $1024,%eax + shrl $10,%eax + cld + ret +.size abi_test_get_and_clear_direction_flag,.-.L_abi_test_get_and_clear_direction_flag_begin +.globl abi_test_set_direction_flag +.hidden abi_test_set_direction_flag +.type abi_test_set_direction_flag,@function +.align 16 +abi_test_set_direction_flag: +.L_abi_test_set_direction_flag_begin: + std + ret +.size abi_test_set_direction_flag,.-.L_abi_test_set_direction_flag_begin +.globl abi_test_clobber_eax +.hidden abi_test_clobber_eax +.type abi_test_clobber_eax,@function +.align 16 +abi_test_clobber_eax: +.L_abi_test_clobber_eax_begin: + xorl %eax,%eax + ret +.size abi_test_clobber_eax,.-.L_abi_test_clobber_eax_begin +.globl abi_test_clobber_ebx +.hidden abi_test_clobber_ebx +.type abi_test_clobber_ebx,@function +.align 16 +abi_test_clobber_ebx: +.L_abi_test_clobber_ebx_begin: + xorl %ebx,%ebx + ret +.size abi_test_clobber_ebx,.-.L_abi_test_clobber_ebx_begin +.globl abi_test_clobber_ecx +.hidden abi_test_clobber_ecx +.type abi_test_clobber_ecx,@function +.align 16 +abi_test_clobber_ecx: +.L_abi_test_clobber_ecx_begin: + xorl %ecx,%ecx + ret +.size abi_test_clobber_ecx,.-.L_abi_test_clobber_ecx_begin +.globl abi_test_clobber_edx +.hidden abi_test_clobber_edx +.type abi_test_clobber_edx,@function +.align 16 +abi_test_clobber_edx: +.L_abi_test_clobber_edx_begin: + xorl %edx,%edx + ret +.size abi_test_clobber_edx,.-.L_abi_test_clobber_edx_begin +.globl abi_test_clobber_edi +.hidden abi_test_clobber_edi +.type abi_test_clobber_edi,@function +.align 16 +abi_test_clobber_edi: +.L_abi_test_clobber_edi_begin: + xorl %edi,%edi + ret +.size abi_test_clobber_edi,.-.L_abi_test_clobber_edi_begin +.globl abi_test_clobber_esi +.hidden abi_test_clobber_esi +.type abi_test_clobber_esi,@function +.align 16 +abi_test_clobber_esi: +.L_abi_test_clobber_esi_begin: + xorl %esi,%esi + ret +.size abi_test_clobber_esi,.-.L_abi_test_clobber_esi_begin +.globl abi_test_clobber_ebp +.hidden abi_test_clobber_ebp +.type abi_test_clobber_ebp,@function +.align 16 +abi_test_clobber_ebp: +.L_abi_test_clobber_ebp_begin: + xorl %ebp,%ebp + ret +.size abi_test_clobber_ebp,.-.L_abi_test_clobber_ebp_begin +.globl abi_test_clobber_xmm0 +.hidden abi_test_clobber_xmm0 +.type abi_test_clobber_xmm0,@function +.align 16 +abi_test_clobber_xmm0: +.L_abi_test_clobber_xmm0_begin: + pxor %xmm0,%xmm0 + ret +.size abi_test_clobber_xmm0,.-.L_abi_test_clobber_xmm0_begin +.globl abi_test_clobber_xmm1 +.hidden abi_test_clobber_xmm1 +.type abi_test_clobber_xmm1,@function +.align 16 +abi_test_clobber_xmm1: +.L_abi_test_clobber_xmm1_begin: + pxor %xmm1,%xmm1 + ret +.size abi_test_clobber_xmm1,.-.L_abi_test_clobber_xmm1_begin +.globl abi_test_clobber_xmm2 +.hidden abi_test_clobber_xmm2 +.type abi_test_clobber_xmm2,@function +.align 16 +abi_test_clobber_xmm2: +.L_abi_test_clobber_xmm2_begin: + pxor %xmm2,%xmm2 + ret +.size abi_test_clobber_xmm2,.-.L_abi_test_clobber_xmm2_begin +.globl abi_test_clobber_xmm3 +.hidden abi_test_clobber_xmm3 +.type abi_test_clobber_xmm3,@function +.align 16 +abi_test_clobber_xmm3: +.L_abi_test_clobber_xmm3_begin: + pxor %xmm3,%xmm3 + ret +.size abi_test_clobber_xmm3,.-.L_abi_test_clobber_xmm3_begin +.globl abi_test_clobber_xmm4 +.hidden abi_test_clobber_xmm4 +.type abi_test_clobber_xmm4,@function +.align 16 +abi_test_clobber_xmm4: +.L_abi_test_clobber_xmm4_begin: + pxor %xmm4,%xmm4 + ret +.size abi_test_clobber_xmm4,.-.L_abi_test_clobber_xmm4_begin +.globl abi_test_clobber_xmm5 +.hidden abi_test_clobber_xmm5 +.type abi_test_clobber_xmm5,@function +.align 16 +abi_test_clobber_xmm5: +.L_abi_test_clobber_xmm5_begin: + pxor %xmm5,%xmm5 + ret +.size abi_test_clobber_xmm5,.-.L_abi_test_clobber_xmm5_begin +.globl abi_test_clobber_xmm6 +.hidden abi_test_clobber_xmm6 +.type abi_test_clobber_xmm6,@function +.align 16 +abi_test_clobber_xmm6: +.L_abi_test_clobber_xmm6_begin: + pxor %xmm6,%xmm6 + ret +.size abi_test_clobber_xmm6,.-.L_abi_test_clobber_xmm6_begin +.globl abi_test_clobber_xmm7 +.hidden abi_test_clobber_xmm7 +.type abi_test_clobber_xmm7,@function +.align 16 +abi_test_clobber_xmm7: +.L_abi_test_clobber_xmm7_begin: + pxor %xmm7,%xmm7 + ret +.size abi_test_clobber_xmm7,.-.L_abi_test_clobber_xmm7_begin +#endif diff --git a/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.S b/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.S index 066f4774..240cb5d4 100644 --- a/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.S +++ b/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.S @@ -556,6 +556,13 @@ _aesni_ctr32_6x: .align 32 aesni_gcm_encrypt: .cfi_startproc +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS +.extern BORINGSSL_function_hit +.hidden BORINGSSL_function_hit + movb $1,BORINGSSL_function_hit+2(%rip) +#endif +#endif xorq %r10,%r10 diff --git a/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/aesni-x86_64.S b/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/aesni-x86_64.S index d9f4e730..42e55307 100644 --- a/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/aesni-x86_64.S +++ b/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/aesni-x86_64.S @@ -20,6 +20,13 @@ .align 16 aes_hw_encrypt: .cfi_startproc +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS +.extern BORINGSSL_function_hit +.hidden BORINGSSL_function_hit + movb $1,BORINGSSL_function_hit+1(%rip) +#endif +#endif movups (%rdi),%xmm2 movl 240(%rdx),%eax movups (%rdx),%xmm0 @@ -874,174 +881,17 @@ aes_hw_ecb_encrypt: .byte 0xf3,0xc3 .cfi_endproc .size aes_hw_ecb_encrypt,.-aes_hw_ecb_encrypt -.globl aes_hw_ccm64_encrypt_blocks -.hidden aes_hw_ccm64_encrypt_blocks -.type aes_hw_ccm64_encrypt_blocks,@function -.align 16 -aes_hw_ccm64_encrypt_blocks: - movl 240(%rcx),%eax - movdqu (%r8),%xmm6 - movdqa .Lincrement64(%rip),%xmm9 - movdqa .Lbswap_mask(%rip),%xmm7 - - shll $4,%eax - movl $16,%r10d - leaq 0(%rcx),%r11 - movdqu (%r9),%xmm3 - movdqa %xmm6,%xmm2 - leaq 32(%rcx,%rax,1),%rcx -.byte 102,15,56,0,247 - subq %rax,%r10 - jmp .Lccm64_enc_outer -.align 16 -.Lccm64_enc_outer: - movups (%r11),%xmm0 - movq %r10,%rax - movups (%rdi),%xmm8 - - xorps %xmm0,%xmm2 - movups 16(%r11),%xmm1 - xorps %xmm8,%xmm0 - xorps %xmm0,%xmm3 - movups 32(%r11),%xmm0 - -.Lccm64_enc2_loop: -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 - movups (%rcx,%rax,1),%xmm1 - addq $32,%rax -.byte 102,15,56,220,208 -.byte 102,15,56,220,216 - movups -16(%rcx,%rax,1),%xmm0 - jnz .Lccm64_enc2_loop -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 - paddq %xmm9,%xmm6 - decq %rdx -.byte 102,15,56,221,208 -.byte 102,15,56,221,216 - - leaq 16(%rdi),%rdi - xorps %xmm2,%xmm8 - movdqa %xmm6,%xmm2 - movups %xmm8,(%rsi) -.byte 102,15,56,0,215 - leaq 16(%rsi),%rsi - jnz .Lccm64_enc_outer - - pxor %xmm0,%xmm0 - pxor %xmm1,%xmm1 - pxor %xmm2,%xmm2 - movups %xmm3,(%r9) - pxor %xmm3,%xmm3 - pxor %xmm8,%xmm8 - pxor %xmm6,%xmm6 - .byte 0xf3,0xc3 -.size aes_hw_ccm64_encrypt_blocks,.-aes_hw_ccm64_encrypt_blocks -.globl aes_hw_ccm64_decrypt_blocks -.hidden aes_hw_ccm64_decrypt_blocks -.type aes_hw_ccm64_decrypt_blocks,@function -.align 16 -aes_hw_ccm64_decrypt_blocks: - movl 240(%rcx),%eax - movups (%r8),%xmm6 - movdqu (%r9),%xmm3 - movdqa .Lincrement64(%rip),%xmm9 - movdqa .Lbswap_mask(%rip),%xmm7 - - movaps %xmm6,%xmm2 - movl %eax,%r10d - movq %rcx,%r11 -.byte 102,15,56,0,247 - movups (%rcx),%xmm0 - movups 16(%rcx),%xmm1 - leaq 32(%rcx),%rcx - xorps %xmm0,%xmm2 -.Loop_enc1_5: -.byte 102,15,56,220,209 - decl %eax - movups (%rcx),%xmm1 - leaq 16(%rcx),%rcx - jnz .Loop_enc1_5 -.byte 102,15,56,221,209 - shll $4,%r10d - movl $16,%eax - movups (%rdi),%xmm8 - paddq %xmm9,%xmm6 - leaq 16(%rdi),%rdi - subq %r10,%rax - leaq 32(%r11,%r10,1),%rcx - movq %rax,%r10 - jmp .Lccm64_dec_outer -.align 16 -.Lccm64_dec_outer: - xorps %xmm2,%xmm8 - movdqa %xmm6,%xmm2 - movups %xmm8,(%rsi) - leaq 16(%rsi),%rsi -.byte 102,15,56,0,215 - - subq $1,%rdx - jz .Lccm64_dec_break - - movups (%r11),%xmm0 - movq %r10,%rax - movups 16(%r11),%xmm1 - xorps %xmm0,%xmm8 - xorps %xmm0,%xmm2 - xorps %xmm8,%xmm3 - movups 32(%r11),%xmm0 - jmp .Lccm64_dec2_loop -.align 16 -.Lccm64_dec2_loop: -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 - movups (%rcx,%rax,1),%xmm1 - addq $32,%rax -.byte 102,15,56,220,208 -.byte 102,15,56,220,216 - movups -16(%rcx,%rax,1),%xmm0 - jnz .Lccm64_dec2_loop - movups (%rdi),%xmm8 - paddq %xmm9,%xmm6 -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 -.byte 102,15,56,221,208 -.byte 102,15,56,221,216 - leaq 16(%rdi),%rdi - jmp .Lccm64_dec_outer - -.align 16 -.Lccm64_dec_break: - - movl 240(%r11),%eax - movups (%r11),%xmm0 - movups 16(%r11),%xmm1 - xorps %xmm0,%xmm8 - leaq 32(%r11),%r11 - xorps %xmm8,%xmm3 -.Loop_enc1_6: -.byte 102,15,56,220,217 - decl %eax - movups (%r11),%xmm1 - leaq 16(%r11),%r11 - jnz .Loop_enc1_6 -.byte 102,15,56,221,217 - pxor %xmm0,%xmm0 - pxor %xmm1,%xmm1 - pxor %xmm2,%xmm2 - movups %xmm3,(%r9) - pxor %xmm3,%xmm3 - pxor %xmm8,%xmm8 - pxor %xmm6,%xmm6 - .byte 0xf3,0xc3 -.size aes_hw_ccm64_decrypt_blocks,.-aes_hw_ccm64_decrypt_blocks .globl aes_hw_ctr32_encrypt_blocks .hidden aes_hw_ctr32_encrypt_blocks .type aes_hw_ctr32_encrypt_blocks,@function .align 16 aes_hw_ctr32_encrypt_blocks: .cfi_startproc +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS + movb $1,BORINGSSL_function_hit(%rip) +#endif +#endif cmpq $1,%rdx jne .Lctr32_bulk @@ -1054,12 +904,12 @@ aes_hw_ctr32_encrypt_blocks: movups 16(%rcx),%xmm1 leaq 32(%rcx),%rcx xorps %xmm0,%xmm2 -.Loop_enc1_7: +.Loop_enc1_5: .byte 102,15,56,220,209 decl %edx movups (%rcx),%xmm1 leaq 16(%rcx),%rcx - jnz .Loop_enc1_7 + jnz .Loop_enc1_5 .byte 102,15,56,221,209 pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 @@ -1616,1839 +1466,6 @@ aes_hw_ctr32_encrypt_blocks: .byte 0xf3,0xc3 .cfi_endproc .size aes_hw_ctr32_encrypt_blocks,.-aes_hw_ctr32_encrypt_blocks -.globl aes_hw_xts_encrypt -.hidden aes_hw_xts_encrypt -.type aes_hw_xts_encrypt,@function -.align 16 -aes_hw_xts_encrypt: -.cfi_startproc - leaq (%rsp),%r11 -.cfi_def_cfa_register %r11 - pushq %rbp -.cfi_offset %rbp,-16 - subq $112,%rsp - andq $-16,%rsp - movups (%r9),%xmm2 - movl 240(%r8),%eax - movl 240(%rcx),%r10d - movups (%r8),%xmm0 - movups 16(%r8),%xmm1 - leaq 32(%r8),%r8 - xorps %xmm0,%xmm2 -.Loop_enc1_8: -.byte 102,15,56,220,209 - decl %eax - movups (%r8),%xmm1 - leaq 16(%r8),%r8 - jnz .Loop_enc1_8 -.byte 102,15,56,221,209 - movups (%rcx),%xmm0 - movq %rcx,%rbp - movl %r10d,%eax - shll $4,%r10d - movq %rdx,%r9 - andq $-16,%rdx - - movups 16(%rcx,%r10,1),%xmm1 - - movdqa .Lxts_magic(%rip),%xmm8 - movdqa %xmm2,%xmm15 - pshufd $0x5f,%xmm2,%xmm9 - pxor %xmm0,%xmm1 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 - movdqa %xmm15,%xmm10 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 - pxor %xmm0,%xmm10 - pxor %xmm14,%xmm15 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 - movdqa %xmm15,%xmm11 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 - pxor %xmm0,%xmm11 - pxor %xmm14,%xmm15 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 - movdqa %xmm15,%xmm12 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 - pxor %xmm0,%xmm12 - pxor %xmm14,%xmm15 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 - movdqa %xmm15,%xmm13 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 - pxor %xmm0,%xmm13 - pxor %xmm14,%xmm15 - movdqa %xmm15,%xmm14 - psrad $31,%xmm9 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm9 - pxor %xmm0,%xmm14 - pxor %xmm9,%xmm15 - movaps %xmm1,96(%rsp) - - subq $96,%rdx - jc .Lxts_enc_short - - movl $16+96,%eax - leaq 32(%rbp,%r10,1),%rcx - subq %r10,%rax - movups 16(%rbp),%xmm1 - movq %rax,%r10 - leaq .Lxts_magic(%rip),%r8 - jmp .Lxts_enc_grandloop - -.align 32 -.Lxts_enc_grandloop: - movdqu 0(%rdi),%xmm2 - movdqa %xmm0,%xmm8 - movdqu 16(%rdi),%xmm3 - pxor %xmm10,%xmm2 - movdqu 32(%rdi),%xmm4 - pxor %xmm11,%xmm3 -.byte 102,15,56,220,209 - movdqu 48(%rdi),%xmm5 - pxor %xmm12,%xmm4 -.byte 102,15,56,220,217 - movdqu 64(%rdi),%xmm6 - pxor %xmm13,%xmm5 -.byte 102,15,56,220,225 - movdqu 80(%rdi),%xmm7 - pxor %xmm15,%xmm8 - movdqa 96(%rsp),%xmm9 - pxor %xmm14,%xmm6 -.byte 102,15,56,220,233 - movups 32(%rbp),%xmm0 - leaq 96(%rdi),%rdi - pxor %xmm8,%xmm7 - - pxor %xmm9,%xmm10 -.byte 102,15,56,220,241 - pxor %xmm9,%xmm11 - movdqa %xmm10,0(%rsp) -.byte 102,15,56,220,249 - movups 48(%rbp),%xmm1 - pxor %xmm9,%xmm12 - -.byte 102,15,56,220,208 - pxor %xmm9,%xmm13 - movdqa %xmm11,16(%rsp) -.byte 102,15,56,220,216 - pxor %xmm9,%xmm14 - movdqa %xmm12,32(%rsp) -.byte 102,15,56,220,224 -.byte 102,15,56,220,232 - pxor %xmm9,%xmm8 - movdqa %xmm14,64(%rsp) -.byte 102,15,56,220,240 -.byte 102,15,56,220,248 - movups 64(%rbp),%xmm0 - movdqa %xmm8,80(%rsp) - pshufd $0x5f,%xmm15,%xmm9 - jmp .Lxts_enc_loop6 -.align 32 -.Lxts_enc_loop6: -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 -.byte 102,15,56,220,241 -.byte 102,15,56,220,249 - movups -64(%rcx,%rax,1),%xmm1 - addq $32,%rax - -.byte 102,15,56,220,208 -.byte 102,15,56,220,216 -.byte 102,15,56,220,224 -.byte 102,15,56,220,232 -.byte 102,15,56,220,240 -.byte 102,15,56,220,248 - movups -80(%rcx,%rax,1),%xmm0 - jnz .Lxts_enc_loop6 - - movdqa (%r8),%xmm8 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 -.byte 102,15,56,220,209 - paddq %xmm15,%xmm15 - psrad $31,%xmm14 -.byte 102,15,56,220,217 - pand %xmm8,%xmm14 - movups (%rbp),%xmm10 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 -.byte 102,15,56,220,241 - pxor %xmm14,%xmm15 - movaps %xmm10,%xmm11 -.byte 102,15,56,220,249 - movups -64(%rcx),%xmm1 - - movdqa %xmm9,%xmm14 -.byte 102,15,56,220,208 - paddd %xmm9,%xmm9 - pxor %xmm15,%xmm10 -.byte 102,15,56,220,216 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 -.byte 102,15,56,220,224 -.byte 102,15,56,220,232 - pand %xmm8,%xmm14 - movaps %xmm11,%xmm12 -.byte 102,15,56,220,240 - pxor %xmm14,%xmm15 - movdqa %xmm9,%xmm14 -.byte 102,15,56,220,248 - movups -48(%rcx),%xmm0 - - paddd %xmm9,%xmm9 -.byte 102,15,56,220,209 - pxor %xmm15,%xmm11 - psrad $31,%xmm14 -.byte 102,15,56,220,217 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 - movdqa %xmm13,48(%rsp) - pxor %xmm14,%xmm15 -.byte 102,15,56,220,241 - movaps %xmm12,%xmm13 - movdqa %xmm9,%xmm14 -.byte 102,15,56,220,249 - movups -32(%rcx),%xmm1 - - paddd %xmm9,%xmm9 -.byte 102,15,56,220,208 - pxor %xmm15,%xmm12 - psrad $31,%xmm14 -.byte 102,15,56,220,216 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 -.byte 102,15,56,220,224 -.byte 102,15,56,220,232 -.byte 102,15,56,220,240 - pxor %xmm14,%xmm15 - movaps %xmm13,%xmm14 -.byte 102,15,56,220,248 - - movdqa %xmm9,%xmm0 - paddd %xmm9,%xmm9 -.byte 102,15,56,220,209 - pxor %xmm15,%xmm13 - psrad $31,%xmm0 -.byte 102,15,56,220,217 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm0 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 - pxor %xmm0,%xmm15 - movups (%rbp),%xmm0 -.byte 102,15,56,220,241 -.byte 102,15,56,220,249 - movups 16(%rbp),%xmm1 - - pxor %xmm15,%xmm14 -.byte 102,15,56,221,84,36,0 - psrad $31,%xmm9 - paddq %xmm15,%xmm15 -.byte 102,15,56,221,92,36,16 -.byte 102,15,56,221,100,36,32 - pand %xmm8,%xmm9 - movq %r10,%rax -.byte 102,15,56,221,108,36,48 -.byte 102,15,56,221,116,36,64 -.byte 102,15,56,221,124,36,80 - pxor %xmm9,%xmm15 - - leaq 96(%rsi),%rsi - movups %xmm2,-96(%rsi) - movups %xmm3,-80(%rsi) - movups %xmm4,-64(%rsi) - movups %xmm5,-48(%rsi) - movups %xmm6,-32(%rsi) - movups %xmm7,-16(%rsi) - subq $96,%rdx - jnc .Lxts_enc_grandloop - - movl $16+96,%eax - subl %r10d,%eax - movq %rbp,%rcx - shrl $4,%eax - -.Lxts_enc_short: - - movl %eax,%r10d - pxor %xmm0,%xmm10 - addq $96,%rdx - jz .Lxts_enc_done - - pxor %xmm0,%xmm11 - cmpq $0x20,%rdx - jb .Lxts_enc_one - pxor %xmm0,%xmm12 - je .Lxts_enc_two - - pxor %xmm0,%xmm13 - cmpq $0x40,%rdx - jb .Lxts_enc_three - pxor %xmm0,%xmm14 - je .Lxts_enc_four - - movdqu (%rdi),%xmm2 - movdqu 16(%rdi),%xmm3 - movdqu 32(%rdi),%xmm4 - pxor %xmm10,%xmm2 - movdqu 48(%rdi),%xmm5 - pxor %xmm11,%xmm3 - movdqu 64(%rdi),%xmm6 - leaq 80(%rdi),%rdi - pxor %xmm12,%xmm4 - pxor %xmm13,%xmm5 - pxor %xmm14,%xmm6 - pxor %xmm7,%xmm7 - - call _aesni_encrypt6 - - xorps %xmm10,%xmm2 - movdqa %xmm15,%xmm10 - xorps %xmm11,%xmm3 - xorps %xmm12,%xmm4 - movdqu %xmm2,(%rsi) - xorps %xmm13,%xmm5 - movdqu %xmm3,16(%rsi) - xorps %xmm14,%xmm6 - movdqu %xmm4,32(%rsi) - movdqu %xmm5,48(%rsi) - movdqu %xmm6,64(%rsi) - leaq 80(%rsi),%rsi - jmp .Lxts_enc_done - -.align 16 -.Lxts_enc_one: - movups (%rdi),%xmm2 - leaq 16(%rdi),%rdi - xorps %xmm10,%xmm2 - movups (%rcx),%xmm0 - movups 16(%rcx),%xmm1 - leaq 32(%rcx),%rcx - xorps %xmm0,%xmm2 -.Loop_enc1_9: -.byte 102,15,56,220,209 - decl %eax - movups (%rcx),%xmm1 - leaq 16(%rcx),%rcx - jnz .Loop_enc1_9 -.byte 102,15,56,221,209 - xorps %xmm10,%xmm2 - movdqa %xmm11,%xmm10 - movups %xmm2,(%rsi) - leaq 16(%rsi),%rsi - jmp .Lxts_enc_done - -.align 16 -.Lxts_enc_two: - movups (%rdi),%xmm2 - movups 16(%rdi),%xmm3 - leaq 32(%rdi),%rdi - xorps %xmm10,%xmm2 - xorps %xmm11,%xmm3 - - call _aesni_encrypt2 - - xorps %xmm10,%xmm2 - movdqa %xmm12,%xmm10 - xorps %xmm11,%xmm3 - movups %xmm2,(%rsi) - movups %xmm3,16(%rsi) - leaq 32(%rsi),%rsi - jmp .Lxts_enc_done - -.align 16 -.Lxts_enc_three: - movups (%rdi),%xmm2 - movups 16(%rdi),%xmm3 - movups 32(%rdi),%xmm4 - leaq 48(%rdi),%rdi - xorps %xmm10,%xmm2 - xorps %xmm11,%xmm3 - xorps %xmm12,%xmm4 - - call _aesni_encrypt3 - - xorps %xmm10,%xmm2 - movdqa %xmm13,%xmm10 - xorps %xmm11,%xmm3 - xorps %xmm12,%xmm4 - movups %xmm2,(%rsi) - movups %xmm3,16(%rsi) - movups %xmm4,32(%rsi) - leaq 48(%rsi),%rsi - jmp .Lxts_enc_done - -.align 16 -.Lxts_enc_four: - movups (%rdi),%xmm2 - movups 16(%rdi),%xmm3 - movups 32(%rdi),%xmm4 - xorps %xmm10,%xmm2 - movups 48(%rdi),%xmm5 - leaq 64(%rdi),%rdi - xorps %xmm11,%xmm3 - xorps %xmm12,%xmm4 - xorps %xmm13,%xmm5 - - call _aesni_encrypt4 - - pxor %xmm10,%xmm2 - movdqa %xmm14,%xmm10 - pxor %xmm11,%xmm3 - pxor %xmm12,%xmm4 - movdqu %xmm2,(%rsi) - pxor %xmm13,%xmm5 - movdqu %xmm3,16(%rsi) - movdqu %xmm4,32(%rsi) - movdqu %xmm5,48(%rsi) - leaq 64(%rsi),%rsi - jmp .Lxts_enc_done - -.align 16 -.Lxts_enc_done: - andq $15,%r9 - jz .Lxts_enc_ret - movq %r9,%rdx - -.Lxts_enc_steal: - movzbl (%rdi),%eax - movzbl -16(%rsi),%ecx - leaq 1(%rdi),%rdi - movb %al,-16(%rsi) - movb %cl,0(%rsi) - leaq 1(%rsi),%rsi - subq $1,%rdx - jnz .Lxts_enc_steal - - subq %r9,%rsi - movq %rbp,%rcx - movl %r10d,%eax - - movups -16(%rsi),%xmm2 - xorps %xmm10,%xmm2 - movups (%rcx),%xmm0 - movups 16(%rcx),%xmm1 - leaq 32(%rcx),%rcx - xorps %xmm0,%xmm2 -.Loop_enc1_10: -.byte 102,15,56,220,209 - decl %eax - movups (%rcx),%xmm1 - leaq 16(%rcx),%rcx - jnz .Loop_enc1_10 -.byte 102,15,56,221,209 - xorps %xmm10,%xmm2 - movups %xmm2,-16(%rsi) - -.Lxts_enc_ret: - xorps %xmm0,%xmm0 - pxor %xmm1,%xmm1 - pxor %xmm2,%xmm2 - pxor %xmm3,%xmm3 - pxor %xmm4,%xmm4 - pxor %xmm5,%xmm5 - pxor %xmm6,%xmm6 - pxor %xmm7,%xmm7 - movaps %xmm0,0(%rsp) - pxor %xmm8,%xmm8 - movaps %xmm0,16(%rsp) - pxor %xmm9,%xmm9 - movaps %xmm0,32(%rsp) - pxor %xmm10,%xmm10 - movaps %xmm0,48(%rsp) - pxor %xmm11,%xmm11 - movaps %xmm0,64(%rsp) - pxor %xmm12,%xmm12 - movaps %xmm0,80(%rsp) - pxor %xmm13,%xmm13 - movaps %xmm0,96(%rsp) - pxor %xmm14,%xmm14 - pxor %xmm15,%xmm15 - movq -8(%r11),%rbp -.cfi_restore %rbp - leaq (%r11),%rsp -.cfi_def_cfa_register %rsp -.Lxts_enc_epilogue: - .byte 0xf3,0xc3 -.cfi_endproc -.size aes_hw_xts_encrypt,.-aes_hw_xts_encrypt -.globl aes_hw_xts_decrypt -.hidden aes_hw_xts_decrypt -.type aes_hw_xts_decrypt,@function -.align 16 -aes_hw_xts_decrypt: -.cfi_startproc - leaq (%rsp),%r11 -.cfi_def_cfa_register %r11 - pushq %rbp -.cfi_offset %rbp,-16 - subq $112,%rsp - andq $-16,%rsp - movups (%r9),%xmm2 - movl 240(%r8),%eax - movl 240(%rcx),%r10d - movups (%r8),%xmm0 - movups 16(%r8),%xmm1 - leaq 32(%r8),%r8 - xorps %xmm0,%xmm2 -.Loop_enc1_11: -.byte 102,15,56,220,209 - decl %eax - movups (%r8),%xmm1 - leaq 16(%r8),%r8 - jnz .Loop_enc1_11 -.byte 102,15,56,221,209 - xorl %eax,%eax - testq $15,%rdx - setnz %al - shlq $4,%rax - subq %rax,%rdx - - movups (%rcx),%xmm0 - movq %rcx,%rbp - movl %r10d,%eax - shll $4,%r10d - movq %rdx,%r9 - andq $-16,%rdx - - movups 16(%rcx,%r10,1),%xmm1 - - movdqa .Lxts_magic(%rip),%xmm8 - movdqa %xmm2,%xmm15 - pshufd $0x5f,%xmm2,%xmm9 - pxor %xmm0,%xmm1 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 - movdqa %xmm15,%xmm10 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 - pxor %xmm0,%xmm10 - pxor %xmm14,%xmm15 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 - movdqa %xmm15,%xmm11 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 - pxor %xmm0,%xmm11 - pxor %xmm14,%xmm15 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 - movdqa %xmm15,%xmm12 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 - pxor %xmm0,%xmm12 - pxor %xmm14,%xmm15 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 - movdqa %xmm15,%xmm13 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 - pxor %xmm0,%xmm13 - pxor %xmm14,%xmm15 - movdqa %xmm15,%xmm14 - psrad $31,%xmm9 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm9 - pxor %xmm0,%xmm14 - pxor %xmm9,%xmm15 - movaps %xmm1,96(%rsp) - - subq $96,%rdx - jc .Lxts_dec_short - - movl $16+96,%eax - leaq 32(%rbp,%r10,1),%rcx - subq %r10,%rax - movups 16(%rbp),%xmm1 - movq %rax,%r10 - leaq .Lxts_magic(%rip),%r8 - jmp .Lxts_dec_grandloop - -.align 32 -.Lxts_dec_grandloop: - movdqu 0(%rdi),%xmm2 - movdqa %xmm0,%xmm8 - movdqu 16(%rdi),%xmm3 - pxor %xmm10,%xmm2 - movdqu 32(%rdi),%xmm4 - pxor %xmm11,%xmm3 -.byte 102,15,56,222,209 - movdqu 48(%rdi),%xmm5 - pxor %xmm12,%xmm4 -.byte 102,15,56,222,217 - movdqu 64(%rdi),%xmm6 - pxor %xmm13,%xmm5 -.byte 102,15,56,222,225 - movdqu 80(%rdi),%xmm7 - pxor %xmm15,%xmm8 - movdqa 96(%rsp),%xmm9 - pxor %xmm14,%xmm6 -.byte 102,15,56,222,233 - movups 32(%rbp),%xmm0 - leaq 96(%rdi),%rdi - pxor %xmm8,%xmm7 - - pxor %xmm9,%xmm10 -.byte 102,15,56,222,241 - pxor %xmm9,%xmm11 - movdqa %xmm10,0(%rsp) -.byte 102,15,56,222,249 - movups 48(%rbp),%xmm1 - pxor %xmm9,%xmm12 - -.byte 102,15,56,222,208 - pxor %xmm9,%xmm13 - movdqa %xmm11,16(%rsp) -.byte 102,15,56,222,216 - pxor %xmm9,%xmm14 - movdqa %xmm12,32(%rsp) -.byte 102,15,56,222,224 -.byte 102,15,56,222,232 - pxor %xmm9,%xmm8 - movdqa %xmm14,64(%rsp) -.byte 102,15,56,222,240 -.byte 102,15,56,222,248 - movups 64(%rbp),%xmm0 - movdqa %xmm8,80(%rsp) - pshufd $0x5f,%xmm15,%xmm9 - jmp .Lxts_dec_loop6 -.align 32 -.Lxts_dec_loop6: -.byte 102,15,56,222,209 -.byte 102,15,56,222,217 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 -.byte 102,15,56,222,241 -.byte 102,15,56,222,249 - movups -64(%rcx,%rax,1),%xmm1 - addq $32,%rax - -.byte 102,15,56,222,208 -.byte 102,15,56,222,216 -.byte 102,15,56,222,224 -.byte 102,15,56,222,232 -.byte 102,15,56,222,240 -.byte 102,15,56,222,248 - movups -80(%rcx,%rax,1),%xmm0 - jnz .Lxts_dec_loop6 - - movdqa (%r8),%xmm8 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 -.byte 102,15,56,222,209 - paddq %xmm15,%xmm15 - psrad $31,%xmm14 -.byte 102,15,56,222,217 - pand %xmm8,%xmm14 - movups (%rbp),%xmm10 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 -.byte 102,15,56,222,241 - pxor %xmm14,%xmm15 - movaps %xmm10,%xmm11 -.byte 102,15,56,222,249 - movups -64(%rcx),%xmm1 - - movdqa %xmm9,%xmm14 -.byte 102,15,56,222,208 - paddd %xmm9,%xmm9 - pxor %xmm15,%xmm10 -.byte 102,15,56,222,216 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 -.byte 102,15,56,222,224 -.byte 102,15,56,222,232 - pand %xmm8,%xmm14 - movaps %xmm11,%xmm12 -.byte 102,15,56,222,240 - pxor %xmm14,%xmm15 - movdqa %xmm9,%xmm14 -.byte 102,15,56,222,248 - movups -48(%rcx),%xmm0 - - paddd %xmm9,%xmm9 -.byte 102,15,56,222,209 - pxor %xmm15,%xmm11 - psrad $31,%xmm14 -.byte 102,15,56,222,217 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 - movdqa %xmm13,48(%rsp) - pxor %xmm14,%xmm15 -.byte 102,15,56,222,241 - movaps %xmm12,%xmm13 - movdqa %xmm9,%xmm14 -.byte 102,15,56,222,249 - movups -32(%rcx),%xmm1 - - paddd %xmm9,%xmm9 -.byte 102,15,56,222,208 - pxor %xmm15,%xmm12 - psrad $31,%xmm14 -.byte 102,15,56,222,216 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 -.byte 102,15,56,222,224 -.byte 102,15,56,222,232 -.byte 102,15,56,222,240 - pxor %xmm14,%xmm15 - movaps %xmm13,%xmm14 -.byte 102,15,56,222,248 - - movdqa %xmm9,%xmm0 - paddd %xmm9,%xmm9 -.byte 102,15,56,222,209 - pxor %xmm15,%xmm13 - psrad $31,%xmm0 -.byte 102,15,56,222,217 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm0 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 - pxor %xmm0,%xmm15 - movups (%rbp),%xmm0 -.byte 102,15,56,222,241 -.byte 102,15,56,222,249 - movups 16(%rbp),%xmm1 - - pxor %xmm15,%xmm14 -.byte 102,15,56,223,84,36,0 - psrad $31,%xmm9 - paddq %xmm15,%xmm15 -.byte 102,15,56,223,92,36,16 -.byte 102,15,56,223,100,36,32 - pand %xmm8,%xmm9 - movq %r10,%rax -.byte 102,15,56,223,108,36,48 -.byte 102,15,56,223,116,36,64 -.byte 102,15,56,223,124,36,80 - pxor %xmm9,%xmm15 - - leaq 96(%rsi),%rsi - movups %xmm2,-96(%rsi) - movups %xmm3,-80(%rsi) - movups %xmm4,-64(%rsi) - movups %xmm5,-48(%rsi) - movups %xmm6,-32(%rsi) - movups %xmm7,-16(%rsi) - subq $96,%rdx - jnc .Lxts_dec_grandloop - - movl $16+96,%eax - subl %r10d,%eax - movq %rbp,%rcx - shrl $4,%eax - -.Lxts_dec_short: - - movl %eax,%r10d - pxor %xmm0,%xmm10 - pxor %xmm0,%xmm11 - addq $96,%rdx - jz .Lxts_dec_done - - pxor %xmm0,%xmm12 - cmpq $0x20,%rdx - jb .Lxts_dec_one - pxor %xmm0,%xmm13 - je .Lxts_dec_two - - pxor %xmm0,%xmm14 - cmpq $0x40,%rdx - jb .Lxts_dec_three - je .Lxts_dec_four - - movdqu (%rdi),%xmm2 - movdqu 16(%rdi),%xmm3 - movdqu 32(%rdi),%xmm4 - pxor %xmm10,%xmm2 - movdqu 48(%rdi),%xmm5 - pxor %xmm11,%xmm3 - movdqu 64(%rdi),%xmm6 - leaq 80(%rdi),%rdi - pxor %xmm12,%xmm4 - pxor %xmm13,%xmm5 - pxor %xmm14,%xmm6 - - call _aesni_decrypt6 - - xorps %xmm10,%xmm2 - xorps %xmm11,%xmm3 - xorps %xmm12,%xmm4 - movdqu %xmm2,(%rsi) - xorps %xmm13,%xmm5 - movdqu %xmm3,16(%rsi) - xorps %xmm14,%xmm6 - movdqu %xmm4,32(%rsi) - pxor %xmm14,%xmm14 - movdqu %xmm5,48(%rsi) - pcmpgtd %xmm15,%xmm14 - movdqu %xmm6,64(%rsi) - leaq 80(%rsi),%rsi - pshufd $0x13,%xmm14,%xmm11 - andq $15,%r9 - jz .Lxts_dec_ret - - movdqa %xmm15,%xmm10 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm11 - pxor %xmm15,%xmm11 - jmp .Lxts_dec_done2 - -.align 16 -.Lxts_dec_one: - movups (%rdi),%xmm2 - leaq 16(%rdi),%rdi - xorps %xmm10,%xmm2 - movups (%rcx),%xmm0 - movups 16(%rcx),%xmm1 - leaq 32(%rcx),%rcx - xorps %xmm0,%xmm2 -.Loop_dec1_12: -.byte 102,15,56,222,209 - decl %eax - movups (%rcx),%xmm1 - leaq 16(%rcx),%rcx - jnz .Loop_dec1_12 -.byte 102,15,56,223,209 - xorps %xmm10,%xmm2 - movdqa %xmm11,%xmm10 - movups %xmm2,(%rsi) - movdqa %xmm12,%xmm11 - leaq 16(%rsi),%rsi - jmp .Lxts_dec_done - -.align 16 -.Lxts_dec_two: - movups (%rdi),%xmm2 - movups 16(%rdi),%xmm3 - leaq 32(%rdi),%rdi - xorps %xmm10,%xmm2 - xorps %xmm11,%xmm3 - - call _aesni_decrypt2 - - xorps %xmm10,%xmm2 - movdqa %xmm12,%xmm10 - xorps %xmm11,%xmm3 - movdqa %xmm13,%xmm11 - movups %xmm2,(%rsi) - movups %xmm3,16(%rsi) - leaq 32(%rsi),%rsi - jmp .Lxts_dec_done - -.align 16 -.Lxts_dec_three: - movups (%rdi),%xmm2 - movups 16(%rdi),%xmm3 - movups 32(%rdi),%xmm4 - leaq 48(%rdi),%rdi - xorps %xmm10,%xmm2 - xorps %xmm11,%xmm3 - xorps %xmm12,%xmm4 - - call _aesni_decrypt3 - - xorps %xmm10,%xmm2 - movdqa %xmm13,%xmm10 - xorps %xmm11,%xmm3 - movdqa %xmm14,%xmm11 - xorps %xmm12,%xmm4 - movups %xmm2,(%rsi) - movups %xmm3,16(%rsi) - movups %xmm4,32(%rsi) - leaq 48(%rsi),%rsi - jmp .Lxts_dec_done - -.align 16 -.Lxts_dec_four: - movups (%rdi),%xmm2 - movups 16(%rdi),%xmm3 - movups 32(%rdi),%xmm4 - xorps %xmm10,%xmm2 - movups 48(%rdi),%xmm5 - leaq 64(%rdi),%rdi - xorps %xmm11,%xmm3 - xorps %xmm12,%xmm4 - xorps %xmm13,%xmm5 - - call _aesni_decrypt4 - - pxor %xmm10,%xmm2 - movdqa %xmm14,%xmm10 - pxor %xmm11,%xmm3 - movdqa %xmm15,%xmm11 - pxor %xmm12,%xmm4 - movdqu %xmm2,(%rsi) - pxor %xmm13,%xmm5 - movdqu %xmm3,16(%rsi) - movdqu %xmm4,32(%rsi) - movdqu %xmm5,48(%rsi) - leaq 64(%rsi),%rsi - jmp .Lxts_dec_done - -.align 16 -.Lxts_dec_done: - andq $15,%r9 - jz .Lxts_dec_ret -.Lxts_dec_done2: - movq %r9,%rdx - movq %rbp,%rcx - movl %r10d,%eax - - movups (%rdi),%xmm2 - xorps %xmm11,%xmm2 - movups (%rcx),%xmm0 - movups 16(%rcx),%xmm1 - leaq 32(%rcx),%rcx - xorps %xmm0,%xmm2 -.Loop_dec1_13: -.byte 102,15,56,222,209 - decl %eax - movups (%rcx),%xmm1 - leaq 16(%rcx),%rcx - jnz .Loop_dec1_13 -.byte 102,15,56,223,209 - xorps %xmm11,%xmm2 - movups %xmm2,(%rsi) - -.Lxts_dec_steal: - movzbl 16(%rdi),%eax - movzbl (%rsi),%ecx - leaq 1(%rdi),%rdi - movb %al,(%rsi) - movb %cl,16(%rsi) - leaq 1(%rsi),%rsi - subq $1,%rdx - jnz .Lxts_dec_steal - - subq %r9,%rsi - movq %rbp,%rcx - movl %r10d,%eax - - movups (%rsi),%xmm2 - xorps %xmm10,%xmm2 - movups (%rcx),%xmm0 - movups 16(%rcx),%xmm1 - leaq 32(%rcx),%rcx - xorps %xmm0,%xmm2 -.Loop_dec1_14: -.byte 102,15,56,222,209 - decl %eax - movups (%rcx),%xmm1 - leaq 16(%rcx),%rcx - jnz .Loop_dec1_14 -.byte 102,15,56,223,209 - xorps %xmm10,%xmm2 - movups %xmm2,(%rsi) - -.Lxts_dec_ret: - xorps %xmm0,%xmm0 - pxor %xmm1,%xmm1 - pxor %xmm2,%xmm2 - pxor %xmm3,%xmm3 - pxor %xmm4,%xmm4 - pxor %xmm5,%xmm5 - pxor %xmm6,%xmm6 - pxor %xmm7,%xmm7 - movaps %xmm0,0(%rsp) - pxor %xmm8,%xmm8 - movaps %xmm0,16(%rsp) - pxor %xmm9,%xmm9 - movaps %xmm0,32(%rsp) - pxor %xmm10,%xmm10 - movaps %xmm0,48(%rsp) - pxor %xmm11,%xmm11 - movaps %xmm0,64(%rsp) - pxor %xmm12,%xmm12 - movaps %xmm0,80(%rsp) - pxor %xmm13,%xmm13 - movaps %xmm0,96(%rsp) - pxor %xmm14,%xmm14 - pxor %xmm15,%xmm15 - movq -8(%r11),%rbp -.cfi_restore %rbp - leaq (%r11),%rsp -.cfi_def_cfa_register %rsp -.Lxts_dec_epilogue: - .byte 0xf3,0xc3 -.cfi_endproc -.size aes_hw_xts_decrypt,.-aes_hw_xts_decrypt -.globl aes_hw_ocb_encrypt -.hidden aes_hw_ocb_encrypt -.type aes_hw_ocb_encrypt,@function -.align 32 -aes_hw_ocb_encrypt: -.cfi_startproc - leaq (%rsp),%rax - pushq %rbx -.cfi_adjust_cfa_offset 8 -.cfi_offset %rbx,-16 - pushq %rbp -.cfi_adjust_cfa_offset 8 -.cfi_offset %rbp,-24 - pushq %r12 -.cfi_adjust_cfa_offset 8 -.cfi_offset %r12,-32 - pushq %r13 -.cfi_adjust_cfa_offset 8 -.cfi_offset %r13,-40 - pushq %r14 -.cfi_adjust_cfa_offset 8 -.cfi_offset %r14,-48 - movq 8(%rax),%rbx - movq 8+8(%rax),%rbp - - movl 240(%rcx),%r10d - movq %rcx,%r11 - shll $4,%r10d - movups (%rcx),%xmm9 - movups 16(%rcx,%r10,1),%xmm1 - - movdqu (%r9),%xmm15 - pxor %xmm1,%xmm9 - pxor %xmm1,%xmm15 - - movl $16+32,%eax - leaq 32(%r11,%r10,1),%rcx - movups 16(%r11),%xmm1 - subq %r10,%rax - movq %rax,%r10 - - movdqu (%rbx),%xmm10 - movdqu (%rbp),%xmm8 - - testq $1,%r8 - jnz .Locb_enc_odd - - bsfq %r8,%r12 - addq $1,%r8 - shlq $4,%r12 - movdqu (%rbx,%r12,1),%xmm7 - movdqu (%rdi),%xmm2 - leaq 16(%rdi),%rdi - - call __ocb_encrypt1 - - movdqa %xmm7,%xmm15 - movups %xmm2,(%rsi) - leaq 16(%rsi),%rsi - subq $1,%rdx - jz .Locb_enc_done - -.Locb_enc_odd: - leaq 1(%r8),%r12 - leaq 3(%r8),%r13 - leaq 5(%r8),%r14 - leaq 6(%r8),%r8 - bsfq %r12,%r12 - bsfq %r13,%r13 - bsfq %r14,%r14 - shlq $4,%r12 - shlq $4,%r13 - shlq $4,%r14 - - subq $6,%rdx - jc .Locb_enc_short - jmp .Locb_enc_grandloop - -.align 32 -.Locb_enc_grandloop: - movdqu 0(%rdi),%xmm2 - movdqu 16(%rdi),%xmm3 - movdqu 32(%rdi),%xmm4 - movdqu 48(%rdi),%xmm5 - movdqu 64(%rdi),%xmm6 - movdqu 80(%rdi),%xmm7 - leaq 96(%rdi),%rdi - - call __ocb_encrypt6 - - movups %xmm2,0(%rsi) - movups %xmm3,16(%rsi) - movups %xmm4,32(%rsi) - movups %xmm5,48(%rsi) - movups %xmm6,64(%rsi) - movups %xmm7,80(%rsi) - leaq 96(%rsi),%rsi - subq $6,%rdx - jnc .Locb_enc_grandloop - -.Locb_enc_short: - addq $6,%rdx - jz .Locb_enc_done - - movdqu 0(%rdi),%xmm2 - cmpq $2,%rdx - jb .Locb_enc_one - movdqu 16(%rdi),%xmm3 - je .Locb_enc_two - - movdqu 32(%rdi),%xmm4 - cmpq $4,%rdx - jb .Locb_enc_three - movdqu 48(%rdi),%xmm5 - je .Locb_enc_four - - movdqu 64(%rdi),%xmm6 - pxor %xmm7,%xmm7 - - call __ocb_encrypt6 - - movdqa %xmm14,%xmm15 - movups %xmm2,0(%rsi) - movups %xmm3,16(%rsi) - movups %xmm4,32(%rsi) - movups %xmm5,48(%rsi) - movups %xmm6,64(%rsi) - - jmp .Locb_enc_done - -.align 16 -.Locb_enc_one: - movdqa %xmm10,%xmm7 - - call __ocb_encrypt1 - - movdqa %xmm7,%xmm15 - movups %xmm2,0(%rsi) - jmp .Locb_enc_done - -.align 16 -.Locb_enc_two: - pxor %xmm4,%xmm4 - pxor %xmm5,%xmm5 - - call __ocb_encrypt4 - - movdqa %xmm11,%xmm15 - movups %xmm2,0(%rsi) - movups %xmm3,16(%rsi) - - jmp .Locb_enc_done - -.align 16 -.Locb_enc_three: - pxor %xmm5,%xmm5 - - call __ocb_encrypt4 - - movdqa %xmm12,%xmm15 - movups %xmm2,0(%rsi) - movups %xmm3,16(%rsi) - movups %xmm4,32(%rsi) - - jmp .Locb_enc_done - -.align 16 -.Locb_enc_four: - call __ocb_encrypt4 - - movdqa %xmm13,%xmm15 - movups %xmm2,0(%rsi) - movups %xmm3,16(%rsi) - movups %xmm4,32(%rsi) - movups %xmm5,48(%rsi) - -.Locb_enc_done: - pxor %xmm0,%xmm15 - movdqu %xmm8,(%rbp) - movdqu %xmm15,(%r9) - - xorps %xmm0,%xmm0 - pxor %xmm1,%xmm1 - pxor %xmm2,%xmm2 - pxor %xmm3,%xmm3 - pxor %xmm4,%xmm4 - pxor %xmm5,%xmm5 - pxor %xmm6,%xmm6 - pxor %xmm7,%xmm7 - pxor %xmm8,%xmm8 - pxor %xmm9,%xmm9 - pxor %xmm10,%xmm10 - pxor %xmm11,%xmm11 - pxor %xmm12,%xmm12 - pxor %xmm13,%xmm13 - pxor %xmm14,%xmm14 - pxor %xmm15,%xmm15 - leaq 40(%rsp),%rax -.cfi_def_cfa %rax,8 - movq -40(%rax),%r14 -.cfi_restore %r14 - movq -32(%rax),%r13 -.cfi_restore %r13 - movq -24(%rax),%r12 -.cfi_restore %r12 - movq -16(%rax),%rbp -.cfi_restore %rbp - movq -8(%rax),%rbx -.cfi_restore %rbx - leaq (%rax),%rsp -.cfi_def_cfa_register %rsp -.Locb_enc_epilogue: - .byte 0xf3,0xc3 -.cfi_endproc -.size aes_hw_ocb_encrypt,.-aes_hw_ocb_encrypt - -.type __ocb_encrypt6,@function -.align 32 -__ocb_encrypt6: - pxor %xmm9,%xmm15 - movdqu (%rbx,%r12,1),%xmm11 - movdqa %xmm10,%xmm12 - movdqu (%rbx,%r13,1),%xmm13 - movdqa %xmm10,%xmm14 - pxor %xmm15,%xmm10 - movdqu (%rbx,%r14,1),%xmm15 - pxor %xmm10,%xmm11 - pxor %xmm2,%xmm8 - pxor %xmm10,%xmm2 - pxor %xmm11,%xmm12 - pxor %xmm3,%xmm8 - pxor %xmm11,%xmm3 - pxor %xmm12,%xmm13 - pxor %xmm4,%xmm8 - pxor %xmm12,%xmm4 - pxor %xmm13,%xmm14 - pxor %xmm5,%xmm8 - pxor %xmm13,%xmm5 - pxor %xmm14,%xmm15 - pxor %xmm6,%xmm8 - pxor %xmm14,%xmm6 - pxor %xmm7,%xmm8 - pxor %xmm15,%xmm7 - movups 32(%r11),%xmm0 - - leaq 1(%r8),%r12 - leaq 3(%r8),%r13 - leaq 5(%r8),%r14 - addq $6,%r8 - pxor %xmm9,%xmm10 - bsfq %r12,%r12 - bsfq %r13,%r13 - bsfq %r14,%r14 - -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 - pxor %xmm9,%xmm11 - pxor %xmm9,%xmm12 -.byte 102,15,56,220,241 - pxor %xmm9,%xmm13 - pxor %xmm9,%xmm14 -.byte 102,15,56,220,249 - movups 48(%r11),%xmm1 - pxor %xmm9,%xmm15 - -.byte 102,15,56,220,208 -.byte 102,15,56,220,216 -.byte 102,15,56,220,224 -.byte 102,15,56,220,232 -.byte 102,15,56,220,240 -.byte 102,15,56,220,248 - movups 64(%r11),%xmm0 - shlq $4,%r12 - shlq $4,%r13 - jmp .Locb_enc_loop6 - -.align 32 -.Locb_enc_loop6: -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 -.byte 102,15,56,220,241 -.byte 102,15,56,220,249 - movups (%rcx,%rax,1),%xmm1 - addq $32,%rax - -.byte 102,15,56,220,208 -.byte 102,15,56,220,216 -.byte 102,15,56,220,224 -.byte 102,15,56,220,232 -.byte 102,15,56,220,240 -.byte 102,15,56,220,248 - movups -16(%rcx,%rax,1),%xmm0 - jnz .Locb_enc_loop6 - -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 -.byte 102,15,56,220,241 -.byte 102,15,56,220,249 - movups 16(%r11),%xmm1 - shlq $4,%r14 - -.byte 102,65,15,56,221,210 - movdqu (%rbx),%xmm10 - movq %r10,%rax -.byte 102,65,15,56,221,219 -.byte 102,65,15,56,221,228 -.byte 102,65,15,56,221,237 -.byte 102,65,15,56,221,246 -.byte 102,65,15,56,221,255 - .byte 0xf3,0xc3 -.size __ocb_encrypt6,.-__ocb_encrypt6 - -.type __ocb_encrypt4,@function -.align 32 -__ocb_encrypt4: - pxor %xmm9,%xmm15 - movdqu (%rbx,%r12,1),%xmm11 - movdqa %xmm10,%xmm12 - movdqu (%rbx,%r13,1),%xmm13 - pxor %xmm15,%xmm10 - pxor %xmm10,%xmm11 - pxor %xmm2,%xmm8 - pxor %xmm10,%xmm2 - pxor %xmm11,%xmm12 - pxor %xmm3,%xmm8 - pxor %xmm11,%xmm3 - pxor %xmm12,%xmm13 - pxor %xmm4,%xmm8 - pxor %xmm12,%xmm4 - pxor %xmm5,%xmm8 - pxor %xmm13,%xmm5 - movups 32(%r11),%xmm0 - - pxor %xmm9,%xmm10 - pxor %xmm9,%xmm11 - pxor %xmm9,%xmm12 - pxor %xmm9,%xmm13 - -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 - movups 48(%r11),%xmm1 - -.byte 102,15,56,220,208 -.byte 102,15,56,220,216 -.byte 102,15,56,220,224 -.byte 102,15,56,220,232 - movups 64(%r11),%xmm0 - jmp .Locb_enc_loop4 - -.align 32 -.Locb_enc_loop4: -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 - movups (%rcx,%rax,1),%xmm1 - addq $32,%rax - -.byte 102,15,56,220,208 -.byte 102,15,56,220,216 -.byte 102,15,56,220,224 -.byte 102,15,56,220,232 - movups -16(%rcx,%rax,1),%xmm0 - jnz .Locb_enc_loop4 - -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 - movups 16(%r11),%xmm1 - movq %r10,%rax - -.byte 102,65,15,56,221,210 -.byte 102,65,15,56,221,219 -.byte 102,65,15,56,221,228 -.byte 102,65,15,56,221,237 - .byte 0xf3,0xc3 -.size __ocb_encrypt4,.-__ocb_encrypt4 - -.type __ocb_encrypt1,@function -.align 32 -__ocb_encrypt1: - pxor %xmm15,%xmm7 - pxor %xmm9,%xmm7 - pxor %xmm2,%xmm8 - pxor %xmm7,%xmm2 - movups 32(%r11),%xmm0 - -.byte 102,15,56,220,209 - movups 48(%r11),%xmm1 - pxor %xmm9,%xmm7 - -.byte 102,15,56,220,208 - movups 64(%r11),%xmm0 - jmp .Locb_enc_loop1 - -.align 32 -.Locb_enc_loop1: -.byte 102,15,56,220,209 - movups (%rcx,%rax,1),%xmm1 - addq $32,%rax - -.byte 102,15,56,220,208 - movups -16(%rcx,%rax,1),%xmm0 - jnz .Locb_enc_loop1 - -.byte 102,15,56,220,209 - movups 16(%r11),%xmm1 - movq %r10,%rax - -.byte 102,15,56,221,215 - .byte 0xf3,0xc3 -.size __ocb_encrypt1,.-__ocb_encrypt1 - -.globl aes_hw_ocb_decrypt -.hidden aes_hw_ocb_decrypt -.type aes_hw_ocb_decrypt,@function -.align 32 -aes_hw_ocb_decrypt: -.cfi_startproc - leaq (%rsp),%rax - pushq %rbx -.cfi_adjust_cfa_offset 8 -.cfi_offset %rbx,-16 - pushq %rbp -.cfi_adjust_cfa_offset 8 -.cfi_offset %rbp,-24 - pushq %r12 -.cfi_adjust_cfa_offset 8 -.cfi_offset %r12,-32 - pushq %r13 -.cfi_adjust_cfa_offset 8 -.cfi_offset %r13,-40 - pushq %r14 -.cfi_adjust_cfa_offset 8 -.cfi_offset %r14,-48 - movq 8(%rax),%rbx - movq 8+8(%rax),%rbp - - movl 240(%rcx),%r10d - movq %rcx,%r11 - shll $4,%r10d - movups (%rcx),%xmm9 - movups 16(%rcx,%r10,1),%xmm1 - - movdqu (%r9),%xmm15 - pxor %xmm1,%xmm9 - pxor %xmm1,%xmm15 - - movl $16+32,%eax - leaq 32(%r11,%r10,1),%rcx - movups 16(%r11),%xmm1 - subq %r10,%rax - movq %rax,%r10 - - movdqu (%rbx),%xmm10 - movdqu (%rbp),%xmm8 - - testq $1,%r8 - jnz .Locb_dec_odd - - bsfq %r8,%r12 - addq $1,%r8 - shlq $4,%r12 - movdqu (%rbx,%r12,1),%xmm7 - movdqu (%rdi),%xmm2 - leaq 16(%rdi),%rdi - - call __ocb_decrypt1 - - movdqa %xmm7,%xmm15 - movups %xmm2,(%rsi) - xorps %xmm2,%xmm8 - leaq 16(%rsi),%rsi - subq $1,%rdx - jz .Locb_dec_done - -.Locb_dec_odd: - leaq 1(%r8),%r12 - leaq 3(%r8),%r13 - leaq 5(%r8),%r14 - leaq 6(%r8),%r8 - bsfq %r12,%r12 - bsfq %r13,%r13 - bsfq %r14,%r14 - shlq $4,%r12 - shlq $4,%r13 - shlq $4,%r14 - - subq $6,%rdx - jc .Locb_dec_short - jmp .Locb_dec_grandloop - -.align 32 -.Locb_dec_grandloop: - movdqu 0(%rdi),%xmm2 - movdqu 16(%rdi),%xmm3 - movdqu 32(%rdi),%xmm4 - movdqu 48(%rdi),%xmm5 - movdqu 64(%rdi),%xmm6 - movdqu 80(%rdi),%xmm7 - leaq 96(%rdi),%rdi - - call __ocb_decrypt6 - - movups %xmm2,0(%rsi) - pxor %xmm2,%xmm8 - movups %xmm3,16(%rsi) - pxor %xmm3,%xmm8 - movups %xmm4,32(%rsi) - pxor %xmm4,%xmm8 - movups %xmm5,48(%rsi) - pxor %xmm5,%xmm8 - movups %xmm6,64(%rsi) - pxor %xmm6,%xmm8 - movups %xmm7,80(%rsi) - pxor %xmm7,%xmm8 - leaq 96(%rsi),%rsi - subq $6,%rdx - jnc .Locb_dec_grandloop - -.Locb_dec_short: - addq $6,%rdx - jz .Locb_dec_done - - movdqu 0(%rdi),%xmm2 - cmpq $2,%rdx - jb .Locb_dec_one - movdqu 16(%rdi),%xmm3 - je .Locb_dec_two - - movdqu 32(%rdi),%xmm4 - cmpq $4,%rdx - jb .Locb_dec_three - movdqu 48(%rdi),%xmm5 - je .Locb_dec_four - - movdqu 64(%rdi),%xmm6 - pxor %xmm7,%xmm7 - - call __ocb_decrypt6 - - movdqa %xmm14,%xmm15 - movups %xmm2,0(%rsi) - pxor %xmm2,%xmm8 - movups %xmm3,16(%rsi) - pxor %xmm3,%xmm8 - movups %xmm4,32(%rsi) - pxor %xmm4,%xmm8 - movups %xmm5,48(%rsi) - pxor %xmm5,%xmm8 - movups %xmm6,64(%rsi) - pxor %xmm6,%xmm8 - - jmp .Locb_dec_done - -.align 16 -.Locb_dec_one: - movdqa %xmm10,%xmm7 - - call __ocb_decrypt1 - - movdqa %xmm7,%xmm15 - movups %xmm2,0(%rsi) - xorps %xmm2,%xmm8 - jmp .Locb_dec_done - -.align 16 -.Locb_dec_two: - pxor %xmm4,%xmm4 - pxor %xmm5,%xmm5 - - call __ocb_decrypt4 - - movdqa %xmm11,%xmm15 - movups %xmm2,0(%rsi) - xorps %xmm2,%xmm8 - movups %xmm3,16(%rsi) - xorps %xmm3,%xmm8 - - jmp .Locb_dec_done - -.align 16 -.Locb_dec_three: - pxor %xmm5,%xmm5 - - call __ocb_decrypt4 - - movdqa %xmm12,%xmm15 - movups %xmm2,0(%rsi) - xorps %xmm2,%xmm8 - movups %xmm3,16(%rsi) - xorps %xmm3,%xmm8 - movups %xmm4,32(%rsi) - xorps %xmm4,%xmm8 - - jmp .Locb_dec_done - -.align 16 -.Locb_dec_four: - call __ocb_decrypt4 - - movdqa %xmm13,%xmm15 - movups %xmm2,0(%rsi) - pxor %xmm2,%xmm8 - movups %xmm3,16(%rsi) - pxor %xmm3,%xmm8 - movups %xmm4,32(%rsi) - pxor %xmm4,%xmm8 - movups %xmm5,48(%rsi) - pxor %xmm5,%xmm8 - -.Locb_dec_done: - pxor %xmm0,%xmm15 - movdqu %xmm8,(%rbp) - movdqu %xmm15,(%r9) - - xorps %xmm0,%xmm0 - pxor %xmm1,%xmm1 - pxor %xmm2,%xmm2 - pxor %xmm3,%xmm3 - pxor %xmm4,%xmm4 - pxor %xmm5,%xmm5 - pxor %xmm6,%xmm6 - pxor %xmm7,%xmm7 - pxor %xmm8,%xmm8 - pxor %xmm9,%xmm9 - pxor %xmm10,%xmm10 - pxor %xmm11,%xmm11 - pxor %xmm12,%xmm12 - pxor %xmm13,%xmm13 - pxor %xmm14,%xmm14 - pxor %xmm15,%xmm15 - leaq 40(%rsp),%rax -.cfi_def_cfa %rax,8 - movq -40(%rax),%r14 -.cfi_restore %r14 - movq -32(%rax),%r13 -.cfi_restore %r13 - movq -24(%rax),%r12 -.cfi_restore %r12 - movq -16(%rax),%rbp -.cfi_restore %rbp - movq -8(%rax),%rbx -.cfi_restore %rbx - leaq (%rax),%rsp -.cfi_def_cfa_register %rsp -.Locb_dec_epilogue: - .byte 0xf3,0xc3 -.cfi_endproc -.size aes_hw_ocb_decrypt,.-aes_hw_ocb_decrypt - -.type __ocb_decrypt6,@function -.align 32 -__ocb_decrypt6: - pxor %xmm9,%xmm15 - movdqu (%rbx,%r12,1),%xmm11 - movdqa %xmm10,%xmm12 - movdqu (%rbx,%r13,1),%xmm13 - movdqa %xmm10,%xmm14 - pxor %xmm15,%xmm10 - movdqu (%rbx,%r14,1),%xmm15 - pxor %xmm10,%xmm11 - pxor %xmm10,%xmm2 - pxor %xmm11,%xmm12 - pxor %xmm11,%xmm3 - pxor %xmm12,%xmm13 - pxor %xmm12,%xmm4 - pxor %xmm13,%xmm14 - pxor %xmm13,%xmm5 - pxor %xmm14,%xmm15 - pxor %xmm14,%xmm6 - pxor %xmm15,%xmm7 - movups 32(%r11),%xmm0 - - leaq 1(%r8),%r12 - leaq 3(%r8),%r13 - leaq 5(%r8),%r14 - addq $6,%r8 - pxor %xmm9,%xmm10 - bsfq %r12,%r12 - bsfq %r13,%r13 - bsfq %r14,%r14 - -.byte 102,15,56,222,209 -.byte 102,15,56,222,217 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 - pxor %xmm9,%xmm11 - pxor %xmm9,%xmm12 -.byte 102,15,56,222,241 - pxor %xmm9,%xmm13 - pxor %xmm9,%xmm14 -.byte 102,15,56,222,249 - movups 48(%r11),%xmm1 - pxor %xmm9,%xmm15 - -.byte 102,15,56,222,208 -.byte 102,15,56,222,216 -.byte 102,15,56,222,224 -.byte 102,15,56,222,232 -.byte 102,15,56,222,240 -.byte 102,15,56,222,248 - movups 64(%r11),%xmm0 - shlq $4,%r12 - shlq $4,%r13 - jmp .Locb_dec_loop6 - -.align 32 -.Locb_dec_loop6: -.byte 102,15,56,222,209 -.byte 102,15,56,222,217 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 -.byte 102,15,56,222,241 -.byte 102,15,56,222,249 - movups (%rcx,%rax,1),%xmm1 - addq $32,%rax - -.byte 102,15,56,222,208 -.byte 102,15,56,222,216 -.byte 102,15,56,222,224 -.byte 102,15,56,222,232 -.byte 102,15,56,222,240 -.byte 102,15,56,222,248 - movups -16(%rcx,%rax,1),%xmm0 - jnz .Locb_dec_loop6 - -.byte 102,15,56,222,209 -.byte 102,15,56,222,217 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 -.byte 102,15,56,222,241 -.byte 102,15,56,222,249 - movups 16(%r11),%xmm1 - shlq $4,%r14 - -.byte 102,65,15,56,223,210 - movdqu (%rbx),%xmm10 - movq %r10,%rax -.byte 102,65,15,56,223,219 -.byte 102,65,15,56,223,228 -.byte 102,65,15,56,223,237 -.byte 102,65,15,56,223,246 -.byte 102,65,15,56,223,255 - .byte 0xf3,0xc3 -.size __ocb_decrypt6,.-__ocb_decrypt6 - -.type __ocb_decrypt4,@function -.align 32 -__ocb_decrypt4: - pxor %xmm9,%xmm15 - movdqu (%rbx,%r12,1),%xmm11 - movdqa %xmm10,%xmm12 - movdqu (%rbx,%r13,1),%xmm13 - pxor %xmm15,%xmm10 - pxor %xmm10,%xmm11 - pxor %xmm10,%xmm2 - pxor %xmm11,%xmm12 - pxor %xmm11,%xmm3 - pxor %xmm12,%xmm13 - pxor %xmm12,%xmm4 - pxor %xmm13,%xmm5 - movups 32(%r11),%xmm0 - - pxor %xmm9,%xmm10 - pxor %xmm9,%xmm11 - pxor %xmm9,%xmm12 - pxor %xmm9,%xmm13 - -.byte 102,15,56,222,209 -.byte 102,15,56,222,217 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 - movups 48(%r11),%xmm1 - -.byte 102,15,56,222,208 -.byte 102,15,56,222,216 -.byte 102,15,56,222,224 -.byte 102,15,56,222,232 - movups 64(%r11),%xmm0 - jmp .Locb_dec_loop4 - -.align 32 -.Locb_dec_loop4: -.byte 102,15,56,222,209 -.byte 102,15,56,222,217 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 - movups (%rcx,%rax,1),%xmm1 - addq $32,%rax - -.byte 102,15,56,222,208 -.byte 102,15,56,222,216 -.byte 102,15,56,222,224 -.byte 102,15,56,222,232 - movups -16(%rcx,%rax,1),%xmm0 - jnz .Locb_dec_loop4 - -.byte 102,15,56,222,209 -.byte 102,15,56,222,217 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 - movups 16(%r11),%xmm1 - movq %r10,%rax - -.byte 102,65,15,56,223,210 -.byte 102,65,15,56,223,219 -.byte 102,65,15,56,223,228 -.byte 102,65,15,56,223,237 - .byte 0xf3,0xc3 -.size __ocb_decrypt4,.-__ocb_decrypt4 - -.type __ocb_decrypt1,@function -.align 32 -__ocb_decrypt1: - pxor %xmm15,%xmm7 - pxor %xmm9,%xmm7 - pxor %xmm7,%xmm2 - movups 32(%r11),%xmm0 - -.byte 102,15,56,222,209 - movups 48(%r11),%xmm1 - pxor %xmm9,%xmm7 - -.byte 102,15,56,222,208 - movups 64(%r11),%xmm0 - jmp .Locb_dec_loop1 - -.align 32 -.Locb_dec_loop1: -.byte 102,15,56,222,209 - movups (%rcx,%rax,1),%xmm1 - addq $32,%rax - -.byte 102,15,56,222,208 - movups -16(%rcx,%rax,1),%xmm0 - jnz .Locb_dec_loop1 - -.byte 102,15,56,222,209 - movups 16(%r11),%xmm1 - movq %r10,%rax - -.byte 102,15,56,223,215 - .byte 0xf3,0xc3 -.size __ocb_decrypt1,.-__ocb_decrypt1 .globl aes_hw_cbc_encrypt .hidden aes_hw_cbc_encrypt .type aes_hw_cbc_encrypt,@function @@ -3479,12 +1496,12 @@ aes_hw_cbc_encrypt: xorps %xmm0,%xmm3 leaq 32(%rcx),%rcx xorps %xmm3,%xmm2 -.Loop_enc1_15: +.Loop_enc1_6: .byte 102,15,56,220,209 decl %eax movups (%rcx),%xmm1 leaq 16(%rcx),%rcx - jnz .Loop_enc1_15 + jnz .Loop_enc1_6 .byte 102,15,56,221,209 movl %r10d,%eax movq %r11,%rcx @@ -3530,12 +1547,12 @@ aes_hw_cbc_encrypt: movups 16(%rcx),%xmm1 leaq 32(%rcx),%rcx xorps %xmm0,%xmm2 -.Loop_dec1_16: +.Loop_dec1_7: .byte 102,15,56,222,209 decl %r10d movups (%rcx),%xmm1 leaq 16(%rcx),%rcx - jnz .Loop_dec1_16 + jnz .Loop_dec1_7 .byte 102,15,56,223,209 pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 @@ -3948,12 +1965,12 @@ aes_hw_cbc_encrypt: movups 16(%rcx),%xmm1 leaq 32(%rcx),%rcx xorps %xmm0,%xmm2 -.Loop_dec1_17: +.Loop_dec1_8: .byte 102,15,56,222,209 decl %eax movups (%rcx),%xmm1 leaq 16(%rcx),%rcx - jnz .Loop_dec1_17 + jnz .Loop_dec1_8 .byte 102,15,56,223,209 xorps %xmm10,%xmm2 movaps %xmm11,%xmm10 @@ -4094,6 +2111,11 @@ aes_hw_set_decrypt_key: aes_hw_set_encrypt_key: __aesni_set_encrypt_key: .cfi_startproc +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS + movb $1,BORINGSSL_function_hit+3(%rip) +#endif +#endif .byte 0x48,0x83,0xEC,0x08 .cfi_adjust_cfa_offset 8 movq $-1,%rax diff --git a/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/bsaes-x86_64.S b/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/bsaes-x86_64.S deleted file mode 100644 index c4cec5c2..00000000 --- a/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/bsaes-x86_64.S +++ /dev/null @@ -1,1640 +0,0 @@ -# This file is generated from a similarly-named Perl script in the BoringSSL -# source tree. Do not edit by hand. - -#if defined(__has_feature) -#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) -#define OPENSSL_NO_ASM -#endif -#endif - -#if defined(__x86_64__) && !defined(OPENSSL_NO_ASM) -#if defined(BORINGSSL_PREFIX) -#include -#endif -.text - -.extern aes_nohw_encrypt -.hidden aes_nohw_encrypt -.extern aes_nohw_decrypt -.hidden aes_nohw_decrypt - -.type _bsaes_encrypt8,@function -.align 64 -_bsaes_encrypt8: -.cfi_startproc - leaq .LBS0(%rip),%r11 - - movdqa (%rax),%xmm8 - leaq 16(%rax),%rax - movdqa 80(%r11),%xmm7 - pxor %xmm8,%xmm15 - pxor %xmm8,%xmm0 - pxor %xmm8,%xmm1 - pxor %xmm8,%xmm2 -.byte 102,68,15,56,0,255 -.byte 102,15,56,0,199 - pxor %xmm8,%xmm3 - pxor %xmm8,%xmm4 -.byte 102,15,56,0,207 -.byte 102,15,56,0,215 - pxor %xmm8,%xmm5 - pxor %xmm8,%xmm6 -.byte 102,15,56,0,223 -.byte 102,15,56,0,231 -.byte 102,15,56,0,239 -.byte 102,15,56,0,247 -_bsaes_encrypt8_bitslice: - movdqa 0(%r11),%xmm7 - movdqa 16(%r11),%xmm8 - movdqa %xmm5,%xmm9 - psrlq $1,%xmm5 - movdqa %xmm3,%xmm10 - psrlq $1,%xmm3 - pxor %xmm6,%xmm5 - pxor %xmm4,%xmm3 - pand %xmm7,%xmm5 - pand %xmm7,%xmm3 - pxor %xmm5,%xmm6 - psllq $1,%xmm5 - pxor %xmm3,%xmm4 - psllq $1,%xmm3 - pxor %xmm9,%xmm5 - pxor %xmm10,%xmm3 - movdqa %xmm1,%xmm9 - psrlq $1,%xmm1 - movdqa %xmm15,%xmm10 - psrlq $1,%xmm15 - pxor %xmm2,%xmm1 - pxor %xmm0,%xmm15 - pand %xmm7,%xmm1 - pand %xmm7,%xmm15 - pxor %xmm1,%xmm2 - psllq $1,%xmm1 - pxor %xmm15,%xmm0 - psllq $1,%xmm15 - pxor %xmm9,%xmm1 - pxor %xmm10,%xmm15 - movdqa 32(%r11),%xmm7 - movdqa %xmm4,%xmm9 - psrlq $2,%xmm4 - movdqa %xmm3,%xmm10 - psrlq $2,%xmm3 - pxor %xmm6,%xmm4 - pxor %xmm5,%xmm3 - pand %xmm8,%xmm4 - pand %xmm8,%xmm3 - pxor %xmm4,%xmm6 - psllq $2,%xmm4 - pxor %xmm3,%xmm5 - psllq $2,%xmm3 - pxor %xmm9,%xmm4 - pxor %xmm10,%xmm3 - movdqa %xmm0,%xmm9 - psrlq $2,%xmm0 - movdqa %xmm15,%xmm10 - psrlq $2,%xmm15 - pxor %xmm2,%xmm0 - pxor %xmm1,%xmm15 - pand %xmm8,%xmm0 - pand %xmm8,%xmm15 - pxor %xmm0,%xmm2 - psllq $2,%xmm0 - pxor %xmm15,%xmm1 - psllq $2,%xmm15 - pxor %xmm9,%xmm0 - pxor %xmm10,%xmm15 - movdqa %xmm2,%xmm9 - psrlq $4,%xmm2 - movdqa %xmm1,%xmm10 - psrlq $4,%xmm1 - pxor %xmm6,%xmm2 - pxor %xmm5,%xmm1 - pand %xmm7,%xmm2 - pand %xmm7,%xmm1 - pxor %xmm2,%xmm6 - psllq $4,%xmm2 - pxor %xmm1,%xmm5 - psllq $4,%xmm1 - pxor %xmm9,%xmm2 - pxor %xmm10,%xmm1 - movdqa %xmm0,%xmm9 - psrlq $4,%xmm0 - movdqa %xmm15,%xmm10 - psrlq $4,%xmm15 - pxor %xmm4,%xmm0 - pxor %xmm3,%xmm15 - pand %xmm7,%xmm0 - pand %xmm7,%xmm15 - pxor %xmm0,%xmm4 - psllq $4,%xmm0 - pxor %xmm15,%xmm3 - psllq $4,%xmm15 - pxor %xmm9,%xmm0 - pxor %xmm10,%xmm15 - decl %r10d - jmp .Lenc_sbox -.align 16 -.Lenc_loop: - pxor 0(%rax),%xmm15 - pxor 16(%rax),%xmm0 - pxor 32(%rax),%xmm1 - pxor 48(%rax),%xmm2 -.byte 102,68,15,56,0,255 -.byte 102,15,56,0,199 - pxor 64(%rax),%xmm3 - pxor 80(%rax),%xmm4 -.byte 102,15,56,0,207 -.byte 102,15,56,0,215 - pxor 96(%rax),%xmm5 - pxor 112(%rax),%xmm6 -.byte 102,15,56,0,223 -.byte 102,15,56,0,231 -.byte 102,15,56,0,239 -.byte 102,15,56,0,247 - leaq 128(%rax),%rax -.Lenc_sbox: - pxor %xmm5,%xmm4 - pxor %xmm0,%xmm1 - pxor %xmm15,%xmm2 - pxor %xmm1,%xmm5 - pxor %xmm15,%xmm4 - - pxor %xmm2,%xmm5 - pxor %xmm6,%xmm2 - pxor %xmm4,%xmm6 - pxor %xmm3,%xmm2 - pxor %xmm4,%xmm3 - pxor %xmm0,%xmm2 - - pxor %xmm6,%xmm1 - pxor %xmm4,%xmm0 - movdqa %xmm6,%xmm10 - movdqa %xmm0,%xmm9 - movdqa %xmm4,%xmm8 - movdqa %xmm1,%xmm12 - movdqa %xmm5,%xmm11 - - pxor %xmm3,%xmm10 - pxor %xmm1,%xmm9 - pxor %xmm2,%xmm8 - movdqa %xmm10,%xmm13 - pxor %xmm3,%xmm12 - movdqa %xmm9,%xmm7 - pxor %xmm15,%xmm11 - movdqa %xmm10,%xmm14 - - por %xmm8,%xmm9 - por %xmm11,%xmm10 - pxor %xmm7,%xmm14 - pand %xmm11,%xmm13 - pxor %xmm8,%xmm11 - pand %xmm8,%xmm7 - pand %xmm11,%xmm14 - movdqa %xmm2,%xmm11 - pxor %xmm15,%xmm11 - pand %xmm11,%xmm12 - pxor %xmm12,%xmm10 - pxor %xmm12,%xmm9 - movdqa %xmm6,%xmm12 - movdqa %xmm4,%xmm11 - pxor %xmm0,%xmm12 - pxor %xmm5,%xmm11 - movdqa %xmm12,%xmm8 - pand %xmm11,%xmm12 - por %xmm11,%xmm8 - pxor %xmm12,%xmm7 - pxor %xmm14,%xmm10 - pxor %xmm13,%xmm9 - pxor %xmm14,%xmm8 - movdqa %xmm1,%xmm11 - pxor %xmm13,%xmm7 - movdqa %xmm3,%xmm12 - pxor %xmm13,%xmm8 - movdqa %xmm0,%xmm13 - pand %xmm2,%xmm11 - movdqa %xmm6,%xmm14 - pand %xmm15,%xmm12 - pand %xmm4,%xmm13 - por %xmm5,%xmm14 - pxor %xmm11,%xmm10 - pxor %xmm12,%xmm9 - pxor %xmm13,%xmm8 - pxor %xmm14,%xmm7 - - - - - - movdqa %xmm10,%xmm11 - pand %xmm8,%xmm10 - pxor %xmm9,%xmm11 - - movdqa %xmm7,%xmm13 - movdqa %xmm11,%xmm14 - pxor %xmm10,%xmm13 - pand %xmm13,%xmm14 - - movdqa %xmm8,%xmm12 - pxor %xmm9,%xmm14 - pxor %xmm7,%xmm12 - - pxor %xmm9,%xmm10 - - pand %xmm10,%xmm12 - - movdqa %xmm13,%xmm9 - pxor %xmm7,%xmm12 - - pxor %xmm12,%xmm9 - pxor %xmm12,%xmm8 - - pand %xmm7,%xmm9 - - pxor %xmm9,%xmm13 - pxor %xmm9,%xmm8 - - pand %xmm14,%xmm13 - - pxor %xmm11,%xmm13 - movdqa %xmm5,%xmm11 - movdqa %xmm4,%xmm7 - movdqa %xmm14,%xmm9 - pxor %xmm13,%xmm9 - pand %xmm5,%xmm9 - pxor %xmm4,%xmm5 - pand %xmm14,%xmm4 - pand %xmm13,%xmm5 - pxor %xmm4,%xmm5 - pxor %xmm9,%xmm4 - pxor %xmm15,%xmm11 - pxor %xmm2,%xmm7 - pxor %xmm12,%xmm14 - pxor %xmm8,%xmm13 - movdqa %xmm14,%xmm10 - movdqa %xmm12,%xmm9 - pxor %xmm13,%xmm10 - pxor %xmm8,%xmm9 - pand %xmm11,%xmm10 - pand %xmm15,%xmm9 - pxor %xmm7,%xmm11 - pxor %xmm2,%xmm15 - pand %xmm14,%xmm7 - pand %xmm12,%xmm2 - pand %xmm13,%xmm11 - pand %xmm8,%xmm15 - pxor %xmm11,%xmm7 - pxor %xmm2,%xmm15 - pxor %xmm10,%xmm11 - pxor %xmm9,%xmm2 - pxor %xmm11,%xmm5 - pxor %xmm11,%xmm15 - pxor %xmm7,%xmm4 - pxor %xmm7,%xmm2 - - movdqa %xmm6,%xmm11 - movdqa %xmm0,%xmm7 - pxor %xmm3,%xmm11 - pxor %xmm1,%xmm7 - movdqa %xmm14,%xmm10 - movdqa %xmm12,%xmm9 - pxor %xmm13,%xmm10 - pxor %xmm8,%xmm9 - pand %xmm11,%xmm10 - pand %xmm3,%xmm9 - pxor %xmm7,%xmm11 - pxor %xmm1,%xmm3 - pand %xmm14,%xmm7 - pand %xmm12,%xmm1 - pand %xmm13,%xmm11 - pand %xmm8,%xmm3 - pxor %xmm11,%xmm7 - pxor %xmm1,%xmm3 - pxor %xmm10,%xmm11 - pxor %xmm9,%xmm1 - pxor %xmm12,%xmm14 - pxor %xmm8,%xmm13 - movdqa %xmm14,%xmm10 - pxor %xmm13,%xmm10 - pand %xmm6,%xmm10 - pxor %xmm0,%xmm6 - pand %xmm14,%xmm0 - pand %xmm13,%xmm6 - pxor %xmm0,%xmm6 - pxor %xmm10,%xmm0 - pxor %xmm11,%xmm6 - pxor %xmm11,%xmm3 - pxor %xmm7,%xmm0 - pxor %xmm7,%xmm1 - pxor %xmm15,%xmm6 - pxor %xmm5,%xmm0 - pxor %xmm6,%xmm3 - pxor %xmm15,%xmm5 - pxor %xmm0,%xmm15 - - pxor %xmm4,%xmm0 - pxor %xmm1,%xmm4 - pxor %xmm2,%xmm1 - pxor %xmm4,%xmm2 - pxor %xmm4,%xmm3 - - pxor %xmm2,%xmm5 - decl %r10d - jl .Lenc_done - pshufd $0x93,%xmm15,%xmm7 - pshufd $0x93,%xmm0,%xmm8 - pxor %xmm7,%xmm15 - pshufd $0x93,%xmm3,%xmm9 - pxor %xmm8,%xmm0 - pshufd $0x93,%xmm5,%xmm10 - pxor %xmm9,%xmm3 - pshufd $0x93,%xmm2,%xmm11 - pxor %xmm10,%xmm5 - pshufd $0x93,%xmm6,%xmm12 - pxor %xmm11,%xmm2 - pshufd $0x93,%xmm1,%xmm13 - pxor %xmm12,%xmm6 - pshufd $0x93,%xmm4,%xmm14 - pxor %xmm13,%xmm1 - pxor %xmm14,%xmm4 - - pxor %xmm15,%xmm8 - pxor %xmm4,%xmm7 - pxor %xmm4,%xmm8 - pshufd $0x4E,%xmm15,%xmm15 - pxor %xmm0,%xmm9 - pshufd $0x4E,%xmm0,%xmm0 - pxor %xmm2,%xmm12 - pxor %xmm7,%xmm15 - pxor %xmm6,%xmm13 - pxor %xmm8,%xmm0 - pxor %xmm5,%xmm11 - pshufd $0x4E,%xmm2,%xmm7 - pxor %xmm1,%xmm14 - pshufd $0x4E,%xmm6,%xmm8 - pxor %xmm3,%xmm10 - pshufd $0x4E,%xmm5,%xmm2 - pxor %xmm4,%xmm10 - pshufd $0x4E,%xmm4,%xmm6 - pxor %xmm4,%xmm11 - pshufd $0x4E,%xmm1,%xmm5 - pxor %xmm11,%xmm7 - pshufd $0x4E,%xmm3,%xmm1 - pxor %xmm12,%xmm8 - pxor %xmm10,%xmm2 - pxor %xmm14,%xmm6 - pxor %xmm13,%xmm5 - movdqa %xmm7,%xmm3 - pxor %xmm9,%xmm1 - movdqa %xmm8,%xmm4 - movdqa 48(%r11),%xmm7 - jnz .Lenc_loop - movdqa 64(%r11),%xmm7 - jmp .Lenc_loop -.align 16 -.Lenc_done: - movdqa 0(%r11),%xmm7 - movdqa 16(%r11),%xmm8 - movdqa %xmm1,%xmm9 - psrlq $1,%xmm1 - movdqa %xmm2,%xmm10 - psrlq $1,%xmm2 - pxor %xmm4,%xmm1 - pxor %xmm6,%xmm2 - pand %xmm7,%xmm1 - pand %xmm7,%xmm2 - pxor %xmm1,%xmm4 - psllq $1,%xmm1 - pxor %xmm2,%xmm6 - psllq $1,%xmm2 - pxor %xmm9,%xmm1 - pxor %xmm10,%xmm2 - movdqa %xmm3,%xmm9 - psrlq $1,%xmm3 - movdqa %xmm15,%xmm10 - psrlq $1,%xmm15 - pxor %xmm5,%xmm3 - pxor %xmm0,%xmm15 - pand %xmm7,%xmm3 - pand %xmm7,%xmm15 - pxor %xmm3,%xmm5 - psllq $1,%xmm3 - pxor %xmm15,%xmm0 - psllq $1,%xmm15 - pxor %xmm9,%xmm3 - pxor %xmm10,%xmm15 - movdqa 32(%r11),%xmm7 - movdqa %xmm6,%xmm9 - psrlq $2,%xmm6 - movdqa %xmm2,%xmm10 - psrlq $2,%xmm2 - pxor %xmm4,%xmm6 - pxor %xmm1,%xmm2 - pand %xmm8,%xmm6 - pand %xmm8,%xmm2 - pxor %xmm6,%xmm4 - psllq $2,%xmm6 - pxor %xmm2,%xmm1 - psllq $2,%xmm2 - pxor %xmm9,%xmm6 - pxor %xmm10,%xmm2 - movdqa %xmm0,%xmm9 - psrlq $2,%xmm0 - movdqa %xmm15,%xmm10 - psrlq $2,%xmm15 - pxor %xmm5,%xmm0 - pxor %xmm3,%xmm15 - pand %xmm8,%xmm0 - pand %xmm8,%xmm15 - pxor %xmm0,%xmm5 - psllq $2,%xmm0 - pxor %xmm15,%xmm3 - psllq $2,%xmm15 - pxor %xmm9,%xmm0 - pxor %xmm10,%xmm15 - movdqa %xmm5,%xmm9 - psrlq $4,%xmm5 - movdqa %xmm3,%xmm10 - psrlq $4,%xmm3 - pxor %xmm4,%xmm5 - pxor %xmm1,%xmm3 - pand %xmm7,%xmm5 - pand %xmm7,%xmm3 - pxor %xmm5,%xmm4 - psllq $4,%xmm5 - pxor %xmm3,%xmm1 - psllq $4,%xmm3 - pxor %xmm9,%xmm5 - pxor %xmm10,%xmm3 - movdqa %xmm0,%xmm9 - psrlq $4,%xmm0 - movdqa %xmm15,%xmm10 - psrlq $4,%xmm15 - pxor %xmm6,%xmm0 - pxor %xmm2,%xmm15 - pand %xmm7,%xmm0 - pand %xmm7,%xmm15 - pxor %xmm0,%xmm6 - psllq $4,%xmm0 - pxor %xmm15,%xmm2 - psllq $4,%xmm15 - pxor %xmm9,%xmm0 - pxor %xmm10,%xmm15 - movdqa (%rax),%xmm7 - pxor %xmm7,%xmm3 - pxor %xmm7,%xmm5 - pxor %xmm7,%xmm2 - pxor %xmm7,%xmm6 - pxor %xmm7,%xmm1 - pxor %xmm7,%xmm4 - pxor %xmm7,%xmm15 - pxor %xmm7,%xmm0 - .byte 0xf3,0xc3 -.cfi_endproc -.size _bsaes_encrypt8,.-_bsaes_encrypt8 - -.type _bsaes_decrypt8,@function -.align 64 -_bsaes_decrypt8: -.cfi_startproc - leaq .LBS0(%rip),%r11 - - movdqa (%rax),%xmm8 - leaq 16(%rax),%rax - movdqa -48(%r11),%xmm7 - pxor %xmm8,%xmm15 - pxor %xmm8,%xmm0 - pxor %xmm8,%xmm1 - pxor %xmm8,%xmm2 -.byte 102,68,15,56,0,255 -.byte 102,15,56,0,199 - pxor %xmm8,%xmm3 - pxor %xmm8,%xmm4 -.byte 102,15,56,0,207 -.byte 102,15,56,0,215 - pxor %xmm8,%xmm5 - pxor %xmm8,%xmm6 -.byte 102,15,56,0,223 -.byte 102,15,56,0,231 -.byte 102,15,56,0,239 -.byte 102,15,56,0,247 - movdqa 0(%r11),%xmm7 - movdqa 16(%r11),%xmm8 - movdqa %xmm5,%xmm9 - psrlq $1,%xmm5 - movdqa %xmm3,%xmm10 - psrlq $1,%xmm3 - pxor %xmm6,%xmm5 - pxor %xmm4,%xmm3 - pand %xmm7,%xmm5 - pand %xmm7,%xmm3 - pxor %xmm5,%xmm6 - psllq $1,%xmm5 - pxor %xmm3,%xmm4 - psllq $1,%xmm3 - pxor %xmm9,%xmm5 - pxor %xmm10,%xmm3 - movdqa %xmm1,%xmm9 - psrlq $1,%xmm1 - movdqa %xmm15,%xmm10 - psrlq $1,%xmm15 - pxor %xmm2,%xmm1 - pxor %xmm0,%xmm15 - pand %xmm7,%xmm1 - pand %xmm7,%xmm15 - pxor %xmm1,%xmm2 - psllq $1,%xmm1 - pxor %xmm15,%xmm0 - psllq $1,%xmm15 - pxor %xmm9,%xmm1 - pxor %xmm10,%xmm15 - movdqa 32(%r11),%xmm7 - movdqa %xmm4,%xmm9 - psrlq $2,%xmm4 - movdqa %xmm3,%xmm10 - psrlq $2,%xmm3 - pxor %xmm6,%xmm4 - pxor %xmm5,%xmm3 - pand %xmm8,%xmm4 - pand %xmm8,%xmm3 - pxor %xmm4,%xmm6 - psllq $2,%xmm4 - pxor %xmm3,%xmm5 - psllq $2,%xmm3 - pxor %xmm9,%xmm4 - pxor %xmm10,%xmm3 - movdqa %xmm0,%xmm9 - psrlq $2,%xmm0 - movdqa %xmm15,%xmm10 - psrlq $2,%xmm15 - pxor %xmm2,%xmm0 - pxor %xmm1,%xmm15 - pand %xmm8,%xmm0 - pand %xmm8,%xmm15 - pxor %xmm0,%xmm2 - psllq $2,%xmm0 - pxor %xmm15,%xmm1 - psllq $2,%xmm15 - pxor %xmm9,%xmm0 - pxor %xmm10,%xmm15 - movdqa %xmm2,%xmm9 - psrlq $4,%xmm2 - movdqa %xmm1,%xmm10 - psrlq $4,%xmm1 - pxor %xmm6,%xmm2 - pxor %xmm5,%xmm1 - pand %xmm7,%xmm2 - pand %xmm7,%xmm1 - pxor %xmm2,%xmm6 - psllq $4,%xmm2 - pxor %xmm1,%xmm5 - psllq $4,%xmm1 - pxor %xmm9,%xmm2 - pxor %xmm10,%xmm1 - movdqa %xmm0,%xmm9 - psrlq $4,%xmm0 - movdqa %xmm15,%xmm10 - psrlq $4,%xmm15 - pxor %xmm4,%xmm0 - pxor %xmm3,%xmm15 - pand %xmm7,%xmm0 - pand %xmm7,%xmm15 - pxor %xmm0,%xmm4 - psllq $4,%xmm0 - pxor %xmm15,%xmm3 - psllq $4,%xmm15 - pxor %xmm9,%xmm0 - pxor %xmm10,%xmm15 - decl %r10d - jmp .Ldec_sbox -.align 16 -.Ldec_loop: - pxor 0(%rax),%xmm15 - pxor 16(%rax),%xmm0 - pxor 32(%rax),%xmm1 - pxor 48(%rax),%xmm2 -.byte 102,68,15,56,0,255 -.byte 102,15,56,0,199 - pxor 64(%rax),%xmm3 - pxor 80(%rax),%xmm4 -.byte 102,15,56,0,207 -.byte 102,15,56,0,215 - pxor 96(%rax),%xmm5 - pxor 112(%rax),%xmm6 -.byte 102,15,56,0,223 -.byte 102,15,56,0,231 -.byte 102,15,56,0,239 -.byte 102,15,56,0,247 - leaq 128(%rax),%rax -.Ldec_sbox: - pxor %xmm3,%xmm2 - - pxor %xmm6,%xmm3 - pxor %xmm6,%xmm1 - pxor %xmm3,%xmm5 - pxor %xmm5,%xmm6 - pxor %xmm6,%xmm0 - - pxor %xmm0,%xmm15 - pxor %xmm4,%xmm1 - pxor %xmm15,%xmm2 - pxor %xmm15,%xmm4 - pxor %xmm2,%xmm0 - movdqa %xmm2,%xmm10 - movdqa %xmm6,%xmm9 - movdqa %xmm0,%xmm8 - movdqa %xmm3,%xmm12 - movdqa %xmm4,%xmm11 - - pxor %xmm15,%xmm10 - pxor %xmm3,%xmm9 - pxor %xmm5,%xmm8 - movdqa %xmm10,%xmm13 - pxor %xmm15,%xmm12 - movdqa %xmm9,%xmm7 - pxor %xmm1,%xmm11 - movdqa %xmm10,%xmm14 - - por %xmm8,%xmm9 - por %xmm11,%xmm10 - pxor %xmm7,%xmm14 - pand %xmm11,%xmm13 - pxor %xmm8,%xmm11 - pand %xmm8,%xmm7 - pand %xmm11,%xmm14 - movdqa %xmm5,%xmm11 - pxor %xmm1,%xmm11 - pand %xmm11,%xmm12 - pxor %xmm12,%xmm10 - pxor %xmm12,%xmm9 - movdqa %xmm2,%xmm12 - movdqa %xmm0,%xmm11 - pxor %xmm6,%xmm12 - pxor %xmm4,%xmm11 - movdqa %xmm12,%xmm8 - pand %xmm11,%xmm12 - por %xmm11,%xmm8 - pxor %xmm12,%xmm7 - pxor %xmm14,%xmm10 - pxor %xmm13,%xmm9 - pxor %xmm14,%xmm8 - movdqa %xmm3,%xmm11 - pxor %xmm13,%xmm7 - movdqa %xmm15,%xmm12 - pxor %xmm13,%xmm8 - movdqa %xmm6,%xmm13 - pand %xmm5,%xmm11 - movdqa %xmm2,%xmm14 - pand %xmm1,%xmm12 - pand %xmm0,%xmm13 - por %xmm4,%xmm14 - pxor %xmm11,%xmm10 - pxor %xmm12,%xmm9 - pxor %xmm13,%xmm8 - pxor %xmm14,%xmm7 - - - - - - movdqa %xmm10,%xmm11 - pand %xmm8,%xmm10 - pxor %xmm9,%xmm11 - - movdqa %xmm7,%xmm13 - movdqa %xmm11,%xmm14 - pxor %xmm10,%xmm13 - pand %xmm13,%xmm14 - - movdqa %xmm8,%xmm12 - pxor %xmm9,%xmm14 - pxor %xmm7,%xmm12 - - pxor %xmm9,%xmm10 - - pand %xmm10,%xmm12 - - movdqa %xmm13,%xmm9 - pxor %xmm7,%xmm12 - - pxor %xmm12,%xmm9 - pxor %xmm12,%xmm8 - - pand %xmm7,%xmm9 - - pxor %xmm9,%xmm13 - pxor %xmm9,%xmm8 - - pand %xmm14,%xmm13 - - pxor %xmm11,%xmm13 - movdqa %xmm4,%xmm11 - movdqa %xmm0,%xmm7 - movdqa %xmm14,%xmm9 - pxor %xmm13,%xmm9 - pand %xmm4,%xmm9 - pxor %xmm0,%xmm4 - pand %xmm14,%xmm0 - pand %xmm13,%xmm4 - pxor %xmm0,%xmm4 - pxor %xmm9,%xmm0 - pxor %xmm1,%xmm11 - pxor %xmm5,%xmm7 - pxor %xmm12,%xmm14 - pxor %xmm8,%xmm13 - movdqa %xmm14,%xmm10 - movdqa %xmm12,%xmm9 - pxor %xmm13,%xmm10 - pxor %xmm8,%xmm9 - pand %xmm11,%xmm10 - pand %xmm1,%xmm9 - pxor %xmm7,%xmm11 - pxor %xmm5,%xmm1 - pand %xmm14,%xmm7 - pand %xmm12,%xmm5 - pand %xmm13,%xmm11 - pand %xmm8,%xmm1 - pxor %xmm11,%xmm7 - pxor %xmm5,%xmm1 - pxor %xmm10,%xmm11 - pxor %xmm9,%xmm5 - pxor %xmm11,%xmm4 - pxor %xmm11,%xmm1 - pxor %xmm7,%xmm0 - pxor %xmm7,%xmm5 - - movdqa %xmm2,%xmm11 - movdqa %xmm6,%xmm7 - pxor %xmm15,%xmm11 - pxor %xmm3,%xmm7 - movdqa %xmm14,%xmm10 - movdqa %xmm12,%xmm9 - pxor %xmm13,%xmm10 - pxor %xmm8,%xmm9 - pand %xmm11,%xmm10 - pand %xmm15,%xmm9 - pxor %xmm7,%xmm11 - pxor %xmm3,%xmm15 - pand %xmm14,%xmm7 - pand %xmm12,%xmm3 - pand %xmm13,%xmm11 - pand %xmm8,%xmm15 - pxor %xmm11,%xmm7 - pxor %xmm3,%xmm15 - pxor %xmm10,%xmm11 - pxor %xmm9,%xmm3 - pxor %xmm12,%xmm14 - pxor %xmm8,%xmm13 - movdqa %xmm14,%xmm10 - pxor %xmm13,%xmm10 - pand %xmm2,%xmm10 - pxor %xmm6,%xmm2 - pand %xmm14,%xmm6 - pand %xmm13,%xmm2 - pxor %xmm6,%xmm2 - pxor %xmm10,%xmm6 - pxor %xmm11,%xmm2 - pxor %xmm11,%xmm15 - pxor %xmm7,%xmm6 - pxor %xmm7,%xmm3 - pxor %xmm6,%xmm0 - pxor %xmm4,%xmm5 - - pxor %xmm0,%xmm3 - pxor %xmm6,%xmm1 - pxor %xmm6,%xmm4 - pxor %xmm1,%xmm3 - pxor %xmm15,%xmm6 - pxor %xmm4,%xmm3 - pxor %xmm5,%xmm2 - pxor %xmm0,%xmm5 - pxor %xmm3,%xmm2 - - pxor %xmm15,%xmm3 - pxor %xmm2,%xmm6 - decl %r10d - jl .Ldec_done - - pshufd $0x4E,%xmm15,%xmm7 - pshufd $0x4E,%xmm2,%xmm13 - pxor %xmm15,%xmm7 - pshufd $0x4E,%xmm4,%xmm14 - pxor %xmm2,%xmm13 - pshufd $0x4E,%xmm0,%xmm8 - pxor %xmm4,%xmm14 - pshufd $0x4E,%xmm5,%xmm9 - pxor %xmm0,%xmm8 - pshufd $0x4E,%xmm3,%xmm10 - pxor %xmm5,%xmm9 - pxor %xmm13,%xmm15 - pxor %xmm13,%xmm0 - pshufd $0x4E,%xmm1,%xmm11 - pxor %xmm3,%xmm10 - pxor %xmm7,%xmm5 - pxor %xmm8,%xmm3 - pshufd $0x4E,%xmm6,%xmm12 - pxor %xmm1,%xmm11 - pxor %xmm14,%xmm0 - pxor %xmm9,%xmm1 - pxor %xmm6,%xmm12 - - pxor %xmm14,%xmm5 - pxor %xmm13,%xmm3 - pxor %xmm13,%xmm1 - pxor %xmm10,%xmm6 - pxor %xmm11,%xmm2 - pxor %xmm14,%xmm1 - pxor %xmm14,%xmm6 - pxor %xmm12,%xmm4 - pshufd $0x93,%xmm15,%xmm7 - pshufd $0x93,%xmm0,%xmm8 - pxor %xmm7,%xmm15 - pshufd $0x93,%xmm5,%xmm9 - pxor %xmm8,%xmm0 - pshufd $0x93,%xmm3,%xmm10 - pxor %xmm9,%xmm5 - pshufd $0x93,%xmm1,%xmm11 - pxor %xmm10,%xmm3 - pshufd $0x93,%xmm6,%xmm12 - pxor %xmm11,%xmm1 - pshufd $0x93,%xmm2,%xmm13 - pxor %xmm12,%xmm6 - pshufd $0x93,%xmm4,%xmm14 - pxor %xmm13,%xmm2 - pxor %xmm14,%xmm4 - - pxor %xmm15,%xmm8 - pxor %xmm4,%xmm7 - pxor %xmm4,%xmm8 - pshufd $0x4E,%xmm15,%xmm15 - pxor %xmm0,%xmm9 - pshufd $0x4E,%xmm0,%xmm0 - pxor %xmm1,%xmm12 - pxor %xmm7,%xmm15 - pxor %xmm6,%xmm13 - pxor %xmm8,%xmm0 - pxor %xmm3,%xmm11 - pshufd $0x4E,%xmm1,%xmm7 - pxor %xmm2,%xmm14 - pshufd $0x4E,%xmm6,%xmm8 - pxor %xmm5,%xmm10 - pshufd $0x4E,%xmm3,%xmm1 - pxor %xmm4,%xmm10 - pshufd $0x4E,%xmm4,%xmm6 - pxor %xmm4,%xmm11 - pshufd $0x4E,%xmm2,%xmm3 - pxor %xmm11,%xmm7 - pshufd $0x4E,%xmm5,%xmm2 - pxor %xmm12,%xmm8 - pxor %xmm1,%xmm10 - pxor %xmm14,%xmm6 - pxor %xmm3,%xmm13 - movdqa %xmm7,%xmm3 - pxor %xmm9,%xmm2 - movdqa %xmm13,%xmm5 - movdqa %xmm8,%xmm4 - movdqa %xmm2,%xmm1 - movdqa %xmm10,%xmm2 - movdqa -16(%r11),%xmm7 - jnz .Ldec_loop - movdqa -32(%r11),%xmm7 - jmp .Ldec_loop -.align 16 -.Ldec_done: - movdqa 0(%r11),%xmm7 - movdqa 16(%r11),%xmm8 - movdqa %xmm2,%xmm9 - psrlq $1,%xmm2 - movdqa %xmm1,%xmm10 - psrlq $1,%xmm1 - pxor %xmm4,%xmm2 - pxor %xmm6,%xmm1 - pand %xmm7,%xmm2 - pand %xmm7,%xmm1 - pxor %xmm2,%xmm4 - psllq $1,%xmm2 - pxor %xmm1,%xmm6 - psllq $1,%xmm1 - pxor %xmm9,%xmm2 - pxor %xmm10,%xmm1 - movdqa %xmm5,%xmm9 - psrlq $1,%xmm5 - movdqa %xmm15,%xmm10 - psrlq $1,%xmm15 - pxor %xmm3,%xmm5 - pxor %xmm0,%xmm15 - pand %xmm7,%xmm5 - pand %xmm7,%xmm15 - pxor %xmm5,%xmm3 - psllq $1,%xmm5 - pxor %xmm15,%xmm0 - psllq $1,%xmm15 - pxor %xmm9,%xmm5 - pxor %xmm10,%xmm15 - movdqa 32(%r11),%xmm7 - movdqa %xmm6,%xmm9 - psrlq $2,%xmm6 - movdqa %xmm1,%xmm10 - psrlq $2,%xmm1 - pxor %xmm4,%xmm6 - pxor %xmm2,%xmm1 - pand %xmm8,%xmm6 - pand %xmm8,%xmm1 - pxor %xmm6,%xmm4 - psllq $2,%xmm6 - pxor %xmm1,%xmm2 - psllq $2,%xmm1 - pxor %xmm9,%xmm6 - pxor %xmm10,%xmm1 - movdqa %xmm0,%xmm9 - psrlq $2,%xmm0 - movdqa %xmm15,%xmm10 - psrlq $2,%xmm15 - pxor %xmm3,%xmm0 - pxor %xmm5,%xmm15 - pand %xmm8,%xmm0 - pand %xmm8,%xmm15 - pxor %xmm0,%xmm3 - psllq $2,%xmm0 - pxor %xmm15,%xmm5 - psllq $2,%xmm15 - pxor %xmm9,%xmm0 - pxor %xmm10,%xmm15 - movdqa %xmm3,%xmm9 - psrlq $4,%xmm3 - movdqa %xmm5,%xmm10 - psrlq $4,%xmm5 - pxor %xmm4,%xmm3 - pxor %xmm2,%xmm5 - pand %xmm7,%xmm3 - pand %xmm7,%xmm5 - pxor %xmm3,%xmm4 - psllq $4,%xmm3 - pxor %xmm5,%xmm2 - psllq $4,%xmm5 - pxor %xmm9,%xmm3 - pxor %xmm10,%xmm5 - movdqa %xmm0,%xmm9 - psrlq $4,%xmm0 - movdqa %xmm15,%xmm10 - psrlq $4,%xmm15 - pxor %xmm6,%xmm0 - pxor %xmm1,%xmm15 - pand %xmm7,%xmm0 - pand %xmm7,%xmm15 - pxor %xmm0,%xmm6 - psllq $4,%xmm0 - pxor %xmm15,%xmm1 - psllq $4,%xmm15 - pxor %xmm9,%xmm0 - pxor %xmm10,%xmm15 - movdqa (%rax),%xmm7 - pxor %xmm7,%xmm5 - pxor %xmm7,%xmm3 - pxor %xmm7,%xmm1 - pxor %xmm7,%xmm6 - pxor %xmm7,%xmm2 - pxor %xmm7,%xmm4 - pxor %xmm7,%xmm15 - pxor %xmm7,%xmm0 - .byte 0xf3,0xc3 -.cfi_endproc -.size _bsaes_decrypt8,.-_bsaes_decrypt8 -.type _bsaes_key_convert,@function -.align 16 -_bsaes_key_convert: -.cfi_startproc - leaq .Lmasks(%rip),%r11 - movdqu (%rcx),%xmm7 - leaq 16(%rcx),%rcx - movdqa 0(%r11),%xmm0 - movdqa 16(%r11),%xmm1 - movdqa 32(%r11),%xmm2 - movdqa 48(%r11),%xmm3 - movdqa 64(%r11),%xmm4 - pcmpeqd %xmm5,%xmm5 - - movdqu (%rcx),%xmm6 - movdqa %xmm7,(%rax) - leaq 16(%rax),%rax - decl %r10d - jmp .Lkey_loop -.align 16 -.Lkey_loop: -.byte 102,15,56,0,244 - - movdqa %xmm0,%xmm8 - movdqa %xmm1,%xmm9 - - pand %xmm6,%xmm8 - pand %xmm6,%xmm9 - movdqa %xmm2,%xmm10 - pcmpeqb %xmm0,%xmm8 - psllq $4,%xmm0 - movdqa %xmm3,%xmm11 - pcmpeqb %xmm1,%xmm9 - psllq $4,%xmm1 - - pand %xmm6,%xmm10 - pand %xmm6,%xmm11 - movdqa %xmm0,%xmm12 - pcmpeqb %xmm2,%xmm10 - psllq $4,%xmm2 - movdqa %xmm1,%xmm13 - pcmpeqb %xmm3,%xmm11 - psllq $4,%xmm3 - - movdqa %xmm2,%xmm14 - movdqa %xmm3,%xmm15 - pxor %xmm5,%xmm8 - pxor %xmm5,%xmm9 - - pand %xmm6,%xmm12 - pand %xmm6,%xmm13 - movdqa %xmm8,0(%rax) - pcmpeqb %xmm0,%xmm12 - psrlq $4,%xmm0 - movdqa %xmm9,16(%rax) - pcmpeqb %xmm1,%xmm13 - psrlq $4,%xmm1 - leaq 16(%rcx),%rcx - - pand %xmm6,%xmm14 - pand %xmm6,%xmm15 - movdqa %xmm10,32(%rax) - pcmpeqb %xmm2,%xmm14 - psrlq $4,%xmm2 - movdqa %xmm11,48(%rax) - pcmpeqb %xmm3,%xmm15 - psrlq $4,%xmm3 - movdqu (%rcx),%xmm6 - - pxor %xmm5,%xmm13 - pxor %xmm5,%xmm14 - movdqa %xmm12,64(%rax) - movdqa %xmm13,80(%rax) - movdqa %xmm14,96(%rax) - movdqa %xmm15,112(%rax) - leaq 128(%rax),%rax - decl %r10d - jnz .Lkey_loop - - movdqa 80(%r11),%xmm7 - - .byte 0xf3,0xc3 -.cfi_endproc -.size _bsaes_key_convert,.-_bsaes_key_convert -.extern aes_nohw_cbc_encrypt -.hidden aes_nohw_cbc_encrypt -.globl bsaes_cbc_encrypt -.hidden bsaes_cbc_encrypt -.type bsaes_cbc_encrypt,@function -.align 16 -bsaes_cbc_encrypt: -.cfi_startproc - cmpl $0,%r9d - jne aes_nohw_cbc_encrypt - cmpq $128,%rdx - jb aes_nohw_cbc_encrypt - - movq %rsp,%rax -.Lcbc_dec_prologue: - pushq %rbp -.cfi_adjust_cfa_offset 8 -.cfi_offset %rbp,-16 - pushq %rbx -.cfi_adjust_cfa_offset 8 -.cfi_offset %rbx,-24 - pushq %r12 -.cfi_adjust_cfa_offset 8 -.cfi_offset %r12,-32 - pushq %r13 -.cfi_adjust_cfa_offset 8 -.cfi_offset %r13,-40 - pushq %r14 -.cfi_adjust_cfa_offset 8 -.cfi_offset %r14,-48 - pushq %r15 -.cfi_adjust_cfa_offset 8 -.cfi_offset %r15,-56 - leaq -72(%rsp),%rsp -.cfi_adjust_cfa_offset 0x48 - movq %rsp,%rbp -.cfi_def_cfa_register %rbp - movl 240(%rcx),%eax - movq %rdi,%r12 - movq %rsi,%r13 - movq %rdx,%r14 - movq %rcx,%r15 - movq %r8,%rbx - shrq $4,%r14 - - movl %eax,%edx - shlq $7,%rax - subq $96,%rax - subq %rax,%rsp - - movq %rsp,%rax - movq %r15,%rcx - movl %edx,%r10d - call _bsaes_key_convert - pxor (%rsp),%xmm7 - movdqa %xmm6,(%rax) - movdqa %xmm7,(%rsp) - - movdqu (%rbx),%xmm14 - subq $8,%r14 -.Lcbc_dec_loop: - movdqu 0(%r12),%xmm15 - movdqu 16(%r12),%xmm0 - movdqu 32(%r12),%xmm1 - movdqu 48(%r12),%xmm2 - movdqu 64(%r12),%xmm3 - movdqu 80(%r12),%xmm4 - movq %rsp,%rax - movdqu 96(%r12),%xmm5 - movl %edx,%r10d - movdqu 112(%r12),%xmm6 - movdqa %xmm14,32(%rbp) - - call _bsaes_decrypt8 - - pxor 32(%rbp),%xmm15 - movdqu 0(%r12),%xmm7 - movdqu 16(%r12),%xmm8 - pxor %xmm7,%xmm0 - movdqu 32(%r12),%xmm9 - pxor %xmm8,%xmm5 - movdqu 48(%r12),%xmm10 - pxor %xmm9,%xmm3 - movdqu 64(%r12),%xmm11 - pxor %xmm10,%xmm1 - movdqu 80(%r12),%xmm12 - pxor %xmm11,%xmm6 - movdqu 96(%r12),%xmm13 - pxor %xmm12,%xmm2 - movdqu 112(%r12),%xmm14 - pxor %xmm13,%xmm4 - movdqu %xmm15,0(%r13) - leaq 128(%r12),%r12 - movdqu %xmm0,16(%r13) - movdqu %xmm5,32(%r13) - movdqu %xmm3,48(%r13) - movdqu %xmm1,64(%r13) - movdqu %xmm6,80(%r13) - movdqu %xmm2,96(%r13) - movdqu %xmm4,112(%r13) - leaq 128(%r13),%r13 - subq $8,%r14 - jnc .Lcbc_dec_loop - - addq $8,%r14 - jz .Lcbc_dec_done - - movdqu 0(%r12),%xmm15 - movq %rsp,%rax - movl %edx,%r10d - cmpq $2,%r14 - jb .Lcbc_dec_one - movdqu 16(%r12),%xmm0 - je .Lcbc_dec_two - movdqu 32(%r12),%xmm1 - cmpq $4,%r14 - jb .Lcbc_dec_three - movdqu 48(%r12),%xmm2 - je .Lcbc_dec_four - movdqu 64(%r12),%xmm3 - cmpq $6,%r14 - jb .Lcbc_dec_five - movdqu 80(%r12),%xmm4 - je .Lcbc_dec_six - movdqu 96(%r12),%xmm5 - movdqa %xmm14,32(%rbp) - call _bsaes_decrypt8 - pxor 32(%rbp),%xmm15 - movdqu 0(%r12),%xmm7 - movdqu 16(%r12),%xmm8 - pxor %xmm7,%xmm0 - movdqu 32(%r12),%xmm9 - pxor %xmm8,%xmm5 - movdqu 48(%r12),%xmm10 - pxor %xmm9,%xmm3 - movdqu 64(%r12),%xmm11 - pxor %xmm10,%xmm1 - movdqu 80(%r12),%xmm12 - pxor %xmm11,%xmm6 - movdqu 96(%r12),%xmm14 - pxor %xmm12,%xmm2 - movdqu %xmm15,0(%r13) - movdqu %xmm0,16(%r13) - movdqu %xmm5,32(%r13) - movdqu %xmm3,48(%r13) - movdqu %xmm1,64(%r13) - movdqu %xmm6,80(%r13) - movdqu %xmm2,96(%r13) - jmp .Lcbc_dec_done -.align 16 -.Lcbc_dec_six: - movdqa %xmm14,32(%rbp) - call _bsaes_decrypt8 - pxor 32(%rbp),%xmm15 - movdqu 0(%r12),%xmm7 - movdqu 16(%r12),%xmm8 - pxor %xmm7,%xmm0 - movdqu 32(%r12),%xmm9 - pxor %xmm8,%xmm5 - movdqu 48(%r12),%xmm10 - pxor %xmm9,%xmm3 - movdqu 64(%r12),%xmm11 - pxor %xmm10,%xmm1 - movdqu 80(%r12),%xmm14 - pxor %xmm11,%xmm6 - movdqu %xmm15,0(%r13) - movdqu %xmm0,16(%r13) - movdqu %xmm5,32(%r13) - movdqu %xmm3,48(%r13) - movdqu %xmm1,64(%r13) - movdqu %xmm6,80(%r13) - jmp .Lcbc_dec_done -.align 16 -.Lcbc_dec_five: - movdqa %xmm14,32(%rbp) - call _bsaes_decrypt8 - pxor 32(%rbp),%xmm15 - movdqu 0(%r12),%xmm7 - movdqu 16(%r12),%xmm8 - pxor %xmm7,%xmm0 - movdqu 32(%r12),%xmm9 - pxor %xmm8,%xmm5 - movdqu 48(%r12),%xmm10 - pxor %xmm9,%xmm3 - movdqu 64(%r12),%xmm14 - pxor %xmm10,%xmm1 - movdqu %xmm15,0(%r13) - movdqu %xmm0,16(%r13) - movdqu %xmm5,32(%r13) - movdqu %xmm3,48(%r13) - movdqu %xmm1,64(%r13) - jmp .Lcbc_dec_done -.align 16 -.Lcbc_dec_four: - movdqa %xmm14,32(%rbp) - call _bsaes_decrypt8 - pxor 32(%rbp),%xmm15 - movdqu 0(%r12),%xmm7 - movdqu 16(%r12),%xmm8 - pxor %xmm7,%xmm0 - movdqu 32(%r12),%xmm9 - pxor %xmm8,%xmm5 - movdqu 48(%r12),%xmm14 - pxor %xmm9,%xmm3 - movdqu %xmm15,0(%r13) - movdqu %xmm0,16(%r13) - movdqu %xmm5,32(%r13) - movdqu %xmm3,48(%r13) - jmp .Lcbc_dec_done -.align 16 -.Lcbc_dec_three: - movdqa %xmm14,32(%rbp) - call _bsaes_decrypt8 - pxor 32(%rbp),%xmm15 - movdqu 0(%r12),%xmm7 - movdqu 16(%r12),%xmm8 - pxor %xmm7,%xmm0 - movdqu 32(%r12),%xmm14 - pxor %xmm8,%xmm5 - movdqu %xmm15,0(%r13) - movdqu %xmm0,16(%r13) - movdqu %xmm5,32(%r13) - jmp .Lcbc_dec_done -.align 16 -.Lcbc_dec_two: - movdqa %xmm14,32(%rbp) - call _bsaes_decrypt8 - pxor 32(%rbp),%xmm15 - movdqu 0(%r12),%xmm7 - movdqu 16(%r12),%xmm14 - pxor %xmm7,%xmm0 - movdqu %xmm15,0(%r13) - movdqu %xmm0,16(%r13) - jmp .Lcbc_dec_done -.align 16 -.Lcbc_dec_one: - leaq (%r12),%rdi - leaq 32(%rbp),%rsi - leaq (%r15),%rdx - call aes_nohw_decrypt - pxor 32(%rbp),%xmm14 - movdqu %xmm14,(%r13) - movdqa %xmm15,%xmm14 - -.Lcbc_dec_done: - movdqu %xmm14,(%rbx) - leaq (%rsp),%rax - pxor %xmm0,%xmm0 -.Lcbc_dec_bzero: - movdqa %xmm0,0(%rax) - movdqa %xmm0,16(%rax) - leaq 32(%rax),%rax - cmpq %rax,%rbp - ja .Lcbc_dec_bzero - - leaq 120(%rbp),%rax -.cfi_def_cfa %rax,8 - movq -48(%rax),%r15 -.cfi_restore %r15 - movq -40(%rax),%r14 -.cfi_restore %r14 - movq -32(%rax),%r13 -.cfi_restore %r13 - movq -24(%rax),%r12 -.cfi_restore %r12 - movq -16(%rax),%rbx -.cfi_restore %rbx - movq -8(%rax),%rbp -.cfi_restore %rbp - leaq (%rax),%rsp -.cfi_def_cfa_register %rsp -.Lcbc_dec_epilogue: - .byte 0xf3,0xc3 -.cfi_endproc -.size bsaes_cbc_encrypt,.-bsaes_cbc_encrypt - -.globl bsaes_ctr32_encrypt_blocks -.hidden bsaes_ctr32_encrypt_blocks -.type bsaes_ctr32_encrypt_blocks,@function -.align 16 -bsaes_ctr32_encrypt_blocks: -.cfi_startproc - movq %rsp,%rax -.Lctr_enc_prologue: - pushq %rbp -.cfi_adjust_cfa_offset 8 -.cfi_offset %rbp,-16 - pushq %rbx -.cfi_adjust_cfa_offset 8 -.cfi_offset %rbx,-24 - pushq %r12 -.cfi_adjust_cfa_offset 8 -.cfi_offset %r12,-32 - pushq %r13 -.cfi_adjust_cfa_offset 8 -.cfi_offset %r13,-40 - pushq %r14 -.cfi_adjust_cfa_offset 8 -.cfi_offset %r14,-48 - pushq %r15 -.cfi_adjust_cfa_offset 8 -.cfi_offset %r15,-56 - leaq -72(%rsp),%rsp -.cfi_adjust_cfa_offset 0x48 - movq %rsp,%rbp -.cfi_def_cfa_register %rbp - movdqu (%r8),%xmm0 - movl 240(%rcx),%eax - movq %rdi,%r12 - movq %rsi,%r13 - movq %rdx,%r14 - movq %rcx,%r15 - movdqa %xmm0,32(%rbp) - cmpq $8,%rdx - jb .Lctr_enc_short - - movl %eax,%ebx - shlq $7,%rax - subq $96,%rax - subq %rax,%rsp - - movq %rsp,%rax - movq %r15,%rcx - movl %ebx,%r10d - call _bsaes_key_convert - pxor %xmm6,%xmm7 - movdqa %xmm7,(%rax) - - movdqa (%rsp),%xmm8 - leaq .LADD1(%rip),%r11 - movdqa 32(%rbp),%xmm15 - movdqa -32(%r11),%xmm7 -.byte 102,68,15,56,0,199 -.byte 102,68,15,56,0,255 - movdqa %xmm8,(%rsp) - jmp .Lctr_enc_loop -.align 16 -.Lctr_enc_loop: - movdqa %xmm15,32(%rbp) - movdqa %xmm15,%xmm0 - movdqa %xmm15,%xmm1 - paddd 0(%r11),%xmm0 - movdqa %xmm15,%xmm2 - paddd 16(%r11),%xmm1 - movdqa %xmm15,%xmm3 - paddd 32(%r11),%xmm2 - movdqa %xmm15,%xmm4 - paddd 48(%r11),%xmm3 - movdqa %xmm15,%xmm5 - paddd 64(%r11),%xmm4 - movdqa %xmm15,%xmm6 - paddd 80(%r11),%xmm5 - paddd 96(%r11),%xmm6 - - - - movdqa (%rsp),%xmm8 - leaq 16(%rsp),%rax - movdqa -16(%r11),%xmm7 - pxor %xmm8,%xmm15 - pxor %xmm8,%xmm0 - pxor %xmm8,%xmm1 - pxor %xmm8,%xmm2 -.byte 102,68,15,56,0,255 -.byte 102,15,56,0,199 - pxor %xmm8,%xmm3 - pxor %xmm8,%xmm4 -.byte 102,15,56,0,207 -.byte 102,15,56,0,215 - pxor %xmm8,%xmm5 - pxor %xmm8,%xmm6 -.byte 102,15,56,0,223 -.byte 102,15,56,0,231 -.byte 102,15,56,0,239 -.byte 102,15,56,0,247 - leaq .LBS0(%rip),%r11 - movl %ebx,%r10d - - call _bsaes_encrypt8_bitslice - - subq $8,%r14 - jc .Lctr_enc_loop_done - - movdqu 0(%r12),%xmm7 - movdqu 16(%r12),%xmm8 - movdqu 32(%r12),%xmm9 - movdqu 48(%r12),%xmm10 - movdqu 64(%r12),%xmm11 - movdqu 80(%r12),%xmm12 - movdqu 96(%r12),%xmm13 - movdqu 112(%r12),%xmm14 - leaq 128(%r12),%r12 - pxor %xmm15,%xmm7 - movdqa 32(%rbp),%xmm15 - pxor %xmm8,%xmm0 - movdqu %xmm7,0(%r13) - pxor %xmm9,%xmm3 - movdqu %xmm0,16(%r13) - pxor %xmm10,%xmm5 - movdqu %xmm3,32(%r13) - pxor %xmm11,%xmm2 - movdqu %xmm5,48(%r13) - pxor %xmm12,%xmm6 - movdqu %xmm2,64(%r13) - pxor %xmm13,%xmm1 - movdqu %xmm6,80(%r13) - pxor %xmm14,%xmm4 - movdqu %xmm1,96(%r13) - leaq .LADD1(%rip),%r11 - movdqu %xmm4,112(%r13) - leaq 128(%r13),%r13 - paddd 112(%r11),%xmm15 - jnz .Lctr_enc_loop - - jmp .Lctr_enc_done -.align 16 -.Lctr_enc_loop_done: - addq $8,%r14 - movdqu 0(%r12),%xmm7 - pxor %xmm7,%xmm15 - movdqu %xmm15,0(%r13) - cmpq $2,%r14 - jb .Lctr_enc_done - movdqu 16(%r12),%xmm8 - pxor %xmm8,%xmm0 - movdqu %xmm0,16(%r13) - je .Lctr_enc_done - movdqu 32(%r12),%xmm9 - pxor %xmm9,%xmm3 - movdqu %xmm3,32(%r13) - cmpq $4,%r14 - jb .Lctr_enc_done - movdqu 48(%r12),%xmm10 - pxor %xmm10,%xmm5 - movdqu %xmm5,48(%r13) - je .Lctr_enc_done - movdqu 64(%r12),%xmm11 - pxor %xmm11,%xmm2 - movdqu %xmm2,64(%r13) - cmpq $6,%r14 - jb .Lctr_enc_done - movdqu 80(%r12),%xmm12 - pxor %xmm12,%xmm6 - movdqu %xmm6,80(%r13) - je .Lctr_enc_done - movdqu 96(%r12),%xmm13 - pxor %xmm13,%xmm1 - movdqu %xmm1,96(%r13) - jmp .Lctr_enc_done - -.align 16 -.Lctr_enc_short: - leaq 32(%rbp),%rdi - leaq 48(%rbp),%rsi - leaq (%r15),%rdx - call aes_nohw_encrypt - movdqu (%r12),%xmm0 - leaq 16(%r12),%r12 - movl 44(%rbp),%eax - bswapl %eax - pxor 48(%rbp),%xmm0 - incl %eax - movdqu %xmm0,(%r13) - bswapl %eax - leaq 16(%r13),%r13 - movl %eax,44(%rsp) - decq %r14 - jnz .Lctr_enc_short - -.Lctr_enc_done: - leaq (%rsp),%rax - pxor %xmm0,%xmm0 -.Lctr_enc_bzero: - movdqa %xmm0,0(%rax) - movdqa %xmm0,16(%rax) - leaq 32(%rax),%rax - cmpq %rax,%rbp - ja .Lctr_enc_bzero - - leaq 120(%rbp),%rax -.cfi_def_cfa %rax,8 - movq -48(%rax),%r15 -.cfi_restore %r15 - movq -40(%rax),%r14 -.cfi_restore %r14 - movq -32(%rax),%r13 -.cfi_restore %r13 - movq -24(%rax),%r12 -.cfi_restore %r12 - movq -16(%rax),%rbx -.cfi_restore %rbx - movq -8(%rax),%rbp -.cfi_restore %rbp - leaq (%rax),%rsp -.cfi_def_cfa_register %rsp -.Lctr_enc_epilogue: - .byte 0xf3,0xc3 -.cfi_endproc -.size bsaes_ctr32_encrypt_blocks,.-bsaes_ctr32_encrypt_blocks -.type _bsaes_const,@object -.align 64 -_bsaes_const: -.LM0ISR: -.quad 0x0a0e0206070b0f03, 0x0004080c0d010509 -.LISRM0: -.quad 0x01040b0e0205080f, 0x0306090c00070a0d -.LISR: -.quad 0x0504070602010003, 0x0f0e0d0c080b0a09 -.LBS0: -.quad 0x5555555555555555, 0x5555555555555555 -.LBS1: -.quad 0x3333333333333333, 0x3333333333333333 -.LBS2: -.quad 0x0f0f0f0f0f0f0f0f, 0x0f0f0f0f0f0f0f0f -.LSR: -.quad 0x0504070600030201, 0x0f0e0d0c0a09080b -.LSRM0: -.quad 0x0304090e00050a0f, 0x01060b0c0207080d -.LM0SR: -.quad 0x0a0e02060f03070b, 0x0004080c05090d01 -.LSWPUP: -.quad 0x0706050403020100, 0x0c0d0e0f0b0a0908 -.LSWPUPM0SR: -.quad 0x0a0d02060c03070b, 0x0004080f05090e01 -.LADD1: -.quad 0x0000000000000000, 0x0000000100000000 -.LADD2: -.quad 0x0000000000000000, 0x0000000200000000 -.LADD3: -.quad 0x0000000000000000, 0x0000000300000000 -.LADD4: -.quad 0x0000000000000000, 0x0000000400000000 -.LADD5: -.quad 0x0000000000000000, 0x0000000500000000 -.LADD6: -.quad 0x0000000000000000, 0x0000000600000000 -.LADD7: -.quad 0x0000000000000000, 0x0000000700000000 -.LADD8: -.quad 0x0000000000000000, 0x0000000800000000 -.Lxts_magic: -.long 0x87,0,1,0 -.Lmasks: -.quad 0x0101010101010101, 0x0101010101010101 -.quad 0x0202020202020202, 0x0202020202020202 -.quad 0x0404040404040404, 0x0404040404040404 -.quad 0x0808080808080808, 0x0808080808080808 -.LM0: -.quad 0x02060a0e03070b0f, 0x0004080c0105090d -.L63: -.quad 0x6363636363636363, 0x6363636363636363 -.byte 66,105,116,45,115,108,105,99,101,100,32,65,69,83,32,102,111,114,32,120,56,54,95,54,52,47,83,83,83,69,51,44,32,69,109,105,108,105,97,32,75,195,164,115,112,101,114,44,32,80,101,116,101,114,32,83,99,104,119,97,98,101,44,32,65,110,100,121,32,80,111,108,121,97,107,111,118,0 -.align 64 -.size _bsaes_const,.-_bsaes_const -#endif diff --git a/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.S b/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.S new file mode 100644 index 00000000..ecf5b66f --- /dev/null +++ b/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.S @@ -0,0 +1,426 @@ +# This file is generated from a similarly-named Perl script in the BoringSSL +# source tree. Do not edit by hand. + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) +#define OPENSSL_NO_ASM +#endif +#endif + +#if defined(__x86_64__) && !defined(OPENSSL_NO_ASM) +#if defined(BORINGSSL_PREFIX) +#include +#endif +.text + + + + + +.type gcm_gmult_ssse3, @function +.globl gcm_gmult_ssse3 +.hidden gcm_gmult_ssse3 +.align 16 +gcm_gmult_ssse3: +.cfi_startproc +.Lgmult_seh_begin: + movdqu (%rdi),%xmm0 + movdqa .Lreverse_bytes(%rip),%xmm10 + movdqa .Llow4_mask(%rip),%xmm2 + + +.byte 102,65,15,56,0,194 + + + movdqa %xmm2,%xmm1 + pandn %xmm0,%xmm1 + psrld $4,%xmm1 + pand %xmm2,%xmm0 + + + + + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + movq $5,%rax +.Loop_row_1: + movdqa (%rsi),%xmm4 + leaq 16(%rsi),%rsi + + + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + + + + + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + + + pxor %xmm5,%xmm2 + + + + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + + + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + + subq $1,%rax + jnz .Loop_row_1 + + + + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movq $5,%rax +.Loop_row_2: + movdqa (%rsi),%xmm4 + leaq 16(%rsi),%rsi + + + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + + + + + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + + + pxor %xmm5,%xmm2 + + + + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + + + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + + subq $1,%rax + jnz .Loop_row_2 + + + + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movq $6,%rax +.Loop_row_3: + movdqa (%rsi),%xmm4 + leaq 16(%rsi),%rsi + + + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + + + + + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + + + pxor %xmm5,%xmm2 + + + + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + + + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + + subq $1,%rax + jnz .Loop_row_3 + + + + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + +.byte 102,65,15,56,0,210 + movdqu %xmm2,(%rdi) + + + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + pxor %xmm4,%xmm4 + pxor %xmm5,%xmm5 + pxor %xmm6,%xmm6 + .byte 0xf3,0xc3 +.Lgmult_seh_end: +.cfi_endproc +.size gcm_gmult_ssse3,.-gcm_gmult_ssse3 + + + + + +.type gcm_ghash_ssse3, @function +.globl gcm_ghash_ssse3 +.hidden gcm_ghash_ssse3 +.align 16 +gcm_ghash_ssse3: +.Lghash_seh_begin: +.cfi_startproc + movdqu (%rdi),%xmm0 + movdqa .Lreverse_bytes(%rip),%xmm10 + movdqa .Llow4_mask(%rip),%xmm11 + + + andq $-16,%rcx + + + +.byte 102,65,15,56,0,194 + + + pxor %xmm3,%xmm3 +.Loop_ghash: + + movdqu (%rdx),%xmm1 +.byte 102,65,15,56,0,202 + pxor %xmm1,%xmm0 + + + movdqa %xmm11,%xmm1 + pandn %xmm0,%xmm1 + psrld $4,%xmm1 + pand %xmm11,%xmm0 + + + + + pxor %xmm2,%xmm2 + + movq $5,%rax +.Loop_row_4: + movdqa (%rsi),%xmm4 + leaq 16(%rsi),%rsi + + + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + + + + + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + + + pxor %xmm5,%xmm2 + + + + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + + + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + + subq $1,%rax + jnz .Loop_row_4 + + + + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movq $5,%rax +.Loop_row_5: + movdqa (%rsi),%xmm4 + leaq 16(%rsi),%rsi + + + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + + + + + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + + + pxor %xmm5,%xmm2 + + + + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + + + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + + subq $1,%rax + jnz .Loop_row_5 + + + + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movq $6,%rax +.Loop_row_6: + movdqa (%rsi),%xmm4 + leaq 16(%rsi),%rsi + + + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + + + + + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + + + pxor %xmm5,%xmm2 + + + + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + + + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + + subq $1,%rax + jnz .Loop_row_6 + + + + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movdqa %xmm2,%xmm0 + + + leaq -256(%rsi),%rsi + + + leaq 16(%rdx),%rdx + subq $16,%rcx + jnz .Loop_ghash + + +.byte 102,65,15,56,0,194 + movdqu %xmm0,(%rdi) + + + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + pxor %xmm4,%xmm4 + pxor %xmm5,%xmm5 + pxor %xmm6,%xmm6 + .byte 0xf3,0xc3 +.Lghash_seh_end: +.cfi_endproc +.size gcm_ghash_ssse3,.-gcm_ghash_ssse3 + +.align 16 + + +.Lreverse_bytes: +.byte 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 + +.Llow4_mask: +.quad 0x0f0f0f0f0f0f0f0f, 0x0f0f0f0f0f0f0f0f +#endif diff --git a/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/ghash-x86_64.S b/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/ghash-x86_64.S index ed0946d9..0b36afac 100644 --- a/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/ghash-x86_64.S +++ b/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/ghash-x86_64.S @@ -722,6 +722,7 @@ gcm_ghash_4bit: .type gcm_init_clmul,@function .align 16 gcm_init_clmul: +.cfi_startproc .L_init_clmul: movdqu (%rsi),%xmm2 pshufd $78,%xmm2,%xmm2 @@ -873,12 +874,14 @@ gcm_init_clmul: .byte 102,15,58,15,227,8 movdqu %xmm4,80(%rdi) .byte 0xf3,0xc3 +.cfi_endproc .size gcm_init_clmul,.-gcm_init_clmul .globl gcm_gmult_clmul .hidden gcm_gmult_clmul .type gcm_gmult_clmul,@function .align 16 gcm_gmult_clmul: +.cfi_startproc .L_gmult_clmul: movdqu (%rdi),%xmm0 movdqa .Lbswap_mask(%rip),%xmm5 @@ -925,12 +928,14 @@ gcm_gmult_clmul: .byte 102,15,56,0,197 movdqu %xmm0,(%rdi) .byte 0xf3,0xc3 +.cfi_endproc .size gcm_gmult_clmul,.-gcm_gmult_clmul .globl gcm_ghash_clmul .hidden gcm_ghash_clmul .type gcm_ghash_clmul,@function .align 32 gcm_ghash_clmul: +.cfi_startproc .L_ghash_clmul: movdqa .Lbswap_mask(%rip),%xmm10 @@ -1310,12 +1315,14 @@ gcm_ghash_clmul: .byte 102,65,15,56,0,194 movdqu %xmm0,(%rdi) .byte 0xf3,0xc3 +.cfi_endproc .size gcm_ghash_clmul,.-gcm_ghash_clmul .globl gcm_init_avx .hidden gcm_init_avx .type gcm_init_avx,@function .align 32 gcm_init_avx: +.cfi_startproc vzeroupper vmovdqu (%rsi),%xmm2 @@ -1418,19 +1425,23 @@ gcm_init_avx: vzeroupper .byte 0xf3,0xc3 +.cfi_endproc .size gcm_init_avx,.-gcm_init_avx .globl gcm_gmult_avx .hidden gcm_gmult_avx .type gcm_gmult_avx,@function .align 32 gcm_gmult_avx: +.cfi_startproc jmp .L_gmult_clmul +.cfi_endproc .size gcm_gmult_avx,.-gcm_gmult_avx .globl gcm_ghash_avx .hidden gcm_ghash_avx .type gcm_ghash_avx,@function .align 32 gcm_ghash_avx: +.cfi_startproc vzeroupper vmovdqu (%rdi),%xmm10 @@ -1802,6 +1813,7 @@ gcm_ghash_avx: vmovdqu %xmm10,(%rdi) vzeroupper .byte 0xf3,0xc3 +.cfi_endproc .size gcm_ghash_avx,.-gcm_ghash_avx .align 64 .Lbswap_mask: diff --git a/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/rdrand-x86_64.S b/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/rdrand-x86_64.S index d7b0cb4b..fefccd6f 100644 --- a/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/rdrand-x86_64.S +++ b/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/rdrand-x86_64.S @@ -23,14 +23,13 @@ CRYPTO_rdrand: .cfi_startproc xorq %rax,%rax - - -.byte 0x48, 0x0f, 0xc7, 0xf1 +.byte 72,15,199,242 adcq %rax,%rax - movq %rcx,0(%rdi) + movq %rdx,0(%rdi) .byte 0xf3,0xc3 .cfi_endproc +.size CRYPTO_rdrand,.-CRYPTO_rdrand @@ -46,9 +45,7 @@ CRYPTO_rdrand_multiple8_buf: jz .Lout movq $8,%rdx .Lloop: - - -.byte 0x48, 0x0f, 0xc7, 0xf1 +.byte 72,15,199,241 jnc .Lerr movq %rcx,0(%rdi) addq %rdx,%rdi @@ -61,4 +58,5 @@ CRYPTO_rdrand_multiple8_buf: xorq %rax,%rax .byte 0xf3,0xc3 .cfi_endproc +.size CRYPTO_rdrand_multiple8_buf,.-CRYPTO_rdrand_multiple8_buf #endif diff --git a/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/rsaz-avx2.S b/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/rsaz-avx2.S index 4ca2cab0..579c7055 100644 --- a/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/rsaz-avx2.S +++ b/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/rsaz-avx2.S @@ -1228,6 +1228,7 @@ rsaz_1024_mul_avx2: .type rsaz_1024_red2norm_avx2,@function .align 32 rsaz_1024_red2norm_avx2: +.cfi_startproc subq $-128,%rsi xorq %rax,%rax movq -128(%rsi),%r8 @@ -1419,6 +1420,7 @@ rsaz_1024_red2norm_avx2: movq %rax,120(%rdi) movq %r11,%rax .byte 0xf3,0xc3 +.cfi_endproc .size rsaz_1024_red2norm_avx2,.-rsaz_1024_red2norm_avx2 .globl rsaz_1024_norm2red_avx2 @@ -1426,6 +1428,7 @@ rsaz_1024_red2norm_avx2: .type rsaz_1024_norm2red_avx2,@function .align 32 rsaz_1024_norm2red_avx2: +.cfi_startproc subq $-128,%rdi movq (%rsi),%r8 movl $0x1fffffff,%eax @@ -1578,12 +1581,14 @@ rsaz_1024_norm2red_avx2: movq %r8,176(%rdi) movq %r8,184(%rdi) .byte 0xf3,0xc3 +.cfi_endproc .size rsaz_1024_norm2red_avx2,.-rsaz_1024_norm2red_avx2 .globl rsaz_1024_scatter5_avx2 .hidden rsaz_1024_scatter5_avx2 .type rsaz_1024_scatter5_avx2,@function .align 32 rsaz_1024_scatter5_avx2: +.cfi_startproc vzeroupper vmovdqu .Lscatter_permd(%rip),%ymm5 shll $4,%edx @@ -1603,6 +1608,7 @@ rsaz_1024_scatter5_avx2: vzeroupper .byte 0xf3,0xc3 +.cfi_endproc .size rsaz_1024_scatter5_avx2,.-rsaz_1024_scatter5_avx2 .globl rsaz_1024_gather5_avx2 @@ -1727,25 +1733,6 @@ rsaz_1024_gather5_avx2: .cfi_endproc .LSEH_end_rsaz_1024_gather5: .size rsaz_1024_gather5_avx2,.-rsaz_1024_gather5_avx2 -.extern OPENSSL_ia32cap_P -.hidden OPENSSL_ia32cap_P -.globl rsaz_avx2_eligible -.hidden rsaz_avx2_eligible -.type rsaz_avx2_eligible,@function -.align 32 -rsaz_avx2_eligible: - leaq OPENSSL_ia32cap_P(%rip),%rax - movl 8(%rax),%eax - movl $524544,%ecx - movl $0,%edx - andl %eax,%ecx - cmpl $524544,%ecx - cmovel %edx,%eax - andl $32,%eax - shrl $5,%eax - .byte 0xf3,0xc3 -.size rsaz_avx2_eligible,.-rsaz_avx2_eligible - .align 64 .Land_mask: .quad 0x1fffffff,0x1fffffff,0x1fffffff,0x1fffffff diff --git a/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/vpaes-x86_64.S b/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/vpaes-x86_64.S index 232ddf99..0fc93f9a 100644 --- a/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/vpaes-x86_64.S +++ b/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/vpaes-x86_64.S @@ -120,6 +120,181 @@ _vpaes_encrypt_core: + + + + + + + + + + + + + + + + + + + + + + + + +.type _vpaes_encrypt_core_2x,@function +.align 16 +_vpaes_encrypt_core_2x: +.cfi_startproc + movq %rdx,%r9 + movq $16,%r11 + movl 240(%rdx),%eax + movdqa %xmm9,%xmm1 + movdqa %xmm9,%xmm7 + movdqa .Lk_ipt(%rip),%xmm2 + movdqa %xmm2,%xmm8 + pandn %xmm0,%xmm1 + pandn %xmm6,%xmm7 + movdqu (%r9),%xmm5 + + psrld $4,%xmm1 + psrld $4,%xmm7 + pand %xmm9,%xmm0 + pand %xmm9,%xmm6 +.byte 102,15,56,0,208 +.byte 102,68,15,56,0,198 + movdqa .Lk_ipt+16(%rip),%xmm0 + movdqa %xmm0,%xmm6 +.byte 102,15,56,0,193 +.byte 102,15,56,0,247 + pxor %xmm5,%xmm2 + pxor %xmm5,%xmm8 + addq $16,%r9 + pxor %xmm2,%xmm0 + pxor %xmm8,%xmm6 + leaq .Lk_mc_backward(%rip),%r10 + jmp .Lenc2x_entry + +.align 16 +.Lenc2x_loop: + + movdqa .Lk_sb1(%rip),%xmm4 + movdqa .Lk_sb1+16(%rip),%xmm0 + movdqa %xmm4,%xmm12 + movdqa %xmm0,%xmm6 +.byte 102,15,56,0,226 +.byte 102,69,15,56,0,224 +.byte 102,15,56,0,195 +.byte 102,65,15,56,0,243 + pxor %xmm5,%xmm4 + pxor %xmm5,%xmm12 + movdqa .Lk_sb2(%rip),%xmm5 + movdqa %xmm5,%xmm13 + pxor %xmm4,%xmm0 + pxor %xmm12,%xmm6 + movdqa -64(%r11,%r10,1),%xmm1 + +.byte 102,15,56,0,234 +.byte 102,69,15,56,0,232 + movdqa (%r11,%r10,1),%xmm4 + + movdqa .Lk_sb2+16(%rip),%xmm2 + movdqa %xmm2,%xmm8 +.byte 102,15,56,0,211 +.byte 102,69,15,56,0,195 + movdqa %xmm0,%xmm3 + movdqa %xmm6,%xmm11 + pxor %xmm5,%xmm2 + pxor %xmm13,%xmm8 +.byte 102,15,56,0,193 +.byte 102,15,56,0,241 + addq $16,%r9 + pxor %xmm2,%xmm0 + pxor %xmm8,%xmm6 +.byte 102,15,56,0,220 +.byte 102,68,15,56,0,220 + addq $16,%r11 + pxor %xmm0,%xmm3 + pxor %xmm6,%xmm11 +.byte 102,15,56,0,193 +.byte 102,15,56,0,241 + andq $0x30,%r11 + subq $1,%rax + pxor %xmm3,%xmm0 + pxor %xmm11,%xmm6 + +.Lenc2x_entry: + + movdqa %xmm9,%xmm1 + movdqa %xmm9,%xmm7 + movdqa .Lk_inv+16(%rip),%xmm5 + movdqa %xmm5,%xmm13 + pandn %xmm0,%xmm1 + pandn %xmm6,%xmm7 + psrld $4,%xmm1 + psrld $4,%xmm7 + pand %xmm9,%xmm0 + pand %xmm9,%xmm6 +.byte 102,15,56,0,232 +.byte 102,68,15,56,0,238 + movdqa %xmm10,%xmm3 + movdqa %xmm10,%xmm11 + pxor %xmm1,%xmm0 + pxor %xmm7,%xmm6 +.byte 102,15,56,0,217 +.byte 102,68,15,56,0,223 + movdqa %xmm10,%xmm4 + movdqa %xmm10,%xmm12 + pxor %xmm5,%xmm3 + pxor %xmm13,%xmm11 +.byte 102,15,56,0,224 +.byte 102,68,15,56,0,230 + movdqa %xmm10,%xmm2 + movdqa %xmm10,%xmm8 + pxor %xmm5,%xmm4 + pxor %xmm13,%xmm12 +.byte 102,15,56,0,211 +.byte 102,69,15,56,0,195 + movdqa %xmm10,%xmm3 + movdqa %xmm10,%xmm11 + pxor %xmm0,%xmm2 + pxor %xmm6,%xmm8 +.byte 102,15,56,0,220 +.byte 102,69,15,56,0,220 + movdqu (%r9),%xmm5 + + pxor %xmm1,%xmm3 + pxor %xmm7,%xmm11 + jnz .Lenc2x_loop + + + movdqa -96(%r10),%xmm4 + movdqa -80(%r10),%xmm0 + movdqa %xmm4,%xmm12 + movdqa %xmm0,%xmm6 +.byte 102,15,56,0,226 +.byte 102,69,15,56,0,224 + pxor %xmm5,%xmm4 + pxor %xmm5,%xmm12 +.byte 102,15,56,0,195 +.byte 102,65,15,56,0,243 + movdqa 64(%r11,%r10,1),%xmm1 + + pxor %xmm4,%xmm0 + pxor %xmm12,%xmm6 +.byte 102,15,56,0,193 +.byte 102,15,56,0,241 + .byte 0xf3,0xc3 +.cfi_endproc +.size _vpaes_encrypt_core_2x,.-_vpaes_encrypt_core_2x + + + + + + .type _vpaes_decrypt_core,@function .align 16 _vpaes_decrypt_core: @@ -637,6 +812,14 @@ _vpaes_schedule_mangle: .align 16 vpaes_set_encrypt_key: .cfi_startproc +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS +.extern BORINGSSL_function_hit +.hidden BORINGSSL_function_hit + movb $1,BORINGSSL_function_hit+5(%rip) +#endif +#endif + movl %esi,%eax shrl $5,%eax addl $5,%eax @@ -680,6 +863,13 @@ vpaes_set_decrypt_key: .align 16 vpaes_encrypt: .cfi_startproc +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS +.extern BORINGSSL_function_hit +.hidden BORINGSSL_function_hit + movb $1,BORINGSSL_function_hit+4(%rip) +#endif +#endif movdqu (%rdi),%xmm0 call _vpaes_preheat call _vpaes_encrypt_core @@ -744,6 +934,69 @@ vpaes_cbc_encrypt: .byte 0xf3,0xc3 .cfi_endproc .size vpaes_cbc_encrypt,.-vpaes_cbc_encrypt +.globl vpaes_ctr32_encrypt_blocks +.hidden vpaes_ctr32_encrypt_blocks +.type vpaes_ctr32_encrypt_blocks,@function +.align 16 +vpaes_ctr32_encrypt_blocks: +.cfi_startproc + + xchgq %rcx,%rdx + testq %rcx,%rcx + jz .Lctr32_abort + movdqu (%r8),%xmm0 + movdqa .Lctr_add_one(%rip),%xmm8 + subq %rdi,%rsi + call _vpaes_preheat + movdqa %xmm0,%xmm6 + pshufb .Lrev_ctr(%rip),%xmm6 + + testq $1,%rcx + jz .Lctr32_prep_loop + + + + movdqu (%rdi),%xmm7 + call _vpaes_encrypt_core + pxor %xmm7,%xmm0 + paddd %xmm8,%xmm6 + movdqu %xmm0,(%rsi,%rdi,1) + subq $1,%rcx + leaq 16(%rdi),%rdi + jz .Lctr32_done + +.Lctr32_prep_loop: + + + movdqa %xmm6,%xmm14 + movdqa %xmm6,%xmm15 + paddd %xmm8,%xmm15 + +.Lctr32_loop: + movdqa .Lrev_ctr(%rip),%xmm1 + movdqa %xmm14,%xmm0 + movdqa %xmm15,%xmm6 +.byte 102,15,56,0,193 +.byte 102,15,56,0,241 + call _vpaes_encrypt_core_2x + movdqu (%rdi),%xmm1 + movdqu 16(%rdi),%xmm2 + movdqa .Lctr_add_two(%rip),%xmm3 + pxor %xmm1,%xmm0 + pxor %xmm2,%xmm6 + paddd %xmm3,%xmm14 + paddd %xmm3,%xmm15 + movdqu %xmm0,(%rsi,%rdi,1) + movdqu %xmm6,16(%rsi,%rdi,1) + subq $2,%rcx + leaq 32(%rdi),%rdi + jnz .Lctr32_loop + +.Lctr32_done: +.Lctr32_abort: + .byte 0xf3,0xc3 +.cfi_endproc +.size vpaes_ctr32_encrypt_blocks,.-vpaes_ctr32_encrypt_blocks @@ -866,6 +1119,17 @@ _vpaes_consts: .Lk_dsbo: .quad 0x1387EA537EF94000, 0xC7AA6DB9D4943E2D .quad 0x12D7560F93441D00, 0xCA4B8159D8C58E9C + + +.Lrev_ctr: +.quad 0x0706050403020100, 0x0c0d0e0f0b0a0908 + + +.Lctr_add_one: +.quad 0x0000000000000000, 0x0000000100000000 +.Lctr_add_two: +.quad 0x0000000000000000, 0x0000000200000000 + .byte 86,101,99,116,111,114,32,80,101,114,109,117,116,97,116,105,111,110,32,65,69,83,32,102,111,114,32,120,56,54,95,54,52,47,83,83,83,69,51,44,32,77,105,107,101,32,72,97,109,98,117,114,103,32,40,83,116,97,110,102,111,114,100,32,85,110,105,118,101,114,115,105,116,121,41,0 .align 64 .size _vpaes_consts,.-_vpaes_consts diff --git a/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/x86_64-mont5.S b/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/x86_64-mont5.S index ecbe285a..b12393e2 100644 --- a/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/x86_64-mont5.S +++ b/third_party/boringssl/kit/linux-x86_64/crypto/fipsmodule/x86_64-mont5.S @@ -566,6 +566,7 @@ bn_mul4x_mont_gather5: .type mul4x_internal,@function .align 32 mul4x_internal: +.cfi_startproc shlq $5,%r9 movd 8(%rax),%xmm5 leaq .Linc(%rip),%rax @@ -1087,6 +1088,7 @@ mul4x_internal: movq 16(%rbp),%r14 movq 24(%rbp),%r15 jmp .Lsqr4x_sub_entry +.cfi_endproc .size mul4x_internal,.-mul4x_internal .globl bn_power5 .hidden bn_power5 @@ -1232,6 +1234,7 @@ bn_power5: .align 32 bn_sqr8x_internal: __bn_sqr8x_internal: +.cfi_startproc @@ -2006,10 +2009,12 @@ __bn_sqr8x_reduction: cmpq %rdx,%rdi jb .L8x_reduction_loop .byte 0xf3,0xc3 +.cfi_endproc .size bn_sqr8x_internal,.-bn_sqr8x_internal .type __bn_post4x_internal,@function .align 32 __bn_post4x_internal: +.cfi_startproc movq 0(%rbp),%r12 leaq (%rdi,%r9,1),%rbx movq %r9,%rcx @@ -2060,16 +2065,19 @@ __bn_post4x_internal: movq %r9,%r10 negq %r9 .byte 0xf3,0xc3 +.cfi_endproc .size __bn_post4x_internal,.-__bn_post4x_internal .globl bn_from_montgomery .hidden bn_from_montgomery .type bn_from_montgomery,@function .align 32 bn_from_montgomery: +.cfi_startproc testl $7,%r9d jz bn_from_mont8x xorl %eax,%eax .byte 0xf3,0xc3 +.cfi_endproc .size bn_from_montgomery,.-bn_from_montgomery .type bn_from_mont8x,@function @@ -2354,6 +2362,7 @@ bn_mulx4x_mont_gather5: .type mulx4x_internal,@function .align 32 mulx4x_internal: +.cfi_startproc movq %r9,8(%rsp) movq %r9,%r10 negq %r9 @@ -2772,6 +2781,7 @@ mulx4x_internal: movq 16(%rbp),%r14 movq 24(%rbp),%r15 jmp .Lsqrx4x_sub_entry +.cfi_endproc .size mulx4x_internal,.-mulx4x_internal .type bn_powerx5,@function .align 32 @@ -3530,7 +3540,9 @@ __bn_sqrx8x_reduction: .cfi_endproc .size bn_sqrx8x_internal,.-bn_sqrx8x_internal .align 32 +.type __bn_postx4x_internal,@function __bn_postx4x_internal: +.cfi_startproc movq 0(%rbp),%r12 movq %rcx,%r10 movq %rcx,%r9 @@ -3578,12 +3590,14 @@ __bn_postx4x_internal: negq %r9 .byte 0xf3,0xc3 +.cfi_endproc .size __bn_postx4x_internal,.-__bn_postx4x_internal .globl bn_scatter5 .hidden bn_scatter5 .type bn_scatter5,@function .align 16 bn_scatter5: +.cfi_startproc cmpl $0,%esi jz .Lscatter_epilogue leaq (%rdx,%rcx,8),%rdx @@ -3596,6 +3610,7 @@ bn_scatter5: jnz .Lscatter .Lscatter_epilogue: .byte 0xf3,0xc3 +.cfi_endproc .size bn_scatter5,.-bn_scatter5 .globl bn_gather5 @@ -3603,9 +3618,11 @@ bn_scatter5: .type bn_gather5,@function .align 32 bn_gather5: +.cfi_startproc .LSEH_begin_bn_gather5: .byte 0x4c,0x8d,0x14,0x24 +.cfi_def_cfa_register %r10 .byte 0x48,0x81,0xec,0x08,0x01,0x00,0x00 leaq .Linc(%rip),%rax andq $-16,%rsp @@ -3759,8 +3776,10 @@ bn_gather5: jnz .Lgather leaq (%r10),%rsp +.cfi_def_cfa_register %rsp .byte 0xf3,0xc3 .LSEH_end_bn_gather5: +.cfi_endproc .size bn_gather5,.-bn_gather5 .align 64 .Linc: diff --git a/third_party/boringssl/kit/linux-x86_64/crypto/test/trampoline-x86_64.S b/third_party/boringssl/kit/linux-x86_64/crypto/test/trampoline-x86_64.S index f2af98c5..91a13f3e 100644 --- a/third_party/boringssl/kit/linux-x86_64/crypto/test/trampoline-x86_64.S +++ b/third_party/boringssl/kit/linux-x86_64/crypto/test/trampoline-x86_64.S @@ -25,7 +25,7 @@ .hidden abi_test_trampoline .align 16 abi_test_trampoline: -.Labi_test_trampoline_begin: +.Labi_test_trampoline_seh_begin: .cfi_startproc @@ -38,27 +38,27 @@ abi_test_trampoline: subq $120,%rsp .cfi_adjust_cfa_offset 120 -.Labi_test_trampoline_prolog_alloc: +.Labi_test_trampoline_seh_prolog_alloc: movq %r8,48(%rsp) movq %rbx,64(%rsp) .cfi_offset rbx, -64 -.Labi_test_trampoline_prolog_rbx: +.Labi_test_trampoline_seh_prolog_rbx: movq %rbp,72(%rsp) .cfi_offset rbp, -56 -.Labi_test_trampoline_prolog_rbp: +.Labi_test_trampoline_seh_prolog_rbp: movq %r12,80(%rsp) .cfi_offset r12, -48 -.Labi_test_trampoline_prolog_r12: +.Labi_test_trampoline_seh_prolog_r12: movq %r13,88(%rsp) .cfi_offset r13, -40 -.Labi_test_trampoline_prolog_r13: +.Labi_test_trampoline_seh_prolog_r13: movq %r14,96(%rsp) .cfi_offset r14, -32 -.Labi_test_trampoline_prolog_r14: +.Labi_test_trampoline_seh_prolog_r14: movq %r15,104(%rsp) .cfi_offset r15, -24 -.Labi_test_trampoline_prolog_r15: -.Labi_test_trampoline_prolog_end: +.Labi_test_trampoline_seh_prolog_r15: +.Labi_test_trampoline_seh_prolog_end: movq 0(%rsi),%rbx movq 8(%rsi),%rbp movq 16(%rsi),%r12 @@ -182,7 +182,7 @@ abi_test_unwind_stop: .byte 0xf3,0xc3 .cfi_endproc -.Labi_test_trampoline_end: +.Labi_test_trampoline_seh_end: .size abi_test_trampoline,.-abi_test_trampoline .type abi_test_clobber_rax, @function .globl abi_test_clobber_rax @@ -441,13 +441,20 @@ abi_test_clobber_xmm15: .align 16 abi_test_bad_unwind_wrong_register: .cfi_startproc +.Labi_test_bad_unwind_wrong_register_seh_begin: pushq %r12 .cfi_adjust_cfa_offset 8 .cfi_offset %r13,-16 +.Labi_test_bad_unwind_wrong_register_seh_push_r13: + + + + nop popq %r12 .cfi_adjust_cfa_offset -8 .cfi_restore %r12 .byte 0xf3,0xc3 +.Labi_test_bad_unwind_wrong_register_seh_end: .cfi_endproc .size abi_test_bad_unwind_wrong_register,.-abi_test_bad_unwind_wrong_register @@ -460,15 +467,18 @@ abi_test_bad_unwind_wrong_register: .align 16 abi_test_bad_unwind_temporary: .cfi_startproc +.Labi_test_bad_unwind_temporary_seh_begin: pushq %r12 .cfi_adjust_cfa_offset 8 .cfi_offset %r12,-16 +.Labi_test_bad_unwind_temporary_seh_push_r12: + + movq %r12,%rax + incq %rax + movq %rax,(%rsp) - incq %r12 - movq %r12,(%rsp) - decq %r12 movq %r12,(%rsp) @@ -476,6 +486,7 @@ abi_test_bad_unwind_temporary: .cfi_adjust_cfa_offset -8 .cfi_restore %r12 .byte 0xf3,0xc3 +.Labi_test_bad_unwind_temporary_seh_end: .cfi_endproc .size abi_test_bad_unwind_temporary,.-abi_test_bad_unwind_temporary @@ -489,7 +500,7 @@ abi_test_get_and_clear_direction_flag: pushfq popq %rax andq $0x400,%rax - shlq $10,%rax + shrq $10,%rax cld .byte 0xf3,0xc3 .size abi_test_get_and_clear_direction_flag,.-abi_test_get_and_clear_direction_flag diff --git a/third_party/boringssl/kit/linux-x86_64/crypto/third_party/sike/asm/fp-x86_64.S b/third_party/boringssl/kit/linux-x86_64/crypto/third_party/sike/asm/fp-x86_64.S new file mode 100644 index 00000000..a6c49d6e --- /dev/null +++ b/third_party/boringssl/kit/linux-x86_64/crypto/third_party/sike/asm/fp-x86_64.S @@ -0,0 +1,2086 @@ +# This file is generated from a similarly-named Perl script in the BoringSSL +# source tree. Do not edit by hand. + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) +#define OPENSSL_NO_ASM +#endif +#endif + +#if defined(__x86_64__) && !defined(OPENSSL_NO_ASM) +#if defined(BORINGSSL_PREFIX) +#include +#endif +.text + + +.Lp503x2: +.quad 0xFFFFFFFFFFFFFFFE +.quad 0xFFFFFFFFFFFFFFFF +.quad 0x57FFFFFFFFFFFFFF +.quad 0x2610B7B44423CF41 +.quad 0x3737ED90F6FCFB5E +.quad 0xC08B8D7BB4EF49A0 +.quad 0x0080CDEA83023C3C + + +.Lp503p1: +.quad 0xAC00000000000000 +.quad 0x13085BDA2211E7A0 +.quad 0x1B9BF6C87B7E7DAF +.quad 0x6045C6BDDA77A4D0 +.quad 0x004066F541811E1E + +.Lp503p1_nz: +.quad 0xAC00000000000000 +.quad 0x13085BDA2211E7A0 +.quad 0x1B9BF6C87B7E7DAF +.quad 0x6045C6BDDA77A4D0 +.quad 0x004066F541811E1E + +.extern OPENSSL_ia32cap_P +.hidden OPENSSL_ia32cap_P +.hidden OPENSSL_ia32cap_P + +.globl sike_fpadd +.hidden sike_fpadd +.type sike_fpadd,@function +sike_fpadd: +.cfi_startproc + pushq %r12 +.cfi_adjust_cfa_offset 8 +.cfi_offset r12, -16 + pushq %r13 +.cfi_adjust_cfa_offset 8 +.cfi_offset r13, -24 + pushq %r14 +.cfi_adjust_cfa_offset 8 +.cfi_offset r14, -32 + pushq %r15 +.cfi_adjust_cfa_offset 8 +.cfi_offset r15, -40 + + xorq %rax,%rax + + movq 0(%rdi),%r8 + movq 8(%rdi),%r9 + movq 16(%rdi),%r10 + movq 24(%rdi),%r11 + movq 32(%rdi),%r12 + movq 40(%rdi),%r13 + movq 48(%rdi),%r14 + movq 56(%rdi),%r15 + + addq 0(%rsi),%r8 + adcq 8(%rsi),%r9 + adcq 16(%rsi),%r10 + adcq 24(%rsi),%r11 + adcq 32(%rsi),%r12 + adcq 40(%rsi),%r13 + adcq 48(%rsi),%r14 + adcq 56(%rsi),%r15 + + movq .Lp503x2(%rip),%rcx; + subq %rcx,%r8 + movq 8+.Lp503x2(%rip),%rcx; + sbbq %rcx,%r9 + sbbq %rcx,%r10 + movq 16+.Lp503x2(%rip),%rcx; + sbbq %rcx,%r11 + movq 24+.Lp503x2(%rip),%rcx; + sbbq %rcx,%r12 + movq 32+.Lp503x2(%rip),%rcx; + sbbq %rcx,%r13 + movq 40+.Lp503x2(%rip),%rcx; + sbbq %rcx,%r14 + movq 48+.Lp503x2(%rip),%rcx; + sbbq %rcx,%r15 + sbbq $0,%rax + + movq .Lp503x2(%rip),%rdi + andq %rax,%rdi + movq 8+.Lp503x2(%rip),%rsi + andq %rax,%rsi + movq 16+.Lp503x2(%rip),%rcx + andq %rax,%rcx + + addq %rdi,%r8 + movq %r8,0(%rdx) + adcq %rsi,%r9 + movq %r9,8(%rdx) + adcq %rsi,%r10 + movq %r10,16(%rdx) + adcq %rcx,%r11 + movq %r11,24(%rdx) + + setc %cl + + movq 24+.Lp503x2(%rip),%r8 + andq %rax,%r8 + movq 32+.Lp503x2(%rip),%r9 + andq %rax,%r9 + movq 40+.Lp503x2(%rip),%r10 + andq %rax,%r10 + movq 48+.Lp503x2(%rip),%r11 + andq %rax,%r11 + + btq $0,%rcx + + adcq %r8,%r12 + movq %r12,32(%rdx) + adcq %r9,%r13 + movq %r13,40(%rdx) + adcq %r10,%r14 + movq %r14,48(%rdx) + adcq %r11,%r15 + movq %r15,56(%rdx) + + popq %r15 +.cfi_adjust_cfa_offset -8 + popq %r14 +.cfi_adjust_cfa_offset -8 + popq %r13 +.cfi_adjust_cfa_offset -8 + popq %r12 +.cfi_adjust_cfa_offset -8 + .byte 0xf3,0xc3 +.cfi_endproc +.globl sike_cswap_asm +.hidden sike_cswap_asm +.type sike_cswap_asm,@function +sike_cswap_asm: + + + movq %rdx,%xmm3 + + + + + + pshufd $68,%xmm3,%xmm3 + + movdqu 0(%rdi),%xmm0 + movdqu 0(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,0(%rdi) + movdqu %xmm1,0(%rsi) + + movdqu 16(%rdi),%xmm0 + movdqu 16(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,16(%rdi) + movdqu %xmm1,16(%rsi) + + movdqu 32(%rdi),%xmm0 + movdqu 32(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,32(%rdi) + movdqu %xmm1,32(%rsi) + + movdqu 48(%rdi),%xmm0 + movdqu 48(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,48(%rdi) + movdqu %xmm1,48(%rsi) + + movdqu 64(%rdi),%xmm0 + movdqu 64(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,64(%rdi) + movdqu %xmm1,64(%rsi) + + movdqu 80(%rdi),%xmm0 + movdqu 80(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,80(%rdi) + movdqu %xmm1,80(%rsi) + + movdqu 96(%rdi),%xmm0 + movdqu 96(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,96(%rdi) + movdqu %xmm1,96(%rsi) + + movdqu 112(%rdi),%xmm0 + movdqu 112(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,112(%rdi) + movdqu %xmm1,112(%rsi) + + movdqu 128(%rdi),%xmm0 + movdqu 128(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,128(%rdi) + movdqu %xmm1,128(%rsi) + + movdqu 144(%rdi),%xmm0 + movdqu 144(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,144(%rdi) + movdqu %xmm1,144(%rsi) + + movdqu 160(%rdi),%xmm0 + movdqu 160(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,160(%rdi) + movdqu %xmm1,160(%rsi) + + movdqu 176(%rdi),%xmm0 + movdqu 176(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,176(%rdi) + movdqu %xmm1,176(%rsi) + + movdqu 192(%rdi),%xmm0 + movdqu 192(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,192(%rdi) + movdqu %xmm1,192(%rsi) + + movdqu 208(%rdi),%xmm0 + movdqu 208(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,208(%rdi) + movdqu %xmm1,208(%rsi) + + movdqu 224(%rdi),%xmm0 + movdqu 224(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,224(%rdi) + movdqu %xmm1,224(%rsi) + + movdqu 240(%rdi),%xmm0 + movdqu 240(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,240(%rdi) + movdqu %xmm1,240(%rsi) + + .byte 0xf3,0xc3 +.globl sike_fpsub +.hidden sike_fpsub +.type sike_fpsub,@function +sike_fpsub: +.cfi_startproc + pushq %r12 +.cfi_adjust_cfa_offset 8 +.cfi_offset r12, -16 + pushq %r13 +.cfi_adjust_cfa_offset 8 +.cfi_offset r13, -24 + pushq %r14 +.cfi_adjust_cfa_offset 8 +.cfi_offset r14, -32 + pushq %r15 +.cfi_adjust_cfa_offset 8 +.cfi_offset r15, -40 + + xorq %rax,%rax + + movq 0(%rdi),%r8 + movq 8(%rdi),%r9 + movq 16(%rdi),%r10 + movq 24(%rdi),%r11 + movq 32(%rdi),%r12 + movq 40(%rdi),%r13 + movq 48(%rdi),%r14 + movq 56(%rdi),%r15 + + subq 0(%rsi),%r8 + sbbq 8(%rsi),%r9 + sbbq 16(%rsi),%r10 + sbbq 24(%rsi),%r11 + sbbq 32(%rsi),%r12 + sbbq 40(%rsi),%r13 + sbbq 48(%rsi),%r14 + sbbq 56(%rsi),%r15 + sbbq $0x0,%rax + + movq .Lp503x2(%rip),%rdi + andq %rax,%rdi + movq 8+.Lp503x2(%rip),%rsi + andq %rax,%rsi + movq 16+.Lp503x2(%rip),%rcx + andq %rax,%rcx + + addq %rdi,%r8 + adcq %rsi,%r9 + adcq %rsi,%r10 + adcq %rcx,%r11 + movq %r8,0(%rdx) + movq %r9,8(%rdx) + movq %r10,16(%rdx) + movq %r11,24(%rdx) + + setc %cl + + movq 24+.Lp503x2(%rip),%r8 + andq %rax,%r8 + movq 32+.Lp503x2(%rip),%r9 + andq %rax,%r9 + movq 40+.Lp503x2(%rip),%r10 + andq %rax,%r10 + movq 48+.Lp503x2(%rip),%r11 + andq %rax,%r11 + + btq $0x0,%rcx + + adcq %r8,%r12 + adcq %r9,%r13 + adcq %r10,%r14 + adcq %r11,%r15 + movq %r12,32(%rdx) + movq %r13,40(%rdx) + movq %r14,48(%rdx) + movq %r15,56(%rdx) + + popq %r15 +.cfi_adjust_cfa_offset -8 + popq %r14 +.cfi_adjust_cfa_offset -8 + popq %r13 +.cfi_adjust_cfa_offset -8 + popq %r12 +.cfi_adjust_cfa_offset -8 + .byte 0xf3,0xc3 +.cfi_endproc +.globl sike_mpadd_asm +.hidden sike_mpadd_asm +.type sike_mpadd_asm,@function +sike_mpadd_asm: +.cfi_startproc + movq 0(%rdi),%r8 + movq 8(%rdi),%r9 + movq 16(%rdi),%r10 + movq 24(%rdi),%r11 + addq 0(%rsi),%r8 + adcq 8(%rsi),%r9 + adcq 16(%rsi),%r10 + adcq 24(%rsi),%r11 + movq %r8,0(%rdx) + movq %r9,8(%rdx) + movq %r10,16(%rdx) + movq %r11,24(%rdx) + + movq 32(%rdi),%r8 + movq 40(%rdi),%r9 + movq 48(%rdi),%r10 + movq 56(%rdi),%r11 + adcq 32(%rsi),%r8 + adcq 40(%rsi),%r9 + adcq 48(%rsi),%r10 + adcq 56(%rsi),%r11 + movq %r8,32(%rdx) + movq %r9,40(%rdx) + movq %r10,48(%rdx) + movq %r11,56(%rdx) + .byte 0xf3,0xc3 +.cfi_endproc +.globl sike_mpsubx2_asm +.hidden sike_mpsubx2_asm +.type sike_mpsubx2_asm,@function +sike_mpsubx2_asm: +.cfi_startproc + xorq %rax,%rax + + movq 0(%rdi),%r8 + movq 8(%rdi),%r9 + movq 16(%rdi),%r10 + movq 24(%rdi),%r11 + movq 32(%rdi),%rcx + subq 0(%rsi),%r8 + sbbq 8(%rsi),%r9 + sbbq 16(%rsi),%r10 + sbbq 24(%rsi),%r11 + sbbq 32(%rsi),%rcx + movq %r8,0(%rdx) + movq %r9,8(%rdx) + movq %r10,16(%rdx) + movq %r11,24(%rdx) + movq %rcx,32(%rdx) + + movq 40(%rdi),%r8 + movq 48(%rdi),%r9 + movq 56(%rdi),%r10 + movq 64(%rdi),%r11 + movq 72(%rdi),%rcx + sbbq 40(%rsi),%r8 + sbbq 48(%rsi),%r9 + sbbq 56(%rsi),%r10 + sbbq 64(%rsi),%r11 + sbbq 72(%rsi),%rcx + movq %r8,40(%rdx) + movq %r9,48(%rdx) + movq %r10,56(%rdx) + movq %r11,64(%rdx) + movq %rcx,72(%rdx) + + movq 80(%rdi),%r8 + movq 88(%rdi),%r9 + movq 96(%rdi),%r10 + movq 104(%rdi),%r11 + movq 112(%rdi),%rcx + sbbq 80(%rsi),%r8 + sbbq 88(%rsi),%r9 + sbbq 96(%rsi),%r10 + sbbq 104(%rsi),%r11 + sbbq 112(%rsi),%rcx + movq %r8,80(%rdx) + movq %r9,88(%rdx) + movq %r10,96(%rdx) + movq %r11,104(%rdx) + movq %rcx,112(%rdx) + + movq 120(%rdi),%r8 + sbbq 120(%rsi),%r8 + sbbq $0x0,%rax + movq %r8,120(%rdx) + .byte 0xf3,0xc3 +.cfi_endproc +.globl sike_mpdblsubx2_asm +.hidden sike_mpdblsubx2_asm +.type sike_mpdblsubx2_asm,@function +sike_mpdblsubx2_asm: +.cfi_startproc + pushq %r12 +.cfi_adjust_cfa_offset 8 +.cfi_offset r12, -16 + pushq %r13 +.cfi_adjust_cfa_offset 8 +.cfi_offset r13, -24 + pushq %r14 +.cfi_adjust_cfa_offset 8 +.cfi_offset r14, -32 + + xorq %rax,%rax + + movq 0(%rdx),%r8 + movq 8(%rdx),%r9 + movq 16(%rdx),%r10 + movq 24(%rdx),%r11 + movq 32(%rdx),%r12 + movq 40(%rdx),%r13 + movq 48(%rdx),%r14 + movq 56(%rdx),%rcx + subq 0(%rdi),%r8 + sbbq 8(%rdi),%r9 + sbbq 16(%rdi),%r10 + sbbq 24(%rdi),%r11 + sbbq 32(%rdi),%r12 + sbbq 40(%rdi),%r13 + sbbq 48(%rdi),%r14 + sbbq 56(%rdi),%rcx + adcq $0x0,%rax + + subq 0(%rsi),%r8 + sbbq 8(%rsi),%r9 + sbbq 16(%rsi),%r10 + sbbq 24(%rsi),%r11 + sbbq 32(%rsi),%r12 + sbbq 40(%rsi),%r13 + sbbq 48(%rsi),%r14 + sbbq 56(%rsi),%rcx + adcq $0x0,%rax + + movq %r8,0(%rdx) + movq %r9,8(%rdx) + movq %r10,16(%rdx) + movq %r11,24(%rdx) + movq %r12,32(%rdx) + movq %r13,40(%rdx) + movq %r14,48(%rdx) + movq %rcx,56(%rdx) + + movq 64(%rdx),%r8 + movq 72(%rdx),%r9 + movq 80(%rdx),%r10 + movq 88(%rdx),%r11 + movq 96(%rdx),%r12 + movq 104(%rdx),%r13 + movq 112(%rdx),%r14 + movq 120(%rdx),%rcx + + subq %rax,%r8 + sbbq 64(%rdi),%r8 + sbbq 72(%rdi),%r9 + sbbq 80(%rdi),%r10 + sbbq 88(%rdi),%r11 + sbbq 96(%rdi),%r12 + sbbq 104(%rdi),%r13 + sbbq 112(%rdi),%r14 + sbbq 120(%rdi),%rcx + subq 64(%rsi),%r8 + sbbq 72(%rsi),%r9 + sbbq 80(%rsi),%r10 + sbbq 88(%rsi),%r11 + sbbq 96(%rsi),%r12 + sbbq 104(%rsi),%r13 + sbbq 112(%rsi),%r14 + sbbq 120(%rsi),%rcx + + movq %r8,64(%rdx) + movq %r9,72(%rdx) + movq %r10,80(%rdx) + movq %r11,88(%rdx) + movq %r12,96(%rdx) + movq %r13,104(%rdx) + movq %r14,112(%rdx) + movq %rcx,120(%rdx) + + popq %r14 +.cfi_adjust_cfa_offset -8 + popq %r13 +.cfi_adjust_cfa_offset -8 + popq %r12 +.cfi_adjust_cfa_offset -8 + .byte 0xf3,0xc3 +.cfi_endproc + +.Lmul_mulx: +.cfi_startproc + +.cfi_adjust_cfa_offset 32 +.cfi_offset r12, -16 +.cfi_offset r13, -24 +.cfi_offset r14, -32 +.cfi_offset r15, -40 + + movq %rdx,%rcx + + + xorq %rax,%rax + movq (%rdi),%r8 + movq 8(%rdi),%r9 + movq 16(%rdi),%r10 + movq 24(%rdi),%r11 + pushq %rbx + +.cfi_adjust_cfa_offset 8 +.cfi_offset rbx, -48 + pushq %rbp +.cfi_offset rbp, -56 +.cfi_adjust_cfa_offset 8 + subq $96,%rsp +.cfi_adjust_cfa_offset 96 + addq 32(%rdi),%r8 + adcq 40(%rdi),%r9 + adcq 48(%rdi),%r10 + adcq 56(%rdi),%r11 + sbbq $0x0,%rax + movq %r8,(%rsp) + movq %r9,8(%rsp) + movq %r10,16(%rsp) + movq %r11,24(%rsp) + + + xorq %rbx,%rbx + movq (%rsi),%r12 + movq 8(%rsi),%r13 + movq 16(%rsi),%r14 + movq 24(%rsi),%r15 + addq 32(%rsi),%r12 + adcq 40(%rsi),%r13 + adcq 48(%rsi),%r14 + adcq 56(%rsi),%r15 + sbbq $0x0,%rbx + movq %r12,32(%rsp) + movq %r13,40(%rsp) + movq %r14,48(%rsp) + movq %r15,56(%rsp) + + + andq %rax,%r12 + andq %rax,%r13 + andq %rax,%r14 + andq %rax,%r15 + + + andq %rbx,%r8 + andq %rbx,%r9 + andq %rbx,%r10 + andq %rbx,%r11 + + + addq %r12,%r8 + adcq %r13,%r9 + adcq %r14,%r10 + adcq %r15,%r11 + movq %r8,64(%rsp) + movq %r9,72(%rsp) + movq %r10,80(%rsp) + movq %r11,88(%rsp) + + + movq 0+0(%rsp),%rdx + mulxq 32+0(%rsp),%r9,%r8 + movq %r9,64+0(%rcx) + mulxq 32+8(%rsp),%r10,%r9 + xorq %rax,%rax + adoxq %r10,%r8 + mulxq 32+16(%rsp),%r11,%r10 + adoxq %r11,%r9 + mulxq 32+24(%rsp),%r12,%r11 + adoxq %r12,%r10 + + movq 0+8(%rsp),%rdx + mulxq 32+0(%rsp),%r12,%r13 + adoxq %rax,%r11 + xorq %rax,%rax + mulxq 32+8(%rsp),%r15,%r14 + adoxq %r8,%r12 + movq %r12,64+8(%rcx) + adcxq %r15,%r13 + mulxq 32+16(%rsp),%rbx,%r15 + adcxq %rbx,%r14 + adoxq %r9,%r13 + mulxq 32+24(%rsp),%rbp,%rbx + adcxq %rbp,%r15 + adcxq %rax,%rbx + adoxq %r10,%r14 + + movq 0+16(%rsp),%rdx + mulxq 32+0(%rsp),%r8,%r9 + adoxq %r11,%r15 + adoxq %rax,%rbx + xorq %rax,%rax + mulxq 32+8(%rsp),%r11,%r10 + adoxq %r13,%r8 + movq %r8,64+16(%rcx) + adcxq %r11,%r9 + mulxq 32+16(%rsp),%r12,%r11 + adcxq %r12,%r10 + adoxq %r14,%r9 + mulxq 32+24(%rsp),%rbp,%r12 + adcxq %rbp,%r11 + + adcxq %rax,%r12 + adoxq %r15,%r10 + adoxq %rbx,%r11 + adoxq %rax,%r12 + + movq 0+24(%rsp),%rdx + mulxq 32+0(%rsp),%r8,%r13 + xorq %rax,%rax + mulxq 32+8(%rsp),%r15,%r14 + adcxq %r15,%r13 + adoxq %r8,%r9 + mulxq 32+16(%rsp),%rbx,%r15 + adcxq %rbx,%r14 + adoxq %r13,%r10 + mulxq 32+24(%rsp),%rbp,%rbx + adcxq %rbp,%r15 + adcxq %rax,%rbx + adoxq %r14,%r11 + adoxq %r15,%r12 + adoxq %rax,%rbx + movq %r9,64+24(%rcx) + movq %r10,64+32(%rcx) + movq %r11,64+40(%rcx) + movq %r12,64+48(%rcx) + movq %rbx,64+56(%rcx) + + + + movq 0+0(%rdi),%rdx + mulxq 0+0(%rsi),%r9,%r8 + movq %r9,0+0(%rcx) + mulxq 0+8(%rsi),%r10,%r9 + xorq %rax,%rax + adoxq %r10,%r8 + mulxq 0+16(%rsi),%r11,%r10 + adoxq %r11,%r9 + mulxq 0+24(%rsi),%r12,%r11 + adoxq %r12,%r10 + + movq 0+8(%rdi),%rdx + mulxq 0+0(%rsi),%r12,%r13 + adoxq %rax,%r11 + xorq %rax,%rax + mulxq 0+8(%rsi),%r15,%r14 + adoxq %r8,%r12 + movq %r12,0+8(%rcx) + adcxq %r15,%r13 + mulxq 0+16(%rsi),%rbx,%r15 + adcxq %rbx,%r14 + adoxq %r9,%r13 + mulxq 0+24(%rsi),%rbp,%rbx + adcxq %rbp,%r15 + adcxq %rax,%rbx + adoxq %r10,%r14 + + movq 0+16(%rdi),%rdx + mulxq 0+0(%rsi),%r8,%r9 + adoxq %r11,%r15 + adoxq %rax,%rbx + xorq %rax,%rax + mulxq 0+8(%rsi),%r11,%r10 + adoxq %r13,%r8 + movq %r8,0+16(%rcx) + adcxq %r11,%r9 + mulxq 0+16(%rsi),%r12,%r11 + adcxq %r12,%r10 + adoxq %r14,%r9 + mulxq 0+24(%rsi),%rbp,%r12 + adcxq %rbp,%r11 + + adcxq %rax,%r12 + adoxq %r15,%r10 + adoxq %rbx,%r11 + adoxq %rax,%r12 + + movq 0+24(%rdi),%rdx + mulxq 0+0(%rsi),%r8,%r13 + xorq %rax,%rax + mulxq 0+8(%rsi),%r15,%r14 + adcxq %r15,%r13 + adoxq %r8,%r9 + mulxq 0+16(%rsi),%rbx,%r15 + adcxq %rbx,%r14 + adoxq %r13,%r10 + mulxq 0+24(%rsi),%rbp,%rbx + adcxq %rbp,%r15 + adcxq %rax,%rbx + adoxq %r14,%r11 + adoxq %r15,%r12 + adoxq %rax,%rbx + movq %r9,0+24(%rcx) + movq %r10,0+32(%rcx) + movq %r11,0+40(%rcx) + movq %r12,0+48(%rcx) + movq %rbx,0+56(%rcx) + + + + movq 32+0(%rdi),%rdx + mulxq 32+0(%rsi),%r9,%r8 + movq %r9,0+0(%rsp) + mulxq 32+8(%rsi),%r10,%r9 + xorq %rax,%rax + adoxq %r10,%r8 + mulxq 32+16(%rsi),%r11,%r10 + adoxq %r11,%r9 + mulxq 32+24(%rsi),%r12,%r11 + adoxq %r12,%r10 + + movq 32+8(%rdi),%rdx + mulxq 32+0(%rsi),%r12,%r13 + adoxq %rax,%r11 + xorq %rax,%rax + mulxq 32+8(%rsi),%r15,%r14 + adoxq %r8,%r12 + movq %r12,0+8(%rsp) + adcxq %r15,%r13 + mulxq 32+16(%rsi),%rbx,%r15 + adcxq %rbx,%r14 + adoxq %r9,%r13 + mulxq 32+24(%rsi),%rbp,%rbx + adcxq %rbp,%r15 + adcxq %rax,%rbx + adoxq %r10,%r14 + + movq 32+16(%rdi),%rdx + mulxq 32+0(%rsi),%r8,%r9 + adoxq %r11,%r15 + adoxq %rax,%rbx + xorq %rax,%rax + mulxq 32+8(%rsi),%r11,%r10 + adoxq %r13,%r8 + movq %r8,0+16(%rsp) + adcxq %r11,%r9 + mulxq 32+16(%rsi),%r12,%r11 + adcxq %r12,%r10 + adoxq %r14,%r9 + mulxq 32+24(%rsi),%rbp,%r12 + adcxq %rbp,%r11 + + adcxq %rax,%r12 + adoxq %r15,%r10 + adoxq %rbx,%r11 + adoxq %rax,%r12 + + movq 32+24(%rdi),%rdx + mulxq 32+0(%rsi),%r8,%r13 + xorq %rax,%rax + mulxq 32+8(%rsi),%r15,%r14 + adcxq %r15,%r13 + adoxq %r8,%r9 + mulxq 32+16(%rsi),%rbx,%r15 + adcxq %rbx,%r14 + adoxq %r13,%r10 + mulxq 32+24(%rsi),%rbp,%rbx + adcxq %rbp,%r15 + adcxq %rax,%rbx + adoxq %r14,%r11 + adoxq %r15,%r12 + adoxq %rax,%rbx + movq %r9,0+24(%rsp) + movq %r10,0+32(%rsp) + movq %r11,0+40(%rsp) + movq %r12,0+48(%rsp) + movq %rbx,0+56(%rsp) + + + + + movq 64(%rsp),%r8 + movq 72(%rsp),%r9 + movq 80(%rsp),%r10 + movq 88(%rsp),%r11 + movq 96(%rcx),%rax + addq %rax,%r8 + movq 104(%rcx),%rax + adcq %rax,%r9 + movq 112(%rcx),%rax + adcq %rax,%r10 + movq 120(%rcx),%rax + adcq %rax,%r11 + + + movq 64(%rcx),%r12 + movq 72(%rcx),%r13 + movq 80(%rcx),%r14 + movq 88(%rcx),%r15 + subq (%rcx),%r12 + sbbq 8(%rcx),%r13 + sbbq 16(%rcx),%r14 + sbbq 24(%rcx),%r15 + sbbq 32(%rcx),%r8 + sbbq 40(%rcx),%r9 + sbbq 48(%rcx),%r10 + sbbq 56(%rcx),%r11 + + + subq (%rsp),%r12 + sbbq 8(%rsp),%r13 + sbbq 16(%rsp),%r14 + sbbq 24(%rsp),%r15 + sbbq 32(%rsp),%r8 + sbbq 40(%rsp),%r9 + sbbq 48(%rsp),%r10 + sbbq 56(%rsp),%r11 + + addq 32(%rcx),%r12 + movq %r12,32(%rcx) + adcq 40(%rcx),%r13 + movq %r13,40(%rcx) + adcq 48(%rcx),%r14 + movq %r14,48(%rcx) + adcq 56(%rcx),%r15 + movq %r15,56(%rcx) + movq (%rsp),%rax + adcq %rax,%r8 + movq %r8,64(%rcx) + movq 8(%rsp),%rax + adcq %rax,%r9 + movq %r9,72(%rcx) + movq 16(%rsp),%rax + adcq %rax,%r10 + movq %r10,80(%rcx) + movq 24(%rsp),%rax + adcq %rax,%r11 + movq %r11,88(%rcx) + movq 32(%rsp),%r12 + adcq $0x0,%r12 + movq %r12,96(%rcx) + movq 40(%rsp),%r13 + adcq $0x0,%r13 + movq %r13,104(%rcx) + movq 48(%rsp),%r14 + adcq $0x0,%r14 + movq %r14,112(%rcx) + movq 56(%rsp),%r15 + adcq $0x0,%r15 + movq %r15,120(%rcx) + + addq $96,%rsp +.cfi_adjust_cfa_offset -96 + popq %rbp +.cfi_adjust_cfa_offset -8 +.cfi_same_value rbp + popq %rbx +.cfi_adjust_cfa_offset -8 +.cfi_same_value rbx + popq %r15 +.cfi_adjust_cfa_offset -8 +.cfi_same_value r15 + popq %r14 +.cfi_adjust_cfa_offset -8 +.cfi_same_value r14 + popq %r13 +.cfi_adjust_cfa_offset -8 +.cfi_same_value r13 + popq %r12 +.cfi_adjust_cfa_offset -8 +.cfi_same_value r12 + .byte 0xf3,0xc3 +.cfi_endproc + +.globl sike_mpmul +.hidden sike_mpmul +.type sike_mpmul,@function +sike_mpmul: +.cfi_startproc + pushq %r12 +.cfi_adjust_cfa_offset 8 +.cfi_offset r12, -16 + pushq %r13 +.cfi_adjust_cfa_offset 8 +.cfi_offset r13, -24 + pushq %r14 +.cfi_adjust_cfa_offset 8 +.cfi_offset r14, -32 + pushq %r15 +.cfi_adjust_cfa_offset 8 +.cfi_offset r15, -40 + + leaq OPENSSL_ia32cap_P(%rip),%rcx + movq 8(%rcx),%rcx + andl $0x80100,%ecx + cmpl $0x80100,%ecx + je .Lmul_mulx + + + + movq %rdx,%rcx + + + xorq %rax,%rax + movq 32(%rdi),%r8 + movq 40(%rdi),%r9 + movq 48(%rdi),%r10 + movq 56(%rdi),%r11 + addq 0(%rdi),%r8 + adcq 8(%rdi),%r9 + adcq 16(%rdi),%r10 + adcq 24(%rdi),%r11 + movq %r8,0(%rcx) + movq %r9,8(%rcx) + movq %r10,16(%rcx) + movq %r11,24(%rcx) + sbbq $0,%rax + subq $80,%rsp +.cfi_adjust_cfa_offset 80 + + + xorq %rdx,%rdx + movq 32(%rsi),%r12 + movq 40(%rsi),%r13 + movq 48(%rsi),%r14 + movq 56(%rsi),%r15 + addq 0(%rsi),%r12 + adcq 8(%rsi),%r13 + adcq 16(%rsi),%r14 + adcq 24(%rsi),%r15 + sbbq $0x0,%rdx + movq %rax,64(%rsp) + movq %rdx,72(%rsp) + + + movq (%rcx),%rax + mulq %r12 + movq %rax,(%rsp) + movq %rdx,%r8 + + xorq %r9,%r9 + movq (%rcx),%rax + mulq %r13 + addq %rax,%r8 + adcq %rdx,%r9 + + xorq %r10,%r10 + movq 8(%rcx),%rax + mulq %r12 + addq %rax,%r8 + movq %r8,8(%rsp) + adcq %rdx,%r9 + adcq $0x0,%r10 + + xorq %r8,%r8 + movq (%rcx),%rax + mulq %r14 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 16(%rcx),%rax + mulq %r12 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 8(%rcx),%rax + mulq %r13 + addq %rax,%r9 + movq %r9,16(%rsp) + adcq %rdx,%r10 + adcq $0x0,%r8 + + xorq %r9,%r9 + movq (%rcx),%rax + mulq %r15 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq 24(%rcx),%rax + mulq %r12 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq 8(%rcx),%rax + mulq %r14 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq 16(%rcx),%rax + mulq %r13 + addq %rax,%r10 + movq %r10,24(%rsp) + adcq %rdx,%r8 + adcq $0x0,%r9 + + xorq %r10,%r10 + movq 8(%rcx),%rax + mulq %r15 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0x0,%r10 + + movq 24(%rcx),%rax + mulq %r13 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0x0,%r10 + + movq 16(%rcx),%rax + mulq %r14 + addq %rax,%r8 + movq %r8,32(%rsp) + adcq %rdx,%r9 + adcq $0x0,%r10 + + xorq %r11,%r11 + movq 16(%rcx),%rax + mulq %r15 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r11 + + movq 24(%rcx),%rax + mulq %r14 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r11 + + movq 24(%rcx),%rax + mulq %r15 + addq %rax,%r10 + adcq %rdx,%r11 + + movq 64(%rsp),%rax + andq %rax,%r12 + andq %rax,%r13 + andq %rax,%r14 + andq %rax,%r15 + addq %r8,%r12 + adcq %r9,%r13 + adcq %r10,%r14 + adcq %r11,%r15 + + movq 72(%rsp),%rax + movq (%rcx),%r8 + movq 8(%rcx),%r9 + movq 16(%rcx),%r10 + movq 24(%rcx),%r11 + andq %rax,%r8 + andq %rax,%r9 + andq %rax,%r10 + andq %rax,%r11 + addq %r12,%r8 + adcq %r13,%r9 + adcq %r14,%r10 + adcq %r15,%r11 + movq %r8,32(%rsp) + movq %r9,40(%rsp) + movq %r10,48(%rsp) + movq %r11,56(%rsp) + + movq (%rdi),%r11 + movq (%rsi),%rax + mulq %r11 + xorq %r9,%r9 + movq %rax,(%rcx) + movq %rdx,%r8 + + movq 16(%rdi),%r14 + movq 8(%rsi),%rax + mulq %r11 + xorq %r10,%r10 + addq %rax,%r8 + adcq %rdx,%r9 + + movq 8(%rdi),%r12 + movq (%rsi),%rax + mulq %r12 + addq %rax,%r8 + movq %r8,8(%rcx) + adcq %rdx,%r9 + adcq $0x0,%r10 + + xorq %r8,%r8 + movq 16(%rsi),%rax + mulq %r11 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq (%rsi),%r13 + movq %r14,%rax + mulq %r13 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 8(%rsi),%rax + mulq %r12 + addq %rax,%r9 + movq %r9,16(%rcx) + adcq %rdx,%r10 + adcq $0x0,%r8 + + xorq %r9,%r9 + movq 24(%rsi),%rax + mulq %r11 + movq 24(%rdi),%r15 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq %r15,%rax + mulq %r13 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq 16(%rsi),%rax + mulq %r12 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq 8(%rsi),%rax + mulq %r14 + addq %rax,%r10 + movq %r10,24(%rcx) + adcq %rdx,%r8 + adcq $0x0,%r9 + + xorq %r10,%r10 + movq 24(%rsi),%rax + mulq %r12 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0x0,%r10 + + movq 8(%rsi),%rax + mulq %r15 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0x0,%r10 + + movq 16(%rsi),%rax + mulq %r14 + addq %rax,%r8 + movq %r8,32(%rcx) + adcq %rdx,%r9 + adcq $0x0,%r10 + + xorq %r8,%r8 + movq 24(%rsi),%rax + mulq %r14 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 16(%rsi),%rax + mulq %r15 + addq %rax,%r9 + movq %r9,40(%rcx) + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 24(%rsi),%rax + mulq %r15 + addq %rax,%r10 + movq %r10,48(%rcx) + adcq %rdx,%r8 + movq %r8,56(%rcx) + + + movq 32(%rdi),%r11 + movq 32(%rsi),%rax + mulq %r11 + xorq %r9,%r9 + movq %rax,64(%rcx) + movq %rdx,%r8 + + movq 48(%rdi),%r14 + movq 40(%rsi),%rax + mulq %r11 + xorq %r10,%r10 + addq %rax,%r8 + adcq %rdx,%r9 + + movq 40(%rdi),%r12 + movq 32(%rsi),%rax + mulq %r12 + addq %rax,%r8 + movq %r8,72(%rcx) + adcq %rdx,%r9 + adcq $0x0,%r10 + + xorq %r8,%r8 + movq 48(%rsi),%rax + mulq %r11 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 32(%rsi),%r13 + movq %r14,%rax + mulq %r13 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 40(%rsi),%rax + mulq %r12 + addq %rax,%r9 + movq %r9,80(%rcx) + adcq %rdx,%r10 + adcq $0x0,%r8 + + xorq %r9,%r9 + movq 56(%rsi),%rax + mulq %r11 + movq 56(%rdi),%r15 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq %r15,%rax + mulq %r13 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq 48(%rsi),%rax + mulq %r12 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq 40(%rsi),%rax + mulq %r14 + addq %rax,%r10 + movq %r10,88(%rcx) + adcq %rdx,%r8 + adcq $0x0,%r9 + + xorq %r10,%r10 + movq 56(%rsi),%rax + mulq %r12 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0x0,%r10 + + movq 40(%rsi),%rax + mulq %r15 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0x0,%r10 + + movq 48(%rsi),%rax + mulq %r14 + addq %rax,%r8 + movq %r8,96(%rcx) + adcq %rdx,%r9 + adcq $0x0,%r10 + + xorq %r8,%r8 + movq 56(%rsi),%rax + mulq %r14 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 48(%rsi),%rax + mulq %r15 + addq %rax,%r9 + movq %r9,104(%rcx) + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 56(%rsi),%rax + mulq %r15 + addq %rax,%r10 + movq %r10,112(%rcx) + adcq %rdx,%r8 + movq %r8,120(%rcx) + + + movq 0(%rsp),%r8 + subq 0(%rcx),%r8 + movq 8(%rsp),%r9 + sbbq 8(%rcx),%r9 + movq 16(%rsp),%r10 + sbbq 16(%rcx),%r10 + movq 24(%rsp),%r11 + sbbq 24(%rcx),%r11 + movq 32(%rsp),%r12 + sbbq 32(%rcx),%r12 + movq 40(%rsp),%r13 + sbbq 40(%rcx),%r13 + movq 48(%rsp),%r14 + sbbq 48(%rcx),%r14 + movq 56(%rsp),%r15 + sbbq 56(%rcx),%r15 + + + movq 64(%rcx),%rax + subq %rax,%r8 + movq 72(%rcx),%rax + sbbq %rax,%r9 + movq 80(%rcx),%rax + sbbq %rax,%r10 + movq 88(%rcx),%rax + sbbq %rax,%r11 + movq 96(%rcx),%rax + sbbq %rax,%r12 + movq 104(%rcx),%rdx + sbbq %rdx,%r13 + movq 112(%rcx),%rdi + sbbq %rdi,%r14 + movq 120(%rcx),%rsi + sbbq %rsi,%r15 + + + addq 32(%rcx),%r8 + movq %r8,32(%rcx) + adcq 40(%rcx),%r9 + movq %r9,40(%rcx) + adcq 48(%rcx),%r10 + movq %r10,48(%rcx) + adcq 56(%rcx),%r11 + movq %r11,56(%rcx) + adcq 64(%rcx),%r12 + movq %r12,64(%rcx) + adcq 72(%rcx),%r13 + movq %r13,72(%rcx) + adcq 80(%rcx),%r14 + movq %r14,80(%rcx) + adcq 88(%rcx),%r15 + movq %r15,88(%rcx) + adcq $0x0,%rax + movq %rax,96(%rcx) + adcq $0x0,%rdx + movq %rdx,104(%rcx) + adcq $0x0,%rdi + movq %rdi,112(%rcx) + adcq $0x0,%rsi + movq %rsi,120(%rcx) + + addq $80,%rsp +.cfi_adjust_cfa_offset -80 + popq %r15 +.cfi_adjust_cfa_offset -8 + popq %r14 +.cfi_adjust_cfa_offset -8 + popq %r13 +.cfi_adjust_cfa_offset -8 + popq %r12 +.cfi_adjust_cfa_offset -8 + .byte 0xf3,0xc3 +.cfi_endproc + +.Lrdc_mulx_asm: +.cfi_startproc + +.cfi_adjust_cfa_offset 32 +.cfi_offset r12, -16 +.cfi_offset r13, -24 +.cfi_offset r14, -32 +.cfi_offset r15, -40 +.cfi_offset rbx, -48 +.cfi_adjust_cfa_offset 8 + + movq 0+0(%rdi),%rdx + mulxq 0+.Lp503p1_nz(%rip),%r8,%r9 + mulxq 8+.Lp503p1_nz(%rip),%r12,%r10 + + xorq %rax,%rax + mulxq 16+.Lp503p1_nz(%rip),%r13,%r11 + adoxq %r12,%r9 + adoxq %r13,%r10 + mulxq 24+.Lp503p1_nz(%rip),%rbx,%r12 + adoxq %rbx,%r11 + mulxq 32+.Lp503p1_nz(%rip),%r14,%r13 + adoxq %r14,%r12 + adoxq %rax,%r13 + + movq 0+8(%rdi),%rdx + mulxq 0+.Lp503p1_nz(%rip),%r14,%rbx + adcxq %r14,%r9 + adcxq %rbx,%r10 + mulxq 8+.Lp503p1_nz(%rip),%rcx,%r14 + adcxq %r14,%r11 + mulxq 16+.Lp503p1_nz(%rip),%rbx,%r15 + adcxq %r15,%r12 + mulxq 24+.Lp503p1_nz(%rip),%r15,%r14 + adcxq %r14,%r13 + mulxq 32+.Lp503p1_nz(%rip),%rdx,%r14 + adcxq %rax,%r14 + + xorq %rax,%rax + adoxq %rcx,%r10 + adoxq %rbx,%r11 + adoxq %r15,%r12 + adoxq %rdx,%r13 + adoxq %rax,%r14 + + + + xorq %r15,%r15 + addq 24(%rdi),%r8 + adcq 32(%rdi),%r9 + adcq 40(%rdi),%r10 + adcq 48(%rdi),%r11 + adcq 56(%rdi),%r12 + adcq 64(%rdi),%r13 + adcq 72(%rdi),%r14 + adcq 80(%rdi),%r15 + movq %r8,24(%rdi) + movq %r9,32(%rdi) + movq %r10,40(%rdi) + movq %r11,48(%rdi) + movq %r12,56(%rdi) + movq %r13,64(%rdi) + movq %r14,72(%rdi) + movq %r15,80(%rdi) + movq 88(%rdi),%r8 + movq 96(%rdi),%r9 + movq 104(%rdi),%r10 + movq 112(%rdi),%r11 + movq 120(%rdi),%r12 + adcq $0x0,%r8 + adcq $0x0,%r9 + adcq $0x0,%r10 + adcq $0x0,%r11 + adcq $0x0,%r12 + movq %r8,88(%rdi) + movq %r9,96(%rdi) + movq %r10,104(%rdi) + movq %r11,112(%rdi) + movq %r12,120(%rdi) + + movq 16+0(%rdi),%rdx + mulxq 0+.Lp503p1_nz(%rip),%r8,%r9 + mulxq 8+.Lp503p1_nz(%rip),%r12,%r10 + + xorq %rax,%rax + mulxq 16+.Lp503p1_nz(%rip),%r13,%r11 + adoxq %r12,%r9 + adoxq %r13,%r10 + mulxq 24+.Lp503p1_nz(%rip),%rbx,%r12 + adoxq %rbx,%r11 + mulxq 32+.Lp503p1_nz(%rip),%r14,%r13 + adoxq %r14,%r12 + adoxq %rax,%r13 + + movq 16+8(%rdi),%rdx + mulxq 0+.Lp503p1_nz(%rip),%r14,%rbx + adcxq %r14,%r9 + adcxq %rbx,%r10 + mulxq 8+.Lp503p1_nz(%rip),%rcx,%r14 + adcxq %r14,%r11 + mulxq 16+.Lp503p1_nz(%rip),%rbx,%r15 + adcxq %r15,%r12 + mulxq 24+.Lp503p1_nz(%rip),%r15,%r14 + adcxq %r14,%r13 + mulxq 32+.Lp503p1_nz(%rip),%rdx,%r14 + adcxq %rax,%r14 + + xorq %rax,%rax + adoxq %rcx,%r10 + adoxq %rbx,%r11 + adoxq %r15,%r12 + adoxq %rdx,%r13 + adoxq %rax,%r14 + + + + xorq %r15,%r15 + addq 40(%rdi),%r8 + adcq 48(%rdi),%r9 + adcq 56(%rdi),%r10 + adcq 64(%rdi),%r11 + adcq 72(%rdi),%r12 + adcq 80(%rdi),%r13 + adcq 88(%rdi),%r14 + adcq 96(%rdi),%r15 + movq %r8,40(%rdi) + movq %r9,48(%rdi) + movq %r10,56(%rdi) + movq %r11,64(%rdi) + movq %r12,72(%rdi) + movq %r13,80(%rdi) + movq %r14,88(%rdi) + movq %r15,96(%rdi) + movq 104(%rdi),%r8 + movq 112(%rdi),%r9 + movq 120(%rdi),%r10 + adcq $0x0,%r8 + adcq $0x0,%r9 + adcq $0x0,%r10 + movq %r8,104(%rdi) + movq %r9,112(%rdi) + movq %r10,120(%rdi) + + movq 32+0(%rdi),%rdx + mulxq 0+.Lp503p1_nz(%rip),%r8,%r9 + mulxq 8+.Lp503p1_nz(%rip),%r12,%r10 + + xorq %rax,%rax + mulxq 16+.Lp503p1_nz(%rip),%r13,%r11 + adoxq %r12,%r9 + adoxq %r13,%r10 + mulxq 24+.Lp503p1_nz(%rip),%rbx,%r12 + adoxq %rbx,%r11 + mulxq 32+.Lp503p1_nz(%rip),%r14,%r13 + adoxq %r14,%r12 + adoxq %rax,%r13 + + movq 32+8(%rdi),%rdx + mulxq 0+.Lp503p1_nz(%rip),%r14,%rbx + adcxq %r14,%r9 + adcxq %rbx,%r10 + mulxq 8+.Lp503p1_nz(%rip),%rcx,%r14 + adcxq %r14,%r11 + mulxq 16+.Lp503p1_nz(%rip),%rbx,%r15 + adcxq %r15,%r12 + mulxq 24+.Lp503p1_nz(%rip),%r15,%r14 + adcxq %r14,%r13 + mulxq 32+.Lp503p1_nz(%rip),%rdx,%r14 + adcxq %rax,%r14 + + xorq %rax,%rax + adoxq %rcx,%r10 + adoxq %rbx,%r11 + adoxq %r15,%r12 + adoxq %rdx,%r13 + adoxq %rax,%r14 + + + + xorq %r15,%r15 + xorq %rbx,%rbx + addq 56(%rdi),%r8 + adcq 64(%rdi),%r9 + adcq 72(%rdi),%r10 + adcq 80(%rdi),%r11 + adcq 88(%rdi),%r12 + adcq 96(%rdi),%r13 + adcq 104(%rdi),%r14 + adcq 112(%rdi),%r15 + adcq 120(%rdi),%rbx + movq %r8,56(%rdi) + movq %r9,(%rsi) + movq %r10,72(%rdi) + movq %r11,80(%rdi) + movq %r12,88(%rdi) + movq %r13,96(%rdi) + movq %r14,104(%rdi) + movq %r15,112(%rdi) + movq %rbx,120(%rdi) + + movq 48+0(%rdi),%rdx + mulxq 0+.Lp503p1_nz(%rip),%r8,%r9 + mulxq 8+.Lp503p1_nz(%rip),%r12,%r10 + + xorq %rax,%rax + mulxq 16+.Lp503p1_nz(%rip),%r13,%r11 + adoxq %r12,%r9 + adoxq %r13,%r10 + mulxq 24+.Lp503p1_nz(%rip),%rbx,%r12 + adoxq %rbx,%r11 + mulxq 32+.Lp503p1_nz(%rip),%r14,%r13 + adoxq %r14,%r12 + adoxq %rax,%r13 + + movq 48+8(%rdi),%rdx + mulxq 0+.Lp503p1_nz(%rip),%r14,%rbx + adcxq %r14,%r9 + adcxq %rbx,%r10 + mulxq 8+.Lp503p1_nz(%rip),%rcx,%r14 + adcxq %r14,%r11 + mulxq 16+.Lp503p1_nz(%rip),%rbx,%r15 + adcxq %r15,%r12 + mulxq 24+.Lp503p1_nz(%rip),%r15,%r14 + adcxq %r14,%r13 + mulxq 32+.Lp503p1_nz(%rip),%rdx,%r14 + adcxq %rax,%r14 + + xorq %rax,%rax + adoxq %rcx,%r10 + adoxq %rbx,%r11 + adoxq %r15,%r12 + adoxq %rdx,%r13 + adoxq %rax,%r14 + + + + addq 72(%rdi),%r8 + adcq 80(%rdi),%r9 + adcq 88(%rdi),%r10 + adcq 96(%rdi),%r11 + adcq 104(%rdi),%r12 + adcq 112(%rdi),%r13 + adcq 120(%rdi),%r14 + movq %r8,8(%rsi) + movq %r9,16(%rsi) + movq %r10,24(%rsi) + movq %r11,32(%rsi) + movq %r12,40(%rsi) + movq %r13,48(%rsi) + movq %r14,56(%rsi) + + popq %rbx +.cfi_adjust_cfa_offset -8 +.cfi_same_value rbx + popq %r15 +.cfi_adjust_cfa_offset -8 +.cfi_same_value r15 + popq %r14 +.cfi_adjust_cfa_offset -8 +.cfi_same_value r14 + popq %r13 +.cfi_adjust_cfa_offset -8 +.cfi_same_value r13 + popq %r12 +.cfi_adjust_cfa_offset -8 +.cfi_same_value r12 + .byte 0xf3,0xc3 +.cfi_endproc +.globl sike_fprdc +.hidden sike_fprdc +.type sike_fprdc,@function +sike_fprdc: +.cfi_startproc + pushq %r12 +.cfi_adjust_cfa_offset 8 +.cfi_offset r12, -16 + pushq %r13 +.cfi_adjust_cfa_offset 8 +.cfi_offset r13, -24 + pushq %r14 +.cfi_adjust_cfa_offset 8 +.cfi_offset r14, -32 + pushq %r15 +.cfi_adjust_cfa_offset 8 +.cfi_offset r15, -40 + pushq %rbx +.cfi_adjust_cfa_offset 8 +.cfi_offset rbx, -48 + + leaq OPENSSL_ia32cap_P(%rip),%rcx + movq 8(%rcx),%rcx + andl $0x80100,%ecx + cmpl $0x80100,%ecx + je .Lrdc_mulx_asm + + + + + leaq .Lp503p1(%rip),%rbx + + movq (%rdi),%r11 + movq (%rbx),%rax + mulq %r11 + xorq %r8,%r8 + addq 24(%rdi),%rax + movq %rax,24(%rsi) + adcq %rdx,%r8 + + xorq %r9,%r9 + movq 8(%rbx),%rax + mulq %r11 + xorq %r10,%r10 + addq %rax,%r8 + adcq %rdx,%r9 + + movq 8(%rdi),%r12 + movq (%rbx),%rax + mulq %r12 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + addq 32(%rdi),%r8 + movq %r8,32(%rsi) + adcq $0,%r9 + adcq $0,%r10 + + xorq %r8,%r8 + movq 16(%rbx),%rax + mulq %r11 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 8(%rbx),%rax + mulq %r12 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 16(%rdi),%r13 + movq (%rbx),%rax + mulq %r13 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + addq 40(%rdi),%r9 + movq %r9,40(%rsi) + adcq $0,%r10 + adcq $0,%r8 + + xorq %r9,%r9 + movq 24(%rbx),%rax + mulq %r11 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 16(%rbx),%rax + mulq %r12 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 8(%rbx),%rax + mulq %r13 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 24(%rsi),%r14 + movq (%rbx),%rax + mulq %r14 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + addq 48(%rdi),%r10 + movq %r10,48(%rsi) + adcq $0,%r8 + adcq $0,%r9 + + xorq %r10,%r10 + movq 32(%rbx),%rax + mulq %r11 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 24(%rbx),%rax + mulq %r12 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 16(%rbx),%rax + mulq %r13 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 8(%rbx),%rax + mulq %r14 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 32(%rsi),%r15 + movq (%rbx),%rax + mulq %r15 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + addq 56(%rdi),%r8 + movq %r8,56(%rsi) + adcq $0,%r9 + adcq $0,%r10 + + xorq %r8,%r8 + movq 32(%rbx),%rax + mulq %r12 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 24(%rbx),%rax + mulq %r13 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 16(%rbx),%rax + mulq %r14 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 8(%rbx),%rax + mulq %r15 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 40(%rsi),%rcx + movq (%rbx),%rax + mulq %rcx + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + addq 64(%rdi),%r9 + movq %r9,(%rsi) + adcq $0,%r10 + adcq $0,%r8 + + xorq %r9,%r9 + movq 32(%rbx),%rax + mulq %r13 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 24(%rbx),%rax + mulq %r14 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 16(%rbx),%rax + mulq %r15 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 8(%rbx),%rax + mulq %rcx + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 48(%rsi),%r13 + movq (%rbx),%rax + mulq %r13 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + addq 72(%rdi),%r10 + movq %r10,8(%rsi) + adcq $0,%r8 + adcq $0,%r9 + + xorq %r10,%r10 + movq 32(%rbx),%rax + mulq %r14 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 24(%rbx),%rax + mulq %r15 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 16(%rbx),%rax + mulq %rcx + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 8(%rbx),%rax + mulq %r13 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 56(%rsi),%r14 + movq (%rbx),%rax + mulq %r14 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + addq 80(%rdi),%r8 + movq %r8,16(%rsi) + adcq $0,%r9 + adcq $0,%r10 + + xorq %r8,%r8 + movq 32(%rbx),%rax + mulq %r15 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 24(%rbx),%rax + mulq %rcx + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 16(%rbx),%rax + mulq %r13 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 8(%rbx),%rax + mulq %r14 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + addq 88(%rdi),%r9 + movq %r9,24(%rsi) + adcq $0,%r10 + adcq $0,%r8 + + xorq %r9,%r9 + movq 32(%rbx),%rax + mulq %rcx + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 24(%rbx),%rax + mulq %r13 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 16(%rbx),%rax + mulq %r14 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + addq 96(%rdi),%r10 + movq %r10,32(%rsi) + adcq $0,%r8 + adcq $0,%r9 + + xorq %r10,%r10 + movq 32(%rbx),%rax + mulq %r13 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 24(%rbx),%rax + mulq %r14 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + addq 104(%rdi),%r8 + movq %r8,40(%rsi) + adcq $0,%r9 + adcq $0,%r10 + + movq 32(%rbx),%rax + mulq %r14 + addq %rax,%r9 + adcq %rdx,%r10 + addq 112(%rdi),%r9 + movq %r9,48(%rsi) + adcq $0,%r10 + addq 120(%rdi),%r10 + movq %r10,56(%rsi) + + popq %rbx +.cfi_adjust_cfa_offset -8 + popq %r15 +.cfi_adjust_cfa_offset -8 + popq %r14 +.cfi_adjust_cfa_offset -8 + popq %r13 +.cfi_adjust_cfa_offset -8 + popq %r12 +.cfi_adjust_cfa_offset -8 + .byte 0xf3,0xc3 +.cfi_endproc +#endif diff --git a/third_party/boringssl/kit/mac-x86/crypto/fipsmodule/aesni-x86.S b/third_party/boringssl/kit/mac-x86/crypto/fipsmodule/aesni-x86.S index cca1d32b..17eeaeac 100644 --- a/third_party/boringssl/kit/mac-x86/crypto/fipsmodule/aesni-x86.S +++ b/third_party/boringssl/kit/mac-x86/crypto/fipsmodule/aesni-x86.S @@ -6,11 +6,25 @@ #include #endif .text +#ifndef NDEBUG +#endif .globl _aes_hw_encrypt .private_extern _aes_hw_encrypt .align 4 _aes_hw_encrypt: L_aes_hw_encrypt_begin: +#ifndef NDEBUG + pushl %ebx + pushl %edx + call L000pic +L000pic: + popl %ebx + leal _BORINGSSL_function_hit+1-L000pic(%ebx),%ebx + movl $1,%edx + movb %dl,(%ebx) + popl %edx + popl %ebx +#endif movl 4(%esp),%eax movl 12(%esp),%edx movups (%eax),%xmm2 @@ -20,12 +34,12 @@ L_aes_hw_encrypt_begin: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -L000enc1_loop_1: +L001enc1_loop_1: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz L000enc1_loop_1 + jnz L001enc1_loop_1 .byte 102,15,56,221,209 pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 @@ -46,12 +60,12 @@ L_aes_hw_decrypt_begin: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -L001dec1_loop_2: +L002dec1_loop_2: .byte 102,15,56,222,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz L001dec1_loop_2 + jnz L002dec1_loop_2 .byte 102,15,56,223,209 pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 @@ -70,7 +84,7 @@ __aesni_encrypt2: leal 32(%edx,%ecx,1),%edx negl %ecx addl $16,%ecx -L002enc2_loop: +L003enc2_loop: .byte 102,15,56,220,209 .byte 102,15,56,220,217 movups (%edx,%ecx,1),%xmm1 @@ -78,7 +92,7 @@ L002enc2_loop: .byte 102,15,56,220,208 .byte 102,15,56,220,216 movups -16(%edx,%ecx,1),%xmm0 - jnz L002enc2_loop + jnz L003enc2_loop .byte 102,15,56,220,209 .byte 102,15,56,220,217 .byte 102,15,56,221,208 @@ -96,7 +110,7 @@ __aesni_decrypt2: leal 32(%edx,%ecx,1),%edx negl %ecx addl $16,%ecx -L003dec2_loop: +L004dec2_loop: .byte 102,15,56,222,209 .byte 102,15,56,222,217 movups (%edx,%ecx,1),%xmm1 @@ -104,7 +118,7 @@ L003dec2_loop: .byte 102,15,56,222,208 .byte 102,15,56,222,216 movups -16(%edx,%ecx,1),%xmm0 - jnz L003dec2_loop + jnz L004dec2_loop .byte 102,15,56,222,209 .byte 102,15,56,222,217 .byte 102,15,56,223,208 @@ -123,7 +137,7 @@ __aesni_encrypt3: leal 32(%edx,%ecx,1),%edx negl %ecx addl $16,%ecx -L004enc3_loop: +L005enc3_loop: .byte 102,15,56,220,209 .byte 102,15,56,220,217 .byte 102,15,56,220,225 @@ -133,7 +147,7 @@ L004enc3_loop: .byte 102,15,56,220,216 .byte 102,15,56,220,224 movups -16(%edx,%ecx,1),%xmm0 - jnz L004enc3_loop + jnz L005enc3_loop .byte 102,15,56,220,209 .byte 102,15,56,220,217 .byte 102,15,56,220,225 @@ -154,7 +168,7 @@ __aesni_decrypt3: leal 32(%edx,%ecx,1),%edx negl %ecx addl $16,%ecx -L005dec3_loop: +L006dec3_loop: .byte 102,15,56,222,209 .byte 102,15,56,222,217 .byte 102,15,56,222,225 @@ -164,7 +178,7 @@ L005dec3_loop: .byte 102,15,56,222,216 .byte 102,15,56,222,224 movups -16(%edx,%ecx,1),%xmm0 - jnz L005dec3_loop + jnz L006dec3_loop .byte 102,15,56,222,209 .byte 102,15,56,222,217 .byte 102,15,56,222,225 @@ -187,7 +201,7 @@ __aesni_encrypt4: negl %ecx .byte 15,31,64,0 addl $16,%ecx -L006enc4_loop: +L007enc4_loop: .byte 102,15,56,220,209 .byte 102,15,56,220,217 .byte 102,15,56,220,225 @@ -199,7 +213,7 @@ L006enc4_loop: .byte 102,15,56,220,224 .byte 102,15,56,220,232 movups -16(%edx,%ecx,1),%xmm0 - jnz L006enc4_loop + jnz L007enc4_loop .byte 102,15,56,220,209 .byte 102,15,56,220,217 .byte 102,15,56,220,225 @@ -224,7 +238,7 @@ __aesni_decrypt4: negl %ecx .byte 15,31,64,0 addl $16,%ecx -L007dec4_loop: +L008dec4_loop: .byte 102,15,56,222,209 .byte 102,15,56,222,217 .byte 102,15,56,222,225 @@ -236,7 +250,7 @@ L007dec4_loop: .byte 102,15,56,222,224 .byte 102,15,56,222,232 movups -16(%edx,%ecx,1),%xmm0 - jnz L007dec4_loop + jnz L008dec4_loop .byte 102,15,56,222,209 .byte 102,15,56,222,217 .byte 102,15,56,222,225 @@ -265,13 +279,13 @@ __aesni_encrypt6: pxor %xmm0,%xmm7 movups (%edx,%ecx,1),%xmm0 addl $16,%ecx - jmp L008_aesni_encrypt6_inner + jmp L009_aesni_encrypt6_inner .align 4,0x90 -L009enc6_loop: +L010enc6_loop: .byte 102,15,56,220,209 .byte 102,15,56,220,217 .byte 102,15,56,220,225 -L008_aesni_encrypt6_inner: +L009_aesni_encrypt6_inner: .byte 102,15,56,220,233 .byte 102,15,56,220,241 .byte 102,15,56,220,249 @@ -285,7 +299,7 @@ L_aesni_encrypt6_enter: .byte 102,15,56,220,240 .byte 102,15,56,220,248 movups -16(%edx,%ecx,1),%xmm0 - jnz L009enc6_loop + jnz L010enc6_loop .byte 102,15,56,220,209 .byte 102,15,56,220,217 .byte 102,15,56,220,225 @@ -318,13 +332,13 @@ __aesni_decrypt6: pxor %xmm0,%xmm7 movups (%edx,%ecx,1),%xmm0 addl $16,%ecx - jmp L010_aesni_decrypt6_inner + jmp L011_aesni_decrypt6_inner .align 4,0x90 -L011dec6_loop: +L012dec6_loop: .byte 102,15,56,222,209 .byte 102,15,56,222,217 .byte 102,15,56,222,225 -L010_aesni_decrypt6_inner: +L011_aesni_decrypt6_inner: .byte 102,15,56,222,233 .byte 102,15,56,222,241 .byte 102,15,56,222,249 @@ -338,7 +352,7 @@ L_aesni_decrypt6_enter: .byte 102,15,56,222,240 .byte 102,15,56,222,248 movups -16(%edx,%ecx,1),%xmm0 - jnz L011dec6_loop + jnz L012dec6_loop .byte 102,15,56,222,209 .byte 102,15,56,222,217 .byte 102,15,56,222,225 @@ -367,14 +381,14 @@ L_aes_hw_ecb_encrypt_begin: movl 32(%esp),%edx movl 36(%esp),%ebx andl $-16,%eax - jz L012ecb_ret + jz L013ecb_ret movl 240(%edx),%ecx testl %ebx,%ebx - jz L013ecb_decrypt + jz L014ecb_decrypt movl %edx,%ebp movl %ecx,%ebx cmpl $96,%eax - jb L014ecb_enc_tail + jb L015ecb_enc_tail movdqu (%esi),%xmm2 movdqu 16(%esi),%xmm3 movdqu 32(%esi),%xmm4 @@ -383,9 +397,9 @@ L_aes_hw_ecb_encrypt_begin: movdqu 80(%esi),%xmm7 leal 96(%esi),%esi subl $96,%eax - jmp L015ecb_enc_loop6_enter + jmp L016ecb_enc_loop6_enter .align 4,0x90 -L016ecb_enc_loop6: +L017ecb_enc_loop6: movups %xmm2,(%edi) movdqu (%esi),%xmm2 movups %xmm3,16(%edi) @@ -400,12 +414,12 @@ L016ecb_enc_loop6: leal 96(%edi),%edi movdqu 80(%esi),%xmm7 leal 96(%esi),%esi -L015ecb_enc_loop6_enter: +L016ecb_enc_loop6_enter: call __aesni_encrypt6 movl %ebp,%edx movl %ebx,%ecx subl $96,%eax - jnc L016ecb_enc_loop6 + jnc L017ecb_enc_loop6 movups %xmm2,(%edi) movups %xmm3,16(%edi) movups %xmm4,32(%edi) @@ -414,18 +428,18 @@ L015ecb_enc_loop6_enter: movups %xmm7,80(%edi) leal 96(%edi),%edi addl $96,%eax - jz L012ecb_ret -L014ecb_enc_tail: + jz L013ecb_ret +L015ecb_enc_tail: movups (%esi),%xmm2 cmpl $32,%eax - jb L017ecb_enc_one + jb L018ecb_enc_one movups 16(%esi),%xmm3 - je L018ecb_enc_two + je L019ecb_enc_two movups 32(%esi),%xmm4 cmpl $64,%eax - jb L019ecb_enc_three + jb L020ecb_enc_three movups 48(%esi),%xmm5 - je L020ecb_enc_four + je L021ecb_enc_four movups 64(%esi),%xmm6 xorps %xmm7,%xmm7 call __aesni_encrypt6 @@ -434,49 +448,49 @@ L014ecb_enc_tail: movups %xmm4,32(%edi) movups %xmm5,48(%edi) movups %xmm6,64(%edi) - jmp L012ecb_ret + jmp L013ecb_ret .align 4,0x90 -L017ecb_enc_one: +L018ecb_enc_one: movups (%edx),%xmm0 movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -L021enc1_loop_3: +L022enc1_loop_3: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz L021enc1_loop_3 + jnz L022enc1_loop_3 .byte 102,15,56,221,209 movups %xmm2,(%edi) - jmp L012ecb_ret + jmp L013ecb_ret .align 4,0x90 -L018ecb_enc_two: +L019ecb_enc_two: call __aesni_encrypt2 movups %xmm2,(%edi) movups %xmm3,16(%edi) - jmp L012ecb_ret + jmp L013ecb_ret .align 4,0x90 -L019ecb_enc_three: +L020ecb_enc_three: call __aesni_encrypt3 movups %xmm2,(%edi) movups %xmm3,16(%edi) movups %xmm4,32(%edi) - jmp L012ecb_ret + jmp L013ecb_ret .align 4,0x90 -L020ecb_enc_four: +L021ecb_enc_four: call __aesni_encrypt4 movups %xmm2,(%edi) movups %xmm3,16(%edi) movups %xmm4,32(%edi) movups %xmm5,48(%edi) - jmp L012ecb_ret + jmp L013ecb_ret .align 4,0x90 -L013ecb_decrypt: +L014ecb_decrypt: movl %edx,%ebp movl %ecx,%ebx cmpl $96,%eax - jb L022ecb_dec_tail + jb L023ecb_dec_tail movdqu (%esi),%xmm2 movdqu 16(%esi),%xmm3 movdqu 32(%esi),%xmm4 @@ -485,9 +499,9 @@ L013ecb_decrypt: movdqu 80(%esi),%xmm7 leal 96(%esi),%esi subl $96,%eax - jmp L023ecb_dec_loop6_enter + jmp L024ecb_dec_loop6_enter .align 4,0x90 -L024ecb_dec_loop6: +L025ecb_dec_loop6: movups %xmm2,(%edi) movdqu (%esi),%xmm2 movups %xmm3,16(%edi) @@ -502,12 +516,12 @@ L024ecb_dec_loop6: leal 96(%edi),%edi movdqu 80(%esi),%xmm7 leal 96(%esi),%esi -L023ecb_dec_loop6_enter: +L024ecb_dec_loop6_enter: call __aesni_decrypt6 movl %ebp,%edx movl %ebx,%ecx subl $96,%eax - jnc L024ecb_dec_loop6 + jnc L025ecb_dec_loop6 movups %xmm2,(%edi) movups %xmm3,16(%edi) movups %xmm4,32(%edi) @@ -516,18 +530,18 @@ L023ecb_dec_loop6_enter: movups %xmm7,80(%edi) leal 96(%edi),%edi addl $96,%eax - jz L012ecb_ret -L022ecb_dec_tail: + jz L013ecb_ret +L023ecb_dec_tail: movups (%esi),%xmm2 cmpl $32,%eax - jb L025ecb_dec_one + jb L026ecb_dec_one movups 16(%esi),%xmm3 - je L026ecb_dec_two + je L027ecb_dec_two movups 32(%esi),%xmm4 cmpl $64,%eax - jb L027ecb_dec_three + jb L028ecb_dec_three movups 48(%esi),%xmm5 - je L028ecb_dec_four + je L029ecb_dec_four movups 64(%esi),%xmm6 xorps %xmm7,%xmm7 call __aesni_decrypt6 @@ -536,43 +550,43 @@ L022ecb_dec_tail: movups %xmm4,32(%edi) movups %xmm5,48(%edi) movups %xmm6,64(%edi) - jmp L012ecb_ret + jmp L013ecb_ret .align 4,0x90 -L025ecb_dec_one: +L026ecb_dec_one: movups (%edx),%xmm0 movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -L029dec1_loop_4: +L030dec1_loop_4: .byte 102,15,56,222,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz L029dec1_loop_4 + jnz L030dec1_loop_4 .byte 102,15,56,223,209 movups %xmm2,(%edi) - jmp L012ecb_ret + jmp L013ecb_ret .align 4,0x90 -L026ecb_dec_two: +L027ecb_dec_two: call __aesni_decrypt2 movups %xmm2,(%edi) movups %xmm3,16(%edi) - jmp L012ecb_ret + jmp L013ecb_ret .align 4,0x90 -L027ecb_dec_three: +L028ecb_dec_three: call __aesni_decrypt3 movups %xmm2,(%edi) movups %xmm3,16(%edi) movups %xmm4,32(%edi) - jmp L012ecb_ret + jmp L013ecb_ret .align 4,0x90 -L028ecb_dec_four: +L029ecb_dec_four: call __aesni_decrypt4 movups %xmm2,(%edi) movups %xmm3,16(%edi) movups %xmm4,32(%edi) movups %xmm5,48(%edi) -L012ecb_ret: +L013ecb_ret: pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 pxor %xmm2,%xmm2 @@ -626,7 +640,7 @@ L_aes_hw_ccm64_encrypt_blocks_begin: leal 32(%edx,%ecx,1),%edx subl %ecx,%ebx .byte 102,15,56,0,253 -L030ccm64_enc_outer: +L031ccm64_enc_outer: movups (%ebp),%xmm0 movl %ebx,%ecx movups (%esi),%xmm6 @@ -635,7 +649,7 @@ L030ccm64_enc_outer: xorps %xmm6,%xmm0 xorps %xmm0,%xmm3 movups 32(%ebp),%xmm0 -L031ccm64_enc2_loop: +L032ccm64_enc2_loop: .byte 102,15,56,220,209 .byte 102,15,56,220,217 movups (%edx,%ecx,1),%xmm1 @@ -643,7 +657,7 @@ L031ccm64_enc2_loop: .byte 102,15,56,220,208 .byte 102,15,56,220,216 movups -16(%edx,%ecx,1),%xmm0 - jnz L031ccm64_enc2_loop + jnz L032ccm64_enc2_loop .byte 102,15,56,220,209 .byte 102,15,56,220,217 paddq 16(%esp),%xmm7 @@ -656,7 +670,7 @@ L031ccm64_enc2_loop: movups %xmm6,(%edi) .byte 102,15,56,0,213 leal 16(%edi),%edi - jnz L030ccm64_enc_outer + jnz L031ccm64_enc_outer movl 48(%esp),%esp movl 40(%esp),%edi movups %xmm3,(%edi) @@ -714,12 +728,12 @@ L_aes_hw_ccm64_decrypt_blocks_begin: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -L032enc1_loop_5: +L033enc1_loop_5: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz L032enc1_loop_5 + jnz L033enc1_loop_5 .byte 102,15,56,221,209 shll $4,%ebx movl $16,%ecx @@ -729,16 +743,16 @@ L032enc1_loop_5: subl %ebx,%ecx leal 32(%ebp,%ebx,1),%edx movl %ecx,%ebx - jmp L033ccm64_dec_outer + jmp L034ccm64_dec_outer .align 4,0x90 -L033ccm64_dec_outer: +L034ccm64_dec_outer: xorps %xmm2,%xmm6 movdqa %xmm7,%xmm2 movups %xmm6,(%edi) leal 16(%edi),%edi .byte 102,15,56,0,213 subl $1,%eax - jz L034ccm64_dec_break + jz L035ccm64_dec_break movups (%ebp),%xmm0 movl %ebx,%ecx movups 16(%ebp),%xmm1 @@ -746,7 +760,7 @@ L033ccm64_dec_outer: xorps %xmm0,%xmm2 xorps %xmm6,%xmm3 movups 32(%ebp),%xmm0 -L035ccm64_dec2_loop: +L036ccm64_dec2_loop: .byte 102,15,56,220,209 .byte 102,15,56,220,217 movups (%edx,%ecx,1),%xmm1 @@ -754,7 +768,7 @@ L035ccm64_dec2_loop: .byte 102,15,56,220,208 .byte 102,15,56,220,216 movups -16(%edx,%ecx,1),%xmm0 - jnz L035ccm64_dec2_loop + jnz L036ccm64_dec2_loop movups (%esi),%xmm6 paddq 16(%esp),%xmm7 .byte 102,15,56,220,209 @@ -762,9 +776,9 @@ L035ccm64_dec2_loop: .byte 102,15,56,221,208 .byte 102,15,56,221,216 leal 16(%esi),%esi - jmp L033ccm64_dec_outer + jmp L034ccm64_dec_outer .align 4,0x90 -L034ccm64_dec_break: +L035ccm64_dec_break: movl 240(%ebp),%ecx movl %ebp,%edx movups (%edx),%xmm0 @@ -772,12 +786,12 @@ L034ccm64_dec_break: xorps %xmm0,%xmm6 leal 32(%edx),%edx xorps %xmm6,%xmm3 -L036enc1_loop_6: +L037enc1_loop_6: .byte 102,15,56,220,217 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz L036enc1_loop_6 + jnz L037enc1_loop_6 .byte 102,15,56,221,217 movl 48(%esp),%esp movl 40(%esp),%edi @@ -804,6 +818,18 @@ L_aes_hw_ctr32_encrypt_blocks_begin: pushl %ebx pushl %esi pushl %edi +#ifndef NDEBUG + pushl %ebx + pushl %edx + call L038pic +L038pic: + popl %ebx + leal _BORINGSSL_function_hit+0-L038pic(%ebx),%ebx + movl $1,%edx + movb %dl,(%ebx) + popl %edx + popl %ebx +#endif movl 20(%esp),%esi movl 24(%esp),%edi movl 28(%esp),%eax @@ -814,7 +840,7 @@ L_aes_hw_ctr32_encrypt_blocks_begin: andl $-16,%esp movl %ebp,80(%esp) cmpl $1,%eax - je L037ctr32_one_shortcut + je L039ctr32_one_shortcut movdqu (%ebx),%xmm7 movl $202182159,(%esp) movl $134810123,4(%esp) @@ -852,7 +878,7 @@ L_aes_hw_ctr32_encrypt_blocks_begin: pshufd $192,%xmm0,%xmm2 pshufd $128,%xmm0,%xmm3 cmpl $6,%eax - jb L038ctr32_tail + jb L040ctr32_tail pxor %xmm6,%xmm7 shll $4,%ecx movl $16,%ebx @@ -861,9 +887,9 @@ L_aes_hw_ctr32_encrypt_blocks_begin: subl %ecx,%ebx leal 32(%edx,%ecx,1),%edx subl $6,%eax - jmp L039ctr32_loop6 + jmp L041ctr32_loop6 .align 4,0x90 -L039ctr32_loop6: +L041ctr32_loop6: pshufd $64,%xmm0,%xmm4 movdqa 32(%esp),%xmm0 pshufd $192,%xmm1,%xmm5 @@ -917,27 +943,27 @@ L039ctr32_loop6: leal 96(%edi),%edi pshufd $128,%xmm0,%xmm3 subl $6,%eax - jnc L039ctr32_loop6 + jnc L041ctr32_loop6 addl $6,%eax - jz L040ctr32_ret + jz L042ctr32_ret movdqu (%ebp),%xmm7 movl %ebp,%edx pxor 32(%esp),%xmm7 movl 240(%ebp),%ecx -L038ctr32_tail: +L040ctr32_tail: por %xmm7,%xmm2 cmpl $2,%eax - jb L041ctr32_one + jb L043ctr32_one pshufd $64,%xmm0,%xmm4 por %xmm7,%xmm3 - je L042ctr32_two + je L044ctr32_two pshufd $192,%xmm1,%xmm5 por %xmm7,%xmm4 cmpl $4,%eax - jb L043ctr32_three + jb L045ctr32_three pshufd $128,%xmm1,%xmm6 por %xmm7,%xmm5 - je L044ctr32_four + je L046ctr32_four por %xmm7,%xmm6 call __aesni_encrypt6 movups (%esi),%xmm1 @@ -955,29 +981,29 @@ L038ctr32_tail: movups %xmm4,32(%edi) movups %xmm5,48(%edi) movups %xmm6,64(%edi) - jmp L040ctr32_ret + jmp L042ctr32_ret .align 4,0x90 -L037ctr32_one_shortcut: +L039ctr32_one_shortcut: movups (%ebx),%xmm2 movl 240(%edx),%ecx -L041ctr32_one: +L043ctr32_one: movups (%edx),%xmm0 movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -L045enc1_loop_7: +L047enc1_loop_7: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz L045enc1_loop_7 + jnz L047enc1_loop_7 .byte 102,15,56,221,209 movups (%esi),%xmm6 xorps %xmm2,%xmm6 movups %xmm6,(%edi) - jmp L040ctr32_ret + jmp L042ctr32_ret .align 4,0x90 -L042ctr32_two: +L044ctr32_two: call __aesni_encrypt2 movups (%esi),%xmm5 movups 16(%esi),%xmm6 @@ -985,9 +1011,9 @@ L042ctr32_two: xorps %xmm6,%xmm3 movups %xmm2,(%edi) movups %xmm3,16(%edi) - jmp L040ctr32_ret + jmp L042ctr32_ret .align 4,0x90 -L043ctr32_three: +L045ctr32_three: call __aesni_encrypt3 movups (%esi),%xmm5 movups 16(%esi),%xmm6 @@ -998,9 +1024,9 @@ L043ctr32_three: xorps %xmm7,%xmm4 movups %xmm3,16(%edi) movups %xmm4,32(%edi) - jmp L040ctr32_ret + jmp L042ctr32_ret .align 4,0x90 -L044ctr32_four: +L046ctr32_four: call __aesni_encrypt4 movups (%esi),%xmm6 movups 16(%esi),%xmm7 @@ -1014,7 +1040,7 @@ L044ctr32_four: xorps %xmm0,%xmm5 movups %xmm4,32(%edi) movups %xmm5,48(%edi) -L040ctr32_ret: +L042ctr32_ret: pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 pxor %xmm2,%xmm2 @@ -1049,12 +1075,12 @@ L_aes_hw_xts_encrypt_begin: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -L046enc1_loop_8: +L048enc1_loop_8: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz L046enc1_loop_8 + jnz L048enc1_loop_8 .byte 102,15,56,221,209 movl 20(%esp),%esi movl 24(%esp),%edi @@ -1078,14 +1104,14 @@ L046enc1_loop_8: movl %edx,%ebp movl %ecx,%ebx subl $96,%eax - jc L047xts_enc_short + jc L049xts_enc_short shll $4,%ecx movl $16,%ebx subl %ecx,%ebx leal 32(%edx,%ecx,1),%edx - jmp L048xts_enc_loop6 + jmp L050xts_enc_loop6 .align 4,0x90 -L048xts_enc_loop6: +L050xts_enc_loop6: pshufd $19,%xmm0,%xmm2 pxor %xmm0,%xmm0 movdqa %xmm1,(%esp) @@ -1174,23 +1200,23 @@ L048xts_enc_loop6: pcmpgtd %xmm1,%xmm0 pxor %xmm2,%xmm1 subl $96,%eax - jnc L048xts_enc_loop6 + jnc L050xts_enc_loop6 movl 240(%ebp),%ecx movl %ebp,%edx movl %ecx,%ebx -L047xts_enc_short: +L049xts_enc_short: addl $96,%eax - jz L049xts_enc_done6x + jz L051xts_enc_done6x movdqa %xmm1,%xmm5 cmpl $32,%eax - jb L050xts_enc_one + jb L052xts_enc_one pshufd $19,%xmm0,%xmm2 pxor %xmm0,%xmm0 paddq %xmm1,%xmm1 pand %xmm3,%xmm2 pcmpgtd %xmm1,%xmm0 pxor %xmm2,%xmm1 - je L051xts_enc_two + je L053xts_enc_two pshufd $19,%xmm0,%xmm2 pxor %xmm0,%xmm0 movdqa %xmm1,%xmm6 @@ -1199,7 +1225,7 @@ L047xts_enc_short: pcmpgtd %xmm1,%xmm0 pxor %xmm2,%xmm1 cmpl $64,%eax - jb L052xts_enc_three + jb L054xts_enc_three pshufd $19,%xmm0,%xmm2 pxor %xmm0,%xmm0 movdqa %xmm1,%xmm7 @@ -1209,7 +1235,7 @@ L047xts_enc_short: pxor %xmm2,%xmm1 movdqa %xmm5,(%esp) movdqa %xmm6,16(%esp) - je L053xts_enc_four + je L055xts_enc_four movdqa %xmm7,32(%esp) pshufd $19,%xmm0,%xmm7 movdqa %xmm1,48(%esp) @@ -1241,9 +1267,9 @@ L047xts_enc_short: movups %xmm5,48(%edi) movups %xmm6,64(%edi) leal 80(%edi),%edi - jmp L054xts_enc_done + jmp L056xts_enc_done .align 4,0x90 -L050xts_enc_one: +L052xts_enc_one: movups (%esi),%xmm2 leal 16(%esi),%esi xorps %xmm5,%xmm2 @@ -1251,20 +1277,20 @@ L050xts_enc_one: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -L055enc1_loop_9: +L057enc1_loop_9: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz L055enc1_loop_9 + jnz L057enc1_loop_9 .byte 102,15,56,221,209 xorps %xmm5,%xmm2 movups %xmm2,(%edi) leal 16(%edi),%edi movdqa %xmm5,%xmm1 - jmp L054xts_enc_done + jmp L056xts_enc_done .align 4,0x90 -L051xts_enc_two: +L053xts_enc_two: movaps %xmm1,%xmm6 movups (%esi),%xmm2 movups 16(%esi),%xmm3 @@ -1278,9 +1304,9 @@ L051xts_enc_two: movups %xmm3,16(%edi) leal 32(%edi),%edi movdqa %xmm6,%xmm1 - jmp L054xts_enc_done + jmp L056xts_enc_done .align 4,0x90 -L052xts_enc_three: +L054xts_enc_three: movaps %xmm1,%xmm7 movups (%esi),%xmm2 movups 16(%esi),%xmm3 @@ -1298,9 +1324,9 @@ L052xts_enc_three: movups %xmm4,32(%edi) leal 48(%edi),%edi movdqa %xmm7,%xmm1 - jmp L054xts_enc_done + jmp L056xts_enc_done .align 4,0x90 -L053xts_enc_four: +L055xts_enc_four: movaps %xmm1,%xmm6 movups (%esi),%xmm2 movups 16(%esi),%xmm3 @@ -1322,28 +1348,28 @@ L053xts_enc_four: movups %xmm5,48(%edi) leal 64(%edi),%edi movdqa %xmm6,%xmm1 - jmp L054xts_enc_done + jmp L056xts_enc_done .align 4,0x90 -L049xts_enc_done6x: +L051xts_enc_done6x: movl 112(%esp),%eax andl $15,%eax - jz L056xts_enc_ret + jz L058xts_enc_ret movdqa %xmm1,%xmm5 movl %eax,112(%esp) - jmp L057xts_enc_steal + jmp L059xts_enc_steal .align 4,0x90 -L054xts_enc_done: +L056xts_enc_done: movl 112(%esp),%eax pxor %xmm0,%xmm0 andl $15,%eax - jz L056xts_enc_ret + jz L058xts_enc_ret pcmpgtd %xmm1,%xmm0 movl %eax,112(%esp) pshufd $19,%xmm0,%xmm5 paddq %xmm1,%xmm1 pand 96(%esp),%xmm5 pxor %xmm1,%xmm5 -L057xts_enc_steal: +L059xts_enc_steal: movzbl (%esi),%ecx movzbl -16(%edi),%edx leal 1(%esi),%esi @@ -1351,7 +1377,7 @@ L057xts_enc_steal: movb %dl,(%edi) leal 1(%edi),%edi subl $1,%eax - jnz L057xts_enc_steal + jnz L059xts_enc_steal subl 112(%esp),%edi movl %ebp,%edx movl %ebx,%ecx @@ -1361,16 +1387,16 @@ L057xts_enc_steal: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -L058enc1_loop_10: +L060enc1_loop_10: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz L058enc1_loop_10 + jnz L060enc1_loop_10 .byte 102,15,56,221,209 xorps %xmm5,%xmm2 movups %xmm2,-16(%edi) -L056xts_enc_ret: +L058xts_enc_ret: pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 pxor %xmm2,%xmm2 @@ -1408,12 +1434,12 @@ L_aes_hw_xts_decrypt_begin: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -L059enc1_loop_11: +L061enc1_loop_11: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz L059enc1_loop_11 + jnz L061enc1_loop_11 .byte 102,15,56,221,209 movl 20(%esp),%esi movl 24(%esp),%edi @@ -1442,14 +1468,14 @@ L059enc1_loop_11: pcmpgtd %xmm1,%xmm0 andl $-16,%eax subl $96,%eax - jc L060xts_dec_short + jc L062xts_dec_short shll $4,%ecx movl $16,%ebx subl %ecx,%ebx leal 32(%edx,%ecx,1),%edx - jmp L061xts_dec_loop6 + jmp L063xts_dec_loop6 .align 4,0x90 -L061xts_dec_loop6: +L063xts_dec_loop6: pshufd $19,%xmm0,%xmm2 pxor %xmm0,%xmm0 movdqa %xmm1,(%esp) @@ -1538,23 +1564,23 @@ L061xts_dec_loop6: pcmpgtd %xmm1,%xmm0 pxor %xmm2,%xmm1 subl $96,%eax - jnc L061xts_dec_loop6 + jnc L063xts_dec_loop6 movl 240(%ebp),%ecx movl %ebp,%edx movl %ecx,%ebx -L060xts_dec_short: +L062xts_dec_short: addl $96,%eax - jz L062xts_dec_done6x + jz L064xts_dec_done6x movdqa %xmm1,%xmm5 cmpl $32,%eax - jb L063xts_dec_one + jb L065xts_dec_one pshufd $19,%xmm0,%xmm2 pxor %xmm0,%xmm0 paddq %xmm1,%xmm1 pand %xmm3,%xmm2 pcmpgtd %xmm1,%xmm0 pxor %xmm2,%xmm1 - je L064xts_dec_two + je L066xts_dec_two pshufd $19,%xmm0,%xmm2 pxor %xmm0,%xmm0 movdqa %xmm1,%xmm6 @@ -1563,7 +1589,7 @@ L060xts_dec_short: pcmpgtd %xmm1,%xmm0 pxor %xmm2,%xmm1 cmpl $64,%eax - jb L065xts_dec_three + jb L067xts_dec_three pshufd $19,%xmm0,%xmm2 pxor %xmm0,%xmm0 movdqa %xmm1,%xmm7 @@ -1573,7 +1599,7 @@ L060xts_dec_short: pxor %xmm2,%xmm1 movdqa %xmm5,(%esp) movdqa %xmm6,16(%esp) - je L066xts_dec_four + je L068xts_dec_four movdqa %xmm7,32(%esp) pshufd $19,%xmm0,%xmm7 movdqa %xmm1,48(%esp) @@ -1605,9 +1631,9 @@ L060xts_dec_short: movups %xmm5,48(%edi) movups %xmm6,64(%edi) leal 80(%edi),%edi - jmp L067xts_dec_done + jmp L069xts_dec_done .align 4,0x90 -L063xts_dec_one: +L065xts_dec_one: movups (%esi),%xmm2 leal 16(%esi),%esi xorps %xmm5,%xmm2 @@ -1615,20 +1641,20 @@ L063xts_dec_one: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -L068dec1_loop_12: +L070dec1_loop_12: .byte 102,15,56,222,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz L068dec1_loop_12 + jnz L070dec1_loop_12 .byte 102,15,56,223,209 xorps %xmm5,%xmm2 movups %xmm2,(%edi) leal 16(%edi),%edi movdqa %xmm5,%xmm1 - jmp L067xts_dec_done + jmp L069xts_dec_done .align 4,0x90 -L064xts_dec_two: +L066xts_dec_two: movaps %xmm1,%xmm6 movups (%esi),%xmm2 movups 16(%esi),%xmm3 @@ -1642,9 +1668,9 @@ L064xts_dec_two: movups %xmm3,16(%edi) leal 32(%edi),%edi movdqa %xmm6,%xmm1 - jmp L067xts_dec_done + jmp L069xts_dec_done .align 4,0x90 -L065xts_dec_three: +L067xts_dec_three: movaps %xmm1,%xmm7 movups (%esi),%xmm2 movups 16(%esi),%xmm3 @@ -1662,9 +1688,9 @@ L065xts_dec_three: movups %xmm4,32(%edi) leal 48(%edi),%edi movdqa %xmm7,%xmm1 - jmp L067xts_dec_done + jmp L069xts_dec_done .align 4,0x90 -L066xts_dec_four: +L068xts_dec_four: movaps %xmm1,%xmm6 movups (%esi),%xmm2 movups 16(%esi),%xmm3 @@ -1686,20 +1712,20 @@ L066xts_dec_four: movups %xmm5,48(%edi) leal 64(%edi),%edi movdqa %xmm6,%xmm1 - jmp L067xts_dec_done + jmp L069xts_dec_done .align 4,0x90 -L062xts_dec_done6x: +L064xts_dec_done6x: movl 112(%esp),%eax andl $15,%eax - jz L069xts_dec_ret + jz L071xts_dec_ret movl %eax,112(%esp) - jmp L070xts_dec_only_one_more + jmp L072xts_dec_only_one_more .align 4,0x90 -L067xts_dec_done: +L069xts_dec_done: movl 112(%esp),%eax pxor %xmm0,%xmm0 andl $15,%eax - jz L069xts_dec_ret + jz L071xts_dec_ret pcmpgtd %xmm1,%xmm0 movl %eax,112(%esp) pshufd $19,%xmm0,%xmm2 @@ -1709,7 +1735,7 @@ L067xts_dec_done: pand %xmm3,%xmm2 pcmpgtd %xmm1,%xmm0 pxor %xmm2,%xmm1 -L070xts_dec_only_one_more: +L072xts_dec_only_one_more: pshufd $19,%xmm0,%xmm5 movdqa %xmm1,%xmm6 paddq %xmm1,%xmm1 @@ -1723,16 +1749,16 @@ L070xts_dec_only_one_more: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -L071dec1_loop_13: +L073dec1_loop_13: .byte 102,15,56,222,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz L071dec1_loop_13 + jnz L073dec1_loop_13 .byte 102,15,56,223,209 xorps %xmm5,%xmm2 movups %xmm2,(%edi) -L072xts_dec_steal: +L074xts_dec_steal: movzbl 16(%esi),%ecx movzbl (%edi),%edx leal 1(%esi),%esi @@ -1740,7 +1766,7 @@ L072xts_dec_steal: movb %dl,16(%edi) leal 1(%edi),%edi subl $1,%eax - jnz L072xts_dec_steal + jnz L074xts_dec_steal subl 112(%esp),%edi movl %ebp,%edx movl %ebx,%ecx @@ -1750,16 +1776,16 @@ L072xts_dec_steal: movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -L073dec1_loop_14: +L075dec1_loop_14: .byte 102,15,56,222,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz L073dec1_loop_14 + jnz L075dec1_loop_14 .byte 102,15,56,223,209 xorps %xmm6,%xmm2 movups %xmm2,(%edi) -L069xts_dec_ret: +L071xts_dec_ret: pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 pxor %xmm2,%xmm2 @@ -1798,7 +1824,7 @@ L_aes_hw_cbc_encrypt_begin: movl 32(%esp),%edx movl 36(%esp),%ebp testl %eax,%eax - jz L074cbc_abort + jz L076cbc_abort cmpl $0,40(%esp) xchgl %esp,%ebx movups (%ebp),%xmm7 @@ -1806,14 +1832,14 @@ L_aes_hw_cbc_encrypt_begin: movl %edx,%ebp movl %ebx,16(%esp) movl %ecx,%ebx - je L075cbc_decrypt + je L077cbc_decrypt movaps %xmm7,%xmm2 cmpl $16,%eax - jb L076cbc_enc_tail + jb L078cbc_enc_tail subl $16,%eax - jmp L077cbc_enc_loop + jmp L079cbc_enc_loop .align 4,0x90 -L077cbc_enc_loop: +L079cbc_enc_loop: movups (%esi),%xmm7 leal 16(%esi),%esi movups (%edx),%xmm0 @@ -1821,25 +1847,25 @@ L077cbc_enc_loop: xorps %xmm0,%xmm7 leal 32(%edx),%edx xorps %xmm7,%xmm2 -L078enc1_loop_15: +L080enc1_loop_15: .byte 102,15,56,220,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz L078enc1_loop_15 + jnz L080enc1_loop_15 .byte 102,15,56,221,209 movl %ebx,%ecx movl %ebp,%edx movups %xmm2,(%edi) leal 16(%edi),%edi subl $16,%eax - jnc L077cbc_enc_loop + jnc L079cbc_enc_loop addl $16,%eax - jnz L076cbc_enc_tail + jnz L078cbc_enc_tail movaps %xmm2,%xmm7 pxor %xmm2,%xmm2 - jmp L079cbc_ret -L076cbc_enc_tail: + jmp L081cbc_ret +L078cbc_enc_tail: movl %eax,%ecx .long 2767451785 movl $16,%ecx @@ -1850,20 +1876,20 @@ L076cbc_enc_tail: movl %ebx,%ecx movl %edi,%esi movl %ebp,%edx - jmp L077cbc_enc_loop + jmp L079cbc_enc_loop .align 4,0x90 -L075cbc_decrypt: +L077cbc_decrypt: cmpl $80,%eax - jbe L080cbc_dec_tail + jbe L082cbc_dec_tail movaps %xmm7,(%esp) subl $80,%eax - jmp L081cbc_dec_loop6_enter + jmp L083cbc_dec_loop6_enter .align 4,0x90 -L082cbc_dec_loop6: +L084cbc_dec_loop6: movaps %xmm0,(%esp) movups %xmm7,(%edi) leal 16(%edi),%edi -L081cbc_dec_loop6_enter: +L083cbc_dec_loop6_enter: movdqu (%esi),%xmm2 movdqu 16(%esi),%xmm3 movdqu 32(%esi),%xmm4 @@ -1893,28 +1919,28 @@ L081cbc_dec_loop6_enter: movups %xmm6,64(%edi) leal 80(%edi),%edi subl $96,%eax - ja L082cbc_dec_loop6 + ja L084cbc_dec_loop6 movaps %xmm7,%xmm2 movaps %xmm0,%xmm7 addl $80,%eax - jle L083cbc_dec_clear_tail_collected + jle L085cbc_dec_clear_tail_collected movups %xmm2,(%edi) leal 16(%edi),%edi -L080cbc_dec_tail: +L082cbc_dec_tail: movups (%esi),%xmm2 movaps %xmm2,%xmm6 cmpl $16,%eax - jbe L084cbc_dec_one + jbe L086cbc_dec_one movups 16(%esi),%xmm3 movaps %xmm3,%xmm5 cmpl $32,%eax - jbe L085cbc_dec_two + jbe L087cbc_dec_two movups 32(%esi),%xmm4 cmpl $48,%eax - jbe L086cbc_dec_three + jbe L088cbc_dec_three movups 48(%esi),%xmm5 cmpl $64,%eax - jbe L087cbc_dec_four + jbe L089cbc_dec_four movups 64(%esi),%xmm6 movaps %xmm7,(%esp) movups (%esi),%xmm2 @@ -1941,26 +1967,26 @@ L080cbc_dec_tail: movaps %xmm6,%xmm2 pxor %xmm6,%xmm6 subl $80,%eax - jmp L088cbc_dec_tail_collected + jmp L090cbc_dec_tail_collected .align 4,0x90 -L084cbc_dec_one: +L086cbc_dec_one: movups (%edx),%xmm0 movups 16(%edx),%xmm1 leal 32(%edx),%edx xorps %xmm0,%xmm2 -L089dec1_loop_16: +L091dec1_loop_16: .byte 102,15,56,222,209 decl %ecx movups (%edx),%xmm1 leal 16(%edx),%edx - jnz L089dec1_loop_16 + jnz L091dec1_loop_16 .byte 102,15,56,223,209 xorps %xmm7,%xmm2 movaps %xmm6,%xmm7 subl $16,%eax - jmp L088cbc_dec_tail_collected + jmp L090cbc_dec_tail_collected .align 4,0x90 -L085cbc_dec_two: +L087cbc_dec_two: call __aesni_decrypt2 xorps %xmm7,%xmm2 xorps %xmm6,%xmm3 @@ -1970,9 +1996,9 @@ L085cbc_dec_two: leal 16(%edi),%edi movaps %xmm5,%xmm7 subl $32,%eax - jmp L088cbc_dec_tail_collected + jmp L090cbc_dec_tail_collected .align 4,0x90 -L086cbc_dec_three: +L088cbc_dec_three: call __aesni_decrypt3 xorps %xmm7,%xmm2 xorps %xmm6,%xmm3 @@ -1985,9 +2011,9 @@ L086cbc_dec_three: leal 32(%edi),%edi movups 32(%esi),%xmm7 subl $48,%eax - jmp L088cbc_dec_tail_collected + jmp L090cbc_dec_tail_collected .align 4,0x90 -L087cbc_dec_four: +L089cbc_dec_four: call __aesni_decrypt4 movups 16(%esi),%xmm1 movups 32(%esi),%xmm0 @@ -2005,21 +2031,21 @@ L087cbc_dec_four: movaps %xmm5,%xmm2 pxor %xmm5,%xmm5 subl $64,%eax - jmp L088cbc_dec_tail_collected + jmp L090cbc_dec_tail_collected .align 4,0x90 -L083cbc_dec_clear_tail_collected: +L085cbc_dec_clear_tail_collected: pxor %xmm3,%xmm3 pxor %xmm4,%xmm4 pxor %xmm5,%xmm5 pxor %xmm6,%xmm6 -L088cbc_dec_tail_collected: +L090cbc_dec_tail_collected: andl $15,%eax - jnz L090cbc_dec_tail_partial + jnz L092cbc_dec_tail_partial movups %xmm2,(%edi) pxor %xmm0,%xmm0 - jmp L079cbc_ret + jmp L081cbc_ret .align 4,0x90 -L090cbc_dec_tail_partial: +L092cbc_dec_tail_partial: movaps %xmm2,(%esp) pxor %xmm0,%xmm0 movl $16,%ecx @@ -2027,14 +2053,14 @@ L090cbc_dec_tail_partial: subl %eax,%ecx .long 2767451785 movdqa %xmm2,(%esp) -L079cbc_ret: +L081cbc_ret: movl 16(%esp),%esp movl 36(%esp),%ebp pxor %xmm2,%xmm2 pxor %xmm1,%xmm1 movups %xmm7,(%ebp) pxor %xmm7,%xmm7 -L074cbc_abort: +L076cbc_abort: popl %edi popl %esi popl %ebx @@ -2046,13 +2072,13 @@ __aesni_set_encrypt_key: pushl %ebp pushl %ebx testl %eax,%eax - jz L091bad_pointer + jz L093bad_pointer testl %edx,%edx - jz L091bad_pointer - call L092pic -L092pic: + jz L093bad_pointer + call L094pic +L094pic: popl %ebx - leal Lkey_const-L092pic(%ebx),%ebx + leal Lkey_const-L094pic(%ebx),%ebx movl L_OPENSSL_ia32cap_P$non_lazy_ptr-Lkey_const(%ebx),%ebp movups (%eax),%xmm0 xorps %xmm4,%xmm4 @@ -2060,45 +2086,45 @@ L092pic: leal 16(%edx),%edx andl $268437504,%ebp cmpl $256,%ecx - je L09314rounds + je L09514rounds cmpl $192,%ecx - je L09412rounds + je L09612rounds cmpl $128,%ecx - jne L095bad_keybits + jne L097bad_keybits .align 4,0x90 -L09610rounds: +L09810rounds: cmpl $268435456,%ebp - je L09710rounds_alt + je L09910rounds_alt movl $9,%ecx movups %xmm0,-16(%edx) .byte 102,15,58,223,200,1 - call L098key_128_cold + call L100key_128_cold .byte 102,15,58,223,200,2 - call L099key_128 + call L101key_128 .byte 102,15,58,223,200,4 - call L099key_128 + call L101key_128 .byte 102,15,58,223,200,8 - call L099key_128 + call L101key_128 .byte 102,15,58,223,200,16 - call L099key_128 + call L101key_128 .byte 102,15,58,223,200,32 - call L099key_128 + call L101key_128 .byte 102,15,58,223,200,64 - call L099key_128 + call L101key_128 .byte 102,15,58,223,200,128 - call L099key_128 + call L101key_128 .byte 102,15,58,223,200,27 - call L099key_128 + call L101key_128 .byte 102,15,58,223,200,54 - call L099key_128 + call L101key_128 movups %xmm0,(%edx) movl %ecx,80(%edx) - jmp L100good_key + jmp L102good_key .align 4,0x90 -L099key_128: +L101key_128: movups %xmm0,(%edx) leal 16(%edx),%edx -L098key_128_cold: +L100key_128_cold: shufps $16,%xmm0,%xmm4 xorps %xmm4,%xmm0 shufps $140,%xmm0,%xmm4 @@ -2107,13 +2133,13 @@ L098key_128_cold: xorps %xmm1,%xmm0 ret .align 4,0x90 -L09710rounds_alt: +L09910rounds_alt: movdqa (%ebx),%xmm5 movl $8,%ecx movdqa 32(%ebx),%xmm4 movdqa %xmm0,%xmm2 movdqu %xmm0,-16(%edx) -L101loop_key128: +L103loop_key128: .byte 102,15,56,0,197 .byte 102,15,56,221,196 pslld $1,%xmm4 @@ -2129,7 +2155,7 @@ L101loop_key128: movdqu %xmm0,-16(%edx) movdqa %xmm0,%xmm2 decl %ecx - jnz L101loop_key128 + jnz L103loop_key128 movdqa 48(%ebx),%xmm4 .byte 102,15,56,0,197 .byte 102,15,56,221,196 @@ -2157,41 +2183,41 @@ L101loop_key128: movdqu %xmm0,16(%edx) movl $9,%ecx movl %ecx,96(%edx) - jmp L100good_key + jmp L102good_key .align 4,0x90 -L09412rounds: +L09612rounds: movq 16(%eax),%xmm2 cmpl $268435456,%ebp - je L10212rounds_alt + je L10412rounds_alt movl $11,%ecx movups %xmm0,-16(%edx) .byte 102,15,58,223,202,1 - call L103key_192a_cold + call L105key_192a_cold .byte 102,15,58,223,202,2 - call L104key_192b + call L106key_192b .byte 102,15,58,223,202,4 - call L105key_192a + call L107key_192a .byte 102,15,58,223,202,8 - call L104key_192b + call L106key_192b .byte 102,15,58,223,202,16 - call L105key_192a + call L107key_192a .byte 102,15,58,223,202,32 - call L104key_192b + call L106key_192b .byte 102,15,58,223,202,64 - call L105key_192a + call L107key_192a .byte 102,15,58,223,202,128 - call L104key_192b + call L106key_192b movups %xmm0,(%edx) movl %ecx,48(%edx) - jmp L100good_key + jmp L102good_key .align 4,0x90 -L105key_192a: +L107key_192a: movups %xmm0,(%edx) leal 16(%edx),%edx .align 4,0x90 -L103key_192a_cold: +L105key_192a_cold: movaps %xmm2,%xmm5 -L106key_192b_warm: +L108key_192b_warm: shufps $16,%xmm0,%xmm4 movdqa %xmm2,%xmm3 xorps %xmm4,%xmm0 @@ -2205,21 +2231,21 @@ L106key_192b_warm: pxor %xmm3,%xmm2 ret .align 4,0x90 -L104key_192b: +L106key_192b: movaps %xmm0,%xmm3 shufps $68,%xmm0,%xmm5 movups %xmm5,(%edx) shufps $78,%xmm2,%xmm3 movups %xmm3,16(%edx) leal 32(%edx),%edx - jmp L106key_192b_warm + jmp L108key_192b_warm .align 4,0x90 -L10212rounds_alt: +L10412rounds_alt: movdqa 16(%ebx),%xmm5 movdqa 32(%ebx),%xmm4 movl $8,%ecx movdqu %xmm0,-16(%edx) -L107loop_key192: +L109loop_key192: movq %xmm2,(%edx) movdqa %xmm2,%xmm1 .byte 102,15,56,0,213 @@ -2241,54 +2267,54 @@ L107loop_key192: pxor %xmm3,%xmm2 movdqu %xmm0,-16(%edx) decl %ecx - jnz L107loop_key192 + jnz L109loop_key192 movl $11,%ecx movl %ecx,32(%edx) - jmp L100good_key + jmp L102good_key .align 4,0x90 -L09314rounds: +L09514rounds: movups 16(%eax),%xmm2 leal 16(%edx),%edx cmpl $268435456,%ebp - je L10814rounds_alt + je L11014rounds_alt movl $13,%ecx movups %xmm0,-32(%edx) movups %xmm2,-16(%edx) .byte 102,15,58,223,202,1 - call L109key_256a_cold + call L111key_256a_cold .byte 102,15,58,223,200,1 - call L110key_256b + call L112key_256b .byte 102,15,58,223,202,2 - call L111key_256a + call L113key_256a .byte 102,15,58,223,200,2 - call L110key_256b + call L112key_256b .byte 102,15,58,223,202,4 - call L111key_256a + call L113key_256a .byte 102,15,58,223,200,4 - call L110key_256b + call L112key_256b .byte 102,15,58,223,202,8 - call L111key_256a + call L113key_256a .byte 102,15,58,223,200,8 - call L110key_256b + call L112key_256b .byte 102,15,58,223,202,16 - call L111key_256a + call L113key_256a .byte 102,15,58,223,200,16 - call L110key_256b + call L112key_256b .byte 102,15,58,223,202,32 - call L111key_256a + call L113key_256a .byte 102,15,58,223,200,32 - call L110key_256b + call L112key_256b .byte 102,15,58,223,202,64 - call L111key_256a + call L113key_256a movups %xmm0,(%edx) movl %ecx,16(%edx) xorl %eax,%eax - jmp L100good_key + jmp L102good_key .align 4,0x90 -L111key_256a: +L113key_256a: movups %xmm2,(%edx) leal 16(%edx),%edx -L109key_256a_cold: +L111key_256a_cold: shufps $16,%xmm0,%xmm4 xorps %xmm4,%xmm0 shufps $140,%xmm0,%xmm4 @@ -2297,7 +2323,7 @@ L109key_256a_cold: xorps %xmm1,%xmm0 ret .align 4,0x90 -L110key_256b: +L112key_256b: movups %xmm0,(%edx) leal 16(%edx),%edx shufps $16,%xmm2,%xmm4 @@ -2308,14 +2334,14 @@ L110key_256b: xorps %xmm1,%xmm2 ret .align 4,0x90 -L10814rounds_alt: +L11014rounds_alt: movdqa (%ebx),%xmm5 movdqa 32(%ebx),%xmm4 movl $7,%ecx movdqu %xmm0,-32(%edx) movdqa %xmm2,%xmm1 movdqu %xmm2,-16(%edx) -L112loop_key256: +L114loop_key256: .byte 102,15,56,0,213 .byte 102,15,56,221,212 movdqa %xmm0,%xmm3 @@ -2329,7 +2355,7 @@ L112loop_key256: pxor %xmm2,%xmm0 movdqu %xmm0,(%edx) decl %ecx - jz L113done_key256 + jz L115done_key256 pshufd $255,%xmm0,%xmm2 pxor %xmm3,%xmm3 .byte 102,15,56,221,211 @@ -2344,11 +2370,11 @@ L112loop_key256: movdqu %xmm2,16(%edx) leal 32(%edx),%edx movdqa %xmm2,%xmm1 - jmp L112loop_key256 -L113done_key256: + jmp L114loop_key256 +L115done_key256: movl $13,%ecx movl %ecx,16(%edx) -L100good_key: +L102good_key: pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 pxor %xmm2,%xmm2 @@ -2360,13 +2386,13 @@ L100good_key: popl %ebp ret .align 2,0x90 -L091bad_pointer: +L093bad_pointer: movl $-1,%eax popl %ebx popl %ebp ret .align 2,0x90 -L095bad_keybits: +L097bad_keybits: pxor %xmm0,%xmm0 movl $-2,%eax popl %ebx @@ -2377,6 +2403,18 @@ L095bad_keybits: .align 4 _aes_hw_set_encrypt_key: L_aes_hw_set_encrypt_key_begin: +#ifndef NDEBUG + pushl %ebx + pushl %edx + call L116pic +L116pic: + popl %ebx + leal _BORINGSSL_function_hit+3-L116pic(%ebx),%ebx + movl $1,%edx + movb %dl,(%ebx) + popl %edx + popl %ebx +#endif movl 4(%esp),%eax movl 8(%esp),%ecx movl 12(%esp),%edx @@ -2394,7 +2432,7 @@ L_aes_hw_set_decrypt_key_begin: movl 12(%esp),%edx shll $4,%ecx testl %eax,%eax - jnz L114dec_key_ret + jnz L117dec_key_ret leal 16(%edx,%ecx,1),%eax movups (%edx),%xmm0 movups (%eax),%xmm1 @@ -2402,7 +2440,7 @@ L_aes_hw_set_decrypt_key_begin: movups %xmm1,(%edx) leal 16(%edx),%edx leal -16(%eax),%eax -L115dec_key_inverse: +L118dec_key_inverse: movups (%edx),%xmm0 movups (%eax),%xmm1 .byte 102,15,56,219,192 @@ -2412,14 +2450,14 @@ L115dec_key_inverse: movups %xmm0,16(%eax) movups %xmm1,-16(%edx) cmpl %edx,%eax - ja L115dec_key_inverse + ja L118dec_key_inverse movups (%edx),%xmm0 .byte 102,15,56,219,192 movups %xmm0,(%edx) pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 xorl %eax,%eax -L114dec_key_ret: +L117dec_key_ret: ret .align 6,0x90 Lkey_const: diff --git a/third_party/boringssl/kit/mac-x86/crypto/fipsmodule/ghash-ssse3-x86.S b/third_party/boringssl/kit/mac-x86/crypto/fipsmodule/ghash-ssse3-x86.S new file mode 100644 index 00000000..f059e283 --- /dev/null +++ b/third_party/boringssl/kit/mac-x86/crypto/fipsmodule/ghash-ssse3-x86.S @@ -0,0 +1,289 @@ +# This file is generated from a similarly-named Perl script in the BoringSSL +# source tree. Do not edit by hand. + +#if defined(__i386__) +#if defined(BORINGSSL_PREFIX) +#include +#endif +.text +.globl _gcm_gmult_ssse3 +.private_extern _gcm_gmult_ssse3 +.align 4 +_gcm_gmult_ssse3: +L_gcm_gmult_ssse3_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 20(%esp),%edi + movl 24(%esp),%esi + movdqu (%edi),%xmm0 + call L000pic_point +L000pic_point: + popl %eax + movdqa Lreverse_bytes-L000pic_point(%eax),%xmm7 + movdqa Llow4_mask-L000pic_point(%eax),%xmm2 +.byte 102,15,56,0,199 + movdqa %xmm2,%xmm1 + pandn %xmm0,%xmm1 + psrld $4,%xmm1 + pand %xmm2,%xmm0 + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + movl $5,%eax +L001loop_row_1: + movdqa (%esi),%xmm4 + leal 16(%esi),%esi + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + pxor %xmm5,%xmm2 + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + subl $1,%eax + jnz L001loop_row_1 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movl $5,%eax +L002loop_row_2: + movdqa (%esi),%xmm4 + leal 16(%esi),%esi + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + pxor %xmm5,%xmm2 + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + subl $1,%eax + jnz L002loop_row_2 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movl $6,%eax +L003loop_row_3: + movdqa (%esi),%xmm4 + leal 16(%esi),%esi + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + pxor %xmm5,%xmm2 + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + subl $1,%eax + jnz L003loop_row_3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 +.byte 102,15,56,0,215 + movdqu %xmm2,(%edi) + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + pxor %xmm4,%xmm4 + pxor %xmm5,%xmm5 + pxor %xmm6,%xmm6 + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.globl _gcm_ghash_ssse3 +.private_extern _gcm_ghash_ssse3 +.align 4 +_gcm_ghash_ssse3: +L_gcm_ghash_ssse3_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 20(%esp),%edi + movl 24(%esp),%esi + movl 28(%esp),%edx + movl 32(%esp),%ecx + movdqu (%edi),%xmm0 + call L004pic_point +L004pic_point: + popl %ebx + movdqa Lreverse_bytes-L004pic_point(%ebx),%xmm7 + andl $-16,%ecx +.byte 102,15,56,0,199 + pxor %xmm3,%xmm3 +L005loop_ghash: + movdqa Llow4_mask-L004pic_point(%ebx),%xmm2 + movdqu (%edx),%xmm1 +.byte 102,15,56,0,207 + pxor %xmm1,%xmm0 + movdqa %xmm2,%xmm1 + pandn %xmm0,%xmm1 + psrld $4,%xmm1 + pand %xmm2,%xmm0 + pxor %xmm2,%xmm2 + movl $5,%eax +L006loop_row_4: + movdqa (%esi),%xmm4 + leal 16(%esi),%esi + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + pxor %xmm5,%xmm2 + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + subl $1,%eax + jnz L006loop_row_4 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movl $5,%eax +L007loop_row_5: + movdqa (%esi),%xmm4 + leal 16(%esi),%esi + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + pxor %xmm5,%xmm2 + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + subl $1,%eax + jnz L007loop_row_5 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movl $6,%eax +L008loop_row_6: + movdqa (%esi),%xmm4 + leal 16(%esi),%esi + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + pxor %xmm5,%xmm2 + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + subl $1,%eax + jnz L008loop_row_6 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movdqa %xmm2,%xmm0 + leal -256(%esi),%esi + leal 16(%edx),%edx + subl $16,%ecx + jnz L005loop_ghash +.byte 102,15,56,0,199 + movdqu %xmm0,(%edi) + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + pxor %xmm4,%xmm4 + pxor %xmm5,%xmm5 + pxor %xmm6,%xmm6 + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.align 4,0x90 +Lreverse_bytes: +.byte 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 +.align 4,0x90 +Llow4_mask: +.long 252645135,252645135,252645135,252645135 +#endif diff --git a/third_party/boringssl/kit/mac-x86/crypto/fipsmodule/vpaes-x86.S b/third_party/boringssl/kit/mac-x86/crypto/fipsmodule/vpaes-x86.S index c47a217d..22043e2a 100644 --- a/third_party/boringssl/kit/mac-x86/crypto/fipsmodule/vpaes-x86.S +++ b/third_party/boringssl/kit/mac-x86/crypto/fipsmodule/vpaes-x86.S @@ -6,6 +6,8 @@ #include #endif .text +#ifndef NDEBUG +#endif .align 6,0x90 L_vpaes_consts: .long 218628480,235210255,168496130,67568393 @@ -466,6 +468,18 @@ L_vpaes_set_encrypt_key_begin: pushl %ebx pushl %esi pushl %edi +#ifndef NDEBUG + pushl %ebx + pushl %edx + call L016pic +L016pic: + popl %ebx + leal _BORINGSSL_function_hit+5-L016pic(%ebx),%ebx + movl $1,%edx + movb %dl,(%ebx) + popl %edx + popl %ebx +#endif movl 20(%esp),%esi leal -56(%esp),%ebx movl 24(%esp),%eax @@ -479,9 +493,9 @@ L_vpaes_set_encrypt_key_begin: movl %ebx,240(%edx) movl $48,%ecx movl $0,%edi - leal L_vpaes_consts+0x30-L016pic_point,%ebp + leal L_vpaes_consts+0x30-L017pic_point,%ebp call __vpaes_schedule_core -L016pic_point: +L017pic_point: movl 48(%esp),%esp xorl %eax,%eax popl %edi @@ -516,9 +530,9 @@ L_vpaes_set_decrypt_key_begin: shrl $1,%ecx andl $32,%ecx xorl $32,%ecx - leal L_vpaes_consts+0x30-L017pic_point,%ebp + leal L_vpaes_consts+0x30-L018pic_point,%ebp call __vpaes_schedule_core -L017pic_point: +L018pic_point: movl 48(%esp),%esp xorl %eax,%eax popl %edi @@ -535,9 +549,21 @@ L_vpaes_encrypt_begin: pushl %ebx pushl %esi pushl %edi - leal L_vpaes_consts+0x30-L018pic_point,%ebp +#ifndef NDEBUG + pushl %ebx + pushl %edx + call L019pic +L019pic: + popl %ebx + leal _BORINGSSL_function_hit+4-L019pic(%ebx),%ebx + movl $1,%edx + movb %dl,(%ebx) + popl %edx + popl %ebx +#endif + leal L_vpaes_consts+0x30-L020pic_point,%ebp call __vpaes_preheat -L018pic_point: +L020pic_point: movl 20(%esp),%esi leal -56(%esp),%ebx movl 24(%esp),%edi @@ -563,9 +589,9 @@ L_vpaes_decrypt_begin: pushl %ebx pushl %esi pushl %edi - leal L_vpaes_consts+0x30-L019pic_point,%ebp + leal L_vpaes_consts+0x30-L021pic_point,%ebp call __vpaes_preheat -L019pic_point: +L021pic_point: movl 20(%esp),%esi leal -56(%esp),%ebx movl 24(%esp),%edi @@ -596,7 +622,7 @@ L_vpaes_cbc_encrypt_begin: movl 28(%esp),%eax movl 32(%esp),%edx subl $16,%eax - jc L020cbc_abort + jc L022cbc_abort leal -56(%esp),%ebx movl 36(%esp),%ebp andl $-16,%ebx @@ -609,14 +635,14 @@ L_vpaes_cbc_encrypt_begin: movl %edx,4(%esp) movl %ebp,8(%esp) movl %eax,%edi - leal L_vpaes_consts+0x30-L021pic_point,%ebp + leal L_vpaes_consts+0x30-L023pic_point,%ebp call __vpaes_preheat -L021pic_point: +L023pic_point: cmpl $0,%ecx - je L022cbc_dec_loop - jmp L023cbc_enc_loop + je L024cbc_dec_loop + jmp L025cbc_enc_loop .align 4,0x90 -L023cbc_enc_loop: +L025cbc_enc_loop: movdqu (%esi),%xmm0 pxor %xmm1,%xmm0 call __vpaes_encrypt_core @@ -626,10 +652,10 @@ L023cbc_enc_loop: movdqu %xmm0,(%ebx,%esi,1) leal 16(%esi),%esi subl $16,%edi - jnc L023cbc_enc_loop - jmp L024cbc_done + jnc L025cbc_enc_loop + jmp L026cbc_done .align 4,0x90 -L022cbc_dec_loop: +L024cbc_dec_loop: movdqu (%esi),%xmm0 movdqa %xmm1,16(%esp) movdqa %xmm0,32(%esp) @@ -641,12 +667,12 @@ L022cbc_dec_loop: movdqu %xmm0,(%ebx,%esi,1) leal 16(%esi),%esi subl $16,%edi - jnc L022cbc_dec_loop -L024cbc_done: + jnc L024cbc_dec_loop +L026cbc_done: movl 8(%esp),%ebx movl 48(%esp),%esp movdqu %xmm1,(%ebx) -L020cbc_abort: +L022cbc_abort: popl %edi popl %esi popl %ebx diff --git a/third_party/boringssl/kit/mac-x86/crypto/test/trampoline-x86.S b/third_party/boringssl/kit/mac-x86/crypto/test/trampoline-x86.S new file mode 100644 index 00000000..601f2f01 --- /dev/null +++ b/third_party/boringssl/kit/mac-x86/crypto/test/trampoline-x86.S @@ -0,0 +1,169 @@ +# This file is generated from a similarly-named Perl script in the BoringSSL +# source tree. Do not edit by hand. + +#if defined(__i386__) +#if defined(BORINGSSL_PREFIX) +#include +#endif +.text +.globl _abi_test_trampoline +.private_extern _abi_test_trampoline +.align 4 +_abi_test_trampoline: +L_abi_test_trampoline_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 24(%esp),%ecx + movl (%ecx),%esi + movl 4(%ecx),%edi + movl 8(%ecx),%ebx + movl 12(%ecx),%ebp + subl $44,%esp + movl 72(%esp),%eax + xorl %ecx,%ecx +L000loop: + cmpl 76(%esp),%ecx + jae L001loop_done + movl (%eax,%ecx,4),%edx + movl %edx,(%esp,%ecx,4) + addl $1,%ecx + jmp L000loop +L001loop_done: + call *64(%esp) + addl $44,%esp + movl 24(%esp),%ecx + movl %esi,(%ecx) + movl %edi,4(%ecx) + movl %ebx,8(%ecx) + movl %ebp,12(%ecx) + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.globl _abi_test_get_and_clear_direction_flag +.private_extern _abi_test_get_and_clear_direction_flag +.align 4 +_abi_test_get_and_clear_direction_flag: +L_abi_test_get_and_clear_direction_flag_begin: + pushfl + popl %eax + andl $1024,%eax + shrl $10,%eax + cld + ret +.globl _abi_test_set_direction_flag +.private_extern _abi_test_set_direction_flag +.align 4 +_abi_test_set_direction_flag: +L_abi_test_set_direction_flag_begin: + std + ret +.globl _abi_test_clobber_eax +.private_extern _abi_test_clobber_eax +.align 4 +_abi_test_clobber_eax: +L_abi_test_clobber_eax_begin: + xorl %eax,%eax + ret +.globl _abi_test_clobber_ebx +.private_extern _abi_test_clobber_ebx +.align 4 +_abi_test_clobber_ebx: +L_abi_test_clobber_ebx_begin: + xorl %ebx,%ebx + ret +.globl _abi_test_clobber_ecx +.private_extern _abi_test_clobber_ecx +.align 4 +_abi_test_clobber_ecx: +L_abi_test_clobber_ecx_begin: + xorl %ecx,%ecx + ret +.globl _abi_test_clobber_edx +.private_extern _abi_test_clobber_edx +.align 4 +_abi_test_clobber_edx: +L_abi_test_clobber_edx_begin: + xorl %edx,%edx + ret +.globl _abi_test_clobber_edi +.private_extern _abi_test_clobber_edi +.align 4 +_abi_test_clobber_edi: +L_abi_test_clobber_edi_begin: + xorl %edi,%edi + ret +.globl _abi_test_clobber_esi +.private_extern _abi_test_clobber_esi +.align 4 +_abi_test_clobber_esi: +L_abi_test_clobber_esi_begin: + xorl %esi,%esi + ret +.globl _abi_test_clobber_ebp +.private_extern _abi_test_clobber_ebp +.align 4 +_abi_test_clobber_ebp: +L_abi_test_clobber_ebp_begin: + xorl %ebp,%ebp + ret +.globl _abi_test_clobber_xmm0 +.private_extern _abi_test_clobber_xmm0 +.align 4 +_abi_test_clobber_xmm0: +L_abi_test_clobber_xmm0_begin: + pxor %xmm0,%xmm0 + ret +.globl _abi_test_clobber_xmm1 +.private_extern _abi_test_clobber_xmm1 +.align 4 +_abi_test_clobber_xmm1: +L_abi_test_clobber_xmm1_begin: + pxor %xmm1,%xmm1 + ret +.globl _abi_test_clobber_xmm2 +.private_extern _abi_test_clobber_xmm2 +.align 4 +_abi_test_clobber_xmm2: +L_abi_test_clobber_xmm2_begin: + pxor %xmm2,%xmm2 + ret +.globl _abi_test_clobber_xmm3 +.private_extern _abi_test_clobber_xmm3 +.align 4 +_abi_test_clobber_xmm3: +L_abi_test_clobber_xmm3_begin: + pxor %xmm3,%xmm3 + ret +.globl _abi_test_clobber_xmm4 +.private_extern _abi_test_clobber_xmm4 +.align 4 +_abi_test_clobber_xmm4: +L_abi_test_clobber_xmm4_begin: + pxor %xmm4,%xmm4 + ret +.globl _abi_test_clobber_xmm5 +.private_extern _abi_test_clobber_xmm5 +.align 4 +_abi_test_clobber_xmm5: +L_abi_test_clobber_xmm5_begin: + pxor %xmm5,%xmm5 + ret +.globl _abi_test_clobber_xmm6 +.private_extern _abi_test_clobber_xmm6 +.align 4 +_abi_test_clobber_xmm6: +L_abi_test_clobber_xmm6_begin: + pxor %xmm6,%xmm6 + ret +.globl _abi_test_clobber_xmm7 +.private_extern _abi_test_clobber_xmm7 +.align 4 +_abi_test_clobber_xmm7: +L_abi_test_clobber_xmm7_begin: + pxor %xmm7,%xmm7 + ret +#endif diff --git a/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.S b/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.S index b7902ca3..9fb4bef1 100644 --- a/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.S +++ b/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.S @@ -556,6 +556,12 @@ L$handle_ctr32_2: .p2align 5 _aesni_gcm_encrypt: +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS + + movb $1,_BORINGSSL_function_hit+2(%rip) +#endif +#endif xorq %r10,%r10 diff --git a/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/aesni-x86_64.S b/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/aesni-x86_64.S index 64bdc418..5e125967 100644 --- a/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/aesni-x86_64.S +++ b/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/aesni-x86_64.S @@ -19,6 +19,12 @@ .p2align 4 _aes_hw_encrypt: +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS + + movb $1,_BORINGSSL_function_hit+1(%rip) +#endif +#endif movups (%rdi),%xmm2 movl 240(%rdx),%eax movups (%rdx),%xmm0 @@ -873,174 +879,17 @@ L$ecb_ret: .byte 0xf3,0xc3 -.globl _aes_hw_ccm64_encrypt_blocks -.private_extern _aes_hw_ccm64_encrypt_blocks - -.p2align 4 -_aes_hw_ccm64_encrypt_blocks: - movl 240(%rcx),%eax - movdqu (%r8),%xmm6 - movdqa L$increment64(%rip),%xmm9 - movdqa L$bswap_mask(%rip),%xmm7 - - shll $4,%eax - movl $16,%r10d - leaq 0(%rcx),%r11 - movdqu (%r9),%xmm3 - movdqa %xmm6,%xmm2 - leaq 32(%rcx,%rax,1),%rcx -.byte 102,15,56,0,247 - subq %rax,%r10 - jmp L$ccm64_enc_outer -.p2align 4 -L$ccm64_enc_outer: - movups (%r11),%xmm0 - movq %r10,%rax - movups (%rdi),%xmm8 - - xorps %xmm0,%xmm2 - movups 16(%r11),%xmm1 - xorps %xmm8,%xmm0 - xorps %xmm0,%xmm3 - movups 32(%r11),%xmm0 - -L$ccm64_enc2_loop: -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 - movups (%rcx,%rax,1),%xmm1 - addq $32,%rax -.byte 102,15,56,220,208 -.byte 102,15,56,220,216 - movups -16(%rcx,%rax,1),%xmm0 - jnz L$ccm64_enc2_loop -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 - paddq %xmm9,%xmm6 - decq %rdx -.byte 102,15,56,221,208 -.byte 102,15,56,221,216 - - leaq 16(%rdi),%rdi - xorps %xmm2,%xmm8 - movdqa %xmm6,%xmm2 - movups %xmm8,(%rsi) -.byte 102,15,56,0,215 - leaq 16(%rsi),%rsi - jnz L$ccm64_enc_outer - - pxor %xmm0,%xmm0 - pxor %xmm1,%xmm1 - pxor %xmm2,%xmm2 - movups %xmm3,(%r9) - pxor %xmm3,%xmm3 - pxor %xmm8,%xmm8 - pxor %xmm6,%xmm6 - .byte 0xf3,0xc3 - -.globl _aes_hw_ccm64_decrypt_blocks -.private_extern _aes_hw_ccm64_decrypt_blocks - -.p2align 4 -_aes_hw_ccm64_decrypt_blocks: - movl 240(%rcx),%eax - movups (%r8),%xmm6 - movdqu (%r9),%xmm3 - movdqa L$increment64(%rip),%xmm9 - movdqa L$bswap_mask(%rip),%xmm7 - - movaps %xmm6,%xmm2 - movl %eax,%r10d - movq %rcx,%r11 -.byte 102,15,56,0,247 - movups (%rcx),%xmm0 - movups 16(%rcx),%xmm1 - leaq 32(%rcx),%rcx - xorps %xmm0,%xmm2 -L$oop_enc1_5: -.byte 102,15,56,220,209 - decl %eax - movups (%rcx),%xmm1 - leaq 16(%rcx),%rcx - jnz L$oop_enc1_5 -.byte 102,15,56,221,209 - shll $4,%r10d - movl $16,%eax - movups (%rdi),%xmm8 - paddq %xmm9,%xmm6 - leaq 16(%rdi),%rdi - subq %r10,%rax - leaq 32(%r11,%r10,1),%rcx - movq %rax,%r10 - jmp L$ccm64_dec_outer -.p2align 4 -L$ccm64_dec_outer: - xorps %xmm2,%xmm8 - movdqa %xmm6,%xmm2 - movups %xmm8,(%rsi) - leaq 16(%rsi),%rsi -.byte 102,15,56,0,215 - - subq $1,%rdx - jz L$ccm64_dec_break - - movups (%r11),%xmm0 - movq %r10,%rax - movups 16(%r11),%xmm1 - xorps %xmm0,%xmm8 - xorps %xmm0,%xmm2 - xorps %xmm8,%xmm3 - movups 32(%r11),%xmm0 - jmp L$ccm64_dec2_loop -.p2align 4 -L$ccm64_dec2_loop: -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 - movups (%rcx,%rax,1),%xmm1 - addq $32,%rax -.byte 102,15,56,220,208 -.byte 102,15,56,220,216 - movups -16(%rcx,%rax,1),%xmm0 - jnz L$ccm64_dec2_loop - movups (%rdi),%xmm8 - paddq %xmm9,%xmm6 -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 -.byte 102,15,56,221,208 -.byte 102,15,56,221,216 - leaq 16(%rdi),%rdi - jmp L$ccm64_dec_outer - -.p2align 4 -L$ccm64_dec_break: - - movl 240(%r11),%eax - movups (%r11),%xmm0 - movups 16(%r11),%xmm1 - xorps %xmm0,%xmm8 - leaq 32(%r11),%r11 - xorps %xmm8,%xmm3 -L$oop_enc1_6: -.byte 102,15,56,220,217 - decl %eax - movups (%r11),%xmm1 - leaq 16(%r11),%r11 - jnz L$oop_enc1_6 -.byte 102,15,56,221,217 - pxor %xmm0,%xmm0 - pxor %xmm1,%xmm1 - pxor %xmm2,%xmm2 - movups %xmm3,(%r9) - pxor %xmm3,%xmm3 - pxor %xmm8,%xmm8 - pxor %xmm6,%xmm6 - .byte 0xf3,0xc3 - .globl _aes_hw_ctr32_encrypt_blocks .private_extern _aes_hw_ctr32_encrypt_blocks .p2align 4 _aes_hw_ctr32_encrypt_blocks: +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS + movb $1,_BORINGSSL_function_hit(%rip) +#endif +#endif cmpq $1,%rdx jne L$ctr32_bulk @@ -1053,12 +902,12 @@ _aes_hw_ctr32_encrypt_blocks: movups 16(%rcx),%xmm1 leaq 32(%rcx),%rcx xorps %xmm0,%xmm2 -L$oop_enc1_7: +L$oop_enc1_5: .byte 102,15,56,220,209 decl %edx movups (%rcx),%xmm1 leaq 16(%rcx),%rcx - jnz L$oop_enc1_7 + jnz L$oop_enc1_5 .byte 102,15,56,221,209 pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 @@ -1615,1829 +1464,6 @@ L$ctr32_epilogue: .byte 0xf3,0xc3 -.globl _aes_hw_xts_encrypt -.private_extern _aes_hw_xts_encrypt - -.p2align 4 -_aes_hw_xts_encrypt: - - leaq (%rsp),%r11 - - pushq %rbp - - subq $112,%rsp - andq $-16,%rsp - movups (%r9),%xmm2 - movl 240(%r8),%eax - movl 240(%rcx),%r10d - movups (%r8),%xmm0 - movups 16(%r8),%xmm1 - leaq 32(%r8),%r8 - xorps %xmm0,%xmm2 -L$oop_enc1_8: -.byte 102,15,56,220,209 - decl %eax - movups (%r8),%xmm1 - leaq 16(%r8),%r8 - jnz L$oop_enc1_8 -.byte 102,15,56,221,209 - movups (%rcx),%xmm0 - movq %rcx,%rbp - movl %r10d,%eax - shll $4,%r10d - movq %rdx,%r9 - andq $-16,%rdx - - movups 16(%rcx,%r10,1),%xmm1 - - movdqa L$xts_magic(%rip),%xmm8 - movdqa %xmm2,%xmm15 - pshufd $0x5f,%xmm2,%xmm9 - pxor %xmm0,%xmm1 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 - movdqa %xmm15,%xmm10 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 - pxor %xmm0,%xmm10 - pxor %xmm14,%xmm15 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 - movdqa %xmm15,%xmm11 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 - pxor %xmm0,%xmm11 - pxor %xmm14,%xmm15 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 - movdqa %xmm15,%xmm12 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 - pxor %xmm0,%xmm12 - pxor %xmm14,%xmm15 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 - movdqa %xmm15,%xmm13 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 - pxor %xmm0,%xmm13 - pxor %xmm14,%xmm15 - movdqa %xmm15,%xmm14 - psrad $31,%xmm9 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm9 - pxor %xmm0,%xmm14 - pxor %xmm9,%xmm15 - movaps %xmm1,96(%rsp) - - subq $96,%rdx - jc L$xts_enc_short - - movl $16+96,%eax - leaq 32(%rbp,%r10,1),%rcx - subq %r10,%rax - movups 16(%rbp),%xmm1 - movq %rax,%r10 - leaq L$xts_magic(%rip),%r8 - jmp L$xts_enc_grandloop - -.p2align 5 -L$xts_enc_grandloop: - movdqu 0(%rdi),%xmm2 - movdqa %xmm0,%xmm8 - movdqu 16(%rdi),%xmm3 - pxor %xmm10,%xmm2 - movdqu 32(%rdi),%xmm4 - pxor %xmm11,%xmm3 -.byte 102,15,56,220,209 - movdqu 48(%rdi),%xmm5 - pxor %xmm12,%xmm4 -.byte 102,15,56,220,217 - movdqu 64(%rdi),%xmm6 - pxor %xmm13,%xmm5 -.byte 102,15,56,220,225 - movdqu 80(%rdi),%xmm7 - pxor %xmm15,%xmm8 - movdqa 96(%rsp),%xmm9 - pxor %xmm14,%xmm6 -.byte 102,15,56,220,233 - movups 32(%rbp),%xmm0 - leaq 96(%rdi),%rdi - pxor %xmm8,%xmm7 - - pxor %xmm9,%xmm10 -.byte 102,15,56,220,241 - pxor %xmm9,%xmm11 - movdqa %xmm10,0(%rsp) -.byte 102,15,56,220,249 - movups 48(%rbp),%xmm1 - pxor %xmm9,%xmm12 - -.byte 102,15,56,220,208 - pxor %xmm9,%xmm13 - movdqa %xmm11,16(%rsp) -.byte 102,15,56,220,216 - pxor %xmm9,%xmm14 - movdqa %xmm12,32(%rsp) -.byte 102,15,56,220,224 -.byte 102,15,56,220,232 - pxor %xmm9,%xmm8 - movdqa %xmm14,64(%rsp) -.byte 102,15,56,220,240 -.byte 102,15,56,220,248 - movups 64(%rbp),%xmm0 - movdqa %xmm8,80(%rsp) - pshufd $0x5f,%xmm15,%xmm9 - jmp L$xts_enc_loop6 -.p2align 5 -L$xts_enc_loop6: -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 -.byte 102,15,56,220,241 -.byte 102,15,56,220,249 - movups -64(%rcx,%rax,1),%xmm1 - addq $32,%rax - -.byte 102,15,56,220,208 -.byte 102,15,56,220,216 -.byte 102,15,56,220,224 -.byte 102,15,56,220,232 -.byte 102,15,56,220,240 -.byte 102,15,56,220,248 - movups -80(%rcx,%rax,1),%xmm0 - jnz L$xts_enc_loop6 - - movdqa (%r8),%xmm8 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 -.byte 102,15,56,220,209 - paddq %xmm15,%xmm15 - psrad $31,%xmm14 -.byte 102,15,56,220,217 - pand %xmm8,%xmm14 - movups (%rbp),%xmm10 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 -.byte 102,15,56,220,241 - pxor %xmm14,%xmm15 - movaps %xmm10,%xmm11 -.byte 102,15,56,220,249 - movups -64(%rcx),%xmm1 - - movdqa %xmm9,%xmm14 -.byte 102,15,56,220,208 - paddd %xmm9,%xmm9 - pxor %xmm15,%xmm10 -.byte 102,15,56,220,216 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 -.byte 102,15,56,220,224 -.byte 102,15,56,220,232 - pand %xmm8,%xmm14 - movaps %xmm11,%xmm12 -.byte 102,15,56,220,240 - pxor %xmm14,%xmm15 - movdqa %xmm9,%xmm14 -.byte 102,15,56,220,248 - movups -48(%rcx),%xmm0 - - paddd %xmm9,%xmm9 -.byte 102,15,56,220,209 - pxor %xmm15,%xmm11 - psrad $31,%xmm14 -.byte 102,15,56,220,217 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 - movdqa %xmm13,48(%rsp) - pxor %xmm14,%xmm15 -.byte 102,15,56,220,241 - movaps %xmm12,%xmm13 - movdqa %xmm9,%xmm14 -.byte 102,15,56,220,249 - movups -32(%rcx),%xmm1 - - paddd %xmm9,%xmm9 -.byte 102,15,56,220,208 - pxor %xmm15,%xmm12 - psrad $31,%xmm14 -.byte 102,15,56,220,216 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 -.byte 102,15,56,220,224 -.byte 102,15,56,220,232 -.byte 102,15,56,220,240 - pxor %xmm14,%xmm15 - movaps %xmm13,%xmm14 -.byte 102,15,56,220,248 - - movdqa %xmm9,%xmm0 - paddd %xmm9,%xmm9 -.byte 102,15,56,220,209 - pxor %xmm15,%xmm13 - psrad $31,%xmm0 -.byte 102,15,56,220,217 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm0 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 - pxor %xmm0,%xmm15 - movups (%rbp),%xmm0 -.byte 102,15,56,220,241 -.byte 102,15,56,220,249 - movups 16(%rbp),%xmm1 - - pxor %xmm15,%xmm14 -.byte 102,15,56,221,84,36,0 - psrad $31,%xmm9 - paddq %xmm15,%xmm15 -.byte 102,15,56,221,92,36,16 -.byte 102,15,56,221,100,36,32 - pand %xmm8,%xmm9 - movq %r10,%rax -.byte 102,15,56,221,108,36,48 -.byte 102,15,56,221,116,36,64 -.byte 102,15,56,221,124,36,80 - pxor %xmm9,%xmm15 - - leaq 96(%rsi),%rsi - movups %xmm2,-96(%rsi) - movups %xmm3,-80(%rsi) - movups %xmm4,-64(%rsi) - movups %xmm5,-48(%rsi) - movups %xmm6,-32(%rsi) - movups %xmm7,-16(%rsi) - subq $96,%rdx - jnc L$xts_enc_grandloop - - movl $16+96,%eax - subl %r10d,%eax - movq %rbp,%rcx - shrl $4,%eax - -L$xts_enc_short: - - movl %eax,%r10d - pxor %xmm0,%xmm10 - addq $96,%rdx - jz L$xts_enc_done - - pxor %xmm0,%xmm11 - cmpq $0x20,%rdx - jb L$xts_enc_one - pxor %xmm0,%xmm12 - je L$xts_enc_two - - pxor %xmm0,%xmm13 - cmpq $0x40,%rdx - jb L$xts_enc_three - pxor %xmm0,%xmm14 - je L$xts_enc_four - - movdqu (%rdi),%xmm2 - movdqu 16(%rdi),%xmm3 - movdqu 32(%rdi),%xmm4 - pxor %xmm10,%xmm2 - movdqu 48(%rdi),%xmm5 - pxor %xmm11,%xmm3 - movdqu 64(%rdi),%xmm6 - leaq 80(%rdi),%rdi - pxor %xmm12,%xmm4 - pxor %xmm13,%xmm5 - pxor %xmm14,%xmm6 - pxor %xmm7,%xmm7 - - call _aesni_encrypt6 - - xorps %xmm10,%xmm2 - movdqa %xmm15,%xmm10 - xorps %xmm11,%xmm3 - xorps %xmm12,%xmm4 - movdqu %xmm2,(%rsi) - xorps %xmm13,%xmm5 - movdqu %xmm3,16(%rsi) - xorps %xmm14,%xmm6 - movdqu %xmm4,32(%rsi) - movdqu %xmm5,48(%rsi) - movdqu %xmm6,64(%rsi) - leaq 80(%rsi),%rsi - jmp L$xts_enc_done - -.p2align 4 -L$xts_enc_one: - movups (%rdi),%xmm2 - leaq 16(%rdi),%rdi - xorps %xmm10,%xmm2 - movups (%rcx),%xmm0 - movups 16(%rcx),%xmm1 - leaq 32(%rcx),%rcx - xorps %xmm0,%xmm2 -L$oop_enc1_9: -.byte 102,15,56,220,209 - decl %eax - movups (%rcx),%xmm1 - leaq 16(%rcx),%rcx - jnz L$oop_enc1_9 -.byte 102,15,56,221,209 - xorps %xmm10,%xmm2 - movdqa %xmm11,%xmm10 - movups %xmm2,(%rsi) - leaq 16(%rsi),%rsi - jmp L$xts_enc_done - -.p2align 4 -L$xts_enc_two: - movups (%rdi),%xmm2 - movups 16(%rdi),%xmm3 - leaq 32(%rdi),%rdi - xorps %xmm10,%xmm2 - xorps %xmm11,%xmm3 - - call _aesni_encrypt2 - - xorps %xmm10,%xmm2 - movdqa %xmm12,%xmm10 - xorps %xmm11,%xmm3 - movups %xmm2,(%rsi) - movups %xmm3,16(%rsi) - leaq 32(%rsi),%rsi - jmp L$xts_enc_done - -.p2align 4 -L$xts_enc_three: - movups (%rdi),%xmm2 - movups 16(%rdi),%xmm3 - movups 32(%rdi),%xmm4 - leaq 48(%rdi),%rdi - xorps %xmm10,%xmm2 - xorps %xmm11,%xmm3 - xorps %xmm12,%xmm4 - - call _aesni_encrypt3 - - xorps %xmm10,%xmm2 - movdqa %xmm13,%xmm10 - xorps %xmm11,%xmm3 - xorps %xmm12,%xmm4 - movups %xmm2,(%rsi) - movups %xmm3,16(%rsi) - movups %xmm4,32(%rsi) - leaq 48(%rsi),%rsi - jmp L$xts_enc_done - -.p2align 4 -L$xts_enc_four: - movups (%rdi),%xmm2 - movups 16(%rdi),%xmm3 - movups 32(%rdi),%xmm4 - xorps %xmm10,%xmm2 - movups 48(%rdi),%xmm5 - leaq 64(%rdi),%rdi - xorps %xmm11,%xmm3 - xorps %xmm12,%xmm4 - xorps %xmm13,%xmm5 - - call _aesni_encrypt4 - - pxor %xmm10,%xmm2 - movdqa %xmm14,%xmm10 - pxor %xmm11,%xmm3 - pxor %xmm12,%xmm4 - movdqu %xmm2,(%rsi) - pxor %xmm13,%xmm5 - movdqu %xmm3,16(%rsi) - movdqu %xmm4,32(%rsi) - movdqu %xmm5,48(%rsi) - leaq 64(%rsi),%rsi - jmp L$xts_enc_done - -.p2align 4 -L$xts_enc_done: - andq $15,%r9 - jz L$xts_enc_ret - movq %r9,%rdx - -L$xts_enc_steal: - movzbl (%rdi),%eax - movzbl -16(%rsi),%ecx - leaq 1(%rdi),%rdi - movb %al,-16(%rsi) - movb %cl,0(%rsi) - leaq 1(%rsi),%rsi - subq $1,%rdx - jnz L$xts_enc_steal - - subq %r9,%rsi - movq %rbp,%rcx - movl %r10d,%eax - - movups -16(%rsi),%xmm2 - xorps %xmm10,%xmm2 - movups (%rcx),%xmm0 - movups 16(%rcx),%xmm1 - leaq 32(%rcx),%rcx - xorps %xmm0,%xmm2 -L$oop_enc1_10: -.byte 102,15,56,220,209 - decl %eax - movups (%rcx),%xmm1 - leaq 16(%rcx),%rcx - jnz L$oop_enc1_10 -.byte 102,15,56,221,209 - xorps %xmm10,%xmm2 - movups %xmm2,-16(%rsi) - -L$xts_enc_ret: - xorps %xmm0,%xmm0 - pxor %xmm1,%xmm1 - pxor %xmm2,%xmm2 - pxor %xmm3,%xmm3 - pxor %xmm4,%xmm4 - pxor %xmm5,%xmm5 - pxor %xmm6,%xmm6 - pxor %xmm7,%xmm7 - movaps %xmm0,0(%rsp) - pxor %xmm8,%xmm8 - movaps %xmm0,16(%rsp) - pxor %xmm9,%xmm9 - movaps %xmm0,32(%rsp) - pxor %xmm10,%xmm10 - movaps %xmm0,48(%rsp) - pxor %xmm11,%xmm11 - movaps %xmm0,64(%rsp) - pxor %xmm12,%xmm12 - movaps %xmm0,80(%rsp) - pxor %xmm13,%xmm13 - movaps %xmm0,96(%rsp) - pxor %xmm14,%xmm14 - pxor %xmm15,%xmm15 - movq -8(%r11),%rbp - - leaq (%r11),%rsp - -L$xts_enc_epilogue: - .byte 0xf3,0xc3 - - -.globl _aes_hw_xts_decrypt -.private_extern _aes_hw_xts_decrypt - -.p2align 4 -_aes_hw_xts_decrypt: - - leaq (%rsp),%r11 - - pushq %rbp - - subq $112,%rsp - andq $-16,%rsp - movups (%r9),%xmm2 - movl 240(%r8),%eax - movl 240(%rcx),%r10d - movups (%r8),%xmm0 - movups 16(%r8),%xmm1 - leaq 32(%r8),%r8 - xorps %xmm0,%xmm2 -L$oop_enc1_11: -.byte 102,15,56,220,209 - decl %eax - movups (%r8),%xmm1 - leaq 16(%r8),%r8 - jnz L$oop_enc1_11 -.byte 102,15,56,221,209 - xorl %eax,%eax - testq $15,%rdx - setnz %al - shlq $4,%rax - subq %rax,%rdx - - movups (%rcx),%xmm0 - movq %rcx,%rbp - movl %r10d,%eax - shll $4,%r10d - movq %rdx,%r9 - andq $-16,%rdx - - movups 16(%rcx,%r10,1),%xmm1 - - movdqa L$xts_magic(%rip),%xmm8 - movdqa %xmm2,%xmm15 - pshufd $0x5f,%xmm2,%xmm9 - pxor %xmm0,%xmm1 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 - movdqa %xmm15,%xmm10 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 - pxor %xmm0,%xmm10 - pxor %xmm14,%xmm15 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 - movdqa %xmm15,%xmm11 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 - pxor %xmm0,%xmm11 - pxor %xmm14,%xmm15 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 - movdqa %xmm15,%xmm12 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 - pxor %xmm0,%xmm12 - pxor %xmm14,%xmm15 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 - movdqa %xmm15,%xmm13 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 - pxor %xmm0,%xmm13 - pxor %xmm14,%xmm15 - movdqa %xmm15,%xmm14 - psrad $31,%xmm9 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm9 - pxor %xmm0,%xmm14 - pxor %xmm9,%xmm15 - movaps %xmm1,96(%rsp) - - subq $96,%rdx - jc L$xts_dec_short - - movl $16+96,%eax - leaq 32(%rbp,%r10,1),%rcx - subq %r10,%rax - movups 16(%rbp),%xmm1 - movq %rax,%r10 - leaq L$xts_magic(%rip),%r8 - jmp L$xts_dec_grandloop - -.p2align 5 -L$xts_dec_grandloop: - movdqu 0(%rdi),%xmm2 - movdqa %xmm0,%xmm8 - movdqu 16(%rdi),%xmm3 - pxor %xmm10,%xmm2 - movdqu 32(%rdi),%xmm4 - pxor %xmm11,%xmm3 -.byte 102,15,56,222,209 - movdqu 48(%rdi),%xmm5 - pxor %xmm12,%xmm4 -.byte 102,15,56,222,217 - movdqu 64(%rdi),%xmm6 - pxor %xmm13,%xmm5 -.byte 102,15,56,222,225 - movdqu 80(%rdi),%xmm7 - pxor %xmm15,%xmm8 - movdqa 96(%rsp),%xmm9 - pxor %xmm14,%xmm6 -.byte 102,15,56,222,233 - movups 32(%rbp),%xmm0 - leaq 96(%rdi),%rdi - pxor %xmm8,%xmm7 - - pxor %xmm9,%xmm10 -.byte 102,15,56,222,241 - pxor %xmm9,%xmm11 - movdqa %xmm10,0(%rsp) -.byte 102,15,56,222,249 - movups 48(%rbp),%xmm1 - pxor %xmm9,%xmm12 - -.byte 102,15,56,222,208 - pxor %xmm9,%xmm13 - movdqa %xmm11,16(%rsp) -.byte 102,15,56,222,216 - pxor %xmm9,%xmm14 - movdqa %xmm12,32(%rsp) -.byte 102,15,56,222,224 -.byte 102,15,56,222,232 - pxor %xmm9,%xmm8 - movdqa %xmm14,64(%rsp) -.byte 102,15,56,222,240 -.byte 102,15,56,222,248 - movups 64(%rbp),%xmm0 - movdqa %xmm8,80(%rsp) - pshufd $0x5f,%xmm15,%xmm9 - jmp L$xts_dec_loop6 -.p2align 5 -L$xts_dec_loop6: -.byte 102,15,56,222,209 -.byte 102,15,56,222,217 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 -.byte 102,15,56,222,241 -.byte 102,15,56,222,249 - movups -64(%rcx,%rax,1),%xmm1 - addq $32,%rax - -.byte 102,15,56,222,208 -.byte 102,15,56,222,216 -.byte 102,15,56,222,224 -.byte 102,15,56,222,232 -.byte 102,15,56,222,240 -.byte 102,15,56,222,248 - movups -80(%rcx,%rax,1),%xmm0 - jnz L$xts_dec_loop6 - - movdqa (%r8),%xmm8 - movdqa %xmm9,%xmm14 - paddd %xmm9,%xmm9 -.byte 102,15,56,222,209 - paddq %xmm15,%xmm15 - psrad $31,%xmm14 -.byte 102,15,56,222,217 - pand %xmm8,%xmm14 - movups (%rbp),%xmm10 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 -.byte 102,15,56,222,241 - pxor %xmm14,%xmm15 - movaps %xmm10,%xmm11 -.byte 102,15,56,222,249 - movups -64(%rcx),%xmm1 - - movdqa %xmm9,%xmm14 -.byte 102,15,56,222,208 - paddd %xmm9,%xmm9 - pxor %xmm15,%xmm10 -.byte 102,15,56,222,216 - psrad $31,%xmm14 - paddq %xmm15,%xmm15 -.byte 102,15,56,222,224 -.byte 102,15,56,222,232 - pand %xmm8,%xmm14 - movaps %xmm11,%xmm12 -.byte 102,15,56,222,240 - pxor %xmm14,%xmm15 - movdqa %xmm9,%xmm14 -.byte 102,15,56,222,248 - movups -48(%rcx),%xmm0 - - paddd %xmm9,%xmm9 -.byte 102,15,56,222,209 - pxor %xmm15,%xmm11 - psrad $31,%xmm14 -.byte 102,15,56,222,217 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 - movdqa %xmm13,48(%rsp) - pxor %xmm14,%xmm15 -.byte 102,15,56,222,241 - movaps %xmm12,%xmm13 - movdqa %xmm9,%xmm14 -.byte 102,15,56,222,249 - movups -32(%rcx),%xmm1 - - paddd %xmm9,%xmm9 -.byte 102,15,56,222,208 - pxor %xmm15,%xmm12 - psrad $31,%xmm14 -.byte 102,15,56,222,216 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm14 -.byte 102,15,56,222,224 -.byte 102,15,56,222,232 -.byte 102,15,56,222,240 - pxor %xmm14,%xmm15 - movaps %xmm13,%xmm14 -.byte 102,15,56,222,248 - - movdqa %xmm9,%xmm0 - paddd %xmm9,%xmm9 -.byte 102,15,56,222,209 - pxor %xmm15,%xmm13 - psrad $31,%xmm0 -.byte 102,15,56,222,217 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm0 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 - pxor %xmm0,%xmm15 - movups (%rbp),%xmm0 -.byte 102,15,56,222,241 -.byte 102,15,56,222,249 - movups 16(%rbp),%xmm1 - - pxor %xmm15,%xmm14 -.byte 102,15,56,223,84,36,0 - psrad $31,%xmm9 - paddq %xmm15,%xmm15 -.byte 102,15,56,223,92,36,16 -.byte 102,15,56,223,100,36,32 - pand %xmm8,%xmm9 - movq %r10,%rax -.byte 102,15,56,223,108,36,48 -.byte 102,15,56,223,116,36,64 -.byte 102,15,56,223,124,36,80 - pxor %xmm9,%xmm15 - - leaq 96(%rsi),%rsi - movups %xmm2,-96(%rsi) - movups %xmm3,-80(%rsi) - movups %xmm4,-64(%rsi) - movups %xmm5,-48(%rsi) - movups %xmm6,-32(%rsi) - movups %xmm7,-16(%rsi) - subq $96,%rdx - jnc L$xts_dec_grandloop - - movl $16+96,%eax - subl %r10d,%eax - movq %rbp,%rcx - shrl $4,%eax - -L$xts_dec_short: - - movl %eax,%r10d - pxor %xmm0,%xmm10 - pxor %xmm0,%xmm11 - addq $96,%rdx - jz L$xts_dec_done - - pxor %xmm0,%xmm12 - cmpq $0x20,%rdx - jb L$xts_dec_one - pxor %xmm0,%xmm13 - je L$xts_dec_two - - pxor %xmm0,%xmm14 - cmpq $0x40,%rdx - jb L$xts_dec_three - je L$xts_dec_four - - movdqu (%rdi),%xmm2 - movdqu 16(%rdi),%xmm3 - movdqu 32(%rdi),%xmm4 - pxor %xmm10,%xmm2 - movdqu 48(%rdi),%xmm5 - pxor %xmm11,%xmm3 - movdqu 64(%rdi),%xmm6 - leaq 80(%rdi),%rdi - pxor %xmm12,%xmm4 - pxor %xmm13,%xmm5 - pxor %xmm14,%xmm6 - - call _aesni_decrypt6 - - xorps %xmm10,%xmm2 - xorps %xmm11,%xmm3 - xorps %xmm12,%xmm4 - movdqu %xmm2,(%rsi) - xorps %xmm13,%xmm5 - movdqu %xmm3,16(%rsi) - xorps %xmm14,%xmm6 - movdqu %xmm4,32(%rsi) - pxor %xmm14,%xmm14 - movdqu %xmm5,48(%rsi) - pcmpgtd %xmm15,%xmm14 - movdqu %xmm6,64(%rsi) - leaq 80(%rsi),%rsi - pshufd $0x13,%xmm14,%xmm11 - andq $15,%r9 - jz L$xts_dec_ret - - movdqa %xmm15,%xmm10 - paddq %xmm15,%xmm15 - pand %xmm8,%xmm11 - pxor %xmm15,%xmm11 - jmp L$xts_dec_done2 - -.p2align 4 -L$xts_dec_one: - movups (%rdi),%xmm2 - leaq 16(%rdi),%rdi - xorps %xmm10,%xmm2 - movups (%rcx),%xmm0 - movups 16(%rcx),%xmm1 - leaq 32(%rcx),%rcx - xorps %xmm0,%xmm2 -L$oop_dec1_12: -.byte 102,15,56,222,209 - decl %eax - movups (%rcx),%xmm1 - leaq 16(%rcx),%rcx - jnz L$oop_dec1_12 -.byte 102,15,56,223,209 - xorps %xmm10,%xmm2 - movdqa %xmm11,%xmm10 - movups %xmm2,(%rsi) - movdqa %xmm12,%xmm11 - leaq 16(%rsi),%rsi - jmp L$xts_dec_done - -.p2align 4 -L$xts_dec_two: - movups (%rdi),%xmm2 - movups 16(%rdi),%xmm3 - leaq 32(%rdi),%rdi - xorps %xmm10,%xmm2 - xorps %xmm11,%xmm3 - - call _aesni_decrypt2 - - xorps %xmm10,%xmm2 - movdqa %xmm12,%xmm10 - xorps %xmm11,%xmm3 - movdqa %xmm13,%xmm11 - movups %xmm2,(%rsi) - movups %xmm3,16(%rsi) - leaq 32(%rsi),%rsi - jmp L$xts_dec_done - -.p2align 4 -L$xts_dec_three: - movups (%rdi),%xmm2 - movups 16(%rdi),%xmm3 - movups 32(%rdi),%xmm4 - leaq 48(%rdi),%rdi - xorps %xmm10,%xmm2 - xorps %xmm11,%xmm3 - xorps %xmm12,%xmm4 - - call _aesni_decrypt3 - - xorps %xmm10,%xmm2 - movdqa %xmm13,%xmm10 - xorps %xmm11,%xmm3 - movdqa %xmm14,%xmm11 - xorps %xmm12,%xmm4 - movups %xmm2,(%rsi) - movups %xmm3,16(%rsi) - movups %xmm4,32(%rsi) - leaq 48(%rsi),%rsi - jmp L$xts_dec_done - -.p2align 4 -L$xts_dec_four: - movups (%rdi),%xmm2 - movups 16(%rdi),%xmm3 - movups 32(%rdi),%xmm4 - xorps %xmm10,%xmm2 - movups 48(%rdi),%xmm5 - leaq 64(%rdi),%rdi - xorps %xmm11,%xmm3 - xorps %xmm12,%xmm4 - xorps %xmm13,%xmm5 - - call _aesni_decrypt4 - - pxor %xmm10,%xmm2 - movdqa %xmm14,%xmm10 - pxor %xmm11,%xmm3 - movdqa %xmm15,%xmm11 - pxor %xmm12,%xmm4 - movdqu %xmm2,(%rsi) - pxor %xmm13,%xmm5 - movdqu %xmm3,16(%rsi) - movdqu %xmm4,32(%rsi) - movdqu %xmm5,48(%rsi) - leaq 64(%rsi),%rsi - jmp L$xts_dec_done - -.p2align 4 -L$xts_dec_done: - andq $15,%r9 - jz L$xts_dec_ret -L$xts_dec_done2: - movq %r9,%rdx - movq %rbp,%rcx - movl %r10d,%eax - - movups (%rdi),%xmm2 - xorps %xmm11,%xmm2 - movups (%rcx),%xmm0 - movups 16(%rcx),%xmm1 - leaq 32(%rcx),%rcx - xorps %xmm0,%xmm2 -L$oop_dec1_13: -.byte 102,15,56,222,209 - decl %eax - movups (%rcx),%xmm1 - leaq 16(%rcx),%rcx - jnz L$oop_dec1_13 -.byte 102,15,56,223,209 - xorps %xmm11,%xmm2 - movups %xmm2,(%rsi) - -L$xts_dec_steal: - movzbl 16(%rdi),%eax - movzbl (%rsi),%ecx - leaq 1(%rdi),%rdi - movb %al,(%rsi) - movb %cl,16(%rsi) - leaq 1(%rsi),%rsi - subq $1,%rdx - jnz L$xts_dec_steal - - subq %r9,%rsi - movq %rbp,%rcx - movl %r10d,%eax - - movups (%rsi),%xmm2 - xorps %xmm10,%xmm2 - movups (%rcx),%xmm0 - movups 16(%rcx),%xmm1 - leaq 32(%rcx),%rcx - xorps %xmm0,%xmm2 -L$oop_dec1_14: -.byte 102,15,56,222,209 - decl %eax - movups (%rcx),%xmm1 - leaq 16(%rcx),%rcx - jnz L$oop_dec1_14 -.byte 102,15,56,223,209 - xorps %xmm10,%xmm2 - movups %xmm2,(%rsi) - -L$xts_dec_ret: - xorps %xmm0,%xmm0 - pxor %xmm1,%xmm1 - pxor %xmm2,%xmm2 - pxor %xmm3,%xmm3 - pxor %xmm4,%xmm4 - pxor %xmm5,%xmm5 - pxor %xmm6,%xmm6 - pxor %xmm7,%xmm7 - movaps %xmm0,0(%rsp) - pxor %xmm8,%xmm8 - movaps %xmm0,16(%rsp) - pxor %xmm9,%xmm9 - movaps %xmm0,32(%rsp) - pxor %xmm10,%xmm10 - movaps %xmm0,48(%rsp) - pxor %xmm11,%xmm11 - movaps %xmm0,64(%rsp) - pxor %xmm12,%xmm12 - movaps %xmm0,80(%rsp) - pxor %xmm13,%xmm13 - movaps %xmm0,96(%rsp) - pxor %xmm14,%xmm14 - pxor %xmm15,%xmm15 - movq -8(%r11),%rbp - - leaq (%r11),%rsp - -L$xts_dec_epilogue: - .byte 0xf3,0xc3 - - -.globl _aes_hw_ocb_encrypt -.private_extern _aes_hw_ocb_encrypt - -.p2align 5 -_aes_hw_ocb_encrypt: - - leaq (%rsp),%rax - pushq %rbx - - pushq %rbp - - pushq %r12 - - pushq %r13 - - pushq %r14 - - movq 8(%rax),%rbx - movq 8+8(%rax),%rbp - - movl 240(%rcx),%r10d - movq %rcx,%r11 - shll $4,%r10d - movups (%rcx),%xmm9 - movups 16(%rcx,%r10,1),%xmm1 - - movdqu (%r9),%xmm15 - pxor %xmm1,%xmm9 - pxor %xmm1,%xmm15 - - movl $16+32,%eax - leaq 32(%r11,%r10,1),%rcx - movups 16(%r11),%xmm1 - subq %r10,%rax - movq %rax,%r10 - - movdqu (%rbx),%xmm10 - movdqu (%rbp),%xmm8 - - testq $1,%r8 - jnz L$ocb_enc_odd - - bsfq %r8,%r12 - addq $1,%r8 - shlq $4,%r12 - movdqu (%rbx,%r12,1),%xmm7 - movdqu (%rdi),%xmm2 - leaq 16(%rdi),%rdi - - call __ocb_encrypt1 - - movdqa %xmm7,%xmm15 - movups %xmm2,(%rsi) - leaq 16(%rsi),%rsi - subq $1,%rdx - jz L$ocb_enc_done - -L$ocb_enc_odd: - leaq 1(%r8),%r12 - leaq 3(%r8),%r13 - leaq 5(%r8),%r14 - leaq 6(%r8),%r8 - bsfq %r12,%r12 - bsfq %r13,%r13 - bsfq %r14,%r14 - shlq $4,%r12 - shlq $4,%r13 - shlq $4,%r14 - - subq $6,%rdx - jc L$ocb_enc_short - jmp L$ocb_enc_grandloop - -.p2align 5 -L$ocb_enc_grandloop: - movdqu 0(%rdi),%xmm2 - movdqu 16(%rdi),%xmm3 - movdqu 32(%rdi),%xmm4 - movdqu 48(%rdi),%xmm5 - movdqu 64(%rdi),%xmm6 - movdqu 80(%rdi),%xmm7 - leaq 96(%rdi),%rdi - - call __ocb_encrypt6 - - movups %xmm2,0(%rsi) - movups %xmm3,16(%rsi) - movups %xmm4,32(%rsi) - movups %xmm5,48(%rsi) - movups %xmm6,64(%rsi) - movups %xmm7,80(%rsi) - leaq 96(%rsi),%rsi - subq $6,%rdx - jnc L$ocb_enc_grandloop - -L$ocb_enc_short: - addq $6,%rdx - jz L$ocb_enc_done - - movdqu 0(%rdi),%xmm2 - cmpq $2,%rdx - jb L$ocb_enc_one - movdqu 16(%rdi),%xmm3 - je L$ocb_enc_two - - movdqu 32(%rdi),%xmm4 - cmpq $4,%rdx - jb L$ocb_enc_three - movdqu 48(%rdi),%xmm5 - je L$ocb_enc_four - - movdqu 64(%rdi),%xmm6 - pxor %xmm7,%xmm7 - - call __ocb_encrypt6 - - movdqa %xmm14,%xmm15 - movups %xmm2,0(%rsi) - movups %xmm3,16(%rsi) - movups %xmm4,32(%rsi) - movups %xmm5,48(%rsi) - movups %xmm6,64(%rsi) - - jmp L$ocb_enc_done - -.p2align 4 -L$ocb_enc_one: - movdqa %xmm10,%xmm7 - - call __ocb_encrypt1 - - movdqa %xmm7,%xmm15 - movups %xmm2,0(%rsi) - jmp L$ocb_enc_done - -.p2align 4 -L$ocb_enc_two: - pxor %xmm4,%xmm4 - pxor %xmm5,%xmm5 - - call __ocb_encrypt4 - - movdqa %xmm11,%xmm15 - movups %xmm2,0(%rsi) - movups %xmm3,16(%rsi) - - jmp L$ocb_enc_done - -.p2align 4 -L$ocb_enc_three: - pxor %xmm5,%xmm5 - - call __ocb_encrypt4 - - movdqa %xmm12,%xmm15 - movups %xmm2,0(%rsi) - movups %xmm3,16(%rsi) - movups %xmm4,32(%rsi) - - jmp L$ocb_enc_done - -.p2align 4 -L$ocb_enc_four: - call __ocb_encrypt4 - - movdqa %xmm13,%xmm15 - movups %xmm2,0(%rsi) - movups %xmm3,16(%rsi) - movups %xmm4,32(%rsi) - movups %xmm5,48(%rsi) - -L$ocb_enc_done: - pxor %xmm0,%xmm15 - movdqu %xmm8,(%rbp) - movdqu %xmm15,(%r9) - - xorps %xmm0,%xmm0 - pxor %xmm1,%xmm1 - pxor %xmm2,%xmm2 - pxor %xmm3,%xmm3 - pxor %xmm4,%xmm4 - pxor %xmm5,%xmm5 - pxor %xmm6,%xmm6 - pxor %xmm7,%xmm7 - pxor %xmm8,%xmm8 - pxor %xmm9,%xmm9 - pxor %xmm10,%xmm10 - pxor %xmm11,%xmm11 - pxor %xmm12,%xmm12 - pxor %xmm13,%xmm13 - pxor %xmm14,%xmm14 - pxor %xmm15,%xmm15 - leaq 40(%rsp),%rax - - movq -40(%rax),%r14 - - movq -32(%rax),%r13 - - movq -24(%rax),%r12 - - movq -16(%rax),%rbp - - movq -8(%rax),%rbx - - leaq (%rax),%rsp - -L$ocb_enc_epilogue: - .byte 0xf3,0xc3 - - - - -.p2align 5 -__ocb_encrypt6: - pxor %xmm9,%xmm15 - movdqu (%rbx,%r12,1),%xmm11 - movdqa %xmm10,%xmm12 - movdqu (%rbx,%r13,1),%xmm13 - movdqa %xmm10,%xmm14 - pxor %xmm15,%xmm10 - movdqu (%rbx,%r14,1),%xmm15 - pxor %xmm10,%xmm11 - pxor %xmm2,%xmm8 - pxor %xmm10,%xmm2 - pxor %xmm11,%xmm12 - pxor %xmm3,%xmm8 - pxor %xmm11,%xmm3 - pxor %xmm12,%xmm13 - pxor %xmm4,%xmm8 - pxor %xmm12,%xmm4 - pxor %xmm13,%xmm14 - pxor %xmm5,%xmm8 - pxor %xmm13,%xmm5 - pxor %xmm14,%xmm15 - pxor %xmm6,%xmm8 - pxor %xmm14,%xmm6 - pxor %xmm7,%xmm8 - pxor %xmm15,%xmm7 - movups 32(%r11),%xmm0 - - leaq 1(%r8),%r12 - leaq 3(%r8),%r13 - leaq 5(%r8),%r14 - addq $6,%r8 - pxor %xmm9,%xmm10 - bsfq %r12,%r12 - bsfq %r13,%r13 - bsfq %r14,%r14 - -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 - pxor %xmm9,%xmm11 - pxor %xmm9,%xmm12 -.byte 102,15,56,220,241 - pxor %xmm9,%xmm13 - pxor %xmm9,%xmm14 -.byte 102,15,56,220,249 - movups 48(%r11),%xmm1 - pxor %xmm9,%xmm15 - -.byte 102,15,56,220,208 -.byte 102,15,56,220,216 -.byte 102,15,56,220,224 -.byte 102,15,56,220,232 -.byte 102,15,56,220,240 -.byte 102,15,56,220,248 - movups 64(%r11),%xmm0 - shlq $4,%r12 - shlq $4,%r13 - jmp L$ocb_enc_loop6 - -.p2align 5 -L$ocb_enc_loop6: -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 -.byte 102,15,56,220,241 -.byte 102,15,56,220,249 - movups (%rcx,%rax,1),%xmm1 - addq $32,%rax - -.byte 102,15,56,220,208 -.byte 102,15,56,220,216 -.byte 102,15,56,220,224 -.byte 102,15,56,220,232 -.byte 102,15,56,220,240 -.byte 102,15,56,220,248 - movups -16(%rcx,%rax,1),%xmm0 - jnz L$ocb_enc_loop6 - -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 -.byte 102,15,56,220,241 -.byte 102,15,56,220,249 - movups 16(%r11),%xmm1 - shlq $4,%r14 - -.byte 102,65,15,56,221,210 - movdqu (%rbx),%xmm10 - movq %r10,%rax -.byte 102,65,15,56,221,219 -.byte 102,65,15,56,221,228 -.byte 102,65,15,56,221,237 -.byte 102,65,15,56,221,246 -.byte 102,65,15,56,221,255 - .byte 0xf3,0xc3 - - - -.p2align 5 -__ocb_encrypt4: - pxor %xmm9,%xmm15 - movdqu (%rbx,%r12,1),%xmm11 - movdqa %xmm10,%xmm12 - movdqu (%rbx,%r13,1),%xmm13 - pxor %xmm15,%xmm10 - pxor %xmm10,%xmm11 - pxor %xmm2,%xmm8 - pxor %xmm10,%xmm2 - pxor %xmm11,%xmm12 - pxor %xmm3,%xmm8 - pxor %xmm11,%xmm3 - pxor %xmm12,%xmm13 - pxor %xmm4,%xmm8 - pxor %xmm12,%xmm4 - pxor %xmm5,%xmm8 - pxor %xmm13,%xmm5 - movups 32(%r11),%xmm0 - - pxor %xmm9,%xmm10 - pxor %xmm9,%xmm11 - pxor %xmm9,%xmm12 - pxor %xmm9,%xmm13 - -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 - movups 48(%r11),%xmm1 - -.byte 102,15,56,220,208 -.byte 102,15,56,220,216 -.byte 102,15,56,220,224 -.byte 102,15,56,220,232 - movups 64(%r11),%xmm0 - jmp L$ocb_enc_loop4 - -.p2align 5 -L$ocb_enc_loop4: -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 - movups (%rcx,%rax,1),%xmm1 - addq $32,%rax - -.byte 102,15,56,220,208 -.byte 102,15,56,220,216 -.byte 102,15,56,220,224 -.byte 102,15,56,220,232 - movups -16(%rcx,%rax,1),%xmm0 - jnz L$ocb_enc_loop4 - -.byte 102,15,56,220,209 -.byte 102,15,56,220,217 -.byte 102,15,56,220,225 -.byte 102,15,56,220,233 - movups 16(%r11),%xmm1 - movq %r10,%rax - -.byte 102,65,15,56,221,210 -.byte 102,65,15,56,221,219 -.byte 102,65,15,56,221,228 -.byte 102,65,15,56,221,237 - .byte 0xf3,0xc3 - - - -.p2align 5 -__ocb_encrypt1: - pxor %xmm15,%xmm7 - pxor %xmm9,%xmm7 - pxor %xmm2,%xmm8 - pxor %xmm7,%xmm2 - movups 32(%r11),%xmm0 - -.byte 102,15,56,220,209 - movups 48(%r11),%xmm1 - pxor %xmm9,%xmm7 - -.byte 102,15,56,220,208 - movups 64(%r11),%xmm0 - jmp L$ocb_enc_loop1 - -.p2align 5 -L$ocb_enc_loop1: -.byte 102,15,56,220,209 - movups (%rcx,%rax,1),%xmm1 - addq $32,%rax - -.byte 102,15,56,220,208 - movups -16(%rcx,%rax,1),%xmm0 - jnz L$ocb_enc_loop1 - -.byte 102,15,56,220,209 - movups 16(%r11),%xmm1 - movq %r10,%rax - -.byte 102,15,56,221,215 - .byte 0xf3,0xc3 - - -.globl _aes_hw_ocb_decrypt -.private_extern _aes_hw_ocb_decrypt - -.p2align 5 -_aes_hw_ocb_decrypt: - - leaq (%rsp),%rax - pushq %rbx - - pushq %rbp - - pushq %r12 - - pushq %r13 - - pushq %r14 - - movq 8(%rax),%rbx - movq 8+8(%rax),%rbp - - movl 240(%rcx),%r10d - movq %rcx,%r11 - shll $4,%r10d - movups (%rcx),%xmm9 - movups 16(%rcx,%r10,1),%xmm1 - - movdqu (%r9),%xmm15 - pxor %xmm1,%xmm9 - pxor %xmm1,%xmm15 - - movl $16+32,%eax - leaq 32(%r11,%r10,1),%rcx - movups 16(%r11),%xmm1 - subq %r10,%rax - movq %rax,%r10 - - movdqu (%rbx),%xmm10 - movdqu (%rbp),%xmm8 - - testq $1,%r8 - jnz L$ocb_dec_odd - - bsfq %r8,%r12 - addq $1,%r8 - shlq $4,%r12 - movdqu (%rbx,%r12,1),%xmm7 - movdqu (%rdi),%xmm2 - leaq 16(%rdi),%rdi - - call __ocb_decrypt1 - - movdqa %xmm7,%xmm15 - movups %xmm2,(%rsi) - xorps %xmm2,%xmm8 - leaq 16(%rsi),%rsi - subq $1,%rdx - jz L$ocb_dec_done - -L$ocb_dec_odd: - leaq 1(%r8),%r12 - leaq 3(%r8),%r13 - leaq 5(%r8),%r14 - leaq 6(%r8),%r8 - bsfq %r12,%r12 - bsfq %r13,%r13 - bsfq %r14,%r14 - shlq $4,%r12 - shlq $4,%r13 - shlq $4,%r14 - - subq $6,%rdx - jc L$ocb_dec_short - jmp L$ocb_dec_grandloop - -.p2align 5 -L$ocb_dec_grandloop: - movdqu 0(%rdi),%xmm2 - movdqu 16(%rdi),%xmm3 - movdqu 32(%rdi),%xmm4 - movdqu 48(%rdi),%xmm5 - movdqu 64(%rdi),%xmm6 - movdqu 80(%rdi),%xmm7 - leaq 96(%rdi),%rdi - - call __ocb_decrypt6 - - movups %xmm2,0(%rsi) - pxor %xmm2,%xmm8 - movups %xmm3,16(%rsi) - pxor %xmm3,%xmm8 - movups %xmm4,32(%rsi) - pxor %xmm4,%xmm8 - movups %xmm5,48(%rsi) - pxor %xmm5,%xmm8 - movups %xmm6,64(%rsi) - pxor %xmm6,%xmm8 - movups %xmm7,80(%rsi) - pxor %xmm7,%xmm8 - leaq 96(%rsi),%rsi - subq $6,%rdx - jnc L$ocb_dec_grandloop - -L$ocb_dec_short: - addq $6,%rdx - jz L$ocb_dec_done - - movdqu 0(%rdi),%xmm2 - cmpq $2,%rdx - jb L$ocb_dec_one - movdqu 16(%rdi),%xmm3 - je L$ocb_dec_two - - movdqu 32(%rdi),%xmm4 - cmpq $4,%rdx - jb L$ocb_dec_three - movdqu 48(%rdi),%xmm5 - je L$ocb_dec_four - - movdqu 64(%rdi),%xmm6 - pxor %xmm7,%xmm7 - - call __ocb_decrypt6 - - movdqa %xmm14,%xmm15 - movups %xmm2,0(%rsi) - pxor %xmm2,%xmm8 - movups %xmm3,16(%rsi) - pxor %xmm3,%xmm8 - movups %xmm4,32(%rsi) - pxor %xmm4,%xmm8 - movups %xmm5,48(%rsi) - pxor %xmm5,%xmm8 - movups %xmm6,64(%rsi) - pxor %xmm6,%xmm8 - - jmp L$ocb_dec_done - -.p2align 4 -L$ocb_dec_one: - movdqa %xmm10,%xmm7 - - call __ocb_decrypt1 - - movdqa %xmm7,%xmm15 - movups %xmm2,0(%rsi) - xorps %xmm2,%xmm8 - jmp L$ocb_dec_done - -.p2align 4 -L$ocb_dec_two: - pxor %xmm4,%xmm4 - pxor %xmm5,%xmm5 - - call __ocb_decrypt4 - - movdqa %xmm11,%xmm15 - movups %xmm2,0(%rsi) - xorps %xmm2,%xmm8 - movups %xmm3,16(%rsi) - xorps %xmm3,%xmm8 - - jmp L$ocb_dec_done - -.p2align 4 -L$ocb_dec_three: - pxor %xmm5,%xmm5 - - call __ocb_decrypt4 - - movdqa %xmm12,%xmm15 - movups %xmm2,0(%rsi) - xorps %xmm2,%xmm8 - movups %xmm3,16(%rsi) - xorps %xmm3,%xmm8 - movups %xmm4,32(%rsi) - xorps %xmm4,%xmm8 - - jmp L$ocb_dec_done - -.p2align 4 -L$ocb_dec_four: - call __ocb_decrypt4 - - movdqa %xmm13,%xmm15 - movups %xmm2,0(%rsi) - pxor %xmm2,%xmm8 - movups %xmm3,16(%rsi) - pxor %xmm3,%xmm8 - movups %xmm4,32(%rsi) - pxor %xmm4,%xmm8 - movups %xmm5,48(%rsi) - pxor %xmm5,%xmm8 - -L$ocb_dec_done: - pxor %xmm0,%xmm15 - movdqu %xmm8,(%rbp) - movdqu %xmm15,(%r9) - - xorps %xmm0,%xmm0 - pxor %xmm1,%xmm1 - pxor %xmm2,%xmm2 - pxor %xmm3,%xmm3 - pxor %xmm4,%xmm4 - pxor %xmm5,%xmm5 - pxor %xmm6,%xmm6 - pxor %xmm7,%xmm7 - pxor %xmm8,%xmm8 - pxor %xmm9,%xmm9 - pxor %xmm10,%xmm10 - pxor %xmm11,%xmm11 - pxor %xmm12,%xmm12 - pxor %xmm13,%xmm13 - pxor %xmm14,%xmm14 - pxor %xmm15,%xmm15 - leaq 40(%rsp),%rax - - movq -40(%rax),%r14 - - movq -32(%rax),%r13 - - movq -24(%rax),%r12 - - movq -16(%rax),%rbp - - movq -8(%rax),%rbx - - leaq (%rax),%rsp - -L$ocb_dec_epilogue: - .byte 0xf3,0xc3 - - - - -.p2align 5 -__ocb_decrypt6: - pxor %xmm9,%xmm15 - movdqu (%rbx,%r12,1),%xmm11 - movdqa %xmm10,%xmm12 - movdqu (%rbx,%r13,1),%xmm13 - movdqa %xmm10,%xmm14 - pxor %xmm15,%xmm10 - movdqu (%rbx,%r14,1),%xmm15 - pxor %xmm10,%xmm11 - pxor %xmm10,%xmm2 - pxor %xmm11,%xmm12 - pxor %xmm11,%xmm3 - pxor %xmm12,%xmm13 - pxor %xmm12,%xmm4 - pxor %xmm13,%xmm14 - pxor %xmm13,%xmm5 - pxor %xmm14,%xmm15 - pxor %xmm14,%xmm6 - pxor %xmm15,%xmm7 - movups 32(%r11),%xmm0 - - leaq 1(%r8),%r12 - leaq 3(%r8),%r13 - leaq 5(%r8),%r14 - addq $6,%r8 - pxor %xmm9,%xmm10 - bsfq %r12,%r12 - bsfq %r13,%r13 - bsfq %r14,%r14 - -.byte 102,15,56,222,209 -.byte 102,15,56,222,217 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 - pxor %xmm9,%xmm11 - pxor %xmm9,%xmm12 -.byte 102,15,56,222,241 - pxor %xmm9,%xmm13 - pxor %xmm9,%xmm14 -.byte 102,15,56,222,249 - movups 48(%r11),%xmm1 - pxor %xmm9,%xmm15 - -.byte 102,15,56,222,208 -.byte 102,15,56,222,216 -.byte 102,15,56,222,224 -.byte 102,15,56,222,232 -.byte 102,15,56,222,240 -.byte 102,15,56,222,248 - movups 64(%r11),%xmm0 - shlq $4,%r12 - shlq $4,%r13 - jmp L$ocb_dec_loop6 - -.p2align 5 -L$ocb_dec_loop6: -.byte 102,15,56,222,209 -.byte 102,15,56,222,217 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 -.byte 102,15,56,222,241 -.byte 102,15,56,222,249 - movups (%rcx,%rax,1),%xmm1 - addq $32,%rax - -.byte 102,15,56,222,208 -.byte 102,15,56,222,216 -.byte 102,15,56,222,224 -.byte 102,15,56,222,232 -.byte 102,15,56,222,240 -.byte 102,15,56,222,248 - movups -16(%rcx,%rax,1),%xmm0 - jnz L$ocb_dec_loop6 - -.byte 102,15,56,222,209 -.byte 102,15,56,222,217 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 -.byte 102,15,56,222,241 -.byte 102,15,56,222,249 - movups 16(%r11),%xmm1 - shlq $4,%r14 - -.byte 102,65,15,56,223,210 - movdqu (%rbx),%xmm10 - movq %r10,%rax -.byte 102,65,15,56,223,219 -.byte 102,65,15,56,223,228 -.byte 102,65,15,56,223,237 -.byte 102,65,15,56,223,246 -.byte 102,65,15,56,223,255 - .byte 0xf3,0xc3 - - - -.p2align 5 -__ocb_decrypt4: - pxor %xmm9,%xmm15 - movdqu (%rbx,%r12,1),%xmm11 - movdqa %xmm10,%xmm12 - movdqu (%rbx,%r13,1),%xmm13 - pxor %xmm15,%xmm10 - pxor %xmm10,%xmm11 - pxor %xmm10,%xmm2 - pxor %xmm11,%xmm12 - pxor %xmm11,%xmm3 - pxor %xmm12,%xmm13 - pxor %xmm12,%xmm4 - pxor %xmm13,%xmm5 - movups 32(%r11),%xmm0 - - pxor %xmm9,%xmm10 - pxor %xmm9,%xmm11 - pxor %xmm9,%xmm12 - pxor %xmm9,%xmm13 - -.byte 102,15,56,222,209 -.byte 102,15,56,222,217 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 - movups 48(%r11),%xmm1 - -.byte 102,15,56,222,208 -.byte 102,15,56,222,216 -.byte 102,15,56,222,224 -.byte 102,15,56,222,232 - movups 64(%r11),%xmm0 - jmp L$ocb_dec_loop4 - -.p2align 5 -L$ocb_dec_loop4: -.byte 102,15,56,222,209 -.byte 102,15,56,222,217 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 - movups (%rcx,%rax,1),%xmm1 - addq $32,%rax - -.byte 102,15,56,222,208 -.byte 102,15,56,222,216 -.byte 102,15,56,222,224 -.byte 102,15,56,222,232 - movups -16(%rcx,%rax,1),%xmm0 - jnz L$ocb_dec_loop4 - -.byte 102,15,56,222,209 -.byte 102,15,56,222,217 -.byte 102,15,56,222,225 -.byte 102,15,56,222,233 - movups 16(%r11),%xmm1 - movq %r10,%rax - -.byte 102,65,15,56,223,210 -.byte 102,65,15,56,223,219 -.byte 102,65,15,56,223,228 -.byte 102,65,15,56,223,237 - .byte 0xf3,0xc3 - - - -.p2align 5 -__ocb_decrypt1: - pxor %xmm15,%xmm7 - pxor %xmm9,%xmm7 - pxor %xmm7,%xmm2 - movups 32(%r11),%xmm0 - -.byte 102,15,56,222,209 - movups 48(%r11),%xmm1 - pxor %xmm9,%xmm7 - -.byte 102,15,56,222,208 - movups 64(%r11),%xmm0 - jmp L$ocb_dec_loop1 - -.p2align 5 -L$ocb_dec_loop1: -.byte 102,15,56,222,209 - movups (%rcx,%rax,1),%xmm1 - addq $32,%rax - -.byte 102,15,56,222,208 - movups -16(%rcx,%rax,1),%xmm0 - jnz L$ocb_dec_loop1 - -.byte 102,15,56,222,209 - movups 16(%r11),%xmm1 - movq %r10,%rax - -.byte 102,15,56,223,215 - .byte 0xf3,0xc3 - .globl _aes_hw_cbc_encrypt .private_extern _aes_hw_cbc_encrypt @@ -3468,12 +1494,12 @@ L$cbc_enc_loop: xorps %xmm0,%xmm3 leaq 32(%rcx),%rcx xorps %xmm3,%xmm2 -L$oop_enc1_15: +L$oop_enc1_6: .byte 102,15,56,220,209 decl %eax movups (%rcx),%xmm1 leaq 16(%rcx),%rcx - jnz L$oop_enc1_15 + jnz L$oop_enc1_6 .byte 102,15,56,221,209 movl %r10d,%eax movq %r11,%rcx @@ -3519,12 +1545,12 @@ L$cbc_decrypt: movups 16(%rcx),%xmm1 leaq 32(%rcx),%rcx xorps %xmm0,%xmm2 -L$oop_dec1_16: +L$oop_dec1_7: .byte 102,15,56,222,209 decl %r10d movups (%rcx),%xmm1 leaq 16(%rcx),%rcx - jnz L$oop_dec1_16 + jnz L$oop_dec1_7 .byte 102,15,56,223,209 pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 @@ -3937,12 +1963,12 @@ L$cbc_dec_one: movups 16(%rcx),%xmm1 leaq 32(%rcx),%rcx xorps %xmm0,%xmm2 -L$oop_dec1_17: +L$oop_dec1_8: .byte 102,15,56,222,209 decl %eax movups (%rcx),%xmm1 leaq 16(%rcx),%rcx - jnz L$oop_dec1_17 + jnz L$oop_dec1_8 .byte 102,15,56,223,209 xorps %xmm10,%xmm2 movaps %xmm11,%xmm10 @@ -4083,6 +2109,11 @@ L$SEH_end_set_decrypt_key: _aes_hw_set_encrypt_key: __aesni_set_encrypt_key: +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS + movb $1,_BORINGSSL_function_hit+3(%rip) +#endif +#endif .byte 0x48,0x83,0xEC,0x08 movq $-1,%rax diff --git a/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/bsaes-x86_64.S b/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/bsaes-x86_64.S deleted file mode 100644 index 1db55ef2..00000000 --- a/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/bsaes-x86_64.S +++ /dev/null @@ -1,1625 +0,0 @@ -# This file is generated from a similarly-named Perl script in the BoringSSL -# source tree. Do not edit by hand. - -#if defined(__has_feature) -#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) -#define OPENSSL_NO_ASM -#endif -#endif - -#if defined(__x86_64__) && !defined(OPENSSL_NO_ASM) -#if defined(BORINGSSL_PREFIX) -#include -#endif -.text - - - - - -.p2align 6 -_bsaes_encrypt8: - - leaq L$BS0(%rip),%r11 - - movdqa (%rax),%xmm8 - leaq 16(%rax),%rax - movdqa 80(%r11),%xmm7 - pxor %xmm8,%xmm15 - pxor %xmm8,%xmm0 - pxor %xmm8,%xmm1 - pxor %xmm8,%xmm2 -.byte 102,68,15,56,0,255 -.byte 102,15,56,0,199 - pxor %xmm8,%xmm3 - pxor %xmm8,%xmm4 -.byte 102,15,56,0,207 -.byte 102,15,56,0,215 - pxor %xmm8,%xmm5 - pxor %xmm8,%xmm6 -.byte 102,15,56,0,223 -.byte 102,15,56,0,231 -.byte 102,15,56,0,239 -.byte 102,15,56,0,247 -_bsaes_encrypt8_bitslice: - movdqa 0(%r11),%xmm7 - movdqa 16(%r11),%xmm8 - movdqa %xmm5,%xmm9 - psrlq $1,%xmm5 - movdqa %xmm3,%xmm10 - psrlq $1,%xmm3 - pxor %xmm6,%xmm5 - pxor %xmm4,%xmm3 - pand %xmm7,%xmm5 - pand %xmm7,%xmm3 - pxor %xmm5,%xmm6 - psllq $1,%xmm5 - pxor %xmm3,%xmm4 - psllq $1,%xmm3 - pxor %xmm9,%xmm5 - pxor %xmm10,%xmm3 - movdqa %xmm1,%xmm9 - psrlq $1,%xmm1 - movdqa %xmm15,%xmm10 - psrlq $1,%xmm15 - pxor %xmm2,%xmm1 - pxor %xmm0,%xmm15 - pand %xmm7,%xmm1 - pand %xmm7,%xmm15 - pxor %xmm1,%xmm2 - psllq $1,%xmm1 - pxor %xmm15,%xmm0 - psllq $1,%xmm15 - pxor %xmm9,%xmm1 - pxor %xmm10,%xmm15 - movdqa 32(%r11),%xmm7 - movdqa %xmm4,%xmm9 - psrlq $2,%xmm4 - movdqa %xmm3,%xmm10 - psrlq $2,%xmm3 - pxor %xmm6,%xmm4 - pxor %xmm5,%xmm3 - pand %xmm8,%xmm4 - pand %xmm8,%xmm3 - pxor %xmm4,%xmm6 - psllq $2,%xmm4 - pxor %xmm3,%xmm5 - psllq $2,%xmm3 - pxor %xmm9,%xmm4 - pxor %xmm10,%xmm3 - movdqa %xmm0,%xmm9 - psrlq $2,%xmm0 - movdqa %xmm15,%xmm10 - psrlq $2,%xmm15 - pxor %xmm2,%xmm0 - pxor %xmm1,%xmm15 - pand %xmm8,%xmm0 - pand %xmm8,%xmm15 - pxor %xmm0,%xmm2 - psllq $2,%xmm0 - pxor %xmm15,%xmm1 - psllq $2,%xmm15 - pxor %xmm9,%xmm0 - pxor %xmm10,%xmm15 - movdqa %xmm2,%xmm9 - psrlq $4,%xmm2 - movdqa %xmm1,%xmm10 - psrlq $4,%xmm1 - pxor %xmm6,%xmm2 - pxor %xmm5,%xmm1 - pand %xmm7,%xmm2 - pand %xmm7,%xmm1 - pxor %xmm2,%xmm6 - psllq $4,%xmm2 - pxor %xmm1,%xmm5 - psllq $4,%xmm1 - pxor %xmm9,%xmm2 - pxor %xmm10,%xmm1 - movdqa %xmm0,%xmm9 - psrlq $4,%xmm0 - movdqa %xmm15,%xmm10 - psrlq $4,%xmm15 - pxor %xmm4,%xmm0 - pxor %xmm3,%xmm15 - pand %xmm7,%xmm0 - pand %xmm7,%xmm15 - pxor %xmm0,%xmm4 - psllq $4,%xmm0 - pxor %xmm15,%xmm3 - psllq $4,%xmm15 - pxor %xmm9,%xmm0 - pxor %xmm10,%xmm15 - decl %r10d - jmp L$enc_sbox -.p2align 4 -L$enc_loop: - pxor 0(%rax),%xmm15 - pxor 16(%rax),%xmm0 - pxor 32(%rax),%xmm1 - pxor 48(%rax),%xmm2 -.byte 102,68,15,56,0,255 -.byte 102,15,56,0,199 - pxor 64(%rax),%xmm3 - pxor 80(%rax),%xmm4 -.byte 102,15,56,0,207 -.byte 102,15,56,0,215 - pxor 96(%rax),%xmm5 - pxor 112(%rax),%xmm6 -.byte 102,15,56,0,223 -.byte 102,15,56,0,231 -.byte 102,15,56,0,239 -.byte 102,15,56,0,247 - leaq 128(%rax),%rax -L$enc_sbox: - pxor %xmm5,%xmm4 - pxor %xmm0,%xmm1 - pxor %xmm15,%xmm2 - pxor %xmm1,%xmm5 - pxor %xmm15,%xmm4 - - pxor %xmm2,%xmm5 - pxor %xmm6,%xmm2 - pxor %xmm4,%xmm6 - pxor %xmm3,%xmm2 - pxor %xmm4,%xmm3 - pxor %xmm0,%xmm2 - - pxor %xmm6,%xmm1 - pxor %xmm4,%xmm0 - movdqa %xmm6,%xmm10 - movdqa %xmm0,%xmm9 - movdqa %xmm4,%xmm8 - movdqa %xmm1,%xmm12 - movdqa %xmm5,%xmm11 - - pxor %xmm3,%xmm10 - pxor %xmm1,%xmm9 - pxor %xmm2,%xmm8 - movdqa %xmm10,%xmm13 - pxor %xmm3,%xmm12 - movdqa %xmm9,%xmm7 - pxor %xmm15,%xmm11 - movdqa %xmm10,%xmm14 - - por %xmm8,%xmm9 - por %xmm11,%xmm10 - pxor %xmm7,%xmm14 - pand %xmm11,%xmm13 - pxor %xmm8,%xmm11 - pand %xmm8,%xmm7 - pand %xmm11,%xmm14 - movdqa %xmm2,%xmm11 - pxor %xmm15,%xmm11 - pand %xmm11,%xmm12 - pxor %xmm12,%xmm10 - pxor %xmm12,%xmm9 - movdqa %xmm6,%xmm12 - movdqa %xmm4,%xmm11 - pxor %xmm0,%xmm12 - pxor %xmm5,%xmm11 - movdqa %xmm12,%xmm8 - pand %xmm11,%xmm12 - por %xmm11,%xmm8 - pxor %xmm12,%xmm7 - pxor %xmm14,%xmm10 - pxor %xmm13,%xmm9 - pxor %xmm14,%xmm8 - movdqa %xmm1,%xmm11 - pxor %xmm13,%xmm7 - movdqa %xmm3,%xmm12 - pxor %xmm13,%xmm8 - movdqa %xmm0,%xmm13 - pand %xmm2,%xmm11 - movdqa %xmm6,%xmm14 - pand %xmm15,%xmm12 - pand %xmm4,%xmm13 - por %xmm5,%xmm14 - pxor %xmm11,%xmm10 - pxor %xmm12,%xmm9 - pxor %xmm13,%xmm8 - pxor %xmm14,%xmm7 - - - - - - movdqa %xmm10,%xmm11 - pand %xmm8,%xmm10 - pxor %xmm9,%xmm11 - - movdqa %xmm7,%xmm13 - movdqa %xmm11,%xmm14 - pxor %xmm10,%xmm13 - pand %xmm13,%xmm14 - - movdqa %xmm8,%xmm12 - pxor %xmm9,%xmm14 - pxor %xmm7,%xmm12 - - pxor %xmm9,%xmm10 - - pand %xmm10,%xmm12 - - movdqa %xmm13,%xmm9 - pxor %xmm7,%xmm12 - - pxor %xmm12,%xmm9 - pxor %xmm12,%xmm8 - - pand %xmm7,%xmm9 - - pxor %xmm9,%xmm13 - pxor %xmm9,%xmm8 - - pand %xmm14,%xmm13 - - pxor %xmm11,%xmm13 - movdqa %xmm5,%xmm11 - movdqa %xmm4,%xmm7 - movdqa %xmm14,%xmm9 - pxor %xmm13,%xmm9 - pand %xmm5,%xmm9 - pxor %xmm4,%xmm5 - pand %xmm14,%xmm4 - pand %xmm13,%xmm5 - pxor %xmm4,%xmm5 - pxor %xmm9,%xmm4 - pxor %xmm15,%xmm11 - pxor %xmm2,%xmm7 - pxor %xmm12,%xmm14 - pxor %xmm8,%xmm13 - movdqa %xmm14,%xmm10 - movdqa %xmm12,%xmm9 - pxor %xmm13,%xmm10 - pxor %xmm8,%xmm9 - pand %xmm11,%xmm10 - pand %xmm15,%xmm9 - pxor %xmm7,%xmm11 - pxor %xmm2,%xmm15 - pand %xmm14,%xmm7 - pand %xmm12,%xmm2 - pand %xmm13,%xmm11 - pand %xmm8,%xmm15 - pxor %xmm11,%xmm7 - pxor %xmm2,%xmm15 - pxor %xmm10,%xmm11 - pxor %xmm9,%xmm2 - pxor %xmm11,%xmm5 - pxor %xmm11,%xmm15 - pxor %xmm7,%xmm4 - pxor %xmm7,%xmm2 - - movdqa %xmm6,%xmm11 - movdqa %xmm0,%xmm7 - pxor %xmm3,%xmm11 - pxor %xmm1,%xmm7 - movdqa %xmm14,%xmm10 - movdqa %xmm12,%xmm9 - pxor %xmm13,%xmm10 - pxor %xmm8,%xmm9 - pand %xmm11,%xmm10 - pand %xmm3,%xmm9 - pxor %xmm7,%xmm11 - pxor %xmm1,%xmm3 - pand %xmm14,%xmm7 - pand %xmm12,%xmm1 - pand %xmm13,%xmm11 - pand %xmm8,%xmm3 - pxor %xmm11,%xmm7 - pxor %xmm1,%xmm3 - pxor %xmm10,%xmm11 - pxor %xmm9,%xmm1 - pxor %xmm12,%xmm14 - pxor %xmm8,%xmm13 - movdqa %xmm14,%xmm10 - pxor %xmm13,%xmm10 - pand %xmm6,%xmm10 - pxor %xmm0,%xmm6 - pand %xmm14,%xmm0 - pand %xmm13,%xmm6 - pxor %xmm0,%xmm6 - pxor %xmm10,%xmm0 - pxor %xmm11,%xmm6 - pxor %xmm11,%xmm3 - pxor %xmm7,%xmm0 - pxor %xmm7,%xmm1 - pxor %xmm15,%xmm6 - pxor %xmm5,%xmm0 - pxor %xmm6,%xmm3 - pxor %xmm15,%xmm5 - pxor %xmm0,%xmm15 - - pxor %xmm4,%xmm0 - pxor %xmm1,%xmm4 - pxor %xmm2,%xmm1 - pxor %xmm4,%xmm2 - pxor %xmm4,%xmm3 - - pxor %xmm2,%xmm5 - decl %r10d - jl L$enc_done - pshufd $0x93,%xmm15,%xmm7 - pshufd $0x93,%xmm0,%xmm8 - pxor %xmm7,%xmm15 - pshufd $0x93,%xmm3,%xmm9 - pxor %xmm8,%xmm0 - pshufd $0x93,%xmm5,%xmm10 - pxor %xmm9,%xmm3 - pshufd $0x93,%xmm2,%xmm11 - pxor %xmm10,%xmm5 - pshufd $0x93,%xmm6,%xmm12 - pxor %xmm11,%xmm2 - pshufd $0x93,%xmm1,%xmm13 - pxor %xmm12,%xmm6 - pshufd $0x93,%xmm4,%xmm14 - pxor %xmm13,%xmm1 - pxor %xmm14,%xmm4 - - pxor %xmm15,%xmm8 - pxor %xmm4,%xmm7 - pxor %xmm4,%xmm8 - pshufd $0x4E,%xmm15,%xmm15 - pxor %xmm0,%xmm9 - pshufd $0x4E,%xmm0,%xmm0 - pxor %xmm2,%xmm12 - pxor %xmm7,%xmm15 - pxor %xmm6,%xmm13 - pxor %xmm8,%xmm0 - pxor %xmm5,%xmm11 - pshufd $0x4E,%xmm2,%xmm7 - pxor %xmm1,%xmm14 - pshufd $0x4E,%xmm6,%xmm8 - pxor %xmm3,%xmm10 - pshufd $0x4E,%xmm5,%xmm2 - pxor %xmm4,%xmm10 - pshufd $0x4E,%xmm4,%xmm6 - pxor %xmm4,%xmm11 - pshufd $0x4E,%xmm1,%xmm5 - pxor %xmm11,%xmm7 - pshufd $0x4E,%xmm3,%xmm1 - pxor %xmm12,%xmm8 - pxor %xmm10,%xmm2 - pxor %xmm14,%xmm6 - pxor %xmm13,%xmm5 - movdqa %xmm7,%xmm3 - pxor %xmm9,%xmm1 - movdqa %xmm8,%xmm4 - movdqa 48(%r11),%xmm7 - jnz L$enc_loop - movdqa 64(%r11),%xmm7 - jmp L$enc_loop -.p2align 4 -L$enc_done: - movdqa 0(%r11),%xmm7 - movdqa 16(%r11),%xmm8 - movdqa %xmm1,%xmm9 - psrlq $1,%xmm1 - movdqa %xmm2,%xmm10 - psrlq $1,%xmm2 - pxor %xmm4,%xmm1 - pxor %xmm6,%xmm2 - pand %xmm7,%xmm1 - pand %xmm7,%xmm2 - pxor %xmm1,%xmm4 - psllq $1,%xmm1 - pxor %xmm2,%xmm6 - psllq $1,%xmm2 - pxor %xmm9,%xmm1 - pxor %xmm10,%xmm2 - movdqa %xmm3,%xmm9 - psrlq $1,%xmm3 - movdqa %xmm15,%xmm10 - psrlq $1,%xmm15 - pxor %xmm5,%xmm3 - pxor %xmm0,%xmm15 - pand %xmm7,%xmm3 - pand %xmm7,%xmm15 - pxor %xmm3,%xmm5 - psllq $1,%xmm3 - pxor %xmm15,%xmm0 - psllq $1,%xmm15 - pxor %xmm9,%xmm3 - pxor %xmm10,%xmm15 - movdqa 32(%r11),%xmm7 - movdqa %xmm6,%xmm9 - psrlq $2,%xmm6 - movdqa %xmm2,%xmm10 - psrlq $2,%xmm2 - pxor %xmm4,%xmm6 - pxor %xmm1,%xmm2 - pand %xmm8,%xmm6 - pand %xmm8,%xmm2 - pxor %xmm6,%xmm4 - psllq $2,%xmm6 - pxor %xmm2,%xmm1 - psllq $2,%xmm2 - pxor %xmm9,%xmm6 - pxor %xmm10,%xmm2 - movdqa %xmm0,%xmm9 - psrlq $2,%xmm0 - movdqa %xmm15,%xmm10 - psrlq $2,%xmm15 - pxor %xmm5,%xmm0 - pxor %xmm3,%xmm15 - pand %xmm8,%xmm0 - pand %xmm8,%xmm15 - pxor %xmm0,%xmm5 - psllq $2,%xmm0 - pxor %xmm15,%xmm3 - psllq $2,%xmm15 - pxor %xmm9,%xmm0 - pxor %xmm10,%xmm15 - movdqa %xmm5,%xmm9 - psrlq $4,%xmm5 - movdqa %xmm3,%xmm10 - psrlq $4,%xmm3 - pxor %xmm4,%xmm5 - pxor %xmm1,%xmm3 - pand %xmm7,%xmm5 - pand %xmm7,%xmm3 - pxor %xmm5,%xmm4 - psllq $4,%xmm5 - pxor %xmm3,%xmm1 - psllq $4,%xmm3 - pxor %xmm9,%xmm5 - pxor %xmm10,%xmm3 - movdqa %xmm0,%xmm9 - psrlq $4,%xmm0 - movdqa %xmm15,%xmm10 - psrlq $4,%xmm15 - pxor %xmm6,%xmm0 - pxor %xmm2,%xmm15 - pand %xmm7,%xmm0 - pand %xmm7,%xmm15 - pxor %xmm0,%xmm6 - psllq $4,%xmm0 - pxor %xmm15,%xmm2 - psllq $4,%xmm15 - pxor %xmm9,%xmm0 - pxor %xmm10,%xmm15 - movdqa (%rax),%xmm7 - pxor %xmm7,%xmm3 - pxor %xmm7,%xmm5 - pxor %xmm7,%xmm2 - pxor %xmm7,%xmm6 - pxor %xmm7,%xmm1 - pxor %xmm7,%xmm4 - pxor %xmm7,%xmm15 - pxor %xmm7,%xmm0 - .byte 0xf3,0xc3 - - - - -.p2align 6 -_bsaes_decrypt8: - - leaq L$BS0(%rip),%r11 - - movdqa (%rax),%xmm8 - leaq 16(%rax),%rax - movdqa -48(%r11),%xmm7 - pxor %xmm8,%xmm15 - pxor %xmm8,%xmm0 - pxor %xmm8,%xmm1 - pxor %xmm8,%xmm2 -.byte 102,68,15,56,0,255 -.byte 102,15,56,0,199 - pxor %xmm8,%xmm3 - pxor %xmm8,%xmm4 -.byte 102,15,56,0,207 -.byte 102,15,56,0,215 - pxor %xmm8,%xmm5 - pxor %xmm8,%xmm6 -.byte 102,15,56,0,223 -.byte 102,15,56,0,231 -.byte 102,15,56,0,239 -.byte 102,15,56,0,247 - movdqa 0(%r11),%xmm7 - movdqa 16(%r11),%xmm8 - movdqa %xmm5,%xmm9 - psrlq $1,%xmm5 - movdqa %xmm3,%xmm10 - psrlq $1,%xmm3 - pxor %xmm6,%xmm5 - pxor %xmm4,%xmm3 - pand %xmm7,%xmm5 - pand %xmm7,%xmm3 - pxor %xmm5,%xmm6 - psllq $1,%xmm5 - pxor %xmm3,%xmm4 - psllq $1,%xmm3 - pxor %xmm9,%xmm5 - pxor %xmm10,%xmm3 - movdqa %xmm1,%xmm9 - psrlq $1,%xmm1 - movdqa %xmm15,%xmm10 - psrlq $1,%xmm15 - pxor %xmm2,%xmm1 - pxor %xmm0,%xmm15 - pand %xmm7,%xmm1 - pand %xmm7,%xmm15 - pxor %xmm1,%xmm2 - psllq $1,%xmm1 - pxor %xmm15,%xmm0 - psllq $1,%xmm15 - pxor %xmm9,%xmm1 - pxor %xmm10,%xmm15 - movdqa 32(%r11),%xmm7 - movdqa %xmm4,%xmm9 - psrlq $2,%xmm4 - movdqa %xmm3,%xmm10 - psrlq $2,%xmm3 - pxor %xmm6,%xmm4 - pxor %xmm5,%xmm3 - pand %xmm8,%xmm4 - pand %xmm8,%xmm3 - pxor %xmm4,%xmm6 - psllq $2,%xmm4 - pxor %xmm3,%xmm5 - psllq $2,%xmm3 - pxor %xmm9,%xmm4 - pxor %xmm10,%xmm3 - movdqa %xmm0,%xmm9 - psrlq $2,%xmm0 - movdqa %xmm15,%xmm10 - psrlq $2,%xmm15 - pxor %xmm2,%xmm0 - pxor %xmm1,%xmm15 - pand %xmm8,%xmm0 - pand %xmm8,%xmm15 - pxor %xmm0,%xmm2 - psllq $2,%xmm0 - pxor %xmm15,%xmm1 - psllq $2,%xmm15 - pxor %xmm9,%xmm0 - pxor %xmm10,%xmm15 - movdqa %xmm2,%xmm9 - psrlq $4,%xmm2 - movdqa %xmm1,%xmm10 - psrlq $4,%xmm1 - pxor %xmm6,%xmm2 - pxor %xmm5,%xmm1 - pand %xmm7,%xmm2 - pand %xmm7,%xmm1 - pxor %xmm2,%xmm6 - psllq $4,%xmm2 - pxor %xmm1,%xmm5 - psllq $4,%xmm1 - pxor %xmm9,%xmm2 - pxor %xmm10,%xmm1 - movdqa %xmm0,%xmm9 - psrlq $4,%xmm0 - movdqa %xmm15,%xmm10 - psrlq $4,%xmm15 - pxor %xmm4,%xmm0 - pxor %xmm3,%xmm15 - pand %xmm7,%xmm0 - pand %xmm7,%xmm15 - pxor %xmm0,%xmm4 - psllq $4,%xmm0 - pxor %xmm15,%xmm3 - psllq $4,%xmm15 - pxor %xmm9,%xmm0 - pxor %xmm10,%xmm15 - decl %r10d - jmp L$dec_sbox -.p2align 4 -L$dec_loop: - pxor 0(%rax),%xmm15 - pxor 16(%rax),%xmm0 - pxor 32(%rax),%xmm1 - pxor 48(%rax),%xmm2 -.byte 102,68,15,56,0,255 -.byte 102,15,56,0,199 - pxor 64(%rax),%xmm3 - pxor 80(%rax),%xmm4 -.byte 102,15,56,0,207 -.byte 102,15,56,0,215 - pxor 96(%rax),%xmm5 - pxor 112(%rax),%xmm6 -.byte 102,15,56,0,223 -.byte 102,15,56,0,231 -.byte 102,15,56,0,239 -.byte 102,15,56,0,247 - leaq 128(%rax),%rax -L$dec_sbox: - pxor %xmm3,%xmm2 - - pxor %xmm6,%xmm3 - pxor %xmm6,%xmm1 - pxor %xmm3,%xmm5 - pxor %xmm5,%xmm6 - pxor %xmm6,%xmm0 - - pxor %xmm0,%xmm15 - pxor %xmm4,%xmm1 - pxor %xmm15,%xmm2 - pxor %xmm15,%xmm4 - pxor %xmm2,%xmm0 - movdqa %xmm2,%xmm10 - movdqa %xmm6,%xmm9 - movdqa %xmm0,%xmm8 - movdqa %xmm3,%xmm12 - movdqa %xmm4,%xmm11 - - pxor %xmm15,%xmm10 - pxor %xmm3,%xmm9 - pxor %xmm5,%xmm8 - movdqa %xmm10,%xmm13 - pxor %xmm15,%xmm12 - movdqa %xmm9,%xmm7 - pxor %xmm1,%xmm11 - movdqa %xmm10,%xmm14 - - por %xmm8,%xmm9 - por %xmm11,%xmm10 - pxor %xmm7,%xmm14 - pand %xmm11,%xmm13 - pxor %xmm8,%xmm11 - pand %xmm8,%xmm7 - pand %xmm11,%xmm14 - movdqa %xmm5,%xmm11 - pxor %xmm1,%xmm11 - pand %xmm11,%xmm12 - pxor %xmm12,%xmm10 - pxor %xmm12,%xmm9 - movdqa %xmm2,%xmm12 - movdqa %xmm0,%xmm11 - pxor %xmm6,%xmm12 - pxor %xmm4,%xmm11 - movdqa %xmm12,%xmm8 - pand %xmm11,%xmm12 - por %xmm11,%xmm8 - pxor %xmm12,%xmm7 - pxor %xmm14,%xmm10 - pxor %xmm13,%xmm9 - pxor %xmm14,%xmm8 - movdqa %xmm3,%xmm11 - pxor %xmm13,%xmm7 - movdqa %xmm15,%xmm12 - pxor %xmm13,%xmm8 - movdqa %xmm6,%xmm13 - pand %xmm5,%xmm11 - movdqa %xmm2,%xmm14 - pand %xmm1,%xmm12 - pand %xmm0,%xmm13 - por %xmm4,%xmm14 - pxor %xmm11,%xmm10 - pxor %xmm12,%xmm9 - pxor %xmm13,%xmm8 - pxor %xmm14,%xmm7 - - - - - - movdqa %xmm10,%xmm11 - pand %xmm8,%xmm10 - pxor %xmm9,%xmm11 - - movdqa %xmm7,%xmm13 - movdqa %xmm11,%xmm14 - pxor %xmm10,%xmm13 - pand %xmm13,%xmm14 - - movdqa %xmm8,%xmm12 - pxor %xmm9,%xmm14 - pxor %xmm7,%xmm12 - - pxor %xmm9,%xmm10 - - pand %xmm10,%xmm12 - - movdqa %xmm13,%xmm9 - pxor %xmm7,%xmm12 - - pxor %xmm12,%xmm9 - pxor %xmm12,%xmm8 - - pand %xmm7,%xmm9 - - pxor %xmm9,%xmm13 - pxor %xmm9,%xmm8 - - pand %xmm14,%xmm13 - - pxor %xmm11,%xmm13 - movdqa %xmm4,%xmm11 - movdqa %xmm0,%xmm7 - movdqa %xmm14,%xmm9 - pxor %xmm13,%xmm9 - pand %xmm4,%xmm9 - pxor %xmm0,%xmm4 - pand %xmm14,%xmm0 - pand %xmm13,%xmm4 - pxor %xmm0,%xmm4 - pxor %xmm9,%xmm0 - pxor %xmm1,%xmm11 - pxor %xmm5,%xmm7 - pxor %xmm12,%xmm14 - pxor %xmm8,%xmm13 - movdqa %xmm14,%xmm10 - movdqa %xmm12,%xmm9 - pxor %xmm13,%xmm10 - pxor %xmm8,%xmm9 - pand %xmm11,%xmm10 - pand %xmm1,%xmm9 - pxor %xmm7,%xmm11 - pxor %xmm5,%xmm1 - pand %xmm14,%xmm7 - pand %xmm12,%xmm5 - pand %xmm13,%xmm11 - pand %xmm8,%xmm1 - pxor %xmm11,%xmm7 - pxor %xmm5,%xmm1 - pxor %xmm10,%xmm11 - pxor %xmm9,%xmm5 - pxor %xmm11,%xmm4 - pxor %xmm11,%xmm1 - pxor %xmm7,%xmm0 - pxor %xmm7,%xmm5 - - movdqa %xmm2,%xmm11 - movdqa %xmm6,%xmm7 - pxor %xmm15,%xmm11 - pxor %xmm3,%xmm7 - movdqa %xmm14,%xmm10 - movdqa %xmm12,%xmm9 - pxor %xmm13,%xmm10 - pxor %xmm8,%xmm9 - pand %xmm11,%xmm10 - pand %xmm15,%xmm9 - pxor %xmm7,%xmm11 - pxor %xmm3,%xmm15 - pand %xmm14,%xmm7 - pand %xmm12,%xmm3 - pand %xmm13,%xmm11 - pand %xmm8,%xmm15 - pxor %xmm11,%xmm7 - pxor %xmm3,%xmm15 - pxor %xmm10,%xmm11 - pxor %xmm9,%xmm3 - pxor %xmm12,%xmm14 - pxor %xmm8,%xmm13 - movdqa %xmm14,%xmm10 - pxor %xmm13,%xmm10 - pand %xmm2,%xmm10 - pxor %xmm6,%xmm2 - pand %xmm14,%xmm6 - pand %xmm13,%xmm2 - pxor %xmm6,%xmm2 - pxor %xmm10,%xmm6 - pxor %xmm11,%xmm2 - pxor %xmm11,%xmm15 - pxor %xmm7,%xmm6 - pxor %xmm7,%xmm3 - pxor %xmm6,%xmm0 - pxor %xmm4,%xmm5 - - pxor %xmm0,%xmm3 - pxor %xmm6,%xmm1 - pxor %xmm6,%xmm4 - pxor %xmm1,%xmm3 - pxor %xmm15,%xmm6 - pxor %xmm4,%xmm3 - pxor %xmm5,%xmm2 - pxor %xmm0,%xmm5 - pxor %xmm3,%xmm2 - - pxor %xmm15,%xmm3 - pxor %xmm2,%xmm6 - decl %r10d - jl L$dec_done - - pshufd $0x4E,%xmm15,%xmm7 - pshufd $0x4E,%xmm2,%xmm13 - pxor %xmm15,%xmm7 - pshufd $0x4E,%xmm4,%xmm14 - pxor %xmm2,%xmm13 - pshufd $0x4E,%xmm0,%xmm8 - pxor %xmm4,%xmm14 - pshufd $0x4E,%xmm5,%xmm9 - pxor %xmm0,%xmm8 - pshufd $0x4E,%xmm3,%xmm10 - pxor %xmm5,%xmm9 - pxor %xmm13,%xmm15 - pxor %xmm13,%xmm0 - pshufd $0x4E,%xmm1,%xmm11 - pxor %xmm3,%xmm10 - pxor %xmm7,%xmm5 - pxor %xmm8,%xmm3 - pshufd $0x4E,%xmm6,%xmm12 - pxor %xmm1,%xmm11 - pxor %xmm14,%xmm0 - pxor %xmm9,%xmm1 - pxor %xmm6,%xmm12 - - pxor %xmm14,%xmm5 - pxor %xmm13,%xmm3 - pxor %xmm13,%xmm1 - pxor %xmm10,%xmm6 - pxor %xmm11,%xmm2 - pxor %xmm14,%xmm1 - pxor %xmm14,%xmm6 - pxor %xmm12,%xmm4 - pshufd $0x93,%xmm15,%xmm7 - pshufd $0x93,%xmm0,%xmm8 - pxor %xmm7,%xmm15 - pshufd $0x93,%xmm5,%xmm9 - pxor %xmm8,%xmm0 - pshufd $0x93,%xmm3,%xmm10 - pxor %xmm9,%xmm5 - pshufd $0x93,%xmm1,%xmm11 - pxor %xmm10,%xmm3 - pshufd $0x93,%xmm6,%xmm12 - pxor %xmm11,%xmm1 - pshufd $0x93,%xmm2,%xmm13 - pxor %xmm12,%xmm6 - pshufd $0x93,%xmm4,%xmm14 - pxor %xmm13,%xmm2 - pxor %xmm14,%xmm4 - - pxor %xmm15,%xmm8 - pxor %xmm4,%xmm7 - pxor %xmm4,%xmm8 - pshufd $0x4E,%xmm15,%xmm15 - pxor %xmm0,%xmm9 - pshufd $0x4E,%xmm0,%xmm0 - pxor %xmm1,%xmm12 - pxor %xmm7,%xmm15 - pxor %xmm6,%xmm13 - pxor %xmm8,%xmm0 - pxor %xmm3,%xmm11 - pshufd $0x4E,%xmm1,%xmm7 - pxor %xmm2,%xmm14 - pshufd $0x4E,%xmm6,%xmm8 - pxor %xmm5,%xmm10 - pshufd $0x4E,%xmm3,%xmm1 - pxor %xmm4,%xmm10 - pshufd $0x4E,%xmm4,%xmm6 - pxor %xmm4,%xmm11 - pshufd $0x4E,%xmm2,%xmm3 - pxor %xmm11,%xmm7 - pshufd $0x4E,%xmm5,%xmm2 - pxor %xmm12,%xmm8 - pxor %xmm1,%xmm10 - pxor %xmm14,%xmm6 - pxor %xmm3,%xmm13 - movdqa %xmm7,%xmm3 - pxor %xmm9,%xmm2 - movdqa %xmm13,%xmm5 - movdqa %xmm8,%xmm4 - movdqa %xmm2,%xmm1 - movdqa %xmm10,%xmm2 - movdqa -16(%r11),%xmm7 - jnz L$dec_loop - movdqa -32(%r11),%xmm7 - jmp L$dec_loop -.p2align 4 -L$dec_done: - movdqa 0(%r11),%xmm7 - movdqa 16(%r11),%xmm8 - movdqa %xmm2,%xmm9 - psrlq $1,%xmm2 - movdqa %xmm1,%xmm10 - psrlq $1,%xmm1 - pxor %xmm4,%xmm2 - pxor %xmm6,%xmm1 - pand %xmm7,%xmm2 - pand %xmm7,%xmm1 - pxor %xmm2,%xmm4 - psllq $1,%xmm2 - pxor %xmm1,%xmm6 - psllq $1,%xmm1 - pxor %xmm9,%xmm2 - pxor %xmm10,%xmm1 - movdqa %xmm5,%xmm9 - psrlq $1,%xmm5 - movdqa %xmm15,%xmm10 - psrlq $1,%xmm15 - pxor %xmm3,%xmm5 - pxor %xmm0,%xmm15 - pand %xmm7,%xmm5 - pand %xmm7,%xmm15 - pxor %xmm5,%xmm3 - psllq $1,%xmm5 - pxor %xmm15,%xmm0 - psllq $1,%xmm15 - pxor %xmm9,%xmm5 - pxor %xmm10,%xmm15 - movdqa 32(%r11),%xmm7 - movdqa %xmm6,%xmm9 - psrlq $2,%xmm6 - movdqa %xmm1,%xmm10 - psrlq $2,%xmm1 - pxor %xmm4,%xmm6 - pxor %xmm2,%xmm1 - pand %xmm8,%xmm6 - pand %xmm8,%xmm1 - pxor %xmm6,%xmm4 - psllq $2,%xmm6 - pxor %xmm1,%xmm2 - psllq $2,%xmm1 - pxor %xmm9,%xmm6 - pxor %xmm10,%xmm1 - movdqa %xmm0,%xmm9 - psrlq $2,%xmm0 - movdqa %xmm15,%xmm10 - psrlq $2,%xmm15 - pxor %xmm3,%xmm0 - pxor %xmm5,%xmm15 - pand %xmm8,%xmm0 - pand %xmm8,%xmm15 - pxor %xmm0,%xmm3 - psllq $2,%xmm0 - pxor %xmm15,%xmm5 - psllq $2,%xmm15 - pxor %xmm9,%xmm0 - pxor %xmm10,%xmm15 - movdqa %xmm3,%xmm9 - psrlq $4,%xmm3 - movdqa %xmm5,%xmm10 - psrlq $4,%xmm5 - pxor %xmm4,%xmm3 - pxor %xmm2,%xmm5 - pand %xmm7,%xmm3 - pand %xmm7,%xmm5 - pxor %xmm3,%xmm4 - psllq $4,%xmm3 - pxor %xmm5,%xmm2 - psllq $4,%xmm5 - pxor %xmm9,%xmm3 - pxor %xmm10,%xmm5 - movdqa %xmm0,%xmm9 - psrlq $4,%xmm0 - movdqa %xmm15,%xmm10 - psrlq $4,%xmm15 - pxor %xmm6,%xmm0 - pxor %xmm1,%xmm15 - pand %xmm7,%xmm0 - pand %xmm7,%xmm15 - pxor %xmm0,%xmm6 - psllq $4,%xmm0 - pxor %xmm15,%xmm1 - psllq $4,%xmm15 - pxor %xmm9,%xmm0 - pxor %xmm10,%xmm15 - movdqa (%rax),%xmm7 - pxor %xmm7,%xmm5 - pxor %xmm7,%xmm3 - pxor %xmm7,%xmm1 - pxor %xmm7,%xmm6 - pxor %xmm7,%xmm2 - pxor %xmm7,%xmm4 - pxor %xmm7,%xmm15 - pxor %xmm7,%xmm0 - .byte 0xf3,0xc3 - - - -.p2align 4 -_bsaes_key_convert: - - leaq L$masks(%rip),%r11 - movdqu (%rcx),%xmm7 - leaq 16(%rcx),%rcx - movdqa 0(%r11),%xmm0 - movdqa 16(%r11),%xmm1 - movdqa 32(%r11),%xmm2 - movdqa 48(%r11),%xmm3 - movdqa 64(%r11),%xmm4 - pcmpeqd %xmm5,%xmm5 - - movdqu (%rcx),%xmm6 - movdqa %xmm7,(%rax) - leaq 16(%rax),%rax - decl %r10d - jmp L$key_loop -.p2align 4 -L$key_loop: -.byte 102,15,56,0,244 - - movdqa %xmm0,%xmm8 - movdqa %xmm1,%xmm9 - - pand %xmm6,%xmm8 - pand %xmm6,%xmm9 - movdqa %xmm2,%xmm10 - pcmpeqb %xmm0,%xmm8 - psllq $4,%xmm0 - movdqa %xmm3,%xmm11 - pcmpeqb %xmm1,%xmm9 - psllq $4,%xmm1 - - pand %xmm6,%xmm10 - pand %xmm6,%xmm11 - movdqa %xmm0,%xmm12 - pcmpeqb %xmm2,%xmm10 - psllq $4,%xmm2 - movdqa %xmm1,%xmm13 - pcmpeqb %xmm3,%xmm11 - psllq $4,%xmm3 - - movdqa %xmm2,%xmm14 - movdqa %xmm3,%xmm15 - pxor %xmm5,%xmm8 - pxor %xmm5,%xmm9 - - pand %xmm6,%xmm12 - pand %xmm6,%xmm13 - movdqa %xmm8,0(%rax) - pcmpeqb %xmm0,%xmm12 - psrlq $4,%xmm0 - movdqa %xmm9,16(%rax) - pcmpeqb %xmm1,%xmm13 - psrlq $4,%xmm1 - leaq 16(%rcx),%rcx - - pand %xmm6,%xmm14 - pand %xmm6,%xmm15 - movdqa %xmm10,32(%rax) - pcmpeqb %xmm2,%xmm14 - psrlq $4,%xmm2 - movdqa %xmm11,48(%rax) - pcmpeqb %xmm3,%xmm15 - psrlq $4,%xmm3 - movdqu (%rcx),%xmm6 - - pxor %xmm5,%xmm13 - pxor %xmm5,%xmm14 - movdqa %xmm12,64(%rax) - movdqa %xmm13,80(%rax) - movdqa %xmm14,96(%rax) - movdqa %xmm15,112(%rax) - leaq 128(%rax),%rax - decl %r10d - jnz L$key_loop - - movdqa 80(%r11),%xmm7 - - .byte 0xf3,0xc3 - - - -.globl _bsaes_cbc_encrypt -.private_extern _bsaes_cbc_encrypt - -.p2align 4 -_bsaes_cbc_encrypt: - - cmpl $0,%r9d - jne _aes_nohw_cbc_encrypt - cmpq $128,%rdx - jb _aes_nohw_cbc_encrypt - - movq %rsp,%rax -L$cbc_dec_prologue: - pushq %rbp - - pushq %rbx - - pushq %r12 - - pushq %r13 - - pushq %r14 - - pushq %r15 - - leaq -72(%rsp),%rsp - - movq %rsp,%rbp - - movl 240(%rcx),%eax - movq %rdi,%r12 - movq %rsi,%r13 - movq %rdx,%r14 - movq %rcx,%r15 - movq %r8,%rbx - shrq $4,%r14 - - movl %eax,%edx - shlq $7,%rax - subq $96,%rax - subq %rax,%rsp - - movq %rsp,%rax - movq %r15,%rcx - movl %edx,%r10d - call _bsaes_key_convert - pxor (%rsp),%xmm7 - movdqa %xmm6,(%rax) - movdqa %xmm7,(%rsp) - - movdqu (%rbx),%xmm14 - subq $8,%r14 -L$cbc_dec_loop: - movdqu 0(%r12),%xmm15 - movdqu 16(%r12),%xmm0 - movdqu 32(%r12),%xmm1 - movdqu 48(%r12),%xmm2 - movdqu 64(%r12),%xmm3 - movdqu 80(%r12),%xmm4 - movq %rsp,%rax - movdqu 96(%r12),%xmm5 - movl %edx,%r10d - movdqu 112(%r12),%xmm6 - movdqa %xmm14,32(%rbp) - - call _bsaes_decrypt8 - - pxor 32(%rbp),%xmm15 - movdqu 0(%r12),%xmm7 - movdqu 16(%r12),%xmm8 - pxor %xmm7,%xmm0 - movdqu 32(%r12),%xmm9 - pxor %xmm8,%xmm5 - movdqu 48(%r12),%xmm10 - pxor %xmm9,%xmm3 - movdqu 64(%r12),%xmm11 - pxor %xmm10,%xmm1 - movdqu 80(%r12),%xmm12 - pxor %xmm11,%xmm6 - movdqu 96(%r12),%xmm13 - pxor %xmm12,%xmm2 - movdqu 112(%r12),%xmm14 - pxor %xmm13,%xmm4 - movdqu %xmm15,0(%r13) - leaq 128(%r12),%r12 - movdqu %xmm0,16(%r13) - movdqu %xmm5,32(%r13) - movdqu %xmm3,48(%r13) - movdqu %xmm1,64(%r13) - movdqu %xmm6,80(%r13) - movdqu %xmm2,96(%r13) - movdqu %xmm4,112(%r13) - leaq 128(%r13),%r13 - subq $8,%r14 - jnc L$cbc_dec_loop - - addq $8,%r14 - jz L$cbc_dec_done - - movdqu 0(%r12),%xmm15 - movq %rsp,%rax - movl %edx,%r10d - cmpq $2,%r14 - jb L$cbc_dec_one - movdqu 16(%r12),%xmm0 - je L$cbc_dec_two - movdqu 32(%r12),%xmm1 - cmpq $4,%r14 - jb L$cbc_dec_three - movdqu 48(%r12),%xmm2 - je L$cbc_dec_four - movdqu 64(%r12),%xmm3 - cmpq $6,%r14 - jb L$cbc_dec_five - movdqu 80(%r12),%xmm4 - je L$cbc_dec_six - movdqu 96(%r12),%xmm5 - movdqa %xmm14,32(%rbp) - call _bsaes_decrypt8 - pxor 32(%rbp),%xmm15 - movdqu 0(%r12),%xmm7 - movdqu 16(%r12),%xmm8 - pxor %xmm7,%xmm0 - movdqu 32(%r12),%xmm9 - pxor %xmm8,%xmm5 - movdqu 48(%r12),%xmm10 - pxor %xmm9,%xmm3 - movdqu 64(%r12),%xmm11 - pxor %xmm10,%xmm1 - movdqu 80(%r12),%xmm12 - pxor %xmm11,%xmm6 - movdqu 96(%r12),%xmm14 - pxor %xmm12,%xmm2 - movdqu %xmm15,0(%r13) - movdqu %xmm0,16(%r13) - movdqu %xmm5,32(%r13) - movdqu %xmm3,48(%r13) - movdqu %xmm1,64(%r13) - movdqu %xmm6,80(%r13) - movdqu %xmm2,96(%r13) - jmp L$cbc_dec_done -.p2align 4 -L$cbc_dec_six: - movdqa %xmm14,32(%rbp) - call _bsaes_decrypt8 - pxor 32(%rbp),%xmm15 - movdqu 0(%r12),%xmm7 - movdqu 16(%r12),%xmm8 - pxor %xmm7,%xmm0 - movdqu 32(%r12),%xmm9 - pxor %xmm8,%xmm5 - movdqu 48(%r12),%xmm10 - pxor %xmm9,%xmm3 - movdqu 64(%r12),%xmm11 - pxor %xmm10,%xmm1 - movdqu 80(%r12),%xmm14 - pxor %xmm11,%xmm6 - movdqu %xmm15,0(%r13) - movdqu %xmm0,16(%r13) - movdqu %xmm5,32(%r13) - movdqu %xmm3,48(%r13) - movdqu %xmm1,64(%r13) - movdqu %xmm6,80(%r13) - jmp L$cbc_dec_done -.p2align 4 -L$cbc_dec_five: - movdqa %xmm14,32(%rbp) - call _bsaes_decrypt8 - pxor 32(%rbp),%xmm15 - movdqu 0(%r12),%xmm7 - movdqu 16(%r12),%xmm8 - pxor %xmm7,%xmm0 - movdqu 32(%r12),%xmm9 - pxor %xmm8,%xmm5 - movdqu 48(%r12),%xmm10 - pxor %xmm9,%xmm3 - movdqu 64(%r12),%xmm14 - pxor %xmm10,%xmm1 - movdqu %xmm15,0(%r13) - movdqu %xmm0,16(%r13) - movdqu %xmm5,32(%r13) - movdqu %xmm3,48(%r13) - movdqu %xmm1,64(%r13) - jmp L$cbc_dec_done -.p2align 4 -L$cbc_dec_four: - movdqa %xmm14,32(%rbp) - call _bsaes_decrypt8 - pxor 32(%rbp),%xmm15 - movdqu 0(%r12),%xmm7 - movdqu 16(%r12),%xmm8 - pxor %xmm7,%xmm0 - movdqu 32(%r12),%xmm9 - pxor %xmm8,%xmm5 - movdqu 48(%r12),%xmm14 - pxor %xmm9,%xmm3 - movdqu %xmm15,0(%r13) - movdqu %xmm0,16(%r13) - movdqu %xmm5,32(%r13) - movdqu %xmm3,48(%r13) - jmp L$cbc_dec_done -.p2align 4 -L$cbc_dec_three: - movdqa %xmm14,32(%rbp) - call _bsaes_decrypt8 - pxor 32(%rbp),%xmm15 - movdqu 0(%r12),%xmm7 - movdqu 16(%r12),%xmm8 - pxor %xmm7,%xmm0 - movdqu 32(%r12),%xmm14 - pxor %xmm8,%xmm5 - movdqu %xmm15,0(%r13) - movdqu %xmm0,16(%r13) - movdqu %xmm5,32(%r13) - jmp L$cbc_dec_done -.p2align 4 -L$cbc_dec_two: - movdqa %xmm14,32(%rbp) - call _bsaes_decrypt8 - pxor 32(%rbp),%xmm15 - movdqu 0(%r12),%xmm7 - movdqu 16(%r12),%xmm14 - pxor %xmm7,%xmm0 - movdqu %xmm15,0(%r13) - movdqu %xmm0,16(%r13) - jmp L$cbc_dec_done -.p2align 4 -L$cbc_dec_one: - leaq (%r12),%rdi - leaq 32(%rbp),%rsi - leaq (%r15),%rdx - call _aes_nohw_decrypt - pxor 32(%rbp),%xmm14 - movdqu %xmm14,(%r13) - movdqa %xmm15,%xmm14 - -L$cbc_dec_done: - movdqu %xmm14,(%rbx) - leaq (%rsp),%rax - pxor %xmm0,%xmm0 -L$cbc_dec_bzero: - movdqa %xmm0,0(%rax) - movdqa %xmm0,16(%rax) - leaq 32(%rax),%rax - cmpq %rax,%rbp - ja L$cbc_dec_bzero - - leaq 120(%rbp),%rax - - movq -48(%rax),%r15 - - movq -40(%rax),%r14 - - movq -32(%rax),%r13 - - movq -24(%rax),%r12 - - movq -16(%rax),%rbx - - movq -8(%rax),%rbp - - leaq (%rax),%rsp - -L$cbc_dec_epilogue: - .byte 0xf3,0xc3 - - - -.globl _bsaes_ctr32_encrypt_blocks -.private_extern _bsaes_ctr32_encrypt_blocks - -.p2align 4 -_bsaes_ctr32_encrypt_blocks: - - movq %rsp,%rax -L$ctr_enc_prologue: - pushq %rbp - - pushq %rbx - - pushq %r12 - - pushq %r13 - - pushq %r14 - - pushq %r15 - - leaq -72(%rsp),%rsp - - movq %rsp,%rbp - - movdqu (%r8),%xmm0 - movl 240(%rcx),%eax - movq %rdi,%r12 - movq %rsi,%r13 - movq %rdx,%r14 - movq %rcx,%r15 - movdqa %xmm0,32(%rbp) - cmpq $8,%rdx - jb L$ctr_enc_short - - movl %eax,%ebx - shlq $7,%rax - subq $96,%rax - subq %rax,%rsp - - movq %rsp,%rax - movq %r15,%rcx - movl %ebx,%r10d - call _bsaes_key_convert - pxor %xmm6,%xmm7 - movdqa %xmm7,(%rax) - - movdqa (%rsp),%xmm8 - leaq L$ADD1(%rip),%r11 - movdqa 32(%rbp),%xmm15 - movdqa -32(%r11),%xmm7 -.byte 102,68,15,56,0,199 -.byte 102,68,15,56,0,255 - movdqa %xmm8,(%rsp) - jmp L$ctr_enc_loop -.p2align 4 -L$ctr_enc_loop: - movdqa %xmm15,32(%rbp) - movdqa %xmm15,%xmm0 - movdqa %xmm15,%xmm1 - paddd 0(%r11),%xmm0 - movdqa %xmm15,%xmm2 - paddd 16(%r11),%xmm1 - movdqa %xmm15,%xmm3 - paddd 32(%r11),%xmm2 - movdqa %xmm15,%xmm4 - paddd 48(%r11),%xmm3 - movdqa %xmm15,%xmm5 - paddd 64(%r11),%xmm4 - movdqa %xmm15,%xmm6 - paddd 80(%r11),%xmm5 - paddd 96(%r11),%xmm6 - - - - movdqa (%rsp),%xmm8 - leaq 16(%rsp),%rax - movdqa -16(%r11),%xmm7 - pxor %xmm8,%xmm15 - pxor %xmm8,%xmm0 - pxor %xmm8,%xmm1 - pxor %xmm8,%xmm2 -.byte 102,68,15,56,0,255 -.byte 102,15,56,0,199 - pxor %xmm8,%xmm3 - pxor %xmm8,%xmm4 -.byte 102,15,56,0,207 -.byte 102,15,56,0,215 - pxor %xmm8,%xmm5 - pxor %xmm8,%xmm6 -.byte 102,15,56,0,223 -.byte 102,15,56,0,231 -.byte 102,15,56,0,239 -.byte 102,15,56,0,247 - leaq L$BS0(%rip),%r11 - movl %ebx,%r10d - - call _bsaes_encrypt8_bitslice - - subq $8,%r14 - jc L$ctr_enc_loop_done - - movdqu 0(%r12),%xmm7 - movdqu 16(%r12),%xmm8 - movdqu 32(%r12),%xmm9 - movdqu 48(%r12),%xmm10 - movdqu 64(%r12),%xmm11 - movdqu 80(%r12),%xmm12 - movdqu 96(%r12),%xmm13 - movdqu 112(%r12),%xmm14 - leaq 128(%r12),%r12 - pxor %xmm15,%xmm7 - movdqa 32(%rbp),%xmm15 - pxor %xmm8,%xmm0 - movdqu %xmm7,0(%r13) - pxor %xmm9,%xmm3 - movdqu %xmm0,16(%r13) - pxor %xmm10,%xmm5 - movdqu %xmm3,32(%r13) - pxor %xmm11,%xmm2 - movdqu %xmm5,48(%r13) - pxor %xmm12,%xmm6 - movdqu %xmm2,64(%r13) - pxor %xmm13,%xmm1 - movdqu %xmm6,80(%r13) - pxor %xmm14,%xmm4 - movdqu %xmm1,96(%r13) - leaq L$ADD1(%rip),%r11 - movdqu %xmm4,112(%r13) - leaq 128(%r13),%r13 - paddd 112(%r11),%xmm15 - jnz L$ctr_enc_loop - - jmp L$ctr_enc_done -.p2align 4 -L$ctr_enc_loop_done: - addq $8,%r14 - movdqu 0(%r12),%xmm7 - pxor %xmm7,%xmm15 - movdqu %xmm15,0(%r13) - cmpq $2,%r14 - jb L$ctr_enc_done - movdqu 16(%r12),%xmm8 - pxor %xmm8,%xmm0 - movdqu %xmm0,16(%r13) - je L$ctr_enc_done - movdqu 32(%r12),%xmm9 - pxor %xmm9,%xmm3 - movdqu %xmm3,32(%r13) - cmpq $4,%r14 - jb L$ctr_enc_done - movdqu 48(%r12),%xmm10 - pxor %xmm10,%xmm5 - movdqu %xmm5,48(%r13) - je L$ctr_enc_done - movdqu 64(%r12),%xmm11 - pxor %xmm11,%xmm2 - movdqu %xmm2,64(%r13) - cmpq $6,%r14 - jb L$ctr_enc_done - movdqu 80(%r12),%xmm12 - pxor %xmm12,%xmm6 - movdqu %xmm6,80(%r13) - je L$ctr_enc_done - movdqu 96(%r12),%xmm13 - pxor %xmm13,%xmm1 - movdqu %xmm1,96(%r13) - jmp L$ctr_enc_done - -.p2align 4 -L$ctr_enc_short: - leaq 32(%rbp),%rdi - leaq 48(%rbp),%rsi - leaq (%r15),%rdx - call _aes_nohw_encrypt - movdqu (%r12),%xmm0 - leaq 16(%r12),%r12 - movl 44(%rbp),%eax - bswapl %eax - pxor 48(%rbp),%xmm0 - incl %eax - movdqu %xmm0,(%r13) - bswapl %eax - leaq 16(%r13),%r13 - movl %eax,44(%rsp) - decq %r14 - jnz L$ctr_enc_short - -L$ctr_enc_done: - leaq (%rsp),%rax - pxor %xmm0,%xmm0 -L$ctr_enc_bzero: - movdqa %xmm0,0(%rax) - movdqa %xmm0,16(%rax) - leaq 32(%rax),%rax - cmpq %rax,%rbp - ja L$ctr_enc_bzero - - leaq 120(%rbp),%rax - - movq -48(%rax),%r15 - - movq -40(%rax),%r14 - - movq -32(%rax),%r13 - - movq -24(%rax),%r12 - - movq -16(%rax),%rbx - - movq -8(%rax),%rbp - - leaq (%rax),%rsp - -L$ctr_enc_epilogue: - .byte 0xf3,0xc3 - - - -.p2align 6 -_bsaes_const: -L$M0ISR: -.quad 0x0a0e0206070b0f03, 0x0004080c0d010509 -L$ISRM0: -.quad 0x01040b0e0205080f, 0x0306090c00070a0d -L$ISR: -.quad 0x0504070602010003, 0x0f0e0d0c080b0a09 -L$BS0: -.quad 0x5555555555555555, 0x5555555555555555 -L$BS1: -.quad 0x3333333333333333, 0x3333333333333333 -L$BS2: -.quad 0x0f0f0f0f0f0f0f0f, 0x0f0f0f0f0f0f0f0f -L$SR: -.quad 0x0504070600030201, 0x0f0e0d0c0a09080b -L$SRM0: -.quad 0x0304090e00050a0f, 0x01060b0c0207080d -L$M0SR: -.quad 0x0a0e02060f03070b, 0x0004080c05090d01 -L$SWPUP: -.quad 0x0706050403020100, 0x0c0d0e0f0b0a0908 -L$SWPUPM0SR: -.quad 0x0a0d02060c03070b, 0x0004080f05090e01 -L$ADD1: -.quad 0x0000000000000000, 0x0000000100000000 -L$ADD2: -.quad 0x0000000000000000, 0x0000000200000000 -L$ADD3: -.quad 0x0000000000000000, 0x0000000300000000 -L$ADD4: -.quad 0x0000000000000000, 0x0000000400000000 -L$ADD5: -.quad 0x0000000000000000, 0x0000000500000000 -L$ADD6: -.quad 0x0000000000000000, 0x0000000600000000 -L$ADD7: -.quad 0x0000000000000000, 0x0000000700000000 -L$ADD8: -.quad 0x0000000000000000, 0x0000000800000000 -L$xts_magic: -.long 0x87,0,1,0 -L$masks: -.quad 0x0101010101010101, 0x0101010101010101 -.quad 0x0202020202020202, 0x0202020202020202 -.quad 0x0404040404040404, 0x0404040404040404 -.quad 0x0808080808080808, 0x0808080808080808 -L$M0: -.quad 0x02060a0e03070b0f, 0x0004080c0105090d -L$63: -.quad 0x6363636363636363, 0x6363636363636363 -.byte 66,105,116,45,115,108,105,99,101,100,32,65,69,83,32,102,111,114,32,120,56,54,95,54,52,47,83,83,83,69,51,44,32,69,109,105,108,105,97,32,75,195,164,115,112,101,114,44,32,80,101,116,101,114,32,83,99,104,119,97,98,101,44,32,65,110,100,121,32,80,111,108,121,97,107,111,118,0 -.p2align 6 - -#endif diff --git a/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.S b/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.S new file mode 100644 index 00000000..1b9129f2 --- /dev/null +++ b/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.S @@ -0,0 +1,426 @@ +# This file is generated from a similarly-named Perl script in the BoringSSL +# source tree. Do not edit by hand. + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) +#define OPENSSL_NO_ASM +#endif +#endif + +#if defined(__x86_64__) && !defined(OPENSSL_NO_ASM) +#if defined(BORINGSSL_PREFIX) +#include +#endif +.text + + + + + + +.globl _gcm_gmult_ssse3 +.private_extern _gcm_gmult_ssse3 +.p2align 4 +_gcm_gmult_ssse3: + +L$gmult_seh_begin: + movdqu (%rdi),%xmm0 + movdqa L$reverse_bytes(%rip),%xmm10 + movdqa L$low4_mask(%rip),%xmm2 + + +.byte 102,65,15,56,0,194 + + + movdqa %xmm2,%xmm1 + pandn %xmm0,%xmm1 + psrld $4,%xmm1 + pand %xmm2,%xmm0 + + + + + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + movq $5,%rax +L$oop_row_1: + movdqa (%rsi),%xmm4 + leaq 16(%rsi),%rsi + + + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + + + + + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + + + pxor %xmm5,%xmm2 + + + + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + + + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + + subq $1,%rax + jnz L$oop_row_1 + + + + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movq $5,%rax +L$oop_row_2: + movdqa (%rsi),%xmm4 + leaq 16(%rsi),%rsi + + + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + + + + + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + + + pxor %xmm5,%xmm2 + + + + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + + + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + + subq $1,%rax + jnz L$oop_row_2 + + + + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movq $6,%rax +L$oop_row_3: + movdqa (%rsi),%xmm4 + leaq 16(%rsi),%rsi + + + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + + + + + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + + + pxor %xmm5,%xmm2 + + + + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + + + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + + subq $1,%rax + jnz L$oop_row_3 + + + + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + +.byte 102,65,15,56,0,210 + movdqu %xmm2,(%rdi) + + + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + pxor %xmm4,%xmm4 + pxor %xmm5,%xmm5 + pxor %xmm6,%xmm6 + .byte 0xf3,0xc3 +L$gmult_seh_end: + + + + + + + + +.globl _gcm_ghash_ssse3 +.private_extern _gcm_ghash_ssse3 +.p2align 4 +_gcm_ghash_ssse3: +L$ghash_seh_begin: + + movdqu (%rdi),%xmm0 + movdqa L$reverse_bytes(%rip),%xmm10 + movdqa L$low4_mask(%rip),%xmm11 + + + andq $-16,%rcx + + + +.byte 102,65,15,56,0,194 + + + pxor %xmm3,%xmm3 +L$oop_ghash: + + movdqu (%rdx),%xmm1 +.byte 102,65,15,56,0,202 + pxor %xmm1,%xmm0 + + + movdqa %xmm11,%xmm1 + pandn %xmm0,%xmm1 + psrld $4,%xmm1 + pand %xmm11,%xmm0 + + + + + pxor %xmm2,%xmm2 + + movq $5,%rax +L$oop_row_4: + movdqa (%rsi),%xmm4 + leaq 16(%rsi),%rsi + + + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + + + + + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + + + pxor %xmm5,%xmm2 + + + + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + + + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + + subq $1,%rax + jnz L$oop_row_4 + + + + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movq $5,%rax +L$oop_row_5: + movdqa (%rsi),%xmm4 + leaq 16(%rsi),%rsi + + + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + + + + + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + + + pxor %xmm5,%xmm2 + + + + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + + + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + + subq $1,%rax + jnz L$oop_row_5 + + + + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movq $6,%rax +L$oop_row_6: + movdqa (%rsi),%xmm4 + leaq 16(%rsi),%rsi + + + movdqa %xmm2,%xmm6 +.byte 102,15,58,15,243,1 + movdqa %xmm6,%xmm3 + psrldq $1,%xmm2 + + + + + movdqa %xmm4,%xmm5 +.byte 102,15,56,0,224 +.byte 102,15,56,0,233 + + + pxor %xmm5,%xmm2 + + + + movdqa %xmm4,%xmm5 + psllq $60,%xmm5 + movdqa %xmm5,%xmm6 + pslldq $8,%xmm6 + pxor %xmm6,%xmm3 + + + psrldq $8,%xmm5 + pxor %xmm5,%xmm2 + psrlq $4,%xmm4 + pxor %xmm4,%xmm2 + + subq $1,%rax + jnz L$oop_row_6 + + + + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $1,%xmm3 + pxor %xmm3,%xmm2 + psrlq $5,%xmm3 + pxor %xmm3,%xmm2 + pxor %xmm3,%xmm3 + movdqa %xmm2,%xmm0 + + + leaq -256(%rsi),%rsi + + + leaq 16(%rdx),%rdx + subq $16,%rcx + jnz L$oop_ghash + + +.byte 102,65,15,56,0,194 + movdqu %xmm0,(%rdi) + + + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + pxor %xmm4,%xmm4 + pxor %xmm5,%xmm5 + pxor %xmm6,%xmm6 + .byte 0xf3,0xc3 +L$ghash_seh_end: + + + +.p2align 4 + + +L$reverse_bytes: +.byte 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 + +L$low4_mask: +.quad 0x0f0f0f0f0f0f0f0f, 0x0f0f0f0f0f0f0f0f +#endif diff --git a/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/ghash-x86_64.S b/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/ghash-x86_64.S index 5256fbfa..d7dcf5d6 100644 --- a/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/ghash-x86_64.S +++ b/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/ghash-x86_64.S @@ -709,6 +709,7 @@ L$ghash_epilogue: .p2align 4 _gcm_init_clmul: + L$_init_clmul: movdqu (%rsi),%xmm2 pshufd $78,%xmm2,%xmm2 @@ -861,11 +862,13 @@ L$_init_clmul: movdqu %xmm4,80(%rdi) .byte 0xf3,0xc3 + .globl _gcm_gmult_clmul .private_extern _gcm_gmult_clmul .p2align 4 _gcm_gmult_clmul: + L$_gmult_clmul: movdqu (%rdi),%xmm0 movdqa L$bswap_mask(%rip),%xmm5 @@ -913,11 +916,13 @@ L$_gmult_clmul: movdqu %xmm0,(%rdi) .byte 0xf3,0xc3 + .globl _gcm_ghash_clmul .private_extern _gcm_ghash_clmul .p2align 5 _gcm_ghash_clmul: + L$_ghash_clmul: movdqa L$bswap_mask(%rip),%xmm10 @@ -1298,11 +1303,13 @@ L$done: movdqu %xmm0,(%rdi) .byte 0xf3,0xc3 + .globl _gcm_init_avx .private_extern _gcm_init_avx .p2align 5 _gcm_init_avx: + vzeroupper vmovdqu (%rsi),%xmm2 @@ -1406,18 +1413,22 @@ L$init_start_avx: vzeroupper .byte 0xf3,0xc3 + .globl _gcm_gmult_avx .private_extern _gcm_gmult_avx .p2align 5 _gcm_gmult_avx: + jmp L$_gmult_clmul + .globl _gcm_ghash_avx .private_extern _gcm_ghash_avx .p2align 5 _gcm_ghash_avx: + vzeroupper vmovdqu (%rdi),%xmm10 @@ -1790,6 +1801,7 @@ L$tail_no_xor_avx: vzeroupper .byte 0xf3,0xc3 + .p2align 6 L$bswap_mask: .byte 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 diff --git a/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/rdrand-x86_64.S b/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/rdrand-x86_64.S index e65b5d64..f6f2be7a 100644 --- a/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/rdrand-x86_64.S +++ b/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/rdrand-x86_64.S @@ -23,12 +23,10 @@ _CRYPTO_rdrand: xorq %rax,%rax - - -.byte 0x48, 0x0f, 0xc7, 0xf1 +.byte 72,15,199,242 adcq %rax,%rax - movq %rcx,0(%rdi) + movq %rdx,0(%rdi) .byte 0xf3,0xc3 @@ -36,6 +34,7 @@ _CRYPTO_rdrand: + .globl _CRYPTO_rdrand_multiple8_buf .private_extern _CRYPTO_rdrand_multiple8_buf @@ -46,9 +45,7 @@ _CRYPTO_rdrand_multiple8_buf: jz L$out movq $8,%rdx L$loop: - - -.byte 0x48, 0x0f, 0xc7, 0xf1 +.byte 72,15,199,241 jnc L$err movq %rcx,0(%rdi) addq %rdx,%rdi @@ -61,4 +58,5 @@ L$err: xorq %rax,%rax .byte 0xf3,0xc3 + #endif diff --git a/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/rsaz-avx2.S b/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/rsaz-avx2.S index e4345bdc..e9cae78c 100644 --- a/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/rsaz-avx2.S +++ b/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/rsaz-avx2.S @@ -1228,6 +1228,7 @@ L$mul_1024_epilogue: .p2align 5 _rsaz_1024_red2norm_avx2: + subq $-128,%rsi xorq %rax,%rax movq -128(%rsi),%r8 @@ -1421,11 +1422,13 @@ _rsaz_1024_red2norm_avx2: .byte 0xf3,0xc3 + .globl _rsaz_1024_norm2red_avx2 .private_extern _rsaz_1024_norm2red_avx2 .p2align 5 _rsaz_1024_norm2red_avx2: + subq $-128,%rdi movq (%rsi),%r8 movl $0x1fffffff,%eax @@ -1579,11 +1582,13 @@ _rsaz_1024_norm2red_avx2: movq %r8,184(%rdi) .byte 0xf3,0xc3 + .globl _rsaz_1024_scatter5_avx2 .private_extern _rsaz_1024_scatter5_avx2 .p2align 5 _rsaz_1024_scatter5_avx2: + vzeroupper vmovdqu L$scatter_permd(%rip),%ymm5 shll $4,%edx @@ -1605,6 +1610,7 @@ L$oop_scatter_1024: .byte 0xf3,0xc3 + .globl _rsaz_1024_gather5_avx2 .private_extern _rsaz_1024_gather5_avx2 @@ -1727,24 +1733,6 @@ L$oop_gather_1024: L$SEH_end_rsaz_1024_gather5: - -.globl _rsaz_avx2_eligible -.private_extern _rsaz_avx2_eligible - -.p2align 5 -_rsaz_avx2_eligible: - leaq _OPENSSL_ia32cap_P(%rip),%rax - movl 8(%rax),%eax - movl $524544,%ecx - movl $0,%edx - andl %eax,%ecx - cmpl $524544,%ecx - cmovel %edx,%eax - andl $32,%eax - shrl $5,%eax - .byte 0xf3,0xc3 - - .p2align 6 L$and_mask: .quad 0x1fffffff,0x1fffffff,0x1fffffff,0x1fffffff diff --git a/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/vpaes-x86_64.S b/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/vpaes-x86_64.S index 2733c07e..2f60a22c 100644 --- a/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/vpaes-x86_64.S +++ b/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/vpaes-x86_64.S @@ -121,6 +121,181 @@ L$enc_entry: + + + + + + + + + + + + + + + + + + + + + + + + +.p2align 4 +_vpaes_encrypt_core_2x: + + movq %rdx,%r9 + movq $16,%r11 + movl 240(%rdx),%eax + movdqa %xmm9,%xmm1 + movdqa %xmm9,%xmm7 + movdqa L$k_ipt(%rip),%xmm2 + movdqa %xmm2,%xmm8 + pandn %xmm0,%xmm1 + pandn %xmm6,%xmm7 + movdqu (%r9),%xmm5 + + psrld $4,%xmm1 + psrld $4,%xmm7 + pand %xmm9,%xmm0 + pand %xmm9,%xmm6 +.byte 102,15,56,0,208 +.byte 102,68,15,56,0,198 + movdqa L$k_ipt+16(%rip),%xmm0 + movdqa %xmm0,%xmm6 +.byte 102,15,56,0,193 +.byte 102,15,56,0,247 + pxor %xmm5,%xmm2 + pxor %xmm5,%xmm8 + addq $16,%r9 + pxor %xmm2,%xmm0 + pxor %xmm8,%xmm6 + leaq L$k_mc_backward(%rip),%r10 + jmp L$enc2x_entry + +.p2align 4 +L$enc2x_loop: + + movdqa L$k_sb1(%rip),%xmm4 + movdqa L$k_sb1+16(%rip),%xmm0 + movdqa %xmm4,%xmm12 + movdqa %xmm0,%xmm6 +.byte 102,15,56,0,226 +.byte 102,69,15,56,0,224 +.byte 102,15,56,0,195 +.byte 102,65,15,56,0,243 + pxor %xmm5,%xmm4 + pxor %xmm5,%xmm12 + movdqa L$k_sb2(%rip),%xmm5 + movdqa %xmm5,%xmm13 + pxor %xmm4,%xmm0 + pxor %xmm12,%xmm6 + movdqa -64(%r11,%r10,1),%xmm1 + +.byte 102,15,56,0,234 +.byte 102,69,15,56,0,232 + movdqa (%r11,%r10,1),%xmm4 + + movdqa L$k_sb2+16(%rip),%xmm2 + movdqa %xmm2,%xmm8 +.byte 102,15,56,0,211 +.byte 102,69,15,56,0,195 + movdqa %xmm0,%xmm3 + movdqa %xmm6,%xmm11 + pxor %xmm5,%xmm2 + pxor %xmm13,%xmm8 +.byte 102,15,56,0,193 +.byte 102,15,56,0,241 + addq $16,%r9 + pxor %xmm2,%xmm0 + pxor %xmm8,%xmm6 +.byte 102,15,56,0,220 +.byte 102,68,15,56,0,220 + addq $16,%r11 + pxor %xmm0,%xmm3 + pxor %xmm6,%xmm11 +.byte 102,15,56,0,193 +.byte 102,15,56,0,241 + andq $0x30,%r11 + subq $1,%rax + pxor %xmm3,%xmm0 + pxor %xmm11,%xmm6 + +L$enc2x_entry: + + movdqa %xmm9,%xmm1 + movdqa %xmm9,%xmm7 + movdqa L$k_inv+16(%rip),%xmm5 + movdqa %xmm5,%xmm13 + pandn %xmm0,%xmm1 + pandn %xmm6,%xmm7 + psrld $4,%xmm1 + psrld $4,%xmm7 + pand %xmm9,%xmm0 + pand %xmm9,%xmm6 +.byte 102,15,56,0,232 +.byte 102,68,15,56,0,238 + movdqa %xmm10,%xmm3 + movdqa %xmm10,%xmm11 + pxor %xmm1,%xmm0 + pxor %xmm7,%xmm6 +.byte 102,15,56,0,217 +.byte 102,68,15,56,0,223 + movdqa %xmm10,%xmm4 + movdqa %xmm10,%xmm12 + pxor %xmm5,%xmm3 + pxor %xmm13,%xmm11 +.byte 102,15,56,0,224 +.byte 102,68,15,56,0,230 + movdqa %xmm10,%xmm2 + movdqa %xmm10,%xmm8 + pxor %xmm5,%xmm4 + pxor %xmm13,%xmm12 +.byte 102,15,56,0,211 +.byte 102,69,15,56,0,195 + movdqa %xmm10,%xmm3 + movdqa %xmm10,%xmm11 + pxor %xmm0,%xmm2 + pxor %xmm6,%xmm8 +.byte 102,15,56,0,220 +.byte 102,69,15,56,0,220 + movdqu (%r9),%xmm5 + + pxor %xmm1,%xmm3 + pxor %xmm7,%xmm11 + jnz L$enc2x_loop + + + movdqa -96(%r10),%xmm4 + movdqa -80(%r10),%xmm0 + movdqa %xmm4,%xmm12 + movdqa %xmm0,%xmm6 +.byte 102,15,56,0,226 +.byte 102,69,15,56,0,224 + pxor %xmm5,%xmm4 + pxor %xmm5,%xmm12 +.byte 102,15,56,0,195 +.byte 102,65,15,56,0,243 + movdqa 64(%r11,%r10,1),%xmm1 + + pxor %xmm4,%xmm0 + pxor %xmm12,%xmm6 +.byte 102,15,56,0,193 +.byte 102,15,56,0,241 + .byte 0xf3,0xc3 + + + + + + + + + .p2align 4 _vpaes_decrypt_core: @@ -637,6 +812,13 @@ L$schedule_mangle_both: .p2align 4 _vpaes_set_encrypt_key: +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS + + movb $1,_BORINGSSL_function_hit+5(%rip) +#endif +#endif + movl %esi,%eax shrl $5,%eax addl $5,%eax @@ -680,6 +862,12 @@ _vpaes_set_decrypt_key: .p2align 4 _vpaes_encrypt: +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS + + movb $1,_BORINGSSL_function_hit+4(%rip) +#endif +#endif movdqu (%rdi),%xmm0 call _vpaes_preheat call _vpaes_encrypt_core @@ -744,6 +932,69 @@ L$cbc_abort: .byte 0xf3,0xc3 +.globl _vpaes_ctr32_encrypt_blocks +.private_extern _vpaes_ctr32_encrypt_blocks + +.p2align 4 +_vpaes_ctr32_encrypt_blocks: + + + xchgq %rcx,%rdx + testq %rcx,%rcx + jz L$ctr32_abort + movdqu (%r8),%xmm0 + movdqa L$ctr_add_one(%rip),%xmm8 + subq %rdi,%rsi + call _vpaes_preheat + movdqa %xmm0,%xmm6 + pshufb L$rev_ctr(%rip),%xmm6 + + testq $1,%rcx + jz L$ctr32_prep_loop + + + + movdqu (%rdi),%xmm7 + call _vpaes_encrypt_core + pxor %xmm7,%xmm0 + paddd %xmm8,%xmm6 + movdqu %xmm0,(%rsi,%rdi,1) + subq $1,%rcx + leaq 16(%rdi),%rdi + jz L$ctr32_done + +L$ctr32_prep_loop: + + + movdqa %xmm6,%xmm14 + movdqa %xmm6,%xmm15 + paddd %xmm8,%xmm15 + +L$ctr32_loop: + movdqa L$rev_ctr(%rip),%xmm1 + movdqa %xmm14,%xmm0 + movdqa %xmm15,%xmm6 +.byte 102,15,56,0,193 +.byte 102,15,56,0,241 + call _vpaes_encrypt_core_2x + movdqu (%rdi),%xmm1 + movdqu 16(%rdi),%xmm2 + movdqa L$ctr_add_two(%rip),%xmm3 + pxor %xmm1,%xmm0 + pxor %xmm2,%xmm6 + paddd %xmm3,%xmm14 + paddd %xmm3,%xmm15 + movdqu %xmm0,(%rsi,%rdi,1) + movdqu %xmm6,16(%rsi,%rdi,1) + subq $2,%rcx + leaq 32(%rdi),%rdi + jnz L$ctr32_loop + +L$ctr32_done: +L$ctr32_abort: + .byte 0xf3,0xc3 + + @@ -866,6 +1117,17 @@ L$k_dsbe: L$k_dsbo: .quad 0x1387EA537EF94000, 0xC7AA6DB9D4943E2D .quad 0x12D7560F93441D00, 0xCA4B8159D8C58E9C + + +L$rev_ctr: +.quad 0x0706050403020100, 0x0c0d0e0f0b0a0908 + + +L$ctr_add_one: +.quad 0x0000000000000000, 0x0000000100000000 +L$ctr_add_two: +.quad 0x0000000000000000, 0x0000000200000000 + .byte 86,101,99,116,111,114,32,80,101,114,109,117,116,97,116,105,111,110,32,65,69,83,32,102,111,114,32,120,56,54,95,54,52,47,83,83,83,69,51,44,32,77,105,107,101,32,72,97,109,98,117,114,103,32,40,83,116,97,110,102,111,114,100,32,85,110,105,118,101,114,115,105,116,121,41,0 .p2align 6 diff --git a/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/x86_64-mont5.S b/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/x86_64-mont5.S index b3438c24..4bd36fea 100644 --- a/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/x86_64-mont5.S +++ b/third_party/boringssl/kit/mac-x86_64/crypto/fipsmodule/x86_64-mont5.S @@ -565,6 +565,7 @@ L$mul4x_epilogue: .p2align 5 mul4x_internal: + shlq $5,%r9 movd 8(%rax),%xmm5 leaq L$inc(%rip),%rax @@ -1087,6 +1088,7 @@ L$inner4x: movq 24(%rbp),%r15 jmp L$sqr4x_sub_entry + .globl _bn_power5 .private_extern _bn_power5 @@ -1302,6 +1304,7 @@ __bn_sqr8x_internal: + leaq 32(%r10),%rbp @@ -2007,8 +2010,10 @@ L$8x_no_tail: .byte 0xf3,0xc3 + .p2align 5 __bn_post4x_internal: + movq 0(%rbp),%r12 leaq (%rdi,%r9,1),%rbx movq %r9,%rcx @@ -2060,11 +2065,13 @@ L$sqr4x_sub_entry: negq %r9 .byte 0xf3,0xc3 + .globl _bn_from_montgomery .private_extern _bn_from_montgomery .p2align 5 _bn_from_montgomery: + testl $7,%r9d jz bn_from_mont8x xorl %eax,%eax @@ -2072,6 +2079,7 @@ _bn_from_montgomery: + .p2align 5 bn_from_mont8x: @@ -2353,6 +2361,7 @@ L$mulx4x_epilogue: .p2align 5 mulx4x_internal: + movq %r9,8(%rsp) movq %r9,%r10 negq %r9 @@ -2773,6 +2782,7 @@ L$mulx4x_inner: jmp L$sqrx4x_sub_entry + .p2align 5 bn_powerx5: @@ -3529,7 +3539,9 @@ L$sqrx8x_no_tail: .p2align 5 + __bn_postx4x_internal: + movq 0(%rbp),%r12 movq %rcx,%r10 movq %rcx,%r9 @@ -3578,11 +3590,13 @@ L$sqrx4x_sub_entry: .byte 0xf3,0xc3 + .globl _bn_scatter5 .private_extern _bn_scatter5 .p2align 4 _bn_scatter5: + cmpl $0,%esi jz L$scatter_epilogue leaq (%rdx,%rcx,8),%rdx @@ -3597,14 +3611,17 @@ L$scatter_epilogue: .byte 0xf3,0xc3 + .globl _bn_gather5 .private_extern _bn_gather5 .p2align 5 _bn_gather5: + L$SEH_begin_bn_gather5: .byte 0x4c,0x8d,0x14,0x24 + .byte 0x48,0x81,0xec,0x08,0x01,0x00,0x00 leaq L$inc(%rip),%rax andq $-16,%rsp @@ -3758,9 +3775,11 @@ L$gather: jnz L$gather leaq (%r10),%rsp + .byte 0xf3,0xc3 L$SEH_end_bn_gather5: + .p2align 6 L$inc: .long 0,0, 1,1 diff --git a/third_party/boringssl/kit/mac-x86_64/crypto/test/trampoline-x86_64.S b/third_party/boringssl/kit/mac-x86_64/crypto/test/trampoline-x86_64.S index 0245eab8..863e6b04 100644 --- a/third_party/boringssl/kit/mac-x86_64/crypto/test/trampoline-x86_64.S +++ b/third_party/boringssl/kit/mac-x86_64/crypto/test/trampoline-x86_64.S @@ -25,7 +25,7 @@ .private_extern _abi_test_trampoline .p2align 4 _abi_test_trampoline: -L$abi_test_trampoline_begin: +L$abi_test_trampoline_seh_begin: @@ -38,27 +38,27 @@ L$abi_test_trampoline_begin: subq $120,%rsp -L$abi_test_trampoline_prolog_alloc: +L$abi_test_trampoline_seh_prolog_alloc: movq %r8,48(%rsp) movq %rbx,64(%rsp) -L$abi_test_trampoline_prolog_rbx: +L$abi_test_trampoline_seh_prolog_rbx: movq %rbp,72(%rsp) -L$abi_test_trampoline_prolog_rbp: +L$abi_test_trampoline_seh_prolog_rbp: movq %r12,80(%rsp) -L$abi_test_trampoline_prolog_r12: +L$abi_test_trampoline_seh_prolog_r12: movq %r13,88(%rsp) -L$abi_test_trampoline_prolog_r13: +L$abi_test_trampoline_seh_prolog_r13: movq %r14,96(%rsp) -L$abi_test_trampoline_prolog_r14: +L$abi_test_trampoline_seh_prolog_r14: movq %r15,104(%rsp) -L$abi_test_trampoline_prolog_r15: -L$abi_test_trampoline_prolog_end: +L$abi_test_trampoline_seh_prolog_r15: +L$abi_test_trampoline_seh_prolog_end: movq 0(%rsi),%rbx movq 8(%rsi),%rbp movq 16(%rsi),%r12 @@ -182,7 +182,7 @@ L$call_done: .byte 0xf3,0xc3 -L$abi_test_trampoline_end: +L$abi_test_trampoline_seh_end: .globl _abi_test_clobber_rax @@ -441,11 +441,18 @@ _abi_test_clobber_xmm15: .p2align 4 _abi_test_bad_unwind_wrong_register: +L$abi_test_bad_unwind_wrong_register_seh_begin: pushq %r12 +L$abi_test_bad_unwind_wrong_register_seh_push_r13: + + + + nop popq %r12 .byte 0xf3,0xc3 +L$abi_test_bad_unwind_wrong_register_seh_end: @@ -458,20 +465,24 @@ _abi_test_bad_unwind_wrong_register: .p2align 4 _abi_test_bad_unwind_temporary: +L$abi_test_bad_unwind_temporary_seh_begin: pushq %r12 +L$abi_test_bad_unwind_temporary_seh_push_r12: + + movq %r12,%rax + incq %rax + movq %rax,(%rsp) - incq %r12 - movq %r12,(%rsp) - decq %r12 movq %r12,(%rsp) popq %r12 .byte 0xf3,0xc3 +L$abi_test_bad_unwind_temporary_seh_end: @@ -485,7 +496,7 @@ _abi_test_get_and_clear_direction_flag: pushfq popq %rax andq $0x400,%rax - shlq $10,%rax + shrq $10,%rax cld .byte 0xf3,0xc3 diff --git a/third_party/boringssl/kit/mac-x86_64/crypto/third_party/sike/asm/fp-x86_64.S b/third_party/boringssl/kit/mac-x86_64/crypto/third_party/sike/asm/fp-x86_64.S new file mode 100644 index 00000000..2fd33e90 --- /dev/null +++ b/third_party/boringssl/kit/mac-x86_64/crypto/third_party/sike/asm/fp-x86_64.S @@ -0,0 +1,2085 @@ +# This file is generated from a similarly-named Perl script in the BoringSSL +# source tree. Do not edit by hand. + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) +#define OPENSSL_NO_ASM +#endif +#endif + +#if defined(__x86_64__) && !defined(OPENSSL_NO_ASM) +#if defined(BORINGSSL_PREFIX) +#include +#endif +.text + + +L$p503x2: +.quad 0xFFFFFFFFFFFFFFFE +.quad 0xFFFFFFFFFFFFFFFF +.quad 0x57FFFFFFFFFFFFFF +.quad 0x2610B7B44423CF41 +.quad 0x3737ED90F6FCFB5E +.quad 0xC08B8D7BB4EF49A0 +.quad 0x0080CDEA83023C3C + + +L$p503p1: +.quad 0xAC00000000000000 +.quad 0x13085BDA2211E7A0 +.quad 0x1B9BF6C87B7E7DAF +.quad 0x6045C6BDDA77A4D0 +.quad 0x004066F541811E1E + +L$p503p1_nz: +.quad 0xAC00000000000000 +.quad 0x13085BDA2211E7A0 +.quad 0x1B9BF6C87B7E7DAF +.quad 0x6045C6BDDA77A4D0 +.quad 0x004066F541811E1E + + +.private_extern _OPENSSL_ia32cap_P + +.globl _sike_fpadd +.private_extern _sike_fpadd + +_sike_fpadd: + + pushq %r12 + + + pushq %r13 + + + pushq %r14 + + + pushq %r15 + + + + xorq %rax,%rax + + movq 0(%rdi),%r8 + movq 8(%rdi),%r9 + movq 16(%rdi),%r10 + movq 24(%rdi),%r11 + movq 32(%rdi),%r12 + movq 40(%rdi),%r13 + movq 48(%rdi),%r14 + movq 56(%rdi),%r15 + + addq 0(%rsi),%r8 + adcq 8(%rsi),%r9 + adcq 16(%rsi),%r10 + adcq 24(%rsi),%r11 + adcq 32(%rsi),%r12 + adcq 40(%rsi),%r13 + adcq 48(%rsi),%r14 + adcq 56(%rsi),%r15 + + movq L$p503x2(%rip),%rcx; + subq %rcx,%r8 + movq 8+L$p503x2(%rip),%rcx; + sbbq %rcx,%r9 + sbbq %rcx,%r10 + movq 16+L$p503x2(%rip),%rcx; + sbbq %rcx,%r11 + movq 24+L$p503x2(%rip),%rcx; + sbbq %rcx,%r12 + movq 32+L$p503x2(%rip),%rcx; + sbbq %rcx,%r13 + movq 40+L$p503x2(%rip),%rcx; + sbbq %rcx,%r14 + movq 48+L$p503x2(%rip),%rcx; + sbbq %rcx,%r15 + sbbq $0,%rax + + movq L$p503x2(%rip),%rdi + andq %rax,%rdi + movq 8+L$p503x2(%rip),%rsi + andq %rax,%rsi + movq 16+L$p503x2(%rip),%rcx + andq %rax,%rcx + + addq %rdi,%r8 + movq %r8,0(%rdx) + adcq %rsi,%r9 + movq %r9,8(%rdx) + adcq %rsi,%r10 + movq %r10,16(%rdx) + adcq %rcx,%r11 + movq %r11,24(%rdx) + + setc %cl + + movq 24+L$p503x2(%rip),%r8 + andq %rax,%r8 + movq 32+L$p503x2(%rip),%r9 + andq %rax,%r9 + movq 40+L$p503x2(%rip),%r10 + andq %rax,%r10 + movq 48+L$p503x2(%rip),%r11 + andq %rax,%r11 + + btq $0,%rcx + + adcq %r8,%r12 + movq %r12,32(%rdx) + adcq %r9,%r13 + movq %r13,40(%rdx) + adcq %r10,%r14 + movq %r14,48(%rdx) + adcq %r11,%r15 + movq %r15,56(%rdx) + + popq %r15 + + popq %r14 + + popq %r13 + + popq %r12 + + .byte 0xf3,0xc3 + +.globl _sike_cswap_asm +.private_extern _sike_cswap_asm + +_sike_cswap_asm: + + + movq %rdx,%xmm3 + + + + + + pshufd $68,%xmm3,%xmm3 + + movdqu 0(%rdi),%xmm0 + movdqu 0(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,0(%rdi) + movdqu %xmm1,0(%rsi) + + movdqu 16(%rdi),%xmm0 + movdqu 16(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,16(%rdi) + movdqu %xmm1,16(%rsi) + + movdqu 32(%rdi),%xmm0 + movdqu 32(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,32(%rdi) + movdqu %xmm1,32(%rsi) + + movdqu 48(%rdi),%xmm0 + movdqu 48(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,48(%rdi) + movdqu %xmm1,48(%rsi) + + movdqu 64(%rdi),%xmm0 + movdqu 64(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,64(%rdi) + movdqu %xmm1,64(%rsi) + + movdqu 80(%rdi),%xmm0 + movdqu 80(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,80(%rdi) + movdqu %xmm1,80(%rsi) + + movdqu 96(%rdi),%xmm0 + movdqu 96(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,96(%rdi) + movdqu %xmm1,96(%rsi) + + movdqu 112(%rdi),%xmm0 + movdqu 112(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,112(%rdi) + movdqu %xmm1,112(%rsi) + + movdqu 128(%rdi),%xmm0 + movdqu 128(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,128(%rdi) + movdqu %xmm1,128(%rsi) + + movdqu 144(%rdi),%xmm0 + movdqu 144(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,144(%rdi) + movdqu %xmm1,144(%rsi) + + movdqu 160(%rdi),%xmm0 + movdqu 160(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,160(%rdi) + movdqu %xmm1,160(%rsi) + + movdqu 176(%rdi),%xmm0 + movdqu 176(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,176(%rdi) + movdqu %xmm1,176(%rsi) + + movdqu 192(%rdi),%xmm0 + movdqu 192(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,192(%rdi) + movdqu %xmm1,192(%rsi) + + movdqu 208(%rdi),%xmm0 + movdqu 208(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,208(%rdi) + movdqu %xmm1,208(%rsi) + + movdqu 224(%rdi),%xmm0 + movdqu 224(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,224(%rdi) + movdqu %xmm1,224(%rsi) + + movdqu 240(%rdi),%xmm0 + movdqu 240(%rsi),%xmm1 + movdqa %xmm1,%xmm2 + pxor %xmm0,%xmm2 + pand %xmm3,%xmm2 + pxor %xmm2,%xmm0 + pxor %xmm2,%xmm1 + movdqu %xmm0,240(%rdi) + movdqu %xmm1,240(%rsi) + + .byte 0xf3,0xc3 +.globl _sike_fpsub +.private_extern _sike_fpsub + +_sike_fpsub: + + pushq %r12 + + + pushq %r13 + + + pushq %r14 + + + pushq %r15 + + + + xorq %rax,%rax + + movq 0(%rdi),%r8 + movq 8(%rdi),%r9 + movq 16(%rdi),%r10 + movq 24(%rdi),%r11 + movq 32(%rdi),%r12 + movq 40(%rdi),%r13 + movq 48(%rdi),%r14 + movq 56(%rdi),%r15 + + subq 0(%rsi),%r8 + sbbq 8(%rsi),%r9 + sbbq 16(%rsi),%r10 + sbbq 24(%rsi),%r11 + sbbq 32(%rsi),%r12 + sbbq 40(%rsi),%r13 + sbbq 48(%rsi),%r14 + sbbq 56(%rsi),%r15 + sbbq $0x0,%rax + + movq L$p503x2(%rip),%rdi + andq %rax,%rdi + movq 8+L$p503x2(%rip),%rsi + andq %rax,%rsi + movq 16+L$p503x2(%rip),%rcx + andq %rax,%rcx + + addq %rdi,%r8 + adcq %rsi,%r9 + adcq %rsi,%r10 + adcq %rcx,%r11 + movq %r8,0(%rdx) + movq %r9,8(%rdx) + movq %r10,16(%rdx) + movq %r11,24(%rdx) + + setc %cl + + movq 24+L$p503x2(%rip),%r8 + andq %rax,%r8 + movq 32+L$p503x2(%rip),%r9 + andq %rax,%r9 + movq 40+L$p503x2(%rip),%r10 + andq %rax,%r10 + movq 48+L$p503x2(%rip),%r11 + andq %rax,%r11 + + btq $0x0,%rcx + + adcq %r8,%r12 + adcq %r9,%r13 + adcq %r10,%r14 + adcq %r11,%r15 + movq %r12,32(%rdx) + movq %r13,40(%rdx) + movq %r14,48(%rdx) + movq %r15,56(%rdx) + + popq %r15 + + popq %r14 + + popq %r13 + + popq %r12 + + .byte 0xf3,0xc3 + +.globl _sike_mpadd_asm +.private_extern _sike_mpadd_asm + +_sike_mpadd_asm: + + movq 0(%rdi),%r8 + movq 8(%rdi),%r9 + movq 16(%rdi),%r10 + movq 24(%rdi),%r11 + addq 0(%rsi),%r8 + adcq 8(%rsi),%r9 + adcq 16(%rsi),%r10 + adcq 24(%rsi),%r11 + movq %r8,0(%rdx) + movq %r9,8(%rdx) + movq %r10,16(%rdx) + movq %r11,24(%rdx) + + movq 32(%rdi),%r8 + movq 40(%rdi),%r9 + movq 48(%rdi),%r10 + movq 56(%rdi),%r11 + adcq 32(%rsi),%r8 + adcq 40(%rsi),%r9 + adcq 48(%rsi),%r10 + adcq 56(%rsi),%r11 + movq %r8,32(%rdx) + movq %r9,40(%rdx) + movq %r10,48(%rdx) + movq %r11,56(%rdx) + .byte 0xf3,0xc3 + +.globl _sike_mpsubx2_asm +.private_extern _sike_mpsubx2_asm + +_sike_mpsubx2_asm: + + xorq %rax,%rax + + movq 0(%rdi),%r8 + movq 8(%rdi),%r9 + movq 16(%rdi),%r10 + movq 24(%rdi),%r11 + movq 32(%rdi),%rcx + subq 0(%rsi),%r8 + sbbq 8(%rsi),%r9 + sbbq 16(%rsi),%r10 + sbbq 24(%rsi),%r11 + sbbq 32(%rsi),%rcx + movq %r8,0(%rdx) + movq %r9,8(%rdx) + movq %r10,16(%rdx) + movq %r11,24(%rdx) + movq %rcx,32(%rdx) + + movq 40(%rdi),%r8 + movq 48(%rdi),%r9 + movq 56(%rdi),%r10 + movq 64(%rdi),%r11 + movq 72(%rdi),%rcx + sbbq 40(%rsi),%r8 + sbbq 48(%rsi),%r9 + sbbq 56(%rsi),%r10 + sbbq 64(%rsi),%r11 + sbbq 72(%rsi),%rcx + movq %r8,40(%rdx) + movq %r9,48(%rdx) + movq %r10,56(%rdx) + movq %r11,64(%rdx) + movq %rcx,72(%rdx) + + movq 80(%rdi),%r8 + movq 88(%rdi),%r9 + movq 96(%rdi),%r10 + movq 104(%rdi),%r11 + movq 112(%rdi),%rcx + sbbq 80(%rsi),%r8 + sbbq 88(%rsi),%r9 + sbbq 96(%rsi),%r10 + sbbq 104(%rsi),%r11 + sbbq 112(%rsi),%rcx + movq %r8,80(%rdx) + movq %r9,88(%rdx) + movq %r10,96(%rdx) + movq %r11,104(%rdx) + movq %rcx,112(%rdx) + + movq 120(%rdi),%r8 + sbbq 120(%rsi),%r8 + sbbq $0x0,%rax + movq %r8,120(%rdx) + .byte 0xf3,0xc3 + +.globl _sike_mpdblsubx2_asm +.private_extern _sike_mpdblsubx2_asm + +_sike_mpdblsubx2_asm: + + pushq %r12 + + + pushq %r13 + + + pushq %r14 + + + + xorq %rax,%rax + + movq 0(%rdx),%r8 + movq 8(%rdx),%r9 + movq 16(%rdx),%r10 + movq 24(%rdx),%r11 + movq 32(%rdx),%r12 + movq 40(%rdx),%r13 + movq 48(%rdx),%r14 + movq 56(%rdx),%rcx + subq 0(%rdi),%r8 + sbbq 8(%rdi),%r9 + sbbq 16(%rdi),%r10 + sbbq 24(%rdi),%r11 + sbbq 32(%rdi),%r12 + sbbq 40(%rdi),%r13 + sbbq 48(%rdi),%r14 + sbbq 56(%rdi),%rcx + adcq $0x0,%rax + + subq 0(%rsi),%r8 + sbbq 8(%rsi),%r9 + sbbq 16(%rsi),%r10 + sbbq 24(%rsi),%r11 + sbbq 32(%rsi),%r12 + sbbq 40(%rsi),%r13 + sbbq 48(%rsi),%r14 + sbbq 56(%rsi),%rcx + adcq $0x0,%rax + + movq %r8,0(%rdx) + movq %r9,8(%rdx) + movq %r10,16(%rdx) + movq %r11,24(%rdx) + movq %r12,32(%rdx) + movq %r13,40(%rdx) + movq %r14,48(%rdx) + movq %rcx,56(%rdx) + + movq 64(%rdx),%r8 + movq 72(%rdx),%r9 + movq 80(%rdx),%r10 + movq 88(%rdx),%r11 + movq 96(%rdx),%r12 + movq 104(%rdx),%r13 + movq 112(%rdx),%r14 + movq 120(%rdx),%rcx + + subq %rax,%r8 + sbbq 64(%rdi),%r8 + sbbq 72(%rdi),%r9 + sbbq 80(%rdi),%r10 + sbbq 88(%rdi),%r11 + sbbq 96(%rdi),%r12 + sbbq 104(%rdi),%r13 + sbbq 112(%rdi),%r14 + sbbq 120(%rdi),%rcx + subq 64(%rsi),%r8 + sbbq 72(%rsi),%r9 + sbbq 80(%rsi),%r10 + sbbq 88(%rsi),%r11 + sbbq 96(%rsi),%r12 + sbbq 104(%rsi),%r13 + sbbq 112(%rsi),%r14 + sbbq 120(%rsi),%rcx + + movq %r8,64(%rdx) + movq %r9,72(%rdx) + movq %r10,80(%rdx) + movq %r11,88(%rdx) + movq %r12,96(%rdx) + movq %r13,104(%rdx) + movq %r14,112(%rdx) + movq %rcx,120(%rdx) + + popq %r14 + + popq %r13 + + popq %r12 + + .byte 0xf3,0xc3 + + +L$mul_mulx: + + + + + + + + + movq %rdx,%rcx + + + xorq %rax,%rax + movq (%rdi),%r8 + movq 8(%rdi),%r9 + movq 16(%rdi),%r10 + movq 24(%rdi),%r11 + pushq %rbx + + + + pushq %rbp + + + subq $96,%rsp + + addq 32(%rdi),%r8 + adcq 40(%rdi),%r9 + adcq 48(%rdi),%r10 + adcq 56(%rdi),%r11 + sbbq $0x0,%rax + movq %r8,(%rsp) + movq %r9,8(%rsp) + movq %r10,16(%rsp) + movq %r11,24(%rsp) + + + xorq %rbx,%rbx + movq (%rsi),%r12 + movq 8(%rsi),%r13 + movq 16(%rsi),%r14 + movq 24(%rsi),%r15 + addq 32(%rsi),%r12 + adcq 40(%rsi),%r13 + adcq 48(%rsi),%r14 + adcq 56(%rsi),%r15 + sbbq $0x0,%rbx + movq %r12,32(%rsp) + movq %r13,40(%rsp) + movq %r14,48(%rsp) + movq %r15,56(%rsp) + + + andq %rax,%r12 + andq %rax,%r13 + andq %rax,%r14 + andq %rax,%r15 + + + andq %rbx,%r8 + andq %rbx,%r9 + andq %rbx,%r10 + andq %rbx,%r11 + + + addq %r12,%r8 + adcq %r13,%r9 + adcq %r14,%r10 + adcq %r15,%r11 + movq %r8,64(%rsp) + movq %r9,72(%rsp) + movq %r10,80(%rsp) + movq %r11,88(%rsp) + + + movq 0+0(%rsp),%rdx + mulxq 32+0(%rsp),%r9,%r8 + movq %r9,64+0(%rcx) + mulxq 32+8(%rsp),%r10,%r9 + xorq %rax,%rax + adoxq %r10,%r8 + mulxq 32+16(%rsp),%r11,%r10 + adoxq %r11,%r9 + mulxq 32+24(%rsp),%r12,%r11 + adoxq %r12,%r10 + + movq 0+8(%rsp),%rdx + mulxq 32+0(%rsp),%r12,%r13 + adoxq %rax,%r11 + xorq %rax,%rax + mulxq 32+8(%rsp),%r15,%r14 + adoxq %r8,%r12 + movq %r12,64+8(%rcx) + adcxq %r15,%r13 + mulxq 32+16(%rsp),%rbx,%r15 + adcxq %rbx,%r14 + adoxq %r9,%r13 + mulxq 32+24(%rsp),%rbp,%rbx + adcxq %rbp,%r15 + adcxq %rax,%rbx + adoxq %r10,%r14 + + movq 0+16(%rsp),%rdx + mulxq 32+0(%rsp),%r8,%r9 + adoxq %r11,%r15 + adoxq %rax,%rbx + xorq %rax,%rax + mulxq 32+8(%rsp),%r11,%r10 + adoxq %r13,%r8 + movq %r8,64+16(%rcx) + adcxq %r11,%r9 + mulxq 32+16(%rsp),%r12,%r11 + adcxq %r12,%r10 + adoxq %r14,%r9 + mulxq 32+24(%rsp),%rbp,%r12 + adcxq %rbp,%r11 + + adcxq %rax,%r12 + adoxq %r15,%r10 + adoxq %rbx,%r11 + adoxq %rax,%r12 + + movq 0+24(%rsp),%rdx + mulxq 32+0(%rsp),%r8,%r13 + xorq %rax,%rax + mulxq 32+8(%rsp),%r15,%r14 + adcxq %r15,%r13 + adoxq %r8,%r9 + mulxq 32+16(%rsp),%rbx,%r15 + adcxq %rbx,%r14 + adoxq %r13,%r10 + mulxq 32+24(%rsp),%rbp,%rbx + adcxq %rbp,%r15 + adcxq %rax,%rbx + adoxq %r14,%r11 + adoxq %r15,%r12 + adoxq %rax,%rbx + movq %r9,64+24(%rcx) + movq %r10,64+32(%rcx) + movq %r11,64+40(%rcx) + movq %r12,64+48(%rcx) + movq %rbx,64+56(%rcx) + + + + movq 0+0(%rdi),%rdx + mulxq 0+0(%rsi),%r9,%r8 + movq %r9,0+0(%rcx) + mulxq 0+8(%rsi),%r10,%r9 + xorq %rax,%rax + adoxq %r10,%r8 + mulxq 0+16(%rsi),%r11,%r10 + adoxq %r11,%r9 + mulxq 0+24(%rsi),%r12,%r11 + adoxq %r12,%r10 + + movq 0+8(%rdi),%rdx + mulxq 0+0(%rsi),%r12,%r13 + adoxq %rax,%r11 + xorq %rax,%rax + mulxq 0+8(%rsi),%r15,%r14 + adoxq %r8,%r12 + movq %r12,0+8(%rcx) + adcxq %r15,%r13 + mulxq 0+16(%rsi),%rbx,%r15 + adcxq %rbx,%r14 + adoxq %r9,%r13 + mulxq 0+24(%rsi),%rbp,%rbx + adcxq %rbp,%r15 + adcxq %rax,%rbx + adoxq %r10,%r14 + + movq 0+16(%rdi),%rdx + mulxq 0+0(%rsi),%r8,%r9 + adoxq %r11,%r15 + adoxq %rax,%rbx + xorq %rax,%rax + mulxq 0+8(%rsi),%r11,%r10 + adoxq %r13,%r8 + movq %r8,0+16(%rcx) + adcxq %r11,%r9 + mulxq 0+16(%rsi),%r12,%r11 + adcxq %r12,%r10 + adoxq %r14,%r9 + mulxq 0+24(%rsi),%rbp,%r12 + adcxq %rbp,%r11 + + adcxq %rax,%r12 + adoxq %r15,%r10 + adoxq %rbx,%r11 + adoxq %rax,%r12 + + movq 0+24(%rdi),%rdx + mulxq 0+0(%rsi),%r8,%r13 + xorq %rax,%rax + mulxq 0+8(%rsi),%r15,%r14 + adcxq %r15,%r13 + adoxq %r8,%r9 + mulxq 0+16(%rsi),%rbx,%r15 + adcxq %rbx,%r14 + adoxq %r13,%r10 + mulxq 0+24(%rsi),%rbp,%rbx + adcxq %rbp,%r15 + adcxq %rax,%rbx + adoxq %r14,%r11 + adoxq %r15,%r12 + adoxq %rax,%rbx + movq %r9,0+24(%rcx) + movq %r10,0+32(%rcx) + movq %r11,0+40(%rcx) + movq %r12,0+48(%rcx) + movq %rbx,0+56(%rcx) + + + + movq 32+0(%rdi),%rdx + mulxq 32+0(%rsi),%r9,%r8 + movq %r9,0+0(%rsp) + mulxq 32+8(%rsi),%r10,%r9 + xorq %rax,%rax + adoxq %r10,%r8 + mulxq 32+16(%rsi),%r11,%r10 + adoxq %r11,%r9 + mulxq 32+24(%rsi),%r12,%r11 + adoxq %r12,%r10 + + movq 32+8(%rdi),%rdx + mulxq 32+0(%rsi),%r12,%r13 + adoxq %rax,%r11 + xorq %rax,%rax + mulxq 32+8(%rsi),%r15,%r14 + adoxq %r8,%r12 + movq %r12,0+8(%rsp) + adcxq %r15,%r13 + mulxq 32+16(%rsi),%rbx,%r15 + adcxq %rbx,%r14 + adoxq %r9,%r13 + mulxq 32+24(%rsi),%rbp,%rbx + adcxq %rbp,%r15 + adcxq %rax,%rbx + adoxq %r10,%r14 + + movq 32+16(%rdi),%rdx + mulxq 32+0(%rsi),%r8,%r9 + adoxq %r11,%r15 + adoxq %rax,%rbx + xorq %rax,%rax + mulxq 32+8(%rsi),%r11,%r10 + adoxq %r13,%r8 + movq %r8,0+16(%rsp) + adcxq %r11,%r9 + mulxq 32+16(%rsi),%r12,%r11 + adcxq %r12,%r10 + adoxq %r14,%r9 + mulxq 32+24(%rsi),%rbp,%r12 + adcxq %rbp,%r11 + + adcxq %rax,%r12 + adoxq %r15,%r10 + adoxq %rbx,%r11 + adoxq %rax,%r12 + + movq 32+24(%rdi),%rdx + mulxq 32+0(%rsi),%r8,%r13 + xorq %rax,%rax + mulxq 32+8(%rsi),%r15,%r14 + adcxq %r15,%r13 + adoxq %r8,%r9 + mulxq 32+16(%rsi),%rbx,%r15 + adcxq %rbx,%r14 + adoxq %r13,%r10 + mulxq 32+24(%rsi),%rbp,%rbx + adcxq %rbp,%r15 + adcxq %rax,%rbx + adoxq %r14,%r11 + adoxq %r15,%r12 + adoxq %rax,%rbx + movq %r9,0+24(%rsp) + movq %r10,0+32(%rsp) + movq %r11,0+40(%rsp) + movq %r12,0+48(%rsp) + movq %rbx,0+56(%rsp) + + + + + movq 64(%rsp),%r8 + movq 72(%rsp),%r9 + movq 80(%rsp),%r10 + movq 88(%rsp),%r11 + movq 96(%rcx),%rax + addq %rax,%r8 + movq 104(%rcx),%rax + adcq %rax,%r9 + movq 112(%rcx),%rax + adcq %rax,%r10 + movq 120(%rcx),%rax + adcq %rax,%r11 + + + movq 64(%rcx),%r12 + movq 72(%rcx),%r13 + movq 80(%rcx),%r14 + movq 88(%rcx),%r15 + subq (%rcx),%r12 + sbbq 8(%rcx),%r13 + sbbq 16(%rcx),%r14 + sbbq 24(%rcx),%r15 + sbbq 32(%rcx),%r8 + sbbq 40(%rcx),%r9 + sbbq 48(%rcx),%r10 + sbbq 56(%rcx),%r11 + + + subq (%rsp),%r12 + sbbq 8(%rsp),%r13 + sbbq 16(%rsp),%r14 + sbbq 24(%rsp),%r15 + sbbq 32(%rsp),%r8 + sbbq 40(%rsp),%r9 + sbbq 48(%rsp),%r10 + sbbq 56(%rsp),%r11 + + addq 32(%rcx),%r12 + movq %r12,32(%rcx) + adcq 40(%rcx),%r13 + movq %r13,40(%rcx) + adcq 48(%rcx),%r14 + movq %r14,48(%rcx) + adcq 56(%rcx),%r15 + movq %r15,56(%rcx) + movq (%rsp),%rax + adcq %rax,%r8 + movq %r8,64(%rcx) + movq 8(%rsp),%rax + adcq %rax,%r9 + movq %r9,72(%rcx) + movq 16(%rsp),%rax + adcq %rax,%r10 + movq %r10,80(%rcx) + movq 24(%rsp),%rax + adcq %rax,%r11 + movq %r11,88(%rcx) + movq 32(%rsp),%r12 + adcq $0x0,%r12 + movq %r12,96(%rcx) + movq 40(%rsp),%r13 + adcq $0x0,%r13 + movq %r13,104(%rcx) + movq 48(%rsp),%r14 + adcq $0x0,%r14 + movq %r14,112(%rcx) + movq 56(%rsp),%r15 + adcq $0x0,%r15 + movq %r15,120(%rcx) + + addq $96,%rsp + + popq %rbp + + + popq %rbx + + + popq %r15 + + + popq %r14 + + + popq %r13 + + + popq %r12 + + + .byte 0xf3,0xc3 + + +.globl _sike_mpmul +.private_extern _sike_mpmul + +_sike_mpmul: + + pushq %r12 + + + pushq %r13 + + + pushq %r14 + + + pushq %r15 + + + + leaq _OPENSSL_ia32cap_P(%rip),%rcx + movq 8(%rcx),%rcx + andl $0x80100,%ecx + cmpl $0x80100,%ecx + je L$mul_mulx + + + + movq %rdx,%rcx + + + xorq %rax,%rax + movq 32(%rdi),%r8 + movq 40(%rdi),%r9 + movq 48(%rdi),%r10 + movq 56(%rdi),%r11 + addq 0(%rdi),%r8 + adcq 8(%rdi),%r9 + adcq 16(%rdi),%r10 + adcq 24(%rdi),%r11 + movq %r8,0(%rcx) + movq %r9,8(%rcx) + movq %r10,16(%rcx) + movq %r11,24(%rcx) + sbbq $0,%rax + subq $80,%rsp + + + + xorq %rdx,%rdx + movq 32(%rsi),%r12 + movq 40(%rsi),%r13 + movq 48(%rsi),%r14 + movq 56(%rsi),%r15 + addq 0(%rsi),%r12 + adcq 8(%rsi),%r13 + adcq 16(%rsi),%r14 + adcq 24(%rsi),%r15 + sbbq $0x0,%rdx + movq %rax,64(%rsp) + movq %rdx,72(%rsp) + + + movq (%rcx),%rax + mulq %r12 + movq %rax,(%rsp) + movq %rdx,%r8 + + xorq %r9,%r9 + movq (%rcx),%rax + mulq %r13 + addq %rax,%r8 + adcq %rdx,%r9 + + xorq %r10,%r10 + movq 8(%rcx),%rax + mulq %r12 + addq %rax,%r8 + movq %r8,8(%rsp) + adcq %rdx,%r9 + adcq $0x0,%r10 + + xorq %r8,%r8 + movq (%rcx),%rax + mulq %r14 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 16(%rcx),%rax + mulq %r12 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 8(%rcx),%rax + mulq %r13 + addq %rax,%r9 + movq %r9,16(%rsp) + adcq %rdx,%r10 + adcq $0x0,%r8 + + xorq %r9,%r9 + movq (%rcx),%rax + mulq %r15 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq 24(%rcx),%rax + mulq %r12 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq 8(%rcx),%rax + mulq %r14 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq 16(%rcx),%rax + mulq %r13 + addq %rax,%r10 + movq %r10,24(%rsp) + adcq %rdx,%r8 + adcq $0x0,%r9 + + xorq %r10,%r10 + movq 8(%rcx),%rax + mulq %r15 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0x0,%r10 + + movq 24(%rcx),%rax + mulq %r13 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0x0,%r10 + + movq 16(%rcx),%rax + mulq %r14 + addq %rax,%r8 + movq %r8,32(%rsp) + adcq %rdx,%r9 + adcq $0x0,%r10 + + xorq %r11,%r11 + movq 16(%rcx),%rax + mulq %r15 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r11 + + movq 24(%rcx),%rax + mulq %r14 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r11 + + movq 24(%rcx),%rax + mulq %r15 + addq %rax,%r10 + adcq %rdx,%r11 + + movq 64(%rsp),%rax + andq %rax,%r12 + andq %rax,%r13 + andq %rax,%r14 + andq %rax,%r15 + addq %r8,%r12 + adcq %r9,%r13 + adcq %r10,%r14 + adcq %r11,%r15 + + movq 72(%rsp),%rax + movq (%rcx),%r8 + movq 8(%rcx),%r9 + movq 16(%rcx),%r10 + movq 24(%rcx),%r11 + andq %rax,%r8 + andq %rax,%r9 + andq %rax,%r10 + andq %rax,%r11 + addq %r12,%r8 + adcq %r13,%r9 + adcq %r14,%r10 + adcq %r15,%r11 + movq %r8,32(%rsp) + movq %r9,40(%rsp) + movq %r10,48(%rsp) + movq %r11,56(%rsp) + + movq (%rdi),%r11 + movq (%rsi),%rax + mulq %r11 + xorq %r9,%r9 + movq %rax,(%rcx) + movq %rdx,%r8 + + movq 16(%rdi),%r14 + movq 8(%rsi),%rax + mulq %r11 + xorq %r10,%r10 + addq %rax,%r8 + adcq %rdx,%r9 + + movq 8(%rdi),%r12 + movq (%rsi),%rax + mulq %r12 + addq %rax,%r8 + movq %r8,8(%rcx) + adcq %rdx,%r9 + adcq $0x0,%r10 + + xorq %r8,%r8 + movq 16(%rsi),%rax + mulq %r11 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq (%rsi),%r13 + movq %r14,%rax + mulq %r13 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 8(%rsi),%rax + mulq %r12 + addq %rax,%r9 + movq %r9,16(%rcx) + adcq %rdx,%r10 + adcq $0x0,%r8 + + xorq %r9,%r9 + movq 24(%rsi),%rax + mulq %r11 + movq 24(%rdi),%r15 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq %r15,%rax + mulq %r13 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq 16(%rsi),%rax + mulq %r12 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq 8(%rsi),%rax + mulq %r14 + addq %rax,%r10 + movq %r10,24(%rcx) + adcq %rdx,%r8 + adcq $0x0,%r9 + + xorq %r10,%r10 + movq 24(%rsi),%rax + mulq %r12 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0x0,%r10 + + movq 8(%rsi),%rax + mulq %r15 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0x0,%r10 + + movq 16(%rsi),%rax + mulq %r14 + addq %rax,%r8 + movq %r8,32(%rcx) + adcq %rdx,%r9 + adcq $0x0,%r10 + + xorq %r8,%r8 + movq 24(%rsi),%rax + mulq %r14 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 16(%rsi),%rax + mulq %r15 + addq %rax,%r9 + movq %r9,40(%rcx) + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 24(%rsi),%rax + mulq %r15 + addq %rax,%r10 + movq %r10,48(%rcx) + adcq %rdx,%r8 + movq %r8,56(%rcx) + + + movq 32(%rdi),%r11 + movq 32(%rsi),%rax + mulq %r11 + xorq %r9,%r9 + movq %rax,64(%rcx) + movq %rdx,%r8 + + movq 48(%rdi),%r14 + movq 40(%rsi),%rax + mulq %r11 + xorq %r10,%r10 + addq %rax,%r8 + adcq %rdx,%r9 + + movq 40(%rdi),%r12 + movq 32(%rsi),%rax + mulq %r12 + addq %rax,%r8 + movq %r8,72(%rcx) + adcq %rdx,%r9 + adcq $0x0,%r10 + + xorq %r8,%r8 + movq 48(%rsi),%rax + mulq %r11 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 32(%rsi),%r13 + movq %r14,%rax + mulq %r13 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 40(%rsi),%rax + mulq %r12 + addq %rax,%r9 + movq %r9,80(%rcx) + adcq %rdx,%r10 + adcq $0x0,%r8 + + xorq %r9,%r9 + movq 56(%rsi),%rax + mulq %r11 + movq 56(%rdi),%r15 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq %r15,%rax + mulq %r13 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq 48(%rsi),%rax + mulq %r12 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0x0,%r9 + + movq 40(%rsi),%rax + mulq %r14 + addq %rax,%r10 + movq %r10,88(%rcx) + adcq %rdx,%r8 + adcq $0x0,%r9 + + xorq %r10,%r10 + movq 56(%rsi),%rax + mulq %r12 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0x0,%r10 + + movq 40(%rsi),%rax + mulq %r15 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0x0,%r10 + + movq 48(%rsi),%rax + mulq %r14 + addq %rax,%r8 + movq %r8,96(%rcx) + adcq %rdx,%r9 + adcq $0x0,%r10 + + xorq %r8,%r8 + movq 56(%rsi),%rax + mulq %r14 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 48(%rsi),%rax + mulq %r15 + addq %rax,%r9 + movq %r9,104(%rcx) + adcq %rdx,%r10 + adcq $0x0,%r8 + + movq 56(%rsi),%rax + mulq %r15 + addq %rax,%r10 + movq %r10,112(%rcx) + adcq %rdx,%r8 + movq %r8,120(%rcx) + + + movq 0(%rsp),%r8 + subq 0(%rcx),%r8 + movq 8(%rsp),%r9 + sbbq 8(%rcx),%r9 + movq 16(%rsp),%r10 + sbbq 16(%rcx),%r10 + movq 24(%rsp),%r11 + sbbq 24(%rcx),%r11 + movq 32(%rsp),%r12 + sbbq 32(%rcx),%r12 + movq 40(%rsp),%r13 + sbbq 40(%rcx),%r13 + movq 48(%rsp),%r14 + sbbq 48(%rcx),%r14 + movq 56(%rsp),%r15 + sbbq 56(%rcx),%r15 + + + movq 64(%rcx),%rax + subq %rax,%r8 + movq 72(%rcx),%rax + sbbq %rax,%r9 + movq 80(%rcx),%rax + sbbq %rax,%r10 + movq 88(%rcx),%rax + sbbq %rax,%r11 + movq 96(%rcx),%rax + sbbq %rax,%r12 + movq 104(%rcx),%rdx + sbbq %rdx,%r13 + movq 112(%rcx),%rdi + sbbq %rdi,%r14 + movq 120(%rcx),%rsi + sbbq %rsi,%r15 + + + addq 32(%rcx),%r8 + movq %r8,32(%rcx) + adcq 40(%rcx),%r9 + movq %r9,40(%rcx) + adcq 48(%rcx),%r10 + movq %r10,48(%rcx) + adcq 56(%rcx),%r11 + movq %r11,56(%rcx) + adcq 64(%rcx),%r12 + movq %r12,64(%rcx) + adcq 72(%rcx),%r13 + movq %r13,72(%rcx) + adcq 80(%rcx),%r14 + movq %r14,80(%rcx) + adcq 88(%rcx),%r15 + movq %r15,88(%rcx) + adcq $0x0,%rax + movq %rax,96(%rcx) + adcq $0x0,%rdx + movq %rdx,104(%rcx) + adcq $0x0,%rdi + movq %rdi,112(%rcx) + adcq $0x0,%rsi + movq %rsi,120(%rcx) + + addq $80,%rsp + + popq %r15 + + popq %r14 + + popq %r13 + + popq %r12 + + .byte 0xf3,0xc3 + + +L$rdc_mulx_asm: + + + + + + + + + + + movq 0+0(%rdi),%rdx + mulxq 0+L$p503p1_nz(%rip),%r8,%r9 + mulxq 8+L$p503p1_nz(%rip),%r12,%r10 + + xorq %rax,%rax + mulxq 16+L$p503p1_nz(%rip),%r13,%r11 + adoxq %r12,%r9 + adoxq %r13,%r10 + mulxq 24+L$p503p1_nz(%rip),%rbx,%r12 + adoxq %rbx,%r11 + mulxq 32+L$p503p1_nz(%rip),%r14,%r13 + adoxq %r14,%r12 + adoxq %rax,%r13 + + movq 0+8(%rdi),%rdx + mulxq 0+L$p503p1_nz(%rip),%r14,%rbx + adcxq %r14,%r9 + adcxq %rbx,%r10 + mulxq 8+L$p503p1_nz(%rip),%rcx,%r14 + adcxq %r14,%r11 + mulxq 16+L$p503p1_nz(%rip),%rbx,%r15 + adcxq %r15,%r12 + mulxq 24+L$p503p1_nz(%rip),%r15,%r14 + adcxq %r14,%r13 + mulxq 32+L$p503p1_nz(%rip),%rdx,%r14 + adcxq %rax,%r14 + + xorq %rax,%rax + adoxq %rcx,%r10 + adoxq %rbx,%r11 + adoxq %r15,%r12 + adoxq %rdx,%r13 + adoxq %rax,%r14 + + + + xorq %r15,%r15 + addq 24(%rdi),%r8 + adcq 32(%rdi),%r9 + adcq 40(%rdi),%r10 + adcq 48(%rdi),%r11 + adcq 56(%rdi),%r12 + adcq 64(%rdi),%r13 + adcq 72(%rdi),%r14 + adcq 80(%rdi),%r15 + movq %r8,24(%rdi) + movq %r9,32(%rdi) + movq %r10,40(%rdi) + movq %r11,48(%rdi) + movq %r12,56(%rdi) + movq %r13,64(%rdi) + movq %r14,72(%rdi) + movq %r15,80(%rdi) + movq 88(%rdi),%r8 + movq 96(%rdi),%r9 + movq 104(%rdi),%r10 + movq 112(%rdi),%r11 + movq 120(%rdi),%r12 + adcq $0x0,%r8 + adcq $0x0,%r9 + adcq $0x0,%r10 + adcq $0x0,%r11 + adcq $0x0,%r12 + movq %r8,88(%rdi) + movq %r9,96(%rdi) + movq %r10,104(%rdi) + movq %r11,112(%rdi) + movq %r12,120(%rdi) + + movq 16+0(%rdi),%rdx + mulxq 0+L$p503p1_nz(%rip),%r8,%r9 + mulxq 8+L$p503p1_nz(%rip),%r12,%r10 + + xorq %rax,%rax + mulxq 16+L$p503p1_nz(%rip),%r13,%r11 + adoxq %r12,%r9 + adoxq %r13,%r10 + mulxq 24+L$p503p1_nz(%rip),%rbx,%r12 + adoxq %rbx,%r11 + mulxq 32+L$p503p1_nz(%rip),%r14,%r13 + adoxq %r14,%r12 + adoxq %rax,%r13 + + movq 16+8(%rdi),%rdx + mulxq 0+L$p503p1_nz(%rip),%r14,%rbx + adcxq %r14,%r9 + adcxq %rbx,%r10 + mulxq 8+L$p503p1_nz(%rip),%rcx,%r14 + adcxq %r14,%r11 + mulxq 16+L$p503p1_nz(%rip),%rbx,%r15 + adcxq %r15,%r12 + mulxq 24+L$p503p1_nz(%rip),%r15,%r14 + adcxq %r14,%r13 + mulxq 32+L$p503p1_nz(%rip),%rdx,%r14 + adcxq %rax,%r14 + + xorq %rax,%rax + adoxq %rcx,%r10 + adoxq %rbx,%r11 + adoxq %r15,%r12 + adoxq %rdx,%r13 + adoxq %rax,%r14 + + + + xorq %r15,%r15 + addq 40(%rdi),%r8 + adcq 48(%rdi),%r9 + adcq 56(%rdi),%r10 + adcq 64(%rdi),%r11 + adcq 72(%rdi),%r12 + adcq 80(%rdi),%r13 + adcq 88(%rdi),%r14 + adcq 96(%rdi),%r15 + movq %r8,40(%rdi) + movq %r9,48(%rdi) + movq %r10,56(%rdi) + movq %r11,64(%rdi) + movq %r12,72(%rdi) + movq %r13,80(%rdi) + movq %r14,88(%rdi) + movq %r15,96(%rdi) + movq 104(%rdi),%r8 + movq 112(%rdi),%r9 + movq 120(%rdi),%r10 + adcq $0x0,%r8 + adcq $0x0,%r9 + adcq $0x0,%r10 + movq %r8,104(%rdi) + movq %r9,112(%rdi) + movq %r10,120(%rdi) + + movq 32+0(%rdi),%rdx + mulxq 0+L$p503p1_nz(%rip),%r8,%r9 + mulxq 8+L$p503p1_nz(%rip),%r12,%r10 + + xorq %rax,%rax + mulxq 16+L$p503p1_nz(%rip),%r13,%r11 + adoxq %r12,%r9 + adoxq %r13,%r10 + mulxq 24+L$p503p1_nz(%rip),%rbx,%r12 + adoxq %rbx,%r11 + mulxq 32+L$p503p1_nz(%rip),%r14,%r13 + adoxq %r14,%r12 + adoxq %rax,%r13 + + movq 32+8(%rdi),%rdx + mulxq 0+L$p503p1_nz(%rip),%r14,%rbx + adcxq %r14,%r9 + adcxq %rbx,%r10 + mulxq 8+L$p503p1_nz(%rip),%rcx,%r14 + adcxq %r14,%r11 + mulxq 16+L$p503p1_nz(%rip),%rbx,%r15 + adcxq %r15,%r12 + mulxq 24+L$p503p1_nz(%rip),%r15,%r14 + adcxq %r14,%r13 + mulxq 32+L$p503p1_nz(%rip),%rdx,%r14 + adcxq %rax,%r14 + + xorq %rax,%rax + adoxq %rcx,%r10 + adoxq %rbx,%r11 + adoxq %r15,%r12 + adoxq %rdx,%r13 + adoxq %rax,%r14 + + + + xorq %r15,%r15 + xorq %rbx,%rbx + addq 56(%rdi),%r8 + adcq 64(%rdi),%r9 + adcq 72(%rdi),%r10 + adcq 80(%rdi),%r11 + adcq 88(%rdi),%r12 + adcq 96(%rdi),%r13 + adcq 104(%rdi),%r14 + adcq 112(%rdi),%r15 + adcq 120(%rdi),%rbx + movq %r8,56(%rdi) + movq %r9,(%rsi) + movq %r10,72(%rdi) + movq %r11,80(%rdi) + movq %r12,88(%rdi) + movq %r13,96(%rdi) + movq %r14,104(%rdi) + movq %r15,112(%rdi) + movq %rbx,120(%rdi) + + movq 48+0(%rdi),%rdx + mulxq 0+L$p503p1_nz(%rip),%r8,%r9 + mulxq 8+L$p503p1_nz(%rip),%r12,%r10 + + xorq %rax,%rax + mulxq 16+L$p503p1_nz(%rip),%r13,%r11 + adoxq %r12,%r9 + adoxq %r13,%r10 + mulxq 24+L$p503p1_nz(%rip),%rbx,%r12 + adoxq %rbx,%r11 + mulxq 32+L$p503p1_nz(%rip),%r14,%r13 + adoxq %r14,%r12 + adoxq %rax,%r13 + + movq 48+8(%rdi),%rdx + mulxq 0+L$p503p1_nz(%rip),%r14,%rbx + adcxq %r14,%r9 + adcxq %rbx,%r10 + mulxq 8+L$p503p1_nz(%rip),%rcx,%r14 + adcxq %r14,%r11 + mulxq 16+L$p503p1_nz(%rip),%rbx,%r15 + adcxq %r15,%r12 + mulxq 24+L$p503p1_nz(%rip),%r15,%r14 + adcxq %r14,%r13 + mulxq 32+L$p503p1_nz(%rip),%rdx,%r14 + adcxq %rax,%r14 + + xorq %rax,%rax + adoxq %rcx,%r10 + adoxq %rbx,%r11 + adoxq %r15,%r12 + adoxq %rdx,%r13 + adoxq %rax,%r14 + + + + addq 72(%rdi),%r8 + adcq 80(%rdi),%r9 + adcq 88(%rdi),%r10 + adcq 96(%rdi),%r11 + adcq 104(%rdi),%r12 + adcq 112(%rdi),%r13 + adcq 120(%rdi),%r14 + movq %r8,8(%rsi) + movq %r9,16(%rsi) + movq %r10,24(%rsi) + movq %r11,32(%rsi) + movq %r12,40(%rsi) + movq %r13,48(%rsi) + movq %r14,56(%rsi) + + popq %rbx + + + popq %r15 + + + popq %r14 + + + popq %r13 + + + popq %r12 + + + .byte 0xf3,0xc3 + +.globl _sike_fprdc +.private_extern _sike_fprdc + +_sike_fprdc: + + pushq %r12 + + + pushq %r13 + + + pushq %r14 + + + pushq %r15 + + + pushq %rbx + + + + leaq _OPENSSL_ia32cap_P(%rip),%rcx + movq 8(%rcx),%rcx + andl $0x80100,%ecx + cmpl $0x80100,%ecx + je L$rdc_mulx_asm + + + + + leaq L$p503p1(%rip),%rbx + + movq (%rdi),%r11 + movq (%rbx),%rax + mulq %r11 + xorq %r8,%r8 + addq 24(%rdi),%rax + movq %rax,24(%rsi) + adcq %rdx,%r8 + + xorq %r9,%r9 + movq 8(%rbx),%rax + mulq %r11 + xorq %r10,%r10 + addq %rax,%r8 + adcq %rdx,%r9 + + movq 8(%rdi),%r12 + movq (%rbx),%rax + mulq %r12 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + addq 32(%rdi),%r8 + movq %r8,32(%rsi) + adcq $0,%r9 + adcq $0,%r10 + + xorq %r8,%r8 + movq 16(%rbx),%rax + mulq %r11 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 8(%rbx),%rax + mulq %r12 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 16(%rdi),%r13 + movq (%rbx),%rax + mulq %r13 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + addq 40(%rdi),%r9 + movq %r9,40(%rsi) + adcq $0,%r10 + adcq $0,%r8 + + xorq %r9,%r9 + movq 24(%rbx),%rax + mulq %r11 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 16(%rbx),%rax + mulq %r12 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 8(%rbx),%rax + mulq %r13 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 24(%rsi),%r14 + movq (%rbx),%rax + mulq %r14 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + addq 48(%rdi),%r10 + movq %r10,48(%rsi) + adcq $0,%r8 + adcq $0,%r9 + + xorq %r10,%r10 + movq 32(%rbx),%rax + mulq %r11 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 24(%rbx),%rax + mulq %r12 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 16(%rbx),%rax + mulq %r13 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 8(%rbx),%rax + mulq %r14 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 32(%rsi),%r15 + movq (%rbx),%rax + mulq %r15 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + addq 56(%rdi),%r8 + movq %r8,56(%rsi) + adcq $0,%r9 + adcq $0,%r10 + + xorq %r8,%r8 + movq 32(%rbx),%rax + mulq %r12 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 24(%rbx),%rax + mulq %r13 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 16(%rbx),%rax + mulq %r14 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 8(%rbx),%rax + mulq %r15 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 40(%rsi),%rcx + movq (%rbx),%rax + mulq %rcx + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + addq 64(%rdi),%r9 + movq %r9,(%rsi) + adcq $0,%r10 + adcq $0,%r8 + + xorq %r9,%r9 + movq 32(%rbx),%rax + mulq %r13 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 24(%rbx),%rax + mulq %r14 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 16(%rbx),%rax + mulq %r15 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 8(%rbx),%rax + mulq %rcx + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 48(%rsi),%r13 + movq (%rbx),%rax + mulq %r13 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + addq 72(%rdi),%r10 + movq %r10,8(%rsi) + adcq $0,%r8 + adcq $0,%r9 + + xorq %r10,%r10 + movq 32(%rbx),%rax + mulq %r14 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 24(%rbx),%rax + mulq %r15 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 16(%rbx),%rax + mulq %rcx + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 8(%rbx),%rax + mulq %r13 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 56(%rsi),%r14 + movq (%rbx),%rax + mulq %r14 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + addq 80(%rdi),%r8 + movq %r8,16(%rsi) + adcq $0,%r9 + adcq $0,%r10 + + xorq %r8,%r8 + movq 32(%rbx),%rax + mulq %r15 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 24(%rbx),%rax + mulq %rcx + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 16(%rbx),%rax + mulq %r13 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + + movq 8(%rbx),%rax + mulq %r14 + addq %rax,%r9 + adcq %rdx,%r10 + adcq $0,%r8 + addq 88(%rdi),%r9 + movq %r9,24(%rsi) + adcq $0,%r10 + adcq $0,%r8 + + xorq %r9,%r9 + movq 32(%rbx),%rax + mulq %rcx + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 24(%rbx),%rax + mulq %r13 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + + movq 16(%rbx),%rax + mulq %r14 + addq %rax,%r10 + adcq %rdx,%r8 + adcq $0,%r9 + addq 96(%rdi),%r10 + movq %r10,32(%rsi) + adcq $0,%r8 + adcq $0,%r9 + + xorq %r10,%r10 + movq 32(%rbx),%rax + mulq %r13 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + + movq 24(%rbx),%rax + mulq %r14 + addq %rax,%r8 + adcq %rdx,%r9 + adcq $0,%r10 + addq 104(%rdi),%r8 + movq %r8,40(%rsi) + adcq $0,%r9 + adcq $0,%r10 + + movq 32(%rbx),%rax + mulq %r14 + addq %rax,%r9 + adcq %rdx,%r10 + addq 112(%rdi),%r9 + movq %r9,48(%rsi) + adcq $0,%r10 + addq 120(%rdi),%r10 + movq %r10,56(%rsi) + + popq %rbx + + popq %r15 + + popq %r14 + + popq %r13 + + popq %r12 + + .byte 0xf3,0xc3 + +#endif diff --git a/third_party/boringssl/kit/src/.gitignore b/third_party/boringssl/kit/src/.gitignore index 79deb06c..41e32b9c 100644 --- a/third_party/boringssl/kit/src/.gitignore +++ b/third_party/boringssl/kit/src/.gitignore @@ -1,5 +1,6 @@ build/ ssl/test/runner/runner +*.pyc *.swp *.swo doc/*.html diff --git a/third_party/boringssl/kit/src/BUILDING.md b/third_party/boringssl/kit/src/BUILDING.md index ba988b76..4fc1615c 100644 --- a/third_party/boringssl/kit/src/BUILDING.md +++ b/third_party/boringssl/kit/src/BUILDING.md @@ -106,6 +106,21 @@ higher to build aarch64 binaries. For other options, see the documentation in the toolchain file. +To debug the resulting binaries on an Android device with `gdb`, run the +commands below. Replace `ARCH` with the architecture of the target device, e.g. +`arm` or `arm64`. + + adb push ${ANDROID_NDK}/prebuilt/android-ARCH/gdbserver/gdbserver \ + /data/local/tmp + adb forward tcp:5039 tcp:5039 + adb shell /data/local/tmp/gdbserver :5039 /path/on/device/to/binary + +Then run the following in a separate shell. Replace `HOST` with the OS and +architecture of the host machine, e.g. `linux-x86_64`. + + ${ANDROID_NDK}/prebuilt/HOST/bin/gdb + target remote :5039 # in gdb + ### Building for iOS To build for iOS, pass `-DCMAKE_OSX_SYSROOT=iphoneos` and diff --git a/third_party/boringssl/kit/src/CMakeLists.txt b/third_party/boringssl/kit/src/CMakeLists.txt index 2bc7febd..67c1145c 100644 --- a/third_party/boringssl/kit/src/CMakeLists.txt +++ b/third_party/boringssl/kit/src/CMakeLists.txt @@ -39,7 +39,7 @@ else() find_program(GO_EXECUTABLE go) endif() -if(CMAKE_SYSTEM_NAME STREQUAL "Linux") +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND NOT CMAKE_CROSSCOMPILING) find_package(PkgConfig QUIET) if (PkgConfig_FOUND) pkg_check_modules(LIBUNWIND libunwind-generic) @@ -65,6 +65,18 @@ if(BORINGSSL_ALLOW_CXX_RUNTIME) add_definitions(-DBORINGSSL_ALLOW_CXX_RUNTIME) endif() +if(CMAKE_BUILD_TYPE STREQUAL "Release") + # Windows release builds don't set NDEBUG in NASM flags automatically. + set(CMAKE_ASM_NASM_FLAGS "${CMAKE_ASM_NASM_FLAGS} -DNDEBUG") +endif() + +# Add a RelWithAsserts build configuration. It is the same as Release, except it +# does not define NDEBUG, so asserts run. +foreach(VAR CMAKE_C_FLAGS CMAKE_CXX_FLAGS CMAKE_ASM_FLAGS) + string(REGEX REPLACE "(^| )[/-]DNDEBUG( |$)" " " "${VAR}_RELWITHASSERTS" + "${${VAR}_RELEASE}") +endforeach() + if(BORINGSSL_PREFIX AND BORINGSSL_PREFIX_SYMBOLS) add_definitions(-DBORINGSSL_PREFIX=${BORINGSSL_PREFIX}) # CMake automatically connects include_directories to the NASM command-line, @@ -192,6 +204,7 @@ elseif(MSVC) # copy constructor is inaccessible or deleted "C4626" # assignment operator could not be generated because a base class # assignment operator is inaccessible or deleted + "C4628" # digraphs not supported with -Ze "C4668" # 'symbol' is not defined as a preprocessor macro, replacing with # '0' for 'directives' # Disable this because GTest uses it everywhere. @@ -330,6 +343,22 @@ if(TSAN) set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=thread") endif() +if(UBSAN) + if(NOT CLANG) + message(FATAL_ERROR "Cannot enable UBSAN unless using Clang") + endif() + + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=undefined") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined") + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=undefined") + + if(NOT UBSAN_RECOVER) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-sanitize-recover=undefined") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-sanitize-recover=undefined") + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fno-sanitize-recover=undefined") + endif() +endif() + if(GCOV) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage") @@ -340,9 +369,13 @@ if(FIPS) if(FIPS_BREAK_TEST) add_definitions("-DBORINGSSL_FIPS_BREAK_${FIPS_BREAK_TEST}=1") endif() - # Delocate does not work for ASan and MSan builds. + # The FIPS integrity check does not work for ASan and MSan builds. if(NOT ASAN AND NOT MSAN) - set(FIPS_DELOCATE "1") + if(BUILD_SHARED_LIBS) + set(FIPS_SHARED "1") + else() + set(FIPS_DELOCATE "1") + endif() endif() endif() diff --git a/third_party/boringssl/kit/src/LICENSE b/third_party/boringssl/kit/src/LICENSE index 49c41fa7..2f4dfcdb 100644 --- a/third_party/boringssl/kit/src/LICENSE +++ b/third_party/boringssl/kit/src/LICENSE @@ -181,6 +181,29 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +The code in third_party/sike also carries the MIT license: + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE + + Licenses for support code ------------------------- diff --git a/third_party/boringssl/kit/src/crypto/CMakeLists.txt b/third_party/boringssl/kit/src/crypto/CMakeLists.txt index 8565977b..017a06a0 100644 --- a/third_party/boringssl/kit/src/crypto/CMakeLists.txt +++ b/third_party/boringssl/kit/src/crypto/CMakeLists.txt @@ -87,7 +87,7 @@ endfunction() add_subdirectory(fipsmodule) add_subdirectory(test) -if(FIPS_DELOCATE) +if(FIPS_DELOCATE OR FIPS_SHARED) SET_SOURCE_FILES_PROPERTIES(fipsmodule/bcm.o PROPERTIES EXTERNAL_OBJECT true) SET_SOURCE_FILES_PROPERTIES(fipsmodule/bcm.o PROPERTIES GENERATED true) @@ -105,6 +105,7 @@ if(${ARCH} STREQUAL "arm") chacha/chacha-armv4.${ASM_EXT} curve25519/asm/x25519-asm-arm.S poly1305/poly1305_arm_asm.S + test/trampoline-armv4.${ASM_EXT} ) endif() @@ -113,6 +114,8 @@ if(${ARCH} STREQUAL "aarch64") CRYPTO_ARCH_SOURCES chacha/chacha-armv8.${ASM_EXT} + test/trampoline-armv8.${ASM_EXT} + third_party/sike/asm/fp-armv8.${ASM_EXT} ) endif() @@ -121,6 +124,7 @@ if(${ARCH} STREQUAL "x86") CRYPTO_ARCH_SOURCES chacha/chacha-x86.${ASM_EXT} + test/trampoline-x86.${ASM_EXT} ) endif() @@ -133,6 +137,7 @@ if(${ARCH} STREQUAL "x86_64") cipher_extra/chacha20_poly1305_x86_64.${ASM_EXT} hrss/asm/poly_rq_mul.S test/trampoline-x86_64.${ASM_EXT} + third_party/sike/asm/fp-x86_64.${ASM_EXT} ) endif() @@ -142,6 +147,11 @@ perlasm(chacha/chacha-x86.${ASM_EXT} chacha/asm/chacha-x86.pl) perlasm(chacha/chacha-x86_64.${ASM_EXT} chacha/asm/chacha-x86_64.pl) perlasm(cipher_extra/aes128gcmsiv-x86_64.${ASM_EXT} cipher_extra/asm/aes128gcmsiv-x86_64.pl) perlasm(cipher_extra/chacha20_poly1305_x86_64.${ASM_EXT} cipher_extra/asm/chacha20_poly1305_x86_64.pl) +perlasm(third_party/sike/asm/fp-x86_64.${ASM_EXT} ../third_party/sike/asm/fp-x86_64.pl) +perlasm(third_party/sike/asm/fp-armv8.${ASM_EXT} ../third_party/sike/asm/fp-armv8.pl) +perlasm(test/trampoline-armv4.${ASM_EXT} test/asm/trampoline-armv4.pl) +perlasm(test/trampoline-armv8.${ASM_EXT} test/asm/trampoline-armv8.pl) +perlasm(test/trampoline-x86.${ASM_EXT} test/asm/trampoline-x86.pl) perlasm(test/trampoline-x86_64.${ASM_EXT} test/asm/trampoline-x86_64.pl) add_custom_command( @@ -398,6 +408,11 @@ add_library( x509v3/v3_sxnet.c x509v3/v3_utl.c ../third_party/fiat/curve25519.c + ../third_party/sike/fpx.c + ../third_party/sike/isogeny.c + ../third_party/sike/P503.c + ../third_party/sike/sike.c + ../third_party/sike/asm/fp_generic.c $ @@ -405,9 +420,25 @@ add_library( ${CRYPTO_FIPS_OBJECTS} ) +if(FIPS_SHARED) + # Rewrite libcrypto.so to inject the correct module hash value. This assumes + # UNIX-style library naming, but we only support FIPS mode on Linux anyway. + add_custom_command( + TARGET crypto POST_BUILD + COMMAND ${GO_EXECUTABLE} run + ${CMAKE_CURRENT_SOURCE_DIR}/../util/fipstools/inject_hash/inject_hash.go + -o libcrypto.so -in-object libcrypto.so + # The DEPENDS argument to a POST_BUILD rule appears to be ignored. Thus + # go_executable isn't used (as it doesn't get built), but we list this + # dependency anyway in case it starts working in some CMake version. + DEPENDS ../util/fipstools/inject_hash/inject_hash.go + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + ) +endif() + add_dependencies(crypto global_target) -if(FIPS_DELOCATE) +if(FIPS_DELOCATE OR FIPS_SHARED) add_dependencies(crypto bcm_o_target) endif() @@ -463,6 +494,7 @@ add_executable( hkdf/hkdf_test.cc hmac_extra/hmac_test.cc hrss/hrss_test.cc + impl_dispatch_test.cc lhash/lhash_test.cc obj/obj_test.cc pem/pem_test.cc @@ -482,6 +514,7 @@ add_executable( x509/x509_time_test.cc x509v3/tab_test.cc x509v3/v3name_test.cc + ../third_party/sike/sike_test.cc $ $ diff --git a/third_party/boringssl/kit/src/crypto/abi_self_test.cc b/third_party/boringssl/kit/src/crypto/abi_self_test.cc index 7790ac5c..1fcf6bc2 100644 --- a/third_party/boringssl/kit/src/crypto/abi_self_test.cc +++ b/third_party/boringssl/kit/src/crypto/abi_self_test.cc @@ -19,46 +19,52 @@ #include "test/abi_test.h" -#if defined(OPENSSL_WINDOWS) -#include -#endif - static bool test_function_ok; static int TestFunction(int a1, int a2, int a3, int a4, int a5, int a6, int a7, - int a8, int a9, int a10) { + int a8) { test_function_ok = a1 == 1 || a2 == 2 || a3 == 3 || a4 == 4 || a5 == 5 || - a6 == 6 || a7 == 7 || a8 == 8 || a9 == 9 || a10 == 10; + a6 == 6 || a7 == 7 || a8 == 8; return 42; } TEST(ABITest, SanityCheck) { - EXPECT_NE(0, CHECK_ABI(strcmp, "hello", "world")); + EXPECT_NE(0, CHECK_ABI_NO_UNWIND(strcmp, "hello", "world")); test_function_ok = false; - EXPECT_EQ(42, CHECK_ABI(TestFunction, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); + EXPECT_EQ(42, CHECK_ABI_SEH(TestFunction, 1, 2, 3, 4, 5, 6, 7, 8)); EXPECT_TRUE(test_function_ok); #if defined(SUPPORTS_ABI_TEST) abi_test::internal::CallerState state; RAND_bytes(reinterpret_cast(&state), sizeof(state)); - const char *arg1 = "hello", *arg2 = "world"; - crypto_word_t argv[2] = { - reinterpret_cast(arg1), - reinterpret_cast(arg2), + crypto_word_t argv[] = { + 1, 2, 3, 4, 5, 6, 7, 8, }; - CHECK_ABI(abi_test_trampoline, reinterpret_cast(strcmp), - &state, argv, 2, 0 /* no breakpoint */); + CHECK_ABI_SEH(abi_test_trampoline, + reinterpret_cast(TestFunction), &state, argv, 8, + 0 /* no breakpoint */); +#if defined(OPENSSL_X86_64) if (abi_test::UnwindTestsEnabled()) { - EXPECT_NONFATAL_FAILURE(CHECK_ABI(abi_test_bad_unwind_wrong_register), - "was not recovered unwinding"); - EXPECT_NONFATAL_FAILURE(CHECK_ABI(abi_test_bad_unwind_temporary), - "was not recovered unwinding"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_SEH(abi_test_bad_unwind_wrong_register), + "was not recovered"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_SEH(abi_test_bad_unwind_temporary), + "was not recovered"); CHECK_ABI_NO_UNWIND(abi_test_bad_unwind_wrong_register); CHECK_ABI_NO_UNWIND(abi_test_bad_unwind_temporary); + +#if defined(OPENSSL_WINDOWS) + // The invalid epilog makes Windows believe the epilog starts later than it + // actually does. As a result, immediately after the popq, it does not + // realize the stack has been unwound and repeats the work. + EXPECT_NONFATAL_FAILURE(CHECK_ABI_SEH(abi_test_bad_unwind_epilog), + "unwound past starting frame"); + CHECK_ABI_NO_UNWIND(abi_test_bad_unwind_epilog); +#endif // OPENSSL_WINDOWS } +#endif // OPENSSL_X86_64 #endif // SUPPORTS_ABI_TEST } @@ -180,31 +186,338 @@ TEST(ABITest, X86_64) { EXPECT_EQ(0, abi_test_get_and_clear_direction_flag()) << "CHECK_ABI did not insulate the caller from direction flag errors"; } - -#if defined(OPENSSL_WINDOWS) -static void ThrowWindowsException() { - DebugBreak(); -} - -static void ExceptionTest() { - bool handled = false; - __try { - CHECK_ABI_NO_UNWIND(ThrowWindowsException); - } __except (GetExceptionCode() == EXCEPTION_BREAKPOINT - ? EXCEPTION_EXECUTE_HANDLER - : EXCEPTION_CONTINUE_SEARCH) { - handled = true; - } - - EXPECT_TRUE(handled); -} - -// Test that the trampoline's SEH metadata works. -TEST(ABITest, TrampolineSEH) { - // Wrap the test in |CHECK_ABI|, to confirm the register-restoring annotations - // were correct. - CHECK_ABI_NO_UNWIND(ExceptionTest); -} -#endif // OPENSSL_WINDOWS - #endif // OPENSSL_X86_64 && SUPPORTS_ABI_TEST + +#if defined(OPENSSL_X86) && defined(SUPPORTS_ABI_TEST) +extern "C" { +void abi_test_clobber_eax(void); +void abi_test_clobber_ebx(void); +void abi_test_clobber_ecx(void); +void abi_test_clobber_edx(void); +void abi_test_clobber_esi(void); +void abi_test_clobber_edi(void); +void abi_test_clobber_ebp(void); +void abi_test_clobber_xmm0(void); +void abi_test_clobber_xmm1(void); +void abi_test_clobber_xmm2(void); +void abi_test_clobber_xmm3(void); +void abi_test_clobber_xmm4(void); +void abi_test_clobber_xmm5(void); +void abi_test_clobber_xmm6(void); +void abi_test_clobber_xmm7(void); +} // extern "C" + +TEST(ABITest, X86) { + // abi_test_trampoline hides unsaved registers from the caller, so we can + // safely call the abi_test_clobber_* functions below. + abi_test::internal::CallerState state; + RAND_bytes(reinterpret_cast(&state), sizeof(state)); + CHECK_ABI_NO_UNWIND(abi_test_trampoline, + reinterpret_cast(abi_test_clobber_ebx), + &state, nullptr, 0, 0 /* no breakpoint */); + + CHECK_ABI_NO_UNWIND(abi_test_clobber_eax); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_ebx), + "ebx was not restored after return"); + CHECK_ABI_NO_UNWIND(abi_test_clobber_ecx); + CHECK_ABI_NO_UNWIND(abi_test_clobber_edx); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_edi), + "edi was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_esi), + "esi was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_ebp), + "ebp was not restored after return"); + + CHECK_ABI_NO_UNWIND(abi_test_clobber_xmm0); + CHECK_ABI_NO_UNWIND(abi_test_clobber_xmm1); + CHECK_ABI_NO_UNWIND(abi_test_clobber_xmm2); + CHECK_ABI_NO_UNWIND(abi_test_clobber_xmm3); + CHECK_ABI_NO_UNWIND(abi_test_clobber_xmm4); + CHECK_ABI_NO_UNWIND(abi_test_clobber_xmm5); + CHECK_ABI_NO_UNWIND(abi_test_clobber_xmm6); + CHECK_ABI_NO_UNWIND(abi_test_clobber_xmm7); + + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_set_direction_flag), + "Direction flag set after return"); + EXPECT_EQ(0, abi_test_get_and_clear_direction_flag()) + << "CHECK_ABI did not insulate the caller from direction flag errors"; +} +#endif // OPENSSL_X86 && SUPPORTS_ABI_TEST + +#if defined(OPENSSL_ARM) && defined(SUPPORTS_ABI_TEST) +extern "C" { +void abi_test_clobber_r0(void); +void abi_test_clobber_r1(void); +void abi_test_clobber_r2(void); +void abi_test_clobber_r3(void); +void abi_test_clobber_r4(void); +void abi_test_clobber_r5(void); +void abi_test_clobber_r6(void); +void abi_test_clobber_r7(void); +void abi_test_clobber_r8(void); +void abi_test_clobber_r9(void); +void abi_test_clobber_r10(void); +void abi_test_clobber_r11(void); +void abi_test_clobber_r12(void); +// r13, r14, and r15, are sp, lr, and pc, respectively. + +void abi_test_clobber_d0(void); +void abi_test_clobber_d1(void); +void abi_test_clobber_d2(void); +void abi_test_clobber_d3(void); +void abi_test_clobber_d4(void); +void abi_test_clobber_d5(void); +void abi_test_clobber_d6(void); +void abi_test_clobber_d7(void); +void abi_test_clobber_d8(void); +void abi_test_clobber_d9(void); +void abi_test_clobber_d10(void); +void abi_test_clobber_d11(void); +void abi_test_clobber_d12(void); +void abi_test_clobber_d13(void); +void abi_test_clobber_d14(void); +void abi_test_clobber_d15(void); +} // extern "C" + +TEST(ABITest, ARM) { + // abi_test_trampoline hides unsaved registers from the caller, so we can + // safely call the abi_test_clobber_* functions below. + abi_test::internal::CallerState state; + RAND_bytes(reinterpret_cast(&state), sizeof(state)); + CHECK_ABI_NO_UNWIND(abi_test_trampoline, + reinterpret_cast(abi_test_clobber_r4), + &state, nullptr, 0, 0 /* no breakpoint */); + + CHECK_ABI_NO_UNWIND(abi_test_clobber_r0); + CHECK_ABI_NO_UNWIND(abi_test_clobber_r1); + CHECK_ABI_NO_UNWIND(abi_test_clobber_r2); + CHECK_ABI_NO_UNWIND(abi_test_clobber_r3); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_r4), + "r4 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_r5), + "r5 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_r6), + "r6 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_r7), + "r7 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_r8), + "r8 was not restored after return"); +#if defined(OPENSSL_APPLE) + CHECK_ABI_NO_UNWIND(abi_test_clobber_r9); +#else + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_r9), + "r9 was not restored after return"); +#endif + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_r10), + "r10 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_r11), + "r11 was not restored after return"); + CHECK_ABI_NO_UNWIND(abi_test_clobber_r12); + + CHECK_ABI_NO_UNWIND(abi_test_clobber_d0); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d1); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d2); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d3); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d4); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d5); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d6); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d7); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_d8), + "d8 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_d9), + "d9 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_d10), + "d10 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_d11), + "d11 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_d12), + "d12 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_d13), + "d13 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_d14), + "d14 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_d15), + "d15 was not restored after return"); +} +#endif // OPENSSL_ARM && SUPPORTS_ABI_TEST + + +#if defined(OPENSSL_AARCH64) && defined(SUPPORTS_ABI_TEST) +extern "C" { +void abi_test_clobber_x0(void); +void abi_test_clobber_x1(void); +void abi_test_clobber_x2(void); +void abi_test_clobber_x3(void); +void abi_test_clobber_x4(void); +void abi_test_clobber_x5(void); +void abi_test_clobber_x6(void); +void abi_test_clobber_x7(void); +void abi_test_clobber_x8(void); +void abi_test_clobber_x9(void); +void abi_test_clobber_x10(void); +void abi_test_clobber_x11(void); +void abi_test_clobber_x12(void); +void abi_test_clobber_x13(void); +void abi_test_clobber_x14(void); +void abi_test_clobber_x15(void); +void abi_test_clobber_x16(void); +void abi_test_clobber_x17(void); +// x18 is the platform register and off limits. +void abi_test_clobber_x19(void); +void abi_test_clobber_x20(void); +void abi_test_clobber_x21(void); +void abi_test_clobber_x22(void); +void abi_test_clobber_x23(void); +void abi_test_clobber_x24(void); +void abi_test_clobber_x25(void); +void abi_test_clobber_x26(void); +void abi_test_clobber_x27(void); +void abi_test_clobber_x28(void); +void abi_test_clobber_x29(void); + +void abi_test_clobber_d0(void); +void abi_test_clobber_d1(void); +void abi_test_clobber_d2(void); +void abi_test_clobber_d3(void); +void abi_test_clobber_d4(void); +void abi_test_clobber_d5(void); +void abi_test_clobber_d6(void); +void abi_test_clobber_d7(void); +void abi_test_clobber_d8(void); +void abi_test_clobber_d9(void); +void abi_test_clobber_d10(void); +void abi_test_clobber_d11(void); +void abi_test_clobber_d12(void); +void abi_test_clobber_d13(void); +void abi_test_clobber_d14(void); +void abi_test_clobber_d15(void); +void abi_test_clobber_d16(void); +void abi_test_clobber_d17(void); +void abi_test_clobber_d18(void); +void abi_test_clobber_d19(void); +void abi_test_clobber_d20(void); +void abi_test_clobber_d21(void); +void abi_test_clobber_d22(void); +void abi_test_clobber_d23(void); +void abi_test_clobber_d24(void); +void abi_test_clobber_d25(void); +void abi_test_clobber_d26(void); +void abi_test_clobber_d27(void); +void abi_test_clobber_d28(void); +void abi_test_clobber_d29(void); +void abi_test_clobber_d30(void); +void abi_test_clobber_d31(void); + +void abi_test_clobber_v8_upper(void); +void abi_test_clobber_v9_upper(void); +void abi_test_clobber_v10_upper(void); +void abi_test_clobber_v11_upper(void); +void abi_test_clobber_v12_upper(void); +void abi_test_clobber_v13_upper(void); +void abi_test_clobber_v14_upper(void); +void abi_test_clobber_v15_upper(void); +} // extern "C" + +TEST(ABITest, AArch64) { + // abi_test_trampoline hides unsaved registers from the caller, so we can + // safely call the abi_test_clobber_* functions below. + abi_test::internal::CallerState state; + RAND_bytes(reinterpret_cast(&state), sizeof(state)); + CHECK_ABI_NO_UNWIND(abi_test_trampoline, + reinterpret_cast(abi_test_clobber_x19), + &state, nullptr, 0, 0 /* no breakpoint */); + + CHECK_ABI_NO_UNWIND(abi_test_clobber_x0); + CHECK_ABI_NO_UNWIND(abi_test_clobber_x1); + CHECK_ABI_NO_UNWIND(abi_test_clobber_x2); + CHECK_ABI_NO_UNWIND(abi_test_clobber_x3); + CHECK_ABI_NO_UNWIND(abi_test_clobber_x4); + CHECK_ABI_NO_UNWIND(abi_test_clobber_x5); + CHECK_ABI_NO_UNWIND(abi_test_clobber_x6); + CHECK_ABI_NO_UNWIND(abi_test_clobber_x7); + CHECK_ABI_NO_UNWIND(abi_test_clobber_x8); + CHECK_ABI_NO_UNWIND(abi_test_clobber_x9); + CHECK_ABI_NO_UNWIND(abi_test_clobber_x10); + CHECK_ABI_NO_UNWIND(abi_test_clobber_x11); + CHECK_ABI_NO_UNWIND(abi_test_clobber_x12); + CHECK_ABI_NO_UNWIND(abi_test_clobber_x13); + CHECK_ABI_NO_UNWIND(abi_test_clobber_x14); + CHECK_ABI_NO_UNWIND(abi_test_clobber_x15); + CHECK_ABI_NO_UNWIND(abi_test_clobber_x16); + CHECK_ABI_NO_UNWIND(abi_test_clobber_x17); + + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_x19), + "x19 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_x20), + "x20 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_x21), + "x21 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_x22), + "x22 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_x23), + "x23 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_x24), + "x24 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_x25), + "x25 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_x26), + "x26 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_x27), + "x27 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_x28), + "x28 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_x29), + "x29 was not restored after return"); + + CHECK_ABI_NO_UNWIND(abi_test_clobber_d0); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d1); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d2); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d3); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d4); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d5); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d6); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d7); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_d8), + "d8 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_d9), + "d9 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_d10), + "d10 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_d11), + "d11 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_d12), + "d12 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_d13), + "d13 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_d14), + "d14 was not restored after return"); + EXPECT_NONFATAL_FAILURE(CHECK_ABI_NO_UNWIND(abi_test_clobber_d15), + "d15 was not restored after return"); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d16); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d18); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d19); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d20); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d21); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d22); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d23); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d24); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d25); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d26); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d27); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d28); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d29); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d30); + CHECK_ABI_NO_UNWIND(abi_test_clobber_d31); + + // The lower halves of v8-v15 (accessed as d8-d15) must be preserved, but not + // the upper halves. + CHECK_ABI_NO_UNWIND(abi_test_clobber_v8_upper); + CHECK_ABI_NO_UNWIND(abi_test_clobber_v9_upper); + CHECK_ABI_NO_UNWIND(abi_test_clobber_v10_upper); + CHECK_ABI_NO_UNWIND(abi_test_clobber_v11_upper); + CHECK_ABI_NO_UNWIND(abi_test_clobber_v12_upper); + CHECK_ABI_NO_UNWIND(abi_test_clobber_v13_upper); + CHECK_ABI_NO_UNWIND(abi_test_clobber_v14_upper); + CHECK_ABI_NO_UNWIND(abi_test_clobber_v15_upper); +} +#endif // OPENSSL_AARCH64 && SUPPORTS_ABI_TEST diff --git a/third_party/boringssl/kit/src/crypto/asn1/a_int.c b/third_party/boringssl/kit/src/crypto/asn1/a_int.c index 6dc18bad..7b483f2d 100644 --- a/third_party/boringssl/kit/src/crypto/asn1/a_int.c +++ b/third_party/boringssl/kit/src/crypto/asn1/a_int.c @@ -195,6 +195,16 @@ ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **a, const unsigned char **pp, unsigned char *to, *s; int i; + /* + * This function can handle lengths up to INT_MAX - 1, but the rest of the + * legacy ASN.1 code mixes integer types, so avoid exposing it to + * ASN1_INTEGERS with larger lengths. + */ + if (len < 0 || len > INT_MAX / 2) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_TOO_LONG); + return NULL; + } + if ((a == NULL) || ((*a) == NULL)) { if ((ret = M_ASN1_INTEGER_new()) == NULL) return (NULL); @@ -276,75 +286,6 @@ ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **a, const unsigned char **pp, return (NULL); } -/* - * This is a version of d2i_ASN1_INTEGER that ignores the sign bit of ASN1 - * integers: some broken software can encode a positive INTEGER with its MSB - * set as negative (it doesn't add a padding zero). - */ - -ASN1_INTEGER *d2i_ASN1_UINTEGER(ASN1_INTEGER **a, const unsigned char **pp, - long length) -{ - ASN1_INTEGER *ret = NULL; - const unsigned char *p; - unsigned char *s; - long len; - int inf, tag, xclass; - int i; - - if ((a == NULL) || ((*a) == NULL)) { - if ((ret = M_ASN1_INTEGER_new()) == NULL) - return (NULL); - ret->type = V_ASN1_INTEGER; - } else - ret = (*a); - - p = *pp; - inf = ASN1_get_object(&p, &len, &tag, &xclass, length); - if (inf & 0x80) { - i = ASN1_R_BAD_OBJECT_HEADER; - goto err; - } - - if (tag != V_ASN1_INTEGER) { - i = ASN1_R_EXPECTING_AN_INTEGER; - goto err; - } - - /* - * We must OPENSSL_malloc stuff, even for 0 bytes otherwise it signifies - * a missing NULL parameter. - */ - s = (unsigned char *)OPENSSL_malloc((int)len + 1); - if (s == NULL) { - i = ERR_R_MALLOC_FAILURE; - goto err; - } - ret->type = V_ASN1_INTEGER; - if (len) { - if ((*p == 0) && (len != 1)) { - p++; - len--; - } - OPENSSL_memcpy(s, p, (int)len); - p += len; - } - - if (ret->data != NULL) - OPENSSL_free(ret->data); - ret->data = s; - ret->length = (int)len; - if (a != NULL) - (*a) = ret; - *pp = p; - return (ret); - err: - OPENSSL_PUT_ERROR(ASN1, i); - if ((ret != NULL) && ((a == NULL) || (*a != ret))) - M_ASN1_INTEGER_free(ret); - return (NULL); -} - int ASN1_INTEGER_set(ASN1_INTEGER *a, long v) { if (v >= 0) { diff --git a/third_party/boringssl/kit/src/crypto/asn1/asn1_lib.c b/third_party/boringssl/kit/src/crypto/asn1/asn1_lib.c index ea727f33..8526aba3 100644 --- a/third_party/boringssl/kit/src/crypto/asn1/asn1_lib.c +++ b/third_party/boringssl/kit/src/crypto/asn1/asn1_lib.c @@ -205,7 +205,11 @@ static int asn1_get_length(const unsigned char **pp, int *inf, long *rl, } else ret = i; } - if (ret > LONG_MAX) + /* + * Bound the length to comfortably fit in an int. Lengths in this module + * often switch between int and long without overflow checks. + */ + if (ret > INT_MAX / 2) return 0; *pp = p; *rl = (long)ret; diff --git a/third_party/boringssl/kit/src/crypto/base64/base64_test.cc b/third_party/boringssl/kit/src/crypto/base64/base64_test.cc index 28b5c8e0..69056595 100644 --- a/third_party/boringssl/kit/src/crypto/base64/base64_test.cc +++ b/third_party/boringssl/kit/src/crypto/base64/base64_test.cc @@ -39,14 +39,14 @@ enum encoding_relation { invalid, }; -struct TestVector { +struct Base64TestVector { enum encoding_relation relation; const char *decoded; const char *encoded; }; // Test vectors from RFC 4648. -static const TestVector kTestVectors[] = { +static const Base64TestVector kTestVectors[] = { {canonical, "", ""}, {canonical, "f", "Zg==\n"}, {canonical, "fo", "Zm8=\n"}, @@ -103,9 +103,9 @@ static const TestVector kTestVectors[] = { "=======\n"}, }; -class Base64Test : public testing::TestWithParam {}; +class Base64Test : public testing::TestWithParam {}; -INSTANTIATE_TEST_CASE_P(, Base64Test, testing::ValuesIn(kTestVectors)); +INSTANTIATE_TEST_SUITE_P(, Base64Test, testing::ValuesIn(kTestVectors)); // RemoveNewlines returns a copy of |in| with all '\n' characters removed. static std::string RemoveNewlines(const char *in) { @@ -122,7 +122,7 @@ static std::string RemoveNewlines(const char *in) { } TEST_P(Base64Test, EncodeBlock) { - const TestVector &t = GetParam(); + const Base64TestVector &t = GetParam(); if (t.relation != canonical) { return; } @@ -140,7 +140,7 @@ TEST_P(Base64Test, EncodeBlock) { } TEST_P(Base64Test, DecodeBase64) { - const TestVector &t = GetParam(); + const Base64TestVector &t = GetParam(); if (t.relation == valid) { // The non-canonical encodings will generally have odd whitespace etc // that |EVP_DecodeBase64| will reject. @@ -164,7 +164,7 @@ TEST_P(Base64Test, DecodeBase64) { } TEST_P(Base64Test, DecodeBlock) { - const TestVector &t = GetParam(); + const Base64TestVector &t = GetParam(); if (t.relation != canonical) { return; } @@ -188,7 +188,7 @@ TEST_P(Base64Test, DecodeBlock) { } TEST_P(Base64Test, EncodeDecode) { - const TestVector &t = GetParam(); + const Base64TestVector &t = GetParam(); EVP_ENCODE_CTX ctx; const size_t decoded_len = strlen(t.decoded); @@ -246,7 +246,7 @@ TEST_P(Base64Test, EncodeDecode) { } TEST_P(Base64Test, DecodeUpdateStreaming) { - const TestVector &t = GetParam(); + const Base64TestVector &t = GetParam(); if (t.relation == invalid) { return; } diff --git a/third_party/boringssl/kit/src/crypto/bio/bio_test.cc b/third_party/boringssl/kit/src/crypto/bio/bio_test.cc index 8479c8e8..797a7337 100644 --- a/third_party/boringssl/kit/src/crypto/bio/bio_test.cc +++ b/third_party/boringssl/kit/src/crypto/bio/bio_test.cc @@ -220,7 +220,7 @@ TEST_P(BIOASN1Test, ReadASN1) { } } -INSTANTIATE_TEST_CASE_P(, BIOASN1Test, testing::ValuesIn(kASN1TestParams)); +INSTANTIATE_TEST_SUITE_P(, BIOASN1Test, testing::ValuesIn(kASN1TestParams)); // Run through the tests twice, swapping |bio1| and |bio2|, for symmetry. class BIOPairTest : public testing::TestWithParam {}; @@ -322,4 +322,4 @@ TEST_P(BIOPairTest, TestPair) { EXPECT_EQ(Bytes("12345"), Bytes(buf, 5)); } -INSTANTIATE_TEST_CASE_P(, BIOPairTest, testing::Values(false, true)); +INSTANTIATE_TEST_SUITE_P(, BIOPairTest, testing::Values(false, true)); diff --git a/third_party/boringssl/kit/src/crypto/bn_extra/convert.c b/third_party/boringssl/kit/src/crypto/bn_extra/convert.c index 9a1a69e3..6e930fc6 100644 --- a/third_party/boringssl/kit/src/crypto/bn_extra/convert.c +++ b/third_party/boringssl/kit/src/crypto/bn_extra/convert.c @@ -460,3 +460,11 @@ BIGNUM *BN_mpi2bn(const uint8_t *in, size_t len, BIGNUM *out) { } return out; } + +int BN_bn2binpad(const BIGNUM *in, uint8_t *out, int len) { + if (len < 0 || + !BN_bn2bin_padded(out, (size_t)len, in)) { + return -1; + } + return len; +} diff --git a/third_party/boringssl/kit/src/crypto/bytestring/bytestring_test.cc b/third_party/boringssl/kit/src/crypto/bytestring/bytestring_test.cc index e99744d5..1f787996 100644 --- a/third_party/boringssl/kit/src/crypto/bytestring/bytestring_test.cc +++ b/third_party/boringssl/kit/src/crypto/bytestring/bytestring_test.cc @@ -42,10 +42,12 @@ TEST(CBSTest, Skip) { } TEST(CBSTest, GetUint) { - static const uint8_t kData[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; + static const uint8_t kData[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; uint8_t u8; uint16_t u16; uint32_t u32; + uint64_t u64; CBS data; CBS_init(&data, kData, sizeof(kData)); @@ -57,10 +59,12 @@ TEST(CBSTest, GetUint) { EXPECT_EQ(0x40506u, u32); ASSERT_TRUE(CBS_get_u32(&data, &u32)); EXPECT_EQ(0x708090au, u32); + ASSERT_TRUE(CBS_get_u64(&data, &u64)); + EXPECT_EQ(0xb0c0d0e0f101112u, u64); ASSERT_TRUE(CBS_get_last_u8(&data, &u8)); - EXPECT_EQ(0xcu, u8); + EXPECT_EQ(0x14u, u8); ASSERT_TRUE(CBS_get_last_u8(&data, &u8)); - EXPECT_EQ(0xbu, u8); + EXPECT_EQ(0x13u, u8); EXPECT_FALSE(CBS_get_u8(&data, &u8)); EXPECT_FALSE(CBS_get_last_u8(&data, &u8)); } @@ -310,7 +314,9 @@ TEST(CBBTest, InitUninitialized) { } TEST(CBBTest, Basic) { - static const uint8_t kExpected[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc}; + static const uint8_t kExpected[] = {1, 2, 3, 4, 5, 6, 7, + 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, + 0xf, 0x10, 0x11, 0x12, 0x13, 0x14}; uint8_t *buf; size_t buf_len; @@ -323,7 +329,8 @@ TEST(CBBTest, Basic) { ASSERT_TRUE(CBB_add_u16(cbb.get(), 0x203)); ASSERT_TRUE(CBB_add_u24(cbb.get(), 0x40506)); ASSERT_TRUE(CBB_add_u32(cbb.get(), 0x708090a)); - ASSERT_TRUE(CBB_add_bytes(cbb.get(), (const uint8_t *)"\x0b\x0c", 2)); + ASSERT_TRUE(CBB_add_u64(cbb.get(), 0xb0c0d0e0f101112)); + ASSERT_TRUE(CBB_add_bytes(cbb.get(), (const uint8_t *)"\x13\x14", 2)); ASSERT_TRUE(CBB_finish(cbb.get(), &buf, &buf_len)); bssl::UniquePtr scoper(buf); diff --git a/third_party/boringssl/kit/src/crypto/bytestring/cbb.c b/third_party/boringssl/kit/src/crypto/bytestring/cbb.c index 38e9a83a..1ddc73c6 100644 --- a/third_party/boringssl/kit/src/crypto/bytestring/cbb.c +++ b/third_party/boringssl/kit/src/crypto/bytestring/cbb.c @@ -44,7 +44,7 @@ static int cbb_init(CBB *cbb, uint8_t *buf, size_t cap) { base->error = 0; cbb->base = base; - cbb->is_top_level = 1; + cbb->is_child = 0; return 1; } @@ -76,11 +76,14 @@ int CBB_init_fixed(CBB *cbb, uint8_t *buf, size_t len) { } void CBB_cleanup(CBB *cbb) { - if (cbb->base) { - // Only top-level |CBB|s are cleaned up. Child |CBB|s are non-owning. They - // are implicitly discarded when the parent is flushed or cleaned up. - assert(cbb->is_top_level); + // Child |CBB|s are non-owning. They are implicitly discarded and should not + // be used with |CBB_cleanup| or |ScopedCBB|. + assert(!cbb->is_child); + if (cbb->is_child) { + return; + } + if (cbb->base) { if (cbb->base->can_resize) { OPENSSL_free(cbb->base->buf); } @@ -144,7 +147,7 @@ static int cbb_buffer_add(struct cbb_buffer_st *base, uint8_t **out, return 1; } -static int cbb_buffer_add_u(struct cbb_buffer_st *base, uint32_t v, +static int cbb_buffer_add_u(struct cbb_buffer_st *base, uint64_t v, size_t len_len) { if (len_len == 0) { return 1; @@ -169,7 +172,7 @@ static int cbb_buffer_add_u(struct cbb_buffer_st *base, uint32_t v, } int CBB_finish(CBB *cbb, uint8_t **out_data, size_t *out_len) { - if (!cbb->is_top_level) { + if (cbb->is_child) { return 0; } @@ -310,6 +313,7 @@ static int cbb_add_length_prefixed(CBB *cbb, CBB *out_contents, OPENSSL_memset(prefix_bytes, 0, len_len); OPENSSL_memset(out_contents, 0, sizeof(CBB)); out_contents->base = cbb->base; + out_contents->is_child = 1; cbb->child = out_contents; cbb->child->offset = offset; cbb->child->pending_len_len = len_len; @@ -381,6 +385,7 @@ int CBB_add_asn1(CBB *cbb, CBB *out_contents, unsigned tag) { OPENSSL_memset(out_contents, 0, sizeof(CBB)); out_contents->base = cbb->base; + out_contents->is_child = 1; cbb->child = out_contents; cbb->child->offset = offset; cbb->child->pending_len_len = 1; @@ -459,6 +464,13 @@ int CBB_add_u32(CBB *cbb, uint32_t value) { return cbb_buffer_add_u(cbb->base, value, 4); } +int CBB_add_u64(CBB *cbb, uint64_t value) { + if (!CBB_flush(cbb)) { + return 0; + } + return cbb_buffer_add_u(cbb->base, value, 8); +} + void CBB_discard_child(CBB *cbb) { if (cbb->child == NULL) { return; diff --git a/third_party/boringssl/kit/src/crypto/bytestring/cbs.c b/third_party/boringssl/kit/src/crypto/bytestring/cbs.c index 372652c4..f8a8353e 100644 --- a/third_party/boringssl/kit/src/crypto/bytestring/cbs.c +++ b/third_party/boringssl/kit/src/crypto/bytestring/cbs.c @@ -88,8 +88,8 @@ int CBS_mem_equal(const CBS *cbs, const uint8_t *data, size_t len) { return CRYPTO_memcmp(cbs->data, data, len) == 0; } -static int cbs_get_u(CBS *cbs, uint32_t *out, size_t len) { - uint32_t result = 0; +static int cbs_get_u(CBS *cbs, uint64_t *out, size_t len) { + uint64_t result = 0; const uint8_t *data; if (!cbs_get(cbs, &data, len)) { @@ -113,7 +113,7 @@ int CBS_get_u8(CBS *cbs, uint8_t *out) { } int CBS_get_u16(CBS *cbs, uint16_t *out) { - uint32_t v; + uint64_t v; if (!cbs_get_u(cbs, &v, 2)) { return 0; } @@ -122,11 +122,25 @@ int CBS_get_u16(CBS *cbs, uint16_t *out) { } int CBS_get_u24(CBS *cbs, uint32_t *out) { - return cbs_get_u(cbs, out, 3); + uint64_t v; + if (!cbs_get_u(cbs, &v, 3)) { + return 0; + } + *out = v; + return 1; } int CBS_get_u32(CBS *cbs, uint32_t *out) { - return cbs_get_u(cbs, out, 4); + uint64_t v; + if (!cbs_get_u(cbs, &v, 4)) { + return 0; + } + *out = v; + return 1; +} + +int CBS_get_u64(CBS *cbs, uint64_t *out) { + return cbs_get_u(cbs, out, 8); } int CBS_get_last_u8(CBS *cbs, uint8_t *out) { @@ -157,10 +171,13 @@ int CBS_copy_bytes(CBS *cbs, uint8_t *out, size_t len) { } static int cbs_get_length_prefixed(CBS *cbs, CBS *out, size_t len_len) { - uint32_t len; + uint64_t len; if (!cbs_get_u(cbs, &len, len_len)) { return 0; } + // If |len_len| <= 3 then we know that |len| will fit into a |size_t|, even on + // 32-bit systems. + assert(len_len <= 3); return CBS_get_bytes(cbs, out, len); } @@ -274,7 +291,7 @@ static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, unsigned *out_tag, // encode the number of subsequent octets used to encode the length (ITU-T // X.690 clause 8.1.3.5.b). const size_t num_bytes = length_byte & 0x7f; - uint32_t len32; + uint64_t len64; if (ber_ok && (tag & CBS_ASN1_CONSTRUCTED) != 0 && num_bytes == 0) { // indefinite length @@ -290,20 +307,20 @@ static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, unsigned *out_tag, if (num_bytes == 0 || num_bytes > 4) { return 0; } - if (!cbs_get_u(&header, &len32, num_bytes)) { + if (!cbs_get_u(&header, &len64, num_bytes)) { return 0; } // ITU-T X.690 section 10.1 (DER length forms) requires encoding the length // with the minimum number of octets. - if (len32 < 128) { + if (len64 < 128) { // Length should have used short-form encoding. return 0; } - if ((len32 >> ((num_bytes-1)*8)) == 0) { + if ((len64 >> ((num_bytes-1)*8)) == 0) { // Length should have been at least one byte shorter. return 0; } - len = len32; + len = len64; if (len + header_len + num_bytes < len) { // Overflow. return 0; diff --git a/third_party/boringssl/kit/src/crypto/chacha/asm/chacha-armv4.pl b/third_party/boringssl/kit/src/crypto/chacha/asm/chacha-armv4.pl index 2a9a7d7b..06be3a66 100755 --- a/third_party/boringssl/kit/src/crypto/chacha/asm/chacha-armv4.pl +++ b/third_party/boringssl/kit/src/crypto/chacha/asm/chacha-armv4.pl @@ -1161,4 +1161,4 @@ foreach (split("\n",$code)) { print $_,"\n"; } -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/chacha/asm/chacha-armv8.pl b/third_party/boringssl/kit/src/crypto/chacha/asm/chacha-armv8.pl index 7795f2cb..02325e7a 100755 --- a/third_party/boringssl/kit/src/crypto/chacha/asm/chacha-armv8.pl +++ b/third_party/boringssl/kit/src/crypto/chacha/asm/chacha-armv8.pl @@ -1134,4 +1134,4 @@ foreach (split("\n",$code)) { print $_,"\n"; } -close STDOUT; # flush +close STDOUT or die "error closing STDOUT"; # flush diff --git a/third_party/boringssl/kit/src/crypto/chacha/asm/chacha-x86.pl b/third_party/boringssl/kit/src/crypto/chacha/asm/chacha-x86.pl index 1d6a4e2b..ec1cf800 100755 --- a/third_party/boringssl/kit/src/crypto/chacha/asm/chacha-x86.pl +++ b/third_party/boringssl/kit/src/crypto/chacha/asm/chacha-x86.pl @@ -769,4 +769,4 @@ sub SSSE3ROUND { # critical path is 20 "SIMD ticks" per round &asm_finish(); -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/chacha/asm/chacha-x86_64.pl b/third_party/boringssl/kit/src/crypto/chacha/asm/chacha-x86_64.pl index 6be270ec..ab8a1f78 100755 --- a/third_party/boringssl/kit/src/crypto/chacha/asm/chacha-x86_64.pl +++ b/third_party/boringssl/kit/src/crypto/chacha/asm/chacha-x86_64.pl @@ -2782,4 +2782,4 @@ foreach (split("\n",$code)) { print $_,"\n"; } -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/cipher_extra/aead_test.cc b/third_party/boringssl/kit/src/crypto/cipher_extra/aead_test.cc index fff7d439..25924bd5 100644 --- a/third_party/boringssl/kit/src/crypto/cipher_extra/aead_test.cc +++ b/third_party/boringssl/kit/src/crypto/cipher_extra/aead_test.cc @@ -42,58 +42,58 @@ struct KnownAEAD { // truncated_tags is true if the AEAD supports truncating tags to arbitrary // lengths. bool truncated_tags; + // variable_nonce is true if the AEAD supports a variable nonce length. + bool variable_nonce; // ad_len, if non-zero, is the required length of the AD. size_t ad_len; }; static const struct KnownAEAD kAEADs[] = { {"AES_128_GCM", EVP_aead_aes_128_gcm, "aes_128_gcm_tests.txt", false, true, - 0}, + true, 0}, {"AES_128_GCM_NIST", EVP_aead_aes_128_gcm, "nist_cavp/aes_128_gcm.txt", - false, true, 0}, + false, true, true, 0}, {"AES_256_GCM", EVP_aead_aes_256_gcm, "aes_256_gcm_tests.txt", false, true, - 0}, + true, 0}, {"AES_256_GCM_NIST", EVP_aead_aes_256_gcm, "nist_cavp/aes_256_gcm.txt", - false, true, 0}, -#if !defined(OPENSSL_SMALL) + false, true, true, 0}, {"AES_128_GCM_SIV", EVP_aead_aes_128_gcm_siv, "aes_128_gcm_siv_tests.txt", - false, false, 0}, + false, false, false, 0}, {"AES_256_GCM_SIV", EVP_aead_aes_256_gcm_siv, "aes_256_gcm_siv_tests.txt", - false, false, 0}, -#endif + false, false, false, 0}, {"ChaCha20Poly1305", EVP_aead_chacha20_poly1305, - "chacha20_poly1305_tests.txt", false, true, 0}, + "chacha20_poly1305_tests.txt", false, true, false, 0}, {"XChaCha20Poly1305", EVP_aead_xchacha20_poly1305, - "xchacha20_poly1305_tests.txt", false, true, 0}, + "xchacha20_poly1305_tests.txt", false, true, false, 0}, {"AES_128_CBC_SHA1_TLS", EVP_aead_aes_128_cbc_sha1_tls, - "aes_128_cbc_sha1_tls_tests.txt", true, false, 11}, + "aes_128_cbc_sha1_tls_tests.txt", true, false, false, 11}, {"AES_128_CBC_SHA1_TLSImplicitIV", EVP_aead_aes_128_cbc_sha1_tls_implicit_iv, - "aes_128_cbc_sha1_tls_implicit_iv_tests.txt", true, false, 11}, + "aes_128_cbc_sha1_tls_implicit_iv_tests.txt", true, false, false, 11}, {"AES_128_CBC_SHA256_TLS", EVP_aead_aes_128_cbc_sha256_tls, - "aes_128_cbc_sha256_tls_tests.txt", true, false, 11}, + "aes_128_cbc_sha256_tls_tests.txt", true, false, false, 11}, {"AES_256_CBC_SHA1_TLS", EVP_aead_aes_256_cbc_sha1_tls, - "aes_256_cbc_sha1_tls_tests.txt", true, false, 11}, + "aes_256_cbc_sha1_tls_tests.txt", true, false, false, 11}, {"AES_256_CBC_SHA1_TLSImplicitIV", EVP_aead_aes_256_cbc_sha1_tls_implicit_iv, - "aes_256_cbc_sha1_tls_implicit_iv_tests.txt", true, false, 11}, + "aes_256_cbc_sha1_tls_implicit_iv_tests.txt", true, false, false, 11}, {"AES_256_CBC_SHA256_TLS", EVP_aead_aes_256_cbc_sha256_tls, - "aes_256_cbc_sha256_tls_tests.txt", true, false, 11}, + "aes_256_cbc_sha256_tls_tests.txt", true, false, false, 11}, {"AES_256_CBC_SHA384_TLS", EVP_aead_aes_256_cbc_sha384_tls, - "aes_256_cbc_sha384_tls_tests.txt", true, false, 11}, + "aes_256_cbc_sha384_tls_tests.txt", true, false, false, 11}, {"DES_EDE3_CBC_SHA1_TLS", EVP_aead_des_ede3_cbc_sha1_tls, - "des_ede3_cbc_sha1_tls_tests.txt", true, false, 11}, + "des_ede3_cbc_sha1_tls_tests.txt", true, false, false, 11}, {"DES_EDE3_CBC_SHA1_TLSImplicitIV", EVP_aead_des_ede3_cbc_sha1_tls_implicit_iv, - "des_ede3_cbc_sha1_tls_implicit_iv_tests.txt", true, false, 11}, + "des_ede3_cbc_sha1_tls_implicit_iv_tests.txt", true, false, false, 11}, {"AES_128_CTR_HMAC_SHA256", EVP_aead_aes_128_ctr_hmac_sha256, - "aes_128_ctr_hmac_sha256.txt", false, true, 0}, + "aes_128_ctr_hmac_sha256.txt", false, true, false, 0}, {"AES_256_CTR_HMAC_SHA256", EVP_aead_aes_256_ctr_hmac_sha256, - "aes_256_ctr_hmac_sha256.txt", false, true, 0}, + "aes_256_ctr_hmac_sha256.txt", false, true, false, 0}, {"AES_128_CCM_BLUETOOTH", EVP_aead_aes_128_ccm_bluetooth, - "aes_128_ccm_bluetooth_tests.txt", false, false, 0}, + "aes_128_ccm_bluetooth_tests.txt", false, false, false, 0}, {"AES_128_CCM_BLUETOOTH_8", EVP_aead_aes_128_ccm_bluetooth_8, - "aes_128_ccm_bluetooth_8_tests.txt", false, false, 0}, + "aes_128_ccm_bluetooth_8_tests.txt", false, false, false, 0}, }; class PerAEADTest : public testing::TestWithParam { @@ -101,9 +101,9 @@ class PerAEADTest : public testing::TestWithParam { const EVP_AEAD *aead() { return GetParam().func(); } }; -INSTANTIATE_TEST_CASE_P(, PerAEADTest, testing::ValuesIn(kAEADs), - [](const testing::TestParamInfo ¶ms) - -> std::string { return params.param.name; }); +INSTANTIATE_TEST_SUITE_P(, PerAEADTest, testing::ValuesIn(kAEADs), + [](const testing::TestParamInfo ¶ms) + -> std::string { return params.param.name; }); // Tests an AEAD against a series of test vectors from a file, using the // FileTest format. As an example, here's a valid test case: @@ -607,50 +607,59 @@ TEST_P(PerAEADTest, Overflow) { // as the input.) } -// Test that EVP_aead_aes_128_gcm and EVP_aead_aes_256_gcm reject empty nonces. -// AES-GCM is not defined for those. -TEST(AEADTest, AESGCMEmptyNonce) { - static const uint8_t kZeros[32] = {0}; +TEST_P(PerAEADTest, InvalidNonceLength) { + size_t valid_nonce_len = EVP_AEAD_nonce_length(aead()); + std::vector nonce_lens; + if (valid_nonce_len != 0) { + // Other than the implicit IV TLS "AEAD"s, none of our AEADs allow empty + // nonces. In particular, although AES-GCM was incorrectly specified with + // variable-length nonces, it does not allow the empty nonce. + nonce_lens.push_back(0); + } + if (!GetParam().variable_nonce) { + nonce_lens.push_back(valid_nonce_len + 1); + if (valid_nonce_len != 0) { + nonce_lens.push_back(valid_nonce_len - 1); + } + } - // Test AES-128-GCM. - uint8_t buf[16]; - size_t len; - bssl::ScopedEVP_AEAD_CTX ctx; - ASSERT_TRUE(EVP_AEAD_CTX_init(ctx.get(), EVP_aead_aes_128_gcm(), kZeros, 16, - EVP_AEAD_DEFAULT_TAG_LENGTH, nullptr)); + static const uint8_t kZeros[EVP_AEAD_MAX_KEY_LENGTH] = {0}; + const size_t ad_len = GetParam().ad_len != 0 ? GetParam().ad_len : 16; + ASSERT_LE(ad_len, sizeof(kZeros)); - EXPECT_FALSE(EVP_AEAD_CTX_seal(ctx.get(), buf, &len, sizeof(buf), - nullptr /* nonce */, 0, nullptr /* in */, 0, - nullptr /* ad */, 0)); - uint32_t err = ERR_get_error(); - EXPECT_EQ(ERR_LIB_CIPHER, ERR_GET_LIB(err)); - EXPECT_EQ(CIPHER_R_INVALID_NONCE_SIZE, ERR_GET_REASON(err)); + for (size_t nonce_len : nonce_lens) { + SCOPED_TRACE(nonce_len); + uint8_t buf[256]; + size_t len; + std::vector nonce(nonce_len); + bssl::ScopedEVP_AEAD_CTX ctx; + ASSERT_TRUE(EVP_AEAD_CTX_init_with_direction( + ctx.get(), aead(), kZeros, EVP_AEAD_key_length(aead()), + EVP_AEAD_DEFAULT_TAG_LENGTH, evp_aead_seal)); - EXPECT_FALSE(EVP_AEAD_CTX_open(ctx.get(), buf, &len, sizeof(buf), - nullptr /* nonce */, 0, kZeros /* in */, - sizeof(kZeros), nullptr /* ad */, 0)); - err = ERR_get_error(); - EXPECT_EQ(ERR_LIB_CIPHER, ERR_GET_LIB(err)); - EXPECT_EQ(CIPHER_R_INVALID_NONCE_SIZE, ERR_GET_REASON(err)); + EXPECT_FALSE(EVP_AEAD_CTX_seal(ctx.get(), buf, &len, sizeof(buf), + nonce.data(), nonce.size(), nullptr /* in */, + 0, kZeros /* ad */, ad_len)); + uint32_t err = ERR_get_error(); + EXPECT_EQ(ERR_LIB_CIPHER, ERR_GET_LIB(err)); + // TODO(davidben): Merge these errors. https://crbug.com/boringssl/129. + if (ERR_GET_REASON(err) != CIPHER_R_UNSUPPORTED_NONCE_SIZE) { + EXPECT_EQ(CIPHER_R_INVALID_NONCE_SIZE, ERR_GET_REASON(err)); + } - // Test AES-256-GCM. - ctx.Reset(); - ASSERT_TRUE(EVP_AEAD_CTX_init(ctx.get(), EVP_aead_aes_256_gcm(), kZeros, 32, - EVP_AEAD_DEFAULT_TAG_LENGTH, nullptr)); - - EXPECT_FALSE(EVP_AEAD_CTX_seal(ctx.get(), buf, &len, sizeof(buf), - nullptr /* nonce */, 0, nullptr /* in */, 0, - nullptr /* ad */, 0)); - err = ERR_get_error(); - EXPECT_EQ(ERR_LIB_CIPHER, ERR_GET_LIB(err)); - EXPECT_EQ(CIPHER_R_INVALID_NONCE_SIZE, ERR_GET_REASON(err)); - - EXPECT_FALSE(EVP_AEAD_CTX_open(ctx.get(), buf, &len, sizeof(buf), - nullptr /* nonce */, 0, kZeros /* in */, - sizeof(kZeros), nullptr /* ad */, 0)); - err = ERR_get_error(); - EXPECT_EQ(ERR_LIB_CIPHER, ERR_GET_LIB(err)); - EXPECT_EQ(CIPHER_R_INVALID_NONCE_SIZE, ERR_GET_REASON(err)); + ctx.Reset(); + ASSERT_TRUE(EVP_AEAD_CTX_init_with_direction( + ctx.get(), aead(), kZeros, EVP_AEAD_key_length(aead()), + EVP_AEAD_DEFAULT_TAG_LENGTH, evp_aead_open)); + EXPECT_FALSE(EVP_AEAD_CTX_open(ctx.get(), buf, &len, sizeof(buf), + nonce.data(), nonce.size(), kZeros /* in */, + sizeof(kZeros), kZeros /* ad */, ad_len)); + err = ERR_get_error(); + EXPECT_EQ(ERR_LIB_CIPHER, ERR_GET_LIB(err)); + if (ERR_GET_REASON(err) != CIPHER_R_UNSUPPORTED_NONCE_SIZE) { + EXPECT_EQ(CIPHER_R_INVALID_NONCE_SIZE, ERR_GET_REASON(err)); + } + } } TEST(AEADTest, AESCCMLargeAD) { diff --git a/third_party/boringssl/kit/src/crypto/cipher_extra/asm/aes128gcmsiv-x86_64.pl b/third_party/boringssl/kit/src/crypto/cipher_extra/asm/aes128gcmsiv-x86_64.pl index 1a3d064e..54f0b5cb 100644 --- a/third_party/boringssl/kit/src/crypto/cipher_extra/asm/aes128gcmsiv-x86_64.pl +++ b/third_party/boringssl/kit/src/crypto/cipher_extra/asm/aes128gcmsiv-x86_64.pl @@ -2253,4 +2253,4 @@ aes256gcmsiv_kdf(); print $code; -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/cipher_extra/asm/chacha20_poly1305_x86_64.pl b/third_party/boringssl/kit/src/crypto/cipher_extra/asm/chacha20_poly1305_x86_64.pl index 0e322798..5b2b977d 100644 --- a/third_party/boringssl/kit/src/crypto/cipher_extra/asm/chacha20_poly1305_x86_64.pl +++ b/third_party/boringssl/kit/src/crypto/cipher_extra/asm/chacha20_poly1305_x86_64.pl @@ -2485,4 +2485,4 @@ dummy_chacha20_poly1305_asm: ___ } -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/cipher_extra/cipher_extra.c b/third_party/boringssl/kit/src/crypto/cipher_extra/cipher_extra.c index 1b23ad32..b132265b 100644 --- a/third_party/boringssl/kit/src/crypto/cipher_extra/cipher_extra.c +++ b/third_party/boringssl/kit/src/crypto/cipher_extra/cipher_extra.c @@ -129,6 +129,14 @@ const EVP_CIPHER *EVP_get_cipherbyname(const char *name) { return EVP_aes_192_ofb(); } else if (OPENSSL_strcasecmp(name, "aes-256-ofb") == 0) { return EVP_aes_256_ofb(); + } else if (OPENSSL_strcasecmp(name, "des-ecb") == 0) { + return EVP_des_ecb(); + } else if (OPENSSL_strcasecmp(name, "des-ede") == 0) { + return EVP_des_ede(); + } else if (OPENSSL_strcasecmp(name, "des-ede-cbc") == 0) { + return EVP_des_ede_cbc(); + } else if (OPENSSL_strcasecmp(name, "rc2-cbc") == 0) { + return EVP_rc2_cbc(); } return NULL; diff --git a/third_party/boringssl/kit/src/crypto/cipher_extra/cipher_test.cc b/third_party/boringssl/kit/src/crypto/cipher_extra/cipher_test.cc index 62ef9396..0a96bf39 100644 --- a/third_party/boringssl/kit/src/crypto/cipher_extra/cipher_test.cc +++ b/third_party/boringssl/kit/src/crypto/cipher_extra/cipher_test.cc @@ -150,7 +150,8 @@ static bool DoCipher(EVP_CIPHER_CTX *ctx, std::vector *out, } static void TestOperation(FileTest *t, const EVP_CIPHER *cipher, bool encrypt, - size_t chunk_size, const std::vector &key, + bool copy, size_t chunk_size, + const std::vector &key, const std::vector &iv, const std::vector &plaintext, const std::vector &ciphertext, @@ -167,45 +168,52 @@ static void TestOperation(FileTest *t, const EVP_CIPHER *cipher, bool encrypt, bool is_aead = EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE; - bssl::ScopedEVP_CIPHER_CTX ctx; - ASSERT_TRUE(EVP_CipherInit_ex(ctx.get(), cipher, nullptr, nullptr, nullptr, - encrypt ? 1 : 0)); + bssl::ScopedEVP_CIPHER_CTX ctx1; + ASSERT_TRUE(EVP_CipherInit_ex(ctx1.get(), cipher, nullptr, nullptr, nullptr, + encrypt ? 1 : 0)); if (t->HasAttribute("IV")) { if (is_aead) { - ASSERT_TRUE(EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_AEAD_SET_IVLEN, + ASSERT_TRUE(EVP_CIPHER_CTX_ctrl(ctx1.get(), EVP_CTRL_AEAD_SET_IVLEN, iv.size(), 0)); } else { - ASSERT_EQ(iv.size(), EVP_CIPHER_CTX_iv_length(ctx.get())); + ASSERT_EQ(iv.size(), EVP_CIPHER_CTX_iv_length(ctx1.get())); } } + + bssl::ScopedEVP_CIPHER_CTX ctx2; + EVP_CIPHER_CTX *ctx = ctx1.get(); + if (copy) { + ASSERT_TRUE(EVP_CIPHER_CTX_copy(ctx2.get(), ctx1.get())); + ctx = ctx2.get(); + } + if (is_aead && !encrypt) { - ASSERT_TRUE(EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_AEAD_SET_TAG, - tag.size(), + ASSERT_TRUE(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, tag.size(), const_cast(tag.data()))); } // The ciphers are run with no padding. For each of the ciphers we test, the // output size matches the input size. ASSERT_EQ(in->size(), out->size()); - ASSERT_TRUE(EVP_CIPHER_CTX_set_key_length(ctx.get(), key.size())); - ASSERT_TRUE(EVP_CipherInit_ex(ctx.get(), nullptr, nullptr, key.data(), - iv.data(), -1)); + ASSERT_TRUE(EVP_CIPHER_CTX_set_key_length(ctx, key.size())); + ASSERT_TRUE( + EVP_CipherInit_ex(ctx, nullptr, nullptr, key.data(), iv.data(), -1)); // Note: the deprecated |EVP_CIPHER|-based AEAD API is sensitive to whether // parameters are NULL, so it is important to skip the |in| and |aad| // |EVP_CipherUpdate| calls when empty. if (!aad.empty()) { int unused; ASSERT_TRUE( - EVP_CipherUpdate(ctx.get(), nullptr, &unused, aad.data(), aad.size())); + EVP_CipherUpdate(ctx, nullptr, &unused, aad.data(), aad.size())); } - ASSERT_TRUE(EVP_CIPHER_CTX_set_padding(ctx.get(), 0)); + ASSERT_TRUE(EVP_CIPHER_CTX_set_padding(ctx, 0)); std::vector result; - ASSERT_TRUE(DoCipher(ctx.get(), &result, *in, chunk_size)); + ASSERT_TRUE(DoCipher(ctx, &result, *in, chunk_size)); EXPECT_EQ(Bytes(*out), Bytes(result)); if (encrypt && is_aead) { uint8_t rtag[16]; ASSERT_LE(tag.size(), sizeof(rtag)); - ASSERT_TRUE(EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_AEAD_GET_TAG, - tag.size(), rtag)); + ASSERT_TRUE( + EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, tag.size(), rtag)); EXPECT_EQ(Bytes(tag), Bytes(rtag, tag.size())); } } @@ -252,14 +260,18 @@ static void TestCipher(FileTest *t) { // By default, both directions are run, unless overridden by the operation. if (operation != kDecrypt) { SCOPED_TRACE("encrypt"); - TestOperation(t, cipher, true /* encrypt */, chunk_size, key, iv, - plaintext, ciphertext, aad, tag); + TestOperation(t, cipher, true /* encrypt */, false /* no copy */, + chunk_size, key, iv, plaintext, ciphertext, aad, tag); + TestOperation(t, cipher, true /* encrypt */, true /* copy */, chunk_size, + key, iv, plaintext, ciphertext, aad, tag); } if (operation != kEncrypt) { SCOPED_TRACE("decrypt"); - TestOperation(t, cipher, false /* decrypt */, chunk_size, key, iv, - plaintext, ciphertext, aad, tag); + TestOperation(t, cipher, false /* decrypt */, false /* no copy */, + chunk_size, key, iv, plaintext, ciphertext, aad, tag); + TestOperation(t, cipher, false /* decrypt */, true /* copy */, chunk_size, + key, iv, plaintext, ciphertext, aad, tag); } } } diff --git a/third_party/boringssl/kit/src/crypto/cipher_extra/e_aesgcmsiv.c b/third_party/boringssl/kit/src/crypto/cipher_extra/e_aesgcmsiv.c index 71a71fac..64febae4 100644 --- a/third_party/boringssl/kit/src/crypto/cipher_extra/e_aesgcmsiv.c +++ b/third_party/boringssl/kit/src/crypto/cipher_extra/e_aesgcmsiv.c @@ -426,6 +426,11 @@ static int aead_aes_gcm_siv_asm_open(const EVP_AEAD_CTX *ctx, uint8_t *out, return 0; } + if (nonce_len != EVP_AEAD_AES_GCM_SIV_NONCE_LEN) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE); + return 0; + } + const struct aead_aes_gcm_siv_asm_ctx *gcm_siv_ctx = asm_ctx_from_ctx(ctx); const size_t plaintext_len = in_len - EVP_AEAD_AES_GCM_SIV_TAG_LEN; const uint8_t *const given_tag = in + plaintext_len; diff --git a/third_party/boringssl/kit/src/crypto/cpu-intel.c b/third_party/boringssl/kit/src/crypto/cpu-intel.c index 98d8d4e5..1621ef6c 100644 --- a/third_party/boringssl/kit/src/crypto/cpu-intel.c +++ b/third_party/boringssl/kit/src/crypto/cpu-intel.c @@ -148,6 +148,9 @@ void OPENSSL_cpuid_setup(void) { int is_intel = ebx == 0x756e6547 /* Genu */ && edx == 0x49656e69 /* ineI */ && ecx == 0x6c65746e /* ntel */; + int is_amd = ebx == 0x68747541 /* Auth */ && + edx == 0x69746e65 /* enti */ && + ecx == 0x444d4163 /* cAMD */; uint32_t extended_features[2] = {0}; if (num_ids >= 7) { @@ -158,6 +161,24 @@ void OPENSSL_cpuid_setup(void) { OPENSSL_cpuid(&eax, &ebx, &ecx, &edx, 1); + if (is_amd) { + // See https://www.amd.com/system/files/TechDocs/25481.pdf, page 10. + const uint32_t base_family = (eax >> 8) & 15; + + uint32_t family = base_family; + if (base_family == 0xf) { + const uint32_t ext_family = (eax >> 20) & 255; + family += ext_family; + } + + if (family < 0x17) { + // Disable RDRAND on AMD families before 0x17 (Zen) due to reported + // failures after suspend. + // https://bugzilla.redhat.com/show_bug.cgi?id=1150286 + ecx &= ~(1u << 30); + } + } + // Force the hyper-threading bit so that the more conservative path is always // chosen. edx |= 1u << 28; diff --git a/third_party/boringssl/kit/src/crypto/crypto.c b/third_party/boringssl/kit/src/crypto/crypto.c index f7ac2558..c86206a0 100644 --- a/third_party/boringssl/kit/src/crypto/crypto.c +++ b/third_party/boringssl/kit/src/crypto/crypto.c @@ -36,8 +36,8 @@ #define BORINGSSL_NO_STATIC_INITIALIZER #endif -#endif /* !OPENSSL_NO_ASM && (OPENSSL_X86 || OPENSSL_X86_64 || - OPENSSL_ARM || OPENSSL_AARCH64) */ +#endif // !NO_ASM && !STATIC_ARMCAP && + // (X86 || X86_64 || ARM || AARCH64 || PPC64LE) // Our assembly does not use the GOT to reference symbols, which means @@ -60,8 +60,7 @@ // that tests the capability values will still skip the constructor but, so // far, the init constructor function only sets the capability variables. -#if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) - +#if !defined(NDEBUG) && !defined(BORINGSSL_FIPS) // This value must be explicitly initialised to zero in order to work around a // bug in libtool or the linker on OS X. // @@ -69,6 +68,12 @@ // archive, linking on OS X will fail to resolve common symbols. By // initialising it to zero, it becomes a "data symbol", which isn't so // affected. +HIDDEN uint8_t BORINGSSL_function_hit[7] = {0}; +#endif + +#if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) + +// This value must be explicitly initialized to zero. See similar comment above. HIDDEN uint32_t OPENSSL_ia32cap_P[4] = {0}; #elif defined(OPENSSL_PPC64LE) diff --git a/third_party/boringssl/kit/src/crypto/digest_extra/digest_test.cc b/third_party/boringssl/kit/src/crypto/digest_extra/digest_test.cc index 72e10b11..6d02c087 100644 --- a/third_party/boringssl/kit/src/crypto/digest_extra/digest_test.cc +++ b/third_party/boringssl/kit/src/crypto/digest_extra/digest_test.cc @@ -17,6 +17,7 @@ #include #include +#include #include @@ -54,7 +55,7 @@ static const MD sha384 = { "SHA384", &EVP_sha384, &SHA384 }; static const MD sha512 = { "SHA512", &EVP_sha512, &SHA512 }; static const MD md5_sha1 = { "MD5-SHA1", &EVP_md5_sha1, nullptr }; -struct TestVector { +struct DigestTestVector { // md is the digest to test. const MD &md; // input is a NUL-terminated string to hash. @@ -65,7 +66,7 @@ struct TestVector { const char *expected_hex; }; -static const TestVector kTestVectors[] = { +static const DigestTestVector kTestVectors[] = { // MD4 tests, from RFC 1320. (crypto/md4 does not provide a // one-shot MD4 function.) { md4, "", 1, "31d6cfe0d16ae931b73c59d7e0c089c0" }, @@ -143,7 +144,7 @@ static const TestVector kTestVectors[] = { "900150983cd24fb0d6963f7d28e17f72a9993e364706816aba3e25717850c26c9cd0d89d" }, }; -static void CompareDigest(const TestVector *test, +static void CompareDigest(const DigestTestVector *test, const uint8_t *digest, size_t digest_len) { static const char kHexTable[] = "0123456789abcdef"; @@ -158,7 +159,7 @@ static void CompareDigest(const TestVector *test, EXPECT_STREQ(test->expected_hex, digest_hex); } -static void TestDigest(const TestVector *test) { +static void TestDigest(const DigestTestVector *test) { bssl::ScopedEVP_MD_CTX ctx; // Test the input provided. @@ -183,6 +184,42 @@ static void TestDigest(const TestVector *test) { EXPECT_EQ(EVP_MD_size(test->md.func()), digest_len); CompareDigest(test, digest.get(), digest_len); + // Test with unaligned input. + ASSERT_TRUE(EVP_DigestInit_ex(ctx.get(), test->md.func(), NULL)); + std::vector unaligned(strlen(test->input) + 1); + char *ptr = unaligned.data(); + if ((reinterpret_cast(ptr) & 1) == 0) { + ptr++; + } + OPENSSL_memcpy(ptr, test->input, strlen(test->input)); + for (size_t i = 0; i < test->repeat; i++) { + ASSERT_TRUE(EVP_DigestUpdate(ctx.get(), ptr, strlen(test->input))); + } + ASSERT_TRUE(EVP_DigestFinal_ex(ctx.get(), digest.get(), &digest_len)); + CompareDigest(test, digest.get(), digest_len); + + // Make a copy of the digest in the initial state. + ASSERT_TRUE(EVP_DigestInit_ex(ctx.get(), test->md.func(), NULL)); + bssl::ScopedEVP_MD_CTX copy; + ASSERT_TRUE(EVP_MD_CTX_copy_ex(copy.get(), ctx.get())); + for (size_t i = 0; i < test->repeat; i++) { + ASSERT_TRUE(EVP_DigestUpdate(copy.get(), test->input, strlen(test->input))); + } + ASSERT_TRUE(EVP_DigestFinal_ex(copy.get(), digest.get(), &digest_len)); + CompareDigest(test, digest.get(), digest_len); + + // Make a copy of the digest with half the input provided. + size_t half = strlen(test->input) / 2; + ASSERT_TRUE(EVP_DigestUpdate(ctx.get(), test->input, half)); + ASSERT_TRUE(EVP_MD_CTX_copy_ex(copy.get(), ctx.get())); + ASSERT_TRUE(EVP_DigestUpdate(copy.get(), test->input + half, + strlen(test->input) - half)); + for (size_t i = 1; i < test->repeat; i++) { + ASSERT_TRUE(EVP_DigestUpdate(copy.get(), test->input, strlen(test->input))); + } + ASSERT_TRUE(EVP_DigestFinal_ex(copy.get(), digest.get(), &digest_len)); + CompareDigest(test, digest.get(), digest_len); + // Test the one-shot function. if (test->md.one_shot_func && test->repeat == 1) { uint8_t *out = test->md.one_shot_func((const uint8_t *)test->input, diff --git a/third_party/boringssl/kit/src/crypto/dsa/dsa.c b/third_party/boringssl/kit/src/crypto/dsa/dsa.c index 288e2c80..51dca7f7 100644 --- a/third_party/boringssl/kit/src/crypto/dsa/dsa.c +++ b/third_party/boringssl/kit/src/crypto/dsa/dsa.c @@ -558,29 +558,34 @@ static int mod_mul_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, } DSA_SIG *DSA_do_sign(const uint8_t *digest, size_t digest_len, const DSA *dsa) { - BIGNUM *kinv = NULL, *r = NULL, *s = NULL; - BIGNUM m; - BIGNUM xr; - BN_CTX *ctx = NULL; - int reason = ERR_R_BN_LIB; - DSA_SIG *ret = NULL; - - BN_init(&m); - BN_init(&xr); - if (!dsa->p || !dsa->q || !dsa->g) { - reason = DSA_R_MISSING_PARAMETERS; - goto err; + OPENSSL_PUT_ERROR(DSA, DSA_R_MISSING_PARAMETERS); + return NULL; + } + + // Reject invalid parameters. In particular, the algorithm will infinite loop + // if |g| is zero. + if (BN_is_zero(dsa->p) || BN_is_zero(dsa->q) || BN_is_zero(dsa->g)) { + OPENSSL_PUT_ERROR(DSA, DSA_R_INVALID_PARAMETERS); + return NULL; } // We only support DSA keys that are a multiple of 8 bits. (This is a weaker // check than the one in |DSA_do_check_signature|, which only allows 160-, // 224-, and 256-bit keys. if (BN_num_bits(dsa->q) % 8 != 0) { - reason = DSA_R_BAD_Q_VALUE; - goto err; + OPENSSL_PUT_ERROR(DSA, DSA_R_BAD_Q_VALUE); + return NULL; } + BIGNUM *kinv = NULL, *r = NULL, *s = NULL; + BIGNUM m; + BIGNUM xr; + BN_CTX *ctx = NULL; + DSA_SIG *ret = NULL; + + BN_init(&m); + BN_init(&xr); s = BN_new(); if (s == NULL) { goto err; @@ -640,7 +645,7 @@ redo: err: if (ret == NULL) { - OPENSSL_PUT_ERROR(DSA, reason); + OPENSSL_PUT_ERROR(DSA, ERR_R_BN_LIB); BN_free(r); BN_free(s); } diff --git a/third_party/boringssl/kit/src/crypto/dsa/dsa_test.cc b/third_party/boringssl/kit/src/crypto/dsa/dsa_test.cc index 295a7fd1..46821316 100644 --- a/third_party/boringssl/kit/src/crypto/dsa/dsa_test.cc +++ b/third_party/boringssl/kit/src/crypto/dsa/dsa_test.cc @@ -62,6 +62,8 @@ #include #include +#include + #include #include @@ -315,3 +317,18 @@ TEST(DSATest, AllTests) { ADD_FAILURE() << "Tests failed"; } } + +TEST(DSATest, InvalidGroup) { + bssl::UniquePtr dsa = GetFIPSDSA(); + ASSERT_TRUE(dsa); + BN_zero(dsa->g); + + std::vector sig(DSA_size(dsa.get())); + unsigned sig_len; + static const uint8_t kDigest[32] = {0}; + EXPECT_FALSE( + DSA_sign(0, kDigest, sizeof(kDigest), sig.data(), &sig_len, dsa.get())); + uint32_t err = ERR_get_error(); + EXPECT_EQ(ERR_LIB_DSA, ERR_GET_LIB(err)); + EXPECT_EQ(DSA_R_INVALID_PARAMETERS, ERR_GET_REASON(err)); +} diff --git a/third_party/boringssl/kit/src/crypto/ec_extra/ec_asn1.c b/third_party/boringssl/kit/src/crypto/ec_extra/ec_asn1.c index 6e212751..31988f3f 100644 --- a/third_party/boringssl/kit/src/crypto/ec_extra/ec_asn1.c +++ b/third_party/boringssl/kit/src/crypto/ec_extra/ec_asn1.c @@ -159,8 +159,8 @@ EC_KEY *EC_KEY_parse_private_key(CBS *cbs, const EC_GROUP *group) { (point_conversion_form_t)(CBS_data(&public_key)[0] & ~0x01); } else { // Compute the public key instead. - if (!ec_point_mul_scalar(group, &ret->pub_key->raw, &ret->priv_key->scalar, - NULL, NULL)) { + if (!ec_point_mul_scalar_base(group, &ret->pub_key->raw, + &ret->priv_key->scalar)) { goto err; } // Remember the original private-key-only encoding. diff --git a/third_party/boringssl/kit/src/crypto/ecdh_extra/ecdh_extra.c b/third_party/boringssl/kit/src/crypto/ecdh_extra/ecdh_extra.c index 1e080995..b8a099a5 100644 --- a/third_party/boringssl/kit/src/crypto/ecdh_extra/ecdh_extra.c +++ b/third_party/boringssl/kit/src/crypto/ecdh_extra/ecdh_extra.c @@ -95,7 +95,7 @@ int ECDH_compute_key(void *out, size_t out_len, const EC_POINT *pub_key, EC_RAW_POINT shared_point; uint8_t buf[EC_MAX_BYTES]; size_t buf_len; - if (!ec_point_mul_scalar(group, &shared_point, NULL, &pub_key->raw, priv) || + if (!ec_point_mul_scalar(group, &shared_point, &pub_key->raw, priv) || !ec_point_get_affine_coordinate_bytes(group, buf, NULL, &buf_len, sizeof(buf), &shared_point)) { OPENSSL_PUT_ERROR(ECDH, ECDH_R_POINT_ARITHMETIC_FAILURE); diff --git a/third_party/boringssl/kit/src/crypto/engine/engine.c b/third_party/boringssl/kit/src/crypto/engine/engine.c index 875f1480..973a57c8 100644 --- a/third_party/boringssl/kit/src/crypto/engine/engine.c +++ b/third_party/boringssl/kit/src/crypto/engine/engine.c @@ -41,9 +41,10 @@ ENGINE *ENGINE_new(void) { return engine; } -void ENGINE_free(ENGINE *engine) { +int ENGINE_free(ENGINE *engine) { // Methods are currently required to be static so are not unref'ed. OPENSSL_free(engine); + return 1; } // set_method takes a pointer to a method and its given size and sets diff --git a/third_party/boringssl/kit/src/crypto/err/dsa.errordata b/third_party/boringssl/kit/src/crypto/err/dsa.errordata index 6f4bc138..1cf5206d 100644 --- a/third_party/boringssl/kit/src/crypto/err/dsa.errordata +++ b/third_party/boringssl/kit/src/crypto/err/dsa.errordata @@ -2,6 +2,7 @@ DSA,100,BAD_Q_VALUE DSA,104,BAD_VERSION DSA,105,DECODE_ERROR DSA,106,ENCODE_ERROR +DSA,107,INVALID_PARAMETERS DSA,101,MISSING_PARAMETERS DSA,102,MODULUS_TOO_LARGE DSA,103,NEED_NEW_SETUP_VALUES diff --git a/third_party/boringssl/kit/src/crypto/err/ssl.errordata b/third_party/boringssl/kit/src/crypto/err/ssl.errordata index 171b9c70..ddb383c3 100644 --- a/third_party/boringssl/kit/src/crypto/err/ssl.errordata +++ b/third_party/boringssl/kit/src/crypto/err/ssl.errordata @@ -75,12 +75,14 @@ SSL,157,INAPPROPRIATE_FALLBACK SSL,259,INVALID_ALPN_PROTOCOL SSL,158,INVALID_COMMAND SSL,256,INVALID_COMPRESSION_LIST +SSL,301,INVALID_DELEGATED_CREDENTIAL SSL,159,INVALID_MESSAGE SSL,251,INVALID_OUTER_RECORD_TYPE SSL,269,INVALID_SCT_LIST SSL,295,INVALID_SIGNATURE_ALGORITHM SSL,160,INVALID_SSL_SESSION SSL,161,INVALID_TICKET_KEYS_LENGTH +SSL,302,KEY_USAGE_BIT_INCORRECT SSL,162,LENGTH_MISMATCH SSL,164,MISSING_EXTENSION SSL,258,MISSING_KEY_SHARE @@ -193,7 +195,7 @@ SSL,218,TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG SSL,219,TOO_MANY_EMPTY_FRAGMENTS SSL,260,TOO_MANY_KEY_UPDATES SSL,220,TOO_MANY_WARNING_ALERTS -SSL,1117,TOO_MUCH_READ_EARLY_DATA +SSL,300,TOO_MUCH_READ_EARLY_DATA SSL,270,TOO_MUCH_SKIPPED_EARLY_DATA SSL,221,UNABLE_TO_FIND_ECDH_PARAMETERS SSL,293,UNCOMPRESSED_CERT_TOO_LARGE diff --git a/third_party/boringssl/kit/src/crypto/evp/evp.c b/third_party/boringssl/kit/src/crypto/evp/evp.c index ed7cc85b..de4db7ef 100644 --- a/third_party/boringssl/kit/src/crypto/evp/evp.c +++ b/third_party/boringssl/kit/src/crypto/evp/evp.c @@ -330,7 +330,73 @@ int EVP_PKEY_set_type(EVP_PKEY *pkey, int type) { return 1; } +EVP_PKEY *EVP_PKEY_new_raw_private_key(int type, ENGINE *unused, + const uint8_t *in, size_t len) { + EVP_PKEY *ret = EVP_PKEY_new(); + if (ret == NULL || + !EVP_PKEY_set_type(ret, type)) { + goto err; + } + if (ret->ameth->set_priv_raw == NULL) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); + goto err; + } + + if (!ret->ameth->set_priv_raw(ret, in, len)) { + goto err; + } + + return ret; + +err: + EVP_PKEY_free(ret); + return NULL; +} + +EVP_PKEY *EVP_PKEY_new_raw_public_key(int type, ENGINE *unused, + const uint8_t *in, size_t len) { + EVP_PKEY *ret = EVP_PKEY_new(); + if (ret == NULL || + !EVP_PKEY_set_type(ret, type)) { + goto err; + } + + if (ret->ameth->set_pub_raw == NULL) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); + goto err; + } + + if (!ret->ameth->set_pub_raw(ret, in, len)) { + goto err; + } + + return ret; + +err: + EVP_PKEY_free(ret); + return NULL; +} + +int EVP_PKEY_get_raw_private_key(const EVP_PKEY *pkey, uint8_t *out, + size_t *out_len) { + if (pkey->ameth->get_priv_raw == NULL) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); + return 0; + } + + return pkey->ameth->get_priv_raw(pkey, out, out_len); +} + +int EVP_PKEY_get_raw_public_key(const EVP_PKEY *pkey, uint8_t *out, + size_t *out_len) { + if (pkey->ameth->get_pub_raw == NULL) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); + return 0; + } + + return pkey->ameth->get_pub_raw(pkey, out, out_len); +} int EVP_PKEY_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b) { if (a->type != b->type) { diff --git a/third_party/boringssl/kit/src/crypto/evp/evp_asn1.c b/third_party/boringssl/kit/src/crypto/evp/evp_asn1.c index 383e2f9b..d56b93b0 100644 --- a/third_party/boringssl/kit/src/crypto/evp/evp_asn1.c +++ b/third_party/boringssl/kit/src/crypto/evp/evp_asn1.c @@ -344,3 +344,44 @@ int i2d_PublicKey(const EVP_PKEY *key, uint8_t **outp) { return -1; } } + +EVP_PKEY *d2i_PublicKey(int type, EVP_PKEY **out, const uint8_t **inp, + long len) { + EVP_PKEY *ret = EVP_PKEY_new(); + if (ret == NULL) { + return NULL; + } + + CBS cbs; + CBS_init(&cbs, *inp, len < 0 ? 0 : (size_t)len); + switch (type) { + case EVP_PKEY_RSA: { + RSA *rsa = RSA_parse_public_key(&cbs); + if (rsa == NULL || !EVP_PKEY_assign_RSA(ret, rsa)) { + RSA_free(rsa); + goto err; + } + break; + } + + // Unlike OpenSSL, we do not support EC keys with this API. The raw EC + // public key serialization requires knowing the group. In OpenSSL, calling + // this function with |EVP_PKEY_EC| and setting |out| to NULL does not work. + // It requires |*out| to include a partially-initiazed |EVP_PKEY| to extract + // the group. + default: + OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_PUBLIC_KEY_TYPE); + goto err; + } + + *inp = CBS_data(&cbs); + if (out != NULL) { + EVP_PKEY_free(*out); + *out = ret; + } + return ret; + +err: + EVP_PKEY_free(ret); + return NULL; +} diff --git a/third_party/boringssl/kit/src/crypto/evp/evp_ctx.c b/third_party/boringssl/kit/src/crypto/evp/evp_ctx.c index 3599f778..daa1954b 100644 --- a/third_party/boringssl/kit/src/crypto/evp/evp_ctx.c +++ b/third_party/boringssl/kit/src/crypto/evp/evp_ctx.c @@ -415,7 +415,7 @@ int EVP_PKEY_keygen_init(EVP_PKEY_CTX *ctx) { return 1; } -int EVP_PKEY_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey) { +int EVP_PKEY_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY **out_pkey) { if (!ctx || !ctx->pmeth || !ctx->pmeth->keygen) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; @@ -425,21 +425,60 @@ int EVP_PKEY_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey) { return 0; } - if (!ppkey) { + if (!out_pkey) { return 0; } - if (!*ppkey) { - *ppkey = EVP_PKEY_new(); - if (!*ppkey) { + if (!*out_pkey) { + *out_pkey = EVP_PKEY_new(); + if (!*out_pkey) { OPENSSL_PUT_ERROR(EVP, ERR_LIB_EVP); return 0; } } - if (!ctx->pmeth->keygen(ctx, *ppkey)) { - EVP_PKEY_free(*ppkey); - *ppkey = NULL; + if (!ctx->pmeth->keygen(ctx, *out_pkey)) { + EVP_PKEY_free(*out_pkey); + *out_pkey = NULL; + return 0; + } + return 1; +} + +int EVP_PKEY_paramgen_init(EVP_PKEY_CTX *ctx) { + if (!ctx || !ctx->pmeth || !ctx->pmeth->paramgen) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); + return 0; + } + ctx->operation = EVP_PKEY_OP_PARAMGEN; + return 1; +} + +int EVP_PKEY_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY **out_pkey) { + if (!ctx || !ctx->pmeth || !ctx->pmeth->paramgen) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); + return 0; + } + if (ctx->operation != EVP_PKEY_OP_PARAMGEN) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATON_NOT_INITIALIZED); + return 0; + } + + if (!out_pkey) { + return 0; + } + + if (!*out_pkey) { + *out_pkey = EVP_PKEY_new(); + if (!*out_pkey) { + OPENSSL_PUT_ERROR(EVP, ERR_LIB_EVP); + return 0; + } + } + + if (!ctx->pmeth->paramgen(ctx, *out_pkey)) { + EVP_PKEY_free(*out_pkey); + *out_pkey = NULL; return 0; } return 1; diff --git a/third_party/boringssl/kit/src/crypto/evp/evp_extra_test.cc b/third_party/boringssl/kit/src/crypto/evp/evp_extra_test.cc index f12650ef..f5205988 100644 --- a/third_party/boringssl/kit/src/crypto/evp/evp_extra_test.cc +++ b/third_party/boringssl/kit/src/crypto/evp/evp_extra_test.cc @@ -555,13 +555,10 @@ TEST(EVPExtraTest, Ed25519) { 0xa6, 0x23, 0x25, 0xaf, 0x02, 0x1a, 0x68, 0xf7, 0x07, 0x51, 0x1a, }; - static const uint8_t kPrivateKey[64] = { + static const uint8_t kPrivateKeySeed[32] = { 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec, 0x2c, 0xc4, 0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, - 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60, 0xd7, - 0x5a, 0x98, 0x01, 0x82, 0xb1, 0x0a, 0xb7, 0xd5, 0x4b, 0xfe, 0xd3, - 0xc9, 0x64, 0x07, 0x3a, 0x0e, 0xe1, 0x72, 0xf3, 0xda, 0xa6, 0x23, - 0x25, 0xaf, 0x02, 0x1a, 0x68, 0xf7, 0x07, 0x51, 0x1a, + 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60, }; static const uint8_t kPrivateKeyPKCS8[] = { @@ -572,10 +569,38 @@ TEST(EVPExtraTest, Ed25519) { }; // Create a public key. - bssl::UniquePtr pubkey(EVP_PKEY_new_ed25519_public(kPublicKey)); + bssl::UniquePtr pubkey(EVP_PKEY_new_raw_public_key( + EVP_PKEY_ED25519, nullptr, kPublicKey, sizeof(kPublicKey))); ASSERT_TRUE(pubkey); EXPECT_EQ(EVP_PKEY_ED25519, EVP_PKEY_id(pubkey.get())); + // The public key must be extractable. + uint8_t buf[32]; + size_t len; + ASSERT_TRUE(EVP_PKEY_get_raw_public_key(pubkey.get(), nullptr, &len)); + EXPECT_EQ(len, 32u); + ASSERT_TRUE(EVP_PKEY_get_raw_public_key(pubkey.get(), buf, &len)); + EXPECT_EQ(Bytes(buf, len), Bytes(kPublicKey)); + // Passing too large of a buffer is okay. The function will still only read + // 32 bytes. + len = 64; + ASSERT_TRUE(EVP_PKEY_get_raw_public_key(pubkey.get(), buf, &len)); + EXPECT_EQ(Bytes(buf, len), Bytes(kPublicKey)); + // Passing too small of a buffer is noticed. + len = 31; + EXPECT_FALSE(EVP_PKEY_get_raw_public_key(pubkey.get(), buf, &len)); + uint32_t err = ERR_get_error(); + EXPECT_EQ(ERR_LIB_EVP, ERR_GET_LIB(err)); + EXPECT_EQ(EVP_R_BUFFER_TOO_SMALL, ERR_GET_REASON(err)); + ERR_clear_error(); + + // There is no private key. + EXPECT_FALSE(EVP_PKEY_get_raw_private_key(pubkey.get(), nullptr, &len)); + err = ERR_get_error(); + EXPECT_EQ(ERR_LIB_EVP, ERR_GET_LIB(err)); + EXPECT_EQ(EVP_R_NOT_A_PRIVATE_KEY, ERR_GET_REASON(err)); + ERR_clear_error(); + // The public key must encode properly. bssl::ScopedCBB cbb; uint8_t *der; @@ -589,16 +614,40 @@ TEST(EVPExtraTest, Ed25519) { // The public key must gracefully fail to encode as a private key. ASSERT_TRUE(CBB_init(cbb.get(), 0)); EXPECT_FALSE(EVP_marshal_private_key(cbb.get(), pubkey.get())); - uint32_t err = ERR_get_error(); + err = ERR_get_error(); EXPECT_EQ(ERR_LIB_EVP, ERR_GET_LIB(err)); EXPECT_EQ(EVP_R_NOT_A_PRIVATE_KEY, ERR_GET_REASON(err)); + ERR_clear_error(); cbb.Reset(); // Create a private key. - bssl::UniquePtr privkey(EVP_PKEY_new_ed25519_private(kPrivateKey)); + bssl::UniquePtr privkey(EVP_PKEY_new_raw_private_key( + EVP_PKEY_ED25519, NULL, kPrivateKeySeed, sizeof(kPrivateKeySeed))); ASSERT_TRUE(privkey); EXPECT_EQ(EVP_PKEY_ED25519, EVP_PKEY_id(privkey.get())); + // The private key must be extractable. + ASSERT_TRUE(EVP_PKEY_get_raw_private_key(privkey.get(), nullptr, &len)); + EXPECT_EQ(len, 32u); + ASSERT_TRUE(EVP_PKEY_get_raw_private_key(privkey.get(), buf, &len)); + EXPECT_EQ(Bytes(buf, len), Bytes(kPrivateKeySeed)); + // Passing too large of a buffer is okay. The function will still only read + // 32 bytes. + len = 64; + ASSERT_TRUE(EVP_PKEY_get_raw_private_key(privkey.get(), buf, &len)); + EXPECT_EQ(Bytes(buf, len), Bytes(kPrivateKeySeed)); + // Passing too small of a buffer is noticed. + len = 31; + EXPECT_FALSE(EVP_PKEY_get_raw_private_key(privkey.get(), buf, &len)); + err = ERR_get_error(); + EXPECT_EQ(ERR_LIB_EVP, ERR_GET_LIB(err)); + EXPECT_EQ(EVP_R_BUFFER_TOO_SMALL, ERR_GET_REASON(err)); + ERR_clear_error(); + // The public key must be extractable. + len = 32; + ASSERT_TRUE(EVP_PKEY_get_raw_public_key(privkey.get(), buf, &len)); + EXPECT_EQ(Bytes(buf, len), Bytes(kPublicKey)); + // The public key must encode from the private key. ASSERT_TRUE(CBB_init(cbb.get(), 0)); ASSERT_TRUE(EVP_marshal_public_key(cbb.get(), privkey.get())); @@ -617,7 +666,8 @@ TEST(EVPExtraTest, Ed25519) { EXPECT_EQ(1, EVP_PKEY_cmp(pubkey.get(), privkey.get())); static const uint8_t kZeros[32] = {0}; - bssl::UniquePtr pubkey2(EVP_PKEY_new_ed25519_public(kZeros)); + bssl::UniquePtr pubkey2(EVP_PKEY_new_raw_public_key( + EVP_PKEY_ED25519, nullptr, kZeros, sizeof(kZeros))); ASSERT_TRUE(pubkey2); EXPECT_EQ(0, EVP_PKEY_cmp(pubkey.get(), pubkey2.get())); EXPECT_EQ(0, EVP_PKEY_cmp(privkey.get(), pubkey2.get())); @@ -627,7 +677,6 @@ TEST(EVPExtraTest, Ed25519) { ASSERT_TRUE( EVP_DigestSignInit(ctx.get(), nullptr, nullptr, nullptr, privkey.get())); EXPECT_FALSE(EVP_DigestSignUpdate(ctx.get(), nullptr, 0)); - size_t len; EXPECT_FALSE(EVP_DigestSignFinal(ctx.get(), nullptr, &len)); ERR_clear_error(); @@ -637,4 +686,99 @@ TEST(EVPExtraTest, Ed25519) { EXPECT_FALSE(EVP_DigestVerifyUpdate(ctx.get(), nullptr, 0)); EXPECT_FALSE(EVP_DigestVerifyFinal(ctx.get(), nullptr, 0)); ERR_clear_error(); + + // The buffer length to |EVP_DigestSign| is an input/output parameter and + // should be checked before signing. + ctx.Reset(); + ASSERT_TRUE( + EVP_DigestSignInit(ctx.get(), nullptr, nullptr, nullptr, privkey.get())); + len = 31; + EXPECT_FALSE(EVP_DigestSign(ctx.get(), buf, &len, nullptr /* msg */, 0)); + err = ERR_get_error(); + EXPECT_EQ(ERR_LIB_EVP, ERR_GET_LIB(err)); + EXPECT_EQ(EVP_R_BUFFER_TOO_SMALL, ERR_GET_REASON(err)); + ERR_clear_error(); +} + +static void ExpectECGroupOnly(const EVP_PKEY *pkey, int nid) { + EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey); + ASSERT_TRUE(ec); + const EC_GROUP *group = EC_KEY_get0_group(ec); + ASSERT_TRUE(group); + EXPECT_EQ(nid, EC_GROUP_get_curve_name(group)); + EXPECT_FALSE(EC_KEY_get0_public_key(ec)); + EXPECT_FALSE(EC_KEY_get0_private_key(ec)); +} + +static void ExpectECGroupAndKey(const EVP_PKEY *pkey, int nid) { + EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey); + ASSERT_TRUE(ec); + const EC_GROUP *group = EC_KEY_get0_group(ec); + ASSERT_TRUE(group); + EXPECT_EQ(nid, EC_GROUP_get_curve_name(group)); + EXPECT_TRUE(EC_KEY_get0_public_key(ec)); + EXPECT_TRUE(EC_KEY_get0_private_key(ec)); +} + +TEST(EVPExtraTest, ECKeygen) { + // |EVP_PKEY_paramgen| may be used as an extremely roundabout way to get an + // |EC_GROUP|. + bssl::UniquePtr ctx(EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr)); + ASSERT_TRUE(ctx); + ASSERT_TRUE(EVP_PKEY_paramgen_init(ctx.get())); + ASSERT_TRUE( + EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx.get(), NID_X9_62_prime256v1)); + EVP_PKEY *raw = nullptr; + ASSERT_TRUE(EVP_PKEY_paramgen(ctx.get(), &raw)); + bssl::UniquePtr pkey(raw); + raw = nullptr; + ExpectECGroupOnly(pkey.get(), NID_X9_62_prime256v1); + + // That resulting |EVP_PKEY| may be used as a template for key generation. + ctx.reset(EVP_PKEY_CTX_new(pkey.get(), nullptr)); + ASSERT_TRUE(ctx); + ASSERT_TRUE(EVP_PKEY_keygen_init(ctx.get())); + raw = nullptr; + ASSERT_TRUE(EVP_PKEY_keygen(ctx.get(), &raw)); + pkey.reset(raw); + raw = nullptr; + ExpectECGroupAndKey(pkey.get(), NID_X9_62_prime256v1); + + // |EVP_PKEY_paramgen| may also be skipped. + ctx.reset(EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr)); + ASSERT_TRUE(ctx); + ASSERT_TRUE(EVP_PKEY_keygen_init(ctx.get())); + ASSERT_TRUE( + EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx.get(), NID_X9_62_prime256v1)); + raw = nullptr; + ASSERT_TRUE(EVP_PKEY_keygen(ctx.get(), &raw)); + pkey.reset(raw); + raw = nullptr; + ExpectECGroupAndKey(pkey.get(), NID_X9_62_prime256v1); +} + +// Test that |EVP_PKEY_keygen| works for Ed25519. +TEST(EVPExtraTest, Ed25519Keygen) { + bssl::UniquePtr pctx( + EVP_PKEY_CTX_new_id(EVP_PKEY_ED25519, nullptr)); + ASSERT_TRUE(pctx); + ASSERT_TRUE(EVP_PKEY_keygen_init(pctx.get())); + EVP_PKEY *raw = nullptr; + ASSERT_TRUE(EVP_PKEY_keygen(pctx.get(), &raw)); + bssl::UniquePtr pkey(raw); + + // Round-trip a signature to sanity-check the key is good. + bssl::ScopedEVP_MD_CTX ctx; + ASSERT_TRUE( + EVP_DigestSignInit(ctx.get(), nullptr, nullptr, nullptr, pkey.get())); + uint8_t sig[64]; + size_t len = sizeof(sig); + ASSERT_TRUE(EVP_DigestSign(ctx.get(), sig, &len, + reinterpret_cast("hello"), 5)); + + ctx.Reset(); + ASSERT_TRUE( + EVP_DigestVerifyInit(ctx.get(), nullptr, nullptr, nullptr, pkey.get())); + ASSERT_TRUE(EVP_DigestVerify(ctx.get(), sig, len, + reinterpret_cast("hello"), 5)); } diff --git a/third_party/boringssl/kit/src/crypto/evp/evp_test.cc b/third_party/boringssl/kit/src/crypto/evp/evp_test.cc index 6571c302..9df54934 100644 --- a/third_party/boringssl/kit/src/crypto/evp/evp_test.cc +++ b/third_party/boringssl/kit/src/crypto/evp/evp_test.cc @@ -179,7 +179,62 @@ static bool ImportKey(FileTest *t, KeyMap *key_map, !t->GetBytes(&output, "Output")) { return false; } - EXPECT_EQ(Bytes(output), Bytes(der, der_len)) << "Re-encoding the key did not match."; + EXPECT_EQ(Bytes(output), Bytes(der, der_len)) + << "Re-encoding the key did not match."; + + if (t->HasAttribute("ExpectNoRawPrivate")) { + size_t len; + EXPECT_FALSE(EVP_PKEY_get_raw_private_key(pkey.get(), nullptr, &len)); + } else if (t->HasAttribute("ExpectRawPrivate")) { + std::vector expected; + if (!t->GetBytes(&expected, "ExpectRawPrivate")) { + return false; + } + + std::vector raw; + size_t len; + if (!EVP_PKEY_get_raw_private_key(pkey.get(), nullptr, &len)) { + return false; + } + raw.resize(len); + if (!EVP_PKEY_get_raw_private_key(pkey.get(), raw.data(), &len)) { + return false; + } + raw.resize(len); + EXPECT_EQ(Bytes(raw), Bytes(expected)); + + // Short buffers should be rejected. + raw.resize(len - 1); + len = raw.size(); + EXPECT_FALSE(EVP_PKEY_get_raw_private_key(pkey.get(), raw.data(), &len)); + } + + if (t->HasAttribute("ExpectNoRawPublic")) { + size_t len; + EXPECT_FALSE(EVP_PKEY_get_raw_public_key(pkey.get(), nullptr, &len)); + } else if (t->HasAttribute("ExpectRawPublic")) { + std::vector expected; + if (!t->GetBytes(&expected, "ExpectRawPublic")) { + return false; + } + + std::vector raw; + size_t len; + if (!EVP_PKEY_get_raw_public_key(pkey.get(), nullptr, &len)) { + return false; + } + raw.resize(len); + if (!EVP_PKEY_get_raw_public_key(pkey.get(), raw.data(), &len)) { + return false; + } + raw.resize(len); + EXPECT_EQ(Bytes(raw), Bytes(expected)); + + // Short buffers should be rejected. + raw.resize(len - 1); + len = raw.size(); + EXPECT_FALSE(EVP_PKEY_get_raw_public_key(pkey.get(), raw.data(), &len)); + } // Save the key for future tests. const std::string &key_name = t->GetParameter(); @@ -297,16 +352,19 @@ static bool TestEVP(FileTest *t, KeyMap *key_map) { } if (md_op_init) { - bssl::ScopedEVP_MD_CTX ctx; + bssl::ScopedEVP_MD_CTX ctx, copy; EVP_PKEY_CTX *pctx; if (!md_op_init(ctx.get(), &pctx, digest, nullptr, key) || - !SetupContext(t, pctx)) { + !SetupContext(t, pctx) || + !EVP_MD_CTX_copy_ex(copy.get(), ctx.get())) { return false; } if (is_verify) { - return !!EVP_DigestVerify(ctx.get(), output.data(), output.size(), - input.data(), input.size()); + return EVP_DigestVerify(ctx.get(), output.data(), output.size(), + input.data(), input.size()) && + EVP_DigestVerify(copy.get(), output.data(), output.size(), + input.data(), input.size()); } size_t len; @@ -321,6 +379,21 @@ static bool TestEVP(FileTest *t, KeyMap *key_map) { } actual.resize(len); EXPECT_EQ(Bytes(output), Bytes(actual)); + + // Repeat the test with |copy|, to check |EVP_MD_CTX_copy_ex| duplicated + // everything. + if (!EVP_DigestSign(copy.get(), nullptr, &len, input.data(), + input.size())) { + return false; + } + actual.resize(len); + if (!EVP_DigestSign(copy.get(), actual.data(), &len, input.data(), + input.size()) || + !t->GetBytes(&output, "Output")) { + return false; + } + actual.resize(len); + EXPECT_EQ(Bytes(output), Bytes(actual)); return true; } @@ -333,72 +406,78 @@ static bool TestEVP(FileTest *t, KeyMap *key_map) { return false; } + bssl::UniquePtr copy(EVP_PKEY_CTX_dup(ctx.get())); + if (!copy) { + return false; + } + if (is_verify) { - return !!EVP_PKEY_verify(ctx.get(), output.data(), output.size(), - input.data(), input.size()); + return EVP_PKEY_verify(ctx.get(), output.data(), output.size(), + input.data(), input.size()) && + EVP_PKEY_verify(copy.get(), output.data(), output.size(), + input.data(), input.size()); } - size_t len; - if (!key_op(ctx.get(), nullptr, &len, input.data(), input.size())) { - return false; - } - actual.resize(len); - if (!key_op(ctx.get(), actual.data(), &len, input.data(), input.size())) { - return false; - } + for (EVP_PKEY_CTX *pctx : {ctx.get(), copy.get()}) { + size_t len; + if (!key_op(pctx, nullptr, &len, input.data(), input.size())) { + return false; + } + actual.resize(len); + if (!key_op(pctx, actual.data(), &len, input.data(), input.size())) { + return false; + } - // Encryption is non-deterministic, so we check by decrypting. - if (t->HasAttribute("CheckDecrypt")) { - size_t plaintext_len; - ctx.reset(EVP_PKEY_CTX_new(key, nullptr)); - if (!ctx || - !EVP_PKEY_decrypt_init(ctx.get()) || - (digest != nullptr && - !EVP_PKEY_CTX_set_signature_md(ctx.get(), digest)) || - !SetupContext(t, ctx.get()) || - !EVP_PKEY_decrypt(ctx.get(), nullptr, &plaintext_len, actual.data(), - actual.size())) { - return false; + if (t->HasAttribute("CheckDecrypt")) { + // Encryption is non-deterministic, so we check by decrypting. + size_t plaintext_len; + bssl::UniquePtr decrypt_ctx(EVP_PKEY_CTX_new(key, nullptr)); + if (!decrypt_ctx || + !EVP_PKEY_decrypt_init(decrypt_ctx.get()) || + (digest != nullptr && + !EVP_PKEY_CTX_set_signature_md(decrypt_ctx.get(), digest)) || + !SetupContext(t, decrypt_ctx.get()) || + !EVP_PKEY_decrypt(decrypt_ctx.get(), nullptr, &plaintext_len, + actual.data(), actual.size())) { + return false; + } + output.resize(plaintext_len); + if (!EVP_PKEY_decrypt(decrypt_ctx.get(), output.data(), &plaintext_len, + actual.data(), actual.size())) { + ADD_FAILURE() << "Could not decrypt result."; + return false; + } + output.resize(plaintext_len); + EXPECT_EQ(Bytes(input), Bytes(output)) << "Decrypted result mismatch."; + } else if (t->HasAttribute("CheckVerify")) { + // Some signature schemes are non-deterministic, so we check by verifying. + bssl::UniquePtr verify_ctx(EVP_PKEY_CTX_new(key, nullptr)); + if (!verify_ctx || + !EVP_PKEY_verify_init(verify_ctx.get()) || + (digest != nullptr && + !EVP_PKEY_CTX_set_signature_md(verify_ctx.get(), digest)) || + !SetupContext(t, verify_ctx.get())) { + return false; + } + if (t->HasAttribute("VerifyPSSSaltLength")) { + if (!EVP_PKEY_CTX_set_rsa_pss_saltlen( + verify_ctx.get(), + atoi(t->GetAttributeOrDie("VerifyPSSSaltLength").c_str()))) { + return false; + } + } + EXPECT_TRUE(EVP_PKEY_verify(verify_ctx.get(), actual.data(), + actual.size(), input.data(), input.size())) + << "Could not verify result."; + } else { + // By default, check by comparing the result against Output. + if (!t->GetBytes(&output, "Output")) { + return false; + } + actual.resize(len); + EXPECT_EQ(Bytes(output), Bytes(actual)); } - output.resize(plaintext_len); - if (!EVP_PKEY_decrypt(ctx.get(), output.data(), &plaintext_len, - actual.data(), actual.size())) { - ADD_FAILURE() << "Could not decrypt result."; - return false; - } - output.resize(plaintext_len); - EXPECT_EQ(Bytes(input), Bytes(output)) << "Decrypted result mismatch."; - return true; } - - // Some signature schemes are non-deterministic, so we check by verifying. - if (t->HasAttribute("CheckVerify")) { - ctx.reset(EVP_PKEY_CTX_new(key, nullptr)); - if (!ctx || - !EVP_PKEY_verify_init(ctx.get()) || - (digest != nullptr && - !EVP_PKEY_CTX_set_signature_md(ctx.get(), digest)) || - !SetupContext(t, ctx.get())) { - return false; - } - if (t->HasAttribute("VerifyPSSSaltLength") && - !EVP_PKEY_CTX_set_rsa_pss_saltlen( - ctx.get(), - atoi(t->GetAttributeOrDie("VerifyPSSSaltLength").c_str()))) { - return false; - } - EXPECT_TRUE(EVP_PKEY_verify(ctx.get(), actual.data(), actual.size(), - input.data(), input.size())) - << "Could not verify result."; - return true; - } - - // By default, check by comparing the result against Output. - if (!t->GetBytes(&output, "Output")) { - return false; - } - actual.resize(len); - EXPECT_EQ(Bytes(output), Bytes(actual)); return true; } diff --git a/third_party/boringssl/kit/src/crypto/evp/evp_tests.txt b/third_party/boringssl/kit/src/crypto/evp/evp_tests.txt index ff08ee76..6090f5f2 100644 --- a/third_party/boringssl/kit/src/crypto/evp/evp_tests.txt +++ b/third_party/boringssl/kit/src/crypto/evp/evp_tests.txt @@ -6,11 +6,15 @@ PrivateKey = RSA-2048 Type = RSA Input = 308204bc020100300d06092a864886f70d0101010500048204a6308204a20201000282010100cd0081ea7b2ae1ea06d59f7c73d9ffb94a09615c2e4ba7c636cef08dd3533ec3185525b015c769b99a77d6725bf9c3532a9b6e5f6627d5fb85160768d3dda9cbd35974511717dc3d309d2fc47ee41f97e32adb7f9dd864a1c4767a666ecd71bc1aacf5e7517f4b38594fea9b05e42d5ada9912008013e45316a4d9bb8ed086b88d28758bacaf922d46a868b485d239c9baeb0e2b64592710f42b2d1ea0a4b4802c0becab328f8a68b0073bdb546feea9809d2849912b390c1532bc7e29c7658f8175fae46f34332ff87bcab3e40649b98577869da0ea718353f0722754886913648760d122be676e0fc483dd20ffc31bda96a31966c9aa2e75ad03de47e1c44f02030100010282010060297ac7991b167a06d6b24758b8cbe208beb9b2d9ec9738bd80f90a2e35005dd7ce292d9e29ba885bd316fef1f20913bc0ac90d6b0808b2414d82104441d8624a33ce0233c8f780a48b375aff02d76712228a702484db3f9ebecccfbbee1709dba182800d949e9e4216e0bff3558388f8bd90da373a1d82743ec3fbdd1427fd16825a657a316912e8695365117ca2f845c909405fcac55f895fc15d20386c26ee78c9e99075029a178a6c1e4cf0c200e8a9cfb27e9d156f86e6c2adc22b1a84a1cd5ca5b2790875d79407c84b352395cb81cc3fed5bb043b69ede0c07204550025cee8c5f440170b6120bb48e0f747bcd8f522110850df043c428dfd187053102818100f6f961b47cbc035d3aedebc7de850a956b65ecdb9cf60764063f15aa48553c58d972fe6675056e35ddfdc37bf3b9f2f622ee271337256849c9bef2176fe8f7c3f8bb91ba374dd53baf3dec814d2bdec10c1fdc88cdd16876f26b1edfa3f094197edf4d42ff1fb2971103b898ca859c427287086a842ab410bb69cf2d35af6be302818100d47e724a7ff41048b270c2524a4101878b73159bb73d3dbc187b220e635b3534f96e243a184d93f860b6bfbb6b71c1ed9a1e1f458583023c301e96a692c1a08b53d0ec9ca910100d80451e3b7dc6a01bac4aecef8df798846bc235a08cbba2cf4c06804cc11219e95608c714e3f1430d491fadbba32a5751a04f97745834c9a502818021f2452bb9b95dfd028c914bf799f1ca77e89a95d50d3c16d384f8455f8bd7af9eb3dfa3d591d9842def235f7630a8e48c088ff6642e101794535a933e1e976fa8509fc728b2da0c4a1a08d7fcf37abaae1ff3001aca1dc1bbb05d9dffbaa1a09f7fb1eef38237d9ebccc722b9338436dde7119112798c26809c1a8dec4320610281801f7510aa62c2d8de4a3c53282781f41e02d0e8b402ae78432e449c48110161a11403f02d01880a8dcc938152d79721a4711a607ac4471ebf964810f95be47a45e60499e29f4c9773c83773404f606637728c2d0351bb03c326c8bb73a721e7fa5440ea2172bba1465fcc30dcb0d9f89930e815aa1f7f9729a857e00e0338dd590281804d1f0d756fe77e01099a652f50a88b7b685dc5bf00981d5d2376fd0c6fe29cd5b638734479305a73ad3c1599d39eae3bae035fbd6fed07c28de705933879a06e48e6a603686ed8e2560a5f6af1f2c24faf4aa960e382186f15eedce9a2491ae730680dd4cf778b70faa86826ab3223477cc91377b19a6d5a2eaea219760beed5 +ExpectNoRawPrivate +ExpectNoRawPublic # The public half of the same key encoded as a SubjectPublicKeyInfo. PublicKey = RSA-2048-SPKI Type = RSA Input = 30820122300d06092a864886f70d01010105000382010f003082010a0282010100cd0081ea7b2ae1ea06d59f7c73d9ffb94a09615c2e4ba7c636cef08dd3533ec3185525b015c769b99a77d6725bf9c3532a9b6e5f6627d5fb85160768d3dda9cbd35974511717dc3d309d2fc47ee41f97e32adb7f9dd864a1c4767a666ecd71bc1aacf5e7517f4b38594fea9b05e42d5ada9912008013e45316a4d9bb8ed086b88d28758bacaf922d46a868b485d239c9baeb0e2b64592710f42b2d1ea0a4b4802c0becab328f8a68b0073bdb546feea9809d2849912b390c1532bc7e29c7658f8175fae46f34332ff87bcab3e40649b98577869da0ea718353f0722754886913648760d122be676e0fc483dd20ffc31bda96a31966c9aa2e75ad03de47e1c44f0203010001 +ExpectNoRawPrivate +ExpectNoRawPublic # The same key but with a negative RSA modulus. PublicKey = RSA-2048-SPKI-Negative @@ -31,21 +35,29 @@ Error = DECODE_ERROR PrivateKey = RSA-512 Type = RSA Input = 30820154020100300d06092a864886f70d01010105000482013e3082013a020100024100dd20403d976a38c9d79152d87b5c8e9f05033eadd7b7de709bf5b0c4a5182a97d18483526b02362b992e154a9f37faa396ca2685cdab8fec09877ebe705f4dd70203010001024055bebcca655d7e39de8a6eaa9d636db682161907064039544755c53eeb99ec618c03a210dbc61471eaba10c5c365c9726d6b7a96f54d455f7d168d49367270e1022100f21a05d9fd6817301ce49ce10448f9bdd44f5ef5b7557cd7d83155db46382ae7022100e9d1f7157783db2feab1936954ddc4e83aa365695868144cda1be6813b61d791022100d6001eb0040920860ce41fafdf23ca6dfbdf74e6e9f98cf3164cf5c16f9e727d02206f6f73f4b52b10517be6f9bc5f87fa0a3bb817e2e711636b651f9af1c85d4f21022063eff2e57f5b4ca20342cfe793e25526624e3692f192461f9e1ce7f13f2d72c8 +ExpectNoRawPrivate +ExpectNoRawPublic # RSA 515 bit key. PrivateKey = RSA-515 Type = RSA Input = 30820157020100300d06092a864886f70d0101010500048201413082013d0201000241054fa166e205e658bbe8a2dc35311c0c2b75b7e4569fd9642c8bae809279271fc824f26baa1166ea46298ca63379ea76adbada2b61e5066820a35beaec1aca227f020301000102410266c972be0d30e53ac2acb1aa13b4bd0401cccf212452a66b4615f7e943831f67b4ca48560582d0ca886044aaaaf87945252a848c1947944186e6eb83969bf91102210309e631761842cc8a2ccfd372c20a9cba21de1a199c30ab440bc6b51079f4e825022101bf715c1db432627ca7c29a293b9210f2eff1e92d12f306ebaa5334f8ee03dcd30221018ac58a765f2b8f37d434081fe5ff92b81735ead2f263f4968ccf63d61fbe3d0d0221015b247a1159a2d5a25d0db049593c6405f77f3a278c521d066e290c2a2d8fb59d0221026224aa31fd95c14d24fd03b8a195bba4cc88df7c37f5370a5ab19f882f1404d6 +ExpectNoRawPrivate +ExpectNoRawPublic # EC P-256 key PrivateKey = P-256 Type = EC Input = 308187020100301306072a8648ce3d020106082a8648ce3d030107046d306b02010104208a872fb62893c4d1ffc5b9f0f91758069f8352e08fa05a49f8db926cb5728725a144034200042c150f429ce70f216c252cf5e062ce1f639cd5d165c7f89424072c27197d78b33b920e95cdb664e990dcf0cfea0d94e2a8e6af9d0e58056e653104925b9fe6c9 +ExpectNoRawPrivate +ExpectNoRawPublic # The same key as above with the optional public key omitted. PrivateKey = P-256-MissingPublic Type = EC Input = 3041020100301306072a8648ce3d020106082a8648ce3d0301070427302502010104208a872fb62893c4d1ffc5b9f0f91758069f8352e08fa05a49f8db926cb5728725 +ExpectNoRawPrivate +ExpectNoRawPublic # The same key as above with redundant parameters. PrivateKey = P-256-ExtraParameters @@ -53,6 +65,8 @@ Type = EC Input = 308193020100301306072a8648ce3d020106082a8648ce3d0301070479307702010104208a872fb62893c4d1ffc5b9f0f91758069f8352e08fa05a49f8db926cb5728725a00a06082a8648ce3d030107a144034200042c150f429ce70f216c252cf5e062ce1f639cd5d165c7f89424072c27197d78b33b920e95cdb664e990dcf0cfea0d94e2a8e6af9d0e58056e653104925b9fe6c9 # The key re-encodes with the parameters removed. Output = 308187020100301306072a8648ce3d020106082a8648ce3d030107046d306b02010104208a872fb62893c4d1ffc5b9f0f91758069f8352e08fa05a49f8db926cb5728725a144034200042c150f429ce70f216c252cf5e062ce1f639cd5d165c7f89424072c27197d78b33b920e95cdb664e990dcf0cfea0d94e2a8e6af9d0e58056e653104925b9fe6c9 +ExpectNoRawPrivate +ExpectNoRawPublic # The same key, but with the redundant parameters in the ECPrivateKey mismatched. PrivateKey = P-256-BadInnerParameters @@ -63,6 +77,8 @@ Error = GROUP_MISMATCH PublicKey = P-256-SPKI Type = EC Input = 3059301306072a8648ce3d020106082a8648ce3d030107034200042c150f429ce70f216c252cf5e062ce1f639cd5d165c7f89424072c27197d78b33b920e95cdb664e990dcf0cfea0d94e2a8e6af9d0e58056e653104925b9fe6c9 +ExpectNoRawPrivate +ExpectNoRawPublic # The same as above, but with the curve explicitly spelled out. PublicKey = P-256-SPKI @@ -78,58 +94,84 @@ Error = DECODE_ERROR PrivateKey = DSA-1024 Type = DSA Input = 308202650201003082023906072a8648ce3804013082022c02820101009e12fab3de12213501dd82aa10ca2d101d2d4ebfef4d2a3f8daa0fe0cedad8d6af85616aa2f3252c0a2b5a6db09e6f14900e0ddb8311876dd8f9669525f99ed65949e184d5064793271169a228680b95ec12f59a8e20b21f2b58eb2a2012d35bde2ee351822fe8f32d0a330565dcce5c672b7259c14b2433d0b5b2ca2b2db0ab626e8f13f47fe0345d904e7294bb038e9ce21a9e580b83356278706cfe768436c69de149ccff98b4aab8cb4f6385c9f102ce59346eaeef27e0ad222d53d6e89cc8cde5776dd00057b03f2d88ab3cedbafd7b585f0b7f7835e17a3728bbf25ea62572f245dc111f3ce39cb6ffacc31b0a2790e7bde90224ea9b09315362af3d2b022100f381dcf53ebf724f8b2e5ca82c010fb4b5eda9358d0fd88ed278589488b54fc3028201000c402a725dcc3a62e02bf4cf43cd17f4a493591220223669cf4193edab423ad08dfb552e308a6a57a5ffbc7cd0fb2087f81f8df0cb08ab2133287d2b6968714a94f633c940845a48a3e16708dde761cc6a8eab2d84db21b6ea5b07681493cc9c31fbc368b243f6ddf8c932a8b4038f44e7b15ca876344a147859f2b43b39458668ad5e0a1a9a669546dd2812e3b3617a0aef99d58e3bb4cc87fd94225e01d2dcc469a77268146c51918f18e8b4d70aa1f0c7623bcc52cf3731d38641b2d2830b7eecb2f09552ff137d046e494e7f33c3590002b16d1b97d936fda28f90c3ed3ca35338168ac16f77c3c57adc2e8f7c6c2256e41a5f65450590dbb5bcf06d66610423022100b0c768702743bc51242993a971a52889795444f7c6452203d0ce84fe6117d46e +ExpectNoRawPrivate +ExpectNoRawPublic # A DSA public key. PublicKey = DSA-1024-SPKI Type = DSA Input = 308201b73082012c06072a8648ce3804013082011f02818100b3429b8b128c9079f9b72e86857e98d265e5d91661ed8b5f4cc56e5eed1e571da30186983a9dd76297eab73ee13a1db841f8800d04a7cab478af6cde2ea4a2868531af169a24858c6268efa39ceb7ed0d4227eb5bbb01124a2a5a26038c7bcfb8cc827f68f5202345166e4718596799b65c9def82828ce44e62e38e41a0d24b1021500c5a56c81ddd87f47e676546c56d05706421624cf0281810094de40d27314fe929e47ff9b1ac65cfc73ef38c4d381c890be6217b15039ae18190e6b421af8c0bda35a5cfd050f58ae2644adce83e68c8e5ba11729df56bbb21e227a60b816cc033fa799a38fe1ba5b4aa1801b6f841ce3df99feb3b4fb96950c960af13fa2ce920aabc12dd24ad2044a35063ea0e25f67f560f4cfbdc5598303818400028180258c30ebbb7f34fdc873ce679f6cea373c7886d75d4421b90920db034daedd292c64d8edd8cdbdd7f3ad23d74cfa2135247d0cef6ecf2e14f99e19d22a8c1266bd8fb8719c0e5667c716c45c7adbdabe548085bdad2dfee636f8d52fd6adb2193df6c4f0520fbd171b91882e0e4f321f8250ffecf4dbea00e114427d3ef96c1a +ExpectNoRawPrivate +ExpectNoRawPublic # The same key as above, but without the parameters. PublicKey = DSA-1024-SPKI-No-Params Type = DSA Input = 308192300906072a8648ce38040103818400028180258c30ebbb7f34fdc873ce679f6cea373c7886d75d4421b90920db034daedd292c64d8edd8cdbdd7f3ad23d74cfa2135247d0cef6ecf2e14f99e19d22a8c1266bd8fb8719c0e5667c716c45c7adbdabe548085bdad2dfee636f8d52fd6adb2193df6c4f0520fbd171b91882e0e4f321f8250ffecf4dbea00e114427d3ef96c1a +ExpectNoRawPrivate +ExpectNoRawPublic # Private keys from RFC 8032. PrivateKey = Ed25519 Type = Ed25519 Input = 302e020100300506032b6570042204209d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60 +ExpectRawPrivate = 9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60 +ExpectRawPublic = d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a PrivateKey = Ed25519-2 Type = Ed25519 Input = 302e020100300506032b6570042204204ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb +ExpectRawPrivate = 4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb +ExpectRawPublic = 3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c PrivateKey = Ed25519-3 Type = Ed25519 Input = 302e020100300506032b657004220420c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7 +ExpectRawPrivate = c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7 +ExpectRawPublic = fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025 PrivateKey = Ed25519-4 Type = Ed25519 Input = 302e020100300506032b657004220420f5e5767cf153319517630f226876b86c8160cc583bc013744c6bf255f5cc0ee5 +ExpectRawPrivate = f5e5767cf153319517630f226876b86c8160cc583bc013744c6bf255f5cc0ee5 +ExpectRawPublic = 278117fc144c72340f67d0f2316e8386ceffbf2b2428c9c51fef7c597f1d426e PrivateKey = Ed25519-5 Type = Ed25519 Input = 302e020100300506032b657004220420833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42 +ExpectRawPrivate = 833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42 +ExpectRawPublic = ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf # Public keys from RFC 8032. PublicKey = Ed25519-SPKI Type = Ed25519 Input = 302a300506032b6570032100d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a +ExpectNoRawPrivate +ExpectRawPublic = d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a PublicKey = Ed25519-SPKI-2 Type = Ed25519 Input = 302a300506032b65700321003d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c +ExpectNoRawPrivate +ExpectRawPublic = 3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c PublicKey = Ed25519-SPKI-3 Type = Ed25519 Input = 302a300506032b6570032100fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025 +ExpectNoRawPrivate +ExpectRawPublic = fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025 PublicKey = Ed25519-SPKI-4 Type = Ed25519 Input = 302a300506032b6570032100278117fc144c72340f67d0f2316e8386ceffbf2b2428c9c51fef7c597f1d426e +ExpectNoRawPrivate +ExpectRawPublic = 278117fc144c72340f67d0f2316e8386ceffbf2b2428c9c51fef7c597f1d426e PublicKey = Ed25519-SPKI-5 Type = Ed25519 Input = 302a300506032b6570032100ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf +ExpectNoRawPrivate +ExpectRawPublic = ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf # The first key, private and public, with invalid NULL parameters. PrivateKey = Ed25519-NULL @@ -274,6 +316,17 @@ Digest = SHA256 Input = "0123456789ABCDEF0123456789ABCDEF" CheckVerify +# Check a salt length with a non-standard digest length, to verify things are +# not just working due to defaults. (The current default is a maximum salt +# length, but the ecosystem has converged on matching the digest length, so we +# may change this in the future.) +Sign = RSA-2048 +RSAPadding = PSS +PSSSaltLength = 42 +Digest = SHA256 +Input = "0123456789ABCDEF0123456789ABCDEF" +CheckVerify + # Auto-detected salt length Verify = RSA-2048-SPKI RSAPadding = PSS diff --git a/third_party/boringssl/kit/src/crypto/evp/internal.h b/third_party/boringssl/kit/src/crypto/evp/internal.h index 4aefa352..a599706a 100644 --- a/third_party/boringssl/kit/src/crypto/evp/internal.h +++ b/third_party/boringssl/kit/src/crypto/evp/internal.h @@ -96,6 +96,11 @@ struct evp_pkey_asn1_method_st { // |out|. It returns one on success and zero on error. int (*priv_encode)(CBB *out, const EVP_PKEY *key); + int (*set_priv_raw)(EVP_PKEY *pkey, const uint8_t *in, size_t len); + int (*set_pub_raw)(EVP_PKEY *pkey, const uint8_t *in, size_t len); + int (*get_priv_raw)(const EVP_PKEY *pkey, uint8_t *out, size_t *out_len); + int (*get_pub_raw)(const EVP_PKEY *pkey, uint8_t *out, size_t *out_len); + // pkey_opaque returns 1 if the |pk| is opaque. Opaque keys are backed by // custom implementations which do not expose key material and parameters. int (*pkey_opaque)(const EVP_PKEY *pk); @@ -119,6 +124,7 @@ struct evp_pkey_asn1_method_st { #define EVP_PKEY_OP_ENCRYPT (1 << 6) #define EVP_PKEY_OP_DECRYPT (1 << 7) #define EVP_PKEY_OP_DERIVE (1 << 8) +#define EVP_PKEY_OP_PARAMGEN (1 << 9) #define EVP_PKEY_OP_TYPE_SIG \ (EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY | EVP_PKEY_OP_VERIFYRECOVER) @@ -128,7 +134,7 @@ struct evp_pkey_asn1_method_st { #define EVP_PKEY_OP_TYPE_NOGEN \ (EVP_PKEY_OP_SIG | EVP_PKEY_OP_CRYPT | EVP_PKEY_OP_DERIVE) -#define EVP_PKEY_OP_TYPE_GEN EVP_PKEY_OP_KEYGEN +#define EVP_PKEY_OP_TYPE_GEN (EVP_PKEY_OP_KEYGEN | EVP_PKEY_OP_PARAMGEN) // EVP_PKEY_CTX_ctrl performs |cmd| on |ctx|. The |keytype| and |optype| // arguments can be -1 to specify that any type and operation are acceptable, @@ -171,6 +177,7 @@ OPENSSL_EXPORT int EVP_PKEY_CTX_ctrl(EVP_PKEY_CTX *ctx, int keytype, int optype, #define EVP_PKEY_CTRL_GET_RSA_MGF1_MD (EVP_PKEY_ALG_CTRL + 10) #define EVP_PKEY_CTRL_RSA_OAEP_LABEL (EVP_PKEY_ALG_CTRL + 11) #define EVP_PKEY_CTRL_GET_RSA_OAEP_LABEL (EVP_PKEY_ALG_CTRL + 12) +#define EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID (EVP_PKEY_ALG_CTRL + 13) struct evp_pkey_ctx_st { // Method associated with this operation @@ -219,6 +226,8 @@ struct evp_pkey_method_st { int (*derive)(EVP_PKEY_CTX *ctx, uint8_t *key, size_t *keylen); + int (*paramgen)(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey); + int (*ctrl)(EVP_PKEY_CTX *ctx, int type, int p1, void *p2); } /* EVP_PKEY_METHOD */; diff --git a/third_party/boringssl/kit/src/crypto/evp/p_dsa_asn1.c b/third_party/boringssl/kit/src/crypto/evp/p_dsa_asn1.c index 34b2e70c..d50e0fc3 100644 --- a/third_party/boringssl/kit/src/crypto/evp/p_dsa_asn1.c +++ b/third_party/boringssl/kit/src/crypto/evp/p_dsa_asn1.c @@ -255,6 +255,11 @@ const EVP_PKEY_ASN1_METHOD dsa_asn1_meth = { dsa_priv_decode, dsa_priv_encode, + NULL /* set_priv_raw */, + NULL /* set_pub_raw */, + NULL /* get_priv_raw */, + NULL /* get_pub_raw */, + NULL /* pkey_opaque */, int_dsa_size, diff --git a/third_party/boringssl/kit/src/crypto/evp/p_ec.c b/third_party/boringssl/kit/src/crypto/evp/p_ec.c index d311d220..9c325ae0 100644 --- a/third_party/boringssl/kit/src/crypto/evp/p_ec.c +++ b/third_party/boringssl/kit/src/crypto/evp/p_ec.c @@ -76,6 +76,7 @@ typedef struct { // message digest const EVP_MD *md; + EC_GROUP *gen_group; } EC_PKEY_CTX; @@ -111,6 +112,7 @@ static void pkey_ec_cleanup(EVP_PKEY_CTX *ctx) { return; } + EC_GROUP_free(dctx->gen_group); OPENSSL_free(dctx); } @@ -199,6 +201,16 @@ static int pkey_ec_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { // Default behaviour is OK return 1; + case EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID: { + EC_GROUP *group = EC_GROUP_new_by_curve_name(p1); + if (group == NULL) { + return 0; + } + EC_GROUP_free(dctx->gen_group); + dctx->gen_group = group; + return 1; + } + default: OPENSSL_PUT_ERROR(EVP, EVP_R_COMMAND_NOT_SUPPORTED); return 0; @@ -206,14 +218,35 @@ static int pkey_ec_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { } static int pkey_ec_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { - if (ctx->pkey == NULL) { + EC_PKEY_CTX *dctx = ctx->data; + const EC_GROUP *group = dctx->gen_group; + if (group == NULL) { + if (ctx->pkey == NULL) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NO_PARAMETERS_SET); + return 0; + } + group = EC_KEY_get0_group(ctx->pkey->pkey.ec); + } + EC_KEY *ec = EC_KEY_new(); + if (ec == NULL || + !EC_KEY_set_group(ec, group) || + !EC_KEY_generate_key(ec)) { + EC_KEY_free(ec); + return 0; + } + EVP_PKEY_assign_EC_KEY(pkey, ec); + return 1; +} + +static int pkey_ec_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { + EC_PKEY_CTX *dctx = ctx->data; + if (dctx->gen_group == NULL) { OPENSSL_PUT_ERROR(EVP, EVP_R_NO_PARAMETERS_SET); return 0; } EC_KEY *ec = EC_KEY_new(); if (ec == NULL || - !EC_KEY_set_group(ec, EC_KEY_get0_group(ctx->pkey->pkey.ec)) || - !EC_KEY_generate_key(ec)) { + !EC_KEY_set_group(ec, dctx->gen_group)) { EC_KEY_free(ec); return 0; } @@ -235,5 +268,20 @@ const EVP_PKEY_METHOD ec_pkey_meth = { NULL /* encrypt */, NULL /* decrypt */, pkey_ec_derive, + pkey_ec_paramgen, pkey_ec_ctrl, }; + +int EVP_PKEY_CTX_set_ec_paramgen_curve_nid(EVP_PKEY_CTX *ctx, int nid) { + return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, EVP_PKEY_OP_TYPE_GEN, + EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID, nid, NULL); +} + +int EVP_PKEY_CTX_set_ec_param_enc(EVP_PKEY_CTX *ctx, int encoding) { + // BoringSSL only supports named curve syntax. + if (encoding != OPENSSL_EC_NAMED_CURVE) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PARAMETERS); + return 0; + } + return 1; +} diff --git a/third_party/boringssl/kit/src/crypto/evp/p_ec_asn1.c b/third_party/boringssl/kit/src/crypto/evp/p_ec_asn1.c index 0ad8f383..dedc5e0a 100644 --- a/third_party/boringssl/kit/src/crypto/evp/p_ec_asn1.c +++ b/third_party/boringssl/kit/src/crypto/evp/p_ec_asn1.c @@ -237,6 +237,11 @@ const EVP_PKEY_ASN1_METHOD ec_asn1_meth = { eckey_priv_decode, eckey_priv_encode, + NULL /* set_priv_raw */, + NULL /* set_pub_raw */, + NULL /* get_priv_raw */, + NULL /* get_pub_raw */, + eckey_opaque, int_ec_size, diff --git a/third_party/boringssl/kit/src/crypto/evp/p_ed25519.c b/third_party/boringssl/kit/src/crypto/evp/p_ed25519.c index 554a379c..9149afb2 100644 --- a/third_party/boringssl/kit/src/crypto/evp/p_ed25519.c +++ b/third_party/boringssl/kit/src/crypto/evp/p_ed25519.c @@ -16,6 +16,7 @@ #include #include +#include #include "internal.h" @@ -23,6 +24,27 @@ // Ed25519 has no parameters to copy. static int pkey_ed25519_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { return 1; } +static int pkey_ed25519_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { + ED25519_KEY *key = OPENSSL_malloc(sizeof(ED25519_KEY)); + if (key == NULL) { + OPENSSL_PUT_ERROR(EVP, ERR_R_MALLOC_FAILURE); + return 0; + } + + if (!EVP_PKEY_set_type(pkey, EVP_PKEY_ED25519)) { + OPENSSL_free(key); + return 0; + } + + uint8_t pubkey_unused[32]; + ED25519_keypair(pubkey_unused, key->key.priv); + key->has_private = 1; + + OPENSSL_free(pkey->pkey.ptr); + pkey->pkey.ptr = key; + return 1; +} + static int pkey_ed25519_sign_message(EVP_PKEY_CTX *ctx, uint8_t *sig, size_t *siglen, const uint8_t *tbs, size_t tbslen) { @@ -32,12 +54,22 @@ static int pkey_ed25519_sign_message(EVP_PKEY_CTX *ctx, uint8_t *sig, return 0; } - *siglen = 64; if (sig == NULL) { + *siglen = 64; return 1; } - return ED25519_sign(sig, tbs, tbslen, key->key.priv); + if (*siglen < 64) { + OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); + return 0; + } + + if (!ED25519_sign(sig, tbs, tbslen, key->key.priv)) { + return 0; + } + + *siglen = 64; + return 1; } static int pkey_ed25519_verify_message(EVP_PKEY_CTX *ctx, const uint8_t *sig, @@ -58,7 +90,7 @@ const EVP_PKEY_METHOD ed25519_pkey_meth = { NULL /* init */, pkey_ed25519_copy, NULL /* cleanup */, - NULL /* keygen */, + pkey_ed25519_keygen, NULL /* sign */, pkey_ed25519_sign_message, NULL /* verify */, @@ -67,5 +99,6 @@ const EVP_PKEY_METHOD ed25519_pkey_meth = { NULL /* encrypt */, NULL /* decrypt */, NULL /* derive */, + NULL /* paramgen */, NULL /* ctrl */, }; diff --git a/third_party/boringssl/kit/src/crypto/evp/p_ed25519_asn1.c b/third_party/boringssl/kit/src/crypto/evp/p_ed25519_asn1.c index ba08c6d3..bd44b3f8 100644 --- a/third_party/boringssl/kit/src/crypto/evp/p_ed25519_asn1.c +++ b/third_party/boringssl/kit/src/crypto/evp/p_ed25519_asn1.c @@ -28,45 +28,101 @@ static void ed25519_free(EVP_PKEY *pkey) { pkey->pkey.ptr = NULL; } -static int set_pubkey(EVP_PKEY *pkey, const uint8_t pubkey[32]) { +static int ed25519_set_priv_raw(EVP_PKEY *pkey, const uint8_t *in, size_t len) { + if (len != 32) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return 0; + } + ED25519_KEY *key = OPENSSL_malloc(sizeof(ED25519_KEY)); if (key == NULL) { OPENSSL_PUT_ERROR(EVP, ERR_R_MALLOC_FAILURE); return 0; } - key->has_private = 0; - OPENSSL_memcpy(key->key.pub.value, pubkey, 32); + + // The RFC 8032 encoding stores only the 32-byte seed, so we must recover the + // full representation which we use from it. + uint8_t pubkey_unused[32]; + ED25519_keypair_from_seed(pubkey_unused, key->key.priv, in); + key->has_private = 1; ed25519_free(pkey); pkey->pkey.ptr = key; return 1; } -static int set_privkey(EVP_PKEY *pkey, const uint8_t privkey[64]) { +static int ed25519_set_pub_raw(EVP_PKEY *pkey, const uint8_t *in, size_t len) { + if (len != 32) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return 0; + } + ED25519_KEY *key = OPENSSL_malloc(sizeof(ED25519_KEY)); if (key == NULL) { OPENSSL_PUT_ERROR(EVP, ERR_R_MALLOC_FAILURE); return 0; } - key->has_private = 1; - OPENSSL_memcpy(key->key.priv, privkey, 64); + + OPENSSL_memcpy(key->key.pub.value, in, 32); + key->has_private = 0; ed25519_free(pkey); pkey->pkey.ptr = key; return 1; } +static int ed25519_get_priv_raw(const EVP_PKEY *pkey, uint8_t *out, + size_t *out_len) { + const ED25519_KEY *key = pkey->pkey.ptr; + if (!key->has_private) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); + return 0; + } + + if (out == NULL) { + *out_len = 32; + return 1; + } + + if (*out_len < 32) { + OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); + return 0; + } + + // The raw private key format is the first 32 bytes of the private key. + OPENSSL_memcpy(out, key->key.priv, 32); + *out_len = 32; + return 1; +} + +static int ed25519_get_pub_raw(const EVP_PKEY *pkey, uint8_t *out, + size_t *out_len) { + const ED25519_KEY *key = pkey->pkey.ptr; + if (out == NULL) { + *out_len = 32; + return 1; + } + + if (*out_len < 32) { + OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); + return 0; + } + + OPENSSL_memcpy(out, key->key.pub.value, 32); + *out_len = 32; + return 1; +} + static int ed25519_pub_decode(EVP_PKEY *out, CBS *params, CBS *key) { // See RFC 8410, section 4. // The parameters must be omitted. Public keys have length 32. - if (CBS_len(params) != 0 || - CBS_len(key) != 32) { + if (CBS_len(params) != 0) { OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); return 0; } - return set_pubkey(out, CBS_data(key)); + return ed25519_set_pub_raw(out, CBS_data(key), CBS_len(key)); } static int ed25519_pub_encode(CBB *out, const EVP_PKEY *pkey) { @@ -103,17 +159,12 @@ static int ed25519_priv_decode(EVP_PKEY *out, CBS *params, CBS *key) { CBS inner; if (CBS_len(params) != 0 || !CBS_get_asn1(key, &inner, CBS_ASN1_OCTETSTRING) || - CBS_len(key) != 0 || - CBS_len(&inner) != 32) { + CBS_len(key) != 0) { OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); return 0; } - // The PKCS#8 encoding stores only the 32-byte seed, so we must recover the - // full representation which we use from it. - uint8_t pubkey[32], privkey[64]; - ED25519_keypair_from_seed(pubkey, privkey, CBS_data(&inner)); - return set_privkey(out, privkey); + return ed25519_set_priv_raw(out, CBS_data(&inner), CBS_len(&inner)); } static int ed25519_priv_encode(CBB *out, const EVP_PKEY *pkey) { @@ -156,6 +207,10 @@ const EVP_PKEY_ASN1_METHOD ed25519_asn1_meth = { ed25519_pub_cmp, ed25519_priv_decode, ed25519_priv_encode, + ed25519_set_priv_raw, + ed25519_set_pub_raw, + ed25519_get_priv_raw, + ed25519_get_pub_raw, NULL /* pkey_opaque */, ed25519_size, ed25519_bits, @@ -164,27 +219,3 @@ const EVP_PKEY_ASN1_METHOD ed25519_asn1_meth = { NULL /* param_cmp */, ed25519_free, }; - -EVP_PKEY *EVP_PKEY_new_ed25519_public(const uint8_t public_key[32]) { - EVP_PKEY *ret = EVP_PKEY_new(); - if (ret == NULL || - !EVP_PKEY_set_type(ret, EVP_PKEY_ED25519) || - !set_pubkey(ret, public_key)) { - EVP_PKEY_free(ret); - return NULL; - } - - return ret; -} - -EVP_PKEY *EVP_PKEY_new_ed25519_private(const uint8_t private_key[64]) { - EVP_PKEY *ret = EVP_PKEY_new(); - if (ret == NULL || - !EVP_PKEY_set_type(ret, EVP_PKEY_ED25519) || - !set_privkey(ret, private_key)) { - EVP_PKEY_free(ret); - return NULL; - } - - return ret; -} diff --git a/third_party/boringssl/kit/src/crypto/evp/p_rsa.c b/third_party/boringssl/kit/src/crypto/evp/p_rsa.c index cfc6bea1..865b36af 100644 --- a/third_party/boringssl/kit/src/crypto/evp/p_rsa.c +++ b/third_party/boringssl/kit/src/crypto/evp/p_rsa.c @@ -132,6 +132,7 @@ static int pkey_rsa_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { dctx->pad_mode = sctx->pad_mode; dctx->md = sctx->md; dctx->mgf1md = sctx->mgf1md; + dctx->saltlen = sctx->saltlen; if (sctx->oaep_label) { OPENSSL_free(dctx->oaep_label); dctx->oaep_label = BUF_memdup(sctx->oaep_label, sctx->oaep_labellen); @@ -553,7 +554,8 @@ const EVP_PKEY_METHOD rsa_pkey_meth = { pkey_rsa_verify_recover, pkey_rsa_encrypt, pkey_rsa_decrypt, - 0 /* derive */, + NULL /* derive */, + NULL /* paramgen */, pkey_rsa_ctrl, }; diff --git a/third_party/boringssl/kit/src/crypto/evp/p_rsa_asn1.c b/third_party/boringssl/kit/src/crypto/evp/p_rsa_asn1.c index 85f6fc83..c0971038 100644 --- a/third_party/boringssl/kit/src/crypto/evp/p_rsa_asn1.c +++ b/third_party/boringssl/kit/src/crypto/evp/p_rsa_asn1.c @@ -178,6 +178,11 @@ const EVP_PKEY_ASN1_METHOD rsa_asn1_meth = { rsa_priv_decode, rsa_priv_encode, + NULL /* set_priv_raw */, + NULL /* set_pub_raw */, + NULL /* get_priv_raw */, + NULL /* get_pub_raw */, + rsa_opaque, int_rsa_size, diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/CMakeLists.txt b/third_party/boringssl/kit/src/crypto/fipsmodule/CMakeLists.txt index 463febbf..e9788200 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/CMakeLists.txt +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/CMakeLists.txt @@ -7,7 +7,7 @@ if(${ARCH} STREQUAL "x86_64") aesni-gcm-x86_64.${ASM_EXT} aesni-x86_64.${ASM_EXT} aes-x86_64.${ASM_EXT} - bsaes-x86_64.${ASM_EXT} + ghash-ssse3-x86_64.${ASM_EXT} ghash-x86_64.${ASM_EXT} md5-x86_64.${ASM_EXT} p256-x86_64-asm.${ASM_EXT} @@ -31,6 +31,7 @@ if(${ARCH} STREQUAL "x86") aesni-x86.${ASM_EXT} bn-586.${ASM_EXT} co-586.${ASM_EXT} + ghash-ssse3-x86.${ASM_EXT} ghash-x86.${ASM_EXT} md5-586.${ASM_EXT} sha1-586.${ASM_EXT} @@ -63,10 +64,12 @@ if(${ARCH} STREQUAL "aarch64") aesv8-armx.${ASM_EXT} armv8-mont.${ASM_EXT} + ghash-neon-armv8.${ASM_EXT} ghashv8-armx.${ASM_EXT} sha1-armv8.${ASM_EXT} sha256-armv8.${ASM_EXT} sha512-armv8.${ASM_EXT} + vpaes-armv8.${ASM_EXT} ) endif() @@ -91,11 +94,13 @@ perlasm(armv4-mont.${ASM_EXT} bn/asm/armv4-mont.pl) perlasm(armv8-mont.${ASM_EXT} bn/asm/armv8-mont.pl) perlasm(bn-586.${ASM_EXT} bn/asm/bn-586.pl) perlasm(bsaes-armv7.${ASM_EXT} aes/asm/bsaes-armv7.pl) -perlasm(bsaes-x86_64.${ASM_EXT} aes/asm/bsaes-x86_64.pl) perlasm(co-586.${ASM_EXT} bn/asm/co-586.pl) perlasm(ghash-armv4.${ASM_EXT} modes/asm/ghash-armv4.pl) perlasm(ghashp8-ppc.${ASM_EXT} modes/asm/ghashp8-ppc.pl) perlasm(ghashv8-armx.${ASM_EXT} modes/asm/ghashv8-armx.pl) +perlasm(ghash-neon-armv8.${ASM_EXT} modes/asm/ghash-neon-armv8.pl) +perlasm(ghash-ssse3-x86_64.${ASM_EXT} modes/asm/ghash-ssse3-x86_64.pl) +perlasm(ghash-ssse3-x86.${ASM_EXT} modes/asm/ghash-ssse3-x86.pl) perlasm(ghash-x86_64.${ASM_EXT} modes/asm/ghash-x86_64.pl) perlasm(ghash-x86.${ASM_EXT} modes/asm/ghash-x86.pl) perlasm(md5-586.${ASM_EXT} md5/asm/md5-586.pl) @@ -116,6 +121,7 @@ perlasm(sha512-586.${ASM_EXT} sha/asm/sha512-586.pl) perlasm(sha512-armv4.${ASM_EXT} sha/asm/sha512-armv4.pl) perlasm(sha512-armv8.${ASM_EXT} sha/asm/sha512-armv8.pl) perlasm(sha512-x86_64.${ASM_EXT} sha/asm/sha512-x86_64.pl) +perlasm(vpaes-armv8.${ASM_EXT} aes/asm/vpaes-armv8.pl) perlasm(vpaes-x86_64.${ASM_EXT} aes/asm/vpaes-x86_64.pl) perlasm(vpaes-x86.${ASM_EXT} aes/asm/vpaes-x86.pl) perlasm(x86_64-mont5.${ASM_EXT} bn/asm/x86_64-mont5.pl) @@ -123,6 +129,10 @@ perlasm(x86_64-mont.${ASM_EXT} bn/asm/x86_64-mont.pl) perlasm(x86-mont.${ASM_EXT} bn/asm/x86-mont.pl) if(FIPS_DELOCATE) + if(FIPS_SHARED) + error("Can't set both delocate and shared mode for FIPS build") + endif() + if(OPENSSL_NO_ASM) # If OPENSSL_NO_ASM was defined then ASM will not have been enabled, but in # FIPS mode we have to have it because the module build requires going via @@ -183,12 +193,49 @@ if(FIPS_DELOCATE) OBJECT + fips_shared_support.c is_fips.c ) add_dependencies(fipsmodule global_target) set_target_properties(fipsmodule PROPERTIES LINKER_LANGUAGE C) +elseif(FIPS_SHARED) + if(NOT BUILD_SHARED_LIBS) + error("FIPS_SHARED set but not BUILD_SHARED_LIBS") + endif() + + add_library( + fipsmodule + + OBJECT + + fips_shared_support.c + is_fips.c + ) + + add_dependencies(fipsmodule global_target) + + add_library( + bcm_library + + STATIC + + bcm.c + + ${BCM_ASM_SOURCES} + ) + + add_dependencies(bcm_library global_target) + + add_custom_command( + OUTPUT bcm.o + COMMAND ld -r -T ${CMAKE_CURRENT_SOURCE_DIR}/fips_shared.lds -o bcm.o --whole-archive $ + DEPENDS bcm_library fips_shared.lds + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + ) + + add_custom_target(bcm_o_target DEPENDS bcm.o) else() add_library( fipsmodule @@ -196,6 +243,7 @@ else() OBJECT bcm.c + fips_shared_support.c is_fips.c ${BCM_ASM_SOURCES} diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/FIPS.md b/third_party/boringssl/kit/src/crypto/fipsmodule/FIPS.md index a60e2bfe..8e6fa671 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/FIPS.md +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/FIPS.md @@ -62,9 +62,25 @@ Additionally, because of shared libraries and ASLR, some relocations can only be BoringCrypto is linked (often statically) into a large number of binaries. It would be a significant cost if each of these binaries had to be post-processed in order to calculate the known-good HMAC value. We would much prefer if the value could be calculated, once, when BoringCrypto itself is compiled. -In order for the value to be calculated before the final link, there can be no relocations in the hashed code and data. This document describes how we build C and assembly code in order to produce an object file containing all the code and data for the FIPS module without that code having any relocations. +In order for the value to be calculated before the final link, there can be no relocations in the hashed code and data. This document describes how we build C and assembly code in order to produce a binary file containing all the code and data for the FIPS module without that code having any relocations. -First, all the C source files for the module are compiled as a single unit by compiling a single source file that `#include`s them all (this is `bcm.c`). The `-fPIC` flag is used to cause the compiler to use IP-relative addressing in many (but not all) cases. Also the `-S` flag is used to instruct the compiler to produce a textual assembly file rather than a binary object file. +There are two build configurations supported: static and shared. The shared build produces `libcrypto.so`, which includes the FIPS module and is significantly more straightforward and so is described first: + +### Shared build + +First, all the C source files for the module are compiled as a single unit by compiling a single source file that `#include`s them all (this is `bcm.c`). This, along with some assembly sources, comprise the FIPS module. + +The object files resulting from compiling (or assembling) those files is linked in partial-linking mode with a linker script that causes the linker to insert symbols marking the beginning and end of the text and rodata sections. The linker script also discards other types of data sections to ensure that no unhashed data is used by the module. + +One source of such data are `rel.ro` sections, which contain data that includes function pointers. Since these function pointers are absolute, they are written by the dynamic linker at run-time and so we must eliminate them. The pattern that causes them is when we have a static `EVP_MD` or `EVP_CIPHER` object thus, inside the module, this pattern is changed to instead reserve space in the BSS for the object, and to add a `CRYPTO_once_t` to protect its initialisation. + +Once the partially-linked result is linked again, with other parts of libcrypto, to produce `libcrypto.so`, the contents of the module are fixed, as required. The module code uses the linker-added symbols to find the its code and data at run-time and hashes them upon initialisation. The result is compared against a value stored inside `libcrypto.so`, but outside of the module. That value will, initially, be incorrect, but `inject-hash.go` can inject the correct value. + +### Static build + +The static build cannot depend on the shared-object link to resolve relocations and thus must take another path. + +As with the shared build, all the C sources are build in a single compilation unit. The `-fPIC` flag is used to cause the compiler to use IP-relative addressing in many (but not all) cases. Also the `-S` flag is used to instruct the compiler to produce a textual assembly file rather than a binary object file. The textual assembly file is then processed by a script to merge in assembly implementations of some primitives and to eliminate the remaining sources of relocations. @@ -80,9 +96,9 @@ In this diagram, the integrity check hashes from `module_start` to `module_end`. ##### Read-only data -Normally read-only data is placed in a `.data` segment that doesn't get mapped into memory with execute permissions. However, the offset of the data segment from the text segment is another thing that isn't determined until the final link. In order to fix data offsets before the link, read-only data is simply placed in the module's `.text` segment. This might make building ROP chains easier for an attacker, but so it goes. +Normally read-only data is placed in an `.rodata` segment that doesn't get mapped into memory with execute permissions. However, the offset of the data segment from the text segment is another thing that isn't determined until the final link. In order to fix data offsets before the link, read-only data is simply placed in the module's `.text` segment. This might make building ROP chains easier for an attacker, but so it goes. -One special case is `rel.ro` data, which is data that contains function pointers. Since these function pointers are absolute, they are written by the dynamic linker at run-time and so we must eliminate them. The pattern that causes them is when we have a static `EVP_MD` or `EVP_CIPHER` object thus, inside the module, we'll change this pattern to instead to reserve space in the BSS for the object, and add a `CRYPTO_once_t` to protect its initialisation. The script will generate functions outside of the module that return pointers to these areas of memory—they effectively act like a special-purpose malloc calls that cannot fail. +Data containing function pointers remains an issue. The source-code changes described above for the shared build apply here too, but no direct references to a BSS section are possible because the offset to that section is not known at compile time. Instead, the script generates functions outside of the module that return pointers to these areas of memory—they effectively act like special-purpose malloc calls that cannot fail. ##### Read-write data @@ -92,7 +108,7 @@ In order to allow this we use a similar design to the redirector functions: the ##### Other transforms -The script performs a number of other transformations which are worth noting but do not warrant their own sections: +The script performs a number of other transformations which are worth noting but do not warrant their own discussions: 1. It duplicates each global symbol with a local symbol that has `_local_target` appended to the name. References to the global symbols are rewritten to use these duplicates instead. Otherwise, although the generated code uses IP-relative references, relocations are emitted for global symbols in case they are overridden by a different object file during the link. 1. Various sections, notably `.rodata`, are moved to the `.text` section, inside the module, so module code may reference it without relocations. @@ -112,15 +128,15 @@ Initially the known-good value will be incorrect. Another script (`inject_hash.g (This is based on reading OpenSSL's [user guide](https://www.openssl.org/docs/fips/UserGuide-2.0.pdf) and inspecting the code of OpenSSL FIPS 2.0.12.) -OpenSSL's solution to this problem is broadly similar but has a number of differences: +OpenSSL's solution to this problem is very similar to our shared build, with just a few differences: 1. OpenSSL deals with run-time relocations by not hashing parts of the module's data. -1. OpenSSL uses `ld -r` (the partial linking mode) to merge a number of object files into their `fipscanister.o`. For BoringCrypto, we merge all the C source files by building a single C file that #includes all the others, and we merge the assembly sources by appending them to the assembly output from the C compiler. -1. OpenSSL depends on the link order and inserts two object files, `fips_start.o` and `fips_end.o`, in order to establish the `module_start` and `module_end` values. BoringCrypto adds labels at the correct places in the assembly. +1. OpenSSL uses `ld -r` (the partial linking mode) to merge a number of object files into their `fipscanister.o`. For BoringCrypto's static build, we merge all the C source files by building a single C file that #includes all the others, and we merge the assembly sources by appending them to the assembly output from the C compiler. +1. OpenSSL depends on the link order and inserts two object files, `fips_start.o` and `fips_end.o`, in order to establish the `module_start` and `module_end` values. BoringCrypto adds labels at the correct places in the assembly for the static build, or uses a linker script for the shared build. 1. OpenSSL calculates the hash after the final link and either injects it into the binary or recompiles with the value of the hash passed in as a #define. BoringCrypto calculates it prior to the final link and injects it into the object file. 1. OpenSSL references read-write data directly, since it can know the offsets to it. BoringCrypto indirects these loads and stores. 1. OpenSSL doesn't run the power-on test until `FIPS_module_mode_set` is called. BoringCrypto does it in a constructor function. Failure of the test is non-fatal in OpenSSL, BoringCrypto will crash. -1. Since the contents of OpenSSL's module change between compilation and use, OpenSSL generates `fipscanister.o.sha1` to check that the compiled object doesn't change before linking. Since BoringCrypto's module is fixed after compilation, the final integrity check is unbroken through the linking process. +1. Since the contents of OpenSSL's module change between compilation and use, OpenSSL generates `fipscanister.o.sha1` to check that the compiled object doesn't change before linking. Since BoringCrypto's module is fixed after compilation (in the static case), the final integrity check is unbroken through the linking process. Some of the similarities are worth noting: diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/aes.c b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/aes.c index a9c20d20..48d60eeb 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/aes.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/aes.c @@ -808,15 +808,16 @@ void aes_nohw_decrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { #endif // NO_ASM || (!X86 && !X86_64 && !ARM) -// Be aware that on x86(-64), the |aes_nohw_*| functions are incompatible with -// the aes_hw_* functions. The latter set |AES_KEY.rounds| to one less than the -// true value, which breaks the former. Therefore the two functions cannot mix. -// Also, on Aarch64, the plain-C code, above, is incompatible with the -// |aes_hw_*| functions. +// Be aware that different sets of AES functions use incompatible key +// representations, varying in format of the key schedule, the |AES_KEY.rounds| +// value, or both. Therefore they cannot mix. Also, on AArch64, the plain-C +// code, above, is incompatible with the |aes_hw_*| functions. void AES_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { if (hwaes_capable()) { aes_hw_encrypt(in, out, key); + } else if (vpaes_capable()) { + vpaes_encrypt(in, out, key); } else { aes_nohw_encrypt(in, out, key); } @@ -825,22 +826,34 @@ void AES_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { void AES_decrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { if (hwaes_capable()) { aes_hw_decrypt(in, out, key); + } else if (vpaes_capable()) { + vpaes_decrypt(in, out, key); } else { aes_nohw_decrypt(in, out, key); } } int AES_set_encrypt_key(const uint8_t *key, unsigned bits, AES_KEY *aeskey) { + if (bits != 128 && bits != 192 && bits != 256) { + return -2; + } if (hwaes_capable()) { return aes_hw_set_encrypt_key(key, bits, aeskey); + } else if (vpaes_capable()) { + return vpaes_set_encrypt_key(key, bits, aeskey); } else { return aes_nohw_set_encrypt_key(key, bits, aeskey); } } int AES_set_decrypt_key(const uint8_t *key, unsigned bits, AES_KEY *aeskey) { + if (bits != 128 && bits != 192 && bits != 256) { + return -2; + } if (hwaes_capable()) { return aes_hw_set_decrypt_key(key, bits, aeskey); + } else if (vpaes_capable()) { + return vpaes_set_decrypt_key(key, bits, aeskey); } else { return aes_nohw_set_decrypt_key(key, bits, aeskey); } diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/aes_test.cc b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/aes_test.cc index a0c94114..1f9a4919 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/aes_test.cc +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/aes_test.cc @@ -189,6 +189,13 @@ TEST(AESTest, WrapBadLengths) { } } +TEST(AESTest, InvalidKeySize) { + static const uint8_t kZero[8] = {0}; + AES_KEY key; + EXPECT_LT(AES_set_encrypt_key(kZero, 42, &key), 0); + EXPECT_LT(AES_set_decrypt_key(kZero, 42, &key), 0); +} + #if defined(SUPPORTS_ABI_TEST) TEST(AESTest, ABI) { for (int bits : {128, 192, 256}) { @@ -250,6 +257,9 @@ TEST(AESTest, ABI) { SCOPED_TRACE(blocks); CHECK_ABI(vpaes_cbc_encrypt, buf, buf, AES_BLOCK_SIZE * blocks, &key, block, AES_ENCRYPT); +#if defined(VPAES_CTR32) + CHECK_ABI(vpaes_ctr32_encrypt_blocks, buf, buf, blocks, &key, block); +#endif } CHECK_ABI(vpaes_set_decrypt_key, kKey, bits, &key); diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aes-586.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aes-586.pl index 25f1813d..9b373de2 100755 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aes-586.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aes-586.pl @@ -2997,4 +2997,4 @@ sub deckey() &asm_finish(); -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aes-armv4.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aes-armv4.pl index f4ae922b..9eebb224 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aes-armv4.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aes-armv4.pl @@ -1247,4 +1247,4 @@ while() { close SELF; print $code; -close STDOUT; # enforce flush +close STDOUT or die "error closing STDOUT"; # enforce flush diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aes-x86_64.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aes-x86_64.pl index ea8b9a41..5b95785e 100755 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aes-x86_64.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aes-x86_64.pl @@ -2906,4 +2906,4 @@ $code =~ s/\`([^\`]*)\`/eval($1)/gem; print $code; -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aesni-x86.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aesni-x86.pl index aff2b408..d57127ab 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aesni-x86.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aesni-x86.pl @@ -84,6 +84,9 @@ open OUT,">$output"; &asm_init($ARGV[0]); &external_label("OPENSSL_ia32cap_P"); +&preprocessor_ifndef("NDEBUG") +&external_label("BORINGSSL_function_hit"); +&preprocessor_endif(); &static_label("key_const"); if ($PREFIX eq $AESNI_PREFIX) { $movekey=\&movups; } @@ -193,6 +196,8 @@ sub aesni_generate1 # fully unrolled loop # void $PREFIX_encrypt (const void *inp,void *out,const AES_KEY *key); &aesni_generate1("enc") if (!$inline); &function_begin_B("${PREFIX}_encrypt"); + &record_function_hit(1); + &mov ("eax",&wparam(0)); &mov ($key,&wparam(2)); &movups ($inout0,&QWP(0,"eax")); @@ -875,6 +880,8 @@ if ($PREFIX eq $AESNI_PREFIX) { # 80 saved %esp &function_begin("${PREFIX}_ctr32_encrypt_blocks"); + &record_function_hit(0); + &mov ($inp,&wparam(0)); &mov ($out,&wparam(1)); &mov ($len,&wparam(2)); @@ -2483,6 +2490,8 @@ if ($PREFIX eq $AESNI_PREFIX) { # int $PREFIX_set_encrypt_key (const unsigned char *userKey, int bits, # AES_KEY *key) &function_begin_B("${PREFIX}_set_encrypt_key"); + &record_function_hit(3); + &mov ("eax",&wparam(0)); &mov ($rounds,&wparam(1)); &mov ($key,&wparam(2)); @@ -2542,4 +2551,4 @@ if ($PREFIX eq $AESNI_PREFIX) { &asm_finish(); -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aesni-x86_64.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aesni-x86_64.pl index 14175ad5..15f68059 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aesni-x86_64.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aesni-x86_64.pl @@ -275,6 +275,12 @@ $code.=<<___; .align 16 ${PREFIX}_encrypt: .cfi_startproc +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS +.extern BORINGSSL_function_hit + movb \$1,BORINGSSL_function_hit+1(%rip) +#endif +#endif movups ($inp),$inout0 # load input mov 240($key),$rounds # key->rounds ___ @@ -972,7 +978,7 @@ ___ # does not update *ivec! Nor does it finalize CMAC value # (see engine/eng_aesni.c for details) # -{ +if (0) { # Omit these functions in BoringSSL my $cmac="%r9"; # 6th argument my $increment="%xmm9"; @@ -1199,6 +1205,11 @@ $code.=<<___; .align 16 ${PREFIX}_ctr32_encrypt_blocks: .cfi_startproc +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS + movb \$1,BORINGSSL_function_hit(%rip) +#endif +#endif cmp \$1,$len jne .Lctr32_bulk @@ -1759,7 +1770,7 @@ ___ # const AES_KEY *key1, const AES_KEY *key2 # const unsigned char iv[16]); # -{ +if (0) { # Omit these functions in BoringSSL my @tweak=map("%xmm$_",(10..15)); my ($twmask,$twres,$twtmp)=("%xmm8","%xmm9",@tweak[4]); my ($key2,$ivp,$len_)=("%r8","%r9","%r9"); @@ -2765,7 +2776,7 @@ ___ # unsigned char offset_i[16], const unsigned char L_[][16], # unsigned char checksum[16]); # -{ +if (0) { # Omit these functions in BoringSSL my @offset=map("%xmm$_",(10..15)); my ($checksum,$rndkey0l)=("%xmm8","%xmm9"); my ($block_num,$offset_p)=("%r8","%r9"); # 5th and 6th arguments @@ -4252,7 +4263,7 @@ $code.=<<___; .cfi_endproc .size ${PREFIX}_cbc_encrypt,.-${PREFIX}_cbc_encrypt ___ -} +} # int ${PREFIX}_set_decrypt_key(const unsigned char *inp, # int bits, AES_KEY *key) # @@ -4343,6 +4354,11 @@ $code.=<<___; ${PREFIX}_set_encrypt_key: __aesni_set_encrypt_key: .cfi_startproc +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS + movb \$1,BORINGSSL_function_hit+3(%rip) +#endif +#endif .byte 0x48,0x83,0xEC,0x08 # sub rsp,8 .cfi_adjust_cfa_offset 8 mov \$-1,%rax @@ -4838,6 +4854,9 @@ ctr_xts_se_handler: jmp .Lcommon_seh_tail .size ctr_xts_se_handler,.-ctr_xts_se_handler +___ +# BoringSSL omits the OCB functions. +$code.=<<___ if (0); .type ocb_se_handler,\@abi-omnipotent .align 16 ocb_se_handler: @@ -4989,33 +5008,9 @@ $code.=<<___ if ($PREFIX eq "aes_hw"); .rva .LSEH_end_${PREFIX}_ecb_encrypt .rva .LSEH_info_ecb - .rva .LSEH_begin_${PREFIX}_ccm64_encrypt_blocks - .rva .LSEH_end_${PREFIX}_ccm64_encrypt_blocks - .rva .LSEH_info_ccm64_enc - - .rva .LSEH_begin_${PREFIX}_ccm64_decrypt_blocks - .rva .LSEH_end_${PREFIX}_ccm64_decrypt_blocks - .rva .LSEH_info_ccm64_dec - .rva .LSEH_begin_${PREFIX}_ctr32_encrypt_blocks .rva .LSEH_end_${PREFIX}_ctr32_encrypt_blocks .rva .LSEH_info_ctr32 - - .rva .LSEH_begin_${PREFIX}_xts_encrypt - .rva .LSEH_end_${PREFIX}_xts_encrypt - .rva .LSEH_info_xts_enc - - .rva .LSEH_begin_${PREFIX}_xts_decrypt - .rva .LSEH_end_${PREFIX}_xts_decrypt - .rva .LSEH_info_xts_dec - - .rva .LSEH_begin_${PREFIX}_ocb_encrypt - .rva .LSEH_end_${PREFIX}_ocb_encrypt - .rva .LSEH_info_ocb_enc - - .rva .LSEH_begin_${PREFIX}_ocb_decrypt - .rva .LSEH_end_${PREFIX}_ocb_decrypt - .rva .LSEH_info_ocb_dec ___ $code.=<<___; .rva .LSEH_begin_${PREFIX}_cbc_encrypt @@ -5037,38 +5032,10 @@ $code.=<<___ if ($PREFIX eq "aes_hw"); .byte 9,0,0,0 .rva ecb_ccm64_se_handler .rva .Lecb_enc_body,.Lecb_enc_ret # HandlerData[] -.LSEH_info_ccm64_enc: - .byte 9,0,0,0 - .rva ecb_ccm64_se_handler - .rva .Lccm64_enc_body,.Lccm64_enc_ret # HandlerData[] -.LSEH_info_ccm64_dec: - .byte 9,0,0,0 - .rva ecb_ccm64_se_handler - .rva .Lccm64_dec_body,.Lccm64_dec_ret # HandlerData[] .LSEH_info_ctr32: .byte 9,0,0,0 .rva ctr_xts_se_handler .rva .Lctr32_body,.Lctr32_epilogue # HandlerData[] -.LSEH_info_xts_enc: - .byte 9,0,0,0 - .rva ctr_xts_se_handler - .rva .Lxts_enc_body,.Lxts_enc_epilogue # HandlerData[] -.LSEH_info_xts_dec: - .byte 9,0,0,0 - .rva ctr_xts_se_handler - .rva .Lxts_dec_body,.Lxts_dec_epilogue # HandlerData[] -.LSEH_info_ocb_enc: - .byte 9,0,0,0 - .rva ocb_se_handler - .rva .Locb_enc_body,.Locb_enc_epilogue # HandlerData[] - .rva .Locb_enc_pop - .long 0 -.LSEH_info_ocb_dec: - .byte 9,0,0,0 - .rva ocb_se_handler - .rva .Locb_dec_body,.Locb_dec_epilogue # HandlerData[] - .rva .Locb_dec_pop - .long 0 ___ $code.=<<___; .LSEH_info_cbc: @@ -5141,4 +5108,4 @@ $code =~ s/\bmovbe\s+%eax,\s*([0-9]+)\(%rsp\)/movbe($1)/gem; print $code; -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aesp8-ppc.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aesp8-ppc.pl index 201da1a4..62d4842b 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aesp8-ppc.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aesp8-ppc.pl @@ -1,5 +1,5 @@ #! /usr/bin/env perl -# Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2014-2018 The OpenSSL Project Authors. All Rights Reserved. # # Licensed under the OpenSSL license (the "License"). You may not use # this file except in compliance with the License. You can obtain a copy @@ -40,6 +40,8 @@ # CBC en-/decrypt CTR XTS # POWER8[le] 3.96/0.72 0.74 1.1 # POWER8[be] 3.75/0.65 0.66 1.0 +# POWER9[le] 4.02/0.86 0.84 1.05 +# POWER9[be] 3.99/0.78 0.79 0.97 $flavour = shift; @@ -1827,7 +1829,7 @@ Lctr32_enc8x_three: stvx_u $out1,$x10,$out stvx_u $out2,$x20,$out addi $out,$out,0x30 - b Lcbc_dec8x_done + b Lctr32_enc8x_done .align 5 Lctr32_enc8x_two: @@ -1839,7 +1841,7 @@ Lctr32_enc8x_two: stvx_u $out0,$x00,$out stvx_u $out1,$x10,$out addi $out,$out,0x20 - b Lcbc_dec8x_done + b Lctr32_enc8x_done .align 5 Lctr32_enc8x_one: @@ -3802,4 +3804,4 @@ foreach(split("\n",$code)) { print $_,"\n"; } -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aesv8-armx.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aesv8-armx.pl index 13f86a0b..187c2219 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aesv8-armx.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/aesv8-armx.pl @@ -1018,4 +1018,4 @@ if ($flavour =~ /64/) { ######## 64-bit code } } -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/bsaes-armv7.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/bsaes-armv7.pl index 775dbd5e..932b3b68 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/bsaes-armv7.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/bsaes-armv7.pl @@ -1113,23 +1113,12 @@ my ($inp,$out,$len,$key, $ivp,$fp,$rounds)=map("r$_",(0..3,8..10)); my ($keysched)=("sp"); $code.=<<___; -.extern AES_cbc_encrypt -.extern AES_decrypt - .global bsaes_cbc_encrypt .type bsaes_cbc_encrypt,%function .align 5 bsaes_cbc_encrypt: -#ifndef __KERNEL__ - cmp $len, #128 -#ifndef __thumb__ - blo AES_cbc_encrypt -#else - bhs 1f - b AES_cbc_encrypt -1: -#endif -#endif + @ In OpenSSL, this function had a fallback to aes_nohw_cbc_encrypt for + @ short inputs. We patch this out, using bsaes for all input sizes. @ it is up to the caller to make sure we are called with enc == 0 @@ -1227,10 +1216,7 @@ bsaes_cbc_encrypt: adds $len, $len, #8 beq .Lcbc_dec_done - vld1.8 {@XMM[0]}, [$inp]! @ load input - cmp $len, #2 - blo .Lcbc_dec_one - vld1.8 {@XMM[1]}, [$inp]! + @ Set up most parameters for the _bsaes_decrypt8 call. #ifndef BSAES_ASM_EXTENDED_KEY mov r4, $keysched @ pass the key #else @@ -1238,6 +1224,11 @@ bsaes_cbc_encrypt: #endif mov r5, $rounds vstmia $fp, {@XMM[15]} @ put aside IV + + vld1.8 {@XMM[0]}, [$inp]! @ load input + cmp $len, #2 + blo .Lcbc_dec_one + vld1.8 {@XMM[1]}, [$inp]! beq .Lcbc_dec_two vld1.8 {@XMM[2]}, [$inp]! cmp $len, #4 @@ -1355,16 +1346,11 @@ bsaes_cbc_encrypt: .align 4 .Lcbc_dec_one: sub $inp, $inp, #0x10 - mov $rounds, $out @ save original out pointer - mov $out, $fp @ use the iv scratch space as out buffer - mov r2, $key - vmov @XMM[4],@XMM[15] @ just in case ensure that IV - vmov @XMM[5],@XMM[0] @ and input are preserved - bl AES_decrypt - vld1.8 {@XMM[0]}, [$fp] @ load result - veor @XMM[0], @XMM[0], @XMM[4] @ ^= IV - vmov @XMM[15], @XMM[5] @ @XMM[5] holds input - vst1.8 {@XMM[0]}, [$rounds] @ write output + bl _bsaes_decrypt8 + vldmia $fp, {@XMM[14]} @ reload IV + vld1.8 {@XMM[15]}, [$inp]! @ reload input + veor @XMM[0], @XMM[0], @XMM[14] @ ^= IV + vst1.8 {@XMM[0]}, [$out]! @ write output .Lcbc_dec_done: #ifndef BSAES_ASM_EXTENDED_KEY @@ -1390,14 +1376,12 @@ my $const = "r6"; # shared with _bsaes_encrypt8_alt my $keysched = "sp"; $code.=<<___; -.extern AES_encrypt .global bsaes_ctr32_encrypt_blocks .type bsaes_ctr32_encrypt_blocks,%function .align 5 bsaes_ctr32_encrypt_blocks: - cmp $len, #8 @ use plain AES for - blo .Lctr_enc_short @ small sizes - + @ In OpenSSL, short inputs fall back to aes_nohw_* here. We patch this + @ out to retain a constant-time implementation. mov ip, sp stmdb sp!, {r4-r10, lr} VFP_ABI_PUSH @@ -1573,54 +1557,13 @@ bsaes_ctr32_encrypt_blocks: VFP_ABI_POP ldmia sp!, {r4-r10, pc} @ return -.align 4 -.Lctr_enc_short: - ldr ip, [sp] @ ctr pointer is passed on stack - stmdb sp!, {r4-r8, lr} - - mov r4, $inp @ copy arguments - mov r5, $out - mov r6, $len - mov r7, $key - ldr r8, [ip, #12] @ load counter LSW - vld1.8 {@XMM[1]}, [ip] @ load whole counter value -#ifdef __ARMEL__ - rev r8, r8 -#endif - sub sp, sp, #0x10 - vst1.8 {@XMM[1]}, [sp] @ copy counter value - sub sp, sp, #0x10 - -.Lctr_enc_short_loop: - add r0, sp, #0x10 @ input counter value - mov r1, sp @ output on the stack - mov r2, r7 @ key - - bl AES_encrypt - - vld1.8 {@XMM[0]}, [r4]! @ load input - vld1.8 {@XMM[1]}, [sp] @ load encrypted counter - add r8, r8, #1 -#ifdef __ARMEL__ - rev r0, r8 - str r0, [sp, #0x1c] @ next counter value -#else - str r8, [sp, #0x1c] @ next counter value -#endif - veor @XMM[0],@XMM[0],@XMM[1] - vst1.8 {@XMM[0]}, [r5]! @ store output - subs r6, r6, #1 - bne .Lctr_enc_short_loop - - vmov.i32 q0, #0 - vmov.i32 q1, #0 - vstmia sp!, {q0-q1} - - ldmia sp!, {r4-r8, pc} + @ OpenSSL contains aes_nohw_* fallback code here. We patch this + @ out to retain a constant-time implementation. .size bsaes_ctr32_encrypt_blocks,.-bsaes_ctr32_encrypt_blocks ___ } -{ +# In BorinSSL, we patch XTS support out. +if (0) { ###################################################################### # void bsaes_xts_[en|de]crypt(const char *inp,char *out,size_t len, # const AES_KEY *key1, const AES_KEY *key2, @@ -1657,7 +1600,7 @@ bsaes_xts_encrypt: ldr r0, [ip, #4] @ iv[] mov r1, sp ldr r2, [ip, #0] @ key2 - bl AES_encrypt + bl aes_nohw_encrypt mov r0,sp @ pointer to initial tweak #endif @@ -1975,7 +1918,7 @@ $code.=<<___; mov r2, $key mov r4, $fp @ preserve fp - bl AES_encrypt + bl aes_nohw_encrypt vld1.8 {@XMM[0]}, [sp,:128] veor @XMM[0], @XMM[0], @XMM[8] @@ -2007,7 +1950,7 @@ $code.=<<___; mov r2, $key mov r4, $fp @ preserve fp - bl AES_encrypt + bl aes_nohw_encrypt vld1.8 {@XMM[0]}, [sp,:128] veor @XMM[0], @XMM[0], @XMM[8] @@ -2061,7 +2004,7 @@ bsaes_xts_decrypt: ldr r0, [ip, #4] @ iv[] mov r1, sp ldr r2, [ip, #0] @ key2 - bl AES_encrypt + bl aes_nohw_encrypt mov r0, sp @ pointer to initial tweak #endif @@ -2387,7 +2330,7 @@ $code.=<<___; mov r2, $key mov r4, $fp @ preserve fp - bl AES_decrypt + bl aes_nohw_decrypt vld1.8 {@XMM[0]}, [sp,:128] veor @XMM[0], @XMM[0], @XMM[8] @@ -2419,7 +2362,7 @@ $code.=<<___; mov r2, $key mov r4, $fp @ preserve fp - bl AES_decrypt + bl aes_nohw_decrypt vld1.8 {@XMM[0]}, [sp,:128] veor @XMM[0], @XMM[0], @XMM[9] @@ -2442,7 +2385,7 @@ $code.=<<___; vst1.8 {@XMM[0]}, [sp,:128] mov r2, $key - bl AES_decrypt + bl aes_nohw_decrypt vld1.8 {@XMM[0]}, [sp,:128] veor @XMM[0], @XMM[0], @XMM[8] @@ -2488,4 +2431,4 @@ close SELF; print $code; -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/bsaes-x86_64.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/bsaes-x86_64.pl deleted file mode 100644 index f0031efb..00000000 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/bsaes-x86_64.pl +++ /dev/null @@ -1,3248 +0,0 @@ -#! /usr/bin/env perl -# Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. -# -# Licensed under the OpenSSL license (the "License"). You may not use -# this file except in compliance with the License. You can obtain a copy -# in the file LICENSE in the source distribution or at -# https://www.openssl.org/source/license.html - - -################################################################### -### AES-128 [originally in CTR mode] ### -### bitsliced implementation for Intel Core 2 processors ### -### requires support of SSE extensions up to SSSE3 ### -### Author: Emilia Käsper and Peter Schwabe ### -### Date: 2009-03-19 ### -### Public domain ### -### ### -### See http://homes.esat.kuleuven.be/~ekasper/#software for ### -### further information. ### -################################################################### -# -# September 2011. -# -# Started as transliteration to "perlasm" the original code has -# undergone following changes: -# -# - code was made position-independent; -# - rounds were folded into a loop resulting in >5x size reduction -# from 12.5KB to 2.2KB; -# - above was possibile thanks to mixcolumns() modification that -# allowed to feed its output back to aesenc[last], this was -# achieved at cost of two additional inter-registers moves; -# - some instruction reordering and interleaving; -# - this module doesn't implement key setup subroutine, instead it -# relies on conversion of "conventional" key schedule as returned -# by AES_set_encrypt_key (see discussion below); -# - first and last round keys are treated differently, which allowed -# to skip one shiftrows(), reduce bit-sliced key schedule and -# speed-up conversion by 22%; -# - support for 192- and 256-bit keys was added; -# -# Resulting performance in CPU cycles spent to encrypt one byte out -# of 4096-byte buffer with 128-bit key is: -# -# Emilia's this(*) difference -# -# Core 2 9.30 8.69 +7% -# Nehalem(**) 7.63 6.88 +11% -# Atom 17.1 16.4 +4% -# Silvermont - 12.9 -# Goldmont - 8.85 -# -# (*) Comparison is not completely fair, because "this" is ECB, -# i.e. no extra processing such as counter values calculation -# and xor-ing input as in Emilia's CTR implementation is -# performed. However, the CTR calculations stand for not more -# than 1% of total time, so comparison is *rather* fair. -# -# (**) Results were collected on Westmere, which is considered to -# be equivalent to Nehalem for this code. -# -# As for key schedule conversion subroutine. Interface to OpenSSL -# relies on per-invocation on-the-fly conversion. This naturally -# has impact on performance, especially for short inputs. Conversion -# time in CPU cycles and its ratio to CPU cycles spent in 8x block -# function is: -# -# conversion conversion/8x block -# Core 2 240 0.22 -# Nehalem 180 0.20 -# Atom 430 0.20 -# -# The ratio values mean that 128-byte blocks will be processed -# 16-18% slower, 256-byte blocks - 9-10%, 384-byte blocks - 6-7%, -# etc. Then keep in mind that input sizes not divisible by 128 are -# *effectively* slower, especially shortest ones, e.g. consecutive -# 144-byte blocks are processed 44% slower than one would expect, -# 272 - 29%, 400 - 22%, etc. Yet, despite all these "shortcomings" -# it's still faster than ["hyper-threading-safe" code path in] -# aes-x86_64.pl on all lengths above 64 bytes... -# -# October 2011. -# -# Add decryption procedure. Performance in CPU cycles spent to decrypt -# one byte out of 4096-byte buffer with 128-bit key is: -# -# Core 2 9.98 -# Nehalem 7.80 -# Atom 17.9 -# Silvermont 14.0 -# Goldmont 10.2 -# -# November 2011. -# -# Add bsaes_xts_[en|de]crypt. Less-than-80-bytes-block performance is -# suboptimal, but XTS is meant to be used with larger blocks... -# -# - -$flavour = shift; -$output = shift; -if ($flavour =~ /\./) { $output = $flavour; undef $flavour; } - -$win64=0; $win64=1 if ($flavour =~ /[nm]asm|mingw64/ || $output =~ /\.asm$/); - -$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; -( $xlate="${dir}x86_64-xlate.pl" and -f $xlate ) or -( $xlate="${dir}../../../perlasm/x86_64-xlate.pl" and -f $xlate) or -die "can't locate x86_64-xlate.pl"; - -open OUT,"| \"$^X\" \"$xlate\" $flavour \"$output\""; -*STDOUT=*OUT; - -my ($inp,$out,$len,$key,$ivp)=("%rdi","%rsi","%rdx","%rcx"); -my @XMM=map("%xmm$_",(15,0..14)); # best on Atom, +10% over (0..15) -my $ecb=0; # suppress unreferenced ECB subroutines, spare some space... -my $xts=0; # Also patch out the XTS subroutines. - -{ -my ($key,$rounds,$const)=("%rax","%r10d","%r11"); - -sub Sbox { -# input in lsb > [b0, b1, b2, b3, b4, b5, b6, b7] < msb -# output in lsb > [b0, b1, b4, b6, b3, b7, b2, b5] < msb -my @b=@_[0..7]; -my @t=@_[8..11]; -my @s=@_[12..15]; - &InBasisChange (@b); - &Inv_GF256 (@b[6,5,0,3,7,1,4,2],@t,@s); - &OutBasisChange (@b[7,1,4,2,6,5,0,3]); -} - -sub InBasisChange { -# input in lsb > [b0, b1, b2, b3, b4, b5, b6, b7] < msb -# output in lsb > [b6, b5, b0, b3, b7, b1, b4, b2] < msb -my @b=@_[0..7]; -$code.=<<___; - pxor @b[6], @b[5] - pxor @b[1], @b[2] - pxor @b[0], @b[3] - pxor @b[2], @b[6] - pxor @b[0], @b[5] - - pxor @b[3], @b[6] - pxor @b[7], @b[3] - pxor @b[5], @b[7] - pxor @b[4], @b[3] - pxor @b[5], @b[4] - pxor @b[1], @b[3] - - pxor @b[7], @b[2] - pxor @b[5], @b[1] -___ -} - -sub OutBasisChange { -# input in lsb > [b0, b1, b2, b3, b4, b5, b6, b7] < msb -# output in lsb > [b6, b1, b2, b4, b7, b0, b3, b5] < msb -my @b=@_[0..7]; -$code.=<<___; - pxor @b[6], @b[0] - pxor @b[4], @b[1] - pxor @b[0], @b[2] - pxor @b[6], @b[4] - pxor @b[1], @b[6] - - pxor @b[5], @b[1] - pxor @b[3], @b[5] - pxor @b[7], @b[3] - pxor @b[5], @b[7] - pxor @b[5], @b[2] - - pxor @b[7], @b[4] -___ -} - -sub InvSbox { -# input in lsb > [b0, b1, b2, b3, b4, b5, b6, b7] < msb -# output in lsb > [b0, b1, b6, b4, b2, b7, b3, b5] < msb -my @b=@_[0..7]; -my @t=@_[8..11]; -my @s=@_[12..15]; - &InvInBasisChange (@b); - &Inv_GF256 (@b[5,1,2,6,3,7,0,4],@t,@s); - &InvOutBasisChange (@b[3,7,0,4,5,1,2,6]); -} - -sub InvInBasisChange { # OutBasisChange in reverse -my @b=@_[5,1,2,6,3,7,0,4]; -$code.=<<___ - pxor @b[7], @b[4] - - pxor @b[5], @b[7] - pxor @b[5], @b[2] - pxor @b[7], @b[3] - pxor @b[3], @b[5] - pxor @b[5], @b[1] - - pxor @b[1], @b[6] - pxor @b[0], @b[2] - pxor @b[6], @b[4] - pxor @b[6], @b[0] - pxor @b[4], @b[1] -___ -} - -sub InvOutBasisChange { # InBasisChange in reverse -my @b=@_[2,5,7,3,6,1,0,4]; -$code.=<<___; - pxor @b[5], @b[1] - pxor @b[7], @b[2] - - pxor @b[1], @b[3] - pxor @b[5], @b[4] - pxor @b[5], @b[7] - pxor @b[4], @b[3] - pxor @b[0], @b[5] - pxor @b[7], @b[3] - pxor @b[2], @b[6] - pxor @b[1], @b[2] - pxor @b[3], @b[6] - - pxor @b[0], @b[3] - pxor @b[6], @b[5] -___ -} - -sub Mul_GF4 { -#;************************************************************* -#;* Mul_GF4: Input x0-x1,y0-y1 Output x0-x1 Temp t0 (8) * -#;************************************************************* -my ($x0,$x1,$y0,$y1,$t0)=@_; -$code.=<<___; - movdqa $y0, $t0 - pxor $y1, $t0 - pand $x0, $t0 - pxor $x1, $x0 - pand $y0, $x1 - pand $y1, $x0 - pxor $x1, $x0 - pxor $t0, $x1 -___ -} - -sub Mul_GF4_N { # not used, see next subroutine -# multiply and scale by N -my ($x0,$x1,$y0,$y1,$t0)=@_; -$code.=<<___; - movdqa $y0, $t0 - pxor $y1, $t0 - pand $x0, $t0 - pxor $x1, $x0 - pand $y0, $x1 - pand $y1, $x0 - pxor $x0, $x1 - pxor $t0, $x0 -___ -} - -sub Mul_GF4_N_GF4 { -# interleaved Mul_GF4_N and Mul_GF4 -my ($x0,$x1,$y0,$y1,$t0, - $x2,$x3,$y2,$y3,$t1)=@_; -$code.=<<___; - movdqa $y0, $t0 - movdqa $y2, $t1 - pxor $y1, $t0 - pxor $y3, $t1 - pand $x0, $t0 - pand $x2, $t1 - pxor $x1, $x0 - pxor $x3, $x2 - pand $y0, $x1 - pand $y2, $x3 - pand $y1, $x0 - pand $y3, $x2 - pxor $x0, $x1 - pxor $x3, $x2 - pxor $t0, $x0 - pxor $t1, $x3 -___ -} -sub Mul_GF16_2 { -my @x=@_[0..7]; -my @y=@_[8..11]; -my @t=@_[12..15]; -$code.=<<___; - movdqa @x[0], @t[0] - movdqa @x[1], @t[1] -___ - &Mul_GF4 (@x[0], @x[1], @y[0], @y[1], @t[2]); -$code.=<<___; - pxor @x[2], @t[0] - pxor @x[3], @t[1] - pxor @y[2], @y[0] - pxor @y[3], @y[1] -___ - Mul_GF4_N_GF4 (@t[0], @t[1], @y[0], @y[1], @t[3], - @x[2], @x[3], @y[2], @y[3], @t[2]); -$code.=<<___; - pxor @t[0], @x[0] - pxor @t[0], @x[2] - pxor @t[1], @x[1] - pxor @t[1], @x[3] - - movdqa @x[4], @t[0] - movdqa @x[5], @t[1] - pxor @x[6], @t[0] - pxor @x[7], @t[1] -___ - &Mul_GF4_N_GF4 (@t[0], @t[1], @y[0], @y[1], @t[3], - @x[6], @x[7], @y[2], @y[3], @t[2]); -$code.=<<___; - pxor @y[2], @y[0] - pxor @y[3], @y[1] -___ - &Mul_GF4 (@x[4], @x[5], @y[0], @y[1], @t[3]); -$code.=<<___; - pxor @t[0], @x[4] - pxor @t[0], @x[6] - pxor @t[1], @x[5] - pxor @t[1], @x[7] -___ -} -sub Inv_GF256 { -#;******************************************************************** -#;* Inv_GF256: Input x0-x7 Output x0-x7 Temp t0-t3,s0-s3 (144) * -#;******************************************************************** -my @x=@_[0..7]; -my @t=@_[8..11]; -my @s=@_[12..15]; -# direct optimizations from hardware -$code.=<<___; - movdqa @x[4], @t[3] - movdqa @x[5], @t[2] - movdqa @x[1], @t[1] - movdqa @x[7], @s[1] - movdqa @x[0], @s[0] - - pxor @x[6], @t[3] - pxor @x[7], @t[2] - pxor @x[3], @t[1] - movdqa @t[3], @s[2] - pxor @x[6], @s[1] - movdqa @t[2], @t[0] - pxor @x[2], @s[0] - movdqa @t[3], @s[3] - - por @t[1], @t[2] - por @s[0], @t[3] - pxor @t[0], @s[3] - pand @s[0], @s[2] - pxor @t[1], @s[0] - pand @t[1], @t[0] - pand @s[0], @s[3] - movdqa @x[3], @s[0] - pxor @x[2], @s[0] - pand @s[0], @s[1] - pxor @s[1], @t[3] - pxor @s[1], @t[2] - movdqa @x[4], @s[1] - movdqa @x[1], @s[0] - pxor @x[5], @s[1] - pxor @x[0], @s[0] - movdqa @s[1], @t[1] - pand @s[0], @s[1] - por @s[0], @t[1] - pxor @s[1], @t[0] - pxor @s[3], @t[3] - pxor @s[2], @t[2] - pxor @s[3], @t[1] - movdqa @x[7], @s[0] - pxor @s[2], @t[0] - movdqa @x[6], @s[1] - pxor @s[2], @t[1] - movdqa @x[5], @s[2] - pand @x[3], @s[0] - movdqa @x[4], @s[3] - pand @x[2], @s[1] - pand @x[1], @s[2] - por @x[0], @s[3] - pxor @s[0], @t[3] - pxor @s[1], @t[2] - pxor @s[2], @t[1] - pxor @s[3], @t[0] - - #Inv_GF16 \t0, \t1, \t2, \t3, \s0, \s1, \s2, \s3 - - # new smaller inversion - - movdqa @t[3], @s[0] - pand @t[1], @t[3] - pxor @t[2], @s[0] - - movdqa @t[0], @s[2] - movdqa @s[0], @s[3] - pxor @t[3], @s[2] - pand @s[2], @s[3] - - movdqa @t[1], @s[1] - pxor @t[2], @s[3] - pxor @t[0], @s[1] - - pxor @t[2], @t[3] - - pand @t[3], @s[1] - - movdqa @s[2], @t[2] - pxor @t[0], @s[1] - - pxor @s[1], @t[2] - pxor @s[1], @t[1] - - pand @t[0], @t[2] - - pxor @t[2], @s[2] - pxor @t[2], @t[1] - - pand @s[3], @s[2] - - pxor @s[0], @s[2] -___ -# output in s3, s2, s1, t1 - -# Mul_GF16_2 \x0, \x1, \x2, \x3, \x4, \x5, \x6, \x7, \t2, \t3, \t0, \t1, \s0, \s1, \s2, \s3 - -# Mul_GF16_2 \x0, \x1, \x2, \x3, \x4, \x5, \x6, \x7, \s3, \s2, \s1, \t1, \s0, \t0, \t2, \t3 - &Mul_GF16_2(@x,@s[3,2,1],@t[1],@s[0],@t[0,2,3]); - -### output msb > [x3,x2,x1,x0,x7,x6,x5,x4] < lsb -} - -# AES linear components - -sub ShiftRows { -my @x=@_[0..7]; -my $mask=pop; -$code.=<<___; - pxor 0x00($key),@x[0] - pxor 0x10($key),@x[1] - pxor 0x20($key),@x[2] - pxor 0x30($key),@x[3] - pshufb $mask,@x[0] - pshufb $mask,@x[1] - pxor 0x40($key),@x[4] - pxor 0x50($key),@x[5] - pshufb $mask,@x[2] - pshufb $mask,@x[3] - pxor 0x60($key),@x[6] - pxor 0x70($key),@x[7] - pshufb $mask,@x[4] - pshufb $mask,@x[5] - pshufb $mask,@x[6] - pshufb $mask,@x[7] - lea 0x80($key),$key -___ -} - -sub MixColumns { -# modified to emit output in order suitable for feeding back to aesenc[last] -my @x=@_[0..7]; -my @t=@_[8..15]; -my $inv=@_[16]; # optional -$code.=<<___; - pshufd \$0x93, @x[0], @t[0] # x0 <<< 32 - pshufd \$0x93, @x[1], @t[1] - pxor @t[0], @x[0] # x0 ^ (x0 <<< 32) - pshufd \$0x93, @x[2], @t[2] - pxor @t[1], @x[1] - pshufd \$0x93, @x[3], @t[3] - pxor @t[2], @x[2] - pshufd \$0x93, @x[4], @t[4] - pxor @t[3], @x[3] - pshufd \$0x93, @x[5], @t[5] - pxor @t[4], @x[4] - pshufd \$0x93, @x[6], @t[6] - pxor @t[5], @x[5] - pshufd \$0x93, @x[7], @t[7] - pxor @t[6], @x[6] - pxor @t[7], @x[7] - - pxor @x[0], @t[1] - pxor @x[7], @t[0] - pxor @x[7], @t[1] - pshufd \$0x4E, @x[0], @x[0] # (x0 ^ (x0 <<< 32)) <<< 64) - pxor @x[1], @t[2] - pshufd \$0x4E, @x[1], @x[1] - pxor @x[4], @t[5] - pxor @t[0], @x[0] - pxor @x[5], @t[6] - pxor @t[1], @x[1] - pxor @x[3], @t[4] - pshufd \$0x4E, @x[4], @t[0] - pxor @x[6], @t[7] - pshufd \$0x4E, @x[5], @t[1] - pxor @x[2], @t[3] - pshufd \$0x4E, @x[3], @x[4] - pxor @x[7], @t[3] - pshufd \$0x4E, @x[7], @x[5] - pxor @x[7], @t[4] - pshufd \$0x4E, @x[6], @x[3] - pxor @t[4], @t[0] - pshufd \$0x4E, @x[2], @x[6] - pxor @t[5], @t[1] -___ -$code.=<<___ if (!$inv); - pxor @t[3], @x[4] - pxor @t[7], @x[5] - pxor @t[6], @x[3] - movdqa @t[0], @x[2] - pxor @t[2], @x[6] - movdqa @t[1], @x[7] -___ -$code.=<<___ if ($inv); - pxor @x[4], @t[3] - pxor @t[7], @x[5] - pxor @x[3], @t[6] - movdqa @t[0], @x[3] - pxor @t[2], @x[6] - movdqa @t[6], @x[2] - movdqa @t[1], @x[7] - movdqa @x[6], @x[4] - movdqa @t[3], @x[6] -___ -} - -sub InvMixColumns_orig { -my @x=@_[0..7]; -my @t=@_[8..15]; - -$code.=<<___; - # multiplication by 0x0e - pshufd \$0x93, @x[7], @t[7] - movdqa @x[2], @t[2] - pxor @x[5], @x[7] # 7 5 - pxor @x[5], @x[2] # 2 5 - pshufd \$0x93, @x[0], @t[0] - movdqa @x[5], @t[5] - pxor @x[0], @x[5] # 5 0 [1] - pxor @x[1], @x[0] # 0 1 - pshufd \$0x93, @x[1], @t[1] - pxor @x[2], @x[1] # 1 25 - pxor @x[6], @x[0] # 01 6 [2] - pxor @x[3], @x[1] # 125 3 [4] - pshufd \$0x93, @x[3], @t[3] - pxor @x[0], @x[2] # 25 016 [3] - pxor @x[7], @x[3] # 3 75 - pxor @x[6], @x[7] # 75 6 [0] - pshufd \$0x93, @x[6], @t[6] - movdqa @x[4], @t[4] - pxor @x[4], @x[6] # 6 4 - pxor @x[3], @x[4] # 4 375 [6] - pxor @x[7], @x[3] # 375 756=36 - pxor @t[5], @x[6] # 64 5 [7] - pxor @t[2], @x[3] # 36 2 - pxor @t[4], @x[3] # 362 4 [5] - pshufd \$0x93, @t[5], @t[5] -___ - my @y = @x[7,5,0,2,1,3,4,6]; -$code.=<<___; - # multiplication by 0x0b - pxor @y[0], @y[1] - pxor @t[0], @y[0] - pxor @t[1], @y[1] - pshufd \$0x93, @t[2], @t[2] - pxor @t[5], @y[0] - pxor @t[6], @y[1] - pxor @t[7], @y[0] - pshufd \$0x93, @t[4], @t[4] - pxor @t[6], @t[7] # clobber t[7] - pxor @y[0], @y[1] - - pxor @t[0], @y[3] - pshufd \$0x93, @t[0], @t[0] - pxor @t[1], @y[2] - pxor @t[1], @y[4] - pxor @t[2], @y[2] - pshufd \$0x93, @t[1], @t[1] - pxor @t[2], @y[3] - pxor @t[2], @y[5] - pxor @t[7], @y[2] - pshufd \$0x93, @t[2], @t[2] - pxor @t[3], @y[3] - pxor @t[3], @y[6] - pxor @t[3], @y[4] - pshufd \$0x93, @t[3], @t[3] - pxor @t[4], @y[7] - pxor @t[4], @y[5] - pxor @t[7], @y[7] - pxor @t[5], @y[3] - pxor @t[4], @y[4] - pxor @t[5], @t[7] # clobber t[7] even more - - pxor @t[7], @y[5] - pshufd \$0x93, @t[4], @t[4] - pxor @t[7], @y[6] - pxor @t[7], @y[4] - - pxor @t[5], @t[7] - pshufd \$0x93, @t[5], @t[5] - pxor @t[6], @t[7] # restore t[7] - - # multiplication by 0x0d - pxor @y[7], @y[4] - pxor @t[4], @y[7] - pshufd \$0x93, @t[6], @t[6] - pxor @t[0], @y[2] - pxor @t[5], @y[7] - pxor @t[2], @y[2] - pshufd \$0x93, @t[7], @t[7] - - pxor @y[1], @y[3] - pxor @t[1], @y[1] - pxor @t[0], @y[0] - pxor @t[0], @y[3] - pxor @t[5], @y[1] - pxor @t[5], @y[0] - pxor @t[7], @y[1] - pshufd \$0x93, @t[0], @t[0] - pxor @t[6], @y[0] - pxor @y[1], @y[3] - pxor @t[1], @y[4] - pshufd \$0x93, @t[1], @t[1] - - pxor @t[7], @y[7] - pxor @t[2], @y[4] - pxor @t[2], @y[5] - pshufd \$0x93, @t[2], @t[2] - pxor @t[6], @y[2] - pxor @t[3], @t[6] # clobber t[6] - pxor @y[7], @y[4] - pxor @t[6], @y[3] - - pxor @t[6], @y[6] - pxor @t[5], @y[5] - pxor @t[4], @y[6] - pshufd \$0x93, @t[4], @t[4] - pxor @t[6], @y[5] - pxor @t[7], @y[6] - pxor @t[3], @t[6] # restore t[6] - - pshufd \$0x93, @t[5], @t[5] - pshufd \$0x93, @t[6], @t[6] - pshufd \$0x93, @t[7], @t[7] - pshufd \$0x93, @t[3], @t[3] - - # multiplication by 0x09 - pxor @y[1], @y[4] - pxor @y[1], @t[1] # t[1]=y[1] - pxor @t[5], @t[0] # clobber t[0] - pxor @t[5], @t[1] - pxor @t[0], @y[3] - pxor @y[0], @t[0] # t[0]=y[0] - pxor @t[6], @t[1] - pxor @t[7], @t[6] # clobber t[6] - pxor @t[1], @y[4] - pxor @t[4], @y[7] - pxor @y[4], @t[4] # t[4]=y[4] - pxor @t[3], @y[6] - pxor @y[3], @t[3] # t[3]=y[3] - pxor @t[2], @y[5] - pxor @y[2], @t[2] # t[2]=y[2] - pxor @t[7], @t[3] - pxor @y[5], @t[5] # t[5]=y[5] - pxor @t[6], @t[2] - pxor @t[6], @t[5] - pxor @y[6], @t[6] # t[6]=y[6] - pxor @y[7], @t[7] # t[7]=y[7] - - movdqa @t[0],@XMM[0] - movdqa @t[1],@XMM[1] - movdqa @t[2],@XMM[2] - movdqa @t[3],@XMM[3] - movdqa @t[4],@XMM[4] - movdqa @t[5],@XMM[5] - movdqa @t[6],@XMM[6] - movdqa @t[7],@XMM[7] -___ -} - -sub InvMixColumns { -my @x=@_[0..7]; -my @t=@_[8..15]; - -# Thanks to Jussi Kivilinna for providing pointer to -# -# | 0e 0b 0d 09 | | 02 03 01 01 | | 05 00 04 00 | -# | 09 0e 0b 0d | = | 01 02 03 01 | x | 00 05 00 04 | -# | 0d 09 0e 0b | | 01 01 02 03 | | 04 00 05 00 | -# | 0b 0d 09 0e | | 03 01 01 02 | | 00 04 00 05 | - -$code.=<<___; - # multiplication by 0x05-0x00-0x04-0x00 - pshufd \$0x4E, @x[0], @t[0] - pshufd \$0x4E, @x[6], @t[6] - pxor @x[0], @t[0] - pshufd \$0x4E, @x[7], @t[7] - pxor @x[6], @t[6] - pshufd \$0x4E, @x[1], @t[1] - pxor @x[7], @t[7] - pshufd \$0x4E, @x[2], @t[2] - pxor @x[1], @t[1] - pshufd \$0x4E, @x[3], @t[3] - pxor @x[2], @t[2] - pxor @t[6], @x[0] - pxor @t[6], @x[1] - pshufd \$0x4E, @x[4], @t[4] - pxor @x[3], @t[3] - pxor @t[0], @x[2] - pxor @t[1], @x[3] - pshufd \$0x4E, @x[5], @t[5] - pxor @x[4], @t[4] - pxor @t[7], @x[1] - pxor @t[2], @x[4] - pxor @x[5], @t[5] - - pxor @t[7], @x[2] - pxor @t[6], @x[3] - pxor @t[6], @x[4] - pxor @t[3], @x[5] - pxor @t[4], @x[6] - pxor @t[7], @x[4] - pxor @t[7], @x[5] - pxor @t[5], @x[7] -___ - &MixColumns (@x,@t,1); # flipped 2<->3 and 4<->6 -} - -sub aesenc { # not used -my @b=@_[0..7]; -my @t=@_[8..15]; -$code.=<<___; - movdqa 0x30($const),@t[0] # .LSR -___ - &ShiftRows (@b,@t[0]); - &Sbox (@b,@t); - &MixColumns (@b[0,1,4,6,3,7,2,5],@t); -} - -sub aesenclast { # not used -my @b=@_[0..7]; -my @t=@_[8..15]; -$code.=<<___; - movdqa 0x40($const),@t[0] # .LSRM0 -___ - &ShiftRows (@b,@t[0]); - &Sbox (@b,@t); -$code.=<<___ - pxor 0x00($key),@b[0] - pxor 0x10($key),@b[1] - pxor 0x20($key),@b[4] - pxor 0x30($key),@b[6] - pxor 0x40($key),@b[3] - pxor 0x50($key),@b[7] - pxor 0x60($key),@b[2] - pxor 0x70($key),@b[5] -___ -} - -sub swapmove { -my ($a,$b,$n,$mask,$t)=@_; -$code.=<<___; - movdqa $b,$t - psrlq \$$n,$b - pxor $a,$b - pand $mask,$b - pxor $b,$a - psllq \$$n,$b - pxor $t,$b -___ -} -sub swapmove2x { -my ($a0,$b0,$a1,$b1,$n,$mask,$t0,$t1)=@_; -$code.=<<___; - movdqa $b0,$t0 - psrlq \$$n,$b0 - movdqa $b1,$t1 - psrlq \$$n,$b1 - pxor $a0,$b0 - pxor $a1,$b1 - pand $mask,$b0 - pand $mask,$b1 - pxor $b0,$a0 - psllq \$$n,$b0 - pxor $b1,$a1 - psllq \$$n,$b1 - pxor $t0,$b0 - pxor $t1,$b1 -___ -} - -sub bitslice { -my @x=reverse(@_[0..7]); -my ($t0,$t1,$t2,$t3)=@_[8..11]; -$code.=<<___; - movdqa 0x00($const),$t0 # .LBS0 - movdqa 0x10($const),$t1 # .LBS1 -___ - &swapmove2x(@x[0,1,2,3],1,$t0,$t2,$t3); - &swapmove2x(@x[4,5,6,7],1,$t0,$t2,$t3); -$code.=<<___; - movdqa 0x20($const),$t0 # .LBS2 -___ - &swapmove2x(@x[0,2,1,3],2,$t1,$t2,$t3); - &swapmove2x(@x[4,6,5,7],2,$t1,$t2,$t3); - - &swapmove2x(@x[0,4,1,5],4,$t0,$t2,$t3); - &swapmove2x(@x[2,6,3,7],4,$t0,$t2,$t3); -} - -$code.=<<___; -.text - -.extern aes_nohw_encrypt -.extern aes_nohw_decrypt - -.type _bsaes_encrypt8,\@abi-omnipotent -.align 64 -_bsaes_encrypt8: -.cfi_startproc - lea .LBS0(%rip), $const # constants table - - movdqa ($key), @XMM[9] # round 0 key - lea 0x10($key), $key - movdqa 0x50($const), @XMM[8] # .LM0SR - pxor @XMM[9], @XMM[0] # xor with round0 key - pxor @XMM[9], @XMM[1] - pxor @XMM[9], @XMM[2] - pxor @XMM[9], @XMM[3] - pshufb @XMM[8], @XMM[0] - pshufb @XMM[8], @XMM[1] - pxor @XMM[9], @XMM[4] - pxor @XMM[9], @XMM[5] - pshufb @XMM[8], @XMM[2] - pshufb @XMM[8], @XMM[3] - pxor @XMM[9], @XMM[6] - pxor @XMM[9], @XMM[7] - pshufb @XMM[8], @XMM[4] - pshufb @XMM[8], @XMM[5] - pshufb @XMM[8], @XMM[6] - pshufb @XMM[8], @XMM[7] -_bsaes_encrypt8_bitslice: -___ - &bitslice (@XMM[0..7, 8..11]); -$code.=<<___; - dec $rounds - jmp .Lenc_sbox -.align 16 -.Lenc_loop: -___ - &ShiftRows (@XMM[0..7, 8]); -$code.=".Lenc_sbox:\n"; - &Sbox (@XMM[0..7, 8..15]); -$code.=<<___; - dec $rounds - jl .Lenc_done -___ - &MixColumns (@XMM[0,1,4,6,3,7,2,5, 8..15]); -$code.=<<___; - movdqa 0x30($const), @XMM[8] # .LSR - jnz .Lenc_loop - movdqa 0x40($const), @XMM[8] # .LSRM0 - jmp .Lenc_loop -.align 16 -.Lenc_done: -___ - # output in lsb > [t0, t1, t4, t6, t3, t7, t2, t5] < msb - &bitslice (@XMM[0,1,4,6,3,7,2,5, 8..11]); -$code.=<<___; - movdqa ($key), @XMM[8] # last round key - pxor @XMM[8], @XMM[4] - pxor @XMM[8], @XMM[6] - pxor @XMM[8], @XMM[3] - pxor @XMM[8], @XMM[7] - pxor @XMM[8], @XMM[2] - pxor @XMM[8], @XMM[5] - pxor @XMM[8], @XMM[0] - pxor @XMM[8], @XMM[1] - ret -.cfi_endproc -.size _bsaes_encrypt8,.-_bsaes_encrypt8 - -.type _bsaes_decrypt8,\@abi-omnipotent -.align 64 -_bsaes_decrypt8: -.cfi_startproc - lea .LBS0(%rip), $const # constants table - - movdqa ($key), @XMM[9] # round 0 key - lea 0x10($key), $key - movdqa -0x30($const), @XMM[8] # .LM0ISR - pxor @XMM[9], @XMM[0] # xor with round0 key - pxor @XMM[9], @XMM[1] - pxor @XMM[9], @XMM[2] - pxor @XMM[9], @XMM[3] - pshufb @XMM[8], @XMM[0] - pshufb @XMM[8], @XMM[1] - pxor @XMM[9], @XMM[4] - pxor @XMM[9], @XMM[5] - pshufb @XMM[8], @XMM[2] - pshufb @XMM[8], @XMM[3] - pxor @XMM[9], @XMM[6] - pxor @XMM[9], @XMM[7] - pshufb @XMM[8], @XMM[4] - pshufb @XMM[8], @XMM[5] - pshufb @XMM[8], @XMM[6] - pshufb @XMM[8], @XMM[7] -___ - &bitslice (@XMM[0..7, 8..11]); -$code.=<<___; - dec $rounds - jmp .Ldec_sbox -.align 16 -.Ldec_loop: -___ - &ShiftRows (@XMM[0..7, 8]); -$code.=".Ldec_sbox:\n"; - &InvSbox (@XMM[0..7, 8..15]); -$code.=<<___; - dec $rounds - jl .Ldec_done -___ - &InvMixColumns (@XMM[0,1,6,4,2,7,3,5, 8..15]); -$code.=<<___; - movdqa -0x10($const), @XMM[8] # .LISR - jnz .Ldec_loop - movdqa -0x20($const), @XMM[8] # .LISRM0 - jmp .Ldec_loop -.align 16 -.Ldec_done: -___ - &bitslice (@XMM[0,1,6,4,2,7,3,5, 8..11]); -$code.=<<___; - movdqa ($key), @XMM[8] # last round key - pxor @XMM[8], @XMM[6] - pxor @XMM[8], @XMM[4] - pxor @XMM[8], @XMM[2] - pxor @XMM[8], @XMM[7] - pxor @XMM[8], @XMM[3] - pxor @XMM[8], @XMM[5] - pxor @XMM[8], @XMM[0] - pxor @XMM[8], @XMM[1] - ret -.cfi_endproc -.size _bsaes_decrypt8,.-_bsaes_decrypt8 -___ -} -{ -my ($out,$inp,$rounds,$const)=("%rax","%rcx","%r10d","%r11"); - -sub bitslice_key { -my @x=reverse(@_[0..7]); -my ($bs0,$bs1,$bs2,$t2,$t3)=@_[8..12]; - - &swapmove (@x[0,1],1,$bs0,$t2,$t3); -$code.=<<___; - #&swapmove(@x[2,3],1,$t0,$t2,$t3); - movdqa @x[0], @x[2] - movdqa @x[1], @x[3] -___ - #&swapmove2x(@x[4,5,6,7],1,$t0,$t2,$t3); - - &swapmove2x (@x[0,2,1,3],2,$bs1,$t2,$t3); -$code.=<<___; - #&swapmove2x(@x[4,6,5,7],2,$t1,$t2,$t3); - movdqa @x[0], @x[4] - movdqa @x[2], @x[6] - movdqa @x[1], @x[5] - movdqa @x[3], @x[7] -___ - &swapmove2x (@x[0,4,1,5],4,$bs2,$t2,$t3); - &swapmove2x (@x[2,6,3,7],4,$bs2,$t2,$t3); -} - -$code.=<<___; -.type _bsaes_key_convert,\@abi-omnipotent -.align 16 -_bsaes_key_convert: -.cfi_startproc - lea .Lmasks(%rip), $const - movdqu ($inp), %xmm7 # load round 0 key - lea 0x10($inp), $inp - movdqa 0x00($const), %xmm0 # 0x01... - movdqa 0x10($const), %xmm1 # 0x02... - movdqa 0x20($const), %xmm2 # 0x04... - movdqa 0x30($const), %xmm3 # 0x08... - movdqa 0x40($const), %xmm4 # .LM0 - pcmpeqd %xmm5, %xmm5 # .LNOT - - movdqu ($inp), %xmm6 # load round 1 key - movdqa %xmm7, ($out) # save round 0 key - lea 0x10($out), $out - dec $rounds - jmp .Lkey_loop -.align 16 -.Lkey_loop: - pshufb %xmm4, %xmm6 # .LM0 - - movdqa %xmm0, %xmm8 - movdqa %xmm1, %xmm9 - - pand %xmm6, %xmm8 - pand %xmm6, %xmm9 - movdqa %xmm2, %xmm10 - pcmpeqb %xmm0, %xmm8 - psllq \$4, %xmm0 # 0x10... - movdqa %xmm3, %xmm11 - pcmpeqb %xmm1, %xmm9 - psllq \$4, %xmm1 # 0x20... - - pand %xmm6, %xmm10 - pand %xmm6, %xmm11 - movdqa %xmm0, %xmm12 - pcmpeqb %xmm2, %xmm10 - psllq \$4, %xmm2 # 0x40... - movdqa %xmm1, %xmm13 - pcmpeqb %xmm3, %xmm11 - psllq \$4, %xmm3 # 0x80... - - movdqa %xmm2, %xmm14 - movdqa %xmm3, %xmm15 - pxor %xmm5, %xmm8 # "pnot" - pxor %xmm5, %xmm9 - - pand %xmm6, %xmm12 - pand %xmm6, %xmm13 - movdqa %xmm8, 0x00($out) # write bit-sliced round key - pcmpeqb %xmm0, %xmm12 - psrlq \$4, %xmm0 # 0x01... - movdqa %xmm9, 0x10($out) - pcmpeqb %xmm1, %xmm13 - psrlq \$4, %xmm1 # 0x02... - lea 0x10($inp), $inp - - pand %xmm6, %xmm14 - pand %xmm6, %xmm15 - movdqa %xmm10, 0x20($out) - pcmpeqb %xmm2, %xmm14 - psrlq \$4, %xmm2 # 0x04... - movdqa %xmm11, 0x30($out) - pcmpeqb %xmm3, %xmm15 - psrlq \$4, %xmm3 # 0x08... - movdqu ($inp), %xmm6 # load next round key - - pxor %xmm5, %xmm13 # "pnot" - pxor %xmm5, %xmm14 - movdqa %xmm12, 0x40($out) - movdqa %xmm13, 0x50($out) - movdqa %xmm14, 0x60($out) - movdqa %xmm15, 0x70($out) - lea 0x80($out),$out - dec $rounds - jnz .Lkey_loop - - movdqa 0x50($const), %xmm7 # .L63 - #movdqa %xmm6, ($out) # don't save last round key - ret -.cfi_endproc -.size _bsaes_key_convert,.-_bsaes_key_convert -___ -} - -if (0 && !$win64) { # following four functions are unsupported interface - # used for benchmarking... -$code.=<<___; -.globl bsaes_enc_key_convert -.type bsaes_enc_key_convert,\@function,2 -.align 16 -bsaes_enc_key_convert: - mov 240($inp),%r10d # pass rounds - mov $inp,%rcx # pass key - mov $out,%rax # pass key schedule - call _bsaes_key_convert - pxor %xmm6,%xmm7 # fix up last round key - movdqa %xmm7,(%rax) # save last round key - ret -.size bsaes_enc_key_convert,.-bsaes_enc_key_convert - -.globl bsaes_encrypt_128 -.type bsaes_encrypt_128,\@function,4 -.align 16 -bsaes_encrypt_128: -.Lenc128_loop: - movdqu 0x00($inp), @XMM[0] # load input - movdqu 0x10($inp), @XMM[1] - movdqu 0x20($inp), @XMM[2] - movdqu 0x30($inp), @XMM[3] - movdqu 0x40($inp), @XMM[4] - movdqu 0x50($inp), @XMM[5] - movdqu 0x60($inp), @XMM[6] - movdqu 0x70($inp), @XMM[7] - mov $key, %rax # pass the $key - lea 0x80($inp), $inp - mov \$10,%r10d - - call _bsaes_encrypt8 - - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[4], 0x20($out) - movdqu @XMM[6], 0x30($out) - movdqu @XMM[3], 0x40($out) - movdqu @XMM[7], 0x50($out) - movdqu @XMM[2], 0x60($out) - movdqu @XMM[5], 0x70($out) - lea 0x80($out), $out - sub \$0x80,$len - ja .Lenc128_loop - ret -.size bsaes_encrypt_128,.-bsaes_encrypt_128 - -.globl bsaes_dec_key_convert -.type bsaes_dec_key_convert,\@function,2 -.align 16 -bsaes_dec_key_convert: - mov 240($inp),%r10d # pass rounds - mov $inp,%rcx # pass key - mov $out,%rax # pass key schedule - call _bsaes_key_convert - pxor ($out),%xmm7 # fix up round 0 key - movdqa %xmm6,(%rax) # save last round key - movdqa %xmm7,($out) - ret -.size bsaes_dec_key_convert,.-bsaes_dec_key_convert - -.globl bsaes_decrypt_128 -.type bsaes_decrypt_128,\@function,4 -.align 16 -bsaes_decrypt_128: -.Ldec128_loop: - movdqu 0x00($inp), @XMM[0] # load input - movdqu 0x10($inp), @XMM[1] - movdqu 0x20($inp), @XMM[2] - movdqu 0x30($inp), @XMM[3] - movdqu 0x40($inp), @XMM[4] - movdqu 0x50($inp), @XMM[5] - movdqu 0x60($inp), @XMM[6] - movdqu 0x70($inp), @XMM[7] - mov $key, %rax # pass the $key - lea 0x80($inp), $inp - mov \$10,%r10d - - call _bsaes_decrypt8 - - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[6], 0x20($out) - movdqu @XMM[4], 0x30($out) - movdqu @XMM[2], 0x40($out) - movdqu @XMM[7], 0x50($out) - movdqu @XMM[3], 0x60($out) - movdqu @XMM[5], 0x70($out) - lea 0x80($out), $out - sub \$0x80,$len - ja .Ldec128_loop - ret -.size bsaes_decrypt_128,.-bsaes_decrypt_128 -___ -} -{ -###################################################################### -# -# OpenSSL interface -# -my ($arg1,$arg2,$arg3,$arg4,$arg5,$arg6)=$win64 ? ("%rcx","%rdx","%r8","%r9","%r10","%r11d") - : ("%rdi","%rsi","%rdx","%rcx","%r8","%r9d"); -my ($inp,$out,$len,$key)=("%r12","%r13","%r14","%r15"); - -if ($ecb) { -$code.=<<___; -.globl bsaes_ecb_encrypt_blocks -.type bsaes_ecb_encrypt_blocks,\@abi-omnipotent -.align 16 -bsaes_ecb_encrypt_blocks: -.cfi_startproc - mov %rsp, %rax -.Lecb_enc_prologue: - push %rbp -.cfi_push %rbp - push %rbx -.cfi_push %rbx - push %r12 -.cfi_push %r12 - push %r13 -.cfi_push %r13 - push %r14 -.cfi_push %r14 - push %r15 -.cfi_push %r15 - lea -0x48(%rsp),%rsp -.cfi_adjust_cfa_offset 0x48 -___ -$code.=<<___ if ($win64); - lea -0xa0(%rsp), %rsp - movaps %xmm6, 0x40(%rsp) - movaps %xmm7, 0x50(%rsp) - movaps %xmm8, 0x60(%rsp) - movaps %xmm9, 0x70(%rsp) - movaps %xmm10, 0x80(%rsp) - movaps %xmm11, 0x90(%rsp) - movaps %xmm12, 0xa0(%rsp) - movaps %xmm13, 0xb0(%rsp) - movaps %xmm14, 0xc0(%rsp) - movaps %xmm15, 0xd0(%rsp) -.Lecb_enc_body: -___ -$code.=<<___; - mov %rsp,%rbp # backup %rsp -.cfi_def_cfa_register %rbp - mov 240($arg4),%eax # rounds - mov $arg1,$inp # backup arguments - mov $arg2,$out - mov $arg3,$len - mov $arg4,$key - cmp \$8,$arg3 - jb .Lecb_enc_short - - mov %eax,%ebx # backup rounds - shl \$7,%rax # 128 bytes per inner round key - sub \$`128-32`,%rax # size of bit-sliced key schedule - sub %rax,%rsp - mov %rsp,%rax # pass key schedule - mov $key,%rcx # pass key - mov %ebx,%r10d # pass rounds - call _bsaes_key_convert - pxor %xmm6,%xmm7 # fix up last round key - movdqa %xmm7,(%rax) # save last round key - - sub \$8,$len -.Lecb_enc_loop: - movdqu 0x00($inp), @XMM[0] # load input - movdqu 0x10($inp), @XMM[1] - movdqu 0x20($inp), @XMM[2] - movdqu 0x30($inp), @XMM[3] - movdqu 0x40($inp), @XMM[4] - movdqu 0x50($inp), @XMM[5] - mov %rsp, %rax # pass key schedule - movdqu 0x60($inp), @XMM[6] - mov %ebx,%r10d # pass rounds - movdqu 0x70($inp), @XMM[7] - lea 0x80($inp), $inp - - call _bsaes_encrypt8 - - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[4], 0x20($out) - movdqu @XMM[6], 0x30($out) - movdqu @XMM[3], 0x40($out) - movdqu @XMM[7], 0x50($out) - movdqu @XMM[2], 0x60($out) - movdqu @XMM[5], 0x70($out) - lea 0x80($out), $out - sub \$8,$len - jnc .Lecb_enc_loop - - add \$8,$len - jz .Lecb_enc_done - - movdqu 0x00($inp), @XMM[0] # load input - mov %rsp, %rax # pass key schedule - mov %ebx,%r10d # pass rounds - cmp \$2,$len - jb .Lecb_enc_one - movdqu 0x10($inp), @XMM[1] - je .Lecb_enc_two - movdqu 0x20($inp), @XMM[2] - cmp \$4,$len - jb .Lecb_enc_three - movdqu 0x30($inp), @XMM[3] - je .Lecb_enc_four - movdqu 0x40($inp), @XMM[4] - cmp \$6,$len - jb .Lecb_enc_five - movdqu 0x50($inp), @XMM[5] - je .Lecb_enc_six - movdqu 0x60($inp), @XMM[6] - call _bsaes_encrypt8 - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[4], 0x20($out) - movdqu @XMM[6], 0x30($out) - movdqu @XMM[3], 0x40($out) - movdqu @XMM[7], 0x50($out) - movdqu @XMM[2], 0x60($out) - jmp .Lecb_enc_done -.align 16 -.Lecb_enc_six: - call _bsaes_encrypt8 - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[4], 0x20($out) - movdqu @XMM[6], 0x30($out) - movdqu @XMM[3], 0x40($out) - movdqu @XMM[7], 0x50($out) - jmp .Lecb_enc_done -.align 16 -.Lecb_enc_five: - call _bsaes_encrypt8 - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[4], 0x20($out) - movdqu @XMM[6], 0x30($out) - movdqu @XMM[3], 0x40($out) - jmp .Lecb_enc_done -.align 16 -.Lecb_enc_four: - call _bsaes_encrypt8 - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[4], 0x20($out) - movdqu @XMM[6], 0x30($out) - jmp .Lecb_enc_done -.align 16 -.Lecb_enc_three: - call _bsaes_encrypt8 - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[4], 0x20($out) - jmp .Lecb_enc_done -.align 16 -.Lecb_enc_two: - call _bsaes_encrypt8 - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - jmp .Lecb_enc_done -.align 16 -.Lecb_enc_one: - call _bsaes_encrypt8 - movdqu @XMM[0], 0x00($out) # write output - jmp .Lecb_enc_done -.align 16 -.Lecb_enc_short: - lea ($inp), $arg1 - lea ($out), $arg2 - lea ($key), $arg3 - call aes_nohw_encrypt - lea 16($inp), $inp - lea 16($out), $out - dec $len - jnz .Lecb_enc_short - -.Lecb_enc_done: - lea (%rsp),%rax - pxor %xmm0, %xmm0 -.Lecb_enc_bzero: # wipe key schedule [if any] - movdqa %xmm0, 0x00(%rax) - movdqa %xmm0, 0x10(%rax) - lea 0x20(%rax), %rax - cmp %rax, %rbp - jb .Lecb_enc_bzero - - lea 0x78(%rbp),%rax -.cfi_def_cfa %rax,8 -___ -$code.=<<___ if ($win64); - movaps 0x40(%rbp), %xmm6 - movaps 0x50(%rbp), %xmm7 - movaps 0x60(%rbp), %xmm8 - movaps 0x70(%rbp), %xmm9 - movaps 0x80(%rbp), %xmm10 - movaps 0x90(%rbp), %xmm11 - movaps 0xa0(%rbp), %xmm12 - movaps 0xb0(%rbp), %xmm13 - movaps 0xc0(%rbp), %xmm14 - movaps 0xd0(%rbp), %xmm15 - lea 0xa0(%rax), %rax -.Lecb_enc_tail: -___ -$code.=<<___; - mov -48(%rax), %r15 -.cfi_restore %r15 - mov -40(%rax), %r14 -.cfi_restore %r14 - mov -32(%rax), %r13 -.cfi_restore %r13 - mov -24(%rax), %r12 -.cfi_restore %r12 - mov -16(%rax), %rbx -.cfi_restore %rbx - mov -8(%rax), %rbp -.cfi_restore %rbp - lea (%rax), %rsp # restore %rsp -.cfi_def_cfa_register %rsp -.Lecb_enc_epilogue: - ret -.cfi_endproc -.size bsaes_ecb_encrypt_blocks,.-bsaes_ecb_encrypt_blocks - -.globl bsaes_ecb_decrypt_blocks -.type bsaes_ecb_decrypt_blocks,\@abi-omnipotent -.align 16 -bsaes_ecb_decrypt_blocks: -.cfi_startproc - mov %rsp, %rax -.Lecb_dec_prologue: - push %rbp -.cfi_push %rbp - push %rbx -.cfi_push %rbx - push %r12 -.cfi_push %r12 - push %r13 -.cfi_push %r13 - push %r14 -.cfi_push %r14 - push %r15 -.cfi_push %r15 - lea -0x48(%rsp),%rsp -.cfi_adjust_cfa_offset 0x48 -___ -$code.=<<___ if ($win64); - lea -0xa0(%rsp), %rsp - movaps %xmm6, 0x40(%rsp) - movaps %xmm7, 0x50(%rsp) - movaps %xmm8, 0x60(%rsp) - movaps %xmm9, 0x70(%rsp) - movaps %xmm10, 0x80(%rsp) - movaps %xmm11, 0x90(%rsp) - movaps %xmm12, 0xa0(%rsp) - movaps %xmm13, 0xb0(%rsp) - movaps %xmm14, 0xc0(%rsp) - movaps %xmm15, 0xd0(%rsp) -.Lecb_dec_body: -___ -$code.=<<___; - mov %rsp,%rbp # backup %rsp -.cfi_def_cfa_register %rbp - mov 240($arg4),%eax # rounds - mov $arg1,$inp # backup arguments - mov $arg2,$out - mov $arg3,$len - mov $arg4,$key - cmp \$8,$arg3 - jb .Lecb_dec_short - - mov %eax,%ebx # backup rounds - shl \$7,%rax # 128 bytes per inner round key - sub \$`128-32`,%rax # size of bit-sliced key schedule - sub %rax,%rsp - mov %rsp,%rax # pass key schedule - mov $key,%rcx # pass key - mov %ebx,%r10d # pass rounds - call _bsaes_key_convert - pxor (%rsp),%xmm7 # fix up 0 round key - movdqa %xmm6,(%rax) # save last round key - movdqa %xmm7,(%rsp) - - sub \$8,$len -.Lecb_dec_loop: - movdqu 0x00($inp), @XMM[0] # load input - movdqu 0x10($inp), @XMM[1] - movdqu 0x20($inp), @XMM[2] - movdqu 0x30($inp), @XMM[3] - movdqu 0x40($inp), @XMM[4] - movdqu 0x50($inp), @XMM[5] - mov %rsp, %rax # pass key schedule - movdqu 0x60($inp), @XMM[6] - mov %ebx,%r10d # pass rounds - movdqu 0x70($inp), @XMM[7] - lea 0x80($inp), $inp - - call _bsaes_decrypt8 - - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[6], 0x20($out) - movdqu @XMM[4], 0x30($out) - movdqu @XMM[2], 0x40($out) - movdqu @XMM[7], 0x50($out) - movdqu @XMM[3], 0x60($out) - movdqu @XMM[5], 0x70($out) - lea 0x80($out), $out - sub \$8,$len - jnc .Lecb_dec_loop - - add \$8,$len - jz .Lecb_dec_done - - movdqu 0x00($inp), @XMM[0] # load input - mov %rsp, %rax # pass key schedule - mov %ebx,%r10d # pass rounds - cmp \$2,$len - jb .Lecb_dec_one - movdqu 0x10($inp), @XMM[1] - je .Lecb_dec_two - movdqu 0x20($inp), @XMM[2] - cmp \$4,$len - jb .Lecb_dec_three - movdqu 0x30($inp), @XMM[3] - je .Lecb_dec_four - movdqu 0x40($inp), @XMM[4] - cmp \$6,$len - jb .Lecb_dec_five - movdqu 0x50($inp), @XMM[5] - je .Lecb_dec_six - movdqu 0x60($inp), @XMM[6] - call _bsaes_decrypt8 - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[6], 0x20($out) - movdqu @XMM[4], 0x30($out) - movdqu @XMM[2], 0x40($out) - movdqu @XMM[7], 0x50($out) - movdqu @XMM[3], 0x60($out) - jmp .Lecb_dec_done -.align 16 -.Lecb_dec_six: - call _bsaes_decrypt8 - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[6], 0x20($out) - movdqu @XMM[4], 0x30($out) - movdqu @XMM[2], 0x40($out) - movdqu @XMM[7], 0x50($out) - jmp .Lecb_dec_done -.align 16 -.Lecb_dec_five: - call _bsaes_decrypt8 - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[6], 0x20($out) - movdqu @XMM[4], 0x30($out) - movdqu @XMM[2], 0x40($out) - jmp .Lecb_dec_done -.align 16 -.Lecb_dec_four: - call _bsaes_decrypt8 - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[6], 0x20($out) - movdqu @XMM[4], 0x30($out) - jmp .Lecb_dec_done -.align 16 -.Lecb_dec_three: - call _bsaes_decrypt8 - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[6], 0x20($out) - jmp .Lecb_dec_done -.align 16 -.Lecb_dec_two: - call _bsaes_decrypt8 - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - jmp .Lecb_dec_done -.align 16 -.Lecb_dec_one: - call _bsaes_decrypt8 - movdqu @XMM[0], 0x00($out) # write output - jmp .Lecb_dec_done -.align 16 -.Lecb_dec_short: - lea ($inp), $arg1 - lea ($out), $arg2 - lea ($key), $arg3 - call aes_nohw_decrypt - lea 16($inp), $inp - lea 16($out), $out - dec $len - jnz .Lecb_dec_short - -.Lecb_dec_done: - lea (%rsp),%rax - pxor %xmm0, %xmm0 -.Lecb_dec_bzero: # wipe key schedule [if any] - movdqa %xmm0, 0x00(%rax) - movdqa %xmm0, 0x10(%rax) - lea 0x20(%rax), %rax - cmp %rax, %rbp - jb .Lecb_dec_bzero - - lea 0x78(%rbp),%rax -.cfi_def_cfa %rax,8 -___ -$code.=<<___ if ($win64); - movaps 0x40(%rbp), %xmm6 - movaps 0x50(%rbp), %xmm7 - movaps 0x60(%rbp), %xmm8 - movaps 0x70(%rbp), %xmm9 - movaps 0x80(%rbp), %xmm10 - movaps 0x90(%rbp), %xmm11 - movaps 0xa0(%rbp), %xmm12 - movaps 0xb0(%rbp), %xmm13 - movaps 0xc0(%rbp), %xmm14 - movaps 0xd0(%rbp), %xmm15 - lea 0xa0(%rax), %rax -.Lecb_dec_tail: -___ -$code.=<<___; - mov -48(%rax), %r15 -.cfi_restore %r15 - mov -40(%rax), %r14 -.cfi_restore %r14 - mov -32(%rax), %r13 -.cfi_restore %r13 - mov -24(%rax), %r12 -.cfi_restore %r12 - mov -16(%rax), %rbx -.cfi_restore %rbx - mov -8(%rax), %rbp -.cfi_restore %rbp - lea (%rax), %rsp # restore %rsp -.cfi_def_cfa_register %rsp -.Lecb_dec_epilogue: - ret -.cfi_endproc -.size bsaes_ecb_decrypt_blocks,.-bsaes_ecb_decrypt_blocks -___ -} -$code.=<<___; -.extern aes_nohw_cbc_encrypt -.globl bsaes_cbc_encrypt -.type bsaes_cbc_encrypt,\@abi-omnipotent -.align 16 -bsaes_cbc_encrypt: -.cfi_startproc -___ -$code.=<<___ if ($win64); - mov 48(%rsp),$arg6 # pull direction flag -___ -$code.=<<___; - cmp \$0,$arg6 - jne aes_nohw_cbc_encrypt - cmp \$128,$arg3 - jb aes_nohw_cbc_encrypt - - mov %rsp, %rax -.Lcbc_dec_prologue: - push %rbp -.cfi_push %rbp - push %rbx -.cfi_push %rbx - push %r12 -.cfi_push %r12 - push %r13 -.cfi_push %r13 - push %r14 -.cfi_push %r14 - push %r15 -.cfi_push %r15 - lea -0x48(%rsp), %rsp -.cfi_adjust_cfa_offset 0x48 -___ -$code.=<<___ if ($win64); - mov 0xa0(%rsp),$arg5 # pull ivp - lea -0xa0(%rsp), %rsp - movaps %xmm6, 0x40(%rsp) - movaps %xmm7, 0x50(%rsp) - movaps %xmm8, 0x60(%rsp) - movaps %xmm9, 0x70(%rsp) - movaps %xmm10, 0x80(%rsp) - movaps %xmm11, 0x90(%rsp) - movaps %xmm12, 0xa0(%rsp) - movaps %xmm13, 0xb0(%rsp) - movaps %xmm14, 0xc0(%rsp) - movaps %xmm15, 0xd0(%rsp) -.Lcbc_dec_body: -___ -$code.=<<___; - mov %rsp, %rbp # backup %rsp -.cfi_def_cfa_register %rbp - mov 240($arg4), %eax # rounds - mov $arg1, $inp # backup arguments - mov $arg2, $out - mov $arg3, $len - mov $arg4, $key - mov $arg5, %rbx - shr \$4, $len # bytes to blocks - - mov %eax, %edx # rounds - shl \$7, %rax # 128 bytes per inner round key - sub \$`128-32`, %rax # size of bit-sliced key schedule - sub %rax, %rsp - - mov %rsp, %rax # pass key schedule - mov $key, %rcx # pass key - mov %edx, %r10d # pass rounds - call _bsaes_key_convert - pxor (%rsp),%xmm7 # fix up 0 round key - movdqa %xmm6,(%rax) # save last round key - movdqa %xmm7,(%rsp) - - movdqu (%rbx), @XMM[15] # load IV - sub \$8,$len -.Lcbc_dec_loop: - movdqu 0x00($inp), @XMM[0] # load input - movdqu 0x10($inp), @XMM[1] - movdqu 0x20($inp), @XMM[2] - movdqu 0x30($inp), @XMM[3] - movdqu 0x40($inp), @XMM[4] - movdqu 0x50($inp), @XMM[5] - mov %rsp, %rax # pass key schedule - movdqu 0x60($inp), @XMM[6] - mov %edx,%r10d # pass rounds - movdqu 0x70($inp), @XMM[7] - movdqa @XMM[15], 0x20(%rbp) # put aside IV - - call _bsaes_decrypt8 - - pxor 0x20(%rbp), @XMM[0] # ^= IV - movdqu 0x00($inp), @XMM[8] # re-load input - movdqu 0x10($inp), @XMM[9] - pxor @XMM[8], @XMM[1] - movdqu 0x20($inp), @XMM[10] - pxor @XMM[9], @XMM[6] - movdqu 0x30($inp), @XMM[11] - pxor @XMM[10], @XMM[4] - movdqu 0x40($inp), @XMM[12] - pxor @XMM[11], @XMM[2] - movdqu 0x50($inp), @XMM[13] - pxor @XMM[12], @XMM[7] - movdqu 0x60($inp), @XMM[14] - pxor @XMM[13], @XMM[3] - movdqu 0x70($inp), @XMM[15] # IV - pxor @XMM[14], @XMM[5] - movdqu @XMM[0], 0x00($out) # write output - lea 0x80($inp), $inp - movdqu @XMM[1], 0x10($out) - movdqu @XMM[6], 0x20($out) - movdqu @XMM[4], 0x30($out) - movdqu @XMM[2], 0x40($out) - movdqu @XMM[7], 0x50($out) - movdqu @XMM[3], 0x60($out) - movdqu @XMM[5], 0x70($out) - lea 0x80($out), $out - sub \$8,$len - jnc .Lcbc_dec_loop - - add \$8,$len - jz .Lcbc_dec_done - - movdqu 0x00($inp), @XMM[0] # load input - mov %rsp, %rax # pass key schedule - mov %edx, %r10d # pass rounds - cmp \$2,$len - jb .Lcbc_dec_one - movdqu 0x10($inp), @XMM[1] - je .Lcbc_dec_two - movdqu 0x20($inp), @XMM[2] - cmp \$4,$len - jb .Lcbc_dec_three - movdqu 0x30($inp), @XMM[3] - je .Lcbc_dec_four - movdqu 0x40($inp), @XMM[4] - cmp \$6,$len - jb .Lcbc_dec_five - movdqu 0x50($inp), @XMM[5] - je .Lcbc_dec_six - movdqu 0x60($inp), @XMM[6] - movdqa @XMM[15], 0x20(%rbp) # put aside IV - call _bsaes_decrypt8 - pxor 0x20(%rbp), @XMM[0] # ^= IV - movdqu 0x00($inp), @XMM[8] # re-load input - movdqu 0x10($inp), @XMM[9] - pxor @XMM[8], @XMM[1] - movdqu 0x20($inp), @XMM[10] - pxor @XMM[9], @XMM[6] - movdqu 0x30($inp), @XMM[11] - pxor @XMM[10], @XMM[4] - movdqu 0x40($inp), @XMM[12] - pxor @XMM[11], @XMM[2] - movdqu 0x50($inp), @XMM[13] - pxor @XMM[12], @XMM[7] - movdqu 0x60($inp), @XMM[15] # IV - pxor @XMM[13], @XMM[3] - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[6], 0x20($out) - movdqu @XMM[4], 0x30($out) - movdqu @XMM[2], 0x40($out) - movdqu @XMM[7], 0x50($out) - movdqu @XMM[3], 0x60($out) - jmp .Lcbc_dec_done -.align 16 -.Lcbc_dec_six: - movdqa @XMM[15], 0x20(%rbp) # put aside IV - call _bsaes_decrypt8 - pxor 0x20(%rbp), @XMM[0] # ^= IV - movdqu 0x00($inp), @XMM[8] # re-load input - movdqu 0x10($inp), @XMM[9] - pxor @XMM[8], @XMM[1] - movdqu 0x20($inp), @XMM[10] - pxor @XMM[9], @XMM[6] - movdqu 0x30($inp), @XMM[11] - pxor @XMM[10], @XMM[4] - movdqu 0x40($inp), @XMM[12] - pxor @XMM[11], @XMM[2] - movdqu 0x50($inp), @XMM[15] # IV - pxor @XMM[12], @XMM[7] - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[6], 0x20($out) - movdqu @XMM[4], 0x30($out) - movdqu @XMM[2], 0x40($out) - movdqu @XMM[7], 0x50($out) - jmp .Lcbc_dec_done -.align 16 -.Lcbc_dec_five: - movdqa @XMM[15], 0x20(%rbp) # put aside IV - call _bsaes_decrypt8 - pxor 0x20(%rbp), @XMM[0] # ^= IV - movdqu 0x00($inp), @XMM[8] # re-load input - movdqu 0x10($inp), @XMM[9] - pxor @XMM[8], @XMM[1] - movdqu 0x20($inp), @XMM[10] - pxor @XMM[9], @XMM[6] - movdqu 0x30($inp), @XMM[11] - pxor @XMM[10], @XMM[4] - movdqu 0x40($inp), @XMM[15] # IV - pxor @XMM[11], @XMM[2] - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[6], 0x20($out) - movdqu @XMM[4], 0x30($out) - movdqu @XMM[2], 0x40($out) - jmp .Lcbc_dec_done -.align 16 -.Lcbc_dec_four: - movdqa @XMM[15], 0x20(%rbp) # put aside IV - call _bsaes_decrypt8 - pxor 0x20(%rbp), @XMM[0] # ^= IV - movdqu 0x00($inp), @XMM[8] # re-load input - movdqu 0x10($inp), @XMM[9] - pxor @XMM[8], @XMM[1] - movdqu 0x20($inp), @XMM[10] - pxor @XMM[9], @XMM[6] - movdqu 0x30($inp), @XMM[15] # IV - pxor @XMM[10], @XMM[4] - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[6], 0x20($out) - movdqu @XMM[4], 0x30($out) - jmp .Lcbc_dec_done -.align 16 -.Lcbc_dec_three: - movdqa @XMM[15], 0x20(%rbp) # put aside IV - call _bsaes_decrypt8 - pxor 0x20(%rbp), @XMM[0] # ^= IV - movdqu 0x00($inp), @XMM[8] # re-load input - movdqu 0x10($inp), @XMM[9] - pxor @XMM[8], @XMM[1] - movdqu 0x20($inp), @XMM[15] # IV - pxor @XMM[9], @XMM[6] - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - movdqu @XMM[6], 0x20($out) - jmp .Lcbc_dec_done -.align 16 -.Lcbc_dec_two: - movdqa @XMM[15], 0x20(%rbp) # put aside IV - call _bsaes_decrypt8 - pxor 0x20(%rbp), @XMM[0] # ^= IV - movdqu 0x00($inp), @XMM[8] # re-load input - movdqu 0x10($inp), @XMM[15] # IV - pxor @XMM[8], @XMM[1] - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - jmp .Lcbc_dec_done -.align 16 -.Lcbc_dec_one: - lea ($inp), $arg1 - lea 0x20(%rbp), $arg2 # buffer output - lea ($key), $arg3 - call aes_nohw_decrypt # doesn't touch %xmm - pxor 0x20(%rbp), @XMM[15] # ^= IV - movdqu @XMM[15], ($out) # write output - movdqa @XMM[0], @XMM[15] # IV - -.Lcbc_dec_done: - movdqu @XMM[15], (%rbx) # return IV - lea (%rsp), %rax - pxor %xmm0, %xmm0 -.Lcbc_dec_bzero: # wipe key schedule [if any] - movdqa %xmm0, 0x00(%rax) - movdqa %xmm0, 0x10(%rax) - lea 0x20(%rax), %rax - cmp %rax, %rbp - ja .Lcbc_dec_bzero - - lea 0x78(%rbp),%rax -.cfi_def_cfa %rax,8 -___ -$code.=<<___ if ($win64); - movaps 0x40(%rbp), %xmm6 - movaps 0x50(%rbp), %xmm7 - movaps 0x60(%rbp), %xmm8 - movaps 0x70(%rbp), %xmm9 - movaps 0x80(%rbp), %xmm10 - movaps 0x90(%rbp), %xmm11 - movaps 0xa0(%rbp), %xmm12 - movaps 0xb0(%rbp), %xmm13 - movaps 0xc0(%rbp), %xmm14 - movaps 0xd0(%rbp), %xmm15 - lea 0xa0(%rax), %rax -.Lcbc_dec_tail: -___ -$code.=<<___; - mov -48(%rax), %r15 -.cfi_restore %r15 - mov -40(%rax), %r14 -.cfi_restore %r14 - mov -32(%rax), %r13 -.cfi_restore %r13 - mov -24(%rax), %r12 -.cfi_restore %r12 - mov -16(%rax), %rbx -.cfi_restore %rbx - mov -8(%rax), %rbp -.cfi_restore %rbp - lea (%rax), %rsp # restore %rsp -.cfi_def_cfa_register %rsp -.Lcbc_dec_epilogue: - ret -.cfi_endproc -.size bsaes_cbc_encrypt,.-bsaes_cbc_encrypt - -.globl bsaes_ctr32_encrypt_blocks -.type bsaes_ctr32_encrypt_blocks,\@abi-omnipotent -.align 16 -bsaes_ctr32_encrypt_blocks: -.cfi_startproc - mov %rsp, %rax -.Lctr_enc_prologue: - push %rbp -.cfi_push %rbp - push %rbx -.cfi_push %rbx - push %r12 -.cfi_push %r12 - push %r13 -.cfi_push %r13 - push %r14 -.cfi_push %r14 - push %r15 -.cfi_push %r15 - lea -0x48(%rsp), %rsp -.cfi_adjust_cfa_offset 0x48 -___ -$code.=<<___ if ($win64); - mov 0xa0(%rsp),$arg5 # pull ivp - lea -0xa0(%rsp), %rsp - movaps %xmm6, 0x40(%rsp) - movaps %xmm7, 0x50(%rsp) - movaps %xmm8, 0x60(%rsp) - movaps %xmm9, 0x70(%rsp) - movaps %xmm10, 0x80(%rsp) - movaps %xmm11, 0x90(%rsp) - movaps %xmm12, 0xa0(%rsp) - movaps %xmm13, 0xb0(%rsp) - movaps %xmm14, 0xc0(%rsp) - movaps %xmm15, 0xd0(%rsp) -.Lctr_enc_body: -___ -$code.=<<___; - mov %rsp, %rbp # backup %rsp -.cfi_def_cfa_register %rbp - movdqu ($arg5), %xmm0 # load counter - mov 240($arg4), %eax # rounds - mov $arg1, $inp # backup arguments - mov $arg2, $out - mov $arg3, $len - mov $arg4, $key - movdqa %xmm0, 0x20(%rbp) # copy counter - cmp \$8, $arg3 - jb .Lctr_enc_short - - mov %eax, %ebx # rounds - shl \$7, %rax # 128 bytes per inner round key - sub \$`128-32`, %rax # size of bit-sliced key schedule - sub %rax, %rsp - - mov %rsp, %rax # pass key schedule - mov $key, %rcx # pass key - mov %ebx, %r10d # pass rounds - call _bsaes_key_convert - pxor %xmm6,%xmm7 # fix up last round key - movdqa %xmm7,(%rax) # save last round key - - movdqa (%rsp), @XMM[9] # load round0 key - lea .LADD1(%rip), %r11 - movdqa 0x20(%rbp), @XMM[0] # counter copy - movdqa -0x20(%r11), @XMM[8] # .LSWPUP - pshufb @XMM[8], @XMM[9] # byte swap upper part - pshufb @XMM[8], @XMM[0] - movdqa @XMM[9], (%rsp) # save adjusted round0 key - jmp .Lctr_enc_loop -.align 16 -.Lctr_enc_loop: - movdqa @XMM[0], 0x20(%rbp) # save counter - movdqa @XMM[0], @XMM[1] # prepare 8 counter values - movdqa @XMM[0], @XMM[2] - paddd 0x00(%r11), @XMM[1] # .LADD1 - movdqa @XMM[0], @XMM[3] - paddd 0x10(%r11), @XMM[2] # .LADD2 - movdqa @XMM[0], @XMM[4] - paddd 0x20(%r11), @XMM[3] # .LADD3 - movdqa @XMM[0], @XMM[5] - paddd 0x30(%r11), @XMM[4] # .LADD4 - movdqa @XMM[0], @XMM[6] - paddd 0x40(%r11), @XMM[5] # .LADD5 - movdqa @XMM[0], @XMM[7] - paddd 0x50(%r11), @XMM[6] # .LADD6 - paddd 0x60(%r11), @XMM[7] # .LADD7 - - # Borrow prologue from _bsaes_encrypt8 to use the opportunity - # to flip byte order in 32-bit counter - movdqa (%rsp), @XMM[9] # round 0 key - lea 0x10(%rsp), %rax # pass key schedule - movdqa -0x10(%r11), @XMM[8] # .LSWPUPM0SR - pxor @XMM[9], @XMM[0] # xor with round0 key - pxor @XMM[9], @XMM[1] - pxor @XMM[9], @XMM[2] - pxor @XMM[9], @XMM[3] - pshufb @XMM[8], @XMM[0] - pshufb @XMM[8], @XMM[1] - pxor @XMM[9], @XMM[4] - pxor @XMM[9], @XMM[5] - pshufb @XMM[8], @XMM[2] - pshufb @XMM[8], @XMM[3] - pxor @XMM[9], @XMM[6] - pxor @XMM[9], @XMM[7] - pshufb @XMM[8], @XMM[4] - pshufb @XMM[8], @XMM[5] - pshufb @XMM[8], @XMM[6] - pshufb @XMM[8], @XMM[7] - lea .LBS0(%rip), %r11 # constants table - mov %ebx,%r10d # pass rounds - - call _bsaes_encrypt8_bitslice - - sub \$8,$len - jc .Lctr_enc_loop_done - - movdqu 0x00($inp), @XMM[8] # load input - movdqu 0x10($inp), @XMM[9] - movdqu 0x20($inp), @XMM[10] - movdqu 0x30($inp), @XMM[11] - movdqu 0x40($inp), @XMM[12] - movdqu 0x50($inp), @XMM[13] - movdqu 0x60($inp), @XMM[14] - movdqu 0x70($inp), @XMM[15] - lea 0x80($inp),$inp - pxor @XMM[0], @XMM[8] - movdqa 0x20(%rbp), @XMM[0] # load counter - pxor @XMM[9], @XMM[1] - movdqu @XMM[8], 0x00($out) # write output - pxor @XMM[10], @XMM[4] - movdqu @XMM[1], 0x10($out) - pxor @XMM[11], @XMM[6] - movdqu @XMM[4], 0x20($out) - pxor @XMM[12], @XMM[3] - movdqu @XMM[6], 0x30($out) - pxor @XMM[13], @XMM[7] - movdqu @XMM[3], 0x40($out) - pxor @XMM[14], @XMM[2] - movdqu @XMM[7], 0x50($out) - pxor @XMM[15], @XMM[5] - movdqu @XMM[2], 0x60($out) - lea .LADD1(%rip), %r11 - movdqu @XMM[5], 0x70($out) - lea 0x80($out), $out - paddd 0x70(%r11), @XMM[0] # .LADD8 - jnz .Lctr_enc_loop - - jmp .Lctr_enc_done -.align 16 -.Lctr_enc_loop_done: - add \$8, $len - movdqu 0x00($inp), @XMM[8] # load input - pxor @XMM[8], @XMM[0] - movdqu @XMM[0], 0x00($out) # write output - cmp \$2,$len - jb .Lctr_enc_done - movdqu 0x10($inp), @XMM[9] - pxor @XMM[9], @XMM[1] - movdqu @XMM[1], 0x10($out) - je .Lctr_enc_done - movdqu 0x20($inp), @XMM[10] - pxor @XMM[10], @XMM[4] - movdqu @XMM[4], 0x20($out) - cmp \$4,$len - jb .Lctr_enc_done - movdqu 0x30($inp), @XMM[11] - pxor @XMM[11], @XMM[6] - movdqu @XMM[6], 0x30($out) - je .Lctr_enc_done - movdqu 0x40($inp), @XMM[12] - pxor @XMM[12], @XMM[3] - movdqu @XMM[3], 0x40($out) - cmp \$6,$len - jb .Lctr_enc_done - movdqu 0x50($inp), @XMM[13] - pxor @XMM[13], @XMM[7] - movdqu @XMM[7], 0x50($out) - je .Lctr_enc_done - movdqu 0x60($inp), @XMM[14] - pxor @XMM[14], @XMM[2] - movdqu @XMM[2], 0x60($out) - jmp .Lctr_enc_done - -.align 16 -.Lctr_enc_short: - lea 0x20(%rbp), $arg1 - lea 0x30(%rbp), $arg2 - lea ($key), $arg3 - call aes_nohw_encrypt - movdqu ($inp), @XMM[1] - lea 16($inp), $inp - mov 0x2c(%rbp), %eax # load 32-bit counter - bswap %eax - pxor 0x30(%rbp), @XMM[1] - inc %eax # increment - movdqu @XMM[1], ($out) - bswap %eax - lea 16($out), $out - mov %eax, 0x2c(%rsp) # save 32-bit counter - dec $len - jnz .Lctr_enc_short - -.Lctr_enc_done: - lea (%rsp), %rax - pxor %xmm0, %xmm0 -.Lctr_enc_bzero: # wipe key schedule [if any] - movdqa %xmm0, 0x00(%rax) - movdqa %xmm0, 0x10(%rax) - lea 0x20(%rax), %rax - cmp %rax, %rbp - ja .Lctr_enc_bzero - - lea 0x78(%rbp),%rax -.cfi_def_cfa %rax,8 -___ -$code.=<<___ if ($win64); - movaps 0x40(%rbp), %xmm6 - movaps 0x50(%rbp), %xmm7 - movaps 0x60(%rbp), %xmm8 - movaps 0x70(%rbp), %xmm9 - movaps 0x80(%rbp), %xmm10 - movaps 0x90(%rbp), %xmm11 - movaps 0xa0(%rbp), %xmm12 - movaps 0xb0(%rbp), %xmm13 - movaps 0xc0(%rbp), %xmm14 - movaps 0xd0(%rbp), %xmm15 - lea 0xa0(%rax), %rax -.Lctr_enc_tail: -___ -$code.=<<___; - mov -48(%rax), %r15 -.cfi_restore %r15 - mov -40(%rax), %r14 -.cfi_restore %r14 - mov -32(%rax), %r13 -.cfi_restore %r13 - mov -24(%rax), %r12 -.cfi_restore %r12 - mov -16(%rax), %rbx -.cfi_restore %rbx - mov -8(%rax), %rbp -.cfi_restore %rbp - lea (%rax), %rsp # restore %rsp -.cfi_def_cfa_register %rsp -.Lctr_enc_epilogue: - ret -.cfi_endproc -.size bsaes_ctr32_encrypt_blocks,.-bsaes_ctr32_encrypt_blocks -___ -###################################################################### -# void bsaes_xts_[en|de]crypt(const char *inp,char *out,size_t len, -# const AES_KEY *key1, const AES_KEY *key2, -# const unsigned char iv[16]); -# -# We patch out the XTS implementation in BoringSSL. -if ($xts) { -my ($twmask,$twres,$twtmp)=@XMM[13..15]; -$arg6=~s/d$//; - -$code.=<<___; -.globl bsaes_xts_encrypt -.type bsaes_xts_encrypt,\@abi-omnipotent -.align 16 -bsaes_xts_encrypt: -.cfi_startproc - mov %rsp, %rax -.Lxts_enc_prologue: - push %rbp -.cfi_push %rbp - push %rbx -.cfi_push %rbx - push %r12 -.cfi_push %r12 - push %r13 -.cfi_push %r13 - push %r14 -.cfi_push %r14 - push %r15 -.cfi_push %r15 - lea -0x48(%rsp), %rsp -.cfi_adjust_cfa_offset 0x48 -___ -$code.=<<___ if ($win64); - mov 0xa0(%rsp),$arg5 # pull key2 - mov 0xa8(%rsp),$arg6 # pull ivp - lea -0xa0(%rsp), %rsp - movaps %xmm6, 0x40(%rsp) - movaps %xmm7, 0x50(%rsp) - movaps %xmm8, 0x60(%rsp) - movaps %xmm9, 0x70(%rsp) - movaps %xmm10, 0x80(%rsp) - movaps %xmm11, 0x90(%rsp) - movaps %xmm12, 0xa0(%rsp) - movaps %xmm13, 0xb0(%rsp) - movaps %xmm14, 0xc0(%rsp) - movaps %xmm15, 0xd0(%rsp) -.Lxts_enc_body: -___ -$code.=<<___; - mov %rsp, %rbp # backup %rsp -.cfi_def_cfa_register %rbp - mov $arg1, $inp # backup arguments - mov $arg2, $out - mov $arg3, $len - mov $arg4, $key - - lea ($arg6), $arg1 - lea 0x20(%rbp), $arg2 - lea ($arg5), $arg3 - call aes_nohw_encrypt # generate initial tweak - - mov 240($key), %eax # rounds - mov $len, %rbx # backup $len - - mov %eax, %edx # rounds - shl \$7, %rax # 128 bytes per inner round key - sub \$`128-32`, %rax # size of bit-sliced key schedule - sub %rax, %rsp - - mov %rsp, %rax # pass key schedule - mov $key, %rcx # pass key - mov %edx, %r10d # pass rounds - call _bsaes_key_convert - pxor %xmm6, %xmm7 # fix up last round key - movdqa %xmm7, (%rax) # save last round key - - and \$-16, $len - sub \$0x80, %rsp # place for tweak[8] - movdqa 0x20(%rbp), @XMM[7] # initial tweak - - pxor $twtmp, $twtmp - movdqa .Lxts_magic(%rip), $twmask - pcmpgtd @XMM[7], $twtmp # broadcast upper bits - - sub \$0x80, $len - jc .Lxts_enc_short - jmp .Lxts_enc_loop - -.align 16 -.Lxts_enc_loop: -___ - for ($i=0;$i<7;$i++) { - $code.=<<___; - pshufd \$0x13, $twtmp, $twres - pxor $twtmp, $twtmp - movdqa @XMM[7], @XMM[$i] - movdqa @XMM[7], `0x10*$i`(%rsp)# save tweak[$i] - paddq @XMM[7], @XMM[7] # psllq 1,$tweak - pand $twmask, $twres # isolate carry and residue - pcmpgtd @XMM[7], $twtmp # broadcast upper bits - pxor $twres, @XMM[7] -___ - $code.=<<___ if ($i>=1); - movdqu `0x10*($i-1)`($inp), @XMM[8+$i-1] -___ - $code.=<<___ if ($i>=2); - pxor @XMM[8+$i-2], @XMM[$i-2]# input[] ^ tweak[] -___ - } -$code.=<<___; - movdqu 0x60($inp), @XMM[8+6] - pxor @XMM[8+5], @XMM[5] - movdqu 0x70($inp), @XMM[8+7] - lea 0x80($inp), $inp - movdqa @XMM[7], 0x70(%rsp) - pxor @XMM[8+6], @XMM[6] - lea 0x80(%rsp), %rax # pass key schedule - pxor @XMM[8+7], @XMM[7] - mov %edx, %r10d # pass rounds - - call _bsaes_encrypt8 - - pxor 0x00(%rsp), @XMM[0] # ^= tweak[] - pxor 0x10(%rsp), @XMM[1] - movdqu @XMM[0], 0x00($out) # write output - pxor 0x20(%rsp), @XMM[4] - movdqu @XMM[1], 0x10($out) - pxor 0x30(%rsp), @XMM[6] - movdqu @XMM[4], 0x20($out) - pxor 0x40(%rsp), @XMM[3] - movdqu @XMM[6], 0x30($out) - pxor 0x50(%rsp), @XMM[7] - movdqu @XMM[3], 0x40($out) - pxor 0x60(%rsp), @XMM[2] - movdqu @XMM[7], 0x50($out) - pxor 0x70(%rsp), @XMM[5] - movdqu @XMM[2], 0x60($out) - movdqu @XMM[5], 0x70($out) - lea 0x80($out), $out - - movdqa 0x70(%rsp), @XMM[7] # prepare next iteration tweak - pxor $twtmp, $twtmp - movdqa .Lxts_magic(%rip), $twmask - pcmpgtd @XMM[7], $twtmp - pshufd \$0x13, $twtmp, $twres - pxor $twtmp, $twtmp - paddq @XMM[7], @XMM[7] # psllq 1,$tweak - pand $twmask, $twres # isolate carry and residue - pcmpgtd @XMM[7], $twtmp # broadcast upper bits - pxor $twres, @XMM[7] - - sub \$0x80,$len - jnc .Lxts_enc_loop - -.Lxts_enc_short: - add \$0x80, $len - jz .Lxts_enc_done -___ - for ($i=0;$i<7;$i++) { - $code.=<<___; - pshufd \$0x13, $twtmp, $twres - pxor $twtmp, $twtmp - movdqa @XMM[7], @XMM[$i] - movdqa @XMM[7], `0x10*$i`(%rsp)# save tweak[$i] - paddq @XMM[7], @XMM[7] # psllq 1,$tweak - pand $twmask, $twres # isolate carry and residue - pcmpgtd @XMM[7], $twtmp # broadcast upper bits - pxor $twres, @XMM[7] -___ - $code.=<<___ if ($i>=1); - movdqu `0x10*($i-1)`($inp), @XMM[8+$i-1] - cmp \$`0x10*$i`,$len - je .Lxts_enc_$i -___ - $code.=<<___ if ($i>=2); - pxor @XMM[8+$i-2], @XMM[$i-2]# input[] ^ tweak[] -___ - } -$code.=<<___; - movdqu 0x60($inp), @XMM[8+6] - pxor @XMM[8+5], @XMM[5] - movdqa @XMM[7], 0x70(%rsp) - lea 0x70($inp), $inp - pxor @XMM[8+6], @XMM[6] - lea 0x80(%rsp), %rax # pass key schedule - mov %edx, %r10d # pass rounds - - call _bsaes_encrypt8 - - pxor 0x00(%rsp), @XMM[0] # ^= tweak[] - pxor 0x10(%rsp), @XMM[1] - movdqu @XMM[0], 0x00($out) # write output - pxor 0x20(%rsp), @XMM[4] - movdqu @XMM[1], 0x10($out) - pxor 0x30(%rsp), @XMM[6] - movdqu @XMM[4], 0x20($out) - pxor 0x40(%rsp), @XMM[3] - movdqu @XMM[6], 0x30($out) - pxor 0x50(%rsp), @XMM[7] - movdqu @XMM[3], 0x40($out) - pxor 0x60(%rsp), @XMM[2] - movdqu @XMM[7], 0x50($out) - movdqu @XMM[2], 0x60($out) - lea 0x70($out), $out - - movdqa 0x70(%rsp), @XMM[7] # next iteration tweak - jmp .Lxts_enc_done -.align 16 -.Lxts_enc_6: - pxor @XMM[8+4], @XMM[4] - lea 0x60($inp), $inp - pxor @XMM[8+5], @XMM[5] - lea 0x80(%rsp), %rax # pass key schedule - mov %edx, %r10d # pass rounds - - call _bsaes_encrypt8 - - pxor 0x00(%rsp), @XMM[0] # ^= tweak[] - pxor 0x10(%rsp), @XMM[1] - movdqu @XMM[0], 0x00($out) # write output - pxor 0x20(%rsp), @XMM[4] - movdqu @XMM[1], 0x10($out) - pxor 0x30(%rsp), @XMM[6] - movdqu @XMM[4], 0x20($out) - pxor 0x40(%rsp), @XMM[3] - movdqu @XMM[6], 0x30($out) - pxor 0x50(%rsp), @XMM[7] - movdqu @XMM[3], 0x40($out) - movdqu @XMM[7], 0x50($out) - lea 0x60($out), $out - - movdqa 0x60(%rsp), @XMM[7] # next iteration tweak - jmp .Lxts_enc_done -.align 16 -.Lxts_enc_5: - pxor @XMM[8+3], @XMM[3] - lea 0x50($inp), $inp - pxor @XMM[8+4], @XMM[4] - lea 0x80(%rsp), %rax # pass key schedule - mov %edx, %r10d # pass rounds - - call _bsaes_encrypt8 - - pxor 0x00(%rsp), @XMM[0] # ^= tweak[] - pxor 0x10(%rsp), @XMM[1] - movdqu @XMM[0], 0x00($out) # write output - pxor 0x20(%rsp), @XMM[4] - movdqu @XMM[1], 0x10($out) - pxor 0x30(%rsp), @XMM[6] - movdqu @XMM[4], 0x20($out) - pxor 0x40(%rsp), @XMM[3] - movdqu @XMM[6], 0x30($out) - movdqu @XMM[3], 0x40($out) - lea 0x50($out), $out - - movdqa 0x50(%rsp), @XMM[7] # next iteration tweak - jmp .Lxts_enc_done -.align 16 -.Lxts_enc_4: - pxor @XMM[8+2], @XMM[2] - lea 0x40($inp), $inp - pxor @XMM[8+3], @XMM[3] - lea 0x80(%rsp), %rax # pass key schedule - mov %edx, %r10d # pass rounds - - call _bsaes_encrypt8 - - pxor 0x00(%rsp), @XMM[0] # ^= tweak[] - pxor 0x10(%rsp), @XMM[1] - movdqu @XMM[0], 0x00($out) # write output - pxor 0x20(%rsp), @XMM[4] - movdqu @XMM[1], 0x10($out) - pxor 0x30(%rsp), @XMM[6] - movdqu @XMM[4], 0x20($out) - movdqu @XMM[6], 0x30($out) - lea 0x40($out), $out - - movdqa 0x40(%rsp), @XMM[7] # next iteration tweak - jmp .Lxts_enc_done -.align 16 -.Lxts_enc_3: - pxor @XMM[8+1], @XMM[1] - lea 0x30($inp), $inp - pxor @XMM[8+2], @XMM[2] - lea 0x80(%rsp), %rax # pass key schedule - mov %edx, %r10d # pass rounds - - call _bsaes_encrypt8 - - pxor 0x00(%rsp), @XMM[0] # ^= tweak[] - pxor 0x10(%rsp), @XMM[1] - movdqu @XMM[0], 0x00($out) # write output - pxor 0x20(%rsp), @XMM[4] - movdqu @XMM[1], 0x10($out) - movdqu @XMM[4], 0x20($out) - lea 0x30($out), $out - - movdqa 0x30(%rsp), @XMM[7] # next iteration tweak - jmp .Lxts_enc_done -.align 16 -.Lxts_enc_2: - pxor @XMM[8+0], @XMM[0] - lea 0x20($inp), $inp - pxor @XMM[8+1], @XMM[1] - lea 0x80(%rsp), %rax # pass key schedule - mov %edx, %r10d # pass rounds - - call _bsaes_encrypt8 - - pxor 0x00(%rsp), @XMM[0] # ^= tweak[] - pxor 0x10(%rsp), @XMM[1] - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - lea 0x20($out), $out - - movdqa 0x20(%rsp), @XMM[7] # next iteration tweak - jmp .Lxts_enc_done -.align 16 -.Lxts_enc_1: - pxor @XMM[0], @XMM[8] - lea 0x10($inp), $inp - movdqa @XMM[8], 0x20(%rbp) - lea 0x20(%rbp), $arg1 - lea 0x20(%rbp), $arg2 - lea ($key), $arg3 - call aes_nohw_encrypt # doesn't touch %xmm - pxor 0x20(%rbp), @XMM[0] # ^= tweak[] - #pxor @XMM[8], @XMM[0] - #lea 0x80(%rsp), %rax # pass key schedule - #mov %edx, %r10d # pass rounds - #call _bsaes_encrypt8 - #pxor 0x00(%rsp), @XMM[0] # ^= tweak[] - movdqu @XMM[0], 0x00($out) # write output - lea 0x10($out), $out - - movdqa 0x10(%rsp), @XMM[7] # next iteration tweak - -.Lxts_enc_done: - and \$15, %ebx - jz .Lxts_enc_ret - mov $out, %rdx - -.Lxts_enc_steal: - movzb ($inp), %eax - movzb -16(%rdx), %ecx - lea 1($inp), $inp - mov %al, -16(%rdx) - mov %cl, 0(%rdx) - lea 1(%rdx), %rdx - sub \$1,%ebx - jnz .Lxts_enc_steal - - movdqu -16($out), @XMM[0] - lea 0x20(%rbp), $arg1 - pxor @XMM[7], @XMM[0] - lea 0x20(%rbp), $arg2 - movdqa @XMM[0], 0x20(%rbp) - lea ($key), $arg3 - call aes_nohw_encrypt # doesn't touch %xmm - pxor 0x20(%rbp), @XMM[7] - movdqu @XMM[7], -16($out) - -.Lxts_enc_ret: - lea (%rsp), %rax - pxor %xmm0, %xmm0 -.Lxts_enc_bzero: # wipe key schedule [if any] - movdqa %xmm0, 0x00(%rax) - movdqa %xmm0, 0x10(%rax) - lea 0x20(%rax), %rax - cmp %rax, %rbp - ja .Lxts_enc_bzero - - lea 0x78(%rbp),%rax -.cfi_def_cfa %rax,8 -___ -$code.=<<___ if ($win64); - movaps 0x40(%rbp), %xmm6 - movaps 0x50(%rbp), %xmm7 - movaps 0x60(%rbp), %xmm8 - movaps 0x70(%rbp), %xmm9 - movaps 0x80(%rbp), %xmm10 - movaps 0x90(%rbp), %xmm11 - movaps 0xa0(%rbp), %xmm12 - movaps 0xb0(%rbp), %xmm13 - movaps 0xc0(%rbp), %xmm14 - movaps 0xd0(%rbp), %xmm15 - lea 0xa0(%rax), %rax -.Lxts_enc_tail: -___ -$code.=<<___; - mov -48(%rax), %r15 -.cfi_restore %r15 - mov -40(%rax), %r14 -.cfi_restore %r14 - mov -32(%rax), %r13 -.cfi_restore %r13 - mov -24(%rax), %r12 -.cfi_restore %r12 - mov -16(%rax), %rbx -.cfi_restore %rbx - mov -8(%rax), %rbp -.cfi_restore %rbp - lea (%rax), %rsp # restore %rsp -.cfi_def_cfa_register %rsp -.Lxts_enc_epilogue: - ret -.cfi_endproc -.size bsaes_xts_encrypt,.-bsaes_xts_encrypt - -.globl bsaes_xts_decrypt -.type bsaes_xts_decrypt,\@abi-omnipotent -.align 16 -bsaes_xts_decrypt: -.cfi_startproc - mov %rsp, %rax -.Lxts_dec_prologue: - push %rbp -.cfi_push %rbp - push %rbx -.cfi_push %rbx - push %r12 -.cfi_push %r12 - push %r13 -.cfi_push %r13 - push %r14 -.cfi_push %r14 - push %r15 -.cfi_push %r15 - lea -0x48(%rsp), %rsp -.cfi_adjust_cfa_offset 0x48 -___ -$code.=<<___ if ($win64); - mov 0xa0(%rsp),$arg5 # pull key2 - mov 0xa8(%rsp),$arg6 # pull ivp - lea -0xa0(%rsp), %rsp - movaps %xmm6, 0x40(%rsp) - movaps %xmm7, 0x50(%rsp) - movaps %xmm8, 0x60(%rsp) - movaps %xmm9, 0x70(%rsp) - movaps %xmm10, 0x80(%rsp) - movaps %xmm11, 0x90(%rsp) - movaps %xmm12, 0xa0(%rsp) - movaps %xmm13, 0xb0(%rsp) - movaps %xmm14, 0xc0(%rsp) - movaps %xmm15, 0xd0(%rsp) -.Lxts_dec_body: -___ -$code.=<<___; - mov %rsp, %rbp # backup %rsp - mov $arg1, $inp # backup arguments - mov $arg2, $out - mov $arg3, $len - mov $arg4, $key - - lea ($arg6), $arg1 - lea 0x20(%rbp), $arg2 - lea ($arg5), $arg3 - call aes_nohw_encrypt # generate initial tweak - - mov 240($key), %eax # rounds - mov $len, %rbx # backup $len - - mov %eax, %edx # rounds - shl \$7, %rax # 128 bytes per inner round key - sub \$`128-32`, %rax # size of bit-sliced key schedule - sub %rax, %rsp - - mov %rsp, %rax # pass key schedule - mov $key, %rcx # pass key - mov %edx, %r10d # pass rounds - call _bsaes_key_convert - pxor (%rsp), %xmm7 # fix up round 0 key - movdqa %xmm6, (%rax) # save last round key - movdqa %xmm7, (%rsp) - - xor %eax, %eax # if ($len%16) len-=16; - and \$-16, $len - test \$15, %ebx - setnz %al - shl \$4, %rax - sub %rax, $len - - sub \$0x80, %rsp # place for tweak[8] - movdqa 0x20(%rbp), @XMM[7] # initial tweak - - pxor $twtmp, $twtmp - movdqa .Lxts_magic(%rip), $twmask - pcmpgtd @XMM[7], $twtmp # broadcast upper bits - - sub \$0x80, $len - jc .Lxts_dec_short - jmp .Lxts_dec_loop - -.align 16 -.Lxts_dec_loop: -___ - for ($i=0;$i<7;$i++) { - $code.=<<___; - pshufd \$0x13, $twtmp, $twres - pxor $twtmp, $twtmp - movdqa @XMM[7], @XMM[$i] - movdqa @XMM[7], `0x10*$i`(%rsp)# save tweak[$i] - paddq @XMM[7], @XMM[7] # psllq 1,$tweak - pand $twmask, $twres # isolate carry and residue - pcmpgtd @XMM[7], $twtmp # broadcast upper bits - pxor $twres, @XMM[7] -___ - $code.=<<___ if ($i>=1); - movdqu `0x10*($i-1)`($inp), @XMM[8+$i-1] -___ - $code.=<<___ if ($i>=2); - pxor @XMM[8+$i-2], @XMM[$i-2]# input[] ^ tweak[] -___ - } -$code.=<<___; - movdqu 0x60($inp), @XMM[8+6] - pxor @XMM[8+5], @XMM[5] - movdqu 0x70($inp), @XMM[8+7] - lea 0x80($inp), $inp - movdqa @XMM[7], 0x70(%rsp) - pxor @XMM[8+6], @XMM[6] - lea 0x80(%rsp), %rax # pass key schedule - pxor @XMM[8+7], @XMM[7] - mov %edx, %r10d # pass rounds - - call _bsaes_decrypt8 - - pxor 0x00(%rsp), @XMM[0] # ^= tweak[] - pxor 0x10(%rsp), @XMM[1] - movdqu @XMM[0], 0x00($out) # write output - pxor 0x20(%rsp), @XMM[6] - movdqu @XMM[1], 0x10($out) - pxor 0x30(%rsp), @XMM[4] - movdqu @XMM[6], 0x20($out) - pxor 0x40(%rsp), @XMM[2] - movdqu @XMM[4], 0x30($out) - pxor 0x50(%rsp), @XMM[7] - movdqu @XMM[2], 0x40($out) - pxor 0x60(%rsp), @XMM[3] - movdqu @XMM[7], 0x50($out) - pxor 0x70(%rsp), @XMM[5] - movdqu @XMM[3], 0x60($out) - movdqu @XMM[5], 0x70($out) - lea 0x80($out), $out - - movdqa 0x70(%rsp), @XMM[7] # prepare next iteration tweak - pxor $twtmp, $twtmp - movdqa .Lxts_magic(%rip), $twmask - pcmpgtd @XMM[7], $twtmp - pshufd \$0x13, $twtmp, $twres - pxor $twtmp, $twtmp - paddq @XMM[7], @XMM[7] # psllq 1,$tweak - pand $twmask, $twres # isolate carry and residue - pcmpgtd @XMM[7], $twtmp # broadcast upper bits - pxor $twres, @XMM[7] - - sub \$0x80,$len - jnc .Lxts_dec_loop - -.Lxts_dec_short: - add \$0x80, $len - jz .Lxts_dec_done -___ - for ($i=0;$i<7;$i++) { - $code.=<<___; - pshufd \$0x13, $twtmp, $twres - pxor $twtmp, $twtmp - movdqa @XMM[7], @XMM[$i] - movdqa @XMM[7], `0x10*$i`(%rsp)# save tweak[$i] - paddq @XMM[7], @XMM[7] # psllq 1,$tweak - pand $twmask, $twres # isolate carry and residue - pcmpgtd @XMM[7], $twtmp # broadcast upper bits - pxor $twres, @XMM[7] -___ - $code.=<<___ if ($i>=1); - movdqu `0x10*($i-1)`($inp), @XMM[8+$i-1] - cmp \$`0x10*$i`,$len - je .Lxts_dec_$i -___ - $code.=<<___ if ($i>=2); - pxor @XMM[8+$i-2], @XMM[$i-2]# input[] ^ tweak[] -___ - } -$code.=<<___; - movdqu 0x60($inp), @XMM[8+6] - pxor @XMM[8+5], @XMM[5] - movdqa @XMM[7], 0x70(%rsp) - lea 0x70($inp), $inp - pxor @XMM[8+6], @XMM[6] - lea 0x80(%rsp), %rax # pass key schedule - mov %edx, %r10d # pass rounds - - call _bsaes_decrypt8 - - pxor 0x00(%rsp), @XMM[0] # ^= tweak[] - pxor 0x10(%rsp), @XMM[1] - movdqu @XMM[0], 0x00($out) # write output - pxor 0x20(%rsp), @XMM[6] - movdqu @XMM[1], 0x10($out) - pxor 0x30(%rsp), @XMM[4] - movdqu @XMM[6], 0x20($out) - pxor 0x40(%rsp), @XMM[2] - movdqu @XMM[4], 0x30($out) - pxor 0x50(%rsp), @XMM[7] - movdqu @XMM[2], 0x40($out) - pxor 0x60(%rsp), @XMM[3] - movdqu @XMM[7], 0x50($out) - movdqu @XMM[3], 0x60($out) - lea 0x70($out), $out - - movdqa 0x70(%rsp), @XMM[7] # next iteration tweak - jmp .Lxts_dec_done -.align 16 -.Lxts_dec_6: - pxor @XMM[8+4], @XMM[4] - lea 0x60($inp), $inp - pxor @XMM[8+5], @XMM[5] - lea 0x80(%rsp), %rax # pass key schedule - mov %edx, %r10d # pass rounds - - call _bsaes_decrypt8 - - pxor 0x00(%rsp), @XMM[0] # ^= tweak[] - pxor 0x10(%rsp), @XMM[1] - movdqu @XMM[0], 0x00($out) # write output - pxor 0x20(%rsp), @XMM[6] - movdqu @XMM[1], 0x10($out) - pxor 0x30(%rsp), @XMM[4] - movdqu @XMM[6], 0x20($out) - pxor 0x40(%rsp), @XMM[2] - movdqu @XMM[4], 0x30($out) - pxor 0x50(%rsp), @XMM[7] - movdqu @XMM[2], 0x40($out) - movdqu @XMM[7], 0x50($out) - lea 0x60($out), $out - - movdqa 0x60(%rsp), @XMM[7] # next iteration tweak - jmp .Lxts_dec_done -.align 16 -.Lxts_dec_5: - pxor @XMM[8+3], @XMM[3] - lea 0x50($inp), $inp - pxor @XMM[8+4], @XMM[4] - lea 0x80(%rsp), %rax # pass key schedule - mov %edx, %r10d # pass rounds - - call _bsaes_decrypt8 - - pxor 0x00(%rsp), @XMM[0] # ^= tweak[] - pxor 0x10(%rsp), @XMM[1] - movdqu @XMM[0], 0x00($out) # write output - pxor 0x20(%rsp), @XMM[6] - movdqu @XMM[1], 0x10($out) - pxor 0x30(%rsp), @XMM[4] - movdqu @XMM[6], 0x20($out) - pxor 0x40(%rsp), @XMM[2] - movdqu @XMM[4], 0x30($out) - movdqu @XMM[2], 0x40($out) - lea 0x50($out), $out - - movdqa 0x50(%rsp), @XMM[7] # next iteration tweak - jmp .Lxts_dec_done -.align 16 -.Lxts_dec_4: - pxor @XMM[8+2], @XMM[2] - lea 0x40($inp), $inp - pxor @XMM[8+3], @XMM[3] - lea 0x80(%rsp), %rax # pass key schedule - mov %edx, %r10d # pass rounds - - call _bsaes_decrypt8 - - pxor 0x00(%rsp), @XMM[0] # ^= tweak[] - pxor 0x10(%rsp), @XMM[1] - movdqu @XMM[0], 0x00($out) # write output - pxor 0x20(%rsp), @XMM[6] - movdqu @XMM[1], 0x10($out) - pxor 0x30(%rsp), @XMM[4] - movdqu @XMM[6], 0x20($out) - movdqu @XMM[4], 0x30($out) - lea 0x40($out), $out - - movdqa 0x40(%rsp), @XMM[7] # next iteration tweak - jmp .Lxts_dec_done -.align 16 -.Lxts_dec_3: - pxor @XMM[8+1], @XMM[1] - lea 0x30($inp), $inp - pxor @XMM[8+2], @XMM[2] - lea 0x80(%rsp), %rax # pass key schedule - mov %edx, %r10d # pass rounds - - call _bsaes_decrypt8 - - pxor 0x00(%rsp), @XMM[0] # ^= tweak[] - pxor 0x10(%rsp), @XMM[1] - movdqu @XMM[0], 0x00($out) # write output - pxor 0x20(%rsp), @XMM[6] - movdqu @XMM[1], 0x10($out) - movdqu @XMM[6], 0x20($out) - lea 0x30($out), $out - - movdqa 0x30(%rsp), @XMM[7] # next iteration tweak - jmp .Lxts_dec_done -.align 16 -.Lxts_dec_2: - pxor @XMM[8+0], @XMM[0] - lea 0x20($inp), $inp - pxor @XMM[8+1], @XMM[1] - lea 0x80(%rsp), %rax # pass key schedule - mov %edx, %r10d # pass rounds - - call _bsaes_decrypt8 - - pxor 0x00(%rsp), @XMM[0] # ^= tweak[] - pxor 0x10(%rsp), @XMM[1] - movdqu @XMM[0], 0x00($out) # write output - movdqu @XMM[1], 0x10($out) - lea 0x20($out), $out - - movdqa 0x20(%rsp), @XMM[7] # next iteration tweak - jmp .Lxts_dec_done -.align 16 -.Lxts_dec_1: - pxor @XMM[0], @XMM[8] - lea 0x10($inp), $inp - movdqa @XMM[8], 0x20(%rbp) - lea 0x20(%rbp), $arg1 - lea 0x20(%rbp), $arg2 - lea ($key), $arg3 - call aes_nohw_decrypt # doesn't touch %xmm - pxor 0x20(%rbp), @XMM[0] # ^= tweak[] - #pxor @XMM[8], @XMM[0] - #lea 0x80(%rsp), %rax # pass key schedule - #mov %edx, %r10d # pass rounds - #call _bsaes_decrypt8 - #pxor 0x00(%rsp), @XMM[0] # ^= tweak[] - movdqu @XMM[0], 0x00($out) # write output - lea 0x10($out), $out - - movdqa 0x10(%rsp), @XMM[7] # next iteration tweak - -.Lxts_dec_done: - and \$15, %ebx - jz .Lxts_dec_ret - - pxor $twtmp, $twtmp - movdqa .Lxts_magic(%rip), $twmask - pcmpgtd @XMM[7], $twtmp - pshufd \$0x13, $twtmp, $twres - movdqa @XMM[7], @XMM[6] - paddq @XMM[7], @XMM[7] # psllq 1,$tweak - pand $twmask, $twres # isolate carry and residue - movdqu ($inp), @XMM[0] - pxor $twres, @XMM[7] - - lea 0x20(%rbp), $arg1 - pxor @XMM[7], @XMM[0] - lea 0x20(%rbp), $arg2 - movdqa @XMM[0], 0x20(%rbp) - lea ($key), $arg3 - call aes_nohw_decrypt # doesn't touch %xmm - pxor 0x20(%rbp), @XMM[7] - mov $out, %rdx - movdqu @XMM[7], ($out) - -.Lxts_dec_steal: - movzb 16($inp), %eax - movzb (%rdx), %ecx - lea 1($inp), $inp - mov %al, (%rdx) - mov %cl, 16(%rdx) - lea 1(%rdx), %rdx - sub \$1,%ebx - jnz .Lxts_dec_steal - - movdqu ($out), @XMM[0] - lea 0x20(%rbp), $arg1 - pxor @XMM[6], @XMM[0] - lea 0x20(%rbp), $arg2 - movdqa @XMM[0], 0x20(%rbp) - lea ($key), $arg3 - call aes_nohw_decrypt # doesn't touch %xmm - pxor 0x20(%rbp), @XMM[6] - movdqu @XMM[6], ($out) - -.Lxts_dec_ret: - lea (%rsp), %rax - pxor %xmm0, %xmm0 -.Lxts_dec_bzero: # wipe key schedule [if any] - movdqa %xmm0, 0x00(%rax) - movdqa %xmm0, 0x10(%rax) - lea 0x20(%rax), %rax - cmp %rax, %rbp - ja .Lxts_dec_bzero - - lea 0x78(%rbp),%rax -.cfi_def_cfa %rax,8 -___ -$code.=<<___ if ($win64); - movaps 0x40(%rbp), %xmm6 - movaps 0x50(%rbp), %xmm7 - movaps 0x60(%rbp), %xmm8 - movaps 0x70(%rbp), %xmm9 - movaps 0x80(%rbp), %xmm10 - movaps 0x90(%rbp), %xmm11 - movaps 0xa0(%rbp), %xmm12 - movaps 0xb0(%rbp), %xmm13 - movaps 0xc0(%rbp), %xmm14 - movaps 0xd0(%rbp), %xmm15 - lea 0xa0(%rax), %rax -.Lxts_dec_tail: -___ -$code.=<<___; - mov -48(%rax), %r15 -.cfi_restore %r15 - mov -40(%rax), %r14 -.cfi_restore %r14 - mov -32(%rax), %r13 -.cfi_restore %r13 - mov -24(%rax), %r12 -.cfi_restore %r12 - mov -16(%rax), %rbx -.cfi_restore %rbx - mov -8(%rax), %rbp -.cfi_restore %rbp - lea (%rax), %rsp # restore %rsp -.cfi_def_cfa_register %rsp -.Lxts_dec_epilogue: - ret -.cfi_endproc -.size bsaes_xts_decrypt,.-bsaes_xts_decrypt -___ -} -} # $xts -$code.=<<___; -.type _bsaes_const,\@object -.align 64 -_bsaes_const: -.LM0ISR: # InvShiftRows constants - .quad 0x0a0e0206070b0f03, 0x0004080c0d010509 -.LISRM0: - .quad 0x01040b0e0205080f, 0x0306090c00070a0d -.LISR: - .quad 0x0504070602010003, 0x0f0e0d0c080b0a09 -.LBS0: # bit-slice constants - .quad 0x5555555555555555, 0x5555555555555555 -.LBS1: - .quad 0x3333333333333333, 0x3333333333333333 -.LBS2: - .quad 0x0f0f0f0f0f0f0f0f, 0x0f0f0f0f0f0f0f0f -.LSR: # shiftrows constants - .quad 0x0504070600030201, 0x0f0e0d0c0a09080b -.LSRM0: - .quad 0x0304090e00050a0f, 0x01060b0c0207080d -.LM0SR: - .quad 0x0a0e02060f03070b, 0x0004080c05090d01 -.LSWPUP: # byte-swap upper dword - .quad 0x0706050403020100, 0x0c0d0e0f0b0a0908 -.LSWPUPM0SR: - .quad 0x0a0d02060c03070b, 0x0004080f05090e01 -.LADD1: # counter increment constants - .quad 0x0000000000000000, 0x0000000100000000 -.LADD2: - .quad 0x0000000000000000, 0x0000000200000000 -.LADD3: - .quad 0x0000000000000000, 0x0000000300000000 -.LADD4: - .quad 0x0000000000000000, 0x0000000400000000 -.LADD5: - .quad 0x0000000000000000, 0x0000000500000000 -.LADD6: - .quad 0x0000000000000000, 0x0000000600000000 -.LADD7: - .quad 0x0000000000000000, 0x0000000700000000 -.LADD8: - .quad 0x0000000000000000, 0x0000000800000000 -.Lxts_magic: - .long 0x87,0,1,0 -.Lmasks: - .quad 0x0101010101010101, 0x0101010101010101 - .quad 0x0202020202020202, 0x0202020202020202 - .quad 0x0404040404040404, 0x0404040404040404 - .quad 0x0808080808080808, 0x0808080808080808 -.LM0: - .quad 0x02060a0e03070b0f, 0x0004080c0105090d -.L63: - .quad 0x6363636363636363, 0x6363636363636363 -.asciz "Bit-sliced AES for x86_64/SSSE3, Emilia Käsper, Peter Schwabe, Andy Polyakov" -.align 64 -.size _bsaes_const,.-_bsaes_const -___ - -# EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame, -# CONTEXT *context,DISPATCHER_CONTEXT *disp) -if ($win64) { -$rec="%rcx"; -$frame="%rdx"; -$context="%r8"; -$disp="%r9"; - -$code.=<<___; -.extern __imp_RtlVirtualUnwind -.type se_handler,\@abi-omnipotent -.align 16 -se_handler: - push %rsi - push %rdi - push %rbx - push %rbp - push %r12 - push %r13 - push %r14 - push %r15 - pushfq - sub \$64,%rsp - - mov 120($context),%rax # pull context->Rax - mov 248($context),%rbx # pull context->Rip - - mov 8($disp),%rsi # disp->ImageBase - mov 56($disp),%r11 # disp->HandlerData - - mov 0(%r11),%r10d # HandlerData[0] - lea (%rsi,%r10),%r10 # prologue label - cmp %r10,%rbx # context->Rip<=prologue label - jbe .Lin_prologue - - mov 4(%r11),%r10d # HandlerData[1] - lea (%rsi,%r10),%r10 # epilogue label - cmp %r10,%rbx # context->Rip>=epilogue label - jae .Lin_prologue - - mov 8(%r11),%r10d # HandlerData[2] - lea (%rsi,%r10),%r10 # epilogue label - cmp %r10,%rbx # context->Rip>=tail label - jae .Lin_tail - - mov 160($context),%rax # pull context->Rbp - - lea 0x40(%rax),%rsi # %xmm save area - lea 512($context),%rdi # &context.Xmm6 - mov \$20,%ecx # 10*sizeof(%xmm0)/sizeof(%rax) - .long 0xa548f3fc # cld; rep movsq - lea 0xa0+0x78(%rax),%rax # adjust stack pointer - -.Lin_tail: - mov -48(%rax),%rbp - mov -40(%rax),%rbx - mov -32(%rax),%r12 - mov -24(%rax),%r13 - mov -16(%rax),%r14 - mov -8(%rax),%r15 - mov %rbx,144($context) # restore context->Rbx - mov %rbp,160($context) # restore context->Rbp - mov %r12,216($context) # restore context->R12 - mov %r13,224($context) # restore context->R13 - mov %r14,232($context) # restore context->R14 - mov %r15,240($context) # restore context->R15 - -.Lin_prologue: - mov %rax,152($context) # restore context->Rsp - - mov 40($disp),%rdi # disp->ContextRecord - mov $context,%rsi # context - mov \$`1232/8`,%ecx # sizeof(CONTEXT) - .long 0xa548f3fc # cld; rep movsq - - mov $disp,%rsi - xor %rcx,%rcx # arg1, UNW_FLAG_NHANDLER - mov 8(%rsi),%rdx # arg2, disp->ImageBase - mov 0(%rsi),%r8 # arg3, disp->ControlPc - mov 16(%rsi),%r9 # arg4, disp->FunctionEntry - mov 40(%rsi),%r10 # disp->ContextRecord - lea 56(%rsi),%r11 # &disp->HandlerData - lea 24(%rsi),%r12 # &disp->EstablisherFrame - mov %r10,32(%rsp) # arg5 - mov %r11,40(%rsp) # arg6 - mov %r12,48(%rsp) # arg7 - mov %rcx,56(%rsp) # arg8, (NULL) - call *__imp_RtlVirtualUnwind(%rip) - - mov \$1,%eax # ExceptionContinueSearch - add \$64,%rsp - popfq - pop %r15 - pop %r14 - pop %r13 - pop %r12 - pop %rbp - pop %rbx - pop %rdi - pop %rsi - ret -.size se_handler,.-se_handler - -.section .pdata -.align 4 -___ -$code.=<<___ if ($ecb); - .rva .Lecb_enc_prologue - .rva .Lecb_enc_epilogue - .rva .Lecb_enc_info - - .rva .Lecb_dec_prologue - .rva .Lecb_dec_epilogue - .rva .Lecb_dec_info -___ -$code.=<<___; - .rva .Lcbc_dec_prologue - .rva .Lcbc_dec_epilogue - .rva .Lcbc_dec_info - - .rva .Lctr_enc_prologue - .rva .Lctr_enc_epilogue - .rva .Lctr_enc_info -___ -$code.=<<___ if ($xts); - .rva .Lxts_enc_prologue - .rva .Lxts_enc_epilogue - .rva .Lxts_enc_info - - .rva .Lxts_dec_prologue - .rva .Lxts_dec_epilogue - .rva .Lxts_dec_info -___ -$code.=<<___; - -.section .xdata -.align 8 -___ -$code.=<<___ if ($ecb); -.Lecb_enc_info: - .byte 9,0,0,0 - .rva se_handler - .rva .Lecb_enc_body,.Lecb_enc_epilogue # HandlerData[] - .rva .Lecb_enc_tail - .long 0 -.Lecb_dec_info: - .byte 9,0,0,0 - .rva se_handler - .rva .Lecb_dec_body,.Lecb_dec_epilogue # HandlerData[] - .rva .Lecb_dec_tail - .long 0 -___ -$code.=<<___; -.Lcbc_dec_info: - .byte 9,0,0,0 - .rva se_handler - .rva .Lcbc_dec_body,.Lcbc_dec_epilogue # HandlerData[] - .rva .Lcbc_dec_tail - .long 0 -.Lctr_enc_info: - .byte 9,0,0,0 - .rva se_handler - .rva .Lctr_enc_body,.Lctr_enc_epilogue # HandlerData[] - .rva .Lctr_enc_tail - .long 0 -___ -$code.=<<___ if ($xts); -.Lxts_enc_info: - .byte 9,0,0,0 - .rva se_handler - .rva .Lxts_enc_body,.Lxts_enc_epilogue # HandlerData[] - .rva .Lxts_enc_tail - .long 0 -.Lxts_dec_info: - .byte 9,0,0,0 - .rva se_handler - .rva .Lxts_dec_body,.Lxts_dec_epilogue # HandlerData[] - .rva .Lxts_dec_tail - .long 0 -___ -} - -$code =~ s/\`([^\`]*)\`/eval($1)/gem; - -print $code; - -close STDOUT; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/vpaes-armv8.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/vpaes-armv8.pl new file mode 100755 index 00000000..bae5e7e9 --- /dev/null +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/vpaes-armv8.pl @@ -0,0 +1,1362 @@ +#! /usr/bin/env perl +# Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. +# +# Licensed under the OpenSSL license (the "License"). You may not use +# this file except in compliance with the License. You can obtain a copy +# in the file LICENSE in the source distribution or at +# https://www.openssl.org/source/license.html + + +###################################################################### +## Constant-time SSSE3 AES core implementation. +## version 0.1 +## +## By Mike Hamburg (Stanford University), 2009 +## Public domain. +## +## For details see http://shiftleft.org/papers/vector_aes/ and +## http://crypto.stanford.edu/vpaes/. +## +###################################################################### +# ARMv8 NEON adaptation by +# +# Reason for undertaken effort is that there is at least one popular +# SoC based on Cortex-A53 that doesn't have crypto extensions. +# +# CBC enc ECB enc/dec(*) [bit-sliced enc/dec] +# Cortex-A53 21.5 18.1/20.6 [17.5/19.8 ] +# Cortex-A57 36.0(**) 20.4/24.9(**) [14.4/16.6 ] +# X-Gene 45.9(**) 45.8/57.7(**) [33.1/37.6(**) ] +# Denver(***) 16.6(**) 15.1/17.8(**) [8.80/9.93 ] +# Apple A7(***) 22.7(**) 10.9/14.3 [8.45/10.0 ] +# Mongoose(***) 26.3(**) 21.0/25.0(**) [13.3/16.8 ] +# +# (*) ECB denotes approximate result for parallelizable modes +# such as CBC decrypt, CTR, etc.; +# (**) these results are worse than scalar compiler-generated +# code, but it's constant-time and therefore preferred; +# (***) presented for reference/comparison purposes; + +$flavour = shift; +while (($output=shift) && ($output!~/\w[\w\-]*\.\w+$/)) {} + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; +( $xlate="${dir}arm-xlate.pl" and -f $xlate ) or +( $xlate="${dir}../../../perlasm/arm-xlate.pl" and -f $xlate) or +die "can't locate arm-xlate.pl"; + +open OUT,"| \"$^X\" $xlate $flavour $output"; +*STDOUT=*OUT; + +$code.=<<___; +.section .rodata + +.type _vpaes_consts,%object +.align 7 // totally strategic alignment +_vpaes_consts: +.Lk_mc_forward: // mc_forward + .quad 0x0407060500030201, 0x0C0F0E0D080B0A09 + .quad 0x080B0A0904070605, 0x000302010C0F0E0D + .quad 0x0C0F0E0D080B0A09, 0x0407060500030201 + .quad 0x000302010C0F0E0D, 0x080B0A0904070605 +.Lk_mc_backward:// mc_backward + .quad 0x0605040702010003, 0x0E0D0C0F0A09080B + .quad 0x020100030E0D0C0F, 0x0A09080B06050407 + .quad 0x0E0D0C0F0A09080B, 0x0605040702010003 + .quad 0x0A09080B06050407, 0x020100030E0D0C0F +.Lk_sr: // sr + .quad 0x0706050403020100, 0x0F0E0D0C0B0A0908 + .quad 0x030E09040F0A0500, 0x0B06010C07020D08 + .quad 0x0F060D040B020900, 0x070E050C030A0108 + .quad 0x0B0E0104070A0D00, 0x0306090C0F020508 + +// +// "Hot" constants +// +.Lk_inv: // inv, inva + .quad 0x0E05060F0D080180, 0x040703090A0B0C02 + .quad 0x01040A060F0B0780, 0x030D0E0C02050809 +.Lk_ipt: // input transform (lo, hi) + .quad 0xC2B2E8985A2A7000, 0xCABAE09052227808 + .quad 0x4C01307D317C4D00, 0xCD80B1FCB0FDCC81 +.Lk_sbo: // sbou, sbot + .quad 0xD0D26D176FBDC700, 0x15AABF7AC502A878 + .quad 0xCFE474A55FBB6A00, 0x8E1E90D1412B35FA +.Lk_sb1: // sb1u, sb1t + .quad 0x3618D415FAE22300, 0x3BF7CCC10D2ED9EF + .quad 0xB19BE18FCB503E00, 0xA5DF7A6E142AF544 +.Lk_sb2: // sb2u, sb2t + .quad 0x69EB88400AE12900, 0xC2A163C8AB82234A + .quad 0xE27A93C60B712400, 0x5EB7E955BC982FCD + +// +// Decryption stuff +// +.Lk_dipt: // decryption input transform + .quad 0x0F505B040B545F00, 0x154A411E114E451A + .quad 0x86E383E660056500, 0x12771772F491F194 +.Lk_dsbo: // decryption sbox final output + .quad 0x1387EA537EF94000, 0xC7AA6DB9D4943E2D + .quad 0x12D7560F93441D00, 0xCA4B8159D8C58E9C +.Lk_dsb9: // decryption sbox output *9*u, *9*t + .quad 0x851C03539A86D600, 0xCAD51F504F994CC9 + .quad 0xC03B1789ECD74900, 0x725E2C9EB2FBA565 +.Lk_dsbd: // decryption sbox output *D*u, *D*t + .quad 0x7D57CCDFE6B1A200, 0xF56E9B13882A4439 + .quad 0x3CE2FAF724C6CB00, 0x2931180D15DEEFD3 +.Lk_dsbb: // decryption sbox output *B*u, *B*t + .quad 0xD022649296B44200, 0x602646F6B0F2D404 + .quad 0xC19498A6CD596700, 0xF3FF0C3E3255AA6B +.Lk_dsbe: // decryption sbox output *E*u, *E*t + .quad 0x46F2929626D4D000, 0x2242600464B4F6B0 + .quad 0x0C55A6CDFFAAC100, 0x9467F36B98593E32 + +// +// Key schedule constants +// +.Lk_dksd: // decryption key schedule: invskew x*D + .quad 0xFEB91A5DA3E44700, 0x0740E3A45A1DBEF9 + .quad 0x41C277F4B5368300, 0x5FDC69EAAB289D1E +.Lk_dksb: // decryption key schedule: invskew x*B + .quad 0x9A4FCA1F8550D500, 0x03D653861CC94C99 + .quad 0x115BEDA7B6FC4A00, 0xD993256F7E3482C8 +.Lk_dkse: // decryption key schedule: invskew x*E + 0x63 + .quad 0xD5031CCA1FC9D600, 0x53859A4C994F5086 + .quad 0xA23196054FDC7BE8, 0xCD5EF96A20B31487 +.Lk_dks9: // decryption key schedule: invskew x*9 + .quad 0xB6116FC87ED9A700, 0x4AED933482255BFC + .quad 0x4576516227143300, 0x8BB89FACE9DAFDCE + +.Lk_rcon: // rcon + .quad 0x1F8391B9AF9DEEB6, 0x702A98084D7C7D81 + +.Lk_opt: // output transform + .quad 0xFF9F4929D6B66000, 0xF7974121DEBE6808 + .quad 0x01EDBD5150BCEC00, 0xE10D5DB1B05C0CE0 +.Lk_deskew: // deskew tables: inverts the sbox's "skew" + .quad 0x07E4A34047A4E300, 0x1DFEB95A5DBEF91A + .quad 0x5F36B5DC83EA6900, 0x2841C2ABF49D1E77 + +.asciz "Vector Permutation AES for ARMv8, Mike Hamburg (Stanford University)" +.size _vpaes_consts,.-_vpaes_consts +.align 6 + +.text +___ + +{ +my ($inp,$out,$key) = map("x$_",(0..2)); + +my ($invlo,$invhi,$iptlo,$ipthi,$sbou,$sbot) = map("v$_.16b",(18..23)); +my ($sb1u,$sb1t,$sb2u,$sb2t) = map("v$_.16b",(24..27)); +my ($sb9u,$sb9t,$sbdu,$sbdt,$sbbu,$sbbt,$sbeu,$sbet)=map("v$_.16b",(24..31)); + +$code.=<<___; +## +## _aes_preheat +## +## Fills register %r10 -> .aes_consts (so you can -fPIC) +## and %xmm9-%xmm15 as specified below. +## +.type _vpaes_encrypt_preheat,%function +.align 4 +_vpaes_encrypt_preheat: + adrp x10, :pg_hi21:.Lk_inv + add x10, x10, :lo12:.Lk_inv + movi v17.16b, #0x0f + ld1 {v18.2d-v19.2d}, [x10],#32 // .Lk_inv + ld1 {v20.2d-v23.2d}, [x10],#64 // .Lk_ipt, .Lk_sbo + ld1 {v24.2d-v27.2d}, [x10] // .Lk_sb1, .Lk_sb2 + ret +.size _vpaes_encrypt_preheat,.-_vpaes_encrypt_preheat + +## +## _aes_encrypt_core +## +## AES-encrypt %xmm0. +## +## Inputs: +## %xmm0 = input +## %xmm9-%xmm15 as in _vpaes_preheat +## (%rdx) = scheduled keys +## +## Output in %xmm0 +## Clobbers %xmm1-%xmm5, %r9, %r10, %r11, %rax +## Preserves %xmm6 - %xmm8 so you get some local vectors +## +## +.type _vpaes_encrypt_core,%function +.align 4 +_vpaes_encrypt_core: + mov x9, $key + ldr w8, [$key,#240] // pull rounds + adrp x11, :pg_hi21:.Lk_mc_forward+16 + add x11, x11, :lo12:.Lk_mc_forward+16 + // vmovdqa .Lk_ipt(%rip), %xmm2 # iptlo + ld1 {v16.2d}, [x9], #16 // vmovdqu (%r9), %xmm5 # round0 key + and v1.16b, v7.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 + ushr v0.16b, v7.16b, #4 // vpsrlb \$4, %xmm0, %xmm0 + tbl v1.16b, {$iptlo}, v1.16b // vpshufb %xmm1, %xmm2, %xmm1 + // vmovdqa .Lk_ipt+16(%rip), %xmm3 # ipthi + tbl v2.16b, {$ipthi}, v0.16b // vpshufb %xmm0, %xmm3, %xmm2 + eor v0.16b, v1.16b, v16.16b // vpxor %xmm5, %xmm1, %xmm0 + eor v0.16b, v0.16b, v2.16b // vpxor %xmm2, %xmm0, %xmm0 + b .Lenc_entry + +.align 4 +.Lenc_loop: + // middle of middle round + add x10, x11, #0x40 + tbl v4.16b, {$sb1t}, v2.16b // vpshufb %xmm2, %xmm13, %xmm4 # 4 = sb1u + ld1 {v1.2d}, [x11], #16 // vmovdqa -0x40(%r11,%r10), %xmm1 # .Lk_mc_forward[] + tbl v0.16b, {$sb1u}, v3.16b // vpshufb %xmm3, %xmm12, %xmm0 # 0 = sb1t + eor v4.16b, v4.16b, v16.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = sb1u + k + tbl v5.16b, {$sb2t}, v2.16b // vpshufb %xmm2, %xmm15, %xmm5 # 4 = sb2u + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = A + tbl v2.16b, {$sb2u}, v3.16b // vpshufb %xmm3, %xmm14, %xmm2 # 2 = sb2t + ld1 {v4.2d}, [x10] // vmovdqa (%r11,%r10), %xmm4 # .Lk_mc_backward[] + tbl v3.16b, {v0.16b}, v1.16b // vpshufb %xmm1, %xmm0, %xmm3 # 0 = B + eor v2.16b, v2.16b, v5.16b // vpxor %xmm5, %xmm2, %xmm2 # 2 = 2A + tbl v0.16b, {v0.16b}, v4.16b // vpshufb %xmm4, %xmm0, %xmm0 # 3 = D + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 # 0 = 2A+B + tbl v4.16b, {v3.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm4 # 0 = 2B+C + eor v0.16b, v0.16b, v3.16b // vpxor %xmm3, %xmm0, %xmm0 # 3 = 2A+B+D + and x11, x11, #~(1<<6) // and \$0x30, %r11 # ... mod 4 + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = 2A+3B+C+D + sub w8, w8, #1 // nr-- + +.Lenc_entry: + // top of round + and v1.16b, v0.16b, v17.16b // vpand %xmm0, %xmm9, %xmm1 # 0 = k + ushr v0.16b, v0.16b, #4 // vpsrlb \$4, %xmm0, %xmm0 # 1 = i + tbl v5.16b, {$invhi}, v1.16b // vpshufb %xmm1, %xmm11, %xmm5 # 2 = a/k + eor v1.16b, v1.16b, v0.16b // vpxor %xmm0, %xmm1, %xmm1 # 0 = j + tbl v3.16b, {$invlo}, v0.16b // vpshufb %xmm0, %xmm10, %xmm3 # 3 = 1/i + tbl v4.16b, {$invlo}, v1.16b // vpshufb %xmm1, %xmm10, %xmm4 # 4 = 1/j + eor v3.16b, v3.16b, v5.16b // vpxor %xmm5, %xmm3, %xmm3 # 3 = iak = 1/i + a/k + eor v4.16b, v4.16b, v5.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = jak = 1/j + a/k + tbl v2.16b, {$invlo}, v3.16b // vpshufb %xmm3, %xmm10, %xmm2 # 2 = 1/iak + tbl v3.16b, {$invlo}, v4.16b // vpshufb %xmm4, %xmm10, %xmm3 # 3 = 1/jak + eor v2.16b, v2.16b, v1.16b // vpxor %xmm1, %xmm2, %xmm2 # 2 = io + eor v3.16b, v3.16b, v0.16b // vpxor %xmm0, %xmm3, %xmm3 # 3 = jo + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm5 + cbnz w8, .Lenc_loop + + // middle of last round + add x10, x11, #0x80 + // vmovdqa -0x60(%r10), %xmm4 # 3 : sbou .Lk_sbo + // vmovdqa -0x50(%r10), %xmm0 # 0 : sbot .Lk_sbo+16 + tbl v4.16b, {$sbou}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbou + ld1 {v1.2d}, [x10] // vmovdqa 0x40(%r11,%r10), %xmm1 # .Lk_sr[] + tbl v0.16b, {$sbot}, v3.16b // vpshufb %xmm3, %xmm0, %xmm0 # 0 = sb1t + eor v4.16b, v4.16b, v16.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = sb1u + k + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = A + tbl v0.16b, {v0.16b}, v1.16b // vpshufb %xmm1, %xmm0, %xmm0 + ret +.size _vpaes_encrypt_core,.-_vpaes_encrypt_core + +.globl vpaes_encrypt +.type vpaes_encrypt,%function +.align 4 +vpaes_encrypt: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + + ld1 {v7.16b}, [$inp] + bl _vpaes_encrypt_preheat + bl _vpaes_encrypt_core + st1 {v0.16b}, [$out] + + ldp x29,x30,[sp],#16 + ret +.size vpaes_encrypt,.-vpaes_encrypt + +.type _vpaes_encrypt_2x,%function +.align 4 +_vpaes_encrypt_2x: + mov x9, $key + ldr w8, [$key,#240] // pull rounds + adrp x11, :pg_hi21:.Lk_mc_forward+16 + add x11, x11, :lo12:.Lk_mc_forward+16 + // vmovdqa .Lk_ipt(%rip), %xmm2 # iptlo + ld1 {v16.2d}, [x9], #16 // vmovdqu (%r9), %xmm5 # round0 key + and v1.16b, v14.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 + ushr v0.16b, v14.16b, #4 // vpsrlb \$4, %xmm0, %xmm0 + and v9.16b, v15.16b, v17.16b + ushr v8.16b, v15.16b, #4 + tbl v1.16b, {$iptlo}, v1.16b // vpshufb %xmm1, %xmm2, %xmm1 + tbl v9.16b, {$iptlo}, v9.16b + // vmovdqa .Lk_ipt+16(%rip), %xmm3 # ipthi + tbl v2.16b, {$ipthi}, v0.16b // vpshufb %xmm0, %xmm3, %xmm2 + tbl v10.16b, {$ipthi}, v8.16b + eor v0.16b, v1.16b, v16.16b // vpxor %xmm5, %xmm1, %xmm0 + eor v8.16b, v9.16b, v16.16b + eor v0.16b, v0.16b, v2.16b // vpxor %xmm2, %xmm0, %xmm0 + eor v8.16b, v8.16b, v10.16b + b .Lenc_2x_entry + +.align 4 +.Lenc_2x_loop: + // middle of middle round + add x10, x11, #0x40 + tbl v4.16b, {$sb1t}, v2.16b // vpshufb %xmm2, %xmm13, %xmm4 # 4 = sb1u + tbl v12.16b, {$sb1t}, v10.16b + ld1 {v1.2d}, [x11], #16 // vmovdqa -0x40(%r11,%r10), %xmm1 # .Lk_mc_forward[] + tbl v0.16b, {$sb1u}, v3.16b // vpshufb %xmm3, %xmm12, %xmm0 # 0 = sb1t + tbl v8.16b, {$sb1u}, v11.16b + eor v4.16b, v4.16b, v16.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = sb1u + k + eor v12.16b, v12.16b, v16.16b + tbl v5.16b, {$sb2t}, v2.16b // vpshufb %xmm2, %xmm15, %xmm5 # 4 = sb2u + tbl v13.16b, {$sb2t}, v10.16b + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = A + eor v8.16b, v8.16b, v12.16b + tbl v2.16b, {$sb2u}, v3.16b // vpshufb %xmm3, %xmm14, %xmm2 # 2 = sb2t + tbl v10.16b, {$sb2u}, v11.16b + ld1 {v4.2d}, [x10] // vmovdqa (%r11,%r10), %xmm4 # .Lk_mc_backward[] + tbl v3.16b, {v0.16b}, v1.16b // vpshufb %xmm1, %xmm0, %xmm3 # 0 = B + tbl v11.16b, {v8.16b}, v1.16b + eor v2.16b, v2.16b, v5.16b // vpxor %xmm5, %xmm2, %xmm2 # 2 = 2A + eor v10.16b, v10.16b, v13.16b + tbl v0.16b, {v0.16b}, v4.16b // vpshufb %xmm4, %xmm0, %xmm0 # 3 = D + tbl v8.16b, {v8.16b}, v4.16b + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 # 0 = 2A+B + eor v11.16b, v11.16b, v10.16b + tbl v4.16b, {v3.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm4 # 0 = 2B+C + tbl v12.16b, {v11.16b},v1.16b + eor v0.16b, v0.16b, v3.16b // vpxor %xmm3, %xmm0, %xmm0 # 3 = 2A+B+D + eor v8.16b, v8.16b, v11.16b + and x11, x11, #~(1<<6) // and \$0x30, %r11 # ... mod 4 + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = 2A+3B+C+D + eor v8.16b, v8.16b, v12.16b + sub w8, w8, #1 // nr-- + +.Lenc_2x_entry: + // top of round + and v1.16b, v0.16b, v17.16b // vpand %xmm0, %xmm9, %xmm1 # 0 = k + ushr v0.16b, v0.16b, #4 // vpsrlb \$4, %xmm0, %xmm0 # 1 = i + and v9.16b, v8.16b, v17.16b + ushr v8.16b, v8.16b, #4 + tbl v5.16b, {$invhi},v1.16b // vpshufb %xmm1, %xmm11, %xmm5 # 2 = a/k + tbl v13.16b, {$invhi},v9.16b + eor v1.16b, v1.16b, v0.16b // vpxor %xmm0, %xmm1, %xmm1 # 0 = j + eor v9.16b, v9.16b, v8.16b + tbl v3.16b, {$invlo},v0.16b // vpshufb %xmm0, %xmm10, %xmm3 # 3 = 1/i + tbl v11.16b, {$invlo},v8.16b + tbl v4.16b, {$invlo},v1.16b // vpshufb %xmm1, %xmm10, %xmm4 # 4 = 1/j + tbl v12.16b, {$invlo},v9.16b + eor v3.16b, v3.16b, v5.16b // vpxor %xmm5, %xmm3, %xmm3 # 3 = iak = 1/i + a/k + eor v11.16b, v11.16b, v13.16b + eor v4.16b, v4.16b, v5.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = jak = 1/j + a/k + eor v12.16b, v12.16b, v13.16b + tbl v2.16b, {$invlo},v3.16b // vpshufb %xmm3, %xmm10, %xmm2 # 2 = 1/iak + tbl v10.16b, {$invlo},v11.16b + tbl v3.16b, {$invlo},v4.16b // vpshufb %xmm4, %xmm10, %xmm3 # 3 = 1/jak + tbl v11.16b, {$invlo},v12.16b + eor v2.16b, v2.16b, v1.16b // vpxor %xmm1, %xmm2, %xmm2 # 2 = io + eor v10.16b, v10.16b, v9.16b + eor v3.16b, v3.16b, v0.16b // vpxor %xmm0, %xmm3, %xmm3 # 3 = jo + eor v11.16b, v11.16b, v8.16b + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm5 + cbnz w8, .Lenc_2x_loop + + // middle of last round + add x10, x11, #0x80 + // vmovdqa -0x60(%r10), %xmm4 # 3 : sbou .Lk_sbo + // vmovdqa -0x50(%r10), %xmm0 # 0 : sbot .Lk_sbo+16 + tbl v4.16b, {$sbou}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbou + tbl v12.16b, {$sbou}, v10.16b + ld1 {v1.2d}, [x10] // vmovdqa 0x40(%r11,%r10), %xmm1 # .Lk_sr[] + tbl v0.16b, {$sbot}, v3.16b // vpshufb %xmm3, %xmm0, %xmm0 # 0 = sb1t + tbl v8.16b, {$sbot}, v11.16b + eor v4.16b, v4.16b, v16.16b // vpxor %xmm5, %xmm4, %xmm4 # 4 = sb1u + k + eor v12.16b, v12.16b, v16.16b + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 0 = A + eor v8.16b, v8.16b, v12.16b + tbl v0.16b, {v0.16b},v1.16b // vpshufb %xmm1, %xmm0, %xmm0 + tbl v1.16b, {v8.16b},v1.16b + ret +.size _vpaes_encrypt_2x,.-_vpaes_encrypt_2x + +.type _vpaes_decrypt_preheat,%function +.align 4 +_vpaes_decrypt_preheat: + adrp x10, :pg_hi21:.Lk_inv + add x10, x10, :lo12:.Lk_inv + movi v17.16b, #0x0f + adrp x11, :pg_hi21:.Lk_dipt + add x11, x11, :lo12:.Lk_dipt + ld1 {v18.2d-v19.2d}, [x10],#32 // .Lk_inv + ld1 {v20.2d-v23.2d}, [x11],#64 // .Lk_dipt, .Lk_dsbo + ld1 {v24.2d-v27.2d}, [x11],#64 // .Lk_dsb9, .Lk_dsbd + ld1 {v28.2d-v31.2d}, [x11] // .Lk_dsbb, .Lk_dsbe + ret +.size _vpaes_decrypt_preheat,.-_vpaes_decrypt_preheat + +## +## Decryption core +## +## Same API as encryption core. +## +.type _vpaes_decrypt_core,%function +.align 4 +_vpaes_decrypt_core: + mov x9, $key + ldr w8, [$key,#240] // pull rounds + + // vmovdqa .Lk_dipt(%rip), %xmm2 # iptlo + lsl x11, x8, #4 // mov %rax, %r11; shl \$4, %r11 + eor x11, x11, #0x30 // xor \$0x30, %r11 + adrp x10, :pg_hi21:.Lk_sr + add x10, x10, :lo12:.Lk_sr + and x11, x11, #0x30 // and \$0x30, %r11 + add x11, x11, x10 + adrp x10, :pg_hi21:.Lk_mc_forward+48 + add x10, x10, :lo12:.Lk_mc_forward+48 + + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm4 # round0 key + and v1.16b, v7.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 + ushr v0.16b, v7.16b, #4 // vpsrlb \$4, %xmm0, %xmm0 + tbl v2.16b, {$iptlo}, v1.16b // vpshufb %xmm1, %xmm2, %xmm2 + ld1 {v5.2d}, [x10] // vmovdqa .Lk_mc_forward+48(%rip), %xmm5 + // vmovdqa .Lk_dipt+16(%rip), %xmm1 # ipthi + tbl v0.16b, {$ipthi}, v0.16b // vpshufb %xmm0, %xmm1, %xmm0 + eor v2.16b, v2.16b, v16.16b // vpxor %xmm4, %xmm2, %xmm2 + eor v0.16b, v0.16b, v2.16b // vpxor %xmm2, %xmm0, %xmm0 + b .Ldec_entry + +.align 4 +.Ldec_loop: +// +// Inverse mix columns +// + // vmovdqa -0x20(%r10),%xmm4 # 4 : sb9u + // vmovdqa -0x10(%r10),%xmm1 # 0 : sb9t + tbl v4.16b, {$sb9u}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sb9u + tbl v1.16b, {$sb9t}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sb9t + eor v0.16b, v4.16b, v16.16b // vpxor %xmm4, %xmm0, %xmm0 + // vmovdqa 0x00(%r10),%xmm4 # 4 : sbdu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + // vmovdqa 0x10(%r10),%xmm1 # 0 : sbdt + + tbl v4.16b, {$sbdu}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbdu + tbl v0.16b, {v0.16b}, v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v1.16b, {$sbdt}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbdt + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + // vmovdqa 0x20(%r10), %xmm4 # 4 : sbbu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + // vmovdqa 0x30(%r10), %xmm1 # 0 : sbbt + + tbl v4.16b, {$sbbu}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbbu + tbl v0.16b, {v0.16b}, v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v1.16b, {$sbbt}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbbt + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + // vmovdqa 0x40(%r10), %xmm4 # 4 : sbeu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + // vmovdqa 0x50(%r10), %xmm1 # 0 : sbet + + tbl v4.16b, {$sbeu}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbeu + tbl v0.16b, {v0.16b}, v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v1.16b, {$sbet}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbet + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + ext v5.16b, v5.16b, v5.16b, #12 // vpalignr \$12, %xmm5, %xmm5, %xmm5 + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + sub w8, w8, #1 // sub \$1,%rax # nr-- + +.Ldec_entry: + // top of round + and v1.16b, v0.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 # 0 = k + ushr v0.16b, v0.16b, #4 // vpsrlb \$4, %xmm0, %xmm0 # 1 = i + tbl v2.16b, {$invhi}, v1.16b // vpshufb %xmm1, %xmm11, %xmm2 # 2 = a/k + eor v1.16b, v1.16b, v0.16b // vpxor %xmm0, %xmm1, %xmm1 # 0 = j + tbl v3.16b, {$invlo}, v0.16b // vpshufb %xmm0, %xmm10, %xmm3 # 3 = 1/i + tbl v4.16b, {$invlo}, v1.16b // vpshufb %xmm1, %xmm10, %xmm4 # 4 = 1/j + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 # 3 = iak = 1/i + a/k + eor v4.16b, v4.16b, v2.16b // vpxor %xmm2, %xmm4, %xmm4 # 4 = jak = 1/j + a/k + tbl v2.16b, {$invlo}, v3.16b // vpshufb %xmm3, %xmm10, %xmm2 # 2 = 1/iak + tbl v3.16b, {$invlo}, v4.16b // vpshufb %xmm4, %xmm10, %xmm3 # 3 = 1/jak + eor v2.16b, v2.16b, v1.16b // vpxor %xmm1, %xmm2, %xmm2 # 2 = io + eor v3.16b, v3.16b, v0.16b // vpxor %xmm0, %xmm3, %xmm3 # 3 = jo + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm0 + cbnz w8, .Ldec_loop + + // middle of last round + // vmovdqa 0x60(%r10), %xmm4 # 3 : sbou + tbl v4.16b, {$sbou}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbou + // vmovdqa 0x70(%r10), %xmm1 # 0 : sbot + ld1 {v2.2d}, [x11] // vmovdqa -0x160(%r11), %xmm2 # .Lk_sr-.Lk_dsbd=-0x160 + tbl v1.16b, {$sbot}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sb1t + eor v4.16b, v4.16b, v16.16b // vpxor %xmm0, %xmm4, %xmm4 # 4 = sb1u + k + eor v0.16b, v1.16b, v4.16b // vpxor %xmm4, %xmm1, %xmm0 # 0 = A + tbl v0.16b, {v0.16b}, v2.16b // vpshufb %xmm2, %xmm0, %xmm0 + ret +.size _vpaes_decrypt_core,.-_vpaes_decrypt_core + +.globl vpaes_decrypt +.type vpaes_decrypt,%function +.align 4 +vpaes_decrypt: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + + ld1 {v7.16b}, [$inp] + bl _vpaes_decrypt_preheat + bl _vpaes_decrypt_core + st1 {v0.16b}, [$out] + + ldp x29,x30,[sp],#16 + ret +.size vpaes_decrypt,.-vpaes_decrypt + +// v14-v15 input, v0-v1 output +.type _vpaes_decrypt_2x,%function +.align 4 +_vpaes_decrypt_2x: + mov x9, $key + ldr w8, [$key,#240] // pull rounds + + // vmovdqa .Lk_dipt(%rip), %xmm2 # iptlo + lsl x11, x8, #4 // mov %rax, %r11; shl \$4, %r11 + eor x11, x11, #0x30 // xor \$0x30, %r11 + adrp x10, :pg_hi21:.Lk_sr + add x10, x10, :lo12:.Lk_sr + and x11, x11, #0x30 // and \$0x30, %r11 + add x11, x11, x10 + adrp x10, :pg_hi21:.Lk_mc_forward+48 + add x10, x10, :lo12:.Lk_mc_forward+48 + + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm4 # round0 key + and v1.16b, v14.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 + ushr v0.16b, v14.16b, #4 // vpsrlb \$4, %xmm0, %xmm0 + and v9.16b, v15.16b, v17.16b + ushr v8.16b, v15.16b, #4 + tbl v2.16b, {$iptlo},v1.16b // vpshufb %xmm1, %xmm2, %xmm2 + tbl v10.16b, {$iptlo},v9.16b + ld1 {v5.2d}, [x10] // vmovdqa .Lk_mc_forward+48(%rip), %xmm5 + // vmovdqa .Lk_dipt+16(%rip), %xmm1 # ipthi + tbl v0.16b, {$ipthi},v0.16b // vpshufb %xmm0, %xmm1, %xmm0 + tbl v8.16b, {$ipthi},v8.16b + eor v2.16b, v2.16b, v16.16b // vpxor %xmm4, %xmm2, %xmm2 + eor v10.16b, v10.16b, v16.16b + eor v0.16b, v0.16b, v2.16b // vpxor %xmm2, %xmm0, %xmm0 + eor v8.16b, v8.16b, v10.16b + b .Ldec_2x_entry + +.align 4 +.Ldec_2x_loop: +// +// Inverse mix columns +// + // vmovdqa -0x20(%r10),%xmm4 # 4 : sb9u + // vmovdqa -0x10(%r10),%xmm1 # 0 : sb9t + tbl v4.16b, {$sb9u}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sb9u + tbl v12.16b, {$sb9u}, v10.16b + tbl v1.16b, {$sb9t}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sb9t + tbl v9.16b, {$sb9t}, v11.16b + eor v0.16b, v4.16b, v16.16b // vpxor %xmm4, %xmm0, %xmm0 + eor v8.16b, v12.16b, v16.16b + // vmovdqa 0x00(%r10),%xmm4 # 4 : sbdu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + eor v8.16b, v8.16b, v9.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + // vmovdqa 0x10(%r10),%xmm1 # 0 : sbdt + + tbl v4.16b, {$sbdu}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbdu + tbl v12.16b, {$sbdu}, v10.16b + tbl v0.16b, {v0.16b},v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v8.16b, {v8.16b},v5.16b + tbl v1.16b, {$sbdt}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbdt + tbl v9.16b, {$sbdt}, v11.16b + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + eor v8.16b, v8.16b, v12.16b + // vmovdqa 0x20(%r10), %xmm4 # 4 : sbbu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + eor v8.16b, v8.16b, v9.16b + // vmovdqa 0x30(%r10), %xmm1 # 0 : sbbt + + tbl v4.16b, {$sbbu}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbbu + tbl v12.16b, {$sbbu}, v10.16b + tbl v0.16b, {v0.16b},v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v8.16b, {v8.16b},v5.16b + tbl v1.16b, {$sbbt}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbbt + tbl v9.16b, {$sbbt}, v11.16b + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + eor v8.16b, v8.16b, v12.16b + // vmovdqa 0x40(%r10), %xmm4 # 4 : sbeu + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + eor v8.16b, v8.16b, v9.16b + // vmovdqa 0x50(%r10), %xmm1 # 0 : sbet + + tbl v4.16b, {$sbeu}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbeu + tbl v12.16b, {$sbeu}, v10.16b + tbl v0.16b, {v0.16b},v5.16b // vpshufb %xmm5, %xmm0, %xmm0 # MC ch + tbl v8.16b, {v8.16b},v5.16b + tbl v1.16b, {$sbet}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sbet + tbl v9.16b, {$sbet}, v11.16b + eor v0.16b, v0.16b, v4.16b // vpxor %xmm4, %xmm0, %xmm0 # 4 = ch + eor v8.16b, v8.16b, v12.16b + ext v5.16b, v5.16b, v5.16b, #12 // vpalignr \$12, %xmm5, %xmm5, %xmm5 + eor v0.16b, v0.16b, v1.16b // vpxor %xmm1, %xmm0, %xmm0 # 0 = ch + eor v8.16b, v8.16b, v9.16b + sub w8, w8, #1 // sub \$1,%rax # nr-- + +.Ldec_2x_entry: + // top of round + and v1.16b, v0.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 # 0 = k + ushr v0.16b, v0.16b, #4 // vpsrlb \$4, %xmm0, %xmm0 # 1 = i + and v9.16b, v8.16b, v17.16b + ushr v8.16b, v8.16b, #4 + tbl v2.16b, {$invhi},v1.16b // vpshufb %xmm1, %xmm11, %xmm2 # 2 = a/k + tbl v10.16b, {$invhi},v9.16b + eor v1.16b, v1.16b, v0.16b // vpxor %xmm0, %xmm1, %xmm1 # 0 = j + eor v9.16b, v9.16b, v8.16b + tbl v3.16b, {$invlo},v0.16b // vpshufb %xmm0, %xmm10, %xmm3 # 3 = 1/i + tbl v11.16b, {$invlo},v8.16b + tbl v4.16b, {$invlo},v1.16b // vpshufb %xmm1, %xmm10, %xmm4 # 4 = 1/j + tbl v12.16b, {$invlo},v9.16b + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 # 3 = iak = 1/i + a/k + eor v11.16b, v11.16b, v10.16b + eor v4.16b, v4.16b, v2.16b // vpxor %xmm2, %xmm4, %xmm4 # 4 = jak = 1/j + a/k + eor v12.16b, v12.16b, v10.16b + tbl v2.16b, {$invlo},v3.16b // vpshufb %xmm3, %xmm10, %xmm2 # 2 = 1/iak + tbl v10.16b, {$invlo},v11.16b + tbl v3.16b, {$invlo},v4.16b // vpshufb %xmm4, %xmm10, %xmm3 # 3 = 1/jak + tbl v11.16b, {$invlo},v12.16b + eor v2.16b, v2.16b, v1.16b // vpxor %xmm1, %xmm2, %xmm2 # 2 = io + eor v10.16b, v10.16b, v9.16b + eor v3.16b, v3.16b, v0.16b // vpxor %xmm0, %xmm3, %xmm3 # 3 = jo + eor v11.16b, v11.16b, v8.16b + ld1 {v16.2d}, [x9],#16 // vmovdqu (%r9), %xmm0 + cbnz w8, .Ldec_2x_loop + + // middle of last round + // vmovdqa 0x60(%r10), %xmm4 # 3 : sbou + tbl v4.16b, {$sbou}, v2.16b // vpshufb %xmm2, %xmm4, %xmm4 # 4 = sbou + tbl v12.16b, {$sbou}, v10.16b + // vmovdqa 0x70(%r10), %xmm1 # 0 : sbot + tbl v1.16b, {$sbot}, v3.16b // vpshufb %xmm3, %xmm1, %xmm1 # 0 = sb1t + tbl v9.16b, {$sbot}, v11.16b + ld1 {v2.2d}, [x11] // vmovdqa -0x160(%r11), %xmm2 # .Lk_sr-.Lk_dsbd=-0x160 + eor v4.16b, v4.16b, v16.16b // vpxor %xmm0, %xmm4, %xmm4 # 4 = sb1u + k + eor v12.16b, v12.16b, v16.16b + eor v0.16b, v1.16b, v4.16b // vpxor %xmm4, %xmm1, %xmm0 # 0 = A + eor v8.16b, v9.16b, v12.16b + tbl v0.16b, {v0.16b},v2.16b // vpshufb %xmm2, %xmm0, %xmm0 + tbl v1.16b, {v8.16b},v2.16b + ret +.size _vpaes_decrypt_2x,.-_vpaes_decrypt_2x +___ +} +{ +my ($inp,$bits,$out,$dir)=("x0","w1","x2","w3"); +my ($invlo,$invhi,$iptlo,$ipthi,$rcon) = map("v$_.16b",(18..21,8)); + +$code.=<<___; +######################################################## +## ## +## AES key schedule ## +## ## +######################################################## +.type _vpaes_key_preheat,%function +.align 4 +_vpaes_key_preheat: + adrp x10, :pg_hi21:.Lk_inv + add x10, x10, :lo12:.Lk_inv + movi v16.16b, #0x5b // .Lk_s63 + adrp x11, :pg_hi21:.Lk_sb1 + add x11, x11, :lo12:.Lk_sb1 + movi v17.16b, #0x0f // .Lk_s0F + ld1 {v18.2d-v21.2d}, [x10] // .Lk_inv, .Lk_ipt + adrp x10, :pg_hi21:.Lk_dksd + add x10, x10, :lo12:.Lk_dksd + ld1 {v22.2d-v23.2d}, [x11] // .Lk_sb1 + adrp x11, :pg_hi21:.Lk_mc_forward + add x11, x11, :lo12:.Lk_mc_forward + ld1 {v24.2d-v27.2d}, [x10],#64 // .Lk_dksd, .Lk_dksb + ld1 {v28.2d-v31.2d}, [x10],#64 // .Lk_dkse, .Lk_dks9 + ld1 {v8.2d}, [x10] // .Lk_rcon + ld1 {v9.2d}, [x11] // .Lk_mc_forward[0] + ret +.size _vpaes_key_preheat,.-_vpaes_key_preheat + +.type _vpaes_schedule_core,%function +.align 4 +_vpaes_schedule_core: + stp x29, x30, [sp,#-16]! + add x29,sp,#0 + + bl _vpaes_key_preheat // load the tables + + ld1 {v0.16b}, [$inp],#16 // vmovdqu (%rdi), %xmm0 # load key (unaligned) + + // input transform + mov v3.16b, v0.16b // vmovdqa %xmm0, %xmm3 + bl _vpaes_schedule_transform + mov v7.16b, v0.16b // vmovdqa %xmm0, %xmm7 + + adrp x10, :pg_hi21:.Lk_sr // lea .Lk_sr(%rip),%r10 + add x10, x10, :lo12:.Lk_sr + + add x8, x8, x10 + cbnz $dir, .Lschedule_am_decrypting + + // encrypting, output zeroth round key after transform + st1 {v0.2d}, [$out] // vmovdqu %xmm0, (%rdx) + b .Lschedule_go + +.Lschedule_am_decrypting: + // decrypting, output zeroth round key after shiftrows + ld1 {v1.2d}, [x8] // vmovdqa (%r8,%r10), %xmm1 + tbl v3.16b, {v3.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm3 + st1 {v3.2d}, [$out] // vmovdqu %xmm3, (%rdx) + eor x8, x8, #0x30 // xor \$0x30, %r8 + +.Lschedule_go: + cmp $bits, #192 // cmp \$192, %esi + b.hi .Lschedule_256 + b.eq .Lschedule_192 + // 128: fall though + +## +## .schedule_128 +## +## 128-bit specific part of key schedule. +## +## This schedule is really simple, because all its parts +## are accomplished by the subroutines. +## +.Lschedule_128: + mov $inp, #10 // mov \$10, %esi + +.Loop_schedule_128: + sub $inp, $inp, #1 // dec %esi + bl _vpaes_schedule_round + cbz $inp, .Lschedule_mangle_last + bl _vpaes_schedule_mangle // write output + b .Loop_schedule_128 + +## +## .aes_schedule_192 +## +## 192-bit specific part of key schedule. +## +## The main body of this schedule is the same as the 128-bit +## schedule, but with more smearing. The long, high side is +## stored in %xmm7 as before, and the short, low side is in +## the high bits of %xmm6. +## +## This schedule is somewhat nastier, however, because each +## round produces 192 bits of key material, or 1.5 round keys. +## Therefore, on each cycle we do 2 rounds and produce 3 round +## keys. +## +.align 4 +.Lschedule_192: + sub $inp, $inp, #8 + ld1 {v0.16b}, [$inp] // vmovdqu 8(%rdi),%xmm0 # load key part 2 (very unaligned) + bl _vpaes_schedule_transform // input transform + mov v6.16b, v0.16b // vmovdqa %xmm0, %xmm6 # save short part + eor v4.16b, v4.16b, v4.16b // vpxor %xmm4, %xmm4, %xmm4 # clear 4 + ins v6.d[0], v4.d[0] // vmovhlps %xmm4, %xmm6, %xmm6 # clobber low side with zeros + mov $inp, #4 // mov \$4, %esi + +.Loop_schedule_192: + sub $inp, $inp, #1 // dec %esi + bl _vpaes_schedule_round + ext v0.16b, v6.16b, v0.16b, #8 // vpalignr \$8,%xmm6,%xmm0,%xmm0 + bl _vpaes_schedule_mangle // save key n + bl _vpaes_schedule_192_smear + bl _vpaes_schedule_mangle // save key n+1 + bl _vpaes_schedule_round + cbz $inp, .Lschedule_mangle_last + bl _vpaes_schedule_mangle // save key n+2 + bl _vpaes_schedule_192_smear + b .Loop_schedule_192 + +## +## .aes_schedule_256 +## +## 256-bit specific part of key schedule. +## +## The structure here is very similar to the 128-bit +## schedule, but with an additional "low side" in +## %xmm6. The low side's rounds are the same as the +## high side's, except no rcon and no rotation. +## +.align 4 +.Lschedule_256: + ld1 {v0.16b}, [$inp] // vmovdqu 16(%rdi),%xmm0 # load key part 2 (unaligned) + bl _vpaes_schedule_transform // input transform + mov $inp, #7 // mov \$7, %esi + +.Loop_schedule_256: + sub $inp, $inp, #1 // dec %esi + bl _vpaes_schedule_mangle // output low result + mov v6.16b, v0.16b // vmovdqa %xmm0, %xmm6 # save cur_lo in xmm6 + + // high round + bl _vpaes_schedule_round + cbz $inp, .Lschedule_mangle_last + bl _vpaes_schedule_mangle + + // low round. swap xmm7 and xmm6 + dup v0.4s, v0.s[3] // vpshufd \$0xFF, %xmm0, %xmm0 + movi v4.16b, #0 + mov v5.16b, v7.16b // vmovdqa %xmm7, %xmm5 + mov v7.16b, v6.16b // vmovdqa %xmm6, %xmm7 + bl _vpaes_schedule_low_round + mov v7.16b, v5.16b // vmovdqa %xmm5, %xmm7 + + b .Loop_schedule_256 + +## +## .aes_schedule_mangle_last +## +## Mangler for last round of key schedule +## Mangles %xmm0 +## when encrypting, outputs out(%xmm0) ^ 63 +## when decrypting, outputs unskew(%xmm0) +## +## Always called right before return... jumps to cleanup and exits +## +.align 4 +.Lschedule_mangle_last: + // schedule last round key from xmm0 + adrp x11, :pg_hi21:.Lk_deskew // lea .Lk_deskew(%rip),%r11 # prepare to deskew + add x11, x11, :lo12:.Lk_deskew + + cbnz $dir, .Lschedule_mangle_last_dec + + // encrypting + ld1 {v1.2d}, [x8] // vmovdqa (%r8,%r10),%xmm1 + adrp x11, :pg_hi21:.Lk_opt // lea .Lk_opt(%rip), %r11 # prepare to output transform + add x11, x11, :lo12:.Lk_opt + add $out, $out, #32 // add \$32, %rdx + tbl v0.16b, {v0.16b}, v1.16b // vpshufb %xmm1, %xmm0, %xmm0 # output permute + +.Lschedule_mangle_last_dec: + ld1 {v20.2d-v21.2d}, [x11] // reload constants + sub $out, $out, #16 // add \$-16, %rdx + eor v0.16b, v0.16b, v16.16b // vpxor .Lk_s63(%rip), %xmm0, %xmm0 + bl _vpaes_schedule_transform // output transform + st1 {v0.2d}, [$out] // vmovdqu %xmm0, (%rdx) # save last key + + // cleanup + eor v0.16b, v0.16b, v0.16b // vpxor %xmm0, %xmm0, %xmm0 + eor v1.16b, v1.16b, v1.16b // vpxor %xmm1, %xmm1, %xmm1 + eor v2.16b, v2.16b, v2.16b // vpxor %xmm2, %xmm2, %xmm2 + eor v3.16b, v3.16b, v3.16b // vpxor %xmm3, %xmm3, %xmm3 + eor v4.16b, v4.16b, v4.16b // vpxor %xmm4, %xmm4, %xmm4 + eor v5.16b, v5.16b, v5.16b // vpxor %xmm5, %xmm5, %xmm5 + eor v6.16b, v6.16b, v6.16b // vpxor %xmm6, %xmm6, %xmm6 + eor v7.16b, v7.16b, v7.16b // vpxor %xmm7, %xmm7, %xmm7 + ldp x29, x30, [sp],#16 + ret +.size _vpaes_schedule_core,.-_vpaes_schedule_core + +## +## .aes_schedule_192_smear +## +## Smear the short, low side in the 192-bit key schedule. +## +## Inputs: +## %xmm7: high side, b a x y +## %xmm6: low side, d c 0 0 +## %xmm13: 0 +## +## Outputs: +## %xmm6: b+c+d b+c 0 0 +## %xmm0: b+c+d b+c b a +## +.type _vpaes_schedule_192_smear,%function +.align 4 +_vpaes_schedule_192_smear: + movi v1.16b, #0 + dup v0.4s, v7.s[3] + ins v1.s[3], v6.s[2] // vpshufd \$0x80, %xmm6, %xmm1 # d c 0 0 -> c 0 0 0 + ins v0.s[0], v7.s[2] // vpshufd \$0xFE, %xmm7, %xmm0 # b a _ _ -> b b b a + eor v6.16b, v6.16b, v1.16b // vpxor %xmm1, %xmm6, %xmm6 # -> c+d c 0 0 + eor v1.16b, v1.16b, v1.16b // vpxor %xmm1, %xmm1, %xmm1 + eor v6.16b, v6.16b, v0.16b // vpxor %xmm0, %xmm6, %xmm6 # -> b+c+d b+c b a + mov v0.16b, v6.16b // vmovdqa %xmm6, %xmm0 + ins v6.d[0], v1.d[0] // vmovhlps %xmm1, %xmm6, %xmm6 # clobber low side with zeros + ret +.size _vpaes_schedule_192_smear,.-_vpaes_schedule_192_smear + +## +## .aes_schedule_round +## +## Runs one main round of the key schedule on %xmm0, %xmm7 +## +## Specifically, runs subbytes on the high dword of %xmm0 +## then rotates it by one byte and xors into the low dword of +## %xmm7. +## +## Adds rcon from low byte of %xmm8, then rotates %xmm8 for +## next rcon. +## +## Smears the dwords of %xmm7 by xoring the low into the +## second low, result into third, result into highest. +## +## Returns results in %xmm7 = %xmm0. +## Clobbers %xmm1-%xmm4, %r11. +## +.type _vpaes_schedule_round,%function +.align 4 +_vpaes_schedule_round: + // extract rcon from xmm8 + movi v4.16b, #0 // vpxor %xmm4, %xmm4, %xmm4 + ext v1.16b, $rcon, v4.16b, #15 // vpalignr \$15, %xmm8, %xmm4, %xmm1 + ext $rcon, $rcon, $rcon, #15 // vpalignr \$15, %xmm8, %xmm8, %xmm8 + eor v7.16b, v7.16b, v1.16b // vpxor %xmm1, %xmm7, %xmm7 + + // rotate + dup v0.4s, v0.s[3] // vpshufd \$0xFF, %xmm0, %xmm0 + ext v0.16b, v0.16b, v0.16b, #1 // vpalignr \$1, %xmm0, %xmm0, %xmm0 + + // fall through... + + // low round: same as high round, but no rotation and no rcon. +_vpaes_schedule_low_round: + // smear xmm7 + ext v1.16b, v4.16b, v7.16b, #12 // vpslldq \$4, %xmm7, %xmm1 + eor v7.16b, v7.16b, v1.16b // vpxor %xmm1, %xmm7, %xmm7 + ext v4.16b, v4.16b, v7.16b, #8 // vpslldq \$8, %xmm7, %xmm4 + + // subbytes + and v1.16b, v0.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 # 0 = k + ushr v0.16b, v0.16b, #4 // vpsrlb \$4, %xmm0, %xmm0 # 1 = i + eor v7.16b, v7.16b, v4.16b // vpxor %xmm4, %xmm7, %xmm7 + tbl v2.16b, {$invhi}, v1.16b // vpshufb %xmm1, %xmm11, %xmm2 # 2 = a/k + eor v1.16b, v1.16b, v0.16b // vpxor %xmm0, %xmm1, %xmm1 # 0 = j + tbl v3.16b, {$invlo}, v0.16b // vpshufb %xmm0, %xmm10, %xmm3 # 3 = 1/i + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 # 3 = iak = 1/i + a/k + tbl v4.16b, {$invlo}, v1.16b // vpshufb %xmm1, %xmm10, %xmm4 # 4 = 1/j + eor v7.16b, v7.16b, v16.16b // vpxor .Lk_s63(%rip), %xmm7, %xmm7 + tbl v3.16b, {$invlo}, v3.16b // vpshufb %xmm3, %xmm10, %xmm3 # 2 = 1/iak + eor v4.16b, v4.16b, v2.16b // vpxor %xmm2, %xmm4, %xmm4 # 4 = jak = 1/j + a/k + tbl v2.16b, {$invlo}, v4.16b // vpshufb %xmm4, %xmm10, %xmm2 # 3 = 1/jak + eor v3.16b, v3.16b, v1.16b // vpxor %xmm1, %xmm3, %xmm3 # 2 = io + eor v2.16b, v2.16b, v0.16b // vpxor %xmm0, %xmm2, %xmm2 # 3 = jo + tbl v4.16b, {v23.16b}, v3.16b // vpshufb %xmm3, %xmm13, %xmm4 # 4 = sbou + tbl v1.16b, {v22.16b}, v2.16b // vpshufb %xmm2, %xmm12, %xmm1 # 0 = sb1t + eor v1.16b, v1.16b, v4.16b // vpxor %xmm4, %xmm1, %xmm1 # 0 = sbox output + + // add in smeared stuff + eor v0.16b, v1.16b, v7.16b // vpxor %xmm7, %xmm1, %xmm0 + eor v7.16b, v1.16b, v7.16b // vmovdqa %xmm0, %xmm7 + ret +.size _vpaes_schedule_round,.-_vpaes_schedule_round + +## +## .aes_schedule_transform +## +## Linear-transform %xmm0 according to tables at (%r11) +## +## Requires that %xmm9 = 0x0F0F... as in preheat +## Output in %xmm0 +## Clobbers %xmm1, %xmm2 +## +.type _vpaes_schedule_transform,%function +.align 4 +_vpaes_schedule_transform: + and v1.16b, v0.16b, v17.16b // vpand %xmm9, %xmm0, %xmm1 + ushr v0.16b, v0.16b, #4 // vpsrlb \$4, %xmm0, %xmm0 + // vmovdqa (%r11), %xmm2 # lo + tbl v2.16b, {$iptlo}, v1.16b // vpshufb %xmm1, %xmm2, %xmm2 + // vmovdqa 16(%r11), %xmm1 # hi + tbl v0.16b, {$ipthi}, v0.16b // vpshufb %xmm0, %xmm1, %xmm0 + eor v0.16b, v0.16b, v2.16b // vpxor %xmm2, %xmm0, %xmm0 + ret +.size _vpaes_schedule_transform,.-_vpaes_schedule_transform + +## +## .aes_schedule_mangle +## +## Mangle xmm0 from (basis-transformed) standard version +## to our version. +## +## On encrypt, +## xor with 0x63 +## multiply by circulant 0,1,1,1 +## apply shiftrows transform +## +## On decrypt, +## xor with 0x63 +## multiply by "inverse mixcolumns" circulant E,B,D,9 +## deskew +## apply shiftrows transform +## +## +## Writes out to (%rdx), and increments or decrements it +## Keeps track of round number mod 4 in %r8 +## Preserves xmm0 +## Clobbers xmm1-xmm5 +## +.type _vpaes_schedule_mangle,%function +.align 4 +_vpaes_schedule_mangle: + mov v4.16b, v0.16b // vmovdqa %xmm0, %xmm4 # save xmm0 for later + // vmovdqa .Lk_mc_forward(%rip),%xmm5 + cbnz $dir, .Lschedule_mangle_dec + + // encrypting + eor v4.16b, v0.16b, v16.16b // vpxor .Lk_s63(%rip), %xmm0, %xmm4 + add $out, $out, #16 // add \$16, %rdx + tbl v4.16b, {v4.16b}, v9.16b // vpshufb %xmm5, %xmm4, %xmm4 + tbl v1.16b, {v4.16b}, v9.16b // vpshufb %xmm5, %xmm4, %xmm1 + tbl v3.16b, {v1.16b}, v9.16b // vpshufb %xmm5, %xmm1, %xmm3 + eor v4.16b, v4.16b, v1.16b // vpxor %xmm1, %xmm4, %xmm4 + ld1 {v1.2d}, [x8] // vmovdqa (%r8,%r10), %xmm1 + eor v3.16b, v3.16b, v4.16b // vpxor %xmm4, %xmm3, %xmm3 + + b .Lschedule_mangle_both +.align 4 +.Lschedule_mangle_dec: + // inverse mix columns + // lea .Lk_dksd(%rip),%r11 + ushr v1.16b, v4.16b, #4 // vpsrlb \$4, %xmm4, %xmm1 # 1 = hi + and v4.16b, v4.16b, v17.16b // vpand %xmm9, %xmm4, %xmm4 # 4 = lo + + // vmovdqa 0x00(%r11), %xmm2 + tbl v2.16b, {v24.16b}, v4.16b // vpshufb %xmm4, %xmm2, %xmm2 + // vmovdqa 0x10(%r11), %xmm3 + tbl v3.16b, {v25.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm3 + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 + tbl v3.16b, {v3.16b}, v9.16b // vpshufb %xmm5, %xmm3, %xmm3 + + // vmovdqa 0x20(%r11), %xmm2 + tbl v2.16b, {v26.16b}, v4.16b // vpshufb %xmm4, %xmm2, %xmm2 + eor v2.16b, v2.16b, v3.16b // vpxor %xmm3, %xmm2, %xmm2 + // vmovdqa 0x30(%r11), %xmm3 + tbl v3.16b, {v27.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm3 + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 + tbl v3.16b, {v3.16b}, v9.16b // vpshufb %xmm5, %xmm3, %xmm3 + + // vmovdqa 0x40(%r11), %xmm2 + tbl v2.16b, {v28.16b}, v4.16b // vpshufb %xmm4, %xmm2, %xmm2 + eor v2.16b, v2.16b, v3.16b // vpxor %xmm3, %xmm2, %xmm2 + // vmovdqa 0x50(%r11), %xmm3 + tbl v3.16b, {v29.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm3 + eor v3.16b, v3.16b, v2.16b // vpxor %xmm2, %xmm3, %xmm3 + + // vmovdqa 0x60(%r11), %xmm2 + tbl v2.16b, {v30.16b}, v4.16b // vpshufb %xmm4, %xmm2, %xmm2 + tbl v3.16b, {v3.16b}, v9.16b // vpshufb %xmm5, %xmm3, %xmm3 + // vmovdqa 0x70(%r11), %xmm4 + tbl v4.16b, {v31.16b}, v1.16b // vpshufb %xmm1, %xmm4, %xmm4 + ld1 {v1.2d}, [x8] // vmovdqa (%r8,%r10), %xmm1 + eor v2.16b, v2.16b, v3.16b // vpxor %xmm3, %xmm2, %xmm2 + eor v3.16b, v4.16b, v2.16b // vpxor %xmm2, %xmm4, %xmm3 + + sub $out, $out, #16 // add \$-16, %rdx + +.Lschedule_mangle_both: + tbl v3.16b, {v3.16b}, v1.16b // vpshufb %xmm1, %xmm3, %xmm3 + add x8, x8, #64-16 // add \$-16, %r8 + and x8, x8, #~(1<<6) // and \$0x30, %r8 + st1 {v3.2d}, [$out] // vmovdqu %xmm3, (%rdx) + ret +.size _vpaes_schedule_mangle,.-_vpaes_schedule_mangle + +.globl vpaes_set_encrypt_key +.type vpaes_set_encrypt_key,%function +.align 4 +vpaes_set_encrypt_key: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + stp d8,d9,[sp,#-16]! // ABI spec says so + + lsr w9, $bits, #5 // shr \$5,%eax + add w9, w9, #5 // \$5,%eax + str w9, [$out,#240] // mov %eax,240(%rdx) # AES_KEY->rounds = nbits/32+5; + + mov $dir, #0 // mov \$0,%ecx + mov x8, #0x30 // mov \$0x30,%r8d + bl _vpaes_schedule_core + eor x0, x0, x0 + + ldp d8,d9,[sp],#16 + ldp x29,x30,[sp],#16 + ret +.size vpaes_set_encrypt_key,.-vpaes_set_encrypt_key + +.globl vpaes_set_decrypt_key +.type vpaes_set_decrypt_key,%function +.align 4 +vpaes_set_decrypt_key: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + stp d8,d9,[sp,#-16]! // ABI spec says so + + lsr w9, $bits, #5 // shr \$5,%eax + add w9, w9, #5 // \$5,%eax + str w9, [$out,#240] // mov %eax,240(%rdx) # AES_KEY->rounds = nbits/32+5; + lsl w9, w9, #4 // shl \$4,%eax + add $out, $out, #16 // lea 16(%rdx,%rax),%rdx + add $out, $out, x9 + + mov $dir, #1 // mov \$1,%ecx + lsr w8, $bits, #1 // shr \$1,%r8d + and x8, x8, #32 // and \$32,%r8d + eor x8, x8, #32 // xor \$32,%r8d # nbits==192?0:32 + bl _vpaes_schedule_core + + ldp d8,d9,[sp],#16 + ldp x29,x30,[sp],#16 + ret +.size vpaes_set_decrypt_key,.-vpaes_set_decrypt_key +___ +} +{ +my ($inp,$out,$len,$key,$ivec,$dir) = map("x$_",(0..5)); + +$code.=<<___; +.globl vpaes_cbc_encrypt +.type vpaes_cbc_encrypt,%function +.align 4 +vpaes_cbc_encrypt: + cbz $len, .Lcbc_abort + cmp w5, #0 // check direction + b.eq vpaes_cbc_decrypt + + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + + mov x17, $len // reassign + mov x2, $key // reassign + + ld1 {v0.16b}, [$ivec] // load ivec + bl _vpaes_encrypt_preheat + b .Lcbc_enc_loop + +.align 4 +.Lcbc_enc_loop: + ld1 {v7.16b}, [$inp],#16 // load input + eor v7.16b, v7.16b, v0.16b // xor with ivec + bl _vpaes_encrypt_core + st1 {v0.16b}, [$out],#16 // save output + subs x17, x17, #16 + b.hi .Lcbc_enc_loop + + st1 {v0.16b}, [$ivec] // write ivec + + ldp x29,x30,[sp],#16 +.Lcbc_abort: + ret +.size vpaes_cbc_encrypt,.-vpaes_cbc_encrypt + +.type vpaes_cbc_decrypt,%function +.align 4 +vpaes_cbc_decrypt: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + stp d8,d9,[sp,#-16]! // ABI spec says so + stp d10,d11,[sp,#-16]! + stp d12,d13,[sp,#-16]! + stp d14,d15,[sp,#-16]! + + mov x17, $len // reassign + mov x2, $key // reassign + ld1 {v6.16b}, [$ivec] // load ivec + bl _vpaes_decrypt_preheat + tst x17, #16 + b.eq .Lcbc_dec_loop2x + + ld1 {v7.16b}, [$inp], #16 // load input + bl _vpaes_decrypt_core + eor v0.16b, v0.16b, v6.16b // xor with ivec + orr v6.16b, v7.16b, v7.16b // next ivec value + st1 {v0.16b}, [$out], #16 + subs x17, x17, #16 + b.ls .Lcbc_dec_done + +.align 4 +.Lcbc_dec_loop2x: + ld1 {v14.16b,v15.16b}, [$inp], #32 + bl _vpaes_decrypt_2x + eor v0.16b, v0.16b, v6.16b // xor with ivec + eor v1.16b, v1.16b, v14.16b + orr v6.16b, v15.16b, v15.16b + st1 {v0.16b,v1.16b}, [$out], #32 + subs x17, x17, #32 + b.hi .Lcbc_dec_loop2x + +.Lcbc_dec_done: + st1 {v6.16b}, [$ivec] + + ldp d14,d15,[sp],#16 + ldp d12,d13,[sp],#16 + ldp d10,d11,[sp],#16 + ldp d8,d9,[sp],#16 + ldp x29,x30,[sp],#16 + ret +.size vpaes_cbc_decrypt,.-vpaes_cbc_decrypt +___ +# We omit vpaes_ecb_* in BoringSSL. They are unused. +if (0) { +$code.=<<___; +.globl vpaes_ecb_encrypt +.type vpaes_ecb_encrypt,%function +.align 4 +vpaes_ecb_encrypt: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + stp d8,d9,[sp,#-16]! // ABI spec says so + stp d10,d11,[sp,#-16]! + stp d12,d13,[sp,#-16]! + stp d14,d15,[sp,#-16]! + + mov x17, $len + mov x2, $key + bl _vpaes_encrypt_preheat + tst x17, #16 + b.eq .Lecb_enc_loop + + ld1 {v7.16b}, [$inp],#16 + bl _vpaes_encrypt_core + st1 {v0.16b}, [$out],#16 + subs x17, x17, #16 + b.ls .Lecb_enc_done + +.align 4 +.Lecb_enc_loop: + ld1 {v14.16b,v15.16b}, [$inp], #32 + bl _vpaes_encrypt_2x + st1 {v0.16b,v1.16b}, [$out], #32 + subs x17, x17, #32 + b.hi .Lecb_enc_loop + +.Lecb_enc_done: + ldp d14,d15,[sp],#16 + ldp d12,d13,[sp],#16 + ldp d10,d11,[sp],#16 + ldp d8,d9,[sp],#16 + ldp x29,x30,[sp],#16 + ret +.size vpaes_ecb_encrypt,.-vpaes_ecb_encrypt + +.globl vpaes_ecb_decrypt +.type vpaes_ecb_decrypt,%function +.align 4 +vpaes_ecb_decrypt: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + stp d8,d9,[sp,#-16]! // ABI spec says so + stp d10,d11,[sp,#-16]! + stp d12,d13,[sp,#-16]! + stp d14,d15,[sp,#-16]! + + mov x17, $len + mov x2, $key + bl _vpaes_decrypt_preheat + tst x17, #16 + b.eq .Lecb_dec_loop + + ld1 {v7.16b}, [$inp],#16 + bl _vpaes_encrypt_core + st1 {v0.16b}, [$out],#16 + subs x17, x17, #16 + b.ls .Lecb_dec_done + +.align 4 +.Lecb_dec_loop: + ld1 {v14.16b,v15.16b}, [$inp], #32 + bl _vpaes_decrypt_2x + st1 {v0.16b,v1.16b}, [$out], #32 + subs x17, x17, #32 + b.hi .Lecb_dec_loop + +.Lecb_dec_done: + ldp d14,d15,[sp],#16 + ldp d12,d13,[sp],#16 + ldp d10,d11,[sp],#16 + ldp d8,d9,[sp],#16 + ldp x29,x30,[sp],#16 + ret +.size vpaes_ecb_decrypt,.-vpaes_ecb_decrypt +___ +} + +my ($ctr, $ctr_tmp) = ("w6", "w7"); + +# void vpaes_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, size_t len, +# const AES_KEY *key, const uint8_t ivec[16]); +$code.=<<___; +.globl vpaes_ctr32_encrypt_blocks +.type vpaes_ctr32_encrypt_blocks,%function +.align 4 +vpaes_ctr32_encrypt_blocks: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + stp d8,d9,[sp,#-16]! // ABI spec says so + stp d10,d11,[sp,#-16]! + stp d12,d13,[sp,#-16]! + stp d14,d15,[sp,#-16]! + + cbz $len, .Lctr32_done + + // Note, unlike the other functions, $len here is measured in blocks, + // not bytes. + mov x17, $len + mov x2, $key + + // Load the IV and counter portion. + ldr $ctr, [$ivec, #12] + ld1 {v7.16b}, [$ivec] + + bl _vpaes_encrypt_preheat + tst x17, #1 + rev $ctr, $ctr // The counter is big-endian. + b.eq .Lctr32_prep_loop + + // Handle one block so the remaining block count is even for + // _vpaes_encrypt_2x. + ld1 {v6.16b}, [$inp], #16 // Load input ahead of time + bl _vpaes_encrypt_core + eor v0.16b, v0.16b, v6.16b // XOR input and result + st1 {v0.16b}, [$out], #16 + subs x17, x17, #1 + // Update the counter. + add $ctr, $ctr, #1 + rev $ctr_tmp, $ctr + mov v7.s[3], $ctr_tmp + b.ls .Lctr32_done + +.Lctr32_prep_loop: + // _vpaes_encrypt_core takes its input from v7, while _vpaes_encrypt_2x + // uses v14 and v15. + mov v15.16b, v7.16b + mov v14.16b, v7.16b + add $ctr, $ctr, #1 + rev $ctr_tmp, $ctr + mov v15.s[3], $ctr_tmp + +.Lctr32_loop: + ld1 {v6.16b,v7.16b}, [$inp], #32 // Load input ahead of time + bl _vpaes_encrypt_2x + eor v0.16b, v0.16b, v6.16b // XOR input and result + eor v1.16b, v1.16b, v7.16b // XOR input and result (#2) + st1 {v0.16b,v1.16b}, [$out], #32 + subs x17, x17, #2 + // Update the counter. + add $ctr_tmp, $ctr, #1 + add $ctr, $ctr, #2 + rev $ctr_tmp, $ctr_tmp + mov v14.s[3], $ctr_tmp + rev $ctr_tmp, $ctr + mov v15.s[3], $ctr_tmp + b.hi .Lctr32_loop + +.Lctr32_done: + ldp d14,d15,[sp],#16 + ldp d12,d13,[sp],#16 + ldp d10,d11,[sp],#16 + ldp d8,d9,[sp],#16 + ldp x29,x30,[sp],#16 + ret +.size vpaes_ctr32_encrypt_blocks,.-vpaes_ctr32_encrypt_blocks +___ +} + +print $code; + +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/vpaes-x86.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/vpaes-x86.pl index 5f4b208d..2b403628 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/vpaes-x86.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/vpaes-x86.pl @@ -69,6 +69,9 @@ $PREFIX="vpaes"; my ($round, $base, $magic, $key, $const, $inp, $out)= ("eax", "ebx", "ecx", "edx","ebp", "esi","edi"); +&preprocessor_ifndef("NDEBUG") +&external_label("BORINGSSL_function_hit"); +&preprocessor_endif(); &static_label("_vpaes_consts"); &static_label("_vpaes_schedule_low_round"); @@ -758,6 +761,8 @@ $k_dsbo=0x2c0; # decryption sbox final output # Interface to OpenSSL # &function_begin("${PREFIX}_set_encrypt_key"); + record_function_hit(5); + &mov ($inp,&wparam(0)); # inp &lea ($base,&DWP(-56,"esp")); &mov ($round,&wparam(1)); # bits @@ -812,6 +817,8 @@ $k_dsbo=0x2c0; # decryption sbox final output &function_end("${PREFIX}_set_decrypt_key"); &function_begin("${PREFIX}_encrypt"); + record_function_hit(4); + &lea ($const,&DWP(&label("_vpaes_consts")."+0x30-".&label("pic_point"))); &call ("_vpaes_preheat"); &set_label("pic_point"); @@ -913,4 +920,4 @@ $k_dsbo=0x2c0; # decryption sbox final output &asm_finish(); -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/vpaes-x86_64.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/vpaes-x86_64.pl index 3d4770c9..45463e8a 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/vpaes-x86_64.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/asm/vpaes-x86_64.pl @@ -175,6 +175,181 @@ _vpaes_encrypt_core: .cfi_endproc .size _vpaes_encrypt_core,.-_vpaes_encrypt_core +## +## _aes_encrypt_core_2x +## +## AES-encrypt %xmm0 and %xmm6 in parallel. +## +## Inputs: +## %xmm0 and %xmm6 = input +## %xmm12-%xmm15 as in _vpaes_preheat +## (%rdx) = scheduled keys +## +## Output in %xmm0 and %xmm6 +## Clobbers %xmm1-%xmm5, %xmm7-%xmm11, %r9, %r10, %r11, %rax +## Preserves %xmm14 and %xmm15 +## +## This function stitches two parallel instances of _vpaes_encrypt_core. x86_64 +## provides 16 XMM registers. _vpaes_encrypt_core computes over six registers +## (%xmm0-%xmm5) and additionally uses seven registers with preloaded constants +## from _vpaes_preheat (%xmm9-%xmm15). This does not quite fit two instances, +## so we spill some of %xmm9 through %xmm15 back to memory. We keep %xmm9 and +## %xmm10 in registers as these values are used several times in a row. The +## remainder are read once per round and are spilled to memory. This leaves two +## registers preserved for the caller. +## +## Thus, of the two _vpaes_encrypt_core instances, the first uses (%xmm0-%xmm5) +## as before. The second uses %xmm6-%xmm8,%xmm11-%xmm13. (Add 6 to %xmm2 and +## below. Add 8 to %xmm3 and up.) Instructions in the second instance are +## indented by one space. +## +## +.type _vpaes_encrypt_core_2x,\@abi-omnipotent +.align 16 +_vpaes_encrypt_core_2x: +.cfi_startproc + mov %rdx, %r9 + mov \$16, %r11 + mov 240(%rdx),%eax + movdqa %xmm9, %xmm1 + movdqa %xmm9, %xmm7 + movdqa .Lk_ipt(%rip), %xmm2 # iptlo + movdqa %xmm2, %xmm8 + pandn %xmm0, %xmm1 + pandn %xmm6, %xmm7 + movdqu (%r9), %xmm5 # round0 key + # Also use %xmm5 in the second instance. + psrld \$4, %xmm1 + psrld \$4, %xmm7 + pand %xmm9, %xmm0 + pand %xmm9, %xmm6 + pshufb %xmm0, %xmm2 + pshufb %xmm6, %xmm8 + movdqa .Lk_ipt+16(%rip), %xmm0 # ipthi + movdqa %xmm0, %xmm6 + pshufb %xmm1, %xmm0 + pshufb %xmm7, %xmm6 + pxor %xmm5, %xmm2 + pxor %xmm5, %xmm8 + add \$16, %r9 + pxor %xmm2, %xmm0 + pxor %xmm8, %xmm6 + lea .Lk_mc_backward(%rip),%r10 + jmp .Lenc2x_entry + +.align 16 +.Lenc2x_loop: + # middle of middle round + movdqa .Lk_sb1(%rip), %xmm4 # 4 : sb1u + movdqa .Lk_sb1+16(%rip),%xmm0 # 0 : sb1t + movdqa %xmm4, %xmm12 + movdqa %xmm0, %xmm6 + pshufb %xmm2, %xmm4 # 4 = sb1u + pshufb %xmm8, %xmm12 + pshufb %xmm3, %xmm0 # 0 = sb1t + pshufb %xmm11, %xmm6 + pxor %xmm5, %xmm4 # 4 = sb1u + k + pxor %xmm5, %xmm12 + movdqa .Lk_sb2(%rip), %xmm5 # 4 : sb2u + movdqa %xmm5, %xmm13 + pxor %xmm4, %xmm0 # 0 = A + pxor %xmm12, %xmm6 + movdqa -0x40(%r11,%r10), %xmm1 # .Lk_mc_forward[] + # Also use %xmm1 in the second instance. + pshufb %xmm2, %xmm5 # 4 = sb2u + pshufb %xmm8, %xmm13 + movdqa (%r11,%r10), %xmm4 # .Lk_mc_backward[] + # Also use %xmm4 in the second instance. + movdqa .Lk_sb2+16(%rip), %xmm2 # 2 : sb2t + movdqa %xmm2, %xmm8 + pshufb %xmm3, %xmm2 # 2 = sb2t + pshufb %xmm11, %xmm8 + movdqa %xmm0, %xmm3 # 3 = A + movdqa %xmm6, %xmm11 + pxor %xmm5, %xmm2 # 2 = 2A + pxor %xmm13, %xmm8 + pshufb %xmm1, %xmm0 # 0 = B + pshufb %xmm1, %xmm6 + add \$16, %r9 # next key + pxor %xmm2, %xmm0 # 0 = 2A+B + pxor %xmm8, %xmm6 + pshufb %xmm4, %xmm3 # 3 = D + pshufb %xmm4, %xmm11 + add \$16, %r11 # next mc + pxor %xmm0, %xmm3 # 3 = 2A+B+D + pxor %xmm6, %xmm11 + pshufb %xmm1, %xmm0 # 0 = 2B+C + pshufb %xmm1, %xmm6 + and \$0x30, %r11 # ... mod 4 + sub \$1,%rax # nr-- + pxor %xmm3, %xmm0 # 0 = 2A+3B+C+D + pxor %xmm11, %xmm6 + +.Lenc2x_entry: + # top of round + movdqa %xmm9, %xmm1 # 1 : i + movdqa %xmm9, %xmm7 + movdqa .Lk_inv+16(%rip), %xmm5 # 2 : a/k + movdqa %xmm5, %xmm13 + pandn %xmm0, %xmm1 # 1 = i<<4 + pandn %xmm6, %xmm7 + psrld \$4, %xmm1 # 1 = i + psrld \$4, %xmm7 + pand %xmm9, %xmm0 # 0 = k + pand %xmm9, %xmm6 + pshufb %xmm0, %xmm5 # 2 = a/k + pshufb %xmm6, %xmm13 + movdqa %xmm10, %xmm3 # 3 : 1/i + movdqa %xmm10, %xmm11 + pxor %xmm1, %xmm0 # 0 = j + pxor %xmm7, %xmm6 + pshufb %xmm1, %xmm3 # 3 = 1/i + pshufb %xmm7, %xmm11 + movdqa %xmm10, %xmm4 # 4 : 1/j + movdqa %xmm10, %xmm12 + pxor %xmm5, %xmm3 # 3 = iak = 1/i + a/k + pxor %xmm13, %xmm11 + pshufb %xmm0, %xmm4 # 4 = 1/j + pshufb %xmm6, %xmm12 + movdqa %xmm10, %xmm2 # 2 : 1/iak + movdqa %xmm10, %xmm8 + pxor %xmm5, %xmm4 # 4 = jak = 1/j + a/k + pxor %xmm13, %xmm12 + pshufb %xmm3, %xmm2 # 2 = 1/iak + pshufb %xmm11, %xmm8 + movdqa %xmm10, %xmm3 # 3 : 1/jak + movdqa %xmm10, %xmm11 + pxor %xmm0, %xmm2 # 2 = io + pxor %xmm6, %xmm8 + pshufb %xmm4, %xmm3 # 3 = 1/jak + pshufb %xmm12, %xmm11 + movdqu (%r9), %xmm5 + # Also use %xmm5 in the second instance. + pxor %xmm1, %xmm3 # 3 = jo + pxor %xmm7, %xmm11 + jnz .Lenc2x_loop + + # middle of last round + movdqa -0x60(%r10), %xmm4 # 3 : sbou .Lk_sbo + movdqa -0x50(%r10), %xmm0 # 0 : sbot .Lk_sbo+16 + movdqa %xmm4, %xmm12 + movdqa %xmm0, %xmm6 + pshufb %xmm2, %xmm4 # 4 = sbou + pshufb %xmm8, %xmm12 + pxor %xmm5, %xmm4 # 4 = sb1u + k + pxor %xmm5, %xmm12 + pshufb %xmm3, %xmm0 # 0 = sb1t + pshufb %xmm11, %xmm6 + movdqa 0x40(%r11,%r10), %xmm1 # .Lk_sr[] + # Also use %xmm1 in the second instance. + pxor %xmm4, %xmm0 # 0 = A + pxor %xmm12, %xmm6 + pshufb %xmm1, %xmm0 + pshufb %xmm1, %xmm6 + ret +.cfi_endproc +.size _vpaes_encrypt_core_2x,.-_vpaes_encrypt_core_2x + ## ## Decryption core ## @@ -696,6 +871,13 @@ _vpaes_schedule_mangle: .align 16 ${PREFIX}_set_encrypt_key: .cfi_startproc +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS +.extern BORINGSSL_function_hit + movb \$1, BORINGSSL_function_hit+5(%rip) +#endif +#endif + ___ $code.=<<___ if ($win64); lea -0xb8(%rsp),%rsp @@ -801,6 +983,12 @@ $code.=<<___; .align 16 ${PREFIX}_encrypt: .cfi_startproc +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS +.extern BORINGSSL_function_hit + movb \$1, BORINGSSL_function_hit+4(%rip) +#endif +#endif ___ $code.=<<___ if ($win64); lea -0xb8(%rsp),%rsp @@ -971,6 +1159,111 @@ $code.=<<___; .size ${PREFIX}_cbc_encrypt,.-${PREFIX}_cbc_encrypt ___ } +{ +my ($inp,$out,$blocks,$key,$ivp)=("%rdi","%rsi","%rdx","%rcx","%r8"); +# void vpaes_ctr32_encrypt_blocks(const uint8_t *inp, uint8_t *out, +# size_t blocks, const AES_KEY *key, +# const uint8_t ivp[16]); +$code.=<<___; +.globl ${PREFIX}_ctr32_encrypt_blocks +.type ${PREFIX}_ctr32_encrypt_blocks,\@function,5 +.align 16 +${PREFIX}_ctr32_encrypt_blocks: +.cfi_startproc + # _vpaes_encrypt_core and _vpaes_encrypt_core_2x expect the key in %rdx. + xchg $key, $blocks +___ +($blocks,$key)=($key,$blocks); +$code.=<<___; + test $blocks, $blocks + jz .Lctr32_abort +___ +$code.=<<___ if ($win64); + lea -0xb8(%rsp),%rsp + movaps %xmm6,0x10(%rsp) + movaps %xmm7,0x20(%rsp) + movaps %xmm8,0x30(%rsp) + movaps %xmm9,0x40(%rsp) + movaps %xmm10,0x50(%rsp) + movaps %xmm11,0x60(%rsp) + movaps %xmm12,0x70(%rsp) + movaps %xmm13,0x80(%rsp) + movaps %xmm14,0x90(%rsp) + movaps %xmm15,0xa0(%rsp) +.Lctr32_body: +___ +$code.=<<___; + movdqu ($ivp), %xmm0 # Load IV. + movdqa .Lctr_add_one(%rip), %xmm8 + sub $inp, $out # This allows only incrementing $inp. + call _vpaes_preheat + movdqa %xmm0, %xmm6 + pshufb .Lrev_ctr(%rip), %xmm6 + + test \$1, $blocks + jz .Lctr32_prep_loop + + # Handle one block so the remaining block count is even for + # _vpaes_encrypt_core_2x. + movdqu ($inp), %xmm7 # Load input. + call _vpaes_encrypt_core + pxor %xmm7, %xmm0 + paddd %xmm8, %xmm6 + movdqu %xmm0, ($out,$inp) + sub \$1, $blocks + lea 16($inp), $inp + jz .Lctr32_done + +.Lctr32_prep_loop: + # _vpaes_encrypt_core_2x leaves only %xmm14 and %xmm15 as spare + # registers. We maintain two byte-swapped counters in them. + movdqa %xmm6, %xmm14 + movdqa %xmm6, %xmm15 + paddd %xmm8, %xmm15 + +.Lctr32_loop: + movdqa .Lrev_ctr(%rip), %xmm1 # Set up counters. + movdqa %xmm14, %xmm0 + movdqa %xmm15, %xmm6 + pshufb %xmm1, %xmm0 + pshufb %xmm1, %xmm6 + call _vpaes_encrypt_core_2x + movdqu ($inp), %xmm1 # Load input. + movdqu 16($inp), %xmm2 + movdqa .Lctr_add_two(%rip), %xmm3 + pxor %xmm1, %xmm0 # XOR input. + pxor %xmm2, %xmm6 + paddd %xmm3, %xmm14 # Increment counters. + paddd %xmm3, %xmm15 + movdqu %xmm0, ($out,$inp) # Write output. + movdqu %xmm6, 16($out,$inp) + sub \$2, $blocks # Advance loop. + lea 32($inp), $inp + jnz .Lctr32_loop + +.Lctr32_done: +___ +$code.=<<___ if ($win64); + movaps 0x10(%rsp),%xmm6 + movaps 0x20(%rsp),%xmm7 + movaps 0x30(%rsp),%xmm8 + movaps 0x40(%rsp),%xmm9 + movaps 0x50(%rsp),%xmm10 + movaps 0x60(%rsp),%xmm11 + movaps 0x70(%rsp),%xmm12 + movaps 0x80(%rsp),%xmm13 + movaps 0x90(%rsp),%xmm14 + movaps 0xa0(%rsp),%xmm15 + lea 0xb8(%rsp),%rsp +.Lctr32_epilogue: +___ +$code.=<<___; +.Lctr32_abort: + ret +.cfi_endproc +.size ${PREFIX}_ctr32_encrypt_blocks,.-${PREFIX}_ctr32_encrypt_blocks +___ +} $code.=<<___; ## ## _aes_preheat @@ -1094,6 +1387,17 @@ _vpaes_consts: .Lk_dsbo: # decryption sbox final output .quad 0x1387EA537EF94000, 0xC7AA6DB9D4943E2D .quad 0x12D7560F93441D00, 0xCA4B8159D8C58E9C + +# .Lrev_ctr is a permutation which byte-swaps the counter portion of the IV. +.Lrev_ctr: + .quad 0x0706050403020100, 0x0c0d0e0f0b0a0908 +# .Lctr_add_* may be added to a byte-swapped xmm register to increment the +# counter. The register must be byte-swapped again to form the actual input. +.Lctr_add_one: + .quad 0x0000000000000000, 0x0000000100000000 +.Lctr_add_two: + .quad 0x0000000000000000, 0x0000000200000000 + .asciz "Vector Permutation AES for x86_64/SSSE3, Mike Hamburg (Stanford University)" .align 64 .size _vpaes_consts,.-_vpaes_consts @@ -1209,6 +1513,10 @@ se_handler: .rva .LSEH_end_${PREFIX}_cbc_encrypt .rva .LSEH_info_${PREFIX}_cbc_encrypt + .rva .LSEH_begin_${PREFIX}_ctr32_encrypt_blocks + .rva .LSEH_end_${PREFIX}_ctr32_encrypt_blocks + .rva .LSEH_info_${PREFIX}_ctr32_encrypt_blocks + .section .xdata .align 8 .LSEH_info_${PREFIX}_set_encrypt_key: @@ -1231,6 +1539,10 @@ se_handler: .byte 9,0,0,0 .rva se_handler .rva .Lcbc_body,.Lcbc_epilogue # HandlerData[] +.LSEH_info_${PREFIX}_ctr32_encrypt_blocks: + .byte 9,0,0,0 + .rva se_handler + .rva .Lctr32_body,.Lctr32_epilogue # HandlerData[] ___ } @@ -1238,4 +1550,4 @@ $code =~ s/\`([^\`]*)\`/eval($1)/gem; print $code; -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/internal.h b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/internal.h index a91ea708..0cebb04c 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/internal.h +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/internal.h @@ -35,23 +35,27 @@ OPENSSL_INLINE int hwaes_capable(void) { } #define VPAES -OPENSSL_INLINE char vpaes_capable(void) { +#if defined(OPENSSL_X86_64) +#define VPAES_CTR32 +#endif +OPENSSL_INLINE int vpaes_capable(void) { return (OPENSSL_ia32cap_get()[1] & (1 << (41 - 32))) != 0; } -#if defined(OPENSSL_X86_64) -#define BSAES -OPENSSL_INLINE char bsaes_capable(void) { return vpaes_capable(); } -#endif // X86_64 - #elif defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64) #define HWAES OPENSSL_INLINE int hwaes_capable(void) { return CRYPTO_is_ARMv8_AES_capable(); } -#if defined(OPENSSL_ARM) && __ARM_MAX_ARCH__ >= 7 +#if defined(OPENSSL_ARM) #define BSAES -OPENSSL_INLINE char bsaes_capable(void) { return CRYPTO_is_NEON_capable(); } +OPENSSL_INLINE int bsaes_capable(void) { return CRYPTO_is_NEON_capable(); } +#endif + +#if defined(OPENSSL_AARCH64) +#define VPAES +#define VPAES_CTR32 +OPENSSL_INLINE int vpaes_capable(void) { return CRYPTO_is_NEON_capable(); } #endif #elif defined(OPENSSL_PPC64LE) @@ -127,7 +131,7 @@ void aes_hw_ecb_encrypt(const uint8_t *in, uint8_t *out, size_t length, #if defined(BSAES) // On platforms where BSAES gets defined (just above), then these functions are -// provided by asm. +// provided by asm. Note |bsaes_cbc_encrypt| requires |enc| to be zero. void bsaes_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, const AES_KEY *key, uint8_t ivec[16], int enc); void bsaes_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, size_t len, @@ -162,6 +166,10 @@ void vpaes_decrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key); void vpaes_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, const AES_KEY *key, uint8_t *ivec, int enc); +#if defined(VPAES_CTR32) +void vpaes_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, size_t len, + const AES_KEY *key, const uint8_t ivec[16]); +#endif #else OPENSSL_INLINE char vpaes_capable(void) { return 0; } diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/mode_wrappers.c b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/mode_wrappers.c index 36c657e4..ae8a91b1 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/aes/mode_wrappers.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/aes/mode_wrappers.c @@ -80,14 +80,16 @@ void AES_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len, } #if defined(AES_NOHW_CBC) - aes_nohw_cbc_encrypt(in, out, len, key, ivec, enc); -#else + if (!vpaes_capable()) { + aes_nohw_cbc_encrypt(in, out, len, key, ivec, enc); + return; + } +#endif if (enc) { CRYPTO_cbc128_encrypt(in, out, len, key, ivec, AES_encrypt); } else { CRYPTO_cbc128_decrypt(in, out, len, key, ivec, AES_decrypt); } -#endif } void AES_ofb128_encrypt(const uint8_t *in, uint8_t *out, size_t length, diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/bcm.c b/third_party/boringssl/kit/src/crypto/fipsmodule/bcm.c index e15ecb85..3fad74b0 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/bcm.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/bcm.c @@ -100,11 +100,16 @@ #if defined(BORINGSSL_FIPS) #if !defined(OPENSSL_ASAN) -// These symbols are filled in by delocate.go. They point to the start and end -// of the module, and the location of the integrity hash, respectively. +// These symbols are filled in by delocate.go (in static builds) or a linker +// script (in shared builds). They point to the start and end of the module, and +// the location of the integrity hash, respectively. extern const uint8_t BORINGSSL_bcm_text_start[]; extern const uint8_t BORINGSSL_bcm_text_end[]; extern const uint8_t BORINGSSL_bcm_text_hash[]; +#if defined(BORINGSSL_SHARED_LIBRARY) +extern const uint8_t BORINGSSL_bcm_rodata_start[]; +extern const uint8_t BORINGSSL_bcm_rodata_end[]; +#endif #endif static void __attribute__((constructor)) @@ -116,17 +121,39 @@ BORINGSSL_bcm_power_on_self_test(void) { // .text section, which triggers the global-buffer overflow detection. const uint8_t *const start = BORINGSSL_bcm_text_start; const uint8_t *const end = BORINGSSL_bcm_text_end; +#if defined(BORINGSSL_SHARED_LIBRARY) + const uint8_t *const rodata_start = BORINGSSL_bcm_rodata_start; + const uint8_t *const rodata_end = BORINGSSL_bcm_rodata_end; +#endif static const uint8_t kHMACKey[64] = {0}; uint8_t result[SHA512_DIGEST_LENGTH]; unsigned result_len; - if (!HMAC(EVP_sha512(), kHMACKey, sizeof(kHMACKey), start, end - start, - result, &result_len) || + HMAC_CTX hmac_ctx; + HMAC_CTX_init(&hmac_ctx); + if (!HMAC_Init_ex(&hmac_ctx, kHMACKey, sizeof(kHMACKey), EVP_sha512(), + NULL /* no ENGINE */)) { + fprintf(stderr, "HMAC_Init_ex failed.\n"); + goto err; + } +#if defined(BORINGSSL_SHARED_LIBRARY) + uint64_t length = end - start; + HMAC_Update(&hmac_ctx, (const uint8_t *) &length, sizeof(length)); + HMAC_Update(&hmac_ctx, start, length); + + length = rodata_end - rodata_start; + HMAC_Update(&hmac_ctx, (const uint8_t *) &length, sizeof(length)); + HMAC_Update(&hmac_ctx, rodata_start, length); +#else + HMAC_Update(&hmac_ctx, start, end - start); +#endif + if (!HMAC_Final(&hmac_ctx, result, &result_len) || result_len != sizeof(result)) { fprintf(stderr, "HMAC failed.\n"); goto err; } + HMAC_CTX_cleanup(&hmac_ctx); const uint8_t *expected = BORINGSSL_bcm_text_hash; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/armv4-mont.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/armv4-mont.pl index 2ee389e2..f3aa4be5 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/armv4-mont.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/armv4-mont.pl @@ -759,4 +759,4 @@ foreach (split("\n",$code)) { print $_,"\n"; } -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/armv8-mont.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/armv8-mont.pl index acad0644..db2ba491 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/armv8-mont.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/armv8-mont.pl @@ -61,7 +61,7 @@ $ap="x1"; # const BN_ULONG *ap, $bp="x2"; # const BN_ULONG *bp, $np="x3"; # const BN_ULONG *np, $n0="x4"; # const BN_ULONG *n0, -$num="x5"; # int num); +$num="x5"; # size_t num); $code.=<<___; .text @@ -1507,4 +1507,4 @@ ___ print $code; -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/bn-586.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/bn-586.pl index 16818d55..05ef28c2 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/bn-586.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/bn-586.pl @@ -31,7 +31,7 @@ for (@ARGV) { $sse2=1 if (/-DOPENSSL_IA32_SSE2/); } &asm_finish(); -close STDOUT; +close STDOUT or die "error closing STDOUT"; sub bn_mul_add_words { diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/co-586.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/co-586.pl index 5eeeef97..abe328ad 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/co-586.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/co-586.pl @@ -22,7 +22,7 @@ open STDOUT,">$output"; &asm_finish(); -close STDOUT; +close STDOUT or die "error closing STDOUT"; sub mul_add_c { diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/rsaz-avx2.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/rsaz-avx2.pl index 72aa2a36..a0da2390 100755 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/rsaz-avx2.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/rsaz-avx2.pl @@ -52,7 +52,6 @@ die "can't locate x86_64-xlate.pl"; # versions, but BoringSSL is intended to be used with pre-generated perlasm # output, so this isn't useful anyway. $avx = 2; -$addx = 1; open OUT,"| \"$^X\" \"$xlate\" $flavour \"$output\""; *STDOUT = *OUT; @@ -1474,6 +1473,7 @@ $code.=<<___; .type rsaz_1024_red2norm_avx2,\@abi-omnipotent .align 32 rsaz_1024_red2norm_avx2: +.cfi_startproc sub \$-128,$inp # size optimization xor %rax,%rax ___ @@ -1507,12 +1507,14 @@ ___ } $code.=<<___; ret +.cfi_endproc .size rsaz_1024_red2norm_avx2,.-rsaz_1024_red2norm_avx2 .globl rsaz_1024_norm2red_avx2 .type rsaz_1024_norm2red_avx2,\@abi-omnipotent .align 32 rsaz_1024_norm2red_avx2: +.cfi_startproc sub \$-128,$out # size optimization mov ($inp),@T[0] mov \$0x1fffffff,%eax @@ -1544,6 +1546,7 @@ $code.=<<___; mov @T[0],`8*($j+2)-128`($out) mov @T[0],`8*($j+3)-128`($out) ret +.cfi_endproc .size rsaz_1024_norm2red_avx2,.-rsaz_1024_norm2red_avx2 ___ } @@ -1555,6 +1558,7 @@ $code.=<<___; .type rsaz_1024_scatter5_avx2,\@abi-omnipotent .align 32 rsaz_1024_scatter5_avx2: +.cfi_startproc vzeroupper vmovdqu .Lscatter_permd(%rip),%ymm5 shl \$4,$power @@ -1574,6 +1578,7 @@ rsaz_1024_scatter5_avx2: vzeroupper ret +.cfi_endproc .size rsaz_1024_scatter5_avx2,.-rsaz_1024_scatter5_avx2 .globl rsaz_1024_gather5_avx2 @@ -1733,27 +1738,6 @@ ___ } $code.=<<___; -.extern OPENSSL_ia32cap_P -.globl rsaz_avx2_eligible -.type rsaz_avx2_eligible,\@abi-omnipotent -.align 32 -rsaz_avx2_eligible: - leaq OPENSSL_ia32cap_P(%rip),%rax - mov 8(%rax),%eax -___ -$code.=<<___ if ($addx); - mov \$`1<<8|1<<19`,%ecx - mov \$0,%edx - and %eax,%ecx - cmp \$`1<<8|1<<19`,%ecx # check for BMI2+AD*X - cmove %edx,%eax -___ -$code.=<<___; - and \$`1<<5`,%eax - shr \$5,%eax - ret -.size rsaz_avx2_eligible,.-rsaz_avx2_eligible - .align 64 .Land_mask: .quad 0x1fffffff,0x1fffffff,0x1fffffff,0x1fffffff @@ -1956,4 +1940,4 @@ rsaz_1024_gather5_avx2: ___ }}} -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/x86-mont.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/x86-mont.pl index 214f2b08..1f61ae55 100755 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/x86-mont.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/x86-mont.pl @@ -628,4 +628,4 @@ $sbit=$num; &asm_finish(); -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/x86_64-mont.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/x86_64-mont.pl index 023143ac..0a9e4d16 100755 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/x86_64-mont.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/x86_64-mont.pl @@ -71,7 +71,9 @@ $ap="%rsi"; # const BN_ULONG *ap, $bp="%rdx"; # const BN_ULONG *bp, $np="%rcx"; # const BN_ULONG *np, $n0="%r8"; # const BN_ULONG *n0, -$num="%r9"; # int num); +# TODO(davidben): The code below treats $num as an int, but C passes in a +# size_t. +$num="%r9"; # size_t num); $lo0="%r10"; $hi0="%r11"; $hi1="%r13"; @@ -1576,4 +1578,4 @@ ___ } print $code; -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/x86_64-mont5.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/x86_64-mont5.pl index 442e6966..b2ff1149 100755 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/x86_64-mont5.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/asm/x86_64-mont5.pl @@ -566,6 +566,7 @@ $code.=<<___; .type mul4x_internal,\@abi-omnipotent .align 32 mul4x_internal: +.cfi_startproc shl \$5,$num # $num was in bytes movd `($win64?56:8)`(%rax),%xmm5 # load 7th argument, index lea .Linc(%rip),%rax @@ -1060,6 +1061,7 @@ $code.=<<___ ___ } $code.=<<___; +.cfi_endproc .size mul4x_internal,.-mul4x_internal ___ }}} @@ -1226,6 +1228,7 @@ $code.=<<___; .align 32 bn_sqr8x_internal: __bn_sqr8x_internal: +.cfi_startproc ############################################################## # Squaring part: # @@ -2017,6 +2020,7 @@ __bn_sqr8x_reduction: cmp %rdx,$tptr # end of t[]? jb .L8x_reduction_loop ret +.cfi_endproc .size bn_sqr8x_internal,.-bn_sqr8x_internal ___ } @@ -2029,6 +2033,7 @@ $code.=<<___; .type __bn_post4x_internal,\@abi-omnipotent .align 32 __bn_post4x_internal: +.cfi_startproc mov 8*0($nptr),%r12 lea (%rdi,$num),$tptr # %rdi was $tptr above mov $num,%rcx @@ -2079,6 +2084,7 @@ __bn_post4x_internal: mov $num,%r10 # prepare for back-to-back call neg $num # restore $num ret +.cfi_endproc .size __bn_post4x_internal,.-__bn_post4x_internal ___ } @@ -2088,10 +2094,12 @@ $code.=<<___; .type bn_from_montgomery,\@abi-omnipotent .align 32 bn_from_montgomery: +.cfi_startproc testl \$7,`($win64?"48(%rsp)":"%r9d")` jz bn_from_mont8x xor %eax,%eax ret +.cfi_endproc .size bn_from_montgomery,.-bn_from_montgomery .type bn_from_mont8x,\@function,6 @@ -2388,6 +2396,7 @@ bn_mulx4x_mont_gather5: .type mulx4x_internal,\@abi-omnipotent .align 32 mulx4x_internal: +.cfi_startproc mov $num,8(%rsp) # save -$num (it was in bytes) mov $num,%r10 neg $num # restore $num @@ -2738,6 +2747,7 @@ $code.=<<___; mov 8*2(%rbp),%r14 mov 8*3(%rbp),%r15 jmp .Lsqrx4x_sub_entry # common post-condition +.cfi_endproc .size mulx4x_internal,.-mulx4x_internal ___ } { @@ -3542,7 +3552,9 @@ ___ my ($rptr,$nptr)=("%rdx","%rbp"); $code.=<<___; .align 32 +.type __bn_postx4x_internal,\@abi-omnipotent __bn_postx4x_internal: +.cfi_startproc mov 8*0($nptr),%r12 mov %rcx,%r10 # -$num mov %rcx,%r9 # -$num @@ -3590,6 +3602,7 @@ __bn_postx4x_internal: neg %r9 # restore $num ret +.cfi_endproc .size __bn_postx4x_internal,.-__bn_postx4x_internal ___ } @@ -3606,6 +3619,7 @@ $code.=<<___; .type bn_scatter5,\@abi-omnipotent .align 16 bn_scatter5: +.cfi_startproc cmp \$0, $num jz .Lscatter_epilogue lea ($tbl,$idx,8),$tbl @@ -3618,15 +3632,18 @@ bn_scatter5: jnz .Lscatter .Lscatter_epilogue: ret +.cfi_endproc .size bn_scatter5,.-bn_scatter5 .globl bn_gather5 .type bn_gather5,\@abi-omnipotent .align 32 bn_gather5: +.cfi_startproc .LSEH_begin_bn_gather5: # Win64 thing, but harmless in other cases # I can't trust assembler to use specific encoding:-( .byte 0x4c,0x8d,0x14,0x24 #lea (%rsp),%r10 +.cfi_def_cfa_register %r10 .byte 0x48,0x81,0xec,0x08,0x01,0x00,0x00 #sub $0x108,%rsp lea .Linc(%rip),%rax and \$-16,%rsp # shouldn't be formally required @@ -3707,8 +3724,10 @@ $code.=<<___; jnz .Lgather lea (%r10),%rsp +.cfi_def_cfa_register %rsp ret .LSEH_end_bn_gather5: +.cfi_endproc .size bn_gather5,.-bn_gather5 ___ } @@ -3911,4 +3930,4 @@ ___ $code =~ s/\`([^\`]*)\`/eval($1)/gem; print $code; -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/bn_test.cc b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/bn_test.cc index be0a86e0..a61d6e1b 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/bn_test.cc +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/bn_test.cc @@ -86,6 +86,7 @@ #include #include "./internal.h" +#include "./rsaz_exp.h" #include "../../internal.h" #include "../../test/abi_test.h" #include "../../test/file_test.h" @@ -2403,3 +2404,84 @@ TEST_F(BNTest, BNMulMontABI) { } } #endif // OPENSSL_BN_ASM_MONT && SUPPORTS_ABI_TEST + +#if defined(OPENSSL_BN_ASM_MONT5) && defined(SUPPORTS_ABI_TEST) +TEST_F(BNTest, BNMulMont5ABI) { + for (size_t words : {4, 5, 6, 7, 8, 16, 32}) { + SCOPED_TRACE(words); + + bssl::UniquePtr m(BN_new()); + ASSERT_TRUE(m); + ASSERT_TRUE(BN_set_bit(m.get(), 0)); + ASSERT_TRUE(BN_set_bit(m.get(), words * BN_BITS2 - 1)); + bssl::UniquePtr mont( + BN_MONT_CTX_new_for_modulus(m.get(), ctx())); + ASSERT_TRUE(mont); + + std::vector r(words), a(words), b(words), table(words * 32); + a[0] = 1; + b[0] = 42; + + bn_mul_mont(r.data(), a.data(), b.data(), mont->N.d, mont->n0, words); + CHECK_ABI(bn_scatter5, r.data(), words, table.data(), 13); + for (size_t i = 0; i < 32; i++) { + bn_mul_mont(r.data(), a.data(), b.data(), mont->N.d, mont->n0, words); + bn_scatter5(r.data(), words, table.data(), i); + } + CHECK_ABI(bn_gather5, r.data(), words, table.data(), 13); + + CHECK_ABI(bn_mul_mont_gather5, r.data(), r.data(), table.data(), m->d, + mont->n0, words, 13); + CHECK_ABI(bn_mul_mont_gather5, r.data(), a.data(), table.data(), m->d, + mont->n0, words, 13); + + if (words % 8 == 0) { + CHECK_ABI(bn_power5, r.data(), r.data(), table.data(), m->d, mont->n0, + words, 13); + CHECK_ABI(bn_power5, r.data(), a.data(), table.data(), m->d, mont->n0, + words, 13); + EXPECT_EQ(1, CHECK_ABI(bn_from_montgomery, r.data(), r.data(), nullptr, + m->d, mont->n0, words)); + EXPECT_EQ(1, CHECK_ABI(bn_from_montgomery, r.data(), a.data(), nullptr, + m->d, mont->n0, words)); + } else { + EXPECT_EQ(0, CHECK_ABI(bn_from_montgomery, r.data(), r.data(), nullptr, + m->d, mont->n0, words)); + EXPECT_EQ(0, CHECK_ABI(bn_from_montgomery, r.data(), a.data(), nullptr, + m->d, mont->n0, words)); + } + } +} +#endif // OPENSSL_BN_ASM_MONT5 && SUPPORTS_ABI_TEST + +#if defined(RSAZ_ENABLED) && defined(SUPPORTS_ABI_TEST) +TEST_F(BNTest, RSAZABI) { + if (!rsaz_avx2_capable()) { + return; + } + + alignas(64) BN_ULONG table[32 * 18] = {0}; + alignas(64) BN_ULONG rsaz1[40], rsaz2[40], rsaz3[40], n_rsaz[40]; + BN_ULONG norm[16], n_norm[16]; + + OPENSSL_memset(norm, 0x42, sizeof(norm)); + OPENSSL_memset(n_norm, 0x99, sizeof(n_norm)); + + bssl::UniquePtr n(BN_new()); + ASSERT_TRUE(n); + ASSERT_TRUE(bn_set_words(n.get(), n_norm, 16)); + bssl::UniquePtr mont( + BN_MONT_CTX_new_for_modulus(n.get(), nullptr)); + ASSERT_TRUE(mont); + const BN_ULONG k = mont->n0[0]; + + CHECK_ABI(rsaz_1024_norm2red_avx2, rsaz1, norm); + CHECK_ABI(rsaz_1024_norm2red_avx2, n_rsaz, n_norm); + CHECK_ABI(rsaz_1024_sqr_avx2, rsaz2, rsaz1, n_rsaz, k, 1); + CHECK_ABI(rsaz_1024_sqr_avx2, rsaz3, rsaz2, n_rsaz, k, 4); + CHECK_ABI(rsaz_1024_mul_avx2, rsaz3, rsaz1, rsaz2, n_rsaz, k); + CHECK_ABI(rsaz_1024_scatter5_avx2, table, rsaz3, 7); + CHECK_ABI(rsaz_1024_gather5_avx2, rsaz1, table, 7); + CHECK_ABI(rsaz_1024_red2norm_avx2, norm, rsaz1); +} +#endif // RSAZ_ENABLED && SUPPORTS_ABI_TEST diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/ctx.c b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/ctx.c index af50de93..1926e80b 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/ctx.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/ctx.c @@ -54,6 +54,7 @@ #include +#include #include #include @@ -62,63 +63,46 @@ #include "../../internal.h" -// How many bignums are in each "pool item"; -#define BN_CTX_POOL_SIZE 16 // The stack frame info is resizing, set a first-time expansion size; #define BN_CTX_START_FRAMES 32 -// A bundle of bignums that can be linked with other bundles -typedef struct bignum_pool_item { - // The bignum values - BIGNUM vals[BN_CTX_POOL_SIZE]; - // Linked-list admin - struct bignum_pool_item *prev, *next; -} BN_POOL_ITEM; - - -typedef struct bignum_pool { - // Linked-list admin - BN_POOL_ITEM *head, *current, *tail; - // Stack depth and allocation size - unsigned used, size; -} BN_POOL; - -static void BN_POOL_init(BN_POOL *); -static void BN_POOL_finish(BN_POOL *); -static BIGNUM *BN_POOL_get(BN_POOL *); -static void BN_POOL_release(BN_POOL *, unsigned int); - // BN_STACK -// A wrapper to manage the "stack frames" -typedef struct bignum_ctx_stack { - // Array of indexes into the bignum stack - unsigned int *indexes; +// A |BN_STACK| is a stack of |size_t| values. +typedef struct { + // Array of indexes into |ctx->bignums|. + size_t *indexes; // Number of stack frames, and the size of the allocated array - unsigned int depth, size; + size_t depth, size; } BN_STACK; -static void BN_STACK_init(BN_STACK *); -static void BN_STACK_finish(BN_STACK *); -static int BN_STACK_push(BN_STACK *, unsigned int); -static unsigned int BN_STACK_pop(BN_STACK *); +static void BN_STACK_init(BN_STACK *); +static void BN_STACK_cleanup(BN_STACK *); +static int BN_STACK_push(BN_STACK *, size_t idx); +static size_t BN_STACK_pop(BN_STACK *); // BN_CTX +DEFINE_STACK_OF(BIGNUM) + // The opaque BN_CTX type struct bignum_ctx { - // The bignum bundles - BN_POOL pool; - // The "stack frames", if you will + // bignums is the stack of |BIGNUM|s managed by this |BN_CTX|. + STACK_OF(BIGNUM) *bignums; + // stack is the stack of |BN_CTX_start| frames. It is the value of |used| at + // the time |BN_CTX_start| was called. BN_STACK stack; - // The number of bignums currently assigned - unsigned int used; - // Depth of stack overflow - int err_stack; - // Block "gets" until an "end" (compatibility behaviour) - int too_many; + // used is the number of |BIGNUM|s from |bignums| that have been used. + size_t used; + // error is one if any operation on this |BN_CTX| failed. All subsequent + // operations will fail. + char error; + // defer_error is one if an operation on this |BN_CTX| has failed, but no + // error has been pushed to the queue yet. This is used to defer errors from + // |BN_CTX_start| to |BN_CTX_get|. + char defer_error; }; BN_CTX *BN_CTX_new(void) { @@ -129,11 +113,11 @@ BN_CTX *BN_CTX_new(void) { } // Initialise the structure - BN_POOL_init(&ret->pool); + ret->bignums = NULL; BN_STACK_init(&ret->stack); ret->used = 0; - ret->err_stack = 0; - ret->too_many = 0; + ret->error = 0; + ret->defer_error = 0; return ret; } @@ -142,57 +126,69 @@ void BN_CTX_free(BN_CTX *ctx) { return; } - BN_STACK_finish(&ctx->stack); - BN_POOL_finish(&ctx->pool); + sk_BIGNUM_pop_free(ctx->bignums, BN_free); + BN_STACK_cleanup(&ctx->stack); OPENSSL_free(ctx); } void BN_CTX_start(BN_CTX *ctx) { - // If we're already overflowing ... - if (ctx->err_stack || ctx->too_many) { - ctx->err_stack++; - } else if (!BN_STACK_push(&ctx->stack, ctx->used)) { - // (Try to) get a new frame pointer - OPENSSL_PUT_ERROR(BN, BN_R_TOO_MANY_TEMPORARY_VARIABLES); - ctx->err_stack++; + if (ctx->error) { + // Once an operation has failed, |ctx->stack| no longer matches the number + // of |BN_CTX_end| calls to come. Do nothing. + return; + } + + if (!BN_STACK_push(&ctx->stack, ctx->used)) { + ctx->error = 1; + // |BN_CTX_start| cannot fail, so defer the error to |BN_CTX_get|. + ctx->defer_error = 1; } } BIGNUM *BN_CTX_get(BN_CTX *ctx) { - BIGNUM *ret; - if (ctx->err_stack || ctx->too_many) { + // Once any operation has failed, they all do. + if (ctx->error) { + if (ctx->defer_error) { + OPENSSL_PUT_ERROR(BN, BN_R_TOO_MANY_TEMPORARY_VARIABLES); + ctx->defer_error = 0; + } return NULL; } - ret = BN_POOL_get(&ctx->pool); - if (ret == NULL) { - // Setting too_many prevents repeated "get" attempts from - // cluttering the error stack. - ctx->too_many = 1; - OPENSSL_PUT_ERROR(BN, BN_R_TOO_MANY_TEMPORARY_VARIABLES); - return NULL; + if (ctx->bignums == NULL) { + ctx->bignums = sk_BIGNUM_new_null(); + if (ctx->bignums == NULL) { + OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE); + ctx->error = 1; + return NULL; + } } - // OK, make sure the returned bignum is "zero" + if (ctx->used == sk_BIGNUM_num(ctx->bignums)) { + BIGNUM *bn = BN_new(); + if (bn == NULL || !sk_BIGNUM_push(ctx->bignums, bn)) { + OPENSSL_PUT_ERROR(BN, BN_R_TOO_MANY_TEMPORARY_VARIABLES); + BN_free(bn); + ctx->error = 1; + return NULL; + } + } + + BIGNUM *ret = sk_BIGNUM_value(ctx->bignums, ctx->used); BN_zero(ret); + // This is bounded by |sk_BIGNUM_num|, so it cannot overflow. ctx->used++; return ret; } void BN_CTX_end(BN_CTX *ctx) { - if (ctx->err_stack) { - ctx->err_stack--; - } else { - unsigned int fp = BN_STACK_pop(&ctx->stack); - // Does this stack frame have anything to release? - if (fp < ctx->used) { - BN_POOL_release(&ctx->pool, ctx->used - fp); - } - - ctx->used = fp; - // Unjam "too_many" in case "get" had failed - ctx->too_many = 0; + if (ctx->error) { + // Once an operation has failed, |ctx->stack| no longer matches the number + // of |BN_CTX_end| calls to come. Do nothing. + return; } + + ctx->used = BN_STACK_pop(&ctx->stack); } @@ -203,101 +199,34 @@ static void BN_STACK_init(BN_STACK *st) { st->depth = st->size = 0; } -static void BN_STACK_finish(BN_STACK *st) { +static void BN_STACK_cleanup(BN_STACK *st) { OPENSSL_free(st->indexes); } -static int BN_STACK_push(BN_STACK *st, unsigned int idx) { +static int BN_STACK_push(BN_STACK *st, size_t idx) { if (st->depth == st->size) { - // Need to expand - unsigned int newsize = - (st->size ? (st->size * 3 / 2) : BN_CTX_START_FRAMES); - unsigned int *newitems = OPENSSL_malloc(newsize * sizeof(unsigned int)); - if (!newitems) { + // This function intentionally does not push to the error queue on error. + // Error-reporting is deferred to |BN_CTX_get|. + size_t new_size = st->size != 0 ? st->size * 3 / 2 : BN_CTX_START_FRAMES; + if (new_size <= st->size || new_size > ((size_t)-1) / sizeof(size_t)) { return 0; } - if (st->depth) { - OPENSSL_memcpy(newitems, st->indexes, st->depth * sizeof(unsigned int)); + size_t *new_indexes = + OPENSSL_realloc(st->indexes, new_size * sizeof(size_t)); + if (new_indexes == NULL) { + return 0; } - OPENSSL_free(st->indexes); - st->indexes = newitems; - st->size = newsize; + st->indexes = new_indexes; + st->size = new_size; } - st->indexes[(st->depth)++] = idx; + st->indexes[st->depth] = idx; + st->depth++; return 1; } -static unsigned int BN_STACK_pop(BN_STACK *st) { - return st->indexes[--(st->depth)]; -} - - -static void BN_POOL_init(BN_POOL *p) { - p->head = p->current = p->tail = NULL; - p->used = p->size = 0; -} - -static void BN_POOL_finish(BN_POOL *p) { - while (p->head) { - for (size_t i = 0; i < BN_CTX_POOL_SIZE; i++) { - BN_clear_free(&p->head->vals[i]); - } - - p->current = p->head->next; - OPENSSL_free(p->head); - p->head = p->current; - } -} - -static BIGNUM *BN_POOL_get(BN_POOL *p) { - if (p->used == p->size) { - BN_POOL_ITEM *item = OPENSSL_malloc(sizeof(BN_POOL_ITEM)); - if (!item) { - return NULL; - } - - // Initialise the structure - for (size_t i = 0; i < BN_CTX_POOL_SIZE; i++) { - BN_init(&item->vals[i]); - } - - item->prev = p->tail; - item->next = NULL; - // Link it in - if (!p->head) { - p->head = p->current = p->tail = item; - } else { - p->tail->next = item; - p->tail = item; - p->current = item; - } - - p->size += BN_CTX_POOL_SIZE; - p->used++; - // Return the first bignum from the new pool - return item->vals; - } - - if (!p->used) { - p->current = p->head; - } else if ((p->used % BN_CTX_POOL_SIZE) == 0) { - p->current = p->current->next; - } - - return p->current->vals + ((p->used++) % BN_CTX_POOL_SIZE); -} - -static void BN_POOL_release(BN_POOL *p, unsigned int num) { - unsigned int offset = (p->used - 1) % BN_CTX_POOL_SIZE; - p->used -= num; - - while (num--) { - if (!offset) { - offset = BN_CTX_POOL_SIZE - 1; - p->current = p->current->prev; - } else { - offset--; - } - } +static size_t BN_STACK_pop(BN_STACK *st) { + assert(st->depth > 0); + st->depth--; + return st->indexes[st->depth]; } diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/exponentiation.c b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/exponentiation.c index 1b9680fb..8d4a5c8b 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/exponentiation.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/exponentiation.c @@ -117,26 +117,8 @@ #include #include "internal.h" - - -#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) -#define OPENSSL_BN_ASM_MONT5 -#define RSAZ_ENABLED - #include "rsaz_exp.h" -void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap, - const BN_ULONG *table, const BN_ULONG *np, - const BN_ULONG *n0, int num, int power); -void bn_scatter5(const BN_ULONG *inp, size_t num, BN_ULONG *table, - size_t power); -void bn_gather5(BN_ULONG *out, size_t num, BN_ULONG *table, size_t power); -void bn_power5(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *table, - const BN_ULONG *np, const BN_ULONG *n0, int num, int power); -int bn_from_montgomery(BN_ULONG *rp, const BN_ULONG *ap, - const BN_ULONG *not_used, const BN_ULONG *np, - const BN_ULONG *n0, int num); -#endif int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { int i, bits, ret = 0; @@ -632,10 +614,9 @@ int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, BN_MONT_CTX *new_mont = NULL; BN_CTX_start(ctx); - BIGNUM *d = BN_CTX_get(ctx); BIGNUM *r = BN_CTX_get(ctx); val[0] = BN_CTX_get(ctx); - if (!d || !r || !val[0]) { + if (r == NULL || val[0] == NULL) { goto err; } @@ -657,7 +638,9 @@ int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, goto err; } if (window > 1) { - if (!BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx)) { + BIGNUM *d = BN_CTX_get(ctx); + if (d == NULL || + !BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx)) { goto err; } for (int i = 1; i < 1 << (window - 1); i++) { @@ -974,12 +957,12 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, alignas(MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH) BN_ULONG storage[MOD_EXP_CTIME_STORAGE_LEN]; #endif -#ifdef RSAZ_ENABLED - // If the size of the operands allow it, perform the optimized - // RSAZ exponentiation. For further information see - // crypto/bn/rsaz_exp.c and accompanying assembly modules. - if ((16 == a->width) && (16 == p->width) && (BN_num_bits(m) == 1024) && - rsaz_avx2_eligible()) { +#if defined(RSAZ_ENABLED) + // If the size of the operands allow it, perform the optimized RSAZ + // exponentiation. For further information see crypto/fipsmodule/bn/rsaz_exp.c + // and accompanying assembly modules. + if (a->width == 16 && p->width == 16 && BN_num_bits(m) == 1024 && + rsaz_avx2_preferred()) { if (!bn_wexpand(rr, 16)) { goto err; } diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/internal.h b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/internal.h index 0bcc031f..c1e60fe5 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/internal.h +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/internal.h @@ -340,10 +340,61 @@ int bn_rand_secret_range(BIGNUM *r, int *out_is_uniform, BN_ULONG min_inclusive, (defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || \ defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)) #define OPENSSL_BN_ASM_MONT +// bn_mul_mont writes |ap| * |bp| mod |np| to |rp|, each |num| words +// long. Inputs and outputs are in Montgomery form. |n0| is a pointer to the +// corresponding field in |BN_MONT_CTX|. It returns one if |bn_mul_mont| handles +// inputs of this size and zero otherwise. +// +// TODO(davidben): The x86_64 implementation expects a 32-bit input and masks +// off upper bits. The aarch64 implementation expects a 64-bit input and does +// not. |size_t| is the safer option but not strictly correct for x86_64. But +// this function implicitly already has a bound on the size of |num| because it +// internally creates |num|-sized stack allocation. +// +// See also discussion in |ToWord| in abi_test.h for notes on smaller-than-word +// inputs. int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, - const BN_ULONG *np, const BN_ULONG *n0, int num); + const BN_ULONG *np, const BN_ULONG *n0, size_t num); #endif +#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) +#define OPENSSL_BN_ASM_MONT5 + +// bn_mul_mont_gather5 multiples loads index |power| of |table|, multiplies it +// by |ap| modulo |np|, and stores the result in |rp|. The values are |num| +// words long and represented in Montgomery form. |n0| is a pointer to the +// corresponding field in |BN_MONT_CTX|. +void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap, + const BN_ULONG *table, const BN_ULONG *np, + const BN_ULONG *n0, int num, int power); + +// bn_scatter5 stores |inp| to index |power| of |table|. |inp| and each entry of +// |table| are |num| words long. |power| must be less than 32. |table| must be +// 32*|num| words long. +void bn_scatter5(const BN_ULONG *inp, size_t num, BN_ULONG *table, + size_t power); + +// bn_gather5 loads index |power| of |table| and stores it in |out|. |out| and +// each entry of |table| are |num| words long. |power| must be less than 32. +void bn_gather5(BN_ULONG *out, size_t num, BN_ULONG *table, size_t power); + +// bn_power5 squares |ap| five times and multiplies it by the value stored at +// index |power| of |table|, modulo |np|. It stores the result in |rp|. The +// values are |num| words long and represented in Montgomery form. |n0| is a +// pointer to the corresponding field in |BN_MONT_CTX|. |num| must be divisible +// by 8. +void bn_power5(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *table, + const BN_ULONG *np, const BN_ULONG *n0, int num, int power); + +// bn_from_montgomery converts |ap| from Montgomery form modulo |np| and writes +// the result in |rp|, each of which is |num| words long. It returns one on +// success and zero if it cannot handle inputs of length |num|. |n0| is a +// pointer to the corresponding field in |BN_MONT_CTX|. +int bn_from_montgomery(BN_ULONG *rp, const BN_ULONG *ap, + const BN_ULONG *not_used, const BN_ULONG *np, + const BN_ULONG *n0, int num); +#endif // !OPENSSL_NO_ASM && OPENSSL_X86_64 + uint64_t bn_mont_n0(const BIGNUM *n); // bn_mod_exp_base_2_consttime calculates r = 2**p (mod n). |p| must be larger diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/prime.c b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/prime.c index b417d4ff..1f3510d9 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/prime.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/prime.c @@ -316,7 +316,7 @@ static const uint16_t kPrimes[] = { // // This table is generated using the algorithm of FIPS PUB 186-4 // Digital Signature Standard (DSS), section F.1, page 117. -// (https://dx.doi.org/10.6028/NIST.FIPS.186-4) +// (https://doi.org/10.6028/NIST.FIPS.186-4) // The following magma script was used to generate the output: // securitybits:=125; // k:=1024; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/rsaz_exp.c b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/rsaz_exp.c index 0e3221c3..7e15aaf9 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/rsaz_exp.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/rsaz_exp.c @@ -12,28 +12,16 @@ * (2) University of Haifa, Israel */ -#include - -#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) - #include "rsaz_exp.h" +#if defined(RSAZ_ENABLED) + #include #include "internal.h" #include "../../internal.h" -// See crypto/bn/asm/rsaz-avx2.pl for further details. -void rsaz_1024_norm2red_avx2(void *red, const void *norm); -void rsaz_1024_mul_avx2(void *ret, const void *a, const void *b, const void *n, - BN_ULONG k); -void rsaz_1024_sqr_avx2(void *ret, const void *a, const void *n, BN_ULONG k, - int cnt); -void rsaz_1024_scatter5_avx2(void *tbl, const void *val, int i); -void rsaz_1024_gather5_avx2(void *val, const void *tbl, int i); -void rsaz_1024_red2norm_avx2(void *norm, const void *red); - // one is 1 in RSAZ's representation. alignas(64) static const BN_ULONG one[40] = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -49,22 +37,21 @@ void RSAZ_1024_mod_exp_avx2(BN_ULONG result_norm[16], const BN_ULONG exponent[16], const BN_ULONG m_norm[16], const BN_ULONG RR[16], BN_ULONG k0, - BN_ULONG storage_words[MOD_EXP_CTIME_STORAGE_LEN]) { + BN_ULONG storage[MOD_EXP_CTIME_STORAGE_LEN]) { OPENSSL_STATIC_ASSERT(MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH % 64 == 0, "MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH is too small"); - unsigned char *storage = (unsigned char *)storage_words; assert((uintptr_t)storage % 64 == 0); - unsigned char *a_inv, *m, *result, *table_s = storage + (320 * 3), - *R2 = table_s; // borrow + BN_ULONG *a_inv, *m, *result, *table_s = storage + 40 * 3, *R2 = table_s; + // Note |R2| aliases |table_s|. if (((((uintptr_t)storage & 4095) + 320) >> 12) != 0) { result = storage; - a_inv = storage + 320; - m = storage + (320 * 2); // should not cross page + a_inv = storage + 40; + m = storage + 40 * 2; // should not cross page } else { m = storage; // should not cross page - result = storage + 320; - a_inv = storage + (320 * 2); + result = storage + 40; + a_inv = storage + 40 * 2; } rsaz_1024_norm2red_avx2(m, m_norm); @@ -236,4 +223,4 @@ void RSAZ_1024_mod_exp_avx2(BN_ULONG result_norm[16], OPENSSL_cleanse(storage, MOD_EXP_CTIME_STORAGE_LEN * sizeof(BN_ULONG)); } -#endif // OPENSSL_X86_64 +#endif // RSAZ_ENABLED diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/rsaz_exp.h b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/rsaz_exp.h index b6aea144..3b061921 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/bn/rsaz_exp.h +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/bn/rsaz_exp.h @@ -16,9 +16,18 @@ #define OPENSSL_HEADER_BN_RSAZ_EXP_H #include +#include #include "internal.h" +#if defined(__cplusplus) +extern "C" { +#endif + +#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) +#define RSAZ_ENABLED + + // RSAZ_1024_mod_exp_avx2 sets |result| to |base_norm| raised to |exponent| // modulo |m_norm|. |base_norm| must be fully-reduced and |exponent| must have // the high bit set (it is 1024 bits wide). |RR| and |k0| must be |RR| and |n0|, @@ -31,8 +40,65 @@ void RSAZ_1024_mod_exp_avx2(BN_ULONG result[16], const BN_ULONG base_norm[16], BN_ULONG k0, BN_ULONG storage_words[MOD_EXP_CTIME_STORAGE_LEN]); -// rsaz_avx2_eligible returns one if |RSAZ_1024_mod_exp_avx2| should be used and -// zero otherwise. -int rsaz_avx2_eligible(void); +OPENSSL_INLINE int rsaz_avx2_capable(void) { + const uint32_t *cap = OPENSSL_ia32cap_get(); + return (cap[2] & (1 << 5)) != 0; // AVX2 +} + +OPENSSL_INLINE int rsaz_avx2_preferred(void) { + const uint32_t *cap = OPENSSL_ia32cap_get(); + static const uint32_t kBMI2AndADX = (1 << 8) | (1 << 19); + if ((cap[2] & kBMI2AndADX) == kBMI2AndADX) { + // If BMI2 and ADX are available, x86_64-mont5.pl is faster. + return 0; + } + return (cap[2] & (1 << 5)) != 0; // AVX2 +} + + +// Assembly functions. + +// RSAZ represents 1024-bit integers using unsaturated 29-bit limbs stored in +// 64-bit integers. This requires 36 limbs but padded up to 40. +// +// See crypto/bn/asm/rsaz-avx2.pl for further details. + +// rsaz_1024_norm2red_avx2 converts |norm| from |BIGNUM| to RSAZ representation +// and writes the result to |red|. +void rsaz_1024_norm2red_avx2(BN_ULONG red[40], const BN_ULONG norm[16]); + +// rsaz_1024_mul_avx2 computes |a| * |b| mod |n| and writes the result to |ret|. +// Inputs and outputs are in Montgomery form, using RSAZ's representation. |k| +// is -|n|^-1 mod 2^64 or |n0| from |BN_MONT_CTX|. +void rsaz_1024_mul_avx2(BN_ULONG ret[40], const BN_ULONG a[40], + const BN_ULONG b[40], const BN_ULONG n[40], BN_ULONG k); + +// rsaz_1024_mul_avx2 computes |a|^(2*|count|) mod |n| and writes the result to +// |ret|. Inputs and outputs are in Montgomery form, using RSAZ's +// representation. |k| is -|n|^-1 mod 2^64 or |n0| from |BN_MONT_CTX|. +void rsaz_1024_sqr_avx2(BN_ULONG ret[40], const BN_ULONG a[40], + const BN_ULONG n[40], BN_ULONG k, int count); + +// rsaz_1024_scatter5_avx2 stores |val| at index |i| of |tbl|. |i| must be +// positive and at most 31. Note the table only uses 18 |BN_ULONG|s per entry +// instead of 40. It packs two 29-bit limbs into each |BN_ULONG| and only stores +// 36 limbs rather than the padded 40. +void rsaz_1024_scatter5_avx2(BN_ULONG tbl[32 * 18], const BN_ULONG val[40], + int i); + +// rsaz_1024_gather5_avx2 loads index |i| of |tbl| and writes it to |val|. +void rsaz_1024_gather5_avx2(BN_ULONG val[40], const BN_ULONG tbl[32 * 18], + int i); + +// rsaz_1024_red2norm_avx2 converts |red| from RSAZ to |BIGNUM| representation +// and writes the result to |norm|. +void rsaz_1024_red2norm_avx2(BN_ULONG norm[16], const BN_ULONG red[40]); + + +#endif // !OPENSSL_NO_ASM && OPENSSL_X86_64 + +#if defined(__cplusplus) +} // extern "C" +#endif #endif // OPENSSL_HEADER_BN_RSAZ_EXP_H diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/cipher/e_aes.c b/third_party/boringssl/kit/src/crypto/fipsmodule/cipher/e_aes.c index f7c145b9..1ea012dd 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/cipher/e_aes.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/cipher/e_aes.c @@ -46,6 +46,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== */ +#include #include #include @@ -63,10 +64,6 @@ #include "../modes/internal.h" #include "../delocate.h" -#if defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64) -#include -#endif - OPENSSL_MSVC_PRAGMA(warning(push)) OPENSSL_MSVC_PRAGMA(warning(disable: 4702)) // Unreachable code. @@ -84,13 +81,13 @@ typedef struct { } EVP_AES_KEY; typedef struct { + GCM128_CONTEXT gcm; union { double align; AES_KEY ks; } ks; // AES key schedule to use int key_set; // Set if key initialised int iv_set; // Set if an iv is set - GCM128_CONTEXT gcm; uint8_t *iv; // Temporary IV store int ivlen; // IV length int taglen; @@ -113,17 +110,23 @@ static int aes_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, dat->stream.cbc = aes_hw_cbc_encrypt; } } else if (bsaes_capable() && mode == EVP_CIPH_CBC_MODE) { - ret = AES_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks); - dat->block = AES_decrypt; + ret = aes_nohw_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks); + // If |dat->stream.cbc| is provided, |dat->block| is never used. + dat->block = NULL; dat->stream.cbc = bsaes_cbc_encrypt; } else if (vpaes_capable()) { ret = vpaes_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks); dat->block = vpaes_decrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? vpaes_cbc_encrypt : NULL; } else { - ret = AES_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks); - dat->block = AES_decrypt; - dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? AES_cbc_encrypt : NULL; + ret = aes_nohw_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks); + dat->block = aes_nohw_decrypt; + dat->stream.cbc = NULL; +#if defined(AES_NOHW_CBC) + if (mode == EVP_CIPH_CBC_MODE) { + dat->stream.cbc = aes_nohw_cbc_encrypt; + } +#endif } } else if (hwaes_capable()) { ret = aes_hw_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks); @@ -135,17 +138,31 @@ static int aes_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, dat->stream.ctr = aes_hw_ctr32_encrypt_blocks; } } else if (bsaes_capable() && mode == EVP_CIPH_CTR_MODE) { - ret = AES_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks); - dat->block = AES_encrypt; + ret = aes_nohw_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks); + // If |dat->stream.ctr| is provided, |dat->block| is never used. + dat->block = NULL; dat->stream.ctr = bsaes_ctr32_encrypt_blocks; } else if (vpaes_capable()) { ret = vpaes_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks); dat->block = vpaes_encrypt; - dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? vpaes_cbc_encrypt : NULL; + dat->stream.cbc = NULL; + if (mode == EVP_CIPH_CBC_MODE) { + dat->stream.cbc = vpaes_cbc_encrypt; + } +#if defined(VPAES_CTR32) + if (mode == EVP_CIPH_CTR_MODE) { + dat->stream.ctr = vpaes_ctr32_encrypt_blocks; + } +#endif } else { - ret = AES_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks); - dat->block = AES_encrypt; - dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? AES_cbc_encrypt : NULL; + ret = aes_nohw_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks); + dat->block = aes_nohw_encrypt; + dat->stream.cbc = NULL; +#if defined(AES_NOHW_CBC) + if (mode == EVP_CIPH_CBC_MODE) { + dat->stream.cbc = aes_nohw_cbc_encrypt; + } +#endif } if (ret < 0) { @@ -226,12 +243,12 @@ ctr128_f aes_ctr_set_key(AES_KEY *aes_key, GCM128_KEY *gcm_key, } if (bsaes_capable()) { - AES_set_encrypt_key(key, key_bytes * 8, aes_key); + aes_nohw_set_encrypt_key(key, key_bytes * 8, aes_key); if (gcm_key != NULL) { - CRYPTO_gcm128_init_key(gcm_key, aes_key, AES_encrypt, 0); + CRYPTO_gcm128_init_key(gcm_key, aes_key, aes_nohw_encrypt, 0); } if (out_block) { - *out_block = AES_encrypt; + *out_block = aes_nohw_encrypt; } return bsaes_ctr32_encrypt_blocks; } @@ -244,22 +261,54 @@ ctr128_f aes_ctr_set_key(AES_KEY *aes_key, GCM128_KEY *gcm_key, if (gcm_key != NULL) { CRYPTO_gcm128_init_key(gcm_key, aes_key, vpaes_encrypt, 0); } +#if defined(VPAES_CTR32) + return vpaes_ctr32_encrypt_blocks; +#else return NULL; +#endif } - AES_set_encrypt_key(key, key_bytes * 8, aes_key); + aes_nohw_set_encrypt_key(key, key_bytes * 8, aes_key); if (gcm_key != NULL) { - CRYPTO_gcm128_init_key(gcm_key, aes_key, AES_encrypt, 0); + CRYPTO_gcm128_init_key(gcm_key, aes_key, aes_nohw_encrypt, 0); } if (out_block) { - *out_block = AES_encrypt; + *out_block = aes_nohw_encrypt; } return NULL; } +#if defined(OPENSSL_32_BIT) +#define EVP_AES_GCM_CTX_PADDING (4+8) +#else +#define EVP_AES_GCM_CTX_PADDING 8 +#endif + +static EVP_AES_GCM_CTX *aes_gcm_from_cipher_ctx(EVP_CIPHER_CTX *ctx) { +#if defined(__GNUC__) || defined(__clang__) + OPENSSL_STATIC_ASSERT( + alignof(EVP_AES_GCM_CTX) <= 16, + "EVP_AES_GCM_CTX needs more alignment than this function provides"); +#endif + + // |malloc| guarantees up to 4-byte alignment on 32-bit and 8-byte alignment + // on 64-bit systems, so we need to adjust to reach 16-byte alignment. + assert(ctx->cipher->ctx_size == + sizeof(EVP_AES_GCM_CTX) + EVP_AES_GCM_CTX_PADDING); + + char *ptr = ctx->cipher_data; +#if defined(OPENSSL_32_BIT) + assert((uintptr_t)ptr % 4 == 0); + ptr += (uintptr_t)ptr & 4; +#endif + assert((uintptr_t)ptr % 8 == 0); + ptr += (uintptr_t)ptr & 8; + return (EVP_AES_GCM_CTX *)ptr; +} + static int aes_gcm_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, const uint8_t *iv, int enc) { - EVP_AES_GCM_CTX *gctx = ctx->cipher_data; + EVP_AES_GCM_CTX *gctx = aes_gcm_from_cipher_ctx(ctx); if (!iv && !key) { return 1; } @@ -290,7 +339,7 @@ static int aes_gcm_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, } static void aes_gcm_cleanup(EVP_CIPHER_CTX *c) { - EVP_AES_GCM_CTX *gctx = c->cipher_data; + EVP_AES_GCM_CTX *gctx = aes_gcm_from_cipher_ctx(c); OPENSSL_cleanse(&gctx->gcm, sizeof(gctx->gcm)); if (gctx->iv != c->iv) { OPENSSL_free(gctx->iv); @@ -314,7 +363,7 @@ static void ctr64_inc(uint8_t *counter) { } static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { - EVP_AES_GCM_CTX *gctx = c->cipher_data; + EVP_AES_GCM_CTX *gctx = aes_gcm_from_cipher_ctx(c); switch (type) { case EVP_CTRL_INIT: gctx->key_set = 0; @@ -406,7 +455,10 @@ static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; - EVP_AES_GCM_CTX *gctx_out = out->cipher_data; + EVP_AES_GCM_CTX *gctx_out = aes_gcm_from_cipher_ctx(out); + // |EVP_CIPHER_CTX_copy| copies this generically, but we must redo it in + // case |out->cipher_data| and |in->cipher_data| are differently aligned. + OPENSSL_memcpy(gctx_out, gctx, sizeof(EVP_AES_GCM_CTX)); if (gctx->iv == c->iv) { gctx_out->iv = out->iv; } else { @@ -426,7 +478,7 @@ static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { static int aes_gcm_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, size_t len) { - EVP_AES_GCM_CTX *gctx = ctx->cipher_data; + EVP_AES_GCM_CTX *gctx = aes_gcm_from_cipher_ctx(ctx); // If not set up, return error if (!gctx->key_set) { @@ -540,8 +592,8 @@ DEFINE_LOCAL_DATA(EVP_CIPHER, aes_128_gcm_generic) { out->block_size = 1; out->key_len = 16; out->iv_len = 12; - out->ctx_size = sizeof(EVP_AES_GCM_CTX); - out->flags = EVP_CIPH_GCM_MODE | EVP_CIPH_CUSTOM_IV | + out->ctx_size = sizeof(EVP_AES_GCM_CTX) + EVP_AES_GCM_CTX_PADDING; + out->flags = EVP_CIPH_GCM_MODE | EVP_CIPH_CUSTOM_IV | EVP_CIPH_CUSTOM_COPY | EVP_CIPH_FLAG_CUSTOM_CIPHER | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT | EVP_CIPH_FLAG_AEAD_CIPHER; out->init = aes_gcm_init_key; @@ -608,8 +660,8 @@ DEFINE_LOCAL_DATA(EVP_CIPHER, aes_192_gcm_generic) { out->block_size = 1; out->key_len = 24; out->iv_len = 12; - out->ctx_size = sizeof(EVP_AES_GCM_CTX); - out->flags = EVP_CIPH_GCM_MODE | EVP_CIPH_CUSTOM_IV | + out->ctx_size = sizeof(EVP_AES_GCM_CTX) + EVP_AES_GCM_CTX_PADDING; + out->flags = EVP_CIPH_GCM_MODE | EVP_CIPH_CUSTOM_IV | EVP_CIPH_CUSTOM_COPY | EVP_CIPH_FLAG_CUSTOM_CIPHER | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT | EVP_CIPH_FLAG_AEAD_CIPHER; out->init = aes_gcm_init_key; @@ -676,8 +728,8 @@ DEFINE_LOCAL_DATA(EVP_CIPHER, aes_256_gcm_generic) { out->block_size = 1; out->key_len = 32; out->iv_len = 12; - out->ctx_size = sizeof(EVP_AES_GCM_CTX); - out->flags = EVP_CIPH_GCM_MODE | EVP_CIPH_CUSTOM_IV | + out->ctx_size = sizeof(EVP_AES_GCM_CTX) + EVP_AES_GCM_CTX_PADDING; + out->flags = EVP_CIPH_GCM_MODE | EVP_CIPH_CUSTOM_IV | EVP_CIPH_CUSTOM_COPY | EVP_CIPH_FLAG_CUSTOM_CIPHER | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT | EVP_CIPH_FLAG_AEAD_CIPHER; out->init = aes_gcm_init_key; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/cipher/internal.h b/third_party/boringssl/kit/src/crypto/fipsmodule/cipher/internal.h index 7c739fbd..68efe33d 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/cipher/internal.h +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/cipher/internal.h @@ -116,8 +116,7 @@ struct evp_aead_st { // where |key_bytes| must either be 16, 24 or 32. If not NULL, |*out_block| is // set to a function that encrypts single blocks. If not NULL, |*gcm_key| is // initialised to do GHASH with the given key. It returns a function for -// optimised CTR-mode, or NULL if CTR-mode should be built using -// |*out_block|. +// optimised CTR-mode, or NULL if CTR-mode should be built using |*out_block|. ctr128_f aes_ctr_set_key(AES_KEY *aes_key, GCM128_KEY *gcm_key, block128_f *out_block, const uint8_t *key, size_t key_bytes); diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/delocate.h b/third_party/boringssl/kit/src/crypto/fipsmodule/delocate.h index 59effde1..d6564e48 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/delocate.h +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/delocate.h @@ -20,7 +20,8 @@ #include "../internal.h" -#if defined(BORINGSSL_FIPS) && !defined(OPENSSL_ASAN) && !defined(OPENSSL_MSAN) +#if !defined(BORINGSSL_SHARED_LIBRARY) && defined(BORINGSSL_FIPS) && \ + !defined(OPENSSL_ASAN) && !defined(OPENSSL_MSAN) #define DEFINE_BSS_GET(type, name) \ static type name __attribute__((used)); \ type *name##_bss_get(void) __attribute__((const)); diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/digest/digest.c b/third_party/boringssl/kit/src/crypto/fipsmodule/digest/digest.c index e49d552d..68e81c49 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/digest/digest.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/digest/digest.c @@ -115,8 +115,15 @@ void EVP_MD_CTX_free(EVP_MD_CTX *ctx) { void EVP_MD_CTX_destroy(EVP_MD_CTX *ctx) { EVP_MD_CTX_free(ctx); } +int EVP_DigestFinalXOF(EVP_MD_CTX *ctx, uint8_t *out, size_t len) { + OPENSSL_PUT_ERROR(DIGEST, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return 0; +} + int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in) { - if (in == NULL || in->digest == NULL) { + // |in->digest| may be NULL if this is a signing |EVP_MD_CTX| for, e.g., + // Ed25519 which does not hash with |EVP_MD_CTX|. + if (in == NULL || (in->pctx == NULL && in->digest == NULL)) { OPENSSL_PUT_ERROR(DIGEST, DIGEST_R_INPUT_NOT_INITIALIZED); return 0; } @@ -131,29 +138,34 @@ int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in) { } } - uint8_t *tmp_buf; - if (out->digest != in->digest) { - assert(in->digest->ctx_size != 0); - tmp_buf = OPENSSL_malloc(in->digest->ctx_size); - if (tmp_buf == NULL) { - if (pctx) { - in->pctx_ops->free(pctx); + uint8_t *tmp_buf = NULL; + if (in->digest != NULL) { + if (out->digest != in->digest) { + assert(in->digest->ctx_size != 0); + tmp_buf = OPENSSL_malloc(in->digest->ctx_size); + if (tmp_buf == NULL) { + if (pctx) { + in->pctx_ops->free(pctx); + } + OPENSSL_PUT_ERROR(DIGEST, ERR_R_MALLOC_FAILURE); + return 0; } - OPENSSL_PUT_ERROR(DIGEST, ERR_R_MALLOC_FAILURE); - return 0; + } else { + // |md_data| will be the correct size in this case. It's removed from + // |out| so that |EVP_MD_CTX_cleanup| doesn't free it, and then it's + // reused. + tmp_buf = out->md_data; + out->md_data = NULL; } - } else { - // |md_data| will be the correct size in this case. It's removed from |out| - // so that |EVP_MD_CTX_cleanup| doesn't free it, and then it's reused. - tmp_buf = out->md_data; - out->md_data = NULL; } EVP_MD_CTX_cleanup(out); out->digest = in->digest; out->md_data = tmp_buf; - OPENSSL_memcpy(out->md_data, in->md_data, in->digest->ctx_size); + if (in->digest != NULL) { + OPENSSL_memcpy(out->md_data, in->md_data, in->digest->ctx_size); + } out->pctx = pctx; out->pctx_ops = in->pctx_ops; assert(out->pctx == NULL || out->pctx_ops != NULL); diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/digest/md32_common.h b/third_party/boringssl/kit/src/crypto/fipsmodule/digest/md32_common.h index a0c3665d..07d39d9d 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/digest/md32_common.h +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/digest/md32_common.h @@ -223,12 +223,12 @@ int HASH_UPDATE(HASH_CTX *c, const void *data_, size_t len) { } -void HASH_TRANSFORM(HASH_CTX *c, const uint8_t *data) { +void HASH_TRANSFORM(HASH_CTX *c, const uint8_t data[HASH_CBLOCK]) { HASH_BLOCK_DATA_ORDER(c->h, data, 1); } -int HASH_FINAL(uint8_t *md, HASH_CTX *c) { +int HASH_FINAL(uint8_t out[HASH_DIGEST_LENGTH], HASH_CTX *c) { // |c->data| always has room for at least one byte. A full block would have // been consumed. size_t n = c->num; @@ -258,7 +258,7 @@ int HASH_FINAL(uint8_t *md, HASH_CTX *c) { c->num = 0; OPENSSL_memset(c->data, 0, HASH_CBLOCK); - HASH_MAKE_STRING(c, md); + HASH_MAKE_STRING(c, out); return 1; } diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/asm/p256-x86_64-asm.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/asm/p256-x86_64-asm.pl index 2f5ae86a..6a021dbc 100755 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/asm/p256-x86_64-asm.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/asm/p256-x86_64-asm.pl @@ -488,7 +488,7 @@ $code.=<<___; # void ecp_nistz256_ord_sqr_mont( # uint64_t res[4], # uint64_t a[4], -# int rep); +# uint64_t rep); .globl ecp_nistz256_ord_sqr_mont .type ecp_nistz256_ord_sqr_mont,\@function,3 @@ -4146,4 +4146,4 @@ ___ $code =~ s/\`([^\`]*)\`/eval $1/gem; print $code; -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/asm/p256_beeu-x86_64-asm.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/asm/p256_beeu-x86_64-asm.pl index 0bb65477..c05abba8 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/asm/p256_beeu-x86_64-asm.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/asm/p256_beeu-x86_64-asm.pl @@ -400,4 +400,4 @@ beeu_mod_inverse_vartime: ___ print $code; -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/ec.c b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/ec.c index 90b9d71f..158d66cc 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/ec.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/ec.c @@ -499,8 +499,8 @@ err: struct built_in_groups_st { EC_GROUP *groups[OPENSSL_NUM_BUILT_IN_CURVES]; }; -DEFINE_BSS_GET(struct built_in_groups_st, built_in_groups); -DEFINE_STATIC_MUTEX(built_in_groups_lock); +DEFINE_BSS_GET(struct built_in_groups_st, built_in_groups) +DEFINE_STATIC_MUTEX(built_in_groups_lock) EC_GROUP *EC_GROUP_new_by_curve_name(int nid) { struct built_in_groups_st *groups = built_in_groups_bss_get(); @@ -660,6 +660,22 @@ const char *EC_curve_nid2nist(int nid) { return NULL; } +int EC_curve_nist2nid(const char *name) { + if (strcmp(name, "P-224") == 0) { + return NID_secp224r1; + } + if (strcmp(name, "P-256") == 0) { + return NID_X9_62_prime256v1; + } + if (strcmp(name, "P-384") == 0) { + return NID_secp384r1; + } + if (strcmp(name, "P-521") == 0) { + return NID_secp521r1; + } + return NID_undef; +} + EC_POINT *EC_POINT_new(const EC_GROUP *group) { if (group == NULL) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); @@ -876,8 +892,6 @@ int EC_POINT_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *g_scalar, } int ret = 0; - EC_SCALAR g_scalar_storage, p_scalar_storage; - EC_SCALAR *g_scalar_arg = NULL, *p_scalar_arg = NULL; BN_CTX *new_ctx = NULL; if (ctx == NULL) { new_ctx = BN_CTX_new(); @@ -887,35 +901,50 @@ int EC_POINT_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *g_scalar, ctx = new_ctx; } + // If both |g_scalar| and |p_scalar| are non-NULL, + // |ec_point_mul_scalar_public| would share the doublings between the two + // products, which would be more efficient. However, we conservatively assume + // the caller needs a constant-time operation. (ECDSA verification does not + // use this function.) + // + // Previously, the low-level constant-time multiplication function aligned + // with this function's calling convention, but this was misleading. Curves + // which combined the two multiplications did not avoid the doubling case + // in the incomplete addition formula and were not constant-time. + if (g_scalar != NULL) { - if (!arbitrary_bignum_to_scalar(group, &g_scalar_storage, g_scalar, ctx)) { + EC_SCALAR scalar; + if (!arbitrary_bignum_to_scalar(group, &scalar, g_scalar, ctx) || + !ec_point_mul_scalar_base(group, &r->raw, &scalar)) { goto err; } - g_scalar_arg = &g_scalar_storage; } if (p_scalar != NULL) { - if (!arbitrary_bignum_to_scalar(group, &p_scalar_storage, p_scalar, ctx)) { + EC_SCALAR scalar; + EC_RAW_POINT tmp; + if (!arbitrary_bignum_to_scalar(group, &scalar, p_scalar, ctx) || + !ec_point_mul_scalar(group, &tmp, &p->raw, &scalar)) { goto err; } - p_scalar_arg = &p_scalar_storage; + if (g_scalar == NULL) { + OPENSSL_memcpy(&r->raw, &tmp, sizeof(EC_RAW_POINT)); + } else { + group->meth->add(group, &r->raw, &r->raw, &tmp); + } } - ret = ec_point_mul_scalar(group, &r->raw, g_scalar_arg, - p == NULL ? NULL : &p->raw, p_scalar_arg); + ret = 1; err: BN_CTX_free(new_ctx); - OPENSSL_cleanse(&g_scalar_storage, sizeof(g_scalar_storage)); - OPENSSL_cleanse(&p_scalar_storage, sizeof(p_scalar_storage)); return ret; } int ec_point_mul_scalar_public(const EC_GROUP *group, EC_RAW_POINT *r, const EC_SCALAR *g_scalar, const EC_RAW_POINT *p, const EC_SCALAR *p_scalar) { - if ((g_scalar == NULL && p_scalar == NULL) || - (p == NULL) != (p_scalar == NULL)) { + if (g_scalar == NULL || p_scalar == NULL || p == NULL) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); return 0; } @@ -925,15 +954,24 @@ int ec_point_mul_scalar_public(const EC_GROUP *group, EC_RAW_POINT *r, } int ec_point_mul_scalar(const EC_GROUP *group, EC_RAW_POINT *r, - const EC_SCALAR *g_scalar, const EC_RAW_POINT *p, - const EC_SCALAR *p_scalar) { - if ((g_scalar == NULL && p_scalar == NULL) || - (p == NULL) != (p_scalar == NULL)) { + const EC_RAW_POINT *p, const EC_SCALAR *scalar) { + if (p == NULL || scalar == NULL) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); return 0; } - group->meth->mul(group, r, g_scalar, p, p_scalar); + group->meth->mul(group, r, p, scalar); + return 1; +} + +int ec_point_mul_scalar_base(const EC_GROUP *group, EC_RAW_POINT *r, + const EC_SCALAR *scalar) { + if (scalar == NULL) { + OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); + return 0; + } + + group->meth->mul_base(group, r, scalar); return 1; } diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/ec_key.c b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/ec_key.c index 4bc12a07..3851c198 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/ec_key.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/ec_key.c @@ -82,7 +82,7 @@ #include "../../internal.h" -DEFINE_STATIC_EX_DATA_CLASS(g_ec_ex_data_class); +DEFINE_STATIC_EX_DATA_CLASS(g_ec_ex_data_class) static EC_WRAPPED_SCALAR *ec_wrapped_scalar_new(const EC_GROUP *group) { EC_WRAPPED_SCALAR *wrapped = OPENSSL_malloc(sizeof(EC_WRAPPED_SCALAR)); @@ -267,7 +267,7 @@ int EC_KEY_set_public_key(EC_KEY *key, const EC_POINT *pub_key) { return 0; } - if (EC_GROUP_cmp(key->group, pub_key->group, NULL) != 0) { + if (pub_key != NULL && EC_GROUP_cmp(key->group, pub_key->group, NULL) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH); return 0; } @@ -322,8 +322,8 @@ int EC_KEY_check_key(const EC_KEY *eckey) { if (eckey->priv_key != NULL) { point = EC_POINT_new(eckey->group); if (point == NULL || - !ec_point_mul_scalar(eckey->group, &point->raw, - &eckey->priv_key->scalar, NULL, NULL)) { + !ec_point_mul_scalar_base(eckey->group, &point->raw, + &eckey->priv_key->scalar)) { OPENSSL_PUT_ERROR(EC, ERR_R_EC_LIB); goto err; } @@ -440,8 +440,7 @@ int EC_KEY_generate_key(EC_KEY *key) { // Generate the private key by testing candidates (FIPS 186-4 B.4.2). !ec_random_nonzero_scalar(key->group, &priv_key->scalar, kDefaultAdditionalData) || - !ec_point_mul_scalar(key->group, &pub_key->raw, &priv_key->scalar, NULL, - NULL)) { + !ec_point_mul_scalar_base(key->group, &pub_key->raw, &priv_key->scalar)) { EC_POINT_free(pub_key); ec_wrapped_scalar_free(priv_key); return 0; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/ec_montgomery.c b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/ec_montgomery.c index caa19661..6fb32c47 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/ec_montgomery.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/ec_montgomery.c @@ -470,6 +470,7 @@ DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_mont_method) { out->add = ec_GFp_mont_add; out->dbl = ec_GFp_mont_dbl; out->mul = ec_GFp_mont_mul; + out->mul_base = ec_GFp_mont_mul_base; out->mul_public = ec_GFp_mont_mul_public; out->felem_mul = ec_GFp_mont_felem_mul; out->felem_sqr = ec_GFp_mont_felem_sqr; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/ec_test.cc b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/ec_test.cc index 97c6d450..c0ad61f5 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/ec_test.cc +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/ec_test.cc @@ -347,6 +347,20 @@ TEST(ECTest, SetKeyWithoutGroup) { EC_KEY_set_public_key(key.get(), EC_GROUP_get0_generator(group.get()))); } +TEST(ECTest, SetNULLKey) { + bssl::UniquePtr key(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1)); + ASSERT_TRUE(key); + + EXPECT_TRUE(EC_KEY_set_public_key( + key.get(), EC_GROUP_get0_generator(EC_KEY_get0_group(key.get())))); + EXPECT_TRUE(EC_KEY_get0_public_key(key.get())); + + // Setting a NULL public-key should clear the public-key and return zero, in + // order to match OpenSSL behaviour exactly. + EXPECT_FALSE(EC_KEY_set_public_key(key.get(), nullptr)); + EXPECT_FALSE(EC_KEY_get0_public_key(key.get())); +} + TEST(ECTest, GroupMismatch) { bssl::UniquePtr key(EC_KEY_new_by_curve_name(NID_secp384r1)); ASSERT_TRUE(key); @@ -750,7 +764,15 @@ TEST_P(ECCurveTest, P224Bug) { ASSERT_TRUE(BN_set_word(bn32.get(), 32)); ASSERT_TRUE(EC_POINT_mul(group(), ret.get(), bn32.get(), p.get(), bn31.get(), nullptr)); + EXPECT_EQ(0, EC_POINT_cmp(group(), ret.get(), g, nullptr)); + // Repeat the computation with |ec_point_mul_scalar_public|, which ties the + // additions together. + EC_SCALAR sc31, sc32; + ASSERT_TRUE(ec_bignum_to_scalar(group(), &sc31, bn31.get())); + ASSERT_TRUE(ec_bignum_to_scalar(group(), &sc32, bn32.get())); + ASSERT_TRUE( + ec_point_mul_scalar_public(group(), &ret->raw, &sc32, &p->raw, &sc31)); EXPECT_EQ(0, EC_POINT_cmp(group(), ret.get(), g, nullptr)); } @@ -778,8 +800,8 @@ static std::string CurveToString( return OBJ_nid2sn(params.param.nid); } -INSTANTIATE_TEST_CASE_P(, ECCurveTest, testing::ValuesIn(AllCurves()), - CurveToString); +INSTANTIATE_TEST_SUITE_P(, ECCurveTest, testing::ValuesIn(AllCurves()), + CurveToString); static bssl::UniquePtr GetCurve(FileTest *t, const char *key) { std::string curve_name; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/internal.h b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/internal.h index 05175a56..7934c3ad 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/internal.h +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/internal.h @@ -140,16 +140,15 @@ struct ec_method_st { // dbl sets |r| to |a| + |a|. void (*dbl)(const EC_GROUP *group, EC_RAW_POINT *r, const EC_RAW_POINT *a); - // Computes |r = g_scalar*generator + p_scalar*p| if |g_scalar| and |p_scalar| - // are both non-null. Computes |r = g_scalar*generator| if |p_scalar| is null. - // Computes |r = p_scalar*p| if g_scalar is null. At least one of |g_scalar| - // and |p_scalar| must be non-null, and |p| must be non-null if |p_scalar| is - // non-null. - void (*mul)(const EC_GROUP *group, EC_RAW_POINT *r, const EC_SCALAR *g_scalar, - const EC_RAW_POINT *p, const EC_SCALAR *p_scalar); - // mul_public performs the same computation as mul. It further assumes that - // the inputs are public so there is no concern about leaking their values - // through timing. + // mul sets |r| to |scalar|*|p|. + void (*mul)(const EC_GROUP *group, EC_RAW_POINT *r, const EC_RAW_POINT *p, + const EC_SCALAR *scalar); + // mul_base sets |r| to |scalar|*generator. + void (*mul_base)(const EC_GROUP *group, EC_RAW_POINT *r, + const EC_SCALAR *scalar); + // mul_public sets |r| to |g_scalar|*generator + |p_scalar|*|p|. It assumes + // that the inputs are public so there is no concern about leaking their + // values through timing. void (*mul_public)(const EC_GROUP *group, EC_RAW_POINT *r, const EC_SCALAR *g_scalar, const EC_RAW_POINT *p, const EC_SCALAR *p_scalar); @@ -325,13 +324,15 @@ void ec_scalar_inv_montgomery(const EC_GROUP *group, EC_SCALAR *r, int ec_scalar_inv_montgomery_vartime(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a); -// ec_point_mul_scalar sets |r| to generator * |g_scalar| + |p| * -// |p_scalar|. Unlike other functions which take |EC_SCALAR|, |g_scalar| and -// |p_scalar| need not be fully reduced. They need only contain as many bits as -// the order. +// ec_point_mul_scalar sets |r| to |p| * |scalar|. Both inputs are considered +// secret. int ec_point_mul_scalar(const EC_GROUP *group, EC_RAW_POINT *r, - const EC_SCALAR *g_scalar, const EC_RAW_POINT *p, - const EC_SCALAR *p_scalar); + const EC_RAW_POINT *p, const EC_SCALAR *scalar); + +// ec_point_mul_scalar_base sets |r| to generator * |scalar|. |scalar| is +// treated as secret. +int ec_point_mul_scalar_base(const EC_GROUP *group, EC_RAW_POINT *r, + const EC_SCALAR *scalar); // ec_point_mul_scalar_public performs the same computation as // ec_point_mul_scalar. It further assumes that the inputs are public so @@ -370,8 +371,9 @@ int ec_point_get_affine_coordinate_bytes(const EC_GROUP *group, uint8_t *out_x, int ec_field_element_to_scalar(const EC_GROUP *group, BIGNUM *r); void ec_GFp_mont_mul(const EC_GROUP *group, EC_RAW_POINT *r, - const EC_SCALAR *g_scalar, const EC_RAW_POINT *p, - const EC_SCALAR *p_scalar); + const EC_RAW_POINT *p, const EC_SCALAR *scalar); +void ec_GFp_mont_mul_base(const EC_GROUP *group, EC_RAW_POINT *r, + const EC_SCALAR *scalar); // ec_compute_wNAF writes the modified width-(w+1) Non-Adjacent Form (wNAF) of // |scalar| to |out|. |out| must have room for |bits| + 1 elements, each of diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/p224-64.c b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/p224-64.c index dd3098f5..7ae7c590 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/p224-64.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/p224-64.c @@ -1031,6 +1031,11 @@ static void ec_GFp_nistp224_points_mul(const EC_GROUP *group, EC_RAW_POINT *r, const EC_SCALAR *g_scalar, const EC_RAW_POINT *p, const EC_SCALAR *p_scalar) { + // Note this function must act in constant-time when exactly one of |g_scalar| + // and |p_scalar| is non-NULL. If both are non-NULL, this is not necessary and + // we'll hit the variable-time doubling case in |p224_point_add|. + // + // TODO(davidben): Split this like the other curves to ease analysis. p224_felem p_pre_comp[17][3]; p224_felem x_out, y_out, z_out; @@ -1072,6 +1077,19 @@ static void ec_GFp_nistp224_points_mul(const EC_GROUP *group, EC_RAW_POINT *r, p224_felem_to_generic(&r->Z, z_out); } +static void ec_GFp_nistp224_point_mul(const EC_GROUP *group, EC_RAW_POINT *r, + const EC_RAW_POINT *p, + const EC_SCALAR *scalar) { + ec_GFp_nistp224_points_mul(group, r, NULL /* g_scalar */, p, scalar); +} + +static void ec_GFp_nistp224_point_mul_base(const EC_GROUP *group, + EC_RAW_POINT *r, + const EC_SCALAR *scalar) { + ec_GFp_nistp224_points_mul(group, r, scalar, NULL /* p */, + NULL /* p_scalar */); +} + static void ec_GFp_nistp224_felem_mul(const EC_GROUP *group, EC_FELEM *r, const EC_FELEM *a, const EC_FELEM *b) { p224_felem felem1, felem2; @@ -1111,7 +1129,8 @@ DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_nistp224_method) { ec_GFp_nistp224_point_get_affine_coordinates; out->add = ec_GFp_nistp224_add; out->dbl = ec_GFp_nistp224_dbl; - out->mul = ec_GFp_nistp224_points_mul; + out->mul = ec_GFp_nistp224_point_mul; + out->mul_base = ec_GFp_nistp224_point_mul_base; out->mul_public = ec_GFp_nistp224_points_mul; out->felem_mul = ec_GFp_nistp224_felem_mul; out->felem_sqr = ec_GFp_nistp224_felem_sqr; @@ -1120,6 +1139,6 @@ DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_nistp224_method) { out->scalar_inv_montgomery = ec_simple_scalar_inv_montgomery; out->scalar_inv_montgomery_vartime = ec_GFp_simple_mont_inv_mod_ord_vartime; out->cmp_x_coordinate = ec_GFp_simple_cmp_x_coordinate; -}; +} #endif // BORINGSSL_HAS_UINT128 && !SMALL diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/p256-x86_64.c b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/p256-x86_64.c index 93772d6e..b4af5446 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/p256-x86_64.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/p256-x86_64.c @@ -48,7 +48,8 @@ static const BN_ULONG ONE[P256_LIMBS] = { // Precomputed tables for the default generator #include "p256-x86_64-table.h" -// Recode window to a signed digit, see util-64.c for details +// Recode window to a signed digit, see |ec_GFp_nistp_recode_scalar_bits| in +// util.c for details static unsigned booth_recode_w5(unsigned in) { unsigned s, d; @@ -316,74 +317,57 @@ static unsigned calc_wvalue(unsigned *index, const uint8_t p_str[33]) { return booth_recode_w7(wvalue); } -static void mul_p_add_and_store(const EC_GROUP *group, EC_RAW_POINT *r, - const EC_SCALAR *g_scalar, - const EC_RAW_POINT *p_, - const EC_SCALAR *p_scalar, - p256_point_union_t *t, p256_point_union_t *p) { - const int p_is_infinity = g_scalar == NULL; - if (p_scalar != NULL) { - P256_POINT *out = &t->p; - if (p_is_infinity) { - out = &p->p; - } +static void ecp_nistz256_point_mul(const EC_GROUP *group, EC_RAW_POINT *r, + const EC_RAW_POINT *p, + const EC_SCALAR *scalar) { + alignas(32) P256_POINT out; + ecp_nistz256_windowed_mul(group, &out, p, scalar); - ecp_nistz256_windowed_mul(group, out, p_, p_scalar); - if (!p_is_infinity) { - ecp_nistz256_point_add(&p->p, &p->p, out); - } + assert(group->field.width == P256_LIMBS); + OPENSSL_memcpy(r->X.words, out.X, P256_LIMBS * sizeof(BN_ULONG)); + OPENSSL_memcpy(r->Y.words, out.Y, P256_LIMBS * sizeof(BN_ULONG)); + OPENSSL_memcpy(r->Z.words, out.Z, P256_LIMBS * sizeof(BN_ULONG)); +} + +static void ecp_nistz256_point_mul_base(const EC_GROUP *group, EC_RAW_POINT *r, + const EC_SCALAR *scalar) { + alignas(32) p256_point_union_t t, p; + + uint8_t p_str[33]; + OPENSSL_memcpy(p_str, scalar->bytes, 32); + p_str[32] = 0; + + // First window + unsigned index = 0; + unsigned wvalue = calc_first_wvalue(&index, p_str); + + ecp_nistz256_select_w7(&p.a, ecp_nistz256_precomputed[0], wvalue >> 1); + ecp_nistz256_neg(p.p.Z, p.p.Y); + copy_conditional(p.p.Y, p.p.Z, wvalue & 1); + + // Convert |p| from affine to Jacobian coordinates. We set Z to zero if |p| + // is infinity and |ONE| otherwise. |p| was computed from the table, so it + // is infinity iff |wvalue >> 1| is zero. + OPENSSL_memset(p.p.Z, 0, sizeof(p.p.Z)); + copy_conditional(p.p.Z, ONE, is_not_zero(wvalue >> 1)); + + for (int i = 1; i < 37; i++) { + wvalue = calc_wvalue(&index, p_str); + + ecp_nistz256_select_w7(&t.a, ecp_nistz256_precomputed[i], wvalue >> 1); + + ecp_nistz256_neg(t.p.Z, t.a.Y); + copy_conditional(t.a.Y, t.p.Z, wvalue & 1); + + // Note |ecp_nistz256_point_add_affine| does not work if |p.p| and |t.a| + // are the same non-infinity point. + ecp_nistz256_point_add_affine(&p.p, &p.p, &t.a); } assert(group->field.width == P256_LIMBS); - OPENSSL_memcpy(r->X.words, p->p.X, P256_LIMBS * sizeof(BN_ULONG)); - OPENSSL_memcpy(r->Y.words, p->p.Y, P256_LIMBS * sizeof(BN_ULONG)); - OPENSSL_memcpy(r->Z.words, p->p.Z, P256_LIMBS * sizeof(BN_ULONG)); -} - -static void ecp_nistz256_points_mul(const EC_GROUP *group, EC_RAW_POINT *r, - const EC_SCALAR *g_scalar, - const EC_RAW_POINT *p_, - const EC_SCALAR *p_scalar) { - assert((p_ != NULL) == (p_scalar != NULL)); - - alignas(32) p256_point_union_t t, p; - - if (g_scalar != NULL) { - uint8_t p_str[33]; - OPENSSL_memcpy(p_str, g_scalar->bytes, 32); - p_str[32] = 0; - - // First window - unsigned index = 0; - unsigned wvalue = calc_first_wvalue(&index, p_str); - - ecp_nistz256_select_w7(&p.a, ecp_nistz256_precomputed[0], wvalue >> 1); - - ecp_nistz256_neg(p.p.Z, p.p.Y); - copy_conditional(p.p.Y, p.p.Z, wvalue & 1); - - // Convert |p| from affine to Jacobian coordinates. We set Z to zero if |p| - // is infinity and |ONE| otherwise. |p| was computed from the table, so it - // is infinity iff |wvalue >> 1| is zero. - OPENSSL_memset(p.p.Z, 0, sizeof(p.p.Z)); - copy_conditional(p.p.Z, ONE, is_not_zero(wvalue >> 1)); - - for (int i = 1; i < 37; i++) { - wvalue = calc_wvalue(&index, p_str); - - ecp_nistz256_select_w7(&t.a, ecp_nistz256_precomputed[i], wvalue >> 1); - - ecp_nistz256_neg(t.p.Z, t.a.Y); - copy_conditional(t.a.Y, t.p.Z, wvalue & 1); - - // Note |ecp_nistz256_point_add_affine| does not work if |p.p| and |t.a| - // are the same non-infinity point, so it is important that we compute the - // |g_scalar| term before the |p_scalar| term. - ecp_nistz256_point_add_affine(&p.p, &p.p, &t.a); - } - } - - mul_p_add_and_store(group, r, g_scalar, p_, p_scalar, &t, &p); + OPENSSL_memcpy(r->X.words, p.p.X, P256_LIMBS * sizeof(BN_ULONG)); + OPENSSL_memcpy(r->Y.words, p.p.Y, P256_LIMBS * sizeof(BN_ULONG)); + OPENSSL_memcpy(r->Z.words, p.p.Z, P256_LIMBS * sizeof(BN_ULONG)); } static void ecp_nistz256_points_mul_public(const EC_GROUP *group, @@ -438,7 +422,13 @@ static void ecp_nistz256_points_mul_public(const EC_GROUP *group, ecp_nistz256_point_add_affine(&p.p, &p.p, &t.a); } - mul_p_add_and_store(group, r, g_scalar, p_, p_scalar, &t, &p); + ecp_nistz256_windowed_mul(group, &t.p, p_, p_scalar); + ecp_nistz256_point_add(&p.p, &p.p, &t.p); + + assert(group->field.width == P256_LIMBS); + OPENSSL_memcpy(r->X.words, p.p.X, P256_LIMBS * sizeof(BN_ULONG)); + OPENSSL_memcpy(r->Y.words, p.p.Y, P256_LIMBS * sizeof(BN_ULONG)); + OPENSSL_memcpy(r->Z.words, p.p.Z, P256_LIMBS * sizeof(BN_ULONG)); } static int ecp_nistz256_get_affine(const EC_GROUP *group, @@ -645,7 +635,8 @@ DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_nistz256_method) { out->point_get_affine_coordinates = ecp_nistz256_get_affine; out->add = ecp_nistz256_add; out->dbl = ecp_nistz256_dbl; - out->mul = ecp_nistz256_points_mul; + out->mul = ecp_nistz256_point_mul; + out->mul_base = ecp_nistz256_point_mul_base; out->mul_public = ecp_nistz256_points_mul_public; out->felem_mul = ec_GFp_mont_felem_mul; out->felem_sqr = ec_GFp_mont_felem_sqr; @@ -654,7 +645,7 @@ DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_nistz256_method) { out->scalar_inv_montgomery = ecp_nistz256_inv_mod_ord; out->scalar_inv_montgomery_vartime = ecp_nistz256_mont_inv_mod_ord_vartime; out->cmp_x_coordinate = ecp_nistz256_cmp_x_coordinate; -}; +} #endif /* !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) && \ !defined(OPENSSL_SMALL) */ diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/p256-x86_64.h b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/p256-x86_64.h index 2d70ca78..5deb81a3 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/p256-x86_64.h +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/p256-x86_64.h @@ -89,7 +89,7 @@ void ecp_nistz256_ord_mul_mont(BN_ULONG res[P256_LIMBS], // outputs are in Montgomery form. That is, |res| is // (|a| * 2^-256)^(2*|rep|) * 2^256 mod N. void ecp_nistz256_ord_sqr_mont(BN_ULONG res[P256_LIMBS], - const BN_ULONG a[P256_LIMBS], int rep); + const BN_ULONG a[P256_LIMBS], BN_ULONG rep); // beeu_mod_inverse_vartime sets out = a^-1 mod p using a Euclidean algorithm. // Assumption: 0 < a < p < 2^(256) and p is odd. diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/simple_mul.c b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/simple_mul.c index e05f491a..4ed6c48c 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/simple_mul.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/simple_mul.c @@ -21,9 +21,8 @@ #include "../../internal.h" -static void ec_GFp_mont_mul_single(const EC_GROUP *group, EC_RAW_POINT *r, - const EC_RAW_POINT *p, - const EC_SCALAR *scalar) { +void ec_GFp_mont_mul(const EC_GROUP *group, EC_RAW_POINT *r, + const EC_RAW_POINT *p, const EC_SCALAR *scalar) { // This is a generic implementation for uncommon curves that not do not // warrant a tuned one. It uses unsigned digits so that the doubling case in // |ec_GFp_mont_add| is always unreachable, erring on safety and simplicity. @@ -79,21 +78,7 @@ static void ec_GFp_mont_mul_single(const EC_GROUP *group, EC_RAW_POINT *r, } } -void ec_GFp_mont_mul(const EC_GROUP *group, EC_RAW_POINT *r, - const EC_SCALAR *g_scalar, const EC_RAW_POINT *p, - const EC_SCALAR *p_scalar) { - assert(g_scalar != NULL || p_scalar != NULL); - if (p_scalar == NULL) { - ec_GFp_mont_mul_single(group, r, &group->generator->raw, g_scalar); - } else if (g_scalar == NULL) { - ec_GFp_mont_mul_single(group, r, p, p_scalar); - } else { - // Support constant-time two-point multiplication for compatibility. This - // does not actually come up in keygen, ECDH, or ECDSA, so we implement it - // the naive way. - ec_GFp_mont_mul_single(group, r, &group->generator->raw, g_scalar); - EC_RAW_POINT tmp; - ec_GFp_mont_mul_single(group, &tmp, p, p_scalar); - ec_GFp_mont_add(group, r, r, &tmp); - } +void ec_GFp_mont_mul_base(const EC_GROUP *group, EC_RAW_POINT *r, + const EC_SCALAR *scalar) { + ec_GFp_mont_mul(group, r, &group->generator->raw, scalar); } diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/util.c b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/util.c index 7303a151..8951203d 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/ec/util.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/ec/util.c @@ -43,13 +43,13 @@ // of a nonnegative integer (b_k in {0, 1}), rewrite it in digits 0, 1, -1 // by using bit-wise subtraction as follows: // -// b_k b_(k-1) ... b_2 b_1 b_0 -// - b_k ... b_3 b_2 b_1 b_0 -// ------------------------------------- -// s_k b_(k-1) ... s_3 s_2 s_1 s_0 +// b_k b_(k-1) ... b_2 b_1 b_0 +// - b_k ... b_3 b_2 b_1 b_0 +// ----------------------------------------- +// s_(k+1) s_k ... s_3 s_2 s_1 s_0 // // A left-shift followed by subtraction of the original value yields a new -// representation of the same value, using signed bits s_i = b_(i+1) - b_i. +// representation of the same value, using signed bits s_i = b_(i-1) - b_i. // This representation from Booth's paper has since appeared in the // literature under a variety of different names including "reversed binary // form", "alternating greedy expansion", "mutual opposite form", and @@ -73,7 +73,7 @@ // (1961), pp. 67-91), in a radix-2^5 setting. That is, we always combine five // signed bits into a signed digit: // -// s_(4j + 4) s_(4j + 3) s_(4j + 2) s_(4j + 1) s_(4j) +// s_(5j + 4) s_(5j + 3) s_(5j + 2) s_(5j + 1) s_(5j) // // The sign-alternating property implies that the resulting digit values are // integers from -16 to 16. @@ -81,14 +81,14 @@ // Of course, we don't actually need to compute the signed digits s_i as an // intermediate step (that's just a nice way to see how this scheme relates // to the wNAF): a direct computation obtains the recoded digit from the -// six bits b_(4j + 4) ... b_(4j - 1). +// six bits b_(5j + 4) ... b_(5j - 1). // -// This function takes those five bits as an integer (0 .. 63), writing the +// This function takes those six bits as an integer (0 .. 63), writing the // recoded digit to *sign (0 for positive, 1 for negative) and *digit (absolute -// value, in the range 0 .. 8). Note that this integer essentially provides the -// input bits "shifted to the left" by one position: for example, the input to -// compute the least significant recoded digit, given that there's no bit b_-1, -// has to be b_4 b_3 b_2 b_1 b_0 0. +// value, in the range 0 .. 16). Note that this integer essentially provides +// the input bits "shifted to the left" by one position: for example, the input +// to compute the least significant recoded digit, given that there's no bit +// b_-1, has to be b_4 b_3 b_2 b_1 b_0 0. void ec_GFp_nistp_recode_scalar_bits(uint8_t *sign, uint8_t *digit, uint8_t in) { uint8_t s, d; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/ecdh/ecdh.c b/third_party/boringssl/kit/src/crypto/fipsmodule/ecdh/ecdh.c index b9dc2374..a7b2f08b 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/ecdh/ecdh.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/ecdh/ecdh.c @@ -93,7 +93,7 @@ int ECDH_compute_key_fips(uint8_t *out, size_t out_len, const EC_POINT *pub_key, EC_RAW_POINT shared_point; uint8_t buf[EC_MAX_BYTES]; size_t buflen; - if (!ec_point_mul_scalar(group, &shared_point, NULL, &pub_key->raw, priv) || + if (!ec_point_mul_scalar(group, &shared_point, &pub_key->raw, priv) || !ec_point_get_affine_coordinate_bytes(group, buf, NULL, &buflen, sizeof(buf), &shared_point)) { OPENSSL_PUT_ERROR(ECDH, ECDH_R_POINT_ARITHMETIC_FAILURE); diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/ecdsa/ecdsa.c b/third_party/boringssl/kit/src/crypto/fipsmodule/ecdsa/ecdsa.c index 010ee023..38771d58 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/ecdsa/ecdsa.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/ecdsa/ecdsa.c @@ -232,7 +232,7 @@ static int ecdsa_sign_setup(const EC_KEY *eckey, EC_SCALAR *out_kinv_mont, ec_scalar_from_montgomery(group, out_kinv_mont, out_kinv_mont); // Compute r, the x-coordinate of generator * k. - if (!ec_point_mul_scalar(group, &tmp_point, &k, NULL, NULL) || + if (!ec_point_mul_scalar_base(group, &tmp_point, &k) || !ec_get_x_coordinate_as_scalar(group, out_r, &tmp_point)) { goto err; } diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/fips_shared.lds b/third_party/boringssl/kit/src/crypto/fipsmodule/fips_shared.lds new file mode 100644 index 00000000..6d44abc4 --- /dev/null +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/fips_shared.lds @@ -0,0 +1,19 @@ +SECTIONS +{ + .text : { + BORINGSSL_bcm_text_start = .; + *(.text) + BORINGSSL_bcm_text_end = .; + } + .rodata : { + BORINGSSL_bcm_rodata_start = .; + *(.rodata) + BORINGSSL_bcm_rodata_end = .; + } + + /DISCARD/ : { + *(.rela.dyn) + *(.data) + *(.rel.ro) + } +} diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/fips_shared_support.c b/third_party/boringssl/kit/src/crypto/fipsmodule/fips_shared_support.c new file mode 100644 index 00000000..2a66a1f0 --- /dev/null +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/fips_shared_support.c @@ -0,0 +1,32 @@ +/* Copyright (c) 2019, Google Inc. + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ + +#include + + +#if defined(BORINGSSL_FIPS) && defined(BORINGSSL_SHARED_LIBRARY) +// BORINGSSL_bcm_text_hash is is default hash value for the FIPS integrity check +// that must be replaced with the real value during the build process. This +// value need only be distinct, i.e. so that we can safely search-and-replace it +// in an object file. +const uint8_t BORINGSSL_bcm_text_hash[64]; +const uint8_t BORINGSSL_bcm_text_hash[64] = { + 0xae, 0x2c, 0xea, 0x2a, 0xbd, 0xa6, 0xf3, 0xec, 0x97, 0x7f, 0x9b, + 0xf6, 0x94, 0x9a, 0xfc, 0x83, 0x68, 0x27, 0xcb, 0xa0, 0xa0, 0x9f, + 0x6b, 0x6f, 0xde, 0x52, 0xcd, 0xe2, 0xcd, 0xff, 0x31, 0x80, 0xa2, + 0xd4, 0xc3, 0x66, 0x0f, 0xc2, 0x6a, 0x7b, 0xf4, 0xbe, 0x39, 0xa2, + 0xd7, 0x25, 0xdb, 0x21, 0x98, 0xe9, 0xd5, 0x53, 0xbf, 0x5c, 0x32, + 0x06, 0x83, 0x34, 0x0c, 0x65, 0x89, 0x52, 0xbd, 0x1f, +}; +#endif // FIPS && SHARED_LIBRARY diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/md4/md4.c b/third_party/boringssl/kit/src/crypto/fipsmodule/md4/md4.c index f0c1dcdf..cc2a6314 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/md4/md4.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/md4/md4.c @@ -62,7 +62,7 @@ #include "../../internal.h" -uint8_t *MD4(const uint8_t *data, size_t len, uint8_t *out) { +uint8_t *MD4(const uint8_t *data, size_t len, uint8_t out[MD4_DIGEST_LENGTH]) { MD4_CTX ctx; MD4_Init(&ctx); MD4_Update(&ctx, data, len); @@ -88,6 +88,7 @@ void md4_block_data_order(uint32_t *state, const uint8_t *data, size_t num); #define HASH_CTX MD4_CTX #define HASH_CBLOCK 64 +#define HASH_DIGEST_LENGTH 16 #define HASH_UPDATE MD4_Update #define HASH_TRANSFORM MD4_Transform #define HASH_FINAL MD4_Final @@ -238,6 +239,7 @@ void md4_block_data_order(uint32_t *state, const uint8_t *data, size_t num) { #undef DATA_ORDER_IS_LITTLE_ENDIAN #undef HASH_CTX #undef HASH_CBLOCK +#undef HASH_DIGEST_LENGTH #undef HASH_UPDATE #undef HASH_TRANSFORM #undef HASH_FINAL diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/md5/asm/md5-586.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/md5/asm/md5-586.pl index ded94425..20c226bc 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/md5/asm/md5-586.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/md5/asm/md5-586.pl @@ -36,7 +36,7 @@ $X="esi"; &md5_block("md5_block_asm_data_order"); &asm_finish(); -close STDOUT; +close STDOUT or die "error closing STDOUT"; sub Np { diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/md5/asm/md5-x86_64.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/md5/asm/md5-x86_64.pl index 6eb33c0e..509bcdea 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/md5/asm/md5-x86_64.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/md5/asm/md5-x86_64.pl @@ -380,4 +380,4 @@ ___ print $code; -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/md5/md5.c b/third_party/boringssl/kit/src/crypto/fipsmodule/md5/md5.c index 66c65a6b..a48d7043 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/md5/md5.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/md5/md5.c @@ -64,7 +64,7 @@ #include "../../internal.h" -uint8_t *MD5(const uint8_t *data, size_t len, uint8_t *out) { +uint8_t *MD5(const uint8_t *data, size_t len, uint8_t out[MD5_DIGEST_LENGTH]) { MD5_CTX ctx; MD5_Init(&ctx); MD5_Update(&ctx, data, len); @@ -94,6 +94,7 @@ static void md5_block_data_order(uint32_t *state, const uint8_t *data, #define HASH_CTX MD5_CTX #define HASH_CBLOCK 64 +#define HASH_DIGEST_LENGTH 16 #define HASH_UPDATE MD5_Update #define HASH_TRANSFORM MD5_Transform #define HASH_FINAL MD5_Final @@ -281,6 +282,7 @@ static void md5_block_data_order(uint32_t *state, const uint8_t *data, #undef DATA_ORDER_IS_LITTLE_ENDIAN #undef HASH_CTX #undef HASH_CBLOCK +#undef HASH_DIGEST_LENGTH #undef HASH_UPDATE #undef HASH_TRANSFORM #undef HASH_FINAL diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/aesni-gcm-x86_64.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/aesni-gcm-x86_64.pl index 3d0600fb..d3e37636 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/aesni-gcm-x86_64.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/aesni-gcm-x86_64.pl @@ -664,6 +664,12 @@ _aesni_ctr32_6x: .align 32 aesni_gcm_encrypt: .cfi_startproc +#ifndef NDEBUG +#ifndef BORINGSSL_FIPS +.extern BORINGSSL_function_hit + movb \$1,BORINGSSL_function_hit+2(%rip) +#endif +#endif xor $ret,$ret # We call |_aesni_ctr32_6x| twice, each call consuming 96 bytes of @@ -1137,4 +1143,4 @@ $code =~ s/\`([^\`]*)\`/eval($1)/gem; print $code; -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-armv4.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-armv4.pl index e93e5b38..54c80f75 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-armv4.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-armv4.pl @@ -1,5 +1,5 @@ #! /usr/bin/env perl -# Copyright 2010-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2010-2018 The OpenSSL Project Authors. All Rights Reserved. # # Licensed under the OpenSSL license (the "License"). You may not use # this file except in compliance with the License. You can obtain a copy @@ -150,6 +150,8 @@ $code=<<___; .text #if defined(__thumb2__) || defined(__clang__) .syntax unified +#define ldrplb ldrbpl +#define ldrneb ldrbne #endif #if defined(__thumb2__) .thumb @@ -157,11 +159,6 @@ $code=<<___; .code 32 #endif -#ifdef __clang__ -#define ldrplb ldrbpl -#define ldrneb ldrbne -#endif - .type rem_4bit,%object .align 5 rem_4bit: @@ -556,4 +553,4 @@ foreach (split("\n",$code)) { print $_,"\n"; } -close STDOUT; # enforce flush +close STDOUT or die "error closing STDOUT"; # enforce flush diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-neon-armv8.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-neon-armv8.pl new file mode 100644 index 00000000..f57017d0 --- /dev/null +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-neon-armv8.pl @@ -0,0 +1,287 @@ +#! /usr/bin/env perl +# Copyright 2010-2016 The OpenSSL Project Authors. All Rights Reserved. +# +# Licensed under the OpenSSL license (the "License"). You may not use +# this file except in compliance with the License. You can obtain a copy +# in the file LICENSE in the source distribution or at +# https://www.openssl.org/source/license.html + +# ==================================================================== +# Written by Andy Polyakov for the OpenSSL +# project. The module is, however, dual licensed under OpenSSL and +# CRYPTOGAMS licenses depending on where you obtain it. For further +# details see http://www.openssl.org/~appro/cryptogams/. +# ==================================================================== + +# This file was adapted to AArch64 from the 32-bit version in ghash-armv4.pl. It +# implements the multiplication algorithm described in: +# +# Câmara, D.; Gouvêa, C. P. L.; López, J. & Dahab, R.: Fast Software +# Polynomial Multiplication on ARM Processors using the NEON Engine. +# +# http://conradoplg.cryptoland.net/files/2010/12/mocrysen13.pdf +# +# The main distinction to keep in mind between 32-bit NEON and AArch64 SIMD is +# AArch64 cannot compute over the upper halves of SIMD registers. In 32-bit +# NEON, the low and high halves of the 128-bit register q0 are accessible as +# 64-bit registers d0 and d1, respectively. In AArch64, dN is the lower half of +# vN. Where the 32-bit version would use the upper half, this file must keep +# halves in separate registers. +# +# The other distinction is in syntax. 32-bit NEON embeds lane information in the +# instruction name, while AArch64 uses suffixes on the registers. For instance, +# left-shifting 64-bit lanes of a SIMD register in 32-bit would be written: +# +# vshl.i64 q0, q0, #1 +# +# in 64-bit, it would be written: +# +# shl v0.2d, v0.2d, #1 +# +# See Programmer's Guide for ARMv8-A, section 7 for details. +# http://infocenter.arm.com/help/topic/com.arm.doc.den0024a/DEN0024A_v8_architecture_PG.pdf +# +# Finally, note the 8-bit and 64-bit polynomial multipliers in AArch64 differ +# only by suffix. pmull vR.8h, vA.8b, vB.8b multiplies eight 8-bit polynomials +# and is always available. pmull vR.1q, vA.1d, vB.1d multiplies a 64-bit +# polynomial and is conditioned on the PMULL extension. This file emulates the +# latter with the former. + +use strict; + +my $flavour = shift; +my $output; +if ($flavour=~/\w[\w\-]*\.\w+$/) { $output=$flavour; undef $flavour; } +else { while (($output=shift) && ($output!~/\w[\w\-]*\.\w+$/)) {} } + +if ($flavour && $flavour ne "void") { + $0 =~ m/(.*[\/\\])[^\/\\]+$/; + my $dir = $1; + my $xlate; + ( $xlate="${dir}arm-xlate.pl" and -f $xlate ) or + ( $xlate="${dir}../../../perlasm/arm-xlate.pl" and -f $xlate) or + die "can't locate arm-xlate.pl"; + + open STDOUT,"| \"$^X\" $xlate $flavour $output"; +} else { + open STDOUT,">$output"; +} + +my ($Xi, $Htbl, $inp, $len) = map("x$_", (0..3)); # argument block +my ($Xl, $Xm, $Xh, $INlo, $INhi) = map("v$_", (0..4)); +my ($Hlo, $Hhi, $Hhl) = map("v$_", (5..7)); +# d8-d15 are callee-saved, so avoid v8-v15. AArch64 SIMD has plenty of registers +# to spare. +my ($t0, $t1, $t2, $t3) = map("v$_", (16..19)); +my ($t0l_t1l, $t0h_t1h, $t2l_t3l, $t2h_t3h) = map("v$_", (20..23)); +my ($k48_k32, $k16_k0) = map("v$_", (24..25)); + +my $code = ""; + +# clmul64x64 emits code which emulates pmull $r.1q, $a.1d, $b.1d. $r, $a, and $b +# must be distinct from $t* and $k*. $t* are clobbered by the emitted code. +sub clmul64x64 { +my ($r, $a, $b) = @_; +$code .= <<___; + ext $t0.8b, $a.8b, $a.8b, #1 // A1 + pmull $t0.8h, $t0.8b, $b.8b // F = A1*B + ext $r.8b, $b.8b, $b.8b, #1 // B1 + pmull $r.8h, $a.8b, $r.8b // E = A*B1 + ext $t1.8b, $a.8b, $a.8b, #2 // A2 + pmull $t1.8h, $t1.8b, $b.8b // H = A2*B + ext $t3.8b, $b.8b, $b.8b, #2 // B2 + pmull $t3.8h, $a.8b, $t3.8b // G = A*B2 + ext $t2.8b, $a.8b, $a.8b, #3 // A3 + eor $t0.16b, $t0.16b, $r.16b // L = E + F + pmull $t2.8h, $t2.8b, $b.8b // J = A3*B + ext $r.8b, $b.8b, $b.8b, #3 // B3 + eor $t1.16b, $t1.16b, $t3.16b // M = G + H + pmull $r.8h, $a.8b, $r.8b // I = A*B3 + + // Here we diverge from the 32-bit version. It computes the following + // (instructions reordered for clarity): + // + // veor \$t0#lo, \$t0#lo, \$t0#hi @ t0 = P0 + P1 (L) + // vand \$t0#hi, \$t0#hi, \$k48 + // veor \$t0#lo, \$t0#lo, \$t0#hi + // + // veor \$t1#lo, \$t1#lo, \$t1#hi @ t1 = P2 + P3 (M) + // vand \$t1#hi, \$t1#hi, \$k32 + // veor \$t1#lo, \$t1#lo, \$t1#hi + // + // veor \$t2#lo, \$t2#lo, \$t2#hi @ t2 = P4 + P5 (N) + // vand \$t2#hi, \$t2#hi, \$k16 + // veor \$t2#lo, \$t2#lo, \$t2#hi + // + // veor \$t3#lo, \$t3#lo, \$t3#hi @ t3 = P6 + P7 (K) + // vmov.i64 \$t3#hi, #0 + // + // \$kN is a mask with the bottom N bits set. AArch64 cannot compute on + // upper halves of SIMD registers, so we must split each half into + // separate registers. To compensate, we pair computations up and + // parallelize. + + ext $t3.8b, $b.8b, $b.8b, #4 // B4 + eor $t2.16b, $t2.16b, $r.16b // N = I + J + pmull $t3.8h, $a.8b, $t3.8b // K = A*B4 + + // This can probably be scheduled more efficiently. For now, we just + // pair up independent instructions. + zip1 $t0l_t1l.2d, $t0.2d, $t1.2d + zip1 $t2l_t3l.2d, $t2.2d, $t3.2d + zip2 $t0h_t1h.2d, $t0.2d, $t1.2d + zip2 $t2h_t3h.2d, $t2.2d, $t3.2d + eor $t0l_t1l.16b, $t0l_t1l.16b, $t0h_t1h.16b + eor $t2l_t3l.16b, $t2l_t3l.16b, $t2h_t3h.16b + and $t0h_t1h.16b, $t0h_t1h.16b, $k48_k32.16b + and $t2h_t3h.16b, $t2h_t3h.16b, $k16_k0.16b + eor $t0l_t1l.16b, $t0l_t1l.16b, $t0h_t1h.16b + eor $t2l_t3l.16b, $t2l_t3l.16b, $t2h_t3h.16b + zip1 $t0.2d, $t0l_t1l.2d, $t0h_t1h.2d + zip1 $t2.2d, $t2l_t3l.2d, $t2h_t3h.2d + zip2 $t1.2d, $t0l_t1l.2d, $t0h_t1h.2d + zip2 $t3.2d, $t2l_t3l.2d, $t2h_t3h.2d + + ext $t0.16b, $t0.16b, $t0.16b, #15 // t0 = t0 << 8 + ext $t1.16b, $t1.16b, $t1.16b, #14 // t1 = t1 << 16 + pmull $r.8h, $a.8b, $b.8b // D = A*B + ext $t3.16b, $t3.16b, $t3.16b, #12 // t3 = t3 << 32 + ext $t2.16b, $t2.16b, $t2.16b, #13 // t2 = t2 << 24 + eor $t0.16b, $t0.16b, $t1.16b + eor $t2.16b, $t2.16b, $t3.16b + eor $r.16b, $r.16b, $t0.16b + eor $r.16b, $r.16b, $t2.16b +___ +} + +$code .= <<___; +.text + +.global gcm_init_neon +.type gcm_init_neon,%function +.align 4 +gcm_init_neon: + // This function is adapted from gcm_init_v8. xC2 is t3. + ld1 {$t1.2d}, [x1] // load H + movi $t3.16b, #0xe1 + shl $t3.2d, $t3.2d, #57 // 0xc2.0 + ext $INlo.16b, $t1.16b, $t1.16b, #8 + ushr $t2.2d, $t3.2d, #63 + dup $t1.4s, $t1.s[1] + ext $t0.16b, $t2.16b, $t3.16b, #8 // t0=0xc2....01 + ushr $t2.2d, $INlo.2d, #63 + sshr $t1.4s, $t1.4s, #31 // broadcast carry bit + and $t2.16b, $t2.16b, $t0.16b + shl $INlo.2d, $INlo.2d, #1 + ext $t2.16b, $t2.16b, $t2.16b, #8 + and $t0.16b, $t0.16b, $t1.16b + orr $INlo.16b, $INlo.16b, $t2.16b // H<<<=1 + eor $Hlo.16b, $INlo.16b, $t0.16b // twisted H + st1 {$Hlo.2d}, [x0] // store Htable[0] + ret +.size gcm_init_neon,.-gcm_init_neon + +.global gcm_gmult_neon +.type gcm_gmult_neon,%function +.align 4 +gcm_gmult_neon: + ld1 {$INlo.16b}, [$Xi] // load Xi + ld1 {$Hlo.1d}, [$Htbl], #8 // load twisted H + ld1 {$Hhi.1d}, [$Htbl] + adrp x9, :pg_hi21:.Lmasks // load constants + add x9, x9, :lo12:.Lmasks + ld1 {$k48_k32.2d, $k16_k0.2d}, [x9] + rev64 $INlo.16b, $INlo.16b // byteswap Xi + ext $INlo.16b, $INlo.16b, $INlo.16b, #8 + eor $Hhl.8b, $Hlo.8b, $Hhi.8b // Karatsuba pre-processing + + mov $len, #16 + b .Lgmult_neon +.size gcm_gmult_neon,.-gcm_gmult_neon + +.global gcm_ghash_neon +.type gcm_ghash_neon,%function +.align 4 +gcm_ghash_neon: + ld1 {$Xl.16b}, [$Xi] // load Xi + ld1 {$Hlo.1d}, [$Htbl], #8 // load twisted H + ld1 {$Hhi.1d}, [$Htbl] + adrp x9, :pg_hi21:.Lmasks // load constants + add x9, x9, :lo12:.Lmasks + ld1 {$k48_k32.2d, $k16_k0.2d}, [x9] + rev64 $Xl.16b, $Xl.16b // byteswap Xi + ext $Xl.16b, $Xl.16b, $Xl.16b, #8 + eor $Hhl.8b, $Hlo.8b, $Hhi.8b // Karatsuba pre-processing + +.Loop_neon: + ld1 {$INlo.16b}, [$inp], #16 // load inp + rev64 $INlo.16b, $INlo.16b // byteswap inp + ext $INlo.16b, $INlo.16b, $INlo.16b, #8 + eor $INlo.16b, $INlo.16b, $Xl.16b // inp ^= Xi + +.Lgmult_neon: + // Split the input into $INlo and $INhi. (The upper halves are unused, + // so it is okay to leave them alone.) + ins $INhi.d[0], $INlo.d[1] +___ +&clmul64x64 ($Xl, $Hlo, $INlo); # H.lo·Xi.lo +$code .= <<___; + eor $INlo.8b, $INlo.8b, $INhi.8b // Karatsuba pre-processing +___ +&clmul64x64 ($Xm, $Hhl, $INlo); # (H.lo+H.hi)·(Xi.lo+Xi.hi) +&clmul64x64 ($Xh, $Hhi, $INhi); # H.hi·Xi.hi +$code .= <<___; + ext $t0.16b, $Xl.16b, $Xh.16b, #8 + eor $Xm.16b, $Xm.16b, $Xl.16b // Karatsuba post-processing + eor $Xm.16b, $Xm.16b, $Xh.16b + eor $Xm.16b, $Xm.16b, $t0.16b // Xm overlaps Xh.lo and Xl.hi + ins $Xl.d[1], $Xm.d[0] // Xh|Xl - 256-bit result + // This is a no-op due to the ins instruction below. + // ins $Xh.d[0], $Xm.d[1] + + // equivalent of reduction_avx from ghash-x86_64.pl + shl $t1.2d, $Xl.2d, #57 // 1st phase + shl $t2.2d, $Xl.2d, #62 + eor $t2.16b, $t2.16b, $t1.16b // + shl $t1.2d, $Xl.2d, #63 + eor $t2.16b, $t2.16b, $t1.16b // + // Note Xm contains {Xl.d[1], Xh.d[0]}. + eor $t2.16b, $t2.16b, $Xm.16b + ins $Xl.d[1], $t2.d[0] // Xl.d[1] ^= t2.d[0] + ins $Xh.d[0], $t2.d[1] // Xh.d[0] ^= t2.d[1] + + ushr $t2.2d, $Xl.2d, #1 // 2nd phase + eor $Xh.16b, $Xh.16b,$Xl.16b + eor $Xl.16b, $Xl.16b,$t2.16b // + ushr $t2.2d, $t2.2d, #6 + ushr $Xl.2d, $Xl.2d, #1 // + eor $Xl.16b, $Xl.16b, $Xh.16b // + eor $Xl.16b, $Xl.16b, $t2.16b // + + subs $len, $len, #16 + bne .Loop_neon + + rev64 $Xl.16b, $Xl.16b // byteswap Xi and write + ext $Xl.16b, $Xl.16b, $Xl.16b, #8 + st1 {$Xl.16b}, [$Xi] + + ret +.size gcm_ghash_neon,.-gcm_ghash_neon + +.section .rodata +.align 4 +.Lmasks: +.quad 0x0000ffffffffffff // k48 +.quad 0x00000000ffffffff // k32 +.quad 0x000000000000ffff // k16 +.quad 0x0000000000000000 // k0 +.asciz "GHASH for ARMv8, derived from ARMv4 version by " +.align 2 +___ + +foreach (split("\n",$code)) { + s/\`([^\`]*)\`/eval $1/geo; + + print $_,"\n"; +} +close STDOUT or die "error closing STDOUT"; # enforce flush diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-ssse3-x86.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-ssse3-x86.pl new file mode 100644 index 00000000..45e1ee1c --- /dev/null +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-ssse3-x86.pl @@ -0,0 +1,288 @@ +#!/usr/bin/env perl +# Copyright (c) 2019, Google Inc. +# +# Permission to use, copy, modify, and/or distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +# ghash-ssse3-x86.pl is a constant-time variant of the traditional 4-bit +# table-based GHASH implementation. It requires SSSE3 instructions. +# +# For background, the table-based strategy is a 4-bit windowed multiplication. +# It precomputes all 4-bit multiples of H (this is 16 128-bit rows), then loops +# over 4-bit windows of the input and indexes them up into the table. Visually, +# it multiplies as in the schoolbook multiplication diagram below, but with +# more terms. (Each term is 4 bits, so there are 32 terms in each row.) First +# it incorporates the terms labeled '1' by indexing the most significant term +# of X into the table. Then it shifts and repeats for '2' and so on. +# +# hhhhhh +# * xxxxxx +# ============ +# 666666 +# 555555 +# 444444 +# 333333 +# 222222 +# 111111 +# +# This implementation changes the order. We treat the table as a 16×16 matrix +# and transpose it. The first row is then the first byte of each multiple of H, +# and so on. We then reorder terms as below. Observe that the terms labeled '1' +# and '2' are all lookups into the first row, etc. This maps well to the SSSE3 +# pshufb instruction, using alternating terms of X in parallel as indices. This +# alternation is needed because pshufb maps 4 bits to 8 bits. Then we shift and +# repeat for each row. +# +# hhhhhh +# * xxxxxx +# ============ +# 224466 +# 113355 +# 224466 +# 113355 +# 224466 +# 113355 +# +# Next we account for GCM's confusing bit order. The "first" bit is the least +# significant coefficient, but GCM treats the most sigificant bit within a byte +# as first. Bytes are little-endian, and bits are big-endian. We reverse the +# bytes in XMM registers for a consistent bit and byte ordering, but this means +# the least significant bit is the most significant coefficient and vice versa. +# +# For consistency, "low", "high", "left-shift", and "right-shift" refer to the +# bit ordering within the XMM register, rather than the reversed coefficient +# ordering. Low bits are less significant bits and more significant +# coefficients. Right-shifts move from MSB to the LSB and correspond to +# increasing the power of each coefficient. +# +# Note this bit reversal enters into the table's column indices. H*1 is stored +# in column 0b1000 and H*x^3 is stored in column 0b0001. It also means earlier +# table rows contain more significant coefficients, so we iterate forwards. + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; +push(@INC,"${dir}","${dir}../../../perlasm"); +require "x86asm.pl"; + +$output = pop; +open STDOUT, ">$output"; + +&asm_init($ARGV[0]); + +my ($Xi, $Htable, $in, $len) = ("edi", "esi", "edx", "ecx"); +&static_label("reverse_bytes"); +&static_label("low4_mask"); + +my $call_counter = 0; +# process_rows emits assembly code to process $rows rows of the table. On +# input, $Htable stores the pointer to the next row. xmm0 and xmm1 store the +# low and high halves of the input. The result so far is passed in xmm2. xmm3 +# must be zero. On output, $Htable is advanced to the next row and xmm2 is +# updated. xmm3 remains zero. It clobbers eax, xmm4, xmm5, and xmm6. +sub process_rows { + my ($rows) = @_; + $call_counter++; + + # Shifting whole XMM registers by bits is complex. psrldq shifts by + # bytes, and psrlq shifts the two 64-bit halves separately. Each row + # produces 8 bits of carry, and the reduction needs an additional 7-bit + # shift. This must fit in 64 bits so reduction can use psrlq. This + # allows up to 7 rows at a time. + die "Carry register would overflow 64 bits." if ($rows*8 + 7 > 64); + + &mov("eax", $rows); +&set_label("loop_row_$call_counter"); + &movdqa("xmm4", &QWP(0, $Htable)); + &lea($Htable, &DWP(16, $Htable)); + + # Right-shift xmm2 and xmm3 by 8 bytes. + &movdqa("xmm6", "xmm2"); + &palignr("xmm6", "xmm3", 1); + &movdqa("xmm3", "xmm6"); + &psrldq("xmm2", 1); + + # Load the next table row and index the low and high bits of the input. + # Note the low (respectively, high) half corresponds to more + # (respectively, less) significant coefficients. + &movdqa("xmm5", "xmm4"); + &pshufb("xmm4", "xmm0"); + &pshufb("xmm5", "xmm1"); + + # Add the high half (xmm5) without shifting. + &pxor("xmm2", "xmm5"); + + # Add the low half (xmm4). This must be right-shifted by 4 bits. First, + # add into the carry register (xmm3). + &movdqa("xmm5", "xmm4"); + &psllq("xmm5", 60); + &movdqa("xmm6", "xmm5"); + &pslldq("xmm6", 8); + &pxor("xmm3", "xmm6"); + + # Next, add into xmm2. + &psrldq("xmm5", 8); + &pxor("xmm2", "xmm5"); + &psrlq("xmm4", 4); + &pxor("xmm2", "xmm4"); + + &sub("eax", 1); + &jnz(&label("loop_row_$call_counter")); + + # Reduce the carry register. The reduction polynomial is 1 + x + x^2 + + # x^7, so we shift and XOR four times. + &pxor("xmm2", "xmm3"); # x^0 = 0 + &psrlq("xmm3", 1); + &pxor("xmm2", "xmm3"); # x^1 = x + &psrlq("xmm3", 1); + &pxor("xmm2", "xmm3"); # x^(1+1) = x^2 + &psrlq("xmm3", 5); + &pxor("xmm2", "xmm3"); # x^(1+1+5) = x^7 + &pxor("xmm3", "xmm3"); +____ +} + +# gcm_gmult_ssse3 multiplies |Xi| by |Htable| and writes the result to |Xi|. +# |Xi| is represented in GHASH's serialized byte representation. |Htable| is +# formatted as described above. +# void gcm_gmult_ssse3(uint64_t Xi[2], const u128 Htable[16]); +&function_begin("gcm_gmult_ssse3"); + &mov($Xi, &wparam(0)); + &mov($Htable, &wparam(1)); + + &movdqu("xmm0", &QWP(0, $Xi)); + &call(&label("pic_point")); +&set_label("pic_point"); + &blindpop("eax"); + &movdqa("xmm7", &QWP(&label("reverse_bytes")."-".&label("pic_point"), "eax")); + &movdqa("xmm2", &QWP(&label("low4_mask")."-".&label("pic_point"), "eax")); + + # Reverse input bytes to deserialize. + &pshufb("xmm0", "xmm7"); + + # Split each byte into low (xmm0) and high (xmm1) halves. + &movdqa("xmm1", "xmm2"); + &pandn("xmm1", "xmm0"); + &psrld("xmm1", 4); + &pand("xmm0", "xmm2"); + + # Maintain the result in xmm2 (the value) and xmm3 (carry bits). Note + # that, due to bit reversal, xmm3 contains bits that fall off when + # right-shifting, not left-shifting. + &pxor("xmm2", "xmm2"); + &pxor("xmm3", "xmm3"); + + # We must reduce at least once every 7 rows, so divide into three + # chunks. + &process_rows(5); + &process_rows(5); + &process_rows(6); + + # Store the result. Reverse bytes to serialize. + &pshufb("xmm2", "xmm7"); + &movdqu(&QWP(0, $Xi), "xmm2"); + + # Zero any registers which contain secrets. + &pxor("xmm0", "xmm0"); + &pxor("xmm1", "xmm1"); + &pxor("xmm2", "xmm2"); + &pxor("xmm3", "xmm3"); + &pxor("xmm4", "xmm4"); + &pxor("xmm5", "xmm5"); + &pxor("xmm6", "xmm6"); +&function_end("gcm_gmult_ssse3"); + +# gcm_ghash_ssse3 incorporates |len| bytes from |in| to |Xi|, using |Htable| as +# the key. It writes the result back to |Xi|. |Xi| is represented in GHASH's +# serialized byte representation. |Htable| is formatted as described above. +# void gcm_ghash_ssse3(uint64_t Xi[2], const u128 Htable[16], const uint8_t *in, +# size_t len); +&function_begin("gcm_ghash_ssse3"); + &mov($Xi, &wparam(0)); + &mov($Htable, &wparam(1)); + &mov($in, &wparam(2)); + &mov($len, &wparam(3)); + + &movdqu("xmm0", &QWP(0, $Xi)); + &call(&label("pic_point")); +&set_label("pic_point"); + &blindpop("ebx"); + &movdqa("xmm7", &QWP(&label("reverse_bytes")."-".&label("pic_point"), "ebx")); + + # This function only processes whole blocks. + &and($len, -16); + + # Reverse input bytes to deserialize. We maintain the running + # total in xmm0. + &pshufb("xmm0", "xmm7"); + + # Iterate over each block. On entry to each iteration, xmm3 is zero. + &pxor("xmm3", "xmm3"); +&set_label("loop_ghash"); + &movdqa("xmm2", &QWP(&label("low4_mask")."-".&label("pic_point"), "ebx")); + + # Incorporate the next block of input. + &movdqu("xmm1", &QWP(0, $in)); + &pshufb("xmm1", "xmm7"); # Reverse bytes. + &pxor("xmm0", "xmm1"); + + # Split each byte into low (xmm0) and high (xmm1) halves. + &movdqa("xmm1", "xmm2"); + &pandn("xmm1", "xmm0"); + &psrld("xmm1", 4); + &pand("xmm0", "xmm2"); + + # Maintain the result in xmm2 (the value) and xmm3 (carry bits). Note + # that, due to bit reversal, xmm3 contains bits that fall off when + # right-shifting, not left-shifting. + &pxor("xmm2", "xmm2"); + # xmm3 is already zero at this point. + + # We must reduce at least once every 7 rows, so divide into three + # chunks. + &process_rows(5); + &process_rows(5); + &process_rows(6); + + &movdqa("xmm0", "xmm2"); + + # Rewind $Htable for the next iteration. + &lea($Htable, &DWP(-256, $Htable)); + + # Advance input and continue. + &lea($in, &DWP(16, $in)); + &sub($len, 16); + &jnz(&label("loop_ghash")); + + # Reverse bytes and store the result. + &pshufb("xmm0", "xmm7"); + &movdqu(&QWP(0, $Xi), "xmm0"); + + # Zero any registers which contain secrets. + &pxor("xmm0", "xmm0"); + &pxor("xmm1", "xmm1"); + &pxor("xmm2", "xmm2"); + &pxor("xmm3", "xmm3"); + &pxor("xmm4", "xmm4"); + &pxor("xmm5", "xmm5"); + &pxor("xmm6", "xmm6"); +&function_end("gcm_ghash_ssse3"); + +# reverse_bytes is a permutation which, if applied with pshufb, reverses the +# bytes in an XMM register. +&set_label("reverse_bytes", 16); +&data_byte(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); +# low4_mask is an XMM mask which selects the low four bits of each byte. +&set_label("low4_mask", 16); +&data_word(0x0f0f0f0f, 0x0f0f0f0f, 0x0f0f0f0f, 0x0f0f0f0f); + +&asm_finish(); + +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-ssse3-x86_64.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-ssse3-x86_64.pl new file mode 100644 index 00000000..e0e50105 --- /dev/null +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-ssse3-x86_64.pl @@ -0,0 +1,413 @@ +#!/usr/bin/env perl +# Copyright (c) 2019, Google Inc. +# +# Permission to use, copy, modify, and/or distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +# ghash-ssse3-x86_64.pl is a constant-time variant of the traditional 4-bit +# table-based GHASH implementation. It requires SSSE3 instructions. +# +# For background, the table-based strategy is a 4-bit windowed multiplication. +# It precomputes all 4-bit multiples of H (this is 16 128-bit rows), then loops +# over 4-bit windows of the input and indexes them up into the table. Visually, +# it multiplies as in the schoolbook multiplication diagram below, but with +# more terms. (Each term is 4 bits, so there are 32 terms in each row.) First +# it incorporates the terms labeled '1' by indexing the most significant term +# of X into the table. Then it shifts and repeats for '2' and so on. +# +# hhhhhh +# * xxxxxx +# ============ +# 666666 +# 555555 +# 444444 +# 333333 +# 222222 +# 111111 +# +# This implementation changes the order. We treat the table as a 16×16 matrix +# and transpose it. The first row is then the first byte of each multiple of H, +# and so on. We then reorder terms as below. Observe that the terms labeled '1' +# and '2' are all lookups into the first row, etc. This maps well to the SSSE3 +# pshufb instruction, using alternating terms of X in parallel as indices. This +# alternation is needed because pshufb maps 4 bits to 8 bits. Then we shift and +# repeat for each row. +# +# hhhhhh +# * xxxxxx +# ============ +# 224466 +# 113355 +# 224466 +# 113355 +# 224466 +# 113355 +# +# Next we account for GCM's confusing bit order. The "first" bit is the least +# significant coefficient, but GCM treats the most sigificant bit within a byte +# as first. Bytes are little-endian, and bits are big-endian. We reverse the +# bytes in XMM registers for a consistent bit and byte ordering, but this means +# the least significant bit is the most significant coefficient and vice versa. +# +# For consistency, "low", "high", "left-shift", and "right-shift" refer to the +# bit ordering within the XMM register, rather than the reversed coefficient +# ordering. Low bits are less significant bits and more significant +# coefficients. Right-shifts move from MSB to the LSB and correspond to +# increasing the power of each coefficient. +# +# Note this bit reversal enters into the table's column indices. H*1 is stored +# in column 0b1000 and H*x^3 is stored in column 0b0001. It also means earlier +# table rows contain more significant coefficients, so we iterate forwards. + +use strict; + +my $flavour = shift; +my $output = shift; +if ($flavour =~ /\./) { $output = $flavour; undef $flavour; } + +my $win64 = 0; +$win64 = 1 if ($flavour =~ /[nm]asm|mingw64/ || $output =~ /\.asm$/); + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; +my $dir = $1; +my $xlate; +( $xlate="${dir}x86_64-xlate.pl" and -f $xlate ) or +( $xlate="${dir}../../../perlasm/x86_64-xlate.pl" and -f $xlate) or +die "can't locate x86_64-xlate.pl"; + +open OUT, "| \"$^X\" \"$xlate\" $flavour \"$output\""; +*STDOUT = *OUT; + +my ($Xi, $Htable, $in, $len) = $win64 ? ("%rcx", "%rdx", "%r8", "%r9") : + ("%rdi", "%rsi", "%rdx", "%rcx"); + + +my $code = <<____; +.text + +# gcm_gmult_ssse3 multiplies |Xi| by |Htable| and writes the result to |Xi|. +# |Xi| is represented in GHASH's serialized byte representation. |Htable| is +# formatted as described above. +# void gcm_gmult_ssse3(uint64_t Xi[2], const u128 Htable[16]); +.type gcm_gmult_ssse3, \@abi-omnipotent +.globl gcm_gmult_ssse3 +.align 16 +gcm_gmult_ssse3: +.cfi_startproc +.Lgmult_seh_begin: +____ +$code .= <<____ if ($win64); + subq \$40, %rsp +.Lgmult_seh_allocstack: + movdqa %xmm6, (%rsp) +.Lgmult_seh_save_xmm6: + movdqa %xmm10, 16(%rsp) +.Lgmult_seh_save_xmm10: +.Lgmult_seh_prolog_end: +____ +$code .= <<____; + movdqu ($Xi), %xmm0 + movdqa .Lreverse_bytes(%rip), %xmm10 + movdqa .Llow4_mask(%rip), %xmm2 + + # Reverse input bytes to deserialize. + pshufb %xmm10, %xmm0 + + # Split each byte into low (%xmm0) and high (%xmm1) halves. + movdqa %xmm2, %xmm1 + pandn %xmm0, %xmm1 + psrld \$4, %xmm1 + pand %xmm2, %xmm0 + + # Maintain the result in %xmm2 (the value) and %xmm3 (carry bits). Note + # that, due to bit reversal, %xmm3 contains bits that fall off when + # right-shifting, not left-shifting. + pxor %xmm2, %xmm2 + pxor %xmm3, %xmm3 +____ + +my $call_counter = 0; +# process_rows returns assembly code to process $rows rows of the table. On +# input, $Htable stores the pointer to the next row. %xmm0 and %xmm1 store the +# low and high halves of the input. The result so far is passed in %xmm2. %xmm3 +# must be zero. On output, $Htable is advanced to the next row and %xmm2 is +# updated. %xmm3 remains zero. It clobbers %rax, %xmm4, %xmm5, and %xmm6. +sub process_rows { + my ($rows) = @_; + $call_counter++; + + # Shifting whole XMM registers by bits is complex. psrldq shifts by bytes, + # and psrlq shifts the two 64-bit halves separately. Each row produces 8 + # bits of carry, and the reduction needs an additional 7-bit shift. This + # must fit in 64 bits so reduction can use psrlq. This allows up to 7 rows + # at a time. + die "Carry register would overflow 64 bits." if ($rows*8 + 7 > 64); + + return <<____; + movq \$$rows, %rax +.Loop_row_$call_counter: + movdqa ($Htable), %xmm4 + leaq 16($Htable), $Htable + + # Right-shift %xmm2 and %xmm3 by 8 bytes. + movdqa %xmm2, %xmm6 + palignr \$1, %xmm3, %xmm6 + movdqa %xmm6, %xmm3 + psrldq \$1, %xmm2 + + # Load the next table row and index the low and high bits of the input. + # Note the low (respectively, high) half corresponds to more + # (respectively, less) significant coefficients. + movdqa %xmm4, %xmm5 + pshufb %xmm0, %xmm4 + pshufb %xmm1, %xmm5 + + # Add the high half (%xmm5) without shifting. + pxor %xmm5, %xmm2 + + # Add the low half (%xmm4). This must be right-shifted by 4 bits. First, + # add into the carry register (%xmm3). + movdqa %xmm4, %xmm5 + psllq \$60, %xmm5 + movdqa %xmm5, %xmm6 + pslldq \$8, %xmm6 + pxor %xmm6, %xmm3 + + # Next, add into %xmm2. + psrldq \$8, %xmm5 + pxor %xmm5, %xmm2 + psrlq \$4, %xmm4 + pxor %xmm4, %xmm2 + + subq \$1, %rax + jnz .Loop_row_$call_counter + + # Reduce the carry register. The reduction polynomial is 1 + x + x^2 + + # x^7, so we shift and XOR four times. + pxor %xmm3, %xmm2 # x^0 = 0 + psrlq \$1, %xmm3 + pxor %xmm3, %xmm2 # x^1 = x + psrlq \$1, %xmm3 + pxor %xmm3, %xmm2 # x^(1+1) = x^2 + psrlq \$5, %xmm3 + pxor %xmm3, %xmm2 # x^(1+1+5) = x^7 + pxor %xmm3, %xmm3 +____ +} + +# We must reduce at least once every 7 rows, so divide into three chunks. +$code .= process_rows(5); +$code .= process_rows(5); +$code .= process_rows(6); + +$code .= <<____; + # Store the result. Reverse bytes to serialize. + pshufb %xmm10, %xmm2 + movdqu %xmm2, ($Xi) + + # Zero any registers which contain secrets. + pxor %xmm0, %xmm0 + pxor %xmm1, %xmm1 + pxor %xmm2, %xmm2 + pxor %xmm3, %xmm3 + pxor %xmm4, %xmm4 + pxor %xmm5, %xmm5 + pxor %xmm6, %xmm6 +____ +$code .= <<____ if ($win64); + movdqa (%rsp), %xmm6 + movdqa 16(%rsp), %xmm10 + addq \$40, %rsp +____ +$code .= <<____; + ret +.Lgmult_seh_end: +.cfi_endproc +.size gcm_gmult_ssse3,.-gcm_gmult_ssse3 +____ + +$code .= <<____; +# gcm_ghash_ssse3 incorporates |len| bytes from |in| to |Xi|, using |Htable| as +# the key. It writes the result back to |Xi|. |Xi| is represented in GHASH's +# serialized byte representation. |Htable| is formatted as described above. +# void gcm_ghash_ssse3(uint64_t Xi[2], const u128 Htable[16], const uint8_t *in, +# size_t len); +.type gcm_ghash_ssse3, \@abi-omnipotent +.globl gcm_ghash_ssse3 +.align 16 +gcm_ghash_ssse3: +.Lghash_seh_begin: +.cfi_startproc +____ +$code .= <<____ if ($win64); + subq \$56, %rsp +.Lghash_seh_allocstack: + movdqa %xmm6, (%rsp) +.Lghash_seh_save_xmm6: + movdqa %xmm10, 16(%rsp) +.Lghash_seh_save_xmm10: + movdqa %xmm11, 32(%rsp) +.Lghash_seh_save_xmm11: +.Lghash_seh_prolog_end: +____ +$code .= <<____; + movdqu ($Xi), %xmm0 + movdqa .Lreverse_bytes(%rip), %xmm10 + movdqa .Llow4_mask(%rip), %xmm11 + + # This function only processes whole blocks. + andq \$-16, $len + + # Reverse input bytes to deserialize. We maintain the running + # total in %xmm0. + pshufb %xmm10, %xmm0 + + # Iterate over each block. On entry to each iteration, %xmm3 is zero. + pxor %xmm3, %xmm3 +.Loop_ghash: + # Incorporate the next block of input. + movdqu ($in), %xmm1 + pshufb %xmm10, %xmm1 # Reverse bytes. + pxor %xmm1, %xmm0 + + # Split each byte into low (%xmm0) and high (%xmm1) halves. + movdqa %xmm11, %xmm1 + pandn %xmm0, %xmm1 + psrld \$4, %xmm1 + pand %xmm11, %xmm0 + + # Maintain the result in %xmm2 (the value) and %xmm3 (carry bits). Note + # that, due to bit reversal, %xmm3 contains bits that fall off when + # right-shifting, not left-shifting. + pxor %xmm2, %xmm2 + # %xmm3 is already zero at this point. +____ + +# We must reduce at least once every 7 rows, so divide into three chunks. +$code .= process_rows(5); +$code .= process_rows(5); +$code .= process_rows(6); + +$code .= <<____; + movdqa %xmm2, %xmm0 + + # Rewind $Htable for the next iteration. + leaq -256($Htable), $Htable + + # Advance input and continue. + leaq 16($in), $in + subq \$16, $len + jnz .Loop_ghash + + # Reverse bytes and store the result. + pshufb %xmm10, %xmm0 + movdqu %xmm0, ($Xi) + + # Zero any registers which contain secrets. + pxor %xmm0, %xmm0 + pxor %xmm1, %xmm1 + pxor %xmm2, %xmm2 + pxor %xmm3, %xmm3 + pxor %xmm4, %xmm4 + pxor %xmm5, %xmm5 + pxor %xmm6, %xmm6 +____ +$code .= <<____ if ($win64); + movdqa (%rsp), %xmm6 + movdqa 16(%rsp), %xmm10 + movdqa 32(%rsp), %xmm11 + addq \$56, %rsp +____ +$code .= <<____; + ret +.Lghash_seh_end: +.cfi_endproc +.size gcm_ghash_ssse3,.-gcm_ghash_ssse3 + +.align 16 +# .Lreverse_bytes is a permutation which, if applied with pshufb, reverses the +# bytes in an XMM register. +.Lreverse_bytes: +.byte 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 +# .Llow4_mask is an XMM mask which selects the low four bits of each byte. +.Llow4_mask: +.quad 0x0f0f0f0f0f0f0f0f, 0x0f0f0f0f0f0f0f0f +____ + +if ($win64) { + # Add unwind metadata for SEH. + # + # TODO(davidben): This is all manual right now. Once we've added SEH tests, + # add support for emitting these in x86_64-xlate.pl, probably based on MASM + # and Yasm's unwind directives, and unify with CFI. Then upstream it to + # replace the error-prone and non-standard custom handlers. + + # See https://docs.microsoft.com/en-us/cpp/build/struct-unwind-code?view=vs-2017 + my $UWOP_ALLOC_SMALL = 2; + my $UWOP_SAVE_XMM128 = 8; + + $code .= <<____; +.section .pdata +.align 4 + .rva .Lgmult_seh_begin + .rva .Lgmult_seh_end + .rva .Lgmult_seh_info + + .rva .Lghash_seh_begin + .rva .Lghash_seh_end + .rva .Lghash_seh_info + +.section .xdata +.align 8 +.Lgmult_seh_info: + .byte 1 # version 1, no flags + .byte .Lgmult_seh_prolog_end-.Lgmult_seh_begin + .byte 5 # num_slots = 1 + 2 + 2 + .byte 0 # no frame register + + .byte .Lgmult_seh_save_xmm10-.Lgmult_seh_begin + .byte @{[$UWOP_SAVE_XMM128 | (10 << 4)]} + .value 1 + + .byte .Lgmult_seh_save_xmm6-.Lgmult_seh_begin + .byte @{[$UWOP_SAVE_XMM128 | (6 << 4)]} + .value 0 + + .byte .Lgmult_seh_allocstack-.Lgmult_seh_begin + .byte @{[$UWOP_ALLOC_SMALL | (((40 - 8) / 8) << 4)]} + +.align 8 +.Lghash_seh_info: + .byte 1 # version 1, no flags + .byte .Lghash_seh_prolog_end-.Lghash_seh_begin + .byte 7 # num_slots = 1 + 2 + 2 + 2 + .byte 0 # no frame register + + .byte .Lghash_seh_save_xmm11-.Lghash_seh_begin + .byte @{[$UWOP_SAVE_XMM128 | (11 << 4)]} + .value 2 + + .byte .Lghash_seh_save_xmm10-.Lghash_seh_begin + .byte @{[$UWOP_SAVE_XMM128 | (10 << 4)]} + .value 1 + + .byte .Lghash_seh_save_xmm6-.Lghash_seh_begin + .byte @{[$UWOP_SAVE_XMM128 | (6 << 4)]} + .value 0 + + .byte .Lghash_seh_allocstack-.Lghash_seh_begin + .byte @{[$UWOP_ALLOC_SMALL | (((56 - 8) / 8) << 4)]} +____ +} + +print $code; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-x86.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-x86.pl index 02edf033..a2ab859c 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-x86.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-x86.pl @@ -1150,7 +1150,7 @@ my ($Xhi,$Xi)=@_; &asciz("GHASH for x86, CRYPTOGAMS by "); &asm_finish(); -close STDOUT; +close STDOUT or die "error closing STDOUT"; # A question was risen about choice of vanilla MMX. Or rather why wasn't # SSE2 chosen instead? In addition to the fact that MMX runs on legacy diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-x86_64.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-x86_64.pl index fc631c77..5c4122fe 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-x86_64.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghash-x86_64.pl @@ -518,6 +518,7 @@ $code.=<<___; .type gcm_init_clmul,\@abi-omnipotent .align 16 gcm_init_clmul: +.cfi_startproc .L_init_clmul: ___ $code.=<<___ if ($win64); @@ -587,6 +588,7 @@ $code.=<<___ if ($win64); ___ $code.=<<___; ret +.cfi_endproc .size gcm_init_clmul,.-gcm_init_clmul ___ } @@ -598,6 +600,7 @@ $code.=<<___; .type gcm_gmult_clmul,\@abi-omnipotent .align 16 gcm_gmult_clmul: +.cfi_startproc .L_gmult_clmul: movdqu ($Xip),$Xi movdqa .Lbswap_mask(%rip),$T3 @@ -634,6 +637,7 @@ $code.=<<___; pshufb $T3,$Xi movdqu $Xi,($Xip) ret +.cfi_endproc .size gcm_gmult_clmul,.-gcm_gmult_clmul ___ } @@ -647,6 +651,7 @@ $code.=<<___; .type gcm_ghash_clmul,\@abi-omnipotent .align 32 gcm_ghash_clmul: +.cfi_startproc .L_ghash_clmul: ___ $code.=<<___ if ($win64); @@ -995,6 +1000,7 @@ $code.=<<___ if ($win64); ___ $code.=<<___; ret +.cfi_endproc .size gcm_ghash_clmul,.-gcm_ghash_clmul ___ } @@ -1004,6 +1010,7 @@ $code.=<<___; .type gcm_init_avx,\@abi-omnipotent .align 32 gcm_init_avx: +.cfi_startproc ___ if ($avx) { my ($Htbl,$Xip)=@_4args; @@ -1132,6 +1139,7 @@ $code.=<<___ if ($win64); ___ $code.=<<___; ret +.cfi_endproc .size gcm_init_avx,.-gcm_init_avx ___ } else { @@ -1146,7 +1154,9 @@ $code.=<<___; .type gcm_gmult_avx,\@abi-omnipotent .align 32 gcm_gmult_avx: +.cfi_startproc jmp .L_gmult_clmul +.cfi_endproc .size gcm_gmult_avx,.-gcm_gmult_avx ___ @@ -1155,6 +1165,7 @@ $code.=<<___; .type gcm_ghash_avx,\@abi-omnipotent .align 32 gcm_ghash_avx: +.cfi_startproc ___ if ($avx) { my ($Xip,$Htbl,$inp,$len)=@_4args; @@ -1567,6 +1578,7 @@ $code.=<<___ if ($win64); ___ $code.=<<___; ret +.cfi_endproc .size gcm_ghash_avx,.-gcm_ghash_avx ___ } else { @@ -1791,4 +1803,4 @@ $code =~ s/\`([^\`]*)\`/eval($1)/gem; print $code; -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghashp8-ppc.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghashp8-ppc.pl index c46cdb5d..7a1259ba 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghashp8-ppc.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghashp8-ppc.pl @@ -667,4 +667,4 @@ foreach (split("\n",$code)) { print $_,"\n"; } -close STDOUT; # enforce flush +close STDOUT or die "error closing STDOUT"; # enforce flush diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghashv8-armx.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghashv8-armx.pl index 1435db50..99124a2b 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghashv8-armx.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/asm/ghashv8-armx.pl @@ -425,4 +425,4 @@ if ($flavour =~ /64/) { ######## 64-bit code } } -close STDOUT; # enforce flush +close STDOUT or die "error closing STDOUT"; # enforce flush diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/cbc.c b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/cbc.c index 64ea5056..3f1d7776 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/cbc.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/cbc.c @@ -49,6 +49,8 @@ #include #include +#include + #include "internal.h" @@ -61,30 +63,15 @@ void CRYPTO_cbc128_encrypt(const uint8_t *in, uint8_t *out, size_t len, assert(key != NULL && ivec != NULL); assert(len == 0 || (in != NULL && out != NULL)); - if (STRICT_ALIGNMENT && - ((uintptr_t)in | (uintptr_t)out | (uintptr_t)ivec) % sizeof(size_t) != - 0) { - while (len >= 16) { - for (n = 0; n < 16; ++n) { - out[n] = in[n] ^ iv[n]; - } - (*block)(out, out, key); - iv = out; - len -= 16; - in += 16; - out += 16; - } - } else { - while (len >= 16) { - for (n = 0; n < 16; n += sizeof(size_t)) { - store_word_le(out + n, load_word_le(in + n) ^ load_word_le(iv + n)); - } - (*block)(out, out, key); - iv = out; - len -= 16; - in += 16; - out += 16; + while (len >= 16) { + for (n = 0; n < 16; n += sizeof(size_t)) { + store_word_le(out + n, load_word_le(in + n) ^ load_word_le(iv + n)); } + (*block)(out, out, key); + iv = out; + len -= 16; + in += 16; + out += 16; } while (len) { @@ -127,66 +114,35 @@ void CRYPTO_cbc128_decrypt(const uint8_t *in, uint8_t *out, size_t len, if ((inptr >= 32 && outptr <= inptr - 32) || inptr < outptr) { // If |out| is at least two blocks behind |in| or completely disjoint, there // is no need to decrypt to a temporary block. + OPENSSL_STATIC_ASSERT(16 % sizeof(size_t) == 0, + "block cannot be evenly divided into words"); const uint8_t *iv = ivec; - - if (STRICT_ALIGNMENT && - ((uintptr_t)in | (uintptr_t)out | (uintptr_t)ivec) % sizeof(size_t) != - 0) { - while (len >= 16) { - (*block)(in, out, key); - for (n = 0; n < 16; ++n) { - out[n] ^= iv[n]; - } - iv = in; - len -= 16; - in += 16; - out += 16; - } - } else if (16 % sizeof(size_t) == 0) { // always true - while (len >= 16) { - (*block)(in, out, key); - for (n = 0; n < 16; n += sizeof(size_t)) { - store_word_le(out + n, load_word_le(out + n) ^ load_word_le(iv + n)); - } - iv = in; - len -= 16; - in += 16; - out += 16; + while (len >= 16) { + (*block)(in, out, key); + for (n = 0; n < 16; n += sizeof(size_t)) { + store_word_le(out + n, load_word_le(out + n) ^ load_word_le(iv + n)); } + iv = in; + len -= 16; + in += 16; + out += 16; } OPENSSL_memcpy(ivec, iv, 16); } else { - // |out| is less than two blocks behind |in|. Decrypting an input block - // directly to |out| would overwrite a ciphertext block before it is used as - // the next block's IV. Decrypt to a temporary block instead. - if (STRICT_ALIGNMENT && - ((uintptr_t)in | (uintptr_t)out | (uintptr_t)ivec) % sizeof(size_t) != - 0) { - uint8_t c; - while (len >= 16) { - (*block)(in, tmp.c, key); - for (n = 0; n < 16; ++n) { - c = in[n]; - out[n] = tmp.c[n] ^ ivec[n]; - ivec[n] = c; - } - len -= 16; - in += 16; - out += 16; - } - } else if (16 % sizeof(size_t) == 0) { // always true - while (len >= 16) { - (*block)(in, tmp.c, key); - for (n = 0; n < 16; n += sizeof(size_t)) { - size_t c = load_word_le(in + n); - store_word_le(out + n, - tmp.t[n / sizeof(size_t)] ^ load_word_le(ivec + n)); - store_word_le(ivec + n, c); - } - len -= 16; - in += 16; - out += 16; + OPENSSL_STATIC_ASSERT(16 % sizeof(size_t) == 0, + "block cannot be evenly divided into words"); + + while (len >= 16) { + (*block)(in, tmp.c, key); + for (n = 0; n < 16; n += sizeof(size_t)) { + size_t c = load_word_le(in + n); + store_word_le(out + n, + tmp.t[n / sizeof(size_t)] ^ load_word_le(ivec + n)); + store_word_le(ivec + n, c); } + len -= 16; + in += 16; + out += 16; } } diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/cfb.c b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/cfb.c index 0a81f3b2..8ca90041 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/cfb.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/cfb.c @@ -60,8 +60,6 @@ OPENSSL_STATIC_ASSERT(16 % sizeof(size_t) == 0, void CRYPTO_cfb128_encrypt(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, uint8_t ivec[16], unsigned *num, int enc, block128_f block) { - size_t l = 0; - assert(in && out && key && ivec && num); unsigned n = *num; @@ -72,21 +70,6 @@ void CRYPTO_cfb128_encrypt(const uint8_t *in, uint8_t *out, size_t len, --len; n = (n + 1) % 16; } -#if STRICT_ALIGNMENT - if (((uintptr_t)in | (uintptr_t)out | (uintptr_t)ivec) % sizeof(size_t) != - 0) { - while (l < len) { - if (n == 0) { - (*block)(ivec, ivec, key); - } - out[l] = ivec[n] ^= in[l]; - ++l; - n = (n + 1) % 16; - } - *num = n; - return; - } -#endif while (len >= 16) { (*block)(ivec, ivec, key); for (; n < 16; n += sizeof(size_t)) { @@ -116,22 +99,6 @@ void CRYPTO_cfb128_encrypt(const uint8_t *in, uint8_t *out, size_t len, --len; n = (n + 1) % 16; } - if (STRICT_ALIGNMENT && - ((uintptr_t)in | (uintptr_t)out | (uintptr_t)ivec) % sizeof(size_t) != - 0) { - while (l < len) { - uint8_t c; - if (n == 0) { - (*block)(ivec, ivec, key); - } - out[l] = ivec[n] ^ (c = in[l]); - ivec[n] = c; - ++l; - n = (n + 1) % 16; - } - *num = n; - return; - } while (len >= 16) { (*block)(ivec, ivec, key); for (; n < 16; n += sizeof(size_t)) { diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/ctr.c b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/ctr.c index b806b9a3..8b0e0594 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/ctr.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/ctr.c @@ -99,26 +99,6 @@ void CRYPTO_ctr128_encrypt(const uint8_t *in, uint8_t *out, size_t len, --len; n = (n + 1) % 16; } - -#if STRICT_ALIGNMENT - if (((uintptr_t)in | (uintptr_t)out | - (uintptr_t)ecount_buf) % sizeof(size_t) != 0) { - size_t l = 0; - while (l < len) { - if (n == 0) { - (*block)(ivec, ecount_buf, key); - ctr128_inc(ivec); - } - out[l] = in[l] ^ ecount_buf[n]; - ++l; - n = (n + 1) % 16; - } - - *num = n; - return; - } -#endif - while (len >= 16) { (*block)(ivec, ecount_buf, key); ctr128_inc(ivec); diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/gcm.c b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/gcm.c index 5e556df2..ca077acc 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/gcm.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/gcm.c @@ -57,12 +57,6 @@ #include "internal.h" #include "../../internal.h" -#if !defined(OPENSSL_NO_ASM) && \ - (defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || \ - defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64) || \ - defined(OPENSSL_PPC64LE)) -#define GHASH_ASM -#endif #define PACK(s) ((size_t)(s) << (sizeof(size_t) * 8 - 16)) #define REDUCE1BIT(V) \ @@ -82,7 +76,7 @@ // bits of a |size_t|. static const size_t kSizeTWithoutLower4Bits = (size_t) -16; -static void gcm_init_4bit(u128 Htable[16], uint64_t H[2]) { +void gcm_init_4bit(u128 Htable[16], const uint64_t H[2]) { u128 V; Htable[0].hi = 0; @@ -127,7 +121,7 @@ static const size_t rem_4bit[16] = { PACK(0xE100), PACK(0xFD20), PACK(0xD940), PACK(0xC560), PACK(0x9180), PACK(0x8DA0), PACK(0xA9C0), PACK(0xB5E0)}; -static void gcm_gmult_4bit(uint64_t Xi[2], const u128 Htable[16]) { +void gcm_gmult_4bit(uint64_t Xi[2], const u128 Htable[16]) { u128 Z; int cnt = 15; size_t rem, nlo, nhi; @@ -182,8 +176,8 @@ static void gcm_gmult_4bit(uint64_t Xi[2], const u128 Htable[16]) { // performance improvement, at least not on x86[_64]. It's here // mostly as reference and a placeholder for possible future // non-trivial optimization[s]... -static void gcm_ghash_4bit(uint64_t Xi[2], const u128 Htable[16], - const uint8_t *inp, size_t len) { +void gcm_ghash_4bit(uint64_t Xi[2], const u128 Htable[16], const uint8_t *inp, + size_t len) { u128 Z; int cnt; size_t rem, nlo, nhi; @@ -237,119 +231,54 @@ static void gcm_ghash_4bit(uint64_t Xi[2], const u128 Htable[16], Xi[1] = CRYPTO_bswap8(Z.lo); } while (inp += 16, len -= 16); } -#else // GHASH_ASM -void gcm_gmult_4bit(uint64_t Xi[2], const u128 Htable[16]); -void gcm_ghash_4bit(uint64_t Xi[2], const u128 Htable[16], const uint8_t *inp, - size_t len); -#endif +#endif // !GHASH_ASM || AARCH64 || PPC64LE #define GCM_MUL(ctx, Xi) gcm_gmult_4bit((ctx)->Xi.u, (ctx)->gcm_key.Htable) -#if defined(GHASH_ASM) #define GHASH(ctx, in, len) \ gcm_ghash_4bit((ctx)->Xi.u, (ctx)->gcm_key.Htable, in, len) // GHASH_CHUNK is "stride parameter" missioned to mitigate cache // trashing effect. In other words idea is to hash data while it's // still in L1 cache after encryption pass... #define GHASH_CHUNK (3 * 1024) -#endif +#if defined(GHASH_ASM_X86_64) || defined(GHASH_ASM_X86) +void gcm_init_ssse3(u128 Htable[16], const uint64_t Xi[2]) { + // Run the existing 4-bit version. + gcm_init_4bit(Htable, Xi); -#if defined(GHASH_ASM) + // First, swap hi and lo. The "4bit" version places hi first. It treats the + // two fields separately, so the order does not matter, but ghash-ssse3 reads + // the entire state into one 128-bit register. + for (int i = 0; i < 16; i++) { + uint64_t tmp = Htable[i].hi; + Htable[i].hi = Htable[i].lo; + Htable[i].lo = tmp; + } -#if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) -#define GCM_FUNCREF_4BIT -void gcm_init_clmul(u128 Htable[16], const uint64_t Xi[2]); -void gcm_gmult_clmul(uint64_t Xi[2], const u128 Htable[16]); -void gcm_ghash_clmul(uint64_t Xi[2], const u128 Htable[16], const uint8_t *inp, - size_t len); - -#if defined(OPENSSL_X86_64) -#define GHASH_ASM_X86_64 -void gcm_init_avx(u128 Htable[16], const uint64_t Xi[2]); -void gcm_gmult_avx(uint64_t Xi[2], const u128 Htable[16]); -void gcm_ghash_avx(uint64_t Xi[2], const u128 Htable[16], const uint8_t *in, - size_t len); -#define AESNI_GCM -size_t aesni_gcm_encrypt(const uint8_t *in, uint8_t *out, size_t len, - const AES_KEY *key, uint8_t ivec[16], uint64_t *Xi); -size_t aesni_gcm_decrypt(const uint8_t *in, uint8_t *out, size_t len, - const AES_KEY *key, uint8_t ivec[16], uint64_t *Xi); -#endif - -#if defined(OPENSSL_X86) -#define GHASH_ASM_X86 -void gcm_gmult_4bit_mmx(uint64_t Xi[2], const u128 Htable[16]); -void gcm_ghash_4bit_mmx(uint64_t Xi[2], const u128 Htable[16], const uint8_t *inp, - size_t len); -#endif - -#elif defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64) -#include -#if __ARM_ARCH__ >= 7 -#define GHASH_ASM_ARM -#define GCM_FUNCREF_4BIT - -static int pmull_capable(void) { - return CRYPTO_is_ARMv8_PMULL_capable(); + // Treat |Htable| as a 16x16 byte table and transpose it. Thus, Htable[i] + // contains the i'th byte of j*H for all j. + uint8_t *Hbytes = (uint8_t *)Htable; + for (int i = 0; i < 16; i++) { + for (int j = 0; j < i; j++) { + uint8_t tmp = Hbytes[16*i + j]; + Hbytes[16*i + j] = Hbytes[16*j + i]; + Hbytes[16*j + i] = tmp; + } + } } - -void gcm_init_v8(u128 Htable[16], const uint64_t Xi[2]); -void gcm_gmult_v8(uint64_t Xi[2], const u128 Htable[16]); -void gcm_ghash_v8(uint64_t Xi[2], const u128 Htable[16], const uint8_t *inp, - size_t len); - -#if defined(OPENSSL_ARM) -// 32-bit ARM also has support for doing GCM with NEON instructions. -static int neon_capable(void) { - return CRYPTO_is_NEON_capable(); -} - -void gcm_init_neon(u128 Htable[16], const uint64_t Xi[2]); -void gcm_gmult_neon(uint64_t Xi[2], const u128 Htable[16]); -void gcm_ghash_neon(uint64_t Xi[2], const u128 Htable[16], const uint8_t *inp, - size_t len); -#else -// AArch64 only has the ARMv8 versions of functions. -static int neon_capable(void) { - return 0; -} -static void gcm_init_neon(u128 Htable[16], const uint64_t Xi[2]) { - abort(); -} -static void gcm_gmult_neon(uint64_t Xi[2], const u128 Htable[16]) { - abort(); -} -static void gcm_ghash_neon(uint64_t Xi[2], const u128 Htable[16], - const uint8_t *inp, size_t len) { - abort(); -} -#endif - -#endif -#elif defined(OPENSSL_PPC64LE) -#define GHASH_ASM_PPC64LE -#define GCM_FUNCREF_4BIT -void gcm_init_p8(u128 Htable[16], const uint64_t Xi[2]); -void gcm_gmult_p8(uint64_t Xi[2], const u128 Htable[16]); -void gcm_ghash_p8(uint64_t Xi[2], const u128 Htable[16], const uint8_t *inp, - size_t len); -#endif -#endif +#endif // GHASH_ASM_X86_64 || GHASH_ASM_X86 #ifdef GCM_FUNCREF_4BIT #undef GCM_MUL #define GCM_MUL(ctx, Xi) (*gcm_gmult_p)((ctx)->Xi.u, (ctx)->gcm_key.Htable) -#ifdef GHASH #undef GHASH #define GHASH(ctx, in, len) \ (*gcm_ghash_p)((ctx)->Xi.u, (ctx)->gcm_key.Htable, in, len) -#endif -#endif +#endif // GCM_FUNCREF_4BIT void CRYPTO_ghash_init(gmult_func *out_mult, ghash_func *out_hash, - u128 *out_key, u128 out_table[16], - int *out_is_avx, - const uint8_t *gcm_key) { + u128 *out_key, u128 out_table[16], int *out_is_avx, + const uint8_t gcm_key[16]) { *out_is_avx = 0; union { @@ -379,6 +308,12 @@ void CRYPTO_ghash_init(gmult_func *out_mult, ghash_func *out_hash, *out_hash = gcm_ghash_clmul; return; } + if (gcm_ssse3_capable()) { + gcm_init_ssse3(out_table, H.u); + *out_mult = gcm_gmult_ssse3; + *out_hash = gcm_ghash_ssse3; + return; + } #elif defined(GHASH_ASM_X86) if (crypto_gcm_clmul_enabled()) { gcm_init_clmul(out_table, H.u); @@ -386,15 +321,21 @@ void CRYPTO_ghash_init(gmult_func *out_mult, ghash_func *out_hash, *out_hash = gcm_ghash_clmul; return; } + if (gcm_ssse3_capable()) { + gcm_init_ssse3(out_table, H.u); + *out_mult = gcm_gmult_ssse3; + *out_hash = gcm_ghash_ssse3; + return; + } #elif defined(GHASH_ASM_ARM) - if (pmull_capable()) { + if (gcm_pmull_capable()) { gcm_init_v8(out_table, H.u); *out_mult = gcm_gmult_v8; *out_hash = gcm_ghash_v8; return; } - if (neon_capable()) { + if (gcm_neon_capable()) { gcm_init_neon(out_table, H.u); *out_mult = gcm_gmult_neon; *out_hash = gcm_ghash_neon; @@ -437,7 +378,6 @@ void CRYPTO_gcm128_init_key(GCM128_KEY *gcm_key, const AES_KEY *aes_key, void CRYPTO_gcm128_setiv(GCM128_CONTEXT *ctx, const AES_KEY *key, const uint8_t *iv, size_t len) { - unsigned int ctr; #ifdef GCM_FUNCREF_4BIT void (*gcm_gmult_p)(uint64_t Xi[2], const u128 Htable[16]) = ctx->gcm_key.gmult; @@ -452,6 +392,7 @@ void CRYPTO_gcm128_setiv(GCM128_CONTEXT *ctx, const AES_KEY *key, ctx->ares = 0; ctx->mres = 0; + uint32_t ctr; if (len == 12) { OPENSSL_memcpy(ctx->Yi.c, iv, 12); ctx->Yi.c[15] = 1; @@ -486,8 +427,6 @@ void CRYPTO_gcm128_setiv(GCM128_CONTEXT *ctx, const AES_KEY *key, } int CRYPTO_gcm128_aad(GCM128_CONTEXT *ctx, const uint8_t *aad, size_t len) { - unsigned int n; - uint64_t alen = ctx->len.u[0]; #ifdef GCM_FUNCREF_4BIT void (*gcm_gmult_p)(uint64_t Xi[2], const u128 Htable[16]) = ctx->gcm_key.gmult; @@ -501,13 +440,13 @@ int CRYPTO_gcm128_aad(GCM128_CONTEXT *ctx, const uint8_t *aad, size_t len) { return 0; } - alen += len; + uint64_t alen = ctx->len.u[0] + len; if (alen > (UINT64_C(1) << 61) || (sizeof(len) == 8 && alen < len)) { return 0; } ctx->len.u[0] = alen; - n = ctx->ares; + unsigned n = ctx->ares; if (n) { while (n && len) { ctx->Xi.c[n] ^= *(aad++); @@ -523,23 +462,12 @@ int CRYPTO_gcm128_aad(GCM128_CONTEXT *ctx, const uint8_t *aad, size_t len) { } // Process a whole number of blocks. -#ifdef GHASH size_t len_blocks = len & kSizeTWithoutLower4Bits; if (len_blocks != 0) { GHASH(ctx, aad, len_blocks); aad += len_blocks; len -= len_blocks; } -#else - while (len >= 16) { - for (size_t i = 0; i < 16; ++i) { - ctx->Xi.c[i] ^= aad[i]; - } - GCM_MUL(ctx, Xi); - aad += 16; - len -= 16; - } -#endif // Process the remainder. if (len != 0) { @@ -555,19 +483,15 @@ int CRYPTO_gcm128_aad(GCM128_CONTEXT *ctx, const uint8_t *aad, size_t len) { int CRYPTO_gcm128_encrypt(GCM128_CONTEXT *ctx, const AES_KEY *key, const uint8_t *in, uint8_t *out, size_t len) { - unsigned int n, ctr; - uint64_t mlen = ctx->len.u[1]; block128_f block = ctx->gcm_key.block; #ifdef GCM_FUNCREF_4BIT void (*gcm_gmult_p)(uint64_t Xi[2], const u128 Htable[16]) = ctx->gcm_key.gmult; -#ifdef GHASH void (*gcm_ghash_p)(uint64_t Xi[2], const u128 Htable[16], const uint8_t *inp, size_t len) = ctx->gcm_key.ghash; -#endif #endif - mlen += len; + uint64_t mlen = ctx->len.u[1] + len; if (mlen > ((UINT64_C(1) << 36) - 32) || (sizeof(len) == 8 && mlen < len)) { return 0; @@ -580,9 +504,7 @@ int CRYPTO_gcm128_encrypt(GCM128_CONTEXT *ctx, const AES_KEY *key, ctx->ares = 0; } - ctr = CRYPTO_bswap4(ctx->Yi.d[3]); - - n = ctx->mres; + unsigned n = ctx->mres; if (n) { while (n && len) { ctx->Xi.c[n] ^= *(out++) = *(in++) ^ ctx->EKi.c[n]; @@ -596,25 +518,8 @@ int CRYPTO_gcm128_encrypt(GCM128_CONTEXT *ctx, const AES_KEY *key, return 1; } } - if (STRICT_ALIGNMENT && - ((uintptr_t)in | (uintptr_t)out) % sizeof(size_t) != 0) { - for (size_t i = 0; i < len; ++i) { - if (n == 0) { - (*block)(ctx->Yi.c, ctx->EKi.c, key); - ++ctr; - ctx->Yi.d[3] = CRYPTO_bswap4(ctr); - } - ctx->Xi.c[n] ^= out[i] = in[i] ^ ctx->EKi.c[n]; - n = (n + 1) % 16; - if (n == 0) { - GCM_MUL(ctx, Xi); - } - } - ctx->mres = n; - return 1; - } -#if defined(GHASH) && defined(GHASH_CHUNK) + uint32_t ctr = CRYPTO_bswap4(ctx->Yi.d[3]); while (len >= GHASH_CHUNK) { size_t j = GHASH_CHUNK; @@ -649,22 +554,6 @@ int CRYPTO_gcm128_encrypt(GCM128_CONTEXT *ctx, const AES_KEY *key, } GHASH(ctx, out - len_blocks, len_blocks); } -#else - while (len >= 16) { - (*block)(ctx->Yi.c, ctx->EKi.c, key); - ++ctr; - ctx->Yi.d[3] = CRYPTO_bswap4(ctr); - for (size_t i = 0; i < 16; i += sizeof(size_t)) { - size_t tmp = load_word_le(in + i) ^ ctx->EKi.t[i / sizeof(size_t)]; - store_word_le(out + i, tmp); - ctx->Xi.t[i / sizeof(size_t)] ^= tmp; - } - GCM_MUL(ctx, Xi); - out += 16; - in += 16; - len -= 16; - } -#endif if (len) { (*block)(ctx->Yi.c, ctx->EKi.c, key); ++ctr; @@ -682,19 +571,15 @@ int CRYPTO_gcm128_encrypt(GCM128_CONTEXT *ctx, const AES_KEY *key, int CRYPTO_gcm128_decrypt(GCM128_CONTEXT *ctx, const AES_KEY *key, const unsigned char *in, unsigned char *out, size_t len) { - unsigned int n, ctr; - uint64_t mlen = ctx->len.u[1]; block128_f block = ctx->gcm_key.block; #ifdef GCM_FUNCREF_4BIT void (*gcm_gmult_p)(uint64_t Xi[2], const u128 Htable[16]) = ctx->gcm_key.gmult; -#ifdef GHASH void (*gcm_ghash_p)(uint64_t Xi[2], const u128 Htable[16], const uint8_t *inp, size_t len) = ctx->gcm_key.ghash; -#endif #endif - mlen += len; + uint64_t mlen = ctx->len.u[1] + len; if (mlen > ((UINT64_C(1) << 36) - 32) || (sizeof(len) == 8 && mlen < len)) { return 0; @@ -707,9 +592,7 @@ int CRYPTO_gcm128_decrypt(GCM128_CONTEXT *ctx, const AES_KEY *key, ctx->ares = 0; } - ctr = CRYPTO_bswap4(ctx->Yi.d[3]); - - n = ctx->mres; + unsigned n = ctx->mres; if (n) { while (n && len) { uint8_t c = *(in++); @@ -725,28 +608,8 @@ int CRYPTO_gcm128_decrypt(GCM128_CONTEXT *ctx, const AES_KEY *key, return 1; } } - if (STRICT_ALIGNMENT && - ((uintptr_t)in | (uintptr_t)out) % sizeof(size_t) != 0) { - for (size_t i = 0; i < len; ++i) { - uint8_t c; - if (n == 0) { - (*block)(ctx->Yi.c, ctx->EKi.c, key); - ++ctr; - ctx->Yi.d[3] = CRYPTO_bswap4(ctr); - } - c = in[i]; - out[i] = c ^ ctx->EKi.c[n]; - ctx->Xi.c[n] ^= c; - n = (n + 1) % 16; - if (n == 0) { - GCM_MUL(ctx, Xi); - } - } - ctx->mres = n; - return 1; - } -#if defined(GHASH) && defined(GHASH_CHUNK) + uint32_t ctr = CRYPTO_bswap4(ctx->Yi.d[3]); while (len >= GHASH_CHUNK) { size_t j = GHASH_CHUNK; @@ -781,22 +644,6 @@ int CRYPTO_gcm128_decrypt(GCM128_CONTEXT *ctx, const AES_KEY *key, len -= 16; } } -#else - while (len >= 16) { - (*block)(ctx->Yi.c, ctx->EKi.c, key); - ++ctr; - ctx->Yi.d[3] = CRYPTO_bswap4(ctr); - for (size_t i = 0; i < 16; i += sizeof(size_t)) { - size_t c = load_word_le(in + i); - store_word_le(out + i, c ^ ctx->EKi.t[i / sizeof(size_t)]); - ctx->Xi.t[i / sizeof(size_t)] ^= c; - } - GCM_MUL(ctx, Xi); - out += 16; - in += 16; - len -= 16; - } -#endif if (len) { (*block)(ctx->Yi.c, ctx->EKi.c, key); ++ctr; @@ -816,18 +663,14 @@ int CRYPTO_gcm128_decrypt(GCM128_CONTEXT *ctx, const AES_KEY *key, int CRYPTO_gcm128_encrypt_ctr32(GCM128_CONTEXT *ctx, const AES_KEY *key, const uint8_t *in, uint8_t *out, size_t len, ctr128_f stream) { - unsigned int n, ctr; - uint64_t mlen = ctx->len.u[1]; #ifdef GCM_FUNCREF_4BIT void (*gcm_gmult_p)(uint64_t Xi[2], const u128 Htable[16]) = ctx->gcm_key.gmult; -#ifdef GHASH void (*gcm_ghash_p)(uint64_t Xi[2], const u128 Htable[16], const uint8_t *inp, size_t len) = ctx->gcm_key.ghash; -#endif #endif - mlen += len; + uint64_t mlen = ctx->len.u[1] + len; if (mlen > ((UINT64_C(1) << 36) - 32) || (sizeof(len) == 8 && mlen < len)) { return 0; @@ -840,7 +683,7 @@ int CRYPTO_gcm128_encrypt_ctr32(GCM128_CONTEXT *ctx, const AES_KEY *key, ctx->ares = 0; } - n = ctx->mres; + unsigned n = ctx->mres; if (n) { while (n && len) { ctx->Xi.c[n] ^= *(out++) = *(in++) ^ ctx->EKi.c[n]; @@ -866,9 +709,7 @@ int CRYPTO_gcm128_encrypt_ctr32(GCM128_CONTEXT *ctx, const AES_KEY *key, } #endif - ctr = CRYPTO_bswap4(ctx->Yi.d[3]); - -#if defined(GHASH) + uint32_t ctr = CRYPTO_bswap4(ctx->Yi.d[3]); while (len >= GHASH_CHUNK) { (*stream)(in, out, GHASH_CHUNK / 16, key, ctx->Yi.c); ctr += GHASH_CHUNK / 16; @@ -878,28 +719,17 @@ int CRYPTO_gcm128_encrypt_ctr32(GCM128_CONTEXT *ctx, const AES_KEY *key, in += GHASH_CHUNK; len -= GHASH_CHUNK; } -#endif - size_t i = len & kSizeTWithoutLower4Bits; - if (i != 0) { - size_t j = i / 16; + size_t len_blocks = len & kSizeTWithoutLower4Bits; + if (len_blocks != 0) { + size_t j = len_blocks / 16; (*stream)(in, out, j, key, ctx->Yi.c); ctr += (unsigned int)j; ctx->Yi.d[3] = CRYPTO_bswap4(ctr); - in += i; - len -= i; -#if defined(GHASH) - GHASH(ctx, out, i); - out += i; -#else - while (j--) { - for (i = 0; i < 16; ++i) { - ctx->Xi.c[i] ^= out[i]; - } - GCM_MUL(ctx, Xi); - out += 16; - } -#endif + in += len_blocks; + len -= len_blocks; + GHASH(ctx, out, len_blocks); + out += len_blocks; } if (len) { (*ctx->gcm_key.block)(ctx->Yi.c, ctx->EKi.c, key); @@ -918,18 +748,14 @@ int CRYPTO_gcm128_encrypt_ctr32(GCM128_CONTEXT *ctx, const AES_KEY *key, int CRYPTO_gcm128_decrypt_ctr32(GCM128_CONTEXT *ctx, const AES_KEY *key, const uint8_t *in, uint8_t *out, size_t len, ctr128_f stream) { - unsigned int n, ctr; - uint64_t mlen = ctx->len.u[1]; #ifdef GCM_FUNCREF_4BIT void (*gcm_gmult_p)(uint64_t Xi[2], const u128 Htable[16]) = ctx->gcm_key.gmult; -#ifdef GHASH void (*gcm_ghash_p)(uint64_t Xi[2], const u128 Htable[16], const uint8_t *inp, size_t len) = ctx->gcm_key.ghash; -#endif #endif - mlen += len; + uint64_t mlen = ctx->len.u[1] + len; if (mlen > ((UINT64_C(1) << 36) - 32) || (sizeof(len) == 8 && mlen < len)) { return 0; @@ -942,7 +768,7 @@ int CRYPTO_gcm128_decrypt_ctr32(GCM128_CONTEXT *ctx, const AES_KEY *key, ctx->ares = 0; } - n = ctx->mres; + unsigned n = ctx->mres; if (n) { while (n && len) { uint8_t c = *(in++); @@ -970,9 +796,7 @@ int CRYPTO_gcm128_decrypt_ctr32(GCM128_CONTEXT *ctx, const AES_KEY *key, } #endif - ctr = CRYPTO_bswap4(ctx->Yi.d[3]); - -#if defined(GHASH) + uint32_t ctr = CRYPTO_bswap4(ctx->Yi.d[3]); while (len >= GHASH_CHUNK) { GHASH(ctx, in, GHASH_CHUNK); (*stream)(in, out, GHASH_CHUNK / 16, key, ctx->Yi.c); @@ -982,31 +806,17 @@ int CRYPTO_gcm128_decrypt_ctr32(GCM128_CONTEXT *ctx, const AES_KEY *key, in += GHASH_CHUNK; len -= GHASH_CHUNK; } -#endif - size_t i = len & kSizeTWithoutLower4Bits; - if (i != 0) { - size_t j = i / 16; + size_t len_blocks = len & kSizeTWithoutLower4Bits; + if (len_blocks != 0) { + size_t j = len_blocks / 16; -#if defined(GHASH) - GHASH(ctx, in, i); -#else - while (j--) { - size_t k; - for (k = 0; k < 16; ++k) { - ctx->Xi.c[k] ^= in[k]; - } - GCM_MUL(ctx, Xi); - in += 16; - } - j = i / 16; - in -= i; -#endif + GHASH(ctx, in, len_blocks); (*stream)(in, out, j, key, ctx->Yi.c); ctr += (unsigned int)j; ctx->Yi.d[3] = CRYPTO_bswap4(ctr); - out += i; - in += i; - len -= i; + out += len_blocks; + in += len_blocks; + len -= len_blocks; } if (len) { (*ctx->gcm_key.block)(ctx->Yi.c, ctx->EKi.c, key); @@ -1025,8 +835,6 @@ int CRYPTO_gcm128_decrypt_ctr32(GCM128_CONTEXT *ctx, const AES_KEY *key, } int CRYPTO_gcm128_finish(GCM128_CONTEXT *ctx, const uint8_t *tag, size_t len) { - uint64_t alen = ctx->len.u[0] << 3; - uint64_t clen = ctx->len.u[1] << 3; #ifdef GCM_FUNCREF_4BIT void (*gcm_gmult_p)(uint64_t Xi[2], const u128 Htable[16]) = ctx->gcm_key.gmult; @@ -1036,11 +844,8 @@ int CRYPTO_gcm128_finish(GCM128_CONTEXT *ctx, const uint8_t *tag, size_t len) { GCM_MUL(ctx, Xi); } - alen = CRYPTO_bswap8(alen); - clen = CRYPTO_bswap8(clen); - - ctx->Xi.u[0] ^= alen; - ctx->Xi.u[1] ^= clen; + ctx->Xi.u[0] ^= CRYPTO_bswap8(ctx->len.u[0] << 3); + ctx->Xi.u[1] ^= CRYPTO_bswap8(ctx->len.u[1] << 3); GCM_MUL(ctx, Xi); ctx->Xi.u[0] ^= ctx->EK0.u[0]; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/gcm_test.cc b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/gcm_test.cc index a6b7fc02..b2e805c1 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/gcm_test.cc +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/gcm_test.cc @@ -54,10 +54,13 @@ #include #include +#include -#include "internal.h" +#include "../../test/abi_test.h" #include "../../test/file_test.h" #include "../../test/test_util.h" +#include "../aes/internal.h" +#include "internal.h" TEST(GCMTest, TestVectors) { @@ -90,7 +93,10 @@ TEST(GCMTest, TestVectors) { CRYPTO_gcm128_encrypt(&ctx, &aes_key, plaintext.data(), out.data(), plaintext.size()); } - ASSERT_TRUE(CRYPTO_gcm128_finish(&ctx, tag.data(), tag.size())); + + std::vector got_tag(tag.size()); + CRYPTO_gcm128_tag(&ctx, got_tag.data(), got_tag.size()); + EXPECT_EQ(Bytes(tag), Bytes(got_tag)); EXPECT_EQ(Bytes(ciphertext), Bytes(out)); CRYPTO_gcm128_setiv(&ctx, &aes_key, nonce.data(), nonce.size()); @@ -112,3 +118,108 @@ TEST(GCMTest, ByteSwap) { EXPECT_EQ(UINT64_C(0x0807060504030201), CRYPTO_bswap8(UINT64_C(0x0102030405060708))); } + +#if defined(SUPPORTS_ABI_TEST) && defined(GHASH_ASM) +TEST(GCMTest, ABI) { + static const uint64_t kH[2] = { + UINT64_C(0x66e94bd4ef8a2c3b), + UINT64_C(0x884cfa59ca342b2e), + }; + static const size_t kBlockCounts[] = {1, 2, 3, 4, 7, 8, 15, 16, 31, 32}; + uint8_t buf[16 * 32]; + OPENSSL_memset(buf, 42, sizeof(buf)); + + uint64_t X[2] = { + UINT64_C(0x0388dace60b6a392), + UINT64_C(0xf328c2b971b2fe78), + }; + + alignas(16) u128 Htable[16]; + CHECK_ABI(gcm_init_4bit, Htable, kH); +#if defined(GHASH_ASM_X86) + CHECK_ABI(gcm_gmult_4bit_mmx, X, Htable); + for (size_t blocks : kBlockCounts) { + CHECK_ABI(gcm_ghash_4bit_mmx, X, Htable, buf, 16 * blocks); + } +#else + CHECK_ABI(gcm_gmult_4bit, X, Htable); + for (size_t blocks : kBlockCounts) { + CHECK_ABI(gcm_ghash_4bit, X, Htable, buf, 16 * blocks); + } +#endif // GHASH_ASM_X86 + +#if defined(GHASH_ASM_X86) || defined(GHASH_ASM_X86_64) + if (gcm_ssse3_capable()) { + CHECK_ABI_SEH(gcm_init_ssse3, Htable, kH); + CHECK_ABI_SEH(gcm_gmult_ssse3, X, Htable); + for (size_t blocks : kBlockCounts) { + CHECK_ABI_SEH(gcm_ghash_ssse3, X, Htable, buf, 16 * blocks); + } + } + + if (crypto_gcm_clmul_enabled()) { + CHECK_ABI_SEH(gcm_init_clmul, Htable, kH); + CHECK_ABI_SEH(gcm_gmult_clmul, X, Htable); + for (size_t blocks : kBlockCounts) { + CHECK_ABI_SEH(gcm_ghash_clmul, X, Htable, buf, 16 * blocks); + } + +#if defined(GHASH_ASM_X86_64) + if (((OPENSSL_ia32cap_get()[1] >> 22) & 0x41) == 0x41) { // AVX+MOVBE + CHECK_ABI_SEH(gcm_init_avx, Htable, kH); + CHECK_ABI_SEH(gcm_gmult_avx, X, Htable); + for (size_t blocks : kBlockCounts) { + CHECK_ABI_SEH(gcm_ghash_avx, X, Htable, buf, 16 * blocks); + } + + if (hwaes_capable()) { + AES_KEY aes_key; + static const uint8_t kKey[16] = {0}; + + // aesni_gcm_* makes assumptions about |GCM128_CONTEXT|'s layout. + GCM128_CONTEXT gcm; + memset(&gcm, 0, sizeof(gcm)); + memcpy(&gcm.gcm_key.H, kH, sizeof(kH)); + memcpy(&gcm.gcm_key.Htable, Htable, sizeof(Htable)); + memcpy(&gcm.Xi, X, sizeof(X)); + uint8_t iv[16] = {0}; + + aes_hw_set_encrypt_key(kKey, 128, &aes_key); + for (size_t blocks : kBlockCounts) { + CHECK_ABI(aesni_gcm_encrypt, buf, buf, blocks * 16, &aes_key, iv, + gcm.Xi.u); + CHECK_ABI(aesni_gcm_encrypt, buf, buf, blocks * 16 + 7, &aes_key, iv, + gcm.Xi.u); + } + aes_hw_set_decrypt_key(kKey, 128, &aes_key); + for (size_t blocks : kBlockCounts) { + CHECK_ABI(aesni_gcm_decrypt, buf, buf, blocks * 16, &aes_key, iv, + gcm.Xi.u); + CHECK_ABI(aesni_gcm_decrypt, buf, buf, blocks * 16 + 7, &aes_key, iv, + gcm.Xi.u); + } + } + } +#endif // GHASH_ASM_X86_64 + } +#endif // GHASH_ASM_X86 || GHASH_ASM_X86_64 + +#if defined(GHASH_ASM_ARM) + if (gcm_neon_capable()) { + CHECK_ABI(gcm_init_neon, Htable, kH); + CHECK_ABI(gcm_gmult_neon, X, Htable); + for (size_t blocks : kBlockCounts) { + CHECK_ABI(gcm_ghash_neon, X, Htable, buf, 16 * blocks); + } + } + + if (gcm_pmull_capable()) { + CHECK_ABI(gcm_init_v8, Htable, kH); + CHECK_ABI(gcm_gmult_v8, X, Htable); + for (size_t blocks : kBlockCounts) { + CHECK_ABI(gcm_ghash_v8, X, Htable, buf, 16 * blocks); + } + } +#endif // GHASH_ASM_ARM +} +#endif // SUPPORTS_ABI_TEST && GHASH_ASM diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/internal.h b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/internal.h index 23aaca2c..dec1e56c 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/modes/internal.h +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/modes/internal.h @@ -50,8 +50,11 @@ #define OPENSSL_HEADER_MODES_INTERNAL_H #include -#include +#include +#include + +#include #include #include "../../internal.h" @@ -61,12 +64,6 @@ extern "C" { #endif -#define STRICT_ALIGNMENT 1 -#if defined(OPENSSL_X86_64) || defined(OPENSSL_X86) || defined(OPENSSL_AARCH64) -#undef STRICT_ALIGNMENT -#define STRICT_ALIGNMENT 0 -#endif - static inline uint32_t GETU32(const void *in) { uint32_t v; OPENSSL_memcpy(&v, in, sizeof(v)); @@ -127,12 +124,6 @@ void CRYPTO_ctr128_encrypt_ctr32(const uint8_t *in, uint8_t *out, size_t len, uint8_t ecount_buf[16], unsigned *num, ctr128_f ctr); -#if !defined(OPENSSL_NO_ASM) && \ - (defined(OPENSSL_X86) || defined(OPENSSL_X86_64)) -void aesni_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, size_t blocks, - const AES_KEY *key, const uint8_t *ivec); -#endif - // GCM. // @@ -156,7 +147,10 @@ typedef void (*ghash_func)(uint64_t Xi[2], const u128 Htable[16], typedef struct gcm128_key_st { // Note the MOVBE-based, x86-64, GHASH assembly requires |H| and |Htable| to - // be the first two elements of this struct. + // be the first two elements of this struct. Additionally, some assembly + // routines require a 16-byte-aligned |Htable| when hashing data, but not + // initialization. |GCM128_KEY| is not itself aligned to simplify embedding in + // |EVP_AEAD_CTX|, but |Htable|'s offset must be a multiple of 16. u128 H; u128 Htable[16]; gmult_func gmult; @@ -181,8 +175,10 @@ typedef struct { } Yi, EKi, EK0, len, Xi; // Note that the order of |Xi| and |gcm_key| is fixed by the MOVBE-based, - // x86-64, GHASH assembly. - GCM128_KEY gcm_key; + // x86-64, GHASH assembly. Additionally, some assembly routines require + // |gcm_key| to be 16-byte aligned. |GCM128_KEY| is not itself aligned to + // simplify embedding in |EVP_AEAD_CTX|. + alignas(16) GCM128_KEY gcm_key; unsigned mres, ares; } GCM128_CONTEXT; @@ -199,7 +195,7 @@ int crypto_gcm_clmul_enabled(void); // AVX implementation was used |*out_is_avx| will be true. void CRYPTO_ghash_init(gmult_func *out_mult, ghash_func *out_hash, u128 *out_key, u128 out_table[16], int *out_is_avx, - const uint8_t *gcm_key); + const uint8_t gcm_key[16]); // CRYPTO_gcm128_init_key initialises |gcm_key| to use |block| (typically AES) // with the given key. |block_is_hwaes| is one if |block| is |aes_hw_encrypt|. @@ -263,6 +259,92 @@ OPENSSL_EXPORT void CRYPTO_gcm128_tag(GCM128_CONTEXT *ctx, uint8_t *tag, size_t len); +// GCM assembly. + +#if !defined(OPENSSL_NO_ASM) && \ + (defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || \ + defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64) || \ + defined(OPENSSL_PPC64LE)) +#define GHASH_ASM +#endif + +void gcm_init_4bit(u128 Htable[16], const uint64_t H[2]); +void gcm_gmult_4bit(uint64_t Xi[2], const u128 Htable[16]); +void gcm_ghash_4bit(uint64_t Xi[2], const u128 Htable[16], const uint8_t *inp, + size_t len); + +#if defined(GHASH_ASM) + +#if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) +#define GCM_FUNCREF_4BIT +void gcm_init_clmul(u128 Htable[16], const uint64_t Xi[2]); +void gcm_gmult_clmul(uint64_t Xi[2], const u128 Htable[16]); +void gcm_ghash_clmul(uint64_t Xi[2], const u128 Htable[16], const uint8_t *inp, + size_t len); + +OPENSSL_INLINE char gcm_ssse3_capable(void) { + return (OPENSSL_ia32cap_get()[1] & (1 << (41 - 32))) != 0; +} + +// |gcm_gmult_ssse3| and |gcm_ghash_ssse3| require |Htable| to be +// 16-byte-aligned, but |gcm_init_ssse3| does not. +void gcm_init_ssse3(u128 Htable[16], const uint64_t Xi[2]); +void gcm_gmult_ssse3(uint64_t Xi[2], const u128 Htable[16]); +void gcm_ghash_ssse3(uint64_t Xi[2], const u128 Htable[16], const uint8_t *in, + size_t len); + +#if defined(OPENSSL_X86_64) +#define GHASH_ASM_X86_64 +void gcm_init_avx(u128 Htable[16], const uint64_t Xi[2]); +void gcm_gmult_avx(uint64_t Xi[2], const u128 Htable[16]); +void gcm_ghash_avx(uint64_t Xi[2], const u128 Htable[16], const uint8_t *in, + size_t len); + +#define AESNI_GCM +size_t aesni_gcm_encrypt(const uint8_t *in, uint8_t *out, size_t len, + const AES_KEY *key, uint8_t ivec[16], uint64_t *Xi); +size_t aesni_gcm_decrypt(const uint8_t *in, uint8_t *out, size_t len, + const AES_KEY *key, uint8_t ivec[16], uint64_t *Xi); +#endif // OPENSSL_X86_64 + +#if defined(OPENSSL_X86) +#define GHASH_ASM_X86 +void gcm_gmult_4bit_mmx(uint64_t Xi[2], const u128 Htable[16]); +void gcm_ghash_4bit_mmx(uint64_t Xi[2], const u128 Htable[16], const uint8_t *inp, + size_t len); +#endif // OPENSSL_X86 + +#elif defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64) +#define GHASH_ASM_ARM +#define GCM_FUNCREF_4BIT + +OPENSSL_INLINE int gcm_pmull_capable(void) { + return CRYPTO_is_ARMv8_PMULL_capable(); +} + +void gcm_init_v8(u128 Htable[16], const uint64_t Xi[2]); +void gcm_gmult_v8(uint64_t Xi[2], const u128 Htable[16]); +void gcm_ghash_v8(uint64_t Xi[2], const u128 Htable[16], const uint8_t *inp, + size_t len); + +OPENSSL_INLINE int gcm_neon_capable(void) { return CRYPTO_is_NEON_capable(); } + +void gcm_init_neon(u128 Htable[16], const uint64_t Xi[2]); +void gcm_gmult_neon(uint64_t Xi[2], const u128 Htable[16]); +void gcm_ghash_neon(uint64_t Xi[2], const u128 Htable[16], const uint8_t *inp, + size_t len); + +#elif defined(OPENSSL_PPC64LE) +#define GHASH_ASM_PPC64LE +#define GCM_FUNCREF_4BIT +void gcm_init_p8(u128 Htable[16], const uint64_t Xi[2]); +void gcm_gmult_p8(uint64_t Xi[2], const u128 Htable[16]); +void gcm_ghash_p8(uint64_t Xi[2], const u128 Htable[16], const uint8_t *inp, + size_t len); +#endif +#endif // GHASH_ASM + + // CCM. typedef struct ccm128_context { @@ -376,10 +458,11 @@ typedef union { struct polyval_ctx { // Note that the order of |S|, |H| and |Htable| is fixed by the MOVBE-based, - // x86-64, GHASH assembly. + // x86-64, GHASH assembly. Additionally, some assembly routines require + // |Htable| to be 16-byte aligned. polyval_block S; u128 H; - u128 Htable[16]; + alignas(16) u128 Htable[16]; gmult_func gmult; ghash_func ghash; }; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/rand/asm/rdrand-x86_64.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/rand/asm/rdrand-x86_64.pl index 056dd748..eb2a5926 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/rand/asm/rdrand-x86_64.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/rand/asm/rdrand-x86_64.pl @@ -14,17 +14,27 @@ # OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -$flavour = shift; -$output = shift; +use strict; + +my $flavour = shift; +my $output = shift; if ($flavour =~ /\./) { $output = $flavour; undef $flavour; } -$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; +my $win64 = 0; +$win64 = 1 if ($flavour =~ /[nm]asm|mingw64/ || $output =~ /\.asm$/); + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; +my $dir = $1; +my $xlate; ( $xlate="${dir}../../../perlasm/x86_64-xlate.pl" and -f $xlate) or die "can't locate x86_64-xlate.pl"; open OUT,"| \"$^X\" $xlate $flavour $output"; *STDOUT=*OUT; +my ($out, $len, $tmp1, $tmp2) = $win64 ? ("%rcx", "%rdx", "%r8", "%r9") + : ("%rdi", "%rsi", "%rdx", "%rcx"); + print<<___; .text @@ -32,40 +42,37 @@ print<<___; # |out|. It returns one on success or zero on hardware failure. # int CRYPTO_rdrand(uint8_t out[8]); .globl CRYPTO_rdrand -.type CRYPTO_rdrand,\@function,1 +.type CRYPTO_rdrand,\@abi-omnipotent .align 16 CRYPTO_rdrand: .cfi_startproc xorq %rax, %rax - # This is rdrand %rcx. It sets rcx to a random value and sets the carry - # flag on success. - .byte 0x48, 0x0f, 0xc7, 0xf1 + rdrand $tmp1 # An add-with-carry of zero effectively sets %rax to the carry flag. adcq %rax, %rax - movq %rcx, 0(%rdi) + movq $tmp1, 0($out) retq .cfi_endproc +.size CRYPTO_rdrand,.-CRYPTO_rdrand # CRYPTO_rdrand_multiple8_buf fills |len| bytes at |buf| with random data from # the hardware RNG. The |len| argument must be a multiple of eight. It returns # one on success and zero on hardware failure. # int CRYPTO_rdrand_multiple8_buf(uint8_t *buf, size_t len); .globl CRYPTO_rdrand_multiple8_buf -.type CRYPTO_rdrand_multiple8_buf,\@function,2 +.type CRYPTO_rdrand_multiple8_buf,\@abi-omnipotent .align 16 CRYPTO_rdrand_multiple8_buf: .cfi_startproc - test %rsi, %rsi + test $len, $len jz .Lout - movq \$8, %rdx + movq \$8, $tmp1 .Lloop: - # This is rdrand %rcx. It sets rcx to a random value and sets the carry - # flag on success. - .byte 0x48, 0x0f, 0xc7, 0xf1 + rdrand $tmp2 jnc .Lerr - movq %rcx, 0(%rdi) - addq %rdx, %rdi - subq %rdx, %rsi + movq $tmp2, 0($out) + addq $tmp1, $out + subq $tmp1, $len jnz .Lloop .Lout: movq \$1, %rax @@ -74,6 +81,7 @@ CRYPTO_rdrand_multiple8_buf: xorq %rax, %rax retq .cfi_endproc +.size CRYPTO_rdrand_multiple8_buf,.-CRYPTO_rdrand_multiple8_buf ___ -close STDOUT; # flush +close STDOUT or die "error closing STDOUT"; # flush diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/rand/internal.h b/third_party/boringssl/kit/src/crypto/fipsmodule/rand/internal.h index f73f4a17..ad75823f 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/rand/internal.h +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/rand/internal.h @@ -16,6 +16,7 @@ #define OPENSSL_HEADER_CRYPTO_RAND_INTERNAL_H #include +#include #include "../../internal.h" #include "../modes/internal.h" @@ -85,6 +86,22 @@ OPENSSL_EXPORT int CTR_DRBG_generate(CTR_DRBG_STATE *drbg, uint8_t *out, OPENSSL_EXPORT void CTR_DRBG_clear(CTR_DRBG_STATE *drbg); +#if defined(OPENSSL_X86_64) && !defined(OPENSSL_NO_ASM) +OPENSSL_INLINE int have_rdrand(void) { + return (OPENSSL_ia32cap_get()[1] & (1u << 30)) != 0; +} + +// CRYPTO_rdrand writes eight bytes of random data from the hardware RNG to +// |out|. It returns one on success or zero on hardware failure. +int CRYPTO_rdrand(uint8_t out[8]); + +// CRYPTO_rdrand_multiple8_buf fills |len| bytes at |buf| with random data from +// the hardware RNG. The |len| argument must be a multiple of eight. It returns +// one on success and zero on hardware failure. +int CRYPTO_rdrand_multiple8_buf(uint8_t *buf, size_t len); +#endif // OPENSSL_X86_64 && !OPENSSL_NO_ASM + + #if defined(__cplusplus) } // extern C #endif diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/rand/rand.c b/third_party/boringssl/kit/src/crypto/fipsmodule/rand/rand.c index 41280334..a8ef4587 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/rand/rand.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/rand/rand.c @@ -125,15 +125,6 @@ static void rand_thread_state_free(void *state_in) { #if defined(OPENSSL_X86_64) && !defined(OPENSSL_NO_ASM) && \ !defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE) - -// These functions are defined in asm/rdrand-x86_64.pl -extern int CRYPTO_rdrand(uint8_t out[8]); -extern int CRYPTO_rdrand_multiple8_buf(uint8_t *buf, size_t len); - -static int have_rdrand(void) { - return (OPENSSL_ia32cap_get()[1] & (1u << 30)) != 0; -} - static int hwrand(uint8_t *buf, const size_t len) { if (!have_rdrand()) { return 0; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/rand/urandom.c b/third_party/boringssl/kit/src/crypto/fipsmodule/rand/urandom.c index d969675e..56e4fbd2 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/rand/urandom.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/rand/urandom.c @@ -120,7 +120,7 @@ static ssize_t boringssl_getrandom(void *buf, size_t buf_len, unsigned flags) { #endif // OPENSSL_LINUX // rand_lock is used to protect the |*_requested| variables. -DEFINE_STATIC_MUTEX(rand_lock); +DEFINE_STATIC_MUTEX(rand_lock) // The following constants are magic values of |urandom_fd|. static const int kUnset = 0; @@ -128,12 +128,12 @@ static const int kHaveGetrandom = -3; // urandom_fd_requested is set by |RAND_set_urandom_fd|. It's protected by // |rand_lock|. -DEFINE_BSS_GET(int, urandom_fd_requested); +DEFINE_BSS_GET(int, urandom_fd_requested) // urandom_fd is a file descriptor to /dev/urandom. It's protected by |once|. -DEFINE_BSS_GET(int, urandom_fd); +DEFINE_BSS_GET(int, urandom_fd) -DEFINE_STATIC_ONCE(rand_once); +DEFINE_STATIC_ONCE(rand_once) // init_once initializes the state of this module to values previously // requested. This is the only function that modifies |urandom_fd| and diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/rsa/rsa.c b/third_party/boringssl/kit/src/crypto/fipsmodule/rsa/rsa.c index efb2f9b6..724de69e 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/rsa/rsa.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/rsa/rsa.c @@ -80,7 +80,7 @@ // Cryptography.io depends on this error code. OPENSSL_DECLARE_ERROR_REASON(RSA, BLOCK_TYPE_IS_NOT_02) -DEFINE_STATIC_EX_DATA_CLASS(g_rsa_ex_data_class); +DEFINE_STATIC_EX_DATA_CLASS(g_rsa_ex_data_class) RSA *RSA_new(void) { return RSA_new_method(NULL); } diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha1-586.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha1-586.pl index 87fd361a..bf429614 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha1-586.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha1-586.pl @@ -1483,4 +1483,4 @@ sub Xtail_avx() &asm_finish(); -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha1-armv4-large.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha1-armv4-large.pl index 27187dd6..ca825146 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha1-armv4-large.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha1-armv4-large.pl @@ -740,4 +740,4 @@ foreach (split($/,$code)) { print $_,$/; } -close STDOUT; # enforce flush +close STDOUT or die "error closing STDOUT"; # enforce flush diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha1-armv8.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha1-armv8.pl index 7c8880fb..c1474626 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha1-armv8.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha1-armv8.pl @@ -353,4 +353,4 @@ foreach(split("\n",$code)) { print $_,"\n"; } -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha1-x86_64.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha1-x86_64.pl index fd4ff2ac..df7cbc30 100755 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha1-x86_64.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha1-x86_64.pl @@ -2122,4 +2122,4 @@ foreach (split("\n",$code)) { print $_,"\n"; } -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha256-586.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha256-586.pl index 129a9f42..240a604a 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha256-586.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha256-586.pl @@ -1287,4 +1287,4 @@ sub bodyx_00_15 () { # +10% &asm_finish(); -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha256-armv4.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha256-armv4.pl index e5ecdfd1..15d78de6 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha256-armv4.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha256-armv4.pl @@ -735,4 +735,4 @@ foreach (split($/,$code)) { print $_,"\n"; } -close STDOUT; # enforce flush +close STDOUT or die "error closing STDOUT"; # enforce flush diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha512-586.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha512-586.pl index 25a5f255..01acf679 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha512-586.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha512-586.pl @@ -922,4 +922,4 @@ sub BODY_00_15_ssse3 { # "phase-less" copy of BODY_00_15_sse2 &asm_finish(); -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha512-armv4.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha512-armv4.pl index cc247a44..c8c715e5 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha512-armv4.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha512-armv4.pl @@ -670,4 +670,4 @@ while() { close SELF; print $code; -close STDOUT; # enforce flush +close STDOUT or die "error closing STDOUT"; # enforce flush diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha512-armv8.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha512-armv8.pl index 3f69071f..64306be8 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha512-armv8.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha512-armv8.pl @@ -457,4 +457,4 @@ foreach(split("\n",$code)) { print $_,"\n"; } -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha512-x86_64.pl b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha512-x86_64.pl index 49278506..8c5a5f33 100755 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha512-x86_64.pl +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/asm/sha512-x86_64.pl @@ -278,7 +278,6 @@ $code.=<<___ if ($SZ==4 && $shaext); jnz _shaext_shortcut ___ # XOP codepath removed. -___ $code.=<<___ if ($avx>1); and \$`1<<8|1<<5|1<<3`,%r11d # check for BMI2+AVX2+BMI1 cmp \$`1<<8|1<<5|1<<3`,%r11d @@ -2083,4 +2082,4 @@ foreach (split("\n",$code)) { print $_,"\n"; } -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/internal.h b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/internal.h index 4def7f3a..a5d70c37 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/internal.h +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/internal.h @@ -27,15 +27,18 @@ extern "C" { #if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || defined(OPENSSL_ARM) || \ defined(OPENSSL_AARCH64) || defined(OPENSSL_PPC64LE) #define SHA1_ASM -void sha1_block_data_order(uint32_t *state, const uint8_t *data, size_t num); +void sha1_block_data_order(uint32_t *state, const uint8_t *in, + size_t num_blocks); #endif #if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || defined(OPENSSL_ARM) || \ defined(OPENSSL_AARCH64) #define SHA256_ASM #define SHA512_ASM -void sha256_block_data_order(uint32_t *state, const uint8_t *in, size_t num); -void sha512_block_data_order(uint64_t *state, const uint64_t *W, size_t num); +void sha256_block_data_order(uint32_t *state, const uint8_t *in, + size_t num_blocks); +void sha512_block_data_order(uint64_t *state, const uint8_t *in, + size_t num_blocks); #endif #endif // OPENSSL_NO_ASM diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/sha1.c b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/sha1.c index a3b771a9..cc1243be 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/sha1.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/sha1.c @@ -74,7 +74,7 @@ int SHA1_Init(SHA_CTX *sha) { return 1; } -uint8_t *SHA1(const uint8_t *data, size_t len, uint8_t *out) { +uint8_t *SHA1(const uint8_t *data, size_t len, uint8_t out[SHA_DIGEST_LENGTH]) { SHA_CTX ctx; SHA1_Init(&ctx); SHA1_Update(&ctx, data, len); @@ -87,6 +87,7 @@ uint8_t *SHA1(const uint8_t *data, size_t len, uint8_t *out) { #define HASH_CTX SHA_CTX #define HASH_CBLOCK 64 +#define HASH_DIGEST_LENGTH 20 #define HASH_MAKE_STRING(c, s) \ do { \ uint32_t ll; \ @@ -343,6 +344,7 @@ static void sha1_block_data_order(uint32_t *state, const uint8_t *data, #undef DATA_ORDER_IS_BIG_ENDIAN #undef HASH_CTX #undef HASH_CBLOCK +#undef HASH_DIGEST_LENGTH #undef HASH_MAKE_STRING #undef HASH_UPDATE #undef HASH_TRANSFORM diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/sha256.c b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/sha256.c index 92a52956..0e424461 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/sha256.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/sha256.c @@ -92,7 +92,8 @@ int SHA256_Init(SHA256_CTX *sha) { return 1; } -uint8_t *SHA224(const uint8_t *data, size_t len, uint8_t *out) { +uint8_t *SHA224(const uint8_t *data, size_t len, + uint8_t out[SHA224_DIGEST_LENGTH]) { SHA256_CTX ctx; SHA224_Init(&ctx); SHA224_Update(&ctx, data, len); @@ -101,7 +102,8 @@ uint8_t *SHA224(const uint8_t *data, size_t len, uint8_t *out) { return out; } -uint8_t *SHA256(const uint8_t *data, size_t len, uint8_t *out) { +uint8_t *SHA256(const uint8_t *data, size_t len, + uint8_t out[SHA256_DIGEST_LENGTH]) { SHA256_CTX ctx; SHA256_Init(&ctx); SHA256_Update(&ctx, data, len); @@ -114,14 +116,17 @@ int SHA224_Update(SHA256_CTX *ctx, const void *data, size_t len) { return SHA256_Update(ctx, data, len); } -int SHA224_Final(uint8_t *md, SHA256_CTX *ctx) { - return SHA256_Final(md, ctx); +int SHA224_Final(uint8_t out[SHA224_DIGEST_LENGTH], SHA256_CTX *ctx) { + // SHA224_Init sets |ctx->md_len| to |SHA224_DIGEST_LENGTH|, so this has a + // smaller output. + return SHA256_Final(out, ctx); } #define DATA_ORDER_IS_BIG_ENDIAN #define HASH_CTX SHA256_CTX #define HASH_CBLOCK 64 +#define HASH_DIGEST_LENGTH 32 // Note that FIPS180-2 discusses "Truncation of the Hash Function Output." // default: case below covers for it. It's not clear however if it's permitted @@ -319,6 +324,7 @@ void SHA256_TransformBlocks(uint32_t state[8], const uint8_t *data, #undef DATA_ORDER_IS_BIG_ENDIAN #undef HASH_CTX #undef HASH_CBLOCK +#undef HASH_DIGEST_LENGTH #undef HASH_MAKE_STRING #undef HASH_UPDATE #undef HASH_TRANSFORM diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/sha512.c b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/sha512.c index a6890563..848f3b62 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/sha512.c +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/sha512.c @@ -64,22 +64,11 @@ #include "../../internal.h" -// IMPLEMENTATION NOTES. -// // The 32-bit hash algorithms share a common byte-order neutral collector and // padding function implementations that operate on unaligned data, -// ../md32_common.h. This SHA-512 implementation does not. Reasons -// [in reverse order] are: -// -// - It's the only 64-bit hash algorithm for the moment of this writing, -// there is no need for common collector/padding implementation [yet]; -// - By supporting only a transform function that operates on *aligned* data -// the collector/padding function is simpler and easier to optimize. - -#if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || \ - defined(__ARM_FEATURE_UNALIGNED) -#define SHA512_BLOCK_CAN_MANAGE_UNALIGNED_DATA -#endif +// ../digest/md32_common.h. SHA-512 is the only 64-bit hash algorithm, as of +// this writing, so there is no need for a common collector/padding +// implementation yet. int SHA384_Init(SHA512_CTX *sha) { sha->h[0] = UINT64_C(0xcbbb9d5dc1059ed8); @@ -116,7 +105,8 @@ int SHA512_Init(SHA512_CTX *sha) { return 1; } -uint8_t *SHA384(const uint8_t *data, size_t len, uint8_t *out) { +uint8_t *SHA384(const uint8_t *data, size_t len, + uint8_t out[SHA384_DIGEST_LENGTH]) { SHA512_CTX ctx; SHA384_Init(&ctx); SHA384_Update(&ctx, data, len); @@ -125,7 +115,8 @@ uint8_t *SHA384(const uint8_t *data, size_t len, uint8_t *out) { return out; } -uint8_t *SHA512(const uint8_t *data, size_t len, uint8_t *out) { +uint8_t *SHA512(const uint8_t *data, size_t len, + uint8_t out[SHA512_DIGEST_LENGTH]) { SHA512_CTX ctx; SHA512_Init(&ctx); SHA512_Update(&ctx, data, len); @@ -135,33 +126,29 @@ uint8_t *SHA512(const uint8_t *data, size_t len, uint8_t *out) { } #if !defined(SHA512_ASM) -static void sha512_block_data_order(uint64_t *state, const uint64_t *W, - size_t num); +static void sha512_block_data_order(uint64_t *state, const uint8_t *in, + size_t num_blocks); #endif -int SHA384_Final(uint8_t *md, SHA512_CTX *sha) { - return SHA512_Final(md, sha); +int SHA384_Final(uint8_t out[SHA384_DIGEST_LENGTH], SHA512_CTX *sha) { + // |SHA384_Init| sets |sha->md_len| to |SHA384_DIGEST_LENGTH|, so this has a + // |smaller output. + return SHA512_Final(out, sha); } int SHA384_Update(SHA512_CTX *sha, const void *data, size_t len) { return SHA512_Update(sha, data, len); } -void SHA512_Transform(SHA512_CTX *c, const uint8_t *block) { -#ifndef SHA512_BLOCK_CAN_MANAGE_UNALIGNED_DATA - if ((size_t)block % sizeof(c->u.d[0]) != 0) { - OPENSSL_memcpy(c->u.p, block, sizeof(c->u.p)); - block = c->u.p; - } -#endif - sha512_block_data_order(c->h, (uint64_t *)block, 1); +void SHA512_Transform(SHA512_CTX *c, const uint8_t block[SHA512_CBLOCK]) { + sha512_block_data_order(c->h, block, 1); } int SHA512_Update(SHA512_CTX *c, const void *in_data, size_t len) { uint64_t l; - uint8_t *p = c->u.p; - const uint8_t *data = (const uint8_t *)in_data; + uint8_t *p = c->p; + const uint8_t *data = in_data; if (len == 0) { return 1; @@ -177,7 +164,7 @@ int SHA512_Update(SHA512_CTX *c, const void *in_data, size_t len) { c->Nl = l; if (c->num != 0) { - size_t n = sizeof(c->u) - c->num; + size_t n = sizeof(c->p) - c->num; if (len < n) { OPENSSL_memcpy(p + c->num, data, len); @@ -187,27 +174,15 @@ int SHA512_Update(SHA512_CTX *c, const void *in_data, size_t len) { OPENSSL_memcpy(p + c->num, data, n), c->num = 0; len -= n; data += n; - sha512_block_data_order(c->h, (uint64_t *)p, 1); + sha512_block_data_order(c->h, p, 1); } } - if (len >= sizeof(c->u)) { -#ifndef SHA512_BLOCK_CAN_MANAGE_UNALIGNED_DATA - if ((size_t)data % sizeof(c->u.d[0]) != 0) { - while (len >= sizeof(c->u)) { - OPENSSL_memcpy(p, data, sizeof(c->u)); - sha512_block_data_order(c->h, (uint64_t *)p, 1); - len -= sizeof(c->u); - data += sizeof(c->u); - } - } else -#endif - { - sha512_block_data_order(c->h, (uint64_t *)data, len / sizeof(c->u)); - data += len; - len %= sizeof(c->u); - data -= len; - } + if (len >= sizeof(c->p)) { + sha512_block_data_order(c->h, data, len / sizeof(c->p)); + data += len; + len %= sizeof(c->p); + data -= len; } if (len != 0) { @@ -218,39 +193,39 @@ int SHA512_Update(SHA512_CTX *c, const void *in_data, size_t len) { return 1; } -int SHA512_Final(uint8_t *md, SHA512_CTX *sha) { - uint8_t *p = (uint8_t *)sha->u.p; +int SHA512_Final(uint8_t out[SHA512_DIGEST_LENGTH], SHA512_CTX *sha) { + uint8_t *p = sha->p; size_t n = sha->num; p[n] = 0x80; // There always is a room for one n++; - if (n > (sizeof(sha->u) - 16)) { - OPENSSL_memset(p + n, 0, sizeof(sha->u) - n); + if (n > (sizeof(sha->p) - 16)) { + OPENSSL_memset(p + n, 0, sizeof(sha->p) - n); n = 0; - sha512_block_data_order(sha->h, (uint64_t *)p, 1); + sha512_block_data_order(sha->h, p, 1); } - OPENSSL_memset(p + n, 0, sizeof(sha->u) - 16 - n); - p[sizeof(sha->u) - 1] = (uint8_t)(sha->Nl); - p[sizeof(sha->u) - 2] = (uint8_t)(sha->Nl >> 8); - p[sizeof(sha->u) - 3] = (uint8_t)(sha->Nl >> 16); - p[sizeof(sha->u) - 4] = (uint8_t)(sha->Nl >> 24); - p[sizeof(sha->u) - 5] = (uint8_t)(sha->Nl >> 32); - p[sizeof(sha->u) - 6] = (uint8_t)(sha->Nl >> 40); - p[sizeof(sha->u) - 7] = (uint8_t)(sha->Nl >> 48); - p[sizeof(sha->u) - 8] = (uint8_t)(sha->Nl >> 56); - p[sizeof(sha->u) - 9] = (uint8_t)(sha->Nh); - p[sizeof(sha->u) - 10] = (uint8_t)(sha->Nh >> 8); - p[sizeof(sha->u) - 11] = (uint8_t)(sha->Nh >> 16); - p[sizeof(sha->u) - 12] = (uint8_t)(sha->Nh >> 24); - p[sizeof(sha->u) - 13] = (uint8_t)(sha->Nh >> 32); - p[sizeof(sha->u) - 14] = (uint8_t)(sha->Nh >> 40); - p[sizeof(sha->u) - 15] = (uint8_t)(sha->Nh >> 48); - p[sizeof(sha->u) - 16] = (uint8_t)(sha->Nh >> 56); + OPENSSL_memset(p + n, 0, sizeof(sha->p) - 16 - n); + p[sizeof(sha->p) - 1] = (uint8_t)(sha->Nl); + p[sizeof(sha->p) - 2] = (uint8_t)(sha->Nl >> 8); + p[sizeof(sha->p) - 3] = (uint8_t)(sha->Nl >> 16); + p[sizeof(sha->p) - 4] = (uint8_t)(sha->Nl >> 24); + p[sizeof(sha->p) - 5] = (uint8_t)(sha->Nl >> 32); + p[sizeof(sha->p) - 6] = (uint8_t)(sha->Nl >> 40); + p[sizeof(sha->p) - 7] = (uint8_t)(sha->Nl >> 48); + p[sizeof(sha->p) - 8] = (uint8_t)(sha->Nl >> 56); + p[sizeof(sha->p) - 9] = (uint8_t)(sha->Nh); + p[sizeof(sha->p) - 10] = (uint8_t)(sha->Nh >> 8); + p[sizeof(sha->p) - 11] = (uint8_t)(sha->Nh >> 16); + p[sizeof(sha->p) - 12] = (uint8_t)(sha->Nh >> 24); + p[sizeof(sha->p) - 13] = (uint8_t)(sha->Nh >> 32); + p[sizeof(sha->p) - 14] = (uint8_t)(sha->Nh >> 40); + p[sizeof(sha->p) - 15] = (uint8_t)(sha->Nh >> 48); + p[sizeof(sha->p) - 16] = (uint8_t)(sha->Nh >> 56); - sha512_block_data_order(sha->h, (uint64_t *)p, 1); + sha512_block_data_order(sha->h, p, 1); - if (md == NULL) { + if (out == NULL) { // TODO(davidben): This NULL check is absent in other low-level hash 'final' // functions and is one of the few places one can fail. return 0; @@ -262,28 +237,28 @@ int SHA512_Final(uint8_t *md, SHA512_CTX *sha) { for (n = 0; n < SHA384_DIGEST_LENGTH / 8; n++) { uint64_t t = sha->h[n]; - *(md++) = (uint8_t)(t >> 56); - *(md++) = (uint8_t)(t >> 48); - *(md++) = (uint8_t)(t >> 40); - *(md++) = (uint8_t)(t >> 32); - *(md++) = (uint8_t)(t >> 24); - *(md++) = (uint8_t)(t >> 16); - *(md++) = (uint8_t)(t >> 8); - *(md++) = (uint8_t)(t); + *(out++) = (uint8_t)(t >> 56); + *(out++) = (uint8_t)(t >> 48); + *(out++) = (uint8_t)(t >> 40); + *(out++) = (uint8_t)(t >> 32); + *(out++) = (uint8_t)(t >> 24); + *(out++) = (uint8_t)(t >> 16); + *(out++) = (uint8_t)(t >> 8); + *(out++) = (uint8_t)(t); } break; case SHA512_DIGEST_LENGTH: for (n = 0; n < SHA512_DIGEST_LENGTH / 8; n++) { uint64_t t = sha->h[n]; - *(md++) = (uint8_t)(t >> 56); - *(md++) = (uint8_t)(t >> 48); - *(md++) = (uint8_t)(t >> 40); - *(md++) = (uint8_t)(t >> 32); - *(md++) = (uint8_t)(t >> 24); - *(md++) = (uint8_t)(t >> 16); - *(md++) = (uint8_t)(t >> 8); - *(md++) = (uint8_t)(t); + *(out++) = (uint8_t)(t >> 56); + *(out++) = (uint8_t)(t >> 48); + *(out++) = (uint8_t)(t >> 40); + *(out++) = (uint8_t)(t >> 32); + *(out++) = (uint8_t)(t >> 24); + *(out++) = (uint8_t)(t >> 16); + *(out++) = (uint8_t)(t >> 8); + *(out++) = (uint8_t)(t); } break; // ... as well as make sure md_len is not abused. @@ -348,20 +323,6 @@ static const uint64_t K512[80] = { __asm__("rorq %1, %0" : "=r"(ret) : "J"(n), "0"(a) : "cc"); \ ret; \ }) -#define PULL64(x) \ - ({ \ - uint64_t ret = *((const uint64_t *)(&(x))); \ - __asm__("bswapq %0" : "=r"(ret) : "0"(ret)); \ - ret; \ - }) -#elif(defined(__i386) || defined(__i386__)) -#define PULL64(x) \ - ({ \ - const unsigned int *p = (const unsigned int *)(&(x)); \ - unsigned int hi = p[0], lo = p[1]; \ - __asm__("bswapl %0; bswapl %1;" : "=r"(lo), "=r"(hi) : "0"(lo), "1"(hi)); \ - ((uint64_t)hi) << 32 | lo; \ - }) #elif(defined(_ARCH_PPC) && defined(__64BIT__)) || defined(_ARCH_PPC64) #define ROTR(a, n) \ ({ \ @@ -376,47 +337,22 @@ static const uint64_t K512[80] = { __asm__("ror %0, %1, %2" : "=r"(ret) : "r"(a), "I"(n)); \ ret; \ }) -#if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \ - __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ -#define PULL64(x) \ - ({ \ - uint64_t ret; \ - __asm__("rev %0, %1" : "=r"(ret) : "r"(*((const uint64_t *)(&(x))))); \ - ret; \ - }) #endif -#endif -#elif defined(_MSC_VER) -#if defined(_WIN64) // applies to both IA-64 and AMD64 +#elif defined(_MSC_VER) && defined(_WIN64) #pragma intrinsic(_rotr64) #define ROTR(a, n) _rotr64((a), n) #endif -#if defined(_M_IX86) && !defined(OPENSSL_NO_ASM) -static uint64_t __fastcall __pull64be(const void *x) { - _asm mov edx, [ecx + 0] - _asm mov eax, [ecx + 4] - _asm bswap edx - _asm bswap eax -} -#define PULL64(x) __pull64be(&(x)) -#if _MSC_VER <= 1200 -#pragma inline_depth(0) -#endif -#endif -#endif - -#ifndef PULL64 -#define B(x, j) \ - (((uint64_t)(*(((const uint8_t *)(&x)) + j))) << ((7 - j) * 8)) -#define PULL64(x) \ - (B(x, 0) | B(x, 1) | B(x, 2) | B(x, 3) | B(x, 4) | B(x, 5) | B(x, 6) | \ - B(x, 7)) -#endif #ifndef ROTR #define ROTR(x, s) (((x) >> s) | (x) << (64 - s)) #endif +static inline uint64_t load_u64_be(const void *ptr) { + uint64_t ret; + OPENSSL_memcpy(&ret, ptr, sizeof(ret)); + return CRYPTO_bswap8(ret); +} + #define Sigma0(x) (ROTR((x), 28) ^ ROTR((x), 34) ^ ROTR((x), 39)) #define Sigma1(x) (ROTR((x), 14) ^ ROTR((x), 18) ^ ROTR((x), 41)) #define sigma0(x) (ROTR((x), 1) ^ ROTR((x), 8) ^ ((x) >> 7)) @@ -429,7 +365,7 @@ static uint64_t __fastcall __pull64be(const void *x) { #if defined(__i386) || defined(__i386__) || defined(_M_IX86) // This code should give better results on 32-bit CPU with less than // ~24 registers, both size and performance wise... -static void sha512_block_data_order(uint64_t *state, const uint64_t *W, +static void sha512_block_data_order(uint64_t *state, const uint8_t *in, size_t num) { uint64_t A, E, T; uint64_t X[9 + 80], *F; @@ -447,7 +383,7 @@ static void sha512_block_data_order(uint64_t *state, const uint64_t *W, F[7] = state[7]; for (i = 0; i < 16; i++, F--) { - T = PULL64(W[i]); + T = load_u64_be(in + i * 8); F[0] = A; F[4] = E; F[8] = T; @@ -478,7 +414,7 @@ static void sha512_block_data_order(uint64_t *state, const uint64_t *W, state[6] += F[6]; state[7] += F[7]; - W += 16; + in += 16 * 8; } } @@ -502,7 +438,7 @@ static void sha512_block_data_order(uint64_t *state, const uint64_t *W, ROUND_00_15(i + j, a, b, c, d, e, f, g, h); \ } while (0) -static void sha512_block_data_order(uint64_t *state, const uint64_t *W, +static void sha512_block_data_order(uint64_t *state, const uint8_t *in, size_t num) { uint64_t a, b, c, d, e, f, g, h, s0, s1, T1; uint64_t X[16]; @@ -519,37 +455,37 @@ static void sha512_block_data_order(uint64_t *state, const uint64_t *W, g = state[6]; h = state[7]; - T1 = X[0] = PULL64(W[0]); + T1 = X[0] = load_u64_be(in); ROUND_00_15(0, a, b, c, d, e, f, g, h); - T1 = X[1] = PULL64(W[1]); + T1 = X[1] = load_u64_be(in + 8); ROUND_00_15(1, h, a, b, c, d, e, f, g); - T1 = X[2] = PULL64(W[2]); + T1 = X[2] = load_u64_be(in + 2 * 8); ROUND_00_15(2, g, h, a, b, c, d, e, f); - T1 = X[3] = PULL64(W[3]); + T1 = X[3] = load_u64_be(in + 3 * 8); ROUND_00_15(3, f, g, h, a, b, c, d, e); - T1 = X[4] = PULL64(W[4]); + T1 = X[4] = load_u64_be(in + 4 * 8); ROUND_00_15(4, e, f, g, h, a, b, c, d); - T1 = X[5] = PULL64(W[5]); + T1 = X[5] = load_u64_be(in + 5 * 8); ROUND_00_15(5, d, e, f, g, h, a, b, c); - T1 = X[6] = PULL64(W[6]); + T1 = X[6] = load_u64_be(in + 6 * 8); ROUND_00_15(6, c, d, e, f, g, h, a, b); - T1 = X[7] = PULL64(W[7]); + T1 = X[7] = load_u64_be(in + 7 * 8); ROUND_00_15(7, b, c, d, e, f, g, h, a); - T1 = X[8] = PULL64(W[8]); + T1 = X[8] = load_u64_be(in + 8 * 8); ROUND_00_15(8, a, b, c, d, e, f, g, h); - T1 = X[9] = PULL64(W[9]); + T1 = X[9] = load_u64_be(in + 9 * 8); ROUND_00_15(9, h, a, b, c, d, e, f, g); - T1 = X[10] = PULL64(W[10]); + T1 = X[10] = load_u64_be(in + 10 * 8); ROUND_00_15(10, g, h, a, b, c, d, e, f); - T1 = X[11] = PULL64(W[11]); + T1 = X[11] = load_u64_be(in + 11 * 8); ROUND_00_15(11, f, g, h, a, b, c, d, e); - T1 = X[12] = PULL64(W[12]); + T1 = X[12] = load_u64_be(in + 12 * 8); ROUND_00_15(12, e, f, g, h, a, b, c, d); - T1 = X[13] = PULL64(W[13]); + T1 = X[13] = load_u64_be(in + 13 * 8); ROUND_00_15(13, d, e, f, g, h, a, b, c); - T1 = X[14] = PULL64(W[14]); + T1 = X[14] = load_u64_be(in + 14 * 8); ROUND_00_15(14, c, d, e, f, g, h, a, b); - T1 = X[15] = PULL64(W[15]); + T1 = X[15] = load_u64_be(in + 15 * 8); ROUND_00_15(15, b, c, d, e, f, g, h, a); for (i = 16; i < 80; i += 16) { @@ -580,7 +516,7 @@ static void sha512_block_data_order(uint64_t *state, const uint64_t *W, state[6] += g; state[7] += h; - W += 16; + in += 16 * 8; } } @@ -589,8 +525,6 @@ static void sha512_block_data_order(uint64_t *state, const uint64_t *W, #endif // !SHA512_ASM #undef ROTR -#undef PULL64 -#undef B #undef Sigma0 #undef Sigma1 #undef sigma0 @@ -599,5 +533,3 @@ static void sha512_block_data_order(uint64_t *state, const uint64_t *W, #undef Maj #undef ROUND_00_15 #undef ROUND_16_80 -#undef HOST_c2l -#undef HOST_l2c diff --git a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/sha_test.cc b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/sha_test.cc index 9cac47f1..5b248b4e 100644 --- a/third_party/boringssl/kit/src/crypto/fipsmodule/sha/sha_test.cc +++ b/third_party/boringssl/kit/src/crypto/fipsmodule/sha/sha_test.cc @@ -51,7 +51,7 @@ TEST(SHATest, SHA512ABI) { SHA512_CTX ctx; SHA512_Init(&ctx); - static const uint64_t kBuf[SHA512_CBLOCK / sizeof(uint64_t) * 4] = {0}; + static const uint8_t kBuf[SHA512_CBLOCK * 4] = {0}; CHECK_ABI(sha512_block_data_order, ctx.h, kBuf, 1); CHECK_ABI(sha512_block_data_order, ctx.h, kBuf, 2); CHECK_ABI(sha512_block_data_order, ctx.h, kBuf, 3); diff --git a/third_party/boringssl/kit/src/crypto/hrss/hrss.c b/third_party/boringssl/kit/src/crypto/hrss/hrss.c index 71fa5e30..d81a43f6 100644 --- a/third_party/boringssl/kit/src/crypto/hrss/hrss.c +++ b/third_party/boringssl/kit/src/crypto/hrss/hrss.c @@ -488,26 +488,30 @@ static int poly2_top_bits_are_clear(const struct poly2 *p) { // ----------------- // 0 | 0 | 0 // 0 | 1 | 1 -// 1 | 0 | 2 (aka -1) -// 1 | 1 | +// 1 | 1 | -1 (aka 2) +// 1 | 0 | // -// ('s' is for sign, and 'a' just a letter.) +// ('s' is for sign, and 'a' is the absolute value.) // // Once bitsliced as such, the following circuits can be used to implement // addition and multiplication mod 3: // // (s3, a3) = (s1, a1) × (s2, a2) -// s3 = (a1 ∧ s2) ⊕ (s1 ∧ a2) -// a3 = (s1 ∧ s2) ⊕ (a1 ∧ a2) +// a3 = a1 ∧ a2 +// s3 = (s1 ⊕ s2) ∧ a3 // // (s3, a3) = (s1, a1) + (s2, a2) -// x = (a1 ⊕ a2) -// y = (s1 ⊕ s2) ⊕ (a1 ∧ a2) -// z = (s1 ∧ s2) -// s3 = y ∧ ¬x -// a3 = z ∨ (x ∧ ¬y) +// t = s1 ⊕ a2 +// s3 = t ∧ (s2 ⊕ a1) +// a3 = (a1 ⊕ a2) ∨ (t ⊕ s2) +// +// (s3, a3) = (s1, a1) - (s2, a2) +// t = a1 ⊕ a2 +// s3 = (s1 ⊕ a2) ∧ (t ⊕ s2) +// a3 = t ∨ (s1 ⊕ s2) +// +// Negating a value just involves XORing s by a. // -// Negating a value just involves swapping s and a. // struct poly3 { // struct poly2 s, a; // }; @@ -540,22 +544,45 @@ static void poly3_zero(struct poly3 *p) { poly2_zero(&p->a); } +// poly3_word_mul sets (|out_s|, |out_a) to (|s1|, |a1|) × (|s2|, |a2|). +static void poly3_word_mul(crypto_word_t *out_s, crypto_word_t *out_a, + const crypto_word_t s1, const crypto_word_t a1, + const crypto_word_t s2, const crypto_word_t a2) { + *out_a = a1 & a2; + *out_s = (s1 ^ s2) & *out_a; +} + +// poly3_word_add sets (|out_s|, |out_a|) to (|s1|, |a1|) + (|s2|, |a2|). +static void poly3_word_add(crypto_word_t *out_s, crypto_word_t *out_a, + const crypto_word_t s1, const crypto_word_t a1, + const crypto_word_t s2, const crypto_word_t a2) { + const crypto_word_t t = s1 ^ a2; + *out_s = t & (s2 ^ a1); + *out_a = (a1 ^ a2) | (t ^ s2); +} + +// poly3_word_sub sets (|out_s|, |out_a|) to (|s1|, |a1|) - (|s2|, |a2|). +static void poly3_word_sub(crypto_word_t *out_s, crypto_word_t *out_a, + const crypto_word_t s1, const crypto_word_t a1, + const crypto_word_t s2, const crypto_word_t a2) { + const crypto_word_t t = a1 ^ a2; + *out_s = (s1 ^ a2) & (t ^ s2); + *out_a = t | (s1 ^ s2); +} + // lsb_to_all replicates the least-significant bit of |v| to all bits of the // word. This is used in bit-slicing operations to make a vector from a fixed // value. static crypto_word_t lsb_to_all(crypto_word_t v) { return 0u - (v & 1); } -// poly3_mul_const sets |p| to |p|×m, where m = (ms, ma). +// poly3_mul_const sets |p| to |p|×m, where m = (ms, ma). static void poly3_mul_const(struct poly3 *p, crypto_word_t ms, crypto_word_t ma) { ms = lsb_to_all(ms); ma = lsb_to_all(ma); for (size_t i = 0; i < WORDS_PER_POLY; i++) { - const crypto_word_t s = p->s.v[i]; - const crypto_word_t a = p->a.v[i]; - p->s.v[i] = (s & ma) ^ (ms & a); - p->a.v[i] = (ms & s) ^ (ma & a); + poly3_word_mul(&p->s.v[i], &p->a.v[i], p->s.v[i], p->a.v[i], ms, ma); } } @@ -566,23 +593,15 @@ static void poly3_rotr_consttime(struct poly3 *p, size_t bits) { HRSS_poly2_rotr_consttime(&p->a, bits); } -// poly3_fmadd sets |out| to |out| + |in|×m, where m is (ms, ma). -static void poly3_fmadd(struct poly3 *RESTRICT out, +// poly3_fmadd sets |out| to |out| - |in|×m, where m is (ms, ma). +static void poly3_fmsub(struct poly3 *RESTRICT out, const struct poly3 *RESTRICT in, crypto_word_t ms, crypto_word_t ma) { - // (See the multiplication and addition circuits given above.) + crypto_word_t product_s, product_a; for (size_t i = 0; i < WORDS_PER_POLY; i++) { - const crypto_word_t s = in->s.v[i]; - const crypto_word_t a = in->a.v[i]; - const crypto_word_t product_s = (s & ma) ^ (ms & a); - const crypto_word_t product_a = (ms & s) ^ (ma & a); - - const crypto_word_t x = out->a.v[i] ^ product_a; - const crypto_word_t y = - (out->s.v[i] ^ product_s) ^ (out->a.v[i] & product_a); - const crypto_word_t z = (out->s.v[i] & product_s); - out->s.v[i] = y & ~x; - out->a.v[i] = z | (x & ~y); + poly3_word_mul(&product_s, &product_a, in->s.v[i], in->a.v[i], ms, ma); + poly3_word_sub(&out->s.v[i], &out->a.v[i], out->s.v[i], out->a.v[i], + product_s, product_a); } } @@ -601,20 +620,13 @@ OPENSSL_UNUSED static int poly3_top_bits_are_clear(const struct poly3 *p) { // poly3_mod_phiN reduces |p| by Φ(N). static void poly3_mod_phiN(struct poly3 *p) { // In order to reduce by Φ(N) we subtract by the value of the greatest - // coefficient. That's the same as adding the negative of its value. The - // negative of (s, a) is (a, s), so the arguments are swapped in the following - // two lines. - const crypto_word_t factor_s = final_bit_to_all(p->a.v[WORDS_PER_POLY - 1]); - const crypto_word_t factor_a = final_bit_to_all(p->s.v[WORDS_PER_POLY - 1]); + // coefficient. + const crypto_word_t factor_s = final_bit_to_all(p->s.v[WORDS_PER_POLY - 1]); + const crypto_word_t factor_a = final_bit_to_all(p->a.v[WORDS_PER_POLY - 1]); for (size_t i = 0; i < WORDS_PER_POLY; i++) { - const crypto_word_t s = p->s.v[i]; - const crypto_word_t a = p->a.v[i]; - const crypto_word_t x = a ^ factor_a; - const crypto_word_t y = (s ^ factor_s) ^ (a & factor_a); - const crypto_word_t z = (s & factor_s); - p->s.v[i] = y & ~x; - p->a.v[i] = z | (x & ~y); + poly3_word_sub(&p->s.v[i], &p->a.v[i], p->s.v[i], p->a.v[i], factor_s, + factor_a); } poly2_clear_top_bits(&p->s); @@ -642,17 +654,6 @@ struct poly3_span { crypto_word_t *a; }; -// poly3_word_add sets (|out_s|, |out_a|) to (|s1|, |a1|) + (|s2|, |a2|). -static void poly3_word_add(crypto_word_t *out_s, crypto_word_t *out_a, - const crypto_word_t s1, const crypto_word_t a1, - const crypto_word_t s2, const crypto_word_t a2) { - const crypto_word_t x = a1 ^ a2; - const crypto_word_t y = (s1 ^ s2) ^ (a1 & a2); - const crypto_word_t z = s1 & s2; - *out_s = y & ~x; - *out_a = z | (x & ~y); -} - // poly3_span_add adds |n| words of values from |a| and |b| and writes the // result to |out|. static void poly3_span_add(const struct poly3_span *out, @@ -667,8 +668,7 @@ static void poly3_span_add(const struct poly3_span *out, static void poly3_span_sub(const struct poly3_span *a, const struct poly3_span *b, size_t n) { for (size_t i = 0; i < n; i++) { - // Swapping |b->s| and |b->a| negates the value being added. - poly3_word_add(&a->s[i], &a->a[i], a->s[i], a->a[i], b->a[i], b->s[i]); + poly3_word_sub(&a->s[i], &a->a[i], a->s[i], a->a[i], b->s[i], b->a[i]); } } @@ -688,14 +688,11 @@ static void poly3_mul_aux(const struct poly3_span *out, for (size_t i = 0; i < BITS_PER_WORD; i++) { // Multiply (s, a) by the next value from (b_s, b_a). - const crypto_word_t v_s = lsb_to_all(b_s); - const crypto_word_t v_a = lsb_to_all(b_a); + crypto_word_t m_s, m_a; + poly3_word_mul(&m_s, &m_a, a_s, a_a, lsb_to_all(b_s), lsb_to_all(b_a)); b_s >>= 1; b_a >>= 1; - const crypto_word_t m_s = (v_s & a_a) ^ (a_s & v_a); - const crypto_word_t m_a = (a_s & v_s) ^ (a_a & v_a); - if (i == 0) { // Special case otherwise the code tries to shift by BITS_PER_WORD // below, which is undefined. @@ -816,21 +813,22 @@ static inline void poly3_vec_cswap(vec_t a_s[6], vec_t a_a[6], vec_t b_s[6], } } -// poly3_vec_fmadd adds (|ms|, |ma|) × (|b_s|, |b_a|) to (|a_s|, |a_a|). -static inline void poly3_vec_fmadd(vec_t a_s[6], vec_t a_a[6], vec_t b_s[6], +// poly3_vec_fmsub subtracts (|ms|, |ma|) × (|b_s|, |b_a|) from (|a_s|, |a_a|). +static inline void poly3_vec_fmsub(vec_t a_s[6], vec_t a_a[6], vec_t b_s[6], vec_t b_a[6], const vec_t ms, const vec_t ma) { for (int i = 0; i < 6; i++) { + // See the bitslice formula, above. const vec_t s = b_s[i]; const vec_t a = b_a[i]; - const vec_t product_s = (s & ma) ^ (ms & a); - const vec_t product_a = (ms & s) ^ (ma & a); + const vec_t product_a = a & ma; + const vec_t product_s = (s ^ ms) & product_a; - const vec_t x = a_a[i] ^ product_a; - const vec_t y = (a_s[i] ^ product_s) ^ (a_a[i] & product_a); - const vec_t z = (a_s[i] & product_s); - a_s[i] = y & ~x; - a_a[i] = z | (x & ~y); + const vec_t out_s = a_s[i]; + const vec_t out_a = a_a[i]; + const vec_t t = out_a ^ product_a; + a_s[i] = (out_s ^ product_a) & (t ^ product_s); + a_a[i] = t | (out_s ^ product_s); } } @@ -874,19 +872,18 @@ static void poly3_invert_vec(struct poly3 *out, const struct poly3 *in) { memset(&still_going, 0xff, sizeof(still_going)); for (unsigned i = 0; i < 2 * (N - 1) - 1; i++) { - const vec_t s_a = vec_broadcast_bit( - still_going & ((f_a[0] & g_s[0]) ^ (f_s[0] & g_a[0]))); - const vec_t s_s = vec_broadcast_bit( - still_going & ((f_a[0] & g_a[0]) ^ (f_s[0] & g_s[0]))); + const vec_t s_a = vec_broadcast_bit(still_going & (f_a[0] & g_a[0])); + const vec_t s_s = + vec_broadcast_bit(still_going & ((f_s[0] ^ g_s[0]) & s_a)); const vec_t should_swap = (s_s | s_a) & vec_broadcast_bit15(deg_f - deg_g); poly3_vec_cswap(f_s, f_a, g_s, g_a, should_swap); - poly3_vec_fmadd(f_s, f_a, g_s, g_a, s_s, s_a); + poly3_vec_fmsub(f_s, f_a, g_s, g_a, s_s, s_a); poly3_vec_rshift1(f_s, f_a); poly3_vec_cswap(b_s, b_a, c_s, c_a, should_swap); - poly3_vec_fmadd(b_s, b_a, c_s, c_a, s_s, s_a); + poly3_vec_fmsub(b_s, b_a, c_s, c_a, s_s, s_a); poly3_vec_lshift1(c_s, c_a); const vec_t deg_sum = should_swap & (deg_f ^ deg_g); @@ -959,9 +956,9 @@ void HRSS_poly3_invert(struct poly3 *out, const struct poly3 *in) { for (unsigned i = 0; i < 2 * (N - 1) - 1; i++) { const crypto_word_t s_a = lsb_to_all( - still_going & ((f.a.v[0] & g.s.v[0]) ^ (f.s.v[0] & g.a.v[0]))); + still_going & (f.a.v[0] & g.a.v[0])); const crypto_word_t s_s = lsb_to_all( - still_going & ((f.a.v[0] & g.a.v[0]) ^ (f.s.v[0] & g.s.v[0]))); + still_going & ((f.s.v[0] ^ g.s.v[0]) & s_a)); const crypto_word_t should_swap = (s_s | s_a) & constant_time_lt_w(deg_f, deg_g); @@ -973,8 +970,8 @@ void HRSS_poly3_invert(struct poly3 *out, const struct poly3 *in) { deg_g ^= deg_sum; assert(deg_g >= 1); - poly3_fmadd(&f, &g, s_s, s_a); - poly3_fmadd(b, &c, s_s, s_a); + poly3_fmsub(&f, &g, s_s, s_a); + poly3_fmsub(b, &c, s_s, s_a); poly3_rshift1(&f); poly3_lshift1(&c); @@ -1463,7 +1460,7 @@ static void poly2_from_poly(struct poly2 *out, const struct poly *in) { *words = word; } -// mod3 treats |a| is a signed number and returns |a| mod 3. +// mod3 treats |a| as a signed number and returns |a| mod 3. static uint16_t mod3(int16_t a) { const int16_t q = ((int32_t)a * 21845) >> 16; int16_t ret = a - 3 * q; @@ -1486,9 +1483,10 @@ static void poly3_from_poly(struct poly3 *out, const struct poly *in) { // The signed value is reduced mod 3, yielding {0, 1, 2}. const uint16_t v = mod3((int16_t)(in->v[i] << 3) >> 3); s >>= 1; - s |= (crypto_word_t)(v & 2) << (BITS_PER_WORD - 2); + const crypto_word_t s_bit = (crypto_word_t)(v & 2) << (BITS_PER_WORD - 2); + s |= s_bit; a >>= 1; - a |= (crypto_word_t)(v & 1) << (BITS_PER_WORD - 1); + a |= s_bit | (crypto_word_t)(v & 1) << (BITS_PER_WORD - 1); shift++; if (shift == BITS_PER_WORD) { @@ -1528,9 +1526,11 @@ static crypto_word_t poly3_from_poly_checked(struct poly3 *out, ok &= constant_time_eq_w(v, expected); s >>= 1; - s |= (crypto_word_t)(mod3 & 2) << (BITS_PER_WORD - 2); + const crypto_word_t s_bit = (crypto_word_t)(mod3 & 2) + << (BITS_PER_WORD - 2); + s |= s_bit; a >>= 1; - a |= (crypto_word_t)(mod3 & 1) << (BITS_PER_WORD - 1); + a |= s_bit | (crypto_word_t)(mod3 & 1) << (BITS_PER_WORD - 1); shift++; if (shift == BITS_PER_WORD) { @@ -1794,69 +1794,21 @@ static void poly_marshal_mod3(uint8_t out[HRSS_POLY3_BYTES], // HRSS-specific functions // ----------------------- -// poly_short_sample implements the sampling algorithm given in [HRSSNIST] -// section 1.8.1. The output coefficients are in {0, 1, 0xffff} which makes some -// later computation easier. +// poly_short_sample samples a vector of values in {0xffff (i.e. -1), 0, 1}. +// This is the same action as the algorithm in [HRSSNIST] section 1.8.1, but +// with HRSS-SXY the sampling algorithm is now a private detail of the +// implementation (previously it had to match between two parties). This +// function uses that freedom to implement a flatter distribution of values. static void poly_short_sample(struct poly *out, const uint8_t in[HRSS_SAMPLE_BYTES]) { - // We wish to calculate the difference (mod 3) between two, two-bit numbers. - // Here is a table of results for a - b. Negative one is written as 0b11 so - // that a couple of shifts can be used to sign-extend it. Any input value of - // 0b11 is invalid and a convention is adopted that an invalid input results - // in an invalid output (0b10). - // - // b a result - // 00 00 00 - // 00 01 01 - // 00 10 11 - // 00 11 10 - // 01 00 11 - // 01 01 00 - // 01 10 01 - // 01 11 10 - // 10 00 01 - // 10 01 11 - // 10 10 00 - // 10 11 10 - // 11 00 10 - // 11 01 10 - // 11 10 10 - // 11 11 10 - // - // The result column is encoded in a single-word lookup-table: - // 0001 1110 1100 0110 0111 0010 1010 1010 - // 1 d c 6 7 2 a a - static const uint32_t kLookup = 0x1dc672aa; - - // In order to generate pairs of numbers mod 3 (non-uniformly) we treat pairs - // of bits in a uint32 as separate values and sum two random vectors of 1-bit - // numbers. This works because these pairs are isolated because no carry can - // spread between them. - - uint16_t *p = out->v; - for (size_t i = 0; i < N / 8; i++) { - uint32_t v; - OPENSSL_memcpy(&v, in, sizeof(v)); - in += sizeof(v); - - uint32_t sums = (v & 0x55555555) + ((v >> 1) & 0x55555555); - for (unsigned j = 0; j < 8; j++) { - p[j] = (int32_t)(kLookup << ((sums & 15) << 1)) >> 30; - sums >>= 4; - } - p += 8; + OPENSSL_STATIC_ASSERT(HRSS_SAMPLE_BYTES == N - 1, + "HRSS_SAMPLE_BYTES incorrect"); + for (size_t i = 0; i < N - 1; i++) { + uint16_t v = mod3(in[i]); + // Map {0, 1, 2} -> {0, 1, 0xffff} + v |= ((v >> 1) ^ 1) - 1; + out->v[i] = v; } - - // There are four values remaining. - uint16_t v; - OPENSSL_memcpy(&v, in, sizeof(v)); - - uint16_t sums = (v & 0x5555) + ((v >> 1) & 0x5555); - for (unsigned j = 0; j < 4; j++) { - p[j] = (int32_t)(kLookup << ((sums & 15) << 1)) >> 30; - sums >>= 4; - } - out->v[N - 1] = 0; } diff --git a/third_party/boringssl/kit/src/crypto/hrss/hrss_test.cc b/third_party/boringssl/kit/src/crypto/hrss/hrss_test.cc index 596db07c..493255d9 100644 --- a/third_party/boringssl/kit/src/crypto/hrss/hrss_test.cc +++ b/third_party/boringssl/kit/src/crypto/hrss/hrss_test.cc @@ -81,20 +81,18 @@ static void poly3_rand(poly3 *p) { RAND_bytes(reinterpret_cast(p), sizeof(poly3)); p->s.v[WORDS_PER_POLY - 1] &= (UINT64_C(1) << BITS_IN_LAST_WORD) - 1; p->a.v[WORDS_PER_POLY - 1] &= (UINT64_C(1) << BITS_IN_LAST_WORD) - 1; - // (s, a) = (1, 1) is invalid. Map those to one. + // (s, a) = (1, 0) is invalid. Map those to -1. for (size_t j = 0; j < WORDS_PER_POLY; j++) { - p->s.v[j] ^= p->s.v[j] & p->a.v[j]; + p->a.v[j] |= p->s.v[j]; } } // poly3_word_add sets (|s1|, |a1|) += (|s2|, |a2|). static void poly3_word_add(crypto_word_t *s1, crypto_word_t *a1, const crypto_word_t s2, const crypto_word_t a2) { - const crypto_word_t x = *a1 ^ a2; - const crypto_word_t y = (*s1 ^ s2) ^ (*a1 & a2); - const crypto_word_t z = *s1 & s2; - *s1 = y & ~x; - *a1 = z | (x & ~y); + const crypto_word_t t = *s1 ^ a2; + *s1 = t & (s2 ^ *a1); + *a1 = (*a1 ^ a2) | (t ^ s2); } TEST(HRSS, Poly3Invert) { @@ -105,6 +103,7 @@ TEST(HRSS, Poly3Invert) { // The inverse of -1 is -1. p.s.v[0] = 1; + p.a.v[0] = 1; HRSS_poly3_invert(&inverse, &p); EXPECT_EQ(Bytes(reinterpret_cast(&p), sizeof(p)), Bytes(reinterpret_cast(&inverse), sizeof(inverse))); @@ -144,7 +143,7 @@ TEST(HRSS, Poly3UnreducedInput) { // |r| is probably already not reduced mod Φ(N), but add x^701 - 1 and // recompute to ensure that we get the same answer. (Since (x^701 - 1) ≡ 0 mod // Φ(N).) - poly3_word_add(&r.s.v[0], &r.a.v[0], 1, 0); + poly3_word_add(&r.s.v[0], &r.a.v[0], 1, 1); poly3_word_add(&r.s.v[WORDS_PER_POLY - 1], &r.a.v[WORDS_PER_POLY - 1], 0, UINT64_C(1) << BITS_IN_LAST_WORD); @@ -160,11 +159,11 @@ TEST(HRSS, Poly3UnreducedInput) { for (size_t i = 0; i < WORDS_PER_POLY-1; i++) { EXPECT_EQ(CONSTTIME_TRUE_W, result.s.v[i]); - EXPECT_EQ(0u, result.a.v[i]); + EXPECT_EQ(CONSTTIME_TRUE_W, result.a.v[i]); } EXPECT_EQ((UINT64_C(1) << (BITS_IN_LAST_WORD - 1)) - 1, result.s.v[WORDS_PER_POLY - 1]); - EXPECT_EQ(0u, result.a.v[WORDS_PER_POLY - 1]); + EXPECT_EQ(result.s.v[WORDS_PER_POLY - 1], result.a.v[WORDS_PER_POLY - 1]); } TEST(HRSS, Basic) { @@ -251,216 +250,217 @@ TEST(HRSS, Golden) { HRSS_generate_key(&pub, &priv, generate_key_entropy); static const uint8_t kExpectedPub[HRSS_PUBLIC_KEY_BYTES] = { - 0xf8, 0x9f, 0xa0, 0xfc, 0xf1, 0xd4, 0xfa, 0x4d, 0x8f, 0x35, 0x28, 0x73, - 0x0e, 0x37, 0x18, 0x1d, 0x09, 0xf3, 0x9e, 0x16, 0x0d, 0x7f, 0x9c, 0x82, - 0x17, 0xa1, 0xa1, 0x88, 0x6b, 0x29, 0x5b, 0x3a, 0x30, 0xcd, 0x6f, 0x8e, - 0x0c, 0xd3, 0x38, 0x0c, 0x05, 0x68, 0x6e, 0x4c, 0xcc, 0x20, 0xd4, 0x06, - 0x77, 0x0c, 0xac, 0x1c, 0x49, 0x14, 0x00, 0xd6, 0x9b, 0x1c, 0xde, 0x43, - 0x0a, 0x59, 0x37, 0xd6, 0x46, 0x68, 0x1f, 0x04, 0xcb, 0x73, 0x92, 0x37, - 0x2d, 0x7f, 0x57, 0x70, 0x16, 0xe8, 0x06, 0x48, 0x3b, 0x66, 0xb3, 0x63, - 0x02, 0x5a, 0x71, 0x46, 0xdd, 0xa4, 0xee, 0xb8, 0x78, 0x44, 0xfd, 0x9e, - 0xd0, 0x71, 0x16, 0x00, 0xbd, 0x01, 0x1e, 0x27, 0x2e, 0xa0, 0xc6, 0x8d, - 0x55, 0x89, 0x7c, 0x2a, 0x01, 0x2b, 0x1b, 0x75, 0xa2, 0xc2, 0xd1, 0x5a, - 0x67, 0xfa, 0xdd, 0x3b, 0x70, 0x9d, 0xdb, 0xcd, 0x73, 0x32, 0x5e, 0x24, - 0xb1, 0xcf, 0x23, 0xbe, 0x3c, 0x56, 0xcc, 0xbe, 0x61, 0xdb, 0xe7, 0x3c, - 0xc7, 0xf5, 0x09, 0xe6, 0x87, 0xa0, 0x09, 0x52, 0x9d, 0x61, 0x5b, 0xc6, - 0xd4, 0xc5, 0x2e, 0xc2, 0x6c, 0x87, 0x30, 0x36, 0x49, 0x6f, 0x04, 0xaa, - 0xb3, 0x26, 0xd5, 0x63, 0xcf, 0xd4, 0x74, 0x1e, 0xc7, 0x79, 0xb3, 0xfc, - 0x8c, 0x41, 0x36, 0x79, 0xaa, 0xd5, 0xba, 0x64, 0x49, 0x48, 0xdb, 0xeb, - 0xe8, 0x33, 0x7d, 0xbe, 0x3b, 0x67, 0xd7, 0xfd, 0x93, 0x1e, 0x80, 0x8d, - 0x17, 0xab, 0x6f, 0xfd, 0x1c, 0x4b, 0x2d, 0x5b, 0x90, 0xf0, 0xf0, 0x5d, - 0xbe, 0x8f, 0x81, 0x18, 0x29, 0x08, 0x9a, 0x47, 0x1b, 0xc2, 0x2d, 0xa2, - 0x22, 0x5a, 0x4f, 0xe9, 0x81, 0x64, 0xdd, 0x53, 0x2e, 0x67, 0xe5, 0x07, - 0x1a, 0xf0, 0x0c, 0x54, 0x9b, 0xe2, 0xf8, 0xe6, 0xb3, 0xb6, 0xe0, 0x5a, - 0x74, 0xfa, 0x8d, 0x9c, 0xa5, 0x7c, 0x6e, 0x73, 0xba, 0xee, 0x6e, 0x6e, - 0x31, 0xcb, 0x59, 0xd7, 0xfd, 0x94, 0x1c, 0x4d, 0x62, 0xc6, 0x87, 0x0b, - 0x38, 0x54, 0xc6, 0x35, 0xac, 0xc8, 0x8c, 0xc0, 0xd9, 0x99, 0xee, 0xfc, - 0xa9, 0xde, 0xc4, 0x50, 0x88, 0x8e, 0x24, 0xf6, 0xd6, 0x04, 0x54, 0x3e, - 0x81, 0xc4, 0x96, 0x9a, 0x40, 0xe5, 0xef, 0x8b, 0xec, 0x41, 0x50, 0x1d, - 0x14, 0xae, 0xa4, 0x5a, 0xac, 0xd4, 0x73, 0x31, 0xc3, 0x1d, 0xc1, 0x96, - 0x89, 0xd8, 0x62, 0x97, 0x60, 0x3f, 0x58, 0x2a, 0x5f, 0xcf, 0xcb, 0x26, - 0x99, 0x69, 0x81, 0x13, 0x9c, 0xaf, 0x17, 0x91, 0xa8, 0xeb, 0x9a, 0xf9, - 0xd3, 0x83, 0x47, 0x66, 0xc7, 0xf8, 0xd8, 0xe3, 0xd2, 0x7e, 0x58, 0xa9, - 0xf5, 0xb2, 0x03, 0xbe, 0x7e, 0xa5, 0x29, 0x9d, 0xff, 0xd1, 0xd8, 0x55, - 0x39, 0xc7, 0x2c, 0xce, 0x03, 0x64, 0xdc, 0x18, 0xe7, 0xb0, 0x60, 0x46, - 0x26, 0xeb, 0xb7, 0x61, 0x4b, 0x91, 0x2c, 0xd8, 0xa2, 0xee, 0x63, 0x2e, - 0x15, 0x0a, 0x58, 0x88, 0x04, 0xb1, 0xed, 0x6d, 0xf1, 0x5c, 0xc7, 0xee, - 0x60, 0x38, 0x26, 0xc9, 0x31, 0x7e, 0x69, 0xe4, 0xac, 0x3c, 0x72, 0x09, - 0x3e, 0xe6, 0x24, 0x30, 0x44, 0x6e, 0x66, 0x83, 0xb9, 0x2a, 0x22, 0xaf, - 0x26, 0x1e, 0xaa, 0xa3, 0xf4, 0xb1, 0xa1, 0x5c, 0xfa, 0x5f, 0x0d, 0x71, - 0xac, 0xe3, 0xe0, 0xc3, 0xdd, 0x4f, 0x96, 0x57, 0x8b, 0x58, 0xac, 0xe3, - 0x42, 0x8e, 0x47, 0x72, 0xb1, 0xe4, 0x19, 0x68, 0x3e, 0xbb, 0x19, 0x14, - 0xdf, 0x16, 0xb5, 0xde, 0x7f, 0x37, 0xaf, 0xd8, 0xd3, 0x3d, 0x6a, 0x16, - 0x1b, 0x26, 0xd3, 0xcc, 0x53, 0x82, 0x57, 0x90, 0x89, 0xc5, 0x7e, 0x6d, - 0x7e, 0x99, 0x5b, 0xcd, 0xd3, 0x18, 0xbb, 0x89, 0xef, 0x76, 0xbd, 0xd2, - 0x62, 0xf0, 0xe8, 0x25, 0x2a, 0x8d, 0xe2, 0x21, 0xea, 0xde, 0x6e, 0xa5, - 0xa4, 0x3d, 0x58, 0xee, 0xdf, 0x90, 0xc1, 0xa1, 0x38, 0x5d, 0x11, 0x50, - 0xb5, 0xac, 0x9d, 0xb4, 0xfd, 0xef, 0x53, 0xe8, 0xc0, 0x17, 0x6c, 0x4f, - 0x31, 0xe0, 0xcc, 0x8f, 0x80, 0x7a, 0x84, 0x14, 0xde, 0xee, 0xec, 0xdd, - 0x6a, 0xad, 0x29, 0x65, 0xa5, 0x72, 0xc3, 0x73, 0x5f, 0xe3, 0x6f, 0x60, - 0xb1, 0xfb, 0x0f, 0xaa, 0xc6, 0xda, 0x53, 0x4a, 0xb1, 0x92, 0x2a, 0xb7, - 0x02, 0xbe, 0xf9, 0xdf, 0x37, 0x16, 0xe7, 0x5c, 0x38, 0x0b, 0x3c, 0xe2, - 0xdd, 0x90, 0xb8, 0x7b, 0x48, 0x69, 0x79, 0x81, 0xc5, 0xae, 0x9a, 0x0d, - 0x78, 0x95, 0x52, 0x63, 0x80, 0xda, 0x46, 0x69, 0x20, 0x57, 0x9b, 0x27, - 0xe2, 0xe8, 0xbd, 0x2f, 0x45, 0xe6, 0x46, 0x40, 0xae, 0x50, 0xd5, 0xa2, - 0x53, 0x93, 0xe1, 0x99, 0xfd, 0x13, 0x7c, 0xf6, 0x22, 0xc4, 0x6c, 0xab, - 0xe3, 0xc9, 0x55, 0x0a, 0x16, 0x67, 0x68, 0x26, 0x6b, 0xd6, 0x7d, 0xde, - 0xd3, 0xae, 0x71, 0x32, 0x02, 0xf1, 0x27, 0x67, 0x47, 0x74, 0xd9, 0x40, - 0x35, 0x1d, 0x25, 0x72, 0x32, 0xdf, 0x75, 0xd5, 0x60, 0x26, 0xab, 0x90, - 0xfa, 0xeb, 0x26, 0x11, 0x4b, 0xb4, 0xc5, 0xc2, 0x3e, 0xa9, 0x23, 0x3a, - 0x4e, 0x6a, 0xb1, 0xbb, 0xb3, 0xea, 0xf9, 0x1e, 0xe4, 0x10, 0xf5, 0xdc, - 0x35, 0xde, 0xb5, 0xee, 0xf0, 0xde, 0xa1, 0x18, 0x80, 0xc7, 0x13, 0x68, - 0x46, 0x94, 0x0e, 0x2a, 0x8e, 0xf8, 0xe9, 0x26, 0x84, 0x42, 0x0f, 0x56, - 0xed, 0x67, 0x7f, 0xeb, 0x7d, 0x35, 0x07, 0x01, 0x11, 0x81, 0x8b, 0x56, - 0x88, 0xc6, 0x58, 0x61, 0x65, 0x3c, 0x5d, 0x9c, 0x58, 0x25, 0xd6, 0xdf, - 0x4e, 0x3b, 0x93, 0xbf, 0x82, 0xe1, 0x19, 0xb8, 0xda, 0xde, 0x26, 0x38, - 0xf2, 0xd9, 0x95, 0x24, 0x98, 0xde, 0x58, 0xf7, 0x0c, 0xe9, 0x32, 0xbb, - 0xcc, 0xf7, 0x92, 0x69, 0xa2, 0xf0, 0xc3, 0xfa, 0xd2, 0x31, 0x8b, 0x43, - 0x4e, 0x03, 0xe2, 0x13, 0x79, 0x6e, 0x73, 0x63, 0x3b, 0x45, 0xde, 0x80, - 0xf4, 0x26, 0xb1, 0x38, 0xed, 0x62, 0x55, 0xc6, 0x6a, 0x67, 0x00, 0x2d, - 0xba, 0xb2, 0xc5, 0xb6, 0x97, 0x62, 0x28, 0x64, 0x30, 0xb9, 0xfb, 0x3f, - 0x94, 0x03, 0x48, 0x36, 0x2c, 0x5d, 0xfd, 0x08, 0x96, 0x40, 0xd1, 0x6c, - 0xe5, 0xd0, 0xf8, 0x99, 0x40, 0x82, 0x87, 0xd7, 0xdc, 0x2f, 0x8b, 0xaa, - 0x31, 0x96, 0x0a, 0x34, 0x33, 0xa6, 0xf1, 0x84, 0x6e, 0x33, 0x73, 0xc5, - 0xe3, 0x26, 0xad, 0xd0, 0xcb, 0x62, 0x71, 0x82, 0xab, 0xd1, 0x82, 0x33, - 0xe6, 0xca, 0xd0, 0x3e, 0xf5, 0x4d, 0x12, 0x6e, 0xf1, 0x83, 0xbd, 0xdc, - 0x4d, 0xdf, 0x49, 0xbc, 0x63, 0xae, 0x7e, 0x59, 0xe8, 0x3c, 0x0d, 0xd6, - 0x1d, 0x41, 0x89, 0x72, 0x52, 0xc0, 0xae, 0xd1, 0x2f, 0x0a, 0x8a, 0xce, - 0x26, 0xd0, 0x3e, 0x0c, 0x71, 0x32, 0x52, 0xb2, 0xe4, 0xee, 0xa2, 0xe5, - 0x28, 0xb6, 0x33, 0x69, 0x97, 0x5a, 0x53, 0xdb, 0x56, 0x63, 0xe9, 0xb3, - 0x6d, 0x60, 0xf4, 0x7a, 0xce, 0xec, 0x36, 0x65, 0xd5, 0xca, 0x63, 0x2a, - 0x19, 0x90, 0x14, 0x7b, 0x02, 0x33, 0xfa, 0x11, 0x58, 0x5a, 0xd9, 0xc5, - 0x54, 0xf3, 0x28, 0xd5, 0x6e, 0xea, 0x85, 0xf5, 0x09, 0xbb, 0x81, 0x44, - 0x1c, 0x63, 0x66, 0x81, 0xc5, 0x96, 0x2d, 0x7c, 0x0e, 0x75, 0x7b, 0xb4, - 0x7e, 0x4e, 0x0c, 0xfd, 0x3c, 0xc5, 0x5a, 0x22, 0x85, 0x5c, 0xc8, 0xf3, - 0x97, 0x98, 0x2c, 0xe9, 0x46, 0xb4, 0x02, 0xcf, 0x7d, 0xa4, 0xf2, 0x44, - 0x7a, 0x89, 0x71, 0xa0, 0xfa, 0xb6, 0xa3, 0xaf, 0x13, 0x25, 0x46, 0xe2, - 0x64, 0xe3, 0x69, 0xba, 0xf9, 0x68, 0x5c, 0xc0, 0xb7, 0xa8, 0xa6, 0x4b, - 0xe1, 0x42, 0xe9, 0xb5, 0xc7, 0x84, 0xbb, 0xa6, 0x4b, 0x10, 0x4e, 0xd4, - 0x68, 0x70, 0x0a, 0x75, 0x2a, 0xbb, 0x9d, 0xa0, 0xcb, 0xf0, 0x36, 0x4c, - 0x70, 0x6c, 0x60, 0x4d, 0xfe, 0xe8, 0xc8, 0x66, 0x80, 0x1b, 0xf7, 0xcc, - 0x1a, 0xdd, 0x6b, 0xa7, 0xa7, 0x25, 0x61, 0x0c, 0x31, 0xf0, 0x34, 0x63, - 0x00, 0x0e, 0x48, 0x6a, 0x5a, 0x8d, 0x47, 0x94, 0x3f, 0x14, 0x16, 0xa8, - 0x8a, 0x49, 0xbb, 0x0c, 0x43, 0x21, 0xda, 0xf2, 0xc5, 0xd0, 0xff, 0x19, - 0x3e, 0x36, 0x64, 0x20, 0xb3, 0x70, 0xae, 0x54, 0xca, 0x73, 0x05, 0x56, - 0x7a, 0x49, 0x45, 0xe9, 0x46, 0xbc, 0xc2, 0x61, 0x70, 0x40, 0x7c, 0xb0, - 0xf7, 0xea, 0xc0, 0xd1, 0xb0, 0x77, 0x2c, 0xc7, 0xdd, 0x88, 0xcb, 0x9d, - 0xea, 0x55, 0x6c, 0x5c, 0x28, 0xb8, 0x84, 0x1c, 0x2c, 0x06, + 0x4a, 0x21, 0x39, 0x7c, 0xb4, 0xa6, 0x58, 0x15, 0x35, 0x77, 0xe4, 0x2a, + 0x02, 0x79, 0xc0, 0x02, 0xe2, 0x21, 0x27, 0x5f, 0x49, 0xc7, 0x2c, 0x14, + 0xb6, 0xe0, 0x67, 0xc2, 0xc7, 0x09, 0x62, 0x0c, 0xe5, 0x23, 0x9c, 0x40, + 0xd7, 0x7e, 0xf5, 0x55, 0x5a, 0xa2, 0xd0, 0x9f, 0xd3, 0x8c, 0x67, 0x7b, + 0x48, 0xa4, 0x53, 0x8d, 0x39, 0xb1, 0xcc, 0x99, 0x29, 0xf7, 0x83, 0xbf, + 0x6f, 0x9b, 0x16, 0x73, 0x23, 0xcc, 0xc3, 0x86, 0x98, 0xb1, 0x7c, 0x53, + 0xb1, 0xf5, 0xf4, 0xdd, 0xc8, 0x97, 0x5e, 0xd3, 0x6d, 0x63, 0xce, 0xf3, + 0xa2, 0xf6, 0xef, 0x94, 0xed, 0x4a, 0x3e, 0xe6, 0x4b, 0xa2, 0xfb, 0x87, + 0xa3, 0xbc, 0x65, 0x1c, 0x17, 0x64, 0x25, 0xa7, 0xb4, 0xa1, 0xe6, 0x84, + 0x06, 0x72, 0x0c, 0x28, 0xe8, 0xfc, 0xaa, 0xca, 0xf8, 0x20, 0x79, 0x89, + 0xa9, 0xf0, 0x60, 0xdf, 0xd6, 0xd4, 0xe0, 0xaf, 0x99, 0x54, 0x21, 0xaf, + 0x76, 0xd5, 0x9a, 0x31, 0x80, 0xea, 0x7f, 0x03, 0x6c, 0x14, 0x74, 0x06, + 0x9c, 0x93, 0xe3, 0x93, 0xcc, 0x46, 0x4d, 0x82, 0xda, 0xdf, 0x67, 0xe9, + 0x6d, 0x58, 0x2b, 0x49, 0xf3, 0x10, 0x71, 0xa0, 0xc5, 0xec, 0xa0, 0x29, + 0xd7, 0x7c, 0x43, 0xd5, 0x05, 0x7e, 0x14, 0x8c, 0x39, 0x28, 0xf9, 0x46, + 0x3d, 0xc1, 0x10, 0x6c, 0x2f, 0xaa, 0xca, 0x11, 0x87, 0x6a, 0xe2, 0xb1, + 0xf6, 0x31, 0x76, 0xb0, 0xdc, 0x30, 0x8a, 0x97, 0x7d, 0xdc, 0xe4, 0xd1, + 0x18, 0xe9, 0x03, 0x91, 0xf5, 0xd2, 0x94, 0x4d, 0x71, 0xf7, 0x35, 0xc8, + 0x3e, 0x46, 0xaf, 0xa3, 0xeb, 0x35, 0x07, 0x01, 0x77, 0xc5, 0x58, 0xca, + 0x82, 0x67, 0x3e, 0x4f, 0x01, 0x88, 0xa4, 0xa0, 0xea, 0x0a, 0xb7, 0x13, + 0x06, 0xbe, 0xb6, 0x61, 0xa4, 0xa2, 0x28, 0xe2, 0x32, 0xcf, 0x25, 0x46, + 0xcf, 0xce, 0xf5, 0x57, 0x9b, 0x74, 0x8f, 0xfd, 0xbc, 0xfa, 0x3a, 0xa2, + 0x18, 0x22, 0xf1, 0xb1, 0x43, 0x12, 0xe8, 0xe2, 0xe3, 0x06, 0xe6, 0x1c, + 0xa7, 0x76, 0x2d, 0x0d, 0xe5, 0x5f, 0xbd, 0x8f, 0xa0, 0x95, 0xcd, 0xe9, + 0x28, 0xdb, 0xcc, 0xe5, 0x66, 0x33, 0xd4, 0x4b, 0xf9, 0x0c, 0x42, 0x9b, + 0x27, 0xee, 0x11, 0xd0, 0xe3, 0x0b, 0x9d, 0xce, 0x2c, 0x91, 0x7a, 0x0e, + 0xb8, 0xde, 0x31, 0x73, 0x86, 0x8e, 0x34, 0x59, 0x93, 0x2e, 0x37, 0x9d, + 0xc2, 0x3e, 0x89, 0x0b, 0x47, 0xff, 0xa6, 0x55, 0x21, 0xe6, 0x4f, 0x72, + 0x7c, 0xcc, 0xe5, 0xb8, 0x18, 0x2c, 0x10, 0xcb, 0xce, 0x48, 0xa5, 0xc5, + 0x26, 0xb6, 0x19, 0x76, 0xc5, 0x38, 0xf0, 0x38, 0x72, 0xec, 0x22, 0xf9, + 0x25, 0xde, 0x1c, 0x0c, 0x1b, 0x3e, 0x43, 0xc5, 0x5c, 0x8c, 0xdb, 0xf1, + 0x42, 0x66, 0xbc, 0xdf, 0xa0, 0x82, 0x4b, 0xec, 0xe1, 0x50, 0x42, 0x57, + 0x84, 0x60, 0xfd, 0x89, 0x12, 0x1b, 0xf6, 0xf9, 0x4d, 0x0d, 0x16, 0xe8, + 0xa4, 0xe2, 0x67, 0x2c, 0x8f, 0x22, 0xea, 0xba, 0x46, 0x34, 0xce, 0x97, + 0x8b, 0x4c, 0x38, 0x0e, 0x16, 0x82, 0xb6, 0xf3, 0x34, 0x38, 0x07, 0x87, + 0x73, 0x2a, 0x3d, 0x80, 0x56, 0x4b, 0x85, 0x67, 0xca, 0x2a, 0x19, 0xb6, + 0xb6, 0x2c, 0xfe, 0xd8, 0x02, 0xe5, 0xad, 0xd0, 0x61, 0x79, 0x73, 0xab, + 0xda, 0x3b, 0xa4, 0x51, 0xb3, 0xf7, 0x85, 0x99, 0xb2, 0xd0, 0x64, 0x97, + 0xb7, 0x3c, 0x0e, 0x58, 0xdf, 0xd2, 0x98, 0x98, 0x18, 0x1a, 0xf5, 0x59, + 0xcd, 0xc5, 0x48, 0x17, 0x10, 0x9f, 0xd8, 0x19, 0xbd, 0xd0, 0x42, 0x71, + 0x1c, 0x30, 0xc6, 0x76, 0xe9, 0xb0, 0xee, 0xf5, 0x38, 0x05, 0xbe, 0x9b, + 0x6c, 0x0d, 0xb0, 0xd0, 0xda, 0x1c, 0x89, 0xbd, 0x40, 0x5d, 0xc2, 0x5a, + 0xbe, 0x83, 0xa6, 0xb5, 0x47, 0xa7, 0xf8, 0xb9, 0xbf, 0xa2, 0x65, 0x17, + 0x1e, 0xd8, 0x28, 0x42, 0xbe, 0xb0, 0x35, 0xf6, 0x7b, 0x88, 0x38, 0xbe, + 0xf5, 0xb5, 0x1b, 0x63, 0x7a, 0x83, 0x92, 0x0d, 0x64, 0xad, 0x92, 0x59, + 0x97, 0x55, 0x5c, 0x60, 0xab, 0x48, 0x8e, 0x23, 0x27, 0x22, 0x75, 0x3b, + 0x7c, 0x9c, 0x69, 0x13, 0x52, 0x6b, 0xae, 0xfd, 0x38, 0xe5, 0x4b, 0x36, + 0x78, 0x55, 0x92, 0xb5, 0x8f, 0x25, 0xde, 0x0e, 0x93, 0xe3, 0x1d, 0x83, + 0x62, 0x05, 0x6a, 0x5a, 0xff, 0x7f, 0x77, 0xf7, 0x1b, 0xfc, 0x21, 0x45, + 0xf7, 0xb8, 0xfa, 0xcb, 0x00, 0x5e, 0x85, 0xf9, 0x2f, 0x15, 0x2f, 0xcf, + 0x17, 0x9e, 0x84, 0xf6, 0xf5, 0x15, 0x6e, 0xdd, 0xb4, 0x73, 0x44, 0xc2, + 0x2c, 0x74, 0xae, 0x27, 0x5f, 0x19, 0xe7, 0x51, 0x61, 0xc1, 0x82, 0xce, + 0xf1, 0x5b, 0xa0, 0x6f, 0x0b, 0x13, 0x10, 0x68, 0xb7, 0xee, 0xfb, 0x8a, + 0x85, 0xe2, 0xd6, 0x17, 0x55, 0x26, 0xa5, 0xc5, 0xb3, 0x94, 0x45, 0xdf, + 0x49, 0xe6, 0x50, 0xf8, 0x99, 0xd8, 0x3c, 0xcb, 0x94, 0x80, 0x67, 0x3b, + 0x73, 0xac, 0xf6, 0x46, 0x31, 0x63, 0xb3, 0x1b, 0x47, 0xce, 0x40, 0x3f, + 0x8c, 0xd0, 0x82, 0xc4, 0x79, 0x3a, 0x7c, 0x48, 0x10, 0xe3, 0x97, 0x98, + 0xdc, 0x0b, 0x62, 0x42, 0xfa, 0x26, 0x05, 0xf6, 0x8c, 0x32, 0xa9, 0xb6, + 0x2c, 0x4f, 0x85, 0xd2, 0x9b, 0xf3, 0x89, 0x1f, 0x91, 0xca, 0x12, 0x3d, + 0xe2, 0xa8, 0x0b, 0xca, 0x64, 0x28, 0x0e, 0xa7, 0xfd, 0xd8, 0xa3, 0xcb, + 0x0a, 0xd9, 0x97, 0x2d, 0xc3, 0xf2, 0x39, 0x74, 0xdb, 0xe3, 0x9a, 0x87, + 0x1a, 0xe0, 0x33, 0xe3, 0x92, 0xe8, 0xde, 0xb5, 0x08, 0x28, 0xcb, 0xd7, + 0xb6, 0x79, 0xec, 0x71, 0xcc, 0xe5, 0xd1, 0x4b, 0x89, 0x96, 0x5f, 0xfa, + 0xfd, 0x4b, 0xd0, 0xa8, 0x66, 0x0d, 0xb4, 0xa7, 0x51, 0x56, 0xbc, 0xa7, + 0x74, 0x07, 0x7f, 0xae, 0x0e, 0xf6, 0x9c, 0x13, 0xd9, 0xf2, 0xed, 0x12, + 0xa9, 0x87, 0x3e, 0xb7, 0x9d, 0x53, 0x8a, 0x82, 0x2d, 0x03, 0x2f, 0xac, + 0x94, 0x84, 0x95, 0x00, 0x29, 0x09, 0x01, 0x38, 0x62, 0xff, 0xaf, 0xfd, + 0x10, 0x2b, 0x31, 0x03, 0xb2, 0x4f, 0x51, 0xfb, 0x76, 0x27, 0x1e, 0x25, + 0x82, 0x79, 0x65, 0x69, 0xfa, 0x24, 0xaf, 0xcb, 0xe8, 0x40, 0x8d, 0x7d, + 0xd2, 0x9a, 0x12, 0x69, 0x2f, 0xe4, 0xce, 0x99, 0x98, 0x4f, 0x6c, 0x46, + 0xfd, 0x63, 0x40, 0x50, 0xef, 0x22, 0x02, 0x68, 0x2e, 0x53, 0xbb, 0x00, + 0xa3, 0x65, 0x61, 0x3e, 0x97, 0xd4, 0x5f, 0xa2, 0xc1, 0x66, 0xcd, 0x04, + 0xdc, 0xda, 0x55, 0x10, 0x28, 0x0d, 0x40, 0x11, 0xe6, 0x68, 0xed, 0x68, + 0x38, 0x7d, 0x20, 0xc3, 0x97, 0x9d, 0xcb, 0x6e, 0x30, 0xfc, 0xbe, 0x63, + 0xe7, 0x72, 0x47, 0x05, 0xf5, 0x0b, 0x7e, 0x66, 0x3b, 0xc5, 0x3a, 0x85, + 0x5a, 0xa3, 0xc5, 0x72, 0x9d, 0xb9, 0xc1, 0xb4, 0x80, 0x98, 0x6e, 0x40, + 0x86, 0xc9, 0xcb, 0xa3, 0xab, 0x77, 0xc2, 0x56, 0xfc, 0xcb, 0x6e, 0x12, + 0xf5, 0x63, 0x62, 0xf8, 0xff, 0x91, 0x15, 0xa7, 0xa1, 0x5e, 0xb6, 0xee, + 0x69, 0x4d, 0x5b, 0x5f, 0x4e, 0xfa, 0xd3, 0x61, 0xca, 0xec, 0x14, 0xfd, + 0xd9, 0x10, 0xf5, 0x4a, 0x05, 0x5f, 0x29, 0xcb, 0x77, 0x2c, 0x2d, 0xe2, + 0x90, 0x67, 0x62, 0x78, 0x75, 0xa9, 0x4e, 0x20, 0x00, 0x0c, 0x91, 0x84, + 0xba, 0xed, 0x1c, 0xce, 0xbd, 0x57, 0x4f, 0xa5, 0x2f, 0x59, 0x6c, 0x4c, + 0xdf, 0x5f, 0xaa, 0x32, 0xf0, 0x86, 0x09, 0x15, 0x36, 0xc6, 0xe6, 0x6a, + 0x24, 0xb4, 0xb3, 0x09, 0xdd, 0x32, 0xc5, 0x95, 0xac, 0x60, 0xb5, 0x09, + 0x97, 0x36, 0xa1, 0x3c, 0x8f, 0x0e, 0x90, 0x8e, 0xcd, 0xd0, 0x49, 0x75, + 0xf7, 0xf3, 0x80, 0x80, 0xcb, 0x1f, 0xee, 0xf2, 0x6a, 0x2f, 0x19, 0x8c, + 0xba, 0x10, 0x00, 0xda, 0x13, 0xef, 0x10, 0x2b, 0xb7, 0xef, 0xfd, 0xd1, + 0xe0, 0x7c, 0xf8, 0x46, 0x01, 0x69, 0x9b, 0x99, 0x80, 0x51, 0x1f, 0x74, + 0x3b, 0x67, 0x93, 0x18, 0x5e, 0xd4, 0x34, 0x6c, 0x81, 0x76, 0x02, 0xef, + 0x91, 0xa4, 0x22, 0x2a, 0x23, 0x1b, 0x58, 0x43, 0x75, 0x65, 0x13, 0x87, + 0x98, 0x60, 0x14, 0x25, 0x28, 0x67, 0xa3, 0x34, 0x8c, 0xe0, 0xd5, 0xd3, + 0x51, 0x33, 0x68, 0xff, 0x65, 0x59, 0x5a, 0xa7, 0xb2, 0x6b, 0x01, 0xad, + 0x70, 0x06, 0x73, 0x01, 0x51, 0x1b, 0xe1, 0xec, 0x28, 0x2f, 0x8a, 0x85, + 0x5a, 0x10, 0xd0, 0x0e, 0x6b, 0x35, 0x45, 0x2e, 0x61, 0xdd, 0x77, 0x20, + 0xb1, 0x35, 0x3b, 0xa8, 0xdd, 0x8a, 0xe2, 0x15, 0x79, 0x07, }; uint8_t pub_bytes[HRSS_PUBLIC_KEY_BYTES]; HRSS_marshal_public_key(pub_bytes, &pub); EXPECT_EQ(Bytes(pub_bytes), Bytes(kExpectedPub)); + uint8_t encap_entropy[HRSS_ENCAP_BYTES]; + for (size_t i = 0; i < sizeof(encap_entropy); i++) { + encap_entropy[i] = 31 + i; + } uint8_t ciphertext[HRSS_CIPHERTEXT_BYTES]; uint8_t shared_key[HRSS_KEY_BYTES]; - OPENSSL_STATIC_ASSERT( - sizeof(kExpectedPub) >= HRSS_ENCAP_BYTES, - "Private key too small to use as input to HRSS encapsulation"); - HRSS_encap(ciphertext, shared_key, &pub, kExpectedPub); + HRSS_encap(ciphertext, shared_key, &pub, encap_entropy); static const uint8_t kExpectedCiphertext[HRSS_CIPHERTEXT_BYTES] = { - 0x8e, 0x6b, 0x46, 0x9d, 0x4a, 0xef, 0xa6, 0x8c, 0x28, 0x7b, 0xec, 0x6f, - 0x13, 0x2d, 0x7f, 0x6c, 0xca, 0x7d, 0x9e, 0x6b, 0x54, 0x62, 0xa3, 0x13, - 0xe1, 0x1e, 0x8f, 0x5f, 0x71, 0x67, 0xc4, 0x85, 0xdf, 0xd5, 0x6b, 0xbd, - 0x86, 0x0f, 0x98, 0xec, 0xa5, 0x04, 0xf7, 0x7b, 0x2a, 0xbe, 0xcb, 0xac, - 0x29, 0xbe, 0xe1, 0x0f, 0xbc, 0x62, 0x87, 0x85, 0x7f, 0x05, 0xae, 0xe4, - 0x3f, 0x87, 0xfc, 0x1f, 0xf7, 0x45, 0x1e, 0xa3, 0xdb, 0xb1, 0xa0, 0x25, - 0xba, 0x82, 0xec, 0xca, 0x8d, 0xab, 0x7a, 0x20, 0x03, 0xeb, 0xe5, 0x5c, - 0x9f, 0xd0, 0x46, 0x78, 0xf1, 0x5a, 0xc7, 0x9e, 0xb4, 0x10, 0x6d, 0x37, - 0xc0, 0x75, 0x08, 0xfb, 0xeb, 0xcb, 0xd8, 0x35, 0x21, 0x9b, 0x89, 0xa0, - 0xaa, 0x87, 0x00, 0x66, 0x38, 0x37, 0x68, 0xa4, 0xa3, 0x93, 0x8e, 0x2b, - 0xca, 0xf7, 0x7a, 0x43, 0xb2, 0x15, 0x79, 0x81, 0xce, 0xa9, 0x09, 0xcb, - 0x29, 0xd4, 0xcc, 0xef, 0xf1, 0x9b, 0xbd, 0xe6, 0x63, 0xd5, 0x26, 0x0f, - 0xe8, 0x8b, 0xdf, 0xf1, 0xc3, 0xb4, 0x18, 0x0e, 0xf2, 0x1d, 0x5d, 0x82, - 0x9b, 0x1f, 0xf3, 0xca, 0x36, 0x2a, 0x26, 0x0a, 0x7f, 0xc4, 0x0d, 0xbd, - 0x5b, 0x15, 0x1c, 0x18, 0x6c, 0x11, 0x4e, 0xec, 0x36, 0x01, 0xc1, 0x15, - 0xab, 0xf7, 0x0b, 0x1a, 0xd3, 0xa1, 0xbd, 0x68, 0xc8, 0x59, 0xe7, 0x49, - 0x5c, 0xd5, 0x4b, 0x8c, 0x31, 0xdb, 0xb3, 0xea, 0x88, 0x09, 0x2f, 0xb9, - 0x8b, 0xfd, 0x96, 0x35, 0x88, 0x53, 0x72, 0x40, 0xcd, 0x89, 0x75, 0xb4, - 0x20, 0xf6, 0xf6, 0xe5, 0x74, 0x19, 0x48, 0xaf, 0x4b, 0xaa, 0x42, 0xa4, - 0xc8, 0x90, 0xee, 0xf3, 0x12, 0x04, 0x63, 0x90, 0x92, 0x8a, 0x89, 0xc3, - 0xa0, 0x7e, 0xfe, 0x19, 0xb3, 0x54, 0x53, 0x83, 0xe9, 0xc1, 0x6c, 0xe3, - 0x97, 0xa6, 0x27, 0xc3, 0x20, 0x9a, 0x79, 0x35, 0xc9, 0xb5, 0xc0, 0x90, - 0xe1, 0x56, 0x84, 0x69, 0xc2, 0x54, 0x77, 0x52, 0x48, 0x55, 0x71, 0x3e, - 0xcd, 0xa7, 0xd6, 0x25, 0x5d, 0x49, 0x13, 0xd2, 0x59, 0xd7, 0xe1, 0xd1, - 0x70, 0x46, 0xa0, 0xd4, 0xee, 0x59, 0x13, 0x1f, 0x1a, 0xd3, 0x39, 0x7d, - 0xb0, 0x79, 0xf7, 0xc0, 0x73, 0x5e, 0xbb, 0x08, 0xf7, 0x5c, 0xb0, 0x31, - 0x41, 0x3d, 0x7b, 0x1e, 0xf0, 0xe6, 0x47, 0x5c, 0x37, 0xd5, 0x54, 0xf1, - 0xbb, 0x64, 0xd7, 0x41, 0x8b, 0x34, 0x55, 0xaa, 0xc3, 0x5a, 0x9c, 0xa0, - 0xcc, 0x29, 0x8e, 0x5a, 0x1a, 0x93, 0x5a, 0x49, 0xd3, 0xd0, 0xa0, 0x56, - 0xda, 0x32, 0xa2, 0xa9, 0xa7, 0x13, 0x42, 0x93, 0x9b, 0x20, 0x32, 0x37, - 0x5c, 0x3e, 0x03, 0xa5, 0x28, 0x10, 0x93, 0xdd, 0xa0, 0x04, 0x7b, 0x2a, - 0xbd, 0x31, 0xc3, 0x6a, 0x89, 0x58, 0x6e, 0x55, 0x0e, 0xc9, 0x5c, 0x70, - 0x07, 0x10, 0xf1, 0x9a, 0xbd, 0xfb, 0xd2, 0xb7, 0x94, 0x5b, 0x4f, 0x8d, - 0x90, 0xfa, 0xee, 0xae, 0x37, 0x48, 0xc5, 0xf8, 0x16, 0xa1, 0x3b, 0x70, - 0x03, 0x1f, 0x0e, 0xb8, 0xbd, 0x8d, 0x30, 0x4f, 0x95, 0x31, 0x0b, 0x9f, - 0xfc, 0x80, 0xf8, 0xef, 0xa3, 0x3c, 0xbc, 0xe2, 0x23, 0x23, 0x3e, 0x2a, - 0x55, 0x11, 0xe8, 0x2c, 0x17, 0xea, 0x1c, 0xbd, 0x1d, 0x2d, 0x1b, 0xd5, - 0x16, 0x9e, 0x05, 0xfc, 0x89, 0x64, 0x50, 0x4d, 0x9a, 0x22, 0x50, 0xc6, - 0x5a, 0xd9, 0x58, 0x99, 0x8f, 0xbd, 0xf2, 0x4f, 0x2c, 0xdb, 0x51, 0x6a, - 0x86, 0xe2, 0xc6, 0x64, 0x8f, 0x54, 0x1a, 0xf2, 0xcb, 0x34, 0x88, 0x08, - 0xbd, 0x2a, 0x8f, 0xec, 0x29, 0xf5, 0x22, 0x36, 0x83, 0x99, 0xb9, 0x71, - 0x8c, 0x99, 0x5c, 0xec, 0x91, 0x78, 0xc1, 0xe2, 0x2d, 0xe9, 0xd1, 0x4d, - 0xf5, 0x15, 0x93, 0x4d, 0x93, 0x92, 0x9f, 0x0f, 0x33, 0x5e, 0xcd, 0x58, - 0x5f, 0x3d, 0x52, 0xb9, 0x38, 0x6a, 0x85, 0x63, 0x8b, 0x63, 0x29, 0xcb, - 0x67, 0x12, 0x25, 0xc2, 0x44, 0xd7, 0xab, 0x1a, 0x24, 0xca, 0x3d, 0xca, - 0x77, 0xce, 0x28, 0x68, 0x1a, 0x91, 0xed, 0x7b, 0xc9, 0x70, 0x84, 0xab, - 0xe2, 0xd4, 0xf4, 0xac, 0x58, 0xf6, 0x70, 0x99, 0xfc, 0x99, 0x4d, 0xbd, - 0xb4, 0x1b, 0x4f, 0x15, 0x86, 0x95, 0x08, 0xd1, 0x4e, 0x73, 0xa9, 0xbc, - 0x6a, 0x8c, 0xbc, 0xb5, 0x4b, 0xe0, 0xee, 0x35, 0x24, 0xf9, 0x12, 0xf5, - 0x88, 0x70, 0x50, 0x6c, 0xfe, 0x0d, 0x35, 0xbd, 0xf7, 0xc4, 0x2e, 0x39, - 0x16, 0x30, 0x6c, 0xf3, 0xb2, 0x19, 0x44, 0xaa, 0xcb, 0x4a, 0xf6, 0x75, - 0xb7, 0x09, 0xb9, 0xe1, 0x47, 0x71, 0x70, 0x5c, 0x05, 0x5f, 0x50, 0x50, - 0x9c, 0xd0, 0xe3, 0xc7, 0x91, 0xee, 0x6b, 0xc7, 0x0f, 0x71, 0x1b, 0xc3, - 0x48, 0x8b, 0xed, 0x15, 0x26, 0x8c, 0xc3, 0xd5, 0x54, 0x08, 0xcc, 0x33, - 0x79, 0xc0, 0x9f, 0x49, 0xc8, 0x75, 0xef, 0xb6, 0xf3, 0x29, 0x89, 0xfd, - 0x75, 0xd1, 0xda, 0x92, 0xc3, 0x13, 0xc6, 0x76, 0x51, 0x11, 0x40, 0x7b, - 0x82, 0xf7, 0x30, 0x79, 0x49, 0x04, 0xe3, 0xbb, 0x61, 0x34, 0xa6, 0x58, - 0x0b, 0x7d, 0xef, 0x3e, 0xf9, 0xb3, 0x8d, 0x2a, 0xba, 0xe9, 0xbc, 0xc0, - 0xa7, 0xe6, 0x6c, 0xda, 0xf8, 0x8c, 0xdf, 0x8d, 0x96, 0x83, 0x2d, 0x80, - 0x4f, 0x21, 0x81, 0xde, 0x57, 0x9d, 0x0a, 0x3c, 0xcc, 0xec, 0x3b, 0xb2, - 0x25, 0x96, 0x3c, 0xea, 0xfd, 0x46, 0x26, 0xbe, 0x1c, 0x79, 0x82, 0x1d, - 0xe0, 0x14, 0x22, 0x7c, 0x80, 0x3d, 0xbd, 0x05, 0x90, 0xfa, 0xaf, 0x7d, - 0x70, 0x13, 0x43, 0x0f, 0x3d, 0xa0, 0x7f, 0x92, 0x3a, 0x53, 0x69, 0xe4, - 0xb0, 0x10, 0x0d, 0xa7, 0x73, 0xa8, 0x8c, 0x74, 0xab, 0xd7, 0x78, 0x15, - 0x45, 0xec, 0x6e, 0xc8, 0x8b, 0xa0, 0xba, 0x21, 0x6f, 0xf3, 0x08, 0xb8, - 0xc7, 0x4f, 0x14, 0xf5, 0xcc, 0xfd, 0x39, 0xbc, 0x11, 0xf5, 0xb9, 0x11, - 0xba, 0xf3, 0x11, 0x24, 0x74, 0x3e, 0x0c, 0x07, 0x4f, 0xac, 0x2a, 0xb2, - 0xb1, 0x3c, 0x00, 0xfa, 0xbb, 0x8c, 0xd8, 0x7d, 0x17, 0x5b, 0x8d, 0x39, - 0xc6, 0x23, 0x31, 0x32, 0x7d, 0x6e, 0x20, 0x38, 0xd0, 0xc3, 0x58, 0xe2, - 0xb1, 0xfe, 0x53, 0x6b, 0xc7, 0x10, 0x13, 0x7e, 0xc6, 0x7c, 0x67, 0x59, - 0x43, 0x70, 0x4a, 0x2d, 0x7f, 0x76, 0xde, 0xbd, 0x45, 0x43, 0x56, 0x60, - 0xcd, 0xe9, 0x24, 0x7b, 0xb7, 0x41, 0xce, 0x56, 0xed, 0xd3, 0x74, 0x75, - 0xcc, 0x9d, 0x48, 0x61, 0xc8, 0x19, 0x66, 0x08, 0xfb, 0x28, 0x60, 0x1f, - 0x83, 0x11, 0xc0, 0x9b, 0xbd, 0x71, 0x53, 0x36, 0x01, 0x76, 0xa8, 0xc0, - 0xdc, 0x1d, 0x18, 0x85, 0x19, 0x65, 0xce, 0xcf, 0x14, 0x2e, 0x6c, 0x32, - 0x15, 0xbc, 0x2c, 0x5e, 0x8f, 0xfc, 0x3c, 0xf0, 0x2d, 0xf5, 0x5c, 0x04, - 0xc9, 0x22, 0xf4, 0xc3, 0xb8, 0x57, 0x79, 0x52, 0x41, 0xfd, 0xff, 0xcd, - 0x26, 0xa8, 0xc0, 0xd2, 0xe1, 0x71, 0xd6, 0xf1, 0xf4, 0x0c, 0xa8, 0xeb, - 0x0c, 0x33, 0x40, 0x25, 0x73, 0xbb, 0x31, 0xda, 0x0c, 0xa6, 0xee, 0x0c, - 0x41, 0x51, 0x94, 0x3c, 0x24, 0x27, 0x65, 0xe9, 0xb5, 0xc4, 0xe2, 0x88, - 0xc0, 0x82, 0xd0, 0x72, 0xd9, 0x10, 0x4d, 0x7f, 0xc0, 0x88, 0x94, 0x41, - 0x2d, 0x05, 0x09, 0xfb, 0x97, 0x31, 0x6e, 0xc1, 0xe9, 0xf4, 0x50, 0x70, - 0xdc, 0x3f, 0x0a, 0x90, 0x46, 0x37, 0x60, 0x8c, 0xfb, 0x06, 0x6e, 0xde, - 0x6f, 0xa7, 0x6b, 0xa3, 0x88, 0x18, 0x96, 0x93, 0x19, 0x87, 0xe7, 0x0a, - 0x98, 0xf0, 0x13, 0x01, 0xab, 0x7c, 0xeb, 0x25, 0xa5, 0xe2, 0x98, 0x44, - 0x7d, 0x09, 0xe2, 0x42, 0x33, 0xd4, 0xeb, 0xcc, 0x9b, 0x70, 0xf6, 0x0f, - 0xf0, 0xb2, 0x99, 0xcc, 0x4f, 0x64, 0xc4, 0x69, 0x12, 0xea, 0x56, 0xfe, - 0x50, 0x0e, 0x02, 0x1f, 0x6d, 0x7a, 0x79, 0x62, 0xaa, 0x2e, 0x52, 0xaf, - 0xa3, 0xed, 0xcd, 0xa7, 0x45, 0xe6, 0x86, 0xed, 0xa1, 0x73, 0x5b, 0x1e, - 0x49, 0x4f, 0x92, 0x50, 0x83, 0x99, 0x3c, 0xf4, 0xf6, 0xa8, 0x49, 0xd7, - 0x08, 0xf7, 0xdc, 0x28, 0x2c, 0xe6, 0x22, 0x6f, 0xf8, 0xfa, 0xba, 0x9e, - 0x0a, 0xcf, 0x72, 0x74, 0x76, 0x75, 0x99, 0x4d, 0x3d, 0x9a, 0x4c, 0x54, - 0xcd, 0xf8, 0x54, 0xf0, 0xbd, 0x73, 0xe9, 0x4f, 0x29, 0xd0, 0xe1, 0x24, - 0x94, 0x52, 0xd6, 0x60, 0x80, 0x71, 0x24, 0x95, 0x92, 0x01, 0x0e, 0xa9, - 0x7e, 0x64, 0x2e, 0xed, 0x51, 0xcc, 0xd2, 0xff, 0xfd, 0x0b, + 0xe0, 0xc0, 0x77, 0xeb, 0x7a, 0x48, 0x7d, 0x74, 0x4e, 0x4f, 0x6d, 0xb9, + 0x5c, 0x18, 0xe9, 0x5b, 0x47, 0x6c, 0x78, 0x9d, 0x98, 0x02, 0x84, 0x9f, + 0xf2, 0x45, 0x43, 0x86, 0x0e, 0xc6, 0x93, 0x48, 0xd8, 0x20, 0xff, 0x82, + 0x38, 0x9e, 0x78, 0xb4, 0x2c, 0xb3, 0x42, 0xe4, 0xb3, 0xab, 0xdf, 0xed, + 0x65, 0x24, 0x0c, 0xa5, 0x95, 0x2c, 0xbf, 0x4c, 0x28, 0xfc, 0xb8, 0xe7, + 0xc6, 0xbc, 0x76, 0xa0, 0xf5, 0x3f, 0x29, 0x73, 0x23, 0xf1, 0x6c, 0x10, + 0x7c, 0x08, 0x8e, 0x16, 0x3a, 0xda, 0x17, 0xa3, 0x0d, 0x46, 0x44, 0xee, + 0x6f, 0x70, 0xf1, 0x88, 0x51, 0x35, 0x33, 0x91, 0x76, 0xeb, 0x98, 0xc1, + 0x04, 0xdb, 0x97, 0xab, 0x88, 0xb9, 0x04, 0x87, 0xd9, 0xb8, 0x34, 0xd3, + 0x38, 0xe7, 0x90, 0x05, 0x2e, 0x45, 0xe0, 0xac, 0x36, 0x0c, 0x59, 0x58, + 0xb1, 0xf5, 0x65, 0x6d, 0x28, 0x1a, 0x39, 0xd9, 0xd2, 0x83, 0x17, 0xee, + 0xeb, 0x6f, 0x7d, 0x29, 0x3c, 0x79, 0xcf, 0x48, 0xf1, 0x6d, 0x35, 0xc2, + 0x8c, 0xe8, 0x67, 0x18, 0xcc, 0x9d, 0x9b, 0x8d, 0x07, 0x7a, 0x4e, 0x56, + 0xa8, 0x00, 0x2e, 0x67, 0x67, 0xbb, 0xc1, 0xda, 0x4a, 0x7b, 0x9f, 0xa6, + 0x4a, 0x5c, 0x40, 0xcc, 0xe4, 0xdd, 0xf5, 0xc0, 0x44, 0xfe, 0xa5, 0xa2, + 0x1c, 0xdc, 0xf2, 0x31, 0xf4, 0x01, 0x1f, 0x69, 0x15, 0x7e, 0x8c, 0x54, + 0xb6, 0x47, 0x0c, 0x1d, 0x9f, 0x1a, 0xfa, 0xf7, 0x46, 0xa3, 0xcb, 0x34, + 0x2c, 0x18, 0x45, 0x65, 0xc4, 0xf2, 0x0e, 0xf8, 0xc7, 0x96, 0x1d, 0x29, + 0x5c, 0x90, 0xd3, 0xdf, 0xb2, 0x8e, 0x21, 0xf9, 0x15, 0x40, 0x7e, 0xd3, + 0x84, 0x52, 0x1d, 0xd9, 0xee, 0xed, 0xe8, 0x71, 0x1c, 0xdb, 0x48, 0xf5, + 0x20, 0x82, 0xc4, 0x61, 0xfd, 0x6d, 0x71, 0x9f, 0xd8, 0x03, 0x90, 0x8e, + 0xfc, 0xed, 0x4d, 0xab, 0x6e, 0xb2, 0xe9, 0x66, 0xfd, 0xcc, 0x3a, 0xa3, + 0x99, 0x53, 0x35, 0x76, 0xea, 0x08, 0x88, 0xba, 0xf0, 0xb7, 0x53, 0xf3, + 0x4c, 0x1a, 0x8f, 0x7f, 0xe4, 0x1b, 0x8b, 0xfc, 0x99, 0x3e, 0x4c, 0xa9, + 0xd9, 0x17, 0x10, 0x64, 0x60, 0xfd, 0x81, 0x76, 0xe6, 0x37, 0xb0, 0xe3, + 0x3e, 0xc0, 0xf7, 0x06, 0x7e, 0x34, 0xa5, 0xf4, 0xb9, 0x5f, 0x66, 0xe6, + 0x81, 0xc8, 0x5e, 0xb2, 0x26, 0x6b, 0x8c, 0xad, 0xd0, 0x94, 0x01, 0x22, + 0xf6, 0xbe, 0x1a, 0x0b, 0x34, 0xfc, 0x33, 0xc0, 0x84, 0xa5, 0xe0, 0x12, + 0x8a, 0x08, 0xae, 0x8a, 0xaf, 0x55, 0x0c, 0x34, 0x4b, 0x2b, 0xdd, 0xa3, + 0x7c, 0xc0, 0xed, 0xe8, 0x8d, 0x98, 0x47, 0x7c, 0x81, 0x25, 0x1b, 0x9f, + 0x08, 0x26, 0x9d, 0xfc, 0x19, 0x8e, 0x39, 0xc4, 0x1a, 0x3c, 0x42, 0x70, + 0x49, 0x37, 0x57, 0x87, 0x0f, 0x76, 0xb1, 0xc4, 0xbe, 0x25, 0x5e, 0x1c, + 0x06, 0x57, 0xc6, 0x88, 0x34, 0x28, 0xdf, 0x60, 0x33, 0x09, 0xc5, 0xcc, + 0xf4, 0xc4, 0x33, 0x85, 0x8b, 0x48, 0xe8, 0x27, 0xb7, 0x72, 0x22, 0x44, + 0xff, 0xe7, 0x89, 0xf9, 0x71, 0x99, 0xed, 0x62, 0x47, 0xb0, 0x22, 0x9e, + 0xa6, 0x7c, 0xaf, 0xa9, 0x98, 0x2b, 0x5c, 0x8a, 0x42, 0x34, 0x77, 0xa3, + 0xc8, 0x13, 0x1e, 0xcf, 0x32, 0xa7, 0x70, 0xa8, 0xad, 0xc1, 0x66, 0x5c, + 0x8f, 0xaf, 0x14, 0x6d, 0xc4, 0x45, 0x05, 0xcd, 0xcb, 0x80, 0xfa, 0x0e, + 0xa6, 0xca, 0x72, 0x86, 0xd2, 0xb7, 0x39, 0x26, 0x77, 0xf8, 0x14, 0xd0, + 0xcd, 0xdd, 0xf7, 0xdc, 0xda, 0x25, 0x8e, 0x3c, 0x21, 0xfd, 0xef, 0x92, + 0xee, 0x52, 0xf7, 0xc3, 0xc7, 0xe2, 0x2d, 0x1c, 0x57, 0x5a, 0xba, 0xd8, + 0xaa, 0x0d, 0x09, 0xa7, 0xb3, 0xcc, 0xa1, 0x5d, 0xdb, 0x04, 0x21, 0x82, + 0xef, 0xba, 0xc2, 0xc8, 0x54, 0xb1, 0xbe, 0xd7, 0x2a, 0x91, 0xd8, 0xeb, + 0x72, 0x54, 0xc1, 0x74, 0x24, 0x24, 0x5a, 0x03, 0xf7, 0xcd, 0xab, 0x91, + 0xd1, 0x63, 0xf1, 0x60, 0x9f, 0x22, 0x07, 0xad, 0x10, 0x2b, 0x97, 0x1c, + 0x6f, 0xce, 0xc0, 0x29, 0xc2, 0xb2, 0xb8, 0x1b, 0xbd, 0x14, 0xc8, 0xb9, + 0x80, 0x66, 0xc1, 0x86, 0xfc, 0x93, 0x5f, 0x6e, 0x0b, 0x7a, 0x7b, 0x8e, + 0x42, 0x8c, 0x08, 0xd1, 0x60, 0xb9, 0xf8, 0x66, 0x24, 0x7d, 0x88, 0x58, + 0x2f, 0xd2, 0x52, 0x75, 0x3a, 0x8a, 0x1c, 0xfa, 0x1e, 0xa1, 0x1c, 0x91, + 0x46, 0x79, 0x9a, 0xe5, 0x8a, 0xdd, 0xc2, 0x75, 0xed, 0x0d, 0xb8, 0x2b, + 0x4f, 0x8f, 0x95, 0xca, 0xce, 0x21, 0xa4, 0x7a, 0x0d, 0x14, 0x7f, 0x2d, + 0x98, 0xf0, 0x88, 0xc3, 0x6f, 0xad, 0xb5, 0x04, 0x24, 0x91, 0x41, 0x65, + 0xd3, 0xa5, 0x7e, 0xfb, 0x53, 0x1c, 0xcc, 0xd0, 0xf7, 0x7c, 0x91, 0x08, + 0x0e, 0xdd, 0xd4, 0x6c, 0x73, 0xaa, 0xa5, 0x7a, 0xd2, 0x24, 0xc9, 0x3b, + 0x6f, 0xda, 0x06, 0x8a, 0xdb, 0x2e, 0xa8, 0xe9, 0xe1, 0x3e, 0x08, 0xee, + 0xbe, 0x96, 0x65, 0x72, 0x68, 0x6f, 0xf7, 0x50, 0xe7, 0xa7, 0x18, 0xda, + 0xc2, 0x94, 0xda, 0xe3, 0xbc, 0xca, 0x03, 0xd8, 0xf7, 0x7a, 0xcc, 0x44, + 0xa1, 0x60, 0xa8, 0x7f, 0xdc, 0xef, 0x80, 0xf4, 0x62, 0xc6, 0x06, 0x4e, + 0xb6, 0xac, 0x77, 0x17, 0xb7, 0xb3, 0x3e, 0xf8, 0x6d, 0x8a, 0x61, 0x83, + 0x3a, 0xfd, 0xbb, 0x93, 0x5b, 0x1a, 0x33, 0xf8, 0xee, 0x7d, 0x9e, 0x5c, + 0xf8, 0xc9, 0xd5, 0x3e, 0x3d, 0x42, 0x9b, 0xe5, 0x0d, 0xec, 0xc9, 0x0f, + 0x6f, 0x03, 0xb0, 0x41, 0x85, 0xb9, 0xfe, 0xf9, 0xb1, 0xb4, 0xc3, 0xd9, + 0x13, 0x03, 0xfa, 0x0d, 0xe7, 0xd1, 0xb4, 0xc8, 0xf6, 0xb5, 0x11, 0x7a, + 0x92, 0x09, 0x21, 0x7b, 0xa9, 0x89, 0x4c, 0x19, 0x90, 0x0d, 0x96, 0x32, + 0x4f, 0x77, 0xfc, 0x7f, 0x8c, 0xa3, 0x39, 0x2a, 0x56, 0xe6, 0x5c, 0xd1, + 0x86, 0x0a, 0x72, 0xf4, 0xa3, 0x1b, 0xa5, 0x30, 0x04, 0x3c, 0x15, 0x20, + 0x4b, 0xe4, 0x2d, 0x1a, 0xf1, 0x44, 0x48, 0xfc, 0xda, 0xc1, 0x41, 0xdb, + 0x71, 0xfd, 0x92, 0x00, 0x53, 0xe4, 0x70, 0xd0, 0xba, 0xf6, 0xef, 0x17, + 0x72, 0xb8, 0xea, 0x6d, 0x41, 0x16, 0x4d, 0x1f, 0x59, 0x18, 0xbd, 0x1f, + 0xc5, 0x6b, 0x6a, 0x6c, 0x2e, 0xa6, 0x1a, 0x33, 0x74, 0x8b, 0xc5, 0x9f, + 0x16, 0x01, 0x77, 0x7e, 0x37, 0xe7, 0x63, 0xe1, 0xa3, 0x8c, 0x1f, 0x71, + 0xe9, 0x4f, 0xad, 0x15, 0x8b, 0xf3, 0xc9, 0xac, 0xdc, 0x19, 0xad, 0x92, + 0x18, 0x00, 0xf6, 0xa1, 0xd5, 0x97, 0xa3, 0x3d, 0x9e, 0x78, 0x02, 0xc3, + 0x8f, 0x75, 0xd8, 0xad, 0x22, 0xbf, 0xef, 0x19, 0x5d, 0x15, 0x34, 0x1a, + 0x7c, 0x9b, 0xaf, 0xd4, 0xf2, 0xf9, 0x5f, 0x72, 0x88, 0x9c, 0xe4, 0x58, + 0xda, 0x46, 0x8f, 0x79, 0x30, 0x2b, 0xd9, 0x3b, 0xbc, 0xab, 0x28, 0x77, + 0x75, 0x0e, 0x2c, 0x23, 0x47, 0x95, 0x14, 0xeb, 0xf0, 0x4a, 0x3e, 0x53, + 0x93, 0xa7, 0xf4, 0x82, 0x9c, 0x34, 0x8b, 0x80, 0x42, 0xb2, 0xa7, 0xb0, + 0x7c, 0x6c, 0xe1, 0x07, 0xf4, 0x34, 0x3e, 0xed, 0x33, 0x9c, 0xb3, 0xde, + 0xa5, 0x91, 0x61, 0x25, 0x8e, 0x8c, 0x54, 0x56, 0xbe, 0x1a, 0xac, 0x17, + 0xd2, 0x7a, 0xa4, 0x12, 0x54, 0x2a, 0x51, 0xd0, 0x0e, 0xd1, 0xc1, 0x44, + 0x50, 0x05, 0x39, 0xa7, 0xb6, 0x14, 0x45, 0xca, 0xf8, 0x5f, 0x06, 0x6b, + 0x5d, 0x5e, 0xc7, 0xe9, 0x27, 0x6f, 0x38, 0xe0, 0x31, 0xcf, 0xf8, 0xcc, + 0x2e, 0xb9, 0x4a, 0x10, 0x1b, 0xb4, 0x34, 0x4b, 0x90, 0xbb, 0xf2, 0xe0, + 0x3c, 0x79, 0x7f, 0x39, 0x59, 0x0c, 0x01, 0x4c, 0x0d, 0x2d, 0x71, 0xf1, + 0xbd, 0xda, 0x1a, 0x78, 0xcf, 0x26, 0x6f, 0xb5, 0xa9, 0x07, 0x20, 0xe6, + 0x8c, 0xd0, 0xad, 0xd4, 0xca, 0x24, 0x6c, 0xc5, 0x28, 0x1d, 0xfb, 0xcc, + 0xe7, 0x93, 0x72, 0x99, 0x61, 0x63, 0x60, 0x4c, 0x5c, 0xa9, 0xb6, 0x15, + 0x32, 0xa4, 0xbc, 0x1f, 0xf6, 0x63, 0x61, 0x2c, 0x26, 0xa7, 0x0e, 0x5f, + 0x1b, 0x25, 0xce, 0x3f, 0x64, 0xdf, 0x6d, 0xb0, 0x8f, 0xd2, 0xe9, 0x3b, + 0x35, 0xd0, 0x59, 0x81, 0x22, 0xf1, 0x65, 0x86, 0x15, 0x10, 0xe8, 0xa7, + 0xa1, 0x6f, 0xb4, 0x34, 0x1c, 0x79, 0xd5, 0x9e, 0x8d, 0xc8, 0xa5, 0xbb, + 0x82, 0x71, 0x81, 0x00, 0x34, 0x55, 0x6b, 0x96, 0x56, 0x13, 0x0e, 0xe7, + 0x39, 0xa2, 0x6f, 0xbe, 0x54, 0x2a, 0x13, 0x03, 0x13, 0xd2, 0x1d, 0x71, + 0x9a, 0xbe, 0x09, 0x00, 0xe1, 0x8d, 0x59, 0xb5, 0x44, 0x02, }; EXPECT_EQ(Bytes(ciphertext), Bytes(kExpectedCiphertext)); static const uint8_t kExpectedSharedKey[HRSS_KEY_BYTES] = { - 0xbc, 0x98, 0x9c, 0x9c, 0x1f, 0x57, 0x6f, 0x38, 0x0b, 0x5d, 0xc2, - 0x23, 0x7d, 0x01, 0xae, 0x63, 0x17, 0xe8, 0xe4, 0xb2, 0x02, 0xa7, - 0xc4, 0x3a, 0x1b, 0x5a, 0xf3, 0xf8, 0xb5, 0xea, 0x6e, 0x22, + 0x57, 0xf2, 0x77, 0xb2, 0xf3, 0x7f, 0xd0, 0x71, 0xb6, 0x7e, 0x64, + 0x0f, 0x85, 0x1f, 0x6d, 0x3b, 0xd1, 0x7a, 0x6e, 0x01, 0x04, 0xde, + 0x0f, 0x9e, 0x03, 0x95, 0x55, 0x60, 0xce, 0xda, 0x32, 0x71, }; EXPECT_EQ(Bytes(shared_key), Bytes(kExpectedSharedKey)); @@ -473,9 +473,9 @@ TEST(HRSS, Golden) { HRSS_decap(shared_key, &priv, ciphertext, sizeof(ciphertext)); static const uint8_t kExpectedFailureKey[HRSS_KEY_BYTES] = { - 0x8e, 0x19, 0xfe, 0x2b, 0x12, 0x67, 0xef, 0x9a, 0x63, 0x4d, 0x79, - 0x33, 0x8c, 0xce, 0xbf, 0x03, 0xdb, 0x9c, 0xc4, 0xc1, 0x70, 0xe1, - 0x32, 0xa6, 0xb3, 0xd3, 0xa1, 0x43, 0x3c, 0xf1, 0x1f, 0x5a, + 0x13, 0xf7, 0xed, 0x51, 0x00, 0xbc, 0xca, 0x29, 0xdf, 0xb0, 0xd0, + 0x5e, 0xa1, 0x9d, 0x15, 0xb2, 0xf6, 0x23, 0x94, 0xfd, 0x93, 0x74, + 0x14, 0x46, 0x85, 0x61, 0x8b, 0x87, 0x30, 0xd3, 0x8d, 0xad, }; EXPECT_EQ(Bytes(shared_key), Bytes(kExpectedFailureKey)); } diff --git a/third_party/boringssl/kit/src/crypto/impl_dispatch_test.cc b/third_party/boringssl/kit/src/crypto/impl_dispatch_test.cc new file mode 100644 index 00000000..54ee704c --- /dev/null +++ b/third_party/boringssl/kit/src/crypto/impl_dispatch_test.cc @@ -0,0 +1,151 @@ +/* Copyright (c) 2018, Google Inc. + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ + +#include + +#if !defined(NDEBUG) && !defined(BORINGSSL_FIPS) && \ + !defined(BORINGSSL_SHARED_LIBRARY) + +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include "internal.h" + + +class ImplDispatchTest : public ::testing::Test { + public: + void SetUp() override { +#if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) + aesni_ = OPENSSL_ia32cap_P[1] & (1 << (57 - 32)); + avx_movbe_ = ((OPENSSL_ia32cap_P[1] >> 22) & 0x41) == 0x41; + ssse3_ = OPENSSL_ia32cap_P[1] & (1 << (41 - 32)); + is_x86_64_ = +#if defined(OPENSSL_X86_64) + true; +#else + false; +#endif +#endif // X86 || X86_64 + } + + protected: + // AssertFunctionsHit takes a list of pairs (flag index, boolean), and a + // function to test. It runs the given function and asserts, for each flag + // index, that the boolean reflects whether that flag index was written or + // not, and that no other flagged functions were triggered. + void AssertFunctionsHit(std::vector> flags, + std::function f) { + OPENSSL_memset(BORINGSSL_function_hit, 0, sizeof(BORINGSSL_function_hit)); + + f(); + + for (const auto flag : flags) { + SCOPED_TRACE(flag.first); + + ASSERT_LT(flag.first, sizeof(BORINGSSL_function_hit)); + EXPECT_EQ(flag.second, BORINGSSL_function_hit[flag.first] == 1); + BORINGSSL_function_hit[flag.first] = 0; + } + + for (size_t i = 0; i < sizeof(BORINGSSL_function_hit); i++) { + EXPECT_EQ(0u, BORINGSSL_function_hit[i]) + << "Flag " << i << " unexpectedly hit"; + } + } + +#if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) + bool aesni_ = false; + bool avx_movbe_ = false; + bool ssse3_ = false; + bool is_x86_64_ = false; +#endif +}; + +#if !defined(OPENSSL_NO_ASM) && \ + (defined(OPENSSL_X86) || defined(OPENSSL_X86_64)) + +constexpr size_t kFlag_aes_hw_ctr32_encrypt_blocks = 0; +constexpr size_t kFlag_aes_hw_encrypt = 1; +constexpr size_t kFlag_aesni_gcm_encrypt = 2; +constexpr size_t kFlag_aes_hw_set_encrypt_key = 3; +constexpr size_t kFlag_vpaes_encrypt = 4; +constexpr size_t kFlag_vpaes_set_encrypt_key = 5; + +TEST_F(ImplDispatchTest, AEAD_AES_GCM) { + AssertFunctionsHit( + { + {kFlag_aes_hw_ctr32_encrypt_blocks, aesni_}, + {kFlag_aes_hw_encrypt, aesni_}, + {kFlag_aes_hw_set_encrypt_key, aesni_}, + {kFlag_aesni_gcm_encrypt, is_x86_64_ && aesni_ && avx_movbe_}, + {kFlag_vpaes_encrypt, ssse3_ && !aesni_}, + {kFlag_vpaes_set_encrypt_key, ssse3_ && !aesni_}, + }, + [] { + const uint8_t kZeros[16] = {0}; + const uint8_t kPlaintext[40] = {1, 2, 3, 4, 0}; + uint8_t ciphertext[sizeof(kPlaintext) + 16]; + size_t ciphertext_len; + EVP_AEAD_CTX ctx; + ASSERT_TRUE(EVP_AEAD_CTX_init(&ctx, EVP_aead_aes_128_gcm(), kZeros, + sizeof(kZeros), + EVP_AEAD_DEFAULT_TAG_LENGTH, nullptr)); + ASSERT_TRUE(EVP_AEAD_CTX_seal( + &ctx, ciphertext, &ciphertext_len, sizeof(ciphertext), kZeros, + EVP_AEAD_nonce_length(EVP_aead_aes_128_gcm()), kPlaintext, + sizeof(kPlaintext), nullptr, 0)); + }); +} + +TEST_F(ImplDispatchTest, AES_set_encrypt_key) { + AssertFunctionsHit( + { + {kFlag_aes_hw_set_encrypt_key, aesni_}, + {kFlag_vpaes_set_encrypt_key, ssse3_ && !aesni_}, + }, + [] { + AES_KEY key; + static const uint8_t kZeros[16] = {0}; + AES_set_encrypt_key(kZeros, sizeof(kZeros) * 8, &key); + }); +} + +TEST_F(ImplDispatchTest, AES_single_block) { + AES_KEY key; + static const uint8_t kZeros[16] = {0}; + AES_set_encrypt_key(kZeros, sizeof(kZeros) * 8, &key); + + AssertFunctionsHit( + { + {kFlag_aes_hw_encrypt, aesni_}, + {kFlag_vpaes_encrypt, ssse3_ && !aesni_}, + }, + [&key] { + uint8_t in[AES_BLOCK_SIZE] = {0}; + uint8_t out[AES_BLOCK_SIZE]; + AES_encrypt(in, out, &key); + }); +} + +#endif // X86 || X86_64 + +#endif // !NDEBUG && !FIPS && !SHARED_LIBRARY diff --git a/third_party/boringssl/kit/src/crypto/mem.c b/third_party/boringssl/kit/src/crypto/mem.c index a06061b4..0ca0e84f 100644 --- a/third_party/boringssl/kit/src/crypto/mem.c +++ b/third_party/boringssl/kit/src/crypto/mem.c @@ -71,7 +71,18 @@ OPENSSL_MSVC_PRAGMA(warning(pop)) #define OPENSSL_MALLOC_PREFIX 8 -#if defined(__GNUC__) || defined(__clang__) +#if defined(OPENSSL_ASAN) +void __asan_poison_memory_region(const volatile void *addr, size_t size); +void __asan_unpoison_memory_region(const volatile void *addr, size_t size); +#else +static void __asan_poison_memory_region(const void *addr, size_t size) {} +static void __asan_unpoison_memory_region(const void *addr, size_t size) {} +#endif + +// Windows doesn't really support weak symbols as of May 2019, and Clang on +// Windows will emit strong symbols instead. See +// https://bugs.llvm.org/show_bug.cgi?id=37598 +#if defined(__GNUC__) || (defined(__clang__) && !defined(_MSC_VER)) // sdallocx is a sized |free| function. By passing the size (which we happen to // always know in BoringSSL), the malloc implementation can save work. We cannot // depend on |sdallocx| being available so we declare a wrapper that falls back @@ -99,6 +110,7 @@ void *OPENSSL_malloc(size_t size) { *(size_t *)ptr = size; + __asan_poison_memory_region(ptr, OPENSSL_MALLOC_PREFIX); return ((uint8_t *)ptr) + OPENSSL_MALLOC_PREFIX; } @@ -108,6 +120,7 @@ void OPENSSL_free(void *orig_ptr) { } void *ptr = ((uint8_t *)orig_ptr) - OPENSSL_MALLOC_PREFIX; + __asan_unpoison_memory_region(ptr, OPENSSL_MALLOC_PREFIX); size_t size = *(size_t *)ptr; OPENSSL_cleanse(ptr, size + OPENSSL_MALLOC_PREFIX); @@ -120,7 +133,9 @@ void *OPENSSL_realloc(void *orig_ptr, size_t new_size) { } void *ptr = ((uint8_t *)orig_ptr) - OPENSSL_MALLOC_PREFIX; + __asan_unpoison_memory_region(ptr, OPENSSL_MALLOC_PREFIX); size_t old_size = *(size_t *)ptr; + __asan_poison_memory_region(ptr, OPENSSL_MALLOC_PREFIX); void *ret = OPENSSL_malloc(new_size); if (ret == NULL) { @@ -153,6 +168,10 @@ void OPENSSL_cleanse(void *ptr, size_t len) { #endif // !OPENSSL_NO_ASM } +void OPENSSL_clear_free(void *ptr, size_t unused) { + OPENSSL_free(ptr); +} + int CRYPTO_memcmp(const void *in_a, const void *in_b, size_t len) { const uint8_t *a = in_a; const uint8_t *b = in_b; diff --git a/third_party/boringssl/kit/src/crypto/obj/obj_dat.h b/third_party/boringssl/kit/src/crypto/obj/obj_dat.h index 0313a08a..1a9bf158 100644 --- a/third_party/boringssl/kit/src/crypto/obj/obj_dat.h +++ b/third_party/boringssl/kit/src/crypto/obj/obj_dat.h @@ -57,7 +57,7 @@ /* This file is generated by crypto/obj/objects.go. */ -#define NUM_NID 960 +#define NUM_NID 961 static const uint8_t kObjectData[] = { /* NID_rsadsi */ @@ -8756,6 +8756,7 @@ static const ASN1_OBJECT kObjects[NUM_NID] = { {"KxANY", "kx-any", NID_kx_any, 0, NULL, 0}, {"AuthANY", "auth-any", NID_auth_any, 0, NULL, 0}, {"CECPQ2", "CECPQ2", NID_CECPQ2, 0, NULL, 0}, + {"CECPQ2b", "CECPQ2b", NID_CECPQ2b, 0, NULL, 0}, }; static const unsigned kNIDsInShortNameOrder[] = { @@ -8818,6 +8819,7 @@ static const unsigned kNIDsInShortNameOrder[] = { 109 /* CAST5-ECB */, 111 /* CAST5-OFB */, 959 /* CECPQ2 */, + 960 /* CECPQ2b */, 894 /* CMAC */, 13 /* CN */, 141 /* CRLReason */, @@ -9723,6 +9725,7 @@ static const unsigned kNIDsInLongNameOrder[] = { 179 /* CA Issuers */, 785 /* CA Repository */, 959 /* CECPQ2 */, + 960 /* CECPQ2b */, 131 /* Code Signing */, 783 /* Diffie-Hellman based MAC */, 382 /* Directory */, diff --git a/third_party/boringssl/kit/src/crypto/obj/obj_mac.num b/third_party/boringssl/kit/src/crypto/obj/obj_mac.num index 5fa839d2..f2d4e8ca 100644 --- a/third_party/boringssl/kit/src/crypto/obj/obj_mac.num +++ b/third_party/boringssl/kit/src/crypto/obj/obj_mac.num @@ -948,3 +948,4 @@ auth_psk 956 kx_any 957 auth_any 958 CECPQ2 959 +CECPQ2b 960 diff --git a/third_party/boringssl/kit/src/crypto/obj/objects.txt b/third_party/boringssl/kit/src/crypto/obj/objects.txt index 6dbb7ad7..6e7ecf07 100644 --- a/third_party/boringssl/kit/src/crypto/obj/objects.txt +++ b/third_party/boringssl/kit/src/crypto/obj/objects.txt @@ -1337,6 +1337,9 @@ secg-scheme 14 3 : dhSinglePass-cofactorDH-sha512kdf-scheme # NID for CECPQ2 (no corresponding OID). : CECPQ2 +# NID for CECPQ2 (no corresponding OID). + : CECPQ2b + # See RFC 8410. 1 3 101 112 : ED25519 diff --git a/third_party/boringssl/kit/src/crypto/perlasm/arm-xlate.pl b/third_party/boringssl/kit/src/crypto/perlasm/arm-xlate.pl index eb8ea59b..655be61b 100755 --- a/third_party/boringssl/kit/src/crypto/perlasm/arm-xlate.pl +++ b/third_party/boringssl/kit/src/crypto/perlasm/arm-xlate.pl @@ -168,6 +168,15 @@ while(my $line=<>) { $line =~ s|^\s+||; # ... and skip white spaces in beginning... $line =~ s|\s+$||; # ... and at the end + if ($flavour =~ /64/) { + my $copy = $line; + # Also remove line comments. + $copy =~ s|//.*||; + if ($copy =~ /\b[wx]18\b/) { + die "r18 is reserved by the platform and may not be used."; + } + } + { $line =~ s|[\b\.]L(\w{2,})|L$1|g; # common denominator for Locallabel $line =~ s|\bL(\w{2,})|\.L$1|g if ($dotinlocallabels); diff --git a/third_party/boringssl/kit/src/crypto/perlasm/x86_64-xlate.pl b/third_party/boringssl/kit/src/crypto/perlasm/x86_64-xlate.pl index 213093da..f9284115 100755 --- a/third_party/boringssl/kit/src/crypto/perlasm/x86_64-xlate.pl +++ b/third_party/boringssl/kit/src/crypto/perlasm/x86_64-xlate.pl @@ -732,7 +732,7 @@ my %globals; $$line = $globals{$$line} if ($prefix); last; }; - /\.type/ && do { my ($sym,$type,$narg) = split(',',$$line); + /\.type/ && do { my ($sym,$type,$narg) = split(/\s*,\s*/,$$line); if ($type eq "\@function") { undef $current_function; $current_function->{name} = $sym; @@ -894,7 +894,7 @@ my %globals; $var=~s/^(0b[0-1]+)/oct($1)/eig; $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm); if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva")) - { $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; } + { $var=~s/^([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; } $var; }; @@ -1181,7 +1181,20 @@ while(defined(my $line=<>)) { $line =~ s|\R$||; # Better chomp - $line =~ s|[#!].*$||; # get rid of asm-style comments... + if ($nasm) { + $line =~ s|^#ifdef |%ifdef |; + $line =~ s|^#ifndef |%ifndef |; + $line =~ s|^#endif|%endif|; + $line =~ s|[#!].*$||; # get rid of asm-style comments... + } else { + # Get rid of asm-style comments but not preprocessor directives. The + # former are identified by having a letter after the '#' and starting in + # the first column. + $line =~ s|!.*$||; + $line =~ s|(?<=.)#.*$||; + $line =~ s|^#([^a-z].*)?$||; + } + $line =~ s|/\*.*\*/||; # ... and C-style comments... $line =~ s|^\s+||; # ... and skip white spaces in beginning $line =~ s|\s+$||; # ... and at the end diff --git a/third_party/boringssl/kit/src/crypto/perlasm/x86asm.pl b/third_party/boringssl/kit/src/crypto/perlasm/x86asm.pl index 3d2943bc..3278188a 100644 --- a/third_party/boringssl/kit/src/crypto/perlasm/x86asm.pl +++ b/third_party/boringssl/kit/src/crypto/perlasm/x86asm.pl @@ -33,6 +33,26 @@ sub ::AUTOLOAD &generic($opcode,@_) or die "undefined subroutine \&$AUTOLOAD"; } +# record_function_hit(int) writes a byte with value one to the given offset of +# |BORINGSSL_function_hit|, but only if NDEBUG is not defined. This is used in +# impl_dispatch_test.cc to test whether the expected assembly functions are +# triggered by high-level API calls. +sub ::record_function_hit +{ my($index)=@_; + &preprocessor_ifndef("NDEBUG"); + &push("ebx"); + &push("edx"); + &call(&label("pic")); + &set_label("pic"); + &blindpop("ebx"); + &lea("ebx",&DWP("BORINGSSL_function_hit+$index"."-".&label("pic"),"ebx")); + &mov("edx", 1); + &movb(&BP(0, "ebx"), "dl"); + &pop("edx"); + &pop("ebx"); + &preprocessor_endif(); +} + sub ::emit { my $opcode=shift; diff --git a/third_party/boringssl/kit/src/crypto/perlasm/x86gas.pl b/third_party/boringssl/kit/src/crypto/perlasm/x86gas.pl index 0c989a14..4e19a899 100644 --- a/third_party/boringssl/kit/src/crypto/perlasm/x86gas.pl +++ b/third_party/boringssl/kit/src/crypto/perlasm/x86gas.pl @@ -265,6 +265,14 @@ ___ sub ::dataseg { push(@out,".data\n"); } +sub ::preprocessor_ifndef +{ my($define)=@_; + push(@out,"#ifndef ${define}\n"); +} + +sub ::preprocessor_endif +{ push(@out,"#endif\n"); } + *::hidden = sub { push(@out,".hidden\t$nmdecor$_[0]\n"); } if ($::elf); 1; diff --git a/third_party/boringssl/kit/src/crypto/perlasm/x86masm.pl b/third_party/boringssl/kit/src/crypto/perlasm/x86masm.pl index dffee762..01bfbf34 100644 --- a/third_party/boringssl/kit/src/crypto/perlasm/x86masm.pl +++ b/third_party/boringssl/kit/src/crypto/perlasm/x86masm.pl @@ -203,4 +203,12 @@ sub ::safeseh push(@out,"ENDIF\n"); } +sub ::preprocessor_ifndef +{ my($define)=@_; + push(@out,"%ifndef ${define}\n"); +} + +sub ::preprocessor_endif +{ push(@out,"%endif\n"); } + 1; diff --git a/third_party/boringssl/kit/src/crypto/perlasm/x86nasm.pl b/third_party/boringssl/kit/src/crypto/perlasm/x86nasm.pl index d3773b68..a3e0ab72 100644 --- a/third_party/boringssl/kit/src/crypto/perlasm/x86nasm.pl +++ b/third_party/boringssl/kit/src/crypto/perlasm/x86nasm.pl @@ -191,4 +191,12 @@ sub ::safeseh push(@out,"%endif\n"); } +sub ::preprocessor_ifndef +{ my($define)=@_; + push(@out,"%ifndef ${define}\n"); +} + +sub ::preprocessor_endif +{ push(@out,"%endif\n"); } + 1; diff --git a/third_party/boringssl/kit/src/crypto/pkcs8/p5_pbev2.c b/third_party/boringssl/kit/src/crypto/pkcs8/p5_pbev2.c index 7497b000..e58cf444 100644 --- a/third_party/boringssl/kit/src/crypto/pkcs8/p5_pbev2.c +++ b/third_party/boringssl/kit/src/crypto/pkcs8/p5_pbev2.c @@ -81,6 +81,10 @@ static const uint8_t kPBES2[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, static const uint8_t kHMACWithSHA1[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x07}; +// 1.2.840.113549.2.9 +static const uint8_t kHMACWithSHA256[] = {0x2a, 0x86, 0x48, 0x86, + 0xf7, 0x0d, 0x02, 0x09}; + static const struct { uint8_t oid[9]; uint8_t oid_len; @@ -140,18 +144,18 @@ static int add_cipher_oid(CBB *out, int nid) { } static int pkcs5_pbe2_cipher_init(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, - unsigned iterations, const char *pass, - size_t pass_len, const uint8_t *salt, - size_t salt_len, const uint8_t *iv, - size_t iv_len, int enc) { + const EVP_MD *pbkdf2_md, unsigned iterations, + const char *pass, size_t pass_len, + const uint8_t *salt, size_t salt_len, + const uint8_t *iv, size_t iv_len, int enc) { if (iv_len != EVP_CIPHER_iv_length(cipher)) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_ERROR_SETTING_CIPHER_PARAMS); return 0; } uint8_t key[EVP_MAX_KEY_LENGTH]; - int ret = PKCS5_PBKDF2_HMAC_SHA1(pass, pass_len, salt, salt_len, iterations, - EVP_CIPHER_key_length(cipher), key) && + int ret = PKCS5_PBKDF2_HMAC(pass, pass_len, salt, salt_len, iterations, + pbkdf2_md, EVP_CIPHER_key_length(cipher), key) && EVP_CipherInit_ex(ctx, cipher, NULL /* engine */, key, iv, enc); OPENSSL_cleanse(key, EVP_MAX_KEY_LENGTH); return ret; @@ -201,9 +205,9 @@ int PKCS5_pbe2_encrypt_init(CBB *out, EVP_CIPHER_CTX *ctx, return 0; } - return pkcs5_pbe2_cipher_init(ctx, cipher, iterations, pass, pass_len, salt, - salt_len, iv, EVP_CIPHER_iv_length(cipher), - 1 /* encrypt */); + return pkcs5_pbe2_cipher_init(ctx, cipher, EVP_sha1(), iterations, pass, + pass_len, salt, salt_len, iv, + EVP_CIPHER_iv_length(cipher), 1 /* encrypt */); } int PKCS5_pbe2_decrypt_init(const struct pbe_suite *suite, EVP_CIPHER_CTX *ctx, @@ -264,6 +268,7 @@ int PKCS5_pbe2_decrypt_init(const struct pbe_suite *suite, EVP_CIPHER_CTX *ctx, } } + const EVP_MD *md = EVP_sha1(); if (CBS_len(&pbkdf2_params) != 0) { CBS alg_id, prf; if (!CBS_get_asn1(&pbkdf2_params, &alg_id, CBS_ASN1_SEQUENCE) || @@ -273,14 +278,18 @@ int PKCS5_pbe2_decrypt_init(const struct pbe_suite *suite, EVP_CIPHER_CTX *ctx, return 0; } - // We only support hmacWithSHA1. It is the DEFAULT, so DER requires it be - // omitted, but we match OpenSSL in tolerating it being present. - if (!CBS_mem_equal(&prf, kHMACWithSHA1, sizeof(kHMACWithSHA1))) { + if (CBS_mem_equal(&prf, kHMACWithSHA1, sizeof(kHMACWithSHA1))) { + // hmacWithSHA1 is the DEFAULT, so DER requires it be omitted, but we + // match OpenSSL in tolerating it being present. + md = EVP_sha1(); + } else if (CBS_mem_equal(&prf, kHMACWithSHA256, sizeof(kHMACWithSHA256))) { + md = EVP_sha256(); + } else { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNSUPPORTED_PRF); return 0; } - // hmacWithSHA1 has a NULL parameter. + // All supported PRFs use a NULL parameter. CBS null; if (!CBS_get_asn1(&alg_id, &null, CBS_ASN1_NULL) || CBS_len(&null) != 0 || @@ -301,7 +310,7 @@ int PKCS5_pbe2_decrypt_init(const struct pbe_suite *suite, EVP_CIPHER_CTX *ctx, return 0; } - return pkcs5_pbe2_cipher_init(ctx, cipher, (unsigned)iterations, pass, + return pkcs5_pbe2_cipher_init(ctx, cipher, md, (unsigned)iterations, pass, pass_len, CBS_data(&salt), CBS_len(&salt), CBS_data(&iv), CBS_len(&iv), 0 /* decrypt */); } diff --git a/third_party/boringssl/kit/src/crypto/pkcs8/pkcs12_test.cc b/third_party/boringssl/kit/src/crypto/pkcs8/pkcs12_test.cc index e6c0e56b..d345006e 100644 --- a/third_party/boringssl/kit/src/crypto/pkcs8/pkcs12_test.cc +++ b/third_party/boringssl/kit/src/crypto/pkcs8/pkcs12_test.cc @@ -683,9 +683,12 @@ static const uint8_t kWindows[] = { 0xfe, 0x3a, 0x66, 0x47, 0x40, 0x49, 0x02, 0x02, 0x07, 0xd0, }; -// kPBES2 is a PKCS#12 file using PBES2 created with: +// kPBES2WithSHA1 is a PKCS#12 file using PBES2 and HMAC-SHA-1 created with: // openssl pkcs12 -export -inkey key.pem -in cert.pem -keypbe AES-128-CBC -certpbe AES-128-CBC -static const uint8_t kPBES2[] = { +// +// This was generated with an older OpenSSL, which used hmacWithSHA1 as the PRF. +// (There is currently no way to specify the PRF in the pkcs12 command.) +static const uint8_t kPBES2WithSHA1[] = { 0x30, 0x82, 0x0a, 0x03, 0x02, 0x01, 0x03, 0x30, 0x82, 0x09, 0xc9, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0xa0, 0x82, 0x09, 0xba, 0x04, 0x82, 0x09, 0xb6, 0x30, 0x82, 0x09, 0xb2, 0x30, 0x82, @@ -901,6 +904,318 @@ static const uint8_t kPBES2[] = { 0xc3, 0x8c, 0xc6, 0x69, 0xdc, 0xc6, 0x7f, 0x54, 0xef, 0x04, 0x08, 0xf8, 0x9c, 0x8b, 0x12, 0x27, 0xe8, 0xec, 0x65, 0x02, 0x02, 0x08, 0x00}; +// kPBES2WithSHA256 is a PKCS#12 file using PBES2 and HMAC-SHA-256. It was +// generated in the same way as |kPBES2WithSHA1|, but using OpenSSL 1.1.1b, +// which uses hmacWithSHA256 as the PRF. +static const uint8_t kPBES2WithSHA256[] = { + 0x30, 0x82, 0x0a, 0x7f, 0x02, 0x01, 0x03, 0x30, 0x82, 0x0a, 0x45, 0x06, + 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0xa0, 0x82, + 0x0a, 0x36, 0x04, 0x82, 0x0a, 0x32, 0x30, 0x82, 0x0a, 0x2e, 0x30, 0x82, + 0x04, 0xa2, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, + 0x06, 0xa0, 0x82, 0x04, 0x93, 0x30, 0x82, 0x04, 0x8f, 0x02, 0x01, 0x00, + 0x30, 0x82, 0x04, 0x88, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, + 0x01, 0x07, 0x01, 0x30, 0x57, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, + 0x0d, 0x01, 0x05, 0x0d, 0x30, 0x4a, 0x30, 0x29, 0x06, 0x09, 0x2a, 0x86, + 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x05, 0x0c, 0x30, 0x1c, 0x04, 0x08, 0xb2, + 0x5e, 0x0d, 0x6d, 0xda, 0xaa, 0x2f, 0xbe, 0x02, 0x02, 0x08, 0x00, 0x30, + 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x09, 0x05, + 0x00, 0x30, 0x1d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, + 0x01, 0x02, 0x04, 0x10, 0x3c, 0x04, 0x78, 0x37, 0xb3, 0xb2, 0x24, 0xd3, + 0xb5, 0x46, 0x20, 0xb7, 0xd2, 0xdd, 0x5d, 0x2e, 0x80, 0x82, 0x04, 0x20, + 0x3a, 0x01, 0xe4, 0xf4, 0x57, 0xd3, 0xed, 0x14, 0xd0, 0x42, 0x3f, 0xd3, + 0x61, 0xee, 0x84, 0xcd, 0x2b, 0x08, 0x60, 0x30, 0xbd, 0x72, 0xa7, 0xd5, + 0xa4, 0xf2, 0x13, 0xe9, 0xf0, 0x44, 0x66, 0x26, 0x34, 0xe7, 0x2c, 0x5d, + 0xc9, 0xb0, 0x4b, 0xab, 0x47, 0x16, 0xab, 0xe6, 0x06, 0xa6, 0x3b, 0x79, + 0x41, 0x0c, 0x79, 0xd5, 0x9b, 0x02, 0x67, 0xd8, 0x7f, 0xc8, 0x36, 0x37, + 0x27, 0xb4, 0x44, 0xa2, 0x5e, 0x0d, 0x38, 0xb8, 0x41, 0x8e, 0x3a, 0xf1, + 0xe9, 0xab, 0xe0, 0x19, 0xd0, 0xe1, 0xc7, 0x92, 0xd4, 0x5b, 0x35, 0xf3, + 0x79, 0x48, 0x3b, 0xfc, 0x25, 0xfc, 0xc6, 0x9f, 0xed, 0x35, 0x28, 0x5b, + 0xfa, 0xee, 0x50, 0x42, 0xa3, 0xc3, 0x96, 0xee, 0xe0, 0x87, 0x33, 0x5e, + 0xa7, 0xc7, 0x0a, 0xfe, 0xda, 0xe5, 0xd5, 0x29, 0x6a, 0x57, 0x08, 0x7f, + 0x56, 0x37, 0x2a, 0x1a, 0xa0, 0x6d, 0xe9, 0x84, 0xac, 0xed, 0x0e, 0xd8, + 0xc0, 0xd8, 0xc6, 0x77, 0xb1, 0xdd, 0x1b, 0xa1, 0xed, 0xa7, 0x79, 0x13, + 0x2e, 0x5b, 0x9b, 0x80, 0x44, 0x9e, 0xff, 0x0a, 0x6e, 0x99, 0x33, 0xcf, + 0xf1, 0x47, 0x24, 0xaa, 0x48, 0xe7, 0x2c, 0xb3, 0xe6, 0xdc, 0xd4, 0x1e, + 0xe4, 0xb8, 0x5e, 0x72, 0xaf, 0x3f, 0xd3, 0x25, 0x4a, 0xac, 0x7b, 0x35, + 0xb1, 0x82, 0xa5, 0xd9, 0xf8, 0x01, 0x12, 0x92, 0x49, 0x4c, 0x17, 0x07, + 0xb2, 0xb1, 0x3e, 0xcb, 0xfd, 0xd1, 0x17, 0xb5, 0x65, 0x3d, 0x0c, 0x2b, + 0x2b, 0xc0, 0x37, 0x9c, 0xe7, 0x04, 0x9b, 0x71, 0x5a, 0x10, 0xc0, 0xba, + 0x3b, 0x31, 0xde, 0x0d, 0x66, 0x6c, 0x0d, 0x4c, 0x99, 0x22, 0x76, 0x2a, + 0x75, 0x7f, 0x84, 0xd1, 0x07, 0x1f, 0x57, 0xf0, 0x0b, 0x71, 0x41, 0xea, + 0x38, 0xe2, 0xe7, 0xbe, 0x11, 0x3c, 0x92, 0x8c, 0x7b, 0x0e, 0xb4, 0x7e, + 0x76, 0xc4, 0x80, 0x41, 0xae, 0x4c, 0xe2, 0x38, 0x36, 0xcb, 0x82, 0x39, + 0x38, 0x3a, 0x55, 0xb4, 0xe2, 0x35, 0x94, 0xc3, 0xae, 0x3d, 0xd1, 0x03, + 0xf3, 0xdb, 0x00, 0xd9, 0xfa, 0x96, 0x62, 0x25, 0x97, 0x51, 0xc5, 0xcf, + 0x84, 0xe8, 0xf7, 0x8b, 0x2f, 0x31, 0xeb, 0xa7, 0x0a, 0x22, 0x6f, 0xad, + 0xf5, 0x28, 0x25, 0xaa, 0x99, 0x0e, 0xb1, 0x83, 0x9f, 0x70, 0x79, 0xaf, + 0x10, 0x7c, 0x2c, 0x55, 0xfe, 0x24, 0x7d, 0xea, 0x85, 0x48, 0x8e, 0x7a, + 0xf7, 0x47, 0xd8, 0x0c, 0x64, 0x97, 0xe0, 0x8f, 0x62, 0x5e, 0xd0, 0x4f, + 0x21, 0xa4, 0x46, 0x8e, 0x28, 0xb0, 0xb1, 0x90, 0xec, 0x01, 0x7d, 0xc4, + 0xc8, 0x6f, 0xf2, 0xe2, 0xb7, 0xc4, 0x35, 0x6c, 0xa9, 0xf6, 0xaf, 0xc2, + 0xb6, 0xa9, 0x02, 0x6d, 0xb2, 0x8b, 0x43, 0x6b, 0x41, 0x80, 0x9d, 0x5e, + 0x51, 0xa7, 0x31, 0x00, 0x1b, 0xb5, 0x24, 0xed, 0x40, 0x99, 0x33, 0xde, + 0x87, 0xd1, 0x4b, 0x76, 0x78, 0x57, 0x4c, 0x33, 0x79, 0x89, 0xd3, 0xfa, + 0x70, 0x0f, 0x2f, 0x31, 0x42, 0x8c, 0xce, 0xe9, 0xc0, 0x58, 0xe1, 0x30, + 0x30, 0xf1, 0xe9, 0xab, 0xc8, 0x60, 0x7c, 0xe0, 0x6a, 0x99, 0xe7, 0xd3, + 0x21, 0x1a, 0xcc, 0x98, 0x60, 0x44, 0xaa, 0xff, 0xee, 0xec, 0x34, 0x20, + 0x19, 0xba, 0x03, 0x3b, 0x67, 0x6f, 0xee, 0xd5, 0xb3, 0xa7, 0x21, 0x57, + 0xd6, 0x49, 0xaf, 0x91, 0x8f, 0xec, 0x70, 0xd0, 0x59, 0x1a, 0x79, 0xe2, + 0xd2, 0x94, 0x82, 0x53, 0xfb, 0xea, 0xd6, 0x83, 0x49, 0x4a, 0x6f, 0xd6, + 0xed, 0x15, 0xc3, 0x71, 0x08, 0x3a, 0xbf, 0xde, 0xa8, 0x2d, 0x54, 0xaf, + 0x4a, 0x40, 0xbc, 0xe5, 0x53, 0xae, 0x4b, 0x3d, 0x70, 0xfe, 0x1c, 0x03, + 0x1e, 0xb2, 0x9d, 0x1c, 0x35, 0xbd, 0x9a, 0xf8, 0xc5, 0xd1, 0xa5, 0x4a, + 0x63, 0x18, 0x02, 0xd4, 0xff, 0xdd, 0xcd, 0xb3, 0x6c, 0x38, 0xd1, 0x9a, + 0xad, 0x16, 0x71, 0xf1, 0xc6, 0x1d, 0x8f, 0x6c, 0x30, 0xfa, 0x2e, 0x13, + 0x9d, 0x0b, 0x4e, 0xe6, 0xd3, 0x37, 0x80, 0x58, 0x26, 0x0d, 0x04, 0x97, + 0xe6, 0x8d, 0xcc, 0x63, 0x3c, 0x39, 0x38, 0x2f, 0x7a, 0x73, 0x01, 0x0f, + 0x22, 0x69, 0x47, 0x54, 0x9e, 0x42, 0xc8, 0x59, 0xb5, 0x35, 0x43, 0xb4, + 0x37, 0x45, 0x59, 0x85, 0xf2, 0x47, 0xc3, 0xfb, 0x23, 0x13, 0x18, 0xef, + 0xd8, 0x11, 0x70, 0x74, 0xce, 0x97, 0xcf, 0xbf, 0xd5, 0x2d, 0x99, 0x00, + 0x86, 0x56, 0x9b, 0xdf, 0x05, 0x67, 0xf4, 0x49, 0x1e, 0xb5, 0x12, 0x23, + 0x46, 0x04, 0x83, 0xf3, 0xc1, 0x59, 0xc7, 0x7b, 0xc3, 0x22, 0x0c, 0x2c, + 0x1b, 0x7d, 0x18, 0xb6, 0xd2, 0xfa, 0x28, 0x36, 0x8b, 0x51, 0x6d, 0x58, + 0xf4, 0xd6, 0xdf, 0x38, 0x94, 0xcf, 0x6c, 0x50, 0x4f, 0x0a, 0xf3, 0xc3, + 0x91, 0x39, 0xa5, 0xc9, 0xbc, 0xa8, 0xeb, 0x24, 0x1a, 0xdd, 0x58, 0x9e, + 0xdc, 0xb2, 0xee, 0xe1, 0xa5, 0x16, 0x68, 0xc2, 0x63, 0x8c, 0xc9, 0xa7, + 0xbe, 0x1e, 0x30, 0x84, 0xa6, 0x28, 0xeb, 0x50, 0xd9, 0xdd, 0x15, 0xea, + 0x64, 0x34, 0xf0, 0x7a, 0x56, 0x6a, 0xdd, 0xb2, 0x70, 0x2e, 0xea, 0x72, + 0x66, 0x39, 0x54, 0xaa, 0x36, 0xfa, 0x68, 0xaa, 0x06, 0x5d, 0x48, 0xca, + 0xad, 0x4e, 0xfe, 0x4b, 0x40, 0xdf, 0x43, 0x46, 0xd6, 0xdf, 0x3f, 0xa1, + 0x9e, 0x4c, 0xdc, 0xfe, 0x4c, 0x01, 0x09, 0x7f, 0xd8, 0x00, 0x84, 0x94, + 0x29, 0x17, 0x67, 0x00, 0xd3, 0x46, 0xd2, 0xba, 0xb9, 0x62, 0x66, 0x50, + 0xcd, 0x7c, 0x7a, 0x70, 0x46, 0x4a, 0x32, 0x62, 0xc2, 0x6e, 0xe7, 0x5e, + 0x04, 0x24, 0xc5, 0xfd, 0x9d, 0xf4, 0x9b, 0xc8, 0xe9, 0xeb, 0x73, 0xf9, + 0xaa, 0xa4, 0xcc, 0x63, 0xa3, 0xdc, 0x63, 0xe0, 0x30, 0xec, 0x70, 0x40, + 0x9e, 0x7c, 0x63, 0x79, 0xae, 0xba, 0xfd, 0x95, 0x4c, 0x46, 0xf1, 0xc4, + 0xae, 0xb9, 0x03, 0xe8, 0xd4, 0xe4, 0x90, 0x29, 0x3a, 0xbb, 0xdb, 0xd8, + 0x8f, 0x40, 0xc3, 0x39, 0x9a, 0x4c, 0x70, 0x54, 0x9f, 0xc9, 0x0a, 0x04, + 0x23, 0x98, 0x6b, 0x9c, 0xc2, 0xe0, 0xad, 0xae, 0x30, 0xef, 0xff, 0x44, + 0x5b, 0x73, 0x2e, 0x8f, 0xd7, 0x2b, 0x12, 0xf0, 0x31, 0x08, 0xfb, 0xb9, + 0x55, 0xf0, 0xc3, 0x62, 0xbb, 0x5f, 0x6d, 0xa7, 0x1d, 0x61, 0xc2, 0x26, + 0xce, 0xab, 0xb6, 0x88, 0x25, 0xce, 0x8b, 0x02, 0xb6, 0xc5, 0xa2, 0xcc, + 0xd4, 0xa3, 0x74, 0x5b, 0x76, 0xf7, 0xb4, 0xd9, 0x9c, 0x93, 0x86, 0x7e, + 0xac, 0x82, 0xe0, 0x0d, 0x83, 0xe1, 0xc9, 0x7f, 0x2a, 0x86, 0xbb, 0xaa, + 0xfe, 0xdc, 0x17, 0x9c, 0x28, 0x77, 0xe1, 0x58, 0x18, 0x15, 0x09, 0xe3, + 0xda, 0xdb, 0x8d, 0xee, 0x55, 0xf6, 0xda, 0xad, 0xe5, 0x52, 0x84, 0xb4, + 0xf0, 0x24, 0xce, 0xa1, 0x54, 0x4b, 0x9f, 0xea, 0x5d, 0x4d, 0x7f, 0x53, + 0x0b, 0x79, 0x1d, 0x87, 0xcb, 0x0b, 0xa8, 0xef, 0x03, 0xfa, 0x58, 0x57, + 0xf6, 0x02, 0x70, 0xdb, 0x7a, 0x64, 0x89, 0x1f, 0xc7, 0xca, 0x87, 0x02, + 0x27, 0x33, 0xc5, 0x5b, 0x2a, 0x50, 0xc5, 0xb5, 0x7b, 0x2d, 0x3d, 0xa9, + 0xbc, 0x21, 0x7b, 0xf2, 0xbe, 0x9c, 0x56, 0x35, 0x83, 0xba, 0xce, 0x34, + 0x8d, 0xec, 0x7b, 0xaa, 0xe4, 0xcb, 0xd1, 0x4f, 0x4a, 0x31, 0x00, 0xd1, + 0xb8, 0x30, 0x38, 0xaf, 0xe8, 0xe3, 0xd7, 0xc2, 0x8c, 0xe3, 0xb4, 0x23, + 0xb3, 0x27, 0x07, 0xc6, 0x88, 0xec, 0x58, 0xe9, 0x59, 0xfb, 0xa9, 0x11, + 0xa2, 0xc8, 0x77, 0x22, 0x6a, 0x5b, 0x86, 0xde, 0xdc, 0xed, 0x76, 0x6e, + 0x73, 0x79, 0x5c, 0xb4, 0xcf, 0x19, 0x76, 0x5c, 0x6b, 0x1c, 0x4b, 0x03, + 0xcb, 0x35, 0x08, 0x94, 0x37, 0x01, 0x98, 0x52, 0xd8, 0x31, 0x42, 0x3d, + 0x7f, 0xa1, 0x11, 0x06, 0x07, 0x88, 0xb8, 0x31, 0x35, 0xb2, 0x49, 0x28, + 0xc6, 0x2c, 0x44, 0x43, 0xb6, 0xbc, 0x58, 0x76, 0x6c, 0x4f, 0xc8, 0xb6, + 0x30, 0x82, 0x05, 0x84, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, + 0x01, 0x07, 0x01, 0xa0, 0x82, 0x05, 0x75, 0x04, 0x82, 0x05, 0x71, 0x30, + 0x82, 0x05, 0x6d, 0x30, 0x82, 0x05, 0x69, 0x06, 0x0b, 0x2a, 0x86, 0x48, + 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x0a, 0x01, 0x02, 0xa0, 0x82, 0x05, 0x31, + 0x30, 0x82, 0x05, 0x2d, 0x30, 0x57, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, + 0xf7, 0x0d, 0x01, 0x05, 0x0d, 0x30, 0x4a, 0x30, 0x29, 0x06, 0x09, 0x2a, + 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x05, 0x0c, 0x30, 0x1c, 0x04, 0x08, + 0x79, 0x31, 0xf9, 0xe2, 0x42, 0x33, 0xf1, 0xaa, 0x02, 0x02, 0x08, 0x00, + 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x09, + 0x05, 0x00, 0x30, 0x1d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, + 0x04, 0x01, 0x02, 0x04, 0x10, 0xc9, 0xda, 0x5f, 0x96, 0xc8, 0x2c, 0x85, + 0x5d, 0xa0, 0x30, 0x82, 0x16, 0x6b, 0xf4, 0xfd, 0x91, 0x04, 0x82, 0x04, + 0xd0, 0xc3, 0x89, 0x6a, 0x56, 0x6a, 0x84, 0x58, 0x76, 0xd7, 0x23, 0xd5, + 0xa8, 0xc1, 0x2f, 0x43, 0x38, 0x99, 0xf8, 0x64, 0x97, 0xe7, 0xe8, 0xd2, + 0xcf, 0x36, 0x9b, 0x7e, 0x04, 0xe5, 0x87, 0x80, 0xff, 0xd5, 0x58, 0x50, + 0x5a, 0xb3, 0xc0, 0x15, 0xc9, 0xd5, 0x61, 0xd6, 0x3b, 0x7f, 0x2f, 0x3b, + 0x98, 0x50, 0x55, 0x09, 0xcf, 0xc3, 0xdd, 0xbd, 0x8b, 0xcd, 0xdf, 0x20, + 0x90, 0xe1, 0xd2, 0xcd, 0x22, 0x9f, 0xa7, 0x3e, 0x10, 0xd3, 0xb7, 0x26, + 0x54, 0x65, 0xfb, 0x18, 0x12, 0x58, 0x81, 0xd8, 0xe6, 0x97, 0xdf, 0x32, + 0xd1, 0x04, 0x4a, 0xdb, 0x05, 0xb4, 0x13, 0xa9, 0x86, 0x62, 0x20, 0x94, + 0xdc, 0xaf, 0x98, 0x53, 0x16, 0xc7, 0xb2, 0x9c, 0x44, 0x30, 0xc5, 0xaa, + 0x14, 0x7a, 0x2d, 0x93, 0x20, 0xff, 0x6d, 0x8d, 0x47, 0x69, 0x6f, 0x39, + 0xd4, 0x15, 0x81, 0x6b, 0x85, 0x36, 0xf9, 0x59, 0xa5, 0x8e, 0x5c, 0x40, + 0x62, 0xf8, 0xfe, 0xf7, 0xe6, 0x75, 0xf7, 0x37, 0xfe, 0x5d, 0x53, 0xa6, + 0x66, 0xe5, 0x0e, 0x4a, 0x23, 0xa9, 0x80, 0x4b, 0x04, 0x11, 0x0e, 0x50, + 0xef, 0x9e, 0x88, 0xed, 0x39, 0xd1, 0x5f, 0xfa, 0x90, 0x22, 0xa3, 0x70, + 0x0c, 0x8b, 0x20, 0x9c, 0x80, 0x2c, 0x90, 0x2e, 0x2c, 0xe0, 0xe6, 0x26, + 0x84, 0xd8, 0x6a, 0xe4, 0x20, 0x1e, 0xbc, 0x96, 0xba, 0x07, 0x9d, 0x1d, + 0x3d, 0x6c, 0xd1, 0x04, 0xc8, 0xd1, 0x79, 0x2c, 0x96, 0x0f, 0xe8, 0xa5, + 0x6b, 0x03, 0x06, 0x51, 0xfd, 0x7b, 0x44, 0xab, 0x66, 0x4a, 0x41, 0x04, + 0x02, 0x64, 0x5a, 0x40, 0x7d, 0x6b, 0x1a, 0xbc, 0x6e, 0xee, 0x68, 0x70, + 0x3c, 0x10, 0x32, 0x73, 0x76, 0x28, 0x48, 0xd9, 0xa4, 0xe1, 0x21, 0xf6, + 0xe4, 0x03, 0x94, 0x10, 0xef, 0x82, 0xe0, 0x76, 0x7c, 0x99, 0x30, 0x26, + 0x9a, 0x95, 0xa2, 0xc5, 0xb9, 0xa7, 0xae, 0x9f, 0x85, 0xcb, 0xf1, 0x82, + 0xcd, 0x3d, 0x06, 0xec, 0xaf, 0x72, 0xc1, 0x33, 0x09, 0xf9, 0x51, 0x94, + 0x42, 0xf0, 0x69, 0xb9, 0xc6, 0x04, 0xe6, 0x7a, 0xfb, 0x1c, 0xee, 0xac, + 0x95, 0x9b, 0x88, 0x67, 0x19, 0xa8, 0x79, 0x67, 0xc7, 0x1b, 0xcc, 0x72, + 0xe9, 0x18, 0xd2, 0x96, 0xcf, 0x3d, 0xf8, 0x98, 0x20, 0x53, 0xc9, 0x37, + 0x0f, 0x92, 0xb1, 0xbc, 0xaf, 0xc6, 0xec, 0x4f, 0x25, 0xda, 0x95, 0x14, + 0xed, 0xb8, 0x3e, 0xaf, 0xd1, 0x52, 0x4c, 0x28, 0x3b, 0x84, 0x8c, 0x49, + 0x34, 0x63, 0x2b, 0xd4, 0xf4, 0x78, 0xb1, 0x8f, 0xb0, 0x35, 0x7b, 0xd5, + 0x44, 0xc3, 0x98, 0x9e, 0x85, 0x86, 0xae, 0xee, 0x05, 0xdd, 0xa1, 0x6f, + 0x53, 0xe4, 0xdc, 0x6f, 0xf5, 0x7c, 0x7e, 0xd8, 0x7a, 0x9b, 0x18, 0x43, + 0x3f, 0x7b, 0x2a, 0xf3, 0xb5, 0x39, 0x5a, 0x1c, 0x72, 0x3b, 0xdd, 0x01, + 0x79, 0x97, 0xff, 0xdb, 0x58, 0xe5, 0x4d, 0x61, 0xde, 0xcf, 0x2f, 0x13, + 0x7b, 0xaf, 0x6b, 0xa4, 0xf2, 0x59, 0x0a, 0x13, 0x56, 0x1c, 0x05, 0x00, + 0x0f, 0x18, 0x66, 0x33, 0x72, 0xbd, 0x62, 0x8d, 0x11, 0xf7, 0x20, 0x52, + 0x29, 0x42, 0x83, 0x33, 0xc1, 0x0f, 0x07, 0x80, 0xd4, 0x58, 0xe2, 0x22, + 0x94, 0xad, 0xec, 0xbf, 0x01, 0xb6, 0x71, 0x7d, 0x92, 0xb1, 0x75, 0x14, + 0xf2, 0xfb, 0x77, 0x39, 0x0d, 0x82, 0xb5, 0x51, 0xba, 0x1f, 0x65, 0x57, + 0xaa, 0x68, 0x6a, 0x17, 0x41, 0x13, 0x38, 0xc0, 0xe5, 0xeb, 0xcc, 0x8c, + 0xdd, 0xb7, 0x00, 0x4e, 0x01, 0x06, 0x25, 0xab, 0x87, 0x1c, 0x30, 0x69, + 0xc4, 0x15, 0x0e, 0xf8, 0xf0, 0x72, 0xb6, 0x1d, 0x92, 0x7e, 0xe2, 0xe6, + 0x77, 0xed, 0xb8, 0x3f, 0xcf, 0x57, 0x8d, 0x90, 0xe4, 0xa3, 0x79, 0x49, + 0x9a, 0xe0, 0x1f, 0x4a, 0xde, 0xe9, 0x44, 0x8d, 0xd5, 0x23, 0x3b, 0x07, + 0x63, 0x92, 0x9f, 0xde, 0xba, 0x7e, 0x67, 0xb0, 0x82, 0x41, 0x2a, 0xcd, + 0xe1, 0xbb, 0x40, 0xf1, 0x8a, 0x66, 0x70, 0x74, 0xf1, 0x99, 0x7d, 0xb0, + 0x0b, 0x6a, 0xa2, 0x5e, 0x7e, 0xc0, 0x8c, 0xb2, 0x71, 0xda, 0xcf, 0xbc, + 0xfb, 0x9c, 0x03, 0x0e, 0x33, 0x5e, 0x13, 0xb2, 0x34, 0x38, 0xc1, 0x83, + 0x95, 0xdf, 0x46, 0xfc, 0xe0, 0xe0, 0xaf, 0x93, 0xe0, 0x70, 0xd5, 0x15, + 0x8c, 0x2f, 0xae, 0x4b, 0xa6, 0xeb, 0x13, 0x8f, 0xaf, 0x1b, 0xf5, 0x71, + 0xc4, 0x62, 0x71, 0x08, 0x97, 0x10, 0x52, 0xfe, 0xbd, 0x60, 0xd7, 0x9f, + 0xdf, 0x3d, 0xc5, 0xdd, 0xcd, 0xe7, 0x8e, 0x85, 0x60, 0xdf, 0x61, 0x79, + 0x5b, 0x90, 0xd9, 0xaa, 0x56, 0x30, 0x6d, 0x0f, 0xfb, 0x27, 0x84, 0xdd, + 0x3d, 0x04, 0x6a, 0xe0, 0x70, 0x7e, 0xbb, 0x59, 0xf4, 0xeb, 0xe8, 0xc0, + 0x62, 0xaa, 0xf6, 0xed, 0xca, 0xae, 0xb2, 0x2b, 0x0f, 0xc1, 0x56, 0x45, + 0xe7, 0x24, 0x6b, 0xaf, 0xeb, 0x15, 0x26, 0xb2, 0xcd, 0xae, 0x1f, 0xe7, + 0x11, 0xc0, 0x1c, 0x19, 0x4a, 0xc7, 0x51, 0x2a, 0x29, 0xdf, 0x14, 0x82, + 0x43, 0xfe, 0x52, 0x39, 0xba, 0xe6, 0x6c, 0xa5, 0x76, 0x8b, 0xb1, 0x21, + 0x9c, 0x20, 0xb0, 0x10, 0x0c, 0x44, 0xf2, 0xd4, 0x6e, 0x41, 0x1b, 0x8f, + 0x90, 0x23, 0xe3, 0x87, 0xfc, 0xf1, 0x46, 0xc6, 0x5b, 0xae, 0xd0, 0x2a, + 0x2b, 0x78, 0xf5, 0x2b, 0xb9, 0x9f, 0x46, 0x4b, 0x30, 0xf8, 0x49, 0x57, + 0x7e, 0xb4, 0xff, 0xca, 0xad, 0x4d, 0xf3, 0xc1, 0x7b, 0x42, 0xe0, 0xa4, + 0x37, 0x2f, 0xe2, 0xb2, 0x60, 0xe8, 0xaf, 0xd7, 0x39, 0x23, 0x4c, 0x67, + 0x44, 0xe5, 0x6d, 0xb3, 0x25, 0x11, 0x9f, 0x2b, 0xea, 0x23, 0xfb, 0x1e, + 0xce, 0xbf, 0xa4, 0x2f, 0x88, 0xec, 0x18, 0x40, 0x16, 0x43, 0x9f, 0x71, + 0x9c, 0x8d, 0xbd, 0x5d, 0x55, 0x3b, 0x92, 0x4e, 0x23, 0x3c, 0x87, 0xed, + 0x5f, 0x2e, 0x8f, 0xde, 0x83, 0xad, 0x30, 0x42, 0x7e, 0x1a, 0x5e, 0xf5, + 0xc5, 0x75, 0xbb, 0x99, 0x6e, 0xf1, 0x87, 0xe0, 0xf3, 0x51, 0x1e, 0x7d, + 0xe8, 0xfc, 0xc6, 0x88, 0xf2, 0x39, 0x6d, 0xae, 0x73, 0x9f, 0xad, 0x9b, + 0x7b, 0x67, 0x99, 0xdb, 0x90, 0x0e, 0xa0, 0xfc, 0xaf, 0xcc, 0xdb, 0x8b, + 0xaa, 0xc2, 0x54, 0xd5, 0x2d, 0xb3, 0x5f, 0xa3, 0x0a, 0x3e, 0xd6, 0x8d, + 0x40, 0x4d, 0x3b, 0xe5, 0x2d, 0x31, 0xd8, 0xb2, 0x12, 0x07, 0xca, 0x36, + 0x56, 0xd9, 0x2f, 0x55, 0x82, 0xdc, 0x8e, 0x92, 0xa9, 0x6c, 0x91, 0x9e, + 0x22, 0xe4, 0xc6, 0x27, 0x8b, 0x1a, 0xa2, 0x78, 0x56, 0x2c, 0x5a, 0x19, + 0xdf, 0x40, 0xf9, 0xfb, 0x44, 0x21, 0x5b, 0xdf, 0x2f, 0x99, 0x84, 0x49, + 0xcf, 0x1a, 0x15, 0xa5, 0x59, 0x3a, 0x66, 0x09, 0x4d, 0xc1, 0xf2, 0xb1, + 0x24, 0x33, 0xbd, 0x86, 0x41, 0xdc, 0x33, 0x9b, 0x03, 0xc0, 0xa8, 0xf8, + 0x94, 0x78, 0x2e, 0x16, 0x97, 0xef, 0x23, 0xee, 0xa4, 0xac, 0x3a, 0x90, + 0xb6, 0xd9, 0xc0, 0xda, 0x5e, 0x26, 0x34, 0x26, 0xce, 0xc9, 0xf8, 0x45, + 0x37, 0x83, 0x7c, 0xbd, 0x9c, 0x60, 0x40, 0x61, 0x28, 0xcd, 0x9c, 0xb4, + 0xe4, 0xe6, 0x5c, 0x4f, 0xd1, 0x79, 0x42, 0x13, 0xa9, 0x6f, 0x26, 0x23, + 0xc2, 0x6c, 0x8e, 0x8d, 0x7e, 0x3f, 0xee, 0x2b, 0x4d, 0xd2, 0x5b, 0x80, + 0xdc, 0x74, 0xda, 0x1f, 0xbc, 0x26, 0x54, 0xc5, 0xfe, 0xee, 0xa9, 0x4f, + 0xce, 0x46, 0xaf, 0x90, 0xb0, 0x12, 0x9a, 0x18, 0x0e, 0x06, 0x05, 0xc7, + 0x98, 0xef, 0xcc, 0x6d, 0xa3, 0x46, 0x91, 0xa5, 0x0e, 0xe7, 0x35, 0x1a, + 0x7f, 0x9d, 0xae, 0xa0, 0xb4, 0x0a, 0x32, 0x3b, 0xe4, 0xcd, 0x4b, 0x3e, + 0x89, 0x73, 0xc9, 0x97, 0x38, 0xe5, 0x86, 0x4f, 0x24, 0xed, 0x4a, 0x43, + 0x04, 0x02, 0xc1, 0x29, 0x8d, 0x85, 0xa2, 0xdd, 0xb2, 0x61, 0x3c, 0xce, + 0x8b, 0x47, 0x2e, 0xed, 0x4b, 0x24, 0x94, 0xb7, 0xbf, 0x9d, 0x55, 0x42, + 0x95, 0xc2, 0x27, 0xe5, 0x09, 0xd4, 0x20, 0x03, 0x20, 0x21, 0x3a, 0xd8, + 0xd2, 0xa2, 0xb3, 0x47, 0x93, 0x4f, 0x5a, 0x39, 0xca, 0xd8, 0x74, 0xa9, + 0x19, 0xa6, 0x9a, 0x23, 0xb1, 0x21, 0xa3, 0xb3, 0x14, 0xcc, 0xe2, 0x12, + 0x91, 0x30, 0xdb, 0x50, 0xf8, 0x44, 0x74, 0xd6, 0x70, 0xdd, 0x7d, 0x26, + 0x7f, 0xbf, 0x32, 0x93, 0x1f, 0x3d, 0x40, 0xbf, 0x2e, 0xec, 0x28, 0xf5, + 0xb1, 0xaf, 0x11, 0xc7, 0x4e, 0x64, 0x13, 0x3c, 0xbf, 0x2e, 0x19, 0x81, + 0xfe, 0x35, 0xba, 0xec, 0x6e, 0xb6, 0xa9, 0xfe, 0xc6, 0x85, 0x33, 0x41, + 0x58, 0xab, 0x06, 0xae, 0x2b, 0x96, 0x62, 0x1f, 0x2c, 0x6c, 0xad, 0xec, + 0x1a, 0x59, 0x55, 0x5a, 0x6f, 0xe0, 0xeb, 0x71, 0x8d, 0xb5, 0x0c, 0x81, + 0x2a, 0x39, 0xbd, 0x67, 0x39, 0x48, 0xfb, 0x91, 0x64, 0xad, 0x01, 0x4c, + 0x4a, 0x0f, 0x30, 0x29, 0xa0, 0xcf, 0x30, 0x96, 0x43, 0xe9, 0xfc, 0x22, + 0x4b, 0xf3, 0x4f, 0xab, 0xec, 0xbc, 0x5a, 0xfb, 0x7f, 0x20, 0xd9, 0xd5, + 0xc7, 0xce, 0x93, 0xa3, 0x2e, 0x82, 0xd1, 0xa0, 0xc6, 0x16, 0xd5, 0x64, + 0x2d, 0x3f, 0x69, 0x15, 0xfd, 0xf3, 0x28, 0x3d, 0x4e, 0x61, 0x01, 0x2c, + 0xd4, 0x2b, 0x40, 0x51, 0x6e, 0x95, 0x00, 0xa4, 0x34, 0x31, 0x25, 0x30, + 0x23, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x15, + 0x31, 0x16, 0x04, 0x14, 0x47, 0xf4, 0x18, 0xa5, 0x4b, 0x85, 0xb7, 0x02, + 0xc1, 0x97, 0xff, 0x57, 0xb6, 0x6f, 0x21, 0x45, 0x34, 0x3d, 0x92, 0x22, + 0x30, 0x31, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, + 0x1a, 0x05, 0x00, 0x04, 0x14, 0x17, 0x45, 0x0c, 0xdf, 0x53, 0x76, 0x9b, + 0xce, 0x3b, 0x12, 0xdd, 0x47, 0x05, 0x6d, 0x16, 0x90, 0x9d, 0x29, 0x9b, + 0xe1, 0x04, 0x08, 0xa1, 0xf2, 0x82, 0x1c, 0xd1, 0xd1, 0x7b, 0x5c, 0x02, + 0x02, 0x08, 0x00, +}; + +// kNoEncryption is a PKCS#12 file with neither the key or certificate is +// encrypted. It was generated with: +// +// openssl pkcs12 -export -inkey ecdsa_p256_key.pem -in ecdsa_p256_cert.pem -keypbe NONE -certpbe NONE -password pass:foo +static const uint8_t kNoEncryption[] = { + 0x30, 0x82, 0x03, 0x6e, 0x02, 0x01, 0x03, 0x30, 0x82, 0x03, 0x34, 0x06, + 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0xa0, 0x82, + 0x03, 0x25, 0x04, 0x82, 0x03, 0x21, 0x30, 0x82, 0x03, 0x1d, 0x30, 0x82, + 0x02, 0x3e, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, + 0x01, 0xa0, 0x82, 0x02, 0x2f, 0x04, 0x82, 0x02, 0x2b, 0x30, 0x82, 0x02, + 0x27, 0x30, 0x82, 0x02, 0x23, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf7, + 0x0d, 0x01, 0x0c, 0x0a, 0x01, 0x03, 0xa0, 0x82, 0x01, 0xeb, 0x30, 0x82, + 0x01, 0xe7, 0x06, 0x0a, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, + 0x16, 0x01, 0xa0, 0x82, 0x01, 0xd7, 0x04, 0x82, 0x01, 0xd3, 0x30, 0x82, + 0x01, 0xcf, 0x30, 0x82, 0x01, 0x76, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, + 0x09, 0x00, 0xd9, 0x4c, 0x04, 0xda, 0x49, 0x7d, 0xbf, 0xeb, 0x30, 0x09, + 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x01, 0x30, 0x45, 0x31, + 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x41, 0x55, + 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c, 0x0a, 0x53, + 0x6f, 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, 0x21, 0x30, + 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x18, 0x49, 0x6e, 0x74, 0x65, + 0x72, 0x6e, 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67, 0x69, 0x74, 0x73, + 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74, 0x64, 0x30, 0x1e, 0x17, 0x0d, + 0x31, 0x34, 0x30, 0x34, 0x32, 0x33, 0x32, 0x33, 0x32, 0x31, 0x35, 0x37, + 0x5a, 0x17, 0x0d, 0x31, 0x34, 0x30, 0x35, 0x32, 0x33, 0x32, 0x33, 0x32, + 0x31, 0x35, 0x37, 0x5a, 0x30, 0x45, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, + 0x55, 0x04, 0x06, 0x13, 0x02, 0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06, + 0x03, 0x55, 0x04, 0x08, 0x0c, 0x0a, 0x53, 0x6f, 0x6d, 0x65, 0x2d, 0x53, + 0x74, 0x61, 0x74, 0x65, 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, + 0x0a, 0x0c, 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x20, + 0x57, 0x69, 0x64, 0x67, 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, + 0x4c, 0x74, 0x64, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, + 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, + 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xe6, 0x2b, 0x69, 0xe2, 0xbf, 0x65, + 0x9f, 0x97, 0xbe, 0x2f, 0x1e, 0x0d, 0x94, 0x8a, 0x4c, 0xd5, 0x97, 0x6b, + 0xb7, 0xa9, 0x1e, 0x0d, 0x46, 0xfb, 0xdd, 0xa9, 0xa9, 0x1e, 0x9d, 0xdc, + 0xba, 0x5a, 0x01, 0xe7, 0xd6, 0x97, 0xa8, 0x0a, 0x18, 0xf9, 0xc3, 0xc4, + 0xa3, 0x1e, 0x56, 0xe2, 0x7c, 0x83, 0x48, 0xdb, 0x16, 0x1a, 0x1c, 0xf5, + 0x1d, 0x7e, 0xf1, 0x94, 0x2d, 0x4b, 0xcf, 0x72, 0x22, 0xc1, 0xa3, 0x50, + 0x30, 0x4e, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, + 0x14, 0xab, 0x84, 0xd2, 0xac, 0xab, 0x95, 0xf0, 0x82, 0x4e, 0x16, 0x78, + 0x07, 0x55, 0x57, 0x5f, 0xe4, 0x26, 0x8d, 0x82, 0xd1, 0x30, 0x1f, 0x06, + 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0xab, 0x84, + 0xd2, 0xac, 0xab, 0x95, 0xf0, 0x82, 0x4e, 0x16, 0x78, 0x07, 0x55, 0x57, + 0x5f, 0xe4, 0x26, 0x8d, 0x82, 0xd1, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, + 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff, 0x30, 0x09, 0x06, 0x07, + 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x01, 0x03, 0x48, 0x00, 0x30, 0x45, + 0x02, 0x21, 0x00, 0xf2, 0xa0, 0x35, 0x5e, 0x51, 0x3a, 0x36, 0xc3, 0x82, + 0x79, 0x9b, 0xee, 0x27, 0x50, 0x85, 0x8e, 0x70, 0x06, 0x74, 0x95, 0x57, + 0xd2, 0x29, 0x74, 0x00, 0xf4, 0xbe, 0x15, 0x87, 0x5d, 0xc4, 0x07, 0x02, + 0x20, 0x7c, 0x1e, 0x79, 0x14, 0x6a, 0x21, 0x83, 0xf0, 0x7a, 0x74, 0x68, + 0x79, 0x5f, 0x14, 0x99, 0x9a, 0x68, 0xb4, 0xf1, 0xcb, 0x9e, 0x15, 0x5e, + 0xe6, 0x1f, 0x32, 0x52, 0x61, 0x5e, 0x75, 0xc9, 0x14, 0x31, 0x25, 0x30, + 0x23, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x15, + 0x31, 0x16, 0x04, 0x14, 0x3f, 0x31, 0x38, 0xec, 0xb9, 0xf1, 0x45, 0xe1, + 0x3e, 0x90, 0x71, 0x0d, 0xc1, 0x28, 0xba, 0x4e, 0x6f, 0xa0, 0x9c, 0xed, + 0x30, 0x81, 0xd8, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, + 0x07, 0x01, 0xa0, 0x81, 0xca, 0x04, 0x81, 0xc7, 0x30, 0x81, 0xc4, 0x30, + 0x81, 0xc1, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, + 0x0a, 0x01, 0x01, 0xa0, 0x81, 0x8a, 0x30, 0x81, 0x87, 0x02, 0x01, 0x00, + 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, + 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x04, 0x6d, 0x30, + 0x6b, 0x02, 0x01, 0x01, 0x04, 0x20, 0x07, 0x0f, 0x08, 0x72, 0x7a, 0xd4, + 0xa0, 0x4a, 0x9c, 0xdd, 0x59, 0xc9, 0x4d, 0x89, 0x68, 0x77, 0x08, 0xb5, + 0x6f, 0xc9, 0x5d, 0x30, 0x77, 0x0e, 0xe8, 0xd1, 0xc9, 0xce, 0x0a, 0x8b, + 0xb4, 0x6a, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0xe6, 0x2b, 0x69, 0xe2, + 0xbf, 0x65, 0x9f, 0x97, 0xbe, 0x2f, 0x1e, 0x0d, 0x94, 0x8a, 0x4c, 0xd5, + 0x97, 0x6b, 0xb7, 0xa9, 0x1e, 0x0d, 0x46, 0xfb, 0xdd, 0xa9, 0xa9, 0x1e, + 0x9d, 0xdc, 0xba, 0x5a, 0x01, 0xe7, 0xd6, 0x97, 0xa8, 0x0a, 0x18, 0xf9, + 0xc3, 0xc4, 0xa3, 0x1e, 0x56, 0xe2, 0x7c, 0x83, 0x48, 0xdb, 0x16, 0x1a, + 0x1c, 0xf5, 0x1d, 0x7e, 0xf1, 0x94, 0x2d, 0x4b, 0xcf, 0x72, 0x22, 0xc1, + 0x31, 0x25, 0x30, 0x23, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, + 0x01, 0x09, 0x15, 0x31, 0x16, 0x04, 0x14, 0x3f, 0x31, 0x38, 0xec, 0xb9, + 0xf1, 0x45, 0xe1, 0x3e, 0x90, 0x71, 0x0d, 0xc1, 0x28, 0xba, 0x4e, 0x6f, + 0xa0, 0x9c, 0xed, 0x30, 0x31, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, + 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14, 0xd0, 0xb4, 0x17, 0x1a, + 0xdb, 0xa3, 0x27, 0xd8, 0x9e, 0xd3, 0xf2, 0xb3, 0x3e, 0x96, 0x07, 0x3a, + 0xf2, 0x6a, 0xc2, 0x1c, 0x04, 0x08, 0xb5, 0xa8, 0xb9, 0xdb, 0x2f, 0xf1, + 0xa4, 0xcd, 0x02, 0x02, 0x08, 0x00, +}; + static const char kPassword[] = "foo"; // Generated with @@ -1230,7 +1545,12 @@ TEST(PKCS12Test, TestWindows) { } TEST(PKCS12Test, TestPBES2) { - TestImpl("PBES2", kPBES2, kPassword, nullptr); + TestImpl("kPBES2WithSHA1", kPBES2WithSHA1, kPassword, nullptr); + TestImpl("kPBES2WithSHA256", kPBES2WithSHA256, kPassword, nullptr); +} + +TEST(PKCS12Test, TestNoEncryption) { + TestImpl("kNoEncryption", kNoEncryption, kPassword, nullptr); } TEST(PKCS12Test, TestEmptyPassword) { @@ -1506,3 +1826,152 @@ TEST(PKCS12Test, RoundTrip) { NID_pbe_WithSHA1And3_Key_TripleDES_CBC, NID_pbe_WithSHA1And3_Key_TripleDES_CBC, 100, 100); } + +static bssl::UniquePtr MakeTestKey() { + bssl::UniquePtr ec_key( + EC_KEY_new_by_curve_name(NID_X9_62_prime256v1)); + if (!ec_key || + !EC_KEY_generate_key(ec_key.get())) { + return nullptr; + } + bssl::UniquePtr evp_pkey(EVP_PKEY_new()); + if (!evp_pkey || + !EVP_PKEY_assign_EC_KEY(evp_pkey.get(), ec_key.release())) { + return nullptr; + } + return evp_pkey; +} + +static bssl::UniquePtr MakeTestCert(EVP_PKEY *key) { + bssl::UniquePtr x509(X509_new()); + if (!x509) { + return nullptr; + } + X509_NAME* subject = X509_get_subject_name(x509.get()); + if (!X509_gmtime_adj(X509_get_notBefore(x509.get()), 0) || + !X509_gmtime_adj(X509_get_notAfter(x509.get()), 60 * 60 * 24) || + !X509_NAME_add_entry_by_txt(subject, "CN", MBSTRING_ASC, + reinterpret_cast("Test"), -1, + -1, 0) || + !X509_set_issuer_name(x509.get(), subject) || + !X509_set_pubkey(x509.get(), key) || + !X509_sign(x509.get(), key, EVP_sha256())) { + return nullptr; + } + return x509; +} + +static bool PKCS12CreateVector(std::vector *out, EVP_PKEY *pkey, + const std::vector &certs) { + bssl::UniquePtr chain(sk_X509_new_null()); + if (!chain) { + return false; + } + + for (X509 *cert : certs) { + if (!bssl::PushToStack(chain.get(), bssl::UpRef(cert))) { + return false; + } + } + + bssl::UniquePtr p12(PKCS12_create(kPassword, nullptr /* name */, pkey, + nullptr /* cert */, chain.get(), 0, + 0, 0, 0, 0)); + if (!p12) { + return false; + } + + int len = i2d_PKCS12(p12.get(), nullptr); + if (len < 0) { + return false; + } + out->resize(static_cast(len)); + uint8_t *ptr = out->data(); + return i2d_PKCS12(p12.get(), &ptr) == len; +} + +static void ExpectPKCS12Parse(bssl::Span in, + EVP_PKEY *expect_key, X509 *expect_cert, + const std::vector &expect_ca_certs) { + bssl::UniquePtr bio(BIO_new_mem_buf(in.data(), in.size())); + ASSERT_TRUE(bio); + + bssl::UniquePtr p12(d2i_PKCS12_bio(bio.get(), nullptr)); + ASSERT_TRUE(p12); + + EVP_PKEY *key = nullptr; + X509 *cert = nullptr; + STACK_OF(X509) *ca_certs = nullptr; + ASSERT_TRUE(PKCS12_parse(p12.get(), kPassword, &key, &cert, &ca_certs)); + + bssl::UniquePtr delete_key(key); + bssl::UniquePtr delete_cert(cert); + bssl::UniquePtr delete_ca_certs(ca_certs); + + if (expect_key == nullptr) { + EXPECT_FALSE(key); + } else { + ASSERT_TRUE(key); + EXPECT_EQ(1, EVP_PKEY_cmp(key, expect_key)); + } + + if (expect_cert == nullptr) { + EXPECT_FALSE(cert); + } else { + ASSERT_TRUE(cert); + EXPECT_EQ(0, X509_cmp(cert, expect_cert)); + } + + ASSERT_EQ(expect_ca_certs.size(), sk_X509_num(ca_certs)); + for (size_t i = 0; i < expect_ca_certs.size(); i++) { + EXPECT_EQ(0, X509_cmp(expect_ca_certs[i], sk_X509_value(ca_certs, i))); + } +} + +// Test that |PKCS12_parse| returns values in the expected order. +TEST(PKCS12Test, Order) { + bssl::UniquePtr key1 = MakeTestKey(); + ASSERT_TRUE(key1); + bssl::UniquePtr cert1 = MakeTestCert(key1.get()); + ASSERT_TRUE(cert1); + bssl::UniquePtr cert1b = MakeTestCert(key1.get()); + ASSERT_TRUE(cert1b); + bssl::UniquePtr key2 = MakeTestKey(); + ASSERT_TRUE(key2); + bssl::UniquePtr cert2 = MakeTestCert(key2.get()); + ASSERT_TRUE(cert2); + bssl::UniquePtr key3 = MakeTestKey(); + ASSERT_TRUE(key3); + bssl::UniquePtr cert3 = MakeTestCert(key3.get()); + ASSERT_TRUE(cert3); + + // PKCS12_parse uses the key to select the main certificate. + std::vector p12; + ASSERT_TRUE(PKCS12CreateVector(&p12, key1.get(), + {cert1.get(), cert2.get(), cert3.get()})); + ExpectPKCS12Parse(p12, key1.get(), cert1.get(), {cert2.get(), cert3.get()}); + + ASSERT_TRUE(PKCS12CreateVector(&p12, key1.get(), + {cert3.get(), cert1.get(), cert2.get()})); + ExpectPKCS12Parse(p12, key1.get(), cert1.get(), {cert3.get(), cert2.get()}); + + ASSERT_TRUE(PKCS12CreateVector(&p12, key1.get(), + {cert2.get(), cert3.get(), cert1.get()})); + ExpectPKCS12Parse(p12, key1.get(), cert1.get(), {cert2.get(), cert3.get()}); + + // In case of duplicates, the last one is selected. (It is unlikely anything + // depends on which is selected, but we match OpenSSL.) + ASSERT_TRUE( + PKCS12CreateVector(&p12, key1.get(), {cert1.get(), cert1b.get()})); + ExpectPKCS12Parse(p12, key1.get(), cert1b.get(), {cert1.get()}); + + // If there is no key, all certificates are returned as "CA" certificates. + ASSERT_TRUE(PKCS12CreateVector(&p12, nullptr, + {cert1.get(), cert2.get(), cert3.get()})); + ExpectPKCS12Parse(p12, nullptr, nullptr, + {cert1.get(), cert2.get(), cert3.get()}); + + // The same happens if there is a key, but it does not match any certificate. + ASSERT_TRUE(PKCS12CreateVector(&p12, key1.get(), {cert2.get(), cert3.get()})); + ExpectPKCS12Parse(p12, key1.get(), nullptr, {cert2.get(), cert3.get()}); +} diff --git a/third_party/boringssl/kit/src/crypto/pkcs8/pkcs8.c b/third_party/boringssl/kit/src/crypto/pkcs8/pkcs8.c index ee25ee29..a19b4a3d 100644 --- a/third_party/boringssl/kit/src/crypto/pkcs8/pkcs8.c +++ b/third_party/boringssl/kit/src/crypto/pkcs8/pkcs8.c @@ -486,6 +486,10 @@ int PKCS8_marshal_encrypted_private_key(CBB *out, int pbe_nid, goto err; } + // TODO(davidben): OpenSSL has since extended |pbe_nid| to control either the + // PBES1 scheme or the PBES2 PRF. E.g. passing |NID_hmacWithSHA256| will + // select PBES2 with HMAC-SHA256 as the PRF. Implement this if anything uses + // it. See 5693a30813a031d3921a016a870420e7eb93ec90 in OpenSSL. int alg_ok; if (pbe_nid == -1) { alg_ok = PKCS5_pbe2_encrypt_init(&epki, &ctx, cipher, (unsigned)iterations, diff --git a/third_party/boringssl/kit/src/crypto/pkcs8/pkcs8_test.cc b/third_party/boringssl/kit/src/crypto/pkcs8/pkcs8_test.cc index df275fb8..beb532f4 100644 --- a/third_party/boringssl/kit/src/crypto/pkcs8/pkcs8_test.cc +++ b/third_party/boringssl/kit/src/crypto/pkcs8/pkcs8_test.cc @@ -22,14 +22,15 @@ #include "../internal.h" -// kDER is a PKCS#8 encrypted private key. It was generated with: +// kEncryptedPBES2WithDESAndSHA1 is a PKCS#8 encrypted private key using PBES2 +// with DES-EDE3-CBC and HMAC-SHA-1. It was generated with: // // openssl genrsa 512 > test.key -// openssl pkcs8 -topk8 -in test.key -out test.key.encrypted -v2 des3 -outform der +// openssl pkcs8 -topk8 -in test.key -out test.key.encrypted -v2 des3 -v2prf hmacWithSHA1 -outform der // hexdump -Cv test.key.encrypted // // The password is "testing". -static const uint8_t kDER[] = { +static const uint8_t kEncryptedPBES2WithDESAndSHA1[] = { 0x30, 0x82, 0x01, 0x9e, 0x30, 0x40, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x05, 0x0d, 0x30, 0x33, 0x30, 0x1b, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x05, 0x0c, 0x30, 0x0e, 0x04, 0x08, 0x06, 0xa5, 0x4b, 0x0c, 0x0c, 0x50, 0x8c, 0x19, 0x02, 0x02, 0x08, 0x00, @@ -59,6 +60,55 @@ static const uint8_t kDER[] = { 0xd6, 0x2d, }; +// kEncryptedPBES2WithAESAndSHA256 is a PKCS#8 encrypted private key using PBES2 +// with AES-128-CBC and HMAC-SHA-256. It was generated with: +// +// openssl genrsa 512 > test.key +// openssl pkcs8 -topk8 -in test.key -out test.key.encrypted -v2 aes-128-cbc -v2prf hmacWithSHA256 -outform der +// hexdump -Cv test.key.encrypted +// +// The password is "testing". +static const uint8_t kEncryptedPBES2WithAESAndSHA256[] = { + 0x30, 0x82, 0x01, 0xbd, 0x30, 0x57, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, + 0xf7, 0x0d, 0x01, 0x05, 0x0d, 0x30, 0x4a, 0x30, 0x29, 0x06, 0x09, 0x2a, + 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x05, 0x0c, 0x30, 0x1c, 0x04, 0x08, + 0xd0, 0x39, 0xb7, 0x6d, 0xd0, 0xff, 0x85, 0xa8, 0x02, 0x02, 0x08, 0x00, + 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x09, + 0x05, 0x00, 0x30, 0x1d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, + 0x04, 0x01, 0x02, 0x04, 0x10, 0x95, 0xc6, 0x49, 0xc1, 0x61, 0x70, 0x74, + 0x36, 0xfe, 0xc0, 0x98, 0x19, 0x26, 0x32, 0x9e, 0x1a, 0x04, 0x82, 0x01, + 0x60, 0x87, 0xe3, 0x4d, 0xff, 0x33, 0x2b, 0x25, 0x07, 0x5f, 0x99, 0x24, + 0x70, 0x40, 0x29, 0xb4, 0xaa, 0xce, 0xdd, 0x93, 0x60, 0x5c, 0x65, 0xec, + 0xba, 0xee, 0xf8, 0x5e, 0xc7, 0x8f, 0x3e, 0x49, 0x00, 0xdf, 0xa7, 0xb2, + 0xbb, 0xa7, 0xf7, 0x74, 0x56, 0xe0, 0xeb, 0x33, 0xe2, 0x30, 0x60, 0x3b, + 0xd3, 0x34, 0x7b, 0xb0, 0x76, 0xc0, 0xed, 0xa2, 0x7d, 0x51, 0x99, 0x4d, + 0x52, 0x1c, 0x9e, 0xd7, 0x28, 0x58, 0x32, 0xcf, 0x55, 0xf0, 0x19, 0x87, + 0x5e, 0x66, 0x69, 0x00, 0x75, 0xd7, 0x68, 0x98, 0x64, 0x6a, 0x1e, 0x8c, + 0xef, 0x7b, 0xbc, 0x9e, 0xed, 0xaf, 0x67, 0xcf, 0xc4, 0x6c, 0x40, 0x8a, + 0x23, 0x73, 0xe6, 0x79, 0x5f, 0x7a, 0x15, 0x53, 0x2c, 0x70, 0x3b, 0x69, + 0xba, 0x3d, 0xfb, 0x6e, 0xb9, 0x27, 0x78, 0x9b, 0xc3, 0x4b, 0xb8, 0xe3, + 0xe7, 0x31, 0x82, 0x43, 0xee, 0x81, 0x5b, 0x01, 0x3b, 0x7e, 0x23, 0xb1, + 0xcc, 0x20, 0xc9, 0xe0, 0xca, 0x9d, 0xaa, 0x9c, 0xe9, 0x47, 0x96, 0x0d, + 0xc4, 0x1e, 0x1b, 0x1f, 0xb1, 0xee, 0x2b, 0x99, 0xaf, 0x2a, 0xb4, 0x9f, + 0x29, 0xb5, 0x9b, 0x83, 0x5e, 0xe5, 0x7e, 0xf7, 0xf7, 0x58, 0x31, 0x54, + 0xf6, 0x29, 0x6b, 0xfc, 0x85, 0x1d, 0x8a, 0x5f, 0x22, 0x03, 0xed, 0xce, + 0x06, 0x5b, 0x93, 0x57, 0x23, 0x4e, 0x0e, 0x5b, 0xf8, 0x29, 0x29, 0x7c, + 0x2d, 0x4a, 0xc6, 0x9a, 0x97, 0x64, 0x4c, 0x15, 0x72, 0xee, 0xaa, 0xd9, + 0xed, 0xfd, 0x8f, 0xa2, 0x36, 0xf5, 0xf8, 0xe7, 0xf7, 0xfe, 0x67, 0x4b, + 0xbe, 0x85, 0xe3, 0xda, 0x3a, 0xcc, 0x5f, 0x17, 0xbe, 0xa6, 0x1a, 0x38, + 0xed, 0x85, 0x4a, 0xd6, 0x05, 0x4b, 0x5f, 0x54, 0x0e, 0xfd, 0xdc, 0x32, + 0x9a, 0x0d, 0xca, 0xec, 0x02, 0x3f, 0x78, 0x23, 0x6e, 0x6a, 0xfa, 0x2c, + 0x04, 0x86, 0xc8, 0x74, 0xa6, 0xf7, 0x2f, 0x1a, 0xf1, 0x1a, 0x51, 0x09, + 0x2b, 0x04, 0xdc, 0x53, 0xaf, 0x39, 0x85, 0x35, 0x81, 0xc3, 0x11, 0xf0, + 0x7d, 0xb7, 0xb3, 0x77, 0x0e, 0x8e, 0x22, 0xda, 0x1f, 0xb0, 0x3d, 0x59, + 0xca, 0xa9, 0x70, 0xc3, 0x33, 0x66, 0xcb, 0x81, 0xfc, 0x85, 0x2a, 0xf0, + 0xbc, 0xd0, 0x30, 0x85, 0x1b, 0xe6, 0x9b, 0x76, 0x88, 0xca, 0xf1, 0xf5, + 0xc8, 0x19, 0x8a, 0x62, 0x16, 0x7b, 0x01, 0xc1, 0x1d, 0x80, 0xc0, 0xf7, + 0xc2, 0x0b, 0xe3, 0xbf, 0x83, 0x9a, 0x3c, 0xc0, 0x0f, 0x5e, 0xea, 0xf7, + 0xb2, 0x4c, 0xcd, 0x5e, 0xf0, 0xad, 0xa5, 0x98, 0x25, 0x62, 0x69, 0xba, + 0xd7, 0xab, 0x78, 0x59, 0xd0, +}; + // kNullPassword is a PKCS#8 encrypted private key using the null password. static const uint8_t kNullPassword[] = { 0x30, 0x81, 0xb0, 0x30, 0x1b, 0x06, 0x0a, 0x2a, 0x86, 0x48, 0x86, 0xf7, @@ -218,7 +268,10 @@ static void TestRoundTrip(int pbe_nid, const EVP_CIPHER *cipher, } TEST(PKCS8Test, DecryptString) { - TestDecrypt(kDER, sizeof(kDER), "testing"); + TestDecrypt(kEncryptedPBES2WithDESAndSHA1, + sizeof(kEncryptedPBES2WithDESAndSHA1), "testing"); + TestDecrypt(kEncryptedPBES2WithAESAndSHA256, + sizeof(kEncryptedPBES2WithAESAndSHA256), "testing"); } TEST(PKCS8Test, DecryptNull) { diff --git a/third_party/boringssl/kit/src/crypto/pkcs8/pkcs8_x509.c b/third_party/boringssl/kit/src/crypto/pkcs8/pkcs8_x509.c index 2c7841ee..4458b56f 100644 --- a/third_party/boringssl/kit/src/crypto/pkcs8/pkcs8_x509.c +++ b/third_party/boringssl/kit/src/crypto/pkcs8/pkcs8_x509.c @@ -293,6 +293,10 @@ err: return ret; } +// 1.2.840.113549.1.12.10.1.1 +static const uint8_t kKeyBag[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, + 0x01, 0x0c, 0x0a, 0x01, 0x01}; + // 1.2.840.113549.1.12.10.1.2 static const uint8_t kPKCS8ShroudedKeyBag[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x0a, 0x01, 0x02}; @@ -392,16 +396,20 @@ static int PKCS12_handle_safe_bag(CBS *safe_bag, struct pkcs12_context *ctx) { return 0; } - if (CBS_mem_equal(&bag_id, kPKCS8ShroudedKeyBag, - sizeof(kPKCS8ShroudedKeyBag))) { - // See RFC 7292, section 4.2.2. + const int is_key_bag = CBS_mem_equal(&bag_id, kKeyBag, sizeof(kKeyBag)); + const int is_shrouded_key_bag = CBS_mem_equal(&bag_id, kPKCS8ShroudedKeyBag, + sizeof(kPKCS8ShroudedKeyBag)); + if (is_key_bag || is_shrouded_key_bag) { + // See RFC 7292, section 4.2.1 and 4.2.2. if (*ctx->out_key) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_MULTIPLE_PRIVATE_KEYS_IN_PKCS12); return 0; } - EVP_PKEY *pkey = PKCS8_parse_encrypted_private_key( - &wrapped_value, ctx->password, ctx->password_len); + EVP_PKEY *pkey = + is_key_bag ? EVP_parse_private_key(&wrapped_value) + : PKCS8_parse_encrypted_private_key( + &wrapped_value, ctx->password, ctx->password_len); if (pkey == NULL) { return 0; } @@ -902,9 +910,25 @@ int PKCS12_parse(const PKCS12 *p12, const char *password, EVP_PKEY **out_pkey, return 0; } + // OpenSSL selects the last certificate which matches the private key as + // |out_cert|. + // + // TODO(davidben): OpenSSL additionally reverses the order of the + // certificates, which was likely originally a bug, but may be a feature by + // now. See https://crbug.com/boringssl/250 and + // https://github.com/openssl/openssl/issues/6698. *out_cert = NULL; - if (sk_X509_num(ca_certs) > 0) { - *out_cert = sk_X509_shift(ca_certs); + size_t num_certs = sk_X509_num(ca_certs); + if (*out_pkey != NULL && num_certs > 0) { + for (size_t i = num_certs - 1; i < num_certs; i--) { + X509 *cert = sk_X509_value(ca_certs, i); + if (X509_check_private_key(cert, *out_pkey)) { + *out_cert = cert; + sk_X509_delete(ca_certs, i); + break; + } + ERR_clear_error(); + } } if (out_ca_certs) { diff --git a/third_party/boringssl/kit/src/crypto/pool/internal.h b/third_party/boringssl/kit/src/crypto/pool/internal.h index 5b288ebb..ed91de61 100644 --- a/third_party/boringssl/kit/src/crypto/pool/internal.h +++ b/third_party/boringssl/kit/src/crypto/pool/internal.h @@ -23,7 +23,7 @@ extern "C" { #endif -DECLARE_LHASH_OF(CRYPTO_BUFFER); +DECLARE_LHASH_OF(CRYPTO_BUFFER) struct crypto_buffer_st { CRYPTO_BUFFER_POOL *pool; diff --git a/third_party/boringssl/kit/src/crypto/rand_extra/rand_test.cc b/third_party/boringssl/kit/src/crypto/rand_extra/rand_test.cc index 9bc5d970..9c69b8f6 100644 --- a/third_party/boringssl/kit/src/crypto/rand_extra/rand_test.cc +++ b/third_party/boringssl/kit/src/crypto/rand_extra/rand_test.cc @@ -21,6 +21,7 @@ #include #include +#include "../fipsmodule/rand/internal.h" #include "../test/abi_test.h" #include "../test/test_util.h" @@ -189,23 +190,18 @@ TEST(RandTest, Threads) { #endif // OPENSSL_THREADS #if defined(OPENSSL_X86_64) && defined(SUPPORTS_ABI_TEST) -extern "C" { -int CRYPTO_rdrand(uint8_t out[8]); -int CRYPTO_rdrand_multiple8_buf(uint8_t *buf, size_t len); -} // extern "C" - TEST(RandTest, RdrandABI) { - if ((OPENSSL_ia32cap_P[1] & (1u << 30)) == 0) { + if (!have_rdrand()) { fprintf(stderr, "rdrand not supported. Skipping.\n"); return; } uint8_t buf[32]; - CHECK_ABI(CRYPTO_rdrand, buf); - CHECK_ABI(CRYPTO_rdrand_multiple8_buf, nullptr, 0); - CHECK_ABI(CRYPTO_rdrand_multiple8_buf, buf, 8); - CHECK_ABI(CRYPTO_rdrand_multiple8_buf, buf, 16); - CHECK_ABI(CRYPTO_rdrand_multiple8_buf, buf, 24); - CHECK_ABI(CRYPTO_rdrand_multiple8_buf, buf, 32); + CHECK_ABI_SEH(CRYPTO_rdrand, buf); + CHECK_ABI_SEH(CRYPTO_rdrand_multiple8_buf, nullptr, 0); + CHECK_ABI_SEH(CRYPTO_rdrand_multiple8_buf, buf, 8); + CHECK_ABI_SEH(CRYPTO_rdrand_multiple8_buf, buf, 16); + CHECK_ABI_SEH(CRYPTO_rdrand_multiple8_buf, buf, 24); + CHECK_ABI_SEH(CRYPTO_rdrand_multiple8_buf, buf, 32); } #endif // OPENSSL_X86_64 && SUPPORTS_ABI_TEST diff --git a/third_party/boringssl/kit/src/crypto/rsa_extra/rsa_test.cc b/third_party/boringssl/kit/src/crypto/rsa_extra/rsa_test.cc index 9bd47b1b..ed1630d9 100644 --- a/third_party/boringssl/kit/src/crypto/rsa_extra/rsa_test.cc +++ b/third_party/boringssl/kit/src/crypto/rsa_extra/rsa_test.cc @@ -461,7 +461,8 @@ TEST_P(RSAEncryptTest, TestKey) { } } -INSTANTIATE_TEST_CASE_P(, RSAEncryptTest, testing::ValuesIn(kRSAEncryptParams)); +INSTANTIATE_TEST_SUITE_P(, RSAEncryptTest, + testing::ValuesIn(kRSAEncryptParams)); TEST(RSATest, TestDecrypt) { bssl::UniquePtr rsa( diff --git a/third_party/boringssl/kit/src/crypto/stack/stack.c b/third_party/boringssl/kit/src/crypto/stack/stack.c index 93b9d1b0..599bd7b1 100644 --- a/third_party/boringssl/kit/src/crypto/stack/stack.c +++ b/third_party/boringssl/kit/src/crypto/stack/stack.c @@ -56,6 +56,7 @@ #include +#include #include #include @@ -272,36 +273,39 @@ int sk_find(const _STACK *sk, size_t *out_index, const void *p, return 0; } - // sk->comp is a function that takes pointers to pointers to elements, but - // qsort and bsearch take a comparison function that just takes pointers to - // elements. However, since we're passing an array of pointers to - // qsort/bsearch, we can just cast the comparison function and everything - // works. + // The stack is sorted, so binary search to find the element. // - // TODO(davidben): This is undefined behavior, but the call is in libc so, - // e.g., CFI does not notice. Unfortunately, |bsearch| is missing a void* - // parameter in its callback and |bsearch_s| is a mess of incompatibility. - const void *const *r = bsearch(&p, sk->data, sk->num, sizeof(void *), - (int (*)(const void *, const void *))sk->comp); - if (r == NULL) { - return 0; - } - size_t idx = ((void **)r) - sk->data; - // This function always returns the first result. Note this logic is, in the - // worst case, O(N) rather than O(log(N)). If this ever becomes a problem, - // restore https://boringssl-review.googlesource.com/c/boringssl/+/32115/ - // which integrates the preference into the binary search. - while (idx > 0) { - const void *elem = sk->data[idx - 1]; - if (call_cmp_func(sk->comp, &p, &elem) != 0) { - break; + // |lo| and |hi| maintain a half-open interval of where the answer may be. All + // indices such that |lo <= idx < hi| are candidates. + size_t lo = 0, hi = sk->num; + while (lo < hi) { + // Bias |mid| towards |lo|. See the |r == 0| case below. + size_t mid = lo + (hi - lo - 1) / 2; + assert(lo <= mid && mid < hi); + const void *elem = sk->data[mid]; + int r = call_cmp_func(sk->comp, &p, &elem); + if (r > 0) { + lo = mid + 1; // |mid| is too low. + } else if (r < 0) { + hi = mid; // |mid| is too high. + } else { + // |mid| matches. However, this function returns the earliest match, so we + // can only return if the range has size one. + if (hi - lo == 1) { + if (out_index != NULL) { + *out_index = mid; + } + return 1; + } + // The sample is biased towards |lo|. |mid| can only be |hi - 1| if + // |hi - lo| was one, so this makes forward progress. + assert(mid + 1 < hi); + hi = mid + 1; } - idx--; } - if (out_index) { - *out_index = idx; - } - return 1; + + assert(lo == hi); + return 0; // Not found. } void *sk_shift(_STACK *sk) { @@ -358,20 +362,24 @@ err: } void sk_sort(_STACK *sk) { - int (*comp_func)(const void *,const void *); - if (sk == NULL || sk->comp == NULL || sk->sorted) { return; } - // See the comment in sk_find about this cast. + // sk->comp is a function that takes pointers to pointers to elements, but + // qsort take a comparison function that just takes pointers to elements. + // However, since we're passing an array of pointers to qsort, we can just + // cast the comparison function and everything works. // // TODO(davidben): This is undefined behavior, but the call is in libc so, // e.g., CFI does not notice. Unfortunately, |qsort| is missing a void* // parameter in its callback and |qsort_s| / |qsort_r| are a mess of // incompatibility. - comp_func = (int (*)(const void *, const void *))(sk->comp); - qsort(sk->data, sk->num, sizeof(void *), comp_func); + if (sk->num >= 2) { + int (*comp_func)(const void *, const void *) = + (int (*)(const void *, const void *))(sk->comp); + qsort(sk->data, sk->num, sizeof(void *), comp_func); + } sk->sorted = 1; } diff --git a/third_party/boringssl/kit/src/crypto/test/CMakeLists.txt b/third_party/boringssl/kit/src/crypto/test/CMakeLists.txt index d2e4cdf2..b968fd78 100644 --- a/third_party/boringssl/kit/src/crypto/test/CMakeLists.txt +++ b/third_party/boringssl/kit/src/crypto/test/CMakeLists.txt @@ -15,6 +15,9 @@ if (LIBUNWIND_FOUND) target_include_directories(test_support_lib PRIVATE ${LIBUNWIND_INCLUDE_DIRS}) target_link_libraries(test_support_lib ${LIBUNWIND_LDFLAGS}) endif() +if(WIN32) + target_link_libraries(test_support_lib dbghelp) +endif() add_dependencies(test_support_lib global_target) add_library( diff --git a/third_party/boringssl/kit/src/crypto/test/abi_test.cc b/third_party/boringssl/kit/src/crypto/test/abi_test.cc index 6530ddf9..9844c73c 100644 --- a/third_party/boringssl/kit/src/crypto/test/abi_test.cc +++ b/third_party/boringssl/kit/src/crypto/test/abi_test.cc @@ -25,10 +25,9 @@ #include #include -#if defined(OPENSSL_LINUX) && defined(SUPPORTS_ABI_TEST) && \ - defined(BORINGSSL_HAVE_LIBUNWIND) -#define UNWIND_TEST_SIGTRAP - +#if defined(OPENSSL_X86_64) && defined(SUPPORTS_ABI_TEST) +#if defined(OPENSSL_LINUX) && defined(BORINGSSL_HAVE_LIBUNWIND) +#define SUPPORTS_UNWIND_TEST #define UNW_LOCAL_ONLY #include #include @@ -40,7 +39,14 @@ #include #include #include -#endif // LINUX && SUPPORTS_ABI_TEST && HAVE_LIBUNWIND +#elif defined(OPENSSL_WINDOWS) +#define SUPPORTS_UNWIND_TEST +OPENSSL_MSVC_PRAGMA(warning(push, 3)) +#include +#include +OPENSSL_MSVC_PRAGMA(warning(pop)) +#endif +#endif // X86_64 && SUPPORTS_ABI_TEST namespace abi_test { @@ -116,11 +122,558 @@ crypto_word_t RunTrampoline(Result *out, crypto_word_t func, } #endif // SUPPORTS_ABI_TEST -#if defined(UNWIND_TEST_SIGTRAP) -// On Linux, we test unwind metadata using libunwind and |SIGTRAP|. We run the -// function under test with the trap flag set. This results in |SIGTRAP|s on -// every instruction. We then handle these signals and verify with libunwind. +#if defined(SUPPORTS_UNWIND_TEST) +// We test unwind metadata by running the function under test with the trap flag +// set. This results in |SIGTRAP| and |EXCEPTION_SINGLE_STEP| on Linux and +// Windows, respectively. We hande these and verify libunwind or the Windows +// unwind APIs unwind successfully. +// IsAncestorStackFrame returns true if |a_sp| is an ancestor stack frame of +// |b_sp|. +static bool IsAncestorStackFrame(crypto_word_t a_sp, crypto_word_t b_sp) { +#if defined(OPENSSL_X86_64) + // The stack grows down, so ancestor stack frames have higher addresses. + return a_sp > b_sp; +#else +#error "unknown architecture" +#endif +} + +// Implement some string formatting utilties. Ideally we would use |snprintf|, +// but this is called in a signal handler and |snprintf| is not async-signal- +// safe. + +#if !defined(OPENSSL_WINDOWS) +static std::array WordToDecimal( + crypto_word_t v) { + std::array ret; + size_t len = 0; + do { + ret[len++] = '0' + v % 10; + v /= 10; + } while (v != 0); + for (size_t i = 0; i < len / 2; i++) { + std::swap(ret[i], ret[len - 1 - i]); + } + ret[len] = '\0'; + return ret; +} +#endif // !OPENSSL_WINDOWS + +static std::array WordToHex( + crypto_word_t v) { + static const char kHex[] = "0123456789abcdef"; + std::array ret; + for (size_t i = sizeof(crypto_word_t) - 1; i < sizeof(crypto_word_t); i--) { + uint8_t b = v & 0xff; + v >>= 8; + ret[i * 2] = kHex[b >> 4]; + ret[i * 2 + 1] = kHex[b & 0xf]; + } + ret[sizeof(crypto_word_t) * 2] = '\0'; + return ret; +} + +static void StrCatSignalSafeImpl(bssl::Span out) {} + +template +static void StrCatSignalSafeImpl(bssl::Span out, const char *str, + Args... args) { + BUF_strlcat(out.data(), str, out.size()); + StrCatSignalSafeImpl(out, args...); +} + +template +static void StrCatSignalSafe(bssl::Span out, Args... args) { + if (out.empty()) { + return; + } + out[0] = '\0'; + StrCatSignalSafeImpl(out, args...); +} + +template +[[noreturn]] static void FatalError(Args... args) { + // We cannot use |snprintf| here because it is not async-signal-safe. + char buf[512]; + StrCatSignalSafe(buf, args..., "\n"); +#if defined(OPENSSL_WINDOWS) + HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE); + if (stderr_handle != INVALID_HANDLE_VALUE) { + DWORD unused; + WriteFile(stderr_handle, buf, strlen(buf), &unused, nullptr); + } +#else + write(STDERR_FILENO, buf, strlen(buf)); +#endif + abort(); +} + +class UnwindStatus { + public: + UnwindStatus() : err_(nullptr) {} + explicit UnwindStatus(const char *err) : err_(err) {} + + bool ok() const { return err_ == nullptr; } + const char *Error() const { return err_; } + + private: + const char *err_; +}; + +template +class UnwindStatusOr { + public: + UnwindStatusOr(UnwindStatus status) : status_(status) { + assert(!status_.ok()); + } + + UnwindStatusOr(const T &value) : status_(UnwindStatus()), value_(value) {} + + bool ok() const { return status_.ok(); } + const char *Error() const { return status_.Error(); } + + const T &ValueOrDie(const char *msg = "Unexpected error") const { + if (!ok()) { + FatalError(msg, ": ", Error()); + } + return value_; + } + + private: + UnwindStatus status_; + T value_; +}; + +// UnwindCursor abstracts between libunwind and Windows unwind APIs. It is +// async-signal-safe. +#if defined(OPENSSL_WINDOWS) +class UnwindCursor { + public: + explicit UnwindCursor(const CONTEXT &ctx) : ctx_(ctx) { + starting_ip_ = ctx_.Rip; + } + + crypto_word_t starting_ip() const { return starting_ip_; } + + // Step unwinds the cursor by one frame. On success, it returns whether there + // were more frames to unwind. + UnwindStatusOr Step() { + bool is_top = is_top_; + is_top_ = false; + + DWORD64 image_base; + RUNTIME_FUNCTION *entry = + RtlLookupFunctionEntry(ctx_.Rip, &image_base, nullptr); + if (entry == nullptr) { + // This is a leaf function. Leaf functions do not touch stack or + // callee-saved registers, so they may be unwound by simulating a ret. + if (!is_top) { + return UnwindStatus("leaf function found below the top frame"); + } + memcpy(&ctx_.Rip, reinterpret_cast(ctx_.Rsp), + sizeof(ctx_.Rip)); + ctx_.Rsp += 8; + return true; + } + + // This is a frame function. Call into the Windows unwinder. + void *handler_data; + DWORD64 establisher_frame; + RtlVirtualUnwind(UNW_FLAG_NHANDLER, image_base, ctx_.Rip, entry, &ctx_, + &handler_data, &establisher_frame, nullptr); + return ctx_.Rip != 0; + } + + // GetIP returns the instruction pointer at the current frame. + UnwindStatusOr GetIP() { return ctx_.Rip; } + + // GetSP returns the stack pointer at the current frame. + UnwindStatusOr GetSP() { return ctx_.Rsp; } + + // GetCallerState returns the callee-saved registers at the current frame. + UnwindStatusOr GetCallerState() { + CallerState state; + state.rbx = ctx_.Rbx; + state.rbp = ctx_.Rbp; + state.rdi = ctx_.Rdi; + state.rsi = ctx_.Rsi; + state.r12 = ctx_.R12; + state.r13 = ctx_.R13; + state.r14 = ctx_.R14; + state.r15 = ctx_.R15; + memcpy(&state.xmm6, &ctx_.Xmm6, sizeof(Reg128)); + memcpy(&state.xmm7, &ctx_.Xmm7, sizeof(Reg128)); + memcpy(&state.xmm8, &ctx_.Xmm8, sizeof(Reg128)); + memcpy(&state.xmm9, &ctx_.Xmm9, sizeof(Reg128)); + memcpy(&state.xmm10, &ctx_.Xmm10, sizeof(Reg128)); + memcpy(&state.xmm11, &ctx_.Xmm11, sizeof(Reg128)); + memcpy(&state.xmm12, &ctx_.Xmm12, sizeof(Reg128)); + memcpy(&state.xmm13, &ctx_.Xmm13, sizeof(Reg128)); + memcpy(&state.xmm14, &ctx_.Xmm14, sizeof(Reg128)); + memcpy(&state.xmm15, &ctx_.Xmm15, sizeof(Reg128)); + return state; + } + + // ToString returns a human-readable representation of the address the cursor + // started at. + const char *ToString() { + StrCatSignalSafe(starting_ip_buf_, "0x", WordToHex(starting_ip_).data()); + return starting_ip_buf_; + } + + private: + CONTEXT ctx_; + crypto_word_t starting_ip_; + char starting_ip_buf_[64]; + bool is_top_ = true; +}; +#else // !OPENSSL_WINDOWS +class UnwindCursor { + public: + explicit UnwindCursor(unw_context_t *ctx) : ctx_(ctx) { + int ret = InitAtSignalFrame(&cursor_); + if (ret < 0) { + FatalError("Error getting unwind context: ", unw_strerror(ret)); + } + starting_ip_ = GetIP().ValueOrDie("Error getting instruction pointer"); + } + + // Step unwinds the cursor by one frame. On success, it returns whether there + // were more frames to unwind. + UnwindStatusOr Step() { + int ret = unw_step(&cursor_); + if (ret < 0) { + return UNWError(ret); + } + return ret != 0; + } + + // GetIP returns the instruction pointer at the current frame. + UnwindStatusOr GetIP() { + crypto_word_t ip; + int ret = GetReg(&ip, UNW_REG_IP); + if (ret < 0) { + return UNWError(ret); + } + return ip; + } + + // GetSP returns the stack pointer at the current frame. + UnwindStatusOr GetSP() { + crypto_word_t sp; + int ret = GetReg(&sp, UNW_REG_SP); + if (ret < 0) { + return UNWError(ret); + } + return sp; + } + + // GetCallerState returns the callee-saved registers at the current frame. + UnwindStatusOr GetCallerState() { + CallerState state; + int ret = 0; +#if defined(OPENSSL_X86_64) + ret = ret < 0 ? ret : GetReg(&state.rbx, UNW_X86_64_RBX); + ret = ret < 0 ? ret : GetReg(&state.rbp, UNW_X86_64_RBP); + ret = ret < 0 ? ret : GetReg(&state.r12, UNW_X86_64_R12); + ret = ret < 0 ? ret : GetReg(&state.r13, UNW_X86_64_R13); + ret = ret < 0 ? ret : GetReg(&state.r14, UNW_X86_64_R14); + ret = ret < 0 ? ret : GetReg(&state.r15, UNW_X86_64_R15); +#else +#error "unknown architecture" +#endif + if (ret < 0) { + return UNWError(ret); + } + return state; + } + + // ToString returns a human-readable representation of the address the cursor + // started at, using debug information if available. + const char *ToString() { + // Use a new cursor. |cursor_| has already been unwound, and + // |unw_get_proc_name| is slow so we do not sample it unconditionally in the + // constructor. + unw_cursor_t cursor; + unw_word_t off; + if (InitAtSignalFrame(&cursor) != 0 || + unw_get_proc_name(&cursor, starting_ip_buf_, sizeof(starting_ip_buf_), + &off) != 0) { + StrCatSignalSafe(starting_ip_buf_, "0x", WordToHex(starting_ip_).data()); + return starting_ip_buf_; + } + size_t len = strlen(starting_ip_buf_); + // Print the offset in decimal, to match gdb's disassembly output and ease + // debugging. + StrCatSignalSafe(bssl::Span(starting_ip_buf_).subspan(len), "+", + WordToDecimal(off).data(), " (0x", + WordToHex(starting_ip_).data(), ")"); + return starting_ip_buf_; + } + + private: + static UnwindStatus UNWError(int ret) { + assert(ret < 0); + const char *msg = unw_strerror(ret); + return UnwindStatus(msg == nullptr ? "unknown error" : msg); + } + + int InitAtSignalFrame(unw_cursor_t *cursor) { + // Work around a bug in libunwind which breaks rax and rdx recovery. This + // breaks functions which temporarily use rax as the CFA register. See + // https://git.savannah.gnu.org/gitweb/?p=libunwind.git;a=commit;h=819bf51bbd2da462c2ec3401e8ac9153b6e725e3 + OPENSSL_memset(cursor, 0, sizeof(*cursor)); + int ret = unw_init_local(cursor, ctx_); + if (ret < 0) { + return ret; + } + for (;;) { + ret = unw_is_signal_frame(cursor); + if (ret < 0) { + return ret; + } + if (ret != 0) { + return 0; // Found the signal frame. + } + ret = unw_step(cursor); + if (ret < 0) { + return ret; + } + } + } + + int GetReg(crypto_word_t *out, unw_regnum_t reg) { + unw_word_t val; + int ret = unw_get_reg(&cursor_, reg, &val); + if (ret >= 0) { + static_assert(sizeof(crypto_word_t) == sizeof(unw_word_t), + "crypto_word_t and unw_word_t are inconsistent"); + *out = val; + } + return ret; + } + + unw_context_t *ctx_; + unw_cursor_t cursor_; + crypto_word_t starting_ip_; + char starting_ip_buf_[64]; +}; +#endif // OPENSSL_WINDOWS + +// g_in_trampoline is true if we are in an instrumented |abi_test_trampoline| +// call, in the region that triggers |SIGTRAP|. +static bool g_in_trampoline = false; +// g_unwind_function_done, if |g_in_trampoline| is true, is whether the function +// under test has returned. It is undefined otherwise. +static bool g_unwind_function_done; +// g_trampoline_state, if |g_in_trampoline| is true, is the state the function +// under test must preserve. It is undefined otherwise. +static CallerState g_trampoline_state; +// g_trampoline_sp, if |g_in_trampoline| is true, is the stack pointer of the +// trampoline frame. It is undefined otherwise. +static crypto_word_t g_trampoline_sp; + +// kMaxUnwindErrors is the maximum number of unwind errors reported per +// function. If a function's unwind tables are wrong, we are otherwise likely to +// repeat the same error at multiple addresses. +static constexpr size_t kMaxUnwindErrors = 10; + +// Errors are saved in a signal handler. We use a static buffer to avoid +// allocation. +static size_t g_num_unwind_errors = 0; + +struct UnwindError { +#if defined(OPENSSL_WINDOWS) + crypto_word_t ip; +#endif + char str[512]; +}; + +static UnwindError g_unwind_errors[kMaxUnwindErrors]; + +template +static void AddUnwindError(UnwindCursor *cursor, Args... args) { + if (g_num_unwind_errors >= kMaxUnwindErrors) { + return; + } +#if defined(OPENSSL_WINDOWS) + // Windows symbol functions should not be called when handling an + // exception. Stash the instruction pointer, to be symbolized later. + g_unwind_errors[g_num_unwind_errors].ip = cursor->starting_ip(); + StrCatSignalSafe(g_unwind_errors[g_num_unwind_errors].str, args...); +#else + StrCatSignalSafe(g_unwind_errors[g_num_unwind_errors].str, + "unwinding at ", cursor->ToString(), ": ", args...); +#endif + g_num_unwind_errors++; +} + +static void CheckUnwind(UnwindCursor *cursor) { + const crypto_word_t kStartAddress = + reinterpret_cast(&abi_test_unwind_start); + const crypto_word_t kReturnAddress = + reinterpret_cast(&abi_test_unwind_return); + const crypto_word_t kStopAddress = + reinterpret_cast(&abi_test_unwind_stop); + + crypto_word_t sp = cursor->GetSP().ValueOrDie("Error getting stack pointer"); + crypto_word_t ip = + cursor->GetIP().ValueOrDie("Error getting instruction pointer"); + if (!g_in_trampoline) { + if (ip != kStartAddress) { + FatalError("Unexpected SIGTRAP at ", cursor->ToString()); + } + + // Save the current state and begin. + g_in_trampoline = true; + g_unwind_function_done = false; + g_trampoline_sp = sp; + g_trampoline_state = cursor->GetCallerState().ValueOrDie( + "Error getting initial caller state"); + } else { + if (sp == g_trampoline_sp || g_unwind_function_done) { + // |g_unwind_function_done| should imply |sp| is |g_trampoline_sp|, but + // clearing the trap flag in x86 briefly displaces the stack pointer. + // + // Also note we check both |ip| and |sp| below, in case the function under + // test is also |abi_test_trampoline|. + if (ip == kReturnAddress && sp == g_trampoline_sp) { + g_unwind_function_done = true; + } + if (ip == kStopAddress && sp == g_trampoline_sp) { + // |SIGTRAP| is fatal again. + g_in_trampoline = false; + } + } else if (IsAncestorStackFrame(sp, g_trampoline_sp)) { + // This should never happen. We went past |g_trampoline_sp| without + // stopping at |kStopAddress|. + AddUnwindError(cursor, "stack frame is before caller"); + g_in_trampoline = false; + } else if (g_num_unwind_errors < kMaxUnwindErrors) { + for (;;) { + UnwindStatusOr step_ret = cursor->Step(); + if (!step_ret.ok()) { + AddUnwindError(cursor, "error unwinding: ", step_ret.Error()); + break; + } + // |Step| returns whether there was a frame to unwind. + if (!step_ret.ValueOrDie()) { + AddUnwindError(cursor, "could not unwind to starting frame"); + break; + } + + UnwindStatusOr cur_sp = cursor->GetSP(); + if (!cur_sp.ok()) { + AddUnwindError(cursor, + "error recovering stack pointer: ", cur_sp.Error()); + break; + } + if (IsAncestorStackFrame(cur_sp.ValueOrDie(), g_trampoline_sp)) { + AddUnwindError(cursor, "unwound past starting frame"); + break; + } + if (cur_sp.ValueOrDie() == g_trampoline_sp) { + // We found the parent frame. Check the return address. + UnwindStatusOr cur_ip = cursor->GetIP(); + if (!cur_ip.ok()) { + AddUnwindError(cursor, + "error recovering return address: ", cur_ip.Error()); + } else if (cur_ip.ValueOrDie() != kReturnAddress) { + AddUnwindError(cursor, "wrong return address"); + } + + // Check the remaining registers. + UnwindStatusOr state = cursor->GetCallerState(); + if (!state.ok()) { + AddUnwindError(cursor, + "error recovering registers: ", state.Error()); + } else { + ForEachMismatch(state.ValueOrDie(), g_trampoline_state, + [&](const char *reg) { + AddUnwindError(cursor, reg, " was not recovered"); + }); + } + break; + } + } + } + } +} + +static void ReadUnwindResult(Result *out) { + for (size_t i = 0; i < g_num_unwind_errors; i++) { +#if defined(OPENSSL_WINDOWS) + const crypto_word_t ip = g_unwind_errors[i].ip; + char buf[256]; + DWORD64 displacement; + struct { + SYMBOL_INFO info; + char name_buf[128]; + } symbol; + memset(&symbol, 0, sizeof(symbol)); + symbol.info.SizeOfStruct = sizeof(symbol.info); + symbol.info.MaxNameLen = sizeof(symbol.name_buf); + if (SymFromAddr(GetCurrentProcess(), ip, &displacement, &symbol.info)) { + snprintf(buf, sizeof(buf), "unwinding at %s+%llu (0x%s): %s", + symbol.info.Name, displacement, WordToHex(ip).data(), + g_unwind_errors[i].str); + } else { + snprintf(buf, sizeof(buf), "unwinding at 0x%s: %s", + WordToHex(ip).data(), g_unwind_errors[i].str); + } + out->errors.emplace_back(buf); +#else + out->errors.emplace_back(g_unwind_errors[i].str); +#endif + } + if (g_num_unwind_errors == kMaxUnwindErrors) { + out->errors.emplace_back("(additional errors omitted)"); + } + g_num_unwind_errors = 0; +} + +#if defined(OPENSSL_WINDOWS) +static DWORD g_main_thread; + +static long ExceptionHandler(EXCEPTION_POINTERS *info) { + if (info->ExceptionRecord->ExceptionCode != EXCEPTION_SINGLE_STEP || + GetCurrentThreadId() != g_main_thread) { + return EXCEPTION_CONTINUE_SEARCH; + } + + UnwindCursor cursor(*info->ContextRecord); + CheckUnwind(&cursor); + if (g_in_trampoline) { + // Windows clears the trap flag, so we must restore it. + info->ContextRecord->EFlags |= 0x100; + } + return EXCEPTION_CONTINUE_EXECUTION; +} + +static void EnableUnwindTestsImpl() { + if (IsDebuggerPresent()) { + // Unwind tests drive logic via |EXCEPTION_SINGLE_STEP|, which conflicts with + // debuggers. + fprintf(stderr, "Debugger detected. Disabling unwind tests.\n"); + return; + } + + g_main_thread = GetCurrentThreadId(); + + SymSetOptions(SYMOPT_DEFERRED_LOADS); + if (!SymInitialize(GetCurrentProcess(), nullptr, TRUE)) { + fprintf(stderr, "Could not initialize symbols.\n"); + } + + if (AddVectoredExceptionHandler(0, ExceptionHandler) == nullptr) { + fprintf(stderr, "Error installing exception handler.\n"); + abort(); + } + + g_unwind_tests_enabled = true; +} +#else // !OPENSSL_WINDOWS // HandleEINTR runs |func| and returns the result, retrying the operation on // |EINTR|. template @@ -170,171 +723,8 @@ static bool IsBeingDebugged() { return idx < status.size() && status[idx] != '0'; } -// IsAncestorStackFrame returns true if |a_sp| is an ancestor stack frame of -// |b_sp|. -static bool IsAncestorStackFrame(unw_word_t a_sp, unw_word_t b_sp) { -#if defined(OPENSSL_X86_64) - // The stack grows down, so ancestor stack frames have higher addresses. - return a_sp > b_sp; -#else -#error "unknown architecture" -#endif -} - -static int CallerStateFromUNWCursor(CallerState *out, unw_cursor_t *cursor) { - // |CallerState| uses |crypto_word_t|, while libunwind uses |unw_word_t|, but - // both are defined as |uint*_t| from stdint.h, so we can assume the types - // match. -#if defined(OPENSSL_X86_64) - int ret = 0; - ret = ret < 0 ? ret : unw_get_reg(cursor, UNW_X86_64_RBX, &out->rbx); - ret = ret < 0 ? ret : unw_get_reg(cursor, UNW_X86_64_RBP, &out->rbp); - ret = ret < 0 ? ret : unw_get_reg(cursor, UNW_X86_64_R12, &out->r12); - ret = ret < 0 ? ret : unw_get_reg(cursor, UNW_X86_64_R13, &out->r13); - ret = ret < 0 ? ret : unw_get_reg(cursor, UNW_X86_64_R14, &out->r14); - ret = ret < 0 ? ret : unw_get_reg(cursor, UNW_X86_64_R15, &out->r15); - return ret; -#else -#error "unknown architecture" -#endif -} - -// Implement some string formatting utilties. Ideally we would use |snprintf|, -// but this is called in a signal handler and |snprintf| is not async-signal- -// safe. - -static std::array WordToDecimal( - unw_word_t v) { - std::array ret; - size_t len = 0; - do { - ret[len++] = '0' + v % 10; - v /= 10; - } while (v != 0); - for (size_t i = 0; i < len / 2; i++) { - std::swap(ret[i], ret[len - 1 - i]); - } - ret[len] = '\0'; - return ret; -} - -static std::array WordToHex(unw_word_t v) { - static const char kHex[] = "0123456789abcdef"; - std::array ret; - for (size_t i = sizeof(unw_word_t) - 1; i < sizeof(unw_word_t); i--) { - uint8_t b = v & 0xff; - v >>= 8; - ret[i * 2] = kHex[b >> 4]; - ret[i * 2 + 1] = kHex[b & 0xf]; - } - ret[sizeof(unw_word_t) * 2] = '\0'; - return ret; -} - -static void StrCatSignalSafeImpl(bssl::Span out) {} - -template -static void StrCatSignalSafeImpl(bssl::Span out, const char *str, - Args... args) { - BUF_strlcat(out.data(), str, out.size()); - StrCatSignalSafeImpl(out, args...); -} - -template -static void StrCatSignalSafe(bssl::Span out, Args... args) { - if (out.empty()) { - return; - } - out[0] = '\0'; - StrCatSignalSafeImpl(out, args...); -} - -static int UnwindToSignalFrame(unw_cursor_t *cursor) { - for (;;) { - int ret = unw_is_signal_frame(cursor); - if (ret < 0) { - return ret; - } - if (ret != 0) { - return 0; // Found the signal frame. - } - ret = unw_step(cursor); - if (ret < 0) { - return ret; - } - } -} - -// IPToString returns a human-readable representation of |ip|, using debug -// information from |ctx| if available. |ip| must be the address of |ctx|'s -// signal frame. This function is async-signal-safe. -static std::array IPToString(unw_word_t ip, unw_context_t *ctx) { - std::array ret; - // Use a new cursor. The caller's cursor has already been unwound, but - // |unw_get_proc_name| is slow so we do not wish to call it all the time. - unw_cursor_t cursor; - // Work around a bug in libunwind. See - // https://git.savannah.gnu.org/gitweb/?p=libunwind.git;a=commit;h=819bf51bbd2da462c2ec3401e8ac9153b6e725e3 - OPENSSL_memset(&cursor, 0, sizeof(cursor)); - unw_word_t off; - if (unw_init_local(&cursor, ctx) != 0 || - UnwindToSignalFrame(&cursor) != 0 || - unw_get_proc_name(&cursor, ret.data(), ret.size(), &off) != 0) { - StrCatSignalSafe(bssl::MakeSpan(ret), "0x", WordToHex(ip).data()); - return ret; - } - size_t len = strlen(ret.data()); - // Print the offset in decimal, to match gdb's disassembly output and ease - // debugging. - StrCatSignalSafe(bssl::MakeSpan(ret).subspan(len), "+", - WordToDecimal(off).data(), " (0x", WordToHex(ip).data(), - ")"); - return ret; -} - static pthread_t g_main_thread; -// g_in_trampoline is true if we are in an instrumented |abi_test_trampoline| -// call, in the region that triggers |SIGTRAP|. -static bool g_in_trampoline = false; -// g_unwind_function_done, if |g_in_trampoline| is true, is whether the function -// under test has returned. It is undefined otherwise. -static bool g_unwind_function_done; -// g_trampoline_state, if |g_in_trampoline| is true, is the state the function -// under test must preserve. It is undefined otherwise. -static CallerState g_trampoline_state; -// g_trampoline_sp, if |g_in_trampoline| is true, is the stack pointer of the -// trampoline frame. It is undefined otherwise. -static unw_word_t g_trampoline_sp; - -// kMaxUnwindErrors is the maximum number of unwind errors reported per -// function. If a function's unwind tables are wrong, we are otherwise likely to -// repeat the same error at multiple addresses. -static constexpr size_t kMaxUnwindErrors = 10; - -// Errors are saved in a signal handler. We use a static buffer to avoid -// allocation. -static size_t num_unwind_errors = 0; -static char unwind_errors[kMaxUnwindErrors][512]; - -template -static void AddUnwindError(Args... args) { - if (num_unwind_errors >= kMaxUnwindErrors) { - return; - } - StrCatSignalSafe(unwind_errors[num_unwind_errors], args...); - num_unwind_errors++; -} - -template -[[noreturn]] static void FatalError(Args... args) { - // We cannot use |snprintf| here because it is not async-signal-safe. - char buf[512]; - StrCatSignalSafe(buf, args..., "\n"); - write(STDERR_FILENO, buf, strlen(buf)); - abort(); -} - static void TrapHandler(int sig) { // Note this is a signal handler, so only async-signal-safe functions may be // used here. See signal-safety(7). libunwind promises local unwind is @@ -348,126 +738,12 @@ static void TrapHandler(int sig) { unw_context_t ctx; int ret = unw_getcontext(&ctx); - unw_cursor_t cursor; - // Work around a bug in libunwind which breaks rax and rdx recovery. This - // breaks functions which temporarily use rax as the CFA register. See - // https://git.savannah.gnu.org/gitweb/?p=libunwind.git;a=commit;h=819bf51bbd2da462c2ec3401e8ac9153b6e725e3 - OPENSSL_memset(&cursor, 0, sizeof(cursor)); - ret = ret < 0 ? ret : unw_init_local(&cursor, &ctx); - ret = ret < 0 ? ret : UnwindToSignalFrame(&cursor); - unw_word_t sp, ip; - ret = ret < 0 ? ret : unw_get_reg(&cursor, UNW_REG_SP, &sp); - ret = ret < 0 ? ret : unw_get_reg(&cursor, UNW_REG_IP, &ip); if (ret < 0) { - FatalError("Error initializing unwind cursor: ", unw_strerror(ret)); + FatalError("Error getting unwind context: ", unw_strerror(ret)); } - const unw_word_t kStartAddress = - reinterpret_cast(&abi_test_unwind_start); - const unw_word_t kReturnAddress = - reinterpret_cast(&abi_test_unwind_return); - const unw_word_t kStopAddress = - reinterpret_cast(&abi_test_unwind_stop); - if (!g_in_trampoline) { - if (ip != kStartAddress) { - FatalError("Unexpected SIGTRAP at ", IPToString(ip, &ctx).data()); - } - - // Save the current state and begin. - g_in_trampoline = true; - g_unwind_function_done = false; - g_trampoline_sp = sp; - ret = CallerStateFromUNWCursor(&g_trampoline_state, &cursor); - if (ret < 0) { - FatalError("Error getting initial caller state: ", unw_strerror(ret)); - } - } else { - if (sp == g_trampoline_sp || g_unwind_function_done) { - // |g_unwind_function_done| should imply |sp| is |g_trampoline_sp|, but - // clearing the trap flag in x86 briefly displaces the stack pointer. - // - // Also note we check both |ip| and |sp| below, in case the function under - // test is also |abi_test_trampoline|. - if (ip == kReturnAddress && sp == g_trampoline_sp) { - g_unwind_function_done = true; - } - if (ip == kStopAddress && sp == g_trampoline_sp) { - // |SIGTRAP| is fatal again. - g_in_trampoline = false; - } - } else if (IsAncestorStackFrame(sp, g_trampoline_sp)) { - // This should never happen. We went past |g_trampoline_sp| without - // stopping at |kStopAddress|. - AddUnwindError("stack frame is before caller at ", - IPToString(ip, &ctx).data()); - g_in_trampoline = false; - } else if (num_unwind_errors < kMaxUnwindErrors) { - for (;;) { - ret = unw_step(&cursor); - if (ret < 0) { - AddUnwindError("error unwinding from ", IPToString(ip, &ctx).data(), - ": ", unw_strerror(ret)); - break; - } - if (ret == 0) { - AddUnwindError("could not unwind to starting frame from ", - IPToString(ip, &ctx).data()); - break; - } - - unw_word_t cur_sp; - ret = unw_get_reg(&cursor, UNW_REG_SP, &cur_sp); - if (ret < 0) { - AddUnwindError("error recovering stack pointer unwinding from ", - IPToString(ip, &ctx).data(), ": ", unw_strerror(ret)); - break; - } - if (IsAncestorStackFrame(cur_sp, g_trampoline_sp)) { - AddUnwindError("unwound past starting frame from ", - IPToString(ip, &ctx).data()); - break; - } - if (cur_sp == g_trampoline_sp) { - // We found the parent frame. Check the return address. - unw_word_t cur_ip; - ret = unw_get_reg(&cursor, UNW_REG_IP, &cur_ip); - if (ret < 0) { - AddUnwindError("error recovering return address unwinding from ", - IPToString(ip, &ctx).data(), ": ", - unw_strerror(ret)); - } else if (cur_ip != kReturnAddress) { - AddUnwindError("wrong return address unwinding from ", - IPToString(ip, &ctx).data()); - } - - // Check the remaining registers. - CallerState state; - ret = CallerStateFromUNWCursor(&state, &cursor); - if (ret < 0) { - AddUnwindError("error recovering registers unwinding from ", - IPToString(ip, &ctx).data(), ": ", - unw_strerror(ret)); - } else { - ForEachMismatch(state, g_trampoline_state, [&](const char *reg) { - AddUnwindError(reg, " was not recovered unwinding from ", - IPToString(ip, &ctx).data()); - }); - } - break; - } - } - } - } -} - -static void ReadUnwindResult(Result *out) { - for (size_t i = 0; i < num_unwind_errors; i++) { - out->errors.emplace_back(unwind_errors[i]); - } - if (num_unwind_errors == kMaxUnwindErrors) { - out->errors.emplace_back("(additional errors omitted)"); - } - num_unwind_errors = 0; + UnwindCursor cursor(&ctx); + CheckUnwind(&cursor); } static void EnableUnwindTestsImpl() { @@ -490,14 +766,16 @@ static void EnableUnwindTestsImpl() { g_unwind_tests_enabled = true; } +#endif // OPENSSL_WINDOWS + +#else // !SUPPORTS_UNWIND_TEST -#else -// TODO(davidben): Implement an SEH-based unwind-tester. #if defined(SUPPORTS_ABI_TEST) static void ReadUnwindResult(Result *) {} #endif static void EnableUnwindTestsImpl() {} -#endif // UNWIND_TEST_SIGTRAP + +#endif // SUPPORTS_UNWIND_TEST } // namespace internal diff --git a/third_party/boringssl/kit/src/crypto/test/abi_test.h b/third_party/boringssl/kit/src/crypto/test/abi_test.h index 370d455a..a3c4bb87 100644 --- a/third_party/boringssl/kit/src/crypto/test/abi_test.h +++ b/third_party/boringssl/kit/src/crypto/test/abi_test.h @@ -55,12 +55,15 @@ struct alignas(16) Reg128 { }; // LOOP_CALLER_STATE_REGISTERS is a macro that iterates over all registers the -// callee is expected to save for the caller. -// -// TODO(davidben): Add support for other architectures. +// callee is expected to save for the caller, with the exception of the stack +// pointer. The stack pointer is tested implicitly by the function successfully +// returning at all. #if defined(OPENSSL_X86_64) + +// References: +// SysV64: https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-1.0.pdf +// Win64: https://docs.microsoft.com/en-us/cpp/build/x64-software-conventions?view=vs-2017#register-usage #if defined(OPENSSL_WINDOWS) -// See https://docs.microsoft.com/en-us/cpp/build/x64-software-conventions?view=vs-2017#register-usage #define LOOP_CALLER_STATE_REGISTERS() \ CALLER_STATE_REGISTER(uint64_t, rbx) \ CALLER_STATE_REGISTER(uint64_t, rbp) \ @@ -81,7 +84,6 @@ struct alignas(16) Reg128 { CALLER_STATE_REGISTER(Reg128, xmm14) \ CALLER_STATE_REGISTER(Reg128, xmm15) #else -// See https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-1.0.pdf #define LOOP_CALLER_STATE_REGISTERS() \ CALLER_STATE_REGISTER(uint64_t, rbx) \ CALLER_STATE_REGISTER(uint64_t, rbp) \ @@ -90,7 +92,94 @@ struct alignas(16) Reg128 { CALLER_STATE_REGISTER(uint64_t, r14) \ CALLER_STATE_REGISTER(uint64_t, r15) #endif // OPENSSL_WINDOWS -#endif // X86_64 && SUPPORTS_ABI_TEST + +#elif defined(OPENSSL_X86) + +// References: +// SysV32: https://uclibc.org/docs/psABI-i386.pdf and +// Win32: https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions?view=vs-2017 +#define LOOP_CALLER_STATE_REGISTERS() \ + CALLER_STATE_REGISTER(uint32_t, esi) \ + CALLER_STATE_REGISTER(uint32_t, edi) \ + CALLER_STATE_REGISTER(uint32_t, ebx) \ + CALLER_STATE_REGISTER(uint32_t, ebp) + +#elif defined(OPENSSL_ARM) + +// References: +// AAPCS: http://infocenter.arm.com/help/topic/com.arm.doc.ihi0042f/IHI0042F_aapcs.pdf +// iOS32: https://developer.apple.com/library/archive/documentation/Xcode/Conceptual/iPhoneOSABIReference/Articles/ARMv6FunctionCallingConventions.html +// Linux: http://sourcery.mentor.com/sgpp/lite/arm/portal/kbattach142/arm_gnu_linux_%20abi.pdf +// +// ARM specifies a common calling convention, except r9 is left to the platform. +// Linux treats r9 as callee-saved, while iOS 3+ treats it as caller-saved. Most +// of our assembly treats it as callee-saved to be uniform, but we match the +// platform to avoid false positives when testing compiler-generated output. +#define LOOP_CALLER_STATE_REGISTERS_PRE_R9() \ + CALLER_STATE_REGISTER(uint64_t, d8) \ + CALLER_STATE_REGISTER(uint64_t, d9) \ + CALLER_STATE_REGISTER(uint64_t, d10) \ + CALLER_STATE_REGISTER(uint64_t, d11) \ + CALLER_STATE_REGISTER(uint64_t, d12) \ + CALLER_STATE_REGISTER(uint64_t, d13) \ + CALLER_STATE_REGISTER(uint64_t, d14) \ + CALLER_STATE_REGISTER(uint64_t, d15) \ + CALLER_STATE_REGISTER(uint32_t, r4) \ + CALLER_STATE_REGISTER(uint32_t, r5) \ + CALLER_STATE_REGISTER(uint32_t, r6) \ + CALLER_STATE_REGISTER(uint32_t, r7) \ + CALLER_STATE_REGISTER(uint32_t, r8) +#define LOOP_CALLER_STATE_REGISTERS_POST_R9() \ + CALLER_STATE_REGISTER(uint32_t, r10) \ + CALLER_STATE_REGISTER(uint32_t, r11) +#if defined(OPENSSL_APPLE) +#define LOOP_CALLER_STATE_REGISTERS() \ + LOOP_CALLER_STATE_REGISTERS_PRE_R9() \ + LOOP_CALLER_STATE_REGISTERS_POST_R9() +#else // !OPENSSL_APPLE +#define LOOP_CALLER_STATE_REGISTERS() \ + LOOP_CALLER_STATE_REGISTERS_PRE_R9() \ + CALLER_STATE_REGISTER(uint32_t, r9) \ + LOOP_CALLER_STATE_REGISTERS_POST_R9() +#endif // OPENSSL_APPLE + +#elif defined(OPENSSL_AARCH64) + +// References: +// AAPCS64: http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf +// iOS64: https://developer.apple.com/library/archive/documentation/Xcode/Conceptual/iPhoneOSABIReference/Articles/ARM64FunctionCallingConventions.html +// +// In aarch64, r18 (accessed as w18 or x18 in a 64-bit context) is the platform +// register. iOS says user code may not touch it. We found no clear reference +// for Linux. The iOS behavior implies portable assembly cannot use it, and +// aarch64 has many registers. Thus this framework ignores register's existence. +// We test r18 violations in arm-xlate.pl. +#define LOOP_CALLER_STATE_REGISTERS() \ + /* Per AAPCS64, section 5.1.2, only the bottom 64 bits of v8-v15 */ \ + /* are preserved. These are accessed as dN. */ \ + CALLER_STATE_REGISTER(uint64_t, d8) \ + CALLER_STATE_REGISTER(uint64_t, d9) \ + CALLER_STATE_REGISTER(uint64_t, d10) \ + CALLER_STATE_REGISTER(uint64_t, d11) \ + CALLER_STATE_REGISTER(uint64_t, d12) \ + CALLER_STATE_REGISTER(uint64_t, d13) \ + CALLER_STATE_REGISTER(uint64_t, d14) \ + CALLER_STATE_REGISTER(uint64_t, d15) \ + /* For consistency with dN, use the 64-bit name xN, rather than */ \ + /* the generic rN. */ \ + CALLER_STATE_REGISTER(uint64_t, x19) \ + CALLER_STATE_REGISTER(uint64_t, x20) \ + CALLER_STATE_REGISTER(uint64_t, x21) \ + CALLER_STATE_REGISTER(uint64_t, x22) \ + CALLER_STATE_REGISTER(uint64_t, x23) \ + CALLER_STATE_REGISTER(uint64_t, x24) \ + CALLER_STATE_REGISTER(uint64_t, x25) \ + CALLER_STATE_REGISTER(uint64_t, x26) \ + CALLER_STATE_REGISTER(uint64_t, x27) \ + CALLER_STATE_REGISTER(uint64_t, x28) \ + CALLER_STATE_REGISTER(uint64_t, x29) + +#endif // X86_64 || X86 || ARM || AARCH64 // Enable ABI testing if all of the following are true. // @@ -119,6 +208,62 @@ crypto_word_t RunTrampoline(Result *out, crypto_word_t func, const crypto_word_t *argv, size_t argc, bool unwind); +template +inline crypto_word_t ToWord(T t) { +#if !defined(OPENSSL_X86) && !defined(OPENSSL_X86_64) && \ + !defined(OPENSSL_ARM) && !defined(OPENSSL_AARCH64) +#error "Unknown architecture" +#endif + static_assert(sizeof(T) <= sizeof(crypto_word_t), + "T is larger than crypto_word_t"); + static_assert(sizeof(T) >= 4, "types under four bytes are complicated"); + + // ABIs are complex around arguments that are smaller than native words. For + // 32-bit architectures, the rules above imply we only have word-sized + // arguments. For 64-bit architectures, we still have assembly functions which + // take |int|. + // + // For aarch64, AAPCS64, section 5.4.2, clauses C.7 and C.14 says any + // remaining bits are unspecified. iOS64 contradicts this and says the callee + // extends arguments up to 32 bits, and only the upper 32 bits are + // unspecified. Rejecting parameters smaller than 32 bits avoids the + // divergence. + // + // TODO(davidben): Find authoritative citations for x86_64. For x86_64, I + // observed the behavior of Clang, GCC, and MSVC. ABI rules here may be + // inferred from two kinds of experiments: + // + // 1. When passing a value to a small-argument-taking function, does the + // compiler ensure unused bits are cleared, sign-extended, etc.? Tests for + // register parameters are confounded by x86_64's implicit clearing of + // registers' upper halves, but passing some_u64 >> 1 usually clears this. + // + // 2. When compiling a small-argument-taking function, does the compiler make + // assumptions about unused bits of arguments? + // + // MSVC for x86_64 is straightforward. It appears to tolerate and produce + // arbitrary values for unused bits, like AAPCS64. + // + // GCC and Clang for x86_64 are more complex. They match MSVC for stack + // parameters. However, for register parameters, they behave like iOS64 and, + // as callers, extend up to 32 bits, leaving the remainder arbitrary. When + // compiling a callee, Clang takes advantage of this conversion, but I was + // unable to make GCC do so. + // + // Note that, although the Win64 rules are sufficient to require our assembly + // be conservative, we wish for |CHECK_ABI| to support C-compiled functions, + // so it must enforce the correct rules for each platform. + // + // Fortunately, the |static_assert|s above cause all supported architectures + // to behave the same. + crypto_word_t ret; + // Filling extra bits with 0xaa will be vastly out of bounds for code + // expecting either sign- or zero-extension. (0xaa is 0b10101010.) + OPENSSL_memset(&ret, 0xaa, sizeof(ret)); + OPENSSL_memcpy(&ret, &t, sizeof(t)); + return ret; +} + // CheckImpl runs |func| on |args|, recording ABI errors in |out|. If |unwind| // is true and unwind tests have been enabled, |func| is single-stepped under an // unwind test. @@ -131,12 +276,17 @@ crypto_word_t RunTrampoline(Result *out, crypto_word_t func, template inline crypto_word_t CheckImpl(Result *out, bool unwind, R (*func)(Args...), typename DeductionGuard::Type... args) { - static_assert(sizeof...(args) <= 10, + // We only support up to 8 arguments. This ensures all arguments on aarch64 + // are passed in registers and avoids the iOS descrepancy around packing small + // arguments on the stack. + // + // https://developer.apple.com/library/archive/documentation/Xcode/Conceptual/iPhoneOSABIReference/Articles/ARM64FunctionCallingConventions.html + static_assert(sizeof...(args) <= 8, "too many arguments for abi_test_trampoline"); // Allocate one extra entry so MSVC does not complain about zero-size arrays. crypto_word_t argv[sizeof...(args) + 1] = { - (crypto_word_t)args..., + ToWord(args)..., }; return RunTrampoline(out, reinterpret_cast(func), argv, sizeof...(args), unwind); @@ -226,8 +376,20 @@ bool UnwindTestsEnabled(); // // Functional testing requires coverage of input values, while ABI testing only // requires branch coverage. Most of our assembly is constant-time, so usually -// only a few instrumented calls are necessray. -#define CHECK_ABI(...) \ +// only a few instrumented calls are necessary. +// +// TODO(https://crbug.com/boringssl/259): Most of Windows assembly currently +// fails SEH testing. For now, |CHECK_ABI| behaves like |CHECK_ABI_NO_UNWIND| +// on Windows. Functions which work with unwind testing on Windows should use +// |CHECK_ABI_SEH|. +#if defined(OPENSSL_WINDOWS) +#define CHECK_ABI(...) CHECK_ABI_NO_UNWIND(__VA_ARGS__) +#else +#define CHECK_ABI(...) CHECK_ABI_SEH(__VA_ARGS__) +#endif + +// CHECK_ABI_SEH behaves like |CHECK_ABI| but enables unwind testing on Windows. +#define CHECK_ABI_SEH(...) \ abi_test::internal::CheckGTest(#__VA_ARGS__, __FILE__, __LINE__, true, \ __VA_ARGS__) @@ -257,6 +419,7 @@ crypto_word_t abi_test_trampoline(crypto_word_t func, const crypto_word_t *argv, size_t argc, crypto_word_t unwind); +#if defined(OPENSSL_X86_64) // abi_test_unwind_start points at the instruction that starts unwind testing in // |abi_test_trampoline|. This is the value of the instruction pointer at the // first |SIGTRAP| during unwind testing. @@ -279,13 +442,21 @@ void abi_test_unwind_return(Uncallable); void abi_test_unwind_stop(Uncallable); // abi_test_bad_unwind_wrong_register preserves the ABI, but annotates the wrong -// register in CFI metadata. +// register in unwind metadata. void abi_test_bad_unwind_wrong_register(void); // abi_test_bad_unwind_temporary preserves the ABI, but temporarily corrupts the // storage space for a saved register, breaking unwind. void abi_test_bad_unwind_temporary(void); +#if defined(OPENSSL_WINDOWS) +// abi_test_bad_unwind_epilog preserves the ABI, and correctly annotates the +// prolog, but the epilog does not match Win64's rules, breaking unwind during +// the epilog. +void abi_test_bad_unwind_epilog(void); +#endif +#endif // OPENSSL_X86_64 + #if defined(OPENSSL_X86_64) || defined(OPENSSL_X86) // abi_test_get_and_clear_direction_flag clears the direction flag. If the flag // was previously set, it returns one. Otherwise, it returns zero. diff --git a/third_party/boringssl/kit/src/crypto/test/asm/trampoline-armv4.pl b/third_party/boringssl/kit/src/crypto/test/asm/trampoline-armv4.pl new file mode 100755 index 00000000..6118dd7b --- /dev/null +++ b/third_party/boringssl/kit/src/crypto/test/asm/trampoline-armv4.pl @@ -0,0 +1,182 @@ +#!/usr/bin/env perl +# Copyright (c) 2019, Google Inc. +# +# Permission to use, copy, modify, and/or distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +# This file defines helper functions for crypto/test/abi_test.h on 32-bit +# ARM. See that header for details on how to use this. +# +# For convenience, this file is linked into libcrypto, where consuming builds +# already support architecture-specific sources. The static linker should drop +# this code in non-test binaries. This includes a shared library build of +# libcrypto, provided --gc-sections (ELF), -dead_strip (iOS), or equivalent is +# used. +# +# References: +# +# AAPCS: http://infocenter.arm.com/help/topic/com.arm.doc.ihi0042f/IHI0042F_aapcs.pdf +# iOS ARMv6: https://developer.apple.com/library/archive/documentation/Xcode/Conceptual/iPhoneOSABIReference/Articles/ARMv6FunctionCallingConventions.html +# iOS ARMv7: https://developer.apple.com/library/archive/documentation/Xcode/Conceptual/iPhoneOSABIReference/Articles/ARMv7FunctionCallingConventions.html +# Linux: http://sourcery.mentor.com/sgpp/lite/arm/portal/kbattach142/arm_gnu_linux_%20abi.pdf + +use strict; + +my $flavour = shift; +my $output = shift; +if ($flavour =~ /\./) { $output = $flavour; undef $flavour; } + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; +my $dir = $1; +my $xlate; +( $xlate="${dir}arm-xlate.pl" and -f $xlate ) or +( $xlate="${dir}../../perlasm/arm-xlate.pl" and -f $xlate) or +die "can't locate arm-xlate.pl"; + +open OUT, "| \"$^X\" \"$xlate\" $flavour \"$output\""; +*STDOUT = *OUT; + +my ($func, $state, $argv, $argc) = ("r0", "r1", "r2", "r3"); +my $code = <<____; +.syntax unified + +.arch armv7-a +.fpu vfp + +.text + +@ abi_test_trampoline loads callee-saved registers from |state|, calls |func| +@ with |argv|, then saves the callee-saved registers into |state|. It returns +@ the result of |func|. The |unwind| argument is unused. +@ uint32_t abi_test_trampoline(void (*func)(...), CallerState *state, +@ const uint32_t *argv, size_t argc, +@ int unwind); +.type abi_test_trampoline, %function +.globl abi_test_trampoline +.align 4 +abi_test_trampoline: +.Labi_test_trampoline_begin: + @ Save parameters and all callee-saved registers. For convenience, we + @ save r9 on iOS even though it's volatile. + vstmdb sp!, {d8-d15} + stmdb sp!, {r0-r11,lr} + + @ Reserve stack space for six (10-4) stack parameters, plus an extra 4 + @ bytes to keep it 8-byte-aligned (see AAPCS, section 5.3). + sub sp, sp, #28 + + @ Every register in AAPCS is either non-volatile or a parameter (except + @ r9 on iOS), so this code, by the actual call, loses all its scratch + @ registers. First fill in stack parameters while there are registers + @ to spare. + cmp $argc, #4 + bls .Lstack_args_done + mov r4, sp @ r4 is the output pointer. + add r5, $argv, $argc, lsl #2 @ Set r5 to the end of argv. + add $argv, $argv, #16 @ Skip four arguments. +.Lstack_args_loop: + ldr r6, [$argv], #4 + cmp $argv, r5 + str r6, [r4], #4 + bne .Lstack_args_loop + +.Lstack_args_done: + @ Load registers from |$state|. + vldmia $state!, {d8-d15} +#if defined(__APPLE__) + @ r9 is not volatile on iOS. + ldmia $state!, {r4-r8,r10-r11} +#else + ldmia $state!, {r4-r11} +#endif + + @ Load register parameters. This uses up our remaining registers, so we + @ repurpose lr as scratch space. + ldr $argc, [sp, #40] @ Reload argc. + ldr lr, [sp, #36] @ Load argv into lr. + cmp $argc, #3 + bhi .Larg_r3 + beq .Larg_r2 + cmp $argc, #1 + bhi .Larg_r1 + beq .Larg_r0 + b .Largs_done + +.Larg_r3: + ldr r3, [lr, #12] @ argv[3] +.Larg_r2: + ldr r2, [lr, #8] @ argv[2] +.Larg_r1: + ldr r1, [lr, #4] @ argv[1] +.Larg_r0: + ldr r0, [lr] @ argv[0] +.Largs_done: + + @ With every other register in use, load the function pointer into lr + @ and call the function. + ldr lr, [sp, #28] + blx lr + + @ r1-r3 are free for use again. The trampoline only supports + @ single-return functions. Pass r4-r11 to the caller. + ldr $state, [sp, #32] + vstmia $state!, {d8-d15} +#if defined(__APPLE__) + @ r9 is not volatile on iOS. + stmia $state!, {r4-r8,r10-r11} +#else + stmia $state!, {r4-r11} +#endif + + @ Unwind the stack and restore registers. + add sp, sp, #44 @ 44 = 28+16 + ldmia sp!, {r4-r11,lr} @ Skip r0-r3 (see +16 above). + vldmia sp!, {d8-d15} + + bx lr +.size abi_test_trampoline,.-abi_test_trampoline +____ + +# abi_test_clobber_* zeros the corresponding register. These are used to test +# the ABI-testing framework. +foreach (0..12) { + # This loop skips r13 (sp), r14 (lr, implicitly clobbered by every call), and + # r15 (pc). + $code .= <<____; +.type abi_test_clobber_r$_, %function +.globl abi_test_clobber_r$_ +.align 4 +abi_test_clobber_r$_: + mov r$_, #0 + bx lr +.size abi_test_clobber_r$_,.-abi_test_clobber_r$_ +____ +} + +foreach (0..15) { + my $lo = "s".(2*$_); + my $hi = "s".(2*$_+1); + $code .= <<____; +.type abi_test_clobber_d$_, %function +.globl abi_test_clobber_d$_ +.align 4 +abi_test_clobber_d$_: + mov r0, #0 + vmov $lo, r0 + vmov $hi, r0 + bx lr +.size abi_test_clobber_d$_,.-abi_test_clobber_d$_ +____ +} + +print $code; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/test/asm/trampoline-armv8.pl b/third_party/boringssl/kit/src/crypto/test/asm/trampoline-armv8.pl new file mode 100755 index 00000000..410b59ef --- /dev/null +++ b/third_party/boringssl/kit/src/crypto/test/asm/trampoline-armv8.pl @@ -0,0 +1,209 @@ +#!/usr/bin/env perl +# Copyright (c) 2019, Google Inc. +# +# Permission to use, copy, modify, and/or distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +# This file defines helper functions for crypto/test/abi_test.h on aarch64. See +# that header for details on how to use this. +# +# For convenience, this file is linked into libcrypto, where consuming builds +# already support architecture-specific sources. The static linker should drop +# this code in non-test binaries. This includes a shared library build of +# libcrypto, provided --gc-sections (ELF), -dead_strip (iOS), or equivalent is +# used. +# +# References: +# +# AAPCS64: http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf +# iOS ARM64: https://developer.apple.com/library/archive/documentation/Xcode/Conceptual/iPhoneOSABIReference/Articles/ARM64FunctionCallingConventions.html + +use strict; + +my $flavour = shift; +my $output = shift; +if ($flavour =~ /\./) { $output = $flavour; undef $flavour; } + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; +my $dir = $1; +my $xlate; +( $xlate="${dir}arm-xlate.pl" and -f $xlate ) or +( $xlate="${dir}../../perlasm/arm-xlate.pl" and -f $xlate) or +die "can't locate arm-xlate.pl"; + +open OUT, "| \"$^X\" \"$xlate\" $flavour \"$output\""; +*STDOUT = *OUT; + +my ($func, $state, $argv, $argc) = ("x0", "x1", "x2", "x3"); +my $code = <<____; +.text + +// abi_test_trampoline loads callee-saved registers from |state|, calls |func| +// with |argv|, then saves the callee-saved registers into |state|. It returns +// the result of |func|. The |unwind| argument is unused. +// uint64_t abi_test_trampoline(void (*func)(...), CallerState *state, +// const uint64_t *argv, size_t argc, +// uint64_t unwind); +.type abi_test_trampoline, %function +.globl abi_test_trampoline +.align 4 +abi_test_trampoline: +.Labi_test_trampoline_begin: + // Stack layout (low to high addresses) + // x29,x30 (16 bytes) + // d8-d15 (64 bytes) + // x19-x28 (80 bytes) + // $state (8 bytes) + // padding (8 bytes) + stp x29, x30, [sp, #-176]! + mov x29, sp + + // Saved callee-saved registers and |state|. + stp d8, d9, [sp, #16] + stp d10, d11, [sp, #32] + stp d12, d13, [sp, #48] + stp d14, d15, [sp, #64] + stp x19, x20, [sp, #80] + stp x21, x22, [sp, #96] + stp x23, x24, [sp, #112] + stp x25, x26, [sp, #128] + stp x27, x28, [sp, #144] + str $state, [sp, #160] + + // Load registers from |state|, with the exception of x29. x29 is the + // frame pointer and also callee-saved, but AAPCS64 allows platforms to + // mandate that x29 always point to a frame. iOS64 does so, which means + // we cannot fill x29 with entropy without violating ABI rules + // ourselves. x29 is tested separately below. + ldp d8, d9, [$state], #16 + ldp d10, d11, [$state], #16 + ldp d12, d13, [$state], #16 + ldp d14, d15, [$state], #16 + ldp x19, x20, [$state], #16 + ldp x21, x22, [$state], #16 + ldp x23, x24, [$state], #16 + ldp x25, x26, [$state], #16 + ldp x27, x28, [$state], #16 + + // Move parameters into temporary registers. + mov x9, $func + mov x10, $argv + mov x11, $argc + + // Load parameters into registers. + cbz x11, .Largs_done + ldr x0, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x1, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x2, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x3, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x4, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x5, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x6, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x7, [x10], #8 + +.Largs_done: + blr x9 + + // Reload |state| and store registers. + ldr $state, [sp, #160] + stp d8, d9, [$state], #16 + stp d10, d11, [$state], #16 + stp d12, d13, [$state], #16 + stp d14, d15, [$state], #16 + stp x19, x20, [$state], #16 + stp x21, x22, [$state], #16 + stp x23, x24, [$state], #16 + stp x25, x26, [$state], #16 + stp x27, x28, [$state], #16 + + // |func| is required to preserve x29, the frame pointer. We cannot load + // random values into x29 (see comment above), so compare it against the + // expected value and zero the field of |state| if corrupted. + mov x9, sp + cmp x29, x9 + b.eq .Lx29_ok + str xzr, [$state] + +.Lx29_ok: + // Restore callee-saved registers. + ldp d8, d9, [sp, #16] + ldp d10, d11, [sp, #32] + ldp d12, d13, [sp, #48] + ldp d14, d15, [sp, #64] + ldp x19, x20, [sp, #80] + ldp x21, x22, [sp, #96] + ldp x23, x24, [sp, #112] + ldp x25, x26, [sp, #128] + ldp x27, x28, [sp, #144] + + ldp x29, x30, [sp], #176 + ret +.size abi_test_trampoline,.-abi_test_trampoline +____ + +# abi_test_clobber_* zeros the corresponding register. These are used to test +# the ABI-testing framework. +foreach (0..29) { + # x18 is the platform register and off limits. + next if ($_ == 18); + $code .= <<____; +.type abi_test_clobber_x$_, %function +.globl abi_test_clobber_x$_ +.align 4 +abi_test_clobber_x$_: + mov x$_, xzr + ret +.size abi_test_clobber_x$_,.-abi_test_clobber_x$_ +____ +} +foreach (0..31) { + $code .= <<____; +.type abi_test_clobber_d$_, %function +.globl abi_test_clobber_d$_ +.align 4 +abi_test_clobber_d$_: + fmov d$_, xzr + ret +.size abi_test_clobber_d$_,.-abi_test_clobber_d$_ +____ +} + +# abi_test_clobber_v*_upper clobbers only the upper half of v*. AAPCS64 only +# requires the lower half (d*) be preserved. +foreach (8..15) { + $code .= <<____; +.type abi_test_clobber_v${_}_upper, %function +.globl abi_test_clobber_v${_}_upper +.align 4 +abi_test_clobber_v${_}_upper: + fmov v${_}.d[1], xzr + ret +.size abi_test_clobber_v${_}_upper,.-abi_test_clobber_v${_}_upper +____ +} + +print $code; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/test/asm/trampoline-x86.pl b/third_party/boringssl/kit/src/crypto/test/asm/trampoline-x86.pl new file mode 100755 index 00000000..4244ac2a --- /dev/null +++ b/third_party/boringssl/kit/src/crypto/test/asm/trampoline-x86.pl @@ -0,0 +1,123 @@ +#!/usr/bin/env perl +# Copyright (c) 2018, Google Inc. +# +# Permission to use, copy, modify, and/or distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +# This file defines helper functions for crypto/test/abi_test.h on x86. See +# that header for details on how to use this. +# +# For convenience, this file is linked into libcrypto, where consuming builds +# already support architecture-specific sources. The static linker should drop +# this code in non-test binaries. This includes a shared library build of +# libcrypto, provided --gc-sections (ELF), -dead_strip (Mac), or equivalent is +# used. +# +# References: +# +# SysV ABI: https://uclibc.org/docs/psABI-i386.pdf +# Win32 ABI: https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions?view=vs-2017 + +use strict; + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; +my $dir = $1; +push(@INC, "${dir}", "${dir}../../perlasm"); +require "x86asm.pl"; + +my $output = pop; +open STDOUT, ">$output"; + +&asm_init($ARGV[0]); + +# abi_test_trampoline loads callee-saved registers from |state|, calls |func| +# with |argv|, then saves the callee-saved registers into |state|. It returns +# the result of |func|. |unwind| is ignored. +# uint32_t abi_test_trampoline(void (*func)(...), CallerState *state, +# const uint32_t *argv, size_t argc, +# int unwind); +&function_begin("abi_test_trampoline") + # Load registers from |state|. Note |function_begin| (as opposed to + # |function_begin_B|) automatically saves all callee-saved registers, so we + # may freely clobber them. + &mov("ecx", &wparam(1)); + &mov("esi", &DWP(4*0, "ecx")); + &mov("edi", &DWP(4*1, "ecx")); + &mov("ebx", &DWP(4*2, "ecx")); + &mov("ebp", &DWP(4*3, "ecx")); + + # Use a fixed stack allocation so |wparam| continues to work. abi_test.h + # supports at most 10 arguments. The SysV ABI requires a 16-byte-aligned + # stack on process entry, so round up to 3 (mod 4). + &stack_push(11); + + # Copy parameters to stack. + &mov("eax", &wparam(2)); + &xor("ecx", "ecx"); +&set_label("loop"); + &cmp("ecx", &wparam(3)); + &jae(&label("loop_done")); + &mov("edx", &DWP(0, "eax", "ecx", 4)); + &mov(&DWP(0, "esp", "ecx", 4), "edx"); + &add("ecx", 1); + &jmp(&label("loop")); + +&set_label("loop_done"); + &call_ptr(&wparam(0)); + + &stack_pop(11); + + # Save registers back into |state|. + &mov("ecx", &wparam(1)); + &mov(&DWP(4*0, "ecx"), "esi"); + &mov(&DWP(4*1, "ecx"), "edi"); + &mov(&DWP(4*2, "ecx"), "ebx"); + &mov(&DWP(4*3, "ecx"), "ebp"); +&function_end("abi_test_trampoline") + +# abi_test_get_and_clear_direction_flag clears the direction flag. If the flag +# was previously set, it returns one. Otherwise, it returns zero. +# int abi_test_get_and_clear_direction_flag(void); +&function_begin_B("abi_test_get_and_clear_direction_flag"); + &pushf(); + &pop("eax"); + &and("eax", 0x400); + &shr("eax", 10); + &cld(); + &ret(); +&function_end_B("abi_test_get_and_clear_direction_flag"); + +# abi_test_set_direction_flag sets the direction flag. +# void abi_test_set_direction_flag(void); +&function_begin_B("abi_test_set_direction_flag"); + &std(); + &ret(); +&function_end_B("abi_test_set_direction_flag"); + +# abi_test_clobber_* zeros the corresponding register. These are used to test +# the ABI-testing framework. +foreach ("eax", "ebx", "ecx", "edx", "edi", "esi", "ebp") { +&function_begin_B("abi_test_clobber_$_"); + &xor($_, $_); + &ret(); +&function_end_B("abi_test_clobber_$_"); +} +foreach (0..7) { +&function_begin_B("abi_test_clobber_xmm$_"); + &pxor("xmm$_", "xmm$_"); + &ret(); +&function_end_B("abi_test_clobber_xmm$_"); +} + +&asm_finish(); + +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/test/asm/trampoline-x86_64.pl b/third_party/boringssl/kit/src/crypto/test/asm/trampoline-x86_64.pl index 4af9b2a0..5196141c 100755 --- a/third_party/boringssl/kit/src/crypto/test/asm/trampoline-x86_64.pl +++ b/third_party/boringssl/kit/src/crypto/test/asm/trampoline-x86_64.pl @@ -139,7 +139,7 @@ my $code = <<____; .globl abi_test_trampoline .align 16 abi_test_trampoline: -.Labi_test_trampoline_begin: +.Labi_test_trampoline_seh_begin: .cfi_startproc # Stack layout: # 8 bytes - align @@ -178,7 +178,7 @@ my $caller_state_offset = $scratch_offset + 8; $code .= <<____; subq \$$stack_alloc_size, %rsp .cfi_adjust_cfa_offset $stack_alloc_size -.Labi_test_trampoline_prolog_alloc: +.Labi_test_trampoline_seh_prolog_alloc: ____ $code .= <<____ if (!$win64); movq $unwind, $unwind_offset(%rsp) @@ -194,11 +194,11 @@ $code .= store_caller_state($caller_state_offset, "%rsp", sub { $off -= $stack_alloc_size + 8; return <<____; .cfi_offset $reg, $off -.Labi_test_trampoline_prolog_$reg: +.Labi_test_trampoline_seh_prolog_$reg: ____ }); $code .= <<____; -.Labi_test_trampoline_prolog_end: +.Labi_test_trampoline_seh_prolog_end: ____ $code .= load_caller_state(0, $state); @@ -295,7 +295,7 @@ $code .= <<____; # %rax already contains \$func's return value, unmodified. ret .cfi_endproc -.Labi_test_trampoline_end: +.Labi_test_trampoline_seh_end: .size abi_test_trampoline,.-abi_test_trampoline ____ @@ -327,18 +327,25 @@ ____ $code .= <<____; # abi_test_bad_unwind_wrong_register preserves the ABI, but annotates the wrong -# register in CFI metadata. +# register in unwind metadata. # void abi_test_bad_unwind_wrong_register(void); .type abi_test_bad_unwind_wrong_register, \@abi-omnipotent .globl abi_test_bad_unwind_wrong_register .align 16 abi_test_bad_unwind_wrong_register: .cfi_startproc +.Labi_test_bad_unwind_wrong_register_seh_begin: pushq %r12 .cfi_push %r13 # This should be %r12 +.Labi_test_bad_unwind_wrong_register_seh_push_r13: + # Windows evaluates epilogs directly in the unwinder, rather than using + # unwind codes. Add a nop so there is one non-epilog point (immediately + # before the nop) where the unwinder can observe the mistake. + nop popq %r12 .cfi_pop %r12 ret +.Labi_test_bad_unwind_wrong_register_seh_end: .cfi_endproc .size abi_test_bad_unwind_wrong_register,.-abi_test_bad_unwind_wrong_register @@ -350,20 +357,24 @@ abi_test_bad_unwind_wrong_register: .align 16 abi_test_bad_unwind_temporary: .cfi_startproc +.Labi_test_bad_unwind_temporary_seh_begin: pushq %r12 .cfi_push %r12 +.Labi_test_bad_unwind_temporary_seh_push_r12: - inc %r12 - movq %r12, (%rsp) - # Unwinding from here is incorrect. + movq %r12, %rax + inc %rax + movq %rax, (%rsp) + # Unwinding from here is incorrect. Although %r12 itself has not been + # changed, the unwind codes say to look in (%rsp) instead. - dec %r12 movq %r12, (%rsp) # Unwinding is now fixed. popq %r12 .cfi_pop %r12 ret +.Labi_test_bad_unwind_temporary_seh_end: .cfi_endproc .size abi_test_bad_unwind_temporary,.-abi_test_bad_unwind_temporary @@ -376,7 +387,7 @@ abi_test_get_and_clear_direction_flag: pushfq popq %rax andq \$0x400, %rax - shlq \$10, %rax + shrq \$10, %rax cld ret .size abi_test_get_and_clear_direction_flag,.-abi_test_get_and_clear_direction_flag @@ -392,6 +403,29 @@ abi_test_set_direction_flag: ____ if ($win64) { + $code .= <<____; +# abi_test_bad_unwind_epilog preserves the ABI, and correctly annotates the +# prolog, but the epilog does not match Win64's rules, breaking unwind during +# the epilog. +# void abi_test_bad_unwind_epilog(void); +.type abi_test_bad_unwind_epilog, \@abi-omnipotent +.globl abi_test_bad_unwind_epilog +.align 16 +abi_test_bad_unwind_epilog: +.Labi_test_bad_unwind_epilog_seh_begin: + pushq %r12 +.Labi_test_bad_unwind_epilog_seh_push_r12: + + nop + + # The epilog should begin here, but the nop makes it invalid. + popq %r12 + nop + ret +.Labi_test_bad_unwind_epilog_seh_end: +.size abi_test_bad_unwind_epilog,.-abi_test_bad_unwind_epilog +____ + # Add unwind metadata for SEH. # # TODO(davidben): This is all manual right now. Once we've added SEH tests, @@ -401,6 +435,7 @@ if ($win64) { # error-prone and non-standard custom handlers. # See https://docs.microsoft.com/en-us/cpp/build/struct-unwind-code?view=vs-2017 + my $UWOP_PUSH_NONVOL = 0; my $UWOP_ALLOC_LARGE = 1; my $UWOP_ALLOC_SMALL = 2; my $UWOP_SAVE_NONVOL = 4; @@ -412,26 +447,7 @@ if ($win64) { my $unwind_codes = ""; my $num_slots = 0; - if ($stack_alloc_size <= 128) { - my $info = $UWOP_ALLOC_SMALL | ((($stack_alloc_size - 8) / 8) << 4); - $unwind_codes .= <<____; - .byte .Labi_test_trampoline_prolog_alloc-.Labi_test_trampoline_begin - .byte $info -____ - $num_slots++; - } else { - die "stack allocation needs three unwind slots" if ($stack_alloc_size > 512 * 1024 + 8); - my $info = $UWOP_ALLOC_LARGE; - my $value = $stack_alloc_size / 8; - $unwind_codes .= <<____; - .byte .Labi_test_trampoline_prolog_alloc-.Labi_test_trampoline_begin - .byte $info - .value $value -____ - $num_slots += 2; - } - - foreach my $reg (@caller_state) { + foreach my $reg (reverse @caller_state) { $reg = substr($reg, 1); die "unknown register $reg" unless exists($reg_offsets{$reg}); if ($reg =~ /^r/) { @@ -439,7 +455,7 @@ ____ my $info = $UWOP_SAVE_NONVOL | ($UWOP_REG_NUMBER{$reg} << 4); my $value = $reg_offsets{$reg} / 8; $unwind_codes .= <<____; - .byte .Labi_test_trampoline_prolog_$reg-.Labi_test_trampoline_begin + .byte .Labi_test_trampoline_seh_prolog_$reg-.Labi_test_trampoline_seh_begin .byte $info .value $value ____ @@ -448,7 +464,7 @@ ____ my $info = $UWOP_SAVE_XMM128 | (substr($reg, 3) << 4); my $value = $reg_offsets{$reg} / 16; $unwind_codes .= <<____; - .byte .Labi_test_trampoline_prolog_$reg-.Labi_test_trampoline_begin + .byte .Labi_test_trampoline_seh_prolog_$reg-.Labi_test_trampoline_seh_begin .byte $info .value $value ____ @@ -458,25 +474,86 @@ ____ } } + if ($stack_alloc_size <= 128) { + my $info = $UWOP_ALLOC_SMALL | ((($stack_alloc_size - 8) / 8) << 4); + $unwind_codes .= <<____; + .byte .Labi_test_trampoline_seh_prolog_alloc-.Labi_test_trampoline_seh_begin + .byte $info +____ + $num_slots++; + } else { + die "stack allocation needs three unwind slots" if ($stack_alloc_size > 512 * 1024 + 8); + my $info = $UWOP_ALLOC_LARGE; + my $value = $stack_alloc_size / 8; + $unwind_codes .= <<____; + .byte .Labi_test_trampoline_seh_prolog_alloc-.Labi_test_trampoline_seh_begin + .byte $info + .value $value +____ + $num_slots += 2; + } + $code .= <<____; .section .pdata .align 4 # https://docs.microsoft.com/en-us/cpp/build/struct-runtime-function?view=vs-2017 - .rva .Labi_test_trampoline_begin - .rva .Labi_test_trampoline_end - .rva .Labi_test_trampoline_info + .rva .Labi_test_trampoline_seh_begin + .rva .Labi_test_trampoline_seh_end + .rva .Labi_test_trampoline_seh_info + + .rva .Labi_test_bad_unwind_wrong_register_seh_begin + .rva .Labi_test_bad_unwind_wrong_register_seh_end + .rva .Labi_test_bad_unwind_wrong_register_seh_info + + .rva .Labi_test_bad_unwind_temporary_seh_begin + .rva .Labi_test_bad_unwind_temporary_seh_end + .rva .Labi_test_bad_unwind_temporary_seh_info + + .rva .Labi_test_bad_unwind_epilog_seh_begin + .rva .Labi_test_bad_unwind_epilog_seh_end + .rva .Labi_test_bad_unwind_epilog_seh_info .section .xdata .align 8 -.Labi_test_trampoline_info: +.Labi_test_trampoline_seh_info: # https://docs.microsoft.com/en-us/cpp/build/struct-unwind-info?view=vs-2017 .byte 1 # version 1, no flags - .byte .Labi_test_trampoline_prolog_end-.Labi_test_trampoline_begin + .byte .Labi_test_trampoline_seh_prolog_end-.Labi_test_trampoline_seh_begin .byte $num_slots .byte 0 # no frame register $unwind_codes + +.align 8 +.Labi_test_bad_unwind_wrong_register_seh_info: + .byte 1 # version 1, no flags + .byte .Labi_test_bad_unwind_wrong_register_seh_push_r13-.Labi_test_bad_unwind_wrong_register_seh_begin + .byte 1 # one slot + .byte 0 # no frame register + + .byte .Labi_test_bad_unwind_wrong_register_seh_push_r13-.Labi_test_bad_unwind_wrong_register_seh_begin + .byte @{[$UWOP_PUSH_NONVOL | ($UWOP_REG_NUMBER{r13} << 4)]} + +.align 8 +.Labi_test_bad_unwind_temporary_seh_info: + .byte 1 # version 1, no flags + .byte .Labi_test_bad_unwind_temporary_seh_push_r12-.Labi_test_bad_unwind_temporary_seh_begin + .byte 1 # one slot + .byte 0 # no frame register + + .byte .Labi_test_bad_unwind_temporary_seh_push_r12-.Labi_test_bad_unwind_temporary_seh_begin + .byte @{[$UWOP_PUSH_NONVOL | ($UWOP_REG_NUMBER{r12} << 4)]} + +.align 8 +.Labi_test_bad_unwind_epilog_seh_info: + .byte 1 # version 1, no flags + .byte .Labi_test_bad_unwind_epilog_seh_push_r12-.Labi_test_bad_unwind_epilog_seh_begin + .byte 1 # one slot + .byte 0 # no frame register + + .byte .Labi_test_bad_unwind_epilog_seh_push_r12-.Labi_test_bad_unwind_epilog_seh_begin + .byte @{[$UWOP_PUSH_NONVOL | ($UWOP_REG_NUMBER{r12} << 4)]} ____ } print $code; -close STDOUT; +close STDOUT or die "error closing STDOUT"; diff --git a/third_party/boringssl/kit/src/crypto/x509/make_many_constraints.go b/third_party/boringssl/kit/src/crypto/x509/make_many_constraints.go index e5074037..578618df 100644 --- a/third_party/boringssl/kit/src/crypto/x509/make_many_constraints.go +++ b/third_party/boringssl/kit/src/crypto/x509/make_many_constraints.go @@ -137,10 +137,10 @@ func main() { }{ {"many_names1.pem", 513, 513}, {"many_names2.pem", 1025, 0}, - {"many_names3.pem", 0, 1025}, + {"many_names3.pem", 1, 1025}, {"some_names1.pem", 256, 256}, {"some_names2.pem", 513, 0}, - {"some_names3.pem", 0, 513}, + {"some_names3.pem", 1, 513}, } for i, leaf := range leaves { leafTemplate := x509.Certificate{ diff --git a/third_party/boringssl/kit/src/crypto/x509/many_names3.pem b/third_party/boringssl/kit/src/crypto/x509/many_names3.pem index dbfa0428..f15638f9 100644 --- a/third_party/boringssl/kit/src/crypto/x509/many_names3.pem +++ b/third_party/boringssl/kit/src/crypto/x509/many_names3.pem @@ -1,5 +1,5 @@ -----BEGIN CERTIFICATE----- -MIJqmDCCaYCgAwIBAgIBBDANBgkqhkiG9w0BAQsFADANMQswCQYDVQQDEwJDQTAg +MIJqrDCCaZSgAwIBAgIBBDANBgkqhkiG9w0BAQsFADANMQswCQYDVQQDEwJDQTAg Fw0wMDAxMDEwMDAwMDBaGA8yMTAwMDEwMTAwMDAwMFowgmfXMRAwDgYDVQQDEwd0 MC50ZXN0MRYwFAYJKoZIhvcNAQkBFgd0MEB0ZXN0MRYwFAYJKoZIhvcNAQkBFgd0 MUB0ZXN0MRYwFAYJKoZIhvcNAQkBFgd0MkB0ZXN0MRYwFAYJKoZIhvcNAQkBFgd0 @@ -560,12 +560,12 @@ AQ8AMIIBCgKCAQEAugvahBkSAUF1fC49vb1bvlPrcl80kop1iLpiuYoz4Qptwy57 oiXCzepBrhtp5UQSjHD4D4hKtgdMgVxX+LRtwgW3mnu/vBu7rzpr/DS8io99p3lq Z1Aky+aNlcMj6MYy8U+YFEevb/V0lRY9oqwmW7BHnXikm/vi6sjIS350U8zb/mRz YeIs2R65LUduTL50+UMgat9ocewI2dv8aO9Dph+8NdGtg8LFYyTTHcUxJoMr1PTO -gnmET19WJH4PrFwk7ZE1QJQQ1L4iKmPeQistuQIDAQABozUwMzAOBgNVHQ8BAf8E -BAMCBaAwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDAYDVR0TAQH/BAIwADANBgkqhkiG -9w0BAQsFAAOCAQEAtMIpnGzOBkJXEBmCsRVbTrg9QgYRlGPG48+cXT2QbIutAmbj -miF+OYg/bRsQtuqcKjnJYog+x6UCU3d34jaMEfEXfHSwF7xPQrqJm45MXhG3so4E -+el5GMAS+SKFQK3w8NPoGhGwn82sz4XV6HMG+ANUxMlCrOcx2jh5UW+7ITjdRwJd -ReJ/JaMpneJdwGFSU9Vn+t7PFb51/pOYqO/PuEANzphovjMVcFZ6mtAQwYDkQZBJ -Vy1/7bPoNmbKD0GAS6HpS+xaJ/DnjjD6Kal2T7GMyvRMogj5BeZ/uEkXCEhvoaBT -os1gaqqnGpZ6JSEDctzjgpCtEPR40yiz1wv1CA== +gnmET19WJH4PrFwk7ZE1QJQQ1L4iKmPeQistuQIDAQABo0kwRzAOBgNVHQ8BAf8E +BAMCBaAwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDAYDVR0TAQH/BAIwADASBgNVHREE +CzAJggd0MC50ZXN0MA0GCSqGSIb3DQEBCwUAA4IBAQAi7LIMyX5Ec514hvjROZ8b +7i4UR3xd5IbniVSej+PKZhG2inN6aX9bksdda0ddYZeRSHAkNJuoabeankQJ/x5x +sxBntWSVLCxz6S8NRrLAPKKPBvFb/W5ns57LP9SrLIij9l/NSd+K/CQNTlfcdorg +4ltPVNwSMp/XXjH6rQYJSbo9MhDoxeqPpv73e4jY0DfGn1a8uwyCXalLjh4EkUyS +Ye0N7MoUKV0IucrXKdgj2sHgBFqNKJ/GVQ422xZRbYqsyIJ0bPD6Fc8VcqfVrvYg +lCYJfu7Xij5n3mjQaSYcbVxH71X8fYhhNq1tk+WtQOXirz2EkSuh1rNGU/LT8Q6r -----END CERTIFICATE----- diff --git a/third_party/boringssl/kit/src/crypto/x509/some_names3.pem b/third_party/boringssl/kit/src/crypto/x509/some_names3.pem index a6d3ee79..7b38bf3c 100644 --- a/third_party/boringssl/kit/src/crypto/x509/some_names3.pem +++ b/third_party/boringssl/kit/src/crypto/x509/some_names3.pem @@ -1,5 +1,5 @@ -----BEGIN CERTIFICATE----- -MII2fzCCNWegAwIBAgIBBzANBgkqhkiG9w0BAQsFADANMQswCQYDVQQDEwJDQTAg +MII2kzCCNXugAwIBAgIBBzANBgkqhkiG9w0BAQsFADANMQswCQYDVQQDEwJDQTAg Fw0wMDAxMDEwMDAwMDBaGA8yMTAwMDEwMTAwMDAwMFowgjO+MRAwDgYDVQQDEwd0 MC50ZXN0MRYwFAYJKoZIhvcNAQkBFgd0MEB0ZXN0MRYwFAYJKoZIhvcNAQkBFgd0 MUB0ZXN0MRYwFAYJKoZIhvcNAQkBFgd0MkB0ZXN0MRYwFAYJKoZIhvcNAQkBFgd0 @@ -282,12 +282,13 @@ M+EKbcMue/hFrLGQXB6a2eQZFn+j3hmexeQF9T8iWxh2S6rzAr1Yj+qXeDBaMf4o BEiEhBxIsaIlws3qQa4baeVEEoxw+A+ISrYHTIFcV/i0bcIFt5p7v7wbu686a/w0 vIqPfad5amdQJMvmjZXDI+jGMvFPmBRHr2/1dJUWPaKsJluwR514pJv74urIyEt+ dFPM2/5kc2HiLNkeuS1Hbky+dPlDIGrfaHHsCNnb/GjvQ6YfvDXRrYPCxWMk0x3F -MSaDK9T0zoJ5hE9fViR+D6xcJO2RNUCUENS+Iipj3kIrLbkCAwEAAaM1MDMwDgYD +MSaDK9T0zoJ5hE9fViR+D6xcJO2RNUCUENS+Iipj3kIrLbkCAwEAAaNJMEcwDgYD VR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMAwGA1UdEwEB/wQCMAAw -DQYJKoZIhvcNAQELBQADggEBAH6ad2kFE0qGDe3ErMdwTGjbBz3T12dDvAUVhGHQ -uZShOdPsXMHD2mUqFgLE0iJFeXB7jOSAKtzmKHNmxZ4W0UZ7eMPPogkgIbG3d3yR -8zBO21CUyOQWChywpKcAou9ji3Kq6pb4+mqq0a5TGIYyGJKSUTv09KI+iHgwteCX -DHzzhuTs8AhodmNO5K/F9YFWJWvQ1NrwyUmOFEw8/UcljyKxFrP2VEov0fWeiTRB -Ps6VaFBW7SEEi8fAM9W5kfsl+iWRvwFcFdXGQt1HbeywCu58DLI4uceHCFb+3MMO -Xv7wJ5UhQODuzwuq7CuZvlxR2tiFoPP+s5fPH0L8MBP5z6w= +EgYDVR0RBAswCYIHdDAudGVzdDANBgkqhkiG9w0BAQsFAAOCAQEAQA/0vvY1gLA2 +0jrPkBVWte7OHzWVkwq7mqgQPR4L9qLLu7Vhelp4dW8n95s1wCbca5j5SJEGv4Uv +0fI1OOK7XQeYdNlHBmvMVW47GoBSo6tuYNPI/y4xnM6ypEZiPKkdj9Ar9qNgURfV +z3s1czip915dyTWgwBy7CTxOlG8NW0uiFgEc9iiDDfQsPwVXiVtxOPtjhPeI3F0J +jh3wctFxBnAvLV9SsDxpWujM1dd/1SSQ25jKQhbKNtiDAC8v+Q043r8ZGHjRdxe8 +W2tVWH/iz9c+ze0P0ao7LKv8eGzoIsrBqICS86X4Zv5lGeTGaD2osF1oNvmmoSlh +536yFa415g== -----END CERTIFICATE----- diff --git a/third_party/boringssl/kit/src/crypto/x509/x509_test.cc b/third_party/boringssl/kit/src/crypto/x509/x509_test.cc index a53ed7a6..1f664b9b 100644 --- a/third_party/boringssl/kit/src/crypto/x509/x509_test.cc +++ b/third_party/boringssl/kit/src/crypto/x509/x509_test.cc @@ -32,6 +32,7 @@ #include "../internal.h" #include "../test/test_util.h" +#include "../x509v3/internal.h" std::string GetTestData(const char *path); @@ -660,6 +661,162 @@ static const char kSelfSignedMismatchAlgorithms[] = "KStYq7X9PKseN+PvmfeoffIKc5R/Ha39oi7cGMVHCr8aiEhsf94=\n" "-----END CERTIFICATE-----\n"; +// kCommonNameWithSANs is a leaf certificate signed by kSANTypesRoot, with +// *.host1.test as the common name and a SAN list of *.host2.test and +// foo.host3.test. +static const char kCommonNameWithSANs[] = + "-----BEGIN CERTIFICATE-----\n" + "MIIB2zCCAUSgAwIBAgIBAzANBgkqhkiG9w0BAQsFADArMRcwFQYDVQQKEw5Cb3Jp\n" + "bmdTU0wgVGVzdDEQMA4GA1UEAxMHUm9vdCBDQTAgFw0wMDAxMDEwMDAwMDBaGA8y\n" + "MDk5MDEwMTAwMDAwMFowNzEeMBwGA1UEChMVQ29tbW9uIG5hbWUgd2l0aCBTQU5z\n" + "MRUwEwYDVQQDDAwqLmhvc3QxLnRlc3QwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNC\n" + "AASgWzfnFnpQrokSLIC+LhCKJDUAY/2usfIDpOnafYoYCasbYetkmOslgyY4Nn07\n" + "zjvjNROprA/0bdULXAkdL9bNo0gwRjAbBgNVHSMEFDASgBBAN9cB+0AvuBx+VAQn\n" + "jFkBMCcGA1UdEQQgMB6CDCouaG9zdDIudGVzdIIOZm9vLmhvc3QzLnRlc3QwDQYJ\n" + "KoZIhvcNAQELBQADgYEAtv2e3hBhsslXB1HTxgusjoschWOVtvGZUaYlhkKzKTCL\n" + "4YpDn50BccnucBU/b9phYvaEZtyzOv4ZXhxTGyLnLrIVB9x5ikfCcfl+LNYNjDwM\n" + "enm/h1zOfJ7wXLyscD4kU29Wc/zxBd70thIgLYn16CC1S9NtXKsXXDXv5VVH/bg=\n" + "-----END CERTIFICATE-----\n"; + +// kCommonNameWithSANs is a leaf certificate signed by kSANTypesRoot, with +// *.host1.test as the common name and no SAN list. +static const char kCommonNameWithoutSANs[] = + "-----BEGIN CERTIFICATE-----\n" + "MIIBtTCCAR6gAwIBAgIBAzANBgkqhkiG9w0BAQsFADArMRcwFQYDVQQKEw5Cb3Jp\n" + "bmdTU0wgVGVzdDEQMA4GA1UEAxMHUm9vdCBDQTAgFw0wMDAxMDEwMDAwMDBaGA8y\n" + "MDk5MDEwMTAwMDAwMFowOjEhMB8GA1UEChMYQ29tbW9uIG5hbWUgd2l0aG91dCBT\n" + "QU5zMRUwEwYDVQQDDAwqLmhvc3QxLnRlc3QwWTATBgcqhkjOPQIBBggqhkjOPQMB\n" + "BwNCAARt2vjlIrPE+kr11VS1rRP/AYQu4fvf1bNw/K9rwYlVBhmLMPYasEmpCtKE\n" + "0bDIFydtDYC3wZDpSS+YiaG40sdAox8wHTAbBgNVHSMEFDASgBBAN9cB+0AvuBx+\n" + "VAQnjFkBMA0GCSqGSIb3DQEBCwUAA4GBAHRbIeaCEytOpJpw9O2dlB656AHe1+t5\n" + "4JiS5mvtzoVOLn7fFk5EFQtZS7sG1Uc2XjlSw+iyvFoTFEqfKyU/mIdc2vBuPwA2\n" + "+YXT8aE4S+UZ9oz5j0gDpikGnkSCW0cyHD8L8fntNjaQRSaM482JpmtdmuxClmWO\n" + "pFFXI2B5usgI\n" + "-----END CERTIFICATE-----\n"; + +// kCommonNameWithEmailSAN is a leaf certificate signed by kSANTypesRoot, with +// *.host1.test as the common name and the email address test@host2.test in the +// SAN list. +static const char kCommonNameWithEmailSAN[] = + "-----BEGIN CERTIFICATE-----\n" + "MIIBvDCCASWgAwIBAgIBAjANBgkqhkiG9w0BAQsFADArMRcwFQYDVQQKEw5Cb3Jp\n" + "bmdTU0wgVGVzdDEQMA4GA1UEAxMHUm9vdCBDQTAgFw0wMDAxMDEwMDAwMDBaGA8y\n" + "MDk5MDEwMTAwMDAwMFowFzEVMBMGA1UEAwwMKi5ob3N0MS50ZXN0MFkwEwYHKoZI\n" + "zj0CAQYIKoZIzj0DAQcDQgAEtevOxcTjpPzlNGoUMFfZyr1k03/Hiuh+EsnuScDs\n" + "8XLKi6fDkvSaDClI99ycabQZRPIrvyT+dglDC6ugQd+CYqNJMEcwDAYDVR0TAQH/\n" + "BAIwADAbBgNVHSMEFDASgBBAN9cB+0AvuBx+VAQnjFkBMBoGA1UdEQQTMBGBD3Rl\n" + "c3RAaG9zdDIudGVzdDANBgkqhkiG9w0BAQsFAAOBgQCGbqb78OWJWl4zb+qw0Dz2\n" + "HJgZZJt6/+nNG/XJKdaYeS4eofsbwsJI4fuuOF6ZvYCJxVNtGqdfZDgycvFA9hjv\n" + "NGosBF1/spP17cmzTahLjxs71jDvHV/EQJbKGl/Zpta1Em1VrzSrwoOFabPXzZTJ\n" + "aet/mER21Z/9ZsTUoJQPJw==\n" + "-----END CERTIFICATE-----\n"; + +// kCommonNameWithIPSAN is a leaf certificate signed by kSANTypesRoot, with +// *.host1.test as the common name and the IP address 127.0.0.1 in the +// SAN list. +static const char kCommonNameWithIPSAN[] = + "-----BEGIN CERTIFICATE-----\n" + "MIIBsTCCARqgAwIBAgIBAjANBgkqhkiG9w0BAQsFADArMRcwFQYDVQQKEw5Cb3Jp\n" + "bmdTU0wgVGVzdDEQMA4GA1UEAxMHUm9vdCBDQTAgFw0wMDAxMDEwMDAwMDBaGA8y\n" + "MDk5MDEwMTAwMDAwMFowFzEVMBMGA1UEAwwMKi5ob3N0MS50ZXN0MFkwEwYHKoZI\n" + "zj0CAQYIKoZIzj0DAQcDQgAEFKrgkxm8PysXbwnHQeTD3p8YY0+sY4ssnZgmj8wX\n" + "KTyn893fdBHWlz71GO6t82wMTF5d+ZYwI2XU52pfl4SB2aM+MDwwDAYDVR0TAQH/\n" + "BAIwADAbBgNVHSMEFDASgBBAN9cB+0AvuBx+VAQnjFkBMA8GA1UdEQQIMAaHBH8A\n" + "AAEwDQYJKoZIhvcNAQELBQADgYEAQWZ8Oj059ZjS109V/ijMYT28xuAN5n6HHxCO\n" + "DopTP56Zu9+gme5wTETWEfocspZvgecoUOcedTFoKSQ7JafO09NcVLA+D6ddYpju\n" + "mgfuiLy9dDhqvX/NHaLBMxOBWWbOLwWE+ibyX+pOzjWRCw1L7eUXOr6PhZAOQsmU\n" + "D0+O6KI=\n" + "-----END CERTIFICATE-----\n"; + +// kConstrainedIntermediate is an intermediate signed by kSANTypesRoot, with +// permitted DNS names of permitted1.test and foo.permitted2.test and an +// excluded DNS name of excluded.permitted1.test. Its private key is: +// +// -----BEGIN PRIVATE KEY----- +// MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgTXUM4tJWM7OzATty +// JhNOfIv/d8heWFBeKOfMR+RfaROhRANCAASbbbWYiN6mn+BCpg4XNpibOH0D/DN4 +// kZ5C/Ml2YVomC9T83OKk2CzB8fPAabPb4P4Vv+fIabpEfjWS5nzKLY1y +// -----END PRIVATE KEY----- +static const char kConstrainedIntermediate[] = + "-----BEGIN CERTIFICATE-----\n" + "MIICDjCCAXegAwIBAgIBAjANBgkqhkiG9w0BAQsFADArMRcwFQYDVQQKEw5Cb3Jp\n" + "bmdTU0wgVGVzdDEQMA4GA1UEAxMHUm9vdCBDQTAgFw0wMDAxMDEwMDAwMDBaGA8y\n" + "MDk5MDEwMTAwMDAwMFowKDEmMCQGA1UEAxMdTmFtZSBDb25zdHJhaW50cyBJbnRl\n" + "cm1lZGlhdGUwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASbbbWYiN6mn+BCpg4X\n" + "NpibOH0D/DN4kZ5C/Ml2YVomC9T83OKk2CzB8fPAabPb4P4Vv+fIabpEfjWS5nzK\n" + "LY1yo4GJMIGGMA8GA1UdEwEB/wQFMAMBAf8wGwYDVR0jBBQwEoAQQDfXAftAL7gc\n" + "flQEJ4xZATBWBgNVHR4BAf8ETDBKoCowEYIPcGVybWl0dGVkMS50ZXN0MBWCE2Zv\n" + "by5wZXJtaXR0ZWQyLnRlc3ShHDAaghhleGNsdWRlZC5wZXJtaXR0ZWQxLnRlc3Qw\n" + "DQYJKoZIhvcNAQELBQADgYEAFq1Ka05hiKREwRpSceQPzIIH4B5a5IVBg5/EvmQI\n" + "9V0fXyAE1GmahPt70sIBxIgzNTEaY8P/IoOuCdlZWe0msmyEO3S6YSAzOWR5Van6\n" + "cXmFM1uMd95TlkxUMRdV+jKJTvG6R/BM2zltaV7Xt662k5HtzT5Svw0rZlFaggZz\n" + "UyM=\n" + "-----END CERTIFICATE-----\n"; + +// kCommonNamePermittedLeaf is a leaf certificate signed by +// kConstrainedIntermediate. Its common name is permitted by the name +// constraints. +static const char kCommonNamePermittedLeaf[] = + "-----BEGIN CERTIFICATE-----\n" + "MIIBaDCCAQ2gAwIBAgIBAzAKBggqhkjOPQQDAjAoMSYwJAYDVQQDEx1OYW1lIENv\n" + "bnN0cmFpbnRzIEludGVybWVkaWF0ZTAgFw0wMDAxMDEwMDAwMDBaGA8yMDk5MDEw\n" + "MTAwMDAwMFowPjEeMBwGA1UEChMVQ29tbW9uIG5hbWUgcGVybWl0dGVkMRwwGgYD\n" + "VQQDExNmb28ucGVybWl0dGVkMS50ZXN0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcD\n" + "QgAENX5Ycs8q8MRzPYUz6DqLHhJR3wcmniFRgkiEa7MxE/mRe00y0VGwH7xi7Aoc\n" + "emXPrtD4JwN5bssbcxWGAKYYzaMQMA4wDAYDVR0TAQH/BAIwADAKBggqhkjOPQQD\n" + "AgNJADBGAiEAtsnWuRQXtw2xbieC78Y8SVEtTjcZUx8uZyQe1GPLfGICIQDR4fNY\n" + "yg3PC94ydPNQZVsFxAne32CbonWWsokalTFpUQ==\n" + "-----END CERTIFICATE-----\n"; +static const char kCommonNamePermitted[] = "foo.permitted1.test"; + +// kCommonNameNotPermittedLeaf is a leaf certificate signed by +// kConstrainedIntermediate. Its common name is not permitted by the name +// constraints. +static const char kCommonNameNotPermittedLeaf[] = + "-----BEGIN CERTIFICATE-----\n" + "MIIBazCCARCgAwIBAgIBBDAKBggqhkjOPQQDAjAoMSYwJAYDVQQDEx1OYW1lIENv\n" + "bnN0cmFpbnRzIEludGVybWVkaWF0ZTAgFw0wMDAxMDEwMDAwMDBaGA8yMDk5MDEw\n" + "MTAwMDAwMFowQTEiMCAGA1UEChMZQ29tbW9uIG5hbWUgbm90IHBlcm1pdHRlZDEb\n" + "MBkGA1UEAxMSbm90LXBlcm1pdHRlZC50ZXN0MFkwEwYHKoZIzj0CAQYIKoZIzj0D\n" + "AQcDQgAEzfghKuWf0JoXb0Drp09C3yXMSQQ1byt+AUaymvsHOWsxQ9v1Q+vkF/IM\n" + "HRqGTk2TyxrB2iClVEn/Uu+YtYox1KMQMA4wDAYDVR0TAQH/BAIwADAKBggqhkjO\n" + "PQQDAgNJADBGAiEAxaUslxmoWL1tIvnDz7gDkto/HcmdU0jHVuUQLXcCG8wCIQCN\n" + "5xZjitlCQU8UB5qSu9wH4B+0JcVO3Ss4Az76HEJWMw==\n" + "-----END CERTIFICATE-----\n"; +static const char kCommonNameNotPermitted[] = "not-permitted.test"; + +// kCommonNameNotPermittedWithSANsLeaf is a leaf certificate signed by +// kConstrainedIntermediate. Its common name is not permitted by the name +// constraints but it has a SAN list. +static const char kCommonNameNotPermittedWithSANsLeaf[] = + "-----BEGIN CERTIFICATE-----\n" + "MIIBqTCCAU+gAwIBAgIBBjAKBggqhkjOPQQDAjAoMSYwJAYDVQQDEx1OYW1lIENv\n" + "bnN0cmFpbnRzIEludGVybWVkaWF0ZTAgFw0wMDAxMDEwMDAwMDBaGA8yMDk5MDEw\n" + "MTAwMDAwMFowSzEsMCoGA1UEChMjQ29tbW9uIG5hbWUgbm90IHBlcm1pdHRlZCB3\n" + "aXRoIFNBTlMxGzAZBgNVBAMTEm5vdC1wZXJtaXR0ZWQudGVzdDBZMBMGByqGSM49\n" + "AgEGCCqGSM49AwEHA0IABKsn9wOApXFHrqhLdQgbFSeaSoAIbxgO0zVSRZUb5naR\n" + "93zoL3MFOvZEF8xiEqh7le+l3XuUig0fwqpcsZzRNJajRTBDMAwGA1UdEwEB/wQC\n" + "MAAwMwYDVR0RBCwwKoITZm9vLnBlcm1pdHRlZDEudGVzdIITZm9vLnBlcm1pdHRl\n" + "ZDIudGVzdDAKBggqhkjOPQQDAgNIADBFAiACk+1f184KkKAXuntmrz+Ygcq8MiZl\n" + "4delx44FtcNaegIhAIA5nYfzxNcTXxDo3U+x1vSLH6Y7faLvHiFySp7O//q+\n" + "-----END CERTIFICATE-----\n"; +static const char kCommonNameNotPermittedWithSANs[] = "not-permitted.test"; + +// kCommonNameNotDNSLeaf is a leaf certificate signed by +// kConstrainedIntermediate. Its common name is not a DNS name. +static const char kCommonNameNotDNSLeaf[] = + "-----BEGIN CERTIFICATE-----\n" + "MIIBYTCCAQagAwIBAgIBCDAKBggqhkjOPQQDAjAoMSYwJAYDVQQDEx1OYW1lIENv\n" + "bnN0cmFpbnRzIEludGVybWVkaWF0ZTAgFw0wMDAxMDEwMDAwMDBaGA8yMDk5MDEw\n" + "MTAwMDAwMFowNzEcMBoGA1UEChMTQ29tbW9uIG5hbWUgbm90IEROUzEXMBUGA1UE\n" + "AxMOTm90IGEgRE5TIG5hbWUwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASnueyc\n" + "Zxtnw5ke2J2T0/LwAK37auQP/RSFd9mem+BJVbgviawtAlignJmafp7Zw4/GdYEJ\n" + "Vm8qlriOJtluvXGcoxAwDjAMBgNVHRMBAf8EAjAAMAoGCCqGSM49BAMCA0kAMEYC\n" + "IQChUAmVNI39VHe0zemRE09VDcSEgOxr1nTvjLcg/Q8pVQIhAJYZnJI0YZAi05QH\n" + "RHNlAkTK2TnUaVn3fGSylaLiFS1r\n" + "-----END CERTIFICATE-----\n"; +static const char kCommonNameNotDNS[] = "Not a DNS name"; + // CertFromPEM parses the given, NUL-terminated pem block and returns an // |X509*|. static bssl::UniquePtr CertFromPEM(const char *pem) { @@ -723,7 +880,8 @@ static int Verify(X509 *leaf, const std::vector &roots, const std::vector &intermediates, const std::vector &crls, unsigned long flags, bool use_additional_untrusted, - std::function configure_callback) { + std::function configure_callback, + int (*verify_callback)(int, X509_STORE_CTX *) = nullptr) { bssl::UniquePtr roots_stack(CertsToStack(roots)); bssl::UniquePtr intermediates_stack( CertsToStack(intermediates)); @@ -1169,9 +1327,11 @@ TEST(X509Test, Ed25519Sign) { uint8_t pub_bytes[32], priv_bytes[64]; ED25519_keypair(pub_bytes, priv_bytes); - bssl::UniquePtr pub(EVP_PKEY_new_ed25519_public(pub_bytes)); + bssl::UniquePtr pub( + EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, nullptr, pub_bytes, 32)); ASSERT_TRUE(pub); - bssl::UniquePtr priv(EVP_PKEY_new_ed25519_private(priv_bytes)); + bssl::UniquePtr priv( + EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, priv_bytes, 32)); ASSERT_TRUE(priv); bssl::ScopedEVP_MD_CTX md_ctx; @@ -1744,3 +1904,172 @@ TEST(X509Test, PartialBIOReturn) { ASSERT_TRUE(cert2); EXPECT_EQ(0, X509_cmp(cert.get(), cert2.get())); } + +TEST(X509Test, CommonNameFallback) { + bssl::UniquePtr root = CertFromPEM(kSANTypesRoot); + ASSERT_TRUE(root); + bssl::UniquePtr with_sans = CertFromPEM(kCommonNameWithSANs); + ASSERT_TRUE(with_sans); + bssl::UniquePtr without_sans = CertFromPEM(kCommonNameWithoutSANs); + ASSERT_TRUE(without_sans); + bssl::UniquePtr with_email = CertFromPEM(kCommonNameWithEmailSAN); + ASSERT_TRUE(with_email); + bssl::UniquePtr with_ip = CertFromPEM(kCommonNameWithIPSAN); + ASSERT_TRUE(with_ip); + + auto verify_cert = [&](X509 *leaf, unsigned flags, const char *host) { + return Verify( + leaf, {root.get()}, {}, {}, 0, false, [&](X509_VERIFY_PARAM *param) { + ASSERT_TRUE(X509_VERIFY_PARAM_set1_host(param, host, strlen(host))); + X509_VERIFY_PARAM_set_hostflags(param, flags); + }); + }; + + // By default, the common name is ignored if the SAN list is present but + // otherwise is checked. + EXPECT_EQ(X509_V_ERR_HOSTNAME_MISMATCH, + verify_cert(with_sans.get(), 0 /* no flags */, "foo.host1.test")); + EXPECT_EQ(X509_V_OK, + verify_cert(with_sans.get(), 0 /* no flags */, "foo.host2.test")); + EXPECT_EQ(X509_V_OK, + verify_cert(with_sans.get(), 0 /* no flags */, "foo.host3.test")); + EXPECT_EQ(X509_V_OK, verify_cert(without_sans.get(), 0 /* no flags */, + "foo.host1.test")); + EXPECT_EQ(X509_V_ERR_HOSTNAME_MISMATCH, + verify_cert(with_email.get(), 0 /* no flags */, "foo.host1.test")); + EXPECT_EQ(X509_V_ERR_HOSTNAME_MISMATCH, + verify_cert(with_ip.get(), 0 /* no flags */, "foo.host1.test")); + + // X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT is ignored. + EXPECT_EQ(X509_V_ERR_HOSTNAME_MISMATCH, + verify_cert(with_sans.get(), X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT, + "foo.host1.test")); + EXPECT_EQ(X509_V_OK, + verify_cert(with_sans.get(), X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT, + "foo.host2.test")); + EXPECT_EQ(X509_V_OK, + verify_cert(with_sans.get(), X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT, + "foo.host3.test")); + EXPECT_EQ(X509_V_OK, verify_cert(without_sans.get(), + X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT, + "foo.host1.test")); + EXPECT_EQ(X509_V_ERR_HOSTNAME_MISMATCH, + verify_cert(with_email.get(), X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT, + "foo.host1.test")); + EXPECT_EQ(X509_V_ERR_HOSTNAME_MISMATCH, + verify_cert(with_ip.get(), X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT, + "foo.host1.test")); + + // X509_CHECK_FLAG_NEVER_CHECK_SUBJECT implements the correct behavior: the + // common name is never checked. + EXPECT_EQ(X509_V_ERR_HOSTNAME_MISMATCH, + verify_cert(with_sans.get(), X509_CHECK_FLAG_NEVER_CHECK_SUBJECT, + "foo.host1.test")); + EXPECT_EQ(X509_V_OK, + verify_cert(with_sans.get(), X509_CHECK_FLAG_NEVER_CHECK_SUBJECT, + "foo.host2.test")); + EXPECT_EQ(X509_V_OK, + verify_cert(with_sans.get(), X509_CHECK_FLAG_NEVER_CHECK_SUBJECT, + "foo.host3.test")); + EXPECT_EQ(X509_V_ERR_HOSTNAME_MISMATCH, + verify_cert(without_sans.get(), X509_CHECK_FLAG_NEVER_CHECK_SUBJECT, + "foo.host1.test")); + EXPECT_EQ(X509_V_ERR_HOSTNAME_MISMATCH, + verify_cert(with_email.get(), X509_CHECK_FLAG_NEVER_CHECK_SUBJECT, + "foo.host1.test")); + EXPECT_EQ(X509_V_ERR_HOSTNAME_MISMATCH, + verify_cert(with_ip.get(), X509_CHECK_FLAG_NEVER_CHECK_SUBJECT, + "foo.host1.test")); +} + +TEST(X509Test, LooksLikeDNSName) { + static const char *kValid[] = { + "example.com", + "eXample123-.com", + "*.example.com", + "exa_mple.com", + "example.com.", + "project-dev:us-central1:main", + }; + static const char *kInvalid[] = { + "-eXample123-.com", + "", + ".", + "*", + "*.", + "example..com", + ".example.com", + "example.com..", + "*foo.example.com", + "foo.*.example.com", + "foo,bar", + }; + + for (const char *str : kValid) { + SCOPED_TRACE(str); + EXPECT_TRUE(x509v3_looks_like_dns_name( + reinterpret_cast(str), strlen(str))); + } + for (const char *str : kInvalid) { + SCOPED_TRACE(str); + EXPECT_FALSE(x509v3_looks_like_dns_name( + reinterpret_cast(str), strlen(str))); + } +} + +TEST(X509Test, CommonNameAndNameConstraints) { + bssl::UniquePtr root = CertFromPEM(kSANTypesRoot); + ASSERT_TRUE(root); + bssl::UniquePtr intermediate = CertFromPEM(kConstrainedIntermediate); + ASSERT_TRUE(intermediate); + bssl::UniquePtr permitted = CertFromPEM(kCommonNamePermittedLeaf); + ASSERT_TRUE(permitted); + bssl::UniquePtr not_permitted = + CertFromPEM(kCommonNameNotPermittedLeaf); + ASSERT_TRUE(not_permitted); + bssl::UniquePtr not_permitted_with_sans = + CertFromPEM(kCommonNameNotPermittedWithSANsLeaf); + ASSERT_TRUE(not_permitted_with_sans); + bssl::UniquePtr not_dns = CertFromPEM(kCommonNameNotDNSLeaf); + ASSERT_TRUE(not_dns); + + auto verify_cert = [&](X509 *leaf, unsigned flags, const char *host) { + return Verify( + leaf, {root.get()}, {intermediate.get()}, {}, 0, false, + [&](X509_VERIFY_PARAM *param) { + ASSERT_TRUE(X509_VERIFY_PARAM_set1_host(param, host, strlen(host))); + X509_VERIFY_PARAM_set_hostflags(param, flags); + }); + }; + + // Certificates which would otherwise trigger the common name fallback are + // rejected whenever there are name constraints. We do this whether or not + // the common name matches the constraints. + EXPECT_EQ( + X509_V_ERR_NAME_CONSTRAINTS_WITHOUT_SANS, + verify_cert(permitted.get(), 0 /* no flags */, kCommonNamePermitted)); + EXPECT_EQ(X509_V_ERR_NAME_CONSTRAINTS_WITHOUT_SANS, + verify_cert(not_permitted.get(), 0 /* no flags */, + kCommonNameNotPermitted)); + + // This occurs even if the built-in name checks aren't used. The caller may + // separately call |X509_check_host|. + EXPECT_EQ(X509_V_ERR_NAME_CONSTRAINTS_WITHOUT_SANS, + Verify(not_permitted.get(), {root.get()}, {intermediate.get()}, {}, + 0 /* no flags */, false, nullptr)); + + // If the leaf certificate has SANs, the common name fallback is always + // disabled, so the name constraints do not apply. + EXPECT_EQ(X509_V_OK, Verify(not_permitted_with_sans.get(), {root.get()}, + {intermediate.get()}, {}, 0, false, nullptr)); + EXPECT_EQ(X509_V_ERR_HOSTNAME_MISMATCH, + verify_cert(not_permitted_with_sans.get(), 0 /* no flags */, + kCommonNameNotPermittedWithSANs)); + + // If the common name does not look like a DNS name, we apply neither name + // constraints nor common name fallback. + EXPECT_EQ(X509_V_OK, Verify(not_dns.get(), {root.get()}, {intermediate.get()}, + {}, 0, false, nullptr)); + EXPECT_EQ(X509_V_ERR_HOSTNAME_MISMATCH, + verify_cert(not_dns.get(), 0 /* no flags */, kCommonNameNotDNS)); +} diff --git a/third_party/boringssl/kit/src/crypto/x509/x509_txt.c b/third_party/boringssl/kit/src/crypto/x509/x509_txt.c index 753e7202..8e6ac27d 100644 --- a/third_party/boringssl/kit/src/crypto/x509/x509_txt.c +++ b/third_party/boringssl/kit/src/crypto/x509/x509_txt.c @@ -54,13 +54,10 @@ * copied and put under another distribution licence * [including the GNU Public Licence.] */ -#include #include const char *X509_verify_cert_error_string(long n) { - static char buf[100]; - switch ((int)n) { case X509_V_OK: return ("ok"); @@ -198,8 +195,10 @@ const char *X509_verify_cert_error_string(long n) case X509_V_ERR_STORE_LOOKUP: return ("Issuer certificate lookup error"); + case X509_V_ERR_NAME_CONSTRAINTS_WITHOUT_SANS: + return "Issuer has name constraints but leaf has no SANs"; + default: - BIO_snprintf(buf, sizeof buf, "error number %ld", n); - return (buf); + return "unknown certificate verification error"; } } diff --git a/third_party/boringssl/kit/src/crypto/x509/x509_vfy.c b/third_party/boringssl/kit/src/crypto/x509/x509_vfy.c index 5af3fb32..fff97fac 100644 --- a/third_party/boringssl/kit/src/crypto/x509/x509_vfy.c +++ b/third_party/boringssl/kit/src/crypto/x509/x509_vfy.c @@ -70,6 +70,7 @@ #include "vpm_int.h" #include "../internal.h" +#include "../x509v3/internal.h" static CRYPTO_EX_DATA_CLASS g_ex_data_class = CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA; @@ -710,13 +711,40 @@ static int check_chain_extensions(X509_STORE_CTX *ctx) return ok; } +static int reject_dns_name_in_common_name(X509 *x509) +{ + X509_NAME *name = X509_get_subject_name(x509); + int i = -1; + for (;;) { + i = X509_NAME_get_index_by_NID(name, NID_commonName, i); + if (i == -1) { + return X509_V_OK; + } + + X509_NAME_ENTRY *entry = X509_NAME_get_entry(name, i); + ASN1_STRING *common_name = X509_NAME_ENTRY_get_data(entry); + unsigned char *idval; + int idlen = ASN1_STRING_to_UTF8(&idval, common_name); + if (idlen < 0) { + return X509_V_ERR_OUT_OF_MEM; + } + /* Only process attributes that look like host names. Note it is + * important that this check be mirrored in |X509_check_host|. */ + int looks_like_dns = x509v3_looks_like_dns_name(idval, (size_t)idlen); + OPENSSL_free(idval); + if (looks_like_dns) { + return X509_V_ERR_NAME_CONSTRAINTS_WITHOUT_SANS; + } + } +} + static int check_name_constraints(X509_STORE_CTX *ctx) { - X509 *x; int i, j, rv; + int has_name_constraints = 0; /* Check name constraints for all certificates */ for (i = sk_X509_num(ctx->chain) - 1; i >= 0; i--) { - x = sk_X509_value(ctx->chain, i); + X509 *x = sk_X509_value(ctx->chain, i); /* Ignore self issued certs unless last in chain */ if (i && (x->ex_flags & EXFLAG_SI)) continue; @@ -729,6 +757,7 @@ static int check_name_constraints(X509_STORE_CTX *ctx) for (j = sk_X509_num(ctx->chain) - 1; j > i; j--) { NAME_CONSTRAINTS *nc = sk_X509_value(ctx->chain, j)->nc; if (nc) { + has_name_constraints = 1; rv = NAME_CONSTRAINTS_check(x, nc); switch (rv) { case X509_V_OK: @@ -747,6 +776,36 @@ static int check_name_constraints(X509_STORE_CTX *ctx) } } } + + /* Name constraints do not match against the common name, but + * |X509_check_host| still implements the legacy behavior where, on + * certificates lacking a SAN list, DNS-like names in the common name are + * checked instead. + * + * While we could apply the name constraints to the common name, name + * constraints are rare enough that can hold such certificates to a higher + * standard. Note this does not make "DNS-like" heuristic failures any + * worse. A decorative common-name misidentified as a DNS name would fail + * the name constraint anyway. */ + X509 *leaf = sk_X509_value(ctx->chain, 0); + if (has_name_constraints && leaf->altname == NULL) { + rv = reject_dns_name_in_common_name(leaf); + switch (rv) { + case X509_V_OK: + break; + case X509_V_ERR_OUT_OF_MEM: + ctx->error = rv; + return 0; + default: + ctx->error = rv; + ctx->error_depth = i; + ctx->current_cert = leaf; + if (!ctx->verify_cb(0, ctx)) + return 0; + break; + } + } + return 1; } diff --git a/third_party/boringssl/kit/src/crypto/x509v3/internal.h b/third_party/boringssl/kit/src/crypto/x509v3/internal.h index e6be6841..c143d735 100644 --- a/third_party/boringssl/kit/src/crypto/x509v3/internal.h +++ b/third_party/boringssl/kit/src/crypto/x509v3/internal.h @@ -43,6 +43,11 @@ unsigned char *x509v3_hex_to_bytes(const char *str, long *len); // followed by '.'. Otherwise, it returns a non-zero number. int x509v3_name_cmp(const char *name, const char *cmp); +// x509v3_looks_like_dns_name returns one if |in| looks like a DNS name and zero +// otherwise. +OPENSSL_EXPORT int x509v3_looks_like_dns_name(const unsigned char *in, + size_t len); + #if defined(__cplusplus) } /* extern C */ diff --git a/third_party/boringssl/kit/src/crypto/x509v3/v3_utl.c b/third_party/boringssl/kit/src/crypto/x509v3/v3_utl.c index 2a293dc8..86c49403 100644 --- a/third_party/boringssl/kit/src/crypto/x509v3/v3_utl.c +++ b/third_party/boringssl/kit/src/crypto/x509v3/v3_utl.c @@ -909,6 +909,53 @@ static int equal_wildcard(const unsigned char *pattern, size_t pattern_len, subject, subject_len, flags); } +int x509v3_looks_like_dns_name(const unsigned char *in, size_t len) { + /* This function is used as a heuristic for whether a common name is a + * hostname to be matched, or merely a decorative name to describe the + * subject. This heuristic must be applied to both name constraints and the + * common name fallback, so it must be loose enough to accept hostname + * common names, and tight enough to reject decorative common names. */ + + if (len > 0 && in[len - 1] == '.') { + len--; + } + + /* Wildcards are allowed in front. */ + if (len >= 2 && in[0] == '*' && in[1] == '.') { + in += 2; + len -= 2; + } + + if (len == 0) { + return 0; + } + + size_t label_start = 0; + for (size_t i = 0; i < len; i++) { + unsigned char c = in[i]; + if ((c >= 'a' && c <= 'z') || + (c >= '0' && c <= '9') || + (c >= 'A' && c <= 'Z') || + (c == '-' && i > label_start) || + /* These are not valid characters in hostnames, but commonly found + * in deployments outside the Web PKI. */ + c == '_' || + c == ':') { + continue; + } + + /* Labels must not be empty. */ + if (c == '.' && i > label_start && i < len - 1) { + label_start = i + 1; + continue; + } + + return 0; + } + + return 1; +} + /* * Compare an ASN1_STRING to a supplied string. If they match return 1. If * cmp_type > 0 only compare if string matches the type, otherwise convert it @@ -916,8 +963,8 @@ static int equal_wildcard(const unsigned char *pattern, size_t pattern_len, */ static int do_check_string(ASN1_STRING *a, int cmp_type, equal_fn equal, - unsigned int flags, const char *b, size_t blen, - char **peername) + unsigned int flags, int check_type, const char *b, + size_t blen, char **peername) { int rv = 0; @@ -938,7 +985,17 @@ static int do_check_string(ASN1_STRING *a, int cmp_type, equal_fn equal, astrlen = ASN1_STRING_to_UTF8(&astr, a); if (astrlen < 0) return -1; - rv = equal(astr, astrlen, (unsigned char *)b, blen, flags); + /* + * We check the common name against DNS name constraints if it passes + * |x509v3_looks_like_dns_name|. Thus we must not consider common names + * for DNS fallbacks if they fail this check. + */ + if (check_type == GEN_DNS && + !x509v3_looks_like_dns_name(astr, astrlen)) { + rv = 0; + } else { + rv = equal(astr, astrlen, (unsigned char *)b, blen, flags); + } if (rv > 0 && peername) *peername = BUF_strndup((char *)astr, astrlen); OPENSSL_free(astr); @@ -955,7 +1012,6 @@ static int do_x509_check(X509 *x, const char *chk, size_t chklen, int j; int cnid = NID_undef; int alt_type; - int san_present = 0; int rv = 0; equal_fn equal; @@ -988,7 +1044,6 @@ static int do_x509_check(X509 *x, const char *chk, size_t chklen, gen = sk_GENERAL_NAME_value(gens, i); if (gen->type != check_type) continue; - san_present = 1; if (check_type == GEN_EMAIL) cstr = gen->d.rfc822Name; else if (check_type == GEN_DNS) @@ -996,21 +1051,16 @@ static int do_x509_check(X509 *x, const char *chk, size_t chklen, else cstr = gen->d.iPAddress; /* Positive on success, negative on error! */ - if ((rv = do_check_string(cstr, alt_type, equal, flags, + if ((rv = do_check_string(cstr, alt_type, equal, flags, check_type, chk, chklen, peername)) != 0) break; } GENERAL_NAMES_free(gens); - if (rv != 0) - return rv; - if (cnid == NID_undef - || (san_present - && !(flags & X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT))) - return 0; + return rv; } /* We're done if CN-ID is not pertinent */ - if (cnid == NID_undef) + if (cnid == NID_undef || (flags & X509_CHECK_FLAG_NEVER_CHECK_SUBJECT)) return 0; j = -1; @@ -1021,7 +1071,7 @@ static int do_x509_check(X509 *x, const char *chk, size_t chklen, ne = X509_NAME_get_entry(name, j); str = X509_NAME_ENTRY_get_data(ne); /* Positive on success, negative on error! */ - if ((rv = do_check_string(str, -1, equal, flags, + if ((rv = do_check_string(str, -1, equal, flags, check_type, chk, chklen, peername)) != 0) return rv; } diff --git a/third_party/boringssl/kit/src/crypto/x509v3/v3name_test.cc b/third_party/boringssl/kit/src/crypto/x509v3/v3name_test.cc index 0736120f..c1da9c85 100644 --- a/third_party/boringssl/kit/src/crypto/x509v3/v3name_test.cc +++ b/third_party/boringssl/kit/src/crypto/x509v3/v3name_test.cc @@ -65,6 +65,7 @@ #include #include "../internal.h" +#include "internal.h" static const char *const names[] = { @@ -344,7 +345,7 @@ static void run_cert(X509 *crt, const char *nameincert, ret = X509_check_host(crt, name, namelen, 0, NULL); match = -1; if (ret < 0) { - fprintf(stderr, "internal error in X509_check_host"); + fprintf(stderr, "internal error in X509_check_host\n"); ++errors; } else if (fn->host) { if (ret == 1 && !samename) @@ -359,7 +360,7 @@ static void run_cert(X509 *crt, const char *nameincert, X509_CHECK_FLAG_NO_WILDCARDS, NULL); match = -1; if (ret < 0) { - fprintf(stderr, "internal error in X509_check_host"); + fprintf(stderr, "internal error in X509_check_host\n"); ++errors; } else if (fn->host) { if (ret == 1 && !samename) @@ -391,6 +392,15 @@ TEST(X509V3Test, NameTest) { while (pfn->name) { const char *const *pname = names; while (*pname) { + // The common name fallback requires the name look sufficiently + // DNS-like. + if (strcmp(pfn->name, "set CN") == 0 && + !x509v3_looks_like_dns_name( + reinterpret_cast(*pname), + strlen(*pname))) { + ++pname; + continue; + } bssl::UniquePtr crt(make_cert()); ASSERT_TRUE(crt); ASSERT_TRUE(pfn->fn(crt.get(), *pname)); diff --git a/third_party/boringssl/kit/src/decrepit/blowfish/blowfish_test.cc b/third_party/boringssl/kit/src/decrepit/blowfish/blowfish_test.cc index d19346aa..4b08fe4b 100644 --- a/third_party/boringssl/kit/src/decrepit/blowfish/blowfish_test.cc +++ b/third_party/boringssl/kit/src/decrepit/blowfish/blowfish_test.cc @@ -19,7 +19,7 @@ #include "../../crypto/internal.h" #include "../../crypto/test/test_util.h" -struct TestCase { +struct BlowfishTestCase { uint8_t key[16]; uint8_t plaintext[16]; uint8_t iv[8]; @@ -28,7 +28,7 @@ struct TestCase { uint8_t cfb_ciphertext[16]; }; -static const TestCase kTests[] = { +static const BlowfishTestCase kTests[] = { // Randomly generated test cases. Checked against vanilla OpenSSL. { {0xbb, 0x56, 0xb1, 0x27, 0x7c, 0x4c, 0xdd, 0x5a, 0x99, 0x90, 0x1e, 0x6f, diff --git a/third_party/boringssl/kit/src/decrepit/cast/cast_test.cc b/third_party/boringssl/kit/src/decrepit/cast/cast_test.cc index 05a04cbb..fd5f2a98 100644 --- a/third_party/boringssl/kit/src/decrepit/cast/cast_test.cc +++ b/third_party/boringssl/kit/src/decrepit/cast/cast_test.cc @@ -19,7 +19,7 @@ #include "../../crypto/internal.h" #include "../../crypto/test/test_util.h" -struct TestCase { +struct CastTestCase { uint8_t key[16]; uint8_t plaintext[16]; uint8_t iv[8]; @@ -27,7 +27,7 @@ struct TestCase { uint8_t cbc_ciphertext[24]; }; -static const TestCase kTests[] = { +static const CastTestCase kTests[] = { // Randomly generated test cases. Checked against vanilla OpenSSL. { {0xbb, 0x56, 0xb1, 0x27, 0x7c, 0x4c, 0xdd, 0x5a, 0x99, 0x90, 0x1e, 0x6f, diff --git a/third_party/boringssl/kit/src/decrepit/evp/evp_do_all.c b/third_party/boringssl/kit/src/decrepit/evp/evp_do_all.c index 38b8f9f7..d540144b 100644 --- a/third_party/boringssl/kit/src/decrepit/evp/evp_do_all.c +++ b/third_party/boringssl/kit/src/decrepit/evp/evp_do_all.c @@ -20,14 +20,20 @@ void EVP_CIPHER_do_all_sorted(void (*callback)(const EVP_CIPHER *cipher, const char *unused, void *arg), void *arg) { callback(EVP_aes_128_cbc(), "AES-128-CBC", NULL, arg); - callback(EVP_aes_128_ctr(), "AES-128-CTR", NULL, arg); - callback(EVP_aes_128_ecb(), "AES-128-ECB", NULL, arg); - callback(EVP_aes_128_ofb(), "AES-128-OFB", NULL, arg); + callback(EVP_aes_192_cbc(), "AES-192-CBC", NULL, arg); callback(EVP_aes_256_cbc(), "AES-256-CBC", NULL, arg); + callback(EVP_aes_128_ctr(), "AES-128-CTR", NULL, arg); + callback(EVP_aes_192_ctr(), "AES-192-CTR", NULL, arg); callback(EVP_aes_256_ctr(), "AES-256-CTR", NULL, arg); + callback(EVP_aes_128_ecb(), "AES-128-ECB", NULL, arg); + callback(EVP_aes_192_ecb(), "AES-192-ECB", NULL, arg); callback(EVP_aes_256_ecb(), "AES-256-ECB", NULL, arg); + callback(EVP_aes_128_ofb(), "AES-128-OFB", NULL, arg); + callback(EVP_aes_192_ofb(), "AES-192-OFB", NULL, arg); callback(EVP_aes_256_ofb(), "AES-256-OFB", NULL, arg); - callback(EVP_aes_256_xts(), "AES-256-XTS", NULL, arg); + callback(EVP_aes_128_gcm(), "AES-128-GCM", NULL, arg); + callback(EVP_aes_192_gcm(), "AES-192-GCM", NULL, arg); + callback(EVP_aes_256_gcm(), "AES-256-GCM", NULL, arg); callback(EVP_des_cbc(), "DES-CBC", NULL, arg); callback(EVP_des_ecb(), "DES-ECB", NULL, arg); callback(EVP_des_ede(), "DES-EDE", NULL, arg); @@ -38,14 +44,20 @@ void EVP_CIPHER_do_all_sorted(void (*callback)(const EVP_CIPHER *cipher, // OpenSSL returns everything twice, the second time in lower case. callback(EVP_aes_128_cbc(), "aes-128-cbc", NULL, arg); - callback(EVP_aes_128_ctr(), "aes-128-ctr", NULL, arg); - callback(EVP_aes_128_ecb(), "aes-128-ecb", NULL, arg); - callback(EVP_aes_128_ofb(), "aes-128-ofb", NULL, arg); + callback(EVP_aes_192_cbc(), "aes-192-cbc", NULL, arg); callback(EVP_aes_256_cbc(), "aes-256-cbc", NULL, arg); + callback(EVP_aes_128_ctr(), "aes-128-ctr", NULL, arg); + callback(EVP_aes_192_ctr(), "aes-192-ctr", NULL, arg); callback(EVP_aes_256_ctr(), "aes-256-ctr", NULL, arg); + callback(EVP_aes_128_ecb(), "aes-128-ecb", NULL, arg); + callback(EVP_aes_192_ecb(), "aes-192-ecb", NULL, arg); callback(EVP_aes_256_ecb(), "aes-256-ecb", NULL, arg); + callback(EVP_aes_128_ofb(), "aes-128-ofb", NULL, arg); + callback(EVP_aes_192_ofb(), "aes-192-ofb", NULL, arg); callback(EVP_aes_256_ofb(), "aes-256-ofb", NULL, arg); - callback(EVP_aes_256_xts(), "aes-256-xts", NULL, arg); + callback(EVP_aes_128_gcm(), "aes-128-gcm", NULL, arg); + callback(EVP_aes_192_gcm(), "aes-192-gcm", NULL, arg); + callback(EVP_aes_256_gcm(), "aes-256-gcm", NULL, arg); callback(EVP_des_cbc(), "des-cbc", NULL, arg); callback(EVP_des_ecb(), "des-ecb", NULL, arg); callback(EVP_des_ede(), "des-ede", NULL, arg); diff --git a/third_party/boringssl/kit/src/decrepit/ripemd/internal.h b/third_party/boringssl/kit/src/decrepit/ripemd/internal.h index fe172caf..089be150 100644 --- a/third_party/boringssl/kit/src/decrepit/ripemd/internal.h +++ b/third_party/boringssl/kit/src/decrepit/ripemd/internal.h @@ -54,8 +54,8 @@ * copied and put under another distribution licence * [including the GNU Public Licence.] */ -#ifndef OPENSSL_HEADER_BN_INTERNAL_H -#define OPENSSL_HEADER_BN_INTERNAL_H +#ifndef OPENSSL_HEADER_RIPEMD_INTERNAL_H +#define OPENSSL_HEADER_RIPEMD_INTERNAL_H #include @@ -72,6 +72,7 @@ static void ripemd160_block_data_order(uint32_t h[5], const uint8_t *data, #define HASH_LONG uint32_t #define HASH_CTX RIPEMD160_CTX #define HASH_CBLOCK RIPEMD160_CBLOCK +#define HASH_DIGEST_LENGTH RIPEMD160_DIGEST_LENGTH #define HASH_UPDATE RIPEMD160_Update #define HASH_TRANSFORM RIPEMD160_Transform #define HASH_FINAL RIPEMD160_Final @@ -490,4 +491,4 @@ static void ripemd160_block_data_order(uint32_t h[5], const uint8_t *data, } // extern C #endif -#endif // OPENSSL_HEADER_BN_INTERNAL_H +#endif // OPENSSL_HEADER_RIPEMD_INTERNAL_H diff --git a/third_party/boringssl/kit/src/decrepit/ripemd/ripemd.c b/third_party/boringssl/kit/src/decrepit/ripemd/ripemd.c index 275d4397..17b3fdfc 100644 --- a/third_party/boringssl/kit/src/decrepit/ripemd/ripemd.c +++ b/third_party/boringssl/kit/src/decrepit/ripemd/ripemd.c @@ -311,7 +311,8 @@ static void ripemd160_block_data_order(uint32_t h[5], const uint8_t *data, #undef X } -uint8_t *RIPEMD160(const uint8_t *data, size_t len, unsigned char *out) { +uint8_t *RIPEMD160(const uint8_t *data, size_t len, + uint8_t out[RIPEMD160_DIGEST_LENGTH]) { RIPEMD160_CTX ctx; if (!RIPEMD160_Init(&ctx)) { diff --git a/third_party/boringssl/kit/src/decrepit/xts/xts.c b/third_party/boringssl/kit/src/decrepit/xts/xts.c index bc2a1b23..a433c3be 100644 --- a/third_party/boringssl/kit/src/decrepit/xts/xts.c +++ b/third_party/boringssl/kit/src/decrepit/xts/xts.c @@ -80,23 +80,13 @@ static size_t CRYPTO_xts128_encrypt(const XTS128_CONTEXT *ctx, if (!enc && (len % 16)) len -= 16; while (len >= 16) { -#if STRICT_ALIGNMENT OPENSSL_memcpy(scratch.c, inp, 16); scratch.u[0] ^= tweak.u[0]; scratch.u[1] ^= tweak.u[1]; -#else - scratch.u[0] = ((uint64_t *)inp)[0] ^ tweak.u[0]; - scratch.u[1] = ((uint64_t *)inp)[1] ^ tweak.u[1]; -#endif (*ctx->block1)(scratch.c, scratch.c, ctx->key1); -#if STRICT_ALIGNMENT scratch.u[0] ^= tweak.u[0]; scratch.u[1] ^= tweak.u[1]; OPENSSL_memcpy(out, scratch.c, 16); -#else - ((uint64_t *)out)[0] = scratch.u[0] ^= tweak.u[0]; - ((uint64_t *)out)[1] = scratch.u[1] ^= tweak.u[1]; -#endif inp += 16; out += 16; len -= 16; @@ -134,14 +124,9 @@ static size_t CRYPTO_xts128_encrypt(const XTS128_CONTEXT *ctx, carry = (unsigned int)(tweak.u[0] >> 63); tweak1.u[0] = (tweak.u[0] << 1) ^ res; tweak1.u[1] = (tweak.u[1] << 1) | carry; -#if STRICT_ALIGNMENT OPENSSL_memcpy(scratch.c, inp, 16); scratch.u[0] ^= tweak1.u[0]; scratch.u[1] ^= tweak1.u[1]; -#else - scratch.u[0] = ((uint64_t *)inp)[0] ^ tweak1.u[0]; - scratch.u[1] = ((uint64_t *)inp)[1] ^ tweak1.u[1]; -#endif (*ctx->block1)(scratch.c, scratch.c, ctx->key1); scratch.u[0] ^= tweak1.u[0]; scratch.u[1] ^= tweak1.u[1]; @@ -154,14 +139,9 @@ static size_t CRYPTO_xts128_encrypt(const XTS128_CONTEXT *ctx, scratch.u[0] ^= tweak.u[0]; scratch.u[1] ^= tweak.u[1]; (*ctx->block1)(scratch.c, scratch.c, ctx->key1); -#if STRICT_ALIGNMENT scratch.u[0] ^= tweak.u[0]; scratch.u[1] ^= tweak.u[1]; OPENSSL_memcpy(out, scratch.c, 16); -#else - ((uint64_t *)out)[0] = scratch.u[0] ^ tweak.u[0]; - ((uint64_t *)out)[1] = scratch.u[1] ^ tweak.u[1]; -#endif } return 1; diff --git a/third_party/boringssl/kit/src/go.mod b/third_party/boringssl/kit/src/go.mod index 09d36fbf..eb5a68a5 100644 --- a/third_party/boringssl/kit/src/go.mod +++ b/third_party/boringssl/kit/src/go.mod @@ -1 +1,3 @@ module boringssl.googlesource.com/boringssl + +go 1.11 diff --git a/third_party/boringssl/kit/src/include/openssl/aes.h b/third_party/boringssl/kit/src/include/openssl/aes.h index 11565854..3606bfc4 100644 --- a/third_party/boringssl/kit/src/include/openssl/aes.h +++ b/third_party/boringssl/kit/src/include/openssl/aes.h @@ -76,18 +76,18 @@ struct aes_key_st { typedef struct aes_key_st AES_KEY; // AES_set_encrypt_key configures |aeskey| to encrypt with the |bits|-bit key, -// |key|. +// |key|. |key| must point to |bits|/8 bytes. It returns zero on success and a +// negative number if |bits| is an invalid AES key size. // -// WARNING: unlike other OpenSSL functions, this returns zero on success and a -// negative number on error. +// WARNING: this function breaks the usual return value convention. OPENSSL_EXPORT int AES_set_encrypt_key(const uint8_t *key, unsigned bits, AES_KEY *aeskey); // AES_set_decrypt_key configures |aeskey| to decrypt with the |bits|-bit key, -// |key|. +// |key|. |key| must point to |bits|/8 bytes. It returns zero on success and a +// negative number if |bits| is an invalid AES key size. // -// WARNING: unlike other OpenSSL functions, this returns zero on success and a -// negative number on error. +// WARNING: this function breaks the usual return value convention. OPENSSL_EXPORT int AES_set_decrypt_key(const uint8_t *key, unsigned bits, AES_KEY *aeskey); diff --git a/third_party/boringssl/kit/src/include/openssl/asn1.h b/third_party/boringssl/kit/src/include/openssl/asn1.h index 8b61eaa3..6ae831b8 100644 --- a/third_party/boringssl/kit/src/include/openssl/asn1.h +++ b/third_party/boringssl/kit/src/include/openssl/asn1.h @@ -666,7 +666,6 @@ OPENSSL_EXPORT int d2i_ASN1_BOOLEAN(int *a,const unsigned char **pp,long lengt DECLARE_ASN1_FUNCTIONS(ASN1_INTEGER) OPENSSL_EXPORT int i2c_ASN1_INTEGER(ASN1_INTEGER *a,unsigned char **pp); OPENSSL_EXPORT ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **a,const unsigned char **pp, long length); -OPENSSL_EXPORT ASN1_INTEGER *d2i_ASN1_UINTEGER(ASN1_INTEGER **a,const unsigned char **pp, long length); OPENSSL_EXPORT ASN1_INTEGER * ASN1_INTEGER_dup(const ASN1_INTEGER *x); OPENSSL_EXPORT int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y); diff --git a/third_party/boringssl/kit/src/include/openssl/base.h b/third_party/boringssl/kit/src/include/openssl/base.h index 7fe232f3..cb1affac 100644 --- a/third_party/boringssl/kit/src/include/openssl/base.h +++ b/third_party/boringssl/kit/src/include/openssl/base.h @@ -291,6 +291,24 @@ extern "C" { #endif #endif // OPENSSL_ASM_INCOMPATIBLE +#if defined(__cplusplus) +// enums can be predeclared, but only in C++ and only if given an explicit type. +// C doesn't support setting an explicit type for enums thus a #define is used +// to do this only for C++. However, the ABI type between C and C++ need to have +// equal sizes, which is confirmed in a unittest. +#define BORINGSSL_ENUM_INT : int +enum ssl_early_data_reason_t BORINGSSL_ENUM_INT; +enum ssl_encryption_level_t BORINGSSL_ENUM_INT; +enum ssl_private_key_result_t BORINGSSL_ENUM_INT; +enum ssl_renegotiate_mode_t BORINGSSL_ENUM_INT; +enum ssl_select_cert_result_t BORINGSSL_ENUM_INT; +enum ssl_select_cert_result_t BORINGSSL_ENUM_INT; +enum ssl_ticket_aead_result_t BORINGSSL_ENUM_INT; +enum ssl_verify_result_t BORINGSSL_ENUM_INT; +#else +#define BORINGSSL_ENUM_INT +#endif + // CRYPTO_THREADID is a dummy value. typedef int CRYPTO_THREADID; diff --git a/third_party/boringssl/kit/src/include/openssl/bn.h b/third_party/boringssl/kit/src/include/openssl/bn.h index c198f4df..b6b7e9ab 100644 --- a/third_party/boringssl/kit/src/include/openssl/bn.h +++ b/third_party/boringssl/kit/src/include/openssl/bn.h @@ -932,6 +932,12 @@ OPENSSL_EXPORT BN_MONT_CTX *BN_MONT_CTX_new(void); OPENSSL_EXPORT int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx); +// BN_bn2binpad behaves like |BN_bn2bin_padded|, but it returns |len| on success +// and -1 on error. +// +// Use |BN_bn2bin_padded| instead. It is |size_t|-clean. +OPENSSL_EXPORT int BN_bn2binpad(const BIGNUM *in, uint8_t *out, int len); + // Private functions diff --git a/third_party/boringssl/kit/src/include/openssl/bytestring.h b/third_party/boringssl/kit/src/include/openssl/bytestring.h index 701466ea..029c2be2 100644 --- a/third_party/boringssl/kit/src/include/openssl/bytestring.h +++ b/third_party/boringssl/kit/src/include/openssl/bytestring.h @@ -110,6 +110,10 @@ OPENSSL_EXPORT int CBS_get_u24(CBS *cbs, uint32_t *out); // and advances |cbs|. It returns one on success and zero on error. OPENSSL_EXPORT int CBS_get_u32(CBS *cbs, uint32_t *out); +// CBS_get_u64 sets |*out| to the next, big-endian uint64_t value from |cbs| +// and advances |cbs|. It returns one on success and zero on error. +OPENSSL_EXPORT int CBS_get_u64(CBS *cbs, uint64_t *out); + // CBS_get_last_u8 sets |*out| to the last uint8_t from |cbs| and shortens // |cbs|. It returns one on success and zero on error. OPENSSL_EXPORT int CBS_get_last_u8(CBS *cbs, uint8_t *out); @@ -341,9 +345,9 @@ struct cbb_st { // length-prefix, or zero if no length-prefix is pending. uint8_t pending_len_len; char pending_is_asn1; - // is_top_level is true iff this is a top-level |CBB| (as opposed to a child + // is_child is true iff this is a child |CBB| (as opposed to a top-level // |CBB|). Top-level objects are valid arguments for |CBB_finish|. - char is_top_level; + char is_child; }; // CBB_zero sets an uninitialised |cbb| to the zero state. It must be @@ -459,6 +463,10 @@ OPENSSL_EXPORT int CBB_add_u24(CBB *cbb, uint32_t value); // returns one on success and zero otherwise. OPENSSL_EXPORT int CBB_add_u32(CBB *cbb, uint32_t value); +// CBB_add_u64 appends a 64-bit, big-endian number from |value| to |cbb|. It +// returns one on success and zero otherwise. +OPENSSL_EXPORT int CBB_add_u64(CBB *cbb, uint64_t value); + // CBB_discard_child discards the current unflushed child of |cbb|. Neither the // child's contents nor the length prefix will be included in the output. OPENSSL_EXPORT void CBB_discard_child(CBB *cbb); diff --git a/third_party/boringssl/kit/src/include/openssl/cpu.h b/third_party/boringssl/kit/src/include/openssl/cpu.h index edac98ea..eb36a57e 100644 --- a/third_party/boringssl/kit/src/include/openssl/cpu.h +++ b/third_party/boringssl/kit/src/include/openssl/cpu.h @@ -93,7 +93,7 @@ extern "C" { // bits in XCR0, so it is not necessary to check those. extern uint32_t OPENSSL_ia32cap_P[4]; -#if defined(BORINGSSL_FIPS) +#if defined(BORINGSSL_FIPS) && !defined(BORINGSSL_SHARED_LIBRARY) const uint32_t *OPENSSL_ia32cap_get(void); #else OPENSSL_INLINE const uint32_t *OPENSSL_ia32cap_get(void) { @@ -190,6 +190,21 @@ extern unsigned long OPENSSL_ppc64le_hwcap2; #endif // OPENSSL_PPC64LE +#if !defined(NDEBUG) && !defined(BORINGSSL_FIPS) +// Runtime CPU dispatch testing support + +// BORINGSSL_function_hit is an array of flags. The following functions will +// set these flags in non-FIPS builds if NDEBUG is not defined. +// 0: aes_hw_ctr32_encrypt_blocks +// 1: aes_hw_encrypt +// 2: aesni_gcm_encrypt +// 3: aes_hw_set_encrypt_key +// 4: vpaes_encrypt +// 5: vpaes_set_encrypt_key +// 6: bsaes_ctr32_encrypt_blocks +extern uint8_t BORINGSSL_function_hit[7]; +#endif // !NDEBUG && !FIPS + #if defined(__cplusplus) } // extern C diff --git a/third_party/boringssl/kit/src/include/openssl/digest.h b/third_party/boringssl/kit/src/include/openssl/digest.h index 1a1ca297..c7c67976 100644 --- a/third_party/boringssl/kit/src/include/openssl/digest.h +++ b/third_party/boringssl/kit/src/include/openssl/digest.h @@ -269,6 +269,11 @@ OPENSSL_EXPORT EVP_MD_CTX *EVP_MD_CTX_create(void); // EVP_MD_CTX_destroy calls |EVP_MD_CTX_free|. OPENSSL_EXPORT void EVP_MD_CTX_destroy(EVP_MD_CTX *ctx); +// EVP_DigestFinalXOF returns zero and adds an error to the error queue. +// BoringSSL does not support any XOF digests. +OPENSSL_EXPORT int EVP_DigestFinalXOF(EVP_MD_CTX *ctx, uint8_t *out, + size_t len); + struct evp_md_pctx_ops; diff --git a/third_party/boringssl/kit/src/include/openssl/dsa.h b/third_party/boringssl/kit/src/include/openssl/dsa.h index bed93c5d..8e3b9b3c 100644 --- a/third_party/boringssl/kit/src/include/openssl/dsa.h +++ b/third_party/boringssl/kit/src/include/openssl/dsa.h @@ -436,5 +436,6 @@ BSSL_NAMESPACE_END #define DSA_R_BAD_VERSION 104 #define DSA_R_DECODE_ERROR 105 #define DSA_R_ENCODE_ERROR 106 +#define DSA_R_INVALID_PARAMETERS 107 #endif // OPENSSL_HEADER_DSA_H diff --git a/third_party/boringssl/kit/src/include/openssl/ec.h b/third_party/boringssl/kit/src/include/openssl/ec.h index c65a1a75..fcecb622 100644 --- a/third_party/boringssl/kit/src/include/openssl/ec.h +++ b/third_party/boringssl/kit/src/include/openssl/ec.h @@ -162,6 +162,11 @@ OPENSSL_EXPORT unsigned EC_GROUP_get_degree(const EC_GROUP *group); // for |NID_X9_62_prime256v1|. OPENSSL_EXPORT const char *EC_curve_nid2nist(int nid); +// EC_curve_nist2nid returns the NID of the elliptic curve specified by the NIST +// name |name|, or |NID_undef| if |name| is not a recognized name. For example, +// it returns |NID_X9_62_prime256v1| for "P-256". +OPENSSL_EXPORT int EC_curve_nist2nid(const char *name); + // Points on elliptic curves. @@ -320,6 +325,7 @@ OPENSSL_EXPORT int EC_GROUP_get_order(const EC_GROUP *group, BIGNUM *order, OPENSSL_EXPORT void EC_GROUP_set_asn1_flag(EC_GROUP *group, int flag); #define OPENSSL_EC_NAMED_CURVE 0 +#define OPENSSL_EC_EXPLICIT_CURVE 1 typedef struct ec_method_st EC_METHOD; diff --git a/third_party/boringssl/kit/src/include/openssl/engine.h b/third_party/boringssl/kit/src/include/openssl/engine.h index 9d459527..ce60de46 100644 --- a/third_party/boringssl/kit/src/include/openssl/engine.h +++ b/third_party/boringssl/kit/src/include/openssl/engine.h @@ -40,8 +40,8 @@ extern "C" { OPENSSL_EXPORT ENGINE *ENGINE_new(void); // ENGINE_free decrements the reference counts for all methods linked from -// |engine| and frees |engine| itself. -OPENSSL_EXPORT void ENGINE_free(ENGINE *engine); +// |engine| and frees |engine| itself. It returns one. +OPENSSL_EXPORT int ENGINE_free(ENGINE *engine); // Method accessors. diff --git a/third_party/boringssl/kit/src/include/openssl/evp.h b/third_party/boringssl/kit/src/include/openssl/evp.h index 1d7192da..39c418b6 100644 --- a/third_party/boringssl/kit/src/include/openssl/evp.h +++ b/third_party/boringssl/kit/src/include/openssl/evp.h @@ -170,16 +170,6 @@ OPENSSL_EXPORT int EVP_PKEY_assign_EC_KEY(EVP_PKEY *pkey, EC_KEY *key); OPENSSL_EXPORT EC_KEY *EVP_PKEY_get0_EC_KEY(const EVP_PKEY *pkey); OPENSSL_EXPORT EC_KEY *EVP_PKEY_get1_EC_KEY(const EVP_PKEY *pkey); -// EVP_PKEY_new_ed25519_public returns a newly allocated |EVP_PKEY| wrapping an -// Ed25519 public key, or NULL on allocation error. -OPENSSL_EXPORT EVP_PKEY *EVP_PKEY_new_ed25519_public( - const uint8_t public_key[32]); - -// EVP_PKEY_new_ed25519_private returns a newly allocated |EVP_PKEY| wrapping an -// Ed25519 private key, or NULL on allocation error. -OPENSSL_EXPORT EVP_PKEY *EVP_PKEY_new_ed25519_private( - const uint8_t private_key[64]); - #define EVP_PKEY_NONE NID_undef #define EVP_PKEY_RSA NID_rsaEncryption #define EVP_PKEY_RSA_PSS NID_rsassaPss @@ -241,6 +231,48 @@ OPENSSL_EXPORT EVP_PKEY *EVP_parse_private_key(CBS *cbs); OPENSSL_EXPORT int EVP_marshal_private_key(CBB *cbb, const EVP_PKEY *key); +// Raw keys +// +// Some keys types support a "raw" serialization. Currently the only supported +// raw format is Ed25519, where the public key and private key formats are those +// specified in RFC 8032. Note the RFC 8032 private key format is the 32-byte +// prefix of |ED25519_sign|'s 64-byte private key. + +// EVP_PKEY_new_raw_private_key returns a newly allocated |EVP_PKEY| wrapping a +// private key of the specified type. It returns one on success and zero on +// error. +OPENSSL_EXPORT EVP_PKEY *EVP_PKEY_new_raw_private_key(int type, ENGINE *unused, + const uint8_t *in, + size_t len); + +// EVP_PKEY_new_raw_public_key returns a newly allocated |EVP_PKEY| wrapping a +// public key of the specified type. It returns one on success and zero on +// error. +OPENSSL_EXPORT EVP_PKEY *EVP_PKEY_new_raw_public_key(int type, ENGINE *unused, + const uint8_t *in, + size_t len); + +// EVP_PKEY_get_raw_private_key outputs the private key for |pkey| in raw form. +// If |out| is NULL, it sets |*out_len| to the size of the raw private key. +// Otherwise, it writes at most |*out_len| bytes to |out| and sets |*out_len| to +// the number of bytes written. +// +// It returns one on success and zero if |pkey| has no private key, the key +// type does not support a raw format, or the buffer is too small. +OPENSSL_EXPORT int EVP_PKEY_get_raw_private_key(const EVP_PKEY *pkey, + uint8_t *out, size_t *out_len); + +// EVP_PKEY_get_raw_public_key outputs the public key for |pkey| in raw form. +// If |out| is NULL, it sets |*out_len| to the size of the raw public key. +// Otherwise, it writes at most |*out_len| bytes to |out| and sets |*out_len| to +// the number of bytes written. +// +// It returns one on success and zero if |pkey| has no public key, the key +// type does not support a raw format, or the buffer is too small. +OPENSSL_EXPORT int EVP_PKEY_get_raw_public_key(const EVP_PKEY *pkey, + uint8_t *out, size_t *out_len); + + // Signing // EVP_DigestSignInit sets up |ctx| for a signing operation with |type| and @@ -646,9 +678,23 @@ OPENSSL_EXPORT int EVP_PKEY_derive(EVP_PKEY_CTX *ctx, uint8_t *key, OPENSSL_EXPORT int EVP_PKEY_keygen_init(EVP_PKEY_CTX *ctx); // EVP_PKEY_keygen performs a key generation operation using the values from -// |ctx| and sets |*ppkey| to a fresh |EVP_PKEY| containing the resulting key. +// |ctx|. If |*out_pkey| is non-NULL, it overwrites |*out_pkey| with the +// resulting key. Otherwise, it sets |*out_pkey| to a newly-allocated |EVP_PKEY| +// containing the result. It returns one on success or zero on error. +OPENSSL_EXPORT int EVP_PKEY_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY **out_pkey); + +// EVP_PKEY_paramgen_init initialises an |EVP_PKEY_CTX| for a parameter +// generation operation. It should be called before |EVP_PKEY_paramgen|. +// // It returns one on success or zero on error. -OPENSSL_EXPORT int EVP_PKEY_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey); +OPENSSL_EXPORT int EVP_PKEY_paramgen_init(EVP_PKEY_CTX *ctx); + +// EVP_PKEY_paramgen performs a parameter generation using the values from +// |ctx|. If |*out_pkey| is non-NULL, it overwrites |*out_pkey| with the +// resulting parameters, but no key. Otherwise, it sets |*out_pkey| to a +// newly-allocated |EVP_PKEY| containing the result. It returns one on success +// or zero on error. +OPENSSL_EXPORT int EVP_PKEY_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY **out_pkey); // Generic control functions. @@ -746,6 +792,15 @@ OPENSSL_EXPORT int EVP_PKEY_CTX_get0_rsa_oaep_label(EVP_PKEY_CTX *ctx, const uint8_t **out_label); +// EC specific control functions. + +// EVP_PKEY_CTX_set_ec_paramgen_curve_nid sets the curve used for +// |EVP_PKEY_keygen| or |EVP_PKEY_paramgen| operations to |nid|. It returns one +// on success and zero on error. +OPENSSL_EXPORT int EVP_PKEY_CTX_set_ec_paramgen_curve_nid(EVP_PKEY_CTX *ctx, + int nid); + + // Deprecated functions. // EVP_PKEY_DH is defined for compatibility, but it is impossible to create an @@ -826,12 +881,31 @@ OPENSSL_EXPORT EVP_PKEY *d2i_PrivateKey(int type, EVP_PKEY **out, OPENSSL_EXPORT EVP_PKEY *d2i_AutoPrivateKey(EVP_PKEY **out, const uint8_t **inp, long len); +// d2i_PublicKey parse a public key from |len| bytes at |*inp| in a type- +// specific format specified by |type|. If |out| is not NULL then, on exit, a +// pointer to the result is in |*out|. Note that, even if |*out| is already non- +// NULL on entry, it will not be written to. Rather, a fresh |EVP_PKEY| is +// allocated and the previous one is freed. On successful exit, |*inp| is +// advanced past the decoded key. It returns the result or NULL on error. +// +// RSA keys are parsed as a DER-encoded RSAPublicKey (RFC 3447) structure. +// Parsing EC keys is not supported by this function. +// +// Use |RSA_parse_public_key| instead. +OPENSSL_EXPORT EVP_PKEY *d2i_PublicKey(int type, EVP_PKEY **out, + const uint8_t **inp, long len); + // EVP_PKEY_get0_DH returns NULL. OPENSSL_EXPORT DH *EVP_PKEY_get0_DH(const EVP_PKEY *pkey); // EVP_PKEY_get1_DH returns NULL. OPENSSL_EXPORT DH *EVP_PKEY_get1_DH(const EVP_PKEY *pkey); +// EVP_PKEY_CTX_set_ec_param_enc returns one if |encoding| is +// |OPENSSL_EC_NAMED_CURVE| or zero with an error otherwise. +OPENSSL_EXPORT int EVP_PKEY_CTX_set_ec_param_enc(EVP_PKEY_CTX *ctx, + int encoding); + // Preprocessor compatibility section (hidden). // diff --git a/third_party/boringssl/kit/src/include/openssl/hrss.h b/third_party/boringssl/kit/src/include/openssl/hrss.h index d4e16dcd..5390696f 100644 --- a/third_party/boringssl/kit/src/include/openssl/hrss.h +++ b/third_party/boringssl/kit/src/include/openssl/hrss.h @@ -38,9 +38,8 @@ struct HRSS_public_key { // HRSS_SAMPLE_BYTES is the number of bytes of entropy needed to generate a // short vector. There are 701 coefficients, but the final one is always set to -// zero when sampling. Otherwise, one byte of input is enough to generate two -// coefficients. -#define HRSS_SAMPLE_BYTES ((701 - 1) / 2) +// zero when sampling. Otherwise, we need one byte of input per coefficient. +#define HRSS_SAMPLE_BYTES (701 - 1) // HRSS_GENERATE_KEY_BYTES is the number of bytes of entropy needed to generate // an HRSS key pair. #define HRSS_GENERATE_KEY_BYTES (HRSS_SAMPLE_BYTES + HRSS_SAMPLE_BYTES + 32) diff --git a/third_party/boringssl/kit/src/include/openssl/lhash.h b/third_party/boringssl/kit/src/include/openssl/lhash.h index c82bb8e6..29e09c83 100644 --- a/third_party/boringssl/kit/src/include/openssl/lhash.h +++ b/third_party/boringssl/kit/src/include/openssl/lhash.h @@ -77,7 +77,7 @@ extern "C" { // int bar; // }; // -// DEFINE_LHASH_OF(struct foo); +// DEFINE_LHASH_OF(struct foo) // // Although note that the hash table will contain /pointers/ to |foo|. // diff --git a/third_party/boringssl/kit/src/include/openssl/md4.h b/third_party/boringssl/kit/src/include/openssl/md4.h index 52b88ca3..b213bc62 100644 --- a/third_party/boringssl/kit/src/include/openssl/md4.h +++ b/third_party/boringssl/kit/src/include/openssl/md4.h @@ -79,17 +79,19 @@ OPENSSL_EXPORT int MD4_Init(MD4_CTX *md4); OPENSSL_EXPORT int MD4_Update(MD4_CTX *md4, const void *data, size_t len); // MD4_Final adds the final padding to |md4| and writes the resulting digest to -// |md|, which must have at least |MD4_DIGEST_LENGTH| bytes of space. It +// |out|, which must have at least |MD4_DIGEST_LENGTH| bytes of space. It // returns one. -OPENSSL_EXPORT int MD4_Final(uint8_t *md, MD4_CTX *md4); +OPENSSL_EXPORT int MD4_Final(uint8_t out[MD4_DIGEST_LENGTH], MD4_CTX *md4); // MD4 writes the digest of |len| bytes from |data| to |out| and returns |out|. // There must be at least |MD4_DIGEST_LENGTH| bytes of space in |out|. -OPENSSL_EXPORT uint8_t *MD4(const uint8_t *data, size_t len, uint8_t *out); +OPENSSL_EXPORT uint8_t *MD4(const uint8_t *data, size_t len, + uint8_t out[MD4_DIGEST_LENGTH]); // MD4_Transform is a low-level function that performs a single, MD4 block // transformation using the state from |md4| and 64 bytes from |block|. -OPENSSL_EXPORT void MD4_Transform(MD4_CTX *md4, const uint8_t *block); +OPENSSL_EXPORT void MD4_Transform(MD4_CTX *md4, + const uint8_t block[MD4_CBLOCK]); struct md4_state_st { uint32_t h[4]; diff --git a/third_party/boringssl/kit/src/include/openssl/md5.h b/third_party/boringssl/kit/src/include/openssl/md5.h index de6027f5..54865129 100644 --- a/third_party/boringssl/kit/src/include/openssl/md5.h +++ b/third_party/boringssl/kit/src/include/openssl/md5.h @@ -80,17 +80,19 @@ OPENSSL_EXPORT int MD5_Init(MD5_CTX *md5); OPENSSL_EXPORT int MD5_Update(MD5_CTX *md5, const void *data, size_t len); // MD5_Final adds the final padding to |md5| and writes the resulting digest to -// |md|, which must have at least |MD5_DIGEST_LENGTH| bytes of space. It +// |out|, which must have at least |MD5_DIGEST_LENGTH| bytes of space. It // returns one. -OPENSSL_EXPORT int MD5_Final(uint8_t *md, MD5_CTX *md5); +OPENSSL_EXPORT int MD5_Final(uint8_t out[MD5_DIGEST_LENGTH], MD5_CTX *md5); // MD5 writes the digest of |len| bytes from |data| to |out| and returns |out|. // There must be at least |MD5_DIGEST_LENGTH| bytes of space in |out|. -OPENSSL_EXPORT uint8_t *MD5(const uint8_t *data, size_t len, uint8_t *out); +OPENSSL_EXPORT uint8_t *MD5(const uint8_t *data, size_t len, + uint8_t out[MD5_DIGEST_LENGTH]); // MD5_Transform is a low-level function that performs a single, MD5 block // transformation using the state from |md5| and 64 bytes from |block|. -OPENSSL_EXPORT void MD5_Transform(MD5_CTX *md5, const uint8_t *block); +OPENSSL_EXPORT void MD5_Transform(MD5_CTX *md5, + const uint8_t block[MD5_CBLOCK]); struct md5_state_st { uint32_t h[4]; diff --git a/third_party/boringssl/kit/src/include/openssl/mem.h b/third_party/boringssl/kit/src/include/openssl/mem.h index 9f9c00dd..2e25f52a 100644 --- a/third_party/boringssl/kit/src/include/openssl/mem.h +++ b/third_party/boringssl/kit/src/include/openssl/mem.h @@ -136,6 +136,10 @@ OPENSSL_EXPORT int BIO_vsnprintf(char *buf, size_t n, const char *format, #define CRYPTO_realloc OPENSSL_realloc #define CRYPTO_free OPENSSL_free +// OPENSSL_clear_free calls |OPENSSL_free|. BoringSSL automatically clears all +// allocations on free, but we define |OPENSSL_clear_free| for compatibility. +OPENSSL_EXPORT void OPENSSL_clear_free(void *ptr, size_t len); + #if defined(__cplusplus) } // extern C diff --git a/third_party/boringssl/kit/src/include/openssl/nid.h b/third_party/boringssl/kit/src/include/openssl/nid.h index 270d443a..cea975a3 100644 --- a/third_party/boringssl/kit/src/include/openssl/nid.h +++ b/third_party/boringssl/kit/src/include/openssl/nid.h @@ -4237,6 +4237,9 @@ extern "C" { #define SN_CECPQ2 "CECPQ2" #define NID_CECPQ2 959 +#define SN_CECPQ2b "CECPQ2b" +#define NID_CECPQ2b 960 + #if defined(__cplusplus) } /* extern C */ diff --git a/third_party/boringssl/kit/src/include/openssl/pkcs8.h b/third_party/boringssl/kit/src/include/openssl/pkcs8.h index ee48f194..385b9950 100644 --- a/third_party/boringssl/kit/src/include/openssl/pkcs8.h +++ b/third_party/boringssl/kit/src/include/openssl/pkcs8.h @@ -168,12 +168,18 @@ OPENSSL_EXPORT int i2d_PKCS12_fp(FILE *fp, const PKCS12 *p12); // PKCS12_parse calls |PKCS12_get_key_and_certs| on the ASN.1 data stored in // |p12|. The |out_pkey| and |out_cert| arguments must not be NULL and, on -// successful exit, the private key and first certificate will be stored in +// successful exit, the private key and matching certificate will be stored in // them. The |out_ca_certs| argument may be NULL but, if not, then any extra // certificates will be appended to |*out_ca_certs|. If |*out_ca_certs| is NULL // then it will be set to a freshly allocated stack containing the extra certs. // +// Note if |p12| does not contain a private key, both |*out_pkey| and +// |*out_cert| will be set to NULL and all certificates will be returned via +// |*out_ca_certs|. +// // It returns one on success and zero on error. +// +// Use |PKCS12_get_key_and_certs| instead. OPENSSL_EXPORT int PKCS12_parse(const PKCS12 *p12, const char *password, EVP_PKEY **out_pkey, X509 **out_cert, STACK_OF(X509) **out_ca_certs); diff --git a/third_party/boringssl/kit/src/include/openssl/ripemd.h b/third_party/boringssl/kit/src/include/openssl/ripemd.h index fb0b50c1..d859b1ff 100644 --- a/third_party/boringssl/kit/src/include/openssl/ripemd.h +++ b/third_party/boringssl/kit/src/include/openssl/ripemd.h @@ -83,21 +83,22 @@ OPENSSL_EXPORT int RIPEMD160_Update(RIPEMD160_CTX *ctx, const void *data, size_t len); // RIPEMD160_Final adds the final padding to |ctx| and writes the resulting -// digest to |md|, which must have at least |RIPEMD160_DIGEST_LENGTH| bytes of +// digest to |out|, which must have at least |RIPEMD160_DIGEST_LENGTH| bytes of // space. It returns one. -OPENSSL_EXPORT int RIPEMD160_Final(uint8_t *md, RIPEMD160_CTX *ctx); +OPENSSL_EXPORT int RIPEMD160_Final(uint8_t out[RIPEMD160_DIGEST_LENGTH], + RIPEMD160_CTX *ctx); // RIPEMD160 writes the digest of |len| bytes from |data| to |out| and returns // |out|. There must be at least |RIPEMD160_DIGEST_LENGTH| bytes of space in // |out|. OPENSSL_EXPORT uint8_t *RIPEMD160(const uint8_t *data, size_t len, - uint8_t *out); + uint8_t out[RIPEMD160_DIGEST_LENGTH]); // RIPEMD160_Transform is a low-level function that performs a single, // RIPEMD160 block transformation using the state from |ctx| and 64 bytes from // |block|. OPENSSL_EXPORT void RIPEMD160_Transform(RIPEMD160_CTX *ctx, - const uint8_t *block); + const uint8_t block[RIPEMD160_CBLOCK]); #if defined(__cplusplus) diff --git a/third_party/boringssl/kit/src/include/openssl/sha.h b/third_party/boringssl/kit/src/include/openssl/sha.h index 2c0dcb73..b163e6a3 100644 --- a/third_party/boringssl/kit/src/include/openssl/sha.h +++ b/third_party/boringssl/kit/src/include/openssl/sha.h @@ -79,20 +79,22 @@ OPENSSL_EXPORT int SHA1_Init(SHA_CTX *sha); // SHA1_Update adds |len| bytes from |data| to |sha| and returns one. OPENSSL_EXPORT int SHA1_Update(SHA_CTX *sha, const void *data, size_t len); -// SHA1_Final adds the final padding to |sha| and writes the resulting digest -// to |md|, which must have at least |SHA_DIGEST_LENGTH| bytes of space. It +// SHA1_Final adds the final padding to |sha| and writes the resulting digest to +// |out|, which must have at least |SHA_DIGEST_LENGTH| bytes of space. It // returns one. -OPENSSL_EXPORT int SHA1_Final(uint8_t *md, SHA_CTX *sha); +OPENSSL_EXPORT int SHA1_Final(uint8_t out[SHA_DIGEST_LENGTH], SHA_CTX *sha); // SHA1 writes the digest of |len| bytes from |data| to |out| and returns // |out|. There must be at least |SHA_DIGEST_LENGTH| bytes of space in // |out|. -OPENSSL_EXPORT uint8_t *SHA1(const uint8_t *data, size_t len, uint8_t *out); +OPENSSL_EXPORT uint8_t *SHA1(const uint8_t *data, size_t len, + uint8_t out[SHA_DIGEST_LENGTH]); // SHA1_Transform is a low-level function that performs a single, SHA-1 block // transformation using the state from |sha| and |SHA_CBLOCK| bytes from // |block|. -OPENSSL_EXPORT void SHA1_Transform(SHA_CTX *sha, const uint8_t *block); +OPENSSL_EXPORT void SHA1_Transform(SHA_CTX *sha, + const uint8_t block[SHA_CBLOCK]); struct sha_state_st { #if defined(OPENSSL_WINDOWS) @@ -132,14 +134,16 @@ OPENSSL_EXPORT int SHA224_Init(SHA256_CTX *sha); OPENSSL_EXPORT int SHA224_Update(SHA256_CTX *sha, const void *data, size_t len); // SHA224_Final adds the final padding to |sha| and writes the resulting digest -// to |md|, which must have at least |SHA224_DIGEST_LENGTH| bytes of space. It +// to |out|, which must have at least |SHA224_DIGEST_LENGTH| bytes of space. It // returns one on success and zero on programmer error. -OPENSSL_EXPORT int SHA224_Final(uint8_t *md, SHA256_CTX *sha); +OPENSSL_EXPORT int SHA224_Final(uint8_t out[SHA224_DIGEST_LENGTH], + SHA256_CTX *sha); // SHA224 writes the digest of |len| bytes from |data| to |out| and returns // |out|. There must be at least |SHA224_DIGEST_LENGTH| bytes of space in // |out|. -OPENSSL_EXPORT uint8_t *SHA224(const uint8_t *data, size_t len, uint8_t *out); +OPENSSL_EXPORT uint8_t *SHA224(const uint8_t *data, size_t len, + uint8_t out[SHA224_DIGEST_LENGTH]); // SHA-256. @@ -157,19 +161,22 @@ OPENSSL_EXPORT int SHA256_Init(SHA256_CTX *sha); OPENSSL_EXPORT int SHA256_Update(SHA256_CTX *sha, const void *data, size_t len); // SHA256_Final adds the final padding to |sha| and writes the resulting digest -// to |md|, which must have at least |SHA256_DIGEST_LENGTH| bytes of space. It +// to |out|, which must have at least |SHA256_DIGEST_LENGTH| bytes of space. It // returns one on success and zero on programmer error. -OPENSSL_EXPORT int SHA256_Final(uint8_t *md, SHA256_CTX *sha); +OPENSSL_EXPORT int SHA256_Final(uint8_t out[SHA256_DIGEST_LENGTH], + SHA256_CTX *sha); // SHA256 writes the digest of |len| bytes from |data| to |out| and returns // |out|. There must be at least |SHA256_DIGEST_LENGTH| bytes of space in // |out|. -OPENSSL_EXPORT uint8_t *SHA256(const uint8_t *data, size_t len, uint8_t *out); +OPENSSL_EXPORT uint8_t *SHA256(const uint8_t *data, size_t len, + uint8_t out[SHA256_DIGEST_LENGTH]); // SHA256_Transform is a low-level function that performs a single, SHA-256 // block transformation using the state from |sha| and |SHA256_CBLOCK| bytes // from |block|. -OPENSSL_EXPORT void SHA256_Transform(SHA256_CTX *sha, const uint8_t *block); +OPENSSL_EXPORT void SHA256_Transform(SHA256_CTX *sha, + const uint8_t block[SHA256_CBLOCK]); // SHA256_TransformBlocks is a low-level function that takes |num_blocks| * // |SHA256_CBLOCK| bytes of data and performs SHA-256 transforms on it to update @@ -202,14 +209,16 @@ OPENSSL_EXPORT int SHA384_Init(SHA512_CTX *sha); OPENSSL_EXPORT int SHA384_Update(SHA512_CTX *sha, const void *data, size_t len); // SHA384_Final adds the final padding to |sha| and writes the resulting digest -// to |md|, which must have at least |SHA384_DIGEST_LENGTH| bytes of space. It +// to |out|, which must have at least |SHA384_DIGEST_LENGTH| bytes of space. It // returns one on success and zero on programmer error. -OPENSSL_EXPORT int SHA384_Final(uint8_t *md, SHA512_CTX *sha); +OPENSSL_EXPORT int SHA384_Final(uint8_t out[SHA384_DIGEST_LENGTH], + SHA512_CTX *sha); // SHA384 writes the digest of |len| bytes from |data| to |out| and returns // |out|. There must be at least |SHA384_DIGEST_LENGTH| bytes of space in // |out|. -OPENSSL_EXPORT uint8_t *SHA384(const uint8_t *data, size_t len, uint8_t *out); +OPENSSL_EXPORT uint8_t *SHA384(const uint8_t *data, size_t len, + uint8_t out[SHA384_DIGEST_LENGTH]); // SHA-512. @@ -227,27 +236,27 @@ OPENSSL_EXPORT int SHA512_Init(SHA512_CTX *sha); OPENSSL_EXPORT int SHA512_Update(SHA512_CTX *sha, const void *data, size_t len); // SHA512_Final adds the final padding to |sha| and writes the resulting digest -// to |md|, which must have at least |SHA512_DIGEST_LENGTH| bytes of space. It +// to |out|, which must have at least |SHA512_DIGEST_LENGTH| bytes of space. It // returns one on success and zero on programmer error. -OPENSSL_EXPORT int SHA512_Final(uint8_t *md, SHA512_CTX *sha); +OPENSSL_EXPORT int SHA512_Final(uint8_t out[SHA512_DIGEST_LENGTH], + SHA512_CTX *sha); // SHA512 writes the digest of |len| bytes from |data| to |out| and returns // |out|. There must be at least |SHA512_DIGEST_LENGTH| bytes of space in // |out|. -OPENSSL_EXPORT uint8_t *SHA512(const uint8_t *data, size_t len, uint8_t *out); +OPENSSL_EXPORT uint8_t *SHA512(const uint8_t *data, size_t len, + uint8_t out[SHA512_DIGEST_LENGTH]); // SHA512_Transform is a low-level function that performs a single, SHA-512 // block transformation using the state from |sha| and |SHA512_CBLOCK| bytes // from |block|. -OPENSSL_EXPORT void SHA512_Transform(SHA512_CTX *sha, const uint8_t *block); +OPENSSL_EXPORT void SHA512_Transform(SHA512_CTX *sha, + const uint8_t block[SHA512_CBLOCK]); struct sha512_state_st { uint64_t h[8]; uint64_t Nl, Nh; - union { - uint64_t d[16]; - uint8_t p[128]; - } u; + uint8_t p[128]; unsigned num, md_len; }; diff --git a/third_party/boringssl/kit/src/include/openssl/span.h b/third_party/boringssl/kit/src/include/openssl/span.h index 298a7222..1d732ebb 100644 --- a/third_party/boringssl/kit/src/include/openssl/span.h +++ b/third_party/boringssl/kit/src/include/openssl/span.h @@ -131,8 +131,8 @@ class Span : private internal::SpanBase { T *begin() const { return data_; } const T *cbegin() const { return data_; } - T *end() const { return data_ + size_; }; - const T *cend() const { return end(); }; + T *end() const { return data_ + size_; } + const T *cend() const { return end(); } T &front() const { if (size_ == 0) { diff --git a/third_party/boringssl/kit/src/include/openssl/ssl.h b/third_party/boringssl/kit/src/include/openssl/ssl.h index a011e0f6..4586bdb3 100644 --- a/third_party/boringssl/kit/src/include/openssl/ssl.h +++ b/third_party/boringssl/kit/src/include/openssl/ssl.h @@ -631,6 +631,12 @@ OPENSSL_EXPORT int SSL_CTX_set_min_proto_version(SSL_CTX *ctx, OPENSSL_EXPORT int SSL_CTX_set_max_proto_version(SSL_CTX *ctx, uint16_t version); +// SSL_CTX_get_min_proto_version returns the minimum protocol version for |ctx| +OPENSSL_EXPORT uint16_t SSL_CTX_get_min_proto_version(SSL_CTX *ctx); + +// SSL_CTX_get_max_proto_version returns the maximum protocol version for |ctx| +OPENSSL_EXPORT uint16_t SSL_CTX_get_max_proto_version(SSL_CTX *ctx); + // SSL_set_min_proto_version sets the minimum protocol version for |ssl| to // |version|. If |version| is zero, the default minimum version is used. It // returns one on success and zero if |version| is invalid. @@ -881,8 +887,9 @@ OPENSSL_EXPORT int SSL_clear_chain_certs(SSL *ssl); // |SSL_get_client_CA_list| for information on the server's certificate // request. // -// On the server, the callback will be called on non-resumption handshakes, -// after extensions have been processed. +// On the server, the callback will be called after extensions have been +// processed, but before the resumption decision has been made. This differs +// from OpenSSL which handles resumption before selecting the certificate. OPENSSL_EXPORT void SSL_CTX_set_cert_cb(SSL_CTX *ctx, int (*cb)(SSL *ssl, void *arg), void *arg); @@ -895,6 +902,10 @@ OPENSSL_EXPORT void SSL_CTX_set_cert_cb(SSL_CTX *ctx, // On the client, the callback may call |SSL_get0_certificate_types| and // |SSL_get_client_CA_list| for information on the server's certificate // request. +// +// On the server, the callback will be called after extensions have been +// processed, but before the resumption decision has been made. This differs +// from OpenSSL which handles resumption before selecting the certificate. OPENSSL_EXPORT void SSL_set_cert_cb(SSL *ssl, int (*cb)(SSL *ssl, void *arg), void *arg); @@ -1149,7 +1160,7 @@ OPENSSL_EXPORT void *SSL_CTX_get_default_passwd_cb_userdata(const SSL_CTX *ctx); // Custom private keys. -enum ssl_private_key_result_t { +enum ssl_private_key_result_t BORINGSSL_ENUM_INT { ssl_private_key_success, ssl_private_key_retry, ssl_private_key_failure, @@ -2100,7 +2111,7 @@ OPENSSL_EXPORT int SSL_CTX_set_tlsext_ticket_key_cb( // ssl_ticket_aead_result_t enumerates the possible results from decrypting a // ticket with an |SSL_TICKET_AEAD_METHOD|. -enum ssl_ticket_aead_result_t { +enum ssl_ticket_aead_result_t BORINGSSL_ENUM_INT { // ssl_ticket_aead_success indicates that the ticket was successfully // decrypted. ssl_ticket_aead_success, @@ -2195,6 +2206,7 @@ OPENSSL_EXPORT int SSL_set1_curves_list(SSL *ssl, const char *curves); #define SSL_CURVE_SECP521R1 25 #define SSL_CURVE_X25519 29 #define SSL_CURVE_CECPQ2 16696 +#define SSL_CURVE_CECPQ2b 65074 // SSL_get_curve_id returns the ID of the curve used by |ssl|'s most recently // completed handshake or 0 if not applicable. @@ -2274,7 +2286,7 @@ OPENSSL_EXPORT void SSL_set_verify(SSL *ssl, int mode, int (*callback)(int ok, X509_STORE_CTX *store_ctx)); -enum ssl_verify_result_t { +enum ssl_verify_result_t BORINGSSL_ENUM_INT { ssl_verify_ok, ssl_verify_invalid, ssl_verify_retry, @@ -2658,7 +2670,7 @@ OPENSSL_EXPORT SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx); // WARNING: this function is dangerous because it breaks the usual return value // convention. OPENSSL_EXPORT int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const uint8_t *protos, - size_t protos_len); + unsigned protos_len); // SSL_set_alpn_protos sets the client ALPN protocol list on |ssl| to |protos|. // |protos| must be in wire-format (i.e. a series of non-empty, 8-bit @@ -2668,7 +2680,7 @@ OPENSSL_EXPORT int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const uint8_t *protos, // WARNING: this function is dangerous because it breaks the usual return value // convention. OPENSSL_EXPORT int SSL_set_alpn_protos(SSL *ssl, const uint8_t *protos, - size_t protos_len); + unsigned protos_len); // SSL_CTX_set_alpn_select_cb sets a callback function on |ctx| that is called // during ClientHello processing in order to select an ALPN protocol from the @@ -3054,6 +3066,41 @@ OPENSSL_EXPORT void SSL_get_peer_quic_transport_params(const SSL *ssl, size_t *out_params_len); +// Delegated credentials. +// +// *** EXPERIMENTAL — PRONE TO CHANGE *** +// +// draft-ietf-tls-subcerts is a proposed extension for TLS 1.3 and above that +// allows an end point to use its certificate to delegate credentials for +// authentication. If the peer indicates support for this extension, then this +// host may use a delegated credential to sign the handshake. Once issued, +// credentials can't be revoked. In order to mitigate the damage in case the +// credential secret key is compromised, the credential is only valid for a +// short time (days, hours, or even minutes). This library implements draft-03 +// of the protocol spec. +// +// The extension ID has not been assigned; we're using 0xff02 for the time +// being. Currently only the server side is implemented. +// +// Servers configure a DC for use in the handshake via +// |SSL_set1_delegated_credential|. It must be signed by the host's end-entity +// certificate as defined in draft-ietf-tls-subcerts-03. + +// SSL_set1_delegated_credential configures the delegated credential (DC) that +// will be sent to the peer for the current connection. |dc| is the DC in wire +// format, and |pkey| or |key_method| is the corresponding private key. +// Currently (as of draft-03), only servers may configure a DC to use in the +// handshake. +// +// The DC will only be used if the protocol version is correct and the signature +// scheme is supported by the peer. If not, the DC will not be negotiated and +// the handshake will use the private key (or private key method) associated +// with the certificate. +OPENSSL_EXPORT int SSL_set1_delegated_credential( + SSL *ssl, CRYPTO_BUFFER *dc, EVP_PKEY *pkey, + const SSL_PRIVATE_KEY_METHOD *key_method); + + // QUIC integration. // // QUIC acts as an underlying transport for the TLS 1.3 handshake. The following @@ -3089,7 +3136,7 @@ OPENSSL_EXPORT void SSL_get_peer_quic_transport_params(const SSL *ssl, // ssl_encryption_level_t represents a specific QUIC encryption level used to // transmit handshake messages. -enum ssl_encryption_level_t { +enum ssl_encryption_level_t BORINGSSL_ENUM_INT { ssl_encryption_initial = 0, ssl_encryption_early_data, ssl_encryption_handshake, @@ -3245,6 +3292,10 @@ OPENSSL_EXPORT void SSL_set_early_data_enabled(SSL *ssl, int enabled); // and |SSL_write| to send half-RTT data. OPENSSL_EXPORT int SSL_in_early_data(const SSL *ssl); +// SSL_SESSION_early_data_capable returns whether early data would have been +// attempted with |session| if enabled. +OPENSSL_EXPORT int SSL_SESSION_early_data_capable(const SSL_SESSION *session); + // SSL_early_data_accepted returns whether early data was accepted on the // handshake performed by |ssl|. OPENSSL_EXPORT int SSL_early_data_accepted(const SSL *ssl); @@ -3265,6 +3316,46 @@ OPENSSL_EXPORT int SSL_export_early_keying_material( SSL *ssl, uint8_t *out, size_t out_len, const char *label, size_t label_len, const uint8_t *context, size_t context_len); +// SSL_get_ticket_age_skew returns the difference, in seconds, between the +// client-sent ticket age and the server-computed value in TLS 1.3 server +// connections which resumed a session. +OPENSSL_EXPORT int32_t SSL_get_ticket_age_skew(const SSL *ssl); + +enum ssl_early_data_reason_t BORINGSSL_ENUM_INT { + // The handshake has not progressed far enough for the 0-RTT status to be + // known. + ssl_early_data_unknown, + // 0-RTT is disabled for this connection. + ssl_early_data_disabled, + // 0-RTT was accepted. + ssl_early_data_accepted, + // The negotiated protocol version does not support 0-RTT. + ssl_early_data_protocol_version, + // The peer declined to offer or accept 0-RTT for an unknown reason. + ssl_early_data_peer_declined, + // The client did not offer a session. + ssl_early_data_no_session_offered, + // The server declined to resume the session. + ssl_early_data_session_not_resumed, + // The session does not support 0-RTT. + ssl_early_data_unsupported_for_session, + // The server sent a HelloRetryRequest. + ssl_early_data_hello_retry_request, + // The negotiated ALPN protocol did not match the session. + ssl_early_data_alpn_mismatch, + // The connection negotiated Channel ID, which is incompatible with 0-RTT. + ssl_early_data_channel_id, + // The connection negotiated token binding, which is incompatible with 0-RTT. + ssl_early_data_token_binding, + // The client and server ticket age were too far apart. + ssl_early_data_ticket_age_skew, +}; + +// SSL_get_early_data_reason returns details why 0-RTT was accepted or rejected +// on |ssl|. This is primarily useful on the server. +OPENSSL_EXPORT enum ssl_early_data_reason_t SSL_get_early_data_reason( + const SSL *ssl); + // Alerts. // @@ -3400,13 +3491,6 @@ OPENSSL_EXPORT uint64_t SSL_get_write_sequence(const SSL *ssl); // Obscure functions. -// SSL_get_structure_sizes returns the sizes of the SSL, SSL_CTX and -// SSL_SESSION structures so that a test can ensure that outside code agrees on -// these values. -OPENSSL_EXPORT void SSL_get_structure_sizes(size_t *ssl_size, - size_t *ssl_ctx_size, - size_t *ssl_session_size); - // SSL_CTX_set_msg_callback installs |cb| as the message callback for |ctx|. // This callback will be called when sending or receiving low-level record // headers, complete handshake messages, ChangeCipherSpec, and alerts. @@ -3483,7 +3567,7 @@ OPENSSL_EXPORT void SSL_CTX_set_current_time_cb( // such as HTTP/1.1, and not others, such as HTTP/2. OPENSSL_EXPORT void SSL_set_shed_handshake_config(SSL *ssl, int enable); -enum ssl_renegotiate_mode_t { +enum ssl_renegotiate_mode_t BORINGSSL_ENUM_INT { ssl_renegotiate_never = 0, ssl_renegotiate_once, ssl_renegotiate_freely, @@ -3581,7 +3665,7 @@ typedef struct ssl_early_callback_ctx { // ssl_select_cert_result_t enumerates the possible results from selecting a // certificate with |select_certificate_cb|. -enum ssl_select_cert_result_t { +enum ssl_select_cert_result_t BORINGSSL_ENUM_INT { // ssl_select_cert_success indicates that the certificate selection was // successful. ssl_select_cert_success = 1, @@ -3631,6 +3715,12 @@ OPENSSL_EXPORT void SSL_CTX_set_dos_protection_cb( // respected on clients. OPENSSL_EXPORT void SSL_CTX_set_reverify_on_resume(SSL_CTX *ctx, int enabled); +// SSL_set_enforce_rsa_key_usage configures whether the keyUsage extension of +// RSA leaf certificates will be checked for consistency with the TLS +// usage. This parameter may be set late; it will not be read until after the +// certificate verification callback. +OPENSSL_EXPORT void SSL_set_enforce_rsa_key_usage(SSL *ssl, int enabled); + // SSL_ST_* are possible values for |SSL_state|, the bitmasks that make them up, // and some historical values for compatibility. Only |SSL_ST_INIT| and // |SSL_ST_OK| are ever returned. @@ -3770,11 +3860,6 @@ OPENSSL_EXPORT void SSL_CTX_set_grease_enabled(SSL_CTX *ctx, int enabled); // record with |ssl|. OPENSSL_EXPORT size_t SSL_max_seal_overhead(const SSL *ssl); -// SSL_get_ticket_age_skew returns the difference, in seconds, between the -// client-sent ticket age and the server-computed value in TLS 1.3 server -// connections which resumed a session. -OPENSSL_EXPORT int32_t SSL_get_ticket_age_skew(const SSL *ssl); - // SSL_CTX_set_false_start_allowed_without_alpn configures whether connections // on |ctx| may use False Start (if |SSL_MODE_ENABLE_FALSE_START| is enabled) // without negotiating ALPN. @@ -3794,12 +3879,12 @@ OPENSSL_EXPORT void SSL_set_ignore_tls13_downgrade(SSL *ssl, int ignore); // mechanism would have aborted |ssl|'s handshake and zero otherwise. OPENSSL_EXPORT int SSL_is_tls13_downgrade(const SSL *ssl); -// SSL_set_jdk11_workaround configures whether to workaround a bug in JDK 11's -// TLS 1.3 implementation. Prior to 11.0.2, JDK 11 fails to send SNI in -// connections which offer a TLS 1.3 session. Enabling this workaround will -// disable TLS 1.3 on such clients. +// SSL_set_jdk11_workaround configures whether to workaround various bugs in +// JDK 11's TLS 1.3 implementation by disabling TLS 1.3 for such clients. // -// See also https://bugs.openjdk.java.net/browse/JDK-8211806. +// https://bugs.openjdk.java.net/browse/JDK-8211806 +// https://bugs.openjdk.java.net/browse/JDK-8212885 +// https://bugs.openjdk.java.net/browse/JDK-8213202 OPENSSL_EXPORT void SSL_set_jdk11_workaround(SSL *ssl, int enable); @@ -4147,6 +4232,7 @@ DEFINE_STACK_OF(SSL_COMP) #define SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG 0 #define SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG 0 #define SSL_OP_NO_COMPRESSION 0 +#define SSL_OP_NO_RENEGOTIATION 0 // ssl_renegotiate_never is the default #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION 0 #define SSL_OP_NO_SSLv2 0 #define SSL_OP_NO_SSLv3 0 @@ -4711,7 +4797,8 @@ OPENSSL_EXPORT bool SealRecord(SSL *ssl, Span out_prefix, OPENSSL_EXPORT void SSL_CTX_set_handoff_mode(SSL_CTX *ctx, bool on); OPENSSL_EXPORT void SSL_set_handoff_mode(SSL *SSL, bool on); -OPENSSL_EXPORT bool SSL_serialize_handoff(const SSL *ssl, CBB *out); +OPENSSL_EXPORT bool SSL_serialize_handoff(const SSL *ssl, CBB *out, + SSL_CLIENT_HELLO *out_hello); OPENSSL_EXPORT bool SSL_decline_handoff(SSL *ssl); OPENSSL_EXPORT bool SSL_apply_handoff(SSL *ssl, Span handoff); OPENSSL_EXPORT bool SSL_serialize_handback(const SSL *ssl, CBB *out); @@ -4932,6 +5019,9 @@ BSSL_NAMESPACE_END #define SSL_R_TLS13_DOWNGRADE 297 #define SSL_R_QUIC_INTERNAL_ERROR 298 #define SSL_R_WRONG_ENCRYPTION_LEVEL_RECEIVED 299 +#define SSL_R_TOO_MUCH_READ_EARLY_DATA 300 +#define SSL_R_INVALID_DELEGATED_CREDENTIAL 301 +#define SSL_R_KEY_USAGE_BIT_INCORRECT 302 #define SSL_R_SSLV3_ALERT_CLOSE_NOTIFY 1000 #define SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE 1010 #define SSL_R_SSLV3_ALERT_BAD_RECORD_MAC 1020 @@ -4964,6 +5054,5 @@ BSSL_NAMESPACE_END #define SSL_R_TLSV1_BAD_CERTIFICATE_HASH_VALUE 1114 #define SSL_R_TLSV1_UNKNOWN_PSK_IDENTITY 1115 #define SSL_R_TLSV1_CERTIFICATE_REQUIRED 1116 -#define SSL_R_TOO_MUCH_READ_EARLY_DATA 1117 #endif // OPENSSL_HEADER_SSL_H diff --git a/third_party/boringssl/kit/src/include/openssl/stack.h b/third_party/boringssl/kit/src/include/openssl/stack.h index 924228a5..04e942cb 100644 --- a/third_party/boringssl/kit/src/include/openssl/stack.h +++ b/third_party/boringssl/kit/src/include/openssl/stack.h @@ -78,7 +78,7 @@ extern "C" { // int bar; // } FOO; // -// DEFINE_STACK_OF(FOO); +// DEFINE_STACK_OF(FOO) // // Although note that the stack will contain /pointers/ to |FOO|. // diff --git a/third_party/boringssl/kit/src/include/openssl/tls1.h b/third_party/boringssl/kit/src/include/openssl/tls1.h index 937be6b3..384d102b 100644 --- a/third_party/boringssl/kit/src/include/openssl/tls1.h +++ b/third_party/boringssl/kit/src/include/openssl/tls1.h @@ -231,6 +231,10 @@ extern "C" { // ExtensionType value from RFC5746 #define TLSEXT_TYPE_renegotiate 0xff01 +// ExtensionType value from draft-ietf-tls-subcerts. This is not an IANA defined +// extension number. +#define TLSEXT_TYPE_delegated_credential 0xff02 + // ExtensionType value from RFC6962 #define TLSEXT_TYPE_certificate_timestamp 18 diff --git a/third_party/boringssl/kit/src/include/openssl/x509_vfy.h b/third_party/boringssl/kit/src/include/openssl/x509_vfy.h index 86aa5469..f2623349 100644 --- a/third_party/boringssl/kit/src/include/openssl/x509_vfy.h +++ b/third_party/boringssl/kit/src/include/openssl/x509_vfy.h @@ -370,6 +370,8 @@ OPENSSL_EXPORT void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth); /* Issuer lookup error */ #define X509_V_ERR_STORE_LOOKUP 66 +#define X509_V_ERR_NAME_CONSTRAINTS_WITHOUT_SANS 67 + /* Certificate verify flags */ /* Send issuer+subject checks to verify_cb */ diff --git a/third_party/boringssl/kit/src/include/openssl/x509v3.h b/third_party/boringssl/kit/src/include/openssl/x509v3.h index d2d39f8e..b5db7157 100644 --- a/third_party/boringssl/kit/src/include/openssl/x509v3.h +++ b/third_party/boringssl/kit/src/include/openssl/x509v3.h @@ -703,8 +703,8 @@ OPENSSL_EXPORT void X509_email_free(STACK_OF(OPENSSL_STRING) *sk); OPENSSL_EXPORT STACK_OF(OPENSSL_STRING) *X509_get1_ocsp(X509 *x); /* Flags for X509_check_* functions */ -/* Always check subject name for host match even if subject alt names present */ -#define X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT 0x1 +/* Deprecated: this flag does nothing */ +#define X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT 0 /* Disable wildcard matching for dnsName fields and common name. */ #define X509_CHECK_FLAG_NO_WILDCARDS 0x2 /* Wildcards must not match a partial label. */ @@ -713,6 +713,8 @@ OPENSSL_EXPORT STACK_OF(OPENSSL_STRING) *X509_get1_ocsp(X509 *x); #define X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS 0x8 /* Constraint verifier subdomain patterns to match a single labels. */ #define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS 0x10 +/* Skip the subject common name fallback if subjectAltNames is missing. */ +#define X509_CHECK_FLAG_NEVER_CHECK_SUBJECT 0x20 /* * Match reference identifiers starting with "." to any sub-domain. * This is a non-public flag, turned on implicitly when the subject diff --git a/third_party/boringssl/kit/src/infra/config/README.md b/third_party/boringssl/kit/src/infra/config/README.md deleted file mode 100644 index fa0bbc44..00000000 --- a/third_party/boringssl/kit/src/infra/config/README.md +++ /dev/null @@ -1,6 +0,0 @@ -Infrastructure location. - -This contains Commit Queue config for automatic testing of changes before they -are committed. - -Initial set up bug: http://crbug.com/618641. diff --git a/third_party/boringssl/kit/src/infra/config/cq.cfg b/third_party/boringssl/kit/src/infra/config/cq.cfg deleted file mode 100644 index f4cb1806..00000000 --- a/third_party/boringssl/kit/src/infra/config/cq.cfg +++ /dev/null @@ -1,74 +0,0 @@ -# See http://luci-config.appspot.com/schemas/projects/refs:cq.cfg for the -# documentation of this file format. -version: 1 -git_repo_url: "https://boringssl.googlesource.com/boringssl" -cq_status_url: "https://chromium-cq-status.appspot.com" -gerrit {} -verifiers { - gerrit_cq_ability { - committer_list: "project-boringssl-committers" - dry_run_access_list: "project-boringssl-tryjob-access" - } - try_job { - buckets { - name: "luci.boringssl.try" - - builders { - name: "android_aarch64" - experiment_percentage: 1 - } - builders { - name: "android_aarch64_rel" - experiment_percentage: 1 - } - builders { - name: "android_arm" - experiment_percentage: 1 - } - builders { - name: "android_arm_rel" - experiment_percentage: 1 - } - - builders { name: "linux" } - builders { name: "linux32" } - builders { name: "linux32_rel" } - builders { name: "linux_clang_rel" } - builders { name: "linux_fuzz" } - builders { name: "linux_noasm_asan" } - builders { name: "linux_nothreads" } - builders { name: "linux_rel" } - builders { name: "linux_shared" } - builders { name: "linux_small" } - - builders { name: "mac" } - builders { name: "mac_rel" } - builders { name: "mac_small" } - - builders { name: "win32" } - builders { name: "win32_rel" } - builders { name: "win32_small" } - builders { name: "win64" } - builders { name: "win64_rel" } - builders { name: "win64_small" } - builders { name: "win32_vs2017_compile" } - builders { name: "win64_vs2017_compile" } - builders { name: "win32_clang_vs2017_compile" } - builders { name: "win64_clang_vs2017_compile" } - - builders { name: "linux_fips" } - builders { name: "linux_fips_rel" } - builders { name: "linux_fips_clang" } - builders { name: "linux_fips_clang_rel" } - builders { name: "linux_fips_noasm_asan" } - - builders { name: "ios_compile" } - builders { name: "ios64_compile" } - - builders { name: "android_arm_compile" } - builders { name: "android_aarch64_compile" } - - builders { name: "docs" } - } - } -} diff --git a/third_party/boringssl/kit/src/ssl/CMakeLists.txt b/third_party/boringssl/kit/src/ssl/CMakeLists.txt index dc89dcaa..0fb532ea 100644 --- a/third_party/boringssl/kit/src/ssl/CMakeLists.txt +++ b/third_party/boringssl/kit/src/ssl/CMakeLists.txt @@ -50,6 +50,7 @@ add_executable( span_test.cc ssl_test.cc + ssl_c_test.c $ ) diff --git a/third_party/boringssl/kit/src/ssl/d1_both.cc b/third_party/boringssl/kit/src/ssl/d1_both.cc index d82852d7..f68cd1c4 100644 --- a/third_party/boringssl/kit/src/ssl/d1_both.cc +++ b/third_party/boringssl/kit/src/ssl/d1_both.cc @@ -405,7 +405,7 @@ ssl_open_record_t dtls1_open_handshake(SSL *ssl, size_t *out_consumed, return ssl_open_record_success; } -bool dtls1_get_message(SSL *ssl, SSLMessage *out) { +bool dtls1_get_message(const SSL *ssl, SSLMessage *out) { if (!dtls1_is_current_message_complete(ssl)) { return false; } diff --git a/third_party/boringssl/kit/src/ssl/handoff.cc b/third_party/boringssl/kit/src/ssl/handoff.cc index f9dbd135..db5886a6 100644 --- a/third_party/boringssl/kit/src/ssl/handoff.cc +++ b/third_party/boringssl/kit/src/ssl/handoff.cc @@ -49,7 +49,8 @@ static bool serialize_features(CBB *out) { return CBB_flush(out); } -bool SSL_serialize_handoff(const SSL *ssl, CBB *out) { +bool SSL_serialize_handoff(const SSL *ssl, CBB *out, + SSL_CLIENT_HELLO *out_hello) { const SSL3_STATE *const s3 = ssl->s3; if (!ssl->server || s3->hs == nullptr || @@ -58,6 +59,7 @@ bool SSL_serialize_handoff(const SSL *ssl, CBB *out) { } CBB seq; + SSLMessage msg; Span transcript = s3->hs->transcript.buffer(); if (!CBB_add_asn1(out, &seq, CBS_ASN1_SEQUENCE) || !CBB_add_asn1_uint64(&seq, kHandoffVersion) || @@ -66,7 +68,9 @@ bool SSL_serialize_handoff(const SSL *ssl, CBB *out) { reinterpret_cast(s3->hs_buf->data), s3->hs_buf->length) || !serialize_features(&seq) || - !CBB_flush(out)) { + !CBB_flush(out) || + !ssl->method->get_message(ssl, &msg) || + !ssl_client_hello_init(ssl, out_hello, msg)) { return false; } @@ -446,6 +450,10 @@ bool SSL_apply_handback(SSL *ssl, Span handback) { s3->aead_write_ctx->SetVersionIfNullCipher(ssl->version); s3->hs->cert_request = cert_request; + // TODO(davidben): When handoff for TLS 1.3 is added, serialize + // |early_data_reason| and stabilize the constants. + s3->early_data_reason = ssl_early_data_protocol_version; + Array key_block; if ((type == handback_after_session_resumption || type == handback_after_handshake) && diff --git a/third_party/boringssl/kit/src/ssl/handshake.cc b/third_party/boringssl/kit/src/ssl/handshake.cc index 091ed44a..b8e00704 100644 --- a/third_party/boringssl/kit/src/ssl/handshake.cc +++ b/third_party/boringssl/kit/src/ssl/handshake.cc @@ -135,6 +135,7 @@ SSL_HANDSHAKE::SSL_HANDSHAKE(SSL *ssl_arg) cert_request(false), certificate_status_expected(false), ocsp_stapling_requested(false), + delegated_credential_requested(false), should_ack_sni(false), in_false_start(false), in_early_data(false), @@ -647,6 +648,7 @@ int ssl_run_handshake(SSL_HANDSHAKE *hs, bool *out_early_return) { return -1; case ssl_hs_early_data_rejected: + assert(ssl->s3->early_data_reason != ssl_early_data_unknown); ssl->s3->rwstate = SSL_EARLY_DATA_REJECTED; // Cause |SSL_write| to start failing immediately. hs->can_early_write = false; diff --git a/third_party/boringssl/kit/src/ssl/handshake_client.cc b/third_party/boringssl/kit/src/ssl/handshake_client.cc index e2b1ffe9..b0de6708 100644 --- a/third_party/boringssl/kit/src/ssl/handshake_client.cc +++ b/third_party/boringssl/kit/src/ssl/handshake_client.cc @@ -1248,6 +1248,27 @@ static enum ssl_hs_wait_t do_send_client_key_exchange(SSL_HANDSHAKE *hs) { Array pms; uint32_t alg_k = hs->new_cipher->algorithm_mkey; uint32_t alg_a = hs->new_cipher->algorithm_auth; + if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) { + CRYPTO_BUFFER *leaf = + sk_CRYPTO_BUFFER_value(hs->new_session->certs.get(), 0); + CBS leaf_cbs; + CBS_init(&leaf_cbs, CRYPTO_BUFFER_data(leaf), CRYPTO_BUFFER_len(leaf)); + + // Check the key usage matches the cipher suite. We do this unconditionally + // for non-RSA certificates. In particular, it's needed to distinguish ECDH + // certificates, which we do not support, from ECDSA certificates. + // Historically, we have not checked RSA key usages, so it is controlled by + // a flag for now. See https://crbug.com/795089. + ssl_key_usage_t intended_use = (alg_k & SSL_kRSA) + ? key_usage_encipherment + : key_usage_digital_signature; + if (ssl->config->enforce_rsa_key_usage || + EVP_PKEY_id(hs->peer_pubkey.get()) != EVP_PKEY_RSA) { + if (!ssl_cert_check_key_usage(&leaf_cbs, intended_use)) { + return ssl_hs_error; + } + } + } // If using a PSK key exchange, prepare the pre-shared key. unsigned psk_len = 0; diff --git a/third_party/boringssl/kit/src/ssl/handshake_server.cc b/third_party/boringssl/kit/src/ssl/handshake_server.cc index 15ba2b08..f7e5df77 100644 --- a/third_party/boringssl/kit/src/ssl/handshake_server.cc +++ b/third_party/boringssl/kit/src/ssl/handshake_server.cc @@ -402,8 +402,7 @@ static enum ssl_hs_wait_t do_start_accept(SSL_HANDSHAKE *hs) { } // is_probably_jdk11_with_tls13 returns whether |client_hello| was probably sent -// from a JDK 11 client (11.0.1 or earlier) with both TLS 1.3 and a prior -// version enabled. +// from a JDK 11 client with both TLS 1.3 and a prior version enabled. static bool is_probably_jdk11_with_tls13(const SSL_CLIENT_HELLO *client_hello) { // JDK 11 ClientHellos contain a number of unusual properties which should // limit false positives. @@ -516,10 +515,6 @@ static enum ssl_hs_wait_t do_read_client_hello(SSL_HANDSHAKE *hs) { return ssl_hs_error; } - if (hs->config->handoff) { - return ssl_hs_handoff; - } - SSL_CLIENT_HELLO client_hello; if (!ssl_client_hello_init(ssl, &client_hello, msg)) { OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR); @@ -527,6 +522,10 @@ static enum ssl_hs_wait_t do_read_client_hello(SSL_HANDSHAKE *hs) { return ssl_hs_error; } + if (hs->config->handoff) { + return ssl_hs_handoff; + } + // Run the early callback. if (ssl->ctx->select_certificate_cb != NULL) { switch (ssl->ctx->select_certificate_cb(&client_hello)) { @@ -636,6 +635,8 @@ static enum ssl_hs_wait_t do_select_certificate(SSL_HANDSHAKE *hs) { return ssl_hs_ok; } + ssl->s3->early_data_reason = ssl_early_data_protocol_version; + SSL_CLIENT_HELLO client_hello; if (!ssl_client_hello_init(ssl, &client_hello, msg)) { return ssl_hs_error; diff --git a/third_party/boringssl/kit/src/ssl/internal.h b/third_party/boringssl/kit/src/ssl/internal.h index 1116badc..c7f6a5e8 100644 --- a/third_party/boringssl/kit/src/ssl/internal.h +++ b/third_party/boringssl/kit/src/ssl/internal.h @@ -1081,7 +1081,7 @@ void dtls_clear_outgoing_messages(SSL *ssl); void ssl_do_info_callback(const SSL *ssl, int type, int value); // ssl_do_msg_callback calls |ssl|'s message callback, if set. -void ssl_do_msg_callback(SSL *ssl, int is_write, int content_type, +void ssl_do_msg_callback(const SSL *ssl, int is_write, int content_type, Span in); @@ -1189,11 +1189,15 @@ bool ssl_parse_cert_chain(uint8_t *out_alert, // an empty certificate list. It returns true on success and false on error. bool ssl_add_cert_chain(SSL_HANDSHAKE *hs, CBB *cbb); -// ssl_cert_check_digital_signature_key_usage parses the DER-encoded, X.509 -// certificate in |in| and returns true if doesn't specify a key usage or, if it -// does, if it includes digitalSignature. Otherwise it pushes to the error queue -// and returns false. -bool ssl_cert_check_digital_signature_key_usage(const CBS *in); +enum ssl_key_usage_t { + key_usage_digital_signature = 0, + key_usage_encipherment = 2, +}; + +// ssl_cert_check_key_usage parses the DER-encoded, X.509 certificate in |in| +// and returns true if doesn't specify a key usage or, if it does, if it +// includes |bit|. Otherwise it pushes to the error queue and returns false. +bool ssl_cert_check_key_usage(const CBS *in, enum ssl_key_usage_t bit); // ssl_cert_parse_pubkey extracts the public key from the DER-encoded, X.509 // certificate in |in|. It returns an allocated |EVP_PKEY| or else returns @@ -1370,6 +1374,46 @@ enum handback_t { handback_after_handshake, }; + +// Delegated credentials. + +// This structure stores a delegated credential (DC) as defined by +// draft-ietf-tls-subcerts-03. +struct DC { + static constexpr bool kAllowUniquePtr = true; + ~DC(); + + // Dup returns a copy of this DC and takes references to |raw| and |pkey|. + UniquePtr Dup(); + + // Parse parses the delegated credential stored in |in|. If successful it + // returns the parsed structure, otherwise it returns |nullptr| and sets + // |*out_alert|. + static UniquePtr Parse(CRYPTO_BUFFER *in, uint8_t *out_alert); + + // raw is the delegated credential encoded as specified in draft-ietf-tls- + // subcerts-03. + UniquePtr raw; + + // expected_cert_verify_algorithm is the signature scheme of the DC public + // key. + uint16_t expected_cert_verify_algorithm = 0; + + // pkey is the public key parsed from |public_key|. + UniquePtr pkey; + + private: + friend DC* New(); + DC(); +}; + +// ssl_signing_with_dc returns true if the peer has indicated support for +// delegated credentials and this host has sent a delegated credential in +// response. If this is true then we've committed to using the DC in the +// handshake. +bool ssl_signing_with_dc(const SSL_HANDSHAKE *hs); + + struct SSL_HANDSHAKE { explicit SSL_HANDSHAKE(SSL *ssl); ~SSL_HANDSHAKE(); @@ -1541,6 +1585,10 @@ struct SSL_HANDSHAKE { // ocsp_stapling_requested is true if a client requested OCSP stapling. bool ocsp_stapling_requested : 1; + // delegated_credential_requested is true if the peer indicated support for + // the delegated credential extension. + bool delegated_credential_requested : 1; + // should_ack_sni is used by a server and indicates that the SNI extension // should be echoed in the ServerHello. bool should_ack_sni : 1; @@ -1750,7 +1798,7 @@ int ssl_log_secret(const SSL *ssl, const char *label, const uint8_t *secret, // ClientHello functions. -bool ssl_client_hello_init(SSL *ssl, SSL_CLIENT_HELLO *out, +bool ssl_client_hello_init(const SSL *ssl, SSL_CLIENT_HELLO *out, const SSLMessage &msg); bool ssl_client_hello_get_extension(const SSL_CLIENT_HELLO *client_hello, @@ -1786,6 +1834,15 @@ bool tls1_get_legacy_signature_algorithm(uint16_t *out, const EVP_PKEY *pkey); // supported. It returns true on success and false on error. bool tls1_choose_signature_algorithm(SSL_HANDSHAKE *hs, uint16_t *out); +// tls1_get_peer_verify_algorithms returns the signature schemes for which the +// peer indicated support. +// +// NOTE: The related function |SSL_get0_peer_verify_algorithms| only has +// well-defined behavior during the callbacks set by |SSL_CTX_set_cert_cb| and +// |SSL_CTX_set_client_cert_cb|, or when the handshake is paused because of +// them. +Span tls1_get_peer_verify_algorithms(const SSL_HANDSHAKE *hs); + // tls12_add_verify_sigalgs adds the signature algorithms acceptable for the // peer signature to |out|. It returns true on success and false on error. If // |for_certs| is true, the potentially more restrictive list of algorithms for @@ -1879,6 +1936,19 @@ struct CERT { // ticket key. Only sessions with a matching value will be accepted. uint8_t sid_ctx_length = 0; uint8_t sid_ctx[SSL_MAX_SID_CTX_LENGTH] = {0}; + + // Delegated credentials. + + // dc is the delegated credential to send to the peer (if requested). + UniquePtr dc = nullptr; + + // dc_privatekey is used instead of |privatekey| or |key_method| to + // authenticate the host if a delegated credential is used in the handshake. + UniquePtr dc_privatekey = nullptr; + + // dc_key_method, if not NULL, is used instead of |dc_privatekey| to + // authenticate the host. + const SSL_PRIVATE_KEY_METHOD *dc_key_method = nullptr; }; // |SSL_PROTOCOL_METHOD| abstracts between TLS and DTLS. @@ -1888,7 +1958,7 @@ struct SSL_PROTOCOL_METHOD { void (*ssl_free)(SSL *ssl); // get_message sets |*out| to the current handshake message and returns true // if one has been received. It returns false if more input is needed. - bool (*get_message)(SSL *ssl, SSLMessage *out); + bool (*get_message)(const SSL *ssl, SSLMessage *out); // next_message is called to release the current handshake message. void (*next_message)(SSL *ssl); // Use the |ssl_open_handshake| wrapper. @@ -1959,7 +2029,7 @@ struct SSL_X509_METHOD { // check_client_CA_list returns one if |names| is a good list of X.509 // distinguished names and zero otherwise. This is used to ensure that we can // reject unparsable values at handshake time when using crypto/x509. - int (*check_client_CA_list)(STACK_OF(CRYPTO_BUFFER) *names); + bool (*check_client_CA_list)(STACK_OF(CRYPTO_BUFFER) *names); // cert_clear frees and NULLs all X509 certificate-related state. void (*cert_clear)(CERT *cert); @@ -1976,35 +2046,35 @@ struct SSL_X509_METHOD { // session_cache_objects fills out |sess->x509_peer| and |sess->x509_chain| // from |sess->certs| and erases |sess->x509_chain_without_leaf|. It returns - // one on success or zero on error. - int (*session_cache_objects)(SSL_SESSION *session); + // true on success or false on error. + bool (*session_cache_objects)(SSL_SESSION *session); // session_dup duplicates any needed fields from |session| to |new_session|. - // It returns one on success or zero on error. - int (*session_dup)(SSL_SESSION *new_session, const SSL_SESSION *session); + // It returns true on success or false on error. + bool (*session_dup)(SSL_SESSION *new_session, const SSL_SESSION *session); // session_clear frees any X509-related state from |session|. void (*session_clear)(SSL_SESSION *session); // session_verify_cert_chain verifies the certificate chain in |session|, - // sets |session->verify_result| and returns one on success or zero on + // sets |session->verify_result| and returns true on success or false on // error. - int (*session_verify_cert_chain)(SSL_SESSION *session, SSL_HANDSHAKE *ssl, - uint8_t *out_alert); + bool (*session_verify_cert_chain)(SSL_SESSION *session, SSL_HANDSHAKE *ssl, + uint8_t *out_alert); // hs_flush_cached_ca_names drops any cached |X509_NAME|s from |hs|. void (*hs_flush_cached_ca_names)(SSL_HANDSHAKE *hs); - // ssl_new does any neccessary initialisation of |hs|. It returns one on - // success or zero on error. - int (*ssl_new)(SSL_HANDSHAKE *hs); + // ssl_new does any necessary initialisation of |hs|. It returns true on + // success or false on error. + bool (*ssl_new)(SSL_HANDSHAKE *hs); // ssl_free frees anything created by |ssl_new|. void (*ssl_config_free)(SSL_CONFIG *cfg); // ssl_flush_cached_client_CA drops any cached |X509_NAME|s from |ssl|. void (*ssl_flush_cached_client_CA)(SSL_CONFIG *cfg); // ssl_auto_chain_if_needed runs the deprecated auto-chaining logic if // necessary. On success, it updates |ssl|'s certificate configuration as - // needed and returns one. Otherwise, it returns zero. - int (*ssl_auto_chain_if_needed)(SSL_HANDSHAKE *hs); - // ssl_ctx_new does any neccessary initialisation of |ctx|. It returns one on - // success or zero on error. - int (*ssl_ctx_new)(SSL_CTX *ctx); + // needed and returns true. Otherwise, it returns false. + bool (*ssl_auto_chain_if_needed)(SSL_HANDSHAKE *hs); + // ssl_ctx_new does any necessary initialisation of |ctx|. It returns true on + // success or false on error. + bool (*ssl_ctx_new)(SSL_CTX *ctx); // ssl_ctx_free frees anything created by |ssl_ctx_new|. void (*ssl_ctx_free)(SSL_CTX *ctx); // ssl_ctx_flush_cached_client_CA drops any cached |X509_NAME|s from |ctx|. @@ -2044,7 +2114,7 @@ BSSL_NAMESPACE_END DEFINE_LHASH_OF(SSL_SESSION) -DEFINE_NAMED_STACK_OF(CertCompressionAlg, bssl::CertCompressionAlg); +DEFINE_NAMED_STACK_OF(CertCompressionAlg, bssl::CertCompressionAlg) BSSL_NAMESPACE_BEGIN @@ -2196,6 +2266,9 @@ struct SSL3_STATE { // which resumed a session. int32_t ticket_age_skew = 0; + // ssl_early_data_reason stores details on why 0-RTT was accepted or rejected. + enum ssl_early_data_reason_t early_data_reason = ssl_early_data_unknown; + // aead_read_ctx is the current read cipher state. UniquePtr aead_read_ctx; @@ -2394,14 +2467,14 @@ struct SSL_CONFIG { // ssl is a non-owning pointer to the parent |SSL| object. SSL *const ssl = nullptr; - // conf_max_version is the maximum acceptable protocol version configured by - // |SSL_set_max_proto_version|. Note this version is normalized in DTLS and is - // further constrainted by |SSL_OP_NO_*|. + // conf_max_version is the maximum acceptable version configured by + // |SSL_set_max_proto_version|. Note this version is not normalized in DTLS + // and is further constrained by |SSL_OP_NO_*|. uint16_t conf_max_version = 0; - // conf_min_version is the minimum acceptable protocol version configured by - // |SSL_set_min_proto_version|. Note this version is normalized in DTLS and is - // further constrainted by |SSL_OP_NO_*|. + // conf_min_version is the minimum acceptable version configured by + // |SSL_set_min_proto_version|. Note this version is not normalized in DTLS + // and is further constrained by |SSL_OP_NO_*|. uint16_t conf_min_version = 0; X509_VERIFY_PARAM *param = nullptr; @@ -2474,6 +2547,11 @@ struct SSL_CONFIG { // advertise support. bool channel_id_enabled : 1; + // If enforce_rsa_key_usage is true, the handshake will fail if the + // keyUsage extension is present and incompatible with the TLS usage. + // This field is not read until after certificate verification. + bool enforce_rsa_key_usage : 1; + // retain_only_sha256_of_client_certs is true if we should compute the SHA256 // hash of the peer's certificate and then discard it to save memory and // session space. Only effective on the server side. @@ -2599,8 +2677,9 @@ void ssl_session_renew_timeout(SSL *ssl, SSL_SESSION *session, void ssl_update_cache(SSL_HANDSHAKE *hs, int mode); -int ssl_send_alert(SSL *ssl, int level, int desc); -bool ssl3_get_message(SSL *ssl, SSLMessage *out); +void ssl_send_alert(SSL *ssl, int level, int desc); +int ssl_send_alert_impl(SSL *ssl, int level, int desc); +bool ssl3_get_message(const SSL *ssl, SSLMessage *out); ssl_open_record_t ssl3_open_handshake(SSL *ssl, size_t *out_consumed, uint8_t *out_alert, Span in); void ssl3_next_message(SSL *ssl); @@ -2666,7 +2745,7 @@ unsigned int dtls1_min_mtu(void); bool dtls1_new(SSL *ssl); void dtls1_free(SSL *ssl); -bool dtls1_get_message(SSL *ssl, SSLMessage *out); +bool dtls1_get_message(const SSL *ssl, SSLMessage *out); ssl_open_record_t dtls1_open_handshake(SSL *ssl, size_t *out_consumed, uint8_t *out_alert, Span in); void dtls1_next_message(SSL *ssl); diff --git a/third_party/boringssl/kit/src/ssl/s3_both.cc b/third_party/boringssl/kit/src/ssl/s3_both.cc index aec6cae3..27e9454f 100644 --- a/third_party/boringssl/kit/src/ssl/s3_both.cc +++ b/third_party/boringssl/kit/src/ssl/s3_both.cc @@ -494,7 +494,7 @@ static bool parse_message(const SSL *ssl, SSLMessage *out, return true; } -bool ssl3_get_message(SSL *ssl, SSLMessage *out) { +bool ssl3_get_message(const SSL *ssl, SSLMessage *out) { size_t unused; if (!parse_message(ssl, out, &unused)) { return false; diff --git a/third_party/boringssl/kit/src/ssl/s3_pkt.cc b/third_party/boringssl/kit/src/ssl/s3_pkt.cc index abc6798e..67bfd63d 100644 --- a/third_party/boringssl/kit/src/ssl/s3_pkt.cc +++ b/third_party/boringssl/kit/src/ssl/s3_pkt.cc @@ -118,6 +118,7 @@ #include #include +#include "../crypto/err/internal.h" #include "../crypto/internal.h" #include "internal.h" @@ -381,7 +382,24 @@ ssl_open_record_t ssl3_open_change_cipher_spec(SSL *ssl, size_t *out_consumed, return ssl_open_record_success; } -int ssl_send_alert(SSL *ssl, int level, int desc) { +void ssl_send_alert(SSL *ssl, int level, int desc) { + // This function is called in response to a fatal error from the peer. Ignore + // any failures writing the alert and report only the original error. In + // particular, if the transport uses |SSL_write|, our existing error will be + // clobbered so we must save and restore the error queue. See + // https://crbug.com/959305. + // + // TODO(davidben): Return the alert out of the handshake, rather than calling + // this function internally everywhere. + // + // TODO(davidben): This does not allow retrying if the alert hit EAGAIN. See + // https://crbug.com/boringssl/130. + UniquePtr err_state(ERR_save_state()); + ssl_send_alert_impl(ssl, level, desc); + ERR_restore_state(err_state.get()); +} + +int ssl_send_alert_impl(SSL *ssl, int level, int desc) { // It is illegal to send an alert when we've already sent a closing one. if (ssl->s3->write_shutdown != ssl_shutdown_none) { OPENSSL_PUT_ERROR(SSL, SSL_R_PROTOCOL_IS_SHUTDOWN); diff --git a/third_party/boringssl/kit/src/ssl/ssl_c_test.c b/third_party/boringssl/kit/src/ssl/ssl_c_test.c new file mode 100644 index 00000000..02f8655d --- /dev/null +++ b/third_party/boringssl/kit/src/ssl/ssl_c_test.c @@ -0,0 +1,15 @@ +#include + +int BORINGSSL_enum_c_type_test(void); + +int BORINGSSL_enum_c_type_test(void) { +#if defined(__cplusplus) +#error "This is testing the behaviour of the C compiler." +#error "It's pointless to build it in C++ mode." +#endif + + // In C++, the enums in ssl.h are explicitly typed as ints to allow them to + // be predeclared. This function confirms that the C compiler believes them + // to be the same size as ints. They may differ in signedness, however. + return sizeof(enum ssl_private_key_result_t) == sizeof(int); +} diff --git a/third_party/boringssl/kit/src/ssl/ssl_cert.cc b/third_party/boringssl/kit/src/ssl/ssl_cert.cc index 95518107..54df38f7 100644 --- a/third_party/boringssl/kit/src/ssl/ssl_cert.cc +++ b/third_party/boringssl/kit/src/ssl/ssl_cert.cc @@ -180,6 +180,16 @@ UniquePtr ssl_cert_dup(CERT *cert) { ret->sid_ctx_length = cert->sid_ctx_length; OPENSSL_memcpy(ret->sid_ctx, cert->sid_ctx, sizeof(ret->sid_ctx)); + if (cert->dc) { + ret->dc = cert->dc->Dup(); + if (!ret->dc) { + return nullptr; + } + } + + ret->dc_privatekey = UpRef(cert->dc_privatekey); + ret->dc_key_method = cert->dc_key_method; + return ret; } @@ -194,6 +204,10 @@ void ssl_cert_clear_certs(CERT *cert) { cert->chain.reset(); cert->privatekey.reset(); cert->key_method = nullptr; + + cert->dc.reset(); + cert->dc_privatekey.reset(); + cert->dc_key_method = nullptr; } static void ssl_cert_set_cert_cb(CERT *cert, int (*cb)(SSL *ssl, void *arg), @@ -232,7 +246,7 @@ static enum leaf_cert_and_privkey_result_t check_leaf_cert_and_privkey( // An ECC certificate may be usable for ECDH or ECDSA. We only support ECDSA // certificates, so sanity-check the key usage extension. if (pubkey->type == EVP_PKEY_EC && - !ssl_cert_check_digital_signature_key_usage(&cert_cbs)) { + !ssl_cert_check_key_usage(&cert_cbs, key_usage_digital_signature)) { OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE); return leaf_cert_and_privkey_error; } @@ -526,7 +540,7 @@ bool ssl_cert_check_private_key(const CERT *cert, const EVP_PKEY *privkey) { return ssl_compare_public_and_private_key(pubkey.get(), privkey); } -bool ssl_cert_check_digital_signature_key_usage(const CBS *in) { +bool ssl_cert_check_key_usage(const CBS *in, enum ssl_key_usage_t bit) { CBS buf = *in; CBS tbs_cert, outer_extensions; @@ -592,8 +606,8 @@ bool ssl_cert_check_digital_signature_key_usage(const CBS *in) { return false; } - if (!CBS_asn1_bitstring_has_bit(&bit_string, 0)) { - OPENSSL_PUT_ERROR(SSL, SSL_R_ECC_CERT_NOT_FOR_SIGNING); + if (!CBS_asn1_bitstring_has_bit(&bit_string, bit)) { + OPENSSL_PUT_ERROR(SSL, SSL_R_KEY_USAGE_BIT_INCORRECT); return false; } @@ -696,20 +710,6 @@ bool ssl_check_leaf_certificate(SSL_HANDSHAKE *hs, EVP_PKEY *pkey, return false; } - // Check key usages for all key types but RSA. This is needed to distinguish - // ECDH certificates, which we do not support, from ECDSA certificates. In - // principle, we should check RSA key usages based on cipher, but this breaks - // buggy antivirus deployments. Other key types are always used for signing. - // - // TODO(davidben): Get more recent data on RSA key usages. - if (EVP_PKEY_id(pkey) != EVP_PKEY_RSA) { - CBS leaf_cbs; - CBS_init(&leaf_cbs, CRYPTO_BUFFER_data(leaf), CRYPTO_BUFFER_len(leaf)); - if (!ssl_cert_check_digital_signature_key_usage(&leaf_cbs)) { - return false; - } - } - if (EVP_PKEY_id(pkey) == EVP_PKEY_EC) { // Check the key's group and point format are acceptable. EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(pkey); @@ -741,10 +741,141 @@ bool ssl_on_certificate_selected(SSL_HANDSHAKE *hs) { CRYPTO_BUFFER_init_CBS( sk_CRYPTO_BUFFER_value(hs->config->cert->chain.get(), 0), &leaf); - hs->local_pubkey = ssl_cert_parse_pubkey(&leaf); + if (ssl_signing_with_dc(hs)) { + hs->local_pubkey = UpRef(hs->config->cert->dc->pkey); + } else { + hs->local_pubkey = ssl_cert_parse_pubkey(&leaf); + } return hs->local_pubkey != NULL; } + +// Delegated credentials. + +DC::DC() = default; +DC::~DC() = default; + +UniquePtr DC::Dup() { + bssl::UniquePtr ret = MakeUnique(); + if (!ret) { + return nullptr; + } + + ret->raw = UpRef(raw); + ret->expected_cert_verify_algorithm = expected_cert_verify_algorithm; + ret->pkey = UpRef(pkey); + return ret; +} + +// static +UniquePtr DC::Parse(CRYPTO_BUFFER *in, uint8_t *out_alert) { + UniquePtr dc = MakeUnique(); + if (!dc) { + *out_alert = SSL_AD_INTERNAL_ERROR; + return nullptr; + } + + dc->raw = UpRef(in); + + CBS pubkey, deleg, sig; + uint32_t valid_time; + uint16_t algorithm; + CRYPTO_BUFFER_init_CBS(dc->raw.get(), &deleg); + if (!CBS_get_u32(&deleg, &valid_time) || + !CBS_get_u16(&deleg, &dc->expected_cert_verify_algorithm) || + !CBS_get_u24_length_prefixed(&deleg, &pubkey) || + !CBS_get_u16(&deleg, &algorithm) || + !CBS_get_u16_length_prefixed(&deleg, &sig) || + CBS_len(&deleg) != 0) { + OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR); + *out_alert = SSL_AD_DECODE_ERROR; + return nullptr; + } + + dc->pkey.reset(EVP_parse_public_key(&pubkey)); + if (dc->pkey == nullptr) { + OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR); + *out_alert = SSL_AD_DECODE_ERROR; + return nullptr; + } + + return dc; +} + +// ssl_can_serve_dc returns true if the host has configured a DC that it can +// serve in the handshake. Specifically, it checks that a DC has been +// configured and that the DC signature algorithm is supported by the peer. +static bool ssl_can_serve_dc(const SSL_HANDSHAKE *hs) { + // Check that a DC has been configured. + const CERT *cert = hs->config->cert.get(); + if (cert->dc == nullptr || + cert->dc->raw == nullptr || + (cert->dc_privatekey == nullptr && cert->dc_key_method == nullptr)) { + return false; + } + + // Check that 1.3 or higher has been negotiated. + const DC *dc = cert->dc.get(); + assert(hs->ssl->s3->have_version); + if (ssl_protocol_version(hs->ssl) < TLS1_3_VERSION) { + return false; + } + + // Check that the DC signature algorithm is supported by the peer. + Span peer_sigalgs = tls1_get_peer_verify_algorithms(hs); + bool sigalg_found = false; + for (uint16_t peer_sigalg : peer_sigalgs) { + if (dc->expected_cert_verify_algorithm == peer_sigalg) { + sigalg_found = true; + break; + } + } + + return sigalg_found; +} + +bool ssl_signing_with_dc(const SSL_HANDSHAKE *hs) { + // As of draft-ietf-tls-subcert-03, only the server may use delegated + // credentials to authenticate itself. + return hs->ssl->server && + hs->delegated_credential_requested && + ssl_can_serve_dc(hs); +} + +static int cert_set_dc(CERT *cert, CRYPTO_BUFFER *const raw, EVP_PKEY *privkey, + const SSL_PRIVATE_KEY_METHOD *key_method) { + if (privkey == nullptr && key_method == nullptr) { + OPENSSL_PUT_ERROR(SSL, ERR_R_PASSED_NULL_PARAMETER); + return 0; + } + + if (privkey != nullptr && key_method != nullptr) { + OPENSSL_PUT_ERROR(SSL, SSL_R_CANNOT_HAVE_BOTH_PRIVKEY_AND_METHOD); + return 0; + } + + uint8_t alert; + UniquePtr dc = DC::Parse(raw, &alert); + if (dc == nullptr) { + OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_DELEGATED_CREDENTIAL); + return 0; + } + + if (privkey) { + // Check that the public and private keys match. + if (!ssl_compare_public_and_private_key(dc->pkey.get(), privkey)) { + OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_AND_PRIVATE_KEY_MISMATCH); + return 0; + } + } + + cert->dc = std::move(dc); + cert->dc_privatekey = UpRef(privkey); + cert->dc_key_method = key_method; + + return 1; +} + BSSL_NAMESPACE_END using namespace bssl; @@ -870,3 +1001,12 @@ void SSL_set0_client_CAs(SSL *ssl, STACK_OF(CRYPTO_BUFFER) *name_list) { ssl->ctx->x509_method->ssl_flush_cached_client_CA(ssl->config.get()); ssl->config->client_CA.reset(name_list); } + +int SSL_set1_delegated_credential(SSL *ssl, CRYPTO_BUFFER *dc, EVP_PKEY *pkey, + const SSL_PRIVATE_KEY_METHOD *key_method) { + if (!ssl->config) { + return 0; + } + + return cert_set_dc(ssl->config->cert.get(), dc, pkey, key_method); +} diff --git a/third_party/boringssl/kit/src/ssl/ssl_key_share.cc b/third_party/boringssl/kit/src/ssl/ssl_key_share.cc index 8556c4f4..2bf177b2 100644 --- a/third_party/boringssl/kit/src/ssl/ssl_key_share.cc +++ b/third_party/boringssl/kit/src/ssl/ssl_key_share.cc @@ -31,7 +31,7 @@ #include "internal.h" #include "../crypto/internal.h" - +#include "../third_party/sike/sike.h" BSSL_NAMESPACE_BEGIN @@ -234,7 +234,7 @@ class CECPQ2KeyShare : public SSLKeyShare { } return true; - }; + } bool Accept(CBB *out_public_key, Array *out_secret, uint8_t *out_alert, Span peer_key) override { @@ -293,13 +293,94 @@ class CECPQ2KeyShare : public SSLKeyShare { *out_secret = std::move(secret); return true; - }; + } private: uint8_t x25519_private_key_[32]; HRSS_private_key hrss_private_key_; }; +class CECPQ2bKeyShare : public SSLKeyShare { + public: + uint16_t GroupID() const override { return SSL_CURVE_CECPQ2b; } + + bool Offer(CBB *out) override { + uint8_t public_x25519[32] = {0}; + X25519_keypair(public_x25519, private_x25519_); + if (!SIKE_keypair(private_sike_, public_sike_)) { + return false; + } + + return CBB_add_bytes(out, public_x25519, sizeof(public_x25519)) && + CBB_add_bytes(out, public_sike_, sizeof(public_sike_)); + } + + bool Accept(CBB *out_public_key, Array *out_secret, + uint8_t *out_alert, Span peer_key) override { + uint8_t public_x25519[32]; + uint8_t private_x25519[32]; + uint8_t sike_ciphertext[SIKEp503_CT_BYTESZ] = {0}; + + *out_alert = SSL_AD_INTERNAL_ERROR; + + if (peer_key.size() != sizeof(public_x25519) + SIKEp503_PUB_BYTESZ) { + *out_alert = SSL_AD_DECODE_ERROR; + OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECPOINT); + return false; + } + + Array secret; + if (!secret.Init(sizeof(private_x25519_) + SIKEp503_SS_BYTESZ)) { + OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE); + return false; + } + + X25519_keypair(public_x25519, private_x25519); + if (!X25519(secret.data(), private_x25519, peer_key.data())) { + *out_alert = SSL_AD_DECODE_ERROR; + OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECPOINT); + return false; + } + + SIKE_encaps(secret.data() + sizeof(private_x25519_), sike_ciphertext, + peer_key.data() + sizeof(public_x25519)); + *out_secret = std::move(secret); + + return CBB_add_bytes(out_public_key, public_x25519, + sizeof(public_x25519)) && + CBB_add_bytes(out_public_key, sike_ciphertext, + sizeof(sike_ciphertext)); + } + + bool Finish(Array *out_secret, uint8_t *out_alert, + Span peer_key) override { + *out_alert = SSL_AD_INTERNAL_ERROR; + + Array secret; + if (!secret.Init(sizeof(private_x25519_) + SIKEp503_SS_BYTESZ)) { + OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE); + return false; + } + + if (peer_key.size() != 32 + SIKEp503_CT_BYTESZ || + !X25519(secret.data(), private_x25519_, peer_key.data())) { + *out_alert = SSL_AD_DECODE_ERROR; + OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECPOINT); + return false; + } + + SIKE_decaps(secret.data() + sizeof(private_x25519_), peer_key.data() + 32, + public_sike_, private_sike_); + *out_secret = std::move(secret); + return true; + } + + private: + uint8_t private_x25519_[32]; + uint8_t private_sike_[SIKEp503_PRV_BYTESZ]; + uint8_t public_sike_[SIKEp503_PUB_BYTESZ]; +}; + CONSTEXPR_ARRAY NamedGroup kNamedGroups[] = { {NID_secp224r1, SSL_CURVE_SECP224R1, "P-224", "secp224r1"}, {NID_X9_62_prime256v1, SSL_CURVE_SECP256R1, "P-256", "prime256v1"}, @@ -307,6 +388,7 @@ CONSTEXPR_ARRAY NamedGroup kNamedGroups[] = { {NID_secp521r1, SSL_CURVE_SECP521R1, "P-521", "secp521r1"}, {NID_X25519, SSL_CURVE_X25519, "X25519", "x25519"}, {NID_CECPQ2, SSL_CURVE_CECPQ2, "CECPQ2", "CECPQ2"}, + {NID_CECPQ2b, SSL_CURVE_CECPQ2b, "CECPQ2b", "CECPQ2b"}, }; } // namespace @@ -333,6 +415,8 @@ UniquePtr SSLKeyShare::Create(uint16_t group_id) { return UniquePtr(New()); case SSL_CURVE_CECPQ2: return UniquePtr(New()); + case SSL_CURVE_CECPQ2b: + return UniquePtr(New()); default: return nullptr; } diff --git a/third_party/boringssl/kit/src/ssl/ssl_lib.cc b/third_party/boringssl/kit/src/ssl/ssl_lib.cc index f3d92a6b..f27f2b87 100644 --- a/third_party/boringssl/kit/src/ssl/ssl_lib.cc +++ b/third_party/boringssl/kit/src/ssl/ssl_lib.cc @@ -378,7 +378,7 @@ void ssl_do_info_callback(const SSL *ssl, int type, int value) { } } -void ssl_do_msg_callback(SSL *ssl, int is_write, int content_type, +void ssl_do_msg_callback(const SSL *ssl, int is_write, int content_type, Span in) { if (ssl->msg_callback == NULL) { return; @@ -399,8 +399,8 @@ void ssl_do_msg_callback(SSL *ssl, int is_write, int content_type, version = SSL_version(ssl); } - ssl->msg_callback(is_write, version, content_type, in.data(), in.size(), ssl, - ssl->msg_callback_arg); + ssl->msg_callback(is_write, version, content_type, in.data(), in.size(), + const_cast(ssl), ssl->msg_callback_arg); } void ssl_get_current_time(const SSL *ssl, struct OPENSSL_timeval *out_clock) { @@ -729,6 +729,7 @@ SSL_CONFIG::SSL_CONFIG(SSL *ssl_arg) signed_cert_timestamps_enabled(false), ocsp_stapling_enabled(false), channel_id_enabled(false), + enforce_rsa_key_usage(false), retain_only_sha256_of_client_certs(false), handoff(false), shed_handshake_config(false), @@ -1194,7 +1195,7 @@ int SSL_shutdown(SSL *ssl) { if (ssl->s3->write_shutdown != ssl_shutdown_close_notify) { // Send a close_notify. - if (ssl_send_alert(ssl, SSL3_AL_WARNING, SSL_AD_CLOSE_NOTIFY) <= 0) { + if (ssl_send_alert_impl(ssl, SSL3_AL_WARNING, SSL_AD_CLOSE_NOTIFY) <= 0) { return -1; } } else if (ssl->s3->alert_dispatch) { @@ -1241,7 +1242,7 @@ int SSL_send_fatal_alert(SSL *ssl, uint8_t alert) { return ssl->method->dispatch_alert(ssl); } - return ssl_send_alert(ssl, SSL3_AL_FATAL, alert); + return ssl_send_alert_impl(ssl, SSL3_AL_FATAL, alert); } int SSL_set_quic_transport_params(SSL *ssl, const uint8_t *params, @@ -1293,6 +1294,10 @@ void SSL_reset_early_data_reject(SSL *ssl) { ssl->s3->wpend_pending = false; } +enum ssl_early_data_reason_t SSL_get_early_data_reason(const SSL *ssl) { + return ssl->s3->early_data_reason; +} + static int bio_retry_reason_to_error(int reason) { switch (reason) { case BIO_RR_CONNECT: @@ -2141,14 +2146,14 @@ void SSL_CTX_set_next_proto_select_cb( } int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const uint8_t *protos, - size_t protos_len) { + unsigned protos_len) { // Note this function's calling convention is backwards. return ctx->alpn_client_proto_list.CopyFrom(MakeConstSpan(protos, protos_len)) ? 0 : 1; } -int SSL_set_alpn_protos(SSL *ssl, const uint8_t *protos, size_t protos_len) { +int SSL_set_alpn_protos(SSL *ssl, const uint8_t *protos, unsigned protos_len) { // Note this function's calling convention is backwards. if (!ssl->config) { return 1; @@ -2671,13 +2676,6 @@ int SSL_cutthrough_complete(const SSL *ssl) { return SSL_in_false_start(ssl); } -void SSL_get_structure_sizes(size_t *ssl_size, size_t *ssl_ctx_size, - size_t *ssl_session_size) { - *ssl_size = sizeof(SSL); - *ssl_ctx_size = sizeof(SSL_CTX); - *ssl_session_size = sizeof(SSL_SESSION); -} - int SSL_is_server(const SSL *ssl) { return ssl->server; } int SSL_is_dtls(const SSL *ssl) { return ssl->method->is_dtls; } @@ -2697,6 +2695,13 @@ void SSL_CTX_set_reverify_on_resume(SSL_CTX *ctx, int enabled) { ctx->reverify_on_resume = !!enabled; } +void SSL_set_enforce_rsa_key_usage(SSL *ssl, int enabled) { + if (!ssl->config) { + return; + } + ssl->config->enforce_rsa_key_usage = !!enabled; +} + void SSL_set_renegotiate_mode(SSL *ssl, enum ssl_renegotiate_mode_t mode) { ssl->renegotiate_mode = mode; diff --git a/third_party/boringssl/kit/src/ssl/ssl_privkey.cc b/third_party/boringssl/kit/src/ssl/ssl_privkey.cc index 16888b92..1ddb1b16 100644 --- a/third_party/boringssl/kit/src/ssl/ssl_privkey.cc +++ b/third_party/boringssl/kit/src/ssl/ssl_privkey.cc @@ -134,8 +134,13 @@ static const SSL_SIGNATURE_ALGORITHM *get_signature_algorithm(uint16_t sigalg) { } bool ssl_has_private_key(const SSL_HANDSHAKE *hs) { - return (hs->config->cert->privatekey != nullptr || - hs->config->cert->key_method != nullptr); + if (hs->config->cert->privatekey != nullptr || + hs->config->cert->key_method != nullptr || + ssl_signing_with_dc(hs)) { + return true; + } + + return false; } static bool pkey_supports_algorithm(const SSL *ssl, EVP_PKEY *pkey, @@ -196,13 +201,20 @@ enum ssl_private_key_result_t ssl_private_key_sign( SSL_HANDSHAKE *hs, uint8_t *out, size_t *out_len, size_t max_out, uint16_t sigalg, Span in) { SSL *const ssl = hs->ssl; - if (hs->config->cert->key_method != NULL) { + const SSL_PRIVATE_KEY_METHOD *key_method = hs->config->cert->key_method; + EVP_PKEY *privatekey = hs->config->cert->privatekey.get(); + if (ssl_signing_with_dc(hs)) { + key_method = hs->config->cert->dc_key_method; + privatekey = hs->config->cert->dc_privatekey.get(); + } + + if (key_method != NULL) { enum ssl_private_key_result_t ret; if (hs->pending_private_key_op) { - ret = hs->config->cert->key_method->complete(ssl, out, out_len, max_out); + ret = key_method->complete(ssl, out, out_len, max_out); } else { - ret = hs->config->cert->key_method->sign(ssl, out, out_len, max_out, - sigalg, in.data(), in.size()); + ret = key_method->sign(ssl, out, out_len, max_out, + sigalg, in.data(), in.size()); } if (ret == ssl_private_key_failure) { OPENSSL_PUT_ERROR(SSL, SSL_R_PRIVATE_KEY_OPERATION_FAILED); @@ -213,8 +225,7 @@ enum ssl_private_key_result_t ssl_private_key_sign( *out_len = max_out; ScopedEVP_MD_CTX ctx; - if (!setup_ctx(ssl, ctx.get(), hs->config->cert->privatekey.get(), sigalg, - false /* sign */) || + if (!setup_ctx(ssl, ctx.get(), privatekey, sigalg, false /* sign */) || !EVP_DigestSign(ctx.get(), out, out_len, in.data(), in.size())) { return ssl_private_key_failure; } @@ -553,6 +564,10 @@ static int compare_uint16_t(const void *p1, const void *p2) { } static bool sigalgs_unique(Span in_sigalgs) { + if (in_sigalgs.size() < 2) { + return true; + } + Array sigalgs; if (!sigalgs.CopyFrom(in_sigalgs)) { return false; diff --git a/third_party/boringssl/kit/src/ssl/ssl_session.cc b/third_party/boringssl/kit/src/ssl/ssl_session.cc index 927dd1ba..bb04b1ad 100644 --- a/third_party/boringssl/kit/src/ssl/ssl_session.cc +++ b/third_party/boringssl/kit/src/ssl/ssl_session.cc @@ -1044,6 +1044,11 @@ void SSL_SESSION_get0_peer_sha256(const SSL_SESSION *session, } } +int SSL_SESSION_early_data_capable(const SSL_SESSION *session) { + return ssl_session_protocol_version(session) >= TLS1_3_VERSION && + session->ticket_max_early_data != 0; +} + SSL_SESSION *SSL_magic_pending_session_ptr(void) { return (SSL_SESSION *)&g_pending_session_magic; } diff --git a/third_party/boringssl/kit/src/ssl/ssl_test.cc b/third_party/boringssl/kit/src/ssl/ssl_test.cc index f3f79234..6f180c74 100644 --- a/third_party/boringssl/kit/src/ssl/ssl_test.cc +++ b/third_party/boringssl/kit/src/ssl/ssl_test.cc @@ -737,111 +737,85 @@ static bool DecodeBase64(std::vector *out, const char *in) { return true; } -static bool TestSSL_SESSIONEncoding(const char *input_b64) { - const uint8_t *cptr; - uint8_t *ptr; +TEST(SSLTest, SessionEncoding) { + for (const char *input_b64 : { + kOpenSSLSession, + kCustomSession, + kBoringSSLSession, + }) { + SCOPED_TRACE(std::string(input_b64)); + // Decode the input. + std::vector input; + ASSERT_TRUE(DecodeBase64(&input, input_b64)); - // Decode the input. - std::vector input; - if (!DecodeBase64(&input, input_b64)) { - return false; + // Verify the SSL_SESSION decodes. + bssl::UniquePtr ssl_ctx(SSL_CTX_new(TLS_method())); + ASSERT_TRUE(ssl_ctx); + bssl::UniquePtr session( + SSL_SESSION_from_bytes(input.data(), input.size(), ssl_ctx.get())); + ASSERT_TRUE(session) << "SSL_SESSION_from_bytes failed"; + + // Verify the SSL_SESSION encoding round-trips. + size_t encoded_len; + bssl::UniquePtr encoded; + uint8_t *encoded_raw; + ASSERT_TRUE(SSL_SESSION_to_bytes(session.get(), &encoded_raw, &encoded_len)) + << "SSL_SESSION_to_bytes failed"; + encoded.reset(encoded_raw); + EXPECT_EQ(Bytes(encoded.get(), encoded_len), Bytes(input)) + << "SSL_SESSION_to_bytes did not round-trip"; + + // Verify the SSL_SESSION also decodes with the legacy API. + const uint8_t *cptr = input.data(); + session.reset(d2i_SSL_SESSION(NULL, &cptr, input.size())); + ASSERT_TRUE(session) << "d2i_SSL_SESSION failed"; + EXPECT_EQ(cptr, input.data() + input.size()); + + // Verify the SSL_SESSION encoding round-trips via the legacy API. + int len = i2d_SSL_SESSION(session.get(), NULL); + ASSERT_GT(len, 0) << "i2d_SSL_SESSION failed"; + ASSERT_EQ(static_cast(len), input.size()) + << "i2d_SSL_SESSION(NULL) returned invalid length"; + + encoded.reset((uint8_t *)OPENSSL_malloc(input.size())); + ASSERT_TRUE(encoded); + + uint8_t *ptr = encoded.get(); + len = i2d_SSL_SESSION(session.get(), &ptr); + ASSERT_GT(len, 0) << "i2d_SSL_SESSION failed"; + ASSERT_EQ(static_cast(len), input.size()) + << "i2d_SSL_SESSION(NULL) returned invalid length"; + ASSERT_EQ(ptr, encoded.get() + input.size()) + << "i2d_SSL_SESSION did not advance ptr correctly"; + EXPECT_EQ(Bytes(encoded.get(), encoded_len), Bytes(input)) + << "SSL_SESSION_to_bytes did not round-trip"; } - // Verify the SSL_SESSION decodes. - bssl::UniquePtr ssl_ctx(SSL_CTX_new(TLS_method())); - if (!ssl_ctx) { - return false; - } - bssl::UniquePtr session( - SSL_SESSION_from_bytes(input.data(), input.size(), ssl_ctx.get())); - if (!session) { - fprintf(stderr, "SSL_SESSION_from_bytes failed\n"); - return false; - } + for (const char *input_b64 : { + kBadSessionExtraField, + kBadSessionVersion, + kBadSessionTrailingData, + }) { + SCOPED_TRACE(std::string(input_b64)); + std::vector input; + ASSERT_TRUE(DecodeBase64(&input, input_b64)); - // Verify the SSL_SESSION encoding round-trips. - size_t encoded_len; - bssl::UniquePtr encoded; - uint8_t *encoded_raw; - if (!SSL_SESSION_to_bytes(session.get(), &encoded_raw, &encoded_len)) { - fprintf(stderr, "SSL_SESSION_to_bytes failed\n"); - return false; + // Verify that the SSL_SESSION fails to decode. + bssl::UniquePtr ssl_ctx(SSL_CTX_new(TLS_method())); + ASSERT_TRUE(ssl_ctx); + bssl::UniquePtr session( + SSL_SESSION_from_bytes(input.data(), input.size(), ssl_ctx.get())); + EXPECT_FALSE(session) << "SSL_SESSION_from_bytes unexpectedly succeeded"; + ERR_clear_error(); } - encoded.reset(encoded_raw); - if (encoded_len != input.size() || - OPENSSL_memcmp(input.data(), encoded.get(), input.size()) != 0) { - fprintf(stderr, "SSL_SESSION_to_bytes did not round-trip\n"); - hexdump(stderr, "Before: ", input.data(), input.size()); - hexdump(stderr, "After: ", encoded_raw, encoded_len); - return false; - } - - // Verify the SSL_SESSION also decodes with the legacy API. - cptr = input.data(); - session.reset(d2i_SSL_SESSION(NULL, &cptr, input.size())); - if (!session || cptr != input.data() + input.size()) { - fprintf(stderr, "d2i_SSL_SESSION failed\n"); - return false; - } - - // Verify the SSL_SESSION encoding round-trips via the legacy API. - int len = i2d_SSL_SESSION(session.get(), NULL); - if (len < 0 || (size_t)len != input.size()) { - fprintf(stderr, "i2d_SSL_SESSION(NULL) returned invalid length\n"); - return false; - } - - encoded.reset((uint8_t *)OPENSSL_malloc(input.size())); - if (!encoded) { - fprintf(stderr, "malloc failed\n"); - return false; - } - - ptr = encoded.get(); - len = i2d_SSL_SESSION(session.get(), &ptr); - if (len < 0 || (size_t)len != input.size()) { - fprintf(stderr, "i2d_SSL_SESSION returned invalid length\n"); - return false; - } - if (ptr != encoded.get() + input.size()) { - fprintf(stderr, "i2d_SSL_SESSION did not advance ptr correctly\n"); - return false; - } - if (OPENSSL_memcmp(input.data(), encoded.get(), input.size()) != 0) { - fprintf(stderr, "i2d_SSL_SESSION did not round-trip\n"); - return false; - } - - return true; -} - -static bool TestBadSSL_SESSIONEncoding(const char *input_b64) { - std::vector input; - if (!DecodeBase64(&input, input_b64)) { - return false; - } - - // Verify that the SSL_SESSION fails to decode. - bssl::UniquePtr ssl_ctx(SSL_CTX_new(TLS_method())); - if (!ssl_ctx) { - return false; - } - bssl::UniquePtr session( - SSL_SESSION_from_bytes(input.data(), input.size(), ssl_ctx.get())); - if (session) { - fprintf(stderr, "SSL_SESSION_from_bytes unexpectedly succeeded\n"); - return false; - } - ERR_clear_error(); - return true; } static void ExpectDefaultVersion(uint16_t min_version, uint16_t max_version, const SSL_METHOD *(*method)(void)) { bssl::UniquePtr ctx(SSL_CTX_new(method())); ASSERT_TRUE(ctx); - EXPECT_EQ(min_version, ctx->conf_min_version); - EXPECT_EQ(max_version, ctx->conf_max_version); + EXPECT_EQ(min_version, SSL_CTX_get_min_proto_version(ctx.get())); + EXPECT_EQ(max_version, SSL_CTX_get_max_proto_version(ctx.get())); } TEST(SSLTest, DefaultVersion) { @@ -850,9 +824,9 @@ TEST(SSLTest, DefaultVersion) { ExpectDefaultVersion(TLS1_VERSION, TLS1_VERSION, &TLSv1_method); ExpectDefaultVersion(TLS1_1_VERSION, TLS1_1_VERSION, &TLSv1_1_method); ExpectDefaultVersion(TLS1_2_VERSION, TLS1_2_VERSION, &TLSv1_2_method); - ExpectDefaultVersion(TLS1_1_VERSION, TLS1_2_VERSION, &DTLS_method); - ExpectDefaultVersion(TLS1_1_VERSION, TLS1_1_VERSION, &DTLSv1_method); - ExpectDefaultVersion(TLS1_2_VERSION, TLS1_2_VERSION, &DTLSv1_2_method); + ExpectDefaultVersion(DTLS1_VERSION, DTLS1_2_VERSION, &DTLS_method); + ExpectDefaultVersion(DTLS1_VERSION, DTLS1_VERSION, &DTLSv1_method); + ExpectDefaultVersion(DTLS1_2_VERSION, DTLS1_2_VERSION, &DTLSv1_2_method); } TEST(SSLTest, CipherProperties) { @@ -1087,63 +1061,67 @@ static size_t GetClientHelloLen(uint16_t max_version, uint16_t session_version, return client_hello.size() - SSL3_RT_HEADER_LENGTH; } -struct PaddingTest { - size_t input_len, padded_len; -}; +TEST(SSLTest, Padding) { + struct PaddingVersions { + uint16_t max_version, session_version; + }; + static const PaddingVersions kPaddingVersions[] = { + // Test the padding extension at TLS 1.2. + {TLS1_2_VERSION, TLS1_2_VERSION}, + // Test the padding extension at TLS 1.3 with a TLS 1.2 session, so there + // will be no PSK binder after the padding extension. + {TLS1_3_VERSION, TLS1_2_VERSION}, + // Test the padding extension at TLS 1.3 with a TLS 1.3 session, so there + // will be a PSK binder after the padding extension. + {TLS1_3_VERSION, TLS1_3_VERSION}, -static const PaddingTest kPaddingTests[] = { - // ClientHellos of length below 0x100 do not require padding. - {0xfe, 0xfe}, - {0xff, 0xff}, - // ClientHellos of length 0x100 through 0x1fb are padded up to 0x200. - {0x100, 0x200}, - {0x123, 0x200}, - {0x1fb, 0x200}, - // ClientHellos of length 0x1fc through 0x1ff get padded beyond 0x200. The - // padding extension takes a minimum of four bytes plus one required content - // byte. (To work around yet more server bugs, we avoid empty final - // extensions.) - {0x1fc, 0x201}, - {0x1fd, 0x202}, - {0x1fe, 0x203}, - {0x1ff, 0x204}, - // Finally, larger ClientHellos need no padding. - {0x200, 0x200}, - {0x201, 0x201}, -}; + }; -static bool TestPaddingExtension(uint16_t max_version, - uint16_t session_version) { - // Sample a baseline length. - size_t base_len = GetClientHelloLen(max_version, session_version, 1); - if (base_len == 0) { - return false; - } + struct PaddingTest { + size_t input_len, padded_len; + }; + static const PaddingTest kPaddingTests[] = { + // ClientHellos of length below 0x100 do not require padding. + {0xfe, 0xfe}, + {0xff, 0xff}, + // ClientHellos of length 0x100 through 0x1fb are padded up to 0x200. + {0x100, 0x200}, + {0x123, 0x200}, + {0x1fb, 0x200}, + // ClientHellos of length 0x1fc through 0x1ff get padded beyond 0x200. The + // padding extension takes a minimum of four bytes plus one required + // content + // byte. (To work around yet more server bugs, we avoid empty final + // extensions.) + {0x1fc, 0x201}, + {0x1fd, 0x202}, + {0x1fe, 0x203}, + {0x1ff, 0x204}, + // Finally, larger ClientHellos need no padding. + {0x200, 0x200}, + {0x201, 0x201}, + }; - for (const PaddingTest &test : kPaddingTests) { - if (base_len > test.input_len) { - fprintf(stderr, - "Baseline ClientHello too long (max_version = %04x, " - "session_version = %04x).\n", - max_version, session_version); - return false; - } + for (const PaddingVersions &versions : kPaddingVersions) { + SCOPED_TRACE(versions.max_version); + SCOPED_TRACE(versions.session_version); - size_t padded_len = GetClientHelloLen(max_version, session_version, - 1 + test.input_len - base_len); - if (padded_len != test.padded_len) { - fprintf(stderr, - "%u-byte ClientHello padded to %u bytes, not %u (max_version = " - "%04x, session_version = %04x).\n", - static_cast(test.input_len), - static_cast(padded_len), - static_cast(test.padded_len), max_version, - session_version); - return false; + // Sample a baseline length. + size_t base_len = + GetClientHelloLen(versions.max_version, versions.session_version, 1); + ASSERT_NE(base_len, 0u) << "Baseline length could not be sampled"; + + for (const PaddingTest &test : kPaddingTests) { + SCOPED_TRACE(test.input_len); + ASSERT_LE(base_len, test.input_len) << "Baseline ClientHello too long"; + + size_t padded_len = + GetClientHelloLen(versions.max_version, versions.session_version, + 1 + test.input_len - base_len); + EXPECT_EQ(padded_len, test.padded_len) + << "ClientHello was not padded to expected length"; } } - - return true; } static bssl::UniquePtr GetTestCertificate() { @@ -1550,6 +1528,37 @@ static bool CompleteHandshakes(SSL *client, SSL *server) { return true; } +static bool FlushNewSessionTickets(SSL *client, SSL *server) { + // NewSessionTickets are deferred on the server to |SSL_write|, and clients do + // not pick them up until |SSL_read|. + for (;;) { + int server_ret = SSL_write(server, nullptr, 0); + int server_err = SSL_get_error(server, server_ret); + // The server may either succeed (|server_ret| is zero) or block on write + // (|server_ret| is -1 and |server_err| is |SSL_ERROR_WANT_WRITE|). + if (server_ret > 0 || + (server_ret < 0 && server_err != SSL_ERROR_WANT_WRITE)) { + fprintf(stderr, "Unexpected server result: %d %d\n", server_ret, + server_err); + return false; + } + + int client_ret = SSL_read(client, nullptr, 0); + int client_err = SSL_get_error(client, client_ret); + // The client must always block on read. + if (client_ret != -1 || client_err != SSL_ERROR_WANT_READ) { + fprintf(stderr, "Unexpected client result: %d %d\n", client_ret, + client_err); + return false; + } + + // The server flushed everything it had to write. + if (server_ret == 0) { + return true; + } + } +} + struct ClientConfig { SSL_SESSION *session = nullptr; std::string servername; @@ -1650,20 +1659,18 @@ class SSLVersionTest : public ::testing::TestWithParam { bssl::UniquePtr key_; }; -INSTANTIATE_TEST_CASE_P(WithVersion, SSLVersionTest, - testing::ValuesIn(kAllVersions), - [](const testing::TestParamInfo &i) { - return i.param.name; - }); +INSTANTIATE_TEST_SUITE_P(WithVersion, SSLVersionTest, + testing::ValuesIn(kAllVersions), + [](const testing::TestParamInfo &i) { + return i.param.name; + }); TEST_P(SSLVersionTest, SequenceNumber) { ASSERT_TRUE(Connect()); // Drain any post-handshake messages to ensure there are no unread records // on either end. - uint8_t byte = 0; - ASSERT_LE(SSL_read(client_.get(), &byte, 1), 0); - ASSERT_LE(SSL_read(server_.get(), &byte, 1), 0); + ASSERT_TRUE(FlushNewSessionTickets(client_.get(), server_.get())); uint64_t client_read_seq = SSL_get_read_sequence(client_.get()); uint64_t client_write_seq = SSL_get_write_sequence(client_.get()); @@ -1687,6 +1694,7 @@ TEST_P(SSLVersionTest, SequenceNumber) { } // Send a record from client to server. + uint8_t byte = 0; EXPECT_EQ(SSL_write(client_.get(), &byte, 1), 1); EXPECT_EQ(SSL_read(server_.get(), &byte, 1), 1); @@ -2084,14 +2092,12 @@ static bssl::UniquePtr CreateClientSession( // Connect client and server to get a session. bssl::UniquePtr client, server; if (!ConnectClientAndServer(&client, &server, client_ctx, server_ctx, - config)) { + config) || + !FlushNewSessionTickets(client.get(), server.get())) { fprintf(stderr, "Failed to connect client and server.\n"); return nullptr; } - // Run the read loop to account for post-handshake tickets in TLS 1.3. - SSL_read(client.get(), nullptr, 0); - SSL_CTX_sess_set_new_cb(client_ctx, nullptr); if (!g_last_session) { @@ -2125,7 +2131,8 @@ static bssl::UniquePtr ExpectSessionRenewed(SSL_CTX *client_ctx, ClientConfig config; config.session = session; if (!ConnectClientAndServer(&client, &server, client_ctx, server_ctx, - config)) { + config) || + !FlushNewSessionTickets(client.get(), server.get())) { fprintf(stderr, "Failed to connect client and server.\n"); return nullptr; } @@ -2140,9 +2147,6 @@ static bssl::UniquePtr ExpectSessionRenewed(SSL_CTX *client_ctx, return nullptr; } - // Run the read loop to account for post-handshake tickets in TLS 1.3. - SSL_read(client.get(), nullptr, 0); - SSL_CTX_sess_set_new_cb(client_ctx, nullptr); if (!g_last_session) { @@ -2617,13 +2621,13 @@ TEST(SSLTest, SetVersion) { // Zero is the default version. EXPECT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), 0)); - EXPECT_EQ(TLS1_2_VERSION, ctx->conf_max_version); + EXPECT_EQ(TLS1_2_VERSION, SSL_CTX_get_max_proto_version(ctx.get())); EXPECT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), 0)); - EXPECT_EQ(TLS1_VERSION, ctx->conf_min_version); + EXPECT_EQ(TLS1_VERSION, SSL_CTX_get_min_proto_version(ctx.get())); // TLS 1.3 is available, but not by default. EXPECT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), TLS1_3_VERSION)); - EXPECT_EQ(TLS1_3_VERSION, ctx->conf_max_version); + EXPECT_EQ(TLS1_3_VERSION, SSL_CTX_get_max_proto_version(ctx.get())); // SSL 3.0 is not available. EXPECT_FALSE(SSL_CTX_set_min_proto_version(ctx.get(), SSL3_VERSION)); @@ -2646,9 +2650,9 @@ TEST(SSLTest, SetVersion) { EXPECT_FALSE(SSL_CTX_set_min_proto_version(ctx.get(), 0x1234)); EXPECT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), 0)); - EXPECT_EQ(TLS1_2_VERSION, ctx->conf_max_version); + EXPECT_EQ(DTLS1_2_VERSION, SSL_CTX_get_max_proto_version(ctx.get())); EXPECT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), 0)); - EXPECT_EQ(TLS1_1_VERSION, ctx->conf_min_version); + EXPECT_EQ(DTLS1_VERSION, SSL_CTX_get_min_proto_version(ctx.get())); } static const char *GetVersionName(uint16_t version) { @@ -3055,6 +3059,82 @@ TEST_P(SSLVersionTest, ClientSessionCacheMode) { EXPECT_FALSE(CreateClientSession(client_ctx_.get(), server_ctx_.get())); } +// Test that all versions survive tiny write buffers. In particular, TLS 1.3 +// NewSessionTickets are written post-handshake. Servers that block +// |SSL_do_handshake| on writing them will deadlock if clients are not draining +// the buffer. Test that we do not do this. +TEST_P(SSLVersionTest, SmallBuffer) { + // DTLS is a datagram protocol and requires packet-sized buffers. + if (is_dtls()) { + return; + } + + // Test both flushing NewSessionTickets with a zero-sized write and + // non-zero-sized write. + for (bool use_zero_write : {false, true}) { + SCOPED_TRACE(use_zero_write); + + g_last_session = nullptr; + SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH); + SSL_CTX_sess_set_new_cb(client_ctx_.get(), SaveLastSession); + + bssl::UniquePtr client(SSL_new(client_ctx_.get())), + server(SSL_new(server_ctx_.get())); + ASSERT_TRUE(client); + ASSERT_TRUE(server); + SSL_set_connect_state(client.get()); + SSL_set_accept_state(server.get()); + + // Use a tiny buffer. + BIO *bio1, *bio2; + ASSERT_TRUE(BIO_new_bio_pair(&bio1, 1, &bio2, 1)); + + // SSL_set_bio takes ownership. + SSL_set_bio(client.get(), bio1, bio1); + SSL_set_bio(server.get(), bio2, bio2); + + ASSERT_TRUE(CompleteHandshakes(client.get(), server.get())); + if (version() >= TLS1_3_VERSION) { + // The post-handshake ticket should not have been processed yet. + EXPECT_FALSE(g_last_session); + } + + if (use_zero_write) { + ASSERT_TRUE(FlushNewSessionTickets(client.get(), server.get())); + EXPECT_TRUE(g_last_session); + } + + // Send some data from server to client. If |use_zero_write| is false, this + // will also flush the NewSessionTickets. + static const char kMessage[] = "hello world"; + char buf[sizeof(kMessage)]; + for (;;) { + int server_ret = SSL_write(server.get(), kMessage, sizeof(kMessage)); + int server_err = SSL_get_error(server.get(), server_ret); + int client_ret = SSL_read(client.get(), buf, sizeof(buf)); + int client_err = SSL_get_error(client.get(), client_ret); + + // The server will write a single record, so every iteration should see + // |SSL_ERROR_WANT_WRITE| and |SSL_ERROR_WANT_READ|, until the final + // iteration, where both will complete. + if (server_ret > 0) { + EXPECT_EQ(server_ret, static_cast(sizeof(kMessage))); + EXPECT_EQ(client_ret, static_cast(sizeof(kMessage))); + EXPECT_EQ(Bytes(buf), Bytes(kMessage)); + break; + } + + ASSERT_EQ(server_ret, -1); + ASSERT_EQ(server_err, SSL_ERROR_WANT_WRITE); + ASSERT_EQ(client_ret, -1); + ASSERT_EQ(client_err, SSL_ERROR_WANT_READ); + } + + // The NewSessionTickets should have been flushed and processed. + EXPECT_TRUE(g_last_session); + } +} + TEST(SSLTest, AddChainCertHack) { // Ensure that we don't accidently break the hack that we have in place to // keep curl and serf happy when they use an |X509| even after transfering @@ -3514,9 +3594,7 @@ TEST_P(TicketAEADMethodTest, Resume) { EXPECT_FALSE(SSL_session_reused(client.get())); EXPECT_FALSE(SSL_session_reused(server.get())); - // Run the read loop to account for post-handshake tickets in TLS 1.3. - SSL_read(client.get(), nullptr, 0); - + ASSERT_TRUE(FlushNewSessionTickets(client.get(), server.get())); bssl::UniquePtr session = std::move(g_last_session); ConnectClientAndServerWithTicketMethod(&client, &server, client_ctx.get(), server_ctx.get(), retry_count, @@ -3574,7 +3652,7 @@ std::string TicketAEADMethodParamToString( return ret; } -INSTANTIATE_TEST_CASE_P( +INSTANTIATE_TEST_SUITE_P( TicketAEADMethodTests, TicketAEADMethodTest, testing::Combine(testing::Values(TLS1_2_VERSION, TLS1_3_VERSION), testing::Values(0, 1, 2), @@ -4050,8 +4128,9 @@ TEST(SSLTest, Handoff) { ScopedCBB cbb; Array handoff; + SSL_CLIENT_HELLO hello; ASSERT_TRUE(CBB_init(cbb.get(), 256)); - ASSERT_TRUE(SSL_serialize_handoff(server.get(), cbb.get())); + ASSERT_TRUE(SSL_serialize_handoff(server.get(), cbb.get(), &hello)); ASSERT_TRUE(CBBFinishArray(cbb.get(), &handoff)); bssl::UniquePtr handshaker(SSL_new(handshaker_ctx.get())); @@ -4122,8 +4201,9 @@ TEST(SSLTest, HandoffDeclined) { ASSERT_EQ(server_err, SSL_ERROR_HANDOFF); ScopedCBB cbb; + SSL_CLIENT_HELLO hello; ASSERT_TRUE(CBB_init(cbb.get(), 256)); - ASSERT_TRUE(SSL_serialize_handoff(server.get(), cbb.get())); + ASSERT_TRUE(SSL_serialize_handoff(server.get(), cbb.get(), &hello)); ASSERT_TRUE(SSL_decline_handoff(server.get())); @@ -4604,7 +4684,7 @@ TEST_P(SSLVersionTest, SessionPropertiesThreads) { thread.join(); } } -#endif +#endif // OPENSSL_THREADS constexpr size_t kNumQUICLevels = 4; static_assert(ssl_encryption_initial < kNumQUICLevels, @@ -5261,23 +5341,101 @@ TEST_F(QUICMethodTest, BadPostHandshake) { EXPECT_EQ(SSL_process_quic_post_handshake(client_.get()), 0); } -// TODO(davidben): Convert this file to GTest properly. -TEST(SSLTest, AllTests) { - if (!TestSSL_SESSIONEncoding(kOpenSSLSession) || - !TestSSL_SESSIONEncoding(kCustomSession) || - !TestSSL_SESSIONEncoding(kBoringSSLSession) || - !TestBadSSL_SESSIONEncoding(kBadSessionExtraField) || - !TestBadSSL_SESSIONEncoding(kBadSessionVersion) || - !TestBadSSL_SESSIONEncoding(kBadSessionTrailingData) || - // Test the padding extension at TLS 1.2. - !TestPaddingExtension(TLS1_2_VERSION, TLS1_2_VERSION) || - // Test the padding extension at TLS 1.3 with a TLS 1.2 session, so there - // will be no PSK binder after the padding extension. - !TestPaddingExtension(TLS1_3_VERSION, TLS1_2_VERSION) || - // Test the padding extension at TLS 1.3 with a TLS 1.3 session, so there - // will be a PSK binder after the padding extension. - !TestPaddingExtension(TLS1_3_VERSION, TLS1_3_VERSION)) { - ADD_FAILURE() << "Tests failed"; +extern "C" { +int BORINGSSL_enum_c_type_test(void); +} + +TEST(SSLTest, EnumTypes) { + EXPECT_EQ(sizeof(int), sizeof(ssl_private_key_result_t)); + EXPECT_EQ(1, BORINGSSL_enum_c_type_test()); +} + +TEST_P(SSLVersionTest, DoubleSSLError) { + // Connect the inner SSL connections. + ASSERT_TRUE(Connect()); + + // Make a pair of |BIO|s which wrap |client_| and |server_|. + UniquePtr bio_method(BIO_meth_new(0, nullptr)); + ASSERT_TRUE(bio_method); + ASSERT_TRUE(BIO_meth_set_read( + bio_method.get(), [](BIO *bio, char *out, int len) -> int { + SSL *ssl = static_cast(BIO_get_data(bio)); + int ret = SSL_read(ssl, out, len); + int ssl_ret = SSL_get_error(ssl, ret); + if (ssl_ret == SSL_ERROR_WANT_READ) { + BIO_set_retry_read(bio); + } + return ret; + })); + ASSERT_TRUE(BIO_meth_set_write( + bio_method.get(), [](BIO *bio, const char *in, int len) -> int { + SSL *ssl = static_cast(BIO_get_data(bio)); + int ret = SSL_write(ssl, in, len); + int ssl_ret = SSL_get_error(ssl, ret); + if (ssl_ret == SSL_ERROR_WANT_WRITE) { + BIO_set_retry_write(bio); + } + return ret; + })); + ASSERT_TRUE(BIO_meth_set_ctrl( + bio_method.get(), [](BIO *bio, int cmd, long larg, void *parg) -> long { + // |SSL| objects require |BIO_flush| support. + if (cmd == BIO_CTRL_FLUSH) { + return 1; + } + return 0; + })); + + UniquePtr client_bio(BIO_new(bio_method.get())); + ASSERT_TRUE(client_bio); + BIO_set_data(client_bio.get(), client_.get()); + BIO_set_init(client_bio.get(), 1); + + UniquePtr server_bio(BIO_new(bio_method.get())); + ASSERT_TRUE(server_bio); + BIO_set_data(server_bio.get(), server_.get()); + BIO_set_init(server_bio.get(), 1); + + // Wrap the inner connections in another layer of SSL. + UniquePtr client_outer(SSL_new(client_ctx_.get())); + ASSERT_TRUE(client_outer); + SSL_set_connect_state(client_outer.get()); + SSL_set_bio(client_outer.get(), client_bio.get(), client_bio.get()); + client_bio.release(); // |SSL_set_bio| takes ownership. + + UniquePtr server_outer(SSL_new(server_ctx_.get())); + ASSERT_TRUE(server_outer); + SSL_set_accept_state(server_outer.get()); + SSL_set_bio(server_outer.get(), server_bio.get(), server_bio.get()); + server_bio.release(); // |SSL_set_bio| takes ownership. + + // Configure |client_outer| to reject the server certificate. + SSL_set_custom_verify( + client_outer.get(), SSL_VERIFY_PEER, + [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t { + return ssl_verify_invalid; + }); + + for (;;) { + int client_ret = SSL_do_handshake(client_outer.get()); + int client_err = SSL_get_error(client_outer.get(), client_ret); + if (client_err != SSL_ERROR_WANT_READ && + client_err != SSL_ERROR_WANT_WRITE) { + // The client handshake should terminate on a certificate verification + // error. + EXPECT_EQ(SSL_ERROR_SSL, client_err); + uint32_t err = ERR_peek_error(); + EXPECT_EQ(ERR_LIB_SSL, ERR_GET_LIB(err)); + EXPECT_EQ(SSL_R_CERTIFICATE_VERIFY_FAILED, ERR_GET_REASON(err)); + break; + } + + // Run the server handshake and continue. + int server_ret = SSL_do_handshake(server_outer.get()); + int server_err = SSL_get_error(server_outer.get(), server_ret); + ASSERT_TRUE(server_err == SSL_ERROR_NONE || + server_err == SSL_ERROR_WANT_READ || + server_err == SSL_ERROR_WANT_WRITE); } } diff --git a/third_party/boringssl/kit/src/ssl/ssl_versions.cc b/third_party/boringssl/kit/src/ssl/ssl_versions.cc index e6dbc8de..e25fce6d 100644 --- a/third_party/boringssl/kit/src/ssl/ssl_versions.cc +++ b/third_party/boringssl/kit/src/ssl/ssl_versions.cc @@ -134,12 +134,12 @@ static bool api_version_to_wire(uint16_t *out, uint16_t version) { static bool set_version_bound(const SSL_PROTOCOL_METHOD *method, uint16_t *out, uint16_t version) { if (!api_version_to_wire(&version, version) || - !ssl_method_supports_version(method, version) || - !ssl_protocol_version_from_wire(out, version)) { + !ssl_method_supports_version(method, version)) { OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_SSL_VERSION); return false; } + *out = version; return true; } @@ -147,8 +147,7 @@ static bool set_min_version(const SSL_PROTOCOL_METHOD *method, uint16_t *out, uint16_t version) { // Zero is interpreted as the default minimum version. if (version == 0) { - // TLS 1.0 does not exist in DTLS. - *out = method->is_dtls ? TLS1_1_VERSION : TLS1_VERSION; + *out = method->is_dtls ? DTLS1_VERSION : TLS1_VERSION; return true; } @@ -159,7 +158,7 @@ static bool set_max_version(const SSL_PROTOCOL_METHOD *method, uint16_t *out, uint16_t version) { // Zero is interpreted as the default maximum version. if (version == 0) { - *out = TLS1_2_VERSION; + *out = method->is_dtls ? DTLS1_2_VERSION : TLS1_2_VERSION; return true; } @@ -188,8 +187,14 @@ bool ssl_get_version_range(const SSL_HANDSHAKE *hs, uint16_t *out_min_version, } } - uint16_t min_version = hs->config->conf_min_version; - uint16_t max_version = hs->config->conf_max_version; + uint16_t min_version, max_version; + if (!ssl_protocol_version_from_wire(&min_version, + hs->config->conf_min_version) || + !ssl_protocol_version_from_wire(&max_version, + hs->config->conf_max_version)) { + OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR); + return false; + } // QUIC requires TLS 1.3. if (hs->ssl->quic_method && min_version < TLS1_3_VERSION) { @@ -344,6 +349,14 @@ int SSL_CTX_set_max_proto_version(SSL_CTX *ctx, uint16_t version) { return set_max_version(ctx->method, &ctx->conf_max_version, version); } +uint16_t SSL_CTX_get_min_proto_version(SSL_CTX *ctx) { + return ctx->conf_min_version; +} + +uint16_t SSL_CTX_get_max_proto_version(SSL_CTX *ctx) { + return ctx->conf_max_version; +} + int SSL_set_min_proto_version(SSL *ssl, uint16_t version) { if (!ssl->config) { return 0; diff --git a/third_party/boringssl/kit/src/ssl/ssl_x509.cc b/third_party/boringssl/kit/src/ssl/ssl_x509.cc index 841482f8..cda76117 100644 --- a/third_party/boringssl/kit/src/ssl/ssl_x509.cc +++ b/third_party/boringssl/kit/src/ssl/ssl_x509.cc @@ -200,19 +200,19 @@ static UniquePtr new_leafless_chain(void) { // forms of elements of |chain|. It returns one on success or zero on error, in // which case no change to |cert->chain| is made. It preverses the existing // leaf from |cert->chain|, if any. -static int ssl_cert_set_chain(CERT *cert, STACK_OF(X509) *chain) { +static bool ssl_cert_set_chain(CERT *cert, STACK_OF(X509) *chain) { UniquePtr new_chain; if (cert->chain != nullptr) { new_chain.reset(sk_CRYPTO_BUFFER_new_null()); if (!new_chain) { - return 0; + return false; } // |leaf| might be NULL if it's a “leafless” chain. CRYPTO_BUFFER *leaf = sk_CRYPTO_BUFFER_value(cert->chain.get(), 0); if (!PushToStack(new_chain.get(), UpRef(leaf))) { - return 0; + return false; } } @@ -220,32 +220,32 @@ static int ssl_cert_set_chain(CERT *cert, STACK_OF(X509) *chain) { if (!new_chain) { new_chain = new_leafless_chain(); if (!new_chain) { - return 0; + return false; } } UniquePtr buffer = x509_to_buffer(x509); if (!buffer || !PushToStack(new_chain.get(), std::move(buffer))) { - return 0; + return false; } } cert->chain = std::move(new_chain); - return 1; + return true; } static void ssl_crypto_x509_cert_flush_cached_leaf(CERT *cert) { X509_free(cert->x509_leaf); - cert->x509_leaf = NULL; + cert->x509_leaf = nullptr; } static void ssl_crypto_x509_cert_flush_cached_chain(CERT *cert) { sk_X509_pop_free(cert->x509_chain, X509_free); - cert->x509_chain = NULL; + cert->x509_chain = nullptr; } -static int ssl_crypto_x509_check_client_CA_list( +static bool ssl_crypto_x509_check_client_CA_list( STACK_OF(CRYPTO_BUFFER) *names) { for (const CRYPTO_BUFFER *buffer : names) { const uint8_t *inp = CRYPTO_BUFFER_data(buffer); @@ -253,11 +253,11 @@ static int ssl_crypto_x509_check_client_CA_list( d2i_X509_NAME(nullptr, &inp, CRYPTO_BUFFER_len(buffer))); if (name == nullptr || inp != CRYPTO_BUFFER_data(buffer) + CRYPTO_BUFFER_len(buffer)) { - return 0; + return false; } } - return 1; + return true; } static void ssl_crypto_x509_cert_clear(CERT *cert) { @@ -265,7 +265,7 @@ static void ssl_crypto_x509_cert_clear(CERT *cert) { ssl_crypto_x509_cert_flush_cached_chain(cert); X509_free(cert->x509_stash); - cert->x509_stash = NULL; + cert->x509_stash = nullptr; } static void ssl_crypto_x509_cert_free(CERT *cert) { @@ -274,19 +274,19 @@ static void ssl_crypto_x509_cert_free(CERT *cert) { } static void ssl_crypto_x509_cert_dup(CERT *new_cert, const CERT *cert) { - if (cert->verify_store != NULL) { + if (cert->verify_store != nullptr) { X509_STORE_up_ref(cert->verify_store); new_cert->verify_store = cert->verify_store; } } -static int ssl_crypto_x509_session_cache_objects(SSL_SESSION *sess) { +static bool ssl_crypto_x509_session_cache_objects(SSL_SESSION *sess) { bssl::UniquePtr chain, chain_without_leaf; if (sk_CRYPTO_BUFFER_num(sess->certs.get()) > 0) { chain.reset(sk_X509_new_null()); if (!chain) { OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE); - return 0; + return false; } if (sess->is_server) { // chain_without_leaf is only needed for server sessions. See @@ -294,7 +294,7 @@ static int ssl_crypto_x509_session_cache_objects(SSL_SESSION *sess) { chain_without_leaf.reset(sk_X509_new_null()); if (!chain_without_leaf) { OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE); - return 0; + return false; } } } @@ -304,18 +304,18 @@ static int ssl_crypto_x509_session_cache_objects(SSL_SESSION *sess) { UniquePtr x509(X509_parse_from_buffer(cert)); if (!x509) { OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR); - return 0; + return false; } if (leaf == nullptr) { leaf = UpRef(x509); } else if (chain_without_leaf && !PushToStack(chain_without_leaf.get(), UpRef(x509))) { OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE); - return 0; + return false; } if (!PushToStack(chain.get(), std::move(x509))) { OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE); - return 0; + return false; } } @@ -327,80 +327,76 @@ static int ssl_crypto_x509_session_cache_objects(SSL_SESSION *sess) { X509_free(sess->x509_peer); sess->x509_peer = leaf.release(); - return 1; + return true; } -static int ssl_crypto_x509_session_dup(SSL_SESSION *new_session, - const SSL_SESSION *session) { +static bool ssl_crypto_x509_session_dup(SSL_SESSION *new_session, + const SSL_SESSION *session) { new_session->x509_peer = UpRef(session->x509_peer).release(); if (session->x509_chain != nullptr) { new_session->x509_chain = X509_chain_up_ref(session->x509_chain); if (new_session->x509_chain == nullptr) { - return 0; + return false; } } if (session->x509_chain_without_leaf != nullptr) { new_session->x509_chain_without_leaf = X509_chain_up_ref(session->x509_chain_without_leaf); if (new_session->x509_chain_without_leaf == nullptr) { - return 0; + return false; } } - return 1; + return true; } static void ssl_crypto_x509_session_clear(SSL_SESSION *session) { X509_free(session->x509_peer); - session->x509_peer = NULL; + session->x509_peer = nullptr; sk_X509_pop_free(session->x509_chain, X509_free); - session->x509_chain = NULL; + session->x509_chain = nullptr; sk_X509_pop_free(session->x509_chain_without_leaf, X509_free); - session->x509_chain_without_leaf = NULL; + session->x509_chain_without_leaf = nullptr; } -static int ssl_crypto_x509_session_verify_cert_chain(SSL_SESSION *session, - SSL_HANDSHAKE *hs, - uint8_t *out_alert) { +static bool ssl_crypto_x509_session_verify_cert_chain(SSL_SESSION *session, + SSL_HANDSHAKE *hs, + uint8_t *out_alert) { *out_alert = SSL_AD_INTERNAL_ERROR; STACK_OF(X509) *const cert_chain = session->x509_chain; - if (cert_chain == NULL || sk_X509_num(cert_chain) == 0) { - return 0; + if (cert_chain == nullptr || sk_X509_num(cert_chain) == 0) { + return false; } SSL_CTX *ssl_ctx = hs->ssl->ctx.get(); X509_STORE *verify_store = ssl_ctx->cert_store; - if (hs->config->cert->verify_store != NULL) { + if (hs->config->cert->verify_store != nullptr) { verify_store = hs->config->cert->verify_store; } X509 *leaf = sk_X509_value(cert_chain, 0); ScopedX509_STORE_CTX ctx; - if (!X509_STORE_CTX_init(ctx.get(), verify_store, leaf, cert_chain)) { + if (!X509_STORE_CTX_init(ctx.get(), verify_store, leaf, cert_chain) || + !X509_STORE_CTX_set_ex_data( + ctx.get(), SSL_get_ex_data_X509_STORE_CTX_idx(), hs->ssl) || + // We need to inherit the verify parameters. These can be determined by + // the context: if its a server it will verify SSL client certificates or + // vice versa. + !X509_STORE_CTX_set_default( + ctx.get(), hs->ssl->server ? "ssl_client" : "ssl_server") || + // Anything non-default in "param" should overwrite anything in the ctx. + !X509_VERIFY_PARAM_set1(X509_STORE_CTX_get0_param(ctx.get()), + hs->config->param)) { OPENSSL_PUT_ERROR(SSL, ERR_R_X509_LIB); - return 0; + return false; } - if (!X509_STORE_CTX_set_ex_data( - ctx.get(), SSL_get_ex_data_X509_STORE_CTX_idx(), hs->ssl)) { - return 0; - } - - // We need to inherit the verify parameters. These can be determined by the - // context: if its a server it will verify SSL client certificates or vice - // versa. - X509_STORE_CTX_set_default(ctx.get(), - hs->ssl->server ? "ssl_client" : "ssl_server"); - - // Anything non-default in "param" should overwrite anything in the ctx. - X509_VERIFY_PARAM_set1(X509_STORE_CTX_get0_param(ctx.get()), - hs->config->param); if (hs->config->verify_callback) { X509_STORE_CTX_set_verify_cb(ctx.get(), hs->config->verify_callback); } int verify_ret; - if (ssl_ctx->app_verify_callback != NULL) { + if (ssl_ctx->app_verify_callback != nullptr) { verify_ret = ssl_ctx->app_verify_callback(ctx.get(), ssl_ctx->app_verify_arg); } else { @@ -412,59 +408,59 @@ static int ssl_crypto_x509_session_verify_cert_chain(SSL_SESSION *session, // If |SSL_VERIFY_NONE|, the error is non-fatal, but we keep the result. if (verify_ret <= 0 && hs->config->verify_mode != SSL_VERIFY_NONE) { *out_alert = SSL_alert_from_verify_result(ctx->error); - return 0; + return false; } ERR_clear_error(); - return 1; + return true; } static void ssl_crypto_x509_hs_flush_cached_ca_names(SSL_HANDSHAKE *hs) { sk_X509_NAME_pop_free(hs->cached_x509_ca_names, X509_NAME_free); - hs->cached_x509_ca_names = NULL; + hs->cached_x509_ca_names = nullptr; } -static int ssl_crypto_x509_ssl_new(SSL_HANDSHAKE *hs) { +static bool ssl_crypto_x509_ssl_new(SSL_HANDSHAKE *hs) { hs->config->param = X509_VERIFY_PARAM_new(); - if (hs->config->param == NULL) { - return 0; + if (hs->config->param == nullptr) { + return false; } X509_VERIFY_PARAM_inherit(hs->config->param, hs->ssl->ctx->param); - return 1; + return true; } static void ssl_crypto_x509_ssl_flush_cached_client_CA(SSL_CONFIG *cfg) { sk_X509_NAME_pop_free(cfg->cached_x509_client_CA, X509_NAME_free); - cfg->cached_x509_client_CA = NULL; + cfg->cached_x509_client_CA = nullptr; } static void ssl_crypto_x509_ssl_config_free(SSL_CONFIG *cfg) { sk_X509_NAME_pop_free(cfg->cached_x509_client_CA, X509_NAME_free); - cfg->cached_x509_client_CA = NULL; + cfg->cached_x509_client_CA = nullptr; X509_VERIFY_PARAM_free(cfg->param); } -static int ssl_crypto_x509_ssl_auto_chain_if_needed(SSL_HANDSHAKE *hs) { +static bool ssl_crypto_x509_ssl_auto_chain_if_needed(SSL_HANDSHAKE *hs) { // Only build a chain if there are no intermediates configured and the feature // isn't disabled. if ((hs->ssl->mode & SSL_MODE_NO_AUTO_CHAIN) || !ssl_has_certificate(hs) || hs->config->cert->chain == NULL || sk_CRYPTO_BUFFER_num(hs->config->cert->chain.get()) > 1) { - return 1; + return true; } UniquePtr leaf(X509_parse_from_buffer( sk_CRYPTO_BUFFER_value(hs->config->cert->chain.get(), 0))); if (!leaf) { OPENSSL_PUT_ERROR(SSL, ERR_R_X509_LIB); - return 0; + return false; } ScopedX509_STORE_CTX ctx; if (!X509_STORE_CTX_init(ctx.get(), hs->ssl->ctx->cert_store, leaf.get(), NULL)) { OPENSSL_PUT_ERROR(SSL, ERR_R_X509_LIB); - return 0; + return false; } // Attempt to build a chain, ignoring the result. @@ -475,23 +471,23 @@ static int ssl_crypto_x509_ssl_auto_chain_if_needed(SSL_HANDSHAKE *hs) { X509_free(sk_X509_shift(ctx->chain)); if (!ssl_cert_set_chain(hs->config->cert.get(), ctx->chain)) { - return 0; + return false; } ssl_crypto_x509_cert_flush_cached_chain(hs->config->cert.get()); - return 1; + return true; } static void ssl_crypto_x509_ssl_ctx_flush_cached_client_CA(SSL_CTX *ctx) { sk_X509_NAME_pop_free(ctx->cached_x509_client_CA, X509_NAME_free); - ctx->cached_x509_client_CA = NULL; + ctx->cached_x509_client_CA = nullptr; } -static int ssl_crypto_x509_ssl_ctx_new(SSL_CTX *ctx) { +static bool ssl_crypto_x509_ssl_ctx_new(SSL_CTX *ctx) { ctx->cert_store = X509_STORE_new(); ctx->param = X509_VERIFY_PARAM_new(); - return (ctx->cert_store != NULL && ctx->param != NULL); + return (ctx->cert_store != nullptr && ctx->param != nullptr); } static void ssl_crypto_x509_ssl_ctx_free(SSL_CTX *ctx) { diff --git a/third_party/boringssl/kit/src/ssl/t1_lib.cc b/third_party/boringssl/kit/src/ssl/t1_lib.cc index 5e65f819..33885563 100644 --- a/third_party/boringssl/kit/src/ssl/t1_lib.cc +++ b/third_party/boringssl/kit/src/ssl/t1_lib.cc @@ -199,10 +199,14 @@ static bool tls1_check_duplicate_extensions(const CBS *cbs) { return true; } -bool ssl_client_hello_init(SSL *ssl, SSL_CLIENT_HELLO *out, +static bool is_post_quantum_group(uint16_t id) { + return id == SSL_CURVE_CECPQ2 || id == SSL_CURVE_CECPQ2b; +} + +bool ssl_client_hello_init(const SSL *ssl, SSL_CLIENT_HELLO *out, const SSLMessage &msg) { OPENSSL_memset(out, 0, sizeof(*out)); - out->ssl = ssl; + out->ssl = const_cast(ssl); out->client_hello = CBS_data(&msg.body); out->client_hello_len = CBS_len(&msg.body); @@ -292,23 +296,10 @@ static const uint16_t kDefaultGroups[] = { SSL_CURVE_SECP384R1, }; -// TLS 1.3 servers will pick CECPQ2 if offered by a client, but it's not enabled -// by default for clients. -static const uint16_t kDefaultGroupsServer[] = { - // CECPQ2 is not yet enabled by default. - // SSL_CURVE_CECPQ2, - SSL_CURVE_X25519, - SSL_CURVE_SECP256R1, - SSL_CURVE_SECP384R1, -};; - Span tls1_get_grouplist(const SSL_HANDSHAKE *hs) { if (!hs->config->supported_group_list.empty()) { return hs->config->supported_group_list; } - if (hs->ssl->server) { - return Span(kDefaultGroupsServer); - } return Span(kDefaultGroups); } @@ -338,10 +329,10 @@ bool tls1_get_shared_group(SSL_HANDSHAKE *hs, uint16_t *out_group_id) { for (uint16_t pref_group : pref) { for (uint16_t supp_group : supp) { if (pref_group == supp_group && - // CECPQ2 doesn't fit in the u8-length-prefixed ECPoint field in TLS - // 1.2 and below. + // CECPQ2(b) doesn't fit in the u8-length-prefixed ECPoint field in + // TLS 1.2 and below. (ssl_protocol_version(ssl) >= TLS1_3_VERSION || - pref_group != SSL_CURVE_CECPQ2)) { + !is_post_quantum_group(pref_group))) { *out_group_id = pref_group; return true; } @@ -403,9 +394,9 @@ bool tls1_set_curves_list(Array *out_group_ids, const char *curves) { } bool tls1_check_group_id(const SSL_HANDSHAKE *hs, uint16_t group_id) { - if (group_id == SSL_CURVE_CECPQ2 && + if (is_post_quantum_group(group_id) && ssl_protocol_version(hs->ssl) < TLS1_3_VERSION) { - // CECPQ2 requires TLS 1.3. + // CECPQ2(b) requires TLS 1.3. return false; } @@ -1803,7 +1794,7 @@ static bool ext_ec_point_add_extension(SSL_HANDSHAKE *hs, CBB *out) { } static bool ext_ec_point_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) { - // The point format extension is unneccessary in TLS 1.3. + // The point format extension is unnecessary in TLS 1.3. if (hs->min_version >= TLS1_3_VERSION) { return true; } @@ -2070,20 +2061,46 @@ static bool ext_psk_key_exchange_modes_parse_clienthello(SSL_HANDSHAKE *hs, static bool ext_early_data_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) { SSL *const ssl = hs->ssl; - if (!ssl->enable_early_data || - // Session must be 0-RTT capable. - ssl->session == nullptr || - ssl_session_protocol_version(ssl->session.get()) < TLS1_3_VERSION || - ssl->session->ticket_max_early_data == 0 || - // The second ClientHello never offers early data. - hs->received_hello_retry_request || - // In case ALPN preferences changed since this session was established, - // avoid reporting a confusing value in |SSL_get0_alpn_selected|. - (!ssl->session->early_alpn.empty() && - !ssl_is_alpn_protocol_allowed(hs, ssl->session->early_alpn))) { + // The second ClientHello never offers early data, and we must have already + // filled in |early_data_reason| by this point. + if (hs->received_hello_retry_request) { + assert(ssl->s3->early_data_reason != ssl_early_data_unknown); return true; } + if (!ssl->enable_early_data) { + ssl->s3->early_data_reason = ssl_early_data_disabled; + return true; + } + + if (hs->max_version < TLS1_3_VERSION) { + // We discard inapplicable sessions, so this is redundant with the session + // checks below, but we check give a more useful reason. + ssl->s3->early_data_reason = ssl_early_data_protocol_version; + return true; + } + + if (ssl->session == nullptr) { + ssl->s3->early_data_reason = ssl_early_data_no_session_offered; + return true; + } + + if (ssl_session_protocol_version(ssl->session.get()) < TLS1_3_VERSION || + ssl->session->ticket_max_early_data == 0) { + ssl->s3->early_data_reason = ssl_early_data_unsupported_for_session; + return true; + } + + // In case ALPN preferences changed since this session was established, avoid + // reporting a confusing value in |SSL_get0_alpn_selected| and sending early + // data we know will be rejected. + if (!ssl->session->early_alpn.empty() && + !ssl_is_alpn_protocol_allowed(hs, ssl->session->early_alpn)) { + ssl->s3->early_data_reason = ssl_early_data_alpn_mismatch; + return true; + } + + // |early_data_reason| will be filled in later when the server responds. hs->early_data_offered = true; if (!CBB_add_u16(out, TLSEXT_TYPE_early_data) || @@ -2096,12 +2113,27 @@ static bool ext_early_data_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) { } static bool ext_early_data_parse_serverhello(SSL_HANDSHAKE *hs, - uint8_t *out_alert, CBS *contents) { + uint8_t *out_alert, + CBS *contents) { SSL *const ssl = hs->ssl; if (contents == NULL) { + if (hs->early_data_offered && !hs->received_hello_retry_request) { + ssl->s3->early_data_reason = ssl->s3->session_reused + ? ssl_early_data_peer_declined + : ssl_early_data_session_not_resumed; + } else { + // We already filled in |early_data_reason| when declining to offer 0-RTT + // or handling the implicit HelloRetryRequest reject. + assert(ssl->s3->early_data_reason != ssl_early_data_unknown); + } return true; } + // If we received an HRR, the second ClientHello never offers early data, so + // the extensions logic will automatically reject early data extensions as + // unsolicited. This covered by the ServerAcceptsEarlyDataOnHRR test. + assert(!hs->received_hello_retry_request); + if (CBS_len(contents) != 0) { *out_alert = SSL_AD_DECODE_ERROR; return false; @@ -2113,6 +2145,7 @@ static bool ext_early_data_parse_serverhello(SSL_HANDSHAKE *hs, return false; } + ssl->s3->early_data_reason = ssl_early_data_accepted; ssl->s3->early_data_accepted = true; return true; } @@ -2199,8 +2232,8 @@ static bool ext_key_share_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) { group_id = groups[0]; - if (group_id == SSL_CURVE_CECPQ2 && groups.size() >= 2) { - // CECPQ2 is not sent as the only initial key share. We'll include the + if (is_post_quantum_group(group_id) && groups.size() >= 2) { + // CECPQ2(b) is not sent as the only initial key share. We'll include the // 2nd preference group too to avoid round-trips. second_group_id = groups[1]; assert(second_group_id != group_id); @@ -2437,7 +2470,7 @@ static bool ext_supported_groups_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) { } for (uint16_t group : tls1_get_grouplist(hs)) { - if (group == SSL_CURVE_CECPQ2 && + if (is_post_quantum_group(group) && hs->max_version < TLS1_3_VERSION) { continue; } @@ -2715,6 +2748,36 @@ static bool ext_quic_transport_params_add_serverhello(SSL_HANDSHAKE *hs, return true; } +// Delegated credentials. +// +// https://tools.ietf.org/html/draft-ietf-tls-subcerts + +static bool ext_delegated_credential_add_clienthello(SSL_HANDSHAKE *hs, + CBB *out) { + return true; +} + +static bool ext_delegated_credential_parse_clienthello(SSL_HANDSHAKE *hs, + uint8_t *out_alert, + CBS *contents) { + assert(TLSEXT_TYPE_delegated_credential == 0xff02); + // TODO: Check that the extension is empty. + // + // As of draft-03, the client sends an empty extension in order indicate + // support for delegated credentials. This could change, however, since the + // spec is not yet finalized. This assertion is here to remind us to enforce + // this check once the extension ID is assigned. + + if (contents == nullptr || ssl_protocol_version(hs->ssl) < TLS1_3_VERSION) { + // Don't use delegated credentials unless we're negotiating TLS 1.3 or + // higher. + return true; + } + + hs->delegated_credential_requested = true; + return true; +} + // Certificate compression static bool cert_compression_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) { @@ -3003,6 +3066,14 @@ static const struct tls_extension kExtensions[] = { cert_compression_parse_clienthello, cert_compression_add_serverhello, }, + { + TLSEXT_TYPE_delegated_credential, + NULL, + ext_delegated_credential_add_clienthello, + forbid_parse_serverhello, + ext_delegated_credential_parse_clienthello, + dont_add_serverhello, + }, }; #define kNumExtensions (sizeof(kExtensions) / sizeof(struct tls_extension)) @@ -3036,6 +3107,9 @@ bool ssl_add_clienthello_tlsext(SSL_HANDSHAKE *hs, CBB *out, return false; } + // Note we may send multiple ClientHellos for DTLS HelloVerifyRequest and TLS + // 1.3 HelloRetryRequest. For the latter, the extensions may change, so it is + // important to reset this value. hs->extensions.sent = 0; for (size_t i = 0; i < kNumExtensions; i++) { @@ -3629,6 +3703,7 @@ bool tls1_get_legacy_signature_algorithm(uint16_t *out, const EVP_PKEY *pkey) { bool tls1_choose_signature_algorithm(SSL_HANDSHAKE *hs, uint16_t *out) { SSL *const ssl = hs->ssl; CERT *cert = hs->config->cert.get(); + DC *dc = cert->dc.get(); // Before TLS 1.2, the signature algorithm isn't negotiated as part of the // handshake. @@ -3641,19 +3716,13 @@ bool tls1_choose_signature_algorithm(SSL_HANDSHAKE *hs, uint16_t *out) { } Span sigalgs = kSignSignatureAlgorithms; - if (!cert->sigalgs.empty()) { + if (ssl_signing_with_dc(hs)) { + sigalgs = MakeConstSpan(&dc->expected_cert_verify_algorithm, 1); + } else if (!cert->sigalgs.empty()) { sigalgs = cert->sigalgs; } - Span peer_sigalgs = hs->peer_sigalgs; - if (peer_sigalgs.empty() && ssl_protocol_version(ssl) < TLS1_3_VERSION) { - // If the client didn't specify any signature_algorithms extension then - // we can assume that it supports SHA1. See - // http://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 - static const uint16_t kDefaultPeerAlgorithms[] = {SSL_SIGN_RSA_PKCS1_SHA1, - SSL_SIGN_ECDSA_SHA1}; - peer_sigalgs = kDefaultPeerAlgorithms; - } + Span peer_sigalgs = tls1_get_peer_verify_algorithms(hs); for (uint16_t sigalg : sigalgs) { // SSL_SIGN_RSA_PKCS1_MD5_SHA1 is an internal value and should never be @@ -3675,6 +3744,19 @@ bool tls1_choose_signature_algorithm(SSL_HANDSHAKE *hs, uint16_t *out) { return false; } +Span tls1_get_peer_verify_algorithms(const SSL_HANDSHAKE *hs) { + Span peer_sigalgs = hs->peer_sigalgs; + if (peer_sigalgs.empty() && ssl_protocol_version(hs->ssl) < TLS1_3_VERSION) { + // If the client didn't specify any signature_algorithms extension then + // we can assume that it supports SHA1. See + // http://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 + static const uint16_t kDefaultPeerAlgorithms[] = {SSL_SIGN_RSA_PKCS1_SHA1, + SSL_SIGN_ECDSA_SHA1}; + peer_sigalgs = kDefaultPeerAlgorithms; + } + return peer_sigalgs; +} + bool tls1_verify_channel_id(SSL_HANDSHAKE *hs, const SSLMessage &msg) { SSL *const ssl = hs->ssl; // A Channel ID handshake message is structured to contain multiple diff --git a/third_party/boringssl/kit/src/ssl/test/bssl_shim.cc b/third_party/boringssl/kit/src/ssl/test/bssl_shim.cc index 62db0767..89b4ba5a 100644 --- a/third_party/boringssl/kit/src/ssl/test/bssl_shim.cc +++ b/third_party/boringssl/kit/src/ssl/test/bssl_shim.cc @@ -279,23 +279,23 @@ static uint16_t GetProtocolVersion(const SSL *ssl) { // after a renegotiation, that authentication-related properties match |config|. static bool CheckAuthProperties(SSL *ssl, bool is_resume, const TestConfig *config) { - if (!config->expected_ocsp_response.empty()) { + if (!config->expect_ocsp_response.empty()) { const uint8_t *data; size_t len; SSL_get0_ocsp_response(ssl, &data, &len); - if (config->expected_ocsp_response.size() != len || - OPENSSL_memcmp(config->expected_ocsp_response.data(), data, len) != 0) { + if (config->expect_ocsp_response.size() != len || + OPENSSL_memcmp(config->expect_ocsp_response.data(), data, len) != 0) { fprintf(stderr, "OCSP response mismatch\n"); return false; } } - if (!config->expected_signed_cert_timestamps.empty()) { + if (!config->expect_signed_cert_timestamps.empty()) { const uint8_t *data; size_t len; SSL_get0_signed_cert_timestamp_list(ssl, &data, &len); - if (config->expected_signed_cert_timestamps.size() != len || - OPENSSL_memcmp(config->expected_signed_cert_timestamps.data(), data, + if (config->expect_signed_cert_timestamps.size() != len || + OPENSSL_memcmp(config->expect_signed_cert_timestamps.data(), data, len) != 0) { fprintf(stderr, "SCT list mismatch\n"); return false; @@ -389,6 +389,39 @@ static bool CheckAuthProperties(SSL *ssl, bool is_resume, return true; } +static const char *EarlyDataReasonToString(ssl_early_data_reason_t reason) { + switch (reason) { + case ssl_early_data_unknown: + return "unknown"; + case ssl_early_data_disabled: + return "disabled"; + case ssl_early_data_accepted: + return "accepted"; + case ssl_early_data_protocol_version: + return "protocol_version"; + case ssl_early_data_peer_declined: + return "peer_declined"; + case ssl_early_data_no_session_offered: + return "no_session_offered"; + case ssl_early_data_session_not_resumed: + return "session_not_resumed"; + case ssl_early_data_unsupported_for_session: + return "unsupported_for_session"; + case ssl_early_data_hello_retry_request: + return "hello_retry_request"; + case ssl_early_data_alpn_mismatch: + return "alpn_mismatch"; + case ssl_early_data_channel_id: + return "channel_id"; + case ssl_early_data_token_binding: + return "token_binding"; + case ssl_early_data_ticket_age_skew: + return "ticket_age_skew"; + } + + abort(); +} + // CheckHandshakeProperties checks, immediately after |ssl| completes its // initial handshake (or False Starts), whether all the properties are // consistent with the test configuration and invariants. @@ -459,23 +492,23 @@ static bool CheckHandshakeProperties(SSL *ssl, bool is_resume, return false; } - if (!config->expected_server_name.empty()) { + if (!config->expect_server_name.empty()) { const char *server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); if (server_name == nullptr || - server_name != config->expected_server_name) { + server_name != config->expect_server_name) { fprintf(stderr, "servername mismatch (got %s; want %s)\n", - server_name, config->expected_server_name.c_str()); + server_name, config->expect_server_name.c_str()); return false; } } - if (!config->expected_next_proto.empty()) { + if (!config->expect_next_proto.empty()) { const uint8_t *next_proto; unsigned next_proto_len; SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len); - if (next_proto_len != config->expected_next_proto.size() || - OPENSSL_memcmp(next_proto, config->expected_next_proto.data(), + if (next_proto_len != config->expect_next_proto.size() || + OPENSSL_memcmp(next_proto, config->expect_next_proto.data(), next_proto_len) != 0) { fprintf(stderr, "negotiated next proto mismatch\n"); return false; @@ -486,48 +519,48 @@ static bool CheckHandshakeProperties(SSL *ssl, bool is_resume, const uint8_t *alpn_proto; unsigned alpn_proto_len; SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len); - if (alpn_proto_len != config->expected_alpn.size() || - OPENSSL_memcmp(alpn_proto, config->expected_alpn.data(), + if (alpn_proto_len != config->expect_alpn.size() || + OPENSSL_memcmp(alpn_proto, config->expect_alpn.data(), alpn_proto_len) != 0) { fprintf(stderr, "negotiated alpn proto mismatch\n"); return false; } } - if (!config->expected_quic_transport_params.empty()) { + if (!config->expect_quic_transport_params.empty()) { const uint8_t *peer_params; size_t peer_params_len; SSL_get_peer_quic_transport_params(ssl, &peer_params, &peer_params_len); - if (peer_params_len != config->expected_quic_transport_params.size() || + if (peer_params_len != config->expect_quic_transport_params.size() || OPENSSL_memcmp(peer_params, - config->expected_quic_transport_params.data(), + config->expect_quic_transport_params.data(), peer_params_len) != 0) { fprintf(stderr, "QUIC transport params mismatch\n"); return false; } } - if (!config->expected_channel_id.empty()) { + if (!config->expect_channel_id.empty()) { uint8_t channel_id[64]; if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) { fprintf(stderr, "no channel id negotiated\n"); return false; } - if (config->expected_channel_id.size() != 64 || - OPENSSL_memcmp(config->expected_channel_id.data(), channel_id, 64) != + if (config->expect_channel_id.size() != 64 || + OPENSSL_memcmp(config->expect_channel_id.data(), channel_id, 64) != 0) { fprintf(stderr, "channel id mismatch\n"); return false; } } - if (config->expected_token_binding_param != -1) { + if (config->expect_token_binding_param != -1) { if (!SSL_is_token_binding_negotiated(ssl)) { fprintf(stderr, "no Token Binding negotiated\n"); return false; } if (SSL_get_negotiated_token_binding_param(ssl) != - static_cast(config->expected_token_binding_param)) { + static_cast(config->expect_token_binding_param)) { fprintf(stderr, "Token Binding param mismatch\n"); return false; } @@ -587,7 +620,8 @@ static bool CheckHandshakeProperties(SSL *ssl, bool is_resume, return false; } - if (is_resume && !SSL_in_early_data(ssl)) { + // The early data status is only applicable after the handshake is confirmed. + if (!SSL_in_early_data(ssl)) { if ((config->expect_accept_early_data && !SSL_early_data_accepted(ssl)) || (config->expect_reject_early_data && SSL_early_data_accepted(ssl))) { fprintf(stderr, @@ -595,6 +629,15 @@ static bool CheckHandshakeProperties(SSL *ssl, bool is_resume, SSL_early_data_accepted(ssl) ? "" : " not"); return false; } + + const char *early_data_reason = + EarlyDataReasonToString(SSL_get_early_data_reason(ssl)); + if (!config->expect_early_data_reason.empty() && + config->expect_early_data_reason != early_data_reason) { + fprintf(stderr, "Early data reason was \"%s\", expected \"%s\"\n", + early_data_reason, config->expect_early_data_reason.c_str()); + return false; + } } if (!config->psk.empty()) { @@ -701,6 +744,16 @@ static bool DoConnection(bssl::UniquePtr *out_session, return false; } + // Client pre- and post-0-RTT reject states are considered logically + // different connections with different test expections. Check that the test + // did not mistakenly configure reason expectations on the wrong one. + if (!config->expect_early_data_reason.empty()) { + fprintf(stderr, + "Test error: client reject -expect-early-data-reason flags " + "should be configured with -on-retry, not -on-resume.\n"); + return false; + } + // Reset the connection and try again at 1-RTT. SSL_reset_early_data_reject(ssl.get()); GetTestState(ssl.get())->cert_verified = false; diff --git a/third_party/boringssl/kit/src/ssl/test/fuzzer.h b/third_party/boringssl/kit/src/ssl/test/fuzzer.h index de058e52..f714d5d7 100644 --- a/third_party/boringssl/kit/src/ssl/test/fuzzer.h +++ b/third_party/boringssl/kit/src/ssl/test/fuzzer.h @@ -414,6 +414,13 @@ class TLSFuzzer { return false; } + static const int kCurves[] = {NID_CECPQ2, NID_X25519, NID_X9_62_prime256v1, + NID_secp384r1, NID_secp521r1}; + if (!SSL_CTX_set1_curves(ctx_.get(), kCurves, + OPENSSL_ARRAY_SIZE(kCurves))) { + return false; + } + SSL_CTX_set_early_data_enabled(ctx_.get(), 1); SSL_CTX_set_next_proto_select_cb(ctx_.get(), NPNSelectCallback, nullptr); diff --git a/third_party/boringssl/kit/src/ssl/test/handshake_util.cc b/third_party/boringssl/kit/src/ssl/test/handshake_util.cc index a36b41a8..afead7f8 100644 --- a/third_party/boringssl/kit/src/ssl/test/handshake_util.cc +++ b/third_party/boringssl/kit/src/ssl/test/handshake_util.cc @@ -413,8 +413,9 @@ static bool PrepareHandoff(SSL *ssl, SettingsWriter *writer, } ScopedCBB cbb; + SSL_CLIENT_HELLO hello; if (!CBB_init(cbb.get(), 512) || - !SSL_serialize_handoff(ssl, cbb.get()) || + !SSL_serialize_handoff(ssl, cbb.get(), &hello) || !writer->WriteHandoff({CBB_data(cbb.get()), CBB_len(cbb.get())}) || !SerializeContextState(ssl->ctx.get(), cbb.get()) || !GetTestState(ssl)->Serialize(cbb.get())) { diff --git a/third_party/boringssl/kit/src/ssl/test/runner/cipher_suites.go b/third_party/boringssl/kit/src/ssl/test/runner/cipher_suites.go index 3246f0b7..e827c524 100644 --- a/third_party/boringssl/kit/src/ssl/test/runner/cipher_suites.go +++ b/third_party/boringssl/kit/src/ssl/test/runner/cipher_suites.go @@ -33,7 +33,7 @@ type keyAgreement interface { // This method may not be called if the server doesn't send a // ServerKeyExchange message. - processServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg, *x509.Certificate, *serverKeyExchangeMsg) error + processServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg, crypto.PublicKey, *serverKeyExchangeMsg) error generateClientKeyExchange(*Config, *clientHelloMsg, *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) // peerSignatureAlgorithm returns the signature algorithm used by the diff --git a/third_party/boringssl/kit/src/ssl/test/runner/common.go b/third_party/boringssl/kit/src/ssl/test/runner/common.go index 86f5a2c0..1729289f 100644 --- a/third_party/boringssl/kit/src/ssl/test/runner/common.go +++ b/third_party/boringssl/kit/src/ssl/test/runner/common.go @@ -125,6 +125,7 @@ const ( extensionRenegotiationInfo uint16 = 0xff01 extensionQUICTransportParams uint16 = 0xffa5 // draft-ietf-quic-tls-13 extensionChannelID uint16 = 30032 // not IANA assigned + extensionDelegatedCredentials uint16 = 0xff02 // not IANA assigned ) // TLS signaling cipher suite values @@ -143,12 +144,13 @@ var tls13HelloRetryRequest = []uint8{ type CurveID uint16 const ( - CurveP224 CurveID = 21 - CurveP256 CurveID = 23 - CurveP384 CurveID = 24 - CurveP521 CurveID = 25 - CurveX25519 CurveID = 29 - CurveCECPQ2 CurveID = 16696 + CurveP224 CurveID = 21 + CurveP256 CurveID = 23 + CurveP384 CurveID = 24 + CurveP521 CurveID = 25 + CurveX25519 CurveID = 29 + CurveCECPQ2 CurveID = 16696 + CurveCECPQ2b CurveID = 65074 ) // TLS Elliptic Curve Point Formats @@ -1636,6 +1638,18 @@ type ProtocolBugs struct { // ExpectKeyShares, if not nil, lists (in order) the curves that a ClientHello // should have key shares for. ExpectedKeyShares []CurveID + + // ExpectDelegatedCredentials, if true, requires that the handshake present + // delegated credentials. + ExpectDelegatedCredentials bool + + // FailIfDelegatedCredentials, if true, causes a handshake failure if the + // server returns delegated credentials. + FailIfDelegatedCredentials bool + + // DisableDelegatedCredentials, if true, disables client support for delegated + // credentials. + DisableDelegatedCredentials bool } func (c *Config) serverInit() { @@ -1715,7 +1729,7 @@ func (c *Config) maxVersion(isDTLS bool) uint16 { return ret } -var defaultCurvePreferences = []CurveID{CurveCECPQ2, CurveX25519, CurveP256, CurveP384, CurveP521} +var defaultCurvePreferences = []CurveID{CurveCECPQ2b, CurveCECPQ2, CurveX25519, CurveP256, CurveP384, CurveP521} func (c *Config) curvePreferences() []CurveID { if c == nil || len(c.CurvePreferences) == 0 { diff --git a/third_party/boringssl/kit/src/ssl/test/runner/ecdsa_p224_key.pem b/third_party/boringssl/kit/src/ssl/test/runner/ecdsa_p224_key.pem index cfe411b4..d62594bb 100644 --- a/third_party/boringssl/kit/src/ssl/test/runner/ecdsa_p224_key.pem +++ b/third_party/boringssl/kit/src/ssl/test/runner/ecdsa_p224_key.pem @@ -1,5 +1,5 @@ ------BEGIN EC PRIVATE KEY----- -MGgCAQEEHGi+rNLi+gHJqmRRtdlLBOw1WYv7H/VnlYGAZ0+gBwYFK4EEACGhPAM6 -AATp26Xp0vT4LKigWIorhX4Rg1g9sxmgtPFFyNGCvDd1vpDMEC+INLEoANNW7JGZ -pULvgx/pugEcOQ== ------END EC PRIVATE KEY----- +-----BEGIN PRIVATE KEY----- +MHgCAQAwEAYHKoZIzj0CAQYFK4EEACEEYTBfAgEBBBxovqzS4voByapkUbXZSwTs +NVmL+x/1Z5WBgGdPoTwDOgAE6dul6dL0+CyooFiKK4V+EYNYPbMZoLTxRcjRgrw3 +db6QzBAviDSxKADTVuyRmaVC74Mf6boBHDk= +-----END PRIVATE KEY----- diff --git a/third_party/boringssl/kit/src/ssl/test/runner/fuzzer_mode.json b/third_party/boringssl/kit/src/ssl/test/runner/fuzzer_mode.json index 1a154c2c..836b7ba8 100644 --- a/third_party/boringssl/kit/src/ssl/test/runner/fuzzer_mode.json +++ b/third_party/boringssl/kit/src/ssl/test/runner/fuzzer_mode.json @@ -30,6 +30,7 @@ "Resume-Server-DeclineCrossVersion*": "Fuzzer mode does not encrypt tickets.", "TicketCallback-SingleCall-*": "Fuzzer mode does not encrypt tickets.", "CorruptTicket-*": "Fuzzer mode does not encrypt tickets.", + "*RejectTicket-Server-*": "Fuzzer mode does not encrypt tickets.", "ShimTicketRewritable*": "Fuzzer mode does not encrypt tickets.", "Resume-Server-*Binder*": "Fuzzer mode does not check binders.", @@ -46,6 +47,7 @@ "*-EarlyData-RejectUnfinishedWrite-Client-*": "Trial decryption does not work with the NULL cipher.", "EarlyData-Reject*-Client-*": "Trial decryption does not work with the NULL cipher.", "CustomExtensions-Server-EarlyDataOffered": "Trial decryption does not work with the NULL cipher.", + "*-TicketAgeSkew-*-Reject": "Trial decryption does not work with the NULL cipher.", "Renegotiate-Client-BadExt*": "Fuzzer mode does not check renegotiation_info.", diff --git a/third_party/boringssl/kit/src/ssl/test/runner/handshake_client.go b/third_party/boringssl/kit/src/ssl/test/runner/handshake_client.go index 80035143..45dc75d1 100644 --- a/third_party/boringssl/kit/src/ssl/test/runner/handshake_client.go +++ b/third_party/boringssl/kit/src/ssl/test/runner/handshake_client.go @@ -32,6 +32,8 @@ type clientHandshakeState struct { masterSecret []byte session *ClientSessionState finishedBytes []byte + peerPublicKey crypto.PublicKey + skxAlgo signatureAlgorithm } func mapClientHelloVersion(vers uint16, isDTLS bool) uint16 { @@ -126,6 +128,7 @@ func (c *Conn) clientHandshake() error { pskBinderFirst: c.config.Bugs.PSKBinderFirst, omitExtensions: c.config.Bugs.OmitExtensions, emptyExtensions: c.config.Bugs.EmptyExtensions, + delegatedCredentials: !c.config.Bugs.DisableDelegatedCredentials, } if maxVersion >= VersionTLS13 { @@ -978,7 +981,6 @@ func (hs *clientHandshakeState) doTLS13Handshake() error { if err := hs.verifyCertificates(certMsg); err != nil { return err } - leaf := c.peerCertificates[0] c.ocspResponse = certMsg.certificates[0].ocspResponse c.sctList = certMsg.certificates[0].sctList @@ -994,7 +996,7 @@ func (hs *clientHandshakeState) doTLS13Handshake() error { c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13) - err = verifyMessage(c.vers, getCertificatePublicKey(leaf), c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature) + err = verifyMessage(c.vers, hs.peerPublicKey, c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature) if err != nil { return err } @@ -1233,7 +1235,7 @@ func (hs *clientHandshakeState) doFullHandshake() error { skx, ok := msg.(*serverKeyExchangeMsg) if ok { hs.writeServerHash(skx.marshal()) - err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx) + err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, hs.peerPublicKey, skx) if err != nil { c.sendAlert(alertUnexpectedMessage) return err @@ -1377,6 +1379,23 @@ func (hs *clientHandshakeState) doFullHandshake() error { return nil } +// delegatedCredentialSignedMessage returns the bytes that are signed in order +// to authenticate a delegated credential. +func delegatedCredentialSignedMessage(credBytes []byte, algorithm signatureAlgorithm, leafDER []byte) []byte { + // https://tools.ietf.org/html/draft-ietf-tls-subcerts-03#section-3 + ret := make([]byte, 64, 128) + for i := range ret { + ret[i] = 0x20 + } + + ret = append(ret, []byte("TLS, server delegated credentials\x00")...) + ret = append(ret, leafDER...) + ret = append(ret, byte(algorithm>>8), byte(algorithm)) + ret = append(ret, credBytes...) + + return ret +} + func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error { c := hs.c @@ -1385,6 +1404,7 @@ func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) erro return errors.New("tls: no certificates sent") } + var dc *delegatedCredential certs := make([]*x509.Certificate, len(certMsg.certificates)) for i, certEntry := range certMsg.certificates { cert, err := x509.ParseCertificate(certEntry.data) @@ -1393,6 +1413,22 @@ func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) erro return errors.New("tls: failed to parse certificate from server: " + err.Error()) } certs[i] = cert + + if certEntry.delegatedCredential != nil { + if c.config.Bugs.FailIfDelegatedCredentials { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: unexpected delegated credential") + } + if i != 0 { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: non-leaf certificate has a delegated credential") + } + if c.config.Bugs.DisableDelegatedCredentials { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: server sent delegated credential without it being requested") + } + dc = certEntry.delegatedCredential + } } if !c.config.InsecureSkipVerify { @@ -1417,16 +1453,45 @@ func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) erro } } - publicKey := getCertificatePublicKey(certs[0]) - switch publicKey.(type) { + leafPublicKey := getCertificatePublicKey(certs[0]) + switch leafPublicKey.(type) { case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey: break default: c.sendAlert(alertUnsupportedCertificate) - return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", publicKey) + return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", leafPublicKey) } c.peerCertificates = certs + + if dc != nil { + // Note that this doesn't check a) the delegated credential temporal + // validity nor b) that the certificate has the special OID asserted. + hs.skxAlgo = dc.expectedCertVerifyAlgo + + var err error + if hs.peerPublicKey, err = x509.ParsePKIXPublicKey(dc.pkixPublicKey); err != nil { + c.sendAlert(alertBadCertificate) + return errors.New("tls: failed to parse public key from delegated credential: " + err.Error()) + } + + verifier, err := getSigner(c.vers, hs.peerPublicKey, c.config, dc.algorithm, true) + if err != nil { + c.sendAlert(alertBadCertificate) + return errors.New("tls: failed to get verifier for delegated credential: " + err.Error()) + } + + if err := verifier.verifyMessage(leafPublicKey, delegatedCredentialSignedMessage(dc.signedBytes, dc.algorithm, certs[0].Raw), dc.signature); err != nil { + c.sendAlert(alertBadCertificate) + return errors.New("tls: failed to verify delegated credential: " + err.Error()) + } + } else if c.config.Bugs.ExpectDelegatedCredentials { + c.sendAlert(alertInternalError) + return errors.New("tls: delegated credentials missing") + } else { + hs.peerPublicKey = leafPublicKey + } + return nil } diff --git a/third_party/boringssl/kit/src/ssl/test/runner/handshake_messages.go b/third_party/boringssl/kit/src/ssl/test/runner/handshake_messages.go index 823c6c8f..f12ca1ac 100644 --- a/third_party/boringssl/kit/src/ssl/test/runner/handshake_messages.go +++ b/third_party/boringssl/kit/src/ssl/test/runner/handshake_messages.go @@ -297,6 +297,7 @@ type clientHelloMsg struct { emptyExtensions bool pad int compressedCertAlgs []uint16 + delegatedCredentials bool } func (m *clientHelloMsg) equal(i interface{}) bool { @@ -350,7 +351,8 @@ func (m *clientHelloMsg) equal(i interface{}) bool { m.omitExtensions == m1.omitExtensions && m.emptyExtensions == m1.emptyExtensions && m.pad == m1.pad && - eqUint16s(m.compressedCertAlgs, m1.compressedCertAlgs) + eqUint16s(m.compressedCertAlgs, m1.compressedCertAlgs) && + m.delegatedCredentials == m1.delegatedCredentials } func (m *clientHelloMsg) marshalKeyShares(bb *byteBuilder) { @@ -592,6 +594,10 @@ func (m *clientHelloMsg) marshal() []byte { algIDs.addU16(v) } } + if m.delegatedCredentials { + extensions.addU16(extensionDelegatedCredentials) + extensions.addU16(0) // Length is always 0 + } // The PSK extension must be last. See https://tools.ietf.org/html/rfc8446#section-4.2.11 if len(m.pskIdentities) > 0 && !m.pskBinderFirst { extensions.addU16(extensionPreSharedKey) @@ -717,6 +723,7 @@ func (m *clientHelloMsg) unmarshal(data []byte) bool { m.alpnProtocols = nil m.extendedMasterSecret = false m.customExtension = "" + m.delegatedCredentials = false if len(reader) == 0 { // ClientHello is optionally followed by extension data @@ -947,6 +954,11 @@ func (m *clientHelloMsg) unmarshal(data []byte) bool { return false } } + case extensionDelegatedCredentials: + if len(body) != 0 { + return false + } + m.delegatedCredentials = true } if isGREASEValue(extension) { @@ -1602,6 +1614,17 @@ type certificateEntry struct { sctList []byte duplicateExtensions bool extraExtension []byte + delegatedCredential *delegatedCredential +} + +type delegatedCredential struct { + // https://tools.ietf.org/html/draft-ietf-tls-subcerts-03#section-3 + signedBytes []byte + lifetimeSecs uint32 + expectedCertVerifyAlgo signatureAlgorithm + pkixPublicKey []byte + algorithm signatureAlgorithm + signature []byte } type certificateMsg struct { @@ -1700,6 +1723,29 @@ func (m *certificateMsg) unmarshal(data []byte) bool { } case extensionSignedCertificateTimestamp: cert.sctList = []byte(body) + case extensionDelegatedCredentials: + // https://tools.ietf.org/html/draft-ietf-tls-subcerts-03#section-3 + if cert.delegatedCredential != nil { + return false + } + + dc := new(delegatedCredential) + origBody := body + var expectedCertVerifyAlgo, algorithm uint16 + + if !body.readU32(&dc.lifetimeSecs) || + !body.readU16(&expectedCertVerifyAlgo) || + !body.readU24LengthPrefixedBytes(&dc.pkixPublicKey) || + !body.readU16(&algorithm) || + !body.readU16LengthPrefixedBytes(&dc.signature) || + len(body) != 0 { + return false + } + + dc.expectedCertVerifyAlgo = signatureAlgorithm(expectedCertVerifyAlgo) + dc.algorithm = signatureAlgorithm(algorithm) + dc.signedBytes = []byte(origBody)[:4+2+3+len(dc.pkixPublicKey)] + cert.delegatedCredential = dc default: return false } diff --git a/third_party/boringssl/kit/src/ssl/test/runner/handshake_server.go b/third_party/boringssl/kit/src/ssl/test/runner/handshake_server.go index 5486342a..2dc70326 100644 --- a/third_party/boringssl/kit/src/ssl/test/runner/handshake_server.go +++ b/third_party/boringssl/kit/src/ssl/test/runner/handshake_server.go @@ -210,8 +210,8 @@ func (hs *serverHandshakeState) readClientHello() error { if config.Bugs.FailIfCECPQ2Offered { for _, offeredCurve := range hs.clientHello.supportedCurves { - if offeredCurve == CurveCECPQ2 { - return errors.New("tls: CECPQ2 was offered") + if isPqGroup(offeredCurve) { + return errors.New("tls: CECPQ2 or CECPQ2b was offered") } } } @@ -881,10 +881,10 @@ ResendHelloRetryRequest: data: certData, } if i == 0 { - if hs.clientHello.ocspStapling { + if hs.clientHello.ocspStapling && !c.config.Bugs.NoOCSPStapling { cert.ocspResponse = hs.cert.OCSPStaple } - if hs.clientHello.sctListSupported { + if hs.clientHello.sctListSupported && !c.config.Bugs.NoSignedCertificateTimestamps { cert.sctList = hs.cert.SignedCertificateTimestampList } cert.duplicateExtensions = config.Bugs.SendDuplicateCertExtensions @@ -1232,8 +1232,8 @@ func (hs *serverHandshakeState) processClientHello() (isResume bool, err error) preferredCurves := config.curvePreferences() Curves: for _, curve := range hs.clientHello.supportedCurves { - if curve == CurveCECPQ2 && c.vers < VersionTLS13 { - // CECPQ2 is TLS 1.3-only. + if isPqGroup(curve) && c.vers < VersionTLS13 { + // CECPQ2 and CECPQ2b is TLS 1.3-only. continue } @@ -1577,11 +1577,11 @@ func (hs *serverHandshakeState) doFullHandshake() error { c := hs.c isPSK := hs.suite.flags&suitePSK != 0 - if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 { + if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 && !c.config.Bugs.NoOCSPStapling { hs.hello.extensions.ocspStapling = true } - if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 { + if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 && !c.config.Bugs.NoSignedCertificateTimestamps { hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList } diff --git a/third_party/boringssl/kit/src/ssl/test/runner/key_agreement.go b/third_party/boringssl/kit/src/ssl/test/runner/key_agreement.go index f40552d9..0d6405fa 100644 --- a/third_party/boringssl/kit/src/ssl/test/runner/key_agreement.go +++ b/third_party/boringssl/kit/src/ssl/test/runner/key_agreement.go @@ -5,6 +5,7 @@ package runner import ( + "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rsa" @@ -18,6 +19,7 @@ import ( "boringssl.googlesource.com/boringssl/ssl/test/runner/curve25519" "boringssl.googlesource.com/boringssl/ssl/test/runner/ed25519" "boringssl.googlesource.com/boringssl/ssl/test/runner/hrss" + "boringssl.googlesource.com/boringssl/ssl/test/runner/sike" ) type keyType int @@ -133,7 +135,7 @@ func (ka *rsaKeyAgreement) processClientKeyExchange(config *Config, cert *Certif return preMasterSecret, nil } -func (ka *rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error { +func (ka *rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, key crypto.PublicKey, skx *serverKeyExchangeMsg) error { return errors.New("tls: unexpected ServerKeyExchange") } @@ -432,6 +434,98 @@ func (e *cecpq2Curve) finish(peerKey []byte) (preMasterSecret []byte, err error) return preMasterSecret, nil } +// cecpq2BCurve implements CECPQ2b, which is SIKEp503 combined with X25519. +type cecpq2BCurve struct { + // Both public key and shared secret size + x25519PrivateKey [32]byte + sikePrivateKey *sike.PrivateKey +} + +func (e *cecpq2BCurve) offer(rand io.Reader) (publicKey []byte, err error) { + if _, err = io.ReadFull(rand, e.x25519PrivateKey[:]); err != nil { + return nil, err + } + + var x25519Public [32]byte + curve25519.ScalarBaseMult(&x25519Public, &e.x25519PrivateKey) + + e.sikePrivateKey = sike.NewPrivateKey(sike.KeyVariant_SIKE) + if err = e.sikePrivateKey.Generate(rand); err != nil { + return nil, err + } + + sikePublic := e.sikePrivateKey.GeneratePublicKey().Export() + var ret []byte + ret = append(ret, x25519Public[:]...) + ret = append(ret, sikePublic...) + return ret, nil +} + +func (e *cecpq2BCurve) accept(rand io.Reader, peerKey []byte) (publicKey []byte, preMasterSecret []byte, err error) { + if len(peerKey) != 32+sike.Params.PublicKeySize { + return nil, nil, errors.New("tls: bad length CECPQ2b offer") + } + + if _, err = io.ReadFull(rand, e.x25519PrivateKey[:]); err != nil { + return nil, nil, err + } + + var x25519Shared, x25519PeerKey, x25519Public [32]byte + copy(x25519PeerKey[:], peerKey) + curve25519.ScalarBaseMult(&x25519Public, &e.x25519PrivateKey) + curve25519.ScalarMult(&x25519Shared, &e.x25519PrivateKey, &x25519PeerKey) + + // Per RFC 7748, reject the all-zero value in constant time. + var zeros [32]byte + if subtle.ConstantTimeCompare(zeros[:], x25519Shared[:]) == 1 { + return nil, nil, errors.New("tls: X25519 value with wrong order") + } + + var sikePubKey = sike.NewPublicKey(sike.KeyVariant_SIKE) + if err = sikePubKey.Import(peerKey[32:]); err != nil { + // should never happen as size was already checked + return nil, nil, errors.New("tls: implementation error") + } + sikeCiphertext, sikeShared, err := sike.Encapsulate(rand, sikePubKey) + if err != nil { + return nil, nil, err + } + + publicKey = append(publicKey, x25519Public[:]...) + publicKey = append(publicKey, sikeCiphertext...) + preMasterSecret = append(preMasterSecret, x25519Shared[:]...) + preMasterSecret = append(preMasterSecret, sikeShared...) + + return publicKey, preMasterSecret, nil +} + +func (e *cecpq2BCurve) finish(peerKey []byte) (preMasterSecret []byte, err error) { + if len(peerKey) != 32+(sike.Params.PublicKeySize+sike.Params.MsgLen) { + return nil, errors.New("tls: bad length CECPQ2b reply") + } + + var x25519Shared, x25519PeerKey [32]byte + copy(x25519PeerKey[:], peerKey) + curve25519.ScalarMult(&x25519Shared, &e.x25519PrivateKey, &x25519PeerKey) + + // Per RFC 7748, reject the all-zero value in constant time. + var zeros [32]byte + if subtle.ConstantTimeCompare(zeros[:], x25519Shared[:]) == 1 { + return nil, errors.New("tls: X25519 value with wrong order") + } + + var sikePubKey = e.sikePrivateKey.GeneratePublicKey() + sikeShared, err := sike.Decapsulate(e.sikePrivateKey, sikePubKey, peerKey[32:]) + if err != nil { + return nil, errors.New("tls: invalid SIKE ciphertext") + } + + preMasterSecret = append(preMasterSecret, x25519Shared[:]...) + preMasterSecret = append(preMasterSecret, sikeShared...) + + return preMasterSecret, nil +} + func curveForCurveID(id CurveID, config *Config) (ecdhCurve, bool) { switch id { case CurveP224: @@ -446,6 +540,8 @@ func curveForCurveID(id CurveID, config *Config) (ecdhCurve, bool) { return &x25519ECDHCurve{setHighBit: config.Bugs.SetX25519HighBit}, true case CurveCECPQ2: return &cecpq2Curve{}, true + case CurveCECPQ2b: + return &cecpq2BCurve{}, true default: return nil, false } @@ -456,7 +552,7 @@ func curveForCurveID(id CurveID, config *Config) (ecdhCurve, bool) { // to authenticate the ServerKeyExchange parameters. type keyAgreementAuthentication interface { signParameters(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, params []byte) (*serverKeyExchangeMsg, error) - verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, params []byte, sig []byte) error + verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, key crypto.PublicKey, params []byte, sig []byte) error } // nilKeyAgreementAuthentication does not authenticate the key @@ -469,7 +565,7 @@ func (ka *nilKeyAgreementAuthentication) signParameters(config *Config, cert *Ce return skx, nil } -func (ka *nilKeyAgreementAuthentication) verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, params []byte, sig []byte) error { +func (ka *nilKeyAgreementAuthentication) verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, key crypto.PublicKey, params []byte, sig []byte) error { return nil } @@ -529,9 +625,8 @@ func (ka *signedKeyAgreement) signParameters(config *Config, cert *Certificate, return skx, nil } -func (ka *signedKeyAgreement) verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, params []byte, sig []byte) error { +func (ka *signedKeyAgreement) verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, publicKey crypto.PublicKey, params []byte, sig []byte) error { // The peer's key must match the cipher type. - publicKey := getCertificatePublicKey(cert) switch ka.keyType { case keyTypeECDSA: _, edsaOk := publicKey.(*ecdsa.PublicKey) @@ -594,8 +689,8 @@ func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Cer NextCandidate: for _, candidate := range preferredCurves { - if candidate == CurveCECPQ2 && version < VersionTLS13 { - // CECPQ2 is TLS 1.3-only. + if isPqGroup(candidate) && version < VersionTLS13 { + // CECPQ2 and CECPQ2b is TLS 1.3-only. continue } @@ -646,7 +741,7 @@ func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Cert return ka.curve.finish(ckx.ciphertext[1:]) } -func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error { +func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, key crypto.PublicKey, skx *serverKeyExchangeMsg) error { if len(skx.key) < 4 { return errServerKeyExchange } @@ -671,7 +766,7 @@ func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHell // Check the signature. serverECDHParams := skx.key[:4+publicLen] sig := skx.key[4+publicLen:] - return ka.auth.verifyParameters(config, clientHello, serverHello, cert, serverECDHParams, sig) + return ka.auth.verifyParameters(config, clientHello, serverHello, key, serverECDHParams, sig) } func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) { @@ -722,7 +817,7 @@ func (ka *nilKeyAgreement) processClientKeyExchange(config *Config, cert *Certif return nil, nil } -func (ka *nilKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error { +func (ka *nilKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, key crypto.PublicKey, skx *serverKeyExchangeMsg) error { if len(skx.key) != 0 { return errServerKeyExchange } @@ -820,7 +915,7 @@ func (ka *pskKeyAgreement) processClientKeyExchange(config *Config, cert *Certif return makePSKPremaster(otherSecret, config.PreSharedKey), nil } -func (ka *pskKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error { +func (ka *pskKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, key crypto.PublicKey, skx *serverKeyExchangeMsg) error { if len(skx.key) < 2 { return errServerKeyExchange } @@ -833,7 +928,7 @@ func (ka *pskKeyAgreement) processServerKeyExchange(config *Config, clientHello // Process the remainder of the ServerKeyExchange. newSkx := new(serverKeyExchangeMsg) newSkx.key = skx.key[2+identityLen:] - return ka.base.processServerKeyExchange(config, clientHello, serverHello, cert, newSkx) + return ka.base.processServerKeyExchange(config, clientHello, serverHello, key, newSkx) } func (ka *pskKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) { diff --git a/third_party/boringssl/kit/src/ssl/test/runner/runner.go b/third_party/boringssl/kit/src/ssl/test/runner/runner.go index e0f75c37..7dd0defa 100644 --- a/third_party/boringssl/kit/src/ssl/test/runner/runner.go +++ b/third_party/boringssl/kit/src/ssl/test/runner/runner.go @@ -16,9 +16,11 @@ package runner import ( "bytes" + "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" + "crypto/rsa" "crypto/x509" "crypto/x509/pkix" "encoding/base64" @@ -246,6 +248,143 @@ func initCertificates() { garbageCertificate.PrivateKey = rsaCertificate.PrivateKey } +// delegatedCredentialConfig specifies the shape of a delegated credential, not +// including the keys themselves. +type delegatedCredentialConfig struct { + // lifetime is the amount of time, from the notBefore of the parent + // certificate, that the delegated credential is valid for. If zero, then 24 + // hours is assumed. + lifetime time.Duration + // expectedAlgo is the signature scheme that should be used with this + // delegated credential. If zero, ECDSA with P-256 is assumed. + expectedAlgo signatureAlgorithm + // tlsVersion is the version of TLS that should be used with this delegated + // credential. If zero, TLS 1.3 is assumed. + tlsVersion uint16 + // algo is the signature algorithm that the delegated credential itself is + // signed with. Cannot be zero. + algo signatureAlgorithm +} + +func loadRSAPrivateKey(filename string) (priv *rsa.PrivateKey, privPKCS8 []byte, err error) { + pemPath := path.Join(*resourceDir, filename) + pemBytes, err := ioutil.ReadFile(pemPath) + if err != nil { + return nil, nil, err + } + + block, _ := pem.Decode(pemBytes) + if block == nil { + return nil, nil, fmt.Errorf("no PEM block found in %q", pemPath) + } + privPKCS8 = block.Bytes + + parsed, err := x509.ParsePKCS8PrivateKey(privPKCS8) + if err != nil { + return nil, nil, fmt.Errorf("failed to parse PKCS#8 key from %q", pemPath) + } + + priv, ok := parsed.(*rsa.PrivateKey) + if !ok { + return nil, nil, fmt.Errorf("found %T in %q rather than an RSA private key", parsed, pemPath) + } + + return priv, privPKCS8, nil +} + +func createDelegatedCredential(config delegatedCredentialConfig, parentDER []byte, parentPriv crypto.PrivateKey) (dc, privPKCS8 []uint8, err error) { + expectedAlgo := config.expectedAlgo + if expectedAlgo == signatureAlgorithm(0) { + expectedAlgo = signatureECDSAWithP256AndSHA256 + } + + var pub crypto.PublicKey + + switch expectedAlgo { + case signatureRSAPKCS1WithMD5, signatureRSAPKCS1WithSHA1, signatureRSAPKCS1WithSHA256, signatureRSAPKCS1WithSHA384, signatureRSAPKCS1WithSHA512, signatureRSAPSSWithSHA256, signatureRSAPSSWithSHA384, signatureRSAPSSWithSHA512: + // RSA keys are expensive to generate so load from disk instead. + var priv *rsa.PrivateKey + if priv, privPKCS8, err = loadRSAPrivateKey(rsaKeyFile); err != nil { + return nil, nil, err + } + + pub = &priv.PublicKey + + case signatureECDSAWithSHA1, signatureECDSAWithP256AndSHA256, signatureECDSAWithP384AndSHA384, signatureECDSAWithP521AndSHA512: + var curve elliptic.Curve + switch expectedAlgo { + case signatureECDSAWithSHA1, signatureECDSAWithP256AndSHA256: + curve = elliptic.P256() + case signatureECDSAWithP384AndSHA384: + curve = elliptic.P384() + case signatureECDSAWithP521AndSHA512: + curve = elliptic.P521() + default: + panic("internal error") + } + + priv, err := ecdsa.GenerateKey(curve, rand.Reader) + if err != nil { + return nil, nil, err + } + + if privPKCS8, err = x509.MarshalPKCS8PrivateKey(priv); err != nil { + return nil, nil, err + } + + pub = &priv.PublicKey + + default: + return nil, nil, fmt.Errorf("unsupported expected signature algorithm: %x", expectedAlgo) + } + + lifetime := config.lifetime + if lifetime == 0 { + lifetime = 24 * time.Hour + } + lifetimeSecs := int64(lifetime.Seconds()) + if lifetimeSecs > 1<<32 { + return nil, nil, fmt.Errorf("lifetime %s is too long to be expressed", lifetime) + } + tlsVersion := config.tlsVersion + if tlsVersion == 0 { + tlsVersion = VersionTLS13 + } + + if tlsVersion < VersionTLS13 { + return nil, nil, fmt.Errorf("delegated credentials require TLS 1.3") + } + + // https://tools.ietf.org/html/draft-ietf-tls-subcerts-03#section-3 + dc = append(dc, byte(lifetimeSecs>>24), byte(lifetimeSecs>>16), byte(lifetimeSecs>>8), byte(lifetimeSecs)) + dc = append(dc, byte(expectedAlgo>>8), byte(expectedAlgo)) + + pubBytes, err := x509.MarshalPKIXPublicKey(pub) + if err != nil { + return nil, nil, err + } + + dc = append(dc, byte(len(pubBytes)>>16), byte(len(pubBytes)>>8), byte(len(pubBytes))) + dc = append(dc, pubBytes...) + + var dummyConfig Config + parentSigner, err := getSigner(tlsVersion, parentPriv, &dummyConfig, config.algo, false /* not for verification */) + if err != nil { + return nil, nil, err + } + + parentSignature, err := parentSigner.signMessage(parentPriv, &dummyConfig, delegatedCredentialSignedMessage(dc, config.algo, parentDER)) + if err != nil { + return nil, nil, err + } + + dc = append(dc, byte(config.algo>>8), byte(config.algo)) + dc = append(dc, byte(len(parentSignature)>>8), byte(len(parentSignature))) + dc = append(dc, parentSignature...) + + return dc, privPKCS8, nil +} + func getRunnerCertificate(t testCert) Certificate { for _, cert := range testCerts { if cert.id == t { @@ -4327,6 +4466,8 @@ func addStateMachineCoverageTests(config stateMachineTestConfig) { }, resumeSession: true, resumeRenewedSession: true, + // 0-RTT being disabled overrides all other 0-RTT reasons. + flags: []string{"-expect-early-data-reason", "disabled"}, }) tests = append(tests, testCase{ @@ -4338,9 +4479,13 @@ func addStateMachineCoverageTests(config stateMachineTestConfig) { }, resumeSession: true, resumeRenewedSession: true, - // TLS 1.3 uses tickets, so the session should not be - // cached statefully. - flags: []string{"-expect-no-session-id"}, + flags: []string{ + // TLS 1.3 uses tickets, so the session should not be + // cached statefully. + "-expect-no-session-id", + // 0-RTT being disabled overrides all other 0-RTT reasons. + "-expect-early-data-reason", "disabled", + }, }) tests = append(tests, testCase{ @@ -4393,7 +4538,7 @@ func addStateMachineCoverageTests(config stateMachineTestConfig) { flags: []string{ "-enable-early-data", "-expect-ticket-supports-early-data", - "-expect-accept-early-data", + "-on-resume-expect-accept-early-data", "-on-resume-shim-writes-first", }, }) @@ -4422,7 +4567,7 @@ func addStateMachineCoverageTests(config stateMachineTestConfig) { flags: []string{ "-enable-early-data", "-expect-ticket-supports-early-data", - "-expect-accept-early-data", + "-on-resume-expect-accept-early-data", "-on-resume-read-with-unfinished-write", "-on-resume-shim-writes-first", }, @@ -4473,7 +4618,7 @@ func addStateMachineCoverageTests(config stateMachineTestConfig) { resumeSession: true, flags: []string{ "-enable-early-data", - "-expect-accept-early-data", + "-on-resume-expect-accept-early-data", }, shouldFail: true, expectedError: ":TOO_MUCH_READ_EARLY_DATA:", @@ -6524,7 +6669,7 @@ func addExtensionTests() { flags: []string{ "-token-binding-params", base64.StdEncoding.EncodeToString([]byte{2, 1, 0}), - "-expected-token-binding-param", + "-expect-token-binding-param", "2", }, }) @@ -6573,7 +6718,7 @@ func addExtensionTests() { flags: []string{ "-token-binding-params", base64.StdEncoding.EncodeToString([]byte{2, 1, 0}), - "-expected-token-binding-param", + "-expect-token-binding-param", "2", }, }) @@ -6609,7 +6754,7 @@ func addExtensionTests() { flags: []string{ "-token-binding-params", base64.StdEncoding.EncodeToString([]byte{2, 1, 0}), - "-expected-token-binding-param", + "-expect-token-binding-param", "2", }, }) @@ -6627,7 +6772,7 @@ func addExtensionTests() { flags: []string{ "-token-binding-params", base64.StdEncoding.EncodeToString([]byte{0, 1, 2}), - "-expected-token-binding-param", + "-expect-token-binding-param", "2", }, }) @@ -6658,7 +6803,7 @@ func addExtensionTests() { flags: []string{ "-token-binding-params", base64.StdEncoding.EncodeToString([]byte{0, 1, 2}), - "-expected-token-binding-param", + "-expect-token-binding-param", "2", }, shouldFail: true, @@ -6678,7 +6823,7 @@ func addExtensionTests() { flags: []string{ "-token-binding-params", base64.StdEncoding.EncodeToString([]byte{0, 1, 2}), - "-expected-token-binding-param", + "-expect-token-binding-param", "2", }, shouldFail: true, @@ -6698,7 +6843,7 @@ func addExtensionTests() { flags: []string{ "-token-binding-params", base64.StdEncoding.EncodeToString([]byte{0, 1, 2}), - "-expected-token-binding-param", + "-expect-token-binding-param", "2", }, shouldFail: true, @@ -6734,7 +6879,7 @@ func addExtensionTests() { flags: []string{ "-token-binding-params", base64.StdEncoding.EncodeToString([]byte{0, 1, 2}), - "-expected-token-binding-param", + "-expect-token-binding-param", "2", }, }) @@ -6879,6 +7024,8 @@ func addExtensionTests() { "-expect-ticket-supports-early-data", "-token-binding-params", base64.StdEncoding.EncodeToString([]byte{2, 1, 0}), + "-expect-reject-early-data", + "-on-retry-expect-early-data-reason", "token_binding", }, }) } @@ -6897,7 +7044,7 @@ func addExtensionTests() { flags: []string{ "-quic-transport-params", base64.StdEncoding.EncodeToString([]byte{3, 4}), - "-expected-quic-transport-params", + "-expect-quic-transport-params", base64.StdEncoding.EncodeToString([]byte{1, 2}), }, expectedQUICTransportParams: []byte{3, 4}, @@ -6914,7 +7061,7 @@ func addExtensionTests() { flags: []string{ "-quic-transport-params", base64.StdEncoding.EncodeToString([]byte{3, 4}), - "-expected-quic-transport-params", + "-expect-quic-transport-params", base64.StdEncoding.EncodeToString([]byte{1, 2}), }, expectedQUICTransportParams: []byte{3, 4}, @@ -6958,7 +7105,7 @@ func addExtensionTests() { QUICTransportParams: []byte{1, 2}, }, flags: []string{ - "-expected-quic-transport-params", + "-expect-quic-transport-params", base64.StdEncoding.EncodeToString([]byte{1, 2}), }, shouldFail: true, @@ -9990,7 +10137,7 @@ func addExportKeyingMaterialTests() { flags: []string{ "-enable-early-data", "-expect-ticket-supports-early-data", - "-expect-accept-early-data", + "-on-resume-expect-accept-early-data", "-on-resume-export-keying-material", "1024", "-on-resume-export-label", "label", "-on-resume-export-context", "context", @@ -10021,7 +10168,7 @@ func addExportKeyingMaterialTests() { flags: []string{ "-enable-early-data", "-expect-ticket-supports-early-data", - "-expect-accept-early-data", + "-on-resume-expect-accept-early-data", "-on-resume-export-early-keying-material", "1024", "-on-resume-export-label", "label", "-on-resume-export-context", "context", @@ -10048,7 +10195,7 @@ func addExportKeyingMaterialTests() { flags: []string{ "-enable-early-data", "-expect-ticket-supports-early-data", - "-expect-accept-early-data", + "-on-resume-expect-accept-early-data", // Handshake twice on the client to force // handshake confirmation. "-handshake-twice", @@ -10441,14 +10588,19 @@ var testCurves = []struct { {"P-521", CurveP521}, {"X25519", CurveX25519}, {"CECPQ2", CurveCECPQ2}, + {"CECPQ2b", CurveCECPQ2b}, } const bogusCurve = 0x1234 +func isPqGroup(r CurveID) bool { + return r == CurveCECPQ2 || r == CurveCECPQ2b +} + func addCurveTests() { for _, curve := range testCurves { for _, ver := range tlsVersions { - if curve.id == CurveCECPQ2 && ver.version < VersionTLS13 { + if isPqGroup(curve.id) && ver.version < VersionTLS13 { continue } @@ -10490,7 +10642,7 @@ func addCurveTests() { expectedCurveID: curve.id, }) - if curve.id != CurveX25519 && curve.id != CurveCECPQ2 { + if curve.id != CurveX25519 && !isPqGroup(curve.id) { testCases = append(testCases, testCase{ name: "CurveTest-Client-Compressed-" + suffix, config: Config{ @@ -10915,6 +11067,21 @@ func addCurveTests() { }, }) + // CECPQ2b should not be offered by a TLS < 1.3 client. + testCases = append(testCases, testCase{ + name: "CECPQ2bNotInTLS12", + config: Config{ + Bugs: ProtocolBugs{ + FailIfCECPQ2Offered: true, + }, + }, + flags: []string{ + "-max-version", strconv.Itoa(VersionTLS12), + "-curves", strconv.Itoa(int(CurveCECPQ2b)), + "-curves", strconv.Itoa(int(CurveX25519)), + }, + }) + // CECPQ2 should not crash a TLS < 1.3 client if the server mistakenly // selects it. testCases = append(testCases, testCase{ @@ -10933,6 +11100,24 @@ func addCurveTests() { expectedError: ":WRONG_CURVE:", }) + // CECPQ2b should not crash a TLS < 1.3 client if the server mistakenly + // selects it. + testCases = append(testCases, testCase{ + name: "CECPQ2bNotAcceptedByTLS12Client", + config: Config{ + Bugs: ProtocolBugs{ + SendCurve: CurveCECPQ2b, + }, + }, + flags: []string{ + "-max-version", strconv.Itoa(VersionTLS12), + "-curves", strconv.Itoa(int(CurveCECPQ2b)), + "-curves", strconv.Itoa(int(CurveX25519)), + }, + shouldFail: true, + expectedError: ":WRONG_CURVE:", + }) + // CECPQ2 should not be offered by default as a client. testCases = append(testCases, testCase{ name: "CECPQ2NotEnabledByDefaultInClients", @@ -10944,6 +11129,17 @@ func addCurveTests() { }, }) + // CECPQ2b should not be offered by default as a client. + testCases = append(testCases, testCase{ + name: "CECPQ2bNotEnabledByDefaultInClients", + config: Config{ + MinVersion: VersionTLS13, + Bugs: ProtocolBugs{ + FailIfCECPQ2Offered: true, + }, + }, + }) + // If CECPQ2 is offered, both X25519 and CECPQ2 should have a key-share. testCases = append(testCases, testCase{ name: "NotJustCECPQ2KeyShare", @@ -10976,6 +11172,38 @@ func addCurveTests() { }, }) + // If CECPQ2b is offered, both X25519 and CECPQ2b should have a key-share. + testCases = append(testCases, testCase{ + name: "NotJustCECPQ2bKeyShare", + config: Config{ + MinVersion: VersionTLS13, + Bugs: ProtocolBugs{ + ExpectedKeyShares: []CurveID{CurveCECPQ2b, CurveX25519}, + }, + }, + flags: []string{ + "-curves", strconv.Itoa(int(CurveCECPQ2b)), + "-curves", strconv.Itoa(int(CurveX25519)), + "-expect-curve-id", strconv.Itoa(int(CurveCECPQ2b)), + }, + }) + + // ... but only if CECPQ2b is listed first. + testCases = append(testCases, testCase{ + name: "CECPQ2bKeyShareNotIncludedSecond", + config: Config{ + MinVersion: VersionTLS13, + Bugs: ProtocolBugs{ + ExpectedKeyShares: []CurveID{CurveX25519}, + }, + }, + flags: []string{ + "-curves", strconv.Itoa(int(CurveX25519)), + "-curves", strconv.Itoa(int(CurveCECPQ2b)), + "-expect-curve-id", strconv.Itoa(int(CurveX25519)), + }, + }) + // If CECPQ2 is the only configured curve, the key share is sent. testCases = append(testCases, testCase{ name: "JustConfiguringCECPQ2Works", @@ -10991,6 +11219,21 @@ func addCurveTests() { }, }) + // If CECPQ2b is the only configured curve, the key share is sent. + testCases = append(testCases, testCase{ + name: "JustConfiguringCECPQ2bWorks", + config: Config{ + MinVersion: VersionTLS13, + Bugs: ProtocolBugs{ + ExpectedKeyShares: []CurveID{CurveCECPQ2b}, + }, + }, + flags: []string{ + "-curves", strconv.Itoa(int(CurveCECPQ2b)), + "-expect-curve-id", strconv.Itoa(int(CurveCECPQ2b)), + }, + }) + // As a server, CECPQ2 is not yet supported by default. testCases = append(testCases, testCase{ testType: serverTest, @@ -11005,6 +11248,21 @@ func addCurveTests() { "-expect-curve-id", strconv.Itoa(int(CurveX25519)), }, }) + + // As a server, CECPQ2b is not yet supported by default. + testCases = append(testCases, testCase{ + testType: serverTest, + name: "CECPQ2bNotEnabledByDefaultForAServer", + config: Config{ + MinVersion: VersionTLS13, + CurvePreferences: []CurveID{CurveCECPQ2b, CurveX25519}, + DefaultCurves: []CurveID{CurveCECPQ2b}, + }, + flags: []string{ + "-server-preference", + "-expect-curve-id", strconv.Itoa(int(CurveX25519)), + }, + }) } func addTLS13RecordTests() { @@ -11183,9 +11441,99 @@ func addSessionTicketTests() { }, }) + // Test that ticket age skew up to 60 seconds in either direction is accepted. + testCases = append(testCases, testCase{ + testType: serverTest, + name: "TLS13-TicketAgeSkew-Forward-60-Accept", + config: Config{ + MaxVersion: VersionTLS13, + Bugs: ProtocolBugs{ + SendTicketAge: 70 * time.Second, + SendEarlyData: [][]byte{{1, 2, 3, 4}}, + ExpectEarlyDataAccepted: true, + ExpectHalfRTTData: [][]byte{{254, 253, 252, 251}}, + }, + }, + resumeSession: true, + flags: []string{ + "-resumption-delay", "10", + "-expect-ticket-age-skew", "60", + // 0-RTT is accepted. + "-enable-early-data", + "-on-resume-expect-accept-early-data", + "-on-resume-expect-early-data-reason", "accept", + }, + }) + testCases = append(testCases, testCase{ + testType: serverTest, + name: "TLS13-TicketAgeSkew-Backward-60-Accept", + config: Config{ + MaxVersion: VersionTLS13, + Bugs: ProtocolBugs{ + SendTicketAge: 10 * time.Second, + SendEarlyData: [][]byte{{1, 2, 3, 4}}, + ExpectEarlyDataAccepted: true, + ExpectHalfRTTData: [][]byte{{254, 253, 252, 251}}, + }, + }, + resumeSession: true, + flags: []string{ + "-resumption-delay", "70", + "-expect-ticket-age-skew", "-60", + // 0-RTT is accepted. + "-enable-early-data", + "-on-resume-expect-accept-early-data", + "-on-resume-expect-early-data-reason", "accept", + }, + }) + + // Test that ticket age skew beyond 60 seconds in either direction is rejected. + testCases = append(testCases, testCase{ + testType: serverTest, + name: "TLS13-TicketAgeSkew-Forward-61-Reject", + config: Config{ + MaxVersion: VersionTLS13, + Bugs: ProtocolBugs{ + SendTicketAge: 71 * time.Second, + SendEarlyData: [][]byte{{1, 2, 3, 4}}, + ExpectEarlyDataAccepted: false, + }, + }, + resumeSession: true, + flags: []string{ + "-resumption-delay", "10", + "-expect-ticket-age-skew", "61", + // 0-RTT is rejected. + "-enable-early-data", + "-expect-reject-early-data", + "-on-resume-expect-early-data-reason", "ticket_age_skew", + }, + }) + testCases = append(testCases, testCase{ + testType: serverTest, + name: "TLS13-TicketAgeSkew-Backward-61-Reject", + config: Config{ + MaxVersion: VersionTLS13, + Bugs: ProtocolBugs{ + SendTicketAge: 10 * time.Second, + SendEarlyData: [][]byte{{1, 2, 3, 4}}, + ExpectEarlyDataAccepted: false, + }, + }, + resumeSession: true, + flags: []string{ + "-resumption-delay", "71", + "-expect-ticket-age-skew", "-61", + // 0-RTT is rejected. + "-enable-early-data", + "-expect-reject-early-data", + "-on-resume-expect-early-data-reason", "ticket_age_skew", + }, + }) + testCases = append(testCases, testCase{ testType: clientTest, - name: "TLS13-SendTicketEarlyDataInfo", + name: "TLS13-SendTicketEarlyDataSupport", config: Config{ MaxVersion: VersionTLS13, MaxEarlyDataSize: 16384, @@ -11196,19 +11544,22 @@ func addSessionTicketTests() { }, }) - // Test that 0-RTT tickets are ignored in clients unless opted in. + // Test that 0-RTT tickets are still recorded as such when early data is disabled overall. testCases = append(testCases, testCase{ testType: clientTest, - name: "TLS13-SendTicketEarlyDataInfo-Disabled", + name: "TLS13-SendTicketEarlyDataSupport-Disabled", config: Config{ MaxVersion: VersionTLS13, MaxEarlyDataSize: 16384, }, + flags: []string{ + "-expect-ticket-supports-early-data", + }, }) testCases = append(testCases, testCase{ testType: clientTest, - name: "TLS13-DuplicateTicketEarlyDataInfo", + name: "TLS13-DuplicateTicketEarlyDataSupport", config: Config{ MaxVersion: VersionTLS13, MaxEarlyDataSize: 16384, @@ -11223,7 +11574,7 @@ func addSessionTicketTests() { testCases = append(testCases, testCase{ testType: serverTest, - name: "TLS13-ExpectTicketEarlyDataInfo", + name: "TLS13-ExpectTicketEarlyDataSupport", config: Config{ MaxVersion: VersionTLS13, Bugs: ProtocolBugs{ @@ -12190,7 +12541,9 @@ func addTLS13HandshakeTests() { flags: []string{ "-enable-early-data", "-expect-ticket-supports-early-data", - "-expect-accept-early-data", + "-on-initial-expect-early-data-reason", "no_session_offered", + "-on-resume-expect-accept-early-data", + "-on-resume-expect-early-data-reason", "accept", "-on-resume-shim-writes-first", }, }) @@ -12215,6 +12568,7 @@ func addTLS13HandshakeTests() { "-expect-ticket-supports-early-data", "-expect-reject-early-data", "-on-resume-shim-writes-first", + "-on-retry-expect-early-data-reason", "peer_declined", }, }) @@ -12234,10 +12588,14 @@ func addTLS13HandshakeTests() { resumeSession: true, flags: []string{ "-enable-early-data", - "-expect-accept-early-data", + "-on-initial-expect-early-data-reason", "no_session_offered", + "-on-resume-expect-accept-early-data", + "-on-resume-expect-early-data-reason", "accept", }, }) + // The above tests the most recent ticket. Additionally test that 0-RTT + // works on the first ticket issued by the server. testCases = append(testCases, testCase{ testType: serverTest, name: "EarlyData-FirstTicket-Server-TLS13", @@ -12255,7 +12613,8 @@ func addTLS13HandshakeTests() { resumeSession: true, flags: []string{ "-enable-early-data", - "-expect-accept-early-data", + "-on-resume-expect-accept-early-data", + "-on-resume-expect-early-data-reason", "accept", }, }) @@ -12324,6 +12683,9 @@ func addTLS13HandshakeTests() { }, DefaultCurves: []CurveID{}, }, + // Though the session is not resumed and we send HelloRetryRequest, + // early data being disabled takes priority as the reject reason. + flags: []string{"-expect-early-data-reason", "disabled"}, }) testCases = append(testCases, testCase{ @@ -12418,7 +12780,8 @@ func addTLS13HandshakeTests() { config: Config{ MaxVersion: VersionTLS13, // Require a HelloRetryRequest for every curve. - DefaultCurves: []CurveID{}, + DefaultCurves: []CurveID{}, + CurvePreferences: []CurveID{CurveX25519}, }, expectedCurveID: CurveX25519, }) @@ -12427,8 +12790,9 @@ func addTLS13HandshakeTests() { testType: serverTest, name: "SendHelloRetryRequest-2-TLS13", config: Config{ - MaxVersion: VersionTLS13, - DefaultCurves: []CurveID{CurveP384}, + MaxVersion: VersionTLS13, + DefaultCurves: []CurveID{CurveP384}, + CurvePreferences: []CurveID{CurveX25519, CurveP384}, }, // Although the ClientHello did not predict our preferred curve, // we always select it whether it is predicted or not. @@ -12838,6 +13202,8 @@ func addTLS13HandshakeTests() { }, }, }) + + // Test the client handles 0-RTT being rejected by a full handshake. testCases = append(testCases, testCase{ testType: clientTest, name: "EarlyData-RejectTicket-Client-TLS13", @@ -12859,6 +13225,9 @@ func addTLS13HandshakeTests() { "-expect-ticket-supports-early-data", "-expect-reject-early-data", "-on-resume-shim-writes-first", + "-on-retry-expect-early-data-reason", "session_not_resumed", + // Test the peer certificate is reported correctly in each of the + // three logical connections. "-on-initial-expect-peer-cert-file", path.Join(*resourceDir, rsaCertificateFile), "-on-resume-expect-peer-cert-file", path.Join(*resourceDir, rsaCertificateFile), "-on-retry-expect-peer-cert-file", path.Join(*resourceDir, ecdsaP256CertificateFile), @@ -12867,6 +13236,34 @@ func addTLS13HandshakeTests() { }, }) + // Test the server rejects 0-RTT if it does not recognize the ticket. + testCases = append(testCases, testCase{ + testType: serverTest, + name: "EarlyData-RejectTicket-Server-TLS13", + config: Config{ + MaxVersion: VersionTLS13, + MinVersion: VersionTLS13, + Bugs: ProtocolBugs{ + SendEarlyData: [][]byte{{1, 2, 3, 4}}, + ExpectEarlyDataAccepted: false, + // Corrupt the ticket. + FilterTicket: func(in []byte) ([]byte, error) { + in[len(in)-1] ^= 1 + return in, nil + }, + }, + }, + messageCount: 2, + resumeSession: true, + expectResumeRejected: true, + flags: []string{ + "-enable-early-data", + "-on-resume-expect-reject-early-data", + "-on-resume-expect-early-data-reason", "session_not_resumed", + }, + }) + + // Test the client handles 0-RTT being rejected via a HelloRetryRequest. testCases = append(testCases, testCase{ testType: clientTest, name: "EarlyData-HRR-Client-TLS13", @@ -12886,6 +13283,99 @@ func addTLS13HandshakeTests() { "-enable-early-data", "-expect-ticket-supports-early-data", "-expect-reject-early-data", + "-on-retry-expect-early-data-reason", "hello_retry_request", + }, + }) + + // Test the server rejects 0-RTT if it needs to send a HelloRetryRequest. + testCases = append(testCases, testCase{ + testType: serverTest, + name: "EarlyData-HRR-Server-TLS13", + config: Config{ + MaxVersion: VersionTLS13, + MinVersion: VersionTLS13, + // Require a HelloRetryRequest for every curve. + DefaultCurves: []CurveID{}, + Bugs: ProtocolBugs{ + SendEarlyData: [][]byte{{1, 2, 3, 4}}, + ExpectEarlyDataAccepted: false, + }, + }, + messageCount: 2, + resumeSession: true, + flags: []string{ + "-enable-early-data", + "-on-resume-expect-reject-early-data", + "-on-resume-expect-early-data-reason", "hello_retry_request", + }, + }) + + // Test the client handles a 0-RTT reject from both ticket rejection and + // HelloRetryRequest. + testCases = append(testCases, testCase{ + testType: clientTest, + name: "EarlyData-HRR-RejectTicket-Client-TLS13", + config: Config{ + MaxVersion: VersionTLS13, + MaxEarlyDataSize: 16384, + Certificates: []Certificate{rsaCertificate}, + }, + resumeConfig: &Config{ + MaxVersion: VersionTLS13, + MaxEarlyDataSize: 16384, + Certificates: []Certificate{ecdsaP256Certificate}, + SessionTicketsDisabled: true, + Bugs: ProtocolBugs{ + SendHelloRetryRequestCookie: []byte{1, 2, 3, 4}, + }, + }, + resumeSession: true, + expectResumeRejected: true, + flags: []string{ + "-enable-early-data", + "-expect-ticket-supports-early-data", + "-expect-reject-early-data", + // The client sees HelloRetryRequest before the resumption result, + // though neither value is inherently preferable. + "-on-retry-expect-early-data-reason", "hello_retry_request", + // Test the peer certificate is reported correctly in each of the + // three logical connections. + "-on-initial-expect-peer-cert-file", path.Join(*resourceDir, rsaCertificateFile), + "-on-resume-expect-peer-cert-file", path.Join(*resourceDir, rsaCertificateFile), + "-on-retry-expect-peer-cert-file", path.Join(*resourceDir, ecdsaP256CertificateFile), + // Session tickets are disabled, so the runner will not send a ticket. + "-on-retry-expect-no-session", + }, + }) + + // Test the server rejects 0-RTT if it needs to send a HelloRetryRequest. + testCases = append(testCases, testCase{ + testType: serverTest, + name: "EarlyData-HRR-RejectTicket-Server-TLS13", + config: Config{ + MaxVersion: VersionTLS13, + MinVersion: VersionTLS13, + // Require a HelloRetryRequest for every curve. + DefaultCurves: []CurveID{}, + Bugs: ProtocolBugs{ + SendEarlyData: [][]byte{{1, 2, 3, 4}}, + ExpectEarlyDataAccepted: false, + // Corrupt the ticket. + FilterTicket: func(in []byte) ([]byte, error) { + in[len(in)-1] ^= 1 + return in, nil + }, + }, + }, + messageCount: 2, + resumeSession: true, + expectResumeRejected: true, + flags: []string{ + "-enable-early-data", + "-on-resume-expect-reject-early-data", + // The server sees the missed resumption before HelloRetryRequest, + // though neither value is inherently preferable. + "-on-resume-expect-early-data-reason", "session_not_resumed", }, }) @@ -13051,6 +13541,10 @@ func addTLS13HandshakeTests() { "-enable-early-data", "-expect-ticket-supports-early-data", "-expect-reject-early-data", + // The client does not learn ALPN was the cause. + "-on-retry-expect-early-data-reason", "peer_declined", + // In the 0-RTT state, we surface the predicted ALPN. After + // processing the reject, we surface the real one. "-on-initial-expect-alpn", "foo", "-on-resume-expect-alpn", "foo", "-on-retry-expect-alpn", "bar", @@ -13077,6 +13571,10 @@ func addTLS13HandshakeTests() { "-enable-early-data", "-expect-ticket-supports-early-data", "-expect-reject-early-data", + // The client does not learn ALPN was the cause. + "-on-retry-expect-early-data-reason", "peer_declined", + // In the 0-RTT state, we surface the predicted ALPN. After + // processing the reject, we surface the real one. "-on-initial-expect-alpn", "", "-on-resume-expect-alpn", "", "-on-retry-expect-alpn", "foo", @@ -13104,6 +13602,10 @@ func addTLS13HandshakeTests() { "-enable-early-data", "-expect-ticket-supports-early-data", "-expect-reject-early-data", + // The client does not learn ALPN was the cause. + "-on-retry-expect-early-data-reason", "peer_declined", + // In the 0-RTT state, we surface the predicted ALPN. After + // processing the reject, we surface the real one. "-on-initial-expect-alpn", "foo", "-on-resume-expect-alpn", "foo", "-on-retry-expect-alpn", "", @@ -13158,10 +13660,31 @@ func addTLS13HandshakeTests() { "-enable-early-data", "-expect-ticket-supports-early-data", "-expect-no-offer-early-data", + // Offer different ALPN values in the initial and resumption. "-on-initial-advertise-alpn", "\x03foo", - "-on-resume-advertise-alpn", "\x03bar", "-on-initial-expect-alpn", "foo", + "-on-resume-advertise-alpn", "\x03bar", "-on-resume-expect-alpn", "bar", + // The ALPN mismatch comes from the client, so it reports it as the + // reason. + "-on-resume-expect-early-data-reason", "alpn_mismatch", + }, + }) + + // Test that the client does not offer 0-RTT to servers which never + // advertise it. + testCases = append(testCases, testCase{ + testType: clientTest, + name: "EarlyData-NonZeroRTTSession-Client-TLS13", + config: Config{ + MaxVersion: VersionTLS13, + }, + resumeSession: true, + flags: []string{ + "-enable-early-data", + "-on-resume-expect-no-offer-early-data", + // The client declines to offer 0-RTT because of the session. + "-on-resume-expect-early-data-reason", "unsupported_for_session", }, }) @@ -13184,6 +13707,8 @@ func addTLS13HandshakeTests() { flags: []string{ "-on-resume-enable-early-data", "-expect-reject-early-data", + // The server rejects 0-RTT because of the session. + "-on-resume-expect-early-data-reason", "unsupported_for_session", }, }) @@ -13209,6 +13734,7 @@ func addTLS13HandshakeTests() { "-enable-early-data", "-on-initial-select-alpn", "", "-on-resume-select-alpn", "foo", + "-on-resume-expect-early-data-reason", "alpn_mismatch", }, }) @@ -13234,6 +13760,7 @@ func addTLS13HandshakeTests() { "-enable-early-data", "-on-initial-select-alpn", "foo", "-on-resume-select-alpn", "", + "-on-resume-expect-early-data-reason", "alpn_mismatch", }, }) @@ -13258,6 +13785,7 @@ func addTLS13HandshakeTests() { "-enable-early-data", "-on-initial-select-alpn", "foo", "-on-resume-select-alpn", "bar", + "-on-resume-expect-early-data-reason", "alpn_mismatch", }, }) @@ -13302,6 +13830,8 @@ func addTLS13HandshakeTests() { "-expect-ticket-supports-early-data", "-send-channel-id", path.Join(*resourceDir, channelIDKeyFile), "-expect-reject-early-data", + // The client never learns the reason was Channel ID. + "-on-retry-expect-early-data-reason", "peer_declined", }, }) @@ -13319,7 +13849,8 @@ func addTLS13HandshakeTests() { "-enable-early-data", "-expect-ticket-supports-early-data", "-send-channel-id", path.Join(*resourceDir, channelIDKeyFile), - "-expect-accept-early-data", + "-on-resume-expect-accept-early-data", + "-on-resume-expect-early-data-reason", "accept", }, }) @@ -13343,6 +13874,7 @@ func addTLS13HandshakeTests() { "-expect-reject-early-data", "-expect-channel-id", base64.StdEncoding.EncodeToString(channelIDBytes), + "-on-resume-expect-early-data-reason", "channel_id", }, }) @@ -13363,8 +13895,9 @@ func addTLS13HandshakeTests() { expectChannelID: false, flags: []string{ "-enable-early-data", - "-expect-accept-early-data", + "-on-resume-expect-accept-early-data", "-enable-channel-id", + "-on-resume-expect-early-data-reason", "accept", }, }) @@ -13424,7 +13957,7 @@ func addTLS13HandshakeTests() { flags: []string{ "-enable-early-data", "-expect-ticket-supports-early-data", - "-expect-accept-early-data", + "-on-resume-expect-accept-early-data", "-expect-version", strconv.Itoa(VersionTLS13), }, }) @@ -13449,7 +13982,7 @@ func addTLS13HandshakeTests() { flags: []string{ "-enable-early-data", "-expect-ticket-supports-early-data", - "-expect-accept-early-data", + "-on-resume-expect-accept-early-data", }, shouldFail: true, expectedError: ":DIGEST_CHECK_FAILED:", @@ -13473,7 +14006,7 @@ func addTLS13HandshakeTests() { resumeSession: true, flags: []string{ "-enable-early-data", - "-expect-accept-early-data", + "-on-resume-expect-accept-early-data", }, shouldFail: true, expectedError: ":DIGEST_CHECK_FAILED:", @@ -13498,7 +14031,7 @@ func addTLS13HandshakeTests() { flags: []string{ "-enable-early-data", "-expect-ticket-supports-early-data", - "-expect-accept-early-data", + "-on-resume-expect-accept-early-data", }, shouldFail: true, expectedError: ":DECODE_ERROR:", @@ -13546,6 +14079,45 @@ func addTLS13HandshakeTests() { expectedLocalError: "remote error: unexpected message", }) + // If the client or server has 0-RTT enabled but disabled TLS 1.3, it should + // report a reason of protocol_version. + testCases = append(testCases, testCase{ + testType: clientTest, + name: "EarlyDataEnabled-Client-MaxTLS12", + expectedVersion: VersionTLS12, + flags: []string{ + "-enable-early-data", + "-max-version", strconv.Itoa(VersionTLS12), + "-expect-early-data-reason", "protocol_version", + }, + }) + testCases = append(testCases, testCase{ + testType: serverTest, + name: "EarlyDataEnabled-Server-MaxTLS12", + expectedVersion: VersionTLS12, + flags: []string{ + "-enable-early-data", + "-max-version", strconv.Itoa(VersionTLS12), + "-expect-early-data-reason", "protocol_version", + }, + }) + + // The server additionally reports protocol_version if it enabled TLS 1.3, + // but the peer negotiated TLS 1.2. (The corresponding situation does not + // exist on the client because negotiating TLS 1.2 with a 0-RTT ClientHello + // is a fatal error.) + testCases = append(testCases, testCase{ + testType: serverTest, + name: "EarlyDataEnabled-Server-NegotiateTLS12", + config: Config{ + MaxVersion: VersionTLS12, + }, + expectedVersion: VersionTLS12, + flags: []string{ + "-enable-early-data", + "-expect-early-data-reason", "protocol_version", + }, + }) } func addTLS13CipherPreferenceTests() { @@ -13560,6 +14132,7 @@ func addTLS13CipherPreferenceTests() { TLS_CHACHA20_POLY1305_SHA256, TLS_AES_128_GCM_SHA256, }, + CurvePreferences: []CurveID{CurveX25519}, }, flags: []string{ "-expect-cipher-aes", strconv.Itoa(int(TLS_CHACHA20_POLY1305_SHA256)), @@ -13576,6 +14149,7 @@ func addTLS13CipherPreferenceTests() { TLS_AES_128_GCM_SHA256, TLS_CHACHA20_POLY1305_SHA256, }, + CurvePreferences: []CurveID{CurveX25519}, }, flags: []string{ "-expect-cipher-aes", strconv.Itoa(int(TLS_AES_128_GCM_SHA256)), @@ -13599,7 +14173,7 @@ func addTLS13CipherPreferenceTests() { }, }) - // Test that CECPQ2 cannot be used with TLS_AES_128_GCM_SHA256. + // CECPQ2 prefers 256-bit ciphers but will use AES-128 if there's nothing else. testCases = append(testCases, testCase{ testType: serverTest, name: "TLS13-CipherPreference-CECPQ2-AES128Only", @@ -13612,9 +14186,89 @@ func addTLS13CipherPreferenceTests() { flags: []string{ "-curves", strconv.Itoa(int(CurveCECPQ2)), }, - shouldFail: true, - expectedError: ":NO_SHARED_CIPHER:", - expectedLocalError: "remote error: handshake failure", + }) + + // CECPQ2b prefers 256-bit ciphers but will use AES-128 if there's nothing else. + testCases = append(testCases, testCase{ + testType: serverTest, + name: "TLS13-CipherPreference-CECPQ2b-AES128Only", + config: Config{ + MaxVersion: VersionTLS13, + CipherSuites: []uint16{ + TLS_AES_128_GCM_SHA256, + }, + }, + flags: []string{ + "-curves", strconv.Itoa(int(CurveCECPQ2b)), + }, + }) + + // When a 256-bit cipher is offered, even if not in first place, it should be + // picked. + testCases = append(testCases, testCase{ + testType: serverTest, + name: "TLS13-CipherPreference-CECPQ2-AES256Preferred", + config: Config{ + MaxVersion: VersionTLS13, + CipherSuites: []uint16{ + TLS_AES_128_GCM_SHA256, + TLS_AES_256_GCM_SHA384, + }, + }, + flags: []string{ + "-curves", strconv.Itoa(int(CurveCECPQ2)), + }, + expectedCipher: TLS_AES_256_GCM_SHA384, + }) + // ... but when CECPQ2 isn't being used, the client's preference controls. + testCases = append(testCases, testCase{ + testType: serverTest, + name: "TLS13-CipherPreference-CECPQ2-AES128PreferredOtherwise", + config: Config{ + MaxVersion: VersionTLS13, + CipherSuites: []uint16{ + TLS_AES_128_GCM_SHA256, + TLS_AES_256_GCM_SHA384, + }, + }, + flags: []string{ + "-curves", strconv.Itoa(int(CurveX25519)), + }, + expectedCipher: TLS_AES_128_GCM_SHA256, + }) + + // When a 256-bit cipher is offered, even if not in first place, it should be + // picked. + testCases = append(testCases, testCase{ + testType: serverTest, + name: "TLS13-CipherPreference-CECPQ2b-AES256Preferred", + config: Config{ + MaxVersion: VersionTLS13, + CipherSuites: []uint16{ + TLS_AES_128_GCM_SHA256, + TLS_AES_256_GCM_SHA384, + }, + }, + flags: []string{ + "-curves", strconv.Itoa(int(CurveCECPQ2b)), + }, + expectedCipher: TLS_AES_256_GCM_SHA384, + }) + // ... but when CECPQ2b isn't being used, the client's preference controls. + testCases = append(testCases, testCase{ + testType: serverTest, + name: "TLS13-CipherPreference-CECPQ2b-AES128PreferredOtherwise", + config: Config{ + MaxVersion: VersionTLS13, + CipherSuites: []uint16{ + TLS_AES_128_GCM_SHA256, + TLS_AES_256_GCM_SHA384, + }, + }, + flags: []string{ + "-curves", strconv.Itoa(int(CurveX25519)), + }, + expectedCipher: TLS_AES_128_GCM_SHA256, }) // Test that CECPQ2 continues to honor AES vs ChaCha20 logic. @@ -13652,6 +14306,42 @@ func addTLS13CipherPreferenceTests() { "-expect-cipher-no-aes", strconv.Itoa(int(TLS_CHACHA20_POLY1305_SHA256)), }, }) + + // Test that CECPQ2b continues to honor AES vs ChaCha20 logic. + testCases = append(testCases, testCase{ + testType: serverTest, + name: "TLS13-CipherPreference-CECPQ2b-AES128-ChaCha20-AES256", + config: Config{ + MaxVersion: VersionTLS13, + CipherSuites: []uint16{ + TLS_AES_128_GCM_SHA256, + TLS_CHACHA20_POLY1305_SHA256, + TLS_AES_256_GCM_SHA384, + }, + }, + flags: []string{ + "-curves", strconv.Itoa(int(CurveCECPQ2b)), + "-expect-cipher-aes", strconv.Itoa(int(TLS_CHACHA20_POLY1305_SHA256)), + "-expect-cipher-no-aes", strconv.Itoa(int(TLS_CHACHA20_POLY1305_SHA256)), + }, + }) + testCases = append(testCases, testCase{ + testType: serverTest, + name: "TLS13-CipherPreference-CECPQ2b-AES128-AES256-ChaCha20", + config: Config{ + MaxVersion: VersionTLS13, + CipherSuites: []uint16{ + TLS_AES_128_GCM_SHA256, + TLS_AES_256_GCM_SHA384, + TLS_CHACHA20_POLY1305_SHA256, + }, + }, + flags: []string{ + "-curves", strconv.Itoa(int(CurveCECPQ2b)), + "-expect-cipher-aes", strconv.Itoa(int(TLS_AES_256_GCM_SHA384)), + "-expect-cipher-no-aes", strconv.Itoa(int(TLS_CHACHA20_POLY1305_SHA256)), + }, + }) } func addPeekTests() { @@ -13972,11 +14662,181 @@ func addECDSAKeyUsageTests() { Certificates: []Certificate{cert}, }, shouldFail: true, - expectedError: ":ECC_CERT_NOT_FOR_SIGNING:", + expectedError: ":KEY_USAGE_BIT_INCORRECT:", }) } } +func addRSAKeyUsageTests() { + priv := rsaCertificate.PrivateKey.(*rsa.PrivateKey) + + serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) + serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) + if err != nil { + panic(err) + } + + dsTemplate := x509.Certificate{ + SerialNumber: serialNumber, + Subject: pkix.Name{ + Organization: []string{"Acme Co"}, + }, + NotBefore: time.Now(), + NotAfter: time.Now(), + + KeyUsage: x509.KeyUsageDigitalSignature, + BasicConstraintsValid: true, + } + + encTemplate := x509.Certificate{ + SerialNumber: serialNumber, + Subject: pkix.Name{ + Organization: []string{"Acme Co"}, + }, + NotBefore: time.Now(), + NotAfter: time.Now(), + + KeyUsage: x509.KeyUsageKeyEncipherment, + BasicConstraintsValid: true, + } + + dsDerBytes, err := x509.CreateCertificate(rand.Reader, &dsTemplate, &dsTemplate, &priv.PublicKey, priv) + if err != nil { + panic(err) + } + + encDerBytes, err := x509.CreateCertificate(rand.Reader, &encTemplate, &encTemplate, &priv.PublicKey, priv) + if err != nil { + panic(err) + } + + dsCert := Certificate{ + Certificate: [][]byte{dsDerBytes}, + PrivateKey: priv, + } + + encCert := Certificate{ + Certificate: [][]byte{encDerBytes}, + PrivateKey: priv, + } + + dsSuites := []uint16{ + TLS_AES_128_GCM_SHA256, + TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, + TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, + } + encSuites := []uint16{ + TLS_RSA_WITH_AES_128_GCM_SHA256, + TLS_RSA_WITH_AES_128_CBC_SHA, + } + + for _, ver := range tlsVersions { + testCases = append(testCases, testCase{ + testType: clientTest, + name: "RSAKeyUsage-WantSignature-GotEncipherment-" + ver.name, + config: Config{ + MinVersion: ver.version, + MaxVersion: ver.version, + Certificates: []Certificate{encCert}, + CipherSuites: dsSuites, + }, + shouldFail: true, + expectedError: ":KEY_USAGE_BIT_INCORRECT:", + flags: []string{ + "-enforce-rsa-key-usage", + }, + }) + + testCases = append(testCases, testCase{ + testType: clientTest, + name: "RSAKeyUsage-WantSignature-GotSignature-" + ver.name, + config: Config{ + MinVersion: ver.version, + MaxVersion: ver.version, + Certificates: []Certificate{dsCert}, + CipherSuites: dsSuites, + }, + flags: []string{ + "-enforce-rsa-key-usage", + }, + }) + + // TLS 1.3 removes the encipherment suites. + if ver.version < VersionTLS13 { + testCases = append(testCases, testCase{ + testType: clientTest, + name: "RSAKeyUsage-WantEncipherment-GotEncipherment" + ver.name, + config: Config{ + MinVersion: ver.version, + MaxVersion: ver.version, + Certificates: []Certificate{encCert}, + CipherSuites: encSuites, + }, + flags: []string{ + "-enforce-rsa-key-usage", + }, + }) + + testCases = append(testCases, testCase{ + testType: clientTest, + name: "RSAKeyUsage-WantEncipherment-GotSignature-" + ver.name, + config: Config{ + MinVersion: ver.version, + MaxVersion: ver.version, + Certificates: []Certificate{dsCert}, + CipherSuites: encSuites, + }, + shouldFail: true, + expectedError: ":KEY_USAGE_BIT_INCORRECT:", + flags: []string{ + "-enforce-rsa-key-usage", + }, + }) + + // In 1.2 and below, we should not enforce without the enforce-rsa-key-usage flag. + testCases = append(testCases, testCase{ + testType: clientTest, + name: "RSAKeyUsage-WantSignature-GotEncipherment-Unenforced" + ver.name, + config: Config{ + MinVersion: ver.version, + MaxVersion: ver.version, + Certificates: []Certificate{dsCert}, + CipherSuites: encSuites, + }, + }) + + testCases = append(testCases, testCase{ + testType: clientTest, + name: "RSAKeyUsage-WantEncipherment-GotSignature-Unenforced" + ver.name, + config: Config{ + MinVersion: ver.version, + MaxVersion: ver.version, + Certificates: []Certificate{encCert}, + CipherSuites: dsSuites, + }, + }) + + } + + if ver.version >= VersionTLS13 { + // In 1.3 and above, we enforce keyUsage even without the flag. + testCases = append(testCases, testCase{ + testType: clientTest, + name: "RSAKeyUsage-WantSignature-GotEncipherment-Enforced" + ver.name, + config: Config{ + MinVersion: ver.version, + MaxVersion: ver.version, + Certificates: []Certificate{encCert}, + CipherSuites: dsSuites, + }, + shouldFail: true, + expectedError: ":KEY_USAGE_BIT_INCORRECT:", + }) + + } + } +} + func addExtraHandshakeTests() { // An extra SSL_do_handshake is normally a no-op. These tests use -async // to ensure there is no transport I/O. @@ -14047,7 +14907,7 @@ func addExtraHandshakeTests() { flags: []string{ "-async", "-enable-early-data", - "-expect-accept-early-data", + "-on-resume-expect-accept-early-data", "-no-op-extra-handshake", }, }) @@ -14146,8 +15006,10 @@ func addOmitExtensionsTests() { OmitExtensions: true, // Disable all ServerHello extensions so // OmitExtensions works. - NoExtendedMasterSecret: true, - NoRenegotiationInfo: true, + NoExtendedMasterSecret: true, + NoRenegotiationInfo: true, + NoOCSPStapling: true, + NoSignedCertificateTimestamps: true, }, }, }) @@ -14163,8 +15025,10 @@ func addOmitExtensionsTests() { EmptyExtensions: true, // Disable all ServerHello extensions so // EmptyExtensions works. - NoExtendedMasterSecret: true, - NoRenegotiationInfo: true, + NoExtendedMasterSecret: true, + NoRenegotiationInfo: true, + NoOCSPStapling: true, + NoSignedCertificateTimestamps: true, }, }, }) @@ -14563,6 +15427,109 @@ func addJDK11WorkaroundTests() { } } +func addDelegatedCredentialTests() { + certPath := path.Join(*resourceDir, rsaCertificateFile) + pemBytes, err := ioutil.ReadFile(certPath) + if err != nil { + panic(err) + } + + block, _ := pem.Decode(pemBytes) + if block == nil { + panic(fmt.Sprintf("no PEM block found in %q", certPath)) + } + parentDER := block.Bytes + + rsaPriv, _, err := loadRSAPrivateKey(rsaKeyFile) + if err != nil { + panic(err) + } + + ecdsaDC, ecdsaPKCS8, err := createDelegatedCredential(delegatedCredentialConfig{ + algo: signatureRSAPSSWithSHA256, + }, parentDER, rsaPriv) + if err != nil { + panic(err) + } + ecdsaFlagValue := fmt.Sprintf("%x,%x", ecdsaDC, ecdsaPKCS8) + + testCases = append(testCases, testCase{ + testType: serverTest, + name: "DelegatedCredentials-NoClientSupport", + config: Config{ + MinVersion: VersionTLS13, + MaxVersion: VersionTLS13, + Bugs: ProtocolBugs{ + DisableDelegatedCredentials: true, + }, + }, + flags: []string{ + "-delegated-credential", ecdsaFlagValue, + }, + }) + + testCases = append(testCases, testCase{ + testType: serverTest, + name: "DelegatedCredentials-Basic", + config: Config{ + MinVersion: VersionTLS13, + MaxVersion: VersionTLS13, + Bugs: ProtocolBugs{ + ExpectDelegatedCredentials: true, + }, + }, + flags: []string{ + "-delegated-credential", ecdsaFlagValue, + }, + }) + + testCases = append(testCases, testCase{ + testType: serverTest, + name: "DelegatedCredentials-SigAlgoMissing", + config: Config{ + MinVersion: VersionTLS13, + MaxVersion: VersionTLS13, + Bugs: ProtocolBugs{ + FailIfDelegatedCredentials: true, + }, + // If the client doesn't support the delegated credential signature + // algorithm then the handshake should complete without using delegated + // credentials. + VerifySignatureAlgorithms: []signatureAlgorithm{signatureRSAPSSWithSHA256}, + }, + flags: []string{ + "-delegated-credential", ecdsaFlagValue, + }, + }) + + // This flag value has mismatched public and private keys which should cause a + // configuration error in the shim. + _, badTLSVersionPKCS8, err := createDelegatedCredential(delegatedCredentialConfig{ + algo: signatureRSAPSSWithSHA256, + tlsVersion: 0x1234, + }, parentDER, rsaPriv) + if err != nil { + panic(err) + } + mismatchFlagValue := fmt.Sprintf("%x,%x", ecdsaDC, badTLSVersionPKCS8) + testCases = append(testCases, testCase{ + testType: serverTest, + name: "DelegatedCredentials-KeyMismatch", + config: Config{ + MinVersion: VersionTLS13, + MaxVersion: VersionTLS13, + Bugs: ProtocolBugs{ + FailIfDelegatedCredentials: true, + }, + }, + flags: []string{ + "-delegated-credential", mismatchFlagValue, + }, + shouldFail: true, + expectedError: ":KEY_VALUES_MISMATCH:", + }) +} + func worker(statusChan chan statusMsg, c chan *testCase, shimPath string, wg *sync.WaitGroup) { defer wg.Done() @@ -14694,10 +15661,12 @@ func main() { addCertificateTests() addRetainOnlySHA256ClientCertTests() addECDSAKeyUsageTests() + addRSAKeyUsageTests() addExtraHandshakeTests() addOmitExtensionsTests() addCertCompressionTests() addJDK11WorkaroundTests() + addDelegatedCredentialTests() testCases = append(testCases, convertToSplitHandshakeTests(testCases)...) diff --git a/third_party/boringssl/kit/src/ssl/test/runner/sike/arith.go b/third_party/boringssl/kit/src/ssl/test/runner/sike/arith.go new file mode 100644 index 00000000..0b9b5c0c --- /dev/null +++ b/third_party/boringssl/kit/src/ssl/test/runner/sike/arith.go @@ -0,0 +1,430 @@ +// Copyright (c) 2019, Cloudflare Inc. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +package sike + +// Helpers + +// uint128 representation +type uint128 struct { + H, L uint64 +} + +func addc64(cin, a, b uint64) (ret, cout uint64) { + ret = cin + ret = ret + a + if ret < a { + cout = 1 + } + ret = ret + b + if ret < b { + cout = 1 + } + + return +} + +func subc64(bIn, a, b uint64) (ret, bOut uint64) { + tmp := a - bIn + if tmp > a { + bOut = 1 + } + ret = tmp - b + if ret > tmp { + bOut = 1 + } + return +} + +func mul64(a, b uint64) (res uint128) { + var al, bl, ah, bh, albl, albh, ahbl, ahbh uint64 + var res1, res2, res3 uint64 + var carry, maskL, maskH, temp uint64 + + maskL = (^maskL) >> 32 + maskH = ^maskL + + al = a & maskL + ah = a >> 32 + bl = b & maskL + bh = b >> 32 + + albl = al * bl + albh = al * bh + ahbl = ah * bl + ahbh = ah * bh + res.L = albl & maskL + + res1 = albl >> 32 + res2 = ahbl & maskL + res3 = albh & maskL + temp = res1 + res2 + res3 + carry = temp >> 32 + res.L ^= temp << 32 + + res1 = ahbl >> 32 + res2 = albh >> 32 + res3 = ahbh & maskL + temp = res1 + res2 + res3 + carry + res.H = temp & maskL + carry = temp & maskH + res.H ^= (ahbh & maskH) + carry + return +} + +// Fp implementation + +// Compute z = x + y (mod 2*p). +func fpAddRdc(z, x, y *Fp) { + var carry uint64 + + // z=x+y % p503 + for i := 0; i < FP_WORDS; i++ { + z[i], carry = addc64(carry, x[i], y[i]) + } + + // z = z - p503x2 + carry = 0 + for i := 0; i < FP_WORDS; i++ { + z[i], carry = subc64(carry, z[i], p503x2[i]) + } + + // if z<0 add p503x2 back + mask := uint64(0 - carry) + carry = 0 + for i := 0; i < FP_WORDS; i++ { + z[i], carry = addc64(carry, z[i], p503x2[i]&mask) + } +} + +// Compute z = x - y (mod 2*p). +func fpSubRdc(z, x, y *Fp) { + var borrow uint64 + + // z = z - p503x2 + for i := 0; i < FP_WORDS; i++ { + z[i], borrow = subc64(borrow, x[i], y[i]) + } + + // if z<0 add p503x2 back + mask := uint64(0 - borrow) + borrow = 0 + for i := 0; i < FP_WORDS; i++ { + z[i], borrow = addc64(borrow, z[i], p503x2[i]&mask) + } +} + +// Reduce a field element in [0, 2*p) to one in [0,p). +func fpRdcP(x *Fp) { + var borrow, mask uint64 + for i := 0; i < FP_WORDS; i++ { + x[i], borrow = subc64(borrow, x[i], p503[i]) + } + + // Sets all bits if borrow = 1 + mask = 0 - borrow + borrow = 0 + for i := 0; i < FP_WORDS; i++ { + x[i], borrow = addc64(borrow, x[i], p503[i]&mask) + } +} + +// Implementation doesn't actually depend on a prime field. +func fpSwapCond(x, y *Fp, mask uint8) { + if mask != 0 { + var tmp Fp + copy(tmp[:], y[:]) + copy(y[:], x[:]) + copy(x[:], tmp[:]) + } +} + +// Compute z = x * y. +func fpMul(z *FpX2, x, y *Fp) { + var u, v, t uint64 + var carry uint64 + var uv uint128 + + for i := uint64(0); i < FP_WORDS; i++ { + for j := uint64(0); j <= i; j++ { + uv = mul64(x[j], y[i-j]) + v, carry = addc64(0, uv.L, v) + u, carry = addc64(carry, uv.H, u) + t += carry + } + z[i] = v + v = u + u = t + t = 0 + } + + for i := FP_WORDS; i < (2*FP_WORDS)-1; i++ { + for j := i - FP_WORDS + 1; j < FP_WORDS; j++ { + uv = mul64(x[j], y[i-j]) + v, carry = addc64(0, uv.L, v) + u, carry = addc64(carry, uv.H, u) + t += carry + } + z[i] = v + v = u + u = t + t = 0 + } + z[2*FP_WORDS-1] = v +} + +// Perform Montgomery reduction: set z = x R^{-1} (mod 2*p) +// with R=2^512. Destroys the input value. +func fpMontRdc(z *Fp, x *FpX2) { + var carry, t, u, v uint64 + var uv uint128 + var count int + + count = 3 // number of 0 digits in the least significat part of p503 + 1 + + for i := 0; i < FP_WORDS; i++ { + for j := 0; j < i; j++ { + if j < (i - count + 1) { + uv = mul64(z[j], p503p1[i-j]) + v, carry = addc64(0, uv.L, v) + u, carry = addc64(carry, uv.H, u) + t += carry + } + } + v, carry = addc64(0, v, x[i]) + u, carry = addc64(carry, u, 0) + t += carry + + z[i] = v + v = u + u = t + t = 0 + } + + for i := FP_WORDS; i < 2*FP_WORDS-1; i++ { + if count > 0 { + count-- + } + for j := i - FP_WORDS + 1; j < FP_WORDS; j++ { + if j < (FP_WORDS - count) { + uv = mul64(z[j], p503p1[i-j]) + v, carry = addc64(0, uv.L, v) + u, carry = addc64(carry, uv.H, u) + t += carry + } + } + v, carry = addc64(0, v, x[i]) + u, carry = addc64(carry, u, 0) + + t += carry + z[i-FP_WORDS] = v + v = u + u = t + t = 0 + } + v, carry = addc64(0, v, x[2*FP_WORDS-1]) + z[FP_WORDS-1] = v +} + +// Compute z = x + y, without reducing mod p. +func fp2Add(z, x, y *FpX2) { + var carry uint64 + for i := 0; i < 2*FP_WORDS; i++ { + z[i], carry = addc64(carry, x[i], y[i]) + } +} + +// Compute z = x - y, without reducing mod p. +func fp2Sub(z, x, y *FpX2) { + var borrow, mask uint64 + for i := 0; i < 2*FP_WORDS; i++ { + z[i], borrow = subc64(borrow, x[i], y[i]) + } + + // Sets all bits if borrow = 1 + mask = 0 - borrow + borrow = 0 + for i := FP_WORDS; i < 2*FP_WORDS; i++ { + z[i], borrow = addc64(borrow, z[i], p503[i-FP_WORDS]&mask) + } +} + +// Montgomery multiplication. Input values must be already +// in Montgomery domain. +func fpMulRdc(dest, lhs, rhs *Fp) { + a := lhs // = a*R + b := rhs // = b*R + + var ab FpX2 + fpMul(&ab, a, b) // = a*b*R*R + fpMontRdc(dest, &ab) // = a*b*R mod p +} + +// Set dest = x^((p-3)/4). If x is square, this is 1/sqrt(x). +// Uses variation of sliding-window algorithm from with window size +// of 5 and least to most significant bit sliding (left-to-right) +// See HAC 14.85 for general description. +// +// Allowed to overlap x with dest. +// All values in Montgomery domains +func p34(dest, x *Fp) { + + // Set dest = x^(2^k), for k >= 1, by repeated squarings. + pow2k := func(dest, x *Fp, k uint8) { + fpMulRdc(dest, x, x) + for i := uint8(1); i < k; i++ { + fpMulRdc(dest, dest, dest) + } + } + // Sliding-window strategy computed with etc/scripts/sliding_window_strat_calc.py + // + // This performs sum(powStrategy) + 1 squarings and len(lookup) + len(mulStrategy) + // multiplications. + powStrategy := []uint8{1, 12, 5, 5, 2, 7, 11, 3, 8, 4, 11, 4, 7, 5, 6, 3, 7, 5, 7, 2, 12, 5, 6, 4, 6, 8, 6, 4, 7, 5, 5, 8, 5, 8, 5, 5, 8, 9, 3, 6, 2, 10, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3} + mulStrategy := []uint8{0, 12, 11, 10, 0, 1, 8, 3, 7, 1, 8, 3, 6, 7, 14, 2, 14, 14, 9, 0, 13, 9, 15, 5, 12, 7, 13, 7, 15, 6, 7, 9, 0, 5, 7, 6, 8, 8, 3, 7, 0, 10, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3} + + // Precompute lookup table of odd multiples of x for window + // size k=5. + lookup := [16]Fp{} + var xx Fp + fpMulRdc(&xx, x, x) + lookup[0] = *x + for i := 1; i < 16; i++ { + fpMulRdc(&lookup[i], &lookup[i-1], &xx) + } + + // Now lookup = {x, x^3, x^5, ... } + // so that lookup[i] = x^{2*i + 1} + // so that lookup[k/2] = x^k, for odd k + *dest = lookup[mulStrategy[0]] + for i := uint8(1); i < uint8(len(powStrategy)); i++ { + pow2k(dest, dest, powStrategy[i]) + fpMulRdc(dest, dest, &lookup[mulStrategy[i]]) + } +} + +func add(dest, lhs, rhs *Fp2) { + fpAddRdc(&dest.A, &lhs.A, &rhs.A) + fpAddRdc(&dest.B, &lhs.B, &rhs.B) +} + +func sub(dest, lhs, rhs *Fp2) { + fpSubRdc(&dest.A, &lhs.A, &rhs.A) + fpSubRdc(&dest.B, &lhs.B, &rhs.B) +} + +func mul(dest, lhs, rhs *Fp2) { + // Let (a,b,c,d) = (lhs.a,lhs.b,rhs.a,rhs.b). + a := &lhs.A + b := &lhs.B + c := &rhs.A + d := &rhs.B + + // We want to compute + // + // (a + bi)*(c + di) = (a*c - b*d) + (a*d + b*c)i + // + // Use Karatsuba's trick: note that + // + // (b - a)*(c - d) = (b*c + a*d) - a*c - b*d + // + // so (a*d + b*c) = (b-a)*(c-d) + a*c + b*d. + + var ac, bd FpX2 + fpMul(&ac, a, c) // = a*c*R*R + fpMul(&bd, b, d) // = b*d*R*R + + var b_minus_a, c_minus_d Fp + fpSubRdc(&b_minus_a, b, a) // = (b-a)*R + fpSubRdc(&c_minus_d, c, d) // = (c-d)*R + + var ad_plus_bc FpX2 + fpMul(&ad_plus_bc, &b_minus_a, &c_minus_d) // = (b-a)*(c-d)*R*R + fp2Add(&ad_plus_bc, &ad_plus_bc, &ac) // = ((b-a)*(c-d) + a*c)*R*R + fp2Add(&ad_plus_bc, &ad_plus_bc, &bd) // = ((b-a)*(c-d) + a*c + b*d)*R*R + + fpMontRdc(&dest.B, &ad_plus_bc) // = (a*d + b*c)*R mod p + + var ac_minus_bd FpX2 + fp2Sub(&ac_minus_bd, &ac, &bd) // = (a*c - b*d)*R*R + fpMontRdc(&dest.A, &ac_minus_bd) // = (a*c - b*d)*R mod p +} + +func inv(dest, x *Fp2) { + var a2PlusB2 Fp + var asq, bsq FpX2 + var ac FpX2 + var minusB Fp + var minusBC FpX2 + + a := &x.A + b := &x.B + + // We want to compute + // + // 1 1 (a - bi) (a - bi) + // -------- = -------- -------- = ----------- + // (a + bi) (a + bi) (a - bi) (a^2 + b^2) + // + // Letting c = 1/(a^2 + b^2), this is + // + // 1/(a+bi) = a*c - b*ci. + + fpMul(&asq, a, a) // = a*a*R*R + fpMul(&bsq, b, b) // = b*b*R*R + fp2Add(&asq, &asq, &bsq) // = (a^2 + b^2)*R*R + fpMontRdc(&a2PlusB2, &asq) // = (a^2 + b^2)*R mod p + // Now a2PlusB2 = a^2 + b^2 + + inv := a2PlusB2 + fpMulRdc(&inv, &a2PlusB2, &a2PlusB2) + p34(&inv, &inv) + fpMulRdc(&inv, &inv, &inv) + fpMulRdc(&inv, &inv, &a2PlusB2) + + fpMul(&ac, a, &inv) + fpMontRdc(&dest.A, &ac) + + fpSubRdc(&minusB, &minusB, b) + fpMul(&minusBC, &minusB, &inv) + fpMontRdc(&dest.B, &minusBC) +} + +func sqr(dest, x *Fp2) { + var a2, aPlusB, aMinusB Fp + var a2MinB2, ab2 FpX2 + + a := &x.A + b := &x.B + + // (a + bi)*(a + bi) = (a^2 - b^2) + 2abi. + fpAddRdc(&a2, a, a) // = a*R + a*R = 2*a*R + fpAddRdc(&aPlusB, a, b) // = a*R + b*R = (a+b)*R + fpSubRdc(&aMinusB, a, b) // = a*R - b*R = (a-b)*R + fpMul(&a2MinB2, &aPlusB, &aMinusB) // = (a+b)*(a-b)*R*R = (a^2 - b^2)*R*R + fpMul(&ab2, &a2, b) // = 2*a*b*R*R + fpMontRdc(&dest.A, &a2MinB2) // = (a^2 - b^2)*R mod p + fpMontRdc(&dest.B, &ab2) // = 2*a*b*R mod p +} + +// In case choice == 1, performs following swap in constant time: +// xPx <-> xQx +// xPz <-> xQz +// Otherwise returns xPx, xPz, xQx, xQz unchanged +func condSwap(xPx, xPz, xQx, xQz *Fp2, choice uint8) { + fpSwapCond(&xPx.A, &xQx.A, choice) + fpSwapCond(&xPx.B, &xQx.B, choice) + fpSwapCond(&xPz.A, &xQz.A, choice) + fpSwapCond(&xPz.B, &xQz.B, choice) +} diff --git a/third_party/boringssl/kit/src/ssl/test/runner/sike/consts.go b/third_party/boringssl/kit/src/ssl/test/runner/sike/consts.go new file mode 100644 index 00000000..0ecff528 --- /dev/null +++ b/third_party/boringssl/kit/src/ssl/test/runner/sike/consts.go @@ -0,0 +1,301 @@ +// Copyright (c) 2019, Cloudflare Inc. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +package sike + +// I keep it bool in order to be able to apply logical NOT +type KeyVariant uint + +// Representation of an element of the base field F_p. +// +// No particular meaning is assigned to the representation -- it could represent +// an element in Montgomery form, or not. Tracking the meaning of the field +// element is left to higher types. +type Fp [FP_WORDS]uint64 + +// Represents an intermediate product of two elements of the base field F_p. +type FpX2 [2 * FP_WORDS]uint64 + +// Represents an element of the extended field Fp^2 = Fp(x+i) +type Fp2 struct { + A Fp + B Fp +} + +type DomainParams struct { + // P, Q and R=P-Q base points + Affine_P, Affine_Q, Affine_R Fp2 + // Size of a compuatation strategy for x-torsion group + IsogenyStrategy []uint32 + // Max size of secret key for x-torsion group + SecretBitLen uint + // Max size of secret key for x-torsion group + SecretByteLen uint +} + +type SidhParams struct { + Id uint8 + // Bytelen of P + Bytelen int + // The public key size, in bytes. + PublicKeySize int + // The shared secret size, in bytes. + SharedSecretSize int + // 2- and 3-torsion group parameter definitions + A, B DomainParams + // Precomputed identity element in the Fp2 in Montgomery domain + OneFp2 Fp2 + // Precomputed 1/2 in the Fp2 in Montgomery domain + HalfFp2 Fp2 + // Length of SIKE secret message. Must be one of {24,32,40}, + // depending on size of prime field used (see [SIKE], 1.4 and 5.1) + MsgLen int + // Length of SIKE ephemeral KEM key (see [SIKE], 1.4 and 5.1) + KemSize int +} + +// Stores curve projective parameters equivalent to A/C. Meaning of the +// values depends on the context. When working with isogenies over +// subgroup that are powers of: +// * three then (A:C) ~ (A+2C:A-2C) +// * four then (A:C) ~ (A+2C: 4C) +// See Appendix A of SIKE for more details +type CurveCoefficientsEquiv struct { + A Fp2 + C Fp2 +} + +// A point on the projective line P^1(F_{p^2}). +// +// This represents a point on the Kummer line of a Montgomery curve. The +// curve is specified by a ProjectiveCurveParameters struct. +type ProjectivePoint struct { + X Fp2 + Z Fp2 +} + +// Base type for public and private key. Used mainly to carry domain +// parameters. +type key struct { + // Domain parameters of the algorithm to be used with a key + params *SidhParams + // Flag indicates whether corresponds to 2-, 3-torsion group or SIKE + keyVariant KeyVariant +} + +// Defines operations on private key +type PrivateKey struct { + key + // Secret key + Scalar []byte + // Used only by KEM + S []byte +} + +// Defines operations on public key +type PublicKey struct { + key + affine_xP Fp2 + affine_xQ Fp2 + affine_xQmP Fp2 +} + +// A point on the projective line P^1(F_{p^2}). +// +// This is used to work projectively with the curve coefficients. +type ProjectiveCurveParameters struct { + A Fp2 + C Fp2 +} + +const ( + // First 2 bits identify SIDH variant third bit indicates + // whether key is a SIKE variant (set) or SIDH (not set) + + // 001 - SIDH: corresponds to 2-torsion group + KeyVariant_SIDH_A KeyVariant = 1 << 0 + // 010 - SIDH: corresponds to 3-torsion group + KeyVariant_SIDH_B = 1 << 1 + // 110 - SIKE + KeyVariant_SIKE = 1<<2 | KeyVariant_SIDH_B + // Number of uint64 limbs used to store field element + FP_WORDS = 8 +) + +// Used internally by this package +// ------------------------------- + +var p503 = Fp{ + 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xABFFFFFFFFFFFFFF, + 0x13085BDA2211E7A0, 0x1B9BF6C87B7E7DAF, 0x6045C6BDDA77A4D0, 0x004066F541811E1E, +} + +// 2*503 +var p503x2 = Fp{ + 0xFFFFFFFFFFFFFFFE, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0x57FFFFFFFFFFFFFF, + 0x2610B7B44423CF41, 0x3737ED90F6FCFB5E, 0xC08B8D7BB4EF49A0, 0x0080CDEA83023C3C, +} + +// p503 + 1 +var p503p1 = Fp{ + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0xAC00000000000000, + 0x13085BDA2211E7A0, 0x1B9BF6C87B7E7DAF, 0x6045C6BDDA77A4D0, 0x004066F541811E1E, +} + +// R^2=(2^512)^2 mod p +var p503R2 = Fp{ + 0x5289A0CF641D011F, 0x9B88257189FED2B9, 0xA3B365D58DC8F17A, 0x5BC57AB6EFF168EC, + 0x9E51998BD84D4423, 0xBF8999CBAC3B5695, 0x46E9127BCE14CDB6, 0x003F6CFCE8B81771, +} + +// p503 + 1 left-shifted by 8, assuming little endianness +var p503p1s8 = Fp{ + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + 0x085BDA2211E7A0AC, 0x9BF6C87B7E7DAF13, 0x45C6BDDA77A4D01B, 0x4066F541811E1E60, +} + +// 1*R mod p +var P503_OneFp2 = Fp2{ + A: Fp{ + 0x00000000000003F9, 0x0000000000000000, 0x0000000000000000, 0xB400000000000000, + 0x63CB1A6EA6DED2B4, 0x51689D8D667EB37D, 0x8ACD77C71AB24142, 0x0026FBAEC60F5953}, +} + +// 1/2 * R mod p +var P503_HalfFp2 = Fp2{ + A: Fp{ + 0x00000000000001FC, 0x0000000000000000, 0x0000000000000000, 0xB000000000000000, + 0x3B69BB2464785D2A, 0x36824A2AF0FE9896, 0xF5899F427A94F309, 0x0033B15203C83BB8}, +} + +var Params SidhParams + +func init() { + Params = SidhParams{ + // SIDH public key byte size. + PublicKeySize: 378, + // SIDH shared secret byte size. + SharedSecretSize: 126, + A: DomainParams{ + // The x-coordinate of PA + Affine_P: Fp2{ + A: Fp{ + 0xE7EF4AA786D855AF, 0xED5758F03EB34D3B, 0x09AE172535A86AA9, 0x237B9CC07D622723, + 0xE3A284CBA4E7932D, 0x27481D9176C5E63F, 0x6A323FF55C6E71BF, 0x002ECC31A6FB8773, + }, + B: Fp{ + 0x64D02E4E90A620B8, 0xDAB8128537D4B9F1, 0x4BADF77B8A228F98, 0x0F5DBDF9D1FB7D1B, + 0xBEC4DB288E1A0DCC, 0xE76A8665E80675DB, 0x6D6F252E12929463, 0x003188BD1463FACC, + }, + }, + // The x-coordinate of QA + Affine_Q: Fp2{ + A: Fp{ + 0xB79D41025DE85D56, 0x0B867DA9DF169686, 0x740E5368021C827D, 0x20615D72157BF25C, + 0xFF1590013C9B9F5B, 0xC884DCADE8C16CEA, 0xEBD05E53BF724E01, 0x0032FEF8FDA5748C, + }, + B: Fp{ + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + }, + }, + // The x-coordinate of RA = PA-QA + Affine_R: Fp2{ + A: Fp{ + 0x12E2E849AA0A8006, 0x41CF47008635A1E8, 0x9CD720A70798AED7, 0x42A820B42FCF04CF, + 0x7BF9BAD32AAE88B1, 0xF619127A54090BBE, 0x1CB10D8F56408EAA, 0x001D6B54C3C0EDEB, + }, + B: Fp{ + 0x34DB54931CBAAC36, 0x420A18CB8DD5F0C4, 0x32008C1A48C0F44D, 0x3B3BA772B1CFD44D, + 0xA74B058FDAF13515, 0x095FC9CA7EEC17B4, 0x448E829D28F120F8, 0x00261EC3ED16A489, + }, + }, + // Max size of secret key for 2-torsion group, corresponds to 2^e2 - 1 + SecretBitLen: 250, + // SecretBitLen in bytes. + SecretByteLen: uint((250 + 7) / 8), + // 2-torsion group computation strategy + IsogenyStrategy: []uint32{ + 0x3D, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x04, 0x02, 0x01, + 0x01, 0x02, 0x01, 0x01, 0x08, 0x04, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x04, 0x02, + 0x01, 0x01, 0x02, 0x01, 0x01, 0x10, 0x08, 0x04, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, + 0x04, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x08, 0x04, 0x02, 0x01, 0x01, 0x02, 0x01, + 0x01, 0x04, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x1D, 0x10, 0x08, 0x04, 0x02, 0x01, + 0x01, 0x02, 0x01, 0x01, 0x04, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x08, 0x04, 0x02, + 0x01, 0x01, 0x02, 0x01, 0x01, 0x04, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x0D, 0x08, + 0x04, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x04, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, + 0x05, 0x04, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01}, + }, + B: DomainParams{ + // The x-coordinate of PB + Affine_P: Fp2{ + A: Fp{ + 0x7EDE37F4FA0BC727, 0xF7F8EC5C8598941C, 0xD15519B516B5F5C8, 0xF6D5AC9B87A36282, + 0x7B19F105B30E952E, 0x13BD8B2025B4EBEE, 0x7B96D27F4EC579A2, 0x00140850CAB7E5DE, + }, + B: Fp{ + 0x7764909DAE7B7B2D, 0x578ABB16284911AB, 0x76E2BFD146A6BF4D, 0x4824044B23AA02F0, + 0x1105048912A321F3, 0xB8A2E482CF0F10C1, 0x42FF7D0BE2152085, 0x0018E599C5223352, + }, + }, + // The x-coordinate of QB + Affine_Q: Fp2{ + A: Fp{ + 0x4256C520FB388820, 0x744FD7C3BAAF0A13, 0x4B6A2DDDB12CBCB8, 0xE46826E27F427DF8, + 0xFE4A663CD505A61B, 0xD6B3A1BAF025C695, 0x7C3BB62B8FCC00BD, 0x003AFDDE4A35746C, + }, + B: Fp{ + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + }, + }, + // The x-coordinate of RB = PB - QB + Affine_R: Fp2{ + A: Fp{ + 0x75601CD1E6C0DFCB, 0x1A9007239B58F93E, 0xC1F1BE80C62107AC, 0x7F513B898F29FF08, + 0xEA0BEDFF43E1F7B2, 0x2C6D94018CBAE6D0, 0x3A430D31BCD84672, 0x000D26892ECCFE83, + }, + B: Fp{ + 0x1119D62AEA3007A1, 0xE3702AA4E04BAE1B, 0x9AB96F7D59F990E7, 0xF58440E8B43319C0, + 0xAF8134BEE1489775, 0xE7F7774E905192AA, 0xF54AE09308E98039, 0x001EF7A041A86112, + }, + }, + // Size of secret key for 3-torsion group, corresponds to log_2(3^e3) - 1. + SecretBitLen: 252, + // SecretBitLen in bytes. + SecretByteLen: uint((252 + 7) / 8), + // 3-torsion group computation strategy + IsogenyStrategy: []uint32{ + 0x47, 0x26, 0x15, 0x0D, 0x08, 0x04, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x04, 0x02, + 0x01, 0x01, 0x02, 0x01, 0x01, 0x05, 0x04, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x02, + 0x01, 0x01, 0x01, 0x09, 0x05, 0x03, 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, + 0x01, 0x04, 0x02, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x11, 0x09, 0x05, 0x03, 0x02, + 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x04, 0x02, 0x01, 0x01, 0x01, 0x02, + 0x01, 0x01, 0x08, 0x04, 0x02, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x04, 0x02, 0x01, + 0x01, 0x02, 0x01, 0x01, 0x21, 0x11, 0x09, 0x05, 0x03, 0x02, 0x01, 0x01, 0x01, 0x01, + 0x02, 0x01, 0x01, 0x01, 0x04, 0x02, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x08, 0x04, + 0x02, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x04, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, + 0x10, 0x08, 0x04, 0x02, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x04, 0x02, 0x01, 0x01, + 0x02, 0x01, 0x01, 0x08, 0x04, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x04, 0x02, 0x01, + 0x01, 0x02, 0x01, 0x01}, + }, + OneFp2: P503_OneFp2, + HalfFp2: P503_HalfFp2, + MsgLen: 24, + // SIKEp503 provides 128 bit of classical security ([SIKE], 5.1) + KemSize: 16, + // ceil(503+7/8) + Bytelen: 63, + } +} diff --git a/third_party/boringssl/kit/src/ssl/test/runner/sike/curve.go b/third_party/boringssl/kit/src/ssl/test/runner/sike/curve.go new file mode 100644 index 00000000..69febaff --- /dev/null +++ b/third_party/boringssl/kit/src/ssl/test/runner/sike/curve.go @@ -0,0 +1,422 @@ +// Copyright (c) 2019, Cloudflare Inc. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +package sike + +// Interface for working with isogenies. +type isogeny interface { + // Given a torsion point on a curve computes isogenous curve. + // Returns curve coefficients (A:C), so that E_(A/C) = E_(A/C)/

, + // where P is a provided projective point. Sets also isogeny constants + // that are needed for isogeny evaluation. + GenerateCurve(*ProjectivePoint) CurveCoefficientsEquiv + // Evaluates isogeny at caller provided point. Requires isogeny curve constants + // to be earlier computed by GenerateCurve. + EvaluatePoint(*ProjectivePoint) ProjectivePoint +} + +// Stores isogeny 3 curve constants +type isogeny3 struct { + K1 Fp2 + K2 Fp2 +} + +// Stores isogeny 4 curve constants +type isogeny4 struct { + isogeny3 + K3 Fp2 +} + +// Constructs isogeny3 objects +func NewIsogeny3() isogeny { + return &isogeny3{} +} + +// Constructs isogeny4 objects +func NewIsogeny4() isogeny { + return &isogeny4{} +} + +// Helper function for RightToLeftLadder(). Returns A+2C / 4. +func calcAplus2Over4(cparams *ProjectiveCurveParameters) (ret Fp2) { + var tmp Fp2 + + // 2C + add(&tmp, &cparams.C, &cparams.C) + // A+2C + add(&ret, &cparams.A, &tmp) + // 1/4C + add(&tmp, &tmp, &tmp) + inv(&tmp, &tmp) + // A+2C/4C + mul(&ret, &ret, &tmp) + return +} + +// Converts values in x.A and x.B to Montgomery domain +// x.A = x.A * R mod p +// x.B = x.B * R mod p +// Performs v = v*R^2*R^(-1) mod p, for both x.A and x.B +func toMontDomain(x *Fp2) { + var aRR FpX2 + + // convert to montgomery domain + fpMul(&aRR, &x.A, &p503R2) // = a*R*R + fpMontRdc(&x.A, &aRR) // = a*R mod p + fpMul(&aRR, &x.B, &p503R2) + fpMontRdc(&x.B, &aRR) +} + +// Converts values in x.A and x.B from Montgomery domain +// a = x.A mod p +// b = x.B mod p +// +// After returning from the call x is not modified. +func fromMontDomain(x *Fp2, out *Fp2) { + var aR FpX2 + + // convert from montgomery domain + copy(aR[:], x.A[:]) + fpMontRdc(&out.A, &aR) // = a mod p in [0, 2p) + fpRdcP(&out.A) // = a mod p in [0, p) + for i := range aR { + aR[i] = 0 + } + copy(aR[:], x.B[:]) + fpMontRdc(&out.B, &aR) + fpRdcP(&out.B) +} + +// Computes j-invariant for a curve y2=x3+A/Cx+x with A,C in F_(p^2). Result +// is returned in 'j'. Implementation corresponds to Algorithm 9 from SIKE. +func Jinvariant(cparams *ProjectiveCurveParameters, j *Fp2) { + var t0, t1 Fp2 + + sqr(j, &cparams.A) // j = A^2 + sqr(&t1, &cparams.C) // t1 = C^2 + add(&t0, &t1, &t1) // t0 = t1 + t1 + sub(&t0, j, &t0) // t0 = j - t0 + sub(&t0, &t0, &t1) // t0 = t0 - t1 + sub(j, &t0, &t1) // t0 = t0 - t1 + sqr(&t1, &t1) // t1 = t1^2 + mul(j, j, &t1) // j = j * t1 + add(&t0, &t0, &t0) // t0 = t0 + t0 + add(&t0, &t0, &t0) // t0 = t0 + t0 + sqr(&t1, &t0) // t1 = t0^2 + mul(&t0, &t0, &t1) // t0 = t0 * t1 + add(&t0, &t0, &t0) // t0 = t0 + t0 + add(&t0, &t0, &t0) // t0 = t0 + t0 + inv(j, j) // j = 1/j + mul(j, &t0, j) // j = t0 * j +} + +// Given affine points x(P), x(Q) and x(Q-P) in a extension field F_{p^2}, function +// recorvers projective coordinate A of a curve. This is Algorithm 10 from SIKE. +func RecoverCoordinateA(curve *ProjectiveCurveParameters, xp, xq, xr *Fp2) { + var t0, t1 Fp2 + + add(&t1, xp, xq) // t1 = Xp + Xq + mul(&t0, xp, xq) // t0 = Xp * Xq + mul(&curve.A, xr, &t1) // A = X(q-p) * t1 + add(&curve.A, &curve.A, &t0) // A = A + t0 + mul(&t0, &t0, xr) // t0 = t0 * X(q-p) + sub(&curve.A, &curve.A, &Params.OneFp2) // A = A - 1 + add(&t0, &t0, &t0) // t0 = t0 + t0 + add(&t1, &t1, xr) // t1 = t1 + X(q-p) + add(&t0, &t0, &t0) // t0 = t0 + t0 + sqr(&curve.A, &curve.A) // A = A^2 + inv(&t0, &t0) // t0 = 1/t0 + mul(&curve.A, &curve.A, &t0) // A = A * t0 + sub(&curve.A, &curve.A, &t1) // A = A - t1 +} + +// Computes equivalence (A:C) ~ (A+2C : A-2C) +func CalcCurveParamsEquiv3(cparams *ProjectiveCurveParameters) CurveCoefficientsEquiv { + var coef CurveCoefficientsEquiv + var c2 Fp2 + + add(&c2, &cparams.C, &cparams.C) + // A24p = A+2*C + add(&coef.A, &cparams.A, &c2) + // A24m = A-2*C + sub(&coef.C, &cparams.A, &c2) + return coef +} + +// Computes equivalence (A:C) ~ (A+2C : 4C) +func CalcCurveParamsEquiv4(cparams *ProjectiveCurveParameters) CurveCoefficientsEquiv { + var coefEq CurveCoefficientsEquiv + + add(&coefEq.C, &cparams.C, &cparams.C) + // A24p = A+2C + add(&coefEq.A, &cparams.A, &coefEq.C) + // C24 = 4*C + add(&coefEq.C, &coefEq.C, &coefEq.C) + return coefEq +} + +// Recovers (A:C) curve parameters from projectively equivalent (A+2C:A-2C). +func RecoverCurveCoefficients3(cparams *ProjectiveCurveParameters, coefEq *CurveCoefficientsEquiv) { + add(&cparams.A, &coefEq.A, &coefEq.C) + // cparams.A = 2*(A+2C+A-2C) = 4A + add(&cparams.A, &cparams.A, &cparams.A) + // cparams.C = (A+2C-A+2C) = 4C + sub(&cparams.C, &coefEq.A, &coefEq.C) + return +} + +// Recovers (A:C) curve parameters from projectively equivalent (A+2C:4C). +func RecoverCurveCoefficients4(cparams *ProjectiveCurveParameters, coefEq *CurveCoefficientsEquiv) { + // cparams.C = (4C)*1/2=2C + mul(&cparams.C, &coefEq.C, &Params.HalfFp2) + // cparams.A = A+2C - 2C = A + sub(&cparams.A, &coefEq.A, &cparams.C) + // cparams.C = 2C * 1/2 = C + mul(&cparams.C, &cparams.C, &Params.HalfFp2) + return +} + +// Combined coordinate doubling and differential addition. Takes projective points +// P,Q,Q-P and (A+2C)/4C curve E coefficient. Returns 2*P and P+Q calculated on E. +// Function is used only by RightToLeftLadder. Corresponds to Algorithm 5 of SIKE +func xDbladd(P, Q, QmP *ProjectivePoint, a24 *Fp2) (dblP, PaQ ProjectivePoint) { + var t0, t1, t2 Fp2 + xQmP, zQmP := &QmP.X, &QmP.Z + xPaQ, zPaQ := &PaQ.X, &PaQ.Z + x2P, z2P := &dblP.X, &dblP.Z + xP, zP := &P.X, &P.Z + xQ, zQ := &Q.X, &Q.Z + + add(&t0, xP, zP) // t0 = Xp+Zp + sub(&t1, xP, zP) // t1 = Xp-Zp + sqr(x2P, &t0) // 2P.X = t0^2 + sub(&t2, xQ, zQ) // t2 = Xq-Zq + add(xPaQ, xQ, zQ) // Xp+q = Xq+Zq + mul(&t0, &t0, &t2) // t0 = t0 * t2 + mul(z2P, &t1, &t1) // 2P.Z = t1 * t1 + mul(&t1, &t1, xPaQ) // t1 = t1 * Xp+q + sub(&t2, x2P, z2P) // t2 = 2P.X - 2P.Z + mul(x2P, x2P, z2P) // 2P.X = 2P.X * 2P.Z + mul(xPaQ, a24, &t2) // Xp+q = A24 * t2 + sub(zPaQ, &t0, &t1) // Zp+q = t0 - t1 + add(z2P, xPaQ, z2P) // 2P.Z = Xp+q + 2P.Z + add(xPaQ, &t0, &t1) // Xp+q = t0 + t1 + mul(z2P, z2P, &t2) // 2P.Z = 2P.Z * t2 + sqr(zPaQ, zPaQ) // Zp+q = Zp+q ^ 2 + sqr(xPaQ, xPaQ) // Xp+q = Xp+q ^ 2 + mul(zPaQ, xQmP, zPaQ) // Zp+q = Xq-p * Zp+q + mul(xPaQ, zQmP, xPaQ) // Xp+q = Zq-p * Xp+q + return +} + +// Given the curve parameters, xP = x(P), computes xP = x([2^k]P) +// Safe to overlap xP, x2P. +func Pow2k(xP *ProjectivePoint, params *CurveCoefficientsEquiv, k uint32) { + var t0, t1 Fp2 + + x, z := &xP.X, &xP.Z + for i := uint32(0); i < k; i++ { + sub(&t0, x, z) // t0 = Xp - Zp + add(&t1, x, z) // t1 = Xp + Zp + sqr(&t0, &t0) // t0 = t0 ^ 2 + sqr(&t1, &t1) // t1 = t1 ^ 2 + mul(z, ¶ms.C, &t0) // Z2p = C24 * t0 + mul(x, z, &t1) // X2p = Z2p * t1 + sub(&t1, &t1, &t0) // t1 = t1 - t0 + mul(&t0, ¶ms.A, &t1) // t0 = A24+ * t1 + add(z, z, &t0) // Z2p = Z2p + t0 + mul(z, z, &t1) // Zp = Z2p * t1 + } +} + +// Given the curve parameters, xP = x(P), and k >= 0, compute xP = x([3^k]P). +// +// Safe to overlap xP, xR. +func Pow3k(xP *ProjectivePoint, params *CurveCoefficientsEquiv, k uint32) { + var t0, t1, t2, t3, t4, t5, t6 Fp2 + + x, z := &xP.X, &xP.Z + for i := uint32(0); i < k; i++ { + sub(&t0, x, z) // t0 = Xp - Zp + sqr(&t2, &t0) // t2 = t0^2 + add(&t1, x, z) // t1 = Xp + Zp + sqr(&t3, &t1) // t3 = t1^2 + add(&t4, &t1, &t0) // t4 = t1 + t0 + sub(&t0, &t1, &t0) // t0 = t1 - t0 + sqr(&t1, &t4) // t1 = t4^2 + sub(&t1, &t1, &t3) // t1 = t1 - t3 + sub(&t1, &t1, &t2) // t1 = t1 - t2 + mul(&t5, &t3, ¶ms.A) // t5 = t3 * A24+ + mul(&t3, &t3, &t5) // t3 = t5 * t3 + mul(&t6, &t2, ¶ms.C) // t6 = t2 * A24- + mul(&t2, &t2, &t6) // t2 = t2 * t6 + sub(&t3, &t2, &t3) // t3 = t2 - t3 + sub(&t2, &t5, &t6) // t2 = t5 - t6 + mul(&t1, &t2, &t1) // t1 = t2 * t1 + add(&t2, &t3, &t1) // t2 = t3 + t1 + sqr(&t2, &t2) // t2 = t2^2 + mul(x, &t2, &t4) // X3p = t2 * t4 + sub(&t1, &t3, &t1) // t1 = t3 - t1 + sqr(&t1, &t1) // t1 = t1^2 + mul(z, &t1, &t0) // Z3p = t1 * t0 + } +} + +// Set (y1, y2, y3) = (1/x1, 1/x2, 1/x3). +// +// All xi, yi must be distinct. +func Fp2Batch3Inv(x1, x2, x3, y1, y2, y3 *Fp2) { + var x1x2, t Fp2 + + mul(&x1x2, x1, x2) // x1*x2 + mul(&t, &x1x2, x3) // 1/(x1*x2*x3) + inv(&t, &t) + mul(y1, &t, x2) // 1/x1 + mul(y1, y1, x3) + mul(y2, &t, x1) // 1/x2 + mul(y2, y2, x3) + mul(y3, &t, &x1x2) // 1/x3 +} + +// ScalarMul3Pt is a right-to-left point multiplication that given the +// x-coordinate of P, Q and P-Q calculates the x-coordinate of R=Q+[scalar]P. +// nbits must be smaller or equal to len(scalar). +func ScalarMul3Pt(cparams *ProjectiveCurveParameters, P, Q, PmQ *ProjectivePoint, nbits uint, scalar []uint8) ProjectivePoint { + var R0, R2, R1 ProjectivePoint + aPlus2Over4 := calcAplus2Over4(cparams) + R1 = *P + R2 = *PmQ + R0 = *Q + + // Iterate over the bits of the scalar, bottom to top + prevBit := uint8(0) + for i := uint(0); i < nbits; i++ { + bit := (scalar[i>>3] >> (i & 7) & 1) + swap := prevBit ^ bit + prevBit = bit + condSwap(&R1.X, &R1.Z, &R2.X, &R2.Z, swap) + R0, R2 = xDbladd(&R0, &R2, &R1, &aPlus2Over4) + } + condSwap(&R1.X, &R1.Z, &R2.X, &R2.Z, prevBit) + return R1 +} + +// Given a three-torsion point p = x(PB) on the curve E_(A:C), construct the +// three-isogeny phi : E_(A:C) -> E_(A:C)/ = E_(A':C'). +// +// Input: (XP_3: ZP_3), where P_3 has exact order 3 on E_A/C +// Output: * Curve coordinates (A' + 2C', A' - 2C') corresponding to E_A'/C' = A_E/C/ +// * isogeny phi with constants in F_p^2 +func (phi *isogeny3) GenerateCurve(p *ProjectivePoint) CurveCoefficientsEquiv { + var t0, t1, t2, t3, t4 Fp2 + var coefEq CurveCoefficientsEquiv + var K1, K2 = &phi.K1, &phi.K2 + + sub(K1, &p.X, &p.Z) // K1 = XP3 - ZP3 + sqr(&t0, K1) // t0 = K1^2 + add(K2, &p.X, &p.Z) // K2 = XP3 + ZP3 + sqr(&t1, K2) // t1 = K2^2 + add(&t2, &t0, &t1) // t2 = t0 + t1 + add(&t3, K1, K2) // t3 = K1 + K2 + sqr(&t3, &t3) // t3 = t3^2 + sub(&t3, &t3, &t2) // t3 = t3 - t2 + add(&t2, &t1, &t3) // t2 = t1 + t3 + add(&t3, &t3, &t0) // t3 = t3 + t0 + add(&t4, &t3, &t0) // t4 = t3 + t0 + add(&t4, &t4, &t4) // t4 = t4 + t4 + add(&t4, &t1, &t4) // t4 = t1 + t4 + mul(&coefEq.C, &t2, &t4) // A24m = t2 * t4 + add(&t4, &t1, &t2) // t4 = t1 + t2 + add(&t4, &t4, &t4) // t4 = t4 + t4 + add(&t4, &t0, &t4) // t4 = t0 + t4 + mul(&t4, &t3, &t4) // t4 = t3 * t4 + sub(&t0, &t4, &coefEq.C) // t0 = t4 - A24m + add(&coefEq.A, &coefEq.C, &t0) // A24p = A24m + t0 + return coefEq +} + +// Given a 3-isogeny phi and a point pB = x(PB), compute x(QB), the x-coordinate +// of the image QB = phi(PB) of PB under phi : E_(A:C) -> E_(A':C'). +// +// The output xQ = x(Q) is then a point on the curve E_(A':C'); the curve +// parameters are returned by the GenerateCurve function used to construct phi. +func (phi *isogeny3) EvaluatePoint(p *ProjectivePoint) ProjectivePoint { + var t0, t1, t2 Fp2 + var q ProjectivePoint + var K1, K2 = &phi.K1, &phi.K2 + var px, pz = &p.X, &p.Z + + add(&t0, px, pz) // t0 = XQ + ZQ + sub(&t1, px, pz) // t1 = XQ - ZQ + mul(&t0, K1, &t0) // t2 = K1 * t0 + mul(&t1, K2, &t1) // t1 = K2 * t1 + add(&t2, &t0, &t1) // t2 = t0 + t1 + sub(&t0, &t1, &t0) // t0 = t1 - t0 + sqr(&t2, &t2) // t2 = t2 ^ 2 + sqr(&t0, &t0) // t0 = t0 ^ 2 + mul(&q.X, px, &t2) // XQ'= XQ * t2 + mul(&q.Z, pz, &t0) // ZQ'= ZQ * t0 + return q +} + +// Given a four-torsion point p = x(PB) on the curve E_(A:C), construct the +// four-isogeny phi : E_(A:C) -> E_(A:C)/ = E_(A':C'). +// +// Input: (XP_4: ZP_4), where P_4 has exact order 4 on E_A/C +// Output: * Curve coordinates (A' + 2C', 4C') corresponding to E_A'/C' = A_E/C/ +// * isogeny phi with constants in F_p^2 +func (phi *isogeny4) GenerateCurve(p *ProjectivePoint) CurveCoefficientsEquiv { + var coefEq CurveCoefficientsEquiv + var xp4, zp4 = &p.X, &p.Z + var K1, K2, K3 = &phi.K1, &phi.K2, &phi.K3 + + sub(K2, xp4, zp4) + add(K3, xp4, zp4) + sqr(K1, zp4) + add(K1, K1, K1) + sqr(&coefEq.C, K1) + add(K1, K1, K1) + sqr(&coefEq.A, xp4) + add(&coefEq.A, &coefEq.A, &coefEq.A) + sqr(&coefEq.A, &coefEq.A) + return coefEq +} + +// Given a 4-isogeny phi and a point xP = x(P), compute x(Q), the x-coordinate +// of the image Q = phi(P) of P under phi : E_(A:C) -> E_(A':C'). +// +// Input: isogeny returned by GenerateCurve and point q=(Qx,Qz) from E0_A/C +// Output: Corresponding point q from E1_A'/C', where E1 is 4-isogenous to E0 +func (phi *isogeny4) EvaluatePoint(p *ProjectivePoint) ProjectivePoint { + var t0, t1 Fp2 + var q = *p + var xq, zq = &q.X, &q.Z + var K1, K2, K3 = &phi.K1, &phi.K2, &phi.K3 + + add(&t0, xq, zq) + sub(&t1, xq, zq) + mul(xq, &t0, K2) + mul(zq, &t1, K3) + mul(&t0, &t0, &t1) + mul(&t0, &t0, K1) + add(&t1, xq, zq) + sub(zq, xq, zq) + sqr(&t1, &t1) + sqr(zq, zq) + add(xq, &t0, &t1) + sub(&t0, zq, &t0) + mul(xq, xq, &t1) + mul(zq, zq, &t0) + return q +} diff --git a/third_party/boringssl/kit/src/ssl/test/runner/sike/sike.go b/third_party/boringssl/kit/src/ssl/test/runner/sike/sike.go new file mode 100644 index 00000000..fc6de05d --- /dev/null +++ b/third_party/boringssl/kit/src/ssl/test/runner/sike/sike.go @@ -0,0 +1,709 @@ +// Copyright (c) 2019, Cloudflare Inc. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +package sike + +import ( + "crypto/hmac" + "crypto/sha256" + "crypto/subtle" + "errors" + "io" +) + +// Constants used for cSHAKE customization +// Those values are different than in [SIKE] - they are encoded on 16bits. This is +// done in order for implementation to be compatible with [REF] and test vectors. +var G = []byte{0x00, 0x00} +var H = []byte{0x01, 0x00} +var F = []byte{0x02, 0x00} + +// Generates HMAC-SHA256 sum +func hashMac(out, in, S []byte) { + h := hmac.New(sha256.New, in) + h.Write(S) + copy(out, h.Sum(nil)) +} + +// Zeroize Fp2 +func zeroize(fp *Fp2) { + // Zeroizing in 2 separated loops tells compiler to + // use fast runtime.memclr() + for i := range fp.A { + fp.A[i] = 0 + } + for i := range fp.B { + fp.B[i] = 0 + } +} + +// Convert the input to wire format. +// +// The output byte slice must be at least 2*bytelen(p) bytes long. +func convFp2ToBytes(output []byte, fp2 *Fp2) { + if len(output) < 2*Params.Bytelen { + panic("output byte slice too short") + } + var a Fp2 + fromMontDomain(fp2, &a) + + // convert to bytes in little endian form + for i := 0; i < Params.Bytelen; i++ { + // set i = j*8 + k + tmp := i / 8 + k := uint64(i % 8) + output[i] = byte(a.A[tmp] >> (8 * k)) + output[i+Params.Bytelen] = byte(a.B[tmp] >> (8 * k)) + } +} + +// Read 2*bytelen(p) bytes into the given ExtensionFieldElement. +// +// It is an error to call this function if the input byte slice is less than 2*bytelen(p) bytes long. +func convBytesToFp2(fp2 *Fp2, input []byte) { + if len(input) < 2*Params.Bytelen { + panic("input byte slice too short") + } + + for i := 0; i < Params.Bytelen; i++ { + j := i / 8 + k := uint64(i % 8) + fp2.A[j] |= uint64(input[i]) << (8 * k) + fp2.B[j] |= uint64(input[i+Params.Bytelen]) << (8 * k) + } + toMontDomain(fp2) +} + +// ----------------------------------------------------------------------------- +// Functions for traversing isogeny trees acoording to strategy. Key type 'A' is +// + +// Traverses isogeny tree in order to compute xR, xP, xQ and xQmP needed +// for public key generation. +func traverseTreePublicKeyA(curve *ProjectiveCurveParameters, xR, phiP, phiQ, phiR *ProjectivePoint, pub *PublicKey) { + var points = make([]ProjectivePoint, 0, 8) + var indices = make([]int, 0, 8) + var i, sidx int + + cparam := CalcCurveParamsEquiv4(curve) + phi := NewIsogeny4() + strat := pub.params.A.IsogenyStrategy + stratSz := len(strat) + + for j := 1; j <= stratSz; j++ { + for i <= stratSz-j { + points = append(points, *xR) + indices = append(indices, i) + + k := strat[sidx] + sidx++ + Pow2k(xR, &cparam, 2*k) + i += int(k) + } + + cparam = phi.GenerateCurve(xR) + for k := 0; k < len(points); k++ { + points[k] = phi.EvaluatePoint(&points[k]) + } + + *phiP = phi.EvaluatePoint(phiP) + *phiQ = phi.EvaluatePoint(phiQ) + *phiR = phi.EvaluatePoint(phiR) + + // pop xR from points + *xR, points = points[len(points)-1], points[:len(points)-1] + i, indices = int(indices[len(indices)-1]), indices[:len(indices)-1] + } +} + +// Traverses isogeny tree in order to compute xR needed +// for public key generation. +func traverseTreeSharedKeyA(curve *ProjectiveCurveParameters, xR *ProjectivePoint, pub *PublicKey) { + var points = make([]ProjectivePoint, 0, 8) + var indices = make([]int, 0, 8) + var i, sidx int + + cparam := CalcCurveParamsEquiv4(curve) + phi := NewIsogeny4() + strat := pub.params.A.IsogenyStrategy + stratSz := len(strat) + + for j := 1; j <= stratSz; j++ { + for i <= stratSz-j { + points = append(points, *xR) + indices = append(indices, i) + + k := strat[sidx] + sidx++ + Pow2k(xR, &cparam, 2*k) + i += int(k) + } + + cparam = phi.GenerateCurve(xR) + for k := 0; k < len(points); k++ { + points[k] = phi.EvaluatePoint(&points[k]) + } + + // pop xR from points + *xR, points = points[len(points)-1], points[:len(points)-1] + i, indices = int(indices[len(indices)-1]), indices[:len(indices)-1] + } +} + +// Traverses isogeny tree in order to compute xR, xP, xQ and xQmP needed +// for public key generation. +func traverseTreePublicKeyB(curve *ProjectiveCurveParameters, xR, phiP, phiQ, phiR *ProjectivePoint, pub *PublicKey) { + var points = make([]ProjectivePoint, 0, 8) + var indices = make([]int, 0, 8) + var i, sidx int + + cparam := CalcCurveParamsEquiv3(curve) + phi := NewIsogeny3() + strat := pub.params.B.IsogenyStrategy + stratSz := len(strat) + + for j := 1; j <= stratSz; j++ { + for i <= stratSz-j { + points = append(points, *xR) + indices = append(indices, i) + + k := strat[sidx] + sidx++ + Pow3k(xR, &cparam, k) + i += int(k) + } + + cparam = phi.GenerateCurve(xR) + for k := 0; k < len(points); k++ { + points[k] = phi.EvaluatePoint(&points[k]) + } + + *phiP = phi.EvaluatePoint(phiP) + *phiQ = phi.EvaluatePoint(phiQ) + *phiR = phi.EvaluatePoint(phiR) + + // pop xR from points + *xR, points = points[len(points)-1], points[:len(points)-1] + i, indices = int(indices[len(indices)-1]), indices[:len(indices)-1] + } +} + +// Traverses isogeny tree in order to compute xR, xP, xQ and xQmP needed +// for public key generation. +func traverseTreeSharedKeyB(curve *ProjectiveCurveParameters, xR *ProjectivePoint, pub *PublicKey) { + var points = make([]ProjectivePoint, 0, 8) + var indices = make([]int, 0, 8) + var i, sidx int + + cparam := CalcCurveParamsEquiv3(curve) + phi := NewIsogeny3() + strat := pub.params.B.IsogenyStrategy + stratSz := len(strat) + + for j := 1; j <= stratSz; j++ { + for i <= stratSz-j { + points = append(points, *xR) + indices = append(indices, i) + + k := strat[sidx] + sidx++ + Pow3k(xR, &cparam, k) + i += int(k) + } + + cparam = phi.GenerateCurve(xR) + for k := 0; k < len(points); k++ { + points[k] = phi.EvaluatePoint(&points[k]) + } + + // pop xR from points + *xR, points = points[len(points)-1], points[:len(points)-1] + i, indices = int(indices[len(indices)-1]), indices[:len(indices)-1] + } +} + +// Generate a public key in the 2-torsion group +func publicKeyGenA(prv *PrivateKey) (pub *PublicKey) { + var xPA, xQA, xRA ProjectivePoint + var xPB, xQB, xRB, xR ProjectivePoint + var invZP, invZQ, invZR Fp2 + var tmp ProjectiveCurveParameters + + pub = NewPublicKey(KeyVariant_SIDH_A) + var phi = NewIsogeny4() + + // Load points for A + xPA = ProjectivePoint{X: prv.params.A.Affine_P, Z: prv.params.OneFp2} + xQA = ProjectivePoint{X: prv.params.A.Affine_Q, Z: prv.params.OneFp2} + xRA = ProjectivePoint{X: prv.params.A.Affine_R, Z: prv.params.OneFp2} + + // Load points for B + xRB = ProjectivePoint{X: prv.params.B.Affine_R, Z: prv.params.OneFp2} + xQB = ProjectivePoint{X: prv.params.B.Affine_Q, Z: prv.params.OneFp2} + xPB = ProjectivePoint{X: prv.params.B.Affine_P, Z: prv.params.OneFp2} + + // Find isogeny kernel + tmp.C = pub.params.OneFp2 + xR = ScalarMul3Pt(&tmp, &xPA, &xQA, &xRA, prv.params.A.SecretBitLen, prv.Scalar) + + // Reset params object and travers isogeny tree + tmp.C = pub.params.OneFp2 + zeroize(&tmp.A) + traverseTreePublicKeyA(&tmp, &xR, &xPB, &xQB, &xRB, pub) + + // Secret isogeny + phi.GenerateCurve(&xR) + xPA = phi.EvaluatePoint(&xPB) + xQA = phi.EvaluatePoint(&xQB) + xRA = phi.EvaluatePoint(&xRB) + Fp2Batch3Inv(&xPA.Z, &xQA.Z, &xRA.Z, &invZP, &invZQ, &invZR) + + mul(&pub.affine_xP, &xPA.X, &invZP) + mul(&pub.affine_xQ, &xQA.X, &invZQ) + mul(&pub.affine_xQmP, &xRA.X, &invZR) + return +} + +// Generate a public key in the 3-torsion group +func publicKeyGenB(prv *PrivateKey) (pub *PublicKey) { + var xPB, xQB, xRB, xR ProjectivePoint + var xPA, xQA, xRA ProjectivePoint + var invZP, invZQ, invZR Fp2 + var tmp ProjectiveCurveParameters + + pub = NewPublicKey(prv.keyVariant) + var phi = NewIsogeny3() + + // Load points for B + xRB = ProjectivePoint{X: prv.params.B.Affine_R, Z: prv.params.OneFp2} + xQB = ProjectivePoint{X: prv.params.B.Affine_Q, Z: prv.params.OneFp2} + xPB = ProjectivePoint{X: prv.params.B.Affine_P, Z: prv.params.OneFp2} + + // Load points for A + xPA = ProjectivePoint{X: prv.params.A.Affine_P, Z: prv.params.OneFp2} + xQA = ProjectivePoint{X: prv.params.A.Affine_Q, Z: prv.params.OneFp2} + xRA = ProjectivePoint{X: prv.params.A.Affine_R, Z: prv.params.OneFp2} + + tmp.C = pub.params.OneFp2 + xR = ScalarMul3Pt(&tmp, &xPB, &xQB, &xRB, prv.params.B.SecretBitLen, prv.Scalar) + + tmp.C = pub.params.OneFp2 + zeroize(&tmp.A) + traverseTreePublicKeyB(&tmp, &xR, &xPA, &xQA, &xRA, pub) + + phi.GenerateCurve(&xR) + xPB = phi.EvaluatePoint(&xPA) + xQB = phi.EvaluatePoint(&xQA) + xRB = phi.EvaluatePoint(&xRA) + Fp2Batch3Inv(&xPB.Z, &xQB.Z, &xRB.Z, &invZP, &invZQ, &invZR) + + mul(&pub.affine_xP, &xPB.X, &invZP) + mul(&pub.affine_xQ, &xQB.X, &invZQ) + mul(&pub.affine_xQmP, &xRB.X, &invZR) + return +} + +// ----------------------------------------------------------------------------- +// Key agreement functions +// + +// Establishing shared keys in in 2-torsion group +func deriveSecretA(prv *PrivateKey, pub *PublicKey) []byte { + var sharedSecret = make([]byte, pub.params.SharedSecretSize) + var cparam ProjectiveCurveParameters + var xP, xQ, xQmP ProjectivePoint + var xR ProjectivePoint + var phi = NewIsogeny4() + var jInv Fp2 + + // Recover curve coefficients + cparam.C = pub.params.OneFp2 + RecoverCoordinateA(&cparam, &pub.affine_xP, &pub.affine_xQ, &pub.affine_xQmP) + + // Find kernel of the morphism + xP = ProjectivePoint{X: pub.affine_xP, Z: pub.params.OneFp2} + xQ = ProjectivePoint{X: pub.affine_xQ, Z: pub.params.OneFp2} + xQmP = ProjectivePoint{X: pub.affine_xQmP, Z: pub.params.OneFp2} + xR = ScalarMul3Pt(&cparam, &xP, &xQ, &xQmP, pub.params.A.SecretBitLen, prv.Scalar) + + // Traverse isogeny tree + traverseTreeSharedKeyA(&cparam, &xR, pub) + + // Calculate j-invariant on isogeneus curve + c := phi.GenerateCurve(&xR) + RecoverCurveCoefficients4(&cparam, &c) + Jinvariant(&cparam, &jInv) + convFp2ToBytes(sharedSecret, &jInv) + return sharedSecret +} + +// Establishing shared keys in in 3-torsion group +func deriveSecretB(prv *PrivateKey, pub *PublicKey) []byte { + var sharedSecret = make([]byte, pub.params.SharedSecretSize) + var xP, xQ, xQmP ProjectivePoint + var xR ProjectivePoint + var cparam ProjectiveCurveParameters + var phi = NewIsogeny3() + var jInv Fp2 + + // Recover curve coefficients + cparam.C = pub.params.OneFp2 + RecoverCoordinateA(&cparam, &pub.affine_xP, &pub.affine_xQ, &pub.affine_xQmP) + + // Find kernel of the morphism + xP = ProjectivePoint{X: pub.affine_xP, Z: pub.params.OneFp2} + xQ = ProjectivePoint{X: pub.affine_xQ, Z: pub.params.OneFp2} + xQmP = ProjectivePoint{X: pub.affine_xQmP, Z: pub.params.OneFp2} + xR = ScalarMul3Pt(&cparam, &xP, &xQ, &xQmP, pub.params.B.SecretBitLen, prv.Scalar) + + // Traverse isogeny tree + traverseTreeSharedKeyB(&cparam, &xR, pub) + + // Calculate j-invariant on isogeneus curve + c := phi.GenerateCurve(&xR) + RecoverCurveCoefficients3(&cparam, &c) + Jinvariant(&cparam, &jInv) + convFp2ToBytes(sharedSecret, &jInv) + return sharedSecret +} + +func encrypt(skA *PrivateKey, pkA, pkB *PublicKey, ptext []byte) ([]byte, error) { + var n [40]byte // n can is max 320-bit (see 1.4 of [SIKE]) + var ptextLen = len(ptext) + + if pkB.keyVariant != KeyVariant_SIKE { + return nil, errors.New("wrong key type") + } + + j, err := DeriveSecret(skA, pkB) + if err != nil { + return nil, err + } + + hashMac(n[:ptextLen], j, F) + for i, _ := range ptext { + n[i] ^= ptext[i] + } + + ret := make([]byte, pkA.Size()+ptextLen) + copy(ret, pkA.Export()) + copy(ret[pkA.Size():], n[:ptextLen]) + return ret, nil +} + +// NewPrivateKey initializes private key. +// Usage of this function guarantees that the object is correctly initialized. +func NewPrivateKey(v KeyVariant) *PrivateKey { + prv := &PrivateKey{key: key{params: &Params, keyVariant: v}} + if (v & KeyVariant_SIDH_A) == KeyVariant_SIDH_A { + prv.Scalar = make([]byte, prv.params.A.SecretByteLen) + } else { + prv.Scalar = make([]byte, prv.params.B.SecretByteLen) + } + if v == KeyVariant_SIKE { + prv.S = make([]byte, prv.params.MsgLen) + } + return prv +} + +// NewPublicKey initializes public key. +// Usage of this function guarantees that the object is correctly initialized. +func NewPublicKey(v KeyVariant) *PublicKey { + return &PublicKey{key: key{params: &Params, keyVariant: v}} +} + +// Import clears content of the public key currently stored in the structure +// and imports key stored in the byte string. Returns error in case byte string +// size is wrong. Doesn't perform any validation. +func (pub *PublicKey) Import(input []byte) error { + if len(input) != pub.Size() { + return errors.New("sidh: input to short") + } + ssSz := pub.params.SharedSecretSize + convBytesToFp2(&pub.affine_xP, input[0:ssSz]) + convBytesToFp2(&pub.affine_xQ, input[ssSz:2*ssSz]) + convBytesToFp2(&pub.affine_xQmP, input[2*ssSz:3*ssSz]) + return nil +} + +// Exports currently stored key. In case structure hasn't been filled with key data +// returned byte string is filled with zeros. +func (pub *PublicKey) Export() []byte { + output := make([]byte, pub.params.PublicKeySize) + ssSz := pub.params.SharedSecretSize + convFp2ToBytes(output[0:ssSz], &pub.affine_xP) + convFp2ToBytes(output[ssSz:2*ssSz], &pub.affine_xQ) + convFp2ToBytes(output[2*ssSz:3*ssSz], &pub.affine_xQmP) + return output +} + +// Size returns size of the public key in bytes +func (pub *PublicKey) Size() int { + return pub.params.PublicKeySize +} + +// Exports currently stored key. In case structure hasn't been filled with key data +// returned byte string is filled with zeros. +func (prv *PrivateKey) Export() []byte { + ret := make([]byte, len(prv.Scalar)+len(prv.S)) + copy(ret, prv.S) + copy(ret[len(prv.S):], prv.Scalar) + return ret +} + +// Size returns size of the private key in bytes +func (prv *PrivateKey) Size() int { + tmp := len(prv.Scalar) + if prv.keyVariant == KeyVariant_SIKE { + tmp += int(prv.params.MsgLen) + } + return tmp +} + +// Import clears content of the private key currently stored in the structure +// and imports key from octet string. In case of SIKE, the random value 'S' +// must be prepended to the value of actual private key (see SIKE spec for details). +// Function doesn't import public key value to PrivateKey object. +func (prv *PrivateKey) Import(input []byte) error { + if len(input) != prv.Size() { + return errors.New("sidh: input to short") + } + copy(prv.S, input[:len(prv.S)]) + copy(prv.Scalar, input[len(prv.S):]) + return nil +} + +// Generates random private key for SIDH or SIKE. Generated value is +// formed as little-endian integer from key-space <2^(e2-1)..2^e2 - 1> +// for KeyVariant_A or <2^(s-1)..2^s - 1>, where s = floor(log_2(3^e3)), +// for KeyVariant_B. +// +// Returns error in case user provided RNG fails. +func (prv *PrivateKey) Generate(rand io.Reader) error { + var err error + var dp *DomainParams + + if (prv.keyVariant & KeyVariant_SIDH_A) == KeyVariant_SIDH_A { + dp = &prv.params.A + } else { + dp = &prv.params.B + } + + if prv.keyVariant == KeyVariant_SIKE { + _, err = io.ReadFull(rand, prv.S) + } + + // Private key generation takes advantage of the fact that keyspace for secret + // key is (0, 2^x - 1), for some possitivite value of 'x' (see SIKE, 1.3.8). + // It means that all bytes in the secret key, but the last one, can take any + // value between <0x00,0xFF>. Similarily for the last byte, but generation + // needs to chop off some bits, to make sure generated value is an element of + // a key-space. + _, err = io.ReadFull(rand, prv.Scalar) + if err != nil { + return err + } + prv.Scalar[len(prv.Scalar)-1] &= (1 << (dp.SecretBitLen % 8)) - 1 + // Make sure scalar is SecretBitLen long. SIKE spec says that key + // space starts from 0, but I'm not confortable with having low + // value scalars used for private keys. It is still secrure as per + // table 5.1 in [SIKE]. + prv.Scalar[len(prv.Scalar)-1] |= 1 << ((dp.SecretBitLen % 8) - 1) + return err +} + +// Generates public key. +// +// Constant time. +func (prv *PrivateKey) GeneratePublicKey() *PublicKey { + if (prv.keyVariant & KeyVariant_SIDH_A) == KeyVariant_SIDH_A { + return publicKeyGenA(prv) + } + return publicKeyGenB(prv) +} + +// Computes a shared secret which is a j-invariant. Function requires that pub has +// different KeyVariant than prv. Length of returned output is 2*ceil(log_2 P)/8), +// where P is a prime defining finite field. +// +// It's important to notice that each keypair must not be used more than once +// to calculate shared secret. +// +// Function may return error. This happens only in case provided input is invalid. +// Constant time for properly initialized private and public key. +func DeriveSecret(prv *PrivateKey, pub *PublicKey) ([]byte, error) { + + if (pub == nil) || (prv == nil) { + return nil, errors.New("sidh: invalid arguments") + } + + if (pub.keyVariant == prv.keyVariant) || (pub.params.Id != prv.params.Id) { + return nil, errors.New("sidh: public and private are incompatbile") + } + + if (prv.keyVariant & KeyVariant_SIDH_A) == KeyVariant_SIDH_A { + return deriveSecretA(prv, pub), nil + } else { + return deriveSecretB(prv, pub), nil + } +} + +// Uses SIKE public key to encrypt plaintext. Requires cryptographically secure PRNG +// Returns ciphertext in case encryption succeeds. Returns error in case PRNG fails +// or wrongly formatted input was provided. +func Encrypt(rng io.Reader, pub *PublicKey, ptext []byte) ([]byte, error) { + var ptextLen = len(ptext) + // c1 must be security level + 64 bits (see [SIKE] 1.4 and 4.3.3) + if ptextLen != (pub.params.KemSize + 8) { + return nil, errors.New("Unsupported message length") + } + + skA := NewPrivateKey(KeyVariant_SIDH_A) + err := skA.Generate(rng) + if err != nil { + return nil, err + } + + pkA := skA.GeneratePublicKey() + return encrypt(skA, pkA, pub, ptext) +} + +// Uses SIKE private key to decrypt ciphertext. Returns plaintext in case +// decryption succeeds or error in case unexptected input was provided. +// Constant time +func Decrypt(prv *PrivateKey, ctext []byte) ([]byte, error) { + var n [40]byte // n can is max 320-bit (see 1.4 of [SIKE]) + var c1_len int + var pk_len = prv.params.PublicKeySize + + if prv.keyVariant != KeyVariant_SIKE { + return nil, errors.New("wrong key type") + } + + // ctext is a concatenation of (pubkey_A || c1=ciphertext) + // it must be security level + 64 bits (see [SIKE] 1.4 and 4.3.3) + c1_len = len(ctext) - pk_len + if c1_len != (int(prv.params.KemSize) + 8) { + return nil, errors.New("wrong size of cipher text") + } + + c0 := NewPublicKey(KeyVariant_SIDH_A) + err := c0.Import(ctext[:pk_len]) + if err != nil { + return nil, err + } + j, err := DeriveSecret(prv, c0) + if err != nil { + return nil, err + } + + hashMac(n[:c1_len], j, F) + for i, _ := range n[:c1_len] { + n[i] ^= ctext[pk_len+i] + } + return n[:c1_len], nil +} + +// Encapsulation receives the public key and generates SIKE ciphertext and shared secret. +// The generated ciphertext is used for authentication. +// The rng must be cryptographically secure PRNG. +// Error is returned in case PRNG fails or wrongly formatted input was provided. +func Encapsulate(rng io.Reader, pub *PublicKey) (ctext []byte, secret []byte, err error) { + // Buffer for random, secret message + var ptext = make([]byte, pub.params.MsgLen) + // r = G(ptext||pub) + var r = make([]byte, pub.params.A.SecretByteLen) + // Resulting shared secret + secret = make([]byte, pub.params.KemSize) + + // Generate ephemeral value + _, err = io.ReadFull(rng, ptext) + if err != nil { + return nil, nil, err + } + + // must be big enough to store ptext+c0+c1 + var hmac_key = make([]byte, pub.Size()+2*Params.MsgLen) + copy(hmac_key, ptext) + copy(hmac_key[len(ptext):], pub.Export()) + hashMac(r, hmac_key[:len(ptext)+pub.Size()], G) + // Ensure bitlength is not bigger than to 2^e2-1 + r[len(r)-1] &= (1 << (pub.params.A.SecretBitLen % 8)) - 1 + + // (c0 || c1) = Enc(pkA, ptext; r) + skA := NewPrivateKey(KeyVariant_SIDH_A) + err = skA.Import(r) + if err != nil { + return nil, nil, err + } + + pkA := skA.GeneratePublicKey() + ctext, err = encrypt(skA, pkA, pub, ptext) + if err != nil { + return nil, nil, err + } + + // K = H(ptext||(c0||c1)) + copy(hmac_key, ptext) + copy(hmac_key[len(ptext):], ctext) + hashMac(secret, hmac_key[:len(ptext)+len(ctext)], H) + return ctext, secret, nil +} + +// Decapsulate given the keypair and ciphertext as inputs, Decapsulate outputs a shared +// secret if plaintext verifies correctly, otherwise function outputs random value. +// Decapsulation may fail in case input is wrongly formatted. +// Constant time for properly initialized input. +func Decapsulate(prv *PrivateKey, pub *PublicKey, ctext []byte) ([]byte, error) { + var r = make([]byte, pub.params.A.SecretByteLen) + // Resulting shared secret + var secret = make([]byte, pub.params.KemSize) + var skA = NewPrivateKey(KeyVariant_SIDH_A) + + m, err := Decrypt(prv, ctext) + if err != nil { + return nil, err + } + + // r' = G(m'||pub) + var hmac_key = make([]byte, pub.Size()+2*Params.MsgLen) + copy(hmac_key, m) + copy(hmac_key[len(m):], pub.Export()) + hashMac(r, hmac_key[:len(m)+pub.Size()], G) + // Ensure bitlength is not bigger than 2^e2-1 + r[len(r)-1] &= (1 << (pub.params.A.SecretBitLen % 8)) - 1 + + // Never fails + skA.Import(r) + + // Never fails + pkA := skA.GeneratePublicKey() + c0 := pkA.Export() + + if subtle.ConstantTimeCompare(c0, ctext[:len(c0)]) == 1 { + copy(hmac_key, m) + } else { + // S is chosen at random when generating a key and unknown to other party. It + // may seem weird, but it's correct. It is important that S is unpredictable + // to other party. Without this check, it is possible to recover a secret, by + // providing series of invalid ciphertexts. It is also important that in case + // + // See more details in "On the security of supersingular isogeny cryptosystems" + // (S. Galbraith, et al., 2016, ePrint #859). + copy(hmac_key, prv.S) + } + copy(hmac_key[len(m):], ctext) + hashMac(secret, hmac_key[:len(m)+len(ctext)], H) + return secret, nil +} diff --git a/third_party/boringssl/kit/src/ssl/test/runner/sike/sike_test.go b/third_party/boringssl/kit/src/ssl/test/runner/sike/sike_test.go new file mode 100644 index 00000000..28135044 --- /dev/null +++ b/third_party/boringssl/kit/src/ssl/test/runner/sike/sike_test.go @@ -0,0 +1,691 @@ +// Copyright (c) 2019, Cloudflare Inc. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +package sike + +import ( + "bufio" + "bytes" + "crypto/rand" + "encoding/hex" + "math/big" + "strings" + "testing" +) + +var tdata = struct { + name string + PrB_sidh string + PkB_sidh string + PkB_sike string + PrB_sike string + PrA_sike string + PkA_sike string +}{ + name: "P-503", + PkB_sike: "68460C22466E95864CFEA7B5D9077E768FF4F9ED69AE56D7CF3F236FB06B31020EEE34B5B572CEA5DDF20B531966AA8F5F3ACC0C6D1CE04EEDC30FD1F1233E2D96FE60C6D638FC646EAF2E2246F1AEC96859CE874A1F029A78F9C978CD6B22114A0D5AB20101191FD923E80C76908B1498B9D0200065CCA09159A0C65A1E346CC6470314FE78388DAA89DD08EC67DBE63C1F606674ACC49EBF9FDBB2B898B3CE733113AA6F942DB401A76D629CE6EE6C0FDAF4CFB1A5E366DB66C17B3923A1B7FB26A3FF25B9018869C674D3DEF4AF269901D686FE4647F9D2CDB2CEB3AFA305B27C885F037ED167F595066C21E7DD467D8332B934A5102DA5F13332DFA356B82156A0BB2E7E91C6B85B7D1E381BC9E3F0FC4DB9C36016D9ECEC415D7E977E9AC29910D934BA2FE4EE49D3B387607A4E1AFABF495FB86A77194626589E802FF5167C7A25C542C1EAD25A6E0AA931D94F2F9AFD3DBDF222E651F729A90E77B20974905F1E65E041CE6C95AAB3E1F22D332E0A5DE9C5DB3D9C7A38", + PrB_sike: "80FC55DA74DEFE3113487B80841E678AF9ED4E0599CF07353A4AB93971C090A0" + + "A9402C9DC98AC6DC8F5FDE5E970AE22BA48A400EFC72851C", + PrB_sidh: "A885A8B889520A6DBAD9FB33365E5B77FDED629440A16A533F259A510F63A822", + PrA_sike: "B0AD510708F4ABCF3E0D97DC2F2FF112D9D2AAE49D97FFD1E4267F21C6E71C03", + PkA_sike: "A6BADBA04518A924B20046B59AC197DCDF0EA48014C9E228C4994CCA432F360E" + + "2D527AFB06CA7C96EE5CEE19BAD53BF9218A3961CAD7EC092BD8D9EBB22A3D51" + + "33008895A3F1F6A023F91E0FE06A00A622FD6335DAC107F8EC4283DC2632F080" + + "4E64B390DAD8A2572F1947C67FDF4F8787D140CE2C6B24E752DA9A195040EDFA" + + "C27333FAE97DBDEB41DA9EEB2DB067AE7DA8C58C0EF57AEFC18A3D6BD0576FF2" + + "F1CFCAEC50C958331BF631F3D2E769790C7B6DF282B74BBC02998AD10F291D47" + + "C5A762FF84253D3B3278BDF20C8D4D4AA317BE401B884E26A1F02C7308AADB68" + + "20EBDB0D339F5A63346F3B40CACED72F544DAF51566C6E807D0E6E1E38514342" + + "432661DC9564DA07548570E256688CD9E8060D8775F95D501886D958588CACA0" + + "9F2D2AE1913F996E76AF63E31A179A7A7D2A46EDA03B2BCCF9020A5AA15F9A28" + + "9340B33F3AE7F97360D45F8AE1B9DD48779A57E8C45B50A02C00349CD1C58C55" + + "1D68BC2A75EAFED944E8C599C288037181E997471352E24C952B", + PkB_sidh: "244AF1F367C2C33912750A98497CC8214BC195BD52BD76513D32ACE4B75E31F0" + + "281755C265F5565C74E3C04182B9C244071859C8588CC7F09547CEFF8F7705D2" + + "60CE87D6BFF914EE7DBE4B9AF051CA420062EEBDF043AF58184495026949B068" + + "98A47046BFAE8DF3B447746184AF550553BB5D266D6E1967ACA33CAC5F399F90" + + "360D70867F2C71EF6F94FF915C7DA8BC9549FB7656E691DAEFC93CF56876E482" + + "CA2F8BE2D6CDCC374C31AD8833CABE997CC92305F38497BEC4DFD1821B004FEC" + + "E16448F9A24F965EFE409A8939EEA671633D9FFCF961283E59B8834BDF7EDDB3" + + "05D6275B61DA6692325432A0BAA074FC7C1F51E76208AB193A57520D40A76334" + + "EE5712BDC3E1EFB6103966F2329EDFF63082C4DFCDF6BE1C5A048630B81871B8" + + "83B735748A8FD4E2D9530C272163AB18105B10015CA7456202FE1C9B92CEB167" + + "5EAE1132E582C88E47ED87B363D45F05BEA714D5E9933D7AF4071CBB5D49008F" + + "3E3DAD7DFF935EE509D5DE561842B678CCEB133D62E270E9AC3E", +} + +/* ------------------------------------------------------------------------- + Helpers + -------------------------------------------------------------------------*/ +// Fail if err !=nil. Display msg as an error message +func checkErr(t testing.TB, err error, msg string) { + if err != nil { + t.Error(msg) + } +} + +// Utility used for running same test with all registered prime fields +type MultiIdTestingFunc func(testing.TB) + +// Converts string to private key +func convToPrv(s string, v KeyVariant) *PrivateKey { + key := NewPrivateKey(v) + hex, e := hex.DecodeString(s) + if e != nil { + panic("non-hex number provided") + } + e = key.Import(hex) + if e != nil { + panic("Can't import private key") + } + return key +} + +// Converts string to public key +func convToPub(s string, v KeyVariant) *PublicKey { + key := NewPublicKey(v) + hex, e := hex.DecodeString(s) + if e != nil { + panic("non-hex number provided") + } + e = key.Import(hex) + if e != nil { + panic("Can't import public key") + } + return key +} + +/* ------------------------------------------------------------------------- + Unit tests + -------------------------------------------------------------------------*/ +func TestKeygen(t *testing.T) { + alicePrivate := convToPrv(tdata.PrA_sike, KeyVariant_SIDH_A) + bobPrivate := convToPrv(tdata.PrB_sidh, KeyVariant_SIDH_B) + expPubA := convToPub(tdata.PkA_sike, KeyVariant_SIDH_A) + expPubB := convToPub(tdata.PkB_sidh, KeyVariant_SIDH_B) + + pubA := alicePrivate.GeneratePublicKey() + pubB := bobPrivate.GeneratePublicKey() + + if !bytes.Equal(pubA.Export(), expPubA.Export()) { + t.Fatalf("unexpected value of public key A") + } + if !bytes.Equal(pubB.Export(), expPubB.Export()) { + t.Fatalf("unexpected value of public key B") + } +} + +func TestImportExport(t *testing.T) { + var err error + a := NewPublicKey(KeyVariant_SIDH_A) + b := NewPublicKey(KeyVariant_SIDH_B) + + // Import keys + a_hex, err := hex.DecodeString(tdata.PkA_sike) + checkErr(t, err, "invalid hex-number provided") + + err = a.Import(a_hex) + checkErr(t, err, "import failed") + + b_hex, err := hex.DecodeString(tdata.PkB_sike) + checkErr(t, err, "invalid hex-number provided") + + err = b.Import(b_hex) + checkErr(t, err, "import failed") + + // Export and check if same + if !bytes.Equal(b.Export(), b_hex) || !bytes.Equal(a.Export(), a_hex) { + t.Fatalf("export/import failed") + } + + if (len(b.Export()) != b.Size()) || (len(a.Export()) != a.Size()) { + t.Fatalf("wrong size of exported keys") + } +} + +func testPrivateKeyBelowMax(t testing.TB) { + for variant, keySz := range map[KeyVariant]*DomainParams{ + KeyVariant_SIDH_A: &Params.A, + KeyVariant_SIDH_B: &Params.B} { + + func(v KeyVariant, dp *DomainParams) { + var blen = int(dp.SecretByteLen) + var prv = NewPrivateKey(v) + + // Calculate either (2^e2 - 1) or (2^s - 1); where s=ceil(log_2(3^e3))) + maxSecertVal := big.NewInt(int64(dp.SecretBitLen)) + maxSecertVal.Exp(big.NewInt(int64(2)), maxSecertVal, nil) + maxSecertVal.Sub(maxSecertVal, big.NewInt(1)) + + // Do same test 1000 times + for i := 0; i < 1000; i++ { + err := prv.Generate(rand.Reader) + checkErr(t, err, "Private key generation") + + // Convert to big-endian, as that's what expected by (*Int)SetBytes() + secretBytes := prv.Export() + for i := 0; i < int(blen/2); i++ { + tmp := secretBytes[i] ^ secretBytes[blen-i-1] + secretBytes[i] = tmp ^ secretBytes[i] + secretBytes[blen-i-1] = tmp ^ secretBytes[blen-i-1] + } + prvBig := new(big.Int).SetBytes(secretBytes) + // Check if generated key is bigger than acceptable + if prvBig.Cmp(maxSecertVal) == 1 { + t.Error("Generated private key is wrong") + } + } + }(variant, keySz) + } +} + +func testKeyAgreement(t *testing.T, pkA, prA, pkB, prB string) { + var e error + + // KeyPairs + alicePublic := convToPub(pkA, KeyVariant_SIDH_A) + bobPublic := convToPub(pkB, KeyVariant_SIDH_B) + alicePrivate := convToPrv(prA, KeyVariant_SIDH_A) + bobPrivate := convToPrv(prB, KeyVariant_SIDH_B) + + // Do actual test + s1, e := DeriveSecret(bobPrivate, alicePublic) + checkErr(t, e, "derivation s1") + s2, e := DeriveSecret(alicePrivate, bobPublic) + checkErr(t, e, "derivation s1") + + if !bytes.Equal(s1[:], s2[:]) { + t.Fatalf("two shared keys: %d, %d do not match", s1, s2) + } + + // Negative case + dec, e := hex.DecodeString(tdata.PkA_sike) + if e != nil { + t.FailNow() + } + dec[0] = ^dec[0] + e = alicePublic.Import(dec) + if e != nil { + t.FailNow() + } + + s1, e = DeriveSecret(bobPrivate, alicePublic) + checkErr(t, e, "derivation of s1 failed") + s2, e = DeriveSecret(alicePrivate, bobPublic) + checkErr(t, e, "derivation of s2 failed") + + if bytes.Equal(s1[:], s2[:]) { + t.Fatalf("The two shared keys: %d, %d match", s1, s2) + } +} + +func TestDerivationRoundTrip(t *testing.T) { + var err error + + prvA := NewPrivateKey(KeyVariant_SIDH_A) + prvB := NewPrivateKey(KeyVariant_SIDH_B) + + // Generate private keys + err = prvA.Generate(rand.Reader) + checkErr(t, err, "key generation failed") + err = prvB.Generate(rand.Reader) + checkErr(t, err, "key generation failed") + + // Generate public keys + pubA := prvA.GeneratePublicKey() + pubB := prvB.GeneratePublicKey() + + // Derive shared secret + s1, err := DeriveSecret(prvB, pubA) + checkErr(t, err, "") + + s2, err := DeriveSecret(prvA, pubB) + checkErr(t, err, "") + + if !bytes.Equal(s1[:], s2[:]) { + t.Fatalf("Two shared keys: \n%X, \n%X do not match", s1, s2) + } +} + +// Encrypt, Decrypt, check if input/output plaintext is the same +func testPKERoundTrip(t testing.TB, id uint8) { + // Message to be encrypted + var msg = make([]byte, Params.MsgLen) + for i, _ := range msg { + msg[i] = byte(i) + } + + // Import keys + pkB := NewPublicKey(KeyVariant_SIKE) + skB := NewPrivateKey(KeyVariant_SIKE) + pk_hex, err := hex.DecodeString(tdata.PkB_sike) + if err != nil { + t.Fatal(err) + } + sk_hex, err := hex.DecodeString(tdata.PrB_sike) + if err != nil { + t.Fatal(err) + } + if pkB.Import(pk_hex) != nil || skB.Import(sk_hex) != nil { + t.Error("Import") + } + + ct, err := Encrypt(rand.Reader, pkB, msg[:]) + if err != nil { + t.Fatal(err) + } + pt, err := Decrypt(skB, ct) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(pt[:], msg[:]) { + t.Errorf("Decryption failed \n got : %X\n exp : %X", pt, msg) + } +} + +// Generate key and check if can encrypt +func TestPKEKeyGeneration(t *testing.T) { + // Message to be encrypted + var msg = make([]byte, Params.MsgLen) + var err error + for i, _ := range msg { + msg[i] = byte(i) + } + + sk := NewPrivateKey(KeyVariant_SIKE) + err = sk.Generate(rand.Reader) + checkErr(t, err, "PEK key generation") + pk := sk.GeneratePublicKey() + + // Try to encrypt + ct, err := Encrypt(rand.Reader, pk, msg[:]) + checkErr(t, err, "PEK encryption") + pt, err := Decrypt(sk, ct) + checkErr(t, err, "PEK key decryption") + + if !bytes.Equal(pt[:], msg[:]) { + t.Fatalf("Decryption failed \n got : %X\n exp : %X", pt, msg) + } +} + +func TestNegativePKE(t *testing.T) { + var msg [40]byte + var err error + + // Generate key + sk := NewPrivateKey(KeyVariant_SIKE) + err = sk.Generate(rand.Reader) + checkErr(t, err, "key generation") + + pk := sk.GeneratePublicKey() + + // bytelen(msg) - 1 + ct, err := Encrypt(rand.Reader, pk, msg[:Params.KemSize+8-1]) + if err == nil { + t.Fatal("Error hasn't been returned") + } + if ct != nil { + t.Fatal("Ciphertext must be nil") + } + + // KemSize - 1 + pt, err := Decrypt(sk, msg[:Params.KemSize+8-1]) + if err == nil { + t.Fatal("Error hasn't been returned") + } + if pt != nil { + t.Fatal("Ciphertext must be nil") + } +} + +func testKEMRoundTrip(t *testing.T, pkB, skB []byte) { + // Import keys + pk := NewPublicKey(KeyVariant_SIKE) + sk := NewPrivateKey(KeyVariant_SIKE) + if pk.Import(pkB) != nil || sk.Import(skB) != nil { + t.Error("Import failed") + } + + ct, ss_e, err := Encapsulate(rand.Reader, pk) + if err != nil { + t.Error("Encapsulate failed") + } + + ss_d, err := Decapsulate(sk, pk, ct) + if err != nil { + t.Error("Decapsulate failed") + } + if !bytes.Equal(ss_e, ss_d) { + t.Error("Shared secrets from decapsulation and encapsulation differ") + } +} + +func TestKEMRoundTrip(t *testing.T) { + pk, err := hex.DecodeString(tdata.PkB_sike) + checkErr(t, err, "public key B not a number") + sk, err := hex.DecodeString(tdata.PrB_sike) + checkErr(t, err, "private key B not a number") + testKEMRoundTrip(t, pk, sk) +} + +func TestKEMKeyGeneration(t *testing.T) { + // Generate key + sk := NewPrivateKey(KeyVariant_SIKE) + checkErr(t, sk.Generate(rand.Reader), "error: key generation") + pk := sk.GeneratePublicKey() + + // calculated shared secret + ct, ss_e, err := Encapsulate(rand.Reader, pk) + checkErr(t, err, "encapsulation failed") + ss_d, err := Decapsulate(sk, pk, ct) + checkErr(t, err, "decapsulation failed") + + if !bytes.Equal(ss_e, ss_d) { + t.Fatalf("KEM failed \n encapsulated: %X\n decapsulated: %X", ss_d, ss_e) + } +} + +func TestNegativeKEM(t *testing.T) { + sk := NewPrivateKey(KeyVariant_SIKE) + checkErr(t, sk.Generate(rand.Reader), "error: key generation") + pk := sk.GeneratePublicKey() + + ct, ss_e, err := Encapsulate(rand.Reader, pk) + checkErr(t, err, "pre-requisite for a test failed") + + ct[0] = ct[0] - 1 + ss_d, err := Decapsulate(sk, pk, ct) + checkErr(t, err, "decapsulation returns error when invalid ciphertext provided") + + if bytes.Equal(ss_e, ss_d) { + // no idea how this could ever happen, but it would be very bad + t.Error("critical error") + } + + // Try encapsulating with SIDH key + pkSidh := NewPublicKey(KeyVariant_SIDH_B) + prSidh := NewPrivateKey(KeyVariant_SIDH_B) + _, _, err = Encapsulate(rand.Reader, pkSidh) + if err == nil { + t.Error("encapsulation accepts SIDH public key") + } + // Try decapsulating with SIDH key + _, err = Decapsulate(prSidh, pk, ct) + if err == nil { + t.Error("decapsulation accepts SIDH private key key") + } +} + +// In case invalid ciphertext is provided, SIKE's decapsulation must +// return same (but unpredictable) result for a given key. +func TestNegativeKEMSameWrongResult(t *testing.T) { + sk := NewPrivateKey(KeyVariant_SIKE) + checkErr(t, sk.Generate(rand.Reader), "error: key generation") + pk := sk.GeneratePublicKey() + + ct, encSs, err := Encapsulate(rand.Reader, pk) + checkErr(t, err, "pre-requisite for a test failed") + + // make ciphertext wrong + ct[0] = ct[0] - 1 + decSs1, err := Decapsulate(sk, pk, ct) + checkErr(t, err, "pre-requisite for a test failed") + + // second decapsulation must be done with same, but imported private key + expSk := sk.Export() + + // creat new private key + sk = NewPrivateKey(KeyVariant_SIKE) + err = sk.Import(expSk) + checkErr(t, err, "import failed") + + // try decapsulating again. ss2 must be same as ss1 and different than + // original plaintext + decSs2, err := Decapsulate(sk, pk, ct) + checkErr(t, err, "pre-requisite for a test failed") + + if !bytes.Equal(decSs1, decSs2) { + t.Error("decapsulation is insecure") + } + + if bytes.Equal(encSs, decSs1) || bytes.Equal(encSs, decSs2) { + // this test requires that decapsulation returns wrong result + t.Errorf("test implementation error") + } +} + +func readAndCheckLine(r *bufio.Reader) []byte { + // Read next line from buffer + line, isPrefix, err := r.ReadLine() + if err != nil || isPrefix { + panic("Wrong format of input file") + } + + // Function expects that line is in format "KEY = HEX_VALUE". Get + // value, which should be a hex string + hexst := strings.Split(string(line), "=")[1] + hexst = strings.TrimSpace(hexst) + // Convert value to byte string + ret, err := hex.DecodeString(hexst) + if err != nil { + panic("Wrong format of input file") + } + return ret +} + +func testKeygenSIKE(pk, sk []byte, id uint8) bool { + // Import provided private key + var prvKey = NewPrivateKey(KeyVariant_SIKE) + if prvKey.Import(sk) != nil { + panic("sike test: can't load KAT") + } + + // Generate public key + pubKey := prvKey.GeneratePublicKey() + return bytes.Equal(pubKey.Export(), pk) +} + +func testDecapsulation(pk, sk, ct, ssExpected []byte, id uint8) bool { + var pubKey = NewPublicKey(KeyVariant_SIKE) + var prvKey = NewPrivateKey(KeyVariant_SIKE) + if pubKey.Import(pk) != nil || prvKey.Import(sk) != nil { + panic("sike test: can't load KAT") + } + + ssGot, err := Decapsulate(prvKey, pubKey, ct) + if err != nil { + panic("sike test: can't perform degcapsulation KAT") + } + + return bytes.Equal(ssGot, ssExpected) +} + +func TestKeyAgreement(t *testing.T) { + testKeyAgreement(t, tdata.PkA_sike, tdata.PrA_sike, tdata.PkB_sidh, tdata.PrB_sidh) +} + +// Same values as in sike_test.cc +func TestDecapsulation(t *testing.T) { + + var sk = [56]byte{ + 0xDB, 0xAF, 0x2C, 0x89, 0xCA, 0x5A, 0xD4, 0x9D, 0x4F, 0x13, + 0x40, 0xDF, 0x2D, 0xB1, 0x5F, 0x4C, 0x91, 0xA7, 0x1F, 0x0B, + 0x29, 0x15, 0x01, 0x59, 0xBC, 0x5F, 0x0B, 0x4A, 0x03, 0x27, + 0x6F, 0x18} + + var pk = []byte{ + 0x07, 0xAA, 0x51, 0x45, 0x3E, 0x1F, 0x53, 0x2A, 0x0A, 0x05, + 0x46, 0xF6, 0x54, 0x7F, 0x5D, 0x56, 0xD6, 0x76, 0xD3, 0xEA, + 0x4B, 0x6B, 0x01, 0x9B, 0x11, 0x72, 0x6F, 0x75, 0xEA, 0x34, + 0x3C, 0x28, 0x2C, 0x36, 0xFD, 0x77, 0xDA, 0xBE, 0xB6, 0x20, + 0x18, 0xC1, 0x93, 0x98, 0x18, 0x86, 0x30, 0x2F, 0x2E, 0xD2, + 0x00, 0x61, 0xFF, 0xAE, 0x78, 0xAE, 0xFB, 0x6F, 0x32, 0xAC, + 0x06, 0xBF, 0x35, 0xF6, 0xF7, 0x5B, 0x98, 0x26, 0x95, 0xC2, + 0xD8, 0xD6, 0x1C, 0x0E, 0x47, 0xDA, 0x76, 0xCE, 0xB5, 0xF1, + 0x19, 0xCC, 0x01, 0xE1, 0x17, 0xA9, 0x62, 0xF7, 0x82, 0x6C, + 0x25, 0x51, 0x25, 0xAE, 0xFE, 0xE3, 0xE2, 0xE1, 0x35, 0xAE, + 0x2E, 0x8F, 0x38, 0xE0, 0x7C, 0x74, 0x3C, 0x1D, 0x39, 0x91, + 0x1B, 0xC7, 0x9F, 0x8E, 0x33, 0x4E, 0x84, 0x19, 0xB8, 0xD9, + 0xC2, 0x71, 0x35, 0x02, 0x47, 0x3E, 0x79, 0xEF, 0x47, 0xE1, + 0xD8, 0x21, 0x96, 0x1F, 0x11, 0x59, 0x39, 0x34, 0x76, 0xEF, + 0x3E, 0xB7, 0x4E, 0xFB, 0x7C, 0x55, 0xA1, 0x85, 0xAA, 0xAB, + 0xAD, 0xF0, 0x09, 0xCB, 0xD1, 0xE3, 0x7C, 0x4F, 0x5D, 0x2D, + 0xE1, 0x13, 0xF0, 0x71, 0xD9, 0xE5, 0xF6, 0xAF, 0x7F, 0xC1, + 0x27, 0x95, 0x8D, 0x52, 0xD5, 0x96, 0x42, 0x38, 0x41, 0xF7, + 0x24, 0x3F, 0x3A, 0xB5, 0x7E, 0x11, 0xE4, 0xF9, 0x33, 0xEE, + 0x4D, 0xBE, 0x74, 0x48, 0xF9, 0x98, 0x04, 0x01, 0x16, 0xEB, + 0xA9, 0x0D, 0x61, 0xC6, 0xFD, 0x4C, 0xCF, 0x98, 0x84, 0x4A, + 0x94, 0xAC, 0x69, 0x2C, 0x02, 0x8B, 0xE3, 0xD1, 0x41, 0x0D, + 0xF2, 0x2D, 0x46, 0x1F, 0x57, 0x1C, 0x77, 0x86, 0x18, 0xE3, + 0x63, 0xDE, 0xF3, 0xE3, 0x02, 0x30, 0x54, 0x73, 0xAE, 0xC2, + 0x32, 0xA2, 0xCE, 0xEB, 0xCF, 0x81, 0x46, 0x54, 0x5C, 0xF4, + 0x5D, 0x2A, 0x03, 0x5D, 0x9C, 0xAE, 0xE0, 0x60, 0x03, 0x80, + 0x11, 0x30, 0xA5, 0xAA, 0xD1, 0x75, 0x67, 0xE0, 0x1C, 0x2B, + 0x6B, 0x5D, 0x83, 0xDE, 0x92, 0x9B, 0x0E, 0xD7, 0x11, 0x0F, + 0x00, 0xC4, 0x59, 0xE4, 0x81, 0x04, 0x3B, 0xEE, 0x5C, 0x04, + 0xD1, 0x0E, 0xD0, 0x67, 0xF5, 0xCC, 0xAA, 0x72, 0x73, 0xEA, + 0xC4, 0x76, 0x99, 0x3B, 0x4C, 0x90, 0x2F, 0xCB, 0xD8, 0x0A, + 0x5B, 0xEC, 0x0E, 0x0E, 0x1F, 0x59, 0xEA, 0x14, 0x8D, 0x34, + 0x53, 0x65, 0x4C, 0x1A, 0x59, 0xA8, 0x95, 0x66, 0x60, 0xBB, + 0xC4, 0xCC, 0x32, 0xA9, 0x8D, 0x2A, 0xAA, 0x14, 0x6F, 0x0F, + 0x81, 0x4D, 0x32, 0x02, 0xFD, 0x33, 0x58, 0x42, 0xCF, 0xF3, + 0x67, 0xD0, 0x9F, 0x0B, 0xB1, 0xCC, 0x18, 0xA5, 0xC4, 0x19, + 0xB6, 0x00, 0xED, 0xFA, 0x32, 0x1A, 0x5F, 0x67, 0xC8, 0xC3, + 0xEB, 0x0D, 0xB5, 0x9A, 0x36, 0x47, 0x82, 0x00, + } + + var ct = []byte{ + 0xE6, 0xB7, 0xE5, 0x7B, 0xA9, 0x19, 0xD1, 0x2C, 0xB8, 0x5C, + 0x7B, 0x66, 0x74, 0xB0, 0x71, 0xA1, 0xFF, 0x71, 0x7F, 0x4B, + 0xB5, 0xA6, 0xAF, 0x48, 0x32, 0x52, 0xD5, 0x82, 0xEE, 0x8A, + 0xBB, 0x08, 0x1E, 0xF6, 0xAC, 0x91, 0xA2, 0xCB, 0x6B, 0x6A, + 0x09, 0x2B, 0xD9, 0xC6, 0x27, 0xD6, 0x3A, 0x6B, 0x8D, 0xFC, + 0xB8, 0x90, 0x8F, 0x72, 0xB3, 0xFA, 0x7D, 0x34, 0x7A, 0xC4, + 0x7E, 0xE3, 0x30, 0xC5, 0xA0, 0xFE, 0x3D, 0x43, 0x14, 0x4E, + 0x3A, 0x14, 0x76, 0x3E, 0xFB, 0xDF, 0xE3, 0xA8, 0xE3, 0x5E, + 0x38, 0xF2, 0xE0, 0x39, 0x67, 0x60, 0xFD, 0xFB, 0xB4, 0x19, + 0xCD, 0xE1, 0x93, 0xA2, 0x06, 0xCC, 0x65, 0xCD, 0x6E, 0xC8, + 0xB4, 0x5E, 0x41, 0x4B, 0x6C, 0xA5, 0xF4, 0xE4, 0x9D, 0x52, + 0x8C, 0x25, 0x60, 0xDD, 0x3D, 0xA9, 0x7F, 0xF2, 0x88, 0xC1, + 0x0C, 0xEE, 0x97, 0xE0, 0xE7, 0x3B, 0xB7, 0xD3, 0x6F, 0x28, + 0x79, 0x2F, 0x50, 0xB2, 0x4F, 0x74, 0x3A, 0x0C, 0x88, 0x27, + 0x98, 0x3A, 0x27, 0xD3, 0x26, 0x83, 0x59, 0x49, 0x81, 0x5B, + 0x0D, 0xA7, 0x0C, 0x4F, 0xEF, 0xFB, 0x1E, 0xAF, 0xE9, 0xD2, + 0x1C, 0x10, 0x25, 0xEC, 0x9E, 0xFA, 0x57, 0x36, 0xAA, 0x3F, + 0xC1, 0xA3, 0x2C, 0xE9, 0xB5, 0xC9, 0xED, 0x72, 0x51, 0x4C, + 0x02, 0xB4, 0x7B, 0xB3, 0xED, 0x9F, 0x45, 0x03, 0x34, 0xAC, + 0x9A, 0x9E, 0x62, 0x5F, 0x82, 0x7A, 0x77, 0x34, 0xF9, 0x21, + 0x94, 0xD2, 0x38, 0x3D, 0x05, 0xF0, 0x8A, 0x60, 0x1C, 0xB7, + 0x1D, 0xF5, 0xB7, 0x53, 0x77, 0xD3, 0x9D, 0x3D, 0x70, 0x6A, + 0xCB, 0x18, 0x20, 0x6B, 0x29, 0x17, 0x3A, 0x6D, 0xA1, 0xB2, + 0x64, 0xDB, 0x6C, 0xE6, 0x1A, 0x95, 0xA7, 0xF4, 0x1A, 0x78, + 0x1D, 0xA2, 0x40, 0x15, 0x41, 0x59, 0xDD, 0xEE, 0x23, 0x57, + 0xCE, 0x36, 0x0D, 0x55, 0xBD, 0xB8, 0xFD, 0x0F, 0x35, 0xBD, + 0x5B, 0x92, 0xD6, 0x1C, 0x84, 0x8C, 0x32, 0x64, 0xA6, 0x5C, + 0x45, 0x18, 0x07, 0x6B, 0xF9, 0xA9, 0x43, 0x9A, 0x83, 0xCD, + 0xB5, 0xB3, 0xD9, 0x17, 0x99, 0x2C, 0x2A, 0x8B, 0xE0, 0x8E, + 0xAF, 0xA6, 0x4C, 0x95, 0xBB, 0x70, 0x60, 0x1A, 0x3A, 0x97, + 0xAA, 0x2F, 0x3D, 0x22, 0x83, 0xB7, 0x4F, 0x59, 0xED, 0x3F, + 0x4E, 0xF4, 0x19, 0xC6, 0x25, 0x0B, 0x0A, 0x5E, 0x21, 0xB9, + 0x91, 0xB8, 0x19, 0x84, 0x48, 0x78, 0xCE, 0x27, 0xBF, 0x41, + 0x89, 0xF6, 0x30, 0xFD, 0x6B, 0xD9, 0xB8, 0x1D, 0x72, 0x8A, + 0x56, 0xCC, 0x2F, 0x82, 0xE4, 0x46, 0x4D, 0x75, 0xD8, 0x92, + 0xE6, 0x9C, 0xCC, 0xD2, 0xCD, 0x35, 0xE4, 0xFC, 0x2A, 0x85, + 0x6B, 0xA9, 0xB2, 0x27, 0xC9, 0xA1, 0xFF, 0xB3, 0x96, 0x3E, + 0x59, 0xF6, 0x4C, 0x66, 0x56, 0x2E, 0xF5, 0x1B, 0x97, 0x32, + 0xB0, 0x71, 0x5A, 0x9C, 0x50, 0x4B, 0x6F, 0xC4, 0xCA, 0x94, + 0x75, 0x37, 0x46, 0x10, 0x12, 0x2F, 0x4F, 0xA3, 0x82, 0xCD, + 0xBD, 0x7C, + } + var ss_exp = []byte{ + 0x74, 0x3D, 0x25, 0x36, 0x00, 0x24, 0x63, 0x1A, 0x39, 0x1A, + 0xB4, 0xAD, 0x01, 0x17, 0x78, 0xE9} + + var prvObj = NewPrivateKey(KeyVariant_SIKE) + var pubObj = NewPublicKey(KeyVariant_SIKE) + + if pubObj.Import(pk) != nil || prvObj.Import(sk[:]) != nil { + t.Error("Can't import one of the keys") + } + + res, _ := Decapsulate(prvObj, pubObj, ct) + if !bytes.Equal(ss_exp, res) { + t.Error("Wrong decapsulation result") + } +} + +/* ------------------------------------------------------------------------- + Benchmarking + -------------------------------------------------------------------------*/ + +func BenchmarkSidhKeyAgreementP503(b *testing.B) { + // KeyPairs + alicePublic := convToPub(tdata.PkA_sike, KeyVariant_SIDH_A) + alicePrivate := convToPrv(tdata.PrA_sike, KeyVariant_SIDH_A) + bobPublic := convToPub(tdata.PkB_sidh, KeyVariant_SIDH_B) + bobPrivate := convToPrv(tdata.PrB_sidh, KeyVariant_SIDH_B) + + for i := 0; i < b.N; i++ { + // Derive shared secret + DeriveSecret(bobPrivate, alicePublic) + DeriveSecret(alicePrivate, bobPublic) + } +} + +func BenchmarkAliceKeyGenPrvP503(b *testing.B) { + prv := NewPrivateKey(KeyVariant_SIDH_A) + for n := 0; n < b.N; n++ { + prv.Generate(rand.Reader) + } +} + +func BenchmarkBobKeyGenPrvP503(b *testing.B) { + prv := NewPrivateKey(KeyVariant_SIDH_B) + for n := 0; n < b.N; n++ { + prv.Generate(rand.Reader) + } +} + +func BenchmarkAliceKeyGenPubP503(b *testing.B) { + prv := NewPrivateKey(KeyVariant_SIDH_A) + prv.Generate(rand.Reader) + for n := 0; n < b.N; n++ { + prv.GeneratePublicKey() + } +} + +func BenchmarkBobKeyGenPubP503(b *testing.B) { + prv := NewPrivateKey(KeyVariant_SIDH_B) + prv.Generate(rand.Reader) + for n := 0; n < b.N; n++ { + prv.GeneratePublicKey() + } +} + +func BenchmarkSharedSecretAliceP503(b *testing.B) { + aPr := convToPrv(tdata.PrA_sike, KeyVariant_SIDH_A) + bPk := convToPub(tdata.PkB_sike, KeyVariant_SIDH_B) + for n := 0; n < b.N; n++ { + DeriveSecret(aPr, bPk) + } +} + +func BenchmarkSharedSecretBobP503(b *testing.B) { + // m_B = 3*randint(0,3^238) + aPk := convToPub(tdata.PkA_sike, KeyVariant_SIDH_A) + bPr := convToPrv(tdata.PrB_sidh, KeyVariant_SIDH_B) + for n := 0; n < b.N; n++ { + DeriveSecret(bPr, aPk) + } +} diff --git a/third_party/boringssl/kit/src/ssl/test/test_config.cc b/third_party/boringssl/kit/src/ssl/test/test_config.cc index edbede62..4a25b1a2 100644 --- a/third_party/boringssl/kit/src/ssl/test/test_config.cc +++ b/third_party/boringssl/kit/src/ssl/test/test_config.cc @@ -51,179 +51,179 @@ T *FindField(TestConfig *config, const Flag (&flags)[N], const char *flag) { } const Flag kBoolFlags[] = { - { "-server", &TestConfig::is_server }, - { "-dtls", &TestConfig::is_dtls }, - { "-fallback-scsv", &TestConfig::fallback_scsv }, - { "-require-any-client-certificate", - &TestConfig::require_any_client_certificate }, - { "-false-start", &TestConfig::false_start }, - { "-async", &TestConfig::async }, - { "-write-different-record-sizes", - &TestConfig::write_different_record_sizes }, - { "-cbc-record-splitting", &TestConfig::cbc_record_splitting }, - { "-partial-write", &TestConfig::partial_write }, - { "-no-tls13", &TestConfig::no_tls13 }, - { "-no-tls12", &TestConfig::no_tls12 }, - { "-no-tls11", &TestConfig::no_tls11 }, - { "-no-tls1", &TestConfig::no_tls1 }, - { "-no-ticket", &TestConfig::no_ticket }, - { "-enable-channel-id", &TestConfig::enable_channel_id }, - { "-shim-writes-first", &TestConfig::shim_writes_first }, - { "-expect-session-miss", &TestConfig::expect_session_miss }, - { "-decline-alpn", &TestConfig::decline_alpn }, - { "-select-empty-alpn", &TestConfig::select_empty_alpn }, - { "-expect-extended-master-secret", - &TestConfig::expect_extended_master_secret }, - { "-enable-ocsp-stapling", &TestConfig::enable_ocsp_stapling }, - { "-enable-signed-cert-timestamps", - &TestConfig::enable_signed_cert_timestamps }, - { "-implicit-handshake", &TestConfig::implicit_handshake }, - { "-use-early-callback", &TestConfig::use_early_callback }, - { "-fail-early-callback", &TestConfig::fail_early_callback }, - { "-install-ddos-callback", &TestConfig::install_ddos_callback }, - { "-fail-ddos-callback", &TestConfig::fail_ddos_callback }, - { "-fail-cert-callback", &TestConfig::fail_cert_callback }, - { "-handshake-never-done", &TestConfig::handshake_never_done }, - { "-use-export-context", &TestConfig::use_export_context }, - { "-tls-unique", &TestConfig::tls_unique }, - { "-expect-ticket-renewal", &TestConfig::expect_ticket_renewal }, - { "-expect-no-session", &TestConfig::expect_no_session }, - { "-expect-ticket-supports-early-data", - &TestConfig::expect_ticket_supports_early_data }, - { "-use-ticket-callback", &TestConfig::use_ticket_callback }, - { "-renew-ticket", &TestConfig::renew_ticket }, - { "-enable-early-data", &TestConfig::enable_early_data }, - { "-check-close-notify", &TestConfig::check_close_notify }, - { "-shim-shuts-down", &TestConfig::shim_shuts_down }, - { "-verify-fail", &TestConfig::verify_fail }, - { "-verify-peer", &TestConfig::verify_peer }, - { "-verify-peer-if-no-obc", &TestConfig::verify_peer_if_no_obc }, - { "-expect-verify-result", &TestConfig::expect_verify_result }, - { "-renegotiate-once", &TestConfig::renegotiate_once }, - { "-renegotiate-freely", &TestConfig::renegotiate_freely }, - { "-renegotiate-ignore", &TestConfig::renegotiate_ignore }, - { "-forbid-renegotiation-after-handshake", - &TestConfig::forbid_renegotiation_after_handshake }, - { "-enable-all-curves", &TestConfig::enable_all_curves }, - { "-use-old-client-cert-callback", - &TestConfig::use_old_client_cert_callback }, - { "-send-alert", &TestConfig::send_alert }, - { "-peek-then-read", &TestConfig::peek_then_read }, - { "-enable-grease", &TestConfig::enable_grease }, - { "-use-exporter-between-reads", &TestConfig::use_exporter_between_reads }, - { "-retain-only-sha256-client-cert", - &TestConfig::retain_only_sha256_client_cert }, - { "-expect-sha256-client-cert", - &TestConfig::expect_sha256_client_cert }, - { "-read-with-unfinished-write", &TestConfig::read_with_unfinished_write }, - { "-expect-secure-renegotiation", - &TestConfig::expect_secure_renegotiation }, - { "-expect-no-secure-renegotiation", - &TestConfig::expect_no_secure_renegotiation }, - { "-expect-session-id", &TestConfig::expect_session_id }, - { "-expect-no-session-id", &TestConfig::expect_no_session_id }, - { "-expect-accept-early-data", &TestConfig::expect_accept_early_data }, - { "-expect-reject-early-data", &TestConfig::expect_reject_early_data }, - { "-expect-no-offer-early-data", &TestConfig::expect_no_offer_early_data }, - { "-no-op-extra-handshake", &TestConfig::no_op_extra_handshake }, - { "-handshake-twice", &TestConfig::handshake_twice }, - { "-allow-unknown-alpn-protos", &TestConfig::allow_unknown_alpn_protos }, - { "-enable-ed25519", &TestConfig::enable_ed25519 }, - { "-use-custom-verify-callback", &TestConfig::use_custom_verify_callback }, - { "-allow-false-start-without-alpn", - &TestConfig::allow_false_start_without_alpn }, - { "-ignore-tls13-downgrade", &TestConfig::ignore_tls13_downgrade }, - { "-expect-tls13-downgrade", &TestConfig::expect_tls13_downgrade }, - { "-handoff", &TestConfig::handoff }, - { "-no-rsa-pss-rsae-certs", &TestConfig::no_rsa_pss_rsae_certs }, - { "-use-ocsp-callback", &TestConfig::use_ocsp_callback }, - { "-set-ocsp-in-callback", &TestConfig::set_ocsp_in_callback }, - { "-decline-ocsp-callback", &TestConfig::decline_ocsp_callback }, - { "-fail-ocsp-callback", &TestConfig::fail_ocsp_callback }, - { "-install-cert-compression-algs", - &TestConfig::install_cert_compression_algs }, - { "-is-handshaker-supported", &TestConfig::is_handshaker_supported }, - { "-handshaker-resume", &TestConfig::handshaker_resume }, - { "-reverify-on-resume", &TestConfig::reverify_on_resume }, - { "-jdk11-workaround", &TestConfig::jdk11_workaround }, - { "-server-preference", &TestConfig::server_preference }, - { "-export-traffic-secrets", &TestConfig::export_traffic_secrets }, - { "-key-update", &TestConfig::key_update }, + {"-server", &TestConfig::is_server}, + {"-dtls", &TestConfig::is_dtls}, + {"-fallback-scsv", &TestConfig::fallback_scsv}, + {"-require-any-client-certificate", + &TestConfig::require_any_client_certificate}, + {"-false-start", &TestConfig::false_start}, + {"-async", &TestConfig::async}, + {"-write-different-record-sizes", + &TestConfig::write_different_record_sizes}, + {"-cbc-record-splitting", &TestConfig::cbc_record_splitting}, + {"-partial-write", &TestConfig::partial_write}, + {"-no-tls13", &TestConfig::no_tls13}, + {"-no-tls12", &TestConfig::no_tls12}, + {"-no-tls11", &TestConfig::no_tls11}, + {"-no-tls1", &TestConfig::no_tls1}, + {"-no-ticket", &TestConfig::no_ticket}, + {"-enable-channel-id", &TestConfig::enable_channel_id}, + {"-shim-writes-first", &TestConfig::shim_writes_first}, + {"-expect-session-miss", &TestConfig::expect_session_miss}, + {"-decline-alpn", &TestConfig::decline_alpn}, + {"-select-empty-alpn", &TestConfig::select_empty_alpn}, + {"-expect-extended-master-secret", + &TestConfig::expect_extended_master_secret}, + {"-enable-ocsp-stapling", &TestConfig::enable_ocsp_stapling}, + {"-enable-signed-cert-timestamps", + &TestConfig::enable_signed_cert_timestamps}, + {"-implicit-handshake", &TestConfig::implicit_handshake}, + {"-use-early-callback", &TestConfig::use_early_callback}, + {"-fail-early-callback", &TestConfig::fail_early_callback}, + {"-install-ddos-callback", &TestConfig::install_ddos_callback}, + {"-fail-ddos-callback", &TestConfig::fail_ddos_callback}, + {"-fail-cert-callback", &TestConfig::fail_cert_callback}, + {"-handshake-never-done", &TestConfig::handshake_never_done}, + {"-use-export-context", &TestConfig::use_export_context}, + {"-tls-unique", &TestConfig::tls_unique}, + {"-expect-ticket-renewal", &TestConfig::expect_ticket_renewal}, + {"-expect-no-session", &TestConfig::expect_no_session}, + {"-expect-ticket-supports-early-data", + &TestConfig::expect_ticket_supports_early_data}, + {"-use-ticket-callback", &TestConfig::use_ticket_callback}, + {"-renew-ticket", &TestConfig::renew_ticket}, + {"-enable-early-data", &TestConfig::enable_early_data}, + {"-check-close-notify", &TestConfig::check_close_notify}, + {"-shim-shuts-down", &TestConfig::shim_shuts_down}, + {"-verify-fail", &TestConfig::verify_fail}, + {"-verify-peer", &TestConfig::verify_peer}, + {"-verify-peer-if-no-obc", &TestConfig::verify_peer_if_no_obc}, + {"-expect-verify-result", &TestConfig::expect_verify_result}, + {"-renegotiate-once", &TestConfig::renegotiate_once}, + {"-renegotiate-freely", &TestConfig::renegotiate_freely}, + {"-renegotiate-ignore", &TestConfig::renegotiate_ignore}, + {"-forbid-renegotiation-after-handshake", + &TestConfig::forbid_renegotiation_after_handshake}, + {"-enable-all-curves", &TestConfig::enable_all_curves}, + {"-use-old-client-cert-callback", + &TestConfig::use_old_client_cert_callback}, + {"-send-alert", &TestConfig::send_alert}, + {"-peek-then-read", &TestConfig::peek_then_read}, + {"-enable-grease", &TestConfig::enable_grease}, + {"-use-exporter-between-reads", &TestConfig::use_exporter_between_reads}, + {"-retain-only-sha256-client-cert", + &TestConfig::retain_only_sha256_client_cert}, + {"-expect-sha256-client-cert", &TestConfig::expect_sha256_client_cert}, + {"-read-with-unfinished-write", &TestConfig::read_with_unfinished_write}, + {"-expect-secure-renegotiation", &TestConfig::expect_secure_renegotiation}, + {"-expect-no-secure-renegotiation", + &TestConfig::expect_no_secure_renegotiation}, + {"-expect-session-id", &TestConfig::expect_session_id}, + {"-expect-no-session-id", &TestConfig::expect_no_session_id}, + {"-expect-accept-early-data", &TestConfig::expect_accept_early_data}, + {"-expect-reject-early-data", &TestConfig::expect_reject_early_data}, + {"-expect-no-offer-early-data", &TestConfig::expect_no_offer_early_data}, + {"-no-op-extra-handshake", &TestConfig::no_op_extra_handshake}, + {"-handshake-twice", &TestConfig::handshake_twice}, + {"-allow-unknown-alpn-protos", &TestConfig::allow_unknown_alpn_protos}, + {"-enable-ed25519", &TestConfig::enable_ed25519}, + {"-use-custom-verify-callback", &TestConfig::use_custom_verify_callback}, + {"-allow-false-start-without-alpn", + &TestConfig::allow_false_start_without_alpn}, + {"-ignore-tls13-downgrade", &TestConfig::ignore_tls13_downgrade}, + {"-expect-tls13-downgrade", &TestConfig::expect_tls13_downgrade}, + {"-handoff", &TestConfig::handoff}, + {"-no-rsa-pss-rsae-certs", &TestConfig::no_rsa_pss_rsae_certs}, + {"-use-ocsp-callback", &TestConfig::use_ocsp_callback}, + {"-set-ocsp-in-callback", &TestConfig::set_ocsp_in_callback}, + {"-decline-ocsp-callback", &TestConfig::decline_ocsp_callback}, + {"-fail-ocsp-callback", &TestConfig::fail_ocsp_callback}, + {"-install-cert-compression-algs", + &TestConfig::install_cert_compression_algs}, + {"-is-handshaker-supported", &TestConfig::is_handshaker_supported}, + {"-handshaker-resume", &TestConfig::handshaker_resume}, + {"-reverify-on-resume", &TestConfig::reverify_on_resume}, + {"-enforce-rsa-key-usage", &TestConfig::enforce_rsa_key_usage}, + {"-jdk11-workaround", &TestConfig::jdk11_workaround}, + {"-server-preference", &TestConfig::server_preference}, + {"-export-traffic-secrets", &TestConfig::export_traffic_secrets}, + {"-key-update", &TestConfig::key_update}, }; const Flag kStringFlags[] = { - { "-write-settings", &TestConfig::write_settings }, - { "-key-file", &TestConfig::key_file }, - { "-cert-file", &TestConfig::cert_file }, - { "-expect-server-name", &TestConfig::expected_server_name }, - { "-advertise-npn", &TestConfig::advertise_npn }, - { "-expect-next-proto", &TestConfig::expected_next_proto }, - { "-select-next-proto", &TestConfig::select_next_proto }, - { "-send-channel-id", &TestConfig::send_channel_id }, - { "-host-name", &TestConfig::host_name }, - { "-advertise-alpn", &TestConfig::advertise_alpn }, - { "-expect-alpn", &TestConfig::expected_alpn }, - { "-expect-late-alpn", &TestConfig::expected_late_alpn }, - { "-expect-advertised-alpn", &TestConfig::expected_advertised_alpn }, - { "-select-alpn", &TestConfig::select_alpn }, - { "-psk", &TestConfig::psk }, - { "-psk-identity", &TestConfig::psk_identity }, - { "-srtp-profiles", &TestConfig::srtp_profiles }, - { "-cipher", &TestConfig::cipher }, - { "-export-label", &TestConfig::export_label }, - { "-export-context", &TestConfig::export_context }, - { "-expect-peer-cert-file", &TestConfig::expect_peer_cert_file }, - { "-use-client-ca-list", &TestConfig::use_client_ca_list }, - { "-expect-client-ca-list", &TestConfig::expected_client_ca_list }, - { "-expect-msg-callback", &TestConfig::expect_msg_callback }, - { "-handshaker-path", &TestConfig::handshaker_path }, + {"-write-settings", &TestConfig::write_settings}, + {"-key-file", &TestConfig::key_file}, + {"-cert-file", &TestConfig::cert_file}, + {"-expect-server-name", &TestConfig::expect_server_name}, + {"-advertise-npn", &TestConfig::advertise_npn}, + {"-expect-next-proto", &TestConfig::expect_next_proto}, + {"-select-next-proto", &TestConfig::select_next_proto}, + {"-send-channel-id", &TestConfig::send_channel_id}, + {"-host-name", &TestConfig::host_name}, + {"-advertise-alpn", &TestConfig::advertise_alpn}, + {"-expect-alpn", &TestConfig::expect_alpn}, + {"-expect-late-alpn", &TestConfig::expect_late_alpn}, + {"-expect-advertised-alpn", &TestConfig::expect_advertised_alpn}, + {"-select-alpn", &TestConfig::select_alpn}, + {"-psk", &TestConfig::psk}, + {"-psk-identity", &TestConfig::psk_identity}, + {"-srtp-profiles", &TestConfig::srtp_profiles}, + {"-cipher", &TestConfig::cipher}, + {"-export-label", &TestConfig::export_label}, + {"-export-context", &TestConfig::export_context}, + {"-expect-peer-cert-file", &TestConfig::expect_peer_cert_file}, + {"-use-client-ca-list", &TestConfig::use_client_ca_list}, + {"-expect-client-ca-list", &TestConfig::expect_client_ca_list}, + {"-expect-msg-callback", &TestConfig::expect_msg_callback}, + {"-handshaker-path", &TestConfig::handshaker_path}, + {"-delegated-credential", &TestConfig::delegated_credential}, + {"-expect-early-data-reason", &TestConfig::expect_early_data_reason}, }; const Flag kBase64Flags[] = { - { "-expect-certificate-types", &TestConfig::expected_certificate_types }, - { "-expect-channel-id", &TestConfig::expected_channel_id }, - { "-token-binding-params", &TestConfig::send_token_binding_params }, - { "-expect-ocsp-response", &TestConfig::expected_ocsp_response }, - { "-expect-signed-cert-timestamps", - &TestConfig::expected_signed_cert_timestamps }, - { "-ocsp-response", &TestConfig::ocsp_response }, - { "-signed-cert-timestamps", &TestConfig::signed_cert_timestamps }, - { "-ticket-key", &TestConfig::ticket_key }, - { "-quic-transport-params", &TestConfig::quic_transport_params }, - { "-expected-quic-transport-params", - &TestConfig::expected_quic_transport_params }, + {"-expect-certificate-types", &TestConfig::expect_certificate_types}, + {"-expect-channel-id", &TestConfig::expect_channel_id}, + {"-token-binding-params", &TestConfig::send_token_binding_params}, + {"-expect-ocsp-response", &TestConfig::expect_ocsp_response}, + {"-expect-signed-cert-timestamps", + &TestConfig::expect_signed_cert_timestamps}, + {"-ocsp-response", &TestConfig::ocsp_response}, + {"-signed-cert-timestamps", &TestConfig::signed_cert_timestamps}, + {"-ticket-key", &TestConfig::ticket_key}, + {"-quic-transport-params", &TestConfig::quic_transport_params}, + {"-expect-quic-transport-params", + &TestConfig::expect_quic_transport_params}, }; const Flag kIntFlags[] = { - { "-port", &TestConfig::port }, - { "-resume-count", &TestConfig::resume_count }, - { "-expected-token-binding-param", - &TestConfig::expected_token_binding_param }, - { "-min-version", &TestConfig::min_version }, - { "-max-version", &TestConfig::max_version }, - { "-expect-version", &TestConfig::expect_version }, - { "-mtu", &TestConfig::mtu }, - { "-export-early-keying-material", - &TestConfig::export_early_keying_material }, - { "-export-keying-material", &TestConfig::export_keying_material }, - { "-expect-total-renegotiations", &TestConfig::expect_total_renegotiations }, - { "-expect-peer-signature-algorithm", - &TestConfig::expect_peer_signature_algorithm }, - { "-expect-curve-id", &TestConfig::expect_curve_id }, - { "-initial-timeout-duration-ms", &TestConfig::initial_timeout_duration_ms }, - { "-max-cert-list", &TestConfig::max_cert_list }, - { "-expect-cipher-aes", &TestConfig::expect_cipher_aes }, - { "-expect-cipher-no-aes", &TestConfig::expect_cipher_no_aes }, - { "-resumption-delay", &TestConfig::resumption_delay }, - { "-max-send-fragment", &TestConfig::max_send_fragment }, - { "-read-size", &TestConfig::read_size }, - { "-expect-ticket-age-skew", &TestConfig::expect_ticket_age_skew }, + {"-port", &TestConfig::port}, + {"-resume-count", &TestConfig::resume_count}, + {"-expect-token-binding-param", &TestConfig::expect_token_binding_param}, + {"-min-version", &TestConfig::min_version}, + {"-max-version", &TestConfig::max_version}, + {"-expect-version", &TestConfig::expect_version}, + {"-mtu", &TestConfig::mtu}, + {"-export-early-keying-material", + &TestConfig::export_early_keying_material}, + {"-export-keying-material", &TestConfig::export_keying_material}, + {"-expect-total-renegotiations", &TestConfig::expect_total_renegotiations}, + {"-expect-peer-signature-algorithm", + &TestConfig::expect_peer_signature_algorithm}, + {"-expect-curve-id", &TestConfig::expect_curve_id}, + {"-initial-timeout-duration-ms", &TestConfig::initial_timeout_duration_ms}, + {"-max-cert-list", &TestConfig::max_cert_list}, + {"-expect-cipher-aes", &TestConfig::expect_cipher_aes}, + {"-expect-cipher-no-aes", &TestConfig::expect_cipher_no_aes}, + {"-resumption-delay", &TestConfig::resumption_delay}, + {"-max-send-fragment", &TestConfig::max_send_fragment}, + {"-read-size", &TestConfig::read_size}, + {"-expect-ticket-age-skew", &TestConfig::expect_ticket_age_skew}, }; const Flag> kIntVectorFlags[] = { {"-signing-prefs", &TestConfig::signing_prefs}, {"-verify-prefs", &TestConfig::verify_prefs}, - {"-expect-peer-verify-pref", &TestConfig::expected_peer_verify_prefs}, + {"-expect-peer-verify-pref", &TestConfig::expect_peer_verify_prefs}, {"-curves", &TestConfig::curves}, }; @@ -401,9 +401,9 @@ static int ServerNameCallback(SSL *ssl, int *out_alert, void *arg) { const TestConfig *config = GetTestConfig(ssl); const char *server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); if (server_name == nullptr || - std::string(server_name) != config->expected_server_name) { + std::string(server_name) != config->expect_server_name) { fprintf(stderr, "servername mismatch (got %s; want %s)\n", server_name, - config->expected_server_name.c_str()); + config->expect_server_name.c_str()); return SSL_TLSEXT_ERR_ALERT_FATAL; } @@ -616,9 +616,9 @@ static int AlpnSelectCallback(SSL *ssl, const uint8_t **out, uint8_t *outlen, return SSL_TLSEXT_ERR_NOACK; } - if (!config->expected_advertised_alpn.empty() && - (config->expected_advertised_alpn.size() != inlen || - OPENSSL_memcmp(config->expected_advertised_alpn.data(), in, inlen) != + if (!config->expect_advertised_alpn.empty() && + (config->expect_advertised_alpn.size() != inlen || + OPENSSL_memcmp(config->expect_advertised_alpn.data(), in, inlen) != 0)) { fprintf(stderr, "bad ALPN select callback inputs\n"); exit(1); @@ -632,7 +632,7 @@ static int AlpnSelectCallback(SSL *ssl, const uint8_t **out, uint8_t *outlen, static bool CheckVerifyCallback(SSL *ssl) { const TestConfig *config = GetTestConfig(ssl); - if (!config->expected_ocsp_response.empty()) { + if (!config->expect_ocsp_response.empty()) { const uint8_t *data; size_t len; SSL_get0_ocsp_response(ssl, &data, &len); @@ -845,22 +845,22 @@ static bssl::UniquePtr DecodeHexX509Names( static bool CheckPeerVerifyPrefs(SSL *ssl) { const TestConfig *config = GetTestConfig(ssl); - if (!config->expected_peer_verify_prefs.empty()) { + if (!config->expect_peer_verify_prefs.empty()) { const uint16_t *peer_sigalgs; size_t num_peer_sigalgs = SSL_get0_peer_verify_algorithms(ssl, &peer_sigalgs); - if (config->expected_peer_verify_prefs.size() != num_peer_sigalgs) { + if (config->expect_peer_verify_prefs.size() != num_peer_sigalgs) { fprintf(stderr, "peer verify preferences length mismatch (got %zu, wanted %zu)\n", - num_peer_sigalgs, config->expected_peer_verify_prefs.size()); + num_peer_sigalgs, config->expect_peer_verify_prefs.size()); return false; } for (size_t i = 0; i < num_peer_sigalgs; i++) { if (static_cast(peer_sigalgs[i]) != - config->expected_peer_verify_prefs[i]) { + config->expect_peer_verify_prefs[i]) { fprintf(stderr, "peer verify preference %zu mismatch (got %04x, wanted %04x\n", - i, peer_sigalgs[i], config->expected_peer_verify_prefs[i]); + i, peer_sigalgs[i], config->expect_peer_verify_prefs[i]); return false; } } @@ -875,22 +875,22 @@ static bool CheckCertificateRequest(SSL *ssl) { return false; } - if (!config->expected_certificate_types.empty()) { + if (!config->expect_certificate_types.empty()) { const uint8_t *certificate_types; size_t certificate_types_len = SSL_get0_certificate_types(ssl, &certificate_types); - if (certificate_types_len != config->expected_certificate_types.size() || + if (certificate_types_len != config->expect_certificate_types.size() || OPENSSL_memcmp(certificate_types, - config->expected_certificate_types.data(), + config->expect_certificate_types.data(), certificate_types_len) != 0) { fprintf(stderr, "certificate types mismatch\n"); return false; } } - if (!config->expected_client_ca_list.empty()) { + if (!config->expect_client_ca_list.empty()) { bssl::UniquePtr expected = - DecodeHexX509Names(config->expected_client_ca_list); + DecodeHexX509Names(config->expect_client_ca_list); const size_t num_expected = sk_X509_NAME_num(expected.get()); const STACK_OF(X509_NAME) *received = SSL_get_client_CA_list(ssl); @@ -1097,7 +1097,7 @@ static enum ssl_select_cert_result_t SelectCertificateCallback( const TestConfig *config = GetTestConfig(client_hello->ssl); GetTestState(client_hello->ssl)->early_callback_called = true; - if (!config->expected_server_name.empty()) { + if (!config->expect_server_name.empty()) { const uint8_t *extension_data; size_t extension_len; CBS extension, server_name_list, host_name; @@ -1122,8 +1122,8 @@ static enum ssl_select_cert_result_t SelectCertificateCallback( } if (!CBS_mem_equal(&host_name, - (const uint8_t *)config->expected_server_name.data(), - config->expected_server_name.size())) { + (const uint8_t *)config->expect_server_name.data(), + config->expect_server_name.size())) { fprintf(stderr, "Server name mismatch.\n"); } } @@ -1238,7 +1238,7 @@ bssl::UniquePtr TestConfig::SetupCtx(SSL_CTX *old_ctx) const { SSL_CTX_set_grease_enabled(ssl_ctx.get(), 1); } - if (!expected_server_name.empty()) { + if (!expect_server_name.empty()) { SSL_CTX_set_tlsext_servername_callback(ssl_ctx.get(), ServerNameCallback); } @@ -1500,6 +1500,9 @@ bssl::UniquePtr TestConfig::NewSSL( if (reverify_on_resume) { SSL_CTX_set_reverify_on_resume(ssl_ctx, 1); } + if (enforce_rsa_key_usage) { + SSL_set_enforce_rsa_key_usage(ssl.get(), 1); + } if (no_tls13) { SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3); } @@ -1515,7 +1518,7 @@ bssl::UniquePtr TestConfig::NewSSL( if (no_ticket) { SSL_set_options(ssl.get(), SSL_OP_NO_TICKET); } - if (!expected_channel_id.empty() || enable_channel_id) { + if (!expect_channel_id.empty() || enable_channel_id) { SSL_set_tls_channel_id_enabled(ssl.get(), 1); } if (!send_channel_id.empty()) { @@ -1617,6 +1620,9 @@ bssl::UniquePtr TestConfig::NewSSL( case SSL_CURVE_CECPQ2: nids.push_back(NID_CECPQ2); break; + case SSL_CURVE_CECPQ2b: + nids.push_back(NID_CECPQ2b); + break; } if (!SSL_set1_curves(ssl.get(), &nids[0], nids.size())) { return nullptr; @@ -1625,8 +1631,8 @@ bssl::UniquePtr TestConfig::NewSSL( } if (enable_all_curves) { static const int kAllCurves[] = { - NID_secp224r1, NID_X9_62_prime256v1, NID_secp384r1, - NID_secp521r1, NID_X25519, NID_CECPQ2, + NID_secp224r1, NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, + NID_X25519, NID_CECPQ2, NID_CECPQ2b, }; if (!SSL_set1_curves(ssl.get(), kAllCurves, OPENSSL_ARRAY_SIZE(kAllCurves))) { @@ -1670,5 +1676,40 @@ bssl::UniquePtr TestConfig::NewSSL( } } + if (!delegated_credential.empty()) { + std::string::size_type comma = delegated_credential.find(','); + if (comma == std::string::npos) { + fprintf(stderr, "failed to find comma in delegated credential argument"); + return nullptr; + } + + const std::string dc_hex = delegated_credential.substr(0, comma); + const std::string pkcs8_hex = delegated_credential.substr(comma + 1); + std::string dc, pkcs8; + if (!HexDecode(&dc, dc_hex) || !HexDecode(&pkcs8, pkcs8_hex)) { + fprintf(stderr, "failed to hex decode delegated credential argument"); + return nullptr; + } + + CBS dc_cbs(bssl::Span( + reinterpret_cast(dc.data()), dc.size())); + CBS pkcs8_cbs(bssl::Span( + reinterpret_cast(pkcs8.data()), pkcs8.size())); + + bssl::UniquePtr priv(EVP_parse_private_key(&pkcs8_cbs)); + if (!priv) { + fprintf(stderr, "failed to parse delegated credential private key"); + return nullptr; + } + + bssl::UniquePtr dc_buf( + CRYPTO_BUFFER_new_from_CBS(&dc_cbs, nullptr)); + if (!SSL_set1_delegated_credential(ssl.get(), dc_buf.get(), + priv.get(), nullptr)) { + fprintf(stderr, "SSL_set1_delegated_credential failed.\n"); + return nullptr; + } + } + return ssl; } diff --git a/third_party/boringssl/kit/src/ssl/test/test_config.h b/third_party/boringssl/kit/src/ssl/test/test_config.h index 41709ab0..195ffc9e 100644 --- a/third_party/boringssl/kit/src/ssl/test/test_config.h +++ b/third_party/boringssl/kit/src/ssl/test/test_config.h @@ -32,15 +32,15 @@ struct TestConfig { bool fallback_scsv = false; std::vector signing_prefs; std::vector verify_prefs; - std::vector expected_peer_verify_prefs; + std::vector expect_peer_verify_prefs; std::vector curves; std::string key_file; std::string cert_file; - std::string expected_server_name; - std::string expected_certificate_types; + std::string expect_server_name; + std::string expect_certificate_types; bool require_any_client_certificate = false; std::string advertise_npn; - std::string expected_next_proto; + std::string expect_next_proto; bool false_start = false; std::string select_next_proto; bool async = false; @@ -52,31 +52,31 @@ struct TestConfig { bool no_tls11 = false; bool no_tls1 = false; bool no_ticket = false; - std::string expected_channel_id; + std::string expect_channel_id; bool enable_channel_id = false; std::string send_channel_id; - int expected_token_binding_param = -1; + int expect_token_binding_param = -1; std::string send_token_binding_params; bool shim_writes_first = false; std::string host_name; std::string advertise_alpn; - std::string expected_alpn; - std::string expected_late_alpn; - std::string expected_advertised_alpn; + std::string expect_alpn; + std::string expect_late_alpn; + std::string expect_advertised_alpn; std::string select_alpn; bool decline_alpn = false; bool select_empty_alpn = false; std::string quic_transport_params; - std::string expected_quic_transport_params; + std::string expect_quic_transport_params; bool expect_session_miss = false; bool expect_extended_master_secret = false; std::string psk; std::string psk_identity; std::string srtp_profiles; bool enable_ocsp_stapling = false; - std::string expected_ocsp_response; + std::string expect_ocsp_response; bool enable_signed_cert_timestamps = false; - std::string expected_signed_cert_timestamps; + std::string expect_signed_cert_timestamps; int min_version = 0; int max_version = 0; int expect_version = 0; @@ -127,7 +127,7 @@ struct TestConfig { bool use_old_client_cert_callback = false; int initial_timeout_duration_ms = 0; std::string use_client_ca_list; - std::string expected_client_ca_list; + std::string expect_client_ca_list; bool send_alert = false; bool peek_then_read = false; bool enable_grease = false; @@ -165,6 +165,7 @@ struct TestConfig { bool fail_ocsp_callback = false; bool install_cert_compression_algs = false; bool reverify_on_resume = false; + bool enforce_rsa_key_usage = false; bool is_handshaker_supported = false; bool handshaker_resume = false; std::string handshaker_path; @@ -172,6 +173,8 @@ struct TestConfig { bool server_preference = false; bool export_traffic_secrets = false; bool key_update = false; + std::string delegated_credential; + std::string expect_early_data_reason; int argc; char **argv; diff --git a/third_party/boringssl/kit/src/ssl/tls13_both.cc b/third_party/boringssl/kit/src/ssl/tls13_both.cc index 7674d996..bd0bb4fe 100644 --- a/third_party/boringssl/kit/src/ssl/tls13_both.cc +++ b/third_party/boringssl/kit/src/ssl/tls13_both.cc @@ -212,7 +212,8 @@ bool tls13_process_certificate(SSL_HANDSHAKE *hs, const SSLMessage &msg, } // TLS 1.3 always uses certificate keys for signing thus the correct // keyUsage is enforced. - if (!ssl_cert_check_digital_signature_key_usage(&certificate)) { + if (!ssl_cert_check_key_usage(&certificate, + key_usage_digital_signature)) { ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER); return false; } @@ -418,6 +419,7 @@ bool tls13_process_finished(SSL_HANDSHAKE *hs, const SSLMessage &msg, bool tls13_add_certificate(SSL_HANDSHAKE *hs) { SSL *const ssl = hs->ssl; CERT *const cert = hs->config->cert.get(); + DC *const dc = cert->dc.get(); ScopedCBB cbb; CBB *body, body_storage, certificate_list; @@ -484,6 +486,19 @@ bool tls13_add_certificate(SSL_HANDSHAKE *hs) { } } + if (ssl_signing_with_dc(hs)) { + const CRYPTO_BUFFER *raw = dc->raw.get(); + CBB child; + if (!CBB_add_u16(&extensions, TLSEXT_TYPE_delegated_credential) || + !CBB_add_u16_length_prefixed(&extensions, &child) || + !CBB_add_bytes(&child, CRYPTO_BUFFER_data(raw), + CRYPTO_BUFFER_len(raw)) || + !CBB_flush(&extensions)) { + OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR); + return 0; + } + } + for (size_t i = 1; i < sk_CRYPTO_BUFFER_num(cert->chain.get()); i++) { CRYPTO_BUFFER *cert_buf = sk_CRYPTO_BUFFER_value(cert->chain.get(), i); CBB child; diff --git a/third_party/boringssl/kit/src/ssl/tls13_client.cc b/third_party/boringssl/kit/src/ssl/tls13_client.cc index ac97165f..f411e194 100644 --- a/third_party/boringssl/kit/src/ssl/tls13_client.cc +++ b/third_party/boringssl/kit/src/ssl/tls13_client.cc @@ -188,6 +188,7 @@ static enum ssl_hs_wait_t do_read_hello_retry_request(SSL_HANDSHAKE *hs) { hs->tls13_state = state_send_second_client_hello; // 0-RTT is rejected if we receive a HelloRetryRequest. if (hs->in_early_data) { + ssl->s3->early_data_reason = ssl_early_data_hello_retry_request; return ssl_hs_early_data_rejected; } return ssl_hs_ok; @@ -900,7 +901,7 @@ bool tls13_process_new_session_ticket(SSL *ssl, const SSLMessage &msg) { return false; } - if (have_early_data_info && ssl->enable_early_data) { + if (have_early_data_info) { if (!CBS_get_u32(&early_data_info, &session->ticket_max_early_data) || CBS_len(&early_data_info) != 0) { ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR); diff --git a/third_party/boringssl/kit/src/ssl/tls13_server.cc b/third_party/boringssl/kit/src/ssl/tls13_server.cc index 562fecb0..8fb0d5ce 100644 --- a/third_party/boringssl/kit/src/ssl/tls13_server.cc +++ b/third_party/boringssl/kit/src/ssl/tls13_server.cc @@ -17,6 +17,8 @@ #include #include +#include + #include #include #include @@ -51,6 +53,12 @@ enum server_hs_state_t { static const uint8_t kZeroes[EVP_MAX_MD_SIZE] = {0}; +// Allow a minute of ticket age skew in either direction. This covers +// transmission delays in ClientHello and NewSessionTicket, as well as +// drift between client and server clock rate since the ticket was issued. +// See RFC 8446, section 8.3. +static const int32_t kMaxTicketAgeSkewSeconds = 60; + static int resolve_ecdhe_secret(SSL_HANDSHAKE *hs, bool *out_need_retry, SSL_CLIENT_HELLO *client_hello) { SSL *const ssl = hs->ssl; @@ -95,6 +103,38 @@ static int ssl_ext_supported_versions_add_serverhello(SSL_HANDSHAKE *hs, return 1; } +// CipherScorer produces a "score" for each possible cipher suite offered by +// the client. +class CipherScorer { + public: + CipherScorer(uint16_t group_id) + : aes_is_fine_(EVP_has_aes_hardware()), + security_128_is_fine_(group_id != SSL_CURVE_CECPQ2 && + group_id != SSL_CURVE_CECPQ2b) {} + + typedef std::tuple Score; + + // MinScore returns a |Score| that will compare less than the score of all + // cipher suites. + Score MinScore() const { + return Score(false, false, false); + } + + Score Evaluate(const SSL_CIPHER *a) const { + return Score( + // Something is always preferable to nothing. + true, + // Either 128-bit is fine, or 256-bit is preferred. + security_128_is_fine_ || a->algorithm_enc != SSL_AES128GCM, + // Either AES is fine, or else ChaCha20 is preferred. + aes_is_fine_ || a->algorithm_enc == SSL_CHACHA20POLY1305); + } + + private: + const bool aes_is_fine_; + const bool security_128_is_fine_; +}; + static const SSL_CIPHER *choose_tls13_cipher( const SSL *ssl, const SSL_CLIENT_HELLO *client_hello, uint16_t group_id) { if (client_hello->cipher_suites_len % 2 != 0) { @@ -105,11 +145,12 @@ static const SSL_CIPHER *choose_tls13_cipher( CBS_init(&cipher_suites, client_hello->cipher_suites, client_hello->cipher_suites_len); - const bool aes_is_fine = EVP_has_aes_hardware(); - const bool require_256_bit = group_id == SSL_CURVE_CECPQ2; const uint16_t version = ssl_protocol_version(ssl); const SSL_CIPHER *best = nullptr; + CipherScorer scorer(group_id); + CipherScorer::Score best_score = scorer.MinScore(); + while (CBS_len(&cipher_suites) > 0) { uint16_t cipher_suite; if (!CBS_get_u16(&cipher_suites, &cipher_suite)) { @@ -124,23 +165,12 @@ static const SSL_CIPHER *choose_tls13_cipher( continue; } - // Post-quantum key exchanges should be paired with 256-bit ciphers. - if (require_256_bit && candidate->algorithm_enc == SSL_AES128GCM) { - continue; - } - - // TLS 1.3 removes legacy ciphers, so honor the client order, but prefer - // ChaCha20 if we do not have AES hardware. - if (aes_is_fine) { - return candidate; - } - - if (candidate->algorithm_enc == SSL_CHACHA20POLY1305) { - return candidate; - } - - if (best == nullptr) { + const CipherScorer::Score candidate_score = scorer.Evaluate(candidate); + // |candidate_score| must be larger to displace the current choice. That way + // the client's order controls between ciphers with an equal score. + if (candidate_score > best_score) { best = candidate; + best_score = candidate_score; } } @@ -284,16 +314,15 @@ static enum ssl_hs_wait_t do_select_parameters(SSL_HANDSHAKE *hs) { static enum ssl_ticket_aead_result_t select_session( SSL_HANDSHAKE *hs, uint8_t *out_alert, UniquePtr *out_session, - int32_t *out_ticket_age_skew, const SSLMessage &msg, - const SSL_CLIENT_HELLO *client_hello) { + int32_t *out_ticket_age_skew, bool *out_offered_ticket, + const SSLMessage &msg, const SSL_CLIENT_HELLO *client_hello) { SSL *const ssl = hs->ssl; - *out_session = NULL; + *out_session = nullptr; - // Decode the ticket if we agreed on a PSK key exchange mode. CBS pre_shared_key; - if (!hs->accept_psk_mode || - !ssl_client_hello_get_extension(client_hello, &pre_shared_key, - TLSEXT_TYPE_pre_shared_key)) { + *out_offered_ticket = ssl_client_hello_get_extension( + client_hello, &pre_shared_key, TLSEXT_TYPE_pre_shared_key); + if (!*out_offered_ticket) { return ssl_ticket_aead_ignore_ticket; } @@ -314,6 +343,11 @@ static enum ssl_ticket_aead_result_t select_session( return ssl_ticket_aead_error; } + // If the peer did not offer psk_dhe, ignore the resumption. + if (!hs->accept_psk_mode) { + return ssl_ticket_aead_ignore_ticket; + } + // TLS 1.3 session tickets are renewed separately as part of the // NewSessionTicket. bool unused_renew; @@ -383,10 +417,18 @@ static enum ssl_hs_wait_t do_select_session(SSL_HANDSHAKE *hs) { uint8_t alert = SSL_AD_DECODE_ERROR; UniquePtr session; - switch (select_session(hs, &alert, &session, &ssl->s3->ticket_age_skew, msg, - &client_hello)) { + bool offered_ticket = false; + switch (select_session(hs, &alert, &session, &ssl->s3->ticket_age_skew, + &offered_ticket, msg, &client_hello)) { case ssl_ticket_aead_ignore_ticket: assert(!session); + if (!ssl->enable_early_data) { + ssl->s3->early_data_reason = ssl_early_data_disabled; + } else if (!offered_ticket) { + ssl->s3->early_data_reason = ssl_early_data_no_session_offered; + } else { + ssl->s3->early_data_reason = ssl_early_data_session_not_resumed; + } if (!ssl_get_new_session(hs, 1 /* server */)) { ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR); return ssl_hs_error; @@ -398,26 +440,34 @@ static enum ssl_hs_wait_t do_select_session(SSL_HANDSHAKE *hs) { // a fresh session. hs->new_session = SSL_SESSION_dup(session.get(), SSL_SESSION_DUP_AUTH_ONLY); - - if (ssl->enable_early_data && - // Early data must be acceptable for this ticket. - session->ticket_max_early_data != 0 && - // The client must have offered early data. - hs->early_data_offered && - // Channel ID is incompatible with 0-RTT. - !ssl->s3->channel_id_valid && - // If Token Binding is negotiated, reject 0-RTT. - !ssl->s3->token_binding_negotiated && - // The negotiated ALPN must match the one in the ticket. - MakeConstSpan(ssl->s3->alpn_selected) == session->early_alpn) { - ssl->s3->early_data_accepted = true; - } - - if (hs->new_session == NULL) { + if (hs->new_session == nullptr) { ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR); return ssl_hs_error; } + if (!ssl->enable_early_data) { + ssl->s3->early_data_reason = ssl_early_data_disabled; + } else if (session->ticket_max_early_data == 0) { + ssl->s3->early_data_reason = ssl_early_data_unsupported_for_session; + } else if (!hs->early_data_offered) { + ssl->s3->early_data_reason = ssl_early_data_peer_declined; + } else if (ssl->s3->channel_id_valid) { + // Channel ID is incompatible with 0-RTT. + ssl->s3->early_data_reason = ssl_early_data_channel_id; + } else if (ssl->s3->token_binding_negotiated) { + // Token Binding is incompatible with 0-RTT. + ssl->s3->early_data_reason = ssl_early_data_token_binding; + } else if (MakeConstSpan(ssl->s3->alpn_selected) != session->early_alpn) { + // The negotiated ALPN must match the one in the ticket. + ssl->s3->early_data_reason = ssl_early_data_alpn_mismatch; + } else if (ssl->s3->ticket_age_skew < -kMaxTicketAgeSkewSeconds || + kMaxTicketAgeSkewSeconds < ssl->s3->ticket_age_skew) { + ssl->s3->early_data_reason = ssl_early_data_ticket_age_skew; + } else { + ssl->s3->early_data_reason = ssl_early_data_accepted; + ssl->s3->early_data_accepted = true; + } + ssl->s3->session_reused = true; // Resumption incorporates fresh key material, so refresh the timeout. @@ -476,7 +526,10 @@ static enum ssl_hs_wait_t do_select_session(SSL_HANDSHAKE *hs) { bool need_retry; if (!resolve_ecdhe_secret(hs, &need_retry, &client_hello)) { if (need_retry) { - ssl->s3->early_data_accepted = false; + if (ssl->s3->early_data_accepted) { + ssl->s3->early_data_reason = ssl_early_data_hello_retry_request; + ssl->s3->early_data_accepted = false; + } ssl->s3->skip_early_data = true; ssl->method->next_message(ssl); if (!hs->transcript.UpdateForHelloRetryRequest()) { @@ -927,7 +980,15 @@ static enum ssl_hs_wait_t do_send_new_session_ticket(SSL_HANDSHAKE *hs) { } hs->tls13_state = state_done; - return sent_tickets ? ssl_hs_flush : ssl_hs_ok; + // In TLS 1.3, the NewSessionTicket isn't flushed until the server performs a + // write, to prevent a non-reading client from causing the server to hang in + // the case of a small server write buffer. Consumers which don't write data + // to the client will need to do a zero-byte write if they wish to flush the + // tickets. + if (hs->ssl->ctx->quic_method != nullptr && sent_tickets) { + return ssl_hs_flush; + } + return ssl_hs_ok; } enum ssl_hs_wait_t tls13_server_handshake(SSL_HANDSHAKE *hs) { diff --git a/third_party/boringssl/kit/src/ssl/tls_method.cc b/third_party/boringssl/kit/src/ssl/tls_method.cc index bc9410b3..95fac4d5 100644 --- a/third_party/boringssl/kit/src/ssl/tls_method.cc +++ b/third_party/boringssl/kit/src/ssl/tls_method.cc @@ -125,9 +125,9 @@ static const SSL_PROTOCOL_METHOD kTLSProtocolMethod = { ssl3_set_write_state, }; -static int ssl_noop_x509_check_client_CA_names( +static bool ssl_noop_x509_check_client_CA_names( STACK_OF(CRYPTO_BUFFER) *names) { - return 1; + return true; } static void ssl_noop_x509_clear(CERT *cert) {} @@ -135,29 +135,29 @@ static void ssl_noop_x509_free(CERT *cert) {} static void ssl_noop_x509_dup(CERT *new_cert, const CERT *cert) {} static void ssl_noop_x509_flush_cached_leaf(CERT *cert) {} static void ssl_noop_x509_flush_cached_chain(CERT *cert) {} -static int ssl_noop_x509_session_cache_objects(SSL_SESSION *sess) { - return 1; +static bool ssl_noop_x509_session_cache_objects(SSL_SESSION *sess) { + return true; } -static int ssl_noop_x509_session_dup(SSL_SESSION *new_session, - const SSL_SESSION *session) { - return 1; +static bool ssl_noop_x509_session_dup(SSL_SESSION *new_session, + const SSL_SESSION *session) { + return true; } static void ssl_noop_x509_session_clear(SSL_SESSION *session) {} -static int ssl_noop_x509_session_verify_cert_chain(SSL_SESSION *session, - SSL_HANDSHAKE *hs, - uint8_t *out_alert) { - return 0; +static bool ssl_noop_x509_session_verify_cert_chain(SSL_SESSION *session, + SSL_HANDSHAKE *hs, + uint8_t *out_alert) { + return false; } static void ssl_noop_x509_hs_flush_cached_ca_names(SSL_HANDSHAKE *hs) {} -static int ssl_noop_x509_ssl_new(SSL_HANDSHAKE *hs) { return 1; } +static bool ssl_noop_x509_ssl_new(SSL_HANDSHAKE *hs) { return true; } static void ssl_noop_x509_ssl_config_free(SSL_CONFIG *cfg) {} static void ssl_noop_x509_ssl_flush_cached_client_CA(SSL_CONFIG *cfg) {} -static int ssl_noop_x509_ssl_auto_chain_if_needed(SSL_HANDSHAKE *hs) { - return 1; +static bool ssl_noop_x509_ssl_auto_chain_if_needed(SSL_HANDSHAKE *hs) { + return true; } -static int ssl_noop_x509_ssl_ctx_new(SSL_CTX *ctx) { return 1; } -static void ssl_noop_x509_ssl_ctx_free(SSL_CTX *ctx) { } +static bool ssl_noop_x509_ssl_ctx_new(SSL_CTX *ctx) { return true; } +static void ssl_noop_x509_ssl_ctx_free(SSL_CTX *ctx) {} static void ssl_noop_x509_ssl_ctx_flush_cached_client_CA(SSL_CTX *ctx) {} const SSL_X509_METHOD ssl_noop_x509_method = { diff --git a/third_party/boringssl/kit/src/third_party/fiat/METADATA b/third_party/boringssl/kit/src/third_party/fiat/METADATA index 6cd16121..0e4012f3 100644 --- a/third_party/boringssl/kit/src/third_party/fiat/METADATA +++ b/third_party/boringssl/kit/src/third_party/fiat/METADATA @@ -6,8 +6,8 @@ third_party { type: GIT value: "https://github.com/mit-plv/fiat-crypto" } - version: "6c4d4afb26de639718fcac39094353ca7feec365" - last_upgrade_date { year: 2017 month: 11 day: 3 } + version: "4441785fb44b88bb6943ddbf639d872c8c903281" + last_upgrade_date { year: 2019 month: 1 day: 16 } local_modifications: "Fiat-generated code has been integrated into existing BoringSSL code" } diff --git a/third_party/boringssl/kit/src/third_party/fiat/curve25519.c b/third_party/boringssl/kit/src/third_party/fiat/curve25519.c index 15623c64..564becb7 100644 --- a/third_party/boringssl/kit/src/third_party/fiat/curve25519.c +++ b/third_party/boringssl/kit/src/third_party/fiat/curve25519.c @@ -45,8 +45,14 @@ // Various pre-computed constants. #include "./curve25519_tables.h" +#if defined(BORINGSSL_CURVE25519_64BIT) +#include "./curve25519_64.h" +#else +#include "./curve25519_32.h" +#endif // BORINGSSL_CURVE25519_64BIT -// Low-level intrinsic operations (hand-written). + +// Low-level intrinsic operations static uint64_t load_3(const uint8_t *in) { uint64_t result; @@ -65,706 +71,111 @@ static uint64_t load_4(const uint8_t *in) { return result; } -#if defined(BORINGSSL_CURVE25519_64BIT) -static uint64_t load_8(const uint8_t *in) { - uint64_t result; - result = (uint64_t)in[0]; - result |= ((uint64_t)in[1]) << 8; - result |= ((uint64_t)in[2]) << 16; - result |= ((uint64_t)in[3]) << 24; - result |= ((uint64_t)in[4]) << 32; - result |= ((uint64_t)in[5]) << 40; - result |= ((uint64_t)in[6]) << 48; - result |= ((uint64_t)in[7]) << 56; - return result; -} - -static uint8_t /*bool*/ addcarryx_u51(uint8_t /*bool*/ c, uint64_t a, - uint64_t b, uint64_t *low) { - // This function extracts 51 bits of result and 1 bit of carry (52 total), so - // a 64-bit intermediate is sufficient. - uint64_t x = a + b + c; - *low = x & ((UINT64_C(1) << 51) - 1); - return (x >> 51) & 1; -} - -static uint8_t /*bool*/ subborrow_u51(uint8_t /*bool*/ c, uint64_t a, - uint64_t b, uint64_t *low) { - // This function extracts 51 bits of result and 1 bit of borrow (52 total), so - // a 64-bit intermediate is sufficient. - uint64_t x = a - b - c; - *low = x & ((UINT64_C(1) << 51) - 1); - return x >> 63; -} - -static uint64_t cmovznz64(uint64_t t, uint64_t z, uint64_t nz) { - t = -!!t; // all set if nonzero, 0 if 0 - return (t&nz) | ((~t)&z); -} - -#else - -static uint8_t /*bool*/ addcarryx_u25(uint8_t /*bool*/ c, uint32_t a, - uint32_t b, uint32_t *low) { - // This function extracts 25 bits of result and 1 bit of carry (26 total), so - // a 32-bit intermediate is sufficient. - uint32_t x = a + b + c; - *low = x & ((1 << 25) - 1); - return (x >> 25) & 1; -} - -static uint8_t /*bool*/ addcarryx_u26(uint8_t /*bool*/ c, uint32_t a, - uint32_t b, uint32_t *low) { - // This function extracts 26 bits of result and 1 bit of carry (27 total), so - // a 32-bit intermediate is sufficient. - uint32_t x = a + b + c; - *low = x & ((1 << 26) - 1); - return (x >> 26) & 1; -} - -static uint8_t /*bool*/ subborrow_u25(uint8_t /*bool*/ c, uint32_t a, - uint32_t b, uint32_t *low) { - // This function extracts 25 bits of result and 1 bit of borrow (26 total), so - // a 32-bit intermediate is sufficient. - uint32_t x = a - b - c; - *low = x & ((1 << 25) - 1); - return x >> 31; -} - -static uint8_t /*bool*/ subborrow_u26(uint8_t /*bool*/ c, uint32_t a, - uint32_t b, uint32_t *low) { - // This function extracts 26 bits of result and 1 bit of borrow (27 total), so - // a 32-bit intermediate is sufficient. - uint32_t x = a - b - c; - *low = x & ((1 << 26) - 1); - return x >> 31; -} - -static uint32_t cmovznz32(uint32_t t, uint32_t z, uint32_t nz) { - t = -!!t; // all set if nonzero, 0 if 0 - return (t&nz) | ((~t)&z); -} - -#endif - // Field operations. #if defined(BORINGSSL_CURVE25519_64BIT) -#define assert_fe(f) do { \ - for (unsigned _assert_fe_i = 0; _assert_fe_i< 5; _assert_fe_i++) { \ - assert(f[_assert_fe_i] < 1.125*(UINT64_C(1)<<51)); \ - } \ -} while (0) +typedef uint64_t fe_limb_t; +#define FE_NUM_LIMBS 5 -#define assert_fe_loose(f) do { \ - for (unsigned _assert_fe_i = 0; _assert_fe_i< 5; _assert_fe_i++) { \ - assert(f[_assert_fe_i] < 3.375*(UINT64_C(1)<<51)); \ - } \ -} while (0) - -#define assert_fe_frozen(f) do { \ - for (unsigned _assert_fe_i = 0; _assert_fe_i< 5; _assert_fe_i++) { \ - assert(f[_assert_fe_i] < (UINT64_C(1)<<51)); \ - } \ -} while (0) - -static void fe_frombytes_impl(uint64_t h[5], const uint8_t *s) { - // Ignores top bit of s. - uint64_t a0 = load_8(s); - uint64_t a1 = load_8(s+8); - uint64_t a2 = load_8(s+16); - uint64_t a3 = load_8(s+24); - // Use 51 bits, 64-51 = 13 left. - h[0] = a0 & ((UINT64_C(1) << 51) - 1); - // (64-51) + 38 = 13 + 38 = 51 - h[1] = (a0 >> 51) | ((a1 & ((UINT64_C(1) << 38) - 1)) << 13); - // (64-38) + 25 = 26 + 25 = 51 - h[2] = (a1 >> 38) | ((a2 & ((UINT64_C(1) << 25) - 1)) << 26); - // (64-25) + 12 = 39 + 12 = 51 - h[3] = (a2 >> 25) | ((a3 & ((UINT64_C(1) << 12) - 1)) << 39); - // (64-12) = 52, ignore top bit - h[4] = (a3 >> 12) & ((UINT64_C(1) << 51) - 1); - assert_fe(h); -} - -static void fe_frombytes(fe *h, const uint8_t *s) { - fe_frombytes_impl(h->v, s); -} - -static void fe_freeze(uint64_t out[5], const uint64_t in1[5]) { - { const uint64_t x7 = in1[4]; - { const uint64_t x8 = in1[3]; - { const uint64_t x6 = in1[2]; - { const uint64_t x4 = in1[1]; - { const uint64_t x2 = in1[0]; - { uint64_t x10; uint8_t/*bool*/ x11 = subborrow_u51(0x0, x2, 0x7ffffffffffed, &x10); - { uint64_t x13; uint8_t/*bool*/ x14 = subborrow_u51(x11, x4, 0x7ffffffffffff, &x13); - { uint64_t x16; uint8_t/*bool*/ x17 = subborrow_u51(x14, x6, 0x7ffffffffffff, &x16); - { uint64_t x19; uint8_t/*bool*/ x20 = subborrow_u51(x17, x8, 0x7ffffffffffff, &x19); - { uint64_t x22; uint8_t/*bool*/ x23 = subborrow_u51(x20, x7, 0x7ffffffffffff, &x22); - { uint64_t x24 = cmovznz64(x23, 0x0, 0xffffffffffffffffL); - { uint64_t x25 = (x24 & 0x7ffffffffffed); - { uint64_t x27; uint8_t/*bool*/ x28 = addcarryx_u51(0x0, x10, x25, &x27); - { uint64_t x29 = (x24 & 0x7ffffffffffff); - { uint64_t x31; uint8_t/*bool*/ x32 = addcarryx_u51(x28, x13, x29, &x31); - { uint64_t x33 = (x24 & 0x7ffffffffffff); - { uint64_t x35; uint8_t/*bool*/ x36 = addcarryx_u51(x32, x16, x33, &x35); - { uint64_t x37 = (x24 & 0x7ffffffffffff); - { uint64_t x39; uint8_t/*bool*/ x40 = addcarryx_u51(x36, x19, x37, &x39); - { uint64_t x41 = (x24 & 0x7ffffffffffff); - { uint64_t x43; addcarryx_u51(x40, x22, x41, &x43); - out[0] = x27; - out[1] = x31; - out[2] = x35; - out[3] = x39; - out[4] = x43; - }}}}}}}}}}}}}}}}}}}}} -} - -static void fe_tobytes(uint8_t s[32], const fe *f) { - assert_fe(f->v); - uint64_t h[5]; - fe_freeze(h, f->v); - assert_fe_frozen(h); - - s[0] = h[0] >> 0; - s[1] = h[0] >> 8; - s[2] = h[0] >> 16; - s[3] = h[0] >> 24; - s[4] = h[0] >> 32; - s[5] = h[0] >> 40; - s[6] = (h[0] >> 48) | (h[1] << 3); - s[7] = h[1] >> 5; - s[8] = h[1] >> 13; - s[9] = h[1] >> 21; - s[10] = h[1] >> 29; - s[11] = h[1] >> 37; - s[12] = (h[1] >> 45) | (h[2] << 6); - s[13] = h[2] >> 2; - s[14] = h[2] >> 10; - s[15] = h[2] >> 18; - s[16] = h[2] >> 26; - s[17] = h[2] >> 34; - s[18] = h[2] >> 42; - s[19] = (h[2] >> 50) | (h[3] << 1); - s[20] = h[3] >> 7; - s[21] = h[3] >> 15; - s[22] = h[3] >> 23; - s[23] = h[3] >> 31; - s[24] = h[3] >> 39; - s[25] = (h[3] >> 47) | (h[4] << 4); - s[26] = h[4] >> 4; - s[27] = h[4] >> 12; - s[28] = h[4] >> 20; - s[29] = h[4] >> 28; - s[30] = h[4] >> 36; - s[31] = h[4] >> 44; -} - -// h = 0 -static void fe_0(fe *h) { - OPENSSL_memset(h, 0, sizeof(fe)); -} - -static void fe_loose_0(fe_loose *h) { - OPENSSL_memset(h, 0, sizeof(fe_loose)); -} - -// h = 1 -static void fe_1(fe *h) { - OPENSSL_memset(h, 0, sizeof(fe)); - h->v[0] = 1; -} - -static void fe_loose_1(fe_loose *h) { - OPENSSL_memset(h, 0, sizeof(fe_loose)); - h->v[0] = 1; -} - -static void fe_add_impl(uint64_t out[5], const uint64_t in1[5], const uint64_t in2[5]) { - { const uint64_t x10 = in1[4]; - { const uint64_t x11 = in1[3]; - { const uint64_t x9 = in1[2]; - { const uint64_t x7 = in1[1]; - { const uint64_t x5 = in1[0]; - { const uint64_t x18 = in2[4]; - { const uint64_t x19 = in2[3]; - { const uint64_t x17 = in2[2]; - { const uint64_t x15 = in2[1]; - { const uint64_t x13 = in2[0]; - out[0] = (x5 + x13); - out[1] = (x7 + x15); - out[2] = (x9 + x17); - out[3] = (x11 + x19); - out[4] = (x10 + x18); - }}}}}}}}}} -} - -// h = f + g -// Can overlap h with f or g. -static void fe_add(fe_loose *h, const fe *f, const fe *g) { - assert_fe(f->v); - assert_fe(g->v); - fe_add_impl(h->v, f->v, g->v); - assert_fe_loose(h->v); -} - -static void fe_sub_impl(uint64_t out[5], const uint64_t in1[5], const uint64_t in2[5]) { - { const uint64_t x10 = in1[4]; - { const uint64_t x11 = in1[3]; - { const uint64_t x9 = in1[2]; - { const uint64_t x7 = in1[1]; - { const uint64_t x5 = in1[0]; - { const uint64_t x18 = in2[4]; - { const uint64_t x19 = in2[3]; - { const uint64_t x17 = in2[2]; - { const uint64_t x15 = in2[1]; - { const uint64_t x13 = in2[0]; - out[0] = ((0xfffffffffffda + x5) - x13); - out[1] = ((0xffffffffffffe + x7) - x15); - out[2] = ((0xffffffffffffe + x9) - x17); - out[3] = ((0xffffffffffffe + x11) - x19); - out[4] = ((0xffffffffffffe + x10) - x18); - }}}}}}}}}} -} - -// h = f - g -// Can overlap h with f or g. -static void fe_sub(fe_loose *h, const fe *f, const fe *g) { - assert_fe(f->v); - assert_fe(g->v); - fe_sub_impl(h->v, f->v, g->v); - assert_fe_loose(h->v); -} - -static void fe_carry_impl(uint64_t out[5], const uint64_t in1[5]) { - { const uint64_t x7 = in1[4]; - { const uint64_t x8 = in1[3]; - { const uint64_t x6 = in1[2]; - { const uint64_t x4 = in1[1]; - { const uint64_t x2 = in1[0]; - { uint64_t x9 = (x2 >> 0x33); - { uint64_t x10 = (x2 & 0x7ffffffffffff); - { uint64_t x11 = (x9 + x4); - { uint64_t x12 = (x11 >> 0x33); - { uint64_t x13 = (x11 & 0x7ffffffffffff); - { uint64_t x14 = (x12 + x6); - { uint64_t x15 = (x14 >> 0x33); - { uint64_t x16 = (x14 & 0x7ffffffffffff); - { uint64_t x17 = (x15 + x8); - { uint64_t x18 = (x17 >> 0x33); - { uint64_t x19 = (x17 & 0x7ffffffffffff); - { uint64_t x20 = (x18 + x7); - { uint64_t x21 = (x20 >> 0x33); - { uint64_t x22 = (x20 & 0x7ffffffffffff); - { uint64_t x23 = (x10 + (0x13 * x21)); - { uint64_t x24 = (x23 >> 0x33); - { uint64_t x25 = (x23 & 0x7ffffffffffff); - { uint64_t x26 = (x24 + x13); - { uint64_t x27 = (x26 >> 0x33); - { uint64_t x28 = (x26 & 0x7ffffffffffff); - out[0] = x25; - out[1] = x28; - out[2] = (x27 + x16); - out[3] = x19; - out[4] = x22; - }}}}}}}}}}}}}}}}}}}}}}}}} -} - -static void fe_carry(fe *h, const fe_loose* f) { - assert_fe_loose(f->v); - fe_carry_impl(h->v, f->v); - assert_fe(h->v); -} - -static void fe_mul_impl(uint64_t out[5], const uint64_t in1[5], const uint64_t in2[5]) { - assert_fe_loose(in1); - assert_fe_loose(in2); - { const uint64_t x10 = in1[4]; - { const uint64_t x11 = in1[3]; - { const uint64_t x9 = in1[2]; - { const uint64_t x7 = in1[1]; - { const uint64_t x5 = in1[0]; - { const uint64_t x18 = in2[4]; - { const uint64_t x19 = in2[3]; - { const uint64_t x17 = in2[2]; - { const uint64_t x15 = in2[1]; - { const uint64_t x13 = in2[0]; - { uint128_t x20 = ((uint128_t)x5 * x13); - { uint128_t x21 = (((uint128_t)x5 * x15) + ((uint128_t)x7 * x13)); - { uint128_t x22 = ((((uint128_t)x5 * x17) + ((uint128_t)x9 * x13)) + ((uint128_t)x7 * x15)); - { uint128_t x23 = (((((uint128_t)x5 * x19) + ((uint128_t)x11 * x13)) + ((uint128_t)x7 * x17)) + ((uint128_t)x9 * x15)); - { uint128_t x24 = ((((((uint128_t)x5 * x18) + ((uint128_t)x10 * x13)) + ((uint128_t)x11 * x15)) + ((uint128_t)x7 * x19)) + ((uint128_t)x9 * x17)); - { uint64_t x25 = (x10 * 0x13); - { uint64_t x26 = (x7 * 0x13); - { uint64_t x27 = (x9 * 0x13); - { uint64_t x28 = (x11 * 0x13); - { uint128_t x29 = ((((x20 + ((uint128_t)x25 * x15)) + ((uint128_t)x26 * x18)) + ((uint128_t)x27 * x19)) + ((uint128_t)x28 * x17)); - { uint128_t x30 = (((x21 + ((uint128_t)x25 * x17)) + ((uint128_t)x27 * x18)) + ((uint128_t)x28 * x19)); - { uint128_t x31 = ((x22 + ((uint128_t)x25 * x19)) + ((uint128_t)x28 * x18)); - { uint128_t x32 = (x23 + ((uint128_t)x25 * x18)); - { uint64_t x33 = (uint64_t) (x29 >> 0x33); - { uint64_t x34 = ((uint64_t)x29 & 0x7ffffffffffff); - { uint128_t x35 = (x33 + x30); - { uint64_t x36 = (uint64_t) (x35 >> 0x33); - { uint64_t x37 = ((uint64_t)x35 & 0x7ffffffffffff); - { uint128_t x38 = (x36 + x31); - { uint64_t x39 = (uint64_t) (x38 >> 0x33); - { uint64_t x40 = ((uint64_t)x38 & 0x7ffffffffffff); - { uint128_t x41 = (x39 + x32); - { uint64_t x42 = (uint64_t) (x41 >> 0x33); - { uint64_t x43 = ((uint64_t)x41 & 0x7ffffffffffff); - { uint128_t x44 = (x42 + x24); - { uint64_t x45 = (uint64_t) (x44 >> 0x33); - { uint64_t x46 = ((uint64_t)x44 & 0x7ffffffffffff); - { uint64_t x47 = (x34 + (0x13 * x45)); - { uint64_t x48 = (x47 >> 0x33); - { uint64_t x49 = (x47 & 0x7ffffffffffff); - { uint64_t x50 = (x48 + x37); - { uint64_t x51 = (x50 >> 0x33); - { uint64_t x52 = (x50 & 0x7ffffffffffff); - out[0] = x49; - out[1] = x52; - out[2] = (x51 + x40); - out[3] = x43; - out[4] = x46; - }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} - assert_fe(out); -} - -static void fe_mul_ltt(fe_loose *h, const fe *f, const fe *g) { - fe_mul_impl(h->v, f->v, g->v); -} - -static void fe_mul_llt(fe_loose *h, const fe_loose *f, const fe *g) { - fe_mul_impl(h->v, f->v, g->v); -} - -static void fe_mul_ttt(fe *h, const fe *f, const fe *g) { - fe_mul_impl(h->v, f->v, g->v); -} - -static void fe_mul_tlt(fe *h, const fe_loose *f, const fe *g) { - fe_mul_impl(h->v, f->v, g->v); -} - -static void fe_mul_ttl(fe *h, const fe *f, const fe_loose *g) { - fe_mul_impl(h->v, f->v, g->v); -} - -static void fe_mul_tll(fe *h, const fe_loose *f, const fe_loose *g) { - fe_mul_impl(h->v, f->v, g->v); -} - -static void fe_sqr_impl(uint64_t out[5], const uint64_t in1[5]) { - assert_fe_loose(in1); - { const uint64_t x7 = in1[4]; - { const uint64_t x8 = in1[3]; - { const uint64_t x6 = in1[2]; - { const uint64_t x4 = in1[1]; - { const uint64_t x2 = in1[0]; - { uint64_t x9 = (x2 * 0x2); - { uint64_t x10 = (x4 * 0x2); - { uint64_t x11 = ((x6 * 0x2) * 0x13); - { uint64_t x12 = (x7 * 0x13); - { uint64_t x13 = (x12 * 0x2); - { uint128_t x14 = ((((uint128_t)x2 * x2) + ((uint128_t)x13 * x4)) + ((uint128_t)x11 * x8)); - { uint128_t x15 = ((((uint128_t)x9 * x4) + ((uint128_t)x13 * x6)) + ((uint128_t)x8 * (x8 * 0x13))); - { uint128_t x16 = ((((uint128_t)x9 * x6) + ((uint128_t)x4 * x4)) + ((uint128_t)x13 * x8)); - { uint128_t x17 = ((((uint128_t)x9 * x8) + ((uint128_t)x10 * x6)) + ((uint128_t)x7 * x12)); - { uint128_t x18 = ((((uint128_t)x9 * x7) + ((uint128_t)x10 * x8)) + ((uint128_t)x6 * x6)); - { uint64_t x19 = (uint64_t) (x14 >> 0x33); - { uint64_t x20 = ((uint64_t)x14 & 0x7ffffffffffff); - { uint128_t x21 = (x19 + x15); - { uint64_t x22 = (uint64_t) (x21 >> 0x33); - { uint64_t x23 = ((uint64_t)x21 & 0x7ffffffffffff); - { uint128_t x24 = (x22 + x16); - { uint64_t x25 = (uint64_t) (x24 >> 0x33); - { uint64_t x26 = ((uint64_t)x24 & 0x7ffffffffffff); - { uint128_t x27 = (x25 + x17); - { uint64_t x28 = (uint64_t) (x27 >> 0x33); - { uint64_t x29 = ((uint64_t)x27 & 0x7ffffffffffff); - { uint128_t x30 = (x28 + x18); - { uint64_t x31 = (uint64_t) (x30 >> 0x33); - { uint64_t x32 = ((uint64_t)x30 & 0x7ffffffffffff); - { uint64_t x33 = (x20 + (0x13 * x31)); - { uint64_t x34 = (x33 >> 0x33); - { uint64_t x35 = (x33 & 0x7ffffffffffff); - { uint64_t x36 = (x34 + x23); - { uint64_t x37 = (x36 >> 0x33); - { uint64_t x38 = (x36 & 0x7ffffffffffff); - out[0] = x35; - out[1] = x38; - out[2] = (x37 + x26); - out[3] = x29; - out[4] = x32; - }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} - assert_fe(out); -} - -static void fe_sq_tl(fe *h, const fe_loose *f) { - fe_sqr_impl(h->v, f->v); -} - -static void fe_sq_tt(fe *h, const fe *f) { - fe_sqr_impl(h->v, f->v); -} - -// Replace (f,g) with (g,f) if b == 1; -// replace (f,g) with (f,g) if b == 0. +// assert_fe asserts that |f| satisfies bounds: // -// Preconditions: b in {0,1}. -static void fe_cswap(fe *f, fe *g, uint64_t b) { - b = 0-b; - for (unsigned i = 0; i < 5; i++) { - uint64_t x = f->v[i] ^ g->v[i]; - x &= b; - f->v[i] ^= x; - g->v[i] ^= x; - } -} - -// NOTE: based on fiat-crypto fe_mul, edited for in2=121666, 0, 0.. -static void fe_mul_121666_impl(uint64_t out[5], const uint64_t in1[5]) { - { const uint64_t x10 = in1[4]; - { const uint64_t x11 = in1[3]; - { const uint64_t x9 = in1[2]; - { const uint64_t x7 = in1[1]; - { const uint64_t x5 = in1[0]; - { const uint64_t x18 = 0; - { const uint64_t x19 = 0; - { const uint64_t x17 = 0; - { const uint64_t x15 = 0; - { const uint64_t x13 = 121666; - { uint128_t x20 = ((uint128_t)x5 * x13); - { uint128_t x21 = (((uint128_t)x5 * x15) + ((uint128_t)x7 * x13)); - { uint128_t x22 = ((((uint128_t)x5 * x17) + ((uint128_t)x9 * x13)) + ((uint128_t)x7 * x15)); - { uint128_t x23 = (((((uint128_t)x5 * x19) + ((uint128_t)x11 * x13)) + ((uint128_t)x7 * x17)) + ((uint128_t)x9 * x15)); - { uint128_t x24 = ((((((uint128_t)x5 * x18) + ((uint128_t)x10 * x13)) + ((uint128_t)x11 * x15)) + ((uint128_t)x7 * x19)) + ((uint128_t)x9 * x17)); - { uint64_t x25 = (x10 * 0x13); - { uint64_t x26 = (x7 * 0x13); - { uint64_t x27 = (x9 * 0x13); - { uint64_t x28 = (x11 * 0x13); - { uint128_t x29 = ((((x20 + ((uint128_t)x25 * x15)) + ((uint128_t)x26 * x18)) + ((uint128_t)x27 * x19)) + ((uint128_t)x28 * x17)); - { uint128_t x30 = (((x21 + ((uint128_t)x25 * x17)) + ((uint128_t)x27 * x18)) + ((uint128_t)x28 * x19)); - { uint128_t x31 = ((x22 + ((uint128_t)x25 * x19)) + ((uint128_t)x28 * x18)); - { uint128_t x32 = (x23 + ((uint128_t)x25 * x18)); - { uint64_t x33 = (uint64_t) (x29 >> 0x33); - { uint64_t x34 = ((uint64_t)x29 & 0x7ffffffffffff); - { uint128_t x35 = (x33 + x30); - { uint64_t x36 = (uint64_t) (x35 >> 0x33); - { uint64_t x37 = ((uint64_t)x35 & 0x7ffffffffffff); - { uint128_t x38 = (x36 + x31); - { uint64_t x39 = (uint64_t) (x38 >> 0x33); - { uint64_t x40 = ((uint64_t)x38 & 0x7ffffffffffff); - { uint128_t x41 = (x39 + x32); - { uint64_t x42 = (uint64_t) (x41 >> 0x33); - { uint64_t x43 = ((uint64_t)x41 & 0x7ffffffffffff); - { uint128_t x44 = (x42 + x24); - { uint64_t x45 = (uint64_t) (x44 >> 0x33); - { uint64_t x46 = ((uint64_t)x44 & 0x7ffffffffffff); - { uint64_t x47 = (x34 + (0x13 * x45)); - { uint64_t x48 = (x47 >> 0x33); - { uint64_t x49 = (x47 & 0x7ffffffffffff); - { uint64_t x50 = (x48 + x37); - { uint64_t x51 = (x50 >> 0x33); - { uint64_t x52 = (x50 & 0x7ffffffffffff); - out[0] = x49; - out[1] = x52; - out[2] = (x51 + x40); - out[3] = x43; - out[4] = x46; - }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} -} - -static void fe_mul121666(fe *h, const fe_loose *f) { - assert_fe_loose(f->v); - fe_mul_121666_impl(h->v, f->v); - assert_fe(h->v); -} - -// Adapted from Fiat-synthesized |fe_sub_impl| with |out| = 0. -static void fe_neg_impl(uint64_t out[5], const uint64_t in2[5]) { - { const uint64_t x10 = 0; - { const uint64_t x11 = 0; - { const uint64_t x9 = 0; - { const uint64_t x7 = 0; - { const uint64_t x5 = 0; - { const uint64_t x18 = in2[4]; - { const uint64_t x19 = in2[3]; - { const uint64_t x17 = in2[2]; - { const uint64_t x15 = in2[1]; - { const uint64_t x13 = in2[0]; - out[0] = ((0xfffffffffffda + x5) - x13); - out[1] = ((0xffffffffffffe + x7) - x15); - out[2] = ((0xffffffffffffe + x9) - x17); - out[3] = ((0xffffffffffffe + x11) - x19); - out[4] = ((0xffffffffffffe + x10) - x18); - }}}}}}}}}} -} - -// h = -f -static void fe_neg(fe_loose *h, const fe *f) { - assert_fe(f->v); - fe_neg_impl(h->v, f->v); - assert_fe_loose(h->v); -} - -// Replace (f,g) with (g,g) if b == 1; -// replace (f,g) with (f,g) if b == 0. +// [[0x0 ~> 0x8cccccccccccc], +// [0x0 ~> 0x8cccccccccccc], +// [0x0 ~> 0x8cccccccccccc], +// [0x0 ~> 0x8cccccccccccc], +// [0x0 ~> 0x8cccccccccccc]] // -// Preconditions: b in {0,1}. -static void fe_cmov(fe_loose *f, const fe_loose *g, uint64_t b) { - b = 0-b; - for (unsigned i = 0; i < 5; i++) { - uint64_t x = f->v[i] ^ g->v[i]; - x &= b; - f->v[i] ^= x; - } -} +// See comments in curve25519_64.h for which functions use these bounds for +// inputs or outputs. +#define assert_fe(f) \ + do { \ + for (unsigned _assert_fe_i = 0; _assert_fe_i < 5; _assert_fe_i++) { \ + assert(f[_assert_fe_i] <= UINT64_C(0x8cccccccccccc)); \ + } \ + } while (0) + +// assert_fe_loose asserts that |f| satisfies bounds: +// +// [[0x0 ~> 0x1a666666666664], +// [0x0 ~> 0x1a666666666664], +// [0x0 ~> 0x1a666666666664], +// [0x0 ~> 0x1a666666666664], +// [0x0 ~> 0x1a666666666664]] +// +// See comments in curve25519_64.h for which functions use these bounds for +// inputs or outputs. +#define assert_fe_loose(f) \ + do { \ + for (unsigned _assert_fe_i = 0; _assert_fe_i < 5; _assert_fe_i++) { \ + assert(f[_assert_fe_i] <= UINT64_C(0x1a666666666664)); \ + } \ + } while (0) #else -#define assert_fe(f) do { \ - for (unsigned _assert_fe_i = 0; _assert_fe_i< 10; _assert_fe_i++) { \ - assert(f[_assert_fe_i] < 1.125*(1<<(26-(_assert_fe_i&1)))); \ - } \ -} while (0) +typedef uint32_t fe_limb_t; +#define FE_NUM_LIMBS 10 -#define assert_fe_loose(f) do { \ - for (unsigned _assert_fe_i = 0; _assert_fe_i< 10; _assert_fe_i++) { \ - assert(f[_assert_fe_i] < 3.375*(1<<(26-(_assert_fe_i&1)))); \ - } \ -} while (0) +// assert_fe asserts that |f| satisfies bounds: +// +// [[0x0 ~> 0x4666666], [0x0 ~> 0x2333333], +// [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], +// [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], +// [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], +// [0x0 ~> 0x4666666], [0x0 ~> 0x2333333]] +// +// See comments in curve25519_32.h for which functions use these bounds for +// inputs or outputs. +#define assert_fe(f) \ + do { \ + for (unsigned _assert_fe_i = 0; _assert_fe_i < 10; _assert_fe_i++) { \ + assert(f[_assert_fe_i] <= \ + ((_assert_fe_i & 1) ? 0x2333333u : 0x4666666u)); \ + } \ + } while (0) -#define assert_fe_frozen(f) do { \ - for (unsigned _assert_fe_i = 0; _assert_fe_i< 10; _assert_fe_i++) { \ - assert(f[_assert_fe_i] < (1u<<(26-(_assert_fe_i&1)))); \ - } \ -} while (0) +// assert_fe_loose asserts that |f| satisfies bounds: +// +// [[0x0 ~> 0xd333332], [0x0 ~> 0x6999999], +// [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], +// [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], +// [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], +// [0x0 ~> 0xd333332], [0x0 ~> 0x6999999]] +// +// See comments in curve25519_32.h for which functions use these bounds for +// inputs or outputs. +#define assert_fe_loose(f) \ + do { \ + for (unsigned _assert_fe_i = 0; _assert_fe_i < 10; _assert_fe_i++) { \ + assert(f[_assert_fe_i] <= \ + ((_assert_fe_i & 1) ? 0x6999999u : 0xd333332u)); \ + } \ + } while (0) -static void fe_frombytes_impl(uint32_t h[10], const uint8_t *s) { - // Ignores top bit of s. - uint32_t a0 = load_4(s); - uint32_t a1 = load_4(s+4); - uint32_t a2 = load_4(s+8); - uint32_t a3 = load_4(s+12); - uint32_t a4 = load_4(s+16); - uint32_t a5 = load_4(s+20); - uint32_t a6 = load_4(s+24); - uint32_t a7 = load_4(s+28); - h[0] = a0&((1<<26)-1); // 26 used, 32-26 left. 26 - h[1] = (a0>>26) | ((a1&((1<<19)-1))<< 6); // (32-26) + 19 = 6+19 = 25 - h[2] = (a1>>19) | ((a2&((1<<13)-1))<<13); // (32-19) + 13 = 13+13 = 26 - h[3] = (a2>>13) | ((a3&((1<< 6)-1))<<19); // (32-13) + 6 = 19+ 6 = 25 - h[4] = (a3>> 6); // (32- 6) = 26 - h[5] = a4&((1<<25)-1); // 25 - h[6] = (a4>>25) | ((a5&((1<<19)-1))<< 7); // (32-25) + 19 = 7+19 = 26 - h[7] = (a5>>19) | ((a6&((1<<12)-1))<<13); // (32-19) + 12 = 13+12 = 25 - h[8] = (a6>>12) | ((a7&((1<< 6)-1))<<20); // (32-12) + 6 = 20+ 6 = 26 - h[9] = (a7>> 6)&((1<<25)-1); // 25 - assert_fe(h); +#endif // BORINGSSL_CURVE25519_64BIT + +OPENSSL_STATIC_ASSERT(sizeof(fe) == sizeof(fe_limb_t) * FE_NUM_LIMBS, + "fe_limb_t[FE_NUM_LIMBS] is inconsistent with fe"); + +static void fe_frombytes_strict(fe *h, const uint8_t s[32]) { + // |fiat_25519_from_bytes| requires the top-most bit be clear. + assert((s[31] & 0x80) == 0); + fiat_25519_from_bytes(h->v, s); + assert_fe(h->v); } -static void fe_frombytes(fe *h, const uint8_t *s) { - fe_frombytes_impl(h->v, s); -} - -static void fe_freeze(uint32_t out[10], const uint32_t in1[10]) { - { const uint32_t x17 = in1[9]; - { const uint32_t x18 = in1[8]; - { const uint32_t x16 = in1[7]; - { const uint32_t x14 = in1[6]; - { const uint32_t x12 = in1[5]; - { const uint32_t x10 = in1[4]; - { const uint32_t x8 = in1[3]; - { const uint32_t x6 = in1[2]; - { const uint32_t x4 = in1[1]; - { const uint32_t x2 = in1[0]; - { uint32_t x20; uint8_t/*bool*/ x21 = subborrow_u26(0x0, x2, 0x3ffffed, &x20); - { uint32_t x23; uint8_t/*bool*/ x24 = subborrow_u25(x21, x4, 0x1ffffff, &x23); - { uint32_t x26; uint8_t/*bool*/ x27 = subborrow_u26(x24, x6, 0x3ffffff, &x26); - { uint32_t x29; uint8_t/*bool*/ x30 = subborrow_u25(x27, x8, 0x1ffffff, &x29); - { uint32_t x32; uint8_t/*bool*/ x33 = subborrow_u26(x30, x10, 0x3ffffff, &x32); - { uint32_t x35; uint8_t/*bool*/ x36 = subborrow_u25(x33, x12, 0x1ffffff, &x35); - { uint32_t x38; uint8_t/*bool*/ x39 = subborrow_u26(x36, x14, 0x3ffffff, &x38); - { uint32_t x41; uint8_t/*bool*/ x42 = subborrow_u25(x39, x16, 0x1ffffff, &x41); - { uint32_t x44; uint8_t/*bool*/ x45 = subborrow_u26(x42, x18, 0x3ffffff, &x44); - { uint32_t x47; uint8_t/*bool*/ x48 = subborrow_u25(x45, x17, 0x1ffffff, &x47); - { uint32_t x49 = cmovznz32(x48, 0x0, 0xffffffff); - { uint32_t x50 = (x49 & 0x3ffffed); - { uint32_t x52; uint8_t/*bool*/ x53 = addcarryx_u26(0x0, x20, x50, &x52); - { uint32_t x54 = (x49 & 0x1ffffff); - { uint32_t x56; uint8_t/*bool*/ x57 = addcarryx_u25(x53, x23, x54, &x56); - { uint32_t x58 = (x49 & 0x3ffffff); - { uint32_t x60; uint8_t/*bool*/ x61 = addcarryx_u26(x57, x26, x58, &x60); - { uint32_t x62 = (x49 & 0x1ffffff); - { uint32_t x64; uint8_t/*bool*/ x65 = addcarryx_u25(x61, x29, x62, &x64); - { uint32_t x66 = (x49 & 0x3ffffff); - { uint32_t x68; uint8_t/*bool*/ x69 = addcarryx_u26(x65, x32, x66, &x68); - { uint32_t x70 = (x49 & 0x1ffffff); - { uint32_t x72; uint8_t/*bool*/ x73 = addcarryx_u25(x69, x35, x70, &x72); - { uint32_t x74 = (x49 & 0x3ffffff); - { uint32_t x76; uint8_t/*bool*/ x77 = addcarryx_u26(x73, x38, x74, &x76); - { uint32_t x78 = (x49 & 0x1ffffff); - { uint32_t x80; uint8_t/*bool*/ x81 = addcarryx_u25(x77, x41, x78, &x80); - { uint32_t x82 = (x49 & 0x3ffffff); - { uint32_t x84; uint8_t/*bool*/ x85 = addcarryx_u26(x81, x44, x82, &x84); - { uint32_t x86 = (x49 & 0x1ffffff); - { uint32_t x88; addcarryx_u25(x85, x47, x86, &x88); - out[0] = x52; - out[1] = x56; - out[2] = x60; - out[3] = x64; - out[4] = x68; - out[5] = x72; - out[6] = x76; - out[7] = x80; - out[8] = x84; - out[9] = x88; - }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} +static void fe_frombytes(fe *h, const uint8_t s[32]) { + uint8_t s_copy[32]; + OPENSSL_memcpy(s_copy, s, 32); + s_copy[31] &= 0x7f; + fe_frombytes_strict(h, s_copy); } static void fe_tobytes(uint8_t s[32], const fe *f) { assert_fe(f->v); - uint32_t h[10]; - fe_freeze(h, f->v); - assert_fe_frozen(h); - - s[0] = h[0] >> 0; - s[1] = h[0] >> 8; - s[2] = h[0] >> 16; - s[3] = (h[0] >> 24) | (h[1] << 2); - s[4] = h[1] >> 6; - s[5] = h[1] >> 14; - s[6] = (h[1] >> 22) | (h[2] << 3); - s[7] = h[2] >> 5; - s[8] = h[2] >> 13; - s[9] = (h[2] >> 21) | (h[3] << 5); - s[10] = h[3] >> 3; - s[11] = h[3] >> 11; - s[12] = (h[3] >> 19) | (h[4] << 6); - s[13] = h[4] >> 2; - s[14] = h[4] >> 10; - s[15] = h[4] >> 18; - s[16] = h[5] >> 0; - s[17] = h[5] >> 8; - s[18] = h[5] >> 16; - s[19] = (h[5] >> 24) | (h[6] << 1); - s[20] = h[6] >> 7; - s[21] = h[6] >> 15; - s[22] = (h[6] >> 23) | (h[7] << 3); - s[23] = h[7] >> 5; - s[24] = h[7] >> 13; - s[25] = (h[7] >> 21) | (h[8] << 4); - s[26] = h[8] >> 4; - s[27] = h[8] >> 12; - s[28] = (h[8] >> 20) | (h[9] << 6); - s[29] = h[9] >> 2; - s[30] = h[9] >> 10; - s[31] = h[9] >> 18; + fiat_25519_to_bytes(s, f->v); } // h = 0 @@ -787,272 +198,36 @@ static void fe_loose_1(fe_loose *h) { h->v[0] = 1; } -static void fe_add_impl(uint32_t out[10], const uint32_t in1[10], const uint32_t in2[10]) { - { const uint32_t x20 = in1[9]; - { const uint32_t x21 = in1[8]; - { const uint32_t x19 = in1[7]; - { const uint32_t x17 = in1[6]; - { const uint32_t x15 = in1[5]; - { const uint32_t x13 = in1[4]; - { const uint32_t x11 = in1[3]; - { const uint32_t x9 = in1[2]; - { const uint32_t x7 = in1[1]; - { const uint32_t x5 = in1[0]; - { const uint32_t x38 = in2[9]; - { const uint32_t x39 = in2[8]; - { const uint32_t x37 = in2[7]; - { const uint32_t x35 = in2[6]; - { const uint32_t x33 = in2[5]; - { const uint32_t x31 = in2[4]; - { const uint32_t x29 = in2[3]; - { const uint32_t x27 = in2[2]; - { const uint32_t x25 = in2[1]; - { const uint32_t x23 = in2[0]; - out[0] = (x5 + x23); - out[1] = (x7 + x25); - out[2] = (x9 + x27); - out[3] = (x11 + x29); - out[4] = (x13 + x31); - out[5] = (x15 + x33); - out[6] = (x17 + x35); - out[7] = (x19 + x37); - out[8] = (x21 + x39); - out[9] = (x20 + x38); - }}}}}}}}}}}}}}}}}}}} -} - // h = f + g // Can overlap h with f or g. static void fe_add(fe_loose *h, const fe *f, const fe *g) { assert_fe(f->v); assert_fe(g->v); - fe_add_impl(h->v, f->v, g->v); + fiat_25519_add(h->v, f->v, g->v); assert_fe_loose(h->v); } -static void fe_sub_impl(uint32_t out[10], const uint32_t in1[10], const uint32_t in2[10]) { - { const uint32_t x20 = in1[9]; - { const uint32_t x21 = in1[8]; - { const uint32_t x19 = in1[7]; - { const uint32_t x17 = in1[6]; - { const uint32_t x15 = in1[5]; - { const uint32_t x13 = in1[4]; - { const uint32_t x11 = in1[3]; - { const uint32_t x9 = in1[2]; - { const uint32_t x7 = in1[1]; - { const uint32_t x5 = in1[0]; - { const uint32_t x38 = in2[9]; - { const uint32_t x39 = in2[8]; - { const uint32_t x37 = in2[7]; - { const uint32_t x35 = in2[6]; - { const uint32_t x33 = in2[5]; - { const uint32_t x31 = in2[4]; - { const uint32_t x29 = in2[3]; - { const uint32_t x27 = in2[2]; - { const uint32_t x25 = in2[1]; - { const uint32_t x23 = in2[0]; - out[0] = ((0x7ffffda + x5) - x23); - out[1] = ((0x3fffffe + x7) - x25); - out[2] = ((0x7fffffe + x9) - x27); - out[3] = ((0x3fffffe + x11) - x29); - out[4] = ((0x7fffffe + x13) - x31); - out[5] = ((0x3fffffe + x15) - x33); - out[6] = ((0x7fffffe + x17) - x35); - out[7] = ((0x3fffffe + x19) - x37); - out[8] = ((0x7fffffe + x21) - x39); - out[9] = ((0x3fffffe + x20) - x38); - }}}}}}}}}}}}}}}}}}}} -} - // h = f - g // Can overlap h with f or g. static void fe_sub(fe_loose *h, const fe *f, const fe *g) { assert_fe(f->v); assert_fe(g->v); - fe_sub_impl(h->v, f->v, g->v); + fiat_25519_sub(h->v, f->v, g->v); assert_fe_loose(h->v); } -static void fe_carry_impl(uint32_t out[10], const uint32_t in1[10]) { - { const uint32_t x17 = in1[9]; - { const uint32_t x18 = in1[8]; - { const uint32_t x16 = in1[7]; - { const uint32_t x14 = in1[6]; - { const uint32_t x12 = in1[5]; - { const uint32_t x10 = in1[4]; - { const uint32_t x8 = in1[3]; - { const uint32_t x6 = in1[2]; - { const uint32_t x4 = in1[1]; - { const uint32_t x2 = in1[0]; - { uint32_t x19 = (x2 >> 0x1a); - { uint32_t x20 = (x2 & 0x3ffffff); - { uint32_t x21 = (x19 + x4); - { uint32_t x22 = (x21 >> 0x19); - { uint32_t x23 = (x21 & 0x1ffffff); - { uint32_t x24 = (x22 + x6); - { uint32_t x25 = (x24 >> 0x1a); - { uint32_t x26 = (x24 & 0x3ffffff); - { uint32_t x27 = (x25 + x8); - { uint32_t x28 = (x27 >> 0x19); - { uint32_t x29 = (x27 & 0x1ffffff); - { uint32_t x30 = (x28 + x10); - { uint32_t x31 = (x30 >> 0x1a); - { uint32_t x32 = (x30 & 0x3ffffff); - { uint32_t x33 = (x31 + x12); - { uint32_t x34 = (x33 >> 0x19); - { uint32_t x35 = (x33 & 0x1ffffff); - { uint32_t x36 = (x34 + x14); - { uint32_t x37 = (x36 >> 0x1a); - { uint32_t x38 = (x36 & 0x3ffffff); - { uint32_t x39 = (x37 + x16); - { uint32_t x40 = (x39 >> 0x19); - { uint32_t x41 = (x39 & 0x1ffffff); - { uint32_t x42 = (x40 + x18); - { uint32_t x43 = (x42 >> 0x1a); - { uint32_t x44 = (x42 & 0x3ffffff); - { uint32_t x45 = (x43 + x17); - { uint32_t x46 = (x45 >> 0x19); - { uint32_t x47 = (x45 & 0x1ffffff); - { uint32_t x48 = (x20 + (0x13 * x46)); - { uint32_t x49 = (x48 >> 0x1a); - { uint32_t x50 = (x48 & 0x3ffffff); - { uint32_t x51 = (x49 + x23); - { uint32_t x52 = (x51 >> 0x19); - { uint32_t x53 = (x51 & 0x1ffffff); - out[0] = x50; - out[1] = x53; - out[2] = (x52 + x26); - out[3] = x29; - out[4] = x32; - out[5] = x35; - out[6] = x38; - out[7] = x41; - out[8] = x44; - out[9] = x47; - }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} -} - static void fe_carry(fe *h, const fe_loose* f) { assert_fe_loose(f->v); - fe_carry_impl(h->v, f->v); + fiat_25519_carry(h->v, f->v); assert_fe(h->v); } -static void fe_mul_impl(uint32_t out[10], const uint32_t in1[10], const uint32_t in2[10]) { +static void fe_mul_impl(fe_limb_t out[FE_NUM_LIMBS], + const fe_limb_t in1[FE_NUM_LIMBS], + const fe_limb_t in2[FE_NUM_LIMBS]) { assert_fe_loose(in1); assert_fe_loose(in2); - { const uint32_t x20 = in1[9]; - { const uint32_t x21 = in1[8]; - { const uint32_t x19 = in1[7]; - { const uint32_t x17 = in1[6]; - { const uint32_t x15 = in1[5]; - { const uint32_t x13 = in1[4]; - { const uint32_t x11 = in1[3]; - { const uint32_t x9 = in1[2]; - { const uint32_t x7 = in1[1]; - { const uint32_t x5 = in1[0]; - { const uint32_t x38 = in2[9]; - { const uint32_t x39 = in2[8]; - { const uint32_t x37 = in2[7]; - { const uint32_t x35 = in2[6]; - { const uint32_t x33 = in2[5]; - { const uint32_t x31 = in2[4]; - { const uint32_t x29 = in2[3]; - { const uint32_t x27 = in2[2]; - { const uint32_t x25 = in2[1]; - { const uint32_t x23 = in2[0]; - { uint64_t x40 = ((uint64_t)x23 * x5); - { uint64_t x41 = (((uint64_t)x23 * x7) + ((uint64_t)x25 * x5)); - { uint64_t x42 = ((((uint64_t)(0x2 * x25) * x7) + ((uint64_t)x23 * x9)) + ((uint64_t)x27 * x5)); - { uint64_t x43 = (((((uint64_t)x25 * x9) + ((uint64_t)x27 * x7)) + ((uint64_t)x23 * x11)) + ((uint64_t)x29 * x5)); - { uint64_t x44 = (((((uint64_t)x27 * x9) + (0x2 * (((uint64_t)x25 * x11) + ((uint64_t)x29 * x7)))) + ((uint64_t)x23 * x13)) + ((uint64_t)x31 * x5)); - { uint64_t x45 = (((((((uint64_t)x27 * x11) + ((uint64_t)x29 * x9)) + ((uint64_t)x25 * x13)) + ((uint64_t)x31 * x7)) + ((uint64_t)x23 * x15)) + ((uint64_t)x33 * x5)); - { uint64_t x46 = (((((0x2 * ((((uint64_t)x29 * x11) + ((uint64_t)x25 * x15)) + ((uint64_t)x33 * x7))) + ((uint64_t)x27 * x13)) + ((uint64_t)x31 * x9)) + ((uint64_t)x23 * x17)) + ((uint64_t)x35 * x5)); - { uint64_t x47 = (((((((((uint64_t)x29 * x13) + ((uint64_t)x31 * x11)) + ((uint64_t)x27 * x15)) + ((uint64_t)x33 * x9)) + ((uint64_t)x25 * x17)) + ((uint64_t)x35 * x7)) + ((uint64_t)x23 * x19)) + ((uint64_t)x37 * x5)); - { uint64_t x48 = (((((((uint64_t)x31 * x13) + (0x2 * (((((uint64_t)x29 * x15) + ((uint64_t)x33 * x11)) + ((uint64_t)x25 * x19)) + ((uint64_t)x37 * x7)))) + ((uint64_t)x27 * x17)) + ((uint64_t)x35 * x9)) + ((uint64_t)x23 * x21)) + ((uint64_t)x39 * x5)); - { uint64_t x49 = (((((((((((uint64_t)x31 * x15) + ((uint64_t)x33 * x13)) + ((uint64_t)x29 * x17)) + ((uint64_t)x35 * x11)) + ((uint64_t)x27 * x19)) + ((uint64_t)x37 * x9)) + ((uint64_t)x25 * x21)) + ((uint64_t)x39 * x7)) + ((uint64_t)x23 * x20)) + ((uint64_t)x38 * x5)); - { uint64_t x50 = (((((0x2 * ((((((uint64_t)x33 * x15) + ((uint64_t)x29 * x19)) + ((uint64_t)x37 * x11)) + ((uint64_t)x25 * x20)) + ((uint64_t)x38 * x7))) + ((uint64_t)x31 * x17)) + ((uint64_t)x35 * x13)) + ((uint64_t)x27 * x21)) + ((uint64_t)x39 * x9)); - { uint64_t x51 = (((((((((uint64_t)x33 * x17) + ((uint64_t)x35 * x15)) + ((uint64_t)x31 * x19)) + ((uint64_t)x37 * x13)) + ((uint64_t)x29 * x21)) + ((uint64_t)x39 * x11)) + ((uint64_t)x27 * x20)) + ((uint64_t)x38 * x9)); - { uint64_t x52 = (((((uint64_t)x35 * x17) + (0x2 * (((((uint64_t)x33 * x19) + ((uint64_t)x37 * x15)) + ((uint64_t)x29 * x20)) + ((uint64_t)x38 * x11)))) + ((uint64_t)x31 * x21)) + ((uint64_t)x39 * x13)); - { uint64_t x53 = (((((((uint64_t)x35 * x19) + ((uint64_t)x37 * x17)) + ((uint64_t)x33 * x21)) + ((uint64_t)x39 * x15)) + ((uint64_t)x31 * x20)) + ((uint64_t)x38 * x13)); - { uint64_t x54 = (((0x2 * ((((uint64_t)x37 * x19) + ((uint64_t)x33 * x20)) + ((uint64_t)x38 * x15))) + ((uint64_t)x35 * x21)) + ((uint64_t)x39 * x17)); - { uint64_t x55 = (((((uint64_t)x37 * x21) + ((uint64_t)x39 * x19)) + ((uint64_t)x35 * x20)) + ((uint64_t)x38 * x17)); - { uint64_t x56 = (((uint64_t)x39 * x21) + (0x2 * (((uint64_t)x37 * x20) + ((uint64_t)x38 * x19)))); - { uint64_t x57 = (((uint64_t)x39 * x20) + ((uint64_t)x38 * x21)); - { uint64_t x58 = ((uint64_t)(0x2 * x38) * x20); - { uint64_t x59 = (x48 + (x58 << 0x4)); - { uint64_t x60 = (x59 + (x58 << 0x1)); - { uint64_t x61 = (x60 + x58); - { uint64_t x62 = (x47 + (x57 << 0x4)); - { uint64_t x63 = (x62 + (x57 << 0x1)); - { uint64_t x64 = (x63 + x57); - { uint64_t x65 = (x46 + (x56 << 0x4)); - { uint64_t x66 = (x65 + (x56 << 0x1)); - { uint64_t x67 = (x66 + x56); - { uint64_t x68 = (x45 + (x55 << 0x4)); - { uint64_t x69 = (x68 + (x55 << 0x1)); - { uint64_t x70 = (x69 + x55); - { uint64_t x71 = (x44 + (x54 << 0x4)); - { uint64_t x72 = (x71 + (x54 << 0x1)); - { uint64_t x73 = (x72 + x54); - { uint64_t x74 = (x43 + (x53 << 0x4)); - { uint64_t x75 = (x74 + (x53 << 0x1)); - { uint64_t x76 = (x75 + x53); - { uint64_t x77 = (x42 + (x52 << 0x4)); - { uint64_t x78 = (x77 + (x52 << 0x1)); - { uint64_t x79 = (x78 + x52); - { uint64_t x80 = (x41 + (x51 << 0x4)); - { uint64_t x81 = (x80 + (x51 << 0x1)); - { uint64_t x82 = (x81 + x51); - { uint64_t x83 = (x40 + (x50 << 0x4)); - { uint64_t x84 = (x83 + (x50 << 0x1)); - { uint64_t x85 = (x84 + x50); - { uint64_t x86 = (x85 >> 0x1a); - { uint32_t x87 = ((uint32_t)x85 & 0x3ffffff); - { uint64_t x88 = (x86 + x82); - { uint64_t x89 = (x88 >> 0x19); - { uint32_t x90 = ((uint32_t)x88 & 0x1ffffff); - { uint64_t x91 = (x89 + x79); - { uint64_t x92 = (x91 >> 0x1a); - { uint32_t x93 = ((uint32_t)x91 & 0x3ffffff); - { uint64_t x94 = (x92 + x76); - { uint64_t x95 = (x94 >> 0x19); - { uint32_t x96 = ((uint32_t)x94 & 0x1ffffff); - { uint64_t x97 = (x95 + x73); - { uint64_t x98 = (x97 >> 0x1a); - { uint32_t x99 = ((uint32_t)x97 & 0x3ffffff); - { uint64_t x100 = (x98 + x70); - { uint64_t x101 = (x100 >> 0x19); - { uint32_t x102 = ((uint32_t)x100 & 0x1ffffff); - { uint64_t x103 = (x101 + x67); - { uint64_t x104 = (x103 >> 0x1a); - { uint32_t x105 = ((uint32_t)x103 & 0x3ffffff); - { uint64_t x106 = (x104 + x64); - { uint64_t x107 = (x106 >> 0x19); - { uint32_t x108 = ((uint32_t)x106 & 0x1ffffff); - { uint64_t x109 = (x107 + x61); - { uint64_t x110 = (x109 >> 0x1a); - { uint32_t x111 = ((uint32_t)x109 & 0x3ffffff); - { uint64_t x112 = (x110 + x49); - { uint64_t x113 = (x112 >> 0x19); - { uint32_t x114 = ((uint32_t)x112 & 0x1ffffff); - { uint64_t x115 = (x87 + (0x13 * x113)); - { uint32_t x116 = (uint32_t) (x115 >> 0x1a); - { uint32_t x117 = ((uint32_t)x115 & 0x3ffffff); - { uint32_t x118 = (x116 + x90); - { uint32_t x119 = (x118 >> 0x19); - { uint32_t x120 = (x118 & 0x1ffffff); - out[0] = x117; - out[1] = x120; - out[2] = (x119 + x93); - out[3] = x96; - out[4] = x99; - out[5] = x102; - out[6] = x105; - out[7] = x108; - out[8] = x111; - out[9] = x114; - }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} + fiat_25519_carry_mul(out, in1, in2); assert_fe(out); } @@ -1080,297 +255,42 @@ static void fe_mul_tll(fe *h, const fe_loose *f, const fe_loose *g) { fe_mul_impl(h->v, f->v, g->v); } -static void fe_sqr_impl(uint32_t out[10], const uint32_t in1[10]) { - assert_fe_loose(in1); - { const uint32_t x17 = in1[9]; - { const uint32_t x18 = in1[8]; - { const uint32_t x16 = in1[7]; - { const uint32_t x14 = in1[6]; - { const uint32_t x12 = in1[5]; - { const uint32_t x10 = in1[4]; - { const uint32_t x8 = in1[3]; - { const uint32_t x6 = in1[2]; - { const uint32_t x4 = in1[1]; - { const uint32_t x2 = in1[0]; - { uint64_t x19 = ((uint64_t)x2 * x2); - { uint64_t x20 = ((uint64_t)(0x2 * x2) * x4); - { uint64_t x21 = (0x2 * (((uint64_t)x4 * x4) + ((uint64_t)x2 * x6))); - { uint64_t x22 = (0x2 * (((uint64_t)x4 * x6) + ((uint64_t)x2 * x8))); - { uint64_t x23 = ((((uint64_t)x6 * x6) + ((uint64_t)(0x4 * x4) * x8)) + ((uint64_t)(0x2 * x2) * x10)); - { uint64_t x24 = (0x2 * ((((uint64_t)x6 * x8) + ((uint64_t)x4 * x10)) + ((uint64_t)x2 * x12))); - { uint64_t x25 = (0x2 * (((((uint64_t)x8 * x8) + ((uint64_t)x6 * x10)) + ((uint64_t)x2 * x14)) + ((uint64_t)(0x2 * x4) * x12))); - { uint64_t x26 = (0x2 * (((((uint64_t)x8 * x10) + ((uint64_t)x6 * x12)) + ((uint64_t)x4 * x14)) + ((uint64_t)x2 * x16))); - { uint64_t x27 = (((uint64_t)x10 * x10) + (0x2 * ((((uint64_t)x6 * x14) + ((uint64_t)x2 * x18)) + (0x2 * (((uint64_t)x4 * x16) + ((uint64_t)x8 * x12)))))); - { uint64_t x28 = (0x2 * ((((((uint64_t)x10 * x12) + ((uint64_t)x8 * x14)) + ((uint64_t)x6 * x16)) + ((uint64_t)x4 * x18)) + ((uint64_t)x2 * x17))); - { uint64_t x29 = (0x2 * (((((uint64_t)x12 * x12) + ((uint64_t)x10 * x14)) + ((uint64_t)x6 * x18)) + (0x2 * (((uint64_t)x8 * x16) + ((uint64_t)x4 * x17))))); - { uint64_t x30 = (0x2 * (((((uint64_t)x12 * x14) + ((uint64_t)x10 * x16)) + ((uint64_t)x8 * x18)) + ((uint64_t)x6 * x17))); - { uint64_t x31 = (((uint64_t)x14 * x14) + (0x2 * (((uint64_t)x10 * x18) + (0x2 * (((uint64_t)x12 * x16) + ((uint64_t)x8 * x17)))))); - { uint64_t x32 = (0x2 * ((((uint64_t)x14 * x16) + ((uint64_t)x12 * x18)) + ((uint64_t)x10 * x17))); - { uint64_t x33 = (0x2 * ((((uint64_t)x16 * x16) + ((uint64_t)x14 * x18)) + ((uint64_t)(0x2 * x12) * x17))); - { uint64_t x34 = (0x2 * (((uint64_t)x16 * x18) + ((uint64_t)x14 * x17))); - { uint64_t x35 = (((uint64_t)x18 * x18) + ((uint64_t)(0x4 * x16) * x17)); - { uint64_t x36 = ((uint64_t)(0x2 * x18) * x17); - { uint64_t x37 = ((uint64_t)(0x2 * x17) * x17); - { uint64_t x38 = (x27 + (x37 << 0x4)); - { uint64_t x39 = (x38 + (x37 << 0x1)); - { uint64_t x40 = (x39 + x37); - { uint64_t x41 = (x26 + (x36 << 0x4)); - { uint64_t x42 = (x41 + (x36 << 0x1)); - { uint64_t x43 = (x42 + x36); - { uint64_t x44 = (x25 + (x35 << 0x4)); - { uint64_t x45 = (x44 + (x35 << 0x1)); - { uint64_t x46 = (x45 + x35); - { uint64_t x47 = (x24 + (x34 << 0x4)); - { uint64_t x48 = (x47 + (x34 << 0x1)); - { uint64_t x49 = (x48 + x34); - { uint64_t x50 = (x23 + (x33 << 0x4)); - { uint64_t x51 = (x50 + (x33 << 0x1)); - { uint64_t x52 = (x51 + x33); - { uint64_t x53 = (x22 + (x32 << 0x4)); - { uint64_t x54 = (x53 + (x32 << 0x1)); - { uint64_t x55 = (x54 + x32); - { uint64_t x56 = (x21 + (x31 << 0x4)); - { uint64_t x57 = (x56 + (x31 << 0x1)); - { uint64_t x58 = (x57 + x31); - { uint64_t x59 = (x20 + (x30 << 0x4)); - { uint64_t x60 = (x59 + (x30 << 0x1)); - { uint64_t x61 = (x60 + x30); - { uint64_t x62 = (x19 + (x29 << 0x4)); - { uint64_t x63 = (x62 + (x29 << 0x1)); - { uint64_t x64 = (x63 + x29); - { uint64_t x65 = (x64 >> 0x1a); - { uint32_t x66 = ((uint32_t)x64 & 0x3ffffff); - { uint64_t x67 = (x65 + x61); - { uint64_t x68 = (x67 >> 0x19); - { uint32_t x69 = ((uint32_t)x67 & 0x1ffffff); - { uint64_t x70 = (x68 + x58); - { uint64_t x71 = (x70 >> 0x1a); - { uint32_t x72 = ((uint32_t)x70 & 0x3ffffff); - { uint64_t x73 = (x71 + x55); - { uint64_t x74 = (x73 >> 0x19); - { uint32_t x75 = ((uint32_t)x73 & 0x1ffffff); - { uint64_t x76 = (x74 + x52); - { uint64_t x77 = (x76 >> 0x1a); - { uint32_t x78 = ((uint32_t)x76 & 0x3ffffff); - { uint64_t x79 = (x77 + x49); - { uint64_t x80 = (x79 >> 0x19); - { uint32_t x81 = ((uint32_t)x79 & 0x1ffffff); - { uint64_t x82 = (x80 + x46); - { uint64_t x83 = (x82 >> 0x1a); - { uint32_t x84 = ((uint32_t)x82 & 0x3ffffff); - { uint64_t x85 = (x83 + x43); - { uint64_t x86 = (x85 >> 0x19); - { uint32_t x87 = ((uint32_t)x85 & 0x1ffffff); - { uint64_t x88 = (x86 + x40); - { uint64_t x89 = (x88 >> 0x1a); - { uint32_t x90 = ((uint32_t)x88 & 0x3ffffff); - { uint64_t x91 = (x89 + x28); - { uint64_t x92 = (x91 >> 0x19); - { uint32_t x93 = ((uint32_t)x91 & 0x1ffffff); - { uint64_t x94 = (x66 + (0x13 * x92)); - { uint32_t x95 = (uint32_t) (x94 >> 0x1a); - { uint32_t x96 = ((uint32_t)x94 & 0x3ffffff); - { uint32_t x97 = (x95 + x69); - { uint32_t x98 = (x97 >> 0x19); - { uint32_t x99 = (x97 & 0x1ffffff); - out[0] = x96; - out[1] = x99; - out[2] = (x98 + x72); - out[3] = x75; - out[4] = x78; - out[5] = x81; - out[6] = x84; - out[7] = x87; - out[8] = x90; - out[9] = x93; - }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} - assert_fe(out); -} - static void fe_sq_tl(fe *h, const fe_loose *f) { - fe_sqr_impl(h->v, f->v); + assert_fe_loose(f->v); + fiat_25519_carry_square(h->v, f->v); + assert_fe(h->v); } static void fe_sq_tt(fe *h, const fe *f) { - fe_sqr_impl(h->v, f->v); + assert_fe_loose(f->v); + fiat_25519_carry_square(h->v, f->v); + assert_fe(h->v); } // Replace (f,g) with (g,f) if b == 1; // replace (f,g) with (f,g) if b == 0. // // Preconditions: b in {0,1}. -static void fe_cswap(fe *f, fe *g, unsigned int b) { +static void fe_cswap(fe *f, fe *g, fe_limb_t b) { b = 0-b; - unsigned i; - for (i = 0; i < 10; i++) { - uint32_t x = f->v[i] ^ g->v[i]; + for (unsigned i = 0; i < FE_NUM_LIMBS; i++) { + fe_limb_t x = f->v[i] ^ g->v[i]; x &= b; f->v[i] ^= x; g->v[i] ^= x; } } -// NOTE: based on fiat-crypto fe_mul, edited for in2=121666, 0, 0.. -static void fe_mul_121666_impl(uint32_t out[10], const uint32_t in1[10]) { - { const uint32_t x20 = in1[9]; - { const uint32_t x21 = in1[8]; - { const uint32_t x19 = in1[7]; - { const uint32_t x17 = in1[6]; - { const uint32_t x15 = in1[5]; - { const uint32_t x13 = in1[4]; - { const uint32_t x11 = in1[3]; - { const uint32_t x9 = in1[2]; - { const uint32_t x7 = in1[1]; - { const uint32_t x5 = in1[0]; - { const uint32_t x38 = 0; - { const uint32_t x39 = 0; - { const uint32_t x37 = 0; - { const uint32_t x35 = 0; - { const uint32_t x33 = 0; - { const uint32_t x31 = 0; - { const uint32_t x29 = 0; - { const uint32_t x27 = 0; - { const uint32_t x25 = 0; - { const uint32_t x23 = 121666; - { uint64_t x40 = ((uint64_t)x23 * x5); - { uint64_t x41 = (((uint64_t)x23 * x7) + ((uint64_t)x25 * x5)); - { uint64_t x42 = ((((uint64_t)(0x2 * x25) * x7) + ((uint64_t)x23 * x9)) + ((uint64_t)x27 * x5)); - { uint64_t x43 = (((((uint64_t)x25 * x9) + ((uint64_t)x27 * x7)) + ((uint64_t)x23 * x11)) + ((uint64_t)x29 * x5)); - { uint64_t x44 = (((((uint64_t)x27 * x9) + (0x2 * (((uint64_t)x25 * x11) + ((uint64_t)x29 * x7)))) + ((uint64_t)x23 * x13)) + ((uint64_t)x31 * x5)); - { uint64_t x45 = (((((((uint64_t)x27 * x11) + ((uint64_t)x29 * x9)) + ((uint64_t)x25 * x13)) + ((uint64_t)x31 * x7)) + ((uint64_t)x23 * x15)) + ((uint64_t)x33 * x5)); - { uint64_t x46 = (((((0x2 * ((((uint64_t)x29 * x11) + ((uint64_t)x25 * x15)) + ((uint64_t)x33 * x7))) + ((uint64_t)x27 * x13)) + ((uint64_t)x31 * x9)) + ((uint64_t)x23 * x17)) + ((uint64_t)x35 * x5)); - { uint64_t x47 = (((((((((uint64_t)x29 * x13) + ((uint64_t)x31 * x11)) + ((uint64_t)x27 * x15)) + ((uint64_t)x33 * x9)) + ((uint64_t)x25 * x17)) + ((uint64_t)x35 * x7)) + ((uint64_t)x23 * x19)) + ((uint64_t)x37 * x5)); - { uint64_t x48 = (((((((uint64_t)x31 * x13) + (0x2 * (((((uint64_t)x29 * x15) + ((uint64_t)x33 * x11)) + ((uint64_t)x25 * x19)) + ((uint64_t)x37 * x7)))) + ((uint64_t)x27 * x17)) + ((uint64_t)x35 * x9)) + ((uint64_t)x23 * x21)) + ((uint64_t)x39 * x5)); - { uint64_t x49 = (((((((((((uint64_t)x31 * x15) + ((uint64_t)x33 * x13)) + ((uint64_t)x29 * x17)) + ((uint64_t)x35 * x11)) + ((uint64_t)x27 * x19)) + ((uint64_t)x37 * x9)) + ((uint64_t)x25 * x21)) + ((uint64_t)x39 * x7)) + ((uint64_t)x23 * x20)) + ((uint64_t)x38 * x5)); - { uint64_t x50 = (((((0x2 * ((((((uint64_t)x33 * x15) + ((uint64_t)x29 * x19)) + ((uint64_t)x37 * x11)) + ((uint64_t)x25 * x20)) + ((uint64_t)x38 * x7))) + ((uint64_t)x31 * x17)) + ((uint64_t)x35 * x13)) + ((uint64_t)x27 * x21)) + ((uint64_t)x39 * x9)); - { uint64_t x51 = (((((((((uint64_t)x33 * x17) + ((uint64_t)x35 * x15)) + ((uint64_t)x31 * x19)) + ((uint64_t)x37 * x13)) + ((uint64_t)x29 * x21)) + ((uint64_t)x39 * x11)) + ((uint64_t)x27 * x20)) + ((uint64_t)x38 * x9)); - { uint64_t x52 = (((((uint64_t)x35 * x17) + (0x2 * (((((uint64_t)x33 * x19) + ((uint64_t)x37 * x15)) + ((uint64_t)x29 * x20)) + ((uint64_t)x38 * x11)))) + ((uint64_t)x31 * x21)) + ((uint64_t)x39 * x13)); - { uint64_t x53 = (((((((uint64_t)x35 * x19) + ((uint64_t)x37 * x17)) + ((uint64_t)x33 * x21)) + ((uint64_t)x39 * x15)) + ((uint64_t)x31 * x20)) + ((uint64_t)x38 * x13)); - { uint64_t x54 = (((0x2 * ((((uint64_t)x37 * x19) + ((uint64_t)x33 * x20)) + ((uint64_t)x38 * x15))) + ((uint64_t)x35 * x21)) + ((uint64_t)x39 * x17)); - { uint64_t x55 = (((((uint64_t)x37 * x21) + ((uint64_t)x39 * x19)) + ((uint64_t)x35 * x20)) + ((uint64_t)x38 * x17)); - { uint64_t x56 = (((uint64_t)x39 * x21) + (0x2 * (((uint64_t)x37 * x20) + ((uint64_t)x38 * x19)))); - { uint64_t x57 = (((uint64_t)x39 * x20) + ((uint64_t)x38 * x21)); - { uint64_t x58 = ((uint64_t)(0x2 * x38) * x20); - { uint64_t x59 = (x48 + (x58 << 0x4)); - { uint64_t x60 = (x59 + (x58 << 0x1)); - { uint64_t x61 = (x60 + x58); - { uint64_t x62 = (x47 + (x57 << 0x4)); - { uint64_t x63 = (x62 + (x57 << 0x1)); - { uint64_t x64 = (x63 + x57); - { uint64_t x65 = (x46 + (x56 << 0x4)); - { uint64_t x66 = (x65 + (x56 << 0x1)); - { uint64_t x67 = (x66 + x56); - { uint64_t x68 = (x45 + (x55 << 0x4)); - { uint64_t x69 = (x68 + (x55 << 0x1)); - { uint64_t x70 = (x69 + x55); - { uint64_t x71 = (x44 + (x54 << 0x4)); - { uint64_t x72 = (x71 + (x54 << 0x1)); - { uint64_t x73 = (x72 + x54); - { uint64_t x74 = (x43 + (x53 << 0x4)); - { uint64_t x75 = (x74 + (x53 << 0x1)); - { uint64_t x76 = (x75 + x53); - { uint64_t x77 = (x42 + (x52 << 0x4)); - { uint64_t x78 = (x77 + (x52 << 0x1)); - { uint64_t x79 = (x78 + x52); - { uint64_t x80 = (x41 + (x51 << 0x4)); - { uint64_t x81 = (x80 + (x51 << 0x1)); - { uint64_t x82 = (x81 + x51); - { uint64_t x83 = (x40 + (x50 << 0x4)); - { uint64_t x84 = (x83 + (x50 << 0x1)); - { uint64_t x85 = (x84 + x50); - { uint64_t x86 = (x85 >> 0x1a); - { uint32_t x87 = ((uint32_t)x85 & 0x3ffffff); - { uint64_t x88 = (x86 + x82); - { uint64_t x89 = (x88 >> 0x19); - { uint32_t x90 = ((uint32_t)x88 & 0x1ffffff); - { uint64_t x91 = (x89 + x79); - { uint64_t x92 = (x91 >> 0x1a); - { uint32_t x93 = ((uint32_t)x91 & 0x3ffffff); - { uint64_t x94 = (x92 + x76); - { uint64_t x95 = (x94 >> 0x19); - { uint32_t x96 = ((uint32_t)x94 & 0x1ffffff); - { uint64_t x97 = (x95 + x73); - { uint64_t x98 = (x97 >> 0x1a); - { uint32_t x99 = ((uint32_t)x97 & 0x3ffffff); - { uint64_t x100 = (x98 + x70); - { uint64_t x101 = (x100 >> 0x19); - { uint32_t x102 = ((uint32_t)x100 & 0x1ffffff); - { uint64_t x103 = (x101 + x67); - { uint64_t x104 = (x103 >> 0x1a); - { uint32_t x105 = ((uint32_t)x103 & 0x3ffffff); - { uint64_t x106 = (x104 + x64); - { uint64_t x107 = (x106 >> 0x19); - { uint32_t x108 = ((uint32_t)x106 & 0x1ffffff); - { uint64_t x109 = (x107 + x61); - { uint64_t x110 = (x109 >> 0x1a); - { uint32_t x111 = ((uint32_t)x109 & 0x3ffffff); - { uint64_t x112 = (x110 + x49); - { uint64_t x113 = (x112 >> 0x19); - { uint32_t x114 = ((uint32_t)x112 & 0x1ffffff); - { uint64_t x115 = (x87 + (0x13 * x113)); - { uint32_t x116 = (uint32_t) (x115 >> 0x1a); - { uint32_t x117 = ((uint32_t)x115 & 0x3ffffff); - { uint32_t x118 = (x116 + x90); - { uint32_t x119 = (x118 >> 0x19); - { uint32_t x120 = (x118 & 0x1ffffff); - out[0] = x117; - out[1] = x120; - out[2] = (x119 + x93); - out[3] = x96; - out[4] = x99; - out[5] = x102; - out[6] = x105; - out[7] = x108; - out[8] = x111; - out[9] = x114; - }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} -} - static void fe_mul121666(fe *h, const fe_loose *f) { assert_fe_loose(f->v); - fe_mul_121666_impl(h->v, f->v); + fiat_25519_carry_scmul_121666(h->v, f->v); assert_fe(h->v); } -// Adapted from Fiat-synthesized |fe_sub_impl| with |out| = 0. -static void fe_neg_impl(uint32_t out[10], const uint32_t in2[10]) { - { const uint32_t x20 = 0; - { const uint32_t x21 = 0; - { const uint32_t x19 = 0; - { const uint32_t x17 = 0; - { const uint32_t x15 = 0; - { const uint32_t x13 = 0; - { const uint32_t x11 = 0; - { const uint32_t x9 = 0; - { const uint32_t x7 = 0; - { const uint32_t x5 = 0; - { const uint32_t x38 = in2[9]; - { const uint32_t x39 = in2[8]; - { const uint32_t x37 = in2[7]; - { const uint32_t x35 = in2[6]; - { const uint32_t x33 = in2[5]; - { const uint32_t x31 = in2[4]; - { const uint32_t x29 = in2[3]; - { const uint32_t x27 = in2[2]; - { const uint32_t x25 = in2[1]; - { const uint32_t x23 = in2[0]; - out[0] = ((0x7ffffda + x5) - x23); - out[1] = ((0x3fffffe + x7) - x25); - out[2] = ((0x7fffffe + x9) - x27); - out[3] = ((0x3fffffe + x11) - x29); - out[4] = ((0x7fffffe + x13) - x31); - out[5] = ((0x3fffffe + x15) - x33); - out[6] = ((0x7fffffe + x17) - x35); - out[7] = ((0x3fffffe + x19) - x37); - out[8] = ((0x7fffffe + x21) - x39); - out[9] = ((0x3fffffe + x20) - x38); - }}}}}}}}}}}}}}}}}}}} -} - // h = -f static void fe_neg(fe_loose *h, const fe *f) { assert_fe(f->v); - fe_neg_impl(h->v, f->v); + fiat_25519_opp(h->v, f->v); assert_fe_loose(h->v); } @@ -1378,18 +298,22 @@ static void fe_neg(fe_loose *h, const fe *f) { // replace (f,g) with (f,g) if b == 0. // // Preconditions: b in {0,1}. -static void fe_cmov(fe_loose *f, const fe_loose *g, unsigned b) { +static void fe_cmov(fe_loose *f, const fe_loose *g, fe_limb_t b) { + // Silence an unused function warning. |fiat_25519_selectznz| isn't quite the + // calling convention the rest of this code wants, so implement it by hand. + // + // TODO(davidben): Switch to fiat's calling convention, or ask fiat to emit a + // different one. + (void)fiat_25519_selectznz; + b = 0-b; - unsigned i; - for (i = 0; i < 10; i++) { - uint32_t x = f->v[i] ^ g->v[i]; + for (unsigned i = 0; i < FE_NUM_LIMBS; i++) { + fe_limb_t x = f->v[i] ^ g->v[i]; x &= b; f->v[i] ^= x; } } -#endif // BORINGSSL_CURVE25519_64BIT - // h = f static void fe_copy(fe *h, const fe *f) { OPENSSL_memmove(h, f, sizeof(fe)); @@ -1584,7 +508,7 @@ static void ge_p3_tobytes(uint8_t s[32], const ge_p3 *h) { s[31] ^= fe_isnegative(&x) << 7; } -int x25519_ge_frombytes_vartime(ge_p3 *h, const uint8_t *s) { +int x25519_ge_frombytes_vartime(ge_p3 *h, const uint8_t s[32]) { fe u; fe_loose v; fe v3; @@ -1813,10 +737,12 @@ void x25519_ge_scalarmult_small_precomp( unsigned i; for (i = 0; i < 15; i++) { + // The precomputed table is assumed to already clear the top bit, so + // |fe_frombytes_strict| may be used directly. const uint8_t *bytes = &precomp_table[i*(2 * 32)]; fe x, y; - fe_frombytes(&x, bytes); - fe_frombytes(&y, bytes + 32); + fe_frombytes_strict(&x, bytes); + fe_frombytes_strict(&y, bytes + 32); ge_precomp *out = &multiples[i]; fe_add(&out->yplusx, &y, &x); @@ -2120,6 +1046,12 @@ static void ge_double_scalarmult_vartime(ge_p2 *r, const uint8_t *a, } } +// int64_lshift21 returns |a << 21| but is defined when shifting bits into the +// sign bit. This works around a language flaw in C. +static inline int64_t int64_lshift21(int64_t a) { + return (int64_t)((uint64_t)a << 21); +} + // The set of scalars is \Z/l // where l = 2^252 + 27742317777372353535851937790883648493. @@ -2223,38 +1155,38 @@ void x25519_sc_reduce(uint8_t s[64]) { carry6 = (s6 + (1 << 20)) >> 21; s7 += carry6; - s6 -= carry6 << 21; + s6 -= int64_lshift21(carry6); carry8 = (s8 + (1 << 20)) >> 21; s9 += carry8; - s8 -= carry8 << 21; + s8 -= int64_lshift21(carry8); carry10 = (s10 + (1 << 20)) >> 21; s11 += carry10; - s10 -= carry10 << 21; + s10 -= int64_lshift21(carry10); carry12 = (s12 + (1 << 20)) >> 21; s13 += carry12; - s12 -= carry12 << 21; + s12 -= int64_lshift21(carry12); carry14 = (s14 + (1 << 20)) >> 21; s15 += carry14; - s14 -= carry14 << 21; + s14 -= int64_lshift21(carry14); carry16 = (s16 + (1 << 20)) >> 21; s17 += carry16; - s16 -= carry16 << 21; + s16 -= int64_lshift21(carry16); carry7 = (s7 + (1 << 20)) >> 21; s8 += carry7; - s7 -= carry7 << 21; + s7 -= int64_lshift21(carry7); carry9 = (s9 + (1 << 20)) >> 21; s10 += carry9; - s9 -= carry9 << 21; + s9 -= int64_lshift21(carry9); carry11 = (s11 + (1 << 20)) >> 21; s12 += carry11; - s11 -= carry11 << 21; + s11 -= int64_lshift21(carry11); carry13 = (s13 + (1 << 20)) >> 21; s14 += carry13; - s13 -= carry13 << 21; + s13 -= int64_lshift21(carry13); carry15 = (s15 + (1 << 20)) >> 21; s16 += carry15; - s15 -= carry15 << 21; + s15 -= int64_lshift21(carry15); s5 += s17 * 666643; s6 += s17 * 470296; @@ -2306,41 +1238,41 @@ void x25519_sc_reduce(uint8_t s[64]) { carry0 = (s0 + (1 << 20)) >> 21; s1 += carry0; - s0 -= carry0 << 21; + s0 -= int64_lshift21(carry0); carry2 = (s2 + (1 << 20)) >> 21; s3 += carry2; - s2 -= carry2 << 21; + s2 -= int64_lshift21(carry2); carry4 = (s4 + (1 << 20)) >> 21; s5 += carry4; - s4 -= carry4 << 21; + s4 -= int64_lshift21(carry4); carry6 = (s6 + (1 << 20)) >> 21; s7 += carry6; - s6 -= carry6 << 21; + s6 -= int64_lshift21(carry6); carry8 = (s8 + (1 << 20)) >> 21; s9 += carry8; - s8 -= carry8 << 21; + s8 -= int64_lshift21(carry8); carry10 = (s10 + (1 << 20)) >> 21; s11 += carry10; - s10 -= carry10 << 21; + s10 -= int64_lshift21(carry10); carry1 = (s1 + (1 << 20)) >> 21; s2 += carry1; - s1 -= carry1 << 21; + s1 -= int64_lshift21(carry1); carry3 = (s3 + (1 << 20)) >> 21; s4 += carry3; - s3 -= carry3 << 21; + s3 -= int64_lshift21(carry3); carry5 = (s5 + (1 << 20)) >> 21; s6 += carry5; - s5 -= carry5 << 21; + s5 -= int64_lshift21(carry5); carry7 = (s7 + (1 << 20)) >> 21; s8 += carry7; - s7 -= carry7 << 21; + s7 -= int64_lshift21(carry7); carry9 = (s9 + (1 << 20)) >> 21; s10 += carry9; - s9 -= carry9 << 21; + s9 -= int64_lshift21(carry9); carry11 = (s11 + (1 << 20)) >> 21; s12 += carry11; - s11 -= carry11 << 21; + s11 -= int64_lshift21(carry11); s0 += s12 * 666643; s1 += s12 * 470296; @@ -2352,40 +1284,40 @@ void x25519_sc_reduce(uint8_t s[64]) { carry0 = s0 >> 21; s1 += carry0; - s0 -= carry0 << 21; + s0 -= int64_lshift21(carry0); carry1 = s1 >> 21; s2 += carry1; - s1 -= carry1 << 21; + s1 -= int64_lshift21(carry1); carry2 = s2 >> 21; s3 += carry2; - s2 -= carry2 << 21; + s2 -= int64_lshift21(carry2); carry3 = s3 >> 21; s4 += carry3; - s3 -= carry3 << 21; + s3 -= int64_lshift21(carry3); carry4 = s4 >> 21; s5 += carry4; - s4 -= carry4 << 21; + s4 -= int64_lshift21(carry4); carry5 = s5 >> 21; s6 += carry5; - s5 -= carry5 << 21; + s5 -= int64_lshift21(carry5); carry6 = s6 >> 21; s7 += carry6; - s6 -= carry6 << 21; + s6 -= int64_lshift21(carry6); carry7 = s7 >> 21; s8 += carry7; - s7 -= carry7 << 21; + s7 -= int64_lshift21(carry7); carry8 = s8 >> 21; s9 += carry8; - s8 -= carry8 << 21; + s8 -= int64_lshift21(carry8); carry9 = s9 >> 21; s10 += carry9; - s9 -= carry9 << 21; + s9 -= int64_lshift21(carry9); carry10 = s10 >> 21; s11 += carry10; - s10 -= carry10 << 21; + s10 -= int64_lshift21(carry10); carry11 = s11 >> 21; s12 += carry11; - s11 -= carry11 << 21; + s11 -= int64_lshift21(carry11); s0 += s12 * 666643; s1 += s12 * 470296; @@ -2397,37 +1329,37 @@ void x25519_sc_reduce(uint8_t s[64]) { carry0 = s0 >> 21; s1 += carry0; - s0 -= carry0 << 21; + s0 -= int64_lshift21(carry0); carry1 = s1 >> 21; s2 += carry1; - s1 -= carry1 << 21; + s1 -= int64_lshift21(carry1); carry2 = s2 >> 21; s3 += carry2; - s2 -= carry2 << 21; + s2 -= int64_lshift21(carry2); carry3 = s3 >> 21; s4 += carry3; - s3 -= carry3 << 21; + s3 -= int64_lshift21(carry3); carry4 = s4 >> 21; s5 += carry4; - s4 -= carry4 << 21; + s4 -= int64_lshift21(carry4); carry5 = s5 >> 21; s6 += carry5; - s5 -= carry5 << 21; + s5 -= int64_lshift21(carry5); carry6 = s6 >> 21; s7 += carry6; - s6 -= carry6 << 21; + s6 -= int64_lshift21(carry6); carry7 = s7 >> 21; s8 += carry7; - s7 -= carry7 << 21; + s7 -= int64_lshift21(carry7); carry8 = s8 >> 21; s9 += carry8; - s8 -= carry8 << 21; + s8 -= int64_lshift21(carry8); carry9 = s9 >> 21; s10 += carry9; - s9 -= carry9 << 21; + s9 -= int64_lshift21(carry9); carry10 = s10 >> 21; s11 += carry10; - s10 -= carry10 << 21; + s10 -= int64_lshift21(carry10); s[0] = s0 >> 0; s[1] = s0 >> 8; @@ -2593,74 +1525,74 @@ static void sc_muladd(uint8_t *s, const uint8_t *a, const uint8_t *b, carry0 = (s0 + (1 << 20)) >> 21; s1 += carry0; - s0 -= carry0 << 21; + s0 -= int64_lshift21(carry0); carry2 = (s2 + (1 << 20)) >> 21; s3 += carry2; - s2 -= carry2 << 21; + s2 -= int64_lshift21(carry2); carry4 = (s4 + (1 << 20)) >> 21; s5 += carry4; - s4 -= carry4 << 21; + s4 -= int64_lshift21(carry4); carry6 = (s6 + (1 << 20)) >> 21; s7 += carry6; - s6 -= carry6 << 21; + s6 -= int64_lshift21(carry6); carry8 = (s8 + (1 << 20)) >> 21; s9 += carry8; - s8 -= carry8 << 21; + s8 -= int64_lshift21(carry8); carry10 = (s10 + (1 << 20)) >> 21; s11 += carry10; - s10 -= carry10 << 21; + s10 -= int64_lshift21(carry10); carry12 = (s12 + (1 << 20)) >> 21; s13 += carry12; - s12 -= carry12 << 21; + s12 -= int64_lshift21(carry12); carry14 = (s14 + (1 << 20)) >> 21; s15 += carry14; - s14 -= carry14 << 21; + s14 -= int64_lshift21(carry14); carry16 = (s16 + (1 << 20)) >> 21; s17 += carry16; - s16 -= carry16 << 21; + s16 -= int64_lshift21(carry16); carry18 = (s18 + (1 << 20)) >> 21; s19 += carry18; - s18 -= carry18 << 21; + s18 -= int64_lshift21(carry18); carry20 = (s20 + (1 << 20)) >> 21; s21 += carry20; - s20 -= carry20 << 21; + s20 -= int64_lshift21(carry20); carry22 = (s22 + (1 << 20)) >> 21; s23 += carry22; - s22 -= carry22 << 21; + s22 -= int64_lshift21(carry22); carry1 = (s1 + (1 << 20)) >> 21; s2 += carry1; - s1 -= carry1 << 21; + s1 -= int64_lshift21(carry1); carry3 = (s3 + (1 << 20)) >> 21; s4 += carry3; - s3 -= carry3 << 21; + s3 -= int64_lshift21(carry3); carry5 = (s5 + (1 << 20)) >> 21; s6 += carry5; - s5 -= carry5 << 21; + s5 -= int64_lshift21(carry5); carry7 = (s7 + (1 << 20)) >> 21; s8 += carry7; - s7 -= carry7 << 21; + s7 -= int64_lshift21(carry7); carry9 = (s9 + (1 << 20)) >> 21; s10 += carry9; - s9 -= carry9 << 21; + s9 -= int64_lshift21(carry9); carry11 = (s11 + (1 << 20)) >> 21; s12 += carry11; - s11 -= carry11 << 21; + s11 -= int64_lshift21(carry11); carry13 = (s13 + (1 << 20)) >> 21; s14 += carry13; - s13 -= carry13 << 21; + s13 -= int64_lshift21(carry13); carry15 = (s15 + (1 << 20)) >> 21; s16 += carry15; - s15 -= carry15 << 21; + s15 -= int64_lshift21(carry15); carry17 = (s17 + (1 << 20)) >> 21; s18 += carry17; - s17 -= carry17 << 21; + s17 -= int64_lshift21(carry17); carry19 = (s19 + (1 << 20)) >> 21; s20 += carry19; - s19 -= carry19 << 21; + s19 -= int64_lshift21(carry19); carry21 = (s21 + (1 << 20)) >> 21; s22 += carry21; - s21 -= carry21 << 21; + s21 -= int64_lshift21(carry21); s11 += s23 * 666643; s12 += s23 * 470296; @@ -2712,38 +1644,38 @@ static void sc_muladd(uint8_t *s, const uint8_t *a, const uint8_t *b, carry6 = (s6 + (1 << 20)) >> 21; s7 += carry6; - s6 -= carry6 << 21; + s6 -= int64_lshift21(carry6); carry8 = (s8 + (1 << 20)) >> 21; s9 += carry8; - s8 -= carry8 << 21; + s8 -= int64_lshift21(carry8); carry10 = (s10 + (1 << 20)) >> 21; s11 += carry10; - s10 -= carry10 << 21; + s10 -= int64_lshift21(carry10); carry12 = (s12 + (1 << 20)) >> 21; s13 += carry12; - s12 -= carry12 << 21; + s12 -= int64_lshift21(carry12); carry14 = (s14 + (1 << 20)) >> 21; s15 += carry14; - s14 -= carry14 << 21; + s14 -= int64_lshift21(carry14); carry16 = (s16 + (1 << 20)) >> 21; s17 += carry16; - s16 -= carry16 << 21; + s16 -= int64_lshift21(carry16); carry7 = (s7 + (1 << 20)) >> 21; s8 += carry7; - s7 -= carry7 << 21; + s7 -= int64_lshift21(carry7); carry9 = (s9 + (1 << 20)) >> 21; s10 += carry9; - s9 -= carry9 << 21; + s9 -= int64_lshift21(carry9); carry11 = (s11 + (1 << 20)) >> 21; s12 += carry11; - s11 -= carry11 << 21; + s11 -= int64_lshift21(carry11); carry13 = (s13 + (1 << 20)) >> 21; s14 += carry13; - s13 -= carry13 << 21; + s13 -= int64_lshift21(carry13); carry15 = (s15 + (1 << 20)) >> 21; s16 += carry15; - s15 -= carry15 << 21; + s15 -= int64_lshift21(carry15); s5 += s17 * 666643; s6 += s17 * 470296; @@ -2795,41 +1727,41 @@ static void sc_muladd(uint8_t *s, const uint8_t *a, const uint8_t *b, carry0 = (s0 + (1 << 20)) >> 21; s1 += carry0; - s0 -= carry0 << 21; + s0 -= int64_lshift21(carry0); carry2 = (s2 + (1 << 20)) >> 21; s3 += carry2; - s2 -= carry2 << 21; + s2 -= int64_lshift21(carry2); carry4 = (s4 + (1 << 20)) >> 21; s5 += carry4; - s4 -= carry4 << 21; + s4 -= int64_lshift21(carry4); carry6 = (s6 + (1 << 20)) >> 21; s7 += carry6; - s6 -= carry6 << 21; + s6 -= int64_lshift21(carry6); carry8 = (s8 + (1 << 20)) >> 21; s9 += carry8; - s8 -= carry8 << 21; + s8 -= int64_lshift21(carry8); carry10 = (s10 + (1 << 20)) >> 21; s11 += carry10; - s10 -= carry10 << 21; + s10 -= int64_lshift21(carry10); carry1 = (s1 + (1 << 20)) >> 21; s2 += carry1; - s1 -= carry1 << 21; + s1 -= int64_lshift21(carry1); carry3 = (s3 + (1 << 20)) >> 21; s4 += carry3; - s3 -= carry3 << 21; + s3 -= int64_lshift21(carry3); carry5 = (s5 + (1 << 20)) >> 21; s6 += carry5; - s5 -= carry5 << 21; + s5 -= int64_lshift21(carry5); carry7 = (s7 + (1 << 20)) >> 21; s8 += carry7; - s7 -= carry7 << 21; + s7 -= int64_lshift21(carry7); carry9 = (s9 + (1 << 20)) >> 21; s10 += carry9; - s9 -= carry9 << 21; + s9 -= int64_lshift21(carry9); carry11 = (s11 + (1 << 20)) >> 21; s12 += carry11; - s11 -= carry11 << 21; + s11 -= int64_lshift21(carry11); s0 += s12 * 666643; s1 += s12 * 470296; @@ -2841,40 +1773,40 @@ static void sc_muladd(uint8_t *s, const uint8_t *a, const uint8_t *b, carry0 = s0 >> 21; s1 += carry0; - s0 -= carry0 << 21; + s0 -= int64_lshift21(carry0); carry1 = s1 >> 21; s2 += carry1; - s1 -= carry1 << 21; + s1 -= int64_lshift21(carry1); carry2 = s2 >> 21; s3 += carry2; - s2 -= carry2 << 21; + s2 -= int64_lshift21(carry2); carry3 = s3 >> 21; s4 += carry3; - s3 -= carry3 << 21; + s3 -= int64_lshift21(carry3); carry4 = s4 >> 21; s5 += carry4; - s4 -= carry4 << 21; + s4 -= int64_lshift21(carry4); carry5 = s5 >> 21; s6 += carry5; - s5 -= carry5 << 21; + s5 -= int64_lshift21(carry5); carry6 = s6 >> 21; s7 += carry6; - s6 -= carry6 << 21; + s6 -= int64_lshift21(carry6); carry7 = s7 >> 21; s8 += carry7; - s7 -= carry7 << 21; + s7 -= int64_lshift21(carry7); carry8 = s8 >> 21; s9 += carry8; - s8 -= carry8 << 21; + s8 -= int64_lshift21(carry8); carry9 = s9 >> 21; s10 += carry9; - s9 -= carry9 << 21; + s9 -= int64_lshift21(carry9); carry10 = s10 >> 21; s11 += carry10; - s10 -= carry10 << 21; + s10 -= int64_lshift21(carry10); carry11 = s11 >> 21; s12 += carry11; - s11 -= carry11 << 21; + s11 -= int64_lshift21(carry11); s0 += s12 * 666643; s1 += s12 * 470296; @@ -2886,37 +1818,37 @@ static void sc_muladd(uint8_t *s, const uint8_t *a, const uint8_t *b, carry0 = s0 >> 21; s1 += carry0; - s0 -= carry0 << 21; + s0 -= int64_lshift21(carry0); carry1 = s1 >> 21; s2 += carry1; - s1 -= carry1 << 21; + s1 -= int64_lshift21(carry1); carry2 = s2 >> 21; s3 += carry2; - s2 -= carry2 << 21; + s2 -= int64_lshift21(carry2); carry3 = s3 >> 21; s4 += carry3; - s3 -= carry3 << 21; + s3 -= int64_lshift21(carry3); carry4 = s4 >> 21; s5 += carry4; - s4 -= carry4 << 21; + s4 -= int64_lshift21(carry4); carry5 = s5 >> 21; s6 += carry5; - s5 -= carry5 << 21; + s5 -= int64_lshift21(carry5); carry6 = s6 >> 21; s7 += carry6; - s6 -= carry6 << 21; + s6 -= int64_lshift21(carry6); carry7 = s7 >> 21; s8 += carry7; - s7 -= carry7 << 21; + s7 -= int64_lshift21(carry7); carry8 = s8 >> 21; s9 += carry8; - s8 -= carry8 << 21; + s8 -= int64_lshift21(carry8); carry9 = s9 >> 21; s10 += carry9; - s9 -= carry9 << 21; + s9 -= int64_lshift21(carry9); carry10 = s10 >> 21; s11 += carry10; - s10 -= carry10 << 21; + s10 -= int64_lshift21(carry10); s[0] = s0 >> 0; s[1] = s0 >> 8; diff --git a/third_party/boringssl/kit/src/third_party/fiat/curve25519_32.h b/third_party/boringssl/kit/src/third_party/fiat/curve25519_32.h new file mode 100644 index 00000000..820a5c9b --- /dev/null +++ b/third_party/boringssl/kit/src/third_party/fiat/curve25519_32.h @@ -0,0 +1,905 @@ +/* Autogenerated */ +/* curve description: 25519 */ +/* requested operations: carry_mul, carry_square, carry_scmul121666, carry, add, sub, opp, selectznz, to_bytes, from_bytes */ +/* n = 10 (from "10") */ +/* s = 0x8000000000000000000000000000000000000000000000000000000000000000 (from "2^255") */ +/* c = [(1, 19)] (from "1,19") */ +/* machine_wordsize = 32 (from "32") */ + +#include +typedef unsigned char fiat_25519_uint1; +typedef signed char fiat_25519_int1; + + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [0x0 ~> 0x3ffffff] + * arg3: [0x0 ~> 0x3ffffff] + * Output Bounds: + * out1: [0x0 ~> 0x3ffffff] + * out2: [0x0 ~> 0x1] + */ +static void fiat_25519_addcarryx_u26(uint32_t* out1, fiat_25519_uint1* out2, fiat_25519_uint1 arg1, uint32_t arg2, uint32_t arg3) { + uint32_t x1 = ((arg1 + arg2) + arg3); + uint32_t x2 = (x1 & UINT32_C(0x3ffffff)); + fiat_25519_uint1 x3 = (fiat_25519_uint1)(x1 >> 26); + *out1 = x2; + *out2 = x3; +} + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [0x0 ~> 0x3ffffff] + * arg3: [0x0 ~> 0x3ffffff] + * Output Bounds: + * out1: [0x0 ~> 0x3ffffff] + * out2: [0x0 ~> 0x1] + */ +static void fiat_25519_subborrowx_u26(uint32_t* out1, fiat_25519_uint1* out2, fiat_25519_uint1 arg1, uint32_t arg2, uint32_t arg3) { + int32_t x1 = ((int32_t)(arg2 - arg1) - (int32_t)arg3); + fiat_25519_int1 x2 = (fiat_25519_int1)(x1 >> 26); + uint32_t x3 = (x1 & UINT32_C(0x3ffffff)); + *out1 = x3; + *out2 = (fiat_25519_uint1)(0x0 - x2); +} + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [0x0 ~> 0x1ffffff] + * arg3: [0x0 ~> 0x1ffffff] + * Output Bounds: + * out1: [0x0 ~> 0x1ffffff] + * out2: [0x0 ~> 0x1] + */ +static void fiat_25519_addcarryx_u25(uint32_t* out1, fiat_25519_uint1* out2, fiat_25519_uint1 arg1, uint32_t arg2, uint32_t arg3) { + uint32_t x1 = ((arg1 + arg2) + arg3); + uint32_t x2 = (x1 & UINT32_C(0x1ffffff)); + fiat_25519_uint1 x3 = (fiat_25519_uint1)(x1 >> 25); + *out1 = x2; + *out2 = x3; +} + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [0x0 ~> 0x1ffffff] + * arg3: [0x0 ~> 0x1ffffff] + * Output Bounds: + * out1: [0x0 ~> 0x1ffffff] + * out2: [0x0 ~> 0x1] + */ +static void fiat_25519_subborrowx_u25(uint32_t* out1, fiat_25519_uint1* out2, fiat_25519_uint1 arg1, uint32_t arg2, uint32_t arg3) { + int32_t x1 = ((int32_t)(arg2 - arg1) - (int32_t)arg3); + fiat_25519_int1 x2 = (fiat_25519_int1)(x1 >> 25); + uint32_t x3 = (x1 & UINT32_C(0x1ffffff)); + *out1 = x3; + *out2 = (fiat_25519_uint1)(0x0 - x2); +} + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [0x0 ~> 0xffffffff] + * arg3: [0x0 ~> 0xffffffff] + * Output Bounds: + * out1: [0x0 ~> 0xffffffff] + */ +static void fiat_25519_cmovznz_u32(uint32_t* out1, fiat_25519_uint1 arg1, uint32_t arg2, uint32_t arg3) { + fiat_25519_uint1 x1 = (!(!arg1)); + uint32_t x2 = ((fiat_25519_int1)(0x0 - x1) & UINT32_C(0xffffffff)); + uint32_t x3 = ((x2 & arg3) | ((~x2) & arg2)); + *out1 = x3; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999]] + * arg2: [[0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999]] + * Output Bounds: + * out1: [[0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333]] + */ +static void fiat_25519_carry_mul(uint32_t out1[10], const uint32_t arg1[10], const uint32_t arg2[10]) { + uint64_t x1 = ((uint64_t)(arg1[9]) * ((arg2[9]) * ((uint32_t)0x2 * UINT8_C(0x13)))); + uint64_t x2 = ((uint64_t)(arg1[9]) * ((arg2[8]) * (uint32_t)UINT8_C(0x13))); + uint64_t x3 = ((uint64_t)(arg1[9]) * ((arg2[7]) * ((uint32_t)0x2 * UINT8_C(0x13)))); + uint64_t x4 = ((uint64_t)(arg1[9]) * ((arg2[6]) * (uint32_t)UINT8_C(0x13))); + uint64_t x5 = ((uint64_t)(arg1[9]) * ((arg2[5]) * ((uint32_t)0x2 * UINT8_C(0x13)))); + uint64_t x6 = ((uint64_t)(arg1[9]) * ((arg2[4]) * (uint32_t)UINT8_C(0x13))); + uint64_t x7 = ((uint64_t)(arg1[9]) * ((arg2[3]) * ((uint32_t)0x2 * UINT8_C(0x13)))); + uint64_t x8 = ((uint64_t)(arg1[9]) * ((arg2[2]) * (uint32_t)UINT8_C(0x13))); + uint64_t x9 = ((uint64_t)(arg1[9]) * ((arg2[1]) * ((uint32_t)0x2 * UINT8_C(0x13)))); + uint64_t x10 = ((uint64_t)(arg1[8]) * ((arg2[9]) * (uint32_t)UINT8_C(0x13))); + uint64_t x11 = ((uint64_t)(arg1[8]) * ((arg2[8]) * (uint32_t)UINT8_C(0x13))); + uint64_t x12 = ((uint64_t)(arg1[8]) * ((arg2[7]) * (uint32_t)UINT8_C(0x13))); + uint64_t x13 = ((uint64_t)(arg1[8]) * ((arg2[6]) * (uint32_t)UINT8_C(0x13))); + uint64_t x14 = ((uint64_t)(arg1[8]) * ((arg2[5]) * (uint32_t)UINT8_C(0x13))); + uint64_t x15 = ((uint64_t)(arg1[8]) * ((arg2[4]) * (uint32_t)UINT8_C(0x13))); + uint64_t x16 = ((uint64_t)(arg1[8]) * ((arg2[3]) * (uint32_t)UINT8_C(0x13))); + uint64_t x17 = ((uint64_t)(arg1[8]) * ((arg2[2]) * (uint32_t)UINT8_C(0x13))); + uint64_t x18 = ((uint64_t)(arg1[7]) * ((arg2[9]) * ((uint32_t)0x2 * UINT8_C(0x13)))); + uint64_t x19 = ((uint64_t)(arg1[7]) * ((arg2[8]) * (uint32_t)UINT8_C(0x13))); + uint64_t x20 = ((uint64_t)(arg1[7]) * ((arg2[7]) * ((uint32_t)0x2 * UINT8_C(0x13)))); + uint64_t x21 = ((uint64_t)(arg1[7]) * ((arg2[6]) * (uint32_t)UINT8_C(0x13))); + uint64_t x22 = ((uint64_t)(arg1[7]) * ((arg2[5]) * ((uint32_t)0x2 * UINT8_C(0x13)))); + uint64_t x23 = ((uint64_t)(arg1[7]) * ((arg2[4]) * (uint32_t)UINT8_C(0x13))); + uint64_t x24 = ((uint64_t)(arg1[7]) * ((arg2[3]) * ((uint32_t)0x2 * UINT8_C(0x13)))); + uint64_t x25 = ((uint64_t)(arg1[6]) * ((arg2[9]) * (uint32_t)UINT8_C(0x13))); + uint64_t x26 = ((uint64_t)(arg1[6]) * ((arg2[8]) * (uint32_t)UINT8_C(0x13))); + uint64_t x27 = ((uint64_t)(arg1[6]) * ((arg2[7]) * (uint32_t)UINT8_C(0x13))); + uint64_t x28 = ((uint64_t)(arg1[6]) * ((arg2[6]) * (uint32_t)UINT8_C(0x13))); + uint64_t x29 = ((uint64_t)(arg1[6]) * ((arg2[5]) * (uint32_t)UINT8_C(0x13))); + uint64_t x30 = ((uint64_t)(arg1[6]) * ((arg2[4]) * (uint32_t)UINT8_C(0x13))); + uint64_t x31 = ((uint64_t)(arg1[5]) * ((arg2[9]) * ((uint32_t)0x2 * UINT8_C(0x13)))); + uint64_t x32 = ((uint64_t)(arg1[5]) * ((arg2[8]) * (uint32_t)UINT8_C(0x13))); + uint64_t x33 = ((uint64_t)(arg1[5]) * ((arg2[7]) * ((uint32_t)0x2 * UINT8_C(0x13)))); + uint64_t x34 = ((uint64_t)(arg1[5]) * ((arg2[6]) * (uint32_t)UINT8_C(0x13))); + uint64_t x35 = ((uint64_t)(arg1[5]) * ((arg2[5]) * ((uint32_t)0x2 * UINT8_C(0x13)))); + uint64_t x36 = ((uint64_t)(arg1[4]) * ((arg2[9]) * (uint32_t)UINT8_C(0x13))); + uint64_t x37 = ((uint64_t)(arg1[4]) * ((arg2[8]) * (uint32_t)UINT8_C(0x13))); + uint64_t x38 = ((uint64_t)(arg1[4]) * ((arg2[7]) * (uint32_t)UINT8_C(0x13))); + uint64_t x39 = ((uint64_t)(arg1[4]) * ((arg2[6]) * (uint32_t)UINT8_C(0x13))); + uint64_t x40 = ((uint64_t)(arg1[3]) * ((arg2[9]) * ((uint32_t)0x2 * UINT8_C(0x13)))); + uint64_t x41 = ((uint64_t)(arg1[3]) * ((arg2[8]) * (uint32_t)UINT8_C(0x13))); + uint64_t x42 = ((uint64_t)(arg1[3]) * ((arg2[7]) * ((uint32_t)0x2 * UINT8_C(0x13)))); + uint64_t x43 = ((uint64_t)(arg1[2]) * ((arg2[9]) * (uint32_t)UINT8_C(0x13))); + uint64_t x44 = ((uint64_t)(arg1[2]) * ((arg2[8]) * (uint32_t)UINT8_C(0x13))); + uint64_t x45 = ((uint64_t)(arg1[1]) * ((arg2[9]) * ((uint32_t)0x2 * UINT8_C(0x13)))); + uint64_t x46 = ((uint64_t)(arg1[9]) * (arg2[0])); + uint64_t x47 = ((uint64_t)(arg1[8]) * (arg2[1])); + uint64_t x48 = ((uint64_t)(arg1[8]) * (arg2[0])); + uint64_t x49 = ((uint64_t)(arg1[7]) * (arg2[2])); + uint64_t x50 = ((uint64_t)(arg1[7]) * ((arg2[1]) * (uint32_t)0x2)); + uint64_t x51 = ((uint64_t)(arg1[7]) * (arg2[0])); + uint64_t x52 = ((uint64_t)(arg1[6]) * (arg2[3])); + uint64_t x53 = ((uint64_t)(arg1[6]) * (arg2[2])); + uint64_t x54 = ((uint64_t)(arg1[6]) * (arg2[1])); + uint64_t x55 = ((uint64_t)(arg1[6]) * (arg2[0])); + uint64_t x56 = ((uint64_t)(arg1[5]) * (arg2[4])); + uint64_t x57 = ((uint64_t)(arg1[5]) * ((arg2[3]) * (uint32_t)0x2)); + uint64_t x58 = ((uint64_t)(arg1[5]) * (arg2[2])); + uint64_t x59 = ((uint64_t)(arg1[5]) * ((arg2[1]) * (uint32_t)0x2)); + uint64_t x60 = ((uint64_t)(arg1[5]) * (arg2[0])); + uint64_t x61 = ((uint64_t)(arg1[4]) * (arg2[5])); + uint64_t x62 = ((uint64_t)(arg1[4]) * (arg2[4])); + uint64_t x63 = ((uint64_t)(arg1[4]) * (arg2[3])); + uint64_t x64 = ((uint64_t)(arg1[4]) * (arg2[2])); + uint64_t x65 = ((uint64_t)(arg1[4]) * (arg2[1])); + uint64_t x66 = ((uint64_t)(arg1[4]) * (arg2[0])); + uint64_t x67 = ((uint64_t)(arg1[3]) * (arg2[6])); + uint64_t x68 = ((uint64_t)(arg1[3]) * ((arg2[5]) * (uint32_t)0x2)); + uint64_t x69 = ((uint64_t)(arg1[3]) * (arg2[4])); + uint64_t x70 = ((uint64_t)(arg1[3]) * ((arg2[3]) * (uint32_t)0x2)); + uint64_t x71 = ((uint64_t)(arg1[3]) * (arg2[2])); + uint64_t x72 = ((uint64_t)(arg1[3]) * ((arg2[1]) * (uint32_t)0x2)); + uint64_t x73 = ((uint64_t)(arg1[3]) * (arg2[0])); + uint64_t x74 = ((uint64_t)(arg1[2]) * (arg2[7])); + uint64_t x75 = ((uint64_t)(arg1[2]) * (arg2[6])); + uint64_t x76 = ((uint64_t)(arg1[2]) * (arg2[5])); + uint64_t x77 = ((uint64_t)(arg1[2]) * (arg2[4])); + uint64_t x78 = ((uint64_t)(arg1[2]) * (arg2[3])); + uint64_t x79 = ((uint64_t)(arg1[2]) * (arg2[2])); + uint64_t x80 = ((uint64_t)(arg1[2]) * (arg2[1])); + uint64_t x81 = ((uint64_t)(arg1[2]) * (arg2[0])); + uint64_t x82 = ((uint64_t)(arg1[1]) * (arg2[8])); + uint64_t x83 = ((uint64_t)(arg1[1]) * ((arg2[7]) * (uint32_t)0x2)); + uint64_t x84 = ((uint64_t)(arg1[1]) * (arg2[6])); + uint64_t x85 = ((uint64_t)(arg1[1]) * ((arg2[5]) * (uint32_t)0x2)); + uint64_t x86 = ((uint64_t)(arg1[1]) * (arg2[4])); + uint64_t x87 = ((uint64_t)(arg1[1]) * ((arg2[3]) * (uint32_t)0x2)); + uint64_t x88 = ((uint64_t)(arg1[1]) * (arg2[2])); + uint64_t x89 = ((uint64_t)(arg1[1]) * ((arg2[1]) * (uint32_t)0x2)); + uint64_t x90 = ((uint64_t)(arg1[1]) * (arg2[0])); + uint64_t x91 = ((uint64_t)(arg1[0]) * (arg2[9])); + uint64_t x92 = ((uint64_t)(arg1[0]) * (arg2[8])); + uint64_t x93 = ((uint64_t)(arg1[0]) * (arg2[7])); + uint64_t x94 = ((uint64_t)(arg1[0]) * (arg2[6])); + uint64_t x95 = ((uint64_t)(arg1[0]) * (arg2[5])); + uint64_t x96 = ((uint64_t)(arg1[0]) * (arg2[4])); + uint64_t x97 = ((uint64_t)(arg1[0]) * (arg2[3])); + uint64_t x98 = ((uint64_t)(arg1[0]) * (arg2[2])); + uint64_t x99 = ((uint64_t)(arg1[0]) * (arg2[1])); + uint64_t x100 = ((uint64_t)(arg1[0]) * (arg2[0])); + uint64_t x101 = (x100 + (x45 + (x44 + (x42 + (x39 + (x35 + (x30 + (x24 + (x17 + x9))))))))); + uint64_t x102 = (x101 >> 26); + uint32_t x103 = (uint32_t)(x101 & UINT32_C(0x3ffffff)); + uint64_t x104 = (x91 + (x82 + (x74 + (x67 + (x61 + (x56 + (x52 + (x49 + (x47 + x46))))))))); + uint64_t x105 = (x92 + (x83 + (x75 + (x68 + (x62 + (x57 + (x53 + (x50 + (x48 + x1))))))))); + uint64_t x106 = (x93 + (x84 + (x76 + (x69 + (x63 + (x58 + (x54 + (x51 + (x10 + x2))))))))); + uint64_t x107 = (x94 + (x85 + (x77 + (x70 + (x64 + (x59 + (x55 + (x18 + (x11 + x3))))))))); + uint64_t x108 = (x95 + (x86 + (x78 + (x71 + (x65 + (x60 + (x25 + (x19 + (x12 + x4))))))))); + uint64_t x109 = (x96 + (x87 + (x79 + (x72 + (x66 + (x31 + (x26 + (x20 + (x13 + x5))))))))); + uint64_t x110 = (x97 + (x88 + (x80 + (x73 + (x36 + (x32 + (x27 + (x21 + (x14 + x6))))))))); + uint64_t x111 = (x98 + (x89 + (x81 + (x40 + (x37 + (x33 + (x28 + (x22 + (x15 + x7))))))))); + uint64_t x112 = (x99 + (x90 + (x43 + (x41 + (x38 + (x34 + (x29 + (x23 + (x16 + x8))))))))); + uint64_t x113 = (x102 + x112); + uint64_t x114 = (x113 >> 25); + uint32_t x115 = (uint32_t)(x113 & UINT32_C(0x1ffffff)); + uint64_t x116 = (x114 + x111); + uint64_t x117 = (x116 >> 26); + uint32_t x118 = (uint32_t)(x116 & UINT32_C(0x3ffffff)); + uint64_t x119 = (x117 + x110); + uint64_t x120 = (x119 >> 25); + uint32_t x121 = (uint32_t)(x119 & UINT32_C(0x1ffffff)); + uint64_t x122 = (x120 + x109); + uint64_t x123 = (x122 >> 26); + uint32_t x124 = (uint32_t)(x122 & UINT32_C(0x3ffffff)); + uint64_t x125 = (x123 + x108); + uint64_t x126 = (x125 >> 25); + uint32_t x127 = (uint32_t)(x125 & UINT32_C(0x1ffffff)); + uint64_t x128 = (x126 + x107); + uint64_t x129 = (x128 >> 26); + uint32_t x130 = (uint32_t)(x128 & UINT32_C(0x3ffffff)); + uint64_t x131 = (x129 + x106); + uint64_t x132 = (x131 >> 25); + uint32_t x133 = (uint32_t)(x131 & UINT32_C(0x1ffffff)); + uint64_t x134 = (x132 + x105); + uint64_t x135 = (x134 >> 26); + uint32_t x136 = (uint32_t)(x134 & UINT32_C(0x3ffffff)); + uint64_t x137 = (x135 + x104); + uint64_t x138 = (x137 >> 25); + uint32_t x139 = (uint32_t)(x137 & UINT32_C(0x1ffffff)); + uint64_t x140 = (x138 * (uint64_t)UINT8_C(0x13)); + uint64_t x141 = (x103 + x140); + uint32_t x142 = (uint32_t)(x141 >> 26); + uint32_t x143 = (uint32_t)(x141 & UINT32_C(0x3ffffff)); + uint32_t x144 = (x142 + x115); + uint32_t x145 = (x144 >> 25); + uint32_t x146 = (x144 & UINT32_C(0x1ffffff)); + uint32_t x147 = (x145 + x118); + out1[0] = x143; + out1[1] = x146; + out1[2] = x147; + out1[3] = x121; + out1[4] = x124; + out1[5] = x127; + out1[6] = x130; + out1[7] = x133; + out1[8] = x136; + out1[9] = x139; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999]] + * Output Bounds: + * out1: [[0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333]] + */ +static void fiat_25519_carry_square(uint32_t out1[10], const uint32_t arg1[10]) { + uint32_t x1 = ((arg1[9]) * (uint32_t)UINT8_C(0x13)); + uint32_t x2 = (x1 * (uint32_t)0x2); + uint32_t x3 = ((arg1[9]) * (uint32_t)0x2); + uint32_t x4 = ((arg1[8]) * (uint32_t)UINT8_C(0x13)); + uint64_t x5 = (x4 * (uint64_t)0x2); + uint32_t x6 = ((arg1[8]) * (uint32_t)0x2); + uint32_t x7 = ((arg1[7]) * (uint32_t)UINT8_C(0x13)); + uint32_t x8 = (x7 * (uint32_t)0x2); + uint32_t x9 = ((arg1[7]) * (uint32_t)0x2); + uint32_t x10 = ((arg1[6]) * (uint32_t)UINT8_C(0x13)); + uint64_t x11 = (x10 * (uint64_t)0x2); + uint32_t x12 = ((arg1[6]) * (uint32_t)0x2); + uint32_t x13 = ((arg1[5]) * (uint32_t)UINT8_C(0x13)); + uint32_t x14 = ((arg1[5]) * (uint32_t)0x2); + uint32_t x15 = ((arg1[4]) * (uint32_t)0x2); + uint32_t x16 = ((arg1[3]) * (uint32_t)0x2); + uint32_t x17 = ((arg1[2]) * (uint32_t)0x2); + uint32_t x18 = ((arg1[1]) * (uint32_t)0x2); + uint64_t x19 = ((uint64_t)(arg1[9]) * (x1 * (uint32_t)0x2)); + uint64_t x20 = ((uint64_t)(arg1[8]) * x2); + uint64_t x21 = ((uint64_t)(arg1[8]) * x4); + uint64_t x22 = ((arg1[7]) * (x2 * (uint64_t)0x2)); + uint64_t x23 = ((arg1[7]) * x5); + uint64_t x24 = ((uint64_t)(arg1[7]) * (x7 * (uint32_t)0x2)); + uint64_t x25 = ((uint64_t)(arg1[6]) * x2); + uint64_t x26 = ((arg1[6]) * x5); + uint64_t x27 = ((uint64_t)(arg1[6]) * x8); + uint64_t x28 = ((uint64_t)(arg1[6]) * x10); + uint64_t x29 = ((arg1[5]) * (x2 * (uint64_t)0x2)); + uint64_t x30 = ((arg1[5]) * x5); + uint64_t x31 = ((arg1[5]) * (x8 * (uint64_t)0x2)); + uint64_t x32 = ((arg1[5]) * x11); + uint64_t x33 = ((uint64_t)(arg1[5]) * (x13 * (uint32_t)0x2)); + uint64_t x34 = ((uint64_t)(arg1[4]) * x2); + uint64_t x35 = ((arg1[4]) * x5); + uint64_t x36 = ((uint64_t)(arg1[4]) * x8); + uint64_t x37 = ((arg1[4]) * x11); + uint64_t x38 = ((uint64_t)(arg1[4]) * x14); + uint64_t x39 = ((uint64_t)(arg1[4]) * (arg1[4])); + uint64_t x40 = ((arg1[3]) * (x2 * (uint64_t)0x2)); + uint64_t x41 = ((arg1[3]) * x5); + uint64_t x42 = ((arg1[3]) * (x8 * (uint64_t)0x2)); + uint64_t x43 = ((uint64_t)(arg1[3]) * x12); + uint64_t x44 = ((uint64_t)(arg1[3]) * (x14 * (uint32_t)0x2)); + uint64_t x45 = ((uint64_t)(arg1[3]) * x15); + uint64_t x46 = ((uint64_t)(arg1[3]) * ((arg1[3]) * (uint32_t)0x2)); + uint64_t x47 = ((uint64_t)(arg1[2]) * x2); + uint64_t x48 = ((arg1[2]) * x5); + uint64_t x49 = ((uint64_t)(arg1[2]) * x9); + uint64_t x50 = ((uint64_t)(arg1[2]) * x12); + uint64_t x51 = ((uint64_t)(arg1[2]) * x14); + uint64_t x52 = ((uint64_t)(arg1[2]) * x15); + uint64_t x53 = ((uint64_t)(arg1[2]) * x16); + uint64_t x54 = ((uint64_t)(arg1[2]) * (arg1[2])); + uint64_t x55 = ((arg1[1]) * (x2 * (uint64_t)0x2)); + uint64_t x56 = ((uint64_t)(arg1[1]) * x6); + uint64_t x57 = ((uint64_t)(arg1[1]) * (x9 * (uint32_t)0x2)); + uint64_t x58 = ((uint64_t)(arg1[1]) * x12); + uint64_t x59 = ((uint64_t)(arg1[1]) * (x14 * (uint32_t)0x2)); + uint64_t x60 = ((uint64_t)(arg1[1]) * x15); + uint64_t x61 = ((uint64_t)(arg1[1]) * (x16 * (uint32_t)0x2)); + uint64_t x62 = ((uint64_t)(arg1[1]) * x17); + uint64_t x63 = ((uint64_t)(arg1[1]) * ((arg1[1]) * (uint32_t)0x2)); + uint64_t x64 = ((uint64_t)(arg1[0]) * x3); + uint64_t x65 = ((uint64_t)(arg1[0]) * x6); + uint64_t x66 = ((uint64_t)(arg1[0]) * x9); + uint64_t x67 = ((uint64_t)(arg1[0]) * x12); + uint64_t x68 = ((uint64_t)(arg1[0]) * x14); + uint64_t x69 = ((uint64_t)(arg1[0]) * x15); + uint64_t x70 = ((uint64_t)(arg1[0]) * x16); + uint64_t x71 = ((uint64_t)(arg1[0]) * x17); + uint64_t x72 = ((uint64_t)(arg1[0]) * x18); + uint64_t x73 = ((uint64_t)(arg1[0]) * (arg1[0])); + uint64_t x74 = (x73 + (x55 + (x48 + (x42 + (x37 + x33))))); + uint64_t x75 = (x74 >> 26); + uint32_t x76 = (uint32_t)(x74 & UINT32_C(0x3ffffff)); + uint64_t x77 = (x64 + (x56 + (x49 + (x43 + x38)))); + uint64_t x78 = (x65 + (x57 + (x50 + (x44 + (x39 + x19))))); + uint64_t x79 = (x66 + (x58 + (x51 + (x45 + x20)))); + uint64_t x80 = (x67 + (x59 + (x52 + (x46 + (x22 + x21))))); + uint64_t x81 = (x68 + (x60 + (x53 + (x25 + x23)))); + uint64_t x82 = (x69 + (x61 + (x54 + (x29 + (x26 + x24))))); + uint64_t x83 = (x70 + (x62 + (x34 + (x30 + x27)))); + uint64_t x84 = (x71 + (x63 + (x40 + (x35 + (x31 + x28))))); + uint64_t x85 = (x72 + (x47 + (x41 + (x36 + x32)))); + uint64_t x86 = (x75 + x85); + uint64_t x87 = (x86 >> 25); + uint32_t x88 = (uint32_t)(x86 & UINT32_C(0x1ffffff)); + uint64_t x89 = (x87 + x84); + uint64_t x90 = (x89 >> 26); + uint32_t x91 = (uint32_t)(x89 & UINT32_C(0x3ffffff)); + uint64_t x92 = (x90 + x83); + uint64_t x93 = (x92 >> 25); + uint32_t x94 = (uint32_t)(x92 & UINT32_C(0x1ffffff)); + uint64_t x95 = (x93 + x82); + uint64_t x96 = (x95 >> 26); + uint32_t x97 = (uint32_t)(x95 & UINT32_C(0x3ffffff)); + uint64_t x98 = (x96 + x81); + uint64_t x99 = (x98 >> 25); + uint32_t x100 = (uint32_t)(x98 & UINT32_C(0x1ffffff)); + uint64_t x101 = (x99 + x80); + uint64_t x102 = (x101 >> 26); + uint32_t x103 = (uint32_t)(x101 & UINT32_C(0x3ffffff)); + uint64_t x104 = (x102 + x79); + uint64_t x105 = (x104 >> 25); + uint32_t x106 = (uint32_t)(x104 & UINT32_C(0x1ffffff)); + uint64_t x107 = (x105 + x78); + uint64_t x108 = (x107 >> 26); + uint32_t x109 = (uint32_t)(x107 & UINT32_C(0x3ffffff)); + uint64_t x110 = (x108 + x77); + uint64_t x111 = (x110 >> 25); + uint32_t x112 = (uint32_t)(x110 & UINT32_C(0x1ffffff)); + uint64_t x113 = (x111 * (uint64_t)UINT8_C(0x13)); + uint64_t x114 = (x76 + x113); + uint32_t x115 = (uint32_t)(x114 >> 26); + uint32_t x116 = (uint32_t)(x114 & UINT32_C(0x3ffffff)); + uint32_t x117 = (x115 + x88); + uint32_t x118 = (x117 >> 25); + uint32_t x119 = (x117 & UINT32_C(0x1ffffff)); + uint32_t x120 = (x118 + x91); + out1[0] = x116; + out1[1] = x119; + out1[2] = x120; + out1[3] = x94; + out1[4] = x97; + out1[5] = x100; + out1[6] = x103; + out1[7] = x106; + out1[8] = x109; + out1[9] = x112; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999]] + * Output Bounds: + * out1: [[0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333]] + */ +static void fiat_25519_carry_scmul_121666(uint32_t out1[10], const uint32_t arg1[10]) { + uint64_t x1 = ((uint64_t)UINT32_C(0x1db42) * (arg1[9])); + uint64_t x2 = ((uint64_t)UINT32_C(0x1db42) * (arg1[8])); + uint64_t x3 = ((uint64_t)UINT32_C(0x1db42) * (arg1[7])); + uint64_t x4 = ((uint64_t)UINT32_C(0x1db42) * (arg1[6])); + uint64_t x5 = ((uint64_t)UINT32_C(0x1db42) * (arg1[5])); + uint64_t x6 = ((uint64_t)UINT32_C(0x1db42) * (arg1[4])); + uint64_t x7 = ((uint64_t)UINT32_C(0x1db42) * (arg1[3])); + uint64_t x8 = ((uint64_t)UINT32_C(0x1db42) * (arg1[2])); + uint64_t x9 = ((uint64_t)UINT32_C(0x1db42) * (arg1[1])); + uint64_t x10 = ((uint64_t)UINT32_C(0x1db42) * (arg1[0])); + uint32_t x11 = (uint32_t)(x10 >> 26); + uint32_t x12 = (uint32_t)(x10 & UINT32_C(0x3ffffff)); + uint64_t x13 = (x11 + x9); + uint32_t x14 = (uint32_t)(x13 >> 25); + uint32_t x15 = (uint32_t)(x13 & UINT32_C(0x1ffffff)); + uint64_t x16 = (x14 + x8); + uint32_t x17 = (uint32_t)(x16 >> 26); + uint32_t x18 = (uint32_t)(x16 & UINT32_C(0x3ffffff)); + uint64_t x19 = (x17 + x7); + uint32_t x20 = (uint32_t)(x19 >> 25); + uint32_t x21 = (uint32_t)(x19 & UINT32_C(0x1ffffff)); + uint64_t x22 = (x20 + x6); + uint32_t x23 = (uint32_t)(x22 >> 26); + uint32_t x24 = (uint32_t)(x22 & UINT32_C(0x3ffffff)); + uint64_t x25 = (x23 + x5); + uint32_t x26 = (uint32_t)(x25 >> 25); + uint32_t x27 = (uint32_t)(x25 & UINT32_C(0x1ffffff)); + uint64_t x28 = (x26 + x4); + uint32_t x29 = (uint32_t)(x28 >> 26); + uint32_t x30 = (uint32_t)(x28 & UINT32_C(0x3ffffff)); + uint64_t x31 = (x29 + x3); + uint32_t x32 = (uint32_t)(x31 >> 25); + uint32_t x33 = (uint32_t)(x31 & UINT32_C(0x1ffffff)); + uint64_t x34 = (x32 + x2); + uint32_t x35 = (uint32_t)(x34 >> 26); + uint32_t x36 = (uint32_t)(x34 & UINT32_C(0x3ffffff)); + uint64_t x37 = (x35 + x1); + uint32_t x38 = (uint32_t)(x37 >> 25); + uint32_t x39 = (uint32_t)(x37 & UINT32_C(0x1ffffff)); + uint32_t x40 = (x38 * (uint32_t)UINT8_C(0x13)); + uint32_t x41 = (x12 + x40); + uint32_t x42 = (x41 >> 26); + uint32_t x43 = (x41 & UINT32_C(0x3ffffff)); + uint32_t x44 = (x42 + x15); + uint32_t x45 = (x44 >> 25); + uint32_t x46 = (x44 & UINT32_C(0x1ffffff)); + uint32_t x47 = (x45 + x18); + out1[0] = x43; + out1[1] = x46; + out1[2] = x47; + out1[3] = x21; + out1[4] = x24; + out1[5] = x27; + out1[6] = x30; + out1[7] = x33; + out1[8] = x36; + out1[9] = x39; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999]] + * Output Bounds: + * out1: [[0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333]] + */ +static void fiat_25519_carry(uint32_t out1[10], const uint32_t arg1[10]) { + uint32_t x1 = (arg1[0]); + uint32_t x2 = ((x1 >> 26) + (arg1[1])); + uint32_t x3 = ((x2 >> 25) + (arg1[2])); + uint32_t x4 = ((x3 >> 26) + (arg1[3])); + uint32_t x5 = ((x4 >> 25) + (arg1[4])); + uint32_t x6 = ((x5 >> 26) + (arg1[5])); + uint32_t x7 = ((x6 >> 25) + (arg1[6])); + uint32_t x8 = ((x7 >> 26) + (arg1[7])); + uint32_t x9 = ((x8 >> 25) + (arg1[8])); + uint32_t x10 = ((x9 >> 26) + (arg1[9])); + uint32_t x11 = ((x1 & UINT32_C(0x3ffffff)) + ((x10 >> 25) * (uint32_t)UINT8_C(0x13))); + uint32_t x12 = ((x11 >> 26) + (x2 & UINT32_C(0x1ffffff))); + uint32_t x13 = (x11 & UINT32_C(0x3ffffff)); + uint32_t x14 = (x12 & UINT32_C(0x1ffffff)); + uint32_t x15 = ((x12 >> 25) + (x3 & UINT32_C(0x3ffffff))); + uint32_t x16 = (x4 & UINT32_C(0x1ffffff)); + uint32_t x17 = (x5 & UINT32_C(0x3ffffff)); + uint32_t x18 = (x6 & UINT32_C(0x1ffffff)); + uint32_t x19 = (x7 & UINT32_C(0x3ffffff)); + uint32_t x20 = (x8 & UINT32_C(0x1ffffff)); + uint32_t x21 = (x9 & UINT32_C(0x3ffffff)); + uint32_t x22 = (x10 & UINT32_C(0x1ffffff)); + out1[0] = x13; + out1[1] = x14; + out1[2] = x15; + out1[3] = x16; + out1[4] = x17; + out1[5] = x18; + out1[6] = x19; + out1[7] = x20; + out1[8] = x21; + out1[9] = x22; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333]] + * arg2: [[0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333]] + * Output Bounds: + * out1: [[0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999]] + */ +static void fiat_25519_add(uint32_t out1[10], const uint32_t arg1[10], const uint32_t arg2[10]) { + uint32_t x1 = ((arg1[0]) + (arg2[0])); + uint32_t x2 = ((arg1[1]) + (arg2[1])); + uint32_t x3 = ((arg1[2]) + (arg2[2])); + uint32_t x4 = ((arg1[3]) + (arg2[3])); + uint32_t x5 = ((arg1[4]) + (arg2[4])); + uint32_t x6 = ((arg1[5]) + (arg2[5])); + uint32_t x7 = ((arg1[6]) + (arg2[6])); + uint32_t x8 = ((arg1[7]) + (arg2[7])); + uint32_t x9 = ((arg1[8]) + (arg2[8])); + uint32_t x10 = ((arg1[9]) + (arg2[9])); + out1[0] = x1; + out1[1] = x2; + out1[2] = x3; + out1[3] = x4; + out1[4] = x5; + out1[5] = x6; + out1[6] = x7; + out1[7] = x8; + out1[8] = x9; + out1[9] = x10; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333]] + * arg2: [[0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333]] + * Output Bounds: + * out1: [[0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999]] + */ +static void fiat_25519_sub(uint32_t out1[10], const uint32_t arg1[10], const uint32_t arg2[10]) { + uint32_t x1 = ((UINT32_C(0x7ffffda) + (arg1[0])) - (arg2[0])); + uint32_t x2 = ((UINT32_C(0x3fffffe) + (arg1[1])) - (arg2[1])); + uint32_t x3 = ((UINT32_C(0x7fffffe) + (arg1[2])) - (arg2[2])); + uint32_t x4 = ((UINT32_C(0x3fffffe) + (arg1[3])) - (arg2[3])); + uint32_t x5 = ((UINT32_C(0x7fffffe) + (arg1[4])) - (arg2[4])); + uint32_t x6 = ((UINT32_C(0x3fffffe) + (arg1[5])) - (arg2[5])); + uint32_t x7 = ((UINT32_C(0x7fffffe) + (arg1[6])) - (arg2[6])); + uint32_t x8 = ((UINT32_C(0x3fffffe) + (arg1[7])) - (arg2[7])); + uint32_t x9 = ((UINT32_C(0x7fffffe) + (arg1[8])) - (arg2[8])); + uint32_t x10 = ((UINT32_C(0x3fffffe) + (arg1[9])) - (arg2[9])); + out1[0] = x1; + out1[1] = x2; + out1[2] = x3; + out1[3] = x4; + out1[4] = x5; + out1[5] = x6; + out1[6] = x7; + out1[7] = x8; + out1[8] = x9; + out1[9] = x10; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333]] + * Output Bounds: + * out1: [[0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], [0x0 ~> 0xd333332], [0x0 ~> 0x6999999]] + */ +static void fiat_25519_opp(uint32_t out1[10], const uint32_t arg1[10]) { + uint32_t x1 = (UINT32_C(0x7ffffda) - (arg1[0])); + uint32_t x2 = (UINT32_C(0x3fffffe) - (arg1[1])); + uint32_t x3 = (UINT32_C(0x7fffffe) - (arg1[2])); + uint32_t x4 = (UINT32_C(0x3fffffe) - (arg1[3])); + uint32_t x5 = (UINT32_C(0x7fffffe) - (arg1[4])); + uint32_t x6 = (UINT32_C(0x3fffffe) - (arg1[5])); + uint32_t x7 = (UINT32_C(0x7fffffe) - (arg1[6])); + uint32_t x8 = (UINT32_C(0x3fffffe) - (arg1[7])); + uint32_t x9 = (UINT32_C(0x7fffffe) - (arg1[8])); + uint32_t x10 = (UINT32_C(0x3fffffe) - (arg1[9])); + out1[0] = x1; + out1[1] = x2; + out1[2] = x3; + out1[3] = x4; + out1[4] = x5; + out1[5] = x6; + out1[6] = x7; + out1[7] = x8; + out1[8] = x9; + out1[9] = x10; +} + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + * arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + */ +static void fiat_25519_selectznz(uint32_t out1[10], fiat_25519_uint1 arg1, const uint32_t arg2[10], const uint32_t arg3[10]) { + uint32_t x1; + fiat_25519_cmovznz_u32(&x1, arg1, (arg2[0]), (arg3[0])); + uint32_t x2; + fiat_25519_cmovznz_u32(&x2, arg1, (arg2[1]), (arg3[1])); + uint32_t x3; + fiat_25519_cmovznz_u32(&x3, arg1, (arg2[2]), (arg3[2])); + uint32_t x4; + fiat_25519_cmovznz_u32(&x4, arg1, (arg2[3]), (arg3[3])); + uint32_t x5; + fiat_25519_cmovznz_u32(&x5, arg1, (arg2[4]), (arg3[4])); + uint32_t x6; + fiat_25519_cmovznz_u32(&x6, arg1, (arg2[5]), (arg3[5])); + uint32_t x7; + fiat_25519_cmovznz_u32(&x7, arg1, (arg2[6]), (arg3[6])); + uint32_t x8; + fiat_25519_cmovznz_u32(&x8, arg1, (arg2[7]), (arg3[7])); + uint32_t x9; + fiat_25519_cmovznz_u32(&x9, arg1, (arg2[8]), (arg3[8])); + uint32_t x10; + fiat_25519_cmovznz_u32(&x10, arg1, (arg2[9]), (arg3[9])); + out1[0] = x1; + out1[1] = x2; + out1[2] = x3; + out1[3] = x4; + out1[4] = x5; + out1[5] = x6; + out1[6] = x7; + out1[7] = x8; + out1[8] = x9; + out1[9] = x10; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333]] + * Output Bounds: + * out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x7f]] + */ +static void fiat_25519_to_bytes(uint8_t out1[32], const uint32_t arg1[10]) { + uint32_t x1; + fiat_25519_uint1 x2; + fiat_25519_subborrowx_u26(&x1, &x2, 0x0, (arg1[0]), UINT32_C(0x3ffffed)); + uint32_t x3; + fiat_25519_uint1 x4; + fiat_25519_subborrowx_u25(&x3, &x4, x2, (arg1[1]), UINT32_C(0x1ffffff)); + uint32_t x5; + fiat_25519_uint1 x6; + fiat_25519_subborrowx_u26(&x5, &x6, x4, (arg1[2]), UINT32_C(0x3ffffff)); + uint32_t x7; + fiat_25519_uint1 x8; + fiat_25519_subborrowx_u25(&x7, &x8, x6, (arg1[3]), UINT32_C(0x1ffffff)); + uint32_t x9; + fiat_25519_uint1 x10; + fiat_25519_subborrowx_u26(&x9, &x10, x8, (arg1[4]), UINT32_C(0x3ffffff)); + uint32_t x11; + fiat_25519_uint1 x12; + fiat_25519_subborrowx_u25(&x11, &x12, x10, (arg1[5]), UINT32_C(0x1ffffff)); + uint32_t x13; + fiat_25519_uint1 x14; + fiat_25519_subborrowx_u26(&x13, &x14, x12, (arg1[6]), UINT32_C(0x3ffffff)); + uint32_t x15; + fiat_25519_uint1 x16; + fiat_25519_subborrowx_u25(&x15, &x16, x14, (arg1[7]), UINT32_C(0x1ffffff)); + uint32_t x17; + fiat_25519_uint1 x18; + fiat_25519_subborrowx_u26(&x17, &x18, x16, (arg1[8]), UINT32_C(0x3ffffff)); + uint32_t x19; + fiat_25519_uint1 x20; + fiat_25519_subborrowx_u25(&x19, &x20, x18, (arg1[9]), UINT32_C(0x1ffffff)); + uint32_t x21; + fiat_25519_cmovznz_u32(&x21, x20, 0x0, UINT32_C(0xffffffff)); + uint32_t x22; + fiat_25519_uint1 x23; + fiat_25519_addcarryx_u26(&x22, &x23, 0x0, (x21 & UINT32_C(0x3ffffed)), x1); + uint32_t x24; + fiat_25519_uint1 x25; + fiat_25519_addcarryx_u25(&x24, &x25, x23, (x21 & UINT32_C(0x1ffffff)), x3); + uint32_t x26; + fiat_25519_uint1 x27; + fiat_25519_addcarryx_u26(&x26, &x27, x25, (x21 & UINT32_C(0x3ffffff)), x5); + uint32_t x28; + fiat_25519_uint1 x29; + fiat_25519_addcarryx_u25(&x28, &x29, x27, (x21 & UINT32_C(0x1ffffff)), x7); + uint32_t x30; + fiat_25519_uint1 x31; + fiat_25519_addcarryx_u26(&x30, &x31, x29, (x21 & UINT32_C(0x3ffffff)), x9); + uint32_t x32; + fiat_25519_uint1 x33; + fiat_25519_addcarryx_u25(&x32, &x33, x31, (x21 & UINT32_C(0x1ffffff)), x11); + uint32_t x34; + fiat_25519_uint1 x35; + fiat_25519_addcarryx_u26(&x34, &x35, x33, (x21 & UINT32_C(0x3ffffff)), x13); + uint32_t x36; + fiat_25519_uint1 x37; + fiat_25519_addcarryx_u25(&x36, &x37, x35, (x21 & UINT32_C(0x1ffffff)), x15); + uint32_t x38; + fiat_25519_uint1 x39; + fiat_25519_addcarryx_u26(&x38, &x39, x37, (x21 & UINT32_C(0x3ffffff)), x17); + uint32_t x40; + fiat_25519_uint1 x41; + fiat_25519_addcarryx_u25(&x40, &x41, x39, (x21 & UINT32_C(0x1ffffff)), x19); + uint32_t x42 = (x40 << 6); + uint32_t x43 = (x38 << 4); + uint32_t x44 = (x36 << 3); + uint32_t x45 = (x34 * (uint32_t)0x2); + uint32_t x46 = (x30 << 6); + uint32_t x47 = (x28 << 5); + uint32_t x48 = (x26 << 3); + uint32_t x49 = (x24 << 2); + uint32_t x50 = (x22 >> 8); + uint8_t x51 = (uint8_t)(x22 & UINT8_C(0xff)); + uint32_t x52 = (x50 >> 8); + uint8_t x53 = (uint8_t)(x50 & UINT8_C(0xff)); + uint8_t x54 = (uint8_t)(x52 >> 8); + uint8_t x55 = (uint8_t)(x52 & UINT8_C(0xff)); + uint32_t x56 = (x54 + x49); + uint32_t x57 = (x56 >> 8); + uint8_t x58 = (uint8_t)(x56 & UINT8_C(0xff)); + uint32_t x59 = (x57 >> 8); + uint8_t x60 = (uint8_t)(x57 & UINT8_C(0xff)); + uint8_t x61 = (uint8_t)(x59 >> 8); + uint8_t x62 = (uint8_t)(x59 & UINT8_C(0xff)); + uint32_t x63 = (x61 + x48); + uint32_t x64 = (x63 >> 8); + uint8_t x65 = (uint8_t)(x63 & UINT8_C(0xff)); + uint32_t x66 = (x64 >> 8); + uint8_t x67 = (uint8_t)(x64 & UINT8_C(0xff)); + uint8_t x68 = (uint8_t)(x66 >> 8); + uint8_t x69 = (uint8_t)(x66 & UINT8_C(0xff)); + uint32_t x70 = (x68 + x47); + uint32_t x71 = (x70 >> 8); + uint8_t x72 = (uint8_t)(x70 & UINT8_C(0xff)); + uint32_t x73 = (x71 >> 8); + uint8_t x74 = (uint8_t)(x71 & UINT8_C(0xff)); + uint8_t x75 = (uint8_t)(x73 >> 8); + uint8_t x76 = (uint8_t)(x73 & UINT8_C(0xff)); + uint32_t x77 = (x75 + x46); + uint32_t x78 = (x77 >> 8); + uint8_t x79 = (uint8_t)(x77 & UINT8_C(0xff)); + uint32_t x80 = (x78 >> 8); + uint8_t x81 = (uint8_t)(x78 & UINT8_C(0xff)); + uint8_t x82 = (uint8_t)(x80 >> 8); + uint8_t x83 = (uint8_t)(x80 & UINT8_C(0xff)); + uint8_t x84 = (uint8_t)(x82 & UINT8_C(0xff)); + uint32_t x85 = (x32 >> 8); + uint8_t x86 = (uint8_t)(x32 & UINT8_C(0xff)); + uint32_t x87 = (x85 >> 8); + uint8_t x88 = (uint8_t)(x85 & UINT8_C(0xff)); + fiat_25519_uint1 x89 = (fiat_25519_uint1)(x87 >> 8); + uint8_t x90 = (uint8_t)(x87 & UINT8_C(0xff)); + uint32_t x91 = (x89 + x45); + uint32_t x92 = (x91 >> 8); + uint8_t x93 = (uint8_t)(x91 & UINT8_C(0xff)); + uint32_t x94 = (x92 >> 8); + uint8_t x95 = (uint8_t)(x92 & UINT8_C(0xff)); + uint8_t x96 = (uint8_t)(x94 >> 8); + uint8_t x97 = (uint8_t)(x94 & UINT8_C(0xff)); + uint32_t x98 = (x96 + x44); + uint32_t x99 = (x98 >> 8); + uint8_t x100 = (uint8_t)(x98 & UINT8_C(0xff)); + uint32_t x101 = (x99 >> 8); + uint8_t x102 = (uint8_t)(x99 & UINT8_C(0xff)); + uint8_t x103 = (uint8_t)(x101 >> 8); + uint8_t x104 = (uint8_t)(x101 & UINT8_C(0xff)); + uint32_t x105 = (x103 + x43); + uint32_t x106 = (x105 >> 8); + uint8_t x107 = (uint8_t)(x105 & UINT8_C(0xff)); + uint32_t x108 = (x106 >> 8); + uint8_t x109 = (uint8_t)(x106 & UINT8_C(0xff)); + uint8_t x110 = (uint8_t)(x108 >> 8); + uint8_t x111 = (uint8_t)(x108 & UINT8_C(0xff)); + uint32_t x112 = (x110 + x42); + uint32_t x113 = (x112 >> 8); + uint8_t x114 = (uint8_t)(x112 & UINT8_C(0xff)); + uint32_t x115 = (x113 >> 8); + uint8_t x116 = (uint8_t)(x113 & UINT8_C(0xff)); + uint8_t x117 = (uint8_t)(x115 >> 8); + uint8_t x118 = (uint8_t)(x115 & UINT8_C(0xff)); + out1[0] = x51; + out1[1] = x53; + out1[2] = x55; + out1[3] = x58; + out1[4] = x60; + out1[5] = x62; + out1[6] = x65; + out1[7] = x67; + out1[8] = x69; + out1[9] = x72; + out1[10] = x74; + out1[11] = x76; + out1[12] = x79; + out1[13] = x81; + out1[14] = x83; + out1[15] = x84; + out1[16] = x86; + out1[17] = x88; + out1[18] = x90; + out1[19] = x93; + out1[20] = x95; + out1[21] = x97; + out1[22] = x100; + out1[23] = x102; + out1[24] = x104; + out1[25] = x107; + out1[26] = x109; + out1[27] = x111; + out1[28] = x114; + out1[29] = x116; + out1[30] = x118; + out1[31] = x117; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x7f]] + * Output Bounds: + * out1: [[0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], [0x0 ~> 0x4666666], [0x0 ~> 0x2333333]] + */ +static void fiat_25519_from_bytes(uint32_t out1[10], const uint8_t arg1[32]) { + uint32_t x1 = ((uint32_t)(arg1[31]) << 18); + uint32_t x2 = ((uint32_t)(arg1[30]) << 10); + uint32_t x3 = ((uint32_t)(arg1[29]) << 2); + uint32_t x4 = ((uint32_t)(arg1[28]) << 20); + uint32_t x5 = ((uint32_t)(arg1[27]) << 12); + uint32_t x6 = ((uint32_t)(arg1[26]) << 4); + uint32_t x7 = ((uint32_t)(arg1[25]) << 21); + uint32_t x8 = ((uint32_t)(arg1[24]) << 13); + uint32_t x9 = ((uint32_t)(arg1[23]) << 5); + uint32_t x10 = ((uint32_t)(arg1[22]) << 23); + uint32_t x11 = ((uint32_t)(arg1[21]) << 15); + uint32_t x12 = ((uint32_t)(arg1[20]) << 7); + uint32_t x13 = ((uint32_t)(arg1[19]) << 24); + uint32_t x14 = ((uint32_t)(arg1[18]) << 16); + uint32_t x15 = ((uint32_t)(arg1[17]) << 8); + uint8_t x16 = (arg1[16]); + uint32_t x17 = ((uint32_t)(arg1[15]) << 18); + uint32_t x18 = ((uint32_t)(arg1[14]) << 10); + uint32_t x19 = ((uint32_t)(arg1[13]) << 2); + uint32_t x20 = ((uint32_t)(arg1[12]) << 19); + uint32_t x21 = ((uint32_t)(arg1[11]) << 11); + uint32_t x22 = ((uint32_t)(arg1[10]) << 3); + uint32_t x23 = ((uint32_t)(arg1[9]) << 21); + uint32_t x24 = ((uint32_t)(arg1[8]) << 13); + uint32_t x25 = ((uint32_t)(arg1[7]) << 5); + uint32_t x26 = ((uint32_t)(arg1[6]) << 22); + uint32_t x27 = ((uint32_t)(arg1[5]) << 14); + uint32_t x28 = ((uint32_t)(arg1[4]) << 6); + uint32_t x29 = ((uint32_t)(arg1[3]) << 24); + uint32_t x30 = ((uint32_t)(arg1[2]) << 16); + uint32_t x31 = ((uint32_t)(arg1[1]) << 8); + uint8_t x32 = (arg1[0]); + uint32_t x33 = (x32 + (x31 + (x30 + x29))); + uint8_t x34 = (uint8_t)(x33 >> 26); + uint32_t x35 = (x33 & UINT32_C(0x3ffffff)); + uint32_t x36 = (x3 + (x2 + x1)); + uint32_t x37 = (x6 + (x5 + x4)); + uint32_t x38 = (x9 + (x8 + x7)); + uint32_t x39 = (x12 + (x11 + x10)); + uint32_t x40 = (x16 + (x15 + (x14 + x13))); + uint32_t x41 = (x19 + (x18 + x17)); + uint32_t x42 = (x22 + (x21 + x20)); + uint32_t x43 = (x25 + (x24 + x23)); + uint32_t x44 = (x28 + (x27 + x26)); + uint32_t x45 = (x34 + x44); + uint8_t x46 = (uint8_t)(x45 >> 25); + uint32_t x47 = (x45 & UINT32_C(0x1ffffff)); + uint32_t x48 = (x46 + x43); + uint8_t x49 = (uint8_t)(x48 >> 26); + uint32_t x50 = (x48 & UINT32_C(0x3ffffff)); + uint32_t x51 = (x49 + x42); + uint8_t x52 = (uint8_t)(x51 >> 25); + uint32_t x53 = (x51 & UINT32_C(0x1ffffff)); + uint32_t x54 = (x52 + x41); + uint32_t x55 = (x54 & UINT32_C(0x3ffffff)); + uint8_t x56 = (uint8_t)(x40 >> 25); + uint32_t x57 = (x40 & UINT32_C(0x1ffffff)); + uint32_t x58 = (x56 + x39); + uint8_t x59 = (uint8_t)(x58 >> 26); + uint32_t x60 = (x58 & UINT32_C(0x3ffffff)); + uint32_t x61 = (x59 + x38); + uint8_t x62 = (uint8_t)(x61 >> 25); + uint32_t x63 = (x61 & UINT32_C(0x1ffffff)); + uint32_t x64 = (x62 + x37); + uint8_t x65 = (uint8_t)(x64 >> 26); + uint32_t x66 = (x64 & UINT32_C(0x3ffffff)); + uint32_t x67 = (x65 + x36); + out1[0] = x35; + out1[1] = x47; + out1[2] = x50; + out1[3] = x53; + out1[4] = x55; + out1[5] = x57; + out1[6] = x60; + out1[7] = x63; + out1[8] = x66; + out1[9] = x67; +} + diff --git a/third_party/boringssl/kit/src/third_party/fiat/curve25519_64.h b/third_party/boringssl/kit/src/third_party/fiat/curve25519_64.h new file mode 100644 index 00000000..23bf361d --- /dev/null +++ b/third_party/boringssl/kit/src/third_party/fiat/curve25519_64.h @@ -0,0 +1,553 @@ +/* Autogenerated */ +/* curve description: 25519 */ +/* requested operations: carry_mul, carry_square, carry_scmul121666, carry, add, sub, opp, selectznz, to_bytes, from_bytes */ +/* n = 5 (from "5") */ +/* s = 0x8000000000000000000000000000000000000000000000000000000000000000 (from "2^255") */ +/* c = [(1, 19)] (from "1,19") */ +/* machine_wordsize = 64 (from "64") */ + +#include +typedef unsigned char fiat_25519_uint1; +typedef signed char fiat_25519_int1; +typedef signed __int128 fiat_25519_int128; +typedef unsigned __int128 fiat_25519_uint128; + + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [0x0 ~> 0x7ffffffffffff] + * arg3: [0x0 ~> 0x7ffffffffffff] + * Output Bounds: + * out1: [0x0 ~> 0x7ffffffffffff] + * out2: [0x0 ~> 0x1] + */ +static void fiat_25519_addcarryx_u51(uint64_t* out1, fiat_25519_uint1* out2, fiat_25519_uint1 arg1, uint64_t arg2, uint64_t arg3) { + uint64_t x1 = ((arg1 + arg2) + arg3); + uint64_t x2 = (x1 & UINT64_C(0x7ffffffffffff)); + fiat_25519_uint1 x3 = (fiat_25519_uint1)(x1 >> 51); + *out1 = x2; + *out2 = x3; +} + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [0x0 ~> 0x7ffffffffffff] + * arg3: [0x0 ~> 0x7ffffffffffff] + * Output Bounds: + * out1: [0x0 ~> 0x7ffffffffffff] + * out2: [0x0 ~> 0x1] + */ +static void fiat_25519_subborrowx_u51(uint64_t* out1, fiat_25519_uint1* out2, fiat_25519_uint1 arg1, uint64_t arg2, uint64_t arg3) { + int64_t x1 = ((int64_t)(arg2 - (int64_t)arg1) - (int64_t)arg3); + fiat_25519_int1 x2 = (fiat_25519_int1)(x1 >> 51); + uint64_t x3 = (x1 & UINT64_C(0x7ffffffffffff)); + *out1 = x3; + *out2 = (fiat_25519_uint1)(0x0 - x2); +} + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [0x0 ~> 0xffffffffffffffff] + * arg3: [0x0 ~> 0xffffffffffffffff] + * Output Bounds: + * out1: [0x0 ~> 0xffffffffffffffff] + */ +static void fiat_25519_cmovznz_u64(uint64_t* out1, fiat_25519_uint1 arg1, uint64_t arg2, uint64_t arg3) { + fiat_25519_uint1 x1 = (!(!arg1)); + uint64_t x2 = ((fiat_25519_int1)(0x0 - x1) & UINT64_C(0xffffffffffffffff)); + uint64_t x3 = ((x2 & arg3) | ((~x2) & arg2)); + *out1 = x3; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664]] + * arg2: [[0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664]] + * Output Bounds: + * out1: [[0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc]] + */ +static void fiat_25519_carry_mul(uint64_t out1[5], const uint64_t arg1[5], const uint64_t arg2[5]) { + fiat_25519_uint128 x1 = ((fiat_25519_uint128)(arg1[4]) * ((arg2[4]) * (uint64_t)UINT8_C(0x13))); + fiat_25519_uint128 x2 = ((fiat_25519_uint128)(arg1[4]) * ((arg2[3]) * (uint64_t)UINT8_C(0x13))); + fiat_25519_uint128 x3 = ((fiat_25519_uint128)(arg1[4]) * ((arg2[2]) * (uint64_t)UINT8_C(0x13))); + fiat_25519_uint128 x4 = ((fiat_25519_uint128)(arg1[4]) * ((arg2[1]) * (uint64_t)UINT8_C(0x13))); + fiat_25519_uint128 x5 = ((fiat_25519_uint128)(arg1[3]) * ((arg2[4]) * (uint64_t)UINT8_C(0x13))); + fiat_25519_uint128 x6 = ((fiat_25519_uint128)(arg1[3]) * ((arg2[3]) * (uint64_t)UINT8_C(0x13))); + fiat_25519_uint128 x7 = ((fiat_25519_uint128)(arg1[3]) * ((arg2[2]) * (uint64_t)UINT8_C(0x13))); + fiat_25519_uint128 x8 = ((fiat_25519_uint128)(arg1[2]) * ((arg2[4]) * (uint64_t)UINT8_C(0x13))); + fiat_25519_uint128 x9 = ((fiat_25519_uint128)(arg1[2]) * ((arg2[3]) * (uint64_t)UINT8_C(0x13))); + fiat_25519_uint128 x10 = ((fiat_25519_uint128)(arg1[1]) * ((arg2[4]) * (uint64_t)UINT8_C(0x13))); + fiat_25519_uint128 x11 = ((fiat_25519_uint128)(arg1[4]) * (arg2[0])); + fiat_25519_uint128 x12 = ((fiat_25519_uint128)(arg1[3]) * (arg2[1])); + fiat_25519_uint128 x13 = ((fiat_25519_uint128)(arg1[3]) * (arg2[0])); + fiat_25519_uint128 x14 = ((fiat_25519_uint128)(arg1[2]) * (arg2[2])); + fiat_25519_uint128 x15 = ((fiat_25519_uint128)(arg1[2]) * (arg2[1])); + fiat_25519_uint128 x16 = ((fiat_25519_uint128)(arg1[2]) * (arg2[0])); + fiat_25519_uint128 x17 = ((fiat_25519_uint128)(arg1[1]) * (arg2[3])); + fiat_25519_uint128 x18 = ((fiat_25519_uint128)(arg1[1]) * (arg2[2])); + fiat_25519_uint128 x19 = ((fiat_25519_uint128)(arg1[1]) * (arg2[1])); + fiat_25519_uint128 x20 = ((fiat_25519_uint128)(arg1[1]) * (arg2[0])); + fiat_25519_uint128 x21 = ((fiat_25519_uint128)(arg1[0]) * (arg2[4])); + fiat_25519_uint128 x22 = ((fiat_25519_uint128)(arg1[0]) * (arg2[3])); + fiat_25519_uint128 x23 = ((fiat_25519_uint128)(arg1[0]) * (arg2[2])); + fiat_25519_uint128 x24 = ((fiat_25519_uint128)(arg1[0]) * (arg2[1])); + fiat_25519_uint128 x25 = ((fiat_25519_uint128)(arg1[0]) * (arg2[0])); + fiat_25519_uint128 x26 = (x25 + (x10 + (x9 + (x7 + x4)))); + uint64_t x27 = (uint64_t)(x26 >> 51); + uint64_t x28 = (uint64_t)(x26 & UINT64_C(0x7ffffffffffff)); + fiat_25519_uint128 x29 = (x21 + (x17 + (x14 + (x12 + x11)))); + fiat_25519_uint128 x30 = (x22 + (x18 + (x15 + (x13 + x1)))); + fiat_25519_uint128 x31 = (x23 + (x19 + (x16 + (x5 + x2)))); + fiat_25519_uint128 x32 = (x24 + (x20 + (x8 + (x6 + x3)))); + fiat_25519_uint128 x33 = (x27 + x32); + uint64_t x34 = (uint64_t)(x33 >> 51); + uint64_t x35 = (uint64_t)(x33 & UINT64_C(0x7ffffffffffff)); + fiat_25519_uint128 x36 = (x34 + x31); + uint64_t x37 = (uint64_t)(x36 >> 51); + uint64_t x38 = (uint64_t)(x36 & UINT64_C(0x7ffffffffffff)); + fiat_25519_uint128 x39 = (x37 + x30); + uint64_t x40 = (uint64_t)(x39 >> 51); + uint64_t x41 = (uint64_t)(x39 & UINT64_C(0x7ffffffffffff)); + fiat_25519_uint128 x42 = (x40 + x29); + uint64_t x43 = (uint64_t)(x42 >> 51); + uint64_t x44 = (uint64_t)(x42 & UINT64_C(0x7ffffffffffff)); + uint64_t x45 = (x43 * (uint64_t)UINT8_C(0x13)); + uint64_t x46 = (x28 + x45); + uint64_t x47 = (x46 >> 51); + uint64_t x48 = (x46 & UINT64_C(0x7ffffffffffff)); + uint64_t x49 = (x47 + x35); + uint64_t x50 = (x49 >> 51); + uint64_t x51 = (x49 & UINT64_C(0x7ffffffffffff)); + uint64_t x52 = (x50 + x38); + out1[0] = x48; + out1[1] = x51; + out1[2] = x52; + out1[3] = x41; + out1[4] = x44; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664]] + * Output Bounds: + * out1: [[0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc]] + */ +static void fiat_25519_carry_square(uint64_t out1[5], const uint64_t arg1[5]) { + uint64_t x1 = ((arg1[4]) * (uint64_t)UINT8_C(0x13)); + uint64_t x2 = (x1 * (uint64_t)0x2); + uint64_t x3 = ((arg1[4]) * (uint64_t)0x2); + uint64_t x4 = ((arg1[3]) * (uint64_t)UINT8_C(0x13)); + uint64_t x5 = (x4 * (uint64_t)0x2); + uint64_t x6 = ((arg1[3]) * (uint64_t)0x2); + uint64_t x7 = ((arg1[2]) * (uint64_t)0x2); + uint64_t x8 = ((arg1[1]) * (uint64_t)0x2); + fiat_25519_uint128 x9 = ((fiat_25519_uint128)(arg1[4]) * x1); + fiat_25519_uint128 x10 = ((fiat_25519_uint128)(arg1[3]) * x2); + fiat_25519_uint128 x11 = ((fiat_25519_uint128)(arg1[3]) * x4); + fiat_25519_uint128 x12 = ((fiat_25519_uint128)(arg1[2]) * x2); + fiat_25519_uint128 x13 = ((fiat_25519_uint128)(arg1[2]) * x5); + fiat_25519_uint128 x14 = ((fiat_25519_uint128)(arg1[2]) * (arg1[2])); + fiat_25519_uint128 x15 = ((fiat_25519_uint128)(arg1[1]) * x2); + fiat_25519_uint128 x16 = ((fiat_25519_uint128)(arg1[1]) * x6); + fiat_25519_uint128 x17 = ((fiat_25519_uint128)(arg1[1]) * x7); + fiat_25519_uint128 x18 = ((fiat_25519_uint128)(arg1[1]) * (arg1[1])); + fiat_25519_uint128 x19 = ((fiat_25519_uint128)(arg1[0]) * x3); + fiat_25519_uint128 x20 = ((fiat_25519_uint128)(arg1[0]) * x6); + fiat_25519_uint128 x21 = ((fiat_25519_uint128)(arg1[0]) * x7); + fiat_25519_uint128 x22 = ((fiat_25519_uint128)(arg1[0]) * x8); + fiat_25519_uint128 x23 = ((fiat_25519_uint128)(arg1[0]) * (arg1[0])); + fiat_25519_uint128 x24 = (x23 + (x15 + x13)); + uint64_t x25 = (uint64_t)(x24 >> 51); + uint64_t x26 = (uint64_t)(x24 & UINT64_C(0x7ffffffffffff)); + fiat_25519_uint128 x27 = (x19 + (x16 + x14)); + fiat_25519_uint128 x28 = (x20 + (x17 + x9)); + fiat_25519_uint128 x29 = (x21 + (x18 + x10)); + fiat_25519_uint128 x30 = (x22 + (x12 + x11)); + fiat_25519_uint128 x31 = (x25 + x30); + uint64_t x32 = (uint64_t)(x31 >> 51); + uint64_t x33 = (uint64_t)(x31 & UINT64_C(0x7ffffffffffff)); + fiat_25519_uint128 x34 = (x32 + x29); + uint64_t x35 = (uint64_t)(x34 >> 51); + uint64_t x36 = (uint64_t)(x34 & UINT64_C(0x7ffffffffffff)); + fiat_25519_uint128 x37 = (x35 + x28); + uint64_t x38 = (uint64_t)(x37 >> 51); + uint64_t x39 = (uint64_t)(x37 & UINT64_C(0x7ffffffffffff)); + fiat_25519_uint128 x40 = (x38 + x27); + uint64_t x41 = (uint64_t)(x40 >> 51); + uint64_t x42 = (uint64_t)(x40 & UINT64_C(0x7ffffffffffff)); + uint64_t x43 = (x41 * (uint64_t)UINT8_C(0x13)); + uint64_t x44 = (x26 + x43); + uint64_t x45 = (x44 >> 51); + uint64_t x46 = (x44 & UINT64_C(0x7ffffffffffff)); + uint64_t x47 = (x45 + x33); + uint64_t x48 = (x47 >> 51); + uint64_t x49 = (x47 & UINT64_C(0x7ffffffffffff)); + uint64_t x50 = (x48 + x36); + out1[0] = x46; + out1[1] = x49; + out1[2] = x50; + out1[3] = x39; + out1[4] = x42; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664]] + * Output Bounds: + * out1: [[0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc]] + */ +static void fiat_25519_carry_scmul_121666(uint64_t out1[5], const uint64_t arg1[5]) { + fiat_25519_uint128 x1 = (UINT32_C(0x1db42) * (fiat_25519_uint128)(arg1[4])); + fiat_25519_uint128 x2 = (UINT32_C(0x1db42) * (fiat_25519_uint128)(arg1[3])); + fiat_25519_uint128 x3 = (UINT32_C(0x1db42) * (fiat_25519_uint128)(arg1[2])); + fiat_25519_uint128 x4 = (UINT32_C(0x1db42) * (fiat_25519_uint128)(arg1[1])); + fiat_25519_uint128 x5 = (UINT32_C(0x1db42) * (fiat_25519_uint128)(arg1[0])); + uint64_t x6 = (uint64_t)(x5 >> 51); + uint64_t x7 = (uint64_t)(x5 & UINT64_C(0x7ffffffffffff)); + fiat_25519_uint128 x8 = (x6 + x4); + uint64_t x9 = (uint64_t)(x8 >> 51); + uint64_t x10 = (uint64_t)(x8 & UINT64_C(0x7ffffffffffff)); + fiat_25519_uint128 x11 = (x9 + x3); + uint64_t x12 = (uint64_t)(x11 >> 51); + uint64_t x13 = (uint64_t)(x11 & UINT64_C(0x7ffffffffffff)); + fiat_25519_uint128 x14 = (x12 + x2); + uint64_t x15 = (uint64_t)(x14 >> 51); + uint64_t x16 = (uint64_t)(x14 & UINT64_C(0x7ffffffffffff)); + fiat_25519_uint128 x17 = (x15 + x1); + uint64_t x18 = (uint64_t)(x17 >> 51); + uint64_t x19 = (uint64_t)(x17 & UINT64_C(0x7ffffffffffff)); + uint64_t x20 = (x18 * (uint64_t)UINT8_C(0x13)); + uint64_t x21 = (x7 + x20); + uint64_t x22 = (x21 >> 51); + uint64_t x23 = (x21 & UINT64_C(0x7ffffffffffff)); + uint64_t x24 = (x22 + x10); + uint64_t x25 = (x24 >> 51); + uint64_t x26 = (x24 & UINT64_C(0x7ffffffffffff)); + uint64_t x27 = (x25 + x13); + out1[0] = x23; + out1[1] = x26; + out1[2] = x27; + out1[3] = x16; + out1[4] = x19; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664]] + * Output Bounds: + * out1: [[0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc]] + */ +static void fiat_25519_carry(uint64_t out1[5], const uint64_t arg1[5]) { + uint64_t x1 = (arg1[0]); + uint64_t x2 = ((x1 >> 51) + (arg1[1])); + uint64_t x3 = ((x2 >> 51) + (arg1[2])); + uint64_t x4 = ((x3 >> 51) + (arg1[3])); + uint64_t x5 = ((x4 >> 51) + (arg1[4])); + uint64_t x6 = ((x1 & UINT64_C(0x7ffffffffffff)) + ((x5 >> 51) * (uint64_t)UINT8_C(0x13))); + uint64_t x7 = ((x6 >> 51) + (x2 & UINT64_C(0x7ffffffffffff))); + uint64_t x8 = (x6 & UINT64_C(0x7ffffffffffff)); + uint64_t x9 = (x7 & UINT64_C(0x7ffffffffffff)); + uint64_t x10 = ((x7 >> 51) + (x3 & UINT64_C(0x7ffffffffffff))); + uint64_t x11 = (x4 & UINT64_C(0x7ffffffffffff)); + uint64_t x12 = (x5 & UINT64_C(0x7ffffffffffff)); + out1[0] = x8; + out1[1] = x9; + out1[2] = x10; + out1[3] = x11; + out1[4] = x12; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc]] + * arg2: [[0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc]] + * Output Bounds: + * out1: [[0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664]] + */ +static void fiat_25519_add(uint64_t out1[5], const uint64_t arg1[5], const uint64_t arg2[5]) { + uint64_t x1 = ((arg1[0]) + (arg2[0])); + uint64_t x2 = ((arg1[1]) + (arg2[1])); + uint64_t x3 = ((arg1[2]) + (arg2[2])); + uint64_t x4 = ((arg1[3]) + (arg2[3])); + uint64_t x5 = ((arg1[4]) + (arg2[4])); + out1[0] = x1; + out1[1] = x2; + out1[2] = x3; + out1[3] = x4; + out1[4] = x5; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc]] + * arg2: [[0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc]] + * Output Bounds: + * out1: [[0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664]] + */ +static void fiat_25519_sub(uint64_t out1[5], const uint64_t arg1[5], const uint64_t arg2[5]) { + uint64_t x1 = ((UINT64_C(0xfffffffffffda) + (arg1[0])) - (arg2[0])); + uint64_t x2 = ((UINT64_C(0xffffffffffffe) + (arg1[1])) - (arg2[1])); + uint64_t x3 = ((UINT64_C(0xffffffffffffe) + (arg1[2])) - (arg2[2])); + uint64_t x4 = ((UINT64_C(0xffffffffffffe) + (arg1[3])) - (arg2[3])); + uint64_t x5 = ((UINT64_C(0xffffffffffffe) + (arg1[4])) - (arg2[4])); + out1[0] = x1; + out1[1] = x2; + out1[2] = x3; + out1[3] = x4; + out1[4] = x5; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc]] + * Output Bounds: + * out1: [[0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664], [0x0 ~> 0x1a666666666664]] + */ +static void fiat_25519_opp(uint64_t out1[5], const uint64_t arg1[5]) { + uint64_t x1 = (UINT64_C(0xfffffffffffda) - (arg1[0])); + uint64_t x2 = (UINT64_C(0xffffffffffffe) - (arg1[1])); + uint64_t x3 = (UINT64_C(0xffffffffffffe) - (arg1[2])); + uint64_t x4 = (UINT64_C(0xffffffffffffe) - (arg1[3])); + uint64_t x5 = (UINT64_C(0xffffffffffffe) - (arg1[4])); + out1[0] = x1; + out1[1] = x2; + out1[2] = x3; + out1[3] = x4; + out1[4] = x5; +} + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + * arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + */ +static void fiat_25519_selectznz(uint64_t out1[5], fiat_25519_uint1 arg1, const uint64_t arg2[5], const uint64_t arg3[5]) { + uint64_t x1; + fiat_25519_cmovznz_u64(&x1, arg1, (arg2[0]), (arg3[0])); + uint64_t x2; + fiat_25519_cmovznz_u64(&x2, arg1, (arg2[1]), (arg3[1])); + uint64_t x3; + fiat_25519_cmovznz_u64(&x3, arg1, (arg2[2]), (arg3[2])); + uint64_t x4; + fiat_25519_cmovznz_u64(&x4, arg1, (arg2[3]), (arg3[3])); + uint64_t x5; + fiat_25519_cmovznz_u64(&x5, arg1, (arg2[4]), (arg3[4])); + out1[0] = x1; + out1[1] = x2; + out1[2] = x3; + out1[3] = x4; + out1[4] = x5; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc]] + * Output Bounds: + * out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x7f]] + */ +static void fiat_25519_to_bytes(uint8_t out1[32], const uint64_t arg1[5]) { + uint64_t x1; + fiat_25519_uint1 x2; + fiat_25519_subborrowx_u51(&x1, &x2, 0x0, (arg1[0]), UINT64_C(0x7ffffffffffed)); + uint64_t x3; + fiat_25519_uint1 x4; + fiat_25519_subborrowx_u51(&x3, &x4, x2, (arg1[1]), UINT64_C(0x7ffffffffffff)); + uint64_t x5; + fiat_25519_uint1 x6; + fiat_25519_subborrowx_u51(&x5, &x6, x4, (arg1[2]), UINT64_C(0x7ffffffffffff)); + uint64_t x7; + fiat_25519_uint1 x8; + fiat_25519_subborrowx_u51(&x7, &x8, x6, (arg1[3]), UINT64_C(0x7ffffffffffff)); + uint64_t x9; + fiat_25519_uint1 x10; + fiat_25519_subborrowx_u51(&x9, &x10, x8, (arg1[4]), UINT64_C(0x7ffffffffffff)); + uint64_t x11; + fiat_25519_cmovznz_u64(&x11, x10, 0x0, UINT64_C(0xffffffffffffffff)); + uint64_t x12; + fiat_25519_uint1 x13; + fiat_25519_addcarryx_u51(&x12, &x13, 0x0, (x11 & UINT64_C(0x7ffffffffffed)), x1); + uint64_t x14; + fiat_25519_uint1 x15; + fiat_25519_addcarryx_u51(&x14, &x15, x13, (x11 & UINT64_C(0x7ffffffffffff)), x3); + uint64_t x16; + fiat_25519_uint1 x17; + fiat_25519_addcarryx_u51(&x16, &x17, x15, (x11 & UINT64_C(0x7ffffffffffff)), x5); + uint64_t x18; + fiat_25519_uint1 x19; + fiat_25519_addcarryx_u51(&x18, &x19, x17, (x11 & UINT64_C(0x7ffffffffffff)), x7); + uint64_t x20; + fiat_25519_uint1 x21; + fiat_25519_addcarryx_u51(&x20, &x21, x19, (x11 & UINT64_C(0x7ffffffffffff)), x9); + uint64_t x22 = (x20 << 4); + uint64_t x23 = (x18 * (uint64_t)0x2); + uint64_t x24 = (x16 << 6); + uint64_t x25 = (x14 << 3); + uint64_t x26 = (x12 >> 8); + uint8_t x27 = (uint8_t)(x12 & UINT8_C(0xff)); + uint64_t x28 = (x26 >> 8); + uint8_t x29 = (uint8_t)(x26 & UINT8_C(0xff)); + uint64_t x30 = (x28 >> 8); + uint8_t x31 = (uint8_t)(x28 & UINT8_C(0xff)); + uint64_t x32 = (x30 >> 8); + uint8_t x33 = (uint8_t)(x30 & UINT8_C(0xff)); + uint64_t x34 = (x32 >> 8); + uint8_t x35 = (uint8_t)(x32 & UINT8_C(0xff)); + uint8_t x36 = (uint8_t)(x34 >> 8); + uint8_t x37 = (uint8_t)(x34 & UINT8_C(0xff)); + uint64_t x38 = (x36 + x25); + uint64_t x39 = (x38 >> 8); + uint8_t x40 = (uint8_t)(x38 & UINT8_C(0xff)); + uint64_t x41 = (x39 >> 8); + uint8_t x42 = (uint8_t)(x39 & UINT8_C(0xff)); + uint64_t x43 = (x41 >> 8); + uint8_t x44 = (uint8_t)(x41 & UINT8_C(0xff)); + uint64_t x45 = (x43 >> 8); + uint8_t x46 = (uint8_t)(x43 & UINT8_C(0xff)); + uint64_t x47 = (x45 >> 8); + uint8_t x48 = (uint8_t)(x45 & UINT8_C(0xff)); + uint8_t x49 = (uint8_t)(x47 >> 8); + uint8_t x50 = (uint8_t)(x47 & UINT8_C(0xff)); + uint64_t x51 = (x49 + x24); + uint64_t x52 = (x51 >> 8); + uint8_t x53 = (uint8_t)(x51 & UINT8_C(0xff)); + uint64_t x54 = (x52 >> 8); + uint8_t x55 = (uint8_t)(x52 & UINT8_C(0xff)); + uint64_t x56 = (x54 >> 8); + uint8_t x57 = (uint8_t)(x54 & UINT8_C(0xff)); + uint64_t x58 = (x56 >> 8); + uint8_t x59 = (uint8_t)(x56 & UINT8_C(0xff)); + uint64_t x60 = (x58 >> 8); + uint8_t x61 = (uint8_t)(x58 & UINT8_C(0xff)); + uint64_t x62 = (x60 >> 8); + uint8_t x63 = (uint8_t)(x60 & UINT8_C(0xff)); + fiat_25519_uint1 x64 = (fiat_25519_uint1)(x62 >> 8); + uint8_t x65 = (uint8_t)(x62 & UINT8_C(0xff)); + uint64_t x66 = (x64 + x23); + uint64_t x67 = (x66 >> 8); + uint8_t x68 = (uint8_t)(x66 & UINT8_C(0xff)); + uint64_t x69 = (x67 >> 8); + uint8_t x70 = (uint8_t)(x67 & UINT8_C(0xff)); + uint64_t x71 = (x69 >> 8); + uint8_t x72 = (uint8_t)(x69 & UINT8_C(0xff)); + uint64_t x73 = (x71 >> 8); + uint8_t x74 = (uint8_t)(x71 & UINT8_C(0xff)); + uint64_t x75 = (x73 >> 8); + uint8_t x76 = (uint8_t)(x73 & UINT8_C(0xff)); + uint8_t x77 = (uint8_t)(x75 >> 8); + uint8_t x78 = (uint8_t)(x75 & UINT8_C(0xff)); + uint64_t x79 = (x77 + x22); + uint64_t x80 = (x79 >> 8); + uint8_t x81 = (uint8_t)(x79 & UINT8_C(0xff)); + uint64_t x82 = (x80 >> 8); + uint8_t x83 = (uint8_t)(x80 & UINT8_C(0xff)); + uint64_t x84 = (x82 >> 8); + uint8_t x85 = (uint8_t)(x82 & UINT8_C(0xff)); + uint64_t x86 = (x84 >> 8); + uint8_t x87 = (uint8_t)(x84 & UINT8_C(0xff)); + uint64_t x88 = (x86 >> 8); + uint8_t x89 = (uint8_t)(x86 & UINT8_C(0xff)); + uint8_t x90 = (uint8_t)(x88 >> 8); + uint8_t x91 = (uint8_t)(x88 & UINT8_C(0xff)); + out1[0] = x27; + out1[1] = x29; + out1[2] = x31; + out1[3] = x33; + out1[4] = x35; + out1[5] = x37; + out1[6] = x40; + out1[7] = x42; + out1[8] = x44; + out1[9] = x46; + out1[10] = x48; + out1[11] = x50; + out1[12] = x53; + out1[13] = x55; + out1[14] = x57; + out1[15] = x59; + out1[16] = x61; + out1[17] = x63; + out1[18] = x65; + out1[19] = x68; + out1[20] = x70; + out1[21] = x72; + out1[22] = x74; + out1[23] = x76; + out1[24] = x78; + out1[25] = x81; + out1[26] = x83; + out1[27] = x85; + out1[28] = x87; + out1[29] = x89; + out1[30] = x91; + out1[31] = x90; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x7f]] + * Output Bounds: + * out1: [[0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc], [0x0 ~> 0x8cccccccccccc]] + */ +static void fiat_25519_from_bytes(uint64_t out1[5], const uint8_t arg1[32]) { + uint64_t x1 = ((uint64_t)(arg1[31]) << 44); + uint64_t x2 = ((uint64_t)(arg1[30]) << 36); + uint64_t x3 = ((uint64_t)(arg1[29]) << 28); + uint64_t x4 = ((uint64_t)(arg1[28]) << 20); + uint64_t x5 = ((uint64_t)(arg1[27]) << 12); + uint64_t x6 = ((uint64_t)(arg1[26]) << 4); + uint64_t x7 = ((uint64_t)(arg1[25]) << 47); + uint64_t x8 = ((uint64_t)(arg1[24]) << 39); + uint64_t x9 = ((uint64_t)(arg1[23]) << 31); + uint64_t x10 = ((uint64_t)(arg1[22]) << 23); + uint64_t x11 = ((uint64_t)(arg1[21]) << 15); + uint64_t x12 = ((uint64_t)(arg1[20]) << 7); + uint64_t x13 = ((uint64_t)(arg1[19]) << 50); + uint64_t x14 = ((uint64_t)(arg1[18]) << 42); + uint64_t x15 = ((uint64_t)(arg1[17]) << 34); + uint64_t x16 = ((uint64_t)(arg1[16]) << 26); + uint64_t x17 = ((uint64_t)(arg1[15]) << 18); + uint64_t x18 = ((uint64_t)(arg1[14]) << 10); + uint64_t x19 = ((uint64_t)(arg1[13]) << 2); + uint64_t x20 = ((uint64_t)(arg1[12]) << 45); + uint64_t x21 = ((uint64_t)(arg1[11]) << 37); + uint64_t x22 = ((uint64_t)(arg1[10]) << 29); + uint64_t x23 = ((uint64_t)(arg1[9]) << 21); + uint64_t x24 = ((uint64_t)(arg1[8]) << 13); + uint64_t x25 = ((uint64_t)(arg1[7]) << 5); + uint64_t x26 = ((uint64_t)(arg1[6]) << 48); + uint64_t x27 = ((uint64_t)(arg1[5]) << 40); + uint64_t x28 = ((uint64_t)(arg1[4]) << 32); + uint64_t x29 = ((uint64_t)(arg1[3]) << 24); + uint64_t x30 = ((uint64_t)(arg1[2]) << 16); + uint64_t x31 = ((uint64_t)(arg1[1]) << 8); + uint8_t x32 = (arg1[0]); + uint64_t x33 = (x32 + (x31 + (x30 + (x29 + (x28 + (x27 + x26)))))); + uint8_t x34 = (uint8_t)(x33 >> 51); + uint64_t x35 = (x33 & UINT64_C(0x7ffffffffffff)); + uint64_t x36 = (x6 + (x5 + (x4 + (x3 + (x2 + x1))))); + uint64_t x37 = (x12 + (x11 + (x10 + (x9 + (x8 + x7))))); + uint64_t x38 = (x19 + (x18 + (x17 + (x16 + (x15 + (x14 + x13)))))); + uint64_t x39 = (x25 + (x24 + (x23 + (x22 + (x21 + x20))))); + uint64_t x40 = (x34 + x39); + uint8_t x41 = (uint8_t)(x40 >> 51); + uint64_t x42 = (x40 & UINT64_C(0x7ffffffffffff)); + uint64_t x43 = (x41 + x38); + uint8_t x44 = (uint8_t)(x43 >> 51); + uint64_t x45 = (x43 & UINT64_C(0x7ffffffffffff)); + uint64_t x46 = (x44 + x37); + uint8_t x47 = (uint8_t)(x46 >> 51); + uint64_t x48 = (x46 & UINT64_C(0x7ffffffffffff)); + uint64_t x49 = (x47 + x36); + out1[0] = x35; + out1[1] = x42; + out1[2] = x45; + out1[3] = x48; + out1[4] = x49; +} + diff --git a/third_party/boringssl/kit/src/third_party/fiat/p256.c b/third_party/boringssl/kit/src/third_party/fiat/p256.c index 414b7e0c..8426beb3 100644 --- a/third_party/boringssl/kit/src/third_party/fiat/p256.c +++ b/third_party/boringssl/kit/src/third_party/fiat/p256.c @@ -46,791 +46,11 @@ // MSVC does not implement uint128_t, and crashes with intrinsics #if defined(BORINGSSL_HAS_UINT128) #define BORINGSSL_NISTP256_64BIT 1 -#endif - -// "intrinsics" - -#if defined(BORINGSSL_NISTP256_64BIT) - -static uint64_t mulx_u64(uint64_t a, uint64_t b, uint64_t *high) { - uint128_t x = (uint128_t)a * b; - *high = (uint64_t) (x >> 64); - return (uint64_t) x; -} - -static uint64_t addcarryx_u64(uint8_t c, uint64_t a, uint64_t b, uint64_t *low) { - uint128_t x = (uint128_t)a + b + c; - *low = (uint64_t) x; - return (uint64_t) (x>>64); -} - -static uint64_t subborrow_u64(uint8_t c, uint64_t a, uint64_t b, uint64_t *low) { - uint128_t t = ((uint128_t) b + c); - uint128_t x = a-t; - *low = (uint64_t) x; - return (uint8_t) (x>>127); -} - -static uint64_t cmovznz_u64(uint64_t t, uint64_t z, uint64_t nz) { - t = -!!t; // all set if nonzero, 0 if 0 - return (t&nz) | ((~t)&z); -} - +#include "p256_64.h" #else - -static uint32_t mulx_u32(uint32_t a, uint32_t b, uint32_t *high) { - uint64_t x = (uint64_t)a * b; - *high = (uint32_t) (x >> 32); - return (uint32_t) x; -} - -static uint32_t addcarryx_u32(uint8_t c, uint32_t a, uint32_t b, uint32_t *low) { - uint64_t x = (uint64_t)a + b + c; - *low = (uint32_t) x; - return (uint32_t) (x>>32); -} - -static uint32_t subborrow_u32(uint8_t c, uint32_t a, uint32_t b, uint32_t *low) { - uint64_t t = ((uint64_t) b + c); - uint64_t x = a-t; - *low = (uint32_t) x; - return (uint8_t) (x>>63); -} - -static uint32_t cmovznz_u32(uint32_t t, uint32_t z, uint32_t nz) { - t = -!!t; // all set if nonzero, 0 if 0 - return (t&nz) | ((~t)&z); -} - +#include "p256_32.h" #endif -// fiat-crypto generated code - -#if defined(BORINGSSL_NISTP256_64BIT) - -static void fe_add(uint64_t out[4], const uint64_t in1[4], const uint64_t in2[4]) { - { const uint64_t x8 = in1[3]; - { const uint64_t x9 = in1[2]; - { const uint64_t x7 = in1[1]; - { const uint64_t x5 = in1[0]; - { const uint64_t x14 = in2[3]; - { const uint64_t x15 = in2[2]; - { const uint64_t x13 = in2[1]; - { const uint64_t x11 = in2[0]; - { uint64_t x17; uint8_t x18 = addcarryx_u64(0x0, x5, x11, &x17); - { uint64_t x20; uint8_t x21 = addcarryx_u64(x18, x7, x13, &x20); - { uint64_t x23; uint8_t x24 = addcarryx_u64(x21, x9, x15, &x23); - { uint64_t x26; uint8_t x27 = addcarryx_u64(x24, x8, x14, &x26); - { uint64_t x29; uint8_t x30 = subborrow_u64(0x0, x17, 0xffffffffffffffffL, &x29); - { uint64_t x32; uint8_t x33 = subborrow_u64(x30, x20, 0xffffffff, &x32); - { uint64_t x35; uint8_t x36 = subborrow_u64(x33, x23, 0x0, &x35); - { uint64_t x38; uint8_t x39 = subborrow_u64(x36, x26, 0xffffffff00000001L, &x38); - { uint64_t _1; uint8_t x42 = subborrow_u64(x39, x27, 0x0, &_1); - { uint64_t x43 = cmovznz_u64(x42, x38, x26); - { uint64_t x44 = cmovznz_u64(x42, x35, x23); - { uint64_t x45 = cmovznz_u64(x42, x32, x20); - { uint64_t x46 = cmovznz_u64(x42, x29, x17); - out[0] = x46; - out[1] = x45; - out[2] = x44; - out[3] = x43; - }}}}}}}}}}}}}}}}}}}}} -} - -// fe_op sets out = -in -static void fe_opp(uint64_t out[4], const uint64_t in1[4]) { - const uint64_t x5 = in1[3]; - const uint64_t x6 = in1[2]; - const uint64_t x4 = in1[1]; - const uint64_t x2 = in1[0]; - uint64_t x8; uint8_t x9 = subborrow_u64(0x0, 0x0, x2, &x8); - uint64_t x11; uint8_t x12 = subborrow_u64(x9, 0x0, x4, &x11); - uint64_t x14; uint8_t x15 = subborrow_u64(x12, 0x0, x6, &x14); - uint64_t x17; uint8_t x18 = subborrow_u64(x15, 0x0, x5, &x17); - uint64_t x19 = (uint64_t)cmovznz_u64(x18, 0x0, 0xffffffffffffffffL); - uint64_t x20 = (x19 & 0xffffffffffffffffL); - uint64_t x22; uint8_t x23 = addcarryx_u64(0x0, x8, x20, &x22); - uint64_t x24 = (x19 & 0xffffffff); - uint64_t x26; uint8_t x27 = addcarryx_u64(x23, x11, x24, &x26); - uint64_t x29; uint8_t x30 = addcarryx_u64(x27, x14, 0x0, &x29); - uint64_t x31 = (x19 & 0xffffffff00000001L); - uint64_t x33; addcarryx_u64(x30, x17, x31, &x33); - out[0] = x22; - out[1] = x26; - out[2] = x29; - out[3] = x33; -} - -static void fe_mul(uint64_t out[4], const uint64_t in1[4], const uint64_t in2[4]) { - const uint64_t x8 = in1[3]; - const uint64_t x9 = in1[2]; - const uint64_t x7 = in1[1]; - const uint64_t x5 = in1[0]; - const uint64_t x14 = in2[3]; - const uint64_t x15 = in2[2]; - const uint64_t x13 = in2[1]; - const uint64_t x11 = in2[0]; - uint64_t x18; uint64_t x17 = mulx_u64(x5, x11, &x18); - uint64_t x21; uint64_t x20 = mulx_u64(x5, x13, &x21); - uint64_t x24; uint64_t x23 = mulx_u64(x5, x15, &x24); - uint64_t x27; uint64_t x26 = mulx_u64(x5, x14, &x27); - uint64_t x29; uint8_t x30 = addcarryx_u64(0x0, x18, x20, &x29); - uint64_t x32; uint8_t x33 = addcarryx_u64(x30, x21, x23, &x32); - uint64_t x35; uint8_t x36 = addcarryx_u64(x33, x24, x26, &x35); - uint64_t x38; addcarryx_u64(0x0, x36, x27, &x38); - uint64_t x42; uint64_t x41 = mulx_u64(x17, 0xffffffffffffffffL, &x42); - uint64_t x45; uint64_t x44 = mulx_u64(x17, 0xffffffff, &x45); - uint64_t x48; uint64_t x47 = mulx_u64(x17, 0xffffffff00000001L, &x48); - uint64_t x50; uint8_t x51 = addcarryx_u64(0x0, x42, x44, &x50); - uint64_t x53; uint8_t x54 = addcarryx_u64(x51, x45, 0x0, &x53); - uint64_t x56; uint8_t x57 = addcarryx_u64(x54, 0x0, x47, &x56); - uint64_t x59; addcarryx_u64(0x0, x57, x48, &x59); - uint64_t _2; uint8_t x63 = addcarryx_u64(0x0, x17, x41, &_2); - uint64_t x65; uint8_t x66 = addcarryx_u64(x63, x29, x50, &x65); - uint64_t x68; uint8_t x69 = addcarryx_u64(x66, x32, x53, &x68); - uint64_t x71; uint8_t x72 = addcarryx_u64(x69, x35, x56, &x71); - uint64_t x74; uint8_t x75 = addcarryx_u64(x72, x38, x59, &x74); - uint64_t x78; uint64_t x77 = mulx_u64(x7, x11, &x78); - uint64_t x81; uint64_t x80 = mulx_u64(x7, x13, &x81); - uint64_t x84; uint64_t x83 = mulx_u64(x7, x15, &x84); - uint64_t x87; uint64_t x86 = mulx_u64(x7, x14, &x87); - uint64_t x89; uint8_t x90 = addcarryx_u64(0x0, x78, x80, &x89); - uint64_t x92; uint8_t x93 = addcarryx_u64(x90, x81, x83, &x92); - uint64_t x95; uint8_t x96 = addcarryx_u64(x93, x84, x86, &x95); - uint64_t x98; addcarryx_u64(0x0, x96, x87, &x98); - uint64_t x101; uint8_t x102 = addcarryx_u64(0x0, x65, x77, &x101); - uint64_t x104; uint8_t x105 = addcarryx_u64(x102, x68, x89, &x104); - uint64_t x107; uint8_t x108 = addcarryx_u64(x105, x71, x92, &x107); - uint64_t x110; uint8_t x111 = addcarryx_u64(x108, x74, x95, &x110); - uint64_t x113; uint8_t x114 = addcarryx_u64(x111, x75, x98, &x113); - uint64_t x117; uint64_t x116 = mulx_u64(x101, 0xffffffffffffffffL, &x117); - uint64_t x120; uint64_t x119 = mulx_u64(x101, 0xffffffff, &x120); - uint64_t x123; uint64_t x122 = mulx_u64(x101, 0xffffffff00000001L, &x123); - uint64_t x125; uint8_t x126 = addcarryx_u64(0x0, x117, x119, &x125); - uint64_t x128; uint8_t x129 = addcarryx_u64(x126, x120, 0x0, &x128); - uint64_t x131; uint8_t x132 = addcarryx_u64(x129, 0x0, x122, &x131); - uint64_t x134; addcarryx_u64(0x0, x132, x123, &x134); - uint64_t _3; uint8_t x138 = addcarryx_u64(0x0, x101, x116, &_3); - uint64_t x140; uint8_t x141 = addcarryx_u64(x138, x104, x125, &x140); - uint64_t x143; uint8_t x144 = addcarryx_u64(x141, x107, x128, &x143); - uint64_t x146; uint8_t x147 = addcarryx_u64(x144, x110, x131, &x146); - uint64_t x149; uint8_t x150 = addcarryx_u64(x147, x113, x134, &x149); - uint8_t x151 = (x150 + x114); - uint64_t x154; uint64_t x153 = mulx_u64(x9, x11, &x154); - uint64_t x157; uint64_t x156 = mulx_u64(x9, x13, &x157); - uint64_t x160; uint64_t x159 = mulx_u64(x9, x15, &x160); - uint64_t x163; uint64_t x162 = mulx_u64(x9, x14, &x163); - uint64_t x165; uint8_t x166 = addcarryx_u64(0x0, x154, x156, &x165); - uint64_t x168; uint8_t x169 = addcarryx_u64(x166, x157, x159, &x168); - uint64_t x171; uint8_t x172 = addcarryx_u64(x169, x160, x162, &x171); - uint64_t x174; addcarryx_u64(0x0, x172, x163, &x174); - uint64_t x177; uint8_t x178 = addcarryx_u64(0x0, x140, x153, &x177); - uint64_t x180; uint8_t x181 = addcarryx_u64(x178, x143, x165, &x180); - uint64_t x183; uint8_t x184 = addcarryx_u64(x181, x146, x168, &x183); - uint64_t x186; uint8_t x187 = addcarryx_u64(x184, x149, x171, &x186); - uint64_t x189; uint8_t x190 = addcarryx_u64(x187, x151, x174, &x189); - uint64_t x193; uint64_t x192 = mulx_u64(x177, 0xffffffffffffffffL, &x193); - uint64_t x196; uint64_t x195 = mulx_u64(x177, 0xffffffff, &x196); - uint64_t x199; uint64_t x198 = mulx_u64(x177, 0xffffffff00000001L, &x199); - uint64_t x201; uint8_t x202 = addcarryx_u64(0x0, x193, x195, &x201); - uint64_t x204; uint8_t x205 = addcarryx_u64(x202, x196, 0x0, &x204); - uint64_t x207; uint8_t x208 = addcarryx_u64(x205, 0x0, x198, &x207); - uint64_t x210; addcarryx_u64(0x0, x208, x199, &x210); - uint64_t _4; uint8_t x214 = addcarryx_u64(0x0, x177, x192, &_4); - uint64_t x216; uint8_t x217 = addcarryx_u64(x214, x180, x201, &x216); - uint64_t x219; uint8_t x220 = addcarryx_u64(x217, x183, x204, &x219); - uint64_t x222; uint8_t x223 = addcarryx_u64(x220, x186, x207, &x222); - uint64_t x225; uint8_t x226 = addcarryx_u64(x223, x189, x210, &x225); - uint8_t x227 = (x226 + x190); - uint64_t x230; uint64_t x229 = mulx_u64(x8, x11, &x230); - uint64_t x233; uint64_t x232 = mulx_u64(x8, x13, &x233); - uint64_t x236; uint64_t x235 = mulx_u64(x8, x15, &x236); - uint64_t x239; uint64_t x238 = mulx_u64(x8, x14, &x239); - uint64_t x241; uint8_t x242 = addcarryx_u64(0x0, x230, x232, &x241); - uint64_t x244; uint8_t x245 = addcarryx_u64(x242, x233, x235, &x244); - uint64_t x247; uint8_t x248 = addcarryx_u64(x245, x236, x238, &x247); - uint64_t x250; addcarryx_u64(0x0, x248, x239, &x250); - uint64_t x253; uint8_t x254 = addcarryx_u64(0x0, x216, x229, &x253); - uint64_t x256; uint8_t x257 = addcarryx_u64(x254, x219, x241, &x256); - uint64_t x259; uint8_t x260 = addcarryx_u64(x257, x222, x244, &x259); - uint64_t x262; uint8_t x263 = addcarryx_u64(x260, x225, x247, &x262); - uint64_t x265; uint8_t x266 = addcarryx_u64(x263, x227, x250, &x265); - uint64_t x269; uint64_t x268 = mulx_u64(x253, 0xffffffffffffffffL, &x269); - uint64_t x272; uint64_t x271 = mulx_u64(x253, 0xffffffff, &x272); - uint64_t x275; uint64_t x274 = mulx_u64(x253, 0xffffffff00000001L, &x275); - uint64_t x277; uint8_t x278 = addcarryx_u64(0x0, x269, x271, &x277); - uint64_t x280; uint8_t x281 = addcarryx_u64(x278, x272, 0x0, &x280); - uint64_t x283; uint8_t x284 = addcarryx_u64(x281, 0x0, x274, &x283); - uint64_t x286; addcarryx_u64(0x0, x284, x275, &x286); - uint64_t _5; uint8_t x290 = addcarryx_u64(0x0, x253, x268, &_5); - uint64_t x292; uint8_t x293 = addcarryx_u64(x290, x256, x277, &x292); - uint64_t x295; uint8_t x296 = addcarryx_u64(x293, x259, x280, &x295); - uint64_t x298; uint8_t x299 = addcarryx_u64(x296, x262, x283, &x298); - uint64_t x301; uint8_t x302 = addcarryx_u64(x299, x265, x286, &x301); - uint8_t x303 = (x302 + x266); - uint64_t x305; uint8_t x306 = subborrow_u64(0x0, x292, 0xffffffffffffffffL, &x305); - uint64_t x308; uint8_t x309 = subborrow_u64(x306, x295, 0xffffffff, &x308); - uint64_t x311; uint8_t x312 = subborrow_u64(x309, x298, 0x0, &x311); - uint64_t x314; uint8_t x315 = subborrow_u64(x312, x301, 0xffffffff00000001L, &x314); - uint64_t _6; uint8_t x318 = subborrow_u64(x315, x303, 0x0, &_6); - uint64_t x319 = cmovznz_u64(x318, x314, x301); - uint64_t x320 = cmovznz_u64(x318, x311, x298); - uint64_t x321 = cmovznz_u64(x318, x308, x295); - uint64_t x322 = cmovznz_u64(x318, x305, x292); - out[0] = x322; - out[1] = x321; - out[2] = x320; - out[3] = x319; -} - -static void fe_sub(uint64_t out[4], const uint64_t in1[4], const uint64_t in2[4]) { - const uint64_t x8 = in1[3]; - const uint64_t x9 = in1[2]; - const uint64_t x7 = in1[1]; - const uint64_t x5 = in1[0]; - const uint64_t x14 = in2[3]; - const uint64_t x15 = in2[2]; - const uint64_t x13 = in2[1]; - const uint64_t x11 = in2[0]; - uint64_t x17; uint8_t x18 = subborrow_u64(0x0, x5, x11, &x17); - uint64_t x20; uint8_t x21 = subborrow_u64(x18, x7, x13, &x20); - uint64_t x23; uint8_t x24 = subborrow_u64(x21, x9, x15, &x23); - uint64_t x26; uint8_t x27 = subborrow_u64(x24, x8, x14, &x26); - uint64_t x28 = (uint64_t)cmovznz_u64(x27, 0x0, 0xffffffffffffffffL); - uint64_t x29 = (x28 & 0xffffffffffffffffL); - uint64_t x31; uint8_t x32 = addcarryx_u64(0x0, x17, x29, &x31); - uint64_t x33 = (x28 & 0xffffffff); - uint64_t x35; uint8_t x36 = addcarryx_u64(x32, x20, x33, &x35); - uint64_t x38; uint8_t x39 = addcarryx_u64(x36, x23, 0x0, &x38); - uint64_t x40 = (x28 & 0xffffffff00000001L); - uint64_t x42; addcarryx_u64(x39, x26, x40, &x42); - out[0] = x31; - out[1] = x35; - out[2] = x38; - out[3] = x42; -} - -#else // 64BIT, else 32BIT - -static void fe_add(uint32_t out[8], const uint32_t in1[8], const uint32_t in2[8]) { - const uint32_t x16 = in1[7]; - const uint32_t x17 = in1[6]; - const uint32_t x15 = in1[5]; - const uint32_t x13 = in1[4]; - const uint32_t x11 = in1[3]; - const uint32_t x9 = in1[2]; - const uint32_t x7 = in1[1]; - const uint32_t x5 = in1[0]; - const uint32_t x30 = in2[7]; - const uint32_t x31 = in2[6]; - const uint32_t x29 = in2[5]; - const uint32_t x27 = in2[4]; - const uint32_t x25 = in2[3]; - const uint32_t x23 = in2[2]; - const uint32_t x21 = in2[1]; - const uint32_t x19 = in2[0]; - uint32_t x33; uint8_t x34 = addcarryx_u32(0x0, x5, x19, &x33); - uint32_t x36; uint8_t x37 = addcarryx_u32(x34, x7, x21, &x36); - uint32_t x39; uint8_t x40 = addcarryx_u32(x37, x9, x23, &x39); - uint32_t x42; uint8_t x43 = addcarryx_u32(x40, x11, x25, &x42); - uint32_t x45; uint8_t x46 = addcarryx_u32(x43, x13, x27, &x45); - uint32_t x48; uint8_t x49 = addcarryx_u32(x46, x15, x29, &x48); - uint32_t x51; uint8_t x52 = addcarryx_u32(x49, x17, x31, &x51); - uint32_t x54; uint8_t x55 = addcarryx_u32(x52, x16, x30, &x54); - uint32_t x57; uint8_t x58 = subborrow_u32(0x0, x33, 0xffffffff, &x57); - uint32_t x60; uint8_t x61 = subborrow_u32(x58, x36, 0xffffffff, &x60); - uint32_t x63; uint8_t x64 = subborrow_u32(x61, x39, 0xffffffff, &x63); - uint32_t x66; uint8_t x67 = subborrow_u32(x64, x42, 0x0, &x66); - uint32_t x69; uint8_t x70 = subborrow_u32(x67, x45, 0x0, &x69); - uint32_t x72; uint8_t x73 = subborrow_u32(x70, x48, 0x0, &x72); - uint32_t x75; uint8_t x76 = subborrow_u32(x73, x51, 0x1, &x75); - uint32_t x78; uint8_t x79 = subborrow_u32(x76, x54, 0xffffffff, &x78); - uint32_t _; uint8_t x82 = subborrow_u32(x79, x55, 0x0, &_); - uint32_t x83 = cmovznz_u32(x82, x78, x54); - uint32_t x84 = cmovznz_u32(x82, x75, x51); - uint32_t x85 = cmovznz_u32(x82, x72, x48); - uint32_t x86 = cmovznz_u32(x82, x69, x45); - uint32_t x87 = cmovznz_u32(x82, x66, x42); - uint32_t x88 = cmovznz_u32(x82, x63, x39); - uint32_t x89 = cmovznz_u32(x82, x60, x36); - uint32_t x90 = cmovznz_u32(x82, x57, x33); - out[0] = x90; - out[1] = x89; - out[2] = x88; - out[3] = x87; - out[4] = x86; - out[5] = x85; - out[6] = x84; - out[7] = x83; -} - -static void fe_mul(uint32_t out[8], const uint32_t in1[8], const uint32_t in2[8]) { - const uint32_t x16 = in1[7]; - const uint32_t x17 = in1[6]; - const uint32_t x15 = in1[5]; - const uint32_t x13 = in1[4]; - const uint32_t x11 = in1[3]; - const uint32_t x9 = in1[2]; - const uint32_t x7 = in1[1]; - const uint32_t x5 = in1[0]; - const uint32_t x30 = in2[7]; - const uint32_t x31 = in2[6]; - const uint32_t x29 = in2[5]; - const uint32_t x27 = in2[4]; - const uint32_t x25 = in2[3]; - const uint32_t x23 = in2[2]; - const uint32_t x21 = in2[1]; - const uint32_t x19 = in2[0]; - uint32_t x34; uint32_t x33 = mulx_u32(x5, x19, &x34); - uint32_t x37; uint32_t x36 = mulx_u32(x5, x21, &x37); - uint32_t x40; uint32_t x39 = mulx_u32(x5, x23, &x40); - uint32_t x43; uint32_t x42 = mulx_u32(x5, x25, &x43); - uint32_t x46; uint32_t x45 = mulx_u32(x5, x27, &x46); - uint32_t x49; uint32_t x48 = mulx_u32(x5, x29, &x49); - uint32_t x52; uint32_t x51 = mulx_u32(x5, x31, &x52); - uint32_t x55; uint32_t x54 = mulx_u32(x5, x30, &x55); - uint32_t x57; uint8_t x58 = addcarryx_u32(0x0, x34, x36, &x57); - uint32_t x60; uint8_t x61 = addcarryx_u32(x58, x37, x39, &x60); - uint32_t x63; uint8_t x64 = addcarryx_u32(x61, x40, x42, &x63); - uint32_t x66; uint8_t x67 = addcarryx_u32(x64, x43, x45, &x66); - uint32_t x69; uint8_t x70 = addcarryx_u32(x67, x46, x48, &x69); - uint32_t x72; uint8_t x73 = addcarryx_u32(x70, x49, x51, &x72); - uint32_t x75; uint8_t x76 = addcarryx_u32(x73, x52, x54, &x75); - uint32_t x78; addcarryx_u32(0x0, x76, x55, &x78); - uint32_t x82; uint32_t x81 = mulx_u32(x33, 0xffffffff, &x82); - uint32_t x85; uint32_t x84 = mulx_u32(x33, 0xffffffff, &x85); - uint32_t x88; uint32_t x87 = mulx_u32(x33, 0xffffffff, &x88); - uint32_t x91; uint32_t x90 = mulx_u32(x33, 0xffffffff, &x91); - uint32_t x93; uint8_t x94 = addcarryx_u32(0x0, x82, x84, &x93); - uint32_t x96; uint8_t x97 = addcarryx_u32(x94, x85, x87, &x96); - uint32_t x99; uint8_t x100 = addcarryx_u32(x97, x88, 0x0, &x99); - uint8_t x101 = (0x0 + 0x0); - uint32_t _1; uint8_t x104 = addcarryx_u32(0x0, x33, x81, &_1); - uint32_t x106; uint8_t x107 = addcarryx_u32(x104, x57, x93, &x106); - uint32_t x109; uint8_t x110 = addcarryx_u32(x107, x60, x96, &x109); - uint32_t x112; uint8_t x113 = addcarryx_u32(x110, x63, x99, &x112); - uint32_t x115; uint8_t x116 = addcarryx_u32(x113, x66, x100, &x115); - uint32_t x118; uint8_t x119 = addcarryx_u32(x116, x69, x101, &x118); - uint32_t x121; uint8_t x122 = addcarryx_u32(x119, x72, x33, &x121); - uint32_t x124; uint8_t x125 = addcarryx_u32(x122, x75, x90, &x124); - uint32_t x127; uint8_t x128 = addcarryx_u32(x125, x78, x91, &x127); - uint8_t x129 = (x128 + 0x0); - uint32_t x132; uint32_t x131 = mulx_u32(x7, x19, &x132); - uint32_t x135; uint32_t x134 = mulx_u32(x7, x21, &x135); - uint32_t x138; uint32_t x137 = mulx_u32(x7, x23, &x138); - uint32_t x141; uint32_t x140 = mulx_u32(x7, x25, &x141); - uint32_t x144; uint32_t x143 = mulx_u32(x7, x27, &x144); - uint32_t x147; uint32_t x146 = mulx_u32(x7, x29, &x147); - uint32_t x150; uint32_t x149 = mulx_u32(x7, x31, &x150); - uint32_t x153; uint32_t x152 = mulx_u32(x7, x30, &x153); - uint32_t x155; uint8_t x156 = addcarryx_u32(0x0, x132, x134, &x155); - uint32_t x158; uint8_t x159 = addcarryx_u32(x156, x135, x137, &x158); - uint32_t x161; uint8_t x162 = addcarryx_u32(x159, x138, x140, &x161); - uint32_t x164; uint8_t x165 = addcarryx_u32(x162, x141, x143, &x164); - uint32_t x167; uint8_t x168 = addcarryx_u32(x165, x144, x146, &x167); - uint32_t x170; uint8_t x171 = addcarryx_u32(x168, x147, x149, &x170); - uint32_t x173; uint8_t x174 = addcarryx_u32(x171, x150, x152, &x173); - uint32_t x176; addcarryx_u32(0x0, x174, x153, &x176); - uint32_t x179; uint8_t x180 = addcarryx_u32(0x0, x106, x131, &x179); - uint32_t x182; uint8_t x183 = addcarryx_u32(x180, x109, x155, &x182); - uint32_t x185; uint8_t x186 = addcarryx_u32(x183, x112, x158, &x185); - uint32_t x188; uint8_t x189 = addcarryx_u32(x186, x115, x161, &x188); - uint32_t x191; uint8_t x192 = addcarryx_u32(x189, x118, x164, &x191); - uint32_t x194; uint8_t x195 = addcarryx_u32(x192, x121, x167, &x194); - uint32_t x197; uint8_t x198 = addcarryx_u32(x195, x124, x170, &x197); - uint32_t x200; uint8_t x201 = addcarryx_u32(x198, x127, x173, &x200); - uint32_t x203; uint8_t x204 = addcarryx_u32(x201, x129, x176, &x203); - uint32_t x207; uint32_t x206 = mulx_u32(x179, 0xffffffff, &x207); - uint32_t x210; uint32_t x209 = mulx_u32(x179, 0xffffffff, &x210); - uint32_t x213; uint32_t x212 = mulx_u32(x179, 0xffffffff, &x213); - uint32_t x216; uint32_t x215 = mulx_u32(x179, 0xffffffff, &x216); - uint32_t x218; uint8_t x219 = addcarryx_u32(0x0, x207, x209, &x218); - uint32_t x221; uint8_t x222 = addcarryx_u32(x219, x210, x212, &x221); - uint32_t x224; uint8_t x225 = addcarryx_u32(x222, x213, 0x0, &x224); - uint8_t x226 = (0x0 + 0x0); - uint32_t _2; uint8_t x229 = addcarryx_u32(0x0, x179, x206, &_2); - uint32_t x231; uint8_t x232 = addcarryx_u32(x229, x182, x218, &x231); - uint32_t x234; uint8_t x235 = addcarryx_u32(x232, x185, x221, &x234); - uint32_t x237; uint8_t x238 = addcarryx_u32(x235, x188, x224, &x237); - uint32_t x240; uint8_t x241 = addcarryx_u32(x238, x191, x225, &x240); - uint32_t x243; uint8_t x244 = addcarryx_u32(x241, x194, x226, &x243); - uint32_t x246; uint8_t x247 = addcarryx_u32(x244, x197, x179, &x246); - uint32_t x249; uint8_t x250 = addcarryx_u32(x247, x200, x215, &x249); - uint32_t x252; uint8_t x253 = addcarryx_u32(x250, x203, x216, &x252); - uint8_t x254 = (x253 + x204); - uint32_t x257; uint32_t x256 = mulx_u32(x9, x19, &x257); - uint32_t x260; uint32_t x259 = mulx_u32(x9, x21, &x260); - uint32_t x263; uint32_t x262 = mulx_u32(x9, x23, &x263); - uint32_t x266; uint32_t x265 = mulx_u32(x9, x25, &x266); - uint32_t x269; uint32_t x268 = mulx_u32(x9, x27, &x269); - uint32_t x272; uint32_t x271 = mulx_u32(x9, x29, &x272); - uint32_t x275; uint32_t x274 = mulx_u32(x9, x31, &x275); - uint32_t x278; uint32_t x277 = mulx_u32(x9, x30, &x278); - uint32_t x280; uint8_t x281 = addcarryx_u32(0x0, x257, x259, &x280); - uint32_t x283; uint8_t x284 = addcarryx_u32(x281, x260, x262, &x283); - uint32_t x286; uint8_t x287 = addcarryx_u32(x284, x263, x265, &x286); - uint32_t x289; uint8_t x290 = addcarryx_u32(x287, x266, x268, &x289); - uint32_t x292; uint8_t x293 = addcarryx_u32(x290, x269, x271, &x292); - uint32_t x295; uint8_t x296 = addcarryx_u32(x293, x272, x274, &x295); - uint32_t x298; uint8_t x299 = addcarryx_u32(x296, x275, x277, &x298); - uint32_t x301; addcarryx_u32(0x0, x299, x278, &x301); - uint32_t x304; uint8_t x305 = addcarryx_u32(0x0, x231, x256, &x304); - uint32_t x307; uint8_t x308 = addcarryx_u32(x305, x234, x280, &x307); - uint32_t x310; uint8_t x311 = addcarryx_u32(x308, x237, x283, &x310); - uint32_t x313; uint8_t x314 = addcarryx_u32(x311, x240, x286, &x313); - uint32_t x316; uint8_t x317 = addcarryx_u32(x314, x243, x289, &x316); - uint32_t x319; uint8_t x320 = addcarryx_u32(x317, x246, x292, &x319); - uint32_t x322; uint8_t x323 = addcarryx_u32(x320, x249, x295, &x322); - uint32_t x325; uint8_t x326 = addcarryx_u32(x323, x252, x298, &x325); - uint32_t x328; uint8_t x329 = addcarryx_u32(x326, x254, x301, &x328); - uint32_t x332; uint32_t x331 = mulx_u32(x304, 0xffffffff, &x332); - uint32_t x335; uint32_t x334 = mulx_u32(x304, 0xffffffff, &x335); - uint32_t x338; uint32_t x337 = mulx_u32(x304, 0xffffffff, &x338); - uint32_t x341; uint32_t x340 = mulx_u32(x304, 0xffffffff, &x341); - uint32_t x343; uint8_t x344 = addcarryx_u32(0x0, x332, x334, &x343); - uint32_t x346; uint8_t x347 = addcarryx_u32(x344, x335, x337, &x346); - uint32_t x349; uint8_t x350 = addcarryx_u32(x347, x338, 0x0, &x349); - uint8_t x351 = (0x0 + 0x0); - uint32_t _3; uint8_t x354 = addcarryx_u32(0x0, x304, x331, &_3); - uint32_t x356; uint8_t x357 = addcarryx_u32(x354, x307, x343, &x356); - uint32_t x359; uint8_t x360 = addcarryx_u32(x357, x310, x346, &x359); - uint32_t x362; uint8_t x363 = addcarryx_u32(x360, x313, x349, &x362); - uint32_t x365; uint8_t x366 = addcarryx_u32(x363, x316, x350, &x365); - uint32_t x368; uint8_t x369 = addcarryx_u32(x366, x319, x351, &x368); - uint32_t x371; uint8_t x372 = addcarryx_u32(x369, x322, x304, &x371); - uint32_t x374; uint8_t x375 = addcarryx_u32(x372, x325, x340, &x374); - uint32_t x377; uint8_t x378 = addcarryx_u32(x375, x328, x341, &x377); - uint8_t x379 = (x378 + x329); - uint32_t x382; uint32_t x381 = mulx_u32(x11, x19, &x382); - uint32_t x385; uint32_t x384 = mulx_u32(x11, x21, &x385); - uint32_t x388; uint32_t x387 = mulx_u32(x11, x23, &x388); - uint32_t x391; uint32_t x390 = mulx_u32(x11, x25, &x391); - uint32_t x394; uint32_t x393 = mulx_u32(x11, x27, &x394); - uint32_t x397; uint32_t x396 = mulx_u32(x11, x29, &x397); - uint32_t x400; uint32_t x399 = mulx_u32(x11, x31, &x400); - uint32_t x403; uint32_t x402 = mulx_u32(x11, x30, &x403); - uint32_t x405; uint8_t x406 = addcarryx_u32(0x0, x382, x384, &x405); - uint32_t x408; uint8_t x409 = addcarryx_u32(x406, x385, x387, &x408); - uint32_t x411; uint8_t x412 = addcarryx_u32(x409, x388, x390, &x411); - uint32_t x414; uint8_t x415 = addcarryx_u32(x412, x391, x393, &x414); - uint32_t x417; uint8_t x418 = addcarryx_u32(x415, x394, x396, &x417); - uint32_t x420; uint8_t x421 = addcarryx_u32(x418, x397, x399, &x420); - uint32_t x423; uint8_t x424 = addcarryx_u32(x421, x400, x402, &x423); - uint32_t x426; addcarryx_u32(0x0, x424, x403, &x426); - uint32_t x429; uint8_t x430 = addcarryx_u32(0x0, x356, x381, &x429); - uint32_t x432; uint8_t x433 = addcarryx_u32(x430, x359, x405, &x432); - uint32_t x435; uint8_t x436 = addcarryx_u32(x433, x362, x408, &x435); - uint32_t x438; uint8_t x439 = addcarryx_u32(x436, x365, x411, &x438); - uint32_t x441; uint8_t x442 = addcarryx_u32(x439, x368, x414, &x441); - uint32_t x444; uint8_t x445 = addcarryx_u32(x442, x371, x417, &x444); - uint32_t x447; uint8_t x448 = addcarryx_u32(x445, x374, x420, &x447); - uint32_t x450; uint8_t x451 = addcarryx_u32(x448, x377, x423, &x450); - uint32_t x453; uint8_t x454 = addcarryx_u32(x451, x379, x426, &x453); - uint32_t x457; uint32_t x456 = mulx_u32(x429, 0xffffffff, &x457); - uint32_t x460; uint32_t x459 = mulx_u32(x429, 0xffffffff, &x460); - uint32_t x463; uint32_t x462 = mulx_u32(x429, 0xffffffff, &x463); - uint32_t x466; uint32_t x465 = mulx_u32(x429, 0xffffffff, &x466); - uint32_t x468; uint8_t x469 = addcarryx_u32(0x0, x457, x459, &x468); - uint32_t x471; uint8_t x472 = addcarryx_u32(x469, x460, x462, &x471); - uint32_t x474; uint8_t x475 = addcarryx_u32(x472, x463, 0x0, &x474); - uint8_t x476 = (0x0 + 0x0); - uint32_t _4; uint8_t x479 = addcarryx_u32(0x0, x429, x456, &_4); - uint32_t x481; uint8_t x482 = addcarryx_u32(x479, x432, x468, &x481); - uint32_t x484; uint8_t x485 = addcarryx_u32(x482, x435, x471, &x484); - uint32_t x487; uint8_t x488 = addcarryx_u32(x485, x438, x474, &x487); - uint32_t x490; uint8_t x491 = addcarryx_u32(x488, x441, x475, &x490); - uint32_t x493; uint8_t x494 = addcarryx_u32(x491, x444, x476, &x493); - uint32_t x496; uint8_t x497 = addcarryx_u32(x494, x447, x429, &x496); - uint32_t x499; uint8_t x500 = addcarryx_u32(x497, x450, x465, &x499); - uint32_t x502; uint8_t x503 = addcarryx_u32(x500, x453, x466, &x502); - uint8_t x504 = (x503 + x454); - uint32_t x507; uint32_t x506 = mulx_u32(x13, x19, &x507); - uint32_t x510; uint32_t x509 = mulx_u32(x13, x21, &x510); - uint32_t x513; uint32_t x512 = mulx_u32(x13, x23, &x513); - uint32_t x516; uint32_t x515 = mulx_u32(x13, x25, &x516); - uint32_t x519; uint32_t x518 = mulx_u32(x13, x27, &x519); - uint32_t x522; uint32_t x521 = mulx_u32(x13, x29, &x522); - uint32_t x525; uint32_t x524 = mulx_u32(x13, x31, &x525); - uint32_t x528; uint32_t x527 = mulx_u32(x13, x30, &x528); - uint32_t x530; uint8_t x531 = addcarryx_u32(0x0, x507, x509, &x530); - uint32_t x533; uint8_t x534 = addcarryx_u32(x531, x510, x512, &x533); - uint32_t x536; uint8_t x537 = addcarryx_u32(x534, x513, x515, &x536); - uint32_t x539; uint8_t x540 = addcarryx_u32(x537, x516, x518, &x539); - uint32_t x542; uint8_t x543 = addcarryx_u32(x540, x519, x521, &x542); - uint32_t x545; uint8_t x546 = addcarryx_u32(x543, x522, x524, &x545); - uint32_t x548; uint8_t x549 = addcarryx_u32(x546, x525, x527, &x548); - uint32_t x551; addcarryx_u32(0x0, x549, x528, &x551); - uint32_t x554; uint8_t x555 = addcarryx_u32(0x0, x481, x506, &x554); - uint32_t x557; uint8_t x558 = addcarryx_u32(x555, x484, x530, &x557); - uint32_t x560; uint8_t x561 = addcarryx_u32(x558, x487, x533, &x560); - uint32_t x563; uint8_t x564 = addcarryx_u32(x561, x490, x536, &x563); - uint32_t x566; uint8_t x567 = addcarryx_u32(x564, x493, x539, &x566); - uint32_t x569; uint8_t x570 = addcarryx_u32(x567, x496, x542, &x569); - uint32_t x572; uint8_t x573 = addcarryx_u32(x570, x499, x545, &x572); - uint32_t x575; uint8_t x576 = addcarryx_u32(x573, x502, x548, &x575); - uint32_t x578; uint8_t x579 = addcarryx_u32(x576, x504, x551, &x578); - uint32_t x582; uint32_t x581 = mulx_u32(x554, 0xffffffff, &x582); - uint32_t x585; uint32_t x584 = mulx_u32(x554, 0xffffffff, &x585); - uint32_t x588; uint32_t x587 = mulx_u32(x554, 0xffffffff, &x588); - uint32_t x591; uint32_t x590 = mulx_u32(x554, 0xffffffff, &x591); - uint32_t x593; uint8_t x594 = addcarryx_u32(0x0, x582, x584, &x593); - uint32_t x596; uint8_t x597 = addcarryx_u32(x594, x585, x587, &x596); - uint32_t x599; uint8_t x600 = addcarryx_u32(x597, x588, 0x0, &x599); - uint8_t x601 = (0x0 + 0x0); - uint32_t _5; uint8_t x604 = addcarryx_u32(0x0, x554, x581, &_5); - uint32_t x606; uint8_t x607 = addcarryx_u32(x604, x557, x593, &x606); - uint32_t x609; uint8_t x610 = addcarryx_u32(x607, x560, x596, &x609); - uint32_t x612; uint8_t x613 = addcarryx_u32(x610, x563, x599, &x612); - uint32_t x615; uint8_t x616 = addcarryx_u32(x613, x566, x600, &x615); - uint32_t x618; uint8_t x619 = addcarryx_u32(x616, x569, x601, &x618); - uint32_t x621; uint8_t x622 = addcarryx_u32(x619, x572, x554, &x621); - uint32_t x624; uint8_t x625 = addcarryx_u32(x622, x575, x590, &x624); - uint32_t x627; uint8_t x628 = addcarryx_u32(x625, x578, x591, &x627); - uint8_t x629 = (x628 + x579); - uint32_t x632; uint32_t x631 = mulx_u32(x15, x19, &x632); - uint32_t x635; uint32_t x634 = mulx_u32(x15, x21, &x635); - uint32_t x638; uint32_t x637 = mulx_u32(x15, x23, &x638); - uint32_t x641; uint32_t x640 = mulx_u32(x15, x25, &x641); - uint32_t x644; uint32_t x643 = mulx_u32(x15, x27, &x644); - uint32_t x647; uint32_t x646 = mulx_u32(x15, x29, &x647); - uint32_t x650; uint32_t x649 = mulx_u32(x15, x31, &x650); - uint32_t x653; uint32_t x652 = mulx_u32(x15, x30, &x653); - uint32_t x655; uint8_t x656 = addcarryx_u32(0x0, x632, x634, &x655); - uint32_t x658; uint8_t x659 = addcarryx_u32(x656, x635, x637, &x658); - uint32_t x661; uint8_t x662 = addcarryx_u32(x659, x638, x640, &x661); - uint32_t x664; uint8_t x665 = addcarryx_u32(x662, x641, x643, &x664); - uint32_t x667; uint8_t x668 = addcarryx_u32(x665, x644, x646, &x667); - uint32_t x670; uint8_t x671 = addcarryx_u32(x668, x647, x649, &x670); - uint32_t x673; uint8_t x674 = addcarryx_u32(x671, x650, x652, &x673); - uint32_t x676; addcarryx_u32(0x0, x674, x653, &x676); - uint32_t x679; uint8_t x680 = addcarryx_u32(0x0, x606, x631, &x679); - uint32_t x682; uint8_t x683 = addcarryx_u32(x680, x609, x655, &x682); - uint32_t x685; uint8_t x686 = addcarryx_u32(x683, x612, x658, &x685); - uint32_t x688; uint8_t x689 = addcarryx_u32(x686, x615, x661, &x688); - uint32_t x691; uint8_t x692 = addcarryx_u32(x689, x618, x664, &x691); - uint32_t x694; uint8_t x695 = addcarryx_u32(x692, x621, x667, &x694); - uint32_t x697; uint8_t x698 = addcarryx_u32(x695, x624, x670, &x697); - uint32_t x700; uint8_t x701 = addcarryx_u32(x698, x627, x673, &x700); - uint32_t x703; uint8_t x704 = addcarryx_u32(x701, x629, x676, &x703); - uint32_t x707; uint32_t x706 = mulx_u32(x679, 0xffffffff, &x707); - uint32_t x710; uint32_t x709 = mulx_u32(x679, 0xffffffff, &x710); - uint32_t x713; uint32_t x712 = mulx_u32(x679, 0xffffffff, &x713); - uint32_t x716; uint32_t x715 = mulx_u32(x679, 0xffffffff, &x716); - uint32_t x718; uint8_t x719 = addcarryx_u32(0x0, x707, x709, &x718); - uint32_t x721; uint8_t x722 = addcarryx_u32(x719, x710, x712, &x721); - uint32_t x724; uint8_t x725 = addcarryx_u32(x722, x713, 0x0, &x724); - uint8_t x726 = (0x0 + 0x0); - uint32_t _6; uint8_t x729 = addcarryx_u32(0x0, x679, x706, &_6); - uint32_t x731; uint8_t x732 = addcarryx_u32(x729, x682, x718, &x731); - uint32_t x734; uint8_t x735 = addcarryx_u32(x732, x685, x721, &x734); - uint32_t x737; uint8_t x738 = addcarryx_u32(x735, x688, x724, &x737); - uint32_t x740; uint8_t x741 = addcarryx_u32(x738, x691, x725, &x740); - uint32_t x743; uint8_t x744 = addcarryx_u32(x741, x694, x726, &x743); - uint32_t x746; uint8_t x747 = addcarryx_u32(x744, x697, x679, &x746); - uint32_t x749; uint8_t x750 = addcarryx_u32(x747, x700, x715, &x749); - uint32_t x752; uint8_t x753 = addcarryx_u32(x750, x703, x716, &x752); - uint8_t x754 = (x753 + x704); - uint32_t x757; uint32_t x756 = mulx_u32(x17, x19, &x757); - uint32_t x760; uint32_t x759 = mulx_u32(x17, x21, &x760); - uint32_t x763; uint32_t x762 = mulx_u32(x17, x23, &x763); - uint32_t x766; uint32_t x765 = mulx_u32(x17, x25, &x766); - uint32_t x769; uint32_t x768 = mulx_u32(x17, x27, &x769); - uint32_t x772; uint32_t x771 = mulx_u32(x17, x29, &x772); - uint32_t x775; uint32_t x774 = mulx_u32(x17, x31, &x775); - uint32_t x778; uint32_t x777 = mulx_u32(x17, x30, &x778); - uint32_t x780; uint8_t x781 = addcarryx_u32(0x0, x757, x759, &x780); - uint32_t x783; uint8_t x784 = addcarryx_u32(x781, x760, x762, &x783); - uint32_t x786; uint8_t x787 = addcarryx_u32(x784, x763, x765, &x786); - uint32_t x789; uint8_t x790 = addcarryx_u32(x787, x766, x768, &x789); - uint32_t x792; uint8_t x793 = addcarryx_u32(x790, x769, x771, &x792); - uint32_t x795; uint8_t x796 = addcarryx_u32(x793, x772, x774, &x795); - uint32_t x798; uint8_t x799 = addcarryx_u32(x796, x775, x777, &x798); - uint32_t x801; addcarryx_u32(0x0, x799, x778, &x801); - uint32_t x804; uint8_t x805 = addcarryx_u32(0x0, x731, x756, &x804); - uint32_t x807; uint8_t x808 = addcarryx_u32(x805, x734, x780, &x807); - uint32_t x810; uint8_t x811 = addcarryx_u32(x808, x737, x783, &x810); - uint32_t x813; uint8_t x814 = addcarryx_u32(x811, x740, x786, &x813); - uint32_t x816; uint8_t x817 = addcarryx_u32(x814, x743, x789, &x816); - uint32_t x819; uint8_t x820 = addcarryx_u32(x817, x746, x792, &x819); - uint32_t x822; uint8_t x823 = addcarryx_u32(x820, x749, x795, &x822); - uint32_t x825; uint8_t x826 = addcarryx_u32(x823, x752, x798, &x825); - uint32_t x828; uint8_t x829 = addcarryx_u32(x826, x754, x801, &x828); - uint32_t x832; uint32_t x831 = mulx_u32(x804, 0xffffffff, &x832); - uint32_t x835; uint32_t x834 = mulx_u32(x804, 0xffffffff, &x835); - uint32_t x838; uint32_t x837 = mulx_u32(x804, 0xffffffff, &x838); - uint32_t x841; uint32_t x840 = mulx_u32(x804, 0xffffffff, &x841); - uint32_t x843; uint8_t x844 = addcarryx_u32(0x0, x832, x834, &x843); - uint32_t x846; uint8_t x847 = addcarryx_u32(x844, x835, x837, &x846); - uint32_t x849; uint8_t x850 = addcarryx_u32(x847, x838, 0x0, &x849); - uint8_t x851 = (0x0 + 0x0); - uint32_t _7; uint8_t x854 = addcarryx_u32(0x0, x804, x831, &_7); - uint32_t x856; uint8_t x857 = addcarryx_u32(x854, x807, x843, &x856); - uint32_t x859; uint8_t x860 = addcarryx_u32(x857, x810, x846, &x859); - uint32_t x862; uint8_t x863 = addcarryx_u32(x860, x813, x849, &x862); - uint32_t x865; uint8_t x866 = addcarryx_u32(x863, x816, x850, &x865); - uint32_t x868; uint8_t x869 = addcarryx_u32(x866, x819, x851, &x868); - uint32_t x871; uint8_t x872 = addcarryx_u32(x869, x822, x804, &x871); - uint32_t x874; uint8_t x875 = addcarryx_u32(x872, x825, x840, &x874); - uint32_t x877; uint8_t x878 = addcarryx_u32(x875, x828, x841, &x877); - uint8_t x879 = (x878 + x829); - uint32_t x882; uint32_t x881 = mulx_u32(x16, x19, &x882); - uint32_t x885; uint32_t x884 = mulx_u32(x16, x21, &x885); - uint32_t x888; uint32_t x887 = mulx_u32(x16, x23, &x888); - uint32_t x891; uint32_t x890 = mulx_u32(x16, x25, &x891); - uint32_t x894; uint32_t x893 = mulx_u32(x16, x27, &x894); - uint32_t x897; uint32_t x896 = mulx_u32(x16, x29, &x897); - uint32_t x900; uint32_t x899 = mulx_u32(x16, x31, &x900); - uint32_t x903; uint32_t x902 = mulx_u32(x16, x30, &x903); - uint32_t x905; uint8_t x906 = addcarryx_u32(0x0, x882, x884, &x905); - uint32_t x908; uint8_t x909 = addcarryx_u32(x906, x885, x887, &x908); - uint32_t x911; uint8_t x912 = addcarryx_u32(x909, x888, x890, &x911); - uint32_t x914; uint8_t x915 = addcarryx_u32(x912, x891, x893, &x914); - uint32_t x917; uint8_t x918 = addcarryx_u32(x915, x894, x896, &x917); - uint32_t x920; uint8_t x921 = addcarryx_u32(x918, x897, x899, &x920); - uint32_t x923; uint8_t x924 = addcarryx_u32(x921, x900, x902, &x923); - uint32_t x926; addcarryx_u32(0x0, x924, x903, &x926); - uint32_t x929; uint8_t x930 = addcarryx_u32(0x0, x856, x881, &x929); - uint32_t x932; uint8_t x933 = addcarryx_u32(x930, x859, x905, &x932); - uint32_t x935; uint8_t x936 = addcarryx_u32(x933, x862, x908, &x935); - uint32_t x938; uint8_t x939 = addcarryx_u32(x936, x865, x911, &x938); - uint32_t x941; uint8_t x942 = addcarryx_u32(x939, x868, x914, &x941); - uint32_t x944; uint8_t x945 = addcarryx_u32(x942, x871, x917, &x944); - uint32_t x947; uint8_t x948 = addcarryx_u32(x945, x874, x920, &x947); - uint32_t x950; uint8_t x951 = addcarryx_u32(x948, x877, x923, &x950); - uint32_t x953; uint8_t x954 = addcarryx_u32(x951, x879, x926, &x953); - uint32_t x957; uint32_t x956 = mulx_u32(x929, 0xffffffff, &x957); - uint32_t x960; uint32_t x959 = mulx_u32(x929, 0xffffffff, &x960); - uint32_t x963; uint32_t x962 = mulx_u32(x929, 0xffffffff, &x963); - uint32_t x966; uint32_t x965 = mulx_u32(x929, 0xffffffff, &x966); - uint32_t x968; uint8_t x969 = addcarryx_u32(0x0, x957, x959, &x968); - uint32_t x971; uint8_t x972 = addcarryx_u32(x969, x960, x962, &x971); - uint32_t x974; uint8_t x975 = addcarryx_u32(x972, x963, 0x0, &x974); - uint8_t x976 = (0x0 + 0x0); - uint32_t _8; uint8_t x979 = addcarryx_u32(0x0, x929, x956, &_8); - uint32_t x981; uint8_t x982 = addcarryx_u32(x979, x932, x968, &x981); - uint32_t x984; uint8_t x985 = addcarryx_u32(x982, x935, x971, &x984); - uint32_t x987; uint8_t x988 = addcarryx_u32(x985, x938, x974, &x987); - uint32_t x990; uint8_t x991 = addcarryx_u32(x988, x941, x975, &x990); - uint32_t x993; uint8_t x994 = addcarryx_u32(x991, x944, x976, &x993); - uint32_t x996; uint8_t x997 = addcarryx_u32(x994, x947, x929, &x996); - uint32_t x999; uint8_t x1000 = addcarryx_u32(x997, x950, x965, &x999); - uint32_t x1002; uint8_t x1003 = addcarryx_u32(x1000, x953, x966, &x1002); - uint8_t x1004 = (x1003 + x954); - uint32_t x1006; uint8_t x1007 = subborrow_u32(0x0, x981, 0xffffffff, &x1006); - uint32_t x1009; uint8_t x1010 = subborrow_u32(x1007, x984, 0xffffffff, &x1009); - uint32_t x1012; uint8_t x1013 = subborrow_u32(x1010, x987, 0xffffffff, &x1012); - uint32_t x1015; uint8_t x1016 = subborrow_u32(x1013, x990, 0x0, &x1015); - uint32_t x1018; uint8_t x1019 = subborrow_u32(x1016, x993, 0x0, &x1018); - uint32_t x1021; uint8_t x1022 = subborrow_u32(x1019, x996, 0x0, &x1021); - uint32_t x1024; uint8_t x1025 = subborrow_u32(x1022, x999, 0x1, &x1024); - uint32_t x1027; uint8_t x1028 = subborrow_u32(x1025, x1002, 0xffffffff, &x1027); - uint32_t _9; uint8_t x1031 = subborrow_u32(x1028, x1004, 0x0, &_9); - uint32_t x1032 = cmovznz_u32(x1031, x1027, x1002); - uint32_t x1033 = cmovznz_u32(x1031, x1024, x999); - uint32_t x1034 = cmovznz_u32(x1031, x1021, x996); - uint32_t x1035 = cmovznz_u32(x1031, x1018, x993); - uint32_t x1036 = cmovznz_u32(x1031, x1015, x990); - uint32_t x1037 = cmovznz_u32(x1031, x1012, x987); - uint32_t x1038 = cmovznz_u32(x1031, x1009, x984); - uint32_t x1039 = cmovznz_u32(x1031, x1006, x981); - out[0] = x1039; - out[1] = x1038; - out[2] = x1037; - out[3] = x1036; - out[4] = x1035; - out[5] = x1034; - out[6] = x1033; - out[7] = x1032; -} - -// NOTE: the following functions are generated from fiat-crypto, from the same -// template as their 64-bit counterparts above, but the correctness proof of -// the template was not composed with the correctness proof of the -// specialization pipeline. This is because Coq unexplainedly loops on trying -// to synthesize opp and sub using the normal pipeline. - -static void fe_sub(uint32_t out[8], const uint32_t in1[8], const uint32_t in2[8]) { - const uint32_t x14 = in1[7]; - const uint32_t x15 = in1[6]; - const uint32_t x13 = in1[5]; - const uint32_t x11 = in1[4]; - const uint32_t x9 = in1[3]; - const uint32_t x7 = in1[2]; - const uint32_t x5 = in1[1]; - const uint32_t x3 = in1[0]; - const uint32_t x28 = in2[7]; - const uint32_t x29 = in2[6]; - const uint32_t x27 = in2[5]; - const uint32_t x25 = in2[4]; - const uint32_t x23 = in2[3]; - const uint32_t x21 = in2[2]; - const uint32_t x19 = in2[1]; - const uint32_t x17 = in2[0]; - uint32_t x31; uint8_t x32 = subborrow_u32(0x0, x3, x17, &x31); - uint32_t x34; uint8_t x35 = subborrow_u32(x32, x5, x19, &x34); - uint32_t x37; uint8_t x38 = subborrow_u32(x35, x7, x21, &x37); - uint32_t x40; uint8_t x41 = subborrow_u32(x38, x9, x23, &x40); - uint32_t x43; uint8_t x44 = subborrow_u32(x41, x11, x25, &x43); - uint32_t x46; uint8_t x47 = subborrow_u32(x44, x13, x27, &x46); - uint32_t x49; uint8_t x50 = subborrow_u32(x47, x15, x29, &x49); - uint32_t x52; uint8_t x53 = subborrow_u32(x50, x14, x28, &x52); - uint32_t x54 = cmovznz_u32(x53, 0x0, 0xffffffff); - uint32_t x56; uint8_t x57 = addcarryx_u32(0x0, x31, (x54 & 0xffffffff), &x56); - uint32_t x59; uint8_t x60 = addcarryx_u32(x57, x34, (x54 & 0xffffffff), &x59); - uint32_t x62; uint8_t x63 = addcarryx_u32(x60, x37, (x54 & 0xffffffff), &x62); - uint32_t x65; uint8_t x66 = addcarryx_u32(x63, x40, 0x0, &x65); - uint32_t x68; uint8_t x69 = addcarryx_u32(x66, x43, 0x0, &x68); - uint32_t x71; uint8_t x72 = addcarryx_u32(x69, x46, 0x0, &x71); - uint32_t x74; uint8_t x75 = addcarryx_u32(x72, x49, ((uint8_t)x54 & 0x1), &x74); - uint32_t x77; addcarryx_u32(x75, x52, (x54 & 0xffffffff), &x77); - out[0] = x56; - out[1] = x59; - out[2] = x62; - out[3] = x65; - out[4] = x68; - out[5] = x71; - out[6] = x74; - out[7] = x77; -} - -// fe_op sets out = -in -static void fe_opp(uint32_t out[8], const uint32_t in1[8]) { - const uint32_t x12 = in1[7]; - const uint32_t x13 = in1[6]; - const uint32_t x11 = in1[5]; - const uint32_t x9 = in1[4]; - const uint32_t x7 = in1[3]; - const uint32_t x5 = in1[2]; - const uint32_t x3 = in1[1]; - const uint32_t x1 = in1[0]; - uint32_t x15; uint8_t x16 = subborrow_u32(0x0, 0x0, x1, &x15); - uint32_t x18; uint8_t x19 = subborrow_u32(x16, 0x0, x3, &x18); - uint32_t x21; uint8_t x22 = subborrow_u32(x19, 0x0, x5, &x21); - uint32_t x24; uint8_t x25 = subborrow_u32(x22, 0x0, x7, &x24); - uint32_t x27; uint8_t x28 = subborrow_u32(x25, 0x0, x9, &x27); - uint32_t x30; uint8_t x31 = subborrow_u32(x28, 0x0, x11, &x30); - uint32_t x33; uint8_t x34 = subborrow_u32(x31, 0x0, x13, &x33); - uint32_t x36; uint8_t x37 = subborrow_u32(x34, 0x0, x12, &x36); - uint32_t x38 = cmovznz_u32(x37, 0x0, 0xffffffff); - uint32_t x40; uint8_t x41 = addcarryx_u32(0x0, x15, (x38 & 0xffffffff), &x40); - uint32_t x43; uint8_t x44 = addcarryx_u32(x41, x18, (x38 & 0xffffffff), &x43); - uint32_t x46; uint8_t x47 = addcarryx_u32(x44, x21, (x38 & 0xffffffff), &x46); - uint32_t x49; uint8_t x50 = addcarryx_u32(x47, x24, 0x0, &x49); - uint32_t x52; uint8_t x53 = addcarryx_u32(x50, x27, 0x0, &x52); - uint32_t x55; uint8_t x56 = addcarryx_u32(x53, x30, 0x0, &x55); - uint32_t x58; uint8_t x59 = addcarryx_u32(x56, x33, ((uint8_t)x38 & 0x1), &x58); - uint32_t x61; addcarryx_u32(x59, x36, (x38 & 0xffffffff), &x61); - out[0] = x40; - out[1] = x43; - out[2] = x46; - out[3] = x49; - out[4] = x52; - out[5] = x55; - out[6] = x58; - out[7] = x61; -} - -#endif // utility functions, handwritten @@ -840,22 +60,28 @@ static void fe_opp(uint32_t out[8], const uint32_t in1[8]) { #define NLIMBS 4 typedef uint64_t limb_t; -#define cmovznz_limb cmovznz_u64 typedef uint64_t fe[NLIMBS]; #else // 64BIT; else 32BIT #define NLIMBS 8 typedef uint32_t limb_t; -#define cmovznz_limb cmovznz_u32 typedef uint32_t fe[NLIMBS]; #endif // 64BIT +#define fe_add fiat_p256_add +#define fe_sub fiat_p256_sub +#define fe_opp fiat_p256_opp + +#define fe_mul fiat_p256_mul +#define fe_sqr fiat_p256_square + +#define fe_tobytes fiat_p256_to_bytes +#define fe_frombytes fiat_p256_from_bytes + static limb_t fe_nz(const limb_t in1[NLIMBS]) { - limb_t ret = 0; - for (int i = 0; i < NLIMBS; i++) { - ret |= in1[i]; - } + limb_t ret; + fiat_p256_nonzero(&ret, in1); return ret; } @@ -867,33 +93,11 @@ static void fe_copy(limb_t out[NLIMBS], const limb_t in1[NLIMBS]) { static void fe_cmovznz(limb_t out[NLIMBS], limb_t t, const limb_t z[NLIMBS], const limb_t nz[NLIMBS]) { - for (int i = 0; i < NLIMBS; i++) { - out[i] = cmovznz_limb(t, z[i], nz[i]); - } -} - -static void fe_sqr(fe out, const fe in) { - fe_mul(out, in, in); -} - -static void fe_tobytes(uint8_t out[NBYTES], const fe in) { - for (int i = 0; i> (8*(i%sizeof(in[0])))); - } -} - -static void fe_frombytes(fe out, const uint8_t in[NBYTES]) { - for (int i = 0; i> 3] >> (i & 7)) & 1; } -// Interleaved point multiplication using precomputed point multiples: The -// small point multiples 0*P, 1*P, ..., 17*P are in p_pre_comp, the scalar -// in p_scalar, if non-NULL. If g_scalar is non-NULL, we also add this multiple -// of the generator, using certain (large) precomputed multiples in g_pre_comp. -// Output point (X, Y, Z) is stored in x_out, y_out, z_out. -static void batch_mul(fe x_out, fe y_out, fe z_out, - const uint8_t *p_scalar, const uint8_t *g_scalar, - const fe p_pre_comp[17][3]) { - // set nq to the point at infinity - fe nq[3] = {{0},{0},{0}}, ftmp, tmp[3]; - uint64_t bits; - uint8_t sign, digit; - - // Loop over both scalars msb-to-lsb, interleaving additions of multiples - // of the generator (two in each of the last 32 rounds) and additions of p - // (every 5th round). - - int skip = 1; // save two point operations in the first round - size_t i = p_scalar != NULL ? 255 : 31; - for (;;) { - // double - if (!skip) { - point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]); - } - - // add multiples of the generator - if (g_scalar != NULL && i <= 31) { - // first, look 32 bits upwards - bits = get_bit(g_scalar, i + 224) << 3; - bits |= get_bit(g_scalar, i + 160) << 2; - bits |= get_bit(g_scalar, i + 96) << 1; - bits |= get_bit(g_scalar, i + 32); - // select the point to add, in constant time - select_point(bits, 16, g_pre_comp[1], tmp); - - if (!skip) { - point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */, - tmp[0], tmp[1], tmp[2]); - } else { - fe_copy(nq[0], tmp[0]); - fe_copy(nq[1], tmp[1]); - fe_copy(nq[2], tmp[2]); - skip = 0; - } - - // second, look at the current position - bits = get_bit(g_scalar, i + 192) << 3; - bits |= get_bit(g_scalar, i + 128) << 2; - bits |= get_bit(g_scalar, i + 64) << 1; - bits |= get_bit(g_scalar, i); - // select the point to add, in constant time - select_point(bits, 16, g_pre_comp[0], tmp); - point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */, tmp[0], - tmp[1], tmp[2]); - } - - // do other additions every 5 doublings - if (p_scalar != NULL && i % 5 == 0) { - bits = get_bit(p_scalar, i + 4) << 5; - bits |= get_bit(p_scalar, i + 3) << 4; - bits |= get_bit(p_scalar, i + 2) << 3; - bits |= get_bit(p_scalar, i + 1) << 2; - bits |= get_bit(p_scalar, i) << 1; - bits |= get_bit(p_scalar, i - 1); - ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits); - - // select the point to add or subtract, in constant time. - select_point(digit, 17, p_pre_comp, tmp); - fe_opp(ftmp, tmp[1]); // (X, -Y, Z) is the negative point. - fe_cmovznz(tmp[1], sign, tmp[1], ftmp); - - if (!skip) { - point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 0 /* mixed */, - tmp[0], tmp[1], tmp[2]); - } else { - fe_copy(nq[0], tmp[0]); - fe_copy(nq[1], tmp[1]); - fe_copy(nq[2], tmp[2]); - skip = 0; - } - } - - if (i == 0) { - break; - } - --i; - } - fe_copy(x_out, nq[0]); - fe_copy(y_out, nq[1]); - fe_copy(z_out, nq[2]); -} - // OPENSSL EC_METHOD FUNCTIONS // Takes the Jacobian coordinates (X, Y, Z) of a point and returns (X', Y') = @@ -1686,45 +798,116 @@ static void ec_GFp_nistp256_dbl(const EC_GROUP *group, EC_RAW_POINT *r, fe_to_generic(&r->Z, z); } -static void ec_GFp_nistp256_points_mul(const EC_GROUP *group, EC_RAW_POINT *r, - const EC_SCALAR *g_scalar, - const EC_RAW_POINT *p, - const EC_SCALAR *p_scalar) { +static void ec_GFp_nistp256_point_mul(const EC_GROUP *group, EC_RAW_POINT *r, + const EC_RAW_POINT *p, + const EC_SCALAR *scalar) { fe p_pre_comp[17][3]; - fe x_out, y_out, z_out; + OPENSSL_memset(&p_pre_comp, 0, sizeof(p_pre_comp)); + // Precompute multiples. + fe_from_generic(p_pre_comp[1][0], &p->X); + fe_from_generic(p_pre_comp[1][1], &p->Y); + fe_from_generic(p_pre_comp[1][2], &p->Z); + for (size_t j = 2; j <= 16; ++j) { + if (j & 1) { + point_add(p_pre_comp[j][0], p_pre_comp[j][1], p_pre_comp[j][2], + p_pre_comp[1][0], p_pre_comp[1][1], p_pre_comp[1][2], 0, + p_pre_comp[j - 1][0], p_pre_comp[j - 1][1], + p_pre_comp[j - 1][2]); + } else { + point_double(p_pre_comp[j][0], p_pre_comp[j][1], p_pre_comp[j][2], + p_pre_comp[j / 2][0], p_pre_comp[j / 2][1], + p_pre_comp[j / 2][2]); + } + } - if (p != NULL && p_scalar != NULL) { - // We treat NULL scalars as 0, and NULL points as points at infinity, i.e., - // they contribute nothing to the linear combination. - OPENSSL_memset(&p_pre_comp, 0, sizeof(p_pre_comp)); - // Precompute multiples. - fe_from_generic(p_pre_comp[1][0], &p->X); - fe_from_generic(p_pre_comp[1][1], &p->Y); - fe_from_generic(p_pre_comp[1][2], &p->Z); - for (size_t j = 2; j <= 16; ++j) { - if (j & 1) { - point_add(p_pre_comp[j][0], p_pre_comp[j][1], - p_pre_comp[j][2], p_pre_comp[1][0], - p_pre_comp[1][1], p_pre_comp[1][2], - 0, - p_pre_comp[j - 1][0], p_pre_comp[j - 1][1], - p_pre_comp[j - 1][2]); + // Set nq to the point at infinity. + fe nq[3] = {{0}, {0}, {0}}, ftmp, tmp[3]; + + // Loop over |scalar| msb-to-lsb, incorporating |p_pre_comp| every 5th round. + int skip = 1; // Save two point operations in the first round. + for (size_t i = 255; i < 256; i--) { + // double + if (!skip) { + point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]); + } + + // do other additions every 5 doublings + if (i % 5 == 0) { + uint64_t bits = get_bit(scalar->bytes, i + 4) << 5; + bits |= get_bit(scalar->bytes, i + 3) << 4; + bits |= get_bit(scalar->bytes, i + 2) << 3; + bits |= get_bit(scalar->bytes, i + 1) << 2; + bits |= get_bit(scalar->bytes, i) << 1; + bits |= get_bit(scalar->bytes, i - 1); + uint8_t sign, digit; + ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits); + + // select the point to add or subtract, in constant time. + select_point(digit, 17, (const fe(*)[3])p_pre_comp, tmp); + fe_opp(ftmp, tmp[1]); // (X, -Y, Z) is the negative point. + fe_cmovznz(tmp[1], sign, tmp[1], ftmp); + + if (!skip) { + point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 0 /* mixed */, + tmp[0], tmp[1], tmp[2]); } else { - point_double(p_pre_comp[j][0], p_pre_comp[j][1], - p_pre_comp[j][2], p_pre_comp[j / 2][0], - p_pre_comp[j / 2][1], p_pre_comp[j / 2][2]); + fe_copy(nq[0], tmp[0]); + fe_copy(nq[1], tmp[1]); + fe_copy(nq[2], tmp[2]); + skip = 0; } } } - batch_mul(x_out, y_out, z_out, - (p != NULL && p_scalar != NULL) ? p_scalar->bytes : NULL, - g_scalar != NULL ? g_scalar->bytes : NULL, - (const fe (*) [3])p_pre_comp); + fe_to_generic(&r->X, nq[0]); + fe_to_generic(&r->Y, nq[1]); + fe_to_generic(&r->Z, nq[2]); +} - fe_to_generic(&r->X, x_out); - fe_to_generic(&r->Y, y_out); - fe_to_generic(&r->Z, z_out); +static void ec_GFp_nistp256_point_mul_base(const EC_GROUP *group, + EC_RAW_POINT *r, + const EC_SCALAR *scalar) { + // Set nq to the point at infinity. + fe nq[3] = {{0}, {0}, {0}}, tmp[3]; + + int skip = 1; // Save two point operations in the first round. + for (size_t i = 31; i < 32; i--) { + if (!skip) { + point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]); + } + + // First, look 32 bits upwards. + uint64_t bits = get_bit(scalar->bytes, i + 224) << 3; + bits |= get_bit(scalar->bytes, i + 160) << 2; + bits |= get_bit(scalar->bytes, i + 96) << 1; + bits |= get_bit(scalar->bytes, i + 32); + // Select the point to add, in constant time. + select_point(bits, 16, g_pre_comp[1], tmp); + + if (!skip) { + point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */, tmp[0], + tmp[1], tmp[2]); + } else { + fe_copy(nq[0], tmp[0]); + fe_copy(nq[1], tmp[1]); + fe_copy(nq[2], tmp[2]); + skip = 0; + } + + // Second, look at the current position. + bits = get_bit(scalar->bytes, i + 192) << 3; + bits |= get_bit(scalar->bytes, i + 128) << 2; + bits |= get_bit(scalar->bytes, i + 64) << 1; + bits |= get_bit(scalar->bytes, i); + // Select the point to add, in constant time. + select_point(bits, 16, g_pre_comp[0], tmp); + point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */, tmp[0], + tmp[1], tmp[2]); + } + + fe_to_generic(&r->X, nq[0]); + fe_to_generic(&r->Y, nq[1]); + fe_to_generic(&r->Z, nq[2]); } static void ec_GFp_nistp256_point_mul_public(const EC_GROUP *group, @@ -1862,7 +1045,8 @@ DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_nistp256_method) { ec_GFp_nistp256_point_get_affine_coordinates; out->add = ec_GFp_nistp256_add; out->dbl = ec_GFp_nistp256_dbl; - out->mul = ec_GFp_nistp256_points_mul; + out->mul = ec_GFp_nistp256_point_mul; + out->mul_base = ec_GFp_nistp256_point_mul_base; out->mul_public = ec_GFp_nistp256_point_mul_public; out->felem_mul = ec_GFp_mont_felem_mul; out->felem_sqr = ec_GFp_mont_felem_sqr; @@ -1871,6 +1055,6 @@ DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_nistp256_method) { out->scalar_inv_montgomery = ec_simple_scalar_inv_montgomery; out->scalar_inv_montgomery_vartime = ec_GFp_simple_mont_inv_mod_ord_vartime; out->cmp_x_coordinate = ec_GFp_nistp256_cmp_x_coordinate; -}; +} #undef BORINGSSL_NISTP256_64BIT diff --git a/third_party/boringssl/kit/src/third_party/fiat/p256_32.h b/third_party/boringssl/kit/src/third_party/fiat/p256_32.h new file mode 100644 index 00000000..faaa0b04 --- /dev/null +++ b/third_party/boringssl/kit/src/third_party/fiat/p256_32.h @@ -0,0 +1,3220 @@ +/* Autogenerated */ +/* curve description: p256 */ +/* requested operations: (all) */ +/* m = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff (from "2^256 - 2^224 + 2^192 + 2^96 - 1") */ +/* machine_wordsize = 32 (from "32") */ +/* */ +/* NOTE: In addition to the bounds specified above each function, all */ +/* functions synthesized for this Montgomery arithmetic require the */ +/* input to be strictly less than the prime modulus (m), and also */ +/* require the input to be in the unique saturated representation. */ +/* All functions also ensure that these two properties are true of */ +/* return values. */ + +#include +typedef unsigned char fiat_p256_uint1; +typedef signed char fiat_p256_int1; + + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [0x0 ~> 0xffffffff] + * arg3: [0x0 ~> 0xffffffff] + * Output Bounds: + * out1: [0x0 ~> 0xffffffff] + * out2: [0x0 ~> 0x1] + */ +static void fiat_p256_addcarryx_u32(uint32_t* out1, fiat_p256_uint1* out2, fiat_p256_uint1 arg1, uint32_t arg2, uint32_t arg3) { + uint64_t x1 = ((arg1 + (uint64_t)arg2) + arg3); + uint32_t x2 = (uint32_t)(x1 & UINT32_C(0xffffffff)); + fiat_p256_uint1 x3 = (fiat_p256_uint1)(x1 >> 32); + *out1 = x2; + *out2 = x3; +} + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [0x0 ~> 0xffffffff] + * arg3: [0x0 ~> 0xffffffff] + * Output Bounds: + * out1: [0x0 ~> 0xffffffff] + * out2: [0x0 ~> 0x1] + */ +static void fiat_p256_subborrowx_u32(uint32_t* out1, fiat_p256_uint1* out2, fiat_p256_uint1 arg1, uint32_t arg2, uint32_t arg3) { + int64_t x1 = ((arg2 - (int64_t)arg1) - arg3); + fiat_p256_int1 x2 = (fiat_p256_int1)(x1 >> 32); + uint32_t x3 = (uint32_t)(x1 & UINT32_C(0xffffffff)); + *out1 = x3; + *out2 = (fiat_p256_uint1)(0x0 - x2); +} + +/* + * Input Bounds: + * arg1: [0x0 ~> 0xffffffff] + * arg2: [0x0 ~> 0xffffffff] + * Output Bounds: + * out1: [0x0 ~> 0xffffffff] + * out2: [0x0 ~> 0xffffffff] + */ +static void fiat_p256_mulx_u32(uint32_t* out1, uint32_t* out2, uint32_t arg1, uint32_t arg2) { + uint64_t x1 = ((uint64_t)arg1 * arg2); + uint32_t x2 = (uint32_t)(x1 & UINT32_C(0xffffffff)); + uint32_t x3 = (uint32_t)(x1 >> 32); + *out1 = x2; + *out2 = x3; +} + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [0x0 ~> 0xffffffff] + * arg3: [0x0 ~> 0xffffffff] + * Output Bounds: + * out1: [0x0 ~> 0xffffffff] + */ +static void fiat_p256_cmovznz_u32(uint32_t* out1, fiat_p256_uint1 arg1, uint32_t arg2, uint32_t arg3) { + fiat_p256_uint1 x1 = (!(!arg1)); + uint32_t x2 = ((fiat_p256_int1)(0x0 - x1) & UINT32_C(0xffffffff)); + uint32_t x3 = ((x2 & arg3) | ((~x2) & arg2)); + *out1 = x3; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + * arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + */ +static void fiat_p256_mul(uint32_t out1[8], const uint32_t arg1[8], const uint32_t arg2[8]) { + uint32_t x1 = (arg1[1]); + uint32_t x2 = (arg1[2]); + uint32_t x3 = (arg1[3]); + uint32_t x4 = (arg1[4]); + uint32_t x5 = (arg1[5]); + uint32_t x6 = (arg1[6]); + uint32_t x7 = (arg1[7]); + uint32_t x8 = (arg1[0]); + uint32_t x9; + uint32_t x10; + fiat_p256_mulx_u32(&x9, &x10, x8, (arg2[7])); + uint32_t x11; + uint32_t x12; + fiat_p256_mulx_u32(&x11, &x12, x8, (arg2[6])); + uint32_t x13; + uint32_t x14; + fiat_p256_mulx_u32(&x13, &x14, x8, (arg2[5])); + uint32_t x15; + uint32_t x16; + fiat_p256_mulx_u32(&x15, &x16, x8, (arg2[4])); + uint32_t x17; + uint32_t x18; + fiat_p256_mulx_u32(&x17, &x18, x8, (arg2[3])); + uint32_t x19; + uint32_t x20; + fiat_p256_mulx_u32(&x19, &x20, x8, (arg2[2])); + uint32_t x21; + uint32_t x22; + fiat_p256_mulx_u32(&x21, &x22, x8, (arg2[1])); + uint32_t x23; + uint32_t x24; + fiat_p256_mulx_u32(&x23, &x24, x8, (arg2[0])); + uint32_t x25; + fiat_p256_uint1 x26; + fiat_p256_addcarryx_u32(&x25, &x26, 0x0, x21, x24); + uint32_t x27; + fiat_p256_uint1 x28; + fiat_p256_addcarryx_u32(&x27, &x28, x26, x19, x22); + uint32_t x29; + fiat_p256_uint1 x30; + fiat_p256_addcarryx_u32(&x29, &x30, x28, x17, x20); + uint32_t x31; + fiat_p256_uint1 x32; + fiat_p256_addcarryx_u32(&x31, &x32, x30, x15, x18); + uint32_t x33; + fiat_p256_uint1 x34; + fiat_p256_addcarryx_u32(&x33, &x34, x32, x13, x16); + uint32_t x35; + fiat_p256_uint1 x36; + fiat_p256_addcarryx_u32(&x35, &x36, x34, x11, x14); + uint32_t x37; + fiat_p256_uint1 x38; + fiat_p256_addcarryx_u32(&x37, &x38, x36, x9, x12); + uint32_t x39; + fiat_p256_uint1 x40; + fiat_p256_addcarryx_u32(&x39, &x40, x38, 0x0, x10); + uint32_t x41; + uint32_t x42; + fiat_p256_mulx_u32(&x41, &x42, x23, UINT32_C(0xffffffff)); + uint32_t x43; + uint32_t x44; + fiat_p256_mulx_u32(&x43, &x44, x23, UINT32_C(0xffffffff)); + uint32_t x45; + uint32_t x46; + fiat_p256_mulx_u32(&x45, &x46, x23, UINT32_C(0xffffffff)); + uint32_t x47; + uint32_t x48; + fiat_p256_mulx_u32(&x47, &x48, x23, UINT32_C(0xffffffff)); + uint32_t x49; + fiat_p256_uint1 x50; + fiat_p256_addcarryx_u32(&x49, &x50, 0x0, x45, x48); + uint32_t x51; + fiat_p256_uint1 x52; + fiat_p256_addcarryx_u32(&x51, &x52, x50, x43, x46); + uint32_t x53; + fiat_p256_uint1 x54; + fiat_p256_addcarryx_u32(&x53, &x54, x52, 0x0, x44); + uint32_t x55; + fiat_p256_uint1 x56; + fiat_p256_addcarryx_u32(&x55, &x56, 0x0, x47, x23); + uint32_t x57; + fiat_p256_uint1 x58; + fiat_p256_addcarryx_u32(&x57, &x58, x56, x49, x25); + uint32_t x59; + fiat_p256_uint1 x60; + fiat_p256_addcarryx_u32(&x59, &x60, x58, x51, x27); + uint32_t x61; + fiat_p256_uint1 x62; + fiat_p256_addcarryx_u32(&x61, &x62, x60, x53, x29); + uint32_t x63; + fiat_p256_uint1 x64; + fiat_p256_addcarryx_u32(&x63, &x64, x62, 0x0, x31); + uint32_t x65; + fiat_p256_uint1 x66; + fiat_p256_addcarryx_u32(&x65, &x66, x64, 0x0, x33); + uint32_t x67; + fiat_p256_uint1 x68; + fiat_p256_addcarryx_u32(&x67, &x68, x66, x23, x35); + uint32_t x69; + fiat_p256_uint1 x70; + fiat_p256_addcarryx_u32(&x69, &x70, x68, x41, x37); + uint32_t x71; + fiat_p256_uint1 x72; + fiat_p256_addcarryx_u32(&x71, &x72, x70, x42, x39); + uint32_t x73; + fiat_p256_uint1 x74; + fiat_p256_addcarryx_u32(&x73, &x74, x72, 0x0, 0x0); + uint32_t x75; + uint32_t x76; + fiat_p256_mulx_u32(&x75, &x76, x1, (arg2[7])); + uint32_t x77; + uint32_t x78; + fiat_p256_mulx_u32(&x77, &x78, x1, (arg2[6])); + uint32_t x79; + uint32_t x80; + fiat_p256_mulx_u32(&x79, &x80, x1, (arg2[5])); + uint32_t x81; + uint32_t x82; + fiat_p256_mulx_u32(&x81, &x82, x1, (arg2[4])); + uint32_t x83; + uint32_t x84; + fiat_p256_mulx_u32(&x83, &x84, x1, (arg2[3])); + uint32_t x85; + uint32_t x86; + fiat_p256_mulx_u32(&x85, &x86, x1, (arg2[2])); + uint32_t x87; + uint32_t x88; + fiat_p256_mulx_u32(&x87, &x88, x1, (arg2[1])); + uint32_t x89; + uint32_t x90; + fiat_p256_mulx_u32(&x89, &x90, x1, (arg2[0])); + uint32_t x91; + fiat_p256_uint1 x92; + fiat_p256_addcarryx_u32(&x91, &x92, 0x0, x87, x90); + uint32_t x93; + fiat_p256_uint1 x94; + fiat_p256_addcarryx_u32(&x93, &x94, x92, x85, x88); + uint32_t x95; + fiat_p256_uint1 x96; + fiat_p256_addcarryx_u32(&x95, &x96, x94, x83, x86); + uint32_t x97; + fiat_p256_uint1 x98; + fiat_p256_addcarryx_u32(&x97, &x98, x96, x81, x84); + uint32_t x99; + fiat_p256_uint1 x100; + fiat_p256_addcarryx_u32(&x99, &x100, x98, x79, x82); + uint32_t x101; + fiat_p256_uint1 x102; + fiat_p256_addcarryx_u32(&x101, &x102, x100, x77, x80); + uint32_t x103; + fiat_p256_uint1 x104; + fiat_p256_addcarryx_u32(&x103, &x104, x102, x75, x78); + uint32_t x105; + fiat_p256_uint1 x106; + fiat_p256_addcarryx_u32(&x105, &x106, x104, 0x0, x76); + uint32_t x107; + fiat_p256_uint1 x108; + fiat_p256_addcarryx_u32(&x107, &x108, 0x0, x89, x57); + uint32_t x109; + fiat_p256_uint1 x110; + fiat_p256_addcarryx_u32(&x109, &x110, x108, x91, x59); + uint32_t x111; + fiat_p256_uint1 x112; + fiat_p256_addcarryx_u32(&x111, &x112, x110, x93, x61); + uint32_t x113; + fiat_p256_uint1 x114; + fiat_p256_addcarryx_u32(&x113, &x114, x112, x95, x63); + uint32_t x115; + fiat_p256_uint1 x116; + fiat_p256_addcarryx_u32(&x115, &x116, x114, x97, x65); + uint32_t x117; + fiat_p256_uint1 x118; + fiat_p256_addcarryx_u32(&x117, &x118, x116, x99, x67); + uint32_t x119; + fiat_p256_uint1 x120; + fiat_p256_addcarryx_u32(&x119, &x120, x118, x101, x69); + uint32_t x121; + fiat_p256_uint1 x122; + fiat_p256_addcarryx_u32(&x121, &x122, x120, x103, x71); + uint32_t x123; + fiat_p256_uint1 x124; + fiat_p256_addcarryx_u32(&x123, &x124, x122, x105, (fiat_p256_uint1)x73); + uint32_t x125; + uint32_t x126; + fiat_p256_mulx_u32(&x125, &x126, x107, UINT32_C(0xffffffff)); + uint32_t x127; + uint32_t x128; + fiat_p256_mulx_u32(&x127, &x128, x107, UINT32_C(0xffffffff)); + uint32_t x129; + uint32_t x130; + fiat_p256_mulx_u32(&x129, &x130, x107, UINT32_C(0xffffffff)); + uint32_t x131; + uint32_t x132; + fiat_p256_mulx_u32(&x131, &x132, x107, UINT32_C(0xffffffff)); + uint32_t x133; + fiat_p256_uint1 x134; + fiat_p256_addcarryx_u32(&x133, &x134, 0x0, x129, x132); + uint32_t x135; + fiat_p256_uint1 x136; + fiat_p256_addcarryx_u32(&x135, &x136, x134, x127, x130); + uint32_t x137; + fiat_p256_uint1 x138; + fiat_p256_addcarryx_u32(&x137, &x138, x136, 0x0, x128); + uint32_t x139; + fiat_p256_uint1 x140; + fiat_p256_addcarryx_u32(&x139, &x140, 0x0, x131, x107); + uint32_t x141; + fiat_p256_uint1 x142; + fiat_p256_addcarryx_u32(&x141, &x142, x140, x133, x109); + uint32_t x143; + fiat_p256_uint1 x144; + fiat_p256_addcarryx_u32(&x143, &x144, x142, x135, x111); + uint32_t x145; + fiat_p256_uint1 x146; + fiat_p256_addcarryx_u32(&x145, &x146, x144, x137, x113); + uint32_t x147; + fiat_p256_uint1 x148; + fiat_p256_addcarryx_u32(&x147, &x148, x146, 0x0, x115); + uint32_t x149; + fiat_p256_uint1 x150; + fiat_p256_addcarryx_u32(&x149, &x150, x148, 0x0, x117); + uint32_t x151; + fiat_p256_uint1 x152; + fiat_p256_addcarryx_u32(&x151, &x152, x150, x107, x119); + uint32_t x153; + fiat_p256_uint1 x154; + fiat_p256_addcarryx_u32(&x153, &x154, x152, x125, x121); + uint32_t x155; + fiat_p256_uint1 x156; + fiat_p256_addcarryx_u32(&x155, &x156, x154, x126, x123); + uint32_t x157; + fiat_p256_uint1 x158; + fiat_p256_addcarryx_u32(&x157, &x158, x156, 0x0, x124); + uint32_t x159; + uint32_t x160; + fiat_p256_mulx_u32(&x159, &x160, x2, (arg2[7])); + uint32_t x161; + uint32_t x162; + fiat_p256_mulx_u32(&x161, &x162, x2, (arg2[6])); + uint32_t x163; + uint32_t x164; + fiat_p256_mulx_u32(&x163, &x164, x2, (arg2[5])); + uint32_t x165; + uint32_t x166; + fiat_p256_mulx_u32(&x165, &x166, x2, (arg2[4])); + uint32_t x167; + uint32_t x168; + fiat_p256_mulx_u32(&x167, &x168, x2, (arg2[3])); + uint32_t x169; + uint32_t x170; + fiat_p256_mulx_u32(&x169, &x170, x2, (arg2[2])); + uint32_t x171; + uint32_t x172; + fiat_p256_mulx_u32(&x171, &x172, x2, (arg2[1])); + uint32_t x173; + uint32_t x174; + fiat_p256_mulx_u32(&x173, &x174, x2, (arg2[0])); + uint32_t x175; + fiat_p256_uint1 x176; + fiat_p256_addcarryx_u32(&x175, &x176, 0x0, x171, x174); + uint32_t x177; + fiat_p256_uint1 x178; + fiat_p256_addcarryx_u32(&x177, &x178, x176, x169, x172); + uint32_t x179; + fiat_p256_uint1 x180; + fiat_p256_addcarryx_u32(&x179, &x180, x178, x167, x170); + uint32_t x181; + fiat_p256_uint1 x182; + fiat_p256_addcarryx_u32(&x181, &x182, x180, x165, x168); + uint32_t x183; + fiat_p256_uint1 x184; + fiat_p256_addcarryx_u32(&x183, &x184, x182, x163, x166); + uint32_t x185; + fiat_p256_uint1 x186; + fiat_p256_addcarryx_u32(&x185, &x186, x184, x161, x164); + uint32_t x187; + fiat_p256_uint1 x188; + fiat_p256_addcarryx_u32(&x187, &x188, x186, x159, x162); + uint32_t x189; + fiat_p256_uint1 x190; + fiat_p256_addcarryx_u32(&x189, &x190, x188, 0x0, x160); + uint32_t x191; + fiat_p256_uint1 x192; + fiat_p256_addcarryx_u32(&x191, &x192, 0x0, x173, x141); + uint32_t x193; + fiat_p256_uint1 x194; + fiat_p256_addcarryx_u32(&x193, &x194, x192, x175, x143); + uint32_t x195; + fiat_p256_uint1 x196; + fiat_p256_addcarryx_u32(&x195, &x196, x194, x177, x145); + uint32_t x197; + fiat_p256_uint1 x198; + fiat_p256_addcarryx_u32(&x197, &x198, x196, x179, x147); + uint32_t x199; + fiat_p256_uint1 x200; + fiat_p256_addcarryx_u32(&x199, &x200, x198, x181, x149); + uint32_t x201; + fiat_p256_uint1 x202; + fiat_p256_addcarryx_u32(&x201, &x202, x200, x183, x151); + uint32_t x203; + fiat_p256_uint1 x204; + fiat_p256_addcarryx_u32(&x203, &x204, x202, x185, x153); + uint32_t x205; + fiat_p256_uint1 x206; + fiat_p256_addcarryx_u32(&x205, &x206, x204, x187, x155); + uint32_t x207; + fiat_p256_uint1 x208; + fiat_p256_addcarryx_u32(&x207, &x208, x206, x189, x157); + uint32_t x209; + uint32_t x210; + fiat_p256_mulx_u32(&x209, &x210, x191, UINT32_C(0xffffffff)); + uint32_t x211; + uint32_t x212; + fiat_p256_mulx_u32(&x211, &x212, x191, UINT32_C(0xffffffff)); + uint32_t x213; + uint32_t x214; + fiat_p256_mulx_u32(&x213, &x214, x191, UINT32_C(0xffffffff)); + uint32_t x215; + uint32_t x216; + fiat_p256_mulx_u32(&x215, &x216, x191, UINT32_C(0xffffffff)); + uint32_t x217; + fiat_p256_uint1 x218; + fiat_p256_addcarryx_u32(&x217, &x218, 0x0, x213, x216); + uint32_t x219; + fiat_p256_uint1 x220; + fiat_p256_addcarryx_u32(&x219, &x220, x218, x211, x214); + uint32_t x221; + fiat_p256_uint1 x222; + fiat_p256_addcarryx_u32(&x221, &x222, x220, 0x0, x212); + uint32_t x223; + fiat_p256_uint1 x224; + fiat_p256_addcarryx_u32(&x223, &x224, 0x0, x215, x191); + uint32_t x225; + fiat_p256_uint1 x226; + fiat_p256_addcarryx_u32(&x225, &x226, x224, x217, x193); + uint32_t x227; + fiat_p256_uint1 x228; + fiat_p256_addcarryx_u32(&x227, &x228, x226, x219, x195); + uint32_t x229; + fiat_p256_uint1 x230; + fiat_p256_addcarryx_u32(&x229, &x230, x228, x221, x197); + uint32_t x231; + fiat_p256_uint1 x232; + fiat_p256_addcarryx_u32(&x231, &x232, x230, 0x0, x199); + uint32_t x233; + fiat_p256_uint1 x234; + fiat_p256_addcarryx_u32(&x233, &x234, x232, 0x0, x201); + uint32_t x235; + fiat_p256_uint1 x236; + fiat_p256_addcarryx_u32(&x235, &x236, x234, x191, x203); + uint32_t x237; + fiat_p256_uint1 x238; + fiat_p256_addcarryx_u32(&x237, &x238, x236, x209, x205); + uint32_t x239; + fiat_p256_uint1 x240; + fiat_p256_addcarryx_u32(&x239, &x240, x238, x210, x207); + uint32_t x241; + fiat_p256_uint1 x242; + fiat_p256_addcarryx_u32(&x241, &x242, x240, 0x0, x208); + uint32_t x243; + uint32_t x244; + fiat_p256_mulx_u32(&x243, &x244, x3, (arg2[7])); + uint32_t x245; + uint32_t x246; + fiat_p256_mulx_u32(&x245, &x246, x3, (arg2[6])); + uint32_t x247; + uint32_t x248; + fiat_p256_mulx_u32(&x247, &x248, x3, (arg2[5])); + uint32_t x249; + uint32_t x250; + fiat_p256_mulx_u32(&x249, &x250, x3, (arg2[4])); + uint32_t x251; + uint32_t x252; + fiat_p256_mulx_u32(&x251, &x252, x3, (arg2[3])); + uint32_t x253; + uint32_t x254; + fiat_p256_mulx_u32(&x253, &x254, x3, (arg2[2])); + uint32_t x255; + uint32_t x256; + fiat_p256_mulx_u32(&x255, &x256, x3, (arg2[1])); + uint32_t x257; + uint32_t x258; + fiat_p256_mulx_u32(&x257, &x258, x3, (arg2[0])); + uint32_t x259; + fiat_p256_uint1 x260; + fiat_p256_addcarryx_u32(&x259, &x260, 0x0, x255, x258); + uint32_t x261; + fiat_p256_uint1 x262; + fiat_p256_addcarryx_u32(&x261, &x262, x260, x253, x256); + uint32_t x263; + fiat_p256_uint1 x264; + fiat_p256_addcarryx_u32(&x263, &x264, x262, x251, x254); + uint32_t x265; + fiat_p256_uint1 x266; + fiat_p256_addcarryx_u32(&x265, &x266, x264, x249, x252); + uint32_t x267; + fiat_p256_uint1 x268; + fiat_p256_addcarryx_u32(&x267, &x268, x266, x247, x250); + uint32_t x269; + fiat_p256_uint1 x270; + fiat_p256_addcarryx_u32(&x269, &x270, x268, x245, x248); + uint32_t x271; + fiat_p256_uint1 x272; + fiat_p256_addcarryx_u32(&x271, &x272, x270, x243, x246); + uint32_t x273; + fiat_p256_uint1 x274; + fiat_p256_addcarryx_u32(&x273, &x274, x272, 0x0, x244); + uint32_t x275; + fiat_p256_uint1 x276; + fiat_p256_addcarryx_u32(&x275, &x276, 0x0, x257, x225); + uint32_t x277; + fiat_p256_uint1 x278; + fiat_p256_addcarryx_u32(&x277, &x278, x276, x259, x227); + uint32_t x279; + fiat_p256_uint1 x280; + fiat_p256_addcarryx_u32(&x279, &x280, x278, x261, x229); + uint32_t x281; + fiat_p256_uint1 x282; + fiat_p256_addcarryx_u32(&x281, &x282, x280, x263, x231); + uint32_t x283; + fiat_p256_uint1 x284; + fiat_p256_addcarryx_u32(&x283, &x284, x282, x265, x233); + uint32_t x285; + fiat_p256_uint1 x286; + fiat_p256_addcarryx_u32(&x285, &x286, x284, x267, x235); + uint32_t x287; + fiat_p256_uint1 x288; + fiat_p256_addcarryx_u32(&x287, &x288, x286, x269, x237); + uint32_t x289; + fiat_p256_uint1 x290; + fiat_p256_addcarryx_u32(&x289, &x290, x288, x271, x239); + uint32_t x291; + fiat_p256_uint1 x292; + fiat_p256_addcarryx_u32(&x291, &x292, x290, x273, x241); + uint32_t x293; + uint32_t x294; + fiat_p256_mulx_u32(&x293, &x294, x275, UINT32_C(0xffffffff)); + uint32_t x295; + uint32_t x296; + fiat_p256_mulx_u32(&x295, &x296, x275, UINT32_C(0xffffffff)); + uint32_t x297; + uint32_t x298; + fiat_p256_mulx_u32(&x297, &x298, x275, UINT32_C(0xffffffff)); + uint32_t x299; + uint32_t x300; + fiat_p256_mulx_u32(&x299, &x300, x275, UINT32_C(0xffffffff)); + uint32_t x301; + fiat_p256_uint1 x302; + fiat_p256_addcarryx_u32(&x301, &x302, 0x0, x297, x300); + uint32_t x303; + fiat_p256_uint1 x304; + fiat_p256_addcarryx_u32(&x303, &x304, x302, x295, x298); + uint32_t x305; + fiat_p256_uint1 x306; + fiat_p256_addcarryx_u32(&x305, &x306, x304, 0x0, x296); + uint32_t x307; + fiat_p256_uint1 x308; + fiat_p256_addcarryx_u32(&x307, &x308, 0x0, x299, x275); + uint32_t x309; + fiat_p256_uint1 x310; + fiat_p256_addcarryx_u32(&x309, &x310, x308, x301, x277); + uint32_t x311; + fiat_p256_uint1 x312; + fiat_p256_addcarryx_u32(&x311, &x312, x310, x303, x279); + uint32_t x313; + fiat_p256_uint1 x314; + fiat_p256_addcarryx_u32(&x313, &x314, x312, x305, x281); + uint32_t x315; + fiat_p256_uint1 x316; + fiat_p256_addcarryx_u32(&x315, &x316, x314, 0x0, x283); + uint32_t x317; + fiat_p256_uint1 x318; + fiat_p256_addcarryx_u32(&x317, &x318, x316, 0x0, x285); + uint32_t x319; + fiat_p256_uint1 x320; + fiat_p256_addcarryx_u32(&x319, &x320, x318, x275, x287); + uint32_t x321; + fiat_p256_uint1 x322; + fiat_p256_addcarryx_u32(&x321, &x322, x320, x293, x289); + uint32_t x323; + fiat_p256_uint1 x324; + fiat_p256_addcarryx_u32(&x323, &x324, x322, x294, x291); + uint32_t x325; + fiat_p256_uint1 x326; + fiat_p256_addcarryx_u32(&x325, &x326, x324, 0x0, x292); + uint32_t x327; + uint32_t x328; + fiat_p256_mulx_u32(&x327, &x328, x4, (arg2[7])); + uint32_t x329; + uint32_t x330; + fiat_p256_mulx_u32(&x329, &x330, x4, (arg2[6])); + uint32_t x331; + uint32_t x332; + fiat_p256_mulx_u32(&x331, &x332, x4, (arg2[5])); + uint32_t x333; + uint32_t x334; + fiat_p256_mulx_u32(&x333, &x334, x4, (arg2[4])); + uint32_t x335; + uint32_t x336; + fiat_p256_mulx_u32(&x335, &x336, x4, (arg2[3])); + uint32_t x337; + uint32_t x338; + fiat_p256_mulx_u32(&x337, &x338, x4, (arg2[2])); + uint32_t x339; + uint32_t x340; + fiat_p256_mulx_u32(&x339, &x340, x4, (arg2[1])); + uint32_t x341; + uint32_t x342; + fiat_p256_mulx_u32(&x341, &x342, x4, (arg2[0])); + uint32_t x343; + fiat_p256_uint1 x344; + fiat_p256_addcarryx_u32(&x343, &x344, 0x0, x339, x342); + uint32_t x345; + fiat_p256_uint1 x346; + fiat_p256_addcarryx_u32(&x345, &x346, x344, x337, x340); + uint32_t x347; + fiat_p256_uint1 x348; + fiat_p256_addcarryx_u32(&x347, &x348, x346, x335, x338); + uint32_t x349; + fiat_p256_uint1 x350; + fiat_p256_addcarryx_u32(&x349, &x350, x348, x333, x336); + uint32_t x351; + fiat_p256_uint1 x352; + fiat_p256_addcarryx_u32(&x351, &x352, x350, x331, x334); + uint32_t x353; + fiat_p256_uint1 x354; + fiat_p256_addcarryx_u32(&x353, &x354, x352, x329, x332); + uint32_t x355; + fiat_p256_uint1 x356; + fiat_p256_addcarryx_u32(&x355, &x356, x354, x327, x330); + uint32_t x357; + fiat_p256_uint1 x358; + fiat_p256_addcarryx_u32(&x357, &x358, x356, 0x0, x328); + uint32_t x359; + fiat_p256_uint1 x360; + fiat_p256_addcarryx_u32(&x359, &x360, 0x0, x341, x309); + uint32_t x361; + fiat_p256_uint1 x362; + fiat_p256_addcarryx_u32(&x361, &x362, x360, x343, x311); + uint32_t x363; + fiat_p256_uint1 x364; + fiat_p256_addcarryx_u32(&x363, &x364, x362, x345, x313); + uint32_t x365; + fiat_p256_uint1 x366; + fiat_p256_addcarryx_u32(&x365, &x366, x364, x347, x315); + uint32_t x367; + fiat_p256_uint1 x368; + fiat_p256_addcarryx_u32(&x367, &x368, x366, x349, x317); + uint32_t x369; + fiat_p256_uint1 x370; + fiat_p256_addcarryx_u32(&x369, &x370, x368, x351, x319); + uint32_t x371; + fiat_p256_uint1 x372; + fiat_p256_addcarryx_u32(&x371, &x372, x370, x353, x321); + uint32_t x373; + fiat_p256_uint1 x374; + fiat_p256_addcarryx_u32(&x373, &x374, x372, x355, x323); + uint32_t x375; + fiat_p256_uint1 x376; + fiat_p256_addcarryx_u32(&x375, &x376, x374, x357, x325); + uint32_t x377; + uint32_t x378; + fiat_p256_mulx_u32(&x377, &x378, x359, UINT32_C(0xffffffff)); + uint32_t x379; + uint32_t x380; + fiat_p256_mulx_u32(&x379, &x380, x359, UINT32_C(0xffffffff)); + uint32_t x381; + uint32_t x382; + fiat_p256_mulx_u32(&x381, &x382, x359, UINT32_C(0xffffffff)); + uint32_t x383; + uint32_t x384; + fiat_p256_mulx_u32(&x383, &x384, x359, UINT32_C(0xffffffff)); + uint32_t x385; + fiat_p256_uint1 x386; + fiat_p256_addcarryx_u32(&x385, &x386, 0x0, x381, x384); + uint32_t x387; + fiat_p256_uint1 x388; + fiat_p256_addcarryx_u32(&x387, &x388, x386, x379, x382); + uint32_t x389; + fiat_p256_uint1 x390; + fiat_p256_addcarryx_u32(&x389, &x390, x388, 0x0, x380); + uint32_t x391; + fiat_p256_uint1 x392; + fiat_p256_addcarryx_u32(&x391, &x392, 0x0, x383, x359); + uint32_t x393; + fiat_p256_uint1 x394; + fiat_p256_addcarryx_u32(&x393, &x394, x392, x385, x361); + uint32_t x395; + fiat_p256_uint1 x396; + fiat_p256_addcarryx_u32(&x395, &x396, x394, x387, x363); + uint32_t x397; + fiat_p256_uint1 x398; + fiat_p256_addcarryx_u32(&x397, &x398, x396, x389, x365); + uint32_t x399; + fiat_p256_uint1 x400; + fiat_p256_addcarryx_u32(&x399, &x400, x398, 0x0, x367); + uint32_t x401; + fiat_p256_uint1 x402; + fiat_p256_addcarryx_u32(&x401, &x402, x400, 0x0, x369); + uint32_t x403; + fiat_p256_uint1 x404; + fiat_p256_addcarryx_u32(&x403, &x404, x402, x359, x371); + uint32_t x405; + fiat_p256_uint1 x406; + fiat_p256_addcarryx_u32(&x405, &x406, x404, x377, x373); + uint32_t x407; + fiat_p256_uint1 x408; + fiat_p256_addcarryx_u32(&x407, &x408, x406, x378, x375); + uint32_t x409; + fiat_p256_uint1 x410; + fiat_p256_addcarryx_u32(&x409, &x410, x408, 0x0, x376); + uint32_t x411; + uint32_t x412; + fiat_p256_mulx_u32(&x411, &x412, x5, (arg2[7])); + uint32_t x413; + uint32_t x414; + fiat_p256_mulx_u32(&x413, &x414, x5, (arg2[6])); + uint32_t x415; + uint32_t x416; + fiat_p256_mulx_u32(&x415, &x416, x5, (arg2[5])); + uint32_t x417; + uint32_t x418; + fiat_p256_mulx_u32(&x417, &x418, x5, (arg2[4])); + uint32_t x419; + uint32_t x420; + fiat_p256_mulx_u32(&x419, &x420, x5, (arg2[3])); + uint32_t x421; + uint32_t x422; + fiat_p256_mulx_u32(&x421, &x422, x5, (arg2[2])); + uint32_t x423; + uint32_t x424; + fiat_p256_mulx_u32(&x423, &x424, x5, (arg2[1])); + uint32_t x425; + uint32_t x426; + fiat_p256_mulx_u32(&x425, &x426, x5, (arg2[0])); + uint32_t x427; + fiat_p256_uint1 x428; + fiat_p256_addcarryx_u32(&x427, &x428, 0x0, x423, x426); + uint32_t x429; + fiat_p256_uint1 x430; + fiat_p256_addcarryx_u32(&x429, &x430, x428, x421, x424); + uint32_t x431; + fiat_p256_uint1 x432; + fiat_p256_addcarryx_u32(&x431, &x432, x430, x419, x422); + uint32_t x433; + fiat_p256_uint1 x434; + fiat_p256_addcarryx_u32(&x433, &x434, x432, x417, x420); + uint32_t x435; + fiat_p256_uint1 x436; + fiat_p256_addcarryx_u32(&x435, &x436, x434, x415, x418); + uint32_t x437; + fiat_p256_uint1 x438; + fiat_p256_addcarryx_u32(&x437, &x438, x436, x413, x416); + uint32_t x439; + fiat_p256_uint1 x440; + fiat_p256_addcarryx_u32(&x439, &x440, x438, x411, x414); + uint32_t x441; + fiat_p256_uint1 x442; + fiat_p256_addcarryx_u32(&x441, &x442, x440, 0x0, x412); + uint32_t x443; + fiat_p256_uint1 x444; + fiat_p256_addcarryx_u32(&x443, &x444, 0x0, x425, x393); + uint32_t x445; + fiat_p256_uint1 x446; + fiat_p256_addcarryx_u32(&x445, &x446, x444, x427, x395); + uint32_t x447; + fiat_p256_uint1 x448; + fiat_p256_addcarryx_u32(&x447, &x448, x446, x429, x397); + uint32_t x449; + fiat_p256_uint1 x450; + fiat_p256_addcarryx_u32(&x449, &x450, x448, x431, x399); + uint32_t x451; + fiat_p256_uint1 x452; + fiat_p256_addcarryx_u32(&x451, &x452, x450, x433, x401); + uint32_t x453; + fiat_p256_uint1 x454; + fiat_p256_addcarryx_u32(&x453, &x454, x452, x435, x403); + uint32_t x455; + fiat_p256_uint1 x456; + fiat_p256_addcarryx_u32(&x455, &x456, x454, x437, x405); + uint32_t x457; + fiat_p256_uint1 x458; + fiat_p256_addcarryx_u32(&x457, &x458, x456, x439, x407); + uint32_t x459; + fiat_p256_uint1 x460; + fiat_p256_addcarryx_u32(&x459, &x460, x458, x441, x409); + uint32_t x461; + uint32_t x462; + fiat_p256_mulx_u32(&x461, &x462, x443, UINT32_C(0xffffffff)); + uint32_t x463; + uint32_t x464; + fiat_p256_mulx_u32(&x463, &x464, x443, UINT32_C(0xffffffff)); + uint32_t x465; + uint32_t x466; + fiat_p256_mulx_u32(&x465, &x466, x443, UINT32_C(0xffffffff)); + uint32_t x467; + uint32_t x468; + fiat_p256_mulx_u32(&x467, &x468, x443, UINT32_C(0xffffffff)); + uint32_t x469; + fiat_p256_uint1 x470; + fiat_p256_addcarryx_u32(&x469, &x470, 0x0, x465, x468); + uint32_t x471; + fiat_p256_uint1 x472; + fiat_p256_addcarryx_u32(&x471, &x472, x470, x463, x466); + uint32_t x473; + fiat_p256_uint1 x474; + fiat_p256_addcarryx_u32(&x473, &x474, x472, 0x0, x464); + uint32_t x475; + fiat_p256_uint1 x476; + fiat_p256_addcarryx_u32(&x475, &x476, 0x0, x467, x443); + uint32_t x477; + fiat_p256_uint1 x478; + fiat_p256_addcarryx_u32(&x477, &x478, x476, x469, x445); + uint32_t x479; + fiat_p256_uint1 x480; + fiat_p256_addcarryx_u32(&x479, &x480, x478, x471, x447); + uint32_t x481; + fiat_p256_uint1 x482; + fiat_p256_addcarryx_u32(&x481, &x482, x480, x473, x449); + uint32_t x483; + fiat_p256_uint1 x484; + fiat_p256_addcarryx_u32(&x483, &x484, x482, 0x0, x451); + uint32_t x485; + fiat_p256_uint1 x486; + fiat_p256_addcarryx_u32(&x485, &x486, x484, 0x0, x453); + uint32_t x487; + fiat_p256_uint1 x488; + fiat_p256_addcarryx_u32(&x487, &x488, x486, x443, x455); + uint32_t x489; + fiat_p256_uint1 x490; + fiat_p256_addcarryx_u32(&x489, &x490, x488, x461, x457); + uint32_t x491; + fiat_p256_uint1 x492; + fiat_p256_addcarryx_u32(&x491, &x492, x490, x462, x459); + uint32_t x493; + fiat_p256_uint1 x494; + fiat_p256_addcarryx_u32(&x493, &x494, x492, 0x0, x460); + uint32_t x495; + uint32_t x496; + fiat_p256_mulx_u32(&x495, &x496, x6, (arg2[7])); + uint32_t x497; + uint32_t x498; + fiat_p256_mulx_u32(&x497, &x498, x6, (arg2[6])); + uint32_t x499; + uint32_t x500; + fiat_p256_mulx_u32(&x499, &x500, x6, (arg2[5])); + uint32_t x501; + uint32_t x502; + fiat_p256_mulx_u32(&x501, &x502, x6, (arg2[4])); + uint32_t x503; + uint32_t x504; + fiat_p256_mulx_u32(&x503, &x504, x6, (arg2[3])); + uint32_t x505; + uint32_t x506; + fiat_p256_mulx_u32(&x505, &x506, x6, (arg2[2])); + uint32_t x507; + uint32_t x508; + fiat_p256_mulx_u32(&x507, &x508, x6, (arg2[1])); + uint32_t x509; + uint32_t x510; + fiat_p256_mulx_u32(&x509, &x510, x6, (arg2[0])); + uint32_t x511; + fiat_p256_uint1 x512; + fiat_p256_addcarryx_u32(&x511, &x512, 0x0, x507, x510); + uint32_t x513; + fiat_p256_uint1 x514; + fiat_p256_addcarryx_u32(&x513, &x514, x512, x505, x508); + uint32_t x515; + fiat_p256_uint1 x516; + fiat_p256_addcarryx_u32(&x515, &x516, x514, x503, x506); + uint32_t x517; + fiat_p256_uint1 x518; + fiat_p256_addcarryx_u32(&x517, &x518, x516, x501, x504); + uint32_t x519; + fiat_p256_uint1 x520; + fiat_p256_addcarryx_u32(&x519, &x520, x518, x499, x502); + uint32_t x521; + fiat_p256_uint1 x522; + fiat_p256_addcarryx_u32(&x521, &x522, x520, x497, x500); + uint32_t x523; + fiat_p256_uint1 x524; + fiat_p256_addcarryx_u32(&x523, &x524, x522, x495, x498); + uint32_t x525; + fiat_p256_uint1 x526; + fiat_p256_addcarryx_u32(&x525, &x526, x524, 0x0, x496); + uint32_t x527; + fiat_p256_uint1 x528; + fiat_p256_addcarryx_u32(&x527, &x528, 0x0, x509, x477); + uint32_t x529; + fiat_p256_uint1 x530; + fiat_p256_addcarryx_u32(&x529, &x530, x528, x511, x479); + uint32_t x531; + fiat_p256_uint1 x532; + fiat_p256_addcarryx_u32(&x531, &x532, x530, x513, x481); + uint32_t x533; + fiat_p256_uint1 x534; + fiat_p256_addcarryx_u32(&x533, &x534, x532, x515, x483); + uint32_t x535; + fiat_p256_uint1 x536; + fiat_p256_addcarryx_u32(&x535, &x536, x534, x517, x485); + uint32_t x537; + fiat_p256_uint1 x538; + fiat_p256_addcarryx_u32(&x537, &x538, x536, x519, x487); + uint32_t x539; + fiat_p256_uint1 x540; + fiat_p256_addcarryx_u32(&x539, &x540, x538, x521, x489); + uint32_t x541; + fiat_p256_uint1 x542; + fiat_p256_addcarryx_u32(&x541, &x542, x540, x523, x491); + uint32_t x543; + fiat_p256_uint1 x544; + fiat_p256_addcarryx_u32(&x543, &x544, x542, x525, x493); + uint32_t x545; + uint32_t x546; + fiat_p256_mulx_u32(&x545, &x546, x527, UINT32_C(0xffffffff)); + uint32_t x547; + uint32_t x548; + fiat_p256_mulx_u32(&x547, &x548, x527, UINT32_C(0xffffffff)); + uint32_t x549; + uint32_t x550; + fiat_p256_mulx_u32(&x549, &x550, x527, UINT32_C(0xffffffff)); + uint32_t x551; + uint32_t x552; + fiat_p256_mulx_u32(&x551, &x552, x527, UINT32_C(0xffffffff)); + uint32_t x553; + fiat_p256_uint1 x554; + fiat_p256_addcarryx_u32(&x553, &x554, 0x0, x549, x552); + uint32_t x555; + fiat_p256_uint1 x556; + fiat_p256_addcarryx_u32(&x555, &x556, x554, x547, x550); + uint32_t x557; + fiat_p256_uint1 x558; + fiat_p256_addcarryx_u32(&x557, &x558, x556, 0x0, x548); + uint32_t x559; + fiat_p256_uint1 x560; + fiat_p256_addcarryx_u32(&x559, &x560, 0x0, x551, x527); + uint32_t x561; + fiat_p256_uint1 x562; + fiat_p256_addcarryx_u32(&x561, &x562, x560, x553, x529); + uint32_t x563; + fiat_p256_uint1 x564; + fiat_p256_addcarryx_u32(&x563, &x564, x562, x555, x531); + uint32_t x565; + fiat_p256_uint1 x566; + fiat_p256_addcarryx_u32(&x565, &x566, x564, x557, x533); + uint32_t x567; + fiat_p256_uint1 x568; + fiat_p256_addcarryx_u32(&x567, &x568, x566, 0x0, x535); + uint32_t x569; + fiat_p256_uint1 x570; + fiat_p256_addcarryx_u32(&x569, &x570, x568, 0x0, x537); + uint32_t x571; + fiat_p256_uint1 x572; + fiat_p256_addcarryx_u32(&x571, &x572, x570, x527, x539); + uint32_t x573; + fiat_p256_uint1 x574; + fiat_p256_addcarryx_u32(&x573, &x574, x572, x545, x541); + uint32_t x575; + fiat_p256_uint1 x576; + fiat_p256_addcarryx_u32(&x575, &x576, x574, x546, x543); + uint32_t x577; + fiat_p256_uint1 x578; + fiat_p256_addcarryx_u32(&x577, &x578, x576, 0x0, x544); + uint32_t x579; + uint32_t x580; + fiat_p256_mulx_u32(&x579, &x580, x7, (arg2[7])); + uint32_t x581; + uint32_t x582; + fiat_p256_mulx_u32(&x581, &x582, x7, (arg2[6])); + uint32_t x583; + uint32_t x584; + fiat_p256_mulx_u32(&x583, &x584, x7, (arg2[5])); + uint32_t x585; + uint32_t x586; + fiat_p256_mulx_u32(&x585, &x586, x7, (arg2[4])); + uint32_t x587; + uint32_t x588; + fiat_p256_mulx_u32(&x587, &x588, x7, (arg2[3])); + uint32_t x589; + uint32_t x590; + fiat_p256_mulx_u32(&x589, &x590, x7, (arg2[2])); + uint32_t x591; + uint32_t x592; + fiat_p256_mulx_u32(&x591, &x592, x7, (arg2[1])); + uint32_t x593; + uint32_t x594; + fiat_p256_mulx_u32(&x593, &x594, x7, (arg2[0])); + uint32_t x595; + fiat_p256_uint1 x596; + fiat_p256_addcarryx_u32(&x595, &x596, 0x0, x591, x594); + uint32_t x597; + fiat_p256_uint1 x598; + fiat_p256_addcarryx_u32(&x597, &x598, x596, x589, x592); + uint32_t x599; + fiat_p256_uint1 x600; + fiat_p256_addcarryx_u32(&x599, &x600, x598, x587, x590); + uint32_t x601; + fiat_p256_uint1 x602; + fiat_p256_addcarryx_u32(&x601, &x602, x600, x585, x588); + uint32_t x603; + fiat_p256_uint1 x604; + fiat_p256_addcarryx_u32(&x603, &x604, x602, x583, x586); + uint32_t x605; + fiat_p256_uint1 x606; + fiat_p256_addcarryx_u32(&x605, &x606, x604, x581, x584); + uint32_t x607; + fiat_p256_uint1 x608; + fiat_p256_addcarryx_u32(&x607, &x608, x606, x579, x582); + uint32_t x609; + fiat_p256_uint1 x610; + fiat_p256_addcarryx_u32(&x609, &x610, x608, 0x0, x580); + uint32_t x611; + fiat_p256_uint1 x612; + fiat_p256_addcarryx_u32(&x611, &x612, 0x0, x593, x561); + uint32_t x613; + fiat_p256_uint1 x614; + fiat_p256_addcarryx_u32(&x613, &x614, x612, x595, x563); + uint32_t x615; + fiat_p256_uint1 x616; + fiat_p256_addcarryx_u32(&x615, &x616, x614, x597, x565); + uint32_t x617; + fiat_p256_uint1 x618; + fiat_p256_addcarryx_u32(&x617, &x618, x616, x599, x567); + uint32_t x619; + fiat_p256_uint1 x620; + fiat_p256_addcarryx_u32(&x619, &x620, x618, x601, x569); + uint32_t x621; + fiat_p256_uint1 x622; + fiat_p256_addcarryx_u32(&x621, &x622, x620, x603, x571); + uint32_t x623; + fiat_p256_uint1 x624; + fiat_p256_addcarryx_u32(&x623, &x624, x622, x605, x573); + uint32_t x625; + fiat_p256_uint1 x626; + fiat_p256_addcarryx_u32(&x625, &x626, x624, x607, x575); + uint32_t x627; + fiat_p256_uint1 x628; + fiat_p256_addcarryx_u32(&x627, &x628, x626, x609, x577); + uint32_t x629; + uint32_t x630; + fiat_p256_mulx_u32(&x629, &x630, x611, UINT32_C(0xffffffff)); + uint32_t x631; + uint32_t x632; + fiat_p256_mulx_u32(&x631, &x632, x611, UINT32_C(0xffffffff)); + uint32_t x633; + uint32_t x634; + fiat_p256_mulx_u32(&x633, &x634, x611, UINT32_C(0xffffffff)); + uint32_t x635; + uint32_t x636; + fiat_p256_mulx_u32(&x635, &x636, x611, UINT32_C(0xffffffff)); + uint32_t x637; + fiat_p256_uint1 x638; + fiat_p256_addcarryx_u32(&x637, &x638, 0x0, x633, x636); + uint32_t x639; + fiat_p256_uint1 x640; + fiat_p256_addcarryx_u32(&x639, &x640, x638, x631, x634); + uint32_t x641; + fiat_p256_uint1 x642; + fiat_p256_addcarryx_u32(&x641, &x642, x640, 0x0, x632); + uint32_t x643; + fiat_p256_uint1 x644; + fiat_p256_addcarryx_u32(&x643, &x644, 0x0, x635, x611); + uint32_t x645; + fiat_p256_uint1 x646; + fiat_p256_addcarryx_u32(&x645, &x646, x644, x637, x613); + uint32_t x647; + fiat_p256_uint1 x648; + fiat_p256_addcarryx_u32(&x647, &x648, x646, x639, x615); + uint32_t x649; + fiat_p256_uint1 x650; + fiat_p256_addcarryx_u32(&x649, &x650, x648, x641, x617); + uint32_t x651; + fiat_p256_uint1 x652; + fiat_p256_addcarryx_u32(&x651, &x652, x650, 0x0, x619); + uint32_t x653; + fiat_p256_uint1 x654; + fiat_p256_addcarryx_u32(&x653, &x654, x652, 0x0, x621); + uint32_t x655; + fiat_p256_uint1 x656; + fiat_p256_addcarryx_u32(&x655, &x656, x654, x611, x623); + uint32_t x657; + fiat_p256_uint1 x658; + fiat_p256_addcarryx_u32(&x657, &x658, x656, x629, x625); + uint32_t x659; + fiat_p256_uint1 x660; + fiat_p256_addcarryx_u32(&x659, &x660, x658, x630, x627); + uint32_t x661; + fiat_p256_uint1 x662; + fiat_p256_addcarryx_u32(&x661, &x662, x660, 0x0, x628); + uint32_t x663; + fiat_p256_uint1 x664; + fiat_p256_subborrowx_u32(&x663, &x664, 0x0, x645, UINT32_C(0xffffffff)); + uint32_t x665; + fiat_p256_uint1 x666; + fiat_p256_subborrowx_u32(&x665, &x666, x664, x647, UINT32_C(0xffffffff)); + uint32_t x667; + fiat_p256_uint1 x668; + fiat_p256_subborrowx_u32(&x667, &x668, x666, x649, UINT32_C(0xffffffff)); + uint32_t x669; + fiat_p256_uint1 x670; + fiat_p256_subborrowx_u32(&x669, &x670, x668, x651, 0x0); + uint32_t x671; + fiat_p256_uint1 x672; + fiat_p256_subborrowx_u32(&x671, &x672, x670, x653, 0x0); + uint32_t x673; + fiat_p256_uint1 x674; + fiat_p256_subborrowx_u32(&x673, &x674, x672, x655, 0x0); + uint32_t x675; + fiat_p256_uint1 x676; + fiat_p256_subborrowx_u32(&x675, &x676, x674, x657, 0x1); + uint32_t x677; + fiat_p256_uint1 x678; + fiat_p256_subborrowx_u32(&x677, &x678, x676, x659, UINT32_C(0xffffffff)); + uint32_t x679; + fiat_p256_uint1 x680; + fiat_p256_subborrowx_u32(&x679, &x680, x678, x661, 0x0); + uint32_t x681; + fiat_p256_cmovznz_u32(&x681, x680, x663, x645); + uint32_t x682; + fiat_p256_cmovznz_u32(&x682, x680, x665, x647); + uint32_t x683; + fiat_p256_cmovznz_u32(&x683, x680, x667, x649); + uint32_t x684; + fiat_p256_cmovznz_u32(&x684, x680, x669, x651); + uint32_t x685; + fiat_p256_cmovznz_u32(&x685, x680, x671, x653); + uint32_t x686; + fiat_p256_cmovznz_u32(&x686, x680, x673, x655); + uint32_t x687; + fiat_p256_cmovznz_u32(&x687, x680, x675, x657); + uint32_t x688; + fiat_p256_cmovznz_u32(&x688, x680, x677, x659); + out1[0] = x681; + out1[1] = x682; + out1[2] = x683; + out1[3] = x684; + out1[4] = x685; + out1[5] = x686; + out1[6] = x687; + out1[7] = x688; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + */ +static void fiat_p256_square(uint32_t out1[8], const uint32_t arg1[8]) { + uint32_t x1 = (arg1[1]); + uint32_t x2 = (arg1[2]); + uint32_t x3 = (arg1[3]); + uint32_t x4 = (arg1[4]); + uint32_t x5 = (arg1[5]); + uint32_t x6 = (arg1[6]); + uint32_t x7 = (arg1[7]); + uint32_t x8 = (arg1[0]); + uint32_t x9; + uint32_t x10; + fiat_p256_mulx_u32(&x9, &x10, x8, (arg1[7])); + uint32_t x11; + uint32_t x12; + fiat_p256_mulx_u32(&x11, &x12, x8, (arg1[6])); + uint32_t x13; + uint32_t x14; + fiat_p256_mulx_u32(&x13, &x14, x8, (arg1[5])); + uint32_t x15; + uint32_t x16; + fiat_p256_mulx_u32(&x15, &x16, x8, (arg1[4])); + uint32_t x17; + uint32_t x18; + fiat_p256_mulx_u32(&x17, &x18, x8, (arg1[3])); + uint32_t x19; + uint32_t x20; + fiat_p256_mulx_u32(&x19, &x20, x8, (arg1[2])); + uint32_t x21; + uint32_t x22; + fiat_p256_mulx_u32(&x21, &x22, x8, (arg1[1])); + uint32_t x23; + uint32_t x24; + fiat_p256_mulx_u32(&x23, &x24, x8, (arg1[0])); + uint32_t x25; + fiat_p256_uint1 x26; + fiat_p256_addcarryx_u32(&x25, &x26, 0x0, x21, x24); + uint32_t x27; + fiat_p256_uint1 x28; + fiat_p256_addcarryx_u32(&x27, &x28, x26, x19, x22); + uint32_t x29; + fiat_p256_uint1 x30; + fiat_p256_addcarryx_u32(&x29, &x30, x28, x17, x20); + uint32_t x31; + fiat_p256_uint1 x32; + fiat_p256_addcarryx_u32(&x31, &x32, x30, x15, x18); + uint32_t x33; + fiat_p256_uint1 x34; + fiat_p256_addcarryx_u32(&x33, &x34, x32, x13, x16); + uint32_t x35; + fiat_p256_uint1 x36; + fiat_p256_addcarryx_u32(&x35, &x36, x34, x11, x14); + uint32_t x37; + fiat_p256_uint1 x38; + fiat_p256_addcarryx_u32(&x37, &x38, x36, x9, x12); + uint32_t x39; + fiat_p256_uint1 x40; + fiat_p256_addcarryx_u32(&x39, &x40, x38, 0x0, x10); + uint32_t x41; + uint32_t x42; + fiat_p256_mulx_u32(&x41, &x42, x23, UINT32_C(0xffffffff)); + uint32_t x43; + uint32_t x44; + fiat_p256_mulx_u32(&x43, &x44, x23, UINT32_C(0xffffffff)); + uint32_t x45; + uint32_t x46; + fiat_p256_mulx_u32(&x45, &x46, x23, UINT32_C(0xffffffff)); + uint32_t x47; + uint32_t x48; + fiat_p256_mulx_u32(&x47, &x48, x23, UINT32_C(0xffffffff)); + uint32_t x49; + fiat_p256_uint1 x50; + fiat_p256_addcarryx_u32(&x49, &x50, 0x0, x45, x48); + uint32_t x51; + fiat_p256_uint1 x52; + fiat_p256_addcarryx_u32(&x51, &x52, x50, x43, x46); + uint32_t x53; + fiat_p256_uint1 x54; + fiat_p256_addcarryx_u32(&x53, &x54, x52, 0x0, x44); + uint32_t x55; + fiat_p256_uint1 x56; + fiat_p256_addcarryx_u32(&x55, &x56, 0x0, x47, x23); + uint32_t x57; + fiat_p256_uint1 x58; + fiat_p256_addcarryx_u32(&x57, &x58, x56, x49, x25); + uint32_t x59; + fiat_p256_uint1 x60; + fiat_p256_addcarryx_u32(&x59, &x60, x58, x51, x27); + uint32_t x61; + fiat_p256_uint1 x62; + fiat_p256_addcarryx_u32(&x61, &x62, x60, x53, x29); + uint32_t x63; + fiat_p256_uint1 x64; + fiat_p256_addcarryx_u32(&x63, &x64, x62, 0x0, x31); + uint32_t x65; + fiat_p256_uint1 x66; + fiat_p256_addcarryx_u32(&x65, &x66, x64, 0x0, x33); + uint32_t x67; + fiat_p256_uint1 x68; + fiat_p256_addcarryx_u32(&x67, &x68, x66, x23, x35); + uint32_t x69; + fiat_p256_uint1 x70; + fiat_p256_addcarryx_u32(&x69, &x70, x68, x41, x37); + uint32_t x71; + fiat_p256_uint1 x72; + fiat_p256_addcarryx_u32(&x71, &x72, x70, x42, x39); + uint32_t x73; + fiat_p256_uint1 x74; + fiat_p256_addcarryx_u32(&x73, &x74, x72, 0x0, 0x0); + uint32_t x75; + uint32_t x76; + fiat_p256_mulx_u32(&x75, &x76, x1, (arg1[7])); + uint32_t x77; + uint32_t x78; + fiat_p256_mulx_u32(&x77, &x78, x1, (arg1[6])); + uint32_t x79; + uint32_t x80; + fiat_p256_mulx_u32(&x79, &x80, x1, (arg1[5])); + uint32_t x81; + uint32_t x82; + fiat_p256_mulx_u32(&x81, &x82, x1, (arg1[4])); + uint32_t x83; + uint32_t x84; + fiat_p256_mulx_u32(&x83, &x84, x1, (arg1[3])); + uint32_t x85; + uint32_t x86; + fiat_p256_mulx_u32(&x85, &x86, x1, (arg1[2])); + uint32_t x87; + uint32_t x88; + fiat_p256_mulx_u32(&x87, &x88, x1, (arg1[1])); + uint32_t x89; + uint32_t x90; + fiat_p256_mulx_u32(&x89, &x90, x1, (arg1[0])); + uint32_t x91; + fiat_p256_uint1 x92; + fiat_p256_addcarryx_u32(&x91, &x92, 0x0, x87, x90); + uint32_t x93; + fiat_p256_uint1 x94; + fiat_p256_addcarryx_u32(&x93, &x94, x92, x85, x88); + uint32_t x95; + fiat_p256_uint1 x96; + fiat_p256_addcarryx_u32(&x95, &x96, x94, x83, x86); + uint32_t x97; + fiat_p256_uint1 x98; + fiat_p256_addcarryx_u32(&x97, &x98, x96, x81, x84); + uint32_t x99; + fiat_p256_uint1 x100; + fiat_p256_addcarryx_u32(&x99, &x100, x98, x79, x82); + uint32_t x101; + fiat_p256_uint1 x102; + fiat_p256_addcarryx_u32(&x101, &x102, x100, x77, x80); + uint32_t x103; + fiat_p256_uint1 x104; + fiat_p256_addcarryx_u32(&x103, &x104, x102, x75, x78); + uint32_t x105; + fiat_p256_uint1 x106; + fiat_p256_addcarryx_u32(&x105, &x106, x104, 0x0, x76); + uint32_t x107; + fiat_p256_uint1 x108; + fiat_p256_addcarryx_u32(&x107, &x108, 0x0, x89, x57); + uint32_t x109; + fiat_p256_uint1 x110; + fiat_p256_addcarryx_u32(&x109, &x110, x108, x91, x59); + uint32_t x111; + fiat_p256_uint1 x112; + fiat_p256_addcarryx_u32(&x111, &x112, x110, x93, x61); + uint32_t x113; + fiat_p256_uint1 x114; + fiat_p256_addcarryx_u32(&x113, &x114, x112, x95, x63); + uint32_t x115; + fiat_p256_uint1 x116; + fiat_p256_addcarryx_u32(&x115, &x116, x114, x97, x65); + uint32_t x117; + fiat_p256_uint1 x118; + fiat_p256_addcarryx_u32(&x117, &x118, x116, x99, x67); + uint32_t x119; + fiat_p256_uint1 x120; + fiat_p256_addcarryx_u32(&x119, &x120, x118, x101, x69); + uint32_t x121; + fiat_p256_uint1 x122; + fiat_p256_addcarryx_u32(&x121, &x122, x120, x103, x71); + uint32_t x123; + fiat_p256_uint1 x124; + fiat_p256_addcarryx_u32(&x123, &x124, x122, x105, (fiat_p256_uint1)x73); + uint32_t x125; + uint32_t x126; + fiat_p256_mulx_u32(&x125, &x126, x107, UINT32_C(0xffffffff)); + uint32_t x127; + uint32_t x128; + fiat_p256_mulx_u32(&x127, &x128, x107, UINT32_C(0xffffffff)); + uint32_t x129; + uint32_t x130; + fiat_p256_mulx_u32(&x129, &x130, x107, UINT32_C(0xffffffff)); + uint32_t x131; + uint32_t x132; + fiat_p256_mulx_u32(&x131, &x132, x107, UINT32_C(0xffffffff)); + uint32_t x133; + fiat_p256_uint1 x134; + fiat_p256_addcarryx_u32(&x133, &x134, 0x0, x129, x132); + uint32_t x135; + fiat_p256_uint1 x136; + fiat_p256_addcarryx_u32(&x135, &x136, x134, x127, x130); + uint32_t x137; + fiat_p256_uint1 x138; + fiat_p256_addcarryx_u32(&x137, &x138, x136, 0x0, x128); + uint32_t x139; + fiat_p256_uint1 x140; + fiat_p256_addcarryx_u32(&x139, &x140, 0x0, x131, x107); + uint32_t x141; + fiat_p256_uint1 x142; + fiat_p256_addcarryx_u32(&x141, &x142, x140, x133, x109); + uint32_t x143; + fiat_p256_uint1 x144; + fiat_p256_addcarryx_u32(&x143, &x144, x142, x135, x111); + uint32_t x145; + fiat_p256_uint1 x146; + fiat_p256_addcarryx_u32(&x145, &x146, x144, x137, x113); + uint32_t x147; + fiat_p256_uint1 x148; + fiat_p256_addcarryx_u32(&x147, &x148, x146, 0x0, x115); + uint32_t x149; + fiat_p256_uint1 x150; + fiat_p256_addcarryx_u32(&x149, &x150, x148, 0x0, x117); + uint32_t x151; + fiat_p256_uint1 x152; + fiat_p256_addcarryx_u32(&x151, &x152, x150, x107, x119); + uint32_t x153; + fiat_p256_uint1 x154; + fiat_p256_addcarryx_u32(&x153, &x154, x152, x125, x121); + uint32_t x155; + fiat_p256_uint1 x156; + fiat_p256_addcarryx_u32(&x155, &x156, x154, x126, x123); + uint32_t x157; + fiat_p256_uint1 x158; + fiat_p256_addcarryx_u32(&x157, &x158, x156, 0x0, x124); + uint32_t x159; + uint32_t x160; + fiat_p256_mulx_u32(&x159, &x160, x2, (arg1[7])); + uint32_t x161; + uint32_t x162; + fiat_p256_mulx_u32(&x161, &x162, x2, (arg1[6])); + uint32_t x163; + uint32_t x164; + fiat_p256_mulx_u32(&x163, &x164, x2, (arg1[5])); + uint32_t x165; + uint32_t x166; + fiat_p256_mulx_u32(&x165, &x166, x2, (arg1[4])); + uint32_t x167; + uint32_t x168; + fiat_p256_mulx_u32(&x167, &x168, x2, (arg1[3])); + uint32_t x169; + uint32_t x170; + fiat_p256_mulx_u32(&x169, &x170, x2, (arg1[2])); + uint32_t x171; + uint32_t x172; + fiat_p256_mulx_u32(&x171, &x172, x2, (arg1[1])); + uint32_t x173; + uint32_t x174; + fiat_p256_mulx_u32(&x173, &x174, x2, (arg1[0])); + uint32_t x175; + fiat_p256_uint1 x176; + fiat_p256_addcarryx_u32(&x175, &x176, 0x0, x171, x174); + uint32_t x177; + fiat_p256_uint1 x178; + fiat_p256_addcarryx_u32(&x177, &x178, x176, x169, x172); + uint32_t x179; + fiat_p256_uint1 x180; + fiat_p256_addcarryx_u32(&x179, &x180, x178, x167, x170); + uint32_t x181; + fiat_p256_uint1 x182; + fiat_p256_addcarryx_u32(&x181, &x182, x180, x165, x168); + uint32_t x183; + fiat_p256_uint1 x184; + fiat_p256_addcarryx_u32(&x183, &x184, x182, x163, x166); + uint32_t x185; + fiat_p256_uint1 x186; + fiat_p256_addcarryx_u32(&x185, &x186, x184, x161, x164); + uint32_t x187; + fiat_p256_uint1 x188; + fiat_p256_addcarryx_u32(&x187, &x188, x186, x159, x162); + uint32_t x189; + fiat_p256_uint1 x190; + fiat_p256_addcarryx_u32(&x189, &x190, x188, 0x0, x160); + uint32_t x191; + fiat_p256_uint1 x192; + fiat_p256_addcarryx_u32(&x191, &x192, 0x0, x173, x141); + uint32_t x193; + fiat_p256_uint1 x194; + fiat_p256_addcarryx_u32(&x193, &x194, x192, x175, x143); + uint32_t x195; + fiat_p256_uint1 x196; + fiat_p256_addcarryx_u32(&x195, &x196, x194, x177, x145); + uint32_t x197; + fiat_p256_uint1 x198; + fiat_p256_addcarryx_u32(&x197, &x198, x196, x179, x147); + uint32_t x199; + fiat_p256_uint1 x200; + fiat_p256_addcarryx_u32(&x199, &x200, x198, x181, x149); + uint32_t x201; + fiat_p256_uint1 x202; + fiat_p256_addcarryx_u32(&x201, &x202, x200, x183, x151); + uint32_t x203; + fiat_p256_uint1 x204; + fiat_p256_addcarryx_u32(&x203, &x204, x202, x185, x153); + uint32_t x205; + fiat_p256_uint1 x206; + fiat_p256_addcarryx_u32(&x205, &x206, x204, x187, x155); + uint32_t x207; + fiat_p256_uint1 x208; + fiat_p256_addcarryx_u32(&x207, &x208, x206, x189, x157); + uint32_t x209; + uint32_t x210; + fiat_p256_mulx_u32(&x209, &x210, x191, UINT32_C(0xffffffff)); + uint32_t x211; + uint32_t x212; + fiat_p256_mulx_u32(&x211, &x212, x191, UINT32_C(0xffffffff)); + uint32_t x213; + uint32_t x214; + fiat_p256_mulx_u32(&x213, &x214, x191, UINT32_C(0xffffffff)); + uint32_t x215; + uint32_t x216; + fiat_p256_mulx_u32(&x215, &x216, x191, UINT32_C(0xffffffff)); + uint32_t x217; + fiat_p256_uint1 x218; + fiat_p256_addcarryx_u32(&x217, &x218, 0x0, x213, x216); + uint32_t x219; + fiat_p256_uint1 x220; + fiat_p256_addcarryx_u32(&x219, &x220, x218, x211, x214); + uint32_t x221; + fiat_p256_uint1 x222; + fiat_p256_addcarryx_u32(&x221, &x222, x220, 0x0, x212); + uint32_t x223; + fiat_p256_uint1 x224; + fiat_p256_addcarryx_u32(&x223, &x224, 0x0, x215, x191); + uint32_t x225; + fiat_p256_uint1 x226; + fiat_p256_addcarryx_u32(&x225, &x226, x224, x217, x193); + uint32_t x227; + fiat_p256_uint1 x228; + fiat_p256_addcarryx_u32(&x227, &x228, x226, x219, x195); + uint32_t x229; + fiat_p256_uint1 x230; + fiat_p256_addcarryx_u32(&x229, &x230, x228, x221, x197); + uint32_t x231; + fiat_p256_uint1 x232; + fiat_p256_addcarryx_u32(&x231, &x232, x230, 0x0, x199); + uint32_t x233; + fiat_p256_uint1 x234; + fiat_p256_addcarryx_u32(&x233, &x234, x232, 0x0, x201); + uint32_t x235; + fiat_p256_uint1 x236; + fiat_p256_addcarryx_u32(&x235, &x236, x234, x191, x203); + uint32_t x237; + fiat_p256_uint1 x238; + fiat_p256_addcarryx_u32(&x237, &x238, x236, x209, x205); + uint32_t x239; + fiat_p256_uint1 x240; + fiat_p256_addcarryx_u32(&x239, &x240, x238, x210, x207); + uint32_t x241; + fiat_p256_uint1 x242; + fiat_p256_addcarryx_u32(&x241, &x242, x240, 0x0, x208); + uint32_t x243; + uint32_t x244; + fiat_p256_mulx_u32(&x243, &x244, x3, (arg1[7])); + uint32_t x245; + uint32_t x246; + fiat_p256_mulx_u32(&x245, &x246, x3, (arg1[6])); + uint32_t x247; + uint32_t x248; + fiat_p256_mulx_u32(&x247, &x248, x3, (arg1[5])); + uint32_t x249; + uint32_t x250; + fiat_p256_mulx_u32(&x249, &x250, x3, (arg1[4])); + uint32_t x251; + uint32_t x252; + fiat_p256_mulx_u32(&x251, &x252, x3, (arg1[3])); + uint32_t x253; + uint32_t x254; + fiat_p256_mulx_u32(&x253, &x254, x3, (arg1[2])); + uint32_t x255; + uint32_t x256; + fiat_p256_mulx_u32(&x255, &x256, x3, (arg1[1])); + uint32_t x257; + uint32_t x258; + fiat_p256_mulx_u32(&x257, &x258, x3, (arg1[0])); + uint32_t x259; + fiat_p256_uint1 x260; + fiat_p256_addcarryx_u32(&x259, &x260, 0x0, x255, x258); + uint32_t x261; + fiat_p256_uint1 x262; + fiat_p256_addcarryx_u32(&x261, &x262, x260, x253, x256); + uint32_t x263; + fiat_p256_uint1 x264; + fiat_p256_addcarryx_u32(&x263, &x264, x262, x251, x254); + uint32_t x265; + fiat_p256_uint1 x266; + fiat_p256_addcarryx_u32(&x265, &x266, x264, x249, x252); + uint32_t x267; + fiat_p256_uint1 x268; + fiat_p256_addcarryx_u32(&x267, &x268, x266, x247, x250); + uint32_t x269; + fiat_p256_uint1 x270; + fiat_p256_addcarryx_u32(&x269, &x270, x268, x245, x248); + uint32_t x271; + fiat_p256_uint1 x272; + fiat_p256_addcarryx_u32(&x271, &x272, x270, x243, x246); + uint32_t x273; + fiat_p256_uint1 x274; + fiat_p256_addcarryx_u32(&x273, &x274, x272, 0x0, x244); + uint32_t x275; + fiat_p256_uint1 x276; + fiat_p256_addcarryx_u32(&x275, &x276, 0x0, x257, x225); + uint32_t x277; + fiat_p256_uint1 x278; + fiat_p256_addcarryx_u32(&x277, &x278, x276, x259, x227); + uint32_t x279; + fiat_p256_uint1 x280; + fiat_p256_addcarryx_u32(&x279, &x280, x278, x261, x229); + uint32_t x281; + fiat_p256_uint1 x282; + fiat_p256_addcarryx_u32(&x281, &x282, x280, x263, x231); + uint32_t x283; + fiat_p256_uint1 x284; + fiat_p256_addcarryx_u32(&x283, &x284, x282, x265, x233); + uint32_t x285; + fiat_p256_uint1 x286; + fiat_p256_addcarryx_u32(&x285, &x286, x284, x267, x235); + uint32_t x287; + fiat_p256_uint1 x288; + fiat_p256_addcarryx_u32(&x287, &x288, x286, x269, x237); + uint32_t x289; + fiat_p256_uint1 x290; + fiat_p256_addcarryx_u32(&x289, &x290, x288, x271, x239); + uint32_t x291; + fiat_p256_uint1 x292; + fiat_p256_addcarryx_u32(&x291, &x292, x290, x273, x241); + uint32_t x293; + uint32_t x294; + fiat_p256_mulx_u32(&x293, &x294, x275, UINT32_C(0xffffffff)); + uint32_t x295; + uint32_t x296; + fiat_p256_mulx_u32(&x295, &x296, x275, UINT32_C(0xffffffff)); + uint32_t x297; + uint32_t x298; + fiat_p256_mulx_u32(&x297, &x298, x275, UINT32_C(0xffffffff)); + uint32_t x299; + uint32_t x300; + fiat_p256_mulx_u32(&x299, &x300, x275, UINT32_C(0xffffffff)); + uint32_t x301; + fiat_p256_uint1 x302; + fiat_p256_addcarryx_u32(&x301, &x302, 0x0, x297, x300); + uint32_t x303; + fiat_p256_uint1 x304; + fiat_p256_addcarryx_u32(&x303, &x304, x302, x295, x298); + uint32_t x305; + fiat_p256_uint1 x306; + fiat_p256_addcarryx_u32(&x305, &x306, x304, 0x0, x296); + uint32_t x307; + fiat_p256_uint1 x308; + fiat_p256_addcarryx_u32(&x307, &x308, 0x0, x299, x275); + uint32_t x309; + fiat_p256_uint1 x310; + fiat_p256_addcarryx_u32(&x309, &x310, x308, x301, x277); + uint32_t x311; + fiat_p256_uint1 x312; + fiat_p256_addcarryx_u32(&x311, &x312, x310, x303, x279); + uint32_t x313; + fiat_p256_uint1 x314; + fiat_p256_addcarryx_u32(&x313, &x314, x312, x305, x281); + uint32_t x315; + fiat_p256_uint1 x316; + fiat_p256_addcarryx_u32(&x315, &x316, x314, 0x0, x283); + uint32_t x317; + fiat_p256_uint1 x318; + fiat_p256_addcarryx_u32(&x317, &x318, x316, 0x0, x285); + uint32_t x319; + fiat_p256_uint1 x320; + fiat_p256_addcarryx_u32(&x319, &x320, x318, x275, x287); + uint32_t x321; + fiat_p256_uint1 x322; + fiat_p256_addcarryx_u32(&x321, &x322, x320, x293, x289); + uint32_t x323; + fiat_p256_uint1 x324; + fiat_p256_addcarryx_u32(&x323, &x324, x322, x294, x291); + uint32_t x325; + fiat_p256_uint1 x326; + fiat_p256_addcarryx_u32(&x325, &x326, x324, 0x0, x292); + uint32_t x327; + uint32_t x328; + fiat_p256_mulx_u32(&x327, &x328, x4, (arg1[7])); + uint32_t x329; + uint32_t x330; + fiat_p256_mulx_u32(&x329, &x330, x4, (arg1[6])); + uint32_t x331; + uint32_t x332; + fiat_p256_mulx_u32(&x331, &x332, x4, (arg1[5])); + uint32_t x333; + uint32_t x334; + fiat_p256_mulx_u32(&x333, &x334, x4, (arg1[4])); + uint32_t x335; + uint32_t x336; + fiat_p256_mulx_u32(&x335, &x336, x4, (arg1[3])); + uint32_t x337; + uint32_t x338; + fiat_p256_mulx_u32(&x337, &x338, x4, (arg1[2])); + uint32_t x339; + uint32_t x340; + fiat_p256_mulx_u32(&x339, &x340, x4, (arg1[1])); + uint32_t x341; + uint32_t x342; + fiat_p256_mulx_u32(&x341, &x342, x4, (arg1[0])); + uint32_t x343; + fiat_p256_uint1 x344; + fiat_p256_addcarryx_u32(&x343, &x344, 0x0, x339, x342); + uint32_t x345; + fiat_p256_uint1 x346; + fiat_p256_addcarryx_u32(&x345, &x346, x344, x337, x340); + uint32_t x347; + fiat_p256_uint1 x348; + fiat_p256_addcarryx_u32(&x347, &x348, x346, x335, x338); + uint32_t x349; + fiat_p256_uint1 x350; + fiat_p256_addcarryx_u32(&x349, &x350, x348, x333, x336); + uint32_t x351; + fiat_p256_uint1 x352; + fiat_p256_addcarryx_u32(&x351, &x352, x350, x331, x334); + uint32_t x353; + fiat_p256_uint1 x354; + fiat_p256_addcarryx_u32(&x353, &x354, x352, x329, x332); + uint32_t x355; + fiat_p256_uint1 x356; + fiat_p256_addcarryx_u32(&x355, &x356, x354, x327, x330); + uint32_t x357; + fiat_p256_uint1 x358; + fiat_p256_addcarryx_u32(&x357, &x358, x356, 0x0, x328); + uint32_t x359; + fiat_p256_uint1 x360; + fiat_p256_addcarryx_u32(&x359, &x360, 0x0, x341, x309); + uint32_t x361; + fiat_p256_uint1 x362; + fiat_p256_addcarryx_u32(&x361, &x362, x360, x343, x311); + uint32_t x363; + fiat_p256_uint1 x364; + fiat_p256_addcarryx_u32(&x363, &x364, x362, x345, x313); + uint32_t x365; + fiat_p256_uint1 x366; + fiat_p256_addcarryx_u32(&x365, &x366, x364, x347, x315); + uint32_t x367; + fiat_p256_uint1 x368; + fiat_p256_addcarryx_u32(&x367, &x368, x366, x349, x317); + uint32_t x369; + fiat_p256_uint1 x370; + fiat_p256_addcarryx_u32(&x369, &x370, x368, x351, x319); + uint32_t x371; + fiat_p256_uint1 x372; + fiat_p256_addcarryx_u32(&x371, &x372, x370, x353, x321); + uint32_t x373; + fiat_p256_uint1 x374; + fiat_p256_addcarryx_u32(&x373, &x374, x372, x355, x323); + uint32_t x375; + fiat_p256_uint1 x376; + fiat_p256_addcarryx_u32(&x375, &x376, x374, x357, x325); + uint32_t x377; + uint32_t x378; + fiat_p256_mulx_u32(&x377, &x378, x359, UINT32_C(0xffffffff)); + uint32_t x379; + uint32_t x380; + fiat_p256_mulx_u32(&x379, &x380, x359, UINT32_C(0xffffffff)); + uint32_t x381; + uint32_t x382; + fiat_p256_mulx_u32(&x381, &x382, x359, UINT32_C(0xffffffff)); + uint32_t x383; + uint32_t x384; + fiat_p256_mulx_u32(&x383, &x384, x359, UINT32_C(0xffffffff)); + uint32_t x385; + fiat_p256_uint1 x386; + fiat_p256_addcarryx_u32(&x385, &x386, 0x0, x381, x384); + uint32_t x387; + fiat_p256_uint1 x388; + fiat_p256_addcarryx_u32(&x387, &x388, x386, x379, x382); + uint32_t x389; + fiat_p256_uint1 x390; + fiat_p256_addcarryx_u32(&x389, &x390, x388, 0x0, x380); + uint32_t x391; + fiat_p256_uint1 x392; + fiat_p256_addcarryx_u32(&x391, &x392, 0x0, x383, x359); + uint32_t x393; + fiat_p256_uint1 x394; + fiat_p256_addcarryx_u32(&x393, &x394, x392, x385, x361); + uint32_t x395; + fiat_p256_uint1 x396; + fiat_p256_addcarryx_u32(&x395, &x396, x394, x387, x363); + uint32_t x397; + fiat_p256_uint1 x398; + fiat_p256_addcarryx_u32(&x397, &x398, x396, x389, x365); + uint32_t x399; + fiat_p256_uint1 x400; + fiat_p256_addcarryx_u32(&x399, &x400, x398, 0x0, x367); + uint32_t x401; + fiat_p256_uint1 x402; + fiat_p256_addcarryx_u32(&x401, &x402, x400, 0x0, x369); + uint32_t x403; + fiat_p256_uint1 x404; + fiat_p256_addcarryx_u32(&x403, &x404, x402, x359, x371); + uint32_t x405; + fiat_p256_uint1 x406; + fiat_p256_addcarryx_u32(&x405, &x406, x404, x377, x373); + uint32_t x407; + fiat_p256_uint1 x408; + fiat_p256_addcarryx_u32(&x407, &x408, x406, x378, x375); + uint32_t x409; + fiat_p256_uint1 x410; + fiat_p256_addcarryx_u32(&x409, &x410, x408, 0x0, x376); + uint32_t x411; + uint32_t x412; + fiat_p256_mulx_u32(&x411, &x412, x5, (arg1[7])); + uint32_t x413; + uint32_t x414; + fiat_p256_mulx_u32(&x413, &x414, x5, (arg1[6])); + uint32_t x415; + uint32_t x416; + fiat_p256_mulx_u32(&x415, &x416, x5, (arg1[5])); + uint32_t x417; + uint32_t x418; + fiat_p256_mulx_u32(&x417, &x418, x5, (arg1[4])); + uint32_t x419; + uint32_t x420; + fiat_p256_mulx_u32(&x419, &x420, x5, (arg1[3])); + uint32_t x421; + uint32_t x422; + fiat_p256_mulx_u32(&x421, &x422, x5, (arg1[2])); + uint32_t x423; + uint32_t x424; + fiat_p256_mulx_u32(&x423, &x424, x5, (arg1[1])); + uint32_t x425; + uint32_t x426; + fiat_p256_mulx_u32(&x425, &x426, x5, (arg1[0])); + uint32_t x427; + fiat_p256_uint1 x428; + fiat_p256_addcarryx_u32(&x427, &x428, 0x0, x423, x426); + uint32_t x429; + fiat_p256_uint1 x430; + fiat_p256_addcarryx_u32(&x429, &x430, x428, x421, x424); + uint32_t x431; + fiat_p256_uint1 x432; + fiat_p256_addcarryx_u32(&x431, &x432, x430, x419, x422); + uint32_t x433; + fiat_p256_uint1 x434; + fiat_p256_addcarryx_u32(&x433, &x434, x432, x417, x420); + uint32_t x435; + fiat_p256_uint1 x436; + fiat_p256_addcarryx_u32(&x435, &x436, x434, x415, x418); + uint32_t x437; + fiat_p256_uint1 x438; + fiat_p256_addcarryx_u32(&x437, &x438, x436, x413, x416); + uint32_t x439; + fiat_p256_uint1 x440; + fiat_p256_addcarryx_u32(&x439, &x440, x438, x411, x414); + uint32_t x441; + fiat_p256_uint1 x442; + fiat_p256_addcarryx_u32(&x441, &x442, x440, 0x0, x412); + uint32_t x443; + fiat_p256_uint1 x444; + fiat_p256_addcarryx_u32(&x443, &x444, 0x0, x425, x393); + uint32_t x445; + fiat_p256_uint1 x446; + fiat_p256_addcarryx_u32(&x445, &x446, x444, x427, x395); + uint32_t x447; + fiat_p256_uint1 x448; + fiat_p256_addcarryx_u32(&x447, &x448, x446, x429, x397); + uint32_t x449; + fiat_p256_uint1 x450; + fiat_p256_addcarryx_u32(&x449, &x450, x448, x431, x399); + uint32_t x451; + fiat_p256_uint1 x452; + fiat_p256_addcarryx_u32(&x451, &x452, x450, x433, x401); + uint32_t x453; + fiat_p256_uint1 x454; + fiat_p256_addcarryx_u32(&x453, &x454, x452, x435, x403); + uint32_t x455; + fiat_p256_uint1 x456; + fiat_p256_addcarryx_u32(&x455, &x456, x454, x437, x405); + uint32_t x457; + fiat_p256_uint1 x458; + fiat_p256_addcarryx_u32(&x457, &x458, x456, x439, x407); + uint32_t x459; + fiat_p256_uint1 x460; + fiat_p256_addcarryx_u32(&x459, &x460, x458, x441, x409); + uint32_t x461; + uint32_t x462; + fiat_p256_mulx_u32(&x461, &x462, x443, UINT32_C(0xffffffff)); + uint32_t x463; + uint32_t x464; + fiat_p256_mulx_u32(&x463, &x464, x443, UINT32_C(0xffffffff)); + uint32_t x465; + uint32_t x466; + fiat_p256_mulx_u32(&x465, &x466, x443, UINT32_C(0xffffffff)); + uint32_t x467; + uint32_t x468; + fiat_p256_mulx_u32(&x467, &x468, x443, UINT32_C(0xffffffff)); + uint32_t x469; + fiat_p256_uint1 x470; + fiat_p256_addcarryx_u32(&x469, &x470, 0x0, x465, x468); + uint32_t x471; + fiat_p256_uint1 x472; + fiat_p256_addcarryx_u32(&x471, &x472, x470, x463, x466); + uint32_t x473; + fiat_p256_uint1 x474; + fiat_p256_addcarryx_u32(&x473, &x474, x472, 0x0, x464); + uint32_t x475; + fiat_p256_uint1 x476; + fiat_p256_addcarryx_u32(&x475, &x476, 0x0, x467, x443); + uint32_t x477; + fiat_p256_uint1 x478; + fiat_p256_addcarryx_u32(&x477, &x478, x476, x469, x445); + uint32_t x479; + fiat_p256_uint1 x480; + fiat_p256_addcarryx_u32(&x479, &x480, x478, x471, x447); + uint32_t x481; + fiat_p256_uint1 x482; + fiat_p256_addcarryx_u32(&x481, &x482, x480, x473, x449); + uint32_t x483; + fiat_p256_uint1 x484; + fiat_p256_addcarryx_u32(&x483, &x484, x482, 0x0, x451); + uint32_t x485; + fiat_p256_uint1 x486; + fiat_p256_addcarryx_u32(&x485, &x486, x484, 0x0, x453); + uint32_t x487; + fiat_p256_uint1 x488; + fiat_p256_addcarryx_u32(&x487, &x488, x486, x443, x455); + uint32_t x489; + fiat_p256_uint1 x490; + fiat_p256_addcarryx_u32(&x489, &x490, x488, x461, x457); + uint32_t x491; + fiat_p256_uint1 x492; + fiat_p256_addcarryx_u32(&x491, &x492, x490, x462, x459); + uint32_t x493; + fiat_p256_uint1 x494; + fiat_p256_addcarryx_u32(&x493, &x494, x492, 0x0, x460); + uint32_t x495; + uint32_t x496; + fiat_p256_mulx_u32(&x495, &x496, x6, (arg1[7])); + uint32_t x497; + uint32_t x498; + fiat_p256_mulx_u32(&x497, &x498, x6, (arg1[6])); + uint32_t x499; + uint32_t x500; + fiat_p256_mulx_u32(&x499, &x500, x6, (arg1[5])); + uint32_t x501; + uint32_t x502; + fiat_p256_mulx_u32(&x501, &x502, x6, (arg1[4])); + uint32_t x503; + uint32_t x504; + fiat_p256_mulx_u32(&x503, &x504, x6, (arg1[3])); + uint32_t x505; + uint32_t x506; + fiat_p256_mulx_u32(&x505, &x506, x6, (arg1[2])); + uint32_t x507; + uint32_t x508; + fiat_p256_mulx_u32(&x507, &x508, x6, (arg1[1])); + uint32_t x509; + uint32_t x510; + fiat_p256_mulx_u32(&x509, &x510, x6, (arg1[0])); + uint32_t x511; + fiat_p256_uint1 x512; + fiat_p256_addcarryx_u32(&x511, &x512, 0x0, x507, x510); + uint32_t x513; + fiat_p256_uint1 x514; + fiat_p256_addcarryx_u32(&x513, &x514, x512, x505, x508); + uint32_t x515; + fiat_p256_uint1 x516; + fiat_p256_addcarryx_u32(&x515, &x516, x514, x503, x506); + uint32_t x517; + fiat_p256_uint1 x518; + fiat_p256_addcarryx_u32(&x517, &x518, x516, x501, x504); + uint32_t x519; + fiat_p256_uint1 x520; + fiat_p256_addcarryx_u32(&x519, &x520, x518, x499, x502); + uint32_t x521; + fiat_p256_uint1 x522; + fiat_p256_addcarryx_u32(&x521, &x522, x520, x497, x500); + uint32_t x523; + fiat_p256_uint1 x524; + fiat_p256_addcarryx_u32(&x523, &x524, x522, x495, x498); + uint32_t x525; + fiat_p256_uint1 x526; + fiat_p256_addcarryx_u32(&x525, &x526, x524, 0x0, x496); + uint32_t x527; + fiat_p256_uint1 x528; + fiat_p256_addcarryx_u32(&x527, &x528, 0x0, x509, x477); + uint32_t x529; + fiat_p256_uint1 x530; + fiat_p256_addcarryx_u32(&x529, &x530, x528, x511, x479); + uint32_t x531; + fiat_p256_uint1 x532; + fiat_p256_addcarryx_u32(&x531, &x532, x530, x513, x481); + uint32_t x533; + fiat_p256_uint1 x534; + fiat_p256_addcarryx_u32(&x533, &x534, x532, x515, x483); + uint32_t x535; + fiat_p256_uint1 x536; + fiat_p256_addcarryx_u32(&x535, &x536, x534, x517, x485); + uint32_t x537; + fiat_p256_uint1 x538; + fiat_p256_addcarryx_u32(&x537, &x538, x536, x519, x487); + uint32_t x539; + fiat_p256_uint1 x540; + fiat_p256_addcarryx_u32(&x539, &x540, x538, x521, x489); + uint32_t x541; + fiat_p256_uint1 x542; + fiat_p256_addcarryx_u32(&x541, &x542, x540, x523, x491); + uint32_t x543; + fiat_p256_uint1 x544; + fiat_p256_addcarryx_u32(&x543, &x544, x542, x525, x493); + uint32_t x545; + uint32_t x546; + fiat_p256_mulx_u32(&x545, &x546, x527, UINT32_C(0xffffffff)); + uint32_t x547; + uint32_t x548; + fiat_p256_mulx_u32(&x547, &x548, x527, UINT32_C(0xffffffff)); + uint32_t x549; + uint32_t x550; + fiat_p256_mulx_u32(&x549, &x550, x527, UINT32_C(0xffffffff)); + uint32_t x551; + uint32_t x552; + fiat_p256_mulx_u32(&x551, &x552, x527, UINT32_C(0xffffffff)); + uint32_t x553; + fiat_p256_uint1 x554; + fiat_p256_addcarryx_u32(&x553, &x554, 0x0, x549, x552); + uint32_t x555; + fiat_p256_uint1 x556; + fiat_p256_addcarryx_u32(&x555, &x556, x554, x547, x550); + uint32_t x557; + fiat_p256_uint1 x558; + fiat_p256_addcarryx_u32(&x557, &x558, x556, 0x0, x548); + uint32_t x559; + fiat_p256_uint1 x560; + fiat_p256_addcarryx_u32(&x559, &x560, 0x0, x551, x527); + uint32_t x561; + fiat_p256_uint1 x562; + fiat_p256_addcarryx_u32(&x561, &x562, x560, x553, x529); + uint32_t x563; + fiat_p256_uint1 x564; + fiat_p256_addcarryx_u32(&x563, &x564, x562, x555, x531); + uint32_t x565; + fiat_p256_uint1 x566; + fiat_p256_addcarryx_u32(&x565, &x566, x564, x557, x533); + uint32_t x567; + fiat_p256_uint1 x568; + fiat_p256_addcarryx_u32(&x567, &x568, x566, 0x0, x535); + uint32_t x569; + fiat_p256_uint1 x570; + fiat_p256_addcarryx_u32(&x569, &x570, x568, 0x0, x537); + uint32_t x571; + fiat_p256_uint1 x572; + fiat_p256_addcarryx_u32(&x571, &x572, x570, x527, x539); + uint32_t x573; + fiat_p256_uint1 x574; + fiat_p256_addcarryx_u32(&x573, &x574, x572, x545, x541); + uint32_t x575; + fiat_p256_uint1 x576; + fiat_p256_addcarryx_u32(&x575, &x576, x574, x546, x543); + uint32_t x577; + fiat_p256_uint1 x578; + fiat_p256_addcarryx_u32(&x577, &x578, x576, 0x0, x544); + uint32_t x579; + uint32_t x580; + fiat_p256_mulx_u32(&x579, &x580, x7, (arg1[7])); + uint32_t x581; + uint32_t x582; + fiat_p256_mulx_u32(&x581, &x582, x7, (arg1[6])); + uint32_t x583; + uint32_t x584; + fiat_p256_mulx_u32(&x583, &x584, x7, (arg1[5])); + uint32_t x585; + uint32_t x586; + fiat_p256_mulx_u32(&x585, &x586, x7, (arg1[4])); + uint32_t x587; + uint32_t x588; + fiat_p256_mulx_u32(&x587, &x588, x7, (arg1[3])); + uint32_t x589; + uint32_t x590; + fiat_p256_mulx_u32(&x589, &x590, x7, (arg1[2])); + uint32_t x591; + uint32_t x592; + fiat_p256_mulx_u32(&x591, &x592, x7, (arg1[1])); + uint32_t x593; + uint32_t x594; + fiat_p256_mulx_u32(&x593, &x594, x7, (arg1[0])); + uint32_t x595; + fiat_p256_uint1 x596; + fiat_p256_addcarryx_u32(&x595, &x596, 0x0, x591, x594); + uint32_t x597; + fiat_p256_uint1 x598; + fiat_p256_addcarryx_u32(&x597, &x598, x596, x589, x592); + uint32_t x599; + fiat_p256_uint1 x600; + fiat_p256_addcarryx_u32(&x599, &x600, x598, x587, x590); + uint32_t x601; + fiat_p256_uint1 x602; + fiat_p256_addcarryx_u32(&x601, &x602, x600, x585, x588); + uint32_t x603; + fiat_p256_uint1 x604; + fiat_p256_addcarryx_u32(&x603, &x604, x602, x583, x586); + uint32_t x605; + fiat_p256_uint1 x606; + fiat_p256_addcarryx_u32(&x605, &x606, x604, x581, x584); + uint32_t x607; + fiat_p256_uint1 x608; + fiat_p256_addcarryx_u32(&x607, &x608, x606, x579, x582); + uint32_t x609; + fiat_p256_uint1 x610; + fiat_p256_addcarryx_u32(&x609, &x610, x608, 0x0, x580); + uint32_t x611; + fiat_p256_uint1 x612; + fiat_p256_addcarryx_u32(&x611, &x612, 0x0, x593, x561); + uint32_t x613; + fiat_p256_uint1 x614; + fiat_p256_addcarryx_u32(&x613, &x614, x612, x595, x563); + uint32_t x615; + fiat_p256_uint1 x616; + fiat_p256_addcarryx_u32(&x615, &x616, x614, x597, x565); + uint32_t x617; + fiat_p256_uint1 x618; + fiat_p256_addcarryx_u32(&x617, &x618, x616, x599, x567); + uint32_t x619; + fiat_p256_uint1 x620; + fiat_p256_addcarryx_u32(&x619, &x620, x618, x601, x569); + uint32_t x621; + fiat_p256_uint1 x622; + fiat_p256_addcarryx_u32(&x621, &x622, x620, x603, x571); + uint32_t x623; + fiat_p256_uint1 x624; + fiat_p256_addcarryx_u32(&x623, &x624, x622, x605, x573); + uint32_t x625; + fiat_p256_uint1 x626; + fiat_p256_addcarryx_u32(&x625, &x626, x624, x607, x575); + uint32_t x627; + fiat_p256_uint1 x628; + fiat_p256_addcarryx_u32(&x627, &x628, x626, x609, x577); + uint32_t x629; + uint32_t x630; + fiat_p256_mulx_u32(&x629, &x630, x611, UINT32_C(0xffffffff)); + uint32_t x631; + uint32_t x632; + fiat_p256_mulx_u32(&x631, &x632, x611, UINT32_C(0xffffffff)); + uint32_t x633; + uint32_t x634; + fiat_p256_mulx_u32(&x633, &x634, x611, UINT32_C(0xffffffff)); + uint32_t x635; + uint32_t x636; + fiat_p256_mulx_u32(&x635, &x636, x611, UINT32_C(0xffffffff)); + uint32_t x637; + fiat_p256_uint1 x638; + fiat_p256_addcarryx_u32(&x637, &x638, 0x0, x633, x636); + uint32_t x639; + fiat_p256_uint1 x640; + fiat_p256_addcarryx_u32(&x639, &x640, x638, x631, x634); + uint32_t x641; + fiat_p256_uint1 x642; + fiat_p256_addcarryx_u32(&x641, &x642, x640, 0x0, x632); + uint32_t x643; + fiat_p256_uint1 x644; + fiat_p256_addcarryx_u32(&x643, &x644, 0x0, x635, x611); + uint32_t x645; + fiat_p256_uint1 x646; + fiat_p256_addcarryx_u32(&x645, &x646, x644, x637, x613); + uint32_t x647; + fiat_p256_uint1 x648; + fiat_p256_addcarryx_u32(&x647, &x648, x646, x639, x615); + uint32_t x649; + fiat_p256_uint1 x650; + fiat_p256_addcarryx_u32(&x649, &x650, x648, x641, x617); + uint32_t x651; + fiat_p256_uint1 x652; + fiat_p256_addcarryx_u32(&x651, &x652, x650, 0x0, x619); + uint32_t x653; + fiat_p256_uint1 x654; + fiat_p256_addcarryx_u32(&x653, &x654, x652, 0x0, x621); + uint32_t x655; + fiat_p256_uint1 x656; + fiat_p256_addcarryx_u32(&x655, &x656, x654, x611, x623); + uint32_t x657; + fiat_p256_uint1 x658; + fiat_p256_addcarryx_u32(&x657, &x658, x656, x629, x625); + uint32_t x659; + fiat_p256_uint1 x660; + fiat_p256_addcarryx_u32(&x659, &x660, x658, x630, x627); + uint32_t x661; + fiat_p256_uint1 x662; + fiat_p256_addcarryx_u32(&x661, &x662, x660, 0x0, x628); + uint32_t x663; + fiat_p256_uint1 x664; + fiat_p256_subborrowx_u32(&x663, &x664, 0x0, x645, UINT32_C(0xffffffff)); + uint32_t x665; + fiat_p256_uint1 x666; + fiat_p256_subborrowx_u32(&x665, &x666, x664, x647, UINT32_C(0xffffffff)); + uint32_t x667; + fiat_p256_uint1 x668; + fiat_p256_subborrowx_u32(&x667, &x668, x666, x649, UINT32_C(0xffffffff)); + uint32_t x669; + fiat_p256_uint1 x670; + fiat_p256_subborrowx_u32(&x669, &x670, x668, x651, 0x0); + uint32_t x671; + fiat_p256_uint1 x672; + fiat_p256_subborrowx_u32(&x671, &x672, x670, x653, 0x0); + uint32_t x673; + fiat_p256_uint1 x674; + fiat_p256_subborrowx_u32(&x673, &x674, x672, x655, 0x0); + uint32_t x675; + fiat_p256_uint1 x676; + fiat_p256_subborrowx_u32(&x675, &x676, x674, x657, 0x1); + uint32_t x677; + fiat_p256_uint1 x678; + fiat_p256_subborrowx_u32(&x677, &x678, x676, x659, UINT32_C(0xffffffff)); + uint32_t x679; + fiat_p256_uint1 x680; + fiat_p256_subborrowx_u32(&x679, &x680, x678, x661, 0x0); + uint32_t x681; + fiat_p256_cmovznz_u32(&x681, x680, x663, x645); + uint32_t x682; + fiat_p256_cmovznz_u32(&x682, x680, x665, x647); + uint32_t x683; + fiat_p256_cmovznz_u32(&x683, x680, x667, x649); + uint32_t x684; + fiat_p256_cmovznz_u32(&x684, x680, x669, x651); + uint32_t x685; + fiat_p256_cmovznz_u32(&x685, x680, x671, x653); + uint32_t x686; + fiat_p256_cmovznz_u32(&x686, x680, x673, x655); + uint32_t x687; + fiat_p256_cmovznz_u32(&x687, x680, x675, x657); + uint32_t x688; + fiat_p256_cmovznz_u32(&x688, x680, x677, x659); + out1[0] = x681; + out1[1] = x682; + out1[2] = x683; + out1[3] = x684; + out1[4] = x685; + out1[5] = x686; + out1[6] = x687; + out1[7] = x688; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + * arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + */ +static void fiat_p256_add(uint32_t out1[8], const uint32_t arg1[8], const uint32_t arg2[8]) { + uint32_t x1; + fiat_p256_uint1 x2; + fiat_p256_addcarryx_u32(&x1, &x2, 0x0, (arg2[0]), (arg1[0])); + uint32_t x3; + fiat_p256_uint1 x4; + fiat_p256_addcarryx_u32(&x3, &x4, x2, (arg2[1]), (arg1[1])); + uint32_t x5; + fiat_p256_uint1 x6; + fiat_p256_addcarryx_u32(&x5, &x6, x4, (arg2[2]), (arg1[2])); + uint32_t x7; + fiat_p256_uint1 x8; + fiat_p256_addcarryx_u32(&x7, &x8, x6, (arg2[3]), (arg1[3])); + uint32_t x9; + fiat_p256_uint1 x10; + fiat_p256_addcarryx_u32(&x9, &x10, x8, (arg2[4]), (arg1[4])); + uint32_t x11; + fiat_p256_uint1 x12; + fiat_p256_addcarryx_u32(&x11, &x12, x10, (arg2[5]), (arg1[5])); + uint32_t x13; + fiat_p256_uint1 x14; + fiat_p256_addcarryx_u32(&x13, &x14, x12, (arg2[6]), (arg1[6])); + uint32_t x15; + fiat_p256_uint1 x16; + fiat_p256_addcarryx_u32(&x15, &x16, x14, (arg2[7]), (arg1[7])); + uint32_t x17; + fiat_p256_uint1 x18; + fiat_p256_subborrowx_u32(&x17, &x18, 0x0, x1, UINT32_C(0xffffffff)); + uint32_t x19; + fiat_p256_uint1 x20; + fiat_p256_subborrowx_u32(&x19, &x20, x18, x3, UINT32_C(0xffffffff)); + uint32_t x21; + fiat_p256_uint1 x22; + fiat_p256_subborrowx_u32(&x21, &x22, x20, x5, UINT32_C(0xffffffff)); + uint32_t x23; + fiat_p256_uint1 x24; + fiat_p256_subborrowx_u32(&x23, &x24, x22, x7, 0x0); + uint32_t x25; + fiat_p256_uint1 x26; + fiat_p256_subborrowx_u32(&x25, &x26, x24, x9, 0x0); + uint32_t x27; + fiat_p256_uint1 x28; + fiat_p256_subborrowx_u32(&x27, &x28, x26, x11, 0x0); + uint32_t x29; + fiat_p256_uint1 x30; + fiat_p256_subborrowx_u32(&x29, &x30, x28, x13, 0x1); + uint32_t x31; + fiat_p256_uint1 x32; + fiat_p256_subborrowx_u32(&x31, &x32, x30, x15, UINT32_C(0xffffffff)); + uint32_t x33; + fiat_p256_uint1 x34; + fiat_p256_subborrowx_u32(&x33, &x34, x32, x16, 0x0); + uint32_t x35; + fiat_p256_cmovznz_u32(&x35, x34, x17, x1); + uint32_t x36; + fiat_p256_cmovznz_u32(&x36, x34, x19, x3); + uint32_t x37; + fiat_p256_cmovznz_u32(&x37, x34, x21, x5); + uint32_t x38; + fiat_p256_cmovznz_u32(&x38, x34, x23, x7); + uint32_t x39; + fiat_p256_cmovznz_u32(&x39, x34, x25, x9); + uint32_t x40; + fiat_p256_cmovznz_u32(&x40, x34, x27, x11); + uint32_t x41; + fiat_p256_cmovznz_u32(&x41, x34, x29, x13); + uint32_t x42; + fiat_p256_cmovznz_u32(&x42, x34, x31, x15); + out1[0] = x35; + out1[1] = x36; + out1[2] = x37; + out1[3] = x38; + out1[4] = x39; + out1[5] = x40; + out1[6] = x41; + out1[7] = x42; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + * arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + */ +static void fiat_p256_sub(uint32_t out1[8], const uint32_t arg1[8], const uint32_t arg2[8]) { + uint32_t x1; + fiat_p256_uint1 x2; + fiat_p256_subborrowx_u32(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); + uint32_t x3; + fiat_p256_uint1 x4; + fiat_p256_subborrowx_u32(&x3, &x4, x2, (arg1[1]), (arg2[1])); + uint32_t x5; + fiat_p256_uint1 x6; + fiat_p256_subborrowx_u32(&x5, &x6, x4, (arg1[2]), (arg2[2])); + uint32_t x7; + fiat_p256_uint1 x8; + fiat_p256_subborrowx_u32(&x7, &x8, x6, (arg1[3]), (arg2[3])); + uint32_t x9; + fiat_p256_uint1 x10; + fiat_p256_subborrowx_u32(&x9, &x10, x8, (arg1[4]), (arg2[4])); + uint32_t x11; + fiat_p256_uint1 x12; + fiat_p256_subborrowx_u32(&x11, &x12, x10, (arg1[5]), (arg2[5])); + uint32_t x13; + fiat_p256_uint1 x14; + fiat_p256_subborrowx_u32(&x13, &x14, x12, (arg1[6]), (arg2[6])); + uint32_t x15; + fiat_p256_uint1 x16; + fiat_p256_subborrowx_u32(&x15, &x16, x14, (arg1[7]), (arg2[7])); + uint32_t x17; + fiat_p256_cmovznz_u32(&x17, x16, 0x0, UINT32_C(0xffffffff)); + uint32_t x18; + fiat_p256_uint1 x19; + fiat_p256_addcarryx_u32(&x18, &x19, 0x0, (x17 & UINT32_C(0xffffffff)), x1); + uint32_t x20; + fiat_p256_uint1 x21; + fiat_p256_addcarryx_u32(&x20, &x21, x19, (x17 & UINT32_C(0xffffffff)), x3); + uint32_t x22; + fiat_p256_uint1 x23; + fiat_p256_addcarryx_u32(&x22, &x23, x21, (x17 & UINT32_C(0xffffffff)), x5); + uint32_t x24; + fiat_p256_uint1 x25; + fiat_p256_addcarryx_u32(&x24, &x25, x23, 0x0, x7); + uint32_t x26; + fiat_p256_uint1 x27; + fiat_p256_addcarryx_u32(&x26, &x27, x25, 0x0, x9); + uint32_t x28; + fiat_p256_uint1 x29; + fiat_p256_addcarryx_u32(&x28, &x29, x27, 0x0, x11); + uint32_t x30; + fiat_p256_uint1 x31; + fiat_p256_addcarryx_u32(&x30, &x31, x29, (fiat_p256_uint1)(x17 & 0x1), x13); + uint32_t x32; + fiat_p256_uint1 x33; + fiat_p256_addcarryx_u32(&x32, &x33, x31, (x17 & UINT32_C(0xffffffff)), x15); + out1[0] = x18; + out1[1] = x20; + out1[2] = x22; + out1[3] = x24; + out1[4] = x26; + out1[5] = x28; + out1[6] = x30; + out1[7] = x32; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + */ +static void fiat_p256_opp(uint32_t out1[8], const uint32_t arg1[8]) { + uint32_t x1; + fiat_p256_uint1 x2; + fiat_p256_subborrowx_u32(&x1, &x2, 0x0, 0x0, (arg1[0])); + uint32_t x3; + fiat_p256_uint1 x4; + fiat_p256_subborrowx_u32(&x3, &x4, x2, 0x0, (arg1[1])); + uint32_t x5; + fiat_p256_uint1 x6; + fiat_p256_subborrowx_u32(&x5, &x6, x4, 0x0, (arg1[2])); + uint32_t x7; + fiat_p256_uint1 x8; + fiat_p256_subborrowx_u32(&x7, &x8, x6, 0x0, (arg1[3])); + uint32_t x9; + fiat_p256_uint1 x10; + fiat_p256_subborrowx_u32(&x9, &x10, x8, 0x0, (arg1[4])); + uint32_t x11; + fiat_p256_uint1 x12; + fiat_p256_subborrowx_u32(&x11, &x12, x10, 0x0, (arg1[5])); + uint32_t x13; + fiat_p256_uint1 x14; + fiat_p256_subborrowx_u32(&x13, &x14, x12, 0x0, (arg1[6])); + uint32_t x15; + fiat_p256_uint1 x16; + fiat_p256_subborrowx_u32(&x15, &x16, x14, 0x0, (arg1[7])); + uint32_t x17; + fiat_p256_cmovznz_u32(&x17, x16, 0x0, UINT32_C(0xffffffff)); + uint32_t x18; + fiat_p256_uint1 x19; + fiat_p256_addcarryx_u32(&x18, &x19, 0x0, (x17 & UINT32_C(0xffffffff)), x1); + uint32_t x20; + fiat_p256_uint1 x21; + fiat_p256_addcarryx_u32(&x20, &x21, x19, (x17 & UINT32_C(0xffffffff)), x3); + uint32_t x22; + fiat_p256_uint1 x23; + fiat_p256_addcarryx_u32(&x22, &x23, x21, (x17 & UINT32_C(0xffffffff)), x5); + uint32_t x24; + fiat_p256_uint1 x25; + fiat_p256_addcarryx_u32(&x24, &x25, x23, 0x0, x7); + uint32_t x26; + fiat_p256_uint1 x27; + fiat_p256_addcarryx_u32(&x26, &x27, x25, 0x0, x9); + uint32_t x28; + fiat_p256_uint1 x29; + fiat_p256_addcarryx_u32(&x28, &x29, x27, 0x0, x11); + uint32_t x30; + fiat_p256_uint1 x31; + fiat_p256_addcarryx_u32(&x30, &x31, x29, (fiat_p256_uint1)(x17 & 0x1), x13); + uint32_t x32; + fiat_p256_uint1 x33; + fiat_p256_addcarryx_u32(&x32, &x33, x31, (x17 & UINT32_C(0xffffffff)), x15); + out1[0] = x18; + out1[1] = x20; + out1[2] = x22; + out1[3] = x24; + out1[4] = x26; + out1[5] = x28; + out1[6] = x30; + out1[7] = x32; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + */ +static void fiat_p256_from_montgomery(uint32_t out1[8], const uint32_t arg1[8]) { + uint32_t x1 = (arg1[0]); + uint32_t x2; + uint32_t x3; + fiat_p256_mulx_u32(&x2, &x3, x1, UINT32_C(0xffffffff)); + uint32_t x4; + uint32_t x5; + fiat_p256_mulx_u32(&x4, &x5, x1, UINT32_C(0xffffffff)); + uint32_t x6; + uint32_t x7; + fiat_p256_mulx_u32(&x6, &x7, x1, UINT32_C(0xffffffff)); + uint32_t x8; + uint32_t x9; + fiat_p256_mulx_u32(&x8, &x9, x1, UINT32_C(0xffffffff)); + uint32_t x10; + fiat_p256_uint1 x11; + fiat_p256_addcarryx_u32(&x10, &x11, 0x0, x6, x9); + uint32_t x12; + fiat_p256_uint1 x13; + fiat_p256_addcarryx_u32(&x12, &x13, x11, x4, x7); + uint32_t x14; + fiat_p256_uint1 x15; + fiat_p256_addcarryx_u32(&x14, &x15, 0x0, x8, x1); + uint32_t x16; + fiat_p256_uint1 x17; + fiat_p256_addcarryx_u32(&x16, &x17, x15, x10, 0x0); + uint32_t x18; + fiat_p256_uint1 x19; + fiat_p256_addcarryx_u32(&x18, &x19, x17, x12, 0x0); + uint32_t x20; + fiat_p256_uint1 x21; + fiat_p256_addcarryx_u32(&x20, &x21, x13, 0x0, x5); + uint32_t x22; + fiat_p256_uint1 x23; + fiat_p256_addcarryx_u32(&x22, &x23, x19, x20, 0x0); + uint32_t x24; + fiat_p256_uint1 x25; + fiat_p256_addcarryx_u32(&x24, &x25, 0x0, (arg1[1]), x16); + uint32_t x26; + fiat_p256_uint1 x27; + fiat_p256_addcarryx_u32(&x26, &x27, x25, 0x0, x18); + uint32_t x28; + fiat_p256_uint1 x29; + fiat_p256_addcarryx_u32(&x28, &x29, x27, 0x0, x22); + uint32_t x30; + uint32_t x31; + fiat_p256_mulx_u32(&x30, &x31, x24, UINT32_C(0xffffffff)); + uint32_t x32; + uint32_t x33; + fiat_p256_mulx_u32(&x32, &x33, x24, UINT32_C(0xffffffff)); + uint32_t x34; + uint32_t x35; + fiat_p256_mulx_u32(&x34, &x35, x24, UINT32_C(0xffffffff)); + uint32_t x36; + uint32_t x37; + fiat_p256_mulx_u32(&x36, &x37, x24, UINT32_C(0xffffffff)); + uint32_t x38; + fiat_p256_uint1 x39; + fiat_p256_addcarryx_u32(&x38, &x39, 0x0, x34, x37); + uint32_t x40; + fiat_p256_uint1 x41; + fiat_p256_addcarryx_u32(&x40, &x41, x39, x32, x35); + uint32_t x42; + fiat_p256_uint1 x43; + fiat_p256_addcarryx_u32(&x42, &x43, 0x0, x36, x24); + uint32_t x44; + fiat_p256_uint1 x45; + fiat_p256_addcarryx_u32(&x44, &x45, x43, x38, x26); + uint32_t x46; + fiat_p256_uint1 x47; + fiat_p256_addcarryx_u32(&x46, &x47, x45, x40, x28); + uint32_t x48; + fiat_p256_uint1 x49; + fiat_p256_addcarryx_u32(&x48, &x49, x23, 0x0, 0x0); + uint32_t x50; + fiat_p256_uint1 x51; + fiat_p256_addcarryx_u32(&x50, &x51, x29, 0x0, (fiat_p256_uint1)x48); + uint32_t x52; + fiat_p256_uint1 x53; + fiat_p256_addcarryx_u32(&x52, &x53, x41, 0x0, x33); + uint32_t x54; + fiat_p256_uint1 x55; + fiat_p256_addcarryx_u32(&x54, &x55, x47, x52, x50); + uint32_t x56; + fiat_p256_uint1 x57; + fiat_p256_addcarryx_u32(&x56, &x57, 0x0, x24, x2); + uint32_t x58; + fiat_p256_uint1 x59; + fiat_p256_addcarryx_u32(&x58, &x59, x57, x30, x3); + uint32_t x60; + fiat_p256_uint1 x61; + fiat_p256_addcarryx_u32(&x60, &x61, 0x0, (arg1[2]), x44); + uint32_t x62; + fiat_p256_uint1 x63; + fiat_p256_addcarryx_u32(&x62, &x63, x61, 0x0, x46); + uint32_t x64; + fiat_p256_uint1 x65; + fiat_p256_addcarryx_u32(&x64, &x65, x63, 0x0, x54); + uint32_t x66; + uint32_t x67; + fiat_p256_mulx_u32(&x66, &x67, x60, UINT32_C(0xffffffff)); + uint32_t x68; + uint32_t x69; + fiat_p256_mulx_u32(&x68, &x69, x60, UINT32_C(0xffffffff)); + uint32_t x70; + uint32_t x71; + fiat_p256_mulx_u32(&x70, &x71, x60, UINT32_C(0xffffffff)); + uint32_t x72; + uint32_t x73; + fiat_p256_mulx_u32(&x72, &x73, x60, UINT32_C(0xffffffff)); + uint32_t x74; + fiat_p256_uint1 x75; + fiat_p256_addcarryx_u32(&x74, &x75, 0x0, x70, x73); + uint32_t x76; + fiat_p256_uint1 x77; + fiat_p256_addcarryx_u32(&x76, &x77, x75, x68, x71); + uint32_t x78; + fiat_p256_uint1 x79; + fiat_p256_addcarryx_u32(&x78, &x79, 0x0, x72, x60); + uint32_t x80; + fiat_p256_uint1 x81; + fiat_p256_addcarryx_u32(&x80, &x81, x79, x74, x62); + uint32_t x82; + fiat_p256_uint1 x83; + fiat_p256_addcarryx_u32(&x82, &x83, x81, x76, x64); + uint32_t x84; + fiat_p256_uint1 x85; + fiat_p256_addcarryx_u32(&x84, &x85, x55, 0x0, 0x0); + uint32_t x86; + fiat_p256_uint1 x87; + fiat_p256_addcarryx_u32(&x86, &x87, x65, 0x0, (fiat_p256_uint1)x84); + uint32_t x88; + fiat_p256_uint1 x89; + fiat_p256_addcarryx_u32(&x88, &x89, x77, 0x0, x69); + uint32_t x90; + fiat_p256_uint1 x91; + fiat_p256_addcarryx_u32(&x90, &x91, x83, x88, x86); + uint32_t x92; + fiat_p256_uint1 x93; + fiat_p256_addcarryx_u32(&x92, &x93, x91, 0x0, x1); + uint32_t x94; + fiat_p256_uint1 x95; + fiat_p256_addcarryx_u32(&x94, &x95, x93, 0x0, x56); + uint32_t x96; + fiat_p256_uint1 x97; + fiat_p256_addcarryx_u32(&x96, &x97, x95, x60, x58); + uint32_t x98; + fiat_p256_uint1 x99; + fiat_p256_addcarryx_u32(&x98, &x99, x59, x31, 0x0); + uint32_t x100; + fiat_p256_uint1 x101; + fiat_p256_addcarryx_u32(&x100, &x101, x97, x66, x98); + uint32_t x102; + fiat_p256_uint1 x103; + fiat_p256_addcarryx_u32(&x102, &x103, 0x0, (arg1[3]), x80); + uint32_t x104; + fiat_p256_uint1 x105; + fiat_p256_addcarryx_u32(&x104, &x105, x103, 0x0, x82); + uint32_t x106; + fiat_p256_uint1 x107; + fiat_p256_addcarryx_u32(&x106, &x107, x105, 0x0, x90); + uint32_t x108; + fiat_p256_uint1 x109; + fiat_p256_addcarryx_u32(&x108, &x109, x107, 0x0, x92); + uint32_t x110; + fiat_p256_uint1 x111; + fiat_p256_addcarryx_u32(&x110, &x111, x109, 0x0, x94); + uint32_t x112; + fiat_p256_uint1 x113; + fiat_p256_addcarryx_u32(&x112, &x113, x111, 0x0, x96); + uint32_t x114; + fiat_p256_uint1 x115; + fiat_p256_addcarryx_u32(&x114, &x115, x113, 0x0, x100); + uint32_t x116; + fiat_p256_uint1 x117; + fiat_p256_addcarryx_u32(&x116, &x117, x101, x67, 0x0); + uint32_t x118; + fiat_p256_uint1 x119; + fiat_p256_addcarryx_u32(&x118, &x119, x115, 0x0, x116); + uint32_t x120; + uint32_t x121; + fiat_p256_mulx_u32(&x120, &x121, x102, UINT32_C(0xffffffff)); + uint32_t x122; + uint32_t x123; + fiat_p256_mulx_u32(&x122, &x123, x102, UINT32_C(0xffffffff)); + uint32_t x124; + uint32_t x125; + fiat_p256_mulx_u32(&x124, &x125, x102, UINT32_C(0xffffffff)); + uint32_t x126; + uint32_t x127; + fiat_p256_mulx_u32(&x126, &x127, x102, UINT32_C(0xffffffff)); + uint32_t x128; + fiat_p256_uint1 x129; + fiat_p256_addcarryx_u32(&x128, &x129, 0x0, x124, x127); + uint32_t x130; + fiat_p256_uint1 x131; + fiat_p256_addcarryx_u32(&x130, &x131, x129, x122, x125); + uint32_t x132; + fiat_p256_uint1 x133; + fiat_p256_addcarryx_u32(&x132, &x133, 0x0, x126, x102); + uint32_t x134; + fiat_p256_uint1 x135; + fiat_p256_addcarryx_u32(&x134, &x135, x133, x128, x104); + uint32_t x136; + fiat_p256_uint1 x137; + fiat_p256_addcarryx_u32(&x136, &x137, x135, x130, x106); + uint32_t x138; + fiat_p256_uint1 x139; + fiat_p256_addcarryx_u32(&x138, &x139, x131, 0x0, x123); + uint32_t x140; + fiat_p256_uint1 x141; + fiat_p256_addcarryx_u32(&x140, &x141, x137, x138, x108); + uint32_t x142; + fiat_p256_uint1 x143; + fiat_p256_addcarryx_u32(&x142, &x143, x141, 0x0, x110); + uint32_t x144; + fiat_p256_uint1 x145; + fiat_p256_addcarryx_u32(&x144, &x145, x143, 0x0, x112); + uint32_t x146; + fiat_p256_uint1 x147; + fiat_p256_addcarryx_u32(&x146, &x147, x145, x102, x114); + uint32_t x148; + fiat_p256_uint1 x149; + fiat_p256_addcarryx_u32(&x148, &x149, x147, x120, x118); + uint32_t x150; + fiat_p256_uint1 x151; + fiat_p256_addcarryx_u32(&x150, &x151, x119, 0x0, 0x0); + uint32_t x152; + fiat_p256_uint1 x153; + fiat_p256_addcarryx_u32(&x152, &x153, x149, x121, (fiat_p256_uint1)x150); + uint32_t x154; + fiat_p256_uint1 x155; + fiat_p256_addcarryx_u32(&x154, &x155, 0x0, (arg1[4]), x134); + uint32_t x156; + fiat_p256_uint1 x157; + fiat_p256_addcarryx_u32(&x156, &x157, x155, 0x0, x136); + uint32_t x158; + fiat_p256_uint1 x159; + fiat_p256_addcarryx_u32(&x158, &x159, x157, 0x0, x140); + uint32_t x160; + fiat_p256_uint1 x161; + fiat_p256_addcarryx_u32(&x160, &x161, x159, 0x0, x142); + uint32_t x162; + fiat_p256_uint1 x163; + fiat_p256_addcarryx_u32(&x162, &x163, x161, 0x0, x144); + uint32_t x164; + fiat_p256_uint1 x165; + fiat_p256_addcarryx_u32(&x164, &x165, x163, 0x0, x146); + uint32_t x166; + fiat_p256_uint1 x167; + fiat_p256_addcarryx_u32(&x166, &x167, x165, 0x0, x148); + uint32_t x168; + fiat_p256_uint1 x169; + fiat_p256_addcarryx_u32(&x168, &x169, x167, 0x0, x152); + uint32_t x170; + uint32_t x171; + fiat_p256_mulx_u32(&x170, &x171, x154, UINT32_C(0xffffffff)); + uint32_t x172; + uint32_t x173; + fiat_p256_mulx_u32(&x172, &x173, x154, UINT32_C(0xffffffff)); + uint32_t x174; + uint32_t x175; + fiat_p256_mulx_u32(&x174, &x175, x154, UINT32_C(0xffffffff)); + uint32_t x176; + uint32_t x177; + fiat_p256_mulx_u32(&x176, &x177, x154, UINT32_C(0xffffffff)); + uint32_t x178; + fiat_p256_uint1 x179; + fiat_p256_addcarryx_u32(&x178, &x179, 0x0, x174, x177); + uint32_t x180; + fiat_p256_uint1 x181; + fiat_p256_addcarryx_u32(&x180, &x181, x179, x172, x175); + uint32_t x182; + fiat_p256_uint1 x183; + fiat_p256_addcarryx_u32(&x182, &x183, 0x0, x176, x154); + uint32_t x184; + fiat_p256_uint1 x185; + fiat_p256_addcarryx_u32(&x184, &x185, x183, x178, x156); + uint32_t x186; + fiat_p256_uint1 x187; + fiat_p256_addcarryx_u32(&x186, &x187, x185, x180, x158); + uint32_t x188; + fiat_p256_uint1 x189; + fiat_p256_addcarryx_u32(&x188, &x189, x181, 0x0, x173); + uint32_t x190; + fiat_p256_uint1 x191; + fiat_p256_addcarryx_u32(&x190, &x191, x187, x188, x160); + uint32_t x192; + fiat_p256_uint1 x193; + fiat_p256_addcarryx_u32(&x192, &x193, x191, 0x0, x162); + uint32_t x194; + fiat_p256_uint1 x195; + fiat_p256_addcarryx_u32(&x194, &x195, x193, 0x0, x164); + uint32_t x196; + fiat_p256_uint1 x197; + fiat_p256_addcarryx_u32(&x196, &x197, x195, x154, x166); + uint32_t x198; + fiat_p256_uint1 x199; + fiat_p256_addcarryx_u32(&x198, &x199, x197, x170, x168); + uint32_t x200; + fiat_p256_uint1 x201; + fiat_p256_addcarryx_u32(&x200, &x201, x153, 0x0, 0x0); + uint32_t x202; + fiat_p256_uint1 x203; + fiat_p256_addcarryx_u32(&x202, &x203, x169, 0x0, (fiat_p256_uint1)x200); + uint32_t x204; + fiat_p256_uint1 x205; + fiat_p256_addcarryx_u32(&x204, &x205, x199, x171, x202); + uint32_t x206; + fiat_p256_uint1 x207; + fiat_p256_addcarryx_u32(&x206, &x207, 0x0, (arg1[5]), x184); + uint32_t x208; + fiat_p256_uint1 x209; + fiat_p256_addcarryx_u32(&x208, &x209, x207, 0x0, x186); + uint32_t x210; + fiat_p256_uint1 x211; + fiat_p256_addcarryx_u32(&x210, &x211, x209, 0x0, x190); + uint32_t x212; + fiat_p256_uint1 x213; + fiat_p256_addcarryx_u32(&x212, &x213, x211, 0x0, x192); + uint32_t x214; + fiat_p256_uint1 x215; + fiat_p256_addcarryx_u32(&x214, &x215, x213, 0x0, x194); + uint32_t x216; + fiat_p256_uint1 x217; + fiat_p256_addcarryx_u32(&x216, &x217, x215, 0x0, x196); + uint32_t x218; + fiat_p256_uint1 x219; + fiat_p256_addcarryx_u32(&x218, &x219, x217, 0x0, x198); + uint32_t x220; + fiat_p256_uint1 x221; + fiat_p256_addcarryx_u32(&x220, &x221, x219, 0x0, x204); + uint32_t x222; + uint32_t x223; + fiat_p256_mulx_u32(&x222, &x223, x206, UINT32_C(0xffffffff)); + uint32_t x224; + uint32_t x225; + fiat_p256_mulx_u32(&x224, &x225, x206, UINT32_C(0xffffffff)); + uint32_t x226; + uint32_t x227; + fiat_p256_mulx_u32(&x226, &x227, x206, UINT32_C(0xffffffff)); + uint32_t x228; + uint32_t x229; + fiat_p256_mulx_u32(&x228, &x229, x206, UINT32_C(0xffffffff)); + uint32_t x230; + fiat_p256_uint1 x231; + fiat_p256_addcarryx_u32(&x230, &x231, 0x0, x226, x229); + uint32_t x232; + fiat_p256_uint1 x233; + fiat_p256_addcarryx_u32(&x232, &x233, x231, x224, x227); + uint32_t x234; + fiat_p256_uint1 x235; + fiat_p256_addcarryx_u32(&x234, &x235, 0x0, x228, x206); + uint32_t x236; + fiat_p256_uint1 x237; + fiat_p256_addcarryx_u32(&x236, &x237, x235, x230, x208); + uint32_t x238; + fiat_p256_uint1 x239; + fiat_p256_addcarryx_u32(&x238, &x239, x237, x232, x210); + uint32_t x240; + fiat_p256_uint1 x241; + fiat_p256_addcarryx_u32(&x240, &x241, x233, 0x0, x225); + uint32_t x242; + fiat_p256_uint1 x243; + fiat_p256_addcarryx_u32(&x242, &x243, x239, x240, x212); + uint32_t x244; + fiat_p256_uint1 x245; + fiat_p256_addcarryx_u32(&x244, &x245, x243, 0x0, x214); + uint32_t x246; + fiat_p256_uint1 x247; + fiat_p256_addcarryx_u32(&x246, &x247, x245, 0x0, x216); + uint32_t x248; + fiat_p256_uint1 x249; + fiat_p256_addcarryx_u32(&x248, &x249, x247, x206, x218); + uint32_t x250; + fiat_p256_uint1 x251; + fiat_p256_addcarryx_u32(&x250, &x251, x249, x222, x220); + uint32_t x252; + fiat_p256_uint1 x253; + fiat_p256_addcarryx_u32(&x252, &x253, x205, 0x0, 0x0); + uint32_t x254; + fiat_p256_uint1 x255; + fiat_p256_addcarryx_u32(&x254, &x255, x221, 0x0, (fiat_p256_uint1)x252); + uint32_t x256; + fiat_p256_uint1 x257; + fiat_p256_addcarryx_u32(&x256, &x257, x251, x223, x254); + uint32_t x258; + fiat_p256_uint1 x259; + fiat_p256_addcarryx_u32(&x258, &x259, 0x0, (arg1[6]), x236); + uint32_t x260; + fiat_p256_uint1 x261; + fiat_p256_addcarryx_u32(&x260, &x261, x259, 0x0, x238); + uint32_t x262; + fiat_p256_uint1 x263; + fiat_p256_addcarryx_u32(&x262, &x263, x261, 0x0, x242); + uint32_t x264; + fiat_p256_uint1 x265; + fiat_p256_addcarryx_u32(&x264, &x265, x263, 0x0, x244); + uint32_t x266; + fiat_p256_uint1 x267; + fiat_p256_addcarryx_u32(&x266, &x267, x265, 0x0, x246); + uint32_t x268; + fiat_p256_uint1 x269; + fiat_p256_addcarryx_u32(&x268, &x269, x267, 0x0, x248); + uint32_t x270; + fiat_p256_uint1 x271; + fiat_p256_addcarryx_u32(&x270, &x271, x269, 0x0, x250); + uint32_t x272; + fiat_p256_uint1 x273; + fiat_p256_addcarryx_u32(&x272, &x273, x271, 0x0, x256); + uint32_t x274; + uint32_t x275; + fiat_p256_mulx_u32(&x274, &x275, x258, UINT32_C(0xffffffff)); + uint32_t x276; + uint32_t x277; + fiat_p256_mulx_u32(&x276, &x277, x258, UINT32_C(0xffffffff)); + uint32_t x278; + uint32_t x279; + fiat_p256_mulx_u32(&x278, &x279, x258, UINT32_C(0xffffffff)); + uint32_t x280; + uint32_t x281; + fiat_p256_mulx_u32(&x280, &x281, x258, UINT32_C(0xffffffff)); + uint32_t x282; + fiat_p256_uint1 x283; + fiat_p256_addcarryx_u32(&x282, &x283, 0x0, x278, x281); + uint32_t x284; + fiat_p256_uint1 x285; + fiat_p256_addcarryx_u32(&x284, &x285, x283, x276, x279); + uint32_t x286; + fiat_p256_uint1 x287; + fiat_p256_addcarryx_u32(&x286, &x287, 0x0, x280, x258); + uint32_t x288; + fiat_p256_uint1 x289; + fiat_p256_addcarryx_u32(&x288, &x289, x287, x282, x260); + uint32_t x290; + fiat_p256_uint1 x291; + fiat_p256_addcarryx_u32(&x290, &x291, x289, x284, x262); + uint32_t x292; + fiat_p256_uint1 x293; + fiat_p256_addcarryx_u32(&x292, &x293, x285, 0x0, x277); + uint32_t x294; + fiat_p256_uint1 x295; + fiat_p256_addcarryx_u32(&x294, &x295, x291, x292, x264); + uint32_t x296; + fiat_p256_uint1 x297; + fiat_p256_addcarryx_u32(&x296, &x297, x295, 0x0, x266); + uint32_t x298; + fiat_p256_uint1 x299; + fiat_p256_addcarryx_u32(&x298, &x299, x297, 0x0, x268); + uint32_t x300; + fiat_p256_uint1 x301; + fiat_p256_addcarryx_u32(&x300, &x301, x299, x258, x270); + uint32_t x302; + fiat_p256_uint1 x303; + fiat_p256_addcarryx_u32(&x302, &x303, x301, x274, x272); + uint32_t x304; + fiat_p256_uint1 x305; + fiat_p256_addcarryx_u32(&x304, &x305, x257, 0x0, 0x0); + uint32_t x306; + fiat_p256_uint1 x307; + fiat_p256_addcarryx_u32(&x306, &x307, x273, 0x0, (fiat_p256_uint1)x304); + uint32_t x308; + fiat_p256_uint1 x309; + fiat_p256_addcarryx_u32(&x308, &x309, x303, x275, x306); + uint32_t x310; + fiat_p256_uint1 x311; + fiat_p256_addcarryx_u32(&x310, &x311, 0x0, (arg1[7]), x288); + uint32_t x312; + fiat_p256_uint1 x313; + fiat_p256_addcarryx_u32(&x312, &x313, x311, 0x0, x290); + uint32_t x314; + fiat_p256_uint1 x315; + fiat_p256_addcarryx_u32(&x314, &x315, x313, 0x0, x294); + uint32_t x316; + fiat_p256_uint1 x317; + fiat_p256_addcarryx_u32(&x316, &x317, x315, 0x0, x296); + uint32_t x318; + fiat_p256_uint1 x319; + fiat_p256_addcarryx_u32(&x318, &x319, x317, 0x0, x298); + uint32_t x320; + fiat_p256_uint1 x321; + fiat_p256_addcarryx_u32(&x320, &x321, x319, 0x0, x300); + uint32_t x322; + fiat_p256_uint1 x323; + fiat_p256_addcarryx_u32(&x322, &x323, x321, 0x0, x302); + uint32_t x324; + fiat_p256_uint1 x325; + fiat_p256_addcarryx_u32(&x324, &x325, x323, 0x0, x308); + uint32_t x326; + uint32_t x327; + fiat_p256_mulx_u32(&x326, &x327, x310, UINT32_C(0xffffffff)); + uint32_t x328; + uint32_t x329; + fiat_p256_mulx_u32(&x328, &x329, x310, UINT32_C(0xffffffff)); + uint32_t x330; + uint32_t x331; + fiat_p256_mulx_u32(&x330, &x331, x310, UINT32_C(0xffffffff)); + uint32_t x332; + uint32_t x333; + fiat_p256_mulx_u32(&x332, &x333, x310, UINT32_C(0xffffffff)); + uint32_t x334; + fiat_p256_uint1 x335; + fiat_p256_addcarryx_u32(&x334, &x335, 0x0, x330, x333); + uint32_t x336; + fiat_p256_uint1 x337; + fiat_p256_addcarryx_u32(&x336, &x337, x335, x328, x331); + uint32_t x338; + fiat_p256_uint1 x339; + fiat_p256_addcarryx_u32(&x338, &x339, 0x0, x332, x310); + uint32_t x340; + fiat_p256_uint1 x341; + fiat_p256_addcarryx_u32(&x340, &x341, x339, x334, x312); + uint32_t x342; + fiat_p256_uint1 x343; + fiat_p256_addcarryx_u32(&x342, &x343, x341, x336, x314); + uint32_t x344; + fiat_p256_uint1 x345; + fiat_p256_addcarryx_u32(&x344, &x345, x337, 0x0, x329); + uint32_t x346; + fiat_p256_uint1 x347; + fiat_p256_addcarryx_u32(&x346, &x347, x343, x344, x316); + uint32_t x348; + fiat_p256_uint1 x349; + fiat_p256_addcarryx_u32(&x348, &x349, x347, 0x0, x318); + uint32_t x350; + fiat_p256_uint1 x351; + fiat_p256_addcarryx_u32(&x350, &x351, x349, 0x0, x320); + uint32_t x352; + fiat_p256_uint1 x353; + fiat_p256_addcarryx_u32(&x352, &x353, x351, x310, x322); + uint32_t x354; + fiat_p256_uint1 x355; + fiat_p256_addcarryx_u32(&x354, &x355, x353, x326, x324); + uint32_t x356; + fiat_p256_uint1 x357; + fiat_p256_addcarryx_u32(&x356, &x357, x309, 0x0, 0x0); + uint32_t x358; + fiat_p256_uint1 x359; + fiat_p256_addcarryx_u32(&x358, &x359, x325, 0x0, (fiat_p256_uint1)x356); + uint32_t x360; + fiat_p256_uint1 x361; + fiat_p256_addcarryx_u32(&x360, &x361, x355, x327, x358); + uint32_t x362; + fiat_p256_uint1 x363; + fiat_p256_subborrowx_u32(&x362, &x363, 0x0, x340, UINT32_C(0xffffffff)); + uint32_t x364; + fiat_p256_uint1 x365; + fiat_p256_subborrowx_u32(&x364, &x365, x363, x342, UINT32_C(0xffffffff)); + uint32_t x366; + fiat_p256_uint1 x367; + fiat_p256_subborrowx_u32(&x366, &x367, x365, x346, UINT32_C(0xffffffff)); + uint32_t x368; + fiat_p256_uint1 x369; + fiat_p256_subborrowx_u32(&x368, &x369, x367, x348, 0x0); + uint32_t x370; + fiat_p256_uint1 x371; + fiat_p256_subborrowx_u32(&x370, &x371, x369, x350, 0x0); + uint32_t x372; + fiat_p256_uint1 x373; + fiat_p256_subborrowx_u32(&x372, &x373, x371, x352, 0x0); + uint32_t x374; + fiat_p256_uint1 x375; + fiat_p256_subborrowx_u32(&x374, &x375, x373, x354, 0x1); + uint32_t x376; + fiat_p256_uint1 x377; + fiat_p256_subborrowx_u32(&x376, &x377, x375, x360, UINT32_C(0xffffffff)); + uint32_t x378; + fiat_p256_uint1 x379; + fiat_p256_addcarryx_u32(&x378, &x379, x361, 0x0, 0x0); + uint32_t x380; + fiat_p256_uint1 x381; + fiat_p256_subborrowx_u32(&x380, &x381, x377, (fiat_p256_uint1)x378, 0x0); + uint32_t x382; + fiat_p256_cmovznz_u32(&x382, x381, x362, x340); + uint32_t x383; + fiat_p256_cmovznz_u32(&x383, x381, x364, x342); + uint32_t x384; + fiat_p256_cmovznz_u32(&x384, x381, x366, x346); + uint32_t x385; + fiat_p256_cmovznz_u32(&x385, x381, x368, x348); + uint32_t x386; + fiat_p256_cmovznz_u32(&x386, x381, x370, x350); + uint32_t x387; + fiat_p256_cmovznz_u32(&x387, x381, x372, x352); + uint32_t x388; + fiat_p256_cmovznz_u32(&x388, x381, x374, x354); + uint32_t x389; + fiat_p256_cmovznz_u32(&x389, x381, x376, x360); + out1[0] = x382; + out1[1] = x383; + out1[2] = x384; + out1[3] = x385; + out1[4] = x386; + out1[5] = x387; + out1[6] = x388; + out1[7] = x389; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + * Output Bounds: + * out1: [0x0 ~> 0xffffffff] + */ +static void fiat_p256_nonzero(uint32_t* out1, const uint32_t arg1[8]) { + uint32_t x1 = ((arg1[0]) | ((arg1[1]) | ((arg1[2]) | ((arg1[3]) | ((arg1[4]) | ((arg1[5]) | ((arg1[6]) | ((arg1[7]) | (uint32_t)0x0)))))))); + *out1 = x1; +} + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + * arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + */ +static void fiat_p256_selectznz(uint32_t out1[8], fiat_p256_uint1 arg1, const uint32_t arg2[8], const uint32_t arg3[8]) { + uint32_t x1; + fiat_p256_cmovznz_u32(&x1, arg1, (arg2[0]), (arg3[0])); + uint32_t x2; + fiat_p256_cmovznz_u32(&x2, arg1, (arg2[1]), (arg3[1])); + uint32_t x3; + fiat_p256_cmovznz_u32(&x3, arg1, (arg2[2]), (arg3[2])); + uint32_t x4; + fiat_p256_cmovznz_u32(&x4, arg1, (arg2[3]), (arg3[3])); + uint32_t x5; + fiat_p256_cmovznz_u32(&x5, arg1, (arg2[4]), (arg3[4])); + uint32_t x6; + fiat_p256_cmovznz_u32(&x6, arg1, (arg2[5]), (arg3[5])); + uint32_t x7; + fiat_p256_cmovznz_u32(&x7, arg1, (arg2[6]), (arg3[6])); + uint32_t x8; + fiat_p256_cmovznz_u32(&x8, arg1, (arg2[7]), (arg3[7])); + out1[0] = x1; + out1[1] = x2; + out1[2] = x3; + out1[3] = x4; + out1[4] = x5; + out1[5] = x6; + out1[6] = x7; + out1[7] = x8; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] + */ +static void fiat_p256_to_bytes(uint8_t out1[32], const uint32_t arg1[8]) { + uint32_t x1 = (arg1[7]); + uint32_t x2 = (arg1[6]); + uint32_t x3 = (arg1[5]); + uint32_t x4 = (arg1[4]); + uint32_t x5 = (arg1[3]); + uint32_t x6 = (arg1[2]); + uint32_t x7 = (arg1[1]); + uint32_t x8 = (arg1[0]); + uint32_t x9 = (x8 >> 8); + uint8_t x10 = (uint8_t)(x8 & UINT8_C(0xff)); + uint32_t x11 = (x9 >> 8); + uint8_t x12 = (uint8_t)(x9 & UINT8_C(0xff)); + uint8_t x13 = (uint8_t)(x11 >> 8); + uint8_t x14 = (uint8_t)(x11 & UINT8_C(0xff)); + uint8_t x15 = (uint8_t)(x13 & UINT8_C(0xff)); + uint32_t x16 = (x7 >> 8); + uint8_t x17 = (uint8_t)(x7 & UINT8_C(0xff)); + uint32_t x18 = (x16 >> 8); + uint8_t x19 = (uint8_t)(x16 & UINT8_C(0xff)); + uint8_t x20 = (uint8_t)(x18 >> 8); + uint8_t x21 = (uint8_t)(x18 & UINT8_C(0xff)); + uint8_t x22 = (uint8_t)(x20 & UINT8_C(0xff)); + uint32_t x23 = (x6 >> 8); + uint8_t x24 = (uint8_t)(x6 & UINT8_C(0xff)); + uint32_t x25 = (x23 >> 8); + uint8_t x26 = (uint8_t)(x23 & UINT8_C(0xff)); + uint8_t x27 = (uint8_t)(x25 >> 8); + uint8_t x28 = (uint8_t)(x25 & UINT8_C(0xff)); + uint8_t x29 = (uint8_t)(x27 & UINT8_C(0xff)); + uint32_t x30 = (x5 >> 8); + uint8_t x31 = (uint8_t)(x5 & UINT8_C(0xff)); + uint32_t x32 = (x30 >> 8); + uint8_t x33 = (uint8_t)(x30 & UINT8_C(0xff)); + uint8_t x34 = (uint8_t)(x32 >> 8); + uint8_t x35 = (uint8_t)(x32 & UINT8_C(0xff)); + uint8_t x36 = (uint8_t)(x34 & UINT8_C(0xff)); + uint32_t x37 = (x4 >> 8); + uint8_t x38 = (uint8_t)(x4 & UINT8_C(0xff)); + uint32_t x39 = (x37 >> 8); + uint8_t x40 = (uint8_t)(x37 & UINT8_C(0xff)); + uint8_t x41 = (uint8_t)(x39 >> 8); + uint8_t x42 = (uint8_t)(x39 & UINT8_C(0xff)); + uint8_t x43 = (uint8_t)(x41 & UINT8_C(0xff)); + uint32_t x44 = (x3 >> 8); + uint8_t x45 = (uint8_t)(x3 & UINT8_C(0xff)); + uint32_t x46 = (x44 >> 8); + uint8_t x47 = (uint8_t)(x44 & UINT8_C(0xff)); + uint8_t x48 = (uint8_t)(x46 >> 8); + uint8_t x49 = (uint8_t)(x46 & UINT8_C(0xff)); + uint8_t x50 = (uint8_t)(x48 & UINT8_C(0xff)); + uint32_t x51 = (x2 >> 8); + uint8_t x52 = (uint8_t)(x2 & UINT8_C(0xff)); + uint32_t x53 = (x51 >> 8); + uint8_t x54 = (uint8_t)(x51 & UINT8_C(0xff)); + uint8_t x55 = (uint8_t)(x53 >> 8); + uint8_t x56 = (uint8_t)(x53 & UINT8_C(0xff)); + uint8_t x57 = (uint8_t)(x55 & UINT8_C(0xff)); + uint32_t x58 = (x1 >> 8); + uint8_t x59 = (uint8_t)(x1 & UINT8_C(0xff)); + uint32_t x60 = (x58 >> 8); + uint8_t x61 = (uint8_t)(x58 & UINT8_C(0xff)); + uint8_t x62 = (uint8_t)(x60 >> 8); + uint8_t x63 = (uint8_t)(x60 & UINT8_C(0xff)); + out1[0] = x10; + out1[1] = x12; + out1[2] = x14; + out1[3] = x15; + out1[4] = x17; + out1[5] = x19; + out1[6] = x21; + out1[7] = x22; + out1[8] = x24; + out1[9] = x26; + out1[10] = x28; + out1[11] = x29; + out1[12] = x31; + out1[13] = x33; + out1[14] = x35; + out1[15] = x36; + out1[16] = x38; + out1[17] = x40; + out1[18] = x42; + out1[19] = x43; + out1[20] = x45; + out1[21] = x47; + out1[22] = x49; + out1[23] = x50; + out1[24] = x52; + out1[25] = x54; + out1[26] = x56; + out1[27] = x57; + out1[28] = x59; + out1[29] = x61; + out1[30] = x63; + out1[31] = x62; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] + */ +static void fiat_p256_from_bytes(uint32_t out1[8], const uint8_t arg1[32]) { + uint32_t x1 = ((uint32_t)(arg1[31]) << 24); + uint32_t x2 = ((uint32_t)(arg1[30]) << 16); + uint32_t x3 = ((uint32_t)(arg1[29]) << 8); + uint8_t x4 = (arg1[28]); + uint32_t x5 = ((uint32_t)(arg1[27]) << 24); + uint32_t x6 = ((uint32_t)(arg1[26]) << 16); + uint32_t x7 = ((uint32_t)(arg1[25]) << 8); + uint8_t x8 = (arg1[24]); + uint32_t x9 = ((uint32_t)(arg1[23]) << 24); + uint32_t x10 = ((uint32_t)(arg1[22]) << 16); + uint32_t x11 = ((uint32_t)(arg1[21]) << 8); + uint8_t x12 = (arg1[20]); + uint32_t x13 = ((uint32_t)(arg1[19]) << 24); + uint32_t x14 = ((uint32_t)(arg1[18]) << 16); + uint32_t x15 = ((uint32_t)(arg1[17]) << 8); + uint8_t x16 = (arg1[16]); + uint32_t x17 = ((uint32_t)(arg1[15]) << 24); + uint32_t x18 = ((uint32_t)(arg1[14]) << 16); + uint32_t x19 = ((uint32_t)(arg1[13]) << 8); + uint8_t x20 = (arg1[12]); + uint32_t x21 = ((uint32_t)(arg1[11]) << 24); + uint32_t x22 = ((uint32_t)(arg1[10]) << 16); + uint32_t x23 = ((uint32_t)(arg1[9]) << 8); + uint8_t x24 = (arg1[8]); + uint32_t x25 = ((uint32_t)(arg1[7]) << 24); + uint32_t x26 = ((uint32_t)(arg1[6]) << 16); + uint32_t x27 = ((uint32_t)(arg1[5]) << 8); + uint8_t x28 = (arg1[4]); + uint32_t x29 = ((uint32_t)(arg1[3]) << 24); + uint32_t x30 = ((uint32_t)(arg1[2]) << 16); + uint32_t x31 = ((uint32_t)(arg1[1]) << 8); + uint8_t x32 = (arg1[0]); + uint32_t x33 = (x32 + (x31 + (x30 + x29))); + uint32_t x34 = (x33 & UINT32_C(0xffffffff)); + uint32_t x35 = (x4 + (x3 + (x2 + x1))); + uint32_t x36 = (x8 + (x7 + (x6 + x5))); + uint32_t x37 = (x12 + (x11 + (x10 + x9))); + uint32_t x38 = (x16 + (x15 + (x14 + x13))); + uint32_t x39 = (x20 + (x19 + (x18 + x17))); + uint32_t x40 = (x24 + (x23 + (x22 + x21))); + uint32_t x41 = (x28 + (x27 + (x26 + x25))); + uint32_t x42 = (x41 & UINT32_C(0xffffffff)); + uint32_t x43 = (x40 & UINT32_C(0xffffffff)); + uint32_t x44 = (x39 & UINT32_C(0xffffffff)); + uint32_t x45 = (x38 & UINT32_C(0xffffffff)); + uint32_t x46 = (x37 & UINT32_C(0xffffffff)); + uint32_t x47 = (x36 & UINT32_C(0xffffffff)); + out1[0] = x34; + out1[1] = x42; + out1[2] = x43; + out1[3] = x44; + out1[4] = x45; + out1[5] = x46; + out1[6] = x47; + out1[7] = x35; +} + diff --git a/third_party/boringssl/kit/src/third_party/fiat/p256_64.h b/third_party/boringssl/kit/src/third_party/fiat/p256_64.h new file mode 100644 index 00000000..8e449c6b --- /dev/null +++ b/third_party/boringssl/kit/src/third_party/fiat/p256_64.h @@ -0,0 +1,1211 @@ +/* Autogenerated */ +/* curve description: p256 */ +/* requested operations: (all) */ +/* m = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff (from "2^256 - 2^224 + 2^192 + 2^96 - 1") */ +/* machine_wordsize = 64 (from "64") */ +/* */ +/* NOTE: In addition to the bounds specified above each function, all */ +/* functions synthesized for this Montgomery arithmetic require the */ +/* input to be strictly less than the prime modulus (m), and also */ +/* require the input to be in the unique saturated representation. */ +/* All functions also ensure that these two properties are true of */ +/* return values. */ + +#include +typedef unsigned char fiat_p256_uint1; +typedef signed char fiat_p256_int1; +typedef signed __int128 fiat_p256_int128; +typedef unsigned __int128 fiat_p256_uint128; + + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [0x0 ~> 0xffffffffffffffff] + * arg3: [0x0 ~> 0xffffffffffffffff] + * Output Bounds: + * out1: [0x0 ~> 0xffffffffffffffff] + * out2: [0x0 ~> 0x1] + */ +static void fiat_p256_addcarryx_u64(uint64_t* out1, fiat_p256_uint1* out2, fiat_p256_uint1 arg1, uint64_t arg2, uint64_t arg3) { + fiat_p256_uint128 x1 = ((arg1 + (fiat_p256_uint128)arg2) + arg3); + uint64_t x2 = (uint64_t)(x1 & UINT64_C(0xffffffffffffffff)); + fiat_p256_uint1 x3 = (fiat_p256_uint1)(x1 >> 64); + *out1 = x2; + *out2 = x3; +} + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [0x0 ~> 0xffffffffffffffff] + * arg3: [0x0 ~> 0xffffffffffffffff] + * Output Bounds: + * out1: [0x0 ~> 0xffffffffffffffff] + * out2: [0x0 ~> 0x1] + */ +static void fiat_p256_subborrowx_u64(uint64_t* out1, fiat_p256_uint1* out2, fiat_p256_uint1 arg1, uint64_t arg2, uint64_t arg3) { + fiat_p256_int128 x1 = ((arg2 - (fiat_p256_int128)arg1) - arg3); + fiat_p256_int1 x2 = (fiat_p256_int1)(x1 >> 64); + uint64_t x3 = (uint64_t)(x1 & UINT64_C(0xffffffffffffffff)); + *out1 = x3; + *out2 = (fiat_p256_uint1)(0x0 - x2); +} + +/* + * Input Bounds: + * arg1: [0x0 ~> 0xffffffffffffffff] + * arg2: [0x0 ~> 0xffffffffffffffff] + * Output Bounds: + * out1: [0x0 ~> 0xffffffffffffffff] + * out2: [0x0 ~> 0xffffffffffffffff] + */ +static void fiat_p256_mulx_u64(uint64_t* out1, uint64_t* out2, uint64_t arg1, uint64_t arg2) { + fiat_p256_uint128 x1 = ((fiat_p256_uint128)arg1 * arg2); + uint64_t x2 = (uint64_t)(x1 & UINT64_C(0xffffffffffffffff)); + uint64_t x3 = (uint64_t)(x1 >> 64); + *out1 = x2; + *out2 = x3; +} + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [0x0 ~> 0xffffffffffffffff] + * arg3: [0x0 ~> 0xffffffffffffffff] + * Output Bounds: + * out1: [0x0 ~> 0xffffffffffffffff] + */ +static void fiat_p256_cmovznz_u64(uint64_t* out1, fiat_p256_uint1 arg1, uint64_t arg2, uint64_t arg3) { + fiat_p256_uint1 x1 = (!(!arg1)); + uint64_t x2 = ((fiat_p256_int1)(0x0 - x1) & UINT64_C(0xffffffffffffffff)); + uint64_t x3 = ((x2 & arg3) | ((~x2) & arg2)); + *out1 = x3; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + * arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + */ +static void fiat_p256_mul(uint64_t out1[4], const uint64_t arg1[4], const uint64_t arg2[4]) { + uint64_t x1 = (arg1[1]); + uint64_t x2 = (arg1[2]); + uint64_t x3 = (arg1[3]); + uint64_t x4 = (arg1[0]); + uint64_t x5; + uint64_t x6; + fiat_p256_mulx_u64(&x5, &x6, x4, (arg2[3])); + uint64_t x7; + uint64_t x8; + fiat_p256_mulx_u64(&x7, &x8, x4, (arg2[2])); + uint64_t x9; + uint64_t x10; + fiat_p256_mulx_u64(&x9, &x10, x4, (arg2[1])); + uint64_t x11; + uint64_t x12; + fiat_p256_mulx_u64(&x11, &x12, x4, (arg2[0])); + uint64_t x13; + fiat_p256_uint1 x14; + fiat_p256_addcarryx_u64(&x13, &x14, 0x0, x9, x12); + uint64_t x15; + fiat_p256_uint1 x16; + fiat_p256_addcarryx_u64(&x15, &x16, x14, x7, x10); + uint64_t x17; + fiat_p256_uint1 x18; + fiat_p256_addcarryx_u64(&x17, &x18, x16, x5, x8); + uint64_t x19; + fiat_p256_uint1 x20; + fiat_p256_addcarryx_u64(&x19, &x20, x18, 0x0, x6); + uint64_t x21; + uint64_t x22; + fiat_p256_mulx_u64(&x21, &x22, x11, UINT64_C(0xffffffff00000001)); + uint64_t x23; + uint64_t x24; + fiat_p256_mulx_u64(&x23, &x24, x11, UINT32_C(0xffffffff)); + uint64_t x25; + uint64_t x26; + fiat_p256_mulx_u64(&x25, &x26, x11, UINT64_C(0xffffffffffffffff)); + uint64_t x27; + fiat_p256_uint1 x28; + fiat_p256_addcarryx_u64(&x27, &x28, 0x0, x23, x26); + uint64_t x29; + fiat_p256_uint1 x30; + fiat_p256_addcarryx_u64(&x29, &x30, x28, 0x0, x24); + uint64_t x31; + fiat_p256_uint1 x32; + fiat_p256_addcarryx_u64(&x31, &x32, 0x0, x25, x11); + uint64_t x33; + fiat_p256_uint1 x34; + fiat_p256_addcarryx_u64(&x33, &x34, x32, x27, x13); + uint64_t x35; + fiat_p256_uint1 x36; + fiat_p256_addcarryx_u64(&x35, &x36, x34, x29, x15); + uint64_t x37; + fiat_p256_uint1 x38; + fiat_p256_addcarryx_u64(&x37, &x38, x36, x21, x17); + uint64_t x39; + fiat_p256_uint1 x40; + fiat_p256_addcarryx_u64(&x39, &x40, x38, x22, x19); + uint64_t x41; + fiat_p256_uint1 x42; + fiat_p256_addcarryx_u64(&x41, &x42, x40, 0x0, 0x0); + uint64_t x43; + uint64_t x44; + fiat_p256_mulx_u64(&x43, &x44, x1, (arg2[3])); + uint64_t x45; + uint64_t x46; + fiat_p256_mulx_u64(&x45, &x46, x1, (arg2[2])); + uint64_t x47; + uint64_t x48; + fiat_p256_mulx_u64(&x47, &x48, x1, (arg2[1])); + uint64_t x49; + uint64_t x50; + fiat_p256_mulx_u64(&x49, &x50, x1, (arg2[0])); + uint64_t x51; + fiat_p256_uint1 x52; + fiat_p256_addcarryx_u64(&x51, &x52, 0x0, x47, x50); + uint64_t x53; + fiat_p256_uint1 x54; + fiat_p256_addcarryx_u64(&x53, &x54, x52, x45, x48); + uint64_t x55; + fiat_p256_uint1 x56; + fiat_p256_addcarryx_u64(&x55, &x56, x54, x43, x46); + uint64_t x57; + fiat_p256_uint1 x58; + fiat_p256_addcarryx_u64(&x57, &x58, x56, 0x0, x44); + uint64_t x59; + fiat_p256_uint1 x60; + fiat_p256_addcarryx_u64(&x59, &x60, 0x0, x49, x33); + uint64_t x61; + fiat_p256_uint1 x62; + fiat_p256_addcarryx_u64(&x61, &x62, x60, x51, x35); + uint64_t x63; + fiat_p256_uint1 x64; + fiat_p256_addcarryx_u64(&x63, &x64, x62, x53, x37); + uint64_t x65; + fiat_p256_uint1 x66; + fiat_p256_addcarryx_u64(&x65, &x66, x64, x55, x39); + uint64_t x67; + fiat_p256_uint1 x68; + fiat_p256_addcarryx_u64(&x67, &x68, x66, x57, (fiat_p256_uint1)x41); + uint64_t x69; + uint64_t x70; + fiat_p256_mulx_u64(&x69, &x70, x59, UINT64_C(0xffffffff00000001)); + uint64_t x71; + uint64_t x72; + fiat_p256_mulx_u64(&x71, &x72, x59, UINT32_C(0xffffffff)); + uint64_t x73; + uint64_t x74; + fiat_p256_mulx_u64(&x73, &x74, x59, UINT64_C(0xffffffffffffffff)); + uint64_t x75; + fiat_p256_uint1 x76; + fiat_p256_addcarryx_u64(&x75, &x76, 0x0, x71, x74); + uint64_t x77; + fiat_p256_uint1 x78; + fiat_p256_addcarryx_u64(&x77, &x78, x76, 0x0, x72); + uint64_t x79; + fiat_p256_uint1 x80; + fiat_p256_addcarryx_u64(&x79, &x80, 0x0, x73, x59); + uint64_t x81; + fiat_p256_uint1 x82; + fiat_p256_addcarryx_u64(&x81, &x82, x80, x75, x61); + uint64_t x83; + fiat_p256_uint1 x84; + fiat_p256_addcarryx_u64(&x83, &x84, x82, x77, x63); + uint64_t x85; + fiat_p256_uint1 x86; + fiat_p256_addcarryx_u64(&x85, &x86, x84, x69, x65); + uint64_t x87; + fiat_p256_uint1 x88; + fiat_p256_addcarryx_u64(&x87, &x88, x86, x70, x67); + uint64_t x89; + fiat_p256_uint1 x90; + fiat_p256_addcarryx_u64(&x89, &x90, x88, 0x0, x68); + uint64_t x91; + uint64_t x92; + fiat_p256_mulx_u64(&x91, &x92, x2, (arg2[3])); + uint64_t x93; + uint64_t x94; + fiat_p256_mulx_u64(&x93, &x94, x2, (arg2[2])); + uint64_t x95; + uint64_t x96; + fiat_p256_mulx_u64(&x95, &x96, x2, (arg2[1])); + uint64_t x97; + uint64_t x98; + fiat_p256_mulx_u64(&x97, &x98, x2, (arg2[0])); + uint64_t x99; + fiat_p256_uint1 x100; + fiat_p256_addcarryx_u64(&x99, &x100, 0x0, x95, x98); + uint64_t x101; + fiat_p256_uint1 x102; + fiat_p256_addcarryx_u64(&x101, &x102, x100, x93, x96); + uint64_t x103; + fiat_p256_uint1 x104; + fiat_p256_addcarryx_u64(&x103, &x104, x102, x91, x94); + uint64_t x105; + fiat_p256_uint1 x106; + fiat_p256_addcarryx_u64(&x105, &x106, x104, 0x0, x92); + uint64_t x107; + fiat_p256_uint1 x108; + fiat_p256_addcarryx_u64(&x107, &x108, 0x0, x97, x81); + uint64_t x109; + fiat_p256_uint1 x110; + fiat_p256_addcarryx_u64(&x109, &x110, x108, x99, x83); + uint64_t x111; + fiat_p256_uint1 x112; + fiat_p256_addcarryx_u64(&x111, &x112, x110, x101, x85); + uint64_t x113; + fiat_p256_uint1 x114; + fiat_p256_addcarryx_u64(&x113, &x114, x112, x103, x87); + uint64_t x115; + fiat_p256_uint1 x116; + fiat_p256_addcarryx_u64(&x115, &x116, x114, x105, x89); + uint64_t x117; + uint64_t x118; + fiat_p256_mulx_u64(&x117, &x118, x107, UINT64_C(0xffffffff00000001)); + uint64_t x119; + uint64_t x120; + fiat_p256_mulx_u64(&x119, &x120, x107, UINT32_C(0xffffffff)); + uint64_t x121; + uint64_t x122; + fiat_p256_mulx_u64(&x121, &x122, x107, UINT64_C(0xffffffffffffffff)); + uint64_t x123; + fiat_p256_uint1 x124; + fiat_p256_addcarryx_u64(&x123, &x124, 0x0, x119, x122); + uint64_t x125; + fiat_p256_uint1 x126; + fiat_p256_addcarryx_u64(&x125, &x126, x124, 0x0, x120); + uint64_t x127; + fiat_p256_uint1 x128; + fiat_p256_addcarryx_u64(&x127, &x128, 0x0, x121, x107); + uint64_t x129; + fiat_p256_uint1 x130; + fiat_p256_addcarryx_u64(&x129, &x130, x128, x123, x109); + uint64_t x131; + fiat_p256_uint1 x132; + fiat_p256_addcarryx_u64(&x131, &x132, x130, x125, x111); + uint64_t x133; + fiat_p256_uint1 x134; + fiat_p256_addcarryx_u64(&x133, &x134, x132, x117, x113); + uint64_t x135; + fiat_p256_uint1 x136; + fiat_p256_addcarryx_u64(&x135, &x136, x134, x118, x115); + uint64_t x137; + fiat_p256_uint1 x138; + fiat_p256_addcarryx_u64(&x137, &x138, x136, 0x0, x116); + uint64_t x139; + uint64_t x140; + fiat_p256_mulx_u64(&x139, &x140, x3, (arg2[3])); + uint64_t x141; + uint64_t x142; + fiat_p256_mulx_u64(&x141, &x142, x3, (arg2[2])); + uint64_t x143; + uint64_t x144; + fiat_p256_mulx_u64(&x143, &x144, x3, (arg2[1])); + uint64_t x145; + uint64_t x146; + fiat_p256_mulx_u64(&x145, &x146, x3, (arg2[0])); + uint64_t x147; + fiat_p256_uint1 x148; + fiat_p256_addcarryx_u64(&x147, &x148, 0x0, x143, x146); + uint64_t x149; + fiat_p256_uint1 x150; + fiat_p256_addcarryx_u64(&x149, &x150, x148, x141, x144); + uint64_t x151; + fiat_p256_uint1 x152; + fiat_p256_addcarryx_u64(&x151, &x152, x150, x139, x142); + uint64_t x153; + fiat_p256_uint1 x154; + fiat_p256_addcarryx_u64(&x153, &x154, x152, 0x0, x140); + uint64_t x155; + fiat_p256_uint1 x156; + fiat_p256_addcarryx_u64(&x155, &x156, 0x0, x145, x129); + uint64_t x157; + fiat_p256_uint1 x158; + fiat_p256_addcarryx_u64(&x157, &x158, x156, x147, x131); + uint64_t x159; + fiat_p256_uint1 x160; + fiat_p256_addcarryx_u64(&x159, &x160, x158, x149, x133); + uint64_t x161; + fiat_p256_uint1 x162; + fiat_p256_addcarryx_u64(&x161, &x162, x160, x151, x135); + uint64_t x163; + fiat_p256_uint1 x164; + fiat_p256_addcarryx_u64(&x163, &x164, x162, x153, x137); + uint64_t x165; + uint64_t x166; + fiat_p256_mulx_u64(&x165, &x166, x155, UINT64_C(0xffffffff00000001)); + uint64_t x167; + uint64_t x168; + fiat_p256_mulx_u64(&x167, &x168, x155, UINT32_C(0xffffffff)); + uint64_t x169; + uint64_t x170; + fiat_p256_mulx_u64(&x169, &x170, x155, UINT64_C(0xffffffffffffffff)); + uint64_t x171; + fiat_p256_uint1 x172; + fiat_p256_addcarryx_u64(&x171, &x172, 0x0, x167, x170); + uint64_t x173; + fiat_p256_uint1 x174; + fiat_p256_addcarryx_u64(&x173, &x174, x172, 0x0, x168); + uint64_t x175; + fiat_p256_uint1 x176; + fiat_p256_addcarryx_u64(&x175, &x176, 0x0, x169, x155); + uint64_t x177; + fiat_p256_uint1 x178; + fiat_p256_addcarryx_u64(&x177, &x178, x176, x171, x157); + uint64_t x179; + fiat_p256_uint1 x180; + fiat_p256_addcarryx_u64(&x179, &x180, x178, x173, x159); + uint64_t x181; + fiat_p256_uint1 x182; + fiat_p256_addcarryx_u64(&x181, &x182, x180, x165, x161); + uint64_t x183; + fiat_p256_uint1 x184; + fiat_p256_addcarryx_u64(&x183, &x184, x182, x166, x163); + uint64_t x185; + fiat_p256_uint1 x186; + fiat_p256_addcarryx_u64(&x185, &x186, x184, 0x0, x164); + uint64_t x187; + fiat_p256_uint1 x188; + fiat_p256_subborrowx_u64(&x187, &x188, 0x0, x177, UINT64_C(0xffffffffffffffff)); + uint64_t x189; + fiat_p256_uint1 x190; + fiat_p256_subborrowx_u64(&x189, &x190, x188, x179, UINT32_C(0xffffffff)); + uint64_t x191; + fiat_p256_uint1 x192; + fiat_p256_subborrowx_u64(&x191, &x192, x190, x181, 0x0); + uint64_t x193; + fiat_p256_uint1 x194; + fiat_p256_subborrowx_u64(&x193, &x194, x192, x183, UINT64_C(0xffffffff00000001)); + uint64_t x195; + fiat_p256_uint1 x196; + fiat_p256_subborrowx_u64(&x195, &x196, x194, x185, 0x0); + uint64_t x197; + fiat_p256_cmovznz_u64(&x197, x196, x187, x177); + uint64_t x198; + fiat_p256_cmovznz_u64(&x198, x196, x189, x179); + uint64_t x199; + fiat_p256_cmovznz_u64(&x199, x196, x191, x181); + uint64_t x200; + fiat_p256_cmovznz_u64(&x200, x196, x193, x183); + out1[0] = x197; + out1[1] = x198; + out1[2] = x199; + out1[3] = x200; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + */ +static void fiat_p256_square(uint64_t out1[4], const uint64_t arg1[4]) { + uint64_t x1 = (arg1[1]); + uint64_t x2 = (arg1[2]); + uint64_t x3 = (arg1[3]); + uint64_t x4 = (arg1[0]); + uint64_t x5; + uint64_t x6; + fiat_p256_mulx_u64(&x5, &x6, x4, (arg1[3])); + uint64_t x7; + uint64_t x8; + fiat_p256_mulx_u64(&x7, &x8, x4, (arg1[2])); + uint64_t x9; + uint64_t x10; + fiat_p256_mulx_u64(&x9, &x10, x4, (arg1[1])); + uint64_t x11; + uint64_t x12; + fiat_p256_mulx_u64(&x11, &x12, x4, (arg1[0])); + uint64_t x13; + fiat_p256_uint1 x14; + fiat_p256_addcarryx_u64(&x13, &x14, 0x0, x9, x12); + uint64_t x15; + fiat_p256_uint1 x16; + fiat_p256_addcarryx_u64(&x15, &x16, x14, x7, x10); + uint64_t x17; + fiat_p256_uint1 x18; + fiat_p256_addcarryx_u64(&x17, &x18, x16, x5, x8); + uint64_t x19; + fiat_p256_uint1 x20; + fiat_p256_addcarryx_u64(&x19, &x20, x18, 0x0, x6); + uint64_t x21; + uint64_t x22; + fiat_p256_mulx_u64(&x21, &x22, x11, UINT64_C(0xffffffff00000001)); + uint64_t x23; + uint64_t x24; + fiat_p256_mulx_u64(&x23, &x24, x11, UINT32_C(0xffffffff)); + uint64_t x25; + uint64_t x26; + fiat_p256_mulx_u64(&x25, &x26, x11, UINT64_C(0xffffffffffffffff)); + uint64_t x27; + fiat_p256_uint1 x28; + fiat_p256_addcarryx_u64(&x27, &x28, 0x0, x23, x26); + uint64_t x29; + fiat_p256_uint1 x30; + fiat_p256_addcarryx_u64(&x29, &x30, x28, 0x0, x24); + uint64_t x31; + fiat_p256_uint1 x32; + fiat_p256_addcarryx_u64(&x31, &x32, 0x0, x25, x11); + uint64_t x33; + fiat_p256_uint1 x34; + fiat_p256_addcarryx_u64(&x33, &x34, x32, x27, x13); + uint64_t x35; + fiat_p256_uint1 x36; + fiat_p256_addcarryx_u64(&x35, &x36, x34, x29, x15); + uint64_t x37; + fiat_p256_uint1 x38; + fiat_p256_addcarryx_u64(&x37, &x38, x36, x21, x17); + uint64_t x39; + fiat_p256_uint1 x40; + fiat_p256_addcarryx_u64(&x39, &x40, x38, x22, x19); + uint64_t x41; + fiat_p256_uint1 x42; + fiat_p256_addcarryx_u64(&x41, &x42, x40, 0x0, 0x0); + uint64_t x43; + uint64_t x44; + fiat_p256_mulx_u64(&x43, &x44, x1, (arg1[3])); + uint64_t x45; + uint64_t x46; + fiat_p256_mulx_u64(&x45, &x46, x1, (arg1[2])); + uint64_t x47; + uint64_t x48; + fiat_p256_mulx_u64(&x47, &x48, x1, (arg1[1])); + uint64_t x49; + uint64_t x50; + fiat_p256_mulx_u64(&x49, &x50, x1, (arg1[0])); + uint64_t x51; + fiat_p256_uint1 x52; + fiat_p256_addcarryx_u64(&x51, &x52, 0x0, x47, x50); + uint64_t x53; + fiat_p256_uint1 x54; + fiat_p256_addcarryx_u64(&x53, &x54, x52, x45, x48); + uint64_t x55; + fiat_p256_uint1 x56; + fiat_p256_addcarryx_u64(&x55, &x56, x54, x43, x46); + uint64_t x57; + fiat_p256_uint1 x58; + fiat_p256_addcarryx_u64(&x57, &x58, x56, 0x0, x44); + uint64_t x59; + fiat_p256_uint1 x60; + fiat_p256_addcarryx_u64(&x59, &x60, 0x0, x49, x33); + uint64_t x61; + fiat_p256_uint1 x62; + fiat_p256_addcarryx_u64(&x61, &x62, x60, x51, x35); + uint64_t x63; + fiat_p256_uint1 x64; + fiat_p256_addcarryx_u64(&x63, &x64, x62, x53, x37); + uint64_t x65; + fiat_p256_uint1 x66; + fiat_p256_addcarryx_u64(&x65, &x66, x64, x55, x39); + uint64_t x67; + fiat_p256_uint1 x68; + fiat_p256_addcarryx_u64(&x67, &x68, x66, x57, (fiat_p256_uint1)x41); + uint64_t x69; + uint64_t x70; + fiat_p256_mulx_u64(&x69, &x70, x59, UINT64_C(0xffffffff00000001)); + uint64_t x71; + uint64_t x72; + fiat_p256_mulx_u64(&x71, &x72, x59, UINT32_C(0xffffffff)); + uint64_t x73; + uint64_t x74; + fiat_p256_mulx_u64(&x73, &x74, x59, UINT64_C(0xffffffffffffffff)); + uint64_t x75; + fiat_p256_uint1 x76; + fiat_p256_addcarryx_u64(&x75, &x76, 0x0, x71, x74); + uint64_t x77; + fiat_p256_uint1 x78; + fiat_p256_addcarryx_u64(&x77, &x78, x76, 0x0, x72); + uint64_t x79; + fiat_p256_uint1 x80; + fiat_p256_addcarryx_u64(&x79, &x80, 0x0, x73, x59); + uint64_t x81; + fiat_p256_uint1 x82; + fiat_p256_addcarryx_u64(&x81, &x82, x80, x75, x61); + uint64_t x83; + fiat_p256_uint1 x84; + fiat_p256_addcarryx_u64(&x83, &x84, x82, x77, x63); + uint64_t x85; + fiat_p256_uint1 x86; + fiat_p256_addcarryx_u64(&x85, &x86, x84, x69, x65); + uint64_t x87; + fiat_p256_uint1 x88; + fiat_p256_addcarryx_u64(&x87, &x88, x86, x70, x67); + uint64_t x89; + fiat_p256_uint1 x90; + fiat_p256_addcarryx_u64(&x89, &x90, x88, 0x0, x68); + uint64_t x91; + uint64_t x92; + fiat_p256_mulx_u64(&x91, &x92, x2, (arg1[3])); + uint64_t x93; + uint64_t x94; + fiat_p256_mulx_u64(&x93, &x94, x2, (arg1[2])); + uint64_t x95; + uint64_t x96; + fiat_p256_mulx_u64(&x95, &x96, x2, (arg1[1])); + uint64_t x97; + uint64_t x98; + fiat_p256_mulx_u64(&x97, &x98, x2, (arg1[0])); + uint64_t x99; + fiat_p256_uint1 x100; + fiat_p256_addcarryx_u64(&x99, &x100, 0x0, x95, x98); + uint64_t x101; + fiat_p256_uint1 x102; + fiat_p256_addcarryx_u64(&x101, &x102, x100, x93, x96); + uint64_t x103; + fiat_p256_uint1 x104; + fiat_p256_addcarryx_u64(&x103, &x104, x102, x91, x94); + uint64_t x105; + fiat_p256_uint1 x106; + fiat_p256_addcarryx_u64(&x105, &x106, x104, 0x0, x92); + uint64_t x107; + fiat_p256_uint1 x108; + fiat_p256_addcarryx_u64(&x107, &x108, 0x0, x97, x81); + uint64_t x109; + fiat_p256_uint1 x110; + fiat_p256_addcarryx_u64(&x109, &x110, x108, x99, x83); + uint64_t x111; + fiat_p256_uint1 x112; + fiat_p256_addcarryx_u64(&x111, &x112, x110, x101, x85); + uint64_t x113; + fiat_p256_uint1 x114; + fiat_p256_addcarryx_u64(&x113, &x114, x112, x103, x87); + uint64_t x115; + fiat_p256_uint1 x116; + fiat_p256_addcarryx_u64(&x115, &x116, x114, x105, x89); + uint64_t x117; + uint64_t x118; + fiat_p256_mulx_u64(&x117, &x118, x107, UINT64_C(0xffffffff00000001)); + uint64_t x119; + uint64_t x120; + fiat_p256_mulx_u64(&x119, &x120, x107, UINT32_C(0xffffffff)); + uint64_t x121; + uint64_t x122; + fiat_p256_mulx_u64(&x121, &x122, x107, UINT64_C(0xffffffffffffffff)); + uint64_t x123; + fiat_p256_uint1 x124; + fiat_p256_addcarryx_u64(&x123, &x124, 0x0, x119, x122); + uint64_t x125; + fiat_p256_uint1 x126; + fiat_p256_addcarryx_u64(&x125, &x126, x124, 0x0, x120); + uint64_t x127; + fiat_p256_uint1 x128; + fiat_p256_addcarryx_u64(&x127, &x128, 0x0, x121, x107); + uint64_t x129; + fiat_p256_uint1 x130; + fiat_p256_addcarryx_u64(&x129, &x130, x128, x123, x109); + uint64_t x131; + fiat_p256_uint1 x132; + fiat_p256_addcarryx_u64(&x131, &x132, x130, x125, x111); + uint64_t x133; + fiat_p256_uint1 x134; + fiat_p256_addcarryx_u64(&x133, &x134, x132, x117, x113); + uint64_t x135; + fiat_p256_uint1 x136; + fiat_p256_addcarryx_u64(&x135, &x136, x134, x118, x115); + uint64_t x137; + fiat_p256_uint1 x138; + fiat_p256_addcarryx_u64(&x137, &x138, x136, 0x0, x116); + uint64_t x139; + uint64_t x140; + fiat_p256_mulx_u64(&x139, &x140, x3, (arg1[3])); + uint64_t x141; + uint64_t x142; + fiat_p256_mulx_u64(&x141, &x142, x3, (arg1[2])); + uint64_t x143; + uint64_t x144; + fiat_p256_mulx_u64(&x143, &x144, x3, (arg1[1])); + uint64_t x145; + uint64_t x146; + fiat_p256_mulx_u64(&x145, &x146, x3, (arg1[0])); + uint64_t x147; + fiat_p256_uint1 x148; + fiat_p256_addcarryx_u64(&x147, &x148, 0x0, x143, x146); + uint64_t x149; + fiat_p256_uint1 x150; + fiat_p256_addcarryx_u64(&x149, &x150, x148, x141, x144); + uint64_t x151; + fiat_p256_uint1 x152; + fiat_p256_addcarryx_u64(&x151, &x152, x150, x139, x142); + uint64_t x153; + fiat_p256_uint1 x154; + fiat_p256_addcarryx_u64(&x153, &x154, x152, 0x0, x140); + uint64_t x155; + fiat_p256_uint1 x156; + fiat_p256_addcarryx_u64(&x155, &x156, 0x0, x145, x129); + uint64_t x157; + fiat_p256_uint1 x158; + fiat_p256_addcarryx_u64(&x157, &x158, x156, x147, x131); + uint64_t x159; + fiat_p256_uint1 x160; + fiat_p256_addcarryx_u64(&x159, &x160, x158, x149, x133); + uint64_t x161; + fiat_p256_uint1 x162; + fiat_p256_addcarryx_u64(&x161, &x162, x160, x151, x135); + uint64_t x163; + fiat_p256_uint1 x164; + fiat_p256_addcarryx_u64(&x163, &x164, x162, x153, x137); + uint64_t x165; + uint64_t x166; + fiat_p256_mulx_u64(&x165, &x166, x155, UINT64_C(0xffffffff00000001)); + uint64_t x167; + uint64_t x168; + fiat_p256_mulx_u64(&x167, &x168, x155, UINT32_C(0xffffffff)); + uint64_t x169; + uint64_t x170; + fiat_p256_mulx_u64(&x169, &x170, x155, UINT64_C(0xffffffffffffffff)); + uint64_t x171; + fiat_p256_uint1 x172; + fiat_p256_addcarryx_u64(&x171, &x172, 0x0, x167, x170); + uint64_t x173; + fiat_p256_uint1 x174; + fiat_p256_addcarryx_u64(&x173, &x174, x172, 0x0, x168); + uint64_t x175; + fiat_p256_uint1 x176; + fiat_p256_addcarryx_u64(&x175, &x176, 0x0, x169, x155); + uint64_t x177; + fiat_p256_uint1 x178; + fiat_p256_addcarryx_u64(&x177, &x178, x176, x171, x157); + uint64_t x179; + fiat_p256_uint1 x180; + fiat_p256_addcarryx_u64(&x179, &x180, x178, x173, x159); + uint64_t x181; + fiat_p256_uint1 x182; + fiat_p256_addcarryx_u64(&x181, &x182, x180, x165, x161); + uint64_t x183; + fiat_p256_uint1 x184; + fiat_p256_addcarryx_u64(&x183, &x184, x182, x166, x163); + uint64_t x185; + fiat_p256_uint1 x186; + fiat_p256_addcarryx_u64(&x185, &x186, x184, 0x0, x164); + uint64_t x187; + fiat_p256_uint1 x188; + fiat_p256_subborrowx_u64(&x187, &x188, 0x0, x177, UINT64_C(0xffffffffffffffff)); + uint64_t x189; + fiat_p256_uint1 x190; + fiat_p256_subborrowx_u64(&x189, &x190, x188, x179, UINT32_C(0xffffffff)); + uint64_t x191; + fiat_p256_uint1 x192; + fiat_p256_subborrowx_u64(&x191, &x192, x190, x181, 0x0); + uint64_t x193; + fiat_p256_uint1 x194; + fiat_p256_subborrowx_u64(&x193, &x194, x192, x183, UINT64_C(0xffffffff00000001)); + uint64_t x195; + fiat_p256_uint1 x196; + fiat_p256_subborrowx_u64(&x195, &x196, x194, x185, 0x0); + uint64_t x197; + fiat_p256_cmovznz_u64(&x197, x196, x187, x177); + uint64_t x198; + fiat_p256_cmovznz_u64(&x198, x196, x189, x179); + uint64_t x199; + fiat_p256_cmovznz_u64(&x199, x196, x191, x181); + uint64_t x200; + fiat_p256_cmovznz_u64(&x200, x196, x193, x183); + out1[0] = x197; + out1[1] = x198; + out1[2] = x199; + out1[3] = x200; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + * arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + */ +static void fiat_p256_add(uint64_t out1[4], const uint64_t arg1[4], const uint64_t arg2[4]) { + uint64_t x1; + fiat_p256_uint1 x2; + fiat_p256_addcarryx_u64(&x1, &x2, 0x0, (arg2[0]), (arg1[0])); + uint64_t x3; + fiat_p256_uint1 x4; + fiat_p256_addcarryx_u64(&x3, &x4, x2, (arg2[1]), (arg1[1])); + uint64_t x5; + fiat_p256_uint1 x6; + fiat_p256_addcarryx_u64(&x5, &x6, x4, (arg2[2]), (arg1[2])); + uint64_t x7; + fiat_p256_uint1 x8; + fiat_p256_addcarryx_u64(&x7, &x8, x6, (arg2[3]), (arg1[3])); + uint64_t x9; + fiat_p256_uint1 x10; + fiat_p256_subborrowx_u64(&x9, &x10, 0x0, x1, UINT64_C(0xffffffffffffffff)); + uint64_t x11; + fiat_p256_uint1 x12; + fiat_p256_subborrowx_u64(&x11, &x12, x10, x3, UINT32_C(0xffffffff)); + uint64_t x13; + fiat_p256_uint1 x14; + fiat_p256_subborrowx_u64(&x13, &x14, x12, x5, 0x0); + uint64_t x15; + fiat_p256_uint1 x16; + fiat_p256_subborrowx_u64(&x15, &x16, x14, x7, UINT64_C(0xffffffff00000001)); + uint64_t x17; + fiat_p256_uint1 x18; + fiat_p256_subborrowx_u64(&x17, &x18, x16, x8, 0x0); + uint64_t x19; + fiat_p256_cmovznz_u64(&x19, x18, x9, x1); + uint64_t x20; + fiat_p256_cmovznz_u64(&x20, x18, x11, x3); + uint64_t x21; + fiat_p256_cmovznz_u64(&x21, x18, x13, x5); + uint64_t x22; + fiat_p256_cmovznz_u64(&x22, x18, x15, x7); + out1[0] = x19; + out1[1] = x20; + out1[2] = x21; + out1[3] = x22; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + * arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + */ +static void fiat_p256_sub(uint64_t out1[4], const uint64_t arg1[4], const uint64_t arg2[4]) { + uint64_t x1; + fiat_p256_uint1 x2; + fiat_p256_subborrowx_u64(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); + uint64_t x3; + fiat_p256_uint1 x4; + fiat_p256_subborrowx_u64(&x3, &x4, x2, (arg1[1]), (arg2[1])); + uint64_t x5; + fiat_p256_uint1 x6; + fiat_p256_subborrowx_u64(&x5, &x6, x4, (arg1[2]), (arg2[2])); + uint64_t x7; + fiat_p256_uint1 x8; + fiat_p256_subborrowx_u64(&x7, &x8, x6, (arg1[3]), (arg2[3])); + uint64_t x9; + fiat_p256_cmovznz_u64(&x9, x8, 0x0, UINT64_C(0xffffffffffffffff)); + uint64_t x10; + fiat_p256_uint1 x11; + fiat_p256_addcarryx_u64(&x10, &x11, 0x0, (x9 & UINT64_C(0xffffffffffffffff)), x1); + uint64_t x12; + fiat_p256_uint1 x13; + fiat_p256_addcarryx_u64(&x12, &x13, x11, (x9 & UINT32_C(0xffffffff)), x3); + uint64_t x14; + fiat_p256_uint1 x15; + fiat_p256_addcarryx_u64(&x14, &x15, x13, 0x0, x5); + uint64_t x16; + fiat_p256_uint1 x17; + fiat_p256_addcarryx_u64(&x16, &x17, x15, (x9 & UINT64_C(0xffffffff00000001)), x7); + out1[0] = x10; + out1[1] = x12; + out1[2] = x14; + out1[3] = x16; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + */ +static void fiat_p256_opp(uint64_t out1[4], const uint64_t arg1[4]) { + uint64_t x1; + fiat_p256_uint1 x2; + fiat_p256_subborrowx_u64(&x1, &x2, 0x0, 0x0, (arg1[0])); + uint64_t x3; + fiat_p256_uint1 x4; + fiat_p256_subborrowx_u64(&x3, &x4, x2, 0x0, (arg1[1])); + uint64_t x5; + fiat_p256_uint1 x6; + fiat_p256_subborrowx_u64(&x5, &x6, x4, 0x0, (arg1[2])); + uint64_t x7; + fiat_p256_uint1 x8; + fiat_p256_subborrowx_u64(&x7, &x8, x6, 0x0, (arg1[3])); + uint64_t x9; + fiat_p256_cmovznz_u64(&x9, x8, 0x0, UINT64_C(0xffffffffffffffff)); + uint64_t x10; + fiat_p256_uint1 x11; + fiat_p256_addcarryx_u64(&x10, &x11, 0x0, (x9 & UINT64_C(0xffffffffffffffff)), x1); + uint64_t x12; + fiat_p256_uint1 x13; + fiat_p256_addcarryx_u64(&x12, &x13, x11, (x9 & UINT32_C(0xffffffff)), x3); + uint64_t x14; + fiat_p256_uint1 x15; + fiat_p256_addcarryx_u64(&x14, &x15, x13, 0x0, x5); + uint64_t x16; + fiat_p256_uint1 x17; + fiat_p256_addcarryx_u64(&x16, &x17, x15, (x9 & UINT64_C(0xffffffff00000001)), x7); + out1[0] = x10; + out1[1] = x12; + out1[2] = x14; + out1[3] = x16; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + */ +static void fiat_p256_from_montgomery(uint64_t out1[4], const uint64_t arg1[4]) { + uint64_t x1 = (arg1[0]); + uint64_t x2; + uint64_t x3; + fiat_p256_mulx_u64(&x2, &x3, x1, UINT64_C(0xffffffff00000001)); + uint64_t x4; + uint64_t x5; + fiat_p256_mulx_u64(&x4, &x5, x1, UINT32_C(0xffffffff)); + uint64_t x6; + uint64_t x7; + fiat_p256_mulx_u64(&x6, &x7, x1, UINT64_C(0xffffffffffffffff)); + uint64_t x8; + fiat_p256_uint1 x9; + fiat_p256_addcarryx_u64(&x8, &x9, 0x0, x4, x7); + uint64_t x10; + fiat_p256_uint1 x11; + fiat_p256_addcarryx_u64(&x10, &x11, 0x0, x6, x1); + uint64_t x12; + fiat_p256_uint1 x13; + fiat_p256_addcarryx_u64(&x12, &x13, x11, x8, 0x0); + uint64_t x14; + fiat_p256_uint1 x15; + fiat_p256_addcarryx_u64(&x14, &x15, 0x0, (arg1[1]), x12); + uint64_t x16; + uint64_t x17; + fiat_p256_mulx_u64(&x16, &x17, x14, UINT64_C(0xffffffff00000001)); + uint64_t x18; + uint64_t x19; + fiat_p256_mulx_u64(&x18, &x19, x14, UINT32_C(0xffffffff)); + uint64_t x20; + uint64_t x21; + fiat_p256_mulx_u64(&x20, &x21, x14, UINT64_C(0xffffffffffffffff)); + uint64_t x22; + fiat_p256_uint1 x23; + fiat_p256_addcarryx_u64(&x22, &x23, 0x0, x18, x21); + uint64_t x24; + fiat_p256_uint1 x25; + fiat_p256_addcarryx_u64(&x24, &x25, x9, 0x0, x5); + uint64_t x26; + fiat_p256_uint1 x27; + fiat_p256_addcarryx_u64(&x26, &x27, x13, x24, 0x0); + uint64_t x28; + fiat_p256_uint1 x29; + fiat_p256_addcarryx_u64(&x28, &x29, x15, 0x0, x26); + uint64_t x30; + fiat_p256_uint1 x31; + fiat_p256_addcarryx_u64(&x30, &x31, 0x0, x20, x14); + uint64_t x32; + fiat_p256_uint1 x33; + fiat_p256_addcarryx_u64(&x32, &x33, x31, x22, x28); + uint64_t x34; + fiat_p256_uint1 x35; + fiat_p256_addcarryx_u64(&x34, &x35, x23, 0x0, x19); + uint64_t x36; + fiat_p256_uint1 x37; + fiat_p256_addcarryx_u64(&x36, &x37, x33, x34, x2); + uint64_t x38; + fiat_p256_uint1 x39; + fiat_p256_addcarryx_u64(&x38, &x39, x37, x16, x3); + uint64_t x40; + fiat_p256_uint1 x41; + fiat_p256_addcarryx_u64(&x40, &x41, 0x0, (arg1[2]), x32); + uint64_t x42; + fiat_p256_uint1 x43; + fiat_p256_addcarryx_u64(&x42, &x43, x41, 0x0, x36); + uint64_t x44; + fiat_p256_uint1 x45; + fiat_p256_addcarryx_u64(&x44, &x45, x43, 0x0, x38); + uint64_t x46; + uint64_t x47; + fiat_p256_mulx_u64(&x46, &x47, x40, UINT64_C(0xffffffff00000001)); + uint64_t x48; + uint64_t x49; + fiat_p256_mulx_u64(&x48, &x49, x40, UINT32_C(0xffffffff)); + uint64_t x50; + uint64_t x51; + fiat_p256_mulx_u64(&x50, &x51, x40, UINT64_C(0xffffffffffffffff)); + uint64_t x52; + fiat_p256_uint1 x53; + fiat_p256_addcarryx_u64(&x52, &x53, 0x0, x48, x51); + uint64_t x54; + fiat_p256_uint1 x55; + fiat_p256_addcarryx_u64(&x54, &x55, 0x0, x50, x40); + uint64_t x56; + fiat_p256_uint1 x57; + fiat_p256_addcarryx_u64(&x56, &x57, x55, x52, x42); + uint64_t x58; + fiat_p256_uint1 x59; + fiat_p256_addcarryx_u64(&x58, &x59, x53, 0x0, x49); + uint64_t x60; + fiat_p256_uint1 x61; + fiat_p256_addcarryx_u64(&x60, &x61, x57, x58, x44); + uint64_t x62; + fiat_p256_uint1 x63; + fiat_p256_addcarryx_u64(&x62, &x63, x39, x17, 0x0); + uint64_t x64; + fiat_p256_uint1 x65; + fiat_p256_addcarryx_u64(&x64, &x65, x45, 0x0, x62); + uint64_t x66; + fiat_p256_uint1 x67; + fiat_p256_addcarryx_u64(&x66, &x67, x61, x46, x64); + uint64_t x68; + fiat_p256_uint1 x69; + fiat_p256_addcarryx_u64(&x68, &x69, 0x0, (arg1[3]), x56); + uint64_t x70; + fiat_p256_uint1 x71; + fiat_p256_addcarryx_u64(&x70, &x71, x69, 0x0, x60); + uint64_t x72; + fiat_p256_uint1 x73; + fiat_p256_addcarryx_u64(&x72, &x73, x71, 0x0, x66); + uint64_t x74; + uint64_t x75; + fiat_p256_mulx_u64(&x74, &x75, x68, UINT64_C(0xffffffff00000001)); + uint64_t x76; + uint64_t x77; + fiat_p256_mulx_u64(&x76, &x77, x68, UINT32_C(0xffffffff)); + uint64_t x78; + uint64_t x79; + fiat_p256_mulx_u64(&x78, &x79, x68, UINT64_C(0xffffffffffffffff)); + uint64_t x80; + fiat_p256_uint1 x81; + fiat_p256_addcarryx_u64(&x80, &x81, 0x0, x76, x79); + uint64_t x82; + fiat_p256_uint1 x83; + fiat_p256_addcarryx_u64(&x82, &x83, 0x0, x78, x68); + uint64_t x84; + fiat_p256_uint1 x85; + fiat_p256_addcarryx_u64(&x84, &x85, x83, x80, x70); + uint64_t x86; + fiat_p256_uint1 x87; + fiat_p256_addcarryx_u64(&x86, &x87, x81, 0x0, x77); + uint64_t x88; + fiat_p256_uint1 x89; + fiat_p256_addcarryx_u64(&x88, &x89, x85, x86, x72); + uint64_t x90; + fiat_p256_uint1 x91; + fiat_p256_addcarryx_u64(&x90, &x91, x67, x47, 0x0); + uint64_t x92; + fiat_p256_uint1 x93; + fiat_p256_addcarryx_u64(&x92, &x93, x73, 0x0, x90); + uint64_t x94; + fiat_p256_uint1 x95; + fiat_p256_addcarryx_u64(&x94, &x95, x89, x74, x92); + uint64_t x96; + fiat_p256_uint1 x97; + fiat_p256_addcarryx_u64(&x96, &x97, x95, x75, 0x0); + uint64_t x98; + fiat_p256_uint1 x99; + fiat_p256_subborrowx_u64(&x98, &x99, 0x0, x84, UINT64_C(0xffffffffffffffff)); + uint64_t x100; + fiat_p256_uint1 x101; + fiat_p256_subborrowx_u64(&x100, &x101, x99, x88, UINT32_C(0xffffffff)); + uint64_t x102; + fiat_p256_uint1 x103; + fiat_p256_subborrowx_u64(&x102, &x103, x101, x94, 0x0); + uint64_t x104; + fiat_p256_uint1 x105; + fiat_p256_subborrowx_u64(&x104, &x105, x103, x96, UINT64_C(0xffffffff00000001)); + uint64_t x106; + fiat_p256_uint1 x107; + fiat_p256_subborrowx_u64(&x106, &x107, x105, 0x0, 0x0); + uint64_t x108; + fiat_p256_cmovznz_u64(&x108, x107, x98, x84); + uint64_t x109; + fiat_p256_cmovznz_u64(&x109, x107, x100, x88); + uint64_t x110; + fiat_p256_cmovznz_u64(&x110, x107, x102, x94); + uint64_t x111; + fiat_p256_cmovznz_u64(&x111, x107, x104, x96); + out1[0] = x108; + out1[1] = x109; + out1[2] = x110; + out1[3] = x111; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + * Output Bounds: + * out1: [0x0 ~> 0xffffffffffffffff] + */ +static void fiat_p256_nonzero(uint64_t* out1, const uint64_t arg1[4]) { + uint64_t x1 = ((arg1[0]) | ((arg1[1]) | ((arg1[2]) | ((arg1[3]) | (uint64_t)0x0)))); + *out1 = x1; +} + +/* + * Input Bounds: + * arg1: [0x0 ~> 0x1] + * arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + * arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + */ +static void fiat_p256_selectznz(uint64_t out1[4], fiat_p256_uint1 arg1, const uint64_t arg2[4], const uint64_t arg3[4]) { + uint64_t x1; + fiat_p256_cmovznz_u64(&x1, arg1, (arg2[0]), (arg3[0])); + uint64_t x2; + fiat_p256_cmovznz_u64(&x2, arg1, (arg2[1]), (arg3[1])); + uint64_t x3; + fiat_p256_cmovznz_u64(&x3, arg1, (arg2[2]), (arg3[2])); + uint64_t x4; + fiat_p256_cmovznz_u64(&x4, arg1, (arg2[3]), (arg3[3])); + out1[0] = x1; + out1[1] = x2; + out1[2] = x3; + out1[3] = x4; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + * Output Bounds: + * out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] + */ +static void fiat_p256_to_bytes(uint8_t out1[32], const uint64_t arg1[4]) { + uint64_t x1 = (arg1[3]); + uint64_t x2 = (arg1[2]); + uint64_t x3 = (arg1[1]); + uint64_t x4 = (arg1[0]); + uint64_t x5 = (x4 >> 8); + uint8_t x6 = (uint8_t)(x4 & UINT8_C(0xff)); + uint64_t x7 = (x5 >> 8); + uint8_t x8 = (uint8_t)(x5 & UINT8_C(0xff)); + uint64_t x9 = (x7 >> 8); + uint8_t x10 = (uint8_t)(x7 & UINT8_C(0xff)); + uint64_t x11 = (x9 >> 8); + uint8_t x12 = (uint8_t)(x9 & UINT8_C(0xff)); + uint64_t x13 = (x11 >> 8); + uint8_t x14 = (uint8_t)(x11 & UINT8_C(0xff)); + uint64_t x15 = (x13 >> 8); + uint8_t x16 = (uint8_t)(x13 & UINT8_C(0xff)); + uint8_t x17 = (uint8_t)(x15 >> 8); + uint8_t x18 = (uint8_t)(x15 & UINT8_C(0xff)); + uint8_t x19 = (uint8_t)(x17 & UINT8_C(0xff)); + uint64_t x20 = (x3 >> 8); + uint8_t x21 = (uint8_t)(x3 & UINT8_C(0xff)); + uint64_t x22 = (x20 >> 8); + uint8_t x23 = (uint8_t)(x20 & UINT8_C(0xff)); + uint64_t x24 = (x22 >> 8); + uint8_t x25 = (uint8_t)(x22 & UINT8_C(0xff)); + uint64_t x26 = (x24 >> 8); + uint8_t x27 = (uint8_t)(x24 & UINT8_C(0xff)); + uint64_t x28 = (x26 >> 8); + uint8_t x29 = (uint8_t)(x26 & UINT8_C(0xff)); + uint64_t x30 = (x28 >> 8); + uint8_t x31 = (uint8_t)(x28 & UINT8_C(0xff)); + uint8_t x32 = (uint8_t)(x30 >> 8); + uint8_t x33 = (uint8_t)(x30 & UINT8_C(0xff)); + uint8_t x34 = (uint8_t)(x32 & UINT8_C(0xff)); + uint64_t x35 = (x2 >> 8); + uint8_t x36 = (uint8_t)(x2 & UINT8_C(0xff)); + uint64_t x37 = (x35 >> 8); + uint8_t x38 = (uint8_t)(x35 & UINT8_C(0xff)); + uint64_t x39 = (x37 >> 8); + uint8_t x40 = (uint8_t)(x37 & UINT8_C(0xff)); + uint64_t x41 = (x39 >> 8); + uint8_t x42 = (uint8_t)(x39 & UINT8_C(0xff)); + uint64_t x43 = (x41 >> 8); + uint8_t x44 = (uint8_t)(x41 & UINT8_C(0xff)); + uint64_t x45 = (x43 >> 8); + uint8_t x46 = (uint8_t)(x43 & UINT8_C(0xff)); + uint8_t x47 = (uint8_t)(x45 >> 8); + uint8_t x48 = (uint8_t)(x45 & UINT8_C(0xff)); + uint8_t x49 = (uint8_t)(x47 & UINT8_C(0xff)); + uint64_t x50 = (x1 >> 8); + uint8_t x51 = (uint8_t)(x1 & UINT8_C(0xff)); + uint64_t x52 = (x50 >> 8); + uint8_t x53 = (uint8_t)(x50 & UINT8_C(0xff)); + uint64_t x54 = (x52 >> 8); + uint8_t x55 = (uint8_t)(x52 & UINT8_C(0xff)); + uint64_t x56 = (x54 >> 8); + uint8_t x57 = (uint8_t)(x54 & UINT8_C(0xff)); + uint64_t x58 = (x56 >> 8); + uint8_t x59 = (uint8_t)(x56 & UINT8_C(0xff)); + uint64_t x60 = (x58 >> 8); + uint8_t x61 = (uint8_t)(x58 & UINT8_C(0xff)); + uint8_t x62 = (uint8_t)(x60 >> 8); + uint8_t x63 = (uint8_t)(x60 & UINT8_C(0xff)); + out1[0] = x6; + out1[1] = x8; + out1[2] = x10; + out1[3] = x12; + out1[4] = x14; + out1[5] = x16; + out1[6] = x18; + out1[7] = x19; + out1[8] = x21; + out1[9] = x23; + out1[10] = x25; + out1[11] = x27; + out1[12] = x29; + out1[13] = x31; + out1[14] = x33; + out1[15] = x34; + out1[16] = x36; + out1[17] = x38; + out1[18] = x40; + out1[19] = x42; + out1[20] = x44; + out1[21] = x46; + out1[22] = x48; + out1[23] = x49; + out1[24] = x51; + out1[25] = x53; + out1[26] = x55; + out1[27] = x57; + out1[28] = x59; + out1[29] = x61; + out1[30] = x63; + out1[31] = x62; +} + +/* + * Input Bounds: + * arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] + * Output Bounds: + * out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] + */ +static void fiat_p256_from_bytes(uint64_t out1[4], const uint8_t arg1[32]) { + uint64_t x1 = ((uint64_t)(arg1[31]) << 56); + uint64_t x2 = ((uint64_t)(arg1[30]) << 48); + uint64_t x3 = ((uint64_t)(arg1[29]) << 40); + uint64_t x4 = ((uint64_t)(arg1[28]) << 32); + uint64_t x5 = ((uint64_t)(arg1[27]) << 24); + uint64_t x6 = ((uint64_t)(arg1[26]) << 16); + uint64_t x7 = ((uint64_t)(arg1[25]) << 8); + uint8_t x8 = (arg1[24]); + uint64_t x9 = ((uint64_t)(arg1[23]) << 56); + uint64_t x10 = ((uint64_t)(arg1[22]) << 48); + uint64_t x11 = ((uint64_t)(arg1[21]) << 40); + uint64_t x12 = ((uint64_t)(arg1[20]) << 32); + uint64_t x13 = ((uint64_t)(arg1[19]) << 24); + uint64_t x14 = ((uint64_t)(arg1[18]) << 16); + uint64_t x15 = ((uint64_t)(arg1[17]) << 8); + uint8_t x16 = (arg1[16]); + uint64_t x17 = ((uint64_t)(arg1[15]) << 56); + uint64_t x18 = ((uint64_t)(arg1[14]) << 48); + uint64_t x19 = ((uint64_t)(arg1[13]) << 40); + uint64_t x20 = ((uint64_t)(arg1[12]) << 32); + uint64_t x21 = ((uint64_t)(arg1[11]) << 24); + uint64_t x22 = ((uint64_t)(arg1[10]) << 16); + uint64_t x23 = ((uint64_t)(arg1[9]) << 8); + uint8_t x24 = (arg1[8]); + uint64_t x25 = ((uint64_t)(arg1[7]) << 56); + uint64_t x26 = ((uint64_t)(arg1[6]) << 48); + uint64_t x27 = ((uint64_t)(arg1[5]) << 40); + uint64_t x28 = ((uint64_t)(arg1[4]) << 32); + uint64_t x29 = ((uint64_t)(arg1[3]) << 24); + uint64_t x30 = ((uint64_t)(arg1[2]) << 16); + uint64_t x31 = ((uint64_t)(arg1[1]) << 8); + uint8_t x32 = (arg1[0]); + uint64_t x33 = (x32 + (x31 + (x30 + (x29 + (x28 + (x27 + (x26 + x25))))))); + uint64_t x34 = (x33 & UINT64_C(0xffffffffffffffff)); + uint64_t x35 = (x8 + (x7 + (x6 + (x5 + (x4 + (x3 + (x2 + x1))))))); + uint64_t x36 = (x16 + (x15 + (x14 + (x13 + (x12 + (x11 + (x10 + x9))))))); + uint64_t x37 = (x24 + (x23 + (x22 + (x21 + (x20 + (x19 + (x18 + x17))))))); + uint64_t x38 = (x37 & UINT64_C(0xffffffffffffffff)); + uint64_t x39 = (x36 & UINT64_C(0xffffffffffffffff)); + out1[0] = x34; + out1[1] = x38; + out1[2] = x39; + out1[3] = x35; +} + diff --git a/third_party/boringssl/kit/src/third_party/sike/LICENSE b/third_party/boringssl/kit/src/third_party/sike/LICENSE new file mode 100644 index 00000000..5cf7c8db --- /dev/null +++ b/third_party/boringssl/kit/src/third_party/sike/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/third_party/boringssl/kit/src/third_party/sike/P503.c b/third_party/boringssl/kit/src/third_party/sike/P503.c new file mode 100644 index 00000000..b8463e76 --- /dev/null +++ b/third_party/boringssl/kit/src/third_party/sike/P503.c @@ -0,0 +1,100 @@ +/******************************************************************************************** +* SIDH: an efficient supersingular isogeny cryptography library +* +* Abstract: supersingular isogeny parameters and generation of functions for P503 +*********************************************************************************************/ + +#include "utils.h" + +// Parameters for isogeny system "SIKEp503" +const struct params_t p503 = { + .prime = { + U64_TO_WORDS(0xFFFFFFFFFFFFFFFF), U64_TO_WORDS(0xFFFFFFFFFFFFFFFF), + U64_TO_WORDS(0xFFFFFFFFFFFFFFFF), U64_TO_WORDS(0xABFFFFFFFFFFFFFF), + U64_TO_WORDS(0x13085BDA2211E7A0), U64_TO_WORDS(0x1B9BF6C87B7E7DAF), + U64_TO_WORDS(0x6045C6BDDA77A4D0), U64_TO_WORDS(0x004066F541811E1E) + }, + .prime_p1 = { + U64_TO_WORDS(0x0000000000000000), U64_TO_WORDS(0x0000000000000000), + U64_TO_WORDS(0x0000000000000000), U64_TO_WORDS(0xAC00000000000000), + U64_TO_WORDS(0x13085BDA2211E7A0), U64_TO_WORDS(0x1B9BF6C87B7E7DAF), + U64_TO_WORDS(0x6045C6BDDA77A4D0), U64_TO_WORDS(0x004066F541811E1E) + }, + .prime_x2 = { + U64_TO_WORDS(0xFFFFFFFFFFFFFFFE), U64_TO_WORDS(0xFFFFFFFFFFFFFFFF), + U64_TO_WORDS(0xFFFFFFFFFFFFFFFF), U64_TO_WORDS(0x57FFFFFFFFFFFFFF), + U64_TO_WORDS(0x2610B7B44423CF41), U64_TO_WORDS(0x3737ED90F6FCFB5E), + U64_TO_WORDS(0xC08B8D7BB4EF49A0), U64_TO_WORDS(0x0080CDEA83023C3C) + }, + .A_gen = { + U64_TO_WORDS(0xE7EF4AA786D855AF), U64_TO_WORDS(0xED5758F03EB34D3B), + U64_TO_WORDS(0x09AE172535A86AA9), U64_TO_WORDS(0x237B9CC07D622723), + U64_TO_WORDS(0xE3A284CBA4E7932D), U64_TO_WORDS(0x27481D9176C5E63F), + U64_TO_WORDS(0x6A323FF55C6E71BF), U64_TO_WORDS(0x002ECC31A6FB8773), // XPA0 + U64_TO_WORDS(0x64D02E4E90A620B8), U64_TO_WORDS(0xDAB8128537D4B9F1), + U64_TO_WORDS(0x4BADF77B8A228F98), U64_TO_WORDS(0x0F5DBDF9D1FB7D1B), + U64_TO_WORDS(0xBEC4DB288E1A0DCC), U64_TO_WORDS(0xE76A8665E80675DB), + U64_TO_WORDS(0x6D6F252E12929463), U64_TO_WORDS(0x003188BD1463FACC), // XPA1 + U64_TO_WORDS(0xB79D41025DE85D56), U64_TO_WORDS(0x0B867DA9DF169686), + U64_TO_WORDS(0x740E5368021C827D), U64_TO_WORDS(0x20615D72157BF25C), + U64_TO_WORDS(0xFF1590013C9B9F5B), U64_TO_WORDS(0xC884DCADE8C16CEA), + U64_TO_WORDS(0xEBD05E53BF724E01), U64_TO_WORDS(0x0032FEF8FDA5748C), // XQA0 + U64_TO_WORDS(0x12E2E849AA0A8006), U64_TO_WORDS(0x41CF47008635A1E8), + U64_TO_WORDS(0x9CD720A70798AED7), U64_TO_WORDS(0x42A820B42FCF04CF), + U64_TO_WORDS(0x7BF9BAD32AAE88B1), U64_TO_WORDS(0xF619127A54090BBE), + U64_TO_WORDS(0x1CB10D8F56408EAA), U64_TO_WORDS(0x001D6B54C3C0EDEB), // XRA0 + U64_TO_WORDS(0x34DB54931CBAAC36), U64_TO_WORDS(0x420A18CB8DD5F0C4), + U64_TO_WORDS(0x32008C1A48C0F44D), U64_TO_WORDS(0x3B3BA772B1CFD44D), + U64_TO_WORDS(0xA74B058FDAF13515), U64_TO_WORDS(0x095FC9CA7EEC17B4), + U64_TO_WORDS(0x448E829D28F120F8), U64_TO_WORDS(0x00261EC3ED16A489) // XRA1 + }, + .B_gen = { + U64_TO_WORDS(0x7EDE37F4FA0BC727), U64_TO_WORDS(0xF7F8EC5C8598941C), + U64_TO_WORDS(0xD15519B516B5F5C8), U64_TO_WORDS(0xF6D5AC9B87A36282), + U64_TO_WORDS(0x7B19F105B30E952E), U64_TO_WORDS(0x13BD8B2025B4EBEE), + U64_TO_WORDS(0x7B96D27F4EC579A2), U64_TO_WORDS(0x00140850CAB7E5DE), // XPB0 + U64_TO_WORDS(0x7764909DAE7B7B2D), U64_TO_WORDS(0x578ABB16284911AB), + U64_TO_WORDS(0x76E2BFD146A6BF4D), U64_TO_WORDS(0x4824044B23AA02F0), + U64_TO_WORDS(0x1105048912A321F3), U64_TO_WORDS(0xB8A2E482CF0F10C1), + U64_TO_WORDS(0x42FF7D0BE2152085), U64_TO_WORDS(0x0018E599C5223352), // XPB1 + U64_TO_WORDS(0x4256C520FB388820), U64_TO_WORDS(0x744FD7C3BAAF0A13), + U64_TO_WORDS(0x4B6A2DDDB12CBCB8), U64_TO_WORDS(0xE46826E27F427DF8), + U64_TO_WORDS(0xFE4A663CD505A61B), U64_TO_WORDS(0xD6B3A1BAF025C695), + U64_TO_WORDS(0x7C3BB62B8FCC00BD), U64_TO_WORDS(0x003AFDDE4A35746C), // XQB0 + U64_TO_WORDS(0x75601CD1E6C0DFCB), U64_TO_WORDS(0x1A9007239B58F93E), + U64_TO_WORDS(0xC1F1BE80C62107AC), U64_TO_WORDS(0x7F513B898F29FF08), + U64_TO_WORDS(0xEA0BEDFF43E1F7B2), U64_TO_WORDS(0x2C6D94018CBAE6D0), + U64_TO_WORDS(0x3A430D31BCD84672), U64_TO_WORDS(0x000D26892ECCFE83), // XRB0 + U64_TO_WORDS(0x1119D62AEA3007A1), U64_TO_WORDS(0xE3702AA4E04BAE1B), + U64_TO_WORDS(0x9AB96F7D59F990E7), U64_TO_WORDS(0xF58440E8B43319C0), + U64_TO_WORDS(0xAF8134BEE1489775), U64_TO_WORDS(0xE7F7774E905192AA), + U64_TO_WORDS(0xF54AE09308E98039), U64_TO_WORDS(0x001EF7A041A86112) // XRB1 + }, + .mont_R2 = { + U64_TO_WORDS(0x5289A0CF641D011F), U64_TO_WORDS(0x9B88257189FED2B9), + U64_TO_WORDS(0xA3B365D58DC8F17A), U64_TO_WORDS(0x5BC57AB6EFF168EC), + U64_TO_WORDS(0x9E51998BD84D4423), U64_TO_WORDS(0xBF8999CBAC3B5695), + U64_TO_WORDS(0x46E9127BCE14CDB6), U64_TO_WORDS(0x003F6CFCE8B81771) + }, + .mont_one = { + U64_TO_WORDS(0x00000000000003F9), U64_TO_WORDS(0x0000000000000000), + U64_TO_WORDS(0x0000000000000000), U64_TO_WORDS(0xB400000000000000), + U64_TO_WORDS(0x63CB1A6EA6DED2B4), U64_TO_WORDS(0x51689D8D667EB37D), + U64_TO_WORDS(0x8ACD77C71AB24142), U64_TO_WORDS(0x0026FBAEC60F5953) + }, + .A_strat = { + 61, 32, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, + 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, + 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 29, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, + 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 13, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, + 1, 1, 2, 1, 1, 5, 4, 2, 1, 1, 2, 1, 1, 2, 1, 1, 1 + }, + .B_strat = { + 71, 38, 21, 13, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 5, 4, 2, 1, 1, 2, 1, + 1, 2, 1, 1, 1, 9, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, 2, 1, 1, 17, 9, + 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 1, 2, 1, + 1, 4, 2, 1, 1, 2, 1, 1, 33, 17, 9, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, + 2, 1, 1, 8, 4, 2, 1, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 1, 2, + 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1 + } +}; diff --git a/third_party/boringssl/kit/src/third_party/sike/asm/fp-armv8.pl b/third_party/boringssl/kit/src/third_party/sike/asm/fp-armv8.pl new file mode 100644 index 00000000..a1728d13 --- /dev/null +++ b/third_party/boringssl/kit/src/third_party/sike/asm/fp-armv8.pl @@ -0,0 +1,968 @@ +#! /usr/bin/env perl +# +# April 2019 +# +# Abstract: field arithmetic in aarch64 assembly for SIDH/p503 + +$flavour = shift; +$output = shift; +if ($flavour =~ /\./) { $output = $flavour; undef $flavour; } + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; +( $xlate="${dir}arm-xlate.pl" and -f $xlate ) or +( $xlate="${dir}../../../crypto/perlasm/arm-xlate.pl" and -f $xlate) or +die "can't locate arm-xlate.pl"; + +open OUT,"| \"$^X\" \"$xlate\" $flavour \"$output\""; +*STDOUT=*OUT; + +$PREFIX="sike"; + +$code.=<<___; +.section .rodata + +.Lp503p1_nz_s8: + .quad 0x085BDA2211E7A0AC, 0x9BF6C87B7E7DAF13 + .quad 0x45C6BDDA77A4D01B, 0x4066F541811E1E60 + +.Lp503x2: + .quad 0xFFFFFFFFFFFFFFFE, 0xFFFFFFFFFFFFFFFF + .quad 0x57FFFFFFFFFFFFFF, 0x2610B7B44423CF41 + .quad 0x3737ED90F6FCFB5E, 0xC08B8D7BB4EF49A0 + .quad 0x0080CDEA83023C3C + +.text +___ + +# C[0-2] = A[0] * B[0-1] +sub mul64x128_comba_cut { + my ($A0,$B0,$B1,$C0,$C1,$C2,$T0,$T1)=@_; + my $body=<<___; + mul $T1, $A0, $B0 + umulh $B0, $A0, $B0 + adds $C0, $C0, $C2 + adc $C1, $C1, xzr + + mul $T0, $A0, $B1 + umulh $B1, $A0, $B1 + adds $C0, $C0, $T1 + adcs $C1, $C1, $B0 + adc $C2, xzr, xzr + + adds $C1, $C1, $T0 + adc $C2, $C2, $B1 +___ + return $body; +} + +sub mul256_karatsuba_comba { + my ($M,$A0,$A1,$A2,$A3,$B0,$B1,$B2,$B3,$C0,$C1,$C2,$C3,$C4,$C5,$C6,$C7,$T0,$T1)=@_; + # (AH+AL) x (BH+BL), low part + my $mul_low=&mul64x128_comba_cut($A1, $C6, $T1, $C3, $C4, $C5, $C7, $A0); + # AL x BL + my $mul_albl=&mul64x128_comba_cut($A1, $B0, $B1, $C1, $T1, $C7, $C6, $A0); + # AH x BH + my $mul_ahbh=&mul64x128_comba_cut($A3, $B2, $B3, $A1, $C6, $B0, $B1, $A2); + my $body=<<___; + // A0-A1 <- AH + AL, T0 <- mask + adds $A0, $A0, $A2 + adcs $A1, $A1, $A3 + adc $T0, xzr, xzr + + // C6, T1 <- BH + BL, C7 <- mask + adds $C6, $B0, $B2 + adcs $T1, $B1, $B3 + adc $C7, xzr, xzr + + // C0-C1 <- masked (BH + BL) + sub $C2, xzr, $T0 + sub $C3, xzr, $C7 + and $C0, $C6, $C2 + and $C1, $T1, $C2 + + // C4-C5 <- masked (AH + AL), T0 <- combined carry + and $C4, $A0, $C3 + and $C5, $A1, $C3 + mul $C2, $A0, $C6 + mul $C3, $A0, $T1 + and $T0, $T0, $C7 + + // C0-C1, T0 <- (AH+AL) x (BH+BL), part 1 + adds $C0, $C4, $C0 + umulh $C4, $A0, $T1 + adcs $C1, $C5, $C1 + umulh $C5, $A0, $C6 + adc $T0, $T0, xzr + + // C2-C5 <- (AH+AL) x (BH+BL), low part + $mul_low + ldp $A0, $A1, [$M,#0] + + // C2-C5, T0 <- (AH+AL) x (BH+BL), final part + adds $C4, $C0, $C4 + umulh $C7, $A0, $B0 + umulh $T1, $A0, $B1 + adcs $C5, $C1, $C5 + mul $C0, $A0, $B0 + mul $C1, $A0, $B1 + adc $T0, $T0, xzr + + // C0-C1, T1, C7 <- AL x BL + $mul_albl + + // C2-C5, T0 <- (AH+AL) x (BH+BL) - ALxBL + mul $A0, $A2, $B2 + umulh $B0, $A2, $B2 + subs $C2, $C2, $C0 + sbcs $C3, $C3, $C1 + sbcs $C4, $C4, $T1 + mul $A1, $A2, $B3 + umulh $C6, $A2, $B3 + sbcs $C5, $C5, $C7 + sbc $T0, $T0, xzr + + // A0, A1, C6, B0 <- AH x BH + $mul_ahbh + + // C2-C5, T0 <- (AH+AL) x (BH+BL) - ALxBL - AHxBH + subs $C2, $C2, $A0 + sbcs $C3, $C3, $A1 + sbcs $C4, $C4, $C6 + sbcs $C5, $C5, $B0 + sbc $T0, $T0, xzr + + adds $C2, $C2, $T1 + adcs $C3, $C3, $C7 + adcs $C4, $C4, $A0 + adcs $C5, $C5, $A1 + adcs $C6, $T0, $C6 + adc $C7, $B0, xzr +___ + return $body; +} + +# 512-bit integer multiplication using Karatsuba (two levels), +# Comba (lower level). +# Operation: c [x2] = a [x0] * b [x1] +sub mul { + # (AH+AL) x (BH+BL), low part + my $mul_kc_low=&mul256_karatsuba_comba( + "x2", # M0 + "x3","x4","x5","x6", # A0-A3 + "x11","x12","x13","x14", # B0-B3 + "x8","x9","x10","x20","x21","x22","x23","x24", # C0-C7 + "x25","x26"); # TMP + # AL x BL + my $mul_albl=&mul256_karatsuba_comba( + "x0", # M0 + "x3","x4","x5","x6", # A0-A3 + "x11","x12","x13","x14", # B0-B3 + "x21","x22","x23","x24","x25","x26","x27","x28",# C0-C7 + "x8","x9"); # TMP + # AH x BH + my $mul_ahbh=&mul256_karatsuba_comba( + "x0", # M0 + "x3","x4","x5","x6", # A0-A3 + "x11","x12","x13","x14", # B0-B3 + "x21","x22","x23","x24","x25","x26","x27","x28",# C0-C7 + "x8","x9"); # TMP + + my $body=<<___; + .global ${PREFIX}_mpmul + .align 4 + ${PREFIX}_mpmul: + stp x29, x30, [sp,#-96]! + add x29, sp, #0 + stp x19, x20, [sp,#16] + stp x21, x22, [sp,#32] + stp x23, x24, [sp,#48] + stp x25, x26, [sp,#64] + stp x27, x28, [sp,#80] + + ldp x3, x4, [x0] + ldp x5, x6, [x0,#16] + ldp x7, x8, [x0,#32] + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + ldp x15, x16, [x1,#32] + ldp x17, x19, [x1,#48] + + // x3-x7 <- AH + AL, x7 <- carry + adds x3, x3, x7 + adcs x4, x4, x8 + adcs x5, x5, x9 + adcs x6, x6, x10 + adc x7, xzr, xzr + + // x11-x14 <- BH + BL, x8 <- carry + adds x11, x11, x15 + adcs x12, x12, x16 + adcs x13, x13, x17 + adcs x14, x14, x19 + adc x8, xzr, xzr + + // x9 <- combined carry + and x9, x7, x8 + // x7-x8 <- mask + sub x7, xzr, x7 + sub x8, xzr, x8 + + + // x15-x19 <- masked (BH + BL) + and x15, x11, x7 + and x16, x12, x7 + and x17, x13, x7 + and x19, x14, x7 + + // x20-x23 <- masked (AH + AL) + and x20, x3, x8 + and x21, x4, x8 + and x22, x5, x8 + and x23, x6, x8 + + // x15-x19, x7 <- masked (AH+AL) + masked (BH+BL), step 1 + adds x15, x15, x20 + adcs x16, x16, x21 + adcs x17, x17, x22 + adcs x19, x19, x23 + adc x7, x9, xzr + + // x8-x10,x20-x24 <- (AH+AL) x (BH+BL), low part + stp x3, x4, [x2,#0] + $mul_kc_low + + // x15-x19, x7 <- (AH+AL) x (BH+BL), final step + adds x15, x15, x21 + adcs x16, x16, x22 + adcs x17, x17, x23 + adcs x19, x19, x24 + adc x7, x7, xzr + + // Load AL + ldp x3, x4, [x0] + ldp x5, x6, [x0,#16] + // Load BL + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + + // Temporarily store x8,x9 in x2 + stp x8,x9, [x2,#0] + // x21-x28 <- AL x BL + $mul_albl + // Restore x8,x9 + ldp x8,x9, [x2,#0] + + // x8-x10,x20,x15-x17,x19 <- maskd (AH+AL) x (BH+BL) - ALxBL + subs x8, x8, x21 + sbcs x9, x9, x22 + sbcs x10, x10, x23 + sbcs x20, x20, x24 + sbcs x15, x15, x25 + sbcs x16, x16, x26 + sbcs x17, x17, x27 + sbcs x19, x19, x28 + sbc x7, x7, xzr + + // Store ALxBL, low + stp x21, x22, [x2] + stp x23, x24, [x2,#16] + + // Load AH + ldp x3, x4, [x0,#32] + ldp x5, x6, [x0,#48] + // Load BH + ldp x11, x12, [x1,#32] + ldp x13, x14, [x1,#48] + + adds x8, x8, x25 + adcs x9, x9, x26 + adcs x10, x10, x27 + adcs x20, x20, x28 + adc x1, xzr, xzr + + add x0, x0, #32 + // Temporarily store x8,x9 in x2 + stp x8,x9, [x2,#32] + // x21-x28 <- AH x BH + $mul_ahbh + // Restore x8,x9 + ldp x8,x9, [x2,#32] + + neg x1, x1 + + // x8-x10,x20,x15-x17,x19 <- (AH+AL) x (BH+BL) - ALxBL - AHxBH + subs x8, x8, x21 + sbcs x9, x9, x22 + sbcs x10, x10, x23 + sbcs x20, x20, x24 + sbcs x15, x15, x25 + sbcs x16, x16, x26 + sbcs x17, x17, x27 + sbcs x19, x19, x28 + sbc x7, x7, xzr + + // Store (AH+AL) x (BH+BL) - ALxBL - AHxBH, low + stp x8, x9, [x2,#32] + stp x10, x20, [x2,#48] + + adds x1, x1, #1 + adcs x15, x15, x21 + adcs x16, x16, x22 + adcs x17, x17, x23 + adcs x19, x19, x24 + adcs x25, x7, x25 + adcs x26, x26, xzr + adcs x27, x27, xzr + adc x28, x28, xzr + + stp x15, x16, [x2,#64] + stp x17, x19, [x2,#80] + stp x25, x26, [x2,#96] + stp x27, x28, [x2,#112] + + ldp x19, x20, [x29,#16] + ldp x21, x22, [x29,#32] + ldp x23, x24, [x29,#48] + ldp x25, x26, [x29,#64] + ldp x27, x28, [x29,#80] + ldp x29, x30, [sp],#96 + ret +___ + return $body; +} +$code.=&mul(); + +# Computes C0-C4 = (A0-A1) * (B0-B3) +# Inputs remain intact +sub mul128x256_comba { + my ($A0,$A1,$B0,$B1,$B2,$B3,$C0,$C1,$C2,$C3,$C4,$T0,$T1,$T2,$T3)=@_; + my $body=<<___; + mul $T0, $A1, $B0 + umulh $T1, $A1, $B0 + adds $C0, $C0, $C2 + adc $C1, $C1, xzr + + mul $T2, $A0, $B2 + umulh $T3, $A0, $B2 + adds $C0, $C0, $T0 + adcs $C1, $C1, $T1 + adc $C2, xzr, xzr + + mul $T0, $A1, $B1 + umulh $T1, $A1, $B1 + adds $C1, $C1, $T2 + adcs $C2, $C2, $T3 + adc $C3, xzr, xzr + + mul $T2, $A0, $B3 + umulh $T3, $A0, $B3 + adds $C1, $C1, $T0 + adcs $C2, $C2, $T1 + adc $C3, $C3, xzr + + mul $T0, $A1, $B2 + umulh $T1, $A1, $B2 + adds $C2, $C2, $T2 + adcs $C3, $C3, $T3 + adc $C4, xzr, xzr + + mul $T2, $A1, $B3 + umulh $T3, $A1, $B3 + adds $C2, $C2, $T0 + adcs $C3, $C3, $T1 + adc $C4, $C4, xzr + adds $C3, $C3, $T2 + adc $C4, $C4, $T3 + +___ + return $body; +} + +# Montgomery reduction +# Based on method described in Faz-Hernandez et al. https://eprint.iacr.org/2017/1015 +# Operation: mc [x1] = ma [x0] +# NOTE: ma=mc is not allowed +sub rdc { + my $mul01=&mul128x256_comba( + "x2","x3", # A0-A1 + "x24","x25","x26","x27", # B0-B3 + "x5","x6","x7","x8","x9", # C0-B4 + "x1","x10","x11","x19"); # TMP + my $mul23=&mul128x256_comba( + "x2","x3", # A0-A1 + "x24","x25","x26","x27", # B0-B3 + "x5","x6","x7","x8","x9", # C0-C4 + "x1","x10","x11","x19"); # TMP + my $mul45=&mul128x256_comba( + "x12","x13", # A0-A1 + "x24","x25","x26","x27", # B0-B3 + "x5","x6","x7","x8","x9", # C0-C4 + "x1","x10","x11","x19"); # TMP + my $mul67=&mul128x256_comba( + "x14","x15", # A0-A1 + "x24","x25","x26","x27", # B0-B3 + "x5","x6","x7","x8","x9", # C0-C4 + "x1","x10","x11","x19"); # TMP + my $body=<<___; + .global ${PREFIX}_fprdc + .align 4 + ${PREFIX}_fprdc: + stp x29, x30, [sp, #-112]! + add x29, sp, #0 + stp x19, x20, [sp,#16] + stp x21, x22, [sp,#32] + stp x23, x24, [sp,#48] + stp x25, x26, [sp,#64] + stp x27, x28, [sp,#80] + str x1, [sp,#96] + + ldp x2, x3, [x0,#0] // a[0-1] + + // Load the prime constant + adrp x23, :pg_hi21:.Lp503p1_nz_s8 + add x23, x23, :lo12:.Lp503p1_nz_s8 + ldp x24, x25, [x23, #0] + ldp x26, x27, [x23, #16] + + // a[0-1] x .Lp503p1_nz_s8 --> result: x4:x9 + mul x4, x2, x24 // a[0] x .Lp503p1_nz_s8[0] + umulh x7, x2, x24 + mul x5, x2, x25 // a[0] x .Lp503p1_nz_s8[1] + umulh x6, x2, x25 + + $mul01 + + ldp x2, x3, [x0,#16] // a[2] + ldp x12, x13, [x0,#32] + ldp x14, x15, [x0,#48] + + orr x10, xzr, x9, lsr #8 + lsl x9, x9, #56 + orr x9, x9, x8, lsr #8 + lsl x8, x8, #56 + orr x8, x8, x7, lsr #8 + lsl x7, x7, #56 + orr x7, x7, x6, lsr #8 + lsl x6, x6, #56 + orr x6, x6, x5, lsr #8 + lsl x5, x5, #56 + orr x5, x5, x4, lsr #8 + lsl x4, x4, #56 + + adds x3, x4, x3 // a[3] + adcs x12, x5, x12 // a[4] + adcs x13, x6, x13 + adcs x14, x7, x14 + adcs x15, x8, x15 + ldp x16, x17, [x0,#64] + ldp x28, x30, [x0,#80] + mul x4, x2, x24 // a[2] x .Lp503p1_nz_s8[0] + umulh x7, x2, x24 + adcs x16, x9, x16 + adcs x17, x10, x17 + adcs x28, xzr, x28 + adcs x30, xzr, x30 + ldp x20, x21, [x0,#96] + ldp x22, x23, [x0,#112] + mul x5, x2, x25 // a[2] x .Lp503p1_nz_s8[1] + umulh x6, x2, x25 + adcs x20, xzr, x20 + adcs x21, xzr, x21 + adcs x22, xzr, x22 + adc x23, xzr, x23 + + // a[2-3] x .Lp503p1_nz_s8 --> result: x4:x9 + $mul23 + + orr x10, xzr, x9, lsr #8 + lsl x9, x9, #56 + orr x9, x9, x8, lsr #8 + lsl x8, x8, #56 + orr x8, x8, x7, lsr #8 + lsl x7, x7, #56 + orr x7, x7, x6, lsr #8 + lsl x6, x6, #56 + orr x6, x6, x5, lsr #8 + lsl x5, x5, #56 + orr x5, x5, x4, lsr #8 + lsl x4, x4, #56 + + adds x13, x4, x13 // a[5] + adcs x14, x5, x14 // a[6] + adcs x15, x6, x15 + adcs x16, x7, x16 + mul x4, x12, x24 // a[4] x .Lp503p1_nz_s8[0] + umulh x7, x12, x24 + adcs x17, x8, x17 + adcs x28, x9, x28 + adcs x30, x10, x30 + adcs x20, xzr, x20 + mul x5, x12, x25 // a[4] x .Lp503p1_nz_s8[1] + umulh x6, x12, x25 + adcs x21, xzr, x21 + adcs x22, xzr, x22 + adc x23, xzr, x23 + + // a[4-5] x .Lp503p1_nz_s8 --> result: x4:x9 + $mul45 + + orr x10, xzr, x9, lsr #8 + lsl x9, x9, #56 + orr x9, x9, x8, lsr #8 + lsl x8, x8, #56 + orr x8, x8, x7, lsr #8 + lsl x7, x7, #56 + orr x7, x7, x6, lsr #8 + lsl x6, x6, #56 + orr x6, x6, x5, lsr #8 + lsl x5, x5, #56 + orr x5, x5, x4, lsr #8 + lsl x4, x4, #56 + + adds x15, x4, x15 // a[7] + adcs x16, x5, x16 // a[8] + adcs x17, x6, x17 + adcs x28, x7, x28 + mul x4, x14, x24 // a[6] x .Lp503p1_nz_s8[0] + umulh x7, x14, x24 + adcs x30, x8, x30 + adcs x20, x9, x20 + adcs x21, x10, x21 + mul x5, x14, x25 // a[6] x .Lp503p1_nz_s8[1] + umulh x6, x14, x25 + adcs x22, xzr, x22 + adc x23, xzr, x23 + + // a[6-7] x .Lp503p1_nz_s8 --> result: x4:x9 + $mul67 + + orr x10, xzr, x9, lsr #8 + lsl x9, x9, #56 + orr x9, x9, x8, lsr #8 + lsl x8, x8, #56 + orr x8, x8, x7, lsr #8 + lsl x7, x7, #56 + orr x7, x7, x6, lsr #8 + lsl x6, x6, #56 + orr x6, x6, x5, lsr #8 + lsl x5, x5, #56 + orr x5, x5, x4, lsr #8 + lsl x4, x4, #56 + + adds x17, x4, x17 + adcs x28, x5, x28 + ldr x1, [sp,#96] + adcs x30, x6, x30 + adcs x20, x7, x20 + stp x16, x17, [x1,#0] // Final result + stp x28, x30, [x1,#16] + adcs x21, x8, x21 + adcs x22, x9, x22 + adc x23, x10, x23 + stp x20, x21, [x1,#32] + stp x22, x23, [x1,#48] + + ldp x19, x20, [x29,#16] + ldp x21, x22, [x29,#32] + ldp x23, x24, [x29,#48] + ldp x25, x26, [x29,#64] + ldp x27, x28, [x29,#80] + ldp x29, x30, [sp],#112 + ret + +___ +} + +$code.=&rdc(); + + +# Field addition +# Operation: c [x2] = a [x0] + b [x1] +$code.=<<___; + .global ${PREFIX}_fpadd + .align 4 + ${PREFIX}_fpadd: + stp x29,x30, [sp,#-16]! + add x29, sp, #0 + + ldp x3, x4, [x0,#0] + ldp x5, x6, [x0,#16] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + + // Add a + b + adds x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x13 + adcs x6, x6, x14 + ldp x7, x8, [x0,#32] + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#32] + ldp x13, x14, [x1,#48] + adcs x7, x7, x11 + adcs x8, x8, x12 + adcs x9, x9, x13 + adc x10, x10, x14 + + // Subtract 2xp503 + adrp x17, :pg_hi21:.Lp503x2 + add x17, x17, :lo12:.Lp503x2 + ldp x11, x12, [x17, #0] + ldp x13, x14, [x17, #16] + subs x3, x3, x11 + sbcs x4, x4, x12 + sbcs x5, x5, x12 + sbcs x6, x6, x13 + sbcs x7, x7, x14 + + ldp x15, x16, [x17, #32] + ldr x17, [x17, #48] + sbcs x8, x8, x15 + sbcs x9, x9, x16 + sbcs x10, x10, x17 + sbc x0, xzr, xzr // x0 can be reused now + + // Add 2xp503 anded with the mask in x0 + and x11, x11, x0 + and x12, x12, x0 + and x13, x13, x0 + and x14, x14, x0 + and x15, x15, x0 + and x16, x16, x0 + and x17, x17, x0 + + adds x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x12 + adcs x6, x6, x13 + adcs x7, x7, x14 + adcs x8, x8, x15 + adcs x9, x9, x16 + adc x10, x10, x17 + + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + + ldp x29, x30, [sp],#16 + ret + +___ + +# Field subtraction +# Operation: c [x2] = a [x0] - b [x1] +$code.=<<___; + .global ${PREFIX}_fpsub + .align 4 + ${PREFIX}_fpsub: + stp x29, x30, [sp,#-16]! + add x29, sp, #0 + + ldp x3, x4, [x0,#0] + ldp x5, x6, [x0,#16] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + + // Subtract a - b + subs x3, x3, x11 + sbcs x4, x4, x12 + sbcs x5, x5, x13 + sbcs x6, x6, x14 + ldp x7, x8, [x0,#32] + ldp x11, x12, [x1,#32] + sbcs x7, x7, x11 + sbcs x8, x8, x12 + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#48] + sbcs x9, x9, x11 + sbcs x10, x10, x12 + sbc x17, xzr, xzr + + // Add 2xp503 anded with the mask in x17 + adrp x16, :pg_hi21:.Lp503x2 + add x16, x16, :lo12:.Lp503x2 + + // First half + ldp x11, x12, [x16, #0] + ldp x13, x14, [x16, #16] + and x11, x11, x17 + and x12, x12, x17 + and x13, x13, x17 + adds x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x12 + adcs x6, x6, x13 + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + + // Second half + ldp x11, x12, [x16, #32] + ldr x13, [x16, #48] + and x14, x14, x17 + and x11, x11, x17 + and x12, x12, x17 + and x13, x13, x17 + adcs x7, x7, x14 + adcs x8, x8, x11 + adcs x9, x9, x12 + adc x10, x10, x13 + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + + ldp x29, x30, [sp],#16 + ret +___ + +# 503-bit multiprecision addition +# Operation: c [x2] = a [x0] + b [x1] +$code.=<<___; + .global ${PREFIX}_mpadd_asm + .align 4 + ${PREFIX}_mpadd_asm: + stp x29, x30, [sp,#-16]! + add x29, sp, #0 + + ldp x3, x4, [x0,#0] + ldp x5, x6, [x0,#16] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + + adds x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x13 + adcs x6, x6, x14 + ldp x7, x8, [x0,#32] + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#32] + ldp x13, x14, [x1,#48] + adcs x7, x7, x11 + adcs x8, x8, x12 + adcs x9, x9, x13 + adc x10, x10, x14 + + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + + ldp x29, x30, [sp],#16 + ret +___ + + +# 2x503-bit multiprecision addition +# Operation: c [x2] = a [x0] + b [x1] +$code.=<<___; + .global ${PREFIX}_mpadd503x2_asm + .align 4 + ${PREFIX}_mpadd503x2_asm: + stp x29, x30, [sp,#-16]! + add x29, sp, #0 + + ldp x3, x4, [x0,#0] + ldp x5, x6, [x0,#16] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + adds x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x13 + adcs x6, x6, x14 + ldp x7, x8, [x0,#32] + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#32] + ldp x13, x14, [x1,#48] + adcs x7, x7, x11 + adcs x8, x8, x12 + adcs x9, x9, x13 + adcs x10, x10, x14 + + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + + ldp x3, x4, [x0,#64] + ldp x5, x6, [x0,#80] + ldp x11, x12, [x1,#64] + ldp x13, x14, [x1,#80] + adcs x3, x3, x11 + adcs x4, x4, x12 + adcs x5, x5, x13 + adcs x6, x6, x14 + ldp x7, x8, [x0,#96] + ldp x9, x10, [x0,#112] + ldp x11, x12, [x1,#96] + ldp x13, x14, [x1,#112] + adcs x7, x7, x11 + adcs x8, x8, x12 + adcs x9, x9, x13 + adc x10, x10, x14 + + stp x3, x4, [x2,#64] + stp x5, x6, [x2,#80] + stp x7, x8, [x2,#96] + stp x9, x10, [x2,#112] + + ldp x29, x30, [sp],#16 + ret +___ + + + +# 2x503-bit multiprecision subtraction +# Operation: c [x2] = a [x0] - b [x1]. +# Returns borrow mask +$code.=<<___; + .global ${PREFIX}_mpsubx2_asm + .align 4 + ${PREFIX}_mpsubx2_asm: + stp x29, x30, [sp,#-16]! + add x29, sp, #0 + + ldp x3, x4, [x0,#0] + ldp x5, x6, [x0,#16] + ldp x11, x12, [x1,#0] + ldp x13, x14, [x1,#16] + subs x3, x3, x11 + sbcs x4, x4, x12 + sbcs x5, x5, x13 + sbcs x6, x6, x14 + ldp x7, x8, [x0,#32] + ldp x9, x10, [x0,#48] + ldp x11, x12, [x1,#32] + ldp x13, x14, [x1,#48] + sbcs x7, x7, x11 + sbcs x8, x8, x12 + sbcs x9, x9, x13 + sbcs x10, x10, x14 + + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + + ldp x3, x4, [x0,#64] + ldp x5, x6, [x0,#80] + ldp x11, x12, [x1,#64] + ldp x13, x14, [x1,#80] + sbcs x3, x3, x11 + sbcs x4, x4, x12 + sbcs x5, x5, x13 + sbcs x6, x6, x14 + ldp x7, x8, [x0,#96] + ldp x9, x10, [x0,#112] + ldp x11, x12, [x1,#96] + ldp x13, x14, [x1,#112] + sbcs x7, x7, x11 + sbcs x8, x8, x12 + sbcs x9, x9, x13 + sbcs x10, x10, x14 + sbc x0, xzr, xzr + + stp x3, x4, [x2,#64] + stp x5, x6, [x2,#80] + stp x7, x8, [x2,#96] + stp x9, x10, [x2,#112] + + ldp x29, x30, [sp],#16 + ret +___ + + +# Double 2x503-bit multiprecision subtraction +# Operation: c [x2] = c [x2] - a [x0] - b [x1] +$code.=<<___; + .global ${PREFIX}_mpdblsubx2_asm + .align 4 + ${PREFIX}_mpdblsubx2_asm: + stp x29, x30, [sp, #-64]! + add x29, sp, #0 + + stp x20, x21, [sp, #16] + stp x22, x23, [sp, #32] + str x24, [sp, #48] + + ldp x3, x4, [x2,#0] + ldp x5, x6, [x2,#16] + ldp x7, x8, [x2,#32] + ldp x9, x10, [x2,#48] + ldp x11, x12, [x2,#64] + ldp x13, x14, [x2,#80] + ldp x15, x16, [x2,#96] + ldp x17, x24, [x2,#112] + + ldp x20, x21, [x0,#0] + ldp x22, x23, [x0,#16] + subs x3, x3, x20 + sbcs x4, x4, x21 + sbcs x5, x5, x22 + sbcs x6, x6, x23 + ldp x20, x21, [x0,#32] + ldp x22, x23, [x0,#48] + sbcs x7, x7, x20 + sbcs x8, x8, x21 + sbcs x9, x9, x22 + sbcs x10, x10, x23 + ldp x20, x21, [x0,#64] + ldp x22, x23, [x0,#80] + sbcs x11, x11, x20 + sbcs x12, x12, x21 + sbcs x13, x13, x22 + sbcs x14, x14, x23 + ldp x20, x21, [x0,#96] + ldp x22, x23, [x0,#112] + sbcs x15, x15, x20 + sbcs x16, x16, x21 + sbcs x17, x17, x22 + sbc x24, x24, x23 + + ldp x20, x21, [x1,#0] + ldp x22, x23, [x1,#16] + subs x3, x3, x20 + sbcs x4, x4, x21 + sbcs x5, x5, x22 + sbcs x6, x6, x23 + ldp x20, x21, [x1,#32] + ldp x22, x23, [x1,#48] + sbcs x7, x7, x20 + sbcs x8, x8, x21 + sbcs x9, x9, x22 + sbcs x10, x10, x23 + ldp x20, x21, [x1,#64] + ldp x22, x23, [x1,#80] + sbcs x11, x11, x20 + sbcs x12, x12, x21 + sbcs x13, x13, x22 + sbcs x14, x14, x23 + ldp x20, x21, [x1,#96] + ldp x22, x23, [x1,#112] + sbcs x15, x15, x20 + sbcs x16, x16, x21 + sbcs x17, x17, x22 + sbc x24, x24, x23 + + stp x3, x4, [x2,#0] + stp x5, x6, [x2,#16] + stp x7, x8, [x2,#32] + stp x9, x10, [x2,#48] + stp x11, x12, [x2,#64] + stp x13, x14, [x2,#80] + stp x15, x16, [x2,#96] + stp x17, x24, [x2,#112] + + ldp x20, x21, [x29,#16] + ldp x22, x23, [x29,#32] + ldr x24, [x29,#48] + + ldp x29, x30, [sp],#64 + ret +___ + +foreach (split("\n",$code)) { + s/\`([^\`]*)\`/eval($1)/ge; + print $_,"\n"; +} + +close STDOUT; diff --git a/third_party/boringssl/kit/src/third_party/sike/asm/fp-x86_64.pl b/third_party/boringssl/kit/src/third_party/sike/asm/fp-x86_64.pl new file mode 100755 index 00000000..c093c203 --- /dev/null +++ b/third_party/boringssl/kit/src/third_party/sike/asm/fp-x86_64.pl @@ -0,0 +1,1850 @@ +#! /usr/bin/env perl +# +# April 2019 +# +# Abstract: field arithmetic in x64 assembly for SIDH/p503 + +$flavour = shift; +$output = shift; +if ($flavour =~ /\./) { $output = $flavour; undef $flavour; } + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; +( $xlate="${dir}x86_64-xlate.pl" and -f $xlate ) or +( $xlate="${dir}../../../crypto/perlasm/x86_64-xlate.pl" and -f $xlate) or +die "can't locate x86_64-xlate.pl"; + +open OUT,"| \"$^X\" \"$xlate\" $flavour \"$output\""; +*STDOUT=*OUT; + +$PREFIX="sike"; +$bmi2_adx = 1; + +$code.=<<___; +.text + +# p503 x 2 +.Lp503x2: +.quad 0xFFFFFFFFFFFFFFFE +.quad 0xFFFFFFFFFFFFFFFF +.quad 0x57FFFFFFFFFFFFFF +.quad 0x2610B7B44423CF41 +.quad 0x3737ED90F6FCFB5E +.quad 0xC08B8D7BB4EF49A0 +.quad 0x0080CDEA83023C3C + +# p503 + 1 +.Lp503p1: +.quad 0xAC00000000000000 +.quad 0x13085BDA2211E7A0 +.quad 0x1B9BF6C87B7E7DAF +.quad 0x6045C6BDDA77A4D0 +.quad 0x004066F541811E1E + +.Lp503p1_nz: +.quad 0xAC00000000000000 +.quad 0x13085BDA2211E7A0 +.quad 0x1B9BF6C87B7E7DAF +.quad 0x6045C6BDDA77A4D0 +.quad 0x004066F541811E1E + +.extern OPENSSL_ia32cap_P +.hidden OPENSSL_ia32cap_P + +___ + +# Performs schoolbook multiplication of 128-bit with 320-bit +# number. Uses MULX, ADOX, ADCX instruction. +sub mul128x320_school { + my ($idxM0,$M0,$M1,$T0,$T1,$T2,$T3,$T4,$T5,$T6,$T7,$T8,$T9)=@_; + my ($MUL0,$MUL8)=map("$idxM0+$_(%$M0)", (0,8)); + my $body.=<<___; + mov $MUL0, %rdx + mulx 0+$M1, %$T0, %$T1 # T0 <- C0_final + mulx 8+$M1, %$T4, %$T2 + + xor %rax, %rax + mulx 16+$M1, %$T5, %$T3 + adox %$T4, %$T1 + adox %$T5, %$T2 + mulx 24+$M1, %$T7, %$T4 + adox %$T7, %$T3 + mulx 32+$M1, %$T6, %$T5 + adox %$T6, %$T4 + adox %rax, %$T5 + + mov $MUL8, %rdx + mulx 0+$M1, %$T6, %$T7 + adcx %$T6, %$T1 # T1 <- C1_final + adcx %$T7, %$T2 + mulx 8+$M1, %$T8, %$T6 + adcx %$T6, %$T3 + mulx 16+$M1, %$T7, %$T9 + adcx %$T9, %$T4 + mulx 24+$M1, %$T9, %$T6 + adcx %$T6, %$T5 + mulx 32+$M1, %rdx, %$T6 + adcx %rax, %$T6 + + xor %rax, %rax + adox %$T8, %$T2 + adox %$T7, %$T3 + adox %$T9, %$T4 + adox %rdx, %$T5 + adox %rax, %$T6 + +___ + return $body; +} + +# Compute z = x + y (mod p). +# Operation: c [rdx] = a [rdi] + b [rsi] +$code.=<<___; +.globl ${PREFIX}_fpadd +.type ${PREFIX}_fpadd,\@function,3 +${PREFIX}_fpadd: +.cfi_startproc + push %r12 +.cfi_adjust_cfa_offset 8 +.cfi_offset r12, -16 + push %r13 +.cfi_adjust_cfa_offset 8 +.cfi_offset r13, -24 + push %r14 +.cfi_adjust_cfa_offset 8 +.cfi_offset r14, -32 + push %r15 +.cfi_adjust_cfa_offset 8 +.cfi_offset r15, -40 + + xor %rax, %rax + + mov 0x0(%rdi), %r8 + mov 0x8(%rdi), %r9 + mov 0x10(%rdi), %r10 + mov 0x18(%rdi), %r11 + mov 0x20(%rdi), %r12 + mov 0x28(%rdi), %r13 + mov 0x30(%rdi), %r14 + mov 0x38(%rdi), %r15 + + add 0x0(%rsi), %r8 + adc 0x8(%rsi), %r9 + adc 0x10(%rsi), %r10 + adc 0x18(%rsi), %r11 + adc 0x20(%rsi), %r12 + adc 0x28(%rsi), %r13 + adc 0x30(%rsi), %r14 + adc 0x38(%rsi), %r15 + + mov .Lp503x2(%rip), %rcx; + sub %rcx, %r8 + mov 8+.Lp503x2(%rip), %rcx; + sbb %rcx, %r9 + sbb %rcx, %r10 + mov 16+.Lp503x2(%rip), %rcx; + sbb %rcx, %r11 + mov 24+.Lp503x2(%rip), %rcx; + sbb %rcx, %r12 + mov 32+.Lp503x2(%rip), %rcx; + sbb %rcx, %r13 + mov 40+.Lp503x2(%rip), %rcx; + sbb %rcx, %r14 + mov 48+.Lp503x2(%rip), %rcx; + sbb %rcx, %r15 + sbb \$0, %rax + + mov .Lp503x2(%rip), %rdi + and %rax, %rdi + mov 8+.Lp503x2(%rip), %rsi + and %rax, %rsi + mov 16+.Lp503x2(%rip), %rcx + and %rax, %rcx + + add %rdi, %r8 + mov %r8, 0x0(%rdx) + adc %rsi, %r9 + mov %r9, 0x8(%rdx) + adc %rsi, %r10 + mov %r10, 0x10(%rdx) + adc %rcx, %r11 + mov %r11, 0x18(%rdx) + + setc %cl + + mov 24+.Lp503x2(%rip), %r8 + and %rax, %r8 + mov 32+.Lp503x2(%rip), %r9 + and %rax, %r9 + mov 40+.Lp503x2(%rip), %r10 + and %rax, %r10 + mov 48+.Lp503x2(%rip), %r11 + and %rax, %r11 + + bt \$0, %rcx + + adc %r8, %r12 + mov %r12, 0x20(%rdx) + adc %r9, %r13 + mov %r13, 0x28(%rdx) + adc %r10, %r14 + mov %r14, 0x30(%rdx) + adc %r11, %r15 + mov %r15, 0x38(%rdx) + + pop %r15 +.cfi_adjust_cfa_offset -8 + pop %r14 +.cfi_adjust_cfa_offset -8 + pop %r13 +.cfi_adjust_cfa_offset -8 + pop %r12 +.cfi_adjust_cfa_offset -8 + ret +.cfi_endproc +___ + + + +# Loads data to XMM0 and XMM1 and +# conditionaly swaps depending on XMM3 +sub cswap_block16() { + my $idx = shift; + $idx *= 16; + (" + movdqu $idx(%rdi), %xmm0 + movdqu $idx(%rsi), %xmm1 + movdqa %xmm1, %xmm2 + pxor %xmm0, %xmm2 + pand %xmm3, %xmm2 + pxor %xmm2, %xmm0 + pxor %xmm2, %xmm1 + movdqu %xmm0, $idx(%rdi) + movdqu %xmm1, $idx(%rsi) + "); +} + +# Conditionally swaps bits in x and y in constant time. +# mask indicates bits to be swapped (set bits are swapped) +# Operation: [rdi] <-> [rsi] if rdx==1 +sub cswap { + # P[0].X with Q[0].X + foreach ( 0.. 3){$BLOCKS.=eval "&cswap_block16($_)";} + # P[0].Z with Q[0].Z + foreach ( 4.. 7){$BLOCKS.=eval "&cswap_block16($_)";} + # P[1].X with Q[1].X + foreach ( 8..11){$BLOCKS.=eval "&cswap_block16($_)";} + # P[1].Z with Q[1].Z + foreach (12..15){$BLOCKS.=eval "&cswap_block16($_)";} + + my $body =<<___; +.globl ${PREFIX}_cswap_asm +.type ${PREFIX}_cswap_asm,\@function,3 +${PREFIX}_cswap_asm: + # Fill XMM3. After this step first half of XMM3 is + # just zeros and second half is whatever in RDX + mov %rdx, %xmm3 + + # Copy lower double word everywhere else. So that + # XMM3=RDX|RDX. As RDX has either all bits set + # or non result will be that XMM3 has also either + # all bits set or non of them. 68 = 01000100b + pshufd \$68, %xmm3, %xmm3 + $BLOCKS + ret +___ + ($body) +} +$code.=&cswap(); + +# Field subtraction +# Operation: c [rdx] = a [rdi] - b [rsi] +$code.=<<___; +.globl ${PREFIX}_fpsub +.type ${PREFIX}_fpsub,\@function,3 +${PREFIX}_fpsub: +.cfi_startproc + push %r12 +.cfi_adjust_cfa_offset 8 +.cfi_offset r12, -16 + push %r13 +.cfi_adjust_cfa_offset 8 +.cfi_offset r13, -24 + push %r14 +.cfi_adjust_cfa_offset 8 +.cfi_offset r14, -32 + push %r15 +.cfi_adjust_cfa_offset 8 +.cfi_offset r15, -40 + + xor %rax, %rax + + mov 0x0(%rdi), %r8 + mov 0x8(%rdi), %r9 + mov 0x10(%rdi), %r10 + mov 0x18(%rdi), %r11 + mov 0x20(%rdi), %r12 + mov 0x28(%rdi), %r13 + mov 0x30(%rdi), %r14 + mov 0x38(%rdi), %r15 + + sub 0x0(%rsi), %r8 + sbb 0x8(%rsi), %r9 + sbb 0x10(%rsi), %r10 + sbb 0x18(%rsi), %r11 + sbb 0x20(%rsi), %r12 + sbb 0x28(%rsi), %r13 + sbb 0x30(%rsi), %r14 + sbb 0x38(%rsi), %r15 + sbb \$0x0, %rax + + mov .Lp503x2(%rip), %rdi + and %rax, %rdi + mov 0x8+.Lp503x2(%rip), %rsi + and %rax, %rsi + mov 0x10+.Lp503x2(%rip), %rcx + and %rax, %rcx + + add %rdi, %r8 + adc %rsi, %r9 + adc %rsi, %r10 + adc %rcx, %r11 + mov %r8, 0x0(%rdx) + mov %r9, 0x8(%rdx) + mov %r10, 0x10(%rdx) + mov %r11, 0x18(%rdx) + + setc %cl + + mov 0x18+.Lp503x2(%rip), %r8 + and %rax, %r8 + mov 0x20+.Lp503x2(%rip), %r9 + and %rax, %r9 + mov 0x28+.Lp503x2(%rip), %r10 + and %rax, %r10 + mov 0x30+.Lp503x2(%rip), %r11 + and %rax, %r11 + + bt \$0x0, %rcx + + adc %r8, %r12 + adc %r9, %r13 + adc %r10, %r14 + adc %r11, %r15 + mov %r12, 0x20(%rdx) + mov %r13, 0x28(%rdx) + mov %r14, 0x30(%rdx) + mov %r15, 0x38(%rdx) + + pop %r15 +.cfi_adjust_cfa_offset -8 + pop %r14 +.cfi_adjust_cfa_offset -8 + pop %r13 +.cfi_adjust_cfa_offset -8 + pop %r12 +.cfi_adjust_cfa_offset -8 + ret +.cfi_endproc +___ + +# 503-bit multiprecision addition +# Operation: c [rdx] = a [rdi] + b [rsi] +$code.=<<___; +.globl ${PREFIX}_mpadd_asm +.type ${PREFIX}_mpadd_asm,\@function,3 +${PREFIX}_mpadd_asm: +.cfi_startproc + mov 0x0(%rdi), %r8 + mov 0x8(%rdi), %r9 + mov 0x10(%rdi), %r10 + mov 0x18(%rdi), %r11 + add 0x0(%rsi), %r8 + adc 0x8(%rsi), %r9 + adc 0x10(%rsi), %r10 + adc 0x18(%rsi), %r11 + mov %r8, 0x0(%rdx) + mov %r9, 0x8(%rdx) + mov %r10, 0x10(%rdx) + mov %r11, 0x18(%rdx) + + mov 0x20(%rdi), %r8 + mov 0x28(%rdi), %r9 + mov 0x30(%rdi), %r10 + mov 0x38(%rdi), %r11 + adc 0x20(%rsi), %r8 + adc 0x28(%rsi), %r9 + adc 0x30(%rsi), %r10 + adc 0x38(%rsi), %r11 + mov %r8, 0x20(%rdx) + mov %r9, 0x28(%rdx) + mov %r10, 0x30(%rdx) + mov %r11, 0x38(%rdx) + ret +.cfi_endproc +___ + +# 2x503-bit multiprecision subtraction +# Operation: c [rdx] = a [rdi] - b [rsi]. +# Returns borrow mask +$code.=<<___; +.globl ${PREFIX}_mpsubx2_asm +.type ${PREFIX}_mpsubx2_asm,\@function,3 +${PREFIX}_mpsubx2_asm: +.cfi_startproc + xor %rax, %rax + + mov 0x0(%rdi), %r8 + mov 0x8(%rdi), %r9 + mov 0x10(%rdi), %r10 + mov 0x18(%rdi), %r11 + mov 0x20(%rdi), %rcx + sub 0x0(%rsi), %r8 + sbb 0x8(%rsi), %r9 + sbb 0x10(%rsi), %r10 + sbb 0x18(%rsi), %r11 + sbb 0x20(%rsi), %rcx + mov %r8, 0x0(%rdx) + mov %r9, 0x8(%rdx) + mov %r10, 0x10(%rdx) + mov %r11, 0x18(%rdx) + mov %rcx, 0x20(%rdx) + + mov 0x28(%rdi), %r8 + mov 0x30(%rdi), %r9 + mov 0x38(%rdi), %r10 + mov 0x40(%rdi), %r11 + mov 0x48(%rdi), %rcx + sbb 0x28(%rsi), %r8 + sbb 0x30(%rsi), %r9 + sbb 0x38(%rsi), %r10 + sbb 0x40(%rsi), %r11 + sbb 0x48(%rsi), %rcx + mov %r8, 0x28(%rdx) + mov %r9, 0x30(%rdx) + mov %r10, 0x38(%rdx) + mov %r11, 0x40(%rdx) + mov %rcx, 0x48(%rdx) + + mov 0x50(%rdi), %r8 + mov 0x58(%rdi), %r9 + mov 0x60(%rdi), %r10 + mov 0x68(%rdi), %r11 + mov 0x70(%rdi), %rcx + sbb 0x50(%rsi), %r8 + sbb 0x58(%rsi), %r9 + sbb 0x60(%rsi), %r10 + sbb 0x68(%rsi), %r11 + sbb 0x70(%rsi), %rcx + mov %r8, 0x50(%rdx) + mov %r9, 0x58(%rdx) + mov %r10, 0x60(%rdx) + mov %r11, 0x68(%rdx) + mov %rcx, 0x70(%rdx) + + mov 0x78(%rdi), %r8 + sbb 0x78(%rsi), %r8 + sbb \$0x0, %rax + mov %r8, 0x78(%rdx) + ret +.cfi_endproc +___ + +# Double 2x503-bit multiprecision subtraction +# Operation: c [rdx] = c [rdx] - a [rdi] - b [rsi] +$code.=<<___; +.globl ${PREFIX}_mpdblsubx2_asm +.type ${PREFIX}_mpdblsubx2_asm,\@function,3 +${PREFIX}_mpdblsubx2_asm: +.cfi_startproc + push %r12 +.cfi_adjust_cfa_offset 8 +.cfi_offset r12, -16 + push %r13 +.cfi_adjust_cfa_offset 8 +.cfi_offset r13, -24 + push %r14 +.cfi_adjust_cfa_offset 8 +.cfi_offset r14, -32 + + xor %rax, %rax + + mov 0x0(%rdx), %r8 + mov 0x8(%rdx), %r9 + mov 0x10(%rdx), %r10 + mov 0x18(%rdx), %r11 + mov 0x20(%rdx), %r12 + mov 0x28(%rdx), %r13 + mov 0x30(%rdx), %r14 + mov 0x38(%rdx), %rcx + sub 0x0(%rdi), %r8 + sbb 0x8(%rdi), %r9 + sbb 0x10(%rdi), %r10 + sbb 0x18(%rdi), %r11 + sbb 0x20(%rdi), %r12 + sbb 0x28(%rdi), %r13 + sbb 0x30(%rdi), %r14 + sbb 0x38(%rdi), %rcx + adc \$0x0, %rax + + sub 0x0(%rsi), %r8 + sbb 0x8(%rsi), %r9 + sbb 0x10(%rsi), %r10 + sbb 0x18(%rsi), %r11 + sbb 0x20(%rsi), %r12 + sbb 0x28(%rsi), %r13 + sbb 0x30(%rsi), %r14 + sbb 0x38(%rsi), %rcx + adc \$0x0, %rax + + mov %r8, 0x0(%rdx) + mov %r9, 0x8(%rdx) + mov %r10, 0x10(%rdx) + mov %r11, 0x18(%rdx) + mov %r12, 0x20(%rdx) + mov %r13, 0x28(%rdx) + mov %r14, 0x30(%rdx) + mov %rcx, 0x38(%rdx) + + mov 0x40(%rdx), %r8 + mov 0x48(%rdx), %r9 + mov 0x50(%rdx), %r10 + mov 0x58(%rdx), %r11 + mov 0x60(%rdx), %r12 + mov 0x68(%rdx), %r13 + mov 0x70(%rdx), %r14 + mov 0x78(%rdx), %rcx + + sub %rax, %r8 + sbb 0x40(%rdi), %r8 + sbb 0x48(%rdi), %r9 + sbb 0x50(%rdi), %r10 + sbb 0x58(%rdi), %r11 + sbb 0x60(%rdi), %r12 + sbb 0x68(%rdi), %r13 + sbb 0x70(%rdi), %r14 + sbb 0x78(%rdi), %rcx + sub 0x40(%rsi), %r8 + sbb 0x48(%rsi), %r9 + sbb 0x50(%rsi), %r10 + sbb 0x58(%rsi), %r11 + sbb 0x60(%rsi), %r12 + sbb 0x68(%rsi), %r13 + sbb 0x70(%rsi), %r14 + sbb 0x78(%rsi), %rcx + + mov %r8, 0x40(%rdx) + mov %r9, 0x48(%rdx) + mov %r10, 0x50(%rdx) + mov %r11, 0x58(%rdx) + mov %r12, 0x60(%rdx) + mov %r13, 0x68(%rdx) + mov %r14, 0x70(%rdx) + mov %rcx, 0x78(%rdx) + + pop %r14 +.cfi_adjust_cfa_offset -8 + pop %r13 +.cfi_adjust_cfa_offset -8 + pop %r12 +.cfi_adjust_cfa_offset -8 + ret +.cfi_endproc + +___ + +# Performs schoolbook multiplication of 2 256-bit numbers. Uses +# MULX instruction. Result is stored in 256 bits pointed by $DST. +sub mul256_school { + my ($idxM0,$M0,$idxM1,$M1,$idxDST,$DST,$T0,$T1,$T2,$T3,$T4,$T5,$T6,$T7,$T8,$T9)=@_; + my ($ML0,$ML8,$ML16,$ML24)=map("$idxM0+$_(%$M0)",(0,8,16,24)); + my ($MR0,$MR8,$MR16,$MR24)=map("$idxM1+$_(%$M1)",(0,8,16,24)); + my ($D0,$D1,$D2,$D3,$D4,$D5,$D6,$D7)=map("$idxDST+$_(%$DST)",(0,8,16,24,32,40,48,56)); + + $body=<<___; + mov $ML0, %rdx + mulx $MR0, %$T1, %$T0 # T0:T1 = A0*B0 + mov %$T1, $D0 # DST0_final + mulx $MR8, %$T2, %$T1 # T1:T2 = A0*B1 + xor %rax, %rax + adox %$T2, %$T0 + mulx $MR16,%$T3, %$T2 # T2:T3 = A0*B2 + adox %$T3, %$T1 + mulx $MR24,%$T4, %$T3 # T3:T4 = A0*B3 + adox %$T4, %$T2 + + mov $ML8, %rdx + mulx $MR0, %$T4, %$T5 # T5:T4 = A1*B0 + adox %rax, %$T3 + xor %rax, %rax + mulx $MR8, %$T7, %$T6 # T6:T7 = A1*B1 + adox %$T0, %$T4 + mov %$T4, $D1 # DST1_final + adcx %$T7, %$T5 + mulx $MR16,%$T8, %$T7 # T7:T8 = A1*B2 + adcx %$T8, %$T6 + adox %$T1, %$T5 + mulx $MR24,%$T9, %$T8 # T8:T9 = A1*B3 + adcx %$T9, %$T7 + adcx %rax, %$T8 + adox %$T2, %$T6 + + mov $ML16,%rdx + mulx $MR0, %$T0, %$T1 # T1:T0 = A2*B0 + adox %$T3, %$T7 + adox %rax, %$T8 + xor %rax, %rax + mulx $MR8, %$T3, %$T2 # T2:T3 = A2*B1 + adox %$T5, %$T0 + mov %$T0, $D2 # DST2_final + adcx %$T3, %$T1 + mulx $MR16,%$T4, %$T3 # T3:T4 = A2*B2 + adcx %$T4, %$T2 + adox %$T6, %$T1 + mulx $MR24,%$T9, %$T4 # T3:T4 = A2*B3 + adcx %$T9, %$T3 + + adcx %rax, %$T4 + adox %$T7, %$T2 + adox %$T8, %$T3 + adox %rax, %$T4 + + mov $ML24, %rdx + mulx $MR0, %$T0, %$T5 # T5:T0 = A3*B0 + xor %rax, %rax + mulx $MR8, %$T7, %$T6 # T6:T7 = A3*B1 + adcx %$T7, %$T5 + adox %$T0, %$T1 + mulx $MR16, %$T8, %$T7 # T7:T8 = A3*B2 + adcx %$T8, %$T6 + adox %$T5, %$T2 + mulx $MR24, %$T9, %$T8 # T8:T9 = A3*B3 + adcx %$T9, %$T7 + adcx %rax, %$T8 + adox %$T6, %$T3 + adox %$T7, %$T4 + adox %rax, %$T8 + mov %$T1, $D3 # DST3_final + mov %$T2, $D4 # DST4_final + mov %$T3, $D5 # DST5_final + mov %$T4, $D6 # DST6_final + mov %$T8, $D7 # DST7_final + +___ + return $body; +} + +# 503-bit multiplication using Karatsuba (one level), +# schoolbook (one level). +sub mul_mulx { + # [rcx+64] <- (AH+AL) x (BH+BL) + my $mul256_low=&mul256_school(0,"rsp",32,"rsp",64,"rcx",map("r$_",(8..15)),"rbx","rbp"); + # [rcx] <- AL x BL + my $mul256_albl=&mul256_school(0,"rdi",0,"rsi",0,"rcx",map("r$_",(8..15)),"rbx","rbp"); + # [rsp] <- AH x BH + my $mul256_ahbh=&mul256_school(32,"rdi",32,"rsi",0,"rsp",map("r$_",(8..15)),"rbx","rbp"); + + $body=<<___; + .Lmul_mulx: + .cfi_startproc + # sike_mpmul has already pushed r12--15 by this point. + .cfi_adjust_cfa_offset 32 + .cfi_offset r12, -16 + .cfi_offset r13, -24 + .cfi_offset r14, -32 + .cfi_offset r15, -40 + + mov %rdx, %rcx + + # r8-r11 <- AH + AL, rax <- mask + xor %rax, %rax + mov (%rdi), %r8 + mov 0x8(%rdi), %r9 + mov 0x10(%rdi), %r10 + mov 0x18(%rdi), %r11 + push %rbx + + .cfi_adjust_cfa_offset 8 + .cfi_offset rbx, -48 + push %rbp + .cfi_offset rbp, -56 + .cfi_adjust_cfa_offset 8 + sub \$96, %rsp + .cfi_adjust_cfa_offset 96 + add 0x20(%rdi), %r8 + adc 0x28(%rdi), %r9 + adc 0x30(%rdi), %r10 + adc 0x38(%rdi), %r11 + sbb \$0x0, %rax + mov %r8, (%rsp) + mov %r9, 0x8(%rsp) + mov %r10, 0x10(%rsp) + mov %r11, 0x18(%rsp) + + # r12-r15 <- BH + BL, rbx <- mask + xor %rbx, %rbx + mov (%rsi), %r12 + mov 0x8(%rsi), %r13 + mov 0x10(%rsi), %r14 + mov 0x18(%rsi), %r15 + add 0x20(%rsi), %r12 + adc 0x28(%rsi), %r13 + adc 0x30(%rsi), %r14 + adc 0x38(%rsi), %r15 + sbb \$0x0, %rbx + mov %r12, 0x20(%rsp) + mov %r13, 0x28(%rsp) + mov %r14, 0x30(%rsp) + mov %r15, 0x38(%rsp) + + # r12-r15 <- masked (BH + BL) + and %rax, %r12 + and %rax, %r13 + and %rax, %r14 + and %rax, %r15 + + # r8-r11 <- masked (AH + AL) + and %rbx, %r8 + and %rbx, %r9 + and %rbx, %r10 + and %rbx, %r11 + + # r8-r11 <- masked (AH + AL) + masked (AH + AL) + add %r12, %r8 + adc %r13, %r9 + adc %r14, %r10 + adc %r15, %r11 + mov %r8, 0x40(%rsp) + mov %r9, 0x48(%rsp) + mov %r10, 0x50(%rsp) + mov %r11, 0x58(%rsp) + + # [rcx+64] <- (AH+AL) x (BH+BL) + $mul256_low + # [rcx] <- AL x BL (Result c0-c3) + $mul256_albl + # [rsp] <- AH x BH + $mul256_ahbh + + # r8-r11 <- (AH+AL) x (BH+BL), final step + mov 0x40(%rsp), %r8 + mov 0x48(%rsp), %r9 + mov 0x50(%rsp), %r10 + mov 0x58(%rsp), %r11 + mov 0x60(%rcx), %rax + add %rax, %r8 + mov 0x68(%rcx), %rax + adc %rax, %r9 + mov 0x70(%rcx), %rax + adc %rax, %r10 + mov 0x78(%rcx), %rax + adc %rax, %r11 + + # [rcx+64], x3-x5 <- (AH+AL) x (BH+BL) - ALxBL + mov 0x40(%rcx), %r12 + mov 0x48(%rcx), %r13 + mov 0x50(%rcx), %r14 + mov 0x58(%rcx), %r15 + sub (%rcx), %r12 + sbb 0x8(%rcx), %r13 + sbb 0x10(%rcx), %r14 + sbb 0x18(%rcx), %r15 + sbb 0x20(%rcx), %r8 + sbb 0x28(%rcx), %r9 + sbb 0x30(%rcx), %r10 + sbb 0x38(%rcx), %r11 + + # r8-r15 <- (AH+AL) x (BH+BL) - ALxBL - AHxBH + sub (%rsp), %r12 + sbb 0x8(%rsp), %r13 + sbb 0x10(%rsp), %r14 + sbb 0x18(%rsp), %r15 + sbb 0x20(%rsp), %r8 + sbb 0x28(%rsp), %r9 + sbb 0x30(%rsp), %r10 + sbb 0x38(%rsp), %r11 + + add 0x20(%rcx), %r12 + mov %r12, 0x20(%rcx) # Result C4-C7 + adc 0x28(%rcx), %r13 + mov %r13, 0x28(%rcx) + adc 0x30(%rcx), %r14 + mov %r14, 0x30(%rcx) + adc 0x38(%rcx), %r15 + mov %r15, 0x38(%rcx) + mov (%rsp), %rax + adc %rax, %r8 # Result C8-C15 + mov %r8, 0x40(%rcx) + mov 0x8(%rsp), %rax + adc %rax, %r9 + mov %r9, 0x48(%rcx) + mov 0x10(%rsp), %rax + adc %rax, %r10 + mov %r10, 0x50(%rcx) + mov 0x18(%rsp), %rax + adc %rax, %r11 + mov %r11, 0x58(%rcx) + mov 0x20(%rsp), %r12 + adc \$0x0, %r12 + mov %r12, 0x60(%rcx) + mov 0x28(%rsp), %r13 + adc \$0x0, %r13 + mov %r13, 0x68(%rcx) + mov 0x30(%rsp), %r14 + adc \$0x0, %r14 + mov %r14, 0x70(%rcx) + mov 0x38(%rsp), %r15 + adc \$0x0, %r15 + mov %r15, 0x78(%rcx) + + add \$96, %rsp + .cfi_adjust_cfa_offset -96 + pop %rbp + .cfi_adjust_cfa_offset -8 + .cfi_same_value rbp + pop %rbx + .cfi_adjust_cfa_offset -8 + .cfi_same_value rbx + pop %r15 + .cfi_adjust_cfa_offset -8 + .cfi_same_value r15 + pop %r14 + .cfi_adjust_cfa_offset -8 + .cfi_same_value r14 + pop %r13 + .cfi_adjust_cfa_offset -8 + .cfi_same_value r13 + pop %r12 + .cfi_adjust_cfa_offset -8 + .cfi_same_value r12 + ret + .cfi_endproc + +___ + return $body; +} + +# Jump to alternative implemenatation provided as an +# argument in case CPU supports ADOX/ADCX and MULX instructions. +sub alt_impl { + $jmp_func = shift; + + $body=<<___; + lea OPENSSL_ia32cap_P(%rip), %rcx + mov 8(%rcx), %rcx + and \$0x80100, %ecx + cmp \$0x80100, %ecx + je $jmp_func + +___ + return $body +} + +# Integer multiplication based on Karatsuba method +# Operation: c [rdx] = a [rdi] * b [rsi] +# NOTE: a=c or b=c are not allowed +sub mul { + my $jump_optim.=&alt_impl(".Lmul_mulx") if ($bmi2_adx); + my $body.=&mul_mulx() if ($bmi2_adx); + + $body.=<<___; + .globl ${PREFIX}_mpmul + .type ${PREFIX}_mpmul,\@function,3 + ${PREFIX}_mpmul: + .cfi_startproc + push %r12 + .cfi_adjust_cfa_offset 8 + .cfi_offset r12, -16 + push %r13 + .cfi_adjust_cfa_offset 8 + .cfi_offset r13, -24 + push %r14 + .cfi_adjust_cfa_offset 8 + .cfi_offset r14, -32 + push %r15 + .cfi_adjust_cfa_offset 8 + .cfi_offset r15, -40 + + $jump_optim + + mov %rdx, %rcx + + # rcx[0-3] <- AH+AL + xor %rax, %rax + mov 0x20(%rdi), %r8 + mov 0x28(%rdi), %r9 + mov 0x30(%rdi), %r10 + mov 0x38(%rdi), %r11 + add 0x0(%rdi), %r8 + adc 0x8(%rdi), %r9 + adc 0x10(%rdi), %r10 + adc 0x18(%rdi), %r11 + mov %r8, 0x0(%rcx) + mov %r9, 0x8(%rcx) + mov %r10, 0x10(%rcx) + mov %r11, 0x18(%rcx) + sbb \$0, %rax + sub \$80, %rsp # Allocating space in stack + .cfi_adjust_cfa_offset 80 + + # r12-r15 <- BH+BL + xor %rdx, %rdx + mov 0x20(%rsi), %r12 + mov 0x28(%rsi), %r13 + mov 0x30(%rsi), %r14 + mov 0x38(%rsi), %r15 + add 0x0(%rsi), %r12 + adc 0x8(%rsi), %r13 + adc 0x10(%rsi), %r14 + adc 0x18(%rsi), %r15 + sbb \$0x0, %rdx + mov %rax, 0x40(%rsp) + mov %rdx, 0x48(%rsp) + + # (rsp[0-3],r8,r9,r10,r11) <- (AH+AL)*(BH+BL) + mov (%rcx), %rax + mul %r12 + mov %rax, (%rsp) # c0 + mov %rdx, %r8 + + xor %r9, %r9 + mov (%rcx), %rax + mul %r13 + add %rax, %r8 + adc %rdx, %r9 + + xor %r10, %r10 + mov 0x8(%rcx), %rax + mul %r12 + add %rax, %r8 + mov %r8, 0x8(%rsp) # c1 + adc %rdx, %r9 + adc \$0x0, %r10 + + xor %r8, %r8 + mov (%rcx), %rax + mul %r14 + add %rax, %r9 + adc %rdx, %r10 + adc \$0x0, %r8 + + mov 0x10(%rcx), %rax + mul %r12 + add %rax, %r9 + adc %rdx, %r10 + adc \$0x0, %r8 + + mov 0x8(%rcx), %rax + mul %r13 + add %rax, %r9 + mov %r9, 0x10(%rsp) # c2 + adc %rdx, %r10 + adc \$0x0, %r8 + + xor %r9, %r9 + mov (%rcx), %rax + mul %r15 + add %rax, %r10 + adc %rdx, %r8 + adc \$0x0, %r9 + + mov 0x18(%rcx), %rax + mul %r12 + add %rax, %r10 + adc %rdx, %r8 + adc \$0x0, %r9 + + mov 0x8(%rcx), %rax + mul %r14 + add %rax, %r10 + adc %rdx, %r8 + adc \$0x0, %r9 + + mov 0x10(%rcx), %rax + mul %r13 + add %rax, %r10 + mov %r10, 0x18(%rsp) # c3 + adc %rdx, %r8 + adc \$0x0, %r9 + + xor %r10, %r10 + mov 0x8(%rcx), %rax + mul %r15 + add %rax, %r8 + adc %rdx, %r9 + adc \$0x0, %r10 + + mov 0x18(%rcx), %rax + mul %r13 + add %rax, %r8 + adc %rdx, %r9 + adc \$0x0, %r10 + + mov 0x10(%rcx), %rax + mul %r14 + add %rax, %r8 + mov %r8, 0x20(%rsp) # c4 + adc %rdx, %r9 + adc \$0x0, %r10 + + xor %r11, %r11 + mov 0x10(%rcx), %rax + mul %r15 + add %rax, %r9 + adc %rdx, %r10 + adc \$0x0, %r11 + + mov 0x18(%rcx), %rax + mul %r14 + add %rax, %r9 # c5 + adc %rdx, %r10 + adc \$0x0, %r11 + + mov 0x18(%rcx), %rax + mul %r15 + add %rax, %r10 # c6 + adc %rdx, %r11 # c7 + + mov 0x40(%rsp), %rax + and %rax, %r12 + and %rax, %r13 + and %rax, %r14 + and %rax, %r15 + add %r8, %r12 + adc %r9, %r13 + adc %r10, %r14 + adc %r11, %r15 + + mov 0x48(%rsp), %rax + mov (%rcx), %r8 + mov 0x8(%rcx), %r9 + mov 0x10(%rcx), %r10 + mov 0x18(%rcx), %r11 + and %rax, %r8 + and %rax, %r9 + and %rax, %r10 + and %rax, %r11 + add %r12, %r8 + adc %r13, %r9 + adc %r14, %r10 + adc %r15, %r11 + mov %r8, 0x20(%rsp) + mov %r9, 0x28(%rsp) + mov %r10, 0x30(%rsp) + mov %r11, 0x38(%rsp) + + mov (%rdi), %r11 + mov (%rsi), %rax + mul %r11 + xor %r9, %r9 + mov %rax, (%rcx) # c0 + mov %rdx, %r8 + + mov 0x10(%rdi), %r14 + mov 0x8(%rsi), %rax + mul %r11 + xor %r10, %r10 + add %rax, %r8 + adc %rdx, %r9 + + mov 0x8(%rdi), %r12 + mov (%rsi), %rax + mul %r12 + add %rax, %r8 + mov %r8, 0x8(%rcx) # c1 + adc %rdx, %r9 + adc \$0x0, %r10 + + xor %r8, %r8 + mov 0x10(%rsi), %rax + mul %r11 + add %rax, %r9 + adc %rdx, %r10 + adc \$0x0, %r8 + + mov (%rsi), %r13 + mov %r14, %rax + mul %r13 + add %rax, %r9 + adc %rdx, %r10 + adc \$0x0, %r8 + + mov 0x8(%rsi), %rax + mul %r12 + add %rax, %r9 + mov %r9, 0x10(%rcx) # c2 + adc %rdx, %r10 + adc \$0x0, %r8 + + xor %r9, %r9 + mov 0x18(%rsi), %rax + mul %r11 + mov 0x18(%rdi), %r15 + add %rax, %r10 + adc %rdx, %r8 + adc \$0x0, %r9 + + mov %r15, %rax + mul %r13 + add %rax, %r10 + adc %rdx, %r8 + adc \$0x0, %r9 + + mov 0x10(%rsi), %rax + mul %r12 + add %rax, %r10 + adc %rdx, %r8 + adc \$0x0, %r9 + + mov 0x8(%rsi), %rax + mul %r14 + add %rax, %r10 + mov %r10, 0x18(%rcx) # c3 + adc %rdx, %r8 + adc \$0x0, %r9 + + xor %r10, %r10 + mov 0x18(%rsi), %rax + mul %r12 + add %rax, %r8 + adc %rdx, %r9 + adc \$0x0, %r10 + + mov 0x8(%rsi), %rax + mul %r15 + add %rax, %r8 + adc %rdx, %r9 + adc \$0x0, %r10 + + mov 0x10(%rsi), %rax + mul %r14 + add %rax, %r8 + mov %r8, 0x20(%rcx) # c4 + adc %rdx, %r9 + adc \$0x0, %r10 + + xor %r8, %r8 + mov 0x18(%rsi), %rax + mul %r14 + add %rax, %r9 + adc %rdx, %r10 + adc \$0x0, %r8 + + mov 0x10(%rsi), %rax + mul %r15 + add %rax, %r9 + mov %r9, 0x28(%rcx) # c5 + adc %rdx, %r10 + adc \$0x0, %r8 + + mov 0x18(%rsi), %rax + mul %r15 + add %rax, %r10 + mov %r10, 0x30(%rcx) # c6 + adc %rdx, %r8 + mov %r8, 0x38(%rcx) # c7 + + # rcx[8-15] <- AH*BH + mov 0x20(%rdi), %r11 + mov 0x20(%rsi), %rax + mul %r11 + xor %r9, %r9 + mov %rax, 0x40(%rcx) # c0 + mov %rdx, %r8 + + mov 0x30(%rdi), %r14 + mov 0x28(%rsi), %rax + mul %r11 + xor %r10, %r10 + add %rax, %r8 + adc %rdx, %r9 + + mov 0x28(%rdi), %r12 + mov 0x20(%rsi), %rax + mul %r12 + add %rax, %r8 + mov %r8, 0x48(%rcx) # c1 + adc %rdx, %r9 + adc \$0x0, %r10 + + xor %r8, %r8 + mov 0x30(%rsi), %rax + mul %r11 + add %rax, %r9 + adc %rdx, %r10 + adc \$0x0, %r8 + + mov 0x20(%rsi), %r13 + mov %r14, %rax + mul %r13 + add %rax, %r9 + adc %rdx, %r10 + adc \$0x0, %r8 + + mov 0x28(%rsi), %rax + mul %r12 + add %rax, %r9 + mov %r9, 0x50(%rcx) # c2 + adc %rdx, %r10 + adc \$0x0, %r8 + + xor %r9, %r9 + mov 0x38(%rsi), %rax + mul %r11 + mov 0x38(%rdi), %r15 + add %rax, %r10 + adc %rdx, %r8 + adc \$0x0, %r9 + + mov %r15, %rax + mul %r13 + add %rax, %r10 + adc %rdx, %r8 + adc \$0x0, %r9 + + mov 0x30(%rsi), %rax + mul %r12 + add %rax, %r10 + adc %rdx, %r8 + adc \$0x0, %r9 + + mov 0x28(%rsi), %rax + mul %r14 + add %rax, %r10 + mov %r10, 0x58(%rcx) # c3 + adc %rdx, %r8 + adc \$0x0, %r9 + + xor %r10, %r10 + mov 0x38(%rsi), %rax + mul %r12 + add %rax, %r8 + adc %rdx, %r9 + adc \$0x0, %r10 + + mov 0x28(%rsi), %rax + mul %r15 + add %rax, %r8 + adc %rdx, %r9 + adc \$0x0, %r10 + + mov 0x30(%rsi), %rax + mul %r14 + add %rax, %r8 + mov %r8, 0x60(%rcx) # c4 + adc %rdx, %r9 + adc \$0x0, %r10 + + xor %r8, %r8 + mov 0x38(%rsi), %rax + mul %r14 + add %rax, %r9 + adc %rdx, %r10 + adc \$0x0, %r8 + + mov 0x30(%rsi), %rax + mul %r15 + add %rax, %r9 + mov %r9, 0x68(%rcx) # c5 + adc %rdx, %r10 + adc \$0x0, %r8 + + mov 0x38(%rsi), %rax + mul %r15 + add %rax, %r10 + mov %r10, 0x70(%rcx) # c6 + adc %rdx, %r8 + mov %r8, 0x78(%rcx) # c7 + + # [r8-r15] <- (AH+AL)*(BH+BL) - AL*BL + mov 0x0(%rsp), %r8 + sub 0x0(%rcx), %r8 + mov 0x8(%rsp), %r9 + sbb 0x8(%rcx), %r9 + mov 0x10(%rsp), %r10 + sbb 0x10(%rcx), %r10 + mov 0x18(%rsp), %r11 + sbb 0x18(%rcx), %r11 + mov 0x20(%rsp), %r12 + sbb 0x20(%rcx), %r12 + mov 0x28(%rsp), %r13 + sbb 0x28(%rcx), %r13 + mov 0x30(%rsp), %r14 + sbb 0x30(%rcx), %r14 + mov 0x38(%rsp), %r15 + sbb 0x38(%rcx), %r15 + + # [r8-r15] <- (AH+AL)*(BH+BL) - AL*BL - AH*BH + mov 0x40(%rcx), %rax + sub %rax, %r8 + mov 0x48(%rcx), %rax + sbb %rax, %r9 + mov 0x50(%rcx), %rax + sbb %rax, %r10 + mov 0x58(%rcx), %rax + sbb %rax, %r11 + mov 0x60(%rcx), %rax + sbb %rax, %r12 + mov 0x68(%rcx), %rdx + sbb %rdx, %r13 + mov 0x70(%rcx), %rdi + sbb %rdi, %r14 + mov 0x78(%rcx), %rsi + sbb %rsi, %r15 + + # Final result + add 0x20(%rcx), %r8 + mov %r8, 0x20(%rcx) + adc 0x28(%rcx), %r9 + mov %r9, 0x28(%rcx) + adc 0x30(%rcx), %r10 + mov %r10, 0x30(%rcx) + adc 0x38(%rcx), %r11 + mov %r11, 0x38(%rcx) + adc 0x40(%rcx), %r12 + mov %r12, 0x40(%rcx) + adc 0x48(%rcx), %r13 + mov %r13, 0x48(%rcx) + adc 0x50(%rcx), %r14 + mov %r14, 0x50(%rcx) + adc 0x58(%rcx), %r15 + mov %r15, 0x58(%rcx) + adc \$0x0, %rax + mov %rax, 0x60(%rcx) + adc \$0x0, %rdx + mov %rdx, 0x68(%rcx) + adc \$0x0, %rdi + mov %rdi, 0x70(%rcx) + adc \$0x0, %rsi + mov %rsi, 0x78(%rcx) + + add \$80, %rsp # Restoring space in stack + .cfi_adjust_cfa_offset -80 + pop %r15 + .cfi_adjust_cfa_offset -8 + pop %r14 + .cfi_adjust_cfa_offset -8 + pop %r13 + .cfi_adjust_cfa_offset -8 + pop %r12 + .cfi_adjust_cfa_offset -8 + ret + .cfi_endproc + +___ + return $body; +} + +$code.=&mul(); + +# Optimized Montgomery reduction for CPUs with ADOX/ADCX and MULX +# Based on method described in Faz-Hernandez et al. https://eprint.iacr.org/2017/1015 +# Operation: c [rsi] = a [rdi] +# NOTE: a=c is not allowed +sub rdc_mulx { + # a[0-1] x .Lp503p1_nz --> result: r8:r14 + my $mul01=&mul128x320_school(0,"rdi",".Lp503p1_nz(%rip)",map("r$_",(8..14)),"rbx","rcx","r15"); + # a[2-3] x .Lp503p1_nz --> result: r8:r14 + my $mul23=&mul128x320_school(16,"rdi",".Lp503p1_nz(%rip)",map("r$_",(8..14)),"rbx","rcx","r15"); + # a[4-5] x .Lp503p1_nz --> result: r8:r14 + my $mul45=&mul128x320_school(32,"rdi",".Lp503p1_nz(%rip)",map("r$_",(8..14)),"rbx","rcx","r15"); + # a[6-7] x .Lp503p1_nz --> result: r8:r14 + my $mul67=&mul128x320_school(48,"rdi",".Lp503p1_nz(%rip)",map("r$_", (8..14)),"rbx","rcx","r15"); + + my $body=<<___; + .Lrdc_mulx_asm: + .cfi_startproc + # sike_fprdc has already pushed r12--15 and rbx by this point. + .cfi_adjust_cfa_offset 32 + .cfi_offset r12, -16 + .cfi_offset r13, -24 + .cfi_offset r14, -32 + .cfi_offset r15, -40 + .cfi_offset rbx, -48 + .cfi_adjust_cfa_offset 8 + + $mul01 + + xor %r15, %r15 + add 0x18(%rdi), %r8 + adc 0x20(%rdi), %r9 + adc 0x28(%rdi), %r10 + adc 0x30(%rdi), %r11 + adc 0x38(%rdi), %r12 + adc 0x40(%rdi), %r13 + adc 0x48(%rdi), %r14 + adc 0x50(%rdi), %r15 + mov %r8, 0x18(%rdi) + mov %r9, 0x20(%rdi) + mov %r10, 0x28(%rdi) + mov %r11, 0x30(%rdi) + mov %r12, 0x38(%rdi) + mov %r13, 0x40(%rdi) + mov %r14, 0x48(%rdi) + mov %r15, 0x50(%rdi) + mov 0x58(%rdi), %r8 + mov 0x60(%rdi), %r9 + mov 0x68(%rdi), %r10 + mov 0x70(%rdi), %r11 + mov 0x78(%rdi), %r12 + adc \$0x0, %r8 + adc \$0x0, %r9 + adc \$0x0, %r10 + adc \$0x0, %r11 + adc \$0x0, %r12 + mov %r8, 0x58(%rdi) + mov %r9, 0x60(%rdi) + mov %r10, 0x68(%rdi) + mov %r11, 0x70(%rdi) + mov %r12, 0x78(%rdi) + + $mul23 + + xor %r15, %r15 + add 0x28(%rdi), %r8 + adc 0x30(%rdi), %r9 + adc 0x38(%rdi), %r10 + adc 0x40(%rdi), %r11 + adc 0x48(%rdi), %r12 + adc 0x50(%rdi), %r13 + adc 0x58(%rdi), %r14 + adc 0x60(%rdi), %r15 + mov %r8, 0x28(%rdi) + mov %r9, 0x30(%rdi) + mov %r10, 0x38(%rdi) + mov %r11, 0x40(%rdi) + mov %r12, 0x48(%rdi) + mov %r13, 0x50(%rdi) + mov %r14, 0x58(%rdi) + mov %r15, 0x60(%rdi) + mov 0x68(%rdi), %r8 + mov 0x70(%rdi), %r9 + mov 0x78(%rdi), %r10 + adc \$0x0, %r8 + adc \$0x0, %r9 + adc \$0x0, %r10 + mov %r8, 0x68(%rdi) + mov %r9, 0x70(%rdi) + mov %r10, 0x78(%rdi) + + $mul45 + + xor %r15, %r15 + xor %rbx, %rbx + add 0x38(%rdi), %r8 + adc 0x40(%rdi), %r9 + adc 0x48(%rdi), %r10 + adc 0x50(%rdi), %r11 + adc 0x58(%rdi), %r12 + adc 0x60(%rdi), %r13 + adc 0x68(%rdi), %r14 + adc 0x70(%rdi), %r15 + adc 0x78(%rdi), %rbx + mov %r8, 0x38(%rdi) + mov %r9, (%rsi) # Final result c0 + mov %r10, 0x48(%rdi) + mov %r11, 0x50(%rdi) + mov %r12, 0x58(%rdi) + mov %r13, 0x60(%rdi) + mov %r14, 0x68(%rdi) + mov %r15, 0x70(%rdi) + mov %rbx, 0x78(%rdi) + + $mul67 + + add 0x48(%rdi), %r8 + adc 0x50(%rdi), %r9 + adc 0x58(%rdi), %r10 + adc 0x60(%rdi), %r11 + adc 0x68(%rdi), %r12 + adc 0x70(%rdi), %r13 + adc 0x78(%rdi), %r14 + mov %r8, 0x8(%rsi) + mov %r9, 0x10(%rsi) + mov %r10, 0x18(%rsi) + mov %r11, 0x20(%rsi) + mov %r12, 0x28(%rsi) + mov %r13, 0x30(%rsi) + mov %r14, 0x38(%rsi) + + pop %rbx + .cfi_adjust_cfa_offset -8 + .cfi_same_value rbx + pop %r15 + .cfi_adjust_cfa_offset -8 + .cfi_same_value r15 + pop %r14 + .cfi_adjust_cfa_offset -8 + .cfi_same_value r14 + pop %r13 + .cfi_adjust_cfa_offset -8 + .cfi_same_value r13 + pop %r12 + .cfi_adjust_cfa_offset -8 + .cfi_same_value r12 + ret + .cfi_endproc +___ + return $body; +} + +# Montgomery reduction +# Based on comba method +# Operation: c [rsi] = a [rdi] +# NOTE: a=c is not allowed +sub rdc { + my $jump_optim=&alt_impl(".Lrdc_mulx_asm") if ($bmi2_adx); + my $body=&rdc_mulx() if ($bmi2_adx); + + $body.=<<___; + .globl ${PREFIX}_fprdc + .type ${PREFIX}_fprdc,\@function,3 + ${PREFIX}_fprdc: + .cfi_startproc + push %r12 + .cfi_adjust_cfa_offset 8 + .cfi_offset r12, -16 + push %r13 + .cfi_adjust_cfa_offset 8 + .cfi_offset r13, -24 + push %r14 + .cfi_adjust_cfa_offset 8 + .cfi_offset r14, -32 + push %r15 + .cfi_adjust_cfa_offset 8 + .cfi_offset r15, -40 + push %rbx + .cfi_adjust_cfa_offset 8 + .cfi_offset rbx, -48 + + $jump_optim + + # Reduction, generic x86 implementation + lea .Lp503p1(%rip), %rbx + + mov (%rdi), %r11 + mov (%rbx), %rax + mul %r11 + xor %r8, %r8 + add 0x18(%rdi), %rax + mov %rax, 0x18(%rsi) # z3 + adc %rdx, %r8 + + xor %r9, %r9 + mov 0x8(%rbx), %rax + mul %r11 + xor %r10, %r10 + add %rax, %r8 + adc %rdx, %r9 + + mov 0x8(%rdi), %r12 + mov (%rbx), %rax + mul %r12 + add %rax, %r8 + adc %rdx, %r9 + adc \$0, %r10 + add 0x20(%rdi), %r8 + mov %r8, 0x20(%rsi) # z4 + adc \$0, %r9 + adc \$0, %r10 + + xor %r8, %r8 + mov 0x10(%rbx), %rax + mul %r11 + add %rax, %r9 + adc %rdx, %r10 + adc \$0, %r8 + + mov 8(%rbx), %rax + mul %r12 + add %rax, %r9 + adc %rdx, %r10 + adc \$0, %r8 + + mov 0x10(%rdi), %r13 + mov (%rbx), %rax + mul %r13 + add %rax, %r9 + adc %rdx, %r10 + adc \$0, %r8 + add 0x28(%rdi), %r9 + mov %r9, 0x28(%rsi) # z5 + adc \$0, %r10 + adc \$0, %r8 + + xor %r9, %r9 + mov 0x18(%rbx), %rax + mul %r11 + add %rax, %r10 + adc %rdx, %r8 + adc \$0, %r9 + + mov 0x10(%rbx), %rax + mul %r12 + add %rax, %r10 + adc %rdx, %r8 + adc \$0, %r9 + + mov 0x8(%rbx), %rax + mul %r13 + add %rax, %r10 + adc %rdx, %r8 + adc \$0, %r9 + + mov 0x18(%rsi), %r14 + mov (%rbx), %rax + mul %r14 + add %rax, %r10 + adc %rdx, %r8 + adc \$0, %r9 + add 0x30(%rdi), %r10 + mov %r10, 0x30(%rsi) # z6 + adc \$0, %r8 + adc \$0, %r9 + + xor %r10, %r10 + mov 0x20(%rbx), %rax + mul %r11 + add %rax, %r8 + adc %rdx, %r9 + adc \$0, %r10 + + mov 0x18(%rbx), %rax + mul %r12 + add %rax, %r8 + adc %rdx, %r9 + adc \$0, %r10 + + mov 0x10(%rbx), %rax + mul %r13 + add %rax, %r8 + adc %rdx, %r9 + adc \$0, %r10 + + mov 0x8(%rbx), %rax + mul %r14 + add %rax, %r8 + adc %rdx, %r9 + adc \$0, %r10 + + mov 0x20(%rsi), %r15 + mov (%rbx), %rax + mul %r15 + add %rax, %r8 + adc %rdx, %r9 + adc \$0, %r10 + add 0x38(%rdi), %r8 # Z7 + mov %r8, 0x38(%rsi) + adc \$0, %r9 + adc \$0, %r10 + + xor %r8, %r8 + mov 0x20(%rbx), %rax + mul %r12 + add %rax, %r9 + adc %rdx, %r10 + adc \$0, %r8 + + mov 0x18(%rbx), %rax + mul %r13 + add %rax, %r9 + adc %rdx, %r10 + adc \$0, %r8 + + mov 0x10(%rbx), %rax + mul %r14 + add %rax, %r9 + adc %rdx, %r10 + adc \$0, %r8 + + mov 0x8(%rbx), %rax + mul %r15 + add %rax, %r9 + adc %rdx, %r10 + adc \$0, %r8 + + mov 0x28(%rsi), %rcx + mov (%rbx), %rax + mul %rcx + add %rax, %r9 + adc %rdx, %r10 + adc \$0, %r8 + add 0x40(%rdi), %r9 + mov %r9, (%rsi) # Z9 + adc \$0, %r10 + adc \$0, %r8 + + xor %r9, %r9 + mov 0x20(%rbx), %rax + mul %r13 + add %rax, %r10 + adc %rdx, %r8 + adc \$0, %r9 + + mov 0x18(%rbx), %rax + mul %r14 + add %rax, %r10 + adc %rdx, %r8 + adc \$0, %r9 + + mov 0x10(%rbx), %rax + mul %r15 + add %rax, %r10 + adc %rdx, %r8 + adc \$0, %r9 + + mov 8(%rbx), %rax + mul %rcx + add %rax, %r10 + adc %rdx, %r8 + adc \$0, %r9 + + mov 0x30(%rsi), %r13 + mov (%rbx), %rax + mul %r13 + add %rax, %r10 + adc %rdx, %r8 + adc \$0, %r9 + add 0x48(%rdi), %r10 + mov %r10, 0x8(%rsi) # Z1 + adc \$0, %r8 + adc \$0, %r9 + + xor %r10, %r10 + mov 0x20(%rbx), %rax + mul %r14 + add %rax, %r8 + adc %rdx, %r9 + adc \$0, %r10 + + mov 0x18(%rbx), %rax + mul %r15 + add %rax, %r8 + adc %rdx, %r9 + adc \$0, %r10 + + mov 0x10(%rbx), %rax + mul %rcx + add %rax, %r8 + adc %rdx, %r9 + adc \$0, %r10 + + mov 8(%rbx), %rax + mul %r13 + add %rax, %r8 + adc %rdx, %r9 + adc \$0, %r10 + + mov 0x38(%rsi), %r14 + mov (%rbx), %rax + mul %r14 + add %rax, %r8 + adc %rdx, %r9 + adc \$0, %r10 + add 0x50(%rdi), %r8 + mov %r8, 0x10(%rsi) # Z2 + adc \$0, %r9 + adc \$0, %r10 + + xor %r8, %r8 + mov 0x20(%rbx), %rax + mul %r15 + add %rax, %r9 + adc %rdx, %r10 + adc \$0, %r8 + + mov 0x18(%rbx), %rax + mul %rcx + add %rax, %r9 + adc %rdx, %r10 + adc \$0, %r8 + + mov 0x10(%rbx), %rax + mul %r13 + add %rax, %r9 + adc %rdx, %r10 + adc \$0, %r8 + + mov 8(%rbx), %rax + mul %r14 + add %rax, %r9 + adc %rdx, %r10 + adc \$0, %r8 + add 0x58(%rdi), %r9 + mov %r9, 0x18(%rsi) # Z3 + adc \$0, %r10 + adc \$0, %r8 + + xor %r9, %r9 + mov 0x20(%rbx), %rax + mul %rcx + add %rax, %r10 + adc %rdx, %r8 + adc \$0, %r9 + + mov 0x18(%rbx), %rax + mul %r13 + add %rax, %r10 + adc %rdx, %r8 + adc \$0, %r9 + + mov 0x10(%rbx), %rax + mul %r14 + add %rax, %r10 + adc %rdx, %r8 + adc \$0, %r9 + add 0x60(%rdi), %r10 + mov %r10, 0x20(%rsi) # Z4 + adc \$0, %r8 + adc \$0, %r9 + + xor %r10, %r10 + mov 0x20(%rbx), %rax + mul %r13 + add %rax, %r8 + adc %rdx, %r9 + adc \$0, %r10 + + mov 0x18(%rbx), %rax + mul %r14 + add %rax, %r8 + adc %rdx, %r9 + adc \$0, %r10 + add 0x68(%rdi), %r8 # Z5 + mov %r8, 0x28(%rsi) # Z5 + adc \$0, %r9 + adc \$0, %r10 + + mov 0x20(%rbx), %rax + mul %r14 + add %rax, %r9 + adc %rdx, %r10 + add 0x70(%rdi), %r9 # Z6 + mov %r9, 0x30(%rsi) # Z6 + adc \$0, %r10 + add 0x78(%rdi), %r10 # Z7 + mov %r10, 0x38(%rsi) # Z7 + + pop %rbx + .cfi_adjust_cfa_offset -8 + pop %r15 + .cfi_adjust_cfa_offset -8 + pop %r14 + .cfi_adjust_cfa_offset -8 + pop %r13 + .cfi_adjust_cfa_offset -8 + pop %r12 + .cfi_adjust_cfa_offset -8 + ret + .cfi_endproc +___ + return $body; +} + +$code.=&rdc(); + +foreach (split("\n",$code)) { + s/\`([^\`]*)\`/eval($1)/ge; + print $_,"\n"; +} + +close STDOUT; diff --git a/third_party/boringssl/kit/src/third_party/sike/asm/fp_generic.c b/third_party/boringssl/kit/src/third_party/sike/asm/fp_generic.c new file mode 100644 index 00000000..60e0da1f --- /dev/null +++ b/third_party/boringssl/kit/src/third_party/sike/asm/fp_generic.c @@ -0,0 +1,181 @@ +/******************************************************************************************** +* SIDH: an efficient supersingular isogeny cryptography library +* +* Abstract: portable modular arithmetic for P503 +*********************************************************************************************/ + +#include + +#if defined(OPENSSL_NO_ASM) || \ + (!defined(OPENSSL_X86_64) && !defined(OPENSSL_AARCH64)) + +#include "../utils.h" +#include "../fpx.h" + +// Global constants +extern const struct params_t p503; + +static void digit_x_digit(const crypto_word_t a, const crypto_word_t b, crypto_word_t* c) +{ // Digit multiplication, digit * digit -> 2-digit result + crypto_word_t al, ah, bl, bh, temp; + crypto_word_t albl, albh, ahbl, ahbh, res1, res2, res3, carry; + crypto_word_t mask_low = (crypto_word_t)(-1) >> (sizeof(crypto_word_t)*4); + crypto_word_t mask_high = (crypto_word_t)(-1) << (sizeof(crypto_word_t)*4); + + al = a & mask_low; // Low part + ah = a >> (sizeof(crypto_word_t) * 4); // High part + bl = b & mask_low; + bh = b >> (sizeof(crypto_word_t) * 4); + + albl = al*bl; + albh = al*bh; + ahbl = ah*bl; + ahbh = ah*bh; + c[0] = albl & mask_low; // C00 + + res1 = albl >> (sizeof(crypto_word_t) * 4); + res2 = ahbl & mask_low; + res3 = albh & mask_low; + temp = res1 + res2 + res3; + carry = temp >> (sizeof(crypto_word_t) * 4); + c[0] ^= temp << (sizeof(crypto_word_t) * 4); // C01 + + res1 = ahbl >> (sizeof(crypto_word_t) * 4); + res2 = albh >> (sizeof(crypto_word_t) * 4); + res3 = ahbh & mask_low; + temp = res1 + res2 + res3 + carry; + c[1] = temp & mask_low; // C10 + carry = temp & mask_high; + c[1] ^= (ahbh & mask_high) + carry; // C11 +} + +void sike_fpadd(const felm_t a, const felm_t b, felm_t c) +{ // Modular addition, c = a+b mod p503. + // Inputs: a, b in [0, 2*p503-1] + // Output: c in [0, 2*p503-1] + unsigned int i, carry = 0; + crypto_word_t mask; + + for (i = 0; i < NWORDS_FIELD; i++) { + ADDC(carry, a[i], b[i], carry, c[i]); + } + + carry = 0; + for (i = 0; i < NWORDS_FIELD; i++) { + SUBC(carry, c[i], p503.prime_x2[i], carry, c[i]); + } + mask = 0 - (crypto_word_t)carry; + + carry = 0; + for (i = 0; i < NWORDS_FIELD; i++) { + ADDC(carry, c[i], p503.prime_x2[i] & mask, carry, c[i]); + } +} + +void sike_fpsub(const felm_t a, const felm_t b, felm_t c) +{ // Modular subtraction, c = a-b mod p503. + // Inputs: a, b in [0, 2*p503-1] + // Output: c in [0, 2*p503-1] + unsigned int i, borrow = 0; + crypto_word_t mask; + + for (i = 0; i < NWORDS_FIELD; i++) { + SUBC(borrow, a[i], b[i], borrow, c[i]); + } + mask = 0 - (crypto_word_t)borrow; + + borrow = 0; + for (i = 0; i < NWORDS_FIELD; i++) { + ADDC(borrow, c[i], p503.prime_x2[i] & mask, borrow, c[i]); + } +} + +void sike_mpmul(const felm_t a, const felm_t b, dfelm_t c) +{ // Multiprecision comba multiply, c = a*b, where lng(a) = lng(b) = NWORDS_FIELD. + unsigned int i, j; + crypto_word_t t = 0, u = 0, v = 0, UV[2]; + unsigned int carry = 0; + + for (i = 0; i < NWORDS_FIELD; i++) { + for (j = 0; j <= i; j++) { + MUL(a[j], b[i-j], UV+1, UV[0]); + ADDC(0, UV[0], v, carry, v); + ADDC(carry, UV[1], u, carry, u); + t += carry; + } + c[i] = v; + v = u; + u = t; + t = 0; + } + + for (i = NWORDS_FIELD; i < 2*NWORDS_FIELD-1; i++) { + for (j = i-NWORDS_FIELD+1; j < NWORDS_FIELD; j++) { + MUL(a[j], b[i-j], UV+1, UV[0]); + ADDC(0, UV[0], v, carry, v); + ADDC(carry, UV[1], u, carry, u); + t += carry; + } + c[i] = v; + v = u; + u = t; + t = 0; + } + c[2*NWORDS_FIELD-1] = v; +} + +void sike_fprdc(const felm_t ma, felm_t mc) +{ // Efficient Montgomery reduction using comba and exploiting the special form of the prime p503. + // mc = ma*R^-1 mod p503x2, where R = 2^512. + // If ma < 2^512*p503, the output mc is in the range [0, 2*p503-1]. + // ma is assumed to be in Montgomery representation. + unsigned int i, j, carry, count = p503_ZERO_WORDS; + crypto_word_t UV[2], t = 0, u = 0, v = 0; + + for (i = 0; i < NWORDS_FIELD; i++) { + mc[i] = 0; + } + + for (i = 0; i < NWORDS_FIELD; i++) { + for (j = 0; j < i; j++) { + if (j < (i-p503_ZERO_WORDS+1)) { + MUL(mc[j], p503.prime_p1[i-j], UV+1, UV[0]); + ADDC(0, UV[0], v, carry, v); + ADDC(carry, UV[1], u, carry, u); + t += carry; + } + } + ADDC(0, v, ma[i], carry, v); + ADDC(carry, u, 0, carry, u); + t += carry; + mc[i] = v; + v = u; + u = t; + t = 0; + } + + for (i = NWORDS_FIELD; i < 2*NWORDS_FIELD-1; i++) { + if (count > 0) { + count -= 1; + } + for (j = i-NWORDS_FIELD+1; j < NWORDS_FIELD; j++) { + if (j < (NWORDS_FIELD-count)) { + MUL(mc[j], p503.prime_p1[i-j], UV+1, UV[0]); + ADDC(0, UV[0], v, carry, v); + ADDC(carry, UV[1], u, carry, u); + t += carry; + } + } + ADDC(0, v, ma[i], carry, v); + ADDC(carry, u, 0, carry, u); + t += carry; + mc[i-NWORDS_FIELD] = v; + v = u; + u = t; + t = 0; + } + ADDC(0, v, ma[2*NWORDS_FIELD-1], carry, v); + mc[NWORDS_FIELD-1] = v; +} + +#endif // NO_ASM || (!X86_64 && !AARCH64) diff --git a/third_party/boringssl/kit/src/third_party/sike/fpx.c b/third_party/boringssl/kit/src/third_party/sike/fpx.c new file mode 100644 index 00000000..0951418f --- /dev/null +++ b/third_party/boringssl/kit/src/third_party/sike/fpx.c @@ -0,0 +1,305 @@ +/******************************************************************************************** +* SIDH: an efficient supersingular isogeny cryptography library +* +* Abstract: core functions over GF(p) and GF(p^2) +*********************************************************************************************/ +#include + +#include "utils.h" +#include "fpx.h" + +extern const struct params_t p503; + +// Multiprecision squaring, c = a^2 mod p. +static void fpsqr_mont(const felm_t ma, felm_t mc) +{ + dfelm_t temp = {0}; + sike_mpmul(ma, ma, temp); + sike_fprdc(temp, mc); +} + +// Chain to compute a^(p-3)/4 using Montgomery arithmetic. +static void fpinv_chain_mont(felm_t a) +{ + unsigned int i, j; + felm_t t[15], tt; + + // Precomputed table + fpsqr_mont(a, tt); + sike_fpmul_mont(a, tt, t[0]); + for (i = 0; i <= 13; i++) sike_fpmul_mont(t[i], tt, t[i+1]); + + sike_fpcopy(a, tt); + for (i = 0; i < 8; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(a, tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[8], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[6], tt, tt); + for (i = 0; i < 6; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[9], tt, tt); + for (i = 0; i < 7; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[0], tt, tt); + for (i = 0; i < 7; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(a, tt, tt); + for (i = 0; i < 7; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[6], tt, tt); + for (i = 0; i < 7; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[2], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[8], tt, tt); + for (i = 0; i < 7; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(a, tt, tt); + for (i = 0; i < 8; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[10], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[0], tt, tt); + for (i = 0; i < 6; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[10], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[10], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[5], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[2], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[6], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[3], tt, tt); + for (i = 0; i < 6; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[5], tt, tt); + for (i = 0; i < 12; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[12], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[8], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[6], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[12], tt, tt); + for (i = 0; i < 6; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[11], tt, tt); + for (i = 0; i < 8; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[6], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[5], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[14], tt, tt); + for (i = 0; i < 7; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[14], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[5], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[6], tt, tt); + for (i = 0; i < 8; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[8], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(a, tt, tt); + for (i = 0; i < 8; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[4], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[6], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[5], tt, tt); + for (i = 0; i < 8; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[7], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(a, tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[0], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[11], tt, tt); + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[13], tt, tt); + for (i = 0; i < 8; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[1], tt, tt); + for (i = 0; i < 6; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[10], tt, tt); + for (j = 0; j < 49; j++) { + for (i = 0; i < 5; i++) fpsqr_mont(tt, tt); + sike_fpmul_mont(t[14], tt, tt); + } + sike_fpcopy(tt, a); +} + +// Field inversion using Montgomery arithmetic, a = a^(-1)*R mod p. +static void fpinv_mont(felm_t a) +{ + felm_t tt = {0}; + sike_fpcopy(a, tt); + fpinv_chain_mont(tt); + fpsqr_mont(tt, tt); + fpsqr_mont(tt, tt); + sike_fpmul_mont(a, tt, a); +} + +// Multiprecision addition, c = a+b, where lng(a) = lng(b) = nwords. Returns the carry bit. +#if defined(OPENSSL_NO_ASM) || (!defined(OPENSSL_X86_64) && !defined(OPENSSL_AARCH64)) +inline static unsigned int mp_add(const felm_t a, const felm_t b, felm_t c, const unsigned int nwords) { + uint8_t carry = 0; + for (size_t i = 0; i < nwords; i++) { + ADDC(carry, a[i], b[i], carry, c[i]); + } + return carry; +} + +// Multiprecision subtraction, c = a-b, where lng(a) = lng(b) = nwords. Returns the borrow bit. +inline static unsigned int mp_sub(const felm_t a, const felm_t b, felm_t c, const unsigned int nwords) { + uint32_t borrow = 0; + for (size_t i = 0; i < nwords; i++) { + SUBC(borrow, a[i], b[i], borrow, c[i]); + } + return borrow; +} +#endif + +// Multiprecision addition, c = a+b. +inline static void mp_addfast(const felm_t a, const felm_t b, felm_t c) +{ +#if defined(OPENSSL_NO_ASM) || (!defined(OPENSSL_X86_64) && !defined(OPENSSL_AARCH64)) + mp_add(a, b, c, NWORDS_FIELD); +#else + sike_mpadd_asm(a, b, c); +#endif +} + +// Multiprecision subtraction, c = a-b, where lng(a) = lng(b) = 2*NWORDS_FIELD. +// If c < 0 then returns mask = 0xFF..F, else mask = 0x00..0 +inline static crypto_word_t mp_subfast(const dfelm_t a, const dfelm_t b, dfelm_t c) { +#if defined(OPENSSL_NO_ASM) || (!defined(OPENSSL_X86_64) && !defined(OPENSSL_AARCH64)) + return (0 - (crypto_word_t)mp_sub(a, b, c, 2*NWORDS_FIELD)); +#else + return sike_mpsubx2_asm(a, b, c); +#endif +} + +// Multiprecision subtraction, c = c-a-b, where lng(a) = lng(b) = 2*NWORDS_FIELD. +// Inputs should be s.t. c > a and c > b +inline static void mp_dblsubfast(const dfelm_t a, const dfelm_t b, dfelm_t c) { +#if defined(OPENSSL_NO_ASM) || (!defined(OPENSSL_X86_64) && !defined(OPENSSL_AARCH64)) + mp_sub(c, a, c, 2*NWORDS_FIELD); + mp_sub(c, b, c, 2*NWORDS_FIELD); +#else + sike_mpdblsubx2_asm(a, b, c); +#endif +} + +// Copy a field element, c = a. +void sike_fpcopy(const felm_t a, felm_t c) { + for (size_t i = 0; i < NWORDS_FIELD; i++) { + c[i] = a[i]; + } +} + +// Field multiplication using Montgomery arithmetic, c = a*b*R^-1 mod p503, where R=2^768 +void sike_fpmul_mont(const felm_t ma, const felm_t mb, felm_t mc) +{ + dfelm_t temp = {0}; + sike_mpmul(ma, mb, temp); + sike_fprdc(temp, mc); +} + +// Conversion from Montgomery representation to standard representation, +// c = ma*R^(-1) mod p = a mod p, where ma in [0, p-1]. +void sike_from_mont(const felm_t ma, felm_t c) +{ + felm_t one = {0}; + one[0] = 1; + + sike_fpmul_mont(ma, one, c); + sike_fpcorrection(c); +} + +// GF(p^2) squaring using Montgomery arithmetic, c = a^2 in GF(p^2). +// Inputs: a = a0+a1*i, where a0, a1 are in [0, 2*p-1] +// Output: c = c0+c1*i, where c0, c1 are in [0, 2*p-1] +void sike_fp2sqr_mont(const f2elm_t a, f2elm_t c) { + felm_t t1, t2, t3; + + mp_addfast(a->c0, a->c1, t1); // t1 = a0+a1 + sike_fpsub(a->c0, a->c1, t2); // t2 = a0-a1 + mp_addfast(a->c0, a->c0, t3); // t3 = 2a0 + sike_fpmul_mont(t1, t2, c->c0); // c0 = (a0+a1)(a0-a1) + sike_fpmul_mont(t3, a->c1, c->c1); // c1 = 2a0*a1 +} + +// Modular negation, a = -a mod p503. +// Input/output: a in [0, 2*p503-1] +void sike_fpneg(felm_t a) { + uint32_t borrow = 0; + for (size_t i = 0; i < NWORDS_FIELD; i++) { + SUBC(borrow, p503.prime_x2[i], a[i], borrow, a[i]); + } +} + +// Modular division by two, c = a/2 mod p503. +// Input : a in [0, 2*p503-1] +// Output: c in [0, 2*p503-1] +void sike_fpdiv2(const felm_t a, felm_t c) { + uint32_t carry = 0; + crypto_word_t mask; + + mask = 0 - (crypto_word_t)(a[0] & 1); // If a is odd compute a+p503 + for (size_t i = 0; i < NWORDS_FIELD; i++) { + ADDC(carry, a[i], p503.prime[i] & mask, carry, c[i]); + } + + // Multiprecision right shift by one. + for (size_t i = 0; i < NWORDS_FIELD-1; i++) { + c[i] = (c[i] >> 1) ^ (c[i+1] << (RADIX - 1)); + } + c[NWORDS_FIELD-1] >>= 1; +} + +// Modular correction to reduce field element a in [0, 2*p503-1] to [0, p503-1]. +void sike_fpcorrection(felm_t a) { + uint32_t borrow = 0; + crypto_word_t mask; + + for (size_t i = 0; i < NWORDS_FIELD; i++) { + SUBC(borrow, a[i], p503.prime[i], borrow, a[i]); + } + mask = 0 - (crypto_word_t)borrow; + + borrow = 0; + for (size_t i = 0; i < NWORDS_FIELD; i++) { + ADDC(borrow, a[i], p503.prime[i] & mask, borrow, a[i]); + } +} + +// GF(p^2) multiplication using Montgomery arithmetic, c = a*b in GF(p^2). +// Inputs: a = a0+a1*i and b = b0+b1*i, where a0, a1, b0, b1 are in [0, 2*p-1] +// Output: c = c0+c1*i, where c0, c1 are in [0, 2*p-1] +void sike_fp2mul_mont(const f2elm_t a, const f2elm_t b, f2elm_t c) { + felm_t t1, t2; + dfelm_t tt1, tt2, tt3; + crypto_word_t mask; + + mp_addfast(a->c0, a->c1, t1); // t1 = a0+a1 + mp_addfast(b->c0, b->c1, t2); // t2 = b0+b1 + sike_mpmul(a->c0, b->c0, tt1); // tt1 = a0*b0 + sike_mpmul(a->c1, b->c1, tt2); // tt2 = a1*b1 + sike_mpmul(t1, t2, tt3); // tt3 = (a0+a1)*(b0+b1) + mp_dblsubfast(tt1, tt2, tt3); // tt3 = (a0+a1)*(b0+b1) - a0*b0 - a1*b1 + mask = mp_subfast(tt1, tt2, tt1); // tt1 = a0*b0 - a1*b1. If tt1 < 0 then mask = 0xFF..F, else if tt1 >= 0 then mask = 0x00..0 + + for (size_t i = 0; i < NWORDS_FIELD; i++) { + t1[i] = p503.prime[i] & mask; + } + + sike_fprdc(tt3, c->c1); // c[1] = (a0+a1)*(b0+b1) - a0*b0 - a1*b1 + mp_addfast(&tt1[NWORDS_FIELD], t1, &tt1[NWORDS_FIELD]); + sike_fprdc(tt1, c->c0); // c[0] = a0*b0 - a1*b1 +} + +// GF(p^2) inversion using Montgomery arithmetic, a = (a0-i*a1)/(a0^2+a1^2). +void sike_fp2inv_mont(f2elm_t a) { + f2elm_t t1; + + fpsqr_mont(a->c0, t1->c0); // t10 = a0^2 + fpsqr_mont(a->c1, t1->c1); // t11 = a1^2 + sike_fpadd(t1->c0, t1->c1, t1->c0); // t10 = a0^2+a1^2 + fpinv_mont(t1->c0); // t10 = (a0^2+a1^2)^-1 + sike_fpneg(a->c1); // a = a0-i*a1 + sike_fpmul_mont(a->c0, t1->c0, a->c0); + sike_fpmul_mont(a->c1, t1->c0, a->c1); // a = (a0-i*a1)*(a0^2+a1^2)^-1 +} diff --git a/third_party/boringssl/kit/src/third_party/sike/fpx.h b/third_party/boringssl/kit/src/third_party/sike/fpx.h new file mode 100644 index 00000000..e787c28c --- /dev/null +++ b/third_party/boringssl/kit/src/third_party/sike/fpx.h @@ -0,0 +1,112 @@ +#ifndef FPX_H_ +#define FPX_H_ + +#include "utils.h" + +#if defined(__cplusplus) +extern "C" { +#endif + +// Modular addition, c = a+b mod p503. +void sike_fpadd(const felm_t a, const felm_t b, felm_t c); +// Modular subtraction, c = a-b mod p503. +void sike_fpsub(const felm_t a, const felm_t b, felm_t c); +// Modular division by two, c = a/2 mod p503. +void sike_fpdiv2(const felm_t a, felm_t c); +// Modular correction to reduce field element a in [0, 2*p503-1] to [0, p503-1]. +void sike_fpcorrection(felm_t a); +// Multiprecision multiply, c = a*b, where lng(a) = lng(b) = nwords. +void sike_mpmul(const felm_t a, const felm_t b, dfelm_t c); +// 503-bit Montgomery reduction, c = a mod p +void sike_fprdc(const dfelm_t a, felm_t c); +// Double 2x503-bit multiprecision subtraction, c = c-a-b +void sike_mpdblsubx2_asm(const felm_t a, const felm_t b, felm_t c); +// Multiprecision subtraction, c = a-b +crypto_word_t sike_mpsubx2_asm(const dfelm_t a, const dfelm_t b, dfelm_t c); +// 503-bit multiprecision addition, c = a+b +void sike_mpadd_asm(const felm_t a, const felm_t b, felm_t c); +// Modular negation, a = -a mod p503. +void sike_fpneg(felm_t a); +// Copy of a field element, c = a +void sike_fpcopy(const felm_t a, felm_t c); +// Copy a field element, c = a. +void sike_fpzero(felm_t a); +// If option = 0xFF...FF x=y; y=x, otherwise swap doesn't happen. Constant time. +void sike_cswap_asm(point_proj_t x, point_proj_t y, const crypto_word_t option); +// Conversion from Montgomery representation to standard representation, +// c = ma*R^(-1) mod p = a mod p, where ma in [0, p-1]. +void sike_from_mont(const felm_t ma, felm_t c); +// Field multiplication using Montgomery arithmetic, c = a*b*R^-1 mod p503, where R=2^768 +void sike_fpmul_mont(const felm_t ma, const felm_t mb, felm_t mc); +// GF(p503^2) multiplication using Montgomery arithmetic, c = a*b in GF(p503^2) +void sike_fp2mul_mont(const f2elm_t a, const f2elm_t b, f2elm_t c); +// GF(p503^2) inversion using Montgomery arithmetic, a = (a0-i*a1)/(a0^2+a1^2) +void sike_fp2inv_mont(f2elm_t a); +// GF(p^2) squaring using Montgomery arithmetic, c = a^2 in GF(p^2). +void sike_fp2sqr_mont(const f2elm_t a, f2elm_t c); +// Modular correction, a = a in GF(p^2). +void sike_fp2correction(f2elm_t a); + +#if defined(__cplusplus) +} // extern C +#endif + +// GF(p^2) addition, c = a+b in GF(p^2). +#define sike_fp2add(a, b, c) \ +do { \ + sike_fpadd(a->c0, b->c0, c->c0); \ + sike_fpadd(a->c1, b->c1, c->c1); \ +} while(0) + +// GF(p^2) subtraction, c = a-b in GF(p^2). +#define sike_fp2sub(a,b,c) \ +do { \ + sike_fpsub(a->c0, b->c0, c->c0); \ + sike_fpsub(a->c1, b->c1, c->c1); \ +} while(0) + +// Copy a GF(p^2) element, c = a. +#define sike_fp2copy(a, c) \ +do { \ + sike_fpcopy(a->c0, c->c0); \ + sike_fpcopy(a->c1, c->c1); \ +} while(0) + +// GF(p^2) negation, a = -a in GF(p^2). +#define sike_fp2neg(a) \ +do { \ + sike_fpneg(a->c0); \ + sike_fpneg(a->c1); \ +} while(0) + +// GF(p^2) division by two, c = a/2 in GF(p^2). +#define sike_fp2div2(a, c) \ +do { \ + sike_fpdiv2(a->c0, c->c0); \ + sike_fpdiv2(a->c1, c->c1); \ +} while(0) + +// Modular correction, a = a in GF(p^2). +#define sike_fp2correction(a) \ +do { \ + sike_fpcorrection(a->c0); \ + sike_fpcorrection(a->c1); \ +} while(0) + +// Conversion of a GF(p^2) element to Montgomery representation, +// mc_i = a_i*R^2*R^(-1) = a_i*R in GF(p^2). +#define sike_to_fp2mont(a, mc) \ +do { \ + sike_fpmul_mont(a->c0, p503.mont_R2, mc->c0); \ + sike_fpmul_mont(a->c1, p503.mont_R2, mc->c1); \ +} while(0) + +// Conversion of a GF(p^2) element from Montgomery representation to standard representation, +// c_i = ma_i*R^(-1) = a_i in GF(p^2). +#define sike_from_fp2mont(ma, c) \ +do { \ + sike_from_mont(ma->c0, c->c0); \ + sike_from_mont(ma->c1, c->c1); \ +} while(0) + +#endif // FPX_H_ diff --git a/third_party/boringssl/kit/src/third_party/sike/isogeny.c b/third_party/boringssl/kit/src/third_party/sike/isogeny.c new file mode 100644 index 00000000..b8807f30 --- /dev/null +++ b/third_party/boringssl/kit/src/third_party/sike/isogeny.c @@ -0,0 +1,260 @@ +/******************************************************************************************** +* SIDH: an efficient supersingular isogeny cryptography library +* +* Abstract: elliptic curve and isogeny functions +*********************************************************************************************/ +#include "utils.h" +#include "isogeny.h" +#include "fpx.h" + +static void xDBL(const point_proj_t P, point_proj_t Q, const f2elm_t A24plus, const f2elm_t C24) +{ // Doubling of a Montgomery point in projective coordinates (X:Z). + // Input: projective Montgomery x-coordinates P = (X1:Z1), where x1=X1/Z1 and Montgomery curve constants A+2C and 4C. + // Output: projective Montgomery x-coordinates Q = 2*P = (X2:Z2). + f2elm_t t0, t1; + + sike_fp2sub(P->X, P->Z, t0); // t0 = X1-Z1 + sike_fp2add(P->X, P->Z, t1); // t1 = X1+Z1 + sike_fp2sqr_mont(t0, t0); // t0 = (X1-Z1)^2 + sike_fp2sqr_mont(t1, t1); // t1 = (X1+Z1)^2 + sike_fp2mul_mont(C24, t0, Q->Z); // Z2 = C24*(X1-Z1)^2 + sike_fp2mul_mont(t1, Q->Z, Q->X); // X2 = C24*(X1-Z1)^2*(X1+Z1)^2 + sike_fp2sub(t1, t0, t1); // t1 = (X1+Z1)^2-(X1-Z1)^2 + sike_fp2mul_mont(A24plus, t1, t0); // t0 = A24plus*[(X1+Z1)^2-(X1-Z1)^2] + sike_fp2add(Q->Z, t0, Q->Z); // Z2 = A24plus*[(X1+Z1)^2-(X1-Z1)^2] + C24*(X1-Z1)^2 + sike_fp2mul_mont(Q->Z, t1, Q->Z); // Z2 = [A24plus*[(X1+Z1)^2-(X1-Z1)^2] + C24*(X1-Z1)^2]*[(X1+Z1)^2-(X1-Z1)^2] +} + +void xDBLe(const point_proj_t P, point_proj_t Q, const f2elm_t A24plus, const f2elm_t C24, size_t e) +{ // Computes [2^e](X:Z) on Montgomery curve with projective constant via e repeated doublings. + // Input: projective Montgomery x-coordinates P = (XP:ZP), such that xP=XP/ZP and Montgomery curve constants A+2C and 4C. + // Output: projective Montgomery x-coordinates Q <- (2^e)*P. + + memmove(Q, P, sizeof(*P)); + for (size_t i = 0; i < e; i++) { + xDBL(Q, Q, A24plus, C24); + } +} + +void get_4_isog(const point_proj_t P, f2elm_t A24plus, f2elm_t C24, f2elm_t* coeff) +{ // Computes the corresponding 4-isogeny of a projective Montgomery point (X4:Z4) of order 4. + // Input: projective point of order four P = (X4:Z4). + // Output: the 4-isogenous Montgomery curve with projective coefficients A+2C/4C and the 3 coefficients + // that are used to evaluate the isogeny at a point in eval_4_isog(). + + sike_fp2sub(P->X, P->Z, coeff[1]); // coeff[1] = X4-Z4 + sike_fp2add(P->X, P->Z, coeff[2]); // coeff[2] = X4+Z4 + sike_fp2sqr_mont(P->Z, coeff[0]); // coeff[0] = Z4^2 + sike_fp2add(coeff[0], coeff[0], coeff[0]); // coeff[0] = 2*Z4^2 + sike_fp2sqr_mont(coeff[0], C24); // C24 = 4*Z4^4 + sike_fp2add(coeff[0], coeff[0], coeff[0]); // coeff[0] = 4*Z4^2 + sike_fp2sqr_mont(P->X, A24plus); // A24plus = X4^2 + sike_fp2add(A24plus, A24plus, A24plus); // A24plus = 2*X4^2 + sike_fp2sqr_mont(A24plus, A24plus); // A24plus = 4*X4^4 +} + +void eval_4_isog(point_proj_t P, f2elm_t* coeff) +{ // Evaluates the isogeny at the point (X:Z) in the domain of the isogeny, given a 4-isogeny phi defined + // by the 3 coefficients in coeff (computed in the function get_4_isog()). + // Inputs: the coefficients defining the isogeny, and the projective point P = (X:Z). + // Output: the projective point P = phi(P) = (X:Z) in the codomain. + f2elm_t t0, t1; + + sike_fp2add(P->X, P->Z, t0); // t0 = X+Z + sike_fp2sub(P->X, P->Z, t1); // t1 = X-Z + sike_fp2mul_mont(t0, coeff[1], P->X); // X = (X+Z)*coeff[1] + sike_fp2mul_mont(t1, coeff[2], P->Z); // Z = (X-Z)*coeff[2] + sike_fp2mul_mont(t0, t1, t0); // t0 = (X+Z)*(X-Z) + sike_fp2mul_mont(t0, coeff[0], t0); // t0 = coeff[0]*(X+Z)*(X-Z) + sike_fp2add(P->X, P->Z, t1); // t1 = (X-Z)*coeff[2] + (X+Z)*coeff[1] + sike_fp2sub(P->X, P->Z, P->Z); // Z = (X-Z)*coeff[2] - (X+Z)*coeff[1] + sike_fp2sqr_mont(t1, t1); // t1 = [(X-Z)*coeff[2] + (X+Z)*coeff[1]]^2 + sike_fp2sqr_mont(P->Z, P->Z); // Z = [(X-Z)*coeff[2] - (X+Z)*coeff[1]]^2 + sike_fp2add(t1, t0, P->X); // X = coeff[0]*(X+Z)*(X-Z) + [(X-Z)*coeff[2] + (X+Z)*coeff[1]]^2 + sike_fp2sub(P->Z, t0, t0); // t0 = [(X-Z)*coeff[2] - (X+Z)*coeff[1]]^2 - coeff[0]*(X+Z)*(X-Z) + sike_fp2mul_mont(P->X, t1, P->X); // Xfinal + sike_fp2mul_mont(P->Z, t0, P->Z); // Zfinal +} + + +void xTPL(const point_proj_t P, point_proj_t Q, const f2elm_t A24minus, const f2elm_t A24plus) +{ // Tripling of a Montgomery point in projective coordinates (X:Z). + // Input: projective Montgomery x-coordinates P = (X:Z), where x=X/Z and Montgomery curve constants A24plus = A+2C and A24minus = A-2C. + // Output: projective Montgomery x-coordinates Q = 3*P = (X3:Z3). + f2elm_t t0, t1, t2, t3, t4, t5, t6; + + sike_fp2sub(P->X, P->Z, t0); // t0 = X-Z + sike_fp2sqr_mont(t0, t2); // t2 = (X-Z)^2 + sike_fp2add(P->X, P->Z, t1); // t1 = X+Z + sike_fp2sqr_mont(t1, t3); // t3 = (X+Z)^2 + sike_fp2add(t0, t1, t4); // t4 = 2*X + sike_fp2sub(t1, t0, t0); // t0 = 2*Z + sike_fp2sqr_mont(t4, t1); // t1 = 4*X^2 + sike_fp2sub(t1, t3, t1); // t1 = 4*X^2 - (X+Z)^2 + sike_fp2sub(t1, t2, t1); // t1 = 4*X^2 - (X+Z)^2 - (X-Z)^2 + sike_fp2mul_mont(t3, A24plus, t5); // t5 = A24plus*(X+Z)^2 + sike_fp2mul_mont(t3, t5, t3); // t3 = A24plus*(X+Z)^3 + sike_fp2mul_mont(A24minus, t2, t6); // t6 = A24minus*(X-Z)^2 + sike_fp2mul_mont(t2, t6, t2); // t2 = A24minus*(X-Z)^3 + sike_fp2sub(t2, t3, t3); // t3 = A24minus*(X-Z)^3 - coeff*(X+Z)^3 + sike_fp2sub(t5, t6, t2); // t2 = A24plus*(X+Z)^2 - A24minus*(X-Z)^2 + sike_fp2mul_mont(t1, t2, t1); // t1 = [4*X^2 - (X+Z)^2 - (X-Z)^2]*[A24plus*(X+Z)^2 - A24minus*(X-Z)^2] + sike_fp2add(t3, t1, t2); // t2 = [4*X^2 - (X+Z)^2 - (X-Z)^2]*[A24plus*(X+Z)^2 - A24minus*(X-Z)^2] + A24minus*(X-Z)^3 - coeff*(X+Z)^3 + sike_fp2sqr_mont(t2, t2); // t2 = t2^2 + sike_fp2mul_mont(t4, t2, Q->X); // X3 = 2*X*t2 + sike_fp2sub(t3, t1, t1); // t1 = A24minus*(X-Z)^3 - A24plus*(X+Z)^3 - [4*X^2 - (X+Z)^2 - (X-Z)^2]*[A24plus*(X+Z)^2 - A24minus*(X-Z)^2] + sike_fp2sqr_mont(t1, t1); // t1 = t1^2 + sike_fp2mul_mont(t0, t1, Q->Z); // Z3 = 2*Z*t1 +} + +void xTPLe(const point_proj_t P, point_proj_t Q, const f2elm_t A24minus, const f2elm_t A24plus, size_t e) +{ // Computes [3^e](X:Z) on Montgomery curve with projective constant via e repeated triplings. + // Input: projective Montgomery x-coordinates P = (XP:ZP), such that xP=XP/ZP and Montgomery curve constants A24plus = A+2C and A24minus = A-2C. + // Output: projective Montgomery x-coordinates Q <- (3^e)*P. + memmove(Q, P, sizeof(*P)); + for (size_t i = 0; i < e; i++) { + xTPL(Q, Q, A24minus, A24plus); + } +} + +void get_3_isog(const point_proj_t P, f2elm_t A24minus, f2elm_t A24plus, f2elm_t* coeff) +{ // Computes the corresponding 3-isogeny of a projective Montgomery point (X3:Z3) of order 3. + // Input: projective point of order three P = (X3:Z3). + // Output: the 3-isogenous Montgomery curve with projective coefficient A/C. + f2elm_t t0, t1, t2, t3, t4; + + sike_fp2sub(P->X, P->Z, coeff[0]); // coeff0 = X-Z + sike_fp2sqr_mont(coeff[0], t0); // t0 = (X-Z)^2 + sike_fp2add(P->X, P->Z, coeff[1]); // coeff1 = X+Z + sike_fp2sqr_mont(coeff[1], t1); // t1 = (X+Z)^2 + sike_fp2add(t0, t1, t2); // t2 = (X+Z)^2 + (X-Z)^2 + sike_fp2add(coeff[0], coeff[1], t3); // t3 = 2*X + sike_fp2sqr_mont(t3, t3); // t3 = 4*X^2 + sike_fp2sub(t3, t2, t3); // t3 = 4*X^2 - (X+Z)^2 - (X-Z)^2 + sike_fp2add(t1, t3, t2); // t2 = 4*X^2 - (X-Z)^2 + sike_fp2add(t3, t0, t3); // t3 = 4*X^2 - (X+Z)^2 + sike_fp2add(t0, t3, t4); // t4 = 4*X^2 - (X+Z)^2 + (X-Z)^2 + sike_fp2add(t4, t4, t4); // t4 = 2(4*X^2 - (X+Z)^2 + (X-Z)^2) + sike_fp2add(t1, t4, t4); // t4 = 8*X^2 - (X+Z)^2 + 2*(X-Z)^2 + sike_fp2mul_mont(t2, t4, A24minus); // A24minus = [4*X^2 - (X-Z)^2]*[8*X^2 - (X+Z)^2 + 2*(X-Z)^2] + sike_fp2add(t1, t2, t4); // t4 = 4*X^2 + (X+Z)^2 - (X-Z)^2 + sike_fp2add(t4, t4, t4); // t4 = 2(4*X^2 + (X+Z)^2 - (X-Z)^2) + sike_fp2add(t0, t4, t4); // t4 = 8*X^2 + 2*(X+Z)^2 - (X-Z)^2 + sike_fp2mul_mont(t3, t4, t4); // t4 = [4*X^2 - (X+Z)^2]*[8*X^2 + 2*(X+Z)^2 - (X-Z)^2] + sike_fp2sub(t4, A24minus, t0); // t0 = [4*X^2 - (X+Z)^2]*[8*X^2 + 2*(X+Z)^2 - (X-Z)^2] - [4*X^2 - (X-Z)^2]*[8*X^2 - (X+Z)^2 + 2*(X-Z)^2] + sike_fp2add(A24minus, t0, A24plus); // A24plus = 8*X^2 - (X+Z)^2 + 2*(X-Z)^2 +} + + +void eval_3_isog(point_proj_t Q, f2elm_t* coeff) +{ // Computes the 3-isogeny R=phi(X:Z), given projective point (X3:Z3) of order 3 on a Montgomery curve and + // a point P with 2 coefficients in coeff (computed in the function get_3_isog()). + // Inputs: projective points P = (X3:Z3) and Q = (X:Z). + // Output: the projective point Q <- phi(Q) = (X3:Z3). + f2elm_t t0, t1, t2; + + sike_fp2add(Q->X, Q->Z, t0); // t0 = X+Z + sike_fp2sub(Q->X, Q->Z, t1); // t1 = X-Z + sike_fp2mul_mont(t0, coeff[0], t0); // t0 = coeff0*(X+Z) + sike_fp2mul_mont(t1, coeff[1], t1); // t1 = coeff1*(X-Z) + sike_fp2add(t0, t1, t2); // t2 = coeff0*(X+Z) + coeff1*(X-Z) + sike_fp2sub(t1, t0, t0); // t0 = coeff1*(X-Z) - coeff0*(X+Z) + sike_fp2sqr_mont(t2, t2); // t2 = [coeff0*(X+Z) + coeff1*(X-Z)]^2 + sike_fp2sqr_mont(t0, t0); // t0 = [coeff1*(X-Z) - coeff0*(X+Z)]^2 + sike_fp2mul_mont(Q->X, t2, Q->X); // X3final = X*[coeff0*(X+Z) + coeff1*(X-Z)]^2 + sike_fp2mul_mont(Q->Z, t0, Q->Z); // Z3final = Z*[coeff1*(X-Z) - coeff0*(X+Z)]^2 +} + + +void inv_3_way(f2elm_t z1, f2elm_t z2, f2elm_t z3) +{ // 3-way simultaneous inversion + // Input: z1,z2,z3 + // Output: 1/z1,1/z2,1/z3 (override inputs). + f2elm_t t0, t1, t2, t3; + + sike_fp2mul_mont(z1, z2, t0); // t0 = z1*z2 + sike_fp2mul_mont(z3, t0, t1); // t1 = z1*z2*z3 + sike_fp2inv_mont(t1); // t1 = 1/(z1*z2*z3) + sike_fp2mul_mont(z3, t1, t2); // t2 = 1/(z1*z2) + sike_fp2mul_mont(t2, z2, t3); // t3 = 1/z1 + sike_fp2mul_mont(t2, z1, z2); // z2 = 1/z2 + sike_fp2mul_mont(t0, t1, z3); // z3 = 1/z3 + sike_fp2copy(t3, z1); // z1 = 1/z1 +} + + +void get_A(const f2elm_t xP, const f2elm_t xQ, const f2elm_t xR, f2elm_t A) +{ // Given the x-coordinates of P, Q, and R, returns the value A corresponding to the Montgomery curve E_A: y^2=x^3+A*x^2+x such that R=Q-P on E_A. + // Input: the x-coordinates xP, xQ, and xR of the points P, Q and R. + // Output: the coefficient A corresponding to the curve E_A: y^2=x^3+A*x^2+x. + f2elm_t t0, t1, one = F2ELM_INIT; + + extern const struct params_t p503; + sike_fpcopy(p503.mont_one, one->c0); + sike_fp2add(xP, xQ, t1); // t1 = xP+xQ + sike_fp2mul_mont(xP, xQ, t0); // t0 = xP*xQ + sike_fp2mul_mont(xR, t1, A); // A = xR*t1 + sike_fp2add(t0, A, A); // A = A+t0 + sike_fp2mul_mont(t0, xR, t0); // t0 = t0*xR + sike_fp2sub(A, one, A); // A = A-1 + sike_fp2add(t0, t0, t0); // t0 = t0+t0 + sike_fp2add(t1, xR, t1); // t1 = t1+xR + sike_fp2add(t0, t0, t0); // t0 = t0+t0 + sike_fp2sqr_mont(A, A); // A = A^2 + sike_fp2inv_mont(t0); // t0 = 1/t0 + sike_fp2mul_mont(A, t0, A); // A = A*t0 + sike_fp2sub(A, t1, A); // Afinal = A-t1 +} + + +void j_inv(const f2elm_t A, const f2elm_t C, f2elm_t jinv) +{ // Computes the j-invariant of a Montgomery curve with projective constant. + // Input: A,C in GF(p^2). + // Output: j=256*(A^2-3*C^2)^3/(C^4*(A^2-4*C^2)), which is the j-invariant of the Montgomery curve B*y^2=x^3+(A/C)*x^2+x or (equivalently) j-invariant of B'*y^2=C*x^3+A*x^2+C*x. + f2elm_t t0, t1; + + sike_fp2sqr_mont(A, jinv); // jinv = A^2 + sike_fp2sqr_mont(C, t1); // t1 = C^2 + sike_fp2add(t1, t1, t0); // t0 = t1+t1 + sike_fp2sub(jinv, t0, t0); // t0 = jinv-t0 + sike_fp2sub(t0, t1, t0); // t0 = t0-t1 + sike_fp2sub(t0, t1, jinv); // jinv = t0-t1 + sike_fp2sqr_mont(t1, t1); // t1 = t1^2 + sike_fp2mul_mont(jinv, t1, jinv); // jinv = jinv*t1 + sike_fp2add(t0, t0, t0); // t0 = t0+t0 + sike_fp2add(t0, t0, t0); // t0 = t0+t0 + sike_fp2sqr_mont(t0, t1); // t1 = t0^2 + sike_fp2mul_mont(t0, t1, t0); // t0 = t0*t1 + sike_fp2add(t0, t0, t0); // t0 = t0+t0 + sike_fp2add(t0, t0, t0); // t0 = t0+t0 + sike_fp2inv_mont(jinv); // jinv = 1/jinv + sike_fp2mul_mont(jinv, t0, jinv); // jinv = t0*jinv +} + + +void xDBLADD(point_proj_t P, point_proj_t Q, const f2elm_t xPQ, const f2elm_t A24) +{ // Simultaneous doubling and differential addition. + // Input: projective Montgomery points P=(XP:ZP) and Q=(XQ:ZQ) such that xP=XP/ZP and xQ=XQ/ZQ, affine difference xPQ=x(P-Q) and Montgomery curve constant A24=(A+2)/4. + // Output: projective Montgomery points P <- 2*P = (X2P:Z2P) such that x(2P)=X2P/Z2P, and Q <- P+Q = (XQP:ZQP) such that = x(Q+P)=XQP/ZQP. + f2elm_t t0, t1, t2; + + sike_fp2add(P->X, P->Z, t0); // t0 = XP+ZP + sike_fp2sub(P->X, P->Z, t1); // t1 = XP-ZP + sike_fp2sqr_mont(t0, P->X); // XP = (XP+ZP)^2 + sike_fp2sub(Q->X, Q->Z, t2); // t2 = XQ-ZQ + sike_fp2correction(t2); + sike_fp2add(Q->X, Q->Z, Q->X); // XQ = XQ+ZQ + sike_fp2mul_mont(t0, t2, t0); // t0 = (XP+ZP)*(XQ-ZQ) + sike_fp2sqr_mont(t1, P->Z); // ZP = (XP-ZP)^2 + sike_fp2mul_mont(t1, Q->X, t1); // t1 = (XP-ZP)*(XQ+ZQ) + sike_fp2sub(P->X, P->Z, t2); // t2 = (XP+ZP)^2-(XP-ZP)^2 + sike_fp2mul_mont(P->X, P->Z, P->X); // XP = (XP+ZP)^2*(XP-ZP)^2 + sike_fp2mul_mont(t2, A24, Q->X); // XQ = A24*[(XP+ZP)^2-(XP-ZP)^2] + sike_fp2sub(t0, t1, Q->Z); // ZQ = (XP+ZP)*(XQ-ZQ)-(XP-ZP)*(XQ+ZQ) + sike_fp2add(Q->X, P->Z, P->Z); // ZP = A24*[(XP+ZP)^2-(XP-ZP)^2]+(XP-ZP)^2 + sike_fp2add(t0, t1, Q->X); // XQ = (XP+ZP)*(XQ-ZQ)+(XP-ZP)*(XQ+ZQ) + sike_fp2mul_mont(P->Z, t2, P->Z); // ZP = [A24*[(XP+ZP)^2-(XP-ZP)^2]+(XP-ZP)^2]*[(XP+ZP)^2-(XP-ZP)^2] + sike_fp2sqr_mont(Q->Z, Q->Z); // ZQ = [(XP+ZP)*(XQ-ZQ)-(XP-ZP)*(XQ+ZQ)]^2 + sike_fp2sqr_mont(Q->X, Q->X); // XQ = [(XP+ZP)*(XQ-ZQ)+(XP-ZP)*(XQ+ZQ)]^2 + sike_fp2mul_mont(Q->Z, xPQ, Q->Z); // ZQ = xPQ*[(XP+ZP)*(XQ-ZQ)-(XP-ZP)*(XQ+ZQ)]^2 +} diff --git a/third_party/boringssl/kit/src/third_party/sike/isogeny.h b/third_party/boringssl/kit/src/third_party/sike/isogeny.h new file mode 100644 index 00000000..460c8c66 --- /dev/null +++ b/third_party/boringssl/kit/src/third_party/sike/isogeny.h @@ -0,0 +1,49 @@ +#ifndef ISOGENY_H_ +#define ISOGENY_H_ + +// Computes [2^e](X:Z) on Montgomery curve with projective +// constant via e repeated doublings. +void xDBLe( + const point_proj_t P, point_proj_t Q, const f2elm_t A24plus, + const f2elm_t C24, size_t e); +// Simultaneous doubling and differential addition. +void xDBLADD( + point_proj_t P, point_proj_t Q, const f2elm_t xPQ, + const f2elm_t A24); +// Tripling of a Montgomery point in projective coordinates (X:Z). +void xTPL( + const point_proj_t P, point_proj_t Q, const f2elm_t A24minus, + const f2elm_t A24plus); +// Computes [3^e](X:Z) on Montgomery curve with projective constant +// via e repeated triplings. +void xTPLe( + const point_proj_t P, point_proj_t Q, const f2elm_t A24minus, + const f2elm_t A24plus, size_t e); +// Given the x-coordinates of P, Q, and R, returns the value A +// corresponding to the Montgomery curve E_A: y^2=x^3+A*x^2+x such that R=Q-P on E_A. +void get_A( + const f2elm_t xP, const f2elm_t xQ, const f2elm_t xR, f2elm_t A); +// Computes the j-invariant of a Montgomery curve with projective constant. +void j_inv( + const f2elm_t A, const f2elm_t C, f2elm_t jinv); +// Computes the corresponding 4-isogeny of a projective Montgomery +// point (X4:Z4) of order 4. +void get_4_isog( + const point_proj_t P, f2elm_t A24plus, f2elm_t C24, f2elm_t* coeff); +// Computes the corresponding 3-isogeny of a projective Montgomery +// point (X3:Z3) of order 3. +void get_3_isog( + const point_proj_t P, f2elm_t A24minus, f2elm_t A24plus, + f2elm_t* coeff); +// Computes the 3-isogeny R=phi(X:Z), given projective point (X3:Z3) +// of order 3 on a Montgomery curve and a point P with coefficients given in coeff. +void eval_3_isog( + point_proj_t Q, f2elm_t* coeff); +// Evaluates the isogeny at the point (X:Z) in the domain of the isogeny. +void eval_4_isog( + point_proj_t P, f2elm_t* coeff); +// 3-way simultaneous inversion +void inv_3_way( + f2elm_t z1, f2elm_t z2, f2elm_t z3); + +#endif // ISOGENY_H_ diff --git a/third_party/boringssl/kit/src/third_party/sike/sike.c b/third_party/boringssl/kit/src/third_party/sike/sike.c new file mode 100644 index 00000000..689baa89 --- /dev/null +++ b/third_party/boringssl/kit/src/third_party/sike/sike.c @@ -0,0 +1,571 @@ +/******************************************************************************************** +* SIDH: an efficient supersingular isogeny cryptography library +* +* Abstract: supersingular isogeny key encapsulation (SIKE) protocol +*********************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "utils.h" +#include "isogeny.h" +#include "fpx.h" + +extern const struct params_t p503; + +// Domain separation parameters for HMAC +static const uint8_t G[2] = {0,0}; +static const uint8_t H[2] = {1,0}; +static const uint8_t F[2] = {2,0}; + +// SIDHp503_JINV_BYTESZ is a number of bytes used for encoding j-invariant. +#define SIDHp503_JINV_BYTESZ 126U +// SIDHp503_PRV_A_BITSZ is a number of bits of SIDH private key (2-isogeny) +#define SIDHp503_PRV_A_BITSZ 250U +// SIDHp503_PRV_A_BITSZ is a number of bits of SIDH private key (3-isogeny) +#define SIDHp503_PRV_B_BITSZ 253U +// MAX_INT_POINTS_ALICE is a number of points used in 2-isogeny tree computation +#define MAX_INT_POINTS_ALICE 7U +// MAX_INT_POINTS_ALICE is a number of points used in 3-isogeny tree computation +#define MAX_INT_POINTS_BOB 8U + +// Produces HMAC-SHA256 of data |S| mac'ed with the key |key|. Result is stored in |out| +// which must have size of at least |outsz| bytes and must be not bigger than +// SHA256_DIGEST_LENGTH. The output of a HMAC may be truncated. +// The |key| buffer is reused by the hmac_sum and hence, it's size must be equal +// to SHA256_CBLOCK. The HMAC key provided in |key| buffer must be smaller or equal +// to SHA256_DIGHEST_LENTH. |key| can overlap |out|. +static void hmac_sum( + uint8_t *out, size_t outsz, const uint8_t S[2], uint8_t key[SHA256_CBLOCK]) { + for(size_t i=0; iX->c0[i] ^ Q->X->c0[i]); + P->X->c0[i] = temp ^ P->X->c0[i]; + Q->X->c0[i] = temp ^ Q->X->c0[i]; + temp = option & (P->Z->c0[i] ^ Q->Z->c0[i]); + P->Z->c0[i] = temp ^ P->Z->c0[i]; + Q->Z->c0[i] = temp ^ Q->Z->c0[i]; + temp = option & (P->X->c1[i] ^ Q->X->c1[i]); + P->X->c1[i] = temp ^ P->X->c1[i]; + Q->X->c1[i] = temp ^ Q->X->c1[i]; + temp = option & (P->Z->c1[i] ^ Q->Z->c1[i]); + P->Z->c1[i] = temp ^ P->Z->c1[i]; + Q->Z->c1[i] = temp ^ Q->Z->c1[i]; + } +} +#endif + +// Swap points. +// If option = 0 then P <- P and Q <- Q, else if option = 0xFF...FF then P <- Q and Q <- P +static inline void sike_fp2cswap(point_proj_t P, point_proj_t Q, const crypto_word_t option) +{ +#if defined(OPENSSL_X86_64) && !defined(OPENSSL_NO_ASM) + sike_cswap_asm(P, Q, option); +#else + sike_cswap(P, Q, option); +#endif +} + +static void LADDER3PT( + const f2elm_t xP, const f2elm_t xQ, const f2elm_t xPQ, const uint8_t* m, + int is_A, point_proj_t R, const f2elm_t A) { + point_proj_t R0 = POINT_PROJ_INIT, R2 = POINT_PROJ_INIT; + f2elm_t A24 = F2ELM_INIT; + crypto_word_t mask; + int bit, swap, prevbit = 0; + + const size_t nbits = is_A?SIDHp503_PRV_A_BITSZ:SIDHp503_PRV_B_BITSZ; + + // Initializing constant + sike_fpcopy(p503.mont_one, A24[0].c0); + sike_fp2add(A24, A24, A24); + sike_fp2add(A, A24, A24); + sike_fp2div2(A24, A24); + sike_fp2div2(A24, A24); // A24 = (A+2)/4 + + // Initializing points + sike_fp2copy(xQ, R0->X); + sike_fpcopy(p503.mont_one, R0->Z[0].c0); + sike_fp2copy(xPQ, R2->X); + sike_fpcopy(p503.mont_one, R2->Z[0].c0); + sike_fp2copy(xP, R->X); + sike_fpcopy(p503.mont_one, R->Z[0].c0); + memset(R->Z->c1, 0, sizeof(R->Z->c1)); + + // Main loop + for (size_t i = 0; i < nbits; i++) { + bit = (m[i >> 3] >> (i & 7)) & 1; + swap = bit ^ prevbit; + prevbit = bit; + mask = 0 - (crypto_word_t)swap; + + sike_fp2cswap(R, R2, mask); + xDBLADD(R0, R2, R->X, A24); + sike_fp2mul_mont(R2->X, R->Z, R2->X); + } +} + +// Initialization of basis points +static inline void sike_init_basis(const crypto_word_t *gen, f2elm_t XP, f2elm_t XQ, f2elm_t XR) { + sike_fpcopy(gen, XP->c0); + sike_fpcopy(gen + NWORDS_FIELD, XP->c1); + sike_fpcopy(gen + 2*NWORDS_FIELD, XQ->c0); + memset(XQ->c1, 0, sizeof(XQ->c1)); + sike_fpcopy(gen + 3*NWORDS_FIELD, XR->c0); + sike_fpcopy(gen + 4*NWORDS_FIELD, XR->c1); +} + +// Conversion of GF(p^2) element from Montgomery to standard representation. +static inline void sike_fp2_encode(const f2elm_t x, uint8_t *enc) { + f2elm_t t; + sike_from_fp2mont(x, t); + + // convert to bytes in little endian form + for (size_t i=0; i> (8*(i%LSZ))) & 0xFF; + enc[i+FIELD_BYTESZ] = (t[0].c1[i/LSZ] >> (8*(i%LSZ))) & 0xFF; + } +} + +// Parse byte sequence back into GF(p^2) element, and conversion to Montgomery representation. +// Elements over GF(p503) are encoded in 63 octets in little endian format +// (i.e., the least significant octet is located in the lowest memory address). +static inline void fp2_decode(const uint8_t *enc, f2elm_t t) { + memset(t[0].c0, 0, sizeof(t[0].c0)); + memset(t[0].c1, 0, sizeof(t[0].c1)); + // convert bytes in little endian form to f2elm_t + for (size_t i = 0; i < FIELD_BYTESZ; i++) { + t[0].c0[i/LSZ] |= ((crypto_word_t)enc[i+ 0]) << (8*(i%LSZ)); + t[0].c1[i/LSZ] |= ((crypto_word_t)enc[i+FIELD_BYTESZ]) << (8*(i%LSZ)); + } + sike_to_fp2mont(t, t); +} + +// Alice's ephemeral public key generation +// Input: a private key prA in the range [0, 2^250 - 1], stored in 32 bytes. +// Output: the public key pkA consisting of 3 GF(p503^2) elements encoded in 378 bytes. +static void gen_iso_A(const uint8_t* skA, uint8_t* pkA) +{ + point_proj_t R, pts[MAX_INT_POINTS_ALICE]; + point_proj_t phiP = POINT_PROJ_INIT; + point_proj_t phiQ = POINT_PROJ_INIT; + point_proj_t phiR = POINT_PROJ_INIT; + f2elm_t XPA, XQA, XRA, coeff[3]; + f2elm_t A24plus = F2ELM_INIT; + f2elm_t C24 = F2ELM_INIT; + f2elm_t A = F2ELM_INIT; + unsigned int m, index = 0, pts_index[MAX_INT_POINTS_ALICE], npts = 0, ii = 0; + + // Initialize basis points + sike_init_basis(p503.A_gen, XPA, XQA, XRA); + sike_init_basis(p503.B_gen, phiP->X, phiQ->X, phiR->X); + sike_fpcopy(p503.mont_one, (phiP->Z)->c0); + sike_fpcopy(p503.mont_one, (phiQ->Z)->c0); + sike_fpcopy(p503.mont_one, (phiR->Z)->c0); + + // Initialize constants + sike_fpcopy(p503.mont_one, A24plus->c0); + sike_fp2add(A24plus, A24plus, C24); + + // Retrieve kernel point + LADDER3PT(XPA, XQA, XRA, skA, 1, R, A); + + // Traverse tree + index = 0; + for (size_t row = 1; row < A_max; row++) { + while (index < A_max-row) { + sike_fp2copy(R->X, pts[npts]->X); + sike_fp2copy(R->Z, pts[npts]->Z); + pts_index[npts++] = index; + m = p503.A_strat[ii++]; + xDBLe(R, R, A24plus, C24, (2*m)); + index += m; + } + get_4_isog(R, A24plus, C24, coeff); + + for (size_t i = 0; i < npts; i++) { + eval_4_isog(pts[i], coeff); + } + eval_4_isog(phiP, coeff); + eval_4_isog(phiQ, coeff); + eval_4_isog(phiR, coeff); + + sike_fp2copy(pts[npts-1]->X, R->X); + sike_fp2copy(pts[npts-1]->Z, R->Z); + index = pts_index[npts-1]; + npts -= 1; + } + + get_4_isog(R, A24plus, C24, coeff); + eval_4_isog(phiP, coeff); + eval_4_isog(phiQ, coeff); + eval_4_isog(phiR, coeff); + + inv_3_way(phiP->Z, phiQ->Z, phiR->Z); + sike_fp2mul_mont(phiP->X, phiP->Z, phiP->X); + sike_fp2mul_mont(phiQ->X, phiQ->Z, phiQ->X); + sike_fp2mul_mont(phiR->X, phiR->Z, phiR->X); + + // Format public key + sike_fp2_encode(phiP->X, pkA); + sike_fp2_encode(phiQ->X, pkA + SIDHp503_JINV_BYTESZ); + sike_fp2_encode(phiR->X, pkA + 2*SIDHp503_JINV_BYTESZ); +} + +// Bob's ephemeral key-pair generation +// It produces a private key skB and computes the public key pkB. +// The private key is an integer in the range [0, 2^Floor(Log(2,3^159)) - 1], stored in 32 bytes. +// The public key consists of 3 GF(p503^2) elements encoded in 378 bytes. +static void gen_iso_B(const uint8_t* skB, uint8_t* pkB) +{ + point_proj_t R, pts[MAX_INT_POINTS_BOB]; + point_proj_t phiP = POINT_PROJ_INIT; + point_proj_t phiQ = POINT_PROJ_INIT; + point_proj_t phiR = POINT_PROJ_INIT; + f2elm_t XPB, XQB, XRB, coeff[3]; + f2elm_t A24plus = F2ELM_INIT; + f2elm_t A24minus = F2ELM_INIT; + f2elm_t A = F2ELM_INIT; + unsigned int m, index = 0, pts_index[MAX_INT_POINTS_BOB], npts = 0, ii = 0; + + // Initialize basis points + sike_init_basis(p503.B_gen, XPB, XQB, XRB); + sike_init_basis(p503.A_gen, phiP->X, phiQ->X, phiR->X); + sike_fpcopy(p503.mont_one, (phiP->Z)->c0); + sike_fpcopy(p503.mont_one, (phiQ->Z)->c0); + sike_fpcopy(p503.mont_one, (phiR->Z)->c0); + + // Initialize constants + sike_fpcopy(p503.mont_one, A24plus->c0); + sike_fp2add(A24plus, A24plus, A24plus); + sike_fp2copy(A24plus, A24minus); + sike_fp2neg(A24minus); + + // Retrieve kernel point + LADDER3PT(XPB, XQB, XRB, skB, 0, R, A); + + // Traverse tree + index = 0; + for (size_t row = 1; row < B_max; row++) { + while (index < B_max-row) { + sike_fp2copy(R->X, pts[npts]->X); + sike_fp2copy(R->Z, pts[npts]->Z); + pts_index[npts++] = index; + m = p503.B_strat[ii++]; + xTPLe(R, R, A24minus, A24plus, m); + index += m; + } + get_3_isog(R, A24minus, A24plus, coeff); + + for (size_t i = 0; i < npts; i++) { + eval_3_isog(pts[i], coeff); + } + eval_3_isog(phiP, coeff); + eval_3_isog(phiQ, coeff); + eval_3_isog(phiR, coeff); + + sike_fp2copy(pts[npts-1]->X, R->X); + sike_fp2copy(pts[npts-1]->Z, R->Z); + index = pts_index[npts-1]; + npts -= 1; + } + + get_3_isog(R, A24minus, A24plus, coeff); + eval_3_isog(phiP, coeff); + eval_3_isog(phiQ, coeff); + eval_3_isog(phiR, coeff); + + inv_3_way(phiP->Z, phiQ->Z, phiR->Z); + sike_fp2mul_mont(phiP->X, phiP->Z, phiP->X); + sike_fp2mul_mont(phiQ->X, phiQ->Z, phiQ->X); + sike_fp2mul_mont(phiR->X, phiR->Z, phiR->X); + + // Format public key + sike_fp2_encode(phiP->X, pkB); + sike_fp2_encode(phiQ->X, pkB + SIDHp503_JINV_BYTESZ); + sike_fp2_encode(phiR->X, pkB + 2*SIDHp503_JINV_BYTESZ); +} + +// Alice's ephemeral shared secret computation +// It produces a shared secret key ssA using her secret key skA and Bob's public key pkB +// Inputs: Alice's skA is an integer in the range [0, 2^250 - 1], stored in 32 bytes. +// Bob's pkB consists of 3 GF(p503^2) elements encoded in 378 bytes. +// Output: a shared secret ssA that consists of one element in GF(p503^2) encoded in 126 bytes. +static void ex_iso_A(const uint8_t* skA, const uint8_t* pkB, uint8_t* ssA) +{ + point_proj_t R, pts[MAX_INT_POINTS_ALICE]; + f2elm_t coeff[3], PKB[3], jinv; + f2elm_t A24plus = F2ELM_INIT; + f2elm_t C24 = F2ELM_INIT; + f2elm_t A = F2ELM_INIT; + unsigned int m, index = 0, pts_index[MAX_INT_POINTS_ALICE], npts = 0, ii = 0; + + // Initialize images of Bob's basis + fp2_decode(pkB, PKB[0]); + fp2_decode(pkB + SIDHp503_JINV_BYTESZ, PKB[1]); + fp2_decode(pkB + 2*SIDHp503_JINV_BYTESZ, PKB[2]); + + // Initialize constants + get_A(PKB[0], PKB[1], PKB[2], A); // TODO: Can return projective A? + sike_fpadd(p503.mont_one, p503.mont_one, C24->c0); + sike_fp2add(A, C24, A24plus); + sike_fpadd(C24->c0, C24->c0, C24->c0); + + // Retrieve kernel point + LADDER3PT(PKB[0], PKB[1], PKB[2], skA, 1, R, A); + + // Traverse tree + index = 0; + for (size_t row = 1; row < A_max; row++) { + while (index < A_max-row) { + sike_fp2copy(R->X, pts[npts]->X); + sike_fp2copy(R->Z, pts[npts]->Z); + pts_index[npts++] = index; + m = p503.A_strat[ii++]; + xDBLe(R, R, A24plus, C24, (2*m)); + index += m; + } + get_4_isog(R, A24plus, C24, coeff); + + for (size_t i = 0; i < npts; i++) { + eval_4_isog(pts[i], coeff); + } + + sike_fp2copy(pts[npts-1]->X, R->X); + sike_fp2copy(pts[npts-1]->Z, R->Z); + index = pts_index[npts-1]; + npts -= 1; + } + + get_4_isog(R, A24plus, C24, coeff); + sike_fp2div2(C24, C24); + sike_fp2sub(A24plus, C24, A24plus); + sike_fp2div2(C24, C24); + j_inv(A24plus, C24, jinv); + sike_fp2_encode(jinv, ssA); +} + +// Bob's ephemeral shared secret computation +// It produces a shared secret key ssB using his secret key skB and Alice's public key pkA +// Inputs: Bob's skB is an integer in the range [0, 2^Floor(Log(2,3^159)) - 1], stored in 32 bytes. +// Alice's pkA consists of 3 GF(p503^2) elements encoded in 378 bytes. +// Output: a shared secret ssB that consists of one element in GF(p503^2) encoded in 126 bytes. +static void ex_iso_B(const uint8_t* skB, const uint8_t* pkA, uint8_t* ssB) +{ + point_proj_t R, pts[MAX_INT_POINTS_BOB]; + f2elm_t coeff[3], PKB[3], jinv; + f2elm_t A24plus = F2ELM_INIT; + f2elm_t A24minus = F2ELM_INIT; + f2elm_t A = F2ELM_INIT; + unsigned int m, index = 0, pts_index[MAX_INT_POINTS_BOB], npts = 0, ii = 0; + + // Initialize images of Alice's basis + fp2_decode(pkA, PKB[0]); + fp2_decode(pkA + SIDHp503_JINV_BYTESZ, PKB[1]); + fp2_decode(pkA + 2*SIDHp503_JINV_BYTESZ, PKB[2]); + + // Initialize constants + get_A(PKB[0], PKB[1], PKB[2], A); + sike_fpadd(p503.mont_one, p503.mont_one, A24minus->c0); + sike_fp2add(A, A24minus, A24plus); + sike_fp2sub(A, A24minus, A24minus); + + // Retrieve kernel point + LADDER3PT(PKB[0], PKB[1], PKB[2], skB, 0, R, A); + + // Traverse tree + index = 0; + for (size_t row = 1; row < B_max; row++) { + while (index < B_max-row) { + sike_fp2copy(R->X, pts[npts]->X); + sike_fp2copy(R->Z, pts[npts]->Z); + pts_index[npts++] = index; + m = p503.B_strat[ii++]; + xTPLe(R, R, A24minus, A24plus, m); + index += m; + } + get_3_isog(R, A24minus, A24plus, coeff); + + for (size_t i = 0; i < npts; i++) { + eval_3_isog(pts[i], coeff); + } + + sike_fp2copy(pts[npts-1]->X, R->X); + sike_fp2copy(pts[npts-1]->Z, R->Z); + index = pts_index[npts-1]; + npts -= 1; + } + + get_3_isog(R, A24minus, A24plus, coeff); + sike_fp2add(A24plus, A24minus, A); + sike_fp2add(A, A, A); + sike_fp2sub(A24plus, A24minus, A24plus); + j_inv(A, A24plus, jinv); + sike_fp2_encode(jinv, ssB); +} + +int SIKE_keypair(uint8_t out_priv[SIKEp503_PRV_BYTESZ], + uint8_t out_pub[SIKEp503_PUB_BYTESZ]) { + int ret = 0; + + // Calculate private key for Alice. Needs to be in range [0, 2^0xFA - 1] and < + // 253 bits + BIGNUM *bn_sidh_prv = BN_new(); + if (!bn_sidh_prv || + !BN_rand(bn_sidh_prv, SIDHp503_PRV_B_BITSZ, BN_RAND_TOP_ONE, + BN_RAND_BOTTOM_ANY) || + !BN_bn2le_padded(out_priv, BITS_TO_BYTES(SIDHp503_PRV_B_BITSZ), + bn_sidh_prv)) { + goto end; + } + + gen_iso_B(out_priv, out_pub); + ret = 1; + +end: + BN_free(bn_sidh_prv); + return ret; +} + +void SIKE_encaps(uint8_t out_shared_key[SIKEp503_SS_BYTESZ], + uint8_t out_ciphertext[SIKEp503_CT_BYTESZ], + const uint8_t pub_key[SIKEp503_PUB_BYTESZ]) { + // Secret buffer is reused by the function to store some ephemeral + // secret data. It's size must be maximum of SHA256_CBLOCK, + // SIKEp503_MSG_BYTESZ and SIDHp503_PRV_A_BITSZ in bytes. + uint8_t secret[SHA256_CBLOCK]; + uint8_t j[SIDHp503_JINV_BYTESZ]; + uint8_t temp[SIKEp503_MSG_BYTESZ + SIKEp503_CT_BYTESZ]; + SHA256_CTX ctx; + + // Generate secret key for A + // secret key A = HMAC({0,1}^n || pub_key), G) mod SIDHp503_PRV_A_BITSZ + RAND_bytes(temp, SIKEp503_MSG_BYTESZ); + + SHA256_Init(&ctx); + SHA256_Update(&ctx, temp, SIKEp503_MSG_BYTESZ); + SHA256_Update(&ctx, pub_key, SIKEp503_PUB_BYTESZ); + SHA256_Final(secret, &ctx); + hmac_sum(secret, BITS_TO_BYTES(SIDHp503_PRV_A_BITSZ), G, secret); + secret[BITS_TO_BYTES(SIDHp503_PRV_A_BITSZ) - 1] &= + (1 << (SIDHp503_PRV_A_BITSZ % 8)) - 1; + + // Generate public key for A - first part of the ciphertext + gen_iso_A(secret, out_ciphertext); + + // Generate c1: + // h = HMAC(j-invariant(secret key A, public key B), F) + // c1 = h ^ m + ex_iso_A(secret, pub_key, j); + SHA256_Init(&ctx); + SHA256_Update(&ctx, j, sizeof(j)); + SHA256_Final(secret, &ctx); + hmac_sum(secret, SIKEp503_MSG_BYTESZ, F, secret); + + // c1 = h ^ m + uint8_t *c1 = &out_ciphertext[SIKEp503_PUB_BYTESZ]; + for (size_t i = 0; i < SIKEp503_MSG_BYTESZ; i++) { + c1[i] = temp[i] ^ secret[i]; + } + + SHA256_Init(&ctx); + SHA256_Update(&ctx, temp, SIKEp503_MSG_BYTESZ); + SHA256_Update(&ctx, out_ciphertext, SIKEp503_CT_BYTESZ); + SHA256_Final(secret, &ctx); + // Generate shared secret out_shared_key = HMAC(m||out_ciphertext, F) + hmac_sum(out_shared_key, SIKEp503_SS_BYTESZ, H, secret); +} + +void SIKE_decaps(uint8_t out_shared_key[SIKEp503_SS_BYTESZ], + const uint8_t ciphertext[SIKEp503_CT_BYTESZ], + const uint8_t pub_key[SIKEp503_PUB_BYTESZ], + const uint8_t priv_key[SIKEp503_PRV_BYTESZ]) { + // Secret buffer is reused by the function to store some ephemeral + // secret data. It's size must be maximum of SHA256_CBLOCK, + // SIKEp503_MSG_BYTESZ and SIDHp503_PRV_A_BITSZ in bytes. + uint8_t secret[SHA256_CBLOCK]; + uint8_t j[SIDHp503_JINV_BYTESZ]; + uint8_t c0[SIKEp503_PUB_BYTESZ]; + uint8_t temp[SIKEp503_MSG_BYTESZ]; + uint8_t shared_nok[SIKEp503_MSG_BYTESZ]; + SHA256_CTX ctx; + + RAND_bytes(shared_nok, SIKEp503_MSG_BYTESZ); + + // Recover m + // Let ciphertext = c0 || c1 - both have fixed sizes + // m = F(j-invariant(c0, priv_key)) ^ c1 + ex_iso_B(priv_key, ciphertext, j); + + SHA256_Init(&ctx); + SHA256_Update(&ctx, j, sizeof(j)); + SHA256_Final(secret, &ctx); + hmac_sum(secret, SIKEp503_MSG_BYTESZ, F, secret); + + const uint8_t *c1 = &ciphertext[sizeof(c0)]; + for (size_t i = 0; i < SIKEp503_MSG_BYTESZ; i++) { + temp[i] = c1[i] ^ secret[i]; + } + + SHA256_Init(&ctx); + SHA256_Update(&ctx, temp, SIKEp503_MSG_BYTESZ); + SHA256_Update(&ctx, pub_key, SIKEp503_PUB_BYTESZ); + SHA256_Final(secret, &ctx); + hmac_sum(secret, BITS_TO_BYTES(SIDHp503_PRV_A_BITSZ), G, secret); + + // Recover secret key A = G(m||pub_key) mod + secret[BITS_TO_BYTES(SIDHp503_PRV_A_BITSZ) - 1] &= + (1 << (SIDHp503_PRV_A_BITSZ % 8)) - 1; + + // Recover c0 = public key A + gen_iso_A(secret, c0); + crypto_word_t ok = constant_time_is_zero_w( + CRYPTO_memcmp(c0, ciphertext, SIKEp503_PUB_BYTESZ)); + for (size_t i = 0; i < SIKEp503_MSG_BYTESZ; i++) { + temp[i] = constant_time_select_8(ok, temp[i], shared_nok[i]); + } + + SHA256_Init(&ctx); + SHA256_Update(&ctx, temp, SIKEp503_MSG_BYTESZ); + SHA256_Update(&ctx, ciphertext, SIKEp503_CT_BYTESZ); + SHA256_Final(secret, &ctx); + hmac_sum(out_shared_key, SIKEp503_SS_BYTESZ, H, secret); +} diff --git a/third_party/boringssl/kit/src/third_party/sike/sike.h b/third_party/boringssl/kit/src/third_party/sike/sike.h new file mode 100644 index 00000000..09093cd1 --- /dev/null +++ b/third_party/boringssl/kit/src/third_party/sike/sike.h @@ -0,0 +1,64 @@ +/******************************************************************************************** +* SIDH: an efficient supersingular isogeny cryptography library +* +* Abstract: API header file for SIKE +*********************************************************************************************/ + +#ifndef SIKE_H_ +#define SIKE_H_ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* SIKEp503 + * + * SIKE is a isogeny based post-quantum key encapsulation mechanism. Description of the + * algorithm is provided in [SIKE]. This implementation uses 503-bit field size. The code + * is based on "Additional_Implementations" from PQC NIST submission package which can + * be found here: + * https://csrc.nist.gov/CSRC/media/Projects/Post-Quantum-Cryptography/documents/round-1/submissions/SIKE.zip + * + * [SIKE] https://sike.org/files/SIDH-spec.pdf + */ + +// SIKEp503_PUB_BYTESZ is the number of bytes in a public key. +#define SIKEp503_PUB_BYTESZ 378 +// SIKEp503_PRV_BYTESZ is the number of bytes in a private key. +#define SIKEp503_PRV_BYTESZ 32 +// SIKEp503_SS_BYTESZ is the number of bytes in a shared key. +#define SIKEp503_SS_BYTESZ 16 +// SIKEp503_MSG_BYTESZ is the number of bytes in a random bit string concatenated +// with the public key (see 1.4 of SIKE). +#define SIKEp503_MSG_BYTESZ 24 +// SIKEp503_SS_BYTESZ is the number of bytes in a ciphertext. +#define SIKEp503_CT_BYTESZ (SIKEp503_PUB_BYTESZ + SIKEp503_MSG_BYTESZ) + +// SIKE_keypair outputs a public and secret key. Internally it uses BN_rand() as +// an entropy source. In case of success function returns 1, otherwise 0. +OPENSSL_EXPORT int SIKE_keypair( + uint8_t out_priv[SIKEp503_PRV_BYTESZ], + uint8_t out_pub[SIKEp503_PUB_BYTESZ]); + +// SIKE_encaps generates and encrypts a random session key, writing those values to +// |out_shared_key| and |out_ciphertext|, respectively. +OPENSSL_EXPORT void SIKE_encaps( + uint8_t out_shared_key[SIKEp503_SS_BYTESZ], + uint8_t out_ciphertext[SIKEp503_CT_BYTESZ], + const uint8_t pub_key[SIKEp503_PUB_BYTESZ]); + +// SIKE_decaps outputs a random session key, writing it to |out_shared_key|. +OPENSSL_EXPORT void SIKE_decaps( + uint8_t out_shared_key[SIKEp503_SS_BYTESZ], + const uint8_t ciphertext[SIKEp503_CT_BYTESZ], + const uint8_t pub_key[SIKEp503_PUB_BYTESZ], + const uint8_t priv_key[SIKEp503_PRV_BYTESZ]); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/third_party/boringssl/kit/src/third_party/sike/sike_test.cc b/third_party/boringssl/kit/src/third_party/sike/sike_test.cc new file mode 100644 index 00000000..1277e09a --- /dev/null +++ b/third_party/boringssl/kit/src/third_party/sike/sike_test.cc @@ -0,0 +1,222 @@ +/* Copyright (c) 2018, Google Inc. + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ + +#include + +#include + +#include "../../crypto/test/abi_test.h" +#include "sike.h" +#include "fpx.h" + +TEST(SIKE, RoundTrip) { + uint8_t sk[SIKEp503_PRV_BYTESZ] = {0}; + uint8_t pk[SIKEp503_PUB_BYTESZ] = {0}; + uint8_t ct[SIKEp503_CT_BYTESZ] = {0}; + uint8_t ss_enc[SIKEp503_SS_BYTESZ] = {0}; + uint8_t ss_dec[SIKEp503_SS_BYTESZ] = {0}; + + EXPECT_EQ(SIKE_keypair(sk, pk), 1); + SIKE_encaps(ss_enc, ct, pk); + SIKE_decaps(ss_dec, ct, pk, sk); + + EXPECT_EQ(memcmp(ss_enc, ss_dec, SIKEp503_SS_BYTESZ), 0); +} + +TEST(SIKE, Decapsulation) { + const uint8_t sk[SIKEp503_PRV_BYTESZ] = { + 0xDB, 0xAF, 0x2C, 0x89, 0xCA, 0x5A, 0xD4, 0x9D, 0x4F, 0x13, + 0x40, 0xDF, 0x2D, 0xB1, 0x5F, 0x4C, 0x91, 0xA7, 0x1F, 0x0B, + 0x29, 0x15, 0x01, 0x59, 0xBC, 0x5F, 0x0B, 0x4A, 0x03, 0x27, + 0x6F, 0x18}; + + const uint8_t pk[SIKEp503_PUB_BYTESZ] = { + 0x07, 0xAA, 0x51, 0x45, 0x3E, 0x1F, 0x53, 0x2A, 0x0A, 0x05, + 0x46, 0xF6, 0x54, 0x7F, 0x5D, 0x56, 0xD6, 0x76, 0xD3, 0xEA, + 0x4B, 0x6B, 0x01, 0x9B, 0x11, 0x72, 0x6F, 0x75, 0xEA, 0x34, + 0x3C, 0x28, 0x2C, 0x36, 0xFD, 0x77, 0xDA, 0xBE, 0xB6, 0x20, + 0x18, 0xC1, 0x93, 0x98, 0x18, 0x86, 0x30, 0x2F, 0x2E, 0xD2, + 0x00, 0x61, 0xFF, 0xAE, 0x78, 0xAE, 0xFB, 0x6F, 0x32, 0xAC, + 0x06, 0xBF, 0x35, 0xF6, 0xF7, 0x5B, 0x98, 0x26, 0x95, 0xC2, + 0xD8, 0xD6, 0x1C, 0x0E, 0x47, 0xDA, 0x76, 0xCE, 0xB5, 0xF1, + 0x19, 0xCC, 0x01, 0xE1, 0x17, 0xA9, 0x62, 0xF7, 0x82, 0x6C, + 0x25, 0x51, 0x25, 0xAE, 0xFE, 0xE3, 0xE2, 0xE1, 0x35, 0xAE, + 0x2E, 0x8F, 0x38, 0xE0, 0x7C, 0x74, 0x3C, 0x1D, 0x39, 0x91, + 0x1B, 0xC7, 0x9F, 0x8E, 0x33, 0x4E, 0x84, 0x19, 0xB8, 0xD9, + 0xC2, 0x71, 0x35, 0x02, 0x47, 0x3E, 0x79, 0xEF, 0x47, 0xE1, + 0xD8, 0x21, 0x96, 0x1F, 0x11, 0x59, 0x39, 0x34, 0x76, 0xEF, + 0x3E, 0xB7, 0x4E, 0xFB, 0x7C, 0x55, 0xA1, 0x85, 0xAA, 0xAB, + 0xAD, 0xF0, 0x09, 0xCB, 0xD1, 0xE3, 0x7C, 0x4F, 0x5D, 0x2D, + 0xE1, 0x13, 0xF0, 0x71, 0xD9, 0xE5, 0xF6, 0xAF, 0x7F, 0xC1, + 0x27, 0x95, 0x8D, 0x52, 0xD5, 0x96, 0x42, 0x38, 0x41, 0xF7, + 0x24, 0x3F, 0x3A, 0xB5, 0x7E, 0x11, 0xE4, 0xF9, 0x33, 0xEE, + 0x4D, 0xBE, 0x74, 0x48, 0xF9, 0x98, 0x04, 0x01, 0x16, 0xEB, + 0xA9, 0x0D, 0x61, 0xC6, 0xFD, 0x4C, 0xCF, 0x98, 0x84, 0x4A, + 0x94, 0xAC, 0x69, 0x2C, 0x02, 0x8B, 0xE3, 0xD1, 0x41, 0x0D, + 0xF2, 0x2D, 0x46, 0x1F, 0x57, 0x1C, 0x77, 0x86, 0x18, 0xE3, + 0x63, 0xDE, 0xF3, 0xE3, 0x02, 0x30, 0x54, 0x73, 0xAE, 0xC2, + 0x32, 0xA2, 0xCE, 0xEB, 0xCF, 0x81, 0x46, 0x54, 0x5C, 0xF4, + 0x5D, 0x2A, 0x03, 0x5D, 0x9C, 0xAE, 0xE0, 0x60, 0x03, 0x80, + 0x11, 0x30, 0xA5, 0xAA, 0xD1, 0x75, 0x67, 0xE0, 0x1C, 0x2B, + 0x6B, 0x5D, 0x83, 0xDE, 0x92, 0x9B, 0x0E, 0xD7, 0x11, 0x0F, + 0x00, 0xC4, 0x59, 0xE4, 0x81, 0x04, 0x3B, 0xEE, 0x5C, 0x04, + 0xD1, 0x0E, 0xD0, 0x67, 0xF5, 0xCC, 0xAA, 0x72, 0x73, 0xEA, + 0xC4, 0x76, 0x99, 0x3B, 0x4C, 0x90, 0x2F, 0xCB, 0xD8, 0x0A, + 0x5B, 0xEC, 0x0E, 0x0E, 0x1F, 0x59, 0xEA, 0x14, 0x8D, 0x34, + 0x53, 0x65, 0x4C, 0x1A, 0x59, 0xA8, 0x95, 0x66, 0x60, 0xBB, + 0xC4, 0xCC, 0x32, 0xA9, 0x8D, 0x2A, 0xAA, 0x14, 0x6F, 0x0F, + 0x81, 0x4D, 0x32, 0x02, 0xFD, 0x33, 0x58, 0x42, 0xCF, 0xF3, + 0x67, 0xD0, 0x9F, 0x0B, 0xB1, 0xCC, 0x18, 0xA5, 0xC4, 0x19, + 0xB6, 0x00, 0xED, 0xFA, 0x32, 0x1A, 0x5F, 0x67, 0xC8, 0xC3, + 0xEB, 0x0D, 0xB5, 0x9A, 0x36, 0x47, 0x82, 0x00}; + + const uint8_t ct_exp[SIKEp503_CT_BYTESZ] = { + 0xE6, 0xB7, 0xE5, 0x7B, 0xA9, 0x19, 0xD1, 0x2C, 0xB8, 0x5C, + 0x7B, 0x66, 0x74, 0xB0, 0x71, 0xA1, 0xFF, 0x71, 0x7F, 0x4B, + 0xB5, 0xA6, 0xAF, 0x48, 0x32, 0x52, 0xD5, 0x82, 0xEE, 0x8A, + 0xBB, 0x08, 0x1E, 0xF6, 0xAC, 0x91, 0xA2, 0xCB, 0x6B, 0x6A, + 0x09, 0x2B, 0xD9, 0xC6, 0x27, 0xD6, 0x3A, 0x6B, 0x8D, 0xFC, + 0xB8, 0x90, 0x8F, 0x72, 0xB3, 0xFA, 0x7D, 0x34, 0x7A, 0xC4, + 0x7E, 0xE3, 0x30, 0xC5, 0xA0, 0xFE, 0x3D, 0x43, 0x14, 0x4E, + 0x3A, 0x14, 0x76, 0x3E, 0xFB, 0xDF, 0xE3, 0xA8, 0xE3, 0x5E, + 0x38, 0xF2, 0xE0, 0x39, 0x67, 0x60, 0xFD, 0xFB, 0xB4, 0x19, + 0xCD, 0xE1, 0x93, 0xA2, 0x06, 0xCC, 0x65, 0xCD, 0x6E, 0xC8, + 0xB4, 0x5E, 0x41, 0x4B, 0x6C, 0xA5, 0xF4, 0xE4, 0x9D, 0x52, + 0x8C, 0x25, 0x60, 0xDD, 0x3D, 0xA9, 0x7F, 0xF2, 0x88, 0xC1, + 0x0C, 0xEE, 0x97, 0xE0, 0xE7, 0x3B, 0xB7, 0xD3, 0x6F, 0x28, + 0x79, 0x2F, 0x50, 0xB2, 0x4F, 0x74, 0x3A, 0x0C, 0x88, 0x27, + 0x98, 0x3A, 0x27, 0xD3, 0x26, 0x83, 0x59, 0x49, 0x81, 0x5B, + 0x0D, 0xA7, 0x0C, 0x4F, 0xEF, 0xFB, 0x1E, 0xAF, 0xE9, 0xD2, + 0x1C, 0x10, 0x25, 0xEC, 0x9E, 0xFA, 0x57, 0x36, 0xAA, 0x3F, + 0xC1, 0xA3, 0x2C, 0xE9, 0xB5, 0xC9, 0xED, 0x72, 0x51, 0x4C, + 0x02, 0xB4, 0x7B, 0xB3, 0xED, 0x9F, 0x45, 0x03, 0x34, 0xAC, + 0x9A, 0x9E, 0x62, 0x5F, 0x82, 0x7A, 0x77, 0x34, 0xF9, 0x21, + 0x94, 0xD2, 0x38, 0x3D, 0x05, 0xF0, 0x8A, 0x60, 0x1C, 0xB7, + 0x1D, 0xF5, 0xB7, 0x53, 0x77, 0xD3, 0x9D, 0x3D, 0x70, 0x6A, + 0xCB, 0x18, 0x20, 0x6B, 0x29, 0x17, 0x3A, 0x6D, 0xA1, 0xB2, + 0x64, 0xDB, 0x6C, 0xE6, 0x1A, 0x95, 0xA7, 0xF4, 0x1A, 0x78, + 0x1D, 0xA2, 0x40, 0x15, 0x41, 0x59, 0xDD, 0xEE, 0x23, 0x57, + 0xCE, 0x36, 0x0D, 0x55, 0xBD, 0xB8, 0xFD, 0x0F, 0x35, 0xBD, + 0x5B, 0x92, 0xD6, 0x1C, 0x84, 0x8C, 0x32, 0x64, 0xA6, 0x5C, + 0x45, 0x18, 0x07, 0x6B, 0xF9, 0xA9, 0x43, 0x9A, 0x83, 0xCD, + 0xB5, 0xB3, 0xD9, 0x17, 0x99, 0x2C, 0x2A, 0x8B, 0xE0, 0x8E, + 0xAF, 0xA6, 0x4C, 0x95, 0xBB, 0x70, 0x60, 0x1A, 0x3A, 0x97, + 0xAA, 0x2F, 0x3D, 0x22, 0x83, 0xB7, 0x4F, 0x59, 0xED, 0x3F, + 0x4E, 0xF4, 0x19, 0xC6, 0x25, 0x0B, 0x0A, 0x5E, 0x21, 0xB9, + 0x91, 0xB8, 0x19, 0x84, 0x48, 0x78, 0xCE, 0x27, 0xBF, 0x41, + 0x89, 0xF6, 0x30, 0xFD, 0x6B, 0xD9, 0xB8, 0x1D, 0x72, 0x8A, + 0x56, 0xCC, 0x2F, 0x82, 0xE4, 0x46, 0x4D, 0x75, 0xD8, 0x92, + 0xE6, 0x9C, 0xCC, 0xD2, 0xCD, 0x35, 0xE4, 0xFC, 0x2A, 0x85, + 0x6B, 0xA9, 0xB2, 0x27, 0xC9, 0xA1, 0xFF, 0xB3, 0x96, 0x3E, + 0x59, 0xF6, 0x4C, 0x66, 0x56, 0x2E, 0xF5, 0x1B, 0x97, 0x32, + 0xB0, 0x71, 0x5A, 0x9C, 0x50, 0x4B, 0x6F, 0xC4, 0xCA, 0x94, + 0x75, 0x37, 0x46, 0x10, 0x12, 0x2F, 0x4F, 0xA3, 0x82, 0xCD, + 0xBD, 0x7C}; + + const uint8_t ss_exp[SIKEp503_SS_BYTESZ] = { + 0x74, 0x3D, 0x25, 0x36, 0x00, 0x24, 0x63, 0x1A, 0x39, 0x1A, + 0xB4, 0xAD, 0x01, 0x17, 0x78, 0xE9}; + + uint8_t ss_dec[SIKEp503_SS_BYTESZ] = {0}; + SIKE_decaps(ss_dec, ct_exp, pk, sk); + EXPECT_EQ(memcmp(ss_dec, ss_exp, sizeof(ss_exp)), 0); +} + +// SIKE_encaps and SIKE_keypair doesn't return zeros. +TEST(SIKE, NonZero) { + uint8_t sk[SIKEp503_PRV_BYTESZ] = {0}; + uint8_t pk[SIKEp503_PUB_BYTESZ] = {0}; + uint8_t ct[SIKEp503_CT_BYTESZ] = {0}; + uint8_t ss[SIKEp503_SS_BYTESZ] = {0}; + + // Check secret and public key returned by SIKE_keypair + EXPECT_EQ(SIKE_keypair(sk, pk), 1); + uint8_t tmp = 0; + for (size_t i=0; i + +#include "../crypto/internal.h" +#include "sike.h" + +// Conversion macro from number of bits to number of bytes +#define BITS_TO_BYTES(nbits) (((nbits)+7)/8) + +// Bit size of the field +#define BITS_FIELD 503 +// Byte size of the field +#define FIELD_BYTESZ BITS_TO_BYTES(BITS_FIELD) +// Number of 64-bit words of a 256-bit element +#define NBITS_ORDER 256 +#define NWORDS64_ORDER ((NBITS_ORDER+63)/64) +// Number of elements in Alice's strategy +#define A_max 125 +// Number of elements in Bob's strategy +#define B_max 159 +// Word size size +#define RADIX sizeof(crypto_word_t)*8 +// Byte size of a limb +#define LSZ sizeof(crypto_word_t) + +#if defined(OPENSSL_64_BIT) + // Number of words of a 503-bit field element + #define NWORDS_FIELD 8 + // Number of "0" digits in the least significant part of p503 + 1 + #define p503_ZERO_WORDS 3 + // U64_TO_WORDS expands |x| for a |crypto_word_t| array literal. + #define U64_TO_WORDS(x) UINT64_C(x) +#else + // Number of words of a 503-bit field element + #define NWORDS_FIELD 16 + // Number of "0" digits in the least significant part of p503 + 1 + #define p503_ZERO_WORDS 7 + // U64_TO_WORDS expands |x| for a |crypto_word_t| array literal. + #define U64_TO_WORDS(x) \ + (uint32_t)(UINT64_C(x) & 0xffffffff), (uint32_t)(UINT64_C(x) >> 32) +#endif + +// Extended datatype support +#if !defined(BORINGSSL_HAS_UINT128) + typedef uint64_t uint128_t[2]; +#endif + +// The following functions return 1 (TRUE) if condition is true, 0 (FALSE) otherwise +// Digit multiplication +#define MUL(multiplier, multiplicand, hi, lo) digit_x_digit((multiplier), (multiplicand), &(lo)); + +// If mask |x|==0xff.ff set |x| to 1, otherwise 0 +#define M2B(x) ((x)>>(RADIX-1)) + +// Digit addition with carry +#define ADDC(carryIn, addend1, addend2, carryOut, sumOut) \ +do { \ + crypto_word_t tempReg = (addend1) + (crypto_word_t)(carryIn); \ + (sumOut) = (addend2) + tempReg; \ + (carryOut) = M2B(constant_time_lt_w(tempReg, (crypto_word_t)(carryIn)) | \ + constant_time_lt_w((sumOut), tempReg)); \ +} while(0) + +// Digit subtraction with borrow +#define SUBC(borrowIn, minuend, subtrahend, borrowOut, differenceOut) \ +do { \ + crypto_word_t tempReg = (minuend) - (subtrahend); \ + crypto_word_t borrowReg = M2B(constant_time_lt_w((minuend), (subtrahend))); \ + borrowReg |= ((borrowIn) & constant_time_is_zero_w(tempReg)); \ + (differenceOut) = tempReg - (crypto_word_t)(borrowIn); \ + (borrowOut) = borrowReg; \ +} while(0) + +/* Old GCC 4.9 (jessie) doesn't implement {0} initialization properly, + which violates C11 as described in 6.7.9, 21 (similarily C99, 6.7.8). + Defines below are used to work around the bug, and provide a way + to initialize f2elem_t and point_proj_t structs. + Bug has been fixed in GCC6 (debian stretch). +*/ +#define F2ELM_INIT {{ {0}, {0} }} +#define POINT_PROJ_INIT {{ F2ELM_INIT, F2ELM_INIT }} + +// Datatype for representing 503-bit field elements (512-bit max.) +// Elements over GF(p503) are encoded in 63 octets in little endian format +// (i.e., the least significant octet is located in the lowest memory address). +typedef crypto_word_t felm_t[NWORDS_FIELD]; + +// An element in F_{p^2}, is composed of two coefficients from F_p, * i.e. +// Fp2 element = c0 + c1*i in F_{p^2} +// Datatype for representing double-precision 2x503-bit field elements (512-bit max.) +// Elements (a+b*i) over GF(p503^2), where a and b are defined over GF(p503), are +// encoded as {a, b}, with a in the lowest memory portion. +typedef struct { + felm_t c0; + felm_t c1; +} fp2; + +// Our F_{p^2} element type is a pointer to the struct. +typedef fp2 f2elm_t[1]; + +// Datatype for representing double-precision 2x503-bit +// field elements in contiguous memory. +typedef crypto_word_t dfelm_t[2*NWORDS_FIELD]; + +// Constants used during SIKEp503 computation. +struct params_t { + // Stores P503 prime + const crypto_word_t prime[NWORDS_FIELD]; + // Stores P503 + 1 + const crypto_word_t prime_p1[NWORDS_FIELD]; + // Stores P503 * 2 + const crypto_word_t prime_x2[NWORDS_FIELD]; + // Alice's generator values {XPA0 + XPA1*i, XQA0, XRA0 + XRA1*i} + // in GF(p503^2), expressed in Montgomery representation + const crypto_word_t A_gen[5*NWORDS_FIELD]; + // Bob's generator values {XPB0 + XPB1*i, XQB0, XRB0 + XRB1*i} + // in GF(p503^2), expressed in Montgomery representation + const crypto_word_t B_gen[5*NWORDS_FIELD]; + // Montgomery constant mont_R2 = (2^512)^2 mod p503 + const crypto_word_t mont_R2[NWORDS_FIELD]; + // Value 'one' in Montgomery representation + const crypto_word_t mont_one[NWORDS_FIELD]; + // Fixed parameters for isogeny tree computation + const unsigned int A_strat[A_max-1]; + const unsigned int B_strat[B_max-1]; +}; + +// Point representation in projective XZ Montgomery coordinates. +typedef struct { + f2elm_t X; + f2elm_t Z; +} point_proj; +typedef point_proj point_proj_t[1]; + +#endif // UTILS_H_ diff --git a/third_party/boringssl/kit/src/tool/speed.cc b/third_party/boringssl/kit/src/tool/speed.cc index 41dbc50e..47edc751 100644 --- a/third_party/boringssl/kit/src/tool/speed.cc +++ b/third_party/boringssl/kit/src/tool/speed.cc @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -50,6 +51,8 @@ OPENSSL_MSVC_PRAGMA(warning(pop)) #include "../crypto/internal.h" #include "internal.h" +#include "../third_party/sike/sike.h" + // TimeResults represents the results of benchmarking a function. struct TimeResults { @@ -98,6 +101,7 @@ static uint64_t time_now() { #endif static uint64_t g_timeout_seconds = 1; +static std::vector g_chunk_lengths = {16, 256, 1350, 8192, 16384}; static bool TimeFunction(TimeResults *results, std::function func) { // total_us is the total amount of time that we'll aim to measure a function @@ -274,26 +278,101 @@ static bool SpeedRSAKeyGen(const std::string &selected) { (static_cast(num_calls) / us) * 1000000); const size_t n = durations.size(); assert(n > 0); + + // |min| and |max| must be stored in temporary variables to avoid an MSVC + // bug on x86. There, size_t is a typedef for unsigned, but MSVC's printf + // warning tries to retain the distinction and suggest %zu for size_t + // instead of %u. It gets confused if std::vector and + // std::vector are both instantiated. Being typedefs, the two + // instantiations are identical, which somehow breaks the size_t vs unsigned + // metadata. + unsigned min = durations[0]; unsigned median = n & 1 ? durations[n / 2] : (durations[n / 2 - 1] + durations[n / 2]) / 2; - printf(" min: %uus, median: %uus, max: %uus\n", durations[0], median, - durations[n - 1]); + unsigned max = durations[n - 1]; + printf(" min: %uus, median: %uus, max: %uus\n", min, median, max); } return true; } +static bool SpeedSIKEP503(const std::string &selected) { + if (!selected.empty() && selected.find("SIKE") == std::string::npos) { + return true; + } + // speed generation + uint8_t public_SIKE[SIKEp503_PUB_BYTESZ]; + uint8_t private_SIKE[SIKEp503_PRV_BYTESZ]; + uint8_t ct[SIKEp503_CT_BYTESZ]; + bool res; + + { + TimeResults results; + res = TimeFunction(&results, + [&private_SIKE, &public_SIKE]() -> bool { + return (SIKE_keypair(private_SIKE, public_SIKE) == 1); + }); + results.Print("SIKE/P503 generate"); + } + + if (!res) { + fprintf(stderr, "Failed to time SIKE_keypair.\n"); + return false; + } + + { + TimeResults results; + TimeFunction(&results, + [&ct, &public_SIKE]() -> bool { + uint8_t ss[SIKEp503_SS_BYTESZ]; + SIKE_encaps(ss, ct, public_SIKE); + return true; + }); + results.Print("SIKE/P503 encap"); + } + + if (!res) { + fprintf(stderr, "Failed to time SIKE_encaps.\n"); + return false; + } + + { + TimeResults results; + TimeFunction(&results, + [&ct, &public_SIKE, &private_SIKE]() -> bool { + uint8_t ss[SIKEp503_SS_BYTESZ]; + SIKE_decaps(ss, ct, public_SIKE, private_SIKE); + return true; + }); + results.Print("SIKE/P503 decap"); + } + + if (!res) { + fprintf(stderr, "Failed to time SIKE_decaps.\n"); + return false; + } + return true; +} + static uint8_t *align(uint8_t *in, unsigned alignment) { return reinterpret_cast( (reinterpret_cast(in) + alignment) & ~static_cast(alignment - 1)); } -static bool SpeedAEADChunk(const EVP_AEAD *aead, const std::string &name, +static std::string ChunkLenSuffix(size_t chunk_len) { + char buf[32]; + snprintf(buf, sizeof(buf), " (%zu byte%s)", chunk_len, + chunk_len != 1 ? "s" : ""); + return buf; +} + +static bool SpeedAEADChunk(const EVP_AEAD *aead, std::string name, size_t chunk_len, size_t ad_len, evp_aead_direction_t direction) { static const unsigned kAlignment = 16; + name += ChunkLenSuffix(chunk_len); bssl::ScopedEVP_AEAD_CTX ctx; const size_t key_len = EVP_AEAD_key_length(aead); const size_t nonce_len = EVP_AEAD_nonce_length(aead); @@ -390,12 +469,12 @@ static bool SpeedAEAD(const EVP_AEAD *aead, const std::string &name, return true; } - return SpeedAEADChunk(aead, name + " (16 bytes)", 16, ad_len, - evp_aead_seal) && - SpeedAEADChunk(aead, name + " (1350 bytes)", 1350, ad_len, - evp_aead_seal) && - SpeedAEADChunk(aead, name + " (8192 bytes)", 8192, ad_len, - evp_aead_seal); + for (size_t chunk_len : g_chunk_lengths) { + if (!SpeedAEADChunk(aead, name, chunk_len, ad_len, evp_aead_seal)) { + return false; + } + } + return true; } static bool SpeedAEADOpen(const EVP_AEAD *aead, const std::string &name, @@ -404,23 +483,25 @@ static bool SpeedAEADOpen(const EVP_AEAD *aead, const std::string &name, return true; } - return SpeedAEADChunk(aead, name + " (16 bytes)", 16, ad_len, - evp_aead_open) && - SpeedAEADChunk(aead, name + " (1350 bytes)", 1350, ad_len, - evp_aead_open) && - SpeedAEADChunk(aead, name + " (8192 bytes)", 8192, ad_len, - evp_aead_open); + for (size_t chunk_len : g_chunk_lengths) { + if (!SpeedAEADChunk(aead, name, chunk_len, ad_len, evp_aead_open)) { + return false; + } + } + + return true; } -static bool SpeedHashChunk(const EVP_MD *md, const std::string &name, +static bool SpeedHashChunk(const EVP_MD *md, std::string name, size_t chunk_len) { bssl::ScopedEVP_MD_CTX ctx; - uint8_t scratch[8192]; + uint8_t scratch[16384]; if (chunk_len > sizeof(scratch)) { return false; } + name += ChunkLenSuffix(chunk_len); TimeResults results; if (!TimeFunction(&results, [&ctx, md, chunk_len, &scratch]() -> bool { uint8_t digest[EVP_MAX_MD_SIZE]; @@ -438,24 +519,30 @@ static bool SpeedHashChunk(const EVP_MD *md, const std::string &name, results.PrintWithBytes(name, chunk_len); return true; } + static bool SpeedHash(const EVP_MD *md, const std::string &name, const std::string &selected) { if (!selected.empty() && name.find(selected) == std::string::npos) { return true; } - return SpeedHashChunk(md, name + " (16 bytes)", 16) && - SpeedHashChunk(md, name + " (256 bytes)", 256) && - SpeedHashChunk(md, name + " (8192 bytes)", 8192); + for (size_t chunk_len : g_chunk_lengths) { + if (!SpeedHashChunk(md, name, chunk_len)) { + return false; + } + } + + return true; } -static bool SpeedRandomChunk(const std::string &name, size_t chunk_len) { - uint8_t scratch[8192]; +static bool SpeedRandomChunk(std::string name, size_t chunk_len) { + uint8_t scratch[16384]; if (chunk_len > sizeof(scratch)) { return false; } + name += ChunkLenSuffix(chunk_len); TimeResults results; if (!TimeFunction(&results, [chunk_len, &scratch]() -> bool { RAND_bytes(scratch, chunk_len); @@ -473,9 +560,13 @@ static bool SpeedRandom(const std::string &selected) { return true; } - return SpeedRandomChunk("RNG (16 bytes)", 16) && - SpeedRandomChunk("RNG (256 bytes)", 256) && - SpeedRandomChunk("RNG (8192 bytes)", 8192); + for (size_t chunk_len : g_chunk_lengths) { + if (!SpeedRandomChunk("RNG", chunk_len)) { + return false; + } + } + + return true; } static bool SpeedECDHCurve(const std::string &name, int nid, @@ -802,15 +893,25 @@ static bool SpeedHRSS(const std::string &selected) { static const struct argument kArguments[] = { { - "-filter", kOptionalArgument, - "A filter on the speed tests to run", + "-filter", + kOptionalArgument, + "A filter on the speed tests to run", }, { - "-timeout", kOptionalArgument, - "The number of seconds to run each test for (default is 1)", + "-timeout", + kOptionalArgument, + "The number of seconds to run each test for (default is 1)", }, { - "", kOptionalArgument, "", + "-chunks", + kOptionalArgument, + "A comma-separated list of input sizes to run tests at (default is " + "16,256,1350,8192,16384)", + }, + { + "", + kOptionalArgument, + "", }, }; @@ -830,6 +931,32 @@ bool Speed(const std::vector &args) { g_timeout_seconds = atoi(args_map["-timeout"].c_str()); } + if (args_map.count("-chunks") != 0) { + g_chunk_lengths.clear(); + const char *start = args_map["-chunks"].data(); + const char *end = start + args_map["-chunks"].size(); + while (start != end) { + errno = 0; + char *ptr; + unsigned long long val = strtoull(start, &ptr, 10); + if (ptr == start /* no numeric characters found */ || + errno == ERANGE /* overflow */ || + static_cast(val) != val) { + fprintf(stderr, "Error parsing -chunks argument\n"); + return false; + } + g_chunk_lengths.push_back(static_cast(val)); + start = ptr; + if (start != end) { + if (*start != ',') { + fprintf(stderr, "Error parsing -chunks argument\n"); + return false; + } + start++; + } + } + } + // kTLSADLen is the number of bytes of additional data that TLS passes to // AEADs. static const size_t kTLSADLen = 13; @@ -871,6 +998,7 @@ bool Speed(const std::vector &args) { !SpeedECDH(selected) || !SpeedECDSA(selected) || !Speed25519(selected) || + !SpeedSIKEP503(selected) || !SpeedSPAKE2(selected) || !SpeedScrypt(selected) || !SpeedRSAKeyGen(selected) || diff --git a/third_party/boringssl/kit/src/util/bot/DEPS b/third_party/boringssl/kit/src/util/bot/DEPS index 5d6e8cd9..1eb563de 100644 --- a/third_party/boringssl/kit/src/util/bot/DEPS +++ b/third_party/boringssl/kit/src/util/bot/DEPS @@ -28,7 +28,7 @@ deps = { }, 'boringssl/util/bot/android_tools': { - 'url': Var('chromium_git') + '/android_tools.git' + '@' + 'e958d6ea74442d4e0849bb8a018d215a0e78981d', + 'url': Var('chromium_git') + '/android_tools.git' + '@' + '347a7c8078a009e98995985b7ab6ec6b35696dea', 'condition': 'checkout_android', }, @@ -36,18 +36,18 @@ deps = { Var('chromium_git') + '/external/gyp.git' + '@' + 'd61a9397e668fa9843c4aa7da9e79460fe590bfb', 'boringssl/util/bot/libFuzzer': { - 'url': Var('chromium_git') + '/chromium/llvm-project/compiler-rt/lib/fuzzer.git' +'@' + '2a53098584c48af50aec3fb51febe5e651489774', + 'url': Var('chromium_git') + '/chromium/llvm-project/compiler-rt/lib/fuzzer.git' +'@' + 'e847d8a9b47158695593d5693b0f69250472b229', 'condition': 'checkout_fuzzer', }, # Update the following revisions from - # https://chromium.googlesource.com/chromium/buildtools/+/master/DEPS + # https://chromium.googlesource.com/chromium/src/+/master/buildtools/DEPS 'boringssl/util/bot/libcxx': { - 'url': Var('chromium_git') + '/chromium/llvm-project/libcxx.git' + '@' + 'e713cc0acf1ae8b82f451bf58ebef67a46ceddfb', + 'url': Var('chromium_git') + '/chromium/llvm-project/libcxx.git' + '@' + '955113db37563c8632e31ddcff2047845553d7ff', 'condition': 'checkout_libcxx', }, 'boringssl/util/bot/libcxxabi': { - 'url': Var('chromium_git') + '/chromium/llvm-project/libcxxabi.git' + '@' + '307bb62985575b2e3216a8cfd7e122e0574f33a9', + 'url': Var('chromium_git') + '/chromium/llvm-project/libcxxabi.git' + '@' + '0d529660e32d77d9111912d73f2c74fc5fa2a858', 'condition': 'checkout_libcxx', }, } diff --git a/third_party/boringssl/kit/src/util/bot/UPDATING b/third_party/boringssl/kit/src/util/bot/UPDATING index 5a46cdf7..0e4f4935 100644 --- a/third_party/boringssl/kit/src/util/bot/UPDATING +++ b/third_party/boringssl/kit/src/util/bot/UPDATING @@ -79,6 +79,6 @@ but upload it with the following command. (Note the bucket is different.) upload_to_google_storage.py -b chrome-boringssl-sde sde-linux64.tar.bz2 sde-win32.tar.bz2 -The current revision is sde-external-8.16.0-2018-01-30-*.tar.bz2. +The current revision is sde-external-8.35.0-2019-03-11-*.tar.bz2. When adding new files, remember to update .gitignore. diff --git a/third_party/boringssl/kit/src/util/bot/go/bootstrap.py b/third_party/boringssl/kit/src/util/bot/go/bootstrap.py index 1a33c793..d2957480 100755 --- a/third_party/boringssl/kit/src/util/bot/go/bootstrap.py +++ b/third_party/boringssl/kit/src/util/bot/go/bootstrap.py @@ -45,7 +45,7 @@ WORKSPACE = os.path.join(ROOT, 'go') EXE_SFX = '.exe' if sys.platform == 'win32' else '' # Pinned version of Go toolset to download. -TOOLSET_VERSION = 'go1.11.4' +TOOLSET_VERSION = 'go1.12.1' # Platform dependent portion of a download URL. See http://golang.org/dl/. TOOLSET_VARIANTS = { diff --git a/third_party/boringssl/kit/src/util/bot/sde-linux64.tar.bz2.sha1 b/third_party/boringssl/kit/src/util/bot/sde-linux64.tar.bz2.sha1 index bd933237..6037df5a 100644 --- a/third_party/boringssl/kit/src/util/bot/sde-linux64.tar.bz2.sha1 +++ b/third_party/boringssl/kit/src/util/bot/sde-linux64.tar.bz2.sha1 @@ -1 +1 @@ -fe5d01f13b82469ce3854307bba9565d1a02b921 \ No newline at end of file +25581fcf3a14d4ca70149c6186111603f725fb26 \ No newline at end of file diff --git a/third_party/boringssl/kit/src/util/bot/sde-win32.tar.bz2.sha1 b/third_party/boringssl/kit/src/util/bot/sde-win32.tar.bz2.sha1 index d17e78db..0837b080 100644 --- a/third_party/boringssl/kit/src/util/bot/sde-win32.tar.bz2.sha1 +++ b/third_party/boringssl/kit/src/util/bot/sde-win32.tar.bz2.sha1 @@ -1 +1 @@ -0f746c4c64e07794fd597ec950a24de571376732 \ No newline at end of file +d08247e1b7d9837f75ffbfa3f44e9b8f44eb90ba \ No newline at end of file diff --git a/third_party/boringssl/kit/src/util/bot/update_clang.py b/third_party/boringssl/kit/src/util/bot/update_clang.py index b1f77767..5151b135 100644 --- a/third_party/boringssl/kit/src/util/bot/update_clang.py +++ b/third_party/boringssl/kit/src/util/bot/update_clang.py @@ -19,8 +19,8 @@ import urllib2 # CLANG_REVISION and CLANG_SUB_REVISION determine the build of clang # to use. These should be synced with tools/clang/scripts/update.py in # Chromium. -CLANG_REVISION = '349417' -CLANG_SUB_REVISION=2 +CLANG_REVISION = '357569' +CLANG_SUB_REVISION = 1 PACKAGE_VERSION = "%s-%s" % (CLANG_REVISION, CLANG_SUB_REVISION) diff --git a/third_party/boringssl/kit/src/util/bot/vs_toolchain.py b/third_party/boringssl/kit/src/util/bot/vs_toolchain.py index 2530662c..feaaa7c7 100644 --- a/third_party/boringssl/kit/src/util/bot/vs_toolchain.py +++ b/third_party/boringssl/kit/src/util/bot/vs_toolchain.py @@ -87,9 +87,9 @@ def _GetDesiredVsToolchainHashes(): # Update 3 final with 10.0.15063.468 SDK and no vctip.exe. return ['f53e4598951162bad6330f7a167486c7ae5db1e5'] if env_version == '2017': - # VS 2017 Update 7.1 (15.7.1) with 10.0.17134.12 SDK, rebuilt with - # dbghelp.dll fix. - return ['3bc0ec615cf20ee342f3bc29bc991b5ad66d8d2c'] + # VS 2017 Update 9 (15.9.3) with 10.0.17763.132 SDK, 10.0.17134 version of + # d3dcompiler_47.dll, with ARM64 libraries. + return ['818a152b3f1da991c1725d85be19a0f27af6bab4'] raise Exception('Unsupported VS version %s' % env_version) diff --git a/third_party/boringssl/kit/src/util/fipstools/delocate/delocate.go b/third_party/boringssl/kit/src/util/fipstools/delocate/delocate.go index ce1a8b2d..a43b4286 100644 --- a/third_party/boringssl/kit/src/util/fipstools/delocate/delocate.go +++ b/third_party/boringssl/kit/src/util/fipstools/delocate/delocate.go @@ -801,6 +801,8 @@ const ( // instrCombine merges the source and destination in some fashion, for example // a 2-operand bitwise operation. instrCombine + // instrThreeArg merges two sources into a destination in some fashion. + instrThreeArg instrOther ) @@ -831,6 +833,11 @@ func classifyInstruction(instr string, args []*node32) instructionType { return instrCombine } + case "sarxq", "shlxq", "shrxq": + if len(args) == 3 { + return instrThreeArg + } + case "vpbroadcastq": if len(args) == 2 { return instrTransformingMove @@ -878,10 +885,24 @@ func saveFlags(w stringWriter, redzoneCleared bool) wrapperFunc { } } -func saveRegister(w stringWriter, avoidReg string) (wrapperFunc, string) { - reg := "%rax" - if reg == avoidReg { - reg = "%rbx" +func saveRegister(w stringWriter, avoidRegs []string) (wrapperFunc, string) { + candidates := []string{"%rax", "%rbx", "%rcx", "%rdx"} + + var reg string +NextCandidate: + for _, candidate := range candidates { + for _, avoid := range avoidRegs { + if candidate == avoid { + continue NextCandidate + } + } + + reg = candidate + break + } + + if len(reg) == 0 { + panic("too many excluded registers") } return func(k func()) { @@ -918,6 +939,13 @@ func combineOp(w stringWriter, instructionName, source, dest string) wrapperFunc } } +func threeArgCombineOp(w stringWriter, instructionName, source1, source2, dest string) wrapperFunc { + return func(k func()) { + k() + w.WriteString("\t" + instructionName + " " + source1 + ", " + source2 + ", " + dest + "\n") + } +} + func isValidLEATarget(reg string) bool { return !strings.HasPrefix(reg, "%xmm") && !strings.HasPrefix(reg, "%ymm") && !strings.HasPrefix(reg, "%zmm") } @@ -1033,9 +1061,6 @@ Args: if len(offset) > 0 { return nil, errors.New("loading from GOT with offset is unsupported") } - if i != 0 { - return nil, errors.New("GOT access must be source operand") - } if !d.isRIPRelative(memRef) { return nil, errors.New("GOT access must be IP-relative") } @@ -1048,10 +1073,15 @@ Args: useGOT = true } + classification := classifyInstruction(instructionName, argNodes) + if classification != instrThreeArg && i != 0 { + return nil, errors.New("GOT access must be source operand") + } + // Reduce the instruction to movq symbol@GOTPCREL, targetReg. var targetReg string var redzoneCleared bool - switch classifyInstruction(instructionName, argNodes) { + switch classification { case instrPush: wrappers = append(wrappers, push(d.output)) targetReg = "%rax" @@ -1073,12 +1103,36 @@ Args: if !isValidLEATarget(targetReg) { return nil, fmt.Errorf("cannot handle combining instructions targeting non-general registers") } - saveRegWrapper, tempReg := saveRegister(d.output, targetReg) + saveRegWrapper, tempReg := saveRegister(d.output, []string{targetReg}) redzoneCleared = true wrappers = append(wrappers, saveRegWrapper) wrappers = append(wrappers, combineOp(d.output, instructionName, tempReg, targetReg)) targetReg = tempReg + case instrThreeArg: + if n := len(argNodes); n != 3 { + return nil, fmt.Errorf("three-argument instruction has %d arguments", n) + } + if i != 0 && i != 1 { + return nil, errors.New("GOT access must be from soure operand") + } + targetReg = d.contents(argNodes[2]) + + otherSource := d.contents(argNodes[1]) + if i == 1 { + otherSource = d.contents(argNodes[0]) + } + + saveRegWrapper, tempReg := saveRegister(d.output, []string{targetReg, otherSource}) + redzoneCleared = true + wrappers = append(wrappers, saveRegWrapper) + + if i == 0 { + wrappers = append(wrappers, threeArgCombineOp(d.output, instructionName, tempReg, otherSource, targetReg)) + } else { + wrappers = append(wrappers, threeArgCombineOp(d.output, instructionName, otherSource, tempReg, targetReg)) + } + targetReg = tempReg default: return nil, fmt.Errorf("Cannot rewrite GOTPCREL reference for instruction %q", instructionName) } @@ -1087,7 +1141,7 @@ Args: // Sometimes the compiler will load from the GOT to an // XMM register, which is not a valid target of an LEA // instruction. - saveRegWrapper, tempReg := saveRegister(d.output, "") + saveRegWrapper, tempReg := saveRegister(d.output, nil) wrappers = append(wrappers, saveRegWrapper) isAVX := strings.HasPrefix(instructionName, "v") wrappers = append(wrappers, moveTo(d.output, targetReg, isAVX, tempReg)) @@ -1215,6 +1269,10 @@ func transform(w stringWriter, inputs []inputFile) error { // maxObservedFileNumber contains the largest seen file number in a // .file directive. Zero is not a valid number. maxObservedFileNumber := 0 + // fileDirectivesContainMD5 is true if the compiler is outputting MD5 + // checksums in .file directives. If it does so, then this script needs + // to match that behaviour otherwise warnings result. + fileDirectivesContainMD5 := false // OPENSSL_ia32cap_get will be synthesized by this script. symbols["OPENSSL_ia32cap_get"] = struct{}{} @@ -1274,6 +1332,12 @@ func transform(w stringWriter, inputs []inputFile) error { if fileNo > maxObservedFileNumber { maxObservedFileNumber = fileNo } + + for _, token := range parts[2:] { + if token == "md5" { + fileDirectivesContainMD5 = true + } + } }, ruleStatement, ruleLocationDirective) } @@ -1294,7 +1358,11 @@ func transform(w stringWriter, inputs []inputFile) error { } w.WriteString(".text\n") - w.WriteString(fmt.Sprintf(".file %d \"inserted_by_delocate.c\"\n", maxObservedFileNumber+1)) + var fileTrailing string + if fileDirectivesContainMD5 { + fileTrailing = " md5 0x00000000000000000000000000000000" + } + w.WriteString(fmt.Sprintf(".file %d \"inserted_by_delocate.c\"%s\n", maxObservedFileNumber+1, fileTrailing)) w.WriteString(fmt.Sprintf(".loc %d 1 0\n", maxObservedFileNumber+1)) w.WriteString("BORINGSSL_bcm_text_start:\n") diff --git a/third_party/boringssl/kit/src/util/fipstools/delocate/delocate.peg b/third_party/boringssl/kit/src/util/fipstools/delocate/delocate.peg index 82a3cb5a..b24a47a3 100644 --- a/third_party/boringssl/kit/src/util/fipstools/delocate/delocate.peg +++ b/third_party/boringssl/kit/src/util/fipstools/delocate/delocate.peg @@ -36,7 +36,7 @@ Arg <- QuotedArg / [[0-9a-z%+\-*_@.]]* QuotedArg <- '"' QuotedText '"' QuotedText <- (EscapedChar / [^"])* LabelContainingDirective <- LabelContainingDirectiveName WS SymbolArgs -LabelContainingDirectiveName <- ".long" / ".set" / ".8byte" / ".4byte" / ".quad" / ".tc" / ".localentry" / ".size" / ".type" +LabelContainingDirectiveName <- ".long" / ".set" / ".8byte" / ".4byte" / ".quad" / ".tc" / ".localentry" / ".size" / ".type" / ".uleb128" / ".sleb128" SymbolArgs <- SymbolArg ((WS? ',' WS?) SymbolArg)* SymbolArg <- Offset / SymbolType / diff --git a/third_party/boringssl/kit/src/util/fipstools/delocate/delocate.peg.go b/third_party/boringssl/kit/src/util/fipstools/delocate/delocate.peg.go index e1479434..298f55c8 100644 --- a/third_party/boringssl/kit/src/util/fipstools/delocate/delocate.peg.go +++ b/third_party/boringssl/kit/src/util/fipstools/delocate/delocate.peg.go @@ -1260,7 +1260,7 @@ func (p *Asm) Init() { position, tokenIndex = position131, tokenIndex131 return false }, - /* 11 LabelContainingDirectiveName <- <(('.' ('l' / 'L') ('o' / 'O') ('n' / 'N') ('g' / 'G')) / ('.' ('s' / 'S') ('e' / 'E') ('t' / 'T')) / ('.' '8' ('b' / 'B') ('y' / 'Y') ('t' / 'T') ('e' / 'E')) / ('.' '4' ('b' / 'B') ('y' / 'Y') ('t' / 'T') ('e' / 'E')) / ('.' ('q' / 'Q') ('u' / 'U') ('a' / 'A') ('d' / 'D')) / ('.' ('t' / 'T') ('c' / 'C')) / ('.' ('l' / 'L') ('o' / 'O') ('c' / 'C') ('a' / 'A') ('l' / 'L') ('e' / 'E') ('n' / 'N') ('t' / 'T') ('r' / 'R') ('y' / 'Y')) / ('.' ('s' / 'S') ('i' / 'I') ('z' / 'Z') ('e' / 'E')) / ('.' ('t' / 'T') ('y' / 'Y') ('p' / 'P') ('e' / 'E')))> */ + /* 11 LabelContainingDirectiveName <- <(('.' ('l' / 'L') ('o' / 'O') ('n' / 'N') ('g' / 'G')) / ('.' ('s' / 'S') ('e' / 'E') ('t' / 'T')) / ('.' '8' ('b' / 'B') ('y' / 'Y') ('t' / 'T') ('e' / 'E')) / ('.' '4' ('b' / 'B') ('y' / 'Y') ('t' / 'T') ('e' / 'E')) / ('.' ('q' / 'Q') ('u' / 'U') ('a' / 'A') ('d' / 'D')) / ('.' ('t' / 'T') ('c' / 'C')) / ('.' ('l' / 'L') ('o' / 'O') ('c' / 'C') ('a' / 'A') ('l' / 'L') ('e' / 'E') ('n' / 'N') ('t' / 'T') ('r' / 'R') ('y' / 'Y')) / ('.' ('s' / 'S') ('i' / 'I') ('z' / 'Z') ('e' / 'E')) / ('.' ('t' / 'T') ('y' / 'Y') ('p' / 'P') ('e' / 'E')) / ('.' ('u' / 'U') ('l' / 'L') ('e' / 'E') ('b' / 'B') '1' '2' '8') / ('.' ('s' / 'S') ('l' / 'L') ('e' / 'E') ('b' / 'B') '1' '2' '8'))> */ func() bool { position133, tokenIndex133 := position, tokenIndex { @@ -1855,71 +1855,229 @@ func (p *Asm) Init() { l212: goto l135 l205: + position, tokenIndex = position135, tokenIndex135 + if buffer[position] != rune('.') { + goto l214 + } + position++ + { + position215, tokenIndex215 := position, tokenIndex + if buffer[position] != rune('t') { + goto l216 + } + position++ + goto l215 + l216: + position, tokenIndex = position215, tokenIndex215 + if buffer[position] != rune('T') { + goto l214 + } + position++ + } + l215: + { + position217, tokenIndex217 := position, tokenIndex + if buffer[position] != rune('y') { + goto l218 + } + position++ + goto l217 + l218: + position, tokenIndex = position217, tokenIndex217 + if buffer[position] != rune('Y') { + goto l214 + } + position++ + } + l217: + { + position219, tokenIndex219 := position, tokenIndex + if buffer[position] != rune('p') { + goto l220 + } + position++ + goto l219 + l220: + position, tokenIndex = position219, tokenIndex219 + if buffer[position] != rune('P') { + goto l214 + } + position++ + } + l219: + { + position221, tokenIndex221 := position, tokenIndex + if buffer[position] != rune('e') { + goto l222 + } + position++ + goto l221 + l222: + position, tokenIndex = position221, tokenIndex221 + if buffer[position] != rune('E') { + goto l214 + } + position++ + } + l221: + goto l135 + l214: + position, tokenIndex = position135, tokenIndex135 + if buffer[position] != rune('.') { + goto l223 + } + position++ + { + position224, tokenIndex224 := position, tokenIndex + if buffer[position] != rune('u') { + goto l225 + } + position++ + goto l224 + l225: + position, tokenIndex = position224, tokenIndex224 + if buffer[position] != rune('U') { + goto l223 + } + position++ + } + l224: + { + position226, tokenIndex226 := position, tokenIndex + if buffer[position] != rune('l') { + goto l227 + } + position++ + goto l226 + l227: + position, tokenIndex = position226, tokenIndex226 + if buffer[position] != rune('L') { + goto l223 + } + position++ + } + l226: + { + position228, tokenIndex228 := position, tokenIndex + if buffer[position] != rune('e') { + goto l229 + } + position++ + goto l228 + l229: + position, tokenIndex = position228, tokenIndex228 + if buffer[position] != rune('E') { + goto l223 + } + position++ + } + l228: + { + position230, tokenIndex230 := position, tokenIndex + if buffer[position] != rune('b') { + goto l231 + } + position++ + goto l230 + l231: + position, tokenIndex = position230, tokenIndex230 + if buffer[position] != rune('B') { + goto l223 + } + position++ + } + l230: + if buffer[position] != rune('1') { + goto l223 + } + position++ + if buffer[position] != rune('2') { + goto l223 + } + position++ + if buffer[position] != rune('8') { + goto l223 + } + position++ + goto l135 + l223: position, tokenIndex = position135, tokenIndex135 if buffer[position] != rune('.') { goto l133 } position++ { - position214, tokenIndex214 := position, tokenIndex - if buffer[position] != rune('t') { - goto l215 + position232, tokenIndex232 := position, tokenIndex + if buffer[position] != rune('s') { + goto l233 } position++ - goto l214 - l215: - position, tokenIndex = position214, tokenIndex214 - if buffer[position] != rune('T') { + goto l232 + l233: + position, tokenIndex = position232, tokenIndex232 + if buffer[position] != rune('S') { goto l133 } position++ } - l214: + l232: { - position216, tokenIndex216 := position, tokenIndex - if buffer[position] != rune('y') { - goto l217 + position234, tokenIndex234 := position, tokenIndex + if buffer[position] != rune('l') { + goto l235 } position++ - goto l216 - l217: - position, tokenIndex = position216, tokenIndex216 - if buffer[position] != rune('Y') { + goto l234 + l235: + position, tokenIndex = position234, tokenIndex234 + if buffer[position] != rune('L') { goto l133 } position++ } - l216: + l234: { - position218, tokenIndex218 := position, tokenIndex - if buffer[position] != rune('p') { - goto l219 - } - position++ - goto l218 - l219: - position, tokenIndex = position218, tokenIndex218 - if buffer[position] != rune('P') { - goto l133 - } - position++ - } - l218: - { - position220, tokenIndex220 := position, tokenIndex + position236, tokenIndex236 := position, tokenIndex if buffer[position] != rune('e') { - goto l221 + goto l237 } position++ - goto l220 - l221: - position, tokenIndex = position220, tokenIndex220 + goto l236 + l237: + position, tokenIndex = position236, tokenIndex236 if buffer[position] != rune('E') { goto l133 } position++ } - l220: + l236: + { + position238, tokenIndex238 := position, tokenIndex + if buffer[position] != rune('b') { + goto l239 + } + position++ + goto l238 + l239: + position, tokenIndex = position238, tokenIndex238 + if buffer[position] != rune('B') { + goto l133 + } + position++ + } + l238: + if buffer[position] != rune('1') { + goto l133 + } + position++ + if buffer[position] != rune('2') { + goto l133 + } + position++ + if buffer[position] != rune('8') { + goto l133 + } + position++ } l135: add(ruleLabelContainingDirectiveName, position134) @@ -1931,570 +2089,460 @@ func (p *Asm) Init() { }, /* 12 SymbolArgs <- <(SymbolArg (WS? ',' WS? SymbolArg)*)> */ func() bool { - position222, tokenIndex222 := position, tokenIndex + position240, tokenIndex240 := position, tokenIndex { - position223 := position + position241 := position if !_rules[ruleSymbolArg]() { - goto l222 + goto l240 } - l224: + l242: { - position225, tokenIndex225 := position, tokenIndex + position243, tokenIndex243 := position, tokenIndex { - position226, tokenIndex226 := position, tokenIndex + position244, tokenIndex244 := position, tokenIndex if !_rules[ruleWS]() { - goto l226 + goto l244 } - goto l227 - l226: - position, tokenIndex = position226, tokenIndex226 + goto l245 + l244: + position, tokenIndex = position244, tokenIndex244 } - l227: + l245: if buffer[position] != rune(',') { - goto l225 + goto l243 } position++ { - position228, tokenIndex228 := position, tokenIndex + position246, tokenIndex246 := position, tokenIndex if !_rules[ruleWS]() { - goto l228 + goto l246 } - goto l229 - l228: - position, tokenIndex = position228, tokenIndex228 + goto l247 + l246: + position, tokenIndex = position246, tokenIndex246 } - l229: + l247: if !_rules[ruleSymbolArg]() { - goto l225 + goto l243 } - goto l224 - l225: - position, tokenIndex = position225, tokenIndex225 + goto l242 + l243: + position, tokenIndex = position243, tokenIndex243 } - add(ruleSymbolArgs, position223) + add(ruleSymbolArgs, position241) } return true - l222: - position, tokenIndex = position222, tokenIndex222 + l240: + position, tokenIndex = position240, tokenIndex240 return false }, /* 13 SymbolArg <- <(Offset / SymbolType / ((Offset / LocalSymbol / SymbolName / Dot) WS? Operator WS? (Offset / LocalSymbol / SymbolName)) / (LocalSymbol TCMarker?) / (SymbolName Offset) / (SymbolName TCMarker?))> */ func() bool { - position230, tokenIndex230 := position, tokenIndex + position248, tokenIndex248 := position, tokenIndex { - position231 := position + position249 := position { - position232, tokenIndex232 := position, tokenIndex + position250, tokenIndex250 := position, tokenIndex if !_rules[ruleOffset]() { - goto l233 + goto l251 } - goto l232 - l233: - position, tokenIndex = position232, tokenIndex232 + goto l250 + l251: + position, tokenIndex = position250, tokenIndex250 if !_rules[ruleSymbolType]() { - goto l234 + goto l252 } - goto l232 - l234: - position, tokenIndex = position232, tokenIndex232 + goto l250 + l252: + position, tokenIndex = position250, tokenIndex250 { - position236, tokenIndex236 := position, tokenIndex + position254, tokenIndex254 := position, tokenIndex if !_rules[ruleOffset]() { - goto l237 + goto l255 } - goto l236 - l237: - position, tokenIndex = position236, tokenIndex236 + goto l254 + l255: + position, tokenIndex = position254, tokenIndex254 if !_rules[ruleLocalSymbol]() { - goto l238 + goto l256 } - goto l236 - l238: - position, tokenIndex = position236, tokenIndex236 + goto l254 + l256: + position, tokenIndex = position254, tokenIndex254 if !_rules[ruleSymbolName]() { - goto l239 + goto l257 } - goto l236 - l239: - position, tokenIndex = position236, tokenIndex236 + goto l254 + l257: + position, tokenIndex = position254, tokenIndex254 if !_rules[ruleDot]() { - goto l235 + goto l253 } } - l236: + l254: { - position240, tokenIndex240 := position, tokenIndex + position258, tokenIndex258 := position, tokenIndex if !_rules[ruleWS]() { - goto l240 + goto l258 } - goto l241 - l240: - position, tokenIndex = position240, tokenIndex240 + goto l259 + l258: + position, tokenIndex = position258, tokenIndex258 } - l241: + l259: if !_rules[ruleOperator]() { - goto l235 + goto l253 } { - position242, tokenIndex242 := position, tokenIndex + position260, tokenIndex260 := position, tokenIndex if !_rules[ruleWS]() { - goto l242 + goto l260 } - goto l243 - l242: - position, tokenIndex = position242, tokenIndex242 + goto l261 + l260: + position, tokenIndex = position260, tokenIndex260 } - l243: + l261: { - position244, tokenIndex244 := position, tokenIndex + position262, tokenIndex262 := position, tokenIndex if !_rules[ruleOffset]() { - goto l245 + goto l263 } - goto l244 - l245: - position, tokenIndex = position244, tokenIndex244 + goto l262 + l263: + position, tokenIndex = position262, tokenIndex262 if !_rules[ruleLocalSymbol]() { - goto l246 + goto l264 } - goto l244 - l246: - position, tokenIndex = position244, tokenIndex244 + goto l262 + l264: + position, tokenIndex = position262, tokenIndex262 if !_rules[ruleSymbolName]() { - goto l235 + goto l253 } } - l244: - goto l232 - l235: - position, tokenIndex = position232, tokenIndex232 + l262: + goto l250 + l253: + position, tokenIndex = position250, tokenIndex250 if !_rules[ruleLocalSymbol]() { - goto l247 + goto l265 } { - position248, tokenIndex248 := position, tokenIndex + position266, tokenIndex266 := position, tokenIndex if !_rules[ruleTCMarker]() { - goto l248 + goto l266 } - goto l249 - l248: - position, tokenIndex = position248, tokenIndex248 + goto l267 + l266: + position, tokenIndex = position266, tokenIndex266 } - l249: - goto l232 - l247: - position, tokenIndex = position232, tokenIndex232 + l267: + goto l250 + l265: + position, tokenIndex = position250, tokenIndex250 if !_rules[ruleSymbolName]() { - goto l250 + goto l268 } if !_rules[ruleOffset]() { - goto l250 + goto l268 } - goto l232 - l250: - position, tokenIndex = position232, tokenIndex232 + goto l250 + l268: + position, tokenIndex = position250, tokenIndex250 if !_rules[ruleSymbolName]() { - goto l230 + goto l248 } { - position251, tokenIndex251 := position, tokenIndex + position269, tokenIndex269 := position, tokenIndex if !_rules[ruleTCMarker]() { - goto l251 + goto l269 } - goto l252 - l251: - position, tokenIndex = position251, tokenIndex251 + goto l270 + l269: + position, tokenIndex = position269, tokenIndex269 } - l252: + l270: } - l232: - add(ruleSymbolArg, position231) + l250: + add(ruleSymbolArg, position249) } return true - l230: - position, tokenIndex = position230, tokenIndex230 + l248: + position, tokenIndex = position248, tokenIndex248 return false }, /* 14 SymbolType <- <(('@' 'f' 'u' 'n' 'c' 't' 'i' 'o' 'n') / ('@' 'o' 'b' 'j' 'e' 'c' 't'))> */ - func() bool { - position253, tokenIndex253 := position, tokenIndex - { - position254 := position - { - position255, tokenIndex255 := position, tokenIndex - if buffer[position] != rune('@') { - goto l256 - } - position++ - if buffer[position] != rune('f') { - goto l256 - } - position++ - if buffer[position] != rune('u') { - goto l256 - } - position++ - if buffer[position] != rune('n') { - goto l256 - } - position++ - if buffer[position] != rune('c') { - goto l256 - } - position++ - if buffer[position] != rune('t') { - goto l256 - } - position++ - if buffer[position] != rune('i') { - goto l256 - } - position++ - if buffer[position] != rune('o') { - goto l256 - } - position++ - if buffer[position] != rune('n') { - goto l256 - } - position++ - goto l255 - l256: - position, tokenIndex = position255, tokenIndex255 - if buffer[position] != rune('@') { - goto l253 - } - position++ - if buffer[position] != rune('o') { - goto l253 - } - position++ - if buffer[position] != rune('b') { - goto l253 - } - position++ - if buffer[position] != rune('j') { - goto l253 - } - position++ - if buffer[position] != rune('e') { - goto l253 - } - position++ - if buffer[position] != rune('c') { - goto l253 - } - position++ - if buffer[position] != rune('t') { - goto l253 - } - position++ - } - l255: - add(ruleSymbolType, position254) - } - return true - l253: - position, tokenIndex = position253, tokenIndex253 - return false - }, - /* 15 Dot <- <'.'> */ - func() bool { - position257, tokenIndex257 := position, tokenIndex - { - position258 := position - if buffer[position] != rune('.') { - goto l257 - } - position++ - add(ruleDot, position258) - } - return true - l257: - position, tokenIndex = position257, tokenIndex257 - return false - }, - /* 16 TCMarker <- <('[' 'T' 'C' ']')> */ - func() bool { - position259, tokenIndex259 := position, tokenIndex - { - position260 := position - if buffer[position] != rune('[') { - goto l259 - } - position++ - if buffer[position] != rune('T') { - goto l259 - } - position++ - if buffer[position] != rune('C') { - goto l259 - } - position++ - if buffer[position] != rune(']') { - goto l259 - } - position++ - add(ruleTCMarker, position260) - } - return true - l259: - position, tokenIndex = position259, tokenIndex259 - return false - }, - /* 17 EscapedChar <- <('\\' .)> */ - func() bool { - position261, tokenIndex261 := position, tokenIndex - { - position262 := position - if buffer[position] != rune('\\') { - goto l261 - } - position++ - if !matchDot() { - goto l261 - } - add(ruleEscapedChar, position262) - } - return true - l261: - position, tokenIndex = position261, tokenIndex261 - return false - }, - /* 18 WS <- <(' ' / '\t')+> */ - func() bool { - position263, tokenIndex263 := position, tokenIndex - { - position264 := position - { - position267, tokenIndex267 := position, tokenIndex - if buffer[position] != rune(' ') { - goto l268 - } - position++ - goto l267 - l268: - position, tokenIndex = position267, tokenIndex267 - if buffer[position] != rune('\t') { - goto l263 - } - position++ - } - l267: - l265: - { - position266, tokenIndex266 := position, tokenIndex - { - position269, tokenIndex269 := position, tokenIndex - if buffer[position] != rune(' ') { - goto l270 - } - position++ - goto l269 - l270: - position, tokenIndex = position269, tokenIndex269 - if buffer[position] != rune('\t') { - goto l266 - } - position++ - } - l269: - goto l265 - l266: - position, tokenIndex = position266, tokenIndex266 - } - add(ruleWS, position264) - } - return true - l263: - position, tokenIndex = position263, tokenIndex263 - return false - }, - /* 19 Comment <- <('#' (!'\n' .)*)> */ func() bool { position271, tokenIndex271 := position, tokenIndex { position272 := position - if buffer[position] != rune('#') { - goto l271 - } - position++ - l273: { - position274, tokenIndex274 := position, tokenIndex - { - position275, tokenIndex275 := position, tokenIndex - if buffer[position] != rune('\n') { - goto l275 - } - position++ - goto l274 - l275: - position, tokenIndex = position275, tokenIndex275 - } - if !matchDot() { + position273, tokenIndex273 := position, tokenIndex + if buffer[position] != rune('@') { goto l274 } + position++ + if buffer[position] != rune('f') { + goto l274 + } + position++ + if buffer[position] != rune('u') { + goto l274 + } + position++ + if buffer[position] != rune('n') { + goto l274 + } + position++ + if buffer[position] != rune('c') { + goto l274 + } + position++ + if buffer[position] != rune('t') { + goto l274 + } + position++ + if buffer[position] != rune('i') { + goto l274 + } + position++ + if buffer[position] != rune('o') { + goto l274 + } + position++ + if buffer[position] != rune('n') { + goto l274 + } + position++ goto l273 l274: - position, tokenIndex = position274, tokenIndex274 + position, tokenIndex = position273, tokenIndex273 + if buffer[position] != rune('@') { + goto l271 + } + position++ + if buffer[position] != rune('o') { + goto l271 + } + position++ + if buffer[position] != rune('b') { + goto l271 + } + position++ + if buffer[position] != rune('j') { + goto l271 + } + position++ + if buffer[position] != rune('e') { + goto l271 + } + position++ + if buffer[position] != rune('c') { + goto l271 + } + position++ + if buffer[position] != rune('t') { + goto l271 + } + position++ } - add(ruleComment, position272) + l273: + add(ruleSymbolType, position272) } return true l271: position, tokenIndex = position271, tokenIndex271 return false }, - /* 20 Label <- <((LocalSymbol / LocalLabel / SymbolName) ':')> */ + /* 15 Dot <- <'.'> */ func() bool { - position276, tokenIndex276 := position, tokenIndex + position275, tokenIndex275 := position, tokenIndex { - position277 := position - { - position278, tokenIndex278 := position, tokenIndex - if !_rules[ruleLocalSymbol]() { - goto l279 - } - goto l278 - l279: - position, tokenIndex = position278, tokenIndex278 - if !_rules[ruleLocalLabel]() { - goto l280 - } - goto l278 - l280: - position, tokenIndex = position278, tokenIndex278 - if !_rules[ruleSymbolName]() { - goto l276 - } - } - l278: - if buffer[position] != rune(':') { - goto l276 + position276 := position + if buffer[position] != rune('.') { + goto l275 } position++ - add(ruleLabel, position277) + add(ruleDot, position276) } return true - l276: - position, tokenIndex = position276, tokenIndex276 + l275: + position, tokenIndex = position275, tokenIndex275 return false }, - /* 21 SymbolName <- <(([a-z] / [A-Z] / '.' / '_') ([a-z] / [A-Z] / '.' / ([0-9] / [0-9]) / '$' / '_')*)> */ + /* 16 TCMarker <- <('[' 'T' 'C' ']')> */ + func() bool { + position277, tokenIndex277 := position, tokenIndex + { + position278 := position + if buffer[position] != rune('[') { + goto l277 + } + position++ + if buffer[position] != rune('T') { + goto l277 + } + position++ + if buffer[position] != rune('C') { + goto l277 + } + position++ + if buffer[position] != rune(']') { + goto l277 + } + position++ + add(ruleTCMarker, position278) + } + return true + l277: + position, tokenIndex = position277, tokenIndex277 + return false + }, + /* 17 EscapedChar <- <('\\' .)> */ + func() bool { + position279, tokenIndex279 := position, tokenIndex + { + position280 := position + if buffer[position] != rune('\\') { + goto l279 + } + position++ + if !matchDot() { + goto l279 + } + add(ruleEscapedChar, position280) + } + return true + l279: + position, tokenIndex = position279, tokenIndex279 + return false + }, + /* 18 WS <- <(' ' / '\t')+> */ func() bool { position281, tokenIndex281 := position, tokenIndex { position282 := position { - position283, tokenIndex283 := position, tokenIndex - if c := buffer[position]; c < rune('a') || c > rune('z') { - goto l284 - } - position++ - goto l283 - l284: - position, tokenIndex = position283, tokenIndex283 - if c := buffer[position]; c < rune('A') || c > rune('Z') { - goto l285 - } - position++ - goto l283 - l285: - position, tokenIndex = position283, tokenIndex283 - if buffer[position] != rune('.') { + position285, tokenIndex285 := position, tokenIndex + if buffer[position] != rune(' ') { goto l286 } position++ - goto l283 + goto l285 l286: - position, tokenIndex = position283, tokenIndex283 - if buffer[position] != rune('_') { + position, tokenIndex = position285, tokenIndex285 + if buffer[position] != rune('\t') { goto l281 } position++ } + l285: l283: - l287: { - position288, tokenIndex288 := position, tokenIndex + position284, tokenIndex284 := position, tokenIndex { - position289, tokenIndex289 := position, tokenIndex - if c := buffer[position]; c < rune('a') || c > rune('z') { - goto l290 - } - position++ - goto l289 - l290: - position, tokenIndex = position289, tokenIndex289 - if c := buffer[position]; c < rune('A') || c > rune('Z') { - goto l291 - } - position++ - goto l289 - l291: - position, tokenIndex = position289, tokenIndex289 - if buffer[position] != rune('.') { - goto l292 - } - position++ - goto l289 - l292: - position, tokenIndex = position289, tokenIndex289 - { - position294, tokenIndex294 := position, tokenIndex - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l295 - } - position++ - goto l294 - l295: - position, tokenIndex = position294, tokenIndex294 - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l293 - } - position++ - } - l294: - goto l289 - l293: - position, tokenIndex = position289, tokenIndex289 - if buffer[position] != rune('$') { - goto l296 - } - position++ - goto l289 - l296: - position, tokenIndex = position289, tokenIndex289 - if buffer[position] != rune('_') { + position287, tokenIndex287 := position, tokenIndex + if buffer[position] != rune(' ') { goto l288 } position++ + goto l287 + l288: + position, tokenIndex = position287, tokenIndex287 + if buffer[position] != rune('\t') { + goto l284 + } + position++ } - l289: - goto l287 - l288: - position, tokenIndex = position288, tokenIndex288 + l287: + goto l283 + l284: + position, tokenIndex = position284, tokenIndex284 } - add(ruleSymbolName, position282) + add(ruleWS, position282) } return true l281: position, tokenIndex = position281, tokenIndex281 return false }, - /* 22 LocalSymbol <- <('.' 'L' ([a-z] / [A-Z] / '.' / ([0-9] / [0-9]) / '$' / '_')+)> */ + /* 19 Comment <- <('#' (!'\n' .)*)> */ func() bool { - position297, tokenIndex297 := position, tokenIndex + position289, tokenIndex289 := position, tokenIndex { - position298 := position - if buffer[position] != rune('.') { - goto l297 + position290 := position + if buffer[position] != rune('#') { + goto l289 } position++ - if buffer[position] != rune('L') { - goto l297 + l291: + { + position292, tokenIndex292 := position, tokenIndex + { + position293, tokenIndex293 := position, tokenIndex + if buffer[position] != rune('\n') { + goto l293 + } + position++ + goto l292 + l293: + position, tokenIndex = position293, tokenIndex293 + } + if !matchDot() { + goto l292 + } + goto l291 + l292: + position, tokenIndex = position292, tokenIndex292 + } + add(ruleComment, position290) + } + return true + l289: + position, tokenIndex = position289, tokenIndex289 + return false + }, + /* 20 Label <- <((LocalSymbol / LocalLabel / SymbolName) ':')> */ + func() bool { + position294, tokenIndex294 := position, tokenIndex + { + position295 := position + { + position296, tokenIndex296 := position, tokenIndex + if !_rules[ruleLocalSymbol]() { + goto l297 + } + goto l296 + l297: + position, tokenIndex = position296, tokenIndex296 + if !_rules[ruleLocalLabel]() { + goto l298 + } + goto l296 + l298: + position, tokenIndex = position296, tokenIndex296 + if !_rules[ruleSymbolName]() { + goto l294 + } + } + l296: + if buffer[position] != rune(':') { + goto l294 } position++ + add(ruleLabel, position295) + } + return true + l294: + position, tokenIndex = position294, tokenIndex294 + return false + }, + /* 21 SymbolName <- <(([a-z] / [A-Z] / '.' / '_') ([a-z] / [A-Z] / '.' / ([0-9] / [0-9]) / '$' / '_')*)> */ + func() bool { + position299, tokenIndex299 := position, tokenIndex + { + position300 := position { position301, tokenIndex301 := position, tokenIndex if c := buffer[position]; c < rune('a') || c > rune('z') { @@ -2517,640 +2565,592 @@ func (p *Asm) Init() { position++ goto l301 l304: - position, tokenIndex = position301, tokenIndex301 - { - position306, tokenIndex306 := position, tokenIndex - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l307 - } - position++ - goto l306 - l307: - position, tokenIndex = position306, tokenIndex306 - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l305 - } - position++ - } - l306: - goto l301 - l305: - position, tokenIndex = position301, tokenIndex301 - if buffer[position] != rune('$') { - goto l308 - } - position++ - goto l301 - l308: position, tokenIndex = position301, tokenIndex301 if buffer[position] != rune('_') { - goto l297 + goto l299 } position++ } l301: - l299: + l305: { - position300, tokenIndex300 := position, tokenIndex + position306, tokenIndex306 := position, tokenIndex { - position309, tokenIndex309 := position, tokenIndex + position307, tokenIndex307 := position, tokenIndex if c := buffer[position]; c < rune('a') || c > rune('z') { + goto l308 + } + position++ + goto l307 + l308: + position, tokenIndex = position307, tokenIndex307 + if c := buffer[position]; c < rune('A') || c > rune('Z') { + goto l309 + } + position++ + goto l307 + l309: + position, tokenIndex = position307, tokenIndex307 + if buffer[position] != rune('.') { goto l310 } position++ - goto l309 + goto l307 l310: - position, tokenIndex = position309, tokenIndex309 - if c := buffer[position]; c < rune('A') || c > rune('Z') { - goto l311 - } - position++ - goto l309 - l311: - position, tokenIndex = position309, tokenIndex309 - if buffer[position] != rune('.') { - goto l312 - } - position++ - goto l309 - l312: - position, tokenIndex = position309, tokenIndex309 + position, tokenIndex = position307, tokenIndex307 { - position314, tokenIndex314 := position, tokenIndex - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l315 - } - position++ - goto l314 - l315: - position, tokenIndex = position314, tokenIndex314 + position312, tokenIndex312 := position, tokenIndex if c := buffer[position]; c < rune('0') || c > rune('9') { goto l313 } position++ + goto l312 + l313: + position, tokenIndex = position312, tokenIndex312 + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l311 + } + position++ } - l314: - goto l309 - l313: - position, tokenIndex = position309, tokenIndex309 + l312: + goto l307 + l311: + position, tokenIndex = position307, tokenIndex307 if buffer[position] != rune('$') { - goto l316 + goto l314 } position++ - goto l309 - l316: - position, tokenIndex = position309, tokenIndex309 + goto l307 + l314: + position, tokenIndex = position307, tokenIndex307 if buffer[position] != rune('_') { - goto l300 + goto l306 } position++ } - l309: - goto l299 - l300: - position, tokenIndex = position300, tokenIndex300 + l307: + goto l305 + l306: + position, tokenIndex = position306, tokenIndex306 } - add(ruleLocalSymbol, position298) + add(ruleSymbolName, position300) } return true - l297: - position, tokenIndex = position297, tokenIndex297 + l299: + position, tokenIndex = position299, tokenIndex299 return false }, - /* 23 LocalLabel <- <([0-9] ([0-9] / '$')*)> */ + /* 22 LocalSymbol <- <('.' 'L' ([a-z] / [A-Z] / '.' / ([0-9] / [0-9]) / '$' / '_')+)> */ func() bool { - position317, tokenIndex317 := position, tokenIndex + position315, tokenIndex315 := position, tokenIndex { - position318 := position - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l317 + position316 := position + if buffer[position] != rune('.') { + goto l315 + } + position++ + if buffer[position] != rune('L') { + goto l315 } position++ - l319: { - position320, tokenIndex320 := position, tokenIndex - { - position321, tokenIndex321 := position, tokenIndex - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l322 - } - position++ - goto l321 - l322: - position, tokenIndex = position321, tokenIndex321 - if buffer[position] != rune('$') { - goto l320 - } - position++ + position319, tokenIndex319 := position, tokenIndex + if c := buffer[position]; c < rune('a') || c > rune('z') { + goto l320 } - l321: + position++ goto l319 l320: - position, tokenIndex = position320, tokenIndex320 + position, tokenIndex = position319, tokenIndex319 + if c := buffer[position]; c < rune('A') || c > rune('Z') { + goto l321 + } + position++ + goto l319 + l321: + position, tokenIndex = position319, tokenIndex319 + if buffer[position] != rune('.') { + goto l322 + } + position++ + goto l319 + l322: + position, tokenIndex = position319, tokenIndex319 + { + position324, tokenIndex324 := position, tokenIndex + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l325 + } + position++ + goto l324 + l325: + position, tokenIndex = position324, tokenIndex324 + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l323 + } + position++ + } + l324: + goto l319 + l323: + position, tokenIndex = position319, tokenIndex319 + if buffer[position] != rune('$') { + goto l326 + } + position++ + goto l319 + l326: + position, tokenIndex = position319, tokenIndex319 + if buffer[position] != rune('_') { + goto l315 + } + position++ } - add(ruleLocalLabel, position318) - } - return true - l317: - position, tokenIndex = position317, tokenIndex317 - return false - }, - /* 24 LocalLabelRef <- <([0-9] ([0-9] / '$')* ('b' / 'f'))> */ - func() bool { - position323, tokenIndex323 := position, tokenIndex - { - position324 := position - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l323 - } - position++ - l325: + l319: + l317: { - position326, tokenIndex326 := position, tokenIndex + position318, tokenIndex318 := position, tokenIndex { position327, tokenIndex327 := position, tokenIndex - if c := buffer[position]; c < rune('0') || c > rune('9') { + if c := buffer[position]; c < rune('a') || c > rune('z') { goto l328 } position++ goto l327 l328: + position, tokenIndex = position327, tokenIndex327 + if c := buffer[position]; c < rune('A') || c > rune('Z') { + goto l329 + } + position++ + goto l327 + l329: + position, tokenIndex = position327, tokenIndex327 + if buffer[position] != rune('.') { + goto l330 + } + position++ + goto l327 + l330: + position, tokenIndex = position327, tokenIndex327 + { + position332, tokenIndex332 := position, tokenIndex + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l333 + } + position++ + goto l332 + l333: + position, tokenIndex = position332, tokenIndex332 + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l331 + } + position++ + } + l332: + goto l327 + l331: position, tokenIndex = position327, tokenIndex327 if buffer[position] != rune('$') { - goto l326 + goto l334 + } + position++ + goto l327 + l334: + position, tokenIndex = position327, tokenIndex327 + if buffer[position] != rune('_') { + goto l318 } position++ } l327: - goto l325 - l326: - position, tokenIndex = position326, tokenIndex326 + goto l317 + l318: + position, tokenIndex = position318, tokenIndex318 } - { - position329, tokenIndex329 := position, tokenIndex - if buffer[position] != rune('b') { - goto l330 - } - position++ - goto l329 - l330: - position, tokenIndex = position329, tokenIndex329 - if buffer[position] != rune('f') { - goto l323 - } - position++ - } - l329: - add(ruleLocalLabelRef, position324) + add(ruleLocalSymbol, position316) } return true - l323: - position, tokenIndex = position323, tokenIndex323 + l315: + position, tokenIndex = position315, tokenIndex315 return false }, - /* 25 Instruction <- <(InstructionName (WS InstructionArg (WS? ',' WS? InstructionArg)*)?)> */ + /* 23 LocalLabel <- <([0-9] ([0-9] / '$')*)> */ func() bool { - position331, tokenIndex331 := position, tokenIndex + position335, tokenIndex335 := position, tokenIndex { - position332 := position - if !_rules[ruleInstructionName]() { - goto l331 + position336 := position + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l335 } + position++ + l337: { - position333, tokenIndex333 := position, tokenIndex - if !_rules[ruleWS]() { - goto l333 - } - if !_rules[ruleInstructionArg]() { - goto l333 - } - l335: + position338, tokenIndex338 := position, tokenIndex { - position336, tokenIndex336 := position, tokenIndex - { - position337, tokenIndex337 := position, tokenIndex - if !_rules[ruleWS]() { - goto l337 - } - goto l338 - l337: - position, tokenIndex = position337, tokenIndex337 - } - l338: - if buffer[position] != rune(',') { - goto l336 + position339, tokenIndex339 := position, tokenIndex + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l340 } position++ - { - position339, tokenIndex339 := position, tokenIndex - if !_rules[ruleWS]() { - goto l339 - } - goto l340 - l339: - position, tokenIndex = position339, tokenIndex339 - } + goto l339 l340: - if !_rules[ruleInstructionArg]() { - goto l336 + position, tokenIndex = position339, tokenIndex339 + if buffer[position] != rune('$') { + goto l338 } - goto l335 - l336: - position, tokenIndex = position336, tokenIndex336 + position++ } - goto l334 - l333: - position, tokenIndex = position333, tokenIndex333 + l339: + goto l337 + l338: + position, tokenIndex = position338, tokenIndex338 } - l334: - add(ruleInstruction, position332) + add(ruleLocalLabel, position336) } return true - l331: - position, tokenIndex = position331, tokenIndex331 + l335: + position, tokenIndex = position335, tokenIndex335 return false }, - /* 26 InstructionName <- <(([a-z] / [A-Z]) ([a-z] / [A-Z] / ([0-9] / [0-9]))* ('.' / '+' / '-')?)> */ + /* 24 LocalLabelRef <- <([0-9] ([0-9] / '$')* ('b' / 'f'))> */ func() bool { position341, tokenIndex341 := position, tokenIndex { position342 := position + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l341 + } + position++ + l343: { - position343, tokenIndex343 := position, tokenIndex - if c := buffer[position]; c < rune('a') || c > rune('z') { - goto l344 + position344, tokenIndex344 := position, tokenIndex + { + position345, tokenIndex345 := position, tokenIndex + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l346 + } + position++ + goto l345 + l346: + position, tokenIndex = position345, tokenIndex345 + if buffer[position] != rune('$') { + goto l344 + } + position++ } - position++ + l345: goto l343 l344: - position, tokenIndex = position343, tokenIndex343 - if c := buffer[position]; c < rune('A') || c > rune('Z') { + position, tokenIndex = position344, tokenIndex344 + } + { + position347, tokenIndex347 := position, tokenIndex + if buffer[position] != rune('b') { + goto l348 + } + position++ + goto l347 + l348: + position, tokenIndex = position347, tokenIndex347 + if buffer[position] != rune('f') { goto l341 } position++ } - l343: - l345: - { - position346, tokenIndex346 := position, tokenIndex - { - position347, tokenIndex347 := position, tokenIndex - if c := buffer[position]; c < rune('a') || c > rune('z') { - goto l348 - } - position++ - goto l347 - l348: - position, tokenIndex = position347, tokenIndex347 - if c := buffer[position]; c < rune('A') || c > rune('Z') { - goto l349 - } - position++ - goto l347 - l349: - position, tokenIndex = position347, tokenIndex347 - { - position350, tokenIndex350 := position, tokenIndex - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l351 - } - position++ - goto l350 - l351: - position, tokenIndex = position350, tokenIndex350 - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l346 - } - position++ - } - l350: - } - l347: - goto l345 - l346: - position, tokenIndex = position346, tokenIndex346 - } - { - position352, tokenIndex352 := position, tokenIndex - { - position354, tokenIndex354 := position, tokenIndex - if buffer[position] != rune('.') { - goto l355 - } - position++ - goto l354 - l355: - position, tokenIndex = position354, tokenIndex354 - if buffer[position] != rune('+') { - goto l356 - } - position++ - goto l354 - l356: - position, tokenIndex = position354, tokenIndex354 - if buffer[position] != rune('-') { - goto l352 - } - position++ - } - l354: - goto l353 - l352: - position, tokenIndex = position352, tokenIndex352 - } - l353: - add(ruleInstructionName, position342) + l347: + add(ruleLocalLabelRef, position342) } return true l341: position, tokenIndex = position341, tokenIndex341 return false }, - /* 27 InstructionArg <- <(IndirectionIndicator? (RegisterOrConstant / LocalLabelRef / TOCRefHigh / TOCRefLow / MemoryRef) AVX512Token*)> */ + /* 25 Instruction <- <(InstructionName (WS InstructionArg (WS? ',' WS? InstructionArg)*)?)> */ func() bool { - position357, tokenIndex357 := position, tokenIndex + position349, tokenIndex349 := position, tokenIndex { - position358 := position - { - position359, tokenIndex359 := position, tokenIndex - if !_rules[ruleIndirectionIndicator]() { - goto l359 - } - goto l360 - l359: - position, tokenIndex = position359, tokenIndex359 + position350 := position + if !_rules[ruleInstructionName]() { + goto l349 } - l360: + { + position351, tokenIndex351 := position, tokenIndex + if !_rules[ruleWS]() { + goto l351 + } + if !_rules[ruleInstructionArg]() { + goto l351 + } + l353: + { + position354, tokenIndex354 := position, tokenIndex + { + position355, tokenIndex355 := position, tokenIndex + if !_rules[ruleWS]() { + goto l355 + } + goto l356 + l355: + position, tokenIndex = position355, tokenIndex355 + } + l356: + if buffer[position] != rune(',') { + goto l354 + } + position++ + { + position357, tokenIndex357 := position, tokenIndex + if !_rules[ruleWS]() { + goto l357 + } + goto l358 + l357: + position, tokenIndex = position357, tokenIndex357 + } + l358: + if !_rules[ruleInstructionArg]() { + goto l354 + } + goto l353 + l354: + position, tokenIndex = position354, tokenIndex354 + } + goto l352 + l351: + position, tokenIndex = position351, tokenIndex351 + } + l352: + add(ruleInstruction, position350) + } + return true + l349: + position, tokenIndex = position349, tokenIndex349 + return false + }, + /* 26 InstructionName <- <(([a-z] / [A-Z]) ([a-z] / [A-Z] / ([0-9] / [0-9]))* ('.' / '+' / '-')?)> */ + func() bool { + position359, tokenIndex359 := position, tokenIndex + { + position360 := position { position361, tokenIndex361 := position, tokenIndex - if !_rules[ruleRegisterOrConstant]() { + if c := buffer[position]; c < rune('a') || c > rune('z') { goto l362 } + position++ goto l361 l362: position, tokenIndex = position361, tokenIndex361 - if !_rules[ruleLocalLabelRef]() { - goto l363 - } - goto l361 - l363: - position, tokenIndex = position361, tokenIndex361 - if !_rules[ruleTOCRefHigh]() { - goto l364 - } - goto l361 - l364: - position, tokenIndex = position361, tokenIndex361 - if !_rules[ruleTOCRefLow]() { - goto l365 - } - goto l361 - l365: - position, tokenIndex = position361, tokenIndex361 - if !_rules[ruleMemoryRef]() { - goto l357 + if c := buffer[position]; c < rune('A') || c > rune('Z') { + goto l359 } + position++ } l361: - l366: + l363: { - position367, tokenIndex367 := position, tokenIndex - if !_rules[ruleAVX512Token]() { - goto l367 + position364, tokenIndex364 := position, tokenIndex + { + position365, tokenIndex365 := position, tokenIndex + if c := buffer[position]; c < rune('a') || c > rune('z') { + goto l366 + } + position++ + goto l365 + l366: + position, tokenIndex = position365, tokenIndex365 + if c := buffer[position]; c < rune('A') || c > rune('Z') { + goto l367 + } + position++ + goto l365 + l367: + position, tokenIndex = position365, tokenIndex365 + { + position368, tokenIndex368 := position, tokenIndex + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l369 + } + position++ + goto l368 + l369: + position, tokenIndex = position368, tokenIndex368 + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l364 + } + position++ + } + l368: } - goto l366 - l367: - position, tokenIndex = position367, tokenIndex367 + l365: + goto l363 + l364: + position, tokenIndex = position364, tokenIndex364 } - add(ruleInstructionArg, position358) - } - return true - l357: - position, tokenIndex = position357, tokenIndex357 - return false - }, - /* 28 AVX512Token <- <(WS? '{' '%'? ([0-9] / [a-z])* '}')> */ - func() bool { - position368, tokenIndex368 := position, tokenIndex - { - position369 := position { position370, tokenIndex370 := position, tokenIndex - if !_rules[ruleWS]() { - goto l370 + { + position372, tokenIndex372 := position, tokenIndex + if buffer[position] != rune('.') { + goto l373 + } + position++ + goto l372 + l373: + position, tokenIndex = position372, tokenIndex372 + if buffer[position] != rune('+') { + goto l374 + } + position++ + goto l372 + l374: + position, tokenIndex = position372, tokenIndex372 + if buffer[position] != rune('-') { + goto l370 + } + position++ } + l372: goto l371 l370: position, tokenIndex = position370, tokenIndex370 } l371: - if buffer[position] != rune('{') { - goto l368 - } - position++ - { - position372, tokenIndex372 := position, tokenIndex - if buffer[position] != rune('%') { - goto l372 - } - position++ - goto l373 - l372: - position, tokenIndex = position372, tokenIndex372 - } - l373: - l374: - { - position375, tokenIndex375 := position, tokenIndex - { - position376, tokenIndex376 := position, tokenIndex - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l377 - } - position++ - goto l376 - l377: - position, tokenIndex = position376, tokenIndex376 - if c := buffer[position]; c < rune('a') || c > rune('z') { - goto l375 - } - position++ - } - l376: - goto l374 - l375: - position, tokenIndex = position375, tokenIndex375 - } - if buffer[position] != rune('}') { - goto l368 - } - position++ - add(ruleAVX512Token, position369) + add(ruleInstructionName, position360) } return true - l368: - position, tokenIndex = position368, tokenIndex368 + l359: + position, tokenIndex = position359, tokenIndex359 + return false + }, + /* 27 InstructionArg <- <(IndirectionIndicator? (RegisterOrConstant / LocalLabelRef / TOCRefHigh / TOCRefLow / MemoryRef) AVX512Token*)> */ + func() bool { + position375, tokenIndex375 := position, tokenIndex + { + position376 := position + { + position377, tokenIndex377 := position, tokenIndex + if !_rules[ruleIndirectionIndicator]() { + goto l377 + } + goto l378 + l377: + position, tokenIndex = position377, tokenIndex377 + } + l378: + { + position379, tokenIndex379 := position, tokenIndex + if !_rules[ruleRegisterOrConstant]() { + goto l380 + } + goto l379 + l380: + position, tokenIndex = position379, tokenIndex379 + if !_rules[ruleLocalLabelRef]() { + goto l381 + } + goto l379 + l381: + position, tokenIndex = position379, tokenIndex379 + if !_rules[ruleTOCRefHigh]() { + goto l382 + } + goto l379 + l382: + position, tokenIndex = position379, tokenIndex379 + if !_rules[ruleTOCRefLow]() { + goto l383 + } + goto l379 + l383: + position, tokenIndex = position379, tokenIndex379 + if !_rules[ruleMemoryRef]() { + goto l375 + } + } + l379: + l384: + { + position385, tokenIndex385 := position, tokenIndex + if !_rules[ruleAVX512Token]() { + goto l385 + } + goto l384 + l385: + position, tokenIndex = position385, tokenIndex385 + } + add(ruleInstructionArg, position376) + } + return true + l375: + position, tokenIndex = position375, tokenIndex375 + return false + }, + /* 28 AVX512Token <- <(WS? '{' '%'? ([0-9] / [a-z])* '}')> */ + func() bool { + position386, tokenIndex386 := position, tokenIndex + { + position387 := position + { + position388, tokenIndex388 := position, tokenIndex + if !_rules[ruleWS]() { + goto l388 + } + goto l389 + l388: + position, tokenIndex = position388, tokenIndex388 + } + l389: + if buffer[position] != rune('{') { + goto l386 + } + position++ + { + position390, tokenIndex390 := position, tokenIndex + if buffer[position] != rune('%') { + goto l390 + } + position++ + goto l391 + l390: + position, tokenIndex = position390, tokenIndex390 + } + l391: + l392: + { + position393, tokenIndex393 := position, tokenIndex + { + position394, tokenIndex394 := position, tokenIndex + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l395 + } + position++ + goto l394 + l395: + position, tokenIndex = position394, tokenIndex394 + if c := buffer[position]; c < rune('a') || c > rune('z') { + goto l393 + } + position++ + } + l394: + goto l392 + l393: + position, tokenIndex = position393, tokenIndex393 + } + if buffer[position] != rune('}') { + goto l386 + } + position++ + add(ruleAVX512Token, position387) + } + return true + l386: + position, tokenIndex = position386, tokenIndex386 return false }, /* 29 TOCRefHigh <- <('.' 'T' 'O' 'C' '.' '-' (('0' 'b') / ('.' 'L' ([a-z] / [A-Z] / '_' / [0-9])+)) ('@' ('h' / 'H') ('a' / 'A')))> */ - func() bool { - position378, tokenIndex378 := position, tokenIndex - { - position379 := position - if buffer[position] != rune('.') { - goto l378 - } - position++ - if buffer[position] != rune('T') { - goto l378 - } - position++ - if buffer[position] != rune('O') { - goto l378 - } - position++ - if buffer[position] != rune('C') { - goto l378 - } - position++ - if buffer[position] != rune('.') { - goto l378 - } - position++ - if buffer[position] != rune('-') { - goto l378 - } - position++ - { - position380, tokenIndex380 := position, tokenIndex - if buffer[position] != rune('0') { - goto l381 - } - position++ - if buffer[position] != rune('b') { - goto l381 - } - position++ - goto l380 - l381: - position, tokenIndex = position380, tokenIndex380 - if buffer[position] != rune('.') { - goto l378 - } - position++ - if buffer[position] != rune('L') { - goto l378 - } - position++ - { - position384, tokenIndex384 := position, tokenIndex - if c := buffer[position]; c < rune('a') || c > rune('z') { - goto l385 - } - position++ - goto l384 - l385: - position, tokenIndex = position384, tokenIndex384 - if c := buffer[position]; c < rune('A') || c > rune('Z') { - goto l386 - } - position++ - goto l384 - l386: - position, tokenIndex = position384, tokenIndex384 - if buffer[position] != rune('_') { - goto l387 - } - position++ - goto l384 - l387: - position, tokenIndex = position384, tokenIndex384 - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l378 - } - position++ - } - l384: - l382: - { - position383, tokenIndex383 := position, tokenIndex - { - position388, tokenIndex388 := position, tokenIndex - if c := buffer[position]; c < rune('a') || c > rune('z') { - goto l389 - } - position++ - goto l388 - l389: - position, tokenIndex = position388, tokenIndex388 - if c := buffer[position]; c < rune('A') || c > rune('Z') { - goto l390 - } - position++ - goto l388 - l390: - position, tokenIndex = position388, tokenIndex388 - if buffer[position] != rune('_') { - goto l391 - } - position++ - goto l388 - l391: - position, tokenIndex = position388, tokenIndex388 - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l383 - } - position++ - } - l388: - goto l382 - l383: - position, tokenIndex = position383, tokenIndex383 - } - } - l380: - if buffer[position] != rune('@') { - goto l378 - } - position++ - { - position392, tokenIndex392 := position, tokenIndex - if buffer[position] != rune('h') { - goto l393 - } - position++ - goto l392 - l393: - position, tokenIndex = position392, tokenIndex392 - if buffer[position] != rune('H') { - goto l378 - } - position++ - } - l392: - { - position394, tokenIndex394 := position, tokenIndex - if buffer[position] != rune('a') { - goto l395 - } - position++ - goto l394 - l395: - position, tokenIndex = position394, tokenIndex394 - if buffer[position] != rune('A') { - goto l378 - } - position++ - } - l394: - add(ruleTOCRefHigh, position379) - } - return true - l378: - position, tokenIndex = position378, tokenIndex378 - return false - }, - /* 30 TOCRefLow <- <('.' 'T' 'O' 'C' '.' '-' (('0' 'b') / ('.' 'L' ([a-z] / [A-Z] / '_' / [0-9])+)) ('@' ('l' / 'L')))> */ func() bool { position396, tokenIndex396 := position, tokenIndex { @@ -3273,494 +3273,538 @@ func (p *Asm) Init() { position++ { position410, tokenIndex410 := position, tokenIndex - if buffer[position] != rune('l') { + if buffer[position] != rune('h') { goto l411 } position++ goto l410 l411: position, tokenIndex = position410, tokenIndex410 - if buffer[position] != rune('L') { + if buffer[position] != rune('H') { goto l396 } position++ } l410: - add(ruleTOCRefLow, position397) + { + position412, tokenIndex412 := position, tokenIndex + if buffer[position] != rune('a') { + goto l413 + } + position++ + goto l412 + l413: + position, tokenIndex = position412, tokenIndex412 + if buffer[position] != rune('A') { + goto l396 + } + position++ + } + l412: + add(ruleTOCRefHigh, position397) } return true l396: position, tokenIndex = position396, tokenIndex396 return false }, - /* 31 IndirectionIndicator <- <'*'> */ - func() bool { - position412, tokenIndex412 := position, tokenIndex - { - position413 := position - if buffer[position] != rune('*') { - goto l412 - } - position++ - add(ruleIndirectionIndicator, position413) - } - return true - l412: - position, tokenIndex = position412, tokenIndex412 - return false - }, - /* 32 RegisterOrConstant <- <((('%' ([a-z] / [A-Z]) ([a-z] / [A-Z] / ([0-9] / [0-9]))*) / ('$'? ((Offset Offset) / Offset))) !('f' / 'b' / ':' / '(' / '+' / '-'))> */ + /* 30 TOCRefLow <- <('.' 'T' 'O' 'C' '.' '-' (('0' 'b') / ('.' 'L' ([a-z] / [A-Z] / '_' / [0-9])+)) ('@' ('l' / 'L')))> */ func() bool { position414, tokenIndex414 := position, tokenIndex { position415 := position + if buffer[position] != rune('.') { + goto l414 + } + position++ + if buffer[position] != rune('T') { + goto l414 + } + position++ + if buffer[position] != rune('O') { + goto l414 + } + position++ + if buffer[position] != rune('C') { + goto l414 + } + position++ + if buffer[position] != rune('.') { + goto l414 + } + position++ + if buffer[position] != rune('-') { + goto l414 + } + position++ { position416, tokenIndex416 := position, tokenIndex - if buffer[position] != rune('%') { + if buffer[position] != rune('0') { goto l417 } position++ - { - position418, tokenIndex418 := position, tokenIndex - if c := buffer[position]; c < rune('a') || c > rune('z') { - goto l419 - } - position++ - goto l418 - l419: - position, tokenIndex = position418, tokenIndex418 - if c := buffer[position]; c < rune('A') || c > rune('Z') { - goto l417 - } - position++ - } - l418: - l420: - { - position421, tokenIndex421 := position, tokenIndex - { - position422, tokenIndex422 := position, tokenIndex - if c := buffer[position]; c < rune('a') || c > rune('z') { - goto l423 - } - position++ - goto l422 - l423: - position, tokenIndex = position422, tokenIndex422 - if c := buffer[position]; c < rune('A') || c > rune('Z') { - goto l424 - } - position++ - goto l422 - l424: - position, tokenIndex = position422, tokenIndex422 - { - position425, tokenIndex425 := position, tokenIndex - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l426 - } - position++ - goto l425 - l426: - position, tokenIndex = position425, tokenIndex425 - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l421 - } - position++ - } - l425: - } - l422: - goto l420 - l421: - position, tokenIndex = position421, tokenIndex421 + if buffer[position] != rune('b') { + goto l417 } + position++ goto l416 l417: position, tokenIndex = position416, tokenIndex416 + if buffer[position] != rune('.') { + goto l414 + } + position++ + if buffer[position] != rune('L') { + goto l414 + } + position++ { - position427, tokenIndex427 := position, tokenIndex - if buffer[position] != rune('$') { - goto l427 + position420, tokenIndex420 := position, tokenIndex + if c := buffer[position]; c < rune('a') || c > rune('z') { + goto l421 } position++ - goto l428 - l427: - position, tokenIndex = position427, tokenIndex427 - } - l428: - { - position429, tokenIndex429 := position, tokenIndex - if !_rules[ruleOffset]() { - goto l430 + goto l420 + l421: + position, tokenIndex = position420, tokenIndex420 + if c := buffer[position]; c < rune('A') || c > rune('Z') { + goto l422 } - if !_rules[ruleOffset]() { - goto l430 + position++ + goto l420 + l422: + position, tokenIndex = position420, tokenIndex420 + if buffer[position] != rune('_') { + goto l423 } - goto l429 - l430: - position, tokenIndex = position429, tokenIndex429 - if !_rules[ruleOffset]() { + position++ + goto l420 + l423: + position, tokenIndex = position420, tokenIndex420 + if c := buffer[position]; c < rune('0') || c > rune('9') { goto l414 } + position++ + } + l420: + l418: + { + position419, tokenIndex419 := position, tokenIndex + { + position424, tokenIndex424 := position, tokenIndex + if c := buffer[position]; c < rune('a') || c > rune('z') { + goto l425 + } + position++ + goto l424 + l425: + position, tokenIndex = position424, tokenIndex424 + if c := buffer[position]; c < rune('A') || c > rune('Z') { + goto l426 + } + position++ + goto l424 + l426: + position, tokenIndex = position424, tokenIndex424 + if buffer[position] != rune('_') { + goto l427 + } + position++ + goto l424 + l427: + position, tokenIndex = position424, tokenIndex424 + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l419 + } + position++ + } + l424: + goto l418 + l419: + position, tokenIndex = position419, tokenIndex419 } - l429: } l416: - { - position431, tokenIndex431 := position, tokenIndex - { - position432, tokenIndex432 := position, tokenIndex - if buffer[position] != rune('f') { - goto l433 - } - position++ - goto l432 - l433: - position, tokenIndex = position432, tokenIndex432 - if buffer[position] != rune('b') { - goto l434 - } - position++ - goto l432 - l434: - position, tokenIndex = position432, tokenIndex432 - if buffer[position] != rune(':') { - goto l435 - } - position++ - goto l432 - l435: - position, tokenIndex = position432, tokenIndex432 - if buffer[position] != rune('(') { - goto l436 - } - position++ - goto l432 - l436: - position, tokenIndex = position432, tokenIndex432 - if buffer[position] != rune('+') { - goto l437 - } - position++ - goto l432 - l437: - position, tokenIndex = position432, tokenIndex432 - if buffer[position] != rune('-') { - goto l431 - } - position++ - } - l432: + if buffer[position] != rune('@') { goto l414 - l431: - position, tokenIndex = position431, tokenIndex431 } - add(ruleRegisterOrConstant, position415) + position++ + { + position428, tokenIndex428 := position, tokenIndex + if buffer[position] != rune('l') { + goto l429 + } + position++ + goto l428 + l429: + position, tokenIndex = position428, tokenIndex428 + if buffer[position] != rune('L') { + goto l414 + } + position++ + } + l428: + add(ruleTOCRefLow, position415) } return true l414: position, tokenIndex = position414, tokenIndex414 return false }, - /* 33 MemoryRef <- <((SymbolRef BaseIndexScale) / SymbolRef / (Offset* BaseIndexScale) / (SegmentRegister Offset BaseIndexScale) / (SegmentRegister BaseIndexScale) / (SegmentRegister Offset) / BaseIndexScale)> */ + /* 31 IndirectionIndicator <- <'*'> */ func() bool { - position438, tokenIndex438 := position, tokenIndex + position430, tokenIndex430 := position, tokenIndex { - position439 := position + position431 := position + if buffer[position] != rune('*') { + goto l430 + } + position++ + add(ruleIndirectionIndicator, position431) + } + return true + l430: + position, tokenIndex = position430, tokenIndex430 + return false + }, + /* 32 RegisterOrConstant <- <((('%' ([a-z] / [A-Z]) ([a-z] / [A-Z] / ([0-9] / [0-9]))*) / ('$'? ((Offset Offset) / Offset))) !('f' / 'b' / ':' / '(' / '+' / '-'))> */ + func() bool { + position432, tokenIndex432 := position, tokenIndex + { + position433 := position { - position440, tokenIndex440 := position, tokenIndex - if !_rules[ruleSymbolRef]() { - goto l441 + position434, tokenIndex434 := position, tokenIndex + if buffer[position] != rune('%') { + goto l435 } - if !_rules[ruleBaseIndexScale]() { - goto l441 + position++ + { + position436, tokenIndex436 := position, tokenIndex + if c := buffer[position]; c < rune('a') || c > rune('z') { + goto l437 + } + position++ + goto l436 + l437: + position, tokenIndex = position436, tokenIndex436 + if c := buffer[position]; c < rune('A') || c > rune('Z') { + goto l435 + } + position++ } - goto l440 - l441: - position, tokenIndex = position440, tokenIndex440 - if !_rules[ruleSymbolRef]() { - goto l442 + l436: + l438: + { + position439, tokenIndex439 := position, tokenIndex + { + position440, tokenIndex440 := position, tokenIndex + if c := buffer[position]; c < rune('a') || c > rune('z') { + goto l441 + } + position++ + goto l440 + l441: + position, tokenIndex = position440, tokenIndex440 + if c := buffer[position]; c < rune('A') || c > rune('Z') { + goto l442 + } + position++ + goto l440 + l442: + position, tokenIndex = position440, tokenIndex440 + { + position443, tokenIndex443 := position, tokenIndex + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l444 + } + position++ + goto l443 + l444: + position, tokenIndex = position443, tokenIndex443 + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l439 + } + position++ + } + l443: + } + l440: + goto l438 + l439: + position, tokenIndex = position439, tokenIndex439 } - goto l440 - l442: - position, tokenIndex = position440, tokenIndex440 - l444: + goto l434 + l435: + position, tokenIndex = position434, tokenIndex434 { position445, tokenIndex445 := position, tokenIndex - if !_rules[ruleOffset]() { + if buffer[position] != rune('$') { goto l445 } - goto l444 + position++ + goto l446 l445: position, tokenIndex = position445, tokenIndex445 } - if !_rules[ruleBaseIndexScale]() { - goto l443 - } - goto l440 - l443: - position, tokenIndex = position440, tokenIndex440 - if !_rules[ruleSegmentRegister]() { - goto l446 - } - if !_rules[ruleOffset]() { - goto l446 - } - if !_rules[ruleBaseIndexScale]() { - goto l446 - } - goto l440 l446: - position, tokenIndex = position440, tokenIndex440 - if !_rules[ruleSegmentRegister]() { + { + position447, tokenIndex447 := position, tokenIndex + if !_rules[ruleOffset]() { + goto l448 + } + if !_rules[ruleOffset]() { + goto l448 + } goto l447 + l448: + position, tokenIndex = position447, tokenIndex447 + if !_rules[ruleOffset]() { + goto l432 + } } - if !_rules[ruleBaseIndexScale]() { - goto l447 - } - goto l440 l447: - position, tokenIndex = position440, tokenIndex440 - if !_rules[ruleSegmentRegister]() { - goto l448 - } - if !_rules[ruleOffset]() { - goto l448 - } - goto l440 - l448: - position, tokenIndex = position440, tokenIndex440 - if !_rules[ruleBaseIndexScale]() { - goto l438 - } } - l440: - add(ruleMemoryRef, position439) + l434: + { + position449, tokenIndex449 := position, tokenIndex + { + position450, tokenIndex450 := position, tokenIndex + if buffer[position] != rune('f') { + goto l451 + } + position++ + goto l450 + l451: + position, tokenIndex = position450, tokenIndex450 + if buffer[position] != rune('b') { + goto l452 + } + position++ + goto l450 + l452: + position, tokenIndex = position450, tokenIndex450 + if buffer[position] != rune(':') { + goto l453 + } + position++ + goto l450 + l453: + position, tokenIndex = position450, tokenIndex450 + if buffer[position] != rune('(') { + goto l454 + } + position++ + goto l450 + l454: + position, tokenIndex = position450, tokenIndex450 + if buffer[position] != rune('+') { + goto l455 + } + position++ + goto l450 + l455: + position, tokenIndex = position450, tokenIndex450 + if buffer[position] != rune('-') { + goto l449 + } + position++ + } + l450: + goto l432 + l449: + position, tokenIndex = position449, tokenIndex449 + } + add(ruleRegisterOrConstant, position433) } return true - l438: - position, tokenIndex = position438, tokenIndex438 + l432: + position, tokenIndex = position432, tokenIndex432 + return false + }, + /* 33 MemoryRef <- <((SymbolRef BaseIndexScale) / SymbolRef / (Offset* BaseIndexScale) / (SegmentRegister Offset BaseIndexScale) / (SegmentRegister BaseIndexScale) / (SegmentRegister Offset) / BaseIndexScale)> */ + func() bool { + position456, tokenIndex456 := position, tokenIndex + { + position457 := position + { + position458, tokenIndex458 := position, tokenIndex + if !_rules[ruleSymbolRef]() { + goto l459 + } + if !_rules[ruleBaseIndexScale]() { + goto l459 + } + goto l458 + l459: + position, tokenIndex = position458, tokenIndex458 + if !_rules[ruleSymbolRef]() { + goto l460 + } + goto l458 + l460: + position, tokenIndex = position458, tokenIndex458 + l462: + { + position463, tokenIndex463 := position, tokenIndex + if !_rules[ruleOffset]() { + goto l463 + } + goto l462 + l463: + position, tokenIndex = position463, tokenIndex463 + } + if !_rules[ruleBaseIndexScale]() { + goto l461 + } + goto l458 + l461: + position, tokenIndex = position458, tokenIndex458 + if !_rules[ruleSegmentRegister]() { + goto l464 + } + if !_rules[ruleOffset]() { + goto l464 + } + if !_rules[ruleBaseIndexScale]() { + goto l464 + } + goto l458 + l464: + position, tokenIndex = position458, tokenIndex458 + if !_rules[ruleSegmentRegister]() { + goto l465 + } + if !_rules[ruleBaseIndexScale]() { + goto l465 + } + goto l458 + l465: + position, tokenIndex = position458, tokenIndex458 + if !_rules[ruleSegmentRegister]() { + goto l466 + } + if !_rules[ruleOffset]() { + goto l466 + } + goto l458 + l466: + position, tokenIndex = position458, tokenIndex458 + if !_rules[ruleBaseIndexScale]() { + goto l456 + } + } + l458: + add(ruleMemoryRef, position457) + } + return true + l456: + position, tokenIndex = position456, tokenIndex456 return false }, /* 34 SymbolRef <- <((Offset* '+')? (LocalSymbol / SymbolName) Offset* ('@' Section Offset*)?)> */ func() bool { - position449, tokenIndex449 := position, tokenIndex + position467, tokenIndex467 := position, tokenIndex { - position450 := position - { - position451, tokenIndex451 := position, tokenIndex - l453: - { - position454, tokenIndex454 := position, tokenIndex - if !_rules[ruleOffset]() { - goto l454 - } - goto l453 - l454: - position, tokenIndex = position454, tokenIndex454 - } - if buffer[position] != rune('+') { - goto l451 - } - position++ - goto l452 - l451: - position, tokenIndex = position451, tokenIndex451 - } - l452: - { - position455, tokenIndex455 := position, tokenIndex - if !_rules[ruleLocalSymbol]() { - goto l456 - } - goto l455 - l456: - position, tokenIndex = position455, tokenIndex455 - if !_rules[ruleSymbolName]() { - goto l449 - } - } - l455: - l457: - { - position458, tokenIndex458 := position, tokenIndex - if !_rules[ruleOffset]() { - goto l458 - } - goto l457 - l458: - position, tokenIndex = position458, tokenIndex458 - } - { - position459, tokenIndex459 := position, tokenIndex - if buffer[position] != rune('@') { - goto l459 - } - position++ - if !_rules[ruleSection]() { - goto l459 - } - l461: - { - position462, tokenIndex462 := position, tokenIndex - if !_rules[ruleOffset]() { - goto l462 - } - goto l461 - l462: - position, tokenIndex = position462, tokenIndex462 - } - goto l460 - l459: - position, tokenIndex = position459, tokenIndex459 - } - l460: - add(ruleSymbolRef, position450) - } - return true - l449: - position, tokenIndex = position449, tokenIndex449 - return false - }, - /* 35 BaseIndexScale <- <('(' RegisterOrConstant? WS? (',' WS? RegisterOrConstant WS? (',' [0-9]+)?)? ')')> */ - func() bool { - position463, tokenIndex463 := position, tokenIndex - { - position464 := position - if buffer[position] != rune('(') { - goto l463 - } - position++ - { - position465, tokenIndex465 := position, tokenIndex - if !_rules[ruleRegisterOrConstant]() { - goto l465 - } - goto l466 - l465: - position, tokenIndex = position465, tokenIndex465 - } - l466: - { - position467, tokenIndex467 := position, tokenIndex - if !_rules[ruleWS]() { - goto l467 - } - goto l468 - l467: - position, tokenIndex = position467, tokenIndex467 - } - l468: + position468 := position { position469, tokenIndex469 := position, tokenIndex - if buffer[position] != rune(',') { + l471: + { + position472, tokenIndex472 := position, tokenIndex + if !_rules[ruleOffset]() { + goto l472 + } + goto l471 + l472: + position, tokenIndex = position472, tokenIndex472 + } + if buffer[position] != rune('+') { goto l469 } position++ - { - position471, tokenIndex471 := position, tokenIndex - if !_rules[ruleWS]() { - goto l471 - } - goto l472 - l471: - position, tokenIndex = position471, tokenIndex471 - } - l472: - if !_rules[ruleRegisterOrConstant]() { - goto l469 - } - { - position473, tokenIndex473 := position, tokenIndex - if !_rules[ruleWS]() { - goto l473 - } - goto l474 - l473: - position, tokenIndex = position473, tokenIndex473 - } - l474: - { - position475, tokenIndex475 := position, tokenIndex - if buffer[position] != rune(',') { - goto l475 - } - position++ - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l475 - } - position++ - l477: - { - position478, tokenIndex478 := position, tokenIndex - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l478 - } - position++ - goto l477 - l478: - position, tokenIndex = position478, tokenIndex478 - } - goto l476 - l475: - position, tokenIndex = position475, tokenIndex475 - } - l476: goto l470 l469: position, tokenIndex = position469, tokenIndex469 } l470: - if buffer[position] != rune(')') { - goto l463 + { + position473, tokenIndex473 := position, tokenIndex + if !_rules[ruleLocalSymbol]() { + goto l474 + } + goto l473 + l474: + position, tokenIndex = position473, tokenIndex473 + if !_rules[ruleSymbolName]() { + goto l467 + } + } + l473: + l475: + { + position476, tokenIndex476 := position, tokenIndex + if !_rules[ruleOffset]() { + goto l476 + } + goto l475 + l476: + position, tokenIndex = position476, tokenIndex476 + } + { + position477, tokenIndex477 := position, tokenIndex + if buffer[position] != rune('@') { + goto l477 + } + position++ + if !_rules[ruleSection]() { + goto l477 + } + l479: + { + position480, tokenIndex480 := position, tokenIndex + if !_rules[ruleOffset]() { + goto l480 + } + goto l479 + l480: + position, tokenIndex = position480, tokenIndex480 + } + goto l478 + l477: + position, tokenIndex = position477, tokenIndex477 + } + l478: + add(ruleSymbolRef, position468) + } + return true + l467: + position, tokenIndex = position467, tokenIndex467 + return false + }, + /* 35 BaseIndexScale <- <('(' RegisterOrConstant? WS? (',' WS? RegisterOrConstant WS? (',' [0-9]+)?)? ')')> */ + func() bool { + position481, tokenIndex481 := position, tokenIndex + { + position482 := position + if buffer[position] != rune('(') { + goto l481 } position++ - add(ruleBaseIndexScale, position464) - } - return true - l463: - position, tokenIndex = position463, tokenIndex463 - return false - }, - /* 36 Operator <- <('+' / '-')> */ - func() bool { - position479, tokenIndex479 := position, tokenIndex - { - position480 := position { - position481, tokenIndex481 := position, tokenIndex - if buffer[position] != rune('+') { - goto l482 + position483, tokenIndex483 := position, tokenIndex + if !_rules[ruleRegisterOrConstant]() { + goto l483 } - position++ - goto l481 - l482: - position, tokenIndex = position481, tokenIndex481 - if buffer[position] != rune('-') { - goto l479 - } - position++ + goto l484 + l483: + position, tokenIndex = position483, tokenIndex483 } - l481: - add(ruleOperator, position480) - } - return true - l479: - position, tokenIndex = position479, tokenIndex479 - return false - }, - /* 37 Offset <- <('+'? '-'? (('0' ('b' / 'B') ('0' / '1')+) / ('0' ('x' / 'X') ([0-9] / [0-9] / ([a-f] / [A-F]))+) / [0-9]+))> */ - func() bool { - position483, tokenIndex483 := position, tokenIndex - { - position484 := position + l484: { position485, tokenIndex485 := position, tokenIndex - if buffer[position] != rune('+') { + if !_rules[ruleWS]() { goto l485 } - position++ goto l486 l485: position, tokenIndex = position485, tokenIndex485 @@ -3768,295 +3812,409 @@ func (p *Asm) Init() { l486: { position487, tokenIndex487 := position, tokenIndex - if buffer[position] != rune('-') { + if buffer[position] != rune(',') { goto l487 } position++ + { + position489, tokenIndex489 := position, tokenIndex + if !_rules[ruleWS]() { + goto l489 + } + goto l490 + l489: + position, tokenIndex = position489, tokenIndex489 + } + l490: + if !_rules[ruleRegisterOrConstant]() { + goto l487 + } + { + position491, tokenIndex491 := position, tokenIndex + if !_rules[ruleWS]() { + goto l491 + } + goto l492 + l491: + position, tokenIndex = position491, tokenIndex491 + } + l492: + { + position493, tokenIndex493 := position, tokenIndex + if buffer[position] != rune(',') { + goto l493 + } + position++ + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l493 + } + position++ + l495: + { + position496, tokenIndex496 := position, tokenIndex + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l496 + } + position++ + goto l495 + l496: + position, tokenIndex = position496, tokenIndex496 + } + goto l494 + l493: + position, tokenIndex = position493, tokenIndex493 + } + l494: goto l488 l487: position, tokenIndex = position487, tokenIndex487 } l488: - { - position489, tokenIndex489 := position, tokenIndex - if buffer[position] != rune('0') { - goto l490 - } - position++ - { - position491, tokenIndex491 := position, tokenIndex - if buffer[position] != rune('b') { - goto l492 - } - position++ - goto l491 - l492: - position, tokenIndex = position491, tokenIndex491 - if buffer[position] != rune('B') { - goto l490 - } - position++ - } - l491: - { - position495, tokenIndex495 := position, tokenIndex - if buffer[position] != rune('0') { - goto l496 - } - position++ - goto l495 - l496: - position, tokenIndex = position495, tokenIndex495 - if buffer[position] != rune('1') { - goto l490 - } - position++ - } - l495: - l493: - { - position494, tokenIndex494 := position, tokenIndex - { - position497, tokenIndex497 := position, tokenIndex - if buffer[position] != rune('0') { - goto l498 - } - position++ - goto l497 - l498: - position, tokenIndex = position497, tokenIndex497 - if buffer[position] != rune('1') { - goto l494 - } - position++ - } - l497: - goto l493 - l494: - position, tokenIndex = position494, tokenIndex494 - } - goto l489 - l490: - position, tokenIndex = position489, tokenIndex489 - if buffer[position] != rune('0') { - goto l499 - } - position++ - { - position500, tokenIndex500 := position, tokenIndex - if buffer[position] != rune('x') { - goto l501 - } - position++ - goto l500 - l501: - position, tokenIndex = position500, tokenIndex500 - if buffer[position] != rune('X') { - goto l499 - } - position++ - } - l500: - { - position504, tokenIndex504 := position, tokenIndex - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l505 - } - position++ - goto l504 - l505: - position, tokenIndex = position504, tokenIndex504 - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l506 - } - position++ - goto l504 - l506: - position, tokenIndex = position504, tokenIndex504 - { - position507, tokenIndex507 := position, tokenIndex - if c := buffer[position]; c < rune('a') || c > rune('f') { - goto l508 - } - position++ - goto l507 - l508: - position, tokenIndex = position507, tokenIndex507 - if c := buffer[position]; c < rune('A') || c > rune('F') { - goto l499 - } - position++ - } - l507: - } - l504: - l502: - { - position503, tokenIndex503 := position, tokenIndex - { - position509, tokenIndex509 := position, tokenIndex - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l510 - } - position++ - goto l509 - l510: - position, tokenIndex = position509, tokenIndex509 - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l511 - } - position++ - goto l509 - l511: - position, tokenIndex = position509, tokenIndex509 - { - position512, tokenIndex512 := position, tokenIndex - if c := buffer[position]; c < rune('a') || c > rune('f') { - goto l513 - } - position++ - goto l512 - l513: - position, tokenIndex = position512, tokenIndex512 - if c := buffer[position]; c < rune('A') || c > rune('F') { - goto l503 - } - position++ - } - l512: - } - l509: - goto l502 - l503: - position, tokenIndex = position503, tokenIndex503 - } - goto l489 - l499: - position, tokenIndex = position489, tokenIndex489 - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l483 - } - position++ - l514: - { - position515, tokenIndex515 := position, tokenIndex - if c := buffer[position]; c < rune('0') || c > rune('9') { - goto l515 - } - position++ - goto l514 - l515: - position, tokenIndex = position515, tokenIndex515 - } + if buffer[position] != rune(')') { + goto l481 } - l489: - add(ruleOffset, position484) + position++ + add(ruleBaseIndexScale, position482) } return true - l483: - position, tokenIndex = position483, tokenIndex483 + l481: + position, tokenIndex = position481, tokenIndex481 + return false + }, + /* 36 Operator <- <('+' / '-')> */ + func() bool { + position497, tokenIndex497 := position, tokenIndex + { + position498 := position + { + position499, tokenIndex499 := position, tokenIndex + if buffer[position] != rune('+') { + goto l500 + } + position++ + goto l499 + l500: + position, tokenIndex = position499, tokenIndex499 + if buffer[position] != rune('-') { + goto l497 + } + position++ + } + l499: + add(ruleOperator, position498) + } + return true + l497: + position, tokenIndex = position497, tokenIndex497 + return false + }, + /* 37 Offset <- <('+'? '-'? (('0' ('b' / 'B') ('0' / '1')+) / ('0' ('x' / 'X') ([0-9] / [0-9] / ([a-f] / [A-F]))+) / [0-9]+))> */ + func() bool { + position501, tokenIndex501 := position, tokenIndex + { + position502 := position + { + position503, tokenIndex503 := position, tokenIndex + if buffer[position] != rune('+') { + goto l503 + } + position++ + goto l504 + l503: + position, tokenIndex = position503, tokenIndex503 + } + l504: + { + position505, tokenIndex505 := position, tokenIndex + if buffer[position] != rune('-') { + goto l505 + } + position++ + goto l506 + l505: + position, tokenIndex = position505, tokenIndex505 + } + l506: + { + position507, tokenIndex507 := position, tokenIndex + if buffer[position] != rune('0') { + goto l508 + } + position++ + { + position509, tokenIndex509 := position, tokenIndex + if buffer[position] != rune('b') { + goto l510 + } + position++ + goto l509 + l510: + position, tokenIndex = position509, tokenIndex509 + if buffer[position] != rune('B') { + goto l508 + } + position++ + } + l509: + { + position513, tokenIndex513 := position, tokenIndex + if buffer[position] != rune('0') { + goto l514 + } + position++ + goto l513 + l514: + position, tokenIndex = position513, tokenIndex513 + if buffer[position] != rune('1') { + goto l508 + } + position++ + } + l513: + l511: + { + position512, tokenIndex512 := position, tokenIndex + { + position515, tokenIndex515 := position, tokenIndex + if buffer[position] != rune('0') { + goto l516 + } + position++ + goto l515 + l516: + position, tokenIndex = position515, tokenIndex515 + if buffer[position] != rune('1') { + goto l512 + } + position++ + } + l515: + goto l511 + l512: + position, tokenIndex = position512, tokenIndex512 + } + goto l507 + l508: + position, tokenIndex = position507, tokenIndex507 + if buffer[position] != rune('0') { + goto l517 + } + position++ + { + position518, tokenIndex518 := position, tokenIndex + if buffer[position] != rune('x') { + goto l519 + } + position++ + goto l518 + l519: + position, tokenIndex = position518, tokenIndex518 + if buffer[position] != rune('X') { + goto l517 + } + position++ + } + l518: + { + position522, tokenIndex522 := position, tokenIndex + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l523 + } + position++ + goto l522 + l523: + position, tokenIndex = position522, tokenIndex522 + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l524 + } + position++ + goto l522 + l524: + position, tokenIndex = position522, tokenIndex522 + { + position525, tokenIndex525 := position, tokenIndex + if c := buffer[position]; c < rune('a') || c > rune('f') { + goto l526 + } + position++ + goto l525 + l526: + position, tokenIndex = position525, tokenIndex525 + if c := buffer[position]; c < rune('A') || c > rune('F') { + goto l517 + } + position++ + } + l525: + } + l522: + l520: + { + position521, tokenIndex521 := position, tokenIndex + { + position527, tokenIndex527 := position, tokenIndex + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l528 + } + position++ + goto l527 + l528: + position, tokenIndex = position527, tokenIndex527 + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l529 + } + position++ + goto l527 + l529: + position, tokenIndex = position527, tokenIndex527 + { + position530, tokenIndex530 := position, tokenIndex + if c := buffer[position]; c < rune('a') || c > rune('f') { + goto l531 + } + position++ + goto l530 + l531: + position, tokenIndex = position530, tokenIndex530 + if c := buffer[position]; c < rune('A') || c > rune('F') { + goto l521 + } + position++ + } + l530: + } + l527: + goto l520 + l521: + position, tokenIndex = position521, tokenIndex521 + } + goto l507 + l517: + position, tokenIndex = position507, tokenIndex507 + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l501 + } + position++ + l532: + { + position533, tokenIndex533 := position, tokenIndex + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l533 + } + position++ + goto l532 + l533: + position, tokenIndex = position533, tokenIndex533 + } + } + l507: + add(ruleOffset, position502) + } + return true + l501: + position, tokenIndex = position501, tokenIndex501 return false }, /* 38 Section <- <([a-z] / [A-Z] / '@')+> */ func() bool { - position516, tokenIndex516 := position, tokenIndex + position534, tokenIndex534 := position, tokenIndex { - position517 := position + position535 := position { - position520, tokenIndex520 := position, tokenIndex + position538, tokenIndex538 := position, tokenIndex if c := buffer[position]; c < rune('a') || c > rune('z') { - goto l521 + goto l539 } position++ - goto l520 - l521: - position, tokenIndex = position520, tokenIndex520 + goto l538 + l539: + position, tokenIndex = position538, tokenIndex538 if c := buffer[position]; c < rune('A') || c > rune('Z') { - goto l522 + goto l540 } position++ - goto l520 - l522: - position, tokenIndex = position520, tokenIndex520 + goto l538 + l540: + position, tokenIndex = position538, tokenIndex538 if buffer[position] != rune('@') { - goto l516 + goto l534 } position++ } - l520: - l518: + l538: + l536: { - position519, tokenIndex519 := position, tokenIndex + position537, tokenIndex537 := position, tokenIndex { - position523, tokenIndex523 := position, tokenIndex + position541, tokenIndex541 := position, tokenIndex if c := buffer[position]; c < rune('a') || c > rune('z') { - goto l524 + goto l542 } position++ - goto l523 - l524: - position, tokenIndex = position523, tokenIndex523 + goto l541 + l542: + position, tokenIndex = position541, tokenIndex541 if c := buffer[position]; c < rune('A') || c > rune('Z') { - goto l525 + goto l543 } position++ - goto l523 - l525: - position, tokenIndex = position523, tokenIndex523 + goto l541 + l543: + position, tokenIndex = position541, tokenIndex541 if buffer[position] != rune('@') { - goto l519 + goto l537 } position++ } - l523: - goto l518 - l519: - position, tokenIndex = position519, tokenIndex519 + l541: + goto l536 + l537: + position, tokenIndex = position537, tokenIndex537 } - add(ruleSection, position517) + add(ruleSection, position535) } return true - l516: - position, tokenIndex = position516, tokenIndex516 + l534: + position, tokenIndex = position534, tokenIndex534 return false }, /* 39 SegmentRegister <- <('%' ([c-g] / 's') ('s' ':'))> */ func() bool { - position526, tokenIndex526 := position, tokenIndex + position544, tokenIndex544 := position, tokenIndex { - position527 := position + position545 := position if buffer[position] != rune('%') { - goto l526 + goto l544 } position++ { - position528, tokenIndex528 := position, tokenIndex + position546, tokenIndex546 := position, tokenIndex if c := buffer[position]; c < rune('c') || c > rune('g') { - goto l529 + goto l547 } position++ - goto l528 - l529: - position, tokenIndex = position528, tokenIndex528 + goto l546 + l547: + position, tokenIndex = position546, tokenIndex546 if buffer[position] != rune('s') { - goto l526 + goto l544 } position++ } - l528: + l546: if buffer[position] != rune('s') { - goto l526 + goto l544 } position++ if buffer[position] != rune(':') { - goto l526 + goto l544 } position++ - add(ruleSegmentRegister, position527) + add(ruleSegmentRegister, position545) } return true - l526: - position, tokenIndex = position526, tokenIndex526 + l544: + position, tokenIndex = position544, tokenIndex544 return false }, } diff --git a/third_party/boringssl/kit/src/util/fipstools/delocate/delocate_test.go b/third_party/boringssl/kit/src/util/fipstools/delocate/delocate_test.go index e0ecc177..1778fa73 100644 --- a/third_party/boringssl/kit/src/util/fipstools/delocate/delocate_test.go +++ b/third_party/boringssl/kit/src/util/fipstools/delocate/delocate_test.go @@ -38,6 +38,7 @@ func (test *delocateTest) Path(file string) string { } var delocateTests = []delocateTest{ + {"generic-FileDirectives", []string{"in.s"}, "out.s"}, {"ppc64le-GlobalEntry", []string{"in.s"}, "out.s"}, {"ppc64le-LoadToR0", []string{"in.s"}, "out.s"}, {"ppc64le-Sample2", []string{"in.s"}, "out.s"}, @@ -48,6 +49,7 @@ var delocateTests = []delocateTest{ {"x86_64-GOTRewrite", []string{"in.s"}, "out.s"}, {"x86_64-LabelRewrite", []string{"in1.s", "in2.s"}, "out.s"}, {"x86_64-Sections", []string{"in.s"}, "out.s"}, + {"x86_64-ThreeArg", []string{"in.s"}, "out.s"}, } func TestDelocate(t *testing.T) { diff --git a/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/generic-FileDirectives/in.s b/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/generic-FileDirectives/in.s new file mode 100644 index 00000000..ca5f8c29 --- /dev/null +++ b/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/generic-FileDirectives/in.s @@ -0,0 +1,6 @@ +.file 10 "some/path/file.c" "file.c" +.file 1000 "some/path/file2.c" "file2.c" +.file 1001 "some/path/file_with_md5.c" "other_name.c" md5 0x5eba7844df6449a7f2fff1556fe7ba8d239f8e2f + +# An instruction is needed to satisfy the architecture auto-detection. + movq %rax, %rbx diff --git a/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/generic-FileDirectives/out.s b/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/generic-FileDirectives/out.s new file mode 100644 index 00000000..bb33e523 --- /dev/null +++ b/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/generic-FileDirectives/out.s @@ -0,0 +1,91 @@ +.text +.file 1002 "inserted_by_delocate.c" md5 0x00000000000000000000000000000000 +.loc 1002 1 0 +BORINGSSL_bcm_text_start: +.file 10 "some/path/file.c" "file.c" +.file 1000 "some/path/file2.c" "file2.c" +.file 1001 "some/path/file_with_md5.c" "other_name.c" md5 0x5eba7844df6449a7f2fff1556fe7ba8d239f8e2f + +# An instruction is needed to satisfy the architecture auto-detection. + movq %rax, %rbx +.text +.loc 1002 2 0 +BORINGSSL_bcm_text_end: +.type OPENSSL_ia32cap_get, @function +.globl OPENSSL_ia32cap_get +.LOPENSSL_ia32cap_get_local_target: +OPENSSL_ia32cap_get: + leaq OPENSSL_ia32cap_P(%rip), %rax + ret +.extern OPENSSL_ia32cap_P +.type OPENSSL_ia32cap_addr_delta, @object +.size OPENSSL_ia32cap_addr_delta, 8 +OPENSSL_ia32cap_addr_delta: +.quad OPENSSL_ia32cap_P-OPENSSL_ia32cap_addr_delta +.type BORINGSSL_bcm_text_hash, @object +.size BORINGSSL_bcm_text_hash, 64 +BORINGSSL_bcm_text_hash: +.byte 0xae +.byte 0x2c +.byte 0xea +.byte 0x2a +.byte 0xbd +.byte 0xa6 +.byte 0xf3 +.byte 0xec +.byte 0x97 +.byte 0x7f +.byte 0x9b +.byte 0xf6 +.byte 0x94 +.byte 0x9a +.byte 0xfc +.byte 0x83 +.byte 0x68 +.byte 0x27 +.byte 0xcb +.byte 0xa0 +.byte 0xa0 +.byte 0x9f +.byte 0x6b +.byte 0x6f +.byte 0xde +.byte 0x52 +.byte 0xcd +.byte 0xe2 +.byte 0xcd +.byte 0xff +.byte 0x31 +.byte 0x80 +.byte 0xa2 +.byte 0xd4 +.byte 0xc3 +.byte 0x66 +.byte 0xf +.byte 0xc2 +.byte 0x6a +.byte 0x7b +.byte 0xf4 +.byte 0xbe +.byte 0x39 +.byte 0xa2 +.byte 0xd7 +.byte 0x25 +.byte 0xdb +.byte 0x21 +.byte 0x98 +.byte 0xe9 +.byte 0xd5 +.byte 0x53 +.byte 0xbf +.byte 0x5c +.byte 0x32 +.byte 0x6 +.byte 0x83 +.byte 0x34 +.byte 0xc +.byte 0x65 +.byte 0x89 +.byte 0x52 +.byte 0xbd +.byte 0x1f diff --git a/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-LabelRewrite/in1.s b/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-LabelRewrite/in1.s index e97b280b..8ee70896 100644 --- a/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-LabelRewrite/in1.s +++ b/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-LabelRewrite/in1.s @@ -35,6 +35,8 @@ bar: .quad 42 .L2: .quad .L2-.L1 + .uleb128 .L2-.L1 + .sleb128 .L2-.L1 # Local labels and their jumps are left alone. .text diff --git a/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-LabelRewrite/in2.s b/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-LabelRewrite/in2.s index 7a5a5510..50273253 100644 --- a/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-LabelRewrite/in2.s +++ b/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-LabelRewrite/in2.s @@ -9,4 +9,6 @@ .quad 42 .L2: .quad .L2-.L1 + .uleb128 .L2-.L1 + .sleb128 .L2-.L1 diff --git a/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-LabelRewrite/out.s b/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-LabelRewrite/out.s index 8cc27de8..252f69c1 100644 --- a/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-LabelRewrite/out.s +++ b/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-LabelRewrite/out.s @@ -56,6 +56,8 @@ bar: .L2: .quad .L2-.L1 + .uleb128 .L2-.L1 + .sleb128 .L2-.L1 # Local labels and their jumps are left alone. .text @@ -82,6 +84,10 @@ bar: # WAS .quad .L2-.L1 .quad .L2_BCM_1-.L1_BCM_1 +# WAS .uleb128 .L2-.L1 + .uleb128 .L2_BCM_1-.L1_BCM_1 +# WAS .sleb128 .L2-.L1 + .sleb128 .L2_BCM_1-.L1_BCM_1 .text .loc 1 2 0 diff --git a/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-ThreeArg/in.s b/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-ThreeArg/in.s new file mode 100644 index 00000000..78a09de1 --- /dev/null +++ b/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-ThreeArg/in.s @@ -0,0 +1,14 @@ + .type foo, @function + .globl foo +foo: + movq %rax, %rax + shrxq %rbx, kBoringSSLRSASqrtTwo@GOTPCREL(%rip), %rax + shrxq kBoringSSLRSASqrtTwo@GOTPCREL(%rip), %rbx, %rax + + + .type kBoringSSLRSASqrtTwo,@object # @kBoringSSLRSASqrtTwo + .section .rodata,"a",@progbits,unique,760 + .globl kBoringSSLRSASqrtTwo + .p2align 4 +kBoringSSLRSASqrtTwo: + .quad -2404814165548301886 # 0xdea06241f7aa81c2 diff --git a/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-ThreeArg/out.s b/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-ThreeArg/out.s new file mode 100644 index 00000000..7ad8f768 --- /dev/null +++ b/third_party/boringssl/kit/src/util/fipstools/delocate/testdata/x86_64-ThreeArg/out.s @@ -0,0 +1,114 @@ +.text +.file 1 "inserted_by_delocate.c" +.loc 1 1 0 +BORINGSSL_bcm_text_start: + .type foo, @function + .globl foo +.Lfoo_local_target: +foo: + movq %rax, %rax +# WAS shrxq %rbx, kBoringSSLRSASqrtTwo@GOTPCREL(%rip), %rax + leaq -128(%rsp), %rsp + pushq %rcx + leaq .LkBoringSSLRSASqrtTwo_local_target(%rip), %rcx + shrxq %rbx, %rcx, %rax + popq %rcx + leaq 128(%rsp), %rsp +# WAS shrxq kBoringSSLRSASqrtTwo@GOTPCREL(%rip), %rbx, %rax + leaq -128(%rsp), %rsp + pushq %rcx + leaq .LkBoringSSLRSASqrtTwo_local_target(%rip), %rcx + shrxq %rcx, %rbx, %rax + popq %rcx + leaq 128(%rsp), %rsp + + + .type kBoringSSLRSASqrtTwo,@object # @kBoringSSLRSASqrtTwo +# WAS .section .rodata,"a",@progbits,unique,760 +.text + .globl kBoringSSLRSASqrtTwo + .p2align 4 +.LkBoringSSLRSASqrtTwo_local_target: +kBoringSSLRSASqrtTwo: + .quad -2404814165548301886 # 0xdea06241f7aa81c2 +.text +.loc 1 2 0 +BORINGSSL_bcm_text_end: +.type OPENSSL_ia32cap_get, @function +.globl OPENSSL_ia32cap_get +.LOPENSSL_ia32cap_get_local_target: +OPENSSL_ia32cap_get: + leaq OPENSSL_ia32cap_P(%rip), %rax + ret +.extern OPENSSL_ia32cap_P +.type OPENSSL_ia32cap_addr_delta, @object +.size OPENSSL_ia32cap_addr_delta, 8 +OPENSSL_ia32cap_addr_delta: +.quad OPENSSL_ia32cap_P-OPENSSL_ia32cap_addr_delta +.type BORINGSSL_bcm_text_hash, @object +.size BORINGSSL_bcm_text_hash, 64 +BORINGSSL_bcm_text_hash: +.byte 0xae +.byte 0x2c +.byte 0xea +.byte 0x2a +.byte 0xbd +.byte 0xa6 +.byte 0xf3 +.byte 0xec +.byte 0x97 +.byte 0x7f +.byte 0x9b +.byte 0xf6 +.byte 0x94 +.byte 0x9a +.byte 0xfc +.byte 0x83 +.byte 0x68 +.byte 0x27 +.byte 0xcb +.byte 0xa0 +.byte 0xa0 +.byte 0x9f +.byte 0x6b +.byte 0x6f +.byte 0xde +.byte 0x52 +.byte 0xcd +.byte 0xe2 +.byte 0xcd +.byte 0xff +.byte 0x31 +.byte 0x80 +.byte 0xa2 +.byte 0xd4 +.byte 0xc3 +.byte 0x66 +.byte 0xf +.byte 0xc2 +.byte 0x6a +.byte 0x7b +.byte 0xf4 +.byte 0xbe +.byte 0x39 +.byte 0xa2 +.byte 0xd7 +.byte 0x25 +.byte 0xdb +.byte 0x21 +.byte 0x98 +.byte 0xe9 +.byte 0xd5 +.byte 0x53 +.byte 0xbf +.byte 0x5c +.byte 0x32 +.byte 0x6 +.byte 0x83 +.byte 0x34 +.byte 0xc +.byte 0x65 +.byte 0x89 +.byte 0x52 +.byte 0xbd +.byte 0x1f diff --git a/third_party/boringssl/kit/src/util/fipstools/inject_hash/inject_hash.go b/third_party/boringssl/kit/src/util/fipstools/inject_hash/inject_hash.go index 29307c03..6bab1434 100644 --- a/third_party/boringssl/kit/src/util/fipstools/inject_hash/inject_hash.go +++ b/third_party/boringssl/kit/src/util/fipstools/inject_hash/inject_hash.go @@ -22,12 +22,14 @@ import ( "crypto/hmac" "crypto/sha512" "debug/elf" + "encoding/binary" "errors" "flag" "fmt" "io" "io/ioutil" "os" + "strings" "boringssl.googlesource.com/boringssl/util/ar" "boringssl.googlesource.com/boringssl/util/fipstools/fipscommon" @@ -35,7 +37,10 @@ import ( func do(outPath, oInput string, arInput string) error { var objectBytes []byte + var isStatic bool if len(arInput) > 0 { + isStatic = true + if len(oInput) > 0 { return fmt.Errorf("-in-archive and -in-object are mutually exclusive") } @@ -63,6 +68,7 @@ func do(outPath, oInput string, arInput string) error { if objectBytes, err = ioutil.ReadFile(oInput); err != nil { return err } + isStatic = strings.HasSuffix(oInput, ".o") } else { return fmt.Errorf("exactly one of -in-archive or -in-object is required") } @@ -72,15 +78,18 @@ func do(outPath, oInput string, arInput string) error { return errors.New("failed to parse object: " + err.Error()) } - // Find the .text section. + // Find the .text and, optionally, .data sections. - var textSection *elf.Section - var textSectionIndex elf.SectionIndex + var textSection, rodataSection *elf.Section + var textSectionIndex, rodataSectionIndex elf.SectionIndex for i, section := range object.Sections { - if section.Name == ".text" { + switch section.Name { + case ".text": textSectionIndex = elf.SectionIndex(i) textSection = section - break + case ".rodata": + rodataSectionIndex = elf.SectionIndex(i) + rodataSection = section } } @@ -90,8 +99,7 @@ func do(outPath, oInput string, arInput string) error { // Find the starting and ending symbols for the module. - var startSeen, endSeen bool - var start, end uint64 + var textStart, textEnd, rodataStart, rodataEnd *uint64 symbols, err := object.Symbols() if err != nil { @@ -99,50 +107,115 @@ func do(outPath, oInput string, arInput string) error { } for _, symbol := range symbols { - if symbol.Section != textSectionIndex { + var base uint64 + switch symbol.Section { + case textSectionIndex: + base = textSection.Addr + case rodataSectionIndex: + if rodataSection == nil { + continue + } + base = rodataSection.Addr + default: continue } + if isStatic { + // Static objects appear to have different semantics about whether symbol + // values are relative to their section or not. + base = 0 + } else if symbol.Value < base { + return fmt.Errorf("symbol %q at %x, which is below base of %x", symbol.Name, symbol.Value, base) + } + + value := symbol.Value - base switch symbol.Name { case "BORINGSSL_bcm_text_start": - if startSeen { + if textStart != nil { return errors.New("duplicate start symbol found") } - startSeen = true - start = symbol.Value + textStart = &value case "BORINGSSL_bcm_text_end": - if endSeen { + if textEnd != nil { return errors.New("duplicate end symbol found") } - endSeen = true - end = symbol.Value + textEnd = &value + case "BORINGSSL_bcm_rodata_start": + if rodataStart != nil { + return errors.New("duplicate rodata start symbol found") + } + rodataStart = &value + case "BORINGSSL_bcm_rodata_end": + if rodataEnd != nil { + return errors.New("duplicate rodata end symbol found") + } + rodataEnd = &value default: continue } } - if !startSeen || !endSeen { - return errors.New("could not find module boundaries in object") + if textStart == nil || textEnd == nil { + return errors.New("could not find .text module boundaries in object") } - if max := textSection.Size; start > max || start > end || end > max { - return fmt.Errorf("invalid module boundaries: start: %x, end: %x, max: %x", start, end, max) + if (rodataStart == nil) != (rodataSection == nil) { + return errors.New("rodata start marker inconsistent with rodata section presence") + } + + if (rodataStart != nil) != (rodataEnd != nil) { + return errors.New("rodata marker presence inconsistent") + } + + if max := textSection.Size; *textStart > max || *textStart > *textEnd || *textEnd > max { + return fmt.Errorf("invalid module .text boundaries: start: %x, end: %x, max: %x", *textStart, *textEnd, max) + } + + if rodataSection != nil { + if max := rodataSection.Size; *rodataStart > max || *rodataStart > *rodataEnd || *rodataEnd > max { + return fmt.Errorf("invalid module .rodata boundaries: start: %x, end: %x, max: %x", *rodataStart, *rodataEnd, max) + } } // Extract the module from the .text section and hash it. text := textSection.Open() - if _, err := text.Seek(int64(start), 0); err != nil { + if _, err := text.Seek(int64(*textStart), 0); err != nil { return errors.New("failed to seek to module start in .text: " + err.Error()) } - moduleText := make([]byte, end-start) + moduleText := make([]byte, *textEnd-*textStart) if _, err := io.ReadFull(text, moduleText); err != nil { return errors.New("failed to read .text: " + err.Error()) } + // Maybe extract the module's read-only data too + var moduleROData []byte + if rodataSection != nil { + rodata := rodataSection.Open() + if _, err := rodata.Seek(int64(*rodataStart), 0); err != nil { + return errors.New("failed to seek to module start in .rodata: " + err.Error()) + } + moduleROData = make([]byte, *rodataEnd-*rodataStart) + if _, err := io.ReadFull(rodata, moduleROData); err != nil { + return errors.New("failed to read .rodata: " + err.Error()) + } + } + var zeroKey [64]byte mac := hmac.New(sha512.New, zeroKey[:]) - mac.Write(moduleText) + + if moduleROData != nil { + var lengthBytes [8]byte + binary.LittleEndian.PutUint64(lengthBytes[:], uint64(len(moduleText))) + mac.Write(lengthBytes[:]) + mac.Write(moduleText) + + binary.LittleEndian.PutUint64(lengthBytes[:], uint64(len(moduleROData))) + mac.Write(lengthBytes[:]) + mac.Write(moduleROData) + } else { + mac.Write(moduleText) + } calculated := mac.Sum(nil) // Replace the default hash value in the object with the calculated diff --git a/third_party/boringssl/kit/src/util/generate_build_files.py b/third_party/boringssl/kit/src/util/generate_build_files.py index 2a6fe3f2..b59373c9 100644 --- a/third_party/boringssl/kit/src/util/generate_build_files.py +++ b/third_party/boringssl/kit/src/util/generate_build_files.py @@ -325,6 +325,8 @@ class GN(object): files['test_support_headers']) self.PrintVariableSection(out, 'crypto_test_sources', files['crypto_test']) + self.PrintVariableSection(out, 'crypto_test_data', + files['crypto_test_data']) self.PrintVariableSection(out, 'ssl_test_sources', files['ssl_test']) @@ -415,7 +417,7 @@ def NoTestRunnerFiles(path, dent, is_dir): def NotGTestSupport(path, dent, is_dir): - return 'gtest' not in dent + return 'gtest' not in dent and 'abi_test' not in dent def SSLHeaderFiles(path, dent, is_dir): @@ -590,7 +592,8 @@ def ExtractVariablesFromCMakeFile(cmakefile): def main(platforms): cmake = ExtractVariablesFromCMakeFile(os.path.join('src', 'sources.cmake')) crypto_c_files = (FindCFiles(os.path.join('src', 'crypto'), NoTestsNorFIPSFragments) + - FindCFiles(os.path.join('src', 'third_party', 'fiat'), NoTestsNorFIPSFragments)) + FindCFiles(os.path.join('src', 'third_party', 'fiat'), NoTestsNorFIPSFragments) + + FindCFiles(os.path.join('src', 'third_party', 'sike'), NoTestsNorFIPSFragments)) fips_fragments = FindCFiles(os.path.join('src', 'crypto', 'fipsmodule'), OnlyFIPSFragments) ssl_source_files = FindCFiles(os.path.join('src', 'ssl'), NoTests) tool_c_files = FindCFiles(os.path.join('src', 'tool'), NoTests) @@ -627,12 +630,16 @@ def main(platforms): crypto_test_files += FindCFiles(os.path.join('src', 'crypto'), OnlyTests) crypto_test_files += [ + 'src/crypto/test/abi_test.cc', 'src/crypto/test/file_test_gtest.cc', 'src/crypto/test/gtest_main.cc', ] ssl_test_files = FindCFiles(os.path.join('src', 'ssl'), OnlyTests) - ssl_test_files.append('src/crypto/test/gtest_main.cc') + ssl_test_files += [ + 'src/crypto/test/abi_test.cc', + 'src/crypto/test/gtest_main.cc', + ] fuzz_c_files = FindCFiles(os.path.join('src', 'fuzz'), NoTests) @@ -651,7 +658,8 @@ def main(platforms): ssl_internal_h_files = FindHeaderFiles(os.path.join('src', 'ssl'), NoTests) crypto_internal_h_files = ( FindHeaderFiles(os.path.join('src', 'crypto'), NoTests) + - FindHeaderFiles(os.path.join('src', 'third_party', 'fiat'), NoTests)) + FindHeaderFiles(os.path.join('src', 'third_party', 'fiat'), NoTests) + + FindHeaderFiles(os.path.join('src', 'third_party', 'sike'), NoTests)) files = { 'crypto': crypto_c_files, @@ -687,7 +695,7 @@ if __name__ == '__main__': parser.add_option( '--embed_test_data', type='choice', dest='embed_test_data', action='store', default="true", choices=["true", "false"], - help='For Bazel, don\'t embed data files in crypto_test_data.cc') + help='For Bazel or GN, don\'t embed data files in crypto_test_data.cc') options, args = parser.parse_args(sys.argv[1:]) PREFIX = options.prefix EMBED_TEST_DATA = (options.embed_test_data == "true") diff --git a/third_party/boringssl/kit/win-x86/crypto/fipsmodule/aesni-x86.asm b/third_party/boringssl/kit/win-x86/crypto/fipsmodule/aesni-x86.asm index 602d0b47..47309503 100644 --- a/third_party/boringssl/kit/win-x86/crypto/fipsmodule/aesni-x86.asm +++ b/third_party/boringssl/kit/win-x86/crypto/fipsmodule/aesni-x86.asm @@ -21,10 +21,25 @@ section .text code align=64 section .text code %endif ;extern _OPENSSL_ia32cap_P +%ifndef NDEBUG +extern _BORINGSSL_function_hit +%endif global _aes_hw_encrypt align 16 _aes_hw_encrypt: L$_aes_hw_encrypt_begin: +%ifndef NDEBUG + push ebx + push edx + call L$000pic +L$000pic: + pop ebx + lea ebx,[(_BORINGSSL_function_hit+1-L$000pic)+ebx] + mov edx,1 + mov BYTE [ebx],dl + pop edx + pop ebx +%endif mov eax,DWORD [4+esp] mov edx,DWORD [12+esp] movups xmm2,[eax] @@ -34,12 +49,12 @@ L$_aes_hw_encrypt_begin: movups xmm1,[16+edx] lea edx,[32+edx] xorps xmm2,xmm0 -L$000enc1_loop_1: +L$001enc1_loop_1: db 102,15,56,220,209 dec ecx movups xmm1,[edx] lea edx,[16+edx] - jnz NEAR L$000enc1_loop_1 + jnz NEAR L$001enc1_loop_1 db 102,15,56,221,209 pxor xmm0,xmm0 pxor xmm1,xmm1 @@ -59,12 +74,12 @@ L$_aes_hw_decrypt_begin: movups xmm1,[16+edx] lea edx,[32+edx] xorps xmm2,xmm0 -L$001dec1_loop_2: +L$002dec1_loop_2: db 102,15,56,222,209 dec ecx movups xmm1,[edx] lea edx,[16+edx] - jnz NEAR L$001dec1_loop_2 + jnz NEAR L$002dec1_loop_2 db 102,15,56,223,209 pxor xmm0,xmm0 pxor xmm1,xmm1 @@ -82,7 +97,7 @@ __aesni_encrypt2: lea edx,[32+ecx*1+edx] neg ecx add ecx,16 -L$002enc2_loop: +L$003enc2_loop: db 102,15,56,220,209 db 102,15,56,220,217 movups xmm1,[ecx*1+edx] @@ -90,7 +105,7 @@ db 102,15,56,220,217 db 102,15,56,220,208 db 102,15,56,220,216 movups xmm0,[ecx*1+edx-16] - jnz NEAR L$002enc2_loop + jnz NEAR L$003enc2_loop db 102,15,56,220,209 db 102,15,56,220,217 db 102,15,56,221,208 @@ -107,7 +122,7 @@ __aesni_decrypt2: lea edx,[32+ecx*1+edx] neg ecx add ecx,16 -L$003dec2_loop: +L$004dec2_loop: db 102,15,56,222,209 db 102,15,56,222,217 movups xmm1,[ecx*1+edx] @@ -115,7 +130,7 @@ db 102,15,56,222,217 db 102,15,56,222,208 db 102,15,56,222,216 movups xmm0,[ecx*1+edx-16] - jnz NEAR L$003dec2_loop + jnz NEAR L$004dec2_loop db 102,15,56,222,209 db 102,15,56,222,217 db 102,15,56,223,208 @@ -133,7 +148,7 @@ __aesni_encrypt3: lea edx,[32+ecx*1+edx] neg ecx add ecx,16 -L$004enc3_loop: +L$005enc3_loop: db 102,15,56,220,209 db 102,15,56,220,217 db 102,15,56,220,225 @@ -143,7 +158,7 @@ db 102,15,56,220,208 db 102,15,56,220,216 db 102,15,56,220,224 movups xmm0,[ecx*1+edx-16] - jnz NEAR L$004enc3_loop + jnz NEAR L$005enc3_loop db 102,15,56,220,209 db 102,15,56,220,217 db 102,15,56,220,225 @@ -163,7 +178,7 @@ __aesni_decrypt3: lea edx,[32+ecx*1+edx] neg ecx add ecx,16 -L$005dec3_loop: +L$006dec3_loop: db 102,15,56,222,209 db 102,15,56,222,217 db 102,15,56,222,225 @@ -173,7 +188,7 @@ db 102,15,56,222,208 db 102,15,56,222,216 db 102,15,56,222,224 movups xmm0,[ecx*1+edx-16] - jnz NEAR L$005dec3_loop + jnz NEAR L$006dec3_loop db 102,15,56,222,209 db 102,15,56,222,217 db 102,15,56,222,225 @@ -195,7 +210,7 @@ __aesni_encrypt4: neg ecx db 15,31,64,0 add ecx,16 -L$006enc4_loop: +L$007enc4_loop: db 102,15,56,220,209 db 102,15,56,220,217 db 102,15,56,220,225 @@ -207,7 +222,7 @@ db 102,15,56,220,216 db 102,15,56,220,224 db 102,15,56,220,232 movups xmm0,[ecx*1+edx-16] - jnz NEAR L$006enc4_loop + jnz NEAR L$007enc4_loop db 102,15,56,220,209 db 102,15,56,220,217 db 102,15,56,220,225 @@ -231,7 +246,7 @@ __aesni_decrypt4: neg ecx db 15,31,64,0 add ecx,16 -L$007dec4_loop: +L$008dec4_loop: db 102,15,56,222,209 db 102,15,56,222,217 db 102,15,56,222,225 @@ -243,7 +258,7 @@ db 102,15,56,222,216 db 102,15,56,222,224 db 102,15,56,222,232 movups xmm0,[ecx*1+edx-16] - jnz NEAR L$007dec4_loop + jnz NEAR L$008dec4_loop db 102,15,56,222,209 db 102,15,56,222,217 db 102,15,56,222,225 @@ -271,13 +286,13 @@ db 102,15,56,220,225 pxor xmm7,xmm0 movups xmm0,[ecx*1+edx] add ecx,16 - jmp NEAR L$008_aesni_encrypt6_inner + jmp NEAR L$009_aesni_encrypt6_inner align 16 -L$009enc6_loop: +L$010enc6_loop: db 102,15,56,220,209 db 102,15,56,220,217 db 102,15,56,220,225 -L$008_aesni_encrypt6_inner: +L$009_aesni_encrypt6_inner: db 102,15,56,220,233 db 102,15,56,220,241 db 102,15,56,220,249 @@ -291,7 +306,7 @@ db 102,15,56,220,232 db 102,15,56,220,240 db 102,15,56,220,248 movups xmm0,[ecx*1+edx-16] - jnz NEAR L$009enc6_loop + jnz NEAR L$010enc6_loop db 102,15,56,220,209 db 102,15,56,220,217 db 102,15,56,220,225 @@ -323,13 +338,13 @@ db 102,15,56,222,225 pxor xmm7,xmm0 movups xmm0,[ecx*1+edx] add ecx,16 - jmp NEAR L$010_aesni_decrypt6_inner + jmp NEAR L$011_aesni_decrypt6_inner align 16 -L$011dec6_loop: +L$012dec6_loop: db 102,15,56,222,209 db 102,15,56,222,217 db 102,15,56,222,225 -L$010_aesni_decrypt6_inner: +L$011_aesni_decrypt6_inner: db 102,15,56,222,233 db 102,15,56,222,241 db 102,15,56,222,249 @@ -343,7 +358,7 @@ db 102,15,56,222,232 db 102,15,56,222,240 db 102,15,56,222,248 movups xmm0,[ecx*1+edx-16] - jnz NEAR L$011dec6_loop + jnz NEAR L$012dec6_loop db 102,15,56,222,209 db 102,15,56,222,217 db 102,15,56,222,225 @@ -371,14 +386,14 @@ L$_aes_hw_ecb_encrypt_begin: mov edx,DWORD [32+esp] mov ebx,DWORD [36+esp] and eax,-16 - jz NEAR L$012ecb_ret + jz NEAR L$013ecb_ret mov ecx,DWORD [240+edx] test ebx,ebx - jz NEAR L$013ecb_decrypt + jz NEAR L$014ecb_decrypt mov ebp,edx mov ebx,ecx cmp eax,96 - jb NEAR L$014ecb_enc_tail + jb NEAR L$015ecb_enc_tail movdqu xmm2,[esi] movdqu xmm3,[16+esi] movdqu xmm4,[32+esi] @@ -387,9 +402,9 @@ L$_aes_hw_ecb_encrypt_begin: movdqu xmm7,[80+esi] lea esi,[96+esi] sub eax,96 - jmp NEAR L$015ecb_enc_loop6_enter + jmp NEAR L$016ecb_enc_loop6_enter align 16 -L$016ecb_enc_loop6: +L$017ecb_enc_loop6: movups [edi],xmm2 movdqu xmm2,[esi] movups [16+edi],xmm3 @@ -404,12 +419,12 @@ L$016ecb_enc_loop6: lea edi,[96+edi] movdqu xmm7,[80+esi] lea esi,[96+esi] -L$015ecb_enc_loop6_enter: +L$016ecb_enc_loop6_enter: call __aesni_encrypt6 mov edx,ebp mov ecx,ebx sub eax,96 - jnc NEAR L$016ecb_enc_loop6 + jnc NEAR L$017ecb_enc_loop6 movups [edi],xmm2 movups [16+edi],xmm3 movups [32+edi],xmm4 @@ -418,18 +433,18 @@ L$015ecb_enc_loop6_enter: movups [80+edi],xmm7 lea edi,[96+edi] add eax,96 - jz NEAR L$012ecb_ret -L$014ecb_enc_tail: + jz NEAR L$013ecb_ret +L$015ecb_enc_tail: movups xmm2,[esi] cmp eax,32 - jb NEAR L$017ecb_enc_one + jb NEAR L$018ecb_enc_one movups xmm3,[16+esi] - je NEAR L$018ecb_enc_two + je NEAR L$019ecb_enc_two movups xmm4,[32+esi] cmp eax,64 - jb NEAR L$019ecb_enc_three + jb NEAR L$020ecb_enc_three movups xmm5,[48+esi] - je NEAR L$020ecb_enc_four + je NEAR L$021ecb_enc_four movups xmm6,[64+esi] xorps xmm7,xmm7 call __aesni_encrypt6 @@ -438,49 +453,49 @@ L$014ecb_enc_tail: movups [32+edi],xmm4 movups [48+edi],xmm5 movups [64+edi],xmm6 - jmp NEAR L$012ecb_ret + jmp NEAR L$013ecb_ret align 16 -L$017ecb_enc_one: +L$018ecb_enc_one: movups xmm0,[edx] movups xmm1,[16+edx] lea edx,[32+edx] xorps xmm2,xmm0 -L$021enc1_loop_3: +L$022enc1_loop_3: db 102,15,56,220,209 dec ecx movups xmm1,[edx] lea edx,[16+edx] - jnz NEAR L$021enc1_loop_3 + jnz NEAR L$022enc1_loop_3 db 102,15,56,221,209 movups [edi],xmm2 - jmp NEAR L$012ecb_ret + jmp NEAR L$013ecb_ret align 16 -L$018ecb_enc_two: +L$019ecb_enc_two: call __aesni_encrypt2 movups [edi],xmm2 movups [16+edi],xmm3 - jmp NEAR L$012ecb_ret + jmp NEAR L$013ecb_ret align 16 -L$019ecb_enc_three: +L$020ecb_enc_three: call __aesni_encrypt3 movups [edi],xmm2 movups [16+edi],xmm3 movups [32+edi],xmm4 - jmp NEAR L$012ecb_ret + jmp NEAR L$013ecb_ret align 16 -L$020ecb_enc_four: +L$021ecb_enc_four: call __aesni_encrypt4 movups [edi],xmm2 movups [16+edi],xmm3 movups [32+edi],xmm4 movups [48+edi],xmm5 - jmp NEAR L$012ecb_ret + jmp NEAR L$013ecb_ret align 16 -L$013ecb_decrypt: +L$014ecb_decrypt: mov ebp,edx mov ebx,ecx cmp eax,96 - jb NEAR L$022ecb_dec_tail + jb NEAR L$023ecb_dec_tail movdqu xmm2,[esi] movdqu xmm3,[16+esi] movdqu xmm4,[32+esi] @@ -489,9 +504,9 @@ L$013ecb_decrypt: movdqu xmm7,[80+esi] lea esi,[96+esi] sub eax,96 - jmp NEAR L$023ecb_dec_loop6_enter + jmp NEAR L$024ecb_dec_loop6_enter align 16 -L$024ecb_dec_loop6: +L$025ecb_dec_loop6: movups [edi],xmm2 movdqu xmm2,[esi] movups [16+edi],xmm3 @@ -506,12 +521,12 @@ L$024ecb_dec_loop6: lea edi,[96+edi] movdqu xmm7,[80+esi] lea esi,[96+esi] -L$023ecb_dec_loop6_enter: +L$024ecb_dec_loop6_enter: call __aesni_decrypt6 mov edx,ebp mov ecx,ebx sub eax,96 - jnc NEAR L$024ecb_dec_loop6 + jnc NEAR L$025ecb_dec_loop6 movups [edi],xmm2 movups [16+edi],xmm3 movups [32+edi],xmm4 @@ -520,18 +535,18 @@ L$023ecb_dec_loop6_enter: movups [80+edi],xmm7 lea edi,[96+edi] add eax,96 - jz NEAR L$012ecb_ret -L$022ecb_dec_tail: + jz NEAR L$013ecb_ret +L$023ecb_dec_tail: movups xmm2,[esi] cmp eax,32 - jb NEAR L$025ecb_dec_one + jb NEAR L$026ecb_dec_one movups xmm3,[16+esi] - je NEAR L$026ecb_dec_two + je NEAR L$027ecb_dec_two movups xmm4,[32+esi] cmp eax,64 - jb NEAR L$027ecb_dec_three + jb NEAR L$028ecb_dec_three movups xmm5,[48+esi] - je NEAR L$028ecb_dec_four + je NEAR L$029ecb_dec_four movups xmm6,[64+esi] xorps xmm7,xmm7 call __aesni_decrypt6 @@ -540,43 +555,43 @@ L$022ecb_dec_tail: movups [32+edi],xmm4 movups [48+edi],xmm5 movups [64+edi],xmm6 - jmp NEAR L$012ecb_ret + jmp NEAR L$013ecb_ret align 16 -L$025ecb_dec_one: +L$026ecb_dec_one: movups xmm0,[edx] movups xmm1,[16+edx] lea edx,[32+edx] xorps xmm2,xmm0 -L$029dec1_loop_4: +L$030dec1_loop_4: db 102,15,56,222,209 dec ecx movups xmm1,[edx] lea edx,[16+edx] - jnz NEAR L$029dec1_loop_4 + jnz NEAR L$030dec1_loop_4 db 102,15,56,223,209 movups [edi],xmm2 - jmp NEAR L$012ecb_ret + jmp NEAR L$013ecb_ret align 16 -L$026ecb_dec_two: +L$027ecb_dec_two: call __aesni_decrypt2 movups [edi],xmm2 movups [16+edi],xmm3 - jmp NEAR L$012ecb_ret + jmp NEAR L$013ecb_ret align 16 -L$027ecb_dec_three: +L$028ecb_dec_three: call __aesni_decrypt3 movups [edi],xmm2 movups [16+edi],xmm3 movups [32+edi],xmm4 - jmp NEAR L$012ecb_ret + jmp NEAR L$013ecb_ret align 16 -L$028ecb_dec_four: +L$029ecb_dec_four: call __aesni_decrypt4 movups [edi],xmm2 movups [16+edi],xmm3 movups [32+edi],xmm4 movups [48+edi],xmm5 -L$012ecb_ret: +L$013ecb_ret: pxor xmm0,xmm0 pxor xmm1,xmm1 pxor xmm2,xmm2 @@ -629,7 +644,7 @@ L$_aes_hw_ccm64_encrypt_blocks_begin: lea edx,[32+ecx*1+edx] sub ebx,ecx db 102,15,56,0,253 -L$030ccm64_enc_outer: +L$031ccm64_enc_outer: movups xmm0,[ebp] mov ecx,ebx movups xmm6,[esi] @@ -638,7 +653,7 @@ L$030ccm64_enc_outer: xorps xmm0,xmm6 xorps xmm3,xmm0 movups xmm0,[32+ebp] -L$031ccm64_enc2_loop: +L$032ccm64_enc2_loop: db 102,15,56,220,209 db 102,15,56,220,217 movups xmm1,[ecx*1+edx] @@ -646,7 +661,7 @@ db 102,15,56,220,217 db 102,15,56,220,208 db 102,15,56,220,216 movups xmm0,[ecx*1+edx-16] - jnz NEAR L$031ccm64_enc2_loop + jnz NEAR L$032ccm64_enc2_loop db 102,15,56,220,209 db 102,15,56,220,217 paddq xmm7,[16+esp] @@ -659,7 +674,7 @@ db 102,15,56,221,216 movups [edi],xmm6 db 102,15,56,0,213 lea edi,[16+edi] - jnz NEAR L$030ccm64_enc_outer + jnz NEAR L$031ccm64_enc_outer mov esp,DWORD [48+esp] mov edi,DWORD [40+esp] movups [edi],xmm3 @@ -716,12 +731,12 @@ db 102,15,56,0,253 movups xmm1,[16+edx] lea edx,[32+edx] xorps xmm2,xmm0 -L$032enc1_loop_5: +L$033enc1_loop_5: db 102,15,56,220,209 dec ecx movups xmm1,[edx] lea edx,[16+edx] - jnz NEAR L$032enc1_loop_5 + jnz NEAR L$033enc1_loop_5 db 102,15,56,221,209 shl ebx,4 mov ecx,16 @@ -731,16 +746,16 @@ db 102,15,56,221,209 sub ecx,ebx lea edx,[32+ebx*1+ebp] mov ebx,ecx - jmp NEAR L$033ccm64_dec_outer + jmp NEAR L$034ccm64_dec_outer align 16 -L$033ccm64_dec_outer: +L$034ccm64_dec_outer: xorps xmm6,xmm2 movdqa xmm2,xmm7 movups [edi],xmm6 lea edi,[16+edi] db 102,15,56,0,213 sub eax,1 - jz NEAR L$034ccm64_dec_break + jz NEAR L$035ccm64_dec_break movups xmm0,[ebp] mov ecx,ebx movups xmm1,[16+ebp] @@ -748,7 +763,7 @@ db 102,15,56,0,213 xorps xmm2,xmm0 xorps xmm3,xmm6 movups xmm0,[32+ebp] -L$035ccm64_dec2_loop: +L$036ccm64_dec2_loop: db 102,15,56,220,209 db 102,15,56,220,217 movups xmm1,[ecx*1+edx] @@ -756,7 +771,7 @@ db 102,15,56,220,217 db 102,15,56,220,208 db 102,15,56,220,216 movups xmm0,[ecx*1+edx-16] - jnz NEAR L$035ccm64_dec2_loop + jnz NEAR L$036ccm64_dec2_loop movups xmm6,[esi] paddq xmm7,[16+esp] db 102,15,56,220,209 @@ -764,9 +779,9 @@ db 102,15,56,220,217 db 102,15,56,221,208 db 102,15,56,221,216 lea esi,[16+esi] - jmp NEAR L$033ccm64_dec_outer + jmp NEAR L$034ccm64_dec_outer align 16 -L$034ccm64_dec_break: +L$035ccm64_dec_break: mov ecx,DWORD [240+ebp] mov edx,ebp movups xmm0,[edx] @@ -774,12 +789,12 @@ L$034ccm64_dec_break: xorps xmm6,xmm0 lea edx,[32+edx] xorps xmm3,xmm6 -L$036enc1_loop_6: +L$037enc1_loop_6: db 102,15,56,220,217 dec ecx movups xmm1,[edx] lea edx,[16+edx] - jnz NEAR L$036enc1_loop_6 + jnz NEAR L$037enc1_loop_6 db 102,15,56,221,217 mov esp,DWORD [48+esp] mov edi,DWORD [40+esp] @@ -805,6 +820,18 @@ L$_aes_hw_ctr32_encrypt_blocks_begin: push ebx push esi push edi +%ifndef NDEBUG + push ebx + push edx + call L$038pic +L$038pic: + pop ebx + lea ebx,[(_BORINGSSL_function_hit+0-L$038pic)+ebx] + mov edx,1 + mov BYTE [ebx],dl + pop edx + pop ebx +%endif mov esi,DWORD [20+esp] mov edi,DWORD [24+esp] mov eax,DWORD [28+esp] @@ -815,7 +842,7 @@ L$_aes_hw_ctr32_encrypt_blocks_begin: and esp,-16 mov DWORD [80+esp],ebp cmp eax,1 - je NEAR L$037ctr32_one_shortcut + je NEAR L$039ctr32_one_shortcut movdqu xmm7,[ebx] mov DWORD [esp],202182159 mov DWORD [4+esp],134810123 @@ -853,7 +880,7 @@ db 102,15,56,0,202 pshufd xmm2,xmm0,192 pshufd xmm3,xmm0,128 cmp eax,6 - jb NEAR L$038ctr32_tail + jb NEAR L$040ctr32_tail pxor xmm7,xmm6 shl ecx,4 mov ebx,16 @@ -862,9 +889,9 @@ db 102,15,56,0,202 sub ebx,ecx lea edx,[32+ecx*1+edx] sub eax,6 - jmp NEAR L$039ctr32_loop6 + jmp NEAR L$041ctr32_loop6 align 16 -L$039ctr32_loop6: +L$041ctr32_loop6: pshufd xmm4,xmm0,64 movdqa xmm0,[32+esp] pshufd xmm5,xmm1,192 @@ -918,27 +945,27 @@ db 102,15,56,0,202 lea edi,[96+edi] pshufd xmm3,xmm0,128 sub eax,6 - jnc NEAR L$039ctr32_loop6 + jnc NEAR L$041ctr32_loop6 add eax,6 - jz NEAR L$040ctr32_ret + jz NEAR L$042ctr32_ret movdqu xmm7,[ebp] mov edx,ebp pxor xmm7,[32+esp] mov ecx,DWORD [240+ebp] -L$038ctr32_tail: +L$040ctr32_tail: por xmm2,xmm7 cmp eax,2 - jb NEAR L$041ctr32_one + jb NEAR L$043ctr32_one pshufd xmm4,xmm0,64 por xmm3,xmm7 - je NEAR L$042ctr32_two + je NEAR L$044ctr32_two pshufd xmm5,xmm1,192 por xmm4,xmm7 cmp eax,4 - jb NEAR L$043ctr32_three + jb NEAR L$045ctr32_three pshufd xmm6,xmm1,128 por xmm5,xmm7 - je NEAR L$044ctr32_four + je NEAR L$046ctr32_four por xmm6,xmm7 call __aesni_encrypt6 movups xmm1,[esi] @@ -956,29 +983,29 @@ L$038ctr32_tail: movups [32+edi],xmm4 movups [48+edi],xmm5 movups [64+edi],xmm6 - jmp NEAR L$040ctr32_ret + jmp NEAR L$042ctr32_ret align 16 -L$037ctr32_one_shortcut: +L$039ctr32_one_shortcut: movups xmm2,[ebx] mov ecx,DWORD [240+edx] -L$041ctr32_one: +L$043ctr32_one: movups xmm0,[edx] movups xmm1,[16+edx] lea edx,[32+edx] xorps xmm2,xmm0 -L$045enc1_loop_7: +L$047enc1_loop_7: db 102,15,56,220,209 dec ecx movups xmm1,[edx] lea edx,[16+edx] - jnz NEAR L$045enc1_loop_7 + jnz NEAR L$047enc1_loop_7 db 102,15,56,221,209 movups xmm6,[esi] xorps xmm6,xmm2 movups [edi],xmm6 - jmp NEAR L$040ctr32_ret + jmp NEAR L$042ctr32_ret align 16 -L$042ctr32_two: +L$044ctr32_two: call __aesni_encrypt2 movups xmm5,[esi] movups xmm6,[16+esi] @@ -986,9 +1013,9 @@ L$042ctr32_two: xorps xmm3,xmm6 movups [edi],xmm2 movups [16+edi],xmm3 - jmp NEAR L$040ctr32_ret + jmp NEAR L$042ctr32_ret align 16 -L$043ctr32_three: +L$045ctr32_three: call __aesni_encrypt3 movups xmm5,[esi] movups xmm6,[16+esi] @@ -999,9 +1026,9 @@ L$043ctr32_three: xorps xmm4,xmm7 movups [16+edi],xmm3 movups [32+edi],xmm4 - jmp NEAR L$040ctr32_ret + jmp NEAR L$042ctr32_ret align 16 -L$044ctr32_four: +L$046ctr32_four: call __aesni_encrypt4 movups xmm6,[esi] movups xmm7,[16+esi] @@ -1015,7 +1042,7 @@ L$044ctr32_four: xorps xmm5,xmm0 movups [32+edi],xmm4 movups [48+edi],xmm5 -L$040ctr32_ret: +L$042ctr32_ret: pxor xmm0,xmm0 pxor xmm1,xmm1 pxor xmm2,xmm2 @@ -1049,12 +1076,12 @@ L$_aes_hw_xts_encrypt_begin: movups xmm1,[16+edx] lea edx,[32+edx] xorps xmm2,xmm0 -L$046enc1_loop_8: +L$048enc1_loop_8: db 102,15,56,220,209 dec ecx movups xmm1,[edx] lea edx,[16+edx] - jnz NEAR L$046enc1_loop_8 + jnz NEAR L$048enc1_loop_8 db 102,15,56,221,209 mov esi,DWORD [20+esp] mov edi,DWORD [24+esp] @@ -1078,14 +1105,14 @@ db 102,15,56,221,209 mov ebp,edx mov ebx,ecx sub eax,96 - jc NEAR L$047xts_enc_short + jc NEAR L$049xts_enc_short shl ecx,4 mov ebx,16 sub ebx,ecx lea edx,[32+ecx*1+edx] - jmp NEAR L$048xts_enc_loop6 + jmp NEAR L$050xts_enc_loop6 align 16 -L$048xts_enc_loop6: +L$050xts_enc_loop6: pshufd xmm2,xmm0,19 pxor xmm0,xmm0 movdqa [esp],xmm1 @@ -1174,23 +1201,23 @@ db 102,15,56,220,249 pcmpgtd xmm0,xmm1 pxor xmm1,xmm2 sub eax,96 - jnc NEAR L$048xts_enc_loop6 + jnc NEAR L$050xts_enc_loop6 mov ecx,DWORD [240+ebp] mov edx,ebp mov ebx,ecx -L$047xts_enc_short: +L$049xts_enc_short: add eax,96 - jz NEAR L$049xts_enc_done6x + jz NEAR L$051xts_enc_done6x movdqa xmm5,xmm1 cmp eax,32 - jb NEAR L$050xts_enc_one + jb NEAR L$052xts_enc_one pshufd xmm2,xmm0,19 pxor xmm0,xmm0 paddq xmm1,xmm1 pand xmm2,xmm3 pcmpgtd xmm0,xmm1 pxor xmm1,xmm2 - je NEAR L$051xts_enc_two + je NEAR L$053xts_enc_two pshufd xmm2,xmm0,19 pxor xmm0,xmm0 movdqa xmm6,xmm1 @@ -1199,7 +1226,7 @@ L$047xts_enc_short: pcmpgtd xmm0,xmm1 pxor xmm1,xmm2 cmp eax,64 - jb NEAR L$052xts_enc_three + jb NEAR L$054xts_enc_three pshufd xmm2,xmm0,19 pxor xmm0,xmm0 movdqa xmm7,xmm1 @@ -1209,7 +1236,7 @@ L$047xts_enc_short: pxor xmm1,xmm2 movdqa [esp],xmm5 movdqa [16+esp],xmm6 - je NEAR L$053xts_enc_four + je NEAR L$055xts_enc_four movdqa [32+esp],xmm7 pshufd xmm7,xmm0,19 movdqa [48+esp],xmm1 @@ -1241,9 +1268,9 @@ L$047xts_enc_short: movups [48+edi],xmm5 movups [64+edi],xmm6 lea edi,[80+edi] - jmp NEAR L$054xts_enc_done + jmp NEAR L$056xts_enc_done align 16 -L$050xts_enc_one: +L$052xts_enc_one: movups xmm2,[esi] lea esi,[16+esi] xorps xmm2,xmm5 @@ -1251,20 +1278,20 @@ L$050xts_enc_one: movups xmm1,[16+edx] lea edx,[32+edx] xorps xmm2,xmm0 -L$055enc1_loop_9: +L$057enc1_loop_9: db 102,15,56,220,209 dec ecx movups xmm1,[edx] lea edx,[16+edx] - jnz NEAR L$055enc1_loop_9 + jnz NEAR L$057enc1_loop_9 db 102,15,56,221,209 xorps xmm2,xmm5 movups [edi],xmm2 lea edi,[16+edi] movdqa xmm1,xmm5 - jmp NEAR L$054xts_enc_done + jmp NEAR L$056xts_enc_done align 16 -L$051xts_enc_two: +L$053xts_enc_two: movaps xmm6,xmm1 movups xmm2,[esi] movups xmm3,[16+esi] @@ -1278,9 +1305,9 @@ L$051xts_enc_two: movups [16+edi],xmm3 lea edi,[32+edi] movdqa xmm1,xmm6 - jmp NEAR L$054xts_enc_done + jmp NEAR L$056xts_enc_done align 16 -L$052xts_enc_three: +L$054xts_enc_three: movaps xmm7,xmm1 movups xmm2,[esi] movups xmm3,[16+esi] @@ -1298,9 +1325,9 @@ L$052xts_enc_three: movups [32+edi],xmm4 lea edi,[48+edi] movdqa xmm1,xmm7 - jmp NEAR L$054xts_enc_done + jmp NEAR L$056xts_enc_done align 16 -L$053xts_enc_four: +L$055xts_enc_four: movaps xmm6,xmm1 movups xmm2,[esi] movups xmm3,[16+esi] @@ -1322,28 +1349,28 @@ L$053xts_enc_four: movups [48+edi],xmm5 lea edi,[64+edi] movdqa xmm1,xmm6 - jmp NEAR L$054xts_enc_done + jmp NEAR L$056xts_enc_done align 16 -L$049xts_enc_done6x: +L$051xts_enc_done6x: mov eax,DWORD [112+esp] and eax,15 - jz NEAR L$056xts_enc_ret + jz NEAR L$058xts_enc_ret movdqa xmm5,xmm1 mov DWORD [112+esp],eax - jmp NEAR L$057xts_enc_steal + jmp NEAR L$059xts_enc_steal align 16 -L$054xts_enc_done: +L$056xts_enc_done: mov eax,DWORD [112+esp] pxor xmm0,xmm0 and eax,15 - jz NEAR L$056xts_enc_ret + jz NEAR L$058xts_enc_ret pcmpgtd xmm0,xmm1 mov DWORD [112+esp],eax pshufd xmm5,xmm0,19 paddq xmm1,xmm1 pand xmm5,[96+esp] pxor xmm5,xmm1 -L$057xts_enc_steal: +L$059xts_enc_steal: movzx ecx,BYTE [esi] movzx edx,BYTE [edi-16] lea esi,[1+esi] @@ -1351,7 +1378,7 @@ L$057xts_enc_steal: mov BYTE [edi],dl lea edi,[1+edi] sub eax,1 - jnz NEAR L$057xts_enc_steal + jnz NEAR L$059xts_enc_steal sub edi,DWORD [112+esp] mov edx,ebp mov ecx,ebx @@ -1361,16 +1388,16 @@ L$057xts_enc_steal: movups xmm1,[16+edx] lea edx,[32+edx] xorps xmm2,xmm0 -L$058enc1_loop_10: +L$060enc1_loop_10: db 102,15,56,220,209 dec ecx movups xmm1,[edx] lea edx,[16+edx] - jnz NEAR L$058enc1_loop_10 + jnz NEAR L$060enc1_loop_10 db 102,15,56,221,209 xorps xmm2,xmm5 movups [edi-16],xmm2 -L$056xts_enc_ret: +L$058xts_enc_ret: pxor xmm0,xmm0 pxor xmm1,xmm1 pxor xmm2,xmm2 @@ -1407,12 +1434,12 @@ L$_aes_hw_xts_decrypt_begin: movups xmm1,[16+edx] lea edx,[32+edx] xorps xmm2,xmm0 -L$059enc1_loop_11: +L$061enc1_loop_11: db 102,15,56,220,209 dec ecx movups xmm1,[edx] lea edx,[16+edx] - jnz NEAR L$059enc1_loop_11 + jnz NEAR L$061enc1_loop_11 db 102,15,56,221,209 mov esi,DWORD [20+esp] mov edi,DWORD [24+esp] @@ -1441,14 +1468,14 @@ db 102,15,56,221,209 pcmpgtd xmm0,xmm1 and eax,-16 sub eax,96 - jc NEAR L$060xts_dec_short + jc NEAR L$062xts_dec_short shl ecx,4 mov ebx,16 sub ebx,ecx lea edx,[32+ecx*1+edx] - jmp NEAR L$061xts_dec_loop6 + jmp NEAR L$063xts_dec_loop6 align 16 -L$061xts_dec_loop6: +L$063xts_dec_loop6: pshufd xmm2,xmm0,19 pxor xmm0,xmm0 movdqa [esp],xmm1 @@ -1537,23 +1564,23 @@ db 102,15,56,222,249 pcmpgtd xmm0,xmm1 pxor xmm1,xmm2 sub eax,96 - jnc NEAR L$061xts_dec_loop6 + jnc NEAR L$063xts_dec_loop6 mov ecx,DWORD [240+ebp] mov edx,ebp mov ebx,ecx -L$060xts_dec_short: +L$062xts_dec_short: add eax,96 - jz NEAR L$062xts_dec_done6x + jz NEAR L$064xts_dec_done6x movdqa xmm5,xmm1 cmp eax,32 - jb NEAR L$063xts_dec_one + jb NEAR L$065xts_dec_one pshufd xmm2,xmm0,19 pxor xmm0,xmm0 paddq xmm1,xmm1 pand xmm2,xmm3 pcmpgtd xmm0,xmm1 pxor xmm1,xmm2 - je NEAR L$064xts_dec_two + je NEAR L$066xts_dec_two pshufd xmm2,xmm0,19 pxor xmm0,xmm0 movdqa xmm6,xmm1 @@ -1562,7 +1589,7 @@ L$060xts_dec_short: pcmpgtd xmm0,xmm1 pxor xmm1,xmm2 cmp eax,64 - jb NEAR L$065xts_dec_three + jb NEAR L$067xts_dec_three pshufd xmm2,xmm0,19 pxor xmm0,xmm0 movdqa xmm7,xmm1 @@ -1572,7 +1599,7 @@ L$060xts_dec_short: pxor xmm1,xmm2 movdqa [esp],xmm5 movdqa [16+esp],xmm6 - je NEAR L$066xts_dec_four + je NEAR L$068xts_dec_four movdqa [32+esp],xmm7 pshufd xmm7,xmm0,19 movdqa [48+esp],xmm1 @@ -1604,9 +1631,9 @@ L$060xts_dec_short: movups [48+edi],xmm5 movups [64+edi],xmm6 lea edi,[80+edi] - jmp NEAR L$067xts_dec_done + jmp NEAR L$069xts_dec_done align 16 -L$063xts_dec_one: +L$065xts_dec_one: movups xmm2,[esi] lea esi,[16+esi] xorps xmm2,xmm5 @@ -1614,20 +1641,20 @@ L$063xts_dec_one: movups xmm1,[16+edx] lea edx,[32+edx] xorps xmm2,xmm0 -L$068dec1_loop_12: +L$070dec1_loop_12: db 102,15,56,222,209 dec ecx movups xmm1,[edx] lea edx,[16+edx] - jnz NEAR L$068dec1_loop_12 + jnz NEAR L$070dec1_loop_12 db 102,15,56,223,209 xorps xmm2,xmm5 movups [edi],xmm2 lea edi,[16+edi] movdqa xmm1,xmm5 - jmp NEAR L$067xts_dec_done + jmp NEAR L$069xts_dec_done align 16 -L$064xts_dec_two: +L$066xts_dec_two: movaps xmm6,xmm1 movups xmm2,[esi] movups xmm3,[16+esi] @@ -1641,9 +1668,9 @@ L$064xts_dec_two: movups [16+edi],xmm3 lea edi,[32+edi] movdqa xmm1,xmm6 - jmp NEAR L$067xts_dec_done + jmp NEAR L$069xts_dec_done align 16 -L$065xts_dec_three: +L$067xts_dec_three: movaps xmm7,xmm1 movups xmm2,[esi] movups xmm3,[16+esi] @@ -1661,9 +1688,9 @@ L$065xts_dec_three: movups [32+edi],xmm4 lea edi,[48+edi] movdqa xmm1,xmm7 - jmp NEAR L$067xts_dec_done + jmp NEAR L$069xts_dec_done align 16 -L$066xts_dec_four: +L$068xts_dec_four: movaps xmm6,xmm1 movups xmm2,[esi] movups xmm3,[16+esi] @@ -1685,20 +1712,20 @@ L$066xts_dec_four: movups [48+edi],xmm5 lea edi,[64+edi] movdqa xmm1,xmm6 - jmp NEAR L$067xts_dec_done + jmp NEAR L$069xts_dec_done align 16 -L$062xts_dec_done6x: +L$064xts_dec_done6x: mov eax,DWORD [112+esp] and eax,15 - jz NEAR L$069xts_dec_ret + jz NEAR L$071xts_dec_ret mov DWORD [112+esp],eax - jmp NEAR L$070xts_dec_only_one_more + jmp NEAR L$072xts_dec_only_one_more align 16 -L$067xts_dec_done: +L$069xts_dec_done: mov eax,DWORD [112+esp] pxor xmm0,xmm0 and eax,15 - jz NEAR L$069xts_dec_ret + jz NEAR L$071xts_dec_ret pcmpgtd xmm0,xmm1 mov DWORD [112+esp],eax pshufd xmm2,xmm0,19 @@ -1708,7 +1735,7 @@ L$067xts_dec_done: pand xmm2,xmm3 pcmpgtd xmm0,xmm1 pxor xmm1,xmm2 -L$070xts_dec_only_one_more: +L$072xts_dec_only_one_more: pshufd xmm5,xmm0,19 movdqa xmm6,xmm1 paddq xmm1,xmm1 @@ -1722,16 +1749,16 @@ L$070xts_dec_only_one_more: movups xmm1,[16+edx] lea edx,[32+edx] xorps xmm2,xmm0 -L$071dec1_loop_13: +L$073dec1_loop_13: db 102,15,56,222,209 dec ecx movups xmm1,[edx] lea edx,[16+edx] - jnz NEAR L$071dec1_loop_13 + jnz NEAR L$073dec1_loop_13 db 102,15,56,223,209 xorps xmm2,xmm5 movups [edi],xmm2 -L$072xts_dec_steal: +L$074xts_dec_steal: movzx ecx,BYTE [16+esi] movzx edx,BYTE [edi] lea esi,[1+esi] @@ -1739,7 +1766,7 @@ L$072xts_dec_steal: mov BYTE [16+edi],dl lea edi,[1+edi] sub eax,1 - jnz NEAR L$072xts_dec_steal + jnz NEAR L$074xts_dec_steal sub edi,DWORD [112+esp] mov edx,ebp mov ecx,ebx @@ -1749,16 +1776,16 @@ L$072xts_dec_steal: movups xmm1,[16+edx] lea edx,[32+edx] xorps xmm2,xmm0 -L$073dec1_loop_14: +L$075dec1_loop_14: db 102,15,56,222,209 dec ecx movups xmm1,[edx] lea edx,[16+edx] - jnz NEAR L$073dec1_loop_14 + jnz NEAR L$075dec1_loop_14 db 102,15,56,223,209 xorps xmm2,xmm6 movups [edi],xmm2 -L$069xts_dec_ret: +L$071xts_dec_ret: pxor xmm0,xmm0 pxor xmm1,xmm1 pxor xmm2,xmm2 @@ -1796,7 +1823,7 @@ L$_aes_hw_cbc_encrypt_begin: mov edx,DWORD [32+esp] mov ebp,DWORD [36+esp] test eax,eax - jz NEAR L$074cbc_abort + jz NEAR L$076cbc_abort cmp DWORD [40+esp],0 xchg ebx,esp movups xmm7,[ebp] @@ -1804,14 +1831,14 @@ L$_aes_hw_cbc_encrypt_begin: mov ebp,edx mov DWORD [16+esp],ebx mov ebx,ecx - je NEAR L$075cbc_decrypt + je NEAR L$077cbc_decrypt movaps xmm2,xmm7 cmp eax,16 - jb NEAR L$076cbc_enc_tail + jb NEAR L$078cbc_enc_tail sub eax,16 - jmp NEAR L$077cbc_enc_loop + jmp NEAR L$079cbc_enc_loop align 16 -L$077cbc_enc_loop: +L$079cbc_enc_loop: movups xmm7,[esi] lea esi,[16+esi] movups xmm0,[edx] @@ -1819,25 +1846,25 @@ L$077cbc_enc_loop: xorps xmm7,xmm0 lea edx,[32+edx] xorps xmm2,xmm7 -L$078enc1_loop_15: +L$080enc1_loop_15: db 102,15,56,220,209 dec ecx movups xmm1,[edx] lea edx,[16+edx] - jnz NEAR L$078enc1_loop_15 + jnz NEAR L$080enc1_loop_15 db 102,15,56,221,209 mov ecx,ebx mov edx,ebp movups [edi],xmm2 lea edi,[16+edi] sub eax,16 - jnc NEAR L$077cbc_enc_loop + jnc NEAR L$079cbc_enc_loop add eax,16 - jnz NEAR L$076cbc_enc_tail + jnz NEAR L$078cbc_enc_tail movaps xmm7,xmm2 pxor xmm2,xmm2 - jmp NEAR L$079cbc_ret -L$076cbc_enc_tail: + jmp NEAR L$081cbc_ret +L$078cbc_enc_tail: mov ecx,eax dd 2767451785 mov ecx,16 @@ -1848,20 +1875,20 @@ dd 2868115081 mov ecx,ebx mov esi,edi mov edx,ebp - jmp NEAR L$077cbc_enc_loop + jmp NEAR L$079cbc_enc_loop align 16 -L$075cbc_decrypt: +L$077cbc_decrypt: cmp eax,80 - jbe NEAR L$080cbc_dec_tail + jbe NEAR L$082cbc_dec_tail movaps [esp],xmm7 sub eax,80 - jmp NEAR L$081cbc_dec_loop6_enter + jmp NEAR L$083cbc_dec_loop6_enter align 16 -L$082cbc_dec_loop6: +L$084cbc_dec_loop6: movaps [esp],xmm0 movups [edi],xmm7 lea edi,[16+edi] -L$081cbc_dec_loop6_enter: +L$083cbc_dec_loop6_enter: movdqu xmm2,[esi] movdqu xmm3,[16+esi] movdqu xmm4,[32+esi] @@ -1891,28 +1918,28 @@ L$081cbc_dec_loop6_enter: movups [64+edi],xmm6 lea edi,[80+edi] sub eax,96 - ja NEAR L$082cbc_dec_loop6 + ja NEAR L$084cbc_dec_loop6 movaps xmm2,xmm7 movaps xmm7,xmm0 add eax,80 - jle NEAR L$083cbc_dec_clear_tail_collected + jle NEAR L$085cbc_dec_clear_tail_collected movups [edi],xmm2 lea edi,[16+edi] -L$080cbc_dec_tail: +L$082cbc_dec_tail: movups xmm2,[esi] movaps xmm6,xmm2 cmp eax,16 - jbe NEAR L$084cbc_dec_one + jbe NEAR L$086cbc_dec_one movups xmm3,[16+esi] movaps xmm5,xmm3 cmp eax,32 - jbe NEAR L$085cbc_dec_two + jbe NEAR L$087cbc_dec_two movups xmm4,[32+esi] cmp eax,48 - jbe NEAR L$086cbc_dec_three + jbe NEAR L$088cbc_dec_three movups xmm5,[48+esi] cmp eax,64 - jbe NEAR L$087cbc_dec_four + jbe NEAR L$089cbc_dec_four movups xmm6,[64+esi] movaps [esp],xmm7 movups xmm2,[esi] @@ -1939,26 +1966,26 @@ L$080cbc_dec_tail: movaps xmm2,xmm6 pxor xmm6,xmm6 sub eax,80 - jmp NEAR L$088cbc_dec_tail_collected + jmp NEAR L$090cbc_dec_tail_collected align 16 -L$084cbc_dec_one: +L$086cbc_dec_one: movups xmm0,[edx] movups xmm1,[16+edx] lea edx,[32+edx] xorps xmm2,xmm0 -L$089dec1_loop_16: +L$091dec1_loop_16: db 102,15,56,222,209 dec ecx movups xmm1,[edx] lea edx,[16+edx] - jnz NEAR L$089dec1_loop_16 + jnz NEAR L$091dec1_loop_16 db 102,15,56,223,209 xorps xmm2,xmm7 movaps xmm7,xmm6 sub eax,16 - jmp NEAR L$088cbc_dec_tail_collected + jmp NEAR L$090cbc_dec_tail_collected align 16 -L$085cbc_dec_two: +L$087cbc_dec_two: call __aesni_decrypt2 xorps xmm2,xmm7 xorps xmm3,xmm6 @@ -1968,9 +1995,9 @@ L$085cbc_dec_two: lea edi,[16+edi] movaps xmm7,xmm5 sub eax,32 - jmp NEAR L$088cbc_dec_tail_collected + jmp NEAR L$090cbc_dec_tail_collected align 16 -L$086cbc_dec_three: +L$088cbc_dec_three: call __aesni_decrypt3 xorps xmm2,xmm7 xorps xmm3,xmm6 @@ -1983,9 +2010,9 @@ L$086cbc_dec_three: lea edi,[32+edi] movups xmm7,[32+esi] sub eax,48 - jmp NEAR L$088cbc_dec_tail_collected + jmp NEAR L$090cbc_dec_tail_collected align 16 -L$087cbc_dec_four: +L$089cbc_dec_four: call __aesni_decrypt4 movups xmm1,[16+esi] movups xmm0,[32+esi] @@ -2003,21 +2030,21 @@ L$087cbc_dec_four: movaps xmm2,xmm5 pxor xmm5,xmm5 sub eax,64 - jmp NEAR L$088cbc_dec_tail_collected + jmp NEAR L$090cbc_dec_tail_collected align 16 -L$083cbc_dec_clear_tail_collected: +L$085cbc_dec_clear_tail_collected: pxor xmm3,xmm3 pxor xmm4,xmm4 pxor xmm5,xmm5 pxor xmm6,xmm6 -L$088cbc_dec_tail_collected: +L$090cbc_dec_tail_collected: and eax,15 - jnz NEAR L$090cbc_dec_tail_partial + jnz NEAR L$092cbc_dec_tail_partial movups [edi],xmm2 pxor xmm0,xmm0 - jmp NEAR L$079cbc_ret + jmp NEAR L$081cbc_ret align 16 -L$090cbc_dec_tail_partial: +L$092cbc_dec_tail_partial: movaps [esp],xmm2 pxor xmm0,xmm0 mov ecx,16 @@ -2025,14 +2052,14 @@ L$090cbc_dec_tail_partial: sub ecx,eax dd 2767451785 movdqa [esp],xmm2 -L$079cbc_ret: +L$081cbc_ret: mov esp,DWORD [16+esp] mov ebp,DWORD [36+esp] pxor xmm2,xmm2 pxor xmm1,xmm1 movups [ebp],xmm7 pxor xmm7,xmm7 -L$074cbc_abort: +L$076cbc_abort: pop edi pop esi pop ebx @@ -2043,13 +2070,13 @@ __aesni_set_encrypt_key: push ebp push ebx test eax,eax - jz NEAR L$091bad_pointer + jz NEAR L$093bad_pointer test edx,edx - jz NEAR L$091bad_pointer - call L$092pic -L$092pic: + jz NEAR L$093bad_pointer + call L$094pic +L$094pic: pop ebx - lea ebx,[(L$key_const-L$092pic)+ebx] + lea ebx,[(L$key_const-L$094pic)+ebx] lea ebp,[_OPENSSL_ia32cap_P] movups xmm0,[eax] xorps xmm4,xmm4 @@ -2057,45 +2084,45 @@ L$092pic: lea edx,[16+edx] and ebp,268437504 cmp ecx,256 - je NEAR L$09314rounds + je NEAR L$09514rounds cmp ecx,192 - je NEAR L$09412rounds + je NEAR L$09612rounds cmp ecx,128 - jne NEAR L$095bad_keybits + jne NEAR L$097bad_keybits align 16 -L$09610rounds: +L$09810rounds: cmp ebp,268435456 - je NEAR L$09710rounds_alt + je NEAR L$09910rounds_alt mov ecx,9 movups [edx-16],xmm0 db 102,15,58,223,200,1 - call L$098key_128_cold + call L$100key_128_cold db 102,15,58,223,200,2 - call L$099key_128 + call L$101key_128 db 102,15,58,223,200,4 - call L$099key_128 + call L$101key_128 db 102,15,58,223,200,8 - call L$099key_128 + call L$101key_128 db 102,15,58,223,200,16 - call L$099key_128 + call L$101key_128 db 102,15,58,223,200,32 - call L$099key_128 + call L$101key_128 db 102,15,58,223,200,64 - call L$099key_128 + call L$101key_128 db 102,15,58,223,200,128 - call L$099key_128 + call L$101key_128 db 102,15,58,223,200,27 - call L$099key_128 + call L$101key_128 db 102,15,58,223,200,54 - call L$099key_128 + call L$101key_128 movups [edx],xmm0 mov DWORD [80+edx],ecx - jmp NEAR L$100good_key + jmp NEAR L$102good_key align 16 -L$099key_128: +L$101key_128: movups [edx],xmm0 lea edx,[16+edx] -L$098key_128_cold: +L$100key_128_cold: shufps xmm4,xmm0,16 xorps xmm0,xmm4 shufps xmm4,xmm0,140 @@ -2104,13 +2131,13 @@ L$098key_128_cold: xorps xmm0,xmm1 ret align 16 -L$09710rounds_alt: +L$09910rounds_alt: movdqa xmm5,[ebx] mov ecx,8 movdqa xmm4,[32+ebx] movdqa xmm2,xmm0 movdqu [edx-16],xmm0 -L$101loop_key128: +L$103loop_key128: db 102,15,56,0,197 db 102,15,56,221,196 pslld xmm4,1 @@ -2126,7 +2153,7 @@ db 102,15,56,221,196 movdqu [edx-16],xmm0 movdqa xmm2,xmm0 dec ecx - jnz NEAR L$101loop_key128 + jnz NEAR L$103loop_key128 movdqa xmm4,[48+ebx] db 102,15,56,0,197 db 102,15,56,221,196 @@ -2154,41 +2181,41 @@ db 102,15,56,221,196 movdqu [16+edx],xmm0 mov ecx,9 mov DWORD [96+edx],ecx - jmp NEAR L$100good_key + jmp NEAR L$102good_key align 16 -L$09412rounds: +L$09612rounds: movq xmm2,[16+eax] cmp ebp,268435456 - je NEAR L$10212rounds_alt + je NEAR L$10412rounds_alt mov ecx,11 movups [edx-16],xmm0 db 102,15,58,223,202,1 - call L$103key_192a_cold + call L$105key_192a_cold db 102,15,58,223,202,2 - call L$104key_192b + call L$106key_192b db 102,15,58,223,202,4 - call L$105key_192a + call L$107key_192a db 102,15,58,223,202,8 - call L$104key_192b + call L$106key_192b db 102,15,58,223,202,16 - call L$105key_192a + call L$107key_192a db 102,15,58,223,202,32 - call L$104key_192b + call L$106key_192b db 102,15,58,223,202,64 - call L$105key_192a + call L$107key_192a db 102,15,58,223,202,128 - call L$104key_192b + call L$106key_192b movups [edx],xmm0 mov DWORD [48+edx],ecx - jmp NEAR L$100good_key + jmp NEAR L$102good_key align 16 -L$105key_192a: +L$107key_192a: movups [edx],xmm0 lea edx,[16+edx] align 16 -L$103key_192a_cold: +L$105key_192a_cold: movaps xmm5,xmm2 -L$106key_192b_warm: +L$108key_192b_warm: shufps xmm4,xmm0,16 movdqa xmm3,xmm2 xorps xmm0,xmm4 @@ -2202,21 +2229,21 @@ L$106key_192b_warm: pxor xmm2,xmm3 ret align 16 -L$104key_192b: +L$106key_192b: movaps xmm3,xmm0 shufps xmm5,xmm0,68 movups [edx],xmm5 shufps xmm3,xmm2,78 movups [16+edx],xmm3 lea edx,[32+edx] - jmp NEAR L$106key_192b_warm + jmp NEAR L$108key_192b_warm align 16 -L$10212rounds_alt: +L$10412rounds_alt: movdqa xmm5,[16+ebx] movdqa xmm4,[32+ebx] mov ecx,8 movdqu [edx-16],xmm0 -L$107loop_key192: +L$109loop_key192: movq [edx],xmm2 movdqa xmm1,xmm2 db 102,15,56,0,213 @@ -2238,54 +2265,54 @@ db 102,15,56,221,212 pxor xmm2,xmm3 movdqu [edx-16],xmm0 dec ecx - jnz NEAR L$107loop_key192 + jnz NEAR L$109loop_key192 mov ecx,11 mov DWORD [32+edx],ecx - jmp NEAR L$100good_key + jmp NEAR L$102good_key align 16 -L$09314rounds: +L$09514rounds: movups xmm2,[16+eax] lea edx,[16+edx] cmp ebp,268435456 - je NEAR L$10814rounds_alt + je NEAR L$11014rounds_alt mov ecx,13 movups [edx-32],xmm0 movups [edx-16],xmm2 db 102,15,58,223,202,1 - call L$109key_256a_cold + call L$111key_256a_cold db 102,15,58,223,200,1 - call L$110key_256b + call L$112key_256b db 102,15,58,223,202,2 - call L$111key_256a + call L$113key_256a db 102,15,58,223,200,2 - call L$110key_256b + call L$112key_256b db 102,15,58,223,202,4 - call L$111key_256a + call L$113key_256a db 102,15,58,223,200,4 - call L$110key_256b + call L$112key_256b db 102,15,58,223,202,8 - call L$111key_256a + call L$113key_256a db 102,15,58,223,200,8 - call L$110key_256b + call L$112key_256b db 102,15,58,223,202,16 - call L$111key_256a + call L$113key_256a db 102,15,58,223,200,16 - call L$110key_256b + call L$112key_256b db 102,15,58,223,202,32 - call L$111key_256a + call L$113key_256a db 102,15,58,223,200,32 - call L$110key_256b + call L$112key_256b db 102,15,58,223,202,64 - call L$111key_256a + call L$113key_256a movups [edx],xmm0 mov DWORD [16+edx],ecx xor eax,eax - jmp NEAR L$100good_key + jmp NEAR L$102good_key align 16 -L$111key_256a: +L$113key_256a: movups [edx],xmm2 lea edx,[16+edx] -L$109key_256a_cold: +L$111key_256a_cold: shufps xmm4,xmm0,16 xorps xmm0,xmm4 shufps xmm4,xmm0,140 @@ -2294,7 +2321,7 @@ L$109key_256a_cold: xorps xmm0,xmm1 ret align 16 -L$110key_256b: +L$112key_256b: movups [edx],xmm0 lea edx,[16+edx] shufps xmm4,xmm2,16 @@ -2305,14 +2332,14 @@ L$110key_256b: xorps xmm2,xmm1 ret align 16 -L$10814rounds_alt: +L$11014rounds_alt: movdqa xmm5,[ebx] movdqa xmm4,[32+ebx] mov ecx,7 movdqu [edx-32],xmm0 movdqa xmm1,xmm2 movdqu [edx-16],xmm2 -L$112loop_key256: +L$114loop_key256: db 102,15,56,0,213 db 102,15,56,221,212 movdqa xmm3,xmm0 @@ -2326,7 +2353,7 @@ db 102,15,56,221,212 pxor xmm0,xmm2 movdqu [edx],xmm0 dec ecx - jz NEAR L$113done_key256 + jz NEAR L$115done_key256 pshufd xmm2,xmm0,255 pxor xmm3,xmm3 db 102,15,56,221,211 @@ -2341,11 +2368,11 @@ db 102,15,56,221,211 movdqu [16+edx],xmm2 lea edx,[32+edx] movdqa xmm1,xmm2 - jmp NEAR L$112loop_key256 -L$113done_key256: + jmp NEAR L$114loop_key256 +L$115done_key256: mov ecx,13 mov DWORD [16+edx],ecx -L$100good_key: +L$102good_key: pxor xmm0,xmm0 pxor xmm1,xmm1 pxor xmm2,xmm2 @@ -2357,13 +2384,13 @@ L$100good_key: pop ebp ret align 4 -L$091bad_pointer: +L$093bad_pointer: mov eax,-1 pop ebx pop ebp ret align 4 -L$095bad_keybits: +L$097bad_keybits: pxor xmm0,xmm0 mov eax,-2 pop ebx @@ -2373,6 +2400,18 @@ global _aes_hw_set_encrypt_key align 16 _aes_hw_set_encrypt_key: L$_aes_hw_set_encrypt_key_begin: +%ifndef NDEBUG + push ebx + push edx + call L$116pic +L$116pic: + pop ebx + lea ebx,[(_BORINGSSL_function_hit+3-L$116pic)+ebx] + mov edx,1 + mov BYTE [ebx],dl + pop edx + pop ebx +%endif mov eax,DWORD [4+esp] mov ecx,DWORD [8+esp] mov edx,DWORD [12+esp] @@ -2389,7 +2428,7 @@ L$_aes_hw_set_decrypt_key_begin: mov edx,DWORD [12+esp] shl ecx,4 test eax,eax - jnz NEAR L$114dec_key_ret + jnz NEAR L$117dec_key_ret lea eax,[16+ecx*1+edx] movups xmm0,[edx] movups xmm1,[eax] @@ -2397,7 +2436,7 @@ L$_aes_hw_set_decrypt_key_begin: movups [edx],xmm1 lea edx,[16+edx] lea eax,[eax-16] -L$115dec_key_inverse: +L$118dec_key_inverse: movups xmm0,[edx] movups xmm1,[eax] db 102,15,56,219,192 @@ -2407,14 +2446,14 @@ db 102,15,56,219,201 movups [16+eax],xmm0 movups [edx-16],xmm1 cmp eax,edx - ja NEAR L$115dec_key_inverse + ja NEAR L$118dec_key_inverse movups xmm0,[edx] db 102,15,56,219,192 movups [edx],xmm0 pxor xmm0,xmm0 pxor xmm1,xmm1 xor eax,eax -L$114dec_key_ret: +L$117dec_key_ret: ret align 64 L$key_const: diff --git a/third_party/boringssl/kit/win-x86/crypto/fipsmodule/ghash-ssse3-x86.asm b/third_party/boringssl/kit/win-x86/crypto/fipsmodule/ghash-ssse3-x86.asm new file mode 100644 index 00000000..1d07be0a --- /dev/null +++ b/third_party/boringssl/kit/win-x86/crypto/fipsmodule/ghash-ssse3-x86.asm @@ -0,0 +1,300 @@ +; This file is generated from a similarly-named Perl script in the BoringSSL +; source tree. Do not edit by hand. + +%ifdef BORINGSSL_PREFIX +%include "boringssl_prefix_symbols_nasm.inc" +%endif +%ifidn __OUTPUT_FORMAT__,obj +section code use32 class=code align=64 +%elifidn __OUTPUT_FORMAT__,win32 +%ifdef __YASM_VERSION_ID__ +%if __YASM_VERSION_ID__ < 01010000h +%error yasm version 1.1.0 or later needed. +%endif +; Yasm automatically includes .00 and complains about redefining it. +; https://www.tortall.net/projects/yasm/manual/html/objfmt-win32-safeseh.html +%else +$@feat.00 equ 1 +%endif +section .text code align=64 +%else +section .text code +%endif +global _gcm_gmult_ssse3 +align 16 +_gcm_gmult_ssse3: +L$_gcm_gmult_ssse3_begin: + push ebp + push ebx + push esi + push edi + mov edi,DWORD [20+esp] + mov esi,DWORD [24+esp] + movdqu xmm0,[edi] + call L$000pic_point +L$000pic_point: + pop eax + movdqa xmm7,[(L$reverse_bytes-L$000pic_point)+eax] + movdqa xmm2,[(L$low4_mask-L$000pic_point)+eax] +db 102,15,56,0,199 + movdqa xmm1,xmm2 + pandn xmm1,xmm0 + psrld xmm1,4 + pand xmm0,xmm2 + pxor xmm2,xmm2 + pxor xmm3,xmm3 + mov eax,5 +L$001loop_row_1: + movdqa xmm4,[esi] + lea esi,[16+esi] + movdqa xmm6,xmm2 +db 102,15,58,15,243,1 + movdqa xmm3,xmm6 + psrldq xmm2,1 + movdqa xmm5,xmm4 +db 102,15,56,0,224 +db 102,15,56,0,233 + pxor xmm2,xmm5 + movdqa xmm5,xmm4 + psllq xmm5,60 + movdqa xmm6,xmm5 + pslldq xmm6,8 + pxor xmm3,xmm6 + psrldq xmm5,8 + pxor xmm2,xmm5 + psrlq xmm4,4 + pxor xmm2,xmm4 + sub eax,1 + jnz NEAR L$001loop_row_1 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,5 + pxor xmm2,xmm3 + pxor xmm3,xmm3 + mov eax,5 +L$002loop_row_2: + movdqa xmm4,[esi] + lea esi,[16+esi] + movdqa xmm6,xmm2 +db 102,15,58,15,243,1 + movdqa xmm3,xmm6 + psrldq xmm2,1 + movdqa xmm5,xmm4 +db 102,15,56,0,224 +db 102,15,56,0,233 + pxor xmm2,xmm5 + movdqa xmm5,xmm4 + psllq xmm5,60 + movdqa xmm6,xmm5 + pslldq xmm6,8 + pxor xmm3,xmm6 + psrldq xmm5,8 + pxor xmm2,xmm5 + psrlq xmm4,4 + pxor xmm2,xmm4 + sub eax,1 + jnz NEAR L$002loop_row_2 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,5 + pxor xmm2,xmm3 + pxor xmm3,xmm3 + mov eax,6 +L$003loop_row_3: + movdqa xmm4,[esi] + lea esi,[16+esi] + movdqa xmm6,xmm2 +db 102,15,58,15,243,1 + movdqa xmm3,xmm6 + psrldq xmm2,1 + movdqa xmm5,xmm4 +db 102,15,56,0,224 +db 102,15,56,0,233 + pxor xmm2,xmm5 + movdqa xmm5,xmm4 + psllq xmm5,60 + movdqa xmm6,xmm5 + pslldq xmm6,8 + pxor xmm3,xmm6 + psrldq xmm5,8 + pxor xmm2,xmm5 + psrlq xmm4,4 + pxor xmm2,xmm4 + sub eax,1 + jnz NEAR L$003loop_row_3 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,5 + pxor xmm2,xmm3 + pxor xmm3,xmm3 +db 102,15,56,0,215 + movdqu [edi],xmm2 + pxor xmm0,xmm0 + pxor xmm1,xmm1 + pxor xmm2,xmm2 + pxor xmm3,xmm3 + pxor xmm4,xmm4 + pxor xmm5,xmm5 + pxor xmm6,xmm6 + pop edi + pop esi + pop ebx + pop ebp + ret +global _gcm_ghash_ssse3 +align 16 +_gcm_ghash_ssse3: +L$_gcm_ghash_ssse3_begin: + push ebp + push ebx + push esi + push edi + mov edi,DWORD [20+esp] + mov esi,DWORD [24+esp] + mov edx,DWORD [28+esp] + mov ecx,DWORD [32+esp] + movdqu xmm0,[edi] + call L$004pic_point +L$004pic_point: + pop ebx + movdqa xmm7,[(L$reverse_bytes-L$004pic_point)+ebx] + and ecx,-16 +db 102,15,56,0,199 + pxor xmm3,xmm3 +L$005loop_ghash: + movdqa xmm2,[(L$low4_mask-L$004pic_point)+ebx] + movdqu xmm1,[edx] +db 102,15,56,0,207 + pxor xmm0,xmm1 + movdqa xmm1,xmm2 + pandn xmm1,xmm0 + psrld xmm1,4 + pand xmm0,xmm2 + pxor xmm2,xmm2 + mov eax,5 +L$006loop_row_4: + movdqa xmm4,[esi] + lea esi,[16+esi] + movdqa xmm6,xmm2 +db 102,15,58,15,243,1 + movdqa xmm3,xmm6 + psrldq xmm2,1 + movdqa xmm5,xmm4 +db 102,15,56,0,224 +db 102,15,56,0,233 + pxor xmm2,xmm5 + movdqa xmm5,xmm4 + psllq xmm5,60 + movdqa xmm6,xmm5 + pslldq xmm6,8 + pxor xmm3,xmm6 + psrldq xmm5,8 + pxor xmm2,xmm5 + psrlq xmm4,4 + pxor xmm2,xmm4 + sub eax,1 + jnz NEAR L$006loop_row_4 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,5 + pxor xmm2,xmm3 + pxor xmm3,xmm3 + mov eax,5 +L$007loop_row_5: + movdqa xmm4,[esi] + lea esi,[16+esi] + movdqa xmm6,xmm2 +db 102,15,58,15,243,1 + movdqa xmm3,xmm6 + psrldq xmm2,1 + movdqa xmm5,xmm4 +db 102,15,56,0,224 +db 102,15,56,0,233 + pxor xmm2,xmm5 + movdqa xmm5,xmm4 + psllq xmm5,60 + movdqa xmm6,xmm5 + pslldq xmm6,8 + pxor xmm3,xmm6 + psrldq xmm5,8 + pxor xmm2,xmm5 + psrlq xmm4,4 + pxor xmm2,xmm4 + sub eax,1 + jnz NEAR L$007loop_row_5 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,5 + pxor xmm2,xmm3 + pxor xmm3,xmm3 + mov eax,6 +L$008loop_row_6: + movdqa xmm4,[esi] + lea esi,[16+esi] + movdqa xmm6,xmm2 +db 102,15,58,15,243,1 + movdqa xmm3,xmm6 + psrldq xmm2,1 + movdqa xmm5,xmm4 +db 102,15,56,0,224 +db 102,15,56,0,233 + pxor xmm2,xmm5 + movdqa xmm5,xmm4 + psllq xmm5,60 + movdqa xmm6,xmm5 + pslldq xmm6,8 + pxor xmm3,xmm6 + psrldq xmm5,8 + pxor xmm2,xmm5 + psrlq xmm4,4 + pxor xmm2,xmm4 + sub eax,1 + jnz NEAR L$008loop_row_6 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,5 + pxor xmm2,xmm3 + pxor xmm3,xmm3 + movdqa xmm0,xmm2 + lea esi,[esi-256] + lea edx,[16+edx] + sub ecx,16 + jnz NEAR L$005loop_ghash +db 102,15,56,0,199 + movdqu [edi],xmm0 + pxor xmm0,xmm0 + pxor xmm1,xmm1 + pxor xmm2,xmm2 + pxor xmm3,xmm3 + pxor xmm4,xmm4 + pxor xmm5,xmm5 + pxor xmm6,xmm6 + pop edi + pop esi + pop ebx + pop ebp + ret +align 16 +L$reverse_bytes: +db 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 +align 16 +L$low4_mask: +dd 252645135,252645135,252645135,252645135 diff --git a/third_party/boringssl/kit/win-x86/crypto/fipsmodule/vpaes-x86.asm b/third_party/boringssl/kit/win-x86/crypto/fipsmodule/vpaes-x86.asm index 5f1dce4e..3201b8d8 100644 --- a/third_party/boringssl/kit/win-x86/crypto/fipsmodule/vpaes-x86.asm +++ b/third_party/boringssl/kit/win-x86/crypto/fipsmodule/vpaes-x86.asm @@ -20,6 +20,9 @@ section .text code align=64 %else section .text code %endif +%ifndef NDEBUG +extern _BORINGSSL_function_hit +%endif align 64 L$_vpaes_consts: dd 218628480,235210255,168496130,67568393 @@ -471,6 +474,18 @@ L$_vpaes_set_encrypt_key_begin: push ebx push esi push edi +%ifndef NDEBUG + push ebx + push edx + call L$016pic +L$016pic: + pop ebx + lea ebx,[(_BORINGSSL_function_hit+5-L$016pic)+ebx] + mov edx,1 + mov BYTE [ebx],dl + pop edx + pop ebx +%endif mov esi,DWORD [20+esp] lea ebx,[esp-56] mov eax,DWORD [24+esp] @@ -484,9 +499,9 @@ L$_vpaes_set_encrypt_key_begin: mov DWORD [240+edx],ebx mov ecx,48 mov edi,0 - lea ebp,[(L$_vpaes_consts+0x30-L$016pic_point)] + lea ebp,[(L$_vpaes_consts+0x30-L$017pic_point)] call __vpaes_schedule_core -L$016pic_point: +L$017pic_point: mov esp,DWORD [48+esp] xor eax,eax pop edi @@ -520,9 +535,9 @@ L$_vpaes_set_decrypt_key_begin: shr ecx,1 and ecx,32 xor ecx,32 - lea ebp,[(L$_vpaes_consts+0x30-L$017pic_point)] + lea ebp,[(L$_vpaes_consts+0x30-L$018pic_point)] call __vpaes_schedule_core -L$017pic_point: +L$018pic_point: mov esp,DWORD [48+esp] xor eax,eax pop edi @@ -538,9 +553,21 @@ L$_vpaes_encrypt_begin: push ebx push esi push edi - lea ebp,[(L$_vpaes_consts+0x30-L$018pic_point)] +%ifndef NDEBUG + push ebx + push edx + call L$019pic +L$019pic: + pop ebx + lea ebx,[(_BORINGSSL_function_hit+4-L$019pic)+ebx] + mov edx,1 + mov BYTE [ebx],dl + pop edx + pop ebx +%endif + lea ebp,[(L$_vpaes_consts+0x30-L$020pic_point)] call __vpaes_preheat -L$018pic_point: +L$020pic_point: mov esi,DWORD [20+esp] lea ebx,[esp-56] mov edi,DWORD [24+esp] @@ -565,9 +592,9 @@ L$_vpaes_decrypt_begin: push ebx push esi push edi - lea ebp,[(L$_vpaes_consts+0x30-L$019pic_point)] + lea ebp,[(L$_vpaes_consts+0x30-L$021pic_point)] call __vpaes_preheat -L$019pic_point: +L$021pic_point: mov esi,DWORD [20+esp] lea ebx,[esp-56] mov edi,DWORD [24+esp] @@ -597,7 +624,7 @@ L$_vpaes_cbc_encrypt_begin: mov eax,DWORD [28+esp] mov edx,DWORD [32+esp] sub eax,16 - jc NEAR L$020cbc_abort + jc NEAR L$022cbc_abort lea ebx,[esp-56] mov ebp,DWORD [36+esp] and ebx,-16 @@ -610,14 +637,14 @@ L$_vpaes_cbc_encrypt_begin: mov DWORD [4+esp],edx mov DWORD [8+esp],ebp mov edi,eax - lea ebp,[(L$_vpaes_consts+0x30-L$021pic_point)] + lea ebp,[(L$_vpaes_consts+0x30-L$023pic_point)] call __vpaes_preheat -L$021pic_point: +L$023pic_point: cmp ecx,0 - je NEAR L$022cbc_dec_loop - jmp NEAR L$023cbc_enc_loop + je NEAR L$024cbc_dec_loop + jmp NEAR L$025cbc_enc_loop align 16 -L$023cbc_enc_loop: +L$025cbc_enc_loop: movdqu xmm0,[esi] pxor xmm0,xmm1 call __vpaes_encrypt_core @@ -627,10 +654,10 @@ L$023cbc_enc_loop: movdqu [esi*1+ebx],xmm0 lea esi,[16+esi] sub edi,16 - jnc NEAR L$023cbc_enc_loop - jmp NEAR L$024cbc_done + jnc NEAR L$025cbc_enc_loop + jmp NEAR L$026cbc_done align 16 -L$022cbc_dec_loop: +L$024cbc_dec_loop: movdqu xmm0,[esi] movdqa [16+esp],xmm1 movdqa [32+esp],xmm0 @@ -642,12 +669,12 @@ L$022cbc_dec_loop: movdqu [esi*1+ebx],xmm0 lea esi,[16+esi] sub edi,16 - jnc NEAR L$022cbc_dec_loop -L$024cbc_done: + jnc NEAR L$024cbc_dec_loop +L$026cbc_done: mov ebx,DWORD [8+esp] mov esp,DWORD [48+esp] movdqu [ebx],xmm1 -L$020cbc_abort: +L$022cbc_abort: pop edi pop esi pop ebx diff --git a/third_party/boringssl/kit/win-x86/crypto/test/trampoline-x86.asm b/third_party/boringssl/kit/win-x86/crypto/test/trampoline-x86.asm new file mode 100644 index 00000000..e5c7d3f7 --- /dev/null +++ b/third_party/boringssl/kit/win-x86/crypto/test/trampoline-x86.asm @@ -0,0 +1,164 @@ +; This file is generated from a similarly-named Perl script in the BoringSSL +; source tree. Do not edit by hand. + +%ifdef BORINGSSL_PREFIX +%include "boringssl_prefix_symbols_nasm.inc" +%endif +%ifidn __OUTPUT_FORMAT__,obj +section code use32 class=code align=64 +%elifidn __OUTPUT_FORMAT__,win32 +%ifdef __YASM_VERSION_ID__ +%if __YASM_VERSION_ID__ < 01010000h +%error yasm version 1.1.0 or later needed. +%endif +; Yasm automatically includes .00 and complains about redefining it. +; https://www.tortall.net/projects/yasm/manual/html/objfmt-win32-safeseh.html +%else +$@feat.00 equ 1 +%endif +section .text code align=64 +%else +section .text code +%endif +global _abi_test_trampoline +align 16 +_abi_test_trampoline: +L$_abi_test_trampoline_begin: + push ebp + push ebx + push esi + push edi + mov ecx,DWORD [24+esp] + mov esi,DWORD [ecx] + mov edi,DWORD [4+ecx] + mov ebx,DWORD [8+ecx] + mov ebp,DWORD [12+ecx] + sub esp,44 + mov eax,DWORD [72+esp] + xor ecx,ecx +L$000loop: + cmp ecx,DWORD [76+esp] + jae NEAR L$001loop_done + mov edx,DWORD [ecx*4+eax] + mov DWORD [ecx*4+esp],edx + add ecx,1 + jmp NEAR L$000loop +L$001loop_done: + call DWORD [64+esp] + add esp,44 + mov ecx,DWORD [24+esp] + mov DWORD [ecx],esi + mov DWORD [4+ecx],edi + mov DWORD [8+ecx],ebx + mov DWORD [12+ecx],ebp + pop edi + pop esi + pop ebx + pop ebp + ret +global _abi_test_get_and_clear_direction_flag +align 16 +_abi_test_get_and_clear_direction_flag: +L$_abi_test_get_and_clear_direction_flag_begin: + pushfd + pop eax + and eax,1024 + shr eax,10 + cld + ret +global _abi_test_set_direction_flag +align 16 +_abi_test_set_direction_flag: +L$_abi_test_set_direction_flag_begin: + std + ret +global _abi_test_clobber_eax +align 16 +_abi_test_clobber_eax: +L$_abi_test_clobber_eax_begin: + xor eax,eax + ret +global _abi_test_clobber_ebx +align 16 +_abi_test_clobber_ebx: +L$_abi_test_clobber_ebx_begin: + xor ebx,ebx + ret +global _abi_test_clobber_ecx +align 16 +_abi_test_clobber_ecx: +L$_abi_test_clobber_ecx_begin: + xor ecx,ecx + ret +global _abi_test_clobber_edx +align 16 +_abi_test_clobber_edx: +L$_abi_test_clobber_edx_begin: + xor edx,edx + ret +global _abi_test_clobber_edi +align 16 +_abi_test_clobber_edi: +L$_abi_test_clobber_edi_begin: + xor edi,edi + ret +global _abi_test_clobber_esi +align 16 +_abi_test_clobber_esi: +L$_abi_test_clobber_esi_begin: + xor esi,esi + ret +global _abi_test_clobber_ebp +align 16 +_abi_test_clobber_ebp: +L$_abi_test_clobber_ebp_begin: + xor ebp,ebp + ret +global _abi_test_clobber_xmm0 +align 16 +_abi_test_clobber_xmm0: +L$_abi_test_clobber_xmm0_begin: + pxor xmm0,xmm0 + ret +global _abi_test_clobber_xmm1 +align 16 +_abi_test_clobber_xmm1: +L$_abi_test_clobber_xmm1_begin: + pxor xmm1,xmm1 + ret +global _abi_test_clobber_xmm2 +align 16 +_abi_test_clobber_xmm2: +L$_abi_test_clobber_xmm2_begin: + pxor xmm2,xmm2 + ret +global _abi_test_clobber_xmm3 +align 16 +_abi_test_clobber_xmm3: +L$_abi_test_clobber_xmm3_begin: + pxor xmm3,xmm3 + ret +global _abi_test_clobber_xmm4 +align 16 +_abi_test_clobber_xmm4: +L$_abi_test_clobber_xmm4_begin: + pxor xmm4,xmm4 + ret +global _abi_test_clobber_xmm5 +align 16 +_abi_test_clobber_xmm5: +L$_abi_test_clobber_xmm5_begin: + pxor xmm5,xmm5 + ret +global _abi_test_clobber_xmm6 +align 16 +_abi_test_clobber_xmm6: +L$_abi_test_clobber_xmm6_begin: + pxor xmm6,xmm6 + ret +global _abi_test_clobber_xmm7 +align 16 +_abi_test_clobber_xmm7: +L$_abi_test_clobber_xmm7_begin: + pxor xmm7,xmm7 + ret diff --git a/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.asm b/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.asm index bb715a17..b512516a 100644 --- a/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.asm +++ b/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.asm @@ -601,6 +601,12 @@ $L$SEH_begin_aesni_gcm_encrypt: +%ifndef NDEBUG +%ifndef BORINGSSL_FIPS +EXTERN BORINGSSL_function_hit + mov BYTE[((BORINGSSL_function_hit+2))],1 +%endif +%endif xor r10,r10 diff --git a/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/aesni-x86_64.asm b/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/aesni-x86_64.asm index b370528c..874596d7 100644 --- a/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/aesni-x86_64.asm +++ b/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/aesni-x86_64.asm @@ -17,6 +17,12 @@ global aes_hw_encrypt ALIGN 16 aes_hw_encrypt: +%ifndef NDEBUG +%ifndef BORINGSSL_FIPS +EXTERN BORINGSSL_function_hit + mov BYTE[((BORINGSSL_function_hit+1))],1 +%endif +%endif movups xmm2,XMMWORD[rcx] mov eax,DWORD[240+r8] movups xmm0,XMMWORD[r8] @@ -898,226 +904,6 @@ $L$ecb_enc_ret: DB 0F3h,0C3h ;repret $L$SEH_end_aes_hw_ecb_encrypt: -global aes_hw_ccm64_encrypt_blocks - -ALIGN 16 -aes_hw_ccm64_encrypt_blocks: - mov QWORD[8+rsp],rdi ;WIN64 prologue - mov QWORD[16+rsp],rsi - mov rax,rsp -$L$SEH_begin_aes_hw_ccm64_encrypt_blocks: - mov rdi,rcx - mov rsi,rdx - mov rdx,r8 - mov rcx,r9 - mov r8,QWORD[40+rsp] - mov r9,QWORD[48+rsp] - - - lea rsp,[((-88))+rsp] - movaps XMMWORD[rsp],xmm6 - movaps XMMWORD[16+rsp],xmm7 - movaps XMMWORD[32+rsp],xmm8 - movaps XMMWORD[48+rsp],xmm9 -$L$ccm64_enc_body: - mov eax,DWORD[240+rcx] - movdqu xmm6,XMMWORD[r8] - movdqa xmm9,XMMWORD[$L$increment64] - movdqa xmm7,XMMWORD[$L$bswap_mask] - - shl eax,4 - mov r10d,16 - lea r11,[rcx] - movdqu xmm3,XMMWORD[r9] - movdqa xmm2,xmm6 - lea rcx,[32+rax*1+rcx] -DB 102,15,56,0,247 - sub r10,rax - jmp NEAR $L$ccm64_enc_outer -ALIGN 16 -$L$ccm64_enc_outer: - movups xmm0,XMMWORD[r11] - mov rax,r10 - movups xmm8,XMMWORD[rdi] - - xorps xmm2,xmm0 - movups xmm1,XMMWORD[16+r11] - xorps xmm0,xmm8 - xorps xmm3,xmm0 - movups xmm0,XMMWORD[32+r11] - -$L$ccm64_enc2_loop: -DB 102,15,56,220,209 -DB 102,15,56,220,217 - movups xmm1,XMMWORD[rax*1+rcx] - add rax,32 -DB 102,15,56,220,208 -DB 102,15,56,220,216 - movups xmm0,XMMWORD[((-16))+rax*1+rcx] - jnz NEAR $L$ccm64_enc2_loop -DB 102,15,56,220,209 -DB 102,15,56,220,217 - paddq xmm6,xmm9 - dec rdx -DB 102,15,56,221,208 -DB 102,15,56,221,216 - - lea rdi,[16+rdi] - xorps xmm8,xmm2 - movdqa xmm2,xmm6 - movups XMMWORD[rsi],xmm8 -DB 102,15,56,0,215 - lea rsi,[16+rsi] - jnz NEAR $L$ccm64_enc_outer - - pxor xmm0,xmm0 - pxor xmm1,xmm1 - pxor xmm2,xmm2 - movups XMMWORD[r9],xmm3 - pxor xmm3,xmm3 - pxor xmm8,xmm8 - pxor xmm6,xmm6 - movaps xmm6,XMMWORD[rsp] - movaps XMMWORD[rsp],xmm0 - movaps xmm7,XMMWORD[16+rsp] - movaps XMMWORD[16+rsp],xmm0 - movaps xmm8,XMMWORD[32+rsp] - movaps XMMWORD[32+rsp],xmm0 - movaps xmm9,XMMWORD[48+rsp] - movaps XMMWORD[48+rsp],xmm0 - lea rsp,[88+rsp] -$L$ccm64_enc_ret: - mov rdi,QWORD[8+rsp] ;WIN64 epilogue - mov rsi,QWORD[16+rsp] - DB 0F3h,0C3h ;repret -$L$SEH_end_aes_hw_ccm64_encrypt_blocks: -global aes_hw_ccm64_decrypt_blocks - -ALIGN 16 -aes_hw_ccm64_decrypt_blocks: - mov QWORD[8+rsp],rdi ;WIN64 prologue - mov QWORD[16+rsp],rsi - mov rax,rsp -$L$SEH_begin_aes_hw_ccm64_decrypt_blocks: - mov rdi,rcx - mov rsi,rdx - mov rdx,r8 - mov rcx,r9 - mov r8,QWORD[40+rsp] - mov r9,QWORD[48+rsp] - - - lea rsp,[((-88))+rsp] - movaps XMMWORD[rsp],xmm6 - movaps XMMWORD[16+rsp],xmm7 - movaps XMMWORD[32+rsp],xmm8 - movaps XMMWORD[48+rsp],xmm9 -$L$ccm64_dec_body: - mov eax,DWORD[240+rcx] - movups xmm6,XMMWORD[r8] - movdqu xmm3,XMMWORD[r9] - movdqa xmm9,XMMWORD[$L$increment64] - movdqa xmm7,XMMWORD[$L$bswap_mask] - - movaps xmm2,xmm6 - mov r10d,eax - mov r11,rcx -DB 102,15,56,0,247 - movups xmm0,XMMWORD[rcx] - movups xmm1,XMMWORD[16+rcx] - lea rcx,[32+rcx] - xorps xmm2,xmm0 -$L$oop_enc1_5: -DB 102,15,56,220,209 - dec eax - movups xmm1,XMMWORD[rcx] - lea rcx,[16+rcx] - jnz NEAR $L$oop_enc1_5 -DB 102,15,56,221,209 - shl r10d,4 - mov eax,16 - movups xmm8,XMMWORD[rdi] - paddq xmm6,xmm9 - lea rdi,[16+rdi] - sub rax,r10 - lea rcx,[32+r10*1+r11] - mov r10,rax - jmp NEAR $L$ccm64_dec_outer -ALIGN 16 -$L$ccm64_dec_outer: - xorps xmm8,xmm2 - movdqa xmm2,xmm6 - movups XMMWORD[rsi],xmm8 - lea rsi,[16+rsi] -DB 102,15,56,0,215 - - sub rdx,1 - jz NEAR $L$ccm64_dec_break - - movups xmm0,XMMWORD[r11] - mov rax,r10 - movups xmm1,XMMWORD[16+r11] - xorps xmm8,xmm0 - xorps xmm2,xmm0 - xorps xmm3,xmm8 - movups xmm0,XMMWORD[32+r11] - jmp NEAR $L$ccm64_dec2_loop -ALIGN 16 -$L$ccm64_dec2_loop: -DB 102,15,56,220,209 -DB 102,15,56,220,217 - movups xmm1,XMMWORD[rax*1+rcx] - add rax,32 -DB 102,15,56,220,208 -DB 102,15,56,220,216 - movups xmm0,XMMWORD[((-16))+rax*1+rcx] - jnz NEAR $L$ccm64_dec2_loop - movups xmm8,XMMWORD[rdi] - paddq xmm6,xmm9 -DB 102,15,56,220,209 -DB 102,15,56,220,217 -DB 102,15,56,221,208 -DB 102,15,56,221,216 - lea rdi,[16+rdi] - jmp NEAR $L$ccm64_dec_outer - -ALIGN 16 -$L$ccm64_dec_break: - - mov eax,DWORD[240+r11] - movups xmm0,XMMWORD[r11] - movups xmm1,XMMWORD[16+r11] - xorps xmm8,xmm0 - lea r11,[32+r11] - xorps xmm3,xmm8 -$L$oop_enc1_6: -DB 102,15,56,220,217 - dec eax - movups xmm1,XMMWORD[r11] - lea r11,[16+r11] - jnz NEAR $L$oop_enc1_6 -DB 102,15,56,221,217 - pxor xmm0,xmm0 - pxor xmm1,xmm1 - pxor xmm2,xmm2 - movups XMMWORD[r9],xmm3 - pxor xmm3,xmm3 - pxor xmm8,xmm8 - pxor xmm6,xmm6 - movaps xmm6,XMMWORD[rsp] - movaps XMMWORD[rsp],xmm0 - movaps xmm7,XMMWORD[16+rsp] - movaps XMMWORD[16+rsp],xmm0 - movaps xmm8,XMMWORD[32+rsp] - movaps XMMWORD[32+rsp],xmm0 - movaps xmm9,XMMWORD[48+rsp] - movaps XMMWORD[48+rsp],xmm0 - lea rsp,[88+rsp] -$L$ccm64_dec_ret: - mov rdi,QWORD[8+rsp] ;WIN64 epilogue - mov rsi,QWORD[16+rsp] - DB 0F3h,0C3h ;repret -$L$SEH_end_aes_hw_ccm64_decrypt_blocks: global aes_hw_ctr32_encrypt_blocks ALIGN 16 @@ -1134,6 +920,11 @@ $L$SEH_begin_aes_hw_ctr32_encrypt_blocks: +%ifndef NDEBUG +%ifndef BORINGSSL_FIPS + mov BYTE[BORINGSSL_function_hit],1 +%endif +%endif cmp rdx,1 jne NEAR $L$ctr32_bulk @@ -1146,12 +937,12 @@ $L$SEH_begin_aes_hw_ctr32_encrypt_blocks: movups xmm1,XMMWORD[16+rcx] lea rcx,[32+rcx] xorps xmm2,xmm0 -$L$oop_enc1_7: +$L$oop_enc1_5: DB 102,15,56,220,209 dec edx movups xmm1,XMMWORD[rcx] lea rcx,[16+rcx] - jnz NEAR $L$oop_enc1_7 + jnz NEAR $L$oop_enc1_5 DB 102,15,56,221,209 pxor xmm0,xmm0 pxor xmm1,xmm1 @@ -1731,1967 +1522,6 @@ $L$ctr32_epilogue: DB 0F3h,0C3h ;repret $L$SEH_end_aes_hw_ctr32_encrypt_blocks: -global aes_hw_xts_encrypt - -ALIGN 16 -aes_hw_xts_encrypt: - mov QWORD[8+rsp],rdi ;WIN64 prologue - mov QWORD[16+rsp],rsi - mov rax,rsp -$L$SEH_begin_aes_hw_xts_encrypt: - mov rdi,rcx - mov rsi,rdx - mov rdx,r8 - mov rcx,r9 - mov r8,QWORD[40+rsp] - mov r9,QWORD[48+rsp] - - - - lea r11,[rsp] - - push rbp - - sub rsp,272 - and rsp,-16 - movaps XMMWORD[(-168)+r11],xmm6 - movaps XMMWORD[(-152)+r11],xmm7 - movaps XMMWORD[(-136)+r11],xmm8 - movaps XMMWORD[(-120)+r11],xmm9 - movaps XMMWORD[(-104)+r11],xmm10 - movaps XMMWORD[(-88)+r11],xmm11 - movaps XMMWORD[(-72)+r11],xmm12 - movaps XMMWORD[(-56)+r11],xmm13 - movaps XMMWORD[(-40)+r11],xmm14 - movaps XMMWORD[(-24)+r11],xmm15 -$L$xts_enc_body: - movups xmm2,XMMWORD[r9] - mov eax,DWORD[240+r8] - mov r10d,DWORD[240+rcx] - movups xmm0,XMMWORD[r8] - movups xmm1,XMMWORD[16+r8] - lea r8,[32+r8] - xorps xmm2,xmm0 -$L$oop_enc1_8: -DB 102,15,56,220,209 - dec eax - movups xmm1,XMMWORD[r8] - lea r8,[16+r8] - jnz NEAR $L$oop_enc1_8 -DB 102,15,56,221,209 - movups xmm0,XMMWORD[rcx] - mov rbp,rcx - mov eax,r10d - shl r10d,4 - mov r9,rdx - and rdx,-16 - - movups xmm1,XMMWORD[16+r10*1+rcx] - - movdqa xmm8,XMMWORD[$L$xts_magic] - movdqa xmm15,xmm2 - pshufd xmm9,xmm2,0x5f - pxor xmm1,xmm0 - movdqa xmm14,xmm9 - paddd xmm9,xmm9 - movdqa xmm10,xmm15 - psrad xmm14,31 - paddq xmm15,xmm15 - pand xmm14,xmm8 - pxor xmm10,xmm0 - pxor xmm15,xmm14 - movdqa xmm14,xmm9 - paddd xmm9,xmm9 - movdqa xmm11,xmm15 - psrad xmm14,31 - paddq xmm15,xmm15 - pand xmm14,xmm8 - pxor xmm11,xmm0 - pxor xmm15,xmm14 - movdqa xmm14,xmm9 - paddd xmm9,xmm9 - movdqa xmm12,xmm15 - psrad xmm14,31 - paddq xmm15,xmm15 - pand xmm14,xmm8 - pxor xmm12,xmm0 - pxor xmm15,xmm14 - movdqa xmm14,xmm9 - paddd xmm9,xmm9 - movdqa xmm13,xmm15 - psrad xmm14,31 - paddq xmm15,xmm15 - pand xmm14,xmm8 - pxor xmm13,xmm0 - pxor xmm15,xmm14 - movdqa xmm14,xmm15 - psrad xmm9,31 - paddq xmm15,xmm15 - pand xmm9,xmm8 - pxor xmm14,xmm0 - pxor xmm15,xmm9 - movaps XMMWORD[96+rsp],xmm1 - - sub rdx,16*6 - jc NEAR $L$xts_enc_short - - mov eax,16+96 - lea rcx,[32+r10*1+rbp] - sub rax,r10 - movups xmm1,XMMWORD[16+rbp] - mov r10,rax - lea r8,[$L$xts_magic] - jmp NEAR $L$xts_enc_grandloop - -ALIGN 32 -$L$xts_enc_grandloop: - movdqu xmm2,XMMWORD[rdi] - movdqa xmm8,xmm0 - movdqu xmm3,XMMWORD[16+rdi] - pxor xmm2,xmm10 - movdqu xmm4,XMMWORD[32+rdi] - pxor xmm3,xmm11 -DB 102,15,56,220,209 - movdqu xmm5,XMMWORD[48+rdi] - pxor xmm4,xmm12 -DB 102,15,56,220,217 - movdqu xmm6,XMMWORD[64+rdi] - pxor xmm5,xmm13 -DB 102,15,56,220,225 - movdqu xmm7,XMMWORD[80+rdi] - pxor xmm8,xmm15 - movdqa xmm9,XMMWORD[96+rsp] - pxor xmm6,xmm14 -DB 102,15,56,220,233 - movups xmm0,XMMWORD[32+rbp] - lea rdi,[96+rdi] - pxor xmm7,xmm8 - - pxor xmm10,xmm9 -DB 102,15,56,220,241 - pxor xmm11,xmm9 - movdqa XMMWORD[rsp],xmm10 -DB 102,15,56,220,249 - movups xmm1,XMMWORD[48+rbp] - pxor xmm12,xmm9 - -DB 102,15,56,220,208 - pxor xmm13,xmm9 - movdqa XMMWORD[16+rsp],xmm11 -DB 102,15,56,220,216 - pxor xmm14,xmm9 - movdqa XMMWORD[32+rsp],xmm12 -DB 102,15,56,220,224 -DB 102,15,56,220,232 - pxor xmm8,xmm9 - movdqa XMMWORD[64+rsp],xmm14 -DB 102,15,56,220,240 -DB 102,15,56,220,248 - movups xmm0,XMMWORD[64+rbp] - movdqa XMMWORD[80+rsp],xmm8 - pshufd xmm9,xmm15,0x5f - jmp NEAR $L$xts_enc_loop6 -ALIGN 32 -$L$xts_enc_loop6: -DB 102,15,56,220,209 -DB 102,15,56,220,217 -DB 102,15,56,220,225 -DB 102,15,56,220,233 -DB 102,15,56,220,241 -DB 102,15,56,220,249 - movups xmm1,XMMWORD[((-64))+rax*1+rcx] - add rax,32 - -DB 102,15,56,220,208 -DB 102,15,56,220,216 -DB 102,15,56,220,224 -DB 102,15,56,220,232 -DB 102,15,56,220,240 -DB 102,15,56,220,248 - movups xmm0,XMMWORD[((-80))+rax*1+rcx] - jnz NEAR $L$xts_enc_loop6 - - movdqa xmm8,XMMWORD[r8] - movdqa xmm14,xmm9 - paddd xmm9,xmm9 -DB 102,15,56,220,209 - paddq xmm15,xmm15 - psrad xmm14,31 -DB 102,15,56,220,217 - pand xmm14,xmm8 - movups xmm10,XMMWORD[rbp] -DB 102,15,56,220,225 -DB 102,15,56,220,233 -DB 102,15,56,220,241 - pxor xmm15,xmm14 - movaps xmm11,xmm10 -DB 102,15,56,220,249 - movups xmm1,XMMWORD[((-64))+rcx] - - movdqa xmm14,xmm9 -DB 102,15,56,220,208 - paddd xmm9,xmm9 - pxor xmm10,xmm15 -DB 102,15,56,220,216 - psrad xmm14,31 - paddq xmm15,xmm15 -DB 102,15,56,220,224 -DB 102,15,56,220,232 - pand xmm14,xmm8 - movaps xmm12,xmm11 -DB 102,15,56,220,240 - pxor xmm15,xmm14 - movdqa xmm14,xmm9 -DB 102,15,56,220,248 - movups xmm0,XMMWORD[((-48))+rcx] - - paddd xmm9,xmm9 -DB 102,15,56,220,209 - pxor xmm11,xmm15 - psrad xmm14,31 -DB 102,15,56,220,217 - paddq xmm15,xmm15 - pand xmm14,xmm8 -DB 102,15,56,220,225 -DB 102,15,56,220,233 - movdqa XMMWORD[48+rsp],xmm13 - pxor xmm15,xmm14 -DB 102,15,56,220,241 - movaps xmm13,xmm12 - movdqa xmm14,xmm9 -DB 102,15,56,220,249 - movups xmm1,XMMWORD[((-32))+rcx] - - paddd xmm9,xmm9 -DB 102,15,56,220,208 - pxor xmm12,xmm15 - psrad xmm14,31 -DB 102,15,56,220,216 - paddq xmm15,xmm15 - pand xmm14,xmm8 -DB 102,15,56,220,224 -DB 102,15,56,220,232 -DB 102,15,56,220,240 - pxor xmm15,xmm14 - movaps xmm14,xmm13 -DB 102,15,56,220,248 - - movdqa xmm0,xmm9 - paddd xmm9,xmm9 -DB 102,15,56,220,209 - pxor xmm13,xmm15 - psrad xmm0,31 -DB 102,15,56,220,217 - paddq xmm15,xmm15 - pand xmm0,xmm8 -DB 102,15,56,220,225 -DB 102,15,56,220,233 - pxor xmm15,xmm0 - movups xmm0,XMMWORD[rbp] -DB 102,15,56,220,241 -DB 102,15,56,220,249 - movups xmm1,XMMWORD[16+rbp] - - pxor xmm14,xmm15 -DB 102,15,56,221,84,36,0 - psrad xmm9,31 - paddq xmm15,xmm15 -DB 102,15,56,221,92,36,16 -DB 102,15,56,221,100,36,32 - pand xmm9,xmm8 - mov rax,r10 -DB 102,15,56,221,108,36,48 -DB 102,15,56,221,116,36,64 -DB 102,15,56,221,124,36,80 - pxor xmm15,xmm9 - - lea rsi,[96+rsi] - movups XMMWORD[(-96)+rsi],xmm2 - movups XMMWORD[(-80)+rsi],xmm3 - movups XMMWORD[(-64)+rsi],xmm4 - movups XMMWORD[(-48)+rsi],xmm5 - movups XMMWORD[(-32)+rsi],xmm6 - movups XMMWORD[(-16)+rsi],xmm7 - sub rdx,16*6 - jnc NEAR $L$xts_enc_grandloop - - mov eax,16+96 - sub eax,r10d - mov rcx,rbp - shr eax,4 - -$L$xts_enc_short: - - mov r10d,eax - pxor xmm10,xmm0 - add rdx,16*6 - jz NEAR $L$xts_enc_done - - pxor xmm11,xmm0 - cmp rdx,0x20 - jb NEAR $L$xts_enc_one - pxor xmm12,xmm0 - je NEAR $L$xts_enc_two - - pxor xmm13,xmm0 - cmp rdx,0x40 - jb NEAR $L$xts_enc_three - pxor xmm14,xmm0 - je NEAR $L$xts_enc_four - - movdqu xmm2,XMMWORD[rdi] - movdqu xmm3,XMMWORD[16+rdi] - movdqu xmm4,XMMWORD[32+rdi] - pxor xmm2,xmm10 - movdqu xmm5,XMMWORD[48+rdi] - pxor xmm3,xmm11 - movdqu xmm6,XMMWORD[64+rdi] - lea rdi,[80+rdi] - pxor xmm4,xmm12 - pxor xmm5,xmm13 - pxor xmm6,xmm14 - pxor xmm7,xmm7 - - call _aesni_encrypt6 - - xorps xmm2,xmm10 - movdqa xmm10,xmm15 - xorps xmm3,xmm11 - xorps xmm4,xmm12 - movdqu XMMWORD[rsi],xmm2 - xorps xmm5,xmm13 - movdqu XMMWORD[16+rsi],xmm3 - xorps xmm6,xmm14 - movdqu XMMWORD[32+rsi],xmm4 - movdqu XMMWORD[48+rsi],xmm5 - movdqu XMMWORD[64+rsi],xmm6 - lea rsi,[80+rsi] - jmp NEAR $L$xts_enc_done - -ALIGN 16 -$L$xts_enc_one: - movups xmm2,XMMWORD[rdi] - lea rdi,[16+rdi] - xorps xmm2,xmm10 - movups xmm0,XMMWORD[rcx] - movups xmm1,XMMWORD[16+rcx] - lea rcx,[32+rcx] - xorps xmm2,xmm0 -$L$oop_enc1_9: -DB 102,15,56,220,209 - dec eax - movups xmm1,XMMWORD[rcx] - lea rcx,[16+rcx] - jnz NEAR $L$oop_enc1_9 -DB 102,15,56,221,209 - xorps xmm2,xmm10 - movdqa xmm10,xmm11 - movups XMMWORD[rsi],xmm2 - lea rsi,[16+rsi] - jmp NEAR $L$xts_enc_done - -ALIGN 16 -$L$xts_enc_two: - movups xmm2,XMMWORD[rdi] - movups xmm3,XMMWORD[16+rdi] - lea rdi,[32+rdi] - xorps xmm2,xmm10 - xorps xmm3,xmm11 - - call _aesni_encrypt2 - - xorps xmm2,xmm10 - movdqa xmm10,xmm12 - xorps xmm3,xmm11 - movups XMMWORD[rsi],xmm2 - movups XMMWORD[16+rsi],xmm3 - lea rsi,[32+rsi] - jmp NEAR $L$xts_enc_done - -ALIGN 16 -$L$xts_enc_three: - movups xmm2,XMMWORD[rdi] - movups xmm3,XMMWORD[16+rdi] - movups xmm4,XMMWORD[32+rdi] - lea rdi,[48+rdi] - xorps xmm2,xmm10 - xorps xmm3,xmm11 - xorps xmm4,xmm12 - - call _aesni_encrypt3 - - xorps xmm2,xmm10 - movdqa xmm10,xmm13 - xorps xmm3,xmm11 - xorps xmm4,xmm12 - movups XMMWORD[rsi],xmm2 - movups XMMWORD[16+rsi],xmm3 - movups XMMWORD[32+rsi],xmm4 - lea rsi,[48+rsi] - jmp NEAR $L$xts_enc_done - -ALIGN 16 -$L$xts_enc_four: - movups xmm2,XMMWORD[rdi] - movups xmm3,XMMWORD[16+rdi] - movups xmm4,XMMWORD[32+rdi] - xorps xmm2,xmm10 - movups xmm5,XMMWORD[48+rdi] - lea rdi,[64+rdi] - xorps xmm3,xmm11 - xorps xmm4,xmm12 - xorps xmm5,xmm13 - - call _aesni_encrypt4 - - pxor xmm2,xmm10 - movdqa xmm10,xmm14 - pxor xmm3,xmm11 - pxor xmm4,xmm12 - movdqu XMMWORD[rsi],xmm2 - pxor xmm5,xmm13 - movdqu XMMWORD[16+rsi],xmm3 - movdqu XMMWORD[32+rsi],xmm4 - movdqu XMMWORD[48+rsi],xmm5 - lea rsi,[64+rsi] - jmp NEAR $L$xts_enc_done - -ALIGN 16 -$L$xts_enc_done: - and r9,15 - jz NEAR $L$xts_enc_ret - mov rdx,r9 - -$L$xts_enc_steal: - movzx eax,BYTE[rdi] - movzx ecx,BYTE[((-16))+rsi] - lea rdi,[1+rdi] - mov BYTE[((-16))+rsi],al - mov BYTE[rsi],cl - lea rsi,[1+rsi] - sub rdx,1 - jnz NEAR $L$xts_enc_steal - - sub rsi,r9 - mov rcx,rbp - mov eax,r10d - - movups xmm2,XMMWORD[((-16))+rsi] - xorps xmm2,xmm10 - movups xmm0,XMMWORD[rcx] - movups xmm1,XMMWORD[16+rcx] - lea rcx,[32+rcx] - xorps xmm2,xmm0 -$L$oop_enc1_10: -DB 102,15,56,220,209 - dec eax - movups xmm1,XMMWORD[rcx] - lea rcx,[16+rcx] - jnz NEAR $L$oop_enc1_10 -DB 102,15,56,221,209 - xorps xmm2,xmm10 - movups XMMWORD[(-16)+rsi],xmm2 - -$L$xts_enc_ret: - xorps xmm0,xmm0 - pxor xmm1,xmm1 - pxor xmm2,xmm2 - pxor xmm3,xmm3 - pxor xmm4,xmm4 - pxor xmm5,xmm5 - movaps xmm6,XMMWORD[((-168))+r11] - movaps XMMWORD[(-168)+r11],xmm0 - movaps xmm7,XMMWORD[((-152))+r11] - movaps XMMWORD[(-152)+r11],xmm0 - movaps xmm8,XMMWORD[((-136))+r11] - movaps XMMWORD[(-136)+r11],xmm0 - movaps xmm9,XMMWORD[((-120))+r11] - movaps XMMWORD[(-120)+r11],xmm0 - movaps xmm10,XMMWORD[((-104))+r11] - movaps XMMWORD[(-104)+r11],xmm0 - movaps xmm11,XMMWORD[((-88))+r11] - movaps XMMWORD[(-88)+r11],xmm0 - movaps xmm12,XMMWORD[((-72))+r11] - movaps XMMWORD[(-72)+r11],xmm0 - movaps xmm13,XMMWORD[((-56))+r11] - movaps XMMWORD[(-56)+r11],xmm0 - movaps xmm14,XMMWORD[((-40))+r11] - movaps XMMWORD[(-40)+r11],xmm0 - movaps xmm15,XMMWORD[((-24))+r11] - movaps XMMWORD[(-24)+r11],xmm0 - movaps XMMWORD[rsp],xmm0 - movaps XMMWORD[16+rsp],xmm0 - movaps XMMWORD[32+rsp],xmm0 - movaps XMMWORD[48+rsp],xmm0 - movaps XMMWORD[64+rsp],xmm0 - movaps XMMWORD[80+rsp],xmm0 - movaps XMMWORD[96+rsp],xmm0 - mov rbp,QWORD[((-8))+r11] - - lea rsp,[r11] - -$L$xts_enc_epilogue: - mov rdi,QWORD[8+rsp] ;WIN64 epilogue - mov rsi,QWORD[16+rsp] - DB 0F3h,0C3h ;repret - -$L$SEH_end_aes_hw_xts_encrypt: -global aes_hw_xts_decrypt - -ALIGN 16 -aes_hw_xts_decrypt: - mov QWORD[8+rsp],rdi ;WIN64 prologue - mov QWORD[16+rsp],rsi - mov rax,rsp -$L$SEH_begin_aes_hw_xts_decrypt: - mov rdi,rcx - mov rsi,rdx - mov rdx,r8 - mov rcx,r9 - mov r8,QWORD[40+rsp] - mov r9,QWORD[48+rsp] - - - - lea r11,[rsp] - - push rbp - - sub rsp,272 - and rsp,-16 - movaps XMMWORD[(-168)+r11],xmm6 - movaps XMMWORD[(-152)+r11],xmm7 - movaps XMMWORD[(-136)+r11],xmm8 - movaps XMMWORD[(-120)+r11],xmm9 - movaps XMMWORD[(-104)+r11],xmm10 - movaps XMMWORD[(-88)+r11],xmm11 - movaps XMMWORD[(-72)+r11],xmm12 - movaps XMMWORD[(-56)+r11],xmm13 - movaps XMMWORD[(-40)+r11],xmm14 - movaps XMMWORD[(-24)+r11],xmm15 -$L$xts_dec_body: - movups xmm2,XMMWORD[r9] - mov eax,DWORD[240+r8] - mov r10d,DWORD[240+rcx] - movups xmm0,XMMWORD[r8] - movups xmm1,XMMWORD[16+r8] - lea r8,[32+r8] - xorps xmm2,xmm0 -$L$oop_enc1_11: -DB 102,15,56,220,209 - dec eax - movups xmm1,XMMWORD[r8] - lea r8,[16+r8] - jnz NEAR $L$oop_enc1_11 -DB 102,15,56,221,209 - xor eax,eax - test rdx,15 - setnz al - shl rax,4 - sub rdx,rax - - movups xmm0,XMMWORD[rcx] - mov rbp,rcx - mov eax,r10d - shl r10d,4 - mov r9,rdx - and rdx,-16 - - movups xmm1,XMMWORD[16+r10*1+rcx] - - movdqa xmm8,XMMWORD[$L$xts_magic] - movdqa xmm15,xmm2 - pshufd xmm9,xmm2,0x5f - pxor xmm1,xmm0 - movdqa xmm14,xmm9 - paddd xmm9,xmm9 - movdqa xmm10,xmm15 - psrad xmm14,31 - paddq xmm15,xmm15 - pand xmm14,xmm8 - pxor xmm10,xmm0 - pxor xmm15,xmm14 - movdqa xmm14,xmm9 - paddd xmm9,xmm9 - movdqa xmm11,xmm15 - psrad xmm14,31 - paddq xmm15,xmm15 - pand xmm14,xmm8 - pxor xmm11,xmm0 - pxor xmm15,xmm14 - movdqa xmm14,xmm9 - paddd xmm9,xmm9 - movdqa xmm12,xmm15 - psrad xmm14,31 - paddq xmm15,xmm15 - pand xmm14,xmm8 - pxor xmm12,xmm0 - pxor xmm15,xmm14 - movdqa xmm14,xmm9 - paddd xmm9,xmm9 - movdqa xmm13,xmm15 - psrad xmm14,31 - paddq xmm15,xmm15 - pand xmm14,xmm8 - pxor xmm13,xmm0 - pxor xmm15,xmm14 - movdqa xmm14,xmm15 - psrad xmm9,31 - paddq xmm15,xmm15 - pand xmm9,xmm8 - pxor xmm14,xmm0 - pxor xmm15,xmm9 - movaps XMMWORD[96+rsp],xmm1 - - sub rdx,16*6 - jc NEAR $L$xts_dec_short - - mov eax,16+96 - lea rcx,[32+r10*1+rbp] - sub rax,r10 - movups xmm1,XMMWORD[16+rbp] - mov r10,rax - lea r8,[$L$xts_magic] - jmp NEAR $L$xts_dec_grandloop - -ALIGN 32 -$L$xts_dec_grandloop: - movdqu xmm2,XMMWORD[rdi] - movdqa xmm8,xmm0 - movdqu xmm3,XMMWORD[16+rdi] - pxor xmm2,xmm10 - movdqu xmm4,XMMWORD[32+rdi] - pxor xmm3,xmm11 -DB 102,15,56,222,209 - movdqu xmm5,XMMWORD[48+rdi] - pxor xmm4,xmm12 -DB 102,15,56,222,217 - movdqu xmm6,XMMWORD[64+rdi] - pxor xmm5,xmm13 -DB 102,15,56,222,225 - movdqu xmm7,XMMWORD[80+rdi] - pxor xmm8,xmm15 - movdqa xmm9,XMMWORD[96+rsp] - pxor xmm6,xmm14 -DB 102,15,56,222,233 - movups xmm0,XMMWORD[32+rbp] - lea rdi,[96+rdi] - pxor xmm7,xmm8 - - pxor xmm10,xmm9 -DB 102,15,56,222,241 - pxor xmm11,xmm9 - movdqa XMMWORD[rsp],xmm10 -DB 102,15,56,222,249 - movups xmm1,XMMWORD[48+rbp] - pxor xmm12,xmm9 - -DB 102,15,56,222,208 - pxor xmm13,xmm9 - movdqa XMMWORD[16+rsp],xmm11 -DB 102,15,56,222,216 - pxor xmm14,xmm9 - movdqa XMMWORD[32+rsp],xmm12 -DB 102,15,56,222,224 -DB 102,15,56,222,232 - pxor xmm8,xmm9 - movdqa XMMWORD[64+rsp],xmm14 -DB 102,15,56,222,240 -DB 102,15,56,222,248 - movups xmm0,XMMWORD[64+rbp] - movdqa XMMWORD[80+rsp],xmm8 - pshufd xmm9,xmm15,0x5f - jmp NEAR $L$xts_dec_loop6 -ALIGN 32 -$L$xts_dec_loop6: -DB 102,15,56,222,209 -DB 102,15,56,222,217 -DB 102,15,56,222,225 -DB 102,15,56,222,233 -DB 102,15,56,222,241 -DB 102,15,56,222,249 - movups xmm1,XMMWORD[((-64))+rax*1+rcx] - add rax,32 - -DB 102,15,56,222,208 -DB 102,15,56,222,216 -DB 102,15,56,222,224 -DB 102,15,56,222,232 -DB 102,15,56,222,240 -DB 102,15,56,222,248 - movups xmm0,XMMWORD[((-80))+rax*1+rcx] - jnz NEAR $L$xts_dec_loop6 - - movdqa xmm8,XMMWORD[r8] - movdqa xmm14,xmm9 - paddd xmm9,xmm9 -DB 102,15,56,222,209 - paddq xmm15,xmm15 - psrad xmm14,31 -DB 102,15,56,222,217 - pand xmm14,xmm8 - movups xmm10,XMMWORD[rbp] -DB 102,15,56,222,225 -DB 102,15,56,222,233 -DB 102,15,56,222,241 - pxor xmm15,xmm14 - movaps xmm11,xmm10 -DB 102,15,56,222,249 - movups xmm1,XMMWORD[((-64))+rcx] - - movdqa xmm14,xmm9 -DB 102,15,56,222,208 - paddd xmm9,xmm9 - pxor xmm10,xmm15 -DB 102,15,56,222,216 - psrad xmm14,31 - paddq xmm15,xmm15 -DB 102,15,56,222,224 -DB 102,15,56,222,232 - pand xmm14,xmm8 - movaps xmm12,xmm11 -DB 102,15,56,222,240 - pxor xmm15,xmm14 - movdqa xmm14,xmm9 -DB 102,15,56,222,248 - movups xmm0,XMMWORD[((-48))+rcx] - - paddd xmm9,xmm9 -DB 102,15,56,222,209 - pxor xmm11,xmm15 - psrad xmm14,31 -DB 102,15,56,222,217 - paddq xmm15,xmm15 - pand xmm14,xmm8 -DB 102,15,56,222,225 -DB 102,15,56,222,233 - movdqa XMMWORD[48+rsp],xmm13 - pxor xmm15,xmm14 -DB 102,15,56,222,241 - movaps xmm13,xmm12 - movdqa xmm14,xmm9 -DB 102,15,56,222,249 - movups xmm1,XMMWORD[((-32))+rcx] - - paddd xmm9,xmm9 -DB 102,15,56,222,208 - pxor xmm12,xmm15 - psrad xmm14,31 -DB 102,15,56,222,216 - paddq xmm15,xmm15 - pand xmm14,xmm8 -DB 102,15,56,222,224 -DB 102,15,56,222,232 -DB 102,15,56,222,240 - pxor xmm15,xmm14 - movaps xmm14,xmm13 -DB 102,15,56,222,248 - - movdqa xmm0,xmm9 - paddd xmm9,xmm9 -DB 102,15,56,222,209 - pxor xmm13,xmm15 - psrad xmm0,31 -DB 102,15,56,222,217 - paddq xmm15,xmm15 - pand xmm0,xmm8 -DB 102,15,56,222,225 -DB 102,15,56,222,233 - pxor xmm15,xmm0 - movups xmm0,XMMWORD[rbp] -DB 102,15,56,222,241 -DB 102,15,56,222,249 - movups xmm1,XMMWORD[16+rbp] - - pxor xmm14,xmm15 -DB 102,15,56,223,84,36,0 - psrad xmm9,31 - paddq xmm15,xmm15 -DB 102,15,56,223,92,36,16 -DB 102,15,56,223,100,36,32 - pand xmm9,xmm8 - mov rax,r10 -DB 102,15,56,223,108,36,48 -DB 102,15,56,223,116,36,64 -DB 102,15,56,223,124,36,80 - pxor xmm15,xmm9 - - lea rsi,[96+rsi] - movups XMMWORD[(-96)+rsi],xmm2 - movups XMMWORD[(-80)+rsi],xmm3 - movups XMMWORD[(-64)+rsi],xmm4 - movups XMMWORD[(-48)+rsi],xmm5 - movups XMMWORD[(-32)+rsi],xmm6 - movups XMMWORD[(-16)+rsi],xmm7 - sub rdx,16*6 - jnc NEAR $L$xts_dec_grandloop - - mov eax,16+96 - sub eax,r10d - mov rcx,rbp - shr eax,4 - -$L$xts_dec_short: - - mov r10d,eax - pxor xmm10,xmm0 - pxor xmm11,xmm0 - add rdx,16*6 - jz NEAR $L$xts_dec_done - - pxor xmm12,xmm0 - cmp rdx,0x20 - jb NEAR $L$xts_dec_one - pxor xmm13,xmm0 - je NEAR $L$xts_dec_two - - pxor xmm14,xmm0 - cmp rdx,0x40 - jb NEAR $L$xts_dec_three - je NEAR $L$xts_dec_four - - movdqu xmm2,XMMWORD[rdi] - movdqu xmm3,XMMWORD[16+rdi] - movdqu xmm4,XMMWORD[32+rdi] - pxor xmm2,xmm10 - movdqu xmm5,XMMWORD[48+rdi] - pxor xmm3,xmm11 - movdqu xmm6,XMMWORD[64+rdi] - lea rdi,[80+rdi] - pxor xmm4,xmm12 - pxor xmm5,xmm13 - pxor xmm6,xmm14 - - call _aesni_decrypt6 - - xorps xmm2,xmm10 - xorps xmm3,xmm11 - xorps xmm4,xmm12 - movdqu XMMWORD[rsi],xmm2 - xorps xmm5,xmm13 - movdqu XMMWORD[16+rsi],xmm3 - xorps xmm6,xmm14 - movdqu XMMWORD[32+rsi],xmm4 - pxor xmm14,xmm14 - movdqu XMMWORD[48+rsi],xmm5 - pcmpgtd xmm14,xmm15 - movdqu XMMWORD[64+rsi],xmm6 - lea rsi,[80+rsi] - pshufd xmm11,xmm14,0x13 - and r9,15 - jz NEAR $L$xts_dec_ret - - movdqa xmm10,xmm15 - paddq xmm15,xmm15 - pand xmm11,xmm8 - pxor xmm11,xmm15 - jmp NEAR $L$xts_dec_done2 - -ALIGN 16 -$L$xts_dec_one: - movups xmm2,XMMWORD[rdi] - lea rdi,[16+rdi] - xorps xmm2,xmm10 - movups xmm0,XMMWORD[rcx] - movups xmm1,XMMWORD[16+rcx] - lea rcx,[32+rcx] - xorps xmm2,xmm0 -$L$oop_dec1_12: -DB 102,15,56,222,209 - dec eax - movups xmm1,XMMWORD[rcx] - lea rcx,[16+rcx] - jnz NEAR $L$oop_dec1_12 -DB 102,15,56,223,209 - xorps xmm2,xmm10 - movdqa xmm10,xmm11 - movups XMMWORD[rsi],xmm2 - movdqa xmm11,xmm12 - lea rsi,[16+rsi] - jmp NEAR $L$xts_dec_done - -ALIGN 16 -$L$xts_dec_two: - movups xmm2,XMMWORD[rdi] - movups xmm3,XMMWORD[16+rdi] - lea rdi,[32+rdi] - xorps xmm2,xmm10 - xorps xmm3,xmm11 - - call _aesni_decrypt2 - - xorps xmm2,xmm10 - movdqa xmm10,xmm12 - xorps xmm3,xmm11 - movdqa xmm11,xmm13 - movups XMMWORD[rsi],xmm2 - movups XMMWORD[16+rsi],xmm3 - lea rsi,[32+rsi] - jmp NEAR $L$xts_dec_done - -ALIGN 16 -$L$xts_dec_three: - movups xmm2,XMMWORD[rdi] - movups xmm3,XMMWORD[16+rdi] - movups xmm4,XMMWORD[32+rdi] - lea rdi,[48+rdi] - xorps xmm2,xmm10 - xorps xmm3,xmm11 - xorps xmm4,xmm12 - - call _aesni_decrypt3 - - xorps xmm2,xmm10 - movdqa xmm10,xmm13 - xorps xmm3,xmm11 - movdqa xmm11,xmm14 - xorps xmm4,xmm12 - movups XMMWORD[rsi],xmm2 - movups XMMWORD[16+rsi],xmm3 - movups XMMWORD[32+rsi],xmm4 - lea rsi,[48+rsi] - jmp NEAR $L$xts_dec_done - -ALIGN 16 -$L$xts_dec_four: - movups xmm2,XMMWORD[rdi] - movups xmm3,XMMWORD[16+rdi] - movups xmm4,XMMWORD[32+rdi] - xorps xmm2,xmm10 - movups xmm5,XMMWORD[48+rdi] - lea rdi,[64+rdi] - xorps xmm3,xmm11 - xorps xmm4,xmm12 - xorps xmm5,xmm13 - - call _aesni_decrypt4 - - pxor xmm2,xmm10 - movdqa xmm10,xmm14 - pxor xmm3,xmm11 - movdqa xmm11,xmm15 - pxor xmm4,xmm12 - movdqu XMMWORD[rsi],xmm2 - pxor xmm5,xmm13 - movdqu XMMWORD[16+rsi],xmm3 - movdqu XMMWORD[32+rsi],xmm4 - movdqu XMMWORD[48+rsi],xmm5 - lea rsi,[64+rsi] - jmp NEAR $L$xts_dec_done - -ALIGN 16 -$L$xts_dec_done: - and r9,15 - jz NEAR $L$xts_dec_ret -$L$xts_dec_done2: - mov rdx,r9 - mov rcx,rbp - mov eax,r10d - - movups xmm2,XMMWORD[rdi] - xorps xmm2,xmm11 - movups xmm0,XMMWORD[rcx] - movups xmm1,XMMWORD[16+rcx] - lea rcx,[32+rcx] - xorps xmm2,xmm0 -$L$oop_dec1_13: -DB 102,15,56,222,209 - dec eax - movups xmm1,XMMWORD[rcx] - lea rcx,[16+rcx] - jnz NEAR $L$oop_dec1_13 -DB 102,15,56,223,209 - xorps xmm2,xmm11 - movups XMMWORD[rsi],xmm2 - -$L$xts_dec_steal: - movzx eax,BYTE[16+rdi] - movzx ecx,BYTE[rsi] - lea rdi,[1+rdi] - mov BYTE[rsi],al - mov BYTE[16+rsi],cl - lea rsi,[1+rsi] - sub rdx,1 - jnz NEAR $L$xts_dec_steal - - sub rsi,r9 - mov rcx,rbp - mov eax,r10d - - movups xmm2,XMMWORD[rsi] - xorps xmm2,xmm10 - movups xmm0,XMMWORD[rcx] - movups xmm1,XMMWORD[16+rcx] - lea rcx,[32+rcx] - xorps xmm2,xmm0 -$L$oop_dec1_14: -DB 102,15,56,222,209 - dec eax - movups xmm1,XMMWORD[rcx] - lea rcx,[16+rcx] - jnz NEAR $L$oop_dec1_14 -DB 102,15,56,223,209 - xorps xmm2,xmm10 - movups XMMWORD[rsi],xmm2 - -$L$xts_dec_ret: - xorps xmm0,xmm0 - pxor xmm1,xmm1 - pxor xmm2,xmm2 - pxor xmm3,xmm3 - pxor xmm4,xmm4 - pxor xmm5,xmm5 - movaps xmm6,XMMWORD[((-168))+r11] - movaps XMMWORD[(-168)+r11],xmm0 - movaps xmm7,XMMWORD[((-152))+r11] - movaps XMMWORD[(-152)+r11],xmm0 - movaps xmm8,XMMWORD[((-136))+r11] - movaps XMMWORD[(-136)+r11],xmm0 - movaps xmm9,XMMWORD[((-120))+r11] - movaps XMMWORD[(-120)+r11],xmm0 - movaps xmm10,XMMWORD[((-104))+r11] - movaps XMMWORD[(-104)+r11],xmm0 - movaps xmm11,XMMWORD[((-88))+r11] - movaps XMMWORD[(-88)+r11],xmm0 - movaps xmm12,XMMWORD[((-72))+r11] - movaps XMMWORD[(-72)+r11],xmm0 - movaps xmm13,XMMWORD[((-56))+r11] - movaps XMMWORD[(-56)+r11],xmm0 - movaps xmm14,XMMWORD[((-40))+r11] - movaps XMMWORD[(-40)+r11],xmm0 - movaps xmm15,XMMWORD[((-24))+r11] - movaps XMMWORD[(-24)+r11],xmm0 - movaps XMMWORD[rsp],xmm0 - movaps XMMWORD[16+rsp],xmm0 - movaps XMMWORD[32+rsp],xmm0 - movaps XMMWORD[48+rsp],xmm0 - movaps XMMWORD[64+rsp],xmm0 - movaps XMMWORD[80+rsp],xmm0 - movaps XMMWORD[96+rsp],xmm0 - mov rbp,QWORD[((-8))+r11] - - lea rsp,[r11] - -$L$xts_dec_epilogue: - mov rdi,QWORD[8+rsp] ;WIN64 epilogue - mov rsi,QWORD[16+rsp] - DB 0F3h,0C3h ;repret - -$L$SEH_end_aes_hw_xts_decrypt: -global aes_hw_ocb_encrypt - -ALIGN 32 -aes_hw_ocb_encrypt: - mov QWORD[8+rsp],rdi ;WIN64 prologue - mov QWORD[16+rsp],rsi - mov rax,rsp -$L$SEH_begin_aes_hw_ocb_encrypt: - mov rdi,rcx - mov rsi,rdx - mov rdx,r8 - mov rcx,r9 - mov r8,QWORD[40+rsp] - mov r9,QWORD[48+rsp] - - - - lea rax,[rsp] - push rbx - - push rbp - - push r12 - - push r13 - - push r14 - - lea rsp,[((-160))+rsp] - movaps XMMWORD[rsp],xmm6 - movaps XMMWORD[16+rsp],xmm7 - movaps XMMWORD[32+rsp],xmm8 - movaps XMMWORD[48+rsp],xmm9 - movaps XMMWORD[64+rsp],xmm10 - movaps XMMWORD[80+rsp],xmm11 - movaps XMMWORD[96+rsp],xmm12 - movaps XMMWORD[112+rsp],xmm13 - movaps XMMWORD[128+rsp],xmm14 - movaps XMMWORD[144+rsp],xmm15 -$L$ocb_enc_body: - mov rbx,QWORD[56+rax] - mov rbp,QWORD[((56+8))+rax] - - mov r10d,DWORD[240+rcx] - mov r11,rcx - shl r10d,4 - movups xmm9,XMMWORD[rcx] - movups xmm1,XMMWORD[16+r10*1+rcx] - - movdqu xmm15,XMMWORD[r9] - pxor xmm9,xmm1 - pxor xmm15,xmm1 - - mov eax,16+32 - lea rcx,[32+r10*1+r11] - movups xmm1,XMMWORD[16+r11] - sub rax,r10 - mov r10,rax - - movdqu xmm10,XMMWORD[rbx] - movdqu xmm8,XMMWORD[rbp] - - test r8,1 - jnz NEAR $L$ocb_enc_odd - - bsf r12,r8 - add r8,1 - shl r12,4 - movdqu xmm7,XMMWORD[r12*1+rbx] - movdqu xmm2,XMMWORD[rdi] - lea rdi,[16+rdi] - - call __ocb_encrypt1 - - movdqa xmm15,xmm7 - movups XMMWORD[rsi],xmm2 - lea rsi,[16+rsi] - sub rdx,1 - jz NEAR $L$ocb_enc_done - -$L$ocb_enc_odd: - lea r12,[1+r8] - lea r13,[3+r8] - lea r14,[5+r8] - lea r8,[6+r8] - bsf r12,r12 - bsf r13,r13 - bsf r14,r14 - shl r12,4 - shl r13,4 - shl r14,4 - - sub rdx,6 - jc NEAR $L$ocb_enc_short - jmp NEAR $L$ocb_enc_grandloop - -ALIGN 32 -$L$ocb_enc_grandloop: - movdqu xmm2,XMMWORD[rdi] - movdqu xmm3,XMMWORD[16+rdi] - movdqu xmm4,XMMWORD[32+rdi] - movdqu xmm5,XMMWORD[48+rdi] - movdqu xmm6,XMMWORD[64+rdi] - movdqu xmm7,XMMWORD[80+rdi] - lea rdi,[96+rdi] - - call __ocb_encrypt6 - - movups XMMWORD[rsi],xmm2 - movups XMMWORD[16+rsi],xmm3 - movups XMMWORD[32+rsi],xmm4 - movups XMMWORD[48+rsi],xmm5 - movups XMMWORD[64+rsi],xmm6 - movups XMMWORD[80+rsi],xmm7 - lea rsi,[96+rsi] - sub rdx,6 - jnc NEAR $L$ocb_enc_grandloop - -$L$ocb_enc_short: - add rdx,6 - jz NEAR $L$ocb_enc_done - - movdqu xmm2,XMMWORD[rdi] - cmp rdx,2 - jb NEAR $L$ocb_enc_one - movdqu xmm3,XMMWORD[16+rdi] - je NEAR $L$ocb_enc_two - - movdqu xmm4,XMMWORD[32+rdi] - cmp rdx,4 - jb NEAR $L$ocb_enc_three - movdqu xmm5,XMMWORD[48+rdi] - je NEAR $L$ocb_enc_four - - movdqu xmm6,XMMWORD[64+rdi] - pxor xmm7,xmm7 - - call __ocb_encrypt6 - - movdqa xmm15,xmm14 - movups XMMWORD[rsi],xmm2 - movups XMMWORD[16+rsi],xmm3 - movups XMMWORD[32+rsi],xmm4 - movups XMMWORD[48+rsi],xmm5 - movups XMMWORD[64+rsi],xmm6 - - jmp NEAR $L$ocb_enc_done - -ALIGN 16 -$L$ocb_enc_one: - movdqa xmm7,xmm10 - - call __ocb_encrypt1 - - movdqa xmm15,xmm7 - movups XMMWORD[rsi],xmm2 - jmp NEAR $L$ocb_enc_done - -ALIGN 16 -$L$ocb_enc_two: - pxor xmm4,xmm4 - pxor xmm5,xmm5 - - call __ocb_encrypt4 - - movdqa xmm15,xmm11 - movups XMMWORD[rsi],xmm2 - movups XMMWORD[16+rsi],xmm3 - - jmp NEAR $L$ocb_enc_done - -ALIGN 16 -$L$ocb_enc_three: - pxor xmm5,xmm5 - - call __ocb_encrypt4 - - movdqa xmm15,xmm12 - movups XMMWORD[rsi],xmm2 - movups XMMWORD[16+rsi],xmm3 - movups XMMWORD[32+rsi],xmm4 - - jmp NEAR $L$ocb_enc_done - -ALIGN 16 -$L$ocb_enc_four: - call __ocb_encrypt4 - - movdqa xmm15,xmm13 - movups XMMWORD[rsi],xmm2 - movups XMMWORD[16+rsi],xmm3 - movups XMMWORD[32+rsi],xmm4 - movups XMMWORD[48+rsi],xmm5 - -$L$ocb_enc_done: - pxor xmm15,xmm0 - movdqu XMMWORD[rbp],xmm8 - movdqu XMMWORD[r9],xmm15 - - xorps xmm0,xmm0 - pxor xmm1,xmm1 - pxor xmm2,xmm2 - pxor xmm3,xmm3 - pxor xmm4,xmm4 - pxor xmm5,xmm5 - movaps xmm6,XMMWORD[rsp] - movaps XMMWORD[rsp],xmm0 - movaps xmm7,XMMWORD[16+rsp] - movaps XMMWORD[16+rsp],xmm0 - movaps xmm8,XMMWORD[32+rsp] - movaps XMMWORD[32+rsp],xmm0 - movaps xmm9,XMMWORD[48+rsp] - movaps XMMWORD[48+rsp],xmm0 - movaps xmm10,XMMWORD[64+rsp] - movaps XMMWORD[64+rsp],xmm0 - movaps xmm11,XMMWORD[80+rsp] - movaps XMMWORD[80+rsp],xmm0 - movaps xmm12,XMMWORD[96+rsp] - movaps XMMWORD[96+rsp],xmm0 - movaps xmm13,XMMWORD[112+rsp] - movaps XMMWORD[112+rsp],xmm0 - movaps xmm14,XMMWORD[128+rsp] - movaps XMMWORD[128+rsp],xmm0 - movaps xmm15,XMMWORD[144+rsp] - movaps XMMWORD[144+rsp],xmm0 - lea rax,[((160+40))+rsp] -$L$ocb_enc_pop: - mov r14,QWORD[((-40))+rax] - - mov r13,QWORD[((-32))+rax] - - mov r12,QWORD[((-24))+rax] - - mov rbp,QWORD[((-16))+rax] - - mov rbx,QWORD[((-8))+rax] - - lea rsp,[rax] - -$L$ocb_enc_epilogue: - mov rdi,QWORD[8+rsp] ;WIN64 epilogue - mov rsi,QWORD[16+rsp] - DB 0F3h,0C3h ;repret - -$L$SEH_end_aes_hw_ocb_encrypt: - - -ALIGN 32 -__ocb_encrypt6: - pxor xmm15,xmm9 - movdqu xmm11,XMMWORD[r12*1+rbx] - movdqa xmm12,xmm10 - movdqu xmm13,XMMWORD[r13*1+rbx] - movdqa xmm14,xmm10 - pxor xmm10,xmm15 - movdqu xmm15,XMMWORD[r14*1+rbx] - pxor xmm11,xmm10 - pxor xmm8,xmm2 - pxor xmm2,xmm10 - pxor xmm12,xmm11 - pxor xmm8,xmm3 - pxor xmm3,xmm11 - pxor xmm13,xmm12 - pxor xmm8,xmm4 - pxor xmm4,xmm12 - pxor xmm14,xmm13 - pxor xmm8,xmm5 - pxor xmm5,xmm13 - pxor xmm15,xmm14 - pxor xmm8,xmm6 - pxor xmm6,xmm14 - pxor xmm8,xmm7 - pxor xmm7,xmm15 - movups xmm0,XMMWORD[32+r11] - - lea r12,[1+r8] - lea r13,[3+r8] - lea r14,[5+r8] - add r8,6 - pxor xmm10,xmm9 - bsf r12,r12 - bsf r13,r13 - bsf r14,r14 - -DB 102,15,56,220,209 -DB 102,15,56,220,217 -DB 102,15,56,220,225 -DB 102,15,56,220,233 - pxor xmm11,xmm9 - pxor xmm12,xmm9 -DB 102,15,56,220,241 - pxor xmm13,xmm9 - pxor xmm14,xmm9 -DB 102,15,56,220,249 - movups xmm1,XMMWORD[48+r11] - pxor xmm15,xmm9 - -DB 102,15,56,220,208 -DB 102,15,56,220,216 -DB 102,15,56,220,224 -DB 102,15,56,220,232 -DB 102,15,56,220,240 -DB 102,15,56,220,248 - movups xmm0,XMMWORD[64+r11] - shl r12,4 - shl r13,4 - jmp NEAR $L$ocb_enc_loop6 - -ALIGN 32 -$L$ocb_enc_loop6: -DB 102,15,56,220,209 -DB 102,15,56,220,217 -DB 102,15,56,220,225 -DB 102,15,56,220,233 -DB 102,15,56,220,241 -DB 102,15,56,220,249 - movups xmm1,XMMWORD[rax*1+rcx] - add rax,32 - -DB 102,15,56,220,208 -DB 102,15,56,220,216 -DB 102,15,56,220,224 -DB 102,15,56,220,232 -DB 102,15,56,220,240 -DB 102,15,56,220,248 - movups xmm0,XMMWORD[((-16))+rax*1+rcx] - jnz NEAR $L$ocb_enc_loop6 - -DB 102,15,56,220,209 -DB 102,15,56,220,217 -DB 102,15,56,220,225 -DB 102,15,56,220,233 -DB 102,15,56,220,241 -DB 102,15,56,220,249 - movups xmm1,XMMWORD[16+r11] - shl r14,4 - -DB 102,65,15,56,221,210 - movdqu xmm10,XMMWORD[rbx] - mov rax,r10 -DB 102,65,15,56,221,219 -DB 102,65,15,56,221,228 -DB 102,65,15,56,221,237 -DB 102,65,15,56,221,246 -DB 102,65,15,56,221,255 - DB 0F3h,0C3h ;repret - - - -ALIGN 32 -__ocb_encrypt4: - pxor xmm15,xmm9 - movdqu xmm11,XMMWORD[r12*1+rbx] - movdqa xmm12,xmm10 - movdqu xmm13,XMMWORD[r13*1+rbx] - pxor xmm10,xmm15 - pxor xmm11,xmm10 - pxor xmm8,xmm2 - pxor xmm2,xmm10 - pxor xmm12,xmm11 - pxor xmm8,xmm3 - pxor xmm3,xmm11 - pxor xmm13,xmm12 - pxor xmm8,xmm4 - pxor xmm4,xmm12 - pxor xmm8,xmm5 - pxor xmm5,xmm13 - movups xmm0,XMMWORD[32+r11] - - pxor xmm10,xmm9 - pxor xmm11,xmm9 - pxor xmm12,xmm9 - pxor xmm13,xmm9 - -DB 102,15,56,220,209 -DB 102,15,56,220,217 -DB 102,15,56,220,225 -DB 102,15,56,220,233 - movups xmm1,XMMWORD[48+r11] - -DB 102,15,56,220,208 -DB 102,15,56,220,216 -DB 102,15,56,220,224 -DB 102,15,56,220,232 - movups xmm0,XMMWORD[64+r11] - jmp NEAR $L$ocb_enc_loop4 - -ALIGN 32 -$L$ocb_enc_loop4: -DB 102,15,56,220,209 -DB 102,15,56,220,217 -DB 102,15,56,220,225 -DB 102,15,56,220,233 - movups xmm1,XMMWORD[rax*1+rcx] - add rax,32 - -DB 102,15,56,220,208 -DB 102,15,56,220,216 -DB 102,15,56,220,224 -DB 102,15,56,220,232 - movups xmm0,XMMWORD[((-16))+rax*1+rcx] - jnz NEAR $L$ocb_enc_loop4 - -DB 102,15,56,220,209 -DB 102,15,56,220,217 -DB 102,15,56,220,225 -DB 102,15,56,220,233 - movups xmm1,XMMWORD[16+r11] - mov rax,r10 - -DB 102,65,15,56,221,210 -DB 102,65,15,56,221,219 -DB 102,65,15,56,221,228 -DB 102,65,15,56,221,237 - DB 0F3h,0C3h ;repret - - - -ALIGN 32 -__ocb_encrypt1: - pxor xmm7,xmm15 - pxor xmm7,xmm9 - pxor xmm8,xmm2 - pxor xmm2,xmm7 - movups xmm0,XMMWORD[32+r11] - -DB 102,15,56,220,209 - movups xmm1,XMMWORD[48+r11] - pxor xmm7,xmm9 - -DB 102,15,56,220,208 - movups xmm0,XMMWORD[64+r11] - jmp NEAR $L$ocb_enc_loop1 - -ALIGN 32 -$L$ocb_enc_loop1: -DB 102,15,56,220,209 - movups xmm1,XMMWORD[rax*1+rcx] - add rax,32 - -DB 102,15,56,220,208 - movups xmm0,XMMWORD[((-16))+rax*1+rcx] - jnz NEAR $L$ocb_enc_loop1 - -DB 102,15,56,220,209 - movups xmm1,XMMWORD[16+r11] - mov rax,r10 - -DB 102,15,56,221,215 - DB 0F3h,0C3h ;repret - - -global aes_hw_ocb_decrypt - -ALIGN 32 -aes_hw_ocb_decrypt: - mov QWORD[8+rsp],rdi ;WIN64 prologue - mov QWORD[16+rsp],rsi - mov rax,rsp -$L$SEH_begin_aes_hw_ocb_decrypt: - mov rdi,rcx - mov rsi,rdx - mov rdx,r8 - mov rcx,r9 - mov r8,QWORD[40+rsp] - mov r9,QWORD[48+rsp] - - - - lea rax,[rsp] - push rbx - - push rbp - - push r12 - - push r13 - - push r14 - - lea rsp,[((-160))+rsp] - movaps XMMWORD[rsp],xmm6 - movaps XMMWORD[16+rsp],xmm7 - movaps XMMWORD[32+rsp],xmm8 - movaps XMMWORD[48+rsp],xmm9 - movaps XMMWORD[64+rsp],xmm10 - movaps XMMWORD[80+rsp],xmm11 - movaps XMMWORD[96+rsp],xmm12 - movaps XMMWORD[112+rsp],xmm13 - movaps XMMWORD[128+rsp],xmm14 - movaps XMMWORD[144+rsp],xmm15 -$L$ocb_dec_body: - mov rbx,QWORD[56+rax] - mov rbp,QWORD[((56+8))+rax] - - mov r10d,DWORD[240+rcx] - mov r11,rcx - shl r10d,4 - movups xmm9,XMMWORD[rcx] - movups xmm1,XMMWORD[16+r10*1+rcx] - - movdqu xmm15,XMMWORD[r9] - pxor xmm9,xmm1 - pxor xmm15,xmm1 - - mov eax,16+32 - lea rcx,[32+r10*1+r11] - movups xmm1,XMMWORD[16+r11] - sub rax,r10 - mov r10,rax - - movdqu xmm10,XMMWORD[rbx] - movdqu xmm8,XMMWORD[rbp] - - test r8,1 - jnz NEAR $L$ocb_dec_odd - - bsf r12,r8 - add r8,1 - shl r12,4 - movdqu xmm7,XMMWORD[r12*1+rbx] - movdqu xmm2,XMMWORD[rdi] - lea rdi,[16+rdi] - - call __ocb_decrypt1 - - movdqa xmm15,xmm7 - movups XMMWORD[rsi],xmm2 - xorps xmm8,xmm2 - lea rsi,[16+rsi] - sub rdx,1 - jz NEAR $L$ocb_dec_done - -$L$ocb_dec_odd: - lea r12,[1+r8] - lea r13,[3+r8] - lea r14,[5+r8] - lea r8,[6+r8] - bsf r12,r12 - bsf r13,r13 - bsf r14,r14 - shl r12,4 - shl r13,4 - shl r14,4 - - sub rdx,6 - jc NEAR $L$ocb_dec_short - jmp NEAR $L$ocb_dec_grandloop - -ALIGN 32 -$L$ocb_dec_grandloop: - movdqu xmm2,XMMWORD[rdi] - movdqu xmm3,XMMWORD[16+rdi] - movdqu xmm4,XMMWORD[32+rdi] - movdqu xmm5,XMMWORD[48+rdi] - movdqu xmm6,XMMWORD[64+rdi] - movdqu xmm7,XMMWORD[80+rdi] - lea rdi,[96+rdi] - - call __ocb_decrypt6 - - movups XMMWORD[rsi],xmm2 - pxor xmm8,xmm2 - movups XMMWORD[16+rsi],xmm3 - pxor xmm8,xmm3 - movups XMMWORD[32+rsi],xmm4 - pxor xmm8,xmm4 - movups XMMWORD[48+rsi],xmm5 - pxor xmm8,xmm5 - movups XMMWORD[64+rsi],xmm6 - pxor xmm8,xmm6 - movups XMMWORD[80+rsi],xmm7 - pxor xmm8,xmm7 - lea rsi,[96+rsi] - sub rdx,6 - jnc NEAR $L$ocb_dec_grandloop - -$L$ocb_dec_short: - add rdx,6 - jz NEAR $L$ocb_dec_done - - movdqu xmm2,XMMWORD[rdi] - cmp rdx,2 - jb NEAR $L$ocb_dec_one - movdqu xmm3,XMMWORD[16+rdi] - je NEAR $L$ocb_dec_two - - movdqu xmm4,XMMWORD[32+rdi] - cmp rdx,4 - jb NEAR $L$ocb_dec_three - movdqu xmm5,XMMWORD[48+rdi] - je NEAR $L$ocb_dec_four - - movdqu xmm6,XMMWORD[64+rdi] - pxor xmm7,xmm7 - - call __ocb_decrypt6 - - movdqa xmm15,xmm14 - movups XMMWORD[rsi],xmm2 - pxor xmm8,xmm2 - movups XMMWORD[16+rsi],xmm3 - pxor xmm8,xmm3 - movups XMMWORD[32+rsi],xmm4 - pxor xmm8,xmm4 - movups XMMWORD[48+rsi],xmm5 - pxor xmm8,xmm5 - movups XMMWORD[64+rsi],xmm6 - pxor xmm8,xmm6 - - jmp NEAR $L$ocb_dec_done - -ALIGN 16 -$L$ocb_dec_one: - movdqa xmm7,xmm10 - - call __ocb_decrypt1 - - movdqa xmm15,xmm7 - movups XMMWORD[rsi],xmm2 - xorps xmm8,xmm2 - jmp NEAR $L$ocb_dec_done - -ALIGN 16 -$L$ocb_dec_two: - pxor xmm4,xmm4 - pxor xmm5,xmm5 - - call __ocb_decrypt4 - - movdqa xmm15,xmm11 - movups XMMWORD[rsi],xmm2 - xorps xmm8,xmm2 - movups XMMWORD[16+rsi],xmm3 - xorps xmm8,xmm3 - - jmp NEAR $L$ocb_dec_done - -ALIGN 16 -$L$ocb_dec_three: - pxor xmm5,xmm5 - - call __ocb_decrypt4 - - movdqa xmm15,xmm12 - movups XMMWORD[rsi],xmm2 - xorps xmm8,xmm2 - movups XMMWORD[16+rsi],xmm3 - xorps xmm8,xmm3 - movups XMMWORD[32+rsi],xmm4 - xorps xmm8,xmm4 - - jmp NEAR $L$ocb_dec_done - -ALIGN 16 -$L$ocb_dec_four: - call __ocb_decrypt4 - - movdqa xmm15,xmm13 - movups XMMWORD[rsi],xmm2 - pxor xmm8,xmm2 - movups XMMWORD[16+rsi],xmm3 - pxor xmm8,xmm3 - movups XMMWORD[32+rsi],xmm4 - pxor xmm8,xmm4 - movups XMMWORD[48+rsi],xmm5 - pxor xmm8,xmm5 - -$L$ocb_dec_done: - pxor xmm15,xmm0 - movdqu XMMWORD[rbp],xmm8 - movdqu XMMWORD[r9],xmm15 - - xorps xmm0,xmm0 - pxor xmm1,xmm1 - pxor xmm2,xmm2 - pxor xmm3,xmm3 - pxor xmm4,xmm4 - pxor xmm5,xmm5 - movaps xmm6,XMMWORD[rsp] - movaps XMMWORD[rsp],xmm0 - movaps xmm7,XMMWORD[16+rsp] - movaps XMMWORD[16+rsp],xmm0 - movaps xmm8,XMMWORD[32+rsp] - movaps XMMWORD[32+rsp],xmm0 - movaps xmm9,XMMWORD[48+rsp] - movaps XMMWORD[48+rsp],xmm0 - movaps xmm10,XMMWORD[64+rsp] - movaps XMMWORD[64+rsp],xmm0 - movaps xmm11,XMMWORD[80+rsp] - movaps XMMWORD[80+rsp],xmm0 - movaps xmm12,XMMWORD[96+rsp] - movaps XMMWORD[96+rsp],xmm0 - movaps xmm13,XMMWORD[112+rsp] - movaps XMMWORD[112+rsp],xmm0 - movaps xmm14,XMMWORD[128+rsp] - movaps XMMWORD[128+rsp],xmm0 - movaps xmm15,XMMWORD[144+rsp] - movaps XMMWORD[144+rsp],xmm0 - lea rax,[((160+40))+rsp] -$L$ocb_dec_pop: - mov r14,QWORD[((-40))+rax] - - mov r13,QWORD[((-32))+rax] - - mov r12,QWORD[((-24))+rax] - - mov rbp,QWORD[((-16))+rax] - - mov rbx,QWORD[((-8))+rax] - - lea rsp,[rax] - -$L$ocb_dec_epilogue: - mov rdi,QWORD[8+rsp] ;WIN64 epilogue - mov rsi,QWORD[16+rsp] - DB 0F3h,0C3h ;repret - -$L$SEH_end_aes_hw_ocb_decrypt: - - -ALIGN 32 -__ocb_decrypt6: - pxor xmm15,xmm9 - movdqu xmm11,XMMWORD[r12*1+rbx] - movdqa xmm12,xmm10 - movdqu xmm13,XMMWORD[r13*1+rbx] - movdqa xmm14,xmm10 - pxor xmm10,xmm15 - movdqu xmm15,XMMWORD[r14*1+rbx] - pxor xmm11,xmm10 - pxor xmm2,xmm10 - pxor xmm12,xmm11 - pxor xmm3,xmm11 - pxor xmm13,xmm12 - pxor xmm4,xmm12 - pxor xmm14,xmm13 - pxor xmm5,xmm13 - pxor xmm15,xmm14 - pxor xmm6,xmm14 - pxor xmm7,xmm15 - movups xmm0,XMMWORD[32+r11] - - lea r12,[1+r8] - lea r13,[3+r8] - lea r14,[5+r8] - add r8,6 - pxor xmm10,xmm9 - bsf r12,r12 - bsf r13,r13 - bsf r14,r14 - -DB 102,15,56,222,209 -DB 102,15,56,222,217 -DB 102,15,56,222,225 -DB 102,15,56,222,233 - pxor xmm11,xmm9 - pxor xmm12,xmm9 -DB 102,15,56,222,241 - pxor xmm13,xmm9 - pxor xmm14,xmm9 -DB 102,15,56,222,249 - movups xmm1,XMMWORD[48+r11] - pxor xmm15,xmm9 - -DB 102,15,56,222,208 -DB 102,15,56,222,216 -DB 102,15,56,222,224 -DB 102,15,56,222,232 -DB 102,15,56,222,240 -DB 102,15,56,222,248 - movups xmm0,XMMWORD[64+r11] - shl r12,4 - shl r13,4 - jmp NEAR $L$ocb_dec_loop6 - -ALIGN 32 -$L$ocb_dec_loop6: -DB 102,15,56,222,209 -DB 102,15,56,222,217 -DB 102,15,56,222,225 -DB 102,15,56,222,233 -DB 102,15,56,222,241 -DB 102,15,56,222,249 - movups xmm1,XMMWORD[rax*1+rcx] - add rax,32 - -DB 102,15,56,222,208 -DB 102,15,56,222,216 -DB 102,15,56,222,224 -DB 102,15,56,222,232 -DB 102,15,56,222,240 -DB 102,15,56,222,248 - movups xmm0,XMMWORD[((-16))+rax*1+rcx] - jnz NEAR $L$ocb_dec_loop6 - -DB 102,15,56,222,209 -DB 102,15,56,222,217 -DB 102,15,56,222,225 -DB 102,15,56,222,233 -DB 102,15,56,222,241 -DB 102,15,56,222,249 - movups xmm1,XMMWORD[16+r11] - shl r14,4 - -DB 102,65,15,56,223,210 - movdqu xmm10,XMMWORD[rbx] - mov rax,r10 -DB 102,65,15,56,223,219 -DB 102,65,15,56,223,228 -DB 102,65,15,56,223,237 -DB 102,65,15,56,223,246 -DB 102,65,15,56,223,255 - DB 0F3h,0C3h ;repret - - - -ALIGN 32 -__ocb_decrypt4: - pxor xmm15,xmm9 - movdqu xmm11,XMMWORD[r12*1+rbx] - movdqa xmm12,xmm10 - movdqu xmm13,XMMWORD[r13*1+rbx] - pxor xmm10,xmm15 - pxor xmm11,xmm10 - pxor xmm2,xmm10 - pxor xmm12,xmm11 - pxor xmm3,xmm11 - pxor xmm13,xmm12 - pxor xmm4,xmm12 - pxor xmm5,xmm13 - movups xmm0,XMMWORD[32+r11] - - pxor xmm10,xmm9 - pxor xmm11,xmm9 - pxor xmm12,xmm9 - pxor xmm13,xmm9 - -DB 102,15,56,222,209 -DB 102,15,56,222,217 -DB 102,15,56,222,225 -DB 102,15,56,222,233 - movups xmm1,XMMWORD[48+r11] - -DB 102,15,56,222,208 -DB 102,15,56,222,216 -DB 102,15,56,222,224 -DB 102,15,56,222,232 - movups xmm0,XMMWORD[64+r11] - jmp NEAR $L$ocb_dec_loop4 - -ALIGN 32 -$L$ocb_dec_loop4: -DB 102,15,56,222,209 -DB 102,15,56,222,217 -DB 102,15,56,222,225 -DB 102,15,56,222,233 - movups xmm1,XMMWORD[rax*1+rcx] - add rax,32 - -DB 102,15,56,222,208 -DB 102,15,56,222,216 -DB 102,15,56,222,224 -DB 102,15,56,222,232 - movups xmm0,XMMWORD[((-16))+rax*1+rcx] - jnz NEAR $L$ocb_dec_loop4 - -DB 102,15,56,222,209 -DB 102,15,56,222,217 -DB 102,15,56,222,225 -DB 102,15,56,222,233 - movups xmm1,XMMWORD[16+r11] - mov rax,r10 - -DB 102,65,15,56,223,210 -DB 102,65,15,56,223,219 -DB 102,65,15,56,223,228 -DB 102,65,15,56,223,237 - DB 0F3h,0C3h ;repret - - - -ALIGN 32 -__ocb_decrypt1: - pxor xmm7,xmm15 - pxor xmm7,xmm9 - pxor xmm2,xmm7 - movups xmm0,XMMWORD[32+r11] - -DB 102,15,56,222,209 - movups xmm1,XMMWORD[48+r11] - pxor xmm7,xmm9 - -DB 102,15,56,222,208 - movups xmm0,XMMWORD[64+r11] - jmp NEAR $L$ocb_dec_loop1 - -ALIGN 32 -$L$ocb_dec_loop1: -DB 102,15,56,222,209 - movups xmm1,XMMWORD[rax*1+rcx] - add rax,32 - -DB 102,15,56,222,208 - movups xmm0,XMMWORD[((-16))+rax*1+rcx] - jnz NEAR $L$ocb_dec_loop1 - -DB 102,15,56,222,209 - movups xmm1,XMMWORD[16+r11] - mov rax,r10 - -DB 102,15,56,223,215 - DB 0F3h,0C3h ;repret - global aes_hw_cbc_encrypt ALIGN 16 @@ -3733,12 +1563,12 @@ $L$cbc_enc_loop: xorps xmm3,xmm0 lea rcx,[32+rcx] xorps xmm2,xmm3 -$L$oop_enc1_15: +$L$oop_enc1_6: DB 102,15,56,220,209 dec eax movups xmm1,XMMWORD[rcx] lea rcx,[16+rcx] - jnz NEAR $L$oop_enc1_15 + jnz NEAR $L$oop_enc1_6 DB 102,15,56,221,209 mov eax,r10d mov rcx,r11 @@ -3784,12 +1614,12 @@ $L$cbc_decrypt: movups xmm1,XMMWORD[16+rcx] lea rcx,[32+rcx] xorps xmm2,xmm0 -$L$oop_dec1_16: +$L$oop_dec1_7: DB 102,15,56,222,209 dec r10d movups xmm1,XMMWORD[rcx] lea rcx,[16+rcx] - jnz NEAR $L$oop_dec1_16 + jnz NEAR $L$oop_dec1_7 DB 102,15,56,223,209 pxor xmm0,xmm0 pxor xmm1,xmm1 @@ -4213,12 +2043,12 @@ $L$cbc_dec_one: movups xmm1,XMMWORD[16+rcx] lea rcx,[32+rcx] xorps xmm2,xmm0 -$L$oop_dec1_17: +$L$oop_dec1_8: DB 102,15,56,222,209 dec eax movups xmm1,XMMWORD[rcx] lea rcx,[16+rcx] - jnz NEAR $L$oop_dec1_17 + jnz NEAR $L$oop_dec1_8 DB 102,15,56,223,209 xorps xmm2,xmm10 movaps xmm10,xmm11 @@ -4375,6 +2205,11 @@ ALIGN 16 aes_hw_set_encrypt_key: __aesni_set_encrypt_key: +%ifndef NDEBUG +%ifndef BORINGSSL_FIPS + mov BYTE[((BORINGSSL_function_hit+3))],1 +%endif +%endif DB 0x48,0x83,0xEC,0x08 mov rax,-1 @@ -4857,64 +2692,6 @@ ctr_xts_se_handler: -ALIGN 16 -ocb_se_handler: - push rsi - push rdi - push rbx - push rbp - push r12 - push r13 - push r14 - push r15 - pushfq - sub rsp,64 - - mov rax,QWORD[120+r8] - mov rbx,QWORD[248+r8] - - mov rsi,QWORD[8+r9] - mov r11,QWORD[56+r9] - - mov r10d,DWORD[r11] - lea r10,[r10*1+rsi] - cmp rbx,r10 - jb NEAR $L$common_seh_tail - - mov r10d,DWORD[4+r11] - lea r10,[r10*1+rsi] - cmp rbx,r10 - jae NEAR $L$common_seh_tail - - mov r10d,DWORD[8+r11] - lea r10,[r10*1+rsi] - cmp rbx,r10 - jae NEAR $L$ocb_no_xmm - - mov rax,QWORD[152+r8] - - lea rsi,[rax] - lea rdi,[512+r8] - mov ecx,20 - DD 0xa548f3fc - lea rax,[((160+40))+rax] - -$L$ocb_no_xmm: - mov rbx,QWORD[((-8))+rax] - mov rbp,QWORD[((-16))+rax] - mov r12,QWORD[((-24))+rax] - mov r13,QWORD[((-32))+rax] - mov r14,QWORD[((-40))+rax] - - mov QWORD[144+r8],rbx - mov QWORD[160+r8],rbp - mov QWORD[216+r8],r12 - mov QWORD[224+r8],r13 - mov QWORD[232+r8],r14 - - jmp NEAR $L$common_seh_tail - - ALIGN 16 cbc_se_handler: push rsi @@ -5003,33 +2780,9 @@ ALIGN 4 DD $L$SEH_end_aes_hw_ecb_encrypt wrt ..imagebase DD $L$SEH_info_ecb wrt ..imagebase - DD $L$SEH_begin_aes_hw_ccm64_encrypt_blocks wrt ..imagebase - DD $L$SEH_end_aes_hw_ccm64_encrypt_blocks wrt ..imagebase - DD $L$SEH_info_ccm64_enc wrt ..imagebase - - DD $L$SEH_begin_aes_hw_ccm64_decrypt_blocks wrt ..imagebase - DD $L$SEH_end_aes_hw_ccm64_decrypt_blocks wrt ..imagebase - DD $L$SEH_info_ccm64_dec wrt ..imagebase - DD $L$SEH_begin_aes_hw_ctr32_encrypt_blocks wrt ..imagebase DD $L$SEH_end_aes_hw_ctr32_encrypt_blocks wrt ..imagebase DD $L$SEH_info_ctr32 wrt ..imagebase - - DD $L$SEH_begin_aes_hw_xts_encrypt wrt ..imagebase - DD $L$SEH_end_aes_hw_xts_encrypt wrt ..imagebase - DD $L$SEH_info_xts_enc wrt ..imagebase - - DD $L$SEH_begin_aes_hw_xts_decrypt wrt ..imagebase - DD $L$SEH_end_aes_hw_xts_decrypt wrt ..imagebase - DD $L$SEH_info_xts_dec wrt ..imagebase - - DD $L$SEH_begin_aes_hw_ocb_encrypt wrt ..imagebase - DD $L$SEH_end_aes_hw_ocb_encrypt wrt ..imagebase - DD $L$SEH_info_ocb_enc wrt ..imagebase - - DD $L$SEH_begin_aes_hw_ocb_decrypt wrt ..imagebase - DD $L$SEH_end_aes_hw_ocb_decrypt wrt ..imagebase - DD $L$SEH_info_ocb_dec wrt ..imagebase DD $L$SEH_begin_aes_hw_cbc_encrypt wrt ..imagebase DD $L$SEH_end_aes_hw_cbc_encrypt wrt ..imagebase DD $L$SEH_info_cbc wrt ..imagebase @@ -5047,38 +2800,10 @@ $L$SEH_info_ecb: DB 9,0,0,0 DD ecb_ccm64_se_handler wrt ..imagebase DD $L$ecb_enc_body wrt ..imagebase,$L$ecb_enc_ret wrt ..imagebase -$L$SEH_info_ccm64_enc: -DB 9,0,0,0 - DD ecb_ccm64_se_handler wrt ..imagebase - DD $L$ccm64_enc_body wrt ..imagebase,$L$ccm64_enc_ret wrt ..imagebase -$L$SEH_info_ccm64_dec: -DB 9,0,0,0 - DD ecb_ccm64_se_handler wrt ..imagebase - DD $L$ccm64_dec_body wrt ..imagebase,$L$ccm64_dec_ret wrt ..imagebase $L$SEH_info_ctr32: DB 9,0,0,0 DD ctr_xts_se_handler wrt ..imagebase DD $L$ctr32_body wrt ..imagebase,$L$ctr32_epilogue wrt ..imagebase -$L$SEH_info_xts_enc: -DB 9,0,0,0 - DD ctr_xts_se_handler wrt ..imagebase - DD $L$xts_enc_body wrt ..imagebase,$L$xts_enc_epilogue wrt ..imagebase -$L$SEH_info_xts_dec: -DB 9,0,0,0 - DD ctr_xts_se_handler wrt ..imagebase - DD $L$xts_dec_body wrt ..imagebase,$L$xts_dec_epilogue wrt ..imagebase -$L$SEH_info_ocb_enc: -DB 9,0,0,0 - DD ocb_se_handler wrt ..imagebase - DD $L$ocb_enc_body wrt ..imagebase,$L$ocb_enc_epilogue wrt ..imagebase - DD $L$ocb_enc_pop wrt ..imagebase - DD 0 -$L$SEH_info_ocb_dec: -DB 9,0,0,0 - DD ocb_se_handler wrt ..imagebase - DD $L$ocb_dec_body wrt ..imagebase,$L$ocb_dec_epilogue wrt ..imagebase - DD $L$ocb_dec_pop wrt ..imagebase - DD 0 $L$SEH_info_cbc: DB 9,0,0,0 DD cbc_se_handler wrt ..imagebase diff --git a/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/bsaes-x86_64.asm b/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/bsaes-x86_64.asm deleted file mode 100644 index d7428e7f..00000000 --- a/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/bsaes-x86_64.asm +++ /dev/null @@ -1,1794 +0,0 @@ -; This file is generated from a similarly-named Perl script in the BoringSSL -; source tree. Do not edit by hand. - -default rel -%define XMMWORD -%define YMMWORD -%define ZMMWORD - -%ifdef BORINGSSL_PREFIX -%include "boringssl_prefix_symbols_nasm.inc" -%endif -section .text code align=64 - - -EXTERN aes_nohw_encrypt -EXTERN aes_nohw_decrypt - - -ALIGN 64 -_bsaes_encrypt8: - - lea r11,[$L$BS0] - - movdqa xmm8,XMMWORD[rax] - lea rax,[16+rax] - movdqa xmm7,XMMWORD[80+r11] - pxor xmm15,xmm8 - pxor xmm0,xmm8 - pxor xmm1,xmm8 - pxor xmm2,xmm8 -DB 102,68,15,56,0,255 -DB 102,15,56,0,199 - pxor xmm3,xmm8 - pxor xmm4,xmm8 -DB 102,15,56,0,207 -DB 102,15,56,0,215 - pxor xmm5,xmm8 - pxor xmm6,xmm8 -DB 102,15,56,0,223 -DB 102,15,56,0,231 -DB 102,15,56,0,239 -DB 102,15,56,0,247 -_bsaes_encrypt8_bitslice: - movdqa xmm7,XMMWORD[r11] - movdqa xmm8,XMMWORD[16+r11] - movdqa xmm9,xmm5 - psrlq xmm5,1 - movdqa xmm10,xmm3 - psrlq xmm3,1 - pxor xmm5,xmm6 - pxor xmm3,xmm4 - pand xmm5,xmm7 - pand xmm3,xmm7 - pxor xmm6,xmm5 - psllq xmm5,1 - pxor xmm4,xmm3 - psllq xmm3,1 - pxor xmm5,xmm9 - pxor xmm3,xmm10 - movdqa xmm9,xmm1 - psrlq xmm1,1 - movdqa xmm10,xmm15 - psrlq xmm15,1 - pxor xmm1,xmm2 - pxor xmm15,xmm0 - pand xmm1,xmm7 - pand xmm15,xmm7 - pxor xmm2,xmm1 - psllq xmm1,1 - pxor xmm0,xmm15 - psllq xmm15,1 - pxor xmm1,xmm9 - pxor xmm15,xmm10 - movdqa xmm7,XMMWORD[32+r11] - movdqa xmm9,xmm4 - psrlq xmm4,2 - movdqa xmm10,xmm3 - psrlq xmm3,2 - pxor xmm4,xmm6 - pxor xmm3,xmm5 - pand xmm4,xmm8 - pand xmm3,xmm8 - pxor xmm6,xmm4 - psllq xmm4,2 - pxor xmm5,xmm3 - psllq xmm3,2 - pxor xmm4,xmm9 - pxor xmm3,xmm10 - movdqa xmm9,xmm0 - psrlq xmm0,2 - movdqa xmm10,xmm15 - psrlq xmm15,2 - pxor xmm0,xmm2 - pxor xmm15,xmm1 - pand xmm0,xmm8 - pand xmm15,xmm8 - pxor xmm2,xmm0 - psllq xmm0,2 - pxor xmm1,xmm15 - psllq xmm15,2 - pxor xmm0,xmm9 - pxor xmm15,xmm10 - movdqa xmm9,xmm2 - psrlq xmm2,4 - movdqa xmm10,xmm1 - psrlq xmm1,4 - pxor xmm2,xmm6 - pxor xmm1,xmm5 - pand xmm2,xmm7 - pand xmm1,xmm7 - pxor xmm6,xmm2 - psllq xmm2,4 - pxor xmm5,xmm1 - psllq xmm1,4 - pxor xmm2,xmm9 - pxor xmm1,xmm10 - movdqa xmm9,xmm0 - psrlq xmm0,4 - movdqa xmm10,xmm15 - psrlq xmm15,4 - pxor xmm0,xmm4 - pxor xmm15,xmm3 - pand xmm0,xmm7 - pand xmm15,xmm7 - pxor xmm4,xmm0 - psllq xmm0,4 - pxor xmm3,xmm15 - psllq xmm15,4 - pxor xmm0,xmm9 - pxor xmm15,xmm10 - dec r10d - jmp NEAR $L$enc_sbox -ALIGN 16 -$L$enc_loop: - pxor xmm15,XMMWORD[rax] - pxor xmm0,XMMWORD[16+rax] - pxor xmm1,XMMWORD[32+rax] - pxor xmm2,XMMWORD[48+rax] -DB 102,68,15,56,0,255 -DB 102,15,56,0,199 - pxor xmm3,XMMWORD[64+rax] - pxor xmm4,XMMWORD[80+rax] -DB 102,15,56,0,207 -DB 102,15,56,0,215 - pxor xmm5,XMMWORD[96+rax] - pxor xmm6,XMMWORD[112+rax] -DB 102,15,56,0,223 -DB 102,15,56,0,231 -DB 102,15,56,0,239 -DB 102,15,56,0,247 - lea rax,[128+rax] -$L$enc_sbox: - pxor xmm4,xmm5 - pxor xmm1,xmm0 - pxor xmm2,xmm15 - pxor xmm5,xmm1 - pxor xmm4,xmm15 - - pxor xmm5,xmm2 - pxor xmm2,xmm6 - pxor xmm6,xmm4 - pxor xmm2,xmm3 - pxor xmm3,xmm4 - pxor xmm2,xmm0 - - pxor xmm1,xmm6 - pxor xmm0,xmm4 - movdqa xmm10,xmm6 - movdqa xmm9,xmm0 - movdqa xmm8,xmm4 - movdqa xmm12,xmm1 - movdqa xmm11,xmm5 - - pxor xmm10,xmm3 - pxor xmm9,xmm1 - pxor xmm8,xmm2 - movdqa xmm13,xmm10 - pxor xmm12,xmm3 - movdqa xmm7,xmm9 - pxor xmm11,xmm15 - movdqa xmm14,xmm10 - - por xmm9,xmm8 - por xmm10,xmm11 - pxor xmm14,xmm7 - pand xmm13,xmm11 - pxor xmm11,xmm8 - pand xmm7,xmm8 - pand xmm14,xmm11 - movdqa xmm11,xmm2 - pxor xmm11,xmm15 - pand xmm12,xmm11 - pxor xmm10,xmm12 - pxor xmm9,xmm12 - movdqa xmm12,xmm6 - movdqa xmm11,xmm4 - pxor xmm12,xmm0 - pxor xmm11,xmm5 - movdqa xmm8,xmm12 - pand xmm12,xmm11 - por xmm8,xmm11 - pxor xmm7,xmm12 - pxor xmm10,xmm14 - pxor xmm9,xmm13 - pxor xmm8,xmm14 - movdqa xmm11,xmm1 - pxor xmm7,xmm13 - movdqa xmm12,xmm3 - pxor xmm8,xmm13 - movdqa xmm13,xmm0 - pand xmm11,xmm2 - movdqa xmm14,xmm6 - pand xmm12,xmm15 - pand xmm13,xmm4 - por xmm14,xmm5 - pxor xmm10,xmm11 - pxor xmm9,xmm12 - pxor xmm8,xmm13 - pxor xmm7,xmm14 - - - - - - movdqa xmm11,xmm10 - pand xmm10,xmm8 - pxor xmm11,xmm9 - - movdqa xmm13,xmm7 - movdqa xmm14,xmm11 - pxor xmm13,xmm10 - pand xmm14,xmm13 - - movdqa xmm12,xmm8 - pxor xmm14,xmm9 - pxor xmm12,xmm7 - - pxor xmm10,xmm9 - - pand xmm12,xmm10 - - movdqa xmm9,xmm13 - pxor xmm12,xmm7 - - pxor xmm9,xmm12 - pxor xmm8,xmm12 - - pand xmm9,xmm7 - - pxor xmm13,xmm9 - pxor xmm8,xmm9 - - pand xmm13,xmm14 - - pxor xmm13,xmm11 - movdqa xmm11,xmm5 - movdqa xmm7,xmm4 - movdqa xmm9,xmm14 - pxor xmm9,xmm13 - pand xmm9,xmm5 - pxor xmm5,xmm4 - pand xmm4,xmm14 - pand xmm5,xmm13 - pxor xmm5,xmm4 - pxor xmm4,xmm9 - pxor xmm11,xmm15 - pxor xmm7,xmm2 - pxor xmm14,xmm12 - pxor xmm13,xmm8 - movdqa xmm10,xmm14 - movdqa xmm9,xmm12 - pxor xmm10,xmm13 - pxor xmm9,xmm8 - pand xmm10,xmm11 - pand xmm9,xmm15 - pxor xmm11,xmm7 - pxor xmm15,xmm2 - pand xmm7,xmm14 - pand xmm2,xmm12 - pand xmm11,xmm13 - pand xmm15,xmm8 - pxor xmm7,xmm11 - pxor xmm15,xmm2 - pxor xmm11,xmm10 - pxor xmm2,xmm9 - pxor xmm5,xmm11 - pxor xmm15,xmm11 - pxor xmm4,xmm7 - pxor xmm2,xmm7 - - movdqa xmm11,xmm6 - movdqa xmm7,xmm0 - pxor xmm11,xmm3 - pxor xmm7,xmm1 - movdqa xmm10,xmm14 - movdqa xmm9,xmm12 - pxor xmm10,xmm13 - pxor xmm9,xmm8 - pand xmm10,xmm11 - pand xmm9,xmm3 - pxor xmm11,xmm7 - pxor xmm3,xmm1 - pand xmm7,xmm14 - pand xmm1,xmm12 - pand xmm11,xmm13 - pand xmm3,xmm8 - pxor xmm7,xmm11 - pxor xmm3,xmm1 - pxor xmm11,xmm10 - pxor xmm1,xmm9 - pxor xmm14,xmm12 - pxor xmm13,xmm8 - movdqa xmm10,xmm14 - pxor xmm10,xmm13 - pand xmm10,xmm6 - pxor xmm6,xmm0 - pand xmm0,xmm14 - pand xmm6,xmm13 - pxor xmm6,xmm0 - pxor xmm0,xmm10 - pxor xmm6,xmm11 - pxor xmm3,xmm11 - pxor xmm0,xmm7 - pxor xmm1,xmm7 - pxor xmm6,xmm15 - pxor xmm0,xmm5 - pxor xmm3,xmm6 - pxor xmm5,xmm15 - pxor xmm15,xmm0 - - pxor xmm0,xmm4 - pxor xmm4,xmm1 - pxor xmm1,xmm2 - pxor xmm2,xmm4 - pxor xmm3,xmm4 - - pxor xmm5,xmm2 - dec r10d - jl NEAR $L$enc_done - pshufd xmm7,xmm15,0x93 - pshufd xmm8,xmm0,0x93 - pxor xmm15,xmm7 - pshufd xmm9,xmm3,0x93 - pxor xmm0,xmm8 - pshufd xmm10,xmm5,0x93 - pxor xmm3,xmm9 - pshufd xmm11,xmm2,0x93 - pxor xmm5,xmm10 - pshufd xmm12,xmm6,0x93 - pxor xmm2,xmm11 - pshufd xmm13,xmm1,0x93 - pxor xmm6,xmm12 - pshufd xmm14,xmm4,0x93 - pxor xmm1,xmm13 - pxor xmm4,xmm14 - - pxor xmm8,xmm15 - pxor xmm7,xmm4 - pxor xmm8,xmm4 - pshufd xmm15,xmm15,0x4E - pxor xmm9,xmm0 - pshufd xmm0,xmm0,0x4E - pxor xmm12,xmm2 - pxor xmm15,xmm7 - pxor xmm13,xmm6 - pxor xmm0,xmm8 - pxor xmm11,xmm5 - pshufd xmm7,xmm2,0x4E - pxor xmm14,xmm1 - pshufd xmm8,xmm6,0x4E - pxor xmm10,xmm3 - pshufd xmm2,xmm5,0x4E - pxor xmm10,xmm4 - pshufd xmm6,xmm4,0x4E - pxor xmm11,xmm4 - pshufd xmm5,xmm1,0x4E - pxor xmm7,xmm11 - pshufd xmm1,xmm3,0x4E - pxor xmm8,xmm12 - pxor xmm2,xmm10 - pxor xmm6,xmm14 - pxor xmm5,xmm13 - movdqa xmm3,xmm7 - pxor xmm1,xmm9 - movdqa xmm4,xmm8 - movdqa xmm7,XMMWORD[48+r11] - jnz NEAR $L$enc_loop - movdqa xmm7,XMMWORD[64+r11] - jmp NEAR $L$enc_loop -ALIGN 16 -$L$enc_done: - movdqa xmm7,XMMWORD[r11] - movdqa xmm8,XMMWORD[16+r11] - movdqa xmm9,xmm1 - psrlq xmm1,1 - movdqa xmm10,xmm2 - psrlq xmm2,1 - pxor xmm1,xmm4 - pxor xmm2,xmm6 - pand xmm1,xmm7 - pand xmm2,xmm7 - pxor xmm4,xmm1 - psllq xmm1,1 - pxor xmm6,xmm2 - psllq xmm2,1 - pxor xmm1,xmm9 - pxor xmm2,xmm10 - movdqa xmm9,xmm3 - psrlq xmm3,1 - movdqa xmm10,xmm15 - psrlq xmm15,1 - pxor xmm3,xmm5 - pxor xmm15,xmm0 - pand xmm3,xmm7 - pand xmm15,xmm7 - pxor xmm5,xmm3 - psllq xmm3,1 - pxor xmm0,xmm15 - psllq xmm15,1 - pxor xmm3,xmm9 - pxor xmm15,xmm10 - movdqa xmm7,XMMWORD[32+r11] - movdqa xmm9,xmm6 - psrlq xmm6,2 - movdqa xmm10,xmm2 - psrlq xmm2,2 - pxor xmm6,xmm4 - pxor xmm2,xmm1 - pand xmm6,xmm8 - pand xmm2,xmm8 - pxor xmm4,xmm6 - psllq xmm6,2 - pxor xmm1,xmm2 - psllq xmm2,2 - pxor xmm6,xmm9 - pxor xmm2,xmm10 - movdqa xmm9,xmm0 - psrlq xmm0,2 - movdqa xmm10,xmm15 - psrlq xmm15,2 - pxor xmm0,xmm5 - pxor xmm15,xmm3 - pand xmm0,xmm8 - pand xmm15,xmm8 - pxor xmm5,xmm0 - psllq xmm0,2 - pxor xmm3,xmm15 - psllq xmm15,2 - pxor xmm0,xmm9 - pxor xmm15,xmm10 - movdqa xmm9,xmm5 - psrlq xmm5,4 - movdqa xmm10,xmm3 - psrlq xmm3,4 - pxor xmm5,xmm4 - pxor xmm3,xmm1 - pand xmm5,xmm7 - pand xmm3,xmm7 - pxor xmm4,xmm5 - psllq xmm5,4 - pxor xmm1,xmm3 - psllq xmm3,4 - pxor xmm5,xmm9 - pxor xmm3,xmm10 - movdqa xmm9,xmm0 - psrlq xmm0,4 - movdqa xmm10,xmm15 - psrlq xmm15,4 - pxor xmm0,xmm6 - pxor xmm15,xmm2 - pand xmm0,xmm7 - pand xmm15,xmm7 - pxor xmm6,xmm0 - psllq xmm0,4 - pxor xmm2,xmm15 - psllq xmm15,4 - pxor xmm0,xmm9 - pxor xmm15,xmm10 - movdqa xmm7,XMMWORD[rax] - pxor xmm3,xmm7 - pxor xmm5,xmm7 - pxor xmm2,xmm7 - pxor xmm6,xmm7 - pxor xmm1,xmm7 - pxor xmm4,xmm7 - pxor xmm15,xmm7 - pxor xmm0,xmm7 - DB 0F3h,0C3h ;repret - - - - -ALIGN 64 -_bsaes_decrypt8: - - lea r11,[$L$BS0] - - movdqa xmm8,XMMWORD[rax] - lea rax,[16+rax] - movdqa xmm7,XMMWORD[((-48))+r11] - pxor xmm15,xmm8 - pxor xmm0,xmm8 - pxor xmm1,xmm8 - pxor xmm2,xmm8 -DB 102,68,15,56,0,255 -DB 102,15,56,0,199 - pxor xmm3,xmm8 - pxor xmm4,xmm8 -DB 102,15,56,0,207 -DB 102,15,56,0,215 - pxor xmm5,xmm8 - pxor xmm6,xmm8 -DB 102,15,56,0,223 -DB 102,15,56,0,231 -DB 102,15,56,0,239 -DB 102,15,56,0,247 - movdqa xmm7,XMMWORD[r11] - movdqa xmm8,XMMWORD[16+r11] - movdqa xmm9,xmm5 - psrlq xmm5,1 - movdqa xmm10,xmm3 - psrlq xmm3,1 - pxor xmm5,xmm6 - pxor xmm3,xmm4 - pand xmm5,xmm7 - pand xmm3,xmm7 - pxor xmm6,xmm5 - psllq xmm5,1 - pxor xmm4,xmm3 - psllq xmm3,1 - pxor xmm5,xmm9 - pxor xmm3,xmm10 - movdqa xmm9,xmm1 - psrlq xmm1,1 - movdqa xmm10,xmm15 - psrlq xmm15,1 - pxor xmm1,xmm2 - pxor xmm15,xmm0 - pand xmm1,xmm7 - pand xmm15,xmm7 - pxor xmm2,xmm1 - psllq xmm1,1 - pxor xmm0,xmm15 - psllq xmm15,1 - pxor xmm1,xmm9 - pxor xmm15,xmm10 - movdqa xmm7,XMMWORD[32+r11] - movdqa xmm9,xmm4 - psrlq xmm4,2 - movdqa xmm10,xmm3 - psrlq xmm3,2 - pxor xmm4,xmm6 - pxor xmm3,xmm5 - pand xmm4,xmm8 - pand xmm3,xmm8 - pxor xmm6,xmm4 - psllq xmm4,2 - pxor xmm5,xmm3 - psllq xmm3,2 - pxor xmm4,xmm9 - pxor xmm3,xmm10 - movdqa xmm9,xmm0 - psrlq xmm0,2 - movdqa xmm10,xmm15 - psrlq xmm15,2 - pxor xmm0,xmm2 - pxor xmm15,xmm1 - pand xmm0,xmm8 - pand xmm15,xmm8 - pxor xmm2,xmm0 - psllq xmm0,2 - pxor xmm1,xmm15 - psllq xmm15,2 - pxor xmm0,xmm9 - pxor xmm15,xmm10 - movdqa xmm9,xmm2 - psrlq xmm2,4 - movdqa xmm10,xmm1 - psrlq xmm1,4 - pxor xmm2,xmm6 - pxor xmm1,xmm5 - pand xmm2,xmm7 - pand xmm1,xmm7 - pxor xmm6,xmm2 - psllq xmm2,4 - pxor xmm5,xmm1 - psllq xmm1,4 - pxor xmm2,xmm9 - pxor xmm1,xmm10 - movdqa xmm9,xmm0 - psrlq xmm0,4 - movdqa xmm10,xmm15 - psrlq xmm15,4 - pxor xmm0,xmm4 - pxor xmm15,xmm3 - pand xmm0,xmm7 - pand xmm15,xmm7 - pxor xmm4,xmm0 - psllq xmm0,4 - pxor xmm3,xmm15 - psllq xmm15,4 - pxor xmm0,xmm9 - pxor xmm15,xmm10 - dec r10d - jmp NEAR $L$dec_sbox -ALIGN 16 -$L$dec_loop: - pxor xmm15,XMMWORD[rax] - pxor xmm0,XMMWORD[16+rax] - pxor xmm1,XMMWORD[32+rax] - pxor xmm2,XMMWORD[48+rax] -DB 102,68,15,56,0,255 -DB 102,15,56,0,199 - pxor xmm3,XMMWORD[64+rax] - pxor xmm4,XMMWORD[80+rax] -DB 102,15,56,0,207 -DB 102,15,56,0,215 - pxor xmm5,XMMWORD[96+rax] - pxor xmm6,XMMWORD[112+rax] -DB 102,15,56,0,223 -DB 102,15,56,0,231 -DB 102,15,56,0,239 -DB 102,15,56,0,247 - lea rax,[128+rax] -$L$dec_sbox: - pxor xmm2,xmm3 - - pxor xmm3,xmm6 - pxor xmm1,xmm6 - pxor xmm5,xmm3 - pxor xmm6,xmm5 - pxor xmm0,xmm6 - - pxor xmm15,xmm0 - pxor xmm1,xmm4 - pxor xmm2,xmm15 - pxor xmm4,xmm15 - pxor xmm0,xmm2 - movdqa xmm10,xmm2 - movdqa xmm9,xmm6 - movdqa xmm8,xmm0 - movdqa xmm12,xmm3 - movdqa xmm11,xmm4 - - pxor xmm10,xmm15 - pxor xmm9,xmm3 - pxor xmm8,xmm5 - movdqa xmm13,xmm10 - pxor xmm12,xmm15 - movdqa xmm7,xmm9 - pxor xmm11,xmm1 - movdqa xmm14,xmm10 - - por xmm9,xmm8 - por xmm10,xmm11 - pxor xmm14,xmm7 - pand xmm13,xmm11 - pxor xmm11,xmm8 - pand xmm7,xmm8 - pand xmm14,xmm11 - movdqa xmm11,xmm5 - pxor xmm11,xmm1 - pand xmm12,xmm11 - pxor xmm10,xmm12 - pxor xmm9,xmm12 - movdqa xmm12,xmm2 - movdqa xmm11,xmm0 - pxor xmm12,xmm6 - pxor xmm11,xmm4 - movdqa xmm8,xmm12 - pand xmm12,xmm11 - por xmm8,xmm11 - pxor xmm7,xmm12 - pxor xmm10,xmm14 - pxor xmm9,xmm13 - pxor xmm8,xmm14 - movdqa xmm11,xmm3 - pxor xmm7,xmm13 - movdqa xmm12,xmm15 - pxor xmm8,xmm13 - movdqa xmm13,xmm6 - pand xmm11,xmm5 - movdqa xmm14,xmm2 - pand xmm12,xmm1 - pand xmm13,xmm0 - por xmm14,xmm4 - pxor xmm10,xmm11 - pxor xmm9,xmm12 - pxor xmm8,xmm13 - pxor xmm7,xmm14 - - - - - - movdqa xmm11,xmm10 - pand xmm10,xmm8 - pxor xmm11,xmm9 - - movdqa xmm13,xmm7 - movdqa xmm14,xmm11 - pxor xmm13,xmm10 - pand xmm14,xmm13 - - movdqa xmm12,xmm8 - pxor xmm14,xmm9 - pxor xmm12,xmm7 - - pxor xmm10,xmm9 - - pand xmm12,xmm10 - - movdqa xmm9,xmm13 - pxor xmm12,xmm7 - - pxor xmm9,xmm12 - pxor xmm8,xmm12 - - pand xmm9,xmm7 - - pxor xmm13,xmm9 - pxor xmm8,xmm9 - - pand xmm13,xmm14 - - pxor xmm13,xmm11 - movdqa xmm11,xmm4 - movdqa xmm7,xmm0 - movdqa xmm9,xmm14 - pxor xmm9,xmm13 - pand xmm9,xmm4 - pxor xmm4,xmm0 - pand xmm0,xmm14 - pand xmm4,xmm13 - pxor xmm4,xmm0 - pxor xmm0,xmm9 - pxor xmm11,xmm1 - pxor xmm7,xmm5 - pxor xmm14,xmm12 - pxor xmm13,xmm8 - movdqa xmm10,xmm14 - movdqa xmm9,xmm12 - pxor xmm10,xmm13 - pxor xmm9,xmm8 - pand xmm10,xmm11 - pand xmm9,xmm1 - pxor xmm11,xmm7 - pxor xmm1,xmm5 - pand xmm7,xmm14 - pand xmm5,xmm12 - pand xmm11,xmm13 - pand xmm1,xmm8 - pxor xmm7,xmm11 - pxor xmm1,xmm5 - pxor xmm11,xmm10 - pxor xmm5,xmm9 - pxor xmm4,xmm11 - pxor xmm1,xmm11 - pxor xmm0,xmm7 - pxor xmm5,xmm7 - - movdqa xmm11,xmm2 - movdqa xmm7,xmm6 - pxor xmm11,xmm15 - pxor xmm7,xmm3 - movdqa xmm10,xmm14 - movdqa xmm9,xmm12 - pxor xmm10,xmm13 - pxor xmm9,xmm8 - pand xmm10,xmm11 - pand xmm9,xmm15 - pxor xmm11,xmm7 - pxor xmm15,xmm3 - pand xmm7,xmm14 - pand xmm3,xmm12 - pand xmm11,xmm13 - pand xmm15,xmm8 - pxor xmm7,xmm11 - pxor xmm15,xmm3 - pxor xmm11,xmm10 - pxor xmm3,xmm9 - pxor xmm14,xmm12 - pxor xmm13,xmm8 - movdqa xmm10,xmm14 - pxor xmm10,xmm13 - pand xmm10,xmm2 - pxor xmm2,xmm6 - pand xmm6,xmm14 - pand xmm2,xmm13 - pxor xmm2,xmm6 - pxor xmm6,xmm10 - pxor xmm2,xmm11 - pxor xmm15,xmm11 - pxor xmm6,xmm7 - pxor xmm3,xmm7 - pxor xmm0,xmm6 - pxor xmm5,xmm4 - - pxor xmm3,xmm0 - pxor xmm1,xmm6 - pxor xmm4,xmm6 - pxor xmm3,xmm1 - pxor xmm6,xmm15 - pxor xmm3,xmm4 - pxor xmm2,xmm5 - pxor xmm5,xmm0 - pxor xmm2,xmm3 - - pxor xmm3,xmm15 - pxor xmm6,xmm2 - dec r10d - jl NEAR $L$dec_done - - pshufd xmm7,xmm15,0x4E - pshufd xmm13,xmm2,0x4E - pxor xmm7,xmm15 - pshufd xmm14,xmm4,0x4E - pxor xmm13,xmm2 - pshufd xmm8,xmm0,0x4E - pxor xmm14,xmm4 - pshufd xmm9,xmm5,0x4E - pxor xmm8,xmm0 - pshufd xmm10,xmm3,0x4E - pxor xmm9,xmm5 - pxor xmm15,xmm13 - pxor xmm0,xmm13 - pshufd xmm11,xmm1,0x4E - pxor xmm10,xmm3 - pxor xmm5,xmm7 - pxor xmm3,xmm8 - pshufd xmm12,xmm6,0x4E - pxor xmm11,xmm1 - pxor xmm0,xmm14 - pxor xmm1,xmm9 - pxor xmm12,xmm6 - - pxor xmm5,xmm14 - pxor xmm3,xmm13 - pxor xmm1,xmm13 - pxor xmm6,xmm10 - pxor xmm2,xmm11 - pxor xmm1,xmm14 - pxor xmm6,xmm14 - pxor xmm4,xmm12 - pshufd xmm7,xmm15,0x93 - pshufd xmm8,xmm0,0x93 - pxor xmm15,xmm7 - pshufd xmm9,xmm5,0x93 - pxor xmm0,xmm8 - pshufd xmm10,xmm3,0x93 - pxor xmm5,xmm9 - pshufd xmm11,xmm1,0x93 - pxor xmm3,xmm10 - pshufd xmm12,xmm6,0x93 - pxor xmm1,xmm11 - pshufd xmm13,xmm2,0x93 - pxor xmm6,xmm12 - pshufd xmm14,xmm4,0x93 - pxor xmm2,xmm13 - pxor xmm4,xmm14 - - pxor xmm8,xmm15 - pxor xmm7,xmm4 - pxor xmm8,xmm4 - pshufd xmm15,xmm15,0x4E - pxor xmm9,xmm0 - pshufd xmm0,xmm0,0x4E - pxor xmm12,xmm1 - pxor xmm15,xmm7 - pxor xmm13,xmm6 - pxor xmm0,xmm8 - pxor xmm11,xmm3 - pshufd xmm7,xmm1,0x4E - pxor xmm14,xmm2 - pshufd xmm8,xmm6,0x4E - pxor xmm10,xmm5 - pshufd xmm1,xmm3,0x4E - pxor xmm10,xmm4 - pshufd xmm6,xmm4,0x4E - pxor xmm11,xmm4 - pshufd xmm3,xmm2,0x4E - pxor xmm7,xmm11 - pshufd xmm2,xmm5,0x4E - pxor xmm8,xmm12 - pxor xmm10,xmm1 - pxor xmm6,xmm14 - pxor xmm13,xmm3 - movdqa xmm3,xmm7 - pxor xmm2,xmm9 - movdqa xmm5,xmm13 - movdqa xmm4,xmm8 - movdqa xmm1,xmm2 - movdqa xmm2,xmm10 - movdqa xmm7,XMMWORD[((-16))+r11] - jnz NEAR $L$dec_loop - movdqa xmm7,XMMWORD[((-32))+r11] - jmp NEAR $L$dec_loop -ALIGN 16 -$L$dec_done: - movdqa xmm7,XMMWORD[r11] - movdqa xmm8,XMMWORD[16+r11] - movdqa xmm9,xmm2 - psrlq xmm2,1 - movdqa xmm10,xmm1 - psrlq xmm1,1 - pxor xmm2,xmm4 - pxor xmm1,xmm6 - pand xmm2,xmm7 - pand xmm1,xmm7 - pxor xmm4,xmm2 - psllq xmm2,1 - pxor xmm6,xmm1 - psllq xmm1,1 - pxor xmm2,xmm9 - pxor xmm1,xmm10 - movdqa xmm9,xmm5 - psrlq xmm5,1 - movdqa xmm10,xmm15 - psrlq xmm15,1 - pxor xmm5,xmm3 - pxor xmm15,xmm0 - pand xmm5,xmm7 - pand xmm15,xmm7 - pxor xmm3,xmm5 - psllq xmm5,1 - pxor xmm0,xmm15 - psllq xmm15,1 - pxor xmm5,xmm9 - pxor xmm15,xmm10 - movdqa xmm7,XMMWORD[32+r11] - movdqa xmm9,xmm6 - psrlq xmm6,2 - movdqa xmm10,xmm1 - psrlq xmm1,2 - pxor xmm6,xmm4 - pxor xmm1,xmm2 - pand xmm6,xmm8 - pand xmm1,xmm8 - pxor xmm4,xmm6 - psllq xmm6,2 - pxor xmm2,xmm1 - psllq xmm1,2 - pxor xmm6,xmm9 - pxor xmm1,xmm10 - movdqa xmm9,xmm0 - psrlq xmm0,2 - movdqa xmm10,xmm15 - psrlq xmm15,2 - pxor xmm0,xmm3 - pxor xmm15,xmm5 - pand xmm0,xmm8 - pand xmm15,xmm8 - pxor xmm3,xmm0 - psllq xmm0,2 - pxor xmm5,xmm15 - psllq xmm15,2 - pxor xmm0,xmm9 - pxor xmm15,xmm10 - movdqa xmm9,xmm3 - psrlq xmm3,4 - movdqa xmm10,xmm5 - psrlq xmm5,4 - pxor xmm3,xmm4 - pxor xmm5,xmm2 - pand xmm3,xmm7 - pand xmm5,xmm7 - pxor xmm4,xmm3 - psllq xmm3,4 - pxor xmm2,xmm5 - psllq xmm5,4 - pxor xmm3,xmm9 - pxor xmm5,xmm10 - movdqa xmm9,xmm0 - psrlq xmm0,4 - movdqa xmm10,xmm15 - psrlq xmm15,4 - pxor xmm0,xmm6 - pxor xmm15,xmm1 - pand xmm0,xmm7 - pand xmm15,xmm7 - pxor xmm6,xmm0 - psllq xmm0,4 - pxor xmm1,xmm15 - psllq xmm15,4 - pxor xmm0,xmm9 - pxor xmm15,xmm10 - movdqa xmm7,XMMWORD[rax] - pxor xmm5,xmm7 - pxor xmm3,xmm7 - pxor xmm1,xmm7 - pxor xmm6,xmm7 - pxor xmm2,xmm7 - pxor xmm4,xmm7 - pxor xmm15,xmm7 - pxor xmm0,xmm7 - DB 0F3h,0C3h ;repret - - - -ALIGN 16 -_bsaes_key_convert: - - lea r11,[$L$masks] - movdqu xmm7,XMMWORD[rcx] - lea rcx,[16+rcx] - movdqa xmm0,XMMWORD[r11] - movdqa xmm1,XMMWORD[16+r11] - movdqa xmm2,XMMWORD[32+r11] - movdqa xmm3,XMMWORD[48+r11] - movdqa xmm4,XMMWORD[64+r11] - pcmpeqd xmm5,xmm5 - - movdqu xmm6,XMMWORD[rcx] - movdqa XMMWORD[rax],xmm7 - lea rax,[16+rax] - dec r10d - jmp NEAR $L$key_loop -ALIGN 16 -$L$key_loop: -DB 102,15,56,0,244 - - movdqa xmm8,xmm0 - movdqa xmm9,xmm1 - - pand xmm8,xmm6 - pand xmm9,xmm6 - movdqa xmm10,xmm2 - pcmpeqb xmm8,xmm0 - psllq xmm0,4 - movdqa xmm11,xmm3 - pcmpeqb xmm9,xmm1 - psllq xmm1,4 - - pand xmm10,xmm6 - pand xmm11,xmm6 - movdqa xmm12,xmm0 - pcmpeqb xmm10,xmm2 - psllq xmm2,4 - movdqa xmm13,xmm1 - pcmpeqb xmm11,xmm3 - psllq xmm3,4 - - movdqa xmm14,xmm2 - movdqa xmm15,xmm3 - pxor xmm8,xmm5 - pxor xmm9,xmm5 - - pand xmm12,xmm6 - pand xmm13,xmm6 - movdqa XMMWORD[rax],xmm8 - pcmpeqb xmm12,xmm0 - psrlq xmm0,4 - movdqa XMMWORD[16+rax],xmm9 - pcmpeqb xmm13,xmm1 - psrlq xmm1,4 - lea rcx,[16+rcx] - - pand xmm14,xmm6 - pand xmm15,xmm6 - movdqa XMMWORD[32+rax],xmm10 - pcmpeqb xmm14,xmm2 - psrlq xmm2,4 - movdqa XMMWORD[48+rax],xmm11 - pcmpeqb xmm15,xmm3 - psrlq xmm3,4 - movdqu xmm6,XMMWORD[rcx] - - pxor xmm13,xmm5 - pxor xmm14,xmm5 - movdqa XMMWORD[64+rax],xmm12 - movdqa XMMWORD[80+rax],xmm13 - movdqa XMMWORD[96+rax],xmm14 - movdqa XMMWORD[112+rax],xmm15 - lea rax,[128+rax] - dec r10d - jnz NEAR $L$key_loop - - movdqa xmm7,XMMWORD[80+r11] - - DB 0F3h,0C3h ;repret - - -EXTERN aes_nohw_cbc_encrypt -global bsaes_cbc_encrypt - -ALIGN 16 -bsaes_cbc_encrypt: - - mov r11d,DWORD[48+rsp] - cmp r11d,0 - jne NEAR aes_nohw_cbc_encrypt - cmp r8,128 - jb NEAR aes_nohw_cbc_encrypt - - mov rax,rsp -$L$cbc_dec_prologue: - push rbp - - push rbx - - push r12 - - push r13 - - push r14 - - push r15 - - lea rsp,[((-72))+rsp] - - mov r10,QWORD[160+rsp] - lea rsp,[((-160))+rsp] - movaps XMMWORD[64+rsp],xmm6 - movaps XMMWORD[80+rsp],xmm7 - movaps XMMWORD[96+rsp],xmm8 - movaps XMMWORD[112+rsp],xmm9 - movaps XMMWORD[128+rsp],xmm10 - movaps XMMWORD[144+rsp],xmm11 - movaps XMMWORD[160+rsp],xmm12 - movaps XMMWORD[176+rsp],xmm13 - movaps XMMWORD[192+rsp],xmm14 - movaps XMMWORD[208+rsp],xmm15 -$L$cbc_dec_body: - mov rbp,rsp - - mov eax,DWORD[240+r9] - mov r12,rcx - mov r13,rdx - mov r14,r8 - mov r15,r9 - mov rbx,r10 - shr r14,4 - - mov edx,eax - shl rax,7 - sub rax,96 - sub rsp,rax - - mov rax,rsp - mov rcx,r15 - mov r10d,edx - call _bsaes_key_convert - pxor xmm7,XMMWORD[rsp] - movdqa XMMWORD[rax],xmm6 - movdqa XMMWORD[rsp],xmm7 - - movdqu xmm14,XMMWORD[rbx] - sub r14,8 -$L$cbc_dec_loop: - movdqu xmm15,XMMWORD[r12] - movdqu xmm0,XMMWORD[16+r12] - movdqu xmm1,XMMWORD[32+r12] - movdqu xmm2,XMMWORD[48+r12] - movdqu xmm3,XMMWORD[64+r12] - movdqu xmm4,XMMWORD[80+r12] - mov rax,rsp - movdqu xmm5,XMMWORD[96+r12] - mov r10d,edx - movdqu xmm6,XMMWORD[112+r12] - movdqa XMMWORD[32+rbp],xmm14 - - call _bsaes_decrypt8 - - pxor xmm15,XMMWORD[32+rbp] - movdqu xmm7,XMMWORD[r12] - movdqu xmm8,XMMWORD[16+r12] - pxor xmm0,xmm7 - movdqu xmm9,XMMWORD[32+r12] - pxor xmm5,xmm8 - movdqu xmm10,XMMWORD[48+r12] - pxor xmm3,xmm9 - movdqu xmm11,XMMWORD[64+r12] - pxor xmm1,xmm10 - movdqu xmm12,XMMWORD[80+r12] - pxor xmm6,xmm11 - movdqu xmm13,XMMWORD[96+r12] - pxor xmm2,xmm12 - movdqu xmm14,XMMWORD[112+r12] - pxor xmm4,xmm13 - movdqu XMMWORD[r13],xmm15 - lea r12,[128+r12] - movdqu XMMWORD[16+r13],xmm0 - movdqu XMMWORD[32+r13],xmm5 - movdqu XMMWORD[48+r13],xmm3 - movdqu XMMWORD[64+r13],xmm1 - movdqu XMMWORD[80+r13],xmm6 - movdqu XMMWORD[96+r13],xmm2 - movdqu XMMWORD[112+r13],xmm4 - lea r13,[128+r13] - sub r14,8 - jnc NEAR $L$cbc_dec_loop - - add r14,8 - jz NEAR $L$cbc_dec_done - - movdqu xmm15,XMMWORD[r12] - mov rax,rsp - mov r10d,edx - cmp r14,2 - jb NEAR $L$cbc_dec_one - movdqu xmm0,XMMWORD[16+r12] - je NEAR $L$cbc_dec_two - movdqu xmm1,XMMWORD[32+r12] - cmp r14,4 - jb NEAR $L$cbc_dec_three - movdqu xmm2,XMMWORD[48+r12] - je NEAR $L$cbc_dec_four - movdqu xmm3,XMMWORD[64+r12] - cmp r14,6 - jb NEAR $L$cbc_dec_five - movdqu xmm4,XMMWORD[80+r12] - je NEAR $L$cbc_dec_six - movdqu xmm5,XMMWORD[96+r12] - movdqa XMMWORD[32+rbp],xmm14 - call _bsaes_decrypt8 - pxor xmm15,XMMWORD[32+rbp] - movdqu xmm7,XMMWORD[r12] - movdqu xmm8,XMMWORD[16+r12] - pxor xmm0,xmm7 - movdqu xmm9,XMMWORD[32+r12] - pxor xmm5,xmm8 - movdqu xmm10,XMMWORD[48+r12] - pxor xmm3,xmm9 - movdqu xmm11,XMMWORD[64+r12] - pxor xmm1,xmm10 - movdqu xmm12,XMMWORD[80+r12] - pxor xmm6,xmm11 - movdqu xmm14,XMMWORD[96+r12] - pxor xmm2,xmm12 - movdqu XMMWORD[r13],xmm15 - movdqu XMMWORD[16+r13],xmm0 - movdqu XMMWORD[32+r13],xmm5 - movdqu XMMWORD[48+r13],xmm3 - movdqu XMMWORD[64+r13],xmm1 - movdqu XMMWORD[80+r13],xmm6 - movdqu XMMWORD[96+r13],xmm2 - jmp NEAR $L$cbc_dec_done -ALIGN 16 -$L$cbc_dec_six: - movdqa XMMWORD[32+rbp],xmm14 - call _bsaes_decrypt8 - pxor xmm15,XMMWORD[32+rbp] - movdqu xmm7,XMMWORD[r12] - movdqu xmm8,XMMWORD[16+r12] - pxor xmm0,xmm7 - movdqu xmm9,XMMWORD[32+r12] - pxor xmm5,xmm8 - movdqu xmm10,XMMWORD[48+r12] - pxor xmm3,xmm9 - movdqu xmm11,XMMWORD[64+r12] - pxor xmm1,xmm10 - movdqu xmm14,XMMWORD[80+r12] - pxor xmm6,xmm11 - movdqu XMMWORD[r13],xmm15 - movdqu XMMWORD[16+r13],xmm0 - movdqu XMMWORD[32+r13],xmm5 - movdqu XMMWORD[48+r13],xmm3 - movdqu XMMWORD[64+r13],xmm1 - movdqu XMMWORD[80+r13],xmm6 - jmp NEAR $L$cbc_dec_done -ALIGN 16 -$L$cbc_dec_five: - movdqa XMMWORD[32+rbp],xmm14 - call _bsaes_decrypt8 - pxor xmm15,XMMWORD[32+rbp] - movdqu xmm7,XMMWORD[r12] - movdqu xmm8,XMMWORD[16+r12] - pxor xmm0,xmm7 - movdqu xmm9,XMMWORD[32+r12] - pxor xmm5,xmm8 - movdqu xmm10,XMMWORD[48+r12] - pxor xmm3,xmm9 - movdqu xmm14,XMMWORD[64+r12] - pxor xmm1,xmm10 - movdqu XMMWORD[r13],xmm15 - movdqu XMMWORD[16+r13],xmm0 - movdqu XMMWORD[32+r13],xmm5 - movdqu XMMWORD[48+r13],xmm3 - movdqu XMMWORD[64+r13],xmm1 - jmp NEAR $L$cbc_dec_done -ALIGN 16 -$L$cbc_dec_four: - movdqa XMMWORD[32+rbp],xmm14 - call _bsaes_decrypt8 - pxor xmm15,XMMWORD[32+rbp] - movdqu xmm7,XMMWORD[r12] - movdqu xmm8,XMMWORD[16+r12] - pxor xmm0,xmm7 - movdqu xmm9,XMMWORD[32+r12] - pxor xmm5,xmm8 - movdqu xmm14,XMMWORD[48+r12] - pxor xmm3,xmm9 - movdqu XMMWORD[r13],xmm15 - movdqu XMMWORD[16+r13],xmm0 - movdqu XMMWORD[32+r13],xmm5 - movdqu XMMWORD[48+r13],xmm3 - jmp NEAR $L$cbc_dec_done -ALIGN 16 -$L$cbc_dec_three: - movdqa XMMWORD[32+rbp],xmm14 - call _bsaes_decrypt8 - pxor xmm15,XMMWORD[32+rbp] - movdqu xmm7,XMMWORD[r12] - movdqu xmm8,XMMWORD[16+r12] - pxor xmm0,xmm7 - movdqu xmm14,XMMWORD[32+r12] - pxor xmm5,xmm8 - movdqu XMMWORD[r13],xmm15 - movdqu XMMWORD[16+r13],xmm0 - movdqu XMMWORD[32+r13],xmm5 - jmp NEAR $L$cbc_dec_done -ALIGN 16 -$L$cbc_dec_two: - movdqa XMMWORD[32+rbp],xmm14 - call _bsaes_decrypt8 - pxor xmm15,XMMWORD[32+rbp] - movdqu xmm7,XMMWORD[r12] - movdqu xmm14,XMMWORD[16+r12] - pxor xmm0,xmm7 - movdqu XMMWORD[r13],xmm15 - movdqu XMMWORD[16+r13],xmm0 - jmp NEAR $L$cbc_dec_done -ALIGN 16 -$L$cbc_dec_one: - lea rcx,[r12] - lea rdx,[32+rbp] - lea r8,[r15] - call aes_nohw_decrypt - pxor xmm14,XMMWORD[32+rbp] - movdqu XMMWORD[r13],xmm14 - movdqa xmm14,xmm15 - -$L$cbc_dec_done: - movdqu XMMWORD[rbx],xmm14 - lea rax,[rsp] - pxor xmm0,xmm0 -$L$cbc_dec_bzero: - movdqa XMMWORD[rax],xmm0 - movdqa XMMWORD[16+rax],xmm0 - lea rax,[32+rax] - cmp rbp,rax - ja NEAR $L$cbc_dec_bzero - - lea rax,[120+rbp] - - movaps xmm6,XMMWORD[64+rbp] - movaps xmm7,XMMWORD[80+rbp] - movaps xmm8,XMMWORD[96+rbp] - movaps xmm9,XMMWORD[112+rbp] - movaps xmm10,XMMWORD[128+rbp] - movaps xmm11,XMMWORD[144+rbp] - movaps xmm12,XMMWORD[160+rbp] - movaps xmm13,XMMWORD[176+rbp] - movaps xmm14,XMMWORD[192+rbp] - movaps xmm15,XMMWORD[208+rbp] - lea rax,[160+rax] -$L$cbc_dec_tail: - mov r15,QWORD[((-48))+rax] - - mov r14,QWORD[((-40))+rax] - - mov r13,QWORD[((-32))+rax] - - mov r12,QWORD[((-24))+rax] - - mov rbx,QWORD[((-16))+rax] - - mov rbp,QWORD[((-8))+rax] - - lea rsp,[rax] - -$L$cbc_dec_epilogue: - DB 0F3h,0C3h ;repret - - - -global bsaes_ctr32_encrypt_blocks - -ALIGN 16 -bsaes_ctr32_encrypt_blocks: - - mov rax,rsp -$L$ctr_enc_prologue: - push rbp - - push rbx - - push r12 - - push r13 - - push r14 - - push r15 - - lea rsp,[((-72))+rsp] - - mov r10,QWORD[160+rsp] - lea rsp,[((-160))+rsp] - movaps XMMWORD[64+rsp],xmm6 - movaps XMMWORD[80+rsp],xmm7 - movaps XMMWORD[96+rsp],xmm8 - movaps XMMWORD[112+rsp],xmm9 - movaps XMMWORD[128+rsp],xmm10 - movaps XMMWORD[144+rsp],xmm11 - movaps XMMWORD[160+rsp],xmm12 - movaps XMMWORD[176+rsp],xmm13 - movaps XMMWORD[192+rsp],xmm14 - movaps XMMWORD[208+rsp],xmm15 -$L$ctr_enc_body: - mov rbp,rsp - - movdqu xmm0,XMMWORD[r10] - mov eax,DWORD[240+r9] - mov r12,rcx - mov r13,rdx - mov r14,r8 - mov r15,r9 - movdqa XMMWORD[32+rbp],xmm0 - cmp r8,8 - jb NEAR $L$ctr_enc_short - - mov ebx,eax - shl rax,7 - sub rax,96 - sub rsp,rax - - mov rax,rsp - mov rcx,r15 - mov r10d,ebx - call _bsaes_key_convert - pxor xmm7,xmm6 - movdqa XMMWORD[rax],xmm7 - - movdqa xmm8,XMMWORD[rsp] - lea r11,[$L$ADD1] - movdqa xmm15,XMMWORD[32+rbp] - movdqa xmm7,XMMWORD[((-32))+r11] -DB 102,68,15,56,0,199 -DB 102,68,15,56,0,255 - movdqa XMMWORD[rsp],xmm8 - jmp NEAR $L$ctr_enc_loop -ALIGN 16 -$L$ctr_enc_loop: - movdqa XMMWORD[32+rbp],xmm15 - movdqa xmm0,xmm15 - movdqa xmm1,xmm15 - paddd xmm0,XMMWORD[r11] - movdqa xmm2,xmm15 - paddd xmm1,XMMWORD[16+r11] - movdqa xmm3,xmm15 - paddd xmm2,XMMWORD[32+r11] - movdqa xmm4,xmm15 - paddd xmm3,XMMWORD[48+r11] - movdqa xmm5,xmm15 - paddd xmm4,XMMWORD[64+r11] - movdqa xmm6,xmm15 - paddd xmm5,XMMWORD[80+r11] - paddd xmm6,XMMWORD[96+r11] - - - - movdqa xmm8,XMMWORD[rsp] - lea rax,[16+rsp] - movdqa xmm7,XMMWORD[((-16))+r11] - pxor xmm15,xmm8 - pxor xmm0,xmm8 - pxor xmm1,xmm8 - pxor xmm2,xmm8 -DB 102,68,15,56,0,255 -DB 102,15,56,0,199 - pxor xmm3,xmm8 - pxor xmm4,xmm8 -DB 102,15,56,0,207 -DB 102,15,56,0,215 - pxor xmm5,xmm8 - pxor xmm6,xmm8 -DB 102,15,56,0,223 -DB 102,15,56,0,231 -DB 102,15,56,0,239 -DB 102,15,56,0,247 - lea r11,[$L$BS0] - mov r10d,ebx - - call _bsaes_encrypt8_bitslice - - sub r14,8 - jc NEAR $L$ctr_enc_loop_done - - movdqu xmm7,XMMWORD[r12] - movdqu xmm8,XMMWORD[16+r12] - movdqu xmm9,XMMWORD[32+r12] - movdqu xmm10,XMMWORD[48+r12] - movdqu xmm11,XMMWORD[64+r12] - movdqu xmm12,XMMWORD[80+r12] - movdqu xmm13,XMMWORD[96+r12] - movdqu xmm14,XMMWORD[112+r12] - lea r12,[128+r12] - pxor xmm7,xmm15 - movdqa xmm15,XMMWORD[32+rbp] - pxor xmm0,xmm8 - movdqu XMMWORD[r13],xmm7 - pxor xmm3,xmm9 - movdqu XMMWORD[16+r13],xmm0 - pxor xmm5,xmm10 - movdqu XMMWORD[32+r13],xmm3 - pxor xmm2,xmm11 - movdqu XMMWORD[48+r13],xmm5 - pxor xmm6,xmm12 - movdqu XMMWORD[64+r13],xmm2 - pxor xmm1,xmm13 - movdqu XMMWORD[80+r13],xmm6 - pxor xmm4,xmm14 - movdqu XMMWORD[96+r13],xmm1 - lea r11,[$L$ADD1] - movdqu XMMWORD[112+r13],xmm4 - lea r13,[128+r13] - paddd xmm15,XMMWORD[112+r11] - jnz NEAR $L$ctr_enc_loop - - jmp NEAR $L$ctr_enc_done -ALIGN 16 -$L$ctr_enc_loop_done: - add r14,8 - movdqu xmm7,XMMWORD[r12] - pxor xmm15,xmm7 - movdqu XMMWORD[r13],xmm15 - cmp r14,2 - jb NEAR $L$ctr_enc_done - movdqu xmm8,XMMWORD[16+r12] - pxor xmm0,xmm8 - movdqu XMMWORD[16+r13],xmm0 - je NEAR $L$ctr_enc_done - movdqu xmm9,XMMWORD[32+r12] - pxor xmm3,xmm9 - movdqu XMMWORD[32+r13],xmm3 - cmp r14,4 - jb NEAR $L$ctr_enc_done - movdqu xmm10,XMMWORD[48+r12] - pxor xmm5,xmm10 - movdqu XMMWORD[48+r13],xmm5 - je NEAR $L$ctr_enc_done - movdqu xmm11,XMMWORD[64+r12] - pxor xmm2,xmm11 - movdqu XMMWORD[64+r13],xmm2 - cmp r14,6 - jb NEAR $L$ctr_enc_done - movdqu xmm12,XMMWORD[80+r12] - pxor xmm6,xmm12 - movdqu XMMWORD[80+r13],xmm6 - je NEAR $L$ctr_enc_done - movdqu xmm13,XMMWORD[96+r12] - pxor xmm1,xmm13 - movdqu XMMWORD[96+r13],xmm1 - jmp NEAR $L$ctr_enc_done - -ALIGN 16 -$L$ctr_enc_short: - lea rcx,[32+rbp] - lea rdx,[48+rbp] - lea r8,[r15] - call aes_nohw_encrypt - movdqu xmm0,XMMWORD[r12] - lea r12,[16+r12] - mov eax,DWORD[44+rbp] - bswap eax - pxor xmm0,XMMWORD[48+rbp] - inc eax - movdqu XMMWORD[r13],xmm0 - bswap eax - lea r13,[16+r13] - mov DWORD[44+rsp],eax - dec r14 - jnz NEAR $L$ctr_enc_short - -$L$ctr_enc_done: - lea rax,[rsp] - pxor xmm0,xmm0 -$L$ctr_enc_bzero: - movdqa XMMWORD[rax],xmm0 - movdqa XMMWORD[16+rax],xmm0 - lea rax,[32+rax] - cmp rbp,rax - ja NEAR $L$ctr_enc_bzero - - lea rax,[120+rbp] - - movaps xmm6,XMMWORD[64+rbp] - movaps xmm7,XMMWORD[80+rbp] - movaps xmm8,XMMWORD[96+rbp] - movaps xmm9,XMMWORD[112+rbp] - movaps xmm10,XMMWORD[128+rbp] - movaps xmm11,XMMWORD[144+rbp] - movaps xmm12,XMMWORD[160+rbp] - movaps xmm13,XMMWORD[176+rbp] - movaps xmm14,XMMWORD[192+rbp] - movaps xmm15,XMMWORD[208+rbp] - lea rax,[160+rax] -$L$ctr_enc_tail: - mov r15,QWORD[((-48))+rax] - - mov r14,QWORD[((-40))+rax] - - mov r13,QWORD[((-32))+rax] - - mov r12,QWORD[((-24))+rax] - - mov rbx,QWORD[((-16))+rax] - - mov rbp,QWORD[((-8))+rax] - - lea rsp,[rax] - -$L$ctr_enc_epilogue: - DB 0F3h,0C3h ;repret - - - -ALIGN 64 -_bsaes_const: -$L$M0ISR: - DQ 0x0a0e0206070b0f03,0x0004080c0d010509 -$L$ISRM0: - DQ 0x01040b0e0205080f,0x0306090c00070a0d -$L$ISR: - DQ 0x0504070602010003,0x0f0e0d0c080b0a09 -$L$BS0: - DQ 0x5555555555555555,0x5555555555555555 -$L$BS1: - DQ 0x3333333333333333,0x3333333333333333 -$L$BS2: - DQ 0x0f0f0f0f0f0f0f0f,0x0f0f0f0f0f0f0f0f -$L$SR: - DQ 0x0504070600030201,0x0f0e0d0c0a09080b -$L$SRM0: - DQ 0x0304090e00050a0f,0x01060b0c0207080d -$L$M0SR: - DQ 0x0a0e02060f03070b,0x0004080c05090d01 -$L$SWPUP: - DQ 0x0706050403020100,0x0c0d0e0f0b0a0908 -$L$SWPUPM0SR: - DQ 0x0a0d02060c03070b,0x0004080f05090e01 -$L$ADD1: - DQ 0x0000000000000000,0x0000000100000000 -$L$ADD2: - DQ 0x0000000000000000,0x0000000200000000 -$L$ADD3: - DQ 0x0000000000000000,0x0000000300000000 -$L$ADD4: - DQ 0x0000000000000000,0x0000000400000000 -$L$ADD5: - DQ 0x0000000000000000,0x0000000500000000 -$L$ADD6: - DQ 0x0000000000000000,0x0000000600000000 -$L$ADD7: - DQ 0x0000000000000000,0x0000000700000000 -$L$ADD8: - DQ 0x0000000000000000,0x0000000800000000 -$L$xts_magic: - DD 0x87,0,1,0 -$L$masks: - DQ 0x0101010101010101,0x0101010101010101 - DQ 0x0202020202020202,0x0202020202020202 - DQ 0x0404040404040404,0x0404040404040404 - DQ 0x0808080808080808,0x0808080808080808 -$L$M0: - DQ 0x02060a0e03070b0f,0x0004080c0105090d -$L$63: - DQ 0x6363636363636363,0x6363636363636363 -DB 66,105,116,45,115,108,105,99,101,100,32,65,69,83,32,102 -DB 111,114,32,120,56,54,95,54,52,47,83,83,83,69,51,44 -DB 32,69,109,105,108,105,97,32,75,195,164,115,112,101,114,44 -DB 32,80,101,116,101,114,32,83,99,104,119,97,98,101,44,32 -DB 65,110,100,121,32,80,111,108,121,97,107,111,118,0 -ALIGN 64 - -EXTERN __imp_RtlVirtualUnwind - -ALIGN 16 -se_handler: - push rsi - push rdi - push rbx - push rbp - push r12 - push r13 - push r14 - push r15 - pushfq - sub rsp,64 - - mov rax,QWORD[120+r8] - mov rbx,QWORD[248+r8] - - mov rsi,QWORD[8+r9] - mov r11,QWORD[56+r9] - - mov r10d,DWORD[r11] - lea r10,[r10*1+rsi] - cmp rbx,r10 - jbe NEAR $L$in_prologue - - mov r10d,DWORD[4+r11] - lea r10,[r10*1+rsi] - cmp rbx,r10 - jae NEAR $L$in_prologue - - mov r10d,DWORD[8+r11] - lea r10,[r10*1+rsi] - cmp rbx,r10 - jae NEAR $L$in_tail - - mov rax,QWORD[160+r8] - - lea rsi,[64+rax] - lea rdi,[512+r8] - mov ecx,20 - DD 0xa548f3fc - lea rax,[((160+120))+rax] - -$L$in_tail: - mov rbp,QWORD[((-48))+rax] - mov rbx,QWORD[((-40))+rax] - mov r12,QWORD[((-32))+rax] - mov r13,QWORD[((-24))+rax] - mov r14,QWORD[((-16))+rax] - mov r15,QWORD[((-8))+rax] - mov QWORD[144+r8],rbx - mov QWORD[160+r8],rbp - mov QWORD[216+r8],r12 - mov QWORD[224+r8],r13 - mov QWORD[232+r8],r14 - mov QWORD[240+r8],r15 - -$L$in_prologue: - mov QWORD[152+r8],rax - - mov rdi,QWORD[40+r9] - mov rsi,r8 - mov ecx,154 - DD 0xa548f3fc - - mov rsi,r9 - xor rcx,rcx - mov rdx,QWORD[8+rsi] - mov r8,QWORD[rsi] - mov r9,QWORD[16+rsi] - mov r10,QWORD[40+rsi] - lea r11,[56+rsi] - lea r12,[24+rsi] - mov QWORD[32+rsp],r10 - mov QWORD[40+rsp],r11 - mov QWORD[48+rsp],r12 - mov QWORD[56+rsp],rcx - call QWORD[__imp_RtlVirtualUnwind] - - mov eax,1 - add rsp,64 - popfq - pop r15 - pop r14 - pop r13 - pop r12 - pop rbp - pop rbx - pop rdi - pop rsi - DB 0F3h,0C3h ;repret - - -section .pdata rdata align=4 -ALIGN 4 - DD $L$cbc_dec_prologue wrt ..imagebase - DD $L$cbc_dec_epilogue wrt ..imagebase - DD $L$cbc_dec_info wrt ..imagebase - - DD $L$ctr_enc_prologue wrt ..imagebase - DD $L$ctr_enc_epilogue wrt ..imagebase - DD $L$ctr_enc_info wrt ..imagebase - -section .xdata rdata align=8 -ALIGN 8 -$L$cbc_dec_info: -DB 9,0,0,0 - DD se_handler wrt ..imagebase - DD $L$cbc_dec_body wrt ..imagebase,$L$cbc_dec_epilogue wrt ..imagebase - DD $L$cbc_dec_tail wrt ..imagebase - DD 0 -$L$ctr_enc_info: -DB 9,0,0,0 - DD se_handler wrt ..imagebase - DD $L$ctr_enc_body wrt ..imagebase,$L$ctr_enc_epilogue wrt ..imagebase - DD $L$ctr_enc_tail wrt ..imagebase - DD 0 diff --git a/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.asm b/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.asm new file mode 100644 index 00000000..434ba10e --- /dev/null +++ b/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.asm @@ -0,0 +1,495 @@ +; This file is generated from a similarly-named Perl script in the BoringSSL +; source tree. Do not edit by hand. + +default rel +%define XMMWORD +%define YMMWORD +%define ZMMWORD + +%ifdef BORINGSSL_PREFIX +%include "boringssl_prefix_symbols_nasm.inc" +%endif +section .text code align=64 + + + + + + + +global gcm_gmult_ssse3 +ALIGN 16 +gcm_gmult_ssse3: + +$L$gmult_seh_begin: + sub rsp,40 +$L$gmult_seh_allocstack: + movdqa XMMWORD[rsp],xmm6 +$L$gmult_seh_save_xmm6: + movdqa XMMWORD[16+rsp],xmm10 +$L$gmult_seh_save_xmm10: +$L$gmult_seh_prolog_end: + movdqu xmm0,XMMWORD[rcx] + movdqa xmm10,XMMWORD[$L$reverse_bytes] + movdqa xmm2,XMMWORD[$L$low4_mask] + + +DB 102,65,15,56,0,194 + + + movdqa xmm1,xmm2 + pandn xmm1,xmm0 + psrld xmm1,4 + pand xmm0,xmm2 + + + + + pxor xmm2,xmm2 + pxor xmm3,xmm3 + mov rax,5 +$L$oop_row_1: + movdqa xmm4,XMMWORD[rdx] + lea rdx,[16+rdx] + + + movdqa xmm6,xmm2 +DB 102,15,58,15,243,1 + movdqa xmm3,xmm6 + psrldq xmm2,1 + + + + + movdqa xmm5,xmm4 +DB 102,15,56,0,224 +DB 102,15,56,0,233 + + + pxor xmm2,xmm5 + + + + movdqa xmm5,xmm4 + psllq xmm5,60 + movdqa xmm6,xmm5 + pslldq xmm6,8 + pxor xmm3,xmm6 + + + psrldq xmm5,8 + pxor xmm2,xmm5 + psrlq xmm4,4 + pxor xmm2,xmm4 + + sub rax,1 + jnz NEAR $L$oop_row_1 + + + + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,5 + pxor xmm2,xmm3 + pxor xmm3,xmm3 + mov rax,5 +$L$oop_row_2: + movdqa xmm4,XMMWORD[rdx] + lea rdx,[16+rdx] + + + movdqa xmm6,xmm2 +DB 102,15,58,15,243,1 + movdqa xmm3,xmm6 + psrldq xmm2,1 + + + + + movdqa xmm5,xmm4 +DB 102,15,56,0,224 +DB 102,15,56,0,233 + + + pxor xmm2,xmm5 + + + + movdqa xmm5,xmm4 + psllq xmm5,60 + movdqa xmm6,xmm5 + pslldq xmm6,8 + pxor xmm3,xmm6 + + + psrldq xmm5,8 + pxor xmm2,xmm5 + psrlq xmm4,4 + pxor xmm2,xmm4 + + sub rax,1 + jnz NEAR $L$oop_row_2 + + + + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,5 + pxor xmm2,xmm3 + pxor xmm3,xmm3 + mov rax,6 +$L$oop_row_3: + movdqa xmm4,XMMWORD[rdx] + lea rdx,[16+rdx] + + + movdqa xmm6,xmm2 +DB 102,15,58,15,243,1 + movdqa xmm3,xmm6 + psrldq xmm2,1 + + + + + movdqa xmm5,xmm4 +DB 102,15,56,0,224 +DB 102,15,56,0,233 + + + pxor xmm2,xmm5 + + + + movdqa xmm5,xmm4 + psllq xmm5,60 + movdqa xmm6,xmm5 + pslldq xmm6,8 + pxor xmm3,xmm6 + + + psrldq xmm5,8 + pxor xmm2,xmm5 + psrlq xmm4,4 + pxor xmm2,xmm4 + + sub rax,1 + jnz NEAR $L$oop_row_3 + + + + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,5 + pxor xmm2,xmm3 + pxor xmm3,xmm3 + +DB 102,65,15,56,0,210 + movdqu XMMWORD[rcx],xmm2 + + + pxor xmm0,xmm0 + pxor xmm1,xmm1 + pxor xmm2,xmm2 + pxor xmm3,xmm3 + pxor xmm4,xmm4 + pxor xmm5,xmm5 + pxor xmm6,xmm6 + movdqa xmm6,XMMWORD[rsp] + movdqa xmm10,XMMWORD[16+rsp] + add rsp,40 + DB 0F3h,0C3h ;repret +$L$gmult_seh_end: + + + + + + + + +global gcm_ghash_ssse3 +ALIGN 16 +gcm_ghash_ssse3: +$L$ghash_seh_begin: + + sub rsp,56 +$L$ghash_seh_allocstack: + movdqa XMMWORD[rsp],xmm6 +$L$ghash_seh_save_xmm6: + movdqa XMMWORD[16+rsp],xmm10 +$L$ghash_seh_save_xmm10: + movdqa XMMWORD[32+rsp],xmm11 +$L$ghash_seh_save_xmm11: +$L$ghash_seh_prolog_end: + movdqu xmm0,XMMWORD[rcx] + movdqa xmm10,XMMWORD[$L$reverse_bytes] + movdqa xmm11,XMMWORD[$L$low4_mask] + + + and r9,-16 + + + +DB 102,65,15,56,0,194 + + + pxor xmm3,xmm3 +$L$oop_ghash: + + movdqu xmm1,XMMWORD[r8] +DB 102,65,15,56,0,202 + pxor xmm0,xmm1 + + + movdqa xmm1,xmm11 + pandn xmm1,xmm0 + psrld xmm1,4 + pand xmm0,xmm11 + + + + + pxor xmm2,xmm2 + + mov rax,5 +$L$oop_row_4: + movdqa xmm4,XMMWORD[rdx] + lea rdx,[16+rdx] + + + movdqa xmm6,xmm2 +DB 102,15,58,15,243,1 + movdqa xmm3,xmm6 + psrldq xmm2,1 + + + + + movdqa xmm5,xmm4 +DB 102,15,56,0,224 +DB 102,15,56,0,233 + + + pxor xmm2,xmm5 + + + + movdqa xmm5,xmm4 + psllq xmm5,60 + movdqa xmm6,xmm5 + pslldq xmm6,8 + pxor xmm3,xmm6 + + + psrldq xmm5,8 + pxor xmm2,xmm5 + psrlq xmm4,4 + pxor xmm2,xmm4 + + sub rax,1 + jnz NEAR $L$oop_row_4 + + + + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,5 + pxor xmm2,xmm3 + pxor xmm3,xmm3 + mov rax,5 +$L$oop_row_5: + movdqa xmm4,XMMWORD[rdx] + lea rdx,[16+rdx] + + + movdqa xmm6,xmm2 +DB 102,15,58,15,243,1 + movdqa xmm3,xmm6 + psrldq xmm2,1 + + + + + movdqa xmm5,xmm4 +DB 102,15,56,0,224 +DB 102,15,56,0,233 + + + pxor xmm2,xmm5 + + + + movdqa xmm5,xmm4 + psllq xmm5,60 + movdqa xmm6,xmm5 + pslldq xmm6,8 + pxor xmm3,xmm6 + + + psrldq xmm5,8 + pxor xmm2,xmm5 + psrlq xmm4,4 + pxor xmm2,xmm4 + + sub rax,1 + jnz NEAR $L$oop_row_5 + + + + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,5 + pxor xmm2,xmm3 + pxor xmm3,xmm3 + mov rax,6 +$L$oop_row_6: + movdqa xmm4,XMMWORD[rdx] + lea rdx,[16+rdx] + + + movdqa xmm6,xmm2 +DB 102,15,58,15,243,1 + movdqa xmm3,xmm6 + psrldq xmm2,1 + + + + + movdqa xmm5,xmm4 +DB 102,15,56,0,224 +DB 102,15,56,0,233 + + + pxor xmm2,xmm5 + + + + movdqa xmm5,xmm4 + psllq xmm5,60 + movdqa xmm6,xmm5 + pslldq xmm6,8 + pxor xmm3,xmm6 + + + psrldq xmm5,8 + pxor xmm2,xmm5 + psrlq xmm4,4 + pxor xmm2,xmm4 + + sub rax,1 + jnz NEAR $L$oop_row_6 + + + + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,1 + pxor xmm2,xmm3 + psrlq xmm3,5 + pxor xmm2,xmm3 + pxor xmm3,xmm3 + movdqa xmm0,xmm2 + + + lea rdx,[((-256))+rdx] + + + lea r8,[16+r8] + sub r9,16 + jnz NEAR $L$oop_ghash + + +DB 102,65,15,56,0,194 + movdqu XMMWORD[rcx],xmm0 + + + pxor xmm0,xmm0 + pxor xmm1,xmm1 + pxor xmm2,xmm2 + pxor xmm3,xmm3 + pxor xmm4,xmm4 + pxor xmm5,xmm5 + pxor xmm6,xmm6 + movdqa xmm6,XMMWORD[rsp] + movdqa xmm10,XMMWORD[16+rsp] + movdqa xmm11,XMMWORD[32+rsp] + add rsp,56 + DB 0F3h,0C3h ;repret +$L$ghash_seh_end: + + + +ALIGN 16 + + +$L$reverse_bytes: +DB 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 + +$L$low4_mask: + DQ 0x0f0f0f0f0f0f0f0f,0x0f0f0f0f0f0f0f0f +section .pdata rdata align=4 +ALIGN 4 + DD $L$gmult_seh_begin wrt ..imagebase + DD $L$gmult_seh_end wrt ..imagebase + DD $L$gmult_seh_info wrt ..imagebase + + DD $L$ghash_seh_begin wrt ..imagebase + DD $L$ghash_seh_end wrt ..imagebase + DD $L$ghash_seh_info wrt ..imagebase + +section .xdata rdata align=8 +ALIGN 8 +$L$gmult_seh_info: +DB 1 +DB $L$gmult_seh_prolog_end-$L$gmult_seh_begin +DB 5 +DB 0 + +DB $L$gmult_seh_save_xmm10-$L$gmult_seh_begin +DB 168 + DW 1 + +DB $L$gmult_seh_save_xmm6-$L$gmult_seh_begin +DB 104 + DW 0 + +DB $L$gmult_seh_allocstack-$L$gmult_seh_begin +DB 66 + +ALIGN 8 +$L$ghash_seh_info: +DB 1 +DB $L$ghash_seh_prolog_end-$L$ghash_seh_begin +DB 7 +DB 0 + +DB $L$ghash_seh_save_xmm11-$L$ghash_seh_begin +DB 184 + DW 2 + +DB $L$ghash_seh_save_xmm10-$L$ghash_seh_begin +DB 168 + DW 1 + +DB $L$ghash_seh_save_xmm6-$L$ghash_seh_begin +DB 104 + DW 0 + +DB $L$ghash_seh_allocstack-$L$ghash_seh_begin +DB 98 diff --git a/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/ghash-x86_64.asm b/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/ghash-x86_64.asm index 31d601aa..fdf914f2 100644 --- a/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/ghash-x86_64.asm +++ b/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/ghash-x86_64.asm @@ -727,6 +727,7 @@ global gcm_init_clmul ALIGN 16 gcm_init_clmul: + $L$_init_clmul: $L$SEH_begin_gcm_init_clmul: @@ -886,10 +887,12 @@ DB 102,15,58,15,227,8 $L$SEH_end_gcm_init_clmul: DB 0F3h,0C3h ;repret + global gcm_gmult_clmul ALIGN 16 gcm_gmult_clmul: + $L$_gmult_clmul: movdqu xmm0,XMMWORD[rcx] movdqa xmm5,XMMWORD[$L$bswap_mask] @@ -937,10 +940,12 @@ DB 102,15,56,0,197 movdqu XMMWORD[rcx],xmm0 DB 0F3h,0C3h ;repret + global gcm_ghash_clmul ALIGN 32 gcm_ghash_clmul: + $L$_ghash_clmul: lea rax,[((-136))+rsp] $L$SEH_begin_gcm_ghash_clmul: @@ -1347,10 +1352,12 @@ DB 102,65,15,56,0,194 $L$SEH_end_gcm_ghash_clmul: DB 0F3h,0C3h ;repret + global gcm_init_avx ALIGN 32 gcm_init_avx: + $L$SEH_begin_gcm_init_avx: DB 0x48,0x83,0xec,0x18 @@ -1461,16 +1468,20 @@ $L$init_start_avx: $L$SEH_end_gcm_init_avx: DB 0F3h,0C3h ;repret + global gcm_gmult_avx ALIGN 32 gcm_gmult_avx: + jmp NEAR $L$_gmult_clmul + global gcm_ghash_avx ALIGN 32 gcm_ghash_avx: + lea rax,[((-136))+rsp] $L$SEH_begin_gcm_ghash_avx: @@ -1869,6 +1880,7 @@ $L$tail_no_xor_avx: $L$SEH_end_gcm_ghash_avx: DB 0F3h,0C3h ;repret + ALIGN 64 $L$bswap_mask: DB 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 diff --git a/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/rdrand-x86_64.asm b/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/rdrand-x86_64.asm index a34249b9..89b91de1 100644 --- a/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/rdrand-x86_64.asm +++ b/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/rdrand-x86_64.asm @@ -19,23 +19,12 @@ global CRYPTO_rdrand ALIGN 16 CRYPTO_rdrand: - mov QWORD[8+rsp],rdi ;WIN64 prologue - mov QWORD[16+rsp],rsi - mov rax,rsp -$L$SEH_begin_CRYPTO_rdrand: - mov rdi,rcx - - xor rax,rax - - -DB 0x48,0x0f,0xc7,0xf1 +DB 73,15,199,240 adc rax,rax - mov QWORD[rdi],rcx - mov rdi,QWORD[8+rsp] ;WIN64 epilogue - mov rsi,QWORD[16+rsp] + mov QWORD[rcx],r8 DB 0F3h,0C3h ;repret @@ -43,39 +32,27 @@ DB 0x48,0x0f,0xc7,0xf1 + global CRYPTO_rdrand_multiple8_buf ALIGN 16 CRYPTO_rdrand_multiple8_buf: - mov QWORD[8+rsp],rdi ;WIN64 prologue - mov QWORD[16+rsp],rsi - mov rax,rsp -$L$SEH_begin_CRYPTO_rdrand_multiple8_buf: - mov rdi,rcx - mov rsi,rdx - - - test rsi,rsi + test rdx,rdx jz NEAR $L$out - mov rdx,8 + mov r8,8 $L$loop: - - -DB 0x48,0x0f,0xc7,0xf1 +DB 73,15,199,241 jnc NEAR $L$err - mov QWORD[rdi],rcx - add rdi,rdx - sub rsi,rdx + mov QWORD[rcx],r9 + add rcx,r8 + sub rdx,r8 jnz NEAR $L$loop $L$out: mov rax,1 - mov rdi,QWORD[8+rsp] ;WIN64 epilogue - mov rsi,QWORD[16+rsp] DB 0F3h,0C3h ;repret $L$err: xor rax,rax - mov rdi,QWORD[8+rsp] ;WIN64 epilogue - mov rsi,QWORD[16+rsp] DB 0F3h,0C3h ;repret + diff --git a/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/rsaz-avx2.asm b/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/rsaz-avx2.asm index 5165c583..74e2705c 100644 --- a/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/rsaz-avx2.asm +++ b/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/rsaz-avx2.asm @@ -1297,6 +1297,7 @@ global rsaz_1024_red2norm_avx2 ALIGN 32 rsaz_1024_red2norm_avx2: + sub rdx,-128 xor rax,rax mov r8,QWORD[((-128))+rdx] @@ -1490,10 +1491,12 @@ rsaz_1024_red2norm_avx2: DB 0F3h,0C3h ;repret + global rsaz_1024_norm2red_avx2 ALIGN 32 rsaz_1024_norm2red_avx2: + sub rcx,-128 mov r8,QWORD[rdx] mov eax,0x1fffffff @@ -1647,10 +1650,12 @@ rsaz_1024_norm2red_avx2: mov QWORD[184+rcx],r8 DB 0F3h,0C3h ;repret + global rsaz_1024_scatter5_avx2 ALIGN 32 rsaz_1024_scatter5_avx2: + vzeroupper vmovdqu ymm5,YMMWORD[$L$scatter_permd] shl r8d,4 @@ -1672,6 +1677,7 @@ $L$oop_scatter_1024: DB 0F3h,0C3h ;repret + global rsaz_1024_gather5_avx2 ALIGN 32 @@ -1817,23 +1823,6 @@ $L$oop_gather_1024: $L$SEH_end_rsaz_1024_gather5: -EXTERN OPENSSL_ia32cap_P -global rsaz_avx2_eligible - -ALIGN 32 -rsaz_avx2_eligible: - lea rax,[OPENSSL_ia32cap_P] - mov eax,DWORD[8+rax] - mov ecx,524544 - mov edx,0 - and ecx,eax - cmp ecx,524544 - cmove eax,edx - and eax,32 - shr eax,5 - DB 0F3h,0C3h ;repret - - ALIGN 64 $L$and_mask: DQ 0x1fffffff,0x1fffffff,0x1fffffff,0x1fffffff diff --git a/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/vpaes-x86_64.asm b/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/vpaes-x86_64.asm index 91e10aa7..10092c8a 100644 --- a/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/vpaes-x86_64.asm +++ b/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/vpaes-x86_64.asm @@ -120,6 +120,181 @@ DB 102,15,56,0,193 + + + + + + + + + + + + + + + + + + + + + + + + +ALIGN 16 +_vpaes_encrypt_core_2x: + + mov r9,rdx + mov r11,16 + mov eax,DWORD[240+rdx] + movdqa xmm1,xmm9 + movdqa xmm7,xmm9 + movdqa xmm2,XMMWORD[$L$k_ipt] + movdqa xmm8,xmm2 + pandn xmm1,xmm0 + pandn xmm7,xmm6 + movdqu xmm5,XMMWORD[r9] + + psrld xmm1,4 + psrld xmm7,4 + pand xmm0,xmm9 + pand xmm6,xmm9 +DB 102,15,56,0,208 +DB 102,68,15,56,0,198 + movdqa xmm0,XMMWORD[(($L$k_ipt+16))] + movdqa xmm6,xmm0 +DB 102,15,56,0,193 +DB 102,15,56,0,247 + pxor xmm2,xmm5 + pxor xmm8,xmm5 + add r9,16 + pxor xmm0,xmm2 + pxor xmm6,xmm8 + lea r10,[$L$k_mc_backward] + jmp NEAR $L$enc2x_entry + +ALIGN 16 +$L$enc2x_loop: + + movdqa xmm4,XMMWORD[$L$k_sb1] + movdqa xmm0,XMMWORD[(($L$k_sb1+16))] + movdqa xmm12,xmm4 + movdqa xmm6,xmm0 +DB 102,15,56,0,226 +DB 102,69,15,56,0,224 +DB 102,15,56,0,195 +DB 102,65,15,56,0,243 + pxor xmm4,xmm5 + pxor xmm12,xmm5 + movdqa xmm5,XMMWORD[$L$k_sb2] + movdqa xmm13,xmm5 + pxor xmm0,xmm4 + pxor xmm6,xmm12 + movdqa xmm1,XMMWORD[((-64))+r10*1+r11] + +DB 102,15,56,0,234 +DB 102,69,15,56,0,232 + movdqa xmm4,XMMWORD[r10*1+r11] + + movdqa xmm2,XMMWORD[(($L$k_sb2+16))] + movdqa xmm8,xmm2 +DB 102,15,56,0,211 +DB 102,69,15,56,0,195 + movdqa xmm3,xmm0 + movdqa xmm11,xmm6 + pxor xmm2,xmm5 + pxor xmm8,xmm13 +DB 102,15,56,0,193 +DB 102,15,56,0,241 + add r9,16 + pxor xmm0,xmm2 + pxor xmm6,xmm8 +DB 102,15,56,0,220 +DB 102,68,15,56,0,220 + add r11,16 + pxor xmm3,xmm0 + pxor xmm11,xmm6 +DB 102,15,56,0,193 +DB 102,15,56,0,241 + and r11,0x30 + sub rax,1 + pxor xmm0,xmm3 + pxor xmm6,xmm11 + +$L$enc2x_entry: + + movdqa xmm1,xmm9 + movdqa xmm7,xmm9 + movdqa xmm5,XMMWORD[(($L$k_inv+16))] + movdqa xmm13,xmm5 + pandn xmm1,xmm0 + pandn xmm7,xmm6 + psrld xmm1,4 + psrld xmm7,4 + pand xmm0,xmm9 + pand xmm6,xmm9 +DB 102,15,56,0,232 +DB 102,68,15,56,0,238 + movdqa xmm3,xmm10 + movdqa xmm11,xmm10 + pxor xmm0,xmm1 + pxor xmm6,xmm7 +DB 102,15,56,0,217 +DB 102,68,15,56,0,223 + movdqa xmm4,xmm10 + movdqa xmm12,xmm10 + pxor xmm3,xmm5 + pxor xmm11,xmm13 +DB 102,15,56,0,224 +DB 102,68,15,56,0,230 + movdqa xmm2,xmm10 + movdqa xmm8,xmm10 + pxor xmm4,xmm5 + pxor xmm12,xmm13 +DB 102,15,56,0,211 +DB 102,69,15,56,0,195 + movdqa xmm3,xmm10 + movdqa xmm11,xmm10 + pxor xmm2,xmm0 + pxor xmm8,xmm6 +DB 102,15,56,0,220 +DB 102,69,15,56,0,220 + movdqu xmm5,XMMWORD[r9] + + pxor xmm3,xmm1 + pxor xmm11,xmm7 + jnz NEAR $L$enc2x_loop + + + movdqa xmm4,XMMWORD[((-96))+r10] + movdqa xmm0,XMMWORD[((-80))+r10] + movdqa xmm12,xmm4 + movdqa xmm6,xmm0 +DB 102,15,56,0,226 +DB 102,69,15,56,0,224 + pxor xmm4,xmm5 + pxor xmm12,xmm5 +DB 102,15,56,0,195 +DB 102,65,15,56,0,243 + movdqa xmm1,XMMWORD[64+r10*1+r11] + + pxor xmm0,xmm4 + pxor xmm6,xmm12 +DB 102,15,56,0,193 +DB 102,15,56,0,241 + DB 0F3h,0C3h ;repret + + + + + + + + + ALIGN 16 _vpaes_decrypt_core: @@ -644,6 +819,13 @@ $L$SEH_begin_vpaes_set_encrypt_key: +%ifndef NDEBUG +%ifndef BORINGSSL_FIPS +EXTERN BORINGSSL_function_hit + mov BYTE[((BORINGSSL_function_hit+5))],1 +%endif +%endif + lea rsp,[((-184))+rsp] movaps XMMWORD[16+rsp],xmm6 movaps XMMWORD[32+rsp],xmm7 @@ -755,6 +937,12 @@ $L$SEH_begin_vpaes_encrypt: +%ifndef NDEBUG +%ifndef BORINGSSL_FIPS +EXTERN BORINGSSL_function_hit + mov BYTE[((BORINGSSL_function_hit+4))],1 +%endif +%endif lea rsp,[((-184))+rsp] movaps XMMWORD[16+rsp],xmm6 movaps XMMWORD[32+rsp],xmm7 @@ -916,6 +1104,105 @@ $L$cbc_abort: DB 0F3h,0C3h ;repret $L$SEH_end_vpaes_cbc_encrypt: +global vpaes_ctr32_encrypt_blocks + +ALIGN 16 +vpaes_ctr32_encrypt_blocks: + mov QWORD[8+rsp],rdi ;WIN64 prologue + mov QWORD[16+rsp],rsi + mov rax,rsp +$L$SEH_begin_vpaes_ctr32_encrypt_blocks: + mov rdi,rcx + mov rsi,rdx + mov rdx,r8 + mov rcx,r9 + mov r8,QWORD[40+rsp] + + + + + xchg rdx,rcx + test rcx,rcx + jz NEAR $L$ctr32_abort + lea rsp,[((-184))+rsp] + movaps XMMWORD[16+rsp],xmm6 + movaps XMMWORD[32+rsp],xmm7 + movaps XMMWORD[48+rsp],xmm8 + movaps XMMWORD[64+rsp],xmm9 + movaps XMMWORD[80+rsp],xmm10 + movaps XMMWORD[96+rsp],xmm11 + movaps XMMWORD[112+rsp],xmm12 + movaps XMMWORD[128+rsp],xmm13 + movaps XMMWORD[144+rsp],xmm14 + movaps XMMWORD[160+rsp],xmm15 +$L$ctr32_body: + movdqu xmm0,XMMWORD[r8] + movdqa xmm8,XMMWORD[$L$ctr_add_one] + sub rsi,rdi + call _vpaes_preheat + movdqa xmm6,xmm0 + pshufb xmm6,XMMWORD[$L$rev_ctr] + + test rcx,1 + jz NEAR $L$ctr32_prep_loop + + + + movdqu xmm7,XMMWORD[rdi] + call _vpaes_encrypt_core + pxor xmm0,xmm7 + paddd xmm6,xmm8 + movdqu XMMWORD[rdi*1+rsi],xmm0 + sub rcx,1 + lea rdi,[16+rdi] + jz NEAR $L$ctr32_done + +$L$ctr32_prep_loop: + + + movdqa xmm14,xmm6 + movdqa xmm15,xmm6 + paddd xmm15,xmm8 + +$L$ctr32_loop: + movdqa xmm1,XMMWORD[$L$rev_ctr] + movdqa xmm0,xmm14 + movdqa xmm6,xmm15 +DB 102,15,56,0,193 +DB 102,15,56,0,241 + call _vpaes_encrypt_core_2x + movdqu xmm1,XMMWORD[rdi] + movdqu xmm2,XMMWORD[16+rdi] + movdqa xmm3,XMMWORD[$L$ctr_add_two] + pxor xmm0,xmm1 + pxor xmm6,xmm2 + paddd xmm14,xmm3 + paddd xmm15,xmm3 + movdqu XMMWORD[rdi*1+rsi],xmm0 + movdqu XMMWORD[16+rdi*1+rsi],xmm6 + sub rcx,2 + lea rdi,[32+rdi] + jnz NEAR $L$ctr32_loop + +$L$ctr32_done: + movaps xmm6,XMMWORD[16+rsp] + movaps xmm7,XMMWORD[32+rsp] + movaps xmm8,XMMWORD[48+rsp] + movaps xmm9,XMMWORD[64+rsp] + movaps xmm10,XMMWORD[80+rsp] + movaps xmm11,XMMWORD[96+rsp] + movaps xmm12,XMMWORD[112+rsp] + movaps xmm13,XMMWORD[128+rsp] + movaps xmm14,XMMWORD[144+rsp] + movaps xmm15,XMMWORD[160+rsp] + lea rsp,[184+rsp] +$L$ctr32_epilogue: +$L$ctr32_abort: + mov rdi,QWORD[8+rsp] ;WIN64 epilogue + mov rsi,QWORD[16+rsp] + DB 0F3h,0C3h ;repret + +$L$SEH_end_vpaes_ctr32_encrypt_blocks: @@ -1038,6 +1325,17 @@ $L$k_dsbe: $L$k_dsbo: DQ 0x1387EA537EF94000,0xC7AA6DB9D4943E2D DQ 0x12D7560F93441D00,0xCA4B8159D8C58E9C + + +$L$rev_ctr: + DQ 0x0706050403020100,0x0c0d0e0f0b0a0908 + + +$L$ctr_add_one: + DQ 0x0000000000000000,0x0000000100000000 +$L$ctr_add_two: + DQ 0x0000000000000000,0x0000000200000000 + DB 86,101,99,116,111,114,32,80,101,114,109,117,116,97,116,105 DB 111,110,32,65,69,83,32,102,111,114,32,120,56,54,95,54 DB 52,47,83,83,83,69,51,44,32,77,105,107,101,32,72,97 @@ -1146,6 +1444,10 @@ ALIGN 4 DD $L$SEH_end_vpaes_cbc_encrypt wrt ..imagebase DD $L$SEH_info_vpaes_cbc_encrypt wrt ..imagebase + DD $L$SEH_begin_vpaes_ctr32_encrypt_blocks wrt ..imagebase + DD $L$SEH_end_vpaes_ctr32_encrypt_blocks wrt ..imagebase + DD $L$SEH_info_vpaes_ctr32_encrypt_blocks wrt ..imagebase + section .xdata rdata align=8 ALIGN 8 $L$SEH_info_vpaes_set_encrypt_key: @@ -1168,3 +1470,7 @@ $L$SEH_info_vpaes_cbc_encrypt: DB 9,0,0,0 DD se_handler wrt ..imagebase DD $L$cbc_body wrt ..imagebase,$L$cbc_epilogue wrt ..imagebase +$L$SEH_info_vpaes_ctr32_encrypt_blocks: +DB 9,0,0,0 + DD se_handler wrt ..imagebase + DD $L$ctr32_body wrt ..imagebase,$L$ctr32_epilogue wrt ..imagebase diff --git a/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/x86_64-mont5.asm b/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/x86_64-mont5.asm index 298fd057..7a1d5dbd 100644 --- a/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/x86_64-mont5.asm +++ b/third_party/boringssl/kit/win-x86_64/crypto/fipsmodule/x86_64-mont5.asm @@ -591,6 +591,7 @@ $L$SEH_end_bn_mul4x_mont_gather5: ALIGN 32 mul4x_internal: + shl r9,5 movd xmm5,DWORD[56+rax] lea rax,[$L$inc] @@ -1113,6 +1114,7 @@ $L$inner4x: mov r15,QWORD[24+rbp] jmp NEAR $L$sqr4x_sub_entry + global bn_power5 ALIGN 32 @@ -1340,6 +1342,7 @@ __bn_sqr8x_internal: + lea rbp,[32+r10] @@ -2045,8 +2048,10 @@ DB 102,73,15,126,217 DB 0F3h,0C3h ;repret + ALIGN 32 __bn_post4x_internal: + mov r12,QWORD[rbp] lea rbx,[r9*1+rdi] mov rcx,r9 @@ -2098,10 +2103,12 @@ $L$sqr4x_sub_entry: neg r9 DB 0F3h,0C3h ;repret + global bn_from_montgomery ALIGN 32 bn_from_montgomery: + test DWORD[48+rsp],7 jz NEAR bn_from_mont8x xor eax,eax @@ -2109,6 +2116,7 @@ bn_from_montgomery: + ALIGN 32 bn_from_mont8x: mov QWORD[8+rsp],rdi ;WIN64 prologue @@ -2418,6 +2426,7 @@ $L$SEH_end_bn_mulx4x_mont_gather5: ALIGN 32 mulx4x_internal: + mov QWORD[8+rsp],r9 mov r10,r9 neg r9 @@ -2838,6 +2847,7 @@ $L$mulx4x_inner: jmp NEAR $L$sqrx4x_sub_entry + ALIGN 32 bn_powerx5: mov QWORD[8+rsp],rdi ;WIN64 prologue @@ -3607,7 +3617,9 @@ DB 102,72,15,126,213 ALIGN 32 + __bn_postx4x_internal: + mov r12,QWORD[rbp] mov r10,rcx mov r9,rcx @@ -3656,10 +3668,12 @@ $L$sqrx4x_sub_entry: DB 0F3h,0C3h ;repret + global bn_scatter5 ALIGN 16 bn_scatter5: + cmp edx,0 jz NEAR $L$scatter_epilogue lea r8,[r9*8+r8] @@ -3674,13 +3688,16 @@ $L$scatter_epilogue: DB 0F3h,0C3h ;repret + global bn_gather5 ALIGN 32 bn_gather5: + $L$SEH_begin_bn_gather5: DB 0x4c,0x8d,0x14,0x24 + DB 0x48,0x81,0xec,0x08,0x01,0x00,0x00 lea rax,[$L$inc] and rsp,-16 @@ -3834,9 +3851,11 @@ $L$gather: jnz NEAR $L$gather lea rsp,[r10] + DB 0F3h,0C3h ;repret $L$SEH_end_bn_gather5: + ALIGN 64 $L$inc: DD 0,0,1,1 diff --git a/third_party/boringssl/kit/win-x86_64/crypto/test/trampoline-x86_64.asm b/third_party/boringssl/kit/win-x86_64/crypto/test/trampoline-x86_64.asm index ba08a257..99006695 100644 --- a/third_party/boringssl/kit/win-x86_64/crypto/test/trampoline-x86_64.asm +++ b/third_party/boringssl/kit/win-x86_64/crypto/test/trampoline-x86_64.asm @@ -23,7 +23,7 @@ section .text code align=64 global abi_test_trampoline ALIGN 16 abi_test_trampoline: -$L$abi_test_trampoline_begin: +$L$abi_test_trampoline_seh_begin: @@ -36,62 +36,62 @@ $L$abi_test_trampoline_begin: sub rsp,344 -$L$abi_test_trampoline_prolog_alloc: +$L$abi_test_trampoline_seh_prolog_alloc: mov QWORD[112+rsp],rbx -$L$abi_test_trampoline_prolog_rbx: +$L$abi_test_trampoline_seh_prolog_rbx: mov QWORD[120+rsp],rbp -$L$abi_test_trampoline_prolog_rbp: +$L$abi_test_trampoline_seh_prolog_rbp: mov QWORD[128+rsp],rdi -$L$abi_test_trampoline_prolog_rdi: +$L$abi_test_trampoline_seh_prolog_rdi: mov QWORD[136+rsp],rsi -$L$abi_test_trampoline_prolog_rsi: +$L$abi_test_trampoline_seh_prolog_rsi: mov QWORD[144+rsp],r12 -$L$abi_test_trampoline_prolog_r12: +$L$abi_test_trampoline_seh_prolog_r12: mov QWORD[152+rsp],r13 -$L$abi_test_trampoline_prolog_r13: +$L$abi_test_trampoline_seh_prolog_r13: mov QWORD[160+rsp],r14 -$L$abi_test_trampoline_prolog_r14: +$L$abi_test_trampoline_seh_prolog_r14: mov QWORD[168+rsp],r15 -$L$abi_test_trampoline_prolog_r15: +$L$abi_test_trampoline_seh_prolog_r15: movdqa XMMWORD[176+rsp],xmm6 -$L$abi_test_trampoline_prolog_xmm6: +$L$abi_test_trampoline_seh_prolog_xmm6: movdqa XMMWORD[192+rsp],xmm7 -$L$abi_test_trampoline_prolog_xmm7: +$L$abi_test_trampoline_seh_prolog_xmm7: movdqa XMMWORD[208+rsp],xmm8 -$L$abi_test_trampoline_prolog_xmm8: +$L$abi_test_trampoline_seh_prolog_xmm8: movdqa XMMWORD[224+rsp],xmm9 -$L$abi_test_trampoline_prolog_xmm9: +$L$abi_test_trampoline_seh_prolog_xmm9: movdqa XMMWORD[240+rsp],xmm10 -$L$abi_test_trampoline_prolog_xmm10: +$L$abi_test_trampoline_seh_prolog_xmm10: movdqa XMMWORD[256+rsp],xmm11 -$L$abi_test_trampoline_prolog_xmm11: +$L$abi_test_trampoline_seh_prolog_xmm11: movdqa XMMWORD[272+rsp],xmm12 -$L$abi_test_trampoline_prolog_xmm12: +$L$abi_test_trampoline_seh_prolog_xmm12: movdqa XMMWORD[288+rsp],xmm13 -$L$abi_test_trampoline_prolog_xmm13: +$L$abi_test_trampoline_seh_prolog_xmm13: movdqa XMMWORD[304+rsp],xmm14 -$L$abi_test_trampoline_prolog_xmm14: +$L$abi_test_trampoline_seh_prolog_xmm14: movdqa XMMWORD[320+rsp],xmm15 -$L$abi_test_trampoline_prolog_xmm15: -$L$abi_test_trampoline_prolog_end: +$L$abi_test_trampoline_seh_prolog_xmm15: +$L$abi_test_trampoline_seh_prolog_end: mov rbx,QWORD[rdx] mov rbp,QWORD[8+rdx] mov rdi,QWORD[16+rdx] @@ -252,7 +252,7 @@ $L$call_done: DB 0F3h,0C3h ;repret -$L$abi_test_trampoline_end: +$L$abi_test_trampoline_seh_end: global abi_test_clobber_rax @@ -479,11 +479,18 @@ global abi_test_bad_unwind_wrong_register ALIGN 16 abi_test_bad_unwind_wrong_register: +$L$abi_test_bad_unwind_wrong_register_seh_begin: push r12 +$L$abi_test_bad_unwind_wrong_register_seh_push_r13: + + + + nop pop r12 DB 0F3h,0C3h ;repret +$L$abi_test_bad_unwind_wrong_register_seh_end: @@ -495,20 +502,24 @@ global abi_test_bad_unwind_temporary ALIGN 16 abi_test_bad_unwind_temporary: +$L$abi_test_bad_unwind_temporary_seh_begin: push r12 +$L$abi_test_bad_unwind_temporary_seh_push_r12: + + mov rax,r12 + inc rax + mov QWORD[rsp],rax - inc r12 - mov QWORD[rsp],r12 - dec r12 mov QWORD[rsp],r12 pop r12 DB 0F3h,0C3h ;repret +$L$abi_test_bad_unwind_temporary_seh_end: @@ -521,7 +532,7 @@ abi_test_get_and_clear_direction_flag: pushfq pop rax and rax,0x400 - shl rax,10 + shr rax,10 cld DB 0F3h,0C3h ;repret @@ -534,76 +545,138 @@ abi_test_set_direction_flag: std DB 0F3h,0C3h ;repret + + + + + +global abi_test_bad_unwind_epilog +ALIGN 16 +abi_test_bad_unwind_epilog: +$L$abi_test_bad_unwind_epilog_seh_begin: + push r12 +$L$abi_test_bad_unwind_epilog_seh_push_r12: + + nop + + + pop r12 + nop + DB 0F3h,0C3h ;repret +$L$abi_test_bad_unwind_epilog_seh_end: + section .pdata rdata align=4 ALIGN 4 - DD $L$abi_test_trampoline_begin wrt ..imagebase - DD $L$abi_test_trampoline_end wrt ..imagebase - DD $L$abi_test_trampoline_info wrt ..imagebase + DD $L$abi_test_trampoline_seh_begin wrt ..imagebase + DD $L$abi_test_trampoline_seh_end wrt ..imagebase + DD $L$abi_test_trampoline_seh_info wrt ..imagebase + + DD $L$abi_test_bad_unwind_wrong_register_seh_begin wrt ..imagebase + DD $L$abi_test_bad_unwind_wrong_register_seh_end wrt ..imagebase + DD $L$abi_test_bad_unwind_wrong_register_seh_info wrt ..imagebase + + DD $L$abi_test_bad_unwind_temporary_seh_begin wrt ..imagebase + DD $L$abi_test_bad_unwind_temporary_seh_end wrt ..imagebase + DD $L$abi_test_bad_unwind_temporary_seh_info wrt ..imagebase + + DD $L$abi_test_bad_unwind_epilog_seh_begin wrt ..imagebase + DD $L$abi_test_bad_unwind_epilog_seh_end wrt ..imagebase + DD $L$abi_test_bad_unwind_epilog_seh_info wrt ..imagebase section .xdata rdata align=8 ALIGN 8 -$L$abi_test_trampoline_info: +$L$abi_test_trampoline_seh_info: DB 1 -DB $L$abi_test_trampoline_prolog_end-$L$abi_test_trampoline_begin +DB $L$abi_test_trampoline_seh_prolog_end-$L$abi_test_trampoline_seh_begin DB 38 DB 0 -DB $L$abi_test_trampoline_prolog_alloc-$L$abi_test_trampoline_begin -DB 1 - DW 43 -DB $L$abi_test_trampoline_prolog_rbx-$L$abi_test_trampoline_begin -DB 52 - DW 14 -DB $L$abi_test_trampoline_prolog_rbp-$L$abi_test_trampoline_begin -DB 84 - DW 15 -DB $L$abi_test_trampoline_prolog_rdi-$L$abi_test_trampoline_begin -DB 116 - DW 16 -DB $L$abi_test_trampoline_prolog_rsi-$L$abi_test_trampoline_begin -DB 100 - DW 17 -DB $L$abi_test_trampoline_prolog_r12-$L$abi_test_trampoline_begin -DB 196 - DW 18 -DB $L$abi_test_trampoline_prolog_r13-$L$abi_test_trampoline_begin -DB 212 - DW 19 -DB $L$abi_test_trampoline_prolog_r14-$L$abi_test_trampoline_begin -DB 228 - DW 20 -DB $L$abi_test_trampoline_prolog_r15-$L$abi_test_trampoline_begin -DB 244 - DW 21 -DB $L$abi_test_trampoline_prolog_xmm6-$L$abi_test_trampoline_begin -DB 104 - DW 11 -DB $L$abi_test_trampoline_prolog_xmm7-$L$abi_test_trampoline_begin -DB 120 - DW 12 -DB $L$abi_test_trampoline_prolog_xmm8-$L$abi_test_trampoline_begin -DB 136 - DW 13 -DB $L$abi_test_trampoline_prolog_xmm9-$L$abi_test_trampoline_begin -DB 152 - DW 14 -DB $L$abi_test_trampoline_prolog_xmm10-$L$abi_test_trampoline_begin -DB 168 - DW 15 -DB $L$abi_test_trampoline_prolog_xmm11-$L$abi_test_trampoline_begin -DB 184 - DW 16 -DB $L$abi_test_trampoline_prolog_xmm12-$L$abi_test_trampoline_begin -DB 200 - DW 17 -DB $L$abi_test_trampoline_prolog_xmm13-$L$abi_test_trampoline_begin -DB 216 - DW 18 -DB $L$abi_test_trampoline_prolog_xmm14-$L$abi_test_trampoline_begin -DB 232 - DW 19 -DB $L$abi_test_trampoline_prolog_xmm15-$L$abi_test_trampoline_begin +DB $L$abi_test_trampoline_seh_prolog_xmm15-$L$abi_test_trampoline_seh_begin DB 248 DW 20 +DB $L$abi_test_trampoline_seh_prolog_xmm14-$L$abi_test_trampoline_seh_begin +DB 232 + DW 19 +DB $L$abi_test_trampoline_seh_prolog_xmm13-$L$abi_test_trampoline_seh_begin +DB 216 + DW 18 +DB $L$abi_test_trampoline_seh_prolog_xmm12-$L$abi_test_trampoline_seh_begin +DB 200 + DW 17 +DB $L$abi_test_trampoline_seh_prolog_xmm11-$L$abi_test_trampoline_seh_begin +DB 184 + DW 16 +DB $L$abi_test_trampoline_seh_prolog_xmm10-$L$abi_test_trampoline_seh_begin +DB 168 + DW 15 +DB $L$abi_test_trampoline_seh_prolog_xmm9-$L$abi_test_trampoline_seh_begin +DB 152 + DW 14 +DB $L$abi_test_trampoline_seh_prolog_xmm8-$L$abi_test_trampoline_seh_begin +DB 136 + DW 13 +DB $L$abi_test_trampoline_seh_prolog_xmm7-$L$abi_test_trampoline_seh_begin +DB 120 + DW 12 +DB $L$abi_test_trampoline_seh_prolog_xmm6-$L$abi_test_trampoline_seh_begin +DB 104 + DW 11 +DB $L$abi_test_trampoline_seh_prolog_r15-$L$abi_test_trampoline_seh_begin +DB 244 + DW 21 +DB $L$abi_test_trampoline_seh_prolog_r14-$L$abi_test_trampoline_seh_begin +DB 228 + DW 20 +DB $L$abi_test_trampoline_seh_prolog_r13-$L$abi_test_trampoline_seh_begin +DB 212 + DW 19 +DB $L$abi_test_trampoline_seh_prolog_r12-$L$abi_test_trampoline_seh_begin +DB 196 + DW 18 +DB $L$abi_test_trampoline_seh_prolog_rsi-$L$abi_test_trampoline_seh_begin +DB 100 + DW 17 +DB $L$abi_test_trampoline_seh_prolog_rdi-$L$abi_test_trampoline_seh_begin +DB 116 + DW 16 +DB $L$abi_test_trampoline_seh_prolog_rbp-$L$abi_test_trampoline_seh_begin +DB 84 + DW 15 +DB $L$abi_test_trampoline_seh_prolog_rbx-$L$abi_test_trampoline_seh_begin +DB 52 + DW 14 +DB $L$abi_test_trampoline_seh_prolog_alloc-$L$abi_test_trampoline_seh_begin +DB 1 + DW 43 + +ALIGN 8 +$L$abi_test_bad_unwind_wrong_register_seh_info: +DB 1 +DB $L$abi_test_bad_unwind_wrong_register_seh_push_r13-$L$abi_test_bad_unwind_wrong_register_seh_begin +DB 1 +DB 0 + +DB $L$abi_test_bad_unwind_wrong_register_seh_push_r13-$L$abi_test_bad_unwind_wrong_register_seh_begin +DB 208 + +ALIGN 8 +$L$abi_test_bad_unwind_temporary_seh_info: +DB 1 +DB $L$abi_test_bad_unwind_temporary_seh_push_r12-$L$abi_test_bad_unwind_temporary_seh_begin +DB 1 +DB 0 + +DB $L$abi_test_bad_unwind_temporary_seh_push_r12-$L$abi_test_bad_unwind_temporary_seh_begin +DB 192 + +ALIGN 8 +$L$abi_test_bad_unwind_epilog_seh_info: +DB 1 +DB $L$abi_test_bad_unwind_epilog_seh_push_r12-$L$abi_test_bad_unwind_epilog_seh_begin +DB 1 +DB 0 + +DB $L$abi_test_bad_unwind_epilog_seh_push_r12-$L$abi_test_bad_unwind_epilog_seh_begin +DB 192 diff --git a/third_party/boringssl/kit/win-x86_64/crypto/third_party/sike/asm/fp-x86_64.asm b/third_party/boringssl/kit/win-x86_64/crypto/third_party/sike/asm/fp-x86_64.asm new file mode 100644 index 00000000..d2d1349f --- /dev/null +++ b/third_party/boringssl/kit/win-x86_64/crypto/third_party/sike/asm/fp-x86_64.asm @@ -0,0 +1,2167 @@ +; This file is generated from a similarly-named Perl script in the BoringSSL +; source tree. Do not edit by hand. + +default rel +%define XMMWORD +%define YMMWORD +%define ZMMWORD + +%ifdef BORINGSSL_PREFIX +%include "boringssl_prefix_symbols_nasm.inc" +%endif +section .text code align=64 + + + +$L$p503x2: + DQ 0xFFFFFFFFFFFFFFFE + DQ 0xFFFFFFFFFFFFFFFF + DQ 0x57FFFFFFFFFFFFFF + DQ 0x2610B7B44423CF41 + DQ 0x3737ED90F6FCFB5E + DQ 0xC08B8D7BB4EF49A0 + DQ 0x0080CDEA83023C3C + + +$L$p503p1: + DQ 0xAC00000000000000 + DQ 0x13085BDA2211E7A0 + DQ 0x1B9BF6C87B7E7DAF + DQ 0x6045C6BDDA77A4D0 + DQ 0x004066F541811E1E + +$L$p503p1_nz: + DQ 0xAC00000000000000 + DQ 0x13085BDA2211E7A0 + DQ 0x1B9BF6C87B7E7DAF + DQ 0x6045C6BDDA77A4D0 + DQ 0x004066F541811E1E + +EXTERN OPENSSL_ia32cap_P + + +global sike_fpadd + +sike_fpadd: + mov QWORD[8+rsp],rdi ;WIN64 prologue + mov QWORD[16+rsp],rsi + mov rax,rsp +$L$SEH_begin_sike_fpadd: + mov rdi,rcx + mov rsi,rdx + mov rdx,r8 + + + + push r12 + + + push r13 + + + push r14 + + + push r15 + + + + xor rax,rax + + mov r8,QWORD[rdi] + mov r9,QWORD[8+rdi] + mov r10,QWORD[16+rdi] + mov r11,QWORD[24+rdi] + mov r12,QWORD[32+rdi] + mov r13,QWORD[40+rdi] + mov r14,QWORD[48+rdi] + mov r15,QWORD[56+rdi] + + add r8,QWORD[rsi] + adc r9,QWORD[8+rsi] + adc r10,QWORD[16+rsi] + adc r11,QWORD[24+rsi] + adc r12,QWORD[32+rsi] + adc r13,QWORD[40+rsi] + adc r14,QWORD[48+rsi] + adc r15,QWORD[56+rsi] + + mov rcx,QWORD[$L$p503x2]; + sub r8,rcx + mov rcx,QWORD[((8+$L$p503x2))]; + sbb r9,rcx + sbb r10,rcx + mov rcx,QWORD[((16+$L$p503x2))]; + sbb r11,rcx + mov rcx,QWORD[((24+$L$p503x2))]; + sbb r12,rcx + mov rcx,QWORD[((32+$L$p503x2))]; + sbb r13,rcx + mov rcx,QWORD[((40+$L$p503x2))]; + sbb r14,rcx + mov rcx,QWORD[((48+$L$p503x2))]; + sbb r15,rcx + sbb rax,0 + + mov rdi,QWORD[$L$p503x2] + and rdi,rax + mov rsi,QWORD[((8+$L$p503x2))] + and rsi,rax + mov rcx,QWORD[((16+$L$p503x2))] + and rcx,rax + + add r8,rdi + mov QWORD[rdx],r8 + adc r9,rsi + mov QWORD[8+rdx],r9 + adc r10,rsi + mov QWORD[16+rdx],r10 + adc r11,rcx + mov QWORD[24+rdx],r11 + + setc cl + + mov r8,QWORD[((24+$L$p503x2))] + and r8,rax + mov r9,QWORD[((32+$L$p503x2))] + and r9,rax + mov r10,QWORD[((40+$L$p503x2))] + and r10,rax + mov r11,QWORD[((48+$L$p503x2))] + and r11,rax + + bt rcx,0 + + adc r12,r8 + mov QWORD[32+rdx],r12 + adc r13,r9 + mov QWORD[40+rdx],r13 + adc r14,r10 + mov QWORD[48+rdx],r14 + adc r15,r11 + mov QWORD[56+rdx],r15 + + pop r15 + + pop r14 + + pop r13 + + pop r12 + + mov rdi,QWORD[8+rsp] ;WIN64 epilogue + mov rsi,QWORD[16+rsp] + DB 0F3h,0C3h ;repret + +global sike_cswap_asm + +sike_cswap_asm: + mov QWORD[8+rsp],rdi ;WIN64 prologue + mov QWORD[16+rsp],rsi + mov rax,rsp +$L$SEH_begin_sike_cswap_asm: + mov rdi,rcx + mov rsi,rdx + mov rdx,r8 + + + + + movq xmm3,rdx + + + + + + pshufd xmm3,xmm3,68 + + movdqu xmm0,XMMWORD[rdi] + movdqu xmm1,XMMWORD[rsi] + movdqa xmm2,xmm1 + pxor xmm2,xmm0 + pand xmm2,xmm3 + pxor xmm0,xmm2 + pxor xmm1,xmm2 + movdqu XMMWORD[rdi],xmm0 + movdqu XMMWORD[rsi],xmm1 + + movdqu xmm0,XMMWORD[16+rdi] + movdqu xmm1,XMMWORD[16+rsi] + movdqa xmm2,xmm1 + pxor xmm2,xmm0 + pand xmm2,xmm3 + pxor xmm0,xmm2 + pxor xmm1,xmm2 + movdqu XMMWORD[16+rdi],xmm0 + movdqu XMMWORD[16+rsi],xmm1 + + movdqu xmm0,XMMWORD[32+rdi] + movdqu xmm1,XMMWORD[32+rsi] + movdqa xmm2,xmm1 + pxor xmm2,xmm0 + pand xmm2,xmm3 + pxor xmm0,xmm2 + pxor xmm1,xmm2 + movdqu XMMWORD[32+rdi],xmm0 + movdqu XMMWORD[32+rsi],xmm1 + + movdqu xmm0,XMMWORD[48+rdi] + movdqu xmm1,XMMWORD[48+rsi] + movdqa xmm2,xmm1 + pxor xmm2,xmm0 + pand xmm2,xmm3 + pxor xmm0,xmm2 + pxor xmm1,xmm2 + movdqu XMMWORD[48+rdi],xmm0 + movdqu XMMWORD[48+rsi],xmm1 + + movdqu xmm0,XMMWORD[64+rdi] + movdqu xmm1,XMMWORD[64+rsi] + movdqa xmm2,xmm1 + pxor xmm2,xmm0 + pand xmm2,xmm3 + pxor xmm0,xmm2 + pxor xmm1,xmm2 + movdqu XMMWORD[64+rdi],xmm0 + movdqu XMMWORD[64+rsi],xmm1 + + movdqu xmm0,XMMWORD[80+rdi] + movdqu xmm1,XMMWORD[80+rsi] + movdqa xmm2,xmm1 + pxor xmm2,xmm0 + pand xmm2,xmm3 + pxor xmm0,xmm2 + pxor xmm1,xmm2 + movdqu XMMWORD[80+rdi],xmm0 + movdqu XMMWORD[80+rsi],xmm1 + + movdqu xmm0,XMMWORD[96+rdi] + movdqu xmm1,XMMWORD[96+rsi] + movdqa xmm2,xmm1 + pxor xmm2,xmm0 + pand xmm2,xmm3 + pxor xmm0,xmm2 + pxor xmm1,xmm2 + movdqu XMMWORD[96+rdi],xmm0 + movdqu XMMWORD[96+rsi],xmm1 + + movdqu xmm0,XMMWORD[112+rdi] + movdqu xmm1,XMMWORD[112+rsi] + movdqa xmm2,xmm1 + pxor xmm2,xmm0 + pand xmm2,xmm3 + pxor xmm0,xmm2 + pxor xmm1,xmm2 + movdqu XMMWORD[112+rdi],xmm0 + movdqu XMMWORD[112+rsi],xmm1 + + movdqu xmm0,XMMWORD[128+rdi] + movdqu xmm1,XMMWORD[128+rsi] + movdqa xmm2,xmm1 + pxor xmm2,xmm0 + pand xmm2,xmm3 + pxor xmm0,xmm2 + pxor xmm1,xmm2 + movdqu XMMWORD[128+rdi],xmm0 + movdqu XMMWORD[128+rsi],xmm1 + + movdqu xmm0,XMMWORD[144+rdi] + movdqu xmm1,XMMWORD[144+rsi] + movdqa xmm2,xmm1 + pxor xmm2,xmm0 + pand xmm2,xmm3 + pxor xmm0,xmm2 + pxor xmm1,xmm2 + movdqu XMMWORD[144+rdi],xmm0 + movdqu XMMWORD[144+rsi],xmm1 + + movdqu xmm0,XMMWORD[160+rdi] + movdqu xmm1,XMMWORD[160+rsi] + movdqa xmm2,xmm1 + pxor xmm2,xmm0 + pand xmm2,xmm3 + pxor xmm0,xmm2 + pxor xmm1,xmm2 + movdqu XMMWORD[160+rdi],xmm0 + movdqu XMMWORD[160+rsi],xmm1 + + movdqu xmm0,XMMWORD[176+rdi] + movdqu xmm1,XMMWORD[176+rsi] + movdqa xmm2,xmm1 + pxor xmm2,xmm0 + pand xmm2,xmm3 + pxor xmm0,xmm2 + pxor xmm1,xmm2 + movdqu XMMWORD[176+rdi],xmm0 + movdqu XMMWORD[176+rsi],xmm1 + + movdqu xmm0,XMMWORD[192+rdi] + movdqu xmm1,XMMWORD[192+rsi] + movdqa xmm2,xmm1 + pxor xmm2,xmm0 + pand xmm2,xmm3 + pxor xmm0,xmm2 + pxor xmm1,xmm2 + movdqu XMMWORD[192+rdi],xmm0 + movdqu XMMWORD[192+rsi],xmm1 + + movdqu xmm0,XMMWORD[208+rdi] + movdqu xmm1,XMMWORD[208+rsi] + movdqa xmm2,xmm1 + pxor xmm2,xmm0 + pand xmm2,xmm3 + pxor xmm0,xmm2 + pxor xmm1,xmm2 + movdqu XMMWORD[208+rdi],xmm0 + movdqu XMMWORD[208+rsi],xmm1 + + movdqu xmm0,XMMWORD[224+rdi] + movdqu xmm1,XMMWORD[224+rsi] + movdqa xmm2,xmm1 + pxor xmm2,xmm0 + pand xmm2,xmm3 + pxor xmm0,xmm2 + pxor xmm1,xmm2 + movdqu XMMWORD[224+rdi],xmm0 + movdqu XMMWORD[224+rsi],xmm1 + + movdqu xmm0,XMMWORD[240+rdi] + movdqu xmm1,XMMWORD[240+rsi] + movdqa xmm2,xmm1 + pxor xmm2,xmm0 + pand xmm2,xmm3 + pxor xmm0,xmm2 + pxor xmm1,xmm2 + movdqu XMMWORD[240+rdi],xmm0 + movdqu XMMWORD[240+rsi],xmm1 + + mov rdi,QWORD[8+rsp] ;WIN64 epilogue + mov rsi,QWORD[16+rsp] + DB 0F3h,0C3h ;repret +global sike_fpsub + +sike_fpsub: + mov QWORD[8+rsp],rdi ;WIN64 prologue + mov QWORD[16+rsp],rsi + mov rax,rsp +$L$SEH_begin_sike_fpsub: + mov rdi,rcx + mov rsi,rdx + mov rdx,r8 + + + + push r12 + + + push r13 + + + push r14 + + + push r15 + + + + xor rax,rax + + mov r8,QWORD[rdi] + mov r9,QWORD[8+rdi] + mov r10,QWORD[16+rdi] + mov r11,QWORD[24+rdi] + mov r12,QWORD[32+rdi] + mov r13,QWORD[40+rdi] + mov r14,QWORD[48+rdi] + mov r15,QWORD[56+rdi] + + sub r8,QWORD[rsi] + sbb r9,QWORD[8+rsi] + sbb r10,QWORD[16+rsi] + sbb r11,QWORD[24+rsi] + sbb r12,QWORD[32+rsi] + sbb r13,QWORD[40+rsi] + sbb r14,QWORD[48+rsi] + sbb r15,QWORD[56+rsi] + sbb rax,0x0 + + mov rdi,QWORD[$L$p503x2] + and rdi,rax + mov rsi,QWORD[((8+$L$p503x2))] + and rsi,rax + mov rcx,QWORD[((16+$L$p503x2))] + and rcx,rax + + add r8,rdi + adc r9,rsi + adc r10,rsi + adc r11,rcx + mov QWORD[rdx],r8 + mov QWORD[8+rdx],r9 + mov QWORD[16+rdx],r10 + mov QWORD[24+rdx],r11 + + setc cl + + mov r8,QWORD[((24+$L$p503x2))] + and r8,rax + mov r9,QWORD[((32+$L$p503x2))] + and r9,rax + mov r10,QWORD[((40+$L$p503x2))] + and r10,rax + mov r11,QWORD[((48+$L$p503x2))] + and r11,rax + + bt rcx,0x0 + + adc r12,r8 + adc r13,r9 + adc r14,r10 + adc r15,r11 + mov QWORD[32+rdx],r12 + mov QWORD[40+rdx],r13 + mov QWORD[48+rdx],r14 + mov QWORD[56+rdx],r15 + + pop r15 + + pop r14 + + pop r13 + + pop r12 + + mov rdi,QWORD[8+rsp] ;WIN64 epilogue + mov rsi,QWORD[16+rsp] + DB 0F3h,0C3h ;repret + +global sike_mpadd_asm + +sike_mpadd_asm: + mov QWORD[8+rsp],rdi ;WIN64 prologue + mov QWORD[16+rsp],rsi + mov rax,rsp +$L$SEH_begin_sike_mpadd_asm: + mov rdi,rcx + mov rsi,rdx + mov rdx,r8 + + + + mov r8,QWORD[rdi] + mov r9,QWORD[8+rdi] + mov r10,QWORD[16+rdi] + mov r11,QWORD[24+rdi] + add r8,QWORD[rsi] + adc r9,QWORD[8+rsi] + adc r10,QWORD[16+rsi] + adc r11,QWORD[24+rsi] + mov QWORD[rdx],r8 + mov QWORD[8+rdx],r9 + mov QWORD[16+rdx],r10 + mov QWORD[24+rdx],r11 + + mov r8,QWORD[32+rdi] + mov r9,QWORD[40+rdi] + mov r10,QWORD[48+rdi] + mov r11,QWORD[56+rdi] + adc r8,QWORD[32+rsi] + adc r9,QWORD[40+rsi] + adc r10,QWORD[48+rsi] + adc r11,QWORD[56+rsi] + mov QWORD[32+rdx],r8 + mov QWORD[40+rdx],r9 + mov QWORD[48+rdx],r10 + mov QWORD[56+rdx],r11 + mov rdi,QWORD[8+rsp] ;WIN64 epilogue + mov rsi,QWORD[16+rsp] + DB 0F3h,0C3h ;repret + +global sike_mpsubx2_asm + +sike_mpsubx2_asm: + mov QWORD[8+rsp],rdi ;WIN64 prologue + mov QWORD[16+rsp],rsi + mov rax,rsp +$L$SEH_begin_sike_mpsubx2_asm: + mov rdi,rcx + mov rsi,rdx + mov rdx,r8 + + + + xor rax,rax + + mov r8,QWORD[rdi] + mov r9,QWORD[8+rdi] + mov r10,QWORD[16+rdi] + mov r11,QWORD[24+rdi] + mov rcx,QWORD[32+rdi] + sub r8,QWORD[rsi] + sbb r9,QWORD[8+rsi] + sbb r10,QWORD[16+rsi] + sbb r11,QWORD[24+rsi] + sbb rcx,QWORD[32+rsi] + mov QWORD[rdx],r8 + mov QWORD[8+rdx],r9 + mov QWORD[16+rdx],r10 + mov QWORD[24+rdx],r11 + mov QWORD[32+rdx],rcx + + mov r8,QWORD[40+rdi] + mov r9,QWORD[48+rdi] + mov r10,QWORD[56+rdi] + mov r11,QWORD[64+rdi] + mov rcx,QWORD[72+rdi] + sbb r8,QWORD[40+rsi] + sbb r9,QWORD[48+rsi] + sbb r10,QWORD[56+rsi] + sbb r11,QWORD[64+rsi] + sbb rcx,QWORD[72+rsi] + mov QWORD[40+rdx],r8 + mov QWORD[48+rdx],r9 + mov QWORD[56+rdx],r10 + mov QWORD[64+rdx],r11 + mov QWORD[72+rdx],rcx + + mov r8,QWORD[80+rdi] + mov r9,QWORD[88+rdi] + mov r10,QWORD[96+rdi] + mov r11,QWORD[104+rdi] + mov rcx,QWORD[112+rdi] + sbb r8,QWORD[80+rsi] + sbb r9,QWORD[88+rsi] + sbb r10,QWORD[96+rsi] + sbb r11,QWORD[104+rsi] + sbb rcx,QWORD[112+rsi] + mov QWORD[80+rdx],r8 + mov QWORD[88+rdx],r9 + mov QWORD[96+rdx],r10 + mov QWORD[104+rdx],r11 + mov QWORD[112+rdx],rcx + + mov r8,QWORD[120+rdi] + sbb r8,QWORD[120+rsi] + sbb rax,0x0 + mov QWORD[120+rdx],r8 + mov rdi,QWORD[8+rsp] ;WIN64 epilogue + mov rsi,QWORD[16+rsp] + DB 0F3h,0C3h ;repret + +global sike_mpdblsubx2_asm + +sike_mpdblsubx2_asm: + mov QWORD[8+rsp],rdi ;WIN64 prologue + mov QWORD[16+rsp],rsi + mov rax,rsp +$L$SEH_begin_sike_mpdblsubx2_asm: + mov rdi,rcx + mov rsi,rdx + mov rdx,r8 + + + + push r12 + + + push r13 + + + push r14 + + + + xor rax,rax + + mov r8,QWORD[rdx] + mov r9,QWORD[8+rdx] + mov r10,QWORD[16+rdx] + mov r11,QWORD[24+rdx] + mov r12,QWORD[32+rdx] + mov r13,QWORD[40+rdx] + mov r14,QWORD[48+rdx] + mov rcx,QWORD[56+rdx] + sub r8,QWORD[rdi] + sbb r9,QWORD[8+rdi] + sbb r10,QWORD[16+rdi] + sbb r11,QWORD[24+rdi] + sbb r12,QWORD[32+rdi] + sbb r13,QWORD[40+rdi] + sbb r14,QWORD[48+rdi] + sbb rcx,QWORD[56+rdi] + adc rax,0x0 + + sub r8,QWORD[rsi] + sbb r9,QWORD[8+rsi] + sbb r10,QWORD[16+rsi] + sbb r11,QWORD[24+rsi] + sbb r12,QWORD[32+rsi] + sbb r13,QWORD[40+rsi] + sbb r14,QWORD[48+rsi] + sbb rcx,QWORD[56+rsi] + adc rax,0x0 + + mov QWORD[rdx],r8 + mov QWORD[8+rdx],r9 + mov QWORD[16+rdx],r10 + mov QWORD[24+rdx],r11 + mov QWORD[32+rdx],r12 + mov QWORD[40+rdx],r13 + mov QWORD[48+rdx],r14 + mov QWORD[56+rdx],rcx + + mov r8,QWORD[64+rdx] + mov r9,QWORD[72+rdx] + mov r10,QWORD[80+rdx] + mov r11,QWORD[88+rdx] + mov r12,QWORD[96+rdx] + mov r13,QWORD[104+rdx] + mov r14,QWORD[112+rdx] + mov rcx,QWORD[120+rdx] + + sub r8,rax + sbb r8,QWORD[64+rdi] + sbb r9,QWORD[72+rdi] + sbb r10,QWORD[80+rdi] + sbb r11,QWORD[88+rdi] + sbb r12,QWORD[96+rdi] + sbb r13,QWORD[104+rdi] + sbb r14,QWORD[112+rdi] + sbb rcx,QWORD[120+rdi] + sub r8,QWORD[64+rsi] + sbb r9,QWORD[72+rsi] + sbb r10,QWORD[80+rsi] + sbb r11,QWORD[88+rsi] + sbb r12,QWORD[96+rsi] + sbb r13,QWORD[104+rsi] + sbb r14,QWORD[112+rsi] + sbb rcx,QWORD[120+rsi] + + mov QWORD[64+rdx],r8 + mov QWORD[72+rdx],r9 + mov QWORD[80+rdx],r10 + mov QWORD[88+rdx],r11 + mov QWORD[96+rdx],r12 + mov QWORD[104+rdx],r13 + mov QWORD[112+rdx],r14 + mov QWORD[120+rdx],rcx + + pop r14 + + pop r13 + + pop r12 + + mov rdi,QWORD[8+rsp] ;WIN64 epilogue + mov rsi,QWORD[16+rsp] + DB 0F3h,0C3h ;repret + + +$L$mul_mulx: + + + + + + + + + mov rcx,rdx + + + xor rax,rax + mov r8,QWORD[rdi] + mov r9,QWORD[8+rdi] + mov r10,QWORD[16+rdi] + mov r11,QWORD[24+rdi] + push rbx + + + + push rbp + + + sub rsp,96 + + add r8,QWORD[32+rdi] + adc r9,QWORD[40+rdi] + adc r10,QWORD[48+rdi] + adc r11,QWORD[56+rdi] + sbb rax,0x0 + mov QWORD[rsp],r8 + mov QWORD[8+rsp],r9 + mov QWORD[16+rsp],r10 + mov QWORD[24+rsp],r11 + + + xor rbx,rbx + mov r12,QWORD[rsi] + mov r13,QWORD[8+rsi] + mov r14,QWORD[16+rsi] + mov r15,QWORD[24+rsi] + add r12,QWORD[32+rsi] + adc r13,QWORD[40+rsi] + adc r14,QWORD[48+rsi] + adc r15,QWORD[56+rsi] + sbb rbx,0x0 + mov QWORD[32+rsp],r12 + mov QWORD[40+rsp],r13 + mov QWORD[48+rsp],r14 + mov QWORD[56+rsp],r15 + + + and r12,rax + and r13,rax + and r14,rax + and r15,rax + + + and r8,rbx + and r9,rbx + and r10,rbx + and r11,rbx + + + add r8,r12 + adc r9,r13 + adc r10,r14 + adc r11,r15 + mov QWORD[64+rsp],r8 + mov QWORD[72+rsp],r9 + mov QWORD[80+rsp],r10 + mov QWORD[88+rsp],r11 + + + mov rdx,QWORD[((0+0))+rsp] + mulx r8,r9,QWORD[((32+0))+rsp] + mov QWORD[((64+0))+rcx],r9 + mulx r9,r10,QWORD[((32+8))+rsp] + xor rax,rax + adox r8,r10 + mulx r10,r11,QWORD[((32+16))+rsp] + adox r9,r11 + mulx r11,r12,QWORD[((32+24))+rsp] + adox r10,r12 + + mov rdx,QWORD[((0+8))+rsp] + mulx r13,r12,QWORD[((32+0))+rsp] + adox r11,rax + xor rax,rax + mulx r14,r15,QWORD[((32+8))+rsp] + adox r12,r8 + mov QWORD[((64+8))+rcx],r12 + adcx r13,r15 + mulx r15,rbx,QWORD[((32+16))+rsp] + adcx r14,rbx + adox r13,r9 + mulx rbx,rbp,QWORD[((32+24))+rsp] + adcx r15,rbp + adcx rbx,rax + adox r14,r10 + + mov rdx,QWORD[((0+16))+rsp] + mulx r9,r8,QWORD[((32+0))+rsp] + adox r15,r11 + adox rbx,rax + xor rax,rax + mulx r10,r11,QWORD[((32+8))+rsp] + adox r8,r13 + mov QWORD[((64+16))+rcx],r8 + adcx r9,r11 + mulx r11,r12,QWORD[((32+16))+rsp] + adcx r10,r12 + adox r9,r14 + mulx r12,rbp,QWORD[((32+24))+rsp] + adcx r11,rbp + + adcx r12,rax + adox r10,r15 + adox r11,rbx + adox r12,rax + + mov rdx,QWORD[((0+24))+rsp] + mulx r13,r8,QWORD[((32+0))+rsp] + xor rax,rax + mulx r14,r15,QWORD[((32+8))+rsp] + adcx r13,r15 + adox r9,r8 + mulx r15,rbx,QWORD[((32+16))+rsp] + adcx r14,rbx + adox r10,r13 + mulx rbx,rbp,QWORD[((32+24))+rsp] + adcx r15,rbp + adcx rbx,rax + adox r11,r14 + adox r12,r15 + adox rbx,rax + mov QWORD[((64+24))+rcx],r9 + mov QWORD[((64+32))+rcx],r10 + mov QWORD[((64+40))+rcx],r11 + mov QWORD[((64+48))+rcx],r12 + mov QWORD[((64+56))+rcx],rbx + + + + mov rdx,QWORD[((0+0))+rdi] + mulx r8,r9,QWORD[((0+0))+rsi] + mov QWORD[((0+0))+rcx],r9 + mulx r9,r10,QWORD[((0+8))+rsi] + xor rax,rax + adox r8,r10 + mulx r10,r11,QWORD[((0+16))+rsi] + adox r9,r11 + mulx r11,r12,QWORD[((0+24))+rsi] + adox r10,r12 + + mov rdx,QWORD[((0+8))+rdi] + mulx r13,r12,QWORD[((0+0))+rsi] + adox r11,rax + xor rax,rax + mulx r14,r15,QWORD[((0+8))+rsi] + adox r12,r8 + mov QWORD[((0+8))+rcx],r12 + adcx r13,r15 + mulx r15,rbx,QWORD[((0+16))+rsi] + adcx r14,rbx + adox r13,r9 + mulx rbx,rbp,QWORD[((0+24))+rsi] + adcx r15,rbp + adcx rbx,rax + adox r14,r10 + + mov rdx,QWORD[((0+16))+rdi] + mulx r9,r8,QWORD[((0+0))+rsi] + adox r15,r11 + adox rbx,rax + xor rax,rax + mulx r10,r11,QWORD[((0+8))+rsi] + adox r8,r13 + mov QWORD[((0+16))+rcx],r8 + adcx r9,r11 + mulx r11,r12,QWORD[((0+16))+rsi] + adcx r10,r12 + adox r9,r14 + mulx r12,rbp,QWORD[((0+24))+rsi] + adcx r11,rbp + + adcx r12,rax + adox r10,r15 + adox r11,rbx + adox r12,rax + + mov rdx,QWORD[((0+24))+rdi] + mulx r13,r8,QWORD[((0+0))+rsi] + xor rax,rax + mulx r14,r15,QWORD[((0+8))+rsi] + adcx r13,r15 + adox r9,r8 + mulx r15,rbx,QWORD[((0+16))+rsi] + adcx r14,rbx + adox r10,r13 + mulx rbx,rbp,QWORD[((0+24))+rsi] + adcx r15,rbp + adcx rbx,rax + adox r11,r14 + adox r12,r15 + adox rbx,rax + mov QWORD[((0+24))+rcx],r9 + mov QWORD[((0+32))+rcx],r10 + mov QWORD[((0+40))+rcx],r11 + mov QWORD[((0+48))+rcx],r12 + mov QWORD[((0+56))+rcx],rbx + + + + mov rdx,QWORD[((32+0))+rdi] + mulx r8,r9,QWORD[((32+0))+rsi] + mov QWORD[((0+0))+rsp],r9 + mulx r9,r10,QWORD[((32+8))+rsi] + xor rax,rax + adox r8,r10 + mulx r10,r11,QWORD[((32+16))+rsi] + adox r9,r11 + mulx r11,r12,QWORD[((32+24))+rsi] + adox r10,r12 + + mov rdx,QWORD[((32+8))+rdi] + mulx r13,r12,QWORD[((32+0))+rsi] + adox r11,rax + xor rax,rax + mulx r14,r15,QWORD[((32+8))+rsi] + adox r12,r8 + mov QWORD[((0+8))+rsp],r12 + adcx r13,r15 + mulx r15,rbx,QWORD[((32+16))+rsi] + adcx r14,rbx + adox r13,r9 + mulx rbx,rbp,QWORD[((32+24))+rsi] + adcx r15,rbp + adcx rbx,rax + adox r14,r10 + + mov rdx,QWORD[((32+16))+rdi] + mulx r9,r8,QWORD[((32+0))+rsi] + adox r15,r11 + adox rbx,rax + xor rax,rax + mulx r10,r11,QWORD[((32+8))+rsi] + adox r8,r13 + mov QWORD[((0+16))+rsp],r8 + adcx r9,r11 + mulx r11,r12,QWORD[((32+16))+rsi] + adcx r10,r12 + adox r9,r14 + mulx r12,rbp,QWORD[((32+24))+rsi] + adcx r11,rbp + + adcx r12,rax + adox r10,r15 + adox r11,rbx + adox r12,rax + + mov rdx,QWORD[((32+24))+rdi] + mulx r13,r8,QWORD[((32+0))+rsi] + xor rax,rax + mulx r14,r15,QWORD[((32+8))+rsi] + adcx r13,r15 + adox r9,r8 + mulx r15,rbx,QWORD[((32+16))+rsi] + adcx r14,rbx + adox r10,r13 + mulx rbx,rbp,QWORD[((32+24))+rsi] + adcx r15,rbp + adcx rbx,rax + adox r11,r14 + adox r12,r15 + adox rbx,rax + mov QWORD[((0+24))+rsp],r9 + mov QWORD[((0+32))+rsp],r10 + mov QWORD[((0+40))+rsp],r11 + mov QWORD[((0+48))+rsp],r12 + mov QWORD[((0+56))+rsp],rbx + + + + + mov r8,QWORD[64+rsp] + mov r9,QWORD[72+rsp] + mov r10,QWORD[80+rsp] + mov r11,QWORD[88+rsp] + mov rax,QWORD[96+rcx] + add r8,rax + mov rax,QWORD[104+rcx] + adc r9,rax + mov rax,QWORD[112+rcx] + adc r10,rax + mov rax,QWORD[120+rcx] + adc r11,rax + + + mov r12,QWORD[64+rcx] + mov r13,QWORD[72+rcx] + mov r14,QWORD[80+rcx] + mov r15,QWORD[88+rcx] + sub r12,QWORD[rcx] + sbb r13,QWORD[8+rcx] + sbb r14,QWORD[16+rcx] + sbb r15,QWORD[24+rcx] + sbb r8,QWORD[32+rcx] + sbb r9,QWORD[40+rcx] + sbb r10,QWORD[48+rcx] + sbb r11,QWORD[56+rcx] + + + sub r12,QWORD[rsp] + sbb r13,QWORD[8+rsp] + sbb r14,QWORD[16+rsp] + sbb r15,QWORD[24+rsp] + sbb r8,QWORD[32+rsp] + sbb r9,QWORD[40+rsp] + sbb r10,QWORD[48+rsp] + sbb r11,QWORD[56+rsp] + + add r12,QWORD[32+rcx] + mov QWORD[32+rcx],r12 + adc r13,QWORD[40+rcx] + mov QWORD[40+rcx],r13 + adc r14,QWORD[48+rcx] + mov QWORD[48+rcx],r14 + adc r15,QWORD[56+rcx] + mov QWORD[56+rcx],r15 + mov rax,QWORD[rsp] + adc r8,rax + mov QWORD[64+rcx],r8 + mov rax,QWORD[8+rsp] + adc r9,rax + mov QWORD[72+rcx],r9 + mov rax,QWORD[16+rsp] + adc r10,rax + mov QWORD[80+rcx],r10 + mov rax,QWORD[24+rsp] + adc r11,rax + mov QWORD[88+rcx],r11 + mov r12,QWORD[32+rsp] + adc r12,0x0 + mov QWORD[96+rcx],r12 + mov r13,QWORD[40+rsp] + adc r13,0x0 + mov QWORD[104+rcx],r13 + mov r14,QWORD[48+rsp] + adc r14,0x0 + mov QWORD[112+rcx],r14 + mov r15,QWORD[56+rsp] + adc r15,0x0 + mov QWORD[120+rcx],r15 + + add rsp,96 + + pop rbp + + + pop rbx + + + pop r15 + + + pop r14 + + + pop r13 + + + pop r12 + + + mov rdi,QWORD[8+rsp] ;WIN64 epilogue + mov rsi,QWORD[16+rsp] + DB 0F3h,0C3h ;repret + + +global sike_mpmul + +sike_mpmul: + mov QWORD[8+rsp],rdi ;WIN64 prologue + mov QWORD[16+rsp],rsi + mov rax,rsp +$L$SEH_begin_sike_mpmul: + mov rdi,rcx + mov rsi,rdx + mov rdx,r8 + + + + push r12 + + + push r13 + + + push r14 + + + push r15 + + + + lea rcx,[OPENSSL_ia32cap_P] + mov rcx,QWORD[8+rcx] + and ecx,0x80100 + cmp ecx,0x80100 + je NEAR $L$mul_mulx + + + + mov rcx,rdx + + + xor rax,rax + mov r8,QWORD[32+rdi] + mov r9,QWORD[40+rdi] + mov r10,QWORD[48+rdi] + mov r11,QWORD[56+rdi] + add r8,QWORD[rdi] + adc r9,QWORD[8+rdi] + adc r10,QWORD[16+rdi] + adc r11,QWORD[24+rdi] + mov QWORD[rcx],r8 + mov QWORD[8+rcx],r9 + mov QWORD[16+rcx],r10 + mov QWORD[24+rcx],r11 + sbb rax,0 + sub rsp,80 + + + + xor rdx,rdx + mov r12,QWORD[32+rsi] + mov r13,QWORD[40+rsi] + mov r14,QWORD[48+rsi] + mov r15,QWORD[56+rsi] + add r12,QWORD[rsi] + adc r13,QWORD[8+rsi] + adc r14,QWORD[16+rsi] + adc r15,QWORD[24+rsi] + sbb rdx,0x0 + mov QWORD[64+rsp],rax + mov QWORD[72+rsp],rdx + + + mov rax,QWORD[rcx] + mul r12 + mov QWORD[rsp],rax + mov r8,rdx + + xor r9,r9 + mov rax,QWORD[rcx] + mul r13 + add r8,rax + adc r9,rdx + + xor r10,r10 + mov rax,QWORD[8+rcx] + mul r12 + add r8,rax + mov QWORD[8+rsp],r8 + adc r9,rdx + adc r10,0x0 + + xor r8,r8 + mov rax,QWORD[rcx] + mul r14 + add r9,rax + adc r10,rdx + adc r8,0x0 + + mov rax,QWORD[16+rcx] + mul r12 + add r9,rax + adc r10,rdx + adc r8,0x0 + + mov rax,QWORD[8+rcx] + mul r13 + add r9,rax + mov QWORD[16+rsp],r9 + adc r10,rdx + adc r8,0x0 + + xor r9,r9 + mov rax,QWORD[rcx] + mul r15 + add r10,rax + adc r8,rdx + adc r9,0x0 + + mov rax,QWORD[24+rcx] + mul r12 + add r10,rax + adc r8,rdx + adc r9,0x0 + + mov rax,QWORD[8+rcx] + mul r14 + add r10,rax + adc r8,rdx + adc r9,0x0 + + mov rax,QWORD[16+rcx] + mul r13 + add r10,rax + mov QWORD[24+rsp],r10 + adc r8,rdx + adc r9,0x0 + + xor r10,r10 + mov rax,QWORD[8+rcx] + mul r15 + add r8,rax + adc r9,rdx + adc r10,0x0 + + mov rax,QWORD[24+rcx] + mul r13 + add r8,rax + adc r9,rdx + adc r10,0x0 + + mov rax,QWORD[16+rcx] + mul r14 + add r8,rax + mov QWORD[32+rsp],r8 + adc r9,rdx + adc r10,0x0 + + xor r11,r11 + mov rax,QWORD[16+rcx] + mul r15 + add r9,rax + adc r10,rdx + adc r11,0x0 + + mov rax,QWORD[24+rcx] + mul r14 + add r9,rax + adc r10,rdx + adc r11,0x0 + + mov rax,QWORD[24+rcx] + mul r15 + add r10,rax + adc r11,rdx + + mov rax,QWORD[64+rsp] + and r12,rax + and r13,rax + and r14,rax + and r15,rax + add r12,r8 + adc r13,r9 + adc r14,r10 + adc r15,r11 + + mov rax,QWORD[72+rsp] + mov r8,QWORD[rcx] + mov r9,QWORD[8+rcx] + mov r10,QWORD[16+rcx] + mov r11,QWORD[24+rcx] + and r8,rax + and r9,rax + and r10,rax + and r11,rax + add r8,r12 + adc r9,r13 + adc r10,r14 + adc r11,r15 + mov QWORD[32+rsp],r8 + mov QWORD[40+rsp],r9 + mov QWORD[48+rsp],r10 + mov QWORD[56+rsp],r11 + + mov r11,QWORD[rdi] + mov rax,QWORD[rsi] + mul r11 + xor r9,r9 + mov QWORD[rcx],rax + mov r8,rdx + + mov r14,QWORD[16+rdi] + mov rax,QWORD[8+rsi] + mul r11 + xor r10,r10 + add r8,rax + adc r9,rdx + + mov r12,QWORD[8+rdi] + mov rax,QWORD[rsi] + mul r12 + add r8,rax + mov QWORD[8+rcx],r8 + adc r9,rdx + adc r10,0x0 + + xor r8,r8 + mov rax,QWORD[16+rsi] + mul r11 + add r9,rax + adc r10,rdx + adc r8,0x0 + + mov r13,QWORD[rsi] + mov rax,r14 + mul r13 + add r9,rax + adc r10,rdx + adc r8,0x0 + + mov rax,QWORD[8+rsi] + mul r12 + add r9,rax + mov QWORD[16+rcx],r9 + adc r10,rdx + adc r8,0x0 + + xor r9,r9 + mov rax,QWORD[24+rsi] + mul r11 + mov r15,QWORD[24+rdi] + add r10,rax + adc r8,rdx + adc r9,0x0 + + mov rax,r15 + mul r13 + add r10,rax + adc r8,rdx + adc r9,0x0 + + mov rax,QWORD[16+rsi] + mul r12 + add r10,rax + adc r8,rdx + adc r9,0x0 + + mov rax,QWORD[8+rsi] + mul r14 + add r10,rax + mov QWORD[24+rcx],r10 + adc r8,rdx + adc r9,0x0 + + xor r10,r10 + mov rax,QWORD[24+rsi] + mul r12 + add r8,rax + adc r9,rdx + adc r10,0x0 + + mov rax,QWORD[8+rsi] + mul r15 + add r8,rax + adc r9,rdx + adc r10,0x0 + + mov rax,QWORD[16+rsi] + mul r14 + add r8,rax + mov QWORD[32+rcx],r8 + adc r9,rdx + adc r10,0x0 + + xor r8,r8 + mov rax,QWORD[24+rsi] + mul r14 + add r9,rax + adc r10,rdx + adc r8,0x0 + + mov rax,QWORD[16+rsi] + mul r15 + add r9,rax + mov QWORD[40+rcx],r9 + adc r10,rdx + adc r8,0x0 + + mov rax,QWORD[24+rsi] + mul r15 + add r10,rax + mov QWORD[48+rcx],r10 + adc r8,rdx + mov QWORD[56+rcx],r8 + + + mov r11,QWORD[32+rdi] + mov rax,QWORD[32+rsi] + mul r11 + xor r9,r9 + mov QWORD[64+rcx],rax + mov r8,rdx + + mov r14,QWORD[48+rdi] + mov rax,QWORD[40+rsi] + mul r11 + xor r10,r10 + add r8,rax + adc r9,rdx + + mov r12,QWORD[40+rdi] + mov rax,QWORD[32+rsi] + mul r12 + add r8,rax + mov QWORD[72+rcx],r8 + adc r9,rdx + adc r10,0x0 + + xor r8,r8 + mov rax,QWORD[48+rsi] + mul r11 + add r9,rax + adc r10,rdx + adc r8,0x0 + + mov r13,QWORD[32+rsi] + mov rax,r14 + mul r13 + add r9,rax + adc r10,rdx + adc r8,0x0 + + mov rax,QWORD[40+rsi] + mul r12 + add r9,rax + mov QWORD[80+rcx],r9 + adc r10,rdx + adc r8,0x0 + + xor r9,r9 + mov rax,QWORD[56+rsi] + mul r11 + mov r15,QWORD[56+rdi] + add r10,rax + adc r8,rdx + adc r9,0x0 + + mov rax,r15 + mul r13 + add r10,rax + adc r8,rdx + adc r9,0x0 + + mov rax,QWORD[48+rsi] + mul r12 + add r10,rax + adc r8,rdx + adc r9,0x0 + + mov rax,QWORD[40+rsi] + mul r14 + add r10,rax + mov QWORD[88+rcx],r10 + adc r8,rdx + adc r9,0x0 + + xor r10,r10 + mov rax,QWORD[56+rsi] + mul r12 + add r8,rax + adc r9,rdx + adc r10,0x0 + + mov rax,QWORD[40+rsi] + mul r15 + add r8,rax + adc r9,rdx + adc r10,0x0 + + mov rax,QWORD[48+rsi] + mul r14 + add r8,rax + mov QWORD[96+rcx],r8 + adc r9,rdx + adc r10,0x0 + + xor r8,r8 + mov rax,QWORD[56+rsi] + mul r14 + add r9,rax + adc r10,rdx + adc r8,0x0 + + mov rax,QWORD[48+rsi] + mul r15 + add r9,rax + mov QWORD[104+rcx],r9 + adc r10,rdx + adc r8,0x0 + + mov rax,QWORD[56+rsi] + mul r15 + add r10,rax + mov QWORD[112+rcx],r10 + adc r8,rdx + mov QWORD[120+rcx],r8 + + + mov r8,QWORD[rsp] + sub r8,QWORD[rcx] + mov r9,QWORD[8+rsp] + sbb r9,QWORD[8+rcx] + mov r10,QWORD[16+rsp] + sbb r10,QWORD[16+rcx] + mov r11,QWORD[24+rsp] + sbb r11,QWORD[24+rcx] + mov r12,QWORD[32+rsp] + sbb r12,QWORD[32+rcx] + mov r13,QWORD[40+rsp] + sbb r13,QWORD[40+rcx] + mov r14,QWORD[48+rsp] + sbb r14,QWORD[48+rcx] + mov r15,QWORD[56+rsp] + sbb r15,QWORD[56+rcx] + + + mov rax,QWORD[64+rcx] + sub r8,rax + mov rax,QWORD[72+rcx] + sbb r9,rax + mov rax,QWORD[80+rcx] + sbb r10,rax + mov rax,QWORD[88+rcx] + sbb r11,rax + mov rax,QWORD[96+rcx] + sbb r12,rax + mov rdx,QWORD[104+rcx] + sbb r13,rdx + mov rdi,QWORD[112+rcx] + sbb r14,rdi + mov rsi,QWORD[120+rcx] + sbb r15,rsi + + + add r8,QWORD[32+rcx] + mov QWORD[32+rcx],r8 + adc r9,QWORD[40+rcx] + mov QWORD[40+rcx],r9 + adc r10,QWORD[48+rcx] + mov QWORD[48+rcx],r10 + adc r11,QWORD[56+rcx] + mov QWORD[56+rcx],r11 + adc r12,QWORD[64+rcx] + mov QWORD[64+rcx],r12 + adc r13,QWORD[72+rcx] + mov QWORD[72+rcx],r13 + adc r14,QWORD[80+rcx] + mov QWORD[80+rcx],r14 + adc r15,QWORD[88+rcx] + mov QWORD[88+rcx],r15 + adc rax,0x0 + mov QWORD[96+rcx],rax + adc rdx,0x0 + mov QWORD[104+rcx],rdx + adc rdi,0x0 + mov QWORD[112+rcx],rdi + adc rsi,0x0 + mov QWORD[120+rcx],rsi + + add rsp,80 + + pop r15 + + pop r14 + + pop r13 + + pop r12 + + mov rdi,QWORD[8+rsp] ;WIN64 epilogue + mov rsi,QWORD[16+rsp] + DB 0F3h,0C3h ;repret + + +$L$rdc_mulx_asm: + + + + + + + + + + + mov rdx,QWORD[((0+0))+rdi] + mulx r9,r8,QWORD[((0+$L$p503p1_nz))] + mulx r10,r12,QWORD[((8+$L$p503p1_nz))] + + xor rax,rax + mulx r11,r13,QWORD[((16+$L$p503p1_nz))] + adox r9,r12 + adox r10,r13 + mulx r12,rbx,QWORD[((24+$L$p503p1_nz))] + adox r11,rbx + mulx r13,r14,QWORD[((32+$L$p503p1_nz))] + adox r12,r14 + adox r13,rax + + mov rdx,QWORD[((0+8))+rdi] + mulx rbx,r14,QWORD[((0+$L$p503p1_nz))] + adcx r9,r14 + adcx r10,rbx + mulx r14,rcx,QWORD[((8+$L$p503p1_nz))] + adcx r11,r14 + mulx r15,rbx,QWORD[((16+$L$p503p1_nz))] + adcx r12,r15 + mulx r14,r15,QWORD[((24+$L$p503p1_nz))] + adcx r13,r14 + mulx r14,rdx,QWORD[((32+$L$p503p1_nz))] + adcx r14,rax + + xor rax,rax + adox r10,rcx + adox r11,rbx + adox r12,r15 + adox r13,rdx + adox r14,rax + + + + xor r15,r15 + add r8,QWORD[24+rdi] + adc r9,QWORD[32+rdi] + adc r10,QWORD[40+rdi] + adc r11,QWORD[48+rdi] + adc r12,QWORD[56+rdi] + adc r13,QWORD[64+rdi] + adc r14,QWORD[72+rdi] + adc r15,QWORD[80+rdi] + mov QWORD[24+rdi],r8 + mov QWORD[32+rdi],r9 + mov QWORD[40+rdi],r10 + mov QWORD[48+rdi],r11 + mov QWORD[56+rdi],r12 + mov QWORD[64+rdi],r13 + mov QWORD[72+rdi],r14 + mov QWORD[80+rdi],r15 + mov r8,QWORD[88+rdi] + mov r9,QWORD[96+rdi] + mov r10,QWORD[104+rdi] + mov r11,QWORD[112+rdi] + mov r12,QWORD[120+rdi] + adc r8,0x0 + adc r9,0x0 + adc r10,0x0 + adc r11,0x0 + adc r12,0x0 + mov QWORD[88+rdi],r8 + mov QWORD[96+rdi],r9 + mov QWORD[104+rdi],r10 + mov QWORD[112+rdi],r11 + mov QWORD[120+rdi],r12 + + mov rdx,QWORD[((16+0))+rdi] + mulx r9,r8,QWORD[((0+$L$p503p1_nz))] + mulx r10,r12,QWORD[((8+$L$p503p1_nz))] + + xor rax,rax + mulx r11,r13,QWORD[((16+$L$p503p1_nz))] + adox r9,r12 + adox r10,r13 + mulx r12,rbx,QWORD[((24+$L$p503p1_nz))] + adox r11,rbx + mulx r13,r14,QWORD[((32+$L$p503p1_nz))] + adox r12,r14 + adox r13,rax + + mov rdx,QWORD[((16+8))+rdi] + mulx rbx,r14,QWORD[((0+$L$p503p1_nz))] + adcx r9,r14 + adcx r10,rbx + mulx r14,rcx,QWORD[((8+$L$p503p1_nz))] + adcx r11,r14 + mulx r15,rbx,QWORD[((16+$L$p503p1_nz))] + adcx r12,r15 + mulx r14,r15,QWORD[((24+$L$p503p1_nz))] + adcx r13,r14 + mulx r14,rdx,QWORD[((32+$L$p503p1_nz))] + adcx r14,rax + + xor rax,rax + adox r10,rcx + adox r11,rbx + adox r12,r15 + adox r13,rdx + adox r14,rax + + + + xor r15,r15 + add r8,QWORD[40+rdi] + adc r9,QWORD[48+rdi] + adc r10,QWORD[56+rdi] + adc r11,QWORD[64+rdi] + adc r12,QWORD[72+rdi] + adc r13,QWORD[80+rdi] + adc r14,QWORD[88+rdi] + adc r15,QWORD[96+rdi] + mov QWORD[40+rdi],r8 + mov QWORD[48+rdi],r9 + mov QWORD[56+rdi],r10 + mov QWORD[64+rdi],r11 + mov QWORD[72+rdi],r12 + mov QWORD[80+rdi],r13 + mov QWORD[88+rdi],r14 + mov QWORD[96+rdi],r15 + mov r8,QWORD[104+rdi] + mov r9,QWORD[112+rdi] + mov r10,QWORD[120+rdi] + adc r8,0x0 + adc r9,0x0 + adc r10,0x0 + mov QWORD[104+rdi],r8 + mov QWORD[112+rdi],r9 + mov QWORD[120+rdi],r10 + + mov rdx,QWORD[((32+0))+rdi] + mulx r9,r8,QWORD[((0+$L$p503p1_nz))] + mulx r10,r12,QWORD[((8+$L$p503p1_nz))] + + xor rax,rax + mulx r11,r13,QWORD[((16+$L$p503p1_nz))] + adox r9,r12 + adox r10,r13 + mulx r12,rbx,QWORD[((24+$L$p503p1_nz))] + adox r11,rbx + mulx r13,r14,QWORD[((32+$L$p503p1_nz))] + adox r12,r14 + adox r13,rax + + mov rdx,QWORD[((32+8))+rdi] + mulx rbx,r14,QWORD[((0+$L$p503p1_nz))] + adcx r9,r14 + adcx r10,rbx + mulx r14,rcx,QWORD[((8+$L$p503p1_nz))] + adcx r11,r14 + mulx r15,rbx,QWORD[((16+$L$p503p1_nz))] + adcx r12,r15 + mulx r14,r15,QWORD[((24+$L$p503p1_nz))] + adcx r13,r14 + mulx r14,rdx,QWORD[((32+$L$p503p1_nz))] + adcx r14,rax + + xor rax,rax + adox r10,rcx + adox r11,rbx + adox r12,r15 + adox r13,rdx + adox r14,rax + + + + xor r15,r15 + xor rbx,rbx + add r8,QWORD[56+rdi] + adc r9,QWORD[64+rdi] + adc r10,QWORD[72+rdi] + adc r11,QWORD[80+rdi] + adc r12,QWORD[88+rdi] + adc r13,QWORD[96+rdi] + adc r14,QWORD[104+rdi] + adc r15,QWORD[112+rdi] + adc rbx,QWORD[120+rdi] + mov QWORD[56+rdi],r8 + mov QWORD[rsi],r9 + mov QWORD[72+rdi],r10 + mov QWORD[80+rdi],r11 + mov QWORD[88+rdi],r12 + mov QWORD[96+rdi],r13 + mov QWORD[104+rdi],r14 + mov QWORD[112+rdi],r15 + mov QWORD[120+rdi],rbx + + mov rdx,QWORD[((48+0))+rdi] + mulx r9,r8,QWORD[((0+$L$p503p1_nz))] + mulx r10,r12,QWORD[((8+$L$p503p1_nz))] + + xor rax,rax + mulx r11,r13,QWORD[((16+$L$p503p1_nz))] + adox r9,r12 + adox r10,r13 + mulx r12,rbx,QWORD[((24+$L$p503p1_nz))] + adox r11,rbx + mulx r13,r14,QWORD[((32+$L$p503p1_nz))] + adox r12,r14 + adox r13,rax + + mov rdx,QWORD[((48+8))+rdi] + mulx rbx,r14,QWORD[((0+$L$p503p1_nz))] + adcx r9,r14 + adcx r10,rbx + mulx r14,rcx,QWORD[((8+$L$p503p1_nz))] + adcx r11,r14 + mulx r15,rbx,QWORD[((16+$L$p503p1_nz))] + adcx r12,r15 + mulx r14,r15,QWORD[((24+$L$p503p1_nz))] + adcx r13,r14 + mulx r14,rdx,QWORD[((32+$L$p503p1_nz))] + adcx r14,rax + + xor rax,rax + adox r10,rcx + adox r11,rbx + adox r12,r15 + adox r13,rdx + adox r14,rax + + + + add r8,QWORD[72+rdi] + adc r9,QWORD[80+rdi] + adc r10,QWORD[88+rdi] + adc r11,QWORD[96+rdi] + adc r12,QWORD[104+rdi] + adc r13,QWORD[112+rdi] + adc r14,QWORD[120+rdi] + mov QWORD[8+rsi],r8 + mov QWORD[16+rsi],r9 + mov QWORD[24+rsi],r10 + mov QWORD[32+rsi],r11 + mov QWORD[40+rsi],r12 + mov QWORD[48+rsi],r13 + mov QWORD[56+rsi],r14 + + pop rbx + + + pop r15 + + + pop r14 + + + pop r13 + + + pop r12 + + + mov rdi,QWORD[8+rsp] ;WIN64 epilogue + mov rsi,QWORD[16+rsp] + DB 0F3h,0C3h ;repret + +global sike_fprdc + +sike_fprdc: + mov QWORD[8+rsp],rdi ;WIN64 prologue + mov QWORD[16+rsp],rsi + mov rax,rsp +$L$SEH_begin_sike_fprdc: + mov rdi,rcx + mov rsi,rdx + mov rdx,r8 + + + + push r12 + + + push r13 + + + push r14 + + + push r15 + + + push rbx + + + + lea rcx,[OPENSSL_ia32cap_P] + mov rcx,QWORD[8+rcx] + and ecx,0x80100 + cmp ecx,0x80100 + je NEAR $L$rdc_mulx_asm + + + + + lea rbx,[$L$p503p1] + + mov r11,QWORD[rdi] + mov rax,QWORD[rbx] + mul r11 + xor r8,r8 + add rax,QWORD[24+rdi] + mov QWORD[24+rsi],rax + adc r8,rdx + + xor r9,r9 + mov rax,QWORD[8+rbx] + mul r11 + xor r10,r10 + add r8,rax + adc r9,rdx + + mov r12,QWORD[8+rdi] + mov rax,QWORD[rbx] + mul r12 + add r8,rax + adc r9,rdx + adc r10,0 + add r8,QWORD[32+rdi] + mov QWORD[32+rsi],r8 + adc r9,0 + adc r10,0 + + xor r8,r8 + mov rax,QWORD[16+rbx] + mul r11 + add r9,rax + adc r10,rdx + adc r8,0 + + mov rax,QWORD[8+rbx] + mul r12 + add r9,rax + adc r10,rdx + adc r8,0 + + mov r13,QWORD[16+rdi] + mov rax,QWORD[rbx] + mul r13 + add r9,rax + adc r10,rdx + adc r8,0 + add r9,QWORD[40+rdi] + mov QWORD[40+rsi],r9 + adc r10,0 + adc r8,0 + + xor r9,r9 + mov rax,QWORD[24+rbx] + mul r11 + add r10,rax + adc r8,rdx + adc r9,0 + + mov rax,QWORD[16+rbx] + mul r12 + add r10,rax + adc r8,rdx + adc r9,0 + + mov rax,QWORD[8+rbx] + mul r13 + add r10,rax + adc r8,rdx + adc r9,0 + + mov r14,QWORD[24+rsi] + mov rax,QWORD[rbx] + mul r14 + add r10,rax + adc r8,rdx + adc r9,0 + add r10,QWORD[48+rdi] + mov QWORD[48+rsi],r10 + adc r8,0 + adc r9,0 + + xor r10,r10 + mov rax,QWORD[32+rbx] + mul r11 + add r8,rax + adc r9,rdx + adc r10,0 + + mov rax,QWORD[24+rbx] + mul r12 + add r8,rax + adc r9,rdx + adc r10,0 + + mov rax,QWORD[16+rbx] + mul r13 + add r8,rax + adc r9,rdx + adc r10,0 + + mov rax,QWORD[8+rbx] + mul r14 + add r8,rax + adc r9,rdx + adc r10,0 + + mov r15,QWORD[32+rsi] + mov rax,QWORD[rbx] + mul r15 + add r8,rax + adc r9,rdx + adc r10,0 + add r8,QWORD[56+rdi] + mov QWORD[56+rsi],r8 + adc r9,0 + adc r10,0 + + xor r8,r8 + mov rax,QWORD[32+rbx] + mul r12 + add r9,rax + adc r10,rdx + adc r8,0 + + mov rax,QWORD[24+rbx] + mul r13 + add r9,rax + adc r10,rdx + adc r8,0 + + mov rax,QWORD[16+rbx] + mul r14 + add r9,rax + adc r10,rdx + adc r8,0 + + mov rax,QWORD[8+rbx] + mul r15 + add r9,rax + adc r10,rdx + adc r8,0 + + mov rcx,QWORD[40+rsi] + mov rax,QWORD[rbx] + mul rcx + add r9,rax + adc r10,rdx + adc r8,0 + add r9,QWORD[64+rdi] + mov QWORD[rsi],r9 + adc r10,0 + adc r8,0 + + xor r9,r9 + mov rax,QWORD[32+rbx] + mul r13 + add r10,rax + adc r8,rdx + adc r9,0 + + mov rax,QWORD[24+rbx] + mul r14 + add r10,rax + adc r8,rdx + adc r9,0 + + mov rax,QWORD[16+rbx] + mul r15 + add r10,rax + adc r8,rdx + adc r9,0 + + mov rax,QWORD[8+rbx] + mul rcx + add r10,rax + adc r8,rdx + adc r9,0 + + mov r13,QWORD[48+rsi] + mov rax,QWORD[rbx] + mul r13 + add r10,rax + adc r8,rdx + adc r9,0 + add r10,QWORD[72+rdi] + mov QWORD[8+rsi],r10 + adc r8,0 + adc r9,0 + + xor r10,r10 + mov rax,QWORD[32+rbx] + mul r14 + add r8,rax + adc r9,rdx + adc r10,0 + + mov rax,QWORD[24+rbx] + mul r15 + add r8,rax + adc r9,rdx + adc r10,0 + + mov rax,QWORD[16+rbx] + mul rcx + add r8,rax + adc r9,rdx + adc r10,0 + + mov rax,QWORD[8+rbx] + mul r13 + add r8,rax + adc r9,rdx + adc r10,0 + + mov r14,QWORD[56+rsi] + mov rax,QWORD[rbx] + mul r14 + add r8,rax + adc r9,rdx + adc r10,0 + add r8,QWORD[80+rdi] + mov QWORD[16+rsi],r8 + adc r9,0 + adc r10,0 + + xor r8,r8 + mov rax,QWORD[32+rbx] + mul r15 + add r9,rax + adc r10,rdx + adc r8,0 + + mov rax,QWORD[24+rbx] + mul rcx + add r9,rax + adc r10,rdx + adc r8,0 + + mov rax,QWORD[16+rbx] + mul r13 + add r9,rax + adc r10,rdx + adc r8,0 + + mov rax,QWORD[8+rbx] + mul r14 + add r9,rax + adc r10,rdx + adc r8,0 + add r9,QWORD[88+rdi] + mov QWORD[24+rsi],r9 + adc r10,0 + adc r8,0 + + xor r9,r9 + mov rax,QWORD[32+rbx] + mul rcx + add r10,rax + adc r8,rdx + adc r9,0 + + mov rax,QWORD[24+rbx] + mul r13 + add r10,rax + adc r8,rdx + adc r9,0 + + mov rax,QWORD[16+rbx] + mul r14 + add r10,rax + adc r8,rdx + adc r9,0 + add r10,QWORD[96+rdi] + mov QWORD[32+rsi],r10 + adc r8,0 + adc r9,0 + + xor r10,r10 + mov rax,QWORD[32+rbx] + mul r13 + add r8,rax + adc r9,rdx + adc r10,0 + + mov rax,QWORD[24+rbx] + mul r14 + add r8,rax + adc r9,rdx + adc r10,0 + add r8,QWORD[104+rdi] + mov QWORD[40+rsi],r8 + adc r9,0 + adc r10,0 + + mov rax,QWORD[32+rbx] + mul r14 + add r9,rax + adc r10,rdx + add r9,QWORD[112+rdi] + mov QWORD[48+rsi],r9 + adc r10,0 + add r10,QWORD[120+rdi] + mov QWORD[56+rsi],r10 + + pop rbx + + pop r15 + + pop r14 + + pop r13 + + pop r12 + + mov rdi,QWORD[8+rsp] ;WIN64 epilogue + mov rsi,QWORD[16+rsp] + DB 0F3h,0C3h ;repret + diff --git a/third_party/gmock.gyp b/third_party/gmock.gyp index 231da2cb..0ba6040f 100644 --- a/third_party/gmock.gyp +++ b/third_party/gmock.gyp @@ -27,6 +27,13 @@ 'googletest/googlemock/include', 'googletest/googletest/include', ], + 'msvs_settings': { + 'VCCLCompilerTool': { + 'DisableSpecificWarnings': [ + '4805', # unsafe mix of type 'const T1' and type 'const T2' + ], + }, + }, }, }, 'targets': [ diff --git a/third_party/gyp/generator/make.py b/third_party/gyp/generator/make.py index 8c2827e9..997eec08 100644 --- a/third_party/gyp/generator/make.py +++ b/third_party/gyp/generator/make.py @@ -1773,7 +1773,8 @@ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj)/%%%s FORCE_DO_CMD # - The multi-output rule will have an do-nothing recipe. # Hash the target name to avoid generating overlong filenames. - cmddigest = hashlib.sha1(command if command else self.target).hexdigest() + cmdstring = (command if command else self.target).encode('utf-8') + cmddigest = hashlib.sha1(cmdstring).hexdigest() intermediate = "%s.intermediate" % (cmddigest) self.WriteLn('%s: %s' % (' '.join(outputs), intermediate)) self.WriteLn('\t%s' % '@:'); diff --git a/third_party/gyp/generator/ninja.py b/third_party/gyp/generator/ninja.py index 66faabca..bf04e567 100644 --- a/third_party/gyp/generator/ninja.py +++ b/third_party/gyp/generator/ninja.py @@ -621,7 +621,7 @@ class NinjaWriter(object): args = action['action'] depfile = action.get('depfile', None) if depfile: - depfile = self.ExpandSpecial(depfile, self.base_to_build) + depfile = self.ExpandSpecial(depfile) pool = 'console' if int(action.get('ninja_use_console', 0)) else None rule_name, _ = self.WriteNewNinjaRule(name, args, description, is_cygwin, env, pool, diff --git a/third_party/gyp/input.py b/third_party/gyp/input.py index 8ac47cb9..39bdbbb3 100644 --- a/third_party/gyp/input.py +++ b/third_party/gyp/input.py @@ -902,7 +902,8 @@ def ExpandVariables(input, phase, variables, build_file): p_stdout, p_stderr = p.communicate('') if p.wait() != 0 or p_stderr: - sys.stderr.write(p_stderr) + p_stderr_decoded = p_stderr.decode('utf-8') + sys.stderr.write(p_stderr_decoded) # Simulate check_call behavior, since check_call only exists # in python 2.5 and later. raise GypError("Call to '%s' returned exit status %d while in %s." % @@ -948,7 +949,7 @@ def ExpandVariables(input, phase, variables, build_file): ProcessVariablesAndConditionsInList(replacement, phase, variables, build_file) elif type(replacement) not in (str, int): - raise GypError('Variable ' + contents + + raise GypError('Variable ' + str(contents) + ' must expand to a string or list of strings; ' + 'found a ' + replacement.__class__.__name__) diff --git a/third_party/gyp/mac_tool.py b/third_party/gyp/mac_tool.py index 84f88639..64d21063 100755 --- a/third_party/gyp/mac_tool.py +++ b/third_party/gyp/mac_tool.py @@ -113,13 +113,14 @@ class MacTool(object): raise current_section_header = None for line in stdout.splitlines(): - if ibtool_section_re.match(line): - current_section_header = line - elif not ibtool_re.match(line): + line_decoded = line.decode('utf-8') + if ibtool_section_re.match(line_decoded): + current_section_header = line_decoded + elif not ibtool_re.match(line_decoded): if current_section_header: print(current_section_header) current_section_header = None - print(line) + print(line_decoded) return 0 def _ConvertToBinary(self, dest): @@ -270,8 +271,9 @@ class MacTool(object): libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE, env=env) _, err = libtoolout.communicate() for line in err.splitlines(): - if not libtool_re.match(line) and not libtool_re5.match(line): - print(line, file=sys.stderr) + line_decoded = line.decode('utf-8') + if not libtool_re.match(line_decoded) and not libtool_re5.match(line_decoded): + print(line_decoded, file=sys.stderr) # Unconditionally touch the output .a file on the command line if present # and the command succeeded. A bit hacky. if not libtoolout.returncode: diff --git a/third_party/gyp/ninja_syntax.py b/third_party/gyp/ninja_syntax.py index d2948f06..95e89427 100644 --- a/third_party/gyp/ninja_syntax.py +++ b/third_party/gyp/ninja_syntax.py @@ -149,6 +149,14 @@ class Writer(object): return [] if isinstance(input, list): return input + + # map is not a class in Python 2 + try: + if isinstance(input, map): + return list(input) + except TypeError: + pass + return [input] diff --git a/third_party/gyp/xcode_emulation.py b/third_party/gyp/xcode_emulation.py index 4c875de3..0bdf88db 100644 --- a/third_party/gyp/xcode_emulation.py +++ b/third_party/gyp/xcode_emulation.py @@ -926,7 +926,7 @@ class XcodeSettings(object): # extensions and provide loader and main function. # These flags reflect the compilation options used by xcode to compile # extensions. - if XcodeVersion() < '0900': + if XcodeVersion()[0] < '0900': ldflags.append('-lpkstart') ldflags.append(sdk_root + '/System/Library/PrivateFrameworks/PlugInKit.framework/PlugInKit') @@ -1133,8 +1133,9 @@ class XcodeSettings(object): output = subprocess.check_output( ['security', 'find-identity', '-p', 'codesigning', '-v']) for line in output.splitlines(): - if identity in line: - fingerprint = line.split()[1] + line_decoded = line.decode('utf-8') + if identity in line_decoded: + fingerprint = line_decoded.split()[1] cache = XcodeSettings._codesigning_key_cache assert identity not in cache or fingerprint == cache[identity], ( "Multiple codesigning fingerprints for identity: %s" % identity) @@ -1450,9 +1451,9 @@ def GetStdout(cmdlist): job = subprocess.Popen(cmdlist, stdout=subprocess.PIPE) out = job.communicate()[0] if job.returncode != 0: - sys.stderr.write(out + '\n') + sys.stderr.write(out + b'\n') raise GypError('Error %d running %s' % (job.returncode, cmdlist[0])) - return out.rstrip('\n') + return out.rstrip(b'\n').decode('utf-8') def MergeGlobalXcodeSettingsToSpec(global_dict, spec): @@ -1660,7 +1661,7 @@ def _GetXcodeEnv(xcode_settings, built_products_dir, srcroot, configuration, install_name_base = xcode_settings.GetInstallNameBase() if install_name_base: env['DYLIB_INSTALL_NAME_BASE'] = install_name_base - if XcodeVersion() >= '0500' and not env.get('SDKROOT'): + if XcodeVersion()[0] >= '0500' and not env.get('SDKROOT'): sdk_root = xcode_settings._SdkRoot(configuration) if not sdk_root: sdk_root = xcode_settings._XcodeSdkPath('') diff --git a/third_party/gyp/xcodeproj_file.py b/third_party/gyp/xcodeproj_file.py index bc9814dd..9220513e 100644 --- a/third_party/gyp/xcodeproj_file.py +++ b/third_party/gyp/xcodeproj_file.py @@ -137,6 +137,7 @@ Strings of class unicode are handled properly and encoded in UTF-8 when a project file is output. """ +import functools import gyp.common import posixpath import re @@ -430,7 +431,7 @@ class XCObject(object): """ hash.update(struct.pack('>i', len(data))) - hash.update(data) + hash.update(data.encode('utf-8')) if seed_hash is None: seed_hash = _new_sha1() @@ -1417,7 +1418,8 @@ class PBXGroup(XCHierarchicalElement): def SortGroup(self): self._properties['children'] = \ - sorted(self._properties['children'], cmp=lambda x,y: x.Compare(y)) + sorted(self._properties['children'], + key=functools.cmp_to_key(XCHierarchicalElement.Compare)) # Recurse. for child in self._properties['children']: @@ -2721,7 +2723,7 @@ class PBXProject(XCContainerPortal): # according to their defined order. self._properties['mainGroup']._properties['children'] = \ sorted(self._properties['mainGroup']._properties['children'], - cmp=lambda x,y: x.CompareRootGroup(y)) + key=functools.cmp_to_key(XCHierarchicalElement.CompareRootGroup)) # Sort everything else by putting group before files, and going # alphabetically by name within sections of groups and files. SortGroup @@ -2812,9 +2814,8 @@ class PBXProject(XCContainerPortal): # Xcode seems to sort this list case-insensitively self._properties['projectReferences'] = \ - sorted(self._properties['projectReferences'], cmp=lambda x,y: - cmp(x['ProjectRef'].Name().lower(), - y['ProjectRef'].Name().lower())) + sorted(self._properties['projectReferences'], + key=lambda x: x['ProjectRef'].Name().lower()) else: # The link already exists. Pull out the relevnt data. project_ref_dict = self._other_pbxprojects[other_pbxproject] @@ -2911,19 +2912,6 @@ class PBXProject(XCContainerPortal): # same order that the targets are sorted in the remote project file. This # is the sort order used by Xcode. - def CompareProducts(x, y, remote_products): - # x and y are PBXReferenceProxy objects. Go through their associated - # PBXContainerItem to get the remote PBXFileReference, which will be - # present in the remote_products list. - x_remote = x._properties['remoteRef']._properties['remoteGlobalIDString'] - y_remote = y._properties['remoteRef']._properties['remoteGlobalIDString'] - x_index = remote_products.index(x_remote) - y_index = remote_products.index(y_remote) - - # Use the order of each remote PBXFileReference in remote_products to - # determine the sort order. - return cmp(x_index, y_index) - for other_pbxproject, ref_dict in self._other_pbxprojects.items(): # Build up a list of products in the remote project file, ordered the # same as the targets that produce them. @@ -2938,7 +2926,7 @@ class PBXProject(XCContainerPortal): product_group = ref_dict['ProductGroup'] product_group._properties['children'] = sorted( product_group._properties['children'], - cmp=lambda x, y, rp=remote_products: CompareProducts(x, y, rp)) + key=lambda x: remote_products.index(x._properties['remoteRef']._properties['remoteGlobalIDString'])) class XCProjectFile(XCObject): @@ -2969,8 +2957,7 @@ class XCProjectFile(XCObject): self._XCPrint(file, 0, '{ ') else: self._XCPrint(file, 0, '{\n') - for property, value in sorted(self._properties.iteritems(), - cmp=lambda x, y: cmp(x, y)): + for property, value in sorted(self._properties.items()): if property == 'objects': self._PrintObjects(file) else: @@ -2997,7 +2984,7 @@ class XCProjectFile(XCObject): self._XCPrint(file, 0, '\n') self._XCPrint(file, 0, '/* Begin ' + class_name + ' section */\n') for object in sorted(objects_by_class[class_name], - cmp=lambda x, y: cmp(x.id, y.id)): + key=lambda x: x.id): object.Print(file) self._XCPrint(file, 0, '/* End ' + class_name + ' section */\n') diff --git a/third_party/protobuf.gypi b/third_party/protobuf.gypi index c795af14..fcc28035 100644 --- a/third_party/protobuf.gypi +++ b/third_party/protobuf.gypi @@ -5,7 +5,7 @@ # point here and protobuf_config is set to 'source'. # # Based on the BUILD file in the Protobuf C++ release package. -# Source lists accurate as of Protobuf v3.5.1 +# Source lists accurate as of Protobuf v3.8.0 { # Some sources are used by both protobuf_lite and protobuf. Representing this @@ -15,21 +15,23 @@ # variable in the sources of both libraries instead. 'variables': { 'protobuf_common_sources': [ + '<(protobuf_source)/src/google/protobuf/any_lite.cc', '<(protobuf_source)/src/google/protobuf/arena.cc', - '<(protobuf_source)/src/google/protobuf/arenastring.cc', '<(protobuf_source)/src/google/protobuf/extension_set.cc', '<(protobuf_source)/src/google/protobuf/generated_message_table_driven_lite.cc', '<(protobuf_source)/src/google/protobuf/generated_message_util.cc', '<(protobuf_source)/src/google/protobuf/implicit_weak_message.cc', '<(protobuf_source)/src/google/protobuf/io/coded_stream.cc', + '<(protobuf_source)/src/google/protobuf/io/io_win32.cc', + '<(protobuf_source)/src/google/protobuf/io/strtod.cc', '<(protobuf_source)/src/google/protobuf/io/zero_copy_stream.cc', '<(protobuf_source)/src/google/protobuf/io/zero_copy_stream_impl_lite.cc', '<(protobuf_source)/src/google/protobuf/message_lite.cc', + '<(protobuf_source)/src/google/protobuf/parse_context.cc', '<(protobuf_source)/src/google/protobuf/repeated_field.cc', '<(protobuf_source)/src/google/protobuf/stubs/bytestream.cc', '<(protobuf_source)/src/google/protobuf/stubs/common.cc', '<(protobuf_source)/src/google/protobuf/stubs/int128.cc', - '<(protobuf_source)/src/google/protobuf/stubs/io_win32.cc', '<(protobuf_source)/src/google/protobuf/stubs/status.cc', '<(protobuf_source)/src/google/protobuf/stubs/statusor.cc', '<(protobuf_source)/src/google/protobuf/stubs/stringpiece.cc', @@ -45,12 +47,10 @@ '-Wno-unknown-warning-option', # These flags come from Protobuf's BUILD file. - '-Wall', - '-Wwrite-strings', + '-Wno-write-strings', '-Woverloaded-virtual', '-Wno-sign-compare', '-Wno-unused-function', - '-Wno-writable-strings', # These flags silence warnings that appear in protobuf upstream. # We will not maintain a divergent copy of protobuf to fix them. @@ -63,9 +63,9 @@ 'excluded_cflags': [ # In addition to turning these off above, GYP's order-of-operations means # that we need to filter the positive versions as well. + '-Wwrite-strings', '-Wsign-compare', '-Wunused-function', - '-Wwritable-strings', '-Wshadow', '-Winvalid-offsetof', '-Wcast-qual', @@ -84,6 +84,9 @@ 'cflags!': ['<@(excluded_cflags)'], 'cflags_cc': ['<@(included_cflags)'], 'cflags_cc!': ['<@(excluded_cflags)'], + 'xcode_settings': { + 'USE_HEADERMAP': 'NO', + }, 'msvs_settings': { 'VCCLCompilerTool': { # Disable warnings for third-party code. @@ -145,7 +148,6 @@ '<(protobuf_source)/src/google/protobuf/generated_message_table_driven.cc', '<(protobuf_source)/src/google/protobuf/io/gzip_stream.cc', '<(protobuf_source)/src/google/protobuf/io/printer.cc', - '<(protobuf_source)/src/google/protobuf/io/strtod.cc', '<(protobuf_source)/src/google/protobuf/io/tokenizer.cc', '<(protobuf_source)/src/google/protobuf/io/zero_copy_stream_impl.cc', '<(protobuf_source)/src/google/protobuf/map_field.cc', @@ -240,8 +242,6 @@ '<(protobuf_source)/src/google/protobuf/compiler/java/java_generator.cc', '<(protobuf_source)/src/google/protobuf/compiler/java/java_generator_factory.cc', '<(protobuf_source)/src/google/protobuf/compiler/java/java_helpers.cc', - '<(protobuf_source)/src/google/protobuf/compiler/java/java_lazy_message_field.cc', - '<(protobuf_source)/src/google/protobuf/compiler/java/java_lazy_message_field_lite.cc', '<(protobuf_source)/src/google/protobuf/compiler/java/java_map_field.cc', '<(protobuf_source)/src/google/protobuf/compiler/java/java_map_field_lite.cc', '<(protobuf_source)/src/google/protobuf/compiler/java/java_message.cc', @@ -295,6 +295,23 @@ '-lm', ], }], + ['OS=="ios"', { + # Copy protoc to iPhone and Sim directories. This allows finding it + # when using <(PRODUCT_DIR). + 'copies': [{ + 'destination': '$(BUILD_DIR)/Default-iphoneos', + 'xcode_code_sign': 1, + 'files': [ + '$(CONFIGURATION_BUILD_DIR)/protoc', + ], + }, { + 'destination': '$(BUILD_DIR)/Default-iphonesimulator', + 'xcode_code_sign': 1, + 'files': [ + '$(CONFIGURATION_BUILD_DIR)/protoc', + ], + }], + }], ], }, ], diff --git a/third_party/protobuf/BUILD b/third_party/protobuf/BUILD index 19f07c54..2fb26050 100644 --- a/third_party/protobuf/BUILD +++ b/third_party/protobuf/BUILD @@ -1,4 +1,4 @@ -# Bazel (http://bazel.io/) BUILD file for Protobuf. +# Bazel (https://bazel.build/) BUILD file for Protobuf. licenses(["notice"]) @@ -15,6 +15,12 @@ config_setting( }, ) +################################################################################ +# ZLIB configuration +################################################################################ + +ZLIB_DEPS = ["@zlib//:zlib"] + ################################################################################ # Protobuf Runtime Library ################################################################################ @@ -22,27 +28,38 @@ config_setting( MSVC_COPTS = [ "/DHAVE_PTHREAD", "/wd4018", # -Wno-sign-compare + "/wd4065", # switch statement contains 'default' but no 'case' labels + "/wd4146", # unary minus operator applied to unsigned type, result still unsigned + "/wd4244", # 'conversion' conversion from 'type1' to 'type2', possible loss of data + "/wd4251", # 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2' + "/wd4267", # 'var' : conversion from 'size_t' to 'type', possible loss of data + "/wd4305", # 'identifier' : truncation from 'type1' to 'type2' + "/wd4307", # 'operator' : integral constant overflow + "/wd4309", # 'conversion' : truncation of constant value + "/wd4334", # 'operator' : result of 32-bit shift implicitly converted to 64 bits (was 64-bit shift intended?) + "/wd4355", # 'this' : used in base member initializer list + "/wd4506", # no definition for inline function 'function' "/wd4514", # -Wno-unused-function + "/wd4800", # 'type' : forcing value to bool 'true' or 'false' (performance warning) + "/wd4996", # The compiler encountered a deprecated declaration. ] COPTS = select({ ":msvc" : MSVC_COPTS, "//conditions:default": [ "-DHAVE_PTHREAD", - "-Wall", - "-Wwrite-strings", + "-DHAVE_ZLIB", "-Woverloaded-virtual", "-Wno-sign-compare", "-Wno-unused-function", # Prevents ISO C++ const string assignment warnings for pyext sources. - "-Wno-writable-strings", + "-Wno-write-strings", ], }) -config_setting( - name = "msvc", - values = { "compiler": "msvc-cl" }, -) +load(":compiler_config_setting.bzl", "create_compiler_config_setting") + +create_compiler_config_setting(name = "msvc", value = "msvc-cl") config_setting( name = "android", @@ -51,10 +68,29 @@ config_setting( }, ) +config_setting( + name = "android-libcpp", + values = { + "crosstool_top": "@androidndk//:toolchain-libcpp", + }, +) + +config_setting( + name = "android-gnu-libstdcpp", + values = { + "crosstool_top": "@androidndk//:toolchain-gnu-libstdcpp", + }, +) + # Android and MSVC builds do not need to link in a separate pthread library. LINK_OPTS = select({ ":android": [], - ":msvc": [], + ":android-libcpp": [], + ":android-gnu-libstdcpp": [], + ":msvc": [ + # Suppress linker warnings about files with no symbols defined. + "-ignore:4221", + ], "//conditions:default": ["-lpthread", "-lm"], }) @@ -71,21 +107,23 @@ cc_library( name = "protobuf_lite", srcs = [ # AUTOGEN(protobuf_lite_srcs) + "src/google/protobuf/any_lite.cc", "src/google/protobuf/arena.cc", - "src/google/protobuf/arenastring.cc", "src/google/protobuf/extension_set.cc", "src/google/protobuf/generated_message_table_driven_lite.cc", "src/google/protobuf/generated_message_util.cc", "src/google/protobuf/implicit_weak_message.cc", "src/google/protobuf/io/coded_stream.cc", + "src/google/protobuf/io/strtod.cc", + "src/google/protobuf/io/io_win32.cc", "src/google/protobuf/io/zero_copy_stream.cc", "src/google/protobuf/io/zero_copy_stream_impl_lite.cc", "src/google/protobuf/message_lite.cc", + "src/google/protobuf/parse_context.cc", "src/google/protobuf/repeated_field.cc", "src/google/protobuf/stubs/bytestream.cc", "src/google/protobuf/stubs/common.cc", "src/google/protobuf/stubs/int128.cc", - "src/google/protobuf/stubs/io_win32.cc", "src/google/protobuf/stubs/status.cc", "src/google/protobuf/stubs/statusor.cc", "src/google/protobuf/stubs/stringpiece.cc", @@ -95,13 +133,18 @@ cc_library( "src/google/protobuf/stubs/time.cc", "src/google/protobuf/wire_format_lite.cc", ], - hdrs = glob(["src/google/protobuf/**/*.h"]), + hdrs = glob(["src/google/protobuf/**/*.h", "src/google/protobuf/**/*.inc"]), copts = COPTS, includes = ["src/"], linkopts = LINK_OPTS, visibility = ["//visibility:public"], ) +PROTOBUF_DEPS = select({ + ":msvc": [], + "//conditions:default": ZLIB_DEPS, +}) + cc_library( name = "protobuf", srcs = [ @@ -123,7 +166,6 @@ cc_library( "src/google/protobuf/generated_message_table_driven.cc", "src/google/protobuf/io/gzip_stream.cc", "src/google/protobuf/io/printer.cc", - "src/google/protobuf/io/strtod.cc", "src/google/protobuf/io/tokenizer.cc", "src/google/protobuf/io/zero_copy_stream_impl.cc", "src/google/protobuf/map_field.cc", @@ -162,12 +204,12 @@ cc_library( "src/google/protobuf/wire_format.cc", "src/google/protobuf/wrappers.pb.cc", ], - hdrs = glob(["src/**/*.h"]), + hdrs = glob(["src/**/*.h", "src/**/*.inc"]), copts = COPTS, includes = ["src/"], linkopts = LINK_OPTS, visibility = ["//visibility:public"], - deps = [":protobuf_lite"], + deps = [":protobuf_lite"] + PROTOBUF_DEPS, ) # This provides just the header files for use in projects that need to build @@ -181,14 +223,6 @@ cc_library( visibility = ["//visibility:public"], ) -objc_library( - name = "protobuf_objc", - hdrs = ["objectivec/GPBProtocolBuffers.h"], - includes = ["objectivec"], - non_arc_srcs = ["objectivec/GPBProtocolBuffers.m"], - visibility = ["//visibility:public"], -) - # Map of all well known protos. # name => (include path, imports) WELL_KNOWN_PROTO_MAP = { @@ -306,8 +340,6 @@ cc_library( "src/google/protobuf/compiler/java/java_generator.cc", "src/google/protobuf/compiler/java/java_generator_factory.cc", "src/google/protobuf/compiler/java/java_helpers.cc", - "src/google/protobuf/compiler/java/java_lazy_message_field.cc", - "src/google/protobuf/compiler/java/java_lazy_message_field_lite.cc", "src/google/protobuf/compiler/java/java_map_field.cc", "src/google/protobuf/compiler/java/java_map_field_lite.cc", "src/google/protobuf/compiler/java/java_message.cc", @@ -347,7 +379,25 @@ cc_library( ], copts = COPTS, includes = ["src/"], - linkopts = LINK_OPTS, + linkopts = LINK_OPTS + select({ + ":msvc": [ + # Linking to setargv.obj makes the default command line argument + # parser expand wildcards, so the main method's argv will contain the + # expanded list instead of the wildcards. + # + # Adding dummy "-DEFAULTLIB:kernel32.lib", because: + # - Microsoft ships this object file next to default libraries + # - but this file is not a library, just a precompiled object + # - "-WHOLEARCHIVE" and "-DEFAULTLIB" only accept library, + # not precompiled object. + # - Bazel would assume linkopt that does not start with "-" or "$" + # as a label to a target, so we add a harmless "-DEFAULTLIB:kernel32.lib" + # before "setargv.obj". + # See https://msdn.microsoft.com/en-us/library/8bch7bkk.aspx + "-DEFAULTLIB:kernel32.lib setargv.obj", + ], + "//conditions:default": [], + }), visibility = ["//visibility:public"], deps = [":protobuf"], ) @@ -404,6 +454,7 @@ RELATIVE_TEST_PROTOS = [ "google/protobuf/unittest_optimize_for.proto", "google/protobuf/unittest_preserve_unknown_enum.proto", "google/protobuf/unittest_preserve_unknown_enum2.proto", + "google/protobuf/unittest_proto3.proto", "google/protobuf/unittest_proto3_arena.proto", "google/protobuf/unittest_proto3_arena_lite.proto", "google/protobuf/unittest_proto3_lite.proto", @@ -419,6 +470,7 @@ RELATIVE_TEST_PROTOS = [ "google/protobuf/util/internal/testdata/struct.proto", "google/protobuf/util/internal/testdata/timestamp_duration.proto", "google/protobuf/util/internal/testdata/wrappers.proto", + "google/protobuf/util/json_format.proto", "google/protobuf/util/json_format_proto3.proto", "google/protobuf/util/message_differencer_unittest.proto", ] @@ -461,7 +513,7 @@ cc_binary( cc_test( name = "win32_test", - srcs = ["src/google/protobuf/stubs/io_win32_unittest.cc"], + srcs = ["src/google/protobuf/io/io_win32_unittest.cc"], deps = [ ":protobuf_lite", "//external:gtest_main", @@ -477,7 +529,6 @@ cc_test( "src/google/protobuf/arena_unittest.cc", "src/google/protobuf/arenastring_unittest.cc", "src/google/protobuf/compiler/annotation_test_util.cc", - "src/google/protobuf/compiler/command_line_interface_unittest.cc", "src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc", "src/google/protobuf/compiler/cpp/cpp_move_unittest.cc", "src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc", @@ -501,6 +552,7 @@ cc_test( "src/google/protobuf/extension_set_unittest.cc", "src/google/protobuf/generated_message_reflection_unittest.cc", "src/google/protobuf/io/coded_stream_unittest.cc", + "src/google/protobuf/io/io_win32_unittest.cc", "src/google/protobuf/io/printer_unittest.cc", "src/google/protobuf/io/tokenizer_unittest.cc", "src/google/protobuf/io/zero_copy_stream_unittest.cc", @@ -513,13 +565,13 @@ cc_test( "src/google/protobuf/proto3_arena_lite_unittest.cc", "src/google/protobuf/proto3_arena_unittest.cc", "src/google/protobuf/proto3_lite_unittest.cc", + "src/google/protobuf/proto3_lite_unittest.inc", "src/google/protobuf/reflection_ops_unittest.cc", "src/google/protobuf/repeated_field_reflection_unittest.cc", "src/google/protobuf/repeated_field_unittest.cc", "src/google/protobuf/stubs/bytestream_unittest.cc", "src/google/protobuf/stubs/common_unittest.cc", "src/google/protobuf/stubs/int128_unittest.cc", - "src/google/protobuf/stubs/io_win32_unittest.cc", "src/google/protobuf/stubs/status_test.cc", "src/google/protobuf/stubs/statusor_test.cc", "src/google/protobuf/stubs/stringpiece_unittest.cc", @@ -545,7 +597,13 @@ cc_test( "src/google/protobuf/util/type_resolver_util_test.cc", "src/google/protobuf/well_known_types_unittest.cc", "src/google/protobuf/wire_format_unittest.cc", - ], + ] + select({ + "//conditions:default" : [ + # Doesn't pass on Windows with MSVC + "src/google/protobuf/compiler/command_line_interface_unittest.cc", + ], + ":msvc": [] + }), copts = COPTS, data = [ ":test_plugin", @@ -564,7 +622,7 @@ cc_test( ":protobuf", ":protoc_lib", "//external:gtest_main", - ], + ] + PROTOBUF_DEPS, ) ################################################################################ @@ -597,6 +655,7 @@ java_library( visibility = ["//visibility:public"], deps = [ "protobuf_java", + "//external:error_prone_annotations", "//external:gson", "//external:guava", ], @@ -610,6 +669,7 @@ py_library( name = "python_srcs", srcs = glob( [ + "python/google/__init__.py", "python/google/protobuf/*.py", "python/google/protobuf/**/*.py", ], @@ -658,6 +718,7 @@ cc_binary( linkstatic = 1, deps = [ ":protobuf", + ":proto_api", ] + select({ "//conditions:default": [], ":use_fast_cpp_protos": ["//external:python_headers"], @@ -800,6 +861,15 @@ internal_protobuf_py_tests( deps = [":python_tests"], ) +cc_library( + name = "proto_api", + hdrs = ["python/google/protobuf/proto_api.h"], + deps = [ + "//external:python_headers", + ], + visibility = ["//visibility:public"], +) + proto_lang_toolchain( name = "cc_toolchain", command_line = "--cpp_out=$(OUT)", @@ -815,83 +885,116 @@ proto_lang_toolchain( visibility = ["//visibility:public"], ) -OBJC_HDRS = [ - "objectivec/GPBArray.h", - "objectivec/GPBBootstrap.h", - "objectivec/GPBCodedInputStream.h", - "objectivec/GPBCodedOutputStream.h", - "objectivec/GPBDescriptor.h", - "objectivec/GPBDictionary.h", - "objectivec/GPBExtensionInternals.h", - "objectivec/GPBExtensionRegistry.h", - "objectivec/GPBMessage.h", - "objectivec/GPBProtocolBuffers.h", - "objectivec/GPBProtocolBuffers_RuntimeSupport.h", - "objectivec/GPBRootObject.h", - "objectivec/GPBRuntimeTypes.h", - "objectivec/GPBUnknownField.h", - "objectivec/GPBUnknownFieldSet.h", - "objectivec/GPBUtilities.h", - "objectivec/GPBWellKnownTypes.h", - "objectivec/GPBWireFormat.h", - "objectivec/google/protobuf/Any.pbobjc.h", - "objectivec/google/protobuf/Api.pbobjc.h", - "objectivec/google/protobuf/Duration.pbobjc.h", - "objectivec/google/protobuf/Empty.pbobjc.h", - "objectivec/google/protobuf/FieldMask.pbobjc.h", - "objectivec/google/protobuf/SourceContext.pbobjc.h", - "objectivec/google/protobuf/Struct.pbobjc.h", - "objectivec/google/protobuf/Timestamp.pbobjc.h", - "objectivec/google/protobuf/Type.pbobjc.h", - "objectivec/google/protobuf/Wrappers.pbobjc.h", -] - -OBJC_PRIVATE_HDRS = [ - "objectivec/GPBArray_PackagePrivate.h", - "objectivec/GPBCodedInputStream_PackagePrivate.h", - "objectivec/GPBCodedOutputStream_PackagePrivate.h", - "objectivec/GPBDescriptor_PackagePrivate.h", - "objectivec/GPBDictionary_PackagePrivate.h", - "objectivec/GPBMessage_PackagePrivate.h", - "objectivec/GPBRootObject_PackagePrivate.h", - "objectivec/GPBUnknownFieldSet_PackagePrivate.h", - "objectivec/GPBUnknownField_PackagePrivate.h", - "objectivec/GPBUtilities_PackagePrivate.h", -] - -OBJC_SRCS = [ - "objectivec/GPBArray.m", - "objectivec/GPBCodedInputStream.m", - "objectivec/GPBCodedOutputStream.m", - "objectivec/GPBDescriptor.m", - "objectivec/GPBDictionary.m", - "objectivec/GPBExtensionInternals.m", - "objectivec/GPBExtensionRegistry.m", - "objectivec/GPBMessage.m", - "objectivec/GPBRootObject.m", - "objectivec/GPBUnknownField.m", - "objectivec/GPBUnknownFieldSet.m", - "objectivec/GPBUtilities.m", - "objectivec/GPBWellKnownTypes.m", - "objectivec/GPBWireFormat.m", - "objectivec/google/protobuf/Any.pbobjc.m", - "objectivec/google/protobuf/Api.pbobjc.m", - "objectivec/google/protobuf/Duration.pbobjc.m", - "objectivec/google/protobuf/Empty.pbobjc.m", - "objectivec/google/protobuf/FieldMask.pbobjc.m", - "objectivec/google/protobuf/SourceContext.pbobjc.m", - "objectivec/google/protobuf/Struct.pbobjc.m", - "objectivec/google/protobuf/Timestamp.pbobjc.m", - "objectivec/google/protobuf/Type.pbobjc.m", - "objectivec/google/protobuf/Wrappers.pbobjc.m", -] +alias( + name = "objectivec", + actual = ":protobuf_objc", + visibility = ["//visibility:public"], +) objc_library( - name = "objectivec", - hdrs = OBJC_HDRS + OBJC_PRIVATE_HDRS, + name = "protobuf_objc", + hdrs = [ + "objectivec/GPBArray.h", + "objectivec/GPBBootstrap.h", + "objectivec/GPBCodedInputStream.h", + "objectivec/GPBCodedOutputStream.h", + "objectivec/GPBDescriptor.h", + "objectivec/GPBDictionary.h", + "objectivec/GPBExtensionInternals.h", + "objectivec/GPBExtensionRegistry.h", + "objectivec/GPBMessage.h", + "objectivec/GPBProtocolBuffers.h", + "objectivec/GPBProtocolBuffers_RuntimeSupport.h", + "objectivec/GPBRootObject.h", + "objectivec/GPBRuntimeTypes.h", + "objectivec/GPBUnknownField.h", + "objectivec/GPBUnknownFieldSet.h", + "objectivec/GPBUtilities.h", + "objectivec/GPBWellKnownTypes.h", + "objectivec/GPBWireFormat.h", + "objectivec/google/protobuf/Any.pbobjc.h", + "objectivec/google/protobuf/Api.pbobjc.h", + "objectivec/google/protobuf/Duration.pbobjc.h", + "objectivec/google/protobuf/Empty.pbobjc.h", + "objectivec/google/protobuf/FieldMask.pbobjc.h", + "objectivec/google/protobuf/SourceContext.pbobjc.h", + "objectivec/google/protobuf/Struct.pbobjc.h", + "objectivec/google/protobuf/Timestamp.pbobjc.h", + "objectivec/google/protobuf/Type.pbobjc.h", + "objectivec/google/protobuf/Wrappers.pbobjc.h", + # Package private headers, but exposed because the generated sources + # need to use them. + "objectivec/GPBArray_PackagePrivate.h", + "objectivec/GPBCodedInputStream_PackagePrivate.h", + "objectivec/GPBCodedOutputStream_PackagePrivate.h", + "objectivec/GPBDescriptor_PackagePrivate.h", + "objectivec/GPBDictionary_PackagePrivate.h", + "objectivec/GPBMessage_PackagePrivate.h", + "objectivec/GPBRootObject_PackagePrivate.h", + "objectivec/GPBUnknownFieldSet_PackagePrivate.h", + "objectivec/GPBUnknownField_PackagePrivate.h", + "objectivec/GPBUtilities_PackagePrivate.h", + ], + copts = [ + "-Wno-vla", + ], includes = [ "objectivec", ], - non_arc_srcs = OBJC_SRCS, + non_arc_srcs = [ + "objectivec/GPBArray.m", + "objectivec/GPBCodedInputStream.m", + "objectivec/GPBCodedOutputStream.m", + "objectivec/GPBDescriptor.m", + "objectivec/GPBDictionary.m", + "objectivec/GPBExtensionInternals.m", + "objectivec/GPBExtensionRegistry.m", + "objectivec/GPBMessage.m", + "objectivec/GPBRootObject.m", + "objectivec/GPBUnknownField.m", + "objectivec/GPBUnknownFieldSet.m", + "objectivec/GPBUtilities.m", + "objectivec/GPBWellKnownTypes.m", + "objectivec/GPBWireFormat.m", + "objectivec/google/protobuf/Any.pbobjc.m", + "objectivec/google/protobuf/Api.pbobjc.m", + "objectivec/google/protobuf/Duration.pbobjc.m", + "objectivec/google/protobuf/Empty.pbobjc.m", + "objectivec/google/protobuf/FieldMask.pbobjc.m", + "objectivec/google/protobuf/SourceContext.pbobjc.m", + "objectivec/google/protobuf/Struct.pbobjc.m", + "objectivec/google/protobuf/Timestamp.pbobjc.m", + "objectivec/google/protobuf/Type.pbobjc.m", + "objectivec/google/protobuf/Wrappers.pbobjc.m", + ], visibility = ["//visibility:public"], ) + +################################################################################ +# Test generated proto support +################################################################################ + +genrule( + name = "generated_protos", + srcs = ["src/google/protobuf/unittest_import.proto"], + outs = ["unittest_gen.proto"], + cmd = "cat $(SRCS) | sed 's|google/|src/google/|' > $(OUTS)" +) + +proto_library( + name = "generated_protos_proto", + srcs = [ + "unittest_gen.proto", + "src/google/protobuf/unittest_import_public.proto", + ], +) + +py_proto_library( + name = "generated_protos_py", + srcs = [ + "unittest_gen.proto", + "src/google/protobuf/unittest_import_public.proto", + ], + default_runtime = "", + protoc = ":protoc", +) diff --git a/third_party/protobuf/CHANGES.txt b/third_party/protobuf/CHANGES.txt index a381084a..72ee3717 100644 --- a/third_party/protobuf/CHANGES.txt +++ b/third_party/protobuf/CHANGES.txt @@ -1,3 +1,140 @@ +2019-04-29 version 3.8.0 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript) + + C++ + * Use std::atomic in case of myriad2 platform + * Always declare enums to be int-sized + * Added DebugString() and ShortDebugString() methods on MessageLite + * Specialized different parse loop control flows + * Make hasbits potentially in register. The or's start forming an obstacle because it's a read modify store on the same mem address on each iteration. + * Move to an internal MACRO for parser validity checks. + * Improve map parsing performance. + * Make MergePartialFromCodedStream non virtual. This allows direct calls, potential inlining and is also a code health improvement + * Add an overall limit to parse_context to prevent reading past it. This allows to remove a annoying level of indirection. + * Fix a mistake, we shouldn't verify map key/value strings for utf8 in opt mode for proto2. + * Further improvements to cut binary size. + * Prepare to make MergePartialFromCodedStream non-virtual. + * A report on some interesting behavior change in python (caused by b/27494216) made me realize there is a check that needs to be done in case the parse ended on a end group tag. + * Add a note of caution to the comments around skip in CodedOutputStream. + * Simplify end check. + * Add overload for ParseMessage for MessageLite/Message types. If the explicit type is not known inlining won't help de-virtualizing the virtual call. + * Reduce linker input. It turns out that ParseMessage is not inlined, producing template instantiations that are used only once and save nothing but cost more. + * Improve the parser. + * [c++17] Changed proto2::RepeatedPtrField iterators to no longer derive from the deprecated std::iterator class. + * Change the default value of case_insensitive_enum_parsing to false for JsonStringToMessage. + * Add a warning if a field name doesn't match the style guide. + * Fix TextFormat not round-trip correctly when float value is max float. + * Added locationed info for some errors at compiler + * Python reserved keywords are now working with getattr()/setattr() for most descriptors. + * Added AllowUnknownField() in text_format + * Append '_' to C++ reserved keywords for message, enum, extension + * Fix MSVC warning C4244 in protobuf's parse_context.h. + * Updating Iterators to be compatible with C++17 in MSVC. + * Use capability annotation in mutex.h + * Fix "UndefinedBehaviorSanitizer: cfi-bad-type" + * CriticalSectionLock class as a lightweight replacement for std::mutex on Windows platforms. + * Removed vestigial wire_format_lite_inl.h + + C# + * Added System.Memory dependency. + + Java + * Make Java protoc code generator ignore optimize_for LITE_RUNTIME. Users should instead use the Java lite protoc plugin. + * Change Extension getMessageDefaultInstance() to return Message instead of MessageLite. + * Prevent malicious input streams from leaking buffers for ByteString or ByteBuffer parsing. + * Release new Javalite runtime. + * Show warning in case potential file name conflict. + * Allow Java reserved keywords to be used in extensions. + * Added setAllowUnknownFields() in text format + * Add memoization to ExtensionRegistryLite.getEmptyRegistry() + * Improve performance of CodedOutputStream.writeUInt32NoTag + * Add an optimized mismatch-finding algorithm to UnsafeUtil. + * When serializing uint32 varints, check that we have MAX_VARINT32_SIZE bytes left, not just MAX_VARINT_SIZE. + * Minor optimization to RopeByteString.PieceIterator + + JavaScript + * Simplify generated toObject code when the default value is used. + + Python + * Changes implementation of Name() for enums that allow aliases in proto2 in Python to be in line with claims in C++ implementation (to return first value). + * Added double_format option in text format printer. + * Added iter and __contains__ to extension dict + * Added allow_unknown_field option in python text format parser + * Fixed Timestamp.ToDatetime() loses precision issue + * Support unknown field in text format printer. + * Float field will be convert to inf if bigger than struct.unpack('f', b'\xff\xff\x7f\x7f')[0] which is about 3.4028234664e+38, + convert to -inf if smaller than -3.4028234664e+38 + * Allowed casting str->bytes in Message.__setstate__ + + Ruby + * Helper methods to get enum name for Ruby. + + +2019-01-24 version 3.7.0 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript) + + C++ + * Introduced new MOMI (maybe-outside-memory-interval) parser. + * Add an option to json_util to parse enum as case-insensitive. In the future, enum parsing in json_util will become case-sensitive. + * Added conformance test for enum aliases + * Added support for --cpp_out=speed:... + * Added use of C++ override keyword where appropriate + * Many other cleanups and fixes. + + Java + * Fix illegal reflective access warning in JDK 9+ + * Add BOM + + Python + * Added Python 3.7 compatibility. + * Modified ParseFromString to return bytes parsed . + * Introduce Proto C API. + * FindFileContainingSymbol in descriptor pool is now able to find field and enum values. + * reflection.MakeClass() and reflection.ParseMessage() are deprecated. + * Added DescriptorPool.FindMethodByName() method in pure python (c extension alreay has it) + * Flipped proto3 to preserve unknown fields by default. + * Added support for memoryview in python3 proto message parsing. + * Added MergeFrom for repeated scalar fields in c extension (pure python already has it) + * Surrogates are now rejected at setters in python3. + * Added public unknown field API. + * RecursionLimit is also set to max if allow_oversize_protos is enabled. + * Disallow duplicate scalars in proto3 text_format parse. + * Fix some segment faults for c extension map field. + + PHP + * Most issues for json encoding/decoding in the c extension have been fixed. There are still some edge cases not fixed. For more details, check conformance/failure_list_php_c.txt. + * Supports php 7.3 + * Added helper methods to convert between enum values and names. + * Allow setting/getting wrapper message fields using primitive values. + * Various bug fixes. + + Ruby + * Ruby 2.6 support. + * Drops support for ruby < 2.3. + * Most issues for json encoding/decoding in the c extension have been fixed. There are still some edge cases not fixed. For more details, check conformance/failure_list_ruby.txt. + * Json parsing can specify an option to ignore unknown fields: msg.decode_json(data, {ignore_unknown_fields: true}). + * Added support for proto2 syntax (partially). + * Various bug fixes. + + Csharp + * More support for FieldMask include merge, intersect and more. + * Increasing the default recursion limit to 100. + * Support loading FileDescriptors dynamically. + * Provide access to comments from descriptors. + * Added Any.Is method. + * Compatible with C# 6 + * Added IComparable and comparison operators on Timestamp. + + Objective C + * Add ability to introspect list of enum values (#4678) + * Copy the value when setting message/data fields (#5215) + * Support suppressing the objc package prefix checks on a list of files (#5309) + * More complete keyword and NSObject method (via categories) checks for field names, can result in more fields being rename, but avoids the collisions at runtime (#5289) + * Small fixes to TextFormat generation for extensions (#5362) + * Provide more details/context in deprecation messages (#5412) + * Array/Dictionary enumeration blocks NS_NOESCAPE annotation for Swift (#5421) + * Properly annotate extensions for ARC when their names imply behaviors (#5427) + * Enum alias name collision improvements (#5480) + + 2018-07-27 version 3.6.1 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript) C++ @@ -102,7 +239,7 @@ Planned Future Changes * Make C++ implementation C++11 only: we plan to require C++11 to build protobuf code starting from 3.6.0 release. Please join this github issue: - https://github.com/google/protobuf/issues/2780 to provide your feedback. + https://github.com/protocolbuffers/protobuf/issues/2780 to provide your feedback. protoc * Fixed a bug introduced in 3.5.0 and protoc in Windows now accepts non-ascii @@ -133,7 +270,7 @@ Planned Future Changes * Make C++ implementation C++11 only: we plan to require C++11 to build protobuf code starting from 3.6.0 release. Please join this github issue: - https://github.com/google/protobuf/issues/2780 to provide your feedback. + https://github.com/protocolbuffers/protobuf/issues/2780 to provide your feedback. General * Unknown fields are now preserved in proto3 for most of the language @@ -220,14 +357,14 @@ For issues and discussions: - https://github.com/google/protobuf/issues/272 + https://github.com/protocolbuffers/protobuf/issues/272 - Make C++ implementation C++11 only: we plan to require C++11 to build protobuf code starting from 3.5.0 or 3.6.0 release, after unknown fields semantic changes are finished. Please join this github issue: - https://github.com/google/protobuf/issues/2780 + https://github.com/protocolbuffers/protobuf/issues/2780 to provide your feedback. @@ -347,14 +484,14 @@ for the timeline and follow up this github issue: - https://github.com/google/protobuf/issues/272 + https://github.com/protocolbuffers/protobuf/issues/272 for discussion. - Make C++ implementation C++11 only: we plan to require C++11 to build protobuf code starting from 3.4.0 or 3.5.0 release. Please join this github issue: - https://github.com/google/protobuf/issues/2780 + https://github.com/protocolbuffers/protobuf/issues/2780 to provide your feedback. @@ -581,7 +718,7 @@ details about APIs. Objective-C - * Helpers are now provided for working the the Any well known type (see + * Helpers are now provided for working the Any well known type (see GPBWellKnownTypes.h for the api additions). * Some improvements in startup code (especially when extensions aren’t used). diff --git a/third_party/protobuf/Makefile.am b/third_party/protobuf/Makefile.am index ae4ac858..33616c58 100644 --- a/third_party/protobuf/Makefile.am +++ b/third_party/protobuf/Makefile.am @@ -49,15 +49,18 @@ pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = protobuf.pc protobuf-lite.pc csharp_EXTRA_DIST= \ + global.json \ csharp/.gitignore \ csharp/CHANGES.txt \ + csharp/Google.Protobuf.Tools.targets \ csharp/Google.Protobuf.Tools.nuspec \ csharp/README.md \ csharp/build_packages.bat \ csharp/build_tools.sh \ + csharp/buildall.bat \ csharp/buildall.sh \ csharp/generate_protos.sh \ - csharp/global.json \ + csharp/install_dotnet_sdk.ps1 \ csharp/keys/Google.Protobuf.public.snk \ csharp/keys/Google.Protobuf.snk \ csharp/keys/README.md \ @@ -74,6 +77,12 @@ csharp_EXTRA_DIST= \ csharp/src/AddressBook/ListPeople.cs \ csharp/src/AddressBook/Program.cs \ csharp/src/AddressBook/SampleUsage.cs \ + csharp/src/Google.Protobuf.Benchmarks/SerializationConfig.cs \ + csharp/src/Google.Protobuf.Benchmarks/SerializationBenchmark.cs \ + csharp/src/Google.Protobuf.Benchmarks/Program.cs \ + csharp/src/Google.Protobuf.Benchmarks/Google.Protobuf.Benchmarks.csproj \ + csharp/src/Google.Protobuf.Benchmarks/Benchmarks.cs \ + csharp/src/Google.Protobuf.Benchmarks/BenchmarkMessage1Proto3.cs \ csharp/src/Google.Protobuf.Conformance/Conformance.cs \ csharp/src/Google.Protobuf.Conformance/Google.Protobuf.Conformance.csproj \ csharp/src/Google.Protobuf.Conformance/Program.cs \ @@ -92,6 +101,7 @@ csharp_EXTRA_DIST= \ csharp/src/Google.Protobuf.Test/DeprecatedMemberTest.cs \ csharp/src/Google.Protobuf.Test/EqualityTester.cs \ csharp/src/Google.Protobuf.Test/FieldCodecTest.cs \ + csharp/src/Google.Protobuf.Test/FieldMaskTreeTest.cs \ csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs \ csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj \ csharp/src/Google.Protobuf.Test/IssuesTest.cs \ @@ -99,6 +109,7 @@ csharp_EXTRA_DIST= \ csharp/src/Google.Protobuf.Test/JsonParserTest.cs \ csharp/src/Google.Protobuf.Test/JsonTokenizerTest.cs \ csharp/src/Google.Protobuf.Test/Reflection/CustomOptionsTest.cs \ + csharp/src/Google.Protobuf.Test/Reflection/DescriptorDeclarationTest.cs \ csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs \ csharp/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs \ csharp/src/Google.Protobuf.Test/Reflection/TypeRegistryTest.cs \ @@ -121,6 +132,7 @@ csharp_EXTRA_DIST= \ csharp/src/Google.Protobuf.Test/WellKnownTypes/TimestampTest.cs \ csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs \ csharp/src/Google.Protobuf.Test/UnknownFieldSetTest.cs \ + csharp/src/Google.Protobuf.Test/testprotos.pb \ csharp/src/Google.Protobuf.sln \ csharp/src/Google.Protobuf/ByteArray.cs \ csharp/src/Google.Protobuf/ByteString.cs \ @@ -137,6 +149,7 @@ csharp_EXTRA_DIST= \ csharp/src/Google.Protobuf/Compatibility/StreamExtensions.cs \ csharp/src/Google.Protobuf/Compatibility/TypeExtensions.cs \ csharp/src/Google.Protobuf/FieldCodec.cs \ + csharp/src/Google.Protobuf/FieldMaskTree.cs \ csharp/src/Google.Protobuf/FrameworkPortability.cs \ csharp/src/Google.Protobuf/Google.Protobuf.csproj \ csharp/src/Google.Protobuf/ICustomDiagnosticMessage.cs \ @@ -156,6 +169,7 @@ csharp_EXTRA_DIST= \ csharp/src/Google.Protobuf/Reflection/CustomOptions.cs \ csharp/src/Google.Protobuf/Reflection/Descriptor.cs \ csharp/src/Google.Protobuf/Reflection/DescriptorBase.cs \ + csharp/src/Google.Protobuf/Reflection/DescriptorDeclaration.cs \ csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs \ csharp/src/Google.Protobuf/Reflection/DescriptorUtil.cs \ csharp/src/Google.Protobuf/Reflection/DescriptorValidationException.cs \ @@ -175,7 +189,6 @@ csharp_EXTRA_DIST= \ csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs \ csharp/src/Google.Protobuf/Reflection/OriginalNameAttribute.cs \ csharp/src/Google.Protobuf/Reflection/PackageDescriptor.cs \ - csharp/src/Google.Protobuf/Reflection/PartialClasses.cs \ csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs \ csharp/src/Google.Protobuf/Reflection/RepeatedFieldAccessor.cs \ csharp/src/Google.Protobuf/Reflection/ServiceDescriptor.cs \ @@ -204,6 +217,7 @@ csharp_EXTRA_DIST= \ java_EXTRA_DIST= \ java/README.md \ + java/bom/pom.xml \ java/core/generate-sources-build.xml \ java/core/generate-test-sources-build.xml \ java/core/pom.xml \ @@ -211,17 +225,25 @@ java_EXTRA_DIST= java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java \ java/core/src/main/java/com/google/protobuf/AbstractParser.java \ java/core/src/main/java/com/google/protobuf/AbstractProtobufList.java \ + java/core/src/main/java/com/google/protobuf/AllocatedBuffer.java \ java/core/src/main/java/com/google/protobuf/Android.java \ + java/core/src/main/java/com/google/protobuf/ArrayDecoders.java \ + java/core/src/main/java/com/google/protobuf/BinaryReader.java \ + java/core/src/main/java/com/google/protobuf/BinaryWriter.java \ java/core/src/main/java/com/google/protobuf/BlockingRpcChannel.java \ java/core/src/main/java/com/google/protobuf/BlockingService.java \ java/core/src/main/java/com/google/protobuf/BooleanArrayList.java \ + java/core/src/main/java/com/google/protobuf/BufferAllocator.java \ java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java \ java/core/src/main/java/com/google/protobuf/ByteOutput.java \ java/core/src/main/java/com/google/protobuf/ByteString.java \ java/core/src/main/java/com/google/protobuf/CodedInputStream.java \ + java/core/src/main/java/com/google/protobuf/CodedInputStreamReader.java \ java/core/src/main/java/com/google/protobuf/CodedOutputStream.java \ - java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java \ + java/core/src/main/java/com/google/protobuf/CodedOutputStreamWriter.java \ + java/core/src/main/java/com/google/protobuf/DescriptorMessageInfoFactory.java \ java/core/src/main/java/com/google/protobuf/Descriptors.java \ + java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java \ java/core/src/main/java/com/google/protobuf/DoubleArrayList.java \ java/core/src/main/java/com/google/protobuf/DynamicMessage.java \ java/core/src/main/java/com/google/protobuf/ExperimentalApi.java \ @@ -230,37 +252,65 @@ java_EXTRA_DIST= java/core/src/main/java/com/google/protobuf/ExtensionRegistry.java \ java/core/src/main/java/com/google/protobuf/ExtensionRegistryFactory.java \ java/core/src/main/java/com/google/protobuf/ExtensionRegistryLite.java \ + java/core/src/main/java/com/google/protobuf/ExtensionSchema.java \ + java/core/src/main/java/com/google/protobuf/ExtensionSchemaFull.java \ + java/core/src/main/java/com/google/protobuf/ExtensionSchemaLite.java \ + java/core/src/main/java/com/google/protobuf/ExtensionSchemas.java \ + java/core/src/main/java/com/google/protobuf/FieldInfo.java \ java/core/src/main/java/com/google/protobuf/FieldSet.java \ + java/core/src/main/java/com/google/protobuf/FieldType.java \ java/core/src/main/java/com/google/protobuf/FloatArrayList.java \ java/core/src/main/java/com/google/protobuf/GeneratedMessage.java \ + java/core/src/main/java/com/google/protobuf/GeneratedMessageInfoFactory.java \ java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java \ java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java \ java/core/src/main/java/com/google/protobuf/IntArrayList.java \ java/core/src/main/java/com/google/protobuf/Internal.java \ java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java \ java/core/src/main/java/com/google/protobuf/IterableByteBufferInputStream.java \ + java/core/src/main/java/com/google/protobuf/JavaType.java \ java/core/src/main/java/com/google/protobuf/LazyField.java \ java/core/src/main/java/com/google/protobuf/LazyFieldLite.java \ java/core/src/main/java/com/google/protobuf/LazyStringArrayList.java \ java/core/src/main/java/com/google/protobuf/LazyStringList.java \ + java/core/src/main/java/com/google/protobuf/ListFieldSchema.java \ java/core/src/main/java/com/google/protobuf/LongArrayList.java \ + java/core/src/main/java/com/google/protobuf/ManifestSchemaFactory.java \ java/core/src/main/java/com/google/protobuf/MapEntry.java \ java/core/src/main/java/com/google/protobuf/MapEntryLite.java \ java/core/src/main/java/com/google/protobuf/MapField.java \ java/core/src/main/java/com/google/protobuf/MapFieldLite.java \ + java/core/src/main/java/com/google/protobuf/MapFieldSchema.java \ + java/core/src/main/java/com/google/protobuf/MapFieldSchemaFull.java \ + java/core/src/main/java/com/google/protobuf/MapFieldSchemaLite.java \ + java/core/src/main/java/com/google/protobuf/MapFieldSchemas.java \ java/core/src/main/java/com/google/protobuf/Message.java \ + java/core/src/main/java/com/google/protobuf/MessageInfo.java \ + java/core/src/main/java/com/google/protobuf/MessageInfoFactory.java \ java/core/src/main/java/com/google/protobuf/MessageLite.java \ java/core/src/main/java/com/google/protobuf/MessageLiteOrBuilder.java \ java/core/src/main/java/com/google/protobuf/MessageLiteToString.java \ java/core/src/main/java/com/google/protobuf/MessageOrBuilder.java \ java/core/src/main/java/com/google/protobuf/MessageReflection.java \ + java/core/src/main/java/com/google/protobuf/MessageSchema.java \ + java/core/src/main/java/com/google/protobuf/MessageSetSchema.java \ java/core/src/main/java/com/google/protobuf/MutabilityOracle.java \ + java/core/src/main/java/com/google/protobuf/NewInstanceSchema.java \ + java/core/src/main/java/com/google/protobuf/NewInstanceSchemaFull.java \ + java/core/src/main/java/com/google/protobuf/NewInstanceSchemaLite.java \ + java/core/src/main/java/com/google/protobuf/NewInstanceSchemas.java \ java/core/src/main/java/com/google/protobuf/NioByteString.java \ + java/core/src/main/java/com/google/protobuf/OneofInfo.java \ java/core/src/main/java/com/google/protobuf/Parser.java \ java/core/src/main/java/com/google/protobuf/PrimitiveNonBoxingCollection.java \ + java/core/src/main/java/com/google/protobuf/ProtoSyntax.java \ + java/core/src/main/java/com/google/protobuf/Protobuf.java \ java/core/src/main/java/com/google/protobuf/ProtobufArrayList.java \ + java/core/src/main/java/com/google/protobuf/ProtobufLists.java \ java/core/src/main/java/com/google/protobuf/ProtocolMessageEnum.java \ java/core/src/main/java/com/google/protobuf/ProtocolStringList.java \ + java/core/src/main/java/com/google/protobuf/RawMessageInfo.java \ + java/core/src/main/java/com/google/protobuf/Reader.java \ java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilder.java \ java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java \ java/core/src/main/java/com/google/protobuf/RopeByteString.java \ @@ -268,30 +318,47 @@ java_EXTRA_DIST= java/core/src/main/java/com/google/protobuf/RpcChannel.java \ java/core/src/main/java/com/google/protobuf/RpcController.java \ java/core/src/main/java/com/google/protobuf/RpcUtil.java \ + java/core/src/main/java/com/google/protobuf/Schema.java \ + java/core/src/main/java/com/google/protobuf/SchemaFactory.java \ + java/core/src/main/java/com/google/protobuf/SchemaUtil.java \ java/core/src/main/java/com/google/protobuf/Service.java \ java/core/src/main/java/com/google/protobuf/ServiceException.java \ java/core/src/main/java/com/google/protobuf/SingleFieldBuilder.java \ java/core/src/main/java/com/google/protobuf/SingleFieldBuilderV3.java \ java/core/src/main/java/com/google/protobuf/SmallSortedMap.java \ + java/core/src/main/java/com/google/protobuf/StructuralMessageInfo.java \ java/core/src/main/java/com/google/protobuf/TextFormat.java \ java/core/src/main/java/com/google/protobuf/TextFormatEscaper.java \ java/core/src/main/java/com/google/protobuf/TextFormatParseInfoTree.java \ java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java \ java/core/src/main/java/com/google/protobuf/UninitializedMessageException.java \ + java/core/src/main/java/com/google/protobuf/UnknownFieldSchema.java \ java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java \ java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java \ + java/core/src/main/java/com/google/protobuf/UnknownFieldSetLiteSchema.java \ + java/core/src/main/java/com/google/protobuf/UnknownFieldSetSchema.java \ java/core/src/main/java/com/google/protobuf/UnmodifiableLazyStringList.java \ java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java \ java/core/src/main/java/com/google/protobuf/UnsafeUtil.java \ java/core/src/main/java/com/google/protobuf/Utf8.java \ java/core/src/main/java/com/google/protobuf/WireFormat.java \ + java/core/src/main/java/com/google/protobuf/Writer.java \ java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java \ + java/core/src/test/java/com/google/protobuf/AbstractProto2LiteSchemaTest.java \ + java/core/src/test/java/com/google/protobuf/AbstractProto2SchemaTest.java \ + java/core/src/test/java/com/google/protobuf/AbstractProto3LiteSchemaTest.java \ + java/core/src/test/java/com/google/protobuf/AbstractProto3SchemaTest.java \ + java/core/src/test/java/com/google/protobuf/AbstractSchemaTest.java \ java/core/src/test/java/com/google/protobuf/AnyTest.java \ + java/core/src/test/java/com/google/protobuf/ArrayDecodersTest.java \ + java/core/src/test/java/com/google/protobuf/BinaryProtocolTest.java \ java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java \ java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java \ java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java \ java/core/src/test/java/com/google/protobuf/ByteStringTest.java \ + java/core/src/test/java/com/google/protobuf/CachedFieldSizeTest.java \ java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java \ + java/core/src/test/java/com/google/protobuf/CodedAdapterTest.java \ java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java \ java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java \ java/core/src/test/java/com/google/protobuf/DecodeUtf8Test.java \ @@ -301,6 +368,9 @@ java_EXTRA_DIST= java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java \ java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java \ java/core/src/test/java/com/google/protobuf/EnumTest.java \ + java/core/src/test/java/com/google/protobuf/ExperimentalMessageFactory.java \ + java/core/src/test/java/com/google/protobuf/ExperimentalSerializationUtil.java \ + java/core/src/test/java/com/google/protobuf/ExperimentalTestDataProvider.java \ java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java \ java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java \ java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java \ @@ -315,17 +385,32 @@ java_EXTRA_DIST= java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java \ java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java \ java/core/src/test/java/com/google/protobuf/LiteEqualsAndHashTest.java \ - java/core/src/test/java/com/google/protobuf/LiteTest.java \ java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java \ java/core/src/test/java/com/google/protobuf/LongArrayListTest.java \ java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java \ java/core/src/test/java/com/google/protobuf/MapForProto2Test.java \ + java/core/src/test/java/com/google/protobuf/MapLiteTest.java \ java/core/src/test/java/com/google/protobuf/MapTest.java \ java/core/src/test/java/com/google/protobuf/MessageTest.java \ java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java \ java/core/src/test/java/com/google/protobuf/NioByteStringTest.java \ + java/core/src/test/java/com/google/protobuf/PackedFieldTest.java \ java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java \ + java/core/src/test/java/com/google/protobuf/ParserLiteTest.java \ java/core/src/test/java/com/google/protobuf/ParserTest.java \ + java/core/src/test/java/com/google/protobuf/Proto2ExtensionLookupSchemaTest.java \ + java/core/src/test/java/com/google/protobuf/Proto2LiteSchemaTest.java \ + java/core/src/test/java/com/google/protobuf/Proto2MessageFactory.java \ + java/core/src/test/java/com/google/protobuf/Proto2MessageInfoFactory.java \ + java/core/src/test/java/com/google/protobuf/Proto2MessageLiteFactory.java \ + java/core/src/test/java/com/google/protobuf/Proto2SchemaTest.java \ + java/core/src/test/java/com/google/protobuf/Proto2UnknownEnumValueTest.java \ + java/core/src/test/java/com/google/protobuf/Proto3LiteSchemaTest.java \ + java/core/src/test/java/com/google/protobuf/Proto3MessageFactory.java \ + java/core/src/test/java/com/google/protobuf/Proto3MessageInfoFactory.java \ + java/core/src/test/java/com/google/protobuf/Proto3MessageLiteFactory.java \ + java/core/src/test/java/com/google/protobuf/Proto3MessageLiteInfoFactory.java \ + java/core/src/test/java/com/google/protobuf/Proto3SchemaTest.java \ java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java \ java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java \ java/core/src/test/java/com/google/protobuf/RopeByteStringSubstringTest.java \ @@ -335,18 +420,25 @@ java_EXTRA_DIST= java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java \ java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java \ java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java \ + java/core/src/test/java/com/google/protobuf/TestSchemas.java \ + java/core/src/test/java/com/google/protobuf/TestSchemasLite.java \ java/core/src/test/java/com/google/protobuf/TestUtil.java \ java/core/src/test/java/com/google/protobuf/TestUtilLite.java \ java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java \ java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java \ java/core/src/test/java/com/google/protobuf/TextFormatTest.java \ java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java \ - java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java \ java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java \ java/core/src/test/java/com/google/protobuf/UnmodifiableLazyStringListTest.java \ + java/core/src/test/java/com/google/protobuf/Utf8Test.java \ + java/core/src/test/java/com/google/protobuf/Utf8Utils.java \ java/core/src/test/java/com/google/protobuf/WellKnownTypesTest.java \ + java/core/src/test/java/com/google/protobuf/WireFormatLiteTest.java \ java/core/src/test/java/com/google/protobuf/WireFormatTest.java \ + java/core/src/test/java/com/google/protobuf/WrappersLiteOfMethodTest.java \ + java/core/src/test/java/com/google/protobuf/WrappersOfMethodTest.java \ java/core/src/test/proto/com/google/protobuf/any_test.proto \ + java/core/src/test/proto/com/google/protobuf/cached_field_size_test.proto \ java/core/src/test/proto/com/google/protobuf/deprecated_file.proto \ java/core/src/test/proto/com/google/protobuf/field_presence_test.proto \ java/core/src/test/proto/com/google/protobuf/lazy_fields_lite.proto \ @@ -356,6 +448,7 @@ java_EXTRA_DIST= java/core/src/test/proto/com/google/protobuf/map_initialization_order_test.proto \ java/core/src/test/proto/com/google/protobuf/map_lite_test.proto \ java/core/src/test/proto/com/google/protobuf/map_test.proto \ + java/core/src/test/proto/com/google/protobuf/message_lite_extension_util_test.proto\ java/core/src/test/proto/com/google/protobuf/multiple_files_test.proto \ java/core/src/test/proto/com/google/protobuf/nested_builders_test.proto \ java/core/src/test/proto/com/google/protobuf/nested_extension.proto \ @@ -365,12 +458,26 @@ java_EXTRA_DIST= java/core/src/test/proto/com/google/protobuf/outer_class_name_test.proto \ java/core/src/test/proto/com/google/protobuf/outer_class_name_test2.proto \ java/core/src/test/proto/com/google/protobuf/outer_class_name_test3.proto \ + java/core/src/test/proto/com/google/protobuf/packed_field_test.proto \ + java/core/src/test/proto/com/google/protobuf/proto2_message.proto \ + java/core/src/test/proto/com/google/protobuf/proto2_message_lite.proto \ + java/core/src/test/proto/com/google/protobuf/proto2_unknown_enum_values.proto \ + java/core/src/test/proto/com/google/protobuf/proto3_message.proto \ + java/core/src/test/proto/com/google/protobuf/proto3_message_lite.proto \ java/core/src/test/proto/com/google/protobuf/test_bad_identifiers.proto \ java/core/src/test/proto/com/google/protobuf/test_check_utf8.proto \ java/core/src/test/proto/com/google/protobuf/test_check_utf8_size.proto \ java/core/src/test/proto/com/google/protobuf/test_custom_options.proto \ java/core/src/test/proto/com/google/protobuf/test_extra_interfaces.proto \ + java/core/src/test/proto/com/google/protobuf/wrappers_test.proto \ java/lite.md \ + java/lite/generate-sources-build.xml \ + java/lite/generate-test-sources-build.xml \ + java/lite/lite.awk \ + java/lite/pom.xml \ + java/lite/process-lite-sources-build.xml \ + java/lite/src/test/java/com/google/protobuf/LiteTest.java \ + java/lite/src/test/java/com/google/protobuf/Proto2MessageLiteInfoFactory.java \ java/pom.xml \ java/util/pom.xml \ java/util/src/main/java/com/google/protobuf/util/Durations.java \ @@ -467,6 +574,12 @@ objectivec_EXTRA_DIST= \ objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings \ objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme \ objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme \ + objectivec/ProtocolBuffers_tvOS.xcodeproj/project.pbxproj \ + objectivec/ProtocolBuffers_tvOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata \ + objectivec/ProtocolBuffers_tvOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist \ + objectivec/ProtocolBuffers_tvOS.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings \ + objectivec/ProtocolBuffers_tvOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme \ + objectivec/ProtocolBuffers_tvOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme \ objectivec/README.md \ objectivec/Tests/CocoaPods/OSXCocoaPodsTester/OSXCocoaPodsTester.xcodeproj/project.pbxproj \ objectivec/Tests/CocoaPods/OSXCocoaPodsTester/OSXCocoaPodsTester.xcodeproj/project.xcworkspace/contents.xcworkspacedata \ @@ -552,6 +665,7 @@ objectivec_EXTRA_DIST= \ objectivec/Tests/GPBUtilitiesTests.m \ objectivec/Tests/GPBWellKnownTypesTest.m \ objectivec/Tests/GPBWireFormatTests.m \ + objectivec/Tests/text_format_extensions_unittest_data.txt \ objectivec/Tests/text_format_map_unittest_data.txt \ objectivec/Tests/text_format_unittest_data.txt \ objectivec/Tests/unittest_cycle.proto \ @@ -565,6 +679,7 @@ objectivec_EXTRA_DIST= \ objectivec/Tests/unittest_extension_chain_f.proto \ objectivec/Tests/unittest_extension_chain_g.proto \ objectivec/Tests/unittest_objc.proto \ + objectivec/Tests/unittest_objc_options.proto \ objectivec/Tests/unittest_objc_startup.proto \ objectivec/Tests/unittest_runtime_proto2.proto \ objectivec/Tests/unittest_runtime_proto3.proto \ @@ -577,6 +692,7 @@ php_EXTRA_DIST= \ php/README.md \ php/composer.json \ php/ext/google/protobuf/array.c \ + php/ext/google/protobuf/builtin_descriptors.inc \ php/ext/google/protobuf/config.m4 \ php/ext/google/protobuf/def.c \ php/ext/google/protobuf/encode_decode.c \ @@ -593,6 +709,7 @@ php_EXTRA_DIST= \ php/ext/google/protobuf/utf8.h \ php/generate_descriptor_protos.sh \ php/phpunit.xml \ + php/release.sh \ php/src/GPBMetadata/Google/Protobuf/Any.php \ php/src/GPBMetadata/Google/Protobuf/Api.php \ php/src/GPBMetadata/Google/Protobuf/Duration.php \ @@ -688,6 +805,18 @@ php_EXTRA_DIST= \ php/src/Google/Protobuf/Internal/SourceCodeInfo/Location.php \ php/src/Google/Protobuf/Internal/UninterpretedOption.php \ php/src/Google/Protobuf/Internal/UninterpretedOption/NamePart.php \ + php/src/Google/Protobuf/Internal/DescriptorProto_ExtensionRange.php \ + php/src/Google/Protobuf/Internal/DescriptorProto_ReservedRange.php \ + php/src/Google/Protobuf/Internal/EnumDescriptorProto_EnumReservedRange.php \ + php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php \ + php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php \ + php/src/Google/Protobuf/Internal/FieldOptions_CType.php \ + php/src/Google/Protobuf/Internal/FieldOptions_JSType.php \ + php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php \ + php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php \ + php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php \ + php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php \ + php/src/Google/Protobuf/Internal/UninterpretedOption_NamePart.php \ php/src/Google/Protobuf/ListValue.php \ php/src/Google/Protobuf/Method.php \ php/src/Google/Protobuf/Mixin.php \ @@ -708,6 +837,7 @@ php_EXTRA_DIST= \ php/tests/autoload.php \ php/tests/bootstrap_phpunit.php \ php/tests/compatibility_test.sh \ + php/tests/compile_extension.sh \ php/tests/descriptors_test.php \ php/tests/encode_decode_test.php \ php/tests/gdb_test.sh \ @@ -734,11 +864,13 @@ php_EXTRA_DIST= \ php/tests/proto/test_reserved_message_upper.proto \ php/tests/proto/test_service.proto \ php/tests/proto/test_service_namespace.proto \ + php/tests/proto/test_wrapper_type_setters.proto \ php/tests/test.sh \ php/tests/test_base.php \ php/tests/test_util.php \ php/tests/undefined_test.php \ - php/tests/well_known_test.php + php/tests/well_known_test.php \ + php/tests/wrapper_type_setters_test.php python_EXTRA_DIST= \ python/MANIFEST.in \ @@ -763,6 +895,7 @@ python_EXTRA_DIST= \ python/google/protobuf/internal/descriptor_test.py \ python/google/protobuf/internal/encoder.py \ python/google/protobuf/internal/enum_type_wrapper.py \ + python/google/protobuf/internal/extension_dict.py \ python/google/protobuf/internal/factory_test1.proto \ python/google/protobuf/internal/factory_test2.proto \ python/google/protobuf/internal/file_options_test.proto \ @@ -771,6 +904,7 @@ python_EXTRA_DIST= \ python/google/protobuf/internal/import_test_package/inner.proto \ python/google/protobuf/internal/import_test_package/outer.proto \ python/google/protobuf/internal/json_format_test.py \ + python/google/protobuf/internal/keywords_test.py \ python/google/protobuf/internal/message_factory_test.py \ python/google/protobuf/internal/message_listener.py \ python/google/protobuf/internal/message_set_extensions.proto \ @@ -804,6 +938,7 @@ python_EXTRA_DIST= \ python/google/protobuf/message.py \ python/google/protobuf/message_factory.py \ python/google/protobuf/python_protobuf.h \ + python/google/protobuf/proto_api.h \ python/google/protobuf/proto_builder.py \ python/google/protobuf/pyext/README \ python/google/protobuf/pyext/__init__.py \ @@ -822,6 +957,10 @@ python_EXTRA_DIST= \ python/google/protobuf/pyext/map_container.h \ python/google/protobuf/pyext/message.cc \ python/google/protobuf/pyext/message.h \ + python/google/protobuf/pyext/field.cc \ + python/google/protobuf/pyext/field.h \ + python/google/protobuf/pyext/unknown_fields.cc \ + python/google/protobuf/pyext/unknown_fields.h \ python/google/protobuf/pyext/message_factory.cc \ python/google/protobuf/pyext/message_factory.h \ python/google/protobuf/pyext/message_module.cc \ @@ -833,7 +972,6 @@ python_EXTRA_DIST= \ python/google/protobuf/pyext/repeated_scalar_container.h \ python/google/protobuf/pyext/safe_numerics.h \ python/google/protobuf/pyext/scoped_pyobject_ptr.h \ - python/google/protobuf/pyext/thread_unsafe_shared_ptr.h \ python/google/protobuf/reflection.py \ python/google/protobuf/service.py \ python/google/protobuf/service_reflection.py \ @@ -899,16 +1037,25 @@ ruby_EXTRA_DIST= \ ruby/src/main/java/com/google/protobuf/jruby/Utils.java \ ruby/src/main/java/google/ProtobufJavaService.java \ ruby/src/main/sentinel.proto \ + ruby/tests/basic_proto2.rb \ + ruby/tests/basic_test_proto2.proto \ + ruby/tests/basic_test.proto \ ruby/tests/basic.rb \ + ruby/tests/common_tests.rb \ ruby/tests/encode_decode_test.rb \ ruby/tests/gc_test.rb \ ruby/tests/repeated_field_test.rb \ ruby/tests/stress.rb \ + ruby/tests/generated_code_proto2_test.rb \ + ruby/tests/generated_code_proto2.proto \ ruby/tests/generated_code.proto \ + ruby/tests/test_import_proto2.proto \ ruby/tests/test_import.proto \ + ruby/tests/test_ruby_package_proto2.proto \ ruby/tests/test_ruby_package.proto \ ruby/tests/generated_code_test.rb \ ruby/tests/well_known_types_test.rb \ + ruby/tests/type_errors.rb \ ruby/travis-test.sh js_EXTRA_DIST= \ @@ -933,6 +1080,7 @@ js_EXTRA_DIST= \ js/commonjs/import_test.js \ js/commonjs/jasmine.json \ js/commonjs/rewrite_tests_for_commonjs.js \ + js/commonjs/strict_test.js \ js/commonjs/test6/test6.proto \ js/commonjs/test7/test7.proto \ js/compatibility_tests/v3.0.0/binary/arith_test.js \ @@ -1004,6 +1152,13 @@ js_EXTRA_DIST= \ js/test4.proto \ js/test5.proto \ js/test8.proto \ + js/test9.proto \ + js/test10.proto \ + js/test11.proto \ + js/test12.proto \ + js/test13.proto \ + js/test14.proto \ + js/test15.proto \ js/test_bootstrap.js \ js/testbinary.proto \ js/testempty.proto @@ -1022,6 +1177,7 @@ EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \ WORKSPACE \ cmake/CMakeLists.txt \ cmake/README.md \ + cmake/conformance.cmake \ cmake/examples.cmake \ cmake/extract_includes.bat.in \ cmake/install.cmake \ @@ -1036,6 +1192,8 @@ EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \ cmake/protobuf.pc.cmake \ cmake/protoc.cmake \ cmake/tests.cmake \ + cmake/version.rc.in \ + compiler_config_setting.bzl \ editors/README.txt \ editors/proto.vim \ editors/protobuf-mode.el \ @@ -1047,20 +1205,25 @@ EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \ examples/README.md \ examples/WORKSPACE \ examples/add_person.cc \ + examples/add_person.dart \ examples/add_person.go \ examples/add_person.py \ examples/add_person_test.go \ examples/addressbook.proto \ examples/list_people.cc \ + examples/list_people.dart \ examples/list_people.go \ examples/list_people.py \ examples/list_people_test.go \ + examples/pubspec.yaml \ + examples/third_party/zlib.BUILD \ protobuf.bzl \ python/release/wheel/build_wheel_manylinux.sh \ python/release/wheel/Dockerfile \ python/release/wheel/protobuf_optimized_pip.sh \ python/release/wheel/README.md \ six.BUILD \ + third_party/zlib.BUILD \ util/python/BUILD diff --git a/third_party/protobuf/Makefile.in b/third_party/protobuf/Makefile.in index 87c28a0f..afdb780e 100644 --- a/third_party/protobuf/Makefile.in +++ b/third_party/protobuf/Makefile.in @@ -291,6 +291,7 @@ ISAINFO = @ISAINFO@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_FOR_BUILD = @LDFLAGS_FOR_BUILD@ +LIBATOMIC_LIBS = @LIBATOMIC_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ @@ -406,15 +407,18 @@ DIST_SUBDIRS = src conformance benchmarks third_party/googletest pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = protobuf.pc protobuf-lite.pc csharp_EXTRA_DIST = \ + global.json \ csharp/.gitignore \ csharp/CHANGES.txt \ + csharp/Google.Protobuf.Tools.targets \ csharp/Google.Protobuf.Tools.nuspec \ csharp/README.md \ csharp/build_packages.bat \ csharp/build_tools.sh \ + csharp/buildall.bat \ csharp/buildall.sh \ csharp/generate_protos.sh \ - csharp/global.json \ + csharp/install_dotnet_sdk.ps1 \ csharp/keys/Google.Protobuf.public.snk \ csharp/keys/Google.Protobuf.snk \ csharp/keys/README.md \ @@ -431,6 +435,12 @@ csharp_EXTRA_DIST = \ csharp/src/AddressBook/ListPeople.cs \ csharp/src/AddressBook/Program.cs \ csharp/src/AddressBook/SampleUsage.cs \ + csharp/src/Google.Protobuf.Benchmarks/SerializationConfig.cs \ + csharp/src/Google.Protobuf.Benchmarks/SerializationBenchmark.cs \ + csharp/src/Google.Protobuf.Benchmarks/Program.cs \ + csharp/src/Google.Protobuf.Benchmarks/Google.Protobuf.Benchmarks.csproj \ + csharp/src/Google.Protobuf.Benchmarks/Benchmarks.cs \ + csharp/src/Google.Protobuf.Benchmarks/BenchmarkMessage1Proto3.cs \ csharp/src/Google.Protobuf.Conformance/Conformance.cs \ csharp/src/Google.Protobuf.Conformance/Google.Protobuf.Conformance.csproj \ csharp/src/Google.Protobuf.Conformance/Program.cs \ @@ -449,6 +459,7 @@ csharp_EXTRA_DIST = \ csharp/src/Google.Protobuf.Test/DeprecatedMemberTest.cs \ csharp/src/Google.Protobuf.Test/EqualityTester.cs \ csharp/src/Google.Protobuf.Test/FieldCodecTest.cs \ + csharp/src/Google.Protobuf.Test/FieldMaskTreeTest.cs \ csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs \ csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj \ csharp/src/Google.Protobuf.Test/IssuesTest.cs \ @@ -456,6 +467,7 @@ csharp_EXTRA_DIST = \ csharp/src/Google.Protobuf.Test/JsonParserTest.cs \ csharp/src/Google.Protobuf.Test/JsonTokenizerTest.cs \ csharp/src/Google.Protobuf.Test/Reflection/CustomOptionsTest.cs \ + csharp/src/Google.Protobuf.Test/Reflection/DescriptorDeclarationTest.cs \ csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs \ csharp/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs \ csharp/src/Google.Protobuf.Test/Reflection/TypeRegistryTest.cs \ @@ -478,6 +490,7 @@ csharp_EXTRA_DIST = \ csharp/src/Google.Protobuf.Test/WellKnownTypes/TimestampTest.cs \ csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs \ csharp/src/Google.Protobuf.Test/UnknownFieldSetTest.cs \ + csharp/src/Google.Protobuf.Test/testprotos.pb \ csharp/src/Google.Protobuf.sln \ csharp/src/Google.Protobuf/ByteArray.cs \ csharp/src/Google.Protobuf/ByteString.cs \ @@ -494,6 +507,7 @@ csharp_EXTRA_DIST = \ csharp/src/Google.Protobuf/Compatibility/StreamExtensions.cs \ csharp/src/Google.Protobuf/Compatibility/TypeExtensions.cs \ csharp/src/Google.Protobuf/FieldCodec.cs \ + csharp/src/Google.Protobuf/FieldMaskTree.cs \ csharp/src/Google.Protobuf/FrameworkPortability.cs \ csharp/src/Google.Protobuf/Google.Protobuf.csproj \ csharp/src/Google.Protobuf/ICustomDiagnosticMessage.cs \ @@ -513,6 +527,7 @@ csharp_EXTRA_DIST = \ csharp/src/Google.Protobuf/Reflection/CustomOptions.cs \ csharp/src/Google.Protobuf/Reflection/Descriptor.cs \ csharp/src/Google.Protobuf/Reflection/DescriptorBase.cs \ + csharp/src/Google.Protobuf/Reflection/DescriptorDeclaration.cs \ csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs \ csharp/src/Google.Protobuf/Reflection/DescriptorUtil.cs \ csharp/src/Google.Protobuf/Reflection/DescriptorValidationException.cs \ @@ -532,7 +547,6 @@ csharp_EXTRA_DIST = \ csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs \ csharp/src/Google.Protobuf/Reflection/OriginalNameAttribute.cs \ csharp/src/Google.Protobuf/Reflection/PackageDescriptor.cs \ - csharp/src/Google.Protobuf/Reflection/PartialClasses.cs \ csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs \ csharp/src/Google.Protobuf/Reflection/RepeatedFieldAccessor.cs \ csharp/src/Google.Protobuf/Reflection/ServiceDescriptor.cs \ @@ -561,6 +575,7 @@ csharp_EXTRA_DIST = \ java_EXTRA_DIST = \ java/README.md \ + java/bom/pom.xml \ java/core/generate-sources-build.xml \ java/core/generate-test-sources-build.xml \ java/core/pom.xml \ @@ -568,17 +583,25 @@ java_EXTRA_DIST = \ java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java \ java/core/src/main/java/com/google/protobuf/AbstractParser.java \ java/core/src/main/java/com/google/protobuf/AbstractProtobufList.java \ + java/core/src/main/java/com/google/protobuf/AllocatedBuffer.java \ java/core/src/main/java/com/google/protobuf/Android.java \ + java/core/src/main/java/com/google/protobuf/ArrayDecoders.java \ + java/core/src/main/java/com/google/protobuf/BinaryReader.java \ + java/core/src/main/java/com/google/protobuf/BinaryWriter.java \ java/core/src/main/java/com/google/protobuf/BlockingRpcChannel.java \ java/core/src/main/java/com/google/protobuf/BlockingService.java \ java/core/src/main/java/com/google/protobuf/BooleanArrayList.java \ + java/core/src/main/java/com/google/protobuf/BufferAllocator.java \ java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java \ java/core/src/main/java/com/google/protobuf/ByteOutput.java \ java/core/src/main/java/com/google/protobuf/ByteString.java \ java/core/src/main/java/com/google/protobuf/CodedInputStream.java \ + java/core/src/main/java/com/google/protobuf/CodedInputStreamReader.java \ java/core/src/main/java/com/google/protobuf/CodedOutputStream.java \ - java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java \ + java/core/src/main/java/com/google/protobuf/CodedOutputStreamWriter.java \ + java/core/src/main/java/com/google/protobuf/DescriptorMessageInfoFactory.java \ java/core/src/main/java/com/google/protobuf/Descriptors.java \ + java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java \ java/core/src/main/java/com/google/protobuf/DoubleArrayList.java \ java/core/src/main/java/com/google/protobuf/DynamicMessage.java \ java/core/src/main/java/com/google/protobuf/ExperimentalApi.java \ @@ -587,37 +610,65 @@ java_EXTRA_DIST = \ java/core/src/main/java/com/google/protobuf/ExtensionRegistry.java \ java/core/src/main/java/com/google/protobuf/ExtensionRegistryFactory.java \ java/core/src/main/java/com/google/protobuf/ExtensionRegistryLite.java \ + java/core/src/main/java/com/google/protobuf/ExtensionSchema.java \ + java/core/src/main/java/com/google/protobuf/ExtensionSchemaFull.java \ + java/core/src/main/java/com/google/protobuf/ExtensionSchemaLite.java \ + java/core/src/main/java/com/google/protobuf/ExtensionSchemas.java \ + java/core/src/main/java/com/google/protobuf/FieldInfo.java \ java/core/src/main/java/com/google/protobuf/FieldSet.java \ + java/core/src/main/java/com/google/protobuf/FieldType.java \ java/core/src/main/java/com/google/protobuf/FloatArrayList.java \ java/core/src/main/java/com/google/protobuf/GeneratedMessage.java \ + java/core/src/main/java/com/google/protobuf/GeneratedMessageInfoFactory.java \ java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java \ java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java \ java/core/src/main/java/com/google/protobuf/IntArrayList.java \ java/core/src/main/java/com/google/protobuf/Internal.java \ java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java \ java/core/src/main/java/com/google/protobuf/IterableByteBufferInputStream.java \ + java/core/src/main/java/com/google/protobuf/JavaType.java \ java/core/src/main/java/com/google/protobuf/LazyField.java \ java/core/src/main/java/com/google/protobuf/LazyFieldLite.java \ java/core/src/main/java/com/google/protobuf/LazyStringArrayList.java \ java/core/src/main/java/com/google/protobuf/LazyStringList.java \ + java/core/src/main/java/com/google/protobuf/ListFieldSchema.java \ java/core/src/main/java/com/google/protobuf/LongArrayList.java \ + java/core/src/main/java/com/google/protobuf/ManifestSchemaFactory.java \ java/core/src/main/java/com/google/protobuf/MapEntry.java \ java/core/src/main/java/com/google/protobuf/MapEntryLite.java \ java/core/src/main/java/com/google/protobuf/MapField.java \ java/core/src/main/java/com/google/protobuf/MapFieldLite.java \ + java/core/src/main/java/com/google/protobuf/MapFieldSchema.java \ + java/core/src/main/java/com/google/protobuf/MapFieldSchemaFull.java \ + java/core/src/main/java/com/google/protobuf/MapFieldSchemaLite.java \ + java/core/src/main/java/com/google/protobuf/MapFieldSchemas.java \ java/core/src/main/java/com/google/protobuf/Message.java \ + java/core/src/main/java/com/google/protobuf/MessageInfo.java \ + java/core/src/main/java/com/google/protobuf/MessageInfoFactory.java \ java/core/src/main/java/com/google/protobuf/MessageLite.java \ java/core/src/main/java/com/google/protobuf/MessageLiteOrBuilder.java \ java/core/src/main/java/com/google/protobuf/MessageLiteToString.java \ java/core/src/main/java/com/google/protobuf/MessageOrBuilder.java \ java/core/src/main/java/com/google/protobuf/MessageReflection.java \ + java/core/src/main/java/com/google/protobuf/MessageSchema.java \ + java/core/src/main/java/com/google/protobuf/MessageSetSchema.java \ java/core/src/main/java/com/google/protobuf/MutabilityOracle.java \ + java/core/src/main/java/com/google/protobuf/NewInstanceSchema.java \ + java/core/src/main/java/com/google/protobuf/NewInstanceSchemaFull.java \ + java/core/src/main/java/com/google/protobuf/NewInstanceSchemaLite.java \ + java/core/src/main/java/com/google/protobuf/NewInstanceSchemas.java \ java/core/src/main/java/com/google/protobuf/NioByteString.java \ + java/core/src/main/java/com/google/protobuf/OneofInfo.java \ java/core/src/main/java/com/google/protobuf/Parser.java \ java/core/src/main/java/com/google/protobuf/PrimitiveNonBoxingCollection.java \ + java/core/src/main/java/com/google/protobuf/ProtoSyntax.java \ + java/core/src/main/java/com/google/protobuf/Protobuf.java \ java/core/src/main/java/com/google/protobuf/ProtobufArrayList.java \ + java/core/src/main/java/com/google/protobuf/ProtobufLists.java \ java/core/src/main/java/com/google/protobuf/ProtocolMessageEnum.java \ java/core/src/main/java/com/google/protobuf/ProtocolStringList.java \ + java/core/src/main/java/com/google/protobuf/RawMessageInfo.java \ + java/core/src/main/java/com/google/protobuf/Reader.java \ java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilder.java \ java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java \ java/core/src/main/java/com/google/protobuf/RopeByteString.java \ @@ -625,30 +676,47 @@ java_EXTRA_DIST = \ java/core/src/main/java/com/google/protobuf/RpcChannel.java \ java/core/src/main/java/com/google/protobuf/RpcController.java \ java/core/src/main/java/com/google/protobuf/RpcUtil.java \ + java/core/src/main/java/com/google/protobuf/Schema.java \ + java/core/src/main/java/com/google/protobuf/SchemaFactory.java \ + java/core/src/main/java/com/google/protobuf/SchemaUtil.java \ java/core/src/main/java/com/google/protobuf/Service.java \ java/core/src/main/java/com/google/protobuf/ServiceException.java \ java/core/src/main/java/com/google/protobuf/SingleFieldBuilder.java \ java/core/src/main/java/com/google/protobuf/SingleFieldBuilderV3.java \ java/core/src/main/java/com/google/protobuf/SmallSortedMap.java \ + java/core/src/main/java/com/google/protobuf/StructuralMessageInfo.java \ java/core/src/main/java/com/google/protobuf/TextFormat.java \ java/core/src/main/java/com/google/protobuf/TextFormatEscaper.java \ java/core/src/main/java/com/google/protobuf/TextFormatParseInfoTree.java \ java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java \ java/core/src/main/java/com/google/protobuf/UninitializedMessageException.java \ + java/core/src/main/java/com/google/protobuf/UnknownFieldSchema.java \ java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java \ java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java \ + java/core/src/main/java/com/google/protobuf/UnknownFieldSetLiteSchema.java \ + java/core/src/main/java/com/google/protobuf/UnknownFieldSetSchema.java \ java/core/src/main/java/com/google/protobuf/UnmodifiableLazyStringList.java \ java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java \ java/core/src/main/java/com/google/protobuf/UnsafeUtil.java \ java/core/src/main/java/com/google/protobuf/Utf8.java \ java/core/src/main/java/com/google/protobuf/WireFormat.java \ + java/core/src/main/java/com/google/protobuf/Writer.java \ java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java \ + java/core/src/test/java/com/google/protobuf/AbstractProto2LiteSchemaTest.java \ + java/core/src/test/java/com/google/protobuf/AbstractProto2SchemaTest.java \ + java/core/src/test/java/com/google/protobuf/AbstractProto3LiteSchemaTest.java \ + java/core/src/test/java/com/google/protobuf/AbstractProto3SchemaTest.java \ + java/core/src/test/java/com/google/protobuf/AbstractSchemaTest.java \ java/core/src/test/java/com/google/protobuf/AnyTest.java \ + java/core/src/test/java/com/google/protobuf/ArrayDecodersTest.java \ + java/core/src/test/java/com/google/protobuf/BinaryProtocolTest.java \ java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java \ java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java \ java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java \ java/core/src/test/java/com/google/protobuf/ByteStringTest.java \ + java/core/src/test/java/com/google/protobuf/CachedFieldSizeTest.java \ java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java \ + java/core/src/test/java/com/google/protobuf/CodedAdapterTest.java \ java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java \ java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java \ java/core/src/test/java/com/google/protobuf/DecodeUtf8Test.java \ @@ -658,6 +726,9 @@ java_EXTRA_DIST = \ java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java \ java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java \ java/core/src/test/java/com/google/protobuf/EnumTest.java \ + java/core/src/test/java/com/google/protobuf/ExperimentalMessageFactory.java \ + java/core/src/test/java/com/google/protobuf/ExperimentalSerializationUtil.java \ + java/core/src/test/java/com/google/protobuf/ExperimentalTestDataProvider.java \ java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java \ java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java \ java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java \ @@ -672,17 +743,32 @@ java_EXTRA_DIST = \ java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java \ java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java \ java/core/src/test/java/com/google/protobuf/LiteEqualsAndHashTest.java \ - java/core/src/test/java/com/google/protobuf/LiteTest.java \ java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java \ java/core/src/test/java/com/google/protobuf/LongArrayListTest.java \ java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java \ java/core/src/test/java/com/google/protobuf/MapForProto2Test.java \ + java/core/src/test/java/com/google/protobuf/MapLiteTest.java \ java/core/src/test/java/com/google/protobuf/MapTest.java \ java/core/src/test/java/com/google/protobuf/MessageTest.java \ java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java \ java/core/src/test/java/com/google/protobuf/NioByteStringTest.java \ + java/core/src/test/java/com/google/protobuf/PackedFieldTest.java \ java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java \ + java/core/src/test/java/com/google/protobuf/ParserLiteTest.java \ java/core/src/test/java/com/google/protobuf/ParserTest.java \ + java/core/src/test/java/com/google/protobuf/Proto2ExtensionLookupSchemaTest.java \ + java/core/src/test/java/com/google/protobuf/Proto2LiteSchemaTest.java \ + java/core/src/test/java/com/google/protobuf/Proto2MessageFactory.java \ + java/core/src/test/java/com/google/protobuf/Proto2MessageInfoFactory.java \ + java/core/src/test/java/com/google/protobuf/Proto2MessageLiteFactory.java \ + java/core/src/test/java/com/google/protobuf/Proto2SchemaTest.java \ + java/core/src/test/java/com/google/protobuf/Proto2UnknownEnumValueTest.java \ + java/core/src/test/java/com/google/protobuf/Proto3LiteSchemaTest.java \ + java/core/src/test/java/com/google/protobuf/Proto3MessageFactory.java \ + java/core/src/test/java/com/google/protobuf/Proto3MessageInfoFactory.java \ + java/core/src/test/java/com/google/protobuf/Proto3MessageLiteFactory.java \ + java/core/src/test/java/com/google/protobuf/Proto3MessageLiteInfoFactory.java \ + java/core/src/test/java/com/google/protobuf/Proto3SchemaTest.java \ java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java \ java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java \ java/core/src/test/java/com/google/protobuf/RopeByteStringSubstringTest.java \ @@ -692,18 +778,25 @@ java_EXTRA_DIST = \ java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java \ java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java \ java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java \ + java/core/src/test/java/com/google/protobuf/TestSchemas.java \ + java/core/src/test/java/com/google/protobuf/TestSchemasLite.java \ java/core/src/test/java/com/google/protobuf/TestUtil.java \ java/core/src/test/java/com/google/protobuf/TestUtilLite.java \ java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java \ java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java \ java/core/src/test/java/com/google/protobuf/TextFormatTest.java \ java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java \ - java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java \ java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java \ java/core/src/test/java/com/google/protobuf/UnmodifiableLazyStringListTest.java \ + java/core/src/test/java/com/google/protobuf/Utf8Test.java \ + java/core/src/test/java/com/google/protobuf/Utf8Utils.java \ java/core/src/test/java/com/google/protobuf/WellKnownTypesTest.java \ + java/core/src/test/java/com/google/protobuf/WireFormatLiteTest.java \ java/core/src/test/java/com/google/protobuf/WireFormatTest.java \ + java/core/src/test/java/com/google/protobuf/WrappersLiteOfMethodTest.java \ + java/core/src/test/java/com/google/protobuf/WrappersOfMethodTest.java \ java/core/src/test/proto/com/google/protobuf/any_test.proto \ + java/core/src/test/proto/com/google/protobuf/cached_field_size_test.proto \ java/core/src/test/proto/com/google/protobuf/deprecated_file.proto \ java/core/src/test/proto/com/google/protobuf/field_presence_test.proto \ java/core/src/test/proto/com/google/protobuf/lazy_fields_lite.proto \ @@ -713,6 +806,7 @@ java_EXTRA_DIST = \ java/core/src/test/proto/com/google/protobuf/map_initialization_order_test.proto \ java/core/src/test/proto/com/google/protobuf/map_lite_test.proto \ java/core/src/test/proto/com/google/protobuf/map_test.proto \ + java/core/src/test/proto/com/google/protobuf/message_lite_extension_util_test.proto\ java/core/src/test/proto/com/google/protobuf/multiple_files_test.proto \ java/core/src/test/proto/com/google/protobuf/nested_builders_test.proto \ java/core/src/test/proto/com/google/protobuf/nested_extension.proto \ @@ -722,12 +816,26 @@ java_EXTRA_DIST = \ java/core/src/test/proto/com/google/protobuf/outer_class_name_test.proto \ java/core/src/test/proto/com/google/protobuf/outer_class_name_test2.proto \ java/core/src/test/proto/com/google/protobuf/outer_class_name_test3.proto \ + java/core/src/test/proto/com/google/protobuf/packed_field_test.proto \ + java/core/src/test/proto/com/google/protobuf/proto2_message.proto \ + java/core/src/test/proto/com/google/protobuf/proto2_message_lite.proto \ + java/core/src/test/proto/com/google/protobuf/proto2_unknown_enum_values.proto \ + java/core/src/test/proto/com/google/protobuf/proto3_message.proto \ + java/core/src/test/proto/com/google/protobuf/proto3_message_lite.proto \ java/core/src/test/proto/com/google/protobuf/test_bad_identifiers.proto \ java/core/src/test/proto/com/google/protobuf/test_check_utf8.proto \ java/core/src/test/proto/com/google/protobuf/test_check_utf8_size.proto \ java/core/src/test/proto/com/google/protobuf/test_custom_options.proto \ java/core/src/test/proto/com/google/protobuf/test_extra_interfaces.proto \ + java/core/src/test/proto/com/google/protobuf/wrappers_test.proto \ java/lite.md \ + java/lite/generate-sources-build.xml \ + java/lite/generate-test-sources-build.xml \ + java/lite/lite.awk \ + java/lite/pom.xml \ + java/lite/process-lite-sources-build.xml \ + java/lite/src/test/java/com/google/protobuf/LiteTest.java \ + java/lite/src/test/java/com/google/protobuf/Proto2MessageLiteInfoFactory.java \ java/pom.xml \ java/util/pom.xml \ java/util/src/main/java/com/google/protobuf/util/Durations.java \ @@ -824,6 +932,12 @@ objectivec_EXTRA_DIST = \ objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings \ objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme \ objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme \ + objectivec/ProtocolBuffers_tvOS.xcodeproj/project.pbxproj \ + objectivec/ProtocolBuffers_tvOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata \ + objectivec/ProtocolBuffers_tvOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist \ + objectivec/ProtocolBuffers_tvOS.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings \ + objectivec/ProtocolBuffers_tvOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme \ + objectivec/ProtocolBuffers_tvOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme \ objectivec/README.md \ objectivec/Tests/CocoaPods/OSXCocoaPodsTester/OSXCocoaPodsTester.xcodeproj/project.pbxproj \ objectivec/Tests/CocoaPods/OSXCocoaPodsTester/OSXCocoaPodsTester.xcodeproj/project.xcworkspace/contents.xcworkspacedata \ @@ -909,6 +1023,7 @@ objectivec_EXTRA_DIST = \ objectivec/Tests/GPBUtilitiesTests.m \ objectivec/Tests/GPBWellKnownTypesTest.m \ objectivec/Tests/GPBWireFormatTests.m \ + objectivec/Tests/text_format_extensions_unittest_data.txt \ objectivec/Tests/text_format_map_unittest_data.txt \ objectivec/Tests/text_format_unittest_data.txt \ objectivec/Tests/unittest_cycle.proto \ @@ -922,6 +1037,7 @@ objectivec_EXTRA_DIST = \ objectivec/Tests/unittest_extension_chain_f.proto \ objectivec/Tests/unittest_extension_chain_g.proto \ objectivec/Tests/unittest_objc.proto \ + objectivec/Tests/unittest_objc_options.proto \ objectivec/Tests/unittest_objc_startup.proto \ objectivec/Tests/unittest_runtime_proto2.proto \ objectivec/Tests/unittest_runtime_proto3.proto \ @@ -934,6 +1050,7 @@ php_EXTRA_DIST = \ php/README.md \ php/composer.json \ php/ext/google/protobuf/array.c \ + php/ext/google/protobuf/builtin_descriptors.inc \ php/ext/google/protobuf/config.m4 \ php/ext/google/protobuf/def.c \ php/ext/google/protobuf/encode_decode.c \ @@ -950,6 +1067,7 @@ php_EXTRA_DIST = \ php/ext/google/protobuf/utf8.h \ php/generate_descriptor_protos.sh \ php/phpunit.xml \ + php/release.sh \ php/src/GPBMetadata/Google/Protobuf/Any.php \ php/src/GPBMetadata/Google/Protobuf/Api.php \ php/src/GPBMetadata/Google/Protobuf/Duration.php \ @@ -1045,6 +1163,18 @@ php_EXTRA_DIST = \ php/src/Google/Protobuf/Internal/SourceCodeInfo/Location.php \ php/src/Google/Protobuf/Internal/UninterpretedOption.php \ php/src/Google/Protobuf/Internal/UninterpretedOption/NamePart.php \ + php/src/Google/Protobuf/Internal/DescriptorProto_ExtensionRange.php \ + php/src/Google/Protobuf/Internal/DescriptorProto_ReservedRange.php \ + php/src/Google/Protobuf/Internal/EnumDescriptorProto_EnumReservedRange.php \ + php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php \ + php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php \ + php/src/Google/Protobuf/Internal/FieldOptions_CType.php \ + php/src/Google/Protobuf/Internal/FieldOptions_JSType.php \ + php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php \ + php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php \ + php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php \ + php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php \ + php/src/Google/Protobuf/Internal/UninterpretedOption_NamePart.php \ php/src/Google/Protobuf/ListValue.php \ php/src/Google/Protobuf/Method.php \ php/src/Google/Protobuf/Mixin.php \ @@ -1065,6 +1195,7 @@ php_EXTRA_DIST = \ php/tests/autoload.php \ php/tests/bootstrap_phpunit.php \ php/tests/compatibility_test.sh \ + php/tests/compile_extension.sh \ php/tests/descriptors_test.php \ php/tests/encode_decode_test.php \ php/tests/gdb_test.sh \ @@ -1091,11 +1222,13 @@ php_EXTRA_DIST = \ php/tests/proto/test_reserved_message_upper.proto \ php/tests/proto/test_service.proto \ php/tests/proto/test_service_namespace.proto \ + php/tests/proto/test_wrapper_type_setters.proto \ php/tests/test.sh \ php/tests/test_base.php \ php/tests/test_util.php \ php/tests/undefined_test.php \ - php/tests/well_known_test.php + php/tests/well_known_test.php \ + php/tests/wrapper_type_setters_test.php python_EXTRA_DIST = \ python/MANIFEST.in \ @@ -1120,6 +1253,7 @@ python_EXTRA_DIST = \ python/google/protobuf/internal/descriptor_test.py \ python/google/protobuf/internal/encoder.py \ python/google/protobuf/internal/enum_type_wrapper.py \ + python/google/protobuf/internal/extension_dict.py \ python/google/protobuf/internal/factory_test1.proto \ python/google/protobuf/internal/factory_test2.proto \ python/google/protobuf/internal/file_options_test.proto \ @@ -1128,6 +1262,7 @@ python_EXTRA_DIST = \ python/google/protobuf/internal/import_test_package/inner.proto \ python/google/protobuf/internal/import_test_package/outer.proto \ python/google/protobuf/internal/json_format_test.py \ + python/google/protobuf/internal/keywords_test.py \ python/google/protobuf/internal/message_factory_test.py \ python/google/protobuf/internal/message_listener.py \ python/google/protobuf/internal/message_set_extensions.proto \ @@ -1161,6 +1296,7 @@ python_EXTRA_DIST = \ python/google/protobuf/message.py \ python/google/protobuf/message_factory.py \ python/google/protobuf/python_protobuf.h \ + python/google/protobuf/proto_api.h \ python/google/protobuf/proto_builder.py \ python/google/protobuf/pyext/README \ python/google/protobuf/pyext/__init__.py \ @@ -1179,6 +1315,10 @@ python_EXTRA_DIST = \ python/google/protobuf/pyext/map_container.h \ python/google/protobuf/pyext/message.cc \ python/google/protobuf/pyext/message.h \ + python/google/protobuf/pyext/field.cc \ + python/google/protobuf/pyext/field.h \ + python/google/protobuf/pyext/unknown_fields.cc \ + python/google/protobuf/pyext/unknown_fields.h \ python/google/protobuf/pyext/message_factory.cc \ python/google/protobuf/pyext/message_factory.h \ python/google/protobuf/pyext/message_module.cc \ @@ -1190,7 +1330,6 @@ python_EXTRA_DIST = \ python/google/protobuf/pyext/repeated_scalar_container.h \ python/google/protobuf/pyext/safe_numerics.h \ python/google/protobuf/pyext/scoped_pyobject_ptr.h \ - python/google/protobuf/pyext/thread_unsafe_shared_ptr.h \ python/google/protobuf/reflection.py \ python/google/protobuf/service.py \ python/google/protobuf/service_reflection.py \ @@ -1256,16 +1395,25 @@ ruby_EXTRA_DIST = \ ruby/src/main/java/com/google/protobuf/jruby/Utils.java \ ruby/src/main/java/google/ProtobufJavaService.java \ ruby/src/main/sentinel.proto \ + ruby/tests/basic_proto2.rb \ + ruby/tests/basic_test_proto2.proto \ + ruby/tests/basic_test.proto \ ruby/tests/basic.rb \ + ruby/tests/common_tests.rb \ ruby/tests/encode_decode_test.rb \ ruby/tests/gc_test.rb \ ruby/tests/repeated_field_test.rb \ ruby/tests/stress.rb \ + ruby/tests/generated_code_proto2_test.rb \ + ruby/tests/generated_code_proto2.proto \ ruby/tests/generated_code.proto \ + ruby/tests/test_import_proto2.proto \ ruby/tests/test_import.proto \ + ruby/tests/test_ruby_package_proto2.proto \ ruby/tests/test_ruby_package.proto \ ruby/tests/generated_code_test.rb \ ruby/tests/well_known_types_test.rb \ + ruby/tests/type_errors.rb \ ruby/travis-test.sh js_EXTRA_DIST = \ @@ -1290,6 +1438,7 @@ js_EXTRA_DIST = \ js/commonjs/import_test.js \ js/commonjs/jasmine.json \ js/commonjs/rewrite_tests_for_commonjs.js \ + js/commonjs/strict_test.js \ js/commonjs/test6/test6.proto \ js/commonjs/test7/test7.proto \ js/compatibility_tests/v3.0.0/binary/arith_test.js \ @@ -1361,6 +1510,13 @@ js_EXTRA_DIST = \ js/test4.proto \ js/test5.proto \ js/test8.proto \ + js/test9.proto \ + js/test10.proto \ + js/test11.proto \ + js/test12.proto \ + js/test13.proto \ + js/test14.proto \ + js/test15.proto \ js/test_bootstrap.js \ js/testbinary.proto \ js/testempty.proto @@ -1378,6 +1534,7 @@ EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \ WORKSPACE \ cmake/CMakeLists.txt \ cmake/README.md \ + cmake/conformance.cmake \ cmake/examples.cmake \ cmake/extract_includes.bat.in \ cmake/install.cmake \ @@ -1392,6 +1549,8 @@ EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \ cmake/protobuf.pc.cmake \ cmake/protoc.cmake \ cmake/tests.cmake \ + cmake/version.rc.in \ + compiler_config_setting.bzl \ editors/README.txt \ editors/proto.vim \ editors/protobuf-mode.el \ @@ -1403,20 +1562,25 @@ EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \ examples/README.md \ examples/WORKSPACE \ examples/add_person.cc \ + examples/add_person.dart \ examples/add_person.go \ examples/add_person.py \ examples/add_person_test.go \ examples/addressbook.proto \ examples/list_people.cc \ + examples/list_people.dart \ examples/list_people.go \ examples/list_people.py \ examples/list_people_test.go \ + examples/pubspec.yaml \ + examples/third_party/zlib.BUILD \ protobuf.bzl \ python/release/wheel/build_wheel_manylinux.sh \ python/release/wheel/Dockerfile \ python/release/wheel/protobuf_optimized_pip.sh \ python/release/wheel/README.md \ six.BUILD \ + third_party/zlib.BUILD \ util/python/BUILD diff --git a/third_party/protobuf/README.md b/third_party/protobuf/README.md index 1a45ee60..049b8cc9 100644 --- a/third_party/protobuf/README.md +++ b/third_party/protobuf/README.md @@ -26,7 +26,7 @@ with the C++ runtime. For non-C++ users, the simplest way to install the protocol compiler is to download a pre-built binary from our release page: - [https://github.com/google/protobuf/releases](https://github.com/google/protobuf/releases) + [https://github.com/protocolbuffers/protobuf/releases](https://github.com/protocolbuffers/protobuf/releases) In the downloads section of each release, you can find pre-built binaries in zip packages: protoc-$VERSION-$PLATFORM.zip. It contains the protoc binary @@ -54,16 +54,16 @@ how to install protobuf runtime for that specific language: | Language | Source | Ubuntu | MacOS | Windows | |--------------------------------------|-------------------------------------------------------------|--------|-------|---------| -| C++ (include C++ runtime and protoc) | [src](src) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-cpp_distcheck.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fcpp_distcheck%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-cpp_distcheck.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp_distcheck%2Fcontinuous) | [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf) | +| C++ (include C++ runtime and protoc) | [src](src) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-cpp_distcheck.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fcpp_distcheck%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-bazel.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fbazel%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-dist_install.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fdist_install%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-cpp_distcheck.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp_distcheck%2Fcontinuous) | [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf) | | Java | [java](java) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-java_compatibility.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjava_compatibility%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-java_jdk7.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjava_jdk7%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-java_oracle7.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjava_oracle7%2Fcontinuous) | | | -| Python | [python](python) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python_compatibility.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython_compatibility%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python_cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython_cpp%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-python.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-python_cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython_cpp%2Fcontinuous) | | +| Python | [python](python) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python27.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython27%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python33.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython33%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python34.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython34%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python35.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython35%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python36.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython36%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python37.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython37%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python_compatibility.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython_compatibility%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python27_cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython27_cpp%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python33_cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython33_cpp%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python34_cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython34_cpp%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python35_cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython35_cpp%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python36_cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython36_cpp%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python37_cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython37_cpp%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python-release.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython_release%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-python.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-python_cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython_cpp%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-python-release.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython_release%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/windows-python-release.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fwindows%2Fpython_release%2Fcontinuous) | | Objective-C | [objectivec](objectivec) | | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_cocoapods_integration.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_cocoapods_integration%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_ios_debug.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_ios_debug%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_ios_release.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_ios_release%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_osx.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_osx%2Fcontinuous) | | -| C# | [csharp](csharp) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-csharp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fcsharp%2Fcontinuous) | | [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf) | +| C# | [csharp](csharp) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-csharp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fcsharp%2Fcontinuous) | | [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/windows-csharp-release.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fwindows%2Fcsharp_release%2Fcontinuous) | | JavaScript | [js](js) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-javascript.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjavascript%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-javascript.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fjavascript%2Fcontinuous) | | -| Ruby | [ruby](ruby) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-ruby_all.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fruby_all%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-ruby21.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fruby21%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-ruby22.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fruby22%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-jruby.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fjruby%2Fcontinuous) | | +| Ruby | [ruby](ruby) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-ruby23.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fruby23%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-ruby24.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fruby24%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-ruby25.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fruby25%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-ruby26.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fruby26%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-ruby-release.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fruby_release%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-ruby23.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fruby23%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-ruby24.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fruby24%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-ruby25.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fruby25%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-ruby26.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fruby26%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-ruby-release.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fruby_release%2Fcontinuous) | | | Go | [golang/protobuf](https://github.com/golang/protobuf) | | | | | PHP | [php](php) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-php_all.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fphp_all%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-32-bit.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2F32-bit%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-php5.6_mac.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fphp5.6_mac%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-php7.0_mac.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fphp7.0_mac%2Fcontinuous) | | -| Dart | [dart-lang/protobuf](https://github.com/dart-lang/protobuf) | | | | +| Dart | [dart-lang/protobuf](https://github.com/dart-lang/protobuf) | [![Build Status](https://travis-ci.org/dart-lang/protobuf.svg?branch=master)](https://travis-ci.org/dart-lang/protobuf) | | | Quick Start ----------- diff --git a/third_party/protobuf/WORKSPACE b/third_party/protobuf/WORKSPACE index 06a8a841..36876800 100644 --- a/third_party/protobuf/WORKSPACE +++ b/third_party/protobuf/WORKSPACE @@ -1,16 +1,29 @@ workspace(name = "com_google_protobuf") +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") +load("//:protobuf_deps.bzl", "protobuf_deps") + +# Load common dependencies. +protobuf_deps() + new_local_repository( name = "submodule_gmock", + build_file = "@//:third_party/googletest/BUILD.bazel", path = "third_party/googletest", - build_file = "third_party/googletest/BUILD.bazel" ) -new_http_archive( +http_archive( name = "six_archive", - build_file = "six.BUILD", + build_file = "@//:six.BUILD", sha256 = "105f8d68616f8248e24bf0e9372ef04d3cc10104f1980f54d57b2ce73a5ad56a", - url = "https://pypi.python.org/packages/source/s/six/six-1.10.0.tar.gz#md5=34eed507548117b2ab523ab14b2f8b55", + urls = ["https://pypi.python.org/packages/source/s/six/six-1.10.0.tar.gz#md5=34eed507548117b2ab523ab14b2f8b55"], +) + +http_archive( + name = "bazel_skylib", + sha256 = "bbccf674aa441c266df9894182d80de104cabd19be98be002f6d478aaa31574d", + strip_prefix = "bazel-skylib-2169ae1c374aab4a09aa90e65efe1a3aad4e279b", + urls = ["https://github.com/bazelbuild/bazel-skylib/archive/2169ae1c374aab4a09aa90e65efe1a3aad4e279b.tar.gz"], ) bind( @@ -52,3 +65,13 @@ bind( name = "gson", actual = "@gson_maven//jar", ) + +maven_jar( + name = "error_prone_annotations_maven", + artifact = "com.google.errorprone:error_prone_annotations:2.3.2", +) + +bind( + name = "error_prone_annotations", + actual = "@error_prone_annotations_maven//jar", +) diff --git a/third_party/protobuf/benchmarks/Makefile.am b/third_party/protobuf/benchmarks/Makefile.am index 3ae14ffb..42334972 100644 --- a/third_party/protobuf/benchmarks/Makefile.am +++ b/third_party/protobuf/benchmarks/Makefile.am @@ -25,6 +25,7 @@ make_tmp_dir: mkdir -p 'tmp/java/src/main/java' touch make_tmp_dir + # We have to cd to $(srcdir) before executing protoc because $(protoc_inputs) is # relative to srcdir, which may not be the same as the current directory when # building out-of-tree. @@ -36,7 +37,7 @@ protoc_middleman2: make_tmp_dir $(top_srcdir)/src/protoc$(EXEEXT) $(benchmarks_ oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --cpp_out=$$oldpwd/cpp --java_out=$$oldpwd/tmp/java/src/main/java --python_out=$$oldpwd/tmp $(benchmarks_protoc_inputs_proto2) ) touch protoc_middleman2 -all_data = $$(find $(srcdir) -type f -name "dataset.*.pb" -not -path "./tmp/*") +all_data = $$(find $$(cd $(srcdir) && pwd) -type f -name "dataset.*.pb" -not -path "$$(cd $(srcdir) && pwd)/tmp/*") ############# CPP RULES ############## @@ -90,9 +91,8 @@ $(benchmarks_protoc_outputs_proto2_header): protoc_middleman2 initialize_submodule: oldpwd=`pwd` - cd $(top_srcdir)/third_party - git submodule update --init -r - cd $(top_srcdir)/third_party/benchmark && cmake -DCMAKE_BUILD_TYPE=Release && make + cd $(top_srcdir) && git submodule update --init -r third_party/benchmark && \ + cd third_party/benchmark && cmake -DCMAKE_BUILD_TYPE=Release && make cd $$oldpwd touch initialize_submodule @@ -127,8 +127,10 @@ java_benchmark_testing_files = \ java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java javac_middleman: $(java_benchmark_testing_files) protoc_middleman protoc_middleman2 - cp -r $(srcdir)/java tmp && cd tmp/java && mvn clean compile assembly:single - cd ../.. + cp -r $(srcdir)/java tmp + mkdir -p tmp/java/lib + cp $(top_srcdir)/java/core/target/*.jar tmp/java/lib/protobuf-java.jar + cd tmp/java && mvn clean compile assembly:single -Dprotobuf.version=$(PACKAGE_VERSION) && cd ../.. @touch javac_middleman java-benchmark: javac_middleman @@ -138,10 +140,10 @@ java-benchmark: javac_middleman @echo 'conf=()' >> java-benchmark @echo 'data_files=""' >> java-benchmark @echo 'for arg in $$@; do if [[ $${arg:0:1} == "-" ]]; then conf+=($$arg); else data_files+="$$arg,"; fi; done' >> java-benchmark - @echo 'java -cp '"tmp/java/target/*.jar"' com.google.caliper.runner.CaliperMain com.google.protobuf.ProtoCaliperBenchmark -i runtime '"\\" >> java-benchmark - @echo '-b serializeToByteString,serializeToByteArray,serializeToMemoryStream,'"\\" >> java-benchmark - @echo 'deserializeFromByteString,deserializeFromByteArray,deserializeFromMemoryStream '"\\" >> java-benchmark - @echo '-DdataFile=$${data_files:0:-1} $${conf[*]}' >> java-benchmark + @echo 'java -cp '\"tmp/java/target/*:$(top_srcdir)/java/core/target/*:$(top_srcdir)/java/util/target/*\"" \\" >>java-benchmark + @echo ' com.google.caliper.runner.CaliperMain com.google.protobuf.ProtoCaliperBenchmark -i runtime '"\\" >> java-benchmark + @echo ' -b serializeToByteArray,serializeToMemoryStream,deserializeFromByteArray,deserializeFromMemoryStream '"\\" >> java-benchmark + @echo ' -DdataFile=$${data_files:0:-1} $${conf[*]}' >> java-benchmark @chmod +x java-benchmark java: protoc_middleman protoc_middleman2 java-benchmark @@ -180,8 +182,8 @@ nodist_libbenchmark_messages_la_SOURCES = \ python-pure-python-benchmark: python_add_init @echo "Writing shortcut script python-pure-python-benchmark..." @echo '#! /bin/bash' > python-pure-python-benchmark - @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-pure-python-benchmark - @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-pure-python-benchmark + @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-pure-python-benchmark + @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-pure-python-benchmark @echo export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=\'python\' >> python-pure-python-benchmark @echo cp $(srcdir)/python/py_benchmark.py tmp >> python-pure-python-benchmark @echo python tmp/py_benchmark.py '$$@' >> python-pure-python-benchmark @@ -190,8 +192,8 @@ python-pure-python-benchmark: python_add_init python-cpp-reflection-benchmark: python_add_init @echo "Writing shortcut script python-cpp-reflection-benchmark..." @echo '#! /bin/bash' > python-cpp-reflection-benchmark - @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-cpp-reflection-benchmark - @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-cpp-reflection-benchmark + @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-cpp-reflection-benchmark + @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-cpp-reflection-benchmark @echo export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=\'cpp\' >> python-cpp-reflection-benchmark @echo cp $(srcdir)/python/py_benchmark.py tmp >> python-cpp-reflection-benchmark @echo python tmp/py_benchmark.py '$$@' >> python-cpp-reflection-benchmark @@ -200,8 +202,8 @@ python-cpp-reflection-benchmark: python_add_init python-cpp-generated-code-benchmark: python_add_init libbenchmark_messages.la @echo "Writing shortcut script python-cpp-generated-code-benchmark..." @echo '#! /bin/bash' > python-cpp-generated-code-benchmark - @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-cpp-generated-code-benchmark - @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-cpp-generated-code-benchmark + @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-cpp-generated-code-benchmark + @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-cpp-generated-code-benchmark @echo export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=\'cpp\' >> python-cpp-generated-code-benchmark @echo cp $(srcdir)/python/py_benchmark.py tmp >> python-cpp-generated-code-benchmark @echo python tmp/py_benchmark.py --cpp_generated '$$@' >> python-cpp-generated-code-benchmark @@ -252,19 +254,19 @@ go_protoc_middleman: make_tmp_dir $(top_srcdir)/src/protoc$(EXEEXT) $(benchmarks oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --go_out=$$oldpwd/tmp $(benchmarks_protoc_inputs_proto2_message4) ) touch go_protoc_middleman -go-benchmark: go_protoc_middleman +go-benchmark: go_protoc_middleman @echo "Writing shortcut script go-benchmark..." @echo '#! /bin/bash' > go-benchmark @echo 'cd $(srcdir)/go' >> go-benchmark @echo 'all_data=""' >> go-benchmark @echo 'conf=()' >> go-benchmark @echo 'data_files=()' >> go-benchmark - @echo 'for arg in $$@; do if [[ $${arg:0:1} == "-" ]]; then conf+=($$arg); else data_files+=("../$$arg"); fi; done' >> go-benchmark + @echo 'for arg in $$@; do if [[ $${arg:0:1} == "-" ]]; then conf+=($$arg); else data_files+=("$$arg"); fi; done' >> go-benchmark @echo 'go test -bench=. $${conf[*]} -- $${data_files[*]}' >> go-benchmark @echo 'cd ..' >> go-benchmark @chmod +x go-benchmark -go: go_protoc_middleman go-benchmark +go: go_protoc_middleman go-benchmark ./go-benchmark $(all_data) ############# GO RULES END ############## @@ -321,9 +323,9 @@ $(cpp_no_group_benchmarks_protoc_outputs_proto2_header): cpp_no_group_protoc_mid generate_cpp_no_group_benchmark_code: cp $(srcdir)/cpp/cpp_benchmark.cc gogo/cpp_no_group/cpp_benchmark.cc sed -i -e "s/\#include \"datasets/\#include \"gogo\/cpp_no_group\/datasets/g" gogo/cpp_no_group/cpp_benchmark.cc - sed -i -e "s/\#include \"benchmarks.pb.h/\#include \"gogo\/cpp_no_group\/benchmarks.pb.h/g" gogo/cpp_no_group/cpp_benchmark.cc + sed -i -e "s/\#include \"benchmarks.pb.h/\#include \"gogo\/cpp_no_group\/benchmarks.pb.h/g" gogo/cpp_no_group/cpp_benchmark.cc touch generate_cpp_no_group_benchmark_code - + bin_PROGRAMS += cpp-no-group-benchmark cpp_no_group_benchmark_LDADD = $(top_srcdir)/src/libprotobuf.la $(top_srcdir)/third_party/benchmark/src/libbenchmark.a cpp_no_group_benchmark_SOURCES = gogo/cpp_no_group/cpp_benchmark.cc @@ -342,19 +344,19 @@ nodist_cpp_no_group_benchmark_SOURCES = \ cpp_no_group: cpp_no_group_protoc_middleman generate_gogo_data cpp-no-group-benchmark ./cpp-no-group-benchmark $(gogo_data) - + gogo_proto_middleman: protoc-gen-gogoproto mkdir -p "tmp/gogo_proto" oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I$(srcdir) -I$(top_srcdir) --plugin=protoc-gen-gogoproto --gogoproto_out=$$oldpwd/tmp/gogo_proto $(benchmarks_protoc_inputs) $(benchmarks_protoc_inputs_benchmark_wrapper) $(benchmarks_protoc_inputs_proto2) ) touch gogo_proto_middleman -new_data = $$(for data in $(all_data); do echo "tmp$${data\#$(srcdir)}"; done | xargs) +gogo_data = $$(for data in $(all_data); do echo "tmp/gogo_data$${data\#$(srcdir)}"; done | xargs) generate_gogo_data: protoc_middleman protoc_middleman2 gogo-data-scrubber - mkdir -p `dirname $(new_data)` - ./gogo-data-scrubber $(all_data) $(new_data) + mkdir -p `dirname $(gogo_data)` + ./gogo-data-scrubber $(all_data) $(gogo_data) touch generate_gogo_data - + make_tmp_dir_gogo: mkdir -p tmp/go_no_group/benchmark_code mkdir -p tmp/gogofast/benchmark_code @@ -407,8 +409,6 @@ gogoslick_protoc_middleman: make_tmp_dir_gogo $(top_srcdir)/src/protoc$(EXEEXT) oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --gogoslick_out=$$oldpwd/tmp/gogoslick $(benchmarks_protoc_inputs_proto2_message4) ) touch gogoslick_protoc_middleman -gogo_data = $$(find . -type f -name "dataset.*.pb" -path "./tmp/*") - generate-gogo-benchmark-code: @echo '#! /bin/bash' > generate-gogo-benchmark-code @echo 'cp $(srcdir)/go/go_benchmark_test.go tmp/$$1/benchmark_code/$$1_benchmark1_test.go' >> generate-gogo-benchmark-code @@ -436,10 +436,10 @@ gogo-benchmark: go_no_group: go_no_group_protoc_middleman generate_gogo_data generate_all_gogo_benchmark_code gogo-benchmark ./gogo-benchmark go_no_group $(gogo_data) - -gogofast: gogofast_protoc_middleman generate_gogo_data gogo-benchmark generate_all_gogo_benchmark_code + +gogofast: gogofast_protoc_middleman generate_gogo_data gogo-benchmark generate_all_gogo_benchmark_code ./gogo-benchmark gogofast $(gogo_data) - + gogofaster: gogofaster_protoc_middleman generate_gogo_data gogo-benchmark generate_all_gogo_benchmark_code ./gogo-benchmark gogofaster $(gogo_data) @@ -449,10 +449,10 @@ gogoslick: gogoslick_protoc_middleman generate_gogo_data gogo-benchmark generat ############# GOGO RULES END ############ - + ############ UTIL RULES BEGIN ############ -bin_PROGRAMS += protoc-gen-gogoproto gogo-data-scrubber +bin_PROGRAMS += protoc-gen-gogoproto gogo-data-scrubber protoc-gen-proto2_to_proto3 proto3-data-stripper protoc_gen_gogoproto_LDADD = $(top_srcdir)/src/libprotobuf.la $(top_srcdir)/src/libprotoc.la protoc_gen_gogoproto_SOURCES = util/protoc-gen-gogoproto.cc @@ -467,9 +467,137 @@ nodist_gogo_data_scrubber_SOURCES = \ $(benchmarks_protoc_outputs_proto2) \ $(benchmarks_protoc_outputs_proto2_header) \ $(benchmarks_protoc_outputs_header) - + +protoc_gen_proto2_to_proto3_LDADD = $(top_srcdir)/src/libprotobuf.la $(top_srcdir)/src/libprotoc.la +protoc_gen_proto2_to_proto3_SOURCES = util/protoc-gen-proto2_to_proto3.cc +protoc_gen_proto2_to_proto3_CPPFLAGS = -I$(top_srcdir)/src -I$(srcdir)/cpp -I$(srcdir)/util + +proto3_data_stripper_LDADD = $(top_srcdir)/src/libprotobuf.la +proto3_data_stripper_SOURCES = util/proto3_data_stripper.cc +proto3_data_stripper_CPPFLAGS = -I$(top_srcdir)/src -I$(srcdir)/cpp -I$(srcdir)/util +util/proto3_data_stripper-proto3_data_stripper.$(OBJEXT): $(benchmarks_protoc_outputs) $(benchmarks_protoc_outputs_proto2) $(benchmarks_protoc_outputs_header) $(benchmarks_protoc_outputs_proto2_header) +nodist_proto3_data_stripper_SOURCES = \ + $(benchmarks_protoc_outputs) \ + $(benchmarks_protoc_outputs_proto2) \ + $(benchmarks_protoc_outputs_proto2_header) \ + $(benchmarks_protoc_outputs_header) + + ############ UTIL RULES END ############ +############ PROTO3 PREPARATION BEGIN ############# + +proto3_proto_middleman: protoc-gen-proto2_to_proto3 + mkdir -p "tmp/proto3_proto" + oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I$(srcdir) -I$(top_srcdir) --plugin=protoc-gen-proto2_to_proto3 --proto2_to_proto3_out=$$oldpwd/tmp/proto3_proto $(benchmarks_protoc_inputs) $(benchmarks_protoc_inputs_benchmark_wrapper) $(benchmarks_protoc_inputs_proto2) ) + touch proto3_proto_middleman + +full_srcdir = $$(cd $(srcdir) && pwd) +proto3_data = $$(for data in $(all_data); do echo $(full_srcdir)"/tmp/proto3_data$${data\#$(full_srcdir)}"; done | xargs) + +generate_proto3_data: protoc_middleman protoc_middleman2 proto3-data-stripper + mkdir -p `dirname $(proto3_data)` + ./proto3-data-stripper $(all_data) $(proto3_data) + touch generate_proto3_data + +############ PROTO3 PREPARATION END ############# + +############ PHP RULES BEGIN ################# + +proto3_middleman_php: proto3_proto_middleman + mkdir -p "tmp/php" + oldpwd=`pwd` && ( cd tmp/proto3_proto && $$oldpwd/../src/protoc$(EXEEXT) -I$(srcdir) -I$(top_srcdir) --php_out=$$oldpwd/tmp/php $(benchmarks_protoc_inputs) $(benchmarks_protoc_inputs_benchmark_wrapper) $(benchmarks_protoc_inputs_proto2) ) + touch proto3_middleman_php + +php-benchmark: proto3_middleman_php generate_proto3_data + mkdir -p "tmp/php/Google/Protobuf/Benchmark" && cp php/PhpBenchmark.php "tmp/php/Google/Protobuf/Benchmark" + cp php/autoload.php "tmp/php" + @echo "Writing shortcut script php-benchmark..." + @echo '#! /bin/bash' > php-benchmark + @echo 'export PROTOBUF_PHP_SRCDIR="$$(cd $(top_srcdir) && pwd)/php/src"' >> php-benchmark + @echo 'cd tmp/php' >> php-benchmark + @echo 'export CURRENT_DIR=$$(pwd)' >> php-benchmark + @echo 'php -d auto_prepend_file="autoload.php" -d include_path="$$(pwd)" Google/Protobuf/Benchmark/PhpBenchmark.php $$@' >> php-benchmark + @echo 'cd ../..' >> php-benchmark + @chmod +x php-benchmark + +php: php-benchmark proto3_middleman_php + ./php-benchmark --behavior_prefix="php" $(proto3_data) + +php_c_extension: + cd $(top_srcdir)/php/ext/google/protobuf && phpize && ./configure CFLAGS='-O3' && make -j8 + +php-c-benchmark: proto3_middleman_php generate_proto3_data php_c_extension php_c_extension + mkdir -p "tmp/php/Google/Protobuf/Benchmark" && cp php/PhpBenchmark.php "tmp/php/Google/Protobuf/Benchmark" + cp php/autoload.php "tmp/php" + @echo "Writing shortcut script php-c-benchmark..." + @echo '#! /bin/bash' > php-c-benchmark + @echo 'export PROTOBUF_PHP_SRCDIR="$$(cd $(top_srcdir) && pwd)/php/src"' >> php-c-benchmark + @echo 'export PROTOBUF_PHP_EXTDIR="$$PROTOBUF_PHP_SRCDIR/../ext/google/protobuf/modules"' >> php-c-benchmark + @echo 'cd tmp/php' >> php-c-benchmark + @echo 'export CURRENT_DIR=$$(pwd)' >> php-c-benchmark + @echo 'php -d auto_prepend_file="autoload.php" -d include_path="$$(pwd)" -d extension="$$PROTOBUF_PHP_EXTDIR/protobuf.so" Google/Protobuf/Benchmark/PhpBenchmark.php $$@' >> php-c-benchmark + @echo 'cd ../..' >> php-c-benchmark + @chmod +x php-c-benchmark + +php_c: php-c-benchmark proto3_middleman_php + ./php-c-benchmark --behavior_prefix="php_c" $(proto3_data) + + +############ PHP RULES END ################# + +############ protobuf.js RULE BEGIN ############# + +pbjs_preparation: + mkdir -p tmp/protobuf.js + cd tmp/protobuf.js && git clone https://github.com/dcodeIO/protobuf.js.git && \ + cd protobuf.js && npm install && npm run build + cd tmp/protobuf.js && npm install benchmark + cp protobuf.js/* tmp/protobuf.js + cp js/benchmark_suite.js tmp/protobuf.js + touch pbjs_preparation + +pbjs_middleman: pbjs_preparation + export OLDDIR=$$(pwd) && cd tmp/protobuf.js && node generate_pbjs_files.js --target static-module --include_path=$$OLDDIR -o generated_bundle_code.js $(benchmarks_protoc_inputs) $(benchmarks_protoc_inputs_benchmark_wrapper) $(benchmarks_protoc_inputs_proto2) + touch pbjs_middleman + +pbjs-benchmark: pbjs_middleman + @echo '#! /bin/bash' > pbjs-benchmark + @echo 'cd tmp/protobuf.js' >> pbjs-benchmark + @echo 'sed -i "s/protobufjs/.\/protobuf.js/g" generated_bundle_code.js' >> pbjs-benchmark + @echo 'env NODE_PATH=".:./node_modules:$$NODE_PATH" node protobufjs_benchmark.js $$@' >> pbjs-benchmark + @chmod +x pbjs-benchmark + +pbjs: pbjs-benchmark + ./pbjs-benchmark $(all_data) + +############ protobuf.js RULE END ############# + +############ JS RULE BEGIN ############# + +js_preparation: + mkdir -p tmp/js + oldpwd=$$(pwd) && cd $(top_srcdir)/js && npm install && npm test + cd tmp/js && npm install benchmark + cp js/* tmp/js + touch js_preparation + +js_middleman: js_preparation + oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --js_out=import_style=commonjs,binary:$$oldpwd/tmp/js $(benchmarks_protoc_inputs) $(benchmarks_protoc_inputs_benchmark_wrapper) $(benchmarks_protoc_inputs_proto2)) + touch js_middleman + +js-benchmark: js_middleman + @echo '#! /bin/bash' > js-benchmark + @echo 'export TOP_JS_SRCDIR=$$(cd $(top_srcdir)/js && pwd)' >> js-benchmark + @echo 'cd tmp/js' >> js-benchmark + @echo 'env NODE_PATH="$$TOP_JS_SRCDIR:.:./node_modules:$$NODE_PATH" node --max-old-space-size=4096 js_benchmark.js $$@' >> js-benchmark + @chmod +x js-benchmark + +js: js-benchmark + ./js-benchmark $(all_data) + +############ JS RULE END ############# + MAINTAINERCLEANFILES = \ Makefile.in @@ -512,8 +640,19 @@ CLEANFILES = \ gogoslick_protoc_middleman \ gogoslick \ gogo-benchmark \ - gogo/cpp_no_group/cpp_benchmark.* - + gogo/cpp_no_group/cpp_benchmark.* \ + proto3_proto_middleman \ + generate_proto3_data \ + php-benchmark \ + php-c-benchmark \ + proto3_middleman_php \ + pbjs_preparation \ + pbjs_middleman \ + pbjs-benchmark \ + js_preparation \ + js_middleman \ + js-benchmark clean-local: -rm -rf tmp/* + diff --git a/third_party/protobuf/benchmarks/Makefile.in b/third_party/protobuf/benchmarks/Makefile.in index e055d285..03525b29 100644 --- a/third_party/protobuf/benchmarks/Makefile.in +++ b/third_party/protobuf/benchmarks/Makefile.in @@ -91,7 +91,9 @@ build_triplet = @build@ host_triplet = @host@ target_triplet = @target@ bin_PROGRAMS = cpp-benchmark$(EXEEXT) cpp-no-group-benchmark$(EXEEXT) \ - protoc-gen-gogoproto$(EXEEXT) gogo-data-scrubber$(EXEEXT) + protoc-gen-gogoproto$(EXEEXT) gogo-data-scrubber$(EXEEXT) \ + protoc-gen-proto2_to_proto3$(EXEEXT) \ + proto3-data-stripper$(EXEEXT) subdir = benchmarks ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_system_extensions.m4 \ @@ -249,11 +251,41 @@ nodist_gogo_data_scrubber_OBJECTS = $(am__objects_8) $(am__objects_9) \ gogo_data_scrubber_OBJECTS = $(am_gogo_data_scrubber_OBJECTS) \ $(nodist_gogo_data_scrubber_OBJECTS) gogo_data_scrubber_DEPENDENCIES = $(top_srcdir)/src/libprotobuf.la +am_proto3_data_stripper_OBJECTS = \ + util/proto3_data_stripper-proto3_data_stripper.$(OBJEXT) +am__objects_10 = cpp/proto3_data_stripper-benchmarks.pb.$(OBJEXT) \ + cpp/datasets/google_message1/proto3/proto3_data_stripper-benchmark_message1_proto3.pb.$(OBJEXT) +am__objects_11 = cpp/datasets/google_message1/proto2/proto3_data_stripper-benchmark_message1_proto2.pb.$(OBJEXT) \ + cpp/datasets/google_message2/proto3_data_stripper-benchmark_message2.pb.$(OBJEXT) \ + cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3.pb.$(OBJEXT) \ + cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_1.pb.$(OBJEXT) \ + cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_2.pb.$(OBJEXT) \ + cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_3.pb.$(OBJEXT) \ + cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_4.pb.$(OBJEXT) \ + cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_5.pb.$(OBJEXT) \ + cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_6.pb.$(OBJEXT) \ + cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_7.pb.$(OBJEXT) \ + cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_8.pb.$(OBJEXT) \ + cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4.pb.$(OBJEXT) \ + cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_1.pb.$(OBJEXT) \ + cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_2.pb.$(OBJEXT) \ + cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_3.pb.$(OBJEXT) +nodist_proto3_data_stripper_OBJECTS = $(am__objects_10) \ + $(am__objects_11) $(am__objects_3) $(am__objects_3) +proto3_data_stripper_OBJECTS = $(am_proto3_data_stripper_OBJECTS) \ + $(nodist_proto3_data_stripper_OBJECTS) +proto3_data_stripper_DEPENDENCIES = $(top_srcdir)/src/libprotobuf.la am_protoc_gen_gogoproto_OBJECTS = \ util/protoc_gen_gogoproto-protoc-gen-gogoproto.$(OBJEXT) protoc_gen_gogoproto_OBJECTS = $(am_protoc_gen_gogoproto_OBJECTS) protoc_gen_gogoproto_DEPENDENCIES = $(top_srcdir)/src/libprotobuf.la \ $(top_srcdir)/src/libprotoc.la +am_protoc_gen_proto2_to_proto3_OBJECTS = util/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.$(OBJEXT) +protoc_gen_proto2_to_proto3_OBJECTS = \ + $(am_protoc_gen_proto2_to_proto3_OBJECTS) +protoc_gen_proto2_to_proto3_DEPENDENCIES = \ + $(top_srcdir)/src/libprotobuf.la \ + $(top_srcdir)/src/libprotoc.la AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false @@ -313,10 +345,15 @@ SOURCES = $(libbenchmark_messages_la_SOURCES) \ $(nodist_cpp_no_group_benchmark_SOURCES) \ $(gogo_data_scrubber_SOURCES) \ $(nodist_gogo_data_scrubber_SOURCES) \ - $(protoc_gen_gogoproto_SOURCES) + $(proto3_data_stripper_SOURCES) \ + $(nodist_proto3_data_stripper_SOURCES) \ + $(protoc_gen_gogoproto_SOURCES) \ + $(protoc_gen_proto2_to_proto3_SOURCES) DIST_SOURCES = $(libbenchmark_messages_la_SOURCES) \ $(cpp_benchmark_SOURCES) $(cpp_no_group_benchmark_SOURCES) \ - $(gogo_data_scrubber_SOURCES) $(protoc_gen_gogoproto_SOURCES) + $(gogo_data_scrubber_SOURCES) $(proto3_data_stripper_SOURCES) \ + $(protoc_gen_gogoproto_SOURCES) \ + $(protoc_gen_proto2_to_proto3_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ @@ -394,6 +431,7 @@ ISAINFO = @ISAINFO@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_FOR_BUILD = @LDFLAGS_FOR_BUILD@ +LIBATOMIC_LIBS = @LIBATOMIC_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ @@ -520,7 +558,7 @@ benchmarks_protoc_inputs_proto2 = \ datasets/google_message4/benchmark_message4_2.proto \ datasets/google_message4/benchmark_message4_3.proto -all_data = $$(find $(srcdir) -type f -name "dataset.*.pb" -not -path "./tmp/*") +all_data = $$(find $$(cd $(srcdir) && pwd) -type f -name "dataset.*.pb" -not -path "$$(cd $(srcdir) && pwd)/tmp/*") ############# CPP RULES ############## benchmarks_protoc_outputs = \ @@ -676,8 +714,7 @@ nodist_cpp_no_group_benchmark_SOURCES = \ $(cpp_no_group_benchmarks_protoc_outputs_header) \ $(cpp_no_group_benchmarks_protoc_outputs_proto2_header) -new_data = $$(for data in $(all_data); do echo "tmp$${data\#$(srcdir)}"; done | xargs) -gogo_data = $$(find . -type f -name "dataset.*.pb" -path "./tmp/*") +gogo_data = $$(for data in $(all_data); do echo "tmp/gogo_data$${data\#$(srcdir)}"; done | xargs) protoc_gen_gogoproto_LDADD = $(top_srcdir)/src/libprotobuf.la $(top_srcdir)/src/libprotoc.la protoc_gen_gogoproto_SOURCES = util/protoc-gen-gogoproto.cc protoc_gen_gogoproto_CPPFLAGS = -I$(top_srcdir)/src -I$(srcdir)/cpp -I$(srcdir)/util @@ -690,8 +727,22 @@ nodist_gogo_data_scrubber_SOURCES = \ $(benchmarks_protoc_outputs_proto2_header) \ $(benchmarks_protoc_outputs_header) +protoc_gen_proto2_to_proto3_LDADD = $(top_srcdir)/src/libprotobuf.la $(top_srcdir)/src/libprotoc.la +protoc_gen_proto2_to_proto3_SOURCES = util/protoc-gen-proto2_to_proto3.cc +protoc_gen_proto2_to_proto3_CPPFLAGS = -I$(top_srcdir)/src -I$(srcdir)/cpp -I$(srcdir)/util +proto3_data_stripper_LDADD = $(top_srcdir)/src/libprotobuf.la +proto3_data_stripper_SOURCES = util/proto3_data_stripper.cc +proto3_data_stripper_CPPFLAGS = -I$(top_srcdir)/src -I$(srcdir)/cpp -I$(srcdir)/util +nodist_proto3_data_stripper_SOURCES = \ + $(benchmarks_protoc_outputs) \ + $(benchmarks_protoc_outputs_proto2) \ + $(benchmarks_protoc_outputs_proto2_header) \ + $(benchmarks_protoc_outputs_header) -############ UTIL RULES END ############ +full_srcdir = $$(cd $(srcdir) && pwd) +proto3_data = $$(for data in $(all_data); do echo $(full_srcdir)"/tmp/proto3_data$${data\#$(full_srcdir)}"; done | xargs) + +############ JS RULE END ############# MAINTAINERCLEANFILES = \ Makefile.in @@ -734,7 +785,18 @@ CLEANFILES = \ gogoslick_protoc_middleman \ gogoslick \ gogo-benchmark \ - gogo/cpp_no_group/cpp_benchmark.* + gogo/cpp_no_group/cpp_benchmark.* \ + proto3_proto_middleman \ + generate_proto3_data \ + php-benchmark \ + php-c-benchmark \ + proto3_middleman_php \ + pbjs_preparation \ + pbjs_middleman \ + pbjs-benchmark \ + js_preparation \ + js_middleman \ + js-benchmark all: all-am @@ -1160,12 +1222,74 @@ cpp/datasets/google_message4/gogo_data_scrubber-benchmark_message4_3.pb.$(OBJEXT gogo-data-scrubber$(EXEEXT): $(gogo_data_scrubber_OBJECTS) $(gogo_data_scrubber_DEPENDENCIES) $(EXTRA_gogo_data_scrubber_DEPENDENCIES) @rm -f gogo-data-scrubber$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(gogo_data_scrubber_OBJECTS) $(gogo_data_scrubber_LDADD) $(LIBS) +util/proto3_data_stripper-proto3_data_stripper.$(OBJEXT): \ + util/$(am__dirstamp) util/$(DEPDIR)/$(am__dirstamp) +cpp/proto3_data_stripper-benchmarks.pb.$(OBJEXT): cpp/$(am__dirstamp) \ + cpp/$(DEPDIR)/$(am__dirstamp) +cpp/datasets/google_message1/proto3/proto3_data_stripper-benchmark_message1_proto3.pb.$(OBJEXT): \ + cpp/datasets/google_message1/proto3/$(am__dirstamp) \ + cpp/datasets/google_message1/proto3/$(DEPDIR)/$(am__dirstamp) +cpp/datasets/google_message1/proto2/proto3_data_stripper-benchmark_message1_proto2.pb.$(OBJEXT): \ + cpp/datasets/google_message1/proto2/$(am__dirstamp) \ + cpp/datasets/google_message1/proto2/$(DEPDIR)/$(am__dirstamp) +cpp/datasets/google_message2/proto3_data_stripper-benchmark_message2.pb.$(OBJEXT): \ + cpp/datasets/google_message2/$(am__dirstamp) \ + cpp/datasets/google_message2/$(DEPDIR)/$(am__dirstamp) +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3.pb.$(OBJEXT): \ + cpp/datasets/google_message3/$(am__dirstamp) \ + cpp/datasets/google_message3/$(DEPDIR)/$(am__dirstamp) +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_1.pb.$(OBJEXT): \ + cpp/datasets/google_message3/$(am__dirstamp) \ + cpp/datasets/google_message3/$(DEPDIR)/$(am__dirstamp) +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_2.pb.$(OBJEXT): \ + cpp/datasets/google_message3/$(am__dirstamp) \ + cpp/datasets/google_message3/$(DEPDIR)/$(am__dirstamp) +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_3.pb.$(OBJEXT): \ + cpp/datasets/google_message3/$(am__dirstamp) \ + cpp/datasets/google_message3/$(DEPDIR)/$(am__dirstamp) +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_4.pb.$(OBJEXT): \ + cpp/datasets/google_message3/$(am__dirstamp) \ + cpp/datasets/google_message3/$(DEPDIR)/$(am__dirstamp) +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_5.pb.$(OBJEXT): \ + cpp/datasets/google_message3/$(am__dirstamp) \ + cpp/datasets/google_message3/$(DEPDIR)/$(am__dirstamp) +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_6.pb.$(OBJEXT): \ + cpp/datasets/google_message3/$(am__dirstamp) \ + cpp/datasets/google_message3/$(DEPDIR)/$(am__dirstamp) +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_7.pb.$(OBJEXT): \ + cpp/datasets/google_message3/$(am__dirstamp) \ + cpp/datasets/google_message3/$(DEPDIR)/$(am__dirstamp) +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_8.pb.$(OBJEXT): \ + cpp/datasets/google_message3/$(am__dirstamp) \ + cpp/datasets/google_message3/$(DEPDIR)/$(am__dirstamp) +cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4.pb.$(OBJEXT): \ + cpp/datasets/google_message4/$(am__dirstamp) \ + cpp/datasets/google_message4/$(DEPDIR)/$(am__dirstamp) +cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_1.pb.$(OBJEXT): \ + cpp/datasets/google_message4/$(am__dirstamp) \ + cpp/datasets/google_message4/$(DEPDIR)/$(am__dirstamp) +cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_2.pb.$(OBJEXT): \ + cpp/datasets/google_message4/$(am__dirstamp) \ + cpp/datasets/google_message4/$(DEPDIR)/$(am__dirstamp) +cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_3.pb.$(OBJEXT): \ + cpp/datasets/google_message4/$(am__dirstamp) \ + cpp/datasets/google_message4/$(DEPDIR)/$(am__dirstamp) + +proto3-data-stripper$(EXEEXT): $(proto3_data_stripper_OBJECTS) $(proto3_data_stripper_DEPENDENCIES) $(EXTRA_proto3_data_stripper_DEPENDENCIES) + @rm -f proto3-data-stripper$(EXEEXT) + $(AM_V_CXXLD)$(CXXLINK) $(proto3_data_stripper_OBJECTS) $(proto3_data_stripper_LDADD) $(LIBS) util/protoc_gen_gogoproto-protoc-gen-gogoproto.$(OBJEXT): \ util/$(am__dirstamp) util/$(DEPDIR)/$(am__dirstamp) protoc-gen-gogoproto$(EXEEXT): $(protoc_gen_gogoproto_OBJECTS) $(protoc_gen_gogoproto_DEPENDENCIES) $(EXTRA_protoc_gen_gogoproto_DEPENDENCIES) @rm -f protoc-gen-gogoproto$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(protoc_gen_gogoproto_OBJECTS) $(protoc_gen_gogoproto_LDADD) $(LIBS) +util/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.$(OBJEXT): \ + util/$(am__dirstamp) util/$(DEPDIR)/$(am__dirstamp) + +protoc-gen-proto2_to_proto3$(EXEEXT): $(protoc_gen_proto2_to_proto3_OBJECTS) $(protoc_gen_proto2_to_proto3_DEPENDENCIES) $(EXTRA_protoc_gen_proto2_to_proto3_DEPENDENCIES) + @rm -f protoc-gen-proto2_to_proto3$(EXEEXT) + $(AM_V_CXXLD)$(CXXLINK) $(protoc_gen_proto2_to_proto3_OBJECTS) $(protoc_gen_proto2_to_proto3_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) @@ -1198,15 +1322,19 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@cpp/$(DEPDIR)/cpp_benchmark-cpp_benchmark.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/$(DEPDIR)/gogo_data_scrubber-benchmarks.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/$(DEPDIR)/libbenchmark_messages_la-benchmarks.pb.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@cpp/$(DEPDIR)/proto3_data_stripper-benchmarks.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message1/proto2/$(DEPDIR)/cpp_benchmark-benchmark_message1_proto2.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message1/proto2/$(DEPDIR)/gogo_data_scrubber-benchmark_message1_proto2.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message1/proto2/$(DEPDIR)/libbenchmark_messages_la-benchmark_message1_proto2.pb.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message1/proto2/$(DEPDIR)/proto3_data_stripper-benchmark_message1_proto2.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message1/proto3/$(DEPDIR)/cpp_benchmark-benchmark_message1_proto3.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message1/proto3/$(DEPDIR)/gogo_data_scrubber-benchmark_message1_proto3.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message1/proto3/$(DEPDIR)/libbenchmark_messages_la-benchmark_message1_proto3.pb.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message1/proto3/$(DEPDIR)/proto3_data_stripper-benchmark_message1_proto3.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message2/$(DEPDIR)/cpp_benchmark-benchmark_message2.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message2/$(DEPDIR)/gogo_data_scrubber-benchmark_message2.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message2/$(DEPDIR)/libbenchmark_messages_la-benchmark_message2.pb.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message2/$(DEPDIR)/proto3_data_stripper-benchmark_message2.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message3/$(DEPDIR)/cpp_benchmark-benchmark_message3.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message3/$(DEPDIR)/cpp_benchmark-benchmark_message3_1.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message3/$(DEPDIR)/cpp_benchmark-benchmark_message3_2.pb.Po@am__quote@ @@ -1234,6 +1362,15 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message3/$(DEPDIR)/libbenchmark_messages_la-benchmark_message3_6.pb.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message3/$(DEPDIR)/libbenchmark_messages_la-benchmark_message3_7.pb.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message3/$(DEPDIR)/libbenchmark_messages_la-benchmark_message3_8.pb.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3.pb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_1.pb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_2.pb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_3.pb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_4.pb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_5.pb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_6.pb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_7.pb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_8.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message4/$(DEPDIR)/cpp_benchmark-benchmark_message4.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message4/$(DEPDIR)/cpp_benchmark-benchmark_message4_1.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message4/$(DEPDIR)/cpp_benchmark-benchmark_message4_2.pb.Po@am__quote@ @@ -1246,6 +1383,10 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message4/$(DEPDIR)/libbenchmark_messages_la-benchmark_message4_1.pb.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message4/$(DEPDIR)/libbenchmark_messages_la-benchmark_message4_2.pb.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message4/$(DEPDIR)/libbenchmark_messages_la-benchmark_message4_3.pb.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4.pb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_1.pb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_2.pb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_3.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@gogo/cpp_no_group/$(DEPDIR)/cpp_no_group_benchmark-benchmarks.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@gogo/cpp_no_group/$(DEPDIR)/cpp_no_group_benchmark-cpp_benchmark.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@gogo/cpp_no_group/datasets/google_message1/proto2/$(DEPDIR)/cpp_no_group_benchmark-benchmark_message1_proto2.pb.Po@am__quote@ @@ -1266,7 +1407,9 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@gogo/cpp_no_group/datasets/google_message4/$(DEPDIR)/cpp_no_group_benchmark-benchmark_message4_3.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@python/$(DEPDIR)/libbenchmark_messages_la-python_benchmark_messages.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@util/$(DEPDIR)/gogo_data_scrubber-gogo_data_scrubber.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@util/$(DEPDIR)/proto3_data_stripper-proto3_data_stripper.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@util/$(DEPDIR)/protoc_gen_gogoproto-protoc-gen-gogoproto.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@util/$(DEPDIR)/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.Po@am__quote@ .cc.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @@ -2174,6 +2317,258 @@ cpp/datasets/google_message4/gogo_data_scrubber-benchmark_message4_3.pb.obj: cpp @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(gogo_data_scrubber_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message4/gogo_data_scrubber-benchmark_message4_3.pb.obj `if test -f 'cpp/datasets/google_message4/benchmark_message4_3.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message4/benchmark_message4_3.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message4/benchmark_message4_3.pb.cc'; fi` +util/proto3_data_stripper-proto3_data_stripper.o: util/proto3_data_stripper.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT util/proto3_data_stripper-proto3_data_stripper.o -MD -MP -MF util/$(DEPDIR)/proto3_data_stripper-proto3_data_stripper.Tpo -c -o util/proto3_data_stripper-proto3_data_stripper.o `test -f 'util/proto3_data_stripper.cc' || echo '$(srcdir)/'`util/proto3_data_stripper.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) util/$(DEPDIR)/proto3_data_stripper-proto3_data_stripper.Tpo util/$(DEPDIR)/proto3_data_stripper-proto3_data_stripper.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='util/proto3_data_stripper.cc' object='util/proto3_data_stripper-proto3_data_stripper.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o util/proto3_data_stripper-proto3_data_stripper.o `test -f 'util/proto3_data_stripper.cc' || echo '$(srcdir)/'`util/proto3_data_stripper.cc + +util/proto3_data_stripper-proto3_data_stripper.obj: util/proto3_data_stripper.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT util/proto3_data_stripper-proto3_data_stripper.obj -MD -MP -MF util/$(DEPDIR)/proto3_data_stripper-proto3_data_stripper.Tpo -c -o util/proto3_data_stripper-proto3_data_stripper.obj `if test -f 'util/proto3_data_stripper.cc'; then $(CYGPATH_W) 'util/proto3_data_stripper.cc'; else $(CYGPATH_W) '$(srcdir)/util/proto3_data_stripper.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) util/$(DEPDIR)/proto3_data_stripper-proto3_data_stripper.Tpo util/$(DEPDIR)/proto3_data_stripper-proto3_data_stripper.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='util/proto3_data_stripper.cc' object='util/proto3_data_stripper-proto3_data_stripper.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o util/proto3_data_stripper-proto3_data_stripper.obj `if test -f 'util/proto3_data_stripper.cc'; then $(CYGPATH_W) 'util/proto3_data_stripper.cc'; else $(CYGPATH_W) '$(srcdir)/util/proto3_data_stripper.cc'; fi` + +cpp/proto3_data_stripper-benchmarks.pb.o: cpp/benchmarks.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/proto3_data_stripper-benchmarks.pb.o -MD -MP -MF cpp/$(DEPDIR)/proto3_data_stripper-benchmarks.pb.Tpo -c -o cpp/proto3_data_stripper-benchmarks.pb.o `test -f 'cpp/benchmarks.pb.cc' || echo '$(srcdir)/'`cpp/benchmarks.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/$(DEPDIR)/proto3_data_stripper-benchmarks.pb.Tpo cpp/$(DEPDIR)/proto3_data_stripper-benchmarks.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/benchmarks.pb.cc' object='cpp/proto3_data_stripper-benchmarks.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/proto3_data_stripper-benchmarks.pb.o `test -f 'cpp/benchmarks.pb.cc' || echo '$(srcdir)/'`cpp/benchmarks.pb.cc + +cpp/proto3_data_stripper-benchmarks.pb.obj: cpp/benchmarks.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/proto3_data_stripper-benchmarks.pb.obj -MD -MP -MF cpp/$(DEPDIR)/proto3_data_stripper-benchmarks.pb.Tpo -c -o cpp/proto3_data_stripper-benchmarks.pb.obj `if test -f 'cpp/benchmarks.pb.cc'; then $(CYGPATH_W) 'cpp/benchmarks.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/benchmarks.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/$(DEPDIR)/proto3_data_stripper-benchmarks.pb.Tpo cpp/$(DEPDIR)/proto3_data_stripper-benchmarks.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/benchmarks.pb.cc' object='cpp/proto3_data_stripper-benchmarks.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/proto3_data_stripper-benchmarks.pb.obj `if test -f 'cpp/benchmarks.pb.cc'; then $(CYGPATH_W) 'cpp/benchmarks.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/benchmarks.pb.cc'; fi` + +cpp/datasets/google_message1/proto3/proto3_data_stripper-benchmark_message1_proto3.pb.o: cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message1/proto3/proto3_data_stripper-benchmark_message1_proto3.pb.o -MD -MP -MF cpp/datasets/google_message1/proto3/$(DEPDIR)/proto3_data_stripper-benchmark_message1_proto3.pb.Tpo -c -o cpp/datasets/google_message1/proto3/proto3_data_stripper-benchmark_message1_proto3.pb.o `test -f 'cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message1/proto3/$(DEPDIR)/proto3_data_stripper-benchmark_message1_proto3.pb.Tpo cpp/datasets/google_message1/proto3/$(DEPDIR)/proto3_data_stripper-benchmark_message1_proto3.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.cc' object='cpp/datasets/google_message1/proto3/proto3_data_stripper-benchmark_message1_proto3.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message1/proto3/proto3_data_stripper-benchmark_message1_proto3.pb.o `test -f 'cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.cc + +cpp/datasets/google_message1/proto3/proto3_data_stripper-benchmark_message1_proto3.pb.obj: cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message1/proto3/proto3_data_stripper-benchmark_message1_proto3.pb.obj -MD -MP -MF cpp/datasets/google_message1/proto3/$(DEPDIR)/proto3_data_stripper-benchmark_message1_proto3.pb.Tpo -c -o cpp/datasets/google_message1/proto3/proto3_data_stripper-benchmark_message1_proto3.pb.obj `if test -f 'cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message1/proto3/$(DEPDIR)/proto3_data_stripper-benchmark_message1_proto3.pb.Tpo cpp/datasets/google_message1/proto3/$(DEPDIR)/proto3_data_stripper-benchmark_message1_proto3.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.cc' object='cpp/datasets/google_message1/proto3/proto3_data_stripper-benchmark_message1_proto3.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message1/proto3/proto3_data_stripper-benchmark_message1_proto3.pb.obj `if test -f 'cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.cc'; fi` + +cpp/datasets/google_message1/proto2/proto3_data_stripper-benchmark_message1_proto2.pb.o: cpp/datasets/google_message1/proto2/benchmark_message1_proto2.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message1/proto2/proto3_data_stripper-benchmark_message1_proto2.pb.o -MD -MP -MF cpp/datasets/google_message1/proto2/$(DEPDIR)/proto3_data_stripper-benchmark_message1_proto2.pb.Tpo -c -o cpp/datasets/google_message1/proto2/proto3_data_stripper-benchmark_message1_proto2.pb.o `test -f 'cpp/datasets/google_message1/proto2/benchmark_message1_proto2.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message1/proto2/benchmark_message1_proto2.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message1/proto2/$(DEPDIR)/proto3_data_stripper-benchmark_message1_proto2.pb.Tpo cpp/datasets/google_message1/proto2/$(DEPDIR)/proto3_data_stripper-benchmark_message1_proto2.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message1/proto2/benchmark_message1_proto2.pb.cc' object='cpp/datasets/google_message1/proto2/proto3_data_stripper-benchmark_message1_proto2.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message1/proto2/proto3_data_stripper-benchmark_message1_proto2.pb.o `test -f 'cpp/datasets/google_message1/proto2/benchmark_message1_proto2.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message1/proto2/benchmark_message1_proto2.pb.cc + +cpp/datasets/google_message1/proto2/proto3_data_stripper-benchmark_message1_proto2.pb.obj: cpp/datasets/google_message1/proto2/benchmark_message1_proto2.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message1/proto2/proto3_data_stripper-benchmark_message1_proto2.pb.obj -MD -MP -MF cpp/datasets/google_message1/proto2/$(DEPDIR)/proto3_data_stripper-benchmark_message1_proto2.pb.Tpo -c -o cpp/datasets/google_message1/proto2/proto3_data_stripper-benchmark_message1_proto2.pb.obj `if test -f 'cpp/datasets/google_message1/proto2/benchmark_message1_proto2.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message1/proto2/benchmark_message1_proto2.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message1/proto2/benchmark_message1_proto2.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message1/proto2/$(DEPDIR)/proto3_data_stripper-benchmark_message1_proto2.pb.Tpo cpp/datasets/google_message1/proto2/$(DEPDIR)/proto3_data_stripper-benchmark_message1_proto2.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message1/proto2/benchmark_message1_proto2.pb.cc' object='cpp/datasets/google_message1/proto2/proto3_data_stripper-benchmark_message1_proto2.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message1/proto2/proto3_data_stripper-benchmark_message1_proto2.pb.obj `if test -f 'cpp/datasets/google_message1/proto2/benchmark_message1_proto2.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message1/proto2/benchmark_message1_proto2.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message1/proto2/benchmark_message1_proto2.pb.cc'; fi` + +cpp/datasets/google_message2/proto3_data_stripper-benchmark_message2.pb.o: cpp/datasets/google_message2/benchmark_message2.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message2/proto3_data_stripper-benchmark_message2.pb.o -MD -MP -MF cpp/datasets/google_message2/$(DEPDIR)/proto3_data_stripper-benchmark_message2.pb.Tpo -c -o cpp/datasets/google_message2/proto3_data_stripper-benchmark_message2.pb.o `test -f 'cpp/datasets/google_message2/benchmark_message2.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message2/benchmark_message2.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message2/$(DEPDIR)/proto3_data_stripper-benchmark_message2.pb.Tpo cpp/datasets/google_message2/$(DEPDIR)/proto3_data_stripper-benchmark_message2.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message2/benchmark_message2.pb.cc' object='cpp/datasets/google_message2/proto3_data_stripper-benchmark_message2.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message2/proto3_data_stripper-benchmark_message2.pb.o `test -f 'cpp/datasets/google_message2/benchmark_message2.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message2/benchmark_message2.pb.cc + +cpp/datasets/google_message2/proto3_data_stripper-benchmark_message2.pb.obj: cpp/datasets/google_message2/benchmark_message2.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message2/proto3_data_stripper-benchmark_message2.pb.obj -MD -MP -MF cpp/datasets/google_message2/$(DEPDIR)/proto3_data_stripper-benchmark_message2.pb.Tpo -c -o cpp/datasets/google_message2/proto3_data_stripper-benchmark_message2.pb.obj `if test -f 'cpp/datasets/google_message2/benchmark_message2.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message2/benchmark_message2.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message2/benchmark_message2.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message2/$(DEPDIR)/proto3_data_stripper-benchmark_message2.pb.Tpo cpp/datasets/google_message2/$(DEPDIR)/proto3_data_stripper-benchmark_message2.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message2/benchmark_message2.pb.cc' object='cpp/datasets/google_message2/proto3_data_stripper-benchmark_message2.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message2/proto3_data_stripper-benchmark_message2.pb.obj `if test -f 'cpp/datasets/google_message2/benchmark_message2.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message2/benchmark_message2.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message2/benchmark_message2.pb.cc'; fi` + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3.pb.o: cpp/datasets/google_message3/benchmark_message3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3.pb.o -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3.pb.cc + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3.pb.obj: cpp/datasets/google_message3/benchmark_message3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3.pb.obj -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3.pb.cc'; fi` + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_1.pb.o: cpp/datasets/google_message3/benchmark_message3_1.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_1.pb.o -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_1.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_1.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3_1.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3_1.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_1.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_1.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3_1.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_1.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_1.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3_1.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3_1.pb.cc + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_1.pb.obj: cpp/datasets/google_message3/benchmark_message3_1.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_1.pb.obj -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_1.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_1.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3_1.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3_1.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3_1.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_1.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_1.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3_1.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_1.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_1.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3_1.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3_1.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3_1.pb.cc'; fi` + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_2.pb.o: cpp/datasets/google_message3/benchmark_message3_2.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_2.pb.o -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_2.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_2.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3_2.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3_2.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_2.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_2.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3_2.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_2.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_2.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3_2.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3_2.pb.cc + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_2.pb.obj: cpp/datasets/google_message3/benchmark_message3_2.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_2.pb.obj -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_2.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_2.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3_2.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3_2.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3_2.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_2.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_2.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3_2.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_2.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_2.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3_2.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3_2.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3_2.pb.cc'; fi` + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_3.pb.o: cpp/datasets/google_message3/benchmark_message3_3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_3.pb.o -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_3.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_3.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3_3.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3_3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_3.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_3.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3_3.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_3.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_3.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3_3.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3_3.pb.cc + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_3.pb.obj: cpp/datasets/google_message3/benchmark_message3_3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_3.pb.obj -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_3.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_3.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3_3.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3_3.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3_3.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_3.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_3.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3_3.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_3.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_3.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3_3.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3_3.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3_3.pb.cc'; fi` + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_4.pb.o: cpp/datasets/google_message3/benchmark_message3_4.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_4.pb.o -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_4.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_4.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3_4.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3_4.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_4.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_4.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3_4.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_4.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_4.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3_4.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3_4.pb.cc + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_4.pb.obj: cpp/datasets/google_message3/benchmark_message3_4.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_4.pb.obj -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_4.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_4.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3_4.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3_4.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3_4.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_4.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_4.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3_4.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_4.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_4.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3_4.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3_4.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3_4.pb.cc'; fi` + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_5.pb.o: cpp/datasets/google_message3/benchmark_message3_5.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_5.pb.o -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_5.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_5.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3_5.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3_5.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_5.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_5.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3_5.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_5.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_5.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3_5.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3_5.pb.cc + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_5.pb.obj: cpp/datasets/google_message3/benchmark_message3_5.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_5.pb.obj -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_5.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_5.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3_5.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3_5.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3_5.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_5.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_5.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3_5.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_5.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_5.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3_5.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3_5.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3_5.pb.cc'; fi` + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_6.pb.o: cpp/datasets/google_message3/benchmark_message3_6.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_6.pb.o -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_6.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_6.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3_6.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3_6.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_6.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_6.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3_6.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_6.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_6.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3_6.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3_6.pb.cc + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_6.pb.obj: cpp/datasets/google_message3/benchmark_message3_6.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_6.pb.obj -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_6.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_6.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3_6.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3_6.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3_6.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_6.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_6.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3_6.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_6.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_6.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3_6.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3_6.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3_6.pb.cc'; fi` + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_7.pb.o: cpp/datasets/google_message3/benchmark_message3_7.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_7.pb.o -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_7.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_7.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3_7.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3_7.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_7.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_7.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3_7.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_7.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_7.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3_7.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3_7.pb.cc + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_7.pb.obj: cpp/datasets/google_message3/benchmark_message3_7.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_7.pb.obj -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_7.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_7.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3_7.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3_7.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3_7.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_7.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_7.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3_7.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_7.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_7.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3_7.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3_7.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3_7.pb.cc'; fi` + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_8.pb.o: cpp/datasets/google_message3/benchmark_message3_8.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_8.pb.o -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_8.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_8.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3_8.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3_8.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_8.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_8.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3_8.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_8.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_8.pb.o `test -f 'cpp/datasets/google_message3/benchmark_message3_8.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message3/benchmark_message3_8.pb.cc + +cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_8.pb.obj: cpp/datasets/google_message3/benchmark_message3_8.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_8.pb.obj -MD -MP -MF cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_8.pb.Tpo -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_8.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3_8.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3_8.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3_8.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_8.pb.Tpo cpp/datasets/google_message3/$(DEPDIR)/proto3_data_stripper-benchmark_message3_8.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message3/benchmark_message3_8.pb.cc' object='cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_8.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message3/proto3_data_stripper-benchmark_message3_8.pb.obj `if test -f 'cpp/datasets/google_message3/benchmark_message3_8.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message3/benchmark_message3_8.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message3/benchmark_message3_8.pb.cc'; fi` + +cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4.pb.o: cpp/datasets/google_message4/benchmark_message4.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4.pb.o -MD -MP -MF cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4.pb.Tpo -c -o cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4.pb.o `test -f 'cpp/datasets/google_message4/benchmark_message4.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message4/benchmark_message4.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4.pb.Tpo cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message4/benchmark_message4.pb.cc' object='cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4.pb.o `test -f 'cpp/datasets/google_message4/benchmark_message4.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message4/benchmark_message4.pb.cc + +cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4.pb.obj: cpp/datasets/google_message4/benchmark_message4.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4.pb.obj -MD -MP -MF cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4.pb.Tpo -c -o cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4.pb.obj `if test -f 'cpp/datasets/google_message4/benchmark_message4.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message4/benchmark_message4.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message4/benchmark_message4.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4.pb.Tpo cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message4/benchmark_message4.pb.cc' object='cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4.pb.obj `if test -f 'cpp/datasets/google_message4/benchmark_message4.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message4/benchmark_message4.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message4/benchmark_message4.pb.cc'; fi` + +cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_1.pb.o: cpp/datasets/google_message4/benchmark_message4_1.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_1.pb.o -MD -MP -MF cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_1.pb.Tpo -c -o cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_1.pb.o `test -f 'cpp/datasets/google_message4/benchmark_message4_1.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message4/benchmark_message4_1.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_1.pb.Tpo cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_1.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message4/benchmark_message4_1.pb.cc' object='cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_1.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_1.pb.o `test -f 'cpp/datasets/google_message4/benchmark_message4_1.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message4/benchmark_message4_1.pb.cc + +cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_1.pb.obj: cpp/datasets/google_message4/benchmark_message4_1.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_1.pb.obj -MD -MP -MF cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_1.pb.Tpo -c -o cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_1.pb.obj `if test -f 'cpp/datasets/google_message4/benchmark_message4_1.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message4/benchmark_message4_1.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message4/benchmark_message4_1.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_1.pb.Tpo cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_1.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message4/benchmark_message4_1.pb.cc' object='cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_1.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_1.pb.obj `if test -f 'cpp/datasets/google_message4/benchmark_message4_1.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message4/benchmark_message4_1.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message4/benchmark_message4_1.pb.cc'; fi` + +cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_2.pb.o: cpp/datasets/google_message4/benchmark_message4_2.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_2.pb.o -MD -MP -MF cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_2.pb.Tpo -c -o cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_2.pb.o `test -f 'cpp/datasets/google_message4/benchmark_message4_2.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message4/benchmark_message4_2.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_2.pb.Tpo cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_2.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message4/benchmark_message4_2.pb.cc' object='cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_2.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_2.pb.o `test -f 'cpp/datasets/google_message4/benchmark_message4_2.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message4/benchmark_message4_2.pb.cc + +cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_2.pb.obj: cpp/datasets/google_message4/benchmark_message4_2.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_2.pb.obj -MD -MP -MF cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_2.pb.Tpo -c -o cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_2.pb.obj `if test -f 'cpp/datasets/google_message4/benchmark_message4_2.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message4/benchmark_message4_2.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message4/benchmark_message4_2.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_2.pb.Tpo cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_2.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message4/benchmark_message4_2.pb.cc' object='cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_2.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_2.pb.obj `if test -f 'cpp/datasets/google_message4/benchmark_message4_2.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message4/benchmark_message4_2.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message4/benchmark_message4_2.pb.cc'; fi` + +cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_3.pb.o: cpp/datasets/google_message4/benchmark_message4_3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_3.pb.o -MD -MP -MF cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_3.pb.Tpo -c -o cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_3.pb.o `test -f 'cpp/datasets/google_message4/benchmark_message4_3.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message4/benchmark_message4_3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_3.pb.Tpo cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_3.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message4/benchmark_message4_3.pb.cc' object='cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_3.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_3.pb.o `test -f 'cpp/datasets/google_message4/benchmark_message4_3.pb.cc' || echo '$(srcdir)/'`cpp/datasets/google_message4/benchmark_message4_3.pb.cc + +cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_3.pb.obj: cpp/datasets/google_message4/benchmark_message4_3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_3.pb.obj -MD -MP -MF cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_3.pb.Tpo -c -o cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_3.pb.obj `if test -f 'cpp/datasets/google_message4/benchmark_message4_3.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message4/benchmark_message4_3.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message4/benchmark_message4_3.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_3.pb.Tpo cpp/datasets/google_message4/$(DEPDIR)/proto3_data_stripper-benchmark_message4_3.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='cpp/datasets/google_message4/benchmark_message4_3.pb.cc' object='cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_3.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(proto3_data_stripper_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o cpp/datasets/google_message4/proto3_data_stripper-benchmark_message4_3.pb.obj `if test -f 'cpp/datasets/google_message4/benchmark_message4_3.pb.cc'; then $(CYGPATH_W) 'cpp/datasets/google_message4/benchmark_message4_3.pb.cc'; else $(CYGPATH_W) '$(srcdir)/cpp/datasets/google_message4/benchmark_message4_3.pb.cc'; fi` + util/protoc_gen_gogoproto-protoc-gen-gogoproto.o: util/protoc-gen-gogoproto.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protoc_gen_gogoproto_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT util/protoc_gen_gogoproto-protoc-gen-gogoproto.o -MD -MP -MF util/$(DEPDIR)/protoc_gen_gogoproto-protoc-gen-gogoproto.Tpo -c -o util/protoc_gen_gogoproto-protoc-gen-gogoproto.o `test -f 'util/protoc-gen-gogoproto.cc' || echo '$(srcdir)/'`util/protoc-gen-gogoproto.cc @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) util/$(DEPDIR)/protoc_gen_gogoproto-protoc-gen-gogoproto.Tpo util/$(DEPDIR)/protoc_gen_gogoproto-protoc-gen-gogoproto.Po @@ -2188,6 +2583,20 @@ util/protoc_gen_gogoproto-protoc-gen-gogoproto.obj: util/protoc-gen-gogoproto.cc @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protoc_gen_gogoproto_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o util/protoc_gen_gogoproto-protoc-gen-gogoproto.obj `if test -f 'util/protoc-gen-gogoproto.cc'; then $(CYGPATH_W) 'util/protoc-gen-gogoproto.cc'; else $(CYGPATH_W) '$(srcdir)/util/protoc-gen-gogoproto.cc'; fi` +util/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.o: util/protoc-gen-proto2_to_proto3.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protoc_gen_proto2_to_proto3_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT util/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.o -MD -MP -MF util/$(DEPDIR)/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.Tpo -c -o util/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.o `test -f 'util/protoc-gen-proto2_to_proto3.cc' || echo '$(srcdir)/'`util/protoc-gen-proto2_to_proto3.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) util/$(DEPDIR)/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.Tpo util/$(DEPDIR)/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='util/protoc-gen-proto2_to_proto3.cc' object='util/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protoc_gen_proto2_to_proto3_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o util/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.o `test -f 'util/protoc-gen-proto2_to_proto3.cc' || echo '$(srcdir)/'`util/protoc-gen-proto2_to_proto3.cc + +util/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.obj: util/protoc-gen-proto2_to_proto3.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protoc_gen_proto2_to_proto3_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT util/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.obj -MD -MP -MF util/$(DEPDIR)/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.Tpo -c -o util/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.obj `if test -f 'util/protoc-gen-proto2_to_proto3.cc'; then $(CYGPATH_W) 'util/protoc-gen-proto2_to_proto3.cc'; else $(CYGPATH_W) '$(srcdir)/util/protoc-gen-proto2_to_proto3.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) util/$(DEPDIR)/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.Tpo util/$(DEPDIR)/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='util/protoc-gen-proto2_to_proto3.cc' object='util/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protoc_gen_proto2_to_proto3_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o util/protoc_gen_proto2_to_proto3-protoc-gen-proto2_to_proto3.obj `if test -f 'util/protoc-gen-proto2_to_proto3.cc'; then $(CYGPATH_W) 'util/protoc-gen-proto2_to_proto3.cc'; else $(CYGPATH_W) '$(srcdir)/util/protoc-gen-proto2_to_proto3.cc'; fi` + mostlyclean-libtool: -rm -f *.lo @@ -2466,9 +2875,8 @@ $(benchmarks_protoc_outputs_proto2_header): protoc_middleman2 initialize_submodule: oldpwd=`pwd` - cd $(top_srcdir)/third_party - git submodule update --init -r - cd $(top_srcdir)/third_party/benchmark && cmake -DCMAKE_BUILD_TYPE=Release && make + cd $(top_srcdir) && git submodule update --init -r third_party/benchmark && \ + cd third_party/benchmark && cmake -DCMAKE_BUILD_TYPE=Release && make cd $$oldpwd touch initialize_submodule @@ -2483,8 +2891,10 @@ cpp: protoc_middleman protoc_middleman2 cpp-benchmark initialize_submodule ./cpp-benchmark $(all_data) javac_middleman: $(java_benchmark_testing_files) protoc_middleman protoc_middleman2 - cp -r $(srcdir)/java tmp && cd tmp/java && mvn clean compile assembly:single - cd ../.. + cp -r $(srcdir)/java tmp + mkdir -p tmp/java/lib + cp $(top_srcdir)/java/core/target/*.jar tmp/java/lib/protobuf-java.jar + cd tmp/java && mvn clean compile assembly:single -Dprotobuf.version=$(PACKAGE_VERSION) && cd ../.. @touch javac_middleman java-benchmark: javac_middleman @@ -2494,10 +2904,10 @@ java-benchmark: javac_middleman @echo 'conf=()' >> java-benchmark @echo 'data_files=""' >> java-benchmark @echo 'for arg in $$@; do if [[ $${arg:0:1} == "-" ]]; then conf+=($$arg); else data_files+="$$arg,"; fi; done' >> java-benchmark - @echo 'java -cp '"tmp/java/target/*.jar"' com.google.caliper.runner.CaliperMain com.google.protobuf.ProtoCaliperBenchmark -i runtime '"\\" >> java-benchmark - @echo '-b serializeToByteString,serializeToByteArray,serializeToMemoryStream,'"\\" >> java-benchmark - @echo 'deserializeFromByteString,deserializeFromByteArray,deserializeFromMemoryStream '"\\" >> java-benchmark - @echo '-DdataFile=$${data_files:0:-1} $${conf[*]}' >> java-benchmark + @echo 'java -cp '\"tmp/java/target/*:$(top_srcdir)/java/core/target/*:$(top_srcdir)/java/util/target/*\"" \\" >>java-benchmark + @echo ' com.google.caliper.runner.CaliperMain com.google.protobuf.ProtoCaliperBenchmark -i runtime '"\\" >> java-benchmark + @echo ' -b serializeToByteArray,serializeToMemoryStream,deserializeFromByteArray,deserializeFromMemoryStream '"\\" >> java-benchmark + @echo ' -DdataFile=$${data_files:0:-1} $${conf[*]}' >> java-benchmark @chmod +x java-benchmark java: protoc_middleman protoc_middleman2 java-benchmark @@ -2522,8 +2932,8 @@ libbenchmark_messages_la-python_benchmark_messages.$(OBJEXT): $(benchmarks_proto python-pure-python-benchmark: python_add_init @echo "Writing shortcut script python-pure-python-benchmark..." @echo '#! /bin/bash' > python-pure-python-benchmark - @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-pure-python-benchmark - @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-pure-python-benchmark + @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-pure-python-benchmark + @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-pure-python-benchmark @echo export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=\'python\' >> python-pure-python-benchmark @echo cp $(srcdir)/python/py_benchmark.py tmp >> python-pure-python-benchmark @echo python tmp/py_benchmark.py '$$@' >> python-pure-python-benchmark @@ -2532,8 +2942,8 @@ python-pure-python-benchmark: python_add_init python-cpp-reflection-benchmark: python_add_init @echo "Writing shortcut script python-cpp-reflection-benchmark..." @echo '#! /bin/bash' > python-cpp-reflection-benchmark - @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-cpp-reflection-benchmark - @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-cpp-reflection-benchmark + @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-cpp-reflection-benchmark + @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-cpp-reflection-benchmark @echo export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=\'cpp\' >> python-cpp-reflection-benchmark @echo cp $(srcdir)/python/py_benchmark.py tmp >> python-cpp-reflection-benchmark @echo python tmp/py_benchmark.py '$$@' >> python-cpp-reflection-benchmark @@ -2542,8 +2952,8 @@ python-cpp-reflection-benchmark: python_add_init python-cpp-generated-code-benchmark: python_add_init libbenchmark_messages.la @echo "Writing shortcut script python-cpp-generated-code-benchmark..." @echo '#! /bin/bash' > python-cpp-generated-code-benchmark - @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-cpp-generated-code-benchmark - @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-cpp-generated-code-benchmark + @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-cpp-generated-code-benchmark + @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-cpp-generated-code-benchmark @echo export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=\'cpp\' >> python-cpp-generated-code-benchmark @echo cp $(srcdir)/python/py_benchmark.py tmp >> python-cpp-generated-code-benchmark @echo python tmp/py_benchmark.py --cpp_generated '$$@' >> python-cpp-generated-code-benchmark @@ -2567,19 +2977,19 @@ go_protoc_middleman: make_tmp_dir $(top_srcdir)/src/protoc$(EXEEXT) $(benchmarks oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --go_out=$$oldpwd/tmp $(benchmarks_protoc_inputs_proto2_message4) ) touch go_protoc_middleman -go-benchmark: go_protoc_middleman +go-benchmark: go_protoc_middleman @echo "Writing shortcut script go-benchmark..." @echo '#! /bin/bash' > go-benchmark @echo 'cd $(srcdir)/go' >> go-benchmark @echo 'all_data=""' >> go-benchmark @echo 'conf=()' >> go-benchmark @echo 'data_files=()' >> go-benchmark - @echo 'for arg in $$@; do if [[ $${arg:0:1} == "-" ]]; then conf+=($$arg); else data_files+=("../$$arg"); fi; done' >> go-benchmark + @echo 'for arg in $$@; do if [[ $${arg:0:1} == "-" ]]; then conf+=($$arg); else data_files+=("$$arg"); fi; done' >> go-benchmark @echo 'go test -bench=. $${conf[*]} -- $${data_files[*]}' >> go-benchmark @echo 'cd ..' >> go-benchmark @chmod +x go-benchmark -go: go_protoc_middleman go-benchmark +go: go_protoc_middleman go-benchmark ./go-benchmark $(all_data) $(cpp_no_group_benchmarks_protoc_outputs): cpp_no_group_protoc_middleman @@ -2590,7 +3000,7 @@ $(cpp_no_group_benchmarks_protoc_outputs_proto2_header): cpp_no_group_protoc_mid generate_cpp_no_group_benchmark_code: cp $(srcdir)/cpp/cpp_benchmark.cc gogo/cpp_no_group/cpp_benchmark.cc sed -i -e "s/\#include \"datasets/\#include \"gogo\/cpp_no_group\/datasets/g" gogo/cpp_no_group/cpp_benchmark.cc - sed -i -e "s/\#include \"benchmarks.pb.h/\#include \"gogo\/cpp_no_group\/benchmarks.pb.h/g" gogo/cpp_no_group/cpp_benchmark.cc + sed -i -e "s/\#include \"benchmarks.pb.h/\#include \"gogo\/cpp_no_group\/benchmarks.pb.h/g" gogo/cpp_no_group/cpp_benchmark.cc touch generate_cpp_no_group_benchmark_code # Explicit deps because BUILT_SOURCES are only done before a "make all/check" # so a direct "make test_cpp" could fail if parallel enough. @@ -2608,8 +3018,8 @@ gogo_proto_middleman: protoc-gen-gogoproto touch gogo_proto_middleman generate_gogo_data: protoc_middleman protoc_middleman2 gogo-data-scrubber - mkdir -p `dirname $(new_data)` - ./gogo-data-scrubber $(all_data) $(new_data) + mkdir -p `dirname $(gogo_data)` + ./gogo-data-scrubber $(all_data) $(gogo_data) touch generate_gogo_data make_tmp_dir_gogo: @@ -2692,7 +3102,7 @@ gogo-benchmark: go_no_group: go_no_group_protoc_middleman generate_gogo_data generate_all_gogo_benchmark_code gogo-benchmark ./gogo-benchmark go_no_group $(gogo_data) -gogofast: gogofast_protoc_middleman generate_gogo_data gogo-benchmark generate_all_gogo_benchmark_code +gogofast: gogofast_protoc_middleman generate_gogo_data gogo-benchmark generate_all_gogo_benchmark_code ./gogo-benchmark gogofast $(gogo_data) gogofaster: gogofaster_protoc_middleman generate_gogo_data gogo-benchmark generate_all_gogo_benchmark_code @@ -2701,6 +3111,116 @@ gogofaster: gogofaster_protoc_middleman generate_gogo_data gogo-benchmark gener gogoslick: gogoslick_protoc_middleman generate_gogo_data gogo-benchmark generate_all_gogo_benchmark_code ./gogo-benchmark gogoslick $(gogo_data) util/gogo_data_scrubber-gogo_data_scrubber.$(OBJEXT): $(benchmarks_protoc_outputs) $(benchmarks_protoc_outputs_proto2) $(benchmarks_protoc_outputs_header) $(benchmarks_protoc_outputs_proto2_header) +util/proto3_data_stripper-proto3_data_stripper.$(OBJEXT): $(benchmarks_protoc_outputs) $(benchmarks_protoc_outputs_proto2) $(benchmarks_protoc_outputs_header) $(benchmarks_protoc_outputs_proto2_header) + +############ UTIL RULES END ############ + +############ PROTO3 PREPARATION BEGIN ############# + +proto3_proto_middleman: protoc-gen-proto2_to_proto3 + mkdir -p "tmp/proto3_proto" + oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I$(srcdir) -I$(top_srcdir) --plugin=protoc-gen-proto2_to_proto3 --proto2_to_proto3_out=$$oldpwd/tmp/proto3_proto $(benchmarks_protoc_inputs) $(benchmarks_protoc_inputs_benchmark_wrapper) $(benchmarks_protoc_inputs_proto2) ) + touch proto3_proto_middleman + +generate_proto3_data: protoc_middleman protoc_middleman2 proto3-data-stripper + mkdir -p `dirname $(proto3_data)` + ./proto3-data-stripper $(all_data) $(proto3_data) + touch generate_proto3_data + +############ PROTO3 PREPARATION END ############# + +############ PHP RULES BEGIN ################# + +proto3_middleman_php: proto3_proto_middleman + mkdir -p "tmp/php" + oldpwd=`pwd` && ( cd tmp/proto3_proto && $$oldpwd/../src/protoc$(EXEEXT) -I$(srcdir) -I$(top_srcdir) --php_out=$$oldpwd/tmp/php $(benchmarks_protoc_inputs) $(benchmarks_protoc_inputs_benchmark_wrapper) $(benchmarks_protoc_inputs_proto2) ) + touch proto3_middleman_php + +php-benchmark: proto3_middleman_php generate_proto3_data + mkdir -p "tmp/php/Google/Protobuf/Benchmark" && cp php/PhpBenchmark.php "tmp/php/Google/Protobuf/Benchmark" + cp php/autoload.php "tmp/php" + @echo "Writing shortcut script php-benchmark..." + @echo '#! /bin/bash' > php-benchmark + @echo 'export PROTOBUF_PHP_SRCDIR="$$(cd $(top_srcdir) && pwd)/php/src"' >> php-benchmark + @echo 'cd tmp/php' >> php-benchmark + @echo 'export CURRENT_DIR=$$(pwd)' >> php-benchmark + @echo 'php -d auto_prepend_file="autoload.php" -d include_path="$$(pwd)" Google/Protobuf/Benchmark/PhpBenchmark.php $$@' >> php-benchmark + @echo 'cd ../..' >> php-benchmark + @chmod +x php-benchmark + +php: php-benchmark proto3_middleman_php + ./php-benchmark --behavior_prefix="php" $(proto3_data) + +php_c_extension: + cd $(top_srcdir)/php/ext/google/protobuf && phpize && ./configure CFLAGS='-O3' && make -j8 + +php-c-benchmark: proto3_middleman_php generate_proto3_data php_c_extension php_c_extension + mkdir -p "tmp/php/Google/Protobuf/Benchmark" && cp php/PhpBenchmark.php "tmp/php/Google/Protobuf/Benchmark" + cp php/autoload.php "tmp/php" + @echo "Writing shortcut script php-c-benchmark..." + @echo '#! /bin/bash' > php-c-benchmark + @echo 'export PROTOBUF_PHP_SRCDIR="$$(cd $(top_srcdir) && pwd)/php/src"' >> php-c-benchmark + @echo 'export PROTOBUF_PHP_EXTDIR="$$PROTOBUF_PHP_SRCDIR/../ext/google/protobuf/modules"' >> php-c-benchmark + @echo 'cd tmp/php' >> php-c-benchmark + @echo 'export CURRENT_DIR=$$(pwd)' >> php-c-benchmark + @echo 'php -d auto_prepend_file="autoload.php" -d include_path="$$(pwd)" -d extension="$$PROTOBUF_PHP_EXTDIR/protobuf.so" Google/Protobuf/Benchmark/PhpBenchmark.php $$@' >> php-c-benchmark + @echo 'cd ../..' >> php-c-benchmark + @chmod +x php-c-benchmark + +php_c: php-c-benchmark proto3_middleman_php + ./php-c-benchmark --behavior_prefix="php_c" $(proto3_data) + +############ PHP RULES END ################# + +############ protobuf.js RULE BEGIN ############# + +pbjs_preparation: + mkdir -p tmp/protobuf.js + cd tmp/protobuf.js && git clone https://github.com/dcodeIO/protobuf.js.git && \ + cd protobuf.js && npm install && npm run build + cd tmp/protobuf.js && npm install benchmark + cp protobuf.js/* tmp/protobuf.js + cp js/benchmark_suite.js tmp/protobuf.js + touch pbjs_preparation + +pbjs_middleman: pbjs_preparation + export OLDDIR=$$(pwd) && cd tmp/protobuf.js && node generate_pbjs_files.js --target static-module --include_path=$$OLDDIR -o generated_bundle_code.js $(benchmarks_protoc_inputs) $(benchmarks_protoc_inputs_benchmark_wrapper) $(benchmarks_protoc_inputs_proto2) + touch pbjs_middleman + +pbjs-benchmark: pbjs_middleman + @echo '#! /bin/bash' > pbjs-benchmark + @echo 'cd tmp/protobuf.js' >> pbjs-benchmark + @echo 'sed -i "s/protobufjs/.\/protobuf.js/g" generated_bundle_code.js' >> pbjs-benchmark + @echo 'env NODE_PATH=".:./node_modules:$$NODE_PATH" node protobufjs_benchmark.js $$@' >> pbjs-benchmark + @chmod +x pbjs-benchmark + +pbjs: pbjs-benchmark + ./pbjs-benchmark $(all_data) + +############ protobuf.js RULE END ############# + +############ JS RULE BEGIN ############# + +js_preparation: + mkdir -p tmp/js + oldpwd=$$(pwd) && cd $(top_srcdir)/js && npm install && npm test + cd tmp/js && npm install benchmark + cp js/* tmp/js + touch js_preparation + +js_middleman: js_preparation + oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --js_out=import_style=commonjs,binary:$$oldpwd/tmp/js $(benchmarks_protoc_inputs) $(benchmarks_protoc_inputs_benchmark_wrapper) $(benchmarks_protoc_inputs_proto2)) + touch js_middleman + +js-benchmark: js_middleman + @echo '#! /bin/bash' > js-benchmark + @echo 'export TOP_JS_SRCDIR=$$(cd $(top_srcdir)/js && pwd)' >> js-benchmark + @echo 'cd tmp/js' >> js-benchmark + @echo 'env NODE_PATH="$$TOP_JS_SRCDIR:.:./node_modules:$$NODE_PATH" node --max-old-space-size=4096 js_benchmark.js $$@' >> js-benchmark + @chmod +x js-benchmark + +js: js-benchmark + ./js-benchmark $(all_data) clean-local: -rm -rf tmp/* diff --git a/third_party/protobuf/benchmarks/cpp/cpp_benchmark.cc b/third_party/protobuf/benchmarks/cpp/cpp_benchmark.cc index f8b55291..036d234f 100644 --- a/third_party/protobuf/benchmarks/cpp/cpp_benchmark.cc +++ b/third_party/protobuf/benchmarks/cpp/cpp_benchmark.cc @@ -30,7 +30,7 @@ #include #include -#include "benchmark/benchmark_api.h" +#include "benchmark/benchmark.h" #include "benchmarks.pb.h" #include "datasets/google_message1/proto2/benchmark_message1_proto2.pb.h" #include "datasets/google_message1/proto3/benchmark_message1_proto3.pb.h" diff --git a/third_party/protobuf/benchmarks/gogo/cpp_no_group/cpp_benchmark.cc b/third_party/protobuf/benchmarks/gogo/cpp_no_group/cpp_benchmark.cc index 3687c5ee..84acd804 100644 --- a/third_party/protobuf/benchmarks/gogo/cpp_no_group/cpp_benchmark.cc +++ b/third_party/protobuf/benchmarks/gogo/cpp_no_group/cpp_benchmark.cc @@ -30,7 +30,7 @@ #include #include -#include "benchmark/benchmark_api.h" +#include "benchmark/benchmark.h" #include "gogo/cpp_no_group/benchmarks.pb.h" #include "gogo/cpp_no_group/datasets/google_message1/proto2/benchmark_message1_proto2.pb.h" #include "gogo/cpp_no_group/datasets/google_message1/proto3/benchmark_message1_proto3.pb.h" diff --git a/third_party/protobuf/benchmarks/util/gogo_data_scrubber.cc b/third_party/protobuf/benchmarks/util/gogo_data_scrubber.cc index fb9af6e2..9ef57b0d 100644 --- a/third_party/protobuf/benchmarks/util/gogo_data_scrubber.cc +++ b/third_party/protobuf/benchmarks/util/gogo_data_scrubber.cc @@ -4,43 +4,11 @@ #include "datasets/google_message2/benchmark_message2.pb.h" #include "datasets/google_message3/benchmark_message3.pb.h" #include "datasets/google_message4/benchmark_message4.pb.h" - -#include "google/protobuf/message.h" -#include "google/protobuf/descriptor.h" +#include "data_proto2_to_proto3_util.h" #include -using google::protobuf::FieldDescriptor; -using google::protobuf::Message; -using google::protobuf::Reflection; - - -class DataGroupStripper { - public: - static void StripMessage(Message *message) { - std::vector set_fields; - const Reflection* reflection = message->GetReflection(); - reflection->ListFields(*message, &set_fields); - - for (size_t i = 0; i < set_fields.size(); i++) { - const FieldDescriptor* field = set_fields[i]; - if (field->type() == FieldDescriptor::TYPE_GROUP) { - reflection->ClearField(message, field); - } - if (field->type() == FieldDescriptor::TYPE_MESSAGE) { - if (field->is_repeated()) { - for (int j = 0; j < reflection->FieldSize(*message, field); j++) { - StripMessage(reflection->MutableRepeatedMessage(message, field, j)); - } - } else { - StripMessage(reflection->MutableMessage(message, field)); - } - } - } - - reflection->MutableUnknownFields(message)->Clear(); - } -}; +using google::protobuf::util::GogoDataStripper; std::string ReadFile(const std::string& name) { std::ifstream file(name.c_str()); @@ -91,7 +59,8 @@ int main(int argc, char *argv[]) { for (int i = 0; i < dataset.payload_size(); i++) { message->ParseFromString(dataset.payload(i)); - DataGroupStripper::StripMessage(message); + GogoDataStripper stripper; + stripper.StripMessage(message); dataset.set_payload(i, message->SerializeAsString()); } diff --git a/third_party/protobuf/benchmarks/util/proto3_data_stripper.cc b/third_party/protobuf/benchmarks/util/proto3_data_stripper.cc new file mode 100644 index 00000000..3096c4c1 --- /dev/null +++ b/third_party/protobuf/benchmarks/util/proto3_data_stripper.cc @@ -0,0 +1,74 @@ +#include "benchmarks.pb.h" +#include "datasets/google_message1/proto2/benchmark_message1_proto2.pb.h" +#include "datasets/google_message1/proto3/benchmark_message1_proto3.pb.h" +#include "datasets/google_message2/benchmark_message2.pb.h" +#include "datasets/google_message3/benchmark_message3.pb.h" +#include "datasets/google_message4/benchmark_message4.pb.h" +#include "data_proto2_to_proto3_util.h" + +#include + +using google::protobuf::util::Proto3DataStripper; + +std::string ReadFile(const std::string& name) { + std::ifstream file(name.c_str()); + GOOGLE_CHECK(file.is_open()) << "Couldn't find file '" + << name + << "', please make sure you are running this command from the benchmarks" + << " directory.\n"; + return std::string((std::istreambuf_iterator(file)), + std::istreambuf_iterator()); +} + +int main(int argc, char *argv[]) { + if (argc % 2 == 0 || argc == 1) { + std::cerr << "Usage: [input_files] [output_file_names] where " << + "input_files are one to one mapping to output_file_names." << + std::endl; + return 1; + } + + for (int i = argc / 2; i > 0; i--) { + const std::string &input_file = argv[i]; + const std::string &output_file = argv[i + argc / 2]; + + std::cerr << "Generating " << input_file + << " to " << output_file << std::endl; + benchmarks::BenchmarkDataset dataset; + Message* message; + std::string dataset_payload = ReadFile(input_file); + GOOGLE_CHECK(dataset.ParseFromString(dataset_payload)) + << "Can' t parse data file " << input_file; + + if (dataset.message_name() == "benchmarks.proto3.GoogleMessage1") { + message = new benchmarks::proto3::GoogleMessage1; + } else if (dataset.message_name() == "benchmarks.proto2.GoogleMessage1") { + message = new benchmarks::proto2::GoogleMessage1; + } else if (dataset.message_name() == "benchmarks.proto2.GoogleMessage2") { + message = new benchmarks::proto2::GoogleMessage2; + } else if (dataset.message_name() == + "benchmarks.google_message3.GoogleMessage3") { + message = new benchmarks::google_message3::GoogleMessage3; + } else if (dataset.message_name() == + "benchmarks.google_message4.GoogleMessage4") { + message = new benchmarks::google_message4::GoogleMessage4; + } else { + std::cerr << "Unknown message type: " << dataset.message_name(); + exit(1); + } + + for (int i = 0; i < dataset.payload_size(); i++) { + message->ParseFromString(dataset.payload(i)); + Proto3DataStripper stripper; + stripper.StripMessage(message); + dataset.set_payload(i, message->SerializeAsString()); + } + + std::ofstream ofs(output_file); + ofs << dataset.SerializeAsString(); + ofs.close(); + } + + + return 0; +} diff --git a/third_party/protobuf/benchmarks/util/protoc-gen-gogoproto.cc b/third_party/protobuf/benchmarks/util/protoc-gen-gogoproto.cc index bfa6a5e5..9c1b3d04 100644 --- a/third_party/protobuf/benchmarks/util/protoc-gen-gogoproto.cc +++ b/third_party/protobuf/benchmarks/util/protoc-gen-gogoproto.cc @@ -12,7 +12,7 @@ using google::protobuf::FileDescriptor; using google::protobuf::DescriptorPool; using google::protobuf::io::Printer; using google::protobuf::util::SchemaGroupStripper; -using google::protobuf::util::SchemaAddZeroEnumValue; +using google::protobuf::util::EnumScrubber; namespace google { namespace protobuf { @@ -74,7 +74,7 @@ class GoGoProtoGenerator : public CodeGenerator { file->CopyTo(&new_file); SchemaGroupStripper::StripFile(file, &new_file); - SchemaAddZeroEnumValue enum_scrubber; + EnumScrubber enum_scrubber; enum_scrubber.ScrubFile(&new_file); string filename = file->name(); diff --git a/third_party/protobuf/benchmarks/util/protoc-gen-proto2_to_proto3.cc b/third_party/protobuf/benchmarks/util/protoc-gen-proto2_to_proto3.cc new file mode 100644 index 00000000..d0a89023 --- /dev/null +++ b/third_party/protobuf/benchmarks/util/protoc-gen-proto2_to_proto3.cc @@ -0,0 +1,115 @@ +#include "google/protobuf/compiler/code_generator.h" +#include "google/protobuf/io/zero_copy_stream.h" +#include "google/protobuf/io/printer.h" +#include "google/protobuf/descriptor.h" +#include "google/protobuf/descriptor.pb.h" +#include "schema_proto2_to_proto3_util.h" + +#include "google/protobuf/compiler/plugin.h" + +using google::protobuf::FileDescriptorProto; +using google::protobuf::FileDescriptor; +using google::protobuf::DescriptorPool; +using google::protobuf::io::Printer; +using google::protobuf::util::SchemaGroupStripper; +using google::protobuf::util::EnumScrubber; +using google::protobuf::util::ExtensionStripper; +using google::protobuf::util::FieldScrubber; + +namespace google { +namespace protobuf { +namespace compiler { + +namespace { + +string StripProto(string filename) { + return filename.substr(0, filename.rfind(".proto")); +} + +DescriptorPool* GetPool() { + static DescriptorPool *pool = new DescriptorPool(); + return pool; +} + +} // namespace + +class Proto2ToProto3Generator final : public CodeGenerator { + public: + bool GenerateAll(const std::vector& files, + const string& parameter, + GeneratorContext* context, + string* error) const { + for (int i = 0; i < files.size(); i++) { + for (auto file : files) { + if (CanGenerate(file)) { + Generate(file, parameter, context, error); + break; + } + } + } + + return true; + } + + bool Generate(const FileDescriptor* file, + const string& parameter, + GeneratorContext* context, + string* error) const { + FileDescriptorProto new_file; + file->CopyTo(&new_file); + SchemaGroupStripper::StripFile(file, &new_file); + + EnumScrubber enum_scrubber; + enum_scrubber.ScrubFile(&new_file); + ExtensionStripper::StripFile(&new_file); + FieldScrubber::ScrubFile(&new_file); + new_file.set_syntax("proto3"); + + string filename = file->name(); + string basename = StripProto(filename); + + std::vector> option_pairs; + ParseGeneratorParameter(parameter, &option_pairs); + + std::unique_ptr output( + context->Open(basename + ".proto")); + string content = GetPool()->BuildFile(new_file)->DebugString(); + Printer printer(output.get(), '$'); + printer.WriteRaw(content.c_str(), content.size()); + + return true; + } + private: + bool CanGenerate(const FileDescriptor* file) const { + if (GetPool()->FindFileByName(file->name()) != nullptr) { + return false; + } + for (int j = 0; j < file->dependency_count(); j++) { + if (GetPool()->FindFileByName(file->dependency(j)->name()) == nullptr) { + return false; + } + } + for (int j = 0; j < file->public_dependency_count(); j++) { + if (GetPool()->FindFileByName( + file->public_dependency(j)->name()) == nullptr) { + return false; + } + } + for (int j = 0; j < file->weak_dependency_count(); j++) { + if (GetPool()->FindFileByName( + file->weak_dependency(j)->name()) == nullptr) { + return false; + } + } + return true; + } +}; + +} // namespace compiler +} // namespace protobuf +} // namespace google + +int main(int argc, char* argv[]) { + google::protobuf::compiler::Proto2ToProto3Generator generator; + return google::protobuf::compiler::PluginMain(argc, argv, &generator); +} diff --git a/third_party/protobuf/cmake/CMakeLists.txt b/third_party/protobuf/cmake/CMakeLists.txt index 02174e96..71a0f37a 100644 --- a/third_party/protobuf/cmake/CMakeLists.txt +++ b/third_party/protobuf/cmake/CMakeLists.txt @@ -7,7 +7,11 @@ endif() # CMake policies cmake_policy(SET CMP0022 NEW) - +# On MacOS use @rpath/ for target's install name prefix path +if (POLICY CMP0042) + cmake_policy(SET CMP0042 NEW) +endif () +# Clear VERSION variables when no VERSION is given to project() if(POLICY CMP0048) cmake_policy(SET CMP0048 NEW) endif() @@ -26,6 +30,7 @@ endif() # Options option(protobuf_BUILD_TESTS "Build tests" ON) +option(protobuf_BUILD_CONFORMANCE "Build conformance tests" OFF) option(protobuf_BUILD_EXAMPLES "Build examples" OFF) option(protobuf_BUILD_PROTOC_BINARIES "Build libprotoc and protoc compiler" ON) if (BUILD_SHARED_LIBS) @@ -63,23 +68,28 @@ string(REGEX REPLACE "${protobuf_AC_INIT_REGEX}" "\\2" string(REGEX REPLACE "${protobuf_AC_INIT_REGEX}" "\\3" protobuf_CONTACT "${protobuf_AC_INIT_LINE}") # Parse version tweaks -set(protobuf_VERSION_REGEX "^([0-9]+)\\.([0-9]+)\\.([0-9]+)-?(.*)$") +set(protobuf_VERSION_REGEX "^([0-9]+)\\.([0-9]+)\\.([0-9]+)([-]rc[-]|\\.)?([0-9]*)$") string(REGEX REPLACE "${protobuf_VERSION_REGEX}" "\\1" protobuf_VERSION_MAJOR "${protobuf_VERSION_STRING}") string(REGEX REPLACE "${protobuf_VERSION_REGEX}" "\\2" protobuf_VERSION_MINOR "${protobuf_VERSION_STRING}") string(REGEX REPLACE "${protobuf_VERSION_REGEX}" "\\3" protobuf_VERSION_PATCH "${protobuf_VERSION_STRING}") -string(REGEX REPLACE "${protobuf_VERSION_REGEX}" "\\4" +string(REGEX REPLACE "${protobuf_VERSION_REGEX}" "\\5" protobuf_VERSION_PRERELEASE "${protobuf_VERSION_STRING}") +message(STATUS "${protobuf_VERSION_PRERELEASE}") + # Package version set(protobuf_VERSION "${protobuf_VERSION_MAJOR}.${protobuf_VERSION_MINOR}.${protobuf_VERSION_PATCH}") if(protobuf_VERSION_PRERELEASE) - set(protobuf_VERSION "${protobuf_VERSION}-${protobuf_VERSION_PRERELEASE}") + set(protobuf_VERSION "${protobuf_VERSION}.${protobuf_VERSION_PRERELEASE}") +else() + set(protobuf_VERSION "${protobuf_VERSION}.0") endif() +message(STATUS "${protobuf_VERSION}") if(protobuf_VERBOSE) message(STATUS "Configuration script parsing status [") @@ -166,12 +176,23 @@ if (MSVC) add_definitions(/bigobj) string(REPLACE "/" "\\" PROTOBUF_SOURCE_WIN32_PATH ${protobuf_SOURCE_DIR}) string(REPLACE "/" "\\" PROTOBUF_BINARY_WIN32_PATH ${protobuf_BINARY_DIR}) + string(REPLACE "." "," protobuf_RC_FILEVERSION "${protobuf_VERSION}") configure_file(extract_includes.bat.in extract_includes.bat) # Suppress linker warnings about files with no symbols defined. set(CMAKE_STATIC_LINKER_FLAGS /ignore:4221) + + # Configure Resource Compiler + enable_language(RC) + # use English language (0x409) in resource compiler + set(rc_flags "/l0x409") + # fix rc.exe invocations because of usage of add_definitions() + set(CMAKE_RC_COMPILE_OBJECT " ${rc_flags} /fo ") + + configure_file(version.rc.in ${CMAKE_CURRENT_BINARY_DIR}/version.rc @ONLY) endif (MSVC) + get_filename_component(protobuf_source_dir ${protobuf_SOURCE_DIR} PATH) include_directories( @@ -203,6 +224,10 @@ if (protobuf_BUILD_TESTS) include(tests.cmake) endif (protobuf_BUILD_TESTS) +if (protobuf_BUILD_CONFORMANCE) + include(conformance.cmake) +endif (protobuf_BUILD_CONFORMANCE) + include(install.cmake) if (protobuf_BUILD_EXAMPLES) diff --git a/third_party/protobuf/cmake/README.md b/third_party/protobuf/cmake/README.md index 26a516c7..96aaf4f9 100644 --- a/third_party/protobuf/cmake/README.md +++ b/third_party/protobuf/cmake/README.md @@ -43,7 +43,7 @@ Getting Sources You can get the latest stable source packages from the release page: - https://github.com/google/protobuf/releases/latest + https://github.com/protocolbuffers/protobuf/releases/latest For example: if you only need C++, download `protobuf-cpp-[VERSION].tar.gz`; if you need C++ and Java, download `protobuf-java-[VERSION].tar.gz` (every package @@ -52,7 +52,7 @@ download `protobuf-all-[VERSION].tar.gz`. Or you can use git to clone from protobuf git repository. - C:\Path\to> git clone -b [release_tag] https://github.com/google/protobuf.git + C:\Path\to> git clone -b [release_tag] https://github.com/protocolbuffers/protobuf.git Where *[release_tag]* is a git tag like *v3.0.0-beta-1* or a branch name like *master* if you want to get the latest code. @@ -130,6 +130,13 @@ It will generate *Visual Studio* solution file *protobuf.sln* in current directo If the *gmock* directory does not exist, and you do not want to build protobuf unit tests, you need to add *cmake* command argument `-Dprotobuf_BUILD_TESTS=OFF` to disable testing. +To make a *Visual Studio* file for Visual Studio 15 2017, create the *Visual Studio* +solution file above and edit the CmakeCache file. + + C:Path\to\protobuf\cmake\build\solution\CMakeCache + +Then create the *Visual Studio* solution file again + Compiling ========= @@ -170,9 +177,9 @@ You should see output similar to: Running main() from gmock_main.cc [==========] Running 1546 tests from 165 test cases. - + ... - + [==========] 1546 tests from 165 test cases ran. (2529 ms total) [ PASSED ] 1546 tests. @@ -191,7 +198,7 @@ To run specific tests: [ RUN ] AnyTest.TestIs [ OK ] AnyTest.TestIs (0 ms) [----------] 3 tests from AnyTest (1 ms total) - + [----------] Global test environment tear-down [==========] 3 tests from 1 test case ran. (2 ms total) [ PASSED ] 3 tests. @@ -303,7 +310,7 @@ If you already have ZLIB library and headers at some other location on your syst -DZLIB_INCLUDE_DIR= -DZLIB_LIB= - + Build and testing protobuf as usual. Notes on Compiler Warnings diff --git a/third_party/protobuf/cmake/conformance.cmake b/third_party/protobuf/cmake/conformance.cmake new file mode 100644 index 00000000..82b4cf58 --- /dev/null +++ b/third_party/protobuf/cmake/conformance.cmake @@ -0,0 +1,50 @@ + +add_custom_command( + OUTPUT ${protobuf_source_dir}/conformance/conformance.pb.cc + DEPENDS protoc ${protobuf_source_dir}/conformance/conformance.proto + COMMAND protoc ${protobuf_source_dir}/conformance/conformance.proto + --proto_path=${protobuf_source_dir}/conformance + --cpp_out=${protobuf_source_dir}/conformance +) + +add_custom_command( + OUTPUT ${protobuf_source_dir}/src/google/protobuf/test_messages_proto3.pb.cc + ${protobuf_source_dir}/src/google/protobuf/test_messages_proto2.pb.cc + DEPENDS protoc ${protobuf_source_dir}/src/google/protobuf/test_messages_proto3.proto + protoc ${protobuf_source_dir}/src/google/protobuf/test_messages_proto2.proto + COMMAND protoc ${protobuf_source_dir}/src/google/protobuf/test_messages_proto3.proto + ${protobuf_source_dir}/src/google/protobuf/test_messages_proto2.proto + --proto_path=${protobuf_source_dir}/src + --cpp_out=${protobuf_source_dir}/src +) + +add_executable(conformance_test_runner + ${protobuf_source_dir}/conformance/conformance.pb.cc + ${protobuf_source_dir}/conformance/conformance_test.cc + ${protobuf_source_dir}/conformance/binary_json_conformance_main.cc + ${protobuf_source_dir}/conformance/binary_json_conformance_suite.cc + ${protobuf_source_dir}/conformance/binary_json_conformance_suite.h + ${protobuf_source_dir}/conformance/conformance_test_runner.cc + ${protobuf_source_dir}/conformance/third_party/jsoncpp/json.h + ${protobuf_source_dir}/conformance/third_party/jsoncpp/jsoncpp.cpp + ${protobuf_source_dir}/src/google/protobuf/test_messages_proto3.pb.cc + ${protobuf_source_dir}/src/google/protobuf/test_messages_proto2.pb.cc +) + +add_executable(conformance_cpp + ${protobuf_source_dir}/conformance/conformance.pb.cc + ${protobuf_source_dir}/conformance/conformance_cpp.cc + ${protobuf_source_dir}/src/google/protobuf/test_messages_proto3.pb.cc + ${protobuf_source_dir}/src/google/protobuf/test_messages_proto2.pb.cc +) + +target_include_directories( + conformance_test_runner + PUBLIC ${protobuf_source_dir}/conformance) + +target_include_directories( + conformance_cpp + PUBLIC ${protobuf_source_dir}/conformance) + +target_link_libraries(conformance_test_runner libprotobuf) +target_link_libraries(conformance_cpp libprotobuf) diff --git a/third_party/protobuf/cmake/extract_includes.bat.in b/third_party/protobuf/cmake/extract_includes.bat.in index 9fd9de0d..c9a1524b 100644 --- a/third_party/protobuf/cmake/extract_includes.bat.in +++ b/third_party/protobuf/cmake/extract_includes.bat.in @@ -44,6 +44,7 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\duration.pb.h" includ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\dynamic_message.h" include\google\protobuf\dynamic_message.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\empty.pb.h" include\google\protobuf\empty.pb.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\extension_set.h" include\google\protobuf\extension_set.h +copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\extension_set_inl.h" include\google\protobuf\extension_set_inl.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\field_mask.pb.h" include\google\protobuf\field_mask.pb.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_enum_reflection.h" include\google\protobuf\generated_enum_reflection.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_enum_util.h" include\google\protobuf\generated_enum_util.h @@ -72,6 +73,10 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\message.h" include\go copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\message_lite.h" include\google\protobuf\message_lite.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\metadata.h" include\google\protobuf\metadata.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\metadata_lite.h" include\google\protobuf\metadata_lite.h +copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\parse_context.h" include\google\protobuf\parse_context.h +copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\port.h" include\google\protobuf\port.h +copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\port_def.inc" include\google\protobuf\port_def.inc +copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\port_undef.inc" include\google\protobuf\port_undef.inc copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\reflection.h" include\google\protobuf\reflection.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\reflection_ops.h" include\google\protobuf\reflection_ops.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\repeated_field.h" include\google\protobuf\repeated_field.h @@ -84,16 +89,17 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\casts.h" includ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\common.h" include\google\protobuf\stubs\common.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\fastmem.h" include\google\protobuf\stubs\fastmem.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\hash.h" include\google\protobuf\stubs\hash.h +copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\io_win32.h" include\google\protobuf\stubs\io_win32.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\logging.h" include\google\protobuf\stubs\logging.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\macros.h" include\google\protobuf\stubs\macros.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\mutex.h" include\google\protobuf\stubs\mutex.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\once.h" include\google\protobuf\stubs\once.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\platform_macros.h" include\google\protobuf\stubs\platform_macros.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\port.h" include\google\protobuf\stubs\port.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\singleton.h" include\google\protobuf\stubs\singleton.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\status.h" include\google\protobuf\stubs\status.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\stl_util.h" include\google\protobuf\stubs\stl_util.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\stringpiece.h" include\google\protobuf\stubs\stringpiece.h +copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\strutil.h" include\google\protobuf\stubs\strutil.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\template_util.h" include\google\protobuf\stubs\template_util.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\text_format.h" include\google\protobuf\text_format.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\timestamp.pb.h" include\google\protobuf\timestamp.pb.h @@ -109,7 +115,6 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\util\type_resolver.h" copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\util\type_resolver_util.h" include\google\protobuf\util\type_resolver_util.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\wire_format.h" include\google\protobuf\wire_format.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\wire_format_lite.h" include\google\protobuf\wire_format_lite.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\wire_format_lite_inl.h" include\google\protobuf\wire_format_lite_inl.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\wrappers.pb.h" include\google\protobuf\wrappers.pb.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\any.proto" include\google\protobuf\any.proto copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\api.proto" include\google\protobuf\api.proto diff --git a/third_party/protobuf/cmake/install.cmake b/third_party/protobuf/cmake/install.cmake index 82036cb6..9b2ae93c 100644 --- a/third_party/protobuf/cmake/install.cmake +++ b/third_party/protobuf/cmake/install.cmake @@ -15,6 +15,13 @@ foreach(_library ${_protobuf_libraries}) PROPERTY INTERFACE_INCLUDE_DIRECTORIES $ $) + if (UNIX AND NOT APPLE) + set_property(TARGET ${_library} + PROPERTY INSTALL_RPATH "$ORIGIN") + elseif (APPLE) + set_property(TARGET ${_library} + PROPERTY INSTALL_RPATH "@loader_path") + endif() install(TARGETS ${_library} EXPORT protobuf-targets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT ${_library} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT ${_library} @@ -24,6 +31,13 @@ endforeach() if (protobuf_BUILD_PROTOC_BINARIES) install(TARGETS protoc EXPORT protobuf-targets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT protoc) + if (UNIX AND NOT APPLE) + set_property(TARGET protoc + PROPERTY INSTALL_RPATH "$ORIGIN/../lib") + elseif (APPLE) + set_property(TARGET protoc + PROPERTY INSTALL_RPATH "@loader_path/../lib") + endif() endif (protobuf_BUILD_PROTOC_BINARIES) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/protobuf.pc ${CMAKE_CURRENT_BINARY_DIR}/protobuf-lite.pc DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") diff --git a/third_party/protobuf/cmake/libprotobuf-lite.cmake b/third_party/protobuf/cmake/libprotobuf-lite.cmake index 911fce5e..652eb91c 100644 --- a/third_party/protobuf/cmake/libprotobuf-lite.cmake +++ b/third_party/protobuf/cmake/libprotobuf-lite.cmake @@ -1,19 +1,21 @@ set(libprotobuf_lite_files + ${protobuf_source_dir}/src/google/protobuf/any_lite.cc ${protobuf_source_dir}/src/google/protobuf/arena.cc - ${protobuf_source_dir}/src/google/protobuf/arenastring.cc ${protobuf_source_dir}/src/google/protobuf/extension_set.cc ${protobuf_source_dir}/src/google/protobuf/generated_message_table_driven_lite.cc ${protobuf_source_dir}/src/google/protobuf/generated_message_util.cc ${protobuf_source_dir}/src/google/protobuf/implicit_weak_message.cc ${protobuf_source_dir}/src/google/protobuf/io/coded_stream.cc + ${protobuf_source_dir}/src/google/protobuf/io/io_win32.cc + ${protobuf_source_dir}/src/google/protobuf/io/strtod.cc ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream.cc ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream_impl_lite.cc ${protobuf_source_dir}/src/google/protobuf/message_lite.cc + ${protobuf_source_dir}/src/google/protobuf/parse_context.cc ${protobuf_source_dir}/src/google/protobuf/repeated_field.cc ${protobuf_source_dir}/src/google/protobuf/stubs/bytestream.cc ${protobuf_source_dir}/src/google/protobuf/stubs/common.cc ${protobuf_source_dir}/src/google/protobuf/stubs/int128.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/io_win32.cc ${protobuf_source_dir}/src/google/protobuf/stubs/status.cc ${protobuf_source_dir}/src/google/protobuf/stubs/statusor.cc ${protobuf_source_dir}/src/google/protobuf/stubs/stringpiece.cc @@ -30,7 +32,9 @@ set(libprotobuf_lite_includes ${protobuf_source_dir}/src/google/protobuf/extension_set.h ${protobuf_source_dir}/src/google/protobuf/generated_message_util.h ${protobuf_source_dir}/src/google/protobuf/implicit_weak_message.h + ${protobuf_source_dir}/src/google/protobuf/parse_context.h ${protobuf_source_dir}/src/google/protobuf/io/coded_stream.h + ${protobuf_source_dir}/src/google/protobuf/io/strtod.h ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream.h ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream_impl_lite.h ${protobuf_source_dir}/src/google/protobuf/message_lite.h @@ -48,8 +52,14 @@ set(libprotobuf_lite_includes ${protobuf_source_dir}/src/google/protobuf/wire_format_lite.h ) +if (MSVC) +set(libprotobuf_lite_rc_files + ${CMAKE_CURRENT_BINARY_DIR}/version.rc +) +endif() + add_library(libprotobuf-lite ${protobuf_SHARED_OR_STATIC} - ${libprotobuf_lite_files} ${libprotobuf_lite_includes}) + ${libprotobuf_lite_files} ${libprotobuf_lite_includes} ${libprotobuf_lite_rc_files}) target_link_libraries(libprotobuf-lite ${CMAKE_THREAD_LIBS_INIT}) target_include_directories(libprotobuf-lite PUBLIC ${protobuf_source_dir}/src) if(MSVC AND protobuf_BUILD_SHARED_LIBS) diff --git a/third_party/protobuf/cmake/libprotobuf.cmake b/third_party/protobuf/cmake/libprotobuf.cmake index 65d05c19..9a434a7d 100644 --- a/third_party/protobuf/cmake/libprotobuf.cmake +++ b/third_party/protobuf/cmake/libprotobuf.cmake @@ -16,7 +16,6 @@ set(libprotobuf_files ${protobuf_source_dir}/src/google/protobuf/generated_message_table_driven.cc ${protobuf_source_dir}/src/google/protobuf/io/gzip_stream.cc ${protobuf_source_dir}/src/google/protobuf/io/printer.cc - ${protobuf_source_dir}/src/google/protobuf/io/strtod.cc ${protobuf_source_dir}/src/google/protobuf/io/tokenizer.cc ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream_impl.cc ${protobuf_source_dir}/src/google/protobuf/map_field.cc @@ -72,7 +71,6 @@ set(libprotobuf_includes ${protobuf_source_dir}/src/google/protobuf/generated_message_reflection.h ${protobuf_source_dir}/src/google/protobuf/io/gzip_stream.h ${protobuf_source_dir}/src/google/protobuf/io/printer.h - ${protobuf_source_dir}/src/google/protobuf/io/strtod.h ${protobuf_source_dir}/src/google/protobuf/io/tokenizer.h ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream_impl.h ${protobuf_source_dir}/src/google/protobuf/map_field.h @@ -112,8 +110,14 @@ set(libprotobuf_includes ${protobuf_source_dir}/src/google/protobuf/wrappers.pb.h ) +if (MSVC) +set(libprotobuf_rc_files + ${CMAKE_CURRENT_BINARY_DIR}/version.rc +) +endif() + add_library(libprotobuf ${protobuf_SHARED_OR_STATIC} - ${libprotobuf_lite_files} ${libprotobuf_files} ${libprotobuf_includes}) + ${libprotobuf_lite_files} ${libprotobuf_files} ${libprotobuf_includes} ${libprotobuf_rc_files}) target_link_libraries(libprotobuf ${CMAKE_THREAD_LIBS_INIT}) if(protobuf_WITH_ZLIB) target_link_libraries(libprotobuf ${ZLIB_LIBRARIES}) diff --git a/third_party/protobuf/cmake/libprotoc.cmake b/third_party/protobuf/cmake/libprotoc.cmake index 58568bb2..b71f2f1b 100644 --- a/third_party/protobuf/cmake/libprotoc.cmake +++ b/third_party/protobuf/cmake/libprotoc.cmake @@ -44,8 +44,6 @@ set(libprotoc_files ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_generator.cc ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_generator_factory.cc ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_helpers.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_lazy_message_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_lazy_message_field_lite.cc ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_map_field.cc ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_map_field_lite.cc ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message.cc @@ -128,8 +126,6 @@ set(libprotoc_headers ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_file.h ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_generator_factory.h ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_helpers.h - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_lazy_message_field.h - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_lazy_message_field_lite.h ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_map_field.h ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_map_field_lite.h ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message.h @@ -155,8 +151,10 @@ set(libprotoc_headers ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_map_field.h ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_message.h ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_message_field.h + ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_nsobject_methods.h ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_oneof.h ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.h + ${protobuf_source_dir}/src/google/protobuf/compiler/scc.h ${protobuf_source_dir}/src/google/protobuf/compiler/subprocess.h ${protobuf_source_dir}/src/google/protobuf/compiler/zip_writer.h ) @@ -168,7 +166,7 @@ set(libprotoc_rc_files endif() add_library(libprotoc ${protobuf_SHARED_OR_STATIC} - ${libprotoc_files} ${libprotoc_headers}) + ${libprotoc_files} ${libprotoc_headers} ${libprotoc_rc_files}) target_link_libraries(libprotoc libprotobuf) if(MSVC AND protobuf_BUILD_SHARED_LIBS) target_compile_definitions(libprotoc @@ -181,3 +179,4 @@ set_target_properties(libprotoc PROPERTIES OUTPUT_NAME ${LIB_PREFIX}protoc DEBUG_POSTFIX "${protobuf_DEBUG_POSTFIX}") add_library(protobuf::libprotoc ALIAS libprotoc) + diff --git a/third_party/protobuf/cmake/protobuf-config.cmake.in b/third_party/protobuf/cmake/protobuf-config.cmake.in index acedcc7a..29e39d88 100644 --- a/third_party/protobuf/cmake/protobuf-config.cmake.in +++ b/third_party/protobuf/cmake/protobuf-config.cmake.in @@ -11,7 +11,7 @@ function(protobuf_generate) include(CMakeParseArguments) set(_options APPEND_PATH) - set(_singleargs LANGUAGE OUT_VAR EXPORT_MACRO) + set(_singleargs LANGUAGE OUT_VAR EXPORT_MACRO PROTOC_OUT_DIR) if(COMMAND target_sources) list(APPEND _singleargs TARGET) endif() @@ -34,15 +34,19 @@ function(protobuf_generate) endif() string(TOLOWER ${protobuf_generate_LANGUAGE} protobuf_generate_LANGUAGE) + if(NOT protobuf_generate_PROTOC_OUT_DIR) + set(protobuf_generate_PROTOC_OUT_DIR ${CMAKE_CURRENT_BINARY_DIR}) + endif() + if(protobuf_generate_EXPORT_MACRO AND protobuf_generate_LANGUAGE STREQUAL cpp) set(_dll_export_decl "dllexport_decl=${protobuf_generate_EXPORT_MACRO}:") endif() - if(NOT protobuf_GENERATE_EXTENSIONS) + if(NOT protobuf_generate_GENERATE_EXTENSIONS) if(protobuf_generate_LANGUAGE STREQUAL cpp) - set(protobuf_GENERATE_EXTENSIONS .pb.h .pb.cc) + set(protobuf_generate_GENERATE_EXTENSIONS .pb.h .pb.cc) elseif(protobuf_generate_LANGUAGE STREQUAL python) - set(protobuf_GENERATE_EXTENSIONS _pb2.py) + set(protobuf_generate_GENERATE_EXTENSIONS _pb2.py) else() message(SEND_ERROR "Error: protobuf_generate given unknown Language ${LANGUAGE}, please provide a value for GENERATE_EXTENSIONS") return() @@ -88,19 +92,21 @@ function(protobuf_generate) set(_generated_srcs_all) foreach(_proto ${protobuf_generate_PROTOS}) get_filename_component(_abs_file ${_proto} ABSOLUTE) + get_filename_component(_abs_dir ${_abs_file} DIRECTORY) get_filename_component(_basename ${_proto} NAME_WE) + file(RELATIVE_PATH _rel_dir ${CMAKE_CURRENT_SOURCE_DIR} ${_abs_dir}) set(_generated_srcs) - foreach(_ext ${protobuf_GENERATE_EXTENSIONS}) - list(APPEND _generated_srcs "${CMAKE_CURRENT_BINARY_DIR}/${_basename}${_ext}") + foreach(_ext ${protobuf_generate_GENERATE_EXTENSIONS}) + list(APPEND _generated_srcs "${protobuf_generate_PROTOC_OUT_DIR}/${_rel_dir}/${_basename}${_ext}") endforeach() list(APPEND _generated_srcs_all ${_generated_srcs}) add_custom_command( OUTPUT ${_generated_srcs} COMMAND protobuf::protoc - ARGS --${protobuf_generate_LANGUAGE}_out ${_dll_export_decl}${CMAKE_CURRENT_BINARY_DIR} ${_protobuf_include_path} ${_abs_file} - DEPENDS ${ABS_FIL} protobuf::protoc + ARGS --${protobuf_generate_LANGUAGE}_out ${_dll_export_decl}${protobuf_generate_PROTOC_OUT_DIR} ${_protobuf_include_path} ${_abs_file} + DEPENDS ${_abs_file} protobuf::protoc COMMENT "Running ${protobuf_generate_LANGUAGE} protocol buffer compiler on ${_proto}" VERBATIM ) endforeach() diff --git a/third_party/protobuf/cmake/protoc.cmake b/third_party/protobuf/cmake/protoc.cmake index 5777b16e..f90e525e 100644 --- a/third_party/protobuf/cmake/protoc.cmake +++ b/third_party/protobuf/cmake/protoc.cmake @@ -2,6 +2,15 @@ set(protoc_files ${protobuf_source_dir}/src/google/protobuf/compiler/main.cc ) -add_executable(protoc ${protoc_files}) -target_link_libraries(protoc libprotobuf libprotoc) +if (MSVC) +set(protoc_rc_files + ${CMAKE_CURRENT_BINARY_DIR}/version.rc +) +endif() + +add_executable(protoc ${protoc_files} ${protoc_rc_files}) +target_link_libraries(protoc libprotoc libprotobuf) add_executable(protobuf::protoc ALIAS protoc) + +set_target_properties(protoc PROPERTIES + VERSION ${protobuf_VERSION}) diff --git a/third_party/protobuf/cmake/tests.cmake b/third_party/protobuf/cmake/tests.cmake index ec790e33..72269617 100644 --- a/third_party/protobuf/cmake/tests.cmake +++ b/third_party/protobuf/cmake/tests.cmake @@ -63,6 +63,7 @@ set(tests_protos google/protobuf/unittest_optimize_for.proto google/protobuf/unittest_preserve_unknown_enum.proto google/protobuf/unittest_preserve_unknown_enum2.proto + google/protobuf/unittest_proto3.proto google/protobuf/unittest_proto3_arena.proto google/protobuf/unittest_proto3_arena_lite.proto google/protobuf/unittest_proto3_lite.proto @@ -78,6 +79,7 @@ set(tests_protos google/protobuf/util/internal/testdata/struct.proto google/protobuf/util/internal/testdata/timestamp_duration.proto google/protobuf/util/internal/testdata/wrappers.proto + google/protobuf/util/json_format.proto google/protobuf/util/json_format_proto3.proto google/protobuf/util/message_differencer_unittest.proto ) @@ -154,6 +156,7 @@ set(tests_files ${protobuf_source_dir}/src/google/protobuf/extension_set_unittest.cc ${protobuf_source_dir}/src/google/protobuf/generated_message_reflection_unittest.cc ${protobuf_source_dir}/src/google/protobuf/io/coded_stream_unittest.cc + ${protobuf_source_dir}/src/google/protobuf/io/io_win32_unittest.cc ${protobuf_source_dir}/src/google/protobuf/io/printer_unittest.cc ${protobuf_source_dir}/src/google/protobuf/io/tokenizer_unittest.cc ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream_unittest.cc @@ -166,13 +169,13 @@ set(tests_files ${protobuf_source_dir}/src/google/protobuf/proto3_arena_lite_unittest.cc ${protobuf_source_dir}/src/google/protobuf/proto3_arena_unittest.cc ${protobuf_source_dir}/src/google/protobuf/proto3_lite_unittest.cc + ${protobuf_source_dir}/src/google/protobuf/proto3_lite_unittest.inc ${protobuf_source_dir}/src/google/protobuf/reflection_ops_unittest.cc ${protobuf_source_dir}/src/google/protobuf/repeated_field_reflection_unittest.cc ${protobuf_source_dir}/src/google/protobuf/repeated_field_unittest.cc ${protobuf_source_dir}/src/google/protobuf/stubs/bytestream_unittest.cc ${protobuf_source_dir}/src/google/protobuf/stubs/common_unittest.cc ${protobuf_source_dir}/src/google/protobuf/stubs/int128_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/io_win32_unittest.cc ${protobuf_source_dir}/src/google/protobuf/stubs/status_test.cc ${protobuf_source_dir}/src/google/protobuf/stubs/statusor_test.cc ${protobuf_source_dir}/src/google/protobuf/stubs/stringpiece_unittest.cc @@ -204,6 +207,17 @@ if(protobuf_ABSOLUTE_TEST_PLUGIN_PATH) add_compile_options(-DGOOGLE_PROTOBUF_TEST_PLUGIN_PATH="$") endif() +if(MINGW) + set_source_files_properties(${tests_files} PROPERTIES COMPILE_FLAGS "-Wno-narrowing") + + # required for tests on MinGW Win64 + if (CMAKE_SIZEOF_VOID_P EQUAL 8) + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--stack,16777216") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wa,-mbig-obj") + endif() + +endif() + add_executable(tests ${tests_files} ${common_test_files} ${tests_proto_files} ${lite_test_proto_files}) target_link_libraries(tests libprotoc libprotobuf gmock_main) diff --git a/third_party/protobuf/cmake/version.rc.in b/third_party/protobuf/cmake/version.rc.in new file mode 100644 index 00000000..f6e7c4a3 --- /dev/null +++ b/third_party/protobuf/cmake/version.rc.in @@ -0,0 +1,45 @@ +#define VS_FF_DEBUG 0x1L +#define VS_VERSION_INFO 0x1L +#define VS_FFI_FILEFLAGSMASK 0x17L +#define VER_PRIVATEBUILD 0x0L +#define VER_PRERELEASE 0x0L +#define VOS__WINDOWS32 0x4L +#define VFT_DLL 0x2L +#define VFT2_UNKNOWN 0x0L + +#ifndef DEBUG +#define VER_DEBUG 0 +#else +#define VER_DEBUG VS_FF_DEBUG +#endif + + +VS_VERSION_INFO VERSIONINFO + FILEVERSION @protobuf_RC_FILEVERSION@ + PRODUCTVERSION @protobuf_RC_FILEVERSION@ + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK + FILEFLAGS VER_DEBUG + FILEOS VOS__WINDOWS32 + FILETYPE VFT_DLL +BEGIN + BLOCK "VarFileInfo" + BEGIN + // English language (0x409) and the Windows Unicode codepage (1200) + VALUE "Translation", 0x409, 1200 + END + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "FileDescription", "Compiled with @CMAKE_CXX_COMPILER_ID@ @CMAKE_CXX_COMPILER_VERSION@\0" + VALUE "ProductVersion", "@protobuf_VERSION@\0" + VALUE "FileVersion", "@protobuf_VERSION@\0" + VALUE "InternalName", "protobuf\0" + VALUE "ProductName", "Protocol Buffers - Google's Data Interchange Format\0" + VALUE "CompanyName", "Google Inc.\0" + VALUE "LegalCopyright", "Copyright 2008 Google Inc. All rights reserved.\0" + VALUE "Licence", "BSD\0" + VALUE "Info", "https://developers.google.com/protocol-buffers/\0" + END + END +END diff --git a/third_party/protobuf/compiler_config_setting.bzl b/third_party/protobuf/compiler_config_setting.bzl new file mode 100644 index 00000000..5e52a652 --- /dev/null +++ b/third_party/protobuf/compiler_config_setting.bzl @@ -0,0 +1,21 @@ +"""Creates config_setting that allows selecting based on 'compiler' value.""" + +def create_compiler_config_setting(name, value): + # The "do_not_use_tools_cpp_compiler_present" attribute exists to + # distinguish between older versions of Bazel that do not support + # "@bazel_tools//tools/cpp:compiler" flag_value, and newer ones that do. + # In the future, the only way to select on the compiler will be through + # flag_values{"@bazel_tools//tools/cpp:compiler"} and the else branch can + # be removed. + if hasattr(cc_common, "do_not_use_tools_cpp_compiler_present"): + native.config_setting( + name = name, + flag_values = { + "@bazel_tools//tools/cpp:compiler": value, + }, + ) + else: + native.config_setting( + name = name, + values = {"compiler": value}, + ) diff --git a/third_party/protobuf/config.guess b/third_party/protobuf/config.guess index 31e01efe..f50dcdb6 100755 --- a/third_party/protobuf/config.guess +++ b/third_party/protobuf/config.guess @@ -1,8 +1,8 @@ #! /bin/sh # Attempt to guess a canonical system name. -# Copyright 1992-2017 Free Software Foundation, Inc. +# Copyright 1992-2018 Free Software Foundation, Inc. -timestamp='2017-11-07' +timestamp='2018-02-24' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by @@ -50,7 +50,7 @@ version="\ GNU config.guess ($timestamp) Originally written by Per Bothner. -Copyright 1992-2017 Free Software Foundation, Inc. +Copyright 1992-2018 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." @@ -107,9 +107,9 @@ trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; dummy=$tmp/dummy ; tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; case $CC_FOR_BUILD,$HOST_CC,$CC in - ,,) echo "int x;" > $dummy.c ; + ,,) echo "int x;" > "$dummy.c" ; for c in cc gcc c89 c99 ; do - if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then + if ($c -c -o "$dummy.o" "$dummy.c") >/dev/null 2>&1 ; then CC_FOR_BUILD="$c"; break ; fi ; done ; @@ -132,14 +132,14 @@ UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown -case "${UNAME_SYSTEM}" in +case "$UNAME_SYSTEM" in Linux|GNU|GNU/*) # If the system lacks a compiler, then just pick glibc. # We could probably try harder. LIBC=gnu - eval $set_cc_for_build - cat <<-EOF > $dummy.c + eval "$set_cc_for_build" + cat <<-EOF > "$dummy.c" #include #if defined(__UCLIBC__) LIBC=uclibc @@ -149,13 +149,20 @@ Linux|GNU|GNU/*) LIBC=gnu #endif EOF - eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC' | sed 's, ,,g'` + eval "`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^LIBC' | sed 's, ,,g'`" + + # If ldd exists, use it to detect musl libc. + if command -v ldd >/dev/null && \ + ldd --version 2>&1 | grep -q ^musl + then + LIBC=musl + fi ;; esac # Note: order is significant - the case branches are not exclusive. -case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in +case "$UNAME_MACHINE:$UNAME_SYSTEM:$UNAME_RELEASE:$UNAME_VERSION" in *:NetBSD:*:*) # NetBSD (nbsd) targets should (where applicable) match one or # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*, @@ -169,30 +176,30 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in # portion of the name. We always set it to "unknown". sysctl="sysctl -n hw.machine_arch" UNAME_MACHINE_ARCH=`(uname -p 2>/dev/null || \ - /sbin/$sysctl 2>/dev/null || \ - /usr/sbin/$sysctl 2>/dev/null || \ + "/sbin/$sysctl" 2>/dev/null || \ + "/usr/sbin/$sysctl" 2>/dev/null || \ echo unknown)` - case "${UNAME_MACHINE_ARCH}" in + case "$UNAME_MACHINE_ARCH" in armeb) machine=armeb-unknown ;; arm*) machine=arm-unknown ;; sh3el) machine=shl-unknown ;; sh3eb) machine=sh-unknown ;; sh5el) machine=sh5le-unknown ;; earmv*) - arch=`echo ${UNAME_MACHINE_ARCH} | sed -e 's,^e\(armv[0-9]\).*$,\1,'` - endian=`echo ${UNAME_MACHINE_ARCH} | sed -ne 's,^.*\(eb\)$,\1,p'` - machine=${arch}${endian}-unknown + arch=`echo "$UNAME_MACHINE_ARCH" | sed -e 's,^e\(armv[0-9]\).*$,\1,'` + endian=`echo "$UNAME_MACHINE_ARCH" | sed -ne 's,^.*\(eb\)$,\1,p'` + machine="${arch}${endian}"-unknown ;; - *) machine=${UNAME_MACHINE_ARCH}-unknown ;; + *) machine="$UNAME_MACHINE_ARCH"-unknown ;; esac # The Operating System including object format, if it has switched # to ELF recently (or will in the future) and ABI. - case "${UNAME_MACHINE_ARCH}" in + case "$UNAME_MACHINE_ARCH" in earm*) os=netbsdelf ;; arm*|i386|m68k|ns32k|sh3*|sparc|vax) - eval $set_cc_for_build + eval "$set_cc_for_build" if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ELF__ then @@ -208,10 +215,10 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in ;; esac # Determine ABI tags. - case "${UNAME_MACHINE_ARCH}" in + case "$UNAME_MACHINE_ARCH" in earm*) expr='s/^earmv[0-9]/-eabi/;s/eb$//' - abi=`echo ${UNAME_MACHINE_ARCH} | sed -e "$expr"` + abi=`echo "$UNAME_MACHINE_ARCH" | sed -e "$expr"` ;; esac # The OS release @@ -219,52 +226,55 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in # thus, need a distinct triplet. However, they do not need # kernel version information, so it can be replaced with a # suitable tag, in the style of linux-gnu. - case "${UNAME_VERSION}" in + case "$UNAME_VERSION" in Debian*) release='-gnu' ;; *) - release=`echo ${UNAME_RELEASE} | sed -e 's/[-_].*//' | cut -d. -f1,2` + release=`echo "$UNAME_RELEASE" | sed -e 's/[-_].*//' | cut -d. -f1,2` ;; esac # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: # contains redundant information, the shorter form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. - echo "${machine}-${os}${release}${abi}" + echo "$machine-${os}${release}${abi}" exit ;; *:Bitrig:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'` - echo ${UNAME_MACHINE_ARCH}-unknown-bitrig${UNAME_RELEASE} + echo "$UNAME_MACHINE_ARCH"-unknown-bitrig"$UNAME_RELEASE" exit ;; *:OpenBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` - echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} + echo "$UNAME_MACHINE_ARCH"-unknown-openbsd"$UNAME_RELEASE" exit ;; *:LibertyBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/^.*BSD\.//'` - echo ${UNAME_MACHINE_ARCH}-unknown-libertybsd${UNAME_RELEASE} + echo "$UNAME_MACHINE_ARCH"-unknown-libertybsd"$UNAME_RELEASE" exit ;; *:MidnightBSD:*:*) - echo ${UNAME_MACHINE}-unknown-midnightbsd${UNAME_RELEASE} + echo "$UNAME_MACHINE"-unknown-midnightbsd"$UNAME_RELEASE" exit ;; *:ekkoBSD:*:*) - echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} + echo "$UNAME_MACHINE"-unknown-ekkobsd"$UNAME_RELEASE" exit ;; *:SolidBSD:*:*) - echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} + echo "$UNAME_MACHINE"-unknown-solidbsd"$UNAME_RELEASE" exit ;; macppc:MirBSD:*:*) - echo powerpc-unknown-mirbsd${UNAME_RELEASE} + echo powerpc-unknown-mirbsd"$UNAME_RELEASE" exit ;; *:MirBSD:*:*) - echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} + echo "$UNAME_MACHINE"-unknown-mirbsd"$UNAME_RELEASE" exit ;; *:Sortix:*:*) - echo ${UNAME_MACHINE}-unknown-sortix + echo "$UNAME_MACHINE"-unknown-sortix exit ;; *:Redox:*:*) - echo ${UNAME_MACHINE}-unknown-redox + echo "$UNAME_MACHINE"-unknown-redox exit ;; + mips:OSF1:*.*) + echo mips-dec-osf1 + exit ;; alpha:OSF1:*:*) case $UNAME_RELEASE in *4.0) @@ -316,7 +326,7 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in # A Tn.n version is a released field test version. # A Xn.n version is an unreleased experimental baselevel. # 1.2 uses "1.2" for uname -r. - echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz` + echo "$UNAME_MACHINE"-dec-osf"`echo "$UNAME_RELEASE" | sed -e 's/^[PVTX]//' | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz`" # Reset EXIT trap before exiting to avoid spurious non-zero exit code. exitcode=$? trap '' 0 @@ -325,10 +335,10 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in echo m68k-unknown-sysv4 exit ;; *:[Aa]miga[Oo][Ss]:*:*) - echo ${UNAME_MACHINE}-unknown-amigaos + echo "$UNAME_MACHINE"-unknown-amigaos exit ;; *:[Mm]orph[Oo][Ss]:*:*) - echo ${UNAME_MACHINE}-unknown-morphos + echo "$UNAME_MACHINE"-unknown-morphos exit ;; *:OS/390:*:*) echo i370-ibm-openedition @@ -340,7 +350,7 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in echo powerpc-ibm-os400 exit ;; arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) - echo arm-acorn-riscix${UNAME_RELEASE} + echo arm-acorn-riscix"$UNAME_RELEASE" exit ;; arm*:riscos:*:*|arm*:RISCOS:*:*) echo arm-unknown-riscos @@ -367,19 +377,19 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in sparc) echo sparc-icl-nx7; exit ;; esac ;; s390x:SunOS:*:*) - echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + echo "$UNAME_MACHINE"-ibm-solaris2"`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'`" exit ;; sun4H:SunOS:5.*:*) - echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + echo sparc-hal-solaris2"`echo "$UNAME_RELEASE"|sed -e 's/[^.]*//'`" exit ;; sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) - echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + echo sparc-sun-solaris2"`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'`" exit ;; i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) - echo i386-pc-auroraux${UNAME_RELEASE} + echo i386-pc-auroraux"$UNAME_RELEASE" exit ;; i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) - eval $set_cc_for_build + eval "$set_cc_for_build" SUN_ARCH=i386 # If there is a compiler, see if it is configured for 64-bit objects. # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. @@ -392,13 +402,13 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in SUN_ARCH=x86_64 fi fi - echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + echo "$SUN_ARCH"-pc-solaris2"`echo "$UNAME_RELEASE"|sed -e 's/[^.]*//'`" exit ;; sun4*:SunOS:6*:*) # According to config.sub, this is the proper way to canonicalize # SunOS6. Hard to guess exactly what SunOS6 will be like, but # it's likely to be more like Solaris than SunOS4. - echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + echo sparc-sun-solaris3"`echo "$UNAME_RELEASE"|sed -e 's/[^.]*//'`" exit ;; sun4*:SunOS:*:*) case "`/usr/bin/arch -k`" in @@ -407,25 +417,25 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in ;; esac # Japanese Language versions have a version number like `4.1.3-JL'. - echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` + echo sparc-sun-sunos"`echo "$UNAME_RELEASE"|sed -e 's/-/_/'`" exit ;; sun3*:SunOS:*:*) - echo m68k-sun-sunos${UNAME_RELEASE} + echo m68k-sun-sunos"$UNAME_RELEASE" exit ;; sun*:*:4.2BSD:*) UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` - test "x${UNAME_RELEASE}" = x && UNAME_RELEASE=3 + test "x$UNAME_RELEASE" = x && UNAME_RELEASE=3 case "`/bin/arch`" in sun3) - echo m68k-sun-sunos${UNAME_RELEASE} + echo m68k-sun-sunos"$UNAME_RELEASE" ;; sun4) - echo sparc-sun-sunos${UNAME_RELEASE} + echo sparc-sun-sunos"$UNAME_RELEASE" ;; esac exit ;; aushp:SunOS:*:*) - echo sparc-auspex-sunos${UNAME_RELEASE} + echo sparc-auspex-sunos"$UNAME_RELEASE" exit ;; # The situation for MiNT is a little confusing. The machine name # can be virtually everything (everything which is not @@ -436,44 +446,44 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in # MiNT. But MiNT is downward compatible to TOS, so this should # be no problem. atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) - echo m68k-atari-mint${UNAME_RELEASE} + echo m68k-atari-mint"$UNAME_RELEASE" exit ;; atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) - echo m68k-atari-mint${UNAME_RELEASE} + echo m68k-atari-mint"$UNAME_RELEASE" exit ;; *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) - echo m68k-atari-mint${UNAME_RELEASE} + echo m68k-atari-mint"$UNAME_RELEASE" exit ;; milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) - echo m68k-milan-mint${UNAME_RELEASE} + echo m68k-milan-mint"$UNAME_RELEASE" exit ;; hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) - echo m68k-hades-mint${UNAME_RELEASE} + echo m68k-hades-mint"$UNAME_RELEASE" exit ;; *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) - echo m68k-unknown-mint${UNAME_RELEASE} + echo m68k-unknown-mint"$UNAME_RELEASE" exit ;; m68k:machten:*:*) - echo m68k-apple-machten${UNAME_RELEASE} + echo m68k-apple-machten"$UNAME_RELEASE" exit ;; powerpc:machten:*:*) - echo powerpc-apple-machten${UNAME_RELEASE} + echo powerpc-apple-machten"$UNAME_RELEASE" exit ;; RISC*:Mach:*:*) echo mips-dec-mach_bsd4.3 exit ;; RISC*:ULTRIX:*:*) - echo mips-dec-ultrix${UNAME_RELEASE} + echo mips-dec-ultrix"$UNAME_RELEASE" exit ;; VAX*:ULTRIX*:*:*) - echo vax-dec-ultrix${UNAME_RELEASE} + echo vax-dec-ultrix"$UNAME_RELEASE" exit ;; 2020:CLIX:*:* | 2430:CLIX:*:*) - echo clipper-intergraph-clix${UNAME_RELEASE} + echo clipper-intergraph-clix"$UNAME_RELEASE" exit ;; mips:*:*:UMIPS | mips:*:*:RISCos) - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c + eval "$set_cc_for_build" + sed 's/^ //' << EOF > "$dummy.c" #ifdef __cplusplus #include /* for printf() prototype */ int main (int argc, char *argv[]) { @@ -494,11 +504,11 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in exit (-1); } EOF - $CC_FOR_BUILD -o $dummy $dummy.c && - dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && - SYSTEM_NAME=`$dummy $dummyarg` && + $CC_FOR_BUILD -o "$dummy" "$dummy.c" && + dummyarg=`echo "$UNAME_RELEASE" | sed -n 's/\([0-9]*\).*/\1/p'` && + SYSTEM_NAME=`"$dummy" "$dummyarg"` && { echo "$SYSTEM_NAME"; exit; } - echo mips-mips-riscos${UNAME_RELEASE} + echo mips-mips-riscos"$UNAME_RELEASE" exit ;; Motorola:PowerMAX_OS:*:*) echo powerpc-motorola-powermax @@ -524,17 +534,17 @@ EOF AViiON:dgux:*:*) # DG/UX returns AViiON for all architectures UNAME_PROCESSOR=`/usr/bin/uname -p` - if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] + if [ "$UNAME_PROCESSOR" = mc88100 ] || [ "$UNAME_PROCESSOR" = mc88110 ] then - if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ - [ ${TARGET_BINARY_INTERFACE}x = x ] + if [ "$TARGET_BINARY_INTERFACE"x = m88kdguxelfx ] || \ + [ "$TARGET_BINARY_INTERFACE"x = x ] then - echo m88k-dg-dgux${UNAME_RELEASE} + echo m88k-dg-dgux"$UNAME_RELEASE" else - echo m88k-dg-dguxbcs${UNAME_RELEASE} + echo m88k-dg-dguxbcs"$UNAME_RELEASE" fi else - echo i586-dg-dgux${UNAME_RELEASE} + echo i586-dg-dgux"$UNAME_RELEASE" fi exit ;; M88*:DolphinOS:*:*) # DolphinOS (SVR3) @@ -551,7 +561,7 @@ EOF echo m68k-tektronix-bsd exit ;; *:IRIX*:*:*) - echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` + echo mips-sgi-irix"`echo "$UNAME_RELEASE"|sed -e 's/-/_/g'`" exit ;; ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id @@ -563,14 +573,14 @@ EOF if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` else - IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + IBM_REV="$UNAME_VERSION.$UNAME_RELEASE" fi - echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} + echo "$UNAME_MACHINE"-ibm-aix"$IBM_REV" exit ;; *:AIX:2:3) if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c + eval "$set_cc_for_build" + sed 's/^ //' << EOF > "$dummy.c" #include main() @@ -581,7 +591,7 @@ EOF exit(0); } EOF - if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` + if $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"` then echo "$SYSTEM_NAME" else @@ -595,7 +605,7 @@ EOF exit ;; *:AIX:*:[4567]) IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` - if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then + if /usr/sbin/lsattr -El "$IBM_CPU_ID" | grep ' POWER' >/dev/null 2>&1; then IBM_ARCH=rs6000 else IBM_ARCH=powerpc @@ -604,9 +614,9 @@ EOF IBM_REV=`/usr/bin/lslpp -Lqc bos.rte.libc | awk -F: '{ print $3 }' | sed s/[0-9]*$/0/` else - IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + IBM_REV="$UNAME_VERSION.$UNAME_RELEASE" fi - echo ${IBM_ARCH}-ibm-aix${IBM_REV} + echo "$IBM_ARCH"-ibm-aix"$IBM_REV" exit ;; *:AIX:*:*) echo rs6000-ibm-aix @@ -615,7 +625,7 @@ EOF echo romp-ibm-bsd4.4 exit ;; ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and - echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to + echo romp-ibm-bsd"$UNAME_RELEASE" # 4.3 with uname added to exit ;; # report: romp-ibm BSD 4.3 *:BOSX:*:*) echo rs6000-bull-bosx @@ -630,28 +640,28 @@ EOF echo m68k-hp-bsd4.4 exit ;; 9000/[34678]??:HP-UX:*:*) - HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` - case "${UNAME_MACHINE}" in + HPUX_REV=`echo "$UNAME_RELEASE"|sed -e 's/[^.]*.[0B]*//'` + case "$UNAME_MACHINE" in 9000/31?) HP_ARCH=m68000 ;; 9000/[34]??) HP_ARCH=m68k ;; 9000/[678][0-9][0-9]) if [ -x /usr/bin/getconf ]; then sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` - case "${sc_cpu_version}" in + case "$sc_cpu_version" in 523) HP_ARCH=hppa1.0 ;; # CPU_PA_RISC1_0 528) HP_ARCH=hppa1.1 ;; # CPU_PA_RISC1_1 532) # CPU_PA_RISC2_0 - case "${sc_kernel_bits}" in + case "$sc_kernel_bits" in 32) HP_ARCH=hppa2.0n ;; 64) HP_ARCH=hppa2.0w ;; '') HP_ARCH=hppa2.0 ;; # HP-UX 10.20 esac ;; esac fi - if [ "${HP_ARCH}" = "" ]; then - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c + if [ "$HP_ARCH" = "" ]; then + eval "$set_cc_for_build" + sed 's/^ //' << EOF > "$dummy.c" #define _HPUX_SOURCE #include @@ -684,13 +694,13 @@ EOF exit (0); } EOF - (CCOPTS="" $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` + (CCOPTS="" $CC_FOR_BUILD -o "$dummy" "$dummy.c" 2>/dev/null) && HP_ARCH=`"$dummy"` test -z "$HP_ARCH" && HP_ARCH=hppa fi ;; esac - if [ ${HP_ARCH} = hppa2.0w ] + if [ "$HP_ARCH" = hppa2.0w ] then - eval $set_cc_for_build + eval "$set_cc_for_build" # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler @@ -709,15 +719,15 @@ EOF HP_ARCH=hppa64 fi fi - echo ${HP_ARCH}-hp-hpux${HPUX_REV} + echo "$HP_ARCH"-hp-hpux"$HPUX_REV" exit ;; ia64:HP-UX:*:*) - HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` - echo ia64-hp-hpux${HPUX_REV} + HPUX_REV=`echo "$UNAME_RELEASE"|sed -e 's/[^.]*.[0B]*//'` + echo ia64-hp-hpux"$HPUX_REV" exit ;; 3050*:HI-UX:*:*) - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c + eval "$set_cc_for_build" + sed 's/^ //' << EOF > "$dummy.c" #include int main () @@ -742,7 +752,7 @@ EOF exit (0); } EOF - $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && + $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"` && { echo "$SYSTEM_NAME"; exit; } echo unknown-hitachi-hiuxwe2 exit ;; @@ -763,9 +773,9 @@ EOF exit ;; i*86:OSF1:*:*) if [ -x /usr/sbin/sysversion ] ; then - echo ${UNAME_MACHINE}-unknown-osf1mk + echo "$UNAME_MACHINE"-unknown-osf1mk else - echo ${UNAME_MACHINE}-unknown-osf1 + echo "$UNAME_MACHINE"-unknown-osf1 fi exit ;; parisc*:Lites*:*:*) @@ -790,109 +800,109 @@ EOF echo c4-convex-bsd exit ;; CRAY*Y-MP:*:*:*) - echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + echo ymp-cray-unicos"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*[A-Z]90:*:*:*) - echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ + echo "$UNAME_MACHINE"-cray-unicos"$UNAME_RELEASE" \ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ -e 's/\.[^.]*$/.X/' exit ;; CRAY*TS:*:*:*) - echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + echo t90-cray-unicos"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*T3E:*:*:*) - echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + echo alphaev5-cray-unicosmk"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*SV1:*:*:*) - echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + echo sv1-cray-unicos"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' exit ;; *:UNICOS/mp:*:*) - echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + echo craynv-cray-unicosmp"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' exit ;; F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) FUJITSU_PROC=`uname -m | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz` FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` - FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` + FUJITSU_REL=`echo "$UNAME_RELEASE" | sed -e 's/ /_/'` echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; 5000:UNIX_System_V:4.*:*) FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` - FUJITSU_REL=`echo ${UNAME_RELEASE} | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/ /_/'` + FUJITSU_REL=`echo "$UNAME_RELEASE" | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/ /_/'` echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) - echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} + echo "$UNAME_MACHINE"-pc-bsdi"$UNAME_RELEASE" exit ;; sparc*:BSD/OS:*:*) - echo sparc-unknown-bsdi${UNAME_RELEASE} + echo sparc-unknown-bsdi"$UNAME_RELEASE" exit ;; *:BSD/OS:*:*) - echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} + echo "$UNAME_MACHINE"-unknown-bsdi"$UNAME_RELEASE" exit ;; *:FreeBSD:*:*) UNAME_PROCESSOR=`/usr/bin/uname -p` - case ${UNAME_PROCESSOR} in + case "$UNAME_PROCESSOR" in amd64) UNAME_PROCESSOR=x86_64 ;; i386) UNAME_PROCESSOR=i586 ;; esac - echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` + echo "$UNAME_PROCESSOR"-unknown-freebsd"`echo "$UNAME_RELEASE"|sed -e 's/[-(].*//'`" exit ;; i*:CYGWIN*:*) - echo ${UNAME_MACHINE}-pc-cygwin + echo "$UNAME_MACHINE"-pc-cygwin exit ;; *:MINGW64*:*) - echo ${UNAME_MACHINE}-pc-mingw64 + echo "$UNAME_MACHINE"-pc-mingw64 exit ;; *:MINGW*:*) - echo ${UNAME_MACHINE}-pc-mingw32 + echo "$UNAME_MACHINE"-pc-mingw32 exit ;; *:MSYS*:*) - echo ${UNAME_MACHINE}-pc-msys + echo "$UNAME_MACHINE"-pc-msys exit ;; i*:PW*:*) - echo ${UNAME_MACHINE}-pc-pw32 + echo "$UNAME_MACHINE"-pc-pw32 exit ;; *:Interix*:*) - case ${UNAME_MACHINE} in + case "$UNAME_MACHINE" in x86) - echo i586-pc-interix${UNAME_RELEASE} + echo i586-pc-interix"$UNAME_RELEASE" exit ;; authenticamd | genuineintel | EM64T) - echo x86_64-unknown-interix${UNAME_RELEASE} + echo x86_64-unknown-interix"$UNAME_RELEASE" exit ;; IA64) - echo ia64-unknown-interix${UNAME_RELEASE} + echo ia64-unknown-interix"$UNAME_RELEASE" exit ;; esac ;; i*:UWIN*:*) - echo ${UNAME_MACHINE}-pc-uwin + echo "$UNAME_MACHINE"-pc-uwin exit ;; amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) echo x86_64-unknown-cygwin exit ;; prep*:SunOS:5.*:*) - echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + echo powerpcle-unknown-solaris2"`echo "$UNAME_RELEASE"|sed -e 's/[^.]*//'`" exit ;; *:GNU:*:*) # the GNU system - echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-${LIBC}`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` + echo "`echo "$UNAME_MACHINE"|sed -e 's,[-/].*$,,'`-unknown-$LIBC`echo "$UNAME_RELEASE"|sed -e 's,/.*$,,'`" exit ;; *:GNU/*:*:*) # other systems with GNU libc and userland - echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr "[:upper:]" "[:lower:]"``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC} + echo "$UNAME_MACHINE-unknown-`echo "$UNAME_SYSTEM" | sed 's,^[^/]*/,,' | tr "[:upper:]" "[:lower:]"``echo "$UNAME_RELEASE"|sed -e 's/[-(].*//'`-$LIBC" exit ;; i*86:Minix:*:*) - echo ${UNAME_MACHINE}-pc-minix + echo "$UNAME_MACHINE"-pc-minix exit ;; aarch64:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; aarch64_be:Linux:*:*) UNAME_MACHINE=aarch64_be - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; alpha:Linux:*:*) case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in @@ -906,63 +916,63 @@ EOF esac objdump --private-headers /bin/sh | grep -q ld.so.1 if test "$?" = 0 ; then LIBC=gnulibc1 ; fi - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; arc:Linux:*:* | arceb:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; arm*:Linux:*:*) - eval $set_cc_for_build + eval "$set_cc_for_build" if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_EABI__ then - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" else if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_PCS_VFP then - echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"eabi else - echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"eabihf fi fi exit ;; avr32*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; cris:Linux:*:*) - echo ${UNAME_MACHINE}-axis-linux-${LIBC} + echo "$UNAME_MACHINE"-axis-linux-"$LIBC" exit ;; crisv32:Linux:*:*) - echo ${UNAME_MACHINE}-axis-linux-${LIBC} + echo "$UNAME_MACHINE"-axis-linux-"$LIBC" exit ;; e2k:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; frv:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; hexagon:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; i*86:Linux:*:*) - echo ${UNAME_MACHINE}-pc-linux-${LIBC} + echo "$UNAME_MACHINE"-pc-linux-"$LIBC" exit ;; ia64:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; k1om:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; m32r*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; m68*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; mips:Linux:*:* | mips64:Linux:*:*) - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c + eval "$set_cc_for_build" + sed 's/^ //' << EOF > "$dummy.c" #undef CPU #undef ${UNAME_MACHINE} #undef ${UNAME_MACHINE}el @@ -976,70 +986,74 @@ EOF #endif #endif EOF - eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'` - test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; } + eval "`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^CPU'`" + test "x$CPU" != x && { echo "$CPU-unknown-linux-$LIBC"; exit; } ;; mips64el:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; openrisc*:Linux:*:*) - echo or1k-unknown-linux-${LIBC} + echo or1k-unknown-linux-"$LIBC" exit ;; or32:Linux:*:* | or1k*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; padre:Linux:*:*) - echo sparc-unknown-linux-${LIBC} + echo sparc-unknown-linux-"$LIBC" exit ;; parisc64:Linux:*:* | hppa64:Linux:*:*) - echo hppa64-unknown-linux-${LIBC} + echo hppa64-unknown-linux-"$LIBC" exit ;; parisc:Linux:*:* | hppa:Linux:*:*) # Look for CPU level case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in - PA7*) echo hppa1.1-unknown-linux-${LIBC} ;; - PA8*) echo hppa2.0-unknown-linux-${LIBC} ;; - *) echo hppa-unknown-linux-${LIBC} ;; + PA7*) echo hppa1.1-unknown-linux-"$LIBC" ;; + PA8*) echo hppa2.0-unknown-linux-"$LIBC" ;; + *) echo hppa-unknown-linux-"$LIBC" ;; esac exit ;; ppc64:Linux:*:*) - echo powerpc64-unknown-linux-${LIBC} + echo powerpc64-unknown-linux-"$LIBC" exit ;; ppc:Linux:*:*) - echo powerpc-unknown-linux-${LIBC} + echo powerpc-unknown-linux-"$LIBC" exit ;; ppc64le:Linux:*:*) - echo powerpc64le-unknown-linux-${LIBC} + echo powerpc64le-unknown-linux-"$LIBC" exit ;; ppcle:Linux:*:*) - echo powerpcle-unknown-linux-${LIBC} + echo powerpcle-unknown-linux-"$LIBC" exit ;; riscv32:Linux:*:* | riscv64:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; s390:Linux:*:* | s390x:Linux:*:*) - echo ${UNAME_MACHINE}-ibm-linux-${LIBC} + echo "$UNAME_MACHINE"-ibm-linux-"$LIBC" exit ;; sh64*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; sh*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; sparc:Linux:*:* | sparc64:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; tile*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; vax:Linux:*:*) - echo ${UNAME_MACHINE}-dec-linux-${LIBC} + echo "$UNAME_MACHINE"-dec-linux-"$LIBC" exit ;; x86_64:Linux:*:*) - echo ${UNAME_MACHINE}-pc-linux-${LIBC} + if objdump -f /bin/sh | grep -q elf32-x86-64; then + echo "$UNAME_MACHINE"-pc-linux-"$LIBC"x32 + else + echo "$UNAME_MACHINE"-pc-linux-"$LIBC" + fi exit ;; xtensa*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; i*86:DYNIX/ptx:4*:*) # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. @@ -1053,34 +1067,34 @@ EOF # I am not positive that other SVR4 systems won't match this, # I just have to hope. -- rms. # Use sysv4.2uw... so that sysv4* matches it. - echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} + echo "$UNAME_MACHINE"-pc-sysv4.2uw"$UNAME_VERSION" exit ;; i*86:OS/2:*:*) # If we were able to find `uname', then EMX Unix compatibility # is probably installed. - echo ${UNAME_MACHINE}-pc-os2-emx + echo "$UNAME_MACHINE"-pc-os2-emx exit ;; i*86:XTS-300:*:STOP) - echo ${UNAME_MACHINE}-unknown-stop + echo "$UNAME_MACHINE"-unknown-stop exit ;; i*86:atheos:*:*) - echo ${UNAME_MACHINE}-unknown-atheos + echo "$UNAME_MACHINE"-unknown-atheos exit ;; i*86:syllable:*:*) - echo ${UNAME_MACHINE}-pc-syllable + echo "$UNAME_MACHINE"-pc-syllable exit ;; i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) - echo i386-unknown-lynxos${UNAME_RELEASE} + echo i386-unknown-lynxos"$UNAME_RELEASE" exit ;; i*86:*DOS:*:*) - echo ${UNAME_MACHINE}-pc-msdosdjgpp + echo "$UNAME_MACHINE"-pc-msdosdjgpp exit ;; i*86:*:4.*:*) - UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` + UNAME_REL=`echo "$UNAME_RELEASE" | sed 's/\/MP$//'` if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then - echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} + echo "$UNAME_MACHINE"-univel-sysv"$UNAME_REL" else - echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} + echo "$UNAME_MACHINE"-pc-sysv"$UNAME_REL" fi exit ;; i*86:*:5:[678]*) @@ -1090,12 +1104,12 @@ EOF *Pentium) UNAME_MACHINE=i586 ;; *Pent*|*Celeron) UNAME_MACHINE=i686 ;; esac - echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} + echo "$UNAME_MACHINE-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}{$UNAME_VERSION}" exit ;; i*86:*:3.2:*) if test -f /usr/options/cb.name; then UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 @@ -1105,9 +1119,9 @@ EOF && UNAME_MACHINE=i686 (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ && UNAME_MACHINE=i686 - echo ${UNAME_MACHINE}-pc-sco$UNAME_REL + echo "$UNAME_MACHINE"-pc-sco"$UNAME_REL" else - echo ${UNAME_MACHINE}-pc-sysv32 + echo "$UNAME_MACHINE"-pc-sysv32 fi exit ;; pc:*:*:*) @@ -1127,9 +1141,9 @@ EOF exit ;; i860:*:4.*:*) # i860-SVR4 if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then - echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 + echo i860-stardent-sysv"$UNAME_RELEASE" # Stardent Vistra i860-SVR4 else # Add other i860-SVR4 vendors below as they are discovered. - echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 + echo i860-unknown-sysv"$UNAME_RELEASE" # Unknown i860-SVR4 fi exit ;; mini*:CTIX:SYS*5:*) @@ -1149,9 +1163,9 @@ EOF test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ - && { echo i486-ncr-sysv4.3${OS_REL}; exit; } + && { echo i486-ncr-sysv4.3"$OS_REL"; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ - && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; + && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } ;; 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4; exit; } ;; @@ -1160,28 +1174,28 @@ EOF test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ - && { echo i486-ncr-sysv4.3${OS_REL}; exit; } + && { echo i486-ncr-sysv4.3"$OS_REL"; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ - && { echo i586-ncr-sysv4.3${OS_REL}; exit; } + && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ - && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; + && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } ;; m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) - echo m68k-unknown-lynxos${UNAME_RELEASE} + echo m68k-unknown-lynxos"$UNAME_RELEASE" exit ;; mc68030:UNIX_System_V:4.*:*) echo m68k-atari-sysv4 exit ;; TSUNAMI:LynxOS:2.*:*) - echo sparc-unknown-lynxos${UNAME_RELEASE} + echo sparc-unknown-lynxos"$UNAME_RELEASE" exit ;; rs6000:LynxOS:2.*:*) - echo rs6000-unknown-lynxos${UNAME_RELEASE} + echo rs6000-unknown-lynxos"$UNAME_RELEASE" exit ;; PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) - echo powerpc-unknown-lynxos${UNAME_RELEASE} + echo powerpc-unknown-lynxos"$UNAME_RELEASE" exit ;; SM[BE]S:UNIX_SV:*:*) - echo mips-dde-sysv${UNAME_RELEASE} + echo mips-dde-sysv"$UNAME_RELEASE" exit ;; RM*:ReliantUNIX-*:*:*) echo mips-sni-sysv4 @@ -1192,7 +1206,7 @@ EOF *:SINIX-*:*:*) if uname -p 2>/dev/null >/dev/null ; then UNAME_MACHINE=`(uname -p) 2>/dev/null` - echo ${UNAME_MACHINE}-sni-sysv4 + echo "$UNAME_MACHINE"-sni-sysv4 else echo ns32k-sni-sysv fi @@ -1212,23 +1226,23 @@ EOF exit ;; i*86:VOS:*:*) # From Paul.Green@stratus.com. - echo ${UNAME_MACHINE}-stratus-vos + echo "$UNAME_MACHINE"-stratus-vos exit ;; *:VOS:*:*) # From Paul.Green@stratus.com. echo hppa1.1-stratus-vos exit ;; mc68*:A/UX:*:*) - echo m68k-apple-aux${UNAME_RELEASE} + echo m68k-apple-aux"$UNAME_RELEASE" exit ;; news*:NEWS-OS:6*:*) echo mips-sony-newsos6 exit ;; R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) if [ -d /usr/nec ]; then - echo mips-nec-sysv${UNAME_RELEASE} + echo mips-nec-sysv"$UNAME_RELEASE" else - echo mips-unknown-sysv${UNAME_RELEASE} + echo mips-unknown-sysv"$UNAME_RELEASE" fi exit ;; BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. @@ -1247,39 +1261,39 @@ EOF echo x86_64-unknown-haiku exit ;; SX-4:SUPER-UX:*:*) - echo sx4-nec-superux${UNAME_RELEASE} + echo sx4-nec-superux"$UNAME_RELEASE" exit ;; SX-5:SUPER-UX:*:*) - echo sx5-nec-superux${UNAME_RELEASE} + echo sx5-nec-superux"$UNAME_RELEASE" exit ;; SX-6:SUPER-UX:*:*) - echo sx6-nec-superux${UNAME_RELEASE} + echo sx6-nec-superux"$UNAME_RELEASE" exit ;; SX-7:SUPER-UX:*:*) - echo sx7-nec-superux${UNAME_RELEASE} + echo sx7-nec-superux"$UNAME_RELEASE" exit ;; SX-8:SUPER-UX:*:*) - echo sx8-nec-superux${UNAME_RELEASE} + echo sx8-nec-superux"$UNAME_RELEASE" exit ;; SX-8R:SUPER-UX:*:*) - echo sx8r-nec-superux${UNAME_RELEASE} + echo sx8r-nec-superux"$UNAME_RELEASE" exit ;; SX-ACE:SUPER-UX:*:*) - echo sxace-nec-superux${UNAME_RELEASE} + echo sxace-nec-superux"$UNAME_RELEASE" exit ;; Power*:Rhapsody:*:*) - echo powerpc-apple-rhapsody${UNAME_RELEASE} + echo powerpc-apple-rhapsody"$UNAME_RELEASE" exit ;; *:Rhapsody:*:*) - echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} + echo "$UNAME_MACHINE"-apple-rhapsody"$UNAME_RELEASE" exit ;; *:Darwin:*:*) UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown - eval $set_cc_for_build + eval "$set_cc_for_build" if test "$UNAME_PROCESSOR" = unknown ; then UNAME_PROCESSOR=powerpc fi - if test `echo "$UNAME_RELEASE" | sed -e 's/\..*//'` -le 10 ; then + if test "`echo "$UNAME_RELEASE" | sed -e 's/\..*//'`" -le 10 ; then if [ "$CC_FOR_BUILD" != no_compiler_found ]; then if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ @@ -1307,7 +1321,7 @@ EOF # that Apple uses in portable devices. UNAME_PROCESSOR=x86_64 fi - echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} + echo "$UNAME_PROCESSOR"-apple-darwin"$UNAME_RELEASE" exit ;; *:procnto*:*:* | *:QNX:[0123456789]*:*) UNAME_PROCESSOR=`uname -p` @@ -1315,22 +1329,25 @@ EOF UNAME_PROCESSOR=i386 UNAME_MACHINE=pc fi - echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} + echo "$UNAME_PROCESSOR"-"$UNAME_MACHINE"-nto-qnx"$UNAME_RELEASE" exit ;; *:QNX:*:4*) echo i386-pc-qnx exit ;; NEO-*:NONSTOP_KERNEL:*:*) - echo neo-tandem-nsk${UNAME_RELEASE} + echo neo-tandem-nsk"$UNAME_RELEASE" exit ;; NSE-*:NONSTOP_KERNEL:*:*) - echo nse-tandem-nsk${UNAME_RELEASE} + echo nse-tandem-nsk"$UNAME_RELEASE" exit ;; NSR-*:NONSTOP_KERNEL:*:*) - echo nsr-tandem-nsk${UNAME_RELEASE} + echo nsr-tandem-nsk"$UNAME_RELEASE" + exit ;; + NSV-*:NONSTOP_KERNEL:*:*) + echo nsv-tandem-nsk"$UNAME_RELEASE" exit ;; NSX-*:NONSTOP_KERNEL:*:*) - echo nsx-tandem-nsk${UNAME_RELEASE} + echo nsx-tandem-nsk"$UNAME_RELEASE" exit ;; *:NonStop-UX:*:*) echo mips-compaq-nonstopux @@ -1339,7 +1356,7 @@ EOF echo bs2000-siemens-sysv exit ;; DS/*:UNIX_System_V:*:*) - echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} + echo "$UNAME_MACHINE"-"$UNAME_SYSTEM"-"$UNAME_RELEASE" exit ;; *:Plan9:*:*) # "uname -m" is not consistent, so use $cputype instead. 386 @@ -1350,7 +1367,7 @@ EOF else UNAME_MACHINE="$cputype" fi - echo ${UNAME_MACHINE}-unknown-plan9 + echo "$UNAME_MACHINE"-unknown-plan9 exit ;; *:TOPS-10:*:*) echo pdp10-unknown-tops10 @@ -1371,14 +1388,14 @@ EOF echo pdp10-unknown-its exit ;; SEI:*:*:SEIUX) - echo mips-sei-seiux${UNAME_RELEASE} + echo mips-sei-seiux"$UNAME_RELEASE" exit ;; *:DragonFly:*:*) - echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` + echo "$UNAME_MACHINE"-unknown-dragonfly"`echo "$UNAME_RELEASE"|sed -e 's/[-(].*//'`" exit ;; *:*VMS:*:*) UNAME_MACHINE=`(uname -p) 2>/dev/null` - case "${UNAME_MACHINE}" in + case "$UNAME_MACHINE" in A*) echo alpha-dec-vms ; exit ;; I*) echo ia64-dec-vms ; exit ;; V*) echo vax-dec-vms ; exit ;; @@ -1387,16 +1404,16 @@ EOF echo i386-pc-xenix exit ;; i*86:skyos:*:*) - echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE} | sed -e 's/ .*$//'` + echo "$UNAME_MACHINE"-pc-skyos"`echo "$UNAME_RELEASE" | sed -e 's/ .*$//'`" exit ;; i*86:rdos:*:*) - echo ${UNAME_MACHINE}-pc-rdos + echo "$UNAME_MACHINE"-pc-rdos exit ;; i*86:AROS:*:*) - echo ${UNAME_MACHINE}-pc-aros + echo "$UNAME_MACHINE"-pc-aros exit ;; x86_64:VMkernel:*:*) - echo ${UNAME_MACHINE}-unknown-esx + echo "$UNAME_MACHINE"-unknown-esx exit ;; amd64:Isilon\ OneFS:*:*) echo x86_64-unknown-onefs @@ -1405,7 +1422,7 @@ esac echo "$0: unable to guess system type" >&2 -case "${UNAME_MACHINE}:${UNAME_SYSTEM}" in +case "$UNAME_MACHINE:$UNAME_SYSTEM" in mips:Linux | mips64:Linux) # If we got here on MIPS GNU/Linux, output extra information. cat >&2 </dev/null` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` -UNAME_MACHINE = ${UNAME_MACHINE} -UNAME_RELEASE = ${UNAME_RELEASE} -UNAME_SYSTEM = ${UNAME_SYSTEM} -UNAME_VERSION = ${UNAME_VERSION} +UNAME_MACHINE = "$UNAME_MACHINE" +UNAME_RELEASE = "$UNAME_RELEASE" +UNAME_SYSTEM = "$UNAME_SYSTEM" +UNAME_VERSION = "$UNAME_VERSION" EOF exit 1 diff --git a/third_party/protobuf/config.sub b/third_party/protobuf/config.sub index 00f68b8e..1d8e98bc 100755 --- a/third_party/protobuf/config.sub +++ b/third_party/protobuf/config.sub @@ -1,8 +1,8 @@ #! /bin/sh # Configuration validation subroutine script. -# Copyright 1992-2017 Free Software Foundation, Inc. +# Copyright 1992-2018 Free Software Foundation, Inc. -timestamp='2017-11-23' +timestamp='2018-02-22' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by @@ -67,7 +67,7 @@ Report bugs and patches to ." version="\ GNU config.sub ($timestamp) -Copyright 1992-2017 Free Software Foundation, Inc. +Copyright 1992-2018 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." @@ -94,7 +94,7 @@ while test $# -gt 0 ; do *local*) # First pass through any local machine types. - echo $1 + echo "$1" exit ;; * ) @@ -112,7 +112,7 @@ esac # Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). # Here we must recognize all the valid KERNEL-OS combinations. -maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` +maybe_os=`echo "$1" | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` case $maybe_os in nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \ linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \ @@ -120,16 +120,16 @@ case $maybe_os in kopensolaris*-gnu* | cloudabi*-eabi* | \ storm-chaos* | os2-emx* | rtmk-nova*) os=-$maybe_os - basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` + basic_machine=`echo "$1" | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` ;; android-linux) os=-linux-android - basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown + basic_machine=`echo "$1" | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown ;; *) - basic_machine=`echo $1 | sed 's/-[^-]*$//'` - if [ $basic_machine != $1 ] - then os=`echo $1 | sed 's/.*-/-/'` + basic_machine=`echo "$1" | sed 's/-[^-]*$//'` + if [ "$basic_machine" != "$1" ] + then os=`echo "$1" | sed 's/.*-/-/'` else os=; fi ;; esac @@ -178,44 +178,44 @@ case $os in ;; -sco6) os=-sco5v6 - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'` ;; -sco5) os=-sco3.2v5 - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'` ;; -sco4) os=-sco3.2v4 - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'` ;; -sco3.2.[4-9]*) os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'` ;; -sco3.2v[4-9]*) # Don't forget version if it is 3.2v4 or newer. - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'` ;; -sco5v6*) # Don't forget version if it is 3.2v4 or newer. - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'` ;; -sco*) os=-sco3.2v2 - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'` ;; -udk*) - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'` ;; -isc) os=-isc2.2 - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'` ;; -clix*) basic_machine=clipper-intergraph ;; -isc*) - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'` ;; -lynx*178) os=-lynxos178 @@ -227,7 +227,7 @@ case $os in os=-lynxos ;; -ptx*) - basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` + basic_machine=`echo "$1" | sed -e 's/86-.*/86-sequent/'` ;; -psos*) os=-psos @@ -296,7 +296,7 @@ case $basic_machine in | nios | nios2 | nios2eb | nios2el \ | ns16k | ns32k \ | open8 | or1k | or1knd | or32 \ - | pdp10 | pdp11 | pj | pjl \ + | pdp10 | pj | pjl \ | powerpc | powerpc64 | powerpc64le | powerpcle \ | pru \ | pyramid \ @@ -333,7 +333,7 @@ case $basic_machine in basic_machine=$basic_machine-unknown os=-none ;; - m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) + m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65) ;; ms1) basic_machine=mt-unknown @@ -362,7 +362,7 @@ case $basic_machine in ;; # Object if more than one company name word. *-*-*) - echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + echo Invalid configuration \`"$1"\': machine \`"$basic_machine"\' not recognized 1>&2 exit 1 ;; # Recognize the basic CPU types with company name. @@ -457,7 +457,7 @@ case $basic_machine in # Recognize the various machine names and aliases which stand # for a CPU type and a company and sometimes even an OS. 386bsd) - basic_machine=i386-unknown + basic_machine=i386-pc os=-bsd ;; 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) @@ -491,7 +491,7 @@ case $basic_machine in basic_machine=x86_64-pc ;; amd64-*) - basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` + basic_machine=x86_64-`echo "$basic_machine" | sed 's/^[^-]*-//'` ;; amdahl) basic_machine=580-amdahl @@ -536,7 +536,7 @@ case $basic_machine in os=-linux ;; blackfin-*) - basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'` + basic_machine=bfin-`echo "$basic_machine" | sed 's/^[^-]*-//'` os=-linux ;; bluegene*) @@ -544,13 +544,13 @@ case $basic_machine in os=-cnk ;; c54x-*) - basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'` + basic_machine=tic54x-`echo "$basic_machine" | sed 's/^[^-]*-//'` ;; c55x-*) - basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'` + basic_machine=tic55x-`echo "$basic_machine" | sed 's/^[^-]*-//'` ;; c6x-*) - basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'` + basic_machine=tic6x-`echo "$basic_machine" | sed 's/^[^-]*-//'` ;; c90) basic_machine=c90-cray @@ -648,7 +648,7 @@ case $basic_machine in os=$os"spe" ;; e500v[12]-*) - basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` + basic_machine=powerpc-`echo "$basic_machine" | sed 's/^[^-]*-//'` os=$os"spe" ;; ebmon29k) @@ -740,9 +740,6 @@ case $basic_machine in hp9k8[0-9][0-9] | hp8[0-9][0-9]) basic_machine=hppa1.0-hp ;; - hppa-next) - os=-nextstep3 - ;; hppaosf) basic_machine=hppa1.1-hp os=-osf @@ -755,26 +752,26 @@ case $basic_machine in basic_machine=i370-ibm ;; i*86v32) - basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + basic_machine=`echo "$1" | sed -e 's/86.*/86-pc/'` os=-sysv32 ;; i*86v4*) - basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + basic_machine=`echo "$1" | sed -e 's/86.*/86-pc/'` os=-sysv4 ;; i*86v) - basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + basic_machine=`echo "$1" | sed -e 's/86.*/86-pc/'` os=-sysv ;; i*86sol2) - basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + basic_machine=`echo "$1" | sed -e 's/86.*/86-pc/'` os=-solaris2 ;; i386mach) basic_machine=i386-mach os=-mach ;; - i386-vsta | vsta) + vsta) basic_machine=i386-unknown os=-vsta ;; @@ -793,19 +790,16 @@ case $basic_machine in os=-sysv ;; leon-*|leon[3-9]-*) - basic_machine=sparc-`echo $basic_machine | sed 's/-.*//'` + basic_machine=sparc-`echo "$basic_machine" | sed 's/-.*//'` ;; m68knommu) basic_machine=m68k-unknown os=-linux ;; m68knommu-*) - basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'` + basic_machine=m68k-`echo "$basic_machine" | sed 's/^[^-]*-//'` os=-linux ;; - m88k-omron*) - basic_machine=m88k-omron - ;; magnum | m3230) basic_machine=mips-mips os=-sysv @@ -837,10 +831,10 @@ case $basic_machine in os=-mint ;; mips3*-*) - basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` + basic_machine=`echo "$basic_machine" | sed -e 's/mips3/mips64/'` ;; mips3*) - basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown + basic_machine=`echo "$basic_machine" | sed -e 's/mips3/mips64/'`-unknown ;; monitor) basic_machine=m68k-rom68k @@ -859,7 +853,7 @@ case $basic_machine in os=-msdos ;; ms1-*) - basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` + basic_machine=`echo "$basic_machine" | sed -e 's/ms1-/mt-/'` ;; msys) basic_machine=i686-pc @@ -946,6 +940,9 @@ case $basic_machine in nsr-tandem) basic_machine=nsr-tandem ;; + nsv-tandem) + basic_machine=nsv-tandem + ;; nsx-tandem) basic_machine=nsx-tandem ;; @@ -981,7 +978,7 @@ case $basic_machine in os=-linux ;; parisc-*) - basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'` + basic_machine=hppa-`echo "$basic_machine" | sed 's/^[^-]*-//'` os=-linux ;; pbd) @@ -997,7 +994,7 @@ case $basic_machine in basic_machine=i386-pc ;; pc98-*) - basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'` + basic_machine=i386-`echo "$basic_machine" | sed 's/^[^-]*-//'` ;; pentium | p5 | k5 | k6 | nexgen | viac3) basic_machine=i586-pc @@ -1012,16 +1009,16 @@ case $basic_machine in basic_machine=i786-pc ;; pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) - basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` + basic_machine=i586-`echo "$basic_machine" | sed 's/^[^-]*-//'` ;; pentiumpro-* | p6-* | 6x86-* | athlon-*) - basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + basic_machine=i686-`echo "$basic_machine" | sed 's/^[^-]*-//'` ;; pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) - basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + basic_machine=i686-`echo "$basic_machine" | sed 's/^[^-]*-//'` ;; pentium4-*) - basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` + basic_machine=i786-`echo "$basic_machine" | sed 's/^[^-]*-//'` ;; pn) basic_machine=pn-gould @@ -1031,23 +1028,23 @@ case $basic_machine in ppc | ppcbe) basic_machine=powerpc-unknown ;; ppc-* | ppcbe-*) - basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` + basic_machine=powerpc-`echo "$basic_machine" | sed 's/^[^-]*-//'` ;; ppcle | powerpclittle) basic_machine=powerpcle-unknown ;; ppcle-* | powerpclittle-*) - basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` + basic_machine=powerpcle-`echo "$basic_machine" | sed 's/^[^-]*-//'` ;; ppc64) basic_machine=powerpc64-unknown ;; - ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` + ppc64-*) basic_machine=powerpc64-`echo "$basic_machine" | sed 's/^[^-]*-//'` ;; ppc64le | powerpc64little) basic_machine=powerpc64le-unknown ;; ppc64le-* | powerpc64little-*) - basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` + basic_machine=powerpc64le-`echo "$basic_machine" | sed 's/^[^-]*-//'` ;; ps2) basic_machine=i386-ibm @@ -1101,17 +1098,10 @@ case $basic_machine in sequent) basic_machine=i386-sequent ;; - sh) - basic_machine=sh-hitachi - os=-hms - ;; sh5el) basic_machine=sh5le-unknown ;; - sh64) - basic_machine=sh64-unknown - ;; - sparclite-wrs | simso-wrs) + simso-wrs) basic_machine=sparclite-wrs os=-vxworks ;; @@ -1130,7 +1120,7 @@ case $basic_machine in os=-sysv4 ;; strongarm-* | thumb-*) - basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'` + basic_machine=arm-`echo "$basic_machine" | sed 's/^[^-]*-//'` ;; sun2) basic_machine=m68000-sun @@ -1244,9 +1234,6 @@ case $basic_machine in basic_machine=a29k-wrs os=-vxworks ;; - wasm32) - basic_machine=wasm32-unknown - ;; w65*) basic_machine=w65-wdc os=-none @@ -1266,20 +1253,12 @@ case $basic_machine in basic_machine=xps100-honeywell ;; xscale-* | xscalee[bl]-*) - basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'` + basic_machine=`echo "$basic_machine" | sed 's/^xscale/arm/'` ;; ymp) basic_machine=ymp-cray os=-unicos ;; - z8k-*-coff) - basic_machine=z8k-unknown - os=-sim - ;; - z80-*-coff) - basic_machine=z80-unknown - os=-sim - ;; none) basic_machine=none-none os=-none @@ -1308,10 +1287,6 @@ case $basic_machine in vax) basic_machine=vax-dec ;; - pdp10) - # there are many clones, so DEC is not a safe bet - basic_machine=pdp10-unknown - ;; pdp11) basic_machine=pdp11-dec ;; @@ -1321,9 +1296,6 @@ case $basic_machine in sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele) basic_machine=sh-unknown ;; - sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v) - basic_machine=sparc-sun - ;; cydra) basic_machine=cydra-cydrome ;; @@ -1343,7 +1315,7 @@ case $basic_machine in # Make sure to match an already-canonicalized machine name. ;; *) - echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + echo Invalid configuration \`"$1"\': machine \`"$basic_machine"\' not recognized 1>&2 exit 1 ;; esac @@ -1351,10 +1323,10 @@ esac # Here we canonicalize certain aliases for manufacturers. case $basic_machine in *-digital*) - basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` + basic_machine=`echo "$basic_machine" | sed 's/digital.*/dec/'` ;; *-commodore*) - basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` + basic_machine=`echo "$basic_machine" | sed 's/commodore.*/cbm/'` ;; *) ;; @@ -1377,15 +1349,16 @@ case $os in -solaris) os=-solaris2 ;; - -svr4*) - os=-sysv4 - ;; -unixware*) os=-sysv4.2uw ;; -gnu/linux*) os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` ;; + # es1800 is here to avoid being matched by es* (a different OS) + -es1800*) + os=-ose + ;; # Now accept the basic system types. # The portable systems comes first. # Each alternative MUST end in a * to match a version number. @@ -1398,7 +1371,7 @@ case $os in | -aos* | -aros* | -cloudabi* | -sortix* \ | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ - | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \ + | -hiux* | -knetbsd* | -mirbsd* | -netbsd* \ | -bitrig* | -openbsd* | -solidbsd* | -libertybsd* \ | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ @@ -1409,14 +1382,15 @@ case $os in | -midipix* | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \ | -linux-newlib* | -linux-musl* | -linux-uclibc* \ | -uxpv* | -beos* | -mpeix* | -udk* | -moxiebox* \ - | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ + | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* \ | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ - | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ + | -morphos* | -superux* | -rtmk* | -windiss* \ | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es* \ - | -onefs* | -tirtos* | -phoenix* | -fuchsia* | -redox*) + | -onefs* | -tirtos* | -phoenix* | -fuchsia* | -redox* | -bme* \ + | -midnightbsd*) # Remember, each alternative MUST END IN *, to match a version number. ;; -qnx*) @@ -1433,12 +1407,12 @@ case $os in -nto*) os=`echo $os | sed -e 's|nto|nto-qnx|'` ;; - -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ - | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \ + -sim | -xray | -os68k* | -v88r* \ + | -windows* | -osx | -abug | -netware* | -os9* \ | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) ;; -mac*) - os=`echo $os | sed -e 's|mac|macos|'` + os=`echo "$os" | sed -e 's|mac|macos|'` ;; -linux-dietlibc) os=-linux-dietlibc @@ -1447,10 +1421,10 @@ case $os in os=`echo $os | sed -e 's|linux|linux-gnu|'` ;; -sunos5*) - os=`echo $os | sed -e 's|sunos5|solaris2|'` + os=`echo "$os" | sed -e 's|sunos5|solaris2|'` ;; -sunos6*) - os=`echo $os | sed -e 's|sunos6|solaris3|'` + os=`echo "$os" | sed -e 's|sunos6|solaris3|'` ;; -opened*) os=-openedition @@ -1461,12 +1435,6 @@ case $os in -wince*) os=-wince ;; - -osfrose*) - os=-osfrose - ;; - -osf*) - os=-osf - ;; -utek*) os=-bsd ;; @@ -1513,7 +1481,7 @@ case $os in -oss*) os=-sysv3 ;; - -svr4) + -svr4*) os=-sysv4 ;; -svr3) @@ -1528,18 +1496,9 @@ case $os in -ose*) os=-ose ;; - -es1800*) - os=-ose - ;; - -xenix) - os=-xenix - ;; -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) os=-mint ;; - -aros*) - os=-aros - ;; -zvmoe) os=-zvmoe ;; @@ -1568,7 +1527,7 @@ case $os in *) # Get rid of the `-' at the beginning of $os. os=`echo $os | sed 's/[^-]*-//'` - echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 + echo Invalid configuration \`"$1"\': system \`"$os"\' not recognized 1>&2 exit 1 ;; esac @@ -1664,9 +1623,6 @@ case $basic_machine in *-be) os=-beos ;; - *-haiku) - os=-haiku - ;; *-ibm) os=-aix ;; @@ -1721,9 +1677,6 @@ case $basic_machine in i370-*) os=-mvs ;; - *-next) - os=-nextstep3 - ;; *-gould) os=-sysv ;; @@ -1833,11 +1786,11 @@ case $basic_machine in vendor=stratus ;; esac - basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` + basic_machine=`echo "$basic_machine" | sed "s/unknown/$vendor/"` ;; esac -echo $basic_machine$os +echo "$basic_machine$os" exit # Local variables: diff --git a/third_party/protobuf/configure b/third_party/protobuf/configure index 0c54ee38..add76733 100755 --- a/third_party/protobuf/configure +++ b/third_party/protobuf/configure @@ -1,6 +1,6 @@ #! /bin/sh # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.69 for Protocol Buffers 3.6.1. +# Generated by GNU Autoconf 2.69 for Protocol Buffers 3.8.0. # # Report bugs to . # @@ -590,8 +590,8 @@ MAKEFLAGS= # Identity of this package. PACKAGE_NAME='Protocol Buffers' PACKAGE_TARNAME='protobuf' -PACKAGE_VERSION='3.6.1' -PACKAGE_STRING='Protocol Buffers 3.6.1' +PACKAGE_VERSION='3.8.0' +PACKAGE_STRING='Protocol Buffers 3.8.0' PACKAGE_BUGREPORT='protobuf@googlegroups.com' PACKAGE_URL='' @@ -637,7 +637,6 @@ ac_subst_vars='am__EXEEXT_FALSE am__EXEEXT_TRUE LTLIBOBJS subdirs -HAVE_CXX11 OBJC_CONFORMANCE_TEST_FALSE OBJC_CONFORMANCE_TEST_TRUE HAVE_PTHREAD_FALSE @@ -649,6 +648,8 @@ ax_pthread_config USE_EXTERNAL_PROTOC_FALSE USE_EXTERNAL_PROTOC_TRUE PROTOC +LIBATOMIC_LIBS +HAVE_CXX11 HAVE_ZLIB_FALSE HAVE_ZLIB_TRUE POW_LIB @@ -1394,7 +1395,7 @@ if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF -\`configure' configures Protocol Buffers 3.6.1 to adapt to many kinds of systems. +\`configure' configures Protocol Buffers 3.8.0 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... @@ -1466,7 +1467,7 @@ fi if test -n "$ac_init_help"; then case $ac_init_help in - short | recursive ) echo "Configuration of Protocol Buffers 3.6.1:";; + short | recursive ) echo "Configuration of Protocol Buffers 3.8.0:";; esac cat <<\_ACEOF @@ -1595,7 +1596,7 @@ fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF -Protocol Buffers configure 3.6.1 +Protocol Buffers configure 3.8.0 generated by GNU Autoconf 2.69 Copyright (C) 2012 Free Software Foundation, Inc. @@ -2267,7 +2268,7 @@ cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. -It was created by Protocol Buffers $as_me 3.6.1, which was +It was created by Protocol Buffers $as_me 3.8.0, which was generated by GNU Autoconf 2.69. Invocation command line was $ $0 $@ @@ -3294,7 +3295,7 @@ fi # Define the identity of the package. PACKAGE='protobuf' - VERSION='3.6.1' + VERSION='3.8.0' cat >>confdefs.h <<_ACEOF @@ -7595,7 +7596,7 @@ fi if test "$SUNCC" = "yes" -a "x${ac_cv_env_CXXFLAGS_set}" = "x"; then : - CXXFLAGS="-g0 -xO3 -xlibmil -xdepend -xbuiltin -mt -compat=5 -library=stlport4 -library=Crun -template=no%extdef ${CXXFLAGS}" + CXXFLAGS="-g0 -xO3 -xlibmil -xdepend -xbuiltin -mt -template=no%extdef ${CXXFLAGS}" fi @@ -7684,6 +7685,11 @@ fi ;; esac + if test "$target_cpu" = "sparc" -a "x$SUNCC" = "xyes" ; then : + + CXXFLAGS="-xregs=no%appl ${CXXFLAGS}" + +fi # Have to do libtool after SUNCC, other wise it "helpfully" adds Crun Cstd @@ -19118,6 +19124,739 @@ else fi +# Add -std=c++11 if necesssary. It is important for us to do this before the +# libatomic check below, since that also depends on C++11. + ax_cxx_compile_alternatives="11 0x" ax_cxx_compile_cxx11_required=true + ac_ext=cpp +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu + ac_success=no + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX supports C++11 features by default" >&5 +$as_echo_n "checking whether $CXX supports C++11 features by default... " >&6; } +if ${ax_cv_cxx_compile_cxx11+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +// If the compiler admits that it is not ready for C++11, why torture it? +// Hopefully, this will speed up the test. + +#ifndef __cplusplus + +#error "This is not a C++ compiler" + +#elif __cplusplus < 201103L + +#error "This is not a C++11 compiler" + +#else + +#include + +namespace cxx11 +{ + + namespace test_static_assert + { + + template + struct check + { + static_assert(sizeof(int) <= sizeof(T), "not big enough"); + }; + + } + + namespace test_final_override + { + + struct Base + { + virtual void f() {} + }; + + struct Derived : public Base + { + virtual void f() override {} + }; + + } + + namespace test_double_right_angle_brackets + { + + template < typename T > + struct check {}; + + typedef check single_type; + typedef check> double_type; + typedef check>> triple_type; + typedef check>>> quadruple_type; + + } + + namespace test_decltype + { + + int + f() + { + int a = 1; + decltype(a) b = 2; + return a + b; + } + + } + + namespace test_type_deduction + { + + template < typename T1, typename T2 > + struct is_same + { + static const bool value = false; + }; + + template < typename T > + struct is_same + { + static const bool value = true; + }; + + template < typename T1, typename T2 > + auto + add(T1 a1, T2 a2) -> decltype(a1 + a2) + { + return a1 + a2; + } + + int + test(const int c, volatile int v) + { + static_assert(is_same::value == true, ""); + static_assert(is_same::value == false, ""); + static_assert(is_same::value == false, ""); + auto ac = c; + auto av = v; + auto sumi = ac + av + 'x'; + auto sumf = ac + av + 1.0; + static_assert(is_same::value == true, ""); + static_assert(is_same::value == true, ""); + static_assert(is_same::value == true, ""); + static_assert(is_same::value == false, ""); + static_assert(is_same::value == true, ""); + return (sumf > 0.0) ? sumi : add(c, v); + } + + } + + namespace test_noexcept + { + + int f() { return 0; } + int g() noexcept { return 0; } + + static_assert(noexcept(f()) == false, ""); + static_assert(noexcept(g()) == true, ""); + + } + + namespace test_constexpr + { + + template < typename CharT > + unsigned long constexpr + strlen_c_r(const CharT *const s, const unsigned long acc) noexcept + { + return *s ? strlen_c_r(s + 1, acc + 1) : acc; + } + + template < typename CharT > + unsigned long constexpr + strlen_c(const CharT *const s) noexcept + { + return strlen_c_r(s, 0UL); + } + + static_assert(strlen_c("") == 0UL, ""); + static_assert(strlen_c("1") == 1UL, ""); + static_assert(strlen_c("example") == 7UL, ""); + static_assert(strlen_c("another\0example") == 7UL, ""); + + } + + namespace test_rvalue_references + { + + template < int N > + struct answer + { + static constexpr int value = N; + }; + + answer<1> f(int&) { return answer<1>(); } + answer<2> f(const int&) { return answer<2>(); } + answer<3> f(int&&) { return answer<3>(); } + + void + test() + { + int i = 0; + const int c = 0; + static_assert(decltype(f(i))::value == 1, ""); + static_assert(decltype(f(c))::value == 2, ""); + static_assert(decltype(f(0))::value == 3, ""); + } + + } + + namespace test_uniform_initialization + { + + struct test + { + static const int zero {}; + static const int one {1}; + }; + + static_assert(test::zero == 0, ""); + static_assert(test::one == 1, ""); + + } + + namespace test_lambdas + { + + void + test1() + { + auto lambda1 = [](){}; + auto lambda2 = lambda1; + lambda1(); + lambda2(); + } + + int + test2() + { + auto a = [](int i, int j){ return i + j; }(1, 2); + auto b = []() -> int { return '0'; }(); + auto c = [=](){ return a + b; }(); + auto d = [&](){ return c; }(); + auto e = [a, &b](int x) mutable { + const auto identity = [](int y){ return y; }; + for (auto i = 0; i < a; ++i) + a += b--; + return x + identity(a + b); + }(0); + return a + b + c + d + e; + } + + int + test3() + { + const auto nullary = [](){ return 0; }; + const auto unary = [](int x){ return x; }; + using nullary_t = decltype(nullary); + using unary_t = decltype(unary); + const auto higher1st = [](nullary_t f){ return f(); }; + const auto higher2nd = [unary](nullary_t f1){ + return [unary, f1](unary_t f2){ return f2(unary(f1())); }; + }; + return higher1st(nullary) + higher2nd(nullary)(unary); + } + + } + + namespace test_variadic_templates + { + + template + struct sum; + + template + struct sum + { + static constexpr auto value = N0 + sum::value; + }; + + template <> + struct sum<> + { + static constexpr auto value = 0; + }; + + static_assert(sum<>::value == 0, ""); + static_assert(sum<1>::value == 1, ""); + static_assert(sum<23>::value == 23, ""); + static_assert(sum<1, 2>::value == 3, ""); + static_assert(sum<5, 5, 11>::value == 21, ""); + static_assert(sum<2, 3, 5, 7, 11, 13>::value == 41, ""); + + } + + // http://stackoverflow.com/questions/13728184/template-aliases-and-sfinae + // Clang 3.1 fails with headers of libstd++ 4.8.3 when using std::function + // because of this. + namespace test_template_alias_sfinae + { + + struct foo {}; + + template + using member = typename T::member_type; + + template + void func(...) {} + + template + void func(member*) {} + + void test(); + + void test() { func(0); } + + } + + namespace test_std_move_and_forward + { + struct message {}; + char foo(message&) { return '\0'; } + int foo(message&&) { return 0; } + + template + void check(Arg&& arg, RT rt) { + static_assert(sizeof(rt) == sizeof(foo(std::forward(arg))), ""); + } + void test() { + message a; + check(a, char()); + check(std::move(a), int()); + } + } + +} // namespace cxx11 + +#endif // __cplusplus >= 201103L + + + +_ACEOF +if ac_fn_cxx_try_compile "$LINENO"; then : + ax_cv_cxx_compile_cxx11=yes +else + ax_cv_cxx_compile_cxx11=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ax_cv_cxx_compile_cxx11" >&5 +$as_echo "$ax_cv_cxx_compile_cxx11" >&6; } + if test x$ax_cv_cxx_compile_cxx11 = xyes; then + ac_success=yes + fi + + + + if test x$ac_success = xno; then + for alternative in ${ax_cxx_compile_alternatives}; do + for switch in -std=c++${alternative} +std=c++${alternative} "-h std=c++${alternative}"; do + cachevar=`$as_echo "ax_cv_cxx_compile_cxx11_$switch" | $as_tr_sh` + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX supports C++11 features with $switch" >&5 +$as_echo_n "checking whether $CXX supports C++11 features with $switch... " >&6; } +if eval \${$cachevar+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_save_CXX="$CXX" + CXX="$CXX $switch" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +// If the compiler admits that it is not ready for C++11, why torture it? +// Hopefully, this will speed up the test. + +#ifndef __cplusplus + +#error "This is not a C++ compiler" + +#elif __cplusplus < 201103L + +#error "This is not a C++11 compiler" + +#else + +#include + +namespace cxx11 +{ + + namespace test_static_assert + { + + template + struct check + { + static_assert(sizeof(int) <= sizeof(T), "not big enough"); + }; + + } + + namespace test_final_override + { + + struct Base + { + virtual void f() {} + }; + + struct Derived : public Base + { + virtual void f() override {} + }; + + } + + namespace test_double_right_angle_brackets + { + + template < typename T > + struct check {}; + + typedef check single_type; + typedef check> double_type; + typedef check>> triple_type; + typedef check>>> quadruple_type; + + } + + namespace test_decltype + { + + int + f() + { + int a = 1; + decltype(a) b = 2; + return a + b; + } + + } + + namespace test_type_deduction + { + + template < typename T1, typename T2 > + struct is_same + { + static const bool value = false; + }; + + template < typename T > + struct is_same + { + static const bool value = true; + }; + + template < typename T1, typename T2 > + auto + add(T1 a1, T2 a2) -> decltype(a1 + a2) + { + return a1 + a2; + } + + int + test(const int c, volatile int v) + { + static_assert(is_same::value == true, ""); + static_assert(is_same::value == false, ""); + static_assert(is_same::value == false, ""); + auto ac = c; + auto av = v; + auto sumi = ac + av + 'x'; + auto sumf = ac + av + 1.0; + static_assert(is_same::value == true, ""); + static_assert(is_same::value == true, ""); + static_assert(is_same::value == true, ""); + static_assert(is_same::value == false, ""); + static_assert(is_same::value == true, ""); + return (sumf > 0.0) ? sumi : add(c, v); + } + + } + + namespace test_noexcept + { + + int f() { return 0; } + int g() noexcept { return 0; } + + static_assert(noexcept(f()) == false, ""); + static_assert(noexcept(g()) == true, ""); + + } + + namespace test_constexpr + { + + template < typename CharT > + unsigned long constexpr + strlen_c_r(const CharT *const s, const unsigned long acc) noexcept + { + return *s ? strlen_c_r(s + 1, acc + 1) : acc; + } + + template < typename CharT > + unsigned long constexpr + strlen_c(const CharT *const s) noexcept + { + return strlen_c_r(s, 0UL); + } + + static_assert(strlen_c("") == 0UL, ""); + static_assert(strlen_c("1") == 1UL, ""); + static_assert(strlen_c("example") == 7UL, ""); + static_assert(strlen_c("another\0example") == 7UL, ""); + + } + + namespace test_rvalue_references + { + + template < int N > + struct answer + { + static constexpr int value = N; + }; + + answer<1> f(int&) { return answer<1>(); } + answer<2> f(const int&) { return answer<2>(); } + answer<3> f(int&&) { return answer<3>(); } + + void + test() + { + int i = 0; + const int c = 0; + static_assert(decltype(f(i))::value == 1, ""); + static_assert(decltype(f(c))::value == 2, ""); + static_assert(decltype(f(0))::value == 3, ""); + } + + } + + namespace test_uniform_initialization + { + + struct test + { + static const int zero {}; + static const int one {1}; + }; + + static_assert(test::zero == 0, ""); + static_assert(test::one == 1, ""); + + } + + namespace test_lambdas + { + + void + test1() + { + auto lambda1 = [](){}; + auto lambda2 = lambda1; + lambda1(); + lambda2(); + } + + int + test2() + { + auto a = [](int i, int j){ return i + j; }(1, 2); + auto b = []() -> int { return '0'; }(); + auto c = [=](){ return a + b; }(); + auto d = [&](){ return c; }(); + auto e = [a, &b](int x) mutable { + const auto identity = [](int y){ return y; }; + for (auto i = 0; i < a; ++i) + a += b--; + return x + identity(a + b); + }(0); + return a + b + c + d + e; + } + + int + test3() + { + const auto nullary = [](){ return 0; }; + const auto unary = [](int x){ return x; }; + using nullary_t = decltype(nullary); + using unary_t = decltype(unary); + const auto higher1st = [](nullary_t f){ return f(); }; + const auto higher2nd = [unary](nullary_t f1){ + return [unary, f1](unary_t f2){ return f2(unary(f1())); }; + }; + return higher1st(nullary) + higher2nd(nullary)(unary); + } + + } + + namespace test_variadic_templates + { + + template + struct sum; + + template + struct sum + { + static constexpr auto value = N0 + sum::value; + }; + + template <> + struct sum<> + { + static constexpr auto value = 0; + }; + + static_assert(sum<>::value == 0, ""); + static_assert(sum<1>::value == 1, ""); + static_assert(sum<23>::value == 23, ""); + static_assert(sum<1, 2>::value == 3, ""); + static_assert(sum<5, 5, 11>::value == 21, ""); + static_assert(sum<2, 3, 5, 7, 11, 13>::value == 41, ""); + + } + + // http://stackoverflow.com/questions/13728184/template-aliases-and-sfinae + // Clang 3.1 fails with headers of libstd++ 4.8.3 when using std::function + // because of this. + namespace test_template_alias_sfinae + { + + struct foo {}; + + template + using member = typename T::member_type; + + template + void func(...) {} + + template + void func(member*) {} + + void test(); + + void test() { func(0); } + + } + + namespace test_std_move_and_forward + { + struct message {}; + char foo(message&) { return '\0'; } + int foo(message&&) { return 0; } + + template + void check(Arg&& arg, RT rt) { + static_assert(sizeof(rt) == sizeof(foo(std::forward(arg))), ""); + } + void test() { + message a; + check(a, char()); + check(std::move(a), int()); + } + } + +} // namespace cxx11 + +#endif // __cplusplus >= 201103L + + + +_ACEOF +if ac_fn_cxx_try_compile "$LINENO"; then : + eval $cachevar=yes +else + eval $cachevar=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + CXX="$ac_save_CXX" +fi +eval ac_res=\$$cachevar + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + if eval test x\$$cachevar = xyes; then + CXX="$CXX $switch" + if test -n "$CXXCPP" ; then + CXXCPP="$CXXCPP $switch" + fi + ac_success=yes + break + fi + done + if test x$ac_success = xyes; then + break + fi + done + fi + ac_ext=cpp +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu + + if test x$ax_cxx_compile_cxx11_required = xtrue; then + if test x$ac_success = xno; then + as_fn_error $? "*** A compiler with support for C++11 language features is required." "$LINENO" 5 + fi + fi + if test x$ac_success = xno; then + HAVE_CXX11=0 + { $as_echo "$as_me:${as_lineno-$LINENO}: No compiler with C++11 support was found" >&5 +$as_echo "$as_me: No compiler with C++11 support was found" >&6;} + else + HAVE_CXX11=1 + +$as_echo "#define HAVE_CXX11 1" >>confdefs.h + + fi + + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -latomic is needed" >&5 +$as_echo_n "checking whether -latomic is needed... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + #include + #include + std::atomic v; + int main() { + return v; + } + +_ACEOF +if ac_fn_cxx_try_link "$LINENO"; then : + STD_ATOMIC_NEED_LIBATOMIC=no +else + STD_ATOMIC_NEED_LIBATOMIC=yes +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $STD_ATOMIC_NEED_LIBATOMIC" >&5 +$as_echo "$STD_ATOMIC_NEED_LIBATOMIC" >&6; } +if test "x$STD_ATOMIC_NEED_LIBATOMIC" = xyes; then + LIBATOMIC_LIBS="-latomic" +fi + + if test "$with_protoc" != "no"; then : PROTOC=$with_protoc @@ -19927,75 +20666,6 @@ $as_echo "$as_me: WARNING: could not find an STL hash_map" >&2;} fi -case "$target_os" in - mingw* | cygwin* | win* | aix*) - ;; - *) - # Need to link against rt on Solaris - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing sched_yield" >&5 -$as_echo_n "checking for library containing sched_yield... " >&6; } -if ${ac_cv_search_sched_yield+:} false; then : - $as_echo_n "(cached) " >&6 -else - ac_func_search_save_LIBS=$LIBS -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char sched_yield (); -int -main () -{ -return sched_yield (); - ; - return 0; -} -_ACEOF -for ac_lib in '' rt; do - if test -z "$ac_lib"; then - ac_res="none required" - else - ac_res=-l$ac_lib - LIBS="-l$ac_lib $ac_func_search_save_LIBS" - fi - if ac_fn_cxx_try_link "$LINENO"; then : - ac_cv_search_sched_yield=$ac_res -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext - if ${ac_cv_search_sched_yield+:} false; then : - break -fi -done -if ${ac_cv_search_sched_yield+:} false; then : - -else - ac_cv_search_sched_yield=no -fi -rm conftest.$ac_ext -LIBS=$ac_func_search_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_sched_yield" >&5 -$as_echo "$ac_cv_search_sched_yield" >&6; } -ac_res=$ac_cv_search_sched_yield -if test "$ac_res" != no; then : - test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" - -else - { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error $? "sched_yield was not found on your system -See \`config.log' for more details" "$LINENO" 5; } -fi - - ;; -esac - # Enable ObjC support for conformance directory on OS X. OBJC_CONFORMANCE_TEST=0 case "$target_os" in @@ -20012,710 +20682,6 @@ else fi - ax_cxx_compile_alternatives="11 0x" ax_cxx_compile_cxx11_required=true - ac_ext=cpp -ac_cpp='$CXXCPP $CPPFLAGS' -ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_cxx_compiler_gnu - ac_success=no - { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX supports C++11 features by default" >&5 -$as_echo_n "checking whether $CXX supports C++11 features by default... " >&6; } -if ${ax_cv_cxx_compile_cxx11+:} false; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - - -// If the compiler admits that it is not ready for C++11, why torture it? -// Hopefully, this will speed up the test. - -#ifndef __cplusplus - -#error "This is not a C++ compiler" - -#elif __cplusplus < 201103L - -#error "This is not a C++11 compiler" - -#else - -#include - -namespace cxx11 -{ - - namespace test_static_assert - { - - template - struct check - { - static_assert(sizeof(int) <= sizeof(T), "not big enough"); - }; - - } - - namespace test_final_override - { - - struct Base - { - virtual void f() {} - }; - - struct Derived : public Base - { - virtual void f() override {} - }; - - } - - namespace test_double_right_angle_brackets - { - - template < typename T > - struct check {}; - - typedef check single_type; - typedef check> double_type; - typedef check>> triple_type; - typedef check>>> quadruple_type; - - } - - namespace test_decltype - { - - int - f() - { - int a = 1; - decltype(a) b = 2; - return a + b; - } - - } - - namespace test_type_deduction - { - - template < typename T1, typename T2 > - struct is_same - { - static const bool value = false; - }; - - template < typename T > - struct is_same - { - static const bool value = true; - }; - - template < typename T1, typename T2 > - auto - add(T1 a1, T2 a2) -> decltype(a1 + a2) - { - return a1 + a2; - } - - int - test(const int c, volatile int v) - { - static_assert(is_same::value == true, ""); - static_assert(is_same::value == false, ""); - static_assert(is_same::value == false, ""); - auto ac = c; - auto av = v; - auto sumi = ac + av + 'x'; - auto sumf = ac + av + 1.0; - static_assert(is_same::value == true, ""); - static_assert(is_same::value == true, ""); - static_assert(is_same::value == true, ""); - static_assert(is_same::value == false, ""); - static_assert(is_same::value == true, ""); - return (sumf > 0.0) ? sumi : add(c, v); - } - - } - - namespace test_noexcept - { - - int f() { return 0; } - int g() noexcept { return 0; } - - static_assert(noexcept(f()) == false, ""); - static_assert(noexcept(g()) == true, ""); - - } - - namespace test_constexpr - { - - template < typename CharT > - unsigned long constexpr - strlen_c_r(const CharT *const s, const unsigned long acc) noexcept - { - return *s ? strlen_c_r(s + 1, acc + 1) : acc; - } - - template < typename CharT > - unsigned long constexpr - strlen_c(const CharT *const s) noexcept - { - return strlen_c_r(s, 0UL); - } - - static_assert(strlen_c("") == 0UL, ""); - static_assert(strlen_c("1") == 1UL, ""); - static_assert(strlen_c("example") == 7UL, ""); - static_assert(strlen_c("another\0example") == 7UL, ""); - - } - - namespace test_rvalue_references - { - - template < int N > - struct answer - { - static constexpr int value = N; - }; - - answer<1> f(int&) { return answer<1>(); } - answer<2> f(const int&) { return answer<2>(); } - answer<3> f(int&&) { return answer<3>(); } - - void - test() - { - int i = 0; - const int c = 0; - static_assert(decltype(f(i))::value == 1, ""); - static_assert(decltype(f(c))::value == 2, ""); - static_assert(decltype(f(0))::value == 3, ""); - } - - } - - namespace test_uniform_initialization - { - - struct test - { - static const int zero {}; - static const int one {1}; - }; - - static_assert(test::zero == 0, ""); - static_assert(test::one == 1, ""); - - } - - namespace test_lambdas - { - - void - test1() - { - auto lambda1 = [](){}; - auto lambda2 = lambda1; - lambda1(); - lambda2(); - } - - int - test2() - { - auto a = [](int i, int j){ return i + j; }(1, 2); - auto b = []() -> int { return '0'; }(); - auto c = [=](){ return a + b; }(); - auto d = [&](){ return c; }(); - auto e = [a, &b](int x) mutable { - const auto identity = [](int y){ return y; }; - for (auto i = 0; i < a; ++i) - a += b--; - return x + identity(a + b); - }(0); - return a + b + c + d + e; - } - - int - test3() - { - const auto nullary = [](){ return 0; }; - const auto unary = [](int x){ return x; }; - using nullary_t = decltype(nullary); - using unary_t = decltype(unary); - const auto higher1st = [](nullary_t f){ return f(); }; - const auto higher2nd = [unary](nullary_t f1){ - return [unary, f1](unary_t f2){ return f2(unary(f1())); }; - }; - return higher1st(nullary) + higher2nd(nullary)(unary); - } - - } - - namespace test_variadic_templates - { - - template - struct sum; - - template - struct sum - { - static constexpr auto value = N0 + sum::value; - }; - - template <> - struct sum<> - { - static constexpr auto value = 0; - }; - - static_assert(sum<>::value == 0, ""); - static_assert(sum<1>::value == 1, ""); - static_assert(sum<23>::value == 23, ""); - static_assert(sum<1, 2>::value == 3, ""); - static_assert(sum<5, 5, 11>::value == 21, ""); - static_assert(sum<2, 3, 5, 7, 11, 13>::value == 41, ""); - - } - - // http://stackoverflow.com/questions/13728184/template-aliases-and-sfinae - // Clang 3.1 fails with headers of libstd++ 4.8.3 when using std::function - // because of this. - namespace test_template_alias_sfinae - { - - struct foo {}; - - template - using member = typename T::member_type; - - template - void func(...) {} - - template - void func(member*) {} - - void test(); - - void test() { func(0); } - - } - - namespace test_std_move_and_forward - { - struct message {}; - char foo(message&) { return '\0'; } - int foo(message&&) { return 0; } - - template - void check(Arg&& arg, RT rt) { - static_assert(sizeof(rt) == sizeof(foo(std::forward(arg))), ""); - } - void test() { - message a; - check(a, char()); - check(std::move(a), int()); - } - } - -} // namespace cxx11 - -#endif // __cplusplus >= 201103L - - - -_ACEOF -if ac_fn_cxx_try_compile "$LINENO"; then : - ax_cv_cxx_compile_cxx11=yes -else - ax_cv_cxx_compile_cxx11=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ax_cv_cxx_compile_cxx11" >&5 -$as_echo "$ax_cv_cxx_compile_cxx11" >&6; } - if test x$ax_cv_cxx_compile_cxx11 = xyes; then - ac_success=yes - fi - - - - if test x$ac_success = xno; then - for alternative in ${ax_cxx_compile_alternatives}; do - for switch in -std=c++${alternative} +std=c++${alternative} "-h std=c++${alternative}"; do - cachevar=`$as_echo "ax_cv_cxx_compile_cxx11_$switch" | $as_tr_sh` - { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX supports C++11 features with $switch" >&5 -$as_echo_n "checking whether $CXX supports C++11 features with $switch... " >&6; } -if eval \${$cachevar+:} false; then : - $as_echo_n "(cached) " >&6 -else - ac_save_CXX="$CXX" - CXX="$CXX $switch" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - - -// If the compiler admits that it is not ready for C++11, why torture it? -// Hopefully, this will speed up the test. - -#ifndef __cplusplus - -#error "This is not a C++ compiler" - -#elif __cplusplus < 201103L - -#error "This is not a C++11 compiler" - -#else - -#include - -namespace cxx11 -{ - - namespace test_static_assert - { - - template - struct check - { - static_assert(sizeof(int) <= sizeof(T), "not big enough"); - }; - - } - - namespace test_final_override - { - - struct Base - { - virtual void f() {} - }; - - struct Derived : public Base - { - virtual void f() override {} - }; - - } - - namespace test_double_right_angle_brackets - { - - template < typename T > - struct check {}; - - typedef check single_type; - typedef check> double_type; - typedef check>> triple_type; - typedef check>>> quadruple_type; - - } - - namespace test_decltype - { - - int - f() - { - int a = 1; - decltype(a) b = 2; - return a + b; - } - - } - - namespace test_type_deduction - { - - template < typename T1, typename T2 > - struct is_same - { - static const bool value = false; - }; - - template < typename T > - struct is_same - { - static const bool value = true; - }; - - template < typename T1, typename T2 > - auto - add(T1 a1, T2 a2) -> decltype(a1 + a2) - { - return a1 + a2; - } - - int - test(const int c, volatile int v) - { - static_assert(is_same::value == true, ""); - static_assert(is_same::value == false, ""); - static_assert(is_same::value == false, ""); - auto ac = c; - auto av = v; - auto sumi = ac + av + 'x'; - auto sumf = ac + av + 1.0; - static_assert(is_same::value == true, ""); - static_assert(is_same::value == true, ""); - static_assert(is_same::value == true, ""); - static_assert(is_same::value == false, ""); - static_assert(is_same::value == true, ""); - return (sumf > 0.0) ? sumi : add(c, v); - } - - } - - namespace test_noexcept - { - - int f() { return 0; } - int g() noexcept { return 0; } - - static_assert(noexcept(f()) == false, ""); - static_assert(noexcept(g()) == true, ""); - - } - - namespace test_constexpr - { - - template < typename CharT > - unsigned long constexpr - strlen_c_r(const CharT *const s, const unsigned long acc) noexcept - { - return *s ? strlen_c_r(s + 1, acc + 1) : acc; - } - - template < typename CharT > - unsigned long constexpr - strlen_c(const CharT *const s) noexcept - { - return strlen_c_r(s, 0UL); - } - - static_assert(strlen_c("") == 0UL, ""); - static_assert(strlen_c("1") == 1UL, ""); - static_assert(strlen_c("example") == 7UL, ""); - static_assert(strlen_c("another\0example") == 7UL, ""); - - } - - namespace test_rvalue_references - { - - template < int N > - struct answer - { - static constexpr int value = N; - }; - - answer<1> f(int&) { return answer<1>(); } - answer<2> f(const int&) { return answer<2>(); } - answer<3> f(int&&) { return answer<3>(); } - - void - test() - { - int i = 0; - const int c = 0; - static_assert(decltype(f(i))::value == 1, ""); - static_assert(decltype(f(c))::value == 2, ""); - static_assert(decltype(f(0))::value == 3, ""); - } - - } - - namespace test_uniform_initialization - { - - struct test - { - static const int zero {}; - static const int one {1}; - }; - - static_assert(test::zero == 0, ""); - static_assert(test::one == 1, ""); - - } - - namespace test_lambdas - { - - void - test1() - { - auto lambda1 = [](){}; - auto lambda2 = lambda1; - lambda1(); - lambda2(); - } - - int - test2() - { - auto a = [](int i, int j){ return i + j; }(1, 2); - auto b = []() -> int { return '0'; }(); - auto c = [=](){ return a + b; }(); - auto d = [&](){ return c; }(); - auto e = [a, &b](int x) mutable { - const auto identity = [](int y){ return y; }; - for (auto i = 0; i < a; ++i) - a += b--; - return x + identity(a + b); - }(0); - return a + b + c + d + e; - } - - int - test3() - { - const auto nullary = [](){ return 0; }; - const auto unary = [](int x){ return x; }; - using nullary_t = decltype(nullary); - using unary_t = decltype(unary); - const auto higher1st = [](nullary_t f){ return f(); }; - const auto higher2nd = [unary](nullary_t f1){ - return [unary, f1](unary_t f2){ return f2(unary(f1())); }; - }; - return higher1st(nullary) + higher2nd(nullary)(unary); - } - - } - - namespace test_variadic_templates - { - - template - struct sum; - - template - struct sum - { - static constexpr auto value = N0 + sum::value; - }; - - template <> - struct sum<> - { - static constexpr auto value = 0; - }; - - static_assert(sum<>::value == 0, ""); - static_assert(sum<1>::value == 1, ""); - static_assert(sum<23>::value == 23, ""); - static_assert(sum<1, 2>::value == 3, ""); - static_assert(sum<5, 5, 11>::value == 21, ""); - static_assert(sum<2, 3, 5, 7, 11, 13>::value == 41, ""); - - } - - // http://stackoverflow.com/questions/13728184/template-aliases-and-sfinae - // Clang 3.1 fails with headers of libstd++ 4.8.3 when using std::function - // because of this. - namespace test_template_alias_sfinae - { - - struct foo {}; - - template - using member = typename T::member_type; - - template - void func(...) {} - - template - void func(member*) {} - - void test(); - - void test() { func(0); } - - } - - namespace test_std_move_and_forward - { - struct message {}; - char foo(message&) { return '\0'; } - int foo(message&&) { return 0; } - - template - void check(Arg&& arg, RT rt) { - static_assert(sizeof(rt) == sizeof(foo(std::forward(arg))), ""); - } - void test() { - message a; - check(a, char()); - check(std::move(a), int()); - } - } - -} // namespace cxx11 - -#endif // __cplusplus >= 201103L - - - -_ACEOF -if ac_fn_cxx_try_compile "$LINENO"; then : - eval $cachevar=yes -else - eval $cachevar=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - CXX="$ac_save_CXX" -fi -eval ac_res=\$$cachevar - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } - if eval test x\$$cachevar = xyes; then - CXX="$CXX $switch" - if test -n "$CXXCPP" ; then - CXXCPP="$CXXCPP $switch" - fi - ac_success=yes - break - fi - done - if test x$ac_success = xyes; then - break - fi - done - fi - ac_ext=cpp -ac_cpp='$CXXCPP $CPPFLAGS' -ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_cxx_compiler_gnu - - if test x$ax_cxx_compile_cxx11_required = xtrue; then - if test x$ac_success = xno; then - as_fn_error $? "*** A compiler with support for C++11 language features is required." "$LINENO" 5 - fi - fi - if test x$ac_success = xno; then - HAVE_CXX11=0 - { $as_echo "$as_me:${as_lineno-$LINENO}: No compiler with C++11 support was found" >&5 -$as_echo "$as_me: No compiler with C++11 support was found" >&6;} - else - HAVE_CXX11=1 - -$as_echo "#define HAVE_CXX11 1" >>confdefs.h - - fi - - - - # HACK: Make gmock's configure script pick up our copy of CFLAGS and CXXFLAGS, # since the flags added by ACX_CHECK_SUNCC must be used when compiling gmock # too. @@ -21302,7 +21268,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" -This file was extended by Protocol Buffers $as_me 3.6.1, which was +This file was extended by Protocol Buffers $as_me 3.8.0, which was generated by GNU Autoconf 2.69. Invocation command line was CONFIG_FILES = $CONFIG_FILES @@ -21368,7 +21334,7 @@ _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ -Protocol Buffers config.status 3.6.1 +Protocol Buffers config.status 3.8.0 configured by $0, generated by GNU Autoconf 2.69, with options \\"\$ac_cs_config\\" diff --git a/third_party/protobuf/configure.ac b/third_party/protobuf/configure.ac index 7d668276..2f025b7e 100644 --- a/third_party/protobuf/configure.ac +++ b/third_party/protobuf/configure.ac @@ -17,7 +17,7 @@ AC_PREREQ(2.59) # In the SVN trunk, the version should always be the next anticipated release # version with the "-pre" suffix. (We used to use "-SNAPSHOT" but this pushed # the size of one file name in the dist tarfile over the 99-char limit.) -AC_INIT([Protocol Buffers],[3.6.1],[protobuf@googlegroups.com],[protobuf]) +AC_INIT([Protocol Buffers],[3.8.0],[protobuf@googlegroups.com],[protobuf]) AM_MAINTAINER_MODE([enable]) @@ -165,6 +165,26 @@ AS_IF([test "$with_zlib" != no], [ ]) AM_CONDITIONAL([HAVE_ZLIB], [test $HAVE_ZLIB = 1]) +# Add -std=c++11 if necesssary. It is important for us to do this before the +# libatomic check below, since that also depends on C++11. +AX_CXX_COMPILE_STDCXX([11], [noext], [mandatory]) + +dnl On some platforms, std::atomic needs a helper library +AC_MSG_CHECKING(whether -latomic is needed) +AC_LINK_IFELSE([AC_LANG_SOURCE([[ + #include + #include + std::atomic v; + int main() { + return v; + } +]])], STD_ATOMIC_NEED_LIBATOMIC=no, STD_ATOMIC_NEED_LIBATOMIC=yes) +AC_MSG_RESULT($STD_ATOMIC_NEED_LIBATOMIC) +if test "x$STD_ATOMIC_NEED_LIBATOMIC" = xyes; then + LIBATOMIC_LIBS="-latomic" +fi +AC_SUBST([LIBATOMIC_LIBS]) + AS_IF([test "$with_protoc" != "no"], [ PROTOC=$with_protoc AS_IF([test "$with_protoc" = "yes"], [ @@ -189,15 +209,6 @@ AM_CONDITIONAL([HAVE_PTHREAD], [test "x$ax_pthread_ok" = "xyes"]) # We still keep this for improving pbconfig.h for unsupported platforms. AC_CXX_STL_HASH -case "$target_os" in - mingw* | cygwin* | win* | aix*) - ;; - *) - # Need to link against rt on Solaris - AC_SEARCH_LIBS([sched_yield], [rt], [], [AC_MSG_FAILURE([sched_yield was not found on your system])]) - ;; -esac - # Enable ObjC support for conformance directory on OS X. OBJC_CONFORMANCE_TEST=0 case "$target_os" in @@ -207,8 +218,6 @@ case "$target_os" in esac AM_CONDITIONAL([OBJC_CONFORMANCE_TEST], [test $OBJC_CONFORMANCE_TEST = 1]) -AX_CXX_COMPILE_STDCXX([11], [noext], [mandatory]) - # HACK: Make gmock's configure script pick up our copy of CFLAGS and CXXFLAGS, # since the flags added by ACX_CHECK_SUNCC must be used when compiling gmock # too. diff --git a/third_party/protobuf/conformance/ConformanceJava.java b/third_party/protobuf/conformance/ConformanceJava.java index 596d113a..c5b3f4e1 100644 --- a/third_party/protobuf/conformance/ConformanceJava.java +++ b/third_party/protobuf/conformance/ConformanceJava.java @@ -1,16 +1,17 @@ -import com.google.protobuf.ByteString; import com.google.protobuf.AbstractMessage; -import com.google.protobuf.Parser; +import com.google.protobuf.ByteString; import com.google.protobuf.CodedInputStream; -import com.google.protobuf.conformance.Conformance; -import com.google.protobuf.InvalidProtocolBufferException; -import com.google.protobuf_test_messages.proto3.TestMessagesProto3; -import com.google.protobuf_test_messages.proto3.TestMessagesProto3.TestAllTypesProto3; -import com.google.protobuf_test_messages.proto2.TestMessagesProto2; -import com.google.protobuf_test_messages.proto2.TestMessagesProto2.TestAllTypesProto2; import com.google.protobuf.ExtensionRegistry; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Parser; +import com.google.protobuf.TextFormat; +import com.google.protobuf.conformance.Conformance; import com.google.protobuf.util.JsonFormat; import com.google.protobuf.util.JsonFormat.TypeRegistry; +import com.google.protobuf_test_messages.proto2.TestMessagesProto2; +import com.google.protobuf_test_messages.proto2.TestMessagesProto2.TestAllTypesProto2; +import com.google.protobuf_test_messages.proto3.TestMessagesProto3; +import com.google.protobuf_test_messages.proto3.TestMessagesProto3.TestAllTypesProto3; import java.nio.ByteBuffer; import java.util.ArrayList; @@ -56,7 +57,7 @@ class ConformanceJava { buf[3] = (byte)(val >> 24); writeToStdout(buf); } - + private enum BinaryDecoderType { BTYE_STRING_DECODER, BYTE_ARRAY_DECODER, @@ -68,11 +69,11 @@ class ConformanceJava { } private static class BinaryDecoder { - public MessageType decode (ByteString bytes, BinaryDecoderType type, + public MessageType decode (ByteString bytes, BinaryDecoderType type, Parser parser, ExtensionRegistry extensions) throws InvalidProtocolBufferException { switch (type) { - case BTYE_STRING_DECODER: + case BTYE_STRING_DECODER: return parser.parseFrom(bytes, extensions); case BYTE_ARRAY_DECODER: return parser.parseFrom(bytes.toByteArray(), extensions); @@ -93,7 +94,7 @@ class ConformanceJava { } catch (InvalidProtocolBufferException e) { throw e; } - } + } case DIRECT_BYTE_BUFFER_DECODER: { ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.size()); bytes.copyTo(buffer); @@ -134,7 +135,7 @@ class ConformanceJava { ArrayList messages = new ArrayList (); ArrayList exceptions = new ArrayList (); - + for (int i = 0; i < BinaryDecoderType.values().length; i++) { messages.add(null); exceptions.add(null); @@ -233,16 +234,48 @@ class ConformanceJava { } case JSON_PAYLOAD: { try { - TestMessagesProto3.TestAllTypesProto3.Builder builder = + TestMessagesProto3.TestAllTypesProto3.Builder builder = TestMessagesProto3.TestAllTypesProto3.newBuilder(); - JsonFormat.parser().usingTypeRegistry(typeRegistry) - .merge(request.getJsonPayload(), builder); + JsonFormat.Parser parser = JsonFormat.parser().usingTypeRegistry(typeRegistry); + if (request.getTestCategory() + == Conformance.TestCategory.JSON_IGNORE_UNKNOWN_PARSING_TEST) { + parser = parser.ignoringUnknownFields(); + } + parser.merge(request.getJsonPayload(), builder); testMessage = builder.build(); } catch (InvalidProtocolBufferException e) { return Conformance.ConformanceResponse.newBuilder().setParseError(e.getMessage()).build(); } break; } + case TEXT_PAYLOAD: { + if (isProto3) { + try { + TestMessagesProto3.TestAllTypesProto3.Builder builder = + TestMessagesProto3.TestAllTypesProto3.newBuilder(); + TextFormat.merge(request.getTextPayload(), builder); + testMessage = builder.build(); + } catch (TextFormat.ParseException e) { + return Conformance.ConformanceResponse.newBuilder() + .setParseError(e.getMessage()) + .build(); + } + } else if (isProto2) { + try { + TestMessagesProto2.TestAllTypesProto2.Builder builder = + TestMessagesProto2.TestAllTypesProto2.newBuilder(); + TextFormat.merge(request.getTextPayload(), builder); + testMessage = builder.build(); + } catch (TextFormat.ParseException e) { + return Conformance.ConformanceResponse.newBuilder() + .setParseError(e.getMessage()) + .build(); + } + } else { + throw new RuntimeException("Protobuf request doesn't have specific payload type."); + } + break; + } case PAYLOAD_NOT_SET: { throw new RuntimeException("Request didn't have payload."); } @@ -257,7 +290,7 @@ class ConformanceJava { throw new RuntimeException("Unspecified output format."); case PROTOBUF: { - ByteString MessageString = testMessage.toByteString(); + ByteString MessageString = testMessage.toByteString(); return Conformance.ConformanceResponse.newBuilder().setProtobufPayload(MessageString).build(); } @@ -270,6 +303,10 @@ class ConformanceJava { e.getMessage()).build(); } + case TEXT_FORMAT: + return Conformance.ConformanceResponse.newBuilder().setTextPayload( + TextFormat.printToString(testMessage)).build(); + default: { throw new RuntimeException("Unexpected request output."); } diff --git a/third_party/protobuf/conformance/Makefile.am b/third_party/protobuf/conformance/Makefile.am index e51ab80a..e47fd108 100644 --- a/third_party/protobuf/conformance/Makefile.am +++ b/third_party/protobuf/conformance/Makefile.am @@ -107,6 +107,7 @@ other_language_protoc_outputs = \ google/protobuf/wrappers_pb2.py \ Conformance/ConformanceRequest.php \ Conformance/ConformanceResponse.php \ + Conformance/FailureSet.php \ Conformance/WireFormat.php \ GPBMetadata/Conformance.php \ GPBMetadata/Google/Protobuf/Any.php \ @@ -206,6 +207,11 @@ EXTRA_DIST = \ conformance_test_runner_LDADD = $(top_srcdir)/src/libprotobuf.la conformance_test_runner_SOURCES = conformance_test.h conformance_test.cc \ + conformance_test_main.cc \ + binary_json_conformance_suite.h \ + binary_json_conformance_suite.cc \ + text_format_conformance_suite.h \ + text_format_conformance_suite.cc \ conformance_test_runner.cc \ third_party/jsoncpp/json.h \ third_party/jsoncpp/jsoncpp.cpp @@ -310,7 +316,7 @@ conformance-java-lite: javac_middleman_lite conformance-csharp: $(other_language_protoc_outputs) @echo "Writing shortcut script conformance-csharp..." @echo '#! /bin/sh' > conformance-csharp - @echo 'dotnet ../csharp/src/Google.Protobuf.Conformance/bin/Release/netcoreapp1.0/Google.Protobuf.Conformance.dll "$$@"' >> conformance-csharp + @echo 'dotnet ../csharp/src/Google.Protobuf.Conformance/bin/Release/netcoreapp2.1/Google.Protobuf.Conformance.dll "$$@"' >> conformance-csharp @chmod +x conformance-csharp conformance-php: @@ -330,30 +336,33 @@ test_cpp: protoc_middleman conformance-test-runner conformance-cpp ./conformance-test-runner --enforce_recommended --failure_list failure_list_cpp.txt ./conformance-cpp test_java: protoc_middleman conformance-test-runner conformance-java - ./conformance-test-runner --enforce_recommended --failure_list failure_list_java.txt ./conformance-java + ./conformance-test-runner --enforce_recommended --failure_list failure_list_java.txt --text_format_failure_list text_format_failure_list_java.txt ./conformance-java test_java_lite: protoc_middleman conformance-test-runner conformance-java-lite ./conformance-test-runner --enforce_recommended ./conformance-java-lite test_csharp: protoc_middleman conformance-test-runner conformance-csharp - ./conformance-test-runner --enforce_recommended --failure_list failure_list_csharp.txt ./conformance-csharp + ./conformance-test-runner --enforce_recommended --failure_list failure_list_csharp.txt --text_format_failure_list text_format_failure_list_csharp.txt ./conformance-csharp test_ruby: protoc_middleman conformance-test-runner $(other_language_protoc_outputs) - RUBYLIB=../ruby/lib:. ./conformance-test-runner --enforce_recommended --failure_list failure_list_ruby.txt ./conformance_ruby.rb + RUBYLIB=../ruby/lib:. ./conformance-test-runner --enforce_recommended --failure_list failure_list_ruby.txt --text_format_failure_list text_format_failure_list_ruby.txt ./conformance_ruby.rb + +test_ruby_mac: protoc_middleman conformance-test-runner $(other_language_protoc_outputs) + RUBYLIB=../ruby/lib:. ./conformance-test-runner --enforce_recommended --failure_list failure_list_ruby_mac.txt --text_format_failure_list text_format_failure_list_ruby.txt ./conformance_ruby.rb test_php: protoc_middleman conformance-test-runner conformance-php $(other_language_protoc_outputs) - ./conformance-test-runner --enforce_recommended --failure_list failure_list_php.txt ./conformance-php + ./conformance-test-runner --enforce_recommended --failure_list failure_list_php.txt --text_format_failure_list text_format_failure_list_php.txt ./conformance-php test_php_c: protoc_middleman conformance-test-runner conformance-php-c $(other_language_protoc_outputs) - ./conformance-test-runner --enforce_recommended --failure_list failure_list_php_c.txt ./conformance-php-c + ./conformance-test-runner --enforce_recommended --failure_list failure_list_php_c.txt --text_format_failure_list text_format_failure_list_php.txt ./conformance-php-c test_php_zts_c: protoc_middleman conformance-test-runner conformance-php-c $(other_language_protoc_outputs) - ./conformance-test-runner --enforce_recommended --failure_list failure_list_php_zts_c.txt ./conformance-php-c + ./conformance-test-runner --enforce_recommended --failure_list failure_list_php_zts_c.txt --text_format_failure_list text_format_failure_list_php.txt ./conformance-php-c # These depend on library paths being properly set up. The easiest way to # run them is to just use "tox" from the python dir. test_python: protoc_middleman conformance-test-runner - ./conformance-test-runner --enforce_recommended --failure_list failure_list_python.txt ./conformance_python.py + ./conformance-test-runner --enforce_recommended --failure_list failure_list_python.txt --text_format_failure_list text_format_failure_list_python.txt ./conformance_python.py test_python_cpp: protoc_middleman conformance-test-runner ./conformance-test-runner --enforce_recommended --failure_list failure_list_python_cpp.txt ./conformance_python.py diff --git a/third_party/protobuf/conformance/Makefile.in b/third_party/protobuf/conformance/Makefile.in index 8c0dbd0f..0cbea2b6 100644 --- a/third_party/protobuf/conformance/Makefile.in +++ b/third_party/protobuf/conformance/Makefile.in @@ -142,6 +142,9 @@ conformance_objc_LINK = $(LIBTOOL) $(AM_V_lt) $(AM_LIBTOOLFLAGS) \ $(OBJCFLAGS) $(conformance_objc_LDFLAGS) $(LDFLAGS) -o $@ am_conformance_test_runner_OBJECTS = \ conformance_test_runner-conformance_test.$(OBJEXT) \ + conformance_test_runner-conformance_test_main.$(OBJEXT) \ + conformance_test_runner-binary_json_conformance_suite.$(OBJEXT) \ + conformance_test_runner-text_format_conformance_suite.$(OBJEXT) \ conformance_test_runner-conformance_test_runner.$(OBJEXT) \ third_party/jsoncpp/conformance_test_runner-jsoncpp.$(OBJEXT) nodist_conformance_test_runner_OBJECTS = \ @@ -311,6 +314,7 @@ ISAINFO = @ISAINFO@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_FOR_BUILD = @LDFLAGS_FOR_BUILD@ +LIBATOMIC_LIBS = @LIBATOMIC_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ @@ -521,6 +525,7 @@ other_language_protoc_outputs = \ google/protobuf/wrappers_pb2.py \ Conformance/ConformanceRequest.php \ Conformance/ConformanceResponse.php \ + Conformance/FailureSet.php \ Conformance/WireFormat.php \ GPBMetadata/Conformance.php \ GPBMetadata/Google/Protobuf/Any.php \ @@ -579,6 +584,11 @@ EXTRA_DIST = \ conformance_test_runner_LDADD = $(top_srcdir)/src/libprotobuf.la conformance_test_runner_SOURCES = conformance_test.h conformance_test.cc \ + conformance_test_main.cc \ + binary_json_conformance_suite.h \ + binary_json_conformance_suite.cc \ + text_format_conformance_suite.h \ + text_format_conformance_suite.cc \ conformance_test_runner.cc \ third_party/jsoncpp/json.h \ third_party/jsoncpp/jsoncpp.cpp @@ -753,9 +763,12 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/conformance_cpp-conformance_cpp.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/conformance_objc-Conformance.pbobjc.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/conformance_objc-conformance_objc.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/conformance_test_runner-binary_json_conformance_suite.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/conformance_test_runner-conformance.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/conformance_test_runner-conformance_test.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/conformance_test_runner-conformance_test_main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/conformance_test_runner-conformance_test_runner.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/conformance_test_runner-text_format_conformance_suite.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/conformance_cpp-test_messages_proto2.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/conformance_cpp-test_messages_proto3.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/conformance_objc-TestMessagesProto2.pbobjc.Po@am__quote@ @@ -858,6 +871,48 @@ conformance_test_runner-conformance_test.obj: conformance_test.cc @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(conformance_test_runner_CPPFLAGS) $(CPPFLAGS) $(conformance_test_runner_CXXFLAGS) $(CXXFLAGS) -c -o conformance_test_runner-conformance_test.obj `if test -f 'conformance_test.cc'; then $(CYGPATH_W) 'conformance_test.cc'; else $(CYGPATH_W) '$(srcdir)/conformance_test.cc'; fi` +conformance_test_runner-conformance_test_main.o: conformance_test_main.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(conformance_test_runner_CPPFLAGS) $(CPPFLAGS) $(conformance_test_runner_CXXFLAGS) $(CXXFLAGS) -MT conformance_test_runner-conformance_test_main.o -MD -MP -MF $(DEPDIR)/conformance_test_runner-conformance_test_main.Tpo -c -o conformance_test_runner-conformance_test_main.o `test -f 'conformance_test_main.cc' || echo '$(srcdir)/'`conformance_test_main.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/conformance_test_runner-conformance_test_main.Tpo $(DEPDIR)/conformance_test_runner-conformance_test_main.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='conformance_test_main.cc' object='conformance_test_runner-conformance_test_main.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(conformance_test_runner_CPPFLAGS) $(CPPFLAGS) $(conformance_test_runner_CXXFLAGS) $(CXXFLAGS) -c -o conformance_test_runner-conformance_test_main.o `test -f 'conformance_test_main.cc' || echo '$(srcdir)/'`conformance_test_main.cc + +conformance_test_runner-conformance_test_main.obj: conformance_test_main.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(conformance_test_runner_CPPFLAGS) $(CPPFLAGS) $(conformance_test_runner_CXXFLAGS) $(CXXFLAGS) -MT conformance_test_runner-conformance_test_main.obj -MD -MP -MF $(DEPDIR)/conformance_test_runner-conformance_test_main.Tpo -c -o conformance_test_runner-conformance_test_main.obj `if test -f 'conformance_test_main.cc'; then $(CYGPATH_W) 'conformance_test_main.cc'; else $(CYGPATH_W) '$(srcdir)/conformance_test_main.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/conformance_test_runner-conformance_test_main.Tpo $(DEPDIR)/conformance_test_runner-conformance_test_main.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='conformance_test_main.cc' object='conformance_test_runner-conformance_test_main.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(conformance_test_runner_CPPFLAGS) $(CPPFLAGS) $(conformance_test_runner_CXXFLAGS) $(CXXFLAGS) -c -o conformance_test_runner-conformance_test_main.obj `if test -f 'conformance_test_main.cc'; then $(CYGPATH_W) 'conformance_test_main.cc'; else $(CYGPATH_W) '$(srcdir)/conformance_test_main.cc'; fi` + +conformance_test_runner-binary_json_conformance_suite.o: binary_json_conformance_suite.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(conformance_test_runner_CPPFLAGS) $(CPPFLAGS) $(conformance_test_runner_CXXFLAGS) $(CXXFLAGS) -MT conformance_test_runner-binary_json_conformance_suite.o -MD -MP -MF $(DEPDIR)/conformance_test_runner-binary_json_conformance_suite.Tpo -c -o conformance_test_runner-binary_json_conformance_suite.o `test -f 'binary_json_conformance_suite.cc' || echo '$(srcdir)/'`binary_json_conformance_suite.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/conformance_test_runner-binary_json_conformance_suite.Tpo $(DEPDIR)/conformance_test_runner-binary_json_conformance_suite.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='binary_json_conformance_suite.cc' object='conformance_test_runner-binary_json_conformance_suite.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(conformance_test_runner_CPPFLAGS) $(CPPFLAGS) $(conformance_test_runner_CXXFLAGS) $(CXXFLAGS) -c -o conformance_test_runner-binary_json_conformance_suite.o `test -f 'binary_json_conformance_suite.cc' || echo '$(srcdir)/'`binary_json_conformance_suite.cc + +conformance_test_runner-binary_json_conformance_suite.obj: binary_json_conformance_suite.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(conformance_test_runner_CPPFLAGS) $(CPPFLAGS) $(conformance_test_runner_CXXFLAGS) $(CXXFLAGS) -MT conformance_test_runner-binary_json_conformance_suite.obj -MD -MP -MF $(DEPDIR)/conformance_test_runner-binary_json_conformance_suite.Tpo -c -o conformance_test_runner-binary_json_conformance_suite.obj `if test -f 'binary_json_conformance_suite.cc'; then $(CYGPATH_W) 'binary_json_conformance_suite.cc'; else $(CYGPATH_W) '$(srcdir)/binary_json_conformance_suite.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/conformance_test_runner-binary_json_conformance_suite.Tpo $(DEPDIR)/conformance_test_runner-binary_json_conformance_suite.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='binary_json_conformance_suite.cc' object='conformance_test_runner-binary_json_conformance_suite.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(conformance_test_runner_CPPFLAGS) $(CPPFLAGS) $(conformance_test_runner_CXXFLAGS) $(CXXFLAGS) -c -o conformance_test_runner-binary_json_conformance_suite.obj `if test -f 'binary_json_conformance_suite.cc'; then $(CYGPATH_W) 'binary_json_conformance_suite.cc'; else $(CYGPATH_W) '$(srcdir)/binary_json_conformance_suite.cc'; fi` + +conformance_test_runner-text_format_conformance_suite.o: text_format_conformance_suite.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(conformance_test_runner_CPPFLAGS) $(CPPFLAGS) $(conformance_test_runner_CXXFLAGS) $(CXXFLAGS) -MT conformance_test_runner-text_format_conformance_suite.o -MD -MP -MF $(DEPDIR)/conformance_test_runner-text_format_conformance_suite.Tpo -c -o conformance_test_runner-text_format_conformance_suite.o `test -f 'text_format_conformance_suite.cc' || echo '$(srcdir)/'`text_format_conformance_suite.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/conformance_test_runner-text_format_conformance_suite.Tpo $(DEPDIR)/conformance_test_runner-text_format_conformance_suite.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='text_format_conformance_suite.cc' object='conformance_test_runner-text_format_conformance_suite.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(conformance_test_runner_CPPFLAGS) $(CPPFLAGS) $(conformance_test_runner_CXXFLAGS) $(CXXFLAGS) -c -o conformance_test_runner-text_format_conformance_suite.o `test -f 'text_format_conformance_suite.cc' || echo '$(srcdir)/'`text_format_conformance_suite.cc + +conformance_test_runner-text_format_conformance_suite.obj: text_format_conformance_suite.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(conformance_test_runner_CPPFLAGS) $(CPPFLAGS) $(conformance_test_runner_CXXFLAGS) $(CXXFLAGS) -MT conformance_test_runner-text_format_conformance_suite.obj -MD -MP -MF $(DEPDIR)/conformance_test_runner-text_format_conformance_suite.Tpo -c -o conformance_test_runner-text_format_conformance_suite.obj `if test -f 'text_format_conformance_suite.cc'; then $(CYGPATH_W) 'text_format_conformance_suite.cc'; else $(CYGPATH_W) '$(srcdir)/text_format_conformance_suite.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/conformance_test_runner-text_format_conformance_suite.Tpo $(DEPDIR)/conformance_test_runner-text_format_conformance_suite.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='text_format_conformance_suite.cc' object='conformance_test_runner-text_format_conformance_suite.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(conformance_test_runner_CPPFLAGS) $(CPPFLAGS) $(conformance_test_runner_CXXFLAGS) $(CXXFLAGS) -c -o conformance_test_runner-text_format_conformance_suite.obj `if test -f 'text_format_conformance_suite.cc'; then $(CYGPATH_W) 'text_format_conformance_suite.cc'; else $(CYGPATH_W) '$(srcdir)/text_format_conformance_suite.cc'; fi` + conformance_test_runner-conformance_test_runner.o: conformance_test_runner.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(conformance_test_runner_CPPFLAGS) $(CPPFLAGS) $(conformance_test_runner_CXXFLAGS) $(CXXFLAGS) -MT conformance_test_runner-conformance_test_runner.o -MD -MP -MF $(DEPDIR)/conformance_test_runner-conformance_test_runner.Tpo -c -o conformance_test_runner-conformance_test_runner.o `test -f 'conformance_test_runner.cc' || echo '$(srcdir)/'`conformance_test_runner.cc @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/conformance_test_runner-conformance_test_runner.Tpo $(DEPDIR)/conformance_test_runner-conformance_test_runner.Po @@ -1371,7 +1426,7 @@ conformance-java-lite: javac_middleman_lite conformance-csharp: $(other_language_protoc_outputs) @echo "Writing shortcut script conformance-csharp..." @echo '#! /bin/sh' > conformance-csharp - @echo 'dotnet ../csharp/src/Google.Protobuf.Conformance/bin/Release/netcoreapp1.0/Google.Protobuf.Conformance.dll "$$@"' >> conformance-csharp + @echo 'dotnet ../csharp/src/Google.Protobuf.Conformance/bin/Release/netcoreapp2.1/Google.Protobuf.Conformance.dll "$$@"' >> conformance-csharp @chmod +x conformance-csharp conformance-php: @@ -1391,30 +1446,33 @@ test_cpp: protoc_middleman conformance-test-runner conformance-cpp ./conformance-test-runner --enforce_recommended --failure_list failure_list_cpp.txt ./conformance-cpp test_java: protoc_middleman conformance-test-runner conformance-java - ./conformance-test-runner --enforce_recommended --failure_list failure_list_java.txt ./conformance-java + ./conformance-test-runner --enforce_recommended --failure_list failure_list_java.txt --text_format_failure_list text_format_failure_list_java.txt ./conformance-java test_java_lite: protoc_middleman conformance-test-runner conformance-java-lite ./conformance-test-runner --enforce_recommended ./conformance-java-lite test_csharp: protoc_middleman conformance-test-runner conformance-csharp - ./conformance-test-runner --enforce_recommended --failure_list failure_list_csharp.txt ./conformance-csharp + ./conformance-test-runner --enforce_recommended --failure_list failure_list_csharp.txt --text_format_failure_list text_format_failure_list_csharp.txt ./conformance-csharp test_ruby: protoc_middleman conformance-test-runner $(other_language_protoc_outputs) - RUBYLIB=../ruby/lib:. ./conformance-test-runner --enforce_recommended --failure_list failure_list_ruby.txt ./conformance_ruby.rb + RUBYLIB=../ruby/lib:. ./conformance-test-runner --enforce_recommended --failure_list failure_list_ruby.txt --text_format_failure_list text_format_failure_list_ruby.txt ./conformance_ruby.rb + +test_ruby_mac: protoc_middleman conformance-test-runner $(other_language_protoc_outputs) + RUBYLIB=../ruby/lib:. ./conformance-test-runner --enforce_recommended --failure_list failure_list_ruby_mac.txt --text_format_failure_list text_format_failure_list_ruby.txt ./conformance_ruby.rb test_php: protoc_middleman conformance-test-runner conformance-php $(other_language_protoc_outputs) - ./conformance-test-runner --enforce_recommended --failure_list failure_list_php.txt ./conformance-php + ./conformance-test-runner --enforce_recommended --failure_list failure_list_php.txt --text_format_failure_list text_format_failure_list_php.txt ./conformance-php test_php_c: protoc_middleman conformance-test-runner conformance-php-c $(other_language_protoc_outputs) - ./conformance-test-runner --enforce_recommended --failure_list failure_list_php_c.txt ./conformance-php-c + ./conformance-test-runner --enforce_recommended --failure_list failure_list_php_c.txt --text_format_failure_list text_format_failure_list_php.txt ./conformance-php-c test_php_zts_c: protoc_middleman conformance-test-runner conformance-php-c $(other_language_protoc_outputs) - ./conformance-test-runner --enforce_recommended --failure_list failure_list_php_zts_c.txt ./conformance-php-c + ./conformance-test-runner --enforce_recommended --failure_list failure_list_php_zts_c.txt --text_format_failure_list text_format_failure_list_php.txt ./conformance-php-c # These depend on library paths being properly set up. The easiest way to # run them is to just use "tox" from the python dir. test_python: protoc_middleman conformance-test-runner - ./conformance-test-runner --enforce_recommended --failure_list failure_list_python.txt ./conformance_python.py + ./conformance-test-runner --enforce_recommended --failure_list failure_list_python.txt --text_format_failure_list text_format_failure_list_python.txt ./conformance_python.py test_python_cpp: protoc_middleman conformance-test-runner ./conformance-test-runner --enforce_recommended --failure_list failure_list_python_cpp.txt ./conformance_python.py diff --git a/third_party/protobuf/conformance/README.md b/third_party/protobuf/conformance/README.md index 971fe8f6..06925dbb 100644 --- a/third_party/protobuf/conformance/README.md +++ b/third_party/protobuf/conformance/README.md @@ -1,8 +1,6 @@ Protocol Buffers - Google's data interchange format =================================================== -[![Build Status](https://travis-ci.org/google/protobuf.svg?branch=master)](https://travis-ci.org/google/protobuf) - Copyright 2008 Google Inc. This directory contains conformance tests for testing completeness and @@ -59,10 +57,10 @@ Testing other Protocol Buffer implementations To run these tests against a new Protocol Buffers implementation, write a program in your language that uses the protobuf implementation you want to test. This program should implement the testing protocol defined in -[conformance.proto](https://github.com/google/protobuf/blob/master/conformance/conformance.proto). +[conformance.proto](https://github.com/protocolbuffers/protobuf/blob/master/conformance/conformance.proto). This is designed to be as easy as possible: the C++ version is only 150 lines and is a good example for what this program should look like -(see [conformance_cpp.cc](https://github.com/google/protobuf/blob/master/conformance/conformance_cpp.cc)). +(see [conformance_cpp.cc](https://github.com/protocolbuffers/protobuf/blob/master/conformance/conformance_cpp.cc)). The program only needs to be able to read from stdin and write to stdout. Portability diff --git a/third_party/protobuf/conformance/binary_json_conformance_suite.cc b/third_party/protobuf/conformance/binary_json_conformance_suite.cc new file mode 100644 index 00000000..8cb9bf7c --- /dev/null +++ b/third_party/protobuf/conformance/binary_json_conformance_suite.cc @@ -0,0 +1,2458 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include "binary_json_conformance_suite.h" +#include "conformance_test.h" +#include "third_party/jsoncpp/json.h" + +#include +#include + +#include +#include +#include +#include +#include +#include + +using conformance::ConformanceRequest; +using conformance::ConformanceResponse; +using conformance::WireFormat; +using google::protobuf::Descriptor; +using google::protobuf::FieldDescriptor; +using google::protobuf::Message; +using google::protobuf::internal::WireFormatLite; +using google::protobuf::TextFormat; +using google::protobuf::util::NewTypeResolverForDescriptorPool; +using protobuf_test_messages::proto3::TestAllTypesProto3; +using protobuf_test_messages::proto2::TestAllTypesProto2; +using std::string; + +namespace { + +static const char kTypeUrlPrefix[] = "type.googleapis.com"; + +static string GetTypeUrl(const Descriptor* message) { + return string(kTypeUrlPrefix) + "/" + message->full_name(); +} + +/* Routines for building arbitrary protos *************************************/ + +// We would use CodedOutputStream except that we want more freedom to build +// arbitrary protos (even invalid ones). + +const string empty; + +string cat(const string& a, const string& b, + const string& c = empty, + const string& d = empty, + const string& e = empty, + const string& f = empty, + const string& g = empty, + const string& h = empty, + const string& i = empty, + const string& j = empty, + const string& k = empty, + const string& l = empty) { + string ret; + ret.reserve(a.size() + b.size() + c.size() + d.size() + e.size() + f.size() + + g.size() + h.size() + i.size() + j.size() + k.size() + l.size()); + ret.append(a); + ret.append(b); + ret.append(c); + ret.append(d); + ret.append(e); + ret.append(f); + ret.append(g); + ret.append(h); + ret.append(i); + ret.append(j); + ret.append(k); + ret.append(l); + return ret; +} + +// The maximum number of bytes that it takes to encode a 64-bit varint. +#define VARINT_MAX_LEN 10 + +size_t vencode64(uint64_t val, int over_encoded_bytes, char *buf) { + if (val == 0) { buf[0] = 0; return 1; } + size_t i = 0; + while (val) { + uint8_t byte = val & 0x7fU; + val >>= 7; + if (val || over_encoded_bytes) byte |= 0x80U; + buf[i++] = byte; + } + while (over_encoded_bytes--) { + assert(i < 10); + uint8_t byte = over_encoded_bytes ? 0x80 : 0; + buf[i++] = byte; + } + return i; +} + +string varint(uint64_t x) { + char buf[VARINT_MAX_LEN]; + size_t len = vencode64(x, 0, buf); + return string(buf, len); +} + +// Encodes a varint that is |extra| bytes longer than it needs to be, but still +// valid. +string longvarint(uint64_t x, int extra) { + char buf[VARINT_MAX_LEN]; + size_t len = vencode64(x, extra, buf); + return string(buf, len); +} + +// TODO: proper byte-swapping for big-endian machines. +string fixed32(void *data) { return string(static_cast(data), 4); } +string fixed64(void *data) { return string(static_cast(data), 8); } + +string delim(const string& buf) { return cat(varint(buf.size()), buf); } +string u32(uint32_t u32) { return fixed32(&u32); } +string u64(uint64_t u64) { return fixed64(&u64); } +string flt(float f) { return fixed32(&f); } +string dbl(double d) { return fixed64(&d); } +string zz32(int32_t x) { return varint(WireFormatLite::ZigZagEncode32(x)); } +string zz64(int64_t x) { return varint(WireFormatLite::ZigZagEncode64(x)); } + +string tag(uint32_t fieldnum, char wire_type) { + return varint((fieldnum << 3) | wire_type); +} + +string submsg(uint32_t fn, const string& buf) { + return cat( tag(fn, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), delim(buf) ); +} + +#define UNKNOWN_FIELD 666 + +const FieldDescriptor* GetFieldForType(FieldDescriptor::Type type, + bool repeated, bool is_proto3) { + + const Descriptor* d = is_proto3 ? + TestAllTypesProto3().GetDescriptor() : TestAllTypesProto2().GetDescriptor(); + for (int i = 0; i < d->field_count(); i++) { + const FieldDescriptor* f = d->field(i); + if (f->type() == type && f->is_repeated() == repeated) { + return f; + } + } + GOOGLE_LOG(FATAL) << "Couldn't find field with type " << (int)type; + return nullptr; +} + +string UpperCase(string str) { + for (int i = 0; i < str.size(); i++) { + str[i] = toupper(str[i]); + } + return str; +} + +std::unique_ptr NewTestMessage(bool is_proto3) { + std::unique_ptr prototype; + if (is_proto3) { + prototype.reset(new TestAllTypesProto3()); + } else { + prototype.reset(new TestAllTypesProto2()); + } + return prototype; +} + +} // anonymous namespace + +namespace google { +namespace protobuf { + +bool BinaryAndJsonConformanceSuite::ParseJsonResponse( + const ConformanceResponse& response, + Message* test_message) { + string binary_protobuf; + util::Status status = + JsonToBinaryString(type_resolver_.get(), type_url_, + response.json_payload(), &binary_protobuf); + + if (!status.ok()) { + return false; + } + + if (!test_message->ParseFromString(binary_protobuf)) { + GOOGLE_LOG(FATAL) + << "INTERNAL ERROR: internal JSON->protobuf transcode " + << "yielded unparseable proto."; + return false; + } + + return true; +} + +bool BinaryAndJsonConformanceSuite::ParseResponse( + const ConformanceResponse& response, + const ConformanceRequestSetting& setting, + Message* test_message) { + const ConformanceRequest& request = setting.GetRequest(); + WireFormat requested_output = request.requested_output_format(); + const string& test_name = setting.GetTestName(); + ConformanceLevel level = setting.GetLevel(); + + switch (response.result_case()) { + case ConformanceResponse::kProtobufPayload: { + if (requested_output != conformance::PROTOBUF) { + ReportFailure( + test_name, level, request, response, + StrCat("Test was asked for ", WireFormatToString(requested_output), + " output but provided PROTOBUF instead.").c_str()); + return false; + } + + if (!test_message->ParseFromString(response.protobuf_payload())) { + ReportFailure(test_name, level, request, response, + "Protobuf output we received from test was unparseable."); + return false; + } + + break; + } + + case ConformanceResponse::kJsonPayload: { + if (requested_output != conformance::JSON) { + ReportFailure( + test_name, level, request, response, + StrCat("Test was asked for ", WireFormatToString(requested_output), + " output but provided JSON instead.").c_str()); + return false; + } + + if (!ParseJsonResponse(response, test_message)) { + ReportFailure(test_name, level, request, response, + "JSON output we received from test was unparseable."); + return false; + } + + break; + } + + default: + GOOGLE_LOG(FATAL) << test_name << ": unknown payload type: " + << response.result_case(); + } + + return true; +} + +void BinaryAndJsonConformanceSuite::ExpectParseFailureForProtoWithProtoVersion ( + const string& proto, const string& test_name, ConformanceLevel level, + bool is_proto3) { + std::unique_ptr prototype = NewTestMessage(is_proto3); + // We don't expect output, but if the program erroneously accepts the protobuf + // we let it send its response as this. We must not leave it unspecified. + ConformanceRequestSetting setting( + level, conformance::PROTOBUF, conformance::PROTOBUF, + conformance::BINARY_TEST, + *prototype, test_name, proto); + + const ConformanceRequest& request = setting.GetRequest(); + ConformanceResponse response; + string effective_test_name = + StrCat(setting.ConformanceLevelToString(level), + (is_proto3 ? ".Proto3" : ".Proto2"), + ".ProtobufInput.", test_name); + + RunTest(effective_test_name, request, &response); + if (response.result_case() == ConformanceResponse::kParseError) { + ReportSuccess(effective_test_name); + } else if (response.result_case() == ConformanceResponse::kSkipped) { + ReportSkip(effective_test_name, request, response); + } else { + ReportFailure(effective_test_name, level, request, response, + "Should have failed to parse, but didn't."); + } +} + +// Expect that this precise protobuf will cause a parse error. +void BinaryAndJsonConformanceSuite::ExpectParseFailureForProto( + const string& proto, const string& test_name, ConformanceLevel level) { + ExpectParseFailureForProtoWithProtoVersion(proto, test_name, level, true); + ExpectParseFailureForProtoWithProtoVersion(proto, test_name, level, false); +} + +// Expect that this protobuf will cause a parse error, even if it is followed +// by valid protobuf data. We can try running this twice: once with this +// data verbatim and once with this data followed by some valid data. +// +// TODO(haberman): implement the second of these. +void BinaryAndJsonConformanceSuite::ExpectHardParseFailureForProto( + const string& proto, const string& test_name, ConformanceLevel level) { + return ExpectParseFailureForProto(proto, test_name, level); +} + +void BinaryAndJsonConformanceSuite::RunValidJsonTest( + const string& test_name, ConformanceLevel level, const string& input_json, + const string& equivalent_text_format) { + TestAllTypesProto3 prototype; + ConformanceRequestSetting setting1( + level, conformance::JSON, conformance::PROTOBUF, + conformance::JSON_TEST, + prototype, test_name, input_json); + RunValidInputTest(setting1, equivalent_text_format); + ConformanceRequestSetting setting2( + level, conformance::JSON, conformance::JSON, + conformance::JSON_TEST, + prototype, test_name, input_json); + RunValidInputTest(setting2, equivalent_text_format); +} + +void BinaryAndJsonConformanceSuite::RunValidJsonTestWithProtobufInput( + const string& test_name, ConformanceLevel level, const TestAllTypesProto3& input, + const string& equivalent_text_format) { + ConformanceRequestSetting setting( + level, conformance::PROTOBUF, conformance::JSON, + conformance::JSON_TEST, + input, test_name, input.SerializeAsString()); + RunValidInputTest(setting, equivalent_text_format); +} + +void BinaryAndJsonConformanceSuite::RunValidJsonIgnoreUnknownTest( + const string& test_name, ConformanceLevel level, const string& input_json, + const string& equivalent_text_format) { + TestAllTypesProto3 prototype; + ConformanceRequestSetting setting( + level, conformance::JSON, conformance::PROTOBUF, + conformance::JSON_IGNORE_UNKNOWN_PARSING_TEST, + prototype, test_name, input_json); + RunValidInputTest(setting, equivalent_text_format); +} + +void BinaryAndJsonConformanceSuite::RunValidProtobufTest( + const string& test_name, ConformanceLevel level, + const string& input_protobuf, const string& equivalent_text_format, + bool is_proto3) { + std::unique_ptr prototype = NewTestMessage(is_proto3); + + ConformanceRequestSetting setting1( + level, conformance::PROTOBUF, conformance::PROTOBUF, + conformance::BINARY_TEST, + *prototype, test_name, input_protobuf); + RunValidInputTest(setting1, equivalent_text_format); + + if (is_proto3) { + ConformanceRequestSetting setting2( + level, conformance::PROTOBUF, conformance::JSON, + conformance::BINARY_TEST, + *prototype, test_name, input_protobuf); + RunValidInputTest(setting2, equivalent_text_format); + } +} + +void BinaryAndJsonConformanceSuite::RunValidBinaryProtobufTest( + const string& test_name, ConformanceLevel level, + const string& input_protobuf, bool is_proto3) { + std::unique_ptr prototype = NewTestMessage(is_proto3); + ConformanceRequestSetting setting( + level, conformance::PROTOBUF, conformance::PROTOBUF, + conformance::BINARY_TEST, + *prototype, test_name, input_protobuf); + RunValidBinaryInputTest(setting, input_protobuf); +} + +void BinaryAndJsonConformanceSuite::RunValidProtobufTestWithMessage( + const string& test_name, ConformanceLevel level, const Message *input, + const string& equivalent_text_format, bool is_proto3) { + RunValidProtobufTest(test_name, level, input->SerializeAsString(), + equivalent_text_format, is_proto3); +} + +// According to proto3 JSON specification, JSON serializers follow more strict +// rules than parsers (e.g., a serializer must serialize int32 values as JSON +// numbers while the parser is allowed to accept them as JSON strings). This +// method allows strict checking on a proto3 JSON serializer by inspecting +// the JSON output directly. +void BinaryAndJsonConformanceSuite::RunValidJsonTestWithValidator( + const string& test_name, ConformanceLevel level, const string& input_json, + const Validator& validator) { + TestAllTypesProto3 prototype; + ConformanceRequestSetting setting( + level, conformance::JSON, conformance::JSON, + conformance::JSON_TEST, + prototype, test_name, input_json); + const ConformanceRequest& request = setting.GetRequest(); + ConformanceResponse response; + string effective_test_name = + StrCat(setting.ConformanceLevelToString(level), + ".Proto3.JsonInput.", + test_name, ".Validator"); + + RunTest(effective_test_name, request, &response); + + if (response.result_case() == ConformanceResponse::kSkipped) { + ReportSkip(effective_test_name, request, response); + return; + } + + if (response.result_case() != ConformanceResponse::kJsonPayload) { + ReportFailure(effective_test_name, level, request, response, + "Expected JSON payload but got type %d.", + response.result_case()); + return; + } + Json::Reader reader; + Json::Value value; + if (!reader.parse(response.json_payload(), value)) { + ReportFailure(effective_test_name, level, request, response, + "JSON payload cannot be parsed as valid JSON: %s", + reader.getFormattedErrorMessages().c_str()); + return; + } + if (!validator(value)) { + ReportFailure(effective_test_name, level, request, response, + "JSON payload validation failed."); + return; + } + ReportSuccess(effective_test_name); +} + +void BinaryAndJsonConformanceSuite::ExpectParseFailureForJson( + const string& test_name, ConformanceLevel level, const string& input_json) { + TestAllTypesProto3 prototype; + // We don't expect output, but if the program erroneously accepts the protobuf + // we let it send its response as this. We must not leave it unspecified. + ConformanceRequestSetting setting( + level, conformance::JSON, conformance::JSON, + conformance::JSON_TEST, + prototype, test_name, input_json); + const ConformanceRequest& request = setting.GetRequest(); + ConformanceResponse response; + string effective_test_name = + StrCat(setting.ConformanceLevelToString(level), + ".Proto3.JsonInput.", test_name); + + RunTest(effective_test_name, request, &response); + if (response.result_case() == ConformanceResponse::kParseError) { + ReportSuccess(effective_test_name); + } else if (response.result_case() == ConformanceResponse::kSkipped) { + ReportSkip(effective_test_name, request, response); + } else { + ReportFailure(effective_test_name, level, request, response, + "Should have failed to parse, but didn't."); + } +} + +void BinaryAndJsonConformanceSuite::ExpectSerializeFailureForJson( + const string& test_name, ConformanceLevel level, const string& text_format) { + TestAllTypesProto3 payload_message; + GOOGLE_CHECK( + TextFormat::ParseFromString(text_format, &payload_message)) + << "Failed to parse: " << text_format; + + TestAllTypesProto3 prototype; + ConformanceRequestSetting setting( + level, conformance::PROTOBUF, conformance::JSON, + conformance::JSON_TEST, + prototype, test_name, payload_message.SerializeAsString()); + const ConformanceRequest& request = setting.GetRequest(); + ConformanceResponse response; + string effective_test_name = + StrCat(setting.ConformanceLevelToString(level), + ".", test_name, ".JsonOutput"); + + RunTest(effective_test_name, request, &response); + if (response.result_case() == ConformanceResponse::kSerializeError) { + ReportSuccess(effective_test_name); + } else if (response.result_case() == ConformanceResponse::kSkipped) { + ReportSkip(effective_test_name, request, response); + } else { + ReportFailure(effective_test_name, level, request, response, + "Should have failed to serialize, but didn't."); + } +} + +//TODO: proto2? +void BinaryAndJsonConformanceSuite::TestPrematureEOFForType( + FieldDescriptor::Type type) { + // Incomplete values for each wire type. + static const string incompletes[6] = { + string("\x80"), // VARINT + string("abcdefg"), // 64BIT + string("\x80"), // DELIMITED (partial length) + string(), // START_GROUP (no value required) + string(), // END_GROUP (no value required) + string("abc") // 32BIT + }; + + const FieldDescriptor* field = GetFieldForType(type, false, true); + const FieldDescriptor* rep_field = GetFieldForType(type, true, true); + WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType( + static_cast(type)); + const string& incomplete = incompletes[wire_type]; + const string type_name = + UpperCase(string(".") + FieldDescriptor::TypeName(type)); + + ExpectParseFailureForProto( + tag(field->number(), wire_type), + "PrematureEofBeforeKnownNonRepeatedValue" + type_name, REQUIRED); + + ExpectParseFailureForProto( + tag(rep_field->number(), wire_type), + "PrematureEofBeforeKnownRepeatedValue" + type_name, REQUIRED); + + ExpectParseFailureForProto( + tag(UNKNOWN_FIELD, wire_type), + "PrematureEofBeforeUnknownValue" + type_name, REQUIRED); + + ExpectParseFailureForProto( + cat( tag(field->number(), wire_type), incomplete ), + "PrematureEofInsideKnownNonRepeatedValue" + type_name, REQUIRED); + + ExpectParseFailureForProto( + cat( tag(rep_field->number(), wire_type), incomplete ), + "PrematureEofInsideKnownRepeatedValue" + type_name, REQUIRED); + + ExpectParseFailureForProto( + cat( tag(UNKNOWN_FIELD, wire_type), incomplete ), + "PrematureEofInsideUnknownValue" + type_name, REQUIRED); + + if (wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { + ExpectParseFailureForProto( + cat( tag(field->number(), wire_type), varint(1) ), + "PrematureEofInDelimitedDataForKnownNonRepeatedValue" + type_name, + REQUIRED); + + ExpectParseFailureForProto( + cat( tag(rep_field->number(), wire_type), varint(1) ), + "PrematureEofInDelimitedDataForKnownRepeatedValue" + type_name, + REQUIRED); + + // EOF in the middle of delimited data for unknown value. + ExpectParseFailureForProto( + cat( tag(UNKNOWN_FIELD, wire_type), varint(1) ), + "PrematureEofInDelimitedDataForUnknownValue" + type_name, REQUIRED); + + if (type == FieldDescriptor::TYPE_MESSAGE) { + // Submessage ends in the middle of a value. + string incomplete_submsg = + cat( tag(WireFormatLite::TYPE_INT32, WireFormatLite::WIRETYPE_VARINT), + incompletes[WireFormatLite::WIRETYPE_VARINT] ); + ExpectHardParseFailureForProto( + cat( tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + varint(incomplete_submsg.size()), + incomplete_submsg ), + "PrematureEofInSubmessageValue" + type_name, REQUIRED); + } + } else if (type != FieldDescriptor::TYPE_GROUP) { + // Non-delimited, non-group: eligible for packing. + + // Packed region ends in the middle of a value. + ExpectHardParseFailureForProto( + cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + varint(incomplete.size()), incomplete), + "PrematureEofInPackedFieldValue" + type_name, REQUIRED); + + // EOF in the middle of packed region. + ExpectParseFailureForProto( + cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + varint(1)), + "PrematureEofInPackedField" + type_name, REQUIRED); + } +} + +void BinaryAndJsonConformanceSuite::TestValidDataForType( + FieldDescriptor::Type type, + std::vector> values) { + for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) { + const string type_name = + UpperCase(string(".") + FieldDescriptor::TypeName(type)); + WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType( + static_cast(type)); + const FieldDescriptor* field = GetFieldForType(type, false, is_proto3); + const FieldDescriptor* rep_field = GetFieldForType(type, true, is_proto3); + + RunValidProtobufTest("ValidDataScalar" + type_name, REQUIRED, + cat(tag(field->number(), wire_type), values[0].first), + field->name() + ": " + values[0].second, is_proto3); + + string proto; + string text = field->name() + ": " + values.back().second; + for (size_t i = 0; i < values.size(); i++) { + proto += cat(tag(field->number(), wire_type), values[i].first); + } + RunValidProtobufTest("RepeatedScalarSelectsLast" + type_name, REQUIRED, + proto, text, is_proto3); + + proto.clear(); + text.clear(); + + for (size_t i = 0; i < values.size(); i++) { + proto += cat(tag(rep_field->number(), wire_type), values[i].first); + text += rep_field->name() + ": " + values[i].second + " "; + } + RunValidProtobufTest("ValidDataRepeated" + type_name, REQUIRED, + proto, text, is_proto3); + } +} + +// TODO: proto2? +void BinaryAndJsonConformanceSuite::TestIllegalTags() { + // field num 0 is illegal + string nullfield[] = { + "\1DEADBEEF", + "\2\1\1", + "\3\4", + "\5DEAD" + }; + for (int i = 0; i < 4; i++) { + string name = "IllegalZeroFieldNum_Case_0"; + name.back() += i; + ExpectParseFailureForProto(nullfield[i], name, REQUIRED); + } +} +template +void BinaryAndJsonConformanceSuite::TestOneofMessage ( + MessageType &message, bool is_proto3) { + message.set_oneof_uint32(0); + RunValidProtobufTestWithMessage( + "OneofZeroUint32", RECOMMENDED, &message, "oneof_uint32: 0", is_proto3); + message.mutable_oneof_nested_message()->set_a(0); + RunValidProtobufTestWithMessage( + "OneofZeroMessage", RECOMMENDED, &message, + is_proto3 ? "oneof_nested_message: {}" : "oneof_nested_message: {a: 0}", + is_proto3); + message.mutable_oneof_nested_message()->set_a(1); + RunValidProtobufTestWithMessage( + "OneofZeroMessageSetTwice", RECOMMENDED, &message, + "oneof_nested_message: {a: 1}", + is_proto3); + message.set_oneof_string(""); + RunValidProtobufTestWithMessage( + "OneofZeroString", RECOMMENDED, &message, "oneof_string: \"\"", is_proto3); + message.set_oneof_bytes(""); + RunValidProtobufTestWithMessage( + "OneofZeroBytes", RECOMMENDED, &message, "oneof_bytes: \"\"", is_proto3); + message.set_oneof_bool(false); + RunValidProtobufTestWithMessage( + "OneofZeroBool", RECOMMENDED, &message, "oneof_bool: false", is_proto3); + message.set_oneof_uint64(0); + RunValidProtobufTestWithMessage( + "OneofZeroUint64", RECOMMENDED, &message, "oneof_uint64: 0", is_proto3); + message.set_oneof_float(0.0f); + RunValidProtobufTestWithMessage( + "OneofZeroFloat", RECOMMENDED, &message, "oneof_float: 0", is_proto3); + message.set_oneof_double(0.0); + RunValidProtobufTestWithMessage( + "OneofZeroDouble", RECOMMENDED, &message, "oneof_double: 0", is_proto3); + message.set_oneof_enum(MessageType::FOO); + RunValidProtobufTestWithMessage( + "OneofZeroEnum", RECOMMENDED, &message, "oneof_enum: FOO", is_proto3); +} + +template +void BinaryAndJsonConformanceSuite::TestUnknownMessage( + MessageType& message, bool is_proto3) { + message.ParseFromString("\xA8\x1F\x01"); + RunValidBinaryProtobufTest("UnknownVarint", REQUIRED, + message.SerializeAsString(), is_proto3); +} + +void BinaryAndJsonConformanceSuite::RunSuiteImpl() { + // Hack to get the list of test failures based on whether + // GOOGLE3_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER is enabled or not. + conformance::FailureSet failure_set; + ConformanceRequest req; + ConformanceResponse res; + req.set_message_type(failure_set.GetTypeName()); + req.set_protobuf_payload(""); + req.set_requested_output_format(conformance::WireFormat::PROTOBUF); + RunTest("FindFailures", req, &res); + GOOGLE_CHECK(failure_set.MergeFromString(res.protobuf_payload())); + for (const string& failure : failure_set.failure()) { + AddExpectedFailedTest(failure); + } + + type_resolver_.reset(NewTypeResolverForDescriptorPool( + kTypeUrlPrefix, DescriptorPool::generated_pool())); + type_url_ = GetTypeUrl(TestAllTypesProto3::descriptor()); + + for (int i = 1; i <= FieldDescriptor::MAX_TYPE; i++) { + if (i == FieldDescriptor::TYPE_GROUP) continue; + TestPrematureEOFForType(static_cast(i)); + } + + TestIllegalTags(); + + int64 kInt64Min = -9223372036854775808ULL; + int64 kInt64Max = 9223372036854775807ULL; + uint64 kUint64Max = 18446744073709551615ULL; + int32 kInt32Max = 2147483647; + int32 kInt32Min = -2147483648; + uint32 kUint32Max = 4294967295UL; + + TestValidDataForType(FieldDescriptor::TYPE_DOUBLE, { + {dbl(0.1), "0.1"}, + {dbl(1.7976931348623157e+308), "1.7976931348623157e+308"}, + {dbl(2.22507385850720138309e-308), "2.22507385850720138309e-308"} + }); + TestValidDataForType(FieldDescriptor::TYPE_FLOAT, { + {flt(0.1), "0.1"}, + {flt(1.00000075e-36), "1.00000075e-36"}, + {flt(3.402823e+38), "3.402823e+38"}, // 3.40282347e+38 + {flt(1.17549435e-38f), "1.17549435e-38"} + }); + TestValidDataForType(FieldDescriptor::TYPE_INT64, { + {varint(12345), "12345"}, + {varint(kInt64Max), std::to_string(kInt64Max)}, + {varint(kInt64Min), std::to_string(kInt64Min)} + }); + TestValidDataForType(FieldDescriptor::TYPE_UINT64, { + {varint(12345), "12345"}, + {varint(kUint64Max), std::to_string(kUint64Max)}, + {varint(0), "0"} + }); + TestValidDataForType(FieldDescriptor::TYPE_INT32, { + {varint(12345), "12345"}, + {longvarint(12345, 2), "12345"}, + {longvarint(12345, 7), "12345"}, + {varint(kInt32Max), std::to_string(kInt32Max)}, + {varint(kInt32Min), std::to_string(kInt32Min)}, + {varint(1LL << 33), std::to_string(static_cast(1LL << 33))}, + {varint((1LL << 33) - 1), + std::to_string(static_cast((1LL << 33) - 1))}, + }); + TestValidDataForType(FieldDescriptor::TYPE_UINT32, { + {varint(12345), "12345"}, + {longvarint(12345, 2), "12345"}, + {longvarint(12345, 7), "12345"}, + {varint(kUint32Max), std::to_string(kUint32Max)}, // UINT32_MAX + {varint(0), "0"}, + {varint(1LL << 33), std::to_string(static_cast(1LL << 33))}, + {varint((1LL << 33) - 1), + std::to_string(static_cast((1LL << 33) - 1))}, + }); + TestValidDataForType(FieldDescriptor::TYPE_FIXED64, { + {u64(12345), "12345"}, + {u64(kUint64Max), std::to_string(kUint64Max)}, + {u64(0), "0"} + }); + TestValidDataForType(FieldDescriptor::TYPE_FIXED32, { + {u32(12345), "12345"}, + {u32(kUint32Max), std::to_string(kUint32Max)}, // UINT32_MAX + {u32(0), "0"} + }); + TestValidDataForType(FieldDescriptor::TYPE_SFIXED64, { + {u64(12345), "12345"}, + {u64(kInt64Max), std::to_string(kInt64Max)}, + {u64(kInt64Min), std::to_string(kInt64Min)} + }); + TestValidDataForType(FieldDescriptor::TYPE_SFIXED32, { + {u32(12345), "12345"}, + {u32(kInt32Max), std::to_string(kInt32Max)}, + {u32(kInt32Min), std::to_string(kInt32Min)} + }); + TestValidDataForType(FieldDescriptor::TYPE_BOOL, { + {varint(1), "true"}, + {varint(0), "false"}, + {varint(12345678), "true"} + }); + TestValidDataForType(FieldDescriptor::TYPE_SINT32, { + {zz32(12345), "12345"}, + {zz32(kInt32Max), std::to_string(kInt32Max)}, + {zz32(kInt32Min), std::to_string(kInt32Min)} + }); + TestValidDataForType(FieldDescriptor::TYPE_SINT64, { + {zz64(12345), "12345"}, + {zz64(kInt64Max), std::to_string(kInt64Max)}, + {zz64(kInt64Min), std::to_string(kInt64Min)} + }); + + // TODO(haberman): + // TestValidDataForType(FieldDescriptor::TYPE_STRING + // TestValidDataForType(FieldDescriptor::TYPE_GROUP + // TestValidDataForType(FieldDescriptor::TYPE_MESSAGE + // TestValidDataForType(FieldDescriptor::TYPE_BYTES + // TestValidDataForType(FieldDescriptor::TYPE_ENUM + + RunValidJsonTest("HelloWorld", REQUIRED, + "{\"optionalString\":\"Hello, World!\"}", + "optional_string: 'Hello, World!'"); + + // NOTE: The spec for JSON support is still being sorted out, these may not + // all be correct. + // Test field name conventions. + RunValidJsonTest( + "FieldNameInSnakeCase", REQUIRED, + R"({ + "fieldname1": 1, + "fieldName2": 2, + "FieldName3": 3, + "fieldName4": 4 + })", + R"( + fieldname1: 1 + field_name2: 2 + _field_name3: 3 + field__name4_: 4 + )"); + RunValidJsonTest( + "FieldNameWithNumbers", REQUIRED, + R"({ + "field0name5": 5, + "field0Name6": 6 + })", + R"( + field0name5: 5 + field_0_name6: 6 + )"); + RunValidJsonTest( + "FieldNameWithMixedCases", REQUIRED, + R"({ + "fieldName7": 7, + "FieldName8": 8, + "fieldName9": 9, + "FieldName10": 10, + "FIELDNAME11": 11, + "FIELDName12": 12 + })", + R"( + fieldName7: 7 + FieldName8: 8 + field_Name9: 9 + Field_Name10: 10 + FIELD_NAME11: 11 + FIELD_name12: 12 + )"); + RunValidJsonTest( + "FieldNameWithDoubleUnderscores", RECOMMENDED, + R"({ + "FieldName13": 13, + "FieldName14": 14, + "fieldName15": 15, + "fieldName16": 16, + "fieldName17": 17, + "FieldName18": 18 + })", + R"( + __field_name13: 13 + __Field_name14: 14 + field__name15: 15 + field__Name16: 16 + field_name17__: 17 + Field_name18__: 18 + )"); + // Using the original proto field name in JSON is also allowed. + RunValidJsonTest( + "OriginalProtoFieldName", REQUIRED, + R"({ + "fieldname1": 1, + "field_name2": 2, + "_field_name3": 3, + "field__name4_": 4, + "field0name5": 5, + "field_0_name6": 6, + "fieldName7": 7, + "FieldName8": 8, + "field_Name9": 9, + "Field_Name10": 10, + "FIELD_NAME11": 11, + "FIELD_name12": 12, + "__field_name13": 13, + "__Field_name14": 14, + "field__name15": 15, + "field__Name16": 16, + "field_name17__": 17, + "Field_name18__": 18 + })", + R"( + fieldname1: 1 + field_name2: 2 + _field_name3: 3 + field__name4_: 4 + field0name5: 5 + field_0_name6: 6 + fieldName7: 7 + FieldName8: 8 + field_Name9: 9 + Field_Name10: 10 + FIELD_NAME11: 11 + FIELD_name12: 12 + __field_name13: 13 + __Field_name14: 14 + field__name15: 15 + field__Name16: 16 + field_name17__: 17 + Field_name18__: 18 + )"); + // Field names can be escaped. + RunValidJsonTest( + "FieldNameEscaped", REQUIRED, + R"({"fieldn\u0061me1": 1})", + "fieldname1: 1"); + // String ends with escape character. + ExpectParseFailureForJson( + "StringEndsWithEscapeChar", RECOMMENDED, + "{\"optionalString\": \"abc\\"); + // Field names must be quoted (or it's not valid JSON). + ExpectParseFailureForJson( + "FieldNameNotQuoted", RECOMMENDED, + "{fieldname1: 1}"); + // Trailing comma is not allowed (not valid JSON). + ExpectParseFailureForJson( + "TrailingCommaInAnObject", RECOMMENDED, + R"({"fieldname1":1,})"); + ExpectParseFailureForJson( + "TrailingCommaInAnObjectWithSpace", RECOMMENDED, + R"({"fieldname1":1 ,})"); + ExpectParseFailureForJson( + "TrailingCommaInAnObjectWithSpaceCommaSpace", RECOMMENDED, + R"({"fieldname1":1 , })"); + ExpectParseFailureForJson( + "TrailingCommaInAnObjectWithNewlines", RECOMMENDED, + R"({ + "fieldname1":1, + })"); + // JSON doesn't support comments. + ExpectParseFailureForJson( + "JsonWithComments", RECOMMENDED, + R"({ + // This is a comment. + "fieldname1": 1 + })"); + // JSON spec says whitespace doesn't matter, so try a few spacings to be sure. + RunValidJsonTest( + "OneLineNoSpaces", RECOMMENDED, + "{\"optionalInt32\":1,\"optionalInt64\":2}", + R"( + optional_int32: 1 + optional_int64: 2 + )"); + RunValidJsonTest( + "OneLineWithSpaces", RECOMMENDED, + "{ \"optionalInt32\" : 1 , \"optionalInt64\" : 2 }", + R"( + optional_int32: 1 + optional_int64: 2 + )"); + RunValidJsonTest( + "MultilineNoSpaces", RECOMMENDED, + "{\n\"optionalInt32\"\n:\n1\n,\n\"optionalInt64\"\n:\n2\n}", + R"( + optional_int32: 1 + optional_int64: 2 + )"); + RunValidJsonTest( + "MultilineWithSpaces", RECOMMENDED, + "{\n \"optionalInt32\" : 1\n ,\n \"optionalInt64\" : 2\n}\n", + R"( + optional_int32: 1 + optional_int64: 2 + )"); + // Missing comma between key/value pairs. + ExpectParseFailureForJson( + "MissingCommaOneLine", RECOMMENDED, + "{ \"optionalInt32\": 1 \"optionalInt64\": 2 }"); + ExpectParseFailureForJson( + "MissingCommaMultiline", RECOMMENDED, + "{\n \"optionalInt32\": 1\n \"optionalInt64\": 2\n}"); + // Duplicated field names are not allowed. + ExpectParseFailureForJson( + "FieldNameDuplicate", RECOMMENDED, + R"({ + "optionalNestedMessage": {a: 1}, + "optionalNestedMessage": {} + })"); + ExpectParseFailureForJson( + "FieldNameDuplicateDifferentCasing1", RECOMMENDED, + R"({ + "optional_nested_message": {a: 1}, + "optionalNestedMessage": {} + })"); + ExpectParseFailureForJson( + "FieldNameDuplicateDifferentCasing2", RECOMMENDED, + R"({ + "optionalNestedMessage": {a: 1}, + "optional_nested_message": {} + })"); + // Serializers should use lowerCamelCase by default. + RunValidJsonTestWithValidator( + "FieldNameInLowerCamelCase", REQUIRED, + R"({ + "fieldname1": 1, + "fieldName2": 2, + "FieldName3": 3, + "fieldName4": 4 + })", + [](const Json::Value& value) { + return value.isMember("fieldname1") && + value.isMember("fieldName2") && + value.isMember("FieldName3") && + value.isMember("fieldName4"); + }); + RunValidJsonTestWithValidator( + "FieldNameWithNumbers", REQUIRED, + R"({ + "field0name5": 5, + "field0Name6": 6 + })", + [](const Json::Value& value) { + return value.isMember("field0name5") && + value.isMember("field0Name6"); + }); + RunValidJsonTestWithValidator( + "FieldNameWithMixedCases", REQUIRED, + R"({ + "fieldName7": 7, + "FieldName8": 8, + "fieldName9": 9, + "FieldName10": 10, + "FIELDNAME11": 11, + "FIELDName12": 12 + })", + [](const Json::Value& value) { + return value.isMember("fieldName7") && + value.isMember("FieldName8") && + value.isMember("fieldName9") && + value.isMember("FieldName10") && + value.isMember("FIELDNAME11") && + value.isMember("FIELDName12"); + }); + RunValidJsonTestWithValidator( + "FieldNameWithDoubleUnderscores", RECOMMENDED, + R"({ + "FieldName13": 13, + "FieldName14": 14, + "fieldName15": 15, + "fieldName16": 16, + "fieldName17": 17, + "FieldName18": 18 + })", + [](const Json::Value& value) { + return value.isMember("FieldName13") && + value.isMember("FieldName14") && + value.isMember("fieldName15") && + value.isMember("fieldName16") && + value.isMember("fieldName17") && + value.isMember("FieldName18"); + }); + + // Integer fields. + RunValidJsonTest( + "Int32FieldMaxValue", REQUIRED, + R"({"optionalInt32": 2147483647})", + "optional_int32: 2147483647"); + RunValidJsonTest( + "Int32FieldMinValue", REQUIRED, + R"({"optionalInt32": -2147483648})", + "optional_int32: -2147483648"); + RunValidJsonTest( + "Uint32FieldMaxValue", REQUIRED, + R"({"optionalUint32": 4294967295})", + "optional_uint32: 4294967295"); + RunValidJsonTest( + "Int64FieldMaxValue", REQUIRED, + R"({"optionalInt64": "9223372036854775807"})", + "optional_int64: 9223372036854775807"); + RunValidJsonTest( + "Int64FieldMinValue", REQUIRED, + R"({"optionalInt64": "-9223372036854775808"})", + "optional_int64: -9223372036854775808"); + RunValidJsonTest( + "Uint64FieldMaxValue", REQUIRED, + R"({"optionalUint64": "18446744073709551615"})", + "optional_uint64: 18446744073709551615"); + // While not the largest Int64, this is the largest + // Int64 which can be exactly represented within an + // IEEE-754 64-bit float, which is the expected level + // of interoperability guarantee. Larger values may + // work in some implementations, but should not be + // relied upon. + RunValidJsonTest( + "Int64FieldMaxValueNotQuoted", REQUIRED, + R"({"optionalInt64": 9223372036854774784})", + "optional_int64: 9223372036854774784"); + RunValidJsonTest( + "Int64FieldMinValueNotQuoted", REQUIRED, + R"({"optionalInt64": -9223372036854775808})", + "optional_int64: -9223372036854775808"); + // Largest interoperable Uint64; see comment above + // for Int64FieldMaxValueNotQuoted. + RunValidJsonTest( + "Uint64FieldMaxValueNotQuoted", REQUIRED, + R"({"optionalUint64": 18446744073709549568})", + "optional_uint64: 18446744073709549568"); + // Values can be represented as JSON strings. + RunValidJsonTest( + "Int32FieldStringValue", REQUIRED, + R"({"optionalInt32": "2147483647"})", + "optional_int32: 2147483647"); + RunValidJsonTest( + "Int32FieldStringValueEscaped", REQUIRED, + R"({"optionalInt32": "2\u003147483647"})", + "optional_int32: 2147483647"); + + // Parsers reject out-of-bound integer values. + ExpectParseFailureForJson( + "Int32FieldTooLarge", REQUIRED, + R"({"optionalInt32": 2147483648})"); + ExpectParseFailureForJson( + "Int32FieldTooSmall", REQUIRED, + R"({"optionalInt32": -2147483649})"); + ExpectParseFailureForJson( + "Uint32FieldTooLarge", REQUIRED, + R"({"optionalUint32": 4294967296})"); + ExpectParseFailureForJson( + "Int64FieldTooLarge", REQUIRED, + R"({"optionalInt64": "9223372036854775808"})"); + ExpectParseFailureForJson( + "Int64FieldTooSmall", REQUIRED, + R"({"optionalInt64": "-9223372036854775809"})"); + ExpectParseFailureForJson( + "Uint64FieldTooLarge", REQUIRED, + R"({"optionalUint64": "18446744073709551616"})"); + // Parser reject non-integer numeric values as well. + ExpectParseFailureForJson( + "Int32FieldNotInteger", REQUIRED, + R"({"optionalInt32": 0.5})"); + ExpectParseFailureForJson( + "Uint32FieldNotInteger", REQUIRED, + R"({"optionalUint32": 0.5})"); + ExpectParseFailureForJson( + "Int64FieldNotInteger", REQUIRED, + R"({"optionalInt64": "0.5"})"); + ExpectParseFailureForJson( + "Uint64FieldNotInteger", REQUIRED, + R"({"optionalUint64": "0.5"})"); + + // Integers but represented as float values are accepted. + RunValidJsonTest( + "Int32FieldFloatTrailingZero", REQUIRED, + R"({"optionalInt32": 100000.000})", + "optional_int32: 100000"); + RunValidJsonTest( + "Int32FieldExponentialFormat", REQUIRED, + R"({"optionalInt32": 1e5})", + "optional_int32: 100000"); + RunValidJsonTest( + "Int32FieldMaxFloatValue", REQUIRED, + R"({"optionalInt32": 2.147483647e9})", + "optional_int32: 2147483647"); + RunValidJsonTest( + "Int32FieldMinFloatValue", REQUIRED, + R"({"optionalInt32": -2.147483648e9})", + "optional_int32: -2147483648"); + RunValidJsonTest( + "Uint32FieldMaxFloatValue", REQUIRED, + R"({"optionalUint32": 4.294967295e9})", + "optional_uint32: 4294967295"); + + // Parser reject non-numeric values. + ExpectParseFailureForJson( + "Int32FieldNotNumber", REQUIRED, + R"({"optionalInt32": "3x3"})"); + ExpectParseFailureForJson( + "Uint32FieldNotNumber", REQUIRED, + R"({"optionalUint32": "3x3"})"); + ExpectParseFailureForJson( + "Int64FieldNotNumber", REQUIRED, + R"({"optionalInt64": "3x3"})"); + ExpectParseFailureForJson( + "Uint64FieldNotNumber", REQUIRED, + R"({"optionalUint64": "3x3"})"); + // JSON does not allow "+" on numric values. + ExpectParseFailureForJson( + "Int32FieldPlusSign", REQUIRED, + R"({"optionalInt32": +1})"); + // JSON doesn't allow leading 0s. + ExpectParseFailureForJson( + "Int32FieldLeadingZero", REQUIRED, + R"({"optionalInt32": 01})"); + ExpectParseFailureForJson( + "Int32FieldNegativeWithLeadingZero", REQUIRED, + R"({"optionalInt32": -01})"); + // String values must follow the same syntax rule. Specifically leading + // or trailing spaces are not allowed. + ExpectParseFailureForJson( + "Int32FieldLeadingSpace", REQUIRED, + R"({"optionalInt32": " 1"})"); + ExpectParseFailureForJson( + "Int32FieldTrailingSpace", REQUIRED, + R"({"optionalInt32": "1 "})"); + + // 64-bit values are serialized as strings. + RunValidJsonTestWithValidator( + "Int64FieldBeString", RECOMMENDED, + R"({"optionalInt64": 1})", + [](const Json::Value& value) { + return value["optionalInt64"].type() == Json::stringValue && + value["optionalInt64"].asString() == "1"; + }); + RunValidJsonTestWithValidator( + "Uint64FieldBeString", RECOMMENDED, + R"({"optionalUint64": 1})", + [](const Json::Value& value) { + return value["optionalUint64"].type() == Json::stringValue && + value["optionalUint64"].asString() == "1"; + }); + + // Bool fields. + RunValidJsonTest( + "BoolFieldTrue", REQUIRED, + R"({"optionalBool":true})", + "optional_bool: true"); + RunValidJsonTest( + "BoolFieldFalse", REQUIRED, + R"({"optionalBool":false})", + "optional_bool: false"); + + // Other forms are not allowed. + ExpectParseFailureForJson( + "BoolFieldIntegerZero", RECOMMENDED, + R"({"optionalBool":0})"); + ExpectParseFailureForJson( + "BoolFieldIntegerOne", RECOMMENDED, + R"({"optionalBool":1})"); + ExpectParseFailureForJson( + "BoolFieldCamelCaseTrue", RECOMMENDED, + R"({"optionalBool":True})"); + ExpectParseFailureForJson( + "BoolFieldCamelCaseFalse", RECOMMENDED, + R"({"optionalBool":False})"); + ExpectParseFailureForJson( + "BoolFieldAllCapitalTrue", RECOMMENDED, + R"({"optionalBool":TRUE})"); + ExpectParseFailureForJson( + "BoolFieldAllCapitalFalse", RECOMMENDED, + R"({"optionalBool":FALSE})"); + ExpectParseFailureForJson( + "BoolFieldDoubleQuotedTrue", RECOMMENDED, + R"({"optionalBool":"true"})"); + ExpectParseFailureForJson( + "BoolFieldDoubleQuotedFalse", RECOMMENDED, + R"({"optionalBool":"false"})"); + + // Float fields. + RunValidJsonTest( + "FloatFieldMinPositiveValue", REQUIRED, + R"({"optionalFloat": 1.175494e-38})", + "optional_float: 1.175494e-38"); + RunValidJsonTest( + "FloatFieldMaxNegativeValue", REQUIRED, + R"({"optionalFloat": -1.175494e-38})", + "optional_float: -1.175494e-38"); + RunValidJsonTest( + "FloatFieldMaxPositiveValue", REQUIRED, + R"({"optionalFloat": 3.402823e+38})", + "optional_float: 3.402823e+38"); + RunValidJsonTest( + "FloatFieldMinNegativeValue", REQUIRED, + R"({"optionalFloat": 3.402823e+38})", + "optional_float: 3.402823e+38"); + // Values can be quoted. + RunValidJsonTest( + "FloatFieldQuotedValue", REQUIRED, + R"({"optionalFloat": "1"})", + "optional_float: 1"); + // Special values. + RunValidJsonTest( + "FloatFieldNan", REQUIRED, + R"({"optionalFloat": "NaN"})", + "optional_float: nan"); + RunValidJsonTest( + "FloatFieldInfinity", REQUIRED, + R"({"optionalFloat": "Infinity"})", + "optional_float: inf"); + RunValidJsonTest( + "FloatFieldNegativeInfinity", REQUIRED, + R"({"optionalFloat": "-Infinity"})", + "optional_float: -inf"); + // Non-cannonical Nan will be correctly normalized. + { + TestAllTypesProto3 message; + // IEEE floating-point standard 32-bit quiet NaN: + // 0111 1111 1xxx xxxx xxxx xxxx xxxx xxxx + message.set_optional_float( + WireFormatLite::DecodeFloat(0x7FA12345)); + RunValidJsonTestWithProtobufInput( + "FloatFieldNormalizeQuietNan", REQUIRED, message, + "optional_float: nan"); + // IEEE floating-point standard 64-bit signaling NaN: + // 1111 1111 1xxx xxxx xxxx xxxx xxxx xxxx + message.set_optional_float( + WireFormatLite::DecodeFloat(0xFFB54321)); + RunValidJsonTestWithProtobufInput( + "FloatFieldNormalizeSignalingNan", REQUIRED, message, + "optional_float: nan"); + } + + // Special values must be quoted. + ExpectParseFailureForJson( + "FloatFieldNanNotQuoted", RECOMMENDED, + R"({"optionalFloat": NaN})"); + ExpectParseFailureForJson( + "FloatFieldInfinityNotQuoted", RECOMMENDED, + R"({"optionalFloat": Infinity})"); + ExpectParseFailureForJson( + "FloatFieldNegativeInfinityNotQuoted", RECOMMENDED, + R"({"optionalFloat": -Infinity})"); + // Parsers should reject out-of-bound values. + ExpectParseFailureForJson( + "FloatFieldTooSmall", REQUIRED, + R"({"optionalFloat": -3.502823e+38})"); + ExpectParseFailureForJson( + "FloatFieldTooLarge", REQUIRED, + R"({"optionalFloat": 3.502823e+38})"); + + // Double fields. + RunValidJsonTest( + "DoubleFieldMinPositiveValue", REQUIRED, + R"({"optionalDouble": 2.22507e-308})", + "optional_double: 2.22507e-308"); + RunValidJsonTest( + "DoubleFieldMaxNegativeValue", REQUIRED, + R"({"optionalDouble": -2.22507e-308})", + "optional_double: -2.22507e-308"); + RunValidJsonTest( + "DoubleFieldMaxPositiveValue", REQUIRED, + R"({"optionalDouble": 1.79769e+308})", + "optional_double: 1.79769e+308"); + RunValidJsonTest( + "DoubleFieldMinNegativeValue", REQUIRED, + R"({"optionalDouble": -1.79769e+308})", + "optional_double: -1.79769e+308"); + // Values can be quoted. + RunValidJsonTest( + "DoubleFieldQuotedValue", REQUIRED, + R"({"optionalDouble": "1"})", + "optional_double: 1"); + // Speical values. + RunValidJsonTest( + "DoubleFieldNan", REQUIRED, + R"({"optionalDouble": "NaN"})", + "optional_double: nan"); + RunValidJsonTest( + "DoubleFieldInfinity", REQUIRED, + R"({"optionalDouble": "Infinity"})", + "optional_double: inf"); + RunValidJsonTest( + "DoubleFieldNegativeInfinity", REQUIRED, + R"({"optionalDouble": "-Infinity"})", + "optional_double: -inf"); + // Non-cannonical Nan will be correctly normalized. + { + TestAllTypesProto3 message; + message.set_optional_double( + WireFormatLite::DecodeDouble(0x7FFA123456789ABCLL)); + RunValidJsonTestWithProtobufInput( + "DoubleFieldNormalizeQuietNan", REQUIRED, message, + "optional_double: nan"); + message.set_optional_double( + WireFormatLite::DecodeDouble(0xFFFBCBA987654321LL)); + RunValidJsonTestWithProtobufInput( + "DoubleFieldNormalizeSignalingNan", REQUIRED, message, + "optional_double: nan"); + } + + // Special values must be quoted. + ExpectParseFailureForJson( + "DoubleFieldNanNotQuoted", RECOMMENDED, + R"({"optionalDouble": NaN})"); + ExpectParseFailureForJson( + "DoubleFieldInfinityNotQuoted", RECOMMENDED, + R"({"optionalDouble": Infinity})"); + ExpectParseFailureForJson( + "DoubleFieldNegativeInfinityNotQuoted", RECOMMENDED, + R"({"optionalDouble": -Infinity})"); + + // Parsers should reject out-of-bound values. + ExpectParseFailureForJson( + "DoubleFieldTooSmall", REQUIRED, + R"({"optionalDouble": -1.89769e+308})"); + ExpectParseFailureForJson( + "DoubleFieldTooLarge", REQUIRED, + R"({"optionalDouble": +1.89769e+308})"); + + // Enum fields. + RunValidJsonTest( + "EnumField", REQUIRED, + R"({"optionalNestedEnum": "FOO"})", + "optional_nested_enum: FOO"); + // Enum fields with alias + RunValidJsonTest( + "EnumFieldWithAlias", REQUIRED, + R"({"optionalAliasedEnum": "ALIAS_BAZ"})", + "optional_aliased_enum: ALIAS_BAZ"); + RunValidJsonTest( + "EnumFieldWithAliasUseAlias", REQUIRED, + R"({"optionalAliasedEnum": "QUX"})", + "optional_aliased_enum: ALIAS_BAZ"); + RunValidJsonTest( + "EnumFieldWithAliasLowerCase", REQUIRED, + R"({"optionalAliasedEnum": "qux"})", + "optional_aliased_enum: ALIAS_BAZ"); + RunValidJsonTest( + "EnumFieldWithAliasDifferentCase", REQUIRED, + R"({"optionalAliasedEnum": "bAz"})", + "optional_aliased_enum: ALIAS_BAZ"); + // Enum values must be represented as strings. + ExpectParseFailureForJson( + "EnumFieldNotQuoted", REQUIRED, + R"({"optionalNestedEnum": FOO})"); + // Numeric values are allowed. + RunValidJsonTest( + "EnumFieldNumericValueZero", REQUIRED, + R"({"optionalNestedEnum": 0})", + "optional_nested_enum: FOO"); + RunValidJsonTest( + "EnumFieldNumericValueNonZero", REQUIRED, + R"({"optionalNestedEnum": 1})", + "optional_nested_enum: BAR"); + // Unknown enum values are represented as numeric values. + RunValidJsonTestWithValidator( + "EnumFieldUnknownValue", REQUIRED, + R"({"optionalNestedEnum": 123})", + [](const Json::Value& value) { + return value["optionalNestedEnum"].type() == Json::intValue && + value["optionalNestedEnum"].asInt() == 123; + }); + + // String fields. + RunValidJsonTest( + "StringField", REQUIRED, + R"({"optionalString": "Hello world!"})", + "optional_string: \"Hello world!\""); + RunValidJsonTest( + "StringFieldUnicode", REQUIRED, + // Google in Chinese. + R"({"optionalString": "谷歌"})", + R"(optional_string: "谷歌")"); + RunValidJsonTest( + "StringFieldEscape", REQUIRED, + R"({"optionalString": "\"\\\/\b\f\n\r\t"})", + R"(optional_string: "\"\\/\b\f\n\r\t")"); + RunValidJsonTest( + "StringFieldUnicodeEscape", REQUIRED, + R"({"optionalString": "\u8C37\u6B4C"})", + R"(optional_string: "谷歌")"); + RunValidJsonTest( + "StringFieldUnicodeEscapeWithLowercaseHexLetters", REQUIRED, + R"({"optionalString": "\u8c37\u6b4c"})", + R"(optional_string: "谷歌")"); + RunValidJsonTest( + "StringFieldSurrogatePair", REQUIRED, + // The character is an emoji: grinning face with smiling eyes. 😁 + R"({"optionalString": "\uD83D\uDE01"})", + R"(optional_string: "\xF0\x9F\x98\x81")"); + + // Unicode escapes must start with "\u" (lowercase u). + ExpectParseFailureForJson( + "StringFieldUppercaseEscapeLetter", RECOMMENDED, + R"({"optionalString": "\U8C37\U6b4C"})"); + ExpectParseFailureForJson( + "StringFieldInvalidEscape", RECOMMENDED, + R"({"optionalString": "\uXXXX\u6B4C"})"); + ExpectParseFailureForJson( + "StringFieldUnterminatedEscape", RECOMMENDED, + R"({"optionalString": "\u8C3"})"); + ExpectParseFailureForJson( + "StringFieldUnpairedHighSurrogate", RECOMMENDED, + R"({"optionalString": "\uD800"})"); + ExpectParseFailureForJson( + "StringFieldUnpairedLowSurrogate", RECOMMENDED, + R"({"optionalString": "\uDC00"})"); + ExpectParseFailureForJson( + "StringFieldSurrogateInWrongOrder", RECOMMENDED, + R"({"optionalString": "\uDE01\uD83D"})"); + ExpectParseFailureForJson( + "StringFieldNotAString", REQUIRED, + R"({"optionalString": 12345})"); + + // Bytes fields. + RunValidJsonTest( + "BytesField", REQUIRED, + R"({"optionalBytes": "AQI="})", + R"(optional_bytes: "\x01\x02")"); + RunValidJsonTest( + "BytesFieldBase64Url", RECOMMENDED, + R"({"optionalBytes": "-_"})", + R"(optional_bytes: "\xfb")"); + + // Message fields. + RunValidJsonTest( + "MessageField", REQUIRED, + R"({"optionalNestedMessage": {"a": 1234}})", + "optional_nested_message: {a: 1234}"); + + // Oneof fields. + ExpectParseFailureForJson( + "OneofFieldDuplicate", REQUIRED, + R"({"oneofUint32": 1, "oneofString": "test"})"); + // Ensure zero values for oneof make it out/backs. + TestAllTypesProto3 messageProto3; + TestAllTypesProto2 messageProto2; + TestOneofMessage(messageProto3, true); + TestOneofMessage(messageProto2, false); + RunValidJsonTest( + "OneofZeroUint32", RECOMMENDED, + R"({"oneofUint32": 0})", "oneof_uint32: 0"); + RunValidJsonTest( + "OneofZeroMessage", RECOMMENDED, + R"({"oneofNestedMessage": {}})", "oneof_nested_message: {}"); + RunValidJsonTest( + "OneofZeroString", RECOMMENDED, + R"({"oneofString": ""})", "oneof_string: \"\""); + RunValidJsonTest( + "OneofZeroBytes", RECOMMENDED, + R"({"oneofBytes": ""})", "oneof_bytes: \"\""); + RunValidJsonTest( + "OneofZeroBool", RECOMMENDED, + R"({"oneofBool": false})", "oneof_bool: false"); + RunValidJsonTest( + "OneofZeroUint64", RECOMMENDED, + R"({"oneofUint64": 0})", "oneof_uint64: 0"); + RunValidJsonTest( + "OneofZeroFloat", RECOMMENDED, + R"({"oneofFloat": 0.0})", "oneof_float: 0"); + RunValidJsonTest( + "OneofZeroDouble", RECOMMENDED, + R"({"oneofDouble": 0.0})", "oneof_double: 0"); + RunValidJsonTest( + "OneofZeroEnum", RECOMMENDED, + R"({"oneofEnum":"FOO"})", "oneof_enum: FOO"); + + // Repeated fields. + RunValidJsonTest( + "PrimitiveRepeatedField", REQUIRED, + R"({"repeatedInt32": [1, 2, 3, 4]})", + "repeated_int32: [1, 2, 3, 4]"); + RunValidJsonTest( + "EnumRepeatedField", REQUIRED, + R"({"repeatedNestedEnum": ["FOO", "BAR", "BAZ"]})", + "repeated_nested_enum: [FOO, BAR, BAZ]"); + RunValidJsonTest( + "StringRepeatedField", REQUIRED, + R"({"repeatedString": ["Hello", "world"]})", + R"(repeated_string: ["Hello", "world"])"); + RunValidJsonTest( + "BytesRepeatedField", REQUIRED, + R"({"repeatedBytes": ["AAEC", "AQI="]})", + R"(repeated_bytes: ["\x00\x01\x02", "\x01\x02"])"); + RunValidJsonTest( + "MessageRepeatedField", REQUIRED, + R"({"repeatedNestedMessage": [{"a": 1234}, {"a": 5678}]})", + "repeated_nested_message: {a: 1234}" + "repeated_nested_message: {a: 5678}"); + + // Repeated field elements are of incorrect type. + ExpectParseFailureForJson( + "RepeatedFieldWrongElementTypeExpectingIntegersGotBool", REQUIRED, + R"({"repeatedInt32": [1, false, 3, 4]})"); + ExpectParseFailureForJson( + "RepeatedFieldWrongElementTypeExpectingIntegersGotString", REQUIRED, + R"({"repeatedInt32": [1, 2, "name", 4]})"); + ExpectParseFailureForJson( + "RepeatedFieldWrongElementTypeExpectingIntegersGotMessage", REQUIRED, + R"({"repeatedInt32": [1, 2, 3, {"a": 4}]})"); + ExpectParseFailureForJson( + "RepeatedFieldWrongElementTypeExpectingStringsGotInt", REQUIRED, + R"({"repeatedString": ["1", 2, "3", "4"]})"); + ExpectParseFailureForJson( + "RepeatedFieldWrongElementTypeExpectingStringsGotBool", REQUIRED, + R"({"repeatedString": ["1", "2", false, "4"]})"); + ExpectParseFailureForJson( + "RepeatedFieldWrongElementTypeExpectingStringsGotMessage", REQUIRED, + R"({"repeatedString": ["1", 2, "3", {"a": 4}]})"); + ExpectParseFailureForJson( + "RepeatedFieldWrongElementTypeExpectingMessagesGotInt", REQUIRED, + R"({"repeatedNestedMessage": [{"a": 1}, 2]})"); + ExpectParseFailureForJson( + "RepeatedFieldWrongElementTypeExpectingMessagesGotBool", REQUIRED, + R"({"repeatedNestedMessage": [{"a": 1}, false]})"); + ExpectParseFailureForJson( + "RepeatedFieldWrongElementTypeExpectingMessagesGotString", REQUIRED, + R"({"repeatedNestedMessage": [{"a": 1}, "2"]})"); + // Trailing comma in the repeated field is not allowed. + ExpectParseFailureForJson( + "RepeatedFieldTrailingComma", RECOMMENDED, + R"({"repeatedInt32": [1, 2, 3, 4,]})"); + ExpectParseFailureForJson( + "RepeatedFieldTrailingCommaWithSpace", RECOMMENDED, + "{\"repeatedInt32\": [1, 2, 3, 4 ,]}"); + ExpectParseFailureForJson( + "RepeatedFieldTrailingCommaWithSpaceCommaSpace", RECOMMENDED, + "{\"repeatedInt32\": [1, 2, 3, 4 , ]}"); + ExpectParseFailureForJson( + "RepeatedFieldTrailingCommaWithNewlines", RECOMMENDED, + "{\"repeatedInt32\": [\n 1,\n 2,\n 3,\n 4,\n]}"); + + // Map fields. + RunValidJsonTest( + "Int32MapField", REQUIRED, + R"({"mapInt32Int32": {"1": 2, "3": 4}})", + "map_int32_int32: {key: 1 value: 2}" + "map_int32_int32: {key: 3 value: 4}"); + ExpectParseFailureForJson( + "Int32MapFieldKeyNotQuoted", RECOMMENDED, + R"({"mapInt32Int32": {1: 2, 3: 4}})"); + RunValidJsonTest( + "Uint32MapField", REQUIRED, + R"({"mapUint32Uint32": {"1": 2, "3": 4}})", + "map_uint32_uint32: {key: 1 value: 2}" + "map_uint32_uint32: {key: 3 value: 4}"); + ExpectParseFailureForJson( + "Uint32MapFieldKeyNotQuoted", RECOMMENDED, + R"({"mapUint32Uint32": {1: 2, 3: 4}})"); + RunValidJsonTest( + "Int64MapField", REQUIRED, + R"({"mapInt64Int64": {"1": 2, "3": 4}})", + "map_int64_int64: {key: 1 value: 2}" + "map_int64_int64: {key: 3 value: 4}"); + ExpectParseFailureForJson( + "Int64MapFieldKeyNotQuoted", RECOMMENDED, + R"({"mapInt64Int64": {1: 2, 3: 4}})"); + RunValidJsonTest( + "Uint64MapField", REQUIRED, + R"({"mapUint64Uint64": {"1": 2, "3": 4}})", + "map_uint64_uint64: {key: 1 value: 2}" + "map_uint64_uint64: {key: 3 value: 4}"); + ExpectParseFailureForJson( + "Uint64MapFieldKeyNotQuoted", RECOMMENDED, + R"({"mapUint64Uint64": {1: 2, 3: 4}})"); + RunValidJsonTest( + "BoolMapField", REQUIRED, + R"({"mapBoolBool": {"true": true, "false": false}})", + "map_bool_bool: {key: true value: true}" + "map_bool_bool: {key: false value: false}"); + ExpectParseFailureForJson( + "BoolMapFieldKeyNotQuoted", RECOMMENDED, + R"({"mapBoolBool": {true: true, false: false}})"); + RunValidJsonTest( + "MessageMapField", REQUIRED, + R"({ + "mapStringNestedMessage": { + "hello": {"a": 1234}, + "world": {"a": 5678} + } + })", + R"( + map_string_nested_message: { + key: "hello" + value: {a: 1234} + } + map_string_nested_message: { + key: "world" + value: {a: 5678} + } + )"); + // Since Map keys are represented as JSON strings, escaping should be allowed. + RunValidJsonTest( + "Int32MapEscapedKey", REQUIRED, + R"({"mapInt32Int32": {"\u0031": 2}})", + "map_int32_int32: {key: 1 value: 2}"); + RunValidJsonTest( + "Int64MapEscapedKey", REQUIRED, + R"({"mapInt64Int64": {"\u0031": 2}})", + "map_int64_int64: {key: 1 value: 2}"); + RunValidJsonTest( + "BoolMapEscapedKey", REQUIRED, + R"({"mapBoolBool": {"tr\u0075e": true}})", + "map_bool_bool: {key: true value: true}"); + + // "null" is accepted for all fields types. + RunValidJsonTest( + "AllFieldAcceptNull", REQUIRED, + R"({ + "optionalInt32": null, + "optionalInt64": null, + "optionalUint32": null, + "optionalUint64": null, + "optionalSint32": null, + "optionalSint64": null, + "optionalFixed32": null, + "optionalFixed64": null, + "optionalSfixed32": null, + "optionalSfixed64": null, + "optionalFloat": null, + "optionalDouble": null, + "optionalBool": null, + "optionalString": null, + "optionalBytes": null, + "optionalNestedEnum": null, + "optionalNestedMessage": null, + "repeatedInt32": null, + "repeatedInt64": null, + "repeatedUint32": null, + "repeatedUint64": null, + "repeatedSint32": null, + "repeatedSint64": null, + "repeatedFixed32": null, + "repeatedFixed64": null, + "repeatedSfixed32": null, + "repeatedSfixed64": null, + "repeatedFloat": null, + "repeatedDouble": null, + "repeatedBool": null, + "repeatedString": null, + "repeatedBytes": null, + "repeatedNestedEnum": null, + "repeatedNestedMessage": null, + "mapInt32Int32": null, + "mapBoolBool": null, + "mapStringNestedMessage": null + })", + ""); + + // Repeated field elements cannot be null. + ExpectParseFailureForJson( + "RepeatedFieldPrimitiveElementIsNull", RECOMMENDED, + R"({"repeatedInt32": [1, null, 2]})"); + ExpectParseFailureForJson( + "RepeatedFieldMessageElementIsNull", RECOMMENDED, + R"({"repeatedNestedMessage": [{"a":1}, null, {"a":2}]})"); + // Map field keys cannot be null. + ExpectParseFailureForJson( + "MapFieldKeyIsNull", RECOMMENDED, + R"({"mapInt32Int32": {null: 1}})"); + // Map field values cannot be null. + ExpectParseFailureForJson( + "MapFieldValueIsNull", RECOMMENDED, + R"({"mapInt32Int32": {"0": null}})"); + + // http://www.rfc-editor.org/rfc/rfc7159.txt says strings have to use double + // quotes. + ExpectParseFailureForJson( + "StringFieldSingleQuoteKey", RECOMMENDED, + R"({'optionalString': "Hello world!"})"); + ExpectParseFailureForJson( + "StringFieldSingleQuoteValue", RECOMMENDED, + R"({"optionalString": 'Hello world!'})"); + ExpectParseFailureForJson( + "StringFieldSingleQuoteBoth", RECOMMENDED, + R"({'optionalString': 'Hello world!'})"); + + // Unknown fields. + { + TestAllTypesProto3 messageProto3; + TestAllTypesProto2 messageProto2; + //TODO(yilunchong): update this behavior when unknown field's behavior + // changed in open source. Also delete + // Required.Proto3.ProtobufInput.UnknownVarint.ProtobufOutput + // from failure list of python_cpp python java + TestUnknownMessage(messageProto3, true); + TestUnknownMessage(messageProto2, false); + } + + // Wrapper types. + RunValidJsonTest( + "OptionalBoolWrapper", REQUIRED, + R"({"optionalBoolWrapper": false})", + "optional_bool_wrapper: {value: false}"); + RunValidJsonTest( + "OptionalInt32Wrapper", REQUIRED, + R"({"optionalInt32Wrapper": 0})", + "optional_int32_wrapper: {value: 0}"); + RunValidJsonTest( + "OptionalUint32Wrapper", REQUIRED, + R"({"optionalUint32Wrapper": 0})", + "optional_uint32_wrapper: {value: 0}"); + RunValidJsonTest( + "OptionalInt64Wrapper", REQUIRED, + R"({"optionalInt64Wrapper": 0})", + "optional_int64_wrapper: {value: 0}"); + RunValidJsonTest( + "OptionalUint64Wrapper", REQUIRED, + R"({"optionalUint64Wrapper": 0})", + "optional_uint64_wrapper: {value: 0}"); + RunValidJsonTest( + "OptionalFloatWrapper", REQUIRED, + R"({"optionalFloatWrapper": 0})", + "optional_float_wrapper: {value: 0}"); + RunValidJsonTest( + "OptionalDoubleWrapper", REQUIRED, + R"({"optionalDoubleWrapper": 0})", + "optional_double_wrapper: {value: 0}"); + RunValidJsonTest( + "OptionalStringWrapper", REQUIRED, + R"({"optionalStringWrapper": ""})", + R"(optional_string_wrapper: {value: ""})"); + RunValidJsonTest( + "OptionalBytesWrapper", REQUIRED, + R"({"optionalBytesWrapper": ""})", + R"(optional_bytes_wrapper: {value: ""})"); + RunValidJsonTest( + "OptionalWrapperTypesWithNonDefaultValue", REQUIRED, + R"({ + "optionalBoolWrapper": true, + "optionalInt32Wrapper": 1, + "optionalUint32Wrapper": 1, + "optionalInt64Wrapper": "1", + "optionalUint64Wrapper": "1", + "optionalFloatWrapper": 1, + "optionalDoubleWrapper": 1, + "optionalStringWrapper": "1", + "optionalBytesWrapper": "AQI=" + })", + R"( + optional_bool_wrapper: {value: true} + optional_int32_wrapper: {value: 1} + optional_uint32_wrapper: {value: 1} + optional_int64_wrapper: {value: 1} + optional_uint64_wrapper: {value: 1} + optional_float_wrapper: {value: 1} + optional_double_wrapper: {value: 1} + optional_string_wrapper: {value: "1"} + optional_bytes_wrapper: {value: "\x01\x02"} + )"); + RunValidJsonTest( + "RepeatedBoolWrapper", REQUIRED, + R"({"repeatedBoolWrapper": [true, false]})", + "repeated_bool_wrapper: {value: true}" + "repeated_bool_wrapper: {value: false}"); + RunValidJsonTest( + "RepeatedInt32Wrapper", REQUIRED, + R"({"repeatedInt32Wrapper": [0, 1]})", + "repeated_int32_wrapper: {value: 0}" + "repeated_int32_wrapper: {value: 1}"); + RunValidJsonTest( + "RepeatedUint32Wrapper", REQUIRED, + R"({"repeatedUint32Wrapper": [0, 1]})", + "repeated_uint32_wrapper: {value: 0}" + "repeated_uint32_wrapper: {value: 1}"); + RunValidJsonTest( + "RepeatedInt64Wrapper", REQUIRED, + R"({"repeatedInt64Wrapper": [0, 1]})", + "repeated_int64_wrapper: {value: 0}" + "repeated_int64_wrapper: {value: 1}"); + RunValidJsonTest( + "RepeatedUint64Wrapper", REQUIRED, + R"({"repeatedUint64Wrapper": [0, 1]})", + "repeated_uint64_wrapper: {value: 0}" + "repeated_uint64_wrapper: {value: 1}"); + RunValidJsonTest( + "RepeatedFloatWrapper", REQUIRED, + R"({"repeatedFloatWrapper": [0, 1]})", + "repeated_float_wrapper: {value: 0}" + "repeated_float_wrapper: {value: 1}"); + RunValidJsonTest( + "RepeatedDoubleWrapper", REQUIRED, + R"({"repeatedDoubleWrapper": [0, 1]})", + "repeated_double_wrapper: {value: 0}" + "repeated_double_wrapper: {value: 1}"); + RunValidJsonTest( + "RepeatedStringWrapper", REQUIRED, + R"({"repeatedStringWrapper": ["", "AQI="]})", + R"( + repeated_string_wrapper: {value: ""} + repeated_string_wrapper: {value: "AQI="} + )"); + RunValidJsonTest( + "RepeatedBytesWrapper", REQUIRED, + R"({"repeatedBytesWrapper": ["", "AQI="]})", + R"( + repeated_bytes_wrapper: {value: ""} + repeated_bytes_wrapper: {value: "\x01\x02"} + )"); + RunValidJsonTest( + "WrapperTypesWithNullValue", REQUIRED, + R"({ + "optionalBoolWrapper": null, + "optionalInt32Wrapper": null, + "optionalUint32Wrapper": null, + "optionalInt64Wrapper": null, + "optionalUint64Wrapper": null, + "optionalFloatWrapper": null, + "optionalDoubleWrapper": null, + "optionalStringWrapper": null, + "optionalBytesWrapper": null, + "repeatedBoolWrapper": null, + "repeatedInt32Wrapper": null, + "repeatedUint32Wrapper": null, + "repeatedInt64Wrapper": null, + "repeatedUint64Wrapper": null, + "repeatedFloatWrapper": null, + "repeatedDoubleWrapper": null, + "repeatedStringWrapper": null, + "repeatedBytesWrapper": null + })", + ""); + + // Duration + RunValidJsonTest( + "DurationMinValue", REQUIRED, + R"({"optionalDuration": "-315576000000.999999999s"})", + "optional_duration: {seconds: -315576000000 nanos: -999999999}"); + RunValidJsonTest( + "DurationMaxValue", REQUIRED, + R"({"optionalDuration": "315576000000.999999999s"})", + "optional_duration: {seconds: 315576000000 nanos: 999999999}"); + RunValidJsonTest( + "DurationRepeatedValue", REQUIRED, + R"({"repeatedDuration": ["1.5s", "-1.5s"]})", + "repeated_duration: {seconds: 1 nanos: 500000000}" + "repeated_duration: {seconds: -1 nanos: -500000000}"); + RunValidJsonTest( + "DurationNull", REQUIRED, + R"({"optionalDuration": null})", + ""); + + ExpectParseFailureForJson( + "DurationMissingS", REQUIRED, + R"({"optionalDuration": "1"})"); + ExpectParseFailureForJson( + "DurationJsonInputTooSmall", REQUIRED, + R"({"optionalDuration": "-315576000001.000000000s"})"); + ExpectParseFailureForJson( + "DurationJsonInputTooLarge", REQUIRED, + R"({"optionalDuration": "315576000001.000000000s"})"); + ExpectSerializeFailureForJson( + "DurationProtoInputTooSmall", REQUIRED, + "optional_duration: {seconds: -315576000001 nanos: 0}"); + ExpectSerializeFailureForJson( + "DurationProtoInputTooLarge", REQUIRED, + "optional_duration: {seconds: 315576000001 nanos: 0}"); + + RunValidJsonTestWithValidator( + "DurationHasZeroFractionalDigit", RECOMMENDED, + R"({"optionalDuration": "1.000000000s"})", + [](const Json::Value& value) { + return value["optionalDuration"].asString() == "1s"; + }); + RunValidJsonTestWithValidator( + "DurationHas3FractionalDigits", RECOMMENDED, + R"({"optionalDuration": "1.010000000s"})", + [](const Json::Value& value) { + return value["optionalDuration"].asString() == "1.010s"; + }); + RunValidJsonTestWithValidator( + "DurationHas6FractionalDigits", RECOMMENDED, + R"({"optionalDuration": "1.000010000s"})", + [](const Json::Value& value) { + return value["optionalDuration"].asString() == "1.000010s"; + }); + RunValidJsonTestWithValidator( + "DurationHas9FractionalDigits", RECOMMENDED, + R"({"optionalDuration": "1.000000010s"})", + [](const Json::Value& value) { + return value["optionalDuration"].asString() == "1.000000010s"; + }); + + // Timestamp + RunValidJsonTest( + "TimestampMinValue", REQUIRED, + R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})", + "optional_timestamp: {seconds: -62135596800}"); + RunValidJsonTest( + "TimestampMaxValue", REQUIRED, + R"({"optionalTimestamp": "9999-12-31T23:59:59.999999999Z"})", + "optional_timestamp: {seconds: 253402300799 nanos: 999999999}"); + RunValidJsonTest( + "TimestampRepeatedValue", REQUIRED, + R"({ + "repeatedTimestamp": [ + "0001-01-01T00:00:00Z", + "9999-12-31T23:59:59.999999999Z" + ] + })", + "repeated_timestamp: {seconds: -62135596800}" + "repeated_timestamp: {seconds: 253402300799 nanos: 999999999}"); + RunValidJsonTest( + "TimestampWithPositiveOffset", REQUIRED, + R"({"optionalTimestamp": "1970-01-01T08:00:00+08:00"})", + "optional_timestamp: {seconds: 0}"); + RunValidJsonTest( + "TimestampWithNegativeOffset", REQUIRED, + R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})", + "optional_timestamp: {seconds: 0}"); + RunValidJsonTest( + "TimestampNull", REQUIRED, + R"({"optionalTimestamp": null})", + ""); + + ExpectParseFailureForJson( + "TimestampJsonInputTooSmall", REQUIRED, + R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})"); + ExpectParseFailureForJson( + "TimestampJsonInputTooLarge", REQUIRED, + R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})"); + ExpectParseFailureForJson( + "TimestampJsonInputMissingZ", REQUIRED, + R"({"optionalTimestamp": "0001-01-01T00:00:00"})"); + ExpectParseFailureForJson( + "TimestampJsonInputMissingT", REQUIRED, + R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})"); + ExpectParseFailureForJson( + "TimestampJsonInputLowercaseZ", REQUIRED, + R"({"optionalTimestamp": "0001-01-01T00:00:00z"})"); + ExpectParseFailureForJson( + "TimestampJsonInputLowercaseT", REQUIRED, + R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})"); + ExpectSerializeFailureForJson( + "TimestampProtoInputTooSmall", REQUIRED, + "optional_timestamp: {seconds: -62135596801}"); + ExpectSerializeFailureForJson( + "TimestampProtoInputTooLarge", REQUIRED, + "optional_timestamp: {seconds: 253402300800}"); + RunValidJsonTestWithValidator( + "TimestampZeroNormalized", RECOMMENDED, + R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})", + [](const Json::Value& value) { + return value["optionalTimestamp"].asString() == + "1970-01-01T00:00:00Z"; + }); + RunValidJsonTestWithValidator( + "TimestampHasZeroFractionalDigit", RECOMMENDED, + R"({"optionalTimestamp": "1970-01-01T00:00:00.000000000Z"})", + [](const Json::Value& value) { + return value["optionalTimestamp"].asString() == + "1970-01-01T00:00:00Z"; + }); + RunValidJsonTestWithValidator( + "TimestampHas3FractionalDigits", RECOMMENDED, + R"({"optionalTimestamp": "1970-01-01T00:00:00.010000000Z"})", + [](const Json::Value& value) { + return value["optionalTimestamp"].asString() == + "1970-01-01T00:00:00.010Z"; + }); + RunValidJsonTestWithValidator( + "TimestampHas6FractionalDigits", RECOMMENDED, + R"({"optionalTimestamp": "1970-01-01T00:00:00.000010000Z"})", + [](const Json::Value& value) { + return value["optionalTimestamp"].asString() == + "1970-01-01T00:00:00.000010Z"; + }); + RunValidJsonTestWithValidator( + "TimestampHas9FractionalDigits", RECOMMENDED, + R"({"optionalTimestamp": "1970-01-01T00:00:00.000000010Z"})", + [](const Json::Value& value) { + return value["optionalTimestamp"].asString() == + "1970-01-01T00:00:00.000000010Z"; + }); + + // FieldMask + RunValidJsonTest( + "FieldMask", REQUIRED, + R"({"optionalFieldMask": "foo,barBaz"})", + R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})"); + RunValidJsonTest( + "EmptyFieldMask", REQUIRED, + R"({"optionalFieldMask": ""})", + R"(optional_field_mask: {})"); + ExpectParseFailureForJson( + "FieldMaskInvalidCharacter", RECOMMENDED, + R"({"optionalFieldMask": "foo,bar_bar"})"); + ExpectSerializeFailureForJson( + "FieldMaskPathsDontRoundTrip", RECOMMENDED, + R"(optional_field_mask: {paths: "fooBar"})"); + ExpectSerializeFailureForJson( + "FieldMaskNumbersDontRoundTrip", RECOMMENDED, + R"(optional_field_mask: {paths: "foo_3_bar"})"); + ExpectSerializeFailureForJson( + "FieldMaskTooManyUnderscore", RECOMMENDED, + R"(optional_field_mask: {paths: "foo__bar"})"); + + // Struct + RunValidJsonTest( + "Struct", REQUIRED, + R"({ + "optionalStruct": { + "nullValue": null, + "intValue": 1234, + "boolValue": true, + "doubleValue": 1234.5678, + "stringValue": "Hello world!", + "listValue": [1234, "5678"], + "objectValue": { + "value": 0 + } + } + })", + R"( + optional_struct: { + fields: { + key: "nullValue" + value: {null_value: NULL_VALUE} + } + fields: { + key: "intValue" + value: {number_value: 1234} + } + fields: { + key: "boolValue" + value: {bool_value: true} + } + fields: { + key: "doubleValue" + value: {number_value: 1234.5678} + } + fields: { + key: "stringValue" + value: {string_value: "Hello world!"} + } + fields: { + key: "listValue" + value: { + list_value: { + values: { + number_value: 1234 + } + values: { + string_value: "5678" + } + } + } + } + fields: { + key: "objectValue" + value: { + struct_value: { + fields: { + key: "value" + value: { + number_value: 0 + } + } + } + } + } + } + )"); + RunValidJsonTest( + "StructWithEmptyListValue", REQUIRED, + R"({ + "optionalStruct": { + "listValue": [] + } + })", + R"( + optional_struct: { + fields: { + key: "listValue" + value: { + list_value: { + } + } + } + } + )"); + // Value + RunValidJsonTest( + "ValueAcceptInteger", REQUIRED, + R"({"optionalValue": 1})", + "optional_value: { number_value: 1}"); + RunValidJsonTest( + "ValueAcceptFloat", REQUIRED, + R"({"optionalValue": 1.5})", + "optional_value: { number_value: 1.5}"); + RunValidJsonTest( + "ValueAcceptBool", REQUIRED, + R"({"optionalValue": false})", + "optional_value: { bool_value: false}"); + RunValidJsonTest( + "ValueAcceptNull", REQUIRED, + R"({"optionalValue": null})", + "optional_value: { null_value: NULL_VALUE}"); + RunValidJsonTest( + "ValueAcceptString", REQUIRED, + R"({"optionalValue": "hello"})", + R"(optional_value: { string_value: "hello"})"); + RunValidJsonTest( + "ValueAcceptList", REQUIRED, + R"({"optionalValue": [0, "hello"]})", + R"( + optional_value: { + list_value: { + values: { + number_value: 0 + } + values: { + string_value: "hello" + } + } + } + )"); + RunValidJsonTest( + "ValueAcceptObject", REQUIRED, + R"({"optionalValue": {"value": 1}})", + R"( + optional_value: { + struct_value: { + fields: { + key: "value" + value: { + number_value: 1 + } + } + } + } + )"); + RunValidJsonTest( + "RepeatedValue", REQUIRED, + R"({ + "repeatedValue": [["a"]] + })", + R"( + repeated_value: [ + { + list_value: { + values: [ + { string_value: "a"} + ] + } + } + ] + )"); + RunValidJsonTest( + "RepeatedListValue", REQUIRED, + R"({ + "repeatedListValue": [["a"]] + })", + R"( + repeated_list_value: [ + { + values: [ + { string_value: "a"} + ] + } + ] + )"); + + // Any + RunValidJsonTest( + "Any", REQUIRED, + R"({ + "optionalAny": { + "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3", + "optionalInt32": 12345 + } + })", + R"( + optional_any: { + [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] { + optional_int32: 12345 + } + } + )"); + RunValidJsonTest( + "AnyNested", REQUIRED, + R"({ + "optionalAny": { + "@type": "type.googleapis.com/google.protobuf.Any", + "value": { + "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3", + "optionalInt32": 12345 + } + } + })", + R"( + optional_any: { + [type.googleapis.com/google.protobuf.Any] { + [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] { + optional_int32: 12345 + } + } + } + )"); + // The special "@type" tag is not required to appear first. + RunValidJsonTest( + "AnyUnorderedTypeTag", REQUIRED, + R"({ + "optionalAny": { + "optionalInt32": 12345, + "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3" + } + })", + R"( + optional_any: { + [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] { + optional_int32: 12345 + } + } + )"); + // Well-known types in Any. + RunValidJsonTest( + "AnyWithInt32ValueWrapper", REQUIRED, + R"({ + "optionalAny": { + "@type": "type.googleapis.com/google.protobuf.Int32Value", + "value": 12345 + } + })", + R"( + optional_any: { + [type.googleapis.com/google.protobuf.Int32Value] { + value: 12345 + } + } + )"); + RunValidJsonTest( + "AnyWithDuration", REQUIRED, + R"({ + "optionalAny": { + "@type": "type.googleapis.com/google.protobuf.Duration", + "value": "1.5s" + } + })", + R"( + optional_any: { + [type.googleapis.com/google.protobuf.Duration] { + seconds: 1 + nanos: 500000000 + } + } + )"); + RunValidJsonTest( + "AnyWithTimestamp", REQUIRED, + R"({ + "optionalAny": { + "@type": "type.googleapis.com/google.protobuf.Timestamp", + "value": "1970-01-01T00:00:00Z" + } + })", + R"( + optional_any: { + [type.googleapis.com/google.protobuf.Timestamp] { + seconds: 0 + nanos: 0 + } + } + )"); + RunValidJsonTest( + "AnyWithFieldMask", REQUIRED, + R"({ + "optionalAny": { + "@type": "type.googleapis.com/google.protobuf.FieldMask", + "value": "foo,barBaz" + } + })", + R"( + optional_any: { + [type.googleapis.com/google.protobuf.FieldMask] { + paths: ["foo", "bar_baz"] + } + } + )"); + RunValidJsonTest( + "AnyWithStruct", REQUIRED, + R"({ + "optionalAny": { + "@type": "type.googleapis.com/google.protobuf.Struct", + "value": { + "foo": 1 + } + } + })", + R"( + optional_any: { + [type.googleapis.com/google.protobuf.Struct] { + fields: { + key: "foo" + value: { + number_value: 1 + } + } + } + } + )"); + RunValidJsonTest( + "AnyWithValueForJsonObject", REQUIRED, + R"({ + "optionalAny": { + "@type": "type.googleapis.com/google.protobuf.Value", + "value": { + "foo": 1 + } + } + })", + R"( + optional_any: { + [type.googleapis.com/google.protobuf.Value] { + struct_value: { + fields: { + key: "foo" + value: { + number_value: 1 + } + } + } + } + } + )"); + RunValidJsonTest( + "AnyWithValueForInteger", REQUIRED, + R"({ + "optionalAny": { + "@type": "type.googleapis.com/google.protobuf.Value", + "value": 1 + } + })", + R"( + optional_any: { + [type.googleapis.com/google.protobuf.Value] { + number_value: 1 + } + } + )"); + + RunValidJsonIgnoreUnknownTest( + "IgnoreUnknownJsonNumber", REQUIRED, + R"({ + "unknown": 1 + })", + ""); + RunValidJsonIgnoreUnknownTest( + "IgnoreUnknownJsonString", REQUIRED, + R"({ + "unknown": "a" + })", + ""); + RunValidJsonIgnoreUnknownTest( + "IgnoreUnknownJsonTrue", REQUIRED, + R"({ + "unknown": true + })", + ""); + RunValidJsonIgnoreUnknownTest( + "IgnoreUnknownJsonFalse", REQUIRED, + R"({ + "unknown": false + })", + ""); + RunValidJsonIgnoreUnknownTest( + "IgnoreUnknownJsonNull", REQUIRED, + R"({ + "unknown": null + })", + ""); + RunValidJsonIgnoreUnknownTest( + "IgnoreUnknownJsonObject", REQUIRED, + R"({ + "unknown": {"a": 1} + })", + ""); +} + +} // namespace protobuf +} // namespace google diff --git a/third_party/protobuf/conformance/binary_json_conformance_suite.h b/third_party/protobuf/conformance/binary_json_conformance_suite.h new file mode 100644 index 00000000..7a03545f --- /dev/null +++ b/third_party/protobuf/conformance/binary_json_conformance_suite.h @@ -0,0 +1,121 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#ifndef CONFORMANCE_BINARY_JSON_CONFORMANCE_SUITE_H +#define CONFORMANCE_BINARY_JSON_CONFORMANCE_SUITE_H + +#include "conformance_test.h" +#include "third_party/jsoncpp/json.h" + +namespace google { +namespace protobuf { + +class BinaryAndJsonConformanceSuite : public ConformanceTestSuite { + public: + BinaryAndJsonConformanceSuite() {} + + private: + void RunSuiteImpl(); + void RunValidJsonTest(const string& test_name, + ConformanceLevel level, + const string& input_json, + const string& equivalent_text_format); + void RunValidJsonTestWithProtobufInput( + const string& test_name, + ConformanceLevel level, + const protobuf_test_messages::proto3::TestAllTypesProto3& input, + const string& equivalent_text_format); + void RunValidJsonIgnoreUnknownTest( + const string& test_name, ConformanceLevel level, const string& input_json, + const string& equivalent_text_format); + void RunValidProtobufTest(const string& test_name, ConformanceLevel level, + const string& input_protobuf, + const string& equivalent_text_format, + bool is_proto3); + void RunValidBinaryProtobufTest(const string& test_name, + ConformanceLevel level, + const string& input_protobuf, + bool is_proto3); + void RunValidProtobufTestWithMessage( + const string& test_name, ConformanceLevel level, + const Message *input, + const string& equivalent_text_format, + bool is_proto3); + + bool ParseJsonResponse( + const conformance::ConformanceResponse& response, + Message* test_message); + bool ParseResponse( + const conformance::ConformanceResponse& response, + const ConformanceRequestSetting& setting, + Message* test_message) override; + + typedef std::function Validator; + void RunValidJsonTestWithValidator(const string& test_name, + ConformanceLevel level, + const string& input_json, + const Validator& validator); + void ExpectParseFailureForJson(const string& test_name, + ConformanceLevel level, + const string& input_json); + void ExpectSerializeFailureForJson(const string& test_name, + ConformanceLevel level, + const string& text_format); + void ExpectParseFailureForProtoWithProtoVersion (const string& proto, + const string& test_name, + ConformanceLevel level, + bool is_proto3); + void ExpectParseFailureForProto(const std::string& proto, + const std::string& test_name, + ConformanceLevel level); + void ExpectHardParseFailureForProto(const std::string& proto, + const std::string& test_name, + ConformanceLevel level); + void TestPrematureEOFForType(google::protobuf::FieldDescriptor::Type type); + void TestIllegalTags(); + template + void TestOneofMessage (MessageType &message, + bool is_proto3); + template + void TestUnknownMessage (MessageType &message, + bool is_proto3); + void TestValidDataForType( + google::protobuf::FieldDescriptor::Type, + std::vector> values); + + std::unique_ptr + type_resolver_; + std::string type_url_; +}; + +} // namespace protobuf +} // namespace google + +#endif // CONFORMANCE_BINARY_JSON_CONFORMANCE_SUITE_H diff --git a/third_party/protobuf/conformance/conformance.proto b/third_party/protobuf/conformance/conformance.proto index 525140e9..54da406c 100644 --- a/third_party/protobuf/conformance/conformance.proto +++ b/third_party/protobuf/conformance/conformance.proto @@ -55,6 +55,32 @@ enum WireFormat { UNSPECIFIED = 0; PROTOBUF = 1; JSON = 2; + JSPB = 3; // Google internal only. Opensource testees just skip it. + TEXT_FORMAT = 4; +} + +enum TestCategory { + UNSPECIFIED_TEST = 0; + BINARY_TEST = 1; // Test binary wire format. + JSON_TEST = 2; // Test json wire format. + // Similar to JSON_TEST. However, during parsing json, testee should ignore + // unknown fields. This feature is optional. Each implementation can descide + // whether to support it. See + // https://developers.google.com/protocol-buffers/docs/proto3#json_options + // for more detail. + JSON_IGNORE_UNKNOWN_PARSING_TEST = 3; + // Test jspb wire format. Google internal only. Opensource testees just skip it. + JSPB_TEST = 4; + // Test text format. For cpp, java and python, testees can already deal with + // this type. Testees of other languages can simply skip it. + TEXT_FORMAT_TEST = 5; +} + +// The conformance runner will request a list of failures as the first request. +// This will be known by message_type == "conformance.FailureSet", a conformance +// test should return a serialized FailureSet in protobuf_payload. +message FailureSet { + repeated string failure = 1; } // Represents a single test case's input. The testee should: @@ -73,6 +99,9 @@ message ConformanceRequest { oneof payload { bytes protobuf_payload = 1; string json_payload = 2; + // Google internal only. Opensource testees just skip it. + string jspb_payload = 7; + string text_payload = 8; } // Which format should the testee serialize its message to? @@ -82,6 +111,18 @@ message ConformanceRequest { // protobuf_test_messages.proto3.TestAllTypesProto3 or // protobuf_test_messages.proto2.TestAllTypesProto2. string message_type = 4; + + // Each test is given a specific test category. Some category may need + // spedific support in testee programs. Refer to the defintion of TestCategory + // for more information. + TestCategory test_category = 5; + + // Specify details for how to encode jspb. + JspbEncodingConfig jspb_encoding_options = 6; + + // This can be used in json and text format. If true, testee should print + // unknown fields instead of ignore. This feature is optional. + bool print_unknown_fields = 9; } // Represents a single test case's output. @@ -115,5 +156,21 @@ message ConformanceResponse { // For when the testee skipped the test, likely because a certain feature // wasn't supported, like JSON input/output. string skipped = 5; + + // If the input was successfully parsed and the requested output was JSPB, + // serialize to JSPB and set it in this field. JSPB is google internal only + // format. Opensource testees can just skip it. + string jspb_payload = 7; + + // If the input was successfully parsed and the requested output was + // TEXT_FORMAT, serialize to TEXT_FORMAT and set it in this field. + string text_payload = 8; } } + +// Encoding options for jspb format. +message JspbEncodingConfig { + // Encode the value field of Any as jspb array if ture, otherwise binary. + bool use_jspb_array_any_format = 1; +} + diff --git a/third_party/protobuf/conformance/conformance_cpp.cc b/third_party/protobuf/conformance/conformance_cpp.cc index 97ae1a7a..5a1f2140 100644 --- a/third_party/protobuf/conformance/conformance_cpp.cc +++ b/third_party/protobuf/conformance/conformance_cpp.cc @@ -36,6 +36,7 @@ #include #include #include +#include #include #include @@ -45,17 +46,48 @@ using google::protobuf::Descriptor; using google::protobuf::DescriptorPool; using google::protobuf::Message; using google::protobuf::MessageFactory; +using google::protobuf::TextFormat; using google::protobuf::util::BinaryToJsonString; +using google::protobuf::util::JsonParseOptions; using google::protobuf::util::JsonToBinaryString; using google::protobuf::util::NewTypeResolverForDescriptorPool; using google::protobuf::util::Status; using google::protobuf::util::TypeResolver; -using protobuf_test_messages::proto3::TestAllTypesProto3; using protobuf_test_messages::proto2::TestAllTypesProto2; +using protobuf_test_messages::proto3::TestAllTypesProto3; using std::string; static const char kTypeUrlPrefix[] = "type.googleapis.com"; +const char* kFailures[] = { +#if !GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + "Required.Proto2.ProtobufInput." + "PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE", + "Required.Proto2.ProtobufInput." + "PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.BOOL", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.ENUM", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.INT32", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.INT64", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT32", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT64", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT32", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT64", + "Required.Proto3.ProtobufInput." + "PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE", + "Required.Proto3.ProtobufInput." + "PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.BOOL", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.ENUM", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.INT32", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.INT64", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.SINT32", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.SINT64", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.UINT32", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.UINT64", +#endif +}; + static string GetTypeUrl(const Descriptor* message) { return string(kTypeUrlPrefix) + "/" + message->full_name(); } @@ -112,8 +144,13 @@ void DoTest(const ConformanceRequest& request, ConformanceResponse* response) { case ConformanceRequest::kJsonPayload: { string proto_binary; + JsonParseOptions options; + options.ignore_unknown_fields = + (request.test_category() == + conformance::JSON_IGNORE_UNKNOWN_PARSING_TEST); Status status = JsonToBinaryString(type_resolver, *type_url, - request.json_payload(), &proto_binary); + request.json_payload(), &proto_binary, + options); if (!status.ok()) { response->set_parse_error(string("Parse error: ") + status.error_message().as_string()); @@ -128,9 +165,28 @@ void DoTest(const ConformanceRequest& request, ConformanceResponse* response) { break; } + case ConformanceRequest::kTextPayload: { + if (!TextFormat::ParseFromString(request.text_payload(), test_message)) { + response->set_parse_error("Parse error"); + return; + } + break; + } + case ConformanceRequest::PAYLOAD_NOT_SET: GOOGLE_LOG(FATAL) << "Request didn't have payload."; break; + + default: + GOOGLE_LOG(FATAL) << "unknown payload type: " + << request.payload_case(); + break; + } + + conformance::FailureSet failures; + if (descriptor == failures.GetDescriptor()) { + for (const char* s : kFailures) failures.add_failure(s); + test_message = &failures; } switch (request.requested_output_format()) { @@ -157,6 +213,14 @@ void DoTest(const ConformanceRequest& request, ConformanceResponse* response) { break; } + case conformance::TEXT_FORMAT: { + TextFormat::Printer printer; + printer.SetHideUnknownFields(!request.print_unknown_fields()); + GOOGLE_CHECK(printer.PrintToString(*test_message, + response->mutable_text_payload())); + break; + } + default: GOOGLE_LOG(FATAL) << "Unknown output format: " << request.requested_output_format(); diff --git a/third_party/protobuf/conformance/conformance_objc.m b/third_party/protobuf/conformance/conformance_objc.m index 84a43811..60b2ac59 100644 --- a/third_party/protobuf/conformance/conformance_objc.m +++ b/third_party/protobuf/conformance/conformance_objc.m @@ -92,6 +92,16 @@ static ConformanceResponse *DoTest(ConformanceRequest *request) { case ConformanceRequest_Payload_OneOfCase_JsonPayload: response.skipped = @"ObjC doesn't support parsing JSON"; break; + + case ConformanceRequest_Payload_OneOfCase_JspbPayload: + response.skipped = + @"ConformanceRequest had a jspb_payload ConformanceRequest.payload;" + " those aren't supposed to happen with opensource."; + break; + + case ConformanceRequest_Payload_OneOfCase_TextPayload: + response.skipped = @"ObjC doesn't support parsing TextFormat"; + break; } if (testMessage) { @@ -112,6 +122,18 @@ static ConformanceResponse *DoTest(ConformanceRequest *request) { case WireFormat_Json: response.skipped = @"ObjC doesn't support generating JSON"; break; + + case WireFormat_Jspb: + response.skipped = + @"ConformanceRequest had a requested_output_format of JSPB WireFormat; that" + " isn't supposed to happen with opensource."; + break; + + case WireFormat_TextFormat: + // ObjC only has partial objc generation, so don't attempt any tests that need + // support. + response.skipped = @"ObjC doesn't support generating TextFormat"; + break; } } diff --git a/third_party/protobuf/conformance/conformance_php.php b/third_party/protobuf/conformance/conformance_php.php index 85fe3d03..9eef0c5a 100755 --- a/third_party/protobuf/conformance/conformance_php.php +++ b/third_party/protobuf/conformance/conformance_php.php @@ -3,15 +3,20 @@ require_once("Conformance/WireFormat.php"); require_once("Conformance/ConformanceResponse.php"); require_once("Conformance/ConformanceRequest.php"); +require_once("Conformance/FailureSet.php"); +require_once("Conformance/JspbEncodingConfig.php"); +require_once("Conformance/TestCategory.php"); require_once("Protobuf_test_messages/Proto3/ForeignMessage.php"); require_once("Protobuf_test_messages/Proto3/ForeignEnum.php"); require_once("Protobuf_test_messages/Proto3/TestAllTypesProto3.php"); +require_once("Protobuf_test_messages/Proto3/TestAllTypesProto3/AliasedEnum.php"); require_once("Protobuf_test_messages/Proto3/TestAllTypesProto3/NestedMessage.php"); require_once("Protobuf_test_messages/Proto3/TestAllTypesProto3/NestedEnum.php"); require_once("GPBMetadata/Conformance.php"); require_once("GPBMetadata/Google/Protobuf/TestMessagesProto3.php"); +use \Conformance\TestCategory; use \Conformance\WireFormat; if (!ini_get("date.timezone")) { @@ -25,7 +30,10 @@ function doTest($request) $test_message = new \Protobuf_test_messages\Proto3\TestAllTypesProto3(); $response = new \Conformance\ConformanceResponse(); if ($request->getPayload() == "protobuf_payload") { - if ($request->getMessageType() == "protobuf_test_messages.proto3.TestAllTypesProto3") { + if ($request->getMessageType() == "conformance.FailureSet") { + $response->setProtobufPayload(""); + return $response; + } elseif ($request->getMessageType() == "protobuf_test_messages.proto3.TestAllTypesProto3") { try { $test_message->mergeFromString($request->getProtobufPayload()); } catch (Exception $e) { @@ -39,13 +47,20 @@ function doTest($request) trigger_error("Protobuf request doesn't have specific payload type", E_USER_ERROR); } } elseif ($request->getPayload() == "json_payload") { + $ignore_json_unknown = + ($request->getTestCategory() == + TestCategory::JSON_IGNORE_UNKNOWN_PARSING_TEST); try { - $test_message->mergeFromJsonString($request->getJsonPayload()); + $test_message->mergeFromJsonString($request->getJsonPayload(), + $ignore_json_unknown); } catch (Exception $e) { $response->setParseError($e->getMessage()); return $response; } - } else { + } elseif ($request->getPayload() == "text_payload") { + $response->setSkipped("PHP doesn't support text format yet"); + return $response; + } else { trigger_error("Request didn't have payload.", E_USER_ERROR); } diff --git a/third_party/protobuf/conformance/conformance_python.py b/third_party/protobuf/conformance/conformance_python.py index c5ba2467..88d97493 100755 --- a/third_party/protobuf/conformance/conformance_python.py +++ b/third_party/protobuf/conformance/conformance_python.py @@ -44,6 +44,7 @@ from google.protobuf import json_format from google.protobuf import message from google.protobuf import test_messages_proto3_pb2 from google.protobuf import test_messages_proto2_pb2 +from google.protobuf import text_format import conformance_pb2 sys.stdout = os.fdopen(sys.stdout.fileno(), 'wb', 0) @@ -56,29 +57,94 @@ class ProtocolError(Exception): pass def do_test(request): + response = conformance_pb2.ConformanceResponse() + + if request.message_type == "conformance.FailureSet": + failure_set = conformance_pb2.FailureSet() + failures = [] + # TODO(gerbens): Remove, this is a hack to detect if the old vs new + # parser is used by the cpp code. Relying on a bug in the old parser. + hack_proto = test_messages_proto2_pb2.TestAllTypesProto2() + old_parser = True + try: + hack_proto.ParseFromString(b"\322\002\001") + except message.DecodeError as e: + old_parser = False + if old_parser: + # the string above is one of the failing conformance test strings of the + # old parser. If we succeed the c++ implementation is using the old + # parser so we add the list of failing conformance tests. + failures = [ + "Required.Proto3.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE", + "Required.Proto3.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.BOOL", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.DOUBLE", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.ENUM", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.FIXED32", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.FIXED64", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.FLOAT", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.INT32", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.INT64", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.SFIXED32", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.SFIXED64", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.SINT32", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.SINT64", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.UINT32", + "Required.Proto3.ProtobufInput.PrematureEofInPackedField.UINT64", + "Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE", + "Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.BOOL", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.DOUBLE", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.ENUM", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.FIXED32", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.FIXED64", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.FLOAT", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.INT32", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.INT64", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.SFIXED32", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.SFIXED64", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT32", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT64", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT32", + "Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT64", + ] + for x in failures: + failure_set.failure.append(x) + response.protobuf_payload = failure_set.SerializeToString() + return response + isProto3 = (request.message_type == "protobuf_test_messages.proto3.TestAllTypesProto3") isJson = (request.WhichOneof('payload') == 'json_payload') isProto2 = (request.message_type == "protobuf_test_messages.proto2.TestAllTypesProto2") - + if (not isProto3) and (not isJson) and (not isProto2): raise ProtocolError("Protobuf request doesn't have specific payload type") - + test_message = test_messages_proto2_pb2.TestAllTypesProto2() if isProto2 else \ test_messages_proto3_pb2.TestAllTypesProto3() - response = conformance_pb2.ConformanceResponse() - try: if request.WhichOneof('payload') == 'protobuf_payload': try: test_message.ParseFromString(request.protobuf_payload) except message.DecodeError as e: response.parse_error = str(e) - return response - + return response + elif request.WhichOneof('payload') == 'json_payload': try: - json_format.Parse(request.json_payload, test_message) + ignore_unknown_fields = \ + request.test_category == \ + conformance_pb2.JSON_IGNORE_UNKNOWN_PARSING_TEST + json_format.Parse(request.json_payload, test_message, + ignore_unknown_fields) + except Exception as e: + response.parse_error = str(e) + return response + + elif request.WhichOneof('payload') == 'text_payload': + try: + text_format.Parse(request.text_payload, test_message) except Exception as e: response.parse_error = str(e) return response @@ -93,12 +159,16 @@ def do_test(request): response.protobuf_payload = test_message.SerializeToString() elif request.requested_output_format == conformance_pb2.JSON: - try: + try: response.json_payload = json_format.MessageToJson(test_message) except Exception as e: response.serialize_error = str(e) return response + elif request.requested_output_format == conformance_pb2.TEXT_FORMAT: + response.text_payload = text_format.MessageToString( + test_message, print_unknown_fields=request.print_unknown_fields) + except Exception as e: response.runtime_error = str(e) diff --git a/third_party/protobuf/conformance/conformance_ruby.rb b/third_party/protobuf/conformance/conformance_ruby.rb index df63bf7c..79d8d3dd 100755 --- a/third_party/protobuf/conformance/conformance_ruby.rb +++ b/third_party/protobuf/conformance/conformance_ruby.rb @@ -54,7 +54,7 @@ def do_test(request) elsif request.message_type.eql?('protobuf_test_messages.proto2.TestAllTypesProto2') response.skipped = "Ruby doesn't support proto2" return response - else + else fail "Protobuf request doesn't have specific payload type" end @@ -66,6 +66,12 @@ def do_test(request) response.parse_error = err.message.encode('utf-8') return response end + + when :text_payload + begin + response.skipped = "Ruby doesn't support proto2" + return response + end when nil fail "Request didn't have payload" diff --git a/third_party/protobuf/conformance/conformance_test.cc b/third_party/protobuf/conformance/conformance_test.cc index 22bbbfb3..6325b354 100644 --- a/third_party/protobuf/conformance/conformance_test.cc +++ b/third_party/protobuf/conformance/conformance_test.cc @@ -28,169 +28,138 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#include #include #include #include #include "conformance.pb.h" #include "conformance_test.h" -#include -#include -#include #include +#include +#include #include #include #include #include -#include -#include - -#include "third_party/jsoncpp/json.h" using conformance::ConformanceRequest; using conformance::ConformanceResponse; using conformance::WireFormat; -using google::protobuf::Descriptor; -using google::protobuf::FieldDescriptor; -using google::protobuf::internal::WireFormatLite; using google::protobuf::TextFormat; using google::protobuf::util::DefaultFieldComparator; using google::protobuf::util::JsonToBinaryString; using google::protobuf::util::MessageDifferencer; -using google::protobuf::util::NewTypeResolverForDescriptorPool; using google::protobuf::util::Status; -using protobuf_test_messages::proto3::TestAllTypesProto3; -using protobuf_test_messages::proto2::TestAllTypesProto2; using std::string; -namespace { - -static const char kTypeUrlPrefix[] = "type.googleapis.com"; - -static string GetTypeUrl(const Descriptor* message) { - return string(kTypeUrlPrefix) + "/" + message->full_name(); -} - -/* Routines for building arbitrary protos *************************************/ - -// We would use CodedOutputStream except that we want more freedom to build -// arbitrary protos (even invalid ones). - -const string empty; - -string cat(const string& a, const string& b, - const string& c = empty, - const string& d = empty, - const string& e = empty, - const string& f = empty, - const string& g = empty, - const string& h = empty, - const string& i = empty, - const string& j = empty, - const string& k = empty, - const string& l = empty) { - string ret; - ret.reserve(a.size() + b.size() + c.size() + d.size() + e.size() + f.size() + - g.size() + h.size() + i.size() + j.size() + k.size() + l.size()); - ret.append(a); - ret.append(b); - ret.append(c); - ret.append(d); - ret.append(e); - ret.append(f); - ret.append(g); - ret.append(h); - ret.append(i); - ret.append(j); - ret.append(k); - ret.append(l); - return ret; -} - -// The maximum number of bytes that it takes to encode a 64-bit varint. -#define VARINT_MAX_LEN 10 - -size_t vencode64(uint64_t val, int over_encoded_bytes, char *buf) { - if (val == 0) { buf[0] = 0; return 1; } - size_t i = 0; - while (val) { - uint8_t byte = val & 0x7fU; - val >>= 7; - if (val || over_encoded_bytes) byte |= 0x80U; - buf[i++] = byte; - } - while (over_encoded_bytes--) { - assert(i < 10); - uint8_t byte = over_encoded_bytes ? 0x80 : 0; - buf[i++] = byte; - } - return i; -} - -string varint(uint64_t x) { - char buf[VARINT_MAX_LEN]; - size_t len = vencode64(x, 0, buf); - return string(buf, len); -} - -// Encodes a varint that is |extra| bytes longer than it needs to be, but still -// valid. -string longvarint(uint64_t x, int extra) { - char buf[VARINT_MAX_LEN]; - size_t len = vencode64(x, extra, buf); - return string(buf, len); -} - -// TODO: proper byte-swapping for big-endian machines. -string fixed32(void *data) { return string(static_cast(data), 4); } -string fixed64(void *data) { return string(static_cast(data), 8); } - -string delim(const string& buf) { return cat(varint(buf.size()), buf); } -string u32(uint32_t u32) { return fixed32(&u32); } -string u64(uint64_t u64) { return fixed64(&u64); } -string flt(float f) { return fixed32(&f); } -string dbl(double d) { return fixed64(&d); } -string zz32(int32_t x) { return varint(WireFormatLite::ZigZagEncode32(x)); } -string zz64(int64_t x) { return varint(WireFormatLite::ZigZagEncode64(x)); } - -string tag(uint32_t fieldnum, char wire_type) { - return varint((fieldnum << 3) | wire_type); -} - -string submsg(uint32_t fn, const string& buf) { - return cat( tag(fn, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), delim(buf) ); -} - -#define UNKNOWN_FIELD 666 - -const FieldDescriptor* GetFieldForType(FieldDescriptor::Type type, - bool repeated, bool isProto3) { - - const Descriptor* d = isProto3 ? - TestAllTypesProto3().GetDescriptor() : TestAllTypesProto2().GetDescriptor(); - for (int i = 0; i < d->field_count(); i++) { - const FieldDescriptor* f = d->field(i); - if (f->type() == type && f->is_repeated() == repeated) { - return f; - } - } - GOOGLE_LOG(FATAL) << "Couldn't find field with type " << (int)type; - return nullptr; -} - -string UpperCase(string str) { - for (int i = 0; i < str.size(); i++) { - str[i] = toupper(str[i]); - } - return str; -} - -} // anonymous namespace - namespace google { namespace protobuf { +ConformanceTestSuite::ConformanceRequestSetting::ConformanceRequestSetting( + ConformanceLevel level, + conformance::WireFormat input_format, + conformance::WireFormat output_format, + conformance::TestCategory test_category, + const Message& prototype_message, + const string& test_name, const string& input) + : level_(level), + input_format_(input_format), + output_format_(output_format), + prototype_message_(prototype_message), + prototype_message_for_compare_(prototype_message.New()), + test_name_(test_name) { + switch (input_format) { + case conformance::PROTOBUF: { + request_.set_protobuf_payload(input); + break; + } + + case conformance::JSON: { + request_.set_json_payload(input); + break; + } + + case conformance::JSPB: { + request_.set_jspb_payload(input); + break; + } + + case conformance::TEXT_FORMAT: { + request_.set_text_payload(input); + break; + } + + default: + GOOGLE_LOG(FATAL) << "Unspecified input format"; + } + + request_.set_test_category(test_category); + + request_.set_message_type(prototype_message.GetDescriptor()->full_name()); + request_.set_requested_output_format(output_format); +} + +Message* ConformanceTestSuite::ConformanceRequestSetting:: + GetTestMessage() const { + return prototype_message_for_compare_->New(); +} + +string ConformanceTestSuite::ConformanceRequestSetting:: + GetTestName() const { + string rname = + prototype_message_.GetDescriptor()->file()->syntax() == + FileDescriptor::SYNTAX_PROTO3 ? "Proto3" : "Proto2"; + + return StrCat(ConformanceLevelToString(level_), ".", + rname, ".", + InputFormatString(input_format_), + ".", test_name_, ".", + OutputFormatString(output_format_)); +} + +string ConformanceTestSuite::ConformanceRequestSetting:: + ConformanceLevelToString( + ConformanceLevel level) const { + switch (level) { + case REQUIRED: return "Required"; + case RECOMMENDED: return "Recommended"; + } + GOOGLE_LOG(FATAL) << "Unknown value: " << level; + return ""; +} + +string ConformanceTestSuite::ConformanceRequestSetting:: + InputFormatString(conformance::WireFormat format) const { + switch (format) { + case conformance::PROTOBUF: + return "ProtobufInput"; + case conformance::JSON: + return "JsonInput"; + case conformance::TEXT_FORMAT: + return "TextFormatInput"; + default: + GOOGLE_LOG(FATAL) << "Unspecified output format"; + } + return ""; +} + +string ConformanceTestSuite::ConformanceRequestSetting:: + OutputFormatString(conformance::WireFormat format) const { + switch (format) { + case conformance::PROTOBUF: + return "ProtobufOutput"; + case conformance::JSON: + return "JsonOutput"; + case conformance::TEXT_FORMAT: + return "TextFormatOutput"; + default: + GOOGLE_LOG(FATAL) << "Unspecified output format"; + } + return ""; +} + void ConformanceTestSuite::ReportSuccess(const string& test_name) { if (expected_to_fail_.erase(test_name) != 0) { StringAppendF(&output_, @@ -237,13 +206,81 @@ void ConformanceTestSuite::ReportSkip(const string& test_name, skipped_.insert(test_name); } -string ConformanceTestSuite::ConformanceLevelToString(ConformanceLevel level) { - switch (level) { - case REQUIRED: return "Required"; - case RECOMMENDED: return "Recommended"; +void ConformanceTestSuite::RunValidInputTest( + const ConformanceRequestSetting& setting, + const string& equivalent_text_format) { + Message* reference_message = setting.GetTestMessage(); + GOOGLE_CHECK( + TextFormat::ParseFromString(equivalent_text_format, reference_message)) + << "Failed to parse data for test case: " << setting.GetTestName() + << ", data: " << equivalent_text_format; + const string equivalent_wire_format = reference_message->SerializeAsString(); + RunValidBinaryInputTest(setting, equivalent_wire_format); +} + +void ConformanceTestSuite::RunValidBinaryInputTest( + const ConformanceRequestSetting& setting, + const string& equivalent_wire_format) { + const ConformanceRequest& request = setting.GetRequest(); + ConformanceResponse response; + RunTest(setting.GetTestName(), request, &response); + VerifyResponse(setting, equivalent_wire_format, response, true); +} + +void ConformanceTestSuite::VerifyResponse( + const ConformanceRequestSetting& setting, + const string& equivalent_wire_format, + const ConformanceResponse& response, + bool need_report_success) { + Message* test_message = setting.GetTestMessage(); + const ConformanceRequest& request = setting.GetRequest(); + const string& test_name = setting.GetTestName(); + ConformanceLevel level = setting.GetLevel(); + Message* reference_message = setting.GetTestMessage(); + + GOOGLE_CHECK( + reference_message->ParseFromString(equivalent_wire_format)) + << "Failed to parse wire data for test case: " << test_name; + + switch (response.result_case()) { + case ConformanceResponse::RESULT_NOT_SET: + ReportFailure(test_name, level, request, response, + "Response didn't have any field in the Response."); + return; + + case ConformanceResponse::kParseError: + case ConformanceResponse::kRuntimeError: + case ConformanceResponse::kSerializeError: + ReportFailure(test_name, level, request, response, + "Failed to parse input or produce output."); + return; + + case ConformanceResponse::kSkipped: + ReportSkip(test_name, request, response); + return; + + default: + if (!ParseResponse(response, setting, test_message)) return; + } + + MessageDifferencer differencer; + DefaultFieldComparator field_comparator; + field_comparator.set_treat_nan_as_equal(true); + differencer.set_field_comparator(&field_comparator); + string differences; + differencer.ReportDifferencesToString(&differences); + + bool check; + check = differencer.Compare(*reference_message, *test_message); + if (check) { + if (need_report_success) { + ReportSuccess(test_name); + } + } else { + ReportFailure(test_name, level, request, response, + "Output was not equivalent to reference message: %s.", + differences.c_str()); } - GOOGLE_LOG(FATAL) << "Unknown value: " << level; - return ""; } void ConformanceTestSuite::RunTest(const string& test_name, @@ -265,505 +302,18 @@ void ConformanceTestSuite::RunTest(const string& test_name, } if (verbose_) { - StringAppendF(&output_, "conformance test: name=%s, request=%s, response=%s\n", + StringAppendF(&output_, + "conformance test: name=%s, request=%s, response=%s\n", test_name.c_str(), request.ShortDebugString().c_str(), response->ShortDebugString().c_str()); } } -void ConformanceTestSuite::RunValidInputTest( - const string& test_name, ConformanceLevel level, const string& input, - WireFormat input_format, const string& equivalent_text_format, - WireFormat requested_output, bool isProto3) { - auto newTestMessage = [&isProto3]() { - Message* newMessage; - if (isProto3) { - newMessage = new TestAllTypesProto3; - } else { - newMessage = new TestAllTypesProto2; - } - return newMessage; - }; - Message* reference_message = newTestMessage(); - GOOGLE_CHECK( - TextFormat::ParseFromString(equivalent_text_format, reference_message)) - << "Failed to parse data for test case: " << test_name - << ", data: " << equivalent_text_format; - const string equivalent_wire_format = reference_message->SerializeAsString(); - RunValidBinaryInputTest(test_name, level, input, input_format, - equivalent_wire_format, requested_output, isProto3); -} - -void ConformanceTestSuite::RunValidBinaryInputTest( - const string& test_name, ConformanceLevel level, const string& input, - WireFormat input_format, const string& equivalent_wire_format, - WireFormat requested_output, bool isProto3) { - auto newTestMessage = [&isProto3]() { - Message* newMessage; - if (isProto3) { - newMessage = new TestAllTypesProto3; - } else { - newMessage = new TestAllTypesProto2; - } - return newMessage; - }; - Message* reference_message = newTestMessage(); - GOOGLE_CHECK( - reference_message->ParseFromString(equivalent_wire_format)) - << "Failed to parse wire data for test case: " << test_name; - - ConformanceRequest request; - ConformanceResponse response; - - switch (input_format) { - case conformance::PROTOBUF: { - request.set_protobuf_payload(input); - if (isProto3) { - request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3"); - } else { - request.set_message_type("protobuf_test_messages.proto2.TestAllTypesProto2"); - } - break; - } - - case conformance::JSON: { - request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3"); - request.set_json_payload(input); - break; - } - - default: - GOOGLE_LOG(FATAL) << "Unspecified input format"; - } - - request.set_requested_output_format(requested_output); - - RunTest(test_name, request, &response); - - Message *test_message = newTestMessage(); - - switch (response.result_case()) { - case ConformanceResponse::RESULT_NOT_SET: - ReportFailure(test_name, level, request, response, - "Response didn't have any field in the Response."); - return; - - case ConformanceResponse::kParseError: - case ConformanceResponse::kRuntimeError: - case ConformanceResponse::kSerializeError: - ReportFailure(test_name, level, request, response, - "Failed to parse input or produce output."); - return; - - case ConformanceResponse::kSkipped: - ReportSkip(test_name, request, response); - return; - - case ConformanceResponse::kJsonPayload: { - if (requested_output != conformance::JSON) { - ReportFailure( - test_name, level, request, response, - "Test was asked for protobuf output but provided JSON instead."); - return; - } - string binary_protobuf; - Status status = - JsonToBinaryString(type_resolver_.get(), type_url_, - response.json_payload(), &binary_protobuf); - if (!status.ok()) { - ReportFailure(test_name, level, request, response, - "JSON output we received from test was unparseable."); - return; - } - - if (!test_message->ParseFromString(binary_protobuf)) { - ReportFailure(test_name, level, request, response, - "INTERNAL ERROR: internal JSON->protobuf transcode " - "yielded unparseable proto."); - return; - } - - break; - } - - case ConformanceResponse::kProtobufPayload: { - if (requested_output != conformance::PROTOBUF) { - ReportFailure( - test_name, level, request, response, - "Test was asked for JSON output but provided protobuf instead."); - return; - } - - if (!test_message->ParseFromString(response.protobuf_payload())) { - ReportFailure(test_name, level, request, response, - "Protobuf output we received from test was unparseable."); - return; - } - - break; - } - - default: - GOOGLE_LOG(FATAL) << test_name << ": unknown payload type: " - << response.result_case(); - } - - MessageDifferencer differencer; - DefaultFieldComparator field_comparator; - field_comparator.set_treat_nan_as_equal(true); - differencer.set_field_comparator(&field_comparator); - string differences; - differencer.ReportDifferencesToString(&differences); - - bool check; - check = differencer.Compare(*reference_message, *test_message); - if (check) { - ReportSuccess(test_name); - } else { - ReportFailure(test_name, level, request, response, - "Output was not equivalent to reference message: %s.", - differences.c_str()); - } -} -void ConformanceTestSuite::ExpectParseFailureForProtoWithProtoVersion ( - const string& proto, const string& test_name, ConformanceLevel level, - bool isProto3) { - ConformanceRequest request; - ConformanceResponse response; - request.set_protobuf_payload(proto); - if (isProto3) { - request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3"); - } else { - request.set_message_type("protobuf_test_messages.proto2.TestAllTypesProto2"); - } - string effective_test_name = ConformanceLevelToString(level) + - (isProto3 ? ".Proto3" : ".Proto2") + - ".ProtobufInput." + test_name; - - // We don't expect output, but if the program erroneously accepts the protobuf - // we let it send its response as this. We must not leave it unspecified. - request.set_requested_output_format(conformance::PROTOBUF); - - RunTest(effective_test_name, request, &response); - if (response.result_case() == ConformanceResponse::kParseError) { - ReportSuccess(effective_test_name); - } else if (response.result_case() == ConformanceResponse::kSkipped) { - ReportSkip(effective_test_name, request, response); - } else { - ReportFailure(effective_test_name, level, request, response, - "Should have failed to parse, but didn't."); - } -} - -// Expect that this precise protobuf will cause a parse error. -void ConformanceTestSuite::ExpectParseFailureForProto( - const string& proto, const string& test_name, ConformanceLevel level) { - ExpectParseFailureForProtoWithProtoVersion(proto, test_name, level, true); - ExpectParseFailureForProtoWithProtoVersion(proto, test_name, level, false); -} - -// Expect that this protobuf will cause a parse error, even if it is followed -// by valid protobuf data. We can try running this twice: once with this -// data verbatim and once with this data followed by some valid data. -// -// TODO(haberman): implement the second of these. -void ConformanceTestSuite::ExpectHardParseFailureForProto( - const string& proto, const string& test_name, ConformanceLevel level) { - return ExpectParseFailureForProto(proto, test_name, level); -} - -void ConformanceTestSuite::RunValidJsonTest( - const string& test_name, ConformanceLevel level, const string& input_json, - const string& equivalent_text_format) { - RunValidInputTest( - ConformanceLevelToString(level) + ".Proto3.JsonInput." + test_name + - ".ProtobufOutput", level, input_json, conformance::JSON, - equivalent_text_format, conformance::PROTOBUF, true); - RunValidInputTest( - ConformanceLevelToString(level) + ".Proto3.JsonInput." + test_name + - ".JsonOutput", level, input_json, conformance::JSON, - equivalent_text_format, conformance::JSON, true); -} - -void ConformanceTestSuite::RunValidJsonTestWithProtobufInput( - const string& test_name, ConformanceLevel level, const TestAllTypesProto3& input, - const string& equivalent_text_format) { - RunValidInputTest( - ConformanceLevelToString(level) + ".Proto3" + ".ProtobufInput." + test_name + - ".JsonOutput", level, input.SerializeAsString(), conformance::PROTOBUF, - equivalent_text_format, conformance::JSON, true); -} - -void ConformanceTestSuite::RunValidProtobufTest( - const string& test_name, ConformanceLevel level, - const string& input_protobuf, const string& equivalent_text_format, - bool isProto3) { - string rname = ".Proto3"; - if (!isProto3) { - rname = ".Proto2"; - } - RunValidInputTest( - ConformanceLevelToString(level) + rname + ".ProtobufInput." + test_name + - ".ProtobufOutput", level, input_protobuf, conformance::PROTOBUF, - equivalent_text_format, conformance::PROTOBUF, isProto3); - if (isProto3) { - RunValidInputTest( - ConformanceLevelToString(level) + rname + ".ProtobufInput." + test_name + - ".JsonOutput", level, input_protobuf, conformance::PROTOBUF, - equivalent_text_format, conformance::JSON, isProto3); - } -} - -void ConformanceTestSuite::RunValidBinaryProtobufTest( - const string& test_name, ConformanceLevel level, - const string& input_protobuf, bool isProto3) { - string rname = ".Proto3"; - if (!isProto3) { - rname = ".Proto2"; - } - RunValidBinaryInputTest( - ConformanceLevelToString(level) + rname + ".ProtobufInput." + test_name + - ".ProtobufOutput", level, input_protobuf, conformance::PROTOBUF, - input_protobuf, conformance::PROTOBUF, isProto3); -} - -void ConformanceTestSuite::RunValidProtobufTestWithMessage( - const string& test_name, ConformanceLevel level, const Message *input, - const string& equivalent_text_format, bool isProto3) { - RunValidProtobufTest(test_name, level, input->SerializeAsString(), equivalent_text_format, isProto3); -} - -// According to proto3 JSON specification, JSON serializers follow more strict -// rules than parsers (e.g., a serializer must serialize int32 values as JSON -// numbers while the parser is allowed to accept them as JSON strings). This -// method allows strict checking on a proto3 JSON serializer by inspecting -// the JSON output directly. -void ConformanceTestSuite::RunValidJsonTestWithValidator( - const string& test_name, ConformanceLevel level, const string& input_json, - const Validator& validator) { - ConformanceRequest request; - ConformanceResponse response; - request.set_json_payload(input_json); - request.set_requested_output_format(conformance::JSON); - request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3"); - - string effective_test_name = ConformanceLevelToString(level) + - ".Proto3.JsonInput." + test_name + ".Validator"; - - RunTest(effective_test_name, request, &response); - - if (response.result_case() == ConformanceResponse::kSkipped) { - ReportSkip(effective_test_name, request, response); - return; - } - - if (response.result_case() != ConformanceResponse::kJsonPayload) { - ReportFailure(effective_test_name, level, request, response, - "Expected JSON payload but got type %d.", - response.result_case()); - return; - } - Json::Reader reader; - Json::Value value; - if (!reader.parse(response.json_payload(), value)) { - ReportFailure(effective_test_name, level, request, response, - "JSON payload cannot be parsed as valid JSON: %s", - reader.getFormattedErrorMessages().c_str()); - return; - } - if (!validator(value)) { - ReportFailure(effective_test_name, level, request, response, - "JSON payload validation failed."); - return; - } - ReportSuccess(effective_test_name); -} - -void ConformanceTestSuite::ExpectParseFailureForJson( - const string& test_name, ConformanceLevel level, const string& input_json) { - ConformanceRequest request; - ConformanceResponse response; - request.set_json_payload(input_json); - request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3"); - string effective_test_name = - ConformanceLevelToString(level) + ".Proto3.JsonInput." + test_name; - - // We don't expect output, but if the program erroneously accepts the protobuf - // we let it send its response as this. We must not leave it unspecified. - request.set_requested_output_format(conformance::JSON); - - RunTest(effective_test_name, request, &response); - if (response.result_case() == ConformanceResponse::kParseError) { - ReportSuccess(effective_test_name); - } else if (response.result_case() == ConformanceResponse::kSkipped) { - ReportSkip(effective_test_name, request, response); - } else { - ReportFailure(effective_test_name, level, request, response, - "Should have failed to parse, but didn't."); - } -} - -void ConformanceTestSuite::ExpectSerializeFailureForJson( - const string& test_name, ConformanceLevel level, const string& text_format) { - TestAllTypesProto3 payload_message; - GOOGLE_CHECK( - TextFormat::ParseFromString(text_format, &payload_message)) - << "Failed to parse: " << text_format; - - ConformanceRequest request; - ConformanceResponse response; - request.set_protobuf_payload(payload_message.SerializeAsString()); - request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3"); - string effective_test_name = - ConformanceLevelToString(level) + "." + test_name + ".JsonOutput"; - request.set_requested_output_format(conformance::JSON); - - RunTest(effective_test_name, request, &response); - if (response.result_case() == ConformanceResponse::kSerializeError) { - ReportSuccess(effective_test_name); - } else if (response.result_case() == ConformanceResponse::kSkipped) { - ReportSkip(effective_test_name, request, response); - } else { - ReportFailure(effective_test_name, level, request, response, - "Should have failed to serialize, but didn't."); - } -} - -//TODO: proto2? -void ConformanceTestSuite::TestPrematureEOFForType(FieldDescriptor::Type type) { - // Incomplete values for each wire type. - static const string incompletes[6] = { - string("\x80"), // VARINT - string("abcdefg"), // 64BIT - string("\x80"), // DELIMITED (partial length) - string(), // START_GROUP (no value required) - string(), // END_GROUP (no value required) - string("abc") // 32BIT - }; - - const FieldDescriptor* field = GetFieldForType(type, false, true); - const FieldDescriptor* rep_field = GetFieldForType(type, true, true); - WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType( - static_cast(type)); - const string& incomplete = incompletes[wire_type]; - const string type_name = - UpperCase(string(".") + FieldDescriptor::TypeName(type)); - - ExpectParseFailureForProto( - tag(field->number(), wire_type), - "PrematureEofBeforeKnownNonRepeatedValue" + type_name, REQUIRED); - - ExpectParseFailureForProto( - tag(rep_field->number(), wire_type), - "PrematureEofBeforeKnownRepeatedValue" + type_name, REQUIRED); - - ExpectParseFailureForProto( - tag(UNKNOWN_FIELD, wire_type), - "PrematureEofBeforeUnknownValue" + type_name, REQUIRED); - - ExpectParseFailureForProto( - cat( tag(field->number(), wire_type), incomplete ), - "PrematureEofInsideKnownNonRepeatedValue" + type_name, REQUIRED); - - ExpectParseFailureForProto( - cat( tag(rep_field->number(), wire_type), incomplete ), - "PrematureEofInsideKnownRepeatedValue" + type_name, REQUIRED); - - ExpectParseFailureForProto( - cat( tag(UNKNOWN_FIELD, wire_type), incomplete ), - "PrematureEofInsideUnknownValue" + type_name, REQUIRED); - - if (wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - ExpectParseFailureForProto( - cat( tag(field->number(), wire_type), varint(1) ), - "PrematureEofInDelimitedDataForKnownNonRepeatedValue" + type_name, - REQUIRED); - - ExpectParseFailureForProto( - cat( tag(rep_field->number(), wire_type), varint(1) ), - "PrematureEofInDelimitedDataForKnownRepeatedValue" + type_name, - REQUIRED); - - // EOF in the middle of delimited data for unknown value. - ExpectParseFailureForProto( - cat( tag(UNKNOWN_FIELD, wire_type), varint(1) ), - "PrematureEofInDelimitedDataForUnknownValue" + type_name, REQUIRED); - - if (type == FieldDescriptor::TYPE_MESSAGE) { - // Submessage ends in the middle of a value. - string incomplete_submsg = - cat( tag(WireFormatLite::TYPE_INT32, WireFormatLite::WIRETYPE_VARINT), - incompletes[WireFormatLite::WIRETYPE_VARINT] ); - ExpectHardParseFailureForProto( - cat( tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - varint(incomplete_submsg.size()), - incomplete_submsg ), - "PrematureEofInSubmessageValue" + type_name, REQUIRED); - } - } else if (type != FieldDescriptor::TYPE_GROUP) { - // Non-delimited, non-group: eligible for packing. - - // Packed region ends in the middle of a value. - ExpectHardParseFailureForProto( - cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - varint(incomplete.size()), incomplete), - "PrematureEofInPackedFieldValue" + type_name, REQUIRED); - - // EOF in the middle of packed region. - ExpectParseFailureForProto( - cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - varint(1)), - "PrematureEofInPackedField" + type_name, REQUIRED); - } -} - -void ConformanceTestSuite::TestValidDataForType( - FieldDescriptor::Type type, - std::vector> values) { - for (int isProto3 = 0; isProto3 < 2; isProto3++) { - const string type_name = - UpperCase(string(".") + FieldDescriptor::TypeName(type)); - WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType( - static_cast(type)); - const FieldDescriptor* field = GetFieldForType(type, false, isProto3); - const FieldDescriptor* rep_field = GetFieldForType(type, true, isProto3); - - RunValidProtobufTest("ValidDataScalar" + type_name, REQUIRED, - cat(tag(field->number(), wire_type), values[0].first), - field->name() + ": " + values[0].second, isProto3); - - string proto; - string text = field->name() + ": " + values.back().second; - for (size_t i = 0; i < values.size(); i++) { - proto += cat(tag(field->number(), wire_type), values[i].first); - } - RunValidProtobufTest("RepeatedScalarSelectsLast" + type_name, REQUIRED, - proto, text, isProto3); - - proto.clear(); - text.clear(); - - for (size_t i = 0; i < values.size(); i++) { - proto += cat(tag(rep_field->number(), wire_type), values[i].first); - text += rep_field->name() + ": " + values[i].second + " "; - } - RunValidProtobufTest("ValidDataRepeated" + type_name, REQUIRED, - proto, text, isProto3); - } -} - -void ConformanceTestSuite::SetFailureList(const string& filename, - const std::vector& failure_list) { - failure_list_filename_ = filename; - expected_to_fail_.clear(); - std::copy(failure_list.begin(), failure_list.end(), - std::inserter(expected_to_fail_, expected_to_fail_.end())); -} - -bool ConformanceTestSuite::CheckSetEmpty(const std::set& set_to_check, - const std::string& write_to_file, - const std::string& msg) { +bool ConformanceTestSuite::CheckSetEmpty( + const std::set& set_to_check, + const std::string& write_to_file, + const std::string& msg) { if (set_to_check.empty()) { return true; } else { @@ -792,70 +342,33 @@ bool ConformanceTestSuite::CheckSetEmpty(const std::set& set_to_check, } } -// TODO: proto2? -void ConformanceTestSuite::TestIllegalTags() { - // field num 0 is illegal - string nullfield[] = { - "\1DEADBEEF", - "\2\1\1", - "\3\4", - "\5DEAD" - }; - for (int i = 0; i < 4; i++) { - string name = "IllegalZeroFieldNum_Case_0"; - name.back() += i; - ExpectParseFailureForProto(nullfield[i], name, REQUIRED); +string ConformanceTestSuite::WireFormatToString( + WireFormat wire_format) { + switch (wire_format) { + case conformance::PROTOBUF: + return "PROTOBUF"; + case conformance::JSON: + return "JSON"; + case conformance::JSPB: + return "JSPB"; + case conformance::TEXT_FORMAT: + return "TEXT_FORMAT"; + case conformance::UNSPECIFIED: + return "UNSPECIFIED"; + default: + GOOGLE_LOG(FATAL) << "unknown wire type: " + << wire_format; } -} -template -void ConformanceTestSuite::TestOneofMessage (MessageType &message, - bool isProto3) { - message.set_oneof_uint32(0); - RunValidProtobufTestWithMessage( - "OneofZeroUint32", RECOMMENDED, &message, "oneof_uint32: 0", isProto3); - message.mutable_oneof_nested_message()->set_a(0); - RunValidProtobufTestWithMessage( - "OneofZeroMessage", RECOMMENDED, &message, - isProto3 ? "oneof_nested_message: {}" : "oneof_nested_message: {a: 0}", - isProto3); - message.mutable_oneof_nested_message()->set_a(1); - RunValidProtobufTestWithMessage( - "OneofZeroMessageSetTwice", RECOMMENDED, &message, - "oneof_nested_message: {a: 1}", - isProto3); - message.set_oneof_string(""); - RunValidProtobufTestWithMessage( - "OneofZeroString", RECOMMENDED, &message, "oneof_string: \"\"", isProto3); - message.set_oneof_bytes(""); - RunValidProtobufTestWithMessage( - "OneofZeroBytes", RECOMMENDED, &message, "oneof_bytes: \"\"", isProto3); - message.set_oneof_bool(false); - RunValidProtobufTestWithMessage( - "OneofZeroBool", RECOMMENDED, &message, "oneof_bool: false", isProto3); - message.set_oneof_uint64(0); - RunValidProtobufTestWithMessage( - "OneofZeroUint64", RECOMMENDED, &message, "oneof_uint64: 0", isProto3); - message.set_oneof_float(0.0f); - RunValidProtobufTestWithMessage( - "OneofZeroFloat", RECOMMENDED, &message, "oneof_float: 0", isProto3); - message.set_oneof_double(0.0); - RunValidProtobufTestWithMessage( - "OneofZeroDouble", RECOMMENDED, &message, "oneof_double: 0", isProto3); - message.set_oneof_enum(MessageType::FOO); - RunValidProtobufTestWithMessage( - "OneofZeroEnum", RECOMMENDED, &message, "oneof_enum: FOO", isProto3); + return ""; } -template -void ConformanceTestSuite::TestUnknownMessage(MessageType& message, - bool isProto3) { - message.ParseFromString("\xA8\x1F\x01"); - RunValidBinaryProtobufTest("UnknownVarint", REQUIRED, - message.SerializeAsString(), isProto3); +void ConformanceTestSuite::AddExpectedFailedTest(const std::string& test_name) { + expected_to_fail_.insert(test_name); } bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner, - std::string* output) { + std::string* output, const string& filename, + conformance::FailureSet* failure_list) { runner_ = runner; successes_ = 0; expected_failures_ = 0; @@ -863,1677 +376,15 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner, test_names_.clear(); unexpected_failing_tests_.clear(); unexpected_succeeding_tests_.clear(); - type_resolver_.reset(NewTypeResolverForDescriptorPool( - kTypeUrlPrefix, DescriptorPool::generated_pool())); - type_url_ = GetTypeUrl(TestAllTypesProto3::descriptor()); output_ = "\nCONFORMANCE TEST BEGIN ====================================\n\n"; - for (int i = 1; i <= FieldDescriptor::MAX_TYPE; i++) { - if (i == FieldDescriptor::TYPE_GROUP) continue; - TestPrematureEOFForType(static_cast(i)); + failure_list_filename_ = filename; + expected_to_fail_.clear(); + for (const string& failure : failure_list->failure()) { + AddExpectedFailedTest(failure); } - - TestIllegalTags(); - - int64 kInt64Min = -9223372036854775808ULL; - int64 kInt64Max = 9223372036854775807ULL; - uint64 kUint64Max = 18446744073709551615ULL; - int32 kInt32Max = 2147483647; - int32 kInt32Min = -2147483648; - uint32 kUint32Max = 4294967295UL; - - TestValidDataForType(FieldDescriptor::TYPE_DOUBLE, { - {dbl(0.1), "0.1"}, - {dbl(1.7976931348623157e+308), "1.7976931348623157e+308"}, - {dbl(2.22507385850720138309e-308), "2.22507385850720138309e-308"} - }); - TestValidDataForType(FieldDescriptor::TYPE_FLOAT, { - {flt(0.1), "0.1"}, - {flt(1.00000075e-36), "1.00000075e-36"}, - {flt(3.402823e+38), "3.402823e+38"}, // 3.40282347e+38 - {flt(1.17549435e-38f), "1.17549435e-38"} - }); - TestValidDataForType(FieldDescriptor::TYPE_INT64, { - {varint(12345), "12345"}, - {varint(kInt64Max), std::to_string(kInt64Max)}, - {varint(kInt64Min), std::to_string(kInt64Min)} - }); - TestValidDataForType(FieldDescriptor::TYPE_UINT64, { - {varint(12345), "12345"}, - {varint(kUint64Max), std::to_string(kUint64Max)}, - {varint(0), "0"} - }); - TestValidDataForType(FieldDescriptor::TYPE_INT32, { - {varint(12345), "12345"}, - {longvarint(12345, 2), "12345"}, - {longvarint(12345, 7), "12345"}, - {varint(kInt32Max), std::to_string(kInt32Max)}, - {varint(kInt32Min), std::to_string(kInt32Min)}, - {varint(1LL << 33), std::to_string(static_cast(1LL << 33))}, - {varint((1LL << 33) - 1), - std::to_string(static_cast((1LL << 33) - 1))}, - }); - TestValidDataForType(FieldDescriptor::TYPE_UINT32, { - {varint(12345), "12345"}, - {longvarint(12345, 2), "12345"}, - {longvarint(12345, 7), "12345"}, - {varint(kUint32Max), std::to_string(kUint32Max)}, // UINT32_MAX - {varint(0), "0"}, - {varint(1LL << 33), std::to_string(static_cast(1LL << 33))}, - {varint((1LL << 33) - 1), - std::to_string(static_cast((1LL << 33) - 1))}, - }); - TestValidDataForType(FieldDescriptor::TYPE_FIXED64, { - {u64(12345), "12345"}, - {u64(kUint64Max), std::to_string(kUint64Max)}, - {u64(0), "0"} - }); - TestValidDataForType(FieldDescriptor::TYPE_FIXED32, { - {u32(12345), "12345"}, - {u32(kUint32Max), std::to_string(kUint32Max)}, // UINT32_MAX - {u32(0), "0"} - }); - TestValidDataForType(FieldDescriptor::TYPE_SFIXED64, { - {u64(12345), "12345"}, - {u64(kInt64Max), std::to_string(kInt64Max)}, - {u64(kInt64Min), std::to_string(kInt64Min)} - }); - TestValidDataForType(FieldDescriptor::TYPE_SFIXED32, { - {u32(12345), "12345"}, - {u32(kInt32Max), std::to_string(kInt32Max)}, - {u32(kInt32Min), std::to_string(kInt32Min)} - }); - TestValidDataForType(FieldDescriptor::TYPE_BOOL, { - {varint(1), "true"}, - {varint(0), "false"}, - {varint(12345678), "true"} - }); - TestValidDataForType(FieldDescriptor::TYPE_SINT32, { - {zz32(12345), "12345"}, - {zz32(kInt32Max), std::to_string(kInt32Max)}, - {zz32(kInt32Min), std::to_string(kInt32Min)} - }); - TestValidDataForType(FieldDescriptor::TYPE_SINT64, { - {zz64(12345), "12345"}, - {zz64(kInt64Max), std::to_string(kInt64Max)}, - {zz64(kInt64Min), std::to_string(kInt64Min)} - }); - - // TODO(haberman): - // TestValidDataForType(FieldDescriptor::TYPE_STRING - // TestValidDataForType(FieldDescriptor::TYPE_GROUP - // TestValidDataForType(FieldDescriptor::TYPE_MESSAGE - // TestValidDataForType(FieldDescriptor::TYPE_BYTES - // TestValidDataForType(FieldDescriptor::TYPE_ENUM - - RunValidJsonTest("HelloWorld", REQUIRED, - "{\"optionalString\":\"Hello, World!\"}", - "optional_string: 'Hello, World!'"); - - // NOTE: The spec for JSON support is still being sorted out, these may not - // all be correct. - // Test field name conventions. - RunValidJsonTest( - "FieldNameInSnakeCase", REQUIRED, - R"({ - "fieldname1": 1, - "fieldName2": 2, - "FieldName3": 3, - "fieldName4": 4 - })", - R"( - fieldname1: 1 - field_name2: 2 - _field_name3: 3 - field__name4_: 4 - )"); - RunValidJsonTest( - "FieldNameWithNumbers", REQUIRED, - R"({ - "field0name5": 5, - "field0Name6": 6 - })", - R"( - field0name5: 5 - field_0_name6: 6 - )"); - RunValidJsonTest( - "FieldNameWithMixedCases", REQUIRED, - R"({ - "fieldName7": 7, - "FieldName8": 8, - "fieldName9": 9, - "FieldName10": 10, - "FIELDNAME11": 11, - "FIELDName12": 12 - })", - R"( - fieldName7: 7 - FieldName8: 8 - field_Name9: 9 - Field_Name10: 10 - FIELD_NAME11: 11 - FIELD_name12: 12 - )"); - RunValidJsonTest( - "FieldNameWithDoubleUnderscores", RECOMMENDED, - R"({ - "FieldName13": 13, - "FieldName14": 14, - "fieldName15": 15, - "fieldName16": 16, - "fieldName17": 17, - "FieldName18": 18 - })", - R"( - __field_name13: 13 - __Field_name14: 14 - field__name15: 15 - field__Name16: 16 - field_name17__: 17 - Field_name18__: 18 - )"); - // Using the original proto field name in JSON is also allowed. - RunValidJsonTest( - "OriginalProtoFieldName", REQUIRED, - R"({ - "fieldname1": 1, - "field_name2": 2, - "_field_name3": 3, - "field__name4_": 4, - "field0name5": 5, - "field_0_name6": 6, - "fieldName7": 7, - "FieldName8": 8, - "field_Name9": 9, - "Field_Name10": 10, - "FIELD_NAME11": 11, - "FIELD_name12": 12, - "__field_name13": 13, - "__Field_name14": 14, - "field__name15": 15, - "field__Name16": 16, - "field_name17__": 17, - "Field_name18__": 18 - })", - R"( - fieldname1: 1 - field_name2: 2 - _field_name3: 3 - field__name4_: 4 - field0name5: 5 - field_0_name6: 6 - fieldName7: 7 - FieldName8: 8 - field_Name9: 9 - Field_Name10: 10 - FIELD_NAME11: 11 - FIELD_name12: 12 - __field_name13: 13 - __Field_name14: 14 - field__name15: 15 - field__Name16: 16 - field_name17__: 17 - Field_name18__: 18 - )"); - // Field names can be escaped. - RunValidJsonTest( - "FieldNameEscaped", REQUIRED, - R"({"fieldn\u0061me1": 1})", - "fieldname1: 1"); - // String ends with escape character. - ExpectParseFailureForJson( - "StringEndsWithEscapeChar", RECOMMENDED, - "{\"optionalString\": \"abc\\"); - // Field names must be quoted (or it's not valid JSON). - ExpectParseFailureForJson( - "FieldNameNotQuoted", RECOMMENDED, - "{fieldname1: 1}"); - // Trailing comma is not allowed (not valid JSON). - ExpectParseFailureForJson( - "TrailingCommaInAnObject", RECOMMENDED, - R"({"fieldname1":1,})"); - ExpectParseFailureForJson( - "TrailingCommaInAnObjectWithSpace", RECOMMENDED, - R"({"fieldname1":1 ,})"); - ExpectParseFailureForJson( - "TrailingCommaInAnObjectWithSpaceCommaSpace", RECOMMENDED, - R"({"fieldname1":1 , })"); - ExpectParseFailureForJson( - "TrailingCommaInAnObjectWithNewlines", RECOMMENDED, - R"({ - "fieldname1":1, - })"); - // JSON doesn't support comments. - ExpectParseFailureForJson( - "JsonWithComments", RECOMMENDED, - R"({ - // This is a comment. - "fieldname1": 1 - })"); - // JSON spec says whitespace doesn't matter, so try a few spacings to be sure. - RunValidJsonTest( - "OneLineNoSpaces", RECOMMENDED, - "{\"optionalInt32\":1,\"optionalInt64\":2}", - R"( - optional_int32: 1 - optional_int64: 2 - )"); - RunValidJsonTest( - "OneLineWithSpaces", RECOMMENDED, - "{ \"optionalInt32\" : 1 , \"optionalInt64\" : 2 }", - R"( - optional_int32: 1 - optional_int64: 2 - )"); - RunValidJsonTest( - "MultilineNoSpaces", RECOMMENDED, - "{\n\"optionalInt32\"\n:\n1\n,\n\"optionalInt64\"\n:\n2\n}", - R"( - optional_int32: 1 - optional_int64: 2 - )"); - RunValidJsonTest( - "MultilineWithSpaces", RECOMMENDED, - "{\n \"optionalInt32\" : 1\n ,\n \"optionalInt64\" : 2\n}\n", - R"( - optional_int32: 1 - optional_int64: 2 - )"); - // Missing comma between key/value pairs. - ExpectParseFailureForJson( - "MissingCommaOneLine", RECOMMENDED, - "{ \"optionalInt32\": 1 \"optionalInt64\": 2 }"); - ExpectParseFailureForJson( - "MissingCommaMultiline", RECOMMENDED, - "{\n \"optionalInt32\": 1\n \"optionalInt64\": 2\n}"); - // Duplicated field names are not allowed. - ExpectParseFailureForJson( - "FieldNameDuplicate", RECOMMENDED, - R"({ - "optionalNestedMessage": {a: 1}, - "optionalNestedMessage": {} - })"); - ExpectParseFailureForJson( - "FieldNameDuplicateDifferentCasing1", RECOMMENDED, - R"({ - "optional_nested_message": {a: 1}, - "optionalNestedMessage": {} - })"); - ExpectParseFailureForJson( - "FieldNameDuplicateDifferentCasing2", RECOMMENDED, - R"({ - "optionalNestedMessage": {a: 1}, - "optional_nested_message": {} - })"); - // Serializers should use lowerCamelCase by default. - RunValidJsonTestWithValidator( - "FieldNameInLowerCamelCase", REQUIRED, - R"({ - "fieldname1": 1, - "fieldName2": 2, - "FieldName3": 3, - "fieldName4": 4 - })", - [](const Json::Value& value) { - return value.isMember("fieldname1") && - value.isMember("fieldName2") && - value.isMember("FieldName3") && - value.isMember("fieldName4"); - }); - RunValidJsonTestWithValidator( - "FieldNameWithNumbers", REQUIRED, - R"({ - "field0name5": 5, - "field0Name6": 6 - })", - [](const Json::Value& value) { - return value.isMember("field0name5") && - value.isMember("field0Name6"); - }); - RunValidJsonTestWithValidator( - "FieldNameWithMixedCases", REQUIRED, - R"({ - "fieldName7": 7, - "FieldName8": 8, - "fieldName9": 9, - "FieldName10": 10, - "FIELDNAME11": 11, - "FIELDName12": 12 - })", - [](const Json::Value& value) { - return value.isMember("fieldName7") && - value.isMember("FieldName8") && - value.isMember("fieldName9") && - value.isMember("FieldName10") && - value.isMember("FIELDNAME11") && - value.isMember("FIELDName12"); - }); - RunValidJsonTestWithValidator( - "FieldNameWithDoubleUnderscores", RECOMMENDED, - R"({ - "FieldName13": 13, - "FieldName14": 14, - "fieldName15": 15, - "fieldName16": 16, - "fieldName17": 17, - "FieldName18": 18 - })", - [](const Json::Value& value) { - return value.isMember("FieldName13") && - value.isMember("FieldName14") && - value.isMember("fieldName15") && - value.isMember("fieldName16") && - value.isMember("fieldName17") && - value.isMember("FieldName18"); - }); - - // Integer fields. - RunValidJsonTest( - "Int32FieldMaxValue", REQUIRED, - R"({"optionalInt32": 2147483647})", - "optional_int32: 2147483647"); - RunValidJsonTest( - "Int32FieldMinValue", REQUIRED, - R"({"optionalInt32": -2147483648})", - "optional_int32: -2147483648"); - RunValidJsonTest( - "Uint32FieldMaxValue", REQUIRED, - R"({"optionalUint32": 4294967295})", - "optional_uint32: 4294967295"); - RunValidJsonTest( - "Int64FieldMaxValue", REQUIRED, - R"({"optionalInt64": "9223372036854775807"})", - "optional_int64: 9223372036854775807"); - RunValidJsonTest( - "Int64FieldMinValue", REQUIRED, - R"({"optionalInt64": "-9223372036854775808"})", - "optional_int64: -9223372036854775808"); - RunValidJsonTest( - "Uint64FieldMaxValue", REQUIRED, - R"({"optionalUint64": "18446744073709551615"})", - "optional_uint64: 18446744073709551615"); - // While not the largest Int64, this is the largest - // Int64 which can be exactly represented within an - // IEEE-754 64-bit float, which is the expected level - // of interoperability guarantee. Larger values may - // work in some implementations, but should not be - // relied upon. - RunValidJsonTest( - "Int64FieldMaxValueNotQuoted", REQUIRED, - R"({"optionalInt64": 9223372036854774784})", - "optional_int64: 9223372036854774784"); - RunValidJsonTest( - "Int64FieldMinValueNotQuoted", REQUIRED, - R"({"optionalInt64": -9223372036854775808})", - "optional_int64: -9223372036854775808"); - // Largest interoperable Uint64; see comment above - // for Int64FieldMaxValueNotQuoted. - RunValidJsonTest( - "Uint64FieldMaxValueNotQuoted", REQUIRED, - R"({"optionalUint64": 18446744073709549568})", - "optional_uint64: 18446744073709549568"); - // Values can be represented as JSON strings. - RunValidJsonTest( - "Int32FieldStringValue", REQUIRED, - R"({"optionalInt32": "2147483647"})", - "optional_int32: 2147483647"); - RunValidJsonTest( - "Int32FieldStringValueEscaped", REQUIRED, - R"({"optionalInt32": "2\u003147483647"})", - "optional_int32: 2147483647"); - - // Parsers reject out-of-bound integer values. - ExpectParseFailureForJson( - "Int32FieldTooLarge", REQUIRED, - R"({"optionalInt32": 2147483648})"); - ExpectParseFailureForJson( - "Int32FieldTooSmall", REQUIRED, - R"({"optionalInt32": -2147483649})"); - ExpectParseFailureForJson( - "Uint32FieldTooLarge", REQUIRED, - R"({"optionalUint32": 4294967296})"); - ExpectParseFailureForJson( - "Int64FieldTooLarge", REQUIRED, - R"({"optionalInt64": "9223372036854775808"})"); - ExpectParseFailureForJson( - "Int64FieldTooSmall", REQUIRED, - R"({"optionalInt64": "-9223372036854775809"})"); - ExpectParseFailureForJson( - "Uint64FieldTooLarge", REQUIRED, - R"({"optionalUint64": "18446744073709551616"})"); - // Parser reject non-integer numeric values as well. - ExpectParseFailureForJson( - "Int32FieldNotInteger", REQUIRED, - R"({"optionalInt32": 0.5})"); - ExpectParseFailureForJson( - "Uint32FieldNotInteger", REQUIRED, - R"({"optionalUint32": 0.5})"); - ExpectParseFailureForJson( - "Int64FieldNotInteger", REQUIRED, - R"({"optionalInt64": "0.5"})"); - ExpectParseFailureForJson( - "Uint64FieldNotInteger", REQUIRED, - R"({"optionalUint64": "0.5"})"); - - // Integers but represented as float values are accepted. - RunValidJsonTest( - "Int32FieldFloatTrailingZero", REQUIRED, - R"({"optionalInt32": 100000.000})", - "optional_int32: 100000"); - RunValidJsonTest( - "Int32FieldExponentialFormat", REQUIRED, - R"({"optionalInt32": 1e5})", - "optional_int32: 100000"); - RunValidJsonTest( - "Int32FieldMaxFloatValue", REQUIRED, - R"({"optionalInt32": 2.147483647e9})", - "optional_int32: 2147483647"); - RunValidJsonTest( - "Int32FieldMinFloatValue", REQUIRED, - R"({"optionalInt32": -2.147483648e9})", - "optional_int32: -2147483648"); - RunValidJsonTest( - "Uint32FieldMaxFloatValue", REQUIRED, - R"({"optionalUint32": 4.294967295e9})", - "optional_uint32: 4294967295"); - - // Parser reject non-numeric values. - ExpectParseFailureForJson( - "Int32FieldNotNumber", REQUIRED, - R"({"optionalInt32": "3x3"})"); - ExpectParseFailureForJson( - "Uint32FieldNotNumber", REQUIRED, - R"({"optionalUint32": "3x3"})"); - ExpectParseFailureForJson( - "Int64FieldNotNumber", REQUIRED, - R"({"optionalInt64": "3x3"})"); - ExpectParseFailureForJson( - "Uint64FieldNotNumber", REQUIRED, - R"({"optionalUint64": "3x3"})"); - // JSON does not allow "+" on numric values. - ExpectParseFailureForJson( - "Int32FieldPlusSign", REQUIRED, - R"({"optionalInt32": +1})"); - // JSON doesn't allow leading 0s. - ExpectParseFailureForJson( - "Int32FieldLeadingZero", REQUIRED, - R"({"optionalInt32": 01})"); - ExpectParseFailureForJson( - "Int32FieldNegativeWithLeadingZero", REQUIRED, - R"({"optionalInt32": -01})"); - // String values must follow the same syntax rule. Specifically leading - // or trailing spaces are not allowed. - ExpectParseFailureForJson( - "Int32FieldLeadingSpace", REQUIRED, - R"({"optionalInt32": " 1"})"); - ExpectParseFailureForJson( - "Int32FieldTrailingSpace", REQUIRED, - R"({"optionalInt32": "1 "})"); - - // 64-bit values are serialized as strings. - RunValidJsonTestWithValidator( - "Int64FieldBeString", RECOMMENDED, - R"({"optionalInt64": 1})", - [](const Json::Value& value) { - return value["optionalInt64"].type() == Json::stringValue && - value["optionalInt64"].asString() == "1"; - }); - RunValidJsonTestWithValidator( - "Uint64FieldBeString", RECOMMENDED, - R"({"optionalUint64": 1})", - [](const Json::Value& value) { - return value["optionalUint64"].type() == Json::stringValue && - value["optionalUint64"].asString() == "1"; - }); - - // Bool fields. - RunValidJsonTest( - "BoolFieldTrue", REQUIRED, - R"({"optionalBool":true})", - "optional_bool: true"); - RunValidJsonTest( - "BoolFieldFalse", REQUIRED, - R"({"optionalBool":false})", - "optional_bool: false"); - - // Other forms are not allowed. - ExpectParseFailureForJson( - "BoolFieldIntegerZero", RECOMMENDED, - R"({"optionalBool":0})"); - ExpectParseFailureForJson( - "BoolFieldIntegerOne", RECOMMENDED, - R"({"optionalBool":1})"); - ExpectParseFailureForJson( - "BoolFieldCamelCaseTrue", RECOMMENDED, - R"({"optionalBool":True})"); - ExpectParseFailureForJson( - "BoolFieldCamelCaseFalse", RECOMMENDED, - R"({"optionalBool":False})"); - ExpectParseFailureForJson( - "BoolFieldAllCapitalTrue", RECOMMENDED, - R"({"optionalBool":TRUE})"); - ExpectParseFailureForJson( - "BoolFieldAllCapitalFalse", RECOMMENDED, - R"({"optionalBool":FALSE})"); - ExpectParseFailureForJson( - "BoolFieldDoubleQuotedTrue", RECOMMENDED, - R"({"optionalBool":"true"})"); - ExpectParseFailureForJson( - "BoolFieldDoubleQuotedFalse", RECOMMENDED, - R"({"optionalBool":"false"})"); - - // Float fields. - RunValidJsonTest( - "FloatFieldMinPositiveValue", REQUIRED, - R"({"optionalFloat": 1.175494e-38})", - "optional_float: 1.175494e-38"); - RunValidJsonTest( - "FloatFieldMaxNegativeValue", REQUIRED, - R"({"optionalFloat": -1.175494e-38})", - "optional_float: -1.175494e-38"); - RunValidJsonTest( - "FloatFieldMaxPositiveValue", REQUIRED, - R"({"optionalFloat": 3.402823e+38})", - "optional_float: 3.402823e+38"); - RunValidJsonTest( - "FloatFieldMinNegativeValue", REQUIRED, - R"({"optionalFloat": 3.402823e+38})", - "optional_float: 3.402823e+38"); - // Values can be quoted. - RunValidJsonTest( - "FloatFieldQuotedValue", REQUIRED, - R"({"optionalFloat": "1"})", - "optional_float: 1"); - // Special values. - RunValidJsonTest( - "FloatFieldNan", REQUIRED, - R"({"optionalFloat": "NaN"})", - "optional_float: nan"); - RunValidJsonTest( - "FloatFieldInfinity", REQUIRED, - R"({"optionalFloat": "Infinity"})", - "optional_float: inf"); - RunValidJsonTest( - "FloatFieldNegativeInfinity", REQUIRED, - R"({"optionalFloat": "-Infinity"})", - "optional_float: -inf"); - // Non-cannonical Nan will be correctly normalized. - { - TestAllTypesProto3 message; - // IEEE floating-point standard 32-bit quiet NaN: - // 0111 1111 1xxx xxxx xxxx xxxx xxxx xxxx - message.set_optional_float( - WireFormatLite::DecodeFloat(0x7FA12345)); - RunValidJsonTestWithProtobufInput( - "FloatFieldNormalizeQuietNan", REQUIRED, message, - "optional_float: nan"); - // IEEE floating-point standard 64-bit signaling NaN: - // 1111 1111 1xxx xxxx xxxx xxxx xxxx xxxx - message.set_optional_float( - WireFormatLite::DecodeFloat(0xFFB54321)); - RunValidJsonTestWithProtobufInput( - "FloatFieldNormalizeSignalingNan", REQUIRED, message, - "optional_float: nan"); - } - - // Special values must be quoted. - ExpectParseFailureForJson( - "FloatFieldNanNotQuoted", RECOMMENDED, - R"({"optionalFloat": NaN})"); - ExpectParseFailureForJson( - "FloatFieldInfinityNotQuoted", RECOMMENDED, - R"({"optionalFloat": Infinity})"); - ExpectParseFailureForJson( - "FloatFieldNegativeInfinityNotQuoted", RECOMMENDED, - R"({"optionalFloat": -Infinity})"); - // Parsers should reject out-of-bound values. - ExpectParseFailureForJson( - "FloatFieldTooSmall", REQUIRED, - R"({"optionalFloat": -3.502823e+38})"); - ExpectParseFailureForJson( - "FloatFieldTooLarge", REQUIRED, - R"({"optionalFloat": 3.502823e+38})"); - - // Double fields. - RunValidJsonTest( - "DoubleFieldMinPositiveValue", REQUIRED, - R"({"optionalDouble": 2.22507e-308})", - "optional_double: 2.22507e-308"); - RunValidJsonTest( - "DoubleFieldMaxNegativeValue", REQUIRED, - R"({"optionalDouble": -2.22507e-308})", - "optional_double: -2.22507e-308"); - RunValidJsonTest( - "DoubleFieldMaxPositiveValue", REQUIRED, - R"({"optionalDouble": 1.79769e+308})", - "optional_double: 1.79769e+308"); - RunValidJsonTest( - "DoubleFieldMinNegativeValue", REQUIRED, - R"({"optionalDouble": -1.79769e+308})", - "optional_double: -1.79769e+308"); - // Values can be quoted. - RunValidJsonTest( - "DoubleFieldQuotedValue", REQUIRED, - R"({"optionalDouble": "1"})", - "optional_double: 1"); - // Speical values. - RunValidJsonTest( - "DoubleFieldNan", REQUIRED, - R"({"optionalDouble": "NaN"})", - "optional_double: nan"); - RunValidJsonTest( - "DoubleFieldInfinity", REQUIRED, - R"({"optionalDouble": "Infinity"})", - "optional_double: inf"); - RunValidJsonTest( - "DoubleFieldNegativeInfinity", REQUIRED, - R"({"optionalDouble": "-Infinity"})", - "optional_double: -inf"); - // Non-cannonical Nan will be correctly normalized. - { - TestAllTypesProto3 message; - message.set_optional_double( - WireFormatLite::DecodeDouble(0x7FFA123456789ABCLL)); - RunValidJsonTestWithProtobufInput( - "DoubleFieldNormalizeQuietNan", REQUIRED, message, - "optional_double: nan"); - message.set_optional_double( - WireFormatLite::DecodeDouble(0xFFFBCBA987654321LL)); - RunValidJsonTestWithProtobufInput( - "DoubleFieldNormalizeSignalingNan", REQUIRED, message, - "optional_double: nan"); - } - - // Special values must be quoted. - ExpectParseFailureForJson( - "DoubleFieldNanNotQuoted", RECOMMENDED, - R"({"optionalDouble": NaN})"); - ExpectParseFailureForJson( - "DoubleFieldInfinityNotQuoted", RECOMMENDED, - R"({"optionalDouble": Infinity})"); - ExpectParseFailureForJson( - "DoubleFieldNegativeInfinityNotQuoted", RECOMMENDED, - R"({"optionalDouble": -Infinity})"); - - // Parsers should reject out-of-bound values. - ExpectParseFailureForJson( - "DoubleFieldTooSmall", REQUIRED, - R"({"optionalDouble": -1.89769e+308})"); - ExpectParseFailureForJson( - "DoubleFieldTooLarge", REQUIRED, - R"({"optionalDouble": +1.89769e+308})"); - - // Enum fields. - RunValidJsonTest( - "EnumField", REQUIRED, - R"({"optionalNestedEnum": "FOO"})", - "optional_nested_enum: FOO"); - // Enum values must be represented as strings. - ExpectParseFailureForJson( - "EnumFieldNotQuoted", REQUIRED, - R"({"optionalNestedEnum": FOO})"); - // Numeric values are allowed. - RunValidJsonTest( - "EnumFieldNumericValueZero", REQUIRED, - R"({"optionalNestedEnum": 0})", - "optional_nested_enum: FOO"); - RunValidJsonTest( - "EnumFieldNumericValueNonZero", REQUIRED, - R"({"optionalNestedEnum": 1})", - "optional_nested_enum: BAR"); - // Unknown enum values are represented as numeric values. - RunValidJsonTestWithValidator( - "EnumFieldUnknownValue", REQUIRED, - R"({"optionalNestedEnum": 123})", - [](const Json::Value& value) { - return value["optionalNestedEnum"].type() == Json::intValue && - value["optionalNestedEnum"].asInt() == 123; - }); - - // String fields. - RunValidJsonTest( - "StringField", REQUIRED, - R"({"optionalString": "Hello world!"})", - "optional_string: \"Hello world!\""); - RunValidJsonTest( - "StringFieldUnicode", REQUIRED, - // Google in Chinese. - R"({"optionalString": "谷歌"})", - R"(optional_string: "谷歌")"); - RunValidJsonTest( - "StringFieldEscape", REQUIRED, - R"({"optionalString": "\"\\\/\b\f\n\r\t"})", - R"(optional_string: "\"\\/\b\f\n\r\t")"); - RunValidJsonTest( - "StringFieldUnicodeEscape", REQUIRED, - R"({"optionalString": "\u8C37\u6B4C"})", - R"(optional_string: "谷歌")"); - RunValidJsonTest( - "StringFieldUnicodeEscapeWithLowercaseHexLetters", REQUIRED, - R"({"optionalString": "\u8c37\u6b4c"})", - R"(optional_string: "谷歌")"); - RunValidJsonTest( - "StringFieldSurrogatePair", REQUIRED, - // The character is an emoji: grinning face with smiling eyes. 😁 - R"({"optionalString": "\uD83D\uDE01"})", - R"(optional_string: "\xF0\x9F\x98\x81")"); - - // Unicode escapes must start with "\u" (lowercase u). - ExpectParseFailureForJson( - "StringFieldUppercaseEscapeLetter", RECOMMENDED, - R"({"optionalString": "\U8C37\U6b4C"})"); - ExpectParseFailureForJson( - "StringFieldInvalidEscape", RECOMMENDED, - R"({"optionalString": "\uXXXX\u6B4C"})"); - ExpectParseFailureForJson( - "StringFieldUnterminatedEscape", RECOMMENDED, - R"({"optionalString": "\u8C3"})"); - ExpectParseFailureForJson( - "StringFieldUnpairedHighSurrogate", RECOMMENDED, - R"({"optionalString": "\uD800"})"); - ExpectParseFailureForJson( - "StringFieldUnpairedLowSurrogate", RECOMMENDED, - R"({"optionalString": "\uDC00"})"); - ExpectParseFailureForJson( - "StringFieldSurrogateInWrongOrder", RECOMMENDED, - R"({"optionalString": "\uDE01\uD83D"})"); - ExpectParseFailureForJson( - "StringFieldNotAString", REQUIRED, - R"({"optionalString": 12345})"); - - // Bytes fields. - RunValidJsonTest( - "BytesField", REQUIRED, - R"({"optionalBytes": "AQI="})", - R"(optional_bytes: "\x01\x02")"); - RunValidJsonTest( - "BytesFieldBase64Url", RECOMMENDED, - R"({"optionalBytes": "-_"})", - R"(optional_bytes: "\xfb")"); - - // Message fields. - RunValidJsonTest( - "MessageField", REQUIRED, - R"({"optionalNestedMessage": {"a": 1234}})", - "optional_nested_message: {a: 1234}"); - - // Oneof fields. - ExpectParseFailureForJson( - "OneofFieldDuplicate", REQUIRED, - R"({"oneofUint32": 1, "oneofString": "test"})"); - // Ensure zero values for oneof make it out/backs. - TestAllTypesProto3 messageProto3; - TestAllTypesProto2 messageProto2; - TestOneofMessage(messageProto3, true); - TestOneofMessage(messageProto2, false); - RunValidJsonTest( - "OneofZeroUint32", RECOMMENDED, - R"({"oneofUint32": 0})", "oneof_uint32: 0"); - RunValidJsonTest( - "OneofZeroMessage", RECOMMENDED, - R"({"oneofNestedMessage": {}})", "oneof_nested_message: {}"); - RunValidJsonTest( - "OneofZeroString", RECOMMENDED, - R"({"oneofString": ""})", "oneof_string: \"\""); - RunValidJsonTest( - "OneofZeroBytes", RECOMMENDED, - R"({"oneofBytes": ""})", "oneof_bytes: \"\""); - RunValidJsonTest( - "OneofZeroBool", RECOMMENDED, - R"({"oneofBool": false})", "oneof_bool: false"); - RunValidJsonTest( - "OneofZeroUint64", RECOMMENDED, - R"({"oneofUint64": 0})", "oneof_uint64: 0"); - RunValidJsonTest( - "OneofZeroFloat", RECOMMENDED, - R"({"oneofFloat": 0.0})", "oneof_float: 0"); - RunValidJsonTest( - "OneofZeroDouble", RECOMMENDED, - R"({"oneofDouble": 0.0})", "oneof_double: 0"); - RunValidJsonTest( - "OneofZeroEnum", RECOMMENDED, - R"({"oneofEnum":"FOO"})", "oneof_enum: FOO"); - - // Repeated fields. - RunValidJsonTest( - "PrimitiveRepeatedField", REQUIRED, - R"({"repeatedInt32": [1, 2, 3, 4]})", - "repeated_int32: [1, 2, 3, 4]"); - RunValidJsonTest( - "EnumRepeatedField", REQUIRED, - R"({"repeatedNestedEnum": ["FOO", "BAR", "BAZ"]})", - "repeated_nested_enum: [FOO, BAR, BAZ]"); - RunValidJsonTest( - "StringRepeatedField", REQUIRED, - R"({"repeatedString": ["Hello", "world"]})", - R"(repeated_string: ["Hello", "world"])"); - RunValidJsonTest( - "BytesRepeatedField", REQUIRED, - R"({"repeatedBytes": ["AAEC", "AQI="]})", - R"(repeated_bytes: ["\x00\x01\x02", "\x01\x02"])"); - RunValidJsonTest( - "MessageRepeatedField", REQUIRED, - R"({"repeatedNestedMessage": [{"a": 1234}, {"a": 5678}]})", - "repeated_nested_message: {a: 1234}" - "repeated_nested_message: {a: 5678}"); - - // Repeated field elements are of incorrect type. - ExpectParseFailureForJson( - "RepeatedFieldWrongElementTypeExpectingIntegersGotBool", REQUIRED, - R"({"repeatedInt32": [1, false, 3, 4]})"); - ExpectParseFailureForJson( - "RepeatedFieldWrongElementTypeExpectingIntegersGotString", REQUIRED, - R"({"repeatedInt32": [1, 2, "name", 4]})"); - ExpectParseFailureForJson( - "RepeatedFieldWrongElementTypeExpectingIntegersGotMessage", REQUIRED, - R"({"repeatedInt32": [1, 2, 3, {"a": 4}]})"); - ExpectParseFailureForJson( - "RepeatedFieldWrongElementTypeExpectingStringsGotInt", REQUIRED, - R"({"repeatedString": ["1", 2, "3", "4"]})"); - ExpectParseFailureForJson( - "RepeatedFieldWrongElementTypeExpectingStringsGotBool", REQUIRED, - R"({"repeatedString": ["1", "2", false, "4"]})"); - ExpectParseFailureForJson( - "RepeatedFieldWrongElementTypeExpectingStringsGotMessage", REQUIRED, - R"({"repeatedString": ["1", 2, "3", {"a": 4}]})"); - ExpectParseFailureForJson( - "RepeatedFieldWrongElementTypeExpectingMessagesGotInt", REQUIRED, - R"({"repeatedNestedMessage": [{"a": 1}, 2]})"); - ExpectParseFailureForJson( - "RepeatedFieldWrongElementTypeExpectingMessagesGotBool", REQUIRED, - R"({"repeatedNestedMessage": [{"a": 1}, false]})"); - ExpectParseFailureForJson( - "RepeatedFieldWrongElementTypeExpectingMessagesGotString", REQUIRED, - R"({"repeatedNestedMessage": [{"a": 1}, "2"]})"); - // Trailing comma in the repeated field is not allowed. - ExpectParseFailureForJson( - "RepeatedFieldTrailingComma", RECOMMENDED, - R"({"repeatedInt32": [1, 2, 3, 4,]})"); - ExpectParseFailureForJson( - "RepeatedFieldTrailingCommaWithSpace", RECOMMENDED, - "{\"repeatedInt32\": [1, 2, 3, 4 ,]}"); - ExpectParseFailureForJson( - "RepeatedFieldTrailingCommaWithSpaceCommaSpace", RECOMMENDED, - "{\"repeatedInt32\": [1, 2, 3, 4 , ]}"); - ExpectParseFailureForJson( - "RepeatedFieldTrailingCommaWithNewlines", RECOMMENDED, - "{\"repeatedInt32\": [\n 1,\n 2,\n 3,\n 4,\n]}"); - - // Map fields. - RunValidJsonTest( - "Int32MapField", REQUIRED, - R"({"mapInt32Int32": {"1": 2, "3": 4}})", - "map_int32_int32: {key: 1 value: 2}" - "map_int32_int32: {key: 3 value: 4}"); - ExpectParseFailureForJson( - "Int32MapFieldKeyNotQuoted", RECOMMENDED, - R"({"mapInt32Int32": {1: 2, 3: 4}})"); - RunValidJsonTest( - "Uint32MapField", REQUIRED, - R"({"mapUint32Uint32": {"1": 2, "3": 4}})", - "map_uint32_uint32: {key: 1 value: 2}" - "map_uint32_uint32: {key: 3 value: 4}"); - ExpectParseFailureForJson( - "Uint32MapFieldKeyNotQuoted", RECOMMENDED, - R"({"mapUint32Uint32": {1: 2, 3: 4}})"); - RunValidJsonTest( - "Int64MapField", REQUIRED, - R"({"mapInt64Int64": {"1": 2, "3": 4}})", - "map_int64_int64: {key: 1 value: 2}" - "map_int64_int64: {key: 3 value: 4}"); - ExpectParseFailureForJson( - "Int64MapFieldKeyNotQuoted", RECOMMENDED, - R"({"mapInt64Int64": {1: 2, 3: 4}})"); - RunValidJsonTest( - "Uint64MapField", REQUIRED, - R"({"mapUint64Uint64": {"1": 2, "3": 4}})", - "map_uint64_uint64: {key: 1 value: 2}" - "map_uint64_uint64: {key: 3 value: 4}"); - ExpectParseFailureForJson( - "Uint64MapFieldKeyNotQuoted", RECOMMENDED, - R"({"mapUint64Uint64": {1: 2, 3: 4}})"); - RunValidJsonTest( - "BoolMapField", REQUIRED, - R"({"mapBoolBool": {"true": true, "false": false}})", - "map_bool_bool: {key: true value: true}" - "map_bool_bool: {key: false value: false}"); - ExpectParseFailureForJson( - "BoolMapFieldKeyNotQuoted", RECOMMENDED, - R"({"mapBoolBool": {true: true, false: false}})"); - RunValidJsonTest( - "MessageMapField", REQUIRED, - R"({ - "mapStringNestedMessage": { - "hello": {"a": 1234}, - "world": {"a": 5678} - } - })", - R"( - map_string_nested_message: { - key: "hello" - value: {a: 1234} - } - map_string_nested_message: { - key: "world" - value: {a: 5678} - } - )"); - // Since Map keys are represented as JSON strings, escaping should be allowed. - RunValidJsonTest( - "Int32MapEscapedKey", REQUIRED, - R"({"mapInt32Int32": {"\u0031": 2}})", - "map_int32_int32: {key: 1 value: 2}"); - RunValidJsonTest( - "Int64MapEscapedKey", REQUIRED, - R"({"mapInt64Int64": {"\u0031": 2}})", - "map_int64_int64: {key: 1 value: 2}"); - RunValidJsonTest( - "BoolMapEscapedKey", REQUIRED, - R"({"mapBoolBool": {"tr\u0075e": true}})", - "map_bool_bool: {key: true value: true}"); - - // "null" is accepted for all fields types. - RunValidJsonTest( - "AllFieldAcceptNull", REQUIRED, - R"({ - "optionalInt32": null, - "optionalInt64": null, - "optionalUint32": null, - "optionalUint64": null, - "optionalSint32": null, - "optionalSint64": null, - "optionalFixed32": null, - "optionalFixed64": null, - "optionalSfixed32": null, - "optionalSfixed64": null, - "optionalFloat": null, - "optionalDouble": null, - "optionalBool": null, - "optionalString": null, - "optionalBytes": null, - "optionalNestedEnum": null, - "optionalNestedMessage": null, - "repeatedInt32": null, - "repeatedInt64": null, - "repeatedUint32": null, - "repeatedUint64": null, - "repeatedSint32": null, - "repeatedSint64": null, - "repeatedFixed32": null, - "repeatedFixed64": null, - "repeatedSfixed32": null, - "repeatedSfixed64": null, - "repeatedFloat": null, - "repeatedDouble": null, - "repeatedBool": null, - "repeatedString": null, - "repeatedBytes": null, - "repeatedNestedEnum": null, - "repeatedNestedMessage": null, - "mapInt32Int32": null, - "mapBoolBool": null, - "mapStringNestedMessage": null - })", - ""); - - // Repeated field elements cannot be null. - ExpectParseFailureForJson( - "RepeatedFieldPrimitiveElementIsNull", RECOMMENDED, - R"({"repeatedInt32": [1, null, 2]})"); - ExpectParseFailureForJson( - "RepeatedFieldMessageElementIsNull", RECOMMENDED, - R"({"repeatedNestedMessage": [{"a":1}, null, {"a":2}]})"); - // Map field keys cannot be null. - ExpectParseFailureForJson( - "MapFieldKeyIsNull", RECOMMENDED, - R"({"mapInt32Int32": {null: 1}})"); - // Map field values cannot be null. - ExpectParseFailureForJson( - "MapFieldValueIsNull", RECOMMENDED, - R"({"mapInt32Int32": {"0": null}})"); - - // http://www.rfc-editor.org/rfc/rfc7159.txt says strings have to use double - // quotes. - ExpectParseFailureForJson( - "StringFieldSingleQuoteKey", RECOMMENDED, - R"({'optionalString': "Hello world!"})"); - ExpectParseFailureForJson( - "StringFieldSingleQuoteValue", RECOMMENDED, - R"({"optionalString": 'Hello world!'})"); - ExpectParseFailureForJson( - "StringFieldSingleQuoteBoth", RECOMMENDED, - R"({'optionalString': 'Hello world!'})"); - - // Unknown fields. - { - TestAllTypesProto3 messageProto3; - TestAllTypesProto2 messageProto2; - //TODO(yilunchong): update this behavior when unknown field's behavior - // changed in open source. Also delete - // Required.Proto3.ProtobufInput.UnknownVarint.ProtobufOutput - // from failure list of python_cpp python java - TestUnknownMessage(messageProto3, true); - TestUnknownMessage(messageProto2, false); - } - - // Wrapper types. - RunValidJsonTest( - "OptionalBoolWrapper", REQUIRED, - R"({"optionalBoolWrapper": false})", - "optional_bool_wrapper: {value: false}"); - RunValidJsonTest( - "OptionalInt32Wrapper", REQUIRED, - R"({"optionalInt32Wrapper": 0})", - "optional_int32_wrapper: {value: 0}"); - RunValidJsonTest( - "OptionalUint32Wrapper", REQUIRED, - R"({"optionalUint32Wrapper": 0})", - "optional_uint32_wrapper: {value: 0}"); - RunValidJsonTest( - "OptionalInt64Wrapper", REQUIRED, - R"({"optionalInt64Wrapper": 0})", - "optional_int64_wrapper: {value: 0}"); - RunValidJsonTest( - "OptionalUint64Wrapper", REQUIRED, - R"({"optionalUint64Wrapper": 0})", - "optional_uint64_wrapper: {value: 0}"); - RunValidJsonTest( - "OptionalFloatWrapper", REQUIRED, - R"({"optionalFloatWrapper": 0})", - "optional_float_wrapper: {value: 0}"); - RunValidJsonTest( - "OptionalDoubleWrapper", REQUIRED, - R"({"optionalDoubleWrapper": 0})", - "optional_double_wrapper: {value: 0}"); - RunValidJsonTest( - "OptionalStringWrapper", REQUIRED, - R"({"optionalStringWrapper": ""})", - R"(optional_string_wrapper: {value: ""})"); - RunValidJsonTest( - "OptionalBytesWrapper", REQUIRED, - R"({"optionalBytesWrapper": ""})", - R"(optional_bytes_wrapper: {value: ""})"); - RunValidJsonTest( - "OptionalWrapperTypesWithNonDefaultValue", REQUIRED, - R"({ - "optionalBoolWrapper": true, - "optionalInt32Wrapper": 1, - "optionalUint32Wrapper": 1, - "optionalInt64Wrapper": "1", - "optionalUint64Wrapper": "1", - "optionalFloatWrapper": 1, - "optionalDoubleWrapper": 1, - "optionalStringWrapper": "1", - "optionalBytesWrapper": "AQI=" - })", - R"( - optional_bool_wrapper: {value: true} - optional_int32_wrapper: {value: 1} - optional_uint32_wrapper: {value: 1} - optional_int64_wrapper: {value: 1} - optional_uint64_wrapper: {value: 1} - optional_float_wrapper: {value: 1} - optional_double_wrapper: {value: 1} - optional_string_wrapper: {value: "1"} - optional_bytes_wrapper: {value: "\x01\x02"} - )"); - RunValidJsonTest( - "RepeatedBoolWrapper", REQUIRED, - R"({"repeatedBoolWrapper": [true, false]})", - "repeated_bool_wrapper: {value: true}" - "repeated_bool_wrapper: {value: false}"); - RunValidJsonTest( - "RepeatedInt32Wrapper", REQUIRED, - R"({"repeatedInt32Wrapper": [0, 1]})", - "repeated_int32_wrapper: {value: 0}" - "repeated_int32_wrapper: {value: 1}"); - RunValidJsonTest( - "RepeatedUint32Wrapper", REQUIRED, - R"({"repeatedUint32Wrapper": [0, 1]})", - "repeated_uint32_wrapper: {value: 0}" - "repeated_uint32_wrapper: {value: 1}"); - RunValidJsonTest( - "RepeatedInt64Wrapper", REQUIRED, - R"({"repeatedInt64Wrapper": [0, 1]})", - "repeated_int64_wrapper: {value: 0}" - "repeated_int64_wrapper: {value: 1}"); - RunValidJsonTest( - "RepeatedUint64Wrapper", REQUIRED, - R"({"repeatedUint64Wrapper": [0, 1]})", - "repeated_uint64_wrapper: {value: 0}" - "repeated_uint64_wrapper: {value: 1}"); - RunValidJsonTest( - "RepeatedFloatWrapper", REQUIRED, - R"({"repeatedFloatWrapper": [0, 1]})", - "repeated_float_wrapper: {value: 0}" - "repeated_float_wrapper: {value: 1}"); - RunValidJsonTest( - "RepeatedDoubleWrapper", REQUIRED, - R"({"repeatedDoubleWrapper": [0, 1]})", - "repeated_double_wrapper: {value: 0}" - "repeated_double_wrapper: {value: 1}"); - RunValidJsonTest( - "RepeatedStringWrapper", REQUIRED, - R"({"repeatedStringWrapper": ["", "AQI="]})", - R"( - repeated_string_wrapper: {value: ""} - repeated_string_wrapper: {value: "AQI="} - )"); - RunValidJsonTest( - "RepeatedBytesWrapper", REQUIRED, - R"({"repeatedBytesWrapper": ["", "AQI="]})", - R"( - repeated_bytes_wrapper: {value: ""} - repeated_bytes_wrapper: {value: "\x01\x02"} - )"); - RunValidJsonTest( - "WrapperTypesWithNullValue", REQUIRED, - R"({ - "optionalBoolWrapper": null, - "optionalInt32Wrapper": null, - "optionalUint32Wrapper": null, - "optionalInt64Wrapper": null, - "optionalUint64Wrapper": null, - "optionalFloatWrapper": null, - "optionalDoubleWrapper": null, - "optionalStringWrapper": null, - "optionalBytesWrapper": null, - "repeatedBoolWrapper": null, - "repeatedInt32Wrapper": null, - "repeatedUint32Wrapper": null, - "repeatedInt64Wrapper": null, - "repeatedUint64Wrapper": null, - "repeatedFloatWrapper": null, - "repeatedDoubleWrapper": null, - "repeatedStringWrapper": null, - "repeatedBytesWrapper": null - })", - ""); - - // Duration - RunValidJsonTest( - "DurationMinValue", REQUIRED, - R"({"optionalDuration": "-315576000000.999999999s"})", - "optional_duration: {seconds: -315576000000 nanos: -999999999}"); - RunValidJsonTest( - "DurationMaxValue", REQUIRED, - R"({"optionalDuration": "315576000000.999999999s"})", - "optional_duration: {seconds: 315576000000 nanos: 999999999}"); - RunValidJsonTest( - "DurationRepeatedValue", REQUIRED, - R"({"repeatedDuration": ["1.5s", "-1.5s"]})", - "repeated_duration: {seconds: 1 nanos: 500000000}" - "repeated_duration: {seconds: -1 nanos: -500000000}"); - RunValidJsonTest( - "DurationNull", REQUIRED, - R"({"optionalDuration": null})", - ""); - - ExpectParseFailureForJson( - "DurationMissingS", REQUIRED, - R"({"optionalDuration": "1"})"); - ExpectParseFailureForJson( - "DurationJsonInputTooSmall", REQUIRED, - R"({"optionalDuration": "-315576000001.000000000s"})"); - ExpectParseFailureForJson( - "DurationJsonInputTooLarge", REQUIRED, - R"({"optionalDuration": "315576000001.000000000s"})"); - ExpectSerializeFailureForJson( - "DurationProtoInputTooSmall", REQUIRED, - "optional_duration: {seconds: -315576000001 nanos: 0}"); - ExpectSerializeFailureForJson( - "DurationProtoInputTooLarge", REQUIRED, - "optional_duration: {seconds: 315576000001 nanos: 0}"); - - RunValidJsonTestWithValidator( - "DurationHasZeroFractionalDigit", RECOMMENDED, - R"({"optionalDuration": "1.000000000s"})", - [](const Json::Value& value) { - return value["optionalDuration"].asString() == "1s"; - }); - RunValidJsonTestWithValidator( - "DurationHas3FractionalDigits", RECOMMENDED, - R"({"optionalDuration": "1.010000000s"})", - [](const Json::Value& value) { - return value["optionalDuration"].asString() == "1.010s"; - }); - RunValidJsonTestWithValidator( - "DurationHas6FractionalDigits", RECOMMENDED, - R"({"optionalDuration": "1.000010000s"})", - [](const Json::Value& value) { - return value["optionalDuration"].asString() == "1.000010s"; - }); - RunValidJsonTestWithValidator( - "DurationHas9FractionalDigits", RECOMMENDED, - R"({"optionalDuration": "1.000000010s"})", - [](const Json::Value& value) { - return value["optionalDuration"].asString() == "1.000000010s"; - }); - - // Timestamp - RunValidJsonTest( - "TimestampMinValue", REQUIRED, - R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})", - "optional_timestamp: {seconds: -62135596800}"); - RunValidJsonTest( - "TimestampMaxValue", REQUIRED, - R"({"optionalTimestamp": "9999-12-31T23:59:59.999999999Z"})", - "optional_timestamp: {seconds: 253402300799 nanos: 999999999}"); - RunValidJsonTest( - "TimestampRepeatedValue", REQUIRED, - R"({ - "repeatedTimestamp": [ - "0001-01-01T00:00:00Z", - "9999-12-31T23:59:59.999999999Z" - ] - })", - "repeated_timestamp: {seconds: -62135596800}" - "repeated_timestamp: {seconds: 253402300799 nanos: 999999999}"); - RunValidJsonTest( - "TimestampWithPositiveOffset", REQUIRED, - R"({"optionalTimestamp": "1970-01-01T08:00:00+08:00"})", - "optional_timestamp: {seconds: 0}"); - RunValidJsonTest( - "TimestampWithNegativeOffset", REQUIRED, - R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})", - "optional_timestamp: {seconds: 0}"); - RunValidJsonTest( - "TimestampNull", REQUIRED, - R"({"optionalTimestamp": null})", - ""); - - ExpectParseFailureForJson( - "TimestampJsonInputTooSmall", REQUIRED, - R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})"); - ExpectParseFailureForJson( - "TimestampJsonInputTooLarge", REQUIRED, - R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})"); - ExpectParseFailureForJson( - "TimestampJsonInputMissingZ", REQUIRED, - R"({"optionalTimestamp": "0001-01-01T00:00:00"})"); - ExpectParseFailureForJson( - "TimestampJsonInputMissingT", REQUIRED, - R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})"); - ExpectParseFailureForJson( - "TimestampJsonInputLowercaseZ", REQUIRED, - R"({"optionalTimestamp": "0001-01-01T00:00:00z"})"); - ExpectParseFailureForJson( - "TimestampJsonInputLowercaseT", REQUIRED, - R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})"); - ExpectSerializeFailureForJson( - "TimestampProtoInputTooSmall", REQUIRED, - "optional_timestamp: {seconds: -62135596801}"); - ExpectSerializeFailureForJson( - "TimestampProtoInputTooLarge", REQUIRED, - "optional_timestamp: {seconds: 253402300800}"); - RunValidJsonTestWithValidator( - "TimestampZeroNormalized", RECOMMENDED, - R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})", - [](const Json::Value& value) { - return value["optionalTimestamp"].asString() == - "1970-01-01T00:00:00Z"; - }); - RunValidJsonTestWithValidator( - "TimestampHasZeroFractionalDigit", RECOMMENDED, - R"({"optionalTimestamp": "1970-01-01T00:00:00.000000000Z"})", - [](const Json::Value& value) { - return value["optionalTimestamp"].asString() == - "1970-01-01T00:00:00Z"; - }); - RunValidJsonTestWithValidator( - "TimestampHas3FractionalDigits", RECOMMENDED, - R"({"optionalTimestamp": "1970-01-01T00:00:00.010000000Z"})", - [](const Json::Value& value) { - return value["optionalTimestamp"].asString() == - "1970-01-01T00:00:00.010Z"; - }); - RunValidJsonTestWithValidator( - "TimestampHas6FractionalDigits", RECOMMENDED, - R"({"optionalTimestamp": "1970-01-01T00:00:00.000010000Z"})", - [](const Json::Value& value) { - return value["optionalTimestamp"].asString() == - "1970-01-01T00:00:00.000010Z"; - }); - RunValidJsonTestWithValidator( - "TimestampHas9FractionalDigits", RECOMMENDED, - R"({"optionalTimestamp": "1970-01-01T00:00:00.000000010Z"})", - [](const Json::Value& value) { - return value["optionalTimestamp"].asString() == - "1970-01-01T00:00:00.000000010Z"; - }); - - // FieldMask - RunValidJsonTest( - "FieldMask", REQUIRED, - R"({"optionalFieldMask": "foo,barBaz"})", - R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})"); - ExpectParseFailureForJson( - "FieldMaskInvalidCharacter", RECOMMENDED, - R"({"optionalFieldMask": "foo,bar_bar"})"); - ExpectSerializeFailureForJson( - "FieldMaskPathsDontRoundTrip", RECOMMENDED, - R"(optional_field_mask: {paths: "fooBar"})"); - ExpectSerializeFailureForJson( - "FieldMaskNumbersDontRoundTrip", RECOMMENDED, - R"(optional_field_mask: {paths: "foo_3_bar"})"); - ExpectSerializeFailureForJson( - "FieldMaskTooManyUnderscore", RECOMMENDED, - R"(optional_field_mask: {paths: "foo__bar"})"); - - // Struct - RunValidJsonTest( - "Struct", REQUIRED, - R"({ - "optionalStruct": { - "nullValue": null, - "intValue": 1234, - "boolValue": true, - "doubleValue": 1234.5678, - "stringValue": "Hello world!", - "listValue": [1234, "5678"], - "objectValue": { - "value": 0 - } - } - })", - R"( - optional_struct: { - fields: { - key: "nullValue" - value: {null_value: NULL_VALUE} - } - fields: { - key: "intValue" - value: {number_value: 1234} - } - fields: { - key: "boolValue" - value: {bool_value: true} - } - fields: { - key: "doubleValue" - value: {number_value: 1234.5678} - } - fields: { - key: "stringValue" - value: {string_value: "Hello world!"} - } - fields: { - key: "listValue" - value: { - list_value: { - values: { - number_value: 1234 - } - values: { - string_value: "5678" - } - } - } - } - fields: { - key: "objectValue" - value: { - struct_value: { - fields: { - key: "value" - value: { - number_value: 0 - } - } - } - } - } - } - )"); - // Value - RunValidJsonTest( - "ValueAcceptInteger", REQUIRED, - R"({"optionalValue": 1})", - "optional_value: { number_value: 1}"); - RunValidJsonTest( - "ValueAcceptFloat", REQUIRED, - R"({"optionalValue": 1.5})", - "optional_value: { number_value: 1.5}"); - RunValidJsonTest( - "ValueAcceptBool", REQUIRED, - R"({"optionalValue": false})", - "optional_value: { bool_value: false}"); - RunValidJsonTest( - "ValueAcceptNull", REQUIRED, - R"({"optionalValue": null})", - "optional_value: { null_value: NULL_VALUE}"); - RunValidJsonTest( - "ValueAcceptString", REQUIRED, - R"({"optionalValue": "hello"})", - R"(optional_value: { string_value: "hello"})"); - RunValidJsonTest( - "ValueAcceptList", REQUIRED, - R"({"optionalValue": [0, "hello"]})", - R"( - optional_value: { - list_value: { - values: { - number_value: 0 - } - values: { - string_value: "hello" - } - } - } - )"); - RunValidJsonTest( - "ValueAcceptListWithNull", REQUIRED, - R"({"optionalValue": ["x", null, "y"]})", - R"( - optional_value: { - list_value: { - values: { - string_value: "x" - } - values: { - null_value: NULL_VALUE - } - values: { - string_value: "y" - } - } - } - )"); - RunValidJsonTest( - "ValueAcceptObject", REQUIRED, - R"({"optionalValue": {"value": 1}})", - R"( - optional_value: { - struct_value: { - fields: { - key: "value" - value: { - number_value: 1 - } - } - } - } - )"); - - // Any - RunValidJsonTest( - "Any", REQUIRED, - R"({ - "optionalAny": { - "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3", - "optionalInt32": 12345 - } - })", - R"( - optional_any: { - [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] { - optional_int32: 12345 - } - } - )"); - RunValidJsonTest( - "AnyNested", REQUIRED, - R"({ - "optionalAny": { - "@type": "type.googleapis.com/google.protobuf.Any", - "value": { - "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3", - "optionalInt32": 12345 - } - } - })", - R"( - optional_any: { - [type.googleapis.com/google.protobuf.Any] { - [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] { - optional_int32: 12345 - } - } - } - )"); - // The special "@type" tag is not required to appear first. - RunValidJsonTest( - "AnyUnorderedTypeTag", REQUIRED, - R"({ - "optionalAny": { - "optionalInt32": 12345, - "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3" - } - })", - R"( - optional_any: { - [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] { - optional_int32: 12345 - } - } - )"); - // Well-known types in Any. - RunValidJsonTest( - "AnyWithInt32ValueWrapper", REQUIRED, - R"({ - "optionalAny": { - "@type": "type.googleapis.com/google.protobuf.Int32Value", - "value": 12345 - } - })", - R"( - optional_any: { - [type.googleapis.com/google.protobuf.Int32Value] { - value: 12345 - } - } - )"); - RunValidJsonTest( - "AnyWithDuration", REQUIRED, - R"({ - "optionalAny": { - "@type": "type.googleapis.com/google.protobuf.Duration", - "value": "1.5s" - } - })", - R"( - optional_any: { - [type.googleapis.com/google.protobuf.Duration] { - seconds: 1 - nanos: 500000000 - } - } - )"); - RunValidJsonTest( - "AnyWithTimestamp", REQUIRED, - R"({ - "optionalAny": { - "@type": "type.googleapis.com/google.protobuf.Timestamp", - "value": "1970-01-01T00:00:00Z" - } - })", - R"( - optional_any: { - [type.googleapis.com/google.protobuf.Timestamp] { - seconds: 0 - nanos: 0 - } - } - )"); - RunValidJsonTest( - "AnyWithFieldMask", REQUIRED, - R"({ - "optionalAny": { - "@type": "type.googleapis.com/google.protobuf.FieldMask", - "value": "foo,barBaz" - } - })", - R"( - optional_any: { - [type.googleapis.com/google.protobuf.FieldMask] { - paths: ["foo", "bar_baz"] - } - } - )"); - RunValidJsonTest( - "AnyWithStruct", REQUIRED, - R"({ - "optionalAny": { - "@type": "type.googleapis.com/google.protobuf.Struct", - "value": { - "foo": 1 - } - } - })", - R"( - optional_any: { - [type.googleapis.com/google.protobuf.Struct] { - fields: { - key: "foo" - value: { - number_value: 1 - } - } - } - } - )"); - RunValidJsonTest( - "AnyWithValueForJsonObject", REQUIRED, - R"({ - "optionalAny": { - "@type": "type.googleapis.com/google.protobuf.Value", - "value": { - "foo": 1 - } - } - })", - R"( - optional_any: { - [type.googleapis.com/google.protobuf.Value] { - struct_value: { - fields: { - key: "foo" - value: { - number_value: 1 - } - } - } - } - } - )"); - RunValidJsonTest( - "AnyWithValueForInteger", REQUIRED, - R"({ - "optionalAny": { - "@type": "type.googleapis.com/google.protobuf.Value", - "value": 1 - } - })", - R"( - optional_any: { - [type.googleapis.com/google.protobuf.Value] { - number_value: 1 - } - } - )"); + RunSuiteImpl(); bool ok = true; if (!CheckSetEmpty(expected_to_fail_, "nonexistent_tests.txt", diff --git a/third_party/protobuf/conformance/conformance_test.h b/third_party/protobuf/conformance/conformance_test.h index 2649f8b2..4d741e7f 100644 --- a/third_party/protobuf/conformance/conformance_test.h +++ b/third_party/protobuf/conformance/conformance_test.h @@ -40,11 +40,13 @@ #include #include + +#include #include #include #include -#include "third_party/jsoncpp/json.h" +#include "conformance.pb.h" namespace conformance { class ConformanceRequest; @@ -60,6 +62,8 @@ class TestAllTypesProto3; namespace google { namespace protobuf { +class ConformanceTestSuite; + class ConformanceTestRunner { public: virtual ~ConformanceTestRunner() {} @@ -76,39 +80,74 @@ class ConformanceTestRunner { std::string* output) = 0; }; +// Test runner that spawns the process being tested and communicates with it +// over a pipe. +class ForkPipeRunner : public ConformanceTestRunner { + public: + // Note: Run() doesn't take ownership of the pointers inside suites. + static int Run(int argc, char *argv[], + const std::vector& suites); + + ForkPipeRunner(const std::string &executable) + : child_pid_(-1), executable_(executable) {} + + virtual ~ForkPipeRunner() {} + + void RunTest(const std::string& test_name, + const std::string& request, + std::string* response); + + private: + void SpawnTestProgram(); + + void CheckedWrite(int fd, const void *buf, size_t len); + bool TryRead(int fd, void *buf, size_t len); + void CheckedRead(int fd, void *buf, size_t len); + + int write_fd_; + int read_fd_; + pid_t child_pid_; + std::string executable_; + std::string current_test_name_; +}; + // Class representing the test suite itself. To run it, implement your own -// class derived from ConformanceTestRunner and then write code like: +// class derived from ConformanceTestRunner, class derived from +// ConformanceTestSuite and then write code like: +// +// class MyConformanceTestSuite : public ConformanceTestSuite { +// public: +// void RunSuiteImpl() { +// // INSERT ACTURAL TESTS. +// } +// }; // // class MyConformanceTestRunner : public ConformanceTestRunner { // public: +// static int Run(int argc, char *argv[], +// ConformanceTestSuite* suite); +// +// private: // virtual void RunTest(...) { // // INSERT YOUR FRAMEWORK-SPECIFIC CODE HERE. // } // }; // // int main() { -// MyConformanceTestRunner runner; -// google::protobuf::ConformanceTestSuite suite; -// -// std::string output; -// suite.RunSuite(&runner, &output); +// MyConformanceTestSuite suite; +// MyConformanceTestRunner::Run(argc, argv, &suite); // } // class ConformanceTestSuite { public: - ConformanceTestSuite() : verbose_(false), enforce_recommended_(false) {} + ConformanceTestSuite() + : verbose_(false), + enforce_recommended_(false), + failure_list_flag_name_("--failure_list") {} + virtual ~ConformanceTestSuite() {} void SetVerbose(bool verbose) { verbose_ = verbose; } - // Sets the list of tests that are expected to fail when RunSuite() is called. - // RunSuite() will fail unless the set of failing tests is exactly the same - // as this list. - // - // The filename here is *only* used to create/format useful error messages for - // how to update the failure list. We do NOT read this file at all. - void SetFailureList(const std::string& filename, - const std::vector& failure_list); - // Whether to require the testee to pass RECOMMENDED tests. By default failing // a RECOMMENDED test case will not fail the entire suite but will only // generated a warning. If this flag is set to true, RECOMMENDED tests will @@ -121,15 +160,28 @@ class ConformanceTestSuite { enforce_recommended_ = value; } + // Gets the flag name to the failure list file. + // By default, this would return --failure_list + string GetFailureListFlagName() { + return failure_list_flag_name_; + } + + void SetFailureListFlagName(const std::string& failure_list_flag_name) { + failure_list_flag_name_ = failure_list_flag_name; + } + // Run all the conformance tests against the given test runner. // Test output will be stored in "output". // // Returns true if the set of failing tests was exactly the same as the - // failure list. If SetFailureList() was not called, returns true if all - // tests passed. - bool RunSuite(ConformanceTestRunner* runner, std::string* output); + // failure list. + // The filename here is *only* used to create/format useful error messages for + // how to update the failure list. We do NOT read this file at all. + bool RunSuite(ConformanceTestRunner* runner, std::string* output, + const std::string& filename, + conformance::FailureSet* failure_list); - private: + protected: // Test cases are classified into a few categories: // REQUIRED: the test case must be passed for an implementation to be // interoperable with other implementations. For example, a @@ -146,7 +198,70 @@ class ConformanceTestSuite { REQUIRED = 0, RECOMMENDED = 1, }; - string ConformanceLevelToString(ConformanceLevel level); + + class ConformanceRequestSetting { + public: + ConformanceRequestSetting( + ConformanceLevel level, + conformance::WireFormat input_format, + conformance::WireFormat output_format, + conformance::TestCategory test_category, + const Message& prototype_message, + const string& test_name, const string& input); + virtual ~ConformanceRequestSetting() {} + + Message* GetTestMessage() const; + + string GetTestName() const; + + const conformance::ConformanceRequest& GetRequest() const { + return request_; + } + + const ConformanceLevel GetLevel() const { + return level_; + } + + string ConformanceLevelToString(ConformanceLevel level) const; + + void SetPrintUnknownFields(bool print_unknown_fields) { + request_.set_print_unknown_fields(true); + } + + void SetPrototypeMessageForCompare(const Message& message) { + prototype_message_for_compare_.reset(message.New()); + } + + protected: + virtual string InputFormatString(conformance::WireFormat format) const; + virtual string OutputFormatString(conformance::WireFormat format) const; + conformance::ConformanceRequest request_; + + private: + ConformanceLevel level_; + ::conformance::WireFormat input_format_; + ::conformance::WireFormat output_format_; + const Message& prototype_message_; + std::unique_ptr prototype_message_for_compare_; + string test_name_; + }; + + bool CheckSetEmpty(const std::set& set_to_check, + const std::string& write_to_file, const std::string& msg); + string WireFormatToString(conformance::WireFormat wire_format); + + // Parse payload in the response to the given message. Returns true on + // success. + virtual bool ParseResponse( + const conformance::ConformanceResponse& response, + const ConformanceRequestSetting& setting, + Message* test_message) = 0; + + void VerifyResponse( + const ConformanceRequestSetting& setting, + const string& equivalent_wire_format, + const conformance::ConformanceResponse& response, + bool need_report_success); void ReportSuccess(const std::string& test_name); void ReportFailure(const string& test_name, @@ -157,86 +272,27 @@ class ConformanceTestSuite { void ReportSkip(const string& test_name, const conformance::ConformanceRequest& request, const conformance::ConformanceResponse& response); + + void RunValidInputTest(const ConformanceRequestSetting& setting, + const string& equivalent_text_format); + void RunValidBinaryInputTest(const ConformanceRequestSetting& setting, + const string& equivalent_wire_format); + void RunTest(const std::string& test_name, const conformance::ConformanceRequest& request, conformance::ConformanceResponse* response); - void RunValidInputTest(const string& test_name, - ConformanceLevel level, - const string& input, - conformance::WireFormat input_format, - const string& equivalent_text_format, - conformance::WireFormat requested_output, - bool isProto3); - void RunValidBinaryInputTest(const string& test_name, - ConformanceLevel level, - const string& input, - conformance::WireFormat input_format, - const string& equivalent_wire_format, - conformance::WireFormat requested_output, - bool isProto3); - void RunValidJsonTest(const string& test_name, - ConformanceLevel level, - const string& input_json, - const string& equivalent_text_format); - void RunValidJsonTestWithProtobufInput( - const string& test_name, - ConformanceLevel level, - const protobuf_test_messages::proto3::TestAllTypesProto3& input, - const string& equivalent_text_format); - void RunValidProtobufTest(const string& test_name, ConformanceLevel level, - const string& input_protobuf, - const string& equivalent_text_format, - bool isProto3); - void RunValidBinaryProtobufTest(const string& test_name, - ConformanceLevel level, - const string& input_protobuf, - bool isProto3); - void RunValidProtobufTestWithMessage( - const string& test_name, ConformanceLevel level, - const Message *input, - const string& equivalent_text_format, - bool isProto3); - typedef std::function Validator; - void RunValidJsonTestWithValidator(const string& test_name, - ConformanceLevel level, - const string& input_json, - const Validator& validator); - void ExpectParseFailureForJson(const string& test_name, - ConformanceLevel level, - const string& input_json); - void ExpectSerializeFailureForJson(const string& test_name, - ConformanceLevel level, - const string& text_format); - void ExpectParseFailureForProtoWithProtoVersion (const string& proto, - const string& test_name, - ConformanceLevel level, - bool isProto3); - void ExpectParseFailureForProto(const std::string& proto, - const std::string& test_name, - ConformanceLevel level); - void ExpectHardParseFailureForProto(const std::string& proto, - const std::string& test_name, - ConformanceLevel level); - void TestPrematureEOFForType(google::protobuf::FieldDescriptor::Type type); - void TestIllegalTags(); - template - void TestOneofMessage (MessageType &message, - bool isProto3); - template - void TestUnknownMessage (MessageType &message, - bool isProto3); - void TestValidDataForType( - google::protobuf::FieldDescriptor::Type, - std::vector> values); - bool CheckSetEmpty(const std::set& set_to_check, - const std::string& write_to_file, const std::string& msg); + void AddExpectedFailedTest(const std::string& test_name); + + virtual void RunSuiteImpl() = 0; + ConformanceTestRunner* runner_; int successes_; int expected_failures_; bool verbose_; bool enforce_recommended_; std::string output_; + std::string failure_list_flag_name_; std::string failure_list_filename_; // The set of test names that are expected to fail in this run, but haven't @@ -255,9 +311,6 @@ class ConformanceTestSuite { // The set of tests that the testee opted out of; std::set skipped_; - - std::unique_ptr type_resolver_; - std::string type_url_; }; } // namespace protobuf diff --git a/third_party/protobuf/src/google/protobuf/arenastring.cc b/third_party/protobuf/conformance/conformance_test_main.cc similarity index 80% rename from third_party/protobuf/src/google/protobuf/arenastring.cc rename to third_party/protobuf/conformance/conformance_test_main.cc index 7f33a0c8..c7ac9fc5 100644 --- a/third_party/protobuf/src/google/protobuf/arenastring.cc +++ b/third_party/protobuf/conformance/conformance_test_main.cc @@ -28,16 +28,13 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// The ArenaString implementation is not included in the open-source release. Do -// not include this file in the distribution. +#include "binary_json_conformance_suite.h" +#include "conformance_test.h" +#include "text_format_conformance_suite.h" -#include - -namespace google { -namespace protobuf { -namespace internal { - - -} // namespace internal -} // namespace protobuf -} // namespace google +int main(int argc, char *argv[]) { + google::protobuf::BinaryAndJsonConformanceSuite binary_and_json_suite; + google::protobuf::TextFormatConformanceTestSuite text_format_suite; + return google::protobuf::ForkPipeRunner::Run( + argc, argv, {&binary_and_json_suite, &text_format_suite}); +} diff --git a/third_party/protobuf/conformance/conformance_test_runner.cc b/third_party/protobuf/conformance/conformance_test_runner.cc index b0357b87..e7aa0a55 100644 --- a/third_party/protobuf/conformance/conformance_test_runner.cc +++ b/third_party/protobuf/conformance/conformance_test_runner.cc @@ -66,9 +66,9 @@ #include "conformance.pb.h" #include "conformance_test.h" -using conformance::ConformanceRequest; using conformance::ConformanceResponse; using google::protobuf::StringAppendF; +using google::protobuf::ConformanceTestSuite; using std::string; using std::vector; @@ -80,190 +80,11 @@ using std::vector; exit(1); \ } -// Test runner that spawns the process being tested and communicates with it -// over a pipe. -class ForkPipeRunner : public google::protobuf::ConformanceTestRunner { - public: - ForkPipeRunner(const std::string &executable) - : child_pid_(-1), executable_(executable) {} +namespace google { +namespace protobuf { - virtual ~ForkPipeRunner() {} - - void RunTest(const std::string& test_name, - const std::string& request, - std::string* response) { - if (child_pid_ < 0) { - SpawnTestProgram(); - } - - current_test_name_ = test_name; - - uint32_t len = request.size(); - CheckedWrite(write_fd_, &len, sizeof(uint32_t)); - CheckedWrite(write_fd_, request.c_str(), request.size()); - - if (!TryRead(read_fd_, &len, sizeof(uint32_t))) { - // We failed to read from the child, assume a crash and try to reap. - GOOGLE_LOG(INFO) << "Trying to reap child, pid=" << child_pid_; - - int status; - waitpid(child_pid_, &status, WEXITED); - - string error_msg; - if (WIFEXITED(status)) { - StringAppendF(&error_msg, - "child exited, status=%d", WEXITSTATUS(status)); - } else if (WIFSIGNALED(status)) { - StringAppendF(&error_msg, - "child killed by signal %d", WTERMSIG(status)); - } - GOOGLE_LOG(INFO) << error_msg; - child_pid_ = -1; - - conformance::ConformanceResponse response_obj; - response_obj.set_runtime_error(error_msg); - response_obj.SerializeToString(response); - return; - } - - response->resize(len); - CheckedRead(read_fd_, (void*)response->c_str(), len); - } - - private: - // TODO(haberman): make this work on Windows, instead of using these - // UNIX-specific APIs. - // - // There is a platform-agnostic API in - // src/google/protobuf/compiler/subprocess.h - // - // However that API only supports sending a single message to the subprocess. - // We really want to be able to send messages and receive responses one at a - // time: - // - // 1. Spawning a new process for each test would take way too long for thousands - // of tests and subprocesses like java that can take 100ms or more to start - // up. - // - // 2. Sending all the tests in one big message and receiving all results in one - // big message would take away our visibility about which test(s) caused a - // crash or other fatal error. It would also give us only a single failure - // instead of all of them. - void SpawnTestProgram() { - int toproc_pipe_fd[2]; - int fromproc_pipe_fd[2]; - if (pipe(toproc_pipe_fd) < 0 || pipe(fromproc_pipe_fd) < 0) { - perror("pipe"); - exit(1); - } - - pid_t pid = fork(); - if (pid < 0) { - perror("fork"); - exit(1); - } - - if (pid) { - // Parent. - CHECK_SYSCALL(close(toproc_pipe_fd[0])); - CHECK_SYSCALL(close(fromproc_pipe_fd[1])); - write_fd_ = toproc_pipe_fd[1]; - read_fd_ = fromproc_pipe_fd[0]; - child_pid_ = pid; - } else { - // Child. - CHECK_SYSCALL(close(STDIN_FILENO)); - CHECK_SYSCALL(close(STDOUT_FILENO)); - CHECK_SYSCALL(dup2(toproc_pipe_fd[0], STDIN_FILENO)); - CHECK_SYSCALL(dup2(fromproc_pipe_fd[1], STDOUT_FILENO)); - - CHECK_SYSCALL(close(toproc_pipe_fd[0])); - CHECK_SYSCALL(close(fromproc_pipe_fd[1])); - CHECK_SYSCALL(close(toproc_pipe_fd[1])); - CHECK_SYSCALL(close(fromproc_pipe_fd[0])); - - std::unique_ptr executable(new char[executable_.size() + 1]); - memcpy(executable.get(), executable_.c_str(), executable_.size()); - executable[executable_.size()] = '\0'; - - char *const argv[] = {executable.get(), NULL}; - CHECK_SYSCALL(execv(executable.get(), argv)); // Never returns. - } - } - - void CheckedWrite(int fd, const void *buf, size_t len) { - if (write(fd, buf, len) != len) { - GOOGLE_LOG(FATAL) << current_test_name_ - << ": error writing to test program: " - << strerror(errno); - } - } - - bool TryRead(int fd, void *buf, size_t len) { - size_t ofs = 0; - while (len > 0) { - ssize_t bytes_read = read(fd, (char*)buf + ofs, len); - - if (bytes_read == 0) { - GOOGLE_LOG(ERROR) << current_test_name_ - << ": unexpected EOF from test program"; - return false; - } else if (bytes_read < 0) { - GOOGLE_LOG(ERROR) << current_test_name_ - << ": error reading from test program: " - << strerror(errno); - return false; - } - - len -= bytes_read; - ofs += bytes_read; - } - - return true; - } - - void CheckedRead(int fd, void *buf, size_t len) { - if (!TryRead(fd, buf, len)) { - GOOGLE_LOG(FATAL) << current_test_name_ - << ": error reading from test program: " - << strerror(errno); - } - } - - int write_fd_; - int read_fd_; - pid_t child_pid_; - std::string executable_; - std::string current_test_name_; -}; - -void UsageError() { - fprintf(stderr, - "Usage: conformance-test-runner [options] \n"); - fprintf(stderr, "\n"); - fprintf(stderr, "Options:\n"); - fprintf(stderr, - " --failure_list Use to specify list of tests\n"); - fprintf(stderr, - " that are expected to fail. File\n"); - fprintf(stderr, - " should contain one test name per\n"); - fprintf(stderr, - " line. Use '#' for comments.\n"); - fprintf(stderr, - " --enforce_recommended Enforce that recommended test\n"); - fprintf(stderr, - " cases are also passing. Specify\n"); - fprintf(stderr, - " this flag if you want to be\n"); - fprintf(stderr, - " strictly conforming to protobuf\n"); - fprintf(stderr, - " spec.\n"); - exit(1); -} - -void ParseFailureList(const char *filename, std::vector* failure_list) { +void ParseFailureList(const char *filename, + conformance::FailureSet *failure_list) { std::ifstream infile(filename); if (!infile.is_open()) { @@ -280,46 +101,243 @@ void ParseFailureList(const char *filename, std::vector* failure_list) { line = line.substr(0, line.find("#")); if (!line.empty()) { - failure_list->push_back(line); + failure_list->add_failure(line); } } } -int main(int argc, char *argv[]) { - char *program; - google::protobuf::ConformanceTestSuite suite; +void UsageError() { + fprintf(stderr, + "Usage: conformance-test-runner [options] \n"); + fprintf(stderr, "\n"); + fprintf(stderr, "Options:\n"); + fprintf(stderr, + " --failure_list Use to specify list of tests\n"); + fprintf(stderr, + " that are expected to fail. File\n"); + fprintf(stderr, + " should contain one test name per\n"); + fprintf(stderr, + " line. Use '#' for comments.\n"); + fprintf(stderr, + " --text_format_failure_list Use to specify list \n"); + fprintf(stderr, + " of tests that are expected to \n"); + fprintf(stderr, + " fail in the \n"); + fprintf(stderr, + " text_format_conformance_suite. \n"); + fprintf(stderr, + " File should contain one test name \n"); + fprintf(stderr, + " per line. Use '#' for comments.\n"); - string failure_list_filename; - std::vector failure_list; + fprintf(stderr, + " --enforce_recommended Enforce that recommended test\n"); + fprintf(stderr, + " cases are also passing. Specify\n"); + fprintf(stderr, + " this flag if you want to be\n"); + fprintf(stderr, + " strictly conforming to protobuf\n"); + fprintf(stderr, + " spec.\n"); + exit(1); +} - for (int arg = 1; arg < argc; ++arg) { - if (strcmp(argv[arg], "--failure_list") == 0) { - if (++arg == argc) UsageError(); - failure_list_filename = argv[arg]; - ParseFailureList(argv[arg], &failure_list); - } else if (strcmp(argv[arg], "--verbose") == 0) { - suite.SetVerbose(true); - } else if (strcmp(argv[arg], "--enforce_recommended") == 0) { - suite.SetEnforceRecommended(true); - } else if (argv[arg][0] == '-') { - fprintf(stderr, "Unknown option: %s\n", argv[arg]); - UsageError(); - } else { - if (arg != argc - 1) { - fprintf(stderr, "Too many arguments.\n"); - UsageError(); +void ForkPipeRunner::RunTest( + const std::string& test_name, + const std::string& request, + std::string* response) { + if (child_pid_ < 0) { + SpawnTestProgram(); + } + + current_test_name_ = test_name; + + uint32_t len = request.size(); + CheckedWrite(write_fd_, &len, sizeof(uint32_t)); + CheckedWrite(write_fd_, request.c_str(), request.size()); + + if (!TryRead(read_fd_, &len, sizeof(uint32_t))) { + // We failed to read from the child, assume a crash and try to reap. + GOOGLE_LOG(INFO) << "Trying to reap child, pid=" << child_pid_; + + int status; + waitpid(child_pid_, &status, WEXITED); + + string error_msg; + if (WIFEXITED(status)) { + StringAppendF(&error_msg, + "child exited, status=%d", WEXITSTATUS(status)); + } else if (WIFSIGNALED(status)) { + StringAppendF(&error_msg, + "child killed by signal %d", WTERMSIG(status)); + } + GOOGLE_LOG(INFO) << error_msg; + child_pid_ = -1; + + conformance::ConformanceResponse response_obj; + response_obj.set_runtime_error(error_msg); + response_obj.SerializeToString(response); + return; + } + + response->resize(len); + CheckedRead(read_fd_, (void*)response->c_str(), len); +} + +int ForkPipeRunner::Run( + int argc, char *argv[], const std::vector& suites) { + if (suites.empty()) { + fprintf(stderr, "No test suites found.\n"); + return EXIT_FAILURE; + } + bool all_ok = true; + for (ConformanceTestSuite* suite : suites) { + char *program; + string failure_list_filename; + conformance::FailureSet failure_list; + + for (int arg = 1; arg < argc; ++arg) { + if (strcmp(argv[arg], suite->GetFailureListFlagName().c_str()) == 0) { + if (++arg == argc) UsageError(); + failure_list_filename = argv[arg]; + ParseFailureList(argv[arg], &failure_list); + } else if (strcmp(argv[arg], "--verbose") == 0) { + suite->SetVerbose(true); + } else if (strcmp(argv[arg], "--enforce_recommended") == 0) { + suite->SetEnforceRecommended(true); + } else if (argv[arg][0] == '-') { + bool recognized_flag = false; + for (ConformanceTestSuite* suite : suites) { + if (strcmp(argv[arg], suite->GetFailureListFlagName().c_str()) == 0) { + if (++arg == argc) UsageError(); + recognized_flag = true; + } + } + if (!recognized_flag) { + fprintf(stderr, "Unknown option: %s\n", argv[arg]); + UsageError(); + } + } else { + if (arg != argc - 1) { + fprintf(stderr, "Too many arguments.\n"); + UsageError(); + } + program = argv[arg]; } - program = argv[arg]; } + + ForkPipeRunner runner(program); + + std::string output; + all_ok = all_ok && + suite->RunSuite(&runner, &output, failure_list_filename, &failure_list); + + fwrite(output.c_str(), 1, output.size(), stderr); + } + return all_ok ? EXIT_SUCCESS : EXIT_FAILURE; +} + +// TODO(haberman): make this work on Windows, instead of using these +// UNIX-specific APIs. +// +// There is a platform-agnostic API in +// src/google/protobuf/compiler/subprocess.h +// +// However that API only supports sending a single message to the subprocess. +// We really want to be able to send messages and receive responses one at a +// time: +// +// 1. Spawning a new process for each test would take way too long for thousands +// of tests and subprocesses like java that can take 100ms or more to start +// up. +// +// 2. Sending all the tests in one big message and receiving all results in one +// big message would take away our visibility about which test(s) caused a +// crash or other fatal error. It would also give us only a single failure +// instead of all of them. +void ForkPipeRunner::SpawnTestProgram() { + int toproc_pipe_fd[2]; + int fromproc_pipe_fd[2]; + if (pipe(toproc_pipe_fd) < 0 || pipe(fromproc_pipe_fd) < 0) { + perror("pipe"); + exit(1); } - suite.SetFailureList(failure_list_filename, failure_list); - ForkPipeRunner runner(program); + pid_t pid = fork(); + if (pid < 0) { + perror("fork"); + exit(1); + } - std::string output; - bool ok = suite.RunSuite(&runner, &output); + if (pid) { + // Parent. + CHECK_SYSCALL(close(toproc_pipe_fd[0])); + CHECK_SYSCALL(close(fromproc_pipe_fd[1])); + write_fd_ = toproc_pipe_fd[1]; + read_fd_ = fromproc_pipe_fd[0]; + child_pid_ = pid; + } else { + // Child. + CHECK_SYSCALL(close(STDIN_FILENO)); + CHECK_SYSCALL(close(STDOUT_FILENO)); + CHECK_SYSCALL(dup2(toproc_pipe_fd[0], STDIN_FILENO)); + CHECK_SYSCALL(dup2(fromproc_pipe_fd[1], STDOUT_FILENO)); - fwrite(output.c_str(), 1, output.size(), stderr); + CHECK_SYSCALL(close(toproc_pipe_fd[0])); + CHECK_SYSCALL(close(fromproc_pipe_fd[1])); + CHECK_SYSCALL(close(toproc_pipe_fd[1])); + CHECK_SYSCALL(close(fromproc_pipe_fd[0])); - return ok ? EXIT_SUCCESS : EXIT_FAILURE; + std::unique_ptr executable(new char[executable_.size() + 1]); + memcpy(executable.get(), executable_.c_str(), executable_.size()); + executable[executable_.size()] = '\0'; + + char *const argv[] = {executable.get(), NULL}; + CHECK_SYSCALL(execv(executable.get(), argv)); // Never returns. + } } + +void ForkPipeRunner::CheckedWrite(int fd, const void *buf, size_t len) { + if (write(fd, buf, len) != len) { + GOOGLE_LOG(FATAL) << current_test_name_ + << ": error writing to test program: " + << strerror(errno); + } +} + +bool ForkPipeRunner::TryRead(int fd, void *buf, size_t len) { + size_t ofs = 0; + while (len > 0) { + ssize_t bytes_read = read(fd, (char*)buf + ofs, len); + + if (bytes_read == 0) { + GOOGLE_LOG(ERROR) << current_test_name_ + << ": unexpected EOF from test program"; + return false; + } else if (bytes_read < 0) { + GOOGLE_LOG(ERROR) << current_test_name_ + << ": error reading from test program: " + << strerror(errno); + return false; + } + + len -= bytes_read; + ofs += bytes_read; + } + + return true; +} + +void ForkPipeRunner::CheckedRead(int fd, void *buf, size_t len) { + if (!TryRead(fd, buf, len)) { + GOOGLE_LOG(FATAL) << current_test_name_ + << ": error reading from test program: " + << strerror(errno); + } +} + +} // namespace protobuf +} // namespace google diff --git a/third_party/protobuf/conformance/failure_list_cpp.txt b/third_party/protobuf/conformance/failure_list_cpp.txt index 752fbb5d..0c01e1e4 100644 --- a/third_party/protobuf/conformance/failure_list_cpp.txt +++ b/third_party/protobuf/conformance/failure_list_cpp.txt @@ -34,23 +34,3 @@ Recommended.Proto3.JsonInput.TrailingCommaInAnObject Recommended.Proto3.JsonInput.TrailingCommaInAnObjectWithNewlines Recommended.Proto3.JsonInput.TrailingCommaInAnObjectWithSpace Recommended.Proto3.JsonInput.TrailingCommaInAnObjectWithSpaceCommaSpace -Required.Proto3.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE -Required.Proto3.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE -Required.Proto3.ProtobufInput.PrematureEofInPackedField.BOOL -Required.Proto3.ProtobufInput.PrematureEofInPackedField.ENUM -Required.Proto3.ProtobufInput.PrematureEofInPackedField.INT32 -Required.Proto3.ProtobufInput.PrematureEofInPackedField.INT64 -Required.Proto3.ProtobufInput.PrematureEofInPackedField.SINT32 -Required.Proto3.ProtobufInput.PrematureEofInPackedField.SINT64 -Required.Proto3.ProtobufInput.PrematureEofInPackedField.UINT32 -Required.Proto3.ProtobufInput.PrematureEofInPackedField.UINT64 -Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE -Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE -Required.Proto2.ProtobufInput.PrematureEofInPackedField.BOOL -Required.Proto2.ProtobufInput.PrematureEofInPackedField.ENUM -Required.Proto2.ProtobufInput.PrematureEofInPackedField.INT32 -Required.Proto2.ProtobufInput.PrematureEofInPackedField.INT64 -Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT32 -Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT64 -Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT32 -Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT64 diff --git a/third_party/protobuf/conformance/failure_list_php.txt b/third_party/protobuf/conformance/failure_list_php.txt index 0d234112..f76e9d73 100644 --- a/third_party/protobuf/conformance/failure_list_php.txt +++ b/third_party/protobuf/conformance/failure_list_php.txt @@ -13,6 +13,10 @@ Required.Proto3.JsonInput.FloatFieldTooSmall Required.Proto3.JsonInput.DoubleFieldTooSmall Required.Proto3.JsonInput.Int32FieldNotInteger Required.Proto3.JsonInput.Int64FieldNotInteger +Required.Proto3.JsonInput.RepeatedFieldWrongElementTypeExpectingStringsGotInt +Required.Proto3.JsonInput.RepeatedListValue.JsonOutput +Required.Proto3.JsonInput.RepeatedListValue.ProtobufOutput +Required.Proto3.JsonInput.StringFieldNotAString Required.Proto3.JsonInput.Uint32FieldNotInteger Required.Proto3.JsonInput.Uint64FieldNotInteger Required.Proto3.JsonInput.Int32FieldLeadingSpace diff --git a/third_party/protobuf/conformance/failure_list_php_c.txt b/third_party/protobuf/conformance/failure_list_php_c.txt index 088708e9..b0405618 100644 --- a/third_party/protobuf/conformance/failure_list_php_c.txt +++ b/third_party/protobuf/conformance/failure_list_php_c.txt @@ -1,182 +1,45 @@ Recommended.FieldMaskNumbersDontRoundTrip.JsonOutput Recommended.FieldMaskPathsDontRoundTrip.JsonOutput Recommended.FieldMaskTooManyUnderscore.JsonOutput -Recommended.Proto3.JsonInput.BoolFieldIntegerOne -Recommended.Proto3.JsonInput.BoolFieldIntegerZero +Recommended.Proto3.JsonInput.BytesFieldBase64Url.JsonOutput +Recommended.Proto3.JsonInput.BytesFieldBase64Url.ProtobufOutput Recommended.Proto3.JsonInput.DurationHas3FractionalDigits.Validator Recommended.Proto3.JsonInput.DurationHas6FractionalDigits.Validator -Recommended.Proto3.JsonInput.DurationHas9FractionalDigits.Validator -Recommended.Proto3.JsonInput.DurationHasZeroFractionalDigit.Validator +Recommended.Proto3.JsonInput.FieldMaskInvalidCharacter Recommended.Proto3.JsonInput.Int64FieldBeString.Validator Recommended.Proto3.JsonInput.MapFieldValueIsNull Recommended.Proto3.JsonInput.OneofZeroBytes.JsonOutput -Recommended.Proto3.JsonInput.OneofZeroBytes.ProtobufOutput -Recommended.Proto3.JsonInput.OneofZeroString.JsonOutput -Recommended.Proto3.JsonInput.OneofZeroString.ProtobufOutput Recommended.Proto3.JsonInput.RepeatedFieldMessageElementIsNull Recommended.Proto3.JsonInput.RepeatedFieldPrimitiveElementIsNull Recommended.Proto3.JsonInput.StringEndsWithEscapeChar Recommended.Proto3.JsonInput.StringFieldSurrogateInWrongOrder Recommended.Proto3.JsonInput.StringFieldUnpairedHighSurrogate Recommended.Proto3.JsonInput.StringFieldUnpairedLowSurrogate +Recommended.Proto3.JsonInput.TimestampHas3FractionalDigits.Validator +Recommended.Proto3.JsonInput.TimestampHas6FractionalDigits.Validator Recommended.Proto3.JsonInput.Uint64FieldBeString.Validator Recommended.Proto3.ProtobufInput.OneofZeroBytes.JsonOutput -Recommended.Proto3.ProtobufInput.OneofZeroBytes.ProtobufOutput -Recommended.Proto3.ProtobufInput.OneofZeroString.JsonOutput -Recommended.Proto3.ProtobufInput.OneofZeroString.ProtobufOutput Required.DurationProtoInputTooLarge.JsonOutput Required.DurationProtoInputTooSmall.JsonOutput -Required.Proto3.JsonInput.Any.JsonOutput -Required.Proto3.JsonInput.Any.ProtobufOutput -Required.Proto3.JsonInput.AnyNested.JsonOutput -Required.Proto3.JsonInput.AnyNested.ProtobufOutput -Required.Proto3.JsonInput.AnyUnorderedTypeTag.JsonOutput -Required.Proto3.JsonInput.AnyUnorderedTypeTag.ProtobufOutput -Required.Proto3.JsonInput.AnyWithDuration.JsonOutput -Required.Proto3.JsonInput.AnyWithDuration.ProtobufOutput -Required.Proto3.JsonInput.AnyWithFieldMask.JsonOutput -Required.Proto3.JsonInput.AnyWithFieldMask.ProtobufOutput -Required.Proto3.JsonInput.AnyWithInt32ValueWrapper.JsonOutput -Required.Proto3.JsonInput.AnyWithInt32ValueWrapper.ProtobufOutput -Required.Proto3.JsonInput.AnyWithStruct.JsonOutput -Required.Proto3.JsonInput.AnyWithStruct.ProtobufOutput -Required.Proto3.JsonInput.AnyWithTimestamp.JsonOutput -Required.Proto3.JsonInput.AnyWithTimestamp.ProtobufOutput -Required.Proto3.JsonInput.AnyWithValueForInteger.JsonOutput -Required.Proto3.JsonInput.AnyWithValueForInteger.ProtobufOutput -Required.Proto3.JsonInput.AnyWithValueForJsonObject.JsonOutput -Required.Proto3.JsonInput.AnyWithValueForJsonObject.ProtobufOutput -Required.Proto3.JsonInput.BoolMapField.JsonOutput -Required.Proto3.JsonInput.DoubleFieldInfinity.JsonOutput -Required.Proto3.JsonInput.DoubleFieldInfinity.ProtobufOutput +Required.TimestampProtoInputTooLarge.JsonOutput +Required.TimestampProtoInputTooSmall.JsonOutput Required.Proto3.JsonInput.DoubleFieldMaxNegativeValue.JsonOutput Required.Proto3.JsonInput.DoubleFieldMaxNegativeValue.ProtobufOutput -Required.Proto3.JsonInput.DoubleFieldMaxPositiveValue.JsonOutput -Required.Proto3.JsonInput.DoubleFieldMaxPositiveValue.ProtobufOutput -Required.Proto3.JsonInput.DoubleFieldMinNegativeValue.JsonOutput -Required.Proto3.JsonInput.DoubleFieldMinNegativeValue.ProtobufOutput Required.Proto3.JsonInput.DoubleFieldMinPositiveValue.JsonOutput Required.Proto3.JsonInput.DoubleFieldMinPositiveValue.ProtobufOutput Required.Proto3.JsonInput.DoubleFieldNan.JsonOutput -Required.Proto3.JsonInput.DoubleFieldNan.ProtobufOutput -Required.Proto3.JsonInput.DoubleFieldNegativeInfinity.JsonOutput -Required.Proto3.JsonInput.DoubleFieldNegativeInfinity.ProtobufOutput -Required.Proto3.JsonInput.DoubleFieldQuotedValue.JsonOutput -Required.Proto3.JsonInput.DoubleFieldQuotedValue.ProtobufOutput -Required.Proto3.JsonInput.DurationMaxValue.JsonOutput -Required.Proto3.JsonInput.DurationMaxValue.ProtobufOutput Required.Proto3.JsonInput.DurationMinValue.JsonOutput -Required.Proto3.JsonInput.DurationMinValue.ProtobufOutput Required.Proto3.JsonInput.DurationRepeatedValue.JsonOutput -Required.Proto3.JsonInput.DurationRepeatedValue.ProtobufOutput -Required.Proto3.JsonInput.EnumFieldNumericValueNonZero.JsonOutput -Required.Proto3.JsonInput.EnumFieldNumericValueNonZero.ProtobufOutput -Required.Proto3.JsonInput.EnumFieldNumericValueZero.JsonOutput -Required.Proto3.JsonInput.EnumFieldNumericValueZero.ProtobufOutput -Required.Proto3.JsonInput.EnumFieldUnknownValue.Validator -Required.Proto3.JsonInput.FieldMask.JsonOutput -Required.Proto3.JsonInput.FieldMask.ProtobufOutput Required.Proto3.JsonInput.FloatFieldInfinity.JsonOutput -Required.Proto3.JsonInput.FloatFieldInfinity.ProtobufOutput Required.Proto3.JsonInput.FloatFieldNan.JsonOutput -Required.Proto3.JsonInput.FloatFieldNan.ProtobufOutput Required.Proto3.JsonInput.FloatFieldNegativeInfinity.JsonOutput -Required.Proto3.JsonInput.FloatFieldNegativeInfinity.ProtobufOutput -Required.Proto3.JsonInput.FloatFieldQuotedValue.JsonOutput -Required.Proto3.JsonInput.FloatFieldQuotedValue.ProtobufOutput -Required.Proto3.JsonInput.FloatFieldTooLarge -Required.Proto3.JsonInput.FloatFieldTooSmall -Required.Proto3.JsonInput.Int32FieldExponentialFormat.JsonOutput -Required.Proto3.JsonInput.Int32FieldExponentialFormat.ProtobufOutput -Required.Proto3.JsonInput.Int32FieldFloatTrailingZero.JsonOutput -Required.Proto3.JsonInput.Int32FieldFloatTrailingZero.ProtobufOutput -Required.Proto3.JsonInput.Int32FieldMaxFloatValue.JsonOutput -Required.Proto3.JsonInput.Int32FieldMaxFloatValue.ProtobufOutput -Required.Proto3.JsonInput.Int32FieldMinFloatValue.JsonOutput -Required.Proto3.JsonInput.Int32FieldMinFloatValue.ProtobufOutput -Required.Proto3.JsonInput.Int32FieldStringValue.JsonOutput -Required.Proto3.JsonInput.Int32FieldStringValue.ProtobufOutput -Required.Proto3.JsonInput.Int32FieldStringValueEscaped.JsonOutput -Required.Proto3.JsonInput.Int32FieldStringValueEscaped.ProtobufOutput -Required.Proto3.JsonInput.Int64FieldMaxValue.JsonOutput -Required.Proto3.JsonInput.Int64FieldMaxValue.ProtobufOutput -Required.Proto3.JsonInput.Int64FieldMinValue.JsonOutput -Required.Proto3.JsonInput.Int64FieldMinValue.ProtobufOutput -Required.Proto3.JsonInput.MessageField.JsonOutput -Required.Proto3.JsonInput.MessageField.ProtobufOutput -Required.Proto3.JsonInput.OptionalBoolWrapper.JsonOutput -Required.Proto3.JsonInput.OptionalBoolWrapper.ProtobufOutput -Required.Proto3.JsonInput.OptionalBytesWrapper.JsonOutput -Required.Proto3.JsonInput.OptionalBytesWrapper.ProtobufOutput -Required.Proto3.JsonInput.OptionalDoubleWrapper.JsonOutput -Required.Proto3.JsonInput.OptionalDoubleWrapper.ProtobufOutput -Required.Proto3.JsonInput.OptionalFloatWrapper.JsonOutput -Required.Proto3.JsonInput.OptionalFloatWrapper.ProtobufOutput -Required.Proto3.JsonInput.OptionalInt32Wrapper.JsonOutput -Required.Proto3.JsonInput.OptionalInt32Wrapper.ProtobufOutput -Required.Proto3.JsonInput.OptionalInt64Wrapper.JsonOutput -Required.Proto3.JsonInput.OptionalInt64Wrapper.ProtobufOutput -Required.Proto3.JsonInput.OptionalStringWrapper.JsonOutput -Required.Proto3.JsonInput.OptionalStringWrapper.ProtobufOutput -Required.Proto3.JsonInput.OptionalUint32Wrapper.JsonOutput -Required.Proto3.JsonInput.OptionalUint32Wrapper.ProtobufOutput -Required.Proto3.JsonInput.OptionalUint64Wrapper.JsonOutput -Required.Proto3.JsonInput.OptionalUint64Wrapper.ProtobufOutput +Required.Proto3.JsonInput.OneofFieldDuplicate Required.Proto3.JsonInput.OptionalWrapperTypesWithNonDefaultValue.JsonOutput Required.Proto3.JsonInput.OptionalWrapperTypesWithNonDefaultValue.ProtobufOutput -Required.Proto3.JsonInput.RepeatedBoolWrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedBoolWrapper.ProtobufOutput -Required.Proto3.JsonInput.RepeatedBytesWrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedBytesWrapper.ProtobufOutput -Required.Proto3.JsonInput.RepeatedDoubleWrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedDoubleWrapper.ProtobufOutput -Required.Proto3.JsonInput.RepeatedFieldWrongElementTypeExpectingMessagesGotInt -Required.Proto3.JsonInput.RepeatedFieldWrongElementTypeExpectingStringsGotInt -Required.Proto3.JsonInput.RepeatedFloatWrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedFloatWrapper.ProtobufOutput -Required.Proto3.JsonInput.RepeatedInt32Wrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedInt32Wrapper.ProtobufOutput -Required.Proto3.JsonInput.RepeatedInt64Wrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedInt64Wrapper.ProtobufOutput -Required.Proto3.JsonInput.RepeatedStringWrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedStringWrapper.ProtobufOutput -Required.Proto3.JsonInput.RepeatedUint32Wrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedUint32Wrapper.ProtobufOutput -Required.Proto3.JsonInput.RepeatedUint64Wrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedUint64Wrapper.ProtobufOutput -Required.Proto3.JsonInput.StringFieldEscape.JsonOutput -Required.Proto3.JsonInput.StringFieldEscape.ProtobufOutput -Required.Proto3.JsonInput.StringFieldNotAString Required.Proto3.JsonInput.StringFieldSurrogatePair.JsonOutput Required.Proto3.JsonInput.StringFieldSurrogatePair.ProtobufOutput -Required.Proto3.JsonInput.StringFieldUnicodeEscape.JsonOutput -Required.Proto3.JsonInput.StringFieldUnicodeEscape.ProtobufOutput -Required.Proto3.JsonInput.StringFieldUnicodeEscapeWithLowercaseHexLetters.JsonOutput -Required.Proto3.JsonInput.StringFieldUnicodeEscapeWithLowercaseHexLetters.ProtobufOutput -Required.Proto3.JsonInput.Struct.JsonOutput -Required.Proto3.JsonInput.Struct.ProtobufOutput -Required.Proto3.JsonInput.Uint32FieldMaxFloatValue.JsonOutput -Required.Proto3.JsonInput.Uint32FieldMaxFloatValue.ProtobufOutput -Required.Proto3.JsonInput.Uint64FieldMaxValue.JsonOutput -Required.Proto3.JsonInput.Uint64FieldMaxValue.ProtobufOutput -Required.Proto3.JsonInput.ValueAcceptBool.JsonOutput -Required.Proto3.JsonInput.ValueAcceptBool.ProtobufOutput -Required.Proto3.JsonInput.ValueAcceptFloat.JsonOutput -Required.Proto3.JsonInput.ValueAcceptFloat.ProtobufOutput -Required.Proto3.JsonInput.ValueAcceptInteger.JsonOutput -Required.Proto3.JsonInput.ValueAcceptInteger.ProtobufOutput -Required.Proto3.JsonInput.ValueAcceptList.JsonOutput -Required.Proto3.JsonInput.ValueAcceptList.ProtobufOutput -Required.Proto3.JsonInput.ValueAcceptNull.JsonOutput -Required.Proto3.JsonInput.ValueAcceptNull.ProtobufOutput -Required.Proto3.JsonInput.ValueAcceptObject.JsonOutput -Required.Proto3.JsonInput.ValueAcceptObject.ProtobufOutput -Required.Proto3.JsonInput.ValueAcceptString.JsonOutput -Required.Proto3.JsonInput.ValueAcceptString.ProtobufOutput Required.Proto3.ProtobufInput.DoubleFieldNormalizeQuietNan.JsonOutput Required.Proto3.ProtobufInput.DoubleFieldNormalizeSignalingNan.JsonOutput Required.Proto3.ProtobufInput.FloatFieldNormalizeQuietNan.JsonOutput Required.Proto3.ProtobufInput.FloatFieldNormalizeSignalingNan.JsonOutput Required.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.JsonOutput -Required.TimestampProtoInputTooLarge.JsonOutput -Required.TimestampProtoInputTooSmall.JsonOutput diff --git a/third_party/protobuf/conformance/failure_list_python_cpp.txt b/third_party/protobuf/conformance/failure_list_python_cpp.txt index a498ad1a..59a969d2 100644 --- a/third_party/protobuf/conformance/failure_list_python_cpp.txt +++ b/third_party/protobuf/conformance/failure_list_python_cpp.txt @@ -20,35 +20,3 @@ Required.Proto3.JsonInput.FloatFieldTooLarge Required.Proto3.JsonInput.FloatFieldTooSmall Required.Proto3.JsonInput.RepeatedFieldWrongElementTypeExpectingIntegersGotBool Required.Proto3.JsonInput.TimestampJsonInputLowercaseT -Required.Proto3.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE -Required.Proto3.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE -Required.Proto3.ProtobufInput.PrematureEofInPackedField.BOOL -Required.Proto3.ProtobufInput.PrematureEofInPackedField.DOUBLE -Required.Proto3.ProtobufInput.PrematureEofInPackedField.ENUM -Required.Proto3.ProtobufInput.PrematureEofInPackedField.FIXED32 -Required.Proto3.ProtobufInput.PrematureEofInPackedField.FIXED64 -Required.Proto3.ProtobufInput.PrematureEofInPackedField.FLOAT -Required.Proto3.ProtobufInput.PrematureEofInPackedField.INT32 -Required.Proto3.ProtobufInput.PrematureEofInPackedField.INT64 -Required.Proto3.ProtobufInput.PrematureEofInPackedField.SFIXED32 -Required.Proto3.ProtobufInput.PrematureEofInPackedField.SFIXED64 -Required.Proto3.ProtobufInput.PrematureEofInPackedField.SINT32 -Required.Proto3.ProtobufInput.PrematureEofInPackedField.SINT64 -Required.Proto3.ProtobufInput.PrematureEofInPackedField.UINT32 -Required.Proto3.ProtobufInput.PrematureEofInPackedField.UINT64 -Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE -Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE -Required.Proto2.ProtobufInput.PrematureEofInPackedField.BOOL -Required.Proto2.ProtobufInput.PrematureEofInPackedField.DOUBLE -Required.Proto2.ProtobufInput.PrematureEofInPackedField.ENUM -Required.Proto2.ProtobufInput.PrematureEofInPackedField.FIXED32 -Required.Proto2.ProtobufInput.PrematureEofInPackedField.FIXED64 -Required.Proto2.ProtobufInput.PrematureEofInPackedField.FLOAT -Required.Proto2.ProtobufInput.PrematureEofInPackedField.INT32 -Required.Proto2.ProtobufInput.PrematureEofInPackedField.INT64 -Required.Proto2.ProtobufInput.PrematureEofInPackedField.SFIXED32 -Required.Proto2.ProtobufInput.PrematureEofInPackedField.SFIXED64 -Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT32 -Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT64 -Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT32 -Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT64 diff --git a/third_party/protobuf/conformance/failure_list_ruby.txt b/third_party/protobuf/conformance/failure_list_ruby.txt index b2683372..651cb55f 100644 --- a/third_party/protobuf/conformance/failure_list_ruby.txt +++ b/third_party/protobuf/conformance/failure_list_ruby.txt @@ -5,8 +5,7 @@ Recommended.Proto3.JsonInput.BytesFieldBase64Url.JsonOutput Recommended.Proto3.JsonInput.BytesFieldBase64Url.ProtobufOutput Recommended.Proto3.JsonInput.DurationHas3FractionalDigits.Validator Recommended.Proto3.JsonInput.DurationHas6FractionalDigits.Validator -Recommended.Proto3.JsonInput.DurationHas9FractionalDigits.Validator -Recommended.Proto3.JsonInput.DurationHasZeroFractionalDigit.Validator +Recommended.Proto3.JsonInput.FieldMaskInvalidCharacter Recommended.Proto3.JsonInput.Int64FieldBeString.Validator Recommended.Proto3.JsonInput.MapFieldValueIsNull Recommended.Proto3.JsonInput.RepeatedFieldMessageElementIsNull @@ -17,117 +16,42 @@ Recommended.Proto3.JsonInput.StringFieldUnpairedHighSurrogate Recommended.Proto3.JsonInput.StringFieldUnpairedLowSurrogate Recommended.Proto3.JsonInput.TimestampHas3FractionalDigits.Validator Recommended.Proto3.JsonInput.TimestampHas6FractionalDigits.Validator -Recommended.Proto3.JsonInput.TimestampHas9FractionalDigits.Validator -Recommended.Proto3.JsonInput.TimestampHasZeroFractionalDigit.Validator -Recommended.Proto3.JsonInput.TimestampZeroNormalized.Validator Recommended.Proto3.JsonInput.Uint64FieldBeString.Validator Required.DurationProtoInputTooLarge.JsonOutput Required.DurationProtoInputTooSmall.JsonOutput -Required.Proto3.JsonInput.Any.JsonOutput -Required.Proto3.JsonInput.Any.ProtobufOutput -Required.Proto3.JsonInput.AnyNested.JsonOutput -Required.Proto3.JsonInput.AnyNested.ProtobufOutput -Required.Proto3.JsonInput.AnyUnorderedTypeTag.JsonOutput -Required.Proto3.JsonInput.AnyUnorderedTypeTag.ProtobufOutput -Required.Proto3.JsonInput.AnyWithDuration.JsonOutput -Required.Proto3.JsonInput.AnyWithDuration.ProtobufOutput -Required.Proto3.JsonInput.AnyWithFieldMask.JsonOutput -Required.Proto3.JsonInput.AnyWithFieldMask.ProtobufOutput -Required.Proto3.JsonInput.AnyWithInt32ValueWrapper.JsonOutput -Required.Proto3.JsonInput.AnyWithInt32ValueWrapper.ProtobufOutput -Required.Proto3.JsonInput.AnyWithStruct.JsonOutput -Required.Proto3.JsonInput.AnyWithStruct.ProtobufOutput -Required.Proto3.JsonInput.AnyWithTimestamp.JsonOutput -Required.Proto3.JsonInput.AnyWithTimestamp.ProtobufOutput -Required.Proto3.JsonInput.AnyWithValueForInteger.JsonOutput -Required.Proto3.JsonInput.AnyWithValueForInteger.ProtobufOutput -Required.Proto3.JsonInput.AnyWithValueForJsonObject.JsonOutput -Required.Proto3.JsonInput.AnyWithValueForJsonObject.ProtobufOutput Required.Proto3.JsonInput.DoubleFieldMaxNegativeValue.JsonOutput Required.Proto3.JsonInput.DoubleFieldMaxNegativeValue.ProtobufOutput Required.Proto3.JsonInput.DoubleFieldMinPositiveValue.JsonOutput Required.Proto3.JsonInput.DoubleFieldMinPositiveValue.ProtobufOutput Required.Proto3.JsonInput.DoubleFieldNan.JsonOutput -Required.Proto3.JsonInput.DurationMaxValue.JsonOutput -Required.Proto3.JsonInput.DurationMaxValue.ProtobufOutput Required.Proto3.JsonInput.DurationMinValue.JsonOutput -Required.Proto3.JsonInput.DurationMinValue.ProtobufOutput Required.Proto3.JsonInput.DurationRepeatedValue.JsonOutput -Required.Proto3.JsonInput.DurationRepeatedValue.ProtobufOutput -Required.Proto3.JsonInput.FieldMask.JsonOutput -Required.Proto3.JsonInput.FieldMask.ProtobufOutput Required.Proto3.JsonInput.FloatFieldInfinity.JsonOutput Required.Proto3.JsonInput.FloatFieldNan.JsonOutput Required.Proto3.JsonInput.FloatFieldNegativeInfinity.JsonOutput Required.Proto3.JsonInput.OneofFieldDuplicate Required.Proto3.JsonInput.OptionalBoolWrapper.JsonOutput -Required.Proto3.JsonInput.OptionalBoolWrapper.ProtobufOutput Required.Proto3.JsonInput.OptionalBytesWrapper.JsonOutput -Required.Proto3.JsonInput.OptionalBytesWrapper.ProtobufOutput Required.Proto3.JsonInput.OptionalDoubleWrapper.JsonOutput -Required.Proto3.JsonInput.OptionalDoubleWrapper.ProtobufOutput Required.Proto3.JsonInput.OptionalFloatWrapper.JsonOutput -Required.Proto3.JsonInput.OptionalFloatWrapper.ProtobufOutput Required.Proto3.JsonInput.OptionalInt32Wrapper.JsonOutput -Required.Proto3.JsonInput.OptionalInt32Wrapper.ProtobufOutput Required.Proto3.JsonInput.OptionalInt64Wrapper.JsonOutput -Required.Proto3.JsonInput.OptionalInt64Wrapper.ProtobufOutput Required.Proto3.JsonInput.OptionalStringWrapper.JsonOutput -Required.Proto3.JsonInput.OptionalStringWrapper.ProtobufOutput Required.Proto3.JsonInput.OptionalUint32Wrapper.JsonOutput -Required.Proto3.JsonInput.OptionalUint32Wrapper.ProtobufOutput Required.Proto3.JsonInput.OptionalUint64Wrapper.JsonOutput -Required.Proto3.JsonInput.OptionalUint64Wrapper.ProtobufOutput Required.Proto3.JsonInput.OptionalWrapperTypesWithNonDefaultValue.JsonOutput Required.Proto3.JsonInput.OptionalWrapperTypesWithNonDefaultValue.ProtobufOutput Required.Proto3.JsonInput.RepeatedBoolWrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedBoolWrapper.ProtobufOutput Required.Proto3.JsonInput.RepeatedBytesWrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedBytesWrapper.ProtobufOutput Required.Proto3.JsonInput.RepeatedDoubleWrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedDoubleWrapper.ProtobufOutput Required.Proto3.JsonInput.RepeatedFloatWrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedFloatWrapper.ProtobufOutput Required.Proto3.JsonInput.RepeatedInt32Wrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedInt32Wrapper.ProtobufOutput Required.Proto3.JsonInput.RepeatedInt64Wrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedInt64Wrapper.ProtobufOutput Required.Proto3.JsonInput.RepeatedStringWrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedStringWrapper.ProtobufOutput Required.Proto3.JsonInput.RepeatedUint32Wrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedUint32Wrapper.ProtobufOutput Required.Proto3.JsonInput.RepeatedUint64Wrapper.JsonOutput -Required.Proto3.JsonInput.RepeatedUint64Wrapper.ProtobufOutput Required.Proto3.JsonInput.StringFieldSurrogatePair.JsonOutput Required.Proto3.JsonInput.StringFieldSurrogatePair.ProtobufOutput -Required.Proto3.JsonInput.Struct.JsonOutput -Required.Proto3.JsonInput.Struct.ProtobufOutput -Required.Proto3.JsonInput.TimestampMaxValue.JsonOutput -Required.Proto3.JsonInput.TimestampMaxValue.ProtobufOutput -Required.Proto3.JsonInput.TimestampMinValue.JsonOutput -Required.Proto3.JsonInput.TimestampMinValue.ProtobufOutput -Required.Proto3.JsonInput.TimestampRepeatedValue.JsonOutput -Required.Proto3.JsonInput.TimestampRepeatedValue.ProtobufOutput -Required.Proto3.JsonInput.TimestampWithNegativeOffset.JsonOutput -Required.Proto3.JsonInput.TimestampWithNegativeOffset.ProtobufOutput -Required.Proto3.JsonInput.TimestampWithPositiveOffset.JsonOutput -Required.Proto3.JsonInput.TimestampWithPositiveOffset.ProtobufOutput -Required.Proto3.JsonInput.ValueAcceptBool.JsonOutput -Required.Proto3.JsonInput.ValueAcceptBool.ProtobufOutput -Required.Proto3.JsonInput.ValueAcceptFloat.JsonOutput -Required.Proto3.JsonInput.ValueAcceptFloat.ProtobufOutput -Required.Proto3.JsonInput.ValueAcceptInteger.JsonOutput -Required.Proto3.JsonInput.ValueAcceptInteger.ProtobufOutput -Required.Proto3.JsonInput.ValueAcceptList.JsonOutput -Required.Proto3.JsonInput.ValueAcceptList.ProtobufOutput -Required.Proto3.JsonInput.ValueAcceptListWithNull.JsonOutput -Required.Proto3.JsonInput.ValueAcceptListWithNull.ProtobufOutput -Required.Proto3.JsonInput.ValueAcceptNull.JsonOutput -Required.Proto3.JsonInput.ValueAcceptNull.ProtobufOutput -Required.Proto3.JsonInput.ValueAcceptObject.JsonOutput -Required.Proto3.JsonInput.ValueAcceptObject.ProtobufOutput -Required.Proto3.JsonInput.ValueAcceptString.JsonOutput -Required.Proto3.JsonInput.ValueAcceptString.ProtobufOutput Required.Proto3.ProtobufInput.DoubleFieldNormalizeQuietNan.JsonOutput Required.Proto3.ProtobufInput.DoubleFieldNormalizeSignalingNan.JsonOutput Required.Proto3.ProtobufInput.FloatFieldNormalizeQuietNan.JsonOutput @@ -135,3 +59,9 @@ Required.Proto3.ProtobufInput.FloatFieldNormalizeSignalingNan.JsonOutput Required.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.JsonOutput Required.TimestampProtoInputTooLarge.JsonOutput Required.TimestampProtoInputTooSmall.JsonOutput +Required.Proto3.JsonInput.IgnoreUnknownJsonFalse.ProtobufOutput +Required.Proto3.JsonInput.IgnoreUnknownJsonNull.ProtobufOutput +Required.Proto3.JsonInput.IgnoreUnknownJsonNumber.ProtobufOutput +Required.Proto3.JsonInput.IgnoreUnknownJsonObject.ProtobufOutput +Required.Proto3.JsonInput.IgnoreUnknownJsonString.ProtobufOutput +Required.Proto3.JsonInput.IgnoreUnknownJsonTrue.ProtobufOutput diff --git a/third_party/protobuf/conformance/text_format_conformance_suite.cc b/third_party/protobuf/conformance/text_format_conformance_suite.cc new file mode 100644 index 00000000..97b7b907 --- /dev/null +++ b/third_party/protobuf/conformance/text_format_conformance_suite.cc @@ -0,0 +1,317 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include "text_format_conformance_suite.h" + +#include "conformance_test.h" + +#include +#include +#include +#include + +using conformance::ConformanceRequest; +using conformance::ConformanceResponse; +using conformance::WireFormat; +using google::protobuf::Message; +using google::protobuf::TextFormat; +using protobuf_test_messages::proto2::TestAllTypesProto2; +using protobuf_test_messages::proto2::UnknownToTestAllTypes; +using protobuf_test_messages::proto3::TestAllTypesProto3; +using std::string; + +namespace google { +namespace protobuf { + +TextFormatConformanceTestSuite::TextFormatConformanceTestSuite() { + SetFailureListFlagName("--text_format_failure_list"); +} + +bool TextFormatConformanceTestSuite::ParseTextFormatResponse( + const ConformanceResponse& response, + const ConformanceRequestSetting& setting, Message* test_message) { + TextFormat::Parser parser; + const ConformanceRequest& request = setting.GetRequest(); + if (request.print_unknown_fields()) { + parser.AllowFieldNumber(true); + } + if (!parser.ParseFromString(response.text_payload(), test_message)) { + GOOGLE_LOG(ERROR) << "INTERNAL ERROR: internal text->protobuf transcode " + << "yielded unparseable proto. Text payload: " + << response.text_payload(); + return false; + } + + return true; +} + +bool TextFormatConformanceTestSuite::ParseResponse( + const ConformanceResponse& response, + const ConformanceRequestSetting& setting, Message* test_message) { + const ConformanceRequest& request = setting.GetRequest(); + WireFormat requested_output = request.requested_output_format(); + const string& test_name = setting.GetTestName(); + ConformanceLevel level = setting.GetLevel(); + + switch (response.result_case()) { + case ConformanceResponse::kProtobufPayload: { + if (requested_output != conformance::PROTOBUF) { + ReportFailure( + test_name, level, request, response, + StrCat("Test was asked for ", WireFormatToString(requested_output), + " output but provided PROTOBUF instead.") + .c_str()); + return false; + } + + if (!test_message->ParseFromString(response.protobuf_payload())) { + ReportFailure(test_name, level, request, response, + "Protobuf output we received from test was unparseable."); + return false; + } + + break; + } + + case ConformanceResponse::kTextPayload: { + if (requested_output != conformance::TEXT_FORMAT) { + ReportFailure( + test_name, level, request, response, + StrCat("Test was asked for ", WireFormatToString(requested_output), + " output but provided TEXT_FORMAT instead.") + .c_str()); + return false; + } + + if (!ParseTextFormatResponse(response, setting, test_message)) { + ReportFailure( + test_name, level, request, response, + "TEXT_FORMAT output we received from test was unparseable."); + return false; + } + + break; + } + + default: + GOOGLE_LOG(FATAL) << test_name + << ": unknown payload type: " << response.result_case(); + } + + return true; +} + +void TextFormatConformanceTestSuite::ExpectParseFailure(const string& test_name, + ConformanceLevel level, + const string& input) { + TestAllTypesProto3 prototype; + // We don't expect output, but if the program erroneously accepts the protobuf + // we let it send its response as this. We must not leave it unspecified. + ConformanceRequestSetting setting( + level, conformance::TEXT_FORMAT, conformance::TEXT_FORMAT, + conformance::TEXT_FORMAT_TEST, prototype, test_name, input); + const ConformanceRequest& request = setting.GetRequest(); + ConformanceResponse response; + string effective_test_name = StrCat(setting.ConformanceLevelToString(level), + ".Proto3.TextFormatInput.", test_name); + + RunTest(effective_test_name, request, &response); + if (response.result_case() == ConformanceResponse::kParseError) { + ReportSuccess(effective_test_name); + } else if (response.result_case() == ConformanceResponse::kSkipped) { + ReportSkip(effective_test_name, request, response); + } else { + ReportFailure(effective_test_name, level, request, response, + "Should have failed to parse, but didn't."); + } +} + +void TextFormatConformanceTestSuite::RunValidTextFormatTest( + const string& test_name, ConformanceLevel level, const string& input_text) { + TestAllTypesProto3 prototype; + RunValidTextFormatTestWithMessage(test_name, level, input_text, prototype); +} + +void TextFormatConformanceTestSuite::RunValidTextFormatTestProto2( + const string& test_name, ConformanceLevel level, const string& input_text) { + TestAllTypesProto2 prototype; + RunValidTextFormatTestWithMessage(test_name, level, input_text, prototype); +} + +void TextFormatConformanceTestSuite::RunValidTextFormatTestWithMessage( + const string& test_name, ConformanceLevel level, const string& input_text, + const Message& prototype) { + ConformanceRequestSetting setting1( + level, conformance::TEXT_FORMAT, conformance::PROTOBUF, + conformance::TEXT_FORMAT_TEST, prototype, test_name, input_text); + RunValidInputTest(setting1, input_text); + ConformanceRequestSetting setting2( + level, conformance::TEXT_FORMAT, conformance::TEXT_FORMAT, + conformance::TEXT_FORMAT_TEST, prototype, test_name, input_text); + RunValidInputTest(setting2, input_text); +} + +void TextFormatConformanceTestSuite::RunValidUnknownTextFormatTest( + const string& test_name, const Message& message) { + string serialized_input; + message.SerializeToString(&serialized_input); + TestAllTypesProto3 prototype; + ConformanceRequestSetting setting1( + RECOMMENDED, conformance::PROTOBUF, conformance::TEXT_FORMAT, + conformance::TEXT_FORMAT_TEST, prototype, test_name + "_Drop", + serialized_input); + setting1.SetPrototypeMessageForCompare(message); + RunValidBinaryInputTest(setting1, ""); + + ConformanceRequestSetting setting2( + RECOMMENDED, conformance::PROTOBUF, conformance::TEXT_FORMAT, + conformance::TEXT_FORMAT_TEST, prototype, test_name + "_Print", + serialized_input); + setting2.SetPrototypeMessageForCompare(message); + setting2.SetPrintUnknownFields(true); + RunValidBinaryInputTest(setting2, serialized_input); +} + +void TextFormatConformanceTestSuite::RunSuiteImpl() { + RunValidTextFormatTest("HelloWorld", REQUIRED, + "optional_string: 'Hello, World!'"); + // Integer fields. + RunValidTextFormatTest("Int32FieldMaxValue", REQUIRED, + "optional_int32: 2147483647"); + RunValidTextFormatTest("Int32FieldMinValue", REQUIRED, + "optional_int32: -2147483648"); + RunValidTextFormatTest("Uint32FieldMaxValue", REQUIRED, + "optional_uint32: 4294967295"); + RunValidTextFormatTest("Int64FieldMaxValue", REQUIRED, + "optional_int64: 9223372036854775807"); + RunValidTextFormatTest("Int64FieldMinValue", REQUIRED, + "optional_int64: -9223372036854775808"); + RunValidTextFormatTest("Uint64FieldMaxValue", REQUIRED, + "optional_uint64: 18446744073709551615"); + + // Parsers reject out-of-bound integer values. + ExpectParseFailure("Int32FieldTooLarge", REQUIRED, + "optional_int32: 2147483648"); + ExpectParseFailure("Int32FieldTooSmall", REQUIRED, + "optional_int32: -2147483649"); + ExpectParseFailure("Uint32FieldTooLarge", REQUIRED, + "optional_uint32: 4294967296"); + ExpectParseFailure("Int64FieldTooLarge", REQUIRED, + "optional_int64: 9223372036854775808"); + ExpectParseFailure("Int64FieldTooSmall", REQUIRED, + "optional_int64: -9223372036854775809"); + ExpectParseFailure("Uint64FieldTooLarge", REQUIRED, + "optional_uint64: 18446744073709551616"); + + // Floating point fields + RunValidTextFormatTest("FloatField", REQUIRED, + "optional_float: 3.192837"); + RunValidTextFormatTest("FloatFieldWithVeryPreciseNumber", REQUIRED, + "optional_float: 3.123456789123456789"); + RunValidTextFormatTest("FloatFieldMaxValue", REQUIRED, + "optional_float: 3.4028235e+38"); + RunValidTextFormatTest("FloatFieldMinValue", REQUIRED, + "optional_float: 1.17549e-38"); + RunValidTextFormatTest("FloatFieldNaNValue", REQUIRED, + "optional_float: NaN"); + RunValidTextFormatTest("FloatFieldPosInfValue", REQUIRED, + "optional_float: inf"); + RunValidTextFormatTest("FloatFieldNegInfValue", REQUIRED, + "optional_float: -inf"); + RunValidTextFormatTest("FloatFieldWithInt32Max", REQUIRED, + "optional_float: 4294967296"); + RunValidTextFormatTest("FloatFieldLargerThanInt64", REQUIRED, + "optional_float: 9223372036854775808"); + RunValidTextFormatTest("FloatFieldTooLarge", REQUIRED, + "optional_float: 3.4028235e+39"); + RunValidTextFormatTest("FloatFieldTooSmall", REQUIRED, + "optional_float: 1.17549e-39"); + RunValidTextFormatTest("FloatFieldLargerThanUint64", REQUIRED, + "optional_float: 18446744073709551616"); + + // Group fields + RunValidTextFormatTestProto2("GroupFieldNoColon", REQUIRED, + "Data { group_int32: 1 }"); + RunValidTextFormatTestProto2("GroupFieldWithColon", REQUIRED, + "Data: { group_int32: 1 }"); + RunValidTextFormatTestProto2("GroupFieldEmpty", REQUIRED, + "Data {}"); + + + // Unknown Fields + UnknownToTestAllTypes message; + // Unable to print unknown Fixed32/Fixed64 fields as if they are known. + // Fixed32/Fixed64 fields are not added in the tests. + message.set_optional_int32(123); + message.set_optional_string("hello"); + message.set_optional_bool(true); + RunValidUnknownTextFormatTest("ScalarUnknownFields", message); + + message.Clear(); + message.mutable_nested_message()->set_c(111); + RunValidUnknownTextFormatTest("MessageUnknownFields", message); + + message.Clear(); + message.mutable_optionalgroup()->set_a(321); + RunValidUnknownTextFormatTest("GroupUnknownFields", message); + + message.add_repeated_int32(1); + message.add_repeated_int32(2); + message.add_repeated_int32(3); + RunValidUnknownTextFormatTest("RepeatedUnknownFields", message); + + // Any fields + RunValidTextFormatTest("AnyField", REQUIRED, + R"( + optional_any: { + [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] { + optional_int32: 12345 + } + } + )"); + RunValidTextFormatTest("AnyFieldWithRawBytes", REQUIRED, + R"( + optional_any: { + type_url: "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3" + value: "\b\271`" + } + )"); + ExpectParseFailure("AnyFieldWithInvalidType", REQUIRED, + R"( + optional_any: { + [type.googleapis.com/unknown] { + optional_int32: 12345 + } + } + )"); +} + +} // namespace protobuf +} // namespace google diff --git a/third_party/protobuf/conformance/text_format_conformance_suite.h b/third_party/protobuf/conformance/text_format_conformance_suite.h new file mode 100644 index 00000000..dd258f50 --- /dev/null +++ b/third_party/protobuf/conformance/text_format_conformance_suite.h @@ -0,0 +1,69 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#ifndef TEXT_FORMAT_CONFORMANCE_SUITE_H_ +#define TEXT_FORMAT_CONFORMANCE_SUITE_H_ + +#include "conformance_test.h" + +namespace google { +namespace protobuf { + +class TextFormatConformanceTestSuite : public ConformanceTestSuite { + public: + TextFormatConformanceTestSuite(); + + private: + void RunSuiteImpl(); + void RunValidTextFormatTest(const string& test_name, ConformanceLevel level, + const string& input); + void RunValidTextFormatTestProto2(const string& test_name, + ConformanceLevel level, + const string& input); + void RunValidTextFormatTestWithMessage(const string& test_name, + ConformanceLevel level, + const string& input_text, + const Message& prototype); + void RunValidUnknownTextFormatTest(const string& test_name, + const Message& message); + void ExpectParseFailure(const string& test_name, ConformanceLevel level, + const string& input); + bool ParseTextFormatResponse(const conformance::ConformanceResponse& response, + const ConformanceRequestSetting& setting, + Message* test_message); + bool ParseResponse(const conformance::ConformanceResponse& response, + const ConformanceRequestSetting& setting, + Message* test_message) override; +}; + +} // namespace protobuf +} // namespace google + +#endif // TEXT_FORMAT_CONFORMANCE_SUITE_H_ diff --git a/third_party/protobuf/conformance/third_party/jsoncpp/json.h b/third_party/protobuf/conformance/third_party/jsoncpp/json.h index 42e7e7f4..32fd0720 100644 --- a/third_party/protobuf/conformance/third_party/jsoncpp/json.h +++ b/third_party/protobuf/conformance/third_party/jsoncpp/json.h @@ -6,28 +6,28 @@ // ////////////////////////////////////////////////////////////////////// /* -The JsonCpp library's source code, including accompanying documentation, +The JsonCpp library's source code, including accompanying documentation, tests and demonstration applications, are licensed under the following conditions... -The author (Baptiste Lepilleur) explicitly disclaims copyright in all -jurisdictions which recognize such a disclaimer. In such jurisdictions, +The author (Baptiste Lepilleur) explicitly disclaims copyright in all +jurisdictions which recognize such a disclaimer. In such jurisdictions, this software is released into the Public Domain. In jurisdictions which do not recognize Public Domain property (e.g. Germany as of 2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is released under the terms of the MIT License (see below). -In jurisdictions which recognize Public Domain property, the user of this -software may choose to accept it either as 1) Public Domain, 2) under the -conditions of the MIT License (see below), or 3) under the terms of dual +In jurisdictions which recognize Public Domain property, the user of this +software may choose to accept it either as 1) Public Domain, 2) under the +conditions of the MIT License (see below), or 3) under the terms of dual Public Domain/MIT License conditions described here, as they choose. The MIT License is about as close to Public Domain as a license can get, and is described in clear, concise terms at: http://en.wikipedia.org/wiki/MIT_License - + The full text of the MIT License follows: ======================================================================== @@ -434,7 +434,7 @@ protected: /** Exceptions which the user cannot easily avoid. * * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input - * + * * \remark derived from Json::Exception */ class JSON_API RuntimeError : public Exception { @@ -445,7 +445,7 @@ public: /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros. * * These are precondition-violations (user bugs) and internal errors (our bugs). - * + * * \remark derived from Json::Exception */ class JSON_API LogicError : public Exception { @@ -1570,7 +1570,7 @@ public: - `"rejectDupKeys": false or true` - If true, `parse()` returns false when a key is duplicated within an object. - `"allowSpecialFloats": false or true` - - If true, special float values (NaNs and infinities) are allowed + - If true, special float values (NaNs and infinities) are allowed and their values are lossfree restorable. You can examine 'settings_` yourself diff --git a/third_party/protobuf/conformance/third_party/jsoncpp/jsoncpp.cpp b/third_party/protobuf/conformance/third_party/jsoncpp/jsoncpp.cpp index f803962a..4d3e0f2f 100644 --- a/third_party/protobuf/conformance/third_party/jsoncpp/jsoncpp.cpp +++ b/third_party/protobuf/conformance/third_party/jsoncpp/jsoncpp.cpp @@ -6,28 +6,28 @@ // ////////////////////////////////////////////////////////////////////// /* -The JsonCpp library's source code, including accompanying documentation, +The JsonCpp library's source code, including accompanying documentation, tests and demonstration applications, are licensed under the following conditions... -The author (Baptiste Lepilleur) explicitly disclaims copyright in all -jurisdictions which recognize such a disclaimer. In such jurisdictions, +The author (Baptiste Lepilleur) explicitly disclaims copyright in all +jurisdictions which recognize such a disclaimer. In such jurisdictions, this software is released into the Public Domain. In jurisdictions which do not recognize Public Domain property (e.g. Germany as of 2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is released under the terms of the MIT License (see below). -In jurisdictions which recognize Public Domain property, the user of this -software may choose to accept it either as 1) Public Domain, 2) under the -conditions of the MIT License (see below), or 3) under the terms of dual +In jurisdictions which recognize Public Domain property, the user of this +software may choose to accept it either as 1) Public Domain, 2) under the +conditions of the MIT License (see below), or 3) under the terms of dual Public Domain/MIT License conditions described here, as they choose. The MIT License is about as close to Public Domain as a license can get, and is described in clear, concise terms at: http://en.wikipedia.org/wiki/MIT_License - + The full text of the MIT License follows: ======================================================================== @@ -207,7 +207,7 @@ static inline void fixNumericLocale(char* begin, char* end) { #include #if defined(_MSC_VER) -#if !defined(WINCE) && defined(__STDC_SECURE_LIB__) && _MSC_VER >= 1500 // VC++ 9.0 and above +#if !defined(WINCE) && defined(__STDC_SECURE_LIB__) && _MSC_VER >= 1500 // VC++ 9.0 and above #define snprintf sprintf_s #elif _MSC_VER >= 1900 // VC++ 14.0 and above #define snprintf std::snprintf @@ -4029,7 +4029,7 @@ Value& Path::make(Value& root) const { #define snprintf std::snprintf #endif -#if defined(__BORLANDC__) +#if defined(__BORLANDC__) #include #define isfinite _finite #define snprintf _snprintf @@ -5096,7 +5096,7 @@ StreamWriter* StreamWriterBuilder::newStreamWriter() const std::string cs_str = settings_["commentStyle"].asString(); bool eyc = settings_["enableYAMLCompatibility"].asBool(); bool dnp = settings_["dropNullPlaceholders"].asBool(); - bool usf = settings_["useSpecialFloats"].asBool(); + bool usf = settings_["useSpecialFloats"].asBool(); unsigned int pre = settings_["precision"].asUInt(); CommentStyle::Enum cs = CommentStyle::All; if (cs_str == "All") { diff --git a/third_party/protobuf/examples/README.md b/third_party/protobuf/examples/README.md index 20f285cd..3eb63527 100644 --- a/third_party/protobuf/examples/README.md +++ b/third_party/protobuf/examples/README.md @@ -119,6 +119,26 @@ is created if it does not exist. To view the data, run: ./list_people_go addressbook.data -Observe that the C++, Python, and Java examples in this directory run in a +Observe that the C++, Python, Java, and Dart examples in this directory run in a similar way and can view/modify files created by the Go example and vice versa. + +### Dart + +First, follow the instructions in [../README.md](../README.md) to install the Protocol Buffer Compiler (protoc). + +Then, install the Dart Protocol Buffer plugin as described [here](https://github.com/dart-lang/dart-protoc-plugin#how-to-build-and-use). +Note, the executable `bin/protoc-gen-dart` must be in your `PATH` for `protoc` to find it. + +Build the Dart samples in this directory with `make dart`. + +To run the examples: + +```sh +$ dart add_person.dart addessbook.data +$ dart list_people.dart addressbook.data +``` + +The two programs take a protocol buffer encoded file as their parameter. +The first can be used to add a person to the file. The file is created +if it does not exist. The second displays the data in the file. diff --git a/third_party/protobuf/examples/WORKSPACE b/third_party/protobuf/examples/WORKSPACE index 153a5932..8b97e47f 100644 --- a/third_party/protobuf/examples/WORKSPACE +++ b/third_party/protobuf/examples/WORKSPACE @@ -1,9 +1,11 @@ +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + # This com_google_protobuf repository is required for proto_library rule. # It provides the protocol compiler binary (i.e., protoc). http_archive( name = "com_google_protobuf", strip_prefix = "protobuf-master", - urls = ["https://github.com/google/protobuf/archive/master.zip"], + urls = ["https://github.com/protocolbuffers/protobuf/archive/master.zip"], ) # This com_google_protobuf_cc repository is required for cc_proto_library @@ -13,14 +15,14 @@ http_archive( http_archive( name = "com_google_protobuf_cc", strip_prefix = "protobuf-master", - urls = ["https://github.com/google/protobuf/archive/master.zip"], + urls = ["https://github.com/protocolbuffers/protobuf/archive/master.zip"], ) # Similar to com_google_protobuf_cc but for Java (i.e., java_proto_library). http_archive( name = "com_google_protobuf_java", strip_prefix = "protobuf-master", - urls = ["https://github.com/google/protobuf/archive/master.zip"], + urls = ["https://github.com/protocolbuffers/protobuf/archive/master.zip"], ) # Similar to com_google_protobuf_cc but for Java lite. If you are building @@ -29,7 +31,7 @@ http_archive( http_archive( name = "com_google_protobuf_javalite", strip_prefix = "protobuf-javalite", - urls = ["https://github.com/google/protobuf/archive/javalite.zip"], + urls = ["https://github.com/protocolbuffers/protobuf/archive/javalite.zip"], ) http_archive( @@ -39,5 +41,10 @@ http_archive( urls = ["https://github.com/bazelbuild/bazel-skylib/archive/2169ae1c374aab4a09aa90e65efe1a3aad4e279b.tar.gz"], ) -load("@bazel_skylib//:lib.bzl", "versions") +load("@com_google_protobuf//:protobuf_deps.bzl", "protobuf_deps") + +protobuf_deps() + +load("@bazel_skylib//lib:versions.bzl", "versions") + versions.check(minimum_bazel_version = "0.5.4") diff --git a/third_party/protobuf/examples/add_person.dart b/third_party/protobuf/examples/add_person.dart new file mode 100644 index 00000000..bb38901a --- /dev/null +++ b/third_party/protobuf/examples/add_person.dart @@ -0,0 +1,70 @@ +import 'dart:io'; + +import 'dart_tutorial/addressbook.pb.dart'; + +// This function fills in a Person message based on user input. +Person promptForAddress() { + Person person = Person(); + + print('Enter person ID: '); + String input = stdin.readLineSync(); + person.id = int.parse(input); + + print('Enter name'); + person.name = stdin.readLineSync(); + + print('Enter email address (blank for none) : '); + String email = stdin.readLineSync(); + if (email.isNotEmpty) { + person.email = email; + } + + while (true) { + print('Enter a phone number (or leave blank to finish): '); + String number = stdin.readLineSync(); + if (number.isEmpty) break; + + Person_PhoneNumber phoneNumber = Person_PhoneNumber(); + + phoneNumber.number = number; + print('Is this a mobile, home, or work phone? '); + + String type = stdin.readLineSync(); + switch (type) { + case 'mobile': + phoneNumber.type = Person_PhoneType.MOBILE; + break; + case 'home': + phoneNumber.type = Person_PhoneType.HOME; + break; + case 'work': + phoneNumber.type = Person_PhoneType.WORK; + break; + default: + print('Unknown phone type. Using default.'); + } + person.phones.add(phoneNumber); + } + + return person; +} + +// Reads the entire address book from a file, adds one person based +// on user input, then writes it back out to the same file. +main(List arguments) { + if (arguments.length != 1) { + print('Usage: add_person ADDRESS_BOOK_FILE'); + exit(-1); + } + + File file = File(arguments.first); + AddressBook addressBook; + if (!file.existsSync()) { + print('File not found. Creating new file.'); + addressBook = AddressBook(); + } else { + addressBook = AddressBook.fromBuffer(file.readAsBytesSync()); + } + addressBook.people.add(promptForAddress()); + file.writeAsBytes(addressBook.writeToBuffer()); +} diff --git a/third_party/protobuf/examples/add_person.go b/third_party/protobuf/examples/add_person.go index 4f2e7f74..7ffb0ab0 100644 --- a/third_party/protobuf/examples/add_person.go +++ b/third_party/protobuf/examples/add_person.go @@ -10,7 +10,7 @@ import ( "strings" "github.com/golang/protobuf/proto" - pb "github.com/google/protobuf/examples/tutorial" + pb "github.com/protocolbuffers/protobuf/examples/tutorial" ) func promptForAddress(r io.Reader) (*pb.Person, error) { diff --git a/third_party/protobuf/examples/add_person_test.go b/third_party/protobuf/examples/add_person_test.go index f8ba9338..d35f10ec 100644 --- a/third_party/protobuf/examples/add_person_test.go +++ b/third_party/protobuf/examples/add_person_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/golang/protobuf/proto" - pb "github.com/google/protobuf/examples/tutorial" + pb "github.com/protocolbuffers/protobuf/examples/tutorial" ) func TestPromptForAddressReturnsAddress(t *testing.T) { diff --git a/third_party/protobuf/examples/list_people.dart b/third_party/protobuf/examples/list_people.dart new file mode 100644 index 00000000..dd5bb410 --- /dev/null +++ b/third_party/protobuf/examples/list_people.dart @@ -0,0 +1,47 @@ +import 'dart:io'; + +import 'dart_tutorial/addressbook.pb.dart'; +import 'dart_tutorial/addressbook.pbenum.dart'; + +// Iterates though all people in the AddressBook and prints info about them. +void printAddressBook(AddressBook addressBook) { + for (Person person in addressBook.people) { + print('Person ID: ${person.id}'); + print(' Name: ${person.name}'); + if (person.hasEmail()) { + print(' E-mail address:${person.email}'); + } + + for (Person_PhoneNumber phoneNumber in person.phones) { + switch (phoneNumber.type) { + case Person_PhoneType.MOBILE: + print(' Mobile phone #: '); + break; + case Person_PhoneType.HOME: + print(' Home phone #: '); + break; + case Person_PhoneType.WORK: + print(' Work phone #: '); + break; + default: + print(' Unknown phone #: '); + break; + } + print(phoneNumber.number); + } + } +} + +// Reads the entire address book from a file and prints all +// the information inside. +main(List arguments) { + if (arguments.length != 1) { + print('Usage: list_person ADDRESS_BOOK_FILE'); + exit(-1); + } + + // Read the existing address book. + File file = new File(arguments.first); + AddressBook addressBook = new AddressBook.fromBuffer(file.readAsBytesSync()); + printAddressBook(addressBook); +} diff --git a/third_party/protobuf/examples/list_people.go b/third_party/protobuf/examples/list_people.go index 70bc589e..6c2c34ac 100644 --- a/third_party/protobuf/examples/list_people.go +++ b/third_party/protobuf/examples/list_people.go @@ -8,7 +8,7 @@ import ( "os" "github.com/golang/protobuf/proto" - pb "github.com/google/protobuf/examples/tutorial" + pb "github.com/protocolbuffers/protobuf/examples/tutorial" ) func writePerson(w io.Writer, p *pb.Person) { diff --git a/third_party/protobuf/examples/list_people_test.go b/third_party/protobuf/examples/list_people_test.go index 887997fe..aceabd4a 100644 --- a/third_party/protobuf/examples/list_people_test.go +++ b/third_party/protobuf/examples/list_people_test.go @@ -5,7 +5,7 @@ import ( "strings" "testing" - pb "github.com/google/protobuf/examples/tutorial" + pb "github.com/protocolbuffers/protobuf/examples/tutorial" ) func TestWritePersonWritesPerson(t *testing.T) { @@ -34,7 +34,7 @@ func TestWritePersonWritesPerson(t *testing.T) { func TestListPeopleWritesList(t *testing.T) { buf := new(bytes.Buffer) - in := pb.AddressBook{People: []*pb.Person { + in := pb.AddressBook{People: []*pb.Person{ { Name: "John Doe", Id: 101, diff --git a/third_party/protobuf/examples/pubspec.yaml b/third_party/protobuf/examples/pubspec.yaml new file mode 100644 index 00000000..0c36dbdc --- /dev/null +++ b/third_party/protobuf/examples/pubspec.yaml @@ -0,0 +1,5 @@ +name: addressbook +description: dartlang.org example code. + +dependencies: + protobuf: diff --git a/third_party/protobuf/examples/third_party/zlib.BUILD b/third_party/protobuf/examples/third_party/zlib.BUILD new file mode 100644 index 00000000..f9481174 --- /dev/null +++ b/third_party/protobuf/examples/third_party/zlib.BUILD @@ -0,0 +1,60 @@ +package(default_visibility = ["//visibility:public"]) + +licenses(["notice"]) # BSD/MIT-like license (for zlib) + +_ZLIB_HEADERS = [ + "crc32.h", + "deflate.h", + "gzguts.h", + "inffast.h", + "inffixed.h", + "inflate.h", + "inftrees.h", + "trees.h", + "zconf.h", + "zlib.h", + "zutil.h", +] + +_ZLIB_PREFIXED_HEADERS = ["zlib/include/" + hdr for hdr in _ZLIB_HEADERS] + +# In order to limit the damage from the `includes` propagation +# via `:zlib`, copy the public headers to a subdirectory and +# expose those. +genrule( + name = "copy_public_headers", + srcs = _ZLIB_HEADERS, + outs = _ZLIB_PREFIXED_HEADERS, + cmd = "cp $(SRCS) $(@D)/zlib/include/", + visibility = ["//visibility:private"], +) + +cc_library( + name = "zlib", + srcs = [ + "adler32.c", + "compress.c", + "crc32.c", + "deflate.c", + "gzclose.c", + "gzlib.c", + "gzread.c", + "gzwrite.c", + "infback.c", + "inffast.c", + "inflate.c", + "inftrees.c", + "trees.c", + "uncompr.c", + "zutil.c", + # Include the un-prefixed headers in srcs to work + # around the fact that zlib isn't consistent in its + # choice of <> or "" delimiter when including itself. + ] + _ZLIB_HEADERS, + hdrs = _ZLIB_PREFIXED_HEADERS, + copts = [ + "-Wno-unused-variable", + "-Wno-implicit-function-declaration", + ], + includes = ["zlib/include/"], +) diff --git a/third_party/protobuf/generate_descriptor_proto.sh b/third_party/protobuf/generate_descriptor_proto.sh index 8a5ed48a..e533d05b 100755 --- a/third_party/protobuf/generate_descriptor_proto.sh +++ b/third_party/protobuf/generate_descriptor_proto.sh @@ -18,14 +18,6 @@ __EOF__ exit 1 fi -if test ! -e src/Makefile; then - cat >&2 << __EOF__ -Could not find src/Makefile. You must run ./configure (and perhaps -./autogen.sh) first. -__EOF__ - exit 1 -fi - cd src declare -a RUNTIME_PROTO_FILES=(\ @@ -51,7 +43,7 @@ while [ $# -gt 0 ]; do case $1 in --bootstrap_protoc) BOOTSTRAP_PROTOC=$2 - shift + shift 2 ;; *) break @@ -78,8 +70,8 @@ do PROTOC="./protoc" fi - $PROTOC --cpp_out=dllexport_decl=LIBPROTOBUF_EXPORT:$TMP ${RUNTIME_PROTO_FILES[@]} && \ - $PROTOC --cpp_out=dllexport_decl=LIBPROTOC_EXPORT:$TMP ${COMPILER_PROTO_FILES[@]} + $PROTOC --cpp_out=dllexport_decl=PROTOBUF_EXPORT:$TMP ${RUNTIME_PROTO_FILES[@]} && \ + $PROTOC --cpp_out=dllexport_decl=PROTOC_EXPORT:$TMP ${COMPILER_PROTO_FILES[@]} for PROTO_FILE in ${RUNTIME_PROTO_FILES[@]} ${COMPILER_PROTO_FILES[@]}; do BASE_NAME=${PROTO_FILE%.*} diff --git a/third_party/protobuf/m4/acx_check_suncc.m4 b/third_party/protobuf/m4/acx_check_suncc.m4 index 8bc0a890..0a9a5770 100644 --- a/third_party/protobuf/m4/acx_check_suncc.m4 +++ b/third_party/protobuf/m4/acx_check_suncc.m4 @@ -26,7 +26,7 @@ AC_DEFUN([ACX_CHECK_SUNCC],[ AS_IF([test "$SUNCC" = "yes" -a "x${ac_cv_env_CXXFLAGS_set}" = "x"],[ dnl Sun Studio has a crashing bug with -xO4 in some cases. Keep this dnl at -xO3 until a proper test to detect those crashes can be done. - CXXFLAGS="-g0 -xO3 -xlibmil -xdepend -xbuiltin -mt -compat=5 -library=stlport4 -library=Crun -template=no%extdef ${CXXFLAGS}" + CXXFLAGS="-g0 -xO3 -xlibmil -xdepend -xbuiltin -mt -template=no%extdef ${CXXFLAGS}" ]) case $host_os in @@ -67,4 +67,7 @@ AC_DEFUN([ACX_CHECK_SUNCC],[ ;; esac + AS_IF([test "$target_cpu" = "sparc" -a "x$SUNCC" = "xyes" ],[ + CXXFLAGS="-xregs=no%appl ${CXXFLAGS}" + ]) ]) diff --git a/third_party/protobuf/protobuf-lite.pc.in b/third_party/protobuf/protobuf-lite.pc.in index 80f1f461..68a2bb45 100644 --- a/third_party/protobuf/protobuf-lite.pc.in +++ b/third_party/protobuf/protobuf-lite.pc.in @@ -6,6 +6,6 @@ includedir=@includedir@ Name: Protocol Buffers Description: Google's Data Interchange Format Version: @VERSION@ -Libs: -L${libdir} -lprotobuf-lite @PTHREAD_CFLAGS@ @PTHREAD_LIBS@ +Libs: -L${libdir} -lprotobuf-lite @PTHREAD_LIBS@ Cflags: -I${includedir} @PTHREAD_CFLAGS@ Conflicts: protobuf diff --git a/third_party/protobuf/protobuf.bzl b/third_party/protobuf/protobuf.bzl index 78f19c62..e764859b 100644 --- a/third_party/protobuf/protobuf.bzl +++ b/third_party/protobuf/protobuf.bzl @@ -1,127 +1,178 @@ +load("@bazel_skylib//lib:versions.bzl", "versions") + def _GetPath(ctx, path): - if ctx.label.workspace_root: - return ctx.label.workspace_root + '/' + path - else: - return path + if ctx.label.workspace_root: + return ctx.label.workspace_root + "/" + path + else: + return path def _IsNewExternal(ctx): - # Bazel 0.4.4 and older have genfiles paths that look like: - # bazel-out/local-fastbuild/genfiles/external/repo/foo - # After the exec root rearrangement, they look like: - # ../repo/bazel-out/local-fastbuild/genfiles/foo - return ctx.label.workspace_root.startswith("../") + # Bazel 0.4.4 and older have genfiles paths that look like: + # bazel-out/local-fastbuild/genfiles/external/repo/foo + # After the exec root rearrangement, they look like: + # ../repo/bazel-out/local-fastbuild/genfiles/foo + return ctx.label.workspace_root.startswith("../") def _GenDir(ctx): - if _IsNewExternal(ctx): - # We are using the fact that Bazel 0.4.4+ provides repository-relative paths - # for ctx.genfiles_dir. - return ctx.genfiles_dir.path + ( - "/" + ctx.attr.includes[0] if ctx.attr.includes and ctx.attr.includes[0] else "") - # This means that we're either in the old version OR the new version in the local repo. - # Either way, appending the source path to the genfiles dir works. - return ctx.var["GENDIR"] + "/" + _SourceDir(ctx) + if _IsNewExternal(ctx): + # We are using the fact that Bazel 0.4.4+ provides repository-relative paths + # for ctx.genfiles_dir. + return ctx.genfiles_dir.path + ( + "/" + ctx.attr.includes[0] if ctx.attr.includes and ctx.attr.includes[0] else "" + ) + + # This means that we're either in the old version OR the new version in the local repo. + # Either way, appending the source path to the genfiles dir works. + return ctx.var["GENDIR"] + "/" + _SourceDir(ctx) def _SourceDir(ctx): - if not ctx.attr.includes: - return ctx.label.workspace_root - if not ctx.attr.includes[0]: - return _GetPath(ctx, ctx.label.package) - if not ctx.label.package: - return _GetPath(ctx, ctx.attr.includes[0]) - return _GetPath(ctx, ctx.label.package + '/' + ctx.attr.includes[0]) + if not ctx.attr.includes: + return ctx.label.workspace_root + if not ctx.attr.includes[0]: + return _GetPath(ctx, ctx.label.package) + if not ctx.label.package: + return _GetPath(ctx, ctx.attr.includes[0]) + return _GetPath(ctx, ctx.label.package + "/" + ctx.attr.includes[0]) -def _CcHdrs(srcs, use_grpc_plugin=False): - ret = [s[:-len(".proto")] + ".pb.h" for s in srcs] - if use_grpc_plugin: - ret += [s[:-len(".proto")] + ".grpc.pb.h" for s in srcs] - return ret +def _CcHdrs(srcs, use_grpc_plugin = False): + ret = [s[:-len(".proto")] + ".pb.h" for s in srcs] + if use_grpc_plugin: + ret += [s[:-len(".proto")] + ".grpc.pb.h" for s in srcs] + return ret -def _CcSrcs(srcs, use_grpc_plugin=False): - ret = [s[:-len(".proto")] + ".pb.cc" for s in srcs] - if use_grpc_plugin: - ret += [s[:-len(".proto")] + ".grpc.pb.cc" for s in srcs] - return ret +def _CcSrcs(srcs, use_grpc_plugin = False): + ret = [s[:-len(".proto")] + ".pb.cc" for s in srcs] + if use_grpc_plugin: + ret += [s[:-len(".proto")] + ".grpc.pb.cc" for s in srcs] + return ret -def _CcOuts(srcs, use_grpc_plugin=False): - return _CcHdrs(srcs, use_grpc_plugin) + _CcSrcs(srcs, use_grpc_plugin) +def _CcOuts(srcs, use_grpc_plugin = False): + return _CcHdrs(srcs, use_grpc_plugin) + _CcSrcs(srcs, use_grpc_plugin) -def _PyOuts(srcs, use_grpc_plugin=False): - ret = [s[:-len(".proto")] + "_pb2.py" for s in srcs] - if use_grpc_plugin: - ret += [s[:-len(".proto")] + "_pb2_grpc.py" for s in srcs] - return ret +def _PyOuts(srcs, use_grpc_plugin = False): + ret = [s[:-len(".proto")] + "_pb2.py" for s in srcs] + if use_grpc_plugin: + ret += [s[:-len(".proto")] + "_pb2_grpc.py" for s in srcs] + return ret -def _RelativeOutputPath(path, include, dest=""): - if include == None: - return path +def _RelativeOutputPath(path, include, dest = ""): + if include == None: + return path - if not path.startswith(include): - fail("Include path %s isn't part of the path %s." % (include, path)) + if not path.startswith(include): + fail("Include path %s isn't part of the path %s." % (include, path)) - if include and include[-1] != '/': - include = include + '/' - if dest and dest[-1] != '/': - dest = dest + '/' + if include and include[-1] != "/": + include = include + "/" + if dest and dest[-1] != "/": + dest = dest + "/" - path = path[len(include):] - return dest + path + path = path[len(include):] + return dest + path def _proto_gen_impl(ctx): - """General implementation for generating protos""" - srcs = ctx.files.srcs - deps = [] - deps += ctx.files.srcs - source_dir = _SourceDir(ctx) - gen_dir = _GenDir(ctx) - if source_dir: - import_flags = ["-I" + source_dir, "-I" + gen_dir] - else: - import_flags = ["-I."] + """General implementation for generating protos""" + srcs = ctx.files.srcs + deps = [] + deps += ctx.files.srcs + source_dir = _SourceDir(ctx) + gen_dir = _GenDir(ctx).rstrip("/") + if source_dir: + import_flags = ["-I" + source_dir, "-I" + gen_dir] + else: + import_flags = ["-I."] - for dep in ctx.attr.deps: - import_flags += dep.proto.import_flags - deps += dep.proto.deps + for dep in ctx.attr.deps: + import_flags += dep.proto.import_flags + deps += dep.proto.deps - args = [] - if ctx.attr.gen_cc: - args += ["--cpp_out=" + gen_dir] - if ctx.attr.gen_py: - args += ["--python_out=" + gen_dir] + if not ctx.attr.gen_cc and not ctx.attr.gen_py and not ctx.executable.plugin: + return struct( + proto = struct( + srcs = srcs, + import_flags = import_flags, + deps = deps, + ), + ) - inputs = srcs + deps - if ctx.executable.plugin: - plugin = ctx.executable.plugin - lang = ctx.attr.plugin_language - if not lang and plugin.basename.startswith('protoc-gen-'): - lang = plugin.basename[len('protoc-gen-'):] - if not lang: - fail("cannot infer the target language of plugin", "plugin_language") + for src in srcs: + args = [] - outdir = gen_dir - if ctx.attr.plugin_options: - outdir = ",".join(ctx.attr.plugin_options) + ":" + outdir - args += ["--plugin=protoc-gen-%s=%s" % (lang, plugin.path)] - args += ["--%s_out=%s" % (lang, outdir)] - inputs += [plugin] + in_gen_dir = src.root.path == gen_dir + if in_gen_dir: + import_flags_real = [] + for f in depset(import_flags).to_list(): + path = f.replace("-I", "") + import_flags_real.append("-I$(realpath -s %s)" % path) - if args: - ctx.action( - inputs=inputs, - outputs=ctx.outputs.outs, - arguments=args + import_flags + [s.path for s in srcs], - executable=ctx.executable.protoc, - mnemonic="ProtoCompile", - use_default_shell_env=True, + outs = [] + use_grpc_plugin = (ctx.attr.plugin_language == "grpc" and ctx.attr.plugin) + path_tpl = "$(realpath %s)" if in_gen_dir else "%s" + if ctx.attr.gen_cc: + args += [("--cpp_out=" + path_tpl) % gen_dir] + outs.extend(_CcOuts([src.basename], use_grpc_plugin = use_grpc_plugin)) + if ctx.attr.gen_py: + args += [("--python_out=" + path_tpl) % gen_dir] + outs.extend(_PyOuts([src.basename], use_grpc_plugin = use_grpc_plugin)) + + outs = [ctx.actions.declare_file(out, sibling = src) for out in outs] + inputs = [src] + deps + if ctx.executable.plugin: + plugin = ctx.executable.plugin + lang = ctx.attr.plugin_language + if not lang and plugin.basename.startswith("protoc-gen-"): + lang = plugin.basename[len("protoc-gen-"):] + if not lang: + fail("cannot infer the target language of plugin", "plugin_language") + + outdir = "." if in_gen_dir else gen_dir + + if ctx.attr.plugin_options: + outdir = ",".join(ctx.attr.plugin_options) + ":" + outdir + args += [("--plugin=protoc-gen-%s=" + path_tpl) % (lang, plugin.path)] + args += ["--%s_out=%s" % (lang, outdir)] + inputs += [plugin] + + if not in_gen_dir: + ctx.actions.run( + inputs = inputs, + outputs = outs, + arguments = args + import_flags + [src.path], + executable = ctx.executable.protoc, + mnemonic = "ProtoCompile", + use_default_shell_env = True, + ) + else: + for out in outs: + orig_command = " ".join( + ["$(realpath %s)" % ctx.executable.protoc.path] + args + + import_flags_real + ["-I.", src.basename], + ) + command = ";".join([ + 'CMD="%s"' % orig_command, + "cd %s" % src.dirname, + "${CMD}", + "cd -", + ]) + generated_out = "/".join([gen_dir, out.basename]) + if generated_out != out.path: + command += ";mv %s %s" % (generated_out, out.path) + ctx.actions.run_shell( + inputs = inputs + [ctx.executable.protoc], + outputs = [out], + command = command, + mnemonic = "ProtoCompile", + use_default_shell_env = True, + ) + + return struct( + proto = struct( + srcs = srcs, + import_flags = import_flags, + deps = deps, + ), ) - return struct( - proto=struct( - srcs=srcs, - import_flags=import_flags, - deps=deps, - ), - ) - proto_gen = rule( attrs = { "srcs": attr.label_list(allow_files = True), @@ -130,7 +181,7 @@ proto_gen = rule( "protoc": attr.label( cfg = "host", executable = True, - single_file = True, + allow_single_file = True, mandatory = True, ), "plugin": attr.label( @@ -170,248 +221,251 @@ Args: def cc_proto_library( name, - srcs=[], - deps=[], - cc_libs=[], - include=None, - protoc="@com_google_protobuf//:protoc", - internal_bootstrap_hack=False, - use_grpc_plugin=False, - default_runtime="@com_google_protobuf//:protobuf", + srcs = [], + deps = [], + cc_libs = [], + include = None, + protoc = "@com_google_protobuf//:protoc", + internal_bootstrap_hack = False, + use_grpc_plugin = False, + default_runtime = "@com_google_protobuf//:protobuf", **kargs): - """Bazel rule to create a C++ protobuf library from proto source files + """Bazel rule to create a C++ protobuf library from proto source files - NOTE: the rule is only an internal workaround to generate protos. The - interface may change and the rule may be removed when bazel has introduced - the native rule. + NOTE: the rule is only an internal workaround to generate protos. The + interface may change and the rule may be removed when bazel has introduced + the native rule. - Args: - name: the name of the cc_proto_library. - srcs: the .proto files of the cc_proto_library. - deps: a list of dependency labels; must be cc_proto_library. - cc_libs: a list of other cc_library targets depended by the generated - cc_library. - include: a string indicating the include path of the .proto files. - protoc: the label of the protocol compiler to generate the sources. - internal_bootstrap_hack: a flag indicate the cc_proto_library is used only - for bootstraping. When it is set to True, no files will be generated. - The rule will simply be a provider for .proto files, so that other - cc_proto_library can depend on it. - use_grpc_plugin: a flag to indicate whether to call the grpc C++ plugin - when processing the proto files. - default_runtime: the implicitly default runtime which will be depended on by - the generated cc_library target. - **kargs: other keyword arguments that are passed to cc_library. + Args: + name: the name of the cc_proto_library. + srcs: the .proto files of the cc_proto_library. + deps: a list of dependency labels; must be cc_proto_library. + cc_libs: a list of other cc_library targets depended by the generated + cc_library. + include: a string indicating the include path of the .proto files. + protoc: the label of the protocol compiler to generate the sources. + internal_bootstrap_hack: a flag indicate the cc_proto_library is used only + for bootstraping. When it is set to True, no files will be generated. + The rule will simply be a provider for .proto files, so that other + cc_proto_library can depend on it. + use_grpc_plugin: a flag to indicate whether to call the grpc C++ plugin + when processing the proto files. + default_runtime: the implicitly default runtime which will be depended on by + the generated cc_library target. + **kargs: other keyword arguments that are passed to cc_library. - """ + """ - includes = [] - if include != None: - includes = [include] + includes = [] + if include != None: + includes = [include] + + if internal_bootstrap_hack: + # For pre-checked-in generated files, we add the internal_bootstrap_hack + # which will skip the codegen action. + proto_gen( + name = name + "_genproto", + srcs = srcs, + deps = [s + "_genproto" for s in deps], + includes = includes, + protoc = protoc, + visibility = ["//visibility:public"], + ) + + # An empty cc_library to make rule dependency consistent. + native.cc_library( + name = name, + **kargs + ) + return + + grpc_cpp_plugin = None + if use_grpc_plugin: + grpc_cpp_plugin = "//external:grpc_cpp_plugin" + + gen_srcs = _CcSrcs(srcs, use_grpc_plugin) + gen_hdrs = _CcHdrs(srcs, use_grpc_plugin) + outs = gen_srcs + gen_hdrs - if internal_bootstrap_hack: - # For pre-checked-in generated files, we add the internal_bootstrap_hack - # which will skip the codegen action. proto_gen( - name=name + "_genproto", - srcs=srcs, - deps=[s + "_genproto" for s in deps], - includes=includes, - protoc=protoc, - visibility=["//visibility:public"], + name = name + "_genproto", + srcs = srcs, + deps = [s + "_genproto" for s in deps], + includes = includes, + protoc = protoc, + plugin = grpc_cpp_plugin, + plugin_language = "grpc", + gen_cc = 1, + outs = outs, + visibility = ["//visibility:public"], ) - # An empty cc_library to make rule dependency consistent. + + if default_runtime and not default_runtime in cc_libs: + cc_libs = cc_libs + [default_runtime] + if use_grpc_plugin: + cc_libs = cc_libs + ["//external:grpc_lib"] + native.cc_library( - name=name, - **kargs) - return - - grpc_cpp_plugin = None - if use_grpc_plugin: - grpc_cpp_plugin = "//external:grpc_cpp_plugin" - - gen_srcs = _CcSrcs(srcs, use_grpc_plugin) - gen_hdrs = _CcHdrs(srcs, use_grpc_plugin) - outs = gen_srcs + gen_hdrs - - proto_gen( - name=name + "_genproto", - srcs=srcs, - deps=[s + "_genproto" for s in deps], - includes=includes, - protoc=protoc, - plugin=grpc_cpp_plugin, - plugin_language="grpc", - gen_cc=1, - outs=outs, - visibility=["//visibility:public"], - ) - - if default_runtime and not default_runtime in cc_libs: - cc_libs = cc_libs + [default_runtime] - if use_grpc_plugin: - cc_libs = cc_libs + ["//external:grpc_lib"] - - native.cc_library( - name=name, - srcs=gen_srcs, - hdrs=gen_hdrs, - deps=cc_libs + deps, - includes=includes, - **kargs) + name = name, + srcs = gen_srcs, + hdrs = gen_hdrs, + deps = cc_libs + deps, + includes = includes, + **kargs + ) def internal_gen_well_known_protos_java(srcs): - """Bazel rule to generate the gen_well_known_protos_java genrule + """Bazel rule to generate the gen_well_known_protos_java genrule - Args: - srcs: the well known protos - """ - root = Label("%s//protobuf_java" % (REPOSITORY_NAME)).workspace_root - pkg = PACKAGE_NAME + "/" if PACKAGE_NAME else "" - if root == "": - include = " -I%ssrc " % pkg - else: - include = " -I%s/%ssrc " % (root, pkg) - native.genrule( - name = "gen_well_known_protos_java", - srcs = srcs, - outs = [ - "wellknown.srcjar", - ], - cmd = "$(location :protoc) --java_out=$(@D)/wellknown.jar" + - " %s $(SRCS) " % include + - " && mv $(@D)/wellknown.jar $(@D)/wellknown.srcjar", - tools = [":protoc"], - ) + Args: + srcs: the well known protos + """ + root = Label("%s//protobuf_java" % (native.repository_name())).workspace_root + pkg = native.package_name() + "/" if native.package_name() else "" + if root == "": + include = " -I%ssrc " % pkg + else: + include = " -I%s/%ssrc " % (root, pkg) + native.genrule( + name = "gen_well_known_protos_java", + srcs = srcs, + outs = [ + "wellknown.srcjar", + ], + cmd = "$(location :protoc) --java_out=$(@D)/wellknown.jar" + + " %s $(SRCS) " % include + + " && mv $(@D)/wellknown.jar $(@D)/wellknown.srcjar", + tools = [":protoc"], + ) def internal_copied_filegroup(name, srcs, strip_prefix, dest, **kwargs): - """Macro to copy files to a different directory and then create a filegroup. + """Macro to copy files to a different directory and then create a filegroup. - This is used by the //:protobuf_python py_proto_library target to work around - an issue caused by Python source files that are part of the same Python - package being in separate directories. + This is used by the //:protobuf_python py_proto_library target to work around + an issue caused by Python source files that are part of the same Python + package being in separate directories. - Args: - srcs: The source files to copy and add to the filegroup. - strip_prefix: Path to the root of the files to copy. - dest: The directory to copy the source files into. - **kwargs: extra arguments that will be passesd to the filegroup. - """ - outs = [_RelativeOutputPath(s, strip_prefix, dest) for s in srcs] + Args: + srcs: The source files to copy and add to the filegroup. + strip_prefix: Path to the root of the files to copy. + dest: The directory to copy the source files into. + **kwargs: extra arguments that will be passesd to the filegroup. + """ + outs = [_RelativeOutputPath(s, strip_prefix, dest) for s in srcs] - native.genrule( - name = name + "_genrule", - srcs = srcs, - outs = outs, - cmd = " && ".join( - ["cp $(location %s) $(location %s)" % - (s, _RelativeOutputPath(s, strip_prefix, dest)) for s in srcs]), - ) + native.genrule( + name = name + "_genrule", + srcs = srcs, + outs = outs, + cmd = " && ".join( + ["cp $(location %s) $(location %s)" % + (s, _RelativeOutputPath(s, strip_prefix, dest)) for s in srcs], + ), + ) - native.filegroup( - name = name, - srcs = outs, - **kwargs) + native.filegroup( + name = name, + srcs = outs, + **kwargs + ) def py_proto_library( name, - srcs=[], - deps=[], - py_libs=[], - py_extra_srcs=[], - include=None, - default_runtime="@com_google_protobuf//:protobuf_python", - protoc="@com_google_protobuf//:protoc", - use_grpc_plugin=False, + srcs = [], + deps = [], + py_libs = [], + py_extra_srcs = [], + include = None, + default_runtime = "@com_google_protobuf//:protobuf_python", + protoc = "@com_google_protobuf//:protoc", + use_grpc_plugin = False, **kargs): - """Bazel rule to create a Python protobuf library from proto source files + """Bazel rule to create a Python protobuf library from proto source files - NOTE: the rule is only an internal workaround to generate protos. The - interface may change and the rule may be removed when bazel has introduced - the native rule. + NOTE: the rule is only an internal workaround to generate protos. The + interface may change and the rule may be removed when bazel has introduced + the native rule. - Args: - name: the name of the py_proto_library. - srcs: the .proto files of the py_proto_library. - deps: a list of dependency labels; must be py_proto_library. - py_libs: a list of other py_library targets depended by the generated - py_library. - py_extra_srcs: extra source files that will be added to the output - py_library. This attribute is used for internal bootstrapping. - include: a string indicating the include path of the .proto files. - default_runtime: the implicitly default runtime which will be depended on by - the generated py_library target. - protoc: the label of the protocol compiler to generate the sources. - use_grpc_plugin: a flag to indicate whether to call the Python C++ plugin - when processing the proto files. - **kargs: other keyword arguments that are passed to cc_library. + Args: + name: the name of the py_proto_library. + srcs: the .proto files of the py_proto_library. + deps: a list of dependency labels; must be py_proto_library. + py_libs: a list of other py_library targets depended by the generated + py_library. + py_extra_srcs: extra source files that will be added to the output + py_library. This attribute is used for internal bootstrapping. + include: a string indicating the include path of the .proto files. + default_runtime: the implicitly default runtime which will be depended on by + the generated py_library target. + protoc: the label of the protocol compiler to generate the sources. + use_grpc_plugin: a flag to indicate whether to call the Python C++ plugin + when processing the proto files. + **kargs: other keyword arguments that are passed to cc_library. - """ - outs = _PyOuts(srcs, use_grpc_plugin) + """ + outs = _PyOuts(srcs, use_grpc_plugin) - includes = [] - if include != None: - includes = [include] + includes = [] + if include != None: + includes = [include] - grpc_python_plugin = None - if use_grpc_plugin: - grpc_python_plugin = "//external:grpc_python_plugin" - # Note: Generated grpc code depends on Python grpc module. This dependency - # is not explicitly listed in py_libs. Instead, host system is assumed to - # have grpc installed. + grpc_python_plugin = None + if use_grpc_plugin: + grpc_python_plugin = "//external:grpc_python_plugin" + # Note: Generated grpc code depends on Python grpc module. This dependency + # is not explicitly listed in py_libs. Instead, host system is assumed to + # have grpc installed. - proto_gen( - name=name + "_genproto", - srcs=srcs, - deps=[s + "_genproto" for s in deps], - includes=includes, - protoc=protoc, - gen_py=1, - outs=outs, - visibility=["//visibility:public"], - plugin=grpc_python_plugin, - plugin_language="grpc" - ) + proto_gen( + name = name + "_genproto", + srcs = srcs, + deps = [s + "_genproto" for s in deps], + includes = includes, + protoc = protoc, + gen_py = 1, + outs = outs, + visibility = ["//visibility:public"], + plugin = grpc_python_plugin, + plugin_language = "grpc", + ) - if default_runtime and not default_runtime in py_libs + deps: - py_libs = py_libs + [default_runtime] + if default_runtime and not default_runtime in py_libs + deps: + py_libs = py_libs + [default_runtime] - native.py_library( - name=name, - srcs=outs+py_extra_srcs, - deps=py_libs+deps, - imports=includes, - **kargs) + native.py_library( + name = name, + srcs = outs + py_extra_srcs, + deps = py_libs + deps, + imports = includes, + **kargs + ) def internal_protobuf_py_tests( - name, - modules=[], - **kargs): - """Bazel rules to create batch tests for protobuf internal. + name, + modules = [], + **kargs): + """Bazel rules to create batch tests for protobuf internal. - Args: - name: the name of the rule. - modules: a list of modules for tests. The macro will create a py_test for - each of the parameter with the source "google/protobuf/%s.py" - kargs: extra parameters that will be passed into the py_test. - - """ - for m in modules: - s = "python/google/protobuf/internal/%s.py" % m - native.py_test( - name="py_%s" % m, - srcs=[s], - main=s, - **kargs) + Args: + name: the name of the rule. + modules: a list of modules for tests. The macro will create a py_test for + each of the parameter with the source "google/protobuf/%s.py" + kargs: extra parameters that will be passed into the py_test. + """ + for m in modules: + s = "python/google/protobuf/internal/%s.py" % m + native.py_test( + name = "py_%s" % m, + srcs = [s], + main = s, + **kargs + ) def check_protobuf_required_bazel_version(): - """For WORKSPACE files, to check the installed version of bazel. + """For WORKSPACE files, to check the installed version of bazel. - This ensures bazel supports our approach to proto_library() depending on a - copied filegroup. (Fixed in bazel 0.5.4) - """ - expected = apple_common.dotted_version("0.5.4") - current = apple_common.dotted_version(native.bazel_version) - if current.compare_to(expected) < 0: - fail("Bazel must be newer than 0.5.4") + This ensures bazel supports our approach to proto_library() depending on a + copied filegroup. (Fixed in bazel 0.5.4) + """ + versions.check(minimum_bazel_version = "0.5.4") diff --git a/third_party/protobuf/protobuf.pc.in b/third_party/protobuf/protobuf.pc.in index 49014903..4e88b514 100644 --- a/third_party/protobuf/protobuf.pc.in +++ b/third_party/protobuf/protobuf.pc.in @@ -6,7 +6,7 @@ includedir=@includedir@ Name: Protocol Buffers Description: Google's Data Interchange Format Version: @VERSION@ -Libs: -L${libdir} -lprotobuf @PTHREAD_CFLAGS@ @PTHREAD_LIBS@ +Libs: -L${libdir} -lprotobuf @PTHREAD_LIBS@ Libs.private: @LIBS@ Cflags: -I${includedir} @PTHREAD_CFLAGS@ Conflicts: protobuf-lite diff --git a/third_party/protobuf/python/release/wheel/protobuf_optimized_pip.sh b/third_party/protobuf/python/release/wheel/protobuf_optimized_pip.sh index 98306f4c..07c2a093 100755 --- a/third_party/protobuf/python/release/wheel/protobuf_optimized_pip.sh +++ b/third_party/protobuf/python/release/wheel/protobuf_optimized_pip.sh @@ -39,7 +39,7 @@ PYTHON_VERSIONS=('cp27-cp27mu' 'cp33-cp33m' 'cp34-cp34m' 'cp35-cp35m' 'cp36-cp36 mkdir -p ${DIR} cd ${DIR} -curl -SsL -O https://github.com/google/protobuf/archive/v${PROTOBUF_VERSION}.tar.gz +curl -SsL -O https://github.com/protocolbuffers/protobuf/archive/v${PROTOBUF_VERSION}.tar.gz tar xzf v${PROTOBUF_VERSION}.tar.gz cd $DIR/protobuf-${PROTOBUF_VERSION} diff --git a/third_party/protobuf/src/Makefile.am b/third_party/protobuf/src/Makefile.am index 4bb77452..be18ba76 100644 --- a/third_party/protobuf/src/Makefile.am +++ b/third_party/protobuf/src/Makefile.am @@ -18,6 +18,8 @@ else PTHREAD_DEF = endif +PROTOBUF_VERSION = 19:0:0 + if GCC # Turn on all warnings except for sign comparison (we ignore sign comparison # in Google so our code base have tons of such warnings). @@ -74,10 +76,10 @@ nobase_include_HEADERS = \ google/protobuf/stubs/once.h \ google/protobuf/stubs/platform_macros.h \ google/protobuf/stubs/port.h \ - google/protobuf/stubs/singleton.h \ google/protobuf/stubs/status.h \ google/protobuf/stubs/stl_util.h \ google/protobuf/stubs/stringpiece.h \ + google/protobuf/stubs/strutil.h \ google/protobuf/stubs/template_util.h \ google/protobuf/any.pb.h \ google/protobuf/api.pb.h \ @@ -92,6 +94,7 @@ nobase_include_HEADERS = \ google/protobuf/dynamic_message.h \ google/protobuf/empty.pb.h \ google/protobuf/extension_set.h \ + google/protobuf/extension_set_inl.h \ google/protobuf/field_mask.pb.h \ google/protobuf/generated_enum_reflection.h \ google/protobuf/generated_enum_util.h \ @@ -112,6 +115,10 @@ nobase_include_HEADERS = \ google/protobuf/message_lite.h \ google/protobuf/metadata.h \ google/protobuf/metadata_lite.h \ + google/protobuf/parse_context.h \ + google/protobuf/port.h \ + google/protobuf/port_def.inc \ + google/protobuf/port_undef.inc \ google/protobuf/reflection.h \ google/protobuf/reflection_ops.h \ google/protobuf/repeated_field.h \ @@ -124,7 +131,6 @@ nobase_include_HEADERS = \ google/protobuf/unknown_field_set.h \ google/protobuf/wire_format.h \ google/protobuf/wire_format_lite.h \ - google/protobuf/wire_format_lite_inl.h \ google/protobuf/wrappers.pb.h \ google/protobuf/io/coded_stream.h \ $(GZHEADERS) \ @@ -163,8 +169,8 @@ nobase_include_HEADERS = \ lib_LTLIBRARIES = libprotobuf-lite.la libprotobuf.la libprotoc.la -libprotobuf_lite_la_LIBADD = $(PTHREAD_LIBS) -libprotobuf_lite_la_LDFLAGS = -version-info 17:0:0 -export-dynamic -no-undefined +libprotobuf_lite_la_LIBADD = $(PTHREAD_LIBS) $(LIBATOMIC_LIBS) +libprotobuf_lite_la_LDFLAGS = -version-info $(PROTOBUF_VERSION) -export-dynamic -no-undefined if HAVE_LD_VERSION_SCRIPT libprotobuf_lite_la_LDFLAGS += -Wl,--version-script=$(srcdir)/libprotobuf-lite.map EXTRA_libprotobuf_lite_la_DEPENDENCIES = libprotobuf-lite.map @@ -176,8 +182,8 @@ libprotobuf_lite_la_SOURCES = \ google/protobuf/stubs/hash.h \ google/protobuf/stubs/int128.cc \ google/protobuf/stubs/int128.h \ - google/protobuf/stubs/io_win32.cc \ - google/protobuf/stubs/io_win32.h \ + google/protobuf/io/io_win32.cc \ + google/protobuf/io/io_win32.h \ google/protobuf/stubs/map_util.h \ google/protobuf/stubs/mathutil.h \ google/protobuf/stubs/status.cc \ @@ -191,26 +197,27 @@ libprotobuf_lite_la_SOURCES = \ google/protobuf/stubs/stringprintf.h \ google/protobuf/stubs/structurally_valid.cc \ google/protobuf/stubs/strutil.cc \ - google/protobuf/stubs/strutil.h \ google/protobuf/stubs/time.cc \ google/protobuf/stubs/time.h \ + google/protobuf/any_lite.cc \ google/protobuf/arena.cc \ - google/protobuf/arenastring.cc \ google/protobuf/extension_set.cc \ google/protobuf/generated_message_util.cc \ google/protobuf/generated_message_table_driven_lite.h \ google/protobuf/generated_message_table_driven_lite.cc \ google/protobuf/implicit_weak_message.cc \ google/protobuf/message_lite.cc \ + google/protobuf/parse_context.cc \ google/protobuf/repeated_field.cc \ google/protobuf/wire_format_lite.cc \ google/protobuf/io/coded_stream.cc \ google/protobuf/io/coded_stream_inl.h \ + google/protobuf/io/strtod.cc \ google/protobuf/io/zero_copy_stream.cc \ google/protobuf/io/zero_copy_stream_impl_lite.cc -libprotobuf_la_LIBADD = $(PTHREAD_LIBS) -libprotobuf_la_LDFLAGS = -version-info 17:0:0 -export-dynamic -no-undefined +libprotobuf_la_LIBADD = $(PTHREAD_LIBS) $(LIBATOMIC_LIBS) +libprotobuf_la_LDFLAGS = -version-info $(PROTOBUF_VERSION) -export-dynamic -no-undefined if HAVE_LD_VERSION_SCRIPT libprotobuf_la_LDFLAGS += -Wl,--version-script=$(srcdir)/libprotobuf.map EXTRA_libprotobuf_la_DEPENDENCIES = libprotobuf.map @@ -250,7 +257,6 @@ libprotobuf_la_SOURCES = \ google/protobuf/wrappers.pb.cc \ google/protobuf/io/gzip_stream.cc \ google/protobuf/io/printer.cc \ - google/protobuf/io/strtod.cc \ google/protobuf/io/tokenizer.cc \ google/protobuf/io/zero_copy_stream_impl.cc \ google/protobuf/compiler/importer.cc \ @@ -301,7 +307,7 @@ libprotobuf_la_SOURCES = \ nodist_libprotobuf_la_SOURCES = $(nodist_libprotobuf_lite_la_SOURCES) libprotoc_la_LIBADD = $(PTHREAD_LIBS) libprotobuf.la -libprotoc_la_LDFLAGS = -version-info 17:0:0 -export-dynamic -no-undefined +libprotoc_la_LDFLAGS = -version-info $(PROTOBUF_VERSION) -export-dynamic -no-undefined if HAVE_LD_VERSION_SCRIPT libprotoc_la_LDFLAGS += -Wl,--version-script=$(srcdir)/libprotoc.map EXTRA_libprotoc_la_DEPENDENCIES = libprotoc.map @@ -311,6 +317,7 @@ libprotoc_la_SOURCES = \ google/protobuf/compiler/command_line_interface.cc \ google/protobuf/compiler/plugin.cc \ google/protobuf/compiler/plugin.pb.cc \ + google/protobuf/compiler/scc.h \ google/protobuf/compiler/subprocess.cc \ google/protobuf/compiler/subprocess.h \ google/protobuf/compiler/zip_writer.cc \ @@ -367,10 +374,6 @@ libprotoc_la_SOURCES = \ google/protobuf/compiler/java/java_generator_factory.h \ google/protobuf/compiler/java/java_helpers.cc \ google/protobuf/compiler/java/java_helpers.h \ - google/protobuf/compiler/java/java_lazy_message_field.cc \ - google/protobuf/compiler/java/java_lazy_message_field.h \ - google/protobuf/compiler/java/java_lazy_message_field_lite.cc\ - google/protobuf/compiler/java/java_lazy_message_field_lite.h \ google/protobuf/compiler/java/java_map_field.cc \ google/protobuf/compiler/java/java_map_field.h \ google/protobuf/compiler/java/java_map_field_lite.cc \ @@ -425,6 +428,7 @@ libprotoc_la_SOURCES = \ google/protobuf/compiler/objectivec/objectivec_message.h \ google/protobuf/compiler/objectivec/objectivec_message_field.cc \ google/protobuf/compiler/objectivec/objectivec_message_field.h \ + google/protobuf/compiler/objectivec/objectivec_nsobject_methods.h \ google/protobuf/compiler/objectivec/objectivec_oneof.cc \ google/protobuf/compiler/objectivec/objectivec_oneof.h \ google/protobuf/compiler/objectivec/objectivec_primitive_field.cc \ @@ -503,6 +507,7 @@ protoc_inputs = \ google/protobuf/unittest_preserve_unknown_enum2.proto \ google/protobuf/unittest_preserve_unknown_enum.proto \ google/protobuf/unittest.proto \ + google/protobuf/unittest_proto3.proto \ google/protobuf/unittest_proto3_arena.proto \ google/protobuf/unittest_proto3_arena_lite.proto \ google/protobuf/unittest_proto3_lite.proto \ @@ -518,15 +523,14 @@ protoc_inputs = \ google/protobuf/util/internal/testdata/struct.proto \ google/protobuf/util/internal/testdata/timestamp_duration.proto \ google/protobuf/util/internal/testdata/wrappers.proto \ + google/protobuf/util/json_format.proto \ google/protobuf/util/json_format_proto3.proto \ google/protobuf/util/message_differencer_unittest.proto \ google/protobuf/compiler/cpp/cpp_test_large_enum_value.proto EXTRA_DIST = \ $(protoc_inputs) \ - $(js_well_known_types_sources) \ solaris/libstdc++.la \ - google/protobuf/unittest_proto3.proto \ google/protobuf/test_messages_proto3.proto \ google/protobuf/test_messages_proto2.proto \ google/protobuf/io/gzip_stream.h \ @@ -549,6 +553,14 @@ EXTRA_DIST = \ google/protobuf/util/package_info.h \ google/protobuf/compiler/ruby/ruby_generated_code.proto \ google/protobuf/compiler/ruby/ruby_generated_code_pb.rb \ + google/protobuf/compiler/ruby/ruby_generated_code_proto2.proto \ + google/protobuf/compiler/ruby/ruby_generated_code_proto2_pb.rb \ + google/protobuf/compiler/ruby/ruby_generated_pkg_explicit.proto \ + google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy.proto \ + google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy_pb.rb \ + google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_pb.rb \ + google/protobuf/compiler/ruby/ruby_generated_pkg_implicit.proto \ + google/protobuf/compiler/ruby/ruby_generated_pkg_implicit_pb.rb \ google/protobuf/compiler/package_info.h \ google/protobuf/compiler/zip_output_unittest.sh \ libprotobuf-lite.map \ @@ -624,6 +636,8 @@ protoc_outputs = \ google/protobuf/unittest_preserve_unknown_enum2.pb.h \ google/protobuf/unittest_preserve_unknown_enum.pb.cc \ google/protobuf/unittest_preserve_unknown_enum.pb.h \ + google/protobuf/unittest_proto3.pb.cc \ + google/protobuf/unittest_proto3.pb.h \ google/protobuf/unittest_proto3_arena.pb.cc \ google/protobuf/unittest_proto3_arena.pb.h \ google/protobuf/unittest_proto3_arena_lite.pb.cc \ @@ -654,6 +668,8 @@ protoc_outputs = \ google/protobuf/util/internal/testdata/timestamp_duration.pb.h \ google/protobuf/util/internal/testdata/wrappers.pb.cc \ google/protobuf/util/internal/testdata/wrappers.pb.h \ + google/protobuf/util/json_format.pb.cc \ + google/protobuf/util/json_format.pb.h \ google/protobuf/util/json_format_proto3.pb.cc \ google/protobuf/util/json_format_proto3.pb.h \ google/protobuf/util/message_differencer_unittest.pb.cc \ @@ -687,6 +703,7 @@ COMMON_TEST_SOURCES = \ google/protobuf/test_util.cc \ google/protobuf/test_util.h \ google/protobuf/test_util.inc \ + google/protobuf/test_util2.h \ google/protobuf/testing/googletest.cc \ google/protobuf/testing/googletest.h \ google/protobuf/testing/file.cc \ @@ -713,7 +730,7 @@ protobuf_test_SOURCES = \ google/protobuf/stubs/bytestream_unittest.cc \ google/protobuf/stubs/common_unittest.cc \ google/protobuf/stubs/int128_unittest.cc \ - google/protobuf/stubs/io_win32_unittest.cc \ + google/protobuf/io/io_win32_unittest.cc \ google/protobuf/stubs/statusor_test.cc \ google/protobuf/stubs/status_test.cc \ google/protobuf/stubs/stringpiece_unittest.cc \ @@ -740,6 +757,7 @@ protobuf_test_SOURCES = \ google/protobuf/proto3_arena_lite_unittest.cc \ google/protobuf/proto3_arena_unittest.cc \ google/protobuf/proto3_lite_unittest.cc \ + google/protobuf/proto3_lite_unittest.inc \ google/protobuf/reflection_ops_unittest.cc \ google/protobuf/repeated_field_reflection_unittest.cc \ google/protobuf/repeated_field_unittest.cc \ diff --git a/third_party/protobuf/src/Makefile.in b/third_party/protobuf/src/Makefile.in index c971a24f..13990a73 100644 --- a/third_party/protobuf/src/Makefile.in +++ b/third_party/protobuf/src/Makefile.in @@ -156,27 +156,29 @@ am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" \ "$(DESTDIR)$(protodir)" "$(DESTDIR)$(includedir)" LTLIBRARIES = $(lib_LTLIBRARIES) am__DEPENDENCIES_1 = -libprotobuf_lite_la_DEPENDENCIES = $(am__DEPENDENCIES_1) +libprotobuf_lite_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \ + $(am__DEPENDENCIES_1) am__dirstamp = $(am__leading_dot)dirstamp am_libprotobuf_lite_la_OBJECTS = google/protobuf/stubs/bytestream.lo \ google/protobuf/stubs/common.lo \ - google/protobuf/stubs/int128.lo \ - google/protobuf/stubs/io_win32.lo \ + google/protobuf/stubs/int128.lo google/protobuf/io/io_win32.lo \ google/protobuf/stubs/status.lo \ google/protobuf/stubs/statusor.lo \ google/protobuf/stubs/stringpiece.lo \ google/protobuf/stubs/stringprintf.lo \ google/protobuf/stubs/structurally_valid.lo \ google/protobuf/stubs/strutil.lo google/protobuf/stubs/time.lo \ - google/protobuf/arena.lo google/protobuf/arenastring.lo \ + google/protobuf/any_lite.lo google/protobuf/arena.lo \ google/protobuf/extension_set.lo \ google/protobuf/generated_message_util.lo \ google/protobuf/generated_message_table_driven_lite.lo \ google/protobuf/implicit_weak_message.lo \ google/protobuf/message_lite.lo \ + google/protobuf/parse_context.lo \ google/protobuf/repeated_field.lo \ google/protobuf/wire_format_lite.lo \ google/protobuf/io/coded_stream.lo \ + google/protobuf/io/strtod.lo \ google/protobuf/io/zero_copy_stream.lo \ google/protobuf/io/zero_copy_stream_impl_lite.lo libprotobuf_lite_la_OBJECTS = $(am_libprotobuf_lite_la_OBJECTS) @@ -188,26 +190,28 @@ libprotobuf_lite_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CXXLD) \ $(AM_CXXFLAGS) $(CXXFLAGS) $(libprotobuf_lite_la_LDFLAGS) \ $(LDFLAGS) -o $@ -libprotobuf_la_DEPENDENCIES = $(am__DEPENDENCIES_1) +libprotobuf_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \ + $(am__DEPENDENCIES_1) am__objects_1 = google/protobuf/stubs/bytestream.lo \ google/protobuf/stubs/common.lo \ - google/protobuf/stubs/int128.lo \ - google/protobuf/stubs/io_win32.lo \ + google/protobuf/stubs/int128.lo google/protobuf/io/io_win32.lo \ google/protobuf/stubs/status.lo \ google/protobuf/stubs/statusor.lo \ google/protobuf/stubs/stringpiece.lo \ google/protobuf/stubs/stringprintf.lo \ google/protobuf/stubs/structurally_valid.lo \ google/protobuf/stubs/strutil.lo google/protobuf/stubs/time.lo \ - google/protobuf/arena.lo google/protobuf/arenastring.lo \ + google/protobuf/any_lite.lo google/protobuf/arena.lo \ google/protobuf/extension_set.lo \ google/protobuf/generated_message_util.lo \ google/protobuf/generated_message_table_driven_lite.lo \ google/protobuf/implicit_weak_message.lo \ google/protobuf/message_lite.lo \ + google/protobuf/parse_context.lo \ google/protobuf/repeated_field.lo \ google/protobuf/wire_format_lite.lo \ google/protobuf/io/coded_stream.lo \ + google/protobuf/io/strtod.lo \ google/protobuf/io/zero_copy_stream.lo \ google/protobuf/io/zero_copy_stream_impl_lite.lo am_libprotobuf_la_OBJECTS = $(am__objects_1) google/protobuf/any.pb.lo \ @@ -231,8 +235,7 @@ am_libprotobuf_la_OBJECTS = $(am__objects_1) google/protobuf/any.pb.lo \ google/protobuf/unknown_field_set.lo \ google/protobuf/wire_format.lo google/protobuf/wrappers.pb.lo \ google/protobuf/io/gzip_stream.lo \ - google/protobuf/io/printer.lo google/protobuf/io/strtod.lo \ - google/protobuf/io/tokenizer.lo \ + google/protobuf/io/printer.lo google/protobuf/io/tokenizer.lo \ google/protobuf/io/zero_copy_stream_impl.lo \ google/protobuf/compiler/importer.lo \ google/protobuf/compiler/parser.lo \ @@ -297,8 +300,6 @@ am_libprotoc_la_OBJECTS = google/protobuf/compiler/code_generator.lo \ google/protobuf/compiler/java/java_generator.lo \ google/protobuf/compiler/java/java_generator_factory.lo \ google/protobuf/compiler/java/java_helpers.lo \ - google/protobuf/compiler/java/java_lazy_message_field.lo \ - google/protobuf/compiler/java/java_lazy_message_field_lite.lo \ google/protobuf/compiler/java/java_map_field.lo \ google/protobuf/compiler/java/java_map_field_lite.lo \ google/protobuf/compiler/java/java_message.lo \ @@ -387,6 +388,7 @@ am__objects_3 = $(am__objects_2) \ google/protobuf/no_warning_test-unittest.pb.$(OBJEXT) \ google/protobuf/no_warning_test-unittest_preserve_unknown_enum2.pb.$(OBJEXT) \ google/protobuf/no_warning_test-unittest_preserve_unknown_enum.pb.$(OBJEXT) \ + google/protobuf/no_warning_test-unittest_proto3.pb.$(OBJEXT) \ google/protobuf/no_warning_test-unittest_proto3_arena.pb.$(OBJEXT) \ google/protobuf/no_warning_test-unittest_proto3_arena_lite.pb.$(OBJEXT) \ google/protobuf/no_warning_test-unittest_proto3_lite.pb.$(OBJEXT) \ @@ -402,6 +404,7 @@ am__objects_3 = $(am__objects_2) \ google/protobuf/util/internal/testdata/no_warning_test-struct.pb.$(OBJEXT) \ google/protobuf/util/internal/testdata/no_warning_test-timestamp_duration.pb.$(OBJEXT) \ google/protobuf/util/internal/testdata/no_warning_test-wrappers.pb.$(OBJEXT) \ + google/protobuf/util/no_warning_test-json_format.pb.$(OBJEXT) \ google/protobuf/util/no_warning_test-json_format_proto3.pb.$(OBJEXT) \ google/protobuf/util/no_warning_test-message_differencer_unittest.pb.$(OBJEXT) nodist_no_warning_test_OBJECTS = \ @@ -453,6 +456,7 @@ am__objects_6 = $(am__objects_5) \ google/protobuf/protobuf_lazy_descriptor_test-unittest.pb.$(OBJEXT) \ google/protobuf/protobuf_lazy_descriptor_test-unittest_preserve_unknown_enum2.pb.$(OBJEXT) \ google/protobuf/protobuf_lazy_descriptor_test-unittest_preserve_unknown_enum.pb.$(OBJEXT) \ + google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3.pb.$(OBJEXT) \ google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3_arena.pb.$(OBJEXT) \ google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3_arena_lite.pb.$(OBJEXT) \ google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3_lite.pb.$(OBJEXT) \ @@ -468,6 +472,7 @@ am__objects_6 = $(am__objects_5) \ google/protobuf/util/internal/testdata/protobuf_lazy_descriptor_test-struct.pb.$(OBJEXT) \ google/protobuf/util/internal/testdata/protobuf_lazy_descriptor_test-timestamp_duration.pb.$(OBJEXT) \ google/protobuf/util/internal/testdata/protobuf_lazy_descriptor_test-wrappers.pb.$(OBJEXT) \ + google/protobuf/util/protobuf_lazy_descriptor_test-json_format.pb.$(OBJEXT) \ google/protobuf/util/protobuf_lazy_descriptor_test-json_format_proto3.pb.$(OBJEXT) \ google/protobuf/util/protobuf_lazy_descriptor_test-message_differencer_unittest.pb.$(OBJEXT) nodist_protobuf_lazy_descriptor_test_OBJECTS = $(am__objects_6) @@ -537,7 +542,7 @@ am__objects_11 = \ am_protobuf_test_OBJECTS = google/protobuf/stubs/protobuf_test-bytestream_unittest.$(OBJEXT) \ google/protobuf/stubs/protobuf_test-common_unittest.$(OBJEXT) \ google/protobuf/stubs/protobuf_test-int128_unittest.$(OBJEXT) \ - google/protobuf/stubs/protobuf_test-io_win32_unittest.$(OBJEXT) \ + google/protobuf/io/protobuf_test-io_win32_unittest.$(OBJEXT) \ google/protobuf/stubs/protobuf_test-statusor_test.$(OBJEXT) \ google/protobuf/stubs/protobuf_test-status_test.$(OBJEXT) \ google/protobuf/stubs/protobuf_test-stringpiece_unittest.$(OBJEXT) \ @@ -639,6 +644,7 @@ am__objects_13 = $(am__objects_12) \ google/protobuf/protobuf_test-unittest.pb.$(OBJEXT) \ google/protobuf/protobuf_test-unittest_preserve_unknown_enum2.pb.$(OBJEXT) \ google/protobuf/protobuf_test-unittest_preserve_unknown_enum.pb.$(OBJEXT) \ + google/protobuf/protobuf_test-unittest_proto3.pb.$(OBJEXT) \ google/protobuf/protobuf_test-unittest_proto3_arena.pb.$(OBJEXT) \ google/protobuf/protobuf_test-unittest_proto3_arena_lite.pb.$(OBJEXT) \ google/protobuf/protobuf_test-unittest_proto3_lite.pb.$(OBJEXT) \ @@ -654,6 +660,7 @@ am__objects_13 = $(am__objects_12) \ google/protobuf/util/internal/testdata/protobuf_test-struct.pb.$(OBJEXT) \ google/protobuf/util/internal/testdata/protobuf_test-timestamp_duration.pb.$(OBJEXT) \ google/protobuf/util/internal/testdata/protobuf_test-wrappers.pb.$(OBJEXT) \ + google/protobuf/util/protobuf_test-json_format.pb.$(OBJEXT) \ google/protobuf/util/protobuf_test-json_format_proto3.pb.$(OBJEXT) \ google/protobuf/util/protobuf_test-message_differencer_unittest.pb.$(OBJEXT) nodist_protobuf_test_OBJECTS = $(am__objects_13) @@ -772,10 +779,10 @@ am__nobase_include_HEADERS_DIST = google/protobuf/stubs/callback.h \ google/protobuf/stubs/logging.h google/protobuf/stubs/macros.h \ google/protobuf/stubs/mutex.h google/protobuf/stubs/once.h \ google/protobuf/stubs/platform_macros.h \ - google/protobuf/stubs/port.h google/protobuf/stubs/singleton.h \ - google/protobuf/stubs/status.h \ + google/protobuf/stubs/port.h google/protobuf/stubs/status.h \ google/protobuf/stubs/stl_util.h \ google/protobuf/stubs/stringpiece.h \ + google/protobuf/stubs/strutil.h \ google/protobuf/stubs/template_util.h google/protobuf/any.pb.h \ google/protobuf/api.pb.h google/protobuf/any.h \ google/protobuf/arena.h google/protobuf/arena_impl.h \ @@ -785,6 +792,7 @@ am__nobase_include_HEADERS_DIST = google/protobuf/stubs/callback.h \ google/protobuf/duration.pb.h \ google/protobuf/dynamic_message.h google/protobuf/empty.pb.h \ google/protobuf/extension_set.h \ + google/protobuf/extension_set_inl.h \ google/protobuf/field_mask.pb.h \ google/protobuf/generated_enum_reflection.h \ google/protobuf/generated_enum_util.h \ @@ -799,8 +807,10 @@ am__nobase_include_HEADERS_DIST = google/protobuf/stubs/callback.h \ google/protobuf/map_field_lite.h google/protobuf/map.h \ google/protobuf/map_type_handler.h google/protobuf/message.h \ google/protobuf/message_lite.h google/protobuf/metadata.h \ - google/protobuf/metadata_lite.h google/protobuf/reflection.h \ - google/protobuf/reflection_ops.h \ + google/protobuf/metadata_lite.h \ + google/protobuf/parse_context.h google/protobuf/port.h \ + google/protobuf/port_def.inc google/protobuf/port_undef.inc \ + google/protobuf/reflection.h google/protobuf/reflection_ops.h \ google/protobuf/repeated_field.h google/protobuf/service.h \ google/protobuf/source_context.pb.h \ google/protobuf/struct.pb.h google/protobuf/text_format.h \ @@ -808,7 +818,6 @@ am__nobase_include_HEADERS_DIST = google/protobuf/stubs/callback.h \ google/protobuf/unknown_field_set.h \ google/protobuf/wire_format.h \ google/protobuf/wire_format_lite.h \ - google/protobuf/wire_format_lite_inl.h \ google/protobuf/wrappers.pb.h \ google/protobuf/io/coded_stream.h \ google/protobuf/io/gzip_stream.h google/protobuf/io/printer.h \ @@ -1095,6 +1104,7 @@ ISAINFO = @ISAINFO@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_FOR_BUILD = @LDFLAGS_FOR_BUILD@ +LIBATOMIC_LIBS = @LIBATOMIC_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ @@ -1208,6 +1218,7 @@ top_srcdir = @top_srcdir@ @HAVE_ZLIB_TRUE@ZLIB_DEF = -DHAVE_ZLIB=1 @HAVE_PTHREAD_FALSE@PTHREAD_DEF = @HAVE_PTHREAD_TRUE@PTHREAD_DEF = -DHAVE_PTHREAD=1 +PROTOBUF_VERSION = 19:0:0 @GCC_FALSE@NO_OPT_CXXFLAGS = $(PTHREAD_CFLAGS) $(PTHREAD_DEF) $(ZLIB_DEF) # Turn on all warnings except for sign comparison (we ignore sign comparison @@ -1256,10 +1267,10 @@ nobase_include_HEADERS = \ google/protobuf/stubs/once.h \ google/protobuf/stubs/platform_macros.h \ google/protobuf/stubs/port.h \ - google/protobuf/stubs/singleton.h \ google/protobuf/stubs/status.h \ google/protobuf/stubs/stl_util.h \ google/protobuf/stubs/stringpiece.h \ + google/protobuf/stubs/strutil.h \ google/protobuf/stubs/template_util.h \ google/protobuf/any.pb.h \ google/protobuf/api.pb.h \ @@ -1274,6 +1285,7 @@ nobase_include_HEADERS = \ google/protobuf/dynamic_message.h \ google/protobuf/empty.pb.h \ google/protobuf/extension_set.h \ + google/protobuf/extension_set_inl.h \ google/protobuf/field_mask.pb.h \ google/protobuf/generated_enum_reflection.h \ google/protobuf/generated_enum_util.h \ @@ -1294,6 +1306,10 @@ nobase_include_HEADERS = \ google/protobuf/message_lite.h \ google/protobuf/metadata.h \ google/protobuf/metadata_lite.h \ + google/protobuf/parse_context.h \ + google/protobuf/port.h \ + google/protobuf/port_def.inc \ + google/protobuf/port_undef.inc \ google/protobuf/reflection.h \ google/protobuf/reflection_ops.h \ google/protobuf/repeated_field.h \ @@ -1306,7 +1322,6 @@ nobase_include_HEADERS = \ google/protobuf/unknown_field_set.h \ google/protobuf/wire_format.h \ google/protobuf/wire_format_lite.h \ - google/protobuf/wire_format_lite_inl.h \ google/protobuf/wrappers.pb.h \ google/protobuf/io/coded_stream.h \ $(GZHEADERS) \ @@ -1344,9 +1359,9 @@ nobase_include_HEADERS = \ google/protobuf/util/message_differencer.h lib_LTLIBRARIES = libprotobuf-lite.la libprotobuf.la libprotoc.la -libprotobuf_lite_la_LIBADD = $(PTHREAD_LIBS) -libprotobuf_lite_la_LDFLAGS = -version-info 17:0:0 -export-dynamic \ - -no-undefined $(am__append_1) +libprotobuf_lite_la_LIBADD = $(PTHREAD_LIBS) $(LIBATOMIC_LIBS) +libprotobuf_lite_la_LDFLAGS = -version-info $(PROTOBUF_VERSION) \ + -export-dynamic -no-undefined $(am__append_1) @HAVE_LD_VERSION_SCRIPT_TRUE@EXTRA_libprotobuf_lite_la_DEPENDENCIES = libprotobuf-lite.map libprotobuf_lite_la_SOURCES = \ google/protobuf/stubs/bytestream.cc \ @@ -1355,8 +1370,8 @@ libprotobuf_lite_la_SOURCES = \ google/protobuf/stubs/hash.h \ google/protobuf/stubs/int128.cc \ google/protobuf/stubs/int128.h \ - google/protobuf/stubs/io_win32.cc \ - google/protobuf/stubs/io_win32.h \ + google/protobuf/io/io_win32.cc \ + google/protobuf/io/io_win32.h \ google/protobuf/stubs/map_util.h \ google/protobuf/stubs/mathutil.h \ google/protobuf/stubs/status.cc \ @@ -1370,27 +1385,28 @@ libprotobuf_lite_la_SOURCES = \ google/protobuf/stubs/stringprintf.h \ google/protobuf/stubs/structurally_valid.cc \ google/protobuf/stubs/strutil.cc \ - google/protobuf/stubs/strutil.h \ google/protobuf/stubs/time.cc \ google/protobuf/stubs/time.h \ + google/protobuf/any_lite.cc \ google/protobuf/arena.cc \ - google/protobuf/arenastring.cc \ google/protobuf/extension_set.cc \ google/protobuf/generated_message_util.cc \ google/protobuf/generated_message_table_driven_lite.h \ google/protobuf/generated_message_table_driven_lite.cc \ google/protobuf/implicit_weak_message.cc \ google/protobuf/message_lite.cc \ + google/protobuf/parse_context.cc \ google/protobuf/repeated_field.cc \ google/protobuf/wire_format_lite.cc \ google/protobuf/io/coded_stream.cc \ google/protobuf/io/coded_stream_inl.h \ + google/protobuf/io/strtod.cc \ google/protobuf/io/zero_copy_stream.cc \ google/protobuf/io/zero_copy_stream_impl_lite.cc -libprotobuf_la_LIBADD = $(PTHREAD_LIBS) -libprotobuf_la_LDFLAGS = -version-info 17:0:0 -export-dynamic \ - -no-undefined $(am__append_2) +libprotobuf_la_LIBADD = $(PTHREAD_LIBS) $(LIBATOMIC_LIBS) +libprotobuf_la_LDFLAGS = -version-info $(PROTOBUF_VERSION) \ + -export-dynamic -no-undefined $(am__append_2) @HAVE_LD_VERSION_SCRIPT_TRUE@EXTRA_libprotobuf_la_DEPENDENCIES = libprotobuf.map libprotobuf_la_SOURCES = \ $(libprotobuf_lite_la_SOURCES) \ @@ -1427,7 +1443,6 @@ libprotobuf_la_SOURCES = \ google/protobuf/wrappers.pb.cc \ google/protobuf/io/gzip_stream.cc \ google/protobuf/io/printer.cc \ - google/protobuf/io/strtod.cc \ google/protobuf/io/tokenizer.cc \ google/protobuf/io/zero_copy_stream_impl.cc \ google/protobuf/compiler/importer.cc \ @@ -1477,14 +1492,15 @@ libprotobuf_la_SOURCES = \ nodist_libprotobuf_la_SOURCES = $(nodist_libprotobuf_lite_la_SOURCES) libprotoc_la_LIBADD = $(PTHREAD_LIBS) libprotobuf.la -libprotoc_la_LDFLAGS = -version-info 17:0:0 -export-dynamic \ - -no-undefined $(am__append_3) +libprotoc_la_LDFLAGS = -version-info $(PROTOBUF_VERSION) \ + -export-dynamic -no-undefined $(am__append_3) @HAVE_LD_VERSION_SCRIPT_TRUE@EXTRA_libprotoc_la_DEPENDENCIES = libprotoc.map libprotoc_la_SOURCES = \ google/protobuf/compiler/code_generator.cc \ google/protobuf/compiler/command_line_interface.cc \ google/protobuf/compiler/plugin.cc \ google/protobuf/compiler/plugin.pb.cc \ + google/protobuf/compiler/scc.h \ google/protobuf/compiler/subprocess.cc \ google/protobuf/compiler/subprocess.h \ google/protobuf/compiler/zip_writer.cc \ @@ -1541,10 +1557,6 @@ libprotoc_la_SOURCES = \ google/protobuf/compiler/java/java_generator_factory.h \ google/protobuf/compiler/java/java_helpers.cc \ google/protobuf/compiler/java/java_helpers.h \ - google/protobuf/compiler/java/java_lazy_message_field.cc \ - google/protobuf/compiler/java/java_lazy_message_field.h \ - google/protobuf/compiler/java/java_lazy_message_field_lite.cc\ - google/protobuf/compiler/java/java_lazy_message_field_lite.h \ google/protobuf/compiler/java/java_map_field.cc \ google/protobuf/compiler/java/java_map_field.h \ google/protobuf/compiler/java/java_map_field_lite.cc \ @@ -1599,6 +1611,7 @@ libprotoc_la_SOURCES = \ google/protobuf/compiler/objectivec/objectivec_message.h \ google/protobuf/compiler/objectivec/objectivec_message_field.cc \ google/protobuf/compiler/objectivec/objectivec_message_field.h \ + google/protobuf/compiler/objectivec/objectivec_nsobject_methods.h \ google/protobuf/compiler/objectivec/objectivec_oneof.cc \ google/protobuf/compiler/objectivec/objectivec_oneof.h \ google/protobuf/compiler/objectivec/objectivec_primitive_field.cc \ @@ -1675,6 +1688,7 @@ protoc_inputs = \ google/protobuf/unittest_preserve_unknown_enum2.proto \ google/protobuf/unittest_preserve_unknown_enum.proto \ google/protobuf/unittest.proto \ + google/protobuf/unittest_proto3.proto \ google/protobuf/unittest_proto3_arena.proto \ google/protobuf/unittest_proto3_arena_lite.proto \ google/protobuf/unittest_proto3_lite.proto \ @@ -1690,15 +1704,14 @@ protoc_inputs = \ google/protobuf/util/internal/testdata/struct.proto \ google/protobuf/util/internal/testdata/timestamp_duration.proto \ google/protobuf/util/internal/testdata/wrappers.proto \ + google/protobuf/util/json_format.proto \ google/protobuf/util/json_format_proto3.proto \ google/protobuf/util/message_differencer_unittest.proto \ google/protobuf/compiler/cpp/cpp_test_large_enum_value.proto EXTRA_DIST = \ $(protoc_inputs) \ - $(js_well_known_types_sources) \ solaris/libstdc++.la \ - google/protobuf/unittest_proto3.proto \ google/protobuf/test_messages_proto3.proto \ google/protobuf/test_messages_proto2.proto \ google/protobuf/io/gzip_stream.h \ @@ -1721,6 +1734,14 @@ EXTRA_DIST = \ google/protobuf/util/package_info.h \ google/protobuf/compiler/ruby/ruby_generated_code.proto \ google/protobuf/compiler/ruby/ruby_generated_code_pb.rb \ + google/protobuf/compiler/ruby/ruby_generated_code_proto2.proto \ + google/protobuf/compiler/ruby/ruby_generated_code_proto2_pb.rb \ + google/protobuf/compiler/ruby/ruby_generated_pkg_explicit.proto \ + google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy.proto \ + google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy_pb.rb \ + google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_pb.rb \ + google/protobuf/compiler/ruby/ruby_generated_pkg_implicit.proto \ + google/protobuf/compiler/ruby/ruby_generated_pkg_implicit_pb.rb \ google/protobuf/compiler/package_info.h \ google/protobuf/compiler/zip_output_unittest.sh \ libprotobuf-lite.map \ @@ -1796,6 +1817,8 @@ protoc_outputs = \ google/protobuf/unittest_preserve_unknown_enum2.pb.h \ google/protobuf/unittest_preserve_unknown_enum.pb.cc \ google/protobuf/unittest_preserve_unknown_enum.pb.h \ + google/protobuf/unittest_proto3.pb.cc \ + google/protobuf/unittest_proto3.pb.h \ google/protobuf/unittest_proto3_arena.pb.cc \ google/protobuf/unittest_proto3_arena.pb.h \ google/protobuf/unittest_proto3_arena_lite.pb.cc \ @@ -1826,6 +1849,8 @@ protoc_outputs = \ google/protobuf/util/internal/testdata/timestamp_duration.pb.h \ google/protobuf/util/internal/testdata/wrappers.pb.cc \ google/protobuf/util/internal/testdata/wrappers.pb.h \ + google/protobuf/util/json_format.pb.cc \ + google/protobuf/util/json_format.pb.h \ google/protobuf/util/json_format_proto3.pb.cc \ google/protobuf/util/json_format_proto3.pb.h \ google/protobuf/util/message_differencer_unittest.pb.cc \ @@ -1840,6 +1865,7 @@ COMMON_TEST_SOURCES = \ google/protobuf/test_util.cc \ google/protobuf/test_util.h \ google/protobuf/test_util.inc \ + google/protobuf/test_util2.h \ google/protobuf/testing/googletest.cc \ google/protobuf/testing/googletest.h \ google/protobuf/testing/file.cc \ @@ -1865,7 +1891,7 @@ protobuf_test_SOURCES = \ google/protobuf/stubs/bytestream_unittest.cc \ google/protobuf/stubs/common_unittest.cc \ google/protobuf/stubs/int128_unittest.cc \ - google/protobuf/stubs/io_win32_unittest.cc \ + google/protobuf/io/io_win32_unittest.cc \ google/protobuf/stubs/statusor_test.cc \ google/protobuf/stubs/status_test.cc \ google/protobuf/stubs/stringpiece_unittest.cc \ @@ -1892,6 +1918,7 @@ protobuf_test_SOURCES = \ google/protobuf/proto3_arena_lite_unittest.cc \ google/protobuf/proto3_arena_unittest.cc \ google/protobuf/proto3_lite_unittest.cc \ + google/protobuf/proto3_lite_unittest.inc \ google/protobuf/reflection_ops_unittest.cc \ google/protobuf/repeated_field_reflection_unittest.cc \ google/protobuf/repeated_field_unittest.cc \ @@ -2107,9 +2134,14 @@ google/protobuf/stubs/common.lo: \ google/protobuf/stubs/int128.lo: \ google/protobuf/stubs/$(am__dirstamp) \ google/protobuf/stubs/$(DEPDIR)/$(am__dirstamp) -google/protobuf/stubs/io_win32.lo: \ - google/protobuf/stubs/$(am__dirstamp) \ - google/protobuf/stubs/$(DEPDIR)/$(am__dirstamp) +google/protobuf/io/$(am__dirstamp): + @$(MKDIR_P) google/protobuf/io + @: > google/protobuf/io/$(am__dirstamp) +google/protobuf/io/$(DEPDIR)/$(am__dirstamp): + @$(MKDIR_P) google/protobuf/io/$(DEPDIR) + @: > google/protobuf/io/$(DEPDIR)/$(am__dirstamp) +google/protobuf/io/io_win32.lo: google/protobuf/io/$(am__dirstamp) \ + google/protobuf/io/$(DEPDIR)/$(am__dirstamp) google/protobuf/stubs/status.lo: \ google/protobuf/stubs/$(am__dirstamp) \ google/protobuf/stubs/$(DEPDIR)/$(am__dirstamp) @@ -2136,9 +2168,9 @@ google/protobuf/$(am__dirstamp): google/protobuf/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) google/protobuf/$(DEPDIR) @: > google/protobuf/$(DEPDIR)/$(am__dirstamp) -google/protobuf/arena.lo: google/protobuf/$(am__dirstamp) \ +google/protobuf/any_lite.lo: google/protobuf/$(am__dirstamp) \ google/protobuf/$(DEPDIR)/$(am__dirstamp) -google/protobuf/arenastring.lo: google/protobuf/$(am__dirstamp) \ +google/protobuf/arena.lo: google/protobuf/$(am__dirstamp) \ google/protobuf/$(DEPDIR)/$(am__dirstamp) google/protobuf/extension_set.lo: google/protobuf/$(am__dirstamp) \ google/protobuf/$(DEPDIR)/$(am__dirstamp) @@ -2153,19 +2185,17 @@ google/protobuf/implicit_weak_message.lo: \ google/protobuf/$(DEPDIR)/$(am__dirstamp) google/protobuf/message_lite.lo: google/protobuf/$(am__dirstamp) \ google/protobuf/$(DEPDIR)/$(am__dirstamp) +google/protobuf/parse_context.lo: google/protobuf/$(am__dirstamp) \ + google/protobuf/$(DEPDIR)/$(am__dirstamp) google/protobuf/repeated_field.lo: google/protobuf/$(am__dirstamp) \ google/protobuf/$(DEPDIR)/$(am__dirstamp) google/protobuf/wire_format_lite.lo: google/protobuf/$(am__dirstamp) \ google/protobuf/$(DEPDIR)/$(am__dirstamp) -google/protobuf/io/$(am__dirstamp): - @$(MKDIR_P) google/protobuf/io - @: > google/protobuf/io/$(am__dirstamp) -google/protobuf/io/$(DEPDIR)/$(am__dirstamp): - @$(MKDIR_P) google/protobuf/io/$(DEPDIR) - @: > google/protobuf/io/$(DEPDIR)/$(am__dirstamp) google/protobuf/io/coded_stream.lo: \ google/protobuf/io/$(am__dirstamp) \ google/protobuf/io/$(DEPDIR)/$(am__dirstamp) +google/protobuf/io/strtod.lo: google/protobuf/io/$(am__dirstamp) \ + google/protobuf/io/$(DEPDIR)/$(am__dirstamp) google/protobuf/io/zero_copy_stream.lo: \ google/protobuf/io/$(am__dirstamp) \ google/protobuf/io/$(DEPDIR)/$(am__dirstamp) @@ -2239,8 +2269,6 @@ google/protobuf/io/gzip_stream.lo: google/protobuf/io/$(am__dirstamp) \ google/protobuf/io/$(DEPDIR)/$(am__dirstamp) google/protobuf/io/printer.lo: google/protobuf/io/$(am__dirstamp) \ google/protobuf/io/$(DEPDIR)/$(am__dirstamp) -google/protobuf/io/strtod.lo: google/protobuf/io/$(am__dirstamp) \ - google/protobuf/io/$(DEPDIR)/$(am__dirstamp) google/protobuf/io/tokenizer.lo: google/protobuf/io/$(am__dirstamp) \ google/protobuf/io/$(DEPDIR)/$(am__dirstamp) google/protobuf/io/zero_copy_stream_impl.lo: \ @@ -2444,12 +2472,6 @@ google/protobuf/compiler/java/java_generator_factory.lo: \ google/protobuf/compiler/java/java_helpers.lo: \ google/protobuf/compiler/java/$(am__dirstamp) \ google/protobuf/compiler/java/$(DEPDIR)/$(am__dirstamp) -google/protobuf/compiler/java/java_lazy_message_field.lo: \ - google/protobuf/compiler/java/$(am__dirstamp) \ - google/protobuf/compiler/java/$(DEPDIR)/$(am__dirstamp) -google/protobuf/compiler/java/java_lazy_message_field_lite.lo: \ - google/protobuf/compiler/java/$(am__dirstamp) \ - google/protobuf/compiler/java/$(DEPDIR)/$(am__dirstamp) google/protobuf/compiler/java/java_map_field.lo: \ google/protobuf/compiler/java/$(am__dirstamp) \ google/protobuf/compiler/java/$(DEPDIR)/$(am__dirstamp) @@ -2790,6 +2812,9 @@ google/protobuf/no_warning_test-unittest_preserve_unknown_enum2.pb.$(OBJEXT): \ google/protobuf/no_warning_test-unittest_preserve_unknown_enum.pb.$(OBJEXT): \ google/protobuf/$(am__dirstamp) \ google/protobuf/$(DEPDIR)/$(am__dirstamp) +google/protobuf/no_warning_test-unittest_proto3.pb.$(OBJEXT): \ + google/protobuf/$(am__dirstamp) \ + google/protobuf/$(DEPDIR)/$(am__dirstamp) google/protobuf/no_warning_test-unittest_proto3_arena.pb.$(OBJEXT): \ google/protobuf/$(am__dirstamp) \ google/protobuf/$(DEPDIR)/$(am__dirstamp) @@ -2841,6 +2866,9 @@ google/protobuf/util/internal/testdata/no_warning_test-timestamp_duration.pb.$(O google/protobuf/util/internal/testdata/no_warning_test-wrappers.pb.$(OBJEXT): \ google/protobuf/util/internal/testdata/$(am__dirstamp) \ google/protobuf/util/internal/testdata/$(DEPDIR)/$(am__dirstamp) +google/protobuf/util/no_warning_test-json_format.pb.$(OBJEXT): \ + google/protobuf/util/$(am__dirstamp) \ + google/protobuf/util/$(DEPDIR)/$(am__dirstamp) google/protobuf/util/no_warning_test-json_format_proto3.pb.$(OBJEXT): \ google/protobuf/util/$(am__dirstamp) \ google/protobuf/util/$(DEPDIR)/$(am__dirstamp) @@ -2971,6 +2999,9 @@ google/protobuf/protobuf_lazy_descriptor_test-unittest_preserve_unknown_enum2.pb google/protobuf/protobuf_lazy_descriptor_test-unittest_preserve_unknown_enum.pb.$(OBJEXT): \ google/protobuf/$(am__dirstamp) \ google/protobuf/$(DEPDIR)/$(am__dirstamp) +google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3.pb.$(OBJEXT): \ + google/protobuf/$(am__dirstamp) \ + google/protobuf/$(DEPDIR)/$(am__dirstamp) google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3_arena.pb.$(OBJEXT): \ google/protobuf/$(am__dirstamp) \ google/protobuf/$(DEPDIR)/$(am__dirstamp) @@ -3016,6 +3047,9 @@ google/protobuf/util/internal/testdata/protobuf_lazy_descriptor_test-timestamp_d google/protobuf/util/internal/testdata/protobuf_lazy_descriptor_test-wrappers.pb.$(OBJEXT): \ google/protobuf/util/internal/testdata/$(am__dirstamp) \ google/protobuf/util/internal/testdata/$(DEPDIR)/$(am__dirstamp) +google/protobuf/util/protobuf_lazy_descriptor_test-json_format.pb.$(OBJEXT): \ + google/protobuf/util/$(am__dirstamp) \ + google/protobuf/util/$(DEPDIR)/$(am__dirstamp) google/protobuf/util/protobuf_lazy_descriptor_test-json_format_proto3.pb.$(OBJEXT): \ google/protobuf/util/$(am__dirstamp) \ google/protobuf/util/$(DEPDIR)/$(am__dirstamp) @@ -3097,9 +3131,9 @@ google/protobuf/stubs/protobuf_test-common_unittest.$(OBJEXT): \ google/protobuf/stubs/protobuf_test-int128_unittest.$(OBJEXT): \ google/protobuf/stubs/$(am__dirstamp) \ google/protobuf/stubs/$(DEPDIR)/$(am__dirstamp) -google/protobuf/stubs/protobuf_test-io_win32_unittest.$(OBJEXT): \ - google/protobuf/stubs/$(am__dirstamp) \ - google/protobuf/stubs/$(DEPDIR)/$(am__dirstamp) +google/protobuf/io/protobuf_test-io_win32_unittest.$(OBJEXT): \ + google/protobuf/io/$(am__dirstamp) \ + google/protobuf/io/$(DEPDIR)/$(am__dirstamp) google/protobuf/stubs/protobuf_test-statusor_test.$(OBJEXT): \ google/protobuf/stubs/$(am__dirstamp) \ google/protobuf/stubs/$(DEPDIR)/$(am__dirstamp) @@ -3409,6 +3443,9 @@ google/protobuf/protobuf_test-unittest_preserve_unknown_enum2.pb.$(OBJEXT): \ google/protobuf/protobuf_test-unittest_preserve_unknown_enum.pb.$(OBJEXT): \ google/protobuf/$(am__dirstamp) \ google/protobuf/$(DEPDIR)/$(am__dirstamp) +google/protobuf/protobuf_test-unittest_proto3.pb.$(OBJEXT): \ + google/protobuf/$(am__dirstamp) \ + google/protobuf/$(DEPDIR)/$(am__dirstamp) google/protobuf/protobuf_test-unittest_proto3_arena.pb.$(OBJEXT): \ google/protobuf/$(am__dirstamp) \ google/protobuf/$(DEPDIR)/$(am__dirstamp) @@ -3454,6 +3491,9 @@ google/protobuf/util/internal/testdata/protobuf_test-timestamp_duration.pb.$(OBJ google/protobuf/util/internal/testdata/protobuf_test-wrappers.pb.$(OBJEXT): \ google/protobuf/util/internal/testdata/$(am__dirstamp) \ google/protobuf/util/internal/testdata/$(DEPDIR)/$(am__dirstamp) +google/protobuf/util/protobuf_test-json_format.pb.$(OBJEXT): \ + google/protobuf/util/$(am__dirstamp) \ + google/protobuf/util/$(DEPDIR)/$(am__dirstamp) google/protobuf/util/protobuf_test-json_format_proto3.pb.$(OBJEXT): \ google/protobuf/util/$(am__dirstamp) \ google/protobuf/util/$(DEPDIR)/$(am__dirstamp) @@ -3538,9 +3578,9 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/no_warning_test-no_warning_test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/any.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/any.pb.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/any_lite.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/api.pb.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/arena.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/arenastring.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/descriptor.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/descriptor.pb.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/descriptor_database.Plo@am__quote@ @@ -3588,10 +3628,12 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/no_warning_test-unittest_optimize_for.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/no_warning_test-unittest_preserve_unknown_enum.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/no_warning_test-unittest_preserve_unknown_enum2.pb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/no_warning_test-unittest_proto3.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/no_warning_test-unittest_proto3_arena.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/no_warning_test-unittest_proto3_arena_lite.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/no_warning_test-unittest_proto3_lite.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/no_warning_test-unittest_well_known_types.pb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/parse_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-any_test.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-arena_test_util.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-map_lite_unittest.pb.Po@am__quote@ @@ -3625,6 +3667,7 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-unittest_optimize_for.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-unittest_preserve_unknown_enum.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-unittest_preserve_unknown_enum2.pb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-unittest_proto3.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-unittest_proto3_arena.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-unittest_proto3_arena_lite.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-unittest_proto3_lite.pb.Po@am__quote@ @@ -3701,6 +3744,7 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/protobuf_test-unittest_optimize_for.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/protobuf_test-unittest_preserve_unknown_enum.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/protobuf_test-unittest_preserve_unknown_enum2.pb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/protobuf_test-unittest_proto3.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/protobuf_test-unittest_proto3_arena.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/protobuf_test-unittest_proto3_arena_lite.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/$(DEPDIR)/protobuf_test-unittest_proto3_lite.pb.Po@am__quote@ @@ -3793,8 +3837,6 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/compiler/java/$(DEPDIR)/java_generator.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/compiler/java/$(DEPDIR)/java_generator_factory.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/compiler/java/$(DEPDIR)/java_helpers.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/compiler/java/$(DEPDIR)/java_lazy_message_field.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/compiler/java/$(DEPDIR)/java_lazy_message_field_lite.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/compiler/java/$(DEPDIR)/java_map_field.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/compiler/java/$(DEPDIR)/java_map_field_lite.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/compiler/java/$(DEPDIR)/java_message.Plo@am__quote@ @@ -3834,8 +3876,10 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/compiler/ruby/$(DEPDIR)/ruby_generator.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/io/$(DEPDIR)/coded_stream.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/io/$(DEPDIR)/gzip_stream.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/io/$(DEPDIR)/io_win32.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/io/$(DEPDIR)/printer.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/io/$(DEPDIR)/protobuf_test-coded_stream_unittest.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/io/$(DEPDIR)/protobuf_test-io_win32_unittest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/io/$(DEPDIR)/protobuf_test-printer_unittest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/io/$(DEPDIR)/protobuf_test-tokenizer_unittest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/io/$(DEPDIR)/protobuf_test-zero_copy_stream_unittest.Po@am__quote@ @@ -3847,12 +3891,10 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/stubs/$(DEPDIR)/bytestream.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/stubs/$(DEPDIR)/common.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/stubs/$(DEPDIR)/int128.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/stubs/$(DEPDIR)/io_win32.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/stubs/$(DEPDIR)/mathlimits.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/stubs/$(DEPDIR)/protobuf_test-bytestream_unittest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/stubs/$(DEPDIR)/protobuf_test-common_unittest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/stubs/$(DEPDIR)/protobuf_test-int128_unittest.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/stubs/$(DEPDIR)/protobuf_test-io_win32_unittest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/stubs/$(DEPDIR)/protobuf_test-status_test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/stubs/$(DEPDIR)/protobuf_test-statusor_test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/stubs/$(DEPDIR)/protobuf_test-stringpiece_unittest.Po@am__quote@ @@ -3881,13 +3923,16 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/util/$(DEPDIR)/field_mask_util.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/util/$(DEPDIR)/json_util.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/util/$(DEPDIR)/message_differencer.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/util/$(DEPDIR)/no_warning_test-json_format.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/util/$(DEPDIR)/no_warning_test-json_format_proto3.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/util/$(DEPDIR)/no_warning_test-message_differencer_unittest.pb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/util/$(DEPDIR)/protobuf_lazy_descriptor_test-json_format.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/util/$(DEPDIR)/protobuf_lazy_descriptor_test-json_format_proto3.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/util/$(DEPDIR)/protobuf_lazy_descriptor_test-message_differencer_unittest.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/util/$(DEPDIR)/protobuf_test-delimited_message_util_test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/util/$(DEPDIR)/protobuf_test-field_comparator_test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/util/$(DEPDIR)/protobuf_test-field_mask_util_test.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/util/$(DEPDIR)/protobuf_test-json_format.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/util/$(DEPDIR)/protobuf_test-json_format_proto3.pb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/util/$(DEPDIR)/protobuf_test-json_util_test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@google/protobuf/util/$(DEPDIR)/protobuf_test-message_differencer_unittest.Po@am__quote@ @@ -4436,6 +4481,20 @@ google/protobuf/no_warning_test-unittest_preserve_unknown_enum.pb.obj: google/pr @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(no_warning_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/no_warning_test-unittest_preserve_unknown_enum.pb.obj `if test -f 'google/protobuf/unittest_preserve_unknown_enum.pb.cc'; then $(CYGPATH_W) 'google/protobuf/unittest_preserve_unknown_enum.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/unittest_preserve_unknown_enum.pb.cc'; fi` +google/protobuf/no_warning_test-unittest_proto3.pb.o: google/protobuf/unittest_proto3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(no_warning_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/no_warning_test-unittest_proto3.pb.o -MD -MP -MF google/protobuf/$(DEPDIR)/no_warning_test-unittest_proto3.pb.Tpo -c -o google/protobuf/no_warning_test-unittest_proto3.pb.o `test -f 'google/protobuf/unittest_proto3.pb.cc' || echo '$(srcdir)/'`google/protobuf/unittest_proto3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/$(DEPDIR)/no_warning_test-unittest_proto3.pb.Tpo google/protobuf/$(DEPDIR)/no_warning_test-unittest_proto3.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='google/protobuf/unittest_proto3.pb.cc' object='google/protobuf/no_warning_test-unittest_proto3.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(no_warning_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/no_warning_test-unittest_proto3.pb.o `test -f 'google/protobuf/unittest_proto3.pb.cc' || echo '$(srcdir)/'`google/protobuf/unittest_proto3.pb.cc + +google/protobuf/no_warning_test-unittest_proto3.pb.obj: google/protobuf/unittest_proto3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(no_warning_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/no_warning_test-unittest_proto3.pb.obj -MD -MP -MF google/protobuf/$(DEPDIR)/no_warning_test-unittest_proto3.pb.Tpo -c -o google/protobuf/no_warning_test-unittest_proto3.pb.obj `if test -f 'google/protobuf/unittest_proto3.pb.cc'; then $(CYGPATH_W) 'google/protobuf/unittest_proto3.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/unittest_proto3.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/$(DEPDIR)/no_warning_test-unittest_proto3.pb.Tpo google/protobuf/$(DEPDIR)/no_warning_test-unittest_proto3.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='google/protobuf/unittest_proto3.pb.cc' object='google/protobuf/no_warning_test-unittest_proto3.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(no_warning_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/no_warning_test-unittest_proto3.pb.obj `if test -f 'google/protobuf/unittest_proto3.pb.cc'; then $(CYGPATH_W) 'google/protobuf/unittest_proto3.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/unittest_proto3.pb.cc'; fi` + google/protobuf/no_warning_test-unittest_proto3_arena.pb.o: google/protobuf/unittest_proto3_arena.pb.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(no_warning_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/no_warning_test-unittest_proto3_arena.pb.o -MD -MP -MF google/protobuf/$(DEPDIR)/no_warning_test-unittest_proto3_arena.pb.Tpo -c -o google/protobuf/no_warning_test-unittest_proto3_arena.pb.o `test -f 'google/protobuf/unittest_proto3_arena.pb.cc' || echo '$(srcdir)/'`google/protobuf/unittest_proto3_arena.pb.cc @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/$(DEPDIR)/no_warning_test-unittest_proto3_arena.pb.Tpo google/protobuf/$(DEPDIR)/no_warning_test-unittest_proto3_arena.pb.Po @@ -4646,6 +4705,20 @@ google/protobuf/util/internal/testdata/no_warning_test-wrappers.pb.obj: google/p @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(no_warning_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/util/internal/testdata/no_warning_test-wrappers.pb.obj `if test -f 'google/protobuf/util/internal/testdata/wrappers.pb.cc'; then $(CYGPATH_W) 'google/protobuf/util/internal/testdata/wrappers.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/util/internal/testdata/wrappers.pb.cc'; fi` +google/protobuf/util/no_warning_test-json_format.pb.o: google/protobuf/util/json_format.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(no_warning_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/util/no_warning_test-json_format.pb.o -MD -MP -MF google/protobuf/util/$(DEPDIR)/no_warning_test-json_format.pb.Tpo -c -o google/protobuf/util/no_warning_test-json_format.pb.o `test -f 'google/protobuf/util/json_format.pb.cc' || echo '$(srcdir)/'`google/protobuf/util/json_format.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/util/$(DEPDIR)/no_warning_test-json_format.pb.Tpo google/protobuf/util/$(DEPDIR)/no_warning_test-json_format.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='google/protobuf/util/json_format.pb.cc' object='google/protobuf/util/no_warning_test-json_format.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(no_warning_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/util/no_warning_test-json_format.pb.o `test -f 'google/protobuf/util/json_format.pb.cc' || echo '$(srcdir)/'`google/protobuf/util/json_format.pb.cc + +google/protobuf/util/no_warning_test-json_format.pb.obj: google/protobuf/util/json_format.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(no_warning_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/util/no_warning_test-json_format.pb.obj -MD -MP -MF google/protobuf/util/$(DEPDIR)/no_warning_test-json_format.pb.Tpo -c -o google/protobuf/util/no_warning_test-json_format.pb.obj `if test -f 'google/protobuf/util/json_format.pb.cc'; then $(CYGPATH_W) 'google/protobuf/util/json_format.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/util/json_format.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/util/$(DEPDIR)/no_warning_test-json_format.pb.Tpo google/protobuf/util/$(DEPDIR)/no_warning_test-json_format.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='google/protobuf/util/json_format.pb.cc' object='google/protobuf/util/no_warning_test-json_format.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(no_warning_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/util/no_warning_test-json_format.pb.obj `if test -f 'google/protobuf/util/json_format.pb.cc'; then $(CYGPATH_W) 'google/protobuf/util/json_format.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/util/json_format.pb.cc'; fi` + google/protobuf/util/no_warning_test-json_format_proto3.pb.o: google/protobuf/util/json_format_proto3.pb.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(no_warning_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/util/no_warning_test-json_format_proto3.pb.o -MD -MP -MF google/protobuf/util/$(DEPDIR)/no_warning_test-json_format_proto3.pb.Tpo -c -o google/protobuf/util/no_warning_test-json_format_proto3.pb.o `test -f 'google/protobuf/util/json_format_proto3.pb.cc' || echo '$(srcdir)/'`google/protobuf/util/json_format_proto3.pb.cc @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/util/$(DEPDIR)/no_warning_test-json_format_proto3.pb.Tpo google/protobuf/util/$(DEPDIR)/no_warning_test-json_format_proto3.pb.Po @@ -5206,6 +5279,20 @@ google/protobuf/protobuf_lazy_descriptor_test-unittest_preserve_unknown_enum.pb. @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_lazy_descriptor_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_lazy_descriptor_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/protobuf_lazy_descriptor_test-unittest_preserve_unknown_enum.pb.obj `if test -f 'google/protobuf/unittest_preserve_unknown_enum.pb.cc'; then $(CYGPATH_W) 'google/protobuf/unittest_preserve_unknown_enum.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/unittest_preserve_unknown_enum.pb.cc'; fi` +google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3.pb.o: google/protobuf/unittest_proto3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_lazy_descriptor_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_lazy_descriptor_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3.pb.o -MD -MP -MF google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-unittest_proto3.pb.Tpo -c -o google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3.pb.o `test -f 'google/protobuf/unittest_proto3.pb.cc' || echo '$(srcdir)/'`google/protobuf/unittest_proto3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-unittest_proto3.pb.Tpo google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-unittest_proto3.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='google/protobuf/unittest_proto3.pb.cc' object='google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_lazy_descriptor_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_lazy_descriptor_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3.pb.o `test -f 'google/protobuf/unittest_proto3.pb.cc' || echo '$(srcdir)/'`google/protobuf/unittest_proto3.pb.cc + +google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3.pb.obj: google/protobuf/unittest_proto3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_lazy_descriptor_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_lazy_descriptor_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3.pb.obj -MD -MP -MF google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-unittest_proto3.pb.Tpo -c -o google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3.pb.obj `if test -f 'google/protobuf/unittest_proto3.pb.cc'; then $(CYGPATH_W) 'google/protobuf/unittest_proto3.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/unittest_proto3.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-unittest_proto3.pb.Tpo google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-unittest_proto3.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='google/protobuf/unittest_proto3.pb.cc' object='google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_lazy_descriptor_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_lazy_descriptor_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3.pb.obj `if test -f 'google/protobuf/unittest_proto3.pb.cc'; then $(CYGPATH_W) 'google/protobuf/unittest_proto3.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/unittest_proto3.pb.cc'; fi` + google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3_arena.pb.o: google/protobuf/unittest_proto3_arena.pb.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_lazy_descriptor_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_lazy_descriptor_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3_arena.pb.o -MD -MP -MF google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-unittest_proto3_arena.pb.Tpo -c -o google/protobuf/protobuf_lazy_descriptor_test-unittest_proto3_arena.pb.o `test -f 'google/protobuf/unittest_proto3_arena.pb.cc' || echo '$(srcdir)/'`google/protobuf/unittest_proto3_arena.pb.cc @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-unittest_proto3_arena.pb.Tpo google/protobuf/$(DEPDIR)/protobuf_lazy_descriptor_test-unittest_proto3_arena.pb.Po @@ -5416,6 +5503,20 @@ google/protobuf/util/internal/testdata/protobuf_lazy_descriptor_test-wrappers.pb @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_lazy_descriptor_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_lazy_descriptor_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/util/internal/testdata/protobuf_lazy_descriptor_test-wrappers.pb.obj `if test -f 'google/protobuf/util/internal/testdata/wrappers.pb.cc'; then $(CYGPATH_W) 'google/protobuf/util/internal/testdata/wrappers.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/util/internal/testdata/wrappers.pb.cc'; fi` +google/protobuf/util/protobuf_lazy_descriptor_test-json_format.pb.o: google/protobuf/util/json_format.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_lazy_descriptor_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_lazy_descriptor_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/util/protobuf_lazy_descriptor_test-json_format.pb.o -MD -MP -MF google/protobuf/util/$(DEPDIR)/protobuf_lazy_descriptor_test-json_format.pb.Tpo -c -o google/protobuf/util/protobuf_lazy_descriptor_test-json_format.pb.o `test -f 'google/protobuf/util/json_format.pb.cc' || echo '$(srcdir)/'`google/protobuf/util/json_format.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/util/$(DEPDIR)/protobuf_lazy_descriptor_test-json_format.pb.Tpo google/protobuf/util/$(DEPDIR)/protobuf_lazy_descriptor_test-json_format.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='google/protobuf/util/json_format.pb.cc' object='google/protobuf/util/protobuf_lazy_descriptor_test-json_format.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_lazy_descriptor_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_lazy_descriptor_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/util/protobuf_lazy_descriptor_test-json_format.pb.o `test -f 'google/protobuf/util/json_format.pb.cc' || echo '$(srcdir)/'`google/protobuf/util/json_format.pb.cc + +google/protobuf/util/protobuf_lazy_descriptor_test-json_format.pb.obj: google/protobuf/util/json_format.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_lazy_descriptor_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_lazy_descriptor_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/util/protobuf_lazy_descriptor_test-json_format.pb.obj -MD -MP -MF google/protobuf/util/$(DEPDIR)/protobuf_lazy_descriptor_test-json_format.pb.Tpo -c -o google/protobuf/util/protobuf_lazy_descriptor_test-json_format.pb.obj `if test -f 'google/protobuf/util/json_format.pb.cc'; then $(CYGPATH_W) 'google/protobuf/util/json_format.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/util/json_format.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/util/$(DEPDIR)/protobuf_lazy_descriptor_test-json_format.pb.Tpo google/protobuf/util/$(DEPDIR)/protobuf_lazy_descriptor_test-json_format.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='google/protobuf/util/json_format.pb.cc' object='google/protobuf/util/protobuf_lazy_descriptor_test-json_format.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_lazy_descriptor_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_lazy_descriptor_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/util/protobuf_lazy_descriptor_test-json_format.pb.obj `if test -f 'google/protobuf/util/json_format.pb.cc'; then $(CYGPATH_W) 'google/protobuf/util/json_format.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/util/json_format.pb.cc'; fi` + google/protobuf/util/protobuf_lazy_descriptor_test-json_format_proto3.pb.o: google/protobuf/util/json_format_proto3.pb.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_lazy_descriptor_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_lazy_descriptor_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/util/protobuf_lazy_descriptor_test-json_format_proto3.pb.o -MD -MP -MF google/protobuf/util/$(DEPDIR)/protobuf_lazy_descriptor_test-json_format_proto3.pb.Tpo -c -o google/protobuf/util/protobuf_lazy_descriptor_test-json_format_proto3.pb.o `test -f 'google/protobuf/util/json_format_proto3.pb.cc' || echo '$(srcdir)/'`google/protobuf/util/json_format_proto3.pb.cc @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/util/$(DEPDIR)/protobuf_lazy_descriptor_test-json_format_proto3.pb.Tpo google/protobuf/util/$(DEPDIR)/protobuf_lazy_descriptor_test-json_format_proto3.pb.Po @@ -5738,19 +5839,19 @@ google/protobuf/stubs/protobuf_test-int128_unittest.obj: google/protobuf/stubs/i @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/stubs/protobuf_test-int128_unittest.obj `if test -f 'google/protobuf/stubs/int128_unittest.cc'; then $(CYGPATH_W) 'google/protobuf/stubs/int128_unittest.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/stubs/int128_unittest.cc'; fi` -google/protobuf/stubs/protobuf_test-io_win32_unittest.o: google/protobuf/stubs/io_win32_unittest.cc -@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/stubs/protobuf_test-io_win32_unittest.o -MD -MP -MF google/protobuf/stubs/$(DEPDIR)/protobuf_test-io_win32_unittest.Tpo -c -o google/protobuf/stubs/protobuf_test-io_win32_unittest.o `test -f 'google/protobuf/stubs/io_win32_unittest.cc' || echo '$(srcdir)/'`google/protobuf/stubs/io_win32_unittest.cc -@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/stubs/$(DEPDIR)/protobuf_test-io_win32_unittest.Tpo google/protobuf/stubs/$(DEPDIR)/protobuf_test-io_win32_unittest.Po -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='google/protobuf/stubs/io_win32_unittest.cc' object='google/protobuf/stubs/protobuf_test-io_win32_unittest.o' libtool=no @AMDEPBACKSLASH@ +google/protobuf/io/protobuf_test-io_win32_unittest.o: google/protobuf/io/io_win32_unittest.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/io/protobuf_test-io_win32_unittest.o -MD -MP -MF google/protobuf/io/$(DEPDIR)/protobuf_test-io_win32_unittest.Tpo -c -o google/protobuf/io/protobuf_test-io_win32_unittest.o `test -f 'google/protobuf/io/io_win32_unittest.cc' || echo '$(srcdir)/'`google/protobuf/io/io_win32_unittest.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/io/$(DEPDIR)/protobuf_test-io_win32_unittest.Tpo google/protobuf/io/$(DEPDIR)/protobuf_test-io_win32_unittest.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='google/protobuf/io/io_win32_unittest.cc' object='google/protobuf/io/protobuf_test-io_win32_unittest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/stubs/protobuf_test-io_win32_unittest.o `test -f 'google/protobuf/stubs/io_win32_unittest.cc' || echo '$(srcdir)/'`google/protobuf/stubs/io_win32_unittest.cc +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/io/protobuf_test-io_win32_unittest.o `test -f 'google/protobuf/io/io_win32_unittest.cc' || echo '$(srcdir)/'`google/protobuf/io/io_win32_unittest.cc -google/protobuf/stubs/protobuf_test-io_win32_unittest.obj: google/protobuf/stubs/io_win32_unittest.cc -@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/stubs/protobuf_test-io_win32_unittest.obj -MD -MP -MF google/protobuf/stubs/$(DEPDIR)/protobuf_test-io_win32_unittest.Tpo -c -o google/protobuf/stubs/protobuf_test-io_win32_unittest.obj `if test -f 'google/protobuf/stubs/io_win32_unittest.cc'; then $(CYGPATH_W) 'google/protobuf/stubs/io_win32_unittest.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/stubs/io_win32_unittest.cc'; fi` -@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/stubs/$(DEPDIR)/protobuf_test-io_win32_unittest.Tpo google/protobuf/stubs/$(DEPDIR)/protobuf_test-io_win32_unittest.Po -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='google/protobuf/stubs/io_win32_unittest.cc' object='google/protobuf/stubs/protobuf_test-io_win32_unittest.obj' libtool=no @AMDEPBACKSLASH@ +google/protobuf/io/protobuf_test-io_win32_unittest.obj: google/protobuf/io/io_win32_unittest.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/io/protobuf_test-io_win32_unittest.obj -MD -MP -MF google/protobuf/io/$(DEPDIR)/protobuf_test-io_win32_unittest.Tpo -c -o google/protobuf/io/protobuf_test-io_win32_unittest.obj `if test -f 'google/protobuf/io/io_win32_unittest.cc'; then $(CYGPATH_W) 'google/protobuf/io/io_win32_unittest.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/io/io_win32_unittest.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/io/$(DEPDIR)/protobuf_test-io_win32_unittest.Tpo google/protobuf/io/$(DEPDIR)/protobuf_test-io_win32_unittest.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='google/protobuf/io/io_win32_unittest.cc' object='google/protobuf/io/protobuf_test-io_win32_unittest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/stubs/protobuf_test-io_win32_unittest.obj `if test -f 'google/protobuf/stubs/io_win32_unittest.cc'; then $(CYGPATH_W) 'google/protobuf/stubs/io_win32_unittest.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/stubs/io_win32_unittest.cc'; fi` +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/io/protobuf_test-io_win32_unittest.obj `if test -f 'google/protobuf/io/io_win32_unittest.cc'; then $(CYGPATH_W) 'google/protobuf/io/io_win32_unittest.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/io/io_win32_unittest.cc'; fi` google/protobuf/stubs/protobuf_test-statusor_test.o: google/protobuf/stubs/statusor_test.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/stubs/protobuf_test-statusor_test.o -MD -MP -MF google/protobuf/stubs/$(DEPDIR)/protobuf_test-statusor_test.Tpo -c -o google/protobuf/stubs/protobuf_test-statusor_test.o `test -f 'google/protobuf/stubs/statusor_test.cc' || echo '$(srcdir)/'`google/protobuf/stubs/statusor_test.cc @@ -7194,6 +7295,20 @@ google/protobuf/protobuf_test-unittest_preserve_unknown_enum.pb.obj: google/prot @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/protobuf_test-unittest_preserve_unknown_enum.pb.obj `if test -f 'google/protobuf/unittest_preserve_unknown_enum.pb.cc'; then $(CYGPATH_W) 'google/protobuf/unittest_preserve_unknown_enum.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/unittest_preserve_unknown_enum.pb.cc'; fi` +google/protobuf/protobuf_test-unittest_proto3.pb.o: google/protobuf/unittest_proto3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/protobuf_test-unittest_proto3.pb.o -MD -MP -MF google/protobuf/$(DEPDIR)/protobuf_test-unittest_proto3.pb.Tpo -c -o google/protobuf/protobuf_test-unittest_proto3.pb.o `test -f 'google/protobuf/unittest_proto3.pb.cc' || echo '$(srcdir)/'`google/protobuf/unittest_proto3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/$(DEPDIR)/protobuf_test-unittest_proto3.pb.Tpo google/protobuf/$(DEPDIR)/protobuf_test-unittest_proto3.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='google/protobuf/unittest_proto3.pb.cc' object='google/protobuf/protobuf_test-unittest_proto3.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/protobuf_test-unittest_proto3.pb.o `test -f 'google/protobuf/unittest_proto3.pb.cc' || echo '$(srcdir)/'`google/protobuf/unittest_proto3.pb.cc + +google/protobuf/protobuf_test-unittest_proto3.pb.obj: google/protobuf/unittest_proto3.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/protobuf_test-unittest_proto3.pb.obj -MD -MP -MF google/protobuf/$(DEPDIR)/protobuf_test-unittest_proto3.pb.Tpo -c -o google/protobuf/protobuf_test-unittest_proto3.pb.obj `if test -f 'google/protobuf/unittest_proto3.pb.cc'; then $(CYGPATH_W) 'google/protobuf/unittest_proto3.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/unittest_proto3.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/$(DEPDIR)/protobuf_test-unittest_proto3.pb.Tpo google/protobuf/$(DEPDIR)/protobuf_test-unittest_proto3.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='google/protobuf/unittest_proto3.pb.cc' object='google/protobuf/protobuf_test-unittest_proto3.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/protobuf_test-unittest_proto3.pb.obj `if test -f 'google/protobuf/unittest_proto3.pb.cc'; then $(CYGPATH_W) 'google/protobuf/unittest_proto3.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/unittest_proto3.pb.cc'; fi` + google/protobuf/protobuf_test-unittest_proto3_arena.pb.o: google/protobuf/unittest_proto3_arena.pb.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/protobuf_test-unittest_proto3_arena.pb.o -MD -MP -MF google/protobuf/$(DEPDIR)/protobuf_test-unittest_proto3_arena.pb.Tpo -c -o google/protobuf/protobuf_test-unittest_proto3_arena.pb.o `test -f 'google/protobuf/unittest_proto3_arena.pb.cc' || echo '$(srcdir)/'`google/protobuf/unittest_proto3_arena.pb.cc @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/$(DEPDIR)/protobuf_test-unittest_proto3_arena.pb.Tpo google/protobuf/$(DEPDIR)/protobuf_test-unittest_proto3_arena.pb.Po @@ -7404,6 +7519,20 @@ google/protobuf/util/internal/testdata/protobuf_test-wrappers.pb.obj: google/pro @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/util/internal/testdata/protobuf_test-wrappers.pb.obj `if test -f 'google/protobuf/util/internal/testdata/wrappers.pb.cc'; then $(CYGPATH_W) 'google/protobuf/util/internal/testdata/wrappers.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/util/internal/testdata/wrappers.pb.cc'; fi` +google/protobuf/util/protobuf_test-json_format.pb.o: google/protobuf/util/json_format.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/util/protobuf_test-json_format.pb.o -MD -MP -MF google/protobuf/util/$(DEPDIR)/protobuf_test-json_format.pb.Tpo -c -o google/protobuf/util/protobuf_test-json_format.pb.o `test -f 'google/protobuf/util/json_format.pb.cc' || echo '$(srcdir)/'`google/protobuf/util/json_format.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/util/$(DEPDIR)/protobuf_test-json_format.pb.Tpo google/protobuf/util/$(DEPDIR)/protobuf_test-json_format.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='google/protobuf/util/json_format.pb.cc' object='google/protobuf/util/protobuf_test-json_format.pb.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/util/protobuf_test-json_format.pb.o `test -f 'google/protobuf/util/json_format.pb.cc' || echo '$(srcdir)/'`google/protobuf/util/json_format.pb.cc + +google/protobuf/util/protobuf_test-json_format.pb.obj: google/protobuf/util/json_format.pb.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/util/protobuf_test-json_format.pb.obj -MD -MP -MF google/protobuf/util/$(DEPDIR)/protobuf_test-json_format.pb.Tpo -c -o google/protobuf/util/protobuf_test-json_format.pb.obj `if test -f 'google/protobuf/util/json_format.pb.cc'; then $(CYGPATH_W) 'google/protobuf/util/json_format.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/util/json_format.pb.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/util/$(DEPDIR)/protobuf_test-json_format.pb.Tpo google/protobuf/util/$(DEPDIR)/protobuf_test-json_format.pb.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='google/protobuf/util/json_format.pb.cc' object='google/protobuf/util/protobuf_test-json_format.pb.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -c -o google/protobuf/util/protobuf_test-json_format.pb.obj `if test -f 'google/protobuf/util/json_format.pb.cc'; then $(CYGPATH_W) 'google/protobuf/util/json_format.pb.cc'; else $(CYGPATH_W) '$(srcdir)/google/protobuf/util/json_format.pb.cc'; fi` + google/protobuf/util/protobuf_test-json_format_proto3.pb.o: google/protobuf/util/json_format_proto3.pb.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(protobuf_test_CPPFLAGS) $(CPPFLAGS) $(protobuf_test_CXXFLAGS) $(CXXFLAGS) -MT google/protobuf/util/protobuf_test-json_format_proto3.pb.o -MD -MP -MF google/protobuf/util/$(DEPDIR)/protobuf_test-json_format_proto3.pb.Tpo -c -o google/protobuf/util/protobuf_test-json_format_proto3.pb.o `test -f 'google/protobuf/util/json_format_proto3.pb.cc' || echo '$(srcdir)/'`google/protobuf/util/json_format_proto3.pb.cc @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) google/protobuf/util/$(DEPDIR)/protobuf_test-json_format_proto3.pb.Tpo google/protobuf/util/$(DEPDIR)/protobuf_test-json_format_proto3.pb.Po diff --git a/third_party/protobuf/src/README.md b/third_party/protobuf/src/README.md index 3cbeb3e6..d84176e3 100644 --- a/third_party/protobuf/src/README.md +++ b/third_party/protobuf/src/README.md @@ -1,7 +1,7 @@ Protocol Buffers - Google's data interchange format =================================================== -[![Build Status](https://travis-ci.org/google/protobuf.svg?branch=master)](https://travis-ci.org/google/protobuf) [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf) +[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-cpp_distcheck.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fcpp_distcheck%2Fcontinuous) [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-bazel.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fbazel%2Fcontinuous) [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp%2Fcontinuous) [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-cpp_distcheck.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp_distcheck%2Fcontinuous) [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf) Copyright 2008 Google Inc. @@ -29,7 +29,7 @@ install them before proceeding. To get the source, download one of the release .tar.gz or .zip packages in the release page: - https://github.com/google/protobuf/releases/latest + https://github.com/protocolbuffers/protobuf/releases/latest For example: if you only need C++, download `protobuf-cpp-[VERSION].tar.gz`; if you need C++ and Java, download `protobuf-java-[VERSION].tar.gz` (every package @@ -40,7 +40,7 @@ You can also get the source by "git clone" our git repository. Make sure you have also cloned the submodules and generated the configure script (skip this if you are using a release .tar.gz or .zip package): - $ git clone https://github.com/google/protobuf.git + $ git clone https://github.com/protocolbuffers/protobuf.git $ cd protobuf $ git submodule update --init --recursive $ ./autogen.sh @@ -184,7 +184,7 @@ C++ Installation - Windows If you only need the protoc binary, you can download it from the release page: - https://github.com/google/protobuf/releases/latest + https://github.com/protocolbuffers/protobuf/releases/latest In the downloads section, download the zip file protoc-$VERSION-win32.zip. It contains the protoc binary as well as public proto files of protobuf diff --git a/third_party/protobuf/src/google/protobuf/any.cc b/third_party/protobuf/src/google/protobuf/any.cc index b94529e6..a79214b7 100644 --- a/third_party/protobuf/src/google/protobuf/any.cc +++ b/third_party/protobuf/src/google/protobuf/any.cc @@ -30,92 +30,50 @@ #include +#include +#include #include +#include +#include namespace google { namespace protobuf { namespace internal { -namespace { -string GetTypeUrl(const Descriptor* message, - const string& type_url_prefix) { - if (!type_url_prefix.empty() && - type_url_prefix[type_url_prefix.size() - 1] == '/') { - return type_url_prefix + message->full_name(); - } else { - return type_url_prefix + "/" + message->full_name(); - } -} -} // namespace - -const char kAnyFullTypeName[] = "google.protobuf.Any"; -const char kTypeGoogleApisComPrefix[] = "type.googleapis.com/"; -const char kTypeGoogleProdComPrefix[] = "type.googleprod.com/"; - -AnyMetadata::AnyMetadata(UrlType* type_url, ValueType* value) - : type_url_(type_url), value_(value) { -} - void AnyMetadata::PackFrom(const Message& message) { PackFrom(message, kTypeGoogleApisComPrefix); } void AnyMetadata::PackFrom(const Message& message, - const string& type_url_prefix) { - type_url_->SetNoArena(&::google::protobuf::internal::GetEmptyString(), - GetTypeUrl(message.GetDescriptor(), type_url_prefix)); + const std::string& type_url_prefix) { + type_url_->SetNoArena( + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString(), + GetTypeUrl(message.GetDescriptor()->full_name(), type_url_prefix)); message.SerializeToString(value_->MutableNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited())); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())); } bool AnyMetadata::UnpackTo(Message* message) const { - if (!InternalIs(message->GetDescriptor())) { + if (!InternalIs(message->GetDescriptor()->full_name())) { return false; } return message->ParseFromString(value_->GetNoArena()); } -bool AnyMetadata::InternalIs(const Descriptor* descriptor) const { - const string type_url = type_url_->GetNoArena(); - string full_name; - if (!ParseAnyTypeUrl(type_url, &full_name)) { - return false; - } - return full_name == descriptor->full_name(); -} - -bool ParseAnyTypeUrl(const string& type_url, string* url_prefix, - string* full_type_name) { - size_t pos = type_url.find_last_of("/"); - if (pos == string::npos || pos + 1 == type_url.size()) { - return false; - } - if (url_prefix) { - *url_prefix = type_url.substr(0, pos + 1); - } - *full_type_name = type_url.substr(pos + 1); - return true; -} - -bool ParseAnyTypeUrl(const string& type_url, string* full_type_name) { - return ParseAnyTypeUrl(type_url, NULL, full_type_name); -} - - bool GetAnyFieldDescriptors(const Message& message, const FieldDescriptor** type_url_field, const FieldDescriptor** value_field) { - const Descriptor* descriptor = message.GetDescriptor(); - if (descriptor->full_name() != kAnyFullTypeName) { - return false; - } - *type_url_field = descriptor->FindFieldByNumber(1); - *value_field = descriptor->FindFieldByNumber(2); - return (*type_url_field != NULL && - (*type_url_field)->type() == FieldDescriptor::TYPE_STRING && - *value_field != NULL && - (*value_field)->type() == FieldDescriptor::TYPE_BYTES); + const Descriptor* descriptor = message.GetDescriptor(); + if (descriptor->full_name() != kAnyFullTypeName) { + return false; + } + *type_url_field = descriptor->FindFieldByNumber(1); + *value_field = descriptor->FindFieldByNumber(2); + return (*type_url_field != NULL && + (*type_url_field)->type() == FieldDescriptor::TYPE_STRING && + *value_field != NULL && + (*value_field)->type() == FieldDescriptor::TYPE_BYTES); } } // namespace internal diff --git a/third_party/protobuf/src/google/protobuf/any.h b/third_party/protobuf/src/google/protobuf/any.h index a34e5f8e..d7d43966 100644 --- a/third_party/protobuf/src/google/protobuf/any.h +++ b/third_party/protobuf/src/google/protobuf/any.h @@ -34,16 +34,28 @@ #include #include -#include -#include #include +#include + +#include namespace google { namespace protobuf { + +class FieldDescriptor; +class Message; + namespace internal { +extern const char kAnyFullTypeName[]; // "google.protobuf.Any". +extern const char kTypeGoogleApisComPrefix[]; // "type.googleapis.com/". +extern const char kTypeGoogleProdComPrefix[]; // "type.googleprod.com/". + +std::string GetTypeUrl(StringPiece message_name, + StringPiece type_url_prefix); + // Helper class used to implement google::protobuf::Any. -class LIBPROTOBUF_EXPORT AnyMetadata { +class PROTOBUF_EXPORT AnyMetadata { typedef ArenaStringPtr UrlType; typedef ArenaStringPtr ValueType; public: @@ -52,31 +64,52 @@ class LIBPROTOBUF_EXPORT AnyMetadata { // Packs a message using the default type URL prefix: "type.googleapis.com". // The resulted type URL will be "type.googleapis.com/". + template + void PackFrom(const T& message) { + InternalPackFrom(message, kTypeGoogleApisComPrefix, T::FullMessageName()); + } + void PackFrom(const Message& message); + // Packs a message using the given type URL prefix. The type URL will be // constructed by concatenating the message type's full name to the prefix // with an optional "/" separator if the prefix doesn't already end up "/". // For example, both PackFrom(message, "type.googleapis.com") and // PackFrom(message, "type.googleapis.com/") yield the same result type // URL: "type.googleapis.com/". - void PackFrom(const Message& message, const string& type_url_prefix); + template + void PackFrom(const T& message, StringPiece type_url_prefix) { + InternalPackFrom(message, type_url_prefix, T::FullMessageName()); + } + + void PackFrom(const Message& message, const std::string& type_url_prefix); // Unpacks the payload into the given message. Returns false if the message's // type doesn't match the type specified in the type URL (i.e., the full // name after the last "/" of the type URL doesn't match the message's actual // full name) or parsing the payload has failed. + template + bool UnpackTo(T* message) const { + return InternalUnpackTo(T::FullMessageName(), message); + } + bool UnpackTo(Message* message) const; // Checks whether the type specified in the type URL matches the given type. // A type is consdiered matching if its full name matches the full name after // the last "/" in the type URL. - template + template bool Is() const { - return InternalIs(T::default_instance().GetDescriptor()); + return InternalIs(T::FullMessageName()); } private: - bool InternalIs(const Descriptor* message) const; + void InternalPackFrom(const MessageLite& message, + StringPiece type_url_prefix, + StringPiece type_name); + bool InternalUnpackTo(StringPiece type_name, + MessageLite* message) const; + bool InternalIs(StringPiece type_name) const; UrlType* type_url_; ValueType* value_; @@ -84,10 +117,6 @@ class LIBPROTOBUF_EXPORT AnyMetadata { GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(AnyMetadata); }; -extern const char kAnyFullTypeName[]; // "google.protobuf.Any". -extern const char kTypeGoogleApisComPrefix[]; // "type.googleapis.com/". -extern const char kTypeGoogleProdComPrefix[]; // "type.googleprod.com/". - // Get the proto type name from Any::type_url value. For example, passing // "type.googleapis.com/rpc.QueryOrigin" will return "rpc.QueryOrigin" in // *full_type_name. Returns false if the type_url does not have a "/" @@ -95,15 +124,15 @@ extern const char kTypeGoogleProdComPrefix[]; // "type.googleprod.com/". // // NOTE: this function is available publicly as: // google::protobuf::Any() // static method on the generated message type. -bool ParseAnyTypeUrl(const string& type_url, string* full_type_name); +bool ParseAnyTypeUrl(const std::string& type_url, std::string* full_type_name); // Get the proto type name and prefix from Any::type_url value. For example, // passing "type.googleapis.com/rpc.QueryOrigin" will return // "type.googleapis.com/" in *url_prefix and "rpc.QueryOrigin" in // *full_type_name. Returns false if the type_url does not have a "/" in the // type url separating the full type name. -bool ParseAnyTypeUrl(const string& type_url, string* url_prefix, - string* full_type_name); +bool ParseAnyTypeUrl(const std::string& type_url, std::string* url_prefix, + std::string* full_type_name); // See if message is of type google.protobuf.Any, if so, return the descriptors // for "type_url" and "value" fields. @@ -113,6 +142,8 @@ bool GetAnyFieldDescriptors(const Message& message, } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_ANY_H__ diff --git a/third_party/protobuf/src/google/protobuf/any.pb.cc b/third_party/protobuf/src/google/protobuf/any.pb.cc index 9d632efe..eea20a1b 100644 --- a/third_party/protobuf/src/google/protobuf/any.pb.cc +++ b/third_party/protobuf/src/google/protobuf/any.pb.cc @@ -6,167 +6,145 @@ #include #include -#include #include -#include +#include +#include #include #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) - -namespace google { -namespace protobuf { +#include +PROTOBUF_NAMESPACE_OPEN class AnyDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _Any_default_instance_; -} // namespace protobuf -} // namespace google -namespace protobuf_google_2fprotobuf_2fany_2eproto { -static void InitDefaultsAny() { +PROTOBUF_NAMESPACE_CLOSE +static void InitDefaultsscc_info_Any_google_2fprotobuf_2fany_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_Any_default_instance_; - new (ptr) ::google::protobuf::Any(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_Any_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::Any(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::Any::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::Any::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Any = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsAny}, {}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Any_google_2fprotobuf_2fany_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_Any_google_2fprotobuf_2fany_2eproto}, {}}; -void InitDefaults() { - ::google::protobuf::internal::InitSCC(&scc_info_Any.base); -} +static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_google_2fprotobuf_2fany_2eproto[1]; +static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fany_2eproto = nullptr; +static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fany_2eproto = nullptr; -::google::protobuf::Metadata file_level_metadata[1]; - -const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_google_2fprotobuf_2fany_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Any, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Any, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Any, type_url_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Any, value_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Any, type_url_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Any, value_), }; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, sizeof(::google::protobuf::Any)}, +static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, -1, sizeof(PROTOBUF_NAMESPACE_ID::Any)}, }; -static ::google::protobuf::Message const * const file_default_instances[] = { - reinterpret_cast(&::google::protobuf::_Any_default_instance_), +static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_Any_default_instance_), }; -void protobuf_AssignDescriptors() { - AddDescriptors(); - AssignDescriptors( - "google/protobuf/any.proto", schemas, file_default_instances, TableStruct::offsets, - file_level_metadata, NULL, NULL); -} +const char descriptor_table_protodef_google_2fprotobuf_2fany_2eproto[] = + "\n\031google/protobuf/any.proto\022\017google.prot" + "obuf\"&\n\003Any\022\020\n\010type_url\030\001 \001(\t\022\r\n\005value\030\002" + " \001(\014Bo\n\023com.google.protobufB\010AnyProtoP\001Z" + "%github.com/golang/protobuf/ptypes/any\242\002" + "\003GPB\252\002\036Google.Protobuf.WellKnownTypesb\006p" + "roto3" + ; +static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_google_2fprotobuf_2fany_2eproto_deps[1] = { +}; +static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_google_2fprotobuf_2fany_2eproto_sccs[1] = { + &scc_info_Any_google_2fprotobuf_2fany_2eproto.base, +}; +static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fany_2eproto_once; +static bool descriptor_table_google_2fprotobuf_2fany_2eproto_initialized = false; +const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fany_2eproto = { + &descriptor_table_google_2fprotobuf_2fany_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fany_2eproto, "google/protobuf/any.proto", 205, + &descriptor_table_google_2fprotobuf_2fany_2eproto_once, descriptor_table_google_2fprotobuf_2fany_2eproto_sccs, descriptor_table_google_2fprotobuf_2fany_2eproto_deps, 1, 0, + schemas, file_default_instances, TableStruct_google_2fprotobuf_2fany_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2fany_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2fany_2eproto, file_level_service_descriptors_google_2fprotobuf_2fany_2eproto, +}; -void protobuf_AssignDescriptorsOnce() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); -} - -void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1); -} - -void AddDescriptorsImpl() { - InitDefaults(); - static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - "\n\031google/protobuf/any.proto\022\017google.prot" - "obuf\"&\n\003Any\022\020\n\010type_url\030\001 \001(\t\022\r\n\005value\030\002" - " \001(\014Bo\n\023com.google.protobufB\010AnyProtoP\001Z" - "%github.com/golang/protobuf/ptypes/any\242\002" - "\003GPB\252\002\036Google.Protobuf.WellKnownTypesb\006p" - "roto3" - }; - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - descriptor, 205); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "google/protobuf/any.proto", &protobuf_RegisterTypes); -} - -void AddDescriptors() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); -} -// Force AddDescriptors() to be called at dynamic initialization time. -struct StaticDescriptorInitializer { - StaticDescriptorInitializer() { - AddDescriptors(); - } -} static_descriptor_initializer; -} // namespace protobuf_google_2fprotobuf_2fany_2eproto -namespace google { -namespace protobuf { +// Force running AddDescriptors() at dynamic initialization time. +static bool dynamic_init_dummy_google_2fprotobuf_2fany_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fany_2eproto), true); +PROTOBUF_NAMESPACE_OPEN // =================================================================== void Any::InitAsDefaultInstance() { } -void Any::PackFrom(const ::google::protobuf::Message& message) { +void Any::PackFrom(const ::PROTOBUF_NAMESPACE_ID::Message& message) { _any_metadata_.PackFrom(message); } -void Any::PackFrom(const ::google::protobuf::Message& message, - const ::std::string& type_url_prefix) { +void Any::PackFrom(const ::PROTOBUF_NAMESPACE_ID::Message& message, + const std::string& type_url_prefix) { _any_metadata_.PackFrom(message, type_url_prefix); } -bool Any::UnpackTo(::google::protobuf::Message* message) const { +bool Any::UnpackTo(::PROTOBUF_NAMESPACE_ID::Message* message) const { return _any_metadata_.UnpackTo(message); } +bool Any::GetAnyFieldDescriptors( + const ::PROTOBUF_NAMESPACE_ID::Message& message, + const ::PROTOBUF_NAMESPACE_ID::FieldDescriptor** type_url_field, + const ::PROTOBUF_NAMESPACE_ID::FieldDescriptor** value_field) { + return ::PROTOBUF_NAMESPACE_ID::internal::GetAnyFieldDescriptors( + message, type_url_field, value_field); +} bool Any::ParseAnyTypeUrl(const string& type_url, - string* full_type_name) { - return ::google::protobuf::internal::ParseAnyTypeUrl(type_url, + std::string* full_type_name) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseAnyTypeUrl(type_url, full_type_name); } +class Any::HasBitSetters { + public: +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Any::kTypeUrlFieldNumber; const int Any::kValueFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Any::Any() - : ::google::protobuf::Message(), _internal_metadata_(NULL), _any_metadata_(&type_url_, &value_) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr), _any_metadata_(&type_url_, &value_) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Any) } Any::Any(const Any& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _any_metadata_(&type_url_, &value_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.type_url().size() > 0) { - type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.type_url_); + type_url_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.type_url_); } - value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.value().size() > 0) { - value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_); + value_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.value_); } // @@protoc_insertion_point(copy_constructor:google.protobuf.Any) } void Any::SharedCtor() { - type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_Any_google_2fprotobuf_2fany_2eproto.base); + type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } Any::~Any() { @@ -175,54 +153,90 @@ Any::~Any() { } void Any::SharedDtor() { - type_url_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + type_url_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + value_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void Any::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* Any::descriptor() { - ::protobuf_google_2fprotobuf_2fany_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fany_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const Any& Any::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_Any_google_2fprotobuf_2fany_2eproto.base); return *internal_default_instance(); } void Any::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.Any) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + type_url_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + value_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* Any::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // string type_url = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(mutable_type_url(), ptr, ctx, "google.protobuf.Any.type_url"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // bytes value = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(mutable_value(), ptr, ctx); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Any::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Any) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string type_url = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_type_url())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->type_url().data(), static_cast(this->type_url().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "google.protobuf.Any.type_url")); } else { goto handle_unusual; @@ -232,9 +246,8 @@ bool Any::MergePartialFromCodedStream( // bytes value = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadBytes( input, this->mutable_value())); } else { goto handle_unusual; @@ -247,7 +260,7 @@ bool Any::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -261,64 +274,64 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void Any::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.Any) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string type_url = 1; if (this->type_url().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->type_url().data(), static_cast(this->type_url().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Any.type_url"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->type_url(), output); } // bytes value = 2; if (this->value().size() > 0) { - ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesMaybeAliased( 2, this->value(), output); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); + if (_internal_metadata_.have_unknown_fields()) { + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( + _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.Any) } -::google::protobuf::uint8* Any::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* Any::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Any) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string type_url = 1; if (this->type_url().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->type_url().data(), static_cast(this->type_url().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Any.type_url"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 1, this->type_url(), target); } // bytes value = 2; if (this->value().size() > 0) { target = - ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesToArray( 2, this->value(), target); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); + if (_internal_metadata_.have_unknown_fields()) { + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( + _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Any) return target; @@ -328,39 +341,43 @@ size_t Any::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.protobuf.Any) size_t total_size = 0; - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { + if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( + _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // string type_url = 1; if (this->type_url().size() > 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->type_url()); } // bytes value = 2; if (this->value().size() > 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::BytesSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->value()); } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void Any::MergeFrom(const ::google::protobuf::Message& from) { +void Any::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Any) GOOGLE_DCHECK_NE(&from, this); const Any* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Any) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Any) MergeFrom(*source); @@ -371,20 +388,20 @@ void Any::MergeFrom(const Any& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Any) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.type_url().size() > 0) { - type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.type_url_); + type_url_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.type_url_); } if (from.value().size() > 0) { - value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_); + value_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.value_); } } -void Any::CopyFrom(const ::google::protobuf::Message& from) { +void Any::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Any) if (&from == this) return; Clear(); @@ -408,28 +425,25 @@ void Any::Swap(Any* other) { } void Any::InternalSwap(Any* other) { using std::swap; - type_url_.Swap(&other->type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - value_.Swap(&other->value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); _internal_metadata_.Swap(&other->_internal_metadata_); + type_url_.Swap(&other->type_url_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + value_.Swap(&other->value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); } -::google::protobuf::Metadata Any::GetMetadata() const { - protobuf_google_2fprotobuf_2fany_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fany_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata Any::GetMetadata() const { + return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Any* Arena::CreateMaybeMessage< ::google::protobuf::Any >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::Any >(arena); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::Any* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Any >(Arena* arena) { + return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::Any >(arena); } -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) +#include diff --git a/third_party/protobuf/src/google/protobuf/any.pb.h b/third_party/protobuf/src/google/protobuf/any.pb.h index 157fc80c..800211b7 100644 --- a/third_party/protobuf/src/google/protobuf/any.pb.h +++ b/third_party/protobuf/src/google/protobuf/any.pb.h @@ -1,24 +1,25 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/any.proto -#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto -#define PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto +#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto +#include #include -#include - -#if GOOGLE_PROTOBUF_VERSION < 3006001 +#include +#if PROTOBUF_VERSION < 3008000 #error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update +#error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3008000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please +#error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include @@ -26,60 +27,62 @@ #include #include #include +#include #include #include // IWYU pragma: export #include // IWYU pragma: export #include #include // @@protoc_insertion_point(includes) -#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fany_2eproto LIBPROTOBUF_EXPORT +#include +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fany_2eproto PROTOBUF_EXPORT +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE -namespace protobuf_google_2fprotobuf_2fany_2eproto { // Internal implementation detail -- do not use these members. -struct LIBPROTOBUF_EXPORT TableStruct { - static const ::google::protobuf::internal::ParseTableField entries[]; - static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; - static const ::google::protobuf::internal::ParseTable schema[1]; - static const ::google::protobuf::internal::FieldMetadata field_metadata[]; - static const ::google::protobuf::internal::SerializationTable serialization_table[]; - static const ::google::protobuf::uint32 offsets[]; +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fany_2eproto { + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; + static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; + static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; -void LIBPROTOBUF_EXPORT AddDescriptors(); -} // namespace protobuf_google_2fprotobuf_2fany_2eproto -namespace google { -namespace protobuf { +extern PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fany_2eproto; +PROTOBUF_NAMESPACE_OPEN class Any; class AnyDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_; -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Any* Arena::CreateMaybeMessage<::google::protobuf::Any>(Arena*); -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { +PROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_; +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::Any* Arena::CreateMaybeMessage(Arena*); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN // =================================================================== -class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Any) */ { +class PROTOBUF_EXPORT Any : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Any) */ { public: Any(); virtual ~Any(); Any(const Any& from); - - inline Any& operator=(const Any& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 Any(Any&& from) noexcept : Any() { *this = ::std::move(from); } + inline Any& operator=(const Any& from) { + CopyFrom(from); + return *this; + } inline Any& operator=(Any&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -88,8 +91,16 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in } return *this; } - #endif - static const ::google::protobuf::Descriptor* descriptor(); + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const Any& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -102,16 +113,19 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in // implements Any ----------------------------------------------- - void PackFrom(const ::google::protobuf::Message& message); - void PackFrom(const ::google::protobuf::Message& message, - const ::std::string& type_url_prefix); - bool UnpackTo(::google::protobuf::Message* message) const; + void PackFrom(const ::PROTOBUF_NAMESPACE_ID::Message& message); + void PackFrom(const ::PROTOBUF_NAMESPACE_ID::Message& message, + const std::string& type_url_prefix); + bool UnpackTo(::PROTOBUF_NAMESPACE_ID::Message* message) const; + static bool GetAnyFieldDescriptors( + const ::PROTOBUF_NAMESPACE_ID::Message& message, + const ::PROTOBUF_NAMESPACE_ID::FieldDescriptor** type_url_field, + const ::PROTOBUF_NAMESPACE_ID::FieldDescriptor** value_field); template bool Is() const { return _any_metadata_.Is(); } static bool ParseAnyTypeUrl(const string& type_url, - string* full_type_name); - + std::string* full_type_name); void Swap(Any* other); friend void swap(Any& a, Any& b) { a.Swap(&b); @@ -120,43 +134,58 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in // implements Message ---------------------------------------------- inline Any* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - Any* New(::google::protobuf::Arena* arena) const final { + Any* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const Any& from); void MergeFrom(const Any& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Any* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Any"; + } private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { + return nullptr; } inline void* MaybeArenaPtr() const { - return NULL; + return nullptr; } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fany_2eproto); + return ::descriptor_table_google_2fprotobuf_2fany_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -165,40 +194,37 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in // string type_url = 1; void clear_type_url(); static const int kTypeUrlFieldNumber = 1; - const ::std::string& type_url() const; - void set_type_url(const ::std::string& value); - #if LANG_CXX11 - void set_type_url(::std::string&& value); - #endif + const std::string& type_url() const; + void set_type_url(const std::string& value); + void set_type_url(std::string&& value); void set_type_url(const char* value); void set_type_url(const char* value, size_t size); - ::std::string* mutable_type_url(); - ::std::string* release_type_url(); - void set_allocated_type_url(::std::string* type_url); + std::string* mutable_type_url(); + std::string* release_type_url(); + void set_allocated_type_url(std::string* type_url); // bytes value = 2; void clear_value(); static const int kValueFieldNumber = 2; - const ::std::string& value() const; - void set_value(const ::std::string& value); - #if LANG_CXX11 - void set_value(::std::string&& value); - #endif + const std::string& value() const; + void set_value(const std::string& value); + void set_value(std::string&& value); void set_value(const char* value); void set_value(const void* value, size_t size); - ::std::string* mutable_value(); - ::std::string* release_value(); - void set_allocated_value(::std::string* value); + std::string* mutable_value(); + std::string* release_value(); + void set_allocated_value(std::string* value); // @@protoc_insertion_point(class_scope:google.protobuf.Any) private: + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::ArenaStringPtr type_url_; - ::google::protobuf::internal::ArenaStringPtr value_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::internal::AnyMetadata _any_metadata_; - friend struct ::protobuf_google_2fprotobuf_2fany_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr type_url_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata _any_metadata_; + friend struct ::TableStruct_google_2fprotobuf_2fany_2eproto; }; // =================================================================== @@ -213,107 +239,103 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in // string type_url = 1; inline void Any::clear_type_url() { - type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + type_url_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline const ::std::string& Any::type_url() const { +inline const std::string& Any::type_url() const { // @@protoc_insertion_point(field_get:google.protobuf.Any.type_url) return type_url_.GetNoArena(); } -inline void Any::set_type_url(const ::std::string& value) { +inline void Any::set_type_url(const std::string& value) { - type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); + type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.protobuf.Any.type_url) } -#if LANG_CXX11 -inline void Any::set_type_url(::std::string&& value) { +inline void Any::set_type_url(std::string&& value) { type_url_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Any.type_url) } -#endif inline void Any::set_type_url(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); - type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.protobuf.Any.type_url) } inline void Any::set_type_url(const char* value, size_t size) { - type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:google.protobuf.Any.type_url) } -inline ::std::string* Any::mutable_type_url() { +inline std::string* Any::mutable_type_url() { // @@protoc_insertion_point(field_mutable:google.protobuf.Any.type_url) - return type_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return type_url_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline ::std::string* Any::release_type_url() { +inline std::string* Any::release_type_url() { // @@protoc_insertion_point(field_release:google.protobuf.Any.type_url) - return type_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return type_url_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline void Any::set_allocated_type_url(::std::string* type_url) { - if (type_url != NULL) { +inline void Any::set_allocated_type_url(std::string* type_url) { + if (type_url != nullptr) { } else { } - type_url_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type_url); + type_url_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), type_url); // @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.type_url) } // bytes value = 2; inline void Any::clear_value() { - value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + value_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline const ::std::string& Any::value() const { +inline const std::string& Any::value() const { // @@protoc_insertion_point(field_get:google.protobuf.Any.value) return value_.GetNoArena(); } -inline void Any::set_value(const ::std::string& value) { +inline void Any::set_value(const std::string& value) { - value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); + value_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.protobuf.Any.value) } -#if LANG_CXX11 -inline void Any::set_value(::std::string&& value) { +inline void Any::set_value(std::string&& value) { value_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Any.value) } -#endif inline void Any::set_value(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); - value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + value_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.protobuf.Any.value) } inline void Any::set_value(const void* value, size_t size) { - value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + value_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:google.protobuf.Any.value) } -inline ::std::string* Any::mutable_value() { +inline std::string* Any::mutable_value() { // @@protoc_insertion_point(field_mutable:google.protobuf.Any.value) - return value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return value_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline ::std::string* Any::release_value() { +inline std::string* Any::release_value() { // @@protoc_insertion_point(field_release:google.protobuf.Any.value) - return value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return value_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline void Any::set_allocated_value(::std::string* value) { - if (value != NULL) { +inline void Any::set_allocated_value(std::string* value) { + if (value != nullptr) { } else { } - value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); + value_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.value) } @@ -323,9 +345,9 @@ inline void Any::set_allocated_value(::std::string* value) { // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto diff --git a/third_party/protobuf/src/google/protobuf/any.proto b/third_party/protobuf/src/google/protobuf/any.proto index 49329425..c9be8541 100644 --- a/third_party/protobuf/src/google/protobuf/any.proto +++ b/third_party/protobuf/src/google/protobuf/any.proto @@ -121,7 +121,8 @@ option objc_class_prefix = "GPB"; // message Any { // A URL/resource name that uniquely identifies the type of the serialized - // protocol buffer message. The last segment of the URL's path must represent + // protocol buffer message. This string must contain at least + // one "/" character. The last segment of the URL's path must represent // the fully qualified name of the type (as in // `path/google.protobuf.Duration`). The name should be in a canonical form // (e.g., leading "." is not accepted). diff --git a/third_party/protobuf/src/google/protobuf/any_lite.cc b/third_party/protobuf/src/google/protobuf/any_lite.cc new file mode 100644 index 00000000..7403ed3f --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/any_lite.cc @@ -0,0 +1,123 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include + +#include +#include +#include +#include + + +namespace google { +namespace protobuf { +namespace internal { + +std::string GetTypeUrl(StringPiece message_name, + StringPiece type_url_prefix) { + if (!type_url_prefix.empty() && + type_url_prefix[type_url_prefix.size() - 1] == '/') { + return StrCat(type_url_prefix, message_name); + } else { + return StrCat(type_url_prefix, "/", message_name); + } +} + +const char kAnyFullTypeName[] = "google.protobuf.Any"; +const char kTypeGoogleApisComPrefix[] = "type.googleapis.com/"; +const char kTypeGoogleProdComPrefix[] = "type.googleprod.com/"; + +AnyMetadata::AnyMetadata(UrlType* type_url, ValueType* value) + : type_url_(type_url), value_(value) {} + +void AnyMetadata::InternalPackFrom(const MessageLite& message, + StringPiece type_url_prefix, + StringPiece type_name) { + type_url_->SetNoArena(&::google::protobuf::internal::GetEmptyString(), + GetTypeUrl(type_name, type_url_prefix)); + message.SerializeToString(value_->MutableNoArena( + &::google::protobuf::internal::GetEmptyStringAlreadyInited())); +} + +bool AnyMetadata::InternalUnpackTo(StringPiece type_name, + MessageLite* message) const { + if (!InternalIs(type_name)) { + return false; + } + return message->ParseFromString(value_->GetNoArena()); +} + +namespace { + +// The type URL could be stored in either an ArenaStringPtr or a +// StringPieceField, so we provide these helpers to get a string_view from +// either type. We use a template function as a way to avoid depending on +// StringPieceField. + +template +StringPiece Get(const T* ptr) { + return ptr->Get(); +} + +template <> +// NOLINTNEXTLINE: clang-diagnostic-unused-function +StringPiece Get(const ArenaStringPtr* ptr) { + return ptr->GetNoArena(); +} + +} // namespace + +bool AnyMetadata::InternalIs(StringPiece type_name) const { + StringPiece type_url = Get(type_url_); + return type_url.size() >= type_name.size() + 1 && + type_url[type_url.size() - type_name.size() - 1] == '/' && + HasSuffixString(type_url, type_name); +} + +bool ParseAnyTypeUrl(const std::string& type_url, std::string* url_prefix, + std::string* full_type_name) { + size_t pos = type_url.find_last_of("/"); + if (pos == std::string::npos || pos + 1 == type_url.size()) { + return false; + } + if (url_prefix) { + *url_prefix = type_url.substr(0, pos + 1); + } + *full_type_name = type_url.substr(pos + 1); + return true; +} + +bool ParseAnyTypeUrl(const std::string& type_url, std::string* full_type_name) { + return ParseAnyTypeUrl(type_url, nullptr, full_type_name); +} + +} // namespace internal +} // namespace protobuf +} // namespace google diff --git a/third_party/protobuf/src/google/protobuf/any_test.cc b/third_party/protobuf/src/google/protobuf/any_test.cc index 1bfaa63d..4fbf0b63 100644 --- a/third_party/protobuf/src/google/protobuf/any_test.cc +++ b/third_party/protobuf/src/google/protobuf/any_test.cc @@ -29,8 +29,11 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include +#include #include + + namespace google { namespace protobuf { namespace { @@ -41,14 +44,26 @@ TEST(AnyTest, TestPackAndUnpack) { protobuf_unittest::TestAny message; message.mutable_any_value()->PackFrom(submessage); - string data = message.SerializeAsString(); + std::string data = message.SerializeAsString(); ASSERT_TRUE(message.ParseFromString(data)); EXPECT_TRUE(message.has_any_value()); + submessage.Clear(); ASSERT_TRUE(message.any_value().UnpackTo(&submessage)); EXPECT_EQ(12345, submessage.int32_value()); } +TEST(AnyTest, TestUnpackWithTypeMismatch) { + protobuf_unittest::TestAny payload; + payload.set_int32_value(13); + google::protobuf::Any any; + any.PackFrom(payload); + + // Attempt to unpack into the wrong type. + protobuf_unittest::TestAllTypes dest; + EXPECT_FALSE(any.UnpackTo(&dest)); +} + TEST(AnyTest, TestPackAndUnpackAny) { // We can pack a Any message inside another Any message. protobuf_unittest::TestAny submessage; @@ -58,15 +73,37 @@ TEST(AnyTest, TestPackAndUnpackAny) { protobuf_unittest::TestAny message; message.mutable_any_value()->PackFrom(any); - string data = message.SerializeAsString(); + std::string data = message.SerializeAsString(); ASSERT_TRUE(message.ParseFromString(data)); EXPECT_TRUE(message.has_any_value()); + any.Clear(); + submessage.Clear(); ASSERT_TRUE(message.any_value().UnpackTo(&any)); ASSERT_TRUE(any.UnpackTo(&submessage)); EXPECT_EQ(12345, submessage.int32_value()); } +TEST(AnyTest, TestPackWithCustomTypeUrl) { + protobuf_unittest::TestAny submessage; + submessage.set_int32_value(12345); + google::protobuf::Any any; + // Pack with a custom type URL prefix. + any.PackFrom(submessage, "type.myservice.com"); + EXPECT_EQ("type.myservice.com/protobuf_unittest.TestAny", any.type_url()); + // Pack with a custom type URL prefix ending with '/'. + any.PackFrom(submessage, "type.myservice.com/"); + EXPECT_EQ("type.myservice.com/protobuf_unittest.TestAny", any.type_url()); + // Pack with an empty type URL prefix. + any.PackFrom(submessage, ""); + EXPECT_EQ("/protobuf_unittest.TestAny", any.type_url()); + + // Test unpacking the type. + submessage.Clear(); + EXPECT_TRUE(any.UnpackTo(&submessage)); + EXPECT_EQ(12345, submessage.int32_value()); +} + TEST(AnyTest, TestIs) { protobuf_unittest::TestAny submessage; submessage.set_int32_value(12345); @@ -81,9 +118,51 @@ TEST(AnyTest, TestIs) { ASSERT_TRUE(message.ParseFromString(message.SerializeAsString())); EXPECT_FALSE(message.any_value().Is()); EXPECT_TRUE(message.any_value().Is()); + + any.set_type_url("/protobuf_unittest.TestAny"); + EXPECT_TRUE(any.Is()); + // The type URL must contain at least one "/". + any.set_type_url("protobuf_unittest.TestAny"); + EXPECT_FALSE(any.Is()); + // The type name after the slash must be fully qualified. + any.set_type_url("/TestAny"); + EXPECT_FALSE(any.Is()); } +TEST(AnyTest, MoveConstructor) { + protobuf_unittest::TestAny payload; + payload.set_int32_value(12345); + + google::protobuf::Any src; + src.PackFrom(payload); + + const char* type_url = src.type_url().data(); + + google::protobuf::Any dst(std::move(src)); + EXPECT_EQ(type_url, dst.type_url().data()); + payload.Clear(); + ASSERT_TRUE(dst.UnpackTo(&payload)); + EXPECT_EQ(12345, payload.int32_value()); +} + +TEST(AnyTest, MoveAssignment) { + protobuf_unittest::TestAny payload; + payload.set_int32_value(12345); + + google::protobuf::Any src; + src.PackFrom(payload); + + const char* type_url = src.type_url().data(); + + google::protobuf::Any dst; + dst = std::move(src); + EXPECT_EQ(type_url, dst.type_url().data()); + payload.Clear(); + ASSERT_TRUE(dst.UnpackTo(&payload)); + EXPECT_EQ(12345, payload.int32_value()); +} + + } // namespace } // namespace protobuf - } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/api.pb.cc b/third_party/protobuf/src/google/protobuf/api.pb.cc index e0a249d0..c979b568 100644 --- a/third_party/protobuf/src/google/protobuf/api.pb.cc +++ b/third_party/protobuf/src/google/protobuf/api.pb.cc @@ -6,226 +6,195 @@ #include #include -#include #include -#include +#include +#include #include #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) - -namespace protobuf_google_2fprotobuf_2fapi_2eproto { -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fapi_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Mixin; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fapi_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Method; -} // namespace protobuf_google_2fprotobuf_2fapi_2eproto -namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto { -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext; -} // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto -namespace protobuf_google_2fprotobuf_2ftype_2eproto { -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Option; -} // namespace protobuf_google_2fprotobuf_2ftype_2eproto -namespace google { -namespace protobuf { +#include +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fapi_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_Method_google_2fprotobuf_2fapi_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fapi_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Mixin_google_2fprotobuf_2fapi_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ftype_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_Option_google_2fprotobuf_2ftype_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fsource_5fcontext_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto; +PROTOBUF_NAMESPACE_OPEN class ApiDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _Api_default_instance_; class MethodDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _Method_default_instance_; class MixinDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _Mixin_default_instance_; -} // namespace protobuf -} // namespace google -namespace protobuf_google_2fprotobuf_2fapi_2eproto { -static void InitDefaultsApi() { +PROTOBUF_NAMESPACE_CLOSE +static void InitDefaultsscc_info_Api_google_2fprotobuf_2fapi_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_Api_default_instance_; - new (ptr) ::google::protobuf::Api(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_Api_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::Api(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::Api::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::Api::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<4> scc_info_Api = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 4, InitDefaultsApi}, { - &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base, - &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base, - &protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base, - &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<4> scc_info_Api_google_2fprotobuf_2fapi_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 4, InitDefaultsscc_info_Api_google_2fprotobuf_2fapi_2eproto}, { + &scc_info_Method_google_2fprotobuf_2fapi_2eproto.base, + &scc_info_Option_google_2fprotobuf_2ftype_2eproto.base, + &scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto.base, + &scc_info_Mixin_google_2fprotobuf_2fapi_2eproto.base,}}; -static void InitDefaultsMethod() { +static void InitDefaultsscc_info_Method_google_2fprotobuf_2fapi_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_Method_default_instance_; - new (ptr) ::google::protobuf::Method(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_Method_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::Method(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::Method::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::Method::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_Method = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethod}, { - &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_Method_google_2fprotobuf_2fapi_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_Method_google_2fprotobuf_2fapi_2eproto}, { + &scc_info_Option_google_2fprotobuf_2ftype_2eproto.base,}}; -static void InitDefaultsMixin() { +static void InitDefaultsscc_info_Mixin_google_2fprotobuf_2fapi_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_Mixin_default_instance_; - new (ptr) ::google::protobuf::Mixin(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_Mixin_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::Mixin(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::Mixin::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::Mixin::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Mixin = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsMixin}, {}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Mixin_google_2fprotobuf_2fapi_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_Mixin_google_2fprotobuf_2fapi_2eproto}, {}}; -void InitDefaults() { - ::google::protobuf::internal::InitSCC(&scc_info_Api.base); - ::google::protobuf::internal::InitSCC(&scc_info_Method.base); - ::google::protobuf::internal::InitSCC(&scc_info_Mixin.base); -} +static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_google_2fprotobuf_2fapi_2eproto[3]; +static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fapi_2eproto = nullptr; +static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fapi_2eproto = nullptr; -::google::protobuf::Metadata file_level_metadata[3]; - -const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_google_2fprotobuf_2fapi_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Api, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, methods_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, options_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, version_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, source_context_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, mixins_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, syntax_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Api, name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Api, methods_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Api, options_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Api, version_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Api, source_context_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Api, mixins_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Api, syntax_), ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Method, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, request_type_url_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, request_streaming_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, response_type_url_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, response_streaming_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, options_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, syntax_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Method, name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Method, request_type_url_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Method, request_streaming_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Method, response_type_url_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Method, response_streaming_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Method, options_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Method, syntax_), ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Mixin, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Mixin, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Mixin, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Mixin, root_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Mixin, name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Mixin, root_), }; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, sizeof(::google::protobuf::Api)}, - { 12, -1, sizeof(::google::protobuf::Method)}, - { 24, -1, sizeof(::google::protobuf::Mixin)}, +static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, -1, sizeof(PROTOBUF_NAMESPACE_ID::Api)}, + { 12, -1, sizeof(PROTOBUF_NAMESPACE_ID::Method)}, + { 24, -1, sizeof(PROTOBUF_NAMESPACE_ID::Mixin)}, }; -static ::google::protobuf::Message const * const file_default_instances[] = { - reinterpret_cast(&::google::protobuf::_Api_default_instance_), - reinterpret_cast(&::google::protobuf::_Method_default_instance_), - reinterpret_cast(&::google::protobuf::_Mixin_default_instance_), +static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_Api_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_Method_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_Mixin_default_instance_), }; -void protobuf_AssignDescriptors() { - AddDescriptors(); - AssignDescriptors( - "google/protobuf/api.proto", schemas, file_default_instances, TableStruct::offsets, - file_level_metadata, NULL, NULL); -} +const char descriptor_table_protodef_google_2fprotobuf_2fapi_2eproto[] = + "\n\031google/protobuf/api.proto\022\017google.prot" + "obuf\032$google/protobuf/source_context.pro" + "to\032\032google/protobuf/type.proto\"\201\002\n\003Api\022\014" + "\n\004name\030\001 \001(\t\022(\n\007methods\030\002 \003(\0132\027.google.p" + "rotobuf.Method\022(\n\007options\030\003 \003(\0132\027.google" + ".protobuf.Option\022\017\n\007version\030\004 \001(\t\0226\n\016sou" + "rce_context\030\005 \001(\0132\036.google.protobuf.Sour" + "ceContext\022&\n\006mixins\030\006 \003(\0132\026.google.proto" + "buf.Mixin\022\'\n\006syntax\030\007 \001(\0162\027.google.proto" + "buf.Syntax\"\325\001\n\006Method\022\014\n\004name\030\001 \001(\t\022\030\n\020r" + "equest_type_url\030\002 \001(\t\022\031\n\021request_streami" + "ng\030\003 \001(\010\022\031\n\021response_type_url\030\004 \001(\t\022\032\n\022r" + "esponse_streaming\030\005 \001(\010\022(\n\007options\030\006 \003(\013" + "2\027.google.protobuf.Option\022\'\n\006syntax\030\007 \001(" + "\0162\027.google.protobuf.Syntax\"#\n\005Mixin\022\014\n\004n" + "ame\030\001 \001(\t\022\014\n\004root\030\002 \001(\tBu\n\023com.google.pr" + "otobufB\010ApiProtoP\001Z+google.golang.org/ge" + "nproto/protobuf/api;api\242\002\003GPB\252\002\036Google.P" + "rotobuf.WellKnownTypesb\006proto3" + ; +static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_google_2fprotobuf_2fapi_2eproto_deps[2] = { + &::descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto, + &::descriptor_table_google_2fprotobuf_2ftype_2eproto, +}; +static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_google_2fprotobuf_2fapi_2eproto_sccs[3] = { + &scc_info_Api_google_2fprotobuf_2fapi_2eproto.base, + &scc_info_Method_google_2fprotobuf_2fapi_2eproto.base, + &scc_info_Mixin_google_2fprotobuf_2fapi_2eproto.base, +}; +static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fapi_2eproto_once; +static bool descriptor_table_google_2fprotobuf_2fapi_2eproto_initialized = false; +const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fapi_2eproto = { + &descriptor_table_google_2fprotobuf_2fapi_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fapi_2eproto, "google/protobuf/api.proto", 750, + &descriptor_table_google_2fprotobuf_2fapi_2eproto_once, descriptor_table_google_2fprotobuf_2fapi_2eproto_sccs, descriptor_table_google_2fprotobuf_2fapi_2eproto_deps, 3, 2, + schemas, file_default_instances, TableStruct_google_2fprotobuf_2fapi_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2fapi_2eproto, 3, file_level_enum_descriptors_google_2fprotobuf_2fapi_2eproto, file_level_service_descriptors_google_2fprotobuf_2fapi_2eproto, +}; -void protobuf_AssignDescriptorsOnce() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); -} - -void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 3); -} - -void AddDescriptorsImpl() { - InitDefaults(); - static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - "\n\031google/protobuf/api.proto\022\017google.prot" - "obuf\032$google/protobuf/source_context.pro" - "to\032\032google/protobuf/type.proto\"\201\002\n\003Api\022\014" - "\n\004name\030\001 \001(\t\022(\n\007methods\030\002 \003(\0132\027.google.p" - "rotobuf.Method\022(\n\007options\030\003 \003(\0132\027.google" - ".protobuf.Option\022\017\n\007version\030\004 \001(\t\0226\n\016sou" - "rce_context\030\005 \001(\0132\036.google.protobuf.Sour" - "ceContext\022&\n\006mixins\030\006 \003(\0132\026.google.proto" - "buf.Mixin\022\'\n\006syntax\030\007 \001(\0162\027.google.proto" - "buf.Syntax\"\325\001\n\006Method\022\014\n\004name\030\001 \001(\t\022\030\n\020r" - "equest_type_url\030\002 \001(\t\022\031\n\021request_streami" - "ng\030\003 \001(\010\022\031\n\021response_type_url\030\004 \001(\t\022\032\n\022r" - "esponse_streaming\030\005 \001(\010\022(\n\007options\030\006 \003(\013" - "2\027.google.protobuf.Option\022\'\n\006syntax\030\007 \001(" - "\0162\027.google.protobuf.Syntax\"#\n\005Mixin\022\014\n\004n" - "ame\030\001 \001(\t\022\014\n\004root\030\002 \001(\tBu\n\023com.google.pr" - "otobufB\010ApiProtoP\001Z+google.golang.org/ge" - "nproto/protobuf/api;api\242\002\003GPB\252\002\036Google.P" - "rotobuf.WellKnownTypesb\006proto3" - }; - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - descriptor, 750); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "google/protobuf/api.proto", &protobuf_RegisterTypes); - ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::AddDescriptors(); - ::protobuf_google_2fprotobuf_2ftype_2eproto::AddDescriptors(); -} - -void AddDescriptors() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); -} -// Force AddDescriptors() to be called at dynamic initialization time. -struct StaticDescriptorInitializer { - StaticDescriptorInitializer() { - AddDescriptors(); - } -} static_descriptor_initializer; -} // namespace protobuf_google_2fprotobuf_2fapi_2eproto -namespace google { -namespace protobuf { +// Force running AddDescriptors() at dynamic initialization time. +static bool dynamic_init_dummy_google_2fprotobuf_2fapi_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fapi_2eproto), true); +PROTOBUF_NAMESPACE_OPEN // =================================================================== void Api::InitAsDefaultInstance() { - ::google::protobuf::_Api_default_instance_._instance.get_mutable()->source_context_ = const_cast< ::google::protobuf::SourceContext*>( - ::google::protobuf::SourceContext::internal_default_instance()); + PROTOBUF_NAMESPACE_ID::_Api_default_instance_._instance.get_mutable()->source_context_ = const_cast< PROTOBUF_NAMESPACE_ID::SourceContext*>( + PROTOBUF_NAMESPACE_ID::SourceContext::internal_default_instance()); +} +class Api::HasBitSetters { + public: + static const PROTOBUF_NAMESPACE_ID::SourceContext& source_context(const Api* msg); +}; + +const PROTOBUF_NAMESPACE_ID::SourceContext& +Api::HasBitSetters::source_context(const Api* msg) { + return *msg->source_context_; } void Api::clear_options() { options_.Clear(); } void Api::clear_source_context() { - if (GetArenaNoVirtual() == NULL && source_context_ != NULL) { + if (GetArenaNoVirtual() == nullptr && source_context_ != nullptr) { delete source_context_; } - source_context_ = NULL; + source_context_ = nullptr; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Api::kNameFieldNumber; @@ -238,39 +207,38 @@ const int Api::kSyntaxFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Api::Api() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Api.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Api) } Api::Api(const Api& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), methods_(from.methods_), options_(from.options_), mixins_(from.mixins_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); + name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name_); } - version_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + version_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.version().size() > 0) { - version_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.version_); + version_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.version_); } if (from.has_source_context()) { - source_context_ = new ::google::protobuf::SourceContext(*from.source_context_); + source_context_ = new PROTOBUF_NAMESPACE_ID::SourceContext(*from.source_context_); } else { - source_context_ = NULL; + source_context_ = nullptr; } syntax_ = from.syntax_; // @@protoc_insertion_point(copy_constructor:google.protobuf.Api) } void Api::SharedCtor() { - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - version_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_Api_google_2fprotobuf_2fapi_2eproto.base); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + version_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(&source_context_, 0, static_cast( reinterpret_cast(&syntax_) - reinterpret_cast(&source_context_)) + sizeof(syntax_)); @@ -282,63 +250,150 @@ Api::~Api() { } void Api::SharedDtor() { - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - version_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + version_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete source_context_; } void Api::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* Api::descriptor() { - ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const Api& Api::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Api.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_Api_google_2fprotobuf_2fapi_2eproto.base); return *internal_default_instance(); } void Api::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.Api) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; methods_.Clear(); options_.Clear(); mixins_.Clear(); - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - version_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (GetArenaNoVirtual() == NULL && source_context_ != NULL) { + name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + version_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + if (GetArenaNoVirtual() == nullptr && source_context_ != nullptr) { delete source_context_; } - source_context_ = NULL; + source_context_ = nullptr; syntax_ = 0; _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* Api::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // string name = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(mutable_name(), ptr, ctx, "google.protobuf.Api.name"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.Method methods = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_methods(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 18); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.Option options = 3; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_options(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 26); + } else goto handle_unusual; + continue; + // string version = 4; + case 4: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(mutable_version(), ptr, ctx, "google.protobuf.Api.version"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // .google.protobuf.SourceContext source_context = 5; + case 5: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) { + ptr = ctx->ParseMessage(mutable_source_context(), ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.Mixin mixins = 6; + case 6: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_mixins(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 50); + } else goto handle_unusual; + continue; + // .google.protobuf.Syntax syntax = 7; + case 7: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 56)) { + ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + set_syntax(static_cast(val)); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Api::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Api) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string name = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_name())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "google.protobuf.Api.name")); } else { goto handle_unusual; @@ -348,9 +403,8 @@ bool Api::MergePartialFromCodedStream( // repeated .google.protobuf.Method methods = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_methods())); } else { goto handle_unusual; @@ -360,9 +414,8 @@ bool Api::MergePartialFromCodedStream( // repeated .google.protobuf.Option options = 3; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_options())); } else { goto handle_unusual; @@ -372,13 +425,12 @@ bool Api::MergePartialFromCodedStream( // string version = 4; case 4: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (34 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_version())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->version().data(), static_cast(this->version().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "google.protobuf.Api.version")); } else { goto handle_unusual; @@ -388,9 +440,8 @@ bool Api::MergePartialFromCodedStream( // .google.protobuf.SourceContext source_context = 5; case 5: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (42 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, mutable_source_context())); } else { goto handle_unusual; @@ -400,9 +451,8 @@ bool Api::MergePartialFromCodedStream( // repeated .google.protobuf.Mixin mixins = 6; case 6: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (50 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_mixins())); } else { goto handle_unusual; @@ -412,13 +462,12 @@ bool Api::MergePartialFromCodedStream( // .google.protobuf.Syntax syntax = 7; case 7: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) { - int value; - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (56 & 0xFF)) { + int value = 0; + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>( input, &value))); - set_syntax(static_cast< ::google::protobuf::Syntax >(value)); + set_syntax(static_cast< PROTOBUF_NAMESPACE_ID::Syntax >(value)); } else { goto handle_unusual; } @@ -430,7 +479,7 @@ bool Api::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -444,27 +493,28 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void Api::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.Api) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string name = 1; if (this->name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Api.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // repeated .google.protobuf.Method methods = 2; for (unsigned int i = 0, n = static_cast(this->methods_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->methods(static_cast(i)), output); @@ -473,7 +523,7 @@ void Api::SerializeWithCachedSizes( // repeated .google.protobuf.Option options = 3; for (unsigned int i = 0, n = static_cast(this->options_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->options(static_cast(i)), output); @@ -481,24 +531,24 @@ void Api::SerializeWithCachedSizes( // string version = 4; if (this->version().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->version().data(), static_cast(this->version().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Api.version"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 4, this->version(), output); } // .google.protobuf.SourceContext source_context = 5; if (this->has_source_context()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 5, this->_internal_source_context(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( + 5, HasBitSetters::source_context(this), output); } // repeated .google.protobuf.Mixin mixins = 6; for (unsigned int i = 0, n = static_cast(this->mixins_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 6, this->mixins(static_cast(i)), output); @@ -506,86 +556,85 @@ void Api::SerializeWithCachedSizes( // .google.protobuf.Syntax syntax = 7; if (this->syntax() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteEnum( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum( 7, this->syntax(), output); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); + if (_internal_metadata_.have_unknown_fields()) { + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( + _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.Api) } -::google::protobuf::uint8* Api::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* Api::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Api) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string name = 1; if (this->name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Api.name"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // repeated .google.protobuf.Method methods = 2; for (unsigned int i = 0, n = static_cast(this->methods_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 2, this->methods(static_cast(i)), deterministic, target); + 2, this->methods(static_cast(i)), target); } // repeated .google.protobuf.Option options = 3; for (unsigned int i = 0, n = static_cast(this->options_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 3, this->options(static_cast(i)), deterministic, target); + 3, this->options(static_cast(i)), target); } // string version = 4; if (this->version().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->version().data(), static_cast(this->version().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Api.version"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 4, this->version(), target); } // .google.protobuf.SourceContext source_context = 5; if (this->has_source_context()) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 5, this->_internal_source_context(), deterministic, target); + 5, HasBitSetters::source_context(this), target); } // repeated .google.protobuf.Mixin mixins = 6; for (unsigned int i = 0, n = static_cast(this->mixins_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 6, this->mixins(static_cast(i)), deterministic, target); + 6, this->mixins(static_cast(i)), target); } // .google.protobuf.Syntax syntax = 7; if (this->syntax() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray( 7, this->syntax(), target); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); + if (_internal_metadata_.have_unknown_fields()) { + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( + _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Api) return target; @@ -595,18 +644,22 @@ size_t Api::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.protobuf.Api) size_t total_size = 0; - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { + if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( + _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.Method methods = 2; { unsigned int count = static_cast(this->methods_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->methods(static_cast(i))); } } @@ -617,7 +670,7 @@ size_t Api::ByteSizeLong() const { total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->options(static_cast(i))); } } @@ -628,7 +681,7 @@ size_t Api::ByteSizeLong() const { total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->mixins(static_cast(i))); } } @@ -636,44 +689,44 @@ size_t Api::ByteSizeLong() const { // string name = 1; if (this->name().size() > 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->name()); } // string version = 4; if (this->version().size() > 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->version()); } // .google.protobuf.SourceContext source_context = 5; if (this->has_source_context()) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *source_context_); } // .google.protobuf.Syntax syntax = 7; if (this->syntax() != 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::EnumSize(this->syntax()); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->syntax()); } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void Api::MergeFrom(const ::google::protobuf::Message& from) { +void Api::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Api) GOOGLE_DCHECK_NE(&from, this); const Api* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Api) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Api) MergeFrom(*source); @@ -684,7 +737,7 @@ void Api::MergeFrom(const Api& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Api) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; methods_.MergeFrom(from.methods_); @@ -692,21 +745,21 @@ void Api::MergeFrom(const Api& from) { mixins_.MergeFrom(from.mixins_); if (from.name().size() > 0) { - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); + name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name_); } if (from.version().size() > 0) { - version_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.version_); + version_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.version_); } if (from.has_source_context()) { - mutable_source_context()->::google::protobuf::SourceContext::MergeFrom(from.source_context()); + mutable_source_context()->PROTOBUF_NAMESPACE_ID::SourceContext::MergeFrom(from.source_context()); } if (from.syntax() != 0) { set_syntax(from.syntax()); } } -void Api::CopyFrom(const ::google::protobuf::Message& from) { +void Api::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Api) if (&from == this) return; Clear(); @@ -730,21 +783,20 @@ void Api::Swap(Api* other) { } void Api::InternalSwap(Api* other) { using std::swap; + _internal_metadata_.Swap(&other->_internal_metadata_); CastToBase(&methods_)->InternalSwap(CastToBase(&other->methods_)); CastToBase(&options_)->InternalSwap(CastToBase(&other->options_)); CastToBase(&mixins_)->InternalSwap(CastToBase(&other->mixins_)); - name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - version_.Swap(&other->version_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + version_.Swap(&other->version_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(source_context_, other->source_context_); swap(syntax_, other->syntax_); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata Api::GetMetadata() const { - protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata Api::GetMetadata() const { + return GetMetadataStatic(); } @@ -752,6 +804,10 @@ void Api::InternalSwap(Api* other) { void Method::InitAsDefaultInstance() { } +class Method::HasBitSetters { + public: +}; + void Method::clear_options() { options_.Clear(); } @@ -766,28 +822,26 @@ const int Method::kSyntaxFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Method::Method() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Method) } Method::Method(const Method& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), options_(from.options_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); + name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name_); } - request_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + request_type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.request_type_url().size() > 0) { - request_type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.request_type_url_); + request_type_url_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.request_type_url_); } - response_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + response_type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.response_type_url().size() > 0) { - response_type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.response_type_url_); + response_type_url_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.response_type_url_); } ::memcpy(&request_streaming_, &from.request_streaming_, static_cast(reinterpret_cast(&syntax_) - @@ -796,9 +850,10 @@ Method::Method(const Method& from) } void Method::SharedCtor() { - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - request_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - response_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_Method_google_2fprotobuf_2fapi_2eproto.base); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + request_type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + response_type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(&request_streaming_, 0, static_cast( reinterpret_cast(&syntax_) - reinterpret_cast(&request_streaming_)) + sizeof(syntax_)); @@ -810,60 +865,137 @@ Method::~Method() { } void Method::SharedDtor() { - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - request_type_url_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - response_type_url_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + request_type_url_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + response_type_url_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void Method::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* Method::descriptor() { - ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const Method& Method::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_Method_google_2fprotobuf_2fapi_2eproto.base); return *internal_default_instance(); } void Method::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.Method) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; options_.Clear(); - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - request_type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - response_type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + request_type_url_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + response_type_url_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(&request_streaming_, 0, static_cast( reinterpret_cast(&syntax_) - reinterpret_cast(&request_streaming_)) + sizeof(syntax_)); _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* Method::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // string name = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(mutable_name(), ptr, ctx, "google.protobuf.Method.name"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // string request_type_url = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(mutable_request_type_url(), ptr, ctx, "google.protobuf.Method.request_type_url"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // bool request_streaming = 3; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) { + request_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // string response_type_url = 4; + case 4: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(mutable_response_type_url(), ptr, ctx, "google.protobuf.Method.response_type_url"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // bool response_streaming = 5; + case 5: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { + response_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.Option options = 6; + case 6: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_options(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 50); + } else goto handle_unusual; + continue; + // .google.protobuf.Syntax syntax = 7; + case 7: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 56)) { + ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + set_syntax(static_cast(val)); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Method::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Method) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string name = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_name())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "google.protobuf.Method.name")); } else { goto handle_unusual; @@ -873,13 +1005,12 @@ bool Method::MergePartialFromCodedStream( // string request_type_url = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_request_type_url())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->request_type_url().data(), static_cast(this->request_type_url().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "google.protobuf.Method.request_type_url")); } else { goto handle_unusual; @@ -889,11 +1020,10 @@ bool Method::MergePartialFromCodedStream( // bool request_streaming = 3; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (24 & 0xFF)) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &request_streaming_))); } else { goto handle_unusual; @@ -903,13 +1033,12 @@ bool Method::MergePartialFromCodedStream( // string response_type_url = 4; case 4: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (34 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_response_type_url())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->response_type_url().data(), static_cast(this->response_type_url().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "google.protobuf.Method.response_type_url")); } else { goto handle_unusual; @@ -919,11 +1048,10 @@ bool Method::MergePartialFromCodedStream( // bool response_streaming = 5; case 5: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (40 & 0xFF)) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &response_streaming_))); } else { goto handle_unusual; @@ -933,9 +1061,8 @@ bool Method::MergePartialFromCodedStream( // repeated .google.protobuf.Option options = 6; case 6: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (50 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_options())); } else { goto handle_unusual; @@ -945,13 +1072,12 @@ bool Method::MergePartialFromCodedStream( // .google.protobuf.Syntax syntax = 7; case 7: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) { - int value; - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (56 & 0xFF)) { + int value = 0; + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>( input, &value))); - set_syntax(static_cast< ::google::protobuf::Syntax >(value)); + set_syntax(static_cast< PROTOBUF_NAMESPACE_ID::Syntax >(value)); } else { goto handle_unusual; } @@ -963,7 +1089,7 @@ bool Method::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -977,57 +1103,58 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void Method::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.Method) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string name = 1; if (this->name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Method.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // string request_type_url = 2; if (this->request_type_url().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->request_type_url().data(), static_cast(this->request_type_url().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Method.request_type_url"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->request_type_url(), output); } // bool request_streaming = 3; if (this->request_streaming() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteBool(3, this->request_streaming(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(3, this->request_streaming(), output); } // string response_type_url = 4; if (this->response_type_url().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->response_type_url().data(), static_cast(this->response_type_url().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Method.response_type_url"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 4, this->response_type_url(), output); } // bool response_streaming = 5; if (this->response_streaming() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteBool(5, this->response_streaming(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(5, this->response_streaming(), output); } // repeated .google.protobuf.Option options = 6; for (unsigned int i = 0, n = static_cast(this->options_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 6, this->options(static_cast(i)), output); @@ -1035,84 +1162,83 @@ void Method::SerializeWithCachedSizes( // .google.protobuf.Syntax syntax = 7; if (this->syntax() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteEnum( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum( 7, this->syntax(), output); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); + if (_internal_metadata_.have_unknown_fields()) { + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( + _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.Method) } -::google::protobuf::uint8* Method::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* Method::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Method) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string name = 1; if (this->name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Method.name"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // string request_type_url = 2; if (this->request_type_url().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->request_type_url().data(), static_cast(this->request_type_url().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Method.request_type_url"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 2, this->request_type_url(), target); } // bool request_streaming = 3; if (this->request_streaming() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->request_streaming(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(3, this->request_streaming(), target); } // string response_type_url = 4; if (this->response_type_url().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->response_type_url().data(), static_cast(this->response_type_url().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Method.response_type_url"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 4, this->response_type_url(), target); } // bool response_streaming = 5; if (this->response_streaming() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(5, this->response_streaming(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(5, this->response_streaming(), target); } // repeated .google.protobuf.Option options = 6; for (unsigned int i = 0, n = static_cast(this->options_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 6, this->options(static_cast(i)), deterministic, target); + 6, this->options(static_cast(i)), target); } // .google.protobuf.Syntax syntax = 7; if (this->syntax() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray( 7, this->syntax(), target); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); + if (_internal_metadata_.have_unknown_fields()) { + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( + _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Method) return target; @@ -1122,18 +1248,22 @@ size_t Method::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.protobuf.Method) size_t total_size = 0; - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { + if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( + _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.Option options = 6; { unsigned int count = static_cast(this->options_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->options(static_cast(i))); } } @@ -1141,21 +1271,21 @@ size_t Method::ByteSizeLong() const { // string name = 1; if (this->name().size() > 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->name()); } // string request_type_url = 2; if (this->request_type_url().size() > 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->request_type_url()); } // string response_type_url = 4; if (this->response_type_url().size() > 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->response_type_url()); } @@ -1172,23 +1302,23 @@ size_t Method::ByteSizeLong() const { // .google.protobuf.Syntax syntax = 7; if (this->syntax() != 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::EnumSize(this->syntax()); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->syntax()); } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void Method::MergeFrom(const ::google::protobuf::Message& from) { +void Method::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Method) GOOGLE_DCHECK_NE(&from, this); const Method* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Method) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Method) MergeFrom(*source); @@ -1199,21 +1329,21 @@ void Method::MergeFrom(const Method& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Method) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; options_.MergeFrom(from.options_); if (from.name().size() > 0) { - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); + name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name_); } if (from.request_type_url().size() > 0) { - request_type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.request_type_url_); + request_type_url_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.request_type_url_); } if (from.response_type_url().size() > 0) { - response_type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.response_type_url_); + response_type_url_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.response_type_url_); } if (from.request_streaming() != 0) { set_request_streaming(from.request_streaming()); @@ -1226,7 +1356,7 @@ void Method::MergeFrom(const Method& from) { } } -void Method::CopyFrom(const ::google::protobuf::Message& from) { +void Method::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Method) if (&from == this) return; Clear(); @@ -1250,22 +1380,21 @@ void Method::Swap(Method* other) { } void Method::InternalSwap(Method* other) { using std::swap; + _internal_metadata_.Swap(&other->_internal_metadata_); CastToBase(&options_)->InternalSwap(CastToBase(&other->options_)); - name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - request_type_url_.Swap(&other->request_type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + request_type_url_.Swap(&other->request_type_url_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - response_type_url_.Swap(&other->response_type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + response_type_url_.Swap(&other->response_type_url_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(request_streaming_, other->request_streaming_); swap(response_streaming_, other->response_streaming_); swap(syntax_, other->syntax_); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata Method::GetMetadata() const { - protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata Method::GetMetadata() const { + return GetMetadataStatic(); } @@ -1273,36 +1402,39 @@ void Method::InternalSwap(Method* other) { void Mixin::InitAsDefaultInstance() { } +class Mixin::HasBitSetters { + public: +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Mixin::kNameFieldNumber; const int Mixin::kRootFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Mixin::Mixin() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Mixin) } Mixin::Mixin(const Mixin& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); + name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name_); } - root_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + root_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.root().size() > 0) { - root_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.root_); + root_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.root_); } // @@protoc_insertion_point(copy_constructor:google.protobuf.Mixin) } void Mixin::SharedCtor() { - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - root_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_Mixin_google_2fprotobuf_2fapi_2eproto.base); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + root_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } Mixin::~Mixin() { @@ -1311,54 +1443,90 @@ Mixin::~Mixin() { } void Mixin::SharedDtor() { - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - root_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + root_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void Mixin::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* Mixin::descriptor() { - ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const Mixin& Mixin::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_Mixin_google_2fprotobuf_2fapi_2eproto.base); return *internal_default_instance(); } void Mixin::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.Mixin) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - root_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + root_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* Mixin::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // string name = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(mutable_name(), ptr, ctx, "google.protobuf.Mixin.name"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // string root = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(mutable_root(), ptr, ctx, "google.protobuf.Mixin.root"); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Mixin::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Mixin) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string name = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_name())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "google.protobuf.Mixin.name")); } else { goto handle_unusual; @@ -1368,13 +1536,12 @@ bool Mixin::MergePartialFromCodedStream( // string root = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_root())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->root().data(), static_cast(this->root().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "google.protobuf.Mixin.root")); } else { goto handle_unusual; @@ -1387,7 +1554,7 @@ bool Mixin::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -1401,72 +1568,72 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void Mixin::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.Mixin) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string name = 1; if (this->name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Mixin.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // string root = 2; if (this->root().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->root().data(), static_cast(this->root().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Mixin.root"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->root(), output); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); + if (_internal_metadata_.have_unknown_fields()) { + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( + _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.Mixin) } -::google::protobuf::uint8* Mixin::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* Mixin::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Mixin) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string name = 1; if (this->name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Mixin.name"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // string root = 2; if (this->root().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->root().data(), static_cast(this->root().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Mixin.root"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 2, this->root(), target); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); + if (_internal_metadata_.have_unknown_fields()) { + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( + _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Mixin) return target; @@ -1476,39 +1643,43 @@ size_t Mixin::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.protobuf.Mixin) size_t total_size = 0; - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { + if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( + _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // string name = 1; if (this->name().size() > 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->name()); } // string root = 2; if (this->root().size() > 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->root()); } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void Mixin::MergeFrom(const ::google::protobuf::Message& from) { +void Mixin::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Mixin) GOOGLE_DCHECK_NE(&from, this); const Mixin* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Mixin) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Mixin) MergeFrom(*source); @@ -1519,20 +1690,20 @@ void Mixin::MergeFrom(const Mixin& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Mixin) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.name().size() > 0) { - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); + name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name_); } if (from.root().size() > 0) { - root_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.root_); + root_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.root_); } } -void Mixin::CopyFrom(const ::google::protobuf::Message& from) { +void Mixin::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Mixin) if (&from == this) return; Clear(); @@ -1556,34 +1727,31 @@ void Mixin::Swap(Mixin* other) { } void Mixin::InternalSwap(Mixin* other) { using std::swap; - name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - root_.Swap(&other->root_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); _internal_metadata_.Swap(&other->_internal_metadata_); + name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + root_.Swap(&other->root_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); } -::google::protobuf::Metadata Mixin::GetMetadata() const { - protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata Mixin::GetMetadata() const { + return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Api* Arena::CreateMaybeMessage< ::google::protobuf::Api >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::Api >(arena); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::Api* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Api >(Arena* arena) { + return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::Api >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Method* Arena::CreateMaybeMessage< ::google::protobuf::Method >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::Method >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::Method* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Method >(Arena* arena) { + return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::Method >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Mixin* Arena::CreateMaybeMessage< ::google::protobuf::Mixin >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::Mixin >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::Mixin* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Mixin >(Arena* arena) { + return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::Mixin >(arena); } -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) +#include diff --git a/third_party/protobuf/src/google/protobuf/api.pb.h b/third_party/protobuf/src/google/protobuf/api.pb.h index 581e21a5..5d4f0007 100644 --- a/third_party/protobuf/src/google/protobuf/api.pb.h +++ b/third_party/protobuf/src/google/protobuf/api.pb.h @@ -1,24 +1,25 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/api.proto -#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto -#define PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto +#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto +#include #include -#include - -#if GOOGLE_PROTOBUF_VERSION < 3006001 +#include +#if PROTOBUF_VERSION < 3008000 #error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update +#error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3008000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please +#error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include @@ -26,6 +27,7 @@ #include #include #include +#include #include #include // IWYU pragma: export #include // IWYU pragma: export @@ -33,62 +35,63 @@ #include #include // @@protoc_insertion_point(includes) -#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fapi_2eproto LIBPROTOBUF_EXPORT +#include +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fapi_2eproto PROTOBUF_EXPORT +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE -namespace protobuf_google_2fprotobuf_2fapi_2eproto { // Internal implementation detail -- do not use these members. -struct LIBPROTOBUF_EXPORT TableStruct { - static const ::google::protobuf::internal::ParseTableField entries[]; - static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; - static const ::google::protobuf::internal::ParseTable schema[3]; - static const ::google::protobuf::internal::FieldMetadata field_metadata[]; - static const ::google::protobuf::internal::SerializationTable serialization_table[]; - static const ::google::protobuf::uint32 offsets[]; +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fapi_2eproto { + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[3] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; + static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; + static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; -void LIBPROTOBUF_EXPORT AddDescriptors(); -} // namespace protobuf_google_2fprotobuf_2fapi_2eproto -namespace google { -namespace protobuf { +extern PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fapi_2eproto; +PROTOBUF_NAMESPACE_OPEN class Api; class ApiDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern ApiDefaultTypeInternal _Api_default_instance_; +PROTOBUF_EXPORT extern ApiDefaultTypeInternal _Api_default_instance_; class Method; class MethodDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern MethodDefaultTypeInternal _Method_default_instance_; +PROTOBUF_EXPORT extern MethodDefaultTypeInternal _Method_default_instance_; class Mixin; class MixinDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern MixinDefaultTypeInternal _Mixin_default_instance_; -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Api* Arena::CreateMaybeMessage<::google::protobuf::Api>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Method* Arena::CreateMaybeMessage<::google::protobuf::Method>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Mixin* Arena::CreateMaybeMessage<::google::protobuf::Mixin>(Arena*); -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { +PROTOBUF_EXPORT extern MixinDefaultTypeInternal _Mixin_default_instance_; +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::Api* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::Method* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::Mixin* Arena::CreateMaybeMessage(Arena*); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN // =================================================================== -class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Api) */ { +class PROTOBUF_EXPORT Api : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Api) */ { public: Api(); virtual ~Api(); Api(const Api& from); - - inline Api& operator=(const Api& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 Api(Api&& from) noexcept : Api() { *this = ::std::move(from); } + inline Api& operator=(const Api& from) { + CopyFrom(from); + return *this; + } inline Api& operator=(Api&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -97,8 +100,16 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in } return *this; } - #endif - static const ::google::protobuf::Descriptor* descriptor(); + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const Api& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -117,43 +128,58 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in // implements Message ---------------------------------------------- inline Api* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - Api* New(::google::protobuf::Arena* arena) const final { + Api* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const Api& from); void MergeFrom(const Api& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Api* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Api"; + } private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { + return nullptr; } inline void* MaybeArenaPtr() const { - return NULL; + return nullptr; } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fapi_2eproto); + return ::descriptor_table_google_2fprotobuf_2fapi_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -163,117 +189,110 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in int methods_size() const; void clear_methods(); static const int kMethodsFieldNumber = 2; - ::google::protobuf::Method* mutable_methods(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Method >* + PROTOBUF_NAMESPACE_ID::Method* mutable_methods(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Method >* mutable_methods(); - const ::google::protobuf::Method& methods(int index) const; - ::google::protobuf::Method* add_methods(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Method >& + const PROTOBUF_NAMESPACE_ID::Method& methods(int index) const; + PROTOBUF_NAMESPACE_ID::Method* add_methods(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Method >& methods() const; // repeated .google.protobuf.Option options = 3; int options_size() const; void clear_options(); static const int kOptionsFieldNumber = 3; - ::google::protobuf::Option* mutable_options(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >* + PROTOBUF_NAMESPACE_ID::Option* mutable_options(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Option >* mutable_options(); - const ::google::protobuf::Option& options(int index) const; - ::google::protobuf::Option* add_options(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >& + const PROTOBUF_NAMESPACE_ID::Option& options(int index) const; + PROTOBUF_NAMESPACE_ID::Option* add_options(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Option >& options() const; // repeated .google.protobuf.Mixin mixins = 6; int mixins_size() const; void clear_mixins(); static const int kMixinsFieldNumber = 6; - ::google::protobuf::Mixin* mutable_mixins(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >* + PROTOBUF_NAMESPACE_ID::Mixin* mutable_mixins(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Mixin >* mutable_mixins(); - const ::google::protobuf::Mixin& mixins(int index) const; - ::google::protobuf::Mixin* add_mixins(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >& + const PROTOBUF_NAMESPACE_ID::Mixin& mixins(int index) const; + PROTOBUF_NAMESPACE_ID::Mixin* add_mixins(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Mixin >& mixins() const; // string name = 1; void clear_name(); static const int kNameFieldNumber = 1; - const ::std::string& name() const; - void set_name(const ::std::string& value); - #if LANG_CXX11 - void set_name(::std::string&& value); - #endif + const std::string& name() const; + void set_name(const std::string& value); + void set_name(std::string&& value); void set_name(const char* value); void set_name(const char* value, size_t size); - ::std::string* mutable_name(); - ::std::string* release_name(); - void set_allocated_name(::std::string* name); + std::string* mutable_name(); + std::string* release_name(); + void set_allocated_name(std::string* name); // string version = 4; void clear_version(); static const int kVersionFieldNumber = 4; - const ::std::string& version() const; - void set_version(const ::std::string& value); - #if LANG_CXX11 - void set_version(::std::string&& value); - #endif + const std::string& version() const; + void set_version(const std::string& value); + void set_version(std::string&& value); void set_version(const char* value); void set_version(const char* value, size_t size); - ::std::string* mutable_version(); - ::std::string* release_version(); - void set_allocated_version(::std::string* version); + std::string* mutable_version(); + std::string* release_version(); + void set_allocated_version(std::string* version); // .google.protobuf.SourceContext source_context = 5; bool has_source_context() const; void clear_source_context(); static const int kSourceContextFieldNumber = 5; - private: - const ::google::protobuf::SourceContext& _internal_source_context() const; - public: - const ::google::protobuf::SourceContext& source_context() const; - ::google::protobuf::SourceContext* release_source_context(); - ::google::protobuf::SourceContext* mutable_source_context(); - void set_allocated_source_context(::google::protobuf::SourceContext* source_context); + const PROTOBUF_NAMESPACE_ID::SourceContext& source_context() const; + PROTOBUF_NAMESPACE_ID::SourceContext* release_source_context(); + PROTOBUF_NAMESPACE_ID::SourceContext* mutable_source_context(); + void set_allocated_source_context(PROTOBUF_NAMESPACE_ID::SourceContext* source_context); // .google.protobuf.Syntax syntax = 7; void clear_syntax(); static const int kSyntaxFieldNumber = 7; - ::google::protobuf::Syntax syntax() const; - void set_syntax(::google::protobuf::Syntax value); + PROTOBUF_NAMESPACE_ID::Syntax syntax() const; + void set_syntax(PROTOBUF_NAMESPACE_ID::Syntax value); // @@protoc_insertion_point(class_scope:google.protobuf.Api) private: + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Method > methods_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin > mixins_; - ::google::protobuf::internal::ArenaStringPtr name_; - ::google::protobuf::internal::ArenaStringPtr version_; - ::google::protobuf::SourceContext* source_context_; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Method > methods_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Option > options_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Mixin > mixins_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr version_; + PROTOBUF_NAMESPACE_ID::SourceContext* source_context_; int syntax_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2fapi_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Method) */ { +class PROTOBUF_EXPORT Method : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Method) */ { public: Method(); virtual ~Method(); Method(const Method& from); - - inline Method& operator=(const Method& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 Method(Method&& from) noexcept : Method() { *this = ::std::move(from); } + inline Method& operator=(const Method& from) { + CopyFrom(from); + return *this; + } inline Method& operator=(Method&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -282,8 +301,16 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc } return *this; } - #endif - static const ::google::protobuf::Descriptor* descriptor(); + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const Method& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -302,43 +329,58 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc // implements Message ---------------------------------------------- inline Method* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - Method* New(::google::protobuf::Arena* arena) const final { + Method* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const Method& from); void MergeFrom(const Method& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Method* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Method"; + } private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { + return nullptr; } inline void* MaybeArenaPtr() const { - return NULL; + return nullptr; } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fapi_2eproto); + return ::descriptor_table_google_2fprotobuf_2fapi_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -348,55 +390,49 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc int options_size() const; void clear_options(); static const int kOptionsFieldNumber = 6; - ::google::protobuf::Option* mutable_options(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >* + PROTOBUF_NAMESPACE_ID::Option* mutable_options(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Option >* mutable_options(); - const ::google::protobuf::Option& options(int index) const; - ::google::protobuf::Option* add_options(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >& + const PROTOBUF_NAMESPACE_ID::Option& options(int index) const; + PROTOBUF_NAMESPACE_ID::Option* add_options(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Option >& options() const; // string name = 1; void clear_name(); static const int kNameFieldNumber = 1; - const ::std::string& name() const; - void set_name(const ::std::string& value); - #if LANG_CXX11 - void set_name(::std::string&& value); - #endif + const std::string& name() const; + void set_name(const std::string& value); + void set_name(std::string&& value); void set_name(const char* value); void set_name(const char* value, size_t size); - ::std::string* mutable_name(); - ::std::string* release_name(); - void set_allocated_name(::std::string* name); + std::string* mutable_name(); + std::string* release_name(); + void set_allocated_name(std::string* name); // string request_type_url = 2; void clear_request_type_url(); static const int kRequestTypeUrlFieldNumber = 2; - const ::std::string& request_type_url() const; - void set_request_type_url(const ::std::string& value); - #if LANG_CXX11 - void set_request_type_url(::std::string&& value); - #endif + const std::string& request_type_url() const; + void set_request_type_url(const std::string& value); + void set_request_type_url(std::string&& value); void set_request_type_url(const char* value); void set_request_type_url(const char* value, size_t size); - ::std::string* mutable_request_type_url(); - ::std::string* release_request_type_url(); - void set_allocated_request_type_url(::std::string* request_type_url); + std::string* mutable_request_type_url(); + std::string* release_request_type_url(); + void set_allocated_request_type_url(std::string* request_type_url); // string response_type_url = 4; void clear_response_type_url(); static const int kResponseTypeUrlFieldNumber = 4; - const ::std::string& response_type_url() const; - void set_response_type_url(const ::std::string& value); - #if LANG_CXX11 - void set_response_type_url(::std::string&& value); - #endif + const std::string& response_type_url() const; + void set_response_type_url(const std::string& value); + void set_response_type_url(std::string&& value); void set_response_type_url(const char* value); void set_response_type_url(const char* value, size_t size); - ::std::string* mutable_response_type_url(); - ::std::string* release_response_type_url(); - void set_allocated_response_type_url(::std::string* response_type_url); + std::string* mutable_response_type_url(); + std::string* release_response_type_url(); + void set_allocated_response_type_url(std::string* response_type_url); // bool request_streaming = 3; void clear_request_streaming(); @@ -413,42 +449,42 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc // .google.protobuf.Syntax syntax = 7; void clear_syntax(); static const int kSyntaxFieldNumber = 7; - ::google::protobuf::Syntax syntax() const; - void set_syntax(::google::protobuf::Syntax value); + PROTOBUF_NAMESPACE_ID::Syntax syntax() const; + void set_syntax(PROTOBUF_NAMESPACE_ID::Syntax value); // @@protoc_insertion_point(class_scope:google.protobuf.Method) private: + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_; - ::google::protobuf::internal::ArenaStringPtr name_; - ::google::protobuf::internal::ArenaStringPtr request_type_url_; - ::google::protobuf::internal::ArenaStringPtr response_type_url_; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Option > options_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr request_type_url_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr response_type_url_; bool request_streaming_; bool response_streaming_; int syntax_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2fapi_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Mixin) */ { +class PROTOBUF_EXPORT Mixin : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Mixin) */ { public: Mixin(); virtual ~Mixin(); Mixin(const Mixin& from); - - inline Mixin& operator=(const Mixin& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 Mixin(Mixin&& from) noexcept : Mixin() { *this = ::std::move(from); } + inline Mixin& operator=(const Mixin& from) { + CopyFrom(from); + return *this; + } inline Mixin& operator=(Mixin&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -457,8 +493,16 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_ } return *this; } - #endif - static const ::google::protobuf::Descriptor* descriptor(); + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const Mixin& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -477,43 +521,58 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_ // implements Message ---------------------------------------------- inline Mixin* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - Mixin* New(::google::protobuf::Arena* arena) const final { + Mixin* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const Mixin& from); void MergeFrom(const Mixin& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Mixin* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Mixin"; + } private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { + return nullptr; } inline void* MaybeArenaPtr() const { - return NULL; + return nullptr; } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fapi_2eproto); + return ::descriptor_table_google_2fprotobuf_2fapi_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -522,39 +581,36 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_ // string name = 1; void clear_name(); static const int kNameFieldNumber = 1; - const ::std::string& name() const; - void set_name(const ::std::string& value); - #if LANG_CXX11 - void set_name(::std::string&& value); - #endif + const std::string& name() const; + void set_name(const std::string& value); + void set_name(std::string&& value); void set_name(const char* value); void set_name(const char* value, size_t size); - ::std::string* mutable_name(); - ::std::string* release_name(); - void set_allocated_name(::std::string* name); + std::string* mutable_name(); + std::string* release_name(); + void set_allocated_name(std::string* name); // string root = 2; void clear_root(); static const int kRootFieldNumber = 2; - const ::std::string& root() const; - void set_root(const ::std::string& value); - #if LANG_CXX11 - void set_root(::std::string&& value); - #endif + const std::string& root() const; + void set_root(const std::string& value); + void set_root(std::string&& value); void set_root(const char* value); void set_root(const char* value, size_t size); - ::std::string* mutable_root(); - ::std::string* release_root(); - void set_allocated_root(::std::string* root); + std::string* mutable_root(); + std::string* release_root(); + void set_allocated_root(std::string* root); // @@protoc_insertion_point(class_scope:google.protobuf.Mixin) private: + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::ArenaStringPtr name_; - ::google::protobuf::internal::ArenaStringPtr root_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr root_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2fapi_2eproto; }; // =================================================================== @@ -569,54 +625,52 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_ // string name = 1; inline void Api::clear_name() { - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline const ::std::string& Api::name() const { +inline const std::string& Api::name() const { // @@protoc_insertion_point(field_get:google.protobuf.Api.name) return name_.GetNoArena(); } -inline void Api::set_name(const ::std::string& value) { +inline void Api::set_name(const std::string& value) { - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); + name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.protobuf.Api.name) } -#if LANG_CXX11 -inline void Api::set_name(::std::string&& value) { +inline void Api::set_name(std::string&& value) { name_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Api.name) } -#endif inline void Api::set_name(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.protobuf.Api.name) } inline void Api::set_name(const char* value, size_t size) { - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:google.protobuf.Api.name) } -inline ::std::string* Api::mutable_name() { +inline std::string* Api::mutable_name() { // @@protoc_insertion_point(field_mutable:google.protobuf.Api.name) - return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return name_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline ::std::string* Api::release_name() { +inline std::string* Api::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.Api.name) - return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return name_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline void Api::set_allocated_name(::std::string* name) { - if (name != NULL) { +inline void Api::set_allocated_name(std::string* name) { + if (name != nullptr) { } else { } - name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name); + name_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name); // @@protoc_insertion_point(field_set_allocated:google.protobuf.Api.name) } @@ -627,24 +681,24 @@ inline int Api::methods_size() const { inline void Api::clear_methods() { methods_.Clear(); } -inline ::google::protobuf::Method* Api::mutable_methods(int index) { +inline PROTOBUF_NAMESPACE_ID::Method* Api::mutable_methods(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Api.methods) return methods_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Method >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Method >* Api::mutable_methods() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Api.methods) return &methods_; } -inline const ::google::protobuf::Method& Api::methods(int index) const { +inline const PROTOBUF_NAMESPACE_ID::Method& Api::methods(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.Api.methods) return methods_.Get(index); } -inline ::google::protobuf::Method* Api::add_methods() { +inline PROTOBUF_NAMESPACE_ID::Method* Api::add_methods() { // @@protoc_insertion_point(field_add:google.protobuf.Api.methods) return methods_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Method >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Method >& Api::methods() const { // @@protoc_insertion_point(field_list:google.protobuf.Api.methods) return methods_; @@ -654,24 +708,24 @@ Api::methods() const { inline int Api::options_size() const { return options_.size(); } -inline ::google::protobuf::Option* Api::mutable_options(int index) { +inline PROTOBUF_NAMESPACE_ID::Option* Api::mutable_options(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Api.options) return options_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Option >* Api::mutable_options() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Api.options) return &options_; } -inline const ::google::protobuf::Option& Api::options(int index) const { +inline const PROTOBUF_NAMESPACE_ID::Option& Api::options(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.Api.options) return options_.Get(index); } -inline ::google::protobuf::Option* Api::add_options() { +inline PROTOBUF_NAMESPACE_ID::Option* Api::add_options() { // @@protoc_insertion_point(field_add:google.protobuf.Api.options) return options_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Option >& Api::options() const { // @@protoc_insertion_point(field_list:google.protobuf.Api.options) return options_; @@ -679,95 +733,90 @@ Api::options() const { // string version = 4; inline void Api::clear_version() { - version_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + version_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline const ::std::string& Api::version() const { +inline const std::string& Api::version() const { // @@protoc_insertion_point(field_get:google.protobuf.Api.version) return version_.GetNoArena(); } -inline void Api::set_version(const ::std::string& value) { +inline void Api::set_version(const std::string& value) { - version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); + version_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.protobuf.Api.version) } -#if LANG_CXX11 -inline void Api::set_version(::std::string&& value) { +inline void Api::set_version(std::string&& value) { version_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Api.version) } -#endif inline void Api::set_version(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); - version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + version_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.protobuf.Api.version) } inline void Api::set_version(const char* value, size_t size) { - version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + version_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:google.protobuf.Api.version) } -inline ::std::string* Api::mutable_version() { +inline std::string* Api::mutable_version() { // @@protoc_insertion_point(field_mutable:google.protobuf.Api.version) - return version_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return version_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline ::std::string* Api::release_version() { +inline std::string* Api::release_version() { // @@protoc_insertion_point(field_release:google.protobuf.Api.version) - return version_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return version_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline void Api::set_allocated_version(::std::string* version) { - if (version != NULL) { +inline void Api::set_allocated_version(std::string* version) { + if (version != nullptr) { } else { } - version_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), version); + version_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), version); // @@protoc_insertion_point(field_set_allocated:google.protobuf.Api.version) } // .google.protobuf.SourceContext source_context = 5; inline bool Api::has_source_context() const { - return this != internal_default_instance() && source_context_ != NULL; + return this != internal_default_instance() && source_context_ != nullptr; } -inline const ::google::protobuf::SourceContext& Api::_internal_source_context() const { - return *source_context_; -} -inline const ::google::protobuf::SourceContext& Api::source_context() const { - const ::google::protobuf::SourceContext* p = source_context_; +inline const PROTOBUF_NAMESPACE_ID::SourceContext& Api::source_context() const { + const PROTOBUF_NAMESPACE_ID::SourceContext* p = source_context_; // @@protoc_insertion_point(field_get:google.protobuf.Api.source_context) - return p != NULL ? *p : *reinterpret_cast( - &::google::protobuf::_SourceContext_default_instance_); + return p != nullptr ? *p : *reinterpret_cast( + &PROTOBUF_NAMESPACE_ID::_SourceContext_default_instance_); } -inline ::google::protobuf::SourceContext* Api::release_source_context() { +inline PROTOBUF_NAMESPACE_ID::SourceContext* Api::release_source_context() { // @@protoc_insertion_point(field_release:google.protobuf.Api.source_context) - ::google::protobuf::SourceContext* temp = source_context_; - source_context_ = NULL; + PROTOBUF_NAMESPACE_ID::SourceContext* temp = source_context_; + source_context_ = nullptr; return temp; } -inline ::google::protobuf::SourceContext* Api::mutable_source_context() { +inline PROTOBUF_NAMESPACE_ID::SourceContext* Api::mutable_source_context() { - if (source_context_ == NULL) { - auto* p = CreateMaybeMessage<::google::protobuf::SourceContext>(GetArenaNoVirtual()); + if (source_context_ == nullptr) { + auto* p = CreateMaybeMessage(GetArenaNoVirtual()); source_context_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.Api.source_context) return source_context_; } -inline void Api::set_allocated_source_context(::google::protobuf::SourceContext* source_context) { - ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); - if (message_arena == NULL) { - delete reinterpret_cast< ::google::protobuf::MessageLite*>(source_context_); +inline void Api::set_allocated_source_context(PROTOBUF_NAMESPACE_ID::SourceContext* source_context) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context_); } if (source_context) { - ::google::protobuf::Arena* submessage_arena = NULL; + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { - source_context = ::google::protobuf::internal::GetOwnedMessage( + source_context = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, source_context, submessage_arena); } @@ -785,24 +834,24 @@ inline int Api::mixins_size() const { inline void Api::clear_mixins() { mixins_.Clear(); } -inline ::google::protobuf::Mixin* Api::mutable_mixins(int index) { +inline PROTOBUF_NAMESPACE_ID::Mixin* Api::mutable_mixins(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Api.mixins) return mixins_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Mixin >* Api::mutable_mixins() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Api.mixins) return &mixins_; } -inline const ::google::protobuf::Mixin& Api::mixins(int index) const { +inline const PROTOBUF_NAMESPACE_ID::Mixin& Api::mixins(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.Api.mixins) return mixins_.Get(index); } -inline ::google::protobuf::Mixin* Api::add_mixins() { +inline PROTOBUF_NAMESPACE_ID::Mixin* Api::add_mixins() { // @@protoc_insertion_point(field_add:google.protobuf.Api.mixins) return mixins_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Mixin >& Api::mixins() const { // @@protoc_insertion_point(field_list:google.protobuf.Api.mixins) return mixins_; @@ -812,11 +861,11 @@ Api::mixins() const { inline void Api::clear_syntax() { syntax_ = 0; } -inline ::google::protobuf::Syntax Api::syntax() const { +inline PROTOBUF_NAMESPACE_ID::Syntax Api::syntax() const { // @@protoc_insertion_point(field_get:google.protobuf.Api.syntax) - return static_cast< ::google::protobuf::Syntax >(syntax_); + return static_cast< PROTOBUF_NAMESPACE_ID::Syntax >(syntax_); } -inline void Api::set_syntax(::google::protobuf::Syntax value) { +inline void Api::set_syntax(PROTOBUF_NAMESPACE_ID::Syntax value) { syntax_ = value; // @@protoc_insertion_point(field_set:google.protobuf.Api.syntax) @@ -828,107 +877,103 @@ inline void Api::set_syntax(::google::protobuf::Syntax value) { // string name = 1; inline void Method::clear_name() { - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline const ::std::string& Method::name() const { +inline const std::string& Method::name() const { // @@protoc_insertion_point(field_get:google.protobuf.Method.name) return name_.GetNoArena(); } -inline void Method::set_name(const ::std::string& value) { +inline void Method::set_name(const std::string& value) { - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); + name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.protobuf.Method.name) } -#if LANG_CXX11 -inline void Method::set_name(::std::string&& value) { +inline void Method::set_name(std::string&& value) { name_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Method.name) } -#endif inline void Method::set_name(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.protobuf.Method.name) } inline void Method::set_name(const char* value, size_t size) { - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:google.protobuf.Method.name) } -inline ::std::string* Method::mutable_name() { +inline std::string* Method::mutable_name() { // @@protoc_insertion_point(field_mutable:google.protobuf.Method.name) - return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return name_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline ::std::string* Method::release_name() { +inline std::string* Method::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.Method.name) - return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return name_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline void Method::set_allocated_name(::std::string* name) { - if (name != NULL) { +inline void Method::set_allocated_name(std::string* name) { + if (name != nullptr) { } else { } - name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name); + name_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name); // @@protoc_insertion_point(field_set_allocated:google.protobuf.Method.name) } // string request_type_url = 2; inline void Method::clear_request_type_url() { - request_type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + request_type_url_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline const ::std::string& Method::request_type_url() const { +inline const std::string& Method::request_type_url() const { // @@protoc_insertion_point(field_get:google.protobuf.Method.request_type_url) return request_type_url_.GetNoArena(); } -inline void Method::set_request_type_url(const ::std::string& value) { +inline void Method::set_request_type_url(const std::string& value) { - request_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); + request_type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.protobuf.Method.request_type_url) } -#if LANG_CXX11 -inline void Method::set_request_type_url(::std::string&& value) { +inline void Method::set_request_type_url(std::string&& value) { request_type_url_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Method.request_type_url) } -#endif inline void Method::set_request_type_url(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); - request_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + request_type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.protobuf.Method.request_type_url) } inline void Method::set_request_type_url(const char* value, size_t size) { - request_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + request_type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:google.protobuf.Method.request_type_url) } -inline ::std::string* Method::mutable_request_type_url() { +inline std::string* Method::mutable_request_type_url() { // @@protoc_insertion_point(field_mutable:google.protobuf.Method.request_type_url) - return request_type_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return request_type_url_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline ::std::string* Method::release_request_type_url() { +inline std::string* Method::release_request_type_url() { // @@protoc_insertion_point(field_release:google.protobuf.Method.request_type_url) - return request_type_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return request_type_url_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline void Method::set_allocated_request_type_url(::std::string* request_type_url) { - if (request_type_url != NULL) { +inline void Method::set_allocated_request_type_url(std::string* request_type_url) { + if (request_type_url != nullptr) { } else { } - request_type_url_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), request_type_url); + request_type_url_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), request_type_url); // @@protoc_insertion_point(field_set_allocated:google.protobuf.Method.request_type_url) } @@ -948,54 +993,52 @@ inline void Method::set_request_streaming(bool value) { // string response_type_url = 4; inline void Method::clear_response_type_url() { - response_type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + response_type_url_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline const ::std::string& Method::response_type_url() const { +inline const std::string& Method::response_type_url() const { // @@protoc_insertion_point(field_get:google.protobuf.Method.response_type_url) return response_type_url_.GetNoArena(); } -inline void Method::set_response_type_url(const ::std::string& value) { +inline void Method::set_response_type_url(const std::string& value) { - response_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); + response_type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.protobuf.Method.response_type_url) } -#if LANG_CXX11 -inline void Method::set_response_type_url(::std::string&& value) { +inline void Method::set_response_type_url(std::string&& value) { response_type_url_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Method.response_type_url) } -#endif inline void Method::set_response_type_url(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); - response_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + response_type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.protobuf.Method.response_type_url) } inline void Method::set_response_type_url(const char* value, size_t size) { - response_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + response_type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:google.protobuf.Method.response_type_url) } -inline ::std::string* Method::mutable_response_type_url() { +inline std::string* Method::mutable_response_type_url() { // @@protoc_insertion_point(field_mutable:google.protobuf.Method.response_type_url) - return response_type_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return response_type_url_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline ::std::string* Method::release_response_type_url() { +inline std::string* Method::release_response_type_url() { // @@protoc_insertion_point(field_release:google.protobuf.Method.response_type_url) - return response_type_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return response_type_url_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline void Method::set_allocated_response_type_url(::std::string* response_type_url) { - if (response_type_url != NULL) { +inline void Method::set_allocated_response_type_url(std::string* response_type_url) { + if (response_type_url != nullptr) { } else { } - response_type_url_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), response_type_url); + response_type_url_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), response_type_url); // @@protoc_insertion_point(field_set_allocated:google.protobuf.Method.response_type_url) } @@ -1017,24 +1060,24 @@ inline void Method::set_response_streaming(bool value) { inline int Method::options_size() const { return options_.size(); } -inline ::google::protobuf::Option* Method::mutable_options(int index) { +inline PROTOBUF_NAMESPACE_ID::Option* Method::mutable_options(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Method.options) return options_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Option >* Method::mutable_options() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Method.options) return &options_; } -inline const ::google::protobuf::Option& Method::options(int index) const { +inline const PROTOBUF_NAMESPACE_ID::Option& Method::options(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.Method.options) return options_.Get(index); } -inline ::google::protobuf::Option* Method::add_options() { +inline PROTOBUF_NAMESPACE_ID::Option* Method::add_options() { // @@protoc_insertion_point(field_add:google.protobuf.Method.options) return options_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Option >& Method::options() const { // @@protoc_insertion_point(field_list:google.protobuf.Method.options) return options_; @@ -1044,11 +1087,11 @@ Method::options() const { inline void Method::clear_syntax() { syntax_ = 0; } -inline ::google::protobuf::Syntax Method::syntax() const { +inline PROTOBUF_NAMESPACE_ID::Syntax Method::syntax() const { // @@protoc_insertion_point(field_get:google.protobuf.Method.syntax) - return static_cast< ::google::protobuf::Syntax >(syntax_); + return static_cast< PROTOBUF_NAMESPACE_ID::Syntax >(syntax_); } -inline void Method::set_syntax(::google::protobuf::Syntax value) { +inline void Method::set_syntax(PROTOBUF_NAMESPACE_ID::Syntax value) { syntax_ = value; // @@protoc_insertion_point(field_set:google.protobuf.Method.syntax) @@ -1060,107 +1103,103 @@ inline void Method::set_syntax(::google::protobuf::Syntax value) { // string name = 1; inline void Mixin::clear_name() { - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline const ::std::string& Mixin::name() const { +inline const std::string& Mixin::name() const { // @@protoc_insertion_point(field_get:google.protobuf.Mixin.name) return name_.GetNoArena(); } -inline void Mixin::set_name(const ::std::string& value) { +inline void Mixin::set_name(const std::string& value) { - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); + name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.protobuf.Mixin.name) } -#if LANG_CXX11 -inline void Mixin::set_name(::std::string&& value) { +inline void Mixin::set_name(std::string&& value) { name_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Mixin.name) } -#endif inline void Mixin::set_name(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.protobuf.Mixin.name) } inline void Mixin::set_name(const char* value, size_t size) { - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:google.protobuf.Mixin.name) } -inline ::std::string* Mixin::mutable_name() { +inline std::string* Mixin::mutable_name() { // @@protoc_insertion_point(field_mutable:google.protobuf.Mixin.name) - return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return name_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline ::std::string* Mixin::release_name() { +inline std::string* Mixin::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.Mixin.name) - return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return name_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline void Mixin::set_allocated_name(::std::string* name) { - if (name != NULL) { +inline void Mixin::set_allocated_name(std::string* name) { + if (name != nullptr) { } else { } - name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name); + name_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name); // @@protoc_insertion_point(field_set_allocated:google.protobuf.Mixin.name) } // string root = 2; inline void Mixin::clear_root() { - root_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + root_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline const ::std::string& Mixin::root() const { +inline const std::string& Mixin::root() const { // @@protoc_insertion_point(field_get:google.protobuf.Mixin.root) return root_.GetNoArena(); } -inline void Mixin::set_root(const ::std::string& value) { +inline void Mixin::set_root(const std::string& value) { - root_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); + root_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.protobuf.Mixin.root) } -#if LANG_CXX11 -inline void Mixin::set_root(::std::string&& value) { +inline void Mixin::set_root(std::string&& value) { root_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Mixin.root) } -#endif inline void Mixin::set_root(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); - root_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + root_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.protobuf.Mixin.root) } inline void Mixin::set_root(const char* value, size_t size) { - root_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + root_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:google.protobuf.Mixin.root) } -inline ::std::string* Mixin::mutable_root() { +inline std::string* Mixin::mutable_root() { // @@protoc_insertion_point(field_mutable:google.protobuf.Mixin.root) - return root_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return root_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline ::std::string* Mixin::release_root() { +inline std::string* Mixin::release_root() { // @@protoc_insertion_point(field_release:google.protobuf.Mixin.root) - return root_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return root_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline void Mixin::set_allocated_root(::std::string* root) { - if (root != NULL) { +inline void Mixin::set_allocated_root(std::string* root) { + if (root != nullptr) { } else { } - root_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), root); + root_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), root); // @@protoc_insertion_point(field_set_allocated:google.protobuf.Mixin.root) } @@ -1174,9 +1213,9 @@ inline void Mixin::set_allocated_root(::std::string* root) { // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto diff --git a/third_party/protobuf/src/google/protobuf/arena.cc b/third_party/protobuf/src/google/protobuf/arena.cc old mode 100755 new mode 100644 index c117c9e5..0171c561 --- a/third_party/protobuf/src/google/protobuf/arena.cc +++ b/third_party/protobuf/src/google/protobuf/arena.cc @@ -31,24 +31,26 @@ #include #include +#include #include +#include #ifdef ADDRESS_SANITIZER #include #endif // ADDRESS_SANITIZER -#include +#include -namespace google { static const size_t kMinCleanupListElements = 8; static const size_t kMaxCleanupListElements = 64; // 1kB on 64-bit. +namespace google { namespace protobuf { namespace internal { -std::atomic ArenaImpl::lifecycle_id_generator_; +std::atomic ArenaImpl::lifecycle_id_generator_; #if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL) ArenaImpl::ThreadCache& ArenaImpl::thread_cache() { static internal::ThreadLocalStorage* thread_cache_ = @@ -57,7 +59,7 @@ ArenaImpl::ThreadCache& ArenaImpl::thread_cache() { } #elif defined(PROTOBUF_USE_DLLS) ArenaImpl::ThreadCache& ArenaImpl::thread_cache() { - static GOOGLE_THREAD_LOCAL ThreadCache thread_cache_ = { -1, NULL }; + static GOOGLE_THREAD_LOCAL ThreadCache thread_cache_ = {-1, NULL}; return thread_cache_; } #else @@ -125,7 +127,7 @@ ArenaImpl::Block* ArenaImpl::NewBlock(Block* last_block, size_t min_bytes) { ArenaImpl::Block::Block(size_t size, Block* next) : next_(next), pos_(kBlockHeaderSize), size_(size) {} -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +PROTOBUF_NOINLINE void ArenaImpl::SerialArena::AddCleanupFallback(void* elem, void (*cleanup)(void*)) { size_t size = cleanup_ ? cleanup_->size * 2 : kMinCleanupListElements; @@ -142,10 +144,10 @@ void ArenaImpl::SerialArena::AddCleanupFallback(void* elem, AddCleanup(elem, cleanup); } -GOOGLE_PROTOBUF_ATTRIBUTE_FUNC_ALIGN(32) +PROTOBUF_FUNC_ALIGN(32) void* ArenaImpl::AllocateAligned(size_t n) { SerialArena* arena; - if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) { + if (PROTOBUF_PREDICT_TRUE(GetSerialArenaFast(&arena))) { return arena->AllocateAligned(n); } else { return AllocateAlignedFallback(n); @@ -155,7 +157,7 @@ void* ArenaImpl::AllocateAligned(size_t n) { void* ArenaImpl::AllocateAlignedAndAddCleanup(size_t n, void (*cleanup)(void*)) { SerialArena* arena; - if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) { + if (PROTOBUF_PREDICT_TRUE(GetSerialArenaFast(&arena))) { return arena->AllocateAlignedAndAddCleanup(n, cleanup); } else { return AllocateAlignedAndAddCleanupFallback(n, cleanup); @@ -164,36 +166,36 @@ void* ArenaImpl::AllocateAlignedAndAddCleanup(size_t n, void ArenaImpl::AddCleanup(void* elem, void (*cleanup)(void*)) { SerialArena* arena; - if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) { + if (PROTOBUF_PREDICT_TRUE(GetSerialArenaFast(&arena))) { arena->AddCleanup(elem, cleanup); } else { return AddCleanupFallback(elem, cleanup); } } -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +PROTOBUF_NOINLINE void* ArenaImpl::AllocateAlignedFallback(size_t n) { return GetSerialArena()->AllocateAligned(n); } -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +PROTOBUF_NOINLINE void* ArenaImpl::AllocateAlignedAndAddCleanupFallback(size_t n, void (*cleanup)(void*)) { return GetSerialArena()->AllocateAlignedAndAddCleanup(n, cleanup); } -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +PROTOBUF_NOINLINE void ArenaImpl::AddCleanupFallback(void* elem, void (*cleanup)(void*)) { GetSerialArena()->AddCleanup(elem, cleanup); } -inline GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE -bool ArenaImpl::GetSerialArenaFast(ArenaImpl::SerialArena** arena) { +inline PROTOBUF_ALWAYS_INLINE bool ArenaImpl::GetSerialArenaFast( + ArenaImpl::SerialArena** arena) { // If this thread already owns a block in this arena then try to use that. // This fast path optimizes the case where multiple threads allocate from the // same arena. ThreadCache* tc = &thread_cache(); - if (GOOGLE_PREDICT_TRUE(tc->last_lifecycle_id_seen == lifecycle_id_)) { + if (PROTOBUF_PREDICT_TRUE(tc->last_lifecycle_id_seen == lifecycle_id_)) { *arena = tc->last_serial_arena; return true; } @@ -201,7 +203,7 @@ bool ArenaImpl::GetSerialArenaFast(ArenaImpl::SerialArena** arena) { // Check whether we own the last accessed SerialArena on this arena. This // fast path optimizes the case where a single thread uses multiple arenas. SerialArena* serial = hint_.load(std::memory_order_acquire); - if (GOOGLE_PREDICT_TRUE(serial != NULL && serial->owner() == tc)) { + if (PROTOBUF_PREDICT_TRUE(serial != NULL && serial->owner() == tc)) { *arena = serial; return true; } @@ -211,14 +213,14 @@ bool ArenaImpl::GetSerialArenaFast(ArenaImpl::SerialArena** arena) { ArenaImpl::SerialArena* ArenaImpl::GetSerialArena() { SerialArena* arena; - if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) { + if (PROTOBUF_PREDICT_TRUE(GetSerialArenaFast(&arena))) { return arena; } else { return GetSerialArenaFallback(&thread_cache()); } } -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +PROTOBUF_NOINLINE void* ArenaImpl::SerialArena::AllocateAlignedFallback(size_t n) { // Sync back to current's pos. head_->set_pos(head_->size() - (limit_ - ptr_)); @@ -241,7 +243,7 @@ uint64 ArenaImpl::SpaceAllocated() const { uint64 ArenaImpl::SpaceUsed() const { SerialArena* serial = threads_.load(std::memory_order_acquire); uint64 space_used = 0; - for ( ; serial; serial = serial->next()) { + for (; serial; serial = serial->next()) { space_used += serial->SpaceUsed(); } return space_used; @@ -285,7 +287,7 @@ uint64 ArenaImpl::SerialArena::Free(ArenaImpl::SerialArena* serial, // We have to be careful in this function, since we will be freeing the Block // that contains this SerialArena. Be careful about accessing |serial|. - for (Block* b = serial->head_; b; ) { + for (Block* b = serial->head_; b;) { // This is inside the block we are freeing, so we need to read it now. Block* next_block = b->next(); space_allocated += (b->size()); @@ -311,7 +313,7 @@ void ArenaImpl::CleanupList() { // properly synchronize Reset() or the destructor will throw a TSAN warning. SerialArena* serial = threads_.load(std::memory_order_relaxed); - for ( ; serial; serial = serial->next()) { + for (; serial; serial = serial->next()) { serial->CleanupList(); } } @@ -323,24 +325,22 @@ void ArenaImpl::SerialArena::CleanupList() { } void ArenaImpl::SerialArena::CleanupListFallback() { - // Cleanup newest chunk: ptrs give us length. + // The first chunk might be only partially full, so calculate its size + // from cleanup_ptr_. Subsequent chunks are always full, so use list->size. size_t n = cleanup_ptr_ - &cleanup_->nodes[0]; - CleanupNode* node = cleanup_ptr_; - for (size_t i = 0; i < n; i++) { - --node; - node->cleanup(node->elem); - } - - // Cleanup older chunks, which are known to be full. - CleanupChunk* list = cleanup_->next; - while (list) { - size_t n = list->size; - CleanupNode* node = &list->nodes[list->size]; - for (size_t i = 0; i < n; i++) { - --node; - node->cleanup(node->elem); + CleanupChunk* list = cleanup_; + while (true) { + CleanupNode* node = &list->nodes[0]; + // Cleanup newest elements first (allocated last). + for (size_t i = n; i > 0; i--) { + node[i - 1].cleanup(node[i - 1].elem); } list = list->next; + if (list == nullptr) { + break; + } + // All but the first chunk are always full. + n = list->size; } } @@ -362,11 +362,11 @@ ArenaImpl::SerialArena* ArenaImpl::SerialArena::New(Block* b, void* owner, return serial; } -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +PROTOBUF_NOINLINE ArenaImpl::SerialArena* ArenaImpl::GetSerialArenaFallback(void* me) { // Look for this SerialArena in our linked list. SerialArena* serial = threads_.load(std::memory_order_acquire); - for ( ; serial; serial = serial->next()) { + for (; serial; serial = serial->next()) { if (serial->owner() == me) { break; } diff --git a/third_party/protobuf/src/google/protobuf/arena.h b/third_party/protobuf/src/google/protobuf/arena.h index 9928c8e6..52f3fb95 100644 --- a/third_party/protobuf/src/google/protobuf/arena.h +++ b/third_party/protobuf/src/google/protobuf/arena.h @@ -34,6 +34,8 @@ #define GOOGLE_PROTOBUF_ARENA_H__ #include +#include +#include #ifdef max #undef max // Visual Studio defines this macro #endif @@ -49,38 +51,41 @@ using type_info = ::type_info; #endif #include -#include +#include #include +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + namespace google { namespace protobuf { struct ArenaOptions; // defined below } // namespace protobuf +} // namespace google -namespace quality_webanswers { - -void TempPrivateWorkAround(::google::protobuf::ArenaOptions* arena_options); - -} // namespace quality_webanswers +namespace google { namespace protobuf { -class Arena; // defined below -class Message; // defined in message.h +class Arena; // defined below +class Message; // defined in message.h class MessageLite; namespace arena_metrics { -void EnableArenaMetrics(::google::protobuf::ArenaOptions* options); +void EnableArenaMetrics(ArenaOptions* options); } // namespace arena_metrics namespace internal { -struct ArenaStringPtr; // defined in arenastring.h -class LazyField; // defined in lazy_field.h +struct ArenaStringPtr; // defined in arenastring.h +class LazyField; // defined in lazy_field.h template class GenericTypeHandler; // defined in repeated_field.h @@ -153,13 +158,14 @@ struct ArenaOptions { private: // Hooks for adding external functionality such as user-specific metrics // collection, specific debugging abilities, etc. - // Init hook may return a pointer to a cookie to be stored in the arena. - // reset and destruction hooks will then be called with the same cookie - // pointer. This allows us to save an external object per arena instance and - // use it on the other hooks (Note: It is just as legal for init to return - // NULL and not use the cookie feature). - // on_arena_reset and on_arena_destruction also receive the space used in - // the arena just before the reset. + // Init hook (if set) will always be called at Arena init time. Init hook may + // return a pointer to a cookie to be stored in the arena. Reset and + // destruction hooks will then be called with the same cookie pointer. This + // allows us to save an external object per arena instance and use it on the + // other hooks (Note: If init hook returns NULL, the other hooks will NOT be + // called on this arena instance). + // on_arena_reset and on_arena_destruction also receive the space used in the + // arena just before the reset. void* (*on_arena_init)(Arena* arena); void (*on_arena_reset)(Arena* arena, void* cookie, uint64 space_used); void (*on_arena_destruction)(Arena* arena, void* cookie, uint64 space_used); @@ -177,15 +183,14 @@ struct ArenaOptions { static const size_t kDefaultStartBlockSize = 256; static const size_t kDefaultMaxBlockSize = 8192; - friend void ::google::protobuf::arena_metrics::EnableArenaMetrics(ArenaOptions*); - friend void quality_webanswers::TempPrivateWorkAround(ArenaOptions*); + friend void arena_metrics::EnableArenaMetrics(ArenaOptions*); friend class Arena; friend class ArenaOptionsTestFriend; }; // Support for non-RTTI environments. (The metrics hooks API uses type // information.) -#ifndef GOOGLE_PROTOBUF_NO_RTTI +#if PROTOBUF_RTTI #define RTTI_TYPE_ID(type) (&typeid(type)) #else #define RTTI_TYPE_ID(type) (NULL) @@ -216,7 +221,7 @@ struct ArenaOptions { // // - The type T must have (at least) two constructors: a constructor with no // arguments, called when a T is allocated on the heap; and a constructor with -// a google::protobuf::Arena* argument, called when a T is allocated on an arena. If the +// a Arena* argument, called when a T is allocated on an arena. If the // second constructor is called with a NULL arena pointer, it must be // equivalent to invoking the first (no-argument) constructor. // @@ -237,11 +242,10 @@ struct ArenaOptions { // arg1, arg2). // // This protocol is implemented by all arena-enabled proto2 message classes as -// well as RepeatedPtrField. -// -// Do NOT subclass Arena. This class will be marked as final when C++11 is -// enabled. -class LIBPROTOBUF_EXPORT Arena { +// well as protobuf container types like RepeatedPtrField and Map. The protocol +// is internal to protobuf and is not guaranteed to be stable. Non-proto types +// should not rely on this protocol. +class PROTOBUF_EXPORT Arena final { public: // Arena constructor taking custom options. See ArenaOptions below for // descriptions of the options available. @@ -291,8 +295,7 @@ class LIBPROTOBUF_EXPORT Arena { // This function also accepts any type T that satisfies the arena message // allocation protocol, documented above. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessage( - Arena* arena, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* CreateMessage(Arena* arena, Args&&... args) { static_assert( InternalHelper::is_arena_constructable::value, "CreateMessage can only construct types that are ArenaConstructable"); @@ -318,8 +321,7 @@ class LIBPROTOBUF_EXPORT Arena { // if the object were allocated on the heap (except that the underlying memory // is obtained from the arena). template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* Create(Arena* arena, - Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* Create(Arena* arena, Args&&... args) { return CreateNoMessage(arena, is_arena_constructable(), std::forward(args)...); } @@ -331,8 +333,8 @@ class LIBPROTOBUF_EXPORT Arena { // (when compiled as C++11) that T is trivially default-constructible and // trivially destructible. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateArray( - Arena* arena, size_t num_elements) { + PROTOBUF_ALWAYS_INLINE static T* CreateArray(Arena* arena, + size_t num_elements) { static_assert(std::is_pod::value, "CreateArray requires a trivially constructible type"); static_assert(std::is_trivially_destructible::value, @@ -359,7 +361,7 @@ class LIBPROTOBUF_EXPORT Arena { // // Combines SpaceAllocated and SpaceUsed. Returns a pair of // . - PROTOBUF_RUNTIME_DEPRECATED("Please use SpaceAllocated() and SpaceUsed()") + PROTOBUF_DEPRECATED_MSG("Please use SpaceAllocated() and SpaceUsed()") std::pair SpaceAllocatedAndUsed() const { return std::make_pair(SpaceAllocated(), SpaceUsed()); } @@ -369,7 +371,7 @@ class LIBPROTOBUF_EXPORT Arena { // Any objects allocated on this arena are unusable after this call. It also // returns the total space used by the arena which is the sums of the sizes // of the allocated blocks. This method is not thread-safe. - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE uint64 Reset() { + PROTOBUF_NOINLINE uint64 Reset() { // Call the reset hook if (on_arena_reset_ != NULL) { on_arena_reset_(this, hooks_cookie_, impl_.SpaceAllocated()); @@ -380,7 +382,7 @@ class LIBPROTOBUF_EXPORT Arena { // Adds |object| to a list of heap-allocated objects to be freed with |delete| // when the arena is destroyed or reset. template - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void Own(T* object) { + PROTOBUF_NOINLINE void Own(T* object) { OwnInternal(object, std::is_convertible()); } @@ -390,7 +392,7 @@ class LIBPROTOBUF_EXPORT Arena { // normally only used for objects that are placement-newed into // arena-allocated memory. template - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void OwnDestructor(T* object) { + PROTOBUF_NOINLINE void OwnDestructor(T* object) { if (object != NULL) { impl_.AddCleanup(object, &internal::arena_destruct_object); } @@ -400,19 +402,18 @@ class LIBPROTOBUF_EXPORT Arena { // will be manually called when the arena is destroyed or reset. This differs // from OwnDestructor() in that any member function may be specified, not only // the class destructor. - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void OwnCustomDestructor( - void* object, void (*destruct)(void*)) { + PROTOBUF_NOINLINE void OwnCustomDestructor(void* object, + void (*destruct)(void*)) { impl_.AddCleanup(object, destruct); } // Retrieves the arena associated with |value| if |value| is an arena-capable - // message, or NULL otherwise. This differs from value->GetArena() in that the - // latter is a virtual call, while this method is a templated call that - // resolves at compile-time. + // message, or NULL otherwise. If possible, the call resolves at compile time. + // Note that we can often devirtualize calls to `value->GetArena()` so usually + // calling this method is unnecessary. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArena( - const T* value) { - return GetArenaInternal(value, is_arena_constructable()); + PROTOBUF_ALWAYS_INLINE static Arena* GetArena(const T* value) { + return GetArenaInternal(value); } template @@ -439,6 +440,19 @@ class LIBPROTOBUF_EXPORT Arena { sizeof(char)> is_arena_constructable; + template () + .GetArena())>::value, + int>::type = 0> + static char HasGetArena(decltype(&U::GetArena)); + template + static double HasGetArena(...); + + typedef std::integral_constant(nullptr)) == + sizeof(char)> + has_get_arena; + template static T* Construct(void* ptr, Args&&... args) { return new (ptr) T(std::forward(args)...); @@ -468,9 +482,12 @@ class LIBPROTOBUF_EXPORT Arena { }; private: + template + struct has_get_arena : InternalHelper::has_get_arena {}; + template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessageInternal( - Arena* arena, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* CreateMessageInternal(Arena* arena, + Args&&... args) { static_assert( InternalHelper::is_arena_constructable::value, "CreateMessage can only construct types that are ArenaConstructable"); @@ -485,8 +502,7 @@ class LIBPROTOBUF_EXPORT Arena { // slightly different. When the arena pointer is nullptr, it calls T() // instead of T(nullptr). template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessageInternal( - Arena* arena) { + PROTOBUF_ALWAYS_INLINE static T* CreateMessageInternal(Arena* arena) { static_assert( InternalHelper::is_arena_constructable::value, "CreateMessage can only construct types that are ArenaConstructable"); @@ -498,8 +514,8 @@ class LIBPROTOBUF_EXPORT Arena { } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateInternal( - Arena* arena, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* CreateInternal(Arena* arena, + Args&&... args) { if (arena == NULL) { return new T(std::forward(args)...); } else { @@ -511,7 +527,7 @@ class LIBPROTOBUF_EXPORT Arena { void CallDestructorHooks(); void OnArenaAllocation(const std::type_info* allocated_type, size_t n) const; inline void AllocHook(const std::type_info* allocated_type, size_t n) const { - if (GOOGLE_PREDICT_FALSE(hooks_cookie_ != NULL)) { + if (PROTOBUF_PREDICT_FALSE(hooks_cookie_ != NULL)) { OnArenaAllocation(allocated_type, n); } } @@ -520,8 +536,7 @@ class LIBPROTOBUF_EXPORT Arena { // allocated type info when the hooks are in place in ArenaOptions and // the cookie is not null. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void* AllocateInternal( - bool skip_explicit_ownership) { + PROTOBUF_ALWAYS_INLINE void* AllocateInternal(bool skip_explicit_ownership) { const size_t n = internal::AlignUpTo8(sizeof(T)); AllocHook(RTTI_TYPE_ID(T), n); // Monitor allocation if needed. @@ -539,27 +554,29 @@ class LIBPROTOBUF_EXPORT Arena { // user code. These are used only internally from LazyField and Repeated // fields, since they are designed to work in all mode combinations. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Msg* DoCreateMaybeMessage( - Arena* arena, std::true_type, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static Msg* DoCreateMaybeMessage(Arena* arena, + std::true_type, + Args&&... args) { return CreateMessageInternal(arena, std::forward(args)...); } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* DoCreateMaybeMessage( - Arena* arena, std::false_type, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* DoCreateMaybeMessage(Arena* arena, + std::false_type, + Args&&... args) { return CreateInternal(arena, std::forward(args)...); } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMaybeMessage( - Arena* arena, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* CreateMaybeMessage(Arena* arena, + Args&&... args) { return DoCreateMaybeMessage(arena, is_arena_constructable(), std::forward(args)...); } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateNoMessage( - Arena* arena, std::true_type, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* CreateNoMessage(Arena* arena, std::true_type, + Args&&... args) { // User is constructing with Create() despite the fact that T supports arena // construction. In this case we have to delegate to CreateInternal(), and // we can't use any CreateMaybeMessage() specialization that may be defined. @@ -567,8 +584,9 @@ class LIBPROTOBUF_EXPORT Arena { } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateNoMessage( - Arena* arena, std::false_type, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* CreateNoMessage(Arena* arena, + std::false_type, + Args&&... args) { // User is constructing with Create() and the type does not support arena // construction. In this case we can delegate to CreateMaybeMessage() and // use any specialization that may be available for that. @@ -578,8 +596,7 @@ class LIBPROTOBUF_EXPORT Arena { // Just allocate the required size for the given type assuming the // type has a trivial constructor. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateInternalRawArray( - size_t num_elements) { + PROTOBUF_ALWAYS_INLINE T* CreateInternalRawArray(size_t num_elements) { GOOGLE_CHECK_LE(num_elements, std::numeric_limits::max() / sizeof(T)) << "Requested size is too large to fit into size_t."; const size_t n = internal::AlignUpTo8(sizeof(T) * num_elements); @@ -589,21 +606,21 @@ class LIBPROTOBUF_EXPORT Arena { } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreate( - bool skip_explicit_ownership, Args&&... args) { + PROTOBUF_ALWAYS_INLINE T* DoCreate(bool skip_explicit_ownership, + Args&&... args) { return new (AllocateInternal(skip_explicit_ownership)) T(std::forward(args)...); } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreateMessage(Args&&... args) { + PROTOBUF_ALWAYS_INLINE T* DoCreateMessage(Args&&... args) { return InternalHelper::Construct( AllocateInternal(InternalHelper::is_destructor_skippable::value), this, std::forward(args)...); } // CreateInArenaStorage is used to implement map field. Without it, - // google::protobuf::Map need to call generated message's protected arena constructor, - // which needs to declare google::protobuf::Map as friend of generated message. + // Map need to call generated message's protected arena constructor, + // which needs to declare Map as friend of generated message. template static void CreateInArenaStorage(T* ptr, Arena* arena) { CreateInArenaStorageInternal(ptr, arena, @@ -635,19 +652,17 @@ class LIBPROTOBUF_EXPORT Arena { // These implement Own(), which registers an object for deletion (destructor // call and operator delete()). The second parameter has type 'true_type' if T - // is a subtype of ::google::protobuf::Message and 'false_type' otherwise. Collapsing + // is a subtype of Message and 'false_type' otherwise. Collapsing // all template instantiations to one for generic Message reduces code size, // using the virtual destructor instead. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object, - std::true_type) { + PROTOBUF_ALWAYS_INLINE void OwnInternal(T* object, std::true_type) { if (object != NULL) { impl_.AddCleanup(object, &internal::arena_delete_object); } } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object, - std::false_type) { + PROTOBUF_ALWAYS_INLINE void OwnInternal(T* object, std::false_type) { if (object != NULL) { impl_.AddCleanup(object, &internal::arena_delete_object); } @@ -656,16 +671,24 @@ class LIBPROTOBUF_EXPORT Arena { // Implementation for GetArena(). Only message objects with // InternalArenaConstructable_ tags can be associated with an arena, and such // objects must implement a GetArenaNoVirtual() method. - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArenaInternal( - const T* value, std::true_type) { + template ::value, int>::type = 0> + PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) { return InternalHelper::GetArena(value); } - - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArenaInternal( - const T* /* value */, std::false_type) { - return NULL; + template ::value && + has_get_arena::value, + int>::type = 0> + PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) { + return value->GetArena(); + } + template ::value && + !has_get_arena::value, + int>::type = 0> + PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) { + return nullptr; } // For friends of arena. @@ -698,6 +721,8 @@ class LIBPROTOBUF_EXPORT Arena { #undef RTTI_TYPE_ID } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_ARENA_H__ diff --git a/third_party/protobuf/src/google/protobuf/arena_impl.h b/third_party/protobuf/src/google/protobuf/arena_impl.h index f648f166..0beec171 100644 --- a/third_party/protobuf/src/google/protobuf/arena_impl.h +++ b/third_party/protobuf/src/google/protobuf/arena_impl.h @@ -39,29 +39,31 @@ #include #include -#include - #ifdef ADDRESS_SANITIZER #include #endif // ADDRESS_SANITIZER -namespace google { +#include + +namespace google { namespace protobuf { namespace internal { inline size_t AlignUpTo8(size_t n) { // Align n to next multiple of 8 (from Hacker's Delight, Chapter 3.) - return (n + 7) & -8; + return (n + 7) & static_cast(-8); } +using LifecycleId = int64_t; + // This class provides the core Arena memory allocation library. Different // implementations only need to implement the public interface below. // Arena is not a template type as that would only be useful if all protos // in turn would be templates, which will/cannot happen. However separating // the memory allocation part from the cruft of the API users expect we can // use #ifdef the select the best implementation based on hardware / OS. -class LIBPROTOBUF_EXPORT ArenaImpl { +class PROTOBUF_EXPORT ArenaImpl { public: struct Options { size_t start_block_size; @@ -73,12 +75,12 @@ class LIBPROTOBUF_EXPORT ArenaImpl { template explicit Options(const O& options) - : start_block_size(options.start_block_size), - max_block_size(options.max_block_size), - initial_block(options.initial_block), - initial_block_size(options.initial_block_size), - block_alloc(options.block_alloc), - block_dealloc(options.block_dealloc) {} + : start_block_size(options.start_block_size), + max_block_size(options.max_block_size), + initial_block(options.initial_block), + initial_block_size(options.initial_block_size), + block_alloc(options.block_alloc), + block_dealloc(options.block_dealloc) {} }; template @@ -137,7 +139,7 @@ class LIBPROTOBUF_EXPORT ArenaImpl { class Block; // A thread-unsafe Arena that can only be used within its owning thread. - class LIBPROTOBUF_EXPORT SerialArena { + class PROTOBUF_EXPORT SerialArena { public: // The allocate/free methods here are a little strange, since SerialArena is // allocated inside a Block which it also manages. This is to avoid doing @@ -157,7 +159,7 @@ class LIBPROTOBUF_EXPORT ArenaImpl { void* AllocateAligned(size_t n) { GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned. GOOGLE_DCHECK_GE(limit_, ptr_); - if (GOOGLE_PREDICT_FALSE(static_cast(limit_ - ptr_) < n)) { + if (PROTOBUF_PREDICT_FALSE(static_cast(limit_ - ptr_) < n)) { return AllocateAlignedFallback(n); } void* ret = ptr_; @@ -169,7 +171,7 @@ class LIBPROTOBUF_EXPORT ArenaImpl { } void AddCleanup(void* elem, void (*cleanup)(void*)) { - if (GOOGLE_PREDICT_FALSE(cleanup_ptr_ == cleanup_limit_)) { + if (PROTOBUF_PREDICT_FALSE(cleanup_ptr_ == cleanup_limit_)) { AddCleanupFallback(elem, cleanup); return; } @@ -193,11 +195,11 @@ class LIBPROTOBUF_EXPORT ArenaImpl { void AddCleanupFallback(void* elem, void (*cleanup)(void*)); void CleanupListFallback(); - ArenaImpl* arena_; // Containing arena. - void* owner_; // &ThreadCache of this thread; - Block* head_; // Head of linked list of blocks. - CleanupChunk* cleanup_; // Head of cleanup list. - SerialArena* next_; // Next SerialArena in this linked list. + ArenaImpl* arena_; // Containing arena. + void* owner_; // &ThreadCache of this thread; + Block* head_; // Head of linked list of blocks. + CleanupChunk* cleanup_; // Head of cleanup list. + SerialArena* next_; // Next SerialArena in this linked list. // Next pointer to allocate from. Always 8-byte aligned. Points inside // head_ (and head_->pos will always be non-canonical). We keep these @@ -212,7 +214,7 @@ class LIBPROTOBUF_EXPORT ArenaImpl { // Blocks are variable length malloc-ed objects. The following structure // describes the common header for all blocks. - class LIBPROTOBUF_EXPORT Block { + class PROTOBUF_EXPORT Block { public: Block(size_t size, Block* next); @@ -227,7 +229,7 @@ class LIBPROTOBUF_EXPORT ArenaImpl { void set_pos(size_t pos) { pos_ = pos; } private: - Block* next_; // Next block for this thread. + Block* next_; // Next block for this thread. size_t pos_; size_t size_; // data follows @@ -243,10 +245,10 @@ class LIBPROTOBUF_EXPORT ArenaImpl { // The ThreadCache is considered valid as long as this matches the // lifecycle_id of the arena being used. - int64 last_lifecycle_id_seen; + LifecycleId last_lifecycle_id_seen; SerialArena* last_serial_arena; }; - static std::atomic lifecycle_id_generator_; + static std::atomic lifecycle_id_generator_; #if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL) // Android ndk does not support GOOGLE_THREAD_LOCAL keyword so we use a custom thread // local storage class we implemented. @@ -279,21 +281,20 @@ class LIBPROTOBUF_EXPORT ArenaImpl { hint_.store(serial, std::memory_order_release); } - std::atomic threads_; // Pointer to a linked list of SerialArena. std::atomic hint_; // Fast thread-local block access std::atomic space_allocated_; // Total size of all allocated blocks. - Block *initial_block_; // If non-NULL, points to the block that came from - // user data. + Block* initial_block_; // If non-NULL, points to the block that came from + // user data. Block* NewBlock(Block* last_block, size_t min_bytes); SerialArena* GetSerialArena(); bool GetSerialArenaFast(SerialArena** arena); SerialArena* GetSerialArenaFallback(void* me); - int64 lifecycle_id_; // Unique for each arena. Changes on Reset(). + LifecycleId lifecycle_id_; // Unique for each arena. Changes on Reset(). Options options_; @@ -306,8 +307,10 @@ class LIBPROTOBUF_EXPORT ArenaImpl { public: // kBlockHeaderSize is sizeof(Block), aligned up to the nearest multiple of 8 // to protect the invariant that pos is always at a multiple of 8. - static const size_t kBlockHeaderSize = (sizeof(Block) + 7) & -8; - static const size_t kSerialArenaSize = (sizeof(SerialArena) + 7) & -8; + static const size_t kBlockHeaderSize = + (sizeof(Block) + 7) & static_cast(-8); + static const size_t kSerialArenaSize = + (sizeof(SerialArena) + 7) & static_cast(-8); static_assert(kBlockHeaderSize % 8 == 0, "kBlockHeaderSize must be a multiple of 8."); static_assert(kSerialArenaSize % 8 == 0, @@ -316,6 +319,8 @@ class LIBPROTOBUF_EXPORT ArenaImpl { } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_ARENA_IMPL_H__ diff --git a/third_party/protobuf/src/google/protobuf/arena_test_util.cc b/third_party/protobuf/src/google/protobuf/arena_test_util.cc index df9c5bd6..da32960c 100644 --- a/third_party/protobuf/src/google/protobuf/arena_test_util.cc +++ b/third_party/protobuf/src/google/protobuf/arena_test_util.cc @@ -28,9 +28,9 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#include #include #include -#include #define EXPECT_EQ GOOGLE_CHECK_EQ diff --git a/third_party/protobuf/src/google/protobuf/arena_test_util.h b/third_party/protobuf/src/google/protobuf/arena_test_util.h index df56ece8..84df3498 100644 --- a/third_party/protobuf/src/google/protobuf/arena_test_util.h +++ b/third_party/protobuf/src/google/protobuf/arena_test_util.h @@ -33,6 +33,8 @@ #include #include +#include +#include #include namespace google { @@ -41,16 +43,23 @@ namespace protobuf { template void TestParseCorruptedString(const T& message) { int success_count = 0; - string s = message.SerializeAsString(); + std::string s; + { + // Map order is not deterministic. To make the test deterministic we want + // to serialize the proto deterministically. + io::StringOutputStream output(&s); + io::CodedOutputStream out(&output); + out.SetSerializationDeterministic(true); + message.SerializePartialToCodedStream(&out); + } const int kMaxIters = 900; const int stride = s.size() <= kMaxIters ? 1 : s.size() / kMaxIters; const int start = stride == 1 || use_arena ? 0 : (stride + 1) / 2; for (int i = start; i < s.size(); i += stride) { for (int c = 1 + (i % 17); c < 256; c += 2 * c + (i & 3)) { s[i] ^= c; - google::protobuf::Arena arena; - T* message = - google::protobuf::Arena::CreateMessage(use_arena ? &arena : nullptr); + Arena arena; + T* message = Arena::CreateMessage(use_arena ? &arena : nullptr); if (message->ParseFromString(s)) { ++success_count; } @@ -69,10 +78,9 @@ namespace internal { class NoHeapChecker { public: - NoHeapChecker() { - capture_alloc.Hook(); - } + NoHeapChecker() { capture_alloc.Hook(); } ~NoHeapChecker(); + private: class NewDeleteCapture { public: @@ -86,6 +94,6 @@ class NoHeapChecker { } // namespace internal } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_ARENA_TEST_UTIL_H__ diff --git a/third_party/protobuf/src/google/protobuf/arena_unittest.cc b/third_party/protobuf/src/google/protobuf/arena_unittest.cc index eaaffce2..7e5b1156 100644 --- a/third_party/protobuf/src/google/protobuf/arena_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/arena_unittest.cc @@ -52,29 +52,27 @@ #include #include #include -#include #include +#include #include +#include +using proto2_arena_unittest::ArenaMessage; +using protobuf_unittest::TestAllExtensions; +using protobuf_unittest::TestAllTypes; +using protobuf_unittest::TestEmptyMessage; +using protobuf_unittest::TestOneof2; +using protobuf_unittest_no_arena::TestNoArenaMessage; + namespace google { -using proto2_arena_unittest::ArenaMessage; -using protobuf_unittest::TestAllTypes; -using protobuf_unittest::TestAllExtensions; -using protobuf_unittest::TestOneof2; -using protobuf_unittest::TestEmptyMessage; - namespace protobuf { class Notifier { public: Notifier() : count_(0) {} - void Notify() { - count_++; - } - int GetCount() { - return count_; - } + void Notify() { count_++; } + int GetCount() { return count_; } private: int count_; @@ -83,14 +81,13 @@ class Notifier { class SimpleDataType { public: SimpleDataType() : notifier_(NULL) {} - void SetNotifier(Notifier* notifier) { - notifier_ = notifier; - } + void SetNotifier(Notifier* notifier) { notifier_ = notifier; } virtual ~SimpleDataType() { if (notifier_ != NULL) { notifier_->Notify(); } }; + private: Notifier* notifier_; }; @@ -111,14 +108,14 @@ class PleaseDontCopyMe { // A class that takes four different types as constructor arguments. class MustBeConstructedWithOneThroughFour { public: - MustBeConstructedWithOneThroughFour( - int one, const char* two, const string& three, - const PleaseDontCopyMe* four) + MustBeConstructedWithOneThroughFour(int one, const char* two, + const std::string& three, + const PleaseDontCopyMe* four) : one_(one), two_(two), three_(three), four_(four) {} int one_; const char* const two_; - string three_; + std::string three_; const PleaseDontCopyMe* four_; private: @@ -128,21 +125,29 @@ class MustBeConstructedWithOneThroughFour { // A class that takes eight different types as constructor arguments. class MustBeConstructedWithOneThroughEight { public: - MustBeConstructedWithOneThroughEight( - int one, const char* two, const string& three, - const PleaseDontCopyMe* four, int five, const char* six, - const string& seven, const string& eight) - : one_(one), two_(two), three_(three), four_(four), five_(five), - six_(six), seven_(seven), eight_(eight) {} + MustBeConstructedWithOneThroughEight(int one, const char* two, + const std::string& three, + const PleaseDontCopyMe* four, int five, + const char* six, + const std::string& seven, + const std::string& eight) + : one_(one), + two_(two), + three_(three), + four_(four), + five_(five), + six_(six), + seven_(seven), + eight_(eight) {} int one_; const char* const two_; - string three_; + std::string three_; const PleaseDontCopyMe* four_; int five_; const char* const six_; - string seven_; - string eight_; + std::string seven_; + std::string eight_; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MustBeConstructedWithOneThroughEight); @@ -151,16 +156,14 @@ class MustBeConstructedWithOneThroughEight { TEST(ArenaTest, ArenaConstructable) { EXPECT_TRUE(Arena::is_arena_constructable::type::value); EXPECT_TRUE(Arena::is_arena_constructable::type::value); - EXPECT_FALSE(Arena::is_arena_constructable< - protobuf_unittest_no_arena::TestNoArenaMessage>::type::value); + EXPECT_FALSE(Arena::is_arena_constructable::type::value); EXPECT_FALSE(Arena::is_arena_constructable::type::value); } TEST(ArenaTest, DestructorSkippable) { EXPECT_TRUE(Arena::is_destructor_skippable::type::value); EXPECT_TRUE(Arena::is_destructor_skippable::type::value); - EXPECT_FALSE(Arena::is_destructor_skippable< - protobuf_unittest_no_arena::TestNoArenaMessage>::type::value); + EXPECT_FALSE(Arena::is_destructor_skippable::type::value); EXPECT_FALSE(Arena::is_destructor_skippable::type::value); } @@ -170,12 +173,12 @@ TEST(ArenaTest, BasicCreate) { EXPECT_TRUE(Arena::Create(&arena) != NULL); EXPECT_TRUE(Arena::Create(&arena) != NULL); EXPECT_TRUE(Arena::Create(&arena) != NULL); - EXPECT_TRUE(Arena::Create(&arena) != NULL); + EXPECT_TRUE(Arena::Create(&arena) != NULL); arena.Own(new int32); arena.Own(new int64); arena.Own(new float); arena.Own(new double); - arena.Own(new string); + arena.Own(new std::string); arena.Own(NULL); Notifier notifier; SimpleDataType* data = Arena::Create(&arena); @@ -189,8 +192,8 @@ TEST(ArenaTest, BasicCreate) { TEST(ArenaTest, CreateAndConstCopy) { Arena arena; - const string s("foo"); - const string* s_copy = Arena::Create(&arena, s); + const std::string s("foo"); + const std::string* s_copy = Arena::Create(&arena, s); EXPECT_TRUE(s_copy != NULL); EXPECT_EQ("foo", s); EXPECT_EQ("foo", *s_copy); @@ -198,8 +201,8 @@ TEST(ArenaTest, CreateAndConstCopy) { TEST(ArenaTest, CreateAndNonConstCopy) { Arena arena; - string s("foo"); - const string* s_copy = Arena::Create(&arena, s); + std::string s("foo"); + const std::string* s_copy = Arena::Create(&arena, s); EXPECT_TRUE(s_copy != NULL); EXPECT_EQ("foo", s); EXPECT_EQ("foo", *s_copy); @@ -207,8 +210,8 @@ TEST(ArenaTest, CreateAndNonConstCopy) { TEST(ArenaTest, CreateAndMove) { Arena arena; - string s("foo"); - const string* s_move = Arena::Create(&arena, std::move(s)); + std::string s("foo"); + const std::string* s_move = Arena::Create(&arena, std::move(s)); EXPECT_TRUE(s_move != NULL); EXPECT_TRUE(s.empty()); // NOLINT EXPECT_EQ("foo", *s_move); @@ -216,11 +219,11 @@ TEST(ArenaTest, CreateAndMove) { TEST(ArenaTest, CreateWithFourConstructorArguments) { Arena arena; - const string three("3"); + const std::string three("3"); const PleaseDontCopyMe four(4); const MustBeConstructedWithOneThroughFour* new_object = - Arena::Create( - &arena, 1, "2", three, &four); + Arena::Create(&arena, 1, "2", three, + &four); EXPECT_TRUE(new_object != NULL); ASSERT_EQ(1, new_object->one_); ASSERT_STREQ("2", new_object->two_); @@ -230,10 +233,10 @@ TEST(ArenaTest, CreateWithFourConstructorArguments) { TEST(ArenaTest, CreateWithEightConstructorArguments) { Arena arena; - const string three("3"); + const std::string three("3"); const PleaseDontCopyMe four(4); - const string seven("7"); - const string eight("8"); + const std::string seven("7"); + const std::string eight("8"); const MustBeConstructedWithOneThroughEight* new_object = Arena::Create( &arena, 1, "2", three, &four, 5, "6", seven, eight); @@ -250,14 +253,14 @@ TEST(ArenaTest, CreateWithEightConstructorArguments) { class PleaseMoveMe { public: - explicit PleaseMoveMe(const string& value) : value_(value) {} + explicit PleaseMoveMe(const std::string& value) : value_(value) {} PleaseMoveMe(PleaseMoveMe&&) = default; PleaseMoveMe(const PleaseMoveMe&) = delete; - const string& value() const { return value_; } + const std::string& value() const { return value_; } private: - string value_; + std::string value_; }; TEST(ArenaTest, CreateWithMoveArguments) { @@ -279,7 +282,7 @@ TEST(ArenaTest, InitialBlockTooSmall) { options.initial_block_size = arena_block.size(); Arena arena(options); - char* p = ::google::protobuf::Arena::CreateArray(&arena, 96); + char* p = Arena::CreateArray(&arena, 96); uintptr_t allocation = reinterpret_cast(p); // Ensure that the arena allocator did not return memory pointing into the @@ -410,7 +413,7 @@ TEST(ArenaTest, ReflectionSwapFields) { reflection->SwapFields(arena1_message, arena2_message, fields); EXPECT_EQ(&arena1, arena1_message->GetArena()); EXPECT_EQ(&arena2, arena2_message->GetArena()); - string output; + std::string output; arena1_message->SerializeToString(&output); EXPECT_EQ(0, output.size()); TestUtil::ExpectAllFieldsSet(*arena2_message); @@ -454,13 +457,13 @@ TEST(ArenaTest, ReflectionSwapFields) { TEST(ArenaTest, SetAllocatedMessage) { Arena arena; - TestAllTypes *arena_message = Arena::CreateMessage(&arena); + TestAllTypes* arena_message = Arena::CreateMessage(&arena); TestAllTypes::NestedMessage* nested = new TestAllTypes::NestedMessage; nested->set_bb(118); arena_message->set_allocated_optional_nested_message(nested); EXPECT_EQ(118, arena_message->optional_nested_message().bb()); - protobuf_unittest_no_arena::TestNoArenaMessage no_arena_message; + TestNoArenaMessage no_arena_message; EXPECT_FALSE(no_arena_message.has_arena_message()); no_arena_message.set_allocated_arena_message(NULL); EXPECT_FALSE(no_arena_message.has_arena_message()); @@ -484,7 +487,7 @@ TEST(ArenaTest, ReleaseMessage) { TEST(ArenaTest, SetAllocatedString) { Arena arena; TestAllTypes* arena_message = Arena::CreateMessage(&arena); - string* allocated_str = new string("hello"); + std::string* allocated_str = new std::string("hello"); arena_message->set_allocated_optional_string(allocated_str); EXPECT_EQ("hello", arena_message->optional_string()); } @@ -493,7 +496,7 @@ TEST(ArenaTest, ReleaseString) { Arena arena; TestAllTypes* arena_message = Arena::CreateMessage(&arena); arena_message->set_optional_string("hello"); - std::unique_ptr released_str( + std::unique_ptr released_str( arena_message->release_optional_string()); EXPECT_EQ("hello", *released_str); @@ -509,7 +512,7 @@ TEST(ArenaTest, SwapBetweenArenasWithAllFieldsSet) { TestAllTypes* arena2_message = Arena::CreateMessage(&arena2); TestUtil::SetAllFields(arena2_message); arena2_message->Swap(arena1_message); - string output; + std::string output; arena2_message->SerializeToString(&output); EXPECT_EQ(0, output.size()); } @@ -547,7 +550,7 @@ TEST(ArenaTest, SwapBetweenArenasUsingReflection) { TestUtil::SetAllFields(arena2_message); const Reflection* r = arena2_message->GetReflection(); r->Swap(arena1_message, arena2_message); - string output; + std::string output; arena2_message->SerializeToString(&output); EXPECT_EQ(0, output.size()); } @@ -570,7 +573,7 @@ TEST(ArenaTest, SwapBetweenArenaAndNonArenaUsingReflection) { TEST(ArenaTest, ReleaseFromArenaMessageMakesCopy) { TestAllTypes::NestedMessage* nested_msg = NULL; - string* nested_string = NULL; + std::string* nested_string = NULL; { Arena arena; TestAllTypes* arena_message = Arena::CreateMessage(&arena); @@ -585,7 +588,7 @@ TEST(ArenaTest, ReleaseFromArenaMessageMakesCopy) { delete nested_string; } -#ifndef GOOGLE_PROTOBUF_NO_RTTI +#if PROTOBUF_RTTI TEST(ArenaTest, ReleaseFromArenaMessageUsingReflectionMakesCopy) { TestAllTypes::NestedMessage* nested_msg = NULL; // Note: no string: reflection API only supports releasing submessages. @@ -602,7 +605,7 @@ TEST(ArenaTest, ReleaseFromArenaMessageUsingReflectionMakesCopy) { EXPECT_EQ(42, nested_msg->bb()); delete nested_msg; } -#endif // !GOOGLE_PROTOBUF_NO_RTTI +#endif // PROTOBUF_RTTI TEST(ArenaTest, SetAllocatedAcrossArenas) { Arena arena1; @@ -612,8 +615,7 @@ TEST(ArenaTest, SetAllocatedAcrossArenas) { heap_submessage->set_bb(42); arena1_message->set_allocated_optional_nested_message(heap_submessage); // Should keep same object and add to arena's Own()-list. - EXPECT_EQ(heap_submessage, - arena1_message->mutable_optional_nested_message()); + EXPECT_EQ(heap_submessage, arena1_message->mutable_optional_nested_message()); { Arena arena2; TestAllTypes::NestedMessage* arena2_submessage = @@ -629,8 +631,7 @@ TEST(ArenaTest, SetAllocatedAcrossArenas) { arena1_submessage->set_bb(42); TestAllTypes* heap_message = new TestAllTypes; heap_message->set_allocated_optional_nested_message(arena1_submessage); - EXPECT_NE(arena1_submessage, - heap_message->mutable_optional_nested_message()); + EXPECT_NE(arena1_submessage, heap_message->mutable_optional_nested_message()); delete heap_message; } @@ -640,15 +641,14 @@ TEST(ArenaTest, SetAllocatedAcrossArenasWithReflection) { TestAllTypes* arena1_message = Arena::CreateMessage(&arena1); const Reflection* r = arena1_message->GetReflection(); const Descriptor* d = arena1_message->GetDescriptor(); - const FieldDescriptor* msg_field = d->FindFieldByName( - "optional_nested_message"); + const FieldDescriptor* msg_field = + d->FindFieldByName("optional_nested_message"); TestAllTypes::NestedMessage* heap_submessage = new TestAllTypes::NestedMessage(); heap_submessage->set_bb(42); r->SetAllocatedMessage(arena1_message, heap_submessage, msg_field); // Should keep same object and add to arena's Own()-list. - EXPECT_EQ(heap_submessage, - arena1_message->mutable_optional_nested_message()); + EXPECT_EQ(heap_submessage, arena1_message->mutable_optional_nested_message()); { Arena arena2; TestAllTypes::NestedMessage* arena2_submessage = @@ -664,8 +664,7 @@ TEST(ArenaTest, SetAllocatedAcrossArenasWithReflection) { arena1_submessage->set_bb(42); TestAllTypes* heap_message = new TestAllTypes; r->SetAllocatedMessage(heap_message, arena1_submessage, msg_field); - EXPECT_NE(arena1_submessage, - heap_message->mutable_optional_nested_message()); + EXPECT_NE(arena1_submessage, heap_message->mutable_optional_nested_message()); delete heap_message; } @@ -720,11 +719,10 @@ TEST(ArenaTest, AddAllocatedToRepeatedField) { TestAllTypes::NestedMessage* heap_submessage = new TestAllTypes::NestedMessage(); heap_submessage->set_bb(42); - arena1_message->mutable_repeated_nested_message()-> - AddAllocated(heap_submessage); + arena1_message->mutable_repeated_nested_message()->AddAllocated( + heap_submessage); // Should not copy object -- will use arena_->Own(). - EXPECT_EQ(heap_submessage, - &arena1_message->repeated_nested_message(i)); + EXPECT_EQ(heap_submessage, &arena1_message->repeated_nested_message(i)); EXPECT_EQ(42, arena1_message->repeated_nested_message(i).bb()); } @@ -735,11 +733,10 @@ TEST(ArenaTest, AddAllocatedToRepeatedField) { TestAllTypes::NestedMessage* arena2_submessage = Arena::CreateMessage(&arena2); arena2_submessage->set_bb(42); - arena1_message->mutable_repeated_nested_message()-> - AddAllocated(arena2_submessage); + arena1_message->mutable_repeated_nested_message()->AddAllocated( + arena2_submessage); // Should copy object. - EXPECT_NE(arena2_submessage, - &arena1_message->repeated_nested_message(i)); + EXPECT_NE(arena2_submessage, &arena1_message->repeated_nested_message(i)); EXPECT_EQ(42, arena1_message->repeated_nested_message(i).bb()); } @@ -750,11 +747,10 @@ TEST(ArenaTest, AddAllocatedToRepeatedField) { TestAllTypes::NestedMessage* arena2_submessage = Arena::CreateMessage(&arena2); arena2_submessage->set_bb(42); - heap_message->mutable_repeated_nested_message()-> - AddAllocated(arena2_submessage); + heap_message->mutable_repeated_nested_message()->AddAllocated( + arena2_submessage); // Should copy object. - EXPECT_NE(arena2_submessage, - &heap_message->repeated_nested_message(i)); + EXPECT_NE(arena2_submessage, &heap_message->repeated_nested_message(i)); EXPECT_EQ(42, heap_message->repeated_nested_message(i).bb()); } delete heap_message; @@ -762,9 +758,8 @@ TEST(ArenaTest, AddAllocatedToRepeatedField) { // Heap-arena case for strings (which are not arena-allocated). arena1_message->Clear(); for (int i = 0; i < 10; i++) { - string* s = new string("Test"); - arena1_message->mutable_repeated_string()-> - AddAllocated(s); + std::string* s = new std::string("Test"); + arena1_message->mutable_repeated_string()->AddAllocated(s); // Should not copy. EXPECT_EQ(s, &arena1_message->repeated_string(i)); EXPECT_EQ("Test", arena1_message->repeated_string(i)); @@ -777,16 +772,14 @@ TEST(ArenaTest, AddAllocatedToRepeatedFieldViaReflection) { TestAllTypes* arena1_message = Arena::CreateMessage(&arena1); const Reflection* r = arena1_message->GetReflection(); const Descriptor* d = arena1_message->GetDescriptor(); - const FieldDescriptor* fd = - d->FindFieldByName("repeated_nested_message"); + const FieldDescriptor* fd = d->FindFieldByName("repeated_nested_message"); for (int i = 0; i < 10; i++) { TestAllTypes::NestedMessage* heap_submessage = new TestAllTypes::NestedMessage; heap_submessage->set_bb(42); r->AddAllocatedMessage(arena1_message, fd, heap_submessage); // Should not copy object -- will use arena_->Own(). - EXPECT_EQ(heap_submessage, - &arena1_message->repeated_nested_message(i)); + EXPECT_EQ(heap_submessage, &arena1_message->repeated_nested_message(i)); EXPECT_EQ(42, arena1_message->repeated_nested_message(i).bb()); } @@ -799,8 +792,7 @@ TEST(ArenaTest, AddAllocatedToRepeatedFieldViaReflection) { arena2_submessage->set_bb(42); r->AddAllocatedMessage(arena1_message, fd, arena2_submessage); // Should copy object. - EXPECT_NE(arena2_submessage, - &arena1_message->repeated_nested_message(i)); + EXPECT_NE(arena2_submessage, &arena1_message->repeated_nested_message(i)); EXPECT_EQ(42, arena1_message->repeated_nested_message(i).bb()); } @@ -813,8 +805,7 @@ TEST(ArenaTest, AddAllocatedToRepeatedFieldViaReflection) { arena2_submessage->set_bb(42); r->AddAllocatedMessage(heap_message, fd, arena2_submessage); // Should copy object. - EXPECT_NE(arena2_submessage, - &heap_message->repeated_nested_message(i)); + EXPECT_NE(arena2_submessage, &heap_message->repeated_nested_message(i)); EXPECT_EQ(42, heap_message->repeated_nested_message(i).bb()); } delete heap_message; @@ -833,9 +824,9 @@ TEST(ArenaTest, ReleaseLastRepeatedField) { } for (int i = 0; i < 10; i++) { - const TestAllTypes::NestedMessage *orig_submessage = + const TestAllTypes::NestedMessage* orig_submessage = &arena_message->repeated_nested_message(10 - 1 - i); // last element - TestAllTypes::NestedMessage *released = + TestAllTypes::NestedMessage* released = arena_message->mutable_repeated_nested_message()->ReleaseLast(); EXPECT_NE(released, orig_submessage); EXPECT_EQ(42, released->bb()); @@ -851,29 +842,31 @@ TEST(ArenaTest, ReleaseLastRepeatedField) { } for (int i = 0; i < 10; i++) { - const TestAllTypes::NestedMessage *orig_submessage = + const TestAllTypes::NestedMessage* orig_submessage = &arena_message->repeated_nested_message(10 - 1 - i); // last element - TestAllTypes::NestedMessage *released = - arena_message->mutable_repeated_nested_message()-> - UnsafeArenaReleaseLast(); + TestAllTypes::NestedMessage* released = + arena_message->mutable_repeated_nested_message() + ->UnsafeArenaReleaseLast(); EXPECT_EQ(released, orig_submessage); EXPECT_EQ(42, released->bb()); // no delete -- |released| is on the arena. } - // Test string case as well. ReleaseLast() in this case must copy the string, - // even though it was originally heap-allocated and its pointer was simply - // appended to the repeated field's internal vector, because the string was - // placed on the arena's destructor list and cannot be removed from that list - // (so the arena permanently owns the original instance). + // Test string case as well. ReleaseLast() in this case must copy the + // string, even though it was originally heap-allocated and its pointer + // was simply appended to the repeated field's internal vector, because the + // string was placed on the arena's destructor list and cannot be removed + // from that list (so the arena permanently owns the original instance). arena_message->Clear(); for (int i = 0; i < 10; i++) { - string* s = new string("Test"); + std::string* s = new std::string("Test"); arena_message->mutable_repeated_string()->AddAllocated(s); } for (int i = 0; i < 10; i++) { - const string* orig_element = &arena_message->repeated_string(10 - 1 - i); - string* released = arena_message->mutable_repeated_string()->ReleaseLast(); + const std::string* orig_element = + &arena_message->repeated_string(10 - 1 - i); + std::string* released = + arena_message->mutable_repeated_string()->ReleaseLast(); EXPECT_NE(released, orig_element); EXPECT_EQ("Test", *released); delete released; @@ -888,7 +881,7 @@ TEST(ArenaTest, UnsafeArenaReleaseAdd) { Arena arena; TestAllTypes* message1 = Arena::CreateMessage(&arena); TestAllTypes* message2 = Arena::CreateMessage(&arena); - string* arena_string = Arena::Create(&arena); + std::string* arena_string = Arena::Create(&arena); *arena_string = kContent; message1->unsafe_arena_set_allocated_optional_string(arena_string); @@ -901,7 +894,7 @@ TEST(ArenaTest, UnsafeArenaAddAllocated) { Arena arena; TestAllTypes* message = Arena::CreateMessage(&arena); for (int i = 0; i < 10; i++) { - string* arena_string = Arena::Create(&arena); + std::string* arena_string = Arena::Create(&arena); message->mutable_repeated_string()->UnsafeArenaAddAllocated(arena_string); EXPECT_EQ(arena_string, message->mutable_repeated_string(i)); } @@ -911,7 +904,7 @@ TEST(ArenaTest, UnsafeArenaRelease) { Arena arena; TestAllTypes* message = Arena::CreateMessage(&arena); - string* s = new string("test string"); + std::string* s = new std::string("test string"); message->unsafe_arena_set_allocated_optional_string(s); EXPECT_TRUE(message->has_optional_string()); EXPECT_EQ("test string", message->optional_string()); @@ -919,7 +912,7 @@ TEST(ArenaTest, UnsafeArenaRelease) { EXPECT_FALSE(message->has_optional_string()); delete s; - s = new string("test string"); + s = new std::string("test string"); message->unsafe_arena_set_allocated_oneof_string(s); EXPECT_TRUE(message->has_oneof_string()); EXPECT_EQ("test string", message->oneof_string()); @@ -933,9 +926,9 @@ TEST(ArenaTest, OneofMerge) { TestAllTypes* message0 = Arena::CreateMessage(&arena); TestAllTypes* message1 = Arena::CreateMessage(&arena); - message0->unsafe_arena_set_allocated_oneof_string(new string("x")); + message0->unsafe_arena_set_allocated_oneof_string(new std::string("x")); ASSERT_TRUE(message0->has_oneof_string()); - message1->unsafe_arena_set_allocated_oneof_string(new string("y")); + message1->unsafe_arena_set_allocated_oneof_string(new std::string("y")); ASSERT_TRUE(message1->has_oneof_string()); EXPECT_EQ("x", message0->oneof_string()); EXPECT_EQ("y", message1->oneof_string()); @@ -952,12 +945,10 @@ TEST(ArenaTest, ArenaOneofReflection) { const Descriptor* desc = message->GetDescriptor(); const Reflection* refl = message->GetReflection(); - const FieldDescriptor* string_field = desc->FindFieldByName( - "oneof_string"); - const FieldDescriptor* msg_field = desc->FindFieldByName( - "oneof_nested_message"); - const OneofDescriptor* oneof = desc->FindOneofByName( - "oneof_field"); + const FieldDescriptor* string_field = desc->FindFieldByName("oneof_string"); + const FieldDescriptor* msg_field = + desc->FindFieldByName("oneof_nested_message"); + const OneofDescriptor* oneof = desc->FindOneofByName("oneof_field"); refl->SetString(message, string_field, "Test value"); EXPECT_TRUE(refl->HasOneof(*message, oneof)); @@ -1004,8 +995,8 @@ void TestSwapRepeatedField(Arena* arena1, Arena* arena2) { field1.Swap(&field2); EXPECT_EQ(5, field1.size()); EXPECT_EQ(10, field2.size()); - EXPECT_TRUE(string("field1") == field2.Get(0).optional_string()); - EXPECT_TRUE(string("field2") == field1.Get(0).optional_string()); + EXPECT_TRUE(std::string("field1") == field2.Get(0).optional_string()); + EXPECT_TRUE(std::string("field2") == field1.Get(0).optional_string()); // Ensure that fields retained their original order: for (int i = 0; i < field1.size(); i++) { EXPECT_EQ(i, field1.Get(i).optional_int32()); @@ -1041,12 +1032,12 @@ TEST(ArenaTest, ExtensionsOnArena) { // Ensure no leaks. TestAllExtensions* message_ext = Arena::CreateMessage(&arena); - message_ext->SetExtension( - protobuf_unittest::optional_int32_extension, 42); - message_ext->SetExtension( - protobuf_unittest::optional_string_extension, string("test")); - message_ext->MutableExtension( - protobuf_unittest::optional_nested_message_extension)->set_bb(42); + message_ext->SetExtension(protobuf_unittest::optional_int32_extension, 42); + message_ext->SetExtension(protobuf_unittest::optional_string_extension, + std::string("test")); + message_ext + ->MutableExtension(protobuf_unittest::optional_nested_message_extension) + ->set_bb(42); } TEST(ArenaTest, RepeatedFieldOnArena) { @@ -1109,7 +1100,7 @@ TEST(ArenaTest, RepeatedFieldOnArena) { // code that may allocate messages or repeated fields of messages on an arena. { RepeatedPtrField* repeated_ptr_on_arena = - Arena::CreateMessage< RepeatedPtrField >(&arena); + Arena::CreateMessage >(&arena); for (int i = 0; i < 10; i++) { // Add some elements and let the leak-checker ensure that everything is // freed. @@ -1117,7 +1108,7 @@ TEST(ArenaTest, RepeatedFieldOnArena) { } RepeatedField* repeated_int_on_arena = - Arena::CreateMessage< RepeatedField >(&arena); + Arena::CreateMessage >(&arena); for (int i = 0; i < 100; i++) { repeated_int_on_arena->Add(i); } @@ -1128,7 +1119,7 @@ TEST(ArenaTest, RepeatedFieldOnArena) { } -#ifndef GOOGLE_PROTOBUF_NO_RTTI +#if PROTOBUF_RTTI TEST(ArenaTest, MutableMessageReflection) { Arena arena; TestAllTypes* message = Arena::CreateMessage(&arena); @@ -1144,7 +1135,8 @@ TEST(ArenaTest, MutableMessageReflection) { EXPECT_EQ(submessage_expected, submessage); EXPECT_EQ(&arena, submessage->GetArena()); - const FieldDescriptor* oneof_field = d->FindFieldByName("oneof_nested_message"); + const FieldDescriptor* oneof_field = + d->FindFieldByName("oneof_nested_message"); submessage = static_cast( r->MutableMessage(message, oneof_field)); submessage_expected = message->mutable_oneof_nested_message(); @@ -1152,11 +1144,11 @@ TEST(ArenaTest, MutableMessageReflection) { EXPECT_EQ(submessage_expected, submessage); EXPECT_EQ(&arena, submessage->GetArena()); } -#endif // !GOOGLE_PROTOBUF_NO_RTTI +#endif // PROTOBUF_RTTI void FillArenaAwareFields(TestAllTypes* message) { - string test_string = "hello world"; + std::string test_string = "hello world"; message->set_optional_int32(42); message->set_optional_string(test_string); message->set_optional_bytes(test_string); @@ -1198,7 +1190,7 @@ TEST(ArenaTest, ParseCorruptedString) { TestParseCorruptedString(message); } -#ifndef GOOGLE_PROTOBUF_NO_RTTI +#if PROTOBUF_RTTI // Test construction on an arena via generic MessageLite interface. We should be // able to successfully deserialize on the arena without incurring heap // allocations, i.e., everything should still be arena-allocation-aware. @@ -1208,16 +1200,16 @@ TEST(ArenaTest, MessageLiteOnArena) { options.initial_block = &arena_block[0]; options.initial_block_size = arena_block.size(); Arena arena(options); - const google::protobuf::MessageLite* prototype = &TestAllTypes::default_instance(); + const MessageLite* prototype = &TestAllTypes::default_instance(); TestAllTypes initial_message; FillArenaAwareFields(&initial_message); - string serialized; + std::string serialized; initial_message.SerializeToString(&serialized); { - google::protobuf::MessageLite* generic_message = prototype->New(&arena); + MessageLite* generic_message = prototype->New(&arena); EXPECT_TRUE(generic_message != NULL); EXPECT_EQ(&arena, generic_message->GetArena()); EXPECT_TRUE(generic_message->ParseFromString(serialized)); @@ -1227,7 +1219,7 @@ TEST(ArenaTest, MessageLiteOnArena) { arena.Reset(); } -#endif // !GOOGLE_PROTOBUF_NO_RTTI +#endif // PROTOBUF_RTTI // RepeatedField should support non-POD types, and invoke constructors and @@ -1235,14 +1227,14 @@ TEST(ArenaTest, MessageLiteOnArena) { // (even if this was not its original intent). TEST(ArenaTest, RepeatedFieldWithNonPODType) { { - RepeatedField field_on_heap; + RepeatedField field_on_heap; for (int i = 0; i < 100; i++) { *field_on_heap.Add() = "test string long enough to exceed inline buffer"; } } { Arena arena; - RepeatedField field_on_arena(&arena); + RepeatedField field_on_arena(&arena); for (int i = 0; i < 100; i++) { *field_on_arena.Add() = "test string long enough to exceed inline buffer"; } @@ -1260,7 +1252,7 @@ TEST(ArenaTest, SpaceAllocated_and_Used) { EXPECT_EQ(0, arena_1.SpaceAllocated()); EXPECT_EQ(0, arena_1.SpaceUsed()); EXPECT_EQ(0, arena_1.Reset()); - ::google::protobuf::Arena::CreateArray(&arena_1, 320); + Arena::CreateArray(&arena_1, 320); // Arena will allocate slightly more than 320 for the block headers. EXPECT_LE(320, arena_1.SpaceAllocated()); EXPECT_EQ(Align8(320), arena_1.SpaceUsed()); @@ -1274,7 +1266,7 @@ TEST(ArenaTest, SpaceAllocated_and_Used) { EXPECT_EQ(1024, arena_2.SpaceAllocated()); EXPECT_EQ(0, arena_2.SpaceUsed()); EXPECT_EQ(1024, arena_2.Reset()); - ::google::protobuf::Arena::CreateArray(&arena_2, 55); + Arena::CreateArray(&arena_2, 55); EXPECT_EQ(1024, arena_2.SpaceAllocated()); EXPECT_EQ(Align8(55), arena_2.SpaceUsed()); EXPECT_EQ(1024, arena_2.Reset()); @@ -1284,45 +1276,51 @@ TEST(ArenaTest, SpaceAllocated_and_Used) { options.initial_block_size = 0; Arena arena_3(options); EXPECT_EQ(0, arena_3.SpaceUsed()); - ::google::protobuf::Arena::CreateArray(&arena_3, 160); + Arena::CreateArray(&arena_3, 160); EXPECT_EQ(256, arena_3.SpaceAllocated()); EXPECT_EQ(Align8(160), arena_3.SpaceUsed()); - ::google::protobuf::Arena::CreateArray(&arena_3, 70); + Arena::CreateArray(&arena_3, 70); EXPECT_EQ(256 + 512, arena_3.SpaceAllocated()); EXPECT_EQ(Align8(160) + Align8(70), arena_3.SpaceUsed()); EXPECT_EQ(256 + 512, arena_3.Reset()); } TEST(ArenaTest, Alignment) { - ::google::protobuf::Arena arena; + Arena arena; for (int i = 0; i < 200; i++) { - void* p = ::google::protobuf::Arena::CreateArray(&arena, i); + void* p = Arena::CreateArray(&arena, i); GOOGLE_CHECK_EQ(reinterpret_cast(p) % 8, 0) << i << ": " << p; } } TEST(ArenaTest, BlockSizeSmallerThanAllocation) { for (size_t i = 0; i <= 8; ++i) { - ::google::protobuf::ArenaOptions opt; + ArenaOptions opt; opt.start_block_size = opt.max_block_size = i; - ::google::protobuf::Arena arena(opt); + Arena arena(opt); - *::google::protobuf::Arena::Create(&arena) = 42; + *Arena::Create(&arena) = 42; EXPECT_GE(arena.SpaceAllocated(), 8); EXPECT_EQ(8, arena.SpaceUsed()); - *::google::protobuf::Arena::Create(&arena) = 42; + *Arena::Create(&arena) = 42; EXPECT_GE(arena.SpaceAllocated(), 16); EXPECT_EQ(16, arena.SpaceUsed()); } } TEST(ArenaTest, GetArenaShouldReturnTheArenaForArenaAllocatedMessages) { - ::google::protobuf::Arena arena; + Arena arena; ArenaMessage* message = Arena::CreateMessage(&arena); const ArenaMessage* const_pointer_to_message = message; EXPECT_EQ(&arena, Arena::GetArena(message)); EXPECT_EQ(&arena, Arena::GetArena(const_pointer_to_message)); + + // Test that the Message* / MessageLite* specialization SFINAE works. + const Message* const_pointer_to_message_type = message; + EXPECT_EQ(&arena, Arena::GetArena(const_pointer_to_message_type)); + const MessageLite* const_pointer_to_message_lite_type = message; + EXPECT_EQ(&arena, Arena::GetArena(const_pointer_to_message_lite_type)); } TEST(ArenaTest, GetArenaShouldReturnNullForNonArenaAllocatedMessages) { @@ -1332,19 +1330,47 @@ TEST(ArenaTest, GetArenaShouldReturnNullForNonArenaAllocatedMessages) { EXPECT_EQ(NULL, Arena::GetArena(const_pointer_to_message)); } +TEST(ArenaTest, GetArenaShouldReturnNullForNonArenaCompatibleTypes) { + TestNoArenaMessage message; + const TestNoArenaMessage* const_pointer_to_message = &message; + EXPECT_EQ(nullptr, Arena::GetArena(&message)); + EXPECT_EQ(nullptr, Arena::GetArena(const_pointer_to_message)); + + // Test that GetArena returns nullptr for types that have a GetArena method + // that doesn't return Arena*. + struct { + int GetArena() const { return 0; } + } has_get_arena_method_wrong_return_type; + EXPECT_EQ(nullptr, Arena::GetArena(&has_get_arena_method_wrong_return_type)); + + // Test that GetArena returns nullptr for types that have a GetArena alias. + struct { + using GetArena = Arena*; + GetArena unused; + } has_get_arena_alias; + EXPECT_EQ(nullptr, Arena::GetArena(&has_get_arena_alias)); + + // Test that GetArena returns nullptr for types that have a GetArena data + // member. + struct { + Arena GetArena; + } has_get_arena_data_member; + EXPECT_EQ(nullptr, Arena::GetArena(&has_get_arena_data_member)); +} + TEST(ArenaTest, AddCleanup) { - ::google::protobuf::Arena arena; + Arena arena; for (int i = 0; i < 100; i++) { arena.Own(new int); } } TEST(ArenaTest, UnsafeSetAllocatedOnArena) { - ::google::protobuf::Arena arena; + Arena arena; TestAllTypes* message = Arena::CreateMessage(&arena); EXPECT_FALSE(message->has_optional_string()); - string owned_string = "test with long enough content to heap-allocate"; + std::string owned_string = "test with long enough content to heap-allocate"; message->unsafe_arena_set_allocated_optional_string(&owned_string); EXPECT_TRUE(message->has_optional_string()); @@ -1357,7 +1383,7 @@ TEST(ArenaTest, UnsafeSetAllocatedOnArena) { // value to be verified. class ArenaHooksTestUtil { public: - static void* on_init(::google::protobuf::Arena* arena) { + static void* on_init(Arena* arena) { ++num_init; int* cookie = new int(kCookieValue); return static_cast(cookie); @@ -1370,15 +1396,13 @@ class ArenaHooksTestUtil { EXPECT_EQ(kCookieValue, cookie_value); } - static void on_reset(::google::protobuf::Arena* arena, void* cookie, - uint64 space_used) { + static void on_reset(Arena* arena, void* cookie, uint64 space_used) { ++num_reset; int cookie_value = *static_cast(cookie); EXPECT_EQ(kCookieValue, cookie_value); } - static void on_destruction(::google::protobuf::Arena* arena, void* cookie, - uint64 space_used) { + static void on_destruction(Arena* arena, void* cookie, uint64 space_used) { ++num_destruct; int cookie_value = *static_cast(cookie); EXPECT_EQ(kCookieValue, cookie_value); @@ -1399,7 +1423,7 @@ const int ArenaHooksTestUtil::kCookieValue; class ArenaOptionsTestFriend { public: - static void Set(::google::protobuf::ArenaOptions* options) { + static void Set(ArenaOptions* options) { options->on_arena_init = ArenaHooksTestUtil::on_init; options->on_arena_allocation = ArenaHooksTestUtil::on_allocation; options->on_arena_reset = ArenaHooksTestUtil::on_reset; @@ -1409,15 +1433,15 @@ class ArenaOptionsTestFriend { // Test the hooks are correctly called and that the cookie is passed. TEST(ArenaTest, ArenaHooksSanity) { - ::google::protobuf::ArenaOptions options; + ArenaOptions options; ArenaOptionsTestFriend::Set(&options); // Scope for defining the arena { - ::google::protobuf::Arena arena(options); + Arena arena(options); EXPECT_EQ(1, ArenaHooksTestUtil::num_init); EXPECT_EQ(0, ArenaHooksTestUtil::num_allocations); - ::google::protobuf::Arena::Create(&arena); + Arena::Create(&arena); if (std::is_trivially_destructible::value) { EXPECT_EQ(1, ArenaHooksTestUtil::num_allocations); } else { diff --git a/third_party/protobuf/src/google/protobuf/arenastring.h b/third_party/protobuf/src/google/protobuf/arenastring.h old mode 100755 new mode 100644 index 168fc972..f4ff07dc --- a/third_party/protobuf/src/google/protobuf/arenastring.h +++ b/third_party/protobuf/src/google/protobuf/arenastring.h @@ -39,6 +39,8 @@ #include #include +#include + // This is the implementation of arena string fields written for the open-source // release. The ArenaStringPtr struct below is an internal implementation class // and *should not be used* by user code. It is used to collect string @@ -63,9 +65,9 @@ class TaggedPtr { uintptr_t ptr_; }; -struct LIBPROTOBUF_EXPORT ArenaStringPtr { +struct PROTOBUF_EXPORT ArenaStringPtr { inline void Set(const ::std::string* default_value, - const ::std::string& value, ::google::protobuf::Arena* arena) { + const ::std::string& value, Arena* arena) { if (ptr_ == default_value) { CreateInstance(arena, &value); } else { @@ -74,8 +76,7 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { } inline void SetLite(const ::std::string* default_value, - const ::std::string& value, - ::google::protobuf::Arena* arena) { + const ::std::string& value, Arena* arena) { Set(default_value, value, arena); } @@ -83,7 +84,7 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { inline const ::std::string& Get() const { return *ptr_; } inline ::std::string* Mutable(const ::std::string* default_value, - ::google::protobuf::Arena* arena) { + Arena* arena) { if (ptr_ == default_value) { CreateInstance(arena, default_value); } @@ -95,7 +96,7 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { // retains ownership. Clears this field back to NULL state. Used to implement // release_() methods on generated classes. inline ::std::string* Release(const ::std::string* default_value, - ::google::protobuf::Arena* arena) { + Arena* arena) { if (ptr_ == default_value) { return NULL; } @@ -103,8 +104,8 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { } // Similar to Release, but ptr_ cannot be the default_value. - inline ::std::string* ReleaseNonDefault( - const ::std::string* default_value, ::google::protobuf::Arena* arena) { + inline ::std::string* ReleaseNonDefault(const ::std::string* default_value, + Arena* arena) { GOOGLE_DCHECK(!IsDefault(default_value)); ::std::string* released = NULL; if (arena != NULL) { @@ -124,7 +125,7 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { // state. Used to implement unsafe_arena_release_() methods on // generated classes. inline ::std::string* UnsafeArenaRelease(const ::std::string* default_value, - ::google::protobuf::Arena* /* arena */) { + Arena* /* arena */) { if (ptr_ == default_value) { return NULL; } @@ -137,7 +138,7 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { // destructor is registered with the arena. Used to implement // set_allocated_ in generated classes. inline void SetAllocated(const ::std::string* default_value, - ::std::string* value, ::google::protobuf::Arena* arena) { + ::std::string* value, Arena* arena) { if (arena == NULL && ptr_ != default_value) { Destroy(default_value, arena); } @@ -157,7 +158,7 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { // to implement unsafe_arena_set_allocated_ in generated classes. inline void UnsafeArenaSetAllocated(const ::std::string* default_value, ::std::string* value, - ::google::protobuf::Arena* /* arena */) { + Arena* /* arena */) { if (value != NULL) { ptr_ = value; } else { @@ -168,11 +169,12 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { // Swaps internal pointers. Arena-safety semantics: this is guarded by the // logic in Swap()/UnsafeArenaSwap() at the message level, so this method is // 'unsafe' if called directly. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Swap(ArenaStringPtr* other) { + PROTOBUF_ALWAYS_INLINE void Swap(ArenaStringPtr* other) { std::swap(ptr_, other->ptr_); } - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Swap( - ArenaStringPtr* other, const ::std::string* default_value, Arena* arena) { + PROTOBUF_ALWAYS_INLINE void Swap(ArenaStringPtr* other, + const ::std::string* default_value, + Arena* arena) { #ifndef NDEBUG // For debug builds, we swap the contents of the string, rather than the // string instances themselves. This invalidates previously taken const @@ -192,12 +194,13 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { this_ptr->swap(*other_ptr); #else std::swap(ptr_, other->ptr_); + (void)default_value; + (void)arena; #endif } // Frees storage (if not on an arena). - inline void Destroy(const ::std::string* default_value, - ::google::protobuf::Arena* arena) { + inline void Destroy(const ::std::string* default_value, Arena* arena) { if (arena == NULL && ptr_ != default_value) { delete ptr_; } @@ -208,7 +211,7 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { // the user) will always be the empty string. Assumes that |default_value| // is an empty string. inline void ClearToEmpty(const ::std::string* default_value, - ::google::protobuf::Arena* /* arena */) { + Arena* /* arena */) { if (ptr_ == default_value) { // Already set to default (which is empty) -- do nothing. } else { @@ -229,7 +232,7 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { // overhead of heap operations. After this returns, the content (as seen by // the user) will always be equal to |default_value|. inline void ClearToDefault(const ::std::string* default_value, - ::google::protobuf::Arena* /* arena */) { + Arena* /* arena */) { if (ptr_ == default_value) { // Already set to default -- do nothing. } else { @@ -364,14 +367,13 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { private: ::std::string* ptr_; - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE - void CreateInstance(::google::protobuf::Arena* arena, - const ::std::string* initial_value) { + PROTOBUF_NOINLINE + void CreateInstance(Arena* arena, const ::std::string* initial_value) { GOOGLE_DCHECK(initial_value != NULL); // uses "new ::std::string" when arena is nullptr ptr_ = Arena::Create< ::std::string >(arena, *initial_value); } - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE + PROTOBUF_NOINLINE void CreateInstanceNoArena(const ::std::string* initial_value) { GOOGLE_DCHECK(initial_value != NULL); ptr_ = new ::std::string(*initial_value); @@ -398,6 +400,8 @@ inline void ArenaStringPtr::AssignWithDefault(const ::std::string* default_value } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_ARENASTRING_H__ diff --git a/third_party/protobuf/src/google/protobuf/arenastring_unittest.cc b/third_party/protobuf/src/google/protobuf/arenastring_unittest.cc index adc44fe2..70a3f767 100644 --- a/third_party/protobuf/src/google/protobuf/arenastring_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/arenastring_unittest.cc @@ -40,96 +40,94 @@ #include #include -#include #include #include +#include namespace google { -using google::protobuf::internal::ArenaStringPtr; - namespace protobuf { +using internal::ArenaStringPtr; -static string WrapString(const char* value) { - return value; -} + +static std::string WrapString(const char* value) { return value; } // Test ArenaStringPtr with arena == NULL. TEST(ArenaStringPtrTest, ArenaStringPtrOnHeap) { ArenaStringPtr field; - ::std::string default_value = "default"; + std::string default_value = "default"; field.UnsafeSetDefault(&default_value); - EXPECT_EQ(string("default"), field.Get()); + EXPECT_EQ(std::string("default"), field.Get()); field.Set(&default_value, WrapString("Test short"), NULL); - EXPECT_EQ(string("Test short"), field.Get()); + EXPECT_EQ(std::string("Test short"), field.Get()); field.Set(&default_value, WrapString("Test long long long long value"), NULL); - EXPECT_EQ(string("Test long long long long value"), field.Get()); - field.Set(&default_value, string(""), NULL); + EXPECT_EQ(std::string("Test long long long long value"), field.Get()); + field.Set(&default_value, std::string(""), NULL); field.Destroy(&default_value, NULL); ArenaStringPtr field2; field2.UnsafeSetDefault(&default_value); - ::std::string* mut = field2.Mutable(&default_value, NULL); + std::string* mut = field2.Mutable(&default_value, NULL); EXPECT_EQ(mut, field2.Mutable(&default_value, NULL)); EXPECT_EQ(mut, &field2.Get()); EXPECT_NE(&default_value, mut); - EXPECT_EQ(string("default"), *mut); + EXPECT_EQ(std::string("default"), *mut); *mut = "Test long long long long value"; // ensure string allocates storage - EXPECT_EQ(string("Test long long long long value"), field2.Get()); + EXPECT_EQ(std::string("Test long long long long value"), field2.Get()); field2.Destroy(&default_value, NULL); } TEST(ArenaStringPtrTest, ArenaStringPtrOnArena) { - google::protobuf::Arena arena; + Arena arena; ArenaStringPtr field; - ::std::string default_value = "default"; + std::string default_value = "default"; field.UnsafeSetDefault(&default_value); - EXPECT_EQ(string("default"), field.Get()); + EXPECT_EQ(std::string("default"), field.Get()); field.Set(&default_value, WrapString("Test short"), &arena); - EXPECT_EQ(string("Test short"), field.Get()); + EXPECT_EQ(std::string("Test short"), field.Get()); field.Set(&default_value, WrapString("Test long long long long value"), &arena); - EXPECT_EQ(string("Test long long long long value"), field.Get()); - field.Set(&default_value, string(""), &arena); + EXPECT_EQ(std::string("Test long long long long value"), field.Get()); + field.Set(&default_value, std::string(""), &arena); field.Destroy(&default_value, &arena); ArenaStringPtr field2; field2.UnsafeSetDefault(&default_value); - ::std::string* mut = field2.Mutable(&default_value, &arena); + std::string* mut = field2.Mutable(&default_value, &arena); EXPECT_EQ(mut, field2.Mutable(&default_value, &arena)); EXPECT_EQ(mut, &field2.Get()); EXPECT_NE(&default_value, mut); - EXPECT_EQ(string("default"), *mut); + EXPECT_EQ(std::string("default"), *mut); *mut = "Test long long long long value"; // ensure string allocates storage - EXPECT_EQ(string("Test long long long long value"), field2.Get()); + EXPECT_EQ(std::string("Test long long long long value"), field2.Get()); field2.Destroy(&default_value, &arena); } TEST(ArenaStringPtrTest, ArenaStringPtrOnArenaNoSSO) { - google::protobuf::Arena arena; + Arena arena; ArenaStringPtr field; - ::std::string default_value = "default"; + std::string default_value = "default"; field.UnsafeSetDefault(&default_value); - EXPECT_EQ(string("default"), field.Get()); + EXPECT_EQ(std::string("default"), field.Get()); // Avoid triggering the SSO optimization by setting the string to something // larger than the internal buffer. field.Set(&default_value, WrapString("Test long long long long value"), &arena); - EXPECT_EQ(string("Test long long long long value"), field.Get()); - field.Set(&default_value, string(""), &arena); + EXPECT_EQ(std::string("Test long long long long value"), field.Get()); + field.Set(&default_value, std::string(""), &arena); field.Destroy(&default_value, &arena); ArenaStringPtr field2; field2.UnsafeSetDefault(&default_value); - ::std::string* mut = field2.Mutable(&default_value, &arena); + std::string* mut = field2.Mutable(&default_value, &arena); EXPECT_EQ(mut, field2.Mutable(&default_value, &arena)); EXPECT_EQ(mut, &field2.Get()); EXPECT_NE(&default_value, mut); - EXPECT_EQ(string("default"), *mut); + EXPECT_EQ(std::string("default"), *mut); *mut = "Test long long long long value"; // ensure string allocates storage - EXPECT_EQ(string("Test long long long long value"), field2.Get()); + EXPECT_EQ(std::string("Test long long long long value"), field2.Get()); field2.Destroy(&default_value, &arena); } diff --git a/third_party/protobuf/src/google/protobuf/compiler/annotation_test_util.cc b/third_party/protobuf/src/google/protobuf/compiler/annotation_test_util.cc index a0530b9a..d33f29fb 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/annotation_test_util.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/annotation_test_util.cc @@ -57,8 +57,9 @@ class DescriptorCapturingGenerator : public CodeGenerator { explicit DescriptorCapturingGenerator(FileDescriptorProto* file) : file_(file) {} - virtual bool Generate(const FileDescriptor* file, const string& parameter, - GeneratorContext* context, string* error) const { + virtual bool Generate(const FileDescriptor* file, + const std::string& parameter, GeneratorContext* context, + std::string* error) const { file->CopyTo(file_); return true; } @@ -68,21 +69,21 @@ class DescriptorCapturingGenerator : public CodeGenerator { }; } // namespace -void AddFile(const string& filename, const string& data) { +void AddFile(const std::string& filename, const std::string& data) { GOOGLE_CHECK_OK(File::SetContents(TestTempDir() + "/" + filename, data, true)); } -bool RunProtoCompiler(const string& filename, - const string& plugin_specific_args, +bool RunProtoCompiler(const std::string& filename, + const std::string& plugin_specific_args, CommandLineInterface* cli, FileDescriptorProto* file) { cli->SetInputsAreProtoPathRelative(true); DescriptorCapturingGenerator capturing_generator(file); cli->RegisterGenerator("--capture_out", &capturing_generator, ""); - string proto_path = "-I" + TestTempDir(); - string capture_out = "--capture_out=" + TestTempDir(); + std::string proto_path = "-I" + TestTempDir(); + std::string capture_out = "--capture_out=" + TestTempDir(); const char* argv[] = {"protoc", proto_path.c_str(), plugin_specific_args.c_str(), capture_out.c_str(), @@ -91,15 +92,15 @@ bool RunProtoCompiler(const string& filename, return cli->Run(5, argv) == 0; } -bool DecodeMetadata(const string& path, GeneratedCodeInfo* info) { - string data; +bool DecodeMetadata(const std::string& path, GeneratedCodeInfo* info) { + std::string data; GOOGLE_CHECK_OK(File::GetContents(path, &data, true)); io::ArrayInputStream input(data.data(), data.size()); return info->ParseFromZeroCopyStream(&input); } void FindAnnotationsOnPath( - const GeneratedCodeInfo& info, const string& source_file, + const GeneratedCodeInfo& info, const std::string& source_file, const std::vector& path, std::vector* annotations) { for (int i = 0; i < info.annotation_size(); ++i) { @@ -121,7 +122,7 @@ void FindAnnotationsOnPath( } const GeneratedCodeInfo::Annotation* FindAnnotationOnPath( - const GeneratedCodeInfo& info, const string& source_file, + const GeneratedCodeInfo& info, const std::string& source_file, const std::vector& path) { std::vector annotations; FindAnnotationsOnPath(info, source_file, path, &annotations); @@ -132,9 +133,9 @@ const GeneratedCodeInfo::Annotation* FindAnnotationOnPath( } bool AtLeastOneAnnotationMatchesSubstring( - const string& file_content, + const std::string& file_content, const std::vector& annotations, - const string& expected_text) { + const std::string& expected_text) { for (std::vector::const_iterator i = annotations.begin(), e = annotations.end(); @@ -152,9 +153,9 @@ bool AtLeastOneAnnotationMatchesSubstring( return false; } -bool AnnotationMatchesSubstring(const string& file_content, +bool AnnotationMatchesSubstring(const std::string& file_content, const GeneratedCodeInfo::Annotation* annotation, - const string& expected_text) { + const std::string& expected_text) { std::vector annotations; annotations.push_back(annotation); return AtLeastOneAnnotationMatchesSubstring(file_content, annotations, diff --git a/third_party/protobuf/src/google/protobuf/compiler/annotation_test_util.h b/third_party/protobuf/src/google/protobuf/compiler/annotation_test_util.h index 90bd88b3..7c131918 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/annotation_test_util.h +++ b/third_party/protobuf/src/google/protobuf/compiler/annotation_test_util.h @@ -49,15 +49,16 @@ namespace annotation_test_util { // file_content = content of Foo.java // file_info = parsed content of Foo.java.pb.meta struct ExpectedOutput { - string file_path; - string file_content; + std::string file_path; + std::string file_content; GeneratedCodeInfo file_info; - explicit ExpectedOutput(const string& file_path) : file_path(file_path) {} + explicit ExpectedOutput(const std::string& file_path) + : file_path(file_path) {} }; // Creates a file with name `filename` and content `data` in temp test // directory. -void AddFile(const string& filename, const string& data); +void AddFile(const std::string& filename, const std::string& data); // Runs proto compiler. Captures proto file structrue in FileDescriptorProto. // Files will be generated in TestTempDir() folder. Callers of this @@ -70,45 +71,45 @@ void AddFile(const string& filename, const string& data); // annotation_unittest.cc for an example of how to initialize it. // file: output parameter, will be set to the descriptor of the proto file // specified in filename. -bool RunProtoCompiler(const string& filename, - const string& plugin_specific_args, +bool RunProtoCompiler(const std::string& filename, + const std::string& plugin_specific_args, CommandLineInterface* cli, FileDescriptorProto* file); -bool DecodeMetadata(const string& path, GeneratedCodeInfo* info); +bool DecodeMetadata(const std::string& path, GeneratedCodeInfo* info); // Finds all of the Annotations for a given source file and path. -// See Location.path in http://google/protobuf/descriptor.proto for +// See Location.path in http://google3/net/proto2/proto/descriptor.proto for // explanation of what path vector is. void FindAnnotationsOnPath( - const GeneratedCodeInfo& info, const string& source_file, + const GeneratedCodeInfo& info, const std::string& source_file, const std::vector& path, std::vector* annotations); // Finds the Annotation for a given source file and path (or returns null if it // couldn't). If there are several annotations for given path, returns the first // one. See Location.path in -// http://google/protobuf/descriptor.proto for explanation of what path +// http://google3/net/proto2/proto/descriptor.proto for explanation of what path // vector is. const GeneratedCodeInfo::Annotation* FindAnnotationOnPath( - const GeneratedCodeInfo& info, const string& source_file, + const GeneratedCodeInfo& info, const std::string& source_file, const std::vector& path); // Returns true if at least one of the provided annotations covers a given // substring in file_content. bool AtLeastOneAnnotationMatchesSubstring( - const string& file_content, + const std::string& file_content, const std::vector& annotations, - const string& expected_text); + const std::string& expected_text); // Returns true if the provided annotation covers a given substring in // file_content. -bool AnnotationMatchesSubstring(const string& file_content, +bool AnnotationMatchesSubstring(const std::string& file_content, const GeneratedCodeInfo::Annotation* annotation, - const string& expected_text); + const std::string& expected_text); } // namespace annotation_test_util } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_ANNOTATION_TEST_UTIL_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/code_generator.cc b/third_party/protobuf/src/google/protobuf/compiler/code_generator.cc index aaabd914..428ec469 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/code_generator.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/code_generator.cc @@ -46,11 +46,10 @@ namespace compiler { CodeGenerator::~CodeGenerator() {} -bool CodeGenerator::GenerateAll( - const std::vector& files, - const string& parameter, - GeneratorContext* generator_context, - string* error) const { +bool CodeGenerator::GenerateAll(const std::vector& files, + const std::string& parameter, + GeneratorContext* generator_context, + std::string* error) const { // Default implemenation is just to call the per file method, and prefix any // error string with the file to provide context. bool succeeded = true; @@ -58,8 +57,9 @@ bool CodeGenerator::GenerateAll( const FileDescriptor* file = files[i]; succeeded = Generate(file, parameter, generator_context, error); if (!succeeded && error && error->empty()) { - *error = "Code generator returned false but provided no error " - "description."; + *error = + "Code generator returned false but provided no error " + "description."; } if (error && !error->empty()) { *error = file->name() + ": " + *error; @@ -74,13 +74,13 @@ bool CodeGenerator::GenerateAll( GeneratorContext::~GeneratorContext() {} -io::ZeroCopyOutputStream* -GeneratorContext::OpenForAppend(const string& filename) { +io::ZeroCopyOutputStream* GeneratorContext::OpenForAppend( + const std::string& filename) { return NULL; } io::ZeroCopyOutputStream* GeneratorContext::OpenForInsert( - const string& filename, const string& insertion_point) { + const std::string& filename, const std::string& insertion_point) { GOOGLE_LOG(FATAL) << "This GeneratorContext does not support insertion."; return NULL; // make compiler happy } @@ -98,14 +98,15 @@ void GeneratorContext::GetCompilerVersion(Version* version) const { } // Parses a set of comma-delimited name/value pairs. -void ParseGeneratorParameter(const string& text, - std::vector >* output) { - std::vector parts = Split(text, ",", true); +void ParseGeneratorParameter( + const std::string& text, + std::vector >* output) { + std::vector parts = Split(text, ",", true); for (int i = 0; i < parts.size(); i++) { - string::size_type equals_pos = parts[i].find_first_of('='); - std::pair value; - if (equals_pos == string::npos) { + std::string::size_type equals_pos = parts[i].find_first_of('='); + std::pair value; + if (equals_pos == std::string::npos) { value.first = parts[i]; value.second = ""; } else { diff --git a/third_party/protobuf/src/google/protobuf/compiler/code_generator.h b/third_party/protobuf/src/google/protobuf/compiler/code_generator.h index 4c2b3ee1..528dc764 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/code_generator.h +++ b/third_party/protobuf/src/google/protobuf/compiler/code_generator.h @@ -38,15 +38,19 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_CODE_GENERATOR_H__ #define GOOGLE_PROTOBUF_COMPILER_CODE_GENERATOR_H__ -#include #include -#include #include +#include +#include + +#include namespace google { namespace protobuf { -namespace io { class ZeroCopyOutputStream; } +namespace io { +class ZeroCopyOutputStream; +} class FileDescriptor; namespace compiler { @@ -61,7 +65,7 @@ class GeneratorContext; // The abstract interface to a class which generates code implementing a // particular proto file in a particular language. A number of these may // be registered with CommandLineInterface to support various languages. -class LIBPROTOC_EXPORT CodeGenerator { +class PROTOC_EXPORT CodeGenerator { public: inline CodeGenerator() {} virtual ~CodeGenerator(); @@ -78,9 +82,9 @@ class LIBPROTOC_EXPORT CodeGenerator { // Returns true if successful. Otherwise, sets *error to a description of // the problem (e.g. "invalid parameter") and returns false. virtual bool Generate(const FileDescriptor* file, - const string& parameter, + const std::string& parameter, GeneratorContext* generator_context, - string* error) const = 0; + std::string* error) const = 0; // Generates code for all given proto files. // @@ -94,9 +98,9 @@ class LIBPROTOC_EXPORT CodeGenerator { // Returns true if successful. Otherwise, sets *error to a description of // the problem (e.g. "invalid parameter") and returns false. virtual bool GenerateAll(const std::vector& files, - const string& parameter, + const std::string& parameter, GeneratorContext* generator_context, - string* error) const; + std::string* error) const; // This is no longer used, but this class is part of the opensource protobuf // library, so it has to remain to keep vtables the same for the current @@ -112,7 +116,7 @@ class LIBPROTOC_EXPORT CodeGenerator { // abstract interface represents the directory to which the CodeGenerator is // to write and other information about the context in which the Generator // runs. -class LIBPROTOC_EXPORT GeneratorContext { +class PROTOC_EXPORT GeneratorContext { public: inline GeneratorContext() { } @@ -128,10 +132,10 @@ class LIBPROTOC_EXPORT GeneratorContext { // generate the files "foo/bar.pb.h" and "foo/bar.pb.cc"; note that // "foo/" is included in these filenames. The filename is not allowed to // contain "." or ".." components. - virtual io::ZeroCopyOutputStream* Open(const string& filename) = 0; + virtual io::ZeroCopyOutputStream* Open(const std::string& filename) = 0; // Similar to Open() but the output will be appended to the file if exists - virtual io::ZeroCopyOutputStream* OpenForAppend(const string& filename); + virtual io::ZeroCopyOutputStream* OpenForAppend(const std::string& filename); // Creates a ZeroCopyOutputStream which will insert code into the given file // at the given insertion point. See plugin.proto (plugin.pb.h) for more @@ -140,7 +144,7 @@ class LIBPROTOC_EXPORT GeneratorContext { // // WARNING: This feature is currently EXPERIMENTAL and is subject to change. virtual io::ZeroCopyOutputStream* OpenForInsert( - const string& filename, const string& insertion_point); + const std::string& filename, const std::string& insertion_point); // Returns a vector of FileDescriptors for all the files being compiled // in this run. Useful for languages, such as Go, that treat files @@ -166,11 +170,13 @@ typedef GeneratorContext OutputDirectory; // "foo=bar,baz,qux=corge" // parses to the pairs: // ("foo", "bar"), ("baz", ""), ("qux", "corge") -LIBPROTOC_EXPORT void ParseGeneratorParameter( - const string&, std::vector >*); +PROTOC_EXPORT void ParseGeneratorParameter( + const std::string&, std::vector >*); } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_CODE_GENERATOR_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/command_line_interface.cc b/third_party/protobuf/src/google/protobuf/compiler/command_line_interface.cc index 8380367f..a74aaefd 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/command_line_interface.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/command_line_interface.cc @@ -45,17 +45,17 @@ #ifdef minor #undef minor #endif -#include #include +#include #ifndef _MSC_VER #include #endif +#include #include #include #include -#include -#include //For PATH_MAX +#include //For PATH_MAX #include @@ -71,6 +71,7 @@ #include #include #include +#include #include #include #include @@ -81,9 +82,10 @@ #include #include #include -#include +#include + namespace google { namespace protobuf { namespace compiler { @@ -92,7 +94,7 @@ namespace compiler { #ifdef _O_BINARY #define O_BINARY _O_BINARY #else -#define O_BINARY 0 // If this isn't defined, the platform doesn't need it. +#define O_BINARY 0 // If this isn't defined, the platform doesn't need it. #endif #endif @@ -100,12 +102,12 @@ namespace { #if defined(_WIN32) // DO NOT include , instead create functions in io_win32.{h,cc} and import // them like we do below. -using google::protobuf::internal::win32::access; -using google::protobuf::internal::win32::close; -using google::protobuf::internal::win32::mkdir; -using google::protobuf::internal::win32::open; -using google::protobuf::internal::win32::setmode; -using google::protobuf::internal::win32::write; +using google::protobuf::io::win32::access; +using google::protobuf::io::win32::close; +using google::protobuf::io::win32::mkdir; +using google::protobuf::io::win32::open; +using google::protobuf::io::win32::setmode; +using google::protobuf::io::win32::write; #endif static const char* kDefaultDirectDependenciesViolationMsg = @@ -114,12 +116,10 @@ static const char* kDefaultDirectDependenciesViolationMsg = // Returns true if the text looks like a Windows-style absolute path, starting // with a drive letter. Example: "C:\foo". TODO(kenton): Share this with // copy in importer.cc? -static bool IsWindowsAbsolutePath(const string& text) { +static bool IsWindowsAbsolutePath(const std::string& text) { #if defined(_WIN32) || defined(__CYGWIN__) - return text.size() >= 3 && text[1] == ':' && - isalpha(text[0]) && - (text[2] == '/' || text[2] == '\\') && - text.find_last_of(':') == 1; + return text.size() >= 3 && text[1] == ':' && isalpha(text[0]) && + (text[2] == '/' || text[2] == '\\') && text.find_last_of(':') == 1; #else return false; #endif @@ -145,13 +145,13 @@ void SetFdToBinaryMode(int fd) { // (Text and binary are the same on non-Windows platforms.) } -void AddTrailingSlash(string* path) { +void AddTrailingSlash(std::string* path) { if (!path->empty() && path->at(path->size() - 1) != '/') { path->push_back('/'); } } -bool VerifyDirectoryExists(const string& path) { +bool VerifyDirectoryExists(const std::string& path) { if (path.empty()) return true; if (access(path.c_str(), F_OK) == -1) { @@ -166,10 +166,13 @@ bool VerifyDirectoryExists(const string& path) { // parent if necessary, and so on. The full file name is actually // (prefix + filename), but we assume |prefix| already exists and only create // directories listed in |filename|. -bool TryCreateParentDirectory(const string& prefix, const string& filename) { +bool TryCreateParentDirectory(const std::string& prefix, + const std::string& filename) { // Recursively create parent directories to the output file. - std::vector parts = Split(filename, "/", true); - string path_so_far = prefix; + // On Windows, both '/' and '\' are valid path separators. + std::vector parts = + Split(filename, "/\\", true); + std::string path_so_far = prefix; for (int i = 0; i < parts.size() - 1; i++) { path_so_far += parts[i]; if (mkdir(path_so_far.c_str(), 0777) != 0) { @@ -186,11 +189,11 @@ bool TryCreateParentDirectory(const string& prefix, const string& filename) { } // Get the absolute path of this protoc binary. -bool GetProtocAbsolutePath(string* path) { +bool GetProtocAbsolutePath(std::string* path) { #ifdef _WIN32 char buffer[MAX_PATH]; int len = GetModuleFileNameA(NULL, buffer, MAX_PATH); -#elif __APPLE__ +#elif defined(__APPLE__) char buffer[PATH_MAX]; int len = 0; @@ -214,51 +217,55 @@ bool GetProtocAbsolutePath(string* path) { // Whether a path is where google/protobuf/descriptor.proto and other well-known // type protos are installed. -bool IsInstalledProtoPath(const string& path) { +bool IsInstalledProtoPath(const std::string& path) { // Checking the descriptor.proto file should be good enough. - string file_path = path + "/google/protobuf/descriptor.proto"; + std::string file_path = path + "/google/protobuf/descriptor.proto"; return access(file_path.c_str(), F_OK) != -1; } // Add the paths where google/protobuf/descriptor.proto and other well-known // type protos are installed. -void AddDefaultProtoPaths(std::vector >* paths) { +void AddDefaultProtoPaths( + std::vector >* paths) { // TODO(xiaofeng): The code currently only checks relative paths of where // the protoc binary is installed. We probably should make it handle more // cases than that. - string path; + std::string path; if (!GetProtocAbsolutePath(&path)) { return; } // Strip the binary name. size_t pos = path.find_last_of("/\\"); - if (pos == string::npos || pos == 0) { + if (pos == std::string::npos || pos == 0) { return; } path = path.substr(0, pos); // Check the binary's directory. if (IsInstalledProtoPath(path)) { - paths->push_back(std::pair("", path)); + paths->push_back(std::pair("", path)); return; } // Check if there is an include subdirectory. if (IsInstalledProtoPath(path + "/include")) { - paths->push_back(std::pair("", path + "/include")); + paths->push_back( + std::pair("", path + "/include")); return; } // Check if the upper level directory has an "include" subdirectory. pos = path.find_last_of("/\\"); - if (pos == string::npos || pos == 0) { + if (pos == std::string::npos || pos == 0) { return; } path = path.substr(0, pos); if (IsInstalledProtoPath(path + "/include")) { - paths->push_back(std::pair("", path + "/include")); + paths->push_back( + std::pair("", path + "/include")); return; } } -string PluginName(const string& plugin_prefix, const string& directive) { +string PluginName(const std::string& plugin_prefix, + const std::string& directive) { // Assuming the directive starts with "--" and ends with "_out" or "_opt", // strip the "--" and "_out/_opt" and add the plugin prefix. return plugin_prefix + "gen-" + directive.substr(2, directive.size() - 6); @@ -272,60 +279,53 @@ class CommandLineInterface::ErrorPrinter public io::ErrorCollector, public DescriptorPool::ErrorCollector { public: - ErrorPrinter(ErrorFormat format, DiskSourceTree *tree = NULL) - : format_(format), tree_(tree), found_errors_(false) {} + ErrorPrinter(ErrorFormat format, DiskSourceTree* tree = NULL) + : format_(format), tree_(tree), found_errors_(false) {} ~ErrorPrinter() {} // implements MultiFileErrorCollector ------------------------------ - void AddError(const string& filename, int line, int column, - const string& message) { + void AddError(const std::string& filename, int line, int column, + const std::string& message) { found_errors_ = true; AddErrorOrWarning(filename, line, column, message, "error", std::cerr); } - void AddWarning(const string& filename, int line, int column, - const string& message) { + void AddWarning(const std::string& filename, int line, int column, + const std::string& message) { AddErrorOrWarning(filename, line, column, message, "warning", std::clog); } // implements io::ErrorCollector ----------------------------------- - void AddError(int line, int column, const string& message) { + void AddError(int line, int column, const std::string& message) { AddError("input", line, column, message); } - void AddWarning(int line, int column, const string& message) { + void AddWarning(int line, int column, const std::string& message) { AddErrorOrWarning("input", line, column, message, "warning", std::clog); } // implements DescriptorPool::ErrorCollector------------------------- - void AddError( - const string& filename, - const string& element_name, - const Message* descriptor, - ErrorLocation location, - const string& message) { + void AddError(const std::string& filename, const std::string& element_name, + const Message* descriptor, ErrorLocation location, + const std::string& message) { AddErrorOrWarning(filename, -1, -1, message, "error", std::cerr); } - void AddWarning( - const string& filename, - const string& element_name, - const Message* descriptor, - ErrorLocation location, - const string& message) { + void AddWarning(const std::string& filename, const std::string& element_name, + const Message* descriptor, ErrorLocation location, + const std::string& message) { AddErrorOrWarning(filename, -1, -1, message, "warning", std::clog); } bool FoundErrors() const { return found_errors_; } private: - void AddErrorOrWarning(const string& filename, int line, int column, - const string& message, const string& type, + void AddErrorOrWarning(const std::string& filename, int line, int column, + const std::string& message, const std::string& type, std::ostream& out) { // Print full path when running under MSVS - string dfile; - if (format_ == CommandLineInterface::ERROR_FORMAT_MSVS && - tree_ != NULL && + std::string dfile; + if (format_ == CommandLineInterface::ERROR_FORMAT_MSVS && tree_ != NULL && tree_->VirtualFileToDiskFile(filename, &dfile)) { out << dfile; } else { @@ -341,8 +341,8 @@ class CommandLineInterface::ErrorPrinter out << ":" << (line + 1) << ":" << (column + 1); break; case CommandLineInterface::ERROR_FORMAT_MSVS: - out << "(" << (line + 1) << ") : " - << type << " in column=" << (column + 1); + out << "(" << (line + 1) << ") : " << type + << " in column=" << (column + 1); break; } } @@ -355,7 +355,7 @@ class CommandLineInterface::ErrorPrinter } const ErrorFormat format_; - DiskSourceTree *tree_; + DiskSourceTree* tree_; bool found_errors_; }; @@ -370,24 +370,24 @@ class CommandLineInterface::GeneratorContextImpl : public GeneratorContext { // Write all files in the directory to disk at the given output location, // which must end in a '/'. - bool WriteAllToDisk(const string& prefix); + bool WriteAllToDisk(const std::string& prefix); // Write the contents of this directory to a ZIP-format archive with the // given name. - bool WriteAllToZip(const string& filename); + bool WriteAllToZip(const std::string& filename); // Add a boilerplate META-INF/MANIFEST.MF file as required by the Java JAR // format, unless one has already been written. void AddJarManifest(); // Get name of all output files. - void GetOutputFilenames(std::vector* output_filenames); + void GetOutputFilenames(std::vector* output_filenames); // implements GeneratorContext -------------------------------------- - io::ZeroCopyOutputStream* Open(const string& filename); - io::ZeroCopyOutputStream* OpenForAppend(const string& filename); - io::ZeroCopyOutputStream* OpenForInsert( - const string& filename, const string& insertion_point); + io::ZeroCopyOutputStream* Open(const std::string& filename); + io::ZeroCopyOutputStream* OpenForAppend(const std::string& filename); + io::ZeroCopyOutputStream* OpenForInsert(const std::string& filename, + const std::string& insertion_point); void ListParsedFiles(std::vector* output) { *output = parsed_files_; } @@ -395,9 +395,9 @@ class CommandLineInterface::GeneratorContextImpl : public GeneratorContext { private: friend class MemoryOutputStream; - // map instead of hash_map so that files are written in order (good when + // map instead of unordered_map so that files are written in order (good when // writing zips). - std::map files_; + std::map files_; const std::vector& parsed_files_; bool had_error_; }; @@ -405,16 +405,17 @@ class CommandLineInterface::GeneratorContextImpl : public GeneratorContext { class CommandLineInterface::MemoryOutputStream : public io::ZeroCopyOutputStream { public: - MemoryOutputStream(GeneratorContextImpl* directory, const string& filename, - bool append_mode); - MemoryOutputStream(GeneratorContextImpl* directory, const string& filename, - const string& insertion_point); + MemoryOutputStream(GeneratorContextImpl* directory, + const std::string& filename, bool append_mode); + MemoryOutputStream(GeneratorContextImpl* directory, + const std::string& filename, + const std::string& insertion_point); virtual ~MemoryOutputStream(); // implements ZeroCopyOutputStream --------------------------------- virtual bool Next(void** data, int* size) { return inner_->Next(data, size); } - virtual void BackUp(int count) { inner_->BackUp(count); } - virtual int64 ByteCount() const { return inner_->ByteCount(); } + virtual void BackUp(int count) { inner_->BackUp(count); } + virtual int64 ByteCount() const { return inner_->ByteCount(); } private: // Checks to see if "filename_.meta" exists in directory_; if so, fixes the @@ -426,11 +427,11 @@ class CommandLineInterface::MemoryOutputStream // Where to insert the string when it's done. GeneratorContextImpl* directory_; - string filename_; - string insertion_point_; + std::string filename_; + std::string insertion_point_; // The string we're building. - string data_; + std::string data_; // Whether we should append the output stream to the existing file. bool append_mode_; @@ -443,15 +444,14 @@ class CommandLineInterface::MemoryOutputStream CommandLineInterface::GeneratorContextImpl::GeneratorContextImpl( const std::vector& parsed_files) - : parsed_files_(parsed_files), - had_error_(false) {} + : parsed_files_(parsed_files), had_error_(false) {} CommandLineInterface::GeneratorContextImpl::~GeneratorContextImpl() { STLDeleteValues(&files_); } bool CommandLineInterface::GeneratorContextImpl::WriteAllToDisk( - const string& prefix) { + const std::string& prefix) { if (had_error_) { return false; } @@ -460,22 +460,23 @@ bool CommandLineInterface::GeneratorContextImpl::WriteAllToDisk( return false; } - for (std::map::const_iterator iter = files_.begin(); + for (std::map::const_iterator iter = + files_.begin(); iter != files_.end(); ++iter) { - const string& relative_filename = iter->first; + const std::string& relative_filename = iter->first; const char* data = iter->second->data(); int size = iter->second->size(); if (!TryCreateParentDirectory(prefix, relative_filename)) { return false; } - string filename = prefix + relative_filename; + std::string filename = prefix + relative_filename; // Create the output file. int file_descriptor; do { file_descriptor = - open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666); + open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666); } while (file_descriptor < 0 && errno == EINTR); if (file_descriptor < 0) { @@ -526,7 +527,7 @@ bool CommandLineInterface::GeneratorContextImpl::WriteAllToDisk( } bool CommandLineInterface::GeneratorContextImpl::WriteAllToZip( - const string& filename) { + const std::string& filename) { if (had_error_) { return false; } @@ -535,7 +536,7 @@ bool CommandLineInterface::GeneratorContextImpl::WriteAllToZip( int file_descriptor; do { file_descriptor = - open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666); + open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666); } while (file_descriptor < 0 && errno == EINTR); if (file_descriptor < 0) { @@ -548,7 +549,8 @@ bool CommandLineInterface::GeneratorContextImpl::WriteAllToZip( io::FileOutputStream stream(file_descriptor); ZipWriter zip_writer(&stream); - for (std::map::const_iterator iter = files_.begin(); + for (std::map::const_iterator iter = + files_.begin(); iter != files_.end(); ++iter) { zip_writer.Write(iter->first, *iter->second); } @@ -567,9 +569,9 @@ bool CommandLineInterface::GeneratorContextImpl::WriteAllToZip( } void CommandLineInterface::GeneratorContextImpl::AddJarManifest() { - string** map_slot = &files_["META-INF/MANIFEST.MF"]; + std::string** map_slot = &files_["META-INF/MANIFEST.MF"]; if (*map_slot == NULL) { - *map_slot = new string( + *map_slot = new std::string( "Manifest-Version: 1.0\n" "Created-By: 1.6.0 (protoc)\n" "\n"); @@ -577,58 +579,57 @@ void CommandLineInterface::GeneratorContextImpl::AddJarManifest() { } void CommandLineInterface::GeneratorContextImpl::GetOutputFilenames( - std::vector* output_filenames) { - for (std::map::iterator iter = files_.begin(); + std::vector* output_filenames) { + for (std::map::iterator iter = files_.begin(); iter != files_.end(); ++iter) { output_filenames->push_back(iter->first); } } io::ZeroCopyOutputStream* CommandLineInterface::GeneratorContextImpl::Open( - const string& filename) { + const std::string& filename) { return new MemoryOutputStream(this, filename, false); } io::ZeroCopyOutputStream* CommandLineInterface::GeneratorContextImpl::OpenForAppend( - const string& filename) { + const std::string& filename) { return new MemoryOutputStream(this, filename, true); } io::ZeroCopyOutputStream* CommandLineInterface::GeneratorContextImpl::OpenForInsert( - const string& filename, const string& insertion_point) { + const std::string& filename, const std::string& insertion_point) { return new MemoryOutputStream(this, filename, insertion_point); } // ------------------------------------------------------------------- CommandLineInterface::MemoryOutputStream::MemoryOutputStream( - GeneratorContextImpl* directory, const string& filename, bool append_mode) + GeneratorContextImpl* directory, const std::string& filename, + bool append_mode) : directory_(directory), filename_(filename), append_mode_(append_mode), - inner_(new io::StringOutputStream(&data_)) { -} + inner_(new io::StringOutputStream(&data_)) {} CommandLineInterface::MemoryOutputStream::MemoryOutputStream( - GeneratorContextImpl* directory, const string& filename, - const string& insertion_point) + GeneratorContextImpl* directory, const std::string& filename, + const std::string& insertion_point) : directory_(directory), filename_(filename), insertion_point_(insertion_point), - inner_(new io::StringOutputStream(&data_)) { -} + inner_(new io::StringOutputStream(&data_)) {} void CommandLineInterface::MemoryOutputStream::UpdateMetadata( size_t insertion_offset, size_t insertion_length) { - std::map::iterator meta_file = + std::map::iterator meta_file = directory_->files_.find(filename_ + ".meta"); if (meta_file == directory_->files_.end() || !meta_file->second) { // No metadata was recorded for this file. return; } - string* encoded_data = meta_file->second; + std::string* encoded_data = meta_file->second; GeneratedCodeInfo metadata; bool is_text_format = false; if (!metadata.ParseFromString(*encoded_data)) { @@ -663,7 +664,7 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() { inner_.reset(); // Insert into the directory. - string** map_slot = &directory_->files_[filename_]; + std::string** map_slot = &directory_->files_[filename_]; if (insertion_point_.empty()) { // This was just a regular Open(). @@ -678,7 +679,7 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() { return; } - *map_slot = new string; + *map_slot = new std::string; (*map_slot)->swap(data_); } else { // This was an OpenForInsert(). @@ -696,14 +697,14 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() { directory_->had_error_ = true; return; } - string* target = *map_slot; + std::string* target = *map_slot; // Find the insertion point. - string magic_string = strings::Substitute( - "@@protoc_insertion_point($0)", insertion_point_); - string::size_type pos = target->find(magic_string); + std::string magic_string = + strings::Substitute("@@protoc_insertion_point($0)", insertion_point_); + std::string::size_type pos = target->find(magic_string); - if (pos == string::npos) { + if (pos == std::string::npos) { std::cerr << filename_ << ": insertion point \"" << insertion_point_ << "\" not found." << std::endl; directory_->had_error_ = true; @@ -720,7 +721,7 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() { // intentional because it means that multiple insertions at the same point // will end up in the expected order in the final output. pos = target->find_last_of('\n', pos); - if (pos == string::npos) { + if (pos == std::string::npos) { // Insertion point is on the first line. pos = 0; } else { @@ -730,7 +731,8 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() { } // Extract indent. - string indent_(*target, pos, target->find_first_not_of(" \t", pos) - pos); + std::string indent_(*target, pos, + target->find_first_not_of(" \t", pos) - pos); if (indent_.empty()) { // No indent. This makes things easier. @@ -748,8 +750,8 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() { UpdateMetadata(pos, data_.size() + indent_size); // Now copy in the data. - string::size_type data_pos = 0; - char* target_ptr = string_as_array(target) + pos; + std::string::size_type data_pos = 0; + char* target_ptr = ::google::protobuf::string_as_array(target) + pos; while (data_pos < data_.size()) { // Copy indent. memcpy(target_ptr, indent_.data(), indent_.size()); @@ -758,7 +760,7 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() { // Copy line from data_. // We already guaranteed that data_ ends with a newline (above), so this // search can't fail. - string::size_type line_length = + std::string::size_type line_length = data_.find_first_of('\n', data_pos) + 1 - data_pos; memcpy(target_ptr, data_.data() + data_pos, line_length); target_ptr += line_length; @@ -766,7 +768,7 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() { } GOOGLE_CHECK_EQ(target_ptr, - string_as_array(target) + pos + data_.size() + indent_size); + ::google::protobuf::string_as_array(target) + pos + data_.size() + indent_size); } } } @@ -788,12 +790,13 @@ CommandLineInterface::CommandLineInterface() kDefaultDirectDependenciesViolationMsg), imports_in_descriptor_set_(false), source_info_in_descriptor_set_(false), - disallow_services_(false) {} + disallow_services_(false) { +} CommandLineInterface::~CommandLineInterface() {} -void CommandLineInterface::RegisterGenerator(const string& flag_name, +void CommandLineInterface::RegisterGenerator(const std::string& flag_name, CodeGenerator* generator, - const string& help_text) { + const std::string& help_text) { GeneratorInfo info; info.flag_name = flag_name; info.generator = generator; @@ -801,10 +804,9 @@ void CommandLineInterface::RegisterGenerator(const string& flag_name, generators_by_flag_name_[flag_name] = info; } -void CommandLineInterface::RegisterGenerator(const string& flag_name, - const string& option_flag_name, - CodeGenerator* generator, - const string& help_text) { +void CommandLineInterface::RegisterGenerator( + const std::string& flag_name, const std::string& option_flag_name, + CodeGenerator* generator, const std::string& help_text) { GeneratorInfo info; info.flag_name = flag_name; info.option_flag_name = option_flag_name; @@ -814,7 +816,7 @@ void CommandLineInterface::RegisterGenerator(const string& flag_name, generators_by_option_name_[option_flag_name] = info; } -void CommandLineInterface::AllowPlugins(const string& exe_name_prefix) { +void CommandLineInterface::AllowPlugins(const std::string& exe_name_prefix) { plugin_prefix_ = exe_name_prefix; } @@ -830,35 +832,51 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) { } std::vector parsed_files; - // null unless descriptor_set_in_names_.empty() std::unique_ptr disk_source_tree; std::unique_ptr error_collector; std::unique_ptr descriptor_pool; - std::unique_ptr descriptor_database; - if (descriptor_set_in_names_.empty()) { - disk_source_tree.reset(new DiskSourceTree()); - if (!InitializeDiskSourceTree(disk_source_tree.get())) { + std::unique_ptr descriptor_set_in_database; + std::unique_ptr source_tree_database; + + // Any --descriptor_set_in FileDescriptorSet objects will be used as a + // fallback to input_files on command line, so create that db first. + if (!descriptor_set_in_names_.empty()) { + descriptor_set_in_database.reset(new SimpleDescriptorDatabase()); + if (!PopulateSimpleDescriptorDatabase(descriptor_set_in_database.get())) { return 1; } + } + + if (proto_path_.empty()) { + // If there are no --proto_path flags, then just look in the specified + // --descriptor_set_in files. But first, verify that the input files are + // there. + if (!VerifyInputFilesInDescriptors(descriptor_set_in_database.get())) { + return 1; + } + + error_collector.reset(new ErrorPrinter(error_format_)); + descriptor_pool.reset(new DescriptorPool(descriptor_set_in_database.get(), + error_collector.get())); + } else { + disk_source_tree.reset(new DiskSourceTree()); + if (!InitializeDiskSourceTree(disk_source_tree.get(), + descriptor_set_in_database.get())) { + return 1; + } + error_collector.reset( new ErrorPrinter(error_format_, disk_source_tree.get())); - SourceTreeDescriptorDatabase* database = - new SourceTreeDescriptorDatabase(disk_source_tree.get()); - database->RecordErrorsTo(error_collector.get()); - descriptor_database.reset(database); - descriptor_pool.reset(new DescriptorPool( - descriptor_database.get(), database->GetValidationErrorCollector())); - } else { - error_collector.reset(new ErrorPrinter(error_format_)); + source_tree_database.reset(new SourceTreeDescriptorDatabase( + disk_source_tree.get(), descriptor_set_in_database.get())); + source_tree_database->RecordErrorsTo(error_collector.get()); - SimpleDescriptorDatabase* database = new SimpleDescriptorDatabase(); - descriptor_database.reset(database); - if (!PopulateSimpleDescriptorDatabase(database)) { - return 1; - } - descriptor_pool.reset(new DescriptorPool(database, error_collector.get())); + descriptor_pool.reset(new DescriptorPool( + source_tree_database.get(), + source_tree_database->GetValidationErrorCollector())); } + descriptor_pool->EnforceWeakDependencies(true); if (!ParseInputFiles(descriptor_pool.get(), &parsed_files)) { return 1; @@ -873,7 +891,7 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) { // Generate output. if (mode_ == MODE_COMPILE) { for (int i = 0; i < output_directives_.size(); i++) { - string output_location = output_directives_[i].output_location; + std::string output_location = output_directives_[i].output_location; if (!HasSuffixString(output_location, ".zip") && !HasSuffixString(output_location, ".jar")) { AddTrailingSlash(&output_location); @@ -895,7 +913,7 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) { // Write all output to disk. for (GeneratorContextMap::iterator iter = output_directories.begin(); iter != output_directories.end(); ++iter) { - const string& location = iter->first; + const std::string& location = iter->first; GeneratorContextImpl* directory = iter->second; if (HasSuffixString(location, "/")) { if (!directory->WriteAllToDisk(location)) { @@ -965,10 +983,10 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) { break; case PRINT_NONE: GOOGLE_LOG(ERROR) << "If the code reaches here, it usually means a bug of " - "flag parsing in the CommandLineInterface."; + "flag parsing in the CommandLineInterface."; return 1; - // Do not add a default case. + // Do not add a default case. } } @@ -976,7 +994,7 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) { } bool CommandLineInterface::InitializeDiskSourceTree( - DiskSourceTree* source_tree) { + DiskSourceTree* source_tree, DescriptorDatabase* fallback_database) { AddDefaultProtoPaths(&proto_path_); // Set up the source tree. @@ -985,9 +1003,10 @@ bool CommandLineInterface::InitializeDiskSourceTree( } // Map input files to virtual paths if possible. - if (!MakeInputsBeProtoPathRelative(source_tree)) { + if (!MakeInputsBeProtoPathRelative(source_tree, fallback_database)) { return false; } + return true; } @@ -999,16 +1018,15 @@ bool CommandLineInterface::PopulateSimpleDescriptorDatabase( fd = open(descriptor_set_in_names_[i].c_str(), O_RDONLY | O_BINARY); } while (fd < 0 && errno == EINTR); if (fd < 0) { - std::cerr << descriptor_set_in_names_[i] << ": " - << strerror(ENOENT) << std::endl; + std::cerr << descriptor_set_in_names_[i] << ": " << strerror(ENOENT) + << std::endl; return false; } FileDescriptorSet file_descriptor_set; bool parsed = file_descriptor_set.ParseFromFileDescriptor(fd); if (close(fd) != 0) { - std::cerr << descriptor_set_in_names_[i] << ": close: " - << strerror(errno) + std::cerr << descriptor_set_in_names_[i] << ": close: " << strerror(errno) << std::endl; return false; } @@ -1034,29 +1052,49 @@ bool CommandLineInterface::PopulateSimpleDescriptorDatabase( return true; } +bool CommandLineInterface::VerifyInputFilesInDescriptors( + DescriptorDatabase* database) { + for (const auto& input_file : input_files_) { + FileDescriptorProto file_descriptor; + if (!database->FindFileByName(input_file, &file_descriptor)) { + std::cerr << input_file << ": " << strerror(ENOENT) << std::endl; + return false; + } + + // Enforce --disallow_services. + if (disallow_services_ && file_descriptor.service_size() > 0) { + std::cerr << file_descriptor.name() + << ": This file contains services, but " + "--disallow_services was used." + << std::endl; + return false; + } + } + return true; +} + bool CommandLineInterface::ParseInputFiles( DescriptorPool* descriptor_pool, std::vector* parsed_files) { // Parse each file. - for (int i = 0; i < input_files_.size(); i++) { + for (const auto& input_file : input_files_) { // Import the file. - descriptor_pool->AddUnusedImportTrackFile(input_files_[i]); + descriptor_pool->AddUnusedImportTrackFile(input_file); const FileDescriptor* parsed_file = - descriptor_pool->FindFileByName(input_files_[i]); + descriptor_pool->FindFileByName(input_file); descriptor_pool->ClearUnusedImportTrackFiles(); if (parsed_file == NULL) { - if (!descriptor_set_in_names_.empty()) { - std::cerr << input_files_[i] << ": " << strerror(ENOENT) << std::endl; - } return false; } parsed_files->push_back(parsed_file); // Enforce --disallow_services. if (disallow_services_ && parsed_file->service_count() > 0) { - std::cerr << parsed_file->name() << ": This file contains services, but " - "--disallow_services was used." << std::endl; + std::cerr << parsed_file->name() + << ": This file contains services, but " + "--disallow_services was used." + << std::endl; return false; } @@ -1096,6 +1134,7 @@ void CommandLineInterface::Clear() { descriptor_set_out_name_.clear(); dependency_out_name_.clear(); + mode_ = MODE_COMPILE; print_mode_ = PRINT_NONE; imports_in_descriptor_set_ = false; @@ -1104,73 +1143,96 @@ void CommandLineInterface::Clear() { direct_dependencies_explicitly_set_ = false; } -bool CommandLineInterface::MakeInputsBeProtoPathRelative( - DiskSourceTree* source_tree) { - for (int i = 0; i < input_files_.size(); i++) { - // If the input file path is not a physical file path, it must be a virtual - // path. - if (access(input_files_[i].c_str(), F_OK) < 0) { - string disk_file; - if (source_tree->VirtualFileToDiskFile(input_files_[i], &disk_file)) { +bool CommandLineInterface::MakeProtoProtoPathRelative( + DiskSourceTree* source_tree, std::string* proto, + DescriptorDatabase* fallback_database) { + // If it's in the fallback db, don't report non-existent file errors. + FileDescriptorProto fallback_file; + bool in_fallback_database = + fallback_database != nullptr && + fallback_database->FindFileByName(*proto, &fallback_file); + + // If the input file path is not a physical file path, it must be a virtual + // path. + if (access(proto->c_str(), F_OK) < 0) { + std::string disk_file; + if (source_tree->VirtualFileToDiskFile(*proto, &disk_file) || + in_fallback_database) { + return true; + } else { + std::cerr << *proto << ": " << strerror(ENOENT) << std::endl; + return false; + } + } + + std::string virtual_file, shadowing_disk_file; + switch (source_tree->DiskFileToVirtualFile(*proto, &virtual_file, + &shadowing_disk_file)) { + case DiskSourceTree::SUCCESS: + *proto = virtual_file; + break; + case DiskSourceTree::SHADOWED: + std::cerr << *proto << ": Input is shadowed in the --proto_path by \"" + << shadowing_disk_file + << "\". Either use the latter file as your input or reorder " + "the --proto_path so that the former file's location " + "comes first." + << std::endl; + return false; + case DiskSourceTree::CANNOT_OPEN: + if (in_fallback_database) { + return true; + } + std::cerr << *proto << ": " << strerror(errno) << std::endl; + return false; + case DiskSourceTree::NO_MAPPING: { + // Try to interpret the path as a virtual path. + std::string disk_file; + if (source_tree->VirtualFileToDiskFile(*proto, &disk_file) || + in_fallback_database) { return true; } else { - std::cerr << input_files_[i] << ": " << strerror(ENOENT) << std::endl; + // The input file path can't be mapped to any --proto_path and it also + // can't be interpreted as a virtual path. + std::cerr + << *proto + << ": File does not reside within any path " + "specified using --proto_path (or -I). You must specify a " + "--proto_path which encompasses this file. Note that the " + "proto_path must be an exact prefix of the .proto file " + "names -- protoc is too dumb to figure out when two paths " + "(e.g. absolute and relative) are equivalent (it's harder " + "than you think)." + << std::endl; return false; } } - string virtual_file, shadowing_disk_file; - switch (source_tree->DiskFileToVirtualFile( - input_files_[i], &virtual_file, &shadowing_disk_file)) { - case DiskSourceTree::SUCCESS: - input_files_[i] = virtual_file; - break; - case DiskSourceTree::SHADOWED: - std::cerr << input_files_[i] - << ": Input is shadowed in the --proto_path by \"" - << shadowing_disk_file - << "\". Either use the latter file as your input or reorder " - "the --proto_path so that the former file's location " - "comes first." << std::endl; - return false; - case DiskSourceTree::CANNOT_OPEN: - std::cerr << input_files_[i] << ": " << strerror(errno) << std::endl; - return false; - case DiskSourceTree::NO_MAPPING: { - // Try to interpret the path as a virtual path. - string disk_file; - if (source_tree->VirtualFileToDiskFile(input_files_[i], &disk_file)) { - return true; - } else { - // The input file path can't be mapped to any --proto_path and it also - // can't be interpreted as a virtual path. - std::cerr - << input_files_[i] - << ": File does not reside within any path " - "specified using --proto_path (or -I). You must specify a " - "--proto_path which encompasses this file. Note that the " - "proto_path must be an exact prefix of the .proto file " - "names -- protoc is too dumb to figure out when two paths " - "(e.g. absolute and relative) are equivalent (it's harder " - "than you think)." - << std::endl; - return false; - } - } + } + return true; +} + +bool CommandLineInterface::MakeInputsBeProtoPathRelative( + DiskSourceTree* source_tree, DescriptorDatabase* fallback_database) { + for (auto& input_file : input_files_) { + if (!MakeProtoProtoPathRelative(source_tree, &input_file, + fallback_database)) { + return false; } } return true; } -bool CommandLineInterface::ExpandArgumentFile(const string& file, - std::vector* arguments) { + +bool CommandLineInterface::ExpandArgumentFile( + const std::string& file, std::vector* arguments) { // The argument file is searched in the working directory only. We don't // use the proto import path here. std::ifstream file_stream(file.c_str()); if (!file_stream.is_open()) { return false; } - string argument; + std::string argument; // We don't support any kind of shell expansion right now. while (std::getline(file_stream, argument)) { arguments->push_back(argument); @@ -1178,11 +1240,11 @@ bool CommandLineInterface::ExpandArgumentFile(const string& file, return true; } -CommandLineInterface::ParseArgumentStatus -CommandLineInterface::ParseArguments(int argc, const char* const argv[]) { +CommandLineInterface::ParseArgumentStatus CommandLineInterface::ParseArguments( + int argc, const char* const argv[]) { executable_name_ = argv[0]; - std::vector arguments; + std::vector arguments; for (int i = 1; i < argc; ++i) { if (argv[i][0] == '@') { if (!ExpandArgumentFile(argv[i] + 1, &arguments)) { @@ -1203,7 +1265,7 @@ CommandLineInterface::ParseArguments(int argc, const char* const argv[]) { // Iterate through all arguments and parse them. for (int i = 0; i < arguments.size(); ++i) { - string name, value; + std::string name, value; if (ParseArgument(arguments[i].c_str(), &name, &value)) { // Returned true => Use the next argument as the flag value. @@ -1221,22 +1283,23 @@ CommandLineInterface::ParseArguments(int argc, const char* const argv[]) { } ParseArgumentStatus status = InterpretArgument(name, value); - if (status != PARSE_ARGUMENT_DONE_AND_CONTINUE) - return status; + if (status != PARSE_ARGUMENT_DONE_AND_CONTINUE) return status; } // Make sure each plugin option has a matching plugin output. bool foundUnknownPluginOption = false; - for (std::map::const_iterator i = plugin_parameters_.begin(); + for (std::map::const_iterator i = + plugin_parameters_.begin(); i != plugin_parameters_.end(); ++i) { if (plugins_.find(i->first) != plugins_.end()) { continue; } bool foundImplicitPlugin = false; - for (std::vector::const_iterator j = output_directives_.begin(); + for (std::vector::const_iterator j = + output_directives_.begin(); j != output_directives_.end(); ++j) { if (j->generator == NULL) { - string plugin_name = PluginName(plugin_prefix_ , j->name); + std::string plugin_name = PluginName(plugin_prefix_, j->name); if (plugin_name == i->first) { foundImplicitPlugin = true; break; @@ -1255,15 +1318,16 @@ CommandLineInterface::ParseArguments(int argc, const char* const argv[]) { return PARSE_ARGUMENT_FAIL; } - // If no --proto_path was given, use the current working directory. - if (proto_path_.empty()) { + // The --proto_path & --descriptor_set_in flags both specify places to look + // for proto files. If neither were given, use the current working directory. + if (proto_path_.empty() && descriptor_set_in_names_.empty()) { // Don't use make_pair as the old/default standard library on Solaris // doesn't support it without explicit template parameters, which are // incompatible with C++0x's make_pair. - proto_path_.push_back(std::pair("", ".")); + proto_path_.push_back(std::pair("", ".")); } - // Check some errror cases. + // Check some error cases. bool decoding_raw = (mode_ == MODE_DECODE) && codec_type_.empty(); if (decoding_raw && !input_files_.empty()) { std::cerr << "When using --decode_raw, no input files should be given." @@ -1291,18 +1355,20 @@ CommandLineInterface::ParseArguments(int argc, const char* const argv[]) { } if (imports_in_descriptor_set_ && descriptor_set_out_name_.empty()) { std::cerr << "--include_imports only makes sense when combined with " - "--descriptor_set_out." << std::endl; + "--descriptor_set_out." + << std::endl; } if (source_info_in_descriptor_set_ && descriptor_set_out_name_.empty()) { std::cerr << "--include_source_info only makes sense when combined with " - "--descriptor_set_out." << std::endl; + "--descriptor_set_out." + << std::endl; } return PARSE_ARGUMENT_DONE_AND_CONTINUE; } -bool CommandLineInterface::ParseArgument(const char* arg, - string* name, string* value) { +bool CommandLineInterface::ParseArgument(const char* arg, std::string* name, + std::string* value) { bool parsed_value = false; if (arg[0] != '-') { @@ -1315,7 +1381,7 @@ bool CommandLineInterface::ParseArgument(const char* arg, // value. const char* equals_pos = strchr(arg, '='); if (equals_pos != NULL) { - *name = string(arg, equals_pos - arg); + *name = std::string(arg, equals_pos - arg); *value = equals_pos + 1; parsed_value = true; } else { @@ -1331,7 +1397,7 @@ bool CommandLineInterface::ParseArgument(const char* arg, *value = arg; parsed_value = true; } else { - *name = string(arg, 2); + *name = std::string(arg, 2); *value = arg + 2; parsed_value = !value->empty(); } @@ -1345,12 +1411,9 @@ bool CommandLineInterface::ParseArgument(const char* arg, return false; } - if (*name == "-h" || *name == "--help" || - *name == "--disallow_services" || - *name == "--include_imports" || - *name == "--include_source_info" || - *name == "--version" || - *name == "--decode_raw" || + if (*name == "-h" || *name == "--help" || *name == "--disallow_services" || + *name == "--include_imports" || *name == "--include_source_info" || + *name == "--version" || *name == "--decode_raw" || *name == "--print_free_field_numbers") { // HACK: These are the only flags that don't take a value. // They probably should not be hard-coded like this but for now it's @@ -1363,43 +1426,38 @@ bool CommandLineInterface::ParseArgument(const char* arg, } CommandLineInterface::ParseArgumentStatus -CommandLineInterface::InterpretArgument(const string& name, - const string& value) { +CommandLineInterface::InterpretArgument(const std::string& name, + const std::string& value) { if (name.empty()) { // Not a flag. Just a filename. if (value.empty()) { std::cerr << "You seem to have passed an empty string as one of the " - "arguments to " << executable_name_ + "arguments to " + << executable_name_ << ". This is actually " "sort of hard to do. Congrats. Unfortunately it is not valid " - "input so the program is going to die now." << std::endl; + "input so the program is going to die now." + << std::endl; return PARSE_ARGUMENT_FAIL; } input_files_.push_back(value); } else if (name == "-I" || name == "--proto_path") { - if (!descriptor_set_in_names_.empty()) { - std::cerr << "Only one of " << name - << " and --descriptor_set_in can be specified." - << std::endl; - return PARSE_ARGUMENT_FAIL; - } - // Java's -classpath (and some other languages) delimits path components // with colons. Let's accept that syntax too just to make things more // intuitive. - std::vector parts = Split( + std::vector parts = Split( value, CommandLineInterface::kPathSeparator, true); for (int i = 0; i < parts.size(); i++) { - string virtual_path; - string disk_path; + std::string virtual_path; + std::string disk_path; - string::size_type equals_pos = parts[i].find_first_of('='); - if (equals_pos == string::npos) { + std::string::size_type equals_pos = parts[i].find_first_of('='); + if (equals_pos == std::string::npos) { virtual_path = ""; disk_path = parts[i]; } else { @@ -1410,7 +1468,8 @@ CommandLineInterface::InterpretArgument(const string& name, if (disk_path.empty()) { std::cerr << "--proto_path passed empty directory name. (Use \".\" for " - "current directory.)" << std::endl; + "current directory.)" + << std::endl; return PARSE_ARGUMENT_FAIL; } @@ -1429,20 +1488,23 @@ CommandLineInterface::InterpretArgument(const string& name, // Don't use make_pair as the old/default standard library on Solaris // doesn't support it without explicit template parameters, which are // incompatible with C++0x's make_pair. - proto_path_.push_back(std::pair(virtual_path, disk_path)); + proto_path_.push_back( + std::pair(virtual_path, disk_path)); } } else if (name == "--direct_dependencies") { if (direct_dependencies_explicitly_set_) { - std::cerr << name << " may only be passed once. To specify multiple " - "direct dependencies, pass them all as a single " - "parameter separated by ':'." + std::cerr << name + << " may only be passed once. To specify multiple " + "direct dependencies, pass them all as a single " + "parameter separated by ':'." << std::endl; return PARSE_ARGUMENT_FAIL; } direct_dependencies_explicitly_set_ = true; - std::vector direct = Split(value, ":", true); + std::vector direct = + Split(value, ":", true); GOOGLE_DCHECK(direct_dependencies_.empty()); direct_dependencies_.insert(direct.begin(), direct.end()); @@ -1451,23 +1513,17 @@ CommandLineInterface::InterpretArgument(const string& name, } else if (name == "--descriptor_set_in") { if (!descriptor_set_in_names_.empty()) { - std::cerr << name << " may only be passed once. To specify multiple " - "descriptor sets, pass them all as a single " - "parameter separated by '" - << CommandLineInterface::kPathSeparator << "'." - << std::endl; + std::cerr << name + << " may only be passed once. To specify multiple " + "descriptor sets, pass them all as a single " + "parameter separated by '" + << CommandLineInterface::kPathSeparator << "'." << std::endl; return PARSE_ARGUMENT_FAIL; } if (value.empty()) { std::cerr << name << " requires a non-empty value." << std::endl; return PARSE_ARGUMENT_FAIL; } - if (!proto_path_.empty()) { - std::cerr << "Only one of " << name - << " and --proto_path can be specified." - << std::endl; - return PARSE_ARGUMENT_FAIL; - } if (!dependency_out_name_.empty()) { std::cerr << name << " cannot be used with --dependency_out." << std::endl; @@ -1490,7 +1546,8 @@ CommandLineInterface::InterpretArgument(const string& name, if (mode_ != MODE_COMPILE) { std::cerr << "Cannot use --encode or --decode and generate descriptors at the " - "same time." << std::endl; + "same time." + << std::endl; return PARSE_ARGUMENT_FAIL; } descriptor_set_out_name_ = value; @@ -1533,9 +1590,8 @@ CommandLineInterface::InterpretArgument(const string& name, if (!version_info_.empty()) { std::cout << version_info_ << std::endl; } - std::cout << "libprotoc " - << protobuf::internal::VersionString(GOOGLE_PROTOBUF_VERSION) - << std::endl; + std::cout << "libprotoc " << internal::VersionString(PROTOBUF_VERSION) + << std::endl; return PARSE_ARGUMENT_DONE_AND_EXIT; // Exit without running compiler. } else if (name == "--disallow_services") { @@ -1587,14 +1643,14 @@ CommandLineInterface::InterpretArgument(const string& name, return PARSE_ARGUMENT_FAIL; } - string plugin_name; - string path; + std::string plugin_name; + std::string path; - string::size_type equals_pos = value.find_first_of('='); - if (equals_pos == string::npos) { + std::string::size_type equals_pos = value.find_first_of('='); + if (equals_pos == std::string::npos) { // Use the basename of the file. - string::size_type slash_pos = value.find_last_of('/'); - if (slash_pos == string::npos) { + std::string::size_type slash_pos = value.find_last_of('/'); + if (slash_pos == std::string::npos) { plugin_name = value; } else { plugin_name = value.substr(slash_pos + 1); @@ -1631,13 +1687,14 @@ CommandLineInterface::InterpretArgument(const string& name, // Check if it's a generator option flag. generator_info = FindOrNull(generators_by_option_name_, name); if (generator_info != NULL) { - string* parameters = &generator_parameters_[generator_info->flag_name]; + std::string* parameters = + &generator_parameters_[generator_info->flag_name]; if (!parameters->empty()) { parameters->append(","); } parameters->append(value); } else if (HasPrefixString(name, "--") && HasSuffixString(name, "_opt")) { - string* parameters = + std::string* parameters = &plugin_parameters_[PluginName(plugin_prefix_, name)]; if (!parameters->empty()) { parameters->append(","); @@ -1651,7 +1708,8 @@ CommandLineInterface::InterpretArgument(const string& name, // It's an output flag. Add it to the output directives. if (mode_ != MODE_COMPILE) { std::cerr << "Cannot use --encode, --decode or print .proto info and " - "generate code at the same time." << std::endl; + "generate code at the same time." + << std::endl; return PARSE_ARGUMENT_FAIL; } @@ -1666,8 +1724,8 @@ CommandLineInterface::InterpretArgument(const string& name, // Split value at ':' to separate the generator parameter from the // filename. However, avoid doing this if the colon is part of a valid // Windows-style absolute path. - string::size_type colon_pos = value.find_first_of(':'); - if (colon_pos == string::npos || IsWindowsAbsolutePath(value)) { + std::string::size_type colon_pos = value.find_first_of(':'); + if (colon_pos == std::string::npos || IsWindowsAbsolutePath(value)) { directive.output_location = value; } else { directive.parameter = value.substr(0, colon_pos); @@ -1683,70 +1741,124 @@ CommandLineInterface::InterpretArgument(const string& name, void CommandLineInterface::PrintHelpText() { // Sorry for indentation here; line wrapping would be uglier. - std::cout << -"Usage: " << executable_name_ << " [OPTION] PROTO_FILES\n" -"Parse PROTO_FILES and generate output based on the options given:\n" -" -IPATH, --proto_path=PATH Specify the directory in which to search for\n" -" imports. May be specified multiple times;\n" -" directories will be searched in order. If not\n" -" given, the current working directory is used.\n" -" --version Show version info and exit.\n" -" -h, --help Show this text and exit.\n" -" --encode=MESSAGE_TYPE Read a text-format message of the given type\n" -" from standard input and write it in binary\n" -" to standard output. The message type must\n" -" be defined in PROTO_FILES or their imports.\n" -" --decode=MESSAGE_TYPE Read a binary message of the given type from\n" -" standard input and write it in text format\n" -" to standard output. The message type must\n" -" be defined in PROTO_FILES or their imports.\n" -" --decode_raw Read an arbitrary protocol message from\n" -" standard input and write the raw tag/value\n" -" pairs in text format to standard output. No\n" -" PROTO_FILES should be given when using this\n" -" flag.\n" -" --descriptor_set_in=FILES Specifies a delimited list of FILES\n" -" each containing a FileDescriptorSet (a\n" -" protocol buffer defined in descriptor.proto).\n" -" The FileDescriptor for each of the PROTO_FILES\n" -" provided will be loaded from these\n" -" FileDescriptorSets. If a FileDescriptor\n" -" appears multiple times, the first occurrence\n" -" will be used.\n" -" -oFILE, Writes a FileDescriptorSet (a protocol buffer,\n" -" --descriptor_set_out=FILE defined in descriptor.proto) containing all of\n" -" the input files to FILE.\n" -" --include_imports When using --descriptor_set_out, also include\n" -" all dependencies of the input files in the\n" -" set, so that the set is self-contained.\n" -" --include_source_info When using --descriptor_set_out, do not strip\n" -" SourceCodeInfo from the FileDescriptorProto.\n" -" This results in vastly larger descriptors that\n" -" include information about the original\n" -" location of each decl in the source file as\n" -" well as surrounding comments.\n" -" --dependency_out=FILE Write a dependency output file in the format\n" -" expected by make. This writes the transitive\n" -" set of input file paths to FILE\n" -" --error_format=FORMAT Set the format in which to print errors.\n" -" FORMAT may be 'gcc' (the default) or 'msvs'\n" -" (Microsoft Visual Studio format).\n" -" --print_free_field_numbers Print the free field numbers of the messages\n" -" defined in the given proto files. Groups share\n" -" the same field number space with the parent \n" -" message. Extension ranges are counted as \n" -" occupied fields numbers.\n" + std::cout + << + "Usage: " << executable_name_ + << " [OPTION] PROTO_FILES\n" + "Parse PROTO_FILES and generate output based on the options given:\n" + " -IPATH, --proto_path=PATH Specify the directory in which to " + "search for\n" + " imports. May be specified multiple " + "times;\n" + " directories will be searched in order. " + " If not\n" + " given, the current working directory " + "is used.\n" + " If not found in any of the these " + "directories,\n" + " the --descriptor_set_in descriptors " + "will be\n" + " checked for required proto file.\n" + " --version Show version info and exit.\n" + " -h, --help Show this text and exit.\n" + " --encode=MESSAGE_TYPE Read a text-format message of the " + "given type\n" + " from standard input and write it in " + "binary\n" + " to standard output. The message type " + "must\n" + " be defined in PROTO_FILES or their " + "imports.\n" + " --decode=MESSAGE_TYPE Read a binary message of the given " + "type from\n" + " standard input and write it in text " + "format\n" + " to standard output. The message type " + "must\n" + " be defined in PROTO_FILES or their " + "imports.\n" + " --decode_raw Read an arbitrary protocol message " + "from\n" + " standard input and write the raw " + "tag/value\n" + " pairs in text format to standard " + "output. No\n" + " PROTO_FILES should be given when using " + "this\n" + " flag.\n" + " --descriptor_set_in=FILES Specifies a delimited list of FILES\n" + " each containing a FileDescriptorSet " + "(a\n" + " protocol buffer defined in " + "descriptor.proto).\n" + " The FileDescriptor for each of the " + "PROTO_FILES\n" + " provided will be loaded from these\n" + " FileDescriptorSets. If a " + "FileDescriptor\n" + " appears multiple times, the first " + "occurrence\n" + " will be used.\n" + " -oFILE, Writes a FileDescriptorSet (a protocol " + "buffer,\n" + " --descriptor_set_out=FILE defined in descriptor.proto) " + "containing all of\n" + " the input files to FILE.\n" + " --include_imports When using --descriptor_set_out, also " + "include\n" + " all dependencies of the input files in " + "the\n" + " set, so that the set is " + "self-contained.\n" + " --include_source_info When using --descriptor_set_out, do " + "not strip\n" + " SourceCodeInfo from the " + "FileDescriptorProto.\n" + " This results in vastly larger " + "descriptors that\n" + " include information about the " + "original\n" + " location of each decl in the source " + "file as\n" + " well as surrounding comments.\n" + " --dependency_out=FILE Write a dependency output file in the " + "format\n" + " expected by make. This writes the " + "transitive\n" + " set of input file paths to FILE\n" + " --error_format=FORMAT Set the format in which to print " + "errors.\n" + " FORMAT may be 'gcc' (the default) or " + "'msvs'\n" + " (Microsoft Visual Studio format).\n" + " --print_free_field_numbers Print the free field numbers of the " + "messages\n" + " defined in the given proto files. " + "Groups share\n" + " the same field number space with the " + "parent \n" + " message. Extension ranges are counted " + "as \n" + " occupied fields numbers.\n" << std::endl; if (!plugin_prefix_.empty()) { - std::cout << -" --plugin=EXECUTABLE Specifies a plugin executable to use.\n" -" Normally, protoc searches the PATH for\n" -" plugins, but you may specify additional\n" -" executables not in the path using this flag.\n" -" Additionally, EXECUTABLE may be of the form\n" -" NAME=PATH, in which case the given plugin name\n" -" is mapped to the given executable even if\n" -" the executable's own name differs." << std::endl; + std::cout + << " --plugin=EXECUTABLE Specifies a plugin executable to " + "use.\n" + " Normally, protoc searches the PATH " + "for\n" + " plugins, but you may specify " + "additional\n" + " executables not in the path using " + "this flag.\n" + " Additionally, EXECUTABLE may be of " + "the form\n" + " NAME=PATH, in which case the given " + "plugin name\n" + " is mapped to the given executable " + "even if\n" + " the executable's own name differs." + << std::endl; } for (GeneratorMap::iterator iter = generators_by_flag_name_.begin(); @@ -1755,23 +1867,34 @@ void CommandLineInterface::PrintHelpText() { // but fixing this nicely (e.g. splitting on spaces) is probably more // trouble than it's worth. std::cout << " " << iter->first << "=OUT_DIR " - << string(19 - iter->first.size(), ' ') // Spaces for alignment. + << std::string(19 - iter->first.size(), + ' ') // Spaces for alignment. << iter->second.help_text << std::endl; } - std::cerr << -" @ Read options and filenames from file. If a\n" -" relative file path is specified, the file\n" -" will be searched in the working directory.\n" -" The --proto_path option will not affect how\n" -" this argument file is searched. Content of\n" -" the file will be expanded in the position of\n" -" @ as in the argument list. Note\n" -" that shell expansion is not applied to the\n" -" content of the file (i.e., you cannot use\n" -" quotes, wildcards, escapes, commands, etc.).\n" -" Each line corresponds to a single argument,\n" -" even if it contains spaces." - << std::endl; + std::cout << " @ Read options and filenames from " + "file. If a\n" + " relative file path is specified, " + "the file\n" + " will be searched in the working " + "directory.\n" + " The --proto_path option will not " + "affect how\n" + " this argument file is searched. " + "Content of\n" + " the file will be expanded in the " + "position of\n" + " @ as in the argument " + "list. Note\n" + " that shell expansion is not " + "applied to the\n" + " content of the file (i.e., you " + "cannot use\n" + " quotes, wildcards, escapes, " + "commands, etc.).\n" + " Each line corresponds to a " + "single argument,\n" + " even if it contains spaces." + << std::endl; } bool CommandLineInterface::GenerateOutput( @@ -1779,38 +1902,37 @@ bool CommandLineInterface::GenerateOutput( const OutputDirective& output_directive, GeneratorContext* generator_context) { // Call the generator. - string error; + std::string error; if (output_directive.generator == NULL) { // This is a plugin. GOOGLE_CHECK(HasPrefixString(output_directive.name, "--") && HasSuffixString(output_directive.name, "_out")) << "Bad name for plugin generator: " << output_directive.name; - string plugin_name = PluginName(plugin_prefix_ , output_directive.name); - string parameters = output_directive.parameter; + std::string plugin_name = PluginName(plugin_prefix_, output_directive.name); + std::string parameters = output_directive.parameter; if (!plugin_parameters_[plugin_name].empty()) { if (!parameters.empty()) { parameters.append(","); } parameters.append(plugin_parameters_[plugin_name]); } - if (!GeneratePluginOutput(parsed_files, plugin_name, - parameters, + if (!GeneratePluginOutput(parsed_files, plugin_name, parameters, generator_context, &error)) { std::cerr << output_directive.name << ": " << error << std::endl; return false; } } else { // Regular generator. - string parameters = output_directive.parameter; + std::string parameters = output_directive.parameter; if (!generator_parameters_[output_directive.name].empty()) { if (!parameters.empty()) { parameters.append(","); } parameters.append(generator_parameters_[output_directive.name]); } - if (!output_directive.generator->GenerateAll( - parsed_files, parameters, generator_context, &error)) { + if (!output_directive.generator->GenerateAll(parsed_files, parameters, + generator_context, &error)) { // Generator returned an error. std::cerr << output_directive.name << ": " << error << std::endl; return false; @@ -1828,22 +1950,19 @@ bool CommandLineInterface::GenerateDependencyManifestFile( std::set already_seen; for (int i = 0; i < parsed_files.size(); i++) { - GetTransitiveDependencies(parsed_files[i], - false, - false, - &already_seen, + GetTransitiveDependencies(parsed_files[i], false, false, &already_seen, file_set.mutable_file()); } - std::vector output_filenames; + std::vector output_filenames; for (GeneratorContextMap::const_iterator iter = output_directories.begin(); iter != output_directories.end(); ++iter) { - const string& location = iter->first; + const std::string& location = iter->first; GeneratorContextImpl* directory = iter->second; - std::vector relative_output_filenames; + std::vector relative_output_filenames; directory->GetOutputFilenames(&relative_output_filenames); for (int i = 0; i < relative_output_filenames.size(); i++) { - string output_filename = location + relative_output_filenames[i]; + std::string output_filename = location + relative_output_filenames[i]; if (output_filename.compare(0, 2, "./") == 0) { output_filename = output_filename.substr(2); } @@ -1876,8 +1995,8 @@ bool CommandLineInterface::GenerateDependencyManifestFile( for (int i = 0; i < file_set.file_size(); i++) { const FileDescriptorProto& file = file_set.file(i); - const string& virtual_file = file.name(); - string disk_file; + const std::string& virtual_file = file.name(); + std::string disk_file; if (source_tree && source_tree->VirtualFileToDiskFile(virtual_file, &disk_file)) { printer.Print(" $disk_file$", "disk_file", disk_file); @@ -1894,13 +2013,11 @@ bool CommandLineInterface::GenerateDependencyManifestFile( bool CommandLineInterface::GeneratePluginOutput( const std::vector& parsed_files, - const string& plugin_name, - const string& parameter, - GeneratorContext* generator_context, - string* error) { + const std::string& plugin_name, const std::string& parameter, + GeneratorContext* generator_context, std::string* error) { CodeGeneratorRequest request; CodeGeneratorResponse response; - string processed_parameter = parameter; + std::string processed_parameter = parameter; // Build the request. @@ -1920,10 +2037,10 @@ bool CommandLineInterface::GeneratePluginOutput( google::protobuf::compiler::Version* version = request.mutable_compiler_version(); - version->set_major(GOOGLE_PROTOBUF_VERSION / 1000000); - version->set_minor(GOOGLE_PROTOBUF_VERSION / 1000 % 1000); - version->set_patch(GOOGLE_PROTOBUF_VERSION % 1000); - version->set_suffix(GOOGLE_PROTOBUF_VERSION_SUFFIX); + version->set_major(PROTOBUF_VERSION / 1000000); + version->set_minor(PROTOBUF_VERSION / 1000 % 1000); + version->set_patch(PROTOBUF_VERSION % 1000); + version->set_suffix(PROTOBUF_VERSION_SUFFIX); // Invoke the plugin. Subprocess subprocess; @@ -1934,7 +2051,7 @@ bool CommandLineInterface::GeneratePluginOutput( subprocess.Start(plugin_name, Subprocess::SEARCH_PATH); } - string communicate_error; + std::string communicate_error; if (!subprocess.Communicate(request, &response, &communicate_error)) { *error = strings::Substitute("$0: $1", plugin_name, communicate_error); return false; @@ -1947,7 +2064,7 @@ bool CommandLineInterface::GeneratePluginOutput( const CodeGeneratorResponse::File& output_file = response.file(i); if (!output_file.insertion_point().empty()) { - string filename = output_file.name(); + std::string filename = output_file.name(); // Open a file for insert. // We reset current_output to NULL first so that the old file is closed // before the new one is opened. @@ -1962,8 +2079,9 @@ bool CommandLineInterface::GeneratePluginOutput( current_output.reset(generator_context->Open(output_file.name())); } else if (current_output == NULL) { *error = strings::Substitute( - "$0: First file chunk returned by plugin did not specify a file name.", - plugin_name); + "$0: First file chunk returned by plugin did not specify a file " + "name.", + plugin_name); return false; } @@ -2072,8 +2190,8 @@ bool CommandLineInterface::WriteDescriptorSet( for (int i = 0; i < parsed_files.size(); i++) { GetTransitiveDependencies(parsed_files[i], true, // Include json_name - source_info_in_descriptor_set_, - &already_seen, file_set.mutable_file()); + source_info_in_descriptor_set_, &already_seen, + file_set.mutable_file()); } int fd; @@ -2104,8 +2222,7 @@ bool CommandLineInterface::WriteDescriptorSet( } void CommandLineInterface::GetTransitiveDependencies( - const FileDescriptor* file, - bool include_json_name, + const FileDescriptor* file, bool include_json_name, bool include_source_code_info, std::set* already_seen, RepeatedPtrField* output) { @@ -2116,10 +2233,8 @@ void CommandLineInterface::GetTransitiveDependencies( // Add all dependencies. for (int i = 0; i < file->dependency_count(); i++) { - GetTransitiveDependencies(file->dependency(i), - include_json_name, - include_source_code_info, - already_seen, output); + GetTransitiveDependencies(file->dependency(i), include_json_name, + include_source_code_info, already_seen, output); } // Add this file. @@ -2201,9 +2316,9 @@ void GatherOccupiedFieldRanges( // Utility function for PrintFreeFieldNumbers. // Actually prints the formatted free field numbers for given message name and // occupied ranges. -void FormatFreeFieldNumbers(const string& name, +void FormatFreeFieldNumbers(const std::string& name, const std::set& ranges) { - string output; + std::string output; StringAppendF(&output, "%-35s free:", name.c_str()); int next_free_number = 1; for (std::set::const_iterator i = ranges.begin(); @@ -2231,8 +2346,7 @@ void FormatFreeFieldNumbers(const string& name, } // namespace -void CommandLineInterface::PrintFreeFieldNumbers( - const Descriptor* descriptor) { +void CommandLineInterface::PrintFreeFieldNumbers(const Descriptor* descriptor) { std::set ranges; std::vector nested_messages; GatherOccupiedFieldRanges(descriptor, &ranges, &nested_messages); @@ -2244,7 +2358,6 @@ void CommandLineInterface::PrintFreeFieldNumbers( } - } // namespace compiler } // namespace protobuf } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/compiler/command_line_interface.h b/third_party/protobuf/src/google/protobuf/compiler/command_line_interface.h index 7d3037a9..6c9893fa 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/command_line_interface.h +++ b/third_party/protobuf/src/google/protobuf/compiler/command_line_interface.h @@ -38,24 +38,29 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_COMMAND_LINE_INTERFACE_H__ #define GOOGLE_PROTOBUF_COMPILER_COMMAND_LINE_INTERFACE_H__ -#include -#include -#include -#include #include #include +#include +#include #include +#include + +#include + +#include namespace google { namespace protobuf { -class Descriptor; // descriptor.h -class DescriptorPool; // descriptor.h -class FileDescriptor; // descriptor.h -class FileDescriptorSet; // descriptor.h -class FileDescriptorProto; // descriptor.pb.h -template class RepeatedPtrField; // repeated_field.h -class SimpleDescriptorDatabase; // descriptor_database.h +class Descriptor; // descriptor.h +class DescriptorDatabase; // descriptor_database.h +class DescriptorPool; // descriptor.h +class FileDescriptor; // descriptor.h +class FileDescriptorSet; // descriptor.h +class FileDescriptorProto; // descriptor.pb.h +template +class RepeatedPtrField; // repeated_field.h +class SimpleDescriptorDatabase; // descriptor_database.h namespace compiler { @@ -101,7 +106,7 @@ class DiskSourceTree; // importer.h // relative virtual path, the physical file path takes precendence. // // For a full description of the command-line syntax, invoke it with --help. -class LIBPROTOC_EXPORT CommandLineInterface { +class PROTOC_EXPORT CommandLineInterface { public: static const char* const kPathSeparator; @@ -124,9 +129,8 @@ class LIBPROTOC_EXPORT CommandLineInterface { // protoc --foo_out=enable_bar:outdir // The text before the colon is passed to CodeGenerator::Generate() as the // "parameter". - void RegisterGenerator(const string& flag_name, - CodeGenerator* generator, - const string& help_text); + void RegisterGenerator(const std::string& flag_name, CodeGenerator* generator, + const std::string& help_text); // Register a code generator for a language. // Besides flag_name you can specify another option_flag_name that could be @@ -136,10 +140,10 @@ class LIBPROTOC_EXPORT CommandLineInterface { // Then you could invoke the compiler with a command like: // protoc --foo_out=enable_bar:outdir --foo_opt=enable_baz // This will pass "enable_bar,enable_baz" as the parameter to the generator. - void RegisterGenerator(const string& flag_name, - const string& option_flag_name, + void RegisterGenerator(const std::string& flag_name, + const std::string& option_flag_name, CodeGenerator* generator, - const string& help_text); + const std::string& help_text); // Enables "plugins". In this mode, if a command-line flag ends with "_out" // but does not match any registered generator, the compiler will attempt to @@ -177,7 +181,7 @@ class LIBPROTOC_EXPORT CommandLineInterface { // protoc --plug_out=enable_bar:outdir --plug_opt=enable_baz // This will pass "enable_bar,enable_baz" as the parameter to the plugin. // - void AllowPlugins(const string& exe_name_prefix); + void AllowPlugins(const std::string& exe_name_prefix); // Run the Protocol Compiler with the given command-line parameters. // Returns the error code which should be returned by main(). @@ -195,9 +199,7 @@ class LIBPROTOC_EXPORT CommandLineInterface { // Provides some text which will be printed when the --version flag is // used. The version of libprotoc will also be printed on the next line // after this text. - void SetVersionInfo(const string& text) { - version_info_ = text; - } + void SetVersionInfo(const std::string& text) { version_info_ = text; } private: @@ -206,16 +208,23 @@ class LIBPROTOC_EXPORT CommandLineInterface { class ErrorPrinter; class GeneratorContextImpl; class MemoryOutputStream; - typedef hash_map GeneratorContextMap; + typedef std::unordered_map + GeneratorContextMap; // Clear state from previous Run(). void Clear(); + // Remaps the proto file so that it is relative to one of the directories + // in proto_path_. Returns false if an error occurred. + bool MakeProtoProtoPathRelative(DiskSourceTree* source_tree, + std::string* proto, + DescriptorDatabase* fallback_database); + // Remaps each file in input_files_ so that it is relative to one of the - // directories in proto_path_. Returns false if an error occurred. This - // is only used if inputs_are_proto_path_relative_ is false. - bool MakeInputsBeProtoPathRelative( - DiskSourceTree* source_tree); + // directories in proto_path_. Returns false if an error occurred. + bool MakeInputsBeProtoPathRelative(DiskSourceTree* source_tree, + DescriptorDatabase* fallback_database); + // Return status for ParseArguments() and InterpretArgument(). enum ParseArgumentStatus { @@ -229,7 +238,8 @@ class LIBPROTOC_EXPORT CommandLineInterface { // Read an argument file and append the file's content to the list of // arguments. Return false if the file cannot be read. - bool ExpandArgumentFile(const string& file, std::vector* arguments); + bool ExpandArgumentFile(const std::string& file, + std::vector* arguments); // Parses a command-line argument into a name/value pair. Returns // true if the next argument in the argv should be used as the value, @@ -242,17 +252,21 @@ class LIBPROTOC_EXPORT CommandLineInterface { // name = "--cpp_out", value = "src/foo.pb2.cc" // "foo.proto" -> // name = "", value = "foo.proto" - bool ParseArgument(const char* arg, string* name, string* value); + bool ParseArgument(const char* arg, std::string* name, std::string* value); // Interprets arguments parsed with ParseArgument. - ParseArgumentStatus InterpretArgument(const string& name, - const string& value); + ParseArgumentStatus InterpretArgument(const std::string& name, + const std::string& value); // Print the --help text to stderr. void PrintHelpText(); // Loads proto_path_ into the provided source_tree. - bool InitializeDiskSourceTree(DiskSourceTree* source_tree); + bool InitializeDiskSourceTree(DiskSourceTree* source_tree, + DescriptorDatabase* fallback_database); + + // Verify that all the input files exist in the given database. + bool VerifyInputFilesInDescriptors(DescriptorDatabase* fallback_database); // Loads descriptor_set_in into the provided database bool PopulateSimpleDescriptorDatabase(SimpleDescriptorDatabase* database); @@ -268,8 +282,8 @@ class LIBPROTOC_EXPORT CommandLineInterface { GeneratorContext* generator_context); bool GeneratePluginOutput( const std::vector& parsed_files, - const string& plugin_name, const string& parameter, - GeneratorContext* generator_context, string* error); + const std::string& plugin_name, const std::string& parameter, + GeneratorContext* generator_context, std::string* error); // Implements --encode and --decode. bool EncodeOrDecode(const DescriptorPool* pool); @@ -294,8 +308,7 @@ class LIBPROTOC_EXPORT CommandLineInterface { // If include_json_name is true, populate the json_name field of // FieldDescriptorProto for all fields. static void GetTransitiveDependencies( - const FileDescriptor* file, - bool include_json_name, + const FileDescriptor* file, bool include_json_name, bool include_source_code_info, std::set* already_seen, RepeatedPtrField* output); @@ -319,36 +332,36 @@ class LIBPROTOC_EXPORT CommandLineInterface { // ----------------------------------------------------------------- // The name of the executable as invoked (i.e. argv[0]). - string executable_name_; + std::string executable_name_; // Version info set with SetVersionInfo(). - string version_info_; + std::string version_info_; // Registered generators. struct GeneratorInfo { - string flag_name; - string option_flag_name; + std::string flag_name; + std::string option_flag_name; CodeGenerator* generator; - string help_text; + std::string help_text; }; - typedef std::map GeneratorMap; + typedef std::map GeneratorMap; GeneratorMap generators_by_flag_name_; GeneratorMap generators_by_option_name_; // A map from generator names to the parameters specified using the option // flag. For example, if the user invokes the compiler with: // protoc --foo_out=outputdir --foo_opt=enable_bar ... // Then there will be an entry ("--foo_out", "enable_bar") in this map. - std::map generator_parameters_; + std::map generator_parameters_; // Similar to generator_parameters_, but stores the parameters for plugins. - std::map plugin_parameters_; + std::map plugin_parameters_; // See AllowPlugins(). If this is empty, plugins aren't allowed. - string plugin_prefix_; + std::string plugin_prefix_; // Maps specific plugin names to files. When executing a plugin, this map // is searched first to find the plugin executable. If not found here, the // PATH (or other OS-specific search strategy) is searched. - std::map plugins_; + std::map plugins_; // Stuff parsed from command line. enum Mode { @@ -361,57 +374,57 @@ class LIBPROTOC_EXPORT CommandLineInterface { Mode mode_; enum PrintMode { - PRINT_NONE, // Not in MODE_PRINT - PRINT_FREE_FIELDS, // --print_free_fields + PRINT_NONE, // Not in MODE_PRINT + PRINT_FREE_FIELDS, // --print_free_fields }; PrintMode print_mode_; enum ErrorFormat { - ERROR_FORMAT_GCC, // GCC error output format (default). - ERROR_FORMAT_MSVS // Visual Studio output (--error_format=msvs). + ERROR_FORMAT_GCC, // GCC error output format (default). + ERROR_FORMAT_MSVS // Visual Studio output (--error_format=msvs). }; ErrorFormat error_format_; - std::vector > - proto_path_; // Search path for proto files. - std::vector input_files_; // Names of the input proto files. + std::vector > + proto_path_; // Search path for proto files. + std::vector input_files_; // Names of the input proto files. // Names of proto files which are allowed to be imported. Used by build // systems to enforce depend-on-what-you-import. - std::set direct_dependencies_; + std::set direct_dependencies_; bool direct_dependencies_explicitly_set_; // If there's a violation of depend-on-what-you-import, this string will be // presented to the user. "%s" will be replaced with the violating import. - string direct_dependencies_violation_msg_; + std::string direct_dependencies_violation_msg_; // output_directives_ lists all the files we are supposed to output and what // generator to use for each. struct OutputDirective { - string name; // E.g. "--foo_out" - CodeGenerator* generator; // NULL for plugins - string parameter; - string output_location; + std::string name; // E.g. "--foo_out" + CodeGenerator* generator; // NULL for plugins + std::string parameter; + std::string output_location; }; std::vector output_directives_; // When using --encode or --decode, this names the type we are encoding or // decoding. (Empty string indicates --decode_raw.) - string codec_type_; + std::string codec_type_; // If --descriptor_set_in was given, these are filenames containing // parsed FileDescriptorSets to be used for loading protos. Otherwise, empty. - std::vector descriptor_set_in_names_; + std::vector descriptor_set_in_names_; // If --descriptor_set_out was given, this is the filename to which the // FileDescriptorSet should be written. Otherwise, empty. - string descriptor_set_out_name_; + std::string descriptor_set_out_name_; // If --dependency_out was given, this is the path to the file where the // dependency file will be written. Otherwise, empty. - string dependency_out_name_; + std::string dependency_out_name_; // True if --include_imports was given, meaning that we should // write all transitive dependencies to the DescriptorSet. Otherwise, only @@ -430,6 +443,8 @@ class LIBPROTOC_EXPORT CommandLineInterface { } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_COMMAND_LINE_INTERFACE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/command_line_interface_unittest.cc b/third_party/protobuf/src/google/protobuf/compiler/command_line_interface_unittest.cc index 41eb244a..6ab5aff2 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/command_line_interface_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/command_line_interface_unittest.cc @@ -49,7 +49,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -61,7 +63,6 @@ #include #include -#include namespace google { namespace protobuf { @@ -70,12 +71,12 @@ namespace compiler { #if defined(_WIN32) // DO NOT include , instead create functions in io_win32.{h,cc} and import // them like we do below. -using google::protobuf::internal::win32::access; -using google::protobuf::internal::win32::dup; -using google::protobuf::internal::win32::dup2; -using google::protobuf::internal::win32::close; -using google::protobuf::internal::win32::open; -using google::protobuf::internal::win32::write; +using google::protobuf::io::win32::access; +using google::protobuf::io::win32::close; +using google::protobuf::io::win32::dup; +using google::protobuf::io::win32::dup2; +using google::protobuf::io::win32::open; +using google::protobuf::io::win32::write; #endif // Disable the whole test when we use tcmalloc for "draconian" heap checks, in @@ -85,7 +86,7 @@ using google::protobuf::internal::win32::write; namespace { -bool FileExists(const string& path) { +bool FileExists(const std::string& path) { return File::Exists(path); } @@ -97,8 +98,8 @@ class CommandLineInterfaceTest : public testing::Test { // Runs the CommandLineInterface with the given command line. The // command is automatically split on spaces, and the string "$tmpdir" // is replaced with TestTempDir(). - void Run(const string& command); - void RunWithArgs(std::vector args); + void Run(const std::string& command); + void RunWithArgs(std::vector args); // ----------------------------------------------------------------- // Methods to set up the test (called before Run()). @@ -111,17 +112,17 @@ class CommandLineInterfaceTest : public testing::Test { // Create a temp file within temp_directory_ with the given name. // The containing directory is also created if necessary. - void CreateTempFile(const string& name, const string& contents); + void CreateTempFile(const std::string& name, const std::string& contents); // Create a subdirectory within temp_directory_. - void CreateTempDir(const string& name); + void CreateTempDir(const std::string& name); #ifdef PROTOBUF_OPENSOURCE // Change working directory to temp directory. void SwitchToTempDirectory() { File::ChangeWorkingDirectory(temp_directory_); } -#else // !PROTOBUF_OPENSOURCE +#else // !PROTOBUF_OPENSOURCE // TODO(teboring): Figure out how to change and get working directory in // google3. #endif // !PROTOBUF_OPENSOURCE @@ -136,27 +137,25 @@ class CommandLineInterfaceTest : public testing::Test { // Checks that Run() returned non-zero and the stderr output is exactly // the text given. expected_test may contain references to "$tmpdir", // which will be replaced by the temporary directory path. - void ExpectErrorText(const string& expected_text); + void ExpectErrorText(const std::string& expected_text); // Checks that Run() returned non-zero and the stderr contains the given // substring. - void ExpectErrorSubstring(const string& expected_substring); - - // Like ExpectErrorSubstring, but checks that Run() returned zero. - void ExpectErrorSubstringWithZeroReturnCode( - const string& expected_substring); + void ExpectErrorSubstring(const std::string& expected_substring); // Checks that the captured stdout is the same as the expected_text. - void ExpectCapturedStdout(const string& expected_text); + void ExpectCapturedStdout(const std::string& expected_text); // Checks that Run() returned zero and the stdout contains the given // substring. void ExpectCapturedStdoutSubstringWithZeroReturnCode( - const string& expected_substring); + const std::string& expected_substring); +#if defined(_WIN32) && !defined(__CYGWIN__) // Returns true if ExpectErrorSubstring(expected_substring) would pass, but // does not fail otherwise. - bool HasAlternateErrorSubstring(const string& expected_substring); + bool HasAlternateErrorSubstring(const std::string& expected_substring); +#endif // _WIN32 && !__CYGWIN__ // Checks that MockCodeGenerator::Generate() was called in the given // context (or the generator in test_plugin.cc, which produces the same @@ -167,37 +166,40 @@ class CommandLineInterfaceTest : public testing::Test { // generate given these inputs. message_name is the name of the first // message that appeared in the proto file; this is just to make extra // sure that the correct file was parsed. - void ExpectGenerated(const string& generator_name, - const string& parameter, - const string& proto_name, - const string& message_name); - void ExpectGenerated(const string& generator_name, - const string& parameter, - const string& proto_name, - const string& message_name, - const string& output_directory); - void ExpectGeneratedWithMultipleInputs(const string& generator_name, - const string& all_proto_names, - const string& proto_name, - const string& message_name); - void ExpectGeneratedWithInsertions(const string& generator_name, - const string& parameter, - const string& insertions, - const string& proto_name, - const string& message_name); - void CheckGeneratedAnnotations(const string& name, const string& file); + void ExpectGenerated(const std::string& generator_name, + const std::string& parameter, + const std::string& proto_name, + const std::string& message_name); + void ExpectGenerated(const std::string& generator_name, + const std::string& parameter, + const std::string& proto_name, + const std::string& message_name, + const std::string& output_directory); + void ExpectGeneratedWithMultipleInputs(const std::string& generator_name, + const std::string& all_proto_names, + const std::string& proto_name, + const std::string& message_name); + void ExpectGeneratedWithInsertions(const std::string& generator_name, + const std::string& parameter, + const std::string& insertions, + const std::string& proto_name, + const std::string& message_name); + void CheckGeneratedAnnotations(const std::string& name, + const std::string& file); - void ExpectNullCodeGeneratorCalled(const string& parameter); +#if defined(_WIN32) + void ExpectNullCodeGeneratorCalled(const std::string& parameter); +#endif // _WIN32 - void ReadDescriptorSet(const string& filename, + void ReadDescriptorSet(const std::string& filename, FileDescriptorSet* descriptor_set); - void WriteDescriptorSet(const string& filename, + void WriteDescriptorSet(const std::string& filename, const FileDescriptorSet* descriptor_set); - void ExpectFileContent(const string& filename, - const string& content); + void ExpectFileContent(const std::string& filename, + const std::string& content); private: // The object we are testing. @@ -210,16 +212,16 @@ class CommandLineInterfaceTest : public testing::Test { // protection against accidentally deleting user files (since we recursively // delete this directory during the test). This is the full path of that // directory. - string temp_directory_; + std::string temp_directory_; // The result of Run(). int return_code_; // The captured stderr output. - string error_text_; + std::string error_text_; // The captured stdout. - string captured_stdout_; + std::string captured_stdout_; // Pointers which need to be deleted later. std::vector mock_generators_to_delete_; @@ -233,13 +235,11 @@ class CommandLineInterfaceTest::NullCodeGenerator : public CodeGenerator { ~NullCodeGenerator() {} mutable bool called_; - mutable string parameter_; + mutable std::string parameter_; // implements CodeGenerator ---------------------------------------- - bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const { + bool Generate(const FileDescriptor* file, const std::string& parameter, + GeneratorContext* context, std::string* error) const { called_ = true; parameter_ = parameter; return true; @@ -291,34 +291,36 @@ void CommandLineInterfaceTest::TearDown() { mock_generators_to_delete_.clear(); } -void CommandLineInterfaceTest::Run(const string& command) { +void CommandLineInterfaceTest::Run(const std::string& command) { RunWithArgs(Split(command, " ", true)); } -void CommandLineInterfaceTest::RunWithArgs(std::vector args) { +void CommandLineInterfaceTest::RunWithArgs(std::vector args) { if (!disallow_plugins_) { cli_.AllowPlugins("prefix-"); -#ifndef GOOGLE_THIRD_PARTY_PROTOBUF - string plugin_path; + std::string plugin_path; #ifdef GOOGLE_PROTOBUF_TEST_PLUGIN_PATH plugin_path = GOOGLE_PROTOBUF_TEST_PLUGIN_PATH; #else const char* possible_paths[] = { - // When building with shared libraries, libtool hides the real executable - // in .libs and puts a fake wrapper in the current directory. - // Unfortunately, due to an apparent bug on Cygwin/MinGW, if one program - // wrapped in this way (e.g. protobuf-tests.exe) tries to execute another - // program wrapped in this way (e.g. test_plugin.exe), the latter fails - // with error code 127 and no explanation message. Presumably the problem - // is that the wrapper for protobuf-tests.exe set some environment - // variables that confuse the wrapper for test_plugin.exe. Luckily, it - // turns out that if we simply invoke the wrapped test_plugin.exe - // directly, it works -- I guess the environment variables set by the - // protobuf-tests.exe wrapper happen to be correct for it too. So we do - // that. - ".libs/test_plugin.exe", // Win32 w/autotool (Cygwin / MinGW) - "test_plugin.exe", // Other Win32 (MSVC) - "test_plugin", // Unix + // When building with shared libraries, libtool hides the real + // executable + // in .libs and puts a fake wrapper in the current directory. + // Unfortunately, due to an apparent bug on Cygwin/MinGW, if one program + // wrapped in this way (e.g. protobuf-tests.exe) tries to execute + // another + // program wrapped in this way (e.g. test_plugin.exe), the latter fails + // with error code 127 and no explanation message. Presumably the + // problem + // is that the wrapper for protobuf-tests.exe set some environment + // variables that confuse the wrapper for test_plugin.exe. Luckily, it + // turns out that if we simply invoke the wrapped test_plugin.exe + // directly, it works -- I guess the environment variables set by the + // protobuf-tests.exe wrapper happen to be correct for it too. So we do + // that. + ".libs/test_plugin.exe", // Win32 w/autotool (Cygwin / MinGW) + "test_plugin.exe", // Other Win32 (MSVC) + "test_plugin", // Unix }; for (int i = 0; i < GOOGLE_ARRAYSIZE(possible_paths); i++) { if (access(possible_paths[i], F_OK) == 0) { @@ -329,11 +331,6 @@ void CommandLineInterfaceTest::RunWithArgs(std::vector args) { #endif if (plugin_path.empty()) { -#else - string plugin_path = "third_party/protobuf/test_plugin"; - - if (access(plugin_path.c_str(), F_OK) != 0) { -#endif // GOOGLE_THIRD_PARTY_PROTOBUF GOOGLE_LOG(ERROR) << "Plugin executable not found. Plugin tests are likely to fail."; } else { @@ -341,7 +338,7 @@ void CommandLineInterfaceTest::RunWithArgs(std::vector args) { } } - std::unique_ptr argv(new const char* [args.size()]); + std::unique_ptr argv(new const char*[args.size()]); for (int i = 0; i < args.size(); i++) { args[i] = StringReplace(args[i], "$tmpdir", temp_directory_, true); @@ -366,13 +363,12 @@ void CommandLineInterfaceTest::RunWithArgs(std::vector args) { // ------------------------------------------------------------------- -void CommandLineInterfaceTest::CreateTempFile( - const string& name, - const string& contents) { +void CommandLineInterfaceTest::CreateTempFile(const std::string& name, + const std::string& contents) { // Create parent directory, if necessary. - string::size_type slash_pos = name.find_last_of('/'); - if (slash_pos != string::npos) { - string dir = name.substr(0, slash_pos); + std::string::size_type slash_pos = name.find_last_of('/'); + if (slash_pos != std::string::npos) { + std::string dir = name.substr(0, slash_pos); if (!FileExists(temp_directory_ + "/" + dir)) { GOOGLE_CHECK_OK(File::RecursivelyCreateDir(temp_directory_ + "/" + dir, 0777)); @@ -380,13 +376,13 @@ void CommandLineInterfaceTest::CreateTempFile( } // Write file. - string full_name = temp_directory_ + "/" + name; + std::string full_name = temp_directory_ + "/" + name; GOOGLE_CHECK_OK(File::SetContents( full_name, StringReplace(contents, "$tmpdir", temp_directory_, true), true)); } -void CommandLineInterfaceTest::CreateTempDir(const string& name) { +void CommandLineInterfaceTest::CreateTempDir(const std::string& name) { GOOGLE_CHECK_OK(File::RecursivelyCreateDir(temp_directory_ + "/" + name, 0777)); } @@ -398,89 +394,78 @@ void CommandLineInterfaceTest::ExpectNoErrors() { EXPECT_EQ("", error_text_); } -void CommandLineInterfaceTest::ExpectErrorText(const string& expected_text) { +void CommandLineInterfaceTest::ExpectErrorText( + const std::string& expected_text) { EXPECT_NE(0, return_code_); EXPECT_EQ(StringReplace(expected_text, "$tmpdir", temp_directory_, true), error_text_); } void CommandLineInterfaceTest::ExpectErrorSubstring( - const string& expected_substring) { + const std::string& expected_substring) { EXPECT_NE(0, return_code_); EXPECT_PRED_FORMAT2(testing::IsSubstring, expected_substring, error_text_); } -void CommandLineInterfaceTest::ExpectErrorSubstringWithZeroReturnCode( - const string& expected_substring) { - EXPECT_EQ(0, return_code_); - EXPECT_PRED_FORMAT2(testing::IsSubstring, expected_substring, error_text_); -} - +#if defined(_WIN32) && !defined(__CYGWIN__) bool CommandLineInterfaceTest::HasAlternateErrorSubstring( - const string& expected_substring) { + const std::string& expected_substring) { EXPECT_NE(0, return_code_); - return error_text_.find(expected_substring) != string::npos; + return error_text_.find(expected_substring) != std::string::npos; +} +#endif // _WIN32 && !__CYGWIN__ + +void CommandLineInterfaceTest::ExpectGenerated( + const std::string& generator_name, const std::string& parameter, + const std::string& proto_name, const std::string& message_name) { + MockCodeGenerator::ExpectGenerated(generator_name, parameter, "", proto_name, + message_name, proto_name, temp_directory_); } void CommandLineInterfaceTest::ExpectGenerated( - const string& generator_name, - const string& parameter, - const string& proto_name, - const string& message_name) { - MockCodeGenerator::ExpectGenerated( - generator_name, parameter, "", proto_name, message_name, proto_name, - temp_directory_); -} - -void CommandLineInterfaceTest::ExpectGenerated( - const string& generator_name, - const string& parameter, - const string& proto_name, - const string& message_name, - const string& output_directory) { - MockCodeGenerator::ExpectGenerated( - generator_name, parameter, "", proto_name, message_name, proto_name, - temp_directory_ + "/" + output_directory); + const std::string& generator_name, const std::string& parameter, + const std::string& proto_name, const std::string& message_name, + const std::string& output_directory) { + MockCodeGenerator::ExpectGenerated(generator_name, parameter, "", proto_name, + message_name, proto_name, + temp_directory_ + "/" + output_directory); } void CommandLineInterfaceTest::ExpectGeneratedWithMultipleInputs( - const string& generator_name, - const string& all_proto_names, - const string& proto_name, - const string& message_name) { - MockCodeGenerator::ExpectGenerated( - generator_name, "", "", proto_name, message_name, - all_proto_names, - temp_directory_); + const std::string& generator_name, const std::string& all_proto_names, + const std::string& proto_name, const std::string& message_name) { + MockCodeGenerator::ExpectGenerated(generator_name, "", "", proto_name, + message_name, all_proto_names, + temp_directory_); } void CommandLineInterfaceTest::ExpectGeneratedWithInsertions( - const string& generator_name, - const string& parameter, - const string& insertions, - const string& proto_name, - const string& message_name) { - MockCodeGenerator::ExpectGenerated( - generator_name, parameter, insertions, proto_name, message_name, - proto_name, temp_directory_); + const std::string& generator_name, const std::string& parameter, + const std::string& insertions, const std::string& proto_name, + const std::string& message_name) { + MockCodeGenerator::ExpectGenerated(generator_name, parameter, insertions, + proto_name, message_name, proto_name, + temp_directory_); } -void CommandLineInterfaceTest::CheckGeneratedAnnotations(const string& name, - const string& file) { +void CommandLineInterfaceTest::CheckGeneratedAnnotations( + const std::string& name, const std::string& file) { MockCodeGenerator::CheckGeneratedAnnotations(name, file, temp_directory_); } +#if defined(_WIN32) void CommandLineInterfaceTest::ExpectNullCodeGeneratorCalled( - const string& parameter) { + const std::string& parameter) { EXPECT_TRUE(null_generator_->called_); EXPECT_EQ(parameter, null_generator_->parameter_); } +#endif // _WIN32 void CommandLineInterfaceTest::ReadDescriptorSet( - const string& filename, FileDescriptorSet* descriptor_set) { - string path = temp_directory_ + "/" + filename; - string file_contents; + const std::string& filename, FileDescriptorSet* descriptor_set) { + std::string path = temp_directory_ + "/" + filename; + std::string file_contents; GOOGLE_CHECK_OK(File::GetContents(path, &file_contents, true)); if (!descriptor_set->ParseFromString(file_contents)) { @@ -489,28 +474,28 @@ void CommandLineInterfaceTest::ReadDescriptorSet( } void CommandLineInterfaceTest::WriteDescriptorSet( - const string& filename, const FileDescriptorSet* descriptor_set) { - string binary_proto; + const std::string& filename, const FileDescriptorSet* descriptor_set) { + std::string binary_proto; GOOGLE_CHECK(descriptor_set->SerializeToString(&binary_proto)); CreateTempFile(filename, binary_proto); } void CommandLineInterfaceTest::ExpectCapturedStdout( - const string& expected_text) { + const std::string& expected_text) { EXPECT_EQ(expected_text, captured_stdout_); } void CommandLineInterfaceTest::ExpectCapturedStdoutSubstringWithZeroReturnCode( - const string& expected_substring) { + const std::string& expected_substring) { EXPECT_EQ(0, return_code_); - EXPECT_PRED_FORMAT2( - testing::IsSubstring, expected_substring, captured_stdout_); + EXPECT_PRED_FORMAT2(testing::IsSubstring, expected_substring, + captured_stdout_); } -void CommandLineInterfaceTest::ExpectFileContent( - const string& filename, const string& content) { - string path = temp_directory_ + "/" + filename; - string file_contents; +void CommandLineInterfaceTest::ExpectFileContent(const std::string& filename, + const std::string& content) { + std::string path = temp_directory_ + "/" + filename; + std::string file_contents; GOOGLE_CHECK_OK(File::GetContents(path, &file_contents, true)); EXPECT_EQ(StringReplace(content, "$tmpdir", temp_directory_, true), @@ -523,8 +508,8 @@ TEST_F(CommandLineInterfaceTest, BasicOutput) { // Test that the common case works. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); @@ -553,8 +538,8 @@ TEST_F(CommandLineInterfaceTest, BasicPlugin) { // Test that basic plugins work. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler --plug_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); @@ -584,8 +569,8 @@ TEST_F(CommandLineInterfaceTest, GeneratorAndPlugin) { // Invoke a generator and a plugin at the same time. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler --test_out=$tmpdir --plug_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); @@ -617,11 +602,11 @@ TEST_F(CommandLineInterfaceTest, MultipleInputs) { // Test parsing multiple input files. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "message Bar {}\n"); + "syntax = \"proto2\";\n" + "message Bar {}\n"); Run("protocol_compiler --test_out=$tmpdir --plug_out=$tmpdir " "--proto_path=$tmpdir foo.proto bar.proto"); @@ -669,17 +654,17 @@ TEST_F(CommandLineInterfaceTest, MultipleInputsWithImport) { // Test parsing multiple input files with an import of a separate file. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"baz.proto\";\n" - "message Bar {\n" - " optional Baz a = 1;\n" - "}\n"); + "syntax = \"proto2\";\n" + "import \"baz.proto\";\n" + "message Bar {\n" + " optional Baz a = 1;\n" + "}\n"); CreateTempFile("baz.proto", - "syntax = \"proto2\";\n" - "message Baz {}\n"); + "syntax = \"proto2\";\n" + "message Baz {}\n"); Run("protocol_compiler --test_out=$tmpdir --plug_out=$tmpdir " "--proto_path=$tmpdir foo.proto bar.proto"); @@ -734,9 +719,8 @@ TEST_F(CommandLineInterfaceTest, MultipleInputsWithImport_DescriptorSetIn) { Run(strings::Substitute( "protocol_compiler --test_out=$$tmpdir --plug_out=$$tmpdir " "--descriptor_set_in=$0 foo.proto bar.proto", - string("$tmpdir/foo_and_bar.bin") + - CommandLineInterface::kPathSeparator + - "$tmpdir/baz_and_bat.bin")); + std::string("$tmpdir/foo_and_bar.bin") + + CommandLineInterface::kPathSeparator + "$tmpdir/baz_and_bat.bin")); ExpectNoErrors(); ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto", @@ -751,9 +735,8 @@ TEST_F(CommandLineInterfaceTest, MultipleInputsWithImport_DescriptorSetIn) { Run(strings::Substitute( "protocol_compiler --test_out=$$tmpdir --plug_out=$$tmpdir " "--descriptor_set_in=$0 baz.proto bat.proto", - string("$tmpdir/foo_and_bar.bin") + - CommandLineInterface::kPathSeparator + - "$tmpdir/baz_and_bat.bin")); + std::string("$tmpdir/foo_and_bar.bin") + + CommandLineInterface::kPathSeparator + "$tmpdir/baz_and_bat.bin")); ExpectNoErrors(); ExpectGeneratedWithMultipleInputs("test_generator", "baz.proto,bat.proto", @@ -810,9 +793,8 @@ TEST_F(CommandLineInterfaceTest, Run(strings::Substitute( "protocol_compiler --test_out=$$tmpdir --plug_out=$$tmpdir " "--descriptor_set_in=$0 bar.proto", - string("$tmpdir/foo_and_bar.bin") + - CommandLineInterface::kPathSeparator + - "$tmpdir/foo_and_baz.bin")); + std::string("$tmpdir/foo_and_bar.bin") + + CommandLineInterface::kPathSeparator + "$tmpdir/foo_and_baz.bin")); ExpectNoErrors(); ExpectGenerated("test_generator", "", "bar.proto", "Bar"); @@ -858,8 +840,8 @@ TEST_F(CommandLineInterfaceTest, CreateDirectory) { // Test that when we output to a sub-directory, it is created. CreateTempFile("bar/baz/foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); CreateTempDir("out"); CreateTempDir("plugout"); @@ -875,8 +857,8 @@ TEST_F(CommandLineInterfaceTest, GeneratorParameters) { // Test that generator parameters are correctly parsed from the command line. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler --test_out=TestParameter:$tmpdir " "--plug_out=TestPluginParameter:$tmpdir " @@ -892,8 +874,8 @@ TEST_F(CommandLineInterfaceTest, ExtraGeneratorParameters) { // correctly passed to the code generator. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); // Create the "a" and "b" sub-directories. CreateTempDir("a"); CreateTempDir("b"); @@ -907,10 +889,10 @@ TEST_F(CommandLineInterfaceTest, ExtraGeneratorParameters) { "--proto_path=$tmpdir foo.proto"); ExpectNoErrors(); - ExpectGenerated( - "test_generator", "bar,foo1,foo2,foo3", "foo.proto", "Foo", "a"); - ExpectGenerated( - "test_generator", "baz,foo1,foo2,foo3", "foo.proto", "Foo", "b"); + ExpectGenerated("test_generator", "bar,foo1,foo2,foo3", "foo.proto", "Foo", + "a"); + ExpectGenerated("test_generator", "baz,foo1,foo2,foo3", "foo.proto", "Foo", + "b"); } TEST_F(CommandLineInterfaceTest, ExtraPluginParameters) { @@ -918,8 +900,8 @@ TEST_F(CommandLineInterfaceTest, ExtraPluginParameters) { // correctly passed to the code generator. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); // Create the "a" and "b" sub-directories. CreateTempDir("a"); CreateTempDir("b"); @@ -933,16 +915,14 @@ TEST_F(CommandLineInterfaceTest, ExtraPluginParameters) { "--proto_path=$tmpdir foo.proto"); ExpectNoErrors(); - ExpectGenerated( - "test_plugin", "bar,foo1,foo2,foo3", "foo.proto", "Foo", "a"); - ExpectGenerated( - "test_plugin", "baz,foo1,foo2,foo3", "foo.proto", "Foo", "b"); + ExpectGenerated("test_plugin", "bar,foo1,foo2,foo3", "foo.proto", "Foo", "a"); + ExpectGenerated("test_plugin", "baz,foo1,foo2,foo3", "foo.proto", "Foo", "b"); } TEST_F(CommandLineInterfaceTest, UnrecognizedExtraParameters) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler --plug_out=TestParameter:$tmpdir " "--unknown_plug_a_opt=Foo " @@ -965,8 +945,8 @@ TEST_F(CommandLineInterfaceTest, ExtraPluginParametersForOutParameters) { // directives appear, they both are reported. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler --plug_out=TestParameter:$tmpdir " "--xyz_opt=foo=bar --xyz_out=$tmpdir " @@ -981,8 +961,8 @@ TEST_F(CommandLineInterfaceTest, Insert) { // Test running a generator that inserts code into another's output. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler " "--test_out=TestParameter:$tmpdir " @@ -992,12 +972,12 @@ TEST_F(CommandLineInterfaceTest, Insert) { "--proto_path=$tmpdir foo.proto"); ExpectNoErrors(); - ExpectGeneratedWithInsertions( - "test_generator", "TestParameter", "test_generator,test_plugin", - "foo.proto", "Foo"); - ExpectGeneratedWithInsertions( - "test_plugin", "TestPluginParameter", "test_generator,test_plugin", - "foo.proto", "Foo"); + ExpectGeneratedWithInsertions("test_generator", "TestParameter", + "test_generator,test_plugin", "foo.proto", + "Foo"); + ExpectGeneratedWithInsertions("test_plugin", "TestPluginParameter", + "test_generator,test_plugin", "foo.proto", + "Foo"); } TEST_F(CommandLineInterfaceTest, InsertWithAnnotationFixup) { @@ -1024,8 +1004,7 @@ TEST_F(CommandLineInterfaceTest, InsertWithAnnotationFixup) { TEST_F(CommandLineInterfaceTest, WindowsOutputPath) { // Test that the output path can be a Windows-style path. - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n"); + CreateTempFile("foo.proto", "syntax = \"proto2\";\n"); Run("protocol_compiler --null_out=C:\\ " "--proto_path=$tmpdir foo.proto"); @@ -1037,8 +1016,7 @@ TEST_F(CommandLineInterfaceTest, WindowsOutputPath) { TEST_F(CommandLineInterfaceTest, WindowsOutputPathAndParameter) { // Test that we can have a windows-style output path and a parameter. - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n"); + CreateTempFile("foo.proto", "syntax = \"proto2\";\n"); Run("protocol_compiler --null_out=bar:C:\\ " "--proto_path=$tmpdir foo.proto"); @@ -1052,8 +1030,8 @@ TEST_F(CommandLineInterfaceTest, TrailingBackslash) { // doesn't work on their system. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler --test_out=$tmpdir\\ " "--proto_path=$tmpdir\\ foo.proto"); @@ -1073,14 +1051,14 @@ TEST_F(CommandLineInterfaceTest, PathLookup) { // Test that specifying multiple directories in the proto search path works. CreateTempFile("b/bar.proto", - "syntax = \"proto2\";\n" - "message Bar {}\n"); + "syntax = \"proto2\";\n" + "message Bar {}\n"); CreateTempFile("a/foo.proto", - "syntax = \"proto2\";\n" - "import \"bar.proto\";\n" - "message Foo {\n" - " optional Bar a = 1;\n" - "}\n"); + "syntax = \"proto2\";\n" + "import \"bar.proto\";\n" + "message Foo {\n" + " optional Bar a = 1;\n" + "}\n"); CreateTempFile("b/foo.proto", "this should not be parsed\n"); Run("protocol_compiler --test_out=$tmpdir " @@ -1094,21 +1072,20 @@ TEST_F(CommandLineInterfaceTest, ColonDelimitedPath) { // Same as PathLookup, but we provide the proto_path in a single flag. CreateTempFile("b/bar.proto", - "syntax = \"proto2\";\n" - "message Bar {}\n"); + "syntax = \"proto2\";\n" + "message Bar {}\n"); CreateTempFile("a/foo.proto", - "syntax = \"proto2\";\n" - "import \"bar.proto\";\n" - "message Foo {\n" - " optional Bar a = 1;\n" - "}\n"); + "syntax = \"proto2\";\n" + "import \"bar.proto\";\n" + "message Foo {\n" + " optional Bar a = 1;\n" + "}\n"); CreateTempFile("b/foo.proto", "this should not be parsed\n"); Run(strings::Substitute( "protocol_compiler --test_out=$$tmpdir --proto_path=$0 foo.proto", - string("$tmpdir/a") + - CommandLineInterface::kPathSeparator + - "$tmpdir/b")); + std::string("$tmpdir/a") + CommandLineInterface::kPathSeparator + + "$tmpdir/b")); ExpectNoErrors(); ExpectGenerated("test_generator", "", "foo.proto", "Foo"); @@ -1118,8 +1095,8 @@ TEST_F(CommandLineInterfaceTest, NonRootMapping) { // Test setting up a search path mapping a directory to a non-root location. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=bar=$tmpdir bar/foo.proto"); @@ -1133,8 +1110,8 @@ TEST_F(CommandLineInterfaceTest, PathWithEqualsSign) { CreateTempDir("with=sign"); CreateTempFile("with=sign/foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir/with=sign foo.proto"); @@ -1148,8 +1125,8 @@ TEST_F(CommandLineInterfaceTest, MultipleGenerators) { // each with a different output directory. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); // Create the "a" and "b" sub-directories. CreateTempDir("a"); CreateTempDir("b"); @@ -1169,8 +1146,8 @@ TEST_F(CommandLineInterfaceTest, DisallowServicesNoServices) { // services. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler --disallow_services --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); @@ -1183,9 +1160,9 @@ TEST_F(CommandLineInterfaceTest, DisallowServicesHasService) { // Test that --disallow_services produces an error when there are services. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n" - "service Bar {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n" + "service Bar {}\n"); Run("protocol_compiler --disallow_services --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); @@ -1197,9 +1174,9 @@ TEST_F(CommandLineInterfaceTest, AllowServicesHasService) { // Test that services work fine as long as --disallow_services is not used. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n" - "service Bar {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n" + "service Bar {}\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); @@ -1281,8 +1258,7 @@ TEST_F(CommandLineInterfaceTest, DirectDependencies_NoViolation_MultiImports) { } TEST_F(CommandLineInterfaceTest, DirectDependencies_ProvidedMultipleTimes) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n"); + CreateTempFile("foo.proto", "syntax = \"proto2\";\n"); Run("protocol_compiler --test_out=$tmpdir --proto_path=$tmpdir " "--direct_dependencies=bar.proto --direct_dependencies=bla.proto " @@ -1303,7 +1279,7 @@ TEST_F(CommandLineInterfaceTest, DirectDependencies_CustomErrorMessage) { "syntax = \"proto2\";\n" "message Bar { optional string text = 1; }"); - std::vector commands; + std::vector commands; commands.push_back("protocol_compiler"); commands.push_back("--test_out=$tmpdir"); commands.push_back("--proto_path=$tmpdir"); @@ -1319,8 +1295,8 @@ TEST_F(CommandLineInterfaceTest, CwdRelativeInputs) { // Test that we can accept working-directory-relative input files. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir $tmpdir/foo.proto"); @@ -1331,14 +1307,14 @@ TEST_F(CommandLineInterfaceTest, CwdRelativeInputs) { TEST_F(CommandLineInterfaceTest, WriteDescriptorSet) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Bar {\n" - " optional Foo foo = 1;\n" - "}\n"); + "syntax = \"proto2\";\n" + "import \"foo.proto\";\n" + "message Bar {\n" + " optional Foo foo = 1;\n" + "}\n"); Run("protocol_compiler --descriptor_set_out=$tmpdir/descriptor_set " "--proto_path=$tmpdir bar.proto"); @@ -1360,20 +1336,20 @@ TEST_F(CommandLineInterfaceTest, WriteDescriptorSet) { TEST_F(CommandLineInterfaceTest, WriteDescriptorSetWithDuplicates) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Bar {\n" - " optional Foo foo = 1;\n" - "}\n"); + "syntax = \"proto2\";\n" + "import \"foo.proto\";\n" + "message Bar {\n" + " optional Foo foo = 1;\n" + "}\n"); CreateTempFile("baz.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Baz {\n" - " optional Foo foo = 1;\n" - "}\n"); + "syntax = \"proto2\";\n" + "import \"foo.proto\";\n" + "message Baz {\n" + " optional Foo foo = 1;\n" + "}\n"); Run("protocol_compiler --descriptor_set_out=$tmpdir/descriptor_set " "--proto_path=$tmpdir bar.proto foo.proto bar.proto baz.proto"); @@ -1399,14 +1375,14 @@ TEST_F(CommandLineInterfaceTest, WriteDescriptorSetWithDuplicates) { TEST_F(CommandLineInterfaceTest, WriteDescriptorSetWithSourceInfo) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Bar {\n" - " optional Foo foo = 1;\n" - "}\n"); + "syntax = \"proto2\";\n" + "import \"foo.proto\";\n" + "message Bar {\n" + " optional Foo foo = 1;\n" + "}\n"); Run("protocol_compiler --descriptor_set_out=$tmpdir/descriptor_set " "--include_source_info --proto_path=$tmpdir bar.proto"); @@ -1424,14 +1400,14 @@ TEST_F(CommandLineInterfaceTest, WriteDescriptorSetWithSourceInfo) { TEST_F(CommandLineInterfaceTest, WriteTransitiveDescriptorSet) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Bar {\n" - " optional Foo foo = 1;\n" - "}\n"); + "syntax = \"proto2\";\n" + "import \"foo.proto\";\n" + "message Bar {\n" + " optional Foo foo = 1;\n" + "}\n"); Run("protocol_compiler --descriptor_set_out=$tmpdir/descriptor_set " "--include_imports --proto_path=$tmpdir bar.proto"); @@ -1455,14 +1431,14 @@ TEST_F(CommandLineInterfaceTest, WriteTransitiveDescriptorSet) { TEST_F(CommandLineInterfaceTest, WriteTransitiveDescriptorSetWithSourceInfo) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Bar {\n" - " optional Foo foo = 1;\n" - "}\n"); + "syntax = \"proto2\";\n" + "import \"foo.proto\";\n" + "message Bar {\n" + " optional Foo foo = 1;\n" + "}\n"); Run("protocol_compiler --descriptor_set_out=$tmpdir/descriptor_set " "--include_imports --include_source_info --proto_path=$tmpdir bar.proto"); @@ -1489,14 +1465,14 @@ TEST_F(CommandLineInterfaceTest, WriteTransitiveDescriptorSetWithSourceInfo) { #else TEST_F(CommandLineInterfaceTest, WriteDependencyManifestFileGivenTwoInputs) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Bar {\n" - " optional Foo foo = 1;\n" - "}\n"); + "syntax = \"proto2\";\n" + "import \"foo.proto\";\n" + "message Bar {\n" + " optional Foo foo = 1;\n" + "}\n"); Run("protocol_compiler --dependency_out=$tmpdir/manifest " "--test_out=$tmpdir --proto_path=$tmpdir bar.proto foo.proto"); @@ -1508,16 +1484,16 @@ TEST_F(CommandLineInterfaceTest, WriteDependencyManifestFileGivenTwoInputs) { #ifdef PROTOBUF_OPENSOURCE TEST_F(CommandLineInterfaceTest, WriteDependencyManifestFile) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Bar {\n" - " optional Foo foo = 1;\n" - "}\n"); + "syntax = \"proto2\";\n" + "import \"foo.proto\";\n" + "message Bar {\n" + " optional Foo foo = 1;\n" + "}\n"); - string current_working_directory = getcwd(NULL, 0); + std::string current_working_directory = getcwd(NULL, 0); SwitchToTempDirectory(); Run("protocol_compiler --dependency_out=manifest --test_out=. " @@ -1538,14 +1514,14 @@ TEST_F(CommandLineInterfaceTest, WriteDependencyManifestFile) { TEST_F(CommandLineInterfaceTest, WriteDependencyManifestFileForAbsolutePath) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Bar {\n" - " optional Foo foo = 1;\n" - "}\n"); + "syntax = \"proto2\";\n" + "import \"foo.proto\";\n" + "message Bar {\n" + " optional Foo foo = 1;\n" + "}\n"); Run("protocol_compiler --dependency_out=$tmpdir/manifest " "--test_out=$tmpdir --proto_path=$tmpdir bar.proto"); @@ -1562,11 +1538,11 @@ TEST_F(CommandLineInterfaceTest, TestArgumentFile) { // Test parsing multiple input files using an argument file. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "message Bar {}\n"); + "syntax = \"proto2\";\n" + "message Bar {}\n"); CreateTempFile("arguments.txt", "--test_out=$tmpdir\n" "--plug_out=$tmpdir\n" @@ -1595,14 +1571,14 @@ TEST_F(CommandLineInterfaceTest, ParseErrors) { // Test that parse errors are reported. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "badsyntax\n"); + "syntax = \"proto2\";\n" + "badsyntax\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); ExpectErrorText( - "foo.proto:2:1: Expected top-level statement (e.g. \"message\").\n"); + "foo.proto:2:1: Expected top-level statement (e.g. \"message\").\n"); } TEST_F(CommandLineInterfaceTest, ParseErrors_DescriptorSetIn) { @@ -1612,8 +1588,7 @@ TEST_F(CommandLineInterfaceTest, ParseErrors_DescriptorSetIn) { Run("protocol_compiler --test_out=$tmpdir " "--descriptor_set_in=$tmpdir/foo.bin foo.proto"); - ExpectErrorText( - "$tmpdir/foo.bin: Unable to parse.\n"); + ExpectErrorText("$tmpdir/foo.bin: Unable to parse.\n"); } TEST_F(CommandLineInterfaceTest, ParseErrorsMultipleFiles) { @@ -1623,37 +1598,38 @@ TEST_F(CommandLineInterfaceTest, ParseErrorsMultipleFiles) { // two ways: Directly and through baz.proto. bar.proto's errors should // only be reported once. CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "badsyntax\n"); + "syntax = \"proto2\";\n" + "badsyntax\n"); CreateTempFile("baz.proto", - "syntax = \"proto2\";\n" - "import \"bar.proto\";\n"); + "syntax = \"proto2\";\n" + "import \"bar.proto\";\n"); CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "import \"bar.proto\";\n" - "import \"baz.proto\";\n"); + "syntax = \"proto2\";\n" + "import \"bar.proto\";\n" + "import \"baz.proto\";\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); ExpectErrorText( - "bar.proto:2:1: Expected top-level statement (e.g. \"message\").\n" - "baz.proto: Import \"bar.proto\" was not found or had errors.\n" - "foo.proto: Import \"bar.proto\" was not found or had errors.\n" - "foo.proto: Import \"baz.proto\" was not found or had errors.\n"); + "bar.proto:2:1: Expected top-level statement (e.g. \"message\").\n" + "baz.proto:2:1: Import \"bar.proto\" was not found or had errors.\n" + "foo.proto:2:1: Import \"bar.proto\" was not found or had errors.\n" + "foo.proto:3:1: Import \"baz.proto\" was not found or had errors.\n"); } TEST_F(CommandLineInterfaceTest, RecursiveImportFails) { // Create a proto file that imports itself. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n"); + "syntax = \"proto2\";\n" + "import \"foo.proto\";\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); ExpectErrorSubstring( - "foo.proto: File recursively imports itself: foo.proto -> foo.proto\n"); + "foo.proto:2:1: File recursively imports itself: " + "foo.proto -> foo.proto\n"); } TEST_F(CommandLineInterfaceTest, InputNotFoundError) { @@ -1671,8 +1647,7 @@ TEST_F(CommandLineInterfaceTest, InputNotFoundError_DescriptorSetIn) { Run("protocol_compiler --test_out=$tmpdir " "--descriptor_set_in=$tmpdir/foo.bin foo.proto"); - ExpectErrorText( - "$tmpdir/foo.bin: No such file or directory\n"); + ExpectErrorText("$tmpdir/foo.bin: No such file or directory\n"); } TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotFoundError) { @@ -1682,8 +1657,7 @@ TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotFoundError) { Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir $tmpdir/foo.proto"); - ExpectErrorText( - "$tmpdir/foo.proto: No such file or directory\n"); + ExpectErrorText("$tmpdir/foo.proto: No such file or directory\n"); } TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotMappedError) { @@ -1691,8 +1665,8 @@ TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotMappedError) { // mapped to a virtual path. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); // Create a directory called "bar" so that we can point --proto_path at it. CreateTempFile("bar/dummy", ""); @@ -1701,7 +1675,7 @@ TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotMappedError) { "--proto_path=$tmpdir/bar $tmpdir/foo.proto"); ExpectErrorText( - "$tmpdir/foo.proto: File does not reside within any path " + "$tmpdir/foo.proto: File does not reside within any path " "specified using --proto_path (or -I). You must specify a " "--proto_path which encompasses this file. Note that the " "proto_path must be an exact prefix of the .proto file " @@ -1720,8 +1694,7 @@ TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotFoundAndNotMappedError) { Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir/bar $tmpdir/foo.proto"); - ExpectErrorText( - "$tmpdir/foo.proto: No such file or directory\n"); + ExpectErrorText("$tmpdir/foo.proto: No such file or directory\n"); } TEST_F(CommandLineInterfaceTest, CwdRelativeInputShadowedError) { @@ -1729,21 +1702,21 @@ TEST_F(CommandLineInterfaceTest, CwdRelativeInputShadowedError) { // by another file in the virtual path. CreateTempFile("foo/foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); CreateTempFile("bar/foo.proto", - "syntax = \"proto2\";\n" - "message Bar {}\n"); + "syntax = \"proto2\";\n" + "message Bar {}\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir/foo --proto_path=$tmpdir/bar " "$tmpdir/bar/foo.proto"); ExpectErrorText( - "$tmpdir/bar/foo.proto: Input is shadowed in the --proto_path " - "by \"$tmpdir/foo/foo.proto\". Either use the latter " - "file as your input or reorder the --proto_path so that the " - "former file's location comes first.\n"); + "$tmpdir/bar/foo.proto: Input is shadowed in the --proto_path " + "by \"$tmpdir/foo/foo.proto\". Either use the latter " + "file as your input or reorder the --proto_path so that the " + "former file's location comes first.\n"); } TEST_F(CommandLineInterfaceTest, ProtoPathNotFoundError) { @@ -1760,13 +1733,49 @@ TEST_F(CommandLineInterfaceTest, ProtoPathNotFoundError) { TEST_F(CommandLineInterfaceTest, ProtoPathAndDescriptorSetIn) { Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir --descriptor_set_in=$tmpdir/foo.bin foo.proto"); - ExpectErrorText( - "Only one of --descriptor_set_in and --proto_path can be specified.\n"); + ExpectErrorText("$tmpdir/foo.bin: No such file or directory\n"); Run("protocol_compiler --test_out=$tmpdir " "--descriptor_set_in=$tmpdir/foo.bin --proto_path=$tmpdir foo.proto"); - ExpectErrorText( - "Only one of --proto_path and --descriptor_set_in can be specified.\n"); + ExpectErrorText("$tmpdir/foo.bin: No such file or directory\n"); +} + +TEST_F(CommandLineInterfaceTest, ProtoPathAndDescriptorSetIn_CompileFiles) { + // Test what happens if a proto is in a --descriptor_set_in and also exists + // on disk. + FileDescriptorSet file_descriptor_set; + + // NOTE: This file desc SHOULD be different from the one created as a temp + // to make it easier to test that the file was output instead of the + // contents of the --descriptor_set_in file. + FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file(); + file_descriptor_proto->set_name("foo.proto"); + file_descriptor_proto->add_message_type()->set_name("Foo"); + + WriteDescriptorSet("foo.bin", &file_descriptor_set); + + CreateTempFile("foo.proto", + "syntax = \"proto2\";\n" + "message FooBar { required string foo_message = 1; }\n"); + + Run("protocol_compiler --descriptor_set_out=$tmpdir/descriptor_set " + "--descriptor_set_in=$tmpdir/foo.bin " + "--include_source_info " + "--proto_path=$tmpdir foo.proto"); + + ExpectNoErrors(); + + FileDescriptorSet descriptor_set; + ReadDescriptorSet("descriptor_set", &descriptor_set); + + EXPECT_EQ(1, descriptor_set.file_size()); + EXPECT_EQ("foo.proto", descriptor_set.file(0).name()); + // Descriptor set SHOULD have source code info. + EXPECT_TRUE(descriptor_set.file(0).has_source_code_info()); + + EXPECT_EQ("FooBar", descriptor_set.file(0).message_type(0).name()); + EXPECT_EQ("foo_message", + descriptor_set.file(0).message_type(0).field(0).name()); } TEST_F(CommandLineInterfaceTest, ProtoPathAndDependencyOut) { @@ -1794,8 +1803,8 @@ TEST_F(CommandLineInterfaceTest, MissingInputError) { TEST_F(CommandLineInterfaceTest, MissingOutputError) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler --proto_path=$tmpdir foo.proto"); @@ -1804,10 +1813,10 @@ TEST_F(CommandLineInterfaceTest, MissingOutputError) { TEST_F(CommandLineInterfaceTest, OutputWriteError) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); - string output_file = + std::string output_file = MockCodeGenerator::GetOutputFileName("test_generator", "foo.proto"); // Create a directory blocking our output location. @@ -1833,10 +1842,10 @@ TEST_F(CommandLineInterfaceTest, OutputWriteError) { TEST_F(CommandLineInterfaceTest, PluginOutputWriteError) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); - string output_file = + std::string output_file = MockCodeGenerator::GetOutputFileName("test_plugin", "foo.proto"); // Create a directory blocking our output location. @@ -1857,8 +1866,8 @@ TEST_F(CommandLineInterfaceTest, PluginOutputWriteError) { TEST_F(CommandLineInterfaceTest, OutputDirectoryNotFoundError) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler --test_out=$tmpdir/nosuchdir " "--proto_path=$tmpdir foo.proto"); @@ -1868,8 +1877,8 @@ TEST_F(CommandLineInterfaceTest, OutputDirectoryNotFoundError) { TEST_F(CommandLineInterfaceTest, PluginOutputDirectoryNotFoundError) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler --plug_out=$tmpdir/nosuchdir " "--proto_path=$tmpdir foo.proto"); @@ -1879,8 +1888,8 @@ TEST_F(CommandLineInterfaceTest, PluginOutputDirectoryNotFoundError) { TEST_F(CommandLineInterfaceTest, OutputDirectoryIsFileError) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler --test_out=$tmpdir/foo.proto " "--proto_path=$tmpdir foo.proto"); @@ -1897,8 +1906,8 @@ TEST_F(CommandLineInterfaceTest, OutputDirectoryIsFileError) { TEST_F(CommandLineInterfaceTest, GeneratorError) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message MockCodeGenerator_Error {}\n"); + "syntax = \"proto2\";\n" + "message MockCodeGenerator_Error {}\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); @@ -1911,8 +1920,8 @@ TEST_F(CommandLineInterfaceTest, GeneratorPluginError) { // Test a generator plugin that returns an error. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message MockCodeGenerator_Error {}\n"); + "syntax = \"proto2\";\n" + "message MockCodeGenerator_Error {}\n"); Run("protocol_compiler --plug_out=TestParameter:$tmpdir " "--proto_path=$tmpdir foo.proto"); @@ -1925,8 +1934,8 @@ TEST_F(CommandLineInterfaceTest, GeneratorPluginFail) { // Test a generator plugin that exits with an error code. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message MockCodeGenerator_Exit {}\n"); + "syntax = \"proto2\";\n" + "message MockCodeGenerator_Exit {}\n"); Run("protocol_compiler --plug_out=TestParameter:$tmpdir " "--proto_path=$tmpdir foo.proto"); @@ -1940,8 +1949,8 @@ TEST_F(CommandLineInterfaceTest, GeneratorPluginCrash) { // Test a generator plugin that crashes. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message MockCodeGenerator_Abort {}\n"); + "syntax = \"proto2\";\n" + "message MockCodeGenerator_Abort {}\n"); Run("protocol_compiler --plug_out=TestParameter:$tmpdir " "--proto_path=$tmpdir foo.proto"); @@ -1955,15 +1964,14 @@ TEST_F(CommandLineInterfaceTest, GeneratorPluginCrash) { "--plug_out: prefix-gen-plug: Plugin failed with status code"); #else // Don't depend on the exact signal number. - ExpectErrorSubstring( - "--plug_out: prefix-gen-plug: Plugin killed by signal"); + ExpectErrorSubstring("--plug_out: prefix-gen-plug: Plugin killed by signal"); #endif } TEST_F(CommandLineInterfaceTest, PluginReceivesSourceCodeInfo) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message MockCodeGenerator_HasSourceCodeInfo {}\n"); + "syntax = \"proto2\";\n" + "message MockCodeGenerator_HasSourceCodeInfo {}\n"); Run("protocol_compiler --plug_out=$tmpdir --proto_path=$tmpdir foo.proto"); @@ -1973,10 +1981,10 @@ TEST_F(CommandLineInterfaceTest, PluginReceivesSourceCodeInfo) { TEST_F(CommandLineInterfaceTest, PluginReceivesJsonName) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message MockCodeGenerator_HasJsonName {\n" - " optional int32 value = 1;\n" - "}\n"); + "syntax = \"proto2\";\n" + "message MockCodeGenerator_HasJsonName {\n" + " optional int32 value = 1;\n" + "}\n"); Run("protocol_compiler --plug_out=$tmpdir --proto_path=$tmpdir foo.proto"); @@ -1985,25 +1993,24 @@ TEST_F(CommandLineInterfaceTest, PluginReceivesJsonName) { TEST_F(CommandLineInterfaceTest, PluginReceivesCompilerVersion) { CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message MockCodeGenerator_ShowVersionNumber {\n" - " optional int32 value = 1;\n" - "}\n"); + "syntax = \"proto2\";\n" + "message MockCodeGenerator_ShowVersionNumber {\n" + " optional int32 value = 1;\n" + "}\n"); Run("protocol_compiler --plug_out=$tmpdir --proto_path=$tmpdir foo.proto"); - ExpectErrorSubstring( - StringPrintf("Saw compiler_version: %d %s", - GOOGLE_PROTOBUF_VERSION, - GOOGLE_PROTOBUF_VERSION_SUFFIX)); + ExpectErrorSubstring(StringPrintf("Saw compiler_version: %d %s", + GOOGLE_PROTOBUF_VERSION, + GOOGLE_PROTOBUF_VERSION_SUFFIX)); } TEST_F(CommandLineInterfaceTest, GeneratorPluginNotFound) { // Test what happens if the plugin isn't found. CreateTempFile("error.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler --badplug_out=TestParameter:$tmpdir " "--plugin=prefix-gen-badplug=no_such_file " @@ -2011,11 +2018,10 @@ TEST_F(CommandLineInterfaceTest, GeneratorPluginNotFound) { #ifdef _WIN32 ExpectErrorSubstring("--badplug_out: prefix-gen-badplug: " + - Subprocess::Win32ErrorMessage(ERROR_FILE_NOT_FOUND)); + Subprocess::Win32ErrorMessage(ERROR_FILE_NOT_FOUND)); #else // Error written to stdout by child process after exec() fails. - ExpectErrorSubstring( - "no_such_file: program not found or is not executable"); + ExpectErrorSubstring("no_such_file: program not found or is not executable"); // Error written by parent process when child fails. ExpectErrorSubstring( @@ -2027,8 +2033,8 @@ TEST_F(CommandLineInterfaceTest, GeneratorPluginNotAllowed) { // Test what happens if plugins aren't allowed. CreateTempFile("error.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); DisallowPlugins(); Run("protocol_compiler --plug_out=TestParameter:$tmpdir " @@ -2052,28 +2058,28 @@ TEST_F(CommandLineInterfaceTest, GccFormatErrors) { // that it can be set explicitly). CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "badsyntax\n"); + "syntax = \"proto2\";\n" + "badsyntax\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir --error_format=gcc foo.proto"); ExpectErrorText( - "foo.proto:2:1: Expected top-level statement (e.g. \"message\").\n"); + "foo.proto:2:1: Expected top-level statement (e.g. \"message\").\n"); } TEST_F(CommandLineInterfaceTest, MsvsFormatErrors) { // Test --error_format=msvs CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "badsyntax\n"); + "syntax = \"proto2\";\n" + "badsyntax\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir --error_format=msvs foo.proto"); ExpectErrorText( - "$tmpdir/foo.proto(2) : error in column=1: Expected top-level statement " + "$tmpdir/foo.proto(2) : error in column=1: Expected top-level statement " "(e.g. \"message\").\n"); } @@ -2081,14 +2087,13 @@ TEST_F(CommandLineInterfaceTest, InvalidErrorFormat) { // Test --error_format=msvs CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "badsyntax\n"); + "syntax = \"proto2\";\n" + "badsyntax\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir --error_format=invalid foo.proto"); - ExpectErrorText( - "Unknown error format: invalid\n"); + ExpectErrorText("Unknown error format: invalid\n"); } // ------------------------------------------------------------------- @@ -2098,8 +2103,8 @@ TEST_F(CommandLineInterfaceTest, ParseSingleCharacterFlag) { // Test that a single-character flag works. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler -t$tmpdir " "--proto_path=$tmpdir foo.proto"); @@ -2112,8 +2117,8 @@ TEST_F(CommandLineInterfaceTest, ParseSpaceDelimitedValue) { // Test that separating the flag value with a space works. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler --test_out $tmpdir " "--proto_path=$tmpdir foo.proto"); @@ -2127,8 +2132,8 @@ TEST_F(CommandLineInterfaceTest, ParseSingleCharacterSpaceDelimitedValue) { // single-character flags. CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); Run("protocol_compiler -t $tmpdir " "--proto_path=$tmpdir foo.proto"); @@ -2155,38 +2160,35 @@ TEST_F(CommandLineInterfaceTest, MissingValueAtEndError) { } TEST_F(CommandLineInterfaceTest, PrintFreeFieldNumbers) { - CreateTempFile( - "foo.proto", - "syntax = \"proto2\";\n" - "package foo;\n" - "message Foo {\n" - " optional int32 a = 2;\n" - " optional string b = 4;\n" - " optional string c = 5;\n" - " optional int64 d = 8;\n" - " optional double e = 10;\n" - "}\n"); - CreateTempFile( - "bar.proto", - "syntax = \"proto2\";\n" - "message Bar {\n" - " optional int32 a = 2;\n" - " extensions 4 to 5;\n" - " optional int64 d = 8;\n" - " extensions 10;\n" - "}\n"); - CreateTempFile( - "baz.proto", - "syntax = \"proto2\";\n" - "message Baz {\n" - " optional int32 a = 2;\n" - " optional int64 d = 8;\n" - " extensions 15 to max;\n" // unordered. - " extensions 13;\n" - " extensions 10 to 12;\n" - " extensions 5;\n" - " extensions 4;\n" - "}\n"); + CreateTempFile("foo.proto", + "syntax = \"proto2\";\n" + "package foo;\n" + "message Foo {\n" + " optional int32 a = 2;\n" + " optional string b = 4;\n" + " optional string c = 5;\n" + " optional int64 d = 8;\n" + " optional double e = 10;\n" + "}\n"); + CreateTempFile("bar.proto", + "syntax = \"proto2\";\n" + "message Bar {\n" + " optional int32 a = 2;\n" + " extensions 4 to 5;\n" + " optional int64 d = 8;\n" + " extensions 10;\n" + "}\n"); + CreateTempFile("baz.proto", + "syntax = \"proto2\";\n" + "message Baz {\n" + " optional int32 a = 2;\n" + " optional int64 d = 8;\n" + " extensions 15 to max;\n" // unordered. + " extensions 13;\n" + " extensions 10 to 12;\n" + " extensions 5;\n" + " extensions 4;\n" + "}\n"); CreateTempFile( "quz.proto", "syntax = \"proto2\";\n" @@ -2231,10 +2233,7 @@ TEST_F(CommandLineInterfaceTest, PrintFreeFieldNumbers) { // platforms that don't have a Bourne-compatible shell available (especially // Windows/MSVC). -enum EncodeDecodeTestMode { - PROTO_PATH, - DESCRIPTOR_SET_IN -}; +enum EncodeDecodeTestMode { PROTO_PATH, DESCRIPTOR_SET_IN }; class EncodeDecodeTest : public testing::TestWithParam { protected: @@ -2248,13 +2247,13 @@ class EncodeDecodeTest : public testing::TestWithParam { close(duped_stdin_); } - void RedirectStdinFromText(const string& input) { - string filename = TestTempDir() + "/test_stdin"; + void RedirectStdinFromText(const std::string& input) { + std::string filename = TestTempDir() + "/test_stdin"; GOOGLE_CHECK_OK(File::SetContents(filename, input, true)); GOOGLE_CHECK(RedirectStdinFromFile(filename)); } - bool RedirectStdinFromFile(const string& filename) { + bool RedirectStdinFromFile(const std::string& filename) { int fd = open(filename.c_str(), O_RDONLY); if (fd < 0) return false; dup2(fd, STDIN_FILENO); @@ -2263,8 +2262,8 @@ class EncodeDecodeTest : public testing::TestWithParam { } // Remove '\r' characters from text. - string StripCR(const string& text) { - string result; + std::string StripCR(const std::string& text) { + std::string result; for (int i = 0; i < text.size(); i++) { if (text[i] != '\r') { @@ -2278,24 +2277,23 @@ class EncodeDecodeTest : public testing::TestWithParam { enum Type { TEXT, BINARY }; enum ReturnCode { SUCCESS, ERROR }; - bool Run(const string& command) { - std::vector args; + bool Run(const std::string& command) { + std::vector args; args.push_back("protoc"); SplitStringUsing(command, " ", &args); switch (GetParam()) { case PROTO_PATH: - args.push_back("--proto_path=" + TestSourceDir()); + args.push_back("--proto_path=" + TestUtil::TestSourceDir()); break; case DESCRIPTOR_SET_IN: - args.push_back(StrCat( - "--descriptor_set_in=", - unittest_proto_descriptor_set_filename_)); + args.push_back(StrCat("--descriptor_set_in=", + unittest_proto_descriptor_set_filename_)); break; default: ADD_FAILURE() << "unexpected EncodeDecodeTestMode: " << GetParam(); } - std::unique_ptr argv(new const char* [args.size()]); + std::unique_ptr argv(new const char*[args.size()]); for (int i = 0; i < args.size(); i++) { argv[i] = args[i].c_str(); } @@ -2313,8 +2311,8 @@ class EncodeDecodeTest : public testing::TestWithParam { return result == 0; } - void ExpectStdoutMatchesBinaryFile(const string& filename) { - string expected_output; + void ExpectStdoutMatchesBinaryFile(const std::string& filename) { + std::string expected_output; GOOGLE_CHECK_OK(File::GetContents(filename, &expected_output, true)); // Don't use EXPECT_EQ because we don't want to print raw binary data to @@ -2322,18 +2320,18 @@ class EncodeDecodeTest : public testing::TestWithParam { EXPECT_TRUE(captured_stdout_ == expected_output); } - void ExpectStdoutMatchesTextFile(const string& filename) { - string expected_output; + void ExpectStdoutMatchesTextFile(const std::string& filename) { + std::string expected_output; GOOGLE_CHECK_OK(File::GetContents(filename, &expected_output, true)); ExpectStdoutMatchesText(expected_output); } - void ExpectStdoutMatchesText(const string& expected_text) { + void ExpectStdoutMatchesText(const std::string& expected_text) { EXPECT_EQ(StripCR(expected_text), StripCR(captured_stdout_)); } - void ExpectStderrMatchesText(const string& expected_text) { + void ExpectStderrMatchesText(const std::string& expected_text) { EXPECT_EQ(StripCR(expected_text), StripCR(captured_stderr_)); } @@ -2348,88 +2346,91 @@ class EncodeDecodeTest : public testing::TestWithParam { protobuf_unittest_import::ImportMessage import_message; import_message.descriptor()->file()->CopyTo(file_descriptor_set.add_file()); - protobuf_unittest_import::PublicImportMessage public_import_message; public_import_message.descriptor()->file()->CopyTo( file_descriptor_set.add_file()); GOOGLE_DCHECK(file_descriptor_set.IsInitialized()); - string binary_proto; + std::string binary_proto; GOOGLE_CHECK(file_descriptor_set.SerializeToString(&binary_proto)); - GOOGLE_CHECK_OK(File::SetContents( - unittest_proto_descriptor_set_filename_, - binary_proto, - true)); + GOOGLE_CHECK_OK(File::SetContents(unittest_proto_descriptor_set_filename_, + binary_proto, true)); } int duped_stdin_; - string captured_stdout_; - string captured_stderr_; - string unittest_proto_descriptor_set_filename_; + std::string captured_stdout_; + std::string captured_stderr_; + std::string unittest_proto_descriptor_set_filename_; }; TEST_P(EncodeDecodeTest, Encode) { - RedirectStdinFromFile(TestSourceDir() + "/google/protobuf/" - "testdata/text_format_unittest_data_oneof_implemented.txt"); - EXPECT_TRUE(Run("google/protobuf/unittest.proto " - "--encode=protobuf_unittest.TestAllTypes")); - ExpectStdoutMatchesBinaryFile(TestSourceDir() + - "/google/protobuf/testdata/golden_message_oneof_implemented"); + RedirectStdinFromFile(TestUtil::GetTestDataPath( + "net/proto2/internal/" + "testdata/text_format_unittest_data_oneof_implemented.txt")); + EXPECT_TRUE( + Run(TestUtil::MaybeTranslatePath("net/proto2/internal/unittest.proto") + + " --encode=protobuf_unittest.TestAllTypes")); + ExpectStdoutMatchesBinaryFile(TestUtil::GetTestDataPath( + "net/proto2/internal/testdata/golden_message_oneof_implemented")); ExpectStderrMatchesText(""); } TEST_P(EncodeDecodeTest, Decode) { - RedirectStdinFromFile(TestSourceDir() + - "/google/protobuf/testdata/golden_message_oneof_implemented"); - EXPECT_TRUE(Run("google/protobuf/unittest.proto " - "--decode=protobuf_unittest.TestAllTypes")); - ExpectStdoutMatchesTextFile(TestSourceDir() + - "/google/protobuf/" - "testdata/text_format_unittest_data_oneof_implemented.txt"); + RedirectStdinFromFile(TestUtil::GetTestDataPath( + "net/proto2/internal/testdata/golden_message_oneof_implemented")); + EXPECT_TRUE( + Run(TestUtil::MaybeTranslatePath("net/proto2/internal/unittest.proto") + + " --decode=protobuf_unittest.TestAllTypes")); + ExpectStdoutMatchesTextFile(TestUtil::GetTestDataPath( + "net/proto2/internal/" + "testdata/text_format_unittest_data_oneof_implemented.txt")); ExpectStderrMatchesText(""); } TEST_P(EncodeDecodeTest, Partial) { RedirectStdinFromText(""); - EXPECT_TRUE(Run("google/protobuf/unittest.proto " - "--encode=protobuf_unittest.TestRequired")); + EXPECT_TRUE( + Run(TestUtil::MaybeTranslatePath("net/proto2/internal/unittest.proto") + + " --encode=protobuf_unittest.TestRequired")); ExpectStdoutMatchesText(""); ExpectStderrMatchesText( - "warning: Input message is missing required fields: a, b, c\n"); + "warning: Input message is missing required fields: a, b, c\n"); } TEST_P(EncodeDecodeTest, DecodeRaw) { protobuf_unittest::TestAllTypes message; message.set_optional_int32(123); message.set_optional_string("foo"); - string data; + std::string data; message.SerializeToString(&data); RedirectStdinFromText(data); EXPECT_TRUE(Run("--decode_raw")); - ExpectStdoutMatchesText("1: 123\n" - "14: \"foo\"\n"); + ExpectStdoutMatchesText( + "1: 123\n" + "14: \"foo\"\n"); ExpectStderrMatchesText(""); } TEST_P(EncodeDecodeTest, UnknownType) { - EXPECT_FALSE(Run("google/protobuf/unittest.proto " - "--encode=NoSuchType")); + EXPECT_FALSE( + Run(TestUtil::MaybeTranslatePath("net/proto2/internal/unittest.proto") + + " --encode=NoSuchType")); ExpectStdoutMatchesText(""); ExpectStderrMatchesText("Type not defined: NoSuchType\n"); } TEST_P(EncodeDecodeTest, ProtoParseError) { - EXPECT_FALSE(Run("google/protobuf/no_such_file.proto " - "--encode=NoSuchType")); + EXPECT_FALSE( + Run("net/proto2/internal/no_such_file.proto " + "--encode=NoSuchType")); ExpectStdoutMatchesText(""); ExpectStderrMatchesText( - "google/protobuf/no_such_file.proto: No such file or directory\n"); + "net/proto2/internal/no_such_file.proto: No such file or directory\n"); } -INSTANTIATE_TEST_CASE_P(FileDescriptorSetSource, - EncodeDecodeTest, - testing::Values(PROTO_PATH, DESCRIPTOR_SET_IN)); +INSTANTIATE_TEST_SUITE_P(FileDescriptorSetSource, EncodeDecodeTest, + testing::Values(PROTO_PATH, DESCRIPTOR_SET_IN)); } // anonymous namespace #endif // !GOOGLE_PROTOBUF_HEAP_CHECK_DRACONIAN diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc index 4e150fe3..debd9a06 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc @@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. // -// This test insures that google/protobuf/descriptor.pb.{h,cc} match exactly +// This test insures that net/proto2/proto/descriptor.pb.{h,cc} match exactly // what would be generated by the protocol compiler. These files are not // generated automatically at build time because they are compiled into the // protocol compiler itself. So, if they were auto-generated, you'd have a @@ -47,8 +47,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -70,34 +72,43 @@ class MockErrorCollector : public MultiFileErrorCollector { MockErrorCollector() {} ~MockErrorCollector() {} - string text_; + std::string text_; // implements ErrorCollector --------------------------------------- - void AddError(const string& filename, int line, int column, - const string& message) { - strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", - filename, line, column, message); + void AddError(const std::string& filename, int line, int column, + const std::string& message) { + strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", filename, line, + column, message); } }; class MockGeneratorContext : public GeneratorContext { public: MockGeneratorContext() {} - ~MockGeneratorContext() { - STLDeleteValues(&files_); - } + ~MockGeneratorContext() { STLDeleteValues(&files_); } - void ExpectFileMatches(const string& virtual_filename, - const string& physical_filename) { - string* expected_contents = FindPtrOrNull(files_, virtual_filename); + void ExpectFileMatches(const std::string& virtual_filename, + const std::string& physical_filename) { + std::string* expected_contents = + FindPtrOrNull(files_, virtual_filename); ASSERT_TRUE(expected_contents != NULL) - << "Generator failed to generate file: " << virtual_filename; + << "Generator failed to generate file: " << virtual_filename; - string actual_contents; + std::string actual_contents; GOOGLE_CHECK_OK( - File::GetContents(TestSourceDir() + "/" + physical_filename, - &actual_contents, true)); - EXPECT_TRUE(actual_contents == *expected_contents) + File::GetContents(TestUtil::TestSourceDir() + "/" + physical_filename, + &actual_contents, true)) + << physical_filename; + CleanStringLineEndings(&actual_contents, false); + +#ifdef WRITE_FILES // Define to debug mismatched files. + GOOGLE_CHECK_OK(File::SetContents("/tmp/expected.cc", *expected_contents, + true)); + GOOGLE_CHECK_OK( + File::SetContents("/tmp/actual.cc", actual_contents, true)); +#endif + + ASSERT_EQ(*expected_contents, actual_contents) << physical_filename << " needs to be regenerated. Please run " "generate_descriptor_proto.sh. " @@ -106,21 +117,21 @@ class MockGeneratorContext : public GeneratorContext { // implements GeneratorContext -------------------------------------- - virtual io::ZeroCopyOutputStream* Open(const string& filename) { - string** map_slot = &files_[filename]; + virtual io::ZeroCopyOutputStream* Open(const std::string& filename) { + std::string** map_slot = &files_[filename]; delete *map_slot; - *map_slot = new string; + *map_slot = new std::string; return new io::StringOutputStream(*map_slot); } private: - std::map files_; + std::map files_; }; -const char kDescriptorParameter[] = "dllexport_decl=LIBPROTOBUF_EXPORT"; -const char kPluginParameter[] = "dllexport_decl=LIBPROTOC_EXPORT"; -const char kNormalParameter[] = ""; +const char kDescriptorParameter[] = "dllexport_decl=PROTOBUF_EXPORT"; +const char kPluginParameter[] = "dllexport_decl=PROTOC_EXPORT"; + const char* test_protos[][2] = { {"google/protobuf/descriptor", kDescriptorParameter}, @@ -130,34 +141,42 @@ const char* test_protos[][2] = { TEST(BootstrapTest, GeneratedFilesMatch) { // We need a mapping from the actual file to virtual and actual path // of the data to compare to. - std::map vpath_map; - std::map rpath_map; - rpath_map["third_party/protobuf/src/google/protobuf/test_messages_proto2"] = - "net/proto2/z_generated_example/test_messages_proto2"; - rpath_map["third_party/protobuf/src/google/protobuf/test_messages_proto3"] = - "net/proto2/z_generated_example/test_messages_proto3"; - rpath_map["google/protobuf/proto2_weak"] = + std::map vpath_map; + std::map rpath_map; + rpath_map + ["third_party/protobuf_legacy_opensource/src/google/protobuf/" + "test_messages_proto2"] = + "net/proto2/z_generated_example/test_messages_proto2"; + rpath_map + ["third_party/protobuf_legacy_opensource/src/google/protobuf/" + "test_messages_proto3"] = + "net/proto2/z_generated_example/test_messages_proto3"; + rpath_map["net/proto2/internal/proto2_weak"] = "net/proto2/z_generated_example/proto2_weak"; DiskSourceTree source_tree; - source_tree.MapPath("", TestSourceDir()); + source_tree.MapPath("", TestUtil::TestSourceDir()); for (auto file_parameter : test_protos) { MockErrorCollector error_collector; Importer importer(&source_tree, &error_collector); const FileDescriptor* file = - importer.Import(file_parameter[0] + string(".proto")); + importer.Import(file_parameter[0] + std::string(".proto")); ASSERT_TRUE(file != nullptr) << "Can't import file " << file_parameter[0] + string(".proto") << "\n"; EXPECT_EQ("", error_collector.text_); CppGenerator generator; MockGeneratorContext context; - string error; +#ifdef GOOGLE_PROTOBUF_RUNTIME_INCLUDE_BASE + generator.set_opensource_runtime(true); + generator.set_runtime_include_base(GOOGLE_PROTOBUF_RUNTIME_INCLUDE_BASE); +#endif + std::string error; ASSERT_TRUE(generator.Generate(file, file_parameter[1], &context, &error)); - string vpath = + std::string vpath = FindWithDefault(vpath_map, file_parameter[0], file_parameter[0]); - string rpath = + std::string rpath = FindWithDefault(rpath_map, file_parameter[0], file_parameter[0]); context.ExpectFileMatches(vpath + ".pb.cc", rpath + ".pb.cc"); context.ExpectFileMatches(vpath + ".pb.h", rpath + ".pb.h"); diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_enum.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_enum.cc index 0d6a9e24..5e2ac253 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_enum.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_enum.cc @@ -46,7 +46,7 @@ namespace cpp { namespace { // The GOOGLE_ARRAYSIZE constant is the max enum value plus 1. If the max enum value -// is ::google::protobuf::kint32max, GOOGLE_ARRAYSIZE will overflow. In such cases we should omit the +// is kint32max, GOOGLE_ARRAYSIZE will overflow. In such cases we should omit the // generation of the GOOGLE_ARRAYSIZE constant. bool ShouldGenerateArraySize(const EnumDescriptor* descriptor) { int32 max_value = descriptor->value(0)->number(); @@ -55,61 +55,52 @@ bool ShouldGenerateArraySize(const EnumDescriptor* descriptor) { max_value = descriptor->value(i)->number(); } } - return max_value != ::google::protobuf::kint32max; + return max_value != kint32max; } } // namespace EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor, + const std::map& vars, const Options& options) - : descriptor_(descriptor), - classname_(ClassName(descriptor, false)), - options_(options), - generate_array_size_(ShouldGenerateArraySize(descriptor)) { + : descriptor_(descriptor), + classname_(ClassName(descriptor, false)), + options_(options), + generate_array_size_(ShouldGenerateArraySize(descriptor)), + variables_(vars) { + variables_["classname"] = classname_; + variables_["classtype"] = QualifiedClassName(descriptor_, options); + variables_["short_name"] = descriptor_->name(); + variables_["nested_name"] = descriptor_->name(); + variables_["resolved_name"] = ResolveKeyword(descriptor_->name()); + variables_["prefix"] = + (descriptor_->containing_type() == NULL) ? "" : classname_ + "_"; } EnumGenerator::~EnumGenerator() {} -void EnumGenerator::FillForwardDeclaration( - std::map* enum_names) { - if (!options_.proto_h) { - return; - } - (*enum_names)[classname_] = descriptor_; -} - void EnumGenerator::GenerateDefinition(io::Printer* printer) { - std::map vars; - vars["classname"] = classname_; - vars["short_name"] = descriptor_->name(); - vars["enumbase"] = options_.proto_h ? " : int" : ""; - // These variables are placeholders to pick out the beginning and ends of - // identifiers for annotations (when doing so with existing variables would - // be ambiguous or impossible). They should never be set to anything but the - // empty string. - vars["{"] = ""; - vars["}"] = ""; - - printer->Print(vars, "enum $classname$$enumbase$ {\n"); - printer->Annotate("classname", descriptor_); - printer->Indent(); + Formatter format(printer, variables_); + format("enum ${1$$classname$$}$ : int {\n", descriptor_); + format.Indent(); const EnumValueDescriptor* min_value = descriptor_->value(0); const EnumValueDescriptor* max_value = descriptor_->value(0); for (int i = 0; i < descriptor_->value_count(); i++) { - vars["name"] = EnumValueName(descriptor_->value(i)); + auto format_value = format; + format_value.Set("name", EnumValueName(descriptor_->value(i))); // In C++, an value of -2147483648 gets interpreted as the negative of // 2147483648, and since 2147483648 can't fit in an integer, this produces a // compiler warning. This works around that issue. - vars["number"] = Int32ToString(descriptor_->value(i)->number()); - vars["prefix"] = (descriptor_->containing_type() == NULL) ? - "" : classname_ + "_"; - vars["deprecation"] = descriptor_->value(i)->options().deprecated() ? - " PROTOBUF_DEPRECATED" : ""; + format_value.Set("number", Int32ToString(descriptor_->value(i)->number())); + format_value.Set( + "deprecation", + DeprecatedAttribute(options_, + descriptor_->value(i)->options().deprecated())); - if (i > 0) printer->Print(",\n"); - printer->Print(vars, "${$$prefix$$name$$}$$deprecation$ = $number$"); - printer->Annotate("{", "}", descriptor_->value(i)); + if (i > 0) format_value(",\n"); + format_value("${1$$prefix$$name$$}$ $deprecation$= $number$", + descriptor_->value(i)); if (descriptor_->value(i)->number() < min_value->number()) { min_value = descriptor_->value(i); @@ -119,156 +110,146 @@ void EnumGenerator::GenerateDefinition(io::Printer* printer) { } } - if (HasPreservingUnknownEnumSemantics(descriptor_->file())) { + if (descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) { // For new enum semantics: generate min and max sentinel values equal to // INT32_MIN and INT32_MAX - if (descriptor_->value_count() > 0) printer->Print(",\n"); - printer->Print(vars, - "$classname$_$prefix$INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min,\n" - "$classname$_$prefix$INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max"); + if (descriptor_->value_count() > 0) format(",\n"); + format( + "$classname$_$prefix$INT_MIN_SENTINEL_DO_NOT_USE_ = " + "std::numeric_limits<$int32$>::min(),\n" + "$classname$_$prefix$INT_MAX_SENTINEL_DO_NOT_USE_ = " + "std::numeric_limits<$int32$>::max()"); } - printer->Outdent(); - printer->Print("\n};\n"); + format.Outdent(); + format("\n};\n"); - vars["min_name"] = EnumValueName(min_value); - vars["max_name"] = EnumValueName(max_value); - - if (options_.dllexport_decl.empty()) { - vars["dllexport"] = ""; - } else { - vars["dllexport"] = options_.dllexport_decl + " "; - } - - printer->Print(vars, - "$dllexport$bool $classname$_IsValid(int value);\n" - "const $classname$ ${$$prefix$$short_name$_MIN$}$ = " - "$prefix$$min_name$;\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(vars, - "const $classname$ ${$$prefix$$short_name$_MAX$}$ = " - "$prefix$$max_name$;\n"); - printer->Annotate("{", "}", descriptor_); + format( + "$dllexport_decl $bool $classname$_IsValid(int value);\n" + "constexpr $classname$ ${1$$prefix$$short_name$_MIN$}$ = " + "$prefix$$2$;\n" + "constexpr $classname$ ${1$$prefix$$short_name$_MAX$}$ = " + "$prefix$$3$;\n", + descriptor_, EnumValueName(min_value), EnumValueName(max_value)); if (generate_array_size_) { - printer->Print(vars, - "const int ${$$prefix$$short_name$_ARRAYSIZE$}$ = " - "$prefix$$short_name$_MAX + 1;\n\n"); - printer->Annotate("{", "}", descriptor_); + format( + "constexpr int ${1$$prefix$$short_name$_ARRAYSIZE$}$ = " + "$prefix$$short_name$_MAX + 1;\n\n", + descriptor_); } if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print(vars, - "$dllexport$const ::google::protobuf::EnumDescriptor* $classname$_descriptor();\n"); + format( + "$dllexport_decl $const ::$proto_ns$::EnumDescriptor* " + "$classname$_descriptor();\n"); // The _Name and _Parse methods - printer->Print( - vars, - "inline const ::std::string& $classname$_Name($classname$ value) {\n" - " return ::google::protobuf::internal::NameOfEnum(\n" - " $classname$_descriptor(), value);\n" + // Support a stricter, type-checked enum-to-string method that + // statically checks whether the parameter is the exact enum type or is + // an integral type. + format( + "template\n" + "inline const std::string& $classname$_Name(T enum_t_value) {\n" + " static_assert(::std::is_same::value ||\n" + " ::std::is_integral::value,\n" + " \"Incorrect type passed to function $classname$_Name.\");\n" + " return ::$proto_ns$::internal::NameOfEnum(\n" + " $classname$_descriptor(), enum_t_value);\n" + "}\n"); + format( + "inline bool $classname$_Parse(\n" + " const std::string& name, $classname$* value) {\n" + " return ::$proto_ns$::internal::ParseNamedEnum<$classname$>(\n" + " $classname$_descriptor(), name, value);\n" "}\n"); - printer->Print(vars, - "inline bool $classname$_Parse(\n" - " const ::std::string& name, $classname$* value) {\n" - " return ::google::protobuf::internal::ParseNamedEnum<$classname$>(\n" - " $classname$_descriptor(), name, value);\n" - "}\n"); } } -void EnumGenerator:: -GenerateGetEnumDescriptorSpecializations(io::Printer* printer) { - printer->Print( - "template <> struct is_proto_enum< $classname$> : ::std::true_type " - "{};\n", - "classname", ClassName(descriptor_, true)); +void EnumGenerator::GenerateGetEnumDescriptorSpecializations( + io::Printer* printer) { + Formatter format(printer, variables_); + format( + "template <> struct is_proto_enum< $classtype$> : ::std::true_type " + "{};\n"); if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print( - "template <>\n" - "inline const EnumDescriptor* GetEnumDescriptor< $classname$>() {\n" - " return $classname$_descriptor();\n" - "}\n", - "classname", ClassName(descriptor_, true)); + format( + "template <>\n" + "inline const EnumDescriptor* GetEnumDescriptor< $classtype$>() {\n" + " return $classtype$_descriptor();\n" + "}\n"); } } -void EnumGenerator::GenerateSymbolImports(io::Printer* printer) { - std::map vars; - vars["nested_name"] = descriptor_->name(); - vars["classname"] = classname_; - vars["constexpr"] = options_.proto_h ? "constexpr " : ""; - vars["{"] = ""; - vars["}"] = ""; - printer->Print(vars, "typedef $classname$ $nested_name$;\n"); +void EnumGenerator::GenerateSymbolImports(io::Printer* printer) const { + Formatter format(printer, variables_); + format("typedef $classname$ $resolved_name$;\n"); for (int j = 0; j < descriptor_->value_count(); j++) { - vars["tag"] = EnumValueName(descriptor_->value(j)); - vars["deprecated_attr"] = descriptor_->value(j)->options().deprecated() ? - "GOOGLE_PROTOBUF_DEPRECATED_ATTR " : ""; - printer->Print(vars, - "$deprecated_attr$static $constexpr$const $nested_name$ ${$$tag$$}$ =\n" - " $classname$_$tag$;\n"); - printer->Annotate("{", "}", descriptor_->value(j)); + std::string deprecated_attr = DeprecatedAttribute( + options_, descriptor_->value(j)->options().deprecated()); + format( + "$1$static constexpr $resolved_name$ ${2$$3$$}$ =\n" + " $classname$_$3$;\n", + deprecated_attr, descriptor_->value(j), + EnumValueName(descriptor_->value(j))); } - printer->Print(vars, - "static inline bool $nested_name$_IsValid(int value) {\n" - " return $classname$_IsValid(value);\n" - "}\n" - "static const $nested_name$ ${$$nested_name$_MIN$}$ =\n" - " $classname$_$nested_name$_MIN;\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(vars, - "static const $nested_name$ ${$$nested_name$_MAX$}$ =\n" - " $classname$_$nested_name$_MAX;\n"); - printer->Annotate("{", "}", descriptor_); + format( + "static inline bool $nested_name$_IsValid(int value) {\n" + " return $classname$_IsValid(value);\n" + "}\n" + "static constexpr $resolved_name$ ${1$$nested_name$_MIN$}$ =\n" + " $classname$_$nested_name$_MIN;\n" + "static constexpr $resolved_name$ ${1$$nested_name$_MAX$}$ =\n" + " $classname$_$nested_name$_MAX;\n", + descriptor_); if (generate_array_size_) { - printer->Print(vars, - "static const int ${$$nested_name$_ARRAYSIZE$}$ =\n" - " $classname$_$nested_name$_ARRAYSIZE;\n"); - printer->Annotate("{", "}", descriptor_); + format( + "static constexpr int ${1$$nested_name$_ARRAYSIZE$}$ =\n" + " $classname$_$nested_name$_ARRAYSIZE;\n", + descriptor_); } if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print(vars, - "static inline const ::google::protobuf::EnumDescriptor*\n" - "$nested_name$_descriptor() {\n" - " return $classname$_descriptor();\n" - "}\n"); - printer->Print(vars, - "static inline const ::std::string& " - "$nested_name$_Name($nested_name$ value) {" - "\n" - " return $classname$_Name(value);\n" - "}\n"); - printer->Print(vars, - "static inline bool $nested_name$_Parse(const ::std::string& name,\n" - " $nested_name$* value) {\n" - " return $classname$_Parse(name, value);\n" - "}\n"); + format( + "static inline const ::$proto_ns$::EnumDescriptor*\n" + "$nested_name$_descriptor() {\n" + " return $classname$_descriptor();\n" + "}\n"); + // Support a stricter, type-checked enum-to-string method that + // statically checks whether the parameter is the exact enum type or is + // an integral type. + format( + "template\n" + "static inline const std::string& $nested_name$_Name(T enum_t_value) " + "{\n" + " static_assert(::std::is_same::value ||\n" + " ::std::is_integral::value,\n" + " \"Incorrect type passed to function $nested_name$_Name.\");\n" + " return $classname$_Name(enum_t_value);\n" + "}\n"); + format( + "static inline bool $nested_name$_Parse(const std::string& name,\n" + " $resolved_name$* value) {\n" + " return $classname$_Parse(name, value);\n" + "}\n"); } } void EnumGenerator::GenerateMethods(int idx, io::Printer* printer) { - std::map vars; - vars["classname"] = classname_; - vars["index_in_metadata"] = SimpleItoa(idx); - vars["constexpr"] = options_.proto_h ? "constexpr " : ""; - vars["file_namespace"] = FileLevelNamespace(descriptor_->file()->name()); - + Formatter format(printer, variables_); if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print( - vars, - "const ::google::protobuf::EnumDescriptor* $classname$_descriptor() {\n" - " $file_namespace$::protobuf_AssignDescriptorsOnce();\n" - " return " - "$file_namespace$::file_level_enum_descriptors[$index_in_metadata$];\n" - "}\n"); + format( + "const ::$proto_ns$::EnumDescriptor* $classname$_descriptor() {\n" + " ::$proto_ns$::internal::AssignDescriptors(&$desc_table$);\n" + " return $file_level_enum_descriptors$[$1$];\n" + "}\n", + idx); } - printer->Print(vars, - "bool $classname$_IsValid(int value) {\n" - " switch (value) {\n"); + format( + "bool $classname$_IsValid(int value) {\n" + " switch (value) {\n"); // Multiple values may have the same number. Make sure we only cover // each number once by first constructing a set containing all valid @@ -280,44 +261,43 @@ void EnumGenerator::GenerateMethods(int idx, io::Printer* printer) { numbers.insert(value->number()); } - for (std::set::iterator iter = numbers.begin(); - iter != numbers.end(); ++iter) { - printer->Print( - " case $number$:\n", - "number", Int32ToString(*iter)); + for (std::set::iterator iter = numbers.begin(); iter != numbers.end(); + ++iter) { + format(" case $1$:\n", Int32ToString(*iter)); } - printer->Print(vars, - " return true;\n" - " default:\n" - " return false;\n" - " }\n" - "}\n" - "\n"); + format( + " return true;\n" + " default:\n" + " return false;\n" + " }\n" + "}\n" + "\n"); if (descriptor_->containing_type() != NULL) { - // We need to "define" the static constants which were declared in the - // header, to give the linker a place to put them. Or at least the C++ - // standard says we have to. MSVC actually insists that we do _not_ define - // them again in the .cc file, prior to VC++ 2015. - printer->Print("#if !defined(_MSC_VER) || _MSC_VER >= 1900\n"); + std::string parent = ClassName(descriptor_->containing_type(), false); + // Before C++17, we must define the static constants which were + // declared in the header, to give the linker a place to put them. + // But pre-2015 MSVC++ insists that we not. + format( + "#if (__cplusplus < 201703) && " + "(!defined(_MSC_VER) || _MSC_VER >= 1900)\n"); - vars["parent"] = ClassName(descriptor_->containing_type(), false); - vars["nested_name"] = descriptor_->name(); for (int i = 0; i < descriptor_->value_count(); i++) { - vars["value"] = EnumValueName(descriptor_->value(i)); - printer->Print(vars, - "$constexpr$const $classname$ $parent$::$value$;\n"); + format("constexpr $classname$ $1$::$2$;\n", parent, + EnumValueName(descriptor_->value(i))); } - printer->Print(vars, - "const $classname$ $parent$::$nested_name$_MIN;\n" - "const $classname$ $parent$::$nested_name$_MAX;\n"); + format( + "constexpr $classname$ $1$::$nested_name$_MIN;\n" + "constexpr $classname$ $1$::$nested_name$_MAX;\n", + parent); if (generate_array_size_) { - printer->Print(vars, - "const int $parent$::$nested_name$_ARRAYSIZE;\n"); + format("constexpr int $1$::$nested_name$_ARRAYSIZE;\n", parent); } - printer->Print("#endif // !defined(_MSC_VER) || _MSC_VER >= 1900\n"); + format( + "#endif // (__cplusplus < 201703) && " + "(!defined(_MSC_VER) || _MSC_VER >= 1900)\n"); } } diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_enum.h b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_enum.h index 0d2488a9..3687f04c 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_enum.h +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_enum.h @@ -43,11 +43,13 @@ namespace google { namespace protobuf { - namespace io { - class Printer; // printer.h - } +namespace io { +class Printer; // printer.h } +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace cpp { @@ -55,20 +57,11 @@ namespace cpp { class EnumGenerator { public: // See generator.cc for the meaning of dllexport_decl. - EnumGenerator(const EnumDescriptor* descriptor, const Options& options); + EnumGenerator(const EnumDescriptor* descriptor, + const std::map& vars, + const Options& options); ~EnumGenerator(); - // Header stuff. - - // Fills the name to use when declaring the enum. This is for use when - // generating other .proto.h files. This code should be placed within the - // enum's package namespace, but NOT within any class, even for nested - // enums. A given key in enum_names will map from an enum class name to the - // EnumDescriptor that was responsible for its inclusion in the map. This can - // be used to associate the descriptor with the code generated for it. - void FillForwardDeclaration( - std::map* enum_names); - // Generate header code defining the enum. This code should be placed // within the enum's package namespace, but NOT within any class, even for // nested enums. @@ -82,7 +75,7 @@ class EnumGenerator { // symbols (e.g. the enum type name, all its values, etc.) into the class's // namespace. This should be placed inside the class definition in the // header. - void GenerateSymbolImports(io::Printer* printer); + void GenerateSymbolImports(io::Printer* printer) const; // Source file stuff. @@ -93,11 +86,13 @@ class EnumGenerator { private: const EnumDescriptor* descriptor_; - const string classname_; + const std::string classname_; const Options& options_; // whether to generate the *_ARRAYSIZE constant. const bool generate_array_size_; + std::map variables_; + friend class FileGenerator; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator); }; @@ -105,6 +100,6 @@ class EnumGenerator { } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_enum_field.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_enum_field.cc index 50c7b5f3..10eed3df 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_enum_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_enum_field.cc @@ -46,11 +46,11 @@ namespace cpp { namespace { void SetEnumVariables(const FieldDescriptor* descriptor, - std::map* variables, + std::map* variables, const Options& options) { SetCommonFieldVariables(descriptor, variables, options); const EnumValueDescriptor* default_value = descriptor->default_value_enum(); - (*variables)["type"] = ClassName(descriptor->enum_type(), true); + (*variables)["type"] = QualifiedClassName(descriptor->enum_type(), options); (*variables)["default"] = Int32ToString(default_value->number()); (*variables)["full_name"] = descriptor->full_name(); } @@ -61,457 +61,452 @@ void SetEnumVariables(const FieldDescriptor* descriptor, EnumFieldGenerator::EnumFieldGenerator(const FieldDescriptor* descriptor, const Options& options) - : FieldGenerator(options), descriptor_(descriptor) { + : FieldGenerator(descriptor, options) { SetEnumVariables(descriptor, &variables_, options); } EnumFieldGenerator::~EnumFieldGenerator() {} -void EnumFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { - printer->Print(variables_, "int $name$_;\n"); +void EnumFieldGenerator::GeneratePrivateMembers(io::Printer* printer) const { + Formatter format(printer, variables_); + format("int $name$_;\n"); } -void EnumFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { - printer->Print(variables_, "$deprecated_attr$$type$ $name$() const;\n"); - printer->Annotate("name", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$set_$name$$}$($type$ value);\n"); - printer->Annotate("{", "}", descriptor_); +void EnumFieldGenerator::GenerateAccessorDeclarations( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "$deprecated_attr$$type$ ${1$$name$$}$() const;\n" + "$deprecated_attr$void ${1$set_$name$$}$($type$ value);\n", + descriptor_); } -void EnumFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - printer->Print(variables_, - "inline $type$ $classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return static_cast< $type$ >($name$_);\n" - "}\n" - "inline void $classname$::set_$name$($type$ value) {\n"); - if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) { - printer->Print(variables_, - " assert($type$_IsValid(value));\n"); +void EnumFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "inline $type$ $classname$::$name$() const {\n" + " // @@protoc_insertion_point(field_get:$full_name$)\n" + " return static_cast< $type$ >($name$_);\n" + "}\n" + "inline void $classname$::set_$name$($type$ value) {\n"); + if (!HasPreservingUnknownEnumSemantics(descriptor_)) { + format(" assert($type$_IsValid(value));\n"); } - printer->Print(variables_, - " $set_hasbit$\n" - " $name$_ = value;\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - "}\n"); -} - -void EnumFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $default$;\n"); -} - -void EnumFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, "set_$name$(from.$name$());\n"); -} - -void EnumFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - printer->Print(variables_, "swap($name$_, other->$name$_);\n"); -} - -void EnumFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $default$;\n"); -} - -void EnumFieldGenerator:: -GenerateCopyConstructorCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = from.$name$_;\n"); -} - -void EnumFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - printer->Print(variables_, - "int value;\n" - "DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n" - " int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(\n" - " input, &value)));\n"); - if (HasPreservingUnknownEnumSemantics(descriptor_->file())) { - printer->Print(variables_, - "set_$name$(static_cast< $type$ >(value));\n"); - } else { - printer->Print(variables_, - "if ($type$_IsValid(value)) {\n" - " set_$name$(static_cast< $type$ >(value));\n"); - if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(variables_, - "} else {\n" - " mutable_unknown_fields()->AddVarint(\n" - " $number$, static_cast< ::google::protobuf::uint64>(value));\n"); - } else { - printer->Print( - "} else {\n" - " unknown_fields_stream.WriteVarint32($tag$u);\n" - " unknown_fields_stream.WriteVarint32(\n" - " static_cast< ::google::protobuf::uint32>(value));\n", - "tag", SimpleItoa(internal::WireFormat::MakeTag(descriptor_))); - } - printer->Print(variables_, + format( + " $set_hasbit$\n" + " $name$_ = value;\n" + " // @@protoc_insertion_point(field_set:$full_name$)\n" "}\n"); +} + +void EnumFieldGenerator::GenerateClearingCode(io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_ = $default$;\n"); +} + +void EnumFieldGenerator::GenerateMergingCode(io::Printer* printer) const { + Formatter format(printer, variables_); + format("set_$name$(from.$name$());\n"); +} + +void EnumFieldGenerator::GenerateSwappingCode(io::Printer* printer) const { + Formatter format(printer, variables_); + format("swap($name$_, other->$name$_);\n"); +} + +void EnumFieldGenerator::GenerateConstructorCode(io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_ = $default$;\n"); +} + +void EnumFieldGenerator::GenerateCopyConstructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_ = from.$name$_;\n"); +} + +void EnumFieldGenerator::GenerateMergeFromCodedStream( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "int value = 0;\n" + "DO_((::$proto_ns$::internal::WireFormatLite::ReadPrimitive<\n" + " int, ::$proto_ns$::internal::WireFormatLite::TYPE_ENUM>(\n" + " input, &value)));\n"); + if (HasPreservingUnknownEnumSemantics(descriptor_)) { + format("set_$name$(static_cast< $type$ >(value));\n"); + } else { + format( + "if ($type$_IsValid(value)) {\n" + " set_$name$(static_cast< $type$ >(value));\n"); + if (UseUnknownFieldSet(descriptor_->file(), options_)) { + format( + "} else {\n" + " mutable_unknown_fields()->AddVarint(\n" + " $number$, static_cast<$uint64$>(value));\n"); + } else { + format( + "} else {\n" + " unknown_fields_stream.WriteVarint32($1$u);\n" + " unknown_fields_stream.WriteVarint32(\n" + " static_cast<$uint32$>(value));\n", + internal::WireFormat::MakeTag(descriptor_)); + } + format("}\n"); } } -void EnumFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { - printer->Print(variables_, - "::google::protobuf::internal::WireFormatLite::WriteEnum(\n" - " $number$, this->$name$(), output);\n"); +void EnumFieldGenerator::GenerateSerializeWithCachedSizes( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "::$proto_ns$::internal::WireFormatLite::WriteEnum(\n" + " $number$, this->$name$(), output);\n"); } -void EnumFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { - printer->Print(variables_, - "target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(\n" - " $number$, this->$name$(), target);\n"); +void EnumFieldGenerator::GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "target = ::$proto_ns$::internal::WireFormatLite::WriteEnumToArray(\n" + " $number$, this->$name$(), target);\n"); } -void EnumFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { - printer->Print(variables_, - "total_size += $tag_size$ +\n" - " ::google::protobuf::internal::WireFormatLite::EnumSize(this->$name$());\n"); +void EnumFieldGenerator::GenerateByteSize(io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "total_size += $tag_size$ +\n" + " ::$proto_ns$::internal::WireFormatLite::EnumSize(this->$name$());\n"); } // =================================================================== -EnumOneofFieldGenerator:: -EnumOneofFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) - : EnumFieldGenerator(descriptor, options) { +EnumOneofFieldGenerator::EnumOneofFieldGenerator( + const FieldDescriptor* descriptor, const Options& options) + : EnumFieldGenerator(descriptor, options) { SetCommonOneofFieldVariables(descriptor, &variables_); } EnumOneofFieldGenerator::~EnumOneofFieldGenerator() {} -void EnumOneofFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - printer->Print(variables_, - "inline $type$ $classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " if (has_$name$()) {\n" - " return static_cast< $type$ >($field_member$);\n" - " }\n" - " return static_cast< $type$ >($default$);\n" - "}\n" - "inline void $classname$::set_$name$($type$ value) {\n"); - if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) { - printer->Print(variables_, - " assert($type$_IsValid(value));\n"); +void EnumOneofFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "inline $type$ $classname$::$name$() const {\n" + " // @@protoc_insertion_point(field_get:$full_name$)\n" + " if (has_$name$()) {\n" + " return static_cast< $type$ >($field_member$);\n" + " }\n" + " return static_cast< $type$ >($default$);\n" + "}\n" + "inline void $classname$::set_$name$($type$ value) {\n"); + if (!HasPreservingUnknownEnumSemantics(descriptor_)) { + format(" assert($type$_IsValid(value));\n"); } - printer->Print(variables_, - " if (!has_$name$()) {\n" - " clear_$oneof_name$();\n" - " set_has_$name$();\n" - " }\n" - " $field_member$ = value;\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - "}\n"); + format( + " if (!has_$name$()) {\n" + " clear_$oneof_name$();\n" + " set_has_$name$();\n" + " }\n" + " $field_member$ = value;\n" + " // @@protoc_insertion_point(field_set:$full_name$)\n" + "}\n"); } -void EnumOneofFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - printer->Print(variables_, "$field_member$ = $default$;\n"); +void EnumOneofFieldGenerator::GenerateClearingCode(io::Printer* printer) const { + Formatter format(printer, variables_); + format("$field_member$ = $default$;\n"); } -void EnumOneofFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { +void EnumOneofFieldGenerator::GenerateSwappingCode(io::Printer* printer) const { // Don't print any swapping code. Swapping the union will swap this field. } -void EnumOneofFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - printer->Print(variables_, - "$ns$::_$classname$_default_instance_.$name$_ = $default$;\n"); +void EnumOneofFieldGenerator::GenerateConstructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$ns$::_$classname$_default_instance_.$name$_ = $default$;\n"); } // =================================================================== RepeatedEnumFieldGenerator::RepeatedEnumFieldGenerator( const FieldDescriptor* descriptor, const Options& options) - : FieldGenerator(options), descriptor_(descriptor) { + : FieldGenerator(descriptor, options) { SetEnumVariables(descriptor, &variables_, options); } RepeatedEnumFieldGenerator::~RepeatedEnumFieldGenerator() {} -void RepeatedEnumFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { - printer->Print(variables_, - "::google::protobuf::RepeatedField $name$_;\n"); +void RepeatedEnumFieldGenerator::GeneratePrivateMembers( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("::$proto_ns$::RepeatedField $name$_;\n"); if (descriptor_->is_packed() && HasGeneratedMethods(descriptor_->file(), options_)) { - printer->Print(variables_, - "mutable int _$name$_cached_byte_size_;\n"); + format("mutable std::atomic _$name$_cached_byte_size_;\n"); } } -void RepeatedEnumFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { - printer->Print(variables_, - "$deprecated_attr$$type$ $name$(int index) const;\n"); - printer->Annotate("name", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$void ${$set_$name$$}$(int index, $type$ value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$add_$name$$}$($type$ value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$const ::google::protobuf::RepeatedField& $name$() const;\n"); - printer->Annotate("name", descriptor_); - printer->Print(variables_, - "$deprecated_attr$::google::protobuf::RepeatedField* " - "${$mutable_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); +void RepeatedEnumFieldGenerator::GenerateAccessorDeclarations( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "$deprecated_attr$$type$ ${1$$name$$}$(int index) const;\n" + "$deprecated_attr$void ${1$set_$name$$}$(int index, $type$ value);\n" + "$deprecated_attr$void ${1$add_$name$$}$($type$ value);\n" + "$deprecated_attr$const ::$proto_ns$::RepeatedField& " + "${1$$name$$}$() const;\n" + "$deprecated_attr$::$proto_ns$::RepeatedField* " + "${1$mutable_$name$$}$();\n", + descriptor_); } -void RepeatedEnumFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - printer->Print(variables_, - "inline $type$ $classname$::$name$(int index) const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return static_cast< $type$ >($name$_.Get(index));\n" - "}\n" - "inline void $classname$::set_$name$(int index, $type$ value) {\n"); - if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) { - printer->Print(variables_, - " assert($type$_IsValid(value));\n"); +void RepeatedEnumFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "inline $type$ $classname$::$name$(int index) const {\n" + " // @@protoc_insertion_point(field_get:$full_name$)\n" + " return static_cast< $type$ >($name$_.Get(index));\n" + "}\n" + "inline void $classname$::set_$name$(int index, $type$ value) {\n"); + if (!HasPreservingUnknownEnumSemantics(descriptor_)) { + format(" assert($type$_IsValid(value));\n"); } - printer->Print(variables_, - " $name$_.Set(index, value);\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - "}\n" - "inline void $classname$::add_$name$($type$ value) {\n"); - if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) { - printer->Print(variables_, - " assert($type$_IsValid(value));\n"); + format( + " $name$_.Set(index, value);\n" + " // @@protoc_insertion_point(field_set:$full_name$)\n" + "}\n" + "inline void $classname$::add_$name$($type$ value) {\n"); + if (!HasPreservingUnknownEnumSemantics(descriptor_)) { + format(" assert($type$_IsValid(value));\n"); } - printer->Print(variables_, - " $name$_.Add(value);\n" - " // @@protoc_insertion_point(field_add:$full_name$)\n" - "}\n" - "inline const ::google::protobuf::RepeatedField&\n" - "$classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_list:$full_name$)\n" - " return $name$_;\n" - "}\n" - "inline ::google::protobuf::RepeatedField*\n" - "$classname$::mutable_$name$() {\n" - " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n" - " return &$name$_;\n" - "}\n"); + format( + " $name$_.Add(value);\n" + " // @@protoc_insertion_point(field_add:$full_name$)\n" + "}\n" + "inline const ::$proto_ns$::RepeatedField&\n" + "$classname$::$name$() const {\n" + " // @@protoc_insertion_point(field_list:$full_name$)\n" + " return $name$_;\n" + "}\n" + "inline ::$proto_ns$::RepeatedField*\n" + "$classname$::mutable_$name$() {\n" + " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n" + " return &$name$_;\n" + "}\n"); } -void RepeatedEnumFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.Clear();\n"); +void RepeatedEnumFieldGenerator::GenerateClearingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.Clear();\n"); } -void RepeatedEnumFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n"); +void RepeatedEnumFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.MergeFrom(from.$name$_);\n"); } -void RepeatedEnumFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.InternalSwap(&other->$name$_);\n"); +void RepeatedEnumFieldGenerator::GenerateSwappingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.InternalSwap(&other->$name$_);\n"); } -void RepeatedEnumFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { +void RepeatedEnumFieldGenerator::GenerateConstructorCode( + io::Printer* printer) const { // Not needed for repeated fields. } -void RepeatedEnumFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { +void RepeatedEnumFieldGenerator::GenerateMergeFromCodedStream( + io::Printer* printer) const { + Formatter format(printer, variables_); // Don't use ReadRepeatedPrimitive here so that the enum can be validated. - printer->Print(variables_, - "int value;\n" - "DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n" - " int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(\n" - " input, &value)));\n"); - if (HasPreservingUnknownEnumSemantics(descriptor_->file())) { - printer->Print(variables_, - "add_$name$(static_cast< $type$ >(value));\n"); - } else { - printer->Print(variables_, - "if ($type$_IsValid(value)) {\n" - " add_$name$(static_cast< $type$ >(value));\n"); - if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(variables_, - "} else {\n" - " mutable_unknown_fields()->AddVarint(\n" - " $number$, static_cast< ::google::protobuf::uint64>(value));\n"); - } else { - printer->Print( - "} else {\n" - " unknown_fields_stream.WriteVarint32(tag);\n" - " unknown_fields_stream.WriteVarint32(\n" - " static_cast< ::google::protobuf::uint32>(value));\n"); - } - printer->Print("}\n"); - } -} - -void RepeatedEnumFieldGenerator:: -GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const { - if (!descriptor_->is_packed()) { - // This path is rarely executed, so we use a non-inlined implementation. - if (HasPreservingUnknownEnumSemantics(descriptor_->file())) { - printer->Print(variables_, - "DO_((::google::protobuf::internal::" - "WireFormatLite::ReadPackedEnumPreserveUnknowns(\n" - " input,\n" - " $number$,\n" - " NULL,\n" - " NULL,\n" - " this->mutable_$name$())));\n"); - } else if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(variables_, - "DO_((::google::protobuf::internal::WireFormat::ReadPackedEnumPreserveUnknowns(\n" - " input,\n" - " $number$,\n" - " $type$_IsValid,\n" - " mutable_unknown_fields(),\n" - " this->mutable_$name$())));\n"); - } else { - printer->Print(variables_, - "DO_((::google::protobuf::internal::" - "WireFormatLite::ReadPackedEnumPreserveUnknowns(\n" - " input,\n" - " $number$,\n" - " $type$_IsValid,\n" - " &unknown_fields_stream,\n" - " this->mutable_$name$())));\n"); - } - } else { - printer->Print(variables_, - "::google::protobuf::uint32 length;\n" - "DO_(input->ReadVarint32(&length));\n" - "::google::protobuf::io::CodedInputStream::Limit limit = " - "input->PushLimit(static_cast(length));\n" - "while (input->BytesUntilLimit() > 0) {\n" - " int value;\n" - " DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n" - " int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(\n" + format( + "int value = 0;\n" + "DO_((::$proto_ns$::internal::WireFormatLite::ReadPrimitive<\n" + " int, ::$proto_ns$::internal::WireFormatLite::TYPE_ENUM>(\n" " input, &value)));\n"); - if (HasPreservingUnknownEnumSemantics(descriptor_->file())) { - printer->Print(variables_, - " add_$name$(static_cast< $type$ >(value));\n"); + if (HasPreservingUnknownEnumSemantics(descriptor_)) { + format("add_$name$(static_cast< $type$ >(value));\n"); + } else { + format( + "if ($type$_IsValid(value)) {\n" + " add_$name$(static_cast< $type$ >(value));\n"); + if (UseUnknownFieldSet(descriptor_->file(), options_)) { + format( + "} else {\n" + " mutable_unknown_fields()->AddVarint(\n" + " $number$, static_cast<$uint64$>(value));\n"); } else { - printer->Print(variables_, - " if ($type$_IsValid(value)) {\n" - " add_$name$(static_cast< $type$ >(value));\n" - " } else {\n"); - if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(variables_, - " mutable_unknown_fields()->AddVarint(\n" - " $number$, static_cast< ::google::protobuf::uint64>(value));\n"); - } else { - printer->Print(variables_, - " unknown_fields_stream.WriteVarint32(tag);\n" - " unknown_fields_stream.WriteVarint32(\n" - " static_cast< ::google::protobuf::uint32>(value));\n"); - } - printer->Print( - " }\n"); + format( + "} else {\n" + " unknown_fields_stream.WriteVarint32(tag);\n" + " unknown_fields_stream.WriteVarint32(\n" + " static_cast<$uint32$>(value));\n"); } - printer->Print(variables_, - "}\n" - "input->PopLimit(limit);\n"); + format("}\n"); } } -void RepeatedEnumFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { +void RepeatedEnumFieldGenerator::GenerateMergeFromCodedStreamWithPacking( + io::Printer* printer) const { + Formatter format(printer, variables_); + if (!descriptor_->is_packed()) { + // This path is rarely executed, so we use a non-inlined implementation. + if (HasPreservingUnknownEnumSemantics(descriptor_)) { + format( + "DO_((::$proto_ns$::internal::" + "WireFormatLite::ReadPackedEnumPreserveUnknowns(\n" + " input,\n" + " $number$,\n" + " nullptr,\n" + " nullptr,\n" + " this->mutable_$name$())));\n"); + } else if (UseUnknownFieldSet(descriptor_->file(), options_)) { + format( + "DO_((::$proto_ns$::internal::WireFormat::" + "ReadPackedEnumPreserveUnknowns(\n" + " input,\n" + " $number$,\n" + " $type$_IsValid,\n" + " mutable_unknown_fields(),\n" + " this->mutable_$name$())));\n"); + } else { + format( + "DO_((::$proto_ns$::internal::" + "WireFormatLite::ReadPackedEnumPreserveUnknowns(\n" + " input,\n" + " $number$,\n" + " $type$_IsValid,\n" + " &unknown_fields_stream,\n" + " this->mutable_$name$())));\n"); + } + } else { + format( + "$uint32$ length;\n" + "DO_(input->ReadVarint32(&length));\n" + "::$proto_ns$::io::CodedInputStream::Limit limit = " + "input->PushLimit(static_cast(length));\n" + "while (input->BytesUntilLimit() > 0) {\n" + " int value = 0;\n" + " DO_((::$proto_ns$::internal::WireFormatLite::ReadPrimitive<\n" + " int, ::$proto_ns$::internal::WireFormatLite::TYPE_ENUM>(\n" + " input, &value)));\n"); + if (HasPreservingUnknownEnumSemantics(descriptor_)) { + format(" add_$name$(static_cast< $type$ >(value));\n"); + } else { + format( + " if ($type$_IsValid(value)) {\n" + " add_$name$(static_cast< $type$ >(value));\n" + " } else {\n"); + if (UseUnknownFieldSet(descriptor_->file(), options_)) { + format( + " mutable_unknown_fields()->AddVarint(\n" + " $number$, static_cast<$uint64$>(value));\n"); + } else { + format( + " unknown_fields_stream.WriteVarint32(tag);\n" + " unknown_fields_stream.WriteVarint32(\n" + " static_cast<$uint32$>(value));\n"); + } + format(" }\n"); + } + format( + "}\n" + "input->PopLimit(limit);\n"); + } +} + +void RepeatedEnumFieldGenerator::GenerateSerializeWithCachedSizes( + io::Printer* printer) const { + Formatter format(printer, variables_); if (descriptor_->is_packed()) { // Write the tag and the size. - printer->Print(variables_, - "if (this->$name$_size() > 0) {\n" - " ::google::protobuf::internal::WireFormatLite::WriteTag(\n" - " $number$,\n" - " ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n" - " output);\n" - " output->WriteVarint32(\n" - " static_cast< ::google::protobuf::uint32>(_$name$_cached_byte_size_));\n" - "}\n"); + format( + "if (this->$name$_size() > 0) {\n" + " ::$proto_ns$::internal::WireFormatLite::WriteTag(\n" + " $number$,\n" + " " + "::$proto_ns$::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n" + " output);\n" + " output->WriteVarint32(_$name$_cached_byte_size_.load(\n" + " std::memory_order_relaxed));\n" + "}\n"); } - printer->Print(variables_, - "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n"); + format("for (int i = 0, n = this->$name$_size(); i < n; i++) {\n"); if (descriptor_->is_packed()) { - printer->Print(variables_, - " ::google::protobuf::internal::WireFormatLite::WriteEnumNoTag(\n" - " this->$name$(i), output);\n"); + format( + " ::$proto_ns$::internal::WireFormatLite::WriteEnumNoTag(\n" + " this->$name$(i), output);\n"); } else { - printer->Print(variables_, - " ::google::protobuf::internal::WireFormatLite::WriteEnum(\n" - " $number$, this->$name$(i), output);\n"); + format( + " ::$proto_ns$::internal::WireFormatLite::WriteEnum(\n" + " $number$, this->$name$(i), output);\n"); } - printer->Print("}\n"); + format("}\n"); } -void RepeatedEnumFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { +void RepeatedEnumFieldGenerator::GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const { + Formatter format(printer, variables_); if (descriptor_->is_packed()) { // Write the tag and the size. - printer->Print(variables_, - "if (this->$name$_size() > 0) {\n" - " target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(\n" - " $number$,\n" - " ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n" - " target);\n" - " target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(" - " static_cast< ::google::protobuf::uint32>(\n" - " _$name$_cached_byte_size_), target);\n" - " target = ::google::protobuf::internal::WireFormatLite::WriteEnumNoTagToArray(\n" - " this->$name$_, target);\n" - "}\n"); + format( + "if (this->$name$_size() > 0) {\n" + " target = ::$proto_ns$::internal::WireFormatLite::WriteTagToArray(\n" + " $number$,\n" + " " + "::$proto_ns$::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n" + " target);\n" + " target = ::$proto_ns$::io::CodedOutputStream::WriteVarint32ToArray(" + " _$name$_cached_byte_size_.load(std::memory_order_relaxed),\n" + " target);\n" + " target = " + "::$proto_ns$::internal::WireFormatLite::WriteEnumNoTagToArray(\n" + " this->$name$_, target);\n" + "}\n"); } else { - printer->Print(variables_, - "target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(\n" - " $number$, this->$name$_, target);\n"); + format( + "target = ::$proto_ns$::internal::WireFormatLite::WriteEnumToArray(\n" + " $number$, this->$name$_, target);\n"); } } -void RepeatedEnumFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { - printer->Print(variables_, - "{\n" - " size_t data_size = 0;\n" - " unsigned int count = static_cast(this->$name$_size());"); - printer->Indent(); - printer->Print(variables_, +void RepeatedEnumFieldGenerator::GenerateByteSize(io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "{\n" + " size_t data_size = 0;\n" + " unsigned int count = static_cast(this->$name$_size());"); + format.Indent(); + format( "for (unsigned int i = 0; i < count; i++) {\n" - " data_size += ::google::protobuf::internal::WireFormatLite::EnumSize(\n" + " data_size += ::$proto_ns$::internal::WireFormatLite::EnumSize(\n" " this->$name$(static_cast(i)));\n" "}\n"); if (descriptor_->is_packed()) { - printer->Print(variables_, - "if (data_size > 0) {\n" - " total_size += $tag_size$ +\n" - " ::google::protobuf::internal::WireFormatLite::Int32Size(\n" - " static_cast< ::google::protobuf::int32>(data_size));\n" - "}\n" - "int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);\n" - "GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n" - "_$name$_cached_byte_size_ = cached_size;\n" - "GOOGLE_SAFE_CONCURRENT_WRITES_END();\n" - "total_size += data_size;\n"); + format( + "if (data_size > 0) {\n" + " total_size += $tag_size$ +\n" + " ::$proto_ns$::internal::WireFormatLite::Int32Size(\n" + " static_cast<$int32$>(data_size));\n" + "}\n" + "int cached_size = ::$proto_ns$::internal::ToCachedSize(data_size);\n" + "_$name$_cached_byte_size_.store(cached_size,\n" + " std::memory_order_relaxed);\n" + "total_size += data_size;\n"); } else { - printer->Print(variables_, - "total_size += ($tag_size$UL * count) + data_size;\n"); + format("total_size += ($tag_size$UL * count) + data_size;\n"); } - printer->Outdent(); - printer->Print("}\n"); + format.Outdent(); + format("}\n"); } } // namespace cpp diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_enum_field.h b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_enum_field.h index d0e87b79..b43d402b 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_enum_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_enum_field.h @@ -63,10 +63,6 @@ class EnumFieldGenerator : public FieldGenerator { void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const; void GenerateByteSize(io::Printer* printer) const; - protected: - const FieldDescriptor* descriptor_; - std::map variables_; - private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator); }; @@ -109,15 +105,12 @@ class RepeatedEnumFieldGenerator : public FieldGenerator { void GenerateByteSize(io::Printer* printer) const; private: - const FieldDescriptor* descriptor_; - std::map variables_; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator); }; } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_FIELD_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_extension.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_extension.cc index c416ba10..97be5e64 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_extension.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_extension.cc @@ -40,6 +40,7 @@ #include + namespace google { namespace protobuf { namespace compiler { @@ -50,7 +51,7 @@ namespace { // Returns the fully-qualified class name of the message that this field // extends. This function is used in the Google-internal code to handle some // legacy cases. -string ExtendeeClassName(const FieldDescriptor* descriptor) { +std::string ExtendeeClassName(const FieldDescriptor* descriptor) { const Descriptor* extendee = descriptor->containing_type(); return ClassName(extendee, true); } @@ -59,8 +60,7 @@ string ExtendeeClassName(const FieldDescriptor* descriptor) { ExtensionGenerator::ExtensionGenerator(const FieldDescriptor* descriptor, const Options& options) - : descriptor_(descriptor), - options_(options) { + : descriptor_(descriptor), options_(options) { // Construct type_traits_. if (descriptor_->is_repeated()) { type_traits_ = "Repeated"; @@ -84,86 +84,98 @@ ExtensionGenerator::ExtensionGenerator(const FieldDescriptor* descriptor, break; default: type_traits_.append("PrimitiveTypeTraits< "); - type_traits_.append(PrimitiveTypeName(descriptor_->cpp_type())); + type_traits_.append(PrimitiveTypeName(options_, descriptor_->cpp_type())); type_traits_.append(" >"); break; } + SetCommonVars(options, &variables_); + variables_["extendee"] = ExtendeeClassName(descriptor_); + variables_["type_traits"] = type_traits_; + std::string name = descriptor_->name(); + variables_["name"] = ResolveKeyword(name); + variables_["constant_name"] = FieldConstantName(descriptor_); + variables_["field_type"] = + StrCat(static_cast(descriptor_->type())); + variables_["packed"] = descriptor_->options().packed() ? "true" : "false"; + + std::string scope = + IsScoped() ? ClassName(descriptor_->extension_scope(), false) + "::" : ""; + variables_["scope"] = scope; + std::string scoped_name = scope + ResolveKeyword(name); + variables_["scoped_name"] = scoped_name; + variables_["number"] = StrCat(descriptor_->number()); } ExtensionGenerator::~ExtensionGenerator() {} -void ExtensionGenerator::GenerateDeclaration(io::Printer* printer) { - std::map vars; - vars["extendee" ] = ExtendeeClassName(descriptor_); - vars["number" ] = SimpleItoa(descriptor_->number()); - vars["type_traits" ] = type_traits_; - vars["name" ] = descriptor_->name(); - vars["field_type" ] = SimpleItoa(static_cast(descriptor_->type())); - vars["packed" ] = descriptor_->options().packed() ? "true" : "false"; - vars["constant_name"] = FieldConstantName(descriptor_); +bool ExtensionGenerator::IsScoped() const { + return descriptor_->extension_scope() != nullptr; +} + +void ExtensionGenerator::GenerateDeclaration(io::Printer* printer) const { + Formatter format(printer, variables_); // If this is a class member, it needs to be declared "static". Otherwise, // it needs to be "extern". In the latter case, it also needs the DLL // export/import specifier. - if (descriptor_->extension_scope() == NULL) { - vars["qualifier"] = "extern"; + std::string qualifier; + if (!IsScoped()) { + qualifier = "extern"; if (!options_.dllexport_decl.empty()) { - vars["qualifier"] = options_.dllexport_decl + " " + vars["qualifier"]; + qualifier = options_.dllexport_decl + " " + qualifier; } } else { - vars["qualifier"] = "static"; + qualifier = "static"; } - printer->Print(vars, - "static const int $constant_name$ = $number$;\n" - "$qualifier$ ::google::protobuf::internal::ExtensionIdentifier< $extendee$,\n" - " ::google::protobuf::internal::$type_traits$, $field_type$, $packed$ >\n" - " $name$;\n" - ); + format( + "static const int $constant_name$ = $number$;\n" + "$1$ ::$proto_ns$::internal::ExtensionIdentifier< $extendee$,\n" + " ::$proto_ns$::internal::$type_traits$, $field_type$, $packed$ >\n" + " ${2$$name$$}$;\n", + qualifier, descriptor_); } void ExtensionGenerator::GenerateDefinition(io::Printer* printer) { + // If we are building for lite with implicit weak fields, we want to skip over + // any custom options (i.e. extensions of messages from descriptor.proto). + // This prevents the creation of any unnecessary linker references to the + // descriptor messages. + if (options_.lite_implicit_weak_fields && + descriptor_->containing_type()->file()->name() == + "net/proto2/proto/descriptor.proto") { + return; + } + + Formatter format(printer, variables_); + std::string default_str; // If this is a class member, it needs to be declared in its class scope. - string scope = (descriptor_->extension_scope() == NULL) ? "" : - ClassName(descriptor_->extension_scope(), false) + "::"; - string name = scope + descriptor_->name(); - - std::map vars; - vars["extendee" ] = ExtendeeClassName(descriptor_); - vars["type_traits" ] = type_traits_; - vars["name" ] = name; - vars["constant_name"] = FieldConstantName(descriptor_); - vars["default" ] = DefaultValue(descriptor_); - vars["field_type" ] = SimpleItoa(static_cast(descriptor_->type())); - vars["packed" ] = descriptor_->options().packed() ? "true" : "false"; - vars["scope" ] = scope; - if (descriptor_->cpp_type() == FieldDescriptor::CPPTYPE_STRING) { // We need to declare a global string which will contain the default value. // We cannot declare it at class scope because that would require exposing // it in the header which would be annoying for other reasons. So we // replace :: with _ in the name and declare it as a global. - string global_name = StringReplace(name, "::", "_", true); - vars["global_name"] = global_name; - printer->Print(vars, - "const ::std::string $global_name$_default($default$);\n"); - - // Update the default to refer to the string global. - vars["default"] = global_name + "_default"; + default_str = + StringReplace(variables_["scoped_name"], "::", "_", true) + "_default"; + format("const std::string $1$($2$);\n", default_str, + DefaultValue(options_, descriptor_)); + } else { + default_str = DefaultValue(options_, descriptor_); } // Likewise, class members need to declare the field constant variable. - if (descriptor_->extension_scope() != NULL) { - printer->Print(vars, - "#if !defined(_MSC_VER) || _MSC_VER >= 1900\n" - "const int $scope$$constant_name$;\n" - "#endif\n"); + if (IsScoped()) { + format( + "#if !defined(_MSC_VER) || _MSC_VER >= 1900\n" + "const int $scope$$constant_name$;\n" + "#endif\n"); } - printer->Print(vars, - "::google::protobuf::internal::ExtensionIdentifier< $extendee$,\n" - " ::google::protobuf::internal::$type_traits$, $field_type$, $packed$ >\n" - " $name$($constant_name$, $default$);\n"); + format( + "::$proto_ns$::internal::ExtensionIdentifier< $extendee$,\n" + " ::$proto_ns$::internal::$type_traits$, $field_type$, $packed$ >\n" + " $scoped_name$($constant_name$, $1$);\n", + default_str); } } // namespace cpp diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_extension.h b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_extension.h index 30236d71..72413f6b 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_extension.h +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_extension.h @@ -35,18 +35,22 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_CPP_EXTENSION_H__ #define GOOGLE_PROTOBUF_COMPILER_CPP_EXTENSION_H__ +#include #include + #include #include namespace google { namespace protobuf { - class FieldDescriptor; // descriptor.h - namespace io { - class Printer; // printer.h - } +class FieldDescriptor; // descriptor.h +namespace io { +class Printer; // printer.h } +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace cpp { @@ -62,22 +66,26 @@ class ExtensionGenerator { ~ExtensionGenerator(); // Header stuff. - void GenerateDeclaration(io::Printer* printer); + void GenerateDeclaration(io::Printer* printer) const; // Source file stuff. void GenerateDefinition(io::Printer* printer); + bool IsScoped() const; + private: const FieldDescriptor* descriptor_; - string type_traits_; + std::string type_traits_; Options options_; + std::map variables_; + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator); }; } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_field.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_field.cc index 0de20f84..411136f3 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_field.cc @@ -38,6 +38,7 @@ #include #include #include + #include #include #include @@ -56,31 +57,29 @@ namespace cpp { using internal::WireFormat; void SetCommonFieldVariables(const FieldDescriptor* descriptor, - std::map* variables, + std::map* variables, const Options& options) { - (*variables)["ns"] = Namespace(descriptor); + SetCommonVars(options, variables); + (*variables)["ns"] = Namespace(descriptor, options); (*variables)["name"] = FieldName(descriptor); - (*variables)["index"] = SimpleItoa(descriptor->index()); - (*variables)["number"] = SimpleItoa(descriptor->number()); + (*variables)["index"] = StrCat(descriptor->index()); + (*variables)["number"] = StrCat(descriptor->number()); (*variables)["classname"] = ClassName(FieldScope(descriptor), false); (*variables)["declared_type"] = DeclaredTypeMethodName(descriptor->type()); (*variables)["field_member"] = FieldName(descriptor) + "_"; - (*variables)["tag_size"] = SimpleItoa( - WireFormat::TagSize(descriptor->number(), descriptor->type())); - (*variables)["deprecation"] = descriptor->options().deprecated() - ? " PROTOBUF_DEPRECATED" : ""; - (*variables)["deprecated_attr"] = descriptor->options().deprecated() - ? "GOOGLE_PROTOBUF_DEPRECATED_ATTR " : ""; + (*variables)["tag_size"] = StrCat( + WireFormat::TagSize(descriptor->number(), descriptor->type())); + (*variables)["deprecated_attr"] = + DeprecatedAttribute(options, descriptor->options().deprecated()); + (*variables)["set_hasbit"] = ""; + (*variables)["clear_hasbit"] = ""; if (HasFieldPresence(descriptor->file())) { - (*variables)["set_hasbit"] = - "set_has_" + FieldName(descriptor) + "();"; - (*variables)["clear_hasbit"] = - "clear_has_" + FieldName(descriptor) + "();"; + (*variables)["set_hasbit_io"] = + "HasBitSetters::set_has_" + FieldName(descriptor) + "(&_has_bits_);"; } else { - (*variables)["set_hasbit"] = ""; - (*variables)["clear_hasbit"] = ""; + (*variables)["set_hasbit_io"] = ""; } // These variables are placeholders to pick out the beginning and ends of @@ -91,17 +90,31 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor, (*variables)["}"] = ""; } -void SetCommonOneofFieldVariables(const FieldDescriptor* descriptor, - std::map* variables) { - const string prefix = descriptor->containing_oneof()->name() + "_."; +void FieldGenerator::SetHasBitIndex(int32 has_bit_index) { + if (!HasFieldPresence(descriptor_->file()) || has_bit_index == -1) { + return; + } + variables_["set_hasbit"] = StrCat( + "_has_bits_[", has_bit_index / 32, "] |= 0x", + strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8), "u;"); + variables_["clear_hasbit"] = StrCat( + "_has_bits_[", has_bit_index / 32, "] &= ~0x", + strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8), "u;"); +} + +void SetCommonOneofFieldVariables( + const FieldDescriptor* descriptor, + std::map* variables) { + const std::string prefix = descriptor->containing_oneof()->name() + "_."; (*variables)["oneof_name"] = descriptor->containing_oneof()->name(); - (*variables)["field_member"] = StrCat(prefix, (*variables)["name"], "_"); + (*variables)["field_member"] = + StrCat(prefix, (*variables)["name"], "_"); } FieldGenerator::~FieldGenerator() {} -void FieldGenerator:: -GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const { +void FieldGenerator::GenerateMergeFromCodedStreamWithPacking( + io::Printer* printer) const { // Reaching here indicates a bug. Cases are: // - This FieldGenerator should support packing, but this method should be // overridden. @@ -109,15 +122,12 @@ GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const { // never have been called. GOOGLE_LOG(FATAL) << "GenerateMergeFromCodedStreamWithPacking() " << "called on field generator that does not support packing."; - } FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor, const Options& options, - SCCAnalyzer* scc_analyzer) - : descriptor_(descriptor), - options_(options), - field_generators_(descriptor->field_count()) { + MessageSCCAnalyzer* scc_analyzer) + : descriptor_(descriptor), field_generators_(descriptor->field_count()) { // Construct all the FieldGenerators. for (int i = 0; i < descriptor->field_count(); i++) { field_generators_[i].reset( @@ -125,9 +135,22 @@ FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor, } } -FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field, - const Options& options, - SCCAnalyzer* scc_analyzer) { +FieldGenerator* FieldGeneratorMap::MakeGoogleInternalGenerator( + const FieldDescriptor* field, const Options& options, + MessageSCCAnalyzer* scc_analyzer) { + + return nullptr; +} + +FieldGenerator* FieldGeneratorMap::MakeGenerator( + const FieldDescriptor* field, const Options& options, + MessageSCCAnalyzer* scc_analyzer) { + FieldGenerator* generator = + MakeGoogleInternalGenerator(field, options, scc_analyzer); + if (generator) { + return generator; + } + if (field->is_repeated()) { switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_MESSAGE: @@ -138,11 +161,7 @@ FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field, scc_analyzer); } case FieldDescriptor::CPPTYPE_STRING: - switch (field->options().ctype()) { - default: // RepeatedStringFieldGenerator handles unknown ctypes. - case FieldOptions::STRING: - return new RepeatedStringFieldGenerator(field, options); - } + return new RepeatedStringFieldGenerator(field, options); case FieldDescriptor::CPPTYPE_ENUM: return new RepeatedEnumFieldGenerator(field, options); default: @@ -153,11 +172,7 @@ FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field, case FieldDescriptor::CPPTYPE_MESSAGE: return new MessageOneofFieldGenerator(field, options, scc_analyzer); case FieldDescriptor::CPPTYPE_STRING: - switch (field->options().ctype()) { - default: // StringOneofFieldGenerator handles unknown ctypes. - case FieldOptions::STRING: - return new StringOneofFieldGenerator(field, options); - } + return new StringOneofFieldGenerator(field, options); case FieldDescriptor::CPPTYPE_ENUM: return new EnumOneofFieldGenerator(field, options); default: @@ -168,11 +183,7 @@ FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field, case FieldDescriptor::CPPTYPE_MESSAGE: return new MessageFieldGenerator(field, options, scc_analyzer); case FieldDescriptor::CPPTYPE_STRING: - switch (field->options().ctype()) { - default: // StringFieldGenerator handles unknown ctypes. - case FieldOptions::STRING: - return new StringFieldGenerator(field, options); - } + return new StringFieldGenerator(field, options); case FieldDescriptor::CPPTYPE_ENUM: return new EnumFieldGenerator(field, options); default: diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_field.h b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_field.h index 8cdbe886..c66bddc4 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_field.h @@ -45,11 +45,13 @@ namespace google { namespace protobuf { - namespace io { - class Printer; // printer.h - } +namespace io { +class Printer; // printer.h } +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace cpp { @@ -59,15 +61,18 @@ namespace cpp { // ['name', 'index', 'number', 'classname', 'declared_type', 'tag_size', // 'deprecation']. void SetCommonFieldVariables(const FieldDescriptor* descriptor, - std::map* variables, + std::map* variables, const Options& options); -void SetCommonOneofFieldVariables(const FieldDescriptor* descriptor, - std::map* variables); +void SetCommonOneofFieldVariables( + const FieldDescriptor* descriptor, + std::map* variables); class FieldGenerator { public: - explicit FieldGenerator(const Options& options) : options_(options) {} + explicit FieldGenerator(const FieldDescriptor* descriptor, + const Options& options) + : descriptor_(descriptor), options_(options) {} virtual ~FieldGenerator(); // Generate lines of code declaring members fields of the message class @@ -95,17 +100,27 @@ class FieldGenerator { virtual void GenerateNonInlineAccessorDefinitions( io::Printer* /*printer*/) const {} + // Generate declarations of accessors that are for internal purposes only. + // Most field types don't need this, so the default implementation is empty. + virtual void GenerateInternalAccessorDefinitions( + io::Printer* /*printer*/) const {} + + // Generate definitions of accessors that are for internal purposes only. + // Most field types don't need this, so the default implementation is empty. + virtual void GenerateInternalAccessorDeclarations( + io::Printer* /*printer*/) const {} + // Generate lines of code (statements, not declarations) which clear the // field. This is used to define the clear_$name$() method virtual void GenerateClearingCode(io::Printer* printer) const = 0; - // Generate lines of code (statements, not declarations) which clear the field - // as part of the Clear() method for the whole message. For message types - // which have field presence bits, MessageGenerator::GenerateClear will have - // already checked the presence bits. + // Generate lines of code (statements, not declarations) which clear the + // field as part of the Clear() method for the whole message. For message + // types which have field presence bits, MessageGenerator::GenerateClear + // will have already checked the presence bits. // - // Since most field types can re-use GenerateClearingCode, this method is not - // pure virtual. + // Since most field types can re-use GenerateClearingCode, this method is + // not pure virtual. virtual void GenerateMessageClearingCode(io::Printer* printer) const { GenerateClearingCode(printer); } @@ -140,17 +155,17 @@ class FieldGenerator { // Generate a manual destructor invocation for use when the message is on an // arena. The code that this method generates will be executed inside a - // shared-for-the-whole-message-class method registered with OwnDestructor(). - // The method should return |true| if it generated any code that requires a - // call; this allows the message generator to eliminate the OwnDestructor() - // registration if no fields require it. + // shared-for-the-whole-message-class method registered with + // OwnDestructor(). The method should return |true| if it generated any code + // that requires a call; this allows the message generator to eliminate the + // OwnDestructor() registration if no fields require it. virtual bool GenerateArenaDestructorCode(io::Printer* printer) const { return false; } // Generate code that allocates the fields's default instance. - virtual void GenerateDefaultInstanceAllocator(io::Printer* /*printer*/) - const {} + virtual void GenerateDefaultInstanceAllocator( + io::Printer* /*printer*/) const {} // Generate lines to decode this field, which will be placed inside the // message's MergeFromCodedStream() method. @@ -162,8 +177,8 @@ class FieldGenerator { // Generate lines to decode this field from a packed value, which will be // placed inside the message's MergeFromCodedStream() method. - virtual void GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) - const; + virtual void GenerateMergeFromCodedStreamWithPacking( + io::Printer* printer) const; // Generate lines to serialize this field, which are placed within the // message's SerializeWithCachedSizes() method. @@ -184,8 +199,12 @@ class FieldGenerator { virtual uint32 CalculateFieldTag() const { return 0; } virtual bool IsInlined() const { return false; } + void SetHasBitIndex(int32 has_bit_index); + protected: + const FieldDescriptor* descriptor_; const Options& options_; + std::map variables_; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator); @@ -195,19 +214,27 @@ class FieldGenerator { class FieldGeneratorMap { public: FieldGeneratorMap(const Descriptor* descriptor, const Options& options, - SCCAnalyzer* scc_analyzer); + MessageSCCAnalyzer* scc_analyzer); ~FieldGeneratorMap(); const FieldGenerator& get(const FieldDescriptor* field) const; + void SetHasBitIndices(const std::vector& has_bit_indices_) { + for (int i = 0; i < descriptor_->field_count(); ++i) { + field_generators_[i]->SetHasBitIndex(has_bit_indices_[i]); + } + } + private: const Descriptor* descriptor_; - const Options& options_; std::vector> field_generators_; + static FieldGenerator* MakeGoogleInternalGenerator( + const FieldDescriptor* field, const Options& options, + MessageSCCAnalyzer* scc_analyzer); static FieldGenerator* MakeGenerator(const FieldDescriptor* field, const Options& options, - SCCAnalyzer* scc_analyzer); + MessageSCCAnalyzer* scc_analyzer); GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap); }; @@ -215,6 +242,6 @@ class FieldGeneratorMap { } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_file.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_file.cc index 42525687..08b9f288 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_file.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_file.cc @@ -44,79 +44,124 @@ #include #include #include +#include #include #include #include + + +#include + namespace google { namespace protobuf { namespace compiler { namespace cpp { +namespace { + +// When we forward-declare things, we want to create a sorted order so our +// output is deterministic and minimizes namespace changes. +template +std::string GetSortKey(const T& val) { + return val.full_name(); +} + +template <> +std::string GetSortKey(const FileDescriptor& val) { + return val.name(); +} + +template <> +std::string GetSortKey(const SCC& val) { + return val.GetRepresentative()->full_name(); +} + +template +bool CompareSortKeys(const T* a, const T* b) { + return GetSortKey(*a) < GetSortKey(*b); +} + +template +std::vector Sorted(const std::unordered_set& vals) { + std::vector sorted(vals.begin(), vals.end()); + std::sort(sorted.begin(), sorted.end(), CompareSortKeys); + return sorted; +} + +} // namespace + FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options) - : file_(file), - options_(options), - scc_analyzer_(options), - enum_generators_owner_( - new std::unique_ptr[file->enum_type_count()]), - service_generators_owner_( - new std::unique_ptr[file->service_count()]), - extension_generators_owner_( - new std::unique_ptr[file->extension_count()]) { + : file_(file), options_(options), scc_analyzer_(options) { + // These variables are the same on a file level + SetCommonVars(options, &variables_); + variables_["dllexport_decl"] = options.dllexport_decl; + variables_["tablename"] = UniqueName("TableStruct", file_, options_); + variables_["file_level_metadata"] = + UniqueName("file_level_metadata", file_, options_); + variables_["desc_table"] = DescriptorTableName(file_, options_); + variables_["file_level_enum_descriptors"] = + UniqueName("file_level_enum_descriptors", file_, options_); + variables_["file_level_service_descriptors"] = + UniqueName("file_level_service_descriptors", file_, options_); + variables_["filename"] = file_->name(); + variables_["package_ns"] = Namespace(file_, options); + std::vector msgs = FlattenMessagesInFile(file); for (int i = 0; i < msgs.size(); i++) { // Deleted in destructor MessageGenerator* msg_gen = - new MessageGenerator(msgs[i], i, options, &scc_analyzer_); - message_generators_.push_back(msg_gen); + new MessageGenerator(msgs[i], variables_, i, options, &scc_analyzer_); + message_generators_.emplace_back(msg_gen); msg_gen->AddGenerators(&enum_generators_, &extension_generators_); } for (int i = 0; i < file->enum_type_count(); i++) { - enum_generators_owner_[i].reset( - new EnumGenerator(file->enum_type(i), options)); - enum_generators_.push_back(enum_generators_owner_[i].get()); + enum_generators_.emplace_back( + new EnumGenerator(file->enum_type(i), variables_, options)); } for (int i = 0; i < file->service_count(); i++) { - service_generators_owner_[i].reset( - new ServiceGenerator(file->service(i), options)); - service_generators_.push_back(service_generators_owner_[i].get()); + service_generators_.emplace_back( + new ServiceGenerator(file->service(i), variables_, options)); } if (HasGenericServices(file_, options_)) { for (int i = 0; i < service_generators_.size(); i++) { service_generators_[i]->index_in_metadata_ = i; } } - for (int i = 0; i < file->extension_count(); i++) { - extension_generators_owner_[i].reset( + extension_generators_.emplace_back( new ExtensionGenerator(file->extension(i), options)); - extension_generators_.push_back(extension_generators_owner_[i].get()); } - - - package_parts_ = Split(file_->package(), ".", true); -} - -FileGenerator::~FileGenerator() { + for (int i = 0; i < file->weak_dependency_count(); ++i) { + weak_deps_.insert(file->weak_dependency(i)); + } for (int i = 0; i < message_generators_.size(); i++) { - delete message_generators_[i]; + if (IsSCCRepresentative(message_generators_[i]->descriptor_)) { + sccs_.push_back(GetSCC(message_generators_[i]->descriptor_)); + } } + + std::sort(sccs_.begin(), sccs_.end(), CompareSortKeys); } +FileGenerator::~FileGenerator() = default; + void FileGenerator::GenerateMacroUndefs(io::Printer* printer) { + Formatter format(printer, variables_); // Only do this for protobuf's own types. There are some google3 protos using // macros as field names and the generated code compiles after the macro // expansion. Undefing these macros actually breaks such code. - if (file_->name() != "google/protobuf/compiler/plugin.proto") { + if (file_->name() != "net/proto2/compiler/proto/plugin.proto" && + file_->name() != "google/protobuf/compiler/plugin.proto") { return; } - std::vector names_to_undef; + std::vector names_to_undef; std::vector fields; ListAllFields(file_, &fields); for (int i = 0; i < fields.size(); i++) { - const string& name = fields[i]->name(); + const std::string& name = fields[i]->name(); static const char* kMacroNames[] = {"major", "minor"}; for (int i = 0; i < GOOGLE_ARRAYSIZE(kMacroNames); ++i) { if (name == kMacroNames[i]) { @@ -126,330 +171,429 @@ void FileGenerator::GenerateMacroUndefs(io::Printer* printer) { } } for (int i = 0; i < names_to_undef.size(); ++i) { - printer->Print( - "#ifdef $name$\n" - "#undef $name$\n" + format( + "#ifdef $1$\n" + "#undef $1$\n" "#endif\n", - "name", names_to_undef[i]); + names_to_undef[i]); } } void FileGenerator::GenerateHeader(io::Printer* printer) { - printer->Print( - "// @@protoc_insertion_point(includes)\n"); + Formatter format(printer, variables_); - printer->Print("#define PROTOBUF_INTERNAL_EXPORT_$filename$ $export$\n", - "filename", FileLevelNamespace(file_), - "export", options_.dllexport_decl); + // port_def.inc must be included after all other includes. + IncludeFile("net/proto2/public/port_def.inc", printer); + format("#define $1$$ dllexport_decl$\n", FileDllExport(file_, options_)); GenerateMacroUndefs(printer); + // For Any support with lite protos, we need to friend AnyMetadata, so we + // forward-declare it here. + format( + "PROTOBUF_NAMESPACE_OPEN\n" + "namespace internal {\n" + "class AnyMetadata;\n" + "} // namespace internal\n" + "PROTOBUF_NAMESPACE_CLOSE\n"); + GenerateGlobalStateFunctionDeclarations(printer); GenerateForwardDeclarations(printer); { - NamespaceOpener ns(Namespace(file_), printer); + NamespaceOpener ns(Namespace(file_, options_), format); - printer->Print("\n"); + format("\n"); GenerateEnumDefinitions(printer); - printer->Print(kThickSeparator); - printer->Print("\n"); + format(kThickSeparator); + format("\n"); GenerateMessageDefinitions(printer); - printer->Print("\n"); - printer->Print(kThickSeparator); - printer->Print("\n"); + format("\n"); + format(kThickSeparator); + format("\n"); GenerateServiceDefinitions(printer); GenerateExtensionIdentifiers(printer); - printer->Print("\n"); - printer->Print(kThickSeparator); - printer->Print("\n"); + format("\n"); + format(kThickSeparator); + format("\n"); GenerateInlineFunctionDefinitions(printer); - printer->Print( - "\n" - "// @@protoc_insertion_point(namespace_scope)\n" - "\n"); + format( + "\n" + "// @@protoc_insertion_point(namespace_scope)\n" + "\n"); } // We need to specialize some templates in the ::google::protobuf namespace: GenerateProto2NamespaceEnumSpecializations(printer); - printer->Print( - "\n" - "// @@protoc_insertion_point(global_scope)\n" - "\n"); + format( + "\n" + "// @@protoc_insertion_point(global_scope)\n" + "\n"); + IncludeFile("net/proto2/public/port_undef.inc", printer); } void FileGenerator::GenerateProtoHeader(io::Printer* printer, - const string& info_path) { + const std::string& info_path) { + Formatter format(printer, variables_); if (!options_.proto_h) { return; } - string filename_identifier = FilenameIdentifier(file_->name()); - GenerateTopHeaderGuard(printer, filename_identifier); + GenerateTopHeaderGuard(printer, false); + if (!options_.opensource_runtime) { + format( + "#ifdef SWIG\n" + "#error \"Do not SWIG-wrap protobufs.\"\n" + "#endif // SWIG\n" + "\n"); + } + + if (IsBootstrapProto(options_, file_)) { + format("// IWYU pragma: private, include \"$1$.proto.h\"\n\n", + StripProto(file_->name())); + } GenerateLibraryIncludes(printer); for (int i = 0; i < file_->public_dependency_count(); i++) { const FileDescriptor* dep = file_->public_dependency(i); - const char* extension = ".proto.h"; - string dependency = StripProto(dep->name()) + extension; - printer->Print( - "#include \"$dependency$\" // IWYU pragma: export\n", - "dependency", dependency); + format("#include \"$1$.proto.h\"\n", StripProto(dep->name())); } + format("// @@protoc_insertion_point(includes)\n"); + GenerateMetadataPragma(printer, info_path); GenerateHeader(printer); - GenerateBottomHeaderGuard(printer, filename_identifier); + GenerateBottomHeaderGuard(printer, false); } void FileGenerator::GeneratePBHeader(io::Printer* printer, - const string& info_path) { - string filename_identifier = - FilenameIdentifier(file_->name() + (options_.proto_h ? ".pb.h" : "")); - GenerateTopHeaderGuard(printer, filename_identifier); + const std::string& info_path) { + Formatter format(printer, variables_); + GenerateTopHeaderGuard(printer, true); if (options_.proto_h) { - string target_basename = StripProto(file_->name()); - printer->Print("#include \"$basename$.proto.h\" // IWYU pragma: export\n", - "basename", target_basename); + std::string target_basename = StripProto(file_->name()); + if (!options_.opensource_runtime) { + GetBootstrapBasename(options_, target_basename, &target_basename); + } + format("#include \"$1$.proto.h\" // IWYU pragma: export\n", + target_basename); } else { GenerateLibraryIncludes(printer); } - GenerateDependencyIncludes(printer); + if (options_.transitive_pb_h) { + GenerateDependencyIncludes(printer); + } + + // This is unfortunately necessary for some plugins. I don't see why we + // need two of the same insertion points. + // TODO(gerbens) remove this. + format("// @@protoc_insertion_point(includes)\n"); + GenerateMetadataPragma(printer, info_path); if (!options_.proto_h) { GenerateHeader(printer); } else { - // This is unfortunately necessary for some plugins. I don't see why we - // need two of the same insertion points. - // TODO(gerbens) remove this. - printer->Print( - "// @@protoc_insertion_point(includes)\n"); { - NamespaceOpener ns(Namespace(file_), printer); - printer->Print( - "\n" - "// @@protoc_insertion_point(namespace_scope)\n"); + NamespaceOpener ns(Namespace(file_, options_), format); + format( + "\n" + "// @@protoc_insertion_point(namespace_scope)\n"); } - printer->Print( - "\n" - "// @@protoc_insertion_point(global_scope)\n" - "\n"); + format( + "\n" + "// @@protoc_insertion_point(global_scope)\n" + "\n"); } - GenerateBottomHeaderGuard(printer, filename_identifier); + GenerateBottomHeaderGuard(printer, true); +} + +void FileGenerator::DoIncludeFile(const std::string& google3_name, + bool do_export, io::Printer* printer) { + Formatter format(printer, variables_); + const std::string prefix = "net/proto2/"; + GOOGLE_CHECK(google3_name.find(prefix) == 0) << google3_name; + + if (options_.opensource_runtime) { + std::string path = google3_name.substr(prefix.size()); + + path = StringReplace(path, "internal/", "", false); + path = StringReplace(path, "proto/", "", false); + path = StringReplace(path, "public/", "", false); + if (options_.runtime_include_base.empty()) { + format("#include ", path); + } else { + format("#include \"$1$google/protobuf/$2$\"", + options_.runtime_include_base, path); + } + } else { + format("#include \"$1$\"", google3_name); + } + + if (do_export) { + format(" // IWYU pragma: export"); + } + + format("\n"); +} + +std::string FileGenerator::CreateHeaderInclude(const std::string& basename, + const FileDescriptor* file) { + bool use_system_include = false; + std::string name = basename; + + if (options_.opensource_runtime) { + if (IsWellKnownMessage(file)) { + if (options_.runtime_include_base.empty()) { + use_system_include = true; + } else { + name = options_.runtime_include_base + basename; + } + } + } + + std::string left = "\""; + std::string right = "\""; + if (use_system_include) { + left = "<"; + right = ">"; + } + return left + name + right; } void FileGenerator::GenerateSourceIncludes(io::Printer* printer) { - string target_basename = StripProto(file_->name()); - const bool use_system_include = IsWellKnownMessage(file_); + Formatter format(printer, variables_); + std::string target_basename = StripProto(file_->name()); + if (!options_.opensource_runtime) { + GetBootstrapBasename(options_, target_basename, &target_basename); + } + target_basename += options_.proto_h ? ".proto.h" : ".pb.h"; + format( + "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" + "// source: $filename$\n" + "\n" + "#include $1$\n" + "\n" + "#include \n" // for swap() + "\n", + CreateHeaderInclude(target_basename, file_)); - string header = target_basename + (options_.proto_h ? ".proto.h" : ".pb.h"); - printer->Print( - "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" - "// source: $filename$\n" - "\n" - "#include $left$$header$$right$\n" - "\n" - "#include \n" // for swap() - "\n" - "#include \n" - "#include \n" - "#include \n" - "#include \n", - "filename", file_->name(), - "header", header, - "left", use_system_include ? "<" : "\"", - "right", use_system_include ? ">" : "\""); + if (options_.opensource_runtime) { + DoIncludeFile("net/proto2/public/stubs/common.h", false, printer); + } + + IncludeFile("net/proto2/io/public/coded_stream.h", printer); + // TODO(gerbens) This is to include parse_context.h, we need a better way + IncludeFile("net/proto2/public/extension_set.h", printer); + IncludeFile("net/proto2/public/wire_format_lite.h", printer); // Unknown fields implementation in lite mode uses StringOutputStream if (!UseUnknownFieldSet(file_, options_) && !message_generators_.empty()) { - printer->Print( - "#include \n"); + IncludeFile("net/proto2/io/public/zero_copy_stream_impl_lite.h", printer); } if (HasDescriptorMethods(file_, options_)) { - printer->Print( - "#include \n" - "#include \n" - "#include \n" - "#include \n"); + IncludeFile("net/proto2/public/descriptor.h", printer); + IncludeFile("net/proto2/public/generated_message_reflection.h", printer); + IncludeFile("net/proto2/public/reflection_ops.h", printer); + IncludeFile("net/proto2/public/wire_format.h", printer); + } + if (IsProto2MessageSetFile(file_, options_)) { + format( + // Implementation of proto1 MessageSet API methods. + "#include \"net/proto2/bridge/internal/message_set_util.h\"\n"); } if (options_.proto_h) { // Use the smaller .proto.h files. for (int i = 0; i < file_->dependency_count(); i++) { const FileDescriptor* dep = file_->dependency(i); - const char* extension = ".proto.h"; - string basename = StripProto(dep->name()); - string dependency = basename + extension; - printer->Print( - "#include \"$dependency$\"\n", - "dependency", dependency); + // Do not import weak deps. + if (!options_.opensource_runtime && IsDepWeak(dep)) continue; + std::string basename = StripProto(dep->name()); + if (IsBootstrapProto(options_, file_)) { + GetBootstrapBasename(options_, basename, &basename); + } + format("#include \"$1$.proto.h\"\n", basename); } } - // TODO(gerbens) Remove this when all code in google is using the same - // proto library. This is a temporary hack to force build errors if - // the proto library is compiled with GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - // and is also linking internal proto2. This is to prevent regressions while - // we work cleaning up the code base. After this is completed and we have - // one proto lib all code uses this should be removed. - printer->Print( - "// This is a temporary google only hack\n" - "#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS\n" - "#include \"third_party/protobuf/version.h\"\n" - "#endif\n"); - - printer->Print( - "// @@protoc_insertion_point(includes)\n"); + format("// @@protoc_insertion_point(includes)\n"); + IncludeFile("net/proto2/public/port_def.inc", printer); } void FileGenerator::GenerateSourceDefaultInstance(int idx, io::Printer* printer) { - printer->Print( - "class $classname$DefaultTypeInternal {\n" + Formatter format(printer, variables_); + format( + "class $1$ {\n" " public:\n" - " ::google::protobuf::internal::ExplicitlyConstructed<$classname$>\n" - " _instance;\n", - "classname", message_generators_[idx]->classname_); - printer->Indent(); + " ::$proto_ns$::internal::ExplicitlyConstructed<$2$> _instance;\n", + DefaultInstanceType(message_generators_[idx]->descriptor_, options_), + message_generators_[idx]->classname_); + format.Indent(); message_generators_[idx]->GenerateExtraDefaultFields(printer); - printer->Outdent(); - printer->Print("} _$classname$_default_instance_;\n", "classname", - message_generators_[idx]->classname_); + format.Outdent(); + format("} $1$;\n", + DefaultInstanceName(message_generators_[idx]->descriptor_, options_)); } -namespace { +// A list of things defined in one .pb.cc file that we need to reference from +// another .pb.cc file. +struct FileGenerator::CrossFileReferences { + // Populated if we are referencing from messages or files. + std::unordered_set strong_sccs; + std::unordered_set weak_sccs; + std::unordered_set weak_default_instances; -// Generates weak symbol declarations for types that are to be considered weakly -// referenced. -void GenerateInternalForwardDeclarations( - const std::vector& fields, const Options& options, - SCCAnalyzer* scc_analyzer, io::Printer* printer) { - // To ensure determinism and minimize the number of namespace statements, - // we output the forward declarations sorted on namespace and type / function - // name. - std::set > messages; - std::set > sccs; - std::set > inits; - for (int i = 0; i < fields.size(); ++i) { - const FieldDescriptor* field = fields[i]; - const Descriptor* msg = field->message_type(); - if (msg == nullptr) continue; - bool is_weak = IsImplicitWeakField(field, options, scc_analyzer); - string flns = FileLevelNamespace(msg); - auto scc = scc_analyzer->GetSCC(msg); - string repr = ClassName(scc->GetRepresentative()); - string weak_attr; - if (is_weak) { - inits.insert(std::make_pair(flns, "AddDescriptors")); - messages.insert(std::make_pair(Namespace(msg), ClassName(msg))); - weak_attr = " __attribute__((weak))"; + // Only if we are referencing from files. + std::unordered_set strong_reflection_files; + std::unordered_set weak_reflection_files; +}; + +void FileGenerator::GetCrossFileReferencesForField(const FieldDescriptor* field, + CrossFileReferences* refs) { + const Descriptor* msg = field->message_type(); + if (msg == nullptr) return; + const SCC* scc = GetSCC(msg); + + if (IsImplicitWeakField(field, options_, &scc_analyzer_) || + IsWeak(field, options_)) { + refs->weak_sccs.insert(scc); + refs->weak_default_instances.insert(msg); + } else { + refs->strong_sccs.insert(scc); + // We don't need to declare default instances, because it is declared in the + // .proto.h file we imported. + } +} + +void FileGenerator::GetCrossFileReferencesForFile(const FileDescriptor* file, + CrossFileReferences* refs) { + ForEachField(file, [this, refs](const FieldDescriptor* field) { + GetCrossFileReferencesForField(field, refs); + }); + + if (!HasDescriptorMethods(file, options_)) return; + + for (int i = 0; i < file->dependency_count(); i++) { + const FileDescriptor* dep = file->dependency(i); + if (IsDepWeak(dep)) { + refs->weak_reflection_files.insert(dep); + } else { + refs->strong_reflection_files.insert(dep); } - string dllexport = "PROTOBUF_INTERNAL_EXPORT_" + FileLevelNamespace(msg); - sccs.insert(std::make_pair(flns, "extern " + dllexport + weak_attr + - " ::google::protobuf::internal::SCCInfo<" + - SimpleItoa(scc->children.size()) + - "> scc_info_" + repr + ";\n")); - } - - printer->Print("\n"); - NamespaceOpener ns(printer); - for (std::set >::const_iterator it = - messages.begin(); - it != messages.end(); ++it) { - ns.ChangeTo(it->first); - printer->Print( - "extern __attribute__((weak)) $classname$DefaultTypeInternal " - "_$classname$_default_instance_;\n", - "classname", it->second); - } - for (std::set >::const_iterator it = inits.begin(); - it != inits.end(); ++it) { - ns.ChangeTo(it->first); - printer->Print("void $name$() __attribute__((weak));\n", - "name", it->second); - } - for (const auto& p : sccs) { - ns.ChangeTo(p.first); - printer->Print(p.second.c_str()); } } -} // namespace +// Generates references to variables defined in other files. +void FileGenerator::GenerateInternalForwardDeclarations( + const CrossFileReferences& refs, io::Printer* printer) { + Formatter format(printer, variables_); + + for (auto scc : Sorted(refs.strong_sccs)) { + format("extern $1$ ::$proto_ns$::internal::SCCInfo<$2$> $3$;\n", + FileDllExport(scc->GetFile(), options_), scc->children.size(), + SccInfoSymbol(scc, options_)); + } + + for (auto scc : Sorted(refs.weak_sccs)) { + format( + "extern __attribute__((weak)) ::$proto_ns$::internal::SCCInfo<$1$> " + "$2$;\n", + scc->children.size(), SccInfoSymbol(scc, options_)); + } + + { + NamespaceOpener ns(format); + for (auto instance : Sorted(refs.weak_default_instances)) { + ns.ChangeTo(Namespace(instance, options_)); + format("extern __attribute__((weak)) $1$ $2$;\n", + DefaultInstanceType(instance, options_), + DefaultInstanceName(instance, options_)); + } + } + + for (auto file : Sorted(refs.weak_reflection_files)) { + format( + "extern __attribute__((weak)) const " + "::$proto_ns$::internal::DescriptorTable $1$;\n", + DescriptorTableName(file, options_)); + } +} void FileGenerator::GenerateSourceForMessage(int idx, io::Printer* printer) { + Formatter format(printer, variables_); GenerateSourceIncludes(printer); // Generate weak declarations. We do this for the whole strongly-connected // component (SCC), because we have a single InitDefaults* function for the // SCC. - std::vector fields; + CrossFileReferences refs; for (const Descriptor* message : scc_analyzer_.GetSCC(message_generators_[idx]->descriptor_) ->descriptors) { - ListAllFields(message, &fields); + ForEachField(message, [this, &refs](const FieldDescriptor* field) { + GetCrossFileReferencesForField(field, &refs); + }); } - GenerateInternalForwardDeclarations(fields, options_, &scc_analyzer_, - printer); + GenerateInternalForwardDeclarations(refs, printer); if (IsSCCRepresentative(message_generators_[idx]->descriptor_)) { - NamespaceOpener ns(FileLevelNamespace(file_), printer); GenerateInitForSCC(GetSCC(message_generators_[idx]->descriptor_), printer); } { // package namespace - NamespaceOpener ns(Namespace(file_), printer); + NamespaceOpener ns(Namespace(file_, options_), format); // Define default instances GenerateSourceDefaultInstance(idx, printer); if (options_.lite_implicit_weak_fields) { - printer->Print("void $classname$_ReferenceStrong() {}\n", "classname", - message_generators_[idx]->classname_); + format("void $1$_ReferenceStrong() {}\n", + message_generators_[idx]->classname_); } // Generate classes. - printer->Print("\n"); + format("\n"); message_generators_[idx]->GenerateClassMethods(printer); - printer->Print( + format( "\n" "// @@protoc_insertion_point(namespace_scope)\n"); } // end package namespace - printer->Print( - "namespace google {\nnamespace protobuf {\n"); - message_generators_[idx]->GenerateSourceInProto2Namespace(printer); - printer->Print( - "} // namespace protobuf\n} // namespace google\n"); + { + NamespaceOpener proto_ns(ProtobufNamespace(options_), format); + message_generators_[idx]->GenerateSourceInProto2Namespace(printer); + } - printer->Print( + format( "\n" "// @@protoc_insertion_point(global_scope)\n"); } void FileGenerator::GenerateGlobalSource(io::Printer* printer) { + Formatter format(printer, variables_); GenerateSourceIncludes(printer); { - NamespaceOpener ns(FileLevelNamespace(file_), printer); GenerateTables(printer); // Define the code to initialize reflection. This code uses a global @@ -459,7 +603,7 @@ void FileGenerator::GenerateGlobalSource(io::Printer* printer) { } } - NamespaceOpener ns(Namespace(file_), printer); + NamespaceOpener ns(Namespace(file_, options_), format); // Generate enums. for (int i = 0; i < enum_generators_.size(); i++) { @@ -474,66 +618,51 @@ void FileGenerator::GenerateGlobalSource(io::Printer* printer) { if (HasGenericServices(file_, options_)) { // Generate services. for (int i = 0; i < service_generators_.size(); i++) { - if (i == 0) printer->Print("\n"); - printer->Print(kThickSeparator); - printer->Print("\n"); + if (i == 0) format("\n"); + format(kThickSeparator); + format("\n"); service_generators_[i]->GenerateImplementation(printer); } } } void FileGenerator::GenerateSource(io::Printer* printer) { + Formatter format(printer, variables_); GenerateSourceIncludes(printer); - std::vector fields; - ListAllFields(file_, &fields); - GenerateInternalForwardDeclarations(fields, options_, &scc_analyzer_, - printer); + CrossFileReferences refs; + GetCrossFileReferencesForFile(file_, &refs); + GenerateInternalForwardDeclarations(refs, printer); { - NamespaceOpener ns(Namespace(file_), printer); + NamespaceOpener ns(Namespace(file_, options_), format); // Define default instances for (int i = 0; i < message_generators_.size(); i++) { GenerateSourceDefaultInstance(i, printer); if (options_.lite_implicit_weak_fields) { - printer->Print("void $classname$_ReferenceStrong() {}\n", "classname", - message_generators_[i]->classname_); + format("void $1$_ReferenceStrong() {}\n", + message_generators_[i]->classname_); } } } { - NamespaceOpener ns(FileLevelNamespace(file_), printer); GenerateTables(printer); // Now generate the InitDefaults for each SCC. - for (int i = 0; i < message_generators_.size(); i++) { - if (IsSCCRepresentative(message_generators_[i]->descriptor_)) { - GenerateInitForSCC(GetSCC(message_generators_[i]->descriptor_), - printer); - } + for (auto scc : sccs_) { + GenerateInitForSCC(scc, printer); } - printer->Print("void InitDefaults() {\n"); - for (int i = 0; i < message_generators_.size(); i++) { - if (!IsSCCRepresentative(message_generators_[i]->descriptor_)) continue; - string scc_name = ClassName(message_generators_[i]->descriptor_); - printer->Print( - " ::google::protobuf::internal::InitSCC(&scc_info_$scc_name$.base);\n", - "scc_name", scc_name); - } - printer->Print("}\n\n"); - - // Define the code to initialize reflection. This code uses a global - // constructor to register reflection data with the runtime pre-main. if (HasDescriptorMethods(file_, options_)) { + // Define the code to initialize reflection. This code uses a global + // constructor to register reflection data with the runtime pre-main. GenerateReflectionInitializationCode(printer); } } - { - NamespaceOpener ns(Namespace(file_), printer); + NamespaceOpener ns(Namespace(file_, options_), format); // Actually implement the protos @@ -544,18 +673,18 @@ void FileGenerator::GenerateSource(io::Printer* printer) { // Generate classes. for (int i = 0; i < message_generators_.size(); i++) { - printer->Print("\n"); - printer->Print(kThickSeparator); - printer->Print("\n"); + format("\n"); + format(kThickSeparator); + format("\n"); message_generators_[i]->GenerateClassMethods(printer); } if (HasGenericServices(file_, options_)) { // Generate services. for (int i = 0; i < service_generators_.size(); i++) { - if (i == 0) printer->Print("\n"); - printer->Print(kThickSeparator); - printer->Print("\n"); + if (i == 0) format("\n"); + format(kThickSeparator); + format("\n"); service_generators_[i]->GenerateImplementation(printer); } } @@ -565,190 +694,78 @@ void FileGenerator::GenerateSource(io::Printer* printer) { extension_generators_[i]->GenerateDefinition(printer); } - printer->Print( + format( + "\n" + "// @@protoc_insertion_point(namespace_scope)\n"); + } + + { + NamespaceOpener proto_ns(ProtobufNamespace(options_), format); + for (int i = 0; i < message_generators_.size(); i++) { + message_generators_[i]->GenerateSourceInProto2Namespace(printer); + } + } + + format( "\n" - "// @@protoc_insertion_point(namespace_scope)\n"); - } + "// @@protoc_insertion_point(global_scope)\n"); - printer->Print( - "namespace google {\nnamespace protobuf {\n"); - for (int i = 0; i < message_generators_.size(); i++) { - message_generators_[i]->GenerateSourceInProto2Namespace(printer); - } - printer->Print( - "} // namespace protobuf\n} // namespace google\n"); - - printer->Print( - "\n" - "// @@protoc_insertion_point(global_scope)\n"); + IncludeFile("net/proto2/public/port_undef.inc", printer); } -class FileGenerator::ForwardDeclarations { - public: - ~ForwardDeclarations() { - for (std::map::iterator - it = namespaces_.begin(), - end = namespaces_.end(); - it != end; ++it) { - delete it->second; - } - namespaces_.clear(); - } - - ForwardDeclarations* AddOrGetNamespace(const string& ns_name) { - ForwardDeclarations*& ns = namespaces_[ns_name]; - if (ns == nullptr) { - ns = new ForwardDeclarations; - } - return ns; - } - - std::map& classes() { return classes_; } - std::map& enums() { return enums_; } - - void PrintForwardDeclarations(io::Printer* printer, - const Options& options) const { - PrintNestedDeclarations(printer, options); - PrintTopLevelDeclarations(printer, options); - } - - - private: - void PrintNestedDeclarations(io::Printer* printer, - const Options& options) const { - PrintDeclarationsInsideNamespace(printer, options); - for (std::map::const_iterator - it = namespaces_.begin(), - end = namespaces_.end(); - it != end; ++it) { - printer->Print("namespace $nsname$ {\n", - "nsname", it->first); - it->second->PrintNestedDeclarations(printer, options); - printer->Print("} // namespace $nsname$\n", - "nsname", it->first); - } - } - - void PrintTopLevelDeclarations(io::Printer* printer, - const Options& options) const { - PrintDeclarationsOutsideNamespace(printer, options); - for (std::map::const_iterator - it = namespaces_.begin(), - end = namespaces_.end(); - it != end; ++it) { - it->second->PrintTopLevelDeclarations(printer, options); - } - } - - void PrintDeclarationsInsideNamespace(io::Printer* printer, - const Options& options) const { - for (std::map::const_iterator - it = enums_.begin(), - end = enums_.end(); - it != end; ++it) { - printer->Print("enum $enumname$ : int;\n", "enumname", it->first); - printer->Annotate("enumname", it->second); - printer->Print("bool $enumname$_IsValid(int value);\n", "enumname", - it->first); - } - for (std::map::const_iterator - it = classes_.begin(), - end = classes_.end(); - it != end; ++it) { - printer->Print("class $classname$;\n", "classname", it->first); - printer->Annotate("classname", it->second); - - printer->Print( - "class $classname$DefaultTypeInternal;\n" - "$dllexport_decl$" - "extern $classname$DefaultTypeInternal " - "_$classname$_default_instance_;\n", // NOLINT - "dllexport_decl", - options.dllexport_decl.empty() ? "" : options.dllexport_decl + " ", - "classname", - it->first); - if (options.lite_implicit_weak_fields) { - printer->Print("void $classname$_ReferenceStrong();\n", - "classname", it->first); - } - } - } - - void PrintDeclarationsOutsideNamespace(io::Printer* printer, - const Options& options) const { - if (classes_.size() == 0) return; - - printer->Print( - "namespace google {\nnamespace protobuf {\n"); - for (std::map::const_iterator - it = classes_.begin(), - end = classes_.end(); - it != end; ++it) { - const Descriptor* d = it->second; - printer->Print( - "template<> " - "$dllexport_decl$" - "$classname$* Arena::CreateMaybeMessage<$classname$>" - "(Arena*);\n", - "classname", QualifiedClassName(d), "dllexport_decl", - options.dllexport_decl.empty() ? "" : options.dllexport_decl + " "); - } - printer->Print( - "} // namespace protobuf\n} // namespace google\n"); - } - - std::map namespaces_; - std::map classes_; - std::map enums_; -}; - void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { - // AddDescriptors() is a file-level procedure which adds the encoded - // FileDescriptorProto for this .proto file to the global DescriptorPool for - // generated files (DescriptorPool::generated_pool()). It ordinarily runs at - // static initialization time, but is not used at all in LITE_RUNTIME mode. - // - // Its sibling, AssignDescriptors(), actually pulls the compiled - // FileDescriptor from the DescriptorPool and uses it to populate all of - // the global variables which store pointers to the descriptor objects. - // It also constructs the reflection objects. It is called the first time - // anyone calls descriptor() or GetReflection() on one of the types defined - // in the file. + Formatter format(printer, variables_); if (!message_generators_.empty()) { - printer->Print("::google::protobuf::Metadata file_level_metadata[$size$];\n", "size", - SimpleItoa(message_generators_.size())); + format("static ::$proto_ns$::Metadata $file_level_metadata$[$1$];\n", + message_generators_.size()); + } else { + format( + "static " + "constexpr ::$proto_ns$::Metadata* $file_level_metadata$ = nullptr;\n"); } if (!enum_generators_.empty()) { - printer->Print( - "const ::google::protobuf::EnumDescriptor* " - "file_level_enum_descriptors[$size$];\n", - "size", SimpleItoa(enum_generators_.size())); + format( + "static " + "const ::$proto_ns$::EnumDescriptor* " + "$file_level_enum_descriptors$[$1$];\n", + enum_generators_.size()); + } else { + format( + "static " + "constexpr ::$proto_ns$::EnumDescriptor const** " + "$file_level_enum_descriptors$ = nullptr;\n"); } if (HasGenericServices(file_, options_) && file_->service_count() > 0) { - printer->Print( - "const ::google::protobuf::ServiceDescriptor* " - "file_level_service_descriptors[$size$];\n", - "size", SimpleItoa(file_->service_count())); + format( + "static " + "const ::$proto_ns$::ServiceDescriptor* " + "$file_level_service_descriptors$[$1$];\n", + file_->service_count()); + } else { + format( + "static " + "constexpr ::$proto_ns$::ServiceDescriptor const** " + "$file_level_service_descriptors$ = nullptr;\n"); } if (!message_generators_.empty()) { - printer->Print( + format( "\n" - "const ::google::protobuf::uint32 TableStruct::offsets[] " - "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n"); - printer->Indent(); + "const $uint32$ $tablename$::offsets[] " + "PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {\n"); + format.Indent(); std::vector > pairs; pairs.reserve(message_generators_.size()); for (int i = 0; i < message_generators_.size(); i++) { pairs.push_back(message_generators_[i]->GenerateOffsets(printer)); } - printer->Outdent(); - printer->Print( + format.Outdent(); + format( "};\n" - "static const ::google::protobuf::internal::MigrationSchema schemas[] " - "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n"); - printer->Indent(); + "static const ::$proto_ns$::internal::MigrationSchema schemas[] " + "PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {\n"); + format.Indent(); { int offset = 0; for (int i = 0; i < message_generators_.size(); i++) { @@ -757,194 +774,142 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { offset += pairs[i].first; } } - printer->Outdent(); - printer->Print( + format.Outdent(); + format( "};\n" "\nstatic " - "::google::protobuf::Message const * const file_default_instances[] = {\n"); - printer->Indent(); + "::$proto_ns$::Message const * const file_default_instances[] = {\n"); + format.Indent(); for (int i = 0; i < message_generators_.size(); i++) { const Descriptor* descriptor = message_generators_[i]->descriptor_; - printer->Print( + format( "reinterpret_cast(&$ns$::_$classname$_default_instance_),\n", - "classname", ClassName(descriptor), "ns", Namespace(descriptor)); + "::$proto_ns$::Message*>(&$1$::_$2$_default_instance_),\n", + Namespace(descriptor, options_), // 1 + ClassName(descriptor)); // 2 } - printer->Outdent(); - printer->Print( + format.Outdent(); + format( "};\n" "\n"); } else { // we still need these symbols to exist - printer->Print( + format( // MSVC doesn't like empty arrays, so we add a dummy. - "const ::google::protobuf::uint32 TableStruct::offsets[1] = {};\n" - "static const ::google::protobuf::internal::MigrationSchema* schemas = NULL;\n" - "static const ::google::protobuf::Message* const* " - "file_default_instances = NULL;\n" + "const $uint32$ $tablename$::offsets[1] = {};\n" + "static constexpr ::$proto_ns$::internal::MigrationSchema* schemas = " + "nullptr;" + "\n" + "static constexpr ::$proto_ns$::Message* const* " + "file_default_instances = nullptr;\n" "\n"); } // --------------------------------------------------------------- - // protobuf_AssignDescriptorsOnce(): The first time it is called, calls - // AssignDescriptors(). All later times, waits for the first call to - // complete and then returns. - printer->Print( - "void protobuf_AssignDescriptors() {\n" - // Make sure the file has found its way into the pool. If a descriptor - // is requested *during* static init then AddDescriptors() may not have - // been called yet, so we call it manually. Note that it's fine if - // AddDescriptors() is called multiple times. - " AddDescriptors();\n" - " AssignDescriptors(\n" - " \"$filename$\", schemas, file_default_instances, " - "TableStruct::offsets,\n" - " $metadata$, $enum_descriptors$, $service_descriptors$);\n", - "filename", file_->name(), "metadata", - !message_generators_.empty() ? "file_level_metadata" : "NULL", - "enum_descriptors", - !enum_generators_.empty() ? "file_level_enum_descriptors" : "NULL", - "service_descriptors", - HasGenericServices(file_, options_) && file_->service_count() > 0 - ? "file_level_service_descriptors" - : "NULL"); - printer->Print( - "}\n" - "\n" - "void protobuf_AssignDescriptorsOnce() {\n" - " static ::google::protobuf::internal::once_flag once;\n" - " ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);\n" - "}\n" - "\n", - "filename", file_->name(), "metadata", - !message_generators_.empty() ? "file_level_metadata" : "NULL", - "enum_descriptors", - !enum_generators_.empty() ? "file_level_enum_descriptors" : "NULL", - "service_descriptors", - HasGenericServices(file_, options_) && file_->service_count() > 0 - ? "file_level_service_descriptors" - : "NULL"); - - // Only here because of useless string reference that we don't want in - // protobuf_AssignDescriptorsOnce, because that is called from all the - // GetMetadata member methods. - printer->Print( - "void protobuf_RegisterTypes(const ::std::string&) " - "GOOGLE_PROTOBUF_ATTRIBUTE_COLD;\n" - "void protobuf_RegisterTypes(const ::std::string&) {\n" - " protobuf_AssignDescriptorsOnce();\n"); - printer->Indent(); - - // All normal messages can be done generically - if (!message_generators_.empty()) { - printer->Print( - "::google::protobuf::internal::RegisterAllTypes(file_level_metadata, $size$);\n", - "size", SimpleItoa(message_generators_.size())); - } - - printer->Outdent(); - printer->Print( - "}\n" - "\n"); - - // Now generate the AddDescriptors() function. - printer->Print( - "void AddDescriptorsImpl() {\n" - " InitDefaults();\n"); - printer->Indent(); - - // Embed the descriptor. We simply serialize the entire - // FileDescriptorProto - // and embed it as a string literal, which is parsed and built into real - // descriptors at initialization time. - FileDescriptorProto file_proto; - file_->CopyTo(&file_proto); - string file_data; - file_proto.SerializeToString(&file_data); - - printer->Print("static const char descriptor[] " - "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) " - "= {\n"); - printer->Indent(); + // Embed the descriptor. We simply serialize the entire + // FileDescriptorProto/ and embed it as a string literal, which is parsed and + // built into real descriptors at initialization time. + const std::string protodef_name = + UniqueName("descriptor_table_protodef", file_, options_); + format("const char $1$[] =\n", protodef_name); + format.Indent(); + FileDescriptorProto file_proto; + file_->CopyTo(&file_proto); + std::string file_data; + file_proto.SerializeToString(&file_data); + { if (file_data.size() > 65535) { - // Workaround for MSVC: "Error C1091: compiler limit: string exceeds 65535 - // bytes in length". Declare a static array of characters rather than use - // a string literal. Only write 25 bytes per line. + // Workaround for MSVC: "Error C1091: compiler limit: string exceeds + // 65535 bytes in length". Declare a static array of chars rather than + // use a string literal. Only write 25 bytes per line. static const int kBytesPerLine = 25; + format("{ "); for (int i = 0; i < file_data.size();) { for (int j = 0; j < kBytesPerLine && i < file_data.size(); ++i, ++j) { - printer->Print("'$char$', ", "char", - CEscape(file_data.substr(i, 1))); + format("'$1$', ", CEscape(file_data.substr(i, 1))); } - printer->Print("\n"); + format("\n"); } + format("'\\0' }"); // null-terminate } else { // Only write 40 bytes per line. static const int kBytesPerLine = 40; for (int i = 0; i < file_data.size(); i += kBytesPerLine) { - printer->Print(" \"$data$\"\n", "data", - EscapeTrigraphs(CEscape( - file_data.substr(i, kBytesPerLine)))); + format( + "\"$1$\"\n", + EscapeTrigraphs(CEscape(file_data.substr(i, kBytesPerLine)))); } } + format(";\n"); + } + format.Outdent(); - printer->Outdent(); - printer->Print("};\n"); - printer->Print( - "::google::protobuf::DescriptorPool::InternalAddGeneratedFile(\n" - " descriptor, $size$);\n", - "size", SimpleItoa(file_data.size())); + CrossFileReferences refs; + GetCrossFileReferencesForFile(file_, &refs); + int num_deps = + refs.strong_reflection_files.size() + refs.weak_reflection_files.size(); - // Call MessageFactory::InternalRegisterGeneratedFile(). - printer->Print( - "::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(\n" - " \"$filename$\", &protobuf_RegisterTypes);\n", - "filename", file_->name()); + // Build array of DescriptorTable deps. + format( + "static const ::$proto_ns$::internal::DescriptorTable*const " + "$desc_table$_deps[$1$] = {\n", + std::max(num_deps, 1)); - // Call the AddDescriptors() methods for all of our dependencies, to make - // sure they get added first. - for (int i = 0; i < file_->dependency_count(); i++) { - const FileDescriptor* dependency = file_->dependency(i); - // Print the namespace prefix for the dependency. - string file_namespace = FileLevelNamespace(dependency); - // Call its AddDescriptors function. - printer->Print("::$file_namespace$::AddDescriptors();\n", "file_namespace", - file_namespace); + for (auto dep : Sorted(refs.strong_reflection_files)) { + format(" &::$1$,\n", DescriptorTableName(dep, options_)); + } + for (auto dep : Sorted(refs.weak_reflection_files)) { + format(" &::$1$,\n", DescriptorTableName(dep, options_)); } - printer->Outdent(); - printer->Print( - "}\n" - "\n" - "void AddDescriptors() {\n" - " static ::google::protobuf::internal::once_flag once;\n" - " ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);\n" - "}\n"); + format("};\n"); - printer->Print( - "// Force AddDescriptors() to be called at dynamic initialization " - "time.\n" - "struct StaticDescriptorInitializer {\n" - " StaticDescriptorInitializer() {\n" - " AddDescriptors();\n" - " }\n" - "} static_descriptor_initializer;\n"); + // Build array of SCCs from this file. + format( + "static ::$proto_ns$::internal::SCCInfoBase*const " + "$desc_table$_sccs[$1$] = {\n", + std::max(sccs_.size(), 1)); + + for (auto scc : sccs_) { + format(" &$1$.base,\n", SccInfoSymbol(scc, options_)); + } + + format("};\n"); + + // The DescriptorTable itself. + format( + "static ::$proto_ns$::internal::once_flag $desc_table$_once;\n" + "static bool $desc_table$_initialized = false;\n" + "const ::$proto_ns$::internal::DescriptorTable $desc_table$ = {\n" + " &$desc_table$_initialized, $1$, \"$filename$\", $2$,\n" + " &$desc_table$_once, $desc_table$_sccs, $desc_table$_deps, $3$, $4$,\n" + " schemas, file_default_instances, $tablename$::offsets,\n" + " $file_level_metadata$, $5$, $file_level_enum_descriptors$, " + "$file_level_service_descriptors$,\n" + "};\n\n", + protodef_name, file_data.size(), sccs_.size(), num_deps, + message_generators_.size()); + + format( + "// Force running AddDescriptors() at dynamic initialization time.\n" + "static bool $1$ = (" + " ::$proto_ns$::internal::AddDescriptors(&$desc_table$), true);\n", + UniqueName("dynamic_init_dummy", file_, options_)); } void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) { - const string scc_name = ClassName(scc->GetRepresentative()); + Formatter format(printer, variables_); // We use static and not anonymous namespace because symbol names are // substantially shorter. - printer->Print( - "static void InitDefaults$scc_name$() {\n" - " GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n" - , // awkward comma due to macro - "scc_name", scc_name); + format("static void InitDefaults$1$() {\n", SccInfoSymbol(scc, options_)); - printer->Indent(); + if (options_.opensource_runtime) { + format(" GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n"); + } + format.Indent(); // First construct all the necessary default instances. for (int i = 0; i < message_generators_.size(); i++) { @@ -954,17 +919,21 @@ void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) { // TODO(gerbens) This requires this function to be friend. Remove // the need for this. message_generators_[i]->GenerateFieldDefaultInstances(printer); - printer->Print( + format( "{\n" - " void* ptr = &$ns$::_$classname$_default_instance_;\n" - " new (ptr) $ns$::$classname$();\n", - "ns", Namespace(message_generators_[i]->descriptor_), - "classname", ClassName(message_generators_[i]->descriptor_)); - if (!IsMapEntryMessage(message_generators_[i]->descriptor_)) { - printer->Print( - " ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);\n"); + " void* ptr = &$1$;\n" + " new (ptr) $2$();\n", + QualifiedDefaultInstanceName(message_generators_[i]->descriptor_, + options_), + QualifiedClassName(message_generators_[i]->descriptor_, options_)); + if (options_.opensource_runtime && + !IsMapEntryMessage(message_generators_[i]->descriptor_)) { + format( + " " + "::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);" + "\n"); } - printer->Print("}\n"); + format("}\n"); } // TODO(gerbens) make default instances be the same as normal instances. @@ -974,37 +943,35 @@ void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) { if (scc_analyzer_.GetSCC(message_generators_[i]->descriptor_) != scc) { continue; } - printer->Print("$classname$::InitAsDefaultInstance();\n", "classname", - QualifiedClassName(message_generators_[i]->descriptor_)); + format("$1$::InitAsDefaultInstance();\n", + QualifiedClassName(message_generators_[i]->descriptor_, options_)); } - printer->Outdent(); - printer->Print("}\n\n"); + format.Outdent(); + format("}\n\n"); - printer->Print( - "$dllexport_decl$::google::protobuf::internal::SCCInfo<$size$> " - "scc_info_$scc_name$ =\n" - " {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), " - "$size$, InitDefaults$scc_name$}, {", - "size", SimpleItoa(scc->children.size()), "scc_name", - ClassName(scc->GetRepresentative()), "dllexport_decl", - options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " "); + format( + "$dllexport_decl $::$proto_ns$::internal::SCCInfo<$1$> $2$ =\n" + " " + "{{ATOMIC_VAR_INIT(::$proto_ns$::internal::SCCInfoBase::kUninitialized), " + "$1$, InitDefaults$2$}, {", + scc->children.size(), // 1 + SccInfoSymbol(scc, options_)); for (const SCC* child : scc->children) { - auto repr = child->GetRepresentative(); - printer->Print("\n &$ns$::scc_info_$child$.base,", "ns", - FileLevelNamespace(repr), "child", ClassName(repr)); + format("\n &$1$.base,", SccInfoSymbol(child, options_)); } - printer->Print("}};\n\n"); + format("}};\n\n"); } void FileGenerator::GenerateTables(io::Printer* printer) { + Formatter format(printer, variables_); if (options_.table_driven_parsing) { // TODO(ckennelly): Gate this with the same options flag to enable // table-driven parsing. - printer->Print( - "PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTableField\n" - " const TableStruct::entries[] " - "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n"); - printer->Indent(); + format( + "PROTOBUF_CONSTEXPR_VAR ::$proto_ns$::internal::ParseTableField\n" + " const $tablename$::entries[] " + "PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {\n"); + format.Indent(); std::vector entries; size_t count = 0; @@ -1016,17 +983,18 @@ void FileGenerator::GenerateTables(io::Printer* printer) { // We need these arrays to exist, and MSVC does not like empty arrays. if (count == 0) { - printer->Print("{0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0},\n"); + format("{0, 0, 0, ::$proto_ns$::internal::kInvalidMask, 0, 0},\n"); } - printer->Outdent(); - printer->Print( + format.Outdent(); + format( "};\n" "\n" - "PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField\n" - " const TableStruct::aux[] " - "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n"); - printer->Indent(); + "PROTOBUF_CONSTEXPR_VAR " + "::$proto_ns$::internal::AuxillaryParseTableField\n" + " const $tablename$::aux[] " + "PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {\n"); + format.Indent(); std::vector aux_entries; count = 0; @@ -1037,16 +1005,16 @@ void FileGenerator::GenerateTables(io::Printer* printer) { } if (count == 0) { - printer->Print("::google::protobuf::internal::AuxillaryParseTableField(),\n"); + format("::$proto_ns$::internal::AuxillaryParseTableField(),\n"); } - printer->Outdent(); - printer->Print( + format.Outdent(); + format( "};\n" - "PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTable const\n" - " TableStruct::schema[] " - "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n"); - printer->Indent(); + "PROTOBUF_CONSTEXPR_VAR ::$proto_ns$::internal::ParseTable const\n" + " $tablename$::schema[] " + "PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {\n"); + format.Indent(); size_t offset = 0; size_t aux_offset = 0; @@ -1057,20 +1025,21 @@ void FileGenerator::GenerateTables(io::Printer* printer) { } if (message_generators_.empty()) { - printer->Print("{ NULL, NULL, 0, -1, -1, false },\n"); + format("{ nullptr, nullptr, 0, -1, -1, false },\n"); } - printer->Outdent(); - printer->Print( + format.Outdent(); + format( "};\n" "\n"); } if (!message_generators_.empty() && options_.table_driven_serialization) { - printer->Print( - "const ::google::protobuf::internal::FieldMetadata TableStruct::field_metadata[] " + format( + "const ::$proto_ns$::internal::FieldMetadata " + "$tablename$::field_metadata[] " "= {\n"); - printer->Indent(); + format.Indent(); std::vector field_metadata_offsets; int idx = 0; for (int i = 0; i < message_generators_.size(); i++) { @@ -1078,12 +1047,12 @@ void FileGenerator::GenerateTables(io::Printer* printer) { idx += message_generators_[i]->GenerateFieldMetadata(printer); } field_metadata_offsets.push_back(idx); - printer->Outdent(); - printer->Print( + format.Outdent(); + format( "};\n" - "const ::google::protobuf::internal::SerializationTable " - "TableStruct::serialization_table[] = {\n"); - printer->Indent(); + "const ::$proto_ns$::internal::SerializationTable " + "$tablename$::serialization_table[] = {\n"); + format.Indent(); // We rely on the order we layout the tables to match the order we // calculate them with FlattenMessagesInFile, so we check here that // these match exactly. @@ -1092,235 +1061,330 @@ void FileGenerator::GenerateTables(io::Printer* printer) { GOOGLE_CHECK_EQ(calculated_order.size(), message_generators_.size()); for (int i = 0; i < message_generators_.size(); i++) { GOOGLE_CHECK_EQ(calculated_order[i], message_generators_[i]->descriptor_); - printer->Print( - "{$num_fields$, TableStruct::field_metadata + $index$},\n", - "classname", message_generators_[i]->classname_, "num_fields", - SimpleItoa(field_metadata_offsets[i + 1] - field_metadata_offsets[i]), - "index", SimpleItoa(field_metadata_offsets[i])); + format("{$1$, $tablename$::field_metadata + $2$},\n", + field_metadata_offsets[i + 1] - field_metadata_offsets[i], // 1 + field_metadata_offsets[i]); // 2 } - printer->Outdent(); - printer->Print( + format.Outdent(); + format( "};\n" "\n"); } } +class FileGenerator::ForwardDeclarations { + public: + void AddMessage(const Descriptor* d) { classes_[ClassName(d)] = d; } + void AddEnum(const EnumDescriptor* d) { enums_[ClassName(d)] = d; } + + void Print(const Formatter& format, const Options& options) const { + for (const auto& p : enums_) { + const std::string& enumname = p.first; + const EnumDescriptor* enum_desc = p.second; + format( + "enum ${1$$2$$}$ : int;\n" + "bool $2$_IsValid(int value);\n", + enum_desc, enumname); + } + for (const auto& p : classes_) { + const std::string& classname = p.first; + const Descriptor* class_desc = p.second; + format( + "class ${1$$2$$}$;\n" + "class $3$;\n" + "$dllexport_decl $extern $3$ $4$;\n", + class_desc, classname, DefaultInstanceType(class_desc, options), + DefaultInstanceName(class_desc, options)); + if (options.lite_implicit_weak_fields) { + format("void $1$_ReferenceStrong();\n", classname); + } + } + } + + void PrintTopLevelDecl(const Formatter& format, + const Options& options) const { + for (const auto& pair : classes_) { + format( + "template<> $dllexport_decl $" + "$1$* Arena::CreateMaybeMessage<$1$>(Arena*);\n", + QualifiedClassName(pair.second, options)); + } + } + + private: + std::map classes_; + std::map enums_; +}; + +static void PublicImportDFS(const FileDescriptor* fd, + std::unordered_set* fd_set) { + for (int i = 0; i < fd->public_dependency_count(); i++) { + const FileDescriptor* dep = fd->public_dependency(i); + if (fd_set->insert(dep).second) PublicImportDFS(dep, fd_set); + } +} + void FileGenerator::GenerateForwardDeclarations(io::Printer* printer) { - ForwardDeclarations decls; - FillForwardDeclarations(&decls); - decls.PrintForwardDeclarations(printer, options_); + Formatter format(printer, variables_); + std::vector classes; + std::vector enums; + + FlattenMessagesInFile(file_, &classes); // All messages need forward decls. + + if (options_.proto_h) { // proto.h needs extra forward declarations. + // All classes / enums refered to as field members + std::vector fields; + ListAllFields(file_, &fields); + for (int i = 0; i < fields.size(); i++) { + classes.push_back(fields[i]->containing_type()); + classes.push_back(fields[i]->message_type()); + enums.push_back(fields[i]->enum_type()); + } + ListAllTypesForServices(file_, &classes); + } + + // Calculate the set of files whose definitions we get through include. + // No need to forward declare types that are defined in these. + std::unordered_set public_set; + PublicImportDFS(file_, &public_set); + + std::map decls; + for (int i = 0; i < classes.size(); i++) { + const Descriptor* d = classes[i]; + if (d && !public_set.count(d->file())) + decls[Namespace(d, options_)].AddMessage(d); + } + for (int i = 0; i < enums.size(); i++) { + const EnumDescriptor* d = enums[i]; + if (d && !public_set.count(d->file())) + decls[Namespace(d, options_)].AddEnum(d); + } + + + { + NamespaceOpener ns(format); + for (const auto& pair : decls) { + ns.ChangeTo(pair.first); + pair.second.Print(format, options_); + } + } + format("PROTOBUF_NAMESPACE_OPEN\n"); + for (const auto& pair : decls) { + pair.second.PrintTopLevelDecl(format, options_); + } + format("PROTOBUF_NAMESPACE_CLOSE\n"); } -void FileGenerator::FillForwardDeclarations(ForwardDeclarations* decls) { - for (int i = 0; i < package_parts_.size(); i++) { - decls = decls->AddOrGetNamespace(package_parts_[i]); - } - // Generate enum definitions. - for (int i = 0; i < enum_generators_.size(); i++) { - enum_generators_[i]->FillForwardDeclaration(&decls->enums()); - } - // Generate forward declarations of classes. - for (int i = 0; i < message_generators_.size(); i++) { - message_generators_[i]->FillMessageForwardDeclarations( - &decls->classes()); - } -} - -void FileGenerator::GenerateTopHeaderGuard(io::Printer* printer, - const string& filename_identifier) { +void FileGenerator::GenerateTopHeaderGuard(io::Printer* printer, bool pb_h) { + Formatter format(printer, variables_); // Generate top of header. - printer->Print( + format( "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" "// source: $filename$\n" "\n" - "#ifndef PROTOBUF_INCLUDED_$filename_identifier$\n" - "#define PROTOBUF_INCLUDED_$filename_identifier$\n" + "#ifndef $1$\n" + "#define $1$\n" "\n" + "#include \n" "#include \n", - "filename", file_->name(), "filename_identifier", filename_identifier); - printer->Print("\n"); + IncludeGuard(file_, pb_h, options_)); + if (!options_.opensource_runtime && !enum_generators_.empty()) { + // Add header to provide std::is_integral for safe Enum_Name() function. + format("#include \n"); + } + format("\n"); } -void FileGenerator::GenerateBottomHeaderGuard( - io::Printer* printer, const string& filename_identifier) { - printer->Print( - "#endif // PROTOBUF_INCLUDED_$filename_identifier$\n", - "filename_identifier", filename_identifier); +void FileGenerator::GenerateBottomHeaderGuard(io::Printer* printer, bool pb_h) { + Formatter format(printer, variables_); + format("#endif // $GOOGLE_PROTOBUF$_INCLUDED_$1$\n", + IncludeGuard(file_, pb_h, options_)); } void FileGenerator::GenerateLibraryIncludes(io::Printer* printer) { + Formatter format(printer, variables_); if (UsingImplicitWeakFields(file_, options_)) { - printer->Print("#include \n"); + IncludeFile("net/proto2/public/implicit_weak_message.h", printer); + } + if (HasWeakFields(file_, options_)) { + GOOGLE_CHECK(!options_.opensource_runtime); + IncludeFile("net/proto2/public/weak_field_map.h", printer); + } + if (HasLazyFields(file_, options_)) { + GOOGLE_CHECK(!options_.opensource_runtime); + IncludeFile("net/proto2/public/lazy_field.h", printer); } - printer->Print( - "#include \n" - "\n"); - - // Verify the protobuf library header version is compatible with the protoc - // version before going any further. - printer->Print( - "#if GOOGLE_PROTOBUF_VERSION < $min_header_version$\n" - "#error This file was generated by a newer version of protoc which is\n" - "#error incompatible with your Protocol Buffer headers. Please update\n" - "#error your headers.\n" - "#endif\n" - "#if $protoc_version$ < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION\n" - "#error This file was generated by an older version of protoc which is\n" - "#error incompatible with your Protocol Buffer headers. Please\n" - "#error regenerate this file with a newer version of protoc.\n" - "#endif\n" - "\n", - "min_header_version", - SimpleItoa(protobuf::internal::kMinHeaderVersionForProtoc), - "protoc_version", SimpleItoa(GOOGLE_PROTOBUF_VERSION)); + if (options_.opensource_runtime) { + // Verify the protobuf library header version is compatible with the protoc + // version before going any further. + IncludeFile("net/proto2/public/port_def.inc", printer); + format( + "#if PROTOBUF_VERSION < $1$\n" + "#error This file was generated by a newer version of protoc which is\n" + "#error incompatible with your Protocol Buffer headers. Please update\n" + "#error your headers.\n" + "#endif\n" + "#if $2$ < PROTOBUF_MIN_PROTOC_VERSION\n" + "#error This file was generated by an older version of protoc which " + "is\n" + "#error incompatible with your Protocol Buffer headers. Please\n" + "#error regenerate this file with a newer version of protoc.\n" + "#endif\n" + "\n", + PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC, // 1 + PROTOBUF_VERSION); // 2 + IncludeFile("net/proto2/public/port_undef.inc", printer); + } // OK, it's now safe to #include other files. - printer->Print( - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n"); - + IncludeFile("net/proto2/io/public/coded_stream.h", printer); + IncludeFile("net/proto2/public/arena.h", printer); + IncludeFile("net/proto2/public/arenastring.h", printer); + IncludeFile("net/proto2/public/generated_message_table_driven.h", printer); + IncludeFile("net/proto2/public/generated_message_util.h", printer); + IncludeFile("net/proto2/public/inlined_string_field.h", printer); if (HasDescriptorMethods(file_, options_)) { - printer->Print( - "#include \n"); + IncludeFile("net/proto2/public/metadata.h", printer); + IncludeFile("net/proto2/public/generated_message_reflection.h", printer); } else { - printer->Print( - "#include \n"); + IncludeFile("net/proto2/public/metadata_lite.h", printer); } if (!message_generators_.empty()) { if (HasDescriptorMethods(file_, options_)) { - printer->Print( - "#include \n"); + IncludeFile("net/proto2/public/message.h", printer); } else { - printer->Print( - "#include \n"); + IncludeFile("net/proto2/public/message_lite.h", printer); + } + } + if (options_.opensource_runtime) { + // Open-source relies on unconditional includes of these. + IncludeFileAndExport("net/proto2/public/repeated_field.h", printer); + IncludeFileAndExport("net/proto2/public/extension_set.h", printer); + } else { + // Google3 includes these files only when they are necessary. + if (HasExtensionsOrExtendableMessage(file_)) { + IncludeFileAndExport("net/proto2/public/extension_set.h", printer); + } + if (HasRepeatedFields(file_)) { + IncludeFileAndExport("net/proto2/public/repeated_field.h", printer); + } + if (HasStringPieceFields(file_, options_)) { + IncludeFile("net/proto2/public/string_piece_field_support.h", printer); + } + if (HasCordFields(file_, options_)) { + format("#include \"third_party/absl/strings/cord.h\"\n"); } } - printer->Print( - "#include " - " // IWYU pragma: export\n" - "#include " - " // IWYU pragma: export\n"); if (HasMapFields(file_)) { - printer->Print( - "#include " - " // IWYU pragma: export\n"); + IncludeFileAndExport("net/proto2/public/map.h", printer); if (HasDescriptorMethods(file_, options_)) { - printer->Print("#include \n"); - printer->Print("#include \n"); + IncludeFile("net/proto2/public/map_entry.h", printer); + IncludeFile("net/proto2/public/map_field_inl.h", printer); } else { - printer->Print("#include \n"); - printer->Print("#include \n"); + IncludeFile("net/proto2/public/map_entry_lite.h", printer); + IncludeFile("net/proto2/public/map_field_lite.h", printer); } } if (HasEnumDefinitions(file_)) { if (HasDescriptorMethods(file_, options_)) { - printer->Print( - "#include \n"); + IncludeFile("net/proto2/public/generated_enum_reflection.h", printer); } else { - printer->Print( - "#include \n"); + IncludeFile("net/proto2/public/generated_enum_util.h", printer); } } if (HasGenericServices(file_, options_)) { - printer->Print( - "#include \n"); + IncludeFile("net/proto2/public/service.h", printer); } if (UseUnknownFieldSet(file_, options_) && !message_generators_.empty()) { - printer->Print( - "#include \n"); + IncludeFile("net/proto2/public/unknown_field_set.h", printer); } - - if (IsAnyMessage(file_)) { - printer->Print( - "#include \n"); + if (IsAnyMessage(file_, options_)) { + IncludeFile("net/proto2/internal/any.h", printer); } } void FileGenerator::GenerateMetadataPragma(io::Printer* printer, - const string& info_path) { + const std::string& info_path) { + Formatter format(printer, variables_); if (!info_path.empty() && !options_.annotation_pragma_name.empty() && !options_.annotation_guard_name.empty()) { - printer->Print( + format.Set("guard", options_.annotation_guard_name); + format.Set("pragma", options_.annotation_pragma_name); + format.Set("info_path", info_path); + format( "#ifdef $guard$\n" "#pragma $pragma$ \"$info_path$\"\n" - "#endif // $guard$\n", - "guard", options_.annotation_guard_name, "pragma", - options_.annotation_pragma_name, "info_path", info_path); + "#endif // $guard$\n"); } } void FileGenerator::GenerateDependencyIncludes(io::Printer* printer) { - std::set public_import_names; - for (int i = 0; i < file_->public_dependency_count(); i++) { - public_import_names.insert(file_->public_dependency(i)->name()); - } - + Formatter format(printer, variables_); for (int i = 0; i < file_->dependency_count(); i++) { - const bool use_system_include = IsWellKnownMessage(file_->dependency(i)); - const string& name = file_->dependency(i)->name(); - bool public_import = (public_import_names.count(name) != 0); - string basename = StripProto(name); + std::string basename = StripProto(file_->dependency(i)->name()); + // Do not import weak deps. + if (IsDepWeak(file_->dependency(i))) continue; - printer->Print( - "#include $left$$dependency$.pb.h$right$$iwyu$\n", - "dependency", basename, - "iwyu", (public_import) ? " // IWYU pragma: export" : "", - "left", use_system_include ? "<" : "\"", - "right", use_system_include ? ">" : "\""); + if (IsBootstrapProto(options_, file_)) { + GetBootstrapBasename(options_, basename, &basename); + } + + format("#include $1$\n", + CreateHeaderInclude(basename + ".pb.h", file_->dependency(i))); } } void FileGenerator::GenerateGlobalStateFunctionDeclarations( io::Printer* printer) { -// Forward-declare the AddDescriptors, InitDefaults because these are called -// by .pb.cc files depending on this file. - printer->Print( + Formatter format(printer, variables_); + // Forward-declare the DescriptorTable because this is referenced by .pb.cc + // files depending on this file. + // + // The TableStruct is also outputted in weak_message_field.cc, because the + // weak fields must refer to table struct but cannot include the header. + // Also it annotates extra weak attributes. + // TODO(gerbens) make sure this situation is handled better. + format( "\n" - "namespace $file_namespace$ {\n" "// Internal implementation detail -- do not use these members.\n" - "struct $dllexport_decl$TableStruct {\n" + "struct $dllexport_decl $$tablename$ {\n" // These tables describe how to serialize and parse messages. Used // for table driven code. - " static const ::google::protobuf::internal::ParseTableField entries[];\n" - " static const ::google::protobuf::internal::AuxillaryParseTableField aux[];\n" - " static const ::google::protobuf::internal::ParseTable schema[$num$];\n" - " static const ::google::protobuf::internal::FieldMetadata field_metadata[];\n" - " static const ::google::protobuf::internal::SerializationTable " + " static const ::$proto_ns$::internal::ParseTableField entries[]\n" + " PROTOBUF_SECTION_VARIABLE(protodesc_cold);\n" + " static const ::$proto_ns$::internal::AuxillaryParseTableField aux[]\n" + " PROTOBUF_SECTION_VARIABLE(protodesc_cold);\n" + " static const ::$proto_ns$::internal::ParseTable schema[$1$]\n" + " PROTOBUF_SECTION_VARIABLE(protodesc_cold);\n" + " static const ::$proto_ns$::internal::FieldMetadata field_metadata[];\n" + " static const ::$proto_ns$::internal::SerializationTable " "serialization_table[];\n" - " static const ::google::protobuf::uint32 offsets[];\n" + " static const $uint32$ offsets[];\n" "};\n", - "file_namespace", FileLevelNamespace(file_), "dllexport_decl", - options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " ", - "num", SimpleItoa(std::max(size_t(1), message_generators_.size()))); + std::max(size_t(1), message_generators_.size())); if (HasDescriptorMethods(file_, options_)) { - printer->Print( - "void $dllexport_decl$AddDescriptors();\n", "dllexport_decl", - options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " "); + format( + "extern $dllexport_decl $const ::$proto_ns$::internal::DescriptorTable " + "$desc_table$;\n"); } - printer->Print( - "} // namespace $file_namespace$\n", - "file_namespace", FileLevelNamespace(file_)); } void FileGenerator::GenerateMessageDefinitions(io::Printer* printer) { + Formatter format(printer, variables_); // Generate class definitions. for (int i = 0; i < message_generators_.size(); i++) { if (i > 0) { - printer->Print("\n"); - printer->Print(kThinSeparator); - printer->Print("\n"); + format("\n"); + format(kThinSeparator); + format("\n"); } message_generators_[i]->GenerateClassDefinition(printer); } @@ -1334,74 +1398,77 @@ void FileGenerator::GenerateEnumDefinitions(io::Printer* printer) { } void FileGenerator::GenerateServiceDefinitions(io::Printer* printer) { + Formatter format(printer, variables_); if (HasGenericServices(file_, options_)) { // Generate service definitions. for (int i = 0; i < service_generators_.size(); i++) { if (i > 0) { - printer->Print("\n"); - printer->Print(kThinSeparator); - printer->Print("\n"); + format("\n"); + format(kThinSeparator); + format("\n"); } service_generators_[i]->GenerateDeclarations(printer); } - printer->Print("\n"); - printer->Print(kThickSeparator); - printer->Print("\n"); + format("\n"); + format(kThickSeparator); + format("\n"); } } void FileGenerator::GenerateExtensionIdentifiers(io::Printer* printer) { // Declare extension identifiers. These are in global scope and so only // the global scope extensions. - for (int i = 0; i < file_->extension_count(); i++) { - extension_generators_owner_[i]->GenerateDeclaration(printer); + for (auto& extension_generator : extension_generators_) { + if (extension_generator->IsScoped()) continue; + extension_generator->GenerateDeclaration(printer); } } void FileGenerator::GenerateInlineFunctionDefinitions(io::Printer* printer) { + Formatter format(printer, variables_); // TODO(gerbens) remove pragmas when gcc is no longer used. Current version // of gcc fires a bogus error when compiled with strict-aliasing. - printer->Print( - "#ifdef __GNUC__\n" - " #pragma GCC diagnostic push\n" - " #pragma GCC diagnostic ignored \"-Wstrict-aliasing\"\n" - "#endif // __GNUC__\n"); + format( + "#ifdef __GNUC__\n" + " #pragma GCC diagnostic push\n" + " #pragma GCC diagnostic ignored \"-Wstrict-aliasing\"\n" + "#endif // __GNUC__\n"); // Generate class inline methods. for (int i = 0; i < message_generators_.size(); i++) { if (i > 0) { - printer->Print(kThinSeparator); - printer->Print("\n"); + format(kThinSeparator); + format("\n"); } message_generators_[i]->GenerateInlineMethods(printer); } - printer->Print( - "#ifdef __GNUC__\n" - " #pragma GCC diagnostic pop\n" - "#endif // __GNUC__\n"); + format( + "#ifdef __GNUC__\n" + " #pragma GCC diagnostic pop\n" + "#endif // __GNUC__\n"); for (int i = 0; i < message_generators_.size(); i++) { if (i > 0) { - printer->Print(kThinSeparator); - printer->Print("\n"); + format(kThinSeparator); + format("\n"); } } } void FileGenerator::GenerateProto2NamespaceEnumSpecializations( io::Printer* printer) { + Formatter format(printer, variables_); // Emit GetEnumDescriptor specializations into google::protobuf namespace: if (HasEnumDefinitions(file_)) { - printer->Print( - "\n" - "namespace google {\nnamespace protobuf {\n" - "\n"); - for (int i = 0; i < enum_generators_.size(); i++) { - enum_generators_[i]->GenerateGetEnumDescriptorSpecializations(printer); + format("\n"); + { + NamespaceOpener proto_ns(ProtobufNamespace(options_), format); + format("\n"); + for (int i = 0; i < enum_generators_.size(); i++) { + enum_generators_[i]->GenerateGetEnumDescriptorSpecializations(printer); + } + format("\n"); } - printer->Print( - "\n" - "} // namespace protobuf\n} // namespace google\n"); } } diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_file.h b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_file.h index 94da9a14..33734c54 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_file.h +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_file.h @@ -44,23 +44,26 @@ #include #include #include +#include namespace google { namespace protobuf { - class FileDescriptor; // descriptor.h - namespace io { - class Printer; // printer.h - } +class FileDescriptor; // descriptor.h +namespace io { +class Printer; // printer.h } +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace cpp { -class EnumGenerator; // enum.h -class MessageGenerator; // message.h -class ServiceGenerator; // service.h -class ExtensionGenerator; // extension.h +class EnumGenerator; // enum.h +class MessageGenerator; // message.h +class ServiceGenerator; // service.h +class ExtensionGenerator; // extension.h class FileGenerator { public: @@ -71,14 +74,12 @@ class FileGenerator { // Shared code between the two header generators below. void GenerateHeader(io::Printer* printer); - // info_path, if non-empty, should be the path (relative to printer's output) - // to the metadata file describing this proto header. - void GenerateProtoHeader(io::Printer* printer, - const string& info_path); - // info_path, if non-empty, should be the path (relative to printer's output) - // to the metadata file describing this PB header. - void GeneratePBHeader(io::Printer* printer, - const string& info_path); + // info_path, if non-empty, should be the path (relative to printer's + // output) to the metadata file describing this proto header. + void GenerateProtoHeader(io::Printer* printer, const std::string& info_path); + // info_path, if non-empty, should be the path (relative to printer's + // output) to the metadata file describing this PB header. + void GeneratePBHeader(io::Printer* printer, const std::string& info_path); void GenerateSource(io::Printer* printer); int NumMessages() const { return message_generators_.size(); } @@ -89,7 +90,26 @@ class FileGenerator { private: // Internal type used by GenerateForwardDeclarations (defined in file.cc). class ForwardDeclarations; + struct CrossFileReferences; + void IncludeFile(const std::string& google3_name, io::Printer* printer) { + DoIncludeFile(google3_name, false, printer); + } + void IncludeFileAndExport(const std::string& google3_name, + io::Printer* printer) { + DoIncludeFile(google3_name, true, printer); + } + void DoIncludeFile(const std::string& google3_name, bool do_export, + io::Printer* printer); + + std::string CreateHeaderInclude(const std::string& basename, + const FileDescriptor* file); + void GetCrossFileReferencesForField(const FieldDescriptor* field, + CrossFileReferences* refs); + void GetCrossFileReferencesForFile(const FileDescriptor* file, + CrossFileReferences* refs); + void GenerateInternalForwardDeclarations(const CrossFileReferences& refs, + io::Printer* printer); void GenerateSourceIncludes(io::Printer* printer); void GenerateSourceDefaultInstance(int idx, io::Printer* printer); @@ -100,16 +120,9 @@ class FileGenerator { // For other imports, generates their forward-declarations. void GenerateForwardDeclarations(io::Printer* printer); - // Internal helper used by GenerateForwardDeclarations: fills 'decls' - // with all necessary forward-declarations for this file and its - // transient depednencies. - void FillForwardDeclarations(ForwardDeclarations* decls); - // Generates top or bottom of a header file. - void GenerateTopHeaderGuard(io::Printer* printer, - const string& filename_identifier); - void GenerateBottomHeaderGuard(io::Printer* printer, - const string& filename_identifier); + void GenerateTopHeaderGuard(io::Printer* printer, bool pb_h); + void GenerateBottomHeaderGuard(io::Printer* printer, bool pb_h); // Generates #include directives. void GenerateLibraryIncludes(io::Printer* printer); @@ -117,7 +130,8 @@ class FileGenerator { // Generate a pragma to pull in metadata using the given info_path (if // non-empty). info_path should be relative to printer's output. - void GenerateMetadataPragma(io::Printer* printer, const string& info_path); + void GenerateMetadataPragma(io::Printer* printer, + const std::string& info_path); // Generates a couple of different pieces before definitions: void GenerateGlobalStateFunctionDeclarations(io::Printer* printer); @@ -138,13 +152,13 @@ class FileGenerator { void GenerateProto2NamespaceEnumSpecializations(io::Printer* printer); - // Sometimes the names we use in a .proto file happen to be defined as macros - // on some platforms (e.g., macro/minor used in plugin.proto are defined as - // macros in sys/types.h on FreeBSD and a few other platforms). To make the - // generated code compile on these platforms, we either have to undef the - // macro for these few platforms, or rename the field name for all platforms. - // Since these names are part of protobuf public API, renaming is generally - // a breaking change so we prefer the #undef approach. + // Sometimes the names we use in a .proto file happen to be defined as + // macros on some platforms (e.g., macro/minor used in plugin.proto are + // defined as macros in sys/types.h on FreeBSD and a few other platforms). + // To make the generated code compile on these platforms, we either have to + // undef the macro for these few platforms, or rename the field name for all + // platforms. Since these names are part of protobuf public API, renaming is + // generally a breaking change so we prefer the #undef approach. void GenerateMacroUndefs(io::Printer* printer); bool IsSCCRepresentative(const Descriptor* d) { @@ -153,34 +167,32 @@ class FileGenerator { const Descriptor* GetSCCRepresentative(const Descriptor* d) { return GetSCC(d)->GetRepresentative(); } - const SCC* GetSCC(const Descriptor* d) { - return scc_analyzer_.GetSCC(d); + const SCC* GetSCC(const Descriptor* d) { return scc_analyzer_.GetSCC(d); } + + bool IsDepWeak(const FileDescriptor* dep) const { + if (weak_deps_.count(dep) != 0) { + GOOGLE_CHECK(!options_.opensource_runtime); + return true; + } + return false; } + std::set weak_deps_; + std::vector sccs_; const FileDescriptor* file_; const Options options_; - SCCAnalyzer scc_analyzer_; + MessageSCCAnalyzer scc_analyzer_; + std::map variables_; // Contains the post-order walk of all the messages (and child messages) in // this file. If you need a pre-order walk just reverse iterate. - std::vector message_generators_; - std::vector enum_generators_; - std::vector service_generators_; - std::vector extension_generators_; - - // These members are just for owning (and thus proper deleting). - // Nested (enum/extension)_generators are owned by child messages. - std::unique_ptr []> enum_generators_owner_; - std::unique_ptr []> - service_generators_owner_; - std::unique_ptr []> - extension_generators_owner_; - - // E.g. if the package is foo.bar, package_parts_ is {"foo", "bar"}. - std::vector package_parts_; + std::vector> message_generators_; + std::vector> enum_generators_; + std::vector> service_generators_; + std::vector> extension_generators_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator); }; @@ -188,6 +200,6 @@ class FileGenerator { } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_FILE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_generator.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_generator.cc index 20bb8a1a..7de07652 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_generator.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_generator.cc @@ -34,9 +34,9 @@ #include -#include #include #include +#include #include #include @@ -46,6 +46,7 @@ #include + namespace google { namespace protobuf { namespace compiler { @@ -55,10 +56,10 @@ CppGenerator::CppGenerator() {} CppGenerator::~CppGenerator() {} bool CppGenerator::Generate(const FileDescriptor* file, - const string& parameter, + const std::string& parameter, GeneratorContext* generator_context, - string* error) const { - std::vector > options; + std::string* error) const { + std::vector > options; ParseGeneratorParameter(parameter, &options); // ----------------------------------------------------------------- @@ -77,6 +78,10 @@ bool CppGenerator::Generate(const FileDescriptor* file, // __declspec(dllimport) depending on what is being compiled. // Options file_options; + + file_options.opensource_runtime = opensource_runtime_; + file_options.runtime_include_base = runtime_include_base_; + for (int i = 0; i < options.size(); i++) { if (options[i].first == "dllexport_decl") { file_options.dllexport_decl = options[i].second; @@ -88,13 +93,16 @@ bool CppGenerator::Generate(const FileDescriptor* file, file_options.annotation_pragma_name = options[i].second; } else if (options[i].first == "annotation_guard_name") { file_options.annotation_guard_name = options[i].second; + } else if (options[i].first == "speed") { + file_options.enforce_mode = EnforceOptimizeMode::kSpeed; } else if (options[i].first == "lite") { - file_options.enforce_lite = true; + file_options.enforce_mode = EnforceOptimizeMode::kLiteRuntime; } else if (options[i].first == "lite_implicit_weak_fields") { + file_options.enforce_mode = EnforceOptimizeMode::kLiteRuntime; file_options.lite_implicit_weak_fields = true; if (!options[i].second.empty()) { - file_options.num_cc_files = strto32(options[i].second.c_str(), - NULL, 10); + file_options.num_cc_files = + strto32(options[i].second.c_str(), NULL, 10); } } else if (options[i].first == "table_driven_parsing") { file_options.table_driven_parsing = true; @@ -108,7 +116,7 @@ bool CppGenerator::Generate(const FileDescriptor* file, // The safe_boundary_check option controls behavior for Google-internal // protobuf APIs. - if (file_options.safe_boundary_check) { + if (file_options.safe_boundary_check && file_options.opensource_runtime) { *error = "The safe_boundary_check option is not supported outside of Google."; return false; @@ -117,8 +125,12 @@ bool CppGenerator::Generate(const FileDescriptor* file, // ----------------------------------------------------------------- - string basename = StripProto(file->name()); + std::string basename = StripProto(file->name()); + if (MaybeBootstrap(file_options, generator_context, file_options.bootstrap, + &basename)) { + return true; + } FileGenerator file_generator(file, file_options); @@ -129,10 +141,10 @@ bool CppGenerator::Generate(const FileDescriptor* file, GeneratedCodeInfo annotations; io::AnnotationProtoCollector annotation_collector( &annotations); - string info_path = basename + ".proto.h.meta"; - io::Printer printer(output.get(), '$', file_options.annotate_headers - ? &annotation_collector - : NULL); + std::string info_path = basename + ".proto.h.meta"; + io::Printer printer( + output.get(), '$', + file_options.annotate_headers ? &annotation_collector : NULL); file_generator.GenerateProtoHeader( &printer, file_options.annotate_headers ? info_path : ""); if (file_options.annotate_headers) { @@ -148,10 +160,10 @@ bool CppGenerator::Generate(const FileDescriptor* file, GeneratedCodeInfo annotations; io::AnnotationProtoCollector annotation_collector( &annotations); - string info_path = basename + ".pb.h.meta"; - io::Printer printer(output.get(), '$', file_options.annotate_headers - ? &annotation_collector - : NULL); + std::string info_path = basename + ".pb.h.meta"; + io::Printer printer( + output.get(), '$', + file_options.annotate_headers ? &annotation_collector : NULL); file_generator.GeneratePBHeader( &printer, file_options.annotate_headers ? info_path : ""); if (file_options.annotate_headers) { @@ -164,7 +176,8 @@ bool CppGenerator::Generate(const FileDescriptor* file, // Generate cc file(s). if (UsingImplicitWeakFields(file, file_options)) { { - // This is the global .cc file, containing enum/services/tables/reflection + // This is the global .cc file, containing + // enum/services/tables/reflection std::unique_ptr output( generator_context->Open(basename + ".pb.cc")); io::Printer printer(output.get(), '$'); @@ -173,19 +186,18 @@ bool CppGenerator::Generate(const FileDescriptor* file, int num_cc_files = file_generator.NumMessages(); - // If we're using implicit weak fields then we allow the user to optionally - // specify how many files to generate, not counting the global pb.cc file. - // If we have more files than messages, then some files will be generated as - // empty placeholders. + // If we're using implicit weak fields then we allow the user to + // optionally specify how many files to generate, not counting the global + // pb.cc file. If we have more files than messages, then some files will + // be generated as empty placeholders. if (file_options.num_cc_files > 0) { GOOGLE_CHECK_LE(file_generator.NumMessages(), file_options.num_cc_files) << "There must be at least as many numbered .cc files as messages."; num_cc_files = file_options.num_cc_files; } for (int i = 0; i < num_cc_files; i++) { - // TODO(gerbens) Agree on naming scheme. std::unique_ptr output( - generator_context->Open(basename + "." + SimpleItoa(i) + ".cc")); + generator_context->Open(StrCat(basename, ".out/", i, ".cc"))); io::Printer printer(output.get(), '$'); if (i < file_generator.NumMessages()) { file_generator.GenerateSourceForMessage(i, &printer); diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_generator.h b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_generator.h index 3d517cf4..dafc6e60 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_generator.h +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_generator.h @@ -40,6 +40,8 @@ #include #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -49,24 +51,49 @@ namespace cpp { // header. If you create your own protocol compiler binary and you want // it to support C++ output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT CppGenerator : public CodeGenerator { +class PROTOC_EXPORT CppGenerator : public CodeGenerator { public: CppGenerator(); ~CppGenerator(); + enum class Runtime { + kGoogle3, // Use the internal google3 runtime. + kOpensource, // Use the open-source runtime. + + // Use the open-source runtime with google3 #include paths. We make these + // absolute to avoid ambiguity, so the runtime will be #included like: + // #include "third_party/protobuf/<...>/google/protobuf/message.h" + kOpensourceGoogle3 + }; + + void set_opensource_runtime(bool opensource) { + opensource_runtime_ = opensource; + } + + // If set to a non-empty string, generated code will do: + // #include "/google/protobuf/message.h" + // instead of: + // #include + // This has no effect if opensource_runtime = false. + void set_runtime_include_base(const std::string& base) { + runtime_include_base_ = base; + } + // implements CodeGenerator ---------------------------------------- - bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* generator_context, - string* error) const; + bool Generate(const FileDescriptor* file, const std::string& parameter, + GeneratorContext* generator_context, std::string* error) const; private: + bool opensource_runtime_ = true; + std::string runtime_include_base_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CppGenerator); }; } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_GENERATOR_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_helpers.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_helpers.cc index 163dac0a..6a32c564 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_helpers.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_helpers.cc @@ -32,22 +32,31 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include +#include + +#include #include #include #include +#include #include -#include #include -#include +#include +#include + +#include #include #include +#include +#include #include #include +#include +#include namespace google { namespace protobuf { @@ -58,54 +67,105 @@ namespace { static const char kAnyMessageName[] = "Any"; static const char kAnyProtoFile[] = "google/protobuf/any.proto"; -static const char kGoogleProtobufPrefix[] = "google/protobuf/"; -string DotsToUnderscores(const string& name) { - return StringReplace(name, ".", "_", true); -} - -string DotsToColons(const string& name) { +std::string DotsToColons(const std::string& name) { return StringReplace(name, ".", "::", true); } -const char* const kKeywordList[] = { - "alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand", "bitor", - "bool", "break", "case", "catch", "char", "class", "compl", "const", - "constexpr", "const_cast", "continue", "decltype", "default", "delete", "do", - "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", - "false", "float", "for", "friend", "goto", "if", "inline", "int", "long", - "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr", - "operator", "or", "or_eq", "private", "protected", "public", "register", - "reinterpret_cast", "return", "short", "signed", "sizeof", "static", - "static_assert", "static_cast", "struct", "switch", "template", "this", - "thread_local", "throw", "true", "try", "typedef", "typeid", "typename", - "union", "unsigned", "using", "virtual", "void", "volatile", "wchar_t", - "while", "xor", "xor_eq" -}; +static const char* const kKeywordList[] = { // + "NULL", + "alignas", + "alignof", + "and", + "and_eq", + "asm", + "auto", + "bitand", + "bitor", + "bool", + "break", + "case", + "catch", + "char", + "class", + "compl", + "const", + "constexpr", + "const_cast", + "continue", + "decltype", + "default", + "delete", + "do", + "double", + "dynamic_cast", + "else", + "enum", + "explicit", + "export", + "extern", + "false", + "float", + "for", + "friend", + "goto", + "if", + "inline", + "int", + "long", + "mutable", + "namespace", + "new", + "noexcept", + "not", + "not_eq", + "nullptr", + "operator", + "or", + "or_eq", + "private", + "protected", + "public", + "register", + "reinterpret_cast", + "return", + "short", + "signed", + "sizeof", + "static", + "static_assert", + "static_cast", + "struct", + "switch", + "template", + "this", + "thread_local", + "throw", + "true", + "try", + "typedef", + "typeid", + "typename", + "union", + "unsigned", + "using", + "virtual", + "void", + "volatile", + "wchar_t", + "while", + "xor", + "xor_eq"}; -hash_set MakeKeywordsMap() { - hash_set result; - for (int i = 0; i < GOOGLE_ARRAYSIZE(kKeywordList); i++) { - result.insert(kKeywordList[i]); +static std::unordered_set* MakeKeywordsMap() { + auto* result = new std::unordered_set(); + for (const auto keyword : kKeywordList) { + result->emplace(keyword); } return result; } -hash_set kKeywords = MakeKeywordsMap(); - -// Returns whether the provided descriptor has an extension. This includes its -// nested types. -bool HasExtension(const Descriptor* descriptor) { - if (descriptor->extension_count() > 0) { - return true; - } - for (int i = 0; i < descriptor->nested_type_count(); ++i) { - if (HasExtension(descriptor->nested_type(i))) { - return true; - } - } - return false; -} +static std::unordered_set& kKeywords = *MakeKeywordsMap(); // Encode [0..63] as 'A'-'Z', 'a'-'z', '0'-'9', '_' char Base63Char(int value) { @@ -122,8 +182,8 @@ char Base63Char(int value) { // Given a c identifier has 63 legal characters we can't implement base64 // encoding. So we return the k least significant "digits" in base 63. template -string Base63(I n, int k) { - string res; +std::string Base63(I n, int k) { + std::string res; while (k-- > 0) { res += Base63Char(static_cast(n % 63)); n /= 63; @@ -131,10 +191,61 @@ string Base63(I n, int k) { return res; } +std::string IntTypeName(const Options& options, const std::string& type) { + if (options.opensource_runtime) { + return "::PROTOBUF_NAMESPACE_ID::" + type; + } else { + return "::" + type; + } +} + +void SetIntVar(const Options& options, const std::string& type, + std::map* variables) { + (*variables)[type] = IntTypeName(options, type); +} + } // namespace -string UnderscoresToCamelCase(const string& input, bool cap_next_letter) { - string result; +void SetCommonVars(const Options& options, + std::map* variables) { + (*variables)["proto_ns"] = ProtobufNamespace(options); + + // Warning: there is some clever naming/splitting here to avoid extract script + // rewrites. The names of these variables must not be things that the extract + // script will rewrite. That's why we use "CHK" (for example) instead of + // "GOOGLE_CHECK". + if (options.opensource_runtime) { + (*variables)["GOOGLE_PROTOBUF"] = "GOOGLE_PROTOBUF"; + (*variables)["CHK"] = "GOOGLE_CHECK"; + (*variables)["DCHK"] = "GOOGLE_DCHECK"; + } else { + // These values are things the extract script would rewrite if we did not + // split them. It might not strictly matter since we don't generate google3 + // code in open-source. But it's good to prevent surprising things from + // happening. + (*variables)["GOOGLE_PROTOBUF"] = + "GOOGLE3" + "_PROTOBUF"; + (*variables)["CHK"] = + "CH" + "ECK"; + (*variables)["DCHK"] = + "DCH" + "ECK"; + } + + SetIntVar(options, "int8", variables); + SetIntVar(options, "uint8", variables); + SetIntVar(options, "uint32", variables); + SetIntVar(options, "uint64", variables); + SetIntVar(options, "int32", variables); + SetIntVar(options, "int64", variables); + (*variables)["string"] = "std::string"; +} + +std::string UnderscoresToCamelCase(const std::string& input, + bool cap_next_letter) { + std::string result; // Note: I distrust ctype.h due to locales. for (int i = 0; i < input.size(); i++) { if ('a' <= input[i] && input[i] <= 'z') { @@ -159,9 +270,9 @@ string UnderscoresToCamelCase(const string& input, bool cap_next_letter) { } const char kThickSeparator[] = - "// ===================================================================\n"; + "// ===================================================================\n"; const char kThinSeparator[] = - "// -------------------------------------------------------------------\n"; + "// -------------------------------------------------------------------\n"; bool CanInitializeByZeroing(const FieldDescriptor* field) { if (field->is_repeated() || field->is_extension()) return false; @@ -187,47 +298,117 @@ bool CanInitializeByZeroing(const FieldDescriptor* field) { } } -string ClassName(const Descriptor* descriptor) { +std::string ClassName(const Descriptor* descriptor) { const Descriptor* parent = descriptor->containing_type(); - string res; + std::string res; if (parent) res += ClassName(parent) + "_"; res += descriptor->name(); if (IsMapEntryMessage(descriptor)) res += "_DoNotUse"; - return res; + return ResolveKeyword(res); } -string ClassName(const EnumDescriptor* enum_descriptor) { - if (enum_descriptor->containing_type() == NULL) { - return enum_descriptor->name(); +std::string ClassName(const EnumDescriptor* enum_descriptor) { + if (enum_descriptor->containing_type() == nullptr) { + return ResolveKeyword(enum_descriptor->name()); } else { return ClassName(enum_descriptor->containing_type()) + "_" + enum_descriptor->name(); } } -string Namespace(const string& package) { +std::string QualifiedClassName(const Descriptor* d, const Options& options) { + return QualifiedFileLevelSymbol(d->file(), ClassName(d), options); +} + +std::string QualifiedClassName(const EnumDescriptor* d, + const Options& options) { + return QualifiedFileLevelSymbol(d->file(), ClassName(d), options); +} + +std::string QualifiedClassName(const Descriptor* d) { + return QualifiedClassName(d, Options()); +} + +std::string QualifiedClassName(const EnumDescriptor* d) { + return QualifiedClassName(d, Options()); +} + +std::string Namespace(const std::string& package) { if (package.empty()) return ""; return "::" + DotsToColons(package); } -string DefaultInstanceName(const Descriptor* descriptor) { - string prefix = descriptor->file()->package().empty() ? "" : "::"; - return prefix + DotsToColons(descriptor->file()->package()) + "::_" + - ClassName(descriptor, false) + "_default_instance_"; +std::string Namespace(const FileDescriptor* d, const Options& options) { + std::string ret = Namespace(d->package()); + if (IsWellKnownMessage(d) && options.opensource_runtime) { + // Written with string concatenation to prevent rewriting of + // ::google::protobuf. + ret = StringReplace(ret, + "::google::" + "protobuf", + "PROTOBUF_NAMESPACE_ID", false); + } + return ret; } -string ReferenceFunctionName(const Descriptor* descriptor) { - return QualifiedClassName(descriptor) + "_ReferenceStrong"; +std::string Namespace(const Descriptor* d, const Options& options) { + return Namespace(d->file(), options); } -string SuperClassName(const Descriptor* descriptor, const Options& options) { - return HasDescriptorMethods(descriptor->file(), options) - ? "::google::protobuf::Message" - : "::google::protobuf::MessageLite"; +std::string Namespace(const FieldDescriptor* d, const Options& options) { + return Namespace(d->file(), options); } -string FieldName(const FieldDescriptor* field) { - string result = field->name(); +std::string Namespace(const EnumDescriptor* d, const Options& options) { + return Namespace(d->file(), options); +} + +std::string DefaultInstanceType(const Descriptor* descriptor, + const Options& options) { + return ClassName(descriptor) + "DefaultTypeInternal"; +} + +std::string DefaultInstanceName(const Descriptor* descriptor, + const Options& options) { + return "_" + ClassName(descriptor, false) + "_default_instance_"; +} + +std::string QualifiedDefaultInstanceName(const Descriptor* descriptor, + const Options& options) { + return QualifiedFileLevelSymbol( + descriptor->file(), DefaultInstanceName(descriptor, options), options); +} + +std::string DescriptorTableName(const FileDescriptor* file, + const Options& options) { + return UniqueName("descriptor_table", file, options); +} + +std::string FileDllExport(const FileDescriptor* file, const Options& options) { + return UniqueName("PROTOBUF_INTERNAL_EXPORT", file, options); +} + +std::string ReferenceFunctionName(const Descriptor* descriptor, + const Options& options) { + return QualifiedClassName(descriptor, options) + "_ReferenceStrong"; +} + +std::string SuperClassName(const Descriptor* descriptor, + const Options& options) { + return "::" + ProtobufNamespace(options) + + (HasDescriptorMethods(descriptor->file(), options) ? "::Message" + : "::MessageLite"); +} + +std::string ResolveKeyword(const string& name) { + if (kKeywords.count(name) > 0) { + return name + "_"; + } + return name; +} + +std::string FieldName(const FieldDescriptor* field) { + std::string result = field->name(); LowerString(&result); if (kKeywords.count(result) > 0) { result.append("_"); @@ -235,8 +416,8 @@ string FieldName(const FieldDescriptor* field) { return result; } -string EnumValueName(const EnumValueDescriptor* enum_value) { - string result = enum_value->name(); +std::string EnumValueName(const EnumValueDescriptor* enum_value) { + std::string result = enum_value->name(); if (kKeywords.count(result) > 0) { result.append("_"); } @@ -244,7 +425,7 @@ string EnumValueName(const EnumValueDescriptor* enum_value) { } int EstimateAlignmentSize(const FieldDescriptor* field) { - if (field == NULL) return 0; + if (field == nullptr) return 0; if (field->is_repeated()) return 8; switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_BOOL: @@ -267,29 +448,30 @@ int EstimateAlignmentSize(const FieldDescriptor* field) { return -1; // Make compiler happy. } -string FieldConstantName(const FieldDescriptor *field) { - string field_name = UnderscoresToCamelCase(field->name(), true); - string result = "k" + field_name + "FieldNumber"; +std::string FieldConstantName(const FieldDescriptor* field) { + std::string field_name = UnderscoresToCamelCase(field->name(), true); + std::string result = "k" + field_name + "FieldNumber"; if (!field->is_extension() && field->containing_type()->FindFieldByCamelcaseName( - field->camelcase_name()) != field) { + field->camelcase_name()) != field) { // This field's camelcase name is not unique. As a hack, add the field // number to the constant name. This makes the constant rather useless, // but what can we do? - result += "_" + SimpleItoa(field->number()); + result += "_" + StrCat(field->number()); } return result; } -string FieldMessageTypeName(const FieldDescriptor* field) { +std::string FieldMessageTypeName(const FieldDescriptor* field, + const Options& options) { // Note: The Google-internal version of Protocol Buffers uses this function // as a hook point for hacks to support legacy code. - return ClassName(field->message_type(), true); + return QualifiedClassName(field->message_type(), options); } -string StripProto(const string& filename) { +std::string StripProto(const std::string& filename) { if (HasSuffixString(filename, ".protodevel")) { return StripSuffixString(filename, ".protodevel"); } else { @@ -299,133 +481,204 @@ string StripProto(const string& filename) { const char* PrimitiveTypeName(FieldDescriptor::CppType type) { switch (type) { - case FieldDescriptor::CPPTYPE_INT32 : return "::google::protobuf::int32"; - case FieldDescriptor::CPPTYPE_INT64 : return "::google::protobuf::int64"; - case FieldDescriptor::CPPTYPE_UINT32 : return "::google::protobuf::uint32"; - case FieldDescriptor::CPPTYPE_UINT64 : return "::google::protobuf::uint64"; - case FieldDescriptor::CPPTYPE_DOUBLE : return "double"; - case FieldDescriptor::CPPTYPE_FLOAT : return "float"; - case FieldDescriptor::CPPTYPE_BOOL : return "bool"; - case FieldDescriptor::CPPTYPE_ENUM : return "int"; - case FieldDescriptor::CPPTYPE_STRING : return "::std::string"; - case FieldDescriptor::CPPTYPE_MESSAGE: return NULL; + case FieldDescriptor::CPPTYPE_INT32: + return "::google::protobuf::int32"; + case FieldDescriptor::CPPTYPE_INT64: + return "::google::protobuf::int64"; + case FieldDescriptor::CPPTYPE_UINT32: + return "::google::protobuf::uint32"; + case FieldDescriptor::CPPTYPE_UINT64: + return "::google::protobuf::uint64"; + case FieldDescriptor::CPPTYPE_DOUBLE: + return "double"; + case FieldDescriptor::CPPTYPE_FLOAT: + return "float"; + case FieldDescriptor::CPPTYPE_BOOL: + return "bool"; + case FieldDescriptor::CPPTYPE_ENUM: + return "int"; + case FieldDescriptor::CPPTYPE_STRING: + return "std::string"; + case FieldDescriptor::CPPTYPE_MESSAGE: + return nullptr; - // No default because we want the compiler to complain if any new - // CppTypes are added. + // No default because we want the compiler to complain if any new + // CppTypes are added. } GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; + return nullptr; +} + +std::string PrimitiveTypeName(const Options& options, + FieldDescriptor::CppType type) { + switch (type) { + case FieldDescriptor::CPPTYPE_INT32: + return IntTypeName(options, "int32"); + case FieldDescriptor::CPPTYPE_INT64: + return IntTypeName(options, "int64"); + case FieldDescriptor::CPPTYPE_UINT32: + return IntTypeName(options, "uint32"); + case FieldDescriptor::CPPTYPE_UINT64: + return IntTypeName(options, "uint64"); + case FieldDescriptor::CPPTYPE_DOUBLE: + return "double"; + case FieldDescriptor::CPPTYPE_FLOAT: + return "float"; + case FieldDescriptor::CPPTYPE_BOOL: + return "bool"; + case FieldDescriptor::CPPTYPE_ENUM: + return "int"; + case FieldDescriptor::CPPTYPE_STRING: + return "std::string"; + case FieldDescriptor::CPPTYPE_MESSAGE: + return ""; + + // No default because we want the compiler to complain if any new + // CppTypes are added. + } + + GOOGLE_LOG(FATAL) << "Can't get here."; + return ""; } const char* DeclaredTypeMethodName(FieldDescriptor::Type type) { switch (type) { - case FieldDescriptor::TYPE_INT32 : return "Int32"; - case FieldDescriptor::TYPE_INT64 : return "Int64"; - case FieldDescriptor::TYPE_UINT32 : return "UInt32"; - case FieldDescriptor::TYPE_UINT64 : return "UInt64"; - case FieldDescriptor::TYPE_SINT32 : return "SInt32"; - case FieldDescriptor::TYPE_SINT64 : return "SInt64"; - case FieldDescriptor::TYPE_FIXED32 : return "Fixed32"; - case FieldDescriptor::TYPE_FIXED64 : return "Fixed64"; - case FieldDescriptor::TYPE_SFIXED32: return "SFixed32"; - case FieldDescriptor::TYPE_SFIXED64: return "SFixed64"; - case FieldDescriptor::TYPE_FLOAT : return "Float"; - case FieldDescriptor::TYPE_DOUBLE : return "Double"; + case FieldDescriptor::TYPE_INT32: + return "Int32"; + case FieldDescriptor::TYPE_INT64: + return "Int64"; + case FieldDescriptor::TYPE_UINT32: + return "UInt32"; + case FieldDescriptor::TYPE_UINT64: + return "UInt64"; + case FieldDescriptor::TYPE_SINT32: + return "SInt32"; + case FieldDescriptor::TYPE_SINT64: + return "SInt64"; + case FieldDescriptor::TYPE_FIXED32: + return "Fixed32"; + case FieldDescriptor::TYPE_FIXED64: + return "Fixed64"; + case FieldDescriptor::TYPE_SFIXED32: + return "SFixed32"; + case FieldDescriptor::TYPE_SFIXED64: + return "SFixed64"; + case FieldDescriptor::TYPE_FLOAT: + return "Float"; + case FieldDescriptor::TYPE_DOUBLE: + return "Double"; - case FieldDescriptor::TYPE_BOOL : return "Bool"; - case FieldDescriptor::TYPE_ENUM : return "Enum"; + case FieldDescriptor::TYPE_BOOL: + return "Bool"; + case FieldDescriptor::TYPE_ENUM: + return "Enum"; - case FieldDescriptor::TYPE_STRING : return "String"; - case FieldDescriptor::TYPE_BYTES : return "Bytes"; - case FieldDescriptor::TYPE_GROUP : return "Group"; - case FieldDescriptor::TYPE_MESSAGE : return "Message"; + case FieldDescriptor::TYPE_STRING: + return "String"; + case FieldDescriptor::TYPE_BYTES: + return "Bytes"; + case FieldDescriptor::TYPE_GROUP: + return "Group"; + case FieldDescriptor::TYPE_MESSAGE: + return "Message"; - // No default because we want the compiler to complain if any new - // types are added. + // No default because we want the compiler to complain if any new + // types are added. } GOOGLE_LOG(FATAL) << "Can't get here."; return ""; } -string Int32ToString(int number) { - // gcc rejects the decimal form of kint32min. +std::string Int32ToString(int number) { if (number == kint32min) { - GOOGLE_COMPILE_ASSERT(kint32min == (~0x7fffffff), kint32min_value_error); - return "(~0x7fffffff)"; + // This needs to be special-cased, see explanation here: + // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52661 + return StrCat(number + 1, " - 1"); } else { - return SimpleItoa(number); + return StrCat(number); } } -string Int64ToString(int64 number) { - // gcc rejects the decimal form of kint64min +std::string Int64ToString(const std::string& macro_prefix, int64 number) { if (number == kint64min) { - // Make sure we are in a 2's complement system. - GOOGLE_COMPILE_ASSERT(kint64min == GOOGLE_LONGLONG(~0x7fffffffffffffff), - kint64min_value_error); - return "GOOGLE_LONGLONG(~0x7fffffffffffffff)"; + // This needs to be special-cased, see explanation here: + // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52661 + return StrCat(macro_prefix, "_LONGLONG(", number + 1, ") - 1"); } - return "GOOGLE_LONGLONG(" + SimpleItoa(number) + ")"; + return StrCat(macro_prefix, "_LONGLONG(", number, ")"); } -string DefaultValue(const FieldDescriptor* field) { +std::string UInt64ToString(const std::string& macro_prefix, uint64 number) { + return StrCat(macro_prefix, "_ULONGLONG(", number, ")"); +} + +std::string DefaultValue(const FieldDescriptor* field) { + switch (field->cpp_type()) { + case FieldDescriptor::CPPTYPE_INT64: + return Int64ToString("GG", field->default_value_int64()); + case FieldDescriptor::CPPTYPE_UINT64: + return UInt64ToString("GG", field->default_value_uint64()); + default: + return DefaultValue(Options(), field); + } +} + +std::string DefaultValue(const Options& options, const FieldDescriptor* field) { switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_INT32: return Int32ToString(field->default_value_int32()); case FieldDescriptor::CPPTYPE_UINT32: - return SimpleItoa(field->default_value_uint32()) + "u"; + return StrCat(field->default_value_uint32()) + "u"; case FieldDescriptor::CPPTYPE_INT64: - return Int64ToString(field->default_value_int64()); + return Int64ToString("PROTOBUF", field->default_value_int64()); case FieldDescriptor::CPPTYPE_UINT64: - return "GOOGLE_ULONGLONG(" + SimpleItoa(field->default_value_uint64())+ ")"; + return UInt64ToString("PROTOBUF", field->default_value_uint64()); case FieldDescriptor::CPPTYPE_DOUBLE: { double value = field->default_value_double(); if (value == std::numeric_limits::infinity()) { - return "::google::protobuf::internal::Infinity()"; + return "std::numeric_limits::infinity()"; } else if (value == -std::numeric_limits::infinity()) { - return "-::google::protobuf::internal::Infinity()"; + return "-std::numeric_limits::infinity()"; } else if (value != value) { - return "::google::protobuf::internal::NaN()"; + return "std::numeric_limits::quiet_NaN()"; } else { return SimpleDtoa(value); } } - case FieldDescriptor::CPPTYPE_FLOAT: - { - float value = field->default_value_float(); - if (value == std::numeric_limits::infinity()) { - return "static_cast(::google::protobuf::internal::Infinity())"; - } else if (value == -std::numeric_limits::infinity()) { - return "static_cast(-::google::protobuf::internal::Infinity())"; - } else if (value != value) { - return "static_cast(::google::protobuf::internal::NaN())"; - } else { - string float_value = SimpleFtoa(value); - // If floating point value contains a period (.) or an exponent - // (either E or e), then append suffix 'f' to make it a float - // literal. - if (float_value.find_first_of(".eE") != string::npos) { - float_value.push_back('f'); - } - return float_value; + case FieldDescriptor::CPPTYPE_FLOAT: { + float value = field->default_value_float(); + if (value == std::numeric_limits::infinity()) { + return "std::numeric_limits::infinity()"; + } else if (value == -std::numeric_limits::infinity()) { + return "-std::numeric_limits::infinity()"; + } else if (value != value) { + return "std::numeric_limits::quiet_NaN()"; + } else { + std::string float_value = SimpleFtoa(value); + // If floating point value contains a period (.) or an exponent + // (either E or e), then append suffix 'f' to make it a float + // literal. + if (float_value.find_first_of(".eE") != string::npos) { + float_value.push_back('f'); } + return float_value; } + } case FieldDescriptor::CPPTYPE_BOOL: return field->default_value_bool() ? "true" : "false"; case FieldDescriptor::CPPTYPE_ENUM: // Lazy: Generate a static_cast because we don't have a helper function // that constructs the full name of an enum value. return strings::Substitute( - "static_cast< $0 >($1)", - ClassName(field->enum_type(), true), + "static_cast< $0 >($1)", ClassName(field->enum_type(), true), Int32ToString(field->default_value_enum()->number())); case FieldDescriptor::CPPTYPE_STRING: - return "\"" + EscapeTrigraphs( - CEscape(field->default_value_string())) + - "\""; + return "\"" + + EscapeTrigraphs(CEscape(field->default_value_string())) + + "\""; case FieldDescriptor::CPPTYPE_MESSAGE: - return "*" + FieldMessageTypeName(field) + + return "*" + FieldMessageTypeName(field, options) + "::internal_default_instance()"; } // Can't actually get here; make compiler happy. (We could add a default @@ -436,8 +689,8 @@ string DefaultValue(const FieldDescriptor* field) { } // Convert a file name into a valid identifier. -string FilenameIdentifier(const string& filename) { - string result; +std::string FilenameIdentifier(const std::string& filename) { + std::string result; for (int i = 0; i < filename.size(); i++) { if (ascii_isalnum(filename[i])) { result.push_back(filename[i]); @@ -450,31 +703,34 @@ string FilenameIdentifier(const string& filename) { return result; } -string FileLevelNamespace(const string& filename) { - return "protobuf_" + FilenameIdentifier(filename); +string UniqueName(const std::string& name, const std::string& filename, + const Options& options) { + return name + "_" + FilenameIdentifier(filename); } // Return the qualified C++ name for a file level symbol. -string QualifiedFileLevelSymbol(const string& package, const string& name) { - if (package.empty()) { +std::string QualifiedFileLevelSymbol(const FileDescriptor* file, + const std::string& name, + const Options& options) { + if (file->package().empty()) { return StrCat("::", name); } - return StrCat("::", DotsToColons(package), "::", name); + return StrCat(Namespace(file, options), "::", name); } // Escape C++ trigraphs by escaping question marks to \? -string EscapeTrigraphs(const string& to_escape) { +std::string EscapeTrigraphs(const std::string& to_escape) { return StringReplace(to_escape, "?", "\\?", true); } // Escaped function name to eliminate naming conflict. -string SafeFunctionName(const Descriptor* descriptor, - const FieldDescriptor* field, - const string& prefix) { +std::string SafeFunctionName(const Descriptor* descriptor, + const FieldDescriptor* field, + const std::string& prefix) { // Do not use FieldName() since it will escape keywords. - string name = field->name(); + std::string name = field->name(); LowerString(&name); - string function_name = prefix + name; + std::string function_name = prefix + name; if (descriptor->FindFieldByName(function_name)) { // Single underscore will also make it conflicting with the private data // member. We use double underscore to escape function names. @@ -487,6 +743,145 @@ string SafeFunctionName(const Descriptor* descriptor, return function_name; } +bool IsStringInlined(const FieldDescriptor* descriptor, + const Options& options) { + if (options.opensource_runtime) return false; + + // TODO(ckennelly): Handle inlining for any.proto. + if (IsAnyMessage(descriptor->containing_type(), options)) return false; + if (descriptor->containing_type()->options().map_entry()) return false; + + // Limit to proto2, as we rely on has bits to distinguish field presence for + // release_$name$. On proto3, we cannot use the address of the string + // instance when the field has been inlined. + if (!HasFieldPresence(descriptor->file())) return false; + + if (options.access_info_map) { + if (descriptor->is_required()) return true; + } + return false; +} + +static bool HasLazyFields(const Descriptor* descriptor, + const Options& options) { + for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { + if (IsLazy(descriptor->field(field_idx), options)) { + return true; + } + } + for (int idx = 0; idx < descriptor->extension_count(); idx++) { + if (IsLazy(descriptor->extension(idx), options)) { + return true; + } + } + for (int idx = 0; idx < descriptor->nested_type_count(); idx++) { + if (HasLazyFields(descriptor->nested_type(idx), options)) { + return true; + } + } + return false; +} + +// Does the given FileDescriptor use lazy fields? +bool HasLazyFields(const FileDescriptor* file, const Options& options) { + for (int i = 0; i < file->message_type_count(); i++) { + const Descriptor* descriptor(file->message_type(i)); + if (HasLazyFields(descriptor, options)) { + return true; + } + } + for (int field_idx = 0; field_idx < file->extension_count(); field_idx++) { + if (IsLazy(file->extension(field_idx), options)) { + return true; + } + } + return false; +} + +static bool HasRepeatedFields(const Descriptor* descriptor) { + for (int i = 0; i < descriptor->field_count(); ++i) { + if (descriptor->field(i)->label() == FieldDescriptor::LABEL_REPEATED) { + return true; + } + } + for (int i = 0; i < descriptor->nested_type_count(); ++i) { + if (HasRepeatedFields(descriptor->nested_type(i))) return true; + } + return false; +} + +bool HasRepeatedFields(const FileDescriptor* file) { + for (int i = 0; i < file->message_type_count(); ++i) { + if (HasRepeatedFields(file->message_type(i))) return true; + } + return false; +} + +static bool IsStringPieceField(const FieldDescriptor* field, + const Options& options) { + return field->cpp_type() == FieldDescriptor::CPPTYPE_STRING && + EffectiveStringCType(field, options) == FieldOptions::STRING_PIECE; +} + +static bool HasStringPieceFields(const Descriptor* descriptor, + const Options& options) { + for (int i = 0; i < descriptor->field_count(); ++i) { + if (IsStringPieceField(descriptor->field(i), options)) return true; + } + for (int i = 0; i < descriptor->nested_type_count(); ++i) { + if (HasStringPieceFields(descriptor->nested_type(i), options)) return true; + } + return false; +} + +bool HasStringPieceFields(const FileDescriptor* file, const Options& options) { + for (int i = 0; i < file->message_type_count(); ++i) { + if (HasStringPieceFields(file->message_type(i), options)) return true; + } + return false; +} + +static bool IsCordField(const FieldDescriptor* field, const Options& options) { + return field->cpp_type() == FieldDescriptor::CPPTYPE_STRING && + EffectiveStringCType(field, options) == FieldOptions::CORD; +} + +static bool HasCordFields(const Descriptor* descriptor, + const Options& options) { + for (int i = 0; i < descriptor->field_count(); ++i) { + if (IsCordField(descriptor->field(i), options)) return true; + } + for (int i = 0; i < descriptor->nested_type_count(); ++i) { + if (HasCordFields(descriptor->nested_type(i), options)) return true; + } + return false; +} + +bool HasCordFields(const FileDescriptor* file, const Options& options) { + for (int i = 0; i < file->message_type_count(); ++i) { + if (HasCordFields(file->message_type(i), options)) return true; + } + return false; +} + +static bool HasExtensionsOrExtendableMessage(const Descriptor* descriptor) { + if (descriptor->extension_range_count() > 0) return true; + if (descriptor->extension_count() > 0) return true; + for (int i = 0; i < descriptor->nested_type_count(); ++i) { + if (HasExtensionsOrExtendableMessage(descriptor->nested_type(i))) { + return true; + } + } + return false; +} + +bool HasExtensionsOrExtendableMessage(const FileDescriptor* file) { + if (file->extension_count() > 0) return true; + for (int i = 0; i < file->message_type_count(); ++i) { + if (HasExtensionsOrExtendableMessage(file->message_type(i))) return true; + } + return false; +} static bool HasMapFields(const Descriptor* descriptor) { for (int i = 0; i < descriptor->field_count(); ++i) { @@ -543,88 +938,127 @@ bool IsStringOrMessage(const FieldDescriptor* field) { return false; } -FieldOptions::CType EffectiveStringCType(const FieldDescriptor* field) { +FieldOptions::CType EffectiveStringCType(const FieldDescriptor* field, + const Options& options) { GOOGLE_DCHECK(field->cpp_type() == FieldDescriptor::CPPTYPE_STRING); - // Open-source protobuf release only supports STRING ctype. - return FieldOptions::STRING; - + if (options.opensource_runtime) { + // Open-source protobuf release only supports STRING ctype. + return FieldOptions::STRING; + } else { + // Google-internal supports all ctypes. + return field->options().ctype(); + } } -bool IsAnyMessage(const FileDescriptor* descriptor) { +bool IsAnyMessage(const FileDescriptor* descriptor, const Options& options) { return descriptor->name() == kAnyProtoFile; } -bool IsAnyMessage(const Descriptor* descriptor) { +bool IsAnyMessage(const Descriptor* descriptor, const Options& options) { return descriptor->name() == kAnyMessageName && - descriptor->file()->name() == kAnyProtoFile; + IsAnyMessage(descriptor->file(), options); } -bool IsWellKnownMessage(const FileDescriptor* descriptor) { - return !descriptor->name().compare(0, 16, kGoogleProtobufPrefix); +bool IsWellKnownMessage(const FileDescriptor* file) { + static const std::unordered_set well_known_files{ + "google/protobuf/any.proto", + "google/protobuf/api.proto", + "google/protobuf/compiler/plugin.proto", + "google/protobuf/descriptor.proto", + "google/protobuf/duration.proto", + "google/protobuf/empty.proto", + "google/protobuf/field_mask.proto", + "google/protobuf/source_context.proto", + "google/protobuf/struct.proto", + "google/protobuf/timestamp.proto", + "google/protobuf/type.proto", + "google/protobuf/wrappers.proto", + }; + return well_known_files.find(file->name()) != well_known_files.end(); } enum Utf8CheckMode { STRICT = 0, // Parsing will fail if non UTF-8 data is in string fields. VERIFY = 1, // Only log an error but parsing will succeed. - NONE = 2, // No UTF-8 check. + NONE = 2, // No UTF-8 check. }; +static bool FieldEnforceUtf8(const FieldDescriptor* field, + const Options& options) { + return true; +} + +static bool FileUtf8Verification(const FileDescriptor* file, + const Options& options) { + return true; +} + // Which level of UTF-8 enforcemant is placed on this file. static Utf8CheckMode GetUtf8CheckMode(const FieldDescriptor* field, const Options& options) { - if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) { + if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 && + FieldEnforceUtf8(field, options)) { return STRICT; } else if (GetOptimizeFor(field->file(), options) != - FileOptions::LITE_RUNTIME) { + FileOptions::LITE_RUNTIME && + FileUtf8Verification(field->file(), options)) { return VERIFY; } else { return NONE; } } +std::string GetUtf8Suffix(const FieldDescriptor* field, + const Options& options) { + switch (GetUtf8CheckMode(field, options)) { + case STRICT: + return "UTF8"; + case VERIFY: + return "UTF8Verify"; + case NONE: + default: // Some build configs warn on missing return without default. + return ""; + } +} + static void GenerateUtf8CheckCode(const FieldDescriptor* field, const Options& options, bool for_parse, - const std::map& variables, const char* parameters, const char* strict_function, const char* verify_function, - io::Printer* printer) { + const Formatter& format) { switch (GetUtf8CheckMode(field, options)) { case STRICT: { if (for_parse) { - printer->Print("DO_("); + format("DO_("); } - printer->Print( - "::google::protobuf::internal::WireFormatLite::$function$(\n", - "function", strict_function); - printer->Indent(); - printer->Print(variables, parameters); + format("::$proto_ns$::internal::WireFormatLite::$1$(\n", strict_function); + format.Indent(); + format(parameters); if (for_parse) { - printer->Print("::google::protobuf::internal::WireFormatLite::PARSE,\n"); + format("::$proto_ns$::internal::WireFormatLite::PARSE,\n"); } else { - printer->Print("::google::protobuf::internal::WireFormatLite::SERIALIZE,\n"); + format("::$proto_ns$::internal::WireFormatLite::SERIALIZE,\n"); } - printer->Print("\"$full_name$\")", "full_name", field->full_name()); + format("\"$1$\")", field->full_name()); if (for_parse) { - printer->Print(")"); + format(")"); } - printer->Print(";\n"); - printer->Outdent(); + format(";\n"); + format.Outdent(); break; } case VERIFY: { - printer->Print( - "::google::protobuf::internal::WireFormat::$function$(\n", - "function", verify_function); - printer->Indent(); - printer->Print(variables, parameters); + format("::$proto_ns$::internal::WireFormat::$1$(\n", verify_function); + format.Indent(); + format(parameters); if (for_parse) { - printer->Print("::google::protobuf::internal::WireFormat::PARSE,\n"); + format("::$proto_ns$::internal::WireFormat::PARSE,\n"); } else { - printer->Print("::google::protobuf::internal::WireFormat::SERIALIZE,\n"); + format("::$proto_ns$::internal::WireFormat::SERIALIZE,\n"); } - printer->Print("\"$full_name$\");\n", "full_name", field->full_name()); - printer->Outdent(); + format("\"$1$\");\n", field->full_name()); + format.Outdent(); break; } case NONE: @@ -634,21 +1068,19 @@ static void GenerateUtf8CheckCode(const FieldDescriptor* field, void GenerateUtf8CheckCodeForString(const FieldDescriptor* field, const Options& options, bool for_parse, - const std::map& variables, const char* parameters, - io::Printer* printer) { - GenerateUtf8CheckCode(field, options, for_parse, variables, parameters, + const Formatter& format) { + GenerateUtf8CheckCode(field, options, for_parse, parameters, "VerifyUtf8String", "VerifyUTF8StringNamedField", - printer); + format); } void GenerateUtf8CheckCodeForCord(const FieldDescriptor* field, const Options& options, bool for_parse, - const std::map& variables, const char* parameters, - io::Printer* printer) { - GenerateUtf8CheckCode(field, options, for_parse, variables, parameters, - "VerifyUtf8Cord", "VerifyUTF8CordNamedField", printer); + const Formatter& format) { + GenerateUtf8CheckCode(field, options, for_parse, parameters, "VerifyUtf8Cord", + "VerifyUTF8CordNamedField", format); } namespace { @@ -669,11 +1101,17 @@ void FlattenMessagesInFile(const FileDescriptor* file, } } -bool HasWeakFields(const Descriptor* descriptor) { +bool HasWeakFields(const Descriptor* descriptor, const Options& options) { + for (int i = 0; i < descriptor->field_count(); i++) { + if (IsWeak(descriptor->field(i), options)) return true; + } return false; } -bool HasWeakFields(const FileDescriptor* file) { +bool HasWeakFields(const FileDescriptor* file, const Options& options) { + for (int i = 0; i < file->message_type_count(); ++i) { + if (HasWeakFields(file->message_type(i), options)) return true; + } return false; } @@ -684,97 +1122,32 @@ bool UsingImplicitWeakFields(const FileDescriptor* file, } bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options, - SCCAnalyzer* scc_analyzer) { + MessageSCCAnalyzer* scc_analyzer) { return UsingImplicitWeakFields(field->file(), options) && field->type() == FieldDescriptor::TYPE_MESSAGE && !field->is_required() && !field->is_map() && - field->containing_oneof() == NULL && + field->containing_oneof() == nullptr && !IsWellKnownMessage(field->message_type()->file()) && + field->message_type()->file()->name() != + "net/proto2/proto/descriptor.proto" && // We do not support implicit weak fields between messages in the same // strongly-connected component. scc_analyzer->GetSCC(field->containing_type()) != scc_analyzer->GetSCC(field->message_type()); } -struct CompareDescriptors { - bool operator()(const Descriptor* a, const Descriptor* b) { - return a->full_name() < b->full_name(); - } -}; - -SCCAnalyzer::NodeData SCCAnalyzer::DFS(const Descriptor* descriptor) { - // Must not have visited already. - GOOGLE_DCHECK_EQ(cache_.count(descriptor), 0); - - // Mark visited by inserting in map. - NodeData& result = cache_[descriptor]; - // Initialize data structures. - result.index = result.lowlink = index_++; - stack_.push_back(descriptor); - - // Recurse the fields / nodes in graph - for (int i = 0; i < descriptor->field_count(); i++) { - const Descriptor* child = descriptor->field(i)->message_type(); - if (child) { - if (cache_.count(child) == 0) { - // unexplored node - NodeData child_data = DFS(child); - result.lowlink = std::min(result.lowlink, child_data.lowlink); - } else { - NodeData child_data = cache_[child]; - if (child_data.scc == NULL) { - // Still in the stack_ so we found a back edge - result.lowlink = std::min(result.lowlink, child_data.index); - } - } - } - } - if (result.index == result.lowlink) { - // This is the root of a strongly connected component - SCC* scc = CreateSCC(); - while (true) { - const Descriptor* scc_desc = stack_.back(); - scc->descriptors.push_back(scc_desc); - // Remove from stack - stack_.pop_back(); - cache_[scc_desc].scc = scc; - - if (scc_desc == descriptor) break; - } - - // The order of descriptors is random and depends how this SCC was - // discovered. In-order to ensure maximum stability we sort it by name. - std::sort(scc->descriptors.begin(), scc->descriptors.end(), - CompareDescriptors()); - AddChildren(scc); - } - return result; -} - -void SCCAnalyzer::AddChildren(SCC* scc) { - std::set seen; - for (int i = 0; i < scc->descriptors.size(); i++) { - const Descriptor* descriptor = scc->descriptors[i]; - for (int j = 0; j < descriptor->field_count(); j++) { - const Descriptor* child_msg = descriptor->field(j)->message_type(); - if (child_msg) { - const SCC* child = GetSCC(child_msg); - if (child == scc) continue; - if (seen.insert(child).second) { - scc->children.push_back(child); - } - } - } - } -} - -MessageAnalysis SCCAnalyzer::GetSCCAnalysis(const SCC* scc) { +MessageAnalysis MessageSCCAnalyzer::GetSCCAnalysis(const SCC* scc) { if (analysis_cache_.count(scc)) return analysis_cache_[scc]; - MessageAnalysis result = MessageAnalysis(); + MessageAnalysis result{}; for (int i = 0; i < scc->descriptors.size(); i++) { const Descriptor* descriptor = scc->descriptors[i]; if (descriptor->extension_range_count() > 0) { result.contains_extension = true; + // Extensions are found by looking up default_instance and extension + // number in a map. So you'd maybe expect here + // result.constructor_requires_initialization = true; + // However the extension registration mechanism already makes sure + // the default will be initialized. } for (int i = 0; i < descriptor->field_count(); i++) { const FieldDescriptor* field = descriptor->field(i); @@ -784,6 +1157,7 @@ MessageAnalysis SCCAnalyzer::GetSCCAnalysis(const SCC* scc) { switch (field->type()) { case FieldDescriptor::TYPE_STRING: case FieldDescriptor::TYPE_BYTES: { + result.constructor_requires_initialization = true; if (field->options().ctype() == FieldOptions::CORD) { result.contains_cord = true; } @@ -791,7 +1165,8 @@ MessageAnalysis SCCAnalyzer::GetSCCAnalysis(const SCC* scc) { } case FieldDescriptor::TYPE_GROUP: case FieldDescriptor::TYPE_MESSAGE: { - const SCC* child = GetSCC(field->message_type()); + result.constructor_requires_initialization = true; + const SCC* child = analyzer_.GetSCC(field->message_type()); if (child != scc) { MessageAnalysis analysis = GetSCCAnalysis(child); result.contains_cord |= analysis.contains_cord; @@ -860,6 +1235,608 @@ void ListAllTypesForServices(const FileDescriptor* fd, } } +bool GetBootstrapBasename(const Options& options, const std::string& basename, + std::string* bootstrap_basename) { + if (options.opensource_runtime) { + return false; + } + + std::unordered_map bootstrap_mapping{ + {"net/proto2/proto/descriptor", + "net/proto2/internal/descriptor"}, + {"net/proto2/compiler/proto/plugin", + "net/proto2/compiler/proto/plugin"}, + {"net/proto2/compiler/proto/profile", + "net/proto2/compiler/proto/profile_bootstrap"}, + }; + auto iter = bootstrap_mapping.find(basename); + if (iter == bootstrap_mapping.end()) { + *bootstrap_basename = basename; + return false; + } else { + *bootstrap_basename = iter->second; + return true; + } +} + +bool IsBootstrapProto(const Options& options, const FileDescriptor* file) { + std::string my_name = StripProto(file->name()); + return GetBootstrapBasename(options, my_name, &my_name); +} + +bool MaybeBootstrap(const Options& options, GeneratorContext* generator_context, + bool bootstrap_flag, std::string* basename) { + std::string bootstrap_basename; + if (!GetBootstrapBasename(options, *basename, &bootstrap_basename)) { + return false; + } + + if (bootstrap_flag) { + // Adjust basename, but don't abort code generation. + *basename = bootstrap_basename; + return false; + } else { + std::string forward_to_basename = bootstrap_basename; + + // Generate forwarding headers and empty .pb.cc. + { + std::unique_ptr output( + generator_context->Open(*basename + ".pb.h")); + io::Printer printer(output.get(), '$', nullptr); + printer.Print( + "#ifndef PROTOBUF_INCLUDED_$filename_identifier$_FORWARD_PB_H\n" + "#define PROTOBUF_INCLUDED_$filename_identifier$_FORWARD_PB_H\n" + "#include \"$forward_to_basename$.pb.h\" // IWYU pragma: export\n" + "#endif // PROTOBUF_INCLUDED_$filename_identifier$_FORWARD_PB_H\n", + "forward_to_basename", forward_to_basename, "filename_identifier", + FilenameIdentifier(*basename)); + + if (!options.opensource_runtime) { + // HACK HACK HACK, tech debt from the deeps of proto1 and SWIG + // protocoltype is SWIG'ed and we need to forward + if (*basename == "net/proto/protocoltype") { + printer.Print( + "#ifdef SWIG\n" + "%include \"$forward_to_basename$.pb.h\"\n" + "#endif // SWIG\n", + "forward_to_basename", forward_to_basename); + } + } + } + + { + std::unique_ptr output( + generator_context->Open(*basename + ".proto.h")); + io::Printer printer(output.get(), '$', nullptr); + printer.Print( + "#ifndef PROTOBUF_INCLUDED_$filename_identifier$_FORWARD_PROTO_H\n" + "#define PROTOBUF_INCLUDED_$filename_identifier$_FORWARD_PROTO_H\n" + "#include \"$forward_to_basename$.proto.h\" // IWYU pragma: " + "export\n" + "#endif // " + "PROTOBUF_INCLUDED_$filename_identifier$_FORWARD_PROTO_H\n", + "forward_to_basename", forward_to_basename, "filename_identifier", + FilenameIdentifier(*basename)); + } + + { + std::unique_ptr output( + generator_context->Open(*basename + ".pb.cc")); + io::Printer printer(output.get(), '$', nullptr); + printer.Print("\n"); + } + + { + std::unique_ptr output( + generator_context->Open(*basename + ".pb.h.meta")); + } + + { + std::unique_ptr output( + generator_context->Open(*basename + ".proto.h.meta")); + } + + // Abort code generation. + return true; + } +} + +class ParseLoopGenerator { + public: + ParseLoopGenerator(int num_hasbits, const Options& options, + MessageSCCAnalyzer* scc_analyzer, io::Printer* printer) + : scc_analyzer_(scc_analyzer), + options_(options), + format_(printer), + num_hasbits_(num_hasbits) {} + + void GenerateParserLoop(const Descriptor* descriptor) { + format_.Set("classname", ClassName(descriptor)); + format_.Set("p_ns", "::" + ProtobufNamespace(options_)); + format_.Set("pi_ns", + StrCat("::", ProtobufNamespace(options_), "::internal")); + format_.Set("GOOGLE_PROTOBUF", MacroPrefix(options_)); + std::map vars; + SetCommonVars(options_, &vars); + format_.AddMap(vars); + + std::vector ordered_fields; + for (auto field : FieldRange(descriptor)) { + ordered_fields.push_back(field); + } + std::sort(ordered_fields.begin(), ordered_fields.end(), + [](const FieldDescriptor* a, const FieldDescriptor* b) { + return a->number() < b->number(); + }); + + format_( + "const char* $classname$::_InternalParse(const char* ptr, " + "$pi_ns$::ParseContext* ctx) {\n" + "#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure\n"); + format_.Indent(); + int hasbits_size = 0; + if (HasFieldPresence(descriptor->file())) { + hasbits_size = (num_hasbits_ + 31) / 32; + } + // For now only optimize small hasbits. + if (hasbits_size != 1) hasbits_size = 0; + if (hasbits_size) { + format_("HasBitSetters::HasBits has_bits{};\n"); + format_.Set("has_bits", "has_bits"); + } else { + format_.Set("has_bits", "_has_bits_"); + } + + if (descriptor->file()->options().cc_enable_arenas()) { + format_("$p_ns$::Arena* arena = GetArenaNoVirtual(); (void)arena;\n"); + } + GenerateParseLoop(descriptor, ordered_fields); + format_.Outdent(); + format_("success:\n"); + if (hasbits_size) format_(" _has_bits_.Or(has_bits);\n"); + format_( + " return ptr;\n" + "failure:\n" + " ptr = nullptr;\n" + " goto success;\n" + "#undef CHK_\n" + "}\n"); + } + + private: + MessageSCCAnalyzer* scc_analyzer_; + const Options& options_; + Formatter format_; + int num_hasbits_; + + using WireFormat = internal::WireFormat; + using WireFormatLite = internal::WireFormatLite; + + void GenerateArenaString(const FieldDescriptor* field, + const std::string& utf8, std::string field_name) { + if (!field_name.empty()) { + format_("static const char kFieldName[] = $1$;\n", + field_name.substr(2)); // remove ", " + field_name = ", kFieldName"; + } + if (HasFieldPresence(field->file())) { + format_("HasBitSetters::set_has_$1$(&$has_bits$);\n", FieldName(field)); + } + string default_string = + field->default_value_string().empty() + ? "::" + ProtobufNamespace(options_) + + "::internal::GetEmptyStringAlreadyInited()" + : QualifiedClassName(field->containing_type(), options_) + + "::" + MakeDefaultName(field) + ".get()"; + format_( + "if (arena != nullptr) {\n" + " ptr = $pi_ns$::InlineCopyIntoArenaString$1$(&$2$_, ptr, ctx, " + " arena$3$);\n" + "} else {\n" + " ptr = " + "$pi_ns$::InlineGreedyStringParser$1$($2$_.MutableNoArenaNoDefault(&$4$" + "), ptr, ctx$3$);" + "\n}\n", + utf8, FieldName(field), field_name, default_string); + } + + void GenerateStrings(const FieldDescriptor* field, bool check_utf8) { + std::string utf8; + std::string field_name; + if (check_utf8) { + utf8 = GetUtf8Suffix(field, options_); + if (!utf8.empty()) { + field_name = ", nullptr"; + if (HasDescriptorMethods(field->file(), options_)) { + field_name = StrCat(", \"", field->full_name(), "\""); + } + } + } + FieldOptions::CType ctype = FieldOptions::STRING; + if (!options_.opensource_runtime) { + // Open source doesn't support other ctypes; + ctype = field->options().ctype(); + } + if (field->file()->options().cc_enable_arenas() && !field->is_repeated() && + !options_.opensource_runtime && + GetOptimizeFor(field->file(), options_) != FileOptions::LITE_RUNTIME && + // For now only use arena string for strings with empty defaults. + field->default_value_string().empty() && + !IsStringInlined(field, options_) && + field->containing_oneof() == nullptr && ctype == FieldOptions::STRING) { + GenerateArenaString(field, utf8, field_name); + return; + } + std::string name; + switch (ctype) { + case FieldOptions::STRING: + name = "GreedyStringParser" + utf8; + break; + case FieldOptions::CORD: + name = "CordParser" + utf8; + break; + case FieldOptions::STRING_PIECE: + name = "StringPieceParser" + utf8; + break; + } + format_("ptr = $pi_ns$::Inline$1$($2$_$3$(), ptr, ctx$4$);\n", name, + field->is_repeated() && !field->is_packable() ? "add" : "mutable", + FieldName(field), field_name); + } + + void GenerateLengthDelim(const FieldDescriptor* field) { + if (field->is_packable()) { + std::string enum_validator; + if (field->type() == FieldDescriptor::TYPE_ENUM && + !HasPreservingUnknownEnumSemantics(field)) { + enum_validator = StrCat( + ", ", QualifiedClassName(field->enum_type(), options_), + "_IsValid, mutable_unknown_fields(), ", field->number()); + } + format_("ptr = $pi_ns$::Packed$1$Parser(mutable_$2$(), ptr, ctx$3$);\n", + DeclaredTypeMethodName(field->type()), FieldName(field), + enum_validator); + } else { + auto field_type = field->type(); + switch (field_type) { + case FieldDescriptor::TYPE_STRING: + GenerateStrings(field, true /* utf8 */); + break; + case FieldDescriptor::TYPE_BYTES: + GenerateStrings(field, false /* utf8 */); + break; + case FieldDescriptor::TYPE_MESSAGE: { + if (field->is_map()) { + const FieldDescriptor* val = + field->message_type()->FindFieldByName("value"); + GOOGLE_CHECK(val); + if (HasFieldPresence(field->file()) && + val->type() == FieldDescriptor::TYPE_ENUM) { + format_( + "auto object = ::$proto_ns$::internal::InitEnumParseWrapper(" + "&$1$_, $2$_IsValid, $3$, &_internal_metadata_);\n" + "ptr = ctx->ParseMessage(&object, ptr);\n", + FieldName(field), QualifiedClassName(val->enum_type()), + field->number()); + } else { + format_("ptr = ctx->ParseMessage(&$1$_, ptr);\n", + FieldName(field)); + } + } else if (IsLazy(field, options_)) { + if (field->containing_oneof() != nullptr) { + format_( + "if (!has_$1$()) {\n" + " clear_$1$();\n" + " $2$_.$1$_ = ::$proto_ns$::Arena::CreateMessage<\n" + " $pi_ns$::LazyField>(" + "GetArenaNoVirtual());\n" + " set_has_$1$();\n" + "}\n" + "ptr = ctx->ParseMessage($2$_.$1$_, ptr);\n", + FieldName(field), field->containing_oneof()->name()); + } else if (HasFieldPresence(field->file())) { + format_( + "HasBitSetters::set_has_$1$(&$has_bits$);\n" + "ptr = ctx->ParseMessage(&$1$_, ptr);\n", + FieldName(field)); + } else { + format_("ptr = ctx->ParseMessage(&$1$_, ptr);\n", + FieldName(field)); + } + } else if (IsImplicitWeakField(field, options_, scc_analyzer_)) { + if (!field->is_repeated()) { + format_( + "ptr = ctx->ParseMessage(HasBitSetters::mutable_$1$(this), " + "ptr);\n", + FieldName(field)); + } else { + format_( + "ptr = ctx->ParseMessage(" + "CastToBase(&$1$_)->AddWeak(reinterpret_cast(&$2$::_$3$_default_instance_)), " + "ptr);\n", + FieldName(field), Namespace(field->message_type(), options_), + ClassName(field->message_type())); + } + } else if (IsWeak(field, options_)) { + format_( + "ptr = ctx->ParseMessage(_weak_field_map_.MutableMessage($1$," + " _$classname$_default_instance_.$2$_), ptr);\n", + field->number(), FieldName(field)); + } else { + format_("ptr = ctx->ParseMessage($1$_$2$(), ptr);\n", + field->is_repeated() ? "add" : "mutable", FieldName(field)); + } + break; + } + default: + GOOGLE_LOG(FATAL) << "Illegal combination for length delimited wiretype " + << " filed type is " << field->type(); + } + } + } + + // Convert a 1 or 2 byte varint into the equivalent value upon a direct load. + static uint32 SmallVarintValue(uint32 x) { + GOOGLE_DCHECK(x < 128 * 128); + if (x >= 128) x += (x & 0xFF80) + 128; + return x; + } + + static bool ShouldRepeat(const FieldDescriptor* descriptor, + internal::WireFormatLite::WireType wiretype) { + constexpr int kMaxTwoByteFieldNumber = 16 * 128; + return descriptor->number() < kMaxTwoByteFieldNumber && + descriptor->is_repeated() && + (!descriptor->is_packable() || + wiretype != internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED); + } + + void GenerateFieldBody(internal::WireFormatLite::WireType wiretype, + const FieldDescriptor* field) { + uint32 tag = WireFormatLite::MakeTag(field->number(), wiretype); + switch (wiretype) { + case WireFormatLite::WIRETYPE_VARINT: { + std::string type = PrimitiveTypeName(options_, field->cpp_type()); + std::string prefix = field->is_repeated() ? "add" : "set"; + if (field->type() == FieldDescriptor::TYPE_ENUM) { + format_( + "$uint64$ val = $pi_ns$::ReadVarint(&ptr);\n" + "CHK_(ptr);\n"); + if (!HasPreservingUnknownEnumSemantics(field)) { + format_("if (PROTOBUF_PREDICT_TRUE($1$_IsValid(val))) {\n", + QualifiedClassName(field->enum_type(), options_)); + format_.Indent(); + } + format_("$1$_$2$(static_cast<$3$>(val));\n", prefix, FieldName(field), + QualifiedClassName(field->enum_type(), options_)); + if (!HasPreservingUnknownEnumSemantics(field)) { + format_.Outdent(); + format_( + "} else {\n" + " $pi_ns$::WriteVarint($1$, val, mutable_unknown_fields());\n" + "}\n", + field->number()); + } + } else { + int size = field->type() == FieldDescriptor::TYPE_SINT32 ? 32 : 64; + std::string zigzag; + if ((field->type() == FieldDescriptor::TYPE_SINT32 || + field->type() == FieldDescriptor::TYPE_SINT64)) { + zigzag = StrCat("ZigZag", size); + } + if (field->is_repeated() || field->containing_oneof()) { + string prefix = field->is_repeated() ? "add" : "set"; + format_( + "$1$_$2$($pi_ns$::ReadVarint$3$(&ptr));\n" + "CHK_(ptr);\n", + prefix, FieldName(field), zigzag); + } else { + if (HasFieldPresence(field->file())) { + format_("HasBitSetters::set_has_$1$(&$has_bits$);\n", + FieldName(field)); + } + format_( + "$1$_ = $pi_ns$::ReadVarint$2$(&ptr);\n" + "CHK_(ptr);\n", + FieldName(field), zigzag); + } + } + break; + } + case WireFormatLite::WIRETYPE_FIXED32: + case WireFormatLite::WIRETYPE_FIXED64: { + std::string type = PrimitiveTypeName(options_, field->cpp_type()); + if (field->is_repeated() || field->containing_oneof()) { + string prefix = field->is_repeated() ? "add" : "set"; + format_( + "$1$_$2$($pi_ns$::UnalignedLoad<$3$>(ptr));\n" + "ptr += sizeof($3$);\n", + prefix, FieldName(field), type); + } else { + if (HasFieldPresence(field->file())) { + format_("HasBitSetters::set_has_$1$(&$has_bits$);\n", + FieldName(field)); + } + format_( + "$1$_ = $pi_ns$::UnalignedLoad<$2$>(ptr);\n" + "ptr += sizeof($2$);\n", + FieldName(field), type); + } + break; + } + case WireFormatLite::WIRETYPE_LENGTH_DELIMITED: { + GenerateLengthDelim(field); + format_("CHK_(ptr);\n"); + break; + } + case WireFormatLite::WIRETYPE_START_GROUP: { + format_( + "ptr = ctx->ParseGroup($1$_$2$(), ptr, $3$);\n" + "CHK_(ptr);\n", + field->is_repeated() ? "add" : "mutable", FieldName(field), tag); + break; + } + case WireFormatLite::WIRETYPE_END_GROUP: { + GOOGLE_LOG(FATAL) << "Can't have end group field\n"; + break; + } + } // switch (wire_type) + } + + // Returns the tag for this field and in case of repeated packable fields, + // sets a fallback tag in fallback_tag_ptr. + static uint32 ExpectedTag(const FieldDescriptor* field, + uint32* fallback_tag_ptr) { + uint32 expected_tag; + if (field->is_packable()) { + auto expected_wiretype = WireFormat::WireTypeForFieldType(field->type()); + expected_tag = + WireFormatLite::MakeTag(field->number(), expected_wiretype); + GOOGLE_CHECK(expected_wiretype != WireFormatLite::WIRETYPE_LENGTH_DELIMITED); + auto fallback_wiretype = WireFormatLite::WIRETYPE_LENGTH_DELIMITED; + uint32 fallback_tag = + WireFormatLite::MakeTag(field->number(), fallback_wiretype); + + if (field->is_packed()) std::swap(expected_tag, fallback_tag); + *fallback_tag_ptr = fallback_tag; + } else { + auto expected_wiretype = WireFormat::WireTypeForField(field); + expected_tag = + WireFormatLite::MakeTag(field->number(), expected_wiretype); + } + return expected_tag; + } + + void GenerateParseLoop( + const Descriptor* descriptor, + const std::vector& ordered_fields) { + format_( + "while (!ctx->Done(&ptr)) {\n" + " $uint32$ tag;\n" + " ptr = $pi_ns$::ReadTag(ptr, &tag);\n" + " CHK_(ptr);\n" + " switch (tag >> 3) {\n"); + + format_.Indent(); + format_.Indent(); + + for (const auto* field : ordered_fields) { + // Print the field's (or oneof's) proto-syntax definition as a comment. + // We don't want to print group bodies so we cut off after the first + // line. + std::string def; + { + DebugStringOptions options; + options.elide_group_body = true; + options.elide_oneof_body = true; + def = field->DebugStringWithOptions(options); + def = def.substr(0, def.find_first_of('\n')); + } + format_( + "// $1$\n" + "case $2$:\n", + def, field->number()); + format_.Indent(); + uint32 fallback_tag = 0; + uint32 expected_tag = ExpectedTag(field, &fallback_tag); + format_( + "if (PROTOBUF_PREDICT_TRUE(static_cast<$uint8$>(tag) == $1$)) {\n", + expected_tag & 0xFF); + format_.Indent(); + auto wiretype = WireFormatLite::GetTagWireType(expected_tag); + uint32 tag = WireFormatLite::MakeTag(field->number(), wiretype); + int tag_size = io::CodedOutputStream::VarintSize32(tag); + bool is_repeat = ShouldRepeat(field, wiretype); + if (is_repeat) { + format_( + "ptr -= $1$;\n" + "do {\n" + " ptr += $1$;\n", + tag_size); + format_.Indent(); + } + GenerateFieldBody(wiretype, field); + if (is_repeat) { + string type = tag_size == 2 ? "uint16" : "uint8"; + format_.Outdent(); + format_( + " if (!ctx->DataAvailable(ptr)) break;\n" + "} while ($pi_ns$::UnalignedLoad<$1$>(ptr) == $2$);\n", + IntTypeName(options_, type), SmallVarintValue(tag)); + } + format_.Outdent(); + if (fallback_tag) { + format_("} else if (static_cast<$uint8$>(tag) == $1$) {\n", + fallback_tag & 0xFF); + format_.Indent(); + GenerateFieldBody(WireFormatLite::GetTagWireType(fallback_tag), field); + format_.Outdent(); + } + format_.Outdent(); + format_( + " } else goto handle_unusual;\n" + " continue;\n"); + } // for loop over ordered fields + + // Default case + format_("default: {\n"); + if (!ordered_fields.empty()) format_("handle_unusual:\n"); + format_( + " if ((tag & 7) == 4 || tag == 0) {\n" + " ctx->SetLastTag(tag);\n" + " goto success;\n" + " }\n"); + if (IsMapEntryMessage(descriptor)) { + format_(" continue;\n"); + } else { + if (descriptor->extension_range_count() > 0) { + format_("if ("); + for (int i = 0; i < descriptor->extension_range_count(); i++) { + const Descriptor::ExtensionRange* range = + descriptor->extension_range(i); + if (i > 0) format_(" ||\n "); + + uint32 start_tag = WireFormatLite::MakeTag( + range->start, static_cast(0)); + uint32 end_tag = WireFormatLite::MakeTag( + range->end, static_cast(0)); + + if (range->end > FieldDescriptor::kMaxNumber) { + format_("($1$u <= tag)", start_tag); + } else { + format_("($1$u <= tag && tag < $2$u)", start_tag, end_tag); + } + } + format_(") {\n"); + format_( + " ptr = _extensions_.ParseField(tag, ptr,\n" + " internal_default_instance(), &_internal_metadata_, ctx);\n" + " CHK_(ptr != nullptr);\n" + " continue;\n" + "}\n"); + } + format_( + " ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);\n" + " CHK_(ptr != nullptr);\n" + " continue;\n"); + } + format_("}\n"); // default case + format_.Outdent(); + format_.Outdent(); + format_( + " } // switch\n" + "} // while\n"); + } +}; + +void GenerateParserLoop(const Descriptor* descriptor, int num_hasbits, + const Options& options, + MessageSCCAnalyzer* scc_analyzer, + io::Printer* printer) { + ParseLoopGenerator generator(num_hasbits, options, scc_analyzer, printer); + generator.GenerateParserLoop(descriptor); +} } // namespace cpp } // namespace compiler diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_helpers.h b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_helpers.h index eac65124..52ecd6cf 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_helpers.h +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_helpers.h @@ -35,48 +35,75 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__ #define GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__ +#include +#include #include #include + #include +#include #include #include #include #include +#include #include + +#include + namespace google { namespace protobuf { namespace compiler { namespace cpp { +inline std::string ProtobufNamespace(const Options& options) { + return "PROTOBUF_NAMESPACE_ID"; +} + +inline std::string MacroPrefix(const Options& options) { + return options.opensource_runtime ? "GOOGLE_PROTOBUF" : "GOOGLE_PROTOBUF"; +} + +inline std::string DeprecatedAttribute(const Options& options, + bool deprecated) { + return deprecated ? "PROTOBUF_DEPRECATED " : ""; +} + // Commonly-used separator comments. Thick is a line of '=', thin is a line // of '-'. extern const char kThickSeparator[]; extern const char kThinSeparator[]; +void SetCommonVars(const Options& options, + std::map* variables); + +bool GetBootstrapBasename(const Options& options, const std::string& basename, + std::string* bootstrap_basename); +bool MaybeBootstrap(const Options& options, GeneratorContext* generator_context, + bool bootstrap_flag, std::string* basename); +bool IsBootstrapProto(const Options& options, const FileDescriptor* file); // Name space of the proto file. This namespace is such that the string // "::some_name" is the correct fully qualified namespace. // This means if the package is empty the namespace is "", and otherwise // the namespace is "::foo::bar::...::baz" without trailing semi-colons. -string Namespace(const string& package); -inline string Namespace(const FileDescriptor* d) { - return Namespace(d->package()); -} -template -string Namespace(const Desc* d) { - return Namespace(d->file()); -} +std::string Namespace(const FileDescriptor* d, const Options& options); +std::string Namespace(const Descriptor* d, const Options& options); +std::string Namespace(const FieldDescriptor* d, const Options& options); +std::string Namespace(const EnumDescriptor* d, const Options& options); // Returns true if it's safe to reset "field" to zero. bool CanInitializeByZeroing(const FieldDescriptor* field); -string ClassName(const Descriptor* descriptor); -string ClassName(const EnumDescriptor* enum_descriptor); -template -string QualifiedClassName(const Desc* d) { - return Namespace(d) + "::" + ClassName(d); -} +std::string ClassName(const Descriptor* descriptor); +std::string ClassName(const EnumDescriptor* enum_descriptor); + +std::string QualifiedClassName(const Descriptor* d, const Options& options); +std::string QualifiedClassName(const EnumDescriptor* d, const Options& options); + +std::string QualifiedClassName(const Descriptor* d); +std::string QualifiedClassName(const EnumDescriptor* d); // DEPRECATED just use ClassName or QualifiedClassName, a boolean is very // unreadable at the callsite. @@ -88,33 +115,57 @@ string QualifiedClassName(const Desc* d) { // ::foo::bar::Baz_Qux // While the non-qualified version would be: // Baz_Qux -inline string ClassName(const Descriptor* descriptor, bool qualified) { - return qualified ? QualifiedClassName(descriptor) : ClassName(descriptor); +inline std::string ClassName(const Descriptor* descriptor, bool qualified) { + return qualified ? QualifiedClassName(descriptor, Options()) + : ClassName(descriptor); } -inline string ClassName(const EnumDescriptor* descriptor, bool qualified) { - return qualified ? QualifiedClassName(descriptor) : ClassName(descriptor); +inline std::string ClassName(const EnumDescriptor* descriptor, bool qualified) { + return qualified ? QualifiedClassName(descriptor, Options()) + : ClassName(descriptor); } +// Type name of default instance. +std::string DefaultInstanceType(const Descriptor* descriptor, + const Options& options); + +// Non-qualified name of the default_instance of this message. +std::string DefaultInstanceName(const Descriptor* descriptor, + const Options& options); + // Fully qualified name of the default_instance of this message. -string DefaultInstanceName(const Descriptor* descriptor); +std::string QualifiedDefaultInstanceName(const Descriptor* descriptor, + const Options& options); + +// DescriptorTable variable name. +std::string DescriptorTableName(const FileDescriptor* file, + const Options& options); + +// When declaring symbol externs from another file, this macro will supply the +// dllexport needed for the target file, if any. +std::string FileDllExport(const FileDescriptor* file, const Options& options); // Returns the name of a no-op function that we can call to introduce a linker // dependency on the given message type. This is used to implement implicit weak // fields. -string ReferenceFunctionName(const Descriptor* descriptor); +std::string ReferenceFunctionName(const Descriptor* descriptor, + const Options& options); // Name of the base class: google::protobuf::Message or google::protobuf::MessageLite. -string SuperClassName(const Descriptor* descriptor, const Options& options); +std::string SuperClassName(const Descriptor* descriptor, + const Options& options); + +// Adds an underscore if necessary to prevent conflicting with a keyword. +std::string ResolveKeyword(const string& name); // Get the (unqualified) name that should be used for this field in C++ code. // The name is coerced to lower-case to emulate proto1 behavior. People // should be using lowercase-with-underscores style for proto field names // anyway, so normally this just returns field->name(). -string FieldName(const FieldDescriptor* field); +std::string FieldName(const FieldDescriptor* field); // Get the sanitized name that should be used for the given enum in C++ code. -string EnumValueName(const EnumValueDescriptor* enum_value); +std::string EnumValueName(const EnumValueDescriptor* enum_value); // Returns an estimate of the compiler's alignment for the field. This // can't guarantee to be correct because the generated code could be compiled on @@ -124,75 +175,108 @@ int EstimateAlignmentSize(const FieldDescriptor* field); // Get the unqualified name that should be used for a field's field // number constant. -string FieldConstantName(const FieldDescriptor *field); +std::string FieldConstantName(const FieldDescriptor* field); // Returns the scope where the field was defined (for extensions, this is // different from the message type to which the field applies). inline const Descriptor* FieldScope(const FieldDescriptor* field) { - return field->is_extension() ? - field->extension_scope() : field->containing_type(); + return field->is_extension() ? field->extension_scope() + : field->containing_type(); } // Returns the fully-qualified type name field->message_type(). Usually this // is just ClassName(field->message_type(), true); -string FieldMessageTypeName(const FieldDescriptor* field); +std::string FieldMessageTypeName(const FieldDescriptor* field, + const Options& options); // Strips ".proto" or ".protodevel" from the end of a filename. -LIBPROTOC_EXPORT string StripProto(const string& filename); +PROTOC_EXPORT std::string StripProto(const std::string& filename); // Get the C++ type name for a primitive type (e.g. "double", "::google::protobuf::int32", etc.). -// Note: non-built-in type names will be qualified, meaning they will start -// with a ::. If you are using the type as a template parameter, you will -// need to insure there is a space between the < and the ::, because the -// ridiculous C++ standard defines "<:" to be a synonym for "[". const char* PrimitiveTypeName(FieldDescriptor::CppType type); +std::string PrimitiveTypeName(const Options& options, + FieldDescriptor::CppType type); // Get the declared type name in CamelCase format, as is used e.g. for the // methods of WireFormat. For example, TYPE_INT32 becomes "Int32". const char* DeclaredTypeMethodName(FieldDescriptor::Type type); // Return the code that evaluates to the number when compiled. -string Int32ToString(int number); +std::string Int32ToString(int number); // Return the code that evaluates to the number when compiled. -string Int64ToString(int64 number); +std::string Int64ToString(const Options& options, int64 number); // Get code that evaluates to the field's default value. -string DefaultValue(const FieldDescriptor* field); +std::string DefaultValue(const Options& options, const FieldDescriptor* field); + +// Compatibility function for callers outside proto2. +std::string DefaultValue(const FieldDescriptor* field); // Convert a file name into a valid identifier. -string FilenameIdentifier(const string& filename); +std::string FilenameIdentifier(const std::string& filename); -// For each .proto file generates a unique namespace. In this namespace global -// definitions are put to prevent collisions. -string FileLevelNamespace(const string& filename); -inline string FileLevelNamespace(const FileDescriptor* file) { - return FileLevelNamespace(file->name()); +// For each .proto file generates a unique name. To prevent collisions of +// symbols in the global namespace +std::string UniqueName(const std::string& name, const std::string& filename, + const Options& options); +inline std::string UniqueName(const std::string& name, const FileDescriptor* d, + const Options& options) { + return UniqueName(name, d->name(), options); } -inline string FileLevelNamespace(const Descriptor* d) { - return FileLevelNamespace(d->file()); +inline std::string UniqueName(const std::string& name, const Descriptor* d, + const Options& options) { + return UniqueName(name, d->file(), options); +} +inline std::string UniqueName(const std::string& name, const EnumDescriptor* d, + const Options& options) { + return UniqueName(name, d->file(), options); +} +inline std::string UniqueName(const std::string& name, + const ServiceDescriptor* d, + const Options& options) { + return UniqueName(name, d->file(), options); +} + +// Versions for call sites that only support the internal runtime (like proto1 +// support). +inline Options InternalRuntimeOptions() { + Options options; + options.opensource_runtime = false; + return options; +} +inline std::string UniqueName(const std::string& name, + const std::string& filename) { + return UniqueName(name, filename, InternalRuntimeOptions()); +} +inline std::string UniqueName(const std::string& name, + const FileDescriptor* d) { + return UniqueName(name, d->name(), InternalRuntimeOptions()); +} +inline std::string UniqueName(const std::string& name, const Descriptor* d) { + return UniqueName(name, d->file(), InternalRuntimeOptions()); +} +inline std::string UniqueName(const std::string& name, + const EnumDescriptor* d) { + return UniqueName(name, d->file(), InternalRuntimeOptions()); +} +inline std::string UniqueName(const std::string& name, + const ServiceDescriptor* d) { + return UniqueName(name, d->file(), InternalRuntimeOptions()); } // Return the qualified C++ name for a file level symbol. -string QualifiedFileLevelSymbol(const string& package, const string& name); +std::string QualifiedFileLevelSymbol(const FileDescriptor* file, + const std::string& name, + const Options& options); // Escape C++ trigraphs by escaping question marks to \? -string EscapeTrigraphs(const string& to_escape); +std::string EscapeTrigraphs(const std::string& to_escape); // Escaped function name to eliminate naming conflict. -string SafeFunctionName(const Descriptor* descriptor, - const FieldDescriptor* field, - const string& prefix); - -// Returns true if unknown fields are always preserved after parsing. -inline bool AlwaysPreserveUnknownFields(const FileDescriptor* file) { - return file->syntax() != FileDescriptor::SYNTAX_PROTO3; -} - -// Returns true if unknown fields are preserved after parsing. -inline bool AlwaysPreserveUnknownFields(const Descriptor* message) { - return AlwaysPreserveUnknownFields(message->file()); -} +std::string SafeFunctionName(const Descriptor* descriptor, + const FieldDescriptor* field, + const std::string& prefix); // Returns true if generated messages have public unknown fields accessors inline bool PublicUnknownFieldsAccessors(const Descriptor* message) { @@ -200,8 +284,8 @@ inline bool PublicUnknownFieldsAccessors(const Descriptor* message) { } // Returns the optimize mode for , respecting . -::google::protobuf::FileOptions_OptimizeMode GetOptimizeFor( - const FileDescriptor* file, const Options& options); +FileOptions_OptimizeMode GetOptimizeFor(const FileDescriptor* file, + const Options& options); // Determines whether unknown fields will be stored in an UnknownFieldSet or // a string. @@ -210,6 +294,58 @@ inline bool UseUnknownFieldSet(const FileDescriptor* file, return GetOptimizeFor(file, options) != FileOptions::LITE_RUNTIME; } +inline bool IsWeak(const FieldDescriptor* field, const Options& options) { + if (field->options().weak()) { + GOOGLE_CHECK(!options.opensource_runtime); + return true; + } + return false; +} + +bool IsStringInlined(const FieldDescriptor* descriptor, const Options& options); + +// For a string field, returns the effective ctype. If the actual ctype is +// not supported, returns the default of STRING. +FieldOptions::CType EffectiveStringCType(const FieldDescriptor* field, + const Options& options); + +inline bool IsCord(const FieldDescriptor* field, const Options& options) { + return field->cpp_type() == FieldDescriptor::CPPTYPE_STRING && + EffectiveStringCType(field, options) == FieldOptions::CORD; +} + +inline bool IsStringPiece(const FieldDescriptor* field, + const Options& options) { + return field->cpp_type() == FieldDescriptor::CPPTYPE_STRING && + EffectiveStringCType(field, options) == FieldOptions::STRING_PIECE; +} + +// Does the given FileDescriptor use lazy fields? +bool HasLazyFields(const FileDescriptor* file, const Options& options); + +// Is the given field a supported lazy field? +inline bool IsLazy(const FieldDescriptor* field, const Options& options) { + return field->options().lazy() && !field->is_repeated() && + field->type() == FieldDescriptor::TYPE_MESSAGE && + GetOptimizeFor(field->file(), options) != FileOptions::LITE_RUNTIME && + !options.opensource_runtime; +} + +// Does the file contain any definitions that need extension_set.h? +bool HasExtensionsOrExtendableMessage(const FileDescriptor* file); + +// Does the file have any repeated fields, necessitating the file to include +// repeated_field.h? This does not include repeated extensions, since those are +// all stored internally in an ExtensionSet, not a separate RepeatedField*. +bool HasRepeatedFields(const FileDescriptor* file); + +// Does the file have any string/bytes fields with ctype=STRING_PIECE? This +// does not include extensions, since ctype is ignored for extensions. +bool HasStringPieceFields(const FileDescriptor* file, const Options& options); + +// Does the file have any string/bytes fields with ctype=CORD? This does not +// include extensions, since ctype is ignored for extensions. +bool HasCordFields(const FileDescriptor* file, const Options& options); // Does the file have any map fields, necessitating the file to include // map_field_inl.h and map.h. @@ -247,6 +383,22 @@ inline bool HasFastArraySerialization(const FileDescriptor* file, return GetOptimizeFor(file, options) == FileOptions::SPEED; } +inline bool IsProto2MessageSet(const Descriptor* descriptor, + const Options& options) { + return !options.opensource_runtime && + options.enforce_mode != EnforceOptimizeMode::kLiteRuntime && + !options.lite_implicit_weak_fields && + descriptor->options().message_set_wire_format() && + descriptor->full_name() == "google.protobuf.bridge.MessageSet"; +} + +inline bool IsProto2MessageSetFile(const FileDescriptor* file, + const Options& options) { + return !options.opensource_runtime && + options.enforce_mode != EnforceOptimizeMode::kLiteRuntime && + !options.lite_implicit_weak_fields && + file->name() == "net/proto2/bridge/proto/message_set.proto"; +} inline bool IsMapEntryMessage(const Descriptor* descriptor) { return descriptor->options().map_entry(); @@ -255,11 +407,8 @@ inline bool IsMapEntryMessage(const Descriptor* descriptor) { // Returns true if the field's CPPTYPE is string or message. bool IsStringOrMessage(const FieldDescriptor* field); -// For a string field, returns the effective ctype. If the actual ctype is -// not supported, returns the default of STRING. -FieldOptions::CType EffectiveStringCType(const FieldDescriptor* field); - -string UnderscoresToCamelCase(const string& input, bool cap_next_letter); +std::string UnderscoresToCamelCase(const std::string& input, + bool cap_next_letter); inline bool HasFieldPresence(const FileDescriptor* file) { return file->syntax() != FileDescriptor::SYNTAX_PROTO3; @@ -267,8 +416,8 @@ inline bool HasFieldPresence(const FileDescriptor* file) { // Returns true if 'enum' semantics are such that unknown values are preserved // in the enum field itself, rather than going to the UnknownFieldSet. -inline bool HasPreservingUnknownEnumSemantics(const FileDescriptor* file) { - return file->syntax() == FileDescriptor::SYNTAX_PROTO3; +inline bool HasPreservingUnknownEnumSemantics(const FieldDescriptor* field) { + return field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3; } inline bool SupportsArenas(const FileDescriptor* file) { @@ -288,36 +437,55 @@ inline bool IsCrossFileMessage(const FieldDescriptor* field) { field->message_type()->file() != field->file(); } -inline string MessageCreateFunction(const Descriptor* d) { +inline std::string MessageCreateFunction(const Descriptor* d) { return SupportsArenas(d) ? "CreateMessage" : "Create"; } -inline string MakeDefaultName(const FieldDescriptor* field) { +inline std::string MakeDefaultName(const FieldDescriptor* field) { return "_i_give_permission_to_break_this_code_default_" + FieldName(field) + "_"; } -bool IsAnyMessage(const FileDescriptor* descriptor); -bool IsAnyMessage(const Descriptor* descriptor); +bool IsAnyMessage(const FileDescriptor* descriptor, const Options& options); +bool IsAnyMessage(const Descriptor* descriptor, const Options& options); bool IsWellKnownMessage(const FileDescriptor* descriptor); -void GenerateUtf8CheckCodeForString(const FieldDescriptor* field, - const Options& options, bool for_parse, - const std::map& variables, - const char* parameters, - io::Printer* printer); +inline std::string IncludeGuard(const FileDescriptor* file, bool pb_h, + const Options& options) { + // If we are generating a .pb.h file and the proto_h option is enabled, then + // the .pb.h gets an extra suffix. + std::string filename_identifier = FilenameIdentifier( + file->name() + (pb_h && options.proto_h ? ".pb.h" : "")); -void GenerateUtf8CheckCodeForCord(const FieldDescriptor* field, - const Options& options, bool for_parse, - const std::map& variables, - const char* parameters, io::Printer* printer); + if (IsWellKnownMessage(file)) { + // For well-known messages we need third_party/protobuf and net/proto2 to + // have distinct include guards, because some source files include both and + // both need to be defined (the third_party copies will be in the + // google::protobuf_opensource namespace). + return MacroPrefix(options) + "_INCLUDED_" + filename_identifier; + } else { + // Ideally this case would use distinct include guards for opensource and + // google3 protos also. (The behavior of "first #included wins" is not + // ideal). But unfortunately some legacy code includes both and depends on + // the identical include guards to avoid compile errors. + // + // We should clean this up so that this case can be removed. + return "GOOGLE_PROTOBUF_INCLUDED_" + filename_identifier; + } +} -inline ::google::protobuf::FileOptions_OptimizeMode GetOptimizeFor( - const FileDescriptor* file, const Options& options) { - return options.enforce_lite - ? FileOptions::LITE_RUNTIME - : file->options().optimize_for(); +inline FileOptions_OptimizeMode GetOptimizeFor(const FileDescriptor* file, + const Options& options) { + switch (options.enforce_mode) { + case EnforceOptimizeMode::kSpeed: + return FileOptions::SPEED; + case EnforceOptimizeMode::kLiteRuntime: + return FileOptions::LITE_RUNTIME; + case EnforceOptimizeMode::kNoEnforcement: + default: + return file->options().optimize_for(); + } } // This orders the messages in a .pb.cc as it's outputted by file.cc @@ -330,80 +498,32 @@ inline std::vector FlattenMessagesInFile( return result; } -bool HasWeakFields(const Descriptor* desc); -bool HasWeakFields(const FileDescriptor* desc); +bool HasWeakFields(const Descriptor* desc, const Options& options); +bool HasWeakFields(const FileDescriptor* desc, const Options& options); // Returns true if the "required" restriction check should be ignored for the // given field. inline static bool ShouldIgnoreRequiredFieldCheck(const FieldDescriptor* field, const Options& options) { - return false; + // Do not check "required" for lazy fields. + return IsLazy(field, options); } -class LIBPROTOC_EXPORT NamespaceOpener { - public: - explicit NamespaceOpener(io::Printer* printer) : printer_(printer) {} - NamespaceOpener(const string& name, io::Printer* printer) - : printer_(printer) { - ChangeTo(name); - } - ~NamespaceOpener() { ChangeTo(""); } - - void ChangeTo(const string& name) { - std::vector new_stack_ = - Split(name, "::", true); - int len = std::min(name_stack_.size(), new_stack_.size()); - int common_idx = 0; - while (common_idx < len) { - if (name_stack_[common_idx] != new_stack_[common_idx]) break; - common_idx++; - } - for (int i = name_stack_.size() - 1; i >= common_idx; i--) { - printer_->Print("} // namespace $ns$\n", "ns", name_stack_[i]); - } - name_stack_.swap(new_stack_); - for (int i = common_idx; i < name_stack_.size(); i++) { - printer_->Print("namespace $ns$ {\n", "ns", name_stack_[i]); - } - } - - private: - io::Printer* printer_; - std::vector name_stack_; -}; - -// Description of each strongly connected component. Note that the order -// of both the descriptors in this SCC and the order of children is -// deterministic. -struct SCC { - std::vector descriptors; - std::vector children; - - const Descriptor* GetRepresentative() const { return descriptors[0]; } -}; - struct MessageAnalysis { bool is_recursive; bool contains_cord; bool contains_extension; bool contains_required; + bool constructor_requires_initialization; }; // This class is used in FileGenerator, to ensure linear instead of // quadratic performance, if we do this per message we would get O(V*(V+E)). // Logically this is just only used in message.cc, but in the header for // FileGenerator to help share it. -class LIBPROTOC_EXPORT SCCAnalyzer { +class PROTOC_EXPORT MessageSCCAnalyzer { public: - explicit SCCAnalyzer(const Options& options) : options_(options), index_(0) {} - ~SCCAnalyzer() { - for (int i = 0; i < garbage_bin_.size(); i++) delete garbage_bin_[i]; - } - - const SCC* GetSCC(const Descriptor* descriptor) { - if (cache_.count(descriptor)) return cache_[descriptor].scc; - return DFS(descriptor).scc; - } + explicit MessageSCCAnalyzer(const Options& options) : options_(options) {} MessageAnalysis GetSCCAnalysis(const SCC* scc); @@ -411,37 +531,60 @@ class LIBPROTOC_EXPORT SCCAnalyzer { MessageAnalysis result = GetSCCAnalysis(GetSCC(descriptor)); return result.contains_required || result.contains_extension; } - - private: - struct NodeData { - const SCC* scc; // if null it means its still on the stack - int index; - int lowlink; - }; - - Options options_; - std::map cache_; - std::map analysis_cache_; - std::vector stack_; - int index_; - std::vector garbage_bin_; - - SCC* CreateSCC() { - garbage_bin_.push_back(new SCC()); - return garbage_bin_.back(); + const SCC* GetSCC(const Descriptor* descriptor) { + return analyzer_.GetSCC(descriptor); } - // Tarjan's Strongly Connected Components algo - NodeData DFS(const Descriptor* descriptor); - - // Add the SCC's that are children of this SCC to its children. - void AddChildren(SCC* scc); + private: + struct DepsGenerator { + std::vector operator()(const Descriptor* desc) const { + std::vector deps; + for (int i = 0; i < desc->field_count(); i++) { + if (desc->field(i)->message_type()) { + deps.push_back(desc->field(i)->message_type()); + } + } + return deps; + } + }; + SCCAnalyzer analyzer_; + Options options_; + std::map analysis_cache_; }; +inline std::string SccInfoSymbol(const SCC* scc, const Options& options) { + return UniqueName("scc_info_" + ClassName(scc->GetRepresentative()), + scc->GetRepresentative(), options); +} + void ListAllFields(const Descriptor* d, std::vector* fields); void ListAllFields(const FileDescriptor* d, std::vector* fields); + +template +void ForEachField(const Descriptor* d, T&& func) { + for (int i = 0; i < d->nested_type_count(); i++) { + ForEachField(d->nested_type(i), std::forward(func)); + } + for (int i = 0; i < d->extension_count(); i++) { + func(d->extension(i)); + } + for (int i = 0; i < d->field_count(); i++) { + func(d->field(i)); + } +} + +template +void ForEachField(const FileDescriptor* d, T&& func) { + for (int i = 0; i < d->message_type_count(); i++) { + ForEachField(d->message_type(i), std::forward(func)); + } + for (int i = 0; i < d->extension_count(); i++) { + func(d->extension(i)); + } +} + void ListAllTypesForServices(const FileDescriptor* fd, std::vector* types); @@ -451,11 +594,246 @@ bool UsingImplicitWeakFields(const FileDescriptor* file, // Indicates whether to treat this field as implicitly weak. bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options, - SCCAnalyzer* scc_analyzer); + MessageSCCAnalyzer* scc_analyzer); + +// Formatter is a functor class which acts as a closure around printer and +// the variable map. It's much like printer->Print except it supports both named +// variables that are substituted using a key value map and direct arguments. In +// the format string $1$, $2$, etc... are substituted for the first, second, ... +// direct argument respectively in the format call, it accepts both strings and +// integers. The implementation verifies all arguments are used and are "first" +// used in order of appearance in the argument list. For example, +// +// Format("return array[$1$];", 3) -> "return array[3];" +// Format("array[$2$] = $1$;", "Bla", 3) -> FATAL error (wrong order) +// Format("array[$1$] = $2$;", 3, "Bla") -> "array[3] = Bla;" +// +// The arguments can be used more than once like +// +// Format("array[$1$] = $2$; // Index = $1$", 3, "Bla") -> +// "array[3] = Bla; // Index = 3" +// +// If you use more arguments use the following style to help the reader, +// +// Format("int $1$() {\n" +// " array[$2$] = $3$;\n" +// " return $4$;" +// "}\n", +// funname, // 1 +// idx, // 2 +// varname, // 3 +// retval); // 4 +// +// but consider using named variables. Named variables like $foo$, with some +// identifier foo, are looked up in the map. One additional feature is that +// spaces are accepted between the '$' delimiters, $ foo$ will +// substiture to " bar" if foo stands for "bar", but in case it's empty +// will substitute to "". Hence, for example, +// +// Format(vars, "$dllexport $void fun();") -> "void fun();" +// "__declspec(export) void fun();" +// +// which is convenient to prevent double, leading or trailing spaces. +class PROTOC_EXPORT Formatter { + public: + explicit Formatter(io::Printer* printer) : printer_(printer) {} + Formatter(io::Printer* printer, + const std::map& vars) + : printer_(printer), vars_(vars) {} + + template + void Set(const std::string& key, const T& value) { + vars_[key] = ToString(value); + } + + void AddMap(const std::map& vars) { + for (const auto& keyval : vars) vars_[keyval.first] = keyval.second; + } + + template + void operator()(const char* format, const Args&... args) const { + printer_->FormatInternal({ToString(args)...}, vars_, format); + } + + void Indent() const { printer_->Indent(); } + void Outdent() const { printer_->Outdent(); } + io::Printer* printer() const { return printer_; } + + class PROTOC_EXPORT SaveState { + public: + explicit SaveState(Formatter* format) + : format_(format), vars_(format->vars_) {} + ~SaveState() { format_->vars_.swap(vars_); } + + private: + Formatter* format_; + std::map vars_; + }; + + private: + io::Printer* printer_; + std::map vars_; + + // Convenience overloads to accept different types as arguments. + static std::string ToString(const std::string& s) { return s; } + template ::value>::type> + static std::string ToString(I x) { + return StrCat(x); + } + static std::string ToString(strings::Hex x) { return StrCat(x); } + static std::string ToString(const FieldDescriptor* d) { return Payload(d); } + static std::string ToString(const Descriptor* d) { return Payload(d); } + static std::string ToString(const EnumDescriptor* d) { return Payload(d); } + static std::string ToString(const EnumValueDescriptor* d) { + return Payload(d); + } + static std::string ToString(const OneofDescriptor* d) { return Payload(d); } + + template + static std::string Payload(const Descriptor* descriptor) { + std::vector path; + descriptor->GetLocationPath(&path); + GeneratedCodeInfo::Annotation annotation; + for (int i = 0; i < path.size(); ++i) { + annotation.add_path(path[i]); + } + annotation.set_source_file(descriptor->file()->name()); + return annotation.SerializeAsString(); + } +}; + +class PROTOC_EXPORT NamespaceOpener { + public: + explicit NamespaceOpener(const Formatter& format) + : printer_(format.printer()) {} + NamespaceOpener(const std::string& name, const Formatter& format) + : NamespaceOpener(format) { + ChangeTo(name); + } + ~NamespaceOpener() { ChangeTo(""); } + + void ChangeTo(const std::string& name) { + std::vector new_stack_ = + Split(name, "::", true); + int len = std::min(name_stack_.size(), new_stack_.size()); + int common_idx = 0; + while (common_idx < len) { + if (name_stack_[common_idx] != new_stack_[common_idx]) break; + common_idx++; + } + for (int i = name_stack_.size() - 1; i >= common_idx; i--) { + if (name_stack_[i] == "PROTOBUF_NAMESPACE_ID") { + printer_->Print("PROTOBUF_NAMESPACE_CLOSE\n"); + } else { + printer_->Print("} // namespace $ns$\n", "ns", name_stack_[i]); + } + } + name_stack_.swap(new_stack_); + for (int i = common_idx; i < name_stack_.size(); i++) { + if (name_stack_[i] == "PROTOBUF_NAMESPACE_ID") { + printer_->Print("PROTOBUF_NAMESPACE_OPEN\n"); + } else { + printer_->Print("namespace $ns$ {\n", "ns", name_stack_[i]); + } + } + } + + private: + io::Printer* printer_; + std::vector name_stack_; +}; + +std::string GetUtf8Suffix(const FieldDescriptor* field, const Options& options); +void GenerateUtf8CheckCodeForString(const FieldDescriptor* field, + const Options& options, bool for_parse, + const char* parameters, + const Formatter& format); + +void GenerateUtf8CheckCodeForCord(const FieldDescriptor* field, + const Options& options, bool for_parse, + const char* parameters, + const Formatter& format); + +template +struct FieldRangeImpl { + struct Iterator { + using iterator_category = std::forward_iterator_tag; + using value_type = const FieldDescriptor*; + using difference_type = int; + + value_type operator*() { return descriptor->field(idx); } + + friend bool operator==(const Iterator& a, const Iterator& b) { + GOOGLE_DCHECK(a.descriptor == b.descriptor); + return a.idx == b.idx; + } + friend bool operator!=(const Iterator& a, const Iterator& b) { + return !(a == b); + } + + Iterator& operator++() { + idx++; + return *this; + } + + int idx; + const T* descriptor; + }; + + Iterator begin() const { return {0, descriptor}; } + Iterator end() const { return {descriptor->field_count(), descriptor}; } + + const T* descriptor; +}; + +template +FieldRangeImpl FieldRange(const T* desc) { + return {desc}; +} + +struct OneOfRangeImpl { + struct Iterator { + using iterator_category = std::forward_iterator_tag; + using value_type = const OneofDescriptor*; + using difference_type = int; + + value_type operator*() { return descriptor->oneof_decl(idx); } + + friend bool operator==(const Iterator& a, const Iterator& b) { + GOOGLE_DCHECK(a.descriptor == b.descriptor); + return a.idx == b.idx; + } + friend bool operator!=(const Iterator& a, const Iterator& b) { + return !(a == b); + } + + Iterator& operator++() { + idx++; + return *this; + } + + int idx; + const Descriptor* descriptor; + }; + + Iterator begin() const { return {0, descriptor}; } + Iterator end() const { return {descriptor->oneof_decl_count(), descriptor}; } + + const Descriptor* descriptor; +}; + +inline OneOfRangeImpl OneOfRange(const Descriptor* desc) { return {desc}; } + +void GenerateParserLoop(const Descriptor* descriptor, int num_hasbits, + const Options& options, + MessageSCCAnalyzer* scc_analyzer, io::Printer* printer); } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_map_field.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_map_field.cc index 0e485cac..0738b91e 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_map_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_map_field.cc @@ -32,9 +32,9 @@ #include #include #include - #include + namespace google { namespace protobuf { namespace compiler { @@ -46,12 +46,10 @@ bool IsProto3Field(const FieldDescriptor* field_descriptor) { } void SetMessageVariables(const FieldDescriptor* descriptor, - std::map* variables, + std::map* variables, const Options& options) { SetCommonFieldVariables(descriptor, variables, options); (*variables)["type"] = ClassName(descriptor->message_type(), false); - (*variables)["file_namespace"] = - FileLevelNamespace(descriptor->file()->name()); (*variables)["stream_writer"] = (*variables)["declared_type"] + (HasFastArraySerialization(descriptor->message_type()->file(), options) @@ -63,29 +61,27 @@ void SetMessageVariables(const FieldDescriptor* descriptor, descriptor->message_type()->FindFieldByName("key"); const FieldDescriptor* val = descriptor->message_type()->FindFieldByName("value"); - (*variables)["key_cpp"] = PrimitiveTypeName(key->cpp_type()); + (*variables)["key_cpp"] = PrimitiveTypeName(options, key->cpp_type()); switch (val->cpp_type()) { case FieldDescriptor::CPPTYPE_MESSAGE: - (*variables)["val_cpp"] = FieldMessageTypeName(val); - (*variables)["wrapper"] = "EntryWrapper"; + (*variables)["val_cpp"] = FieldMessageTypeName(val, options); + (*variables)["wrapper"] = "MapEntryWrapper"; break; case FieldDescriptor::CPPTYPE_ENUM: (*variables)["val_cpp"] = ClassName(val->enum_type(), true); - (*variables)["wrapper"] = "EnumEntryWrapper"; + (*variables)["wrapper"] = "MapEnumEntryWrapper"; break; default: - (*variables)["val_cpp"] = PrimitiveTypeName(val->cpp_type()); - (*variables)["wrapper"] = "EntryWrapper"; + (*variables)["val_cpp"] = PrimitiveTypeName(options, val->cpp_type()); + (*variables)["wrapper"] = "MapEntryWrapper"; } (*variables)["key_wire_type"] = - "::google::protobuf::internal::WireFormatLite::TYPE_" + - ToUpper(DeclaredTypeMethodName(key->type())); + "TYPE_" + ToUpper(DeclaredTypeMethodName(key->type())); (*variables)["val_wire_type"] = - "::google::protobuf::internal::WireFormatLite::TYPE_" + - ToUpper(DeclaredTypeMethodName(val->type())); + "TYPE_" + ToUpper(DeclaredTypeMethodName(val->type())); (*variables)["map_classname"] = ClassName(descriptor->message_type(), false); - (*variables)["number"] = SimpleItoa(descriptor->number()); - (*variables)["tag"] = SimpleItoa(internal::WireFormat::MakeTag(descriptor)); + (*variables)["number"] = StrCat(descriptor->number()); + (*variables)["tag"] = StrCat(internal::WireFormat::MakeTag(descriptor)); if (HasDescriptorMethods(descriptor->file(), options)) { (*variables)["lite"] = ""; @@ -93,8 +89,7 @@ void SetMessageVariables(const FieldDescriptor* descriptor, (*variables)["lite"] = "Lite"; } - if (!IsProto3Field(descriptor) && - val->type() == FieldDescriptor::TYPE_ENUM) { + if (!IsProto3Field(descriptor) && val->type() == FieldDescriptor::TYPE_ENUM) { const EnumValueDescriptor* default_value = val->default_value_enum(); (*variables)["default_enum_value"] = Int32ToString(default_value->number()); } else { @@ -104,215 +99,195 @@ void SetMessageVariables(const FieldDescriptor* descriptor, MapFieldGenerator::MapFieldGenerator(const FieldDescriptor* descriptor, const Options& options) - : FieldGenerator(options), descriptor_(descriptor) { + : FieldGenerator(descriptor, options) { SetMessageVariables(descriptor, &variables_, options); } MapFieldGenerator::~MapFieldGenerator() {} -void MapFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { - printer->Print(variables_, - "::google::protobuf::internal::MapField$lite$<\n" - " $map_classname$,\n" - " $key_cpp$, $val_cpp$,\n" - " $key_wire_type$,\n" - " $val_wire_type$,\n" - " $default_enum_value$ > $name$_;\n"); +void MapFieldGenerator::GeneratePrivateMembers(io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "::$proto_ns$::internal::MapField$lite$<\n" + " $map_classname$,\n" + " $key_cpp$, $val_cpp$,\n" + " ::$proto_ns$::internal::WireFormatLite::$key_wire_type$,\n" + " ::$proto_ns$::internal::WireFormatLite::$val_wire_type$,\n" + " $default_enum_value$ > $name$_;\n"); } -void MapFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { - printer->Print( - variables_, - "$deprecated_attr$const ::google::protobuf::Map< $key_cpp$, $val_cpp$ >&\n" - " $name$() const;\n"); - printer->Annotate("name", descriptor_); - printer->Print(variables_, - "$deprecated_attr$::google::protobuf::Map< $key_cpp$, $val_cpp$ >*\n" - " ${$mutable_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); +void MapFieldGenerator::GenerateAccessorDeclarations( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "$deprecated_attr$const ::$proto_ns$::Map< $key_cpp$, $val_cpp$ >&\n" + " ${1$$name$$}$() const;\n" + "$deprecated_attr$::$proto_ns$::Map< $key_cpp$, $val_cpp$ >*\n" + " ${1$mutable_$name$$}$();\n", + descriptor_); } -void MapFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - printer->Print(variables_, - "inline const ::google::protobuf::Map< $key_cpp$, $val_cpp$ >&\n" +void MapFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "inline const ::$proto_ns$::Map< $key_cpp$, $val_cpp$ >&\n" "$classname$::$name$() const {\n" " // @@protoc_insertion_point(field_map:$full_name$)\n" " return $name$_.GetMap();\n" "}\n" - "inline ::google::protobuf::Map< $key_cpp$, $val_cpp$ >*\n" + "inline ::$proto_ns$::Map< $key_cpp$, $val_cpp$ >*\n" "$classname$::mutable_$name$() {\n" " // @@protoc_insertion_point(field_mutable_map:$full_name$)\n" " return $name$_.MutableMap();\n" "}\n"); } -void MapFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.Clear();\n"); +void MapFieldGenerator::GenerateClearingCode(io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.Clear();\n"); } -void MapFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n"); +void MapFieldGenerator::GenerateMergingCode(io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.MergeFrom(from.$name$_);\n"); } -void MapFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.Swap(&other->$name$_);\n"); +void MapFieldGenerator::GenerateSwappingCode(io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.Swap(&other->$name$_);\n"); } -void MapFieldGenerator:: -GenerateCopyConstructorCode(io::Printer* printer) const { +void MapFieldGenerator::GenerateCopyConstructorCode( + io::Printer* printer) const { GenerateConstructorCode(printer); GenerateMergingCode(printer); } -void MapFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - const FieldDescriptor* key_field = - descriptor_->message_type()->FindFieldByName("key"); +void MapFieldGenerator::GenerateMergeFromCodedStream( + io::Printer* printer) const { + Formatter format(printer, variables_); + const FieldDescriptor* key_field = + descriptor_->message_type()->FindFieldByName("key"); const FieldDescriptor* value_field = descriptor_->message_type()->FindFieldByName("value"); - bool using_entry = false; - string key; - string value; + std::string key; + std::string value; + format( + "$map_classname$::Parser< ::$proto_ns$::internal::MapField$lite$<\n" + " $map_classname$,\n" + " $key_cpp$, $val_cpp$,\n" + " ::$proto_ns$::internal::WireFormatLite::$key_wire_type$,\n" + " ::$proto_ns$::internal::WireFormatLite::$val_wire_type$,\n" + " $default_enum_value$ >,\n" + " ::$proto_ns$::Map< $key_cpp$, $val_cpp$ > >" + " parser(&$name$_);\n"); if (IsProto3Field(descriptor_) || value_field->type() != FieldDescriptor::TYPE_ENUM) { - printer->Print( - variables_, - "$map_classname$::Parser< ::google::protobuf::internal::MapField$lite$<\n" - " $map_classname$,\n" - " $key_cpp$, $val_cpp$,\n" - " $key_wire_type$,\n" - " $val_wire_type$,\n" - " $default_enum_value$ >,\n" - " ::google::protobuf::Map< $key_cpp$, $val_cpp$ > >" - " parser(&$name$_);\n" - "DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(\n" + format( + "DO_(::$proto_ns$::internal::WireFormatLite::ReadMessageNoVirtual(\n" " input, &parser));\n"); key = "parser.key()"; value = "parser.value()"; } else { - using_entry = true; key = "entry->key()"; value = "entry->value()"; - printer->Print(variables_, - "::std::unique_ptr<$map_classname$> entry($name$_.NewEntry());\n"); - printer->Print(variables_, - "{\n" - " ::std::string data;\n" - " DO_(::google::protobuf::internal::WireFormatLite::ReadString(input, &data));\n" - " DO_(entry->ParseFromString(data));\n" - " if ($val_cpp$_IsValid(*entry->mutable_value())) {\n" - " (*mutable_$name$())[entry->key()] =\n" - " static_cast< $val_cpp$ >(*entry->mutable_value());\n" - " } else {\n"); + format("auto entry = parser.NewEntry();\n"); + format( + "std::string data;\n" + "DO_(::$proto_ns$::internal::WireFormatLite::ReadString(input, " + "&data));\n" + "DO_(entry->ParseFromString(data));\n" + "if ($val_cpp$_IsValid(*entry->mutable_value())) {\n" + " (*mutable_$name$())[entry->key()] =\n" + " static_cast< $val_cpp$ >(*entry->mutable_value());\n" + "} else {\n"); if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print(variables_, - " mutable_unknown_fields()" + format( + " mutable_unknown_fields()" "->AddLengthDelimited($number$, data);\n"); } else { - printer->Print(variables_, - " unknown_fields_stream.WriteVarint32($tag$u);\n" - " unknown_fields_stream.WriteVarint32(\n" - " static_cast< ::google::protobuf::uint32>(data.size()));\n" - " unknown_fields_stream.WriteString(data);\n"); + format( + " unknown_fields_stream.WriteVarint32($tag$u);\n" + " unknown_fields_stream.WriteVarint32(\n" + " static_cast< ::google::protobuf::uint32>(data.size()));\n" + " unknown_fields_stream.WriteString(data);\n"); } - - printer->Print(variables_, - " }\n" - "}\n"); + format("}\n"); } if (key_field->type() == FieldDescriptor::TYPE_STRING) { GenerateUtf8CheckCodeForString( - key_field, options_, true, variables_, - StrCat(key, ".data(), static_cast(", key, ".length()),\n").data(), - printer); + key_field, options_, true, + StrCat(key, ".data(), static_cast(", key, ".length()),\n") + .data(), + format); } if (value_field->type() == FieldDescriptor::TYPE_STRING) { GenerateUtf8CheckCodeForString( - value_field, options_, true, variables_, - StrCat(value, ".data(), static_cast(", value, ".length()),\n") + value_field, options_, true, + StrCat(value, ".data(), static_cast(", value, + ".length()),\n") .data(), - printer); - } - - // If entry is allocated by arena, its desctructor should be avoided. - if (using_entry && SupportsArenas(descriptor_)) { - printer->Print(variables_, - "if (entry->GetArena() != NULL) entry.release();\n"); + format); } } -static void GenerateSerializationLoop(io::Printer* printer, - const std::map& variables, - bool supports_arenas, - const string& utf8_check, - const string& loop_header, - const string& ptr, - bool loop_via_iterators) { - printer->Print(variables, - StrCat("::std::unique_ptr<$map_classname$> entry;\n", - loop_header, " {\n").c_str()); - printer->Indent(); +static void GenerateSerializationLoop(const Formatter& format, bool string_key, + bool string_value, bool to_array, + bool is_deterministic) { + std::string ptr; + if (is_deterministic) { + format("for (size_type i = 0; i < n; i++) {\n"); + ptr = string_key ? "items[static_cast(i)]" + : "items[static_cast(i)].second"; + } else { + format( + "for (::$proto_ns$::Map< $key_cpp$, $val_cpp$ >::const_iterator\n" + " it = this->$name$().begin();\n" + " it != this->$name$().end(); ++it) {\n"); + ptr = "it"; + } + format.Indent(); - printer->Print(variables, StrCat( - "entry.reset($name$_.New$wrapper$(\n" - " ", ptr, "->first, ", ptr, "->second));\n" - "$write_entry$;\n").c_str()); - - // If entry is allocated by arena, its desctructor should be avoided. - if (supports_arenas) { - printer->Print( - "if (entry->GetArena() != NULL) {\n" - " entry.release();\n" - "}\n"); + format( + "$map_classname$::$wrapper$ entry(nullptr, $1$->first, $1$->second);\n", + ptr); + if (to_array) { + format( + "target = ::$proto_ns$::internal::WireFormatLite::InternalWrite" + "$declared_type$NoVirtualToArray($number$, entry, target);\n"); + } else { + format( + "::$proto_ns$::internal::WireFormatLite::Write$stream_writer$($number$," + " entry, output);\n"); } - if (!utf8_check.empty()) { - // If loop_via_iterators is true then ptr is actually an iterator, and we - // create a pointer by prefixing it with "&*". - printer->Print( - StrCat(utf8_check, "(", (loop_via_iterators ? "&*" : ""), ptr, ");\n") - .c_str()); + if (string_key || string_value) { + // ptr is either an actual pointer or an iterator, either way we can + // create a pointer by taking the address after de-referencing it. + format("Utf8Check::Check(&(*$1$));\n", ptr); } - printer->Outdent(); - printer->Print( - "}\n"); -} - -void MapFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { - std::map variables(variables_); - variables["write_entry"] = "::google::protobuf::internal::WireFormatLite::Write" + - variables["stream_writer"] + "(\n " + - variables["number"] + ", *entry, output)"; - variables["deterministic"] = "output->IsSerializationDeterministic()"; - GenerateSerializeWithCachedSizes(printer, variables); -} - -void MapFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { - std::map variables(variables_); - variables["write_entry"] = - "target = ::google::protobuf::internal::WireFormatLite::\n" - " InternalWrite" + variables["declared_type"] + - "NoVirtualToArray(\n " + variables["number"] + - ", *entry, deterministic, target);\n"; - variables["deterministic"] = "deterministic"; - GenerateSerializeWithCachedSizes(printer, variables); + format.Outdent(); + format("}\n"); } void MapFieldGenerator::GenerateSerializeWithCachedSizes( - io::Printer* printer, const std::map& variables) const { - printer->Print(variables, - "if (!this->$name$().empty()) {\n"); - printer->Indent(); + io::Printer* printer) const { + GenerateSerializeWithCachedSizes(printer, false); +} + +void MapFieldGenerator::GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const { + GenerateSerializeWithCachedSizes(printer, true); +} + +void MapFieldGenerator::GenerateSerializeWithCachedSizes(io::Printer* printer, + bool to_array) const { + Formatter format(printer, variables_); + format("if (!this->$name$().empty()) {\n"); + format.Indent(); const FieldDescriptor* key_field = descriptor_->message_type()->FindFieldByName("key"); const FieldDescriptor* value_field = @@ -320,114 +295,85 @@ void MapFieldGenerator::GenerateSerializeWithCachedSizes( const bool string_key = key_field->type() == FieldDescriptor::TYPE_STRING; const bool string_value = value_field->type() == FieldDescriptor::TYPE_STRING; - printer->Print(variables, - "typedef ::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_pointer\n" + format( + "typedef ::$proto_ns$::Map< $key_cpp$, $val_cpp$ >::const_pointer\n" " ConstPtr;\n"); if (string_key) { - printer->Print(variables, + format( "typedef ConstPtr SortItem;\n" - "typedef ::google::protobuf::internal::" + "typedef ::$proto_ns$::internal::" "CompareByDerefFirst Less;\n"); } else { - printer->Print(variables, - "typedef ::google::protobuf::internal::SortItem< $key_cpp$, ConstPtr > " + format( + "typedef ::$proto_ns$::internal::SortItem< $key_cpp$, ConstPtr > " "SortItem;\n" - "typedef ::google::protobuf::internal::CompareByFirstField Less;\n"); + "typedef ::$proto_ns$::internal::CompareByFirstField " + "Less;\n"); } - string utf8_check; - if (string_key || string_value) { - printer->Print( + bool utf8_check = string_key || string_value; + if (utf8_check) { + format( "struct Utf8Check {\n" " static void Check(ConstPtr p) {\n"); - printer->Indent(); - printer->Indent(); + format.Indent(); + format.Indent(); if (string_key) { GenerateUtf8CheckCodeForString( - key_field, options_, false, variables, - "p->first.data(), static_cast(p->first.length()),\n", printer); + key_field, options_, false, + "p->first.data(), static_cast(p->first.length()),\n", format); } if (string_value) { GenerateUtf8CheckCodeForString( - value_field, options_, false, variables, - "p->second.data(), static_cast(p->second.length()),\n", printer); + value_field, options_, false, + "p->second.data(), static_cast(p->second.length()),\n", format); } - printer->Outdent(); - printer->Outdent(); - printer->Print( + format.Outdent(); + format.Outdent(); + format( " }\n" "};\n"); - utf8_check = "Utf8Check::Check"; } - printer->Print(variables, + format( "\n" - "if ($deterministic$ &&\n" + "if ($1$ &&\n" " this->$name$().size() > 1) {\n" " ::std::unique_ptr items(\n" " new SortItem[this->$name$().size()]);\n" - " typedef ::google::protobuf::Map< $key_cpp$, $val_cpp$ >::size_type size_type;\n" + " typedef ::$proto_ns$::Map< $key_cpp$, $val_cpp$ >::size_type " + "size_type;\n" " size_type n = 0;\n" - " for (::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_iterator\n" + " for (::$proto_ns$::Map< $key_cpp$, $val_cpp$ >::const_iterator\n" " it = this->$name$().begin();\n" " it != this->$name$().end(); ++it, ++n) {\n" " items[static_cast(n)] = SortItem(&*it);\n" " }\n" - " ::std::sort(&items[0], &items[static_cast(n)], Less());\n"); - printer->Indent(); - GenerateSerializationLoop(printer, variables, SupportsArenas(descriptor_), - utf8_check, "for (size_type i = 0; i < n; i++)", - string_key ? "items[static_cast(i)]" : - "items[static_cast(i)].second", false); - printer->Outdent(); - printer->Print( - "} else {\n"); - printer->Indent(); - GenerateSerializationLoop( - printer, variables, SupportsArenas(descriptor_), utf8_check, - "for (::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_iterator\n" - " it = this->$name$().begin();\n" - " it != this->$name$().end(); ++it)", - "it", true); - printer->Outdent(); - printer->Print("}\n"); - printer->Outdent(); - printer->Print("}\n"); + " ::std::sort(&items[0], &items[static_cast(n)], Less());\n", + to_array ? "false" : "output->IsSerializationDeterministic()"); + format.Indent(); + GenerateSerializationLoop(format, string_key, string_value, to_array, true); + format.Outdent(); + format("} else {\n"); + format.Indent(); + GenerateSerializationLoop(format, string_key, string_value, to_array, false); + format.Outdent(); + format("}\n"); + format.Outdent(); + format("}\n"); } -void MapFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { - printer->Print(variables_, +void MapFieldGenerator::GenerateByteSize(io::Printer* printer) const { + Formatter format(printer, variables_); + format( "total_size += $tag_size$ *\n" - " ::google::protobuf::internal::FromIntSize(this->$name$_size());\n" - "{\n" - " ::std::unique_ptr<$map_classname$> entry;\n" - " for (::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_iterator\n" - " it = this->$name$().begin();\n" - " it != this->$name$().end(); ++it) {\n"); - - // If entry is allocated by arena, its desctructor should be avoided. - if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - " if (entry.get() != NULL && entry->GetArena() != NULL) {\n" - " entry.release();\n" - " }\n"); - } - - printer->Print(variables_, - " entry.reset($name$_.New$wrapper$(it->first, it->second));\n" - " total_size += ::google::protobuf::internal::WireFormatLite::\n" - " $declared_type$SizeNoVirtual(*entry);\n" - " }\n"); - - // If entry is allocated by arena, its desctructor should be avoided. - if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - " if (entry.get() != NULL && entry->GetArena() != NULL) {\n" - " entry.release();\n" - " }\n"); - } - - printer->Print("}\n"); + " ::$proto_ns$::internal::FromIntSize(this->$name$_size());\n" + "for (::$proto_ns$::Map< $key_cpp$, $val_cpp$ >::const_iterator\n" + " it = this->$name$().begin();\n" + " it != this->$name$().end(); ++it) {\n" + " $map_classname$::$wrapper$ entry(nullptr, it->first, it->second);\n" + " total_size += ::$proto_ns$::internal::WireFormatLite::\n" + " $declared_type$SizeNoVirtual(entry);\n" + "}\n"); } } // namespace cpp diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_map_field.h b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_map_field.h index 0d54f0ea..95eecc07 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_map_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_map_field.h @@ -62,11 +62,8 @@ class MapFieldGenerator : public FieldGenerator { private: // A helper for GenerateSerializeWithCachedSizes{,ToArray}. - void GenerateSerializeWithCachedSizes( - io::Printer* printer, const std::map& variables) const; - - const FieldDescriptor* descriptor_; - std::map variables_; + void GenerateSerializeWithCachedSizes(io::Printer* printer, + bool to_array) const; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldGenerator); }; @@ -74,6 +71,6 @@ class MapFieldGenerator : public FieldGenerator { } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_MAP_FIELD_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message.cc index 8c2336af..74a24402 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message.cc @@ -35,9 +35,9 @@ #include #include -#include #include #include +#include #include #include @@ -57,6 +57,8 @@ #include +#include + namespace google { namespace protobuf { @@ -69,16 +71,33 @@ using internal::WireFormatLite; namespace { template -void PrintFieldComment(io::Printer* printer, const T* field) { +void PrintFieldComment(const Formatter& format, const T* field) { // Print the field's (or oneof's) proto-syntax definition as a comment. // We don't want to print group bodies so we cut off after the first // line. DebugStringOptions options; options.elide_group_body = true; options.elide_oneof_body = true; - string def = field->DebugStringWithOptions(options); - printer->Print("// $def$\n", - "def", def.substr(0, def.find_first_of('\n'))); + std::string def = field->DebugStringWithOptions(options); + format("// $1$\n", def.substr(0, def.find_first_of('\n'))); +} + +void PrintPresenceCheck(const Formatter& format, const FieldDescriptor* field, + const std::vector& has_bit_indices, + io::Printer* printer, int* cached_has_bit_index) { + if (!field->options().weak()) { + int has_bit_index = has_bit_indices[field->index()]; + if (*cached_has_bit_index != (has_bit_index / 32)) { + *cached_has_bit_index = (has_bit_index / 32); + format("cached_has_bits = _has_bits_[$1$];\n", *cached_has_bit_index); + } + const std::string mask = + StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8)); + format("if (cached_has_bits & 0x$1$u) {\n", mask); + } else { + format("if (has_$1$()) {\n", FieldName(field)); + } + format.Indent(); } struct FieldOrderingByNumber { @@ -135,9 +154,8 @@ bool CanConstructByZeroing(const FieldDescriptor* field, // Non-repeated, non-lazy message fields are simply raw pointers, so we can // use memset to initialize these in SharedCtor. We cannot use this in // Clear, as we need to potentially delete the existing value. - ret = ret || - (!field->is_repeated() && - field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE); + ret = ret || (!field->is_repeated() && !IsLazy(field, options) && + field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE); return ret; } @@ -146,35 +164,31 @@ bool CanConstructByZeroing(const FieldDescriptor* field, // without true field presence. Should only be called if // !HasFieldPresence(message_descriptor). bool EmitFieldNonDefaultCondition(io::Printer* printer, - const string& prefix, + const std::string& prefix, const FieldDescriptor* field) { + Formatter format(printer); + format.Set("prefix", prefix); + format.Set("name", FieldName(field)); // Merge and serialize semantics: primitive fields are merged/serialized only // if non-zero (numeric) or non-empty (string). if (!field->is_repeated() && !field->containing_oneof()) { if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) { - printer->Print( - "if ($prefix$$name$().size() > 0) {\n", - "prefix", prefix, - "name", FieldName(field)); + format("if ($prefix$$name$().size() > 0) {\n"); } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { // Message fields still have has_$name$() methods. - printer->Print( - "if ($prefix$has_$name$()) {\n", - "prefix", prefix, - "name", FieldName(field)); + format("if ($prefix$has_$name$()) {\n"); + } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_DOUBLE || + field->cpp_type() == FieldDescriptor::CPPTYPE_FLOAT) { + // Handle float comparison to prevent -Wfloat-equal warnings + format("if (!($prefix$$name$() <= 0 && $prefix$$name$() >= 0)) {\n"); } else { - printer->Print( - "if ($prefix$$name$() != 0) {\n", - "prefix", prefix, - "name", FieldName(field)); + format("if ($prefix$$name$() != 0) {\n"); } - printer->Indent(); + format.Indent(); return true; } else if (field->containing_oneof()) { - printer->Print( - "if (has_$name$()) {\n", - "name", FieldName(field)); - printer->Indent(); + format("if (has_$name$()) {\n"); + format.Indent(); return true; } return false; @@ -192,27 +206,27 @@ bool HasHasMethod(const FieldDescriptor* field) { } // Collects map entry message type information. -void CollectMapInfo(const Descriptor* descriptor, - std::map* variables) { +void CollectMapInfo(const Options& options, const Descriptor* descriptor, + std::map* variables) { GOOGLE_CHECK(IsMapEntryMessage(descriptor)); - std::map& vars = *variables; + std::map& vars = *variables; const FieldDescriptor* key = descriptor->FindFieldByName("key"); const FieldDescriptor* val = descriptor->FindFieldByName("value"); - vars["key_cpp"] = PrimitiveTypeName(key->cpp_type()); + vars["key_cpp"] = PrimitiveTypeName(options, key->cpp_type()); switch (val->cpp_type()) { case FieldDescriptor::CPPTYPE_MESSAGE: - vars["val_cpp"] = FieldMessageTypeName(val); + vars["val_cpp"] = FieldMessageTypeName(val, options); break; case FieldDescriptor::CPPTYPE_ENUM: vars["val_cpp"] = ClassName(val->enum_type(), true); break; default: - vars["val_cpp"] = PrimitiveTypeName(val->cpp_type()); + vars["val_cpp"] = PrimitiveTypeName(options, val->cpp_type()); } - vars["key_wire_type"] = "::google::protobuf::internal::WireFormatLite::TYPE_" + - ToUpper(DeclaredTypeMethodName(key->type())); - vars["val_wire_type"] = "::google::protobuf::internal::WireFormatLite::TYPE_" + - ToUpper(DeclaredTypeMethodName(val->type())); + vars["key_wire_type"] = + "TYPE_" + ToUpper(DeclaredTypeMethodName(key->type())); + vars["val_wire_type"] = + "TYPE_" + ToUpper(DeclaredTypeMethodName(val->type())); if (descriptor->file()->syntax() != FileDescriptor::SYNTAX_PROTO3 && val->type() == FieldDescriptor::TYPE_ENUM) { const EnumValueDescriptor* default_value = val->default_value_enum(); @@ -231,9 +245,46 @@ bool HasPrivateHasMethod(const FieldDescriptor* field) { field->containing_oneof() != NULL); } +// TODO(ckennelly): Cull these exclusions if/when these protos do not have +// their methods overriden by subclasses. -bool TableDrivenParsingEnabled( - const Descriptor* descriptor, const Options& options) { +bool ShouldMarkClassAsFinal(const Descriptor* descriptor, + const Options& options) { + return false; +} + +bool ShouldMarkClearAsFinal(const Descriptor* descriptor, + const Options& options) { + static std::set exclusions{ + }; + + const std::string name = ClassName(descriptor, true); + return exclusions.find(name) == exclusions.end() || + options.opensource_runtime; +} + +bool ShouldMarkIsInitializedAsFinal(const Descriptor* descriptor, + const Options& options) { + static std::set exclusions{ + }; + + const std::string name = ClassName(descriptor, true); + return exclusions.find(name) == exclusions.end() || + options.opensource_runtime; +} + +bool ShouldMarkNewAsFinal(const Descriptor* descriptor, + const Options& options) { + static std::set exclusions{ + }; + + const std::string name = ClassName(descriptor, true); + return exclusions.find(name) == exclusions.end() || + options.opensource_runtime; +} + +bool TableDrivenParsingEnabled(const Descriptor* descriptor, + const Options& options) { if (!options.table_driven_parsing) { return false; } @@ -247,14 +298,18 @@ bool TableDrivenParsingEnabled( const double table_sparseness = 0.5; int max_field_number = 0; - for (int i = 0; i < descriptor->field_count(); i++) { - const FieldDescriptor* field = descriptor->field(i); + for (auto field : FieldRange(descriptor)) { if (max_field_number < field->number()) { max_field_number = field->number(); } // - There are no weak fields. - if (field->options().weak()) { + if (IsWeak(field, options)) { + return false; + } + + // - There are no lazy fields (they require the non-lite library). + if (IsLazy(field, options)) { return false; } } @@ -281,25 +336,17 @@ bool TableDrivenParsingEnabled( void SetUnknkownFieldsVariable(const Descriptor* descriptor, const Options& options, - std::map* variables) { + std::map* variables) { + std::string proto_ns = ProtobufNamespace(options); if (UseUnknownFieldSet(descriptor->file(), options)) { - (*variables)["unknown_fields_type"] = "::google::protobuf::UnknownFieldSet"; + (*variables)["unknown_fields_type"] = "::" + proto_ns + "::UnknownFieldSet"; } else { - (*variables)["unknown_fields_type"] = "::std::string"; - } - if (AlwaysPreserveUnknownFields(descriptor)) { - (*variables)["have_unknown_fields"] = - "_internal_metadata_.have_unknown_fields()"; - (*variables)["unknown_fields"] = "_internal_metadata_.unknown_fields()"; - } else { - (*variables)["have_unknown_fields"] = - "(_internal_metadata_.have_unknown_fields() && " - " ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())"; - (*variables)["unknown_fields"] = - "(::google::protobuf::internal::GetProto3PreserveUnknownsDefault()" - " ? _internal_metadata_.unknown_fields()" - " : _internal_metadata_.default_instance())"; + (*variables)["unknown_fields_type"] = + PrimitiveTypeName(options, FieldDescriptor::CPPTYPE_STRING); } + (*variables)["have_unknown_fields"] = + "_internal_metadata_.have_unknown_fields()"; + (*variables)["unknown_fields"] = "_internal_metadata_.unknown_fields()"; (*variables)["mutable_unknown_fields"] = "_internal_metadata_.mutable_unknown_fields()"; } @@ -383,23 +430,23 @@ class MatchRepeatedAndHasByteAndZeroInits : public MatchRepeatedAndHasByte { // Collects neighboring fields based on a given criteria (equivalent predicate). template -std::vector > CollectFields( +std::vector> CollectFields( const std::vector& fields, const Predicate& equivalent) { - std::vector > chunks; + std::vector> chunks; if (fields.empty()) { return chunks; } const FieldDescriptor* last_field = fields.front(); std::vector chunk; - for (int i = 0; i < fields.size(); i++) { - if (!equivalent(last_field, fields[i]) && !chunk.empty()) { + for (auto field : fields) { + if (!equivalent(last_field, field) && !chunk.empty()) { chunks.push_back(chunk); chunk.clear(); } - chunk.push_back(fields[i]); - last_field = fields[i]; + chunk.push_back(field); + last_field = field; } if (!chunk.empty()) { chunks.push_back(chunk); @@ -415,8 +462,7 @@ uint32 GenChunkMask(const std::vector& fields, GOOGLE_CHECK(!fields.empty()); int first_index_offset = has_bit_indices[fields.front()->index()] / 32; uint32 chunk_mask = 0; - for (int i = 0; i < fields.size(); i++) { - const FieldDescriptor* field = fields[i]; + for (auto field : fields) { // "index" defines where in the _has_bits_ the field appears. int index = has_bit_indices[field->index()]; GOOGLE_CHECK_EQ(first_index_offset, index / 32); @@ -426,32 +472,165 @@ uint32 GenChunkMask(const std::vector& fields, return chunk_mask; } +// Return the number of bits set in n, a non-negative integer. +static int popcnt(uint32 n) { + int result = 0; + while (n != 0) { + result += (n & 1); + n = n / 2; + } + return result; +} + +// For a run of cold chunks, opens and closes an external if statement that +// checks multiple has_bits words to skip bulk of cold fields. +class ColdChunkSkipper { + public: + ColdChunkSkipper( + const Options& options, + const std::vector>& chunks, + const std::vector& has_bit_indices, const double cold_threshold, + bool has_field_presence) + : chunks_(chunks), + has_bit_indices_(has_bit_indices), + access_info_map_(options.access_info_map), + cold_threshold_(cold_threshold), + has_field_presence_(has_field_presence) { + SetCommonVars(options, &variables_); + } + + // May open an external if check for a batch of cold fields. "from" is the + // prefix to _has_bits_ to allow MergeFrom to use "from._has_bits_". + // Otherwise, it should be "". + void OnStartChunk(int chunk, int cached_has_bit_index, + const std::string& from, io::Printer* printer); + bool OnEndChunk(int chunk, io::Printer* printer); + + private: + bool IsColdChunk(int chunk); + + int HasbitWord(int chunk, int offset) { + return has_bit_indices_[chunks_[chunk][offset]->index()] / 32; + } + + const std::vector>& chunks_; + const std::vector& has_bit_indices_; + const AccessInfoMap* access_info_map_; + const double cold_threshold_; + std::map variables_; + int limit_chunk_ = -1; + bool has_field_presence_; +}; + +// Tuning parameters for ColdChunkSkipper. +const double kColdRatio = 0.005; + +bool ColdChunkSkipper::IsColdChunk(int chunk) { + // Mark this variable as used until it is actually used + (void)cold_threshold_; + return false; +} + + +void ColdChunkSkipper::OnStartChunk(int chunk, int cached_has_bit_index, + const std::string& from, + io::Printer* printer) { + Formatter format(printer, variables_); + if (!access_info_map_ || !has_field_presence_) { + return; + } else if (chunk < limit_chunk_) { + // We are already inside a run of cold chunks. + return; + } else if (!IsColdChunk(chunk)) { + // We can't start a run of cold chunks. + return; + } + + // Find the end of consecutive cold chunks. + limit_chunk_ = chunk; + while (limit_chunk_ < chunks_.size() && IsColdChunk(limit_chunk_)) { + limit_chunk_++; + } + + if (limit_chunk_ <= chunk + 1) { + // Require at least two chunks to emit external has_bit checks. + limit_chunk_ = -1; + return; + } + + // Emit has_bit check for each has_bit_dword index. + format("if (PROTOBUF_PREDICT_FALSE("); + int first_word = HasbitWord(chunk, 0); + while (chunk < limit_chunk_) { + uint32 mask = 0; + int this_word = HasbitWord(chunk, 0); + // Generate mask for chunks on the same word. + for (; chunk < limit_chunk_ && HasbitWord(chunk, 0) == this_word; chunk++) { + for (auto field : chunks_[chunk]) { + int hasbit_index = has_bit_indices_[field->index()]; + // Fields on a chunk must be in the same word. + GOOGLE_CHECK_EQ(this_word, hasbit_index / 32); + mask |= 1 << (hasbit_index % 32); + } + } + + if (this_word != first_word) { + format(" ||\n "); + } + format.Set("mask", strings::Hex(mask, strings::ZERO_PAD_8)); + if (this_word == cached_has_bit_index) { + format("(cached_has_bits & 0x$mask$u) != 0"); + } else { + format("($1$_has_bits_[$2$] & 0x$mask$u) != 0", from, this_word); + } + } + format(")) {\n"); + format.Indent(); +} + +bool ColdChunkSkipper::OnEndChunk(int chunk, io::Printer* printer) { + Formatter format(printer, variables_); + if (chunk != limit_chunk_ - 1) { + return false; + } + format.Outdent(); + format("}\n"); + return true; +} + } // anonymous namespace // =================================================================== -MessageGenerator::MessageGenerator(const Descriptor* descriptor, - int index_in_file_messages, - const Options& options, - SCCAnalyzer* scc_analyzer) +MessageGenerator::MessageGenerator( + const Descriptor* descriptor, + const std::map& vars, int index_in_file_messages, + const Options& options, MessageSCCAnalyzer* scc_analyzer) : descriptor_(descriptor), index_in_file_messages_(index_in_file_messages), classname_(ClassName(descriptor, false)), options_(options), field_generators_(descriptor, options, scc_analyzer), max_has_bit_index_(0), - enum_generators_( - new std::unique_ptr[descriptor->enum_type_count()]), - extension_generators_(new std::unique_ptr< - ExtensionGenerator>[descriptor->extension_count()]), num_weak_fields_(0), - message_layout_helper_(new PaddingOptimizer()), - scc_analyzer_(scc_analyzer) { + scc_analyzer_(scc_analyzer), + variables_(vars) { + if (!message_layout_helper_) { + message_layout_helper_.reset(new PaddingOptimizer()); + } + + // Variables that apply to this class + variables_["classname"] = classname_; + variables_["classtype"] = QualifiedClassName(descriptor_, options); + variables_["scc_info"] = + SccInfoSymbol(scc_analyzer_->GetSCC(descriptor_), options_); + variables_["full_name"] = descriptor_->full_name(); + variables_["superclass"] = SuperClassName(descriptor_, options_); + // Compute optimized field order to be used for layout and initialization // purposes. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - if (field->options().weak()) { + for (auto field : FieldRange(descriptor_)) { + if (IsWeak(field, options_)) { num_weak_fields_++; } else if (!field->containing_oneof()) { optimized_order_.push_back(field); @@ -463,8 +642,7 @@ MessageGenerator::MessageGenerator(const Descriptor* descriptor, if (HasFieldPresence(descriptor_->file())) { // We use -1 as a sentinel. has_bit_indices_.resize(descriptor_->field_count(), -1); - for (int i = 0; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; + for (auto field : optimized_order_) { // Skip fields that do not have has bits. if (field->is_repeated()) { continue; @@ -472,16 +650,7 @@ MessageGenerator::MessageGenerator(const Descriptor* descriptor, has_bit_indices_[field->index()] = max_has_bit_index_++; } - } - - for (int i = 0; i < descriptor->enum_type_count(); i++) { - enum_generators_[i].reset( - new EnumGenerator(descriptor->enum_type(i), options)); - } - - for (int i = 0; i < descriptor->extension_count(); i++) { - extension_generators_[i].reset( - new ExtensionGenerator(descriptor->extension(i), options)); + field_generators_.SetHasBitIndices(has_bit_indices_); } num_required_fields_ = 0; @@ -492,12 +661,9 @@ MessageGenerator::MessageGenerator(const Descriptor* descriptor, } table_driven_ = TableDrivenParsingEnabled(descriptor_, options_); - - scc_name_ = - ClassName(scc_analyzer_->GetSCC(descriptor_)->GetRepresentative(), false); } -MessageGenerator::~MessageGenerator() {} +MessageGenerator::~MessageGenerator() = default; size_t MessageGenerator::HasBitsSize() const { size_t sizeof_has_bits = (max_has_bit_index_ + 31) / 32 * 4; @@ -513,23 +679,22 @@ size_t MessageGenerator::HasBitsSize() const { } void MessageGenerator::AddGenerators( - std::vector* enum_generators, - std::vector* extension_generators) { + std::vector>* enum_generators, + std::vector>* extension_generators) { for (int i = 0; i < descriptor_->enum_type_count(); i++) { - enum_generators->push_back(enum_generators_[i].get()); + enum_generators->emplace_back( + new EnumGenerator(descriptor_->enum_type(i), variables_, options_)); + enum_generators_.push_back(enum_generators->back().get()); } for (int i = 0; i < descriptor_->extension_count(); i++) { - extension_generators->push_back(extension_generators_[i].get()); + extension_generators->emplace_back( + new ExtensionGenerator(descriptor_->extension(i), options_)); + extension_generators_.push_back(extension_generators->back().get()); } } -void MessageGenerator::FillMessageForwardDeclarations( - std::map* class_names) { - (*class_names)[classname_] = descriptor_; -} - -void MessageGenerator:: -GenerateFieldAccessorDeclarations(io::Printer* printer) { +void MessageGenerator::GenerateFieldAccessorDeclarations(io::Printer* printer) { + Formatter format(printer, variables_); // optimized_fields_ does not contain fields where // field->containing_oneof() != NULL // so we need to iterate over those as well. @@ -540,77 +705,76 @@ GenerateFieldAccessorDeclarations(io::Printer* printer) { std::vector ordered_fields; ordered_fields.reserve(descriptor_->field_count()); - ordered_fields.insert( - ordered_fields.begin(), optimized_order_.begin(), optimized_order_.end()); - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); + ordered_fields.insert(ordered_fields.begin(), optimized_order_.begin(), + optimized_order_.end()); + for (auto field : FieldRange(descriptor_)) { if (field->containing_oneof() == NULL && !field->options().weak()) { continue; } ordered_fields.push_back(field); } - for (int i = 0; i < ordered_fields.size(); i++) { - const FieldDescriptor* field = ordered_fields[i]; + for (auto field : ordered_fields) { + PrintFieldComment(format, field); - PrintFieldComment(printer, field); + Formatter::SaveState save(&format); - std::map vars; + std::map vars; SetCommonFieldVariables(field, &vars, options_); - vars["constant_name"] = FieldConstantName(field); + format.AddMap(vars); if (field->is_repeated()) { - printer->Print(vars, "$deprecated_attr$int ${$$name$_size$}$() const;\n"); - printer->Annotate("{", "}", field); + format("$deprecated_attr$int ${1$$name$_size$}$() const;\n", field); } else if (HasHasMethod(field)) { - printer->Print(vars, "$deprecated_attr$bool ${$has_$name$$}$() const;\n"); - printer->Annotate("{", "}", field); + format("$deprecated_attr$bool ${1$has_$name$$}$() const;\n", field); } else if (HasPrivateHasMethod(field)) { - printer->Print(vars, - "private:\n" - "bool ${$has_$name$$}$() const;\n" - "public:\n"); - printer->Annotate("{", "}", field); + format( + "private:\n" + "bool ${1$has_$name$$}$() const;\n" + "public:\n", + field); } - printer->Print(vars, "$deprecated_attr$void ${$clear_$name$$}$();\n"); - printer->Annotate("{", "}", field); - printer->Print(vars, - "$deprecated_attr$static const int $constant_name$ = " - "$number$;\n"); - printer->Annotate("constant_name", field); + format( + "$deprecated_attr$void ${1$clear_$name$$}$();\n" + "$deprecated_attr$static const int ${1$$2$$}$ = $number$;\n", + field, FieldConstantName(field)); // Generate type-specific accessor declarations. field_generators_.get(field).GenerateAccessorDeclarations(printer); - printer->Print("\n"); + format("\n"); } if (descriptor_->extension_range_count() > 0) { // Generate accessors for extensions. We just call a macro located in // extension_set.h since the accessors about 80 lines of static code. - printer->Print( - "GOOGLE_PROTOBUF_EXTENSION_ACCESSORS($classname$)\n", - "classname", classname_); + format("$GOOGLE_PROTOBUF$_EXTENSION_ACCESSORS($classname$)\n"); + // Generate MessageSet specific APIs for proto2 MessageSet. + // For testing purposes we don't check for bridge.MessageSet, so + // we don't use IsProto2MessageSet + if (descriptor_->options().message_set_wire_format() && + !options_.opensource_runtime && !options_.lite_implicit_weak_fields) { + // Special-case MessageSet + format("GOOGLE_PROTOBUF_EXTENSION_MESSAGE_SET_ACCESSORS($classname$)\n"); + } } - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "void clear_$oneof_name$();\n" + for (auto oneof : OneOfRange(descriptor_)) { + Formatter::SaveState saver(&format); + format.Set("oneof_name", oneof->name()); + format.Set("camel_oneof_name", UnderscoresToCamelCase(oneof->name(), true)); + format( + "void ${1$clear_$oneof_name$$}$();\n" "$camel_oneof_name$Case $oneof_name$_case() const;\n", - "camel_oneof_name", - UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true), - "oneof_name", descriptor_->oneof_decl(i)->name()); + oneof); } } -void MessageGenerator:: -GenerateSingularFieldHasBits(const FieldDescriptor* field, - std::map vars, - io::Printer* printer) { +void MessageGenerator::GenerateSingularFieldHasBits( + const FieldDescriptor* field, Formatter format) { if (field->options().weak()) { - printer->Print( - vars, + format( "inline bool $classname$::has_$name$() const {\n" " return _weak_field_map_.Has($number$);\n" "}\n"); @@ -622,50 +786,39 @@ GenerateSingularFieldHasBits(const FieldDescriptor* field, int has_bit_index = has_bit_indices_[field->index()]; GOOGLE_CHECK_GE(has_bit_index, 0); - vars["has_array_index"] = SimpleItoa(has_bit_index / 32); - vars["has_mask"] = StrCat(strings::Hex(1u << (has_bit_index % 32), - strings::ZERO_PAD_8)); - printer->Print(vars, - "inline bool $classname$::has_$name$() const {\n" - " return (_has_bits_[$has_array_index$] & 0x$has_mask$u) != 0;\n" - "}\n" - "inline void $classname$::set_has_$name$() {\n" - " _has_bits_[$has_array_index$] |= 0x$has_mask$u;\n" - "}\n" - "inline void $classname$::clear_has_$name$() {\n" - " _has_bits_[$has_array_index$] &= ~0x$has_mask$u;\n" - "}\n"); + format.Set("has_array_index", has_bit_index / 32); + format.Set("has_mask", + strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8)); + format( + "inline bool $classname$::has_$name$() const {\n" + " return (_has_bits_[$has_array_index$] & 0x$has_mask$u) != 0;\n" + "}\n"); } else { // Message fields have a has_$name$() method. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - bool is_lazy = false; - if (is_lazy) { - printer->Print(vars, - "inline bool $classname$::has_$name$() const {\n" - " return !$name$_.IsCleared();\n" - "}\n"); - } else { - printer->Print( - vars, + if (IsLazy(field, options_)) { + format( "inline bool $classname$::has_$name$() const {\n" - " return this != internal_default_instance() && $name$_ != NULL;\n" + " return !$name$_.IsCleared();\n" + "}\n"); + } else { + format( + "inline bool $classname$::has_$name$() const {\n" + " return this != internal_default_instance() " + "&& $name$_ != nullptr;\n" "}\n"); } } } } -void MessageGenerator:: -GenerateOneofHasBits(io::Printer* printer) { - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - std::map vars; - vars["oneof_name"] = descriptor_->oneof_decl(i)->name(); - vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index()); - vars["cap_oneof_name"] = - ToUpper(descriptor_->oneof_decl(i)->name()); - vars["classname"] = classname_; - printer->Print( - vars, +void MessageGenerator::GenerateOneofHasBits(io::Printer* printer) { + Formatter format(printer, variables_); + for (auto oneof : OneOfRange(descriptor_)) { + format.Set("oneof_name", oneof->name()); + format.Set("oneof_index", oneof->index()); + format.Set("cap_oneof_name", ToUpper(oneof->name())); + format( "inline bool $classname$::has_$oneof_name$() const {\n" " return $oneof_name$_case() != $cap_oneof_name$_NOT_SET;\n" "}\n" @@ -675,207 +828,252 @@ GenerateOneofHasBits(io::Printer* printer) { } } -void MessageGenerator:: -GenerateOneofMemberHasBits(const FieldDescriptor* field, - const std::map& vars, - io::Printer* printer) { +void MessageGenerator::GenerateOneofMemberHasBits(const FieldDescriptor* field, + const Formatter& format) { // Singular field in a oneof // N.B.: Without field presence, we do not use has-bits or generate // has_$name$() methods, but oneofs still have set_has_$name$(). // Oneofs also have has_$name$() but only as a private helper // method, so that generated code is slightly cleaner (vs. comparing // _oneof_case_[index] against a constant everywhere). - printer->Print(vars, - "inline bool $classname$::has_$name$() const {\n" - " return $oneof_name$_case() == k$field_name$;\n" - "}\n"); - printer->Print(vars, - "inline void $classname$::set_has_$name$() {\n" - " _oneof_case_[$oneof_index$] = k$field_name$;\n" - "}\n"); + format( + "inline bool $classname$::has_$name$() const {\n" + " return $oneof_name$_case() == k$field_name$;\n" + "}\n" + "inline void $classname$::set_has_$name$() {\n" + " _oneof_case_[$oneof_index$] = k$field_name$;\n" + "}\n"); } -void MessageGenerator:: -GenerateFieldClear(const FieldDescriptor* field, - const std::map& vars, - bool is_inline, - io::Printer* printer) { +void MessageGenerator::GenerateFieldClear(const FieldDescriptor* field, + bool is_inline, Formatter format) { // Generate clear_$name$(). if (is_inline) { - printer->Print("inline "); + format("inline "); } - printer->Print(vars, - "void $classname$::clear_$name$() {\n"); + format("void $classname$::clear_$name$() {\n"); - printer->Indent(); + format.Indent(); if (field->containing_oneof()) { // Clear this field only if it is the active field in this oneof, // otherwise ignore - printer->Print(vars, - "if (has_$name$()) {\n"); - printer->Indent(); - field_generators_.get(field) - .GenerateClearingCode(printer); - printer->Print(vars, - "clear_has_$oneof_name$();\n"); - printer->Outdent(); - printer->Print("}\n"); + format("if (has_$name$()) {\n"); + format.Indent(); + field_generators_.get(field).GenerateClearingCode(format.printer()); + format("clear_has_$oneof_name$();\n"); + format.Outdent(); + format("}\n"); } else { - field_generators_.get(field) - .GenerateClearingCode(printer); + field_generators_.get(field).GenerateClearingCode(format.printer()); if (HasFieldPresence(descriptor_->file())) { if (!field->is_repeated() && !field->options().weak()) { - printer->Print(vars, "clear_has_$name$();\n"); + int has_bit_index = has_bit_indices_[field->index()]; + GOOGLE_CHECK_GE(has_bit_index, 0); + + format.Set("has_array_index", has_bit_index / 32); + format.Set("has_mask", + strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8)); + format("_has_bits_[$has_array_index$] &= ~0x$has_mask$u;\n"); } } } - printer->Outdent(); - printer->Print("}\n"); + format.Outdent(); + format("}\n"); } -void MessageGenerator:: -GenerateFieldAccessorDefinitions(io::Printer* printer) { - printer->Print("// $classname$\n\n", "classname", classname_); +void MessageGenerator::GenerateFieldAccessorDefinitions(io::Printer* printer) { + Formatter format(printer, variables_); + format("// $classname$\n\n"); - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); + for (auto field : FieldRange(descriptor_)) { + PrintFieldComment(format, field); - PrintFieldComment(printer, field); - - std::map vars; + std::map vars; SetCommonFieldVariables(field, &vars, options_); + Formatter::SaveState saver(&format); + format.AddMap(vars); + // Generate has_$name$() or $name$_size(). if (field->is_repeated()) { - printer->Print(vars, - "inline int $classname$::$name$_size() const {\n" - " return $name$_.size();\n" - "}\n"); + format( + "inline int $classname$::$name$_size() const {\n" + " return $name$_.size();\n" + "}\n"); } else if (field->containing_oneof()) { - vars["field_name"] = UnderscoresToCamelCase(field->name(), true); - vars["oneof_name"] = field->containing_oneof()->name(); - vars["oneof_index"] = SimpleItoa(field->containing_oneof()->index()); - GenerateOneofMemberHasBits(field, vars, printer); + format.Set("field_name", UnderscoresToCamelCase(field->name(), true)); + format.Set("oneof_name", field->containing_oneof()->name()); + format.Set("oneof_index", + StrCat(field->containing_oneof()->index())); + GenerateOneofMemberHasBits(field, format); } else { // Singular field. - GenerateSingularFieldHasBits(field, vars, printer); + GenerateSingularFieldHasBits(field, format); } if (!IsCrossFileMaybeMap(field)) { - GenerateFieldClear(field, vars, true, printer); + GenerateFieldClear(field, true, format); } // Generate type-specific accessors. field_generators_.get(field).GenerateInlineAccessorDefinitions(printer); - printer->Print("\n"); + format("\n"); } // Generate has_$name$() and clear_has_$name$() functions for oneofs. GenerateOneofHasBits(printer); } -void MessageGenerator:: -GenerateClassDefinition(io::Printer* printer) { +void MessageGenerator::GenerateClassDefinition(io::Printer* printer) { + Formatter format(printer, variables_); + format.Set("class_final", + ShouldMarkClassAsFinal(descriptor_, options_) ? "final" : ""); + if (IsMapEntryMessage(descriptor_)) { - std::map vars; - vars["classname"] = classname_; - CollectMapInfo(descriptor_, &vars); + std::map vars; + CollectMapInfo(options_, descriptor_, &vars); vars["lite"] = HasDescriptorMethods(descriptor_->file(), options_) ? "" : "Lite"; - printer->Print( - vars, + format.AddMap(vars); + format( "class $classname$ : public " - "::google::protobuf::internal::MapEntry$lite$<$classname$, \n" + "::$proto_ns$::internal::MapEntry$lite$<$classname$, \n" " $key_cpp$, $val_cpp$,\n" - " $key_wire_type$,\n" - " $val_wire_type$,\n" + " ::$proto_ns$::internal::WireFormatLite::$key_wire_type$,\n" + " ::$proto_ns$::internal::WireFormatLite::$val_wire_type$,\n" " $default_enum_value$ > {\n" "public:\n" - " typedef ::google::protobuf::internal::MapEntry$lite$<$classname$, \n" + " typedef ::$proto_ns$::internal::MapEntry$lite$<$classname$, \n" " $key_cpp$, $val_cpp$,\n" - " $key_wire_type$,\n" - " $val_wire_type$,\n" + " ::$proto_ns$::internal::WireFormatLite::$key_wire_type$,\n" + " ::$proto_ns$::internal::WireFormatLite::$val_wire_type$,\n" " $default_enum_value$ > SuperType;\n" " $classname$();\n" - " $classname$(::google::protobuf::Arena* arena);\n" + " $classname$(::$proto_ns$::Arena* arena);\n" " void MergeFrom(const $classname$& other);\n" " static const $classname$* internal_default_instance() { return " "reinterpret_cast(&_$classname$_default_instance_); }\n"); - if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print( - " void MergeFrom(const ::google::protobuf::Message& other) final;\n" - " ::google::protobuf::Metadata GetMetadata() const;\n" - "};\n"); + std::string suffix = GetUtf8Suffix(descriptor_->field(0), options_); + if (descriptor_->field(0)->type() == FieldDescriptor::TYPE_STRING && + !suffix.empty()) { + if (suffix == "UTF8") { + format( + " static bool ValidateKey(std::string* s) {\n" + " return ::$proto_ns$::internal::WireFormatLite::" + "VerifyUtf8String(s->data(), s->size(), " + "::$proto_ns$::internal::WireFormatLite::PARSE, \"$1$\");\n" + " }\n", + descriptor_->field(0)->full_name()); + } else { + GOOGLE_CHECK(suffix == "UTF8Verify"); + format( + " static bool ValidateKey(std::string* s) {\n" + "#ifndef NDEBUG\n" + " ::$proto_ns$::internal::WireFormatLite::VerifyUtf8String(\n" + " s->data(), s->size(), ::$proto_ns$::internal::" + "WireFormatLite::PARSE, \"$1$\");\n" + "#endif\n" + " return true;\n" + " }\n", + descriptor_->field(0)->full_name()); + } } else { - printer->Print("};\n"); + format(" static bool ValidateKey(void*) { return true; }\n"); + } + if (descriptor_->field(1)->type() == FieldDescriptor::TYPE_STRING && + !suffix.empty()) { + if (suffix == "UTF8") { + format( + " static bool ValidateValue(std::string* s) {\n" + " return ::$proto_ns$::internal::WireFormatLite::" + "VerifyUtf8String(s->data(), s->size(), " + "::$proto_ns$::internal::WireFormatLite::PARSE, \"$1$\");\n" + " }\n", + descriptor_->field(1)->full_name()); + } else { + GOOGLE_CHECK(suffix == "UTF8Verify"); + format( + " static bool ValidateValue(std::string* s) {\n" + "#ifndef NDEBUG\n" + " ::$proto_ns$::internal::WireFormatLite::VerifyUtf8String(\n" + " s->data(), s->size(), ::$proto_ns$::internal::" + "WireFormatLite::PARSE, \"$1$\");\n" + "#endif\n" + " return true;\n" + " }\n", + descriptor_->field(1)->full_name()); + } + } else { + format(" static bool ValidateValue(void*) { return true; }\n"); + } + if (HasDescriptorMethods(descriptor_->file(), options_)) { + format( + " void MergeFrom(const ::$proto_ns$::Message& other) final;\n" + " ::$proto_ns$::Metadata GetMetadata() const final;\n" + " private:\n" + " static ::$proto_ns$::Metadata GetMetadataStatic() {\n" + " ::$proto_ns$::internal::AssignDescriptors(&::$desc_table$);\n" + " return ::$desc_table$.file_level_metadata[$1$];\n" + " }\n" + "\n" + " public:\n" + "};\n", + index_in_file_messages_); + } else { + format("};\n"); } return; } - std::map vars; - vars["classname"] = classname_; - vars["full_name"] = descriptor_->full_name(); - vars["field_count"] = SimpleItoa(descriptor_->field_count()); - vars["oneof_decl_count"] = SimpleItoa(descriptor_->oneof_decl_count()); - if (options_.dllexport_decl.empty()) { - vars["dllexport"] = ""; - } else { - vars["dllexport"] = options_.dllexport_decl + " "; - } - vars["superclass"] = SuperClassName(descriptor_, options_); - printer->Print(vars, - "class $dllexport$$classname$ : public $superclass$ " - "/* @@protoc_insertion_point(class_definition:$full_name$) */ " - "{\n"); - printer->Annotate("classname", descriptor_); - printer->Print(" public:\n"); - printer->Indent(); + format( + "class $dllexport_decl $${1$$classname$$}$$ class_final$ :\n" + " public $superclass$ /* @@protoc_insertion_point(" + "class_definition:$full_name$) */ {\n", + descriptor_); + format(" public:\n"); + format.Indent(); - printer->Print( - vars, + format( "$classname$();\n" "virtual ~$classname$();\n" "\n" "$classname$(const $classname$& from);\n" + "$classname$($classname$&& from) noexcept\n" + " : $classname$() {\n" + " *this = ::std::move(from);\n" + "}\n" "\n" "inline $classname$& operator=(const $classname$& from) {\n" " CopyFrom(from);\n" " return *this;\n" - "}\n"); + "}\n" + "inline $classname$& operator=($classname$&& from) noexcept {\n" + " if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {\n" + " if (this != &from) InternalSwap(&from);\n" + " } else {\n" + " CopyFrom(from);\n" + " }\n" + " return *this;\n" + "}\n" + "\n"); if (options_.table_driven_serialization) { - printer->Print( - "private:\n" - "const void* InternalGetTable() const;\n" - "public:\n" - "\n"); + format( + "private:\n" + "const void* InternalGetTable() const;\n" + "public:\n" + "\n"); } - // Generate move constructor and move assignment operator. - printer->Print(vars, - "#if LANG_CXX11\n" - "$classname$($classname$&& from) noexcept\n" - " : $classname$() {\n" - " *this = ::std::move(from);\n" - "}\n" - "\n" - "inline $classname$& operator=($classname$&& from) noexcept {\n" - " if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {\n" - " if (this != &from) InternalSwap(&from);\n" - " } else {\n" - " CopyFrom(from);\n" - " }\n" - " return *this;\n" - "}\n" - "#endif\n"); - + std::map vars; SetUnknkownFieldsVariable(descriptor_, options_, &vars); + format.AddMap(vars); if (PublicUnknownFieldsAccessors(descriptor_)) { - printer->Print(vars, + format( "inline const $unknown_fields_type$& unknown_fields() const {\n" " return $unknown_fields$;\n" "}\n" @@ -889,10 +1087,10 @@ GenerateClassDefinition(io::Printer* printer) { // MessageLite's implementation which returns NULL rather than generating our // own method which returns NULL, in order to reduce code size. if (SupportsArenas(descriptor_)) { - // virtual method version of GetArenaNoVirtual(), required for generic dispatch given a - // MessageLite* (e.g., in RepeatedField::AddAllocated()). - printer->Print( - "inline ::google::protobuf::Arena* GetArena() const final {\n" + // virtual method version of GetArenaNoVirtual(), required for generic + // dispatch given a MessageLite* (e.g., in RepeatedField::AddAllocated()). + format( + "inline ::$proto_ns$::Arena* GetArena() const final {\n" " return GetArenaNoVirtual();\n" "}\n" "inline void* GetMaybeArenaPointer() const final {\n" @@ -903,229 +1101,280 @@ GenerateClassDefinition(io::Printer* printer) { // Only generate this member if it's not disabled. if (HasDescriptorMethods(descriptor_->file(), options_) && !descriptor_->options().no_standard_descriptor_accessor()) { - printer->Print(vars, - "static const ::google::protobuf::Descriptor* descriptor();\n"); + format( + "static const ::$proto_ns$::Descriptor* descriptor() {\n" + " return GetDescriptor();\n" + "}\n"); } - printer->Print(vars, - "static const $classname$& default_instance();\n" - "\n"); + if (HasDescriptorMethods(descriptor_->file(), options_)) { + // These shadow non-static methods of the same names in Message. We + // redefine them here because calls directly on the generated class can be + // statically analyzed -- we know what descriptor types are being requested. + // It also avoids a vtable dispatch. + // + // We would eventually like to eliminate the methods in Message, and having + // this separate also lets us track calls to the base class methods + // separately. + format( + "static const ::$proto_ns$::Descriptor* GetDescriptor() {\n" + " return GetMetadataStatic().descriptor;\n" + "}\n" + "static const ::$proto_ns$::Reflection* GetReflection() {\n" + " return GetMetadataStatic().reflection;\n" + "}\n"); + } + + format( + "static const $classname$& default_instance();\n" + "\n"); // Generate enum values for every field in oneofs. One list is generated for // each oneof with an additional *_NOT_SET value. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "enum $camel_oneof_name$Case {\n", - "camel_oneof_name", - UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true)); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - printer->Print( - "k$field_name$ = $field_number$,\n", - "field_name", - UnderscoresToCamelCase( - descriptor_->oneof_decl(i)->field(j)->name(), true), - "field_number", - SimpleItoa(descriptor_->oneof_decl(i)->field(j)->number())); + for (auto oneof : OneOfRange(descriptor_)) { + format("enum $1$Case {\n", UnderscoresToCamelCase(oneof->name(), true)); + format.Indent(); + for (auto field : FieldRange(oneof)) { + std::string oneof_enum_case_field_name = + UnderscoresToCamelCase(field->name(), true); + format("k$1$ = $2$,\n", oneof_enum_case_field_name, // 1 + field->number()); // 2 } - printer->Print( - "$cap_oneof_name$_NOT_SET = 0,\n", - "cap_oneof_name", - ToUpper(descriptor_->oneof_decl(i)->name())); - printer->Outdent(); - printer->Print( + format("$1$_NOT_SET = 0,\n", ToUpper(oneof->name())); + format.Outdent(); + format( "};\n" "\n"); } // TODO(gerbens) make this private, while still granting other protos access. - vars["message_index"] = SimpleItoa(index_in_file_messages_); - printer->Print( - vars, + format( "static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY\n" "static inline const $classname$* internal_default_instance() {\n" " return reinterpret_cast(\n" " &_$classname$_default_instance_);\n" "}\n" "static constexpr int kIndexInFileMessages =\n" - " $message_index$;\n" - "\n"); + " $1$;\n" + "\n", + index_in_file_messages_); if (SupportsArenas(descriptor_)) { - printer->Print(vars, - "void UnsafeArenaSwap($classname$* other);\n"); + format("void UnsafeArenaSwap($classname$* other);\n"); } - if (IsAnyMessage(descriptor_)) { - printer->Print(vars, - "// implements Any -----------------------------------------------\n" - "\n" - "void PackFrom(const ::google::protobuf::Message& message);\n" - "void PackFrom(const ::google::protobuf::Message& message,\n" - " const ::std::string& type_url_prefix);\n" - "bool UnpackTo(::google::protobuf::Message* message) const;\n" - "template bool Is() const {\n" - " return _any_metadata_.Is();\n" + if (IsAnyMessage(descriptor_, options_)) { + format( + "// implements Any -----------------------------------------------\n" + "\n"); + if (HasDescriptorMethods(descriptor_->file(), options_)) { + format( + "void PackFrom(const ::$proto_ns$::Message& message);\n" + "void PackFrom(const ::$proto_ns$::Message& message,\n" + " const std::string& type_url_prefix);\n" + "bool UnpackTo(::$proto_ns$::Message* message) const;\n" + "static bool GetAnyFieldDescriptors(\n" + " const ::$proto_ns$::Message& message,\n" + " const ::$proto_ns$::FieldDescriptor** type_url_field,\n" + " const ::$proto_ns$::FieldDescriptor** value_field);\n"); + } else { + format( + "template \n" + "void PackFrom(const T& message) {\n" + " _any_metadata_.PackFrom(message);\n" + "}\n" + "template \n" + "void PackFrom(const T& message,\n" + " const std::string& type_url_prefix) {\n" + " _any_metadata_.PackFrom(message, type_url_prefix);" + "}\n" + "template \n" + "bool UnpackTo(T* message) const {\n" + " return _any_metadata_.UnpackTo(message);\n" + "}\n"); + } + format( + "template bool Is() const {\n" + " return _any_metadata_.Is();\n" + "}\n" + "static bool ParseAnyTypeUrl(const string& type_url,\n" + " std::string* full_type_name);\n"); + } + + format.Set("new_final", + ShouldMarkNewAsFinal(descriptor_, options_) ? "final" : ""); + + format( + "void Swap($classname$* other);\n" + "friend void swap($classname$& a, $classname$& b) {\n" + " a.Swap(&b);\n" "}\n" - "static bool ParseAnyTypeUrl(const string& type_url,\n" - " string* full_type_name);\n" - "\n"); - } - - vars["new_final"] = " final"; - - printer->Print(vars, - "void Swap($classname$* other);\n" - "friend void swap($classname$& a, $classname$& b) {\n" - " a.Swap(&b);\n" - "}\n" - "\n" - "// implements Message ----------------------------------------------\n" - "\n" - "inline $classname$* New() const$new_final$ {\n" - " return CreateMaybeMessage<$classname$>(NULL);\n" - "}\n" - "\n" - "$classname$* New(::google::protobuf::Arena* arena) const$new_final$ {\n" - " return CreateMaybeMessage<$classname$>(arena);\n" - "}\n"); + "\n" + "// implements Message ----------------------------------------------\n" + "\n" + "inline $classname$* New() const$ new_final$ {\n" + " return CreateMaybeMessage<$classname$>(nullptr);\n" + "}\n" + "\n" + "$classname$* New(::$proto_ns$::Arena* arena) const$ new_final$ {\n" + " return CreateMaybeMessage<$classname$>(arena);\n" + "}\n"); // For instances that derive from Message (rather than MessageLite), some // methods are virtual and should be marked as final. - string use_final = HasDescriptorMethods(descriptor_->file(), options_) ? - " final" : ""; + format.Set("full_final", HasDescriptorMethods(descriptor_->file(), options_) + ? "final" + : ""); if (HasGeneratedMethods(descriptor_->file(), options_)) { if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print(vars, - "void CopyFrom(const ::google::protobuf::Message& from) final;\n" - "void MergeFrom(const ::google::protobuf::Message& from) final;\n"); + format( + "void CopyFrom(const ::$proto_ns$::Message& from) final;\n" + "void MergeFrom(const ::$proto_ns$::Message& from) final;\n"); } else { - printer->Print(vars, - "void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)\n" - " final;\n"); + format( + "void CheckTypeAndMergeFrom(const ::$proto_ns$::MessageLite& from)\n" + " final;\n"); } - vars["clear_final"] = " final"; - vars["is_initialized_final"] = " final"; - vars["merge_partial_final"] = " final"; + format.Set("clear_final", + ShouldMarkClearAsFinal(descriptor_, options_) ? "final" : ""); + format.Set( + "is_initialized_final", + ShouldMarkIsInitializedAsFinal(descriptor_, options_) ? "final" : ""); - printer->Print( - vars, + format( "void CopyFrom(const $classname$& from);\n" "void MergeFrom(const $classname$& from);\n" - "void Clear()$clear_final$;\n" - "bool IsInitialized() const$is_initialized_final$;\n" + "PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear()$ clear_final$;\n" + "bool IsInitialized() const$ is_initialized_final$;\n" "\n" "size_t ByteSizeLong() const final;\n" + "#if $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n" + "const char* _InternalParse(const char* ptr, " + "::$proto_ns$::internal::ParseContext* ctx) final;\n" + "#else\n" "bool MergePartialFromCodedStream(\n" - " ::google::protobuf::io::CodedInputStream* input)$merge_partial_final$;\n"); + " ::$proto_ns$::io::CodedInputStream* input) final;\n" + "#endif // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n"); + if (!options_.table_driven_serialization || descriptor_->options().message_set_wire_format()) { - printer->Print( + format( "void SerializeWithCachedSizes(\n" - " ::google::protobuf::io::CodedOutputStream* output) const " - "final;\n"); + " ::$proto_ns$::io::CodedOutputStream* output) const final;\n"); } // DiscardUnknownFields() is implemented in message.cc using reflections. We // need to implement this function in generated code for messages. if (!UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print( - "void DiscardUnknownFields()$final$;\n", - "final", use_final); + format("void DiscardUnknownFields()$ full_final$;\n"); } if (HasFastArraySerialization(descriptor_->file(), options_)) { - printer->Print( - "::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(\n" - " bool deterministic, ::google::protobuf::uint8* target) const final;\n"); + format( + "$uint8$* InternalSerializeWithCachedSizesToArray(\n" + " $uint8$* target) const final;\n"); } } - printer->Print( + format( "int GetCachedSize() const final { return _cached_size_.Get(); }" "\n\nprivate:\n" - "void SharedCtor();\n" - "void SharedDtor();\n" - "void SetCachedSize(int size) const$final$;\n" - "void InternalSwap($classname$* other);\n", - "classname", classname_, "final", use_final); + "inline void SharedCtor();\n" + "inline void SharedDtor();\n" + "void SetCachedSize(int size) const$ full_final$;\n" + "void InternalSwap($classname$* other);\n"); + + format( + // Friend AnyMetadata so that it can call this FullMessageName() method. + "friend class ::$proto_ns$::internal::AnyMetadata;\n" + "static $1$ FullMessageName() {\n" + " return \"$full_name$\";\n" + "}\n", + options_.opensource_runtime ? "::PROTOBUF_NAMESPACE_ID::StringPiece" + : "::StringPiece"); + if (SupportsArenas(descriptor_)) { - printer->Print( - // TODO(gerbens) Make this private! Currently people are deriving from - // protos to give access to this constructor, breaking the invariants - // we rely on. - "protected:\n" - "explicit $classname$(::google::protobuf::Arena* arena);\n" - "private:\n" - "static void ArenaDtor(void* object);\n" - "inline void RegisterArenaDtor(::google::protobuf::Arena* arena);\n", - "classname", classname_); + format( + // TODO(gerbens) Make this private! Currently people are deriving from + // protos to give access to this constructor, breaking the invariants + // we rely on. + "protected:\n" + "explicit $classname$(::$proto_ns$::Arena* arena);\n" + "private:\n" + "static void ArenaDtor(void* object);\n" + "inline void RegisterArenaDtor(::$proto_ns$::Arena* arena);\n"); } if (SupportsArenas(descriptor_)) { - printer->Print( - "private:\n" - "inline ::google::protobuf::Arena* GetArenaNoVirtual() const {\n" - " return _internal_metadata_.arena();\n" - "}\n" - "inline void* MaybeArenaPtr() const {\n" - " return _internal_metadata_.raw_arena_ptr();\n" - "}\n"); + format( + "private:\n" + "inline ::$proto_ns$::Arena* GetArenaNoVirtual() const {\n" + " return _internal_metadata_.arena();\n" + "}\n" + "inline void* MaybeArenaPtr() const {\n" + " return _internal_metadata_.raw_arena_ptr();\n" + "}\n"); } else { - printer->Print( - "private:\n" - "inline ::google::protobuf::Arena* GetArenaNoVirtual() const {\n" - " return NULL;\n" - "}\n" - "inline void* MaybeArenaPtr() const {\n" - " return NULL;\n" - "}\n"); + format( + "private:\n" + "inline ::$proto_ns$::Arena* GetArenaNoVirtual() const {\n" + " return nullptr;\n" + "}\n" + "inline void* MaybeArenaPtr() const {\n" + " return nullptr;\n" + "}\n"); } - printer->Print( + format( "public:\n" "\n"); if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print( - "::google::protobuf::Metadata GetMetadata() const final;\n" - "\n"); + format( + "::$proto_ns$::Metadata GetMetadata() const final;\n" + "private:\n" + "static ::$proto_ns$::Metadata GetMetadataStatic() {\n" + " ::$proto_ns$::internal::AssignDescriptors(&::$desc_table$);\n" + " return ::$desc_table$.file_level_metadata[kIndexInFileMessages];\n" + "}\n" + "\n" + "public:\n" + "\n"); } else { - printer->Print( - "::std::string GetTypeName() const final;\n" - "\n"); + format( + "std::string GetTypeName() const final;\n" + "\n"); } - printer->Print( - "// nested types ----------------------------------------------------\n" - "\n"); + format( + "// nested types ----------------------------------------------------\n" + "\n"); // Import all nested message classes into this class's scope with typedefs. for (int i = 0; i < descriptor_->nested_type_count(); i++) { const Descriptor* nested_type = descriptor_->nested_type(i); if (!IsMapEntryMessage(nested_type)) { - printer->Print("typedef $nested_full_name$ $nested_name$;\n", - "nested_name", nested_type->name(), - "nested_full_name", ClassName(nested_type, false)); - printer->Annotate("nested_full_name", nested_type); - printer->Annotate("nested_name", nested_type); + format.Set("nested_full_name", ClassName(nested_type, false)); + format.Set("nested_name", ResolveKeyword(nested_type->name())); + format("typedef ${1$$nested_full_name$$}$ ${1$$nested_name$$}$;\n", + nested_type); } } if (descriptor_->nested_type_count() > 0) { - printer->Print("\n"); + format("\n"); } // Import all nested enums and their values into this class's scope with // typedefs and constants. for (int i = 0; i < descriptor_->enum_type_count(); i++) { enum_generators_[i]->GenerateSymbolImports(printer); - printer->Print("\n"); + format("\n"); } - printer->Print( - "// accessors -------------------------------------------------------\n" - "\n"); + format( + "// accessors -------------------------------------------------------\n" + "\n"); // Generate accessor methods for all fields. GenerateFieldAccessorDeclarations(printer); @@ -1136,49 +1385,37 @@ GenerateClassDefinition(io::Printer* printer) { } - printer->Print( - "// @@protoc_insertion_point(class_scope:$full_name$)\n", - "full_name", descriptor_->full_name()); + format("// @@protoc_insertion_point(class_scope:$full_name$)\n"); // Generate private members. - printer->Outdent(); - printer->Print(" private:\n"); - printer->Indent(); + format.Outdent(); + format(" private:\n"); + format.Indent(); + // TODO(seongkim): Remove hack to track field access and remove this class. + format("class HasBitSetters;\n"); - for (int i = 0; i < descriptor_->field_count(); i++) { - if (!descriptor_->field(i)->is_repeated() && - !descriptor_->field(i)->options().weak()) { - // set_has_***() generated in all proto1/2 code and in oneofs (only) for - // messages without true field presence. - if (HasFieldPresence(descriptor_->file()) || - descriptor_->field(i)->containing_oneof()) { - printer->Print("void set_has_$name$();\n", "name", - FieldName(descriptor_->field(i))); - } - // clear_has_***() generated only for non-oneof fields - // in proto1/2. - if (!descriptor_->field(i)->containing_oneof() && - HasFieldPresence(descriptor_->file())) { - printer->Print("void clear_has_$name$();\n", "name", - FieldName(descriptor_->field(i))); - } + for (auto field : FieldRange(descriptor_)) { + // set_has_***() generated in all oneofs. + if (!field->is_repeated() && !field->options().weak() && + field->containing_oneof()) { + format("void set_has_$1$();\n", FieldName(field)); } } - printer->Print("\n"); + format("\n"); // Generate oneof function declarations - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "inline bool has_$oneof_name$() const;\n" - "inline void clear_has_$oneof_name$();\n\n", - "oneof_name", descriptor_->oneof_decl(i)->name()); + for (auto oneof : OneOfRange(descriptor_)) { + format( + "inline bool has_$1$() const;\n" + "inline void clear_has_$1$();\n\n", + oneof->name()); } if (HasGeneratedMethods(descriptor_->file(), options_) && !descriptor_->options().message_set_wire_format() && num_required_fields_ > 1) { - printer->Print( + format( "// helper for ByteSizeLong()\n" "size_t RequiredFieldsByteSizeFallback() const;\n\n"); } @@ -1187,14 +1424,15 @@ GenerateClassDefinition(io::Printer* printer) { // output will be determined later. bool need_to_emit_cached_size = true; - // TODO(kenton): Make _cached_size_ an atomic when C++ supports it. - const string cached_size_decl = - "mutable ::google::protobuf::internal::CachedSize _cached_size_;\n"; + const std::string cached_size_decl = + "mutable ::$proto_ns$::internal::CachedSize _cached_size_;\n"; const size_t sizeof_has_bits = HasBitsSize(); - const string has_bits_decl = sizeof_has_bits == 0 ? "" : - "::google::protobuf::internal::HasBits<" + SimpleItoa(sizeof_has_bits / 4) + - "> _has_bits_;\n"; + const std::string has_bits_decl = + sizeof_has_bits == 0 + ? "" + : StrCat("::$proto_ns$::internal::HasBits<", + sizeof_has_bits / 4, "> _has_bits_;\n"); // To minimize padding, data members are divided into three sections: // (1) members assumed to align to 8 bytes @@ -1205,154 +1443,138 @@ GenerateClassDefinition(io::Printer* printer) { // Members assumed to align to 8 bytes: if (descriptor_->extension_range_count() > 0) { - printer->Print( - "::google::protobuf::internal::ExtensionSet _extensions_;\n" - "\n"); + format( + "::$proto_ns$::internal::ExtensionSet _extensions_;\n" + "\n"); } if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print( - "::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;\n"); + format( + "::$proto_ns$::internal::InternalMetadataWithArena " + "_internal_metadata_;\n"); } else { - printer->Print( - "::google::protobuf::internal::InternalMetadataWithArenaLite " + format( + "::$proto_ns$::internal::InternalMetadataWithArenaLite " "_internal_metadata_;\n"); } if (SupportsArenas(descriptor_)) { - printer->Print( - "template friend class ::google::protobuf::Arena::InternalHelper;\n" - "typedef void InternalArenaConstructable_;\n" - "typedef void DestructorSkippable_;\n"); + format( + "template friend class " + "::$proto_ns$::Arena::InternalHelper;\n" + "typedef void InternalArenaConstructable_;\n" + "typedef void DestructorSkippable_;\n"); } if (HasFieldPresence(descriptor_->file())) { // _has_bits_ is frequently accessed, so to reduce code size and improve - // speed, it should be close to the start of the object. But, try not to - // waste space:_has_bits_ by itself always makes sense if its size is a - // multiple of 8, but, otherwise, maybe _has_bits_ and cached_size_ together - // will work well. - printer->Print(has_bits_decl.c_str()); - if ((sizeof_has_bits % 8) != 0) { - printer->Print(cached_size_decl.c_str()); - need_to_emit_cached_size = false; - } + // speed, it should be close to the start of the object. Placing + // _cached_size_ together with _has_bits_ improves cache locality despite + // potential alignment padding. + format(has_bits_decl.c_str()); + format(cached_size_decl.c_str()); + need_to_emit_cached_size = false; } // Field members: // Emit some private and static members - for (int i = 0; i < optimized_order_.size(); ++i) { - const FieldDescriptor* field = optimized_order_[i]; + for (auto field : optimized_order_) { const FieldGenerator& generator = field_generators_.get(field); generator.GenerateStaticMembers(printer); generator.GeneratePrivateMembers(printer); } // For each oneof generate a union - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "union $camel_oneof_name$Union {\n" + for (auto oneof : OneOfRange(descriptor_)) { + std::string camel_oneof_name = UnderscoresToCamelCase(oneof->name(), true); + format( + "union $1$Union {\n" // explicit empty constructor is needed when union contains // ArenaStringPtr members for string fields. - " $camel_oneof_name$Union() {}\n", - "camel_oneof_name", - UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true)); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - field_generators_.get(descriptor_->oneof_decl(i)-> - field(j)).GeneratePrivateMembers(printer); + " $1$Union() {}\n", + camel_oneof_name); + format.Indent(); + for (auto field : FieldRange(oneof)) { + field_generators_.get(field).GeneratePrivateMembers(printer); } - printer->Outdent(); - printer->Print( - "} $oneof_name$_;\n", - "oneof_name", descriptor_->oneof_decl(i)->name()); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - field_generators_.get(descriptor_->oneof_decl(i)-> - field(j)).GenerateStaticMembers(printer); + format.Outdent(); + format("} $1$_;\n", oneof->name()); + for (auto field : FieldRange(oneof)) { + field_generators_.get(field).GenerateStaticMembers(printer); } } // Members assumed to align to 4 bytes: if (need_to_emit_cached_size) { - printer->Print(cached_size_decl.c_str()); + format(cached_size_decl.c_str()); need_to_emit_cached_size = false; } // Generate _oneof_case_. if (descriptor_->oneof_decl_count() > 0) { - printer->Print(vars, - "::google::protobuf::uint32 _oneof_case_[$oneof_decl_count$];\n" - "\n"); + format( + "$uint32$ _oneof_case_[$1$];\n" + "\n", + descriptor_->oneof_decl_count()); } if (num_weak_fields_) { - printer->Print( - "::google::protobuf::internal::WeakFieldMap _weak_field_map_;\n"); + format("::$proto_ns$::internal::WeakFieldMap _weak_field_map_;\n"); } // Generate _any_metadata_ for the Any type. - if (IsAnyMessage(descriptor_)) { - printer->Print(vars, - "::google::protobuf::internal::AnyMetadata _any_metadata_;\n"); + if (IsAnyMessage(descriptor_, options_)) { + format("::$proto_ns$::internal::AnyMetadata _any_metadata_;\n"); } // The TableStruct struct needs access to the private parts, in order to // construct the offsets of all members. - printer->Print("friend struct ::$file_namespace$::TableStruct;\n", - // Vars. - "scc_name", scc_name_, "file_namespace", - FileLevelNamespace(descriptor_)); + format("friend struct ::$tablename$;\n"); - printer->Outdent(); - printer->Print("};"); + format.Outdent(); + format("};"); GOOGLE_DCHECK(!need_to_emit_cached_size); } -void MessageGenerator:: -GenerateInlineMethods(io::Printer* printer) { +void MessageGenerator::GenerateInlineMethods(io::Printer* printer) { if (IsMapEntryMessage(descriptor_)) return; GenerateFieldAccessorDefinitions(printer); // Generate oneof_case() functions. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - std::map vars; - vars["class_name"] = classname_; - vars["camel_oneof_name"] = UnderscoresToCamelCase( - descriptor_->oneof_decl(i)->name(), true); - vars["oneof_name"] = descriptor_->oneof_decl(i)->name(); - vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index()); - printer->Print( - vars, - "inline $class_name$::$camel_oneof_name$Case $class_name$::" - "$oneof_name$_case() const {\n" - " return $class_name$::$camel_oneof_name$Case(" + for (auto oneof : OneOfRange(descriptor_)) { + Formatter format(printer, variables_); + format.Set("camel_oneof_name", UnderscoresToCamelCase(oneof->name(), true)); + format.Set("oneof_name", oneof->name()); + format.Set("oneof_index", oneof->index()); + format( + "inline $classname$::$camel_oneof_name$Case $classname$::" + "${1$$oneof_name$_case$}$() const {\n" + " return $classname$::$camel_oneof_name$Case(" "_oneof_case_[$oneof_index$]);\n" - "}\n"); + "}\n", + oneof); } } -void MessageGenerator:: -GenerateExtraDefaultFields(io::Printer* printer) { +void MessageGenerator::GenerateExtraDefaultFields(io::Printer* printer) { // Generate oneof default instance and weak field instances for reflection // usage. + Formatter format(printer, variables_); if (descriptor_->oneof_decl_count() > 0 || num_weak_fields_ > 0) { - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); + for (auto oneof : OneOfRange(descriptor_)) { + for (auto field : FieldRange(oneof)) { if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE || (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING && - EffectiveStringCType(field) != FieldOptions::STRING)) { - printer->Print("const "); + EffectiveStringCType(field, options_) != FieldOptions::STRING)) { + format("const "); } field_generators_.get(field).GeneratePrivateMembers(printer); } } - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); + for (auto field : FieldRange(descriptor_)) { if (field->options().weak()) { - printer->Print( - " const ::google::protobuf::Message* $name$_;\n", "name", FieldName(field)); + format(" const ::$proto_ns$::Message* $1$_;\n", FieldName(field)); } } } @@ -1360,130 +1582,78 @@ GenerateExtraDefaultFields(io::Printer* printer) { bool MessageGenerator::GenerateParseTable(io::Printer* printer, size_t offset, size_t aux_offset) { + Formatter format(printer, variables_); + if (!table_driven_) { - printer->Print("{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },\n"); + format("{ nullptr, nullptr, 0, -1, -1, -1, -1, nullptr, false },\n"); return false; } - std::map vars; - - vars["classname"] = ClassName(descriptor_); - vars["classtype"] = QualifiedClassName(descriptor_); - vars["offset"] = SimpleItoa(offset); - vars["aux_offset"] = SimpleItoa(aux_offset); - int max_field_number = 0; - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); + for (auto field : FieldRange(descriptor_)) { if (max_field_number < field->number()) { max_field_number = field->number(); } } - vars["max_field_number"] = SimpleItoa(max_field_number); + format("{\n"); + format.Indent(); - printer->Print("{\n"); - printer->Indent(); - - printer->Print(vars, - "TableStruct::entries + $offset$,\n" - "TableStruct::aux + $aux_offset$,\n" - "$max_field_number$,\n"); + format( + "$tablename$::entries + $1$,\n" + "$tablename$::aux + $2$,\n" + "$3$,\n", + offset, aux_offset, max_field_number); if (!HasFieldPresence(descriptor_->file())) { // If we don't have field presence, then _has_bits_ does not exist. - printer->Print(vars, "-1,\n"); + format("-1,\n"); } else { - printer->Print(vars, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n" - " $classtype$, _has_bits_),\n"); + format("PROTOBUF_FIELD_OFFSET($classtype$, _has_bits_),\n"); } if (descriptor_->oneof_decl_count() > 0) { - printer->Print(vars, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n" - " $classtype$, _oneof_case_),\n"); + format("PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_),\n"); } else { - printer->Print("-1, // no _oneof_case_\n"); + format("-1, // no _oneof_case_\n"); } if (descriptor_->extension_range_count() > 0) { - printer->Print(vars, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, " - "_extensions_),\n"); + format("PROTOBUF_FIELD_OFFSET($classtype$, _extensions_),\n"); } else { - printer->Print("-1, // no _extensions_\n"); + format("-1, // no _extensions_\n"); } // TODO(ckennelly): Consolidate this with the calculation for // AuxillaryParseTableField. - vars["ns"] = Namespace(descriptor_); - - printer->Print(vars, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n" - " $classtype$, _internal_metadata_),\n" - "&$ns$::_$classname$_default_instance_,\n"); + format( + "PROTOBUF_FIELD_OFFSET($classtype$, _internal_metadata_),\n" + "&$package_ns$::_$classname$_default_instance_,\n"); if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(vars, "true,\n"); + format("true,\n"); } else { - printer->Print(vars, "false,\n"); + format("false,\n"); } - printer->Outdent(); - printer->Print("},\n"); + format.Outdent(); + format("},\n"); return true; } void MessageGenerator::GenerateSchema(io::Printer* printer, int offset, int has_offset) { - std::map vars; - - vars["classname"] = QualifiedClassName(descriptor_); - vars["offset"] = SimpleItoa(offset); - vars["has_bits_offsets"] = + Formatter format(printer, variables_); + has_offset = HasFieldPresence(descriptor_->file()) || IsMapEntryMessage(descriptor_) - ? SimpleItoa(offset + has_offset) - : "-1"; + ? offset + has_offset + : -1; - printer->Print(vars, - "{ $offset$, $has_bits_offsets$, sizeof($classname$)},\n"); + format("{ $1$, $2$, sizeof($classtype$)},\n", offset, has_offset); } namespace { -// TODO(gerbens) remove this after the next sync with GitHub code base. -// Then the opensource testing has gained the functionality to compile -// the CalcFieldNum given the symbols defined in generated-message-util. -#ifdef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP -// We need a clean version of CalcFieldNum that doesn't use new functionality -// in the runtime, because this functionality is not yet in the opensource -// runtime - -uint32 CalculateType(uint32 type, uint32 type_class) { - return (type - 1) + type_class * 20; -} - -uint32 CalcFieldNum(const FieldGenerator&, const FieldDescriptor* field, - const Options& options) { - bool is_a_map = IsMapEntryMessage(field->containing_type()); - int type = field->type(); - if (field->containing_oneof()) { - return CalculateType(type, 4); - } - if (field->is_packed()) { - return CalculateType(type, 3); - } else if (field->is_repeated()) { - return CalculateType(type, 2); - } else if (!HasFieldPresence(field->file()) && - field->containing_oneof() == NULL && !is_a_map) { - return CalculateType(type, 1); - } else { - return CalculateType(type, 0); - } -} - -#else // We need to calculate for each field what function the table driven code // should use to serialize it. This returns the index in a lookup table. uint32 CalcFieldNum(const FieldGenerator& generator, @@ -1495,6 +1665,12 @@ uint32 CalcFieldNum(const FieldGenerator& generator, if (generator.IsInlined()) { type = internal::FieldMetadata::kInlinedType; } + // string field + if (IsCord(field, options)) { + type = internal::FieldMetadata::kCordType; + } else if (IsStringPiece(field, options)) { + type = internal::FieldMetadata::kStringPieceType; + } } if (field->containing_oneof()) { return internal::FieldMetadata::CalculateType( @@ -1515,7 +1691,6 @@ uint32 CalcFieldNum(const FieldGenerator& generator, type, internal::FieldMetadata::kPresence); } } -#endif int FindMessageIndexInFile(const Descriptor* descriptor) { std::vector flatten = @@ -1527,12 +1702,11 @@ int FindMessageIndexInFile(const Descriptor* descriptor) { } // namespace int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { + Formatter format(printer, variables_); if (!options_.table_driven_serialization) { return 0; } - string full_classname = QualifiedClassName(descriptor_); - std::vector sorted = SortFieldsByNumber(descriptor_); if (IsMapEntryMessage(descriptor_)) { for (int i = 0; i < 2; i++) { @@ -1542,38 +1716,38 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { uint32 tag = internal::WireFormatLite::MakeTag( field->number(), WireFormat::WireTypeForFieldType(field->type())); - std::map vars; - vars["classname"] = QualifiedClassName(descriptor_); + std::map vars; + vars["classtype"] = QualifiedClassName(descriptor_, options_); vars["field_name"] = FieldName(field); - vars["tag"] = SimpleItoa(tag); - vars["hasbit"] = SimpleItoa(i); - vars["type"] = SimpleItoa(CalcFieldNum(generator, field, options_)); - vars["ptr"] = "NULL"; + vars["tag"] = StrCat(tag); + vars["hasbit"] = StrCat(i); + vars["type"] = StrCat(CalcFieldNum(generator, field, options_)); + vars["ptr"] = "nullptr"; if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { GOOGLE_CHECK(!IsMapEntryMessage(field->message_type())); - { - vars["ptr"] = - "::" + FileLevelNamespace(field->message_type()) + - "::TableStruct::serialization_table + " + - SimpleItoa(FindMessageIndexInFile(field->message_type())); - } + vars["ptr"] = + "::" + UniqueName("TableStruct", field->message_type(), options_) + + "::serialization_table + " + + StrCat(FindMessageIndexInFile(field->message_type())); } - printer->Print(vars, - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(" - "::google::protobuf::internal::MapEntryHelper<$classname$::" - "SuperType>, $field_name$_), $tag$," - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(" - "::google::protobuf::internal::MapEntryHelper<$classname$::" - "SuperType>, _has_bits_) * 8 + $hasbit$, $type$, " - "$ptr$},\n"); + Formatter::SaveState saver(&format); + format.AddMap(vars); + format( + "{PROTOBUF_FIELD_OFFSET(" + "::$proto_ns$::internal::MapEntryHelper<$classtype$::" + "SuperType>, $field_name$_), $tag$," + "PROTOBUF_FIELD_OFFSET(" + "::$proto_ns$::internal::MapEntryHelper<$classtype$::" + "SuperType>, _has_bits_) * 8 + $hasbit$, $type$, " + "$ptr$},\n"); } return 2; } - printer->Print( - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, " - "_cached_size_), 0, 0, 0, NULL},\n", - "classname", full_classname); + format( + "{PROTOBUF_FIELD_OFFSET($classtype$, _cached_size_)," + " 0, 0, 0, nullptr},\n"); std::vector sorted_extensions; + sorted_extensions.reserve(descriptor_->extension_range_count()); for (int i = 0; i < descriptor_->extension_range_count(); ++i) { sorted_extensions.push_back(descriptor_->extension_range(i)); } @@ -1586,14 +1760,12 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { extension_idx++) { const Descriptor::ExtensionRange* range = sorted_extensions[extension_idx]; - printer->Print( - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, " - "_extensions_), $start$, $end$, " - "::google::protobuf::internal::FieldMetadata::kSpecial, " + format( + "{PROTOBUF_FIELD_OFFSET($classtype$, _extensions_), " + "$1$, $2$, ::$proto_ns$::internal::FieldMetadata::kSpecial, " "reinterpret_cast(::google::protobuf::internal::ExtensionSerializer)},\n", - "classname", full_classname, "start", SimpleItoa(range->start), "end", - SimpleItoa(range->end)); + "void*>(::$proto_ns$::internal::ExtensionSerializer)},\n", + range->start, range->end); } if (i == sorted.size()) break; const FieldDescriptor* field = sorted[i]; @@ -1605,113 +1777,122 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED); } - string classfieldname = FieldName(field); + std::string classfieldname = FieldName(field); if (field->containing_oneof()) { classfieldname = field->containing_oneof()->name(); } - std::map vars; - vars["classname"] = full_classname; - vars["field_name"] = classfieldname; - vars["tag"] = SimpleItoa(tag); - vars["ptr"] = "NULL"; + format.Set("field_name", classfieldname); + std::string ptr = "nullptr"; if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { if (IsMapEntryMessage(field->message_type())) { - vars["idx"] = SimpleItoa(FindMessageIndexInFile(field->message_type())); - vars["fieldclassname"] = QualifiedClassName(field->message_type()); - printer->Print(vars, - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($" - "classname$, $field_name$_), $tag$, $idx$, " - "::google::protobuf::internal::FieldMetadata::kSpecial, " - "reinterpret_cast(static_cast< " - "::google::protobuf::internal::SpecialSerializer>(" - "::google::protobuf::internal::MapFieldSerializer< " - "::google::protobuf::internal::MapEntryToMapField<" - "$fieldclassname$>::MapFieldType, " - "TableStruct::serialization_table>))},\n"); + format( + "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), $1$, $2$, " + "::$proto_ns$::internal::FieldMetadata::kSpecial, " + "reinterpret_cast(static_cast< " + "::$proto_ns$::internal::SpecialSerializer>(" + "::$proto_ns$::internal::MapFieldSerializer< " + "::$proto_ns$::internal::MapEntryToMapField<" + "$3$>::MapFieldType, " + "$tablename$::serialization_table>))},\n", + tag, FindMessageIndexInFile(field->message_type()), + QualifiedClassName(field->message_type(), options_)); continue; - } else { - vars["ptr"] = - "::" + FileLevelNamespace(field->message_type()) + - "::TableStruct::serialization_table + " + - SimpleItoa(FindMessageIndexInFile(field->message_type())); + } else if (!field->message_type()->options().message_set_wire_format()) { + // message_set doesn't have the usual table and we need to + // dispatch to generated serializer, hence ptr stays zero. + ptr = + "::" + UniqueName("TableStruct", field->message_type(), options_) + + "::serialization_table + " + + StrCat(FindMessageIndexInFile(field->message_type())); } } const FieldGenerator& generator = field_generators_.get(field); - vars["type"] = SimpleItoa(CalcFieldNum(generator, field, options_)); + int type = CalcFieldNum(generator, field, options_); + if (IsLazy(field, options_)) { + type = internal::FieldMetadata::kSpecial; + ptr = "reinterpret_cast(::" + variables_["proto_ns"] + + "::internal::LazyFieldSerializer"; + if (field->containing_oneof()) { + ptr += "OneOf"; + } else if (!HasFieldPresence(descriptor_->file()) || + has_bit_indices_[field->index()] == -1) { + ptr += "NoPresence"; + } + ptr += ")"; + } if (field->options().weak()) { // TODO(gerbens) merge weak fields into ranges - printer->Print(vars, - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($" - "classname$, _weak_field_map_), $tag$, $tag$, " - "::google::protobuf::internal::FieldMetadata::kSpecial, " - "reinterpret_cast(::google::protobuf::internal::WeakFieldSerializer)},\n"); + format( + "{PROTOBUF_FIELD_OFFSET(" + "$classtype$, _weak_field_map_), $1$, $1$, " + "::$proto_ns$::internal::FieldMetadata::kSpecial, " + "reinterpret_cast(::$proto_ns$::internal::WeakFieldSerializer)},\n", + tag); } else if (field->containing_oneof()) { - vars["oneofoffset"] = - SimpleItoa(sizeof(uint32) * field->containing_oneof()->index()); - printer->Print(vars, - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($" - "classname$, $field_name$_), $tag$, " - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($" - "classname$, _oneof_case_) + $oneofoffset$, " - "$type$, $ptr$},\n"); + format.Set("oneofoffset", + sizeof(uint32) * field->containing_oneof()->index()); + format( + "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), $1$," + " PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_) + " + "$oneofoffset$, $2$, $3$},\n", + tag, type, ptr); } else if (HasFieldPresence(descriptor_->file()) && has_bit_indices_[field->index()] != -1) { - vars["hasbitsoffset"] = SimpleItoa(has_bit_indices_[field->index()]); - printer->Print(vars, - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($" - "classname$, $field_name$_), $tag$, " - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($" - "classname$, _has_bits_) * 8 + $hasbitsoffset$, $type$, " - "$ptr$},\n"); + format.Set("hasbitsoffset", has_bit_indices_[field->index()]); + format( + "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), " + "$1$, PROTOBUF_FIELD_OFFSET($classtype$, _has_bits_) * 8 + " + "$hasbitsoffset$, $2$, $3$},\n", + tag, type, ptr); } else { - printer->Print(vars, - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($" - "classname$, $field_name$_), $tag$, ~0u, $type$, " - "$ptr$},\n"); + format( + "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), " + "$1$, ~0u, $2$, $3$},\n", + tag, type, ptr); } } int num_field_metadata = 1 + sorted.size() + sorted_extensions.size(); num_field_metadata++; - string serializer = UseUnknownFieldSet(descriptor_->file(), options_) - ? "::google::protobuf::internal::UnknownFieldSetSerializer" - : "::google::protobuf::internal::UnknownFieldSerializerLite"; - printer->Print( - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, " - "_internal_metadata_), 0, ~0u, " - "::google::protobuf::internal::FieldMetadata::kSpecial, reinterpret_cast($serializer$)},\n", - "classname", full_classname, "serializer", serializer); + std::string serializer = UseUnknownFieldSet(descriptor_->file(), options_) + ? "UnknownFieldSetSerializer" + : "UnknownFieldSerializerLite"; + format( + "{PROTOBUF_FIELD_OFFSET($classtype$, _internal_metadata_), 0, ~0u, " + "::$proto_ns$::internal::FieldMetadata::kSpecial, reinterpret_cast(::$proto_ns$::internal::$1$)},\n", + serializer); return num_field_metadata; } void MessageGenerator::GenerateFieldDefaultInstances(io::Printer* printer) { // Construct the default instances for all fields that need one. - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(descriptor_->field(i)) - .GenerateDefaultInstanceAllocator(printer); + for (auto field : FieldRange(descriptor_)) { + field_generators_.get(field).GenerateDefaultInstanceAllocator(printer); } } -void MessageGenerator:: -GenerateDefaultInstanceInitializer(io::Printer* printer) { +void MessageGenerator::GenerateDefaultInstanceInitializer( + io::Printer* printer) { + Formatter format(printer, variables_); + // The default instance needs all of its embedded message pointers // cross-linked to other default instances. We can't do this initialization // in the constructor because some other default instances may not have been // constructed yet at that time. // TODO(kenton): Maybe all message fields (even for non-default messages) // should be initialized to point at default instances rather than NULL? - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); + for (auto field : FieldRange(descriptor_)) { + Formatter::SaveState saver(&format); - if (!field->is_repeated() && + if (!field->is_repeated() && !IsLazy(field, options_) && field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && (field->containing_oneof() == NULL || HasDescriptorMethods(descriptor_->file(), options_))) { - string name; + std::string name; if (field->containing_oneof() || field->options().weak()) { name = "_" + classname_ + "_default_instance_."; } else { @@ -1719,201 +1900,232 @@ GenerateDefaultInstanceInitializer(io::Printer* printer) { "_" + classname_ + "_default_instance_._instance.get_mutable()->"; } name += FieldName(field); - printer->Print( - "$ns$::$name$_ = const_cast< $type$*>(\n" - " $type$::internal_default_instance());\n", - // Vars. - "name", name, "type", FieldMessageTypeName(field), "ns", - Namespace(descriptor_)); + format.Set("name", name); + if (IsWeak(field, options_)) { + format( + "$package_ns$::$name$_ = reinterpret_cast(&$1$);\n" + "if ($package_ns$::$name$_ == nullptr) {\n" + " $package_ns$::$name$_ = " + "::$proto_ns$::Empty::internal_default_instance();\n" + "}\n", + QualifiedDefaultInstanceName(field->message_type(), + options_)); // 1 + continue; + } + format( + "$package_ns$::$name$_ = const_cast< $1$*>(\n" + " $1$::internal_default_instance());\n", + FieldMessageTypeName(field, options_)); } else if (field->containing_oneof() && HasDescriptorMethods(descriptor_->file(), options_)) { - field_generators_.get(descriptor_->field(i)) - .GenerateConstructorCode(printer); + field_generators_.get(field).GenerateConstructorCode(printer); } } } -void MessageGenerator:: -GenerateClassMethods(io::Printer* printer) { +void MessageGenerator::GenerateClassMethods(io::Printer* printer) { + Formatter format(printer, variables_); if (IsMapEntryMessage(descriptor_)) { - printer->Print( + format( "$classname$::$classname$() {}\n" - "$classname$::$classname$(::google::protobuf::Arena* arena) : " - "SuperType(arena) {}\n" + "$classname$::$classname$(::$proto_ns$::Arena* arena)\n" + " : SuperType(arena) {}\n" "void $classname$::MergeFrom(const $classname$& other) {\n" " MergeFromInternal(other);\n" - "}\n", - "classname", classname_); + "}\n"); if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print( - "::google::protobuf::Metadata $classname$::GetMetadata() const {\n" - " ::$file_namespace$::protobuf_AssignDescriptorsOnce();\n" - " return ::$file_namespace$::file_level_metadata[$index$];\n" - "}\n" + format( + "::$proto_ns$::Metadata $classname$::GetMetadata() const {\n" + " return GetMetadataStatic();\n" + "}\n"); + format( "void $classname$::MergeFrom(\n" - " const ::google::protobuf::Message& other) {\n" - " ::google::protobuf::Message::MergeFrom(other);\n" + " const ::$proto_ns$::Message& other) {\n" + " ::$proto_ns$::Message::MergeFrom(other);\n" "}\n" - "\n", - "file_namespace", FileLevelNamespace(descriptor_), - "classname", classname_, "index", - SimpleItoa(index_in_file_messages_)); + "\n"); } return; } // TODO(gerbens) Remove this function. With a little bit of cleanup and // refactoring this is superfluous. - printer->Print("void $classname$::InitAsDefaultInstance() {\n", "classname", - classname_); - printer->Indent(); + format("void $classname$::InitAsDefaultInstance() {\n"); + format.Indent(); GenerateDefaultInstanceInitializer(printer); - printer->Outdent(); - printer->Print("}\n"); + format.Outdent(); + format("}\n"); - if (IsAnyMessage(descriptor_)) { - printer->Print( - "void $classname$::PackFrom(const ::google::protobuf::Message& message) {\n" - " _any_metadata_.PackFrom(message);\n" - "}\n" - "\n" - "void $classname$::PackFrom(const ::google::protobuf::Message& message,\n" - " const ::std::string& type_url_prefix) {\n" - " _any_metadata_.PackFrom(message, type_url_prefix);\n" - "}\n" - "\n" - "bool $classname$::UnpackTo(::google::protobuf::Message* message) const {\n" - " return _any_metadata_.UnpackTo(message);\n" - "}\n" - "bool $classname$::ParseAnyTypeUrl(const string& type_url,\n" - " string* full_type_name) {\n" - " return ::google::protobuf::internal::ParseAnyTypeUrl(type_url,\n" - " full_type_name);\n" - "}\n" - "\n", - "classname", classname_); + if (IsAnyMessage(descriptor_, options_)) { + if (HasDescriptorMethods(descriptor_->file(), options_)) { + format( + "void $classname$::PackFrom(const ::$proto_ns$::Message& message) {\n" + " _any_metadata_.PackFrom(message);\n" + "}\n" + "\n" + "void $classname$::PackFrom(const ::$proto_ns$::Message& message,\n" + " const std::string& type_url_prefix) {\n" + " _any_metadata_.PackFrom(message, type_url_prefix);\n" + "}\n" + "\n" + "bool $classname$::UnpackTo(::$proto_ns$::Message* message) const {\n" + " return _any_metadata_.UnpackTo(message);\n" + "}\n" + "bool $classname$::GetAnyFieldDescriptors(\n" + " const ::$proto_ns$::Message& message,\n" + " const ::$proto_ns$::FieldDescriptor** type_url_field,\n" + " const ::$proto_ns$::FieldDescriptor** value_field) {\n" + " return ::$proto_ns$::internal::GetAnyFieldDescriptors(\n" + " message, type_url_field, value_field);\n" + "}\n"); + } + format( + "bool $classname$::ParseAnyTypeUrl(const string& type_url,\n" + " std::string* full_type_name) {\n" + " return ::$proto_ns$::internal::ParseAnyTypeUrl(type_url,\n" + " full_type_name);\n" + "}\n" + "\n"); + } + + format( + "class $classname$::HasBitSetters {\n" + " public:\n"); + format.Indent(); + if (HasFieldPresence(descriptor_->file()) && HasBitsSize() != 0) { + format( + "using HasBits = decltype(std::declval<$classname$>()._has_bits_);\n"); + } + for (auto field : FieldRange(descriptor_)) { + field_generators_.get(field).GenerateInternalAccessorDeclarations(printer); + if (HasFieldPresence(descriptor_->file()) && !field->is_repeated() && + !field->options().weak() && !field->containing_oneof()) { + int has_bit_index = has_bit_indices_[field->index()]; + GOOGLE_CHECK_GE(has_bit_index, 0); + format( + "static void set_has_$1$(HasBits* has_bits) {\n" + " (*has_bits)[$2$] |= $3$u;\n" + "}\n", + FieldName(field), has_bit_index / 32, (1u << (has_bit_index % 32))); + } + } + format.Outdent(); + format("};\n\n"); + for (auto field : FieldRange(descriptor_)) { + field_generators_.get(field).GenerateInternalAccessorDefinitions(printer); } // Generate non-inline field definitions. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - field_generators_.get(field) - .GenerateNonInlineAccessorDefinitions(printer); + for (auto field : FieldRange(descriptor_)) { + field_generators_.get(field).GenerateNonInlineAccessorDefinitions(printer); if (IsCrossFileMaybeMap(field)) { - std::map vars; + Formatter::SaveState saver(&format); + std::map vars; SetCommonFieldVariables(field, &vars, options_); if (field->containing_oneof()) { SetCommonOneofFieldVariables(field, &vars); } - GenerateFieldClear(field, vars, false, printer); + format.AddMap(vars); + GenerateFieldClear(field, false, format); } } // Generate field number constants. - printer->Print("#if !defined(_MSC_VER) || _MSC_VER >= 1900\n"); - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor *field = descriptor_->field(i); - printer->Print( - "const int $classname$::$constant_name$;\n", - "classname", ClassName(FieldScope(field), false), - "constant_name", FieldConstantName(field)); + format("#if !defined(_MSC_VER) || _MSC_VER >= 1900\n"); + for (auto field : FieldRange(descriptor_)) { + format("const int $classname$::$1$;\n", FieldConstantName(field)); } - printer->Print( - "#endif // !defined(_MSC_VER) || _MSC_VER >= 1900\n" - "\n"); + format( + "#endif // !defined(_MSC_VER) || _MSC_VER >= 1900\n" + "\n"); GenerateStructors(printer); - printer->Print("\n"); + format("\n"); if (descriptor_->oneof_decl_count() > 0) { GenerateOneofClear(printer); - printer->Print("\n"); + format("\n"); } if (HasGeneratedMethods(descriptor_->file(), options_)) { GenerateClear(printer); - printer->Print("\n"); + format("\n"); GenerateMergeFromCodedStream(printer); - printer->Print("\n"); + format("\n"); GenerateSerializeWithCachedSizes(printer); - printer->Print("\n"); + format("\n"); if (HasFastArraySerialization(descriptor_->file(), options_)) { GenerateSerializeWithCachedSizesToArray(printer); - printer->Print("\n"); + format("\n"); } GenerateByteSize(printer); - printer->Print("\n"); + format("\n"); GenerateMergeFrom(printer); - printer->Print("\n"); + format("\n"); GenerateCopyFrom(printer); - printer->Print("\n"); + format("\n"); GenerateIsInitialized(printer); - printer->Print("\n"); + format("\n"); } GenerateSwap(printer); - printer->Print("\n"); + format("\n"); if (options_.table_driven_serialization) { - printer->Print( + format( "const void* $classname$::InternalGetTable() const {\n" - " return ::$file_namespace$::TableStruct::serialization_table + " - "$index$;\n" + " return ::$tablename$::serialization_table + $1$;\n" "}\n" "\n", - "classname", classname_, "index", SimpleItoa(index_in_file_messages_), - "file_namespace", FileLevelNamespace(descriptor_)); + index_in_file_messages_); } if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print( - "::google::protobuf::Metadata $classname$::GetMetadata() const {\n" - " $file_namespace$::protobuf_AssignDescriptorsOnce();\n" - " return ::" - "$file_namespace$::file_level_metadata[kIndexInFileMessages];\n" + format( + "::$proto_ns$::Metadata $classname$::GetMetadata() const {\n" + " return GetMetadataStatic();\n" "}\n" - "\n", - "classname", classname_, "file_namespace", - FileLevelNamespace(descriptor_)); + "\n"); } else { - printer->Print( - "::std::string $classname$::GetTypeName() const {\n" - " return \"$type_name$\";\n" - "}\n" - "\n", - "classname", classname_, - "type_name", descriptor_->full_name()); + format( + "std::string $classname$::GetTypeName() const {\n" + " return \"$full_name$\";\n" + "}\n" + "\n"); } } size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) { + Formatter format(printer, variables_); + if (!table_driven_) { return 0; } // Field "0" is special: We use it in our switch statement of processing // types to handle the successful end tag case. - printer->Print("{0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0},\n"); + format("{0, 0, 0, ::$proto_ns$::internal::kInvalidMask, 0, 0},\n"); int last_field_number = 1; std::vector ordered_fields = SortFieldsByNumber(descriptor_); - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = ordered_fields[i]; + for (auto field : ordered_fields) { + Formatter::SaveState saver(&format); GOOGLE_CHECK_GE(field->number(), last_field_number); for (; last_field_number < field->number(); last_field_number++) { - printer->Print( - "{ 0, 0, ::google::protobuf::internal::kInvalidMask,\n" - " ::google::protobuf::internal::kInvalidMask, 0, 0 },\n"); + format( + "{ 0, 0, ::$proto_ns$::internal::kInvalidMask,\n" + " ::$proto_ns$::internal::kInvalidMask, 0, 0 },\n"); } last_field_number++; @@ -1929,30 +2141,39 @@ size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) { processing_type = static_cast(field->type()); const FieldGenerator& generator = field_generators_.get(field); if (field->type() == FieldDescriptor::TYPE_STRING) { - switch (EffectiveStringCType(field)) { + switch (EffectiveStringCType(field, options_)) { case FieldOptions::STRING: - default: { if (generator.IsInlined()) { processing_type = internal::TYPE_STRING_INLINED; break; } break; - } + case FieldOptions::CORD: + processing_type = internal::TYPE_STRING_CORD; + break; + case FieldOptions::STRING_PIECE: + processing_type = internal::TYPE_STRING_STRING_PIECE; + break; } } else if (field->type() == FieldDescriptor::TYPE_BYTES) { - switch (EffectiveStringCType(field)) { + switch (EffectiveStringCType(field, options_)) { case FieldOptions::STRING: - default: if (generator.IsInlined()) { processing_type = internal::TYPE_BYTES_INLINED; break; } break; + case FieldOptions::CORD: + processing_type = internal::TYPE_BYTES_CORD; + break; + case FieldOptions::STRING_PIECE: + processing_type = internal::TYPE_BYTES_STRING_PIECE; + break; } } processing_type |= static_cast( - field->is_repeated() ? internal::kRepeatedMask : 0); + field->is_repeated() ? internal::kRepeatedMask : 0); processing_type |= static_cast( field->containing_oneof() ? internal::kOneofMask : 0); @@ -1961,35 +2182,37 @@ size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) { } const unsigned char tag_size = - WireFormat::TagSize(field->number(), field->type()); + WireFormat::TagSize(field->number(), field->type()); - std::map vars; - vars["classname"] = QualifiedClassName(descriptor_); + std::map vars; if (field->containing_oneof() != NULL) { vars["name"] = field->containing_oneof()->name(); - vars["presence"] = SimpleItoa(field->containing_oneof()->index()); + vars["presence"] = StrCat(field->containing_oneof()->index()); } else { vars["name"] = FieldName(field); - vars["presence"] = SimpleItoa(has_bit_indices_[field->index()]); + vars["presence"] = StrCat(has_bit_indices_[field->index()]); } - vars["nwtype"] = SimpleItoa(normal_wiretype); - vars["pwtype"] = SimpleItoa(packed_wiretype); - vars["ptype"] = SimpleItoa(processing_type); - vars["tag_size"] = SimpleItoa(tag_size); + vars["nwtype"] = StrCat(normal_wiretype); + vars["pwtype"] = StrCat(packed_wiretype); + vars["ptype"] = StrCat(processing_type); + vars["tag_size"] = StrCat(tag_size); - printer->Print(vars, - "{\n" - " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n" - " $classname$, $name$_),\n" - " static_cast<::google::protobuf::uint32>($presence$),\n" - " $nwtype$, $pwtype$, $ptype$, $tag_size$\n" - "},\n"); + format.AddMap(vars); + + format( + "{\n" + " PROTOBUF_FIELD_OFFSET($classtype$, $name$_),\n" + " static_cast<$uint32$>($presence$),\n" + " $nwtype$, $pwtype$, $ptype$, $tag_size$\n" + "},\n"); } return last_field_number; } size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) { + Formatter format(printer, variables_); + if (!table_driven_) { return 0; } @@ -1997,74 +2220,79 @@ size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) { std::vector ordered_fields = SortFieldsByNumber(descriptor_); - printer->Print("::google::protobuf::internal::AuxillaryParseTableField(),\n"); + format("::$proto_ns$::internal::AuxillaryParseTableField(),\n"); int last_field_number = 1; - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = ordered_fields[i]; + for (auto field : ordered_fields) { + Formatter::SaveState saver(&format); GOOGLE_CHECK_GE(field->number(), last_field_number); for (; last_field_number < field->number(); last_field_number++) { - printer->Print("::google::protobuf::internal::AuxillaryParseTableField(),\n"); + format("::$proto_ns$::internal::AuxillaryParseTableField(),\n"); } - std::map vars; + std::map vars; SetCommonFieldVariables(field, &vars, options_); + format.AddMap(vars); switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_ENUM: - vars["type"] = ClassName(field->enum_type(), true); - printer->Print( - vars, - "{::google::protobuf::internal::AuxillaryParseTableField::enum_aux{" - "$type$_IsValid}},\n"); + if (HasPreservingUnknownEnumSemantics(field)) { + format( + "{::$proto_ns$::internal::AuxillaryParseTableField::enum_aux{" + "nullptr}},\n"); + } else { + format( + "{::$proto_ns$::internal::AuxillaryParseTableField::enum_aux{" + "$1$_IsValid}},\n", + ClassName(field->enum_type(), true)); + } last_field_number++; break; case FieldDescriptor::CPPTYPE_MESSAGE: { if (field->is_map()) { - vars["classname"] = QualifiedClassName(field->message_type()); - printer->Print(vars, - "{::google::protobuf::internal::AuxillaryParseTableField::map_" - "aux{&::google::protobuf::internal::ParseMap<$classname$>}},\n"); + format( + "{::$proto_ns$::internal::AuxillaryParseTableField::map_" + "aux{&::$proto_ns$::internal::ParseMap<$1$>}},\n", + QualifiedClassName(field->message_type(), options_)); last_field_number++; break; - } else { - vars["classname"] = ClassName(field->message_type(), false); } - vars["ns"] = Namespace(field->message_type()); - vars["type"] = FieldMessageTypeName(field); - vars["file_namespace"] = - FileLevelNamespace(field->message_type()); + format.Set("field_classname", ClassName(field->message_type(), false)); + format.Set("default_instance", QualifiedDefaultInstanceName( + field->message_type(), options_)); - printer->Print( - vars, - "{::google::protobuf::internal::AuxillaryParseTableField::message_aux{\n" - " &$ns$::_$classname$_default_instance_}},\n"); + format( + "{::$proto_ns$::internal::AuxillaryParseTableField::message_aux{\n" + " &$default_instance$}},\n"); last_field_number++; break; } - case FieldDescriptor::CPPTYPE_STRING: - switch (EffectiveStringCType(field)) { + case FieldDescriptor::CPPTYPE_STRING: { + std::string default_val; + switch (EffectiveStringCType(field, options_)) { case FieldOptions::STRING: - vars["default"] = - field->default_value_string().empty() - ? "&::google::protobuf::internal::fixed_address_empty_string" - : "&" + Namespace(field) + " ::" + classname_ + - "::" + MakeDefaultName(field); + default_val = field->default_value_string().empty() + ? "&::" + variables_["proto_ns"] + + "::internal::fixed_address_empty_string" + : "&" + + QualifiedClassName(descriptor_, options_) + + "::" + MakeDefaultName(field); break; case FieldOptions::CORD: case FieldOptions::STRING_PIECE: - vars["default"] = + default_val = "\"" + CEscape(field->default_value_string()) + "\""; break; } - vars["full_name"] = field->full_name(); - printer->Print(vars, - "{::google::protobuf::internal::AuxillaryParseTableField::string_aux{\n" - " $default$,\n" - " \"$full_name$\"\n" - "}},\n"); + format( + "{::$proto_ns$::internal::AuxillaryParseTableField::string_aux{\n" + " $1$,\n" + " \"$2$\"\n" + "}},\n", + default_val, field->full_name()); last_field_number++; break; + } default: break; } @@ -2075,171 +2303,145 @@ size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) { std::pair MessageGenerator::GenerateOffsets( io::Printer* printer) { - std::map variables; - string full_classname = QualifiedClassName(descriptor_); - variables["classname"] = full_classname; + Formatter format(printer, variables_); if (HasFieldPresence(descriptor_->file()) || IsMapEntryMessage(descriptor_)) { - printer->Print( - variables, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, " - "_has_bits_),\n"); + format("PROTOBUF_FIELD_OFFSET($classtype$, _has_bits_),\n"); } else { - printer->Print("~0u, // no _has_bits_\n"); + format("~0u, // no _has_bits_\n"); } - printer->Print(variables, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, " - "_internal_metadata_),\n"); + format("PROTOBUF_FIELD_OFFSET($classtype$, _internal_metadata_),\n"); if (descriptor_->extension_range_count() > 0) { - printer->Print( - variables, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, " - "_extensions_),\n"); + format("PROTOBUF_FIELD_OFFSET($classtype$, _extensions_),\n"); } else { - printer->Print("~0u, // no _extensions_\n"); + format("~0u, // no _extensions_\n"); } if (descriptor_->oneof_decl_count() > 0) { - printer->Print(variables, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(" - "$classname$, _oneof_case_[0]),\n"); + format("PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_[0]),\n"); } else { - printer->Print("~0u, // no _oneof_case_\n"); + format("~0u, // no _oneof_case_\n"); } if (num_weak_fields_ > 0) { - printer->Print(variables, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$," - " _weak_field_map_),\n"); + format("PROTOBUF_FIELD_OFFSET($classtype$, _weak_field_map_),\n"); } else { - printer->Print("~0u, // no _weak_field_map_\n"); + format("~0u, // no _weak_field_map_\n"); } const int kNumGenericOffsets = 5; // the number of fixed offsets above - const size_t offsets = kNumGenericOffsets + - descriptor_->field_count() + + const size_t offsets = kNumGenericOffsets + descriptor_->field_count() + descriptor_->oneof_decl_count(); size_t entries = offsets; - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); + for (auto field : FieldRange(descriptor_)) { if (field->containing_oneof() || field->options().weak()) { - printer->Print("offsetof($classname$DefaultTypeInternal, $name$_)", - "classname", full_classname, "name", FieldName(field)); + format("offsetof($classtype$DefaultTypeInternal, $1$_)", + FieldName(field)); } else { - printer->Print( - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, $name$_)", - "classname", full_classname, "name", FieldName(field)); + format("PROTOBUF_FIELD_OFFSET($classtype$, $1$_)", FieldName(field)); } uint32 tag = field_generators_.get(field).CalculateFieldTag(); if (tag != 0) { - printer->Print(" | $tag$", "tag", SimpleItoa(tag)); + format(" | $1$", tag); } - printer->Print(",\n"); + format(",\n"); } - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - const OneofDescriptor* oneof = descriptor_->oneof_decl(i); - printer->Print( - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, $name$_),\n", - "classname", full_classname, "name", oneof->name()); + for (auto oneof : OneOfRange(descriptor_)) { + format("PROTOBUF_FIELD_OFFSET($classtype$, $1$_),\n", oneof->name()); } if (IsMapEntryMessage(descriptor_)) { entries += 2; - printer->Print( + format( "0,\n" "1,\n"); } else if (HasFieldPresence(descriptor_->file())) { entries += has_bit_indices_.size(); for (int i = 0; i < has_bit_indices_.size(); i++) { - const string index = has_bit_indices_[i] >= 0 ? - SimpleItoa(has_bit_indices_[i]) : "~0u"; - printer->Print("$index$,\n", "index", index); + const std::string index = + has_bit_indices_[i] >= 0 ? StrCat(has_bit_indices_[i]) : "~0u"; + format("$1$,\n", index); } } return std::make_pair(entries, offsets); } -void MessageGenerator:: -GenerateSharedConstructorCode(io::Printer* printer) { - printer->Print( - "void $classname$::SharedCtor() {\n", - "classname", classname_); - printer->Indent(); +void MessageGenerator::GenerateSharedConstructorCode(io::Printer* printer) { + Formatter format(printer, variables_); + + format("void $classname$::SharedCtor() {\n"); + if (scc_analyzer_->GetSCCAnalysis(scc_analyzer_->GetSCC(descriptor_)) + .constructor_requires_initialization) { + format(" ::$proto_ns$::internal::InitSCC(&$scc_info$.base);\n"); + } + + format.Indent(); std::vector processed(optimized_order_.size(), false); GenerateConstructorBody(printer, processed, false); - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "clear_has_$oneof_name$();\n", - "oneof_name", descriptor_->oneof_decl(i)->name()); + for (auto oneof : OneOfRange(descriptor_)) { + format("clear_has_$1$();\n", oneof->name()); } - printer->Outdent(); - printer->Print("}\n\n"); + format.Outdent(); + format("}\n\n"); } -void MessageGenerator:: -GenerateSharedDestructorCode(io::Printer* printer) { - printer->Print( - "void $classname$::SharedDtor() {\n", - "classname", classname_); - printer->Indent(); +void MessageGenerator::GenerateSharedDestructorCode(io::Printer* printer) { + Formatter format(printer, variables_); + + format("void $classname$::SharedDtor() {\n"); + format.Indent(); if (SupportsArenas(descriptor_)) { - printer->Print( - "GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);\n"); + format("$DCHK$(GetArenaNoVirtual() == nullptr);\n"); } // Write the destructors for each field except oneof members. // optimized_order_ does not contain oneof fields. - for (int i = 0; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; + for (auto field : optimized_order_) { field_generators_.get(field).GenerateDestructorCode(printer); } // Generate code to destruct oneofs. Clearing should do the work. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "if (has_$oneof_name$()) {\n" - " clear_$oneof_name$();\n" + for (auto oneof : OneOfRange(descriptor_)) { + format( + "if (has_$1$()) {\n" + " clear_$1$();\n" "}\n", - "oneof_name", descriptor_->oneof_decl(i)->name()); + oneof->name()); } if (num_weak_fields_) { - printer->Print("_weak_field_map_.ClearAll();\n"); + format("_weak_field_map_.ClearAll();\n"); } - printer->Outdent(); - printer->Print( - "}\n" - "\n"); + format.Outdent(); + format( + "}\n" + "\n"); } -void MessageGenerator:: -GenerateArenaDestructorCode(io::Printer* printer) { +void MessageGenerator::GenerateArenaDestructorCode(io::Printer* printer) { + Formatter format(printer, variables_); + // Generate the ArenaDtor() method. Track whether any fields actually produced // code that needs to be called. - printer->Print( - "void $classname$::ArenaDtor(void* object) {\n", - "classname", classname_); - printer->Indent(); + format("void $classname$::ArenaDtor(void* object) {\n"); + format.Indent(); // This code is placed inside a static method, rather than an ordinary one, // since that simplifies Arena's destructor list (ordinary function pointers // rather than member function pointers). _this is the object being // destructed. - printer->Print( + format( "$classname$* _this = reinterpret_cast< $classname$* >(object);\n" // avoid an "unused variable" warning in case no fields have dtor code. - "(void)_this;\n", - "classname", classname_); + "(void)_this;\n"); bool need_registration = false; // Process non-oneof fields first. - for (int i = 0; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; - if (field_generators_.get(field) - .GenerateArenaDestructorCode(printer)) { + for (auto field : optimized_order_) { + if (field_generators_.get(field).GenerateArenaDestructorCode(printer)) { need_registration = true; } } @@ -2248,13 +2450,9 @@ GenerateArenaDestructorCode(io::Printer* printer) { // // Note: As of 10/5/2016, GenerateArenaDestructorCode does not emit anything // and returns false for oneof fields. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - const OneofDescriptor* oneof = descriptor_->oneof_decl(i); - - for (int j = 0; j < oneof->field_count(); j++) { - const FieldDescriptor* field = oneof->field(j); - if (field_generators_.get(field) - .GenerateArenaDestructorCode(printer)) { + for (auto oneof : OneOfRange(descriptor_)) { + for (auto field : FieldRange(oneof)) { + if (field_generators_.get(field).GenerateArenaDestructorCode(printer)) { need_registration = true; } } @@ -2262,42 +2460,40 @@ GenerateArenaDestructorCode(io::Printer* printer) { if (num_weak_fields_) { // _this is the object being destructed (we are inside a static method // here). - printer->Print("_this->_weak_field_map_.ClearAll();\n"); + format("_this->_weak_field_map_.ClearAll();\n"); need_registration = true; } - printer->Outdent(); - printer->Print( - "}\n"); + format.Outdent(); + format("}\n"); if (need_registration) { - printer->Print( - "inline void $classname$::RegisterArenaDtor(::google::protobuf::Arena* arena) {\n" - " if (arena != NULL) {\n" + format( + "inline void $classname$::RegisterArenaDtor(::$proto_ns$::Arena* " + "arena) {\n" + " if (arena != nullptr) {\n" " arena->OwnCustomDestructor(this, &$classname$::ArenaDtor);\n" " }\n" - "}\n", - "classname", classname_); + "}\n"); } else { - printer->Print( - "void $classname$::RegisterArenaDtor(::google::protobuf::Arena* arena) {\n" - "}\n", - "classname", classname_); + format( + "void $classname$::RegisterArenaDtor(::$proto_ns$::Arena*) {\n" + "}\n"); } } void MessageGenerator::GenerateConstructorBody(io::Printer* printer, std::vector processed, bool copy_constructor) const { + Formatter format(printer, variables_); const FieldDescriptor* last_start = NULL; // RunMap maps from fields that start each run to the number of fields in that // run. This is optimized for the common case that there are very few runs in // a message and that most of the eligible fields appear together. - typedef hash_map RunMap; + typedef std::unordered_map RunMap; RunMap runs; - for (int i = 0; i < optimized_order_.size(); ++i) { - const FieldDescriptor* field = optimized_order_[i]; + for (auto field : optimized_order_) { if ((copy_constructor && IsPOD(field)) || (!copy_constructor && CanConstructByZeroing(field, options_))) { if (last_start == NULL) { @@ -2310,7 +2506,7 @@ void MessageGenerator::GenerateConstructorBody(io::Printer* printer, } } - string pod_template; + std::string pod_template; if (copy_constructor) { pod_template = "::memcpy(&$first$_, &from.$first$_,\n" @@ -2336,13 +2532,14 @@ void MessageGenerator::GenerateConstructorBody(io::Printer* printer, if (it != runs.end() && it->second > 1) { // Use a memset, then skip run_length fields. const size_t run_length = it->second; - const string first_field_name = FieldName(field); - const string last_field_name = + const std::string first_field_name = FieldName(field); + const std::string last_field_name = FieldName(optimized_order_[i + run_length - 1]); - printer->Print(pod_template.c_str(), - "first", first_field_name, - "last", last_field_name); + format.Set("first", first_field_name); + format.Set("last", last_field_name); + + format(pod_template.c_str()); i += run_length - 1; // ++i at the top of the loop. @@ -2356,11 +2553,12 @@ void MessageGenerator::GenerateConstructorBody(io::Printer* printer, } } -void MessageGenerator:: -GenerateStructors(io::Printer* printer) { - string superclass; +void MessageGenerator::GenerateStructors(io::Printer* printer) { + Formatter format(printer, variables_); + + std::string superclass; superclass = SuperClassName(descriptor_, options_); - string initializer_with_arena = superclass + "()"; + std::string initializer_with_arena = superclass + "()"; if (descriptor_->extension_range_count() > 0) { initializer_with_arena += ",\n _extensions_(arena)"; @@ -2369,58 +2567,51 @@ GenerateStructors(io::Printer* printer) { initializer_with_arena += ",\n _internal_metadata_(arena)"; // Initialize member variables with arena constructor. - for (int i = 0; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; - + for (auto field : optimized_order_) { bool has_arena_constructor = field->is_repeated(); + if (field->containing_oneof() == NULL && + (IsLazy(field, options_) || IsStringPiece(field, options_))) { + has_arena_constructor = true; + } if (has_arena_constructor) { - initializer_with_arena += string(",\n ") + - FieldName(field) + string("_(arena)"); + initializer_with_arena += + std::string(",\n ") + FieldName(field) + std::string("_(arena)"); } } - if (IsAnyMessage(descriptor_)) { + if (IsAnyMessage(descriptor_, options_)) { initializer_with_arena += ",\n _any_metadata_(&type_url_, &value_)"; } if (num_weak_fields_ > 0) { initializer_with_arena += ", _weak_field_map_(arena)"; } - string initializer_null = superclass + "(), _internal_metadata_(NULL)"; - if (IsAnyMessage(descriptor_)) { + std::string initializer_null = + superclass + "(), _internal_metadata_(nullptr)"; + if (IsAnyMessage(descriptor_, options_)) { initializer_null += ", _any_metadata_(&type_url_, &value_)"; } if (num_weak_fields_ > 0) { initializer_null += ", _weak_field_map_(nullptr)"; } - printer->Print( + format( "$classname$::$classname$()\n" - " : $initializer$ {\n" - " ::google::protobuf::internal::InitSCC(\n" - " &$file_namespace$::scc_info_$scc_name$.base);\n" + " : $1$ {\n" " SharedCtor();\n" " // @@protoc_insertion_point(constructor:$full_name$)\n" "}\n", - "classname", classname_, "full_name", descriptor_->full_name(), - "scc_name", scc_name_, "initializer", initializer_null, "file_namespace", - FileLevelNamespace(descriptor_)); + initializer_null); if (SupportsArenas(descriptor_)) { - printer->Print( - "$classname$::$classname$(::google::protobuf::Arena* arena)\n" - " : $initializer$ {\n" - " " - "::google::protobuf::internal::InitSCC(&$file_namespace$::scc_info_$scc_name$." - "base);\n" + format( + "$classname$::$classname$(::$proto_ns$::Arena* arena)\n" + " : $1$ {\n" " SharedCtor();\n" " RegisterArenaDtor(arena);\n" " // @@protoc_insertion_point(arena_constructor:$full_name$)\n" "}\n", - "initializer", initializer_with_arena, "classname", classname_, - "superclass", superclass, "full_name", descriptor_->full_name(), - "scc_name", scc_name_, "file_namespace", - FileLevelNamespace(descriptor_)); + initializer_with_arena); } // Generate the copy constructor. @@ -2429,117 +2620,98 @@ GenerateStructors(io::Printer* printer) { // one-liner copy constructor that delegates to MergeFrom. This saves some // code size and also cuts down on the complexity of implicit weak fields. // We might eventually want to do this for all lite protos. - printer->Print( - "$classname$::$classname$(const $classname$& from)\n" - " : $classname$() {\n" - " MergeFrom(from);\n" - "}\n", - "classname", classname_); + format( + "$classname$::$classname$(const $classname$& from)\n" + " : $classname$() {\n" + " MergeFrom(from);\n" + "}\n"); } else { - printer->Print( - "$classname$::$classname$(const $classname$& from)\n" - " : $superclass$()", - "classname", classname_, - "superclass", superclass, - "full_name", descriptor_->full_name()); - printer->Indent(); - printer->Indent(); - printer->Indent(); - - printer->Print( - ",\n_internal_metadata_(NULL)"); + format( + "$classname$::$classname$(const $classname$& from)\n" + " : $superclass$()"); + format.Indent(); + format.Indent(); + format.Indent(); + format(",\n_internal_metadata_(nullptr)"); if (HasFieldPresence(descriptor_->file())) { - printer->Print(",\n_has_bits_(from._has_bits_)"); + if (!IsProto2MessageSet(descriptor_, options_)) { + format(",\n_has_bits_(from._has_bits_)"); + } } std::vector processed(optimized_order_.size(), false); - for (int i = 0; i < optimized_order_.size(); ++i) { - const FieldDescriptor* field = optimized_order_[i]; - - if (!(field->is_repeated() && !(field->is_map())) - ) { + for (int i = 0; i < optimized_order_.size(); i++) { + auto field = optimized_order_[i]; + if (!(field->is_repeated() && !(field->is_map())) && + !IsCord(field, options_)) { continue; } processed[i] = true; - printer->Print(",\n$name$_(from.$name$_)", - "name", FieldName(field)); + format(",\n$1$_(from.$1$_)", FieldName(field)); } - if (IsAnyMessage(descriptor_)) { - printer->Print(",\n_any_metadata_(&type_url_, &value_)"); + if (IsAnyMessage(descriptor_, options_)) { + format(",\n_any_metadata_(&type_url_, &value_)"); } if (num_weak_fields_ > 0) { - printer->Print(",\n_weak_field_map_(from._weak_field_map_)"); + format(",\n_weak_field_map_(from._weak_field_map_)"); } - printer->Outdent(); - printer->Outdent(); - printer->Print(" {\n"); + format.Outdent(); + format.Outdent(); + format(" {\n"); - printer->Print( - "_internal_metadata_.MergeFrom(from._internal_metadata_);\n"); + format("_internal_metadata_.MergeFrom(from._internal_metadata_);\n"); if (descriptor_->extension_range_count() > 0) { - printer->Print("_extensions_.MergeFrom(from._extensions_);\n"); + format("_extensions_.MergeFrom(from._extensions_);\n"); } GenerateConstructorBody(printer, processed, true); // Copy oneof fields. Oneof field requires oneof case check. - for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) { - printer->Print( - "clear_has_$oneofname$();\n" - "switch (from.$oneofname$_case()) {\n", - "oneofname", descriptor_->oneof_decl(i)->name()); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print( - "case k$field_name$: {\n", - "field_name", UnderscoresToCamelCase(field->name(), true)); - printer->Indent(); + for (auto oneof : OneOfRange(descriptor_)) { + format( + "clear_has_$1$();\n" + "switch (from.$1$_case()) {\n", + oneof->name()); + format.Indent(); + for (auto field : FieldRange(oneof)) { + format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true)); + format.Indent(); field_generators_.get(field).GenerateMergingCode(printer); - printer->Print( - "break;\n"); - printer->Outdent(); - printer->Print( - "}\n"); + format("break;\n"); + format.Outdent(); + format("}\n"); } - printer->Print( - "case $cap_oneof_name$_NOT_SET: {\n" + format( + "case $1$_NOT_SET: {\n" " break;\n" "}\n", - "oneof_index", - SimpleItoa(descriptor_->oneof_decl(i)->index()), - "cap_oneof_name", - ToUpper(descriptor_->oneof_decl(i)->name())); - printer->Outdent(); - printer->Print( - "}\n"); + ToUpper(oneof->name())); + format.Outdent(); + format("}\n"); } - printer->Outdent(); - printer->Print( - " // @@protoc_insertion_point(copy_constructor:$full_name$)\n" - "}\n" - "\n", - "full_name", descriptor_->full_name()); + format.Outdent(); + format( + " // @@protoc_insertion_point(copy_constructor:$full_name$)\n" + "}\n" + "\n"); } // Generate the shared constructor code. GenerateSharedConstructorCode(printer); // Generate the destructor. - printer->Print( - "$classname$::~$classname$() {\n" - " // @@protoc_insertion_point(destructor:$full_name$)\n" - " SharedDtor();\n" - "}\n" - "\n", - "classname", classname_, - "full_name", descriptor_->full_name()); + format( + "$classname$::~$classname$() {\n" + " // @@protoc_insertion_point(destructor:$full_name$)\n" + " SharedDtor();\n" + "}\n" + "\n"); // Generate the shared destructor code. GenerateSharedDestructorCode(printer); @@ -2550,90 +2722,45 @@ GenerateStructors(io::Printer* printer) { } // Generate SetCachedSize. - printer->Print( + format( "void $classname$::SetCachedSize(int size) const {\n" " _cached_size_.Set(size);\n" - "}\n", - "classname", classname_); + "}\n"); - // Only generate this member if it's not disabled. - if (HasDescriptorMethods(descriptor_->file(), options_) && - !descriptor_->options().no_standard_descriptor_accessor()) { - printer->Print( - "const ::google::protobuf::Descriptor* $classname$::descriptor() {\n" - " ::$file_namespace$::protobuf_AssignDescriptorsOnce();\n" - " return ::" - "$file_namespace$::file_level_metadata[kIndexInFileMessages]." - "descriptor;\n" - "}\n" - "\n", - "classname", classname_, "file_namespace", - FileLevelNamespace(descriptor_)); - } - - printer->Print( + format( "const $classname$& $classname$::default_instance() {\n" " " - "::google::protobuf::internal::InitSCC(&$file_namespace$::scc_info_$scc_name$.base)" + "::$proto_ns$::internal::InitSCC(&::$scc_info$.base)" ";\n" " return *internal_default_instance();\n" - "}\n\n", - "classname", classname_, "scc_name", scc_name_, "file_namespace", - FileLevelNamespace(descriptor_)); + "}\n\n"); } void MessageGenerator::GenerateSourceInProto2Namespace(io::Printer* printer) { - printer->Print( + Formatter format(printer, variables_); + format( "template<> " - "GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE " - "$classname$* Arena::CreateMaybeMessage< $classname$ >(Arena* arena) {\n" - " return Arena::$create_func$Internal< $classname$ >(arena);\n" + "PROTOBUF_NOINLINE " + "$classtype$* Arena::CreateMaybeMessage< $classtype$ >(Arena* arena) {\n" + " return Arena::$1$Internal< $classtype$ >(arena);\n" "}\n", - "classname", QualifiedClassName(descriptor_), - "create_func", MessageCreateFunction(descriptor_)); + MessageCreateFunction(descriptor_)); } -// Return the number of bits set in n, a non-negative integer. -static int popcnt(uint32 n) { - int result = 0; - while (n != 0) { - result += (n & 1); - n = n / 2; - } - return result; -} - -bool MessageGenerator::MaybeGenerateOptionalFieldCondition( - io::Printer* printer, const FieldDescriptor* field, - int expected_has_bits_index) { - int has_bit_index = has_bit_indices_[field->index()]; - if (!field->options().weak() && - expected_has_bits_index == has_bit_index / 32) { - const string mask = - StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8)); - printer->Print( - "if (cached_has_bits & 0x$mask$u) {\n", - "mask", mask); - return true; - } - return false; -} - -void MessageGenerator:: -GenerateClear(io::Printer* printer) { +void MessageGenerator::GenerateClear(io::Printer* printer) { + Formatter format(printer, variables_); // Performance tuning parameters const int kMaxUnconditionalPrimitiveBytesClear = 4; - printer->Print( + format( "void $classname$::Clear() {\n" - "// @@protoc_insertion_point(message_clear_start:$full_name$)\n", - "classname", classname_, "full_name", descriptor_->full_name()); - printer->Indent(); + "// @@protoc_insertion_point(message_clear_start:$full_name$)\n"); + format.Indent(); - printer->Print( + format( // TODO(jwb): It would be better to avoid emitting this if it is not used, // rather than emitting a workaround for the resulting warning. - "::google::protobuf::uint32 cached_has_bits = 0;\n" + "$uint32$ cached_has_bits = 0;\n" "// Prevent compiler warnings about cached_has_bits being unused\n" "(void) cached_has_bits;\n\n"); @@ -2641,7 +2768,7 @@ GenerateClear(io::Printer* printer) { // Step 1: Extensions if (descriptor_->extension_range_count() > 0) { - printer->Print("_extensions_.Clear();\n"); + format("_extensions_.Clear();\n"); } int unconditional_budget = kMaxUnconditionalPrimitiveBytesClear; @@ -2655,14 +2782,14 @@ GenerateClear(io::Printer* printer) { unconditional_budget -= EstimateAlignmentSize(field); } - std::vector > chunks_frag = CollectFields( + std::vector> chunks_frag = CollectFields( optimized_order_, MatchRepeatedAndHasByteAndZeroInits( &has_bit_indices_, HasFieldPresence(descriptor_->file()))); // Merge next non-zero initializable chunk if it has the same has_byte index // and not meeting unconditional clear condition. - std::vector > chunks; + std::vector> chunks; if (!HasFieldPresence(descriptor_->file())) { // Don't bother with merging without has_bit field. chunks = chunks_frag; @@ -2687,6 +2814,8 @@ GenerateClear(io::Printer* printer) { } } + ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, kColdRatio, + HasFieldPresence(descriptor_->file())); for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) { std::vector& chunk = chunks[chunk_index]; GOOGLE_CHECK(!chunk.empty()); @@ -2703,6 +2832,8 @@ GenerateClear(io::Printer* printer) { continue; } + cold_skipper.OnStartChunk(chunk_index, cached_has_bit_index, "", printer); + // Step 3: Non-repeated fields that can be cleared by memset-to-0, then // non-repeated, non-zero initializable fields. int last_chunk = HasFieldPresence(descriptor_->file()) @@ -2738,12 +2869,11 @@ GenerateClear(io::Printer* printer) { if (cached_has_bit_index != last_chunk / 4) { cached_has_bit_index = last_chunk / 4; - printer->Print("cached_has_bits = _has_bits_[$idx$];\n", "idx", - SimpleItoa(cached_has_bit_index)); + format("cached_has_bits = _has_bits_[$1$];\n", cached_has_bit_index); } - printer->Print("if (cached_has_bits & $mask$u) {\n", "mask", - SimpleItoa(last_chunk_mask)); - printer->Indent(); + format("if (cached_has_bits & 0x$1$u) {\n", + StrCat(strings::Hex(last_chunk_mask, strings::ZERO_PAD_8))); + format.Indent(); } if (memset_run_start != -1) { @@ -2753,14 +2883,14 @@ GenerateClear(io::Printer* printer) { field_generators_.get(chunk[memset_run_start]); generator.GenerateMessageClearingCode(printer); } else { - const string first_field_name = FieldName(chunk[memset_run_start]); - const string last_field_name = FieldName(chunk[memset_run_end]); + const std::string first_field_name = FieldName(chunk[memset_run_start]); + const std::string last_field_name = FieldName(chunk[memset_run_end]); - printer->Print( - "::memset(&$first$_, 0, static_cast(\n" - " reinterpret_cast(&$last$_) -\n" - " reinterpret_cast(&$first$_)) + sizeof($last$_));\n", - "first", first_field_name, "last", last_field_name); + format( + "::memset(&$1$_, 0, static_cast(\n" + " reinterpret_cast(&$2$_) -\n" + " reinterpret_cast(&$1$_)) + sizeof($2$_));\n", + first_field_name, last_field_name); } // Advance last_chunk_start to skip over the fields we zeroed/memset. @@ -2770,7 +2900,6 @@ GenerateClear(io::Printer* printer) { // Go back and emit clears for each of the fields we processed. for (int j = last_chunk_start; j < chunk.size(); j++) { const FieldDescriptor* field = chunk[j]; - const string fieldname = FieldName(field); const FieldGenerator& generator = field_generators_.get(field); // It's faster to just overwrite primitive types, but we should only @@ -2785,121 +2914,101 @@ GenerateClear(io::Printer* printer) { if (should_check_bit && // If no field presence, then always clear strings/messages as well. HasFieldPresence(descriptor_->file())) { - if (!field->options().weak() && - cached_has_bit_index != (has_bit_indices_[field->index()] / 32)) { - cached_has_bit_index = (has_bit_indices_[field->index()] / 32); - printer->Print("cached_has_bits = _has_bits_[$new_index$];\n", - "new_index", SimpleItoa(cached_has_bit_index)); - } - if (!MaybeGenerateOptionalFieldCondition(printer, field, - cached_has_bit_index)) { - printer->Print("if (has_$name$()) {\n", "name", fieldname); - } - printer->Indent(); + PrintPresenceCheck(format, field, has_bit_indices_, printer, + &cached_has_bit_index); have_enclosing_if = true; } generator.GenerateMessageClearingCode(printer); if (have_enclosing_if) { - printer->Outdent(); - printer->Print("}\n"); + format.Outdent(); + format("}\n"); } } if (have_outer_if) { - printer->Outdent(); - printer->Print("}\n"); + format.Outdent(); + format("}\n"); + } + + if (cold_skipper.OnEndChunk(chunk_index, printer)) { + // Reset here as it may have been updated in just closed if statement. + cached_has_bit_index = -1; } } // Step 4: Unions. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "clear_$oneof_name$();\n", - "oneof_name", descriptor_->oneof_decl(i)->name()); + for (auto oneof : OneOfRange(descriptor_)) { + format("clear_$1$();\n", oneof->name()); } if (num_weak_fields_) { - printer->Print("_weak_field_map_.ClearAll();\n"); + format("_weak_field_map_.ClearAll();\n"); } if (HasFieldPresence(descriptor_->file())) { // Step 5: Everything else. - printer->Print("_has_bits_.Clear();\n"); + format("_has_bits_.Clear();\n"); } - printer->Print("_internal_metadata_.Clear();\n"); + format("_internal_metadata_.Clear();\n"); - printer->Outdent(); - printer->Print("}\n"); + format.Outdent(); + format("}\n"); } -void MessageGenerator:: -GenerateOneofClear(io::Printer* printer) { +void MessageGenerator::GenerateOneofClear(io::Printer* printer) { // Generated function clears the active field and union case (e.g. foo_case_). for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - std::map oneof_vars; - oneof_vars["classname"] = classname_; - oneof_vars["oneofname"] = descriptor_->oneof_decl(i)->name(); - oneof_vars["full_name"] = descriptor_->full_name(); - string message_class; + auto oneof = descriptor_->oneof_decl(i); + Formatter format(printer, variables_); + format.Set("oneofname", oneof->name()); - printer->Print(oneof_vars, - "void $classname$::clear_$oneofname$() {\n" - "// @@protoc_insertion_point(one_of_clear_start:" - "$full_name$)\n"); - printer->Indent(); - printer->Print(oneof_vars, - "switch ($oneofname$_case()) {\n"); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print( - "case k$field_name$: {\n", - "field_name", UnderscoresToCamelCase(field->name(), true)); - printer->Indent(); + format( + "void $classname$::clear_$oneofname$() {\n" + "// @@protoc_insertion_point(one_of_clear_start:$full_name$)\n"); + format.Indent(); + format("switch ($oneofname$_case()) {\n"); + format.Indent(); + for (auto field : FieldRange(oneof)) { + format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true)); + format.Indent(); // We clear only allocated objects in oneofs if (!IsStringOrMessage(field)) { - printer->Print( - "// No need to clear\n"); + format("// No need to clear\n"); } else { field_generators_.get(field).GenerateClearingCode(printer); } - printer->Print( - "break;\n"); - printer->Outdent(); - printer->Print( - "}\n"); + format("break;\n"); + format.Outdent(); + format("}\n"); } - printer->Print( - "case $cap_oneof_name$_NOT_SET: {\n" + format( + "case $1$_NOT_SET: {\n" " break;\n" "}\n", - "cap_oneof_name", - ToUpper(descriptor_->oneof_decl(i)->name())); - printer->Outdent(); - printer->Print( + ToUpper(oneof->name())); + format.Outdent(); + format( "}\n" - "_oneof_case_[$oneof_index$] = $cap_oneof_name$_NOT_SET;\n", - "oneof_index", SimpleItoa(i), - "cap_oneof_name", - ToUpper(descriptor_->oneof_decl(i)->name())); - printer->Outdent(); - printer->Print( + "_oneof_case_[$1$] = $2$_NOT_SET;\n", + i, ToUpper(oneof->name())); + format.Outdent(); + format( "}\n" "\n"); } } -void MessageGenerator:: -GenerateSwap(io::Printer* printer) { +void MessageGenerator::GenerateSwap(io::Printer* printer) { + Formatter format(printer, variables_); if (SupportsArenas(descriptor_)) { // Generate the Swap member function. This is a lightweight wrapper around // UnsafeArenaSwap() / MergeFrom() with temporaries, depending on the memory // ownership situation: swapping across arenas or between an arena and a // heap requires copying. - printer->Print( + format( "void $classname$::Swap($classname$* other) {\n" " if (other == this) return;\n" " if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {\n" @@ -2909,33 +3018,42 @@ GenerateSwap(io::Printer* printer) { " temp->MergeFrom(*other);\n" " other->CopyFrom(*this);\n" " InternalSwap(temp);\n" - " if (GetArenaNoVirtual() == NULL) {\n" + " if (GetArenaNoVirtual() == nullptr) {\n" " delete temp;\n" " }\n" " }\n" "}\n" "void $classname$::UnsafeArenaSwap($classname$* other) {\n" " if (other == this) return;\n" - " GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());\n" + " $DCHK$(GetArenaNoVirtual() == other->GetArenaNoVirtual());\n" " InternalSwap(other);\n" - "}\n", - "classname", classname_); + "}\n"); } else { - printer->Print( + format( "void $classname$::Swap($classname$* other) {\n" " if (other == this) return;\n" " InternalSwap(other);\n" - "}\n", - "classname", classname_); + "}\n"); } // Generate the UnsafeArenaSwap member function. - printer->Print("void $classname$::InternalSwap($classname$* other) {\n", - "classname", classname_); - printer->Indent(); - printer->Print("using std::swap;\n"); + format("void $classname$::InternalSwap($classname$* other) {\n"); + format.Indent(); + format("using std::swap;\n"); if (HasGeneratedMethods(descriptor_->file(), options_)) { + if (descriptor_->extension_range_count() > 0) { + format("_extensions_.Swap(&other->_extensions_);\n"); + } + + format("_internal_metadata_.Swap(&other->_internal_metadata_);\n"); + + if (HasFieldPresence(descriptor_->file())) { + for (int i = 0; i < HasBitsSize() / 4; ++i) { + format("swap(_has_bits_[$1$], other->_has_bits_[$1$]);\n", i); + } + } + for (int i = 0; i < optimized_order_.size(); i++) { // optimized_order_ does not contain oneof fields, but the field // generators for these fields do not emit swapping code on their own. @@ -2943,163 +3061,125 @@ GenerateSwap(io::Printer* printer) { field_generators_.get(field).GenerateSwappingCode(printer); } + for (auto oneof : OneOfRange(descriptor_)) { + format("swap($1$_, other->$1$_);\n", oneof->name()); + } + for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "swap($oneof_name$_, other->$oneof_name$_);\n" - "swap(_oneof_case_[$i$], other->_oneof_case_[$i$]);\n", - "oneof_name", descriptor_->oneof_decl(i)->name(), - "i", SimpleItoa(i)); + format("swap(_oneof_case_[$1$], other->_oneof_case_[$1$]);\n", i); } - if (HasFieldPresence(descriptor_->file())) { - for (int i = 0; i < HasBitsSize() / 4; ++i) { - printer->Print("swap(_has_bits_[$i$], other->_has_bits_[$i$]);\n", - "i", SimpleItoa(i)); - } - } - - printer->Print("_internal_metadata_.Swap(&other->_internal_metadata_);\n"); - - if (descriptor_->extension_range_count() > 0) { - printer->Print("_extensions_.Swap(&other->_extensions_);\n"); - } if (num_weak_fields_) { - printer->Print( - "_weak_field_map_.UnsafeArenaSwap(&other->_weak_field_map_);\n"); + format("_weak_field_map_.UnsafeArenaSwap(&other->_weak_field_map_);\n"); } } else { - printer->Print("GetReflection()->Swap(this, other);"); + format("GetReflection()->Swap(this, other);"); } - printer->Outdent(); - printer->Print("}\n"); + format.Outdent(); + format("}\n"); } -void MessageGenerator:: -GenerateMergeFrom(io::Printer* printer) { +void MessageGenerator::GenerateMergeFrom(io::Printer* printer) { + Formatter format(printer, variables_); if (HasDescriptorMethods(descriptor_->file(), options_)) { // Generate the generalized MergeFrom (aka that which takes in the Message // base class as a parameter). - printer->Print( - "void $classname$::MergeFrom(const ::google::protobuf::Message& from) {\n" + format( + "void $classname$::MergeFrom(const ::$proto_ns$::Message& from) {\n" "// @@protoc_insertion_point(generalized_merge_from_start:" "$full_name$)\n" - " GOOGLE_DCHECK_NE(&from, this);\n", - "classname", classname_, "full_name", descriptor_->full_name()); - printer->Indent(); + " $DCHK$_NE(&from, this);\n"); + format.Indent(); // Cast the message to the proper type. If we find that the message is // *not* of the proper type, we can still call Merge via the reflection // system, as the GOOGLE_CHECK above ensured that we have the same descriptor // for each message. - printer->Print( - "const $classname$* source =\n" - " ::google::protobuf::internal::DynamicCastToGenerated(\n" - " &from);\n" - "if (source == NULL) {\n" - "// @@protoc_insertion_point(generalized_merge_from_cast_fail:" - "$full_name$)\n" - " ::google::protobuf::internal::ReflectionOps::Merge(from, this);\n" - "} else {\n" - "// @@protoc_insertion_point(generalized_merge_from_cast_success:" - "$full_name$)\n" - " MergeFrom(*source);\n" - "}\n", - "classname", classname_, "full_name", descriptor_->full_name()); + format( + "const $classname$* source =\n" + " ::$proto_ns$::DynamicCastToGenerated<$classname$>(\n" + " &from);\n" + "if (source == nullptr) {\n" + "// @@protoc_insertion_point(generalized_merge_from_cast_fail:" + "$full_name$)\n" + " ::$proto_ns$::internal::ReflectionOps::Merge(from, this);\n" + "} else {\n" + "// @@protoc_insertion_point(generalized_merge_from_cast_success:" + "$full_name$)\n" + " MergeFrom(*source);\n" + "}\n"); - printer->Outdent(); - printer->Print("}\n\n"); + format.Outdent(); + format("}\n\n"); } else { // Generate CheckTypeAndMergeFrom(). - printer->Print( - "void $classname$::CheckTypeAndMergeFrom(\n" - " const ::google::protobuf::MessageLite& from) {\n" - " MergeFrom(*::google::protobuf::down_cast(&from));\n" - "}\n" - "\n", - "classname", classname_); + format( + "void $classname$::CheckTypeAndMergeFrom(\n" + " const ::$proto_ns$::MessageLite& from) {\n" + " MergeFrom(*::$proto_ns$::internal::DownCast(\n" + " &from));\n" + "}\n" + "\n"); } // Generate the class-specific MergeFrom, which avoids the GOOGLE_CHECK and cast. - printer->Print( + format( "void $classname$::MergeFrom(const $classname$& from) {\n" "// @@protoc_insertion_point(class_specific_merge_from_start:" "$full_name$)\n" - " GOOGLE_DCHECK_NE(&from, this);\n", - "classname", classname_, "full_name", descriptor_->full_name()); - printer->Indent(); + " $DCHK$_NE(&from, this);\n"); + format.Indent(); if (descriptor_->extension_range_count() > 0) { - printer->Print("_extensions_.MergeFrom(from._extensions_);\n"); + format("_extensions_.MergeFrom(from._extensions_);\n"); } - printer->Print( - "_internal_metadata_.MergeFrom(from._internal_metadata_);\n" - "::google::protobuf::uint32 cached_has_bits = 0;\n" - "(void) cached_has_bits;\n\n"); + format( + "_internal_metadata_.MergeFrom(from._internal_metadata_);\n" + "$uint32$ cached_has_bits = 0;\n" + "(void) cached_has_bits;\n\n"); - // cached_has_bit_index maintains that: - // cached_has_bits = from._has_bits_[cached_has_bit_index] - // for cached_has_bit_index >= 0 - int cached_has_bit_index = -1; + if (HasFieldPresence(descriptor_->file())) { + std::vector> chunks = CollectFields( + optimized_order_, MatchRepeatedAndHasByte(&has_bit_indices_, true)); - int last_i = -1; - for (int i = 0; i < optimized_order_.size(); ) { - // Detect infinite loops. - GOOGLE_CHECK_NE(i, last_i); - last_i = i; + ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, + kColdRatio, true); - // Merge Repeated fields. These fields do not require a - // check as we can simply iterate over them. - for (; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; - if (!field->is_repeated()) { - break; + // cached_has_bit_index maintains that: + // cached_has_bits = from._has_bits_[cached_has_bit_index] + // for cached_has_bit_index >= 0 + int cached_has_bit_index = -1; + + for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) { + const std::vector& chunk = chunks[chunk_index]; + GOOGLE_CHECK(!chunk.empty()); + + // Merge Repeated fields. These fields do not require a + // check as we can simply iterate over them. + if (chunk.front()->is_repeated()) { + for (int i = 0; i < chunk.size(); i++) { + const FieldDescriptor* field = chunk[i]; + + const FieldGenerator& generator = field_generators_.get(field); + generator.GenerateMergingCode(printer); + } + continue; } - const FieldGenerator& generator = field_generators_.get(field); - generator.GenerateMergingCode(printer); - } + // Merge Optional and Required fields (after a _has_bit_ check). + cold_skipper.OnStartChunk(chunk_index, cached_has_bit_index, "from.", + printer); - // Merge Optional and Required fields (after a _has_bit_ check). - int last_chunk = -1; - int last_chunk_start = -1; - int last_chunk_end = -1; - uint32 last_chunk_mask = 0; - for (; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; - if (field->is_repeated()) { - break; - } - - // "index" defines where in the _has_bits_ the field appears. - // "i" is our loop counter within optimized_order_. - int index = HasFieldPresence(descriptor_->file()) ? - has_bit_indices_[field->index()] : 0; - int chunk = index / 8; - - if (last_chunk == -1) { - last_chunk = chunk; - last_chunk_start = i; - } else if (chunk != last_chunk) { - // Emit the fields for this chunk so far. - break; - } - - last_chunk_end = i; - last_chunk_mask |= static_cast(1) << (index % 32); - } - - if (last_chunk != -1) { - GOOGLE_DCHECK_NE(-1, last_chunk_start); - GOOGLE_DCHECK_NE(-1, last_chunk_end); - GOOGLE_DCHECK_NE(0, last_chunk_mask); - - const int count = popcnt(last_chunk_mask); - const bool have_outer_if = HasFieldPresence(descriptor_->file()) && - (last_chunk_start != last_chunk_end); + int last_chunk = has_bit_indices_[chunk.front()->index()] / 8; + GOOGLE_DCHECK_NE(-1, last_chunk); + const bool have_outer_if = chunk.size() > 1; if (have_outer_if) { + uint32 last_chunk_mask = GenChunkMask(chunk, has_bit_indices_); + const int count = popcnt(last_chunk_mask); + // Check (up to) 8 has_bits at a time if we have more than one field in // this chunk. Due to field layout ordering, we may check // _has_bits_[last_chunk * 8 / 32] multiple times. @@ -3107,50 +3187,32 @@ GenerateMergeFrom(io::Printer* printer) { GOOGLE_DCHECK_GE(8, count); if (cached_has_bit_index != last_chunk / 4) { - int new_index = last_chunk / 4; - printer->Print("cached_has_bits = from._has_bits_[$new_index$];\n", - "new_index", SimpleItoa(new_index)); - cached_has_bit_index = new_index; + cached_has_bit_index = last_chunk / 4; + format("cached_has_bits = from._has_bits_[$1$];\n", + cached_has_bit_index); } - - printer->Print( - "if (cached_has_bits & $mask$u) {\n", - "mask", SimpleItoa(last_chunk_mask)); - printer->Indent(); + format("if (cached_has_bits & 0x$1$u) {\n", + StrCat(strings::Hex(last_chunk_mask, strings::ZERO_PAD_8))); + format.Indent(); } - // Go back and emit clears for each of the fields we processed. + // Go back and emit merging code for each of the fields we processed. bool deferred_has_bit_changes = false; - for (int j = last_chunk_start; j <= last_chunk_end; j++) { - const FieldDescriptor* field = optimized_order_[j]; + for (const auto field : chunk) { const FieldGenerator& generator = field_generators_.get(field); - bool have_enclosing_if = false; - if (HasFieldPresence(descriptor_->file())) { - // Attempt to use the state of cached_has_bits, if possible. - int has_bit_index = has_bit_indices_[field->index()]; - if (!field->options().weak() && - cached_has_bit_index == has_bit_index / 32) { - const string mask = StrCat( - strings::Hex(1u << (has_bit_index % 32), - strings::ZERO_PAD_8)); + // Attempt to use the state of cached_has_bits, if possible. + int has_bit_index = has_bit_indices_[field->index()]; + if (!field->options().weak() && + cached_has_bit_index == has_bit_index / 32) { + const std::string mask = StrCat( + strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8)); - printer->Print( - "if (cached_has_bits & 0x$mask$u) {\n", "mask", mask); - } else { - printer->Print( - "if (from.has_$name$()) {\n", - "name", FieldName(field)); - } - - printer->Indent(); - have_enclosing_if = true; + format("if (cached_has_bits & 0x$1$u) {\n", mask); } else { - // Merge semantics without true field presence: primitive fields are - // merged only if non-zero (numeric) or non-empty (string). - have_enclosing_if = EmitFieldNonDefaultCondition( - printer, "from.", field); + format("if (from.has_$1$()) {\n", FieldName(field)); } + format.Indent(); if (have_outer_if && IsPOD(field)) { // GenerateCopyConstructorCode for enum and primitive scalar fields @@ -3164,181 +3226,224 @@ GenerateMergeFrom(io::Printer* printer) { generator.GenerateMergingCode(printer); } - if (have_enclosing_if) { - printer->Outdent(); - printer->Print("}\n"); - } + format.Outdent(); + format("}\n"); } if (have_outer_if) { if (deferred_has_bit_changes) { // Flush the has bits for the primitives we deferred. GOOGLE_CHECK_LE(0, cached_has_bit_index); - printer->Print( - "_has_bits_[$index$] |= cached_has_bits;\n", - "index", SimpleItoa(cached_has_bit_index)); + format("_has_bits_[$1$] |= cached_has_bits;\n", cached_has_bit_index); } - printer->Outdent(); - printer->Print("}\n"); + format.Outdent(); + format("}\n"); + } + + if (cold_skipper.OnEndChunk(chunk_index, printer)) { + // Reset here as it may have been updated in just closed if statement. + cached_has_bit_index = -1; + } + } + } else { + // proto3 + for (const auto field : optimized_order_) { + const FieldGenerator& generator = field_generators_.get(field); + // Merge semantics without true field presence: primitive fields are + // merged only if non-zero (numeric) or non-empty (string). + bool have_enclosing_if = + EmitFieldNonDefaultCondition(printer, "from.", field); + + generator.GenerateMergingCode(printer); + + if (have_enclosing_if) { + format.Outdent(); + format("}\n"); } } } // Merge oneof fields. Oneof field requires oneof case check. - for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) { - printer->Print( - "switch (from.$oneofname$_case()) {\n", - "oneofname", descriptor_->oneof_decl(i)->name()); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print( - "case k$field_name$: {\n", - "field_name", UnderscoresToCamelCase(field->name(), true)); - printer->Indent(); + for (auto oneof : OneOfRange(descriptor_)) { + format("switch (from.$1$_case()) {\n", oneof->name()); + format.Indent(); + for (auto field : FieldRange(oneof)) { + format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true)); + format.Indent(); field_generators_.get(field).GenerateMergingCode(printer); - printer->Print( - "break;\n"); - printer->Outdent(); - printer->Print( - "}\n"); + format("break;\n"); + format.Outdent(); + format("}\n"); } - printer->Print( - "case $cap_oneof_name$_NOT_SET: {\n" + format( + "case $1$_NOT_SET: {\n" " break;\n" "}\n", - "cap_oneof_name", - ToUpper(descriptor_->oneof_decl(i)->name())); - printer->Outdent(); - printer->Print( - "}\n"); + ToUpper(oneof->name())); + format.Outdent(); + format("}\n"); } if (num_weak_fields_) { - printer->Print("_weak_field_map_.MergeFrom(from._weak_field_map_);\n"); + format("_weak_field_map_.MergeFrom(from._weak_field_map_);\n"); } - printer->Outdent(); - printer->Print("}\n"); + format.Outdent(); + format("}\n"); } -void MessageGenerator:: -GenerateCopyFrom(io::Printer* printer) { +void MessageGenerator::GenerateCopyFrom(io::Printer* printer) { + Formatter format(printer, variables_); if (HasDescriptorMethods(descriptor_->file(), options_)) { // Generate the generalized CopyFrom (aka that which takes in the Message // base class as a parameter). - printer->Print( - "void $classname$::CopyFrom(const ::google::protobuf::Message& from) {\n" + format( + "void $classname$::CopyFrom(const ::$proto_ns$::Message& from) {\n" "// @@protoc_insertion_point(generalized_copy_from_start:" - "$full_name$)\n", - "classname", classname_, "full_name", descriptor_->full_name()); - printer->Indent(); + "$full_name$)\n"); + format.Indent(); - printer->Print( - "if (&from == this) return;\n" - "Clear();\n" - "MergeFrom(from);\n"); + format("if (&from == this) return;\n"); - printer->Outdent(); - printer->Print("}\n\n"); + if (!options_.opensource_runtime) { + // This check is disabled in the opensource release because we're + // concerned that many users do not define NDEBUG in their release + // builds. + format( + "#ifndef NDEBUG\n" + "size_t from_size = from.ByteSizeLong();\n" + "#endif\n" + "Clear();\n" + "#ifndef NDEBUG\n" + "$CHK$_EQ(from_size, from.ByteSizeLong())\n" + " << \"Source of CopyFrom changed when clearing target. Either \"\n" + " << \"source is a nested message in target (not allowed), or \"\n" + " << \"another thread is modifying the source.\";\n" + "#endif\n"); + } else { + format("Clear();\n"); + } + format("MergeFrom(from);\n"); + + format.Outdent(); + format("}\n\n"); } // Generate the class-specific CopyFrom. - printer->Print( + format( "void $classname$::CopyFrom(const $classname$& from) {\n" "// @@protoc_insertion_point(class_specific_copy_from_start:" - "$full_name$)\n", - "classname", classname_, "full_name", descriptor_->full_name()); - printer->Indent(); + "$full_name$)\n"); + format.Indent(); - printer->Print( - "if (&from == this) return;\n" - "Clear();\n" - "MergeFrom(from);\n"); + format("if (&from == this) return;\n"); - printer->Outdent(); - printer->Print("}\n"); + if (!options_.opensource_runtime) { + // This check is disabled in the opensource release because we're + // concerned that many users do not define NDEBUG in their release builds. + format( + "#ifndef NDEBUG\n" + "size_t from_size = from.ByteSizeLong();\n" + "#endif\n" + "Clear();\n" + "#ifndef NDEBUG\n" + "$CHK$_EQ(from_size, from.ByteSizeLong())\n" + " << \"Source of CopyFrom changed when clearing target. Either \"\n" + " << \"source is a nested message in target (not allowed), or \"\n" + " << \"another thread is modifying the source.\";\n" + "#endif\n"); + } else { + format("Clear();\n"); + } + format("MergeFrom(from);\n"); + + format.Outdent(); + format("}\n"); } -void MessageGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) { - std::map vars; +void MessageGenerator::GenerateMergeFromCodedStream(io::Printer* printer) { + std::map vars = variables_; SetUnknkownFieldsVariable(descriptor_, options_, &vars); + Formatter format(printer, vars); if (descriptor_->options().message_set_wire_format()) { // Special-case MessageSet. - vars["classname"] = classname_; - printer->Print(vars, - "bool $classname$::MergePartialFromCodedStream(\n" - " ::google::protobuf::io::CodedInputStream* input) {\n" - " return _extensions_.ParseMessageSet(input,\n" - " internal_default_instance(), $mutable_unknown_fields$);\n" - "}\n"); + format( + "#if $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n" + "const char* $classname$::_InternalParse(const char* ptr,\n" + " ::$proto_ns$::internal::ParseContext* ctx) {\n" + " return _extensions_.ParseMessageSet(ptr, \n" + " internal_default_instance(), &_internal_metadata_, ctx);\n" + "}\n" + "#else\n" + "bool $classname$::MergePartialFromCodedStream(\n" + " ::$proto_ns$::io::CodedInputStream* input) {\n" + " return _extensions_.ParseMessageSet(input,\n" + " internal_default_instance(), $mutable_unknown_fields$);\n" + "}\n" + "#endif // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n"); return; } + format("#if $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n"); + GenerateParserLoop(descriptor_, max_has_bit_index_, options_, scc_analyzer_, + printer); + format("#else // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n"); std::vector ordered_fields = SortFieldsByNumber(descriptor_); - printer->Print( - "bool $classname$::MergePartialFromCodedStream(\n" - " ::google::protobuf::io::CodedInputStream* input) {\n", - "classname", classname_); + format( + "bool $classname$::MergePartialFromCodedStream(\n" + " ::$proto_ns$::io::CodedInputStream* input) {\n"); if (table_driven_) { - printer->Indent(); + format.Indent(); - const string lite = UseUnknownFieldSet(descriptor_->file(), options_) ? - "" : "Lite"; + const std::string lite = + UseUnknownFieldSet(descriptor_->file(), options_) ? "" : "Lite"; - printer->Print( - "return ::google::protobuf::internal::MergePartialFromCodedStream$lite$(\n" - " this,\n" - " ::$file_namespace$::TableStruct::schema[\n" - " $classname$::kIndexInFileMessages],\n" - " input);\n", - "classname", classname_, "file_namespace", - FileLevelNamespace(descriptor_), "lite", lite); + format( + "return ::$proto_ns$::internal::MergePartialFromCodedStream$1$(\n" + " this, ::$tablename$::schema[\n" + " $classname$::kIndexInFileMessages], input);\n", + lite); - printer->Outdent(); + format.Outdent(); - printer->Print("}\n"); + format("}\n"); + format("#endif // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n"); return; } if (SupportsArenas(descriptor_)) { - for (int i = 0; i < ordered_fields.size(); i++) { - const FieldDescriptor* field = ordered_fields[i]; + for (auto field : ordered_fields) { const FieldGenerator& field_generator = field_generators_.get(field); if (field_generator.MergeFromCodedStreamNeedsArena()) { - printer->Print( - " ::google::protobuf::Arena* arena = GetArenaNoVirtual();\n"); + format(" ::$proto_ns$::Arena* arena = GetArenaNoVirtual();\n"); break; } } } - printer->Print( - "#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto " - "failure\n" - " ::google::protobuf::uint32 tag;\n"); + format( + "#define DO_(EXPRESSION) if " + "(!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure\n" + " $uint32$ tag;\n"); if (!UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print( - " ::google::protobuf::internal::LiteUnknownFieldSetter unknown_fields_setter(\n" + format( + " ::$proto_ns$::internal::LiteUnknownFieldSetter " + "unknown_fields_setter(\n" " &_internal_metadata_);\n" - " ::google::protobuf::io::StringOutputStream unknown_fields_output(\n" + " ::$proto_ns$::io::StringOutputStream unknown_fields_output(\n" " unknown_fields_setter.buffer());\n" - " ::google::protobuf::io::CodedOutputStream unknown_fields_stream(\n" - " &unknown_fields_output, false);\n", - "classname", classname_); + " ::$proto_ns$::io::CodedOutputStream unknown_fields_stream(\n" + " &unknown_fields_output, false);\n"); } - printer->Print( - " // @@protoc_insertion_point(parse_start:$full_name$)\n", - "full_name", descriptor_->full_name()); + format(" // @@protoc_insertion_point(parse_start:$full_name$)\n"); - printer->Indent(); - printer->Print("for (;;) {\n"); - printer->Indent(); + format.Indent(); + format("for (;;) {\n"); + format.Indent(); // To calculate the maximum tag to expect, we look at the highest-numbered // field. We need to be prepared to handle more than one wire type if that @@ -3355,8 +3460,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) { bool capture_last_tag = false; const Descriptor* parent = descriptor_->containing_type(); if (parent) { - for (int i = 0; i < parent->field_count(); i++) { - const FieldDescriptor* field = parent->field(i); + for (auto field : FieldRange(parent)) { if (field->type() == FieldDescriptor::TYPE_GROUP && field->message_type() == descriptor_) { capture_last_tag = true; @@ -3383,13 +3487,12 @@ GenerateMergeFromCodedStream(io::Printer* printer) { } } - printer->Print("::std::pair<::google::protobuf::uint32, bool> p = " - "input->ReadTagWithCutoffNoLastTag($max$u);\n" - "tag = p.first;\n" - "if (!p.second) goto handle_unusual;\n", - "max", SimpleItoa(maxtag <= kCutoff0 ? kCutoff0 : - (maxtag <= kCutoff1 ? kCutoff1 : - maxtag))); + format( + "::std::pair<$uint32$, bool> p = " + "input->ReadTagWithCutoffNoLastTag($1$u);\n" + "tag = p.first;\n" + "if (!p.second) goto handle_unusual;\n", + maxtag <= kCutoff0 ? kCutoff0 : (maxtag <= kCutoff1 ? kCutoff1 : maxtag)); if (descriptor_->field_count() > 0) { // We don't even want to print the switch() if we have no fields because @@ -3407,182 +3510,186 @@ GenerateMergeFromCodedStream(io::Printer* printer) { // inserts branches that may fail (especially for real world protos that // interleave--in field number order--hot and cold fields). Loadtests // confirmed that removing this optimization is performance neutral. - printer->Print("switch (::google::protobuf::internal::WireFormatLite::" - "GetTagFieldNumber(tag)) {\n"); + if (num_weak_fields_ > 0) { + format("uint32 weak_offset;\n"); + } + format( + "switch (::$proto_ns$::internal::WireFormatLite::" + "GetTagFieldNumber(tag)) {\n"); - printer->Indent(); + format.Indent(); - for (int i = 0; i < ordered_fields.size(); i++) { - const FieldDescriptor* field = ordered_fields[i]; + for (auto field : ordered_fields) { + PrintFieldComment(format, field); + if (IsWeak(field, options_)) { + format( + "case $1$:\n" + " weak_offset = offsetof($classname$DefaultTypeInternal, $2$_);\n" + " goto handle_weak_field_map;\n", + field->number(), FieldName(field)); + continue; + } - PrintFieldComment(printer, field); - - printer->Print( - "case $number$: {\n", - "number", SimpleItoa(field->number())); - printer->Indent(); + format("case $1$: {\n", field->number()); + format.Indent(); const FieldGenerator& field_generator = field_generators_.get(field); // Emit code to parse the common, expected case. - printer->Print( - "if (static_cast< ::google::protobuf::uint8>(tag) ==\n" - " static_cast< ::google::protobuf::uint8>($truncated$u /* $full$ & 0xFF */)) {\n", - "truncated", SimpleItoa(WireFormat::MakeTag(field) & 0xFF), - "full", SimpleItoa(WireFormat::MakeTag(field))); + // MSVC is warning about truncating constant in the static_cast so + // we truncate the tag explicitly. + format("if (static_cast< $uint8$>(tag) == ($1$ & 0xFF)) {\n", + WireFormat::MakeTag(field)); - printer->Indent(); + format.Indent(); if (field->is_packed()) { field_generator.GenerateMergeFromCodedStreamWithPacking(printer); } else { field_generator.GenerateMergeFromCodedStream(printer); } - printer->Outdent(); + format.Outdent(); // Emit code to parse unexpectedly packed or unpacked values. if (field->is_packed()) { internal::WireFormatLite::WireType wiretype = WireFormat::WireTypeForFieldType(field->type()); - const uint32 tag = internal::WireFormatLite::MakeTag( - field->number(), wiretype); - printer->Print( - "} else if (\n" - " static_cast< ::google::protobuf::uint8>(tag) ==\n" - " static_cast< ::google::protobuf::uint8>($truncated$u /* $full$ & 0xFF */)) {\n", - "truncated", SimpleItoa(tag & 0xFF), - "full", SimpleItoa(tag)); + const uint32 tag = + internal::WireFormatLite::MakeTag(field->number(), wiretype); + format("} else if (static_cast< $uint8$>(tag) == ($1$ & 0xFF)) {\n", + tag); - printer->Indent(); + format.Indent(); field_generator.GenerateMergeFromCodedStream(printer); - printer->Outdent(); + format.Outdent(); } else if (field->is_packable() && !field->is_packed()) { internal::WireFormatLite::WireType wiretype = internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED; - const uint32 tag = internal::WireFormatLite::MakeTag( - field->number(), wiretype); - - printer->Print( - "} else if (\n" - " static_cast< ::google::protobuf::uint8>(tag) ==\n" - " static_cast< ::google::protobuf::uint8>($truncated$u /* $full$ & 0xFF */)) {\n", - "truncated", SimpleItoa(tag & 0xFF), - "full", SimpleItoa(tag)); - printer->Indent(); + const uint32 tag = + internal::WireFormatLite::MakeTag(field->number(), wiretype); + format("} else if (static_cast< $uint8$>(tag) == ($1$ & 0xFF)) {\n", + tag); + format.Indent(); field_generator.GenerateMergeFromCodedStreamWithPacking(printer); - printer->Outdent(); + format.Outdent(); } - printer->Print( - "} else {\n" - " goto handle_unusual;\n" - "}\n"); + format( + "} else {\n" + " goto handle_unusual;\n" + "}\n"); - printer->Print( - "break;\n"); + format("break;\n"); - printer->Outdent(); - printer->Print("}\n\n"); + format.Outdent(); + format("}\n\n"); } - printer->Print("default: {\n"); - printer->Indent(); + if (num_weak_fields_ > 0) { + format("handle_weak_field_map: {\n"); + format.Indent(); + + format( + "if ((tag & 0x7) != 2) goto handle_unusual;\n" + "DO_(_weak_field_map_.ReadMessage(input, tag >> 3,\n" + " &_$classname$_default_instance_, weak_offset));\n"); + format("break;\n"); + format.Outdent(); + format("}\n\n"); + } + format("default: {\n"); + format.Indent(); } - printer->Outdent(); - printer->Print("handle_unusual:\n"); - printer->Indent(); + format.Outdent(); + format("handle_unusual:\n"); + format.Indent(); // If tag is 0 or an end-group tag then this must be the end of the message. if (capture_last_tag) { - printer->Print( - "if (tag == 0 ||\n" - " ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==\n" - " ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {\n" - " input->SetLastTag(tag);\n" - " goto success;\n" - "}\n"); + format( + "if (tag == 0 ||\n" + " ::$proto_ns$::internal::WireFormatLite::GetTagWireType(tag) ==\n" + " ::$proto_ns$::internal::WireFormatLite::WIRETYPE_END_GROUP) {\n" + " input->SetLastTag(tag);\n" + " goto success;\n" + "}\n"); } else { - printer->Print( - "if (tag == 0) {\n" - " goto success;\n" - "}\n"); + format( + "if (tag == 0) {\n" + " goto success;\n" + "}\n"); } // Handle extension ranges. if (descriptor_->extension_range_count() > 0) { - printer->Print( - "if ("); + format("if ("); for (int i = 0; i < descriptor_->extension_range_count(); i++) { - const Descriptor::ExtensionRange* range = - descriptor_->extension_range(i); - if (i > 0) printer->Print(" ||\n "); + const Descriptor::ExtensionRange* range = descriptor_->extension_range(i); + if (i > 0) format(" ||\n "); uint32 start_tag = WireFormatLite::MakeTag( - range->start, static_cast(0)); + range->start, static_cast(0)); uint32 end_tag = WireFormatLite::MakeTag( - range->end, static_cast(0)); + range->end, static_cast(0)); if (range->end > FieldDescriptor::kMaxNumber) { - printer->Print( - "($start$u <= tag)", - "start", SimpleItoa(start_tag)); + format("($1$u <= tag)", start_tag); } else { - printer->Print( - "($start$u <= tag && tag < $end$u)", - "start", SimpleItoa(start_tag), - "end", SimpleItoa(end_tag)); + format("($1$u <= tag && tag < $2$u)", start_tag, end_tag); } } - printer->Print(") {\n"); + format(") {\n"); if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(vars, - " DO_(_extensions_.ParseField(tag, input,\n" - " internal_default_instance(),\n" - " $mutable_unknown_fields$));\n"); + format( + " DO_(_extensions_.ParseField(tag, input,\n" + " internal_default_instance(),\n" + " $mutable_unknown_fields$));\n"); } else { - printer->Print( - " DO_(_extensions_.ParseField(tag, input,\n" - " internal_default_instance(),\n" - " &unknown_fields_stream));\n"); + format( + " DO_(_extensions_.ParseField(tag, input,\n" + " internal_default_instance(),\n" + " &unknown_fields_stream));\n"); } - printer->Print( - " continue;\n" - "}\n"); + format( + " continue;\n" + "}\n"); } // We really don't recognize this tag. Skip it. if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(vars, - "DO_(::google::protobuf::internal::WireFormat::SkipField(\n" + format( + "DO_(::$proto_ns$::internal::WireFormat::SkipField(\n" " input, tag, $mutable_unknown_fields$));\n"); } else { - printer->Print( - "DO_(::google::protobuf::internal::WireFormatLite::SkipField(\n" + format( + "DO_(::$proto_ns$::internal::WireFormatLite::SkipField(\n" " input, tag, &unknown_fields_stream));\n"); } if (descriptor_->field_count() > 0) { - printer->Print("break;\n"); - printer->Outdent(); - printer->Print("}\n"); // default: - printer->Outdent(); - printer->Print("}\n"); // switch + format("break;\n"); + format.Outdent(); + format("}\n"); // default: + format.Outdent(); + format("}\n"); // switch } - printer->Outdent(); - printer->Outdent(); - printer->Print( - " }\n" // for (;;) - "success:\n" - " // @@protoc_insertion_point(parse_success:$full_name$)\n" - " return true;\n" - "failure:\n" - " // @@protoc_insertion_point(parse_failure:$full_name$)\n" - " return false;\n" - "#undef DO_\n" - "}\n", "full_name", descriptor_->full_name()); + format.Outdent(); + format.Outdent(); + format( + " }\n" // for (;;) + "success:\n" + " // @@protoc_insertion_point(parse_success:$full_name$)\n" + " return true;\n" + "failure:\n" + " // @@protoc_insertion_point(parse_failure:$full_name$)\n" + " return false;\n" + "#undef DO_\n" + "}\n"); + format("#endif // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n"); } void MessageGenerator::GenerateSerializeOneofFields( io::Printer* printer, const std::vector& fields, bool to_array) { + Formatter format(printer, variables_); GOOGLE_CHECK(!fields.empty()); if (fields.size() == 1) { GenerateSerializeOneField(printer, fields[0], to_array, -1); @@ -3590,39 +3697,35 @@ void MessageGenerator::GenerateSerializeOneofFields( } // We have multiple mutually exclusive choices. Emit a switch statement. const OneofDescriptor* oneof = fields[0]->containing_oneof(); - printer->Print( - "switch ($oneofname$_case()) {\n", - "oneofname", oneof->name()); - printer->Indent(); - for (int i = 0; i < fields.size(); i++) { - const FieldDescriptor* field = fields[i]; - printer->Print( - "case k$field_name$:\n", - "field_name", UnderscoresToCamelCase(field->name(), true)); - printer->Indent(); + format("switch ($1$_case()) {\n", oneof->name()); + format.Indent(); + for (auto field : fields) { + format("case k$1$:\n", UnderscoresToCamelCase(field->name(), true)); + format.Indent(); if (to_array) { field_generators_.get(field).GenerateSerializeWithCachedSizesToArray( printer); } else { field_generators_.get(field).GenerateSerializeWithCachedSizes(printer); } - printer->Print( - "break;\n"); - printer->Outdent(); + format("break;\n"); + format.Outdent(); } - printer->Outdent(); + format.Outdent(); // Doing nothing is an option. - printer->Print( - " default: ;\n" - "}\n"); + format( + " default: ;\n" + "}\n"); } -void MessageGenerator::GenerateSerializeOneField( - io::Printer* printer, const FieldDescriptor* field, bool to_array, - int cached_has_bits_index) { +void MessageGenerator::GenerateSerializeOneField(io::Printer* printer, + const FieldDescriptor* field, + bool to_array, + int cached_has_bits_index) { + Formatter format(printer, variables_); if (!field->options().weak()) { // For weakfields, PrintFieldComment is called during iteration. - PrintFieldComment(printer, field); + PrintFieldComment(format, field); } bool have_enclosing_if = false; @@ -3631,19 +3734,15 @@ void MessageGenerator::GenerateSerializeOneField( // Attempt to use the state of cached_has_bits, if possible. int has_bit_index = has_bit_indices_[field->index()]; if (cached_has_bits_index == has_bit_index / 32) { - const string mask = StrCat( - strings::Hex(1u << (has_bit_index % 32), - strings::ZERO_PAD_8)); + const std::string mask = + StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8)); - printer->Print( - "if (cached_has_bits & 0x$mask$u) {\n", "mask", mask); + format("if (cached_has_bits & 0x$1$u) {\n", mask); } else { - printer->Print( - "if (has_$name$()) {\n", - "name", FieldName(field)); + format("if (has_$1$()) {\n", FieldName(field)); } - printer->Indent(); + format.Indent(); have_enclosing_if = true; } else if (!HasFieldPresence(descriptor_->file())) { have_enclosing_if = EmitFieldNonDefaultCondition(printer, "this->", field); @@ -3657,122 +3756,110 @@ void MessageGenerator::GenerateSerializeOneField( } if (have_enclosing_if) { - printer->Outdent(); - printer->Print("}\n"); + format.Outdent(); + format("}\n"); } - printer->Print("\n"); + format("\n"); } void MessageGenerator::GenerateSerializeOneExtensionRange( io::Printer* printer, const Descriptor::ExtensionRange* range, bool to_array) { - std::map vars; - vars["start"] = SimpleItoa(range->start); - vars["end"] = SimpleItoa(range->end); - printer->Print(vars, - "// Extension range [$start$, $end$)\n"); + std::map vars; + vars["start"] = StrCat(range->start); + vars["end"] = StrCat(range->end); + Formatter format(printer, vars); + format("// Extension range [$start$, $end$)\n"); if (to_array) { - printer->Print(vars, - "target = _extensions_.InternalSerializeWithCachedSizesToArray(\n" - " $start$, $end$, deterministic, target);\n\n"); + format( + "target = _extensions_.InternalSerializeWithCachedSizesToArray(\n" + " $start$, $end$, target);\n\n"); } else { - printer->Print(vars, - "_extensions_.SerializeWithCachedSizes(\n" - " $start$, $end$, output);\n\n"); + format( + "_extensions_.SerializeWithCachedSizes($start$, $end$, output);\n" + "\n"); } } -void MessageGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) { +void MessageGenerator::GenerateSerializeWithCachedSizes(io::Printer* printer) { + Formatter format(printer, variables_); if (descriptor_->options().message_set_wire_format()) { // Special-case MessageSet. - printer->Print( - "void $classname$::SerializeWithCachedSizes(\n" - " ::google::protobuf::io::CodedOutputStream* output) const {\n" - " _extensions_.SerializeMessageSetWithCachedSizes(output);\n", - "classname", classname_); - GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file(), options_)); - std::map vars; + format( + "void $classname$::SerializeWithCachedSizes(\n" + " ::$proto_ns$::io::CodedOutputStream* output) const {\n" + " _extensions_.SerializeMessageSetWithCachedSizes(output);\n"); + std::map vars; SetUnknkownFieldsVariable(descriptor_, options_, &vars); - printer->Print(vars, - " ::google::protobuf::internal::WireFormat::SerializeUnknownMessageSetItems(\n" - " $unknown_fields$, output);\n"); - printer->Print( - "}\n"); + format.AddMap(vars); + format( + " " + "::$proto_ns$::internal::SerializeUnknownMessageSetItems(\n" + " $unknown_fields$, output);\n"); + format("}\n"); return; } if (options_.table_driven_serialization) return; - printer->Print( - "void $classname$::SerializeWithCachedSizes(\n" - " ::google::protobuf::io::CodedOutputStream* output) const {\n", - "classname", classname_); - printer->Indent(); + format( + "void $classname$::SerializeWithCachedSizes(\n" + " ::$proto_ns$::io::CodedOutputStream* output) const {\n"); + format.Indent(); - printer->Print( - "// @@protoc_insertion_point(serialize_start:$full_name$)\n", - "full_name", descriptor_->full_name()); + format("// @@protoc_insertion_point(serialize_start:$full_name$)\n"); GenerateSerializeWithCachedSizesBody(printer, false); - printer->Print( - "// @@protoc_insertion_point(serialize_end:$full_name$)\n", - "full_name", descriptor_->full_name()); + format("// @@protoc_insertion_point(serialize_end:$full_name$)\n"); - printer->Outdent(); - printer->Print( - "}\n"); + format.Outdent(); + format("}\n"); } -void MessageGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) { +void MessageGenerator::GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) { + Formatter format(printer, variables_); if (descriptor_->options().message_set_wire_format()) { // Special-case MessageSet. - printer->Print( - "::google::protobuf::uint8* $classname$::InternalSerializeWithCachedSizesToArray(\n" - " bool deterministic, ::google::protobuf::uint8* target) const {\n" - " target = _extensions_." - "InternalSerializeMessageSetWithCachedSizesToArray(\n" - " deterministic, target);\n", - "classname", classname_); + format( + "$uint8$* $classname$::InternalSerializeWithCachedSizesToArray(\n" + " $uint8$* target) const {\n" + " target = _extensions_." + "InternalSerializeMessageSetWithCachedSizesToArray(target);\n"); GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file(), options_)); - std::map vars; + std::map vars; SetUnknkownFieldsVariable(descriptor_, options_, &vars); - printer->Print(vars, - " target = ::google::protobuf::internal::WireFormat::\n" - " SerializeUnknownMessageSetItemsToArray(\n" - " $unknown_fields$, target);\n"); - printer->Print( - " return target;\n" - "}\n"); + format.AddMap(vars); + format( + " target = ::$proto_ns$::internal::WireFormat::\n" + " SerializeUnknownMessageSetItemsToArray(\n" + " $unknown_fields$, target);\n"); + format( + " return target;\n" + "}\n"); return; } - printer->Print( - "::google::protobuf::uint8* $classname$::InternalSerializeWithCachedSizesToArray(\n" - " bool deterministic, ::google::protobuf::uint8* target) const {\n", - "classname", classname_); - printer->Indent(); + format( + "$uint8$* $classname$::InternalSerializeWithCachedSizesToArray(\n" + " $uint8$* target) const {\n"); + format.Indent(); - printer->Print("(void)deterministic; // Unused\n"); - printer->Print( - "// @@protoc_insertion_point(serialize_to_array_start:$full_name$)\n", - "full_name", descriptor_->full_name()); + format("// @@protoc_insertion_point(serialize_to_array_start:$full_name$)\n"); GenerateSerializeWithCachedSizesBody(printer, true); - printer->Print( - "// @@protoc_insertion_point(serialize_to_array_end:$full_name$)\n", - "full_name", descriptor_->full_name()); + format("// @@protoc_insertion_point(serialize_to_array_end:$full_name$)\n"); - printer->Outdent(); - printer->Print( - " return target;\n" - "}\n"); + format.Outdent(); + format( + " return target;\n" + "}\n"); } -void MessageGenerator:: -GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) { +void MessageGenerator::GenerateSerializeWithCachedSizesBody( + io::Printer* printer, bool to_array) { + Formatter format(printer, variables_); // If there are multiple fields in a row from the same oneof then we // coalesce them and emit a switch statement. This is more efficient // because it lets the C++ compiler know this is a "at most one can happen" @@ -3783,7 +3870,7 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) { LazySerializerEmitter(MessageGenerator* mg, io::Printer* printer, bool to_array) : mg_(mg), - printer_(printer), + format_(printer), to_array_(to_array), eager_(!HasFieldPresence(mg->descriptor_->file())), cached_has_bit_index_(-1) {} @@ -3808,16 +3895,14 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) { // Reload. int new_index = has_bit_index / 32; - printer_->Print( - "cached_has_bits = _has_bits_[$new_index$];\n", - "new_index", SimpleItoa(new_index)); + format_("cached_has_bits = _has_bits_[$1$];\n", new_index); cached_has_bit_index_ = new_index; } } - mg_->GenerateSerializeOneField( - printer_, field, to_array_, cached_has_bit_index_); + mg_->GenerateSerializeOneField(format_.printer(), field, to_array_, + cached_has_bit_index_); } else { v_.push_back(field); } @@ -3825,7 +3910,7 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) { void Flush() { if (!v_.empty()) { - mg_->GenerateSerializeOneofFields(printer_, v_, to_array_); + mg_->GenerateSerializeOneofFields(format_.printer(), v_, to_array_); v_.clear(); } } @@ -3839,7 +3924,7 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) { } MessageGenerator* mg_; - io::Printer* printer_; + Formatter format_; const bool to_array_; const bool eager_; std::vector v_; @@ -3854,19 +3939,20 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) { SortFieldsByNumber(descriptor_); std::vector sorted_extensions; + sorted_extensions.reserve(descriptor_->extension_range_count()); for (int i = 0; i < descriptor_->extension_range_count(); ++i) { sorted_extensions.push_back(descriptor_->extension_range(i)); } std::sort(sorted_extensions.begin(), sorted_extensions.end(), ExtensionRangeSorter()); if (num_weak_fields_) { - printer->Print( - "::google::protobuf::internal::WeakFieldMap::FieldWriter field_writer(" + format( + "::$proto_ns$::internal::WeakFieldMap::FieldWriter field_writer(" "_weak_field_map_);\n"); } - printer->Print( - "::google::protobuf::uint32 cached_has_bits = 0;\n" + format( + "$uint32$ cached_has_bits = 0;\n" "(void) cached_has_bits;\n\n"); // Merge the fields and the extension ranges, both sorted by field number. @@ -3882,7 +3968,7 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) { const FieldDescriptor* field = ordered_fields[i++]; if (field->options().weak()) { last_weak_field = field; - PrintFieldComment(printer, field); + PrintFieldComment(format, field); } else { if (last_weak_field != nullptr) { e.Emit(last_weak_field); @@ -3890,14 +3976,13 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) { } e.Emit(field); } - } else { + } else { if (last_weak_field != nullptr) { e.Emit(last_weak_field); last_weak_field = nullptr; } e.Flush(); - GenerateSerializeOneExtensionRange(printer, - sorted_extensions[j++], + GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++], to_array); } } @@ -3906,29 +3991,29 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) { } } - std::map vars; + std::map vars; SetUnknkownFieldsVariable(descriptor_, options_, &vars); + format.AddMap(vars); if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(vars, - "if ($have_unknown_fields$) {\n"); - printer->Indent(); + format("if ($have_unknown_fields$) {\n"); + format.Indent(); if (to_array) { - printer->Print(vars, - "target = " - "::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(\n" - " $unknown_fields$, target);\n"); + format( + "target = " + "::$proto_ns$::internal::WireFormat::SerializeUnknownFieldsToArray(\n" + " $unknown_fields$, target);\n"); } else { - printer->Print(vars, - "::google::protobuf::internal::WireFormat::SerializeUnknownFields(\n" - " $unknown_fields$, output);\n"); + format( + "::$proto_ns$::internal::WireFormat::SerializeUnknownFields(\n" + " $unknown_fields$, output);\n"); } - printer->Outdent(); + format.Outdent(); - printer->Print("}\n"); + format("}\n"); } else { - printer->Print(vars, - "output->WriteRaw($unknown_fields$.data(),\n" - " static_cast($unknown_fields$.size()));\n"); + format( + "output->WriteRaw($unknown_fields$.data(),\n" + " static_cast($unknown_fields$.size()));\n"); } } @@ -3936,15 +4021,13 @@ std::vector MessageGenerator::RequiredFieldsBitMask() const { const int array_size = HasBitsSize(); std::vector masks(array_size, 0); - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); + for (auto field : FieldRange(descriptor_)) { if (!field->is_required()) { continue; } const int has_bit_index = has_bit_indices_[field->index()]; - masks[has_bit_index / 32] |= - static_cast(1) << (has_bit_index % 32); + masks[has_bit_index / 32] |= static_cast(1) << (has_bit_index % 32); } return masks; } @@ -3953,41 +4036,43 @@ std::vector MessageGenerator::RequiredFieldsBitMask() const { // "for all i, (_has_bits_[i] & masks[i]) == masks[i]" // masks is allowed to be shorter than _has_bits_, but at least one element of // masks must be non-zero. -static string ConditionalToCheckBitmasks(const std::vector& masks) { - std::vector parts; +static std::string ConditionalToCheckBitmasks( + const std::vector& masks) { + std::vector parts; for (int i = 0; i < masks.size(); i++) { if (masks[i] == 0) continue; - string m = StrCat("0x", strings::Hex(masks[i], strings::ZERO_PAD_8)); + std::string m = StrCat("0x", strings::Hex(masks[i], strings::ZERO_PAD_8)); // Each xor evaluates to 0 if the expected bits are present. - parts.push_back(StrCat("((_has_bits_[", i, "] & ", m, ") ^ ", m, ")")); + parts.push_back( + StrCat("((_has_bits_[", i, "] & ", m, ") ^ ", m, ")")); } GOOGLE_CHECK(!parts.empty()); // If we have multiple parts, each expected to be 0, then bitwise-or them. - string result = parts.size() == 1 - ? parts[0] - : StrCat("(", Join(parts, "\n | "), ")"); + std::string result = + parts.size() == 1 + ? parts[0] + : StrCat("(", Join(parts, "\n | "), ")"); return result + " == 0"; } -void MessageGenerator:: -GenerateByteSize(io::Printer* printer) { +void MessageGenerator::GenerateByteSize(io::Printer* printer) { + Formatter format(printer, variables_); + if (descriptor_->options().message_set_wire_format()) { // Special-case MessageSet. - GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file(), options_)); - std::map vars; + std::map vars; SetUnknkownFieldsVariable(descriptor_, options_, &vars); - vars["classname"] = classname_; - vars["full_name"] = descriptor_->full_name(); - printer->Print( - vars, + format.AddMap(vars); + format( "size_t $classname$::ByteSizeLong() const {\n" "// @@protoc_insertion_point(message_set_byte_size_start:$full_name$)\n" " size_t total_size = _extensions_.MessageSetByteSize();\n" " if ($have_unknown_fields$) {\n" - " total_size += ::google::protobuf::internal::WireFormat::\n" + " total_size += ::$proto_ns$::internal::\n" " ComputeUnknownMessageSetItemsSize($unknown_fields$);\n" " }\n" - " int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n" + " int cached_size = " + "::$proto_ns$::internal::ToCachedSize(total_size);\n" " SetCachedSize(cached_size);\n" " return total_size;\n" "}\n"); @@ -3997,60 +4082,60 @@ GenerateByteSize(io::Printer* printer) { if (num_required_fields_ > 1 && HasFieldPresence(descriptor_->file())) { // Emit a function (rarely used, we hope) that handles the required fields // by checking for each one individually. - printer->Print( + format( "size_t $classname$::RequiredFieldsByteSizeFallback() const {\n" "// @@protoc_insertion_point(required_fields_byte_size_fallback_start:" - "$full_name$)\n", - "classname", classname_, "full_name", descriptor_->full_name()); - printer->Indent(); - printer->Print("size_t total_size = 0;\n"); - for (int i = 0; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; + "$full_name$)\n"); + format.Indent(); + format("size_t total_size = 0;\n"); + for (auto field : optimized_order_) { if (field->is_required()) { - printer->Print("\n" - "if (has_$name$()) {\n", - "name", FieldName(field)); - printer->Indent(); - PrintFieldComment(printer, field); + format( + "\n" + "if (has_$1$()) {\n", + FieldName(field)); + format.Indent(); + PrintFieldComment(format, field); field_generators_.get(field).GenerateByteSize(printer); - printer->Outdent(); - printer->Print("}\n"); + format.Outdent(); + format("}\n"); } } - printer->Print("\n" - "return total_size;\n"); - printer->Outdent(); - printer->Print("}\n"); + format( + "\n" + "return total_size;\n"); + format.Outdent(); + format("}\n"); } - printer->Print( + format( "size_t $classname$::ByteSizeLong() const {\n" - "// @@protoc_insertion_point(message_byte_size_start:$full_name$)\n", - "classname", classname_, "full_name", descriptor_->full_name()); - printer->Indent(); - printer->Print( - "size_t total_size = 0;\n" - "\n"); + "// @@protoc_insertion_point(message_byte_size_start:$full_name$)\n"); + format.Indent(); + format( + "size_t total_size = 0;\n" + "\n"); if (descriptor_->extension_range_count() > 0) { - printer->Print( - "total_size += _extensions_.ByteSize();\n" - "\n"); + format( + "total_size += _extensions_.ByteSize();\n" + "\n"); } - std::map vars; + std::map vars; SetUnknkownFieldsVariable(descriptor_, options_, &vars); + format.AddMap(vars); if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(vars, - "if ($have_unknown_fields$) {\n" - " total_size +=\n" - " ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(\n" - " $unknown_fields$);\n" - "}\n"); + format( + "if ($have_unknown_fields$) {\n" + " total_size +=\n" + " ::$proto_ns$::internal::WireFormat::ComputeUnknownFieldsSize(\n" + " $unknown_fields$);\n" + "}\n"); } else { - printer->Print(vars, - "total_size += $unknown_fields$.size();\n" - "\n"); + format( + "total_size += $unknown_fields$.size();\n" + "\n"); } // Handle required fields (if any). We expect all of them to be @@ -4059,39 +4144,36 @@ GenerateByteSize(io::Printer* printer) { if (num_required_fields_ > 1 && HasFieldPresence(descriptor_->file())) { // The fast path works if all required fields are present. const std::vector masks_for_has_bits = RequiredFieldsBitMask(); - printer->Print((string("if (") + - ConditionalToCheckBitmasks(masks_for_has_bits) + - ") { // All required fields are present.\n").c_str()); - printer->Indent(); + format("if ($1$) { // All required fields are present.\n", + ConditionalToCheckBitmasks(masks_for_has_bits)); + format.Indent(); // Oneof fields cannot be required, so optimized_order_ contains all of the // fields that we need to potentially emit. - for (int i = 0; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; + for (auto field : optimized_order_) { if (!field->is_required()) continue; - PrintFieldComment(printer, field); + PrintFieldComment(format, field); field_generators_.get(field).GenerateByteSize(printer); - printer->Print("\n"); + format("\n"); } - printer->Outdent(); - printer->Print("} else {\n" // the slow path - " total_size += RequiredFieldsByteSizeFallback();\n" - "}\n"); + format.Outdent(); + format( + "} else {\n" // the slow path + " total_size += RequiredFieldsByteSizeFallback();\n" + "}\n"); } else { // num_required_fields_ <= 1: no need to be tricky - for (int i = 0; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; + for (auto field : optimized_order_) { if (!field->is_required()) continue; - PrintFieldComment(printer, field); - printer->Print("if (has_$name$()) {\n", - "name", FieldName(field)); - printer->Indent(); + PrintFieldComment(format, field); + format("if (has_$1$()) {\n", FieldName(field)); + format.Indent(); field_generators_.get(field).GenerateByteSize(printer); - printer->Outdent(); - printer->Print("}\n"); + format.Outdent(); + format("}\n"); } } - std::vector > chunks = CollectFields( + std::vector> chunks = CollectFields( optimized_order_, MatchRepeatedAndHasByteAndRequired( &has_bit_indices_, HasFieldPresence(descriptor_->file()))); @@ -4100,6 +4182,16 @@ GenerateByteSize(io::Printer* printer) { chunks.erase(std::remove_if(chunks.begin(), chunks.end(), IsRequired), chunks.end()); + ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, kColdRatio, + HasFieldPresence(descriptor_->file())); + + format( + "$uint32$ cached_has_bits = 0;\n" + "// Prevent compiler warnings about cached_has_bits being unused\n" + "(void) cached_has_bits;\n\n"); + + int cached_has_bit_index = -1; + for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) { const std::vector& chunk = chunks[chunk_index]; GOOGLE_CHECK(!chunk.empty()); @@ -4109,14 +4201,16 @@ GenerateByteSize(io::Printer* printer) { for (int i = 0; i < chunk.size(); i++) { const FieldDescriptor* field = chunk[i]; - PrintFieldComment(printer, field); + PrintFieldComment(format, field); const FieldGenerator& generator = field_generators_.get(field); generator.GenerateByteSize(printer); - printer->Print("\n"); + format("\n"); } continue; } + cold_skipper.OnStartChunk(chunk_index, cached_has_bit_index, "", printer); + // Handle optional (non-repeated/oneof) fields. // // These are handled in chunks of 8. The first chunk is @@ -4144,10 +4238,13 @@ GenerateByteSize(io::Printer* printer) { GOOGLE_DCHECK_LE(2, count); GOOGLE_DCHECK_GE(8, count); - printer->Print("if (_has_bits_[$index$ / 32] & $mask$u) {\n", "index", - SimpleItoa(last_chunk * 8), "mask", - SimpleItoa(last_chunk_mask)); - printer->Indent(); + if (cached_has_bit_index != last_chunk / 4) { + cached_has_bit_index = last_chunk / 4; + format("cached_has_bits = _has_bits_[$1$];\n", cached_has_bit_index); + } + format("if (cached_has_bits & 0x$1$u) {\n", + StrCat(strings::Hex(last_chunk_mask, strings::ZERO_PAD_8))); + format.Indent(); } // Go back and emit checks for each of the fields we processed. @@ -4155,12 +4252,12 @@ GenerateByteSize(io::Printer* printer) { const FieldDescriptor* field = chunk[j]; const FieldGenerator& generator = field_generators_.get(field); - PrintFieldComment(printer, field); + PrintFieldComment(format, field); bool have_enclosing_if = false; if (HasFieldPresence(descriptor_->file())) { - printer->Print("if (has_$name$()) {\n", "name", FieldName(field)); - printer->Indent(); + PrintPresenceCheck(format, field, has_bit_indices_, printer, + &cached_has_bit_index); have_enclosing_if = true; } else { // Without field presence: field is serialized only if it has a @@ -4172,54 +4269,50 @@ GenerateByteSize(io::Printer* printer) { generator.GenerateByteSize(printer); if (have_enclosing_if) { - printer->Outdent(); - printer->Print( + format.Outdent(); + format( "}\n" "\n"); } } if (have_outer_if) { - printer->Outdent(); - printer->Print("}\n"); + format.Outdent(); + format("}\n"); + } + + if (cold_skipper.OnEndChunk(chunk_index, printer)) { + // Reset here as it may have been updated in just closed if statement. + cached_has_bit_index = -1; } } // Fields inside a oneof don't use _has_bits_ so we count them in a separate // pass. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "switch ($oneofname$_case()) {\n", - "oneofname", descriptor_->oneof_decl(i)->name()); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - PrintFieldComment(printer, field); - printer->Print( - "case k$field_name$: {\n", - "field_name", UnderscoresToCamelCase(field->name(), true)); - printer->Indent(); + for (auto oneof : OneOfRange(descriptor_)) { + format("switch ($1$_case()) {\n", oneof->name()); + format.Indent(); + for (auto field : FieldRange(oneof)) { + PrintFieldComment(format, field); + format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true)); + format.Indent(); field_generators_.get(field).GenerateByteSize(printer); - printer->Print( - "break;\n"); - printer->Outdent(); - printer->Print( - "}\n"); + format("break;\n"); + format.Outdent(); + format("}\n"); } - printer->Print( - "case $cap_oneof_name$_NOT_SET: {\n" + format( + "case $1$_NOT_SET: {\n" " break;\n" "}\n", - "cap_oneof_name", - ToUpper(descriptor_->oneof_decl(i)->name())); - printer->Outdent(); - printer->Print( - "}\n"); + ToUpper(oneof->name())); + format.Outdent(); + format("}\n"); } if (num_weak_fields_) { // TagSize + MessageSize - printer->Print("total_size += _weak_field_map_.ByteSizeLong();\n"); + format("total_size += _weak_field_map_.ByteSizeLong();\n"); } // We update _cached_size_ even though this is a const method. Because @@ -4230,27 +4323,25 @@ GenerateByteSize(io::Printer* printer) { // the underlying atomic. This makes it easier on platforms where even relaxed // memory order might have perf impact to replace it with ordinary loads and // stores. - printer->Print( - "int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n" + format( + "int cached_size = ::$proto_ns$::internal::ToCachedSize(total_size);\n" "SetCachedSize(cached_size);\n" "return total_size;\n"); - printer->Outdent(); - printer->Print("}\n"); + format.Outdent(); + format("}\n"); } -void MessageGenerator:: -GenerateIsInitialized(io::Printer* printer) { - printer->Print( - "bool $classname$::IsInitialized() const {\n", - "classname", classname_); - printer->Indent(); +void MessageGenerator::GenerateIsInitialized(io::Printer* printer) { + Formatter format(printer, variables_); + format("bool $classname$::IsInitialized() const {\n"); + format.Indent(); if (descriptor_->extension_range_count() > 0) { - printer->Print( - "if (!_extensions_.IsInitialized()) {\n" - " return false;\n" - "}\n\n"); + format( + "if (!_extensions_.IsInitialized()) {\n" + " return false;\n" + "}\n\n"); } if (HasFieldPresence(descriptor_->file())) { @@ -4267,57 +4358,51 @@ GenerateIsInitialized(io::Printer* printer) { // TODO(ckennelly): Consider doing something similar to ByteSizeLong(), // where we check all of the required fields in a single branch (assuming // that we aren't going to benefit from early termination). - printer->Print( - "if ((_has_bits_[$i$] & 0x$mask$) != 0x$mask$) return false;\n", - "i", SimpleItoa(i), - "mask", StrCat(strings::Hex(mask, strings::ZERO_PAD_8))); + format("if ((_has_bits_[$1$] & 0x$2$) != 0x$2$) return false;\n", + i, // 1 + StrCat(strings::Hex(mask, strings::ZERO_PAD_8))); // 2 } } // Now check that all non-oneof embedded messages are initialized. - for (int i = 0; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; + for (auto field : optimized_order_) { // TODO(ckennelly): Push this down into a generator? if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && !ShouldIgnoreRequiredFieldCheck(field, options_) && scc_analyzer_->HasRequiredFields(field->message_type())) { if (field->is_repeated()) { if (IsImplicitWeakField(field, options_, scc_analyzer_)) { - printer->Print( - "if (!::google::protobuf::internal::AllAreInitializedWeak(this->$name$_))" - " return false;\n", - "name", FieldName(field)); + format( + "if (!::$proto_ns$::internal::AllAreInitializedWeak(this->$1$_))" + " return false;\n", + FieldName(field)); } else { - printer->Print( - "if (!::google::protobuf::internal::AllAreInitialized(this->$name$()))" - " return false;\n", - "name", FieldName(field)); + format( + "if (!::$proto_ns$::internal::AllAreInitialized(this->$1$()))" + " return false;\n", + FieldName(field)); } } else if (field->options().weak()) { continue; } else { GOOGLE_CHECK(!field->containing_oneof()); - printer->Print( - "if (has_$name$()) {\n" - " if (!this->$name$_->IsInitialized()) return false;\n" + format( + "if (has_$1$()) {\n" + " if (!this->$1$_->IsInitialized()) return false;\n" "}\n", - "name", FieldName(field)); + FieldName(field)); } } } if (num_weak_fields_) { // For Weak fields. - printer->Print("if (!_weak_field_map_.IsInitialized()) return false;\n"); + format("if (!_weak_field_map_.IsInitialized()) return false;\n"); } // Go through the oneof fields, emitting a switch if any might have required // fields. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - const OneofDescriptor* oneof = descriptor_->oneof_decl(i); - + for (auto oneof : OneOfRange(descriptor_)) { bool has_required_fields = false; - for (int j = 0; j < oneof->field_count(); j++) { - const FieldDescriptor* field = oneof->field(j); - + for (auto field : FieldRange(oneof)) { if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && !ShouldIgnoreRequiredFieldCheck(field, options_) && scc_analyzer_->HasRequiredFields(field->message_type())) { @@ -4330,16 +4415,11 @@ GenerateIsInitialized(io::Printer* printer) { continue; } - printer->Print( - "switch ($oneofname$_case()) {\n", - "oneofname", oneof->name()); - printer->Indent(); - for (int j = 0; j < oneof->field_count(); j++) { - const FieldDescriptor* field = oneof->field(j); - printer->Print( - "case k$field_name$: {\n", - "field_name", UnderscoresToCamelCase(field->name(), true)); - printer->Indent(); + format("switch ($1$_case()) {\n", oneof->name()); + format.Indent(); + for (auto field : FieldRange(oneof)) { + format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true)); + format.Indent(); if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && !ShouldIgnoreRequiredFieldCheck(field, options_) && @@ -4348,35 +4428,31 @@ GenerateIsInitialized(io::Printer* printer) { if (field->options().weak()) { // Just skip. } else { - printer->Print( - "if (has_$name$()) {\n" - " if (!this->$name$().IsInitialized()) return false;\n" - "}\n", - "name", FieldName(field)); + format( + "if (has_$1$()) {\n" + " if (!this->$1$().IsInitialized()) return false;\n" + "}\n", + FieldName(field)); } } - printer->Print( - "break;\n"); - printer->Outdent(); - printer->Print( - "}\n"); + format("break;\n"); + format.Outdent(); + format("}\n"); } - printer->Print( - "case $cap_oneof_name$_NOT_SET: {\n" + format( + "case $1$_NOT_SET: {\n" " break;\n" "}\n", - "cap_oneof_name", ToUpper(oneof->name())); - printer->Outdent(); - printer->Print( - "}\n"); + format.Outdent(); + format("}\n"); } - printer->Outdent(); - printer->Print( - " return true;\n" - "}\n"); + format.Outdent(); + format( + " return true;\n" + "}\n"); } } // namespace cpp diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message.h b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message.h index ca2ca2c9..f7206b94 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message.h +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message.h @@ -45,37 +45,33 @@ namespace google { namespace protobuf { - namespace io { - class Printer; // printer.h - } +namespace io { +class Printer; // printer.h } +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace cpp { -class EnumGenerator; // enum.h -class ExtensionGenerator; // extension.h +class EnumGenerator; // enum.h +class ExtensionGenerator; // extension.h class MessageGenerator { public: // See generator.cc for the meaning of dllexport_decl. - MessageGenerator(const Descriptor* descriptor, int index_in_file_messages, - const Options& options, SCCAnalyzer* scc_analyzer); + MessageGenerator(const Descriptor* descriptor, + const std::map& vars, + int index_in_file_messages, const Options& options, + MessageSCCAnalyzer* scc_analyzer); ~MessageGenerator(); // Append the two types of nested generators to the corresponding vector. - void AddGenerators(std::vector* enum_generators, - std::vector* extension_generators); - - // Header stuff. - - // Return names for forward declarations of this class and all its nested - // types. A given key in {class,enum}_names will map from a class name to the - // descriptor that was responsible for its inclusion in the map. This can be - // used to associate the descriptor with the code generated for it. - void FillMessageForwardDeclarations( - std::map* class_names); + void AddGenerators( + std::vector>* enum_generators, + std::vector>* extension_generators); // Generate definitions for this class and all its nested types. void GenerateClassDefinition(io::Printer* printer); @@ -112,8 +108,8 @@ class MessageGenerator { // generated. size_t GenerateParseOffsets(io::Printer* printer); size_t GenerateParseAuxTable(io::Printer* printer); - // Generates a ParseTable entry. Returns whether the proto uses table-driven - // parsing. + // Generates a ParseTable entry. Returns whether the proto uses + // table-driven parsing. bool GenerateParseTable(io::Printer* printer, size_t offset, size_t aux_offset); @@ -139,13 +135,6 @@ class MessageGenerator { // Generate the arena-specific destructor code. void GenerateArenaDestructorCode(io::Printer* printer); - // Helper for GenerateClear and others. Optionally emits a condition that - // assumes the existence of the cached_has_bits variable, and returns true if - // the condition was printed. - bool MaybeGenerateOptionalFieldCondition(io::Printer* printer, - const FieldDescriptor* field, - int expected_has_bits_index); - // Generate standard Message methods. void GenerateClear(io::Printer* printer); void GenerateOneofClear(io::Printer* printer); @@ -166,8 +155,7 @@ class MessageGenerator { // cached_has_bits = _has_bits_[cached_has_bit_index] // for cached_has_bit_index >= 0 void GenerateSerializeOneField(io::Printer* printer, - const FieldDescriptor* field, - bool unbounded, + const FieldDescriptor* field, bool unbounded, int cached_has_bits_index); // Generate a switch statement to serialize 2+ fields from the same oneof. // Or, if fields.size() == 1, just call GenerateSerializeOneField(). @@ -180,19 +168,15 @@ class MessageGenerator { // Generates has_foo() functions and variables for singular field has-bits. void GenerateSingularFieldHasBits(const FieldDescriptor* field, - std::map vars, - io::Printer* printer); + Formatter format); // Generates has_foo() functions and variables for oneof field has-bits. void GenerateOneofHasBits(io::Printer* printer); // Generates has_foo_bar() functions for oneof members. void GenerateOneofMemberHasBits(const FieldDescriptor* field, - const std::map& vars, - io::Printer* printer); + const Formatter& format); // Generates the clear_foo() method for a field. - void GenerateFieldClear(const FieldDescriptor* field, - const std::map& vars, - bool is_inline, - io::Printer* printer); + void GenerateFieldClear(const FieldDescriptor* field, bool is_inline, + Formatter format); void GenerateConstructorBody(io::Printer* printer, std::vector already_processed, @@ -203,18 +187,19 @@ class MessageGenerator { const Descriptor* descriptor_; int index_in_file_messages_; - string classname_; + std::string classname_; Options options_; FieldGeneratorMap field_generators_; - // optimized_order_ is the order we layout the message's fields in the class. - // This is reused to initialize the fields in-order for cache efficiency. + // optimized_order_ is the order we layout the message's fields in the + // class. This is reused to initialize the fields in-order for cache + // efficiency. // // optimized_order_ excludes oneof fields and weak fields. - std::vector optimized_order_; + std::vector optimized_order_; std::vector has_bit_indices_; int max_has_bit_index_; - std::unique_ptr []> enum_generators_; - std::unique_ptr []> extension_generators_; + std::vector enum_generators_; + std::vector extension_generators_; int num_required_fields_; int num_weak_fields_; // table_driven_ indicates the generated message uses table-driven parsing. @@ -222,8 +207,9 @@ class MessageGenerator { std::unique_ptr message_layout_helper_; - SCCAnalyzer* scc_analyzer_; - string scc_name_; + MessageSCCAnalyzer* scc_analyzer_; + + std::map variables_; friend class FileGenerator; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator); @@ -232,6 +218,6 @@ class MessageGenerator { } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message_field.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message_field.cc index c1e15c52..659e3fae 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message_field.cc @@ -44,22 +44,6 @@ namespace compiler { namespace cpp { namespace { - -// When we are generating code for implicit weak fields, we need to insert some -// additional casts. These functions return the casted expression if -// implicit_weak_field is true but otherwise return the original expression. -// Ordinarily a static_cast is enough to cast google::protobuf::MessageLite* to a class -// deriving from it, but we need a reinterpret_cast in cases where the generated -// message is forward-declared but its full definition is not visible. -string StaticCast(const string& type, const string& expression, - bool implicit_weak_field) { - if (implicit_weak_field) { - return "static_cast< " + type + " >(" + expression + ")"; - } else { - return expression; - } -} - string ReinterpretCast(const string& type, const string& expression, bool implicit_weak_field) { if (implicit_weak_field) { @@ -71,16 +55,17 @@ string ReinterpretCast(const string& type, const string& expression, void SetMessageVariables(const FieldDescriptor* descriptor, const Options& options, bool implicit_weak, - std::map* variables) { + std::map* variables) { SetCommonFieldVariables(descriptor, variables, options); - (*variables)["type"] = FieldMessageTypeName(descriptor); + (*variables)["type"] = FieldMessageTypeName(descriptor, options); (*variables)["casted_member"] = ReinterpretCast( (*variables)["type"] + "*", (*variables)["name"] + "_", implicit_weak); (*variables)["type_default_instance"] = - DefaultInstanceName(descriptor->message_type()); + QualifiedDefaultInstanceName(descriptor->message_type(), options); (*variables)["type_reference_function"] = implicit_weak - ? (" " + ReferenceFunctionName(descriptor->message_type()) + "();\n") + ? (" " + ReferenceFunctionName(descriptor->message_type(), options) + + "();\n") : ""; (*variables)["stream_writer"] = (*variables)["declared_type"] + @@ -90,8 +75,7 @@ void SetMessageVariables(const FieldDescriptor* descriptor, // NOTE: Escaped here to unblock proto1->proto2 migration. // TODO(liujisi): Extend this to apply for other conflicting methods. (*variables)["release_name"] = - SafeFunctionName(descriptor->containing_type(), - descriptor, "release_"); + SafeFunctionName(descriptor->containing_type(), descriptor, "release_"); (*variables)["full_name"] = descriptor->full_name(); } @@ -101,9 +85,8 @@ void SetMessageVariables(const FieldDescriptor* descriptor, MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor, const Options& options, - SCCAnalyzer* scc_analyzer) - : FieldGenerator(options), - descriptor_(descriptor), + MessageSCCAnalyzer* scc_analyzer) + : FieldGenerator(descriptor, options), implicit_weak_field_( IsImplicitWeakField(descriptor, options, scc_analyzer)) { SetMessageVariables(descriptor, options, implicit_weak_field_, &variables_); @@ -111,366 +94,384 @@ MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor, MessageFieldGenerator::~MessageFieldGenerator() {} -void MessageFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { +void MessageFieldGenerator::GeneratePrivateMembers(io::Printer* printer) const { + Formatter format(printer, variables_); if (implicit_weak_field_) { - printer->Print(variables_, "::google::protobuf::MessageLite* $name$_;\n"); + format("::$proto_ns$::MessageLite* $name$_;\n"); } else { - printer->Print(variables_, "$type$* $name$_;\n"); + format("$type$* $name$_;\n"); } } -void MessageFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { - if (implicit_weak_field_) { - // These private accessors are used by MergeFrom and - // MergePartialFromCodedStream, and their purpose is to provide access to - // the field without creating a strong dependency on the message type. - printer->Print(variables_, - "private:\n" - "const ::google::protobuf::MessageLite& _internal_$name$() const;\n" - "::google::protobuf::MessageLite* _internal_mutable_$name$();\n" - "public:\n"); - } else { - // This inline accessor directly returns member field and is used in - // Serialize such that AFDO profile correctly captures access information to - // message fields under serialize. - printer->Print(variables_, - "private:\n" - "const $type$& _internal_$name$() const;\n" - "public:\n"); - } - printer->Print(variables_, - "$deprecated_attr$const $type$& $name$() const;\n"); - printer->Annotate("name", descriptor_); - printer->Print(variables_, "$deprecated_attr$$type$* $release_name$();\n"); - printer->Annotate("release_name", descriptor_); - printer->Print(variables_, - "$deprecated_attr$$type$* ${$mutable_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$set_allocated_$name$$}$" - "($type$* $name$);\n"); - printer->Annotate("{", "}", descriptor_); +void MessageFieldGenerator::GenerateAccessorDeclarations( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "$deprecated_attr$const $type$& ${1$$name$$}$() const;\n" + "$deprecated_attr$$type$* ${1$$release_name$$}$();\n" + "$deprecated_attr$$type$* ${1$mutable_$name$$}$();\n" + "$deprecated_attr$void ${1$set_allocated_$name$$}$" + "($type$* $name$);\n", + descriptor_); if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - "$deprecated_attr$void " - "${$unsafe_arena_set_allocated_$name$$}$(\n" - " $type$* $name$);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$$type$* ${$unsafe_arena_release_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); + format( + "$deprecated_attr$void " + "${1$unsafe_arena_set_allocated_$name$$}$(\n" + " $type$* $name$);\n" + "$deprecated_attr$$type$* ${1$unsafe_arena_release_$name$$}$();\n", + descriptor_); } } void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions( io::Printer* printer) const { - if (implicit_weak_field_) { - printer->Print(variables_, - "const ::google::protobuf::MessageLite& $classname$::_internal_$name$() const {\n" - " if ($name$_ != NULL) {\n" - " return *$name$_;\n" - " } else if (&$type_default_instance$ != NULL) {\n" - " return *reinterpret_cast(\n" - " &$type_default_instance$);\n" - " } else {\n" - " return " - "*::google::protobuf::internal::ImplicitWeakMessage::default_instance();\n" - " }\n" - "}\n"); - } + Formatter format(printer, variables_); if (SupportsArenas(descriptor_)) { - if (implicit_weak_field_) { - printer->Print(variables_, - "::google::protobuf::MessageLite* $classname$::_internal_mutable_$name$() {\n" - " $set_hasbit$\n" - " if ($name$_ == NULL) {\n" - " if (&$type_default_instance$ == NULL) {\n" - " $name$_ = ::google::protobuf::Arena::CreateMessage<\n" - " ::google::protobuf::internal::ImplicitWeakMessage>(\n" - " GetArenaNoVirtual());\n" - " } else {\n" - " $name$_ = reinterpret_cast(\n" - " &$type_default_instance$)->New(GetArenaNoVirtual());\n" - " }\n" + format( + "void $classname$::unsafe_arena_set_allocated_$name$(\n" + " $type$* $name$) {\n" + // If we're not on an arena, free whatever we were holding before. + // (If we are on arena, we can just forget the earlier pointer.) + " if (GetArenaNoVirtual() == nullptr) {\n" + " delete $name$_;\n" " }\n" - " return $name$_;\n" - "}\n"); - } - - printer->Print(variables_, - "void $classname$::unsafe_arena_set_allocated_$name$(\n" - " $type$* $name$) {\n" - // If we're not on an arena, free whatever we were holding before. - // (If we are on arena, we can just forget the earlier pointer.) - " if (GetArenaNoVirtual() == NULL) {\n" - " delete $name$_;\n" - " }\n" - " $name$_ = $name$;\n" - " if ($name$) {\n" - " $set_hasbit$\n" - " } else {\n" - " $clear_hasbit$\n" - " }\n" - " // @@protoc_insertion_point(field_unsafe_arena_set_allocated" - ":$full_name$)\n" - "}\n"); - } else if (implicit_weak_field_) { - printer->Print(variables_, - "::google::protobuf::MessageLite* $classname$::_internal_mutable_$name$() {\n" - " $set_hasbit$\n" - " if ($name$_ == NULL) {\n" - " if (&$type_default_instance$ == NULL) {\n" - " $name$_ = new ::google::protobuf::internal::ImplicitWeakMessage;\n" - " } else {\n" - " $name$_ = reinterpret_cast(\n" - " &$type_default_instance$)->New();\n" - " }\n" + " $name$_ = $name$;\n" + " if ($name$) {\n" + " $set_hasbit$\n" + " } else {\n" + " $clear_hasbit$\n" " }\n" - " return $name$_;\n" + " // @@protoc_insertion_point(field_unsafe_arena_set_allocated" + ":$full_name$)\n" "}\n"); } } -void MessageFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - if (!implicit_weak_field_) { - printer->Print(variables_, - "inline const $type$& $classname$::_internal_$name$() const {\n" - " return *$field_member$;\n" +void MessageFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "inline const $type$& $classname$::$name$() const {\n" + " const $type$* p = $casted_member$;\n" + " // @@protoc_insertion_point(field_get:$full_name$)\n" + " return p != nullptr ? *p : *reinterpret_cast(\n" + " &$type_default_instance$);\n" "}\n"); - } - printer->Print(variables_, - "inline const $type$& $classname$::$name$() const {\n" - " const $type$* p = $casted_member$;\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return p != NULL ? *p : *reinterpret_cast(\n" - " &$type_default_instance$);\n" - "}\n"); - printer->Print(variables_, - "inline $type$* $classname$::$release_name$() {\n" - " // @@protoc_insertion_point(field_release:$full_name$)\n" - "$type_reference_function$" - " $clear_hasbit$\n" - " $type$* temp = $casted_member$;\n"); - if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - " if (GetArenaNoVirtual() != NULL) {\n" - " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);\n" - " }\n"); - } - printer->Print(variables_, - " $name$_ = NULL;\n" - " return temp;\n" - "}\n"); - - if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - "inline $type$* $classname$::unsafe_arena_release_$name$() {\n" - " // @@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n" + format( + "inline $type$* $classname$::$release_name$() {\n" + " // @@protoc_insertion_point(field_release:$full_name$)\n" "$type_reference_function$" " $clear_hasbit$\n" - " $type$* temp = $casted_member$;\n" - " $name$_ = NULL;\n" + " $type$* temp = $casted_member$;\n"); + if (SupportsArenas(descriptor_)) { + format( + " if (GetArenaNoVirtual() != nullptr) {\n" + " temp = ::$proto_ns$::internal::DuplicateIfNonNull(temp);\n" + " }\n"); + } + format( + " $name$_ = nullptr;\n" " return temp;\n" "}\n"); + + if (SupportsArenas(descriptor_)) { + format( + "inline $type$* $classname$::unsafe_arena_release_$name$() {\n" + " // " + "@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n" + "$type_reference_function$" + " $clear_hasbit$\n" + " $type$* temp = $casted_member$;\n" + " $name$_ = nullptr;\n" + " return temp;\n" + "}\n"); } - printer->Print(variables_, - "inline $type$* $classname$::mutable_$name$() {\n" - " $set_hasbit$\n" - " if ($name$_ == NULL) {\n" - " auto* p = CreateMaybeMessage<$type$>(GetArenaNoVirtual());\n"); + format( + "inline $type$* $classname$::mutable_$name$() {\n" + " $set_hasbit$\n" + " if ($name$_ == nullptr) {\n" + " auto* p = CreateMaybeMessage<$type$>(GetArenaNoVirtual());\n"); if (implicit_weak_field_) { - printer->Print(variables_, - " $name$_ = reinterpret_cast<::google::protobuf::MessageLite*>(p);\n"); + format(" $name$_ = reinterpret_cast<::$proto_ns$::MessageLite*>(p);\n"); } else { - printer->Print(variables_, - " $name$_ = p;\n"); + format(" $name$_ = p;\n"); } - printer->Print(variables_, - " }\n" - " // @@protoc_insertion_point(field_mutable:$full_name$)\n" - " return $casted_member$;\n" - "}\n"); + format( + " }\n" + " // @@protoc_insertion_point(field_mutable:$full_name$)\n" + " return $casted_member$;\n" + "}\n"); // We handle the most common case inline, and delegate less common cases to // the slow fallback function. - printer->Print(variables_, - "inline void $classname$::set_allocated_$name$($type$* $name$) {\n" - " ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();\n"); - printer->Print(variables_, - " if (message_arena == NULL) {\n"); + format( + "inline void $classname$::set_allocated_$name$($type$* $name$) {\n" + " ::$proto_ns$::Arena* message_arena = GetArenaNoVirtual();\n"); + format(" if (message_arena == nullptr) {\n"); if (IsCrossFileMessage(descriptor_)) { - printer->Print(variables_, - " delete reinterpret_cast< ::google::protobuf::MessageLite*>($name$_);\n"); + format( + " delete reinterpret_cast< ::$proto_ns$::MessageLite*>($name$_);\n"); } else { - printer->Print(variables_, - " delete $name$_;\n"); + format(" delete $name$_;\n"); } - printer->Print(variables_, - " }\n" - " if ($name$) {\n"); + format( + " }\n" + " if ($name$) {\n"); if (SupportsArenas(descriptor_->message_type()) && IsCrossFileMessage(descriptor_)) { // We have to read the arena through the virtual method, because the type // isn't defined in this file. - printer->Print(variables_, - " ::google::protobuf::Arena* submessage_arena =\n" - " reinterpret_cast<::google::protobuf::MessageLite*>($name$)->GetArena();\n"); + format( + " ::$proto_ns$::Arena* submessage_arena =\n" + " " + "reinterpret_cast<::$proto_ns$::MessageLite*>($name$)->GetArena();\n"); } else if (!SupportsArenas(descriptor_->message_type())) { - printer->Print(variables_, - " ::google::protobuf::Arena* submessage_arena = NULL;\n"); + format(" ::$proto_ns$::Arena* submessage_arena = nullptr;\n"); } else { - printer->Print(variables_, - " ::google::protobuf::Arena* submessage_arena =\n" - " ::google::protobuf::Arena::GetArena($name$);\n"); + format( + " ::$proto_ns$::Arena* submessage_arena =\n" + " ::$proto_ns$::Arena::GetArena($name$);\n"); } - printer->Print(variables_, - " if (message_arena != submessage_arena) {\n" - " $name$ = ::google::protobuf::internal::GetOwnedMessage(\n" - " message_arena, $name$, submessage_arena);\n" - " }\n" - " $set_hasbit$\n" - " } else {\n" - " $clear_hasbit$\n" - " }\n"); + format( + " if (message_arena != submessage_arena) {\n" + " $name$ = ::$proto_ns$::internal::GetOwnedMessage(\n" + " message_arena, $name$, submessage_arena);\n" + " }\n" + " $set_hasbit$\n" + " } else {\n" + " $clear_hasbit$\n" + " }\n"); if (implicit_weak_field_) { - printer->Print(variables_, - " $name$_ = reinterpret_cast($name$);\n"); + format(" $name$_ = reinterpret_cast($name$);\n"); } else { - printer->Print(variables_, - " $name$_ = $name$;\n"); + format(" $name$_ = $name$;\n"); } - printer->Print(variables_, - " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n" - "}\n"); + format( + " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n" + "}\n"); } -void MessageFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { +void MessageFieldGenerator::GenerateInternalAccessorDeclarations( + io::Printer* printer) const { + Formatter format(printer, variables_); + if (implicit_weak_field_) { + format( + "static const ::$proto_ns$::MessageLite& $name$(" + "const $classname$* msg);\n" + "static ::$proto_ns$::MessageLite* mutable_$name$(" + "$classname$* msg);\n"); + } else { + format("static const $type$& $name$(const $classname$* msg);\n"); + } +} + +void MessageFieldGenerator::GenerateInternalAccessorDefinitions( + io::Printer* printer) const { + // In theory, these accessors could be inline in HasBitSetters. However, in + // practice, the linker is then not able to throw them out making implicit + // weak dependencies not work at all. + Formatter format(printer, variables_); + if (implicit_weak_field_) { + // These private accessors are used by MergeFrom and + // MergePartialFromCodedStream, and their purpose is to provide access to + // the field without creating a strong dependency on the message type. + format( + "const ::$proto_ns$::MessageLite& $classname$::HasBitSetters::$name$(\n" + " const $classname$* msg) {\n" + " if (msg->$name$_ != nullptr) {\n" + " return *msg->$name$_;\n" + " } else if (&$type_default_instance$ != nullptr) {\n" + " return *reinterpret_cast(\n" + " &$type_default_instance$);\n" + " } else {\n" + " return " + "*::$proto_ns$::internal::ImplicitWeakMessage::default_instance();\n" + " }\n" + "}\n"); + if (SupportsArenas(descriptor_)) { + format( + "::$proto_ns$::MessageLite*\n" + "$classname$::HasBitSetters::mutable_$name$($classname$* msg) {\n"); + if (HasFieldPresence(descriptor_->file())) { + format(" msg->$set_hasbit$\n"); + } + format( + " if (msg->$name$_ == nullptr) {\n" + " if (&$type_default_instance$ == nullptr) {\n" + " msg->$name$_ = ::$proto_ns$::Arena::CreateMessage<\n" + " ::$proto_ns$::internal::ImplicitWeakMessage>(\n" + " msg->GetArenaNoVirtual());\n" + " } else {\n" + " msg->$name$_ = reinterpret_cast(\n" + " &$type_default_instance$)->New(" + "msg->GetArenaNoVirtual());\n" + " }\n" + " }\n" + " return msg->$name$_;\n" + "}\n"); + } else { + format( + "::$proto_ns$::MessageLite*\n" + "$classname$::HasBitSetters::mutable_$name$($classname$* msg) {\n"); + if (HasFieldPresence(descriptor_->file())) { + format(" msg->$set_hasbit$\n"); + } + format( + " if (msg->$name$_ == nullptr) {\n" + " if (&$type_default_instance$ == nullptr) {\n" + " msg->$name$_ = " + "new ::$proto_ns$::internal::ImplicitWeakMessage;\n" + " } else {\n" + " msg->$name$_ = " + "reinterpret_cast(\n" + " &$type_default_instance$)->New();\n" + " }\n" + " }\n" + " return msg->$name$_;\n" + "}\n"); + } + } else { + // This inline accessor directly returns member field and is used in + // Serialize such that AFDO profile correctly captures access information to + // message fields under serialize. + format( + "const $type$&\n" + "$classname$::HasBitSetters::$name$(const $classname$* msg) {\n" + " return *msg->$field_member$;\n" + "}\n"); + } +} + +void MessageFieldGenerator::GenerateClearingCode(io::Printer* printer) const { + Formatter format(printer, variables_); if (!HasFieldPresence(descriptor_->file())) { // If we don't have has-bits, message presence is indicated only by ptr != // NULL. Thus on clear, we need to delete the object. - printer->Print(variables_, - "if (GetArenaNoVirtual() == NULL && $name$_ != NULL) {\n" - " delete $name$_;\n" - "}\n" - "$name$_ = NULL;\n"); + format( + "if (GetArenaNoVirtual() == nullptr && $name$_ != nullptr) {\n" + " delete $name$_;\n" + "}\n" + "$name$_ = nullptr;\n"); } else { - printer->Print(variables_, - "if ($name$_ != NULL) $name$_->Clear();\n"); + format("if ($name$_ != nullptr) $name$_->Clear();\n"); } } -void MessageFieldGenerator:: -GenerateMessageClearingCode(io::Printer* printer) const { +void MessageFieldGenerator::GenerateMessageClearingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); if (!HasFieldPresence(descriptor_->file())) { // If we don't have has-bits, message presence is indicated only by ptr != // NULL. Thus on clear, we need to delete the object. - printer->Print(variables_, - "if (GetArenaNoVirtual() == NULL && $name$_ != NULL) {\n" - " delete $name$_;\n" - "}\n" - "$name$_ = NULL;\n"); + format( + "if (GetArenaNoVirtual() == nullptr && $name$_ != nullptr) {\n" + " delete $name$_;\n" + "}\n" + "$name$_ = nullptr;\n"); } else { - printer->Print(variables_, - "GOOGLE_DCHECK($name$_ != NULL);\n" - "$name$_->Clear();\n"); + format( + "$DCHK$($name$_ != nullptr);\n" + "$name$_->Clear();\n"); } } -void MessageFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { +void MessageFieldGenerator::GenerateMergingCode(io::Printer* printer) const { + Formatter format(printer, variables_); if (implicit_weak_field_) { - printer->Print(variables_, - "_internal_mutable_$name$()->CheckTypeAndMergeFrom(\n" - " from._internal_$name$());\n"); + format( + "HasBitSetters::mutable_$name$(this)->CheckTypeAndMergeFrom(\n" + " HasBitSetters::$name$(&from));\n"); } else { - printer->Print(variables_, - "mutable_$name$()->$type$::MergeFrom(from.$name$());\n"); + format("mutable_$name$()->$type$::MergeFrom(from.$name$());\n"); } } -void MessageFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - printer->Print(variables_, "swap($name$_, other->$name$_);\n"); +void MessageFieldGenerator::GenerateSwappingCode(io::Printer* printer) const { + Formatter format(printer, variables_); + format("swap($name$_, other->$name$_);\n"); } -void MessageFieldGenerator:: -GenerateDestructorCode(io::Printer* printer) const { - // TODO(gerbens) Remove this when we don't need to destruct default instances. - // In google3 a default instance will never get deleted so we don't need to - // worry about that but in opensource protobuf default instances are deleted - // in shutdown process and we need to take special care when handling them. - printer->Print(variables_, - "if (this != internal_default_instance()) "); - printer->Print(variables_, "delete $name$_;\n"); +void MessageFieldGenerator::GenerateDestructorCode(io::Printer* printer) const { + Formatter format(printer, variables_); + if (options_.opensource_runtime) { + // TODO(gerbens) Remove this when we don't need to destruct default + // instances. In google3 a default instance will never get deleted so we + // don't need to worry about that but in opensource protobuf default + // instances are deleted in shutdown process and we need to take special + // care when handling them. + format("if (this != internal_default_instance()) "); + } + format("delete $name$_;\n"); } -void MessageFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = NULL;\n"); +void MessageFieldGenerator::GenerateConstructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_ = nullptr;\n"); } -void MessageFieldGenerator:: -GenerateCopyConstructorCode(io::Printer* printer) const { - printer->Print(variables_, - "if (from.has_$name$()) {\n" - " $name$_ = new $type$(*from.$name$_);\n" - "} else {\n" - " $name$_ = NULL;\n" - "}\n"); +void MessageFieldGenerator::GenerateCopyConstructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "if (from.has_$name$()) {\n" + " $name$_ = new $type$(*from.$name$_);\n" + "} else {\n" + " $name$_ = nullptr;\n" + "}\n"); } -void MessageFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { +void MessageFieldGenerator::GenerateMergeFromCodedStream( + io::Printer* printer) const { + Formatter format(printer, variables_); if (implicit_weak_field_) { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(\n" - " input, _internal_mutable_$name$()));\n"); + format( + "DO_(::$proto_ns$::internal::WireFormatLite::ReadMessage(\n" + " input, HasBitSetters::mutable_$name$(this)));\n"); } else if (descriptor_->type() == FieldDescriptor::TYPE_MESSAGE) { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(\n" - " input, mutable_$name$()));\n"); + format( + "DO_(::$proto_ns$::internal::WireFormatLite::ReadMessage(\n" + " input, mutable_$name$()));\n"); } else { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::ReadGroup(\n" - " $number$, input, mutable_$name$()));\n"); + format( + "DO_(::$proto_ns$::internal::WireFormatLite::ReadGroup(\n" + " $number$, input, mutable_$name$()));\n"); } } -void MessageFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { - printer->Print(variables_, - "::google::protobuf::internal::WireFormatLite::Write$stream_writer$(\n" - " $number$, this->_internal_$name$(), output);\n"); +void MessageFieldGenerator::GenerateSerializeWithCachedSizes( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "::$proto_ns$::internal::WireFormatLite::Write$stream_writer$(\n" + " $number$, HasBitSetters::$name$(this), output);\n"); } -void MessageFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { - printer->Print(variables_, - "target = ::google::protobuf::internal::WireFormatLite::\n" - " InternalWrite$declared_type$ToArray(\n" - " $number$, this->_internal_$name$(), deterministic, target);\n"); +void MessageFieldGenerator::GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "target = ::$proto_ns$::internal::WireFormatLite::\n" + " InternalWrite$declared_type$ToArray(\n" + " $number$, HasBitSetters::$name$(this), target);\n"); } -void MessageFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { - printer->Print(variables_, - "total_size += $tag_size$ +\n" - " ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n" - " *$field_member$);\n"); +void MessageFieldGenerator::GenerateByteSize(io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "total_size += $tag_size$ +\n" + " ::$proto_ns$::internal::WireFormatLite::$declared_type$Size(\n" + " *$field_member$);\n"); } // =================================================================== MessageOneofFieldGenerator::MessageOneofFieldGenerator( const FieldDescriptor* descriptor, const Options& options, - SCCAnalyzer* scc_analyzer) + MessageSCCAnalyzer* scc_analyzer) : MessageFieldGenerator(descriptor, options, scc_analyzer) { SetCommonOneofFieldVariables(descriptor, &variables_); } @@ -479,147 +480,143 @@ MessageOneofFieldGenerator::~MessageOneofFieldGenerator() {} void MessageOneofFieldGenerator::GenerateNonInlineAccessorDefinitions( io::Printer* printer) const { - printer->Print(variables_, - "void $classname$::set_allocated_$name$($type$* $name$) {\n" - " ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();\n" - " clear_$oneof_name$();\n" - " if ($name$) {\n"); + Formatter format(printer, variables_); + format( + "void $classname$::set_allocated_$name$($type$* $name$) {\n" + " ::$proto_ns$::Arena* message_arena = GetArenaNoVirtual();\n" + " clear_$oneof_name$();\n" + " if ($name$) {\n"); if (SupportsArenas(descriptor_->message_type()) && descriptor_->file() != descriptor_->message_type()->file()) { // We have to read the arena through the virtual method, because the type // isn't defined in this file. - printer->Print(variables_, - " ::google::protobuf::Arena* submessage_arena =\n" - " reinterpret_cast<::google::protobuf::MessageLite*>($name$)->GetArena();\n"); + format( + " ::$proto_ns$::Arena* submessage_arena =\n" + " " + "reinterpret_cast<::$proto_ns$::MessageLite*>($name$)->GetArena();\n"); } else if (!SupportsArenas(descriptor_->message_type())) { - printer->Print(variables_, - " ::google::protobuf::Arena* submessage_arena = NULL;\n"); + format(" ::$proto_ns$::Arena* submessage_arena = nullptr;\n"); } else { - printer->Print(variables_, - " ::google::protobuf::Arena* submessage_arena =\n" - " ::google::protobuf::Arena::GetArena($name$);\n"); + format( + " ::$proto_ns$::Arena* submessage_arena =\n" + " ::$proto_ns$::Arena::GetArena($name$);\n"); } - printer->Print(variables_, - " if (message_arena != submessage_arena) {\n" - " $name$ = ::google::protobuf::internal::GetOwnedMessage(\n" - " message_arena, $name$, submessage_arena);\n" - " }\n" - " set_has_$name$();\n" - " $field_member$ = $name$;\n" - " }\n" - " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n" - "}\n"); -} - -void MessageOneofFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - if (!implicit_weak_field_) { - printer->Print(variables_, - "inline const $type$& $classname$::_internal_$name$() const {\n" - " return *$field_member$;\n" - "}\n"); - } - printer->Print(variables_, - "inline $type$* $classname$::$release_name$() {\n" - " // @@protoc_insertion_point(field_release:$full_name$)\n" - " if (has_$name$()) {\n" - " clear_has_$oneof_name$();\n" - " $type$* temp = $field_member$;\n"); - if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - " if (GetArenaNoVirtual() != NULL) {\n" - " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);\n" - " }\n"); - } - printer->Print(variables_, - " $field_member$ = NULL;\n" - " return temp;\n" - " } else {\n" - " return NULL;\n" - " }\n" - "}\n"); - - printer->Print(variables_, - "inline const $type$& $classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return has_$name$()\n" - " ? *$field_member$\n" - " : *reinterpret_cast< $type$*>(&$type_default_instance$);\n" - "}\n"); - - if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - "inline $type$* $classname$::unsafe_arena_release_$name$() {\n" - " // @@protoc_insertion_point(field_unsafe_arena_release" - ":$full_name$)\n" - " if (has_$name$()) {\n" - " clear_has_$oneof_name$();\n" - " $type$* temp = $field_member$;\n" - " $field_member$ = NULL;\n" - " return temp;\n" - " } else {\n" - " return NULL;\n" - " }\n" - "}\n" - "inline void $classname$::unsafe_arena_set_allocated_$name$" - "($type$* $name$) {\n" - // We rely on the oneof clear method to free the earlier contents of this - // oneof. We can directly use the pointer we're given to set the new - // value. - " clear_$oneof_name$();\n" - " if ($name$) {\n" + format( + " if (message_arena != submessage_arena) {\n" + " $name$ = ::$proto_ns$::internal::GetOwnedMessage(\n" + " message_arena, $name$, submessage_arena);\n" + " }\n" " set_has_$name$();\n" " $field_member$ = $name$;\n" " }\n" - " // @@protoc_insertion_point(field_unsafe_arena_set_allocated:" - "$full_name$)\n" + " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n" "}\n"); - } - - printer->Print(variables_, - "inline $type$* $classname$::mutable_$name$() {\n" - " if (!has_$name$()) {\n" - " clear_$oneof_name$();\n" - " set_has_$name$();\n" - " $field_member$ = CreateMaybeMessage< $type$ >(\n" - " GetArenaNoVirtual());\n" - " }\n" - " // @@protoc_insertion_point(field_mutable:$full_name$)\n" - " return $field_member$;\n" - "}\n"); } -void MessageOneofFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { +void MessageOneofFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "inline $type$* $classname$::$release_name$() {\n" + " // @@protoc_insertion_point(field_release:$full_name$)\n" + " if (has_$name$()) {\n" + " clear_has_$oneof_name$();\n" + " $type$* temp = $field_member$;\n"); if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - "if (GetArenaNoVirtual() == NULL) {\n" - " delete $field_member$;\n" + format( + " if (GetArenaNoVirtual() != nullptr) {\n" + " temp = ::$proto_ns$::internal::DuplicateIfNonNull(temp);\n" + " }\n"); + } + format( + " $field_member$ = nullptr;\n" + " return temp;\n" + " } else {\n" + " return nullptr;\n" + " }\n" "}\n"); + + format( + "inline const $type$& $classname$::$name$() const {\n" + " // @@protoc_insertion_point(field_get:$full_name$)\n" + " return has_$name$()\n" + " ? *$field_member$\n" + " : *reinterpret_cast< $type$*>(&$type_default_instance$);\n" + "}\n"); + + if (SupportsArenas(descriptor_)) { + format( + "inline $type$* $classname$::unsafe_arena_release_$name$() {\n" + " // @@protoc_insertion_point(field_unsafe_arena_release" + ":$full_name$)\n" + " if (has_$name$()) {\n" + " clear_has_$oneof_name$();\n" + " $type$* temp = $field_member$;\n" + " $field_member$ = nullptr;\n" + " return temp;\n" + " } else {\n" + " return nullptr;\n" + " }\n" + "}\n" + "inline void $classname$::unsafe_arena_set_allocated_$name$" + "($type$* $name$) {\n" + // We rely on the oneof clear method to free the earlier contents of + // this oneof. We can directly use the pointer we're given to set the + // new value. + " clear_$oneof_name$();\n" + " if ($name$) {\n" + " set_has_$name$();\n" + " $field_member$ = $name$;\n" + " }\n" + " // @@protoc_insertion_point(field_unsafe_arena_set_allocated:" + "$full_name$)\n" + "}\n"); + } + + format( + "inline $type$* $classname$::mutable_$name$() {\n" + " if (!has_$name$()) {\n" + " clear_$oneof_name$();\n" + " set_has_$name$();\n" + " $field_member$ = CreateMaybeMessage< $type$ >(\n" + " GetArenaNoVirtual());\n" + " }\n" + " // @@protoc_insertion_point(field_mutable:$full_name$)\n" + " return $field_member$;\n" + "}\n"); +} + +void MessageOneofFieldGenerator::GenerateClearingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + if (SupportsArenas(descriptor_)) { + format( + "if (GetArenaNoVirtual() == nullptr) {\n" + " delete $field_member$;\n" + "}\n"); } else { - printer->Print(variables_, - "delete $field_member$;\n"); + format("delete $field_member$;\n"); } } -void MessageOneofFieldGenerator:: -GenerateMessageClearingCode(io::Printer* printer) const { +void MessageOneofFieldGenerator::GenerateMessageClearingCode( + io::Printer* printer) const { GenerateClearingCode(printer); } -void MessageOneofFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { +void MessageOneofFieldGenerator::GenerateSwappingCode( + io::Printer* printer) const { // Don't print any swapping code. Swapping the union will swap this field. } -void MessageOneofFieldGenerator:: -GenerateDestructorCode(io::Printer* printer) const { +void MessageOneofFieldGenerator::GenerateDestructorCode( + io::Printer* printer) const { // We inherit from MessageFieldGenerator, so we need to override the default // behavior. } -void MessageOneofFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { +void MessageOneofFieldGenerator::GenerateConstructorCode( + io::Printer* printer) const { // Don't print any constructor code. The field is in a union. We allocate // space only when this field is used. } @@ -628,9 +625,8 @@ GenerateConstructorCode(io::Printer* printer) const { RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator( const FieldDescriptor* descriptor, const Options& options, - SCCAnalyzer* scc_analyzer) - : FieldGenerator(options), - descriptor_(descriptor), + MessageSCCAnalyzer* scc_analyzer) + : FieldGenerator(descriptor, options), implicit_weak_field_( IsImplicitWeakField(descriptor, options, scc_analyzer)) { SetMessageVariables(descriptor, options, implicit_weak_field_, &variables_); @@ -638,196 +634,190 @@ RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator( RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() {} -void RepeatedMessageFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { - printer->Print(variables_, - "::google::protobuf::RepeatedPtrField< $type$ > $name$_;\n"); +void RepeatedMessageFieldGenerator::GeneratePrivateMembers( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("::$proto_ns$::RepeatedPtrField< $type$ > $name$_;\n"); } -void RepeatedMessageFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { - printer->Print(variables_, - "$deprecated_attr$$type$* ${$mutable_$name$$}$(int index);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$::google::protobuf::RepeatedPtrField< $type$ >*\n" - " ${$mutable_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); - - printer->Print(variables_, - "$deprecated_attr$const $type$& $name$(int index) const;\n"); - printer->Annotate("name", descriptor_); - printer->Print(variables_, "$deprecated_attr$$type$* ${$add_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$const ::google::protobuf::RepeatedPtrField< $type$ >&\n" - " $name$() const;\n"); - printer->Annotate("name", descriptor_); +void RepeatedMessageFieldGenerator::GenerateAccessorDeclarations( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "$deprecated_attr$$type$* ${1$mutable_$name$$}$(int index);\n" + "$deprecated_attr$::$proto_ns$::RepeatedPtrField< $type$ >*\n" + " ${1$mutable_$name$$}$();\n" + "$deprecated_attr$const $type$& ${1$$name$$}$(int index) const;\n" + "$deprecated_attr$$type$* ${1$add_$name$$}$();\n" + "$deprecated_attr$const ::$proto_ns$::RepeatedPtrField< $type$ >&\n" + " ${1$$name$$}$() const;\n", + descriptor_); } -void RepeatedMessageFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - printer->Print(variables_, - "inline $type$* $classname$::mutable_$name$(int index) {\n" - // TODO(dlj): move insertion points - " // @@protoc_insertion_point(field_mutable:$full_name$)\n" - "$type_reference_function$" - " return $name$_.Mutable(index);\n" - "}\n" - "inline ::google::protobuf::RepeatedPtrField< $type$ >*\n" - "$classname$::mutable_$name$() {\n" - " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n" - "$type_reference_function$" - " return &$name$_;\n" - "}\n"); +void RepeatedMessageFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "inline $type$* $classname$::mutable_$name$(int index) {\n" + // TODO(dlj): move insertion points + " // @@protoc_insertion_point(field_mutable:$full_name$)\n" + "$type_reference_function$" + " return $name$_.Mutable(index);\n" + "}\n" + "inline ::$proto_ns$::RepeatedPtrField< $type$ >*\n" + "$classname$::mutable_$name$() {\n" + " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n" + "$type_reference_function$" + " return &$name$_;\n" + "}\n"); if (options_.safe_boundary_check) { - printer->Print(variables_, - "inline const $type$& $classname$::$name$(int index) const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return $name$_.InternalCheckedGet(index,\n" - " *reinterpret_cast(&$type_default_instance$));\n" - "}\n"); + format( + "inline const $type$& $classname$::$name$(int index) const {\n" + " // @@protoc_insertion_point(field_get:$full_name$)\n" + " return $name$_.InternalCheckedGet(index,\n" + " *reinterpret_cast(&$type_default_instance$));\n" + "}\n"); } else { - printer->Print(variables_, - "inline const $type$& $classname$::$name$(int index) const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" + format( + "inline const $type$& $classname$::$name$(int index) const {\n" + " // @@protoc_insertion_point(field_get:$full_name$)\n" + "$type_reference_function$" + " return $name$_.Get(index);\n" + "}\n"); + } + + format( + "inline $type$* $classname$::add_$name$() {\n" + " // @@protoc_insertion_point(field_add:$full_name$)\n" + " return $name$_.Add();\n" + "}\n"); + + format( + "inline const ::$proto_ns$::RepeatedPtrField< $type$ >&\n" + "$classname$::$name$() const {\n" + " // @@protoc_insertion_point(field_list:$full_name$)\n" "$type_reference_function$" - " return $name$_.Get(index);\n" + " return $name$_;\n" "}\n"); - } - - printer->Print(variables_, - "inline $type$* $classname$::add_$name$() {\n" - " // @@protoc_insertion_point(field_add:$full_name$)\n" - " return $name$_.Add();\n" - "}\n"); - - printer->Print(variables_, - "inline const ::google::protobuf::RepeatedPtrField< $type$ >&\n" - "$classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_list:$full_name$)\n" - "$type_reference_function$" - " return $name$_;\n" - "}\n"); } -void RepeatedMessageFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { +void RepeatedMessageFieldGenerator::GenerateClearingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); if (implicit_weak_field_) { - printer->Print( - variables_, + format( "CastToBase(&$name$_)->Clear<" - "::google::protobuf::internal::ImplicitWeakTypeHandler<$type$>>();\n"); + "::$proto_ns$::internal::ImplicitWeakTypeHandler<$type$>>();\n"); } else { - printer->Print(variables_, "$name$_.Clear();\n"); + format("$name$_.Clear();\n"); } } -void RepeatedMessageFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { +void RepeatedMessageFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); if (implicit_weak_field_) { - printer->Print( - variables_, + format( "CastToBase(&$name$_)->MergeFrom<" - "::google::protobuf::internal::ImplicitWeakTypeHandler<$type$>>(CastToBase(" + "::$proto_ns$::internal::ImplicitWeakTypeHandler<$type$>>(CastToBase(" "from.$name$_));\n"); } else { - printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n"); + format("$name$_.MergeFrom(from.$name$_);\n"); } } -void RepeatedMessageFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - printer->Print( - variables_, - "CastToBase(&$name$_)->InternalSwap(CastToBase(&other->$name$_));\n"); +void RepeatedMessageFieldGenerator::GenerateSwappingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("CastToBase(&$name$_)->InternalSwap(CastToBase(&other->$name$_));\n"); } -void RepeatedMessageFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { +void RepeatedMessageFieldGenerator::GenerateConstructorCode( + io::Printer* printer) const { // Not needed for repeated fields. } -void RepeatedMessageFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { +void RepeatedMessageFieldGenerator::GenerateMergeFromCodedStream( + io::Printer* printer) const { + Formatter format(printer, variables_); if (descriptor_->type() == FieldDescriptor::TYPE_MESSAGE) { if (implicit_weak_field_) { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::" - "ReadMessage(input, CastToBase(&$name$_)->AddWeak(\n" - " reinterpret_cast(\n" - " &$type_default_instance$))));\n"); + format( + "DO_(::$proto_ns$::internal::WireFormatLite::" + "ReadMessage(input, CastToBase(&$name$_)->AddWeak(\n" + " reinterpret_cast(\n" + " &$type_default_instance$))));\n"); } else { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::" - "ReadMessage(\n" - " input, add_$name$()));\n"); + format( + "DO_(::$proto_ns$::internal::WireFormatLite::" + "ReadMessage(\n" + " input, add_$name$()));\n"); } } else { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::" - "ReadGroup($number$, input, add_$name$()));\n"); + format( + "DO_(::$proto_ns$::internal::WireFormatLite::" + "ReadGroup($number$, input, add_$name$()));\n"); } } -void RepeatedMessageFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { - printer->Print(variables_, - "for (unsigned int i = 0,\n" - " n = static_cast(this->$name$_size()); i < n; i++) {\n" - " ::google::protobuf::internal::WireFormatLite::Write$stream_writer$(\n" - " $number$,\n"); +void RepeatedMessageFieldGenerator::GenerateSerializeWithCachedSizes( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "for (unsigned int i = 0,\n" + " n = static_cast(this->$name$_size()); i < n; i++) {\n" + " ::$proto_ns$::internal::WireFormatLite::Write$stream_writer$(\n" + " $number$,\n"); if (implicit_weak_field_) { - printer->Print( - variables_, + format( " CastToBase($name$_).Get<" - "::google::protobuf::internal::ImplicitWeakTypeHandler<$type$>>(" + "::$proto_ns$::internal::ImplicitWeakTypeHandler<$type$>>(" "static_cast(i)),\n"); } else { - printer->Print(variables_, - " this->$name$(static_cast(i)),\n"); + format(" this->$name$(static_cast(i)),\n"); } - printer->Print(variables_, - " output);\n" - "}\n"); + format( + " output);\n" + "}\n"); } -void RepeatedMessageFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { - printer->Print(variables_, - "for (unsigned int i = 0,\n" - " n = static_cast(this->$name$_size()); i < n; i++) {\n" - " target = ::google::protobuf::internal::WireFormatLite::\n" - " InternalWrite$declared_type$ToArray(\n" - " $number$, this->$name$(static_cast(i)), deterministic, target);\n" - "}\n"); +void RepeatedMessageFieldGenerator::GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "for (unsigned int i = 0,\n" + " n = static_cast(this->$name$_size()); i < n; i++) {\n" + " target = ::$proto_ns$::internal::WireFormatLite::\n" + " InternalWrite$declared_type$ToArray(\n" + " $number$, this->$name$(static_cast(i)), target);\n" + "}\n"); } -void RepeatedMessageFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { - printer->Print(variables_, - "{\n" - " unsigned int count = static_cast(this->$name$_size());\n"); - printer->Indent(); - printer->Print(variables_, - "total_size += $tag_size$UL * count;\n" - "for (unsigned int i = 0; i < count; i++) {\n" - " total_size +=\n" - " ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n"); +void RepeatedMessageFieldGenerator::GenerateByteSize( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "{\n" + " unsigned int count = static_cast(this->$name$_size());\n"); + format.Indent(); + format( + "total_size += $tag_size$UL * count;\n" + "for (unsigned int i = 0; i < count; i++) {\n" + " total_size +=\n" + " ::$proto_ns$::internal::WireFormatLite::$declared_type$Size(\n"); if (implicit_weak_field_) { - printer->Print( - variables_, + format( " CastToBase($name$_).Get<" - "::google::protobuf::internal::ImplicitWeakTypeHandler<$type$>>(" + "::$proto_ns$::internal::ImplicitWeakTypeHandler<$type$>>(" "static_cast(i)));\n"); } else { - printer->Print(variables_, - " this->$name$(static_cast(i)));\n"); + format(" this->$name$(static_cast(i)));\n"); } - printer->Print(variables_, "}\n"); - printer->Outdent(); - printer->Print("}\n"); + format("}\n"); + format.Outdent(); + format("}\n"); } } // namespace cpp diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message_field.h b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message_field.h index 6879539c..eed8e4f5 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message_field.h @@ -48,7 +48,8 @@ namespace cpp { class MessageFieldGenerator : public FieldGenerator { public: MessageFieldGenerator(const FieldDescriptor* descriptor, - const Options& options, SCCAnalyzer* scc_analyzer); + const Options& options, + MessageSCCAnalyzer* scc_analyzer); ~MessageFieldGenerator(); // implements FieldGenerator --------------------------------------- @@ -56,6 +57,8 @@ class MessageFieldGenerator : public FieldGenerator { void GenerateAccessorDeclarations(io::Printer* printer) const; void GenerateInlineAccessorDefinitions(io::Printer* printer) const; void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const; + void GenerateInternalAccessorDeclarations(io::Printer* printer) const; + void GenerateInternalAccessorDefinitions(io::Printer* printer) const; void GenerateClearingCode(io::Printer* printer) const; void GenerateMessageClearingCode(io::Printer* printer) const; void GenerateMergingCode(io::Printer* printer) const; @@ -69,9 +72,7 @@ class MessageFieldGenerator : public FieldGenerator { void GenerateByteSize(io::Printer* printer) const; protected: - const FieldDescriptor* descriptor_; const bool implicit_weak_field_; - std::map variables_; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator); @@ -80,7 +81,8 @@ class MessageFieldGenerator : public FieldGenerator { class MessageOneofFieldGenerator : public MessageFieldGenerator { public: MessageOneofFieldGenerator(const FieldDescriptor* descriptor, - const Options& options, SCCAnalyzer* scc_analyzer); + const Options& options, + MessageSCCAnalyzer* scc_analyzer); ~MessageOneofFieldGenerator(); // implements FieldGenerator --------------------------------------- @@ -103,7 +105,7 @@ class RepeatedMessageFieldGenerator : public FieldGenerator { public: RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor, const Options& options, - SCCAnalyzer* scc_analyzer); + MessageSCCAnalyzer* scc_analyzer); ~RepeatedMessageFieldGenerator(); // implements FieldGenerator --------------------------------------- @@ -121,9 +123,7 @@ class RepeatedMessageFieldGenerator : public FieldGenerator { void GenerateByteSize(io::Printer* printer) const; private: - const FieldDescriptor* descriptor_; const bool implicit_weak_field_; - std::map variables_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator); }; @@ -131,6 +131,6 @@ class RepeatedMessageFieldGenerator : public FieldGenerator { } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_FIELD_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h index d502a6f0..67eeff0a 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h @@ -56,6 +56,6 @@ class MessageLayoutHelper { } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_LAYOUT_HELPER_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_options.h b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_options.h index f09885be..6616e4ba 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_options.h +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_options.h @@ -35,7 +35,6 @@ #include -#include namespace google { namespace protobuf { namespace compiler { @@ -43,41 +42,35 @@ class AccessInfoMap; namespace cpp { +enum class EnforceOptimizeMode { + kNoEnforcement, // Use the runtime specified by the file specific options. + kSpeed, // This is the full runtime. + kLiteRuntime, +}; + // Generator options (see generator.cc for a description of each): struct Options { - Options() - : safe_boundary_check(false), - proto_h(false), - transitive_pb_h(true), - annotate_headers(false), - enforce_lite(false), - table_driven_parsing(false), - table_driven_serialization(false), - lite_implicit_weak_fields(false), - bootstrap(false), - num_cc_files(0), - access_info_map(NULL) {} - - string dllexport_decl; - bool safe_boundary_check; - bool proto_h; - bool transitive_pb_h; - bool annotate_headers; - bool enforce_lite; - bool table_driven_parsing; - bool table_driven_serialization; - bool lite_implicit_weak_fields; - bool bootstrap; - int num_cc_files; - string annotation_pragma_name; - string annotation_guard_name; - const AccessInfoMap* access_info_map; + std::string dllexport_decl; + bool safe_boundary_check = false; + bool proto_h = false; + bool transitive_pb_h = true; + bool annotate_headers = false; + EnforceOptimizeMode enforce_mode = EnforceOptimizeMode::kNoEnforcement; + bool table_driven_parsing = false; + bool table_driven_serialization = false; + bool lite_implicit_weak_fields = false; + bool bootstrap = false; + bool opensource_runtime = false; + std::string runtime_include_base; + int num_cc_files = 0; + std::string annotation_pragma_name; + std::string annotation_guard_name; + const AccessInfoMap* access_info_map = nullptr; }; } // namespace cpp } // namespace compiler } // namespace protobuf - - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_OPTIONS_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc index e9303865..2f78bda5 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc @@ -106,6 +106,8 @@ class FieldGroup { // STRING is grouped next, as our Clear/SharedCtor/SharedDtor walks it and // calls ArenaStringPtr::Destroy on each. // +// LAZY_MESSAGE is grouped next, as it interferes with the ability to memset +// non-repeated fields otherwise. // // MESSAGE is grouped next, as our Clear/SharedDtor code walks it and calls // delete on each. We initialize these fields with a NULL pointer (see @@ -122,6 +124,9 @@ void PaddingOptimizer::OptimizeLayout( enum Family { REPEATED = 0, STRING = 1, + // Laying out LAZY_MESSAGE before MESSAGE allows a single memset to zero + // MESSAGE and ZERO_INITIALIZABLE fields together. + LAZY_MESSAGE = 2, MESSAGE = 3, ZERO_INITIALIZABLE = 4, OTHER = 5, @@ -142,7 +147,9 @@ void PaddingOptimizer::OptimizeLayout( f = STRING; } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { f = MESSAGE; - + if (IsLazy(field, options)) { + f = LAZY_MESSAGE; + } } else if (CanInitializeByZeroing(field)) { f = ZERO_INITIALIZABLE; } diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h index 42a3b5cd..2382081b 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h @@ -59,6 +59,6 @@ class PaddingOptimizer : public MessageLayoutHelper { } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_PADDING_OPTIMIZER_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc index ff6ba0f8..10e468b0 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc @@ -38,8 +38,8 @@ #include #include -#include #include +#include #include #include @@ -58,9 +58,8 @@ class TestGenerator : public CodeGenerator { ~TestGenerator() {} virtual bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const { + const std::string& parameter, GeneratorContext* context, + std::string* error) const { TryInsert("test.pb.h", "includes", context); TryInsert("test.pb.h", "namespace_scope", context); TryInsert("test.pb.h", "global_scope", context); @@ -129,7 +128,8 @@ class TestGenerator : public CodeGenerator { // Check field accessors for a message inside oneof{}: TryInsert("test.pb.h", "field_get:foo.Bar.oneOfMessage", context); TryInsert("test.pb.h", "field_mutable:foo.Bar.oneOfMessage", context); - TryInsert("test.pb.cc", "field_set_allocated:foo.Bar.oneOfMessage", context); + TryInsert("test.pb.cc", "field_set_allocated:foo.Bar.oneOfMessage", + context); // Check field accessors for an optional enum: TryInsert("test.pb.h", "field_get:foo.Bar.optEnum", context); @@ -167,7 +167,8 @@ class TestGenerator : public CodeGenerator { return true; } - void TryInsert(const string& filename, const string& insertion_point, + void TryInsert(const std::string& filename, + const std::string& insertion_point, GeneratorContext* context) const { std::unique_ptr output( context->OpenForInsert(filename, insertion_point)); @@ -219,7 +220,7 @@ TEST(CppPluginTest, PluginTest) { "}\n", true)); - google::protobuf::compiler::CommandLineInterface cli; + CommandLineInterface cli; cli.SetInputsAreProtoPathRelative(true); CppGenerator cpp_generator; @@ -227,17 +228,12 @@ TEST(CppPluginTest, PluginTest) { cli.RegisterGenerator("--cpp_out", &cpp_generator, ""); cli.RegisterGenerator("--test_out", &test_generator, ""); - string proto_path = "-I" + TestTempDir(); - string cpp_out = "--cpp_out=" + TestTempDir(); - string test_out = "--test_out=" + TestTempDir(); + std::string proto_path = "-I" + TestTempDir(); + std::string cpp_out = "--cpp_out=" + TestTempDir(); + std::string test_out = "--test_out=" + TestTempDir(); - const char* argv[] = { - "protoc", - proto_path.c_str(), - cpp_out.c_str(), - test_out.c_str(), - "test.proto" - }; + const char* argv[] = {"protoc", proto_path.c_str(), cpp_out.c_str(), + test_out.c_str(), "test.proto"}; EXPECT_EQ(0, cli.Run(5, argv)); } diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc index 701f9d2d..164bb1c5 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc @@ -38,6 +38,7 @@ #include #include + namespace google { namespace protobuf { namespace compiler { @@ -51,48 +52,65 @@ namespace { // returns -1. int FixedSize(FieldDescriptor::Type type) { switch (type) { - case FieldDescriptor::TYPE_INT32 : return -1; - case FieldDescriptor::TYPE_INT64 : return -1; - case FieldDescriptor::TYPE_UINT32 : return -1; - case FieldDescriptor::TYPE_UINT64 : return -1; - case FieldDescriptor::TYPE_SINT32 : return -1; - case FieldDescriptor::TYPE_SINT64 : return -1; - case FieldDescriptor::TYPE_FIXED32 : return WireFormatLite::kFixed32Size; - case FieldDescriptor::TYPE_FIXED64 : return WireFormatLite::kFixed64Size; - case FieldDescriptor::TYPE_SFIXED32: return WireFormatLite::kSFixed32Size; - case FieldDescriptor::TYPE_SFIXED64: return WireFormatLite::kSFixed64Size; - case FieldDescriptor::TYPE_FLOAT : return WireFormatLite::kFloatSize; - case FieldDescriptor::TYPE_DOUBLE : return WireFormatLite::kDoubleSize; + case FieldDescriptor::TYPE_INT32: + return -1; + case FieldDescriptor::TYPE_INT64: + return -1; + case FieldDescriptor::TYPE_UINT32: + return -1; + case FieldDescriptor::TYPE_UINT64: + return -1; + case FieldDescriptor::TYPE_SINT32: + return -1; + case FieldDescriptor::TYPE_SINT64: + return -1; + case FieldDescriptor::TYPE_FIXED32: + return WireFormatLite::kFixed32Size; + case FieldDescriptor::TYPE_FIXED64: + return WireFormatLite::kFixed64Size; + case FieldDescriptor::TYPE_SFIXED32: + return WireFormatLite::kSFixed32Size; + case FieldDescriptor::TYPE_SFIXED64: + return WireFormatLite::kSFixed64Size; + case FieldDescriptor::TYPE_FLOAT: + return WireFormatLite::kFloatSize; + case FieldDescriptor::TYPE_DOUBLE: + return WireFormatLite::kDoubleSize; - case FieldDescriptor::TYPE_BOOL : return WireFormatLite::kBoolSize; - case FieldDescriptor::TYPE_ENUM : return -1; + case FieldDescriptor::TYPE_BOOL: + return WireFormatLite::kBoolSize; + case FieldDescriptor::TYPE_ENUM: + return -1; - case FieldDescriptor::TYPE_STRING : return -1; - case FieldDescriptor::TYPE_BYTES : return -1; - case FieldDescriptor::TYPE_GROUP : return -1; - case FieldDescriptor::TYPE_MESSAGE : return -1; + case FieldDescriptor::TYPE_STRING: + return -1; + case FieldDescriptor::TYPE_BYTES: + return -1; + case FieldDescriptor::TYPE_GROUP: + return -1; + case FieldDescriptor::TYPE_MESSAGE: + return -1; - // No default because we want the compiler to complain if any new - // types are added. + // No default because we want the compiler to complain if any new + // types are added. } GOOGLE_LOG(FATAL) << "Can't get here."; return -1; } void SetPrimitiveVariables(const FieldDescriptor* descriptor, - std::map* variables, + std::map* variables, const Options& options) { SetCommonFieldVariables(descriptor, variables, options); - (*variables)["type"] = PrimitiveTypeName(descriptor->cpp_type()); - (*variables)["default"] = DefaultValue(descriptor); - (*variables)["tag"] = SimpleItoa(internal::WireFormat::MakeTag(descriptor)); + (*variables)["type"] = PrimitiveTypeName(options, descriptor->cpp_type()); + (*variables)["default"] = DefaultValue(options, descriptor); + (*variables)["tag"] = StrCat(internal::WireFormat::MakeTag(descriptor)); int fixed_size = FixedSize(descriptor->type()); if (fixed_size != -1) { - (*variables)["fixed_size"] = SimpleItoa(fixed_size); + (*variables)["fixed_size"] = StrCat(fixed_size); } - (*variables)["wire_format_field_type"] = - "::google::protobuf::internal::WireFormatLite::" + FieldDescriptorProto_Type_Name( - static_cast(descriptor->type())); + (*variables)["wire_format_field_type"] = FieldDescriptorProto_Type_Name( + static_cast(descriptor->type())); (*variables)["full_name"] = descriptor->full_name(); } @@ -102,164 +120,175 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor, PrimitiveFieldGenerator::PrimitiveFieldGenerator( const FieldDescriptor* descriptor, const Options& options) - : FieldGenerator(options), descriptor_(descriptor) { + : FieldGenerator(descriptor, options) { SetPrimitiveVariables(descriptor, &variables_, options); } PrimitiveFieldGenerator::~PrimitiveFieldGenerator() {} -void PrimitiveFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { - printer->Print(variables_, "$type$ $name$_;\n"); +void PrimitiveFieldGenerator::GeneratePrivateMembers( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$type$ $name$_;\n"); } -void PrimitiveFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { - printer->Print(variables_, "$deprecated_attr$$type$ $name$() const;\n"); - printer->Annotate("name", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$set_$name$$}$($type$ value);\n"); - printer->Annotate("{", "}", descriptor_); +void PrimitiveFieldGenerator::GenerateAccessorDeclarations( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "$deprecated_attr$$type$ ${1$$name$$}$() const;\n" + "$deprecated_attr$void ${1$set_$name$$}$($type$ value);\n", + descriptor_); } -void PrimitiveFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - printer->Print(variables_, - "inline $type$ $classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return $name$_;\n" - "}\n" - "inline void $classname$::set_$name$($type$ value) {\n" - " $set_hasbit$\n" - " $name$_ = value;\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - "}\n"); +void PrimitiveFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "inline $type$ $classname$::$name$() const {\n" + " // @@protoc_insertion_point(field_get:$full_name$)\n" + " return $name$_;\n" + "}\n" + "inline void $classname$::set_$name$($type$ value) {\n" + " $set_hasbit$\n" + " $name$_ = value;\n" + " // @@protoc_insertion_point(field_set:$full_name$)\n" + "}\n"); } -void PrimitiveFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $default$;\n"); +void PrimitiveFieldGenerator::GenerateClearingCode(io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_ = $default$;\n"); } -void PrimitiveFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, "set_$name$(from.$name$());\n"); +void PrimitiveFieldGenerator::GenerateMergingCode(io::Printer* printer) const { + Formatter format(printer, variables_); + format("set_$name$(from.$name$());\n"); } -void PrimitiveFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - printer->Print(variables_, "swap($name$_, other->$name$_);\n"); +void PrimitiveFieldGenerator::GenerateSwappingCode(io::Printer* printer) const { + Formatter format(printer, variables_); + format("swap($name$_, other->$name$_);\n"); } -void PrimitiveFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $default$;\n"); +void PrimitiveFieldGenerator::GenerateConstructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_ = $default$;\n"); } -void PrimitiveFieldGenerator:: -GenerateCopyConstructorCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = from.$name$_;\n"); +void PrimitiveFieldGenerator::GenerateCopyConstructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_ = from.$name$_;\n"); } -void PrimitiveFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - printer->Print(variables_, - "$set_hasbit$\n" - "DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n" - " $type$, $wire_format_field_type$>(\n" - " input, &$name$_)));\n"); +void PrimitiveFieldGenerator::GenerateMergeFromCodedStream( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "$set_hasbit_io$\n" + "DO_((::$proto_ns$::internal::WireFormatLite::ReadPrimitive<\n" + " $type$, " + "::$proto_ns$::internal::WireFormatLite::$wire_format_field_type$>(\n" + " input, &$name$_)));\n"); } -void PrimitiveFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { - printer->Print(variables_, - "::google::protobuf::internal::WireFormatLite::Write$declared_type$(" +void PrimitiveFieldGenerator::GenerateSerializeWithCachedSizes( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "::$proto_ns$::internal::WireFormatLite::Write$declared_type$(" "$number$, this->$name$(), output);\n"); } -void PrimitiveFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { - printer->Print(variables_, - "target = ::google::protobuf::internal::WireFormatLite::Write$declared_type$ToArray(" +void PrimitiveFieldGenerator::GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "target = " + "::$proto_ns$::internal::WireFormatLite::Write$declared_type$ToArray(" "$number$, this->$name$(), target);\n"); } -void PrimitiveFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { +void PrimitiveFieldGenerator::GenerateByteSize(io::Printer* printer) const { + Formatter format(printer, variables_); int fixed_size = FixedSize(descriptor_->type()); if (fixed_size == -1) { - printer->Print(variables_, - "total_size += $tag_size$ +\n" - " ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n" - " this->$name$());\n"); + format( + "total_size += $tag_size$ +\n" + " ::$proto_ns$::internal::WireFormatLite::$declared_type$Size(\n" + " this->$name$());\n"); } else { - printer->Print(variables_, - "total_size += $tag_size$ + $fixed_size$;\n"); + format("total_size += $tag_size$ + $fixed_size$;\n"); } } // =================================================================== -PrimitiveOneofFieldGenerator:: -PrimitiveOneofFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) - : PrimitiveFieldGenerator(descriptor, options) { +PrimitiveOneofFieldGenerator::PrimitiveOneofFieldGenerator( + const FieldDescriptor* descriptor, const Options& options) + : PrimitiveFieldGenerator(descriptor, options) { SetCommonOneofFieldVariables(descriptor, &variables_); } PrimitiveOneofFieldGenerator::~PrimitiveOneofFieldGenerator() {} -void PrimitiveOneofFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - printer->Print(variables_, - "inline $type$ $classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " if (has_$name$()) {\n" - " return $field_member$;\n" - " }\n" - " return $default$;\n" - "}\n" - "inline void $classname$::set_$name$($type$ value) {\n" - " if (!has_$name$()) {\n" - " clear_$oneof_name$();\n" - " set_has_$name$();\n" - " }\n" - " $field_member$ = value;\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - "}\n"); +void PrimitiveOneofFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "inline $type$ $classname$::$name$() const {\n" + " // @@protoc_insertion_point(field_get:$full_name$)\n" + " if (has_$name$()) {\n" + " return $field_member$;\n" + " }\n" + " return $default$;\n" + "}\n" + "inline void $classname$::set_$name$($type$ value) {\n" + " if (!has_$name$()) {\n" + " clear_$oneof_name$();\n" + " set_has_$name$();\n" + " }\n" + " $field_member$ = value;\n" + " // @@protoc_insertion_point(field_set:$full_name$)\n" + "}\n"); } -void PrimitiveOneofFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - printer->Print(variables_, "$field_member$ = $default$;\n"); +void PrimitiveOneofFieldGenerator::GenerateClearingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$field_member$ = $default$;\n"); } -void PrimitiveOneofFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { +void PrimitiveOneofFieldGenerator::GenerateSwappingCode( + io::Printer* printer) const { // Don't print any swapping code. Swapping the union will swap this field. } -void PrimitiveOneofFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - printer->Print(variables_, - "$ns$::_$classname$_default_instance_.$name$_ = $default$;\n"); +void PrimitiveOneofFieldGenerator::GenerateConstructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$ns$::_$classname$_default_instance_.$name$_ = $default$;\n"); } -void PrimitiveOneofFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - printer->Print(variables_, - "clear_$oneof_name$();\n" - "DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n" - " $type$, $wire_format_field_type$>(\n" - " input, &$field_member$)));\n" - "set_has_$name$();\n"); +void PrimitiveOneofFieldGenerator::GenerateMergeFromCodedStream( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "clear_$oneof_name$();\n" + "DO_((::$proto_ns$::internal::WireFormatLite::ReadPrimitive<\n" + " $type$, " + "::$proto_ns$::internal::WireFormatLite::$wire_format_field_type$>(\n" + " input, &$field_member$)));\n" + "set_has_$name$();\n"); } // =================================================================== RepeatedPrimitiveFieldGenerator::RepeatedPrimitiveFieldGenerator( const FieldDescriptor* descriptor, const Options& options) - : FieldGenerator(options), descriptor_(descriptor) { + : FieldGenerator(descriptor, options) { SetPrimitiveVariables(descriptor, &variables_, options); if (descriptor->is_packed()) { @@ -273,206 +302,212 @@ RepeatedPrimitiveFieldGenerator::RepeatedPrimitiveFieldGenerator( RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() {} -void RepeatedPrimitiveFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { - printer->Print(variables_, - "::google::protobuf::RepeatedField< $type$ > $name$_;\n"); +void RepeatedPrimitiveFieldGenerator::GeneratePrivateMembers( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("::$proto_ns$::RepeatedField< $type$ > $name$_;\n"); if (descriptor_->is_packed() && HasGeneratedMethods(descriptor_->file(), options_)) { - printer->Print(variables_, - "mutable int _$name$_cached_byte_size_;\n"); + format("mutable std::atomic _$name$_cached_byte_size_;\n"); } } -void RepeatedPrimitiveFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { - printer->Print(variables_, - "$deprecated_attr$$type$ $name$(int index) const;\n"); - printer->Annotate("name", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$void ${$set_$name$$}$(int index, $type$ value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$add_$name$$}$($type$ value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$const ::google::protobuf::RepeatedField< $type$ >&\n" - " $name$() const;\n"); - printer->Annotate("name", descriptor_); - printer->Print(variables_, - "$deprecated_attr$::google::protobuf::RepeatedField< $type$ >*\n" - " ${$mutable_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); +void RepeatedPrimitiveFieldGenerator::GenerateAccessorDeclarations( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "$deprecated_attr$$type$ ${1$$name$$}$(int index) const;\n" + "$deprecated_attr$void ${1$set_$name$$}$(int index, $type$ value);\n" + "$deprecated_attr$void ${1$add_$name$$}$($type$ value);\n" + "$deprecated_attr$const ::$proto_ns$::RepeatedField< $type$ >&\n" + " ${1$$name$$}$() const;\n" + "$deprecated_attr$::$proto_ns$::RepeatedField< $type$ >*\n" + " ${1$mutable_$name$$}$();\n", + descriptor_); } -void RepeatedPrimitiveFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - printer->Print(variables_, - "inline $type$ $classname$::$name$(int index) const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return $name$_.Get(index);\n" - "}\n" - "inline void $classname$::set_$name$(int index, $type$ value) {\n" - " $name$_.Set(index, value);\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - "}\n" - "inline void $classname$::add_$name$($type$ value) {\n" - " $name$_.Add(value);\n" - " // @@protoc_insertion_point(field_add:$full_name$)\n" - "}\n" - "inline const ::google::protobuf::RepeatedField< $type$ >&\n" - "$classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_list:$full_name$)\n" - " return $name$_;\n" - "}\n" - "inline ::google::protobuf::RepeatedField< $type$ >*\n" - "$classname$::mutable_$name$() {\n" - " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n" - " return &$name$_;\n" - "}\n"); +void RepeatedPrimitiveFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "inline $type$ $classname$::$name$(int index) const {\n" + " // @@protoc_insertion_point(field_get:$full_name$)\n" + " return $name$_.Get(index);\n" + "}\n" + "inline void $classname$::set_$name$(int index, $type$ value) {\n" + " $name$_.Set(index, value);\n" + " // @@protoc_insertion_point(field_set:$full_name$)\n" + "}\n" + "inline void $classname$::add_$name$($type$ value) {\n" + " $name$_.Add(value);\n" + " // @@protoc_insertion_point(field_add:$full_name$)\n" + "}\n" + "inline const ::$proto_ns$::RepeatedField< $type$ >&\n" + "$classname$::$name$() const {\n" + " // @@protoc_insertion_point(field_list:$full_name$)\n" + " return $name$_;\n" + "}\n" + "inline ::$proto_ns$::RepeatedField< $type$ >*\n" + "$classname$::mutable_$name$() {\n" + " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n" + " return &$name$_;\n" + "}\n"); } -void RepeatedPrimitiveFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.Clear();\n"); +void RepeatedPrimitiveFieldGenerator::GenerateClearingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.Clear();\n"); } -void RepeatedPrimitiveFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n"); +void RepeatedPrimitiveFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.MergeFrom(from.$name$_);\n"); } -void RepeatedPrimitiveFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.InternalSwap(&other->$name$_);\n"); +void RepeatedPrimitiveFieldGenerator::GenerateSwappingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.InternalSwap(&other->$name$_);\n"); } -void RepeatedPrimitiveFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { +void RepeatedPrimitiveFieldGenerator::GenerateConstructorCode( + io::Printer* printer) const { // Not needed for repeated fields. } -void RepeatedPrimitiveFieldGenerator:: -GenerateCopyConstructorCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.CopyFrom(from.$name$_);\n"); +void RepeatedPrimitiveFieldGenerator::GenerateCopyConstructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.CopyFrom(from.$name$_);\n"); } -void RepeatedPrimitiveFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - printer->Print(variables_, - "DO_((::google::protobuf::internal::WireFormatLite::$repeated_reader$<\n" - " $type$, $wire_format_field_type$>(\n" - " $tag_size$, $tag$u, input, this->mutable_$name$())));\n"); +void RepeatedPrimitiveFieldGenerator::GenerateMergeFromCodedStream( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "DO_((::$proto_ns$::internal::WireFormatLite::$repeated_reader$<\n" + " $type$, " + "::$proto_ns$::internal::WireFormatLite::$wire_format_field_type$>(\n" + " $tag_size$, $tag$u, input, this->mutable_$name$())));\n"); } -void RepeatedPrimitiveFieldGenerator:: -GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const { - printer->Print(variables_, - "DO_((::google::protobuf::internal::WireFormatLite::$packed_reader$<\n" - " $type$, $wire_format_field_type$>(\n" - " input, this->mutable_$name$())));\n"); +void RepeatedPrimitiveFieldGenerator::GenerateMergeFromCodedStreamWithPacking( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "DO_((::$proto_ns$::internal::WireFormatLite::$packed_reader$<\n" + " $type$, " + "::$proto_ns$::internal::WireFormatLite::$wire_format_field_type$>(\n" + " input, this->mutable_$name$())));\n"); } -void RepeatedPrimitiveFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { +void RepeatedPrimitiveFieldGenerator::GenerateSerializeWithCachedSizes( + io::Printer* printer) const { + Formatter format(printer, variables_); bool array_written = false; if (descriptor_->is_packed()) { // Write the tag and the size. - printer->Print(variables_, - "if (this->$name$_size() > 0) {\n" - " ::google::protobuf::internal::WireFormatLite::WriteTag(" - "$number$, " - "::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, " - "output);\n" - " output->WriteVarint32(static_cast< ::google::protobuf::uint32>(\n" - " _$name$_cached_byte_size_));\n"); + format( + "if (this->$name$_size() > 0) {\n" + " ::$proto_ns$::internal::WireFormatLite::WriteTag(" + "$number$, " + "::$proto_ns$::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, " + "output);\n" + " output->WriteVarint32(_$name$_cached_byte_size_.load(\n" + " std::memory_order_relaxed));\n"); if (FixedSize(descriptor_->type()) > 0) { // TODO(ckennelly): Use RepeatedField::unsafe_data() via // WireFormatLite to access the contents of this->$name$_ to save a branch // here. - printer->Print(variables_, - " ::google::protobuf::internal::WireFormatLite::Write$declared_type$Array(\n" - " this->$name$().data(), this->$name$_size(), output);\n"); + format( + " " + "::$proto_ns$::internal::WireFormatLite::Write$declared_type$Array(\n" + " this->$name$().data(), this->$name$_size(), output);\n"); array_written = true; // Wrote array all at once } - printer->Print(variables_, "}\n"); + format("}\n"); } if (!array_written) { - printer->Print(variables_, - "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n"); + format("for (int i = 0, n = this->$name$_size(); i < n; i++) {\n"); if (descriptor_->is_packed()) { - printer->Print(variables_, - " ::google::protobuf::internal::WireFormatLite::Write$declared_type$NoTag(\n" - " this->$name$(i), output);\n"); + format( + " " + "::$proto_ns$::internal::WireFormatLite::Write$declared_type$NoTag(\n" + " this->$name$(i), output);\n"); } else { - printer->Print(variables_, - " ::google::protobuf::internal::WireFormatLite::Write$declared_type$(\n" - " $number$, this->$name$(i), output);\n"); + format( + " ::$proto_ns$::internal::WireFormatLite::Write$declared_type$(\n" + " $number$, this->$name$(i), output);\n"); } - printer->Print("}\n"); + format("}\n"); } } -void RepeatedPrimitiveFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { +void RepeatedPrimitiveFieldGenerator::GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const { + Formatter format(printer, variables_); if (descriptor_->is_packed()) { // Write the tag and the size. - printer->Print(variables_, - "if (this->$name$_size() > 0) {\n" - " target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(\n" - " $number$,\n" - " ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n" - " target);\n" - " target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(\n" - " static_cast< ::google::protobuf::int32>(\n" - " _$name$_cached_byte_size_), target);\n" - " target = ::google::protobuf::internal::WireFormatLite::\n" - " Write$declared_type$NoTagToArray(this->$name$_, target);\n" - "}\n"); + format( + "if (this->$name$_size() > 0) {\n" + " target = ::$proto_ns$::internal::WireFormatLite::WriteTagToArray(\n" + " $number$,\n" + " " + "::$proto_ns$::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n" + " target);\n" + " target = " + "::$proto_ns$::io::CodedOutputStream::WriteVarint32ToArray(\n" + " _$name$_cached_byte_size_.load(std::memory_order_relaxed),\n" + " target);\n" + " target = ::$proto_ns$::internal::WireFormatLite::\n" + " Write$declared_type$NoTagToArray(this->$name$_, target);\n" + "}\n"); } else { - printer->Print(variables_, - "target = ::google::protobuf::internal::WireFormatLite::\n" - " Write$declared_type$ToArray($number$, this->$name$_, target);\n"); + format( + "target = ::$proto_ns$::internal::WireFormatLite::\n" + " Write$declared_type$ToArray($number$, this->$name$_, target);\n"); } } -void RepeatedPrimitiveFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { - printer->Print(variables_, "{\n"); - printer->Indent(); +void RepeatedPrimitiveFieldGenerator::GenerateByteSize( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("{\n"); + format.Indent(); int fixed_size = FixedSize(descriptor_->type()); if (fixed_size == -1) { - printer->Print(variables_, - "size_t data_size = ::google::protobuf::internal::WireFormatLite::\n" - " $declared_type$Size(this->$name$_);\n"); + format( + "size_t data_size = ::$proto_ns$::internal::WireFormatLite::\n" + " $declared_type$Size(this->$name$_);\n"); } else { - printer->Print(variables_, - "unsigned int count = static_cast(this->$name$_size());\n" - "size_t data_size = $fixed_size$UL * count;\n"); + format( + "unsigned int count = static_cast(this->$name$_size());\n" + "size_t data_size = $fixed_size$UL * count;\n"); } if (descriptor_->is_packed()) { - printer->Print(variables_, - "if (data_size > 0) {\n" - " total_size += $tag_size$ +\n" - " ::google::protobuf::internal::WireFormatLite::Int32Size(\n" - " static_cast< ::google::protobuf::int32>(data_size));\n" - "}\n" - "int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);\n" - "GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n" - "_$name$_cached_byte_size_ = cached_size;\n" - "GOOGLE_SAFE_CONCURRENT_WRITES_END();\n" - "total_size += data_size;\n"); + format( + "if (data_size > 0) {\n" + " total_size += $tag_size$ +\n" + " ::$proto_ns$::internal::WireFormatLite::Int32Size(\n" + " static_cast<$int32$>(data_size));\n" + "}\n" + "int cached_size = ::$proto_ns$::internal::ToCachedSize(data_size);\n" + "_$name$_cached_byte_size_.store(cached_size,\n" + " std::memory_order_relaxed);\n" + "total_size += data_size;\n"); } else { - printer->Print(variables_, - "total_size += $tag_size$ *\n" - " ::google::protobuf::internal::FromIntSize(this->$name$_size());\n" - "total_size += data_size;\n"); + format( + "total_size += $tag_size$ *\n" + " " + "::$proto_ns$::internal::FromIntSize(this->$name$_size());\n" + "total_size += data_size;\n"); } - printer->Outdent(); - printer->Print("}\n"); + format.Outdent(); + format("}\n"); } } // namespace cpp diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_primitive_field.h b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_primitive_field.h index d52228e9..77389aa0 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_primitive_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_primitive_field.h @@ -64,10 +64,6 @@ class PrimitiveFieldGenerator : public FieldGenerator { void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const; void GenerateByteSize(io::Printer* printer) const; - protected: - const FieldDescriptor* descriptor_; - std::map variables_; - private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator); }; @@ -111,15 +107,12 @@ class RepeatedPrimitiveFieldGenerator : public FieldGenerator { void GenerateByteSize(io::Printer* printer) const; private: - const FieldDescriptor* descriptor_; - std::map variables_; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator); }; } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_PRIMITIVE_FIELD_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_service.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_service.cc index 95357d9f..994e653e 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_service.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_service.cc @@ -42,151 +42,147 @@ namespace protobuf { namespace compiler { namespace cpp { -ServiceGenerator::ServiceGenerator(const ServiceDescriptor* descriptor, - const Options& options) - : descriptor_(descriptor) { +namespace { + +void InitMethodVariables(const MethodDescriptor* method, const Options& options, + Formatter* format) { + format->Set("name", method->name()); + format->Set("input_type", QualifiedClassName(method->input_type(), options)); + format->Set("output_type", + QualifiedClassName(method->output_type(), options)); +} + +} // namespace + +ServiceGenerator::ServiceGenerator( + const ServiceDescriptor* descriptor, + const std::map& vars, const Options& options) + : descriptor_(descriptor), vars_(vars), options_(options) { vars_["classname"] = descriptor_->name(); - vars_["file_namespace"] = FileLevelNamespace(descriptor_->file()->name()); vars_["full_name"] = descriptor_->full_name(); - if (options.dllexport_decl.empty()) { - vars_["dllexport"] = ""; - } else { - vars_["dllexport"] = options.dllexport_decl + " "; - } } ServiceGenerator::~ServiceGenerator() {} void ServiceGenerator::GenerateDeclarations(io::Printer* printer) { + Formatter format(printer, vars_); // Forward-declare the stub type. - printer->Print(vars_, - "class $classname$_Stub;\n" - "\n"); + format( + "class $classname$_Stub;\n" + "\n"); GenerateInterface(printer); GenerateStubDefinition(printer); } void ServiceGenerator::GenerateInterface(io::Printer* printer) { - printer->Print(vars_, - "class $dllexport$$classname$ : public ::google::protobuf::Service {\n" - " protected:\n" - " // This class should be treated as an abstract interface.\n" - " inline $classname$() {};\n" - " public:\n" - " virtual ~$classname$();\n"); + Formatter format(printer, vars_); + format( + "class $dllexport_decl $$classname$ : public ::$proto_ns$::Service {\n" + " protected:\n" + " // This class should be treated as an abstract interface.\n" + " inline $classname$() {};\n" + " public:\n" + " virtual ~$classname$();\n"); printer->Indent(); - printer->Print(vars_, - "\n" - "typedef $classname$_Stub Stub;\n" - "\n" - "static const ::google::protobuf::ServiceDescriptor* descriptor();\n" - "\n"); + format( + "\n" + "typedef $classname$_Stub Stub;\n" + "\n" + "static const ::$proto_ns$::ServiceDescriptor* descriptor();\n" + "\n"); GenerateMethodSignatures(VIRTUAL, printer); - printer->Print( - "\n" - "// implements Service ----------------------------------------------\n" - "\n" - "const ::google::protobuf::ServiceDescriptor* GetDescriptor();\n" - "void CallMethod(const ::google::protobuf::MethodDescriptor* method,\n" - " ::google::protobuf::RpcController* controller,\n" - " const ::google::protobuf::Message* request,\n" - " ::google::protobuf::Message* response,\n" - " ::google::protobuf::Closure* done);\n" - "const ::google::protobuf::Message& GetRequestPrototype(\n" - " const ::google::protobuf::MethodDescriptor* method) const;\n" - "const ::google::protobuf::Message& GetResponsePrototype(\n" - " const ::google::protobuf::MethodDescriptor* method) const;\n"); + format( + "\n" + "// implements Service ----------------------------------------------\n" + "\n" + "const ::$proto_ns$::ServiceDescriptor* GetDescriptor();\n" + "void CallMethod(const ::$proto_ns$::MethodDescriptor* method,\n" + " ::$proto_ns$::RpcController* controller,\n" + " const ::$proto_ns$::Message* request,\n" + " ::$proto_ns$::Message* response,\n" + " ::google::protobuf::Closure* done);\n" + "const ::$proto_ns$::Message& GetRequestPrototype(\n" + " const ::$proto_ns$::MethodDescriptor* method) const;\n" + "const ::$proto_ns$::Message& GetResponsePrototype(\n" + " const ::$proto_ns$::MethodDescriptor* method) const;\n"); printer->Outdent(); - printer->Print(vars_, - "\n" - " private:\n" - " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$);\n" - "};\n" - "\n"); + format( + "\n" + " private:\n" + " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$);\n" + "};\n" + "\n"); } void ServiceGenerator::GenerateStubDefinition(io::Printer* printer) { - printer->Print(vars_, - "class $dllexport$$classname$_Stub : public $classname$ {\n" - " public:\n"); + Formatter format(printer, vars_); + format( + "class $dllexport_decl $$classname$_Stub : public $classname$ {\n" + " public:\n"); printer->Indent(); - printer->Print(vars_, - "$classname$_Stub(::google::protobuf::RpcChannel* channel);\n" - "$classname$_Stub(::google::protobuf::RpcChannel* channel,\n" - " ::google::protobuf::Service::ChannelOwnership ownership);\n" - "~$classname$_Stub();\n" - "\n" - "inline ::google::protobuf::RpcChannel* channel() { return channel_; }\n" - "\n" - "// implements $classname$ ------------------------------------------\n" - "\n"); + format( + "$classname$_Stub(::$proto_ns$::RpcChannel* channel);\n" + "$classname$_Stub(::$proto_ns$::RpcChannel* channel,\n" + " ::$proto_ns$::Service::ChannelOwnership ownership);\n" + "~$classname$_Stub();\n" + "\n" + "inline ::$proto_ns$::RpcChannel* channel() { return channel_; }\n" + "\n" + "// implements $classname$ ------------------------------------------\n" + "\n"); GenerateMethodSignatures(NON_VIRTUAL, printer); printer->Outdent(); - printer->Print(vars_, - " private:\n" - " ::google::protobuf::RpcChannel* channel_;\n" - " bool owns_channel_;\n" - " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$_Stub);\n" - "};\n" - "\n"); + format( + " private:\n" + " ::$proto_ns$::RpcChannel* channel_;\n" + " bool owns_channel_;\n" + " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$_Stub);\n" + "};\n" + "\n"); } -void ServiceGenerator::GenerateMethodSignatures( - VirtualOrNon virtual_or_non, io::Printer* printer) { +void ServiceGenerator::GenerateMethodSignatures(VirtualOrNon virtual_or_non, + io::Printer* printer) { for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); - std::map sub_vars; - sub_vars["name"] = method->name(); - sub_vars["input_type"] = ClassName(method->input_type(), true); - sub_vars["output_type"] = ClassName(method->output_type(), true); - sub_vars["virtual"] = virtual_or_non == VIRTUAL ? "virtual " : ""; - - printer->Print(sub_vars, - "$virtual$void $name$(::google::protobuf::RpcController* controller,\n" - " const $input_type$* request,\n" - " $output_type$* response,\n" - " ::google::protobuf::Closure* done);\n"); + Formatter format(printer, vars_); + InitMethodVariables(method, options_, &format); + format.Set("virtual", virtual_or_non == VIRTUAL ? "virtual " : ""); + format( + "$virtual$void $name$(::$proto_ns$::RpcController* controller,\n" + " const $input_type$* request,\n" + " $output_type$* response,\n" + " ::google::protobuf::Closure* done);\n"); } } // =================================================================== -void ServiceGenerator::GenerateDescriptorInitializer( - io::Printer* printer, int index) { - std::map vars; - vars["classname"] = descriptor_->name(); - vars["index"] = SimpleItoa(index); - - printer->Print(vars, - "$classname$_descriptor_ = file->service($index$);\n"); -} - -// =================================================================== - void ServiceGenerator::GenerateImplementation(io::Printer* printer) { - vars_["index"] = SimpleItoa(index_in_metadata_); - printer->Print( - vars_, + Formatter format(printer, vars_); + format( "$classname$::~$classname$() {}\n" "\n" - "const ::google::protobuf::ServiceDescriptor* $classname$::descriptor() {\n" - " $file_namespace$::protobuf_AssignDescriptorsOnce();\n" - " return $file_namespace$::file_level_service_descriptors[$index$];\n" + "const ::$proto_ns$::ServiceDescriptor* $classname$::descriptor() {\n" + " " + "::$proto_ns$::internal::AssignDescriptors(&$desc_table$);\n" + " return $file_level_service_descriptors$[$1$];\n" "}\n" "\n" - "const ::google::protobuf::ServiceDescriptor* $classname$::GetDescriptor() {\n" + "const ::$proto_ns$::ServiceDescriptor* $classname$::GetDescriptor() {\n" " return descriptor();\n" "}\n" - "\n"); + "\n", + index_in_metadata_); // Generate methods of the interface. GenerateNotImplementedMethods(printer); @@ -195,18 +191,20 @@ void ServiceGenerator::GenerateImplementation(io::Printer* printer) { GenerateGetPrototype(RESPONSE, printer); // Generate stub implementation. - printer->Print(vars_, - "$classname$_Stub::$classname$_Stub(::google::protobuf::RpcChannel* channel)\n" - " : channel_(channel), owns_channel_(false) {}\n" - "$classname$_Stub::$classname$_Stub(\n" - " ::google::protobuf::RpcChannel* channel,\n" - " ::google::protobuf::Service::ChannelOwnership ownership)\n" - " : channel_(channel),\n" - " owns_channel_(ownership == ::google::protobuf::Service::STUB_OWNS_CHANNEL) {}\n" - "$classname$_Stub::~$classname$_Stub() {\n" - " if (owns_channel_) delete channel_;\n" - "}\n" - "\n"); + format( + "$classname$_Stub::$classname$_Stub(::$proto_ns$::RpcChannel* channel)\n" + " : channel_(channel), owns_channel_(false) {}\n" + "$classname$_Stub::$classname$_Stub(\n" + " ::$proto_ns$::RpcChannel* channel,\n" + " ::$proto_ns$::Service::ChannelOwnership ownership)\n" + " : channel_(channel),\n" + " owns_channel_(ownership == " + "::$proto_ns$::Service::STUB_OWNS_CHANNEL) " + "{}\n" + "$classname$_Stub::~$classname$_Stub() {\n" + " if (owns_channel_) delete channel_;\n" + "}\n" + "\n"); GenerateStubMethods(printer); } @@ -214,123 +212,112 @@ void ServiceGenerator::GenerateImplementation(io::Printer* printer) { void ServiceGenerator::GenerateNotImplementedMethods(io::Printer* printer) { for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); - std::map sub_vars; - sub_vars["classname"] = descriptor_->name(); - sub_vars["name"] = method->name(); - sub_vars["index"] = SimpleItoa(i); - sub_vars["input_type"] = ClassName(method->input_type(), true); - sub_vars["output_type"] = ClassName(method->output_type(), true); - - printer->Print(sub_vars, - "void $classname$::$name$(::google::protobuf::RpcController* controller,\n" - " const $input_type$*,\n" - " $output_type$*,\n" - " ::google::protobuf::Closure* done) {\n" - " controller->SetFailed(\"Method $name$() not implemented.\");\n" - " done->Run();\n" - "}\n" - "\n"); + Formatter format(printer, vars_); + InitMethodVariables(method, options_, &format); + format( + "void $classname$::$name$(::$proto_ns$::RpcController* controller,\n" + " const $input_type$*,\n" + " $output_type$*,\n" + " ::google::protobuf::Closure* done) {\n" + " controller->SetFailed(\"Method $name$() not implemented.\");\n" + " done->Run();\n" + "}\n" + "\n"); } } void ServiceGenerator::GenerateCallMethod(io::Printer* printer) { - printer->Print( - vars_, - "void $classname$::CallMethod(const ::google::protobuf::MethodDescriptor* method,\n" - " ::google::protobuf::RpcController* controller,\n" - " const ::google::protobuf::Message* request,\n" - " ::google::protobuf::Message* response,\n" + Formatter format(printer, vars_); + format( + "void $classname$::CallMethod(const ::$proto_ns$::MethodDescriptor* " + "method,\n" + " ::$proto_ns$::RpcController* controller,\n" + " const ::$proto_ns$::Message* request,\n" + " ::$proto_ns$::Message* response,\n" " ::google::protobuf::Closure* done) {\n" - " GOOGLE_DCHECK_EQ(method->service(), " - "$file_namespace$::file_level_service_descriptors[$index$]);\n" - " switch(method->index()) {\n"); + " GOOGLE_DCHECK_EQ(method->service(), $file_level_service_descriptors$[$1$]);\n" + " switch(method->index()) {\n", + index_in_metadata_); for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); - std::map sub_vars; - sub_vars["name"] = method->name(); - sub_vars["index"] = SimpleItoa(i); - sub_vars["input_type"] = ClassName(method->input_type(), true); - sub_vars["output_type"] = ClassName(method->output_type(), true); + Formatter format(printer, vars_); + InitMethodVariables(method, options_, &format); // Note: down_cast does not work here because it only works on pointers, // not references. - printer->Print(sub_vars, - " case $index$:\n" - " $name$(controller,\n" - " ::google::protobuf::down_cast(request),\n" - " ::google::protobuf::down_cast< $output_type$*>(response),\n" - " done);\n" - " break;\n"); + format( + " case $1$:\n" + " $name$(controller,\n" + " ::$proto_ns$::internal::DownCast(\n" + " request),\n" + " ::$proto_ns$::internal::DownCast<$output_type$*>(\n" + " response),\n" + " done);\n" + " break;\n", + i); } - printer->Print(vars_, - " default:\n" - " GOOGLE_LOG(FATAL) << \"Bad method index; this should never happen.\";\n" - " break;\n" - " }\n" - "}\n" - "\n"); + format( + " default:\n" + " GOOGLE_LOG(FATAL) << \"Bad method index; this should never happen.\";\n" + " break;\n" + " }\n" + "}\n" + "\n"); } void ServiceGenerator::GenerateGetPrototype(RequestOrResponse which, io::Printer* printer) { + Formatter format(printer, vars_); if (which == REQUEST) { - printer->Print(vars_, - "const ::google::protobuf::Message& $classname$::GetRequestPrototype(\n"); + format("const ::$proto_ns$::Message& $classname$::GetRequestPrototype(\n"); } else { - printer->Print(vars_, - "const ::google::protobuf::Message& $classname$::GetResponsePrototype(\n"); + format("const ::$proto_ns$::Message& $classname$::GetResponsePrototype(\n"); } - printer->Print(vars_, - " const ::google::protobuf::MethodDescriptor* method) const {\n" - " GOOGLE_DCHECK_EQ(method->service(), descriptor());\n" - " switch(method->index()) {\n"); + format( + " const ::$proto_ns$::MethodDescriptor* method) const {\n" + " GOOGLE_DCHECK_EQ(method->service(), descriptor());\n" + " switch(method->index()) {\n"); for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); const Descriptor* type = - (which == REQUEST) ? method->input_type() : method->output_type(); + (which == REQUEST) ? method->input_type() : method->output_type(); - std::map sub_vars; - sub_vars["index"] = SimpleItoa(i); - sub_vars["type"] = ClassName(type, true); - - printer->Print(sub_vars, - " case $index$:\n" - " return $type$::default_instance();\n"); + format( + " case $1$:\n" + " return $2$::default_instance();\n", + i, QualifiedClassName(type, options_)); } - printer->Print( - " default:\n" - " GOOGLE_LOG(FATAL) << \"Bad method index; this should never happen.\";\n" - " return *::google::protobuf::MessageFactory::generated_factory()\n" - " ->GetPrototype(method->$input_or_output$_type());\n" - " }\n" - "}\n" - "\n", - "input_or_output", which == REQUEST ? "input" : "output"); + format( + " default:\n" + " GOOGLE_LOG(FATAL) << \"Bad method index; this should never happen.\";\n" + " return *::$proto_ns$::MessageFactory::generated_factory()\n" + " ->GetPrototype(method->$1$_type());\n" + " }\n" + "}\n" + "\n", + which == REQUEST ? "input" : "output"); } void ServiceGenerator::GenerateStubMethods(io::Printer* printer) { for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); - std::map sub_vars; - sub_vars["classname"] = descriptor_->name(); - sub_vars["name"] = method->name(); - sub_vars["index"] = SimpleItoa(i); - sub_vars["input_type"] = ClassName(method->input_type(), true); - sub_vars["output_type"] = ClassName(method->output_type(), true); - - printer->Print(sub_vars, - "void $classname$_Stub::$name$(::google::protobuf::RpcController* controller,\n" - " const $input_type$* request,\n" - " $output_type$* response,\n" - " ::google::protobuf::Closure* done) {\n" - " channel_->CallMethod(descriptor()->method($index$),\n" - " controller, request, response, done);\n" - "}\n"); + Formatter format(printer, vars_); + InitMethodVariables(method, options_, &format); + format( + "void $classname$_Stub::$name$(::$proto_ns$::RpcController* " + "controller,\n" + " const $input_type$* request,\n" + " $output_type$* response,\n" + " ::google::protobuf::Closure* done) {\n" + " channel_->CallMethod(descriptor()->method($1$),\n" + " controller, request, response, done);\n" + "}\n", + i); } } diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_service.h b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_service.h index 33c02547..63c7ca44 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_service.h +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_service.h @@ -42,11 +42,13 @@ namespace google { namespace protobuf { - namespace io { - class Printer; // printer.h - } +namespace io { +class Printer; // printer.h } +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace cpp { @@ -55,6 +57,7 @@ class ServiceGenerator { public: // See generator.cc for the meaning of dllexport_decl. explicit ServiceGenerator(const ServiceDescriptor* descriptor, + const std::map& vars, const Options& options); ~ServiceGenerator(); @@ -66,11 +69,8 @@ class ServiceGenerator { // Source file stuff. - // Generate code that initializes the global variable storing the service's - // descriptor. - void GenerateDescriptorInitializer(io::Printer* printer, int index); - - // Generate implementations of everything declared by GenerateDeclarations(). + // Generate implementations of everything declared by + // GenerateDeclarations(). void GenerateImplementation(io::Printer* printer); private: @@ -105,7 +105,8 @@ class ServiceGenerator { void GenerateStubMethods(io::Printer* printer); const ServiceDescriptor* descriptor_; - std::map vars_; + std::map vars_; + const Options& options_; int index_in_metadata_; @@ -116,6 +117,6 @@ class ServiceGenerator { } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_SERVICE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_string_field.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_string_field.cc index cf6c4b33..bd25d7a8 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_string_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_string_field.cc @@ -36,9 +36,10 @@ #include #include #include - #include + + namespace google { namespace protobuf { namespace compiler { @@ -47,30 +48,34 @@ namespace cpp { namespace { void SetStringVariables(const FieldDescriptor* descriptor, - std::map* variables, + std::map* variables, const Options& options) { SetCommonFieldVariables(descriptor, variables, options); - (*variables)["default"] = DefaultValue(descriptor); + (*variables)["default"] = DefaultValue(options, descriptor); (*variables)["default_length"] = - SimpleItoa(descriptor->default_value_string().length()); - string default_variable_string = MakeDefaultName(descriptor); + StrCat(descriptor->default_value_string().length()); + std::string default_variable_string = MakeDefaultName(descriptor); (*variables)["default_variable_name"] = default_variable_string; (*variables)["default_variable"] = descriptor->default_value_string().empty() - ? "&::google::protobuf::internal::GetEmptyStringAlreadyInited()" - : "&" + Namespace(descriptor) + "::" + (*variables)["classname"] + + ? "&::" + (*variables)["proto_ns"] + + "::internal::GetEmptyStringAlreadyInited()" + : "&" + QualifiedClassName(descriptor->containing_type(), options) + "::" + default_variable_string + ".get()"; (*variables)["pointer_type"] = descriptor->type() == FieldDescriptor::TYPE_BYTES ? "void" : "char"; - (*variables)["null_check"] = "GOOGLE_DCHECK(value != NULL);\n"; + (*variables)["null_check"] = (*variables)["DCHK"] + "(value != nullptr);\n"; // NOTE: Escaped here to unblock proto1->proto2 migration. // TODO(liujisi): Extend this to apply for other conflicting methods. (*variables)["release_name"] = - SafeFunctionName(descriptor->containing_type(), - descriptor, "release_"); + SafeFunctionName(descriptor->containing_type(), descriptor, "release_"); (*variables)["full_name"] = descriptor->full_name(); - (*variables)["string_piece"] = "::std::string"; + if (options.opensource_runtime) { + (*variables)["string_piece"] = "::std::string"; + } else { + (*variables)["string_piece"] = "::StringPiece"; + } (*variables)["lite"] = HasDescriptorMethods(descriptor->file(), options) ? "" : "Lite"; @@ -82,34 +87,18 @@ void SetStringVariables(const FieldDescriptor* descriptor, StringFieldGenerator::StringFieldGenerator(const FieldDescriptor* descriptor, const Options& options) - : FieldGenerator(options), - descriptor_(descriptor), + : FieldGenerator(descriptor, options), lite_(!HasDescriptorMethods(descriptor->file(), options)), - inlined_(false) { - - // TODO(ckennelly): Handle inlining for any.proto. - if (IsAnyMessage(descriptor_->containing_type())) { - inlined_ = false; - } - if (descriptor_->containing_type()->options().map_entry()) { - inlined_ = false; - } - - // Limit to proto2, as we rely on has bits to distinguish field presence for - // release_$name$. On proto3, we cannot use the address of the string - // instance when the field has been inlined. - inlined_ = inlined_ && HasFieldPresence(descriptor_->file()); - + inlined_(IsStringInlined(descriptor, options)) { SetStringVariables(descriptor, &variables_, options); } StringFieldGenerator::~StringFieldGenerator() {} -void StringFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { +void StringFieldGenerator::GeneratePrivateMembers(io::Printer* printer) const { + Formatter format(printer, variables_); if (inlined_) { - printer->Print(variables_, - "::google::protobuf::internal::InlinedStringField $name$_;\n"); + format("::$proto_ns$::internal::InlinedStringField $name$_;\n"); } else { // N.B. that we continue to use |ArenaStringPtr| instead of |string*| for // string fields, even when SupportArenas(descriptor_) == false. Why? The @@ -123,25 +112,26 @@ GeneratePrivateMembers(io::Printer* printer) const { // conditionals. It's simpler to stick with this but use lightweight // accessors that assume arena == NULL. There should be very little // overhead anyway because it's just a tagged pointer in-memory. - printer->Print(variables_, "::google::protobuf::internal::ArenaStringPtr $name$_;\n"); + format("::$proto_ns$::internal::ArenaStringPtr $name$_;\n"); } } -void StringFieldGenerator:: -GenerateStaticMembers(io::Printer* printer) const { +void StringFieldGenerator::GenerateStaticMembers(io::Printer* printer) const { + Formatter format(printer, variables_); if (!descriptor_->default_value_string().empty()) { // We make the default instance public, so it can be initialized by // non-friend code. - printer->Print(variables_, - "public:\n" - "static ::google::protobuf::internal::ExplicitlyConstructed< ::std::string>" - " $default_variable_name$;\n" - "private:\n"); + format( + "public:\n" + "static ::$proto_ns$::internal::ExplicitlyConstructed" + " $default_variable_name$;\n" + "private:\n"); } } -void StringFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { +void StringFieldGenerator::GenerateAccessorDeclarations( + io::Printer* printer) const { + Formatter format(printer, variables_); // If we're using StringFieldGenerator for a field with a ctype, it's // because that ctype isn't actually implemented. In particular, this is // true of ctype=CORD and ctype=STRING_PIECE in the open source release. @@ -159,103 +149,99 @@ GenerateAccessorDeclarations(io::Printer* printer) const { // reflection interface since the reflection interface is independent of // the string's underlying representation. - bool unknown_ctype = - descriptor_->options().ctype() != EffectiveStringCType(descriptor_); + bool unknown_ctype = descriptor_->options().ctype() != + EffectiveStringCType(descriptor_, options_); if (unknown_ctype) { - printer->Outdent(); - printer->Print( - " private:\n" - " // Hidden due to unknown ctype option.\n"); - printer->Indent(); + format.Outdent(); + format( + " private:\n" + " // Hidden due to unknown ctype option.\n"); + format.Indent(); } - printer->Print(variables_, - "$deprecated_attr$const ::std::string& $name$() const;\n"); - printer->Annotate("name", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$void ${$set_$name$$}$(const ::std::string& value);\n"); - printer->Annotate("{", "}", descriptor_); - - printer->Print(variables_, - "#if LANG_CXX11\n" - "$deprecated_attr$void ${$set_$name$$}$(::std::string&& value);\n" - "#endif\n"); - printer->Annotate("{", "}", descriptor_); - - printer->Print( - variables_, - "$deprecated_attr$void ${$set_$name$$}$(const char* value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$set_$name$$}$(const $pointer_type$* " - "value, size_t size)" - ";\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$::std::string* ${$mutable_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, "$deprecated_attr$::std::string* $release_name$();\n"); - printer->Annotate("release_name", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$void ${$set_allocated_$name$$}$(::std::string* $name$);\n"); - printer->Annotate("{", "}", descriptor_); - if (SupportsArenas(descriptor_)) { - printer->Print( - variables_, - "PROTOBUF_RUNTIME_DEPRECATED(\"The unsafe_arena_ accessors for\"\n" - "\" string fields are deprecated and will be removed in a\"\n" - "\" future release.\")\n" - "::std::string* ${$unsafe_arena_release_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print( - variables_, - "PROTOBUF_RUNTIME_DEPRECATED(\"The unsafe_arena_ accessors for\"\n" - "\" string fields are deprecated and will be removed in a\"\n" - "\" future release.\")\n" - "void ${$unsafe_arena_set_allocated_$name$$}$(\n" - " ::std::string* $name$);\n"); - printer->Annotate("{", "}", descriptor_); + format( + "$deprecated_attr$const std::string& ${1$$name$$}$() const;\n" + "$deprecated_attr$void ${1$set_$name$$}$(const std::string& value);\n" + "$deprecated_attr$void ${1$set_$name$$}$(std::string&& value);\n" + "$deprecated_attr$void ${1$set_$name$$}$(const char* value);\n", + descriptor_); + if (!options_.opensource_runtime) { + format( + "$deprecated_attr$void ${1$set_$name$$}$(::StringPiece value);\n", + descriptor_); + } + format( + "$deprecated_attr$void ${1$set_$name$$}$(const $pointer_type$* " + "value, size_t size)" + ";\n" + "$deprecated_attr$std::string* ${1$mutable_$name$$}$();\n" + "$deprecated_attr$std::string* ${1$$release_name$$}$();\n" + "$deprecated_attr$void ${1$set_allocated_$name$$}$(std::string* " + "$name$);\n", + descriptor_); + if (options_.opensource_runtime) { + if (SupportsArenas(descriptor_)) { + format( + "$GOOGLE_PROTOBUF$_RUNTIME_DEPRECATED(\"The unsafe_arena_ accessors " + "for\"\n" + "\" string fields are deprecated and will be removed in a\"\n" + "\" future release.\")\n" + "std::string* ${1$unsafe_arena_release_$name$$}$();\n" + "$GOOGLE_PROTOBUF$_RUNTIME_DEPRECATED(\"The unsafe_arena_ accessors " + "for\"\n" + "\" string fields are deprecated and will be removed in a\"\n" + "\" future release.\")\n" + "void ${1$unsafe_arena_set_allocated_$name$$}$(\n" + " std::string* $name$);\n", + descriptor_); + } } if (unknown_ctype) { - printer->Outdent(); - printer->Print(" public:\n"); - printer->Indent(); + format.Outdent(); + format(" public:\n"); + format.Indent(); } } -void StringFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { +void StringFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); if (SupportsArenas(descriptor_)) { - printer->Print( - variables_, - "inline const ::std::string& $classname$::$name$() const {\n" + format( + "inline const std::string& $classname$::$name$() const {\n" " // @@protoc_insertion_point(field_get:$full_name$)\n" " return $name$_.Get();\n" "}\n" - "inline void $classname$::set_$name$(const ::std::string& value) {\n" + "inline void $classname$::set_$name$(const std::string& value) {\n" " $set_hasbit$\n" " $name$_.Set$lite$($default_variable$, value, GetArenaNoVirtual());\n" " // @@protoc_insertion_point(field_set:$full_name$)\n" "}\n" - "#if LANG_CXX11\n" - "inline void $classname$::set_$name$(::std::string&& value) {\n" + "inline void $classname$::set_$name$(std::string&& value) {\n" " $set_hasbit$\n" " $name$_.Set$lite$(\n" " $default_variable$, ::std::move(value), GetArenaNoVirtual());\n" " // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n" "}\n" - "#endif\n" "inline void $classname$::set_$name$(const char* value) {\n" " $null_check$" " $set_hasbit$\n" " $name$_.Set$lite$($default_variable$, $string_piece$(value),\n" " GetArenaNoVirtual());\n" " // @@protoc_insertion_point(field_set_char:$full_name$)\n" - "}\n" + "}\n"); + if (!options_.opensource_runtime) { + format( + "inline void $classname$::set_$name$(::StringPiece value) {\n" + " $set_hasbit$\n" + " $name$_.Set$lite$($default_variable$, value, " + "GetArenaNoVirtual());\n" + " // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n" + "}\n"); + } + format( "inline " "void $classname$::set_$name$(const $pointer_type$* value,\n" " size_t size) {\n" @@ -265,32 +251,33 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { "GetArenaNoVirtual());\n" " // @@protoc_insertion_point(field_set_pointer:$full_name$)\n" "}\n" - "inline ::std::string* $classname$::mutable_$name$() {\n" + "inline std::string* $classname$::mutable_$name$() {\n" " $set_hasbit$\n" " // @@protoc_insertion_point(field_mutable:$full_name$)\n" " return $name$_.Mutable($default_variable$, GetArenaNoVirtual());\n" "}\n" - "inline ::std::string* $classname$::$release_name$() {\n" + "inline std::string* $classname$::$release_name$() {\n" " // @@protoc_insertion_point(field_release:$full_name$)\n"); if (HasFieldPresence(descriptor_->file())) { - printer->Print(variables_, - " if (!has_$name$()) {\n" - " return NULL;\n" - " }\n" - " $clear_hasbit$\n" - " return $name$_.ReleaseNonDefault(" - "$default_variable$, GetArenaNoVirtual());\n"); + format( + " if (!has_$name$()) {\n" + " return nullptr;\n" + " }\n" + " $clear_hasbit$\n" + " return $name$_.ReleaseNonDefault(" + "$default_variable$, GetArenaNoVirtual());\n"); } else { - printer->Print(variables_, - " $clear_hasbit$\n" - " return $name$_.Release($default_variable$, GetArenaNoVirtual());\n"); + format( + " $clear_hasbit$\n" + " return $name$_.Release($default_variable$, " + "GetArenaNoVirtual());\n"); } - printer->Print(variables_, + format( "}\n" - "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n" - " if ($name$ != NULL) {\n" + "inline void $classname$::set_allocated_$name$(std::string* $name$) {\n" + " if ($name$ != nullptr) {\n" " $set_hasbit$\n" " } else {\n" " $clear_hasbit$\n" @@ -298,55 +285,64 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " $name$_.SetAllocated($default_variable$, $name$,\n" " GetArenaNoVirtual());\n" " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n" - "}\n" - "inline ::std::string* $classname$::unsafe_arena_release_$name$() {\n" - " // " - "@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n" - " GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n" - " $clear_hasbit$\n" - " return $name$_.UnsafeArenaRelease($default_variable$,\n" - " GetArenaNoVirtual());\n" - "}\n" - "inline void $classname$::unsafe_arena_set_allocated_$name$(\n" - " ::std::string* $name$) {\n" - " GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n" - " if ($name$ != NULL) {\n" - " $set_hasbit$\n" - " } else {\n" - " $clear_hasbit$\n" - " }\n" - " $name$_.UnsafeArenaSetAllocated($default_variable$,\n" - " $name$, GetArenaNoVirtual());\n" - " // @@protoc_insertion_point(field_unsafe_arena_set_allocated:" - "$full_name$)\n" "}\n"); + if (options_.opensource_runtime) { + format( + "inline std::string* $classname$::unsafe_arena_release_$name$() {\n" + " // " + "@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n" + " $DCHK$(GetArenaNoVirtual() != nullptr);\n" + " $clear_hasbit$\n" + " return $name$_.UnsafeArenaRelease($default_variable$,\n" + " GetArenaNoVirtual());\n" + "}\n" + "inline void $classname$::unsafe_arena_set_allocated_$name$(\n" + " std::string* $name$) {\n" + " $DCHK$(GetArenaNoVirtual() != nullptr);\n" + " if ($name$ != nullptr) {\n" + " $set_hasbit$\n" + " } else {\n" + " $clear_hasbit$\n" + " }\n" + " $name$_.UnsafeArenaSetAllocated($default_variable$,\n" + " $name$, GetArenaNoVirtual());\n" + " // @@protoc_insertion_point(field_unsafe_arena_set_allocated:" + "$full_name$)\n" + "}\n"); + } } else { // No-arena case. - printer->Print( - variables_, - "inline const ::std::string& $classname$::$name$() const {\n" + format( + "inline const std::string& $classname$::$name$() const {\n" " // @@protoc_insertion_point(field_get:$full_name$)\n" " return $name$_.GetNoArena();\n" "}\n" - "inline void $classname$::set_$name$(const ::std::string& value) {\n" + "inline void $classname$::set_$name$(const std::string& value) {\n" " $set_hasbit$\n" " $name$_.SetNoArena($default_variable$, value);\n" " // @@protoc_insertion_point(field_set:$full_name$)\n" "}\n" - "#if LANG_CXX11\n" - "inline void $classname$::set_$name$(::std::string&& value) {\n" + "inline void $classname$::set_$name$(std::string&& value) {\n" " $set_hasbit$\n" " $name$_.SetNoArena(\n" " $default_variable$, ::std::move(value));\n" " // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n" "}\n" - "#endif\n" "inline void $classname$::set_$name$(const char* value) {\n" " $null_check$" " $set_hasbit$\n" " $name$_.SetNoArena($default_variable$, $string_piece$(value));\n" " // @@protoc_insertion_point(field_set_char:$full_name$)\n" - "}\n" + "}\n"); + if (!options_.opensource_runtime) { + format( + "inline void $classname$::set_$name$(::StringPiece value) {\n" + " $set_hasbit$\n" + " $name$_.SetNoArena($default_variable$, value);\n" + " // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n" + "}\n"); + } + format( "inline " "void $classname$::set_$name$(const $pointer_type$* value, " "size_t size) {\n" @@ -355,31 +351,31 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " $string_piece$(reinterpret_cast(value), size));\n" " // @@protoc_insertion_point(field_set_pointer:$full_name$)\n" "}\n" - "inline ::std::string* $classname$::mutable_$name$() {\n" + "inline std::string* $classname$::mutable_$name$() {\n" " $set_hasbit$\n" " // @@protoc_insertion_point(field_mutable:$full_name$)\n" " return $name$_.MutableNoArena($default_variable$);\n" "}\n" - "inline ::std::string* $classname$::$release_name$() {\n" + "inline std::string* $classname$::$release_name$() {\n" " // @@protoc_insertion_point(field_release:$full_name$)\n"); if (HasFieldPresence(descriptor_->file())) { - printer->Print(variables_, - " if (!has_$name$()) {\n" - " return NULL;\n" - " }\n" - " $clear_hasbit$\n" - " return $name$_.ReleaseNonDefaultNoArena($default_variable$);\n"); + format( + " if (!has_$name$()) {\n" + " return nullptr;\n" + " }\n" + " $clear_hasbit$\n" + " return $name$_.ReleaseNonDefaultNoArena($default_variable$);\n"); } else { - printer->Print(variables_, - " $clear_hasbit$\n" - " return $name$_.ReleaseNoArena($default_variable$);\n"); + format( + " $clear_hasbit$\n" + " return $name$_.ReleaseNoArena($default_variable$);\n"); } - printer->Print(variables_, + format( "}\n" - "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n" - " if ($name$ != NULL) {\n" + "inline void $classname$::set_allocated_$name$(std::string* $name$) {\n" + " if ($name$ != nullptr) {\n" " $set_hasbit$\n" " } else {\n" " $clear_hasbit$\n" @@ -390,43 +386,43 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { } } -void StringFieldGenerator:: -GenerateNonInlineAccessorDefinitions(io::Printer* printer) const { +void StringFieldGenerator::GenerateNonInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); if (!descriptor_->default_value_string().empty()) { // Initialized in GenerateDefaultInstanceAllocator. - printer->Print(variables_, - "::google::protobuf::internal::ExplicitlyConstructed<::std::string> " - "$classname$::$default_variable_name$;\n"); + format( + "::$proto_ns$::internal::ExplicitlyConstructed " + "$classname$::$default_variable_name$;\n"); } } -void StringFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { +void StringFieldGenerator::GenerateClearingCode(io::Printer* printer) const { + Formatter format(printer, variables_); // Two-dimension specialization here: supporting arenas or not, and default // value is the empty string or not. Complexity here ensures the minimal // number of branches / amount of extraneous code at runtime (given that the // below methods are inlined one-liners)! if (SupportsArenas(descriptor_)) { if (descriptor_->default_value_string().empty()) { - printer->Print(variables_, - "$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n"); + format( + "$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n"); } else { - printer->Print(variables_, - "$name$_.ClearToDefault($default_variable$, GetArenaNoVirtual());\n"); + format( + "$name$_.ClearToDefault($default_variable$, GetArenaNoVirtual());\n"); } } else { if (descriptor_->default_value_string().empty()) { - printer->Print(variables_, - "$name$_.ClearToEmptyNoArena($default_variable$);\n"); + format("$name$_.ClearToEmptyNoArena($default_variable$);\n"); } else { - printer->Print(variables_, - "$name$_.ClearToDefaultNoArena($default_variable$);\n"); + format("$name$_.ClearToDefaultNoArena($default_variable$);\n"); } } } -void StringFieldGenerator:: -GenerateMessageClearingCode(io::Printer* printer) const { +void StringFieldGenerator::GenerateMessageClearingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); // Two-dimension specialization here: supporting arenas, field presence, or // not, and default value is the empty string or not. Complexity here ensures // the minimal number of branches / amount of extraneous code at runtime @@ -435,8 +431,7 @@ GenerateMessageClearingCode(io::Printer* printer) const { // If we have field presence, then the Clear() method of the protocol buffer // will have checked that this field is set. If so, we can avoid redundant // checks against default_variable. - const bool must_be_present = - HasFieldPresence(descriptor_->file()); + const bool must_be_present = HasFieldPresence(descriptor_->file()); if (inlined_ && must_be_present) { // Calling mutable_$name$() gives us a string reference and sets the has bit @@ -447,74 +442,65 @@ GenerateMessageClearingCode(io::Printer* printer) const { // // For non-inlined strings, we distinguish from non-default by comparing // instances, rather than contents. - printer->Print(variables_, - "GOOGLE_DCHECK(!$name$_.IsDefault($default_variable$));\n"); + format("$DCHK$(!$name$_.IsDefault($default_variable$));\n"); } if (SupportsArenas(descriptor_)) { if (descriptor_->default_value_string().empty()) { if (must_be_present) { - printer->Print(variables_, - "$name$_.ClearNonDefaultToEmpty();\n"); + format("$name$_.ClearNonDefaultToEmpty();\n"); } else { - printer->Print(variables_, - "$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n"); + format( + "$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n"); } } else { // Clear to a non-empty default is more involved, as we try to use the // Arena if one is present and may need to reallocate the string. - printer->Print(variables_, - "$name$_.ClearToDefault($default_variable$, GetArenaNoVirtual());\n"); + format( + "$name$_.ClearToDefault($default_variable$, GetArenaNoVirtual());\n"); } } else if (must_be_present) { // When Arenas are disabled and field presence has been checked, we can // safely treat the ArenaStringPtr as a string*. if (descriptor_->default_value_string().empty()) { - printer->Print(variables_, "$name$_.ClearNonDefaultToEmptyNoArena();\n"); + format("$name$_.ClearNonDefaultToEmptyNoArena();\n"); } else { - printer->Print( - variables_, - "$name$_.UnsafeMutablePointer()->assign(*$default_variable$);\n"); + format("$name$_.UnsafeMutablePointer()->assign(*$default_variable$);\n"); } } else { if (descriptor_->default_value_string().empty()) { - printer->Print(variables_, - "$name$_.ClearToEmptyNoArena($default_variable$);\n"); + format("$name$_.ClearToEmptyNoArena($default_variable$);\n"); } else { - printer->Print(variables_, - "$name$_.ClearToDefaultNoArena($default_variable$);\n"); + format("$name$_.ClearToDefaultNoArena($default_variable$);\n"); } } } -void StringFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { +void StringFieldGenerator::GenerateMergingCode(io::Printer* printer) const { + Formatter format(printer, variables_); if (SupportsArenas(descriptor_) || descriptor_->containing_oneof() != NULL) { // TODO(gpike): improve this - printer->Print(variables_, "set_$name$(from.$name$());\n"); + format("set_$name$(from.$name$());\n"); } else { - printer->Print(variables_, - "$set_hasbit$\n" - "$name$_.AssignWithDefault($default_variable$, from.$name$_);\n"); + format( + "$set_hasbit$\n" + "$name$_.AssignWithDefault($default_variable$, from.$name$_);\n"); } } -void StringFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { +void StringFieldGenerator::GenerateSwappingCode(io::Printer* printer) const { + Formatter format(printer, variables_); if (inlined_) { - printer->Print( - variables_, - "$name$_.Swap(&other->$name$_);\n"); + format("$name$_.Swap(&other->$name$_);\n"); } else { - printer->Print( - variables_, + format( "$name$_.Swap(&other->$name$_, $default_variable$,\n" " GetArenaNoVirtual());\n"); } } -void StringFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { +void StringFieldGenerator::GenerateConstructorCode(io::Printer* printer) const { + Formatter format(printer, variables_); // TODO(ckennelly): Construct non-empty strings as part of the initializer // list. if (inlined_ && descriptor_->default_value_string().empty()) { @@ -522,125 +508,146 @@ GenerateConstructorCode(io::Printer* printer) const { return; } - printer->Print(variables_, - "$name$_.UnsafeSetDefault($default_variable$);\n"); + format("$name$_.UnsafeSetDefault($default_variable$);\n"); } -void StringFieldGenerator:: -GenerateCopyConstructorCode(io::Printer* printer) const { +void StringFieldGenerator::GenerateCopyConstructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); GenerateConstructorCode(printer); if (HasFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "if (from.has_$name$()) {\n"); + format("if (from.has_$name$()) {\n"); } else { - printer->Print(variables_, - "if (from.$name$().size() > 0) {\n"); + format("if (from.$name$().size() > 0) {\n"); } - printer->Indent(); + format.Indent(); if (SupportsArenas(descriptor_) || descriptor_->containing_oneof() != NULL) { // TODO(gpike): improve this - printer->Print(variables_, - "$name$_.Set$lite$($default_variable$, from.$name$(),\n" - " GetArenaNoVirtual());\n"); + format( + "$name$_.Set$lite$($default_variable$, from.$name$(),\n" + " GetArenaNoVirtual());\n"); } else { - printer->Print(variables_, - "$name$_.AssignWithDefault($default_variable$, from.$name$_);\n"); + format("$name$_.AssignWithDefault($default_variable$, from.$name$_);\n"); } - printer->Outdent(); - printer->Print("}\n"); + format.Outdent(); + format("}\n"); } -void StringFieldGenerator:: -GenerateDestructorCode(io::Printer* printer) const { +void StringFieldGenerator::GenerateDestructorCode(io::Printer* printer) const { + Formatter format(printer, variables_); if (inlined_) { // The destructor is automatically invoked. return; } - printer->Print(variables_, "$name$_.DestroyNoArena($default_variable$);\n"); + format("$name$_.DestroyNoArena($default_variable$);\n"); } bool StringFieldGenerator::GenerateArenaDestructorCode( io::Printer* printer) const { + Formatter format(printer, variables_); if (!inlined_) { return false; } - printer->Print(variables_, - "_this->$name$_.DestroyNoArena($default_variable$);\n"); + format("_this->$name$_.DestroyNoArena($default_variable$);\n"); return true; } -void StringFieldGenerator:: -GenerateDefaultInstanceAllocator(io::Printer* printer) const { +void StringFieldGenerator::GenerateDefaultInstanceAllocator( + io::Printer* printer) const { + Formatter format(printer, variables_); if (!descriptor_->default_value_string().empty()) { - printer->Print( - variables_, + format( "$ns$::$classname$::$default_variable_name$.DefaultConstruct();\n" "*$ns$::$classname$::$default_variable_name$.get_mutable() = " - "::std::string($default$, $default_length$);\n" - "::google::protobuf::internal::OnShutdownDestroyString(\n" - " $ns$::$classname$::$default_variable_name$.get_mutable());\n" - ); + "std::string($default$, $default_length$);\n" + "::$proto_ns$::internal::OnShutdownDestroyString(\n" + " $ns$::$classname$::$default_variable_name$.get_mutable());\n"); } } -void StringFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::Read$declared_type$(\n" - " input, this->mutable_$name$()));\n"); +void StringFieldGenerator::GenerateMergeFromCodedStream( + io::Printer* printer) const { + Formatter format(printer, variables_); + // The google3 version of proto2 has ArenaStrings and parses into them + // directly, but for the open-source release, we always parse into std::string + // instances. Note that for lite, we do similarly to the open source release + // and use std::string, not ArenaString. + if (!options_.opensource_runtime && !inlined_ && + SupportsArenas(descriptor_) && !lite_) { + // If arena != NULL, the current string is either an ArenaString (no + // destructor necessary) or a materialized std::string (and is on the + // Arena's destructor list). No call to ArenaStringPtr::Destroy is needed. + format( + "if (arena != nullptr) {\n" + " ::$proto_ns$::internal::TaggedPtr str =\n" + " ::$proto_ns$::internal::ReadArenaString(input, arena);\n" + " DO_(!str.IsNull());\n" + " $set_hasbit_io$\n" + " $name$_.UnsafeSetTaggedPointer(str);\n" + "} else {\n" + " DO_(::$proto_ns$::internal::WireFormatLite::Read$declared_type$(\n" + " input, this->mutable_$name$()));\n" + "}\n"); + } else { + format( + "DO_(::$proto_ns$::internal::WireFormatLite::Read$declared_type$(\n" + " input, this->mutable_$name$()));\n"); + } if (descriptor_->type() == FieldDescriptor::TYPE_STRING) { GenerateUtf8CheckCodeForString( - descriptor_, options_, true, variables_, + descriptor_, options_, true, "this->$name$().data(), static_cast(this->$name$().length()),\n", - printer); + format); } } -bool StringFieldGenerator:: -MergeFromCodedStreamNeedsArena() const { - return false; +bool StringFieldGenerator::MergeFromCodedStreamNeedsArena() const { + return !lite_ && !inlined_ && !options_.opensource_runtime; } -void StringFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { +void StringFieldGenerator::GenerateSerializeWithCachedSizes( + io::Printer* printer) const { + Formatter format(printer, variables_); if (descriptor_->type() == FieldDescriptor::TYPE_STRING) { GenerateUtf8CheckCodeForString( - descriptor_, options_, false, variables_, + descriptor_, options_, false, "this->$name$().data(), static_cast(this->$name$().length()),\n", - printer); + format); } - printer->Print(variables_, - "::google::protobuf::internal::WireFormatLite::Write$declared_type$MaybeAliased(\n" - " $number$, this->$name$(), output);\n"); + format( + "::$proto_ns$::internal::WireFormatLite::Write$declared_type$" + "MaybeAliased(\n" + " $number$, this->$name$(), output);\n"); } -void StringFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { +void StringFieldGenerator::GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const { + Formatter format(printer, variables_); if (descriptor_->type() == FieldDescriptor::TYPE_STRING) { GenerateUtf8CheckCodeForString( - descriptor_, options_, false, variables_, + descriptor_, options_, false, "this->$name$().data(), static_cast(this->$name$().length()),\n", - printer); + format); } - printer->Print(variables_, - "target =\n" - " ::google::protobuf::internal::WireFormatLite::Write$declared_type$ToArray(\n" - " $number$, this->$name$(), target);\n"); + format( + "target =\n" + " ::$proto_ns$::internal::WireFormatLite::Write$declared_type$ToArray(\n" + " $number$, this->$name$(), target);\n"); } -void StringFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { - printer->Print(variables_, - "total_size += $tag_size$ +\n" - " ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n" - " this->$name$());\n"); +void StringFieldGenerator::GenerateByteSize(io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "total_size += $tag_size$ +\n" + " ::$proto_ns$::internal::WireFormatLite::$declared_type$Size(\n" + " this->$name$());\n"); } uint32 StringFieldGenerator::CalculateFieldTag() const { @@ -659,19 +666,19 @@ StringOneofFieldGenerator::StringOneofFieldGenerator( StringOneofFieldGenerator::~StringOneofFieldGenerator() {} -void StringOneofFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { +void StringOneofFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); if (SupportsArenas(descriptor_)) { - printer->Print( - variables_, - "inline const ::std::string& $classname$::$name$() const {\n" + format( + "inline const std::string& $classname$::$name$() const {\n" " // @@protoc_insertion_point(field_get:$full_name$)\n" " if (has_$name$()) {\n" " return $field_member$.Get();\n" " }\n" " return *$default_variable$;\n" "}\n" - "inline void $classname$::set_$name$(const ::std::string& value) {\n" + "inline void $classname$::set_$name$(const std::string& value) {\n" " if (!has_$name$()) {\n" " clear_$oneof_name$();\n" " set_has_$name$();\n" @@ -681,8 +688,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " GetArenaNoVirtual());\n" " // @@protoc_insertion_point(field_set:$full_name$)\n" "}\n" - "#if LANG_CXX11\n" - "inline void $classname$::set_$name$(::std::string&& value) {\n" + "inline void $classname$::set_$name$(std::string&& value) {\n" " // @@protoc_insertion_point(field_set:$full_name$)\n" " if (!has_$name$()) {\n" " clear_$oneof_name$();\n" @@ -693,7 +699,6 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " $default_variable$, ::std::move(value), GetArenaNoVirtual());\n" " // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n" "}\n" - "#endif\n" "inline void $classname$::set_$name$(const char* value) {\n" " $null_check$" " if (!has_$name$()) {\n" @@ -704,7 +709,21 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " $field_member$.Set$lite$($default_variable$,\n" " $string_piece$(value), GetArenaNoVirtual());\n" " // @@protoc_insertion_point(field_set_char:$full_name$)\n" - "}\n" + "}\n"); + if (!options_.opensource_runtime) { + format( + "inline void $classname$::set_$name$(::StringPiece value) {\n" + " if (!has_$name$()) {\n" + " clear_$oneof_name$();\n" + " set_has_$name$();\n" + " $field_member$.UnsafeSetDefault($default_variable$);\n" + " }\n" + " $field_member$.Set$lite$($default_variable$, value,\n" + " GetArenaNoVirtual());\n" + " // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n" + "}\n"); + } + format( "inline " "void $classname$::set_$name$(const $pointer_type$* value,\n" " size_t size) {\n" @@ -719,7 +738,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " GetArenaNoVirtual());\n" " // @@protoc_insertion_point(field_set_pointer:$full_name$)\n" "}\n" - "inline ::std::string* $classname$::mutable_$name$() {\n" + "inline std::string* $classname$::mutable_$name$() {\n" " if (!has_$name$()) {\n" " clear_$oneof_name$();\n" " set_has_$name$();\n" @@ -729,67 +748,67 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " GetArenaNoVirtual());\n" " // @@protoc_insertion_point(field_mutable:$full_name$)\n" "}\n" - "inline ::std::string* $classname$::$release_name$() {\n" + "inline std::string* $classname$::$release_name$() {\n" " // @@protoc_insertion_point(field_release:$full_name$)\n" " if (has_$name$()) {\n" " clear_has_$oneof_name$();\n" " return $field_member$.Release($default_variable$,\n" " GetArenaNoVirtual());\n" " } else {\n" - " return NULL;\n" + " return nullptr;\n" " }\n" "}\n" - "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n" - " if (!has_$name$()) {\n" - " $field_member$.UnsafeSetDefault($default_variable$);\n" + "inline void $classname$::set_allocated_$name$(std::string* $name$) {\n" + " if (has_$oneof_name$()) {\n" + " clear_$oneof_name$();\n" " }\n" - " clear_$oneof_name$();\n" - " if ($name$ != NULL) {\n" + " if ($name$ != nullptr) {\n" " set_has_$name$();\n" - " $field_member$.SetAllocated($default_variable$, $name$,\n" - " GetArenaNoVirtual());\n" + " $field_member$.UnsafeSetDefault($name$);\n" " }\n" " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n" - "}\n" - "inline ::std::string* $classname$::unsafe_arena_release_$name$() {\n" - " // " - "@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n" - " GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n" - " if (has_$name$()) {\n" - " clear_has_$oneof_name$();\n" - " return $field_member$.UnsafeArenaRelease(\n" - " $default_variable$, GetArenaNoVirtual());\n" - " } else {\n" - " return NULL;\n" - " }\n" - "}\n" - "inline void $classname$::unsafe_arena_set_allocated_$name$(" - "::std::string* $name$) {\n" - " GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n" - " if (!has_$name$()) {\n" - " $field_member$.UnsafeSetDefault($default_variable$);\n" - " }\n" - " clear_$oneof_name$();\n" - " if ($name$) {\n" - " set_has_$name$();\n" - " $field_member$.UnsafeArenaSetAllocated($default_variable$, " - "$name$, GetArenaNoVirtual());\n" - " }\n" - " // @@protoc_insertion_point(field_unsafe_arena_set_allocated:" - "$full_name$)\n" "}\n"); + if (options_.opensource_runtime) { + format( + "inline std::string* $classname$::unsafe_arena_release_$name$() {\n" + " // " + "@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n" + " $DCHK$(GetArenaNoVirtual() != nullptr);\n" + " if (has_$name$()) {\n" + " clear_has_$oneof_name$();\n" + " return $field_member$.UnsafeArenaRelease(\n" + " $default_variable$, GetArenaNoVirtual());\n" + " } else {\n" + " return nullptr;\n" + " }\n" + "}\n" + "inline void $classname$::unsafe_arena_set_allocated_$name$(" + "std::string* $name$) {\n" + " $DCHK$(GetArenaNoVirtual() != nullptr);\n" + " if (!has_$name$()) {\n" + " $field_member$.UnsafeSetDefault($default_variable$);\n" + " }\n" + " clear_$oneof_name$();\n" + " if ($name$) {\n" + " set_has_$name$();\n" + " $field_member$.UnsafeArenaSetAllocated($default_variable$, " + "$name$, GetArenaNoVirtual());\n" + " }\n" + " // @@protoc_insertion_point(field_unsafe_arena_set_allocated:" + "$full_name$)\n" + "}\n"); + } } else { // No-arena case. - printer->Print( - variables_, - "inline const ::std::string& $classname$::$name$() const {\n" + format( + "inline const std::string& $classname$::$name$() const {\n" " // @@protoc_insertion_point(field_get:$full_name$)\n" " if (has_$name$()) {\n" " return $field_member$.GetNoArena();\n" " }\n" " return *$default_variable$;\n" "}\n" - "inline void $classname$::set_$name$(const ::std::string& value) {\n" + "inline void $classname$::set_$name$(const std::string& value) {\n" " // @@protoc_insertion_point(field_set:$full_name$)\n" " if (!has_$name$()) {\n" " clear_$oneof_name$();\n" @@ -799,8 +818,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " $field_member$.SetNoArena($default_variable$, value);\n" " // @@protoc_insertion_point(field_set:$full_name$)\n" "}\n" - "#if LANG_CXX11\n" - "inline void $classname$::set_$name$(::std::string&& value) {\n" + "inline void $classname$::set_$name$(std::string&& value) {\n" " // @@protoc_insertion_point(field_set:$full_name$)\n" " if (!has_$name$()) {\n" " clear_$oneof_name$();\n" @@ -810,7 +828,6 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " $field_member$.SetNoArena($default_variable$, ::std::move(value));\n" " // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n" "}\n" - "#endif\n" "inline void $classname$::set_$name$(const char* value) {\n" " $null_check$" " if (!has_$name$()) {\n" @@ -821,7 +838,20 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " $field_member$.SetNoArena($default_variable$,\n" " $string_piece$(value));\n" " // @@protoc_insertion_point(field_set_char:$full_name$)\n" - "}\n" + "}\n"); + if (!options_.opensource_runtime) { + format( + "inline void $classname$::set_$name$(::StringPiece value) {\n" + " if (!has_$name$()) {\n" + " clear_$oneof_name$();\n" + " set_has_$name$();\n" + " $field_member$.UnsafeSetDefault($default_variable$);\n" + " }\n" + " $field_member$.SetNoArena($default_variable$, value);\n" + " // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n" + "}\n"); + } + format( "inline " "void $classname$::set_$name$(const $pointer_type$* value, size_t " "size) {\n" @@ -834,7 +864,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " reinterpret_cast(value), size));\n" " // @@protoc_insertion_point(field_set_pointer:$full_name$)\n" "}\n" - "inline ::std::string* $classname$::mutable_$name$() {\n" + "inline std::string* $classname$::mutable_$name$() {\n" " if (!has_$name$()) {\n" " clear_$oneof_name$();\n" " set_has_$name$();\n" @@ -843,341 +873,369 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " // @@protoc_insertion_point(field_mutable:$full_name$)\n" " return $field_member$.MutableNoArena($default_variable$);\n" "}\n" - "inline ::std::string* $classname$::$release_name$() {\n" + "inline std::string* $classname$::$release_name$() {\n" " // @@protoc_insertion_point(field_release:$full_name$)\n" " if (has_$name$()) {\n" " clear_has_$oneof_name$();\n" " return $field_member$.ReleaseNoArena($default_variable$);\n" " } else {\n" - " return NULL;\n" + " return nullptr;\n" " }\n" "}\n" - "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n" - " if (!has_$name$()) {\n" - " $field_member$.UnsafeSetDefault($default_variable$);\n" + "inline void $classname$::set_allocated_$name$(std::string* $name$) {\n" + " if (has_$oneof_name$()) {\n" + " clear_$oneof_name$();\n" " }\n" - " clear_$oneof_name$();\n" - " if ($name$ != NULL) {\n" + " if ($name$ != nullptr) {\n" " set_has_$name$();\n" - " $field_member$.SetAllocatedNoArena($default_variable$, $name$);\n" + " $field_member$.UnsafeSetDefault($name$);\n" " }\n" " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n" "}\n"); } } -void StringOneofFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { +void StringOneofFieldGenerator::GenerateClearingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - "$field_member$.Destroy($default_variable$,\n" - " GetArenaNoVirtual());\n"); + format( + "$field_member$.Destroy($default_variable$,\n" + " GetArenaNoVirtual());\n"); } else { - printer->Print(variables_, - "$field_member$.DestroyNoArena($default_variable$);\n"); + format("$field_member$.DestroyNoArena($default_variable$);\n"); } } -void StringOneofFieldGenerator:: -GenerateMessageClearingCode(io::Printer* printer) const { +void StringOneofFieldGenerator::GenerateMessageClearingCode( + io::Printer* printer) const { return GenerateClearingCode(printer); } -void StringOneofFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { +void StringOneofFieldGenerator::GenerateSwappingCode( + io::Printer* printer) const { // Don't print any swapping code. Swapping the union will swap this field. } -void StringOneofFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - printer->Print( - variables_, +void StringOneofFieldGenerator::GenerateConstructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( "$ns$::_$classname$_default_instance_.$name$_.UnsafeSetDefault(\n" " $default_variable$);\n"); } -void StringOneofFieldGenerator:: -GenerateDestructorCode(io::Printer* printer) const { - printer->Print(variables_, - "if (has_$name$()) {\n" - " $field_member$.DestroyNoArena($default_variable$);\n" - "}\n"); +void StringOneofFieldGenerator::GenerateDestructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "if (has_$name$()) {\n" + " $field_member$.DestroyNoArena($default_variable$);\n" + "}\n"); } -void StringOneofFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::Read$declared_type$(\n" - " input, this->mutable_$name$()));\n"); +void StringOneofFieldGenerator::GenerateMergeFromCodedStream( + io::Printer* printer) const { + Formatter format(printer, variables_); + // See above: ArenaString is not included in the open-source release. + if (!options_.opensource_runtime && SupportsArenas(descriptor_) && !lite_) { + // If has_$name$(), then the current string is either an ArenaString (no + // destructor necessary) or a materialized std::string (and is on the + // Arena's destructor list). No call to ArenaStringPtr::Destroy is needed. + format( + "if (arena != nullptr) {\n" + " clear_$oneof_name$();\n" + " if (!has_$name$()) {\n" + " $field_member$.UnsafeSetDefault($default_variable$);\n" + " set_has_$name$();\n" + " }\n" + " ::$proto_ns$::internal::TaggedPtr new_value =\n" + " ::$proto_ns$::internal::ReadArenaString(input, arena);\n" + " DO_(!new_value.IsNull());\n" + " $field_member$.UnsafeSetTaggedPointer(new_value);\n" + "} else {\n" + " DO_(::$proto_ns$::internal::WireFormatLite::Read$declared_type$(\n" + " input, this->mutable_$name$()));\n" + "}\n"); + } else { + format( + "DO_(::$proto_ns$::internal::WireFormatLite::Read$declared_type$(\n" + " input, this->mutable_$name$()));\n"); + } if (descriptor_->type() == FieldDescriptor::TYPE_STRING) { GenerateUtf8CheckCodeForString( - descriptor_, options_, true, variables_, + descriptor_, options_, true, "this->$name$().data(), static_cast(this->$name$().length()),\n", - printer); + format); } } - // =================================================================== RepeatedStringFieldGenerator::RepeatedStringFieldGenerator( const FieldDescriptor* descriptor, const Options& options) - : FieldGenerator(options), descriptor_(descriptor) { + : FieldGenerator(descriptor, options) { SetStringVariables(descriptor, &variables_, options); } RepeatedStringFieldGenerator::~RepeatedStringFieldGenerator() {} -void RepeatedStringFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { - printer->Print(variables_, - "::google::protobuf::RepeatedPtrField< ::std::string> $name$_;\n"); +void RepeatedStringFieldGenerator::GeneratePrivateMembers( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("::$proto_ns$::RepeatedPtrField $name$_;\n"); } -void RepeatedStringFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { +void RepeatedStringFieldGenerator::GenerateAccessorDeclarations( + io::Printer* printer) const { + Formatter format(printer, variables_); // See comment above about unknown ctypes. - bool unknown_ctype = - descriptor_->options().ctype() != EffectiveStringCType(descriptor_); + bool unknown_ctype = descriptor_->options().ctype() != + EffectiveStringCType(descriptor_, options_); if (unknown_ctype) { - printer->Outdent(); - printer->Print( - " private:\n" - " // Hidden due to unknown ctype option.\n"); - printer->Indent(); + format.Outdent(); + format( + " private:\n" + " // Hidden due to unknown ctype option.\n"); + format.Indent(); } - printer->Print(variables_, - "$deprecated_attr$const ::std::string& $name$(int index) const;\n"); - printer->Annotate("name", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$::std::string* ${$mutable_$name$$}$(int index);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$set_$name$$}$(int index, const " - "::std::string& value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print( - variables_, - "#if LANG_CXX11\n" - "$deprecated_attr$void ${$set_$name$$}$(int index, ::std::string&& value);\n" - "#endif\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$set_$name$$}$(int index, const " - "char* value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "" - "$deprecated_attr$void ${$set_$name$$}$(" - "int index, const $pointer_type$* value, size_t size);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$::std::string* ${$add_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$void ${$add_$name$$}$(const ::std::string& value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "#if LANG_CXX11\n" - "$deprecated_attr$void ${$add_$name$$}$(::std::string&& value);\n" - "#endif\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$void ${$add_$name$$}$(const char* value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$add_$name$$}$(const $pointer_type$* " - "value, size_t size)" - ";\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$const ::google::protobuf::RepeatedPtrField< ::std::string>& $name$() " - "const;\n"); - printer->Annotate("name", descriptor_); - printer->Print(variables_, - "$deprecated_attr$::google::protobuf::RepeatedPtrField< ::std::string>* " - "${$mutable_$name$$}$()" - ";\n"); - printer->Annotate("{", "}", descriptor_); + format( + "$deprecated_attr$const std::string& ${1$$name$$}$(int index) const;\n" + "$deprecated_attr$std::string* ${1$mutable_$name$$}$(int index);\n" + "$deprecated_attr$void ${1$set_$name$$}$(int index, const " + "std::string& value);\n" + "$deprecated_attr$void ${1$set_$name$$}$(int index, std::string&& " + "value);\n" + "$deprecated_attr$void ${1$set_$name$$}$(int index, const " + "char* value);\n", + descriptor_); + if (!options_.opensource_runtime) { + format( + "$deprecated_attr$void ${1$set_$name$$}$(int index, " + "StringPiece value);\n", + descriptor_); + } + format( + "$deprecated_attr$void ${1$set_$name$$}$(" + "int index, const $pointer_type$* value, size_t size);\n" + "$deprecated_attr$std::string* ${1$add_$name$$}$();\n" + "$deprecated_attr$void ${1$add_$name$$}$(const std::string& value);\n" + "$deprecated_attr$void ${1$add_$name$$}$(std::string&& value);\n" + "$deprecated_attr$void ${1$add_$name$$}$(const char* value);\n", + descriptor_); + if (!options_.opensource_runtime) { + format( + "$deprecated_attr$void ${1$add_$name$$}$(StringPiece value);\n", + descriptor_); + } + format( + "$deprecated_attr$void ${1$add_$name$$}$(const $pointer_type$* " + "value, size_t size)" + ";\n" + "$deprecated_attr$const ::$proto_ns$::RepeatedPtrField& " + "${1$$name$$}$() " + "const;\n" + "$deprecated_attr$::$proto_ns$::RepeatedPtrField* " + "${1$mutable_$name$$}$()" + ";\n", + descriptor_); if (unknown_ctype) { - printer->Outdent(); - printer->Print(" public:\n"); - printer->Indent(); + format.Outdent(); + format(" public:\n"); + format.Indent(); } } -void RepeatedStringFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { +void RepeatedStringFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); if (options_.safe_boundary_check) { - printer->Print(variables_, - "inline const ::std::string& $classname$::$name$(int index) const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return $name$_.InternalCheckedGet(\n" - " index, ::google::protobuf::internal::GetEmptyStringAlreadyInited());\n" - "}\n"); + format( + "inline const std::string& $classname$::$name$(int index) const {\n" + " // @@protoc_insertion_point(field_get:$full_name$)\n" + " return $name$_.InternalCheckedGet(\n" + " index, ::$proto_ns$::internal::GetEmptyStringAlreadyInited());\n" + "}\n"); } else { - printer->Print(variables_, - "inline const ::std::string& $classname$::$name$(int index) const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return $name$_.Get(index);\n" - "}\n"); + format( + "inline const std::string& $classname$::$name$(int index) const {\n" + " // @@protoc_insertion_point(field_get:$full_name$)\n" + " return $name$_.Get(index);\n" + "}\n"); } - printer->Print(variables_, - "inline ::std::string* $classname$::mutable_$name$(int index) {\n" - " // @@protoc_insertion_point(field_mutable:$full_name$)\n" - " return $name$_.Mutable(index);\n" - "}\n" - "inline void $classname$::set_$name$(int index, const ::std::string& value) {\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - " $name$_.Mutable(index)->assign(value);\n" - "}\n" - "#if LANG_CXX11\n" - "inline void $classname$::set_$name$(int index, ::std::string&& value) {\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - " $name$_.Mutable(index)->assign(std::move(value));\n" - "}\n" - "#endif\n" - "inline void $classname$::set_$name$(int index, const char* value) {\n" - " $null_check$" - " $name$_.Mutable(index)->assign(value);\n" - " // @@protoc_insertion_point(field_set_char:$full_name$)\n" - "}\n" - "inline void " - "$classname$::set_$name$" - "(int index, const $pointer_type$* value, size_t size) {\n" - " $name$_.Mutable(index)->assign(\n" - " reinterpret_cast(value), size);\n" - " // @@protoc_insertion_point(field_set_pointer:$full_name$)\n" - "}\n" - "inline ::std::string* $classname$::add_$name$() {\n" - " // @@protoc_insertion_point(field_add_mutable:$full_name$)\n" - " return $name$_.Add();\n" - "}\n" - "inline void $classname$::add_$name$(const ::std::string& value) {\n" - " $name$_.Add()->assign(value);\n" - " // @@protoc_insertion_point(field_add:$full_name$)\n" - "}\n" - "#if LANG_CXX11\n" - "inline void $classname$::add_$name$(::std::string&& value) {\n" - " $name$_.Add(std::move(value));\n" - " // @@protoc_insertion_point(field_add:$full_name$)\n" - "}\n" - "#endif\n" - "inline void $classname$::add_$name$(const char* value) {\n" - " $null_check$" - " $name$_.Add()->assign(value);\n" - " // @@protoc_insertion_point(field_add_char:$full_name$)\n" - "}\n" - "inline void " - "$classname$::add_$name$(const $pointer_type$* value, size_t size) {\n" - " $name$_.Add()->assign(reinterpret_cast(value), size);\n" - " // @@protoc_insertion_point(field_add_pointer:$full_name$)\n" - "}\n" - "inline const ::google::protobuf::RepeatedPtrField< ::std::string>&\n" - "$classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_list:$full_name$)\n" - " return $name$_;\n" - "}\n" - "inline ::google::protobuf::RepeatedPtrField< ::std::string>*\n" - "$classname$::mutable_$name$() {\n" - " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n" - " return &$name$_;\n" - "}\n"); + format( + "inline std::string* $classname$::mutable_$name$(int index) {\n" + " // @@protoc_insertion_point(field_mutable:$full_name$)\n" + " return $name$_.Mutable(index);\n" + "}\n" + "inline void $classname$::set_$name$(int index, const std::string& " + "value) " + "{\n" + " // @@protoc_insertion_point(field_set:$full_name$)\n" + " $name$_.Mutable(index)->assign(value);\n" + "}\n" + "inline void $classname$::set_$name$(int index, std::string&& value) {\n" + " // @@protoc_insertion_point(field_set:$full_name$)\n" + " $name$_.Mutable(index)->assign(std::move(value));\n" + "}\n" + "inline void $classname$::set_$name$(int index, const char* value) {\n" + " $null_check$" + " $name$_.Mutable(index)->assign(value);\n" + " // @@protoc_insertion_point(field_set_char:$full_name$)\n" + "}\n"); + if (!options_.opensource_runtime) { + format( + "inline void " + "$classname$::set_$name$(int index, StringPiece value) {\n" + " $name$_.Mutable(index)->assign(value.data(), value.size());\n" + " // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n" + "}\n"); + } + format( + "inline void " + "$classname$::set_$name$" + "(int index, const $pointer_type$* value, size_t size) {\n" + " $name$_.Mutable(index)->assign(\n" + " reinterpret_cast(value), size);\n" + " // @@protoc_insertion_point(field_set_pointer:$full_name$)\n" + "}\n" + "inline std::string* $classname$::add_$name$() {\n" + " // @@protoc_insertion_point(field_add_mutable:$full_name$)\n" + " return $name$_.Add();\n" + "}\n" + "inline void $classname$::add_$name$(const std::string& value) {\n" + " $name$_.Add()->assign(value);\n" + " // @@protoc_insertion_point(field_add:$full_name$)\n" + "}\n" + "inline void $classname$::add_$name$(std::string&& value) {\n" + " $name$_.Add(std::move(value));\n" + " // @@protoc_insertion_point(field_add:$full_name$)\n" + "}\n" + "inline void $classname$::add_$name$(const char* value) {\n" + " $null_check$" + " $name$_.Add()->assign(value);\n" + " // @@protoc_insertion_point(field_add_char:$full_name$)\n" + "}\n"); + if (!options_.opensource_runtime) { + format( + "inline void $classname$::add_$name$(StringPiece value) {\n" + " $name$_.Add()->assign(value.data(), value.size());\n" + " // @@protoc_insertion_point(field_add_string_piece:$full_name$)\n" + "}\n"); + } + format( + "inline void " + "$classname$::add_$name$(const $pointer_type$* value, size_t size) {\n" + " $name$_.Add()->assign(reinterpret_cast(value), size);\n" + " // @@protoc_insertion_point(field_add_pointer:$full_name$)\n" + "}\n" + "inline const ::$proto_ns$::RepeatedPtrField&\n" + "$classname$::$name$() const {\n" + " // @@protoc_insertion_point(field_list:$full_name$)\n" + " return $name$_;\n" + "}\n" + "inline ::$proto_ns$::RepeatedPtrField*\n" + "$classname$::mutable_$name$() {\n" + " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n" + " return &$name$_;\n" + "}\n"); } -void RepeatedStringFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.Clear();\n"); +void RepeatedStringFieldGenerator::GenerateClearingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.Clear();\n"); } -void RepeatedStringFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n"); +void RepeatedStringFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.MergeFrom(from.$name$_);\n"); } -void RepeatedStringFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_.InternalSwap(CastToBase(&other->$name$_));\n"); +void RepeatedStringFieldGenerator::GenerateSwappingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.InternalSwap(CastToBase(&other->$name$_));\n"); } -void RepeatedStringFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { +void RepeatedStringFieldGenerator::GenerateConstructorCode( + io::Printer* printer) const { // Not needed for repeated fields. } -void RepeatedStringFieldGenerator:: -GenerateCopyConstructorCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.CopyFrom(from.$name$_);"); +void RepeatedStringFieldGenerator::GenerateCopyConstructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.CopyFrom(from.$name$_);"); } -void RepeatedStringFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::Read$declared_type$(\n" - " input, this->add_$name$()));\n"); +void RepeatedStringFieldGenerator::GenerateMergeFromCodedStream( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "DO_(::$proto_ns$::internal::WireFormatLite::Read$declared_type$(\n" + " input, this->add_$name$()));\n"); if (descriptor_->type() == FieldDescriptor::TYPE_STRING) { GenerateUtf8CheckCodeForString( - descriptor_, options_, true, variables_, + descriptor_, options_, true, "this->$name$(this->$name$_size() - 1).data(),\n" "static_cast(this->$name$(this->$name$_size() - 1).length()),\n", - printer); + format); } } -void RepeatedStringFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n"); - printer->Indent(); +void RepeatedStringFieldGenerator::GenerateSerializeWithCachedSizes( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("for (int i = 0, n = this->$name$_size(); i < n; i++) {\n"); + format.Indent(); if (descriptor_->type() == FieldDescriptor::TYPE_STRING) { GenerateUtf8CheckCodeForString( - descriptor_, options_, false, variables_, + descriptor_, options_, false, "this->$name$(i).data(), static_cast(this->$name$(i).length()),\n", - printer); + format); } - printer->Outdent(); - printer->Print(variables_, - " ::google::protobuf::internal::WireFormatLite::Write$declared_type$(\n" - " $number$, this->$name$(i), output);\n" - "}\n"); + format.Outdent(); + format( + " ::$proto_ns$::internal::WireFormatLite::Write$declared_type$(\n" + " $number$, this->$name$(i), output);\n" + "}\n"); } -void RepeatedStringFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n"); - printer->Indent(); +void RepeatedStringFieldGenerator::GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("for (int i = 0, n = this->$name$_size(); i < n; i++) {\n"); + format.Indent(); if (descriptor_->type() == FieldDescriptor::TYPE_STRING) { GenerateUtf8CheckCodeForString( - descriptor_, options_, false, variables_, + descriptor_, options_, false, "this->$name$(i).data(), static_cast(this->$name$(i).length()),\n", - printer); + format); } - printer->Outdent(); - printer->Print(variables_, - " target = ::google::protobuf::internal::WireFormatLite::\n" - " Write$declared_type$ToArray($number$, this->$name$(i), target);\n" - "}\n"); + format.Outdent(); + format( + " target = ::$proto_ns$::internal::WireFormatLite::\n" + " Write$declared_type$ToArray($number$, this->$name$(i), target);\n" + "}\n"); } -void RepeatedStringFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { - printer->Print(variables_, - "total_size += $tag_size$ *\n" - " ::google::protobuf::internal::FromIntSize(this->$name$_size());\n" - "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n" - " total_size += ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n" - " this->$name$(i));\n" - "}\n"); +void RepeatedStringFieldGenerator::GenerateByteSize( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "total_size += $tag_size$ *\n" + " ::$proto_ns$::internal::FromIntSize(this->$name$_size());\n" + "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n" + " total_size += " + "::$proto_ns$::internal::WireFormatLite::$declared_type$Size(\n" + " this->$name$(i));\n" + "}\n"); } } // namespace cpp diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_string_field.h b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_string_field.h index 6cbf722f..3a1de551 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_string_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_string_field.h @@ -75,8 +75,6 @@ class StringFieldGenerator : public FieldGenerator { bool MergeFromCodedStreamNeedsArena() const; protected: - const FieldDescriptor* descriptor_; - std::map variables_; const bool lite_; bool inlined_; @@ -127,15 +125,12 @@ class RepeatedStringFieldGenerator : public FieldGenerator { void GenerateByteSize(io::Printer* printer) const; private: - const FieldDescriptor* descriptor_; - std::map variables_; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedStringFieldGenerator); }; } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_STRING_FIELD_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto index 7fe98759..47971082 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto @@ -35,11 +35,13 @@ // This file tests that various identifiers work as field and type names even // though the same identifiers are used internally by the C++ code generator. +// LINT: LEGACY_NAMES + syntax = "proto2"; // Some generic_services option(s) added automatically. // See: http://go/proto2-generic-services-default -option cc_generic_services = true; // auto-added +option cc_generic_services = true; // auto-added // We don't put this in a package within proto2 because we need to make sure // that the generated code doesn't depend on being in the proto2 namespace. @@ -55,17 +57,29 @@ message TestConflictingSymbolNames { optional int32 output = 2; optional string length = 3; repeated int32 i = 4; - repeated string new_element = 5 [ctype=STRING_PIECE]; + repeated string new_element = 5 [ctype = STRING_PIECE]; optional int32 total_size = 6; optional int32 tag = 7; enum TestEnum { FOO = 0; } - message Data1 { repeated int32 data = 1; } - message Data2 { repeated TestEnum data = 1; } - message Data3 { repeated string data = 1; } - message Data4 { repeated Data4 data = 1; } - message Data5 { repeated string data = 1 [ctype=STRING_PIECE]; } - message Data6 { repeated string data = 1 [ctype=CORD]; } + message Data1 { + repeated int32 data = 1; + } + message Data2 { + repeated TestEnum data = 1; + } + message Data3 { + repeated string data = 1; + } + message Data4 { + repeated Data4 data = 1; + } + message Data5 { + repeated string data = 1 [ctype = STRING_PIECE]; + } + message Data6 { + repeated string data = 1 [ctype = CORD]; + } optional int32 source = 8; optional int32 value = 9; @@ -91,10 +105,10 @@ message TestConflictingSymbolNames { optional uint32 reflection = 27; message Cord {} - optional string some_cord = 28 [ctype=CORD]; + optional string some_cord = 28 [ctype = CORD]; message StringPiece {} - optional string some_string_piece = 29 [ctype=STRING_PIECE]; + optional string some_string_piece = 29 [ctype = STRING_PIECE]; // Some keywords. optional uint32 int = 30; @@ -125,14 +139,15 @@ message TestConflictingSymbolNames { extensions 1000 to max; // NO_PROTO3 } -message TestConflictingSymbolNamesExtension { // NO_PROTO3 - extend TestConflictingSymbolNames { // NO_PROTO3 - repeated int32 repeated_int32_ext = 20423638 [packed=true]; // NO_PROTO3 - } // NO_PROTO3 -} // NO_PROTO3 +message TestConflictingSymbolNamesExtension { // NO_PROTO3 + extend TestConflictingSymbolNames { // NO_PROTO3 + repeated int32 repeated_int32_ext = 20423638 [packed = true]; // NO_PROTO3 + } // NO_PROTO3 +} // NO_PROTO3 message TestConflictingEnumNames { // NO_PROTO3 - enum NestedConflictingEnum { // NO_PROTO3 + enum while { // NO_PROTO3 + default = 0; // NO_PROTO3 and = 1; // NO_PROTO3 class = 2; // NO_PROTO3 int = 3; // NO_PROTO3 @@ -140,10 +155,11 @@ message TestConflictingEnumNames { // NO_PROTO3 XOR = 5; // NO_PROTO3 } // NO_PROTO3 - optional NestedConflictingEnum conflicting_enum = 1; // NO_PROTO3 + optional while conflicting_enum = 1; // NO_PROTO3 } // NO_PROTO3 -enum ConflictingEnum { // NO_PROTO3 +enum bool { // NO_PROTO3 + default = 0; // NO_PROTO3 NOT_EQ = 1; // NO_PROTO3 volatile = 2; // NO_PROTO3 return = 3; // NO_PROTO3 @@ -151,6 +167,14 @@ enum ConflictingEnum { // NO_PROTO3 message DummyMessage {} +message NULL { + optional int32 int = 1; +} + +extend TestConflictingSymbolNames { // NO_PROTO3 + optional int32 void = 314253; // NO_PROTO3 +} // NO_PROTO3 + // Message names that could conflict. message Shutdown {} message TableStruct {} diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_unittest.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_unittest.cc index 22b759a9..74310a7f 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_unittest.cc @@ -33,7 +33,7 @@ // Sanjay Ghemawat, Jeff Dean, and others. // // To test the code generator, we actually use it to generate code for -// google/protobuf/unittest.proto, then test that. This means that we +// net/proto2/internal/unittest.proto, then test that. This means that we // are actually testing the parser and other parts of the system at the same // time, and that problems in the generator may show up as compile-time errors // rather than unittest failures, which may be surprising. However, testing @@ -47,8 +47,8 @@ #include #include -#include #include +#include #include @@ -60,7 +60,7 @@ #define HELPERS_TEST_NAME HelpersTest #define DESCRIPTOR_INIT_TEST_NAME DescriptorInitializationTest -#define UNITTEST_PROTO_PATH "google/protobuf/unittest.proto" +#define UNITTEST_PROTO_PATH "net/proto2/internal/unittest.proto" #define UNITTEST ::protobuf_unittest #define UNITTEST_IMPORT ::protobuf_unittest_import @@ -96,25 +96,37 @@ TEST(GENERATED_MESSAGE_TEST_NAME, TestConflictingSymbolNames) { // parameter names. typedef protobuf_unittest::TestConflictingSymbolNamesExtension ExtensionMessage; message.AddExtension(ExtensionMessage::repeated_int32_ext, 123); - EXPECT_EQ(123, - message.GetExtension(ExtensionMessage::repeated_int32_ext, 0)); + EXPECT_EQ(123, message.GetExtension(ExtensionMessage::repeated_int32_ext, 0)); } TEST(GENERATED_MESSAGE_TEST_NAME, TestConflictingEnumNames) { protobuf_unittest::TestConflictingEnumNames message; - message.set_conflicting_enum(protobuf_unittest::TestConflictingEnumNames_NestedConflictingEnum_and_); + message.set_conflicting_enum( + protobuf_unittest::TestConflictingEnumNames_while_and_); EXPECT_EQ(1, message.conflicting_enum()); - message.set_conflicting_enum(protobuf_unittest::TestConflictingEnumNames_NestedConflictingEnum_XOR); + message.set_conflicting_enum( + protobuf_unittest::TestConflictingEnumNames_while_XOR); EXPECT_EQ(5, message.conflicting_enum()); - - protobuf_unittest::ConflictingEnum conflicting_enum; + protobuf_unittest::bool_ conflicting_enum; conflicting_enum = protobuf_unittest::NOT_EQ; EXPECT_EQ(1, conflicting_enum); conflicting_enum = protobuf_unittest::return_; EXPECT_EQ(3, conflicting_enum); } +TEST(GENERATED_MESSAGE_TEST_NAME, TestConflictingMessageNames) { + protobuf_unittest::NULL_ message; + message.set_int_(123); + EXPECT_EQ(message.int_(), 123); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, TestConflictingExtension) { + protobuf_unittest::TestConflictingSymbolNames message; + message.SetExtension(protobuf_unittest::void_, 123); + EXPECT_EQ(123, message.GetExtension(protobuf_unittest::void_)); +} + } // namespace cpp_unittest } // namespace cpp } // namespace compiler diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_unittest.h b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_unittest.h index 69c8f44c..c5dc767a 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_unittest.h +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_unittest.h @@ -46,6 +46,6 @@ namespace google { namespace protobuf { namespace protobuf_unittest {} } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_UNITTEST_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_unittest.inc b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_unittest.inc index ff6354f8..0b18662e 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_unittest.inc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/cpp_unittest.inc @@ -33,7 +33,7 @@ // Sanjay Ghemawat, Jeff Dean, and others. // // To test the code generator, we actually use it to generate code for -// google/protobuf/unittest.proto, then test that. This means that we +// net/proto2/internal/unittest.proto, then test that. This means that we // are actually testing the parser and other parts of the system at the same // time, and that problems in the generator may show up as compile-time errors // rather than unittest failures, which may be surprising. However, testing @@ -50,6 +50,7 @@ #include #include +#include #if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER) // We exclude this large proto from cmake build because it's too large for // visual studio to compile (report internal errors). @@ -57,7 +58,9 @@ #endif #include #include +#include #include +#include #include #include #include @@ -72,8 +75,11 @@ #include #include #include +#include #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -88,11 +94,11 @@ class MockErrorCollector : public MultiFileErrorCollector { MockErrorCollector() {} ~MockErrorCollector() {} - string text_; + std::string text_; // implements ErrorCollector --------------------------------------- - void AddError(const string& filename, int line, int column, - const string& message) { + void AddError(const std::string& filename, int line, int column, + const std::string& message) { strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", filename, line, column, message); } @@ -110,12 +116,12 @@ TEST(GENERATED_DESCRIPTOR_TEST_NAME, IdenticalDescriptors) { // Set up the Importer. MockErrorCollector error_collector; DiskSourceTree source_tree; - source_tree.MapPath("", TestSourceDir()); + source_tree.MapPath("", TestUtil::TestSourceDir()); Importer importer(&source_tree, &error_collector); // Import (parse) unittest.proto. const FileDescriptor* parsed_descriptor = - importer.Import(UNITTEST_PROTO_PATH); + importer.Import(TestUtil::MaybeTranslatePath(UNITTEST_PROTO_PATH)); EXPECT_EQ("", error_collector.text_); ASSERT_TRUE(parsed_descriptor != NULL); @@ -136,7 +142,7 @@ TEST(GENERATED_DESCRIPTOR_TEST_NAME, IdenticalDescriptors) { // limit for string literal size TEST(GENERATED_DESCRIPTOR_TEST_NAME, EnormousDescriptor) { const Descriptor* generated_descriptor = - TestEnormousDescriptor::descriptor(); + ::protobuf_unittest::TestEnormousDescriptor::descriptor(); EXPECT_TRUE(generated_descriptor != NULL); } @@ -165,21 +171,6 @@ TEST(GENERATED_MESSAGE_TEST_NAME, Defaults) { &message.optional_import_message()); } -#ifndef PROTOBUF_USE_DLLS -TEST(GENERATED_MESSAGE_TEST_NAME, Int32StringConversion) { - EXPECT_EQ("971", Int32ToString(971)); - EXPECT_EQ("(~0x7fffffff)", Int32ToString(kint32min)); - EXPECT_EQ("2147483647", Int32ToString(kint32max)); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, Int64StringConversion) { - EXPECT_EQ("GOOGLE_LONGLONG(971)", Int64ToString(971)); - EXPECT_EQ("GOOGLE_LONGLONG(-2147483648)", Int64ToString(kint32min)); - EXPECT_EQ("GOOGLE_LONGLONG(~0x7fffffffffffffff)", Int64ToString(kint64min)); - EXPECT_EQ("GOOGLE_LONGLONG(9223372036854775807)", Int64ToString(kint64max)); -} -#endif // !PROTOBUF_USE_DLLS - TEST(GENERATED_MESSAGE_TEST_NAME, FloatingPointDefaults) { const UNITTEST::TestExtremeDefaultValues& extreme_default = UNITTEST::TestExtremeDefaultValues::default_instance(); @@ -214,7 +205,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, ExtremeSmallIntegerDefault) { const UNITTEST::TestExtremeDefaultValues& extreme_default = UNITTEST::TestExtremeDefaultValues::default_instance(); EXPECT_EQ(~0x7fffffff, kint32min); - EXPECT_EQ(GOOGLE_LONGLONG(~0x7fffffffffffffff), kint64min); + EXPECT_EQ(PROTOBUF_LONGLONG(~0x7fffffffffffffff), kint64min); EXPECT_EQ(kint32min, extreme_default.really_small_int32()); EXPECT_EQ(kint64min, extreme_default.really_small_int64()); } @@ -250,8 +241,8 @@ TEST(GENERATED_MESSAGE_TEST_NAME, MutableStringDefault) { TEST(GENERATED_MESSAGE_TEST_NAME, StringDefaults) { UNITTEST::TestExtremeDefaultValues message; // Check if '\000' can be used in default string value. - EXPECT_EQ(string("hel\000lo", 6), message.string_with_zero()); - EXPECT_EQ(string("wor\000ld", 6), message.bytes_with_zero()); + EXPECT_EQ(std::string("hel\000lo", 6), message.string_with_zero()); + EXPECT_EQ(std::string("wor\000ld", 6), message.bytes_with_zero()); } TEST(GENERATED_MESSAGE_TEST_NAME, ReleaseString) { @@ -265,7 +256,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, ReleaseString) { message.set_default_string("blah"); EXPECT_TRUE(message.has_default_string()); - std::unique_ptr str(message.release_default_string()); + std::unique_ptr str(message.release_default_string()); EXPECT_FALSE(message.has_default_string()); ASSERT_TRUE(str != NULL); EXPECT_EQ("blah", *str); @@ -299,7 +290,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, SetAllocatedString) { UNITTEST::TestAllTypes message; EXPECT_FALSE(message.has_optional_string()); - const string kHello("hello"); + const std::string kHello("hello"); message.set_optional_string(kHello); EXPECT_TRUE(message.has_optional_string()); @@ -307,7 +298,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, SetAllocatedString) { EXPECT_FALSE(message.has_optional_string()); EXPECT_EQ("", message.optional_string()); - message.set_allocated_optional_string(new string(kHello)); + message.set_allocated_optional_string(new std::string(kHello)); EXPECT_TRUE(message.has_optional_string()); EXPECT_EQ(kHello, message.optional_string()); } @@ -411,70 +402,68 @@ TEST(GENERATED_MESSAGE_TEST_NAME, StringCharStarLength) { EXPECT_EQ("wx", message.repeated_string(0)); } -#if LANG_CXX11 TEST(GENERATED_MESSAGE_TEST_NAME, StringMove) { // Verify that we trigger the move behavior on a scalar setter. protobuf_unittest_no_arena::TestAllTypes message; { - string tmp(32, 'a'); + std::string tmp(32, 'a'); const char* old_data = tmp.data(); message.set_optional_string(std::move(tmp)); const char* new_data = message.optional_string().data(); EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'a'), message.optional_string()); + EXPECT_EQ(std::string(32, 'a'), message.optional_string()); - string tmp2(32, 'b'); + std::string tmp2(32, 'b'); old_data = tmp2.data(); message.set_optional_string(std::move(tmp2)); new_data = message.optional_string().data(); EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'b'), message.optional_string()); + EXPECT_EQ(std::string(32, 'b'), message.optional_string()); } // Verify that we trigger the move behavior on a oneof setter. { - string tmp(32, 'a'); + std::string tmp(32, 'a'); const char* old_data = tmp.data(); message.set_oneof_string(std::move(tmp)); const char* new_data = message.oneof_string().data(); EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'a'), message.oneof_string()); + EXPECT_EQ(std::string(32, 'a'), message.oneof_string()); - string tmp2(32, 'b'); + std::string tmp2(32, 'b'); old_data = tmp2.data(); message.set_oneof_string(std::move(tmp2)); new_data = message.oneof_string().data(); EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'b'), message.oneof_string()); + EXPECT_EQ(std::string(32, 'b'), message.oneof_string()); } // Verify that we trigger the move behavior on a repeated setter. { - string tmp(32, 'a'); + std::string tmp(32, 'a'); const char* old_data = tmp.data(); message.add_repeated_string(std::move(tmp)); const char* new_data = message.repeated_string(0).data(); EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'a'), message.repeated_string(0)); + EXPECT_EQ(std::string(32, 'a'), message.repeated_string(0)); - string tmp2(32, 'b'); + std::string tmp2(32, 'b'); old_data = tmp2.data(); message.set_repeated_string(0, std::move(tmp2)); new_data = message.repeated_string(0).data(); EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'b'), message.repeated_string(0)); + EXPECT_EQ(std::string(32, 'b'), message.repeated_string(0)); } } -#endif TEST(GENERATED_MESSAGE_TEST_NAME, CopyFrom) { @@ -667,8 +656,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, CopyAssignmentOperator) { TestUtil::ExpectAllFieldsSet(message2); } -#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \ - !defined(GOOGLE_PROTOBUF_NO_RTTI) +#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || PROTOBUF_RTTI TEST(GENERATED_MESSAGE_TEST_NAME, UpcastCopyFrom) { // Test the CopyFrom method that takes in the generic const Message& // parameter. @@ -709,7 +697,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, DynamicMessageCopyFrom) { TEST(GENERATED_MESSAGE_TEST_NAME, NonEmptyMergeFrom) { // Test merging with a non-empty message. Code is a modified form - // of that found in google/protobuf/reflection_ops_unittest.cc. + // of that found in net/proto2/internal/reflection_ops_unittest.cc. UNITTEST::TestAllTypes message1, message2; TestUtil::SetAllFields(&message1); @@ -737,11 +725,11 @@ TEST(GENERATED_MESSAGE_TEST_NAME, NonEmptyMergeFrom) { // Test the generated SerializeWithCachedSizesToArray(), TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToArray) { UNITTEST::TestAllTypes message1, message2; - string data; + std::string data; TestUtil::SetAllFields(&message1); int size = message1.ByteSizeLong(); data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); + uint8* start = reinterpret_cast(::google::protobuf::string_as_array(&data)); uint8* end = message1.SerializeWithCachedSizesToArray(start); EXPECT_EQ(size, end - start); EXPECT_TRUE(message2.ParseFromString(data)); @@ -751,11 +739,11 @@ TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToArray) { TEST(GENERATED_MESSAGE_TEST_NAME, PackedFieldsSerializationToArray) { UNITTEST::TestPackedTypes packed_message1, packed_message2; - string packed_data; + std::string packed_data; TestUtil::SetPackedFields(&packed_message1); int packed_size = packed_message1.ByteSizeLong(); packed_data.resize(packed_size); - uint8* start = reinterpret_cast(string_as_array(&packed_data)); + uint8* start = reinterpret_cast(::google::protobuf::string_as_array(&packed_data)); uint8* end = packed_message1.SerializeWithCachedSizesToArray(start); EXPECT_EQ(packed_size, end - start); EXPECT_TRUE(packed_message2.ParseFromString(packed_data)); @@ -768,11 +756,11 @@ TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToStream) { UNITTEST::TestAllTypes message1, message2; TestUtil::SetAllFields(&message1); int size = message1.ByteSizeLong(); - string data; + std::string data; data.resize(size); { // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1); io::CodedOutputStream output_stream(&array_stream); message1.SerializeWithCachedSizes(&output_stream); EXPECT_FALSE(output_stream.HadError()); @@ -787,11 +775,11 @@ TEST(GENERATED_MESSAGE_TEST_NAME, PackedFieldsSerializationToStream) { UNITTEST::TestPackedTypes message1, message2; TestUtil::SetPackedFields(&message1); int size = message1.ByteSizeLong(); - string data; + std::string data; data.resize(size); { // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1); io::CodedOutputStream output_stream(&array_stream); message1.SerializeWithCachedSizes(&output_stream); EXPECT_FALSE(output_stream.HadError()); @@ -854,7 +842,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, ForeignNested) { TEST(GENERATED_MESSAGE_TEST_NAME, ReallyLargeTagNumber) { // Test that really large tag numbers don't break anything. UNITTEST::TestReallyLargeTagNumber message1, message2; - string data; + std::string data; // For the most part, if this compiles and runs then we're probably good. // (The most likely cause for failure would be if something were attempting @@ -937,7 +925,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, TestEmbedOptimizedForSize) { UNITTEST::TestEmbedOptimizedForSize message, message2; message.mutable_optional_message()->set_i(1); message.add_repeated_message()->mutable_msg()->set_c(2); - string data; + std::string data; message.SerializeToString(&data); ASSERT_TRUE(message2.ParseFromString(data)); EXPECT_EQ(1, message2.optional_message().i()); @@ -966,7 +954,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, TestSpaceUsed) { // Setting a string to a value larger than the string object itself should // increase SpaceUsedLong(), because it cannot store the value internally. - message1.set_optional_string(string(sizeof(string) + 1, 'x')); + message1.set_optional_string(std::string(sizeof(std::string) + 1, 'x')); int min_expected_increase = message1.optional_string().capacity(); EXPECT_LE(empty_message_size + min_expected_increase, message1.SpaceUsedLong()); @@ -996,14 +984,14 @@ TEST(GENERATED_MESSAGE_TEST_NAME, TestOneofSpaceUsed) { // Setting a string in oneof to a small value should only increase // SpaceUsedLong() by the size of a string object. message1.set_foo_string("abc"); - EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsedLong()); + EXPECT_LE(empty_message_size + sizeof(std::string), message1.SpaceUsedLong()); // Setting a string in oneof to a value larger than the string object itself // should increase SpaceUsedLong(), because it cannot store the value // internally. - message1.set_foo_string(string(sizeof(string) + 1, 'x')); - int min_expected_increase = message1.foo_string().capacity() + - sizeof(string); + message1.set_foo_string(std::string(sizeof(std::string) + 1, 'x')); + int min_expected_increase = + message1.foo_string().capacity() + sizeof(std::string); EXPECT_LE(empty_message_size + min_expected_increase, message1.SpaceUsedLong()); @@ -1048,10 +1036,10 @@ TEST(GENERATED_MESSAGE_TEST_NAME, ExtensionConstantValues) { } TEST(GENERATED_MESSAGE_TEST_NAME, ParseFromTruncated) { - const string long_string = string(128, 'q'); + const std::string long_string = std::string(128, 'q'); FileDescriptorProto p; p.add_extension()->set_name(long_string); - const string msg = p.SerializeAsString(); + const std::string msg = p.SerializeAsString(); int successful_count = 0; for (int i = 0; i <= msg.size(); i++) { if (p.ParseFromArray(msg.c_str(), i)) { @@ -1153,7 +1141,7 @@ TEST(GENERATED_ENUM_TEST_NAME, MinAndMax) { #ifndef PROTOBUF_TEST_NO_DESCRIPTORS TEST(GENERATED_ENUM_TEST_NAME, Name) { - // "Names" in the presence of dup values are a bit arbitrary. + // "Names" in the presence of dup values map to the first alias. EXPECT_EQ("FOO1", UNITTEST::TestEnumWithDupValue_Name(UNITTEST::FOO1)); EXPECT_EQ("FOO1", UNITTEST::TestEnumWithDupValue_Name(UNITTEST::FOO2)); @@ -1254,7 +1242,7 @@ class GENERATED_SERVICE_TEST_NAME : public testing::Test { // --------------------------------------------------------------- bool called_; - string method_; + std::string method_; RpcController* controller_; const Message* request_; Message* response_; @@ -1314,14 +1302,14 @@ class GENERATED_SERVICE_TEST_NAME : public testing::Test { ADD_FAILURE() << "Failed() not expected during this test."; return false; } - string ErrorText() const { + std::string ErrorText() const { ADD_FAILURE() << "ErrorText() not expected during this test."; return ""; } void StartCancel() { ADD_FAILURE() << "StartCancel() not expected during this test."; } - void SetFailed(const string& reason) { + void SetFailed(const std::string& reason) { ADD_FAILURE() << "SetFailed() not expected during this test."; } bool IsCanceled() const { @@ -1481,7 +1469,7 @@ TEST_F(GENERATED_SERVICE_TEST_NAME, NotImplemented) { public: ExpectUnimplementedController() : called_(false) {} - void SetFailed(const string& reason) { + void SetFailed(const std::string& reason) { EXPECT_FALSE(called_); called_ = true; EXPECT_EQ("Method Foo() not implemented.", reason); @@ -1631,7 +1619,7 @@ TEST_F(OneofTest, SetString) { message.clear_foo_string(); EXPECT_FALSE(message.has_foo_string()); - message.set_foo_string(string("bar")); + message.set_foo_string(std::string("bar")); EXPECT_TRUE(message.has_foo_string()); EXPECT_EQ(message.foo_string(), "bar"); message.clear_foo_string(); @@ -1667,7 +1655,7 @@ TEST_F(OneofTest, ReleaseString) { message.set_foo_string("blah"); EXPECT_TRUE(message.has_foo_string()); - std::unique_ptr str(message.release_foo_string()); + std::unique_ptr str(message.release_foo_string()); EXPECT_FALSE(message.has_foo_string()); ASSERT_TRUE(str != NULL); EXPECT_EQ("blah", *str); @@ -1681,7 +1669,7 @@ TEST_F(OneofTest, SetAllocatedString) { UNITTEST::TestOneof2 message; EXPECT_FALSE(message.has_foo_string()); - const string kHello("hello"); + const std::string kHello("hello"); message.set_foo_string(kHello); EXPECT_TRUE(message.has_foo_string()); @@ -1689,7 +1677,7 @@ TEST_F(OneofTest, SetAllocatedString) { EXPECT_FALSE(message.has_foo_string()); EXPECT_EQ("", message.foo_string()); - message.set_allocated_foo_string(new string(kHello)); + message.set_allocated_foo_string(new std::string(kHello)); EXPECT_TRUE(message.has_foo_string()); EXPECT_EQ(kHello, message.foo_string()); } @@ -1872,7 +1860,7 @@ TEST_F(OneofTest, CopyAssignmentOperator) { EXPECT_EQ(message2.foo_message().qux_int(), 123); // Make sure that self-assignment does something sane. - message2 = message2; + message2 = *&message2; // Avoid -Wself-assign. EXPECT_EQ(message2.foo_message().qux_int(), 123); } @@ -1898,25 +1886,25 @@ TEST_F(OneofTest, SerializationToArray) { // Primitive type { UNITTEST::TestOneof2 message1, message2; - string data; - message1.set_foo_int(123); - int size = message1.ByteSizeLong(); - data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_int(), 123); +std::string data; +message1.set_foo_int(123); +int size = message1.ByteSizeLong(); +data.resize(size); +uint8* start = reinterpret_cast(::google::protobuf::string_as_array(&data)); +uint8* end = message1.SerializeWithCachedSizesToArray(start); +EXPECT_EQ(size, end - start); +EXPECT_TRUE(message2.ParseFromString(data)); +EXPECT_EQ(message2.foo_int(), 123); } // String { UNITTEST::TestOneof2 message1, message2; - string data; + std::string data; message1.set_foo_string("foo"); int size = message1.ByteSizeLong(); data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); + uint8* start = reinterpret_cast(::google::protobuf::string_as_array(&data)); uint8* end = message1.SerializeWithCachedSizesToArray(start); EXPECT_EQ(size, end - start); EXPECT_TRUE(message2.ParseFromString(data)); @@ -1927,11 +1915,11 @@ TEST_F(OneofTest, SerializationToArray) { // Bytes { UNITTEST::TestOneof2 message1, message2; - string data; + std::string data; message1.set_foo_bytes("qux"); int size = message1.ByteSizeLong(); data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); + uint8* start = reinterpret_cast(::google::protobuf::string_as_array(&data)); uint8* end = message1.SerializeWithCachedSizesToArray(start); EXPECT_EQ(size, end - start); EXPECT_TRUE(message2.ParseFromString(data)); @@ -1941,11 +1929,11 @@ TEST_F(OneofTest, SerializationToArray) { // Enum { UNITTEST::TestOneof2 message1, message2; - string data; + std::string data; message1.set_foo_enum(UNITTEST::TestOneof2::FOO); int size = message1.ByteSizeLong(); data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); + uint8* start = reinterpret_cast(::google::protobuf::string_as_array(&data)); uint8* end = message1.SerializeWithCachedSizesToArray(start); EXPECT_EQ(size, end - start); EXPECT_TRUE(message2.ParseFromString(data)); @@ -1955,11 +1943,11 @@ TEST_F(OneofTest, SerializationToArray) { // Message { UNITTEST::TestOneof2 message1, message2; - string data; + std::string data; message1.mutable_foo_message()->set_qux_int(234); int size = message1.ByteSizeLong(); data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); + uint8* start = reinterpret_cast(::google::protobuf::string_as_array(&data)); uint8* end = message1.SerializeWithCachedSizesToArray(start); EXPECT_EQ(size, end - start); EXPECT_TRUE(message2.ParseFromString(data)); @@ -1969,11 +1957,11 @@ TEST_F(OneofTest, SerializationToArray) { // Group { UNITTEST::TestOneof2 message1, message2; - string data; + std::string data; message1.mutable_foogroup()->set_a(345); int size = message1.ByteSizeLong(); data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); + uint8* start = reinterpret_cast(::google::protobuf::string_as_array(&data)); uint8* end = message1.SerializeWithCachedSizesToArray(start); EXPECT_EQ(size, end - start); EXPECT_TRUE(message2.ParseFromString(data)); @@ -1991,19 +1979,19 @@ TEST_F(OneofTest, SerializationToStream) { // Primitive type { UNITTEST::TestOneof2 message1, message2; - string data; - message1.set_foo_int(123); - int size = message1.ByteSizeLong(); - data.resize(size); +std::string data; +message1.set_foo_int(123); +int size = message1.ByteSizeLong(); +data.resize(size); - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message1.SerializeWithCachedSizes(&output_stream); - EXPECT_FALSE(output_stream.HadError()); - EXPECT_EQ(size, output_stream.ByteCount()); - } +{ + // Allow the output stream to buffer only one byte at a time. + io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1); + io::CodedOutputStream output_stream(&array_stream); + message1.SerializeWithCachedSizes(&output_stream); + EXPECT_FALSE(output_stream.HadError()); + EXPECT_EQ(size, output_stream.ByteCount()); +} EXPECT_TRUE(message2.ParseFromString(data)); EXPECT_EQ(message2.foo_int(), 123); @@ -2012,14 +2000,14 @@ TEST_F(OneofTest, SerializationToStream) { // String { UNITTEST::TestOneof2 message1, message2; - string data; + std::string data; message1.set_foo_string("foo"); int size = message1.ByteSizeLong(); data.resize(size); { // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1); io::CodedOutputStream output_stream(&array_stream); message1.SerializeWithCachedSizes(&output_stream); EXPECT_FALSE(output_stream.HadError()); @@ -2034,14 +2022,14 @@ TEST_F(OneofTest, SerializationToStream) { // Bytes { UNITTEST::TestOneof2 message1, message2; - string data; + std::string data; message1.set_foo_bytes("qux"); int size = message1.ByteSizeLong(); data.resize(size); { // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1); io::CodedOutputStream output_stream(&array_stream); message1.SerializeWithCachedSizes(&output_stream); EXPECT_FALSE(output_stream.HadError()); @@ -2055,14 +2043,14 @@ TEST_F(OneofTest, SerializationToStream) { // Enum { UNITTEST::TestOneof2 message1, message2; - string data; + std::string data; message1.set_foo_enum(UNITTEST::TestOneof2::FOO); int size = message1.ByteSizeLong(); data.resize(size); { // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1); io::CodedOutputStream output_stream(&array_stream); message1.SerializeWithCachedSizes(&output_stream); EXPECT_FALSE(output_stream.HadError()); @@ -2076,14 +2064,14 @@ TEST_F(OneofTest, SerializationToStream) { // Message { UNITTEST::TestOneof2 message1, message2; - string data; + std::string data; message1.mutable_foo_message()->set_qux_int(234); int size = message1.ByteSizeLong(); data.resize(size); { // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1); io::CodedOutputStream output_stream(&array_stream); message1.SerializeWithCachedSizes(&output_stream); EXPECT_FALSE(output_stream.HadError()); @@ -2097,14 +2085,14 @@ TEST_F(OneofTest, SerializationToStream) { // Group { UNITTEST::TestOneof2 message1, message2; - string data; + std::string data; message1.mutable_foogroup()->set_a(345); int size = message1.ByteSizeLong(); data.resize(size); { // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1); io::CodedOutputStream output_stream(&array_stream); message1.SerializeWithCachedSizes(&output_stream); EXPECT_FALSE(output_stream.HadError()); @@ -2161,13 +2149,14 @@ TEST_F(OneofTest, MergeFrom) { TEST(HELPERS_TEST_NAME, TestSCC) { UNITTEST::TestMutualRecursionA a; - SCCAnalyzer scc_analyzer((Options())); + MessageSCCAnalyzer scc_analyzer((Options())); const SCC* scc = scc_analyzer.GetSCC(a.GetDescriptor()); - std::vector names; + std::vector names; + names.reserve(scc->descriptors.size()); for (int i = 0; i < scc->descriptors.size(); i++) { names.push_back(scc->descriptors[i]->full_name()); } - string package = a.GetDescriptor()->file()->package(); + std::string package = a.GetDescriptor()->file()->package(); ASSERT_EQ(names.size(), 4); std::sort(names.begin(), names.end()); EXPECT_EQ(names[0], package + ".TestMutualRecursionA"); @@ -2185,7 +2174,7 @@ TEST(HELPERS_TEST_NAME, TestSCC) { TEST(HELPERS_TEST_NAME, TestSCCAnalysis) { { UNITTEST::TestRecursiveMessage msg; - SCCAnalyzer scc_analyzer((Options())); + MessageSCCAnalyzer scc_analyzer((Options())); const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); EXPECT_EQ(result.is_recursive, true); @@ -2195,7 +2184,7 @@ TEST(HELPERS_TEST_NAME, TestSCCAnalysis) { } { UNITTEST::TestAllExtensions msg; - SCCAnalyzer scc_analyzer((Options())); + MessageSCCAnalyzer scc_analyzer((Options())); const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); EXPECT_EQ(result.is_recursive, false); @@ -2205,7 +2194,7 @@ TEST(HELPERS_TEST_NAME, TestSCCAnalysis) { } { UNITTEST::TestRequired msg; - SCCAnalyzer scc_analyzer((Options())); + MessageSCCAnalyzer scc_analyzer((Options())); const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); EXPECT_EQ(result.is_recursive, false); @@ -2235,16 +2224,19 @@ namespace cpp_unittest { TEST_F(GENERATED_SERVICE_TEST_NAME, NoGenericServices) { // Verify that non-services in unittest_no_generic_services.proto were // generated. - no_generic_services_test::TestMessage message; + ::protobuf_unittest::no_generic_services_test::TestMessage message; message.set_a(1); - message.SetExtension(no_generic_services_test::test_extension, 123); - no_generic_services_test::TestEnum e = no_generic_services_test::FOO; + message.SetExtension( + ::protobuf_unittest::no_generic_services_test::test_extension, 123); + ::protobuf_unittest::no_generic_services_test::TestEnum e = + ::protobuf_unittest::no_generic_services_test::FOO; EXPECT_EQ(e, 1); // Verify that a ServiceDescriptor is generated for the service even if the // class itself is not. const FileDescriptor* file = - no_generic_services_test::TestMessage::descriptor()->file(); + ::google::protobuf::unittest::no_generic_services_test::TestMessage::descriptor() + ->file(); ASSERT_EQ(1, file->service_count()); EXPECT_EQ("TestService", file->service(0)->name()); @@ -2269,8 +2261,8 @@ TEST(DESCRIPTOR_INIT_TEST_NAME, Initialized) { #endif EXPECT_EQ(should_have_descriptors, - DescriptorPool::generated_pool()->InternalIsFileLoaded( - UNITTEST_PROTO_PATH)); + DescriptorPool::generated_pool()->InternalIsFileLoaded( + TestUtil::MaybeTranslatePath(UNITTEST_PROTO_PATH))); } } // namespace cpp_unittest @@ -2279,3 +2271,5 @@ TEST(DESCRIPTOR_INIT_TEST_NAME, Initialized) { } // namespace compiler } // namespace protobuf } // namespace google + +#include diff --git a/third_party/protobuf/src/google/protobuf/compiler/cpp/metadata_test.cc b/third_party/protobuf/src/google/protobuf/compiler/cpp/metadata_test.cc index 2ad4edd2..045c6a3d 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/cpp/metadata_test.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/cpp/metadata_test.cc @@ -42,11 +42,12 @@ #include namespace google { -namespace atu = ::google::protobuf::compiler::annotation_test_util; - namespace protobuf { namespace compiler { namespace cpp { + +namespace atu = annotation_test_util; + namespace { class CppMetadataTest : public ::testing::Test { @@ -55,27 +56,26 @@ class CppMetadataTest : public ::testing::Test { // code from the previously added file with name `filename`. Returns true on // success. If pb_h is non-null, expects a .pb.h and a .pb.h.meta (copied to // pb_h and pb_h_info respecfively); similarly for proto_h and proto_h_info. - bool CaptureMetadata(const string& filename, FileDescriptorProto* file, - string* pb_h, GeneratedCodeInfo* pb_h_info, - string* proto_h, GeneratedCodeInfo* proto_h_info, - string* pb_cc) { - google::protobuf::compiler::CommandLineInterface cli; + bool CaptureMetadata(const std::string& filename, FileDescriptorProto* file, + std::string* pb_h, GeneratedCodeInfo* pb_h_info, + std::string* proto_h, GeneratedCodeInfo* proto_h_info, + std::string* pb_cc) { + CommandLineInterface cli; CppGenerator cpp_generator; cli.RegisterGenerator("--cpp_out", &cpp_generator, ""); - string cpp_out = + std::string cpp_out = "--cpp_out=annotate_headers=true," "annotation_pragma_name=pragma_name," "annotation_guard_name=guard_name:" + TestTempDir(); - const bool result = - atu::RunProtoCompiler(filename, cpp_out, &cli, file); + const bool result = atu::RunProtoCompiler(filename, cpp_out, &cli, file); if (!result) { return result; } - string output_base = TestTempDir() + "/" + StripProto(filename); + std::string output_base = TestTempDir() + "/" + StripProto(filename); if (pb_cc != NULL) { GOOGLE_CHECK_OK( @@ -111,7 +111,7 @@ const char kSmallTestFile[] = TEST_F(CppMetadataTest, CapturesEnumNames) { FileDescriptorProto file; GeneratedCodeInfo info; - string pb_h; + std::string pb_h; atu::AddFile("test.proto", kSmallTestFile); EXPECT_TRUE( CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL)); @@ -128,19 +128,19 @@ TEST_F(CppMetadataTest, CapturesEnumNames) { TEST_F(CppMetadataTest, AddsPragma) { FileDescriptorProto file; GeneratedCodeInfo info; - string pb_h; + std::string pb_h; atu::AddFile("test.proto", kSmallTestFile); EXPECT_TRUE( CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL)); EXPECT_TRUE(pb_h.find("#ifdef guard_name") != string::npos); EXPECT_TRUE(pb_h.find("#pragma pragma_name \"test.pb.h.meta\"") != - string::npos); + std::string::npos); } TEST_F(CppMetadataTest, CapturesMessageNames) { FileDescriptorProto file; GeneratedCodeInfo info; - string pb_h; + std::string pb_h; atu::AddFile("test.proto", kSmallTestFile); EXPECT_TRUE( CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL)); diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc index 8c38e52f..33c56198 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc @@ -90,7 +90,7 @@ class MockGeneratorContext : public GeneratorContext { string actual_contents; GOOGLE_CHECK_OK( - File::GetContents(TestSourceDir() + "/" + physical_filename, + File::GetContentsAsText(TestSourceDir() + "/" + physical_filename, &actual_contents, true)) << "Unable to get " << physical_filename; EXPECT_TRUE(actual_contents == *expected_contents) diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_doc_comment.cc b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_doc_comment.cc index a21dc0a4..fcc0aec0 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_doc_comment.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_doc_comment.cc @@ -56,7 +56,8 @@ void WriteDocCommentBodyImpl(io::Printer* printer, SourceLocation location) { // node of a summary element, not part of an attribute. comments = StringReplace(comments, "&", "&", true); comments = StringReplace(comments, "<", "<", true); - std::vector lines = Split(comments, "\n", false /* skip_empty */); + std::vector lines; + SplitStringAllowEmpty(comments, "\n", &lines); // TODO: We really should work out which part to put in the summary and which to put in the remarks... // but that needs to be part of a bigger effort to understand the markdown better anyway. printer->Print("/// \n"); diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_enum.cc b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_enum.cc index 32c71990..f4570966 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_enum.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_enum.cc @@ -31,7 +31,6 @@ #include #include -#include #include #include #include diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_enum.h b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_enum.h index 8925cdf2..e409c2e4 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_enum.h +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_enum.h @@ -35,6 +35,8 @@ #include #include +#include +#include namespace google { namespace protobuf { @@ -46,12 +48,13 @@ class EnumGenerator : public SourceGeneratorBase { EnumGenerator(const EnumDescriptor* descriptor, const Options* options); ~EnumGenerator(); + EnumGenerator(const EnumGenerator&) = delete; + EnumGenerator& operator=(const EnumGenerator&) = delete; + void Generate(io::Printer* printer); private: const EnumDescriptor* descriptor_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator); }; } // namespace csharp diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_enum_field.cc b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_enum_field.cc index 9ceffa8c..4d9bb672 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_enum_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_enum_field.cc @@ -31,7 +31,6 @@ #include #include -#include #include #include #include @@ -47,8 +46,8 @@ namespace compiler { namespace csharp { EnumFieldGenerator::EnumFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, const Options *options) - : PrimitiveFieldGenerator(descriptor, fieldOrdinal, options) { + int presenceIndex, const Options *options) + : PrimitiveFieldGenerator(descriptor, presenceIndex, options) { } EnumFieldGenerator::~EnumFieldGenerator() { @@ -56,7 +55,7 @@ EnumFieldGenerator::~EnumFieldGenerator() { void EnumFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print(variables_, - "$name$_ = ($type_name$) input.ReadEnum();\n"); + "$property_name$ = ($type_name$) input.ReadEnum();\n"); } void EnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) { @@ -82,8 +81,8 @@ void EnumFieldGenerator::GenerateCodecCode(io::Printer* printer) { } EnumOneofFieldGenerator::EnumOneofFieldGenerator( - const FieldDescriptor* descriptor, int fieldOrdinal, const Options *options) - : PrimitiveOneofFieldGenerator(descriptor, fieldOrdinal, options) { + const FieldDescriptor* descriptor, int presenceIndex, const Options *options) + : PrimitiveOneofFieldGenerator(descriptor, presenceIndex, options) { } EnumOneofFieldGenerator::~EnumOneofFieldGenerator() { diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_enum_field.h b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_enum_field.h index 631632bc..04ca68da 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_enum_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_enum_field.h @@ -44,33 +44,33 @@ namespace csharp { class EnumFieldGenerator : public PrimitiveFieldGenerator { public: EnumFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, + int presenceIndex, const Options *options); ~EnumFieldGenerator(); + EnumFieldGenerator(const EnumFieldGenerator&) = delete; + EnumFieldGenerator& operator=(const EnumFieldGenerator&) = delete; + virtual void GenerateCodecCode(io::Printer* printer); virtual void GenerateParsingCode(io::Printer* printer); virtual void GenerateSerializationCode(io::Printer* printer); virtual void GenerateSerializedSizeCode(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator); }; class EnumOneofFieldGenerator : public PrimitiveOneofFieldGenerator { public: EnumOneofFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, + int presenceIndex, const Options *options); ~EnumOneofFieldGenerator(); + EnumOneofFieldGenerator(const EnumOneofFieldGenerator&) = delete; + EnumOneofFieldGenerator& operator=(const EnumOneofFieldGenerator&) = delete; + virtual void GenerateMergingCode(io::Printer* printer); virtual void GenerateParsingCode(io::Printer* printer); virtual void GenerateSerializationCode(io::Printer* printer); virtual void GenerateSerializedSizeCode(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumOneofFieldGenerator); }; } // namespace csharp diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_field_base.cc b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_field_base.cc index 7e737e47..02adfeae 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_field_base.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_field_base.cc @@ -28,17 +28,16 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#include #include #include #include -#include #include #include #include #include #include -#include #include #include @@ -57,6 +56,9 @@ void FieldGeneratorBase::SetCommonFieldVariables( // repeated fields varies by wire format. The wire format is encoded in the bottom 3 bits, which // never effects the tag size. int tag_size = internal::WireFormat::TagSize(descriptor_->number(), descriptor_->type()); + if (descriptor_->type() == FieldDescriptor::TYPE_GROUP) { + tag_size /= 2; + } uint tag = internal::WireFormat::MakeTag(descriptor_); uint8 tag_array[5]; io::CodedOutputStream::WriteTagToArray(tag, tag_array); @@ -75,34 +77,52 @@ void FieldGeneratorBase::SetCommonFieldVariables( (*variables)["name"] = name(); (*variables)["descriptor_name"] = descriptor_->name(); (*variables)["default_value"] = default_value(); - if (has_default_value()) { + (*variables)["capitalized_type_name"] = capitalized_type_name(); + (*variables)["number"] = number(); + if (has_default_value() && !IsProto2(descriptor_->file())) { (*variables)["name_def_message"] = (*variables)["name"] + "_ = " + (*variables)["default_value"]; } else { (*variables)["name_def_message"] = (*variables)["name"] + "_"; } - (*variables)["capitalized_type_name"] = capitalized_type_name(); - (*variables)["number"] = number(); - (*variables)["has_property_check"] = - (*variables)["property_name"] + " != " + (*variables)["default_value"]; - (*variables)["other_has_property_check"] = "other." + - (*variables)["property_name"] + " != " + (*variables)["default_value"]; + if (IsProto2(descriptor_->file())) { + (*variables)["has_property_check"] = "Has" + (*variables)["property_name"]; + (*variables)["other_has_property_check"] = "other.Has" + (*variables)["property_name"]; + (*variables)["has_not_property_check"] = "!" + (*variables)["has_property_check"]; + (*variables)["other_has_not_property_check"] = "!" + (*variables)["other_has_property_check"]; + if (presenceIndex_ != -1) { + string hasBitsNumber = SimpleItoa(presenceIndex_ / 32); + string hasBitsMask = SimpleItoa(1 << (presenceIndex_ % 32)); + (*variables)["has_field_check"] = "(_hasBits" + hasBitsNumber + " & " + hasBitsMask + ") != 0"; + (*variables)["set_has_field"] = "_hasBits" + hasBitsNumber + " |= " + hasBitsMask; + (*variables)["clear_has_field"] = "_hasBits" + hasBitsNumber + " &= ~" + hasBitsMask; + } + } else { + (*variables)["has_property_check"] = + (*variables)["property_name"] + " != " + (*variables)["default_value"]; + (*variables)["other_has_property_check"] = "other." + + (*variables)["property_name"] + " != " + (*variables)["default_value"]; + } } void FieldGeneratorBase::SetCommonOneofFieldVariables( std::map* variables) { (*variables)["oneof_name"] = oneof_name(); - (*variables)["has_property_check"] = - oneof_name() + "Case_ == " + oneof_property_name() + - "OneofCase." + property_name(); + if (IsProto2(descriptor_->file())) { + (*variables)["has_property_check"] = "Has" + property_name(); + } else { + (*variables)["has_property_check"] = + oneof_name() + "Case_ == " + oneof_property_name() + + "OneofCase." + property_name(); + } (*variables)["oneof_property_name"] = oneof_property_name(); } FieldGeneratorBase::FieldGeneratorBase(const FieldDescriptor* descriptor, - int fieldOrdinal, const Options* options) + int presenceIndex, const Options* options) : SourceGeneratorBase(descriptor->file(), options), descriptor_(descriptor), - fieldOrdinal_(fieldOrdinal) { + presenceIndex_(presenceIndex) { SetCommonFieldVariables(&variables_); } @@ -251,36 +271,6 @@ bool FieldGeneratorBase::has_default_value() { } } -bool FieldGeneratorBase::is_nullable_type() { - switch (descriptor_->type()) { - case FieldDescriptor::TYPE_ENUM: - case FieldDescriptor::TYPE_DOUBLE: - case FieldDescriptor::TYPE_FLOAT: - case FieldDescriptor::TYPE_INT64: - case FieldDescriptor::TYPE_UINT64: - case FieldDescriptor::TYPE_INT32: - case FieldDescriptor::TYPE_FIXED64: - case FieldDescriptor::TYPE_FIXED32: - case FieldDescriptor::TYPE_BOOL: - case FieldDescriptor::TYPE_UINT32: - case FieldDescriptor::TYPE_SFIXED32: - case FieldDescriptor::TYPE_SFIXED64: - case FieldDescriptor::TYPE_SINT32: - case FieldDescriptor::TYPE_SINT64: - return false; - - case FieldDescriptor::TYPE_MESSAGE: - case FieldDescriptor::TYPE_GROUP: - case FieldDescriptor::TYPE_STRING: - case FieldDescriptor::TYPE_BYTES: - return true; - - default: - GOOGLE_LOG(FATAL)<< "Unknown field type."; - return true; - } -} - bool AllPrintableAscii(const std::string& text) { for(int i = 0; i < text.size(); i++) { if (text[i] < 0x20 || text[i] > 0x7e) { @@ -290,14 +280,18 @@ bool AllPrintableAscii(const std::string& text) { return true; } -std::string FieldGeneratorBase::GetStringDefaultValueInternal() { - // No other default values needed for proto3... - return "\"\""; +std::string FieldGeneratorBase::GetStringDefaultValueInternal(const FieldDescriptor* descriptor) { + if (descriptor->default_value_string().empty()) + return "\"\""; + else + return "global::System.Encoding.UTF8.GetString(global::System.Convert.FromBase64String(\" +" + StringToBase64(descriptor->default_value_string()) + " +\"))"; } -std::string FieldGeneratorBase::GetBytesDefaultValueInternal() { - // No other default values needed for proto3... - return "pb::ByteString.Empty"; +std::string FieldGeneratorBase::GetBytesDefaultValueInternal(const FieldDescriptor* descriptor) { + if (descriptor->default_value_string().empty()) + return "pb::ByteString.Empty"; + else + return "pb::ByteString.FromBase64(\"" + StringToBase64(descriptor->default_value_string()) + "\")"; } std::string FieldGeneratorBase::default_value() { @@ -307,9 +301,13 @@ std::string FieldGeneratorBase::default_value() { std::string FieldGeneratorBase::default_value(const FieldDescriptor* descriptor) { switch (descriptor->type()) { case FieldDescriptor::TYPE_ENUM: - // All proto3 enums have a default value of 0, and there's an implicit conversion from the constant 0 to - // any C# enum. This means we don't need to work out what we actually mapped the enum value name to. - return "0"; + if (IsProto2(descriptor_->file())) { + return GetClassName(descriptor->default_value_enum()->type()) + "." + + GetEnumValueName(descriptor->default_value_enum()->type()->name(), descriptor->default_value_enum()->name()); + } + else { + return "0"; + } case FieldDescriptor::TYPE_MESSAGE: case FieldDescriptor::TYPE_GROUP: if (IsWrapperType(descriptor)) { @@ -324,7 +322,7 @@ std::string FieldGeneratorBase::default_value(const FieldDescriptor* descriptor) return "double.PositiveInfinity"; } else if (value == -std::numeric_limits::infinity()) { return "double.NegativeInfinity"; - } else if (MathLimits::IsNaN(value)) { + } else if (std::isnan(value)) { return "double.NaN"; } return SimpleDtoa(value) + "D"; @@ -335,7 +333,7 @@ std::string FieldGeneratorBase::default_value(const FieldDescriptor* descriptor) return "float.PositiveInfinity"; } else if (value == -std::numeric_limits::infinity()) { return "float.NegativeInfinity"; - } else if (MathLimits::IsNaN(value)) { + } else if (std::isnan(value)) { return "float.NaN"; } return SimpleFtoa(value) + "F"; @@ -357,9 +355,9 @@ std::string FieldGeneratorBase::default_value(const FieldDescriptor* descriptor) return "false"; } case FieldDescriptor::TYPE_STRING: - return GetStringDefaultValueInternal(); + return GetStringDefaultValueInternal(descriptor); case FieldDescriptor::TYPE_BYTES: - return GetBytesDefaultValueInternal(); + return GetBytesDefaultValueInternal(descriptor); case FieldDescriptor::TYPE_UINT32: return SimpleItoa(descriptor->default_value_uint32()); case FieldDescriptor::TYPE_SFIXED32: diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_field_base.h b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_field_base.h index df26853b..28a09621 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_field_base.h +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_field_base.h @@ -36,6 +36,8 @@ #include #include +#include +#include namespace google { namespace protobuf { @@ -45,10 +47,13 @@ namespace csharp { class FieldGeneratorBase : public SourceGeneratorBase { public: FieldGeneratorBase(const FieldDescriptor* descriptor, - int fieldOrdinal, + int presenceIndex, const Options* options); ~FieldGeneratorBase(); + FieldGeneratorBase(const FieldGeneratorBase&) = delete; + FieldGeneratorBase& operator=(const FieldGeneratorBase&) = delete; + virtual void GenerateCloningCode(io::Printer* printer) = 0; virtual void GenerateFreezingCode(io::Printer* printer); virtual void GenerateCodecCode(io::Printer* printer); @@ -65,7 +70,7 @@ class FieldGeneratorBase : public SourceGeneratorBase { protected: const FieldDescriptor* descriptor_; - const int fieldOrdinal_; + const int presenceIndex_; std::map variables_; void AddDeprecatedFlag(io::Printer* printer); @@ -82,7 +87,6 @@ class FieldGeneratorBase : public SourceGeneratorBase { std::string type_name(); std::string type_name(const FieldDescriptor* descriptor); bool has_default_value(); - bool is_nullable_type(); std::string default_value(); std::string default_value(const FieldDescriptor* descriptor); std::string number(); @@ -90,10 +94,8 @@ class FieldGeneratorBase : public SourceGeneratorBase { private: void SetCommonFieldVariables(std::map* variables); - std::string GetStringDefaultValueInternal(); - std::string GetBytesDefaultValueInternal(); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorBase); + std::string GetStringDefaultValueInternal(const FieldDescriptor* descriptor); + std::string GetBytesDefaultValueInternal(const FieldDescriptor* descriptor); }; } // namespace csharp diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_generator.cc b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_generator.cc index 0c93fc29..2b353b34 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_generator.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_generator.cc @@ -31,7 +31,6 @@ #include #include -#include #include #include #include @@ -49,8 +48,7 @@ namespace protobuf { namespace compiler { namespace csharp { -void GenerateFile(const google::protobuf::FileDescriptor* file, - io::Printer* printer, +void GenerateFile(const FileDescriptor* file, io::Printer* printer, const Options* options) { ReflectionClassGenerator reflectionClassGenerator(file, options); reflectionClassGenerator.Generate(printer); @@ -81,6 +79,8 @@ bool Generator::Generate( cli_options.base_namespace_specified = true; } else if (options[i].first == "internal_access") { cli_options.internal_access = true; + } else if (options[i].first == "serializable") { + cli_options.serializable = true; } else { *error = "Unknown generator option: " + options[i].first; return false; diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_generator.h b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_generator.h index c8b19529..da72e0e7 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_generator.h +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_generator.h @@ -37,6 +37,8 @@ #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -46,9 +48,8 @@ namespace csharp { // header. If you create your own protocol compiler binary and you want // it to support C# output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT Generator - : public google::protobuf::compiler::CodeGenerator { -public: +class PROTOC_EXPORT Generator : public CodeGenerator { + public: virtual bool Generate( const FileDescriptor* file, const string& parameter, @@ -61,4 +62,6 @@ public: } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_GENERATOR_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_helpers.cc b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_helpers.cc index 5bca1ffa..e8b5dcda 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_helpers.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_helpers.cc @@ -33,9 +33,9 @@ // Sanjay Ghemawat, Jeff Dean, and others. #include -#include #include #include +#include #include #include @@ -43,7 +43,6 @@ #include #include #include -#include #include #include @@ -169,7 +168,7 @@ std::string UnderscoresToCamelCase(const std::string& input, } } // Add a trailing "_" if the name should be altered. - if (input[input.size() - 1] == '#') { + if (input.size() > 0 && input[input.size() - 1] == '#') { result += '_'; } return result; @@ -197,7 +196,7 @@ std::string ShoutyToPascalCase(const std::string& input) { char current = input[i]; if (!ascii_isalnum(current)) { previous = current; - continue; + continue; } if (!ascii_isalnum(previous)) { result += ascii_toupper(current); @@ -227,7 +226,7 @@ std::string TryRemovePrefix(const std::string& prefix, const std::string& value) prefix_to_match += ascii_tolower(prefix[i]); } } - + // This keeps track of how much of value we've consumed size_t prefix_index, value_index; for (prefix_index = 0, value_index = 0; @@ -277,6 +276,19 @@ std::string GetEnumValueName(const std::string& enum_name, const std::string& en return result; } +uint GetGroupEndTag(const Descriptor* descriptor) { + const Descriptor* containing_type = descriptor->containing_type(); + if (containing_type == NULL) { + return 0; + } + const FieldDescriptor* field = containing_type->FindFieldByName(descriptor->name()); + if (field != NULL && field->type() == FieldDescriptor::Type::TYPE_GROUP) { + return internal::WireFormatLite::MakeTag(field->number(), internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED); + } else { + return 0; + } +} + std::string ToCSharpName(const std::string& name, const FileDescriptor* file) { std::string result = GetFileNamespace(file); if (result != "") { @@ -341,12 +353,10 @@ std::string GetPropertyName(const FieldDescriptor* descriptor) { return property_name; } -std::string GetOutputFile( - const google::protobuf::FileDescriptor* descriptor, - const std::string file_extension, - const bool generate_directories, - const std::string base_namespace, - string* error) { +std::string GetOutputFile(const FileDescriptor* descriptor, + const std::string file_extension, + const bool generate_directories, + const std::string base_namespace, string* error) { string relative_filename = GetFileNameBase(descriptor) + file_extension; if (!generate_directories) { return relative_filename; @@ -452,55 +462,89 @@ std::string FileDescriptorToBase64(const FileDescriptor* descriptor) { } FieldGeneratorBase* CreateFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, + int presenceIndex, const Options* options) { switch (descriptor->type()) { case FieldDescriptor::TYPE_GROUP: case FieldDescriptor::TYPE_MESSAGE: if (descriptor->is_repeated()) { if (descriptor->is_map()) { - return new MapFieldGenerator(descriptor, fieldOrdinal, options); + return new MapFieldGenerator(descriptor, presenceIndex, options); } else { - return new RepeatedMessageFieldGenerator(descriptor, fieldOrdinal, options); + return new RepeatedMessageFieldGenerator(descriptor, presenceIndex, options); } } else { if (IsWrapperType(descriptor)) { if (descriptor->containing_oneof()) { - return new WrapperOneofFieldGenerator(descriptor, fieldOrdinal, options); + return new WrapperOneofFieldGenerator(descriptor, presenceIndex, options); } else { - return new WrapperFieldGenerator(descriptor, fieldOrdinal, options); + return new WrapperFieldGenerator(descriptor, presenceIndex, options); } } else { if (descriptor->containing_oneof()) { - return new MessageOneofFieldGenerator(descriptor, fieldOrdinal, options); + return new MessageOneofFieldGenerator(descriptor, presenceIndex, options); } else { - return new MessageFieldGenerator(descriptor, fieldOrdinal, options); + return new MessageFieldGenerator(descriptor, presenceIndex, options); } } } case FieldDescriptor::TYPE_ENUM: if (descriptor->is_repeated()) { - return new RepeatedEnumFieldGenerator(descriptor, fieldOrdinal, options); + return new RepeatedEnumFieldGenerator(descriptor, presenceIndex, options); } else { if (descriptor->containing_oneof()) { - return new EnumOneofFieldGenerator(descriptor, fieldOrdinal, options); + return new EnumOneofFieldGenerator(descriptor, presenceIndex, options); } else { - return new EnumFieldGenerator(descriptor, fieldOrdinal, options); + return new EnumFieldGenerator(descriptor, presenceIndex, options); } } default: if (descriptor->is_repeated()) { - return new RepeatedPrimitiveFieldGenerator(descriptor, fieldOrdinal, options); + return new RepeatedPrimitiveFieldGenerator(descriptor, presenceIndex, options); } else { if (descriptor->containing_oneof()) { - return new PrimitiveOneofFieldGenerator(descriptor, fieldOrdinal, options); + return new PrimitiveOneofFieldGenerator(descriptor, presenceIndex, options); } else { - return new PrimitiveFieldGenerator(descriptor, fieldOrdinal, options); + return new PrimitiveFieldGenerator(descriptor, presenceIndex, options); } } } } +bool IsNullable(const FieldDescriptor* descriptor) { + if (descriptor->is_repeated()) { + return true; + } + + switch (descriptor->type()) { + case FieldDescriptor::TYPE_ENUM: + case FieldDescriptor::TYPE_DOUBLE: + case FieldDescriptor::TYPE_FLOAT: + case FieldDescriptor::TYPE_INT64: + case FieldDescriptor::TYPE_UINT64: + case FieldDescriptor::TYPE_INT32: + case FieldDescriptor::TYPE_FIXED64: + case FieldDescriptor::TYPE_FIXED32: + case FieldDescriptor::TYPE_BOOL: + case FieldDescriptor::TYPE_UINT32: + case FieldDescriptor::TYPE_SFIXED32: + case FieldDescriptor::TYPE_SFIXED64: + case FieldDescriptor::TYPE_SINT32: + case FieldDescriptor::TYPE_SINT64: + return false; + + case FieldDescriptor::TYPE_MESSAGE: + case FieldDescriptor::TYPE_GROUP: + case FieldDescriptor::TYPE_STRING: + case FieldDescriptor::TYPE_BYTES: + return true; + + default: + GOOGLE_LOG(FATAL) << "Unknown field type."; + return true; + } +} + } // namespace csharp } // namespace compiler } // namespace protobuf diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_helpers.h b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_helpers.h index c317ad0e..d351a1c9 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_helpers.h +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_helpers.h @@ -42,6 +42,8 @@ #include #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -96,7 +98,8 @@ std::string UnderscoresToPascalCase(const std::string& input); // Note that we wouldn't normally want to export this (we're not expecting // it to be used outside libprotoc itself) but this exposes it for testing. -std::string LIBPROTOBUF_EXPORT GetEnumValueName(const std::string& enum_name, const std::string& enum_value_name); +std::string PROTOC_EXPORT GetEnumValueName(const std::string& enum_name, + const std::string& enum_value_name); // TODO(jtattermusch): perhaps we could move this to strutil std::string StringToBase64(const std::string& input); @@ -104,15 +107,20 @@ std::string StringToBase64(const std::string& input); std::string FileDescriptorToBase64(const FileDescriptor* descriptor); FieldGeneratorBase* CreateFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, + int presenceIndex, const Options* options); +bool IsNullable(const FieldDescriptor* descriptor); + // Determines whether the given message is a map entry message, // i.e. one implicitly created by protoc due to a map field. inline bool IsMapEntryMessage(const Descriptor* descriptor) { return descriptor->options().map_entry(); } +// Checks if this descriptor is for a group and gets its end tag or 0 if it's not a group +uint GetGroupEndTag(const Descriptor* descriptor); + // Determines whether we're generating code for the proto representation of // descriptors etc, for use in the runtime. This is the only type which is // allowed to use proto2 syntax, and it generates internal classes. @@ -141,8 +149,15 @@ inline bool IsWrapperType(const FieldDescriptor* descriptor) { descriptor->message_type()->file()->name() == "google/protobuf/wrappers.proto"; } +inline bool IsProto2(const FileDescriptor* descriptor) { + return descriptor->syntax() == FileDescriptor::SYNTAX_PROTO2; +} + } // namespace csharp } // namespace compiler } // namespace protobuf } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_HELPERS_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_map_field.cc b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_map_field.cc index d58514ce..f3f09ea4 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_map_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_map_field.cc @@ -31,7 +31,6 @@ #include #include -#include #include #include #include @@ -48,15 +47,15 @@ namespace compiler { namespace csharp { MapFieldGenerator::MapFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, + int presenceIndex, const Options* options) - : FieldGeneratorBase(descriptor, fieldOrdinal, options) { + : FieldGeneratorBase(descriptor, presenceIndex, options) { } MapFieldGenerator::~MapFieldGenerator() { } -void MapFieldGenerator::GenerateMembers(io::Printer* printer) { +void MapFieldGenerator::GenerateMembers(io::Printer* printer) { const FieldDescriptor* key_descriptor = descriptor_->message_type()->FindFieldByName("key"); const FieldDescriptor* value_descriptor = diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_map_field.h b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_map_field.h index 84a33a03..b920b9f2 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_map_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_map_field.h @@ -44,10 +44,13 @@ namespace csharp { class MapFieldGenerator : public FieldGeneratorBase { public: MapFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, + int presenceIndex, const Options* options); ~MapFieldGenerator(); + MapFieldGenerator(const MapFieldGenerator&) = delete; + MapFieldGenerator& operator=(const MapFieldGenerator&) = delete; + virtual void GenerateCloningCode(io::Printer* printer); virtual void GenerateFreezingCode(io::Printer* printer); virtual void GenerateMembers(io::Printer* printer); @@ -59,9 +62,6 @@ class MapFieldGenerator : public FieldGeneratorBase { virtual void WriteHash(io::Printer* printer); virtual void WriteEquals(io::Printer* printer); virtual void WriteToString(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldGenerator); }; } // namespace csharp diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_message.cc b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_message.cc index 8a4307f1..e365463b 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_message.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_message.cc @@ -33,7 +33,6 @@ #include #include -#include #include #include #include @@ -42,6 +41,7 @@ #include #include +#include #include #include #include @@ -61,20 +61,28 @@ bool CompareFieldNumbers(const FieldDescriptor* d1, const FieldDescriptor* d2) { MessageGenerator::MessageGenerator(const Descriptor* descriptor, const Options* options) : SourceGeneratorBase(descriptor->file(), options), - descriptor_(descriptor) { - - // sorted field names - for (int i = 0; i < descriptor_->field_count(); i++) { - field_names_.push_back(descriptor_->field(i)->name()); - } - std::sort(field_names_.begin(), field_names_.end()); - + descriptor_(descriptor), + has_bit_field_count_(0), + end_tag_(GetGroupEndTag(descriptor)) { // fields by number for (int i = 0; i < descriptor_->field_count(); i++) { fields_by_number_.push_back(descriptor_->field(i)); } std::sort(fields_by_number_.begin(), fields_by_number_.end(), CompareFieldNumbers); + + if (IsProto2(descriptor_->file())) { + int primitiveCount = 0; + for (int i = 0; i < descriptor_->field_count(); i++) { + const FieldDescriptor* field = descriptor_->field(i); + if (!IsNullable(field)) { + primitiveCount++; + if (has_bit_field_count_ == 0 || (primitiveCount % 32) == 0) { + has_bit_field_count_++; + } + } + } + } } MessageGenerator::~MessageGenerator() { @@ -88,10 +96,6 @@ std::string MessageGenerator::full_class_name() { return GetClassName(descriptor_); } -const std::vector& MessageGenerator::field_names() { - return field_names_; -} - const std::vector& MessageGenerator::fields_by_number() { return fields_by_number_; } @@ -102,6 +106,12 @@ void MessageGenerator::AddDeprecatedFlag(io::Printer* printer) { } } +void MessageGenerator::AddSerializableAttribute(io::Printer* printer) { + if (this->options()->serializable) { + printer->Print("[global::System.SerializableAttribute]\n"); + } +} + void MessageGenerator::Generate(io::Printer* printer) { std::map vars; vars["class_name"] = class_name(); @@ -109,6 +119,7 @@ void MessageGenerator::Generate(io::Printer* printer) { WriteMessageDocComment(printer, descriptor_); AddDeprecatedFlag(printer); + AddSerializableAttribute(printer); printer->Print( vars, @@ -123,6 +134,12 @@ void MessageGenerator::Generate(io::Printer* printer) { printer->Print( "private pb::UnknownFieldSet _unknownFields;\n"); + for (int i = 0; i < has_bit_field_count_; i++) { + // don't use arrays since all arrays are heap allocated, saving allocations + // use ints instead of bytes since bytes lack bitwise operators, saving casts + printer->Print("private int _hasBits$i$;\n", "i", SimpleItoa(i)); + } + WriteGeneratedCodeAttributes(printer); printer->Print( @@ -288,6 +305,9 @@ void MessageGenerator::GenerateCloningCode(io::Printer* printer) { vars, "public $class_name$($class_name$ other) : this() {\n"); printer->Indent(); + for (int i = 0; i < has_bit_field_count_; i++) { + printer->Print("_hasBits$i$ = other._hasBits$i$;\n", "i", SimpleItoa(i)); + } // Clone non-oneof fields first for (int i = 0; i < descriptor_->field_count(); i++) { if (!descriptor_->field(i)->containing_oneof()) { @@ -466,7 +486,7 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) { "}\n"); // Merge non-oneof fields for (int i = 0; i < descriptor_->field_count(); i++) { - if (!descriptor_->field(i)->containing_oneof()) { + if (!descriptor_->field(i)->containing_oneof()) { std::unique_ptr generator( CreateFieldGeneratorInternal(descriptor_->field(i))); generator->GenerateMergingCode(printer); @@ -521,6 +541,12 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) { "default:\n" " _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);\n" " break;\n"); + if (end_tag_ != 0) { + printer->Print( + "$end_tag$:\n" + " return;\n", + "end_tag", SimpleItoa(end_tag_)); + } } for (int i = 0; i < fields_by_number().size(); i++) { const FieldDescriptor* field = fields_by_number()[i]; @@ -559,19 +585,29 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) { printer->Print("}\n\n"); // method } -int MessageGenerator::GetFieldOrdinal(const FieldDescriptor* descriptor) { - for (int i = 0; i < field_names().size(); i++) { - if (field_names()[i] == descriptor->name()) { - return i; +// it's a waste of space to track presence for all values, so we only track them if they're not nullable +int MessageGenerator::GetPresenceIndex(const FieldDescriptor* descriptor) { + if (IsNullable(descriptor) || !IsProto2(descriptor_->file())) { + return -1; + } + + int index = 0; + for (int i = 0; i < fields_by_number().size(); i++) { + const FieldDescriptor* field = fields_by_number()[i]; + if (field == descriptor) { + return index; + } + if (!IsNullable(field)) { + index++; } } - GOOGLE_LOG(DFATAL)<< "Could not find ordinal for field " << descriptor->name(); + GOOGLE_LOG(DFATAL)<< "Could not find presence index for field " << descriptor->name(); return -1; } FieldGeneratorBase* MessageGenerator::CreateFieldGeneratorInternal( const FieldDescriptor* descriptor) { - return CreateFieldGenerator(descriptor, GetFieldOrdinal(descriptor), this->options()); + return CreateFieldGenerator(descriptor, GetPresenceIndex(descriptor), this->options()); } } // namespace csharp diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_message.h b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_message.h index e7f3b4d0..7e88ecf1 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_message.h +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_message.h @@ -50,6 +50,9 @@ class MessageGenerator : public SourceGeneratorBase { MessageGenerator(const Descriptor* descriptor, const Options* options); ~MessageGenerator(); + MessageGenerator(const MessageGenerator&) = delete; + MessageGenerator& operator=(const MessageGenerator&) = delete; + void GenerateCloningCode(io::Printer* printer); void GenerateFreezingCode(io::Printer* printer); void GenerateFrameworkMethods(io::Printer* printer); @@ -57,30 +60,27 @@ class MessageGenerator : public SourceGeneratorBase { private: const Descriptor* descriptor_; - std::vector field_names_; std::vector fields_by_number_; + int has_bit_field_count_; + uint end_tag_; void GenerateMessageSerializationMethods(io::Printer* printer); void GenerateMergingMethods(io::Printer* printer); - int GetFieldOrdinal(const FieldDescriptor* descriptor); + int GetPresenceIndex(const FieldDescriptor* descriptor); FieldGeneratorBase* CreateFieldGeneratorInternal( const FieldDescriptor* descriptor); bool HasNestedGeneratedTypes(); void AddDeprecatedFlag(io::Printer* printer); - + void AddSerializableAttribute(io::Printer* printer); + std::string class_name(); std::string full_class_name(); - // field names sorted alphabetically - const std::vector& field_names(); - // field descriptors sorted by number const std::vector& fields_by_number(); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator); }; } // namespace csharp diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_message_field.cc b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_message_field.cc index cf1b4dbf..ab76552d 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_message_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_message_field.cc @@ -31,12 +31,13 @@ #include #include -#include #include #include #include #include #include +#include +#include #include #include @@ -49,11 +50,28 @@ namespace compiler { namespace csharp { MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, + int presenceIndex, const Options *options) - : FieldGeneratorBase(descriptor, fieldOrdinal, options) { - variables_["has_property_check"] = name() + "_ != null"; - variables_["has_not_property_check"] = name() + "_ == null"; + : FieldGeneratorBase(descriptor, presenceIndex, options) { + if (!IsProto2(descriptor_->file())) { + variables_["has_property_check"] = name() + "_ != null"; + variables_["has_not_property_check"] = name() + "_ == null"; + } + + if (descriptor_->type() == FieldDescriptor::Type::TYPE_GROUP) { + int tag_size = internal::WireFormat::TagSize(descriptor_->number(), descriptor_->type()) / 2; + uint tag = internal::WireFormatLite::MakeTag( + descriptor_->number(), + internal::WireFormatLite::WIRETYPE_END_GROUP); + uint8 tag_array[5]; + io::CodedOutputStream::WriteTagToArray(tag, tag_array); + string tag_bytes = SimpleItoa(tag_array[0]); + for (int i = 1; i < tag_size; i++) { + tag_bytes += ", " + SimpleItoa(tag_array[i]); + } + variables_["end_tag"] = SimpleItoa(tag); + variables_["end_tag_bytes"] = tag_bytes; + } } MessageFieldGenerator::~MessageFieldGenerator() { @@ -74,6 +92,26 @@ void MessageFieldGenerator::GenerateMembers(io::Printer* printer) { " $name$_ = value;\n" " }\n" "}\n"); + if (IsProto2(descriptor_->file())) { + printer->Print( + variables_, + "/// Gets whether the $descriptor_name$ field is set\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ bool Has$property_name$ {\n" + " get { return $name$_ != null; }\n" + "}\n"); + printer->Print( + variables_, + "/// Clears the value of the $descriptor_name$ field\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ void Clear$property_name$() {\n" + " $name$_ = null;\n" + "}\n"); + } } void MessageFieldGenerator::GenerateMergingCode(io::Printer* printer) { @@ -81,7 +119,7 @@ void MessageFieldGenerator::GenerateMergingCode(io::Printer* printer) { variables_, "if (other.$has_property_check$) {\n" " if ($has_not_property_check$) {\n" - " $name$_ = new $type_name$();\n" + " $property_name$ = new $type_name$();\n" " }\n" " $property_name$.MergeFrom(other.$property_name$);\n" "}\n"); @@ -91,27 +129,48 @@ void MessageFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, "if ($has_not_property_check$) {\n" - " $name$_ = new $type_name$();\n" - "}\n" - // TODO(jonskeet): Do we really need merging behaviour like this? - "input.ReadMessage($name$_);\n"); // No need to support TYPE_GROUP... + " $property_name$ = new $type_name$();\n" + "}\n"); + if (descriptor_->type() == FieldDescriptor::Type::TYPE_MESSAGE) { + printer->Print(variables_, "input.ReadMessage($property_name$);\n"); + } else { + printer->Print(variables_, "input.ReadGroup($property_name$);\n"); + } } void MessageFieldGenerator::GenerateSerializationCode(io::Printer* printer) { - printer->Print( - variables_, - "if ($has_property_check$) {\n" - " output.WriteRawTag($tag_bytes$);\n" - " output.WriteMessage($property_name$);\n" - "}\n"); + if (descriptor_->type() == FieldDescriptor::Type::TYPE_MESSAGE) { + printer->Print( + variables_, + "if ($has_property_check$) {\n" + " output.WriteRawTag($tag_bytes$);\n" + " output.WriteMessage($property_name$);\n" + "}\n"); + } else { + printer->Print( + variables_, + "if ($has_property_check$) {\n" + " output.WriteRawTag($tag_bytes$);\n" + " output.WriteGroup($property_name$);\n" + " output.WriteRawTag($end_tag_bytes$);\n" + "}\n"); + } } void MessageFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { - printer->Print( - variables_, - "if ($has_property_check$) {\n" - " size += $tag_size$ + pb::CodedOutputStream.ComputeMessageSize($property_name$);\n" - "}\n"); + if (descriptor_->type() == FieldDescriptor::Type::TYPE_MESSAGE) { + printer->Print( + variables_, + "if ($has_property_check$) {\n" + " size += $tag_size$ + pb::CodedOutputStream.ComputeMessageSize($property_name$);\n" + "}\n"); + } else { + printer->Print( + variables_, + "if ($has_property_check$) {\n" + " size += $tag_size$ + $tag_size$ + pb::CodedOutputStream.ComputeGroupSize($property_name$);\n" + "}\n"); + } } void MessageFieldGenerator::WriteHash(io::Printer* printer) { @@ -130,7 +189,6 @@ void MessageFieldGenerator::WriteToString(io::Printer* printer) { variables_, "PrintField(\"$field_name$\", has$property_name$, $name$_, writer);\n"); } - void MessageFieldGenerator::GenerateCloningCode(io::Printer* printer) { printer->Print(variables_, "$name$_ = other.$has_property_check$ ? other.$name$_.Clone() : null;\n"); @@ -140,16 +198,22 @@ void MessageFieldGenerator::GenerateFreezingCode(io::Printer* printer) { } void MessageFieldGenerator::GenerateCodecCode(io::Printer* printer) { - printer->Print( - variables_, - "pb::FieldCodec.ForMessage($tag$, $type_name$.Parser)"); + if (descriptor_->type() == FieldDescriptor::Type::TYPE_MESSAGE) { + printer->Print( + variables_, + "pb::FieldCodec.ForMessage($tag$, $type_name$.Parser)"); + } else { + printer->Print( + variables_, + "pb::FieldCodec.ForGroup($tag$, $end_tag$, $type_name$.Parser)"); + } } MessageOneofFieldGenerator::MessageOneofFieldGenerator( const FieldDescriptor* descriptor, - int fieldOrdinal, + int presenceIndex, const Options *options) - : MessageFieldGenerator(descriptor, fieldOrdinal, options) { + : MessageFieldGenerator(descriptor, presenceIndex, options) { SetCommonOneofFieldVariables(&variables_); } @@ -169,10 +233,32 @@ void MessageOneofFieldGenerator::GenerateMembers(io::Printer* printer) { " $oneof_name$Case_ = value == null ? $oneof_property_name$OneofCase.None : $oneof_property_name$OneofCase.$property_name$;\n" " }\n" "}\n"); + if (IsProto2(descriptor_->file())) { + printer->Print( + variables_, + "/// Gets whether the \"$descriptor_name$\" field is set\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ bool Has$property_name$ {\n" + " get { return $oneof_name$Case_ == $oneof_property_name$OneofCase.$property_name$; }\n" + "}\n"); + printer->Print( + variables_, + "/// Clears the value of the oneof if it's currently set to \"$descriptor_name$\" \n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ void Clear$property_name$() {\n" + " if ($has_property_check$) {\n" + " Clear$oneof_property_name$();\n" + " }\n" + "}\n"); + } } void MessageOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) { - printer->Print(variables_, + printer->Print(variables_, "if ($property_name$ == null) {\n" " $property_name$ = new $type_name$();\n" "}\n" @@ -186,9 +272,13 @@ void MessageOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { "$type_name$ subBuilder = new $type_name$();\n" "if ($has_property_check$) {\n" " subBuilder.MergeFrom($property_name$);\n" - "}\n" - "input.ReadMessage(subBuilder);\n" // No support of TYPE_GROUP - "$property_name$ = subBuilder;\n"); + "}\n"); + if (descriptor_->type() == FieldDescriptor::Type::TYPE_MESSAGE) { + printer->Print("input.ReadMessage(subBuilder);\n"); + } else { + printer->Print("input.ReadGroup(subBuilder);\n"); + } + printer->Print(variables_, "$property_name$ = subBuilder;\n"); } void MessageOneofFieldGenerator::WriteToString(io::Printer* printer) { diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_message_field.h b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_message_field.h index c41ee88a..224bc28e 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_message_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_message_field.h @@ -44,10 +44,13 @@ namespace csharp { class MessageFieldGenerator : public FieldGeneratorBase { public: MessageFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, + int presenceIndex, const Options *options); ~MessageFieldGenerator(); + MessageFieldGenerator(const MessageFieldGenerator&) = delete; + MessageFieldGenerator& operator=(const MessageFieldGenerator&) = delete; + virtual void GenerateCodecCode(io::Printer* printer); virtual void GenerateCloningCode(io::Printer* printer); virtual void GenerateFreezingCode(io::Printer* printer); @@ -60,26 +63,24 @@ class MessageFieldGenerator : public FieldGeneratorBase { virtual void WriteHash(io::Printer* printer); virtual void WriteEquals(io::Printer* printer); virtual void WriteToString(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator); }; class MessageOneofFieldGenerator : public MessageFieldGenerator { public: MessageOneofFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, + int presenceIndex, const Options *options); ~MessageOneofFieldGenerator(); + MessageOneofFieldGenerator(const MessageOneofFieldGenerator&) = delete; + MessageOneofFieldGenerator& operator=(const MessageOneofFieldGenerator&) = + delete; + virtual void GenerateCloningCode(io::Printer* printer); virtual void GenerateMembers(io::Printer* printer); virtual void GenerateMergingCode(io::Printer* printer); virtual void WriteToString(io::Printer* printer); virtual void GenerateParsingCode(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageOneofFieldGenerator); }; } // namespace csharp diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_names.h b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_names.h index 21758f28..0c5ade91 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_names.h +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_names.h @@ -41,6 +41,8 @@ #include #include +#include + namespace google { namespace protobuf { @@ -57,14 +59,14 @@ namespace csharp { // // Returns: // The namespace to use for given file descriptor. -string LIBPROTOC_EXPORT GetFileNamespace(const FileDescriptor* descriptor); +string PROTOC_EXPORT GetFileNamespace(const FileDescriptor* descriptor); // Requires: // descriptor != NULL // // Returns: // The fully-qualified C# class name. -string LIBPROTOC_EXPORT GetClassName(const Descriptor* descriptor); +string PROTOC_EXPORT GetClassName(const Descriptor* descriptor); // Requires: // descriptor != NULL @@ -73,7 +75,7 @@ string LIBPROTOC_EXPORT GetClassName(const Descriptor* descriptor); // The fully-qualified name of the C# class that provides // access to the file descriptor. Proto compiler generates // such class for each .proto file processed. -string LIBPROTOC_EXPORT GetReflectionClassName(const FileDescriptor* descriptor); +string PROTOC_EXPORT GetReflectionClassName(const FileDescriptor* descriptor); // Generates output file name for given file descriptor. If generate_directories // is true, the output file will be put under directory corresponding to file's @@ -89,16 +91,16 @@ string LIBPROTOC_EXPORT GetReflectionClassName(const FileDescriptor* descriptor) // The file name to use as output file for given file descriptor. In case // of failure, this function will return empty string and error parameter // will contain the error message. -string LIBPROTOC_EXPORT GetOutputFile( - const google::protobuf::FileDescriptor* descriptor, - const string file_extension, - const bool generate_directories, - const string base_namespace, - string* error); +string PROTOC_EXPORT GetOutputFile(const FileDescriptor* descriptor, + const string file_extension, + const bool generate_directories, + const string base_namespace, string* error); } // namespace csharp } // namespace compiler } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_NAMES_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_options.h b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_options.h index 426fb3b5..42ff6d86 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_options.h +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_options.h @@ -33,7 +33,6 @@ #include -#include namespace google { namespace protobuf { namespace compiler { @@ -45,10 +44,11 @@ struct Options { file_extension(".cs"), base_namespace(""), base_namespace_specified(false), - internal_access(false) { + internal_access(false), + serializable(false) { } // Extension of the generated file. Defaults to ".cs" - string file_extension; + std::string file_extension; // Base namespace to use to create directory hierarchy. Defaults to "". // This option allows the simple creation of a conventional C# file layout, // where directories are created relative to a project-specific base @@ -59,7 +59,7 @@ struct Options { // // If no base namespace is specified, all files are generated in the // --csharp_out directory, with no subdirectories created automatically. - string base_namespace; + std::string base_namespace; // Whether the base namespace has been explicitly specified by the user. // This is required as the base namespace can be explicitly set to the empty // string, meaning "create a full directory hierarchy, starting from the first @@ -68,12 +68,14 @@ struct Options { // Whether the generated classes should have accessibility level of "internal". // Defaults to false that generates "public" classes. bool internal_access; + // Whether the generated classes should have a global::System.Serializable attribute added + // Defaults to false + bool serializable; }; } // namespace csharp } // namespace compiler } // namespace protobuf - - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_OPTIONS_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc index c3003e3d..0bf10f2e 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc @@ -31,7 +31,6 @@ #include #include -#include #include #include #include @@ -49,12 +48,12 @@ namespace compiler { namespace csharp { PrimitiveFieldGenerator::PrimitiveFieldGenerator( - const FieldDescriptor* descriptor, int fieldOrdinal, const Options *options) - : FieldGeneratorBase(descriptor, fieldOrdinal, options) { + const FieldDescriptor* descriptor, int presenceIndex, const Options *options) + : FieldGeneratorBase(descriptor, presenceIndex, options) { // TODO(jonskeet): Make this cleaner... is_value_type = descriptor->type() != FieldDescriptor::TYPE_STRING && descriptor->type() != FieldDescriptor::TYPE_BYTES; - if (!is_value_type) { + if (!is_value_type && !IsProto2(descriptor_->file())) { variables_["has_property_check"] = variables_["property_name"] + ".Length != 0"; variables_["other_has_property_check"] = "other." + variables_["property_name"] + ".Length != 0"; } @@ -67,16 +66,44 @@ void PrimitiveFieldGenerator::GenerateMembers(io::Printer* printer) { // TODO(jonskeet): Work out whether we want to prevent the fields from ever being // null, or whether we just handle it, in the cases of bytes and string. // (Basically, should null-handling code be in the getter or the setter?) + if (IsProto2(descriptor_->file())) { + printer->Print( + variables_, + "private readonly static $type_name$ $property_name$DefaultValue = $default_value$;\n\n"); + } + printer->Print( variables_, "private $type_name$ $name_def_message$;\n"); + WritePropertyDocComment(printer, descriptor_); AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "$access_level$ $type_name$ $property_name$ {\n" - " get { return $name$_; }\n" - " set {\n"); + if (IsProto2(descriptor_->file())) { + if (presenceIndex_ == -1) { + printer->Print( + variables_, + "$access_level$ $type_name$ $property_name$ {\n" + " get { return $name$_ ?? $property_name$DefaultValue; }\n" + " set {\n"); + } else { + printer->Print( + variables_, + "$access_level$ $type_name$ $property_name$ {\n" + " get { if ($has_field_check$) { return $name$_; } else { return $property_name$DefaultValue; } }\n" + " set {\n"); + } + } else { + printer->Print( + variables_, + "$access_level$ $type_name$ $property_name$ {\n" + " get { return $name$_; }\n" + " set {\n"); + } + if (presenceIndex_ != -1) { + printer->Print( + variables_, + " $set_has_field$;\n"); + } if (is_value_type) { printer->Print( variables_, @@ -89,6 +116,36 @@ void PrimitiveFieldGenerator::GenerateMembers(io::Printer* printer) { printer->Print( " }\n" "}\n"); + if (IsProto2(descriptor_->file())) { + printer->Print(variables_, "/// Gets whether the \"$descriptor_name$\" field is set\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ bool Has$property_name$ {\n" + " get { return "); + if (IsNullable(descriptor_)) { + printer->Print( + variables_, + "$name$_ != null; }\n}\n"); + } else { + printer->Print( + variables_, + "$has_field_check$; }\n}\n"); + } + } + if (IsProto2(descriptor_->file())) { + printer->Print(variables_, "/// Clears the value of the \"$descriptor_name$\" field\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ void Clear$property_name$() {\n"); + if (IsNullable(descriptor_)) { + printer->Print(variables_, " $name$_ = null;\n"); + } else { + printer->Print(variables_, " $clear_has_field$;\n"); + } + printer->Print("}\n"); + } } void PrimitiveFieldGenerator::GenerateMergingCode(io::Printer* printer) { @@ -172,8 +229,8 @@ void PrimitiveFieldGenerator::GenerateCodecCode(io::Printer* printer) { } PrimitiveOneofFieldGenerator::PrimitiveOneofFieldGenerator( - const FieldDescriptor* descriptor, int fieldOrdinal, const Options *options) - : PrimitiveFieldGenerator(descriptor, fieldOrdinal, options) { + const FieldDescriptor* descriptor, int presenceIndex, const Options *options) + : PrimitiveFieldGenerator(descriptor, presenceIndex, options) { SetCommonOneofFieldVariables(&variables_); } @@ -188,20 +245,42 @@ void PrimitiveOneofFieldGenerator::GenerateMembers(io::Printer* printer) { "$access_level$ $type_name$ $property_name$ {\n" " get { return $has_property_check$ ? ($type_name$) $oneof_name$_ : $default_value$; }\n" " set {\n"); - if (is_value_type) { - printer->Print( - variables_, - " $oneof_name$_ = value;\n"); - } else { - printer->Print( - variables_, - " $oneof_name$_ = pb::ProtoPreconditions.CheckNotNull(value, \"value\");\n"); - } + if (is_value_type) { printer->Print( variables_, - " $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" + " $oneof_name$_ = value;\n"); + } else { + printer->Print( + variables_, + " $oneof_name$_ = pb::ProtoPreconditions.CheckNotNull(value, \"value\");\n"); + } + printer->Print( + variables_, + " $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" + " }\n" + "}\n"); + if (IsProto2(descriptor_->file())) { + printer->Print( + variables_, + "/// Gets whether the \"$descriptor_name$\" field is set\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ bool Has$property_name$ {\n" + " get { return $oneof_name$Case_ == $oneof_property_name$OneofCase.$property_name$; }\n" + "}\n"); + printer->Print( + variables_, + "/// Clears the value of the oneof if it's currently set to \"$descriptor_name$\" \n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ void Clear$property_name$() {\n" + " if ($has_property_check$) {\n" + " Clear$oneof_property_name$();\n" " }\n" "}\n"); + } } void PrimitiveOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) { diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_primitive_field.h b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_primitive_field.h index ca7b8b3d..54782e15 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_primitive_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_primitive_field.h @@ -46,10 +46,13 @@ struct Options; class PrimitiveFieldGenerator : public FieldGeneratorBase { public: PrimitiveFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, + int presenceIndex, const Options *options); ~PrimitiveFieldGenerator(); + PrimitiveFieldGenerator(const PrimitiveFieldGenerator&) = delete; + PrimitiveFieldGenerator& operator=(const PrimitiveFieldGenerator&) = delete; + virtual void GenerateCodecCode(io::Printer* printer); virtual void GenerateCloningCode(io::Printer* printer); virtual void GenerateMembers(io::Printer* printer); @@ -64,26 +67,24 @@ class PrimitiveFieldGenerator : public FieldGeneratorBase { protected: bool is_value_type; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator); }; class PrimitiveOneofFieldGenerator : public PrimitiveFieldGenerator { public: PrimitiveOneofFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, + int presenceIndex, const Options *options); ~PrimitiveOneofFieldGenerator(); + PrimitiveOneofFieldGenerator(const PrimitiveOneofFieldGenerator&) = delete; + PrimitiveOneofFieldGenerator& operator=(const PrimitiveOneofFieldGenerator&) = + delete; + virtual void GenerateCloningCode(io::Printer* printer); virtual void GenerateMembers(io::Printer* printer); virtual void GenerateMergingCode(io::Printer* printer); virtual void WriteToString(io::Printer* printer); virtual void GenerateParsingCode(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveOneofFieldGenerator); }; } // namespace csharp diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_reflection_class.cc b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_reflection_class.cc index 5ddd616e..4ed2ef36 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_reflection_class.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_reflection_class.cc @@ -31,7 +31,6 @@ #include #include -#include #include #include #include @@ -234,7 +233,7 @@ void ReflectionClassGenerator::WriteGeneratedCodeInfo(const Descriptor* descript } // Generated message type printer->Print("new pbr::GeneratedClrTypeInfo(typeof($type_name$), $type_name$.Parser, ", "type_name", GetClassName(descriptor)); - + // Fields if (descriptor->field_count() > 0) { std::vector fields; @@ -273,7 +272,7 @@ void ReflectionClassGenerator::WriteGeneratedCodeInfo(const Descriptor* descript // Nested types if (descriptor->nested_type_count() > 0) { - // Need to specify array type explicitly here, as all elements may be null. + // Need to specify array type explicitly here, as all elements may be null. printer->Print("new pbr::GeneratedClrTypeInfo[] { "); for (int i = 0; i < descriptor->nested_type_count(); i++) { WriteGeneratedCodeInfo(descriptor->nested_type(i), printer, i == descriptor->nested_type_count() - 1); diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_reflection_class.h b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_reflection_class.h index e0c69f31..1a4a2f4a 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_reflection_class.h +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_reflection_class.h @@ -35,6 +35,8 @@ #include #include +#include +#include namespace google { namespace protobuf { @@ -46,6 +48,9 @@ class ReflectionClassGenerator : public SourceGeneratorBase { ReflectionClassGenerator(const FileDescriptor* file, const Options* options); ~ReflectionClassGenerator(); + ReflectionClassGenerator(const ReflectionClassGenerator&) = delete; + ReflectionClassGenerator& operator=(const ReflectionClassGenerator&) = delete; + void Generate(io::Printer* printer); private: @@ -59,8 +64,6 @@ class ReflectionClassGenerator : public SourceGeneratorBase { void WriteGeneratedCodeInfo(const Descriptor* descriptor, io::Printer* printer, bool last); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ReflectionClassGenerator); }; } // namespace csharp diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc index 683c4b0b..b8e66abb 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc @@ -31,7 +31,6 @@ #include #include -#include #include #include #include @@ -48,8 +47,8 @@ namespace compiler { namespace csharp { RepeatedEnumFieldGenerator::RepeatedEnumFieldGenerator( - const FieldDescriptor* descriptor, int fieldOrdinal, const Options *options) - : FieldGeneratorBase(descriptor, fieldOrdinal, options) { + const FieldDescriptor* descriptor, int presenceIndex, const Options *options) + : FieldGeneratorBase(descriptor, presenceIndex, options) { } RepeatedEnumFieldGenerator::~RepeatedEnumFieldGenerator() { @@ -90,7 +89,7 @@ void RepeatedEnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) "$name$_.WriteTo(output, _repeated_$name$_codec);\n"); } -void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { +void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { printer->Print( variables_, "size += $name$_.CalculateSize(_repeated_$name$_codec);\n"); diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.h b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.h index 819b5832..75de1ada 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.h @@ -41,15 +41,19 @@ namespace protobuf { namespace compiler { namespace csharp { -// TODO(jonskeet): Refactor repeated field support; all the implementations are *really* similar. We -// should probably have a RepeatedFieldGeneratorBase. +// TODO(jonskeet): Refactor repeated field support; all the implementations are +// *really* similar. We should probably have a RepeatedFieldGeneratorBase. class RepeatedEnumFieldGenerator : public FieldGeneratorBase { public: RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, + int presenceIndex, const Options *options); ~RepeatedEnumFieldGenerator(); + RepeatedEnumFieldGenerator(const RepeatedEnumFieldGenerator&) = delete; + RepeatedEnumFieldGenerator& operator=(const RepeatedEnumFieldGenerator&) = + delete; + virtual void GenerateCloningCode(io::Printer* printer); virtual void GenerateFreezingCode(io::Printer* printer); virtual void GenerateMembers(io::Printer* printer); @@ -61,9 +65,6 @@ class RepeatedEnumFieldGenerator : public FieldGeneratorBase { virtual void WriteHash(io::Printer* printer); virtual void WriteEquals(io::Printer* printer); virtual void WriteToString(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator); }; } // namespace csharp diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc index 90af569c..bf76c0d3 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc @@ -31,7 +31,6 @@ #include #include -#include #include #include #include @@ -49,8 +48,8 @@ namespace compiler { namespace csharp { RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator( - const FieldDescriptor* descriptor, int fieldOrdinal, const Options *options) - : FieldGeneratorBase(descriptor, fieldOrdinal, options) { + const FieldDescriptor* descriptor, int presenceIndex, const Options *options) + : FieldGeneratorBase(descriptor, presenceIndex, options) { } RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() { @@ -67,11 +66,11 @@ void RepeatedMessageFieldGenerator::GenerateMembers(io::Printer* printer) { // function, but it doesn't seem worth it for just this. if (IsWrapperType(descriptor_)) { std::unique_ptr single_generator( - new WrapperFieldGenerator(descriptor_, fieldOrdinal_, this->options())); + new WrapperFieldGenerator(descriptor_, presenceIndex_, this->options())); single_generator->GenerateCodecCode(printer); } else { std::unique_ptr single_generator( - new MessageFieldGenerator(descriptor_, fieldOrdinal_, this->options())); + new MessageFieldGenerator(descriptor_, presenceIndex_, this->options())); single_generator->GenerateCodecCode(printer); } printer->Print(";\n"); diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.h b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.h index 6e33648b..e1b5f27c 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.h @@ -46,10 +46,14 @@ struct Options; class RepeatedMessageFieldGenerator : public FieldGeneratorBase { public: RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, + int presenceIndex, const Options *options); ~RepeatedMessageFieldGenerator(); + RepeatedMessageFieldGenerator(const RepeatedMessageFieldGenerator&) = delete; + RepeatedMessageFieldGenerator& operator=( + const RepeatedMessageFieldGenerator&) = delete; + virtual void GenerateCloningCode(io::Printer* printer); virtual void GenerateFreezingCode(io::Printer* printer); virtual void GenerateMembers(io::Printer* printer); @@ -61,9 +65,6 @@ class RepeatedMessageFieldGenerator : public FieldGeneratorBase { virtual void WriteHash(io::Printer* printer); virtual void WriteEquals(io::Printer* printer); virtual void WriteToString(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator); }; } // namespace csharp diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc index cd91506f..78fcdc67 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc @@ -31,7 +31,6 @@ #include #include -#include #include #include #include @@ -48,8 +47,8 @@ namespace compiler { namespace csharp { RepeatedPrimitiveFieldGenerator::RepeatedPrimitiveFieldGenerator( - const FieldDescriptor* descriptor, int fieldOrdinal, const Options *options) - : FieldGeneratorBase(descriptor, fieldOrdinal, options) { + const FieldDescriptor* descriptor, int presenceIndex, const Options *options) + : FieldGeneratorBase(descriptor, presenceIndex, options) { } RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() { diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.h b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.h index a59348a9..7d9826fc 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.h @@ -43,9 +43,13 @@ namespace csharp { class RepeatedPrimitiveFieldGenerator : public FieldGeneratorBase { public: - RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor, int fieldOrdinal, const Options *options); + RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor, + int presenceIndex, const Options* options); ~RepeatedPrimitiveFieldGenerator(); + RepeatedPrimitiveFieldGenerator(const RepeatedPrimitiveFieldGenerator&) = delete; + RepeatedPrimitiveFieldGenerator& operator=(const RepeatedPrimitiveFieldGenerator&) = delete; + virtual void GenerateCloningCode(io::Printer* printer); virtual void GenerateFreezingCode(io::Printer* printer); virtual void GenerateMembers(io::Printer* printer); @@ -57,9 +61,6 @@ class RepeatedPrimitiveFieldGenerator : public FieldGeneratorBase { virtual void WriteHash(io::Printer* printer); virtual void WriteEquals(io::Printer* printer); virtual void WriteToString(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator); }; } // namespace csharp diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_source_generator_base.cc b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_source_generator_base.cc index 1fda7ddf..68209cc8 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_source_generator_base.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_source_generator_base.cc @@ -31,7 +31,6 @@ #include #include -#include #include #include #include diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_source_generator_base.h b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_source_generator_base.h index c741080e..695c4225 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_source_generator_base.h +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_source_generator_base.h @@ -34,6 +34,7 @@ #include #include +#include namespace google { namespace protobuf { @@ -47,6 +48,9 @@ class SourceGeneratorBase { SourceGeneratorBase(const FileDescriptor* descriptor, const Options* options); virtual ~SourceGeneratorBase(); + SourceGeneratorBase(const SourceGeneratorBase&) = delete; + SourceGeneratorBase& operator=(const SourceGeneratorBase&) = delete; + std::string class_access_level(); const Options* options(); @@ -57,8 +61,6 @@ class SourceGeneratorBase { private: const FileDescriptor* descriptor_; const Options *options_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SourceGeneratorBase); }; } // namespace csharp diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc index 047edf73..f284763d 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc @@ -31,7 +31,6 @@ #include #include -#include #include #include #include @@ -48,8 +47,8 @@ namespace compiler { namespace csharp { WrapperFieldGenerator::WrapperFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, const Options *options) - : FieldGeneratorBase(descriptor, fieldOrdinal, options) { + int presenceIndex, const Options *options) + : FieldGeneratorBase(descriptor, presenceIndex, options) { variables_["has_property_check"] = name() + "_ != null"; variables_["has_not_property_check"] = name() + "_ == null"; const FieldDescriptor* wrapped_field = descriptor->message_type()->field(0); @@ -81,7 +80,27 @@ void WrapperFieldGenerator::GenerateMembers(io::Printer* printer) { " set {\n" " $name$_ = value;\n" " }\n" - "}\n"); + "}\n\n"); + if (IsProto2(descriptor_->file())) { + printer->Print( + variables_, + "/// Gets whether the $descriptor_name$ field is set\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ bool Has$property_name$ {\n" + " get { return $name$_ != null; }\n" + "}\n\n"); + printer->Print( + variables_, + "/// Clears the value of the $descriptor_name$ field\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ void Clear$property_name$() {\n" + " $name$_ = null;\n" + "}\n"); + } } void WrapperFieldGenerator::GenerateMergingCode(io::Printer* printer) { @@ -163,8 +182,8 @@ void WrapperFieldGenerator::GenerateCodecCode(io::Printer* printer) { } WrapperOneofFieldGenerator::WrapperOneofFieldGenerator( - const FieldDescriptor* descriptor, int fieldOrdinal, const Options *options) - : WrapperFieldGenerator(descriptor, fieldOrdinal, options) { + const FieldDescriptor* descriptor, int presenceIndex, const Options *options) + : WrapperFieldGenerator(descriptor, presenceIndex, options) { SetCommonOneofFieldVariables(&variables_); } @@ -189,6 +208,28 @@ void WrapperOneofFieldGenerator::GenerateMembers(io::Printer* printer) { " $oneof_name$Case_ = value == null ? $oneof_property_name$OneofCase.None : $oneof_property_name$OneofCase.$property_name$;\n" " }\n" "}\n"); + if (IsProto2(descriptor_->file())) { + printer->Print( + variables_, + "/// Gets whether the \"$descriptor_name$\" field is set\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ bool Has$property_name$ {\n" + " get { return $oneof_name$Case_ == $oneof_property_name$OneofCase.$property_name$; }\n" + "}\n"); + printer->Print( + variables_, + "/// Clears the value of the oneof if it's currently set to \"$descriptor_name$\" \n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ void Clear$property_name$() {\n" + " if ($has_property_check$) {\n" + " Clear$oneof_property_name$();\n" + " }\n" + "}\n"); + } } void WrapperOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) { diff --git a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_wrapper_field.h b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_wrapper_field.h index 452531fb..ee684dda 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_wrapper_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_wrapper_field.h @@ -46,10 +46,13 @@ struct Options; class WrapperFieldGenerator : public FieldGeneratorBase { public: WrapperFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, + int presenceIndex, const Options *options); ~WrapperFieldGenerator(); + WrapperFieldGenerator(const WrapperFieldGenerator&) = delete; + WrapperFieldGenerator& operator=(const WrapperFieldGenerator&) = delete; + virtual void GenerateCodecCode(io::Printer* printer); virtual void GenerateCloningCode(io::Printer* printer); virtual void GenerateMembers(io::Printer* printer); @@ -64,24 +67,23 @@ class WrapperFieldGenerator : public FieldGeneratorBase { private: bool is_value_type; // True for int32 etc; false for bytes and string - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(WrapperFieldGenerator); }; class WrapperOneofFieldGenerator : public WrapperFieldGenerator { public: WrapperOneofFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, + int presenceIndex, const Options *options); ~WrapperOneofFieldGenerator(); + WrapperOneofFieldGenerator(const WrapperOneofFieldGenerator&) = delete; + WrapperOneofFieldGenerator& operator=(const WrapperOneofFieldGenerator&) = delete; + virtual void GenerateMembers(io::Printer* printer); virtual void GenerateMergingCode(io::Printer* printer); virtual void GenerateParsingCode(io::Printer* printer); virtual void GenerateSerializationCode(io::Printer* printer); virtual void GenerateSerializedSizeCode(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(WrapperOneofFieldGenerator); }; } // namespace csharp diff --git a/third_party/protobuf/src/google/protobuf/compiler/importer.cc b/third_party/protobuf/src/google/protobuf/compiler/importer.cc index c3831e72..715d999e 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/importer.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/importer.cc @@ -37,10 +37,10 @@ #else #include #endif -#include -#include -#include #include +#include +#include +#include #include #include @@ -48,12 +48,12 @@ #include #include +#include #include #include #include -#include #ifdef _WIN32 #include @@ -66,19 +66,17 @@ namespace compiler { #ifdef _WIN32 // DO NOT include , instead create functions in io_win32.{h,cc} and import // them like we do below. -using google::protobuf::internal::win32::access; -using google::protobuf::internal::win32::open; +using google::protobuf::io::win32::access; +using google::protobuf::io::win32::open; #endif // Returns true if the text looks like a Windows-style absolute path, starting // with a drive letter. Example: "C:\foo". TODO(kenton): Share this with // copy in command_line_interface.cc? -static bool IsWindowsAbsolutePath(const string& text) { +static bool IsWindowsAbsolutePath(const std::string& text) { #if defined(_WIN32) || defined(__CYGWIN__) - return text.size() >= 3 && text[1] == ':' && - isalpha(text[0]) && - (text[2] == '/' || text[2] == '\\') && - text.find_last_of(':') == 1; + return text.size() >= 3 && text[1] == ':' && isalpha(text[0]) && + (text[2] == '/' || text[2] == '\\') && text.find_last_of(':') == 1; #else return false; #endif @@ -93,17 +91,17 @@ MultiFileErrorCollector::~MultiFileErrorCollector() {} class SourceTreeDescriptorDatabase::SingleFileErrorCollector : public io::ErrorCollector { public: - SingleFileErrorCollector(const string& filename, + SingleFileErrorCollector(const std::string& filename, MultiFileErrorCollector* multi_file_error_collector) - : filename_(filename), - multi_file_error_collector_(multi_file_error_collector), - had_errors_(false) {} + : filename_(filename), + multi_file_error_collector_(multi_file_error_collector), + had_errors_(false) {} ~SingleFileErrorCollector() {} bool had_errors() { return had_errors_; } // implements ErrorCollector --------------------------------------- - void AddError(int line, int column, const string& message) { + void AddError(int line, int column, const std::string& message) override { if (multi_file_error_collector_ != NULL) { multi_file_error_collector_->AddError(filename_, line, column, message); } @@ -111,7 +109,7 @@ class SourceTreeDescriptorDatabase::SingleFileErrorCollector } private: - string filename_; + std::string filename_; MultiFileErrorCollector* multi_file_error_collector_; bool had_errors_; }; @@ -120,17 +118,30 @@ class SourceTreeDescriptorDatabase::SingleFileErrorCollector SourceTreeDescriptorDatabase::SourceTreeDescriptorDatabase( SourceTree* source_tree) - : source_tree_(source_tree), - error_collector_(NULL), - using_validation_error_collector_(false), - validation_error_collector_(this) {} + : source_tree_(source_tree), + fallback_database_(nullptr), + error_collector_(nullptr), + using_validation_error_collector_(false), + validation_error_collector_(this) {} + +SourceTreeDescriptorDatabase::SourceTreeDescriptorDatabase( + SourceTree* source_tree, DescriptorDatabase* fallback_database) + : source_tree_(source_tree), + fallback_database_(fallback_database), + error_collector_(nullptr), + using_validation_error_collector_(false), + validation_error_collector_(this) {} SourceTreeDescriptorDatabase::~SourceTreeDescriptorDatabase() {} -bool SourceTreeDescriptorDatabase::FindFileByName( - const string& filename, FileDescriptorProto* output) { +bool SourceTreeDescriptorDatabase::FindFileByName(const std::string& filename, + FileDescriptorProto* output) { std::unique_ptr input(source_tree_->Open(filename)); if (input == NULL) { + if (fallback_database_ != nullptr && + fallback_database_->FindFileByName(filename, output)) { + return true; + } if (error_collector_ != NULL) { error_collector_->AddError(filename, -1, 0, source_tree_->GetLastErrorMessage()); @@ -152,17 +163,16 @@ bool SourceTreeDescriptorDatabase::FindFileByName( // Parse it. output->set_name(filename); - return parser.Parse(&tokenizer, output) && - !file_error_collector.had_errors(); + return parser.Parse(&tokenizer, output) && !file_error_collector.had_errors(); } bool SourceTreeDescriptorDatabase::FindFileContainingSymbol( - const string& symbol_name, FileDescriptorProto* output) { + const std::string& symbol_name, FileDescriptorProto* output) { return false; } bool SourceTreeDescriptorDatabase::FindFileContainingExtension( - const string& containing_type, int field_number, + const std::string& containing_type, int field_number, FileDescriptorProto* output) { return false; } @@ -170,35 +180,41 @@ bool SourceTreeDescriptorDatabase::FindFileContainingExtension( // ------------------------------------------------------------------- SourceTreeDescriptorDatabase::ValidationErrorCollector:: -ValidationErrorCollector(SourceTreeDescriptorDatabase* owner) - : owner_(owner) {} + ValidationErrorCollector(SourceTreeDescriptorDatabase* owner) + : owner_(owner) {} SourceTreeDescriptorDatabase::ValidationErrorCollector:: -~ValidationErrorCollector() {} + ~ValidationErrorCollector() {} void SourceTreeDescriptorDatabase::ValidationErrorCollector::AddError( - const string& filename, - const string& element_name, - const Message* descriptor, - ErrorLocation location, - const string& message) { + const std::string& filename, const std::string& element_name, + const Message* descriptor, ErrorLocation location, + const std::string& message) { if (owner_->error_collector_ == NULL) return; int line, column; - owner_->source_locations_.Find(descriptor, location, &line, &column); + if (location == DescriptorPool::ErrorCollector::IMPORT) { + owner_->source_locations_.FindImport(descriptor, element_name, &line, + &column); + } else { + owner_->source_locations_.Find(descriptor, location, &line, &column); + } owner_->error_collector_->AddError(filename, line, column, message); } void SourceTreeDescriptorDatabase::ValidationErrorCollector::AddWarning( - const string& filename, - const string& element_name, - const Message* descriptor, - ErrorLocation location, - const string& message) { + const std::string& filename, const std::string& element_name, + const Message* descriptor, ErrorLocation location, + const std::string& message) { if (owner_->error_collector_ == NULL) return; int line, column; - owner_->source_locations_.Find(descriptor, location, &line, &column); + if (location == DescriptorPool::ErrorCollector::IMPORT) { + owner_->source_locations_.FindImport(descriptor, element_name, &line, + &column); + } else { + owner_->source_locations_.Find(descriptor, location, &line, &column); + } owner_->error_collector_->AddWarning(filename, line, column, message); } @@ -206,19 +222,19 @@ void SourceTreeDescriptorDatabase::ValidationErrorCollector::AddWarning( Importer::Importer(SourceTree* source_tree, MultiFileErrorCollector* error_collector) - : database_(source_tree), - pool_(&database_, database_.GetValidationErrorCollector()) { + : database_(source_tree), + pool_(&database_, database_.GetValidationErrorCollector()) { pool_.EnforceWeakDependencies(true); database_.RecordErrorsTo(error_collector); } Importer::~Importer() {} -const FileDescriptor* Importer::Import(const string& filename) { +const FileDescriptor* Importer::Import(const std::string& filename) { return pool_.FindFileByName(filename); } -void Importer::AddUnusedImportTrackFile(const string& file_name) { +void Importer::AddUnusedImportTrackFile(const std::string& file_name) { pool_.AddUnusedImportTrackFile(file_name); } @@ -231,15 +247,13 @@ void Importer::ClearUnusedImportTrackFiles() { SourceTree::~SourceTree() {} -string SourceTree::GetLastErrorMessage() { - return "File not found."; -} +std::string SourceTree::GetLastErrorMessage() { return "File not found."; } DiskSourceTree::DiskSourceTree() {} DiskSourceTree::~DiskSourceTree() {} -static inline char LastChar(const string& str) { +static inline char LastChar(const std::string& str) { return str[str.size() - 1]; } @@ -262,7 +276,7 @@ static inline char LastChar(const string& str) { // then if foo/bar is a symbolic link, foo/bar/baz.proto will canonicalize // to a path which does not appear to be under foo, and thus the compiler // will complain that baz.proto is not inside the --proto_path. -static string CanonicalizePath(string path) { +static std::string CanonicalizePath(std::string path) { #ifdef _WIN32 // The Win32 API accepts forward slashes as a path delimiter even though // backslashes are standard. Let's avoid confusion and use only forward @@ -275,8 +289,8 @@ static string CanonicalizePath(string path) { } #endif - std::vector canonical_parts; - std::vector parts = Split( + std::vector canonical_parts; + std::vector parts = Split( path, "/", true); // Note: Removes empty parts. for (int i = 0; i < parts.size(); i++) { if (parts[i] == ".") { @@ -285,20 +299,20 @@ static string CanonicalizePath(string path) { canonical_parts.push_back(parts[i]); } } - string result = Join(canonical_parts, "/"); + std::string result = Join(canonical_parts, "/"); if (!path.empty() && path[0] == '/') { // Restore leading slash. result = '/' + result; } - if (!path.empty() && LastChar(path) == '/' && - !result.empty() && LastChar(result) != '/') { + if (!path.empty() && LastChar(path) == '/' && !result.empty() && + LastChar(result) != '/') { // Restore trailing slash. result += '/'; } return result; } -static inline bool ContainsParentReference(const string& path) { +static inline bool ContainsParentReference(const std::string& path) { return path == ".." || HasPrefixString(path, "../") || HasSuffixString(path, "/..") || path.find("/../") != string::npos; } @@ -320,10 +334,9 @@ static inline bool ContainsParentReference(const string& path) { // assert(!ApplyMapping("foo/bar", "baz", "qux", &result)); // assert(!ApplyMapping("foo/bar", "baz", "qux", &result)); // assert(!ApplyMapping("foobar", "foo", "baz", &result)); -static bool ApplyMapping(const string& filename, - const string& old_prefix, - const string& new_prefix, - string* result) { +static bool ApplyMapping(const std::string& filename, + const std::string& old_prefix, + const std::string& new_prefix, std::string* result) { if (old_prefix.empty()) { // old_prefix matches any relative path. if (ContainsParentReference(filename)) { @@ -359,7 +372,7 @@ static bool ApplyMapping(const string& filename, if (after_prefix_start != -1) { // Yep. So the prefixes are directories and the filename is a file // inside them. - string after_prefix = filename.substr(after_prefix_start); + std::string after_prefix = filename.substr(after_prefix_start); if (ContainsParentReference(after_prefix)) { // We do not allow the file name to use "..". return false; @@ -375,18 +388,17 @@ static bool ApplyMapping(const string& filename, return false; } -void DiskSourceTree::MapPath(const string& virtual_path, - const string& disk_path) { +void DiskSourceTree::MapPath(const std::string& virtual_path, + const std::string& disk_path) { mappings_.push_back(Mapping(virtual_path, CanonicalizePath(disk_path))); } DiskSourceTree::DiskFileToVirtualFileResult -DiskSourceTree::DiskFileToVirtualFile( - const string& disk_file, - string* virtual_file, - string* shadowing_disk_file) { +DiskSourceTree::DiskFileToVirtualFile(const std::string& disk_file, + std::string* virtual_file, + std::string* shadowing_disk_file) { int mapping_index = -1; - string canonical_disk_file = CanonicalizePath(disk_file); + std::string canonical_disk_file = CanonicalizePath(disk_file); for (int i = 0; i < mappings_.size(); i++) { // Apply the mapping in reverse. @@ -426,36 +438,36 @@ DiskSourceTree::DiskFileToVirtualFile( return SUCCESS; } -bool DiskSourceTree::VirtualFileToDiskFile(const string& virtual_file, - string* disk_file) { +bool DiskSourceTree::VirtualFileToDiskFile(const std::string& virtual_file, + std::string* disk_file) { std::unique_ptr stream( OpenVirtualFile(virtual_file, disk_file)); return stream != NULL; } -io::ZeroCopyInputStream* DiskSourceTree::Open(const string& filename) { +io::ZeroCopyInputStream* DiskSourceTree::Open(const std::string& filename) { return OpenVirtualFile(filename, NULL); } -string DiskSourceTree::GetLastErrorMessage() { +std::string DiskSourceTree::GetLastErrorMessage() { return last_error_message_; } io::ZeroCopyInputStream* DiskSourceTree::OpenVirtualFile( - const string& virtual_file, - string* disk_file) { + const std::string& virtual_file, std::string* disk_file) { if (virtual_file != CanonicalizePath(virtual_file) || ContainsParentReference(virtual_file)) { // We do not allow importing of paths containing things like ".." or // consecutive slashes since the compiler expects files to be uniquely // identified by file name. - last_error_message_ = "Backslashes, consecutive slashes, \".\", or \"..\" " - "are not allowed in the virtual path"; + last_error_message_ = + "Backslashes, consecutive slashes, \".\", or \"..\" " + "are not allowed in the virtual path"; return NULL; } for (int i = 0; i < mappings_.size(); i++) { - string temp_disk_file; + std::string temp_disk_file; if (ApplyMapping(virtual_file, mappings_[i].virtual_path, mappings_[i].disk_path, &temp_disk_file)) { io::ZeroCopyInputStream* stream = OpenDiskFile(temp_disk_file); @@ -468,8 +480,8 @@ io::ZeroCopyInputStream* DiskSourceTree::OpenVirtualFile( if (errno == EACCES) { // The file exists but is not readable. - last_error_message_ = "Read access is denied for file: " + - temp_disk_file; + last_error_message_ = + "Read access is denied for file: " + temp_disk_file; return NULL; } } @@ -479,7 +491,7 @@ io::ZeroCopyInputStream* DiskSourceTree::OpenVirtualFile( } io::ZeroCopyInputStream* DiskSourceTree::OpenDiskFile( - const string& filename) { + const std::string& filename) { int file_descriptor; do { file_descriptor = open(filename.c_str(), O_RDONLY); diff --git a/third_party/protobuf/src/google/protobuf/compiler/importer.h b/third_party/protobuf/src/google/protobuf/compiler/importer.h index a4ffcf87..1a0b47ae 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/importer.h +++ b/third_party/protobuf/src/google/protobuf/compiler/importer.h @@ -37,18 +37,22 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_IMPORTER_H__ #define GOOGLE_PROTOBUF_COMPILER_IMPORTER_H__ -#include -#include #include +#include #include +#include +#include #include #include -#include + +#include namespace google { namespace protobuf { -namespace io { class ZeroCopyInputStream; } +namespace io { +class ZeroCopyInputStream; +} namespace compiler { @@ -73,9 +77,14 @@ class DiskSourceTree; // // Note: This class does not implement FindFileContainingSymbol() or // FindFileContainingExtension(); these will always return false. -class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabase { +class PROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabase { public: SourceTreeDescriptorDatabase(SourceTree* source_tree); + + // If non-NULL, fallback_database will be checked if a file doesn't exist in + // the specified source_tree. + SourceTreeDescriptorDatabase(SourceTree* source_tree, + DescriptorDatabase* fallback_database); ~SourceTreeDescriptorDatabase(); // Instructs the SourceTreeDescriptorDatabase to report any parse errors @@ -96,36 +105,36 @@ class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabas } // implements DescriptorDatabase ----------------------------------- - bool FindFileByName(const string& filename, FileDescriptorProto* output); - bool FindFileContainingSymbol(const string& symbol_name, - FileDescriptorProto* output); - bool FindFileContainingExtension(const string& containing_type, + bool FindFileByName(const std::string& filename, + FileDescriptorProto* output) override; + bool FindFileContainingSymbol(const std::string& symbol_name, + FileDescriptorProto* output) override; + bool FindFileContainingExtension(const std::string& containing_type, int field_number, - FileDescriptorProto* output); + FileDescriptorProto* output) override; private: class SingleFileErrorCollector; SourceTree* source_tree_; + DescriptorDatabase* fallback_database_; MultiFileErrorCollector* error_collector_; - class LIBPROTOBUF_EXPORT ValidationErrorCollector : public DescriptorPool::ErrorCollector { + class PROTOBUF_EXPORT ValidationErrorCollector + : public DescriptorPool::ErrorCollector { public: ValidationErrorCollector(SourceTreeDescriptorDatabase* owner); ~ValidationErrorCollector(); // implements ErrorCollector --------------------------------------- - void AddError(const string& filename, - const string& element_name, - const Message* descriptor, - ErrorLocation location, - const string& message); + void AddError(const std::string& filename, const std::string& element_name, + const Message* descriptor, ErrorLocation location, + const std::string& message) override; - virtual void AddWarning(const string& filename, - const string& element_name, - const Message* descriptor, - ErrorLocation location, - const string& message); + void AddWarning(const std::string& filename, + const std::string& element_name, const Message* descriptor, + ErrorLocation location, + const std::string& message) override; private: SourceTreeDescriptorDatabase* owner_; @@ -145,10 +154,9 @@ class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabas // You may find that SourceTreeDescriptorDatabase is more flexible. // // TODO(kenton): I feel like this class is not well-named. -class LIBPROTOBUF_EXPORT Importer { +class PROTOBUF_EXPORT Importer { public: - Importer(SourceTree* source_tree, - MultiFileErrorCollector* error_collector); + Importer(SourceTree* source_tree, MultiFileErrorCollector* error_collector); ~Importer(); // Import the given file and build a FileDescriptor representing it. If @@ -164,15 +172,13 @@ class LIBPROTOBUF_EXPORT Importer { // you want to see errors for the same files repeatedly, you can use a // separate Importer object to import each one (but use the same // DescriptorPool so that they can be cross-linked). - const FileDescriptor* Import(const string& filename); + const FileDescriptor* Import(const std::string& filename); // The DescriptorPool in which all imported FileDescriptors and their // contents are stored. - inline const DescriptorPool* pool() const { - return &pool_; - } + inline const DescriptorPool* pool() const { return &pool_; } - void AddUnusedImportTrackFile(const string& file_name); + void AddUnusedImportTrackFile(const std::string& file_name); void ClearUnusedImportTrackFiles(); @@ -185,18 +191,18 @@ class LIBPROTOBUF_EXPORT Importer { // If the importer encounters problems while trying to import the proto files, // it reports them to a MultiFileErrorCollector. -class LIBPROTOBUF_EXPORT MultiFileErrorCollector { +class PROTOBUF_EXPORT MultiFileErrorCollector { public: inline MultiFileErrorCollector() {} virtual ~MultiFileErrorCollector(); // Line and column numbers are zero-based. A line number of -1 indicates // an error with the entire file (e.g. "not found"). - virtual void AddError(const string& filename, int line, int column, - const string& message) = 0; + virtual void AddError(const std::string& filename, int line, int column, + const std::string& message) = 0; - virtual void AddWarning(const string& filename, int line, int column, - const string& message) {} + virtual void AddWarning(const std::string& filename, int line, int column, + const std::string& message) {} private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MultiFileErrorCollector); @@ -206,7 +212,7 @@ class LIBPROTOBUF_EXPORT MultiFileErrorCollector { // Used by the default implementation of Importer to resolve import statements // Most users will probably want to use the DiskSourceTree implementation, // below. -class LIBPROTOBUF_EXPORT SourceTree { +class PROTOBUF_EXPORT SourceTree { public: inline SourceTree() {} virtual ~SourceTree(); @@ -215,14 +221,14 @@ class LIBPROTOBUF_EXPORT SourceTree { // found. The caller takes ownership of the returned object. The filename // must be a path relative to the root of the source tree and must not // contain "." or ".." components. - virtual io::ZeroCopyInputStream* Open(const string& filename) = 0; + virtual io::ZeroCopyInputStream* Open(const std::string& filename) = 0; // If Open() returns NULL, calling this method immediately will return an // description of the error. // Subclasses should implement this method and return a meaningful value for // better error reporting. // TODO(xiaofeng): change this to a pure virtual function. - virtual string GetLastErrorMessage(); + virtual std::string GetLastErrorMessage(); private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SourceTree); @@ -231,7 +237,7 @@ class LIBPROTOBUF_EXPORT SourceTree { // An implementation of SourceTree which loads files from locations on disk. // Multiple mappings can be set up to map locations in the DiskSourceTree to // locations in the physical filesystem. -class LIBPROTOBUF_EXPORT DiskSourceTree : public SourceTree { +class PROTOBUF_EXPORT DiskSourceTree : public SourceTree { public: DiskSourceTree(); ~DiskSourceTree(); @@ -252,7 +258,7 @@ class LIBPROTOBUF_EXPORT DiskSourceTree : public SourceTree { // // disk_path may be an absolute path or relative to the current directory, // just like a path you'd pass to open(). - void MapPath(const string& virtual_path, const string& disk_path); + void MapPath(const std::string& virtual_path, const std::string& disk_path); // Return type for DiskFileToVirtualFile(). enum DiskFileToVirtualFileResult { @@ -282,46 +288,48 @@ class LIBPROTOBUF_EXPORT DiskSourceTree : public SourceTree { // it is not useful. // * NO_MAPPING: Indicates that no mapping was found which contains this // file. - DiskFileToVirtualFileResult - DiskFileToVirtualFile(const string& disk_file, - string* virtual_file, - string* shadowing_disk_file); + DiskFileToVirtualFileResult DiskFileToVirtualFile( + const std::string& disk_file, std::string* virtual_file, + std::string* shadowing_disk_file); // Given a virtual path, find the path to the file on disk. // Return true and update disk_file with the on-disk path if the file exists. // Return false and leave disk_file untouched if the file doesn't exist. - bool VirtualFileToDiskFile(const string& virtual_file, string* disk_file); + bool VirtualFileToDiskFile(const std::string& virtual_file, + std::string* disk_file); // implements SourceTree ------------------------------------------- - virtual io::ZeroCopyInputStream* Open(const string& filename); + io::ZeroCopyInputStream* Open(const std::string& filename) override; - virtual string GetLastErrorMessage(); + std::string GetLastErrorMessage() override; private: struct Mapping { - string virtual_path; - string disk_path; + std::string virtual_path; + std::string disk_path; - inline Mapping(const string& virtual_path_param, - const string& disk_path_param) - : virtual_path(virtual_path_param), disk_path(disk_path_param) {} + inline Mapping(const std::string& virtual_path_param, + const std::string& disk_path_param) + : virtual_path(virtual_path_param), disk_path(disk_path_param) {} }; std::vector mappings_; - string last_error_message_; + std::string last_error_message_; // Like Open(), but returns the on-disk path in disk_file if disk_file is // non-NULL and the file could be successfully opened. - io::ZeroCopyInputStream* OpenVirtualFile(const string& virtual_file, - string* disk_file); + io::ZeroCopyInputStream* OpenVirtualFile(const std::string& virtual_file, + std::string* disk_file); // Like Open() but given the actual on-disk path. - io::ZeroCopyInputStream* OpenDiskFile(const string& filename); + io::ZeroCopyInputStream* OpenDiskFile(const std::string& filename); GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DiskSourceTree); }; } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_IMPORTER_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/importer_unittest.cc b/third_party/protobuf/src/google/protobuf/compiler/importer_unittest.cc index 73bef3f4..82ffc0fc 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/importer_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/importer_unittest.cc @@ -34,8 +34,8 @@ #include -#include #include +#include #include #include @@ -56,7 +56,7 @@ namespace compiler { namespace { -bool FileExists(const string& path) { +bool FileExists(const std::string& path) { return File::Exists(path); } @@ -68,20 +68,20 @@ class MockErrorCollector : public MultiFileErrorCollector { MockErrorCollector() {} ~MockErrorCollector() {} - string text_; - string warning_text_; + std::string text_; + std::string warning_text_; // implements ErrorCollector --------------------------------------- - void AddError(const string& filename, int line, int column, - const string& message) { - strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", - filename, line, column, message); + void AddError(const std::string& filename, int line, int column, + const std::string& message) { + strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", filename, line, + column, message); } - void AddWarning(const string& filename, int line, int column, - const string& message) { - strings::SubstituteAndAppend(&warning_text_, "$0:$1:$2: $3\n", - filename, line, column, message); + void AddWarning(const std::string& filename, int line, int column, + const std::string& message) { + strings::SubstituteAndAppend(&warning_text_, "$0:$1:$2: $3\n", filename, + line, column, message); } }; @@ -93,12 +93,12 @@ class MockSourceTree : public SourceTree { MockSourceTree() {} ~MockSourceTree() {} - void AddFile(const string& name, const char* contents) { + void AddFile(const std::string& name, const char* contents) { files_[name] = contents; } // implements SourceTree ------------------------------------------- - io::ZeroCopyInputStream* Open(const string& filename) { + io::ZeroCopyInputStream* Open(const std::string& filename) { const char* contents = FindPtrOrNull(files_, filename); if (contents == NULL) { return NULL; @@ -107,28 +107,24 @@ class MockSourceTree : public SourceTree { } } - string GetLastErrorMessage() { - return "File not found."; - } + std::string GetLastErrorMessage() { return "File not found."; } private: - hash_map files_; + std::unordered_map files_; }; // =================================================================== class ImporterTest : public testing::Test { protected: - ImporterTest() - : importer_(&source_tree_, &error_collector_) {} + ImporterTest() : importer_(&source_tree_, &error_collector_) {} - void AddFile(const string& filename, const char* text) { + void AddFile(const std::string& filename, const char* text) { source_tree_.AddFile(filename, text); } // Return the collected error text - string error() const { return error_collector_.text_; } - string warning() const { return error_collector_.warning_text_; } + std::string warning() const { return error_collector_.warning_text_; } MockErrorCollector error_collector_; MockSourceTree source_tree_; @@ -138,8 +134,8 @@ class ImporterTest : public testing::Test { TEST_F(ImporterTest, Import) { // Test normal importing. AddFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); + "syntax = \"proto2\";\n" + "message Foo {}\n"); const FileDescriptor* file = importer_.Import("foo.proto"); EXPECT_EQ("", error_collector_.text_); @@ -155,14 +151,14 @@ TEST_F(ImporterTest, Import) { TEST_F(ImporterTest, ImportNested) { // Test that importing a file which imports another file works. AddFile("foo.proto", - "syntax = \"proto2\";\n" - "import \"bar.proto\";\n" - "message Foo {\n" - " optional Bar bar = 1;\n" - "}\n"); + "syntax = \"proto2\";\n" + "import \"bar.proto\";\n" + "message Foo {\n" + " optional Bar bar = 1;\n" + "}\n"); AddFile("bar.proto", - "syntax = \"proto2\";\n" - "message Bar {}\n"); + "syntax = \"proto2\";\n" + "message Bar {}\n"); // Note that both files are actually parsed by the first call to Import() // here, since foo.proto imports bar.proto. The second call just returns @@ -192,42 +188,73 @@ TEST_F(ImporterTest, ImportNested) { TEST_F(ImporterTest, FileNotFound) { // Error: Parsing a file that doesn't exist. EXPECT_TRUE(importer_.Import("foo.proto") == NULL); - EXPECT_EQ( - "foo.proto:-1:0: File not found.\n", - error_collector_.text_); + EXPECT_EQ("foo.proto:-1:0: File not found.\n", error_collector_.text_); } TEST_F(ImporterTest, ImportNotFound) { // Error: Importing a file that doesn't exist. AddFile("foo.proto", - "syntax = \"proto2\";\n" - "import \"bar.proto\";\n"); + "syntax = \"proto2\";\n" + "import \"bar.proto\";\n"); EXPECT_TRUE(importer_.Import("foo.proto") == NULL); EXPECT_EQ( - "bar.proto:-1:0: File not found.\n" - "foo.proto:-1:0: Import \"bar.proto\" was not found or had errors.\n", - error_collector_.text_); + "bar.proto:-1:0: File not found.\n" + "foo.proto:1:0: Import \"bar.proto\" was not found or had errors.\n", + error_collector_.text_); } TEST_F(ImporterTest, RecursiveImport) { // Error: Recursive import. AddFile("recursive1.proto", - "syntax = \"proto2\";\n" - "import \"recursive2.proto\";\n"); + "syntax = \"proto2\";\n" + "\n" + "import \"recursive2.proto\";\n"); AddFile("recursive2.proto", - "syntax = \"proto2\";\n" - "import \"recursive1.proto\";\n"); + "syntax = \"proto2\";\n" + "import \"recursive1.proto\";\n"); EXPECT_TRUE(importer_.Import("recursive1.proto") == NULL); EXPECT_EQ( - "recursive1.proto:-1:0: File recursively imports itself: recursive1.proto " + "recursive1.proto:2:0: File recursively imports itself: " + "recursive1.proto " "-> recursive2.proto -> recursive1.proto\n" - "recursive2.proto:-1:0: Import \"recursive1.proto\" was not found " + "recursive2.proto:1:0: Import \"recursive1.proto\" was not found " "or had errors.\n" - "recursive1.proto:-1:0: Import \"recursive2.proto\" was not found " + "recursive1.proto:2:0: Import \"recursive2.proto\" was not found " "or had errors.\n", - error_collector_.text_); + error_collector_.text_); +} + +TEST_F(ImporterTest, RecursiveImportSelf) { + // Error: Recursive import. + AddFile("recursive.proto", + "syntax = \"proto2\";\n" + "\n" + "import \"recursive.proto\";\n"); + + EXPECT_TRUE(importer_.Import("recursive.proto") == nullptr); + EXPECT_EQ( + "recursive.proto:2:0: File recursively imports itself: " + "recursive.proto -> recursive.proto\n", + error_collector_.text_); +} + +TEST_F(ImporterTest, LiteRuntimeImport) { + // Error: Recursive import. + AddFile("bar.proto", + "syntax = \"proto2\";\n" + "option optimize_for = LITE_RUNTIME;\n"); + AddFile("foo.proto", + "syntax = \"proto2\";\n" + "import \"bar.proto\";\n"); + + EXPECT_TRUE(importer_.Import("foo.proto") == nullptr); + EXPECT_EQ( + "foo.proto:1:0: Files that do not use optimize_for = LITE_RUNTIME " + "cannot import files which do use this option. This file is not " + "lite, but it imports \"bar.proto\" which is.\n", + error_collector_.text_); } @@ -255,22 +282,22 @@ class DiskSourceTreeTest : public testing::Test { } } - void AddFile(const string& filename, const char* contents) { + void AddFile(const std::string& filename, const char* contents) { GOOGLE_CHECK_OK(File::SetContents(filename, contents, true)); } - void AddSubdir(const string& dirname) { + void AddSubdir(const std::string& dirname) { GOOGLE_CHECK_OK(File::CreateDir(dirname, 0777)); } - void ExpectFileContents(const string& filename, + void ExpectFileContents(const std::string& filename, const char* expected_contents) { std::unique_ptr input(source_tree_.Open(filename)); ASSERT_FALSE(input == NULL); // Read all the data from the file. - string file_contents; + std::string file_contents; const void* data; int size; while (input->Next(&data, &size)) { @@ -280,8 +307,8 @@ class DiskSourceTreeTest : public testing::Test { EXPECT_EQ(expected_contents, file_contents); } - void ExpectCannotOpenFile(const string& filename, - const string& error_message) { + void ExpectCannotOpenFile(const std::string& filename, + const std::string& error_message) { std::unique_ptr input(source_tree_.Open(filename)); EXPECT_TRUE(input == NULL); EXPECT_EQ(error_message, source_tree_.GetLastErrorMessage()); @@ -290,7 +317,7 @@ class DiskSourceTreeTest : public testing::Test { DiskSourceTree source_tree_; // Paths of two on-disk directories to use during the test. - std::vector dirnames_; + std::vector dirnames_; }; TEST_F(DiskSourceTreeTest, MapRoot) { @@ -394,27 +421,27 @@ TEST_F(DiskSourceTreeTest, DiskFileToVirtualFile) { source_tree_.MapPath("bar", dirnames_[0]); source_tree_.MapPath("bar", dirnames_[1]); - string virtual_file; - string shadowing_disk_file; + std::string virtual_file; + std::string shadowing_disk_file; EXPECT_EQ(DiskSourceTree::NO_MAPPING, - source_tree_.DiskFileToVirtualFile( - "/foo", &virtual_file, &shadowing_disk_file)); + source_tree_.DiskFileToVirtualFile("/foo", &virtual_file, + &shadowing_disk_file)); EXPECT_EQ(DiskSourceTree::SHADOWED, - source_tree_.DiskFileToVirtualFile( - dirnames_[1] + "/foo", &virtual_file, &shadowing_disk_file)); + source_tree_.DiskFileToVirtualFile( + dirnames_[1] + "/foo", &virtual_file, &shadowing_disk_file)); EXPECT_EQ("bar/foo", virtual_file); EXPECT_EQ(dirnames_[0] + "/foo", shadowing_disk_file); EXPECT_EQ(DiskSourceTree::CANNOT_OPEN, - source_tree_.DiskFileToVirtualFile( - dirnames_[1] + "/baz", &virtual_file, &shadowing_disk_file)); + source_tree_.DiskFileToVirtualFile( + dirnames_[1] + "/baz", &virtual_file, &shadowing_disk_file)); EXPECT_EQ("bar/baz", virtual_file); EXPECT_EQ(DiskSourceTree::SUCCESS, - source_tree_.DiskFileToVirtualFile( - dirnames_[0] + "/foo", &virtual_file, &shadowing_disk_file)); + source_tree_.DiskFileToVirtualFile( + dirnames_[0] + "/foo", &virtual_file, &shadowing_disk_file)); EXPECT_EQ("bar/foo", virtual_file); } @@ -428,60 +455,60 @@ TEST_F(DiskSourceTreeTest, DiskFileToVirtualFileCanonicalization) { source_tree_.MapPath("", "/qux"); source_tree_.MapPath("dir5", "/quux/"); - string virtual_file; - string shadowing_disk_file; + std::string virtual_file; + std::string shadowing_disk_file; // "../.." should not be considered to be under "..". EXPECT_EQ(DiskSourceTree::NO_MAPPING, - source_tree_.DiskFileToVirtualFile( - "../../baz", &virtual_file, &shadowing_disk_file)); + source_tree_.DiskFileToVirtualFile("../../baz", &virtual_file, + &shadowing_disk_file)); // "/foo" is not mapped (it should not be misintepreted as being under "."). EXPECT_EQ(DiskSourceTree::NO_MAPPING, - source_tree_.DiskFileToVirtualFile( - "/foo", &virtual_file, &shadowing_disk_file)); + source_tree_.DiskFileToVirtualFile("/foo", &virtual_file, + &shadowing_disk_file)); #ifdef WIN32 // "C:\foo" is not mapped (it should not be misintepreted as being under "."). EXPECT_EQ(DiskSourceTree::NO_MAPPING, - source_tree_.DiskFileToVirtualFile( - "C:\\foo", &virtual_file, &shadowing_disk_file)); + source_tree_.DiskFileToVirtualFile("C:\\foo", &virtual_file, + &shadowing_disk_file)); #endif // WIN32 // But "../baz" should be. EXPECT_EQ(DiskSourceTree::CANNOT_OPEN, - source_tree_.DiskFileToVirtualFile( - "../baz", &virtual_file, &shadowing_disk_file)); + source_tree_.DiskFileToVirtualFile("../baz", &virtual_file, + &shadowing_disk_file)); EXPECT_EQ("dir1/baz", virtual_file); // "../../foo/baz" is under "../../foo". EXPECT_EQ(DiskSourceTree::CANNOT_OPEN, - source_tree_.DiskFileToVirtualFile( - "../../foo/baz", &virtual_file, &shadowing_disk_file)); + source_tree_.DiskFileToVirtualFile("../../foo/baz", &virtual_file, + &shadowing_disk_file)); EXPECT_EQ("dir2/baz", virtual_file); // "foo/./bar/baz" is under "./foo/bar/.". EXPECT_EQ(DiskSourceTree::CANNOT_OPEN, - source_tree_.DiskFileToVirtualFile( - "foo/bar/baz", &virtual_file, &shadowing_disk_file)); + source_tree_.DiskFileToVirtualFile("foo/bar/baz", &virtual_file, + &shadowing_disk_file)); EXPECT_EQ("dir3/baz", virtual_file); // "bar" is under ".". EXPECT_EQ(DiskSourceTree::CANNOT_OPEN, - source_tree_.DiskFileToVirtualFile( - "bar", &virtual_file, &shadowing_disk_file)); + source_tree_.DiskFileToVirtualFile("bar", &virtual_file, + &shadowing_disk_file)); EXPECT_EQ("dir4/bar", virtual_file); // "/qux/baz" is under "/qux". EXPECT_EQ(DiskSourceTree::CANNOT_OPEN, - source_tree_.DiskFileToVirtualFile( - "/qux/baz", &virtual_file, &shadowing_disk_file)); + source_tree_.DiskFileToVirtualFile("/qux/baz", &virtual_file, + &shadowing_disk_file)); EXPECT_EQ("baz", virtual_file); // "/quux/bar" is under "/quux". EXPECT_EQ(DiskSourceTree::CANNOT_OPEN, - source_tree_.DiskFileToVirtualFile( - "/quux/bar", &virtual_file, &shadowing_disk_file)); + source_tree_.DiskFileToVirtualFile("/quux/bar", &virtual_file, + &shadowing_disk_file)); EXPECT_EQ("dir5/bar", virtual_file); } @@ -495,14 +522,14 @@ TEST_F(DiskSourceTreeTest, VirtualFileToDiskFile) { source_tree_.MapPath("bar", dirnames_[1]); // Existent files, shadowed and non-shadowed case. - string disk_file; + std::string disk_file; EXPECT_TRUE(source_tree_.VirtualFileToDiskFile("bar/foo", &disk_file)); EXPECT_EQ(dirnames_[0] + "/foo", disk_file); EXPECT_TRUE(source_tree_.VirtualFileToDiskFile("bar/quux", &disk_file)); EXPECT_EQ(dirnames_[1] + "/quux", disk_file); // Nonexistent file in existent directory and vice versa. - string not_touched = "not touched"; + std::string not_touched = "not touched"; EXPECT_FALSE(source_tree_.VirtualFileToDiskFile("bar/baz", ¬_touched)); EXPECT_EQ("not touched", not_touched); EXPECT_FALSE(source_tree_.VirtualFileToDiskFile("baz/foo", ¬_touched)); diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_context.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_context.cc index 2528c2d1..778d3ba1 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_context.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_context.cc @@ -35,6 +35,7 @@ #include #include #include + #include namespace google { @@ -47,8 +48,7 @@ Context::Context(const FileDescriptor* file, const Options& options) InitializeFieldGeneratorInfo(file); } -Context::~Context() { -} +Context::~Context() {} ClassNameResolver* Context::GetNameResolver() const { return name_resolver_.get(); @@ -58,9 +58,9 @@ namespace { // Whether two fields have conflicting accessors (assuming name1 and name2 // are different). name1 and name2 are field1 and field2's camel-case name // respectively. -bool IsConflicting(const FieldDescriptor* field1, const string& name1, - const FieldDescriptor* field2, const string& name2, - string* info) { +bool IsConflicting(const FieldDescriptor* field1, const std::string& name1, + const FieldDescriptor* field2, const std::string& name2, + std::string* info) { if (field1->is_repeated()) { if (field2->is_repeated()) { // Both fields are repeated. @@ -128,13 +128,13 @@ void Context::InitializeFieldGeneratorInfoForFields( // Find out all fields that conflict with some other field in the same // message. std::vector is_conflict(fields.size()); - std::vector conflict_reason(fields.size()); + std::vector conflict_reason(fields.size()); for (int i = 0; i < fields.size(); ++i) { const FieldDescriptor* field = fields[i]; - const string& name = UnderscoresToCapitalizedCamelCase(field); + const std::string& name = UnderscoresToCapitalizedCamelCase(field); for (int j = i + 1; j < fields.size(); ++j) { const FieldDescriptor* other = fields[j]; - const string& other_name = UnderscoresToCapitalizedCamelCase(other); + const std::string& other_name = UnderscoresToCapitalizedCamelCase(other); if (name == other_name) { is_conflict[i] = is_conflict[j] = true; conflict_reason[i] = conflict_reason[j] = @@ -159,8 +159,8 @@ void Context::InitializeFieldGeneratorInfoForFields( // For fields conflicting with some other fields, we append the field // number to their field names in generated code to avoid conflicts. if (is_conflict[i]) { - info.name += SimpleItoa(field->number()); - info.capitalized_name += SimpleItoa(field->number()); + info.name += StrCat(field->number()); + info.capitalized_name += StrCat(field->number()); info.disambiguated_reason = conflict_reason[i]; } field_generator_info_map_[field] = info; diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_context.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_context.h index 9de7415a..3fa6af17 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_context.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_context.h @@ -40,18 +40,20 @@ namespace google { namespace protobuf { - class FileDescriptor; - class FieldDescriptor; - class OneofDescriptor; - class Descriptor; - class EnumDescriptor; - namespace compiler { - namespace java { - class ClassNameResolver; // name_resolver.h - } - } +class FileDescriptor; +class FieldDescriptor; +class OneofDescriptor; +class Descriptor; +class EnumDescriptor; +namespace compiler { +namespace java { +class ClassNameResolver; // name_resolver.h +} +} // namespace compiler } // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { @@ -106,6 +108,6 @@ class Context { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_CONTEXT_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_doc_comment.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_doc_comment.cc index 59c04ad4..29447ac0 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_doc_comment.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_doc_comment.cc @@ -44,13 +44,13 @@ namespace protobuf { namespace compiler { namespace java { -string EscapeJavadoc(const string& input) { - string result; +std::string EscapeJavadoc(const std::string& input) { + std::string result; result.reserve(input.size() * 2); char prev = '*'; - for (string::size_type i = 0; i < input.size(); i++) { + for (std::string::size_type i = 0; i < input.size(); i++) { char c = input[i]; switch (c) { case '*': @@ -102,10 +102,11 @@ string EscapeJavadoc(const string& input) { return result; } -static void WriteDocCommentBodyForLocation( - io::Printer* printer, const SourceLocation& location) { - string comments = location.leading_comments.empty() ? - location.trailing_comments : location.leading_comments; +static void WriteDocCommentBodyForLocation(io::Printer* printer, + const SourceLocation& location) { + std::string comments = location.leading_comments.empty() + ? location.trailing_comments + : location.leading_comments; if (!comments.empty()) { // TODO(kenton): Ideally we should parse the comment text as Markdown and // write it back as HTML, but this requires a Markdown parser. For now @@ -115,7 +116,7 @@ static void WriteDocCommentBodyForLocation( // HTML-escape them so that they don't accidentally close the doc comment. comments = EscapeJavadoc(comments); - std::vector lines = Split(comments, "\n"); + std::vector lines = Split(comments, "\n"); while (!lines.empty() && lines.back().empty()) { lines.pop_back(); } @@ -138,19 +139,19 @@ static void WriteDocCommentBodyForLocation( } template -static void WriteDocCommentBody( - io::Printer* printer, const DescriptorType* descriptor) { +static void WriteDocCommentBody(io::Printer* printer, + const DescriptorType* descriptor) { SourceLocation location; if (descriptor->GetSourceLocation(&location)) { WriteDocCommentBodyForLocation(printer, location); } } -static string FirstLineOf(const string& value) { - string result = value; +static std::string FirstLineOf(const std::string& value) { + std::string result = value; - string::size_type pos = result.find_first_of('\n'); - if (pos != string::npos) { + std::string::size_type pos = result.find_first_of('\n'); + if (pos != std::string::npos) { result.erase(pos); } @@ -166,9 +167,9 @@ void WriteMessageDocComment(io::Printer* printer, const Descriptor* message) { printer->Print("/**\n"); WriteDocCommentBody(printer, message); printer->Print( - " * Protobuf type {@code $fullname$}\n" - " */\n", - "fullname", EscapeJavadoc(message->full_name())); + " * Protobuf type {@code $fullname$}\n" + " */\n", + "fullname", EscapeJavadoc(message->full_name())); } void WriteFieldDocComment(io::Printer* printer, const FieldDescriptor* field) { @@ -182,9 +183,8 @@ void WriteFieldDocComment(io::Printer* printer, const FieldDescriptor* field) { // If the field is a group, the debug string might end with {. printer->Print("/**\n"); WriteDocCommentBody(printer, field); - printer->Print( - " * $def$\n", - "def", EscapeJavadoc(FirstLineOf(field->DebugString()))); + printer->Print(" * $def$\n", "def", + EscapeJavadoc(FirstLineOf(field->DebugString()))); printer->Print(" */\n"); } @@ -192,9 +192,9 @@ void WriteEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_) { printer->Print("/**\n"); WriteDocCommentBody(printer, enum_); printer->Print( - " * Protobuf enum {@code $fullname$}\n" - " */\n", - "fullname", EscapeJavadoc(enum_->full_name())); + " * Protobuf enum {@code $fullname$}\n" + " */\n", + "fullname", EscapeJavadoc(enum_->full_name())); } void WriteEnumValueDocComment(io::Printer* printer, @@ -202,9 +202,9 @@ void WriteEnumValueDocComment(io::Printer* printer, printer->Print("/**\n"); WriteDocCommentBody(printer, value); printer->Print( - " * $def$\n" - " */\n", - "def", EscapeJavadoc(FirstLineOf(value->DebugString()))); + " * $def$\n" + " */\n", + "def", EscapeJavadoc(FirstLineOf(value->DebugString()))); } void WriteServiceDocComment(io::Printer* printer, @@ -212,9 +212,9 @@ void WriteServiceDocComment(io::Printer* printer, printer->Print("/**\n"); WriteDocCommentBody(printer, service); printer->Print( - " * Protobuf service {@code $fullname$}\n" - " */\n", - "fullname", EscapeJavadoc(service->full_name())); + " * Protobuf service {@code $fullname$}\n" + " */\n", + "fullname", EscapeJavadoc(service->full_name())); } void WriteMethodDocComment(io::Printer* printer, @@ -222,9 +222,9 @@ void WriteMethodDocComment(io::Printer* printer, printer->Print("/**\n"); WriteDocCommentBody(printer, method); printer->Print( - " * $def$\n" - " */\n", - "def", EscapeJavadoc(FirstLineOf(method->DebugString()))); + " * $def$\n" + " */\n", + "def", EscapeJavadoc(FirstLineOf(method->DebugString()))); } } // namespace java diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_doc_comment.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_doc_comment.h index 7d9535c9..ef9b3a90 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_doc_comment.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_doc_comment.h @@ -37,13 +37,17 @@ #include +#include + namespace google { namespace protobuf { - namespace io { - class Printer; // printer.h - } +namespace io { +class Printer; // printer.h } +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { @@ -59,11 +63,13 @@ void WriteMethodDocComment(io::Printer* printer, const MethodDescriptor* method); // Exposed for testing only. -LIBPROTOC_EXPORT string EscapeJavadoc(const string& input); +PROTOC_EXPORT std::string EscapeJavadoc(const std::string& input); } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_DOC_COMMENT_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_enum.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_enum.cc index bef69f1a..0dade1c3 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_enum.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_enum.cc @@ -44,21 +44,22 @@ #include #include + namespace google { namespace protobuf { namespace compiler { namespace java { EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor, - bool immutable_api, - Context* context) - : descriptor_(descriptor), immutable_api_(immutable_api), - context_(context), - name_resolver_(context->GetNameResolver()) { + bool immutable_api, Context* context) + : descriptor_(descriptor), + immutable_api_(immutable_api), + context_(context), + name_resolver_(context->GetNameResolver()) { for (int i = 0; i < descriptor_->value_count(); i++) { const EnumValueDescriptor* value = descriptor_->value(i); const EnumValueDescriptor* canonical_value = - descriptor_->FindValueByNumber(value->number()); + descriptor_->FindValueByNumber(value->number()); if (value == canonical_value) { canonical_values_.push_back(value); @@ -84,7 +85,7 @@ void EnumGenerator::Generate(io::Printer* printer) { printer->Indent(); bool ordinal_is_index = true; - string index_text = "ordinal()"; + std::string index_text = "ordinal()"; for (int i = 0; i < canonical_values_.size(); i++) { if (canonical_values_[i]->index() != i) { ordinal_is_index = false; @@ -94,20 +95,18 @@ void EnumGenerator::Generate(io::Printer* printer) { } for (int i = 0; i < canonical_values_.size(); i++) { - std::map vars; + std::map vars; vars["name"] = canonical_values_[i]->name(); - vars["index"] = SimpleItoa(canonical_values_[i]->index()); - vars["number"] = SimpleItoa(canonical_values_[i]->number()); + vars["index"] = StrCat(canonical_values_[i]->index()); + vars["number"] = StrCat(canonical_values_[i]->number()); WriteEnumValueDocComment(printer, canonical_values_[i]); if (canonical_values_[i]->options().deprecated()) { printer->Print("@java.lang.Deprecated\n"); } if (ordinal_is_index) { - printer->Print(vars, - "$name$($number$),\n"); + printer->Print(vars, "$name$($number$),\n"); } else { - printer->Print(vars, - "$name$($index$, $number$),\n"); + printer->Print(vars, "$name$($index$, $number$),\n"); } printer->Annotate("name", canonical_values_[i]); } @@ -122,31 +121,31 @@ void EnumGenerator::Generate(io::Printer* printer) { } printer->Print( - ";\n" - "\n"); + ";\n" + "\n"); // ----------------------------------------------------------------- for (int i = 0; i < aliases_.size(); i++) { - std::map vars; + std::map vars; vars["classname"] = descriptor_->name(); vars["name"] = aliases_[i].value->name(); vars["canonical_name"] = aliases_[i].canonical_value->name(); WriteEnumValueDocComment(printer, aliases_[i].value); - printer->Print(vars, - "public static final $classname$ $name$ = $canonical_name$;\n"); + printer->Print( + vars, "public static final $classname$ $name$ = $canonical_name$;\n"); printer->Annotate("name", aliases_[i].value); } for (int i = 0; i < descriptor_->value_count(); i++) { - std::map vars; + std::map vars; vars["name"] = descriptor_->value(i)->name(); - vars["number"] = SimpleItoa(descriptor_->value(i)->number()); + vars["number"] = StrCat(descriptor_->value(i)->number()); vars["{"] = ""; vars["}"] = ""; WriteEnumValueDocComment(printer, descriptor_->value(i)); printer->Print(vars, - "public static final int ${$$name$_VALUE$}$ = $number$;\n"); + "public static final int ${$$name$_VALUE$}$ = $number$;\n"); printer->Annotate("{", "}", descriptor_->value(i)); } printer->Print("\n"); @@ -154,85 +153,84 @@ void EnumGenerator::Generate(io::Printer* printer) { // ----------------------------------------------------------------- printer->Print( - "\n" - "public final int getNumber() {\n"); + "\n" + "public final int getNumber() {\n"); if (SupportUnknownEnumValue(descriptor_->file())) { if (ordinal_is_index) { printer->Print( - " if (this == UNRECOGNIZED) {\n" - " throw new java.lang.IllegalArgumentException(\n" - " \"Can't get the number of an unknown enum value.\");\n" - " }\n"); + " if (this == UNRECOGNIZED) {\n" + " throw new java.lang.IllegalArgumentException(\n" + " \"Can't get the number of an unknown enum value.\");\n" + " }\n"); } else { printer->Print( - " if (index == -1) {\n" - " throw new java.lang.IllegalArgumentException(\n" - " \"Can't get the number of an unknown enum value.\");\n" - " }\n"); + " if (index == -1) {\n" + " throw new java.lang.IllegalArgumentException(\n" + " \"Can't get the number of an unknown enum value.\");\n" + " }\n"); } } printer->Print( - " return value;\n" - "}\n" - "\n" - "/**\n" - " * @deprecated Use {@link #forNumber(int)} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public static $classname$ valueOf(int value) {\n" - " return forNumber(value);\n" - "}\n" - "\n" - "public static $classname$ forNumber(int value) {\n" - " switch (value) {\n", - "classname", descriptor_->name()); + " return value;\n" + "}\n" + "\n" + "/**\n" + " * @deprecated Use {@link #forNumber(int)} instead.\n" + " */\n" + "@java.lang.Deprecated\n" + "public static $classname$ valueOf(int value) {\n" + " return forNumber(value);\n" + "}\n" + "\n" + "public static $classname$ forNumber(int value) {\n" + " switch (value) {\n", + "classname", descriptor_->name()); printer->Indent(); printer->Indent(); for (int i = 0; i < canonical_values_.size(); i++) { - printer->Print( - "case $number$: return $name$;\n", - "name", canonical_values_[i]->name(), - "number", SimpleItoa(canonical_values_[i]->number())); + printer->Print("case $number$: return $name$;\n", "name", + canonical_values_[i]->name(), "number", + StrCat(canonical_values_[i]->number())); } printer->Outdent(); printer->Outdent(); printer->Print( - " default: return null;\n" - " }\n" - "}\n" - "\n" - "public static com.google.protobuf.Internal.EnumLiteMap<$classname$>\n" - " internalGetValueMap() {\n" - " return internalValueMap;\n" - "}\n" - "private static final com.google.protobuf.Internal.EnumLiteMap<\n" - " $classname$> internalValueMap =\n" - " new com.google.protobuf.Internal.EnumLiteMap<$classname$>() {\n" - " public $classname$ findValueByNumber(int number) {\n" - " return $classname$.forNumber(number);\n" - " }\n" - " };\n" - "\n", - "classname", descriptor_->name()); + " default: return null;\n" + " }\n" + "}\n" + "\n" + "public static com.google.protobuf.Internal.EnumLiteMap<$classname$>\n" + " internalGetValueMap() {\n" + " return internalValueMap;\n" + "}\n" + "private static final com.google.protobuf.Internal.EnumLiteMap<\n" + " $classname$> internalValueMap =\n" + " new com.google.protobuf.Internal.EnumLiteMap<$classname$>() {\n" + " public $classname$ findValueByNumber(int number) {\n" + " return $classname$.forNumber(number);\n" + " }\n" + " };\n" + "\n", + "classname", descriptor_->name()); // ----------------------------------------------------------------- // Reflection if (HasDescriptorMethods(descriptor_, context_->EnforceLite())) { printer->Print( - "public final com.google.protobuf.Descriptors.EnumValueDescriptor\n" - " getValueDescriptor() {\n" - " return getDescriptor().getValues().get($index_text$);\n" - "}\n" - "public final com.google.protobuf.Descriptors.EnumDescriptor\n" - " getDescriptorForType() {\n" - " return getDescriptor();\n" - "}\n" - "public static final com.google.protobuf.Descriptors.EnumDescriptor\n" - " getDescriptor() {\n", - "index_text", index_text); + "public final com.google.protobuf.Descriptors.EnumValueDescriptor\n" + " getValueDescriptor() {\n" + " return getDescriptor().getValues().get($index_text$);\n" + "}\n" + "public final com.google.protobuf.Descriptors.EnumDescriptor\n" + " getDescriptorForType() {\n" + " return getDescriptor();\n" + "}\n" + "public static final com.google.protobuf.Descriptors.EnumDescriptor\n" + " getDescriptor() {\n", + "index_text", index_text); // TODO(kenton): Cache statically? Note that we can't access descriptors // at module init time because it wouldn't work with descriptor.proto, but @@ -242,27 +240,30 @@ void EnumGenerator::Generate(io::Printer* printer) { // extensions in both the mutable and immutable cases. (In the mutable api // this is accomplished by attempting to load the immutable outer class). printer->Print( - " return $file$.getDescriptor().getEnumTypes().get($index$);\n", - "file", name_resolver_->GetClassName(descriptor_->file(), - immutable_api_), - "index", SimpleItoa(descriptor_->index())); + " return $file$.getDescriptor().getEnumTypes().get($index$);\n", + "file", + name_resolver_->GetClassName(descriptor_->file(), immutable_api_), + "index", StrCat(descriptor_->index())); } else { printer->Print( " return $parent$.$descriptor$.getEnumTypes().get($index$);\n", - "parent", name_resolver_->GetClassName(descriptor_->containing_type(), - immutable_api_), - "descriptor", descriptor_->containing_type()->options() - .no_standard_descriptor_accessor() - ? "getDefaultInstance().getDescriptorForType()" - : "getDescriptor()", - "index", SimpleItoa(descriptor_->index())); + "parent", + name_resolver_->GetClassName(descriptor_->containing_type(), + immutable_api_), + "descriptor", + descriptor_->containing_type() + ->options() + .no_standard_descriptor_accessor() + ? "getDefaultInstance().getDescriptorForType()" + : "getDescriptor()", + "index", StrCat(descriptor_->index())); } printer->Print( - "}\n" - "\n" - "private static final $classname$[] VALUES = ", - "classname", descriptor_->name()); + "}\n" + "\n" + "private static final $classname$[] VALUES = ", + "classname", descriptor_->name()); if (CanUseEnumValues()) { // If the constants we are going to output are exactly the ones we @@ -272,11 +273,10 @@ void EnumGenerator::Generate(io::Printer* printer) { printer->Print("values();\n"); } else { printer->Print( - "{\n" - " "); + "{\n" + " "); for (int i = 0; i < descriptor_->value_count(); i++) { - printer->Print("$name$, ", - "name", descriptor_->value(i)->name()); + printer->Print("$name$, ", "name", descriptor_->value(i)->name()); } printer->Print( "\n" @@ -284,24 +284,24 @@ void EnumGenerator::Generate(io::Printer* printer) { } printer->Print( - "\n" - "public static $classname$ valueOf(\n" - " com.google.protobuf.Descriptors.EnumValueDescriptor desc) {\n" - " if (desc.getType() != getDescriptor()) {\n" - " throw new java.lang.IllegalArgumentException(\n" - " \"EnumValueDescriptor is not for this type.\");\n" - " }\n", - "classname", descriptor_->name()); + "\n" + "public static $classname$ valueOf(\n" + " com.google.protobuf.Descriptors.EnumValueDescriptor desc) {\n" + " if (desc.getType() != getDescriptor()) {\n" + " throw new java.lang.IllegalArgumentException(\n" + " \"EnumValueDescriptor is not for this type.\");\n" + " }\n", + "classname", descriptor_->name()); if (SupportUnknownEnumValue(descriptor_->file())) { printer->Print( - " if (desc.getIndex() == -1) {\n" - " return UNRECOGNIZED;\n" - " }\n"); + " if (desc.getIndex() == -1) {\n" + " return UNRECOGNIZED;\n" + " }\n"); } printer->Print( - " return VALUES[desc.getIndex()];\n" - "}\n" - "\n"); + " return VALUES[desc.getIndex()];\n" + "}\n" + "\n"); if (!ordinal_is_index) { printer->Print("private final int index;\n"); @@ -310,30 +310,27 @@ void EnumGenerator::Generate(io::Printer* printer) { // ----------------------------------------------------------------- - printer->Print( - "private final int value;\n\n"); + printer->Print("private final int value;\n\n"); if (ordinal_is_index) { - printer->Print( - "private $classname$(int value) {\n", - "classname", descriptor_->name()); + printer->Print("private $classname$(int value) {\n", "classname", + descriptor_->name()); } else { - printer->Print( - "private $classname$(int index, int value) {\n", - "classname", descriptor_->name()); + printer->Print("private $classname$(int index, int value) {\n", "classname", + descriptor_->name()); } if (HasDescriptorMethods(descriptor_, context_->EnforceLite()) && !ordinal_is_index) { printer->Print(" this.index = index;\n"); } printer->Print( - " this.value = value;\n" - "}\n"); + " this.value = value;\n" + "}\n"); printer->Print( - "\n" - "// @@protoc_insertion_point(enum_scope:$full_name$)\n", - "full_name", descriptor_->full_name()); + "\n" + "// @@protoc_insertion_point(enum_scope:$full_name$)\n", + "full_name", descriptor_->full_name()); printer->Outdent(); printer->Print("}\n\n"); diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_enum.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_enum.h index 13dfc32d..0a2c363b 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_enum.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_enum.h @@ -41,17 +41,19 @@ namespace google { namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +namespace io { +class Printer; // printer.h } +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { @@ -67,9 +69,9 @@ class EnumGenerator { private: const EnumDescriptor* descriptor_; - // The proto language allows multiple enum constants to have the same numeric - // value. Java, however, does not allow multiple enum constants to be - // considered equivalent. We treat the first defined constant for any + // The proto language allows multiple enum constants to have the same + // numeric value. Java, however, does not allow multiple enum constants to + // be considered equivalent. We treat the first defined constant for any // given numeric value as "canonical" and the rest as aliases of that // canonical value. std::vector canonical_values_; @@ -93,6 +95,6 @@ class EnumGenerator { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_field.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_field.cc index 0686ea0f..280efaf5 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_field.cc @@ -46,6 +46,7 @@ #include #include + namespace google { namespace protobuf { namespace compiler { @@ -53,12 +54,10 @@ namespace java { namespace { -void SetEnumVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - const FieldGeneratorInfo* info, +void SetEnumVariables(const FieldDescriptor* descriptor, int messageBitIndex, + int builderBitIndex, const FieldGeneratorInfo* info, ClassNameResolver* name_resolver, - std::map* variables) { + std::map* variables) { SetCommonFieldVariables(descriptor, info, variables); (*variables)["type"] = @@ -66,16 +65,16 @@ void SetEnumVariables(const FieldDescriptor* descriptor, (*variables)["mutable_type"] = name_resolver->GetMutableClassName(descriptor->enum_type()); (*variables)["default"] = ImmutableDefaultValue(descriptor, name_resolver); - (*variables)["default_number"] = SimpleItoa( - descriptor->default_value_enum()->number()); - (*variables)["tag"] = - SimpleItoa(static_cast(internal::WireFormat::MakeTag(descriptor))); - (*variables)["tag_size"] = SimpleItoa( + (*variables)["default_number"] = + StrCat(descriptor->default_value_enum()->number()); + (*variables)["tag"] = StrCat( + static_cast(internal::WireFormat::MakeTag(descriptor))); + (*variables)["tag_size"] = StrCat( internal::WireFormat::TagSize(descriptor->number(), GetType(descriptor))); // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; + (*variables)["deprecation"] = + descriptor->options().deprecated() ? "@java.lang.Deprecated " : ""; (*variables)["on_changed"] = "onChanged();"; // Use deprecated valueOf() method to be compatible with old generated code // for v2.5.0/v2.6.1. @@ -103,8 +102,8 @@ void SetEnumVariables(const FieldDescriptor* descriptor, (*variables)["clear_has_field_bit_builder"] = ""; (*variables)["is_field_present_message"] = - (*variables)["name"] + "_ != " + - (*variables)["default"] + ".getNumber()"; + (*variables)["name"] + "_ != " + (*variables)["default"] + + ".getNumber()"; } // For repated builders, one bit is used for whether the array is immutable. @@ -135,460 +134,461 @@ void SetEnumVariables(const FieldDescriptor* descriptor, // =================================================================== -ImmutableEnumFieldGenerator:: -ImmutableEnumFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), - name_resolver_(context->GetNameResolver()) { +ImmutableEnumFieldGenerator::ImmutableEnumFieldGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, + Context* context) + : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) { SetEnumVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); + context->GetFieldGeneratorInfo(descriptor), name_resolver_, + &variables_); } ImmutableEnumFieldGenerator::~ImmutableEnumFieldGenerator() {} int ImmutableEnumFieldGenerator::GetNumBitsForMessage() const { - return 1; + return SupportFieldPresence(descriptor_->file()) ? 1 : 0; } int ImmutableEnumFieldGenerator::GetNumBitsForBuilder() const { - return 1; + return GetNumBitsForMessage(); } -void ImmutableEnumFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { +void ImmutableEnumFieldGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); + "$deprecation$boolean has$capitalized_name$();\n"); } if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$int get$capitalized_name$Value();\n"); + "$deprecation$int get$capitalized_name$Value();\n"); } WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$();\n"); + printer->Print(variables_, "$deprecation$$type$ get$capitalized_name$();\n"); } -void ImmutableEnumFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private int $name$_;\n"); +void ImmutableEnumFieldGenerator::GenerateMembers(io::Printer* printer) const { + printer->Print(variables_, "private int $name$_;\n"); PrintExtraFieldInfo(variables_, printer); if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $get_has_field_bit_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" - " return $name$_;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" + " return $name$_;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " @SuppressWarnings(\"deprecation\")\n" - " $type$ result = $type$.$for_number$($name$_);\n" - " return result == null ? $unknown$ : result;\n" - "}\n"); + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " @SuppressWarnings(\"deprecation\")\n" + " $type$ result = $type$.$for_number$($name$_);\n" + " return result == null ? $unknown$ : result;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } -void ImmutableEnumFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - printer->Print(variables_, - "private int $name$_ = $default_number$;\n"); +void ImmutableEnumFieldGenerator::GenerateBuilderMembers( + io::Printer* printer) const { + printer->Print(variables_, "private int $name$_ = $default_number$;\n"); if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_builder$;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $get_has_field_bit_builder$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" - " return $name$_;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" + " return $name$_;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder " - "${$set$capitalized_name$Value$}$(int value) {\n" - " $name$_ = value;\n" + "$deprecation$public Builder " + "${$set$capitalized_name$Value$}$(int value) {\n" + " $name$_ = value;\n" + " $on_changed$\n" + " return this;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + } + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " @SuppressWarnings(\"deprecation\")\n" + " $type$ result = $type$.$for_number$($name$_);\n" + " return result == null ? $unknown$ : result;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$public Builder " + "${$set$capitalized_name$$}$($type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" + " $set_has_field_bit_builder$\n" + " $name$_ = value.getNumber();\n" + " $on_changed$\n" + " return this;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " $clear_has_field_bit_builder$\n" + " $name$_ = $default_number$;\n" " $on_changed$\n" " return this;\n" "}\n"); - printer->Annotate("{", "}", descriptor_); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " @SuppressWarnings(\"deprecation\")\n" - " $type$ result = $type$.$for_number$($name$_);\n" - " return result == null ? $unknown$ : result;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " $set_has_field_bit_builder$\n" - " $name$_ = value.getNumber();\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " $clear_has_field_bit_builder$\n" - " $name$_ = $default_number$;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); printer->Annotate("{", "}", descriptor_); } -void ImmutableEnumFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { +void ImmutableEnumFieldGenerator::GenerateFieldBuilderInitializationCode( + io::Printer* printer) const { // noop for enums } -void ImmutableEnumFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { +void ImmutableEnumFieldGenerator::GenerateInitializationCode( + io::Printer* printer) const { printer->Print(variables_, "$name$_ = $default_number$;\n"); } -void ImmutableEnumFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { +void ImmutableEnumFieldGenerator::GenerateBuilderClearCode( + io::Printer* printer) const { printer->Print(variables_, - "$name$_ = $default_number$;\n" - "$clear_has_field_bit_builder$\n"); + "$name$_ = $default_number$;\n" + "$clear_has_field_bit_builder$\n"); } -void ImmutableEnumFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { +void ImmutableEnumFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { printer->Print(variables_, - "if (other.has$capitalized_name$()) {\n" - " set$capitalized_name$(other.get$capitalized_name$());\n" - "}\n"); + "if (other.has$capitalized_name$()) {\n" + " set$capitalized_name$(other.get$capitalized_name$());\n" + "}\n"); } else if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "if (other.$name$_ != $default_number$) {\n" - " set$capitalized_name$Value(other.get$capitalized_name$Value());\n" - "}\n"); + printer->Print( + variables_, + "if (other.$name$_ != $default_number$) {\n" + " set$capitalized_name$Value(other.get$capitalized_name$Value());\n" + "}\n"); } else { GOOGLE_LOG(FATAL) << "Can't reach here."; } } -void ImmutableEnumFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { +void ImmutableEnumFieldGenerator::GenerateBuildingCode( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { printer->Print(variables_, - "if ($get_has_field_bit_from_local$) {\n" - " $set_has_field_bit_to_local$;\n" - "}\n"); + "if ($get_has_field_bit_from_local$) {\n" + " $set_has_field_bit_to_local$;\n" + "}\n"); } - printer->Print(variables_, - "result.$name$_ = $name$_;\n"); + printer->Print(variables_, "result.$name$_ = $name$_;\n"); } -void ImmutableEnumFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { +void ImmutableEnumFieldGenerator::GenerateParsingCode( + io::Printer* printer) const { if (SupportUnknownEnumValue(descriptor_->file())) { printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "$set_has_field_bit_message$\n" - "$name$_ = rawValue;\n"); + "int rawValue = input.readEnum();\n" + "$set_has_field_bit_message$\n" + "$name$_ = rawValue;\n"); } else { printer->Print(variables_, - "int rawValue = input.readEnum();\n" - " @SuppressWarnings(\"deprecation\")\n" - "$type$ value = $type$.$for_number$(rawValue);\n" - "if (value == null) {\n" - " unknownFields.mergeVarintField($number$, rawValue);\n" - "} else {\n" - " $set_has_field_bit_message$\n" - " $name$_ = rawValue;\n" - "}\n"); + "int rawValue = input.readEnum();\n" + " @SuppressWarnings(\"deprecation\")\n" + "$type$ value = $type$.$for_number$(rawValue);\n" + "if (value == null) {\n" + " unknownFields.mergeVarintField($number$, rawValue);\n" + "} else {\n" + " $set_has_field_bit_message$\n" + " $name$_ = rawValue;\n" + "}\n"); } } -void ImmutableEnumFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { +void ImmutableEnumFieldGenerator::GenerateParsingDoneCode( + io::Printer* printer) const { // noop for enums } -void ImmutableEnumFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { +void ImmutableEnumFieldGenerator::GenerateSerializationCode( + io::Printer* printer) const { printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " output.writeEnum($number$, $name$_);\n" - "}\n"); + "if ($is_field_present_message$) {\n" + " output.writeEnum($number$, $name$_);\n" + "}\n"); } -void ImmutableEnumFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { +void ImmutableEnumFieldGenerator::GenerateSerializedSizeCode( + io::Printer* printer) const { printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeEnumSize($number$, $name$_);\n" - "}\n"); + "if ($is_field_present_message$) {\n" + " size += com.google.protobuf.CodedOutputStream\n" + " .computeEnumSize($number$, $name$_);\n" + "}\n"); } -void ImmutableEnumFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && $name$_ == other.$name$_;\n"); +void ImmutableEnumFieldGenerator::GenerateEqualsCode( + io::Printer* printer) const { + printer->Print(variables_, "if ($name$_ != other.$name$_) return false;\n"); } -void ImmutableEnumFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { +void ImmutableEnumFieldGenerator::GenerateHashCode(io::Printer* printer) const { printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n" - "hash = (53 * hash) + $name$_;\n"); + "hash = (37 * hash) + $constant_name$;\n" + "hash = (53 * hash) + $name$_;\n"); } -string ImmutableEnumFieldGenerator::GetBoxedType() const { +std::string ImmutableEnumFieldGenerator::GetBoxedType() const { return name_resolver_->GetImmutableClassName(descriptor_->enum_type()); } // =================================================================== -ImmutableEnumOneofFieldGenerator:: -ImmutableEnumOneofFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableEnumFieldGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { +ImmutableEnumOneofFieldGenerator::ImmutableEnumOneofFieldGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, + Context* context) + : ImmutableEnumFieldGenerator(descriptor, messageBitIndex, builderBitIndex, + context) { const OneofGeneratorInfo* info = context->GetOneofGeneratorInfo(descriptor->containing_oneof()); SetCommonOneofVariables(descriptor, info, &variables_); } -ImmutableEnumOneofFieldGenerator:: -~ImmutableEnumOneofFieldGenerator() {} +ImmutableEnumOneofFieldGenerator::~ImmutableEnumOneofFieldGenerator() {} -void ImmutableEnumOneofFieldGenerator:: -GenerateMembers(io::Printer* printer) const { +void ImmutableEnumOneofFieldGenerator::GenerateMembers( + io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $has_oneof_case_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return (java.lang.Integer) $oneof_name$_;\n" - " }\n" - " return $default_number$;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" + " if ($has_oneof_case_message$) {\n" + " return (java.lang.Integer) $oneof_name$_;\n" + " }\n" + " return $default_number$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " @SuppressWarnings(\"deprecation\")\n" - " $type$ result = $type$.$for_number$(\n" - " (java.lang.Integer) $oneof_name$_);\n" - " return result == null ? $unknown$ : result;\n" - " }\n" - " return $default$;\n" - "}\n"); + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " if ($has_oneof_case_message$) {\n" + " @SuppressWarnings(\"deprecation\")\n" + " $type$ result = $type$.$for_number$(\n" + " (java.lang.Integer) $oneof_name$_);\n" + " return result == null ? $unknown$ : result;\n" + " }\n" + " return $default$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } -void ImmutableEnumOneofFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void ImmutableEnumOneofFieldGenerator::GenerateBuilderMembers( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $has_oneof_case_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ((java.lang.Integer) $oneof_name$_).intValue();\n" - " }\n" - " return $default_number$;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" + " if ($has_oneof_case_message$) {\n" + " return ((java.lang.Integer) $oneof_name$_).intValue();\n" + " }\n" + " return $default_number$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder " - "${$set$capitalized_name$Value$}$(int value) {\n" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value;\n" - " $on_changed$\n" + "$deprecation$public Builder " + "${$set$capitalized_name$Value$}$(int value) {\n" + " $set_oneof_case_message$;\n" + " $oneof_name$_ = value;\n" + " $on_changed$\n" + " return this;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + } + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " if ($has_oneof_case_message$) {\n" + " @SuppressWarnings(\"deprecation\")\n" + " $type$ result = $type$.$for_number$(\n" + " (java.lang.Integer) $oneof_name$_);\n" + " return result == null ? $unknown$ : result;\n" + " }\n" + " return $default$;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$public Builder " + "${$set$capitalized_name$$}$($type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" + " $set_oneof_case_message$;\n" + " $oneof_name$_ = value.getNumber();\n" + " $on_changed$\n" + " return this;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " if ($has_oneof_case_message$) {\n" + " $clear_oneof_case_message$;\n" + " $oneof_name$_ = null;\n" + " $on_changed$\n" + " }\n" " return this;\n" "}\n"); - printer->Annotate("{", "}", descriptor_); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " @SuppressWarnings(\"deprecation\")\n" - " $type$ result = $type$.$for_number$(\n" - " (java.lang.Integer) $oneof_name$_);\n" - " return result == null ? $unknown$ : result;\n" - " }\n" - " return $default$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value.getNumber();\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " $on_changed$\n" - " }\n" - " return this;\n" - "}\n"); printer->Annotate("{", "}", descriptor_); } -void ImmutableEnumOneofFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { +void ImmutableEnumOneofFieldGenerator::GenerateBuildingCode( + io::Printer* printer) const { printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " result.$oneof_name$_ = $oneof_name$_;\n" - "}\n"); + "if ($has_oneof_case_message$) {\n" + " result.$oneof_name$_ = $oneof_name$_;\n" + "}\n"); } -void ImmutableEnumOneofFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { +void ImmutableEnumOneofFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "set$capitalized_name$Value(other.get$capitalized_name$Value());\n"); + printer->Print( + variables_, + "set$capitalized_name$Value(other.get$capitalized_name$Value());\n"); } else { printer->Print(variables_, - "set$capitalized_name$(other.get$capitalized_name$());\n"); + "set$capitalized_name$(other.get$capitalized_name$());\n"); } } -void ImmutableEnumOneofFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { +void ImmutableEnumOneofFieldGenerator::GenerateParsingCode( + io::Printer* printer) const { if (SupportUnknownEnumValue(descriptor_->file())) { printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "$set_oneof_case_message$;\n" - "$oneof_name$_ = rawValue;\n"); + "int rawValue = input.readEnum();\n" + "$set_oneof_case_message$;\n" + "$oneof_name$_ = rawValue;\n"); } else { printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "@SuppressWarnings(\"deprecation\")\n" - "$type$ value = $type$.$for_number$(rawValue);\n" - "if (value == null) {\n" - " unknownFields.mergeVarintField($number$, rawValue);\n" - "} else {\n" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = rawValue;\n" + "int rawValue = input.readEnum();\n" + "@SuppressWarnings(\"deprecation\")\n" + "$type$ value = $type$.$for_number$(rawValue);\n" + "if (value == null) {\n" + " unknownFields.mergeVarintField($number$, rawValue);\n" + "} else {\n" + " $set_oneof_case_message$;\n" + " $oneof_name$_ = rawValue;\n" + "}\n"); + } +} + +void ImmutableEnumOneofFieldGenerator::GenerateSerializationCode( + io::Printer* printer) const { + printer->Print( + variables_, + "if ($has_oneof_case_message$) {\n" + " output.writeEnum($number$, ((java.lang.Integer) $oneof_name$_));\n" "}\n"); +} + +void ImmutableEnumOneofFieldGenerator::GenerateSerializedSizeCode( + io::Printer* printer) const { + printer->Print( + variables_, + "if ($has_oneof_case_message$) {\n" + " size += com.google.protobuf.CodedOutputStream\n" + " .computeEnumSize($number$, ((java.lang.Integer) $oneof_name$_));\n" + "}\n"); +} + +void ImmutableEnumOneofFieldGenerator::GenerateEqualsCode( + io::Printer* printer) const { + if (SupportUnknownEnumValue(descriptor_->file())) { + printer->Print( + variables_, + "if (get$capitalized_name$Value()\n" + " != other.get$capitalized_name$Value()) return false;\n"); + } else { + printer->Print( + variables_, + "if (!get$capitalized_name$()\n" + " .equals(other.get$capitalized_name$())) return false;\n"); } } -void ImmutableEnumOneofFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.writeEnum($number$, ((java.lang.Integer) $oneof_name$_));\n" - "}\n"); -} - -void ImmutableEnumOneofFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeEnumSize($number$, ((java.lang.Integer) $oneof_name$_));\n" - "}\n"); -} - -void ImmutableEnumOneofFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { +void ImmutableEnumOneofFieldGenerator::GenerateHashCode( + io::Printer* printer) const { if (SupportUnknownEnumValue(descriptor_->file())) { printer->Print(variables_, - "result = result && get$capitalized_name$Value()\n" - " == other.get$capitalized_name$Value();\n"); + "hash = (37 * hash) + $constant_name$;\n" + "hash = (53 * hash) + get$capitalized_name$Value();\n"); } else { - printer->Print(variables_, - "result = result && get$capitalized_name$()\n" - " .equals(other.get$capitalized_name$());\n"); - } -} - -void ImmutableEnumOneofFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n" - "hash = (53 * hash) + get$capitalized_name$Value();\n"); - } else { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n" - "hash = (53 * hash) + get$capitalized_name$().getNumber();\n"); + printer->Print( + variables_, + "hash = (37 * hash) + $constant_name$;\n" + "hash = (53 * hash) + get$capitalized_name$().getNumber();\n"); } } // =================================================================== -RepeatedImmutableEnumFieldGenerator:: -RepeatedImmutableEnumFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { +RepeatedImmutableEnumFieldGenerator::RepeatedImmutableEnumFieldGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, + Context* context) + : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) { SetEnumVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); + context->GetFieldGeneratorInfo(descriptor), name_resolver_, + &variables_); } RepeatedImmutableEnumFieldGenerator::~RepeatedImmutableEnumFieldGenerator() {} @@ -601,401 +601,416 @@ int RepeatedImmutableEnumFieldGenerator::GetNumBitsForBuilder() const { return 1; } -void RepeatedImmutableEnumFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { +void RepeatedImmutableEnumFieldGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$java.util.List<$type$> get$capitalized_name$List();\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$java.util.List<$type$> get$capitalized_name$List();\n"); + "$deprecation$int get$capitalized_name$Count();\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$(int index);\n"); + "$deprecation$$type$ get$capitalized_name$(int index);\n"); if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$java.util.List\n" - "get$capitalized_name$ValueList();\n"); + "$deprecation$java.util.List\n" + "get$capitalized_name$ValueList();\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$int get$capitalized_name$Value(int index);\n"); + "$deprecation$int get$capitalized_name$Value(int index);\n"); } } -void RepeatedImmutableEnumFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private java.util.List $name$_;\n" - "private static final com.google.protobuf.Internal.ListAdapter.Converter<\n" - " java.lang.Integer, $type$> $name$_converter_ =\n" - " new com.google.protobuf.Internal.ListAdapter.Converter<\n" - " java.lang.Integer, $type$>() {\n" - " public $type$ convert(java.lang.Integer from) {\n" - " @SuppressWarnings(\"deprecation\")\n" - " $type$ result = $type$.$for_number$(from);\n" - " return result == null ? $unknown$ : result;\n" - " }\n" - " };\n"); +void RepeatedImmutableEnumFieldGenerator::GenerateMembers( + io::Printer* printer) const { + printer->Print( + variables_, + "private java.util.List $name$_;\n" + "private static final " + "com.google.protobuf.Internal.ListAdapter.Converter<\n" + " java.lang.Integer, $type$> $name$_converter_ =\n" + " new com.google.protobuf.Internal.ListAdapter.Converter<\n" + " java.lang.Integer, $type$>() {\n" + " public $type$ convert(java.lang.Integer from) {\n" + " @SuppressWarnings(\"deprecation\")\n" + " $type$ result = $type$.$for_number$(from);\n" + " return result == null ? $unknown$ : result;\n" + " }\n" + " };\n"); PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List<$type$> " - "${$get$capitalized_name$List$}$() {\n" - " return new com.google.protobuf.Internal.ListAdapter<\n" - " java.lang.Integer, $type$>($name$_, $name$_converter_);\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public java.util.List<$type$> " + "${$get$capitalized_name$List$}$() {\n" + " return new com.google.protobuf.Internal.ListAdapter<\n" + " java.lang.Integer, $type$>($name$_, $name$_converter_);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" + " return $name$_.size();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return $name$_converter_.convert($name$_.get(index));\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" + " return $name$_converter_.convert($name$_.get(index));\n" + "}\n"); printer->Annotate("{", "}", descriptor_); if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public java.util.List\n" - "${$get$capitalized_name$ValueList$}$() {\n" - " return $name$_;\n" - "}\n"); + "$deprecation$public java.util.List\n" + "${$get$capitalized_name$ValueList$}$() {\n" + " return $name$_;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); + "$deprecation$public int " + "${$get$capitalized_name$Value$}$(int index) {\n" + " return $name$_.get(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } if (descriptor_->is_packed()) { - printer->Print(variables_, - "private int $name$MemoizedSerializedSize;\n"); + printer->Print(variables_, "private int $name$MemoizedSerializedSize;\n"); } } -void RepeatedImmutableEnumFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - printer->Print(variables_, - // One field is the list and the other field keeps track of whether the - // list is immutable. If it's immutable, the invariant is that it must - // either an instance of Collections.emptyList() or it's an ArrayList - // wrapped in a Collections.unmodifiableList() wrapper and nobody else has - // a refererence to the underlying ArrayList. This invariant allows us to - // share instances of lists between protocol buffers avoiding expensive - // memory allocations. Note, immutable is a strong guarantee here -- not - // just that the list cannot be modified via the reference but that the - // list can never be modified. - "private java.util.List $name$_ =\n" - " java.util.Collections.emptyList();\n" +void RepeatedImmutableEnumFieldGenerator::GenerateBuilderMembers( + io::Printer* printer) const { + printer->Print( + variables_, + // One field is the list and the other field keeps track of whether the + // list is immutable. If it's immutable, the invariant is that it must + // either an instance of Collections.emptyList() or it's an ArrayList + // wrapped in a Collections.unmodifiableList() wrapper and nobody else has + // a refererence to the underlying ArrayList. This invariant allows us to + // share instances of lists between protocol buffers avoiding expensive + // memory allocations. Note, immutable is a strong guarantee here -- not + // just that the list cannot be modified via the reference but that the + // list can never be modified. + "private java.util.List $name$_ =\n" + " java.util.Collections.emptyList();\n" - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$get_mutable_bit_builder$) {\n" - " $name$_ = new java.util.ArrayList($name$_);\n" - " $set_mutable_bit_builder$;\n" - " }\n" - "}\n"); + "private void ensure$capitalized_name$IsMutable() {\n" + " if (!$get_mutable_bit_builder$) {\n" + " $name$_ = new java.util.ArrayList($name$_);\n" + " $set_mutable_bit_builder$;\n" + " }\n" + "}\n"); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - // Note: We return an unmodifiable list because otherwise the caller - // could hold on to the returned list and modify it after the message - // has been built, thus mutating the message which is supposed to be - // immutable. - "$deprecation$public java.util.List<$type$> " - "${$get$capitalized_name$List$}$() {\n" - " return new com.google.protobuf.Internal.ListAdapter<\n" - " java.lang.Integer, $type$>($name$_, $name$_converter_);\n" - "}\n"); + printer->Print( + variables_, + // Note: We return an unmodifiable list because otherwise the caller + // could hold on to the returned list and modify it after the message + // has been built, thus mutating the message which is supposed to be + // immutable. + "$deprecation$public java.util.List<$type$> " + "${$get$capitalized_name$List$}$() {\n" + " return new com.google.protobuf.Internal.ListAdapter<\n" + " java.lang.Integer, $type$>($name$_, $name$_converter_);\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" + " return $name$_.size();\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" + " return $name$_converter_.convert($name$_.get(index));\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " int index, $type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.set(index, value.getNumber());\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return $name$_converter_.convert($name$_.get(index));\n" - "}\n"); + "$deprecation$public Builder " + "${$add$capitalized_name$$}$($type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.add(value.getNumber());\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, $type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(index, value.getNumber());\n" - " $on_changed$\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" + " java.lang.Iterable values) {\n" + " ensure$capitalized_name$IsMutable();\n" + " for ($type$ value : values) {\n" + " $name$_.add(value.getNumber());\n" + " }\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(value.getNumber());\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " for ($type$ value : values) {\n" - " $name$_.add(value.getNumber());\n" - " }\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " $name$_ = java.util.Collections.emptyList();\n" - " $clear_mutable_bit_builder$;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " $name$_ = java.util.Collections.emptyList();\n" + " $clear_mutable_bit_builder$;\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public java.util.List\n" - "${$get$capitalized_name$ValueList$}$() {\n" - " return java.util.Collections.unmodifiableList($name$_);\n" - "}\n"); + "$deprecation$public java.util.List\n" + "${$get$capitalized_name$ValueList$}$() {\n" + " return java.util.Collections.unmodifiableList($name$_);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); + "$deprecation$public int " + "${$get$capitalized_name$Value$}$(int index) {\n" + " return $name$_.get(index);\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public Builder ${$set$capitalized_name$Value$}$(\n" + " int index, int value) {\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.set(index, value);\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$Value$}$(\n" - " int index, int value) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(index, value);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder " + "${$add$capitalized_name$Value$}$(int value) {\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.add(value);\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder " - "${$add$capitalized_name$Value$}$(int value) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(value);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$Value$}$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " for (int value : values) {\n" - " $name$_.add(value);\n" - " }\n" - " $on_changed$\n" - " return this;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$addAll$capitalized_name$Value$}$(\n" + " java.lang.Iterable values) {\n" + " ensure$capitalized_name$IsMutable();\n" + " for (int value : values) {\n" + " $name$_.add(value);\n" + " }\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } } void RepeatedImmutableEnumFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { + GenerateFieldBuilderInitializationCode(io::Printer* printer) const { // noop for enums } -void RepeatedImmutableEnumFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { +void RepeatedImmutableEnumFieldGenerator::GenerateInitializationCode( + io::Printer* printer) const { printer->Print(variables_, "$name$_ = java.util.Collections.emptyList();\n"); } -void RepeatedImmutableEnumFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { +void RepeatedImmutableEnumFieldGenerator::GenerateBuilderClearCode( + io::Printer* printer) const { printer->Print(variables_, - "$name$_ = java.util.Collections.emptyList();\n" - "$clear_mutable_bit_builder$;\n"); + "$name$_ = java.util.Collections.emptyList();\n" + "$clear_mutable_bit_builder$;\n"); } -void RepeatedImmutableEnumFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { +void RepeatedImmutableEnumFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { // The code below does two optimizations: // 1. If the other list is empty, there's nothing to do. This ensures we // don't allocate a new array if we already have an immutable one. // 2. If the other list is non-empty and our current list is empty, we can // reuse the other list which is guaranteed to be immutable. printer->Print(variables_, - "if (!other.$name$_.isEmpty()) {\n" - " if ($name$_.isEmpty()) {\n" - " $name$_ = other.$name$_;\n" - " $clear_mutable_bit_builder$;\n" - " } else {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.addAll(other.$name$_);\n" - " }\n" - " $on_changed$\n" - "}\n"); + "if (!other.$name$_.isEmpty()) {\n" + " if ($name$_.isEmpty()) {\n" + " $name$_ = other.$name$_;\n" + " $clear_mutable_bit_builder$;\n" + " } else {\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.addAll(other.$name$_);\n" + " }\n" + " $on_changed$\n" + "}\n"); } -void RepeatedImmutableEnumFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { +void RepeatedImmutableEnumFieldGenerator::GenerateBuildingCode( + io::Printer* printer) const { // The code below ensures that the result has an immutable list. If our // list is immutable, we can just reuse it. If not, we make it immutable. - printer->Print(variables_, - "if ($get_mutable_bit_builder$) {\n" - " $name$_ = java.util.Collections.unmodifiableList($name$_);\n" - " $clear_mutable_bit_builder$;\n" - "}\n" - "result.$name$_ = $name$_;\n"); + printer->Print( + variables_, + "if ($get_mutable_bit_builder$) {\n" + " $name$_ = java.util.Collections.unmodifiableList($name$_);\n" + " $clear_mutable_bit_builder$;\n" + "}\n" + "result.$name$_ = $name$_;\n"); } -void RepeatedImmutableEnumFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { +void RepeatedImmutableEnumFieldGenerator::GenerateParsingCode( + io::Printer* printer) const { // Read and store the enum if (SupportUnknownEnumValue(descriptor_->file())) { printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "if (!$get_mutable_bit_parser$) {\n" - " $name$_ = new java.util.ArrayList();\n" - " $set_mutable_bit_parser$;\n" - "}\n" - "$name$_.add(rawValue);\n"); + "int rawValue = input.readEnum();\n" + "if (!$get_mutable_bit_parser$) {\n" + " $name$_ = new java.util.ArrayList();\n" + " $set_mutable_bit_parser$;\n" + "}\n" + "$name$_.add(rawValue);\n"); } else { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "@SuppressWarnings(\"deprecation\")\n" - "$type$ value = $type$.$for_number$(rawValue);\n" - "if (value == null) {\n" - " unknownFields.mergeVarintField($number$, rawValue);\n" - "} else {\n" - " if (!$get_mutable_bit_parser$) {\n" - " $name$_ = new java.util.ArrayList();\n" - " $set_mutable_bit_parser$;\n" - " }\n" - " $name$_.add(rawValue);\n" - "}\n"); + printer->Print( + variables_, + "int rawValue = input.readEnum();\n" + "@SuppressWarnings(\"deprecation\")\n" + "$type$ value = $type$.$for_number$(rawValue);\n" + "if (value == null) {\n" + " unknownFields.mergeVarintField($number$, rawValue);\n" + "} else {\n" + " if (!$get_mutable_bit_parser$) {\n" + " $name$_ = new java.util.ArrayList();\n" + " $set_mutable_bit_parser$;\n" + " }\n" + " $name$_.add(rawValue);\n" + "}\n"); } } -void RepeatedImmutableEnumFieldGenerator:: -GenerateParsingCodeFromPacked(io::Printer* printer) const { +void RepeatedImmutableEnumFieldGenerator::GenerateParsingCodeFromPacked( + io::Printer* printer) const { // Wrap GenerateParsingCode's contents with a while loop. printer->Print(variables_, - "int length = input.readRawVarint32();\n" - "int oldLimit = input.pushLimit(length);\n" - "while(input.getBytesUntilLimit() > 0) {\n"); + "int length = input.readRawVarint32();\n" + "int oldLimit = input.pushLimit(length);\n" + "while(input.getBytesUntilLimit() > 0) {\n"); printer->Indent(); GenerateParsingCode(printer); printer->Outdent(); printer->Print(variables_, - "}\n" - "input.popLimit(oldLimit);\n"); + "}\n" + "input.popLimit(oldLimit);\n"); } -void RepeatedImmutableEnumFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($get_mutable_bit_parser$) {\n" - " $name$_ = java.util.Collections.unmodifiableList($name$_);\n" - "}\n"); +void RepeatedImmutableEnumFieldGenerator::GenerateParsingDoneCode( + io::Printer* printer) const { + printer->Print( + variables_, + "if ($get_mutable_bit_parser$) {\n" + " $name$_ = java.util.Collections.unmodifiableList($name$_);\n" + "}\n"); } -void RepeatedImmutableEnumFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { +void RepeatedImmutableEnumFieldGenerator::GenerateSerializationCode( + io::Printer* printer) const { if (descriptor_->is_packed()) { printer->Print(variables_, - "if (get$capitalized_name$List().size() > 0) {\n" - " output.writeUInt32NoTag($tag$);\n" - " output.writeUInt32NoTag($name$MemoizedSerializedSize);\n" - "}\n" - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.writeEnumNoTag($name$_.get(i));\n" - "}\n"); + "if (get$capitalized_name$List().size() > 0) {\n" + " output.writeUInt32NoTag($tag$);\n" + " output.writeUInt32NoTag($name$MemoizedSerializedSize);\n" + "}\n" + "for (int i = 0; i < $name$_.size(); i++) {\n" + " output.writeEnumNoTag($name$_.get(i));\n" + "}\n"); } else { printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.writeEnum($number$, $name$_.get(i));\n" - "}\n"); + "for (int i = 0; i < $name$_.size(); i++) {\n" + " output.writeEnum($number$, $name$_.get(i));\n" + "}\n"); } } -void RepeatedImmutableEnumFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { +void RepeatedImmutableEnumFieldGenerator::GenerateSerializedSizeCode( + io::Printer* printer) const { printer->Print(variables_, - "{\n" - " int dataSize = 0;\n"); + "{\n" + " int dataSize = 0;\n"); printer->Indent(); printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " dataSize += com.google.protobuf.CodedOutputStream\n" - " .computeEnumSizeNoTag($name$_.get(i));\n" - "}\n"); - printer->Print( - "size += dataSize;\n"); + "for (int i = 0; i < $name$_.size(); i++) {\n" + " dataSize += com.google.protobuf.CodedOutputStream\n" + " .computeEnumSizeNoTag($name$_.get(i));\n" + "}\n"); + printer->Print("size += dataSize;\n"); if (descriptor_->is_packed()) { printer->Print(variables_, - "if (!get$capitalized_name$List().isEmpty()) {" - " size += $tag_size$;\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeUInt32SizeNoTag(dataSize);\n" - "}"); + "if (!get$capitalized_name$List().isEmpty()) {" + " size += $tag_size$;\n" + " size += com.google.protobuf.CodedOutputStream\n" + " .computeUInt32SizeNoTag(dataSize);\n" + "}"); } else { - printer->Print(variables_, - "size += $tag_size$ * $name$_.size();\n"); + printer->Print(variables_, "size += $tag_size$ * $name$_.size();\n"); } // cache the data size for packed fields. if (descriptor_->is_packed()) { - printer->Print(variables_, - "$name$MemoizedSerializedSize = dataSize;\n"); + printer->Print(variables_, "$name$MemoizedSerializedSize = dataSize;\n"); } printer->Outdent(); printer->Print("}\n"); } -void RepeatedImmutableEnumFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { +void RepeatedImmutableEnumFieldGenerator::GenerateEqualsCode( + io::Printer* printer) const { printer->Print(variables_, - "result = result && $name$_.equals(other.$name$_);\n"); + "if (!$name$_.equals(other.$name$_)) return false;\n"); } -void RepeatedImmutableEnumFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { +void RepeatedImmutableEnumFieldGenerator::GenerateHashCode( + io::Printer* printer) const { printer->Print(variables_, - "if (get$capitalized_name$Count() > 0) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + $name$_.hashCode();\n" - "}\n"); + "if (get$capitalized_name$Count() > 0) {\n" + " hash = (37 * hash) + $constant_name$;\n" + " hash = (53 * hash) + $name$_.hashCode();\n" + "}\n"); } -string RepeatedImmutableEnumFieldGenerator::GetBoxedType() const { +std::string RepeatedImmutableEnumFieldGenerator::GetBoxedType() const { return name_resolver_->GetImmutableClassName(descriptor_->enum_type()); } diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_field.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_field.h index 924ff281..95c7db57 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_field.h @@ -41,26 +41,29 @@ namespace google { namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } -} +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { class ImmutableEnumFieldGenerator : public ImmutableFieldGenerator { public: - explicit ImmutableEnumFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + explicit ImmutableEnumFieldGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, int builderBitIndex, + Context* context); ~ImmutableEnumFieldGenerator(); - // implements ImmutableFieldGenerator --------------------------------------- + // implements ImmutableFieldGenerator + // --------------------------------------- int GetNumBitsForMessage() const; int GetNumBitsForBuilder() const; void GenerateInterfaceMembers(io::Printer* printer) const; @@ -78,14 +81,11 @@ class ImmutableEnumFieldGenerator : public ImmutableFieldGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; + std::map variables_; ClassNameResolver* name_resolver_; private: @@ -94,9 +94,9 @@ class ImmutableEnumFieldGenerator : public ImmutableFieldGenerator { class ImmutableEnumOneofFieldGenerator : public ImmutableEnumFieldGenerator { public: - ImmutableEnumOneofFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + ImmutableEnumOneofFieldGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, int builderBitIndex, + Context* context); ~ImmutableEnumOneofFieldGenerator(); void GenerateMembers(io::Printer* printer) const; @@ -139,14 +139,11 @@ class RepeatedImmutableEnumFieldGenerator : public ImmutableFieldGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; private: const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; + std::map variables_; ClassNameResolver* name_resolver_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableEnumFieldGenerator); @@ -155,6 +152,6 @@ class RepeatedImmutableEnumFieldGenerator : public ImmutableFieldGenerator { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_field_lite.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_field_lite.cc index f1fe71b0..376aa861 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_field_lite.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_field_lite.cc @@ -46,19 +46,25 @@ #include #include + namespace google { namespace protobuf { namespace compiler { namespace java { namespace { +bool EnableExperimentalRuntimeForLite() { +#ifdef PROTOBUF_EXPERIMENT + return PROTOBUF_EXPERIMENT; +#else // PROTOBUF_EXPERIMENT + return false; +#endif // !PROTOBUF_EXPERIMENT +} -void SetEnumVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - const FieldGeneratorInfo* info, +void SetEnumVariables(const FieldDescriptor* descriptor, int messageBitIndex, + int builderBitIndex, const FieldGeneratorInfo* info, ClassNameResolver* name_resolver, - std::map* variables) { + std::map* variables) { SetCommonFieldVariables(descriptor, info, variables); (*variables)["type"] = @@ -66,16 +72,16 @@ void SetEnumVariables(const FieldDescriptor* descriptor, (*variables)["mutable_type"] = name_resolver->GetMutableClassName(descriptor->enum_type()); (*variables)["default"] = ImmutableDefaultValue(descriptor, name_resolver); - (*variables)["default_number"] = SimpleItoa( - descriptor->default_value_enum()->number()); - (*variables)["tag"] = - SimpleItoa(static_cast(internal::WireFormat::MakeTag(descriptor))); - (*variables)["tag_size"] = SimpleItoa( + (*variables)["default_number"] = + StrCat(descriptor->default_value_enum()->number()); + (*variables)["tag"] = StrCat( + static_cast(internal::WireFormat::MakeTag(descriptor))); + (*variables)["tag_size"] = StrCat( internal::WireFormat::TagSize(descriptor->number(), GetType(descriptor))); // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; + (*variables)["deprecation"] = + descriptor->options().deprecated() ? "@java.lang.Deprecated " : ""; (*variables)["required"] = descriptor->is_required() ? "true" : "false"; if (SupportFieldPresence(descriptor->file())) { @@ -94,8 +100,8 @@ void SetEnumVariables(const FieldDescriptor* descriptor, (*variables)["clear_has_field_bit_message"] = ""; (*variables)["is_field_present_message"] = - (*variables)["name"] + "_ != " + - (*variables)["default"] + ".getNumber()"; + (*variables)["name"] + "_ != " + (*variables)["default"] + + ".getNumber()"; } // For repeated builders, the underlying list tracks mutability state. @@ -117,902 +123,647 @@ void SetEnumVariables(const FieldDescriptor* descriptor, // =================================================================== -ImmutableEnumFieldLiteGenerator:: -ImmutableEnumFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), - name_resolver_(context->GetNameResolver()) { - SetEnumVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); +ImmutableEnumFieldLiteGenerator::ImmutableEnumFieldLiteGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, Context* context) + : descriptor_(descriptor), + messageBitIndex_(messageBitIndex), + context_(context), + name_resolver_(context->GetNameResolver()) { + SetEnumVariables(descriptor, messageBitIndex, 0, + context->GetFieldGeneratorInfo(descriptor), name_resolver_, + &variables_); } ImmutableEnumFieldLiteGenerator::~ImmutableEnumFieldLiteGenerator() {} int ImmutableEnumFieldLiteGenerator::GetNumBitsForMessage() const { - return 1; + return SupportFieldPresence(descriptor_->file()) ? 1 : 0; } -int ImmutableEnumFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { +void ImmutableEnumFieldLiteGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); + "$deprecation$boolean has$capitalized_name$();\n"); } if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$int get$capitalized_name$Value();\n"); + "$deprecation$int get$capitalized_name$Value();\n"); } WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$();\n"); + printer->Print(variables_, "$deprecation$$type$ get$capitalized_name$();\n"); } -void ImmutableEnumFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private int $name$_;\n"); +void ImmutableEnumFieldLiteGenerator::GenerateMembers( + io::Printer* printer) const { + printer->Print(variables_, "private int $name$_;\n"); PrintExtraFieldInfo(variables_, printer); if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $get_has_field_bit_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" - " return $name$_;\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" + " return $name$_;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " $type$ result = $type$.forNumber($name$_);\n" - " return result == null ? $unknown$ : result;\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " $type$ result = $type$.forNumber($name$_);\n" + " return result == null ? $unknown$ : result;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Generate private setters for the builder to proxy into. if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void set$capitalized_name$Value(int value) {\n" - " $set_has_field_bit_message$" - " $name$_ = value;\n" - "}\n"); + "private void set$capitalized_name$Value(int value) {\n" + " $set_has_field_bit_message$" + " $name$_ = value;\n" + "}\n"); } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void set$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " $set_has_field_bit_message$\n" - " $name$_ = value.getNumber();\n" - "}\n"); + "private void set$capitalized_name$($type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" + " $set_has_field_bit_message$\n" + " $name$_ = value.getNumber();\n" + "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $clear_has_field_bit_message$\n" - " $name$_ = $default_number$;\n" - "}\n"); + "private void clear$capitalized_name$() {\n" + " $clear_has_field_bit_message$\n" + " $name$_ = $default_number$;\n" + "}\n"); } -void ImmutableEnumFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void ImmutableEnumFieldLiteGenerator::GenerateBuilderMembers( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return instance.has$capitalized_name$();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" - " return instance.get$capitalized_name$Value();\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" + " return instance.get$capitalized_name$Value();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder " - "${$set$capitalized_name$Value$}$(int value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$Value(value);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder " + "${$set$capitalized_name$Value$}$(int value) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$Value(value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " return instance.get$capitalized_name$();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder " + "${$set$capitalized_name$$}$($type$ value) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$(value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " copyOnWrite();\n" + " instance.clear$capitalized_name$();\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } -void ImmutableEnumFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for enums -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const { +void ImmutableEnumFieldLiteGenerator::GenerateInitializationCode( + io::Printer* printer) const { if (!IsDefaultValueJavaDefault(descriptor_)) { printer->Print(variables_, "$name$_ = $default_number$;\n"); } } -void ImmutableEnumFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { +void ImmutableEnumFieldLiteGenerator::GenerateFieldInfo( + io::Printer* printer, std::vector* output) const { + WriteIntToUtf16CharSequence(descriptor_->number(), output); + WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_), + output); if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "$name$_ = visitor.visitInt(has$capitalized_name$(), $name$_,\n" - " other.has$capitalized_name$(), other.$name$_);\n"); - } else if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "$name$_ = visitor.visitInt($name$_ != $default_number$, $name$_," - " other.$name$_ != $default_number$, other.$name$_);\n"); - } else { - GOOGLE_LOG(FATAL) << "Can't reach here."; + WriteIntToUtf16CharSequence(messageBitIndex_, output); + } + printer->Print(variables_, "\"$name$_\",\n"); + if (SupportFieldPresence(descriptor_->file())) { + PrintEnumVerifierLogic(printer, descriptor_, variables_, + /*var_name=*/"$type$", + /*terminating_string=*/",\n", + /*enforce_lite=*/context_->EnforceLite()); } } -void ImmutableEnumFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - // noop for scalars -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "$set_has_field_bit_message$\n" - "$name$_ = rawValue;\n"); - } else { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "$type$ value = $type$.forNumber(rawValue);\n" - "if (value == null) {\n" - " super.mergeVarintField($number$, rawValue);\n" - "} else {\n" - " $set_has_field_bit_message$\n" - " $name$_ = rawValue;\n" - "}\n"); - } -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - // noop for enums -} - - -void ImmutableEnumFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " output.writeEnum($number$, $name$_);\n" - "}\n"); -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeEnumSize($number$, $name$_);\n" - "}\n"); -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && $name$_ == other.$name$_;\n"); -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n" - "hash = (53 * hash) + $name$_;\n"); -} - -string ImmutableEnumFieldLiteGenerator::GetBoxedType() const { +std::string ImmutableEnumFieldLiteGenerator::GetBoxedType() const { return name_resolver_->GetImmutableClassName(descriptor_->enum_type()); } // =================================================================== -ImmutableEnumOneofFieldLiteGenerator:: -ImmutableEnumOneofFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableEnumFieldLiteGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { +ImmutableEnumOneofFieldLiteGenerator::ImmutableEnumOneofFieldLiteGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, Context* context) + : ImmutableEnumFieldLiteGenerator(descriptor, messageBitIndex, context) { const OneofGeneratorInfo* info = context->GetOneofGeneratorInfo(descriptor->containing_oneof()); SetCommonOneofVariables(descriptor, info, &variables_); } -ImmutableEnumOneofFieldLiteGenerator:: -~ImmutableEnumOneofFieldLiteGenerator() {} +ImmutableEnumOneofFieldLiteGenerator::~ImmutableEnumOneofFieldLiteGenerator() {} -void ImmutableEnumOneofFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { +void ImmutableEnumOneofFieldLiteGenerator::GenerateMembers( + io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $has_oneof_case_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return (java.lang.Integer) $oneof_name$_;\n" - " }\n" - " return $default_number$;\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" + " if ($has_oneof_case_message$) {\n" + " return (java.lang.Integer) $oneof_name$_;\n" + " }\n" + " return $default_number$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " $type$ result = $type$.forNumber((java.lang.Integer) $oneof_name$_);\n" - " return result == null ? $unknown$ : result;\n" - " }\n" - " return $default$;\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " if ($has_oneof_case_message$) {\n" + " $type$ result = $type$.forNumber((java.lang.Integer) " + "$oneof_name$_);\n" + " return result == null ? $unknown$ : result;\n" + " }\n" + " return $default$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Generate private setters for the builder to proxy into. if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void set$capitalized_name$Value(int value) {\n" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value;\n" - "}\n"); + "private void set$capitalized_name$Value(int value) {\n" + " $set_oneof_case_message$;\n" + " $oneof_name$_ = value;\n" + "}\n"); } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void set$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value.getNumber();\n" - "}\n"); + "private void set$capitalized_name$($type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" + " $set_oneof_case_message$;\n" + " $oneof_name$_ = value.getNumber();\n" + "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " }\n" - "}\n"); + "private void clear$capitalized_name$() {\n" + " if ($has_oneof_case_message$) {\n" + " $clear_oneof_case_message$;\n" + " $oneof_name$_ = null;\n" + " }\n" + "}\n"); } +void ImmutableEnumOneofFieldLiteGenerator::GenerateFieldInfo( + io::Printer* printer, std::vector* output) const { + WriteIntToUtf16CharSequence(descriptor_->number(), output); + WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_), + output); + WriteIntToUtf16CharSequence(descriptor_->containing_oneof()->index(), output); + if (SupportFieldPresence(descriptor_->file())) { + PrintEnumVerifierLogic(printer, descriptor_, variables_, + /*var_name=*/"$type$", + /*terminating_string=*/",\n", + /*enforce_lite=*/context_->EnforceLite()); + } +} -void ImmutableEnumOneofFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void ImmutableEnumOneofFieldLiteGenerator::GenerateBuilderMembers( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return instance.has$capitalized_name$();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" - " return instance.get$capitalized_name$Value();\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" + " return instance.get$capitalized_name$Value();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder " - "${$set$capitalized_name$Value$}$(int value) {\n" + "$deprecation$public Builder " + "${$set$capitalized_name$Value$}$(int value) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$Value(value);\n" + " return this;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + } + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " return instance.get$capitalized_name$();\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$public Builder " + "${$set$capitalized_name$$}$($type$ value) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$(value);\n" + " return this;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" " copyOnWrite();\n" - " instance.set$capitalized_name$Value(value);\n" + " instance.clear$capitalized_name$();\n" " return this;\n" "}\n"); - printer->Annotate("{", "}", descriptor_); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutableEnumOneofFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$oneof_name$_ = visitor.visitOneofInt(\n" - " $has_oneof_case_message$, $oneof_name$_, other.$oneof_name$_);\n"); -} - -void ImmutableEnumOneofFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "$set_oneof_case_message$;\n" - "$oneof_name$_ = rawValue;\n"); - } else { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "$type$ value = $type$.forNumber(rawValue);\n" - "if (value == null) {\n" - " super.mergeVarintField($number$, rawValue);\n" - "} else {\n" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = rawValue;\n" - "}\n"); - } -} - -void ImmutableEnumOneofFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.writeEnum($number$, ((java.lang.Integer) $oneof_name$_));\n" - "}\n"); -} - -void ImmutableEnumOneofFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeEnumSize($number$, ((java.lang.Integer) $oneof_name$_));\n" - "}\n"); -} - -void ImmutableEnumOneofFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "result = result && get$capitalized_name$Value()\n" - " == other.get$capitalized_name$Value();\n"); - } else { - printer->Print(variables_, - "result = result && get$capitalized_name$()\n" - " .equals(other.get$capitalized_name$());\n"); - } -} - -void ImmutableEnumOneofFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n" - "hash = (53 * hash) + get$capitalized_name$Value();\n"); - } else { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n" - "hash = (53 * hash) + get$capitalized_name$().getNumber();\n"); - } } // =================================================================== RepeatedImmutableEnumFieldLiteGenerator:: -RepeatedImmutableEnumFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetEnumVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); + RepeatedImmutableEnumFieldLiteGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, + Context* context) + : descriptor_(descriptor), + context_(context), + name_resolver_(context->GetNameResolver()) { + SetEnumVariables(descriptor, messageBitIndex, 0, + context->GetFieldGeneratorInfo(descriptor), name_resolver_, + &variables_); } RepeatedImmutableEnumFieldLiteGenerator:: -~RepeatedImmutableEnumFieldLiteGenerator() {} + ~RepeatedImmutableEnumFieldLiteGenerator() {} int RepeatedImmutableEnumFieldLiteGenerator::GetNumBitsForMessage() const { return 0; } -int RepeatedImmutableEnumFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { +void RepeatedImmutableEnumFieldLiteGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$java.util.List<$type$> get$capitalized_name$List();\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$java.util.List<$type$> get$capitalized_name$List();\n"); + "$deprecation$int get$capitalized_name$Count();\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$(int index);\n"); + "$deprecation$$type$ get$capitalized_name$(int index);\n"); if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$java.util.List\n" - "get$capitalized_name$ValueList();\n"); + "$deprecation$java.util.List\n" + "get$capitalized_name$ValueList();\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$int get$capitalized_name$Value(int index);\n"); + "$deprecation$int get$capitalized_name$Value(int index);\n"); } } -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private com.google.protobuf.Internal.IntList $name$_;\n" - "private static final com.google.protobuf.Internal.ListAdapter.Converter<\n" - " java.lang.Integer, $type$> $name$_converter_ =\n" - " new com.google.protobuf.Internal.ListAdapter.Converter<\n" - " java.lang.Integer, $type$>() {\n" - " @java.lang.Override\n" - " public $type$ convert(java.lang.Integer from) {\n" - " $type$ result = $type$.forNumber(from);\n" - " return result == null ? $unknown$ : result;\n" - " }\n" - " };\n"); +void RepeatedImmutableEnumFieldLiteGenerator::GenerateMembers( + io::Printer* printer) const { + printer->Print( + variables_, + "private com.google.protobuf.Internal.IntList $name$_;\n" + "private static final " + "com.google.protobuf.Internal.ListAdapter.Converter<\n" + " java.lang.Integer, $type$> $name$_converter_ =\n" + " new com.google.protobuf.Internal.ListAdapter.Converter<\n" + " java.lang.Integer, $type$>() {\n" + " @java.lang.Override\n" + " public $type$ convert(java.lang.Integer from) {\n" + " $type$ result = $type$.forNumber(from);\n" + " return result == null ? $unknown$ : result;\n" + " }\n" + " };\n"); PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List<$type$> " - "${$get$capitalized_name$List$}$() {\n" - " return new com.google.protobuf.Internal.ListAdapter<\n" - " java.lang.Integer, $type$>($name$_, $name$_converter_);\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public java.util.List<$type$> " + "${$get$capitalized_name$List$}$() {\n" + " return new com.google.protobuf.Internal.ListAdapter<\n" + " java.lang.Integer, $type$>($name$_, $name$_converter_);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" + " return $name$_.size();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return $name$_converter_.convert($name$_.getInt(index));\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" + " return $name$_converter_.convert($name$_.getInt(index));\n" + "}\n"); printer->Annotate("{", "}", descriptor_); if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List\n" - "${$get$capitalized_name$ValueList$}$() {\n" - " return $name$_;\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public java.util.List\n" + "${$get$capitalized_name$ValueList$}$() {\n" + " return $name$_;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n" - " return $name$_.getInt(index);\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public int " + "${$get$capitalized_name$Value$}$(int index) {\n" + " return $name$_.getInt(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } - if (descriptor_->is_packed() && + if (!EnableExperimentalRuntimeForLite() && descriptor_->is_packed() && context_->HasGeneratedMethods(descriptor_->containing_type())) { - printer->Print(variables_, - "private int $name$MemoizedSerializedSize;\n"); + printer->Print(variables_, "private int $name$MemoizedSerializedSize;\n"); } // Generate private setters for the builder to proxy into. - printer->Print(variables_, - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - " }\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " int index, $type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.setInt(index, value.getNumber());\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.addInt(value.getNumber());\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void addAll$capitalized_name$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " for ($type$ value : values) {\n" - " $name$_.addInt(value.getNumber());\n" - " }\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $name$_ = emptyIntList();\n" - "}\n"); - - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$Value(\n" - " int index, int value) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.setInt(index, value);\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$Value(int value) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.addInt(value);\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void addAll$capitalized_name$Value(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " for (int value : values) {\n" - " $name$_.addInt(value);\n" + printer->Print( + variables_, + "private void ensure$capitalized_name$IsMutable() {\n" + " if (!$is_mutable$) {\n" + " $name$_ =\n" + " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" " }\n" "}\n"); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "private void set$capitalized_name$(\n" + " int index, $type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.setInt(index, value.getNumber());\n" + "}\n"); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "private void add$capitalized_name$($type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.addInt(value.getNumber());\n" + "}\n"); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "private void addAll$capitalized_name$(\n" + " java.lang.Iterable values) {\n" + " ensure$capitalized_name$IsMutable();\n" + " for ($type$ value : values) {\n" + " $name$_.addInt(value.getNumber());\n" + " }\n" + "}\n"); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "private void clear$capitalized_name$() {\n" + " $name$_ = emptyIntList();\n" + "}\n"); + + if (SupportUnknownEnumValue(descriptor_->file())) { + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "private void set$capitalized_name$Value(\n" + " int index, int value) {\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.setInt(index, value);\n" + "}\n"); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "private void add$capitalized_name$Value(int value) {\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.addInt(value);\n" + "}\n"); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "private void addAll$capitalized_name$Value(\n" + " java.lang.Iterable values) {\n" + " ensure$capitalized_name$IsMutable();\n" + " for (int value : values) {\n" + " $name$_.addInt(value);\n" + " }\n" + "}\n"); } } +void RepeatedImmutableEnumFieldLiteGenerator::GenerateFieldInfo( + io::Printer* printer, std::vector* output) const { + WriteIntToUtf16CharSequence(descriptor_->number(), output); + WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_), + output); + printer->Print(variables_, "\"$name$_\",\n"); + if (SupportFieldPresence(descriptor_->file())) { + PrintEnumVerifierLogic(printer, descriptor_, variables_, + /*var_name=*/"$type$", + /*terminating_string=*/",\n", + /*enforce_lite=*/context_->EnforceLite()); + } +} -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void RepeatedImmutableEnumFieldLiteGenerator::GenerateBuilderMembers( + io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List<$type$> " - "${$get$capitalized_name$List$}$() {\n" - " return instance.get$capitalized_name$List();\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public java.util.List<$type$> " + "${$get$capitalized_name$List$}$() {\n" + " return instance.get$capitalized_name$List();\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" + " return instance.get$capitalized_name$Count();\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" + " return instance.get$capitalized_name$(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return instance.get$capitalized_name$Count();\n" - "}\n"); + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " int index, $type$ value) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$(index, value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return instance.get$capitalized_name$(index);\n" - "}\n"); + "$deprecation$public Builder " + "${$add$capitalized_name$$}$($type$ value) {\n" + " copyOnWrite();\n" + " instance.add$capitalized_name$(value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, $type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(index, value);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" + " java.lang.Iterable values) {\n" + " copyOnWrite();\n" + " instance.addAll$capitalized_name$(values);" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" - " java.lang.Iterable values) {\n" - " copyOnWrite();\n" - " instance.addAll$capitalized_name$(values);" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " copyOnWrite();\n" + " instance.clear$capitalized_name$();\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List\n" - "${$get$capitalized_name$ValueList$}$() {\n" - " return java.util.Collections.unmodifiableList(\n" - " instance.get$capitalized_name$ValueList());\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public java.util.List\n" + "${$get$capitalized_name$ValueList$}$() {\n" + " return java.util.Collections.unmodifiableList(\n" + " instance.get$capitalized_name$ValueList());\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n" - " return instance.get$capitalized_name$Value(index);\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public int " + "${$get$capitalized_name$Value$}$(int index) {\n" + " return instance.get$capitalized_name$Value(index);\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public Builder ${$set$capitalized_name$Value$}$(\n" + " int index, int value) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$Value(index, value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$Value$}$(\n" - " int index, int value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$Value(index, value);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder " + "${$add$capitalized_name$Value$}$(int value) {\n" + " instance.add$capitalized_name$Value(value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder " - "${$add$capitalized_name$Value$}$(int value) {\n" - " instance.add$capitalized_name$Value(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$Value$}$(\n" - " java.lang.Iterable values) {\n" - " copyOnWrite();\n" - " instance.addAll$capitalized_name$Value(values);\n" - " return this;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$addAll$capitalized_name$Value$}$(\n" + " java.lang.Iterable values) {\n" + " copyOnWrite();\n" + " instance.addAll$capitalized_name$Value(values);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } } -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for enums -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const { +void RepeatedImmutableEnumFieldLiteGenerator::GenerateInitializationCode( + io::Printer* printer) const { printer->Print(variables_, "$name$_ = emptyIntList();\n"); } -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_= visitor.visitIntList($name$_, other.$name$_);\n"); -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_.makeImmutable();\n"); -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - // Read and store the enum - printer->Print(variables_, - "if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - "}\n"); - - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "$name$_.addInt(input.readEnum());\n"); - } else { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "$type$ value = $type$.forNumber(rawValue);\n" - "if (value == null) {\n" - // We store the unknown value in unknown fields. - " super.mergeVarintField($number$, rawValue);\n" - "} else {\n" - " $name$_.addInt(rawValue);\n" - "}\n"); - } -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateParsingCodeFromPacked(io::Printer* printer) const { - printer->Print(variables_, - "if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - "}\n"); - - printer->Print(variables_, - "int length = input.readRawVarint32();\n" - "int oldLimit = input.pushLimit(length);\n" - "while(input.getBytesUntilLimit() > 0) {\n"); - printer->Indent(); - - // Read and store the enum - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "$name$_.addInt(input.readEnum());\n"); - } else { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "$type$ value = $type$.forNumber(rawValue);\n" - "if (value == null) {\n" - // We store the unknown value in unknown fields. - " super.mergeVarintField($number$, rawValue);\n" - "} else {\n" - " $name$_.addInt(rawValue);\n" - "}\n"); - } - - printer->Outdent(); - printer->Print(variables_, - "}\n" - "input.popLimit(oldLimit);\n"); -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_mutable$) {\n" - " $name$_.makeImmutable();\n" - "}\n"); -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - if (descriptor_->is_packed()) { - printer->Print(variables_, - "if (get$capitalized_name$List().size() > 0) {\n" - " output.writeUInt32NoTag($tag$);\n" - " output.writeUInt32NoTag($name$MemoizedSerializedSize);\n" - "}\n" - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.writeEnumNoTag($name$_.getInt(i));\n" - "}\n"); - } else { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.writeEnum($number$, $name$_.getInt(i));\n" - "}\n"); - } -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "{\n" - " int dataSize = 0;\n"); - printer->Indent(); - - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " dataSize += com.google.protobuf.CodedOutputStream\n" - " .computeEnumSizeNoTag($name$_.getInt(i));\n" - "}\n"); - printer->Print( - "size += dataSize;\n"); - if (descriptor_->is_packed()) { - printer->Print(variables_, - "if (!get$capitalized_name$List().isEmpty()) {" - " size += $tag_size$;\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeUInt32SizeNoTag(dataSize);\n" - "}"); - } else { - printer->Print(variables_, - "size += $tag_size$ * $name$_.size();\n"); - } - - // cache the data size for packed fields. - if (descriptor_->is_packed()) { - printer->Print(variables_, - "$name$MemoizedSerializedSize = dataSize;\n"); - } - - printer->Outdent(); - printer->Print("}\n"); -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && $name$_.equals(other.$name$_);\n"); -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "if (get$capitalized_name$Count() > 0) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + $name$_.hashCode();\n" - "}\n"); -} - -string RepeatedImmutableEnumFieldLiteGenerator::GetBoxedType() const { +std::string RepeatedImmutableEnumFieldLiteGenerator::GetBoxedType() const { return name_resolver_->GetImmutableClassName(descriptor_->enum_type()); } diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_field_lite.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_field_lite.h index fa004720..b5e98077 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_field_lite.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_field_lite.h @@ -41,49 +41,43 @@ namespace google { namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } -} +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { class ImmutableEnumFieldLiteGenerator : public ImmutableFieldLiteGenerator { public: - explicit ImmutableEnumFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + explicit ImmutableEnumFieldLiteGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, + Context* context); ~ImmutableEnumFieldLiteGenerator(); - // implements ImmutableFieldLiteGenerator ------------------------------------ + // implements ImmutableFieldLiteGenerator + // ------------------------------------ int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; void GenerateInterfaceMembers(io::Printer* printer) const; void GenerateMembers(io::Printer* printer) const; void GenerateBuilderMembers(io::Printer* printer) const; void GenerateInitializationCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; + void GenerateFieldInfo(io::Printer* printer, + std::vector* output) const; - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; - const int builderBitIndex_; Context* context_; ClassNameResolver* name_resolver_; @@ -94,19 +88,14 @@ class ImmutableEnumFieldLiteGenerator : public ImmutableFieldLiteGenerator { class ImmutableEnumOneofFieldLiteGenerator : public ImmutableEnumFieldLiteGenerator { public: - ImmutableEnumOneofFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + ImmutableEnumOneofFieldLiteGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, Context* context); ~ImmutableEnumOneofFieldLiteGenerator(); void GenerateMembers(io::Printer* printer) const; void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; + void GenerateFieldInfo(io::Printer* printer, + std::vector* output) const; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableEnumOneofFieldLiteGenerator); @@ -116,35 +105,23 @@ class RepeatedImmutableEnumFieldLiteGenerator : public ImmutableFieldLiteGenerator { public: explicit RepeatedImmutableEnumFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + const FieldDescriptor* descriptor, int messageBitIndex, Context* context); ~RepeatedImmutableEnumFieldLiteGenerator(); // implements ImmutableFieldLiteGenerator ------------------------------------ int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; void GenerateInterfaceMembers(io::Printer* printer) const; void GenerateMembers(io::Printer* printer) const; void GenerateBuilderMembers(io::Printer* printer) const; void GenerateInitializationCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingCodeFromPacked(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; + void GenerateFieldInfo(io::Printer* printer, + std::vector* output) const; - string GetBoxedType() const; + std::string GetBoxedType() const; private: const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; + std::map variables_; Context* context_; ClassNameResolver* name_resolver_; @@ -154,6 +131,6 @@ class RepeatedImmutableEnumFieldLiteGenerator } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_LITE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_lite.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_lite.cc index 806008ee..a00624b5 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_lite.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_lite.cc @@ -44,6 +44,8 @@ #include #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -58,7 +60,7 @@ EnumLiteGenerator::EnumLiteGenerator(const EnumDescriptor* descriptor, for (int i = 0; i < descriptor_->value_count(); i++) { const EnumValueDescriptor* value = descriptor_->value(i); const EnumValueDescriptor* canonical_value = - descriptor_->FindValueByNumber(value->number()); + descriptor_->FindValueByNumber(value->number()); if (value == canonical_value) { canonical_values_.push_back(value); @@ -84,15 +86,14 @@ void EnumLiteGenerator::Generate(io::Printer* printer) { printer->Indent(); for (int i = 0; i < canonical_values_.size(); i++) { - std::map vars; + std::map vars; vars["name"] = canonical_values_[i]->name(); - vars["number"] = SimpleItoa(canonical_values_[i]->number()); + vars["number"] = StrCat(canonical_values_[i]->number()); WriteEnumValueDocComment(printer, canonical_values_[i]); if (canonical_values_[i]->options().deprecated()) { printer->Print("@java.lang.Deprecated\n"); } - printer->Print(vars, - "$name$($number$),\n"); + printer->Print(vars, "$name$($number$),\n"); printer->Annotate("name", canonical_values_[i]); } @@ -102,31 +103,31 @@ void EnumLiteGenerator::Generate(io::Printer* printer) { } printer->Print( - ";\n" - "\n"); + ";\n" + "\n"); // ----------------------------------------------------------------- for (int i = 0; i < aliases_.size(); i++) { - std::map vars; + std::map vars; vars["classname"] = descriptor_->name(); vars["name"] = aliases_[i].value->name(); vars["canonical_name"] = aliases_[i].canonical_value->name(); WriteEnumValueDocComment(printer, aliases_[i].value); - printer->Print(vars, - "public static final $classname$ $name$ = $canonical_name$;\n"); + printer->Print( + vars, "public static final $classname$ $name$ = $canonical_name$;\n"); printer->Annotate("name", aliases_[i].value); } for (int i = 0; i < descriptor_->value_count(); i++) { - std::map vars; + std::map vars; vars["name"] = descriptor_->value(i)->name(); - vars["number"] = SimpleItoa(descriptor_->value(i)->number()); + vars["number"] = StrCat(descriptor_->value(i)->number()); vars["{"] = ""; vars["}"] = ""; WriteEnumValueDocComment(printer, descriptor_->value(i)); printer->Print(vars, - "public static final int ${$$name$_VALUE$}$ = $number$;\n"); + "public static final int ${$$name$_VALUE$}$ = $number$;\n"); printer->Annotate("{", "}", descriptor_->value(i)); } printer->Print("\n"); @@ -163,63 +164,65 @@ void EnumLiteGenerator::Generate(io::Printer* printer) { printer->Indent(); for (int i = 0; i < canonical_values_.size(); i++) { - printer->Print( - "case $number$: return $name$;\n", - "name", canonical_values_[i]->name(), - "number", SimpleItoa(canonical_values_[i]->number())); + printer->Print("case $number$: return $name$;\n", "name", + canonical_values_[i]->name(), "number", + StrCat(canonical_values_[i]->number())); } printer->Outdent(); printer->Outdent(); printer->Print( - " default: return null;\n" - " }\n" - "}\n" - "\n" - "public static com.google.protobuf.Internal.EnumLiteMap<$classname$>\n" - " internalGetValueMap() {\n" - " return internalValueMap;\n" - "}\n" - "private static final com.google.protobuf.Internal.EnumLiteMap<\n" - " $classname$> internalValueMap =\n" - " new com.google.protobuf.Internal.EnumLiteMap<$classname$>() {\n" - " @java.lang.Override\n" - " public $classname$ findValueByNumber(int number) {\n" - " return $classname$.forNumber(number);\n" - " }\n" - " };\n" - "\n", - "classname", descriptor_->name()); + " default: return null;\n" + " }\n" + "}\n" + "\n" + "public static com.google.protobuf.Internal.EnumLiteMap<$classname$>\n" + " internalGetValueMap() {\n" + " return internalValueMap;\n" + "}\n" + "private static final com.google.protobuf.Internal.EnumLiteMap<\n" + " $classname$> internalValueMap =\n" + " new com.google.protobuf.Internal.EnumLiteMap<$classname$>() {\n" + " @java.lang.Override\n" + " public $classname$ findValueByNumber(int number) {\n" + " return $classname$.forNumber(number);\n" + " }\n" + " };\n" + "\n" + "public static com.google.protobuf.Internal.EnumVerifier \n" + " internalGetVerifier() {\n" + " return $classname$Verifier.INSTANCE;\n" + "}\n" + "\n" + "private static final class $classname$Verifier implements \n" + " com.google.protobuf.Internal.EnumVerifier { \n" + " static final com.google.protobuf.Internal.EnumVerifier " + " INSTANCE = new $classname$Verifier();\n" + " @java.lang.Override\n" + " public boolean isInRange(int number) {\n" + " return $classname$.forNumber(number) != null;\n" + " }\n" + " };\n" + "\n", + "classname", descriptor_->name()); printer->Print( - "private final int value;\n\n" - "private $classname$(int value) {\n", - "classname", descriptor_->name()); + "private final int value;\n\n" + "private $classname$(int value) {\n", + "classname", descriptor_->name()); printer->Print( - " this.value = value;\n" - "}\n"); + " this.value = value;\n" + "}\n"); printer->Print( - "\n" - "// @@protoc_insertion_point(enum_scope:$full_name$)\n", - "full_name", descriptor_->full_name()); + "\n" + "// @@protoc_insertion_point(enum_scope:$full_name$)\n", + "full_name", descriptor_->full_name()); printer->Outdent(); printer->Print("}\n\n"); } -bool EnumLiteGenerator::CanUseEnumValues() { - if (canonical_values_.size() != descriptor_->value_count()) { - return false; - } - for (int i = 0; i < descriptor_->value_count(); i++) { - if (descriptor_->value(i)->name() != canonical_values_[i]->name()) { - return false; - } - } - return true; -} - } // namespace java } // namespace compiler } // namespace protobuf diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_lite.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_lite.h index b7be912c..50f3fe7b 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_lite.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_enum_lite.h @@ -41,17 +41,19 @@ namespace google { namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +namespace io { +class Printer; // printer.h } +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { @@ -67,9 +69,9 @@ class EnumLiteGenerator { private: const EnumDescriptor* descriptor_; - // The proto language allows multiple enum constants to have the same numeric - // value. Java, however, does not allow multiple enum constants to be - // considered equivalent. We treat the first defined constant for any + // The proto language allows multiple enum constants to have the same + // numeric value. Java, however, does not allow multiple enum constants to + // be considered equivalent. We treat the first defined constant for any // given numeric value as "canonical" and the rest as aliases of that // canonical value. std::vector canonical_values_; @@ -85,14 +87,12 @@ class EnumLiteGenerator { Context* context_; ClassNameResolver* name_resolver_; - bool CanUseEnumValues(); - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumLiteGenerator); }; } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_LITE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_extension.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_extension.cc index 3eb1370d..3ad64e06 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_extension.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_extension.cc @@ -41,6 +41,7 @@ #include #include + namespace google { namespace protobuf { namespace compiler { @@ -48,11 +49,10 @@ namespace java { ImmutableExtensionGenerator::ImmutableExtensionGenerator( const FieldDescriptor* descriptor, Context* context) - : descriptor_(descriptor), context_(context), - name_resolver_(context->GetNameResolver()) { + : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) { if (descriptor_->extension_scope() != NULL) { - scope_ = name_resolver_->GetImmutableClassName( - descriptor_->extension_scope()); + scope_ = + name_resolver_->GetImmutableClassName(descriptor_->extension_scope()); } else { scope_ = name_resolver_->GetImmutableClassName(descriptor_->file()); } @@ -62,34 +62,36 @@ ImmutableExtensionGenerator::~ImmutableExtensionGenerator() {} // Initializes the vars referenced in the generated code templates. void ExtensionGenerator::InitTemplateVars( - const FieldDescriptor* descriptor, const string& scope, bool immutable, - ClassNameResolver* name_resolver, std::map* vars_pointer) { - std::map &vars = *vars_pointer; + const FieldDescriptor* descriptor, const std::string& scope, bool immutable, + ClassNameResolver* name_resolver, + std::map* vars_pointer) { + std::map& vars = *vars_pointer; vars["scope"] = scope; - vars["name"] = UnderscoresToCamelCase(descriptor); + vars["name"] = UnderscoresToCamelCaseCheckReserved(descriptor); vars["containing_type"] = name_resolver->GetClassName(descriptor->containing_type(), immutable); - vars["number"] = SimpleItoa(descriptor->number()); + vars["number"] = StrCat(descriptor->number()); vars["constant_name"] = FieldConstantName(descriptor); - vars["index"] = SimpleItoa(descriptor->index()); - vars["default"] = descriptor->is_repeated() ? - "" : DefaultValue(descriptor, immutable, name_resolver); + vars["index"] = StrCat(descriptor->index()); + vars["default"] = descriptor->is_repeated() + ? "" + : DefaultValue(descriptor, immutable, name_resolver); vars["type_constant"] = FieldTypeName(GetType(descriptor)); vars["packed"] = descriptor->is_packed() ? "true" : "false"; vars["enum_map"] = "null"; vars["prototype"] = "null"; JavaType java_type = GetJavaType(descriptor); - string singular_type; + std::string singular_type; switch (java_type) { case JAVATYPE_MESSAGE: - singular_type = name_resolver->GetClassName(descriptor->message_type(), - immutable); + singular_type = + name_resolver->GetClassName(descriptor->message_type(), immutable); vars["prototype"] = singular_type + ".getDefaultInstance()"; break; case JAVATYPE_ENUM: - singular_type = name_resolver->GetClassName(descriptor->enum_type(), - immutable); + singular_type = + name_resolver->GetClassName(descriptor->enum_type(), immutable); vars["enum_map"] = singular_type + ".internalGetValueMap()"; break; case JAVATYPE_STRING: @@ -102,18 +104,18 @@ void ExtensionGenerator::InitTemplateVars( singular_type = BoxedPrimitiveTypeName(java_type); break; } - vars["type"] = descriptor->is_repeated() ? - "java.util.List<" + singular_type + ">" : singular_type; + vars["type"] = descriptor->is_repeated() + ? "java.util.List<" + singular_type + ">" + : singular_type; vars["singular_type"] = singular_type; } void ImmutableExtensionGenerator::Generate(io::Printer* printer) { - std::map vars; + std::map vars; const bool kUseImmutableNames = true; InitTemplateVars(descriptor_, scope_, kUseImmutableNames, name_resolver_, &vars); - printer->Print(vars, - "public static final int $constant_name$ = $number$;\n"); + printer->Print(vars, "public static final int $constant_name$ = $number$;\n"); WriteFieldDocComment(printer, descriptor_); if (descriptor_->extension_scope() == NULL) { @@ -151,8 +153,8 @@ int ImmutableExtensionGenerator::GenerateNonNestedInitializationCode( // Only applies to non-nested extensions. printer->Print( "$name$.internalInit(descriptor.getExtensions().get($index$));\n", - "name", UnderscoresToCamelCase(descriptor_), - "index", SimpleItoa(descriptor_->index())); + "name", UnderscoresToCamelCaseCheckReserved(descriptor_), "index", + StrCat(descriptor_->index())); bytecode_estimate += 21; } return bytecode_estimate; @@ -160,10 +162,8 @@ int ImmutableExtensionGenerator::GenerateNonNestedInitializationCode( int ImmutableExtensionGenerator::GenerateRegistrationCode( io::Printer* printer) { - printer->Print( - "registry.add($scope$.$name$);\n", - "scope", scope_, - "name", UnderscoresToCamelCase(descriptor_)); + printer->Print("registry.add($scope$.$name$);\n", "scope", scope_, "name", + UnderscoresToCamelCaseCheckReserved(descriptor_)); return 7; } diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_extension.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_extension.h index fb8d5201..ab878907 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_extension.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_extension.h @@ -42,18 +42,20 @@ namespace google { namespace protobuf { - class FieldDescriptor; // descriptor.h - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } +class FieldDescriptor; // descriptor.h +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +namespace io { +class Printer; // printer.h } +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { @@ -68,18 +70,19 @@ class ExtensionGenerator { virtual void Generate(io::Printer* printer) = 0; - // Returns an estimate of the number of bytes the printed code will compile to + // Returns an estimate of the number of bytes the printed code will compile + // to virtual int GenerateNonNestedInitializationCode(io::Printer* printer) = 0; - // Returns an estimate of the number of bytes the printed code will compile to + // Returns an estimate of the number of bytes the printed code will compile + // to virtual int GenerateRegistrationCode(io::Printer* printer) = 0; protected: - static void InitTemplateVars(const FieldDescriptor* descriptor, - const string& scope, - bool immutable, - ClassNameResolver* name_resolver, - std::map* vars_pointer); + static void InitTemplateVars( + const FieldDescriptor* descriptor, const std::string& scope, + bool immutable, ClassNameResolver* name_resolver, + std::map* vars_pointer); private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator); @@ -97,9 +100,8 @@ class ImmutableExtensionGenerator : public ExtensionGenerator { protected: const FieldDescriptor* descriptor_; - Context* context_; ClassNameResolver* name_resolver_; - string scope_; + std::string scope_; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableExtensionGenerator); @@ -108,6 +110,6 @@ class ImmutableExtensionGenerator : public ExtensionGenerator { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_EXTENSION_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_extension_lite.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_extension_lite.cc index 70ce8e7d..71bf4e23 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_extension_lite.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_extension_lite.cc @@ -44,11 +44,10 @@ namespace java { ImmutableExtensionLiteGenerator::ImmutableExtensionLiteGenerator( const FieldDescriptor* descriptor, Context* context) - : descriptor_(descriptor), context_(context), - name_resolver_(context->GetNameResolver()) { + : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) { if (descriptor_->extension_scope() != NULL) { - scope_ = name_resolver_->GetImmutableClassName( - descriptor_->extension_scope()); + scope_ = + name_resolver_->GetImmutableClassName(descriptor_->extension_scope()); } else { scope_ = name_resolver_->GetImmutableClassName(descriptor_->file()); } @@ -57,12 +56,11 @@ ImmutableExtensionLiteGenerator::ImmutableExtensionLiteGenerator( ImmutableExtensionLiteGenerator::~ImmutableExtensionLiteGenerator() {} void ImmutableExtensionLiteGenerator::Generate(io::Printer* printer) { - std::map vars; + std::map vars; const bool kUseImmutableNames = true; InitTemplateVars(descriptor_, scope_, kUseImmutableNames, name_resolver_, &vars); - printer->Print(vars, - "public static final int $constant_name$ = $number$;\n"); + printer->Print(vars, "public static final int $constant_name$ = $number$;\n"); WriteFieldDocComment(printer, descriptor_); if (descriptor_->is_repeated()) { @@ -106,10 +104,8 @@ int ImmutableExtensionLiteGenerator::GenerateNonNestedInitializationCode( int ImmutableExtensionLiteGenerator::GenerateRegistrationCode( io::Printer* printer) { - printer->Print( - "registry.add($scope$.$name$);\n", - "scope", scope_, - "name", UnderscoresToCamelCase(descriptor_)); + printer->Print("registry.add($scope$.$name$);\n", "scope", scope_, "name", + UnderscoresToCamelCaseCheckReserved(descriptor_)); return 7; } diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_extension_lite.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_extension_lite.h index 4cd49bda..410781dd 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_extension_lite.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_extension_lite.h @@ -61,9 +61,8 @@ class ImmutableExtensionLiteGenerator : public ExtensionGenerator { private: const FieldDescriptor* descriptor_; - Context* context_; ClassNameResolver* name_resolver_; - string scope_; + std::string scope_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableExtensionLiteGenerator); }; @@ -71,6 +70,6 @@ class ImmutableExtensionLiteGenerator : public ExtensionGenerator { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_EXTENSION_LITE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_field.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_field.cc index 93de0229..18a86bad 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_field.cc @@ -55,6 +55,7 @@ #include + namespace google { namespace protobuf { namespace compiler { @@ -62,15 +63,16 @@ namespace java { namespace { -ImmutableFieldGenerator* MakeImmutableGenerator( - const FieldDescriptor* field, int messageBitIndex, int builderBitIndex, - Context* context) { +ImmutableFieldGenerator* MakeImmutableGenerator(const FieldDescriptor* field, + int messageBitIndex, + int builderBitIndex, + Context* context) { if (field->is_repeated()) { switch (GetJavaType(field)) { case JAVATYPE_MESSAGE: if (IsMapEntry(field->message_type())) { - return new ImmutableMapFieldGenerator( - field, messageBitIndex, builderBitIndex, context); + return new ImmutableMapFieldGenerator(field, messageBitIndex, + builderBitIndex, context); } else { return new RepeatedImmutableMessageFieldGenerator( field, messageBitIndex, builderBitIndex, context); @@ -92,8 +94,8 @@ ImmutableFieldGenerator* MakeImmutableGenerator( return new ImmutableMessageOneofFieldGenerator( field, messageBitIndex, builderBitIndex, context); case JAVATYPE_ENUM: - return new ImmutableEnumOneofFieldGenerator( - field, messageBitIndex, builderBitIndex, context); + return new ImmutableEnumOneofFieldGenerator(field, messageBitIndex, + builderBitIndex, context); case JAVATYPE_STRING: return new ImmutableStringOneofFieldGenerator( field, messageBitIndex, builderBitIndex, context); @@ -104,75 +106,74 @@ ImmutableFieldGenerator* MakeImmutableGenerator( } else { switch (GetJavaType(field)) { case JAVATYPE_MESSAGE: - return new ImmutableMessageFieldGenerator( - field, messageBitIndex, builderBitIndex, context); + return new ImmutableMessageFieldGenerator(field, messageBitIndex, + builderBitIndex, context); case JAVATYPE_ENUM: - return new ImmutableEnumFieldGenerator( - field, messageBitIndex, builderBitIndex, context); + return new ImmutableEnumFieldGenerator(field, messageBitIndex, + builderBitIndex, context); case JAVATYPE_STRING: - return new ImmutableStringFieldGenerator( - field, messageBitIndex, builderBitIndex, context); + return new ImmutableStringFieldGenerator(field, messageBitIndex, + builderBitIndex, context); default: - return new ImmutablePrimitiveFieldGenerator( - field, messageBitIndex, builderBitIndex, context); + return new ImmutablePrimitiveFieldGenerator(field, messageBitIndex, + builderBitIndex, context); } } } } ImmutableFieldLiteGenerator* MakeImmutableLiteGenerator( - const FieldDescriptor* field, int messageBitIndex, int builderBitIndex, - Context* context) { + const FieldDescriptor* field, int messageBitIndex, Context* context) { if (field->is_repeated()) { switch (GetJavaType(field)) { case JAVATYPE_MESSAGE: if (IsMapEntry(field->message_type())) { - return new ImmutableMapFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); + return new ImmutableMapFieldLiteGenerator(field, messageBitIndex, + context); } else { return new RepeatedImmutableMessageFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); + field, messageBitIndex, context); } case JAVATYPE_ENUM: return new RepeatedImmutableEnumFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); + field, messageBitIndex, context); case JAVATYPE_STRING: return new RepeatedImmutableStringFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); + field, messageBitIndex, context); default: return new RepeatedImmutablePrimitiveFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); + field, messageBitIndex, context); } } else { if (field->containing_oneof()) { switch (GetJavaType(field)) { case JAVATYPE_MESSAGE: return new ImmutableMessageOneofFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); + field, messageBitIndex, context); case JAVATYPE_ENUM: return new ImmutableEnumOneofFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); + field, messageBitIndex, context); case JAVATYPE_STRING: return new ImmutableStringOneofFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); + field, messageBitIndex, context); default: return new ImmutablePrimitiveOneofFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); + field, messageBitIndex, context); } } else { switch (GetJavaType(field)) { case JAVATYPE_MESSAGE: - return new ImmutableMessageFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); + return new ImmutableMessageFieldLiteGenerator(field, messageBitIndex, + context); case JAVATYPE_ENUM: - return new ImmutableEnumFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); + return new ImmutableEnumFieldLiteGenerator(field, messageBitIndex, + context); case JAVATYPE_STRING: - return new ImmutableStringFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); + return new ImmutableStringFieldLiteGenerator(field, messageBitIndex, + context); default: return new ImmutablePrimitiveFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); + field, messageBitIndex, context); } } } @@ -193,26 +194,19 @@ static inline void ReportUnexpectedPackedFieldsCall(io::Printer* printer) { ImmutableFieldGenerator::~ImmutableFieldGenerator() {} -void ImmutableFieldGenerator:: -GenerateParsingCodeFromPacked(io::Printer* printer) const { +void ImmutableFieldGenerator::GenerateParsingCodeFromPacked( + io::Printer* printer) const { ReportUnexpectedPackedFieldsCall(printer); } ImmutableFieldLiteGenerator::~ImmutableFieldLiteGenerator() {} -void ImmutableFieldLiteGenerator:: -GenerateParsingCodeFromPacked(io::Printer* printer) const { - ReportUnexpectedPackedFieldsCall(printer); -} - // =================================================================== template <> FieldGeneratorMap::FieldGeneratorMap( const Descriptor* descriptor, Context* context) - : descriptor_(descriptor), - field_generators_(descriptor->field_count()) { - + : descriptor_(descriptor), field_generators_(descriptor->field_count()) { // Construct all the FieldGenerators and assign them bit indices for their // bit fields. int messageBitIndex = 0; @@ -226,41 +220,38 @@ FieldGeneratorMap::FieldGeneratorMap( } } -template<> +template <> FieldGeneratorMap::~FieldGeneratorMap() {} template <> FieldGeneratorMap::FieldGeneratorMap( const Descriptor* descriptor, Context* context) - : descriptor_(descriptor), - field_generators_(descriptor->field_count()) { + : descriptor_(descriptor), field_generators_(descriptor->field_count()) { // Construct all the FieldGenerators and assign them bit indices for their // bit fields. int messageBitIndex = 0; - int builderBitIndex = 0; for (int i = 0; i < descriptor->field_count(); i++) { ImmutableFieldLiteGenerator* generator = MakeImmutableLiteGenerator( - descriptor->field(i), messageBitIndex, builderBitIndex, context); + descriptor->field(i), messageBitIndex, context); field_generators_[i].reset(generator); messageBitIndex += generator->GetNumBitsForMessage(); - builderBitIndex += generator->GetNumBitsForBuilder(); } } -template<> +template <> FieldGeneratorMap::~FieldGeneratorMap() {} void SetCommonFieldVariables(const FieldDescriptor* descriptor, const FieldGeneratorInfo* info, - std::map* variables) { + std::map* variables) { (*variables)["field_name"] = descriptor->name(); (*variables)["name"] = info->name; (*variables)["classname"] = descriptor->containing_type()->name(); (*variables)["capitalized_name"] = info->capitalized_name; (*variables)["disambiguated_reason"] = info->disambiguated_reason; (*variables)["constant_name"] = FieldConstantName(descriptor); - (*variables)["number"] = SimpleItoa(descriptor->number()); + (*variables)["number"] = StrCat(descriptor->number()); // These variables are placeholders to pick out the beginning and ends of // identifiers for annotations (when doing so with existing variables would // be ambiguous or impossible). They should never be set to anything but the @@ -271,22 +262,22 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor, void SetCommonOneofVariables(const FieldDescriptor* descriptor, const OneofGeneratorInfo* info, - std::map* variables) { + std::map* variables) { (*variables)["oneof_name"] = info->name; (*variables)["oneof_capitalized_name"] = info->capitalized_name; (*variables)["oneof_index"] = - SimpleItoa(descriptor->containing_oneof()->index()); - (*variables)["set_oneof_case_message"] = info->name + - "Case_ = " + SimpleItoa(descriptor->number()); - (*variables)["clear_oneof_case_message"] = info->name + - "Case_ = 0"; - (*variables)["has_oneof_case_message"] = info->name + - "Case_ == " + SimpleItoa(descriptor->number()); + StrCat(descriptor->containing_oneof()->index()); + (*variables)["oneof_stored_type"] = GetOneofStoredType(descriptor); + (*variables)["set_oneof_case_message"] = + info->name + "Case_ = " + StrCat(descriptor->number()); + (*variables)["clear_oneof_case_message"] = info->name + "Case_ = 0"; + (*variables)["has_oneof_case_message"] = + info->name + "Case_ == " + StrCat(descriptor->number()); } -void PrintExtraFieldInfo(const std::map& variables, +void PrintExtraFieldInfo(const std::map& variables, io::Printer* printer) { - const std::map::const_iterator it = + const std::map::const_iterator it = variables.find("disambiguated_reason"); if (it != variables.end() && !it->second.empty()) { printer->Print( diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_field.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_field.h index 7275c099..9d04dc84 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_field.h @@ -39,23 +39,25 @@ #include #include +#include #include #include -#include namespace google { namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +namespace io { +class Printer; // printer.h } +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { @@ -79,13 +81,13 @@ class ImmutableFieldGenerator { virtual void GenerateParsingDoneCode(io::Printer* printer) const = 0; virtual void GenerateSerializationCode(io::Printer* printer) const = 0; virtual void GenerateSerializedSizeCode(io::Printer* printer) const = 0; - virtual void GenerateFieldBuilderInitializationCode(io::Printer* printer) - const = 0; + virtual void GenerateFieldBuilderInitializationCode( + io::Printer* printer) const = 0; virtual void GenerateEqualsCode(io::Printer* printer) const = 0; virtual void GenerateHashCode(io::Printer* printer) const = 0; - virtual string GetBoxedType() const = 0; + virtual std::string GetBoxedType() const = 0; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableFieldGenerator); @@ -97,27 +99,14 @@ class ImmutableFieldLiteGenerator { virtual ~ImmutableFieldLiteGenerator(); virtual int GetNumBitsForMessage() const = 0; - virtual int GetNumBitsForBuilder() const = 0; virtual void GenerateInterfaceMembers(io::Printer* printer) const = 0; virtual void GenerateMembers(io::Printer* printer) const = 0; virtual void GenerateBuilderMembers(io::Printer* printer) const = 0; virtual void GenerateInitializationCode(io::Printer* printer) const = 0; - virtual void GenerateVisitCode(io::Printer* printer) const = 0; - virtual void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) - const = 0; - virtual void GenerateParsingCode(io::Printer* printer) const = 0; - virtual void GenerateParsingCodeFromPacked(io::Printer* printer) const; - virtual void GenerateParsingDoneCode(io::Printer* printer) const = 0; - virtual void GenerateSerializationCode(io::Printer* printer) const = 0; - virtual void GenerateSerializedSizeCode(io::Printer* printer) const = 0; - virtual void GenerateFieldBuilderInitializationCode(io::Printer* printer) - const = 0; + virtual void GenerateFieldInfo(io::Printer* printer, + std::vector* output) const = 0; - virtual void GenerateEqualsCode(io::Printer* printer) const = 0; - virtual void GenerateHashCode(io::Printer* printer) const = 0; - - - virtual string GetBoxedType() const = 0; + virtual std::string GetBoxedType() const = 0; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableFieldLiteGenerator); @@ -125,38 +114,34 @@ class ImmutableFieldLiteGenerator { // Convenience class which constructs FieldGenerators for a Descriptor. -template +template class FieldGeneratorMap { public: - explicit FieldGeneratorMap(const Descriptor* descriptor, - Context* context); + explicit FieldGeneratorMap(const Descriptor* descriptor, Context* context); ~FieldGeneratorMap(); const FieldGeneratorType& get(const FieldDescriptor* field) const; private: const Descriptor* descriptor_; - Context* context_; - ClassNameResolver* name_resolver_; std::vector> field_generators_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap); }; -template -inline const FieldGeneratorType& -FieldGeneratorMap::get(const FieldDescriptor* field) const { +template +inline const FieldGeneratorType& FieldGeneratorMap::get( + const FieldDescriptor* field) const { GOOGLE_CHECK_EQ(field->containing_type(), descriptor_); return *field_generators_[field->index()]; } // Instantiate template for mutable and immutable maps. -template<> -FieldGeneratorMap:: -FieldGeneratorMap(const Descriptor* descriptor, - Context* context); +template <> +FieldGeneratorMap::FieldGeneratorMap( + const Descriptor* descriptor, Context* context); -template<> +template <> FieldGeneratorMap::~FieldGeneratorMap(); @@ -170,34 +155,34 @@ FieldGeneratorMap::~FieldGeneratorMap(); // Field information used in FieldGeneartors. struct FieldGeneratorInfo { - string name; - string capitalized_name; - string disambiguated_reason; + std::string name; + std::string capitalized_name; + std::string disambiguated_reason; }; // Oneof information used in OneofFieldGenerators. struct OneofGeneratorInfo { - string name; - string capitalized_name; + std::string name; + std::string capitalized_name; }; // Set some common variables used in variable FieldGenerators. void SetCommonFieldVariables(const FieldDescriptor* descriptor, const FieldGeneratorInfo* info, - std::map* variables); + std::map* variables); // Set some common oneof variables used in OneofFieldGenerators. void SetCommonOneofVariables(const FieldDescriptor* descriptor, const OneofGeneratorInfo* info, - std::map* variables); + std::map* variables); // Print useful comments before a field's accessors. -void PrintExtraFieldInfo(const std::map& variables, +void PrintExtraFieldInfo(const std::map& variables, io::Printer* printer); } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_FIELD_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_file.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_file.cc index 5583b779..e8953911 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_file.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_file.cc @@ -54,6 +54,7 @@ #include #include + namespace google { namespace protobuf { namespace compiler { @@ -62,26 +63,26 @@ namespace java { namespace { struct FieldDescriptorCompare { - bool operator ()(const FieldDescriptor* f1, const FieldDescriptor* f2) const { - if(f1 == NULL) { + bool operator()(const FieldDescriptor* f1, const FieldDescriptor* f2) const { + if (f1 == NULL) { return false; } - if(f2 == NULL) { + if (f2 == NULL) { return true; } return f1->full_name() < f2->full_name(); } }; -typedef std::set FieldDescriptorSet; +typedef std::set + FieldDescriptorSet; // Recursively searches the given message to collect extensions. // Returns true if all the extensions can be recognized. The extensions will be // appended in to the extensions parameter. // Returns false when there are unknown fields, in which case the data in the // extensions output parameter is not reliable and should be discarded. -bool CollectExtensions(const Message& message, - FieldDescriptorSet* extensions) { +bool CollectExtensions(const Message& message, FieldDescriptorSet* extensions) { const Reflection* reflection = message.GetReflection(); // There are unknown fields that could be extensions, thus this call fails. @@ -98,7 +99,7 @@ bool CollectExtensions(const Message& message, int size = reflection->FieldSize(message, fields[i]); for (int j = 0; j < size; j++) { const Message& sub_message = - reflection->GetRepeatedMessage(message, fields[i], j); + reflection->GetRepeatedMessage(message, fields[i], j); if (!CollectExtensions(sub_message, extensions)) return false; } } else { @@ -119,7 +120,7 @@ bool CollectExtensions(const Message& message, void CollectExtensions(const FileDescriptorProto& file_proto, const DescriptorPool& alternate_pool, FieldDescriptorSet* extensions, - const string& file_data) { + const std::string& file_data) { if (!CollectExtensions(file_proto, extensions)) { // There are unknown fields in the file_proto, which are probably // extensions. We need to parse the data into a dynamic message based on the @@ -159,11 +160,9 @@ void CollectExtensions(const FileDescriptorProto& file_proto, // extend our methods by simply chaining them to another method // with a tail call. This inserts the sequence call-next-method, // end this one, begin-next-method as needed. -void MaybeRestartJavaMethod(io::Printer* printer, - int *bytecode_estimate, - int *method_num, - const char *chain_statement, - const char *method_decl) { +void MaybeRestartJavaMethod(io::Printer* printer, int* bytecode_estimate, + int* method_num, const char* chain_statement, + const char* method_decl) { // The goal here is to stay under 64K bytes of jvm bytecode/method, // since otherwise we hit a hardcoded limit in the jvm and javac will // then fail with the error "code too large". This limit lets our @@ -172,10 +171,10 @@ void MaybeRestartJavaMethod(io::Printer* printer, if ((*bytecode_estimate) > bytesPerMethod) { ++(*method_num); - printer->Print(chain_statement, "method_num", SimpleItoa(*method_num)); + printer->Print(chain_statement, "method_num", StrCat(*method_num)); printer->Outdent(); printer->Print("}\n"); - printer->Print(method_decl, "method_num", SimpleItoa(*method_num)); + printer->Print(method_decl, "method_num", StrCat(*method_num)); printer->Indent(); *bytecode_estimate = 0; } @@ -193,8 +192,7 @@ FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options, options_(options), immutable_api_(immutable_api) { classname_ = name_resolver_->GetFileClassName(file, immutable_api); - generator_factory_.reset( - new ImmutableGeneratorFactory(context_.get())); + generator_factory_.reset(new ImmutableGeneratorFactory(context_.get())); for (int i = 0; i < file_->message_type_count(); ++i) { message_generators_[i].reset( generator_factory_->NewMessageGenerator(file_->message_type(i))); @@ -207,31 +205,48 @@ FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options, FileGenerator::~FileGenerator() {} -bool FileGenerator::Validate(string* error) { +bool FileGenerator::Validate(std::string* error) { // Check that no class name matches the file's class name. This is a common // problem that leads to Java compile errors that can be hard to understand. // It's especially bad when using the java_multiple_files, since we would // end up overwriting the outer class with one of the inner ones. - if (name_resolver_->HasConflictingClassName(file_, classname_)) { + if (name_resolver_->HasConflictingClassName(file_, classname_, + NameEquality::EXACT_EQUAL)) { error->assign(file_->name()); error->append( - ": Cannot generate Java output because the file's outer class name, \""); + ": Cannot generate Java output because the file's outer class name, " + "\""); error->append(classname_); error->append( - "\", matches the name of one of the types declared inside it. " - "Please either rename the type or use the java_outer_classname " - "option to specify a different outer class name for the .proto file."); + "\", matches the name of one of the types declared inside it. " + "Please either rename the type or use the java_outer_classname " + "option to specify a different outer class name for the .proto file."); return false; } + // Similar to the check above, but ignore the case this time. This is not a + // problem on Linux, but will lead to Java compile errors on Windows / Mac + // because filenames are case-insensitive on those platforms. + if (name_resolver_->HasConflictingClassName( + file_, classname_, NameEquality::EQUAL_IGNORE_CASE)) { + GOOGLE_LOG(WARNING) + << file_->name() << ": The file's outer class name, \"" << classname_ + << "\", matches the name of one of the types declared inside it when " + << "case is ignored. This can cause compilation issues on Windows / " + << "MacOS. Please either rename the type or use the " + << "java_outer_classname option to specify a different outer class " + << "name for the .proto file to be safe."; + } + // Print a warning if optimize_for = LITE_RUNTIME is used. if (file_->options().optimize_for() == FileOptions::LITE_RUNTIME) { GOOGLE_LOG(WARNING) << "The optimize_for = LITE_RUNTIME option is no longer supported by " - << "protobuf Java code generator and may generate broken code. It " - << "will be ignored by protoc in the future and protoc will always " + << "protobuf Java code generator and is ignored--protoc will always " << "generate full runtime code for Java. To use Java Lite runtime, " << "users should use the Java Lite plugin instead. See:\n" - << " https://github.com/google/protobuf/blob/master/java/lite.md"; + << " " + "https://github.com/protocolbuffers/protobuf/blob/master/java/" + "lite.md"; } return true; } @@ -240,33 +255,32 @@ void FileGenerator::Generate(io::Printer* printer) { // We don't import anything because we refer to all classes by their // fully-qualified names in the generated source. printer->Print( - "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" - "// source: $filename$\n" - "\n", - "filename", file_->name()); + "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" + "// source: $filename$\n" + "\n", + "filename", file_->name()); if (!java_package_.empty()) { printer->Print( - "package $package$;\n" - "\n", - "package", java_package_); + "package $package$;\n" + "\n", + "package", java_package_); } PrintGeneratedAnnotation( printer, '$', options_.annotate_code ? classname_ + ".java.pb.meta" : ""); printer->Print( "$deprecation$public final class $classname$ {\n" " private $ctor$() {}\n", - "deprecation", file_->options().deprecated() ? - "@java.lang.Deprecated " : "", - "classname", classname_, - "ctor", classname_); + "deprecation", + file_->options().deprecated() ? "@java.lang.Deprecated " : "", + "classname", classname_, "ctor", classname_); printer->Annotate("classname", file_->name()); printer->Indent(); // ----------------------------------------------------------------- printer->Print( - "public static void registerAllExtensions(\n" - " com.google.protobuf.ExtensionRegistryLite registry) {\n"); + "public static void registerAllExtensions(\n" + " com.google.protobuf.ExtensionRegistryLite registry) {\n"); printer->Indent(); @@ -279,8 +293,7 @@ void FileGenerator::Generate(io::Printer* printer) { } printer->Outdent(); - printer->Print( - "}\n"); + printer->Print("}\n"); if (HasDescriptorMethods(file_, context_->EnforceLite())) { // Overload registerAllExtensions for the non-lite usage to // redundantly maintain the original signature (this is @@ -288,12 +301,12 @@ void FileGenerator::Generate(io::Printer* printer) { // ExtensionRegistry in the non-lite usage). Intent is // to remove this in the future. printer->Print( - "\n" - "public static void registerAllExtensions(\n" - " com.google.protobuf.ExtensionRegistry registry) {\n" - " registerAllExtensions(\n" - " (com.google.protobuf.ExtensionRegistryLite) registry);\n" - "}\n"); + "\n" + "public static void registerAllExtensions(\n" + " com.google.protobuf.ExtensionRegistry registry) {\n" + " registerAllExtensions(\n" + " (com.google.protobuf.ExtensionRegistryLite) registry);\n" + "}\n"); } // ----------------------------------------------------------------- @@ -345,29 +358,27 @@ void FileGenerator::Generate(io::Printer* printer) { GenerateDescriptorInitializationCodeForMutable(printer); } } else { - printer->Print( - "static {\n"); + printer->Print("static {\n"); printer->Indent(); int bytecode_estimate = 0; int method_num = 0; for (int i = 0; i < file_->message_type_count(); i++) { - bytecode_estimate += message_generators_[i]->GenerateStaticVariableInitializers(printer); + bytecode_estimate += + message_generators_[i]->GenerateStaticVariableInitializers(printer); MaybeRestartJavaMethod( - printer, - &bytecode_estimate, &method_num, - "_clinit_autosplit_$method_num$();\n", - "private static void _clinit_autosplit_$method_num$() {\n"); + printer, &bytecode_estimate, &method_num, + "_clinit_autosplit_$method_num$();\n", + "private static void _clinit_autosplit_$method_num$() {\n"); } printer->Outdent(); - printer->Print( - "}\n"); + printer->Print("}\n"); } printer->Print( - "\n" - "// @@protoc_insertion_point(outer_class_scope)\n"); + "\n" + "// @@protoc_insertion_point(outer_class_scope)\n"); printer->Outdent(); printer->Print("}\n"); @@ -376,15 +387,15 @@ void FileGenerator::Generate(io::Printer* printer) { void FileGenerator::GenerateDescriptorInitializationCodeForImmutable( io::Printer* printer) { printer->Print( - "public static com.google.protobuf.Descriptors.FileDescriptor\n" - " getDescriptor() {\n" - " return descriptor;\n" - "}\n" - "private static $final$ com.google.protobuf.Descriptors.FileDescriptor\n" - " descriptor;\n" - "static {\n", - // TODO(dweis): Mark this as final. - "final", ""); + "public static com.google.protobuf.Descriptors.FileDescriptor\n" + " getDescriptor() {\n" + " return descriptor;\n" + "}\n" + "private static $final$ com.google.protobuf.Descriptors.FileDescriptor\n" + " descriptor;\n" + "static {\n", + // TODO(dweis): Mark this as final. + "final", ""); printer->Indent(); SharedCodeGenerator shared_code_generator(file_, options_); @@ -394,20 +405,20 @@ void FileGenerator::GenerateDescriptorInitializationCodeForImmutable( int method_num = 0; for (int i = 0; i < file_->message_type_count(); i++) { - bytecode_estimate += message_generators_[i]->GenerateStaticVariableInitializers(printer); + bytecode_estimate += + message_generators_[i]->GenerateStaticVariableInitializers(printer); MaybeRestartJavaMethod( - printer, - &bytecode_estimate, &method_num, - "_clinit_autosplit_dinit_$method_num$();\n", - "private static void _clinit_autosplit_dinit_$method_num$() {\n"); + printer, &bytecode_estimate, &method_num, + "_clinit_autosplit_dinit_$method_num$();\n", + "private static void _clinit_autosplit_dinit_$method_num$() {\n"); } for (int i = 0; i < file_->extension_count(); i++) { - bytecode_estimate += extension_generators_[i]->GenerateNonNestedInitializationCode(printer); + bytecode_estimate += + extension_generators_[i]->GenerateNonNestedInitializationCode(printer); MaybeRestartJavaMethod( - printer, - &bytecode_estimate, &method_num, - "_clinit_autosplit_dinit_$method_num$();\n", - "private static void _clinit_autosplit_dinit_$method_num$() {\n"); + printer, &bytecode_estimate, &method_num, + "_clinit_autosplit_dinit_$method_num$();\n", + "private static void _clinit_autosplit_dinit_$method_num$() {\n"); } // Proto compiler builds a DescriptorPool, which holds all the descriptors to @@ -427,7 +438,7 @@ void FileGenerator::GenerateDescriptorInitializationCodeForImmutable( // reflections to find all extension fields FileDescriptorProto file_proto; file_->CopyTo(&file_proto); - string file_data; + std::string file_data; file_proto.SerializeToString(&file_data); FieldDescriptorSet extensions; CollectExtensions(file_proto, *file_->pool(), &extensions, file_data); @@ -436,56 +447,54 @@ void FileGenerator::GenerateDescriptorInitializationCodeForImmutable( // Must construct an ExtensionRegistry containing all existing extensions // and use it to parse the descriptor data again to recognize extensions. printer->Print( - "com.google.protobuf.ExtensionRegistry registry =\n" - " com.google.protobuf.ExtensionRegistry.newInstance();\n"); + "com.google.protobuf.ExtensionRegistry registry =\n" + " com.google.protobuf.ExtensionRegistry.newInstance();\n"); FieldDescriptorSet::iterator it; for (it = extensions.begin(); it != extensions.end(); it++) { std::unique_ptr generator( generator_factory_->NewExtensionGenerator(*it)); bytecode_estimate += generator->GenerateRegistrationCode(printer); MaybeRestartJavaMethod( - printer, - &bytecode_estimate, &method_num, - "_clinit_autosplit_dinit_$method_num$(registry);\n", - "private static void _clinit_autosplit_dinit_$method_num$(\n" - " com.google.protobuf.ExtensionRegistry registry) {\n"); + printer, &bytecode_estimate, &method_num, + "_clinit_autosplit_dinit_$method_num$(registry);\n", + "private static void _clinit_autosplit_dinit_$method_num$(\n" + " com.google.protobuf.ExtensionRegistry registry) {\n"); } printer->Print( - "com.google.protobuf.Descriptors.FileDescriptor\n" - " .internalUpdateFileDescriptor(descriptor, registry);\n"); + "com.google.protobuf.Descriptors.FileDescriptor\n" + " .internalUpdateFileDescriptor(descriptor, registry);\n"); } // Force descriptor initialization of all dependencies. for (int i = 0; i < file_->dependency_count(); i++) { if (ShouldIncludeDependency(file_->dependency(i), true)) { - string dependency = + std::string dependency = name_resolver_->GetImmutableClassName(file_->dependency(i)); - printer->Print( - "$dependency$.getDescriptor();\n", - "dependency", dependency); + printer->Print("$dependency$.getDescriptor();\n", "dependency", + dependency); } } printer->Outdent(); - printer->Print( - "}\n"); + printer->Print("}\n"); } -void FileGenerator::GenerateDescriptorInitializationCodeForMutable(io::Printer* printer) { +void FileGenerator::GenerateDescriptorInitializationCodeForMutable( + io::Printer* printer) { printer->Print( - "public static com.google.protobuf.Descriptors.FileDescriptor\n" - " getDescriptor() {\n" - " return descriptor;\n" - "}\n" - "private static final com.google.protobuf.Descriptors.FileDescriptor\n" - " descriptor;\n" - "static {\n"); + "public static com.google.protobuf.Descriptors.FileDescriptor\n" + " getDescriptor() {\n" + " return descriptor;\n" + "}\n" + "private static final com.google.protobuf.Descriptors.FileDescriptor\n" + " descriptor;\n" + "static {\n"); printer->Indent(); printer->Print( - "descriptor = $immutable_package$.$descriptor_classname$.descriptor;\n", - "immutable_package", FileJavaPackage(file_, true), - "descriptor_classname", name_resolver_->GetDescriptorClassName(file_)); + "descriptor = $immutable_package$.$descriptor_classname$.descriptor;\n", + "immutable_package", FileJavaPackage(file_, true), "descriptor_classname", + name_resolver_->GetDescriptorClassName(file_)); for (int i = 0; i < file_->message_type_count(); i++) { message_generators_[i]->GenerateStaticVariableInitializers(printer); @@ -498,7 +507,7 @@ void FileGenerator::GenerateDescriptorInitializationCodeForMutable(io::Printer* // custom options are only represented with immutable messages. FileDescriptorProto file_proto; file_->CopyTo(&file_proto); - string file_data; + std::string file_data; file_proto.SerializeToString(&file_data); FieldDescriptorSet extensions; CollectExtensions(file_proto, *file_->pool(), &extensions, file_data); @@ -527,7 +536,7 @@ void FileGenerator::GenerateDescriptorInitializationCodeForMutable(io::Printer* FieldDescriptorSet::iterator it; for (it = extensions.begin(); it != extensions.end(); it++) { const FieldDescriptor* field = *it; - string scope; + std::string scope; if (field->extension_scope() != NULL) { scope = name_resolver_->GetMutableClassName(field->extension_scope()) + ".getDescriptor()"; @@ -545,11 +554,11 @@ void FileGenerator::GenerateDescriptorInitializationCodeForMutable(io::Printer* " $scope$.getExtensions().get($index$),\n" " (com.google.protobuf.Message) defaultExtensionInstance);\n" "}\n", - "scope", scope, "index", SimpleItoa(field->index()), "class", + "scope", scope, "index", StrCat(field->index()), "class", name_resolver_->GetImmutableClassName(field->message_type())); } else { printer->Print("registry.add($scope$.getExtensions().get($index$));\n", - "scope", scope, "index", SimpleItoa(field->index())); + "scope", scope, "index", StrCat(field->index())); } } printer->Print( @@ -563,32 +572,29 @@ void FileGenerator::GenerateDescriptorInitializationCodeForMutable(io::Printer* // Force descriptor initialization of all dependencies. for (int i = 0; i < file_->dependency_count(); i++) { if (ShouldIncludeDependency(file_->dependency(i), false)) { - string dependency = name_resolver_->GetMutableClassName( - file_->dependency(i)); - printer->Print( - "$dependency$.getDescriptor();\n", - "dependency", dependency); + std::string dependency = + name_resolver_->GetMutableClassName(file_->dependency(i)); + printer->Print("$dependency$.getDescriptor();\n", "dependency", + dependency); } } printer->Outdent(); - printer->Print( - "}\n"); + printer->Print("}\n"); } template -static void GenerateSibling(const string& package_dir, - const string& java_package, - const DescriptorClass* descriptor, - GeneratorContext* context, - std::vector* file_list, bool annotate_code, - std::vector* annotation_list, - const string& name_suffix, - GeneratorClass* generator, - void (GeneratorClass::*pfn)(io::Printer* printer)) { - string filename = package_dir + descriptor->name() + name_suffix + ".java"; +static void GenerateSibling( + const std::string& package_dir, const std::string& java_package, + const DescriptorClass* descriptor, GeneratorContext* context, + std::vector* file_list, bool annotate_code, + std::vector* annotation_list, const std::string& name_suffix, + GeneratorClass* generator, + void (GeneratorClass::*pfn)(io::Printer* printer)) { + std::string filename = + package_dir + descriptor->name() + name_suffix + ".java"; file_list->push_back(filename); - string info_full_path = filename + ".pb.meta"; + std::string info_full_path = filename + ".pb.meta"; GeneratedCodeInfo annotations; io::AnnotationProtoCollector annotation_collector( &annotations); @@ -598,15 +604,15 @@ static void GenerateSibling(const string& package_dir, annotate_code ? &annotation_collector : NULL); printer.Print( - "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" - "// source: $filename$\n" - "\n", - "filename", descriptor->file()->name()); + "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" + "// source: $filename$\n" + "\n", + "filename", descriptor->file()->name()); if (!java_package.empty()) { printer.Print( - "package $package$;\n" - "\n", - "package", java_package); + "package $package$;\n" + "\n", + "package", java_package); } (generator->*pfn)(&printer); @@ -619,10 +625,10 @@ static void GenerateSibling(const string& package_dir, } } -void FileGenerator::GenerateSiblings(const string& package_dir, - GeneratorContext* context, - std::vector* file_list, - std::vector* annotation_list) { +void FileGenerator::GenerateSiblings( + const std::string& package_dir, GeneratorContext* context, + std::vector* file_list, + std::vector* annotation_list) { if (MultipleJavaFiles(file_, immutable_api_)) { for (int i = 0; i < file_->enum_type_count(); i++) { if (HasDescriptorMethods(file_, context_->EnforceLite())) { @@ -666,8 +672,8 @@ void FileGenerator::GenerateSiblings(const string& package_dir, } } -bool FileGenerator::ShouldIncludeDependency( - const FileDescriptor* descriptor, bool immutable_api) { +bool FileGenerator::ShouldIncludeDependency(const FileDescriptor* descriptor, + bool immutable_api) { return true; } diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_file.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_file.h index 78833a45..bb3e4a57 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_file.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_file.h @@ -43,22 +43,24 @@ namespace google { namespace protobuf { - class FileDescriptor; // descriptor.h - namespace io { - class Printer; // printer.h - } - namespace compiler { - class GeneratorContext; // code_generator.h - namespace java { - class Context; // context.h - class MessageGenerator; // message.h - class GeneratorFactory; // generator_factory.h - class ExtensionGenerator; // extension.h - class ClassNameResolver; // name_resolver.h - } - } +class FileDescriptor; // descriptor.h +namespace io { +class Printer; // printer.h } +namespace compiler { +class GeneratorContext; // code_generator.h +namespace java { +class Context; // context.h +class MessageGenerator; // message.h +class GeneratorFactory; // generator_factory.h +class ExtensionGenerator; // extension.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { @@ -72,20 +74,20 @@ class FileGenerator { // Checks for problems that would otherwise lead to cryptic compile errors. // Returns true if there are no problems, or writes an error description to // the given string and returns false otherwise. - bool Validate(string* error); + bool Validate(std::string* error); void Generate(io::Printer* printer); // If we aren't putting everything into one file, this will write all the // files other than the outer file (i.e. one for each message, enum, and // service type). - void GenerateSiblings(const string& package_dir, + void GenerateSiblings(const std::string& package_dir, GeneratorContext* generator_context, - std::vector* file_list, - std::vector* annotation_list); + std::vector* file_list, + std::vector* annotation_list); - const string& java_package() { return java_package_; } - const string& classname() { return classname_; } + const std::string& java_package() { return java_package_; } + const std::string& classname() { return classname_; } private: void GenerateDescriptorInitializationCodeForImmutable(io::Printer* printer); @@ -95,8 +97,8 @@ class FileGenerator { bool immutable_api_); const FileDescriptor* file_; - string java_package_; - string classname_; + std::string java_package_; + std::string classname_; std::vector> message_generators_; std::vector> extension_generators_; @@ -112,6 +114,6 @@ class FileGenerator { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_FILE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_generator.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_generator.cc index a5b2e784..5045cfdc 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_generator.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_generator.cc @@ -34,6 +34,7 @@ #include + #include #include @@ -58,14 +59,13 @@ JavaGenerator::JavaGenerator() {} JavaGenerator::~JavaGenerator() {} bool JavaGenerator::Generate(const FileDescriptor* file, - const string& parameter, + const std::string& parameter, GeneratorContext* context, - string* error) const { + std::string* error) const { // ----------------------------------------------------------------- // parse generator options - - std::vector > options; + std::vector > options; ParseGeneratorParameter(parameter, &options); Options file_options; @@ -78,6 +78,10 @@ bool JavaGenerator::Generate(const FileDescriptor* file, file_options.generate_mutable_code = true; } else if (options[i].first == "shared") { file_options.generate_shared_code = true; + } else if (options[i].first == "lite") { + // Note: Java Lite does not guarantee API/ABI stability. We may choose to + // break existing API in order to boost performance / reduce code size. + file_options.enforce_lite = true; } else if (options[i].first == "annotate_code") { file_options.annotate_code = true; } else if (options[i].first == "annotation_list_file") { @@ -104,8 +108,8 @@ bool JavaGenerator::Generate(const FileDescriptor* file, // ----------------------------------------------------------------- - std::vector all_files; - std::vector all_annotations; + std::vector all_files; + std::vector all_annotations; std::vector file_generators; @@ -117,6 +121,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file, file_generators.push_back(new FileGenerator(file, file_options, /* mutable = */ false)); } + for (int i = 0; i < file_generators.size(); ++i) { if (!file_generators[i]->Validate(error)) { for (int j = 0; j < file_generators.size(); ++j) { @@ -129,13 +134,13 @@ bool JavaGenerator::Generate(const FileDescriptor* file, for (int i = 0; i < file_generators.size(); ++i) { FileGenerator* file_generator = file_generators[i]; - string package_dir = JavaPackageToDir(file_generator->java_package()); + std::string package_dir = JavaPackageToDir(file_generator->java_package()); - string java_filename = package_dir; + std::string java_filename = package_dir; java_filename += file_generator->classname(); java_filename += ".java"; all_files.push_back(java_filename); - string info_full_path = java_filename + ".pb.meta"; + std::string info_full_path = java_filename + ".pb.meta"; if (file_options.annotate_code) { all_annotations.push_back(info_full_path); } @@ -146,9 +151,9 @@ bool JavaGenerator::Generate(const FileDescriptor* file, GeneratedCodeInfo annotations; io::AnnotationProtoCollector annotation_collector( &annotations); - io::Printer printer(output.get(), '$', file_options.annotate_code - ? &annotation_collector - : NULL); + io::Printer printer( + output.get(), '$', + file_options.annotate_code ? &annotation_collector : NULL); file_generator->Generate(&printer); @@ -163,6 +168,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file, } } + for (int i = 0; i < file_generators.size(); ++i) { delete file_generators[i]; } diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_generator.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_generator.h index 47f76be9..be63ac49 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_generator.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_generator.h @@ -40,6 +40,8 @@ #include #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -49,16 +51,14 @@ namespace java { // own protocol compiler binary and you want it to support Java output, you // can do so by registering an instance of this CodeGenerator with the // CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT JavaGenerator : public CodeGenerator { +class PROTOC_EXPORT JavaGenerator : public CodeGenerator { public: JavaGenerator(); ~JavaGenerator(); // implements CodeGenerator ---------------------------------------- - bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const; + bool Generate(const FileDescriptor* file, const std::string& parameter, + GeneratorContext* context, std::string* error) const; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(JavaGenerator); @@ -67,6 +67,8 @@ class LIBPROTOC_EXPORT JavaGenerator : public CodeGenerator { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_generator_factory.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_generator_factory.cc index 3218b410..3a62adb1 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_generator_factory.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_generator_factory.cc @@ -52,9 +52,8 @@ GeneratorFactory::~GeneratorFactory() {} // =================================================================== -ImmutableGeneratorFactory::ImmutableGeneratorFactory( - Context* context) : context_(context) { -} +ImmutableGeneratorFactory::ImmutableGeneratorFactory(Context* context) + : context_(context) {} ImmutableGeneratorFactory::~ImmutableGeneratorFactory() {} MessageGenerator* ImmutableGeneratorFactory::NewMessageGenerator( diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_generator_factory.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_generator_factory.h index 55365a9d..16688a56 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_generator_factory.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_generator_factory.h @@ -37,19 +37,21 @@ namespace google { namespace protobuf { - class FieldDescriptor; // descriptor.h - class Descriptor; // descriptor.h - class ServiceDescriptor; // descriptor.h - namespace compiler { - namespace java { - class MessageGenerator; // message.h - class ExtensionGenerator; // extension.h - class ServiceGenerator; // service.h - class Context; // context.h - } - } -} +class FieldDescriptor; // descriptor.h +class Descriptor; // descriptor.h +class ServiceDescriptor; // descriptor.h +namespace compiler { +namespace java { +class MessageGenerator; // message.h +class ExtensionGenerator; // extension.h +class ServiceGenerator; // service.h +class Context; // context.h +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { @@ -96,6 +98,6 @@ class ImmutableGeneratorFactory : public GeneratorFactory { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_FACTORY_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_helpers.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_helpers.cc index 957076cb..ac0e9cd3 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_helpers.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_helpers.cc @@ -33,8 +33,8 @@ // Sanjay Ghemawat, Jeff Dean, and others. #include -#include #include +#include #include #include @@ -46,6 +46,7 @@ #include + #include // for hash namespace google { @@ -57,9 +58,9 @@ using internal::WireFormat; using internal::WireFormatLite; const char kThickSeparator[] = - "// ===================================================================\n"; + "// ===================================================================\n"; const char kThinSeparator[] = - "// -------------------------------------------------------------------\n"; + "// -------------------------------------------------------------------\n"; namespace { @@ -69,15 +70,28 @@ const char* kDefaultPackage = ""; // Using them will cause the compiler to generate accessors whose names are // colliding with methods defined in base classes. const char* kForbiddenWordList[] = { - // message base class: - "cached_size", "serialized_size", - // java.lang.Object: - "class", + // message base class: + "cached_size", + "serialized_size", + // java.lang.Object: + "class", }; -const int kDefaultLookUpStartFieldNumber = 40; +const std::unordered_set* kReservedNames = + new std::unordered_set({ + "abstract", "assert", "boolean", "break", "byte", + "case", "catch", "char", "class", "const", + "continue", "default", "do", "double", "else", + "enum", "extends", "final", "finally", "float", + "for", "goto", "if", "implements", "import", + "instanceof", "int", "interface", "long", "native", + "new", "package", "private", "protected", "public", + "return", "short", "static", "strictfp", "super", + "switch", "synchronized", "this", "throw", "throws", + "transient", "try", "void", "volatile", "while", + }); -bool IsForbidden(const string& field_name) { +bool IsForbidden(const std::string& field_name) { for (int i = 0; i < GOOGLE_ARRAYSIZE(kForbiddenWordList); ++i) { if (field_name == kForbiddenWordList[i]) { return true; @@ -86,8 +100,8 @@ bool IsForbidden(const string& field_name) { return false; } -string FieldName(const FieldDescriptor* field) { - string field_name; +std::string FieldName(const FieldDescriptor* field) { + std::string field_name; // Groups are hacky: The name of the field is just the lower-cased name // of the group type. In Java, though, we would like to retain the original // capitalization of the type name. @@ -105,28 +119,14 @@ string FieldName(const FieldDescriptor* field) { } -// Judge whether should use table or use look up. -// Copied from com.google.protobuf.SchemaUtil.shouldUseTableSwitch -bool ShouldUseTable(int lo, int hi, int number_of_fields) { - if (hi < kDefaultLookUpStartFieldNumber) { - return true; - } - int64 table_space_cost = (static_cast(hi) - lo + 1); // words - int64 table_time_cost = 3; // comparisons - int64 lookup_space_cost = 3 + 2 * static_cast(number_of_fields); - int64 lookup_time_cost = 3 + number_of_fields; - return table_space_cost + 3 * table_time_cost <= - lookup_space_cost + 3 * lookup_time_cost; -} - } // namespace void PrintGeneratedAnnotation(io::Printer* printer, char delimiter, - const string& annotation_file) { + const std::string& annotation_file) { if (annotation_file.empty()) { return; } - string ptemplate = + std::string ptemplate = "@javax.annotation.Generated(value=\"protoc\", comments=\"annotations:"; ptemplate.push_back(delimiter); ptemplate.append("annotation_file"); @@ -135,8 +135,31 @@ void PrintGeneratedAnnotation(io::Printer* printer, char delimiter, printer->Print(ptemplate.c_str(), "annotation_file", annotation_file); } -string UnderscoresToCamelCase(const string& input, bool cap_next_letter) { - string result; +void PrintEnumVerifierLogic(io::Printer* printer, + const FieldDescriptor* descriptor, + const std::map& variables, + const char* var_name, + const char* terminating_string, bool enforce_lite) { + std::string enum_verifier_string = + enforce_lite ? StrCat(var_name, ".internalGetVerifier()") + : StrCat( + "new com.google.protobuf.Internal.EnumVerifier() {\n" + " @java.lang.Override\n" + " public boolean isInRange(int number) {\n" + " return ", + var_name, + ".forNumber(number) != null;\n" + " }\n" + " }"); + printer->Print( + variables, + StrCat(enum_verifier_string, terminating_string).c_str()); +} + +std::string UnderscoresToCamelCase(const std::string& input, + bool cap_next_letter) { + GOOGLE_CHECK(!input.empty()); + std::string result; // Note: I distrust ctype.h due to locales. for (int i = 0; i < input.size(); i++) { if ('a' <= input[i] && input[i] <= 'z') { @@ -170,31 +193,43 @@ string UnderscoresToCamelCase(const string& input, bool cap_next_letter) { return result; } -string UnderscoresToCamelCase(const FieldDescriptor* field) { +std::string UnderscoresToCamelCase(const FieldDescriptor* field) { return UnderscoresToCamelCase(FieldName(field), false); } -string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field) { +std::string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field) { return UnderscoresToCamelCase(FieldName(field), true); } -string UnderscoresToCamelCase(const MethodDescriptor* method) { +std::string CapitalizedFieldName(const FieldDescriptor* field) { + return UnderscoresToCapitalizedCamelCase(field); +} + +std::string UnderscoresToCamelCase(const MethodDescriptor* method) { return UnderscoresToCamelCase(method->name(), false); } -string UniqueFileScopeIdentifier(const Descriptor* descriptor) { +std::string UnderscoresToCamelCaseCheckReserved(const FieldDescriptor* field) { + std::string name = UnderscoresToCamelCase(field); + if (kReservedNames->find(name) != kReservedNames->end()) { + return name + "_"; + } + return name; +} + +std::string UniqueFileScopeIdentifier(const Descriptor* descriptor) { return "static_" + StringReplace(descriptor->full_name(), ".", "_", true); } -string CamelCaseFieldName(const FieldDescriptor* field) { - string fieldName = UnderscoresToCamelCase(field); +std::string CamelCaseFieldName(const FieldDescriptor* field) { + std::string fieldName = UnderscoresToCamelCase(field); if ('0' <= fieldName[0] && fieldName[0] <= '9') { return '_' + fieldName; } return fieldName; } -string StripProto(const string& filename) { +std::string StripProto(const std::string& filename) { if (HasSuffixString(filename, ".protodevel")) { return StripSuffixString(filename, ".protodevel"); } else { @@ -202,13 +237,13 @@ string StripProto(const string& filename) { } } -string FileClassName(const FileDescriptor* file, bool immutable) { +std::string FileClassName(const FileDescriptor* file, bool immutable) { ClassNameResolver name_resolver; return name_resolver.GetFileClassName(file, immutable); } -string FileJavaPackage(const FileDescriptor* file, bool immutable) { - string result; +std::string FileJavaPackage(const FileDescriptor* file, bool immutable) { + std::string result; if (file->options().has_java_package()) { result = file->options().java_package(); @@ -223,78 +258,58 @@ string FileJavaPackage(const FileDescriptor* file, bool immutable) { return result; } -string JavaPackageToDir(string package_name) { - string package_dir = - StringReplace(package_name, ".", "/", true); +std::string FileJavaPackage(const FileDescriptor* file) { + return FileJavaPackage(file, true /* immutable */); +} + +std::string JavaPackageToDir(std::string package_name) { + std::string package_dir = StringReplace(package_name, ".", "/", true); if (!package_dir.empty()) package_dir += "/"; return package_dir; } -// TODO(xiaofeng): This function is only kept for it's publicly referenced. -// It should be removed after mutable API up-integration. -string ToJavaName(const string& full_name, - const FileDescriptor* file) { - string result; - if (file->options().java_multiple_files()) { - result = FileJavaPackage(file); - } else { - result = ClassName(file); - } - if (!result.empty()) { - result += '.'; - } - if (file->package().empty()) { - result += full_name; - } else { - // Strip the proto package from full_name since we've replaced it with - // the Java package. - result += full_name.substr(file->package().size() + 1); - } - return result; -} - -string ClassName(const Descriptor* descriptor) { +std::string ClassName(const Descriptor* descriptor) { ClassNameResolver name_resolver; return name_resolver.GetClassName(descriptor, true); } -string ClassName(const EnumDescriptor* descriptor) { +std::string ClassName(const EnumDescriptor* descriptor) { ClassNameResolver name_resolver; return name_resolver.GetClassName(descriptor, true); } -string ClassName(const ServiceDescriptor* descriptor) { +std::string ClassName(const ServiceDescriptor* descriptor) { ClassNameResolver name_resolver; return name_resolver.GetClassName(descriptor, true); } -string ClassName(const FileDescriptor* descriptor) { +std::string ClassName(const FileDescriptor* descriptor) { ClassNameResolver name_resolver; return name_resolver.GetClassName(descriptor, true); } -string ExtraMessageInterfaces(const Descriptor* descriptor) { - string interfaces = "// @@protoc_insertion_point(message_implements:" - + descriptor->full_name() + ")"; +std::string ExtraMessageInterfaces(const Descriptor* descriptor) { + std::string interfaces = "// @@protoc_insertion_point(message_implements:" + + descriptor->full_name() + ")"; return interfaces; } -string ExtraBuilderInterfaces(const Descriptor* descriptor) { - string interfaces = "// @@protoc_insertion_point(builder_implements:" - + descriptor->full_name() + ")"; +std::string ExtraBuilderInterfaces(const Descriptor* descriptor) { + std::string interfaces = "// @@protoc_insertion_point(builder_implements:" + + descriptor->full_name() + ")"; return interfaces; } -string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor) { - string interfaces = "// @@protoc_insertion_point(interface_extends:" - + descriptor->full_name() + ")"; +std::string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor) { + std::string interfaces = "// @@protoc_insertion_point(interface_extends:" + + descriptor->full_name() + ")"; return interfaces; } -string FieldConstantName(const FieldDescriptor *field) { - string name = field->name() + "_FIELD_NUMBER"; +std::string FieldConstantName(const FieldDescriptor* field) { + std::string name = field->name() + "_FIELD_NUMBER"; UpperString(&name); return name; } @@ -341,8 +356,8 @@ JavaType GetJavaType(const FieldDescriptor* field) { case FieldDescriptor::TYPE_MESSAGE: return JAVATYPE_MESSAGE; - // No default because we want the compiler to complain if any new - // types are added. + // No default because we want the compiler to complain if any new + // types are added. } GOOGLE_LOG(FATAL) << "Can't get here."; @@ -351,75 +366,130 @@ JavaType GetJavaType(const FieldDescriptor* field) { const char* PrimitiveTypeName(JavaType type) { switch (type) { - case JAVATYPE_INT : return "int"; - case JAVATYPE_LONG : return "long"; - case JAVATYPE_FLOAT : return "float"; - case JAVATYPE_DOUBLE : return "double"; - case JAVATYPE_BOOLEAN: return "boolean"; - case JAVATYPE_STRING : return "java.lang.String"; - case JAVATYPE_BYTES : return "com.google.protobuf.ByteString"; - case JAVATYPE_ENUM : return NULL; - case JAVATYPE_MESSAGE: return NULL; + case JAVATYPE_INT: + return "int"; + case JAVATYPE_LONG: + return "long"; + case JAVATYPE_FLOAT: + return "float"; + case JAVATYPE_DOUBLE: + return "double"; + case JAVATYPE_BOOLEAN: + return "boolean"; + case JAVATYPE_STRING: + return "java.lang.String"; + case JAVATYPE_BYTES: + return "com.google.protobuf.ByteString"; + case JAVATYPE_ENUM: + return NULL; + case JAVATYPE_MESSAGE: + return NULL; - // No default because we want the compiler to complain if any new - // JavaTypes are added. + // No default because we want the compiler to complain if any new + // JavaTypes are added. } GOOGLE_LOG(FATAL) << "Can't get here."; return NULL; } +const char* PrimitiveTypeName(const FieldDescriptor* descriptor) { + return PrimitiveTypeName(GetJavaType(descriptor)); +} + const char* BoxedPrimitiveTypeName(JavaType type) { switch (type) { - case JAVATYPE_INT : return "java.lang.Integer"; - case JAVATYPE_LONG : return "java.lang.Long"; - case JAVATYPE_FLOAT : return "java.lang.Float"; - case JAVATYPE_DOUBLE : return "java.lang.Double"; - case JAVATYPE_BOOLEAN: return "java.lang.Boolean"; - case JAVATYPE_STRING : return "java.lang.String"; - case JAVATYPE_BYTES : return "com.google.protobuf.ByteString"; - case JAVATYPE_ENUM : return NULL; - case JAVATYPE_MESSAGE: return NULL; + case JAVATYPE_INT: + return "java.lang.Integer"; + case JAVATYPE_LONG: + return "java.lang.Long"; + case JAVATYPE_FLOAT: + return "java.lang.Float"; + case JAVATYPE_DOUBLE: + return "java.lang.Double"; + case JAVATYPE_BOOLEAN: + return "java.lang.Boolean"; + case JAVATYPE_STRING: + return "java.lang.String"; + case JAVATYPE_BYTES: + return "com.google.protobuf.ByteString"; + case JAVATYPE_ENUM: + return NULL; + case JAVATYPE_MESSAGE: + return NULL; - // No default because we want the compiler to complain if any new - // JavaTypes are added. + // No default because we want the compiler to complain if any new + // JavaTypes are added. } GOOGLE_LOG(FATAL) << "Can't get here."; return NULL; } +const char* BoxedPrimitiveTypeName(const FieldDescriptor* descriptor) { + return BoxedPrimitiveTypeName(GetJavaType(descriptor)); +} + +std::string GetOneofStoredType(const FieldDescriptor* field) { + const JavaType javaType = GetJavaType(field); + switch (javaType) { + case JAVATYPE_ENUM: + return "java.lang.Integer"; + case JAVATYPE_MESSAGE: + return ClassName(field->message_type()); + default: + return BoxedPrimitiveTypeName(javaType); + } +} const char* FieldTypeName(FieldDescriptor::Type field_type) { switch (field_type) { - case FieldDescriptor::TYPE_INT32 : return "INT32"; - case FieldDescriptor::TYPE_UINT32 : return "UINT32"; - case FieldDescriptor::TYPE_SINT32 : return "SINT32"; - case FieldDescriptor::TYPE_FIXED32 : return "FIXED32"; - case FieldDescriptor::TYPE_SFIXED32: return "SFIXED32"; - case FieldDescriptor::TYPE_INT64 : return "INT64"; - case FieldDescriptor::TYPE_UINT64 : return "UINT64"; - case FieldDescriptor::TYPE_SINT64 : return "SINT64"; - case FieldDescriptor::TYPE_FIXED64 : return "FIXED64"; - case FieldDescriptor::TYPE_SFIXED64: return "SFIXED64"; - case FieldDescriptor::TYPE_FLOAT : return "FLOAT"; - case FieldDescriptor::TYPE_DOUBLE : return "DOUBLE"; - case FieldDescriptor::TYPE_BOOL : return "BOOL"; - case FieldDescriptor::TYPE_STRING : return "STRING"; - case FieldDescriptor::TYPE_BYTES : return "BYTES"; - case FieldDescriptor::TYPE_ENUM : return "ENUM"; - case FieldDescriptor::TYPE_GROUP : return "GROUP"; - case FieldDescriptor::TYPE_MESSAGE : return "MESSAGE"; + case FieldDescriptor::TYPE_INT32: + return "INT32"; + case FieldDescriptor::TYPE_UINT32: + return "UINT32"; + case FieldDescriptor::TYPE_SINT32: + return "SINT32"; + case FieldDescriptor::TYPE_FIXED32: + return "FIXED32"; + case FieldDescriptor::TYPE_SFIXED32: + return "SFIXED32"; + case FieldDescriptor::TYPE_INT64: + return "INT64"; + case FieldDescriptor::TYPE_UINT64: + return "UINT64"; + case FieldDescriptor::TYPE_SINT64: + return "SINT64"; + case FieldDescriptor::TYPE_FIXED64: + return "FIXED64"; + case FieldDescriptor::TYPE_SFIXED64: + return "SFIXED64"; + case FieldDescriptor::TYPE_FLOAT: + return "FLOAT"; + case FieldDescriptor::TYPE_DOUBLE: + return "DOUBLE"; + case FieldDescriptor::TYPE_BOOL: + return "BOOL"; + case FieldDescriptor::TYPE_STRING: + return "STRING"; + case FieldDescriptor::TYPE_BYTES: + return "BYTES"; + case FieldDescriptor::TYPE_ENUM: + return "ENUM"; + case FieldDescriptor::TYPE_GROUP: + return "GROUP"; + case FieldDescriptor::TYPE_MESSAGE: + return "MESSAGE"; - // No default because we want the compiler to complain if any new - // types are added. + // No default because we want the compiler to complain if any new + // types are added. } GOOGLE_LOG(FATAL) << "Can't get here."; return NULL; } -bool AllAscii(const string& text) { +bool AllAscii(const std::string& text) { for (int i = 0; i < text.size(); i++) { if ((text[i] & 0x80) != 0) { return false; @@ -428,20 +498,20 @@ bool AllAscii(const string& text) { return true; } -string DefaultValue(const FieldDescriptor* field, bool immutable, - ClassNameResolver* name_resolver) { +std::string DefaultValue(const FieldDescriptor* field, bool immutable, + ClassNameResolver* name_resolver) { // Switch on CppType since we need to know which default_value_* method // of FieldDescriptor to call. switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_INT32: - return SimpleItoa(field->default_value_int32()); + return StrCat(field->default_value_int32()); case FieldDescriptor::CPPTYPE_UINT32: // Need to print as a signed int since Java has no unsigned. - return SimpleItoa(static_cast(field->default_value_uint32())); + return StrCat(static_cast(field->default_value_uint32())); case FieldDescriptor::CPPTYPE_INT64: - return SimpleItoa(field->default_value_int64()) + "L"; + return StrCat(field->default_value_int64()) + "L"; case FieldDescriptor::CPPTYPE_UINT64: - return SimpleItoa(static_cast(field->default_value_uint64())) + + return StrCat(static_cast(field->default_value_uint64())) + "L"; case FieldDescriptor::CPPTYPE_DOUBLE: { double value = field->default_value_double(); @@ -474,8 +544,8 @@ string DefaultValue(const FieldDescriptor* field, bool immutable, if (field->has_default_value()) { // See comments in Internal.java for gory details. return strings::Substitute( - "com.google.protobuf.Internal.bytesDefaultValue(\"$0\")", - CEscape(field->default_value_string())); + "com.google.protobuf.Internal.bytesDefaultValue(\"$0\")", + CEscape(field->default_value_string())); } else { return "com.google.protobuf.ByteString.EMPTY"; } @@ -493,14 +563,14 @@ string DefaultValue(const FieldDescriptor* field, bool immutable, case FieldDescriptor::CPPTYPE_ENUM: return name_resolver->GetClassName(field->enum_type(), immutable) + "." + - field->default_value_enum()->name(); + field->default_value_enum()->name(); case FieldDescriptor::CPPTYPE_MESSAGE: return name_resolver->GetClassName(field->message_type(), immutable) + - ".getDefaultInstance()"; + ".getDefaultInstance()"; - // No default because we want the compiler to complain if any new - // types are added. + // No default because we want the compiler to complain if any new + // types are added. } GOOGLE_LOG(FATAL) << "Can't get here."; @@ -531,8 +601,8 @@ bool IsDefaultValueJavaDefault(const FieldDescriptor* field) { case FieldDescriptor::CPPTYPE_MESSAGE: return false; - // No default because we want the compiler to complain if any new - // types are added. + // No default because we want the compiler to complain if any new + // types are added. } GOOGLE_LOG(FATAL) << "Can't get here."; @@ -545,123 +615,108 @@ bool IsByteStringWithCustomDefaultValue(const FieldDescriptor* field) { } const char* bit_masks[] = { - "0x00000001", - "0x00000002", - "0x00000004", - "0x00000008", - "0x00000010", - "0x00000020", - "0x00000040", - "0x00000080", + "0x00000001", "0x00000002", "0x00000004", "0x00000008", + "0x00000010", "0x00000020", "0x00000040", "0x00000080", - "0x00000100", - "0x00000200", - "0x00000400", - "0x00000800", - "0x00001000", - "0x00002000", - "0x00004000", - "0x00008000", + "0x00000100", "0x00000200", "0x00000400", "0x00000800", + "0x00001000", "0x00002000", "0x00004000", "0x00008000", - "0x00010000", - "0x00020000", - "0x00040000", - "0x00080000", - "0x00100000", - "0x00200000", - "0x00400000", - "0x00800000", + "0x00010000", "0x00020000", "0x00040000", "0x00080000", + "0x00100000", "0x00200000", "0x00400000", "0x00800000", - "0x01000000", - "0x02000000", - "0x04000000", - "0x08000000", - "0x10000000", - "0x20000000", - "0x40000000", - "0x80000000", + "0x01000000", "0x02000000", "0x04000000", "0x08000000", + "0x10000000", "0x20000000", "0x40000000", "0x80000000", }; -string GetBitFieldName(int index) { - string varName = "bitField"; - varName += SimpleItoa(index); +std::string GetBitFieldName(int index) { + std::string varName = "bitField"; + varName += StrCat(index); varName += "_"; return varName; } -string GetBitFieldNameForBit(int bitIndex) { +std::string GetBitFieldNameForBit(int bitIndex) { return GetBitFieldName(bitIndex / 32); } namespace { -string GenerateGetBitInternal(const string& prefix, int bitIndex) { - string varName = prefix + GetBitFieldNameForBit(bitIndex); +std::string GenerateGetBitInternal(const std::string& prefix, int bitIndex) { + std::string varName = prefix + GetBitFieldNameForBit(bitIndex); int bitInVarIndex = bitIndex % 32; - string mask = bit_masks[bitInVarIndex]; - string result = "((" + varName + " & " + mask + ") == " + mask + ")"; + std::string mask = bit_masks[bitInVarIndex]; + std::string result = "((" + varName + " & " + mask + ") != 0)"; return result; } -string GenerateSetBitInternal(const string& prefix, int bitIndex) { - string varName = prefix + GetBitFieldNameForBit(bitIndex); +std::string GenerateSetBitInternal(const std::string& prefix, int bitIndex) { + std::string varName = prefix + GetBitFieldNameForBit(bitIndex); int bitInVarIndex = bitIndex % 32; - string mask = bit_masks[bitInVarIndex]; - string result = varName + " |= " + mask; + std::string mask = bit_masks[bitInVarIndex]; + std::string result = varName + " |= " + mask; return result; } } // namespace -string GenerateGetBit(int bitIndex) { +std::string GenerateGetBit(int bitIndex) { return GenerateGetBitInternal("", bitIndex); } -string GenerateSetBit(int bitIndex) { +std::string GenerateSetBit(int bitIndex) { return GenerateSetBitInternal("", bitIndex); } -string GenerateClearBit(int bitIndex) { - string varName = GetBitFieldNameForBit(bitIndex); +std::string GenerateClearBit(int bitIndex) { + std::string varName = GetBitFieldNameForBit(bitIndex); int bitInVarIndex = bitIndex % 32; - string mask = bit_masks[bitInVarIndex]; - string result = varName + " = (" + varName + " & ~" + mask + ")"; + std::string mask = bit_masks[bitInVarIndex]; + std::string result = varName + " = (" + varName + " & ~" + mask + ")"; return result; } -string GenerateGetBitFromLocal(int bitIndex) { +std::string GenerateGetBitFromLocal(int bitIndex) { return GenerateGetBitInternal("from_", bitIndex); } -string GenerateSetBitToLocal(int bitIndex) { +std::string GenerateSetBitToLocal(int bitIndex) { return GenerateSetBitInternal("to_", bitIndex); } -string GenerateGetBitMutableLocal(int bitIndex) { +std::string GenerateGetBitMutableLocal(int bitIndex) { return GenerateGetBitInternal("mutable_", bitIndex); } -string GenerateSetBitMutableLocal(int bitIndex) { +std::string GenerateSetBitMutableLocal(int bitIndex) { return GenerateSetBitInternal("mutable_", bitIndex); } bool IsReferenceType(JavaType type) { switch (type) { - case JAVATYPE_INT : return false; - case JAVATYPE_LONG : return false; - case JAVATYPE_FLOAT : return false; - case JAVATYPE_DOUBLE : return false; - case JAVATYPE_BOOLEAN: return false; - case JAVATYPE_STRING : return true; - case JAVATYPE_BYTES : return true; - case JAVATYPE_ENUM : return true; - case JAVATYPE_MESSAGE: return true; + case JAVATYPE_INT: + return false; + case JAVATYPE_LONG: + return false; + case JAVATYPE_FLOAT: + return false; + case JAVATYPE_DOUBLE: + return false; + case JAVATYPE_BOOLEAN: + return false; + case JAVATYPE_STRING: + return true; + case JAVATYPE_BYTES: + return true; + case JAVATYPE_ENUM: + return true; + case JAVATYPE_MESSAGE: + return true; - // No default because we want the compiler to complain if any new - // JavaTypes are added. + // No default because we want the compiler to complain if any new + // JavaTypes are added. } GOOGLE_LOG(FATAL) << "Can't get here."; @@ -670,29 +725,46 @@ bool IsReferenceType(JavaType type) { const char* GetCapitalizedType(const FieldDescriptor* field, bool immutable) { switch (GetType(field)) { - case FieldDescriptor::TYPE_INT32 : return "Int32"; - case FieldDescriptor::TYPE_UINT32 : return "UInt32"; - case FieldDescriptor::TYPE_SINT32 : return "SInt32"; - case FieldDescriptor::TYPE_FIXED32 : return "Fixed32"; - case FieldDescriptor::TYPE_SFIXED32: return "SFixed32"; - case FieldDescriptor::TYPE_INT64 : return "Int64"; - case FieldDescriptor::TYPE_UINT64 : return "UInt64"; - case FieldDescriptor::TYPE_SINT64 : return "SInt64"; - case FieldDescriptor::TYPE_FIXED64 : return "Fixed64"; - case FieldDescriptor::TYPE_SFIXED64: return "SFixed64"; - case FieldDescriptor::TYPE_FLOAT : return "Float"; - case FieldDescriptor::TYPE_DOUBLE : return "Double"; - case FieldDescriptor::TYPE_BOOL : return "Bool"; - case FieldDescriptor::TYPE_STRING : return "String"; - case FieldDescriptor::TYPE_BYTES : { + case FieldDescriptor::TYPE_INT32: + return "Int32"; + case FieldDescriptor::TYPE_UINT32: + return "UInt32"; + case FieldDescriptor::TYPE_SINT32: + return "SInt32"; + case FieldDescriptor::TYPE_FIXED32: + return "Fixed32"; + case FieldDescriptor::TYPE_SFIXED32: + return "SFixed32"; + case FieldDescriptor::TYPE_INT64: + return "Int64"; + case FieldDescriptor::TYPE_UINT64: + return "UInt64"; + case FieldDescriptor::TYPE_SINT64: + return "SInt64"; + case FieldDescriptor::TYPE_FIXED64: + return "Fixed64"; + case FieldDescriptor::TYPE_SFIXED64: + return "SFixed64"; + case FieldDescriptor::TYPE_FLOAT: + return "Float"; + case FieldDescriptor::TYPE_DOUBLE: + return "Double"; + case FieldDescriptor::TYPE_BOOL: + return "Bool"; + case FieldDescriptor::TYPE_STRING: + return "String"; + case FieldDescriptor::TYPE_BYTES: { return "Bytes"; } - case FieldDescriptor::TYPE_ENUM : return "Enum"; - case FieldDescriptor::TYPE_GROUP : return "Group"; - case FieldDescriptor::TYPE_MESSAGE : return "Message"; + case FieldDescriptor::TYPE_ENUM: + return "Enum"; + case FieldDescriptor::TYPE_GROUP: + return "Group"; + case FieldDescriptor::TYPE_MESSAGE: + return "Message"; - // No default because we want the compiler to complain if any new - // types are added. + // No default because we want the compiler to complain if any new + // types are added. } GOOGLE_LOG(FATAL) << "Can't get here."; @@ -703,29 +775,47 @@ const char* GetCapitalizedType(const FieldDescriptor* field, bool immutable) { // returns -1. int FixedSize(FieldDescriptor::Type type) { switch (type) { - case FieldDescriptor::TYPE_INT32 : return -1; - case FieldDescriptor::TYPE_INT64 : return -1; - case FieldDescriptor::TYPE_UINT32 : return -1; - case FieldDescriptor::TYPE_UINT64 : return -1; - case FieldDescriptor::TYPE_SINT32 : return -1; - case FieldDescriptor::TYPE_SINT64 : return -1; - case FieldDescriptor::TYPE_FIXED32 : return WireFormatLite::kFixed32Size; - case FieldDescriptor::TYPE_FIXED64 : return WireFormatLite::kFixed64Size; - case FieldDescriptor::TYPE_SFIXED32: return WireFormatLite::kSFixed32Size; - case FieldDescriptor::TYPE_SFIXED64: return WireFormatLite::kSFixed64Size; - case FieldDescriptor::TYPE_FLOAT : return WireFormatLite::kFloatSize; - case FieldDescriptor::TYPE_DOUBLE : return WireFormatLite::kDoubleSize; + case FieldDescriptor::TYPE_INT32: + return -1; + case FieldDescriptor::TYPE_INT64: + return -1; + case FieldDescriptor::TYPE_UINT32: + return -1; + case FieldDescriptor::TYPE_UINT64: + return -1; + case FieldDescriptor::TYPE_SINT32: + return -1; + case FieldDescriptor::TYPE_SINT64: + return -1; + case FieldDescriptor::TYPE_FIXED32: + return WireFormatLite::kFixed32Size; + case FieldDescriptor::TYPE_FIXED64: + return WireFormatLite::kFixed64Size; + case FieldDescriptor::TYPE_SFIXED32: + return WireFormatLite::kSFixed32Size; + case FieldDescriptor::TYPE_SFIXED64: + return WireFormatLite::kSFixed64Size; + case FieldDescriptor::TYPE_FLOAT: + return WireFormatLite::kFloatSize; + case FieldDescriptor::TYPE_DOUBLE: + return WireFormatLite::kDoubleSize; - case FieldDescriptor::TYPE_BOOL : return WireFormatLite::kBoolSize; - case FieldDescriptor::TYPE_ENUM : return -1; + case FieldDescriptor::TYPE_BOOL: + return WireFormatLite::kBoolSize; + case FieldDescriptor::TYPE_ENUM: + return -1; - case FieldDescriptor::TYPE_STRING : return -1; - case FieldDescriptor::TYPE_BYTES : return -1; - case FieldDescriptor::TYPE_GROUP : return -1; - case FieldDescriptor::TYPE_MESSAGE : return -1; + case FieldDescriptor::TYPE_STRING: + return -1; + case FieldDescriptor::TYPE_BYTES: + return -1; + case FieldDescriptor::TYPE_GROUP: + return -1; + case FieldDescriptor::TYPE_MESSAGE: + return -1; - // No default because we want the compiler to complain if any new - // types are added. + // No default because we want the compiler to complain if any new + // types are added. } GOOGLE_LOG(FATAL) << "Can't get here."; return -1; @@ -735,7 +825,7 @@ int FixedSize(FieldDescriptor::Type type) { // and return it. The caller should delete the returned array. const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) { const FieldDescriptor** fields = - new const FieldDescriptor*[descriptor->field_count()]; + new const FieldDescriptor*[descriptor->field_count()]; for (int i = 0; i < descriptor->field_count(); i++) { fields[i] = descriptor->field(i); } @@ -749,9 +839,8 @@ const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) { // // already_seen is used to avoid checking the same type multiple times // (and also to protect against recursion). -bool HasRequiredFields( - const Descriptor* type, - hash_set* already_seen) { +bool HasRequiredFields(const Descriptor* type, + std::unordered_set* already_seen) { if (already_seen->count(type) > 0) { // The type is already in cache. This means that either: // a. The type has no required fields. @@ -786,7 +875,7 @@ bool HasRequiredFields( } bool HasRequiredFields(const Descriptor* type) { - hash_set already_seen; + std::unordered_set already_seen; return HasRequiredFields(type, &already_seen); } @@ -908,7 +997,7 @@ int GetExperimentalJavaFieldType(const FieldDescriptor* field) { } // Escape a UTF-16 character to be embedded in a Java string. -void EscapeUtf16ToString(uint16 code, string* output) { +void EscapeUtf16ToString(uint16 code, std::string* output) { if (code == '\t') { output->append("\\t"); } else if (code == '\b') { @@ -932,22 +1021,6 @@ void EscapeUtf16ToString(uint16 code, string* output) { } } -std::pair GetTableDrivenNumberOfEntriesAndLookUpStartFieldNumber( - const FieldDescriptor** fields, int count) { - GOOGLE_CHECK_GT(count, 0); - int table_driven_number_of_entries = count; - int look_up_start_field_number = 0; - for (int i = 0; i < count; i++) { - const int field_number = fields[i]->number(); - if (ShouldUseTable(fields[0]->number(), field_number, i + 1)) { - table_driven_number_of_entries = - field_number - fields[0]->number() + 1 + count - i - 1; - look_up_start_field_number = field_number + 1; - } - } - return std::make_pair( - table_driven_number_of_entries, look_up_start_field_number); -} } // namespace java } // namespace compiler } // namespace protobuf diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_helpers.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_helpers.h index dd9b65b8..b06ab208 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_helpers.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_helpers.h @@ -60,79 +60,84 @@ extern const char kThinSeparator[]; // annotation_file should be generated from the filename of the source file // being annotated (which in turn must be a Java identifier plus ".java"). void PrintGeneratedAnnotation(io::Printer* printer, char delimiter = '$', - const string& annotation_file = ""); + const std::string& annotation_file = ""); + +// If a GeneratedMessageLite contains non-lite enums, then its verifier +// must be instantiated inline, rather than retrieved from the enum class. +void PrintEnumVerifierLogic(io::Printer* printer, + const FieldDescriptor* descriptor, + const std::map& variables, + const char* var_name, + const char* terminating_string, bool enforce_lite); // Converts a name to camel-case. If cap_first_letter is true, capitalize the // first letter. -string UnderscoresToCamelCase(const string& name, bool cap_first_letter); +std::string UnderscoresToCamelCase(const std::string& name, + bool cap_first_letter); // Converts the field's name to camel-case, e.g. "foo_bar_baz" becomes // "fooBarBaz" or "FooBarBaz", respectively. -string UnderscoresToCamelCase(const FieldDescriptor* field); -string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field); +std::string UnderscoresToCamelCase(const FieldDescriptor* field); +std::string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field); // Similar, but for method names. (Typically, this merely has the effect // of lower-casing the first letter of the name.) -string UnderscoresToCamelCase(const MethodDescriptor* method); +std::string UnderscoresToCamelCase(const MethodDescriptor* method); + +// Same as UnderscoresToCamelCase, but checks for reserved keywords +std::string UnderscoresToCamelCaseCheckReserved(const FieldDescriptor* field); // Similar to UnderscoresToCamelCase, but guarentees that the result is a // complete Java identifier by adding a _ if needed. -string CamelCaseFieldName(const FieldDescriptor* field); +std::string CamelCaseFieldName(const FieldDescriptor* field); // Get an identifier that uniquely identifies this type within the file. // This is used to declare static variables related to this type at the // outermost file scope. -string UniqueFileScopeIdentifier(const Descriptor* descriptor); +std::string UniqueFileScopeIdentifier(const Descriptor* descriptor); // Strips ".proto" or ".protodevel" from the end of a filename. -string StripProto(const string& filename); +std::string StripProto(const std::string& filename); // Gets the unqualified class name for the file. For each .proto file, there // will be one Java class containing all the immutable messages and another // Java class containing all the mutable messages. // TODO(xiaofeng): remove the default value after updating client code. -string FileClassName(const FileDescriptor* file, bool immutable = true); +std::string FileClassName(const FileDescriptor* file, bool immutable = true); // Returns the file's Java package name. -string FileJavaPackage(const FileDescriptor* file, bool immutable = true); +std::string FileJavaPackage(const FileDescriptor* file); +std::string FileJavaPackage(const FileDescriptor* file, bool immutable); // Returns output directory for the given package name. -string JavaPackageToDir(string package_name); - -// Converts the given fully-qualified name in the proto namespace to its -// fully-qualified name in the Java namespace, given that it is in the given -// file. -// TODO(xiaofeng): this method is deprecated and should be removed in the -// future. -string ToJavaName(const string& full_name, - const FileDescriptor* file); +std::string JavaPackageToDir(std::string package_name); // TODO(xiaofeng): the following methods are kept for they are exposed -// publicly in //google/protobuf/compiler/java/names.h. They return +// publicly in //net/proto2/compiler/java/public/names.h. They return // immutable names only and should be removed after mutable API is // integrated into google3. -string ClassName(const Descriptor* descriptor); -string ClassName(const EnumDescriptor* descriptor); -string ClassName(const ServiceDescriptor* descriptor); -string ClassName(const FileDescriptor* descriptor); +std::string ClassName(const Descriptor* descriptor); +std::string ClassName(const EnumDescriptor* descriptor); +std::string ClassName(const ServiceDescriptor* descriptor); +std::string ClassName(const FileDescriptor* descriptor); // Comma-separate list of option-specified interfaces implemented by the // Message, to follow the "implements" declaration of the Message definition. -string ExtraMessageInterfaces(const Descriptor* descriptor); +std::string ExtraMessageInterfaces(const Descriptor* descriptor); // Comma-separate list of option-specified interfaces implemented by the // MutableMessage, to follow the "implements" declaration of the MutableMessage // definition. -string ExtraMutableMessageInterfaces(const Descriptor* descriptor); +std::string ExtraMutableMessageInterfaces(const Descriptor* descriptor); // Comma-separate list of option-specified interfaces implemented by the // Builder, to follow the "implements" declaration of the Builder definition. -string ExtraBuilderInterfaces(const Descriptor* descriptor); +std::string ExtraBuilderInterfaces(const Descriptor* descriptor); // Comma-separate list of option-specified interfaces extended by the // MessageOrBuilder, to follow the "extends" declaration of the // MessageOrBuilder definition. -string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor); +std::string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor); // Get the unqualified Java class name for mutable messages. i.e. without // package or outer classnames. -inline string ShortMutableJavaClassName(const Descriptor* descriptor) { +inline std::string ShortMutableJavaClassName(const Descriptor* descriptor) { return descriptor->name(); } @@ -140,13 +145,18 @@ inline string ShortMutableJavaClassName(const Descriptor* descriptor) { // cannot currently use the new runtime with core protos since there is a // bootstrapping problem with obtaining their descriptors. inline bool IsDescriptorProto(const Descriptor* descriptor) { - return descriptor->file()->name() == "google/protobuf/descriptor.proto"; + return descriptor->file()->name() == "net/proto2/proto/descriptor.proto" || + descriptor->file()->name() == "google/protobuf/descriptor.proto"; } +// Returns the stored type string used by the experimental runtime for oneof +// fields. +std::string GetOneofStoredType(const FieldDescriptor* field); + // Whether we should generate multiple java files for messages. -inline bool MultipleJavaFiles( - const FileDescriptor* descriptor, bool immutable) { +inline bool MultipleJavaFiles(const FileDescriptor* descriptor, + bool immutable) { return descriptor->options().java_multiple_files(); } @@ -168,14 +178,15 @@ inline bool IsOwnFile(const ServiceDescriptor* descriptor, bool immutable) { // annotation data for that descriptor. `suffix` is usually empty, but may // (e.g.) be "OrBuilder" for some generated interfaces. template -string AnnotationFileName(const Descriptor* descriptor, const string& suffix) { +std::string AnnotationFileName(const Descriptor* descriptor, + const std::string& suffix) { return descriptor->name() + suffix + ".java.pb.meta"; } template void MaybePrintGeneratedAnnotation(Context* context, io::Printer* printer, Descriptor* descriptor, bool immutable, - const string& suffix = "") { + const std::string& suffix = "") { if (context->options().annotate_code && IsOwnFile(descriptor, immutable)) { PrintGeneratedAnnotation(printer, '$', AnnotationFileName(descriptor, suffix)); @@ -184,7 +195,7 @@ void MaybePrintGeneratedAnnotation(Context* context, io::Printer* printer, // Get the unqualified name that should be used for a field's field // number constant. -string FieldConstantName(const FieldDescriptor *field); +std::string FieldConstantName(const FieldDescriptor* field); // Returns the type of the FieldDescriptor. // This does nothing interesting for the open source release, but is used for @@ -218,10 +229,10 @@ const char* BoxedPrimitiveTypeName(JavaType type); const char* FieldTypeName(const FieldDescriptor::Type field_type); class ClassNameResolver; -string DefaultValue(const FieldDescriptor* field, bool immutable, - ClassNameResolver* name_resolver); -inline string ImmutableDefaultValue(const FieldDescriptor* field, - ClassNameResolver* name_resolver) { +std::string DefaultValue(const FieldDescriptor* field, bool immutable, + ClassNameResolver* name_resolver); +inline std::string ImmutableDefaultValue(const FieldDescriptor* field, + ClassNameResolver* name_resolver) { return DefaultValue(field, true, name_resolver); } bool IsDefaultValueJavaDefault(const FieldDescriptor* field); @@ -230,24 +241,19 @@ bool IsByteStringWithCustomDefaultValue(const FieldDescriptor* field); // Does this message class have descriptor and reflection methods? inline bool HasDescriptorMethods(const Descriptor* descriptor, bool enforce_lite) { - return !enforce_lite && - descriptor->file()->options().optimize_for() != - FileOptions::LITE_RUNTIME; + return !enforce_lite; } inline bool HasDescriptorMethods(const EnumDescriptor* descriptor, bool enforce_lite) { - return !enforce_lite && - descriptor->file()->options().optimize_for() != - FileOptions::LITE_RUNTIME; + return !enforce_lite; } inline bool HasDescriptorMethods(const FileDescriptor* descriptor, bool enforce_lite) { - return !enforce_lite && - descriptor->options().optimize_for() != FileOptions::LITE_RUNTIME; + return !enforce_lite; } // Should we generate generic services for this file? -inline bool HasGenericServices(const FileDescriptor *file, bool enforce_lite) { +inline bool HasGenericServices(const FileDescriptor* file, bool enforce_lite) { return file->service_count() > 0 && HasDescriptorMethods(file, enforce_lite) && file->options().java_generic_services(); @@ -256,50 +262,50 @@ inline bool HasGenericServices(const FileDescriptor *file, bool enforce_lite) { // Methods for shared bitfields. // Gets the name of the shared bitfield for the given index. -string GetBitFieldName(int index); +std::string GetBitFieldName(int index); // Gets the name of the shared bitfield for the given bit index. // Effectively, GetBitFieldName(bitIndex / 32) -string GetBitFieldNameForBit(int bitIndex); +std::string GetBitFieldNameForBit(int bitIndex); // Generates the java code for the expression that returns the boolean value // of the bit of the shared bitfields for the given bit index. // Example: "((bitField1_ & 0x04) == 0x04)" -string GenerateGetBit(int bitIndex); +std::string GenerateGetBit(int bitIndex); // Generates the java code for the expression that sets the bit of the shared // bitfields for the given bit index. // Example: "bitField1_ = (bitField1_ | 0x04)" -string GenerateSetBit(int bitIndex); +std::string GenerateSetBit(int bitIndex); // Generates the java code for the expression that clears the bit of the shared // bitfields for the given bit index. // Example: "bitField1_ = (bitField1_ & ~0x04)" -string GenerateClearBit(int bitIndex); +std::string GenerateClearBit(int bitIndex); // Does the same as GenerateGetBit but operates on the bit field on a local // variable. This is used by the builder to copy the value in the builder to // the message. // Example: "((from_bitField1_ & 0x04) == 0x04)" -string GenerateGetBitFromLocal(int bitIndex); +std::string GenerateGetBitFromLocal(int bitIndex); // Does the same as GenerateSetBit but operates on the bit field on a local // variable. This is used by the builder to copy the value in the builder to // the message. // Example: "to_bitField1_ = (to_bitField1_ | 0x04)" -string GenerateSetBitToLocal(int bitIndex); +std::string GenerateSetBitToLocal(int bitIndex); // Does the same as GenerateGetBit but operates on the bit field on a local // variable. This is used by the parsing constructor to record if a repeated // field is mutable. // Example: "((mutable_bitField1_ & 0x04) == 0x04)" -string GenerateGetBitMutableLocal(int bitIndex); +std::string GenerateGetBitMutableLocal(int bitIndex); // Does the same as GenerateSetBit but operates on the bit field on a local // variable. This is used by the parsing constructor to record if a repeated // field is mutable. // Example: "mutable_bitField1_ = (mutable_bitField1_ | 0x04)" -string GenerateSetBitMutableLocal(int bitIndex); +std::string GenerateSetBitMutableLocal(int bitIndex); // Returns whether the JavaType is a reference type. bool IsReferenceType(JavaType type); @@ -384,17 +390,13 @@ inline bool IsWrappersProtoFile(const FileDescriptor* descriptor) { inline bool CheckUtf8(const FieldDescriptor* descriptor) { return descriptor->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 || - descriptor->file()->options().java_string_check_utf8(); + descriptor->file()->options().java_string_check_utf8(); } -inline string GeneratedCodeVersionSuffix() { +inline std::string GeneratedCodeVersionSuffix() { return "V3"; } -inline bool EnableExperimentalRuntime(Context* context) { - return false; -} - void WriteUInt32ToUtf16CharSequence(uint32 number, std::vector* output); inline void WriteIntToUtf16CharSequence(int value, @@ -403,7 +405,7 @@ inline void WriteIntToUtf16CharSequence(int value, } // Escape a UTF-16 character so it can be embedded in a Java string literal. -void EscapeUtf16ToString(uint16 code, string* output); +void EscapeUtf16ToString(uint16 code, std::string* output); // Only the lowest two bytes of the return value are used. The lowest byte // is the integer value of a j/c/g/protobuf/FieldType enum. For the other @@ -422,6 +424,6 @@ std::pair GetTableDrivenNumberOfEntriesAndLookUpStartFieldNumber( } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_lazy_message_field.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_lazy_message_field.cc deleted file mode 100644 index abf8e55c..00000000 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_lazy_message_field.cc +++ /dev/null @@ -1,814 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Author: niwasaki@google.com (Naoki Iwasaki) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -ImmutableLazyMessageFieldGenerator:: -ImmutableLazyMessageFieldGenerator( - const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableMessageFieldGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { -} - -ImmutableLazyMessageFieldGenerator::~ImmutableLazyMessageFieldGenerator() {} - -void ImmutableLazyMessageFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private com.google.protobuf.LazyFieldLite $name$_ =\n" - " new com.google.protobuf.LazyFieldLite();\n"); - - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$() {\n" - " return ($type$) $name$_.getValue($type$.getDefaultInstance());\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder() {\n" - " return $name$_;\n" - "}\n"); -} - -void ImmutableLazyMessageFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // When using nested-builders, the code initially works just like the - // non-nested builder case. It only creates a nested builder lazily on - // demand and then forever delegates to it after creation. - - printer->Print(variables_, - "private com.google.protobuf.LazyFieldLite $name$_ =\n" - " new com.google.protobuf.LazyFieldLite();\n"); - - printer->Print(variables_, - // If this builder is non-null, it is used and the other fields are - // ignored. - "private com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;" - "\n"); - - // The comments above the methods below are based on a hypothetical - // field of type "Field" called "Field". - - // boolean hasField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return $get_has_field_bit_builder$;\n" - "}\n"); - - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$() {\n" - " return ($type$) $name$_.getValue($type$.getDefaultInstance());\n" - "}\n"); - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder set$capitalized_name$($type$ value)", - - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "$name$_.setValue(value);\n" - "$on_changed$\n", - - NULL, // Lazy fields are supported only for lite-runtime. - - "$set_has_field_bit_builder$;\n" - "return this;\n"); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder set$capitalized_name$(\n" - " $type$.Builder builderForValue)", - - "$name$_.setValue(builderForValue.build());\n" - "$on_changed$\n", - - NULL, - - "$set_has_field_bit_builder$;\n" - "return this;\n"); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder merge$capitalized_name$($type$ value)", - - "if ($get_has_field_bit_builder$ &&\n" - " !$name$_.containsDefaultInstance()) {\n" - " $name$_.setValue(\n" - " $type$.newBuilder(\n" - " get$capitalized_name$()).mergeFrom(value).buildPartial());\n" - "} else {\n" - " $name$_.setValue(value);\n" - "}\n" - "$on_changed$\n", - - NULL, - - "$set_has_field_bit_builder$;\n" - "return this;\n"); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder clear$capitalized_name$()", - - "$name$_.clear();\n" - "$on_changed$\n", - - NULL, - - "$clear_has_field_bit_builder$;\n" - "return this;\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$.Builder get$capitalized_name$Builder() {\n" - " $set_has_field_bit_builder$;\n" - " $on_changed$\n" - " return get$capitalized_name$FieldBuilder().getBuilder();\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder() {\n" - " if ($name$Builder_ != null) {\n" - " return $name$Builder_.getMessageOrBuilder();\n" - " } else {\n" - " return $name$_;\n" - " }\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> \n" - " get$capitalized_name$FieldBuilder() {\n" - " if ($name$Builder_ == null) {\n" - " $name$Builder_ = new com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder>(\n" - " $name$_,\n" - " getParentForChildren(),\n" - " isClean());\n" - " $name$_ = null;\n" - " }\n" - " return $name$Builder_;\n" - "}\n"); -} - - -void ImmutableLazyMessageFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.clear();\n"); -} - -void ImmutableLazyMessageFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.clear();\n"); - printer->Print(variables_, "$clear_has_field_bit_builder$;\n"); -} - -void ImmutableLazyMessageFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (other.has$capitalized_name$()) {\n" - " $name$_.merge(other.$name$_);\n" - " $set_has_field_bit_builder$;\n" - "}\n"); -} - -void ImmutableLazyMessageFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($get_has_field_bit_from_local$) {\n" - " $set_has_field_bit_to_local$;\n" - "}\n"); - - printer->Print(variables_, - "result.$name$_.set(\n" - " $name$_);\n"); -} - -void ImmutableLazyMessageFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_.setByteString(input.readBytes(), extensionRegistry);\n"); - printer->Print(variables_, - "$set_has_field_bit_message$;\n"); -} - -void ImmutableLazyMessageFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - // Do not de-serialize lazy fields. - printer->Print(variables_, - "if ($get_has_field_bit_message$) {\n" - " output.writeBytes($number$, $name$_.toByteString());\n" - "}\n"); -} - -void ImmutableLazyMessageFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($get_has_field_bit_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeLazyFieldSize($number$, $name$_);\n" - "}\n"); -} - -// =================================================================== - -ImmutableLazyMessageOneofFieldGenerator:: -ImmutableLazyMessageOneofFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableLazyMessageFieldGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { - const OneofGeneratorInfo* info = - context->GetOneofGeneratorInfo(descriptor->containing_oneof()); - SetCommonOneofVariables(descriptor, info, &variables_); - variables_["lazy_type"] = "com.google.protobuf.LazyFieldLite"; -} - -ImmutableLazyMessageOneofFieldGenerator:: -~ImmutableLazyMessageOneofFieldGenerator() {} - -void ImmutableLazyMessageOneofFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($type$) (($lazy_type$) $oneof_name$_).getValue(\n" - " $type$.getDefaultInstance());\n" - " }\n" - " return $type$.getDefaultInstance();\n" - "}\n"); -} - -void ImmutableLazyMessageOneofFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // boolean hasField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($type$) (($lazy_type$) $oneof_name$_).getValue(\n" - " $type$.getDefaultInstance());\n" - " }\n" - " return $type$.getDefaultInstance();\n" - "}\n"); - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder set$capitalized_name$($type$ value)", - - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - " $set_oneof_case_message$;\n" - "}\n" - "(($lazy_type$) $oneof_name$_).setValue(value);\n" - "$on_changed$\n", - - NULL, // Lazy fields are supported only for lite-runtime. - - "return this;\n"); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder set$capitalized_name$(\n" - " $type$.Builder builderForValue)", - - "if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - " $set_oneof_case_message$;\n" - "}\n" - "(($lazy_type$) $oneof_name$_).setValue(builderForValue.build());\n" - "$on_changed$\n", - - NULL, - - "return this;\n"); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder merge$capitalized_name$($type$ value)", - - "if ($has_oneof_case_message$ &&\n" - " !(($lazy_type$) $oneof_name$_).containsDefaultInstance()) {\n" - " (($lazy_type$) $oneof_name$_).setValue(\n" - " $type$.newBuilder(\n" - " get$capitalized_name$()).mergeFrom(value).buildPartial());\n" - "} else {\n" - " if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - " $set_oneof_case_message$;\n" - " }\n" - " (($lazy_type$) $oneof_name$_).setValue(value);\n" - "}\n" - "$on_changed$\n", - - NULL, - - "return this;\n"); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder clear$capitalized_name$()", - - "if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " $on_changed$\n" - "}\n", - - NULL, - - "return this;\n"); -} - -void ImmutableLazyMessageOneofFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - "}\n" - "(($lazy_type$) $oneof_name$_).merge(\n" - " ($lazy_type$) other.$oneof_name$_);\n" - "$set_oneof_case_message$;\n"); -} - -void ImmutableLazyMessageOneofFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n"); - printer->Indent(); - - printer->Print(variables_, - "result.$oneof_name$_ = new $lazy_type$();\n" - "(($lazy_type$) result.$oneof_name$_).set(\n" - " (($lazy_type$) $oneof_name$_));\n"); - printer->Outdent(); - printer->Print("}\n"); -} - -void ImmutableLazyMessageOneofFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - "}\n" - "(($lazy_type$) $oneof_name$_).setByteString(\n" - " input.readBytes(), extensionRegistry);\n" - "$set_oneof_case_message$;\n"); -} - -void ImmutableLazyMessageOneofFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - // Do not de-serialize lazy fields. - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.writeBytes(\n" - " $number$, (($lazy_type$) $oneof_name$_).toByteString());\n" - "}\n"); -} - -void ImmutableLazyMessageOneofFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeLazyFieldSize($number$, ($lazy_type$) $oneof_name$_);\n" - "}\n"); -} - -// =================================================================== - -RepeatedImmutableLazyMessageFieldGenerator:: -RepeatedImmutableLazyMessageFieldGenerator( - const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : RepeatedImmutableMessageFieldGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { -} - - -RepeatedImmutableLazyMessageFieldGenerator:: -~RepeatedImmutableLazyMessageFieldGenerator() {} - -void RepeatedImmutableLazyMessageFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private java.util.List $name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List<$type$>\n" - " get$capitalized_name$List() {\n" - " java.util.List<$type$> list =\n" - " new java.util.ArrayList<$type$>($name$_.size());\n" - " for (com.google.protobuf.LazyFieldLite lf : $name$_) {\n" - " list.add(($type$) lf.getValue($type$.getDefaultInstance()));\n" - " }\n" - " return list;\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List\n" - " get$capitalized_name$OrBuilderList() {\n" - " return get$capitalized_name$List();\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int get$capitalized_name$Count() {\n" - " return $name$_.size();\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$(int index) {\n" - " return ($type$)\n" - " $name$_.get(index).getValue($type$.getDefaultInstance());\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n" - " int index) {\n" - " return ($type$OrBuilder)\n" - " $name$_.get(index).getValue($type$.getDefaultInstance());\n" - "}\n"); -} - -void RepeatedImmutableLazyMessageFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // When using nested-builders, the code initially works just like the - // non-nested builder case. It only creates a nested builder lazily on - // demand and then forever delegates to it after creation. - - printer->Print(variables_, - "private java.util.List $name$_ =\n" - " java.util.Collections.emptyList();\n" - - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$get_mutable_bit_builder$) {\n" - " $name$_ =\n" - " new java.util.ArrayList(\n" - " $name$_);\n" - " $set_mutable_bit_builder$;\n" - " }\n" - "}\n" - "\n"); - - printer->Print(variables_, - // If this builder is non-null, it is used and the other fields are - // ignored. - "private com.google.protobuf.RepeatedFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;\n" - "\n"); - - // The comments above the methods below are based on a hypothetical - // repeated field of type "Field" called "RepeatedField". - - // List getRepeatedFieldList() - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public java.util.List<$type$> get$capitalized_name$List()", - - "java.util.List<$type$> list =\n" - " new java.util.ArrayList<$type$>($name$_.size());\n" - "for (com.google.protobuf.LazyFieldLite lf : $name$_) {\n" - " list.add(($type$) lf.getValue($type$.getDefaultInstance()));\n" - "}\n" - "return java.util.Collections.unmodifiableList(list);\n", - - "return $name$Builder_.getMessageList();\n", - - NULL); - - // int getRepeatedFieldCount() - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public int get$capitalized_name$Count()", - - "return $name$_.size();\n", - "return $name$Builder_.getCount();\n", - - NULL); - - // Field getRepeatedField(int index) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public $type$ get$capitalized_name$(int index)", - - "return ($type$) $name$_.get(index).getValue(\n" - " $type$.getDefaultInstance());\n", - - "return $name$Builder_.getMessage(index);\n", - - NULL); - - // Builder setRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder set$capitalized_name$(\n" - " int index, $type$ value)", - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "ensure$capitalized_name$IsMutable();\n" - "$name$_.set(index, com.google.protobuf.LazyFieldLite.fromValue(value));\n" - "$on_changed$\n", - "$name$Builder_.setMessage(index, value);\n", - "return this;\n"); - - // Builder setRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder set$capitalized_name$(\n" - " int index, $type$.Builder builderForValue)", - - "ensure$capitalized_name$IsMutable();\n" - "$name$_.set(index, com.google.protobuf.LazyFieldLite.fromValue(\n" - " builderForValue.build()));\n" - "$on_changed$\n", - - "$name$Builder_.setMessage(index, builderForValue.build());\n", - - "return this;\n"); - - // Builder addRepeatedField(Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder add$capitalized_name$($type$ value)", - - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "ensure$capitalized_name$IsMutable();\n" - "$name$_.add(com.google.protobuf.LazyFieldLite.fromValue(value));\n" - - "$on_changed$\n", - - "$name$Builder_.addMessage(value);\n", - - "return this;\n"); - - // Builder addRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder add$capitalized_name$(\n" - " int index, $type$ value)", - - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "ensure$capitalized_name$IsMutable();\n" - "$name$_.add(index, com.google.protobuf.LazyFieldLite.fromValue(value));\n" - "$on_changed$\n", - - "$name$Builder_.addMessage(index, value);\n", - - "return this;\n"); - - // Builder addRepeatedField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder add$capitalized_name$(\n" - " $type$.Builder builderForValue)", - - "ensure$capitalized_name$IsMutable();\n" - "$name$_.add(com.google.protobuf.LazyFieldLite.fromValue(\n" - " builderForValue.build()));\n" - "$on_changed$\n", - - "$name$Builder_.addMessage(builderForValue.build());\n", - - "return this;\n"); - - // Builder addRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder add$capitalized_name$(\n" - " int index, $type$.Builder builderForValue)", - - "ensure$capitalized_name$IsMutable();\n" - "$name$_.add(index, com.google.protobuf.LazyFieldLite.fromValue(\n" - " builderForValue.build()));\n" - "$on_changed$\n", - - "$name$Builder_.addMessage(index, builderForValue.build());\n", - - "return this;\n"); - - // Builder addAllRepeatedField(Iterable values) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder addAll$capitalized_name$(\n" - " java.lang.Iterable values)", - - "ensure$capitalized_name$IsMutable();\n" - "for (com.google.protobuf.MessageLite v : values) {\n" - " $name$_.add(com.google.protobuf.LazyFieldLite.fromValue(v));\n" - "}\n" - "$on_changed$\n", - - "$name$Builder_.addAllMessages(values);\n", - - "return this;\n"); - - // Builder clearAllRepeatedField() - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder clear$capitalized_name$()", - - "$name$_ = java.util.Collections.emptyList();\n" - "$clear_mutable_bit_builder$;\n" - "$on_changed$\n", - - "$name$Builder_.clear();\n", - - "return this;\n"); - - // Builder removeRepeatedField(int index) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder remove$capitalized_name$(int index)", - - "ensure$capitalized_name$IsMutable();\n" - "$name$_.remove(index);\n" - "$on_changed$\n", - - "$name$Builder_.remove(index);\n", - - "return this;\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$.Builder get$capitalized_name$Builder(\n" - " int index) {\n" - " return get$capitalized_name$FieldBuilder().getBuilder(index);\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n" - " int index) {\n" - " if ($name$Builder_ == null) {\n" - " return $name$_.get(index);" - " } else {\n" - " return $name$Builder_.getMessageOrBuilder(index);\n" - " }\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List \n" - " get$capitalized_name$OrBuilderList() {\n" - " if ($name$Builder_ != null) {\n" - " return $name$Builder_.getMessageOrBuilderList();\n" - " } else {\n" - " return java.util.Collections.unmodifiableList($name$_);\n" - " }\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$.Builder add$capitalized_name$Builder() {\n" - " return get$capitalized_name$FieldBuilder().addBuilder(\n" - " $type$.getDefaultInstance());\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$.Builder add$capitalized_name$Builder(\n" - " int index) {\n" - " return get$capitalized_name$FieldBuilder().addBuilder(\n" - " index, $type$.getDefaultInstance());\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List<$type$.Builder> \n" - " get$capitalized_name$BuilderList() {\n" - " return get$capitalized_name$FieldBuilder().getBuilderList();\n" - "}\n" - "private com.google.protobuf.RepeatedFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> \n" - " get$capitalized_name$FieldBuilder() {\n" - " if ($name$Builder_ == null) {\n" - " $name$Builder_ = new com.google.protobuf.RepeatedFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder>(\n" - " $name$_,\n" - " $get_mutable_bit_builder$,\n" - " getParentForChildren(),\n" - " isClean());\n" - " $name$_ = null;\n" - " }\n" - " return $name$Builder_;\n" - "}\n"); -} - -void RepeatedImmutableLazyMessageFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!$get_mutable_bit_parser$) {\n" - " $name$_ =\n" - " new java.util.ArrayList();\n" - " $set_mutable_bit_parser$;\n" - "}\n" - "$name$_.add(new com.google.protobuf.LazyFieldLite(\n" - " extensionRegistry, input.readBytes()));\n"); -} - -void RepeatedImmutableLazyMessageFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.writeBytes($number$, $name$_.get(i).toByteString());\n" - "}\n"); -} - -void RepeatedImmutableLazyMessageFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeLazyFieldSize($number$, $name$_.get(i));\n" - "}\n"); -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_lazy_message_field.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_lazy_message_field.h deleted file mode 100644 index b1b7f282..00000000 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_lazy_message_field.h +++ /dev/null @@ -1,121 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Author: niwasaki@google.com (Naoki Iwasaki) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_H__ - -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - } - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class ImmutableLazyMessageFieldGenerator - : public ImmutableMessageFieldGenerator { - public: - explicit ImmutableLazyMessageFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableLazyMessageFieldGenerator(); - - // overroads ImmutableMessageFieldGenerator --------------------------------- - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateBuilderClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableLazyMessageFieldGenerator); -}; - -class ImmutableLazyMessageOneofFieldGenerator - : public ImmutableLazyMessageFieldGenerator { - public: - ImmutableLazyMessageOneofFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableLazyMessageOneofFieldGenerator(); - - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableLazyMessageOneofFieldGenerator); -}; - -class RepeatedImmutableLazyMessageFieldGenerator - : public RepeatedImmutableMessageFieldGenerator { - public: - explicit RepeatedImmutableLazyMessageFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~RepeatedImmutableLazyMessageFieldGenerator(); - - // overroads RepeatedImmutableMessageFieldGenerator ------------------------- - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableLazyMessageFieldGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_lazy_message_field_lite.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_lazy_message_field_lite.cc deleted file mode 100644 index 51bb11f1..00000000 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_lazy_message_field_lite.cc +++ /dev/null @@ -1,725 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Author: niwasaki@google.com (Naoki Iwasaki) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -ImmutableLazyMessageFieldLiteGenerator:: -ImmutableLazyMessageFieldLiteGenerator( - const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableMessageFieldLiteGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { -} - -ImmutableLazyMessageFieldLiteGenerator:: -~ImmutableLazyMessageFieldLiteGenerator() {} - -void ImmutableLazyMessageFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private com.google.protobuf.LazyFieldLite $name$_;"); - - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); - } else { - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return $name$_ != null;\n" - "}\n"); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$() {\n" - " if ($name$_ == null) {\n" - " return $type$.getDefaultInstance();\n" - " }\n" - " return ($type$) $name$_.getValue($type$.getDefaultInstance());\n" - "}\n"); - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " if ($name$_ == null) {\n" - " $name$_ = new com.google.protobuf.LazyFieldLite();\n" - " }\n" - " $name$_.setValue(value);\n" - " $set_has_field_bit_message$\n" - "}\n"); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " if ($name$_ == null) {\n" - " $name$_ = new com.google.protobuf.LazyFieldLite();\n" - " }\n" - " $name$_.setValue(builderForValue.build());\n" - " $set_has_field_bit_message$\n" - "}\n"); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void merge$capitalized_name$($type$ value) {\n" - " if (has$capitalized_name$() &&\n" - " !$name$_.containsDefaultInstance()) {\n" - " $name$_.setValue(\n" - " $type$.newBuilder(\n" - " get$capitalized_name$()).mergeFrom(value).buildPartial());\n" - " } else {\n" - " if ($name$_ == null) {\n" - " $name$_ = new com.google.protobuf.LazyFieldLite();\n" - " }\n" - " $name$_.setValue(value);\n" - " $set_has_field_bit_message$\n" - " }\n" - "}\n"); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $name$_ = null;\n" - " $clear_has_field_bit_message$;\n" - "}\n"); -} - -void ImmutableLazyMessageFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // The comments above the methods below are based on a hypothetical - // field of type "Field" called "Field". - - // boolean hasField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder set$capitalized_name$($type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder set$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(builderForValue);\n" - " return this;\n" - "}\n"); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder merge$capitalized_name$($type$ value) {\n" - " copyOnWrite();\n" - " instance.merge$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder clear$capitalized_name$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); -} - - -void ImmutableLazyMessageFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const {} - -void ImmutableLazyMessageFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_ = visitor.visitLazyMessage($name$_, other.$name$_);\n"); -} - -void ImmutableLazyMessageFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($name$_ == null) {\n" - " $name$_ = new com.google.protobuf.LazyFieldLite();\n" - "}\n" - "$name$_.mergeFrom(input, extensionRegistry);\n"); - printer->Print(variables_, - "$set_has_field_bit_message$\n"); -} - -void ImmutableLazyMessageFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - // Do not de-serialize lazy fields. - printer->Print(variables_, - "if (has$capitalized_name$()) {\n" - " output.writeBytes($number$, $name$_.toByteString());\n" - "}\n"); -} - -void ImmutableLazyMessageFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if (has$capitalized_name$()) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeLazyFieldSize($number$, $name$_);\n" - "}\n"); -} - - -// =================================================================== - -ImmutableLazyMessageOneofFieldLiteGenerator:: -ImmutableLazyMessageOneofFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableLazyMessageFieldLiteGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { - const OneofGeneratorInfo* info = - context->GetOneofGeneratorInfo(descriptor->containing_oneof()); - SetCommonOneofVariables(descriptor, info, &variables_); - variables_["lazy_type"] = "com.google.protobuf.LazyFieldLite"; -} - -ImmutableLazyMessageOneofFieldLiteGenerator:: -~ImmutableLazyMessageOneofFieldLiteGenerator() {} - -void ImmutableLazyMessageOneofFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($type$) (($lazy_type$) $oneof_name$_).getValue(\n" - " $type$.getDefaultInstance());\n" - " }\n" - " return $type$.getDefaultInstance();\n" - "}\n"); - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - " $set_oneof_case_message$;\n" - " }\n" - " (($lazy_type$) $oneof_name$_).setValue(value);\n" - "}\n"); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - " $set_oneof_case_message$;\n" - " }\n" - " (($lazy_type$) $oneof_name$_).setValue(builderForValue.build());\n" - "}\n"); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void merge$capitalized_name$($type$ value) {\n" - " if ($has_oneof_case_message$ &&\n" - " !(($lazy_type$) $oneof_name$_).containsDefaultInstance()) {\n" - " (($lazy_type$) $oneof_name$_).setValue(\n" - " $type$.newBuilder(\n" - " get$capitalized_name$()).mergeFrom(value).buildPartial());\n" - " } else {\n" - " if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - " $set_oneof_case_message$;\n" - " }\n" - " (($lazy_type$) $oneof_name$_).setValue(value);\n" - " }\n" - "}\n"); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " }\n" - "}\n"); -} - -void ImmutableLazyMessageOneofFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // boolean hasField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); - - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder set$capitalized_name$($type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder set$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(builderForValue);\n" - " return this;\n" - "}\n"); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder merge$capitalized_name$($type$ value) {\n" - " copyOnWrite();\n" - " instance.merge$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder clear$capitalized_name$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); -} - -void ImmutableLazyMessageOneofFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$oneof_name$_ = visitor.visitOneofLazyMessage(\n" - " $has_oneof_case_message$,\n" - " ($lazy_type$) $oneof_name$_,\n" - " ($lazy_type$) other.$oneof_name$_);\n"); -} - -void ImmutableLazyMessageOneofFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - "}\n" - "(($lazy_type$) $oneof_name$_).mergeFrom(input, extensionRegistry);\n" - "$set_oneof_case_message$;\n"); -} - -void ImmutableLazyMessageOneofFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - // Do not de-serialize lazy fields. - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.writeBytes(\n" - " $number$, (($lazy_type$) $oneof_name$_).toByteString());\n" - "}\n"); -} - -void ImmutableLazyMessageOneofFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeLazyFieldSize($number$, ($lazy_type$) $oneof_name$_);\n" - "}\n"); -} - - -// =================================================================== - -RepeatedImmutableLazyMessageFieldLiteGenerator:: -RepeatedImmutableLazyMessageFieldLiteGenerator( - const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : RepeatedImmutableMessageFieldLiteGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { -} - - -RepeatedImmutableLazyMessageFieldLiteGenerator:: -~RepeatedImmutableLazyMessageFieldLiteGenerator() {} - -void RepeatedImmutableLazyMessageFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private com.google.protobuf.Internal.ProtobufList<\n" - " com.google.protobuf.LazyFieldLite> $name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List<$type$>\n" - " get$capitalized_name$List() {\n" - " java.util.List<$type$> list =\n" - " new java.util.ArrayList<$type$>($name$_.size());\n" - " for (com.google.protobuf.LazyFieldLite lf : $name$_) {\n" - " list.add(($type$) lf.getValue($type$.getDefaultInstance()));\n" - " }\n" - " return java.util.Collections.unmodifiableList(list);\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List\n" - " get$capitalized_name$OrBuilderList() {\n" - " return get$capitalized_name$List();\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int get$capitalized_name$Count() {\n" - " return $name$_.size();\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$(int index) {\n" - " return ($type$)\n" - " $name$_.get(index).getValue($type$.getDefaultInstance());\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n" - " int index) {\n" - " return ($type$OrBuilder)\n" - " $name$_.get(index).getValue($type$.getDefaultInstance());\n" - "}\n"); - - printer->Print(variables_, - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - " }\n" - "}\n" - "\n"); - - // Builder setRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " int index, $type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(\n" - " index, com.google.protobuf.LazyFieldLite.fromValue(value));\n" - "}\n"); - - // Builder setRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " int index, $type$.Builder builderForValue) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(index, com.google.protobuf.LazyFieldLite.fromValue(\n" - " builderForValue.build()));\n" - "}\n"); - - // Builder addRepeatedField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(com.google.protobuf.LazyFieldLite.fromValue(value));\n" - "}\n"); - - // Builder addRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$(\n" - " int index, $type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(\n" - " index, com.google.protobuf.LazyFieldLite.fromValue(value));\n" - "}\n"); - - // Builder addRepeatedField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(com.google.protobuf.LazyFieldLite.fromValue(\n" - " builderForValue.build()));\n" - "}\n"); - - // Builder addRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$(\n" - " int index, $type$.Builder builderForValue) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(index, com.google.protobuf.LazyFieldLite.fromValue(\n" - " builderForValue.build()));\n" - "}\n"); - - // Builder addAllRepeatedField(Iterable values) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void addAll$capitalized_name$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " for (com.google.protobuf.MessageLite v : values) {\n" - " $name$_.add(com.google.protobuf.LazyFieldLite.fromValue(v));\n" - " }\n" - "}\n"); - - // Builder clearAllRepeatedField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $name$_ = emptyProtobufList();\n" - "}\n"); - - // Builder removeRepeatedField(int index) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void remove$capitalized_name$(int index) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.remove(index);\n" - "}\n"); -} - -void RepeatedImmutableLazyMessageFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // List getRepeatedFieldList() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List<$type$> get$capitalized_name$List() {\n" - " return java.util.Collections.unmodifiableList(\n" - " instance.get$capitalized_name$List());\n" - "}\n"); - - // int getRepeatedFieldCount() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int get$capitalized_name$Count() {\n" - " return instance.get$capitalized_name$Count();\n" - "}\n"); - - // Field getRepeatedField(int index) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$(int index) {\n" - " return instance.get$capitalized_name$(index);\n" - "}\n"); - - // Builder setRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder set$capitalized_name$(\n" - " int index, $type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(index, value);\n" - " return this;\n" - "}\n"); - - // Builder setRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder set$capitalized_name$(\n" - " int index, $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(index, builderForValue);\n" - " return this;\n" - "}\n"); - - // Builder addRepeatedField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder add$capitalized_name$($type$ value) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - - // Builder addRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder add$capitalized_name$(\n" - " int index, $type$ value) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(index, value);\n" - " return this;\n" - "}\n"); - - // Builder addRepeatedField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder add$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(builderForValue);\n" - " return this;\n" - "}\n"); - - // Builder addRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder add$capitalized_name$(\n" - " int index, $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(index, builderForValue);\n" - " return this;\n" - "}\n"); - - // Builder addAllRepeatedField(Iterable values) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder addAll$capitalized_name$(\n" - " java.lang.Iterable values) {\n" - " copyOnWrite();\n" - " instance.addAll$capitalized_name$(values);\n" - " return this;\n" - "}\n"); - - // Builder clearAllRepeatedField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder clear$capitalized_name$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); - - // Builder removeRepeatedField(int index) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder remove$capitalized_name$(int index) {\n" - " copyOnWrite();\n" - " instance.remove$capitalized_name$(index);\n" - " return this;\n" - "}\n"); -} - -void RepeatedImmutableLazyMessageFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - "}\n" - "$name$_.add(new com.google.protobuf.LazyFieldLite(\n" - " extensionRegistry, input.readBytes()));\n"); -} - -void RepeatedImmutableLazyMessageFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.writeBytes($number$, $name$_.get(i).toByteString());\n" - "}\n"); -} - -void RepeatedImmutableLazyMessageFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeLazyFieldSize($number$, $name$_.get(i));\n" - "}\n"); -} - - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_lazy_message_field_lite.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_lazy_message_field_lite.h deleted file mode 100644 index 65b84fbc..00000000 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_lazy_message_field_lite.h +++ /dev/null @@ -1,121 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Author: niwasaki@google.com (Naoki Iwasaki) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_LITE_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_LITE_H__ - -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - } - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class ImmutableLazyMessageFieldLiteGenerator - : public ImmutableMessageFieldLiteGenerator { - public: - explicit ImmutableLazyMessageFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableLazyMessageFieldLiteGenerator(); - - // overroads ImmutableMessageFieldLiteGenerator ------------------------------ - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableLazyMessageFieldLiteGenerator); -}; - -class ImmutableLazyMessageOneofFieldLiteGenerator - : public ImmutableLazyMessageFieldLiteGenerator { - public: - ImmutableLazyMessageOneofFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableLazyMessageOneofFieldLiteGenerator(); - - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableLazyMessageOneofFieldLiteGenerator); -}; - -class RepeatedImmutableLazyMessageFieldLiteGenerator - : public RepeatedImmutableMessageFieldLiteGenerator { - public: - explicit RepeatedImmutableLazyMessageFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~RepeatedImmutableLazyMessageFieldLiteGenerator(); - - // overroads RepeatedImmutableMessageFieldLiteGenerator ---------------------- - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableLazyMessageFieldLiteGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_LITE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_map_field.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_map_field.cc index b22a2199..53537458 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_map_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_map_field.cc @@ -57,9 +57,8 @@ const FieldDescriptor* ValueField(const FieldDescriptor* descriptor) { return message->FindFieldByName("value"); } -string TypeName(const FieldDescriptor* field, - ClassNameResolver* name_resolver, - bool boxed) { +std::string TypeName(const FieldDescriptor* field, + ClassNameResolver* name_resolver, bool boxed) { if (GetJavaType(field) == JAVATYPE_MESSAGE) { return name_resolver->GetImmutableClassName(field->message_type()); } else if (GetJavaType(field) == JAVATYPE_ENUM) { @@ -70,17 +69,15 @@ string TypeName(const FieldDescriptor* field, } } -string WireType(const FieldDescriptor* field) { +std::string WireType(const FieldDescriptor* field) { return "com.google.protobuf.WireFormat.FieldType." + - string(FieldTypeName(field->type())); + std::string(FieldTypeName(field->type())); } -void SetMessageVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - const FieldGeneratorInfo* info, +void SetMessageVariables(const FieldDescriptor* descriptor, int messageBitIndex, + int builderBitIndex, const FieldGeneratorInfo* info, Context* context, - std::map* variables) { + std::map* variables) { SetCommonFieldVariables(descriptor, info, variables); ClassNameResolver* name_resolver = context->GetNameResolver(); @@ -92,17 +89,21 @@ void SetMessageVariables(const FieldDescriptor* descriptor, const JavaType valueJavaType = GetJavaType(value); (*variables)["key_type"] = TypeName(key, name_resolver, false); - string boxed_key_type = TypeName(key, name_resolver, true); + std::string boxed_key_type = TypeName(key, name_resolver, true); (*variables)["boxed_key_type"] = boxed_key_type; // Used for calling the serialization function. (*variables)["short_key_type"] = boxed_key_type.substr(boxed_key_type.rfind('.') + 1); (*variables)["key_wire_type"] = WireType(key); (*variables)["key_default_value"] = DefaultValue(key, true, name_resolver); - (*variables)["key_null_check"] = IsReferenceType(keyJavaType) ? - "if (key == null) { throw new java.lang.NullPointerException(); }" : ""; - (*variables)["value_null_check"] = IsReferenceType(valueJavaType) ? - "if (value == null) { throw new java.lang.NullPointerException(); }" : ""; + (*variables)["key_null_check"] = + IsReferenceType(keyJavaType) + ? "if (key == null) { throw new java.lang.NullPointerException(); }" + : ""; + (*variables)["value_null_check"] = + IsReferenceType(valueJavaType) + ? "if (value == null) { throw new java.lang.NullPointerException(); }" + : ""; if (valueJavaType == JAVATYPE_ENUM) { // We store enums as Integers internally. (*variables)["value_type"] = "int"; @@ -133,8 +134,8 @@ void SetMessageVariables(const FieldDescriptor* descriptor, (*variables)["boxed_key_type"] + ", " + (*variables)["boxed_value_type"]; // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; + (*variables)["deprecation"] = + descriptor->options().deprecated() ? "@java.lang.Deprecated " : ""; (*variables)["on_changed"] = "onChanged();"; // For repeated fields, one bit is used for whether the array is immutable @@ -144,62 +145,51 @@ void SetMessageVariables(const FieldDescriptor* descriptor, (*variables)["set_mutable_bit_parser"] = GenerateSetBitMutableLocal(builderBitIndex); - (*variables)["default_entry"] = (*variables)["capitalized_name"] + - "DefaultEntryHolder.defaultEntry"; + (*variables)["default_entry"] = + (*variables)["capitalized_name"] + "DefaultEntryHolder.defaultEntry"; (*variables)["map_field_parameter"] = (*variables)["default_entry"]; (*variables)["descriptor"] = - name_resolver->GetImmutableClassName(descriptor->file()) + - ".internal_" + UniqueFileScopeIdentifier(descriptor->message_type()) + - "_descriptor, "; + name_resolver->GetImmutableClassName(descriptor->file()) + ".internal_" + + UniqueFileScopeIdentifier(descriptor->message_type()) + "_descriptor, "; (*variables)["ver"] = GeneratedCodeVersionSuffix(); } } // namespace -ImmutableMapFieldGenerator:: -ImmutableMapFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) { +ImmutableMapFieldGenerator::ImmutableMapFieldGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, + Context* context) + : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) { SetMessageVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - context, &variables_); + context->GetFieldGeneratorInfo(descriptor), context, + &variables_); } -ImmutableMapFieldGenerator:: -~ImmutableMapFieldGenerator() {} +ImmutableMapFieldGenerator::~ImmutableMapFieldGenerator() {} -int ImmutableMapFieldGenerator::GetNumBitsForMessage() const { - return 0; -} +int ImmutableMapFieldGenerator::GetNumBitsForMessage() const { return 0; } -int ImmutableMapFieldGenerator::GetNumBitsForBuilder() const { - return 1; -} +int ImmutableMapFieldGenerator::GetNumBitsForBuilder() const { return 1; } -void ImmutableMapFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { +void ImmutableMapFieldGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$int ${$get$capitalized_name$Count$}$();\n"); + printer->Print(variables_, + "$deprecation$int ${$get$capitalized_name$Count$}$();\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$boolean ${$contains$capitalized_name$$}$(\n" - " $key_type$ key);\n"); + printer->Print(variables_, + "$deprecation$boolean ${$contains$capitalized_name$$}$(\n" + " $key_type$ key);\n"); printer->Annotate("{", "}", descriptor_); if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$get$capitalized_name$$}$();\n"); + printer->Print(variables_, + "/**\n" + " * Use {@link #get$capitalized_name$Map()} instead.\n" + " */\n" + "@java.lang.Deprecated\n" + "java.util.Map<$boxed_key_type$, $value_enum_type$>\n" + "${$get$capitalized_name$$}$();\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print( @@ -231,63 +221,55 @@ GenerateInterfaceMembers(io::Printer* printer) const { "${$get$capitalized_name$Value$}$();\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$java.util.Map<$type_parameters$>\n" - "${$get$capitalized_name$ValueMap$}$();\n"); + printer->Print(variables_, + "$deprecation$java.util.Map<$type_parameters$>\n" + "${$get$capitalized_name$ValueMap$}$();\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "$value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n" - " $key_type$ key,\n" - " $value_type$ defaultValue);\n"); + printer->Print(variables_, + "$deprecation$\n" + "$value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n" + " $key_type$ key,\n" + " $value_type$ defaultValue);\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "$value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n" - " $key_type$ key);\n"); + printer->Print(variables_, + "$deprecation$\n" + "$value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n" + " $key_type$ key);\n"); printer->Annotate("{", "}", descriptor_); } } else { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "java.util.Map<$type_parameters$>\n" - "${$get$capitalized_name$$}$();\n"); + printer->Print(variables_, + "/**\n" + " * Use {@link #get$capitalized_name$Map()} instead.\n" + " */\n" + "@java.lang.Deprecated\n" + "java.util.Map<$type_parameters$>\n" + "${$get$capitalized_name$$}$();\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$java.util.Map<$type_parameters$>\n" - "${$get$capitalized_name$Map$}$();\n"); + printer->Print(variables_, + "$deprecation$java.util.Map<$type_parameters$>\n" + "${$get$capitalized_name$Map$}$();\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "$value_type$ ${$get$capitalized_name$OrDefault$}$(\n" - " $key_type$ key,\n" - " $value_type$ defaultValue);\n"); + printer->Print(variables_, + "$deprecation$\n" + "$value_type$ ${$get$capitalized_name$OrDefault$}$(\n" + " $key_type$ key,\n" + " $value_type$ defaultValue);\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "$value_type$ ${$get$capitalized_name$OrThrow$}$(\n" - " $key_type$ key);\n"); + printer->Print(variables_, + "$deprecation$\n" + "$value_type$ ${$get$capitalized_name$OrThrow$}$(\n" + " $key_type$ key);\n"); printer->Annotate("{", "}", descriptor_); } } -void ImmutableMapFieldGenerator:: -GenerateMembers(io::Printer* printer) const { +void ImmutableMapFieldGenerator::GenerateMembers(io::Printer* printer) const { printer->Print( variables_, "private static final class $capitalized_name$DefaultEntryHolder {\n" @@ -301,18 +283,17 @@ GenerateMembers(io::Printer* printer) const { " $value_wire_type$,\n" " $value_default_value$);\n" "}\n"); - printer->Print( - variables_, - "private com.google.protobuf.MapField<\n" - " $type_parameters$> $name$_;\n" - "private com.google.protobuf.MapField<$type_parameters$>\n" - "internalGet$capitalized_name$() {\n" - " if ($name$_ == null) {\n" - " return com.google.protobuf.MapField.emptyMapField(\n" - " $map_field_parameter$);\n" - " }\n" - " return $name$_;\n" - "}\n"); + printer->Print(variables_, + "private com.google.protobuf.MapField<\n" + " $type_parameters$> $name$_;\n" + "private com.google.protobuf.MapField<$type_parameters$>\n" + "internalGet$capitalized_name$() {\n" + " if ($name$_ == null) {\n" + " return com.google.protobuf.MapField.emptyMapField(\n" + " $map_field_parameter$);\n" + " }\n" + " return $name$_;\n" + "}\n"); if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { printer->Print( variables_, @@ -336,53 +317,50 @@ GenerateMembers(io::Printer* printer) const { GenerateMapGetters(printer); } -void ImmutableMapFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - printer->Print( - variables_, - "private com.google.protobuf.MapField<\n" - " $type_parameters$> $name$_;\n" - "private com.google.protobuf.MapField<$type_parameters$>\n" - "internalGet$capitalized_name$() {\n" - " if ($name$_ == null) {\n" - " return com.google.protobuf.MapField.emptyMapField(\n" - " $map_field_parameter$);\n" - " }\n" - " return $name$_;\n" - "}\n" - "private com.google.protobuf.MapField<$type_parameters$>\n" - "internalGetMutable$capitalized_name$() {\n" - " $on_changed$;\n" - " if ($name$_ == null) {\n" - " $name$_ = com.google.protobuf.MapField.newMapField(\n" - " $map_field_parameter$);\n" - " }\n" - " if (!$name$_.isMutable()) {\n" - " $name$_ = $name$_.copy();\n" - " }\n" - " return $name$_;\n" - "}\n"); +void ImmutableMapFieldGenerator::GenerateBuilderMembers( + io::Printer* printer) const { + printer->Print(variables_, + "private com.google.protobuf.MapField<\n" + " $type_parameters$> $name$_;\n" + "private com.google.protobuf.MapField<$type_parameters$>\n" + "internalGet$capitalized_name$() {\n" + " if ($name$_ == null) {\n" + " return com.google.protobuf.MapField.emptyMapField(\n" + " $map_field_parameter$);\n" + " }\n" + " return $name$_;\n" + "}\n" + "private com.google.protobuf.MapField<$type_parameters$>\n" + "internalGetMutable$capitalized_name$() {\n" + " $on_changed$;\n" + " if ($name$_ == null) {\n" + " $name$_ = com.google.protobuf.MapField.newMapField(\n" + " $map_field_parameter$);\n" + " }\n" + " if (!$name$_.isMutable()) {\n" + " $name$_ = $name$_.copy();\n" + " }\n" + " return $name$_;\n" + "}\n"); GenerateMapGetters(printer); - printer->Print( - variables_, - "$deprecation$\n" - "public Builder ${$clear$capitalized_name$$}$() {\n" - " internalGetMutable$capitalized_name$().getMutableMap()\n" - " .clear();\n" - " return this;\n" - "}\n"); + printer->Print(variables_, + "$deprecation$\n" + "public Builder ${$clear$capitalized_name$$}$() {\n" + " internalGetMutable$capitalized_name$().getMutableMap()\n" + " .clear();\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public Builder ${$remove$capitalized_name$$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " internalGetMutable$capitalized_name$().getMutableMap()\n" - " .remove(key);\n" - " return this;\n" - "}\n"); + printer->Print(variables_, + "$deprecation$\n" + "public Builder ${$remove$capitalized_name$$}$(\n" + " $key_type$ key) {\n" + " $key_null_check$\n" + " internalGetMutable$capitalized_name$().getMutableMap()\n" + " .remove(key);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { printer->Print( @@ -468,41 +446,38 @@ GenerateBuilderMembers(io::Printer* printer) const { "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$" - "public Builder ${$put$capitalized_name$$}$(\n" - " $key_type$ key,\n" - " $value_type$ value) {\n" - " $key_null_check$\n" - " $value_null_check$\n" - " internalGetMutable$capitalized_name$().getMutableMap()\n" - " .put(key, value);\n" - " return this;\n" - "}\n"); + printer->Print(variables_, + "$deprecation$" + "public Builder ${$put$capitalized_name$$}$(\n" + " $key_type$ key,\n" + " $value_type$ value) {\n" + " $key_null_check$\n" + " $value_null_check$\n" + " internalGetMutable$capitalized_name$().getMutableMap()\n" + " .put(key, value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public Builder ${$putAll$capitalized_name$$}$(\n" - " java.util.Map<$type_parameters$> values) {\n" - " internalGetMutable$capitalized_name$().getMutableMap()\n" - " .putAll(values);\n" - " return this;\n" - "}\n"); + printer->Print(variables_, + "$deprecation$\n" + "public Builder ${$putAll$capitalized_name$$}$(\n" + " java.util.Map<$type_parameters$> values) {\n" + " internalGetMutable$capitalized_name$().getMutableMap()\n" + " .putAll(values);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } } -void ImmutableMapFieldGenerator:: -GenerateMapGetters(io::Printer* printer) const { - printer->Print( - variables_, - "$deprecation$\n" - "public int ${$get$capitalized_name$Count$}$() {\n" - " return internalGet$capitalized_name$().getMap().size();\n" - "}\n"); +void ImmutableMapFieldGenerator::GenerateMapGetters( + io::Printer* printer) const { + printer->Print(variables_, + "$deprecation$\n" + "public int ${$get$capitalized_name$Count$}$() {\n" + " return internalGet$capitalized_name$().getMap().size();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print( @@ -515,26 +490,24 @@ GenerateMapGetters(io::Printer* printer) const { "}\n"); printer->Annotate("{", "}", descriptor_); if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$get$capitalized_name$$}$() {\n" - " return get$capitalized_name$Map();\n" - "}\n"); + printer->Print(variables_, + "/**\n" + " * Use {@link #get$capitalized_name$Map()} instead.\n" + " */\n" + "@java.lang.Deprecated\n" + "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" + "${$get$capitalized_name$$}$() {\n" + " return get$capitalized_name$Map();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$get$capitalized_name$Map$}$() {\n" - " return internalGetAdapted$capitalized_name$Map(\n" - " internalGet$capitalized_name$().getMap());" - "}\n"); + printer->Print(variables_, + "$deprecation$\n" + "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" + "${$get$capitalized_name$Map$}$() {\n" + " return internalGetAdapted$capitalized_name$Map(\n" + " internalGet$capitalized_name$().getMap());" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print( @@ -617,25 +590,23 @@ GenerateMapGetters(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); } } else { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$type_parameters$> " - "${$get$capitalized_name$$}$() {\n" - " return get$capitalized_name$Map();\n" - "}\n"); + printer->Print(variables_, + "/**\n" + " * Use {@link #get$capitalized_name$Map()} instead.\n" + " */\n" + "@java.lang.Deprecated\n" + "public java.util.Map<$type_parameters$> " + "${$get$capitalized_name$$}$() {\n" + " return get$capitalized_name$Map();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public java.util.Map<$type_parameters$> " - "${$get$capitalized_name$Map$}$() {\n" - " return internalGet$capitalized_name$().getMap();\n" - "}\n"); + printer->Print(variables_, + "$deprecation$\n" + "public java.util.Map<$type_parameters$> " + "${$get$capitalized_name$Map$}$() {\n" + " return internalGet$capitalized_name$().getMap();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print( @@ -651,65 +622,60 @@ GenerateMapGetters(io::Printer* printer) const { "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " java.util.Map<$type_parameters$> map =\n" - " internalGet$capitalized_name$().getMap();\n" - " if (!map.containsKey(key)) {\n" - " throw new java.lang.IllegalArgumentException();\n" - " }\n" - " return map.get(key);\n" - "}\n"); + printer->Print(variables_, + "$deprecation$\n" + "public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n" + " $key_type$ key) {\n" + " $key_null_check$\n" + " java.util.Map<$type_parameters$> map =\n" + " internalGet$capitalized_name$().getMap();\n" + " if (!map.containsKey(key)) {\n" + " throw new java.lang.IllegalArgumentException();\n" + " }\n" + " return map.get(key);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } } -void ImmutableMapFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { +void ImmutableMapFieldGenerator::GenerateFieldBuilderInitializationCode( + io::Printer* printer) const { // Nothing to initialize. } -void ImmutableMapFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { +void ImmutableMapFieldGenerator::GenerateInitializationCode( + io::Printer* printer) const { // Nothing to initialize. } -void ImmutableMapFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { - printer->Print( - variables_, - "internalGetMutable$capitalized_name$().clear();\n"); +void ImmutableMapFieldGenerator::GenerateBuilderClearCode( + io::Printer* printer) const { + printer->Print(variables_, + "internalGetMutable$capitalized_name$().clear();\n"); } -void ImmutableMapFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print( - variables_, - "internalGetMutable$capitalized_name$().mergeFrom(\n" - " other.internalGet$capitalized_name$());\n"); +void ImmutableMapFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { + printer->Print(variables_, + "internalGetMutable$capitalized_name$().mergeFrom(\n" + " other.internalGet$capitalized_name$());\n"); } -void ImmutableMapFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - printer->Print( - variables_, - "result.$name$_ = internalGet$capitalized_name$();\n" - "result.$name$_.makeImmutable();\n"); +void ImmutableMapFieldGenerator::GenerateBuildingCode( + io::Printer* printer) const { + printer->Print(variables_, + "result.$name$_ = internalGet$capitalized_name$();\n" + "result.$name$_.makeImmutable();\n"); } -void ImmutableMapFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print( - variables_, - "if (!$get_mutable_bit_parser$) {\n" - " $name$_ = com.google.protobuf.MapField.newMapField(\n" - " $map_field_parameter$);\n" - " $set_mutable_bit_parser$;\n" - "}\n"); +void ImmutableMapFieldGenerator::GenerateParsingCode( + io::Printer* printer) const { + printer->Print(variables_, + "if (!$get_mutable_bit_parser$) {\n" + " $name$_ = com.google.protobuf.MapField.newMapField(\n" + " $map_field_parameter$);\n" + " $set_mutable_bit_parser$;\n" + "}\n"); if (!SupportUnknownEnumValue(descriptor_->file()) && GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { printer->Print( @@ -736,25 +702,24 @@ GenerateParsingCode(io::Printer* printer) const { } } -void ImmutableMapFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { +void ImmutableMapFieldGenerator::GenerateParsingDoneCode( + io::Printer* printer) const { // Nothing to do here. } -void ImmutableMapFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print( - variables_, - "com.google.protobuf.GeneratedMessage$ver$\n" - " .serialize$short_key_type$MapTo(\n" - " output,\n" - " internalGet$capitalized_name$(),\n" - " $default_entry$,\n" - " $number$);\n"); +void ImmutableMapFieldGenerator::GenerateSerializationCode( + io::Printer* printer) const { + printer->Print(variables_, + "com.google.protobuf.GeneratedMessage$ver$\n" + " .serialize$short_key_type$MapTo(\n" + " output,\n" + " internalGet$capitalized_name$(),\n" + " $default_entry$,\n" + " $number$);\n"); } -void ImmutableMapFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { +void ImmutableMapFieldGenerator::GenerateSerializedSizeCode( + io::Printer* printer) const { printer->Print( variables_, "for (java.util.Map.Entry<$type_parameters$> entry\n" @@ -769,16 +734,14 @@ GenerateSerializedSizeCode(io::Printer* printer) const { "}\n"); } -void ImmutableMapFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print( - variables_, - "result = result && internalGet$capitalized_name$().equals(\n" - " other.internalGet$capitalized_name$());\n"); +void ImmutableMapFieldGenerator::GenerateEqualsCode( + io::Printer* printer) const { + printer->Print(variables_, + "if (!internalGet$capitalized_name$().equals(\n" + " other.internalGet$capitalized_name$())) return false;\n"); } -void ImmutableMapFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { +void ImmutableMapFieldGenerator::GenerateHashCode(io::Printer* printer) const { printer->Print( variables_, "if (!internalGet$capitalized_name$().getMap().isEmpty()) {\n" @@ -787,7 +750,7 @@ GenerateHashCode(io::Printer* printer) const { "}\n"); } -string ImmutableMapFieldGenerator::GetBoxedType() const { +std::string ImmutableMapFieldGenerator::GetBoxedType() const { return name_resolver_->GetImmutableClassName(descriptor_->message_type()); } diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_map_field.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_map_field.h index 47021740..2ff1f767 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_map_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_map_field.h @@ -40,9 +40,9 @@ namespace java { class ImmutableMapFieldGenerator : public ImmutableFieldGenerator { public: - explicit ImmutableMapFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + explicit ImmutableMapFieldGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, int builderBitIndex, + Context* context); ~ImmutableMapFieldGenerator(); // implements ImmutableFieldGenerator --------------------------------------- @@ -63,11 +63,11 @@ class ImmutableMapFieldGenerator : public ImmutableFieldGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; private: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; ClassNameResolver* name_resolver_; void GenerateMapGetters(io::Printer* printer) const; }; @@ -75,6 +75,6 @@ class ImmutableMapFieldGenerator : public ImmutableFieldGenerator { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MAP_FIELD_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_map_field_lite.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_map_field_lite.cc index e2e68076..90557748 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_map_field_lite.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_map_field_lite.cc @@ -57,9 +57,8 @@ const FieldDescriptor* ValueField(const FieldDescriptor* descriptor) { return message->FindFieldByName("value"); } -string TypeName(const FieldDescriptor* field, - ClassNameResolver* name_resolver, - bool boxed) { +std::string TypeName(const FieldDescriptor* field, + ClassNameResolver* name_resolver, bool boxed) { if (GetJavaType(field) == JAVATYPE_MESSAGE) { return name_resolver->GetImmutableClassName(field->message_type()); } else if (GetJavaType(field) == JAVATYPE_ENUM) { @@ -70,17 +69,15 @@ string TypeName(const FieldDescriptor* field, } } -string WireType(const FieldDescriptor* field) { +std::string WireType(const FieldDescriptor* field) { return "com.google.protobuf.WireFormat.FieldType." + - string(FieldTypeName(field->type())); + std::string(FieldTypeName(field->type())); } -void SetMessageVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - const FieldGeneratorInfo* info, +void SetMessageVariables(const FieldDescriptor* descriptor, int messageBitIndex, + int builderBitIndex, const FieldGeneratorInfo* info, Context* context, - std::map* variables) { + std::map* variables) { SetCommonFieldVariables(descriptor, info, variables); ClassNameResolver* name_resolver = context->GetNameResolver(); @@ -95,10 +92,14 @@ void SetMessageVariables(const FieldDescriptor* descriptor, (*variables)["boxed_key_type"] = TypeName(key, name_resolver, true); (*variables)["key_wire_type"] = WireType(key); (*variables)["key_default_value"] = DefaultValue(key, true, name_resolver); - (*variables)["key_null_check"] = IsReferenceType(keyJavaType) ? - "if (key == null) { throw new java.lang.NullPointerException(); }" : ""; - (*variables)["value_null_check"] = IsReferenceType(valueJavaType) ? - "if (value == null) { throw new java.lang.NullPointerException(); }" : ""; + (*variables)["key_null_check"] = + IsReferenceType(keyJavaType) + ? "if (key == null) { throw new java.lang.NullPointerException(); }" + : ""; + (*variables)["value_null_check"] = + IsReferenceType(valueJavaType) + ? "if (value == null) { throw new java.lang.NullPointerException(); }" + : ""; if (GetJavaType(value) == JAVATYPE_ENUM) { // We store enums as Integers internally. @@ -130,59 +131,48 @@ void SetMessageVariables(const FieldDescriptor* descriptor, (*variables)["boxed_key_type"] + ", " + (*variables)["boxed_value_type"]; // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; + (*variables)["deprecation"] = + descriptor->options().deprecated() ? "@java.lang.Deprecated " : ""; - (*variables)["default_entry"] = (*variables)["capitalized_name"] + - "DefaultEntryHolder.defaultEntry"; + (*variables)["default_entry"] = + (*variables)["capitalized_name"] + "DefaultEntryHolder.defaultEntry"; } } // namespace -ImmutableMapFieldLiteGenerator:: -ImmutableMapFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) { - SetMessageVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - context, &variables_); +ImmutableMapFieldLiteGenerator::ImmutableMapFieldLiteGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, Context* context) + : descriptor_(descriptor), + context_(context), + name_resolver_(context->GetNameResolver()) { + SetMessageVariables(descriptor, messageBitIndex, 0, + context->GetFieldGeneratorInfo(descriptor), context, + &variables_); } -ImmutableMapFieldLiteGenerator:: -~ImmutableMapFieldLiteGenerator() {} +ImmutableMapFieldLiteGenerator::~ImmutableMapFieldLiteGenerator() {} -int ImmutableMapFieldLiteGenerator::GetNumBitsForMessage() const { - return 0; -} +int ImmutableMapFieldLiteGenerator::GetNumBitsForMessage() const { return 0; } -int ImmutableMapFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; -} - -void ImmutableMapFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { +void ImmutableMapFieldLiteGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$int ${$get$capitalized_name$Count$}$();\n"); + printer->Print(variables_, + "$deprecation$int ${$get$capitalized_name$Count$}$();\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$boolean ${$contains$capitalized_name$$}$(\n" - " $key_type$ key);\n"); + printer->Print(variables_, + "$deprecation$boolean ${$contains$capitalized_name$$}$(\n" + " $key_type$ key);\n"); printer->Annotate("{", "}", descriptor_); if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$get$capitalized_name$$}$();\n"); + printer->Print(variables_, + "/**\n" + " * Use {@link #get$capitalized_name$Map()} instead.\n" + " */\n" + "@java.lang.Deprecated\n" + "java.util.Map<$boxed_key_type$, $value_enum_type$>\n" + "${$get$capitalized_name$$}$();\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print( @@ -214,63 +204,56 @@ GenerateInterfaceMembers(io::Printer* printer) const { "${$get$capitalized_name$Value$}$();\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$java.util.Map<$type_parameters$>\n" - "${$get$capitalized_name$ValueMap$}$();\n"); + printer->Print(variables_, + "$deprecation$java.util.Map<$type_parameters$>\n" + "${$get$capitalized_name$ValueMap$}$();\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "$value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n" - " $key_type$ key,\n" - " $value_type$ defaultValue);\n"); + printer->Print(variables_, + "$deprecation$\n" + "$value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n" + " $key_type$ key,\n" + " $value_type$ defaultValue);\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "$value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n" - " $key_type$ key);\n"); + printer->Print(variables_, + "$deprecation$\n" + "$value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n" + " $key_type$ key);\n"); printer->Annotate("{", "}", descriptor_); } } else { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "java.util.Map<$type_parameters$>\n" - "${$get$capitalized_name$$}$();\n"); + printer->Print(variables_, + "/**\n" + " * Use {@link #get$capitalized_name$Map()} instead.\n" + " */\n" + "@java.lang.Deprecated\n" + "java.util.Map<$type_parameters$>\n" + "${$get$capitalized_name$$}$();\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$java.util.Map<$type_parameters$>\n" - "${$get$capitalized_name$Map$}$();\n"); + printer->Print(variables_, + "$deprecation$java.util.Map<$type_parameters$>\n" + "${$get$capitalized_name$Map$}$();\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "$value_type$ ${$get$capitalized_name$OrDefault$}$(\n" - " $key_type$ key,\n" - " $value_type$ defaultValue);\n"); + printer->Print(variables_, + "$deprecation$\n" + "$value_type$ ${$get$capitalized_name$OrDefault$}$(\n" + " $key_type$ key,\n" + " $value_type$ defaultValue);\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "$value_type$ ${$get$capitalized_name$OrThrow$}$(\n" - " $key_type$ key);\n"); + printer->Print(variables_, + "$deprecation$\n" + "$value_type$ ${$get$capitalized_name$OrThrow$}$(\n" + " $key_type$ key);\n"); printer->Annotate("{", "}", descriptor_); } } -void ImmutableMapFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { +void ImmutableMapFieldLiteGenerator::GenerateMembers( + io::Printer* printer) const { printer->Print( variables_, "private static final class $capitalized_name$DefaultEntryHolder {\n" @@ -283,40 +266,37 @@ GenerateMembers(io::Printer* printer) const { " $value_wire_type$,\n" " $value_default_value$);\n" "}\n"); - printer->Print( - variables_, - "private com.google.protobuf.MapFieldLite<\n" - " $type_parameters$> $name$_ =\n" - " com.google.protobuf.MapFieldLite.emptyMapField();\n" - "private com.google.protobuf.MapFieldLite<$type_parameters$>\n" - "internalGet$capitalized_name$() {\n" - " return $name$_;\n" - "}\n" - "private com.google.protobuf.MapFieldLite<$type_parameters$>\n" - "internalGetMutable$capitalized_name$() {\n" - " if (!$name$_.isMutable()) {\n" - " $name$_ = $name$_.mutableCopy();\n" - " }\n" - " return $name$_;\n" - "}\n"); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public int ${$get$capitalized_name$Count$}$() {\n" - " return internalGet$capitalized_name$().size();\n" - "}\n"); + printer->Print(variables_, + "private com.google.protobuf.MapFieldLite<\n" + " $type_parameters$> $name$_ =\n" + " com.google.protobuf.MapFieldLite.emptyMapField();\n" + "private com.google.protobuf.MapFieldLite<$type_parameters$>\n" + "internalGet$capitalized_name$() {\n" + " return $name$_;\n" + "}\n" + "private com.google.protobuf.MapFieldLite<$type_parameters$>\n" + "internalGetMutable$capitalized_name$() {\n" + " if (!$name$_.isMutable()) {\n" + " $name$_ = $name$_.mutableCopy();\n" + " }\n" + " return $name$_;\n" + "}\n"); + printer->Print(variables_, + "@java.lang.Override\n" + "$deprecation$\n" + "public int ${$get$capitalized_name$Count$}$() {\n" + " return internalGet$capitalized_name$().size();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public boolean ${$contains$capitalized_name$$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " return internalGet$capitalized_name$().containsKey(key);\n" - "}\n"); + printer->Print(variables_, + "@java.lang.Override\n" + "$deprecation$\n" + "public boolean ${$contains$capitalized_name$$}$(\n" + " $key_type$ key) {\n" + " $key_null_check$\n" + " return internalGet$capitalized_name$().containsKey(key);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { printer->Print( @@ -327,16 +307,15 @@ GenerateMembers(io::Printer* printer) const { " com.google.protobuf.Internal.MapAdapter.newEnumConverter(\n" " $value_enum_type$.internalGetValueMap(),\n" " $unrecognized_value$);\n"); - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$get$capitalized_name$$}$() {\n" - " return get$capitalized_name$Map();\n" - "}\n"); + printer->Print(variables_, + "/**\n" + " * Use {@link #get$capitalized_name$Map()} instead.\n" + " */\n" + "@java.lang.Deprecated\n" + "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" + "${$get$capitalized_name$$}$() {\n" + " return get$capitalized_name$Map();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print( @@ -440,28 +419,26 @@ GenerateMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); } } else { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Override\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$type_parameters$> " - "${$get$capitalized_name$$}$() {\n" - " return get$capitalized_name$Map();\n" - "}\n"); + printer->Print(variables_, + "/**\n" + " * Use {@link #get$capitalized_name$Map()} instead.\n" + " */\n" + "@java.lang.Override\n" + "@java.lang.Deprecated\n" + "public java.util.Map<$type_parameters$> " + "${$get$capitalized_name$$}$() {\n" + " return get$capitalized_name$Map();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public java.util.Map<$type_parameters$> " - "${$get$capitalized_name$Map$}$() {\n" - " return java.util.Collections.unmodifiableMap(\n" - " internalGet$capitalized_name$());\n" - "}\n"); + printer->Print(variables_, + "@java.lang.Override\n" + "$deprecation$\n" + "public java.util.Map<$type_parameters$> " + "${$get$capitalized_name$Map$}$() {\n" + " return java.util.Collections.unmodifiableMap(\n" + " internalGet$capitalized_name$());\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print( @@ -478,20 +455,19 @@ GenerateMembers(io::Printer* printer) const { "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " java.util.Map<$type_parameters$> map =\n" - " internalGet$capitalized_name$();\n" - " if (!map.containsKey(key)) {\n" - " throw new java.lang.IllegalArgumentException();\n" - " }\n" - " return map.get(key);\n" - "}\n"); + printer->Print(variables_, + "@java.lang.Override\n" + "$deprecation$\n" + "public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n" + " $key_type$ key) {\n" + " $key_null_check$\n" + " java.util.Map<$type_parameters$> map =\n" + " internalGet$capitalized_name$();\n" + " if (!map.containsKey(key)) {\n" + " throw new java.lang.IllegalArgumentException();\n" + " }\n" + " return map.get(key);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } @@ -518,25 +494,39 @@ GenerateMembers(io::Printer* printer) const { } } else { WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "private java.util.Map<$type_parameters$>\n" - "getMutable$capitalized_name$Map() {\n" - " return internalGetMutable$capitalized_name$();\n" - "}\n"); + printer->Print(variables_, + "private java.util.Map<$type_parameters$>\n" + "getMutable$capitalized_name$Map() {\n" + " return internalGetMutable$capitalized_name$();\n" + "}\n"); } } +void ImmutableMapFieldLiteGenerator::GenerateFieldInfo( + io::Printer* printer, std::vector* output) const { + WriteIntToUtf16CharSequence(descriptor_->number(), output); + WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_), + output); + printer->Print(variables_, + "\"$name$_\",\n" + "$default_entry$,\n"); + if (SupportFieldPresence(descriptor_->file()) && + GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { + PrintEnumVerifierLogic(printer, ValueField(descriptor_), variables_, + /*var_name=*/"$value_enum_type$", + /*terminating_string=*/",\n", + /*enforce_lite=*/context_->EnforceLite()); + } +} -void ImmutableMapFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public int ${$get$capitalized_name$Count$}$() {\n" - " return instance.get$capitalized_name$Map().size();\n" - "}\n"); +void ImmutableMapFieldLiteGenerator::GenerateBuilderMembers( + io::Printer* printer) const { + printer->Print(variables_, + "@java.lang.Override\n" + "$deprecation$\n" + "public int ${$get$capitalized_name$Count$}$() {\n" + " return instance.get$capitalized_name$Map().size();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print( @@ -549,49 +539,45 @@ GenerateBuilderMembers(io::Printer* printer) const { " return instance.get$capitalized_name$Map().containsKey(key);\n" "}\n"); printer->Annotate("{", "}", descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.getMutable$capitalized_name$Map().clear();\n" - " return this;\n" - "}\n"); + printer->Print(variables_, + "$deprecation$\n" + "public Builder ${$clear$capitalized_name$$}$() {\n" + " copyOnWrite();\n" + " instance.getMutable$capitalized_name$Map().clear();\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public Builder ${$remove$capitalized_name$$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " copyOnWrite();\n" - " instance.getMutable$capitalized_name$Map().remove(key);\n" - " return this;\n" - "}\n"); + printer->Print(variables_, + "$deprecation$\n" + "public Builder ${$remove$capitalized_name$$}$(\n" + " $key_type$ key) {\n" + " $key_null_check$\n" + " copyOnWrite();\n" + " instance.getMutable$capitalized_name$Map().remove(key);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$get$capitalized_name$$}$() {\n" - " return get$capitalized_name$Map();\n" - "}\n"); + printer->Print(variables_, + "/**\n" + " * Use {@link #get$capitalized_name$Map()} instead.\n" + " */\n" + "@java.lang.Deprecated\n" + "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" + "${$get$capitalized_name$$}$() {\n" + " return get$capitalized_name$Map();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$get$capitalized_name$Map$}$() {\n" - " return java.util.Collections.unmodifiableMap(\n" - " instance.get$capitalized_name$Map());\n" - "}\n"); + printer->Print(variables_, + "@java.lang.Override\n" + "$deprecation$\n" + "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" + "${$get$capitalized_name$Map$}$() {\n" + " return java.util.Collections.unmodifiableMap(\n" + " instance.get$capitalized_name$Map());\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print( @@ -726,28 +712,26 @@ GenerateBuilderMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); } } else { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Override\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$type_parameters$> " - "${$get$capitalized_name$$}$() {\n" - " return get$capitalized_name$Map();\n" - "}\n"); + printer->Print(variables_, + "/**\n" + " * Use {@link #get$capitalized_name$Map()} instead.\n" + " */\n" + "@java.lang.Override\n" + "@java.lang.Deprecated\n" + "public java.util.Map<$type_parameters$> " + "${$get$capitalized_name$$}$() {\n" + " return get$capitalized_name$Map();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$" - "public java.util.Map<$type_parameters$> " - "${$get$capitalized_name$Map$}$() {\n" - " return java.util.Collections.unmodifiableMap(\n" - " instance.get$capitalized_name$Map());\n" - "}\n"); + printer->Print(variables_, + "@java.lang.Override\n" + "$deprecation$" + "public java.util.Map<$type_parameters$> " + "${$get$capitalized_name$Map$}$() {\n" + " return java.util.Collections.unmodifiableMap(\n" + " instance.get$capitalized_name$Map());\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print( @@ -764,20 +748,19 @@ GenerateBuilderMembers(io::Printer* printer) const { "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " java.util.Map<$type_parameters$> map =\n" - " instance.get$capitalized_name$Map();\n" - " if (!map.containsKey(key)) {\n" - " throw new java.lang.IllegalArgumentException();\n" - " }\n" - " return map.get(key);\n" - "}\n"); + printer->Print(variables_, + "@java.lang.Override\n" + "$deprecation$\n" + "public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n" + " $key_type$ key) {\n" + " $key_null_check$\n" + " java.util.Map<$type_parameters$> map =\n" + " instance.get$capitalized_name$Map();\n" + " if (!map.containsKey(key)) {\n" + " throw new java.lang.IllegalArgumentException();\n" + " }\n" + " return map.get(key);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print( @@ -807,104 +790,12 @@ GenerateBuilderMembers(io::Printer* printer) const { } } -void ImmutableMapFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { +void ImmutableMapFieldLiteGenerator::GenerateInitializationCode( + io::Printer* printer) const { // Nothing to initialize. } -void ImmutableMapFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - // Nothing to initialize. -} - -void ImmutableMapFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print( - variables_, - "$name$_ = visitor.visitMap(\n" - " $name$_, other.internalGet$capitalized_name$());\n"); -} - -void ImmutableMapFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_.makeImmutable();\n"); -} - -void ImmutableMapFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print( - variables_, - "if (!$name$_.isMutable()) {\n" - " $name$_ = $name$_.mutableCopy();\n" - "}\n"); - if (!SupportUnknownEnumValue(descriptor_->file()) && - GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { - printer->Print( - variables_, - "com.google.protobuf.ByteString bytes = input.readBytes();\n" - "java.util.Map.Entry<$type_parameters$> $name$__ =\n" - " $default_entry$.parseEntry(bytes, extensionRegistry);\n"); - printer->Print( - variables_, - "if ($value_enum_type$.forNumber($name$__.getValue()) == null) {\n" - " super.mergeLengthDelimitedField($number$, bytes);\n" - "} else {\n" - " $name$_.put($name$__);\n" - "}\n"); - } else { - printer->Print( - variables_, - "$default_entry$.parseInto($name$_, input, extensionRegistry);"); - } -} - -void ImmutableMapFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - // Nothing to do here. -} - -void ImmutableMapFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print( - variables_, - "for (java.util.Map.Entry<$type_parameters$> entry\n" - " : internalGet$capitalized_name$().entrySet()) {\n" - " $default_entry$.serializeTo(\n" - " output, $number$, entry.getKey(), entry.getValue());\n" - "}\n"); -} - -void ImmutableMapFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print( - variables_, - "for (java.util.Map.Entry<$type_parameters$> entry\n" - " : internalGet$capitalized_name$().entrySet()) {\n" - " size += $default_entry$.computeMessageSize(\n" - " $number$, entry.getKey(), entry.getValue());\n" - "}\n"); -} - -void ImmutableMapFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print( - variables_, - "result = result && internalGet$capitalized_name$().equals(\n" - " other.internalGet$capitalized_name$());\n"); -} - -void ImmutableMapFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print( - variables_, - "if (!internalGet$capitalized_name$().isEmpty()) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + internalGet$capitalized_name$().hashCode();\n" - "}\n"); -} - -string ImmutableMapFieldLiteGenerator::GetBoxedType() const { +std::string ImmutableMapFieldLiteGenerator::GetBoxedType() const { return name_resolver_->GetImmutableClassName(descriptor_->message_type()); } diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_map_field_lite.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_map_field_lite.h index 94aa4813..49cbf6cc 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_map_field_lite.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_map_field_lite.h @@ -40,40 +40,32 @@ namespace java { class ImmutableMapFieldLiteGenerator : public ImmutableFieldLiteGenerator { public: - explicit ImmutableMapFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + explicit ImmutableMapFieldLiteGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, + Context* context); ~ImmutableMapFieldLiteGenerator(); // implements ImmutableFieldLiteGenerator ------------------------------------ int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; void GenerateInterfaceMembers(io::Printer* printer) const; void GenerateMembers(io::Printer* printer) const; void GenerateBuilderMembers(io::Printer* printer) const; void GenerateInitializationCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; + void GenerateFieldInfo(io::Printer* printer, + std::vector* output) const; - - string GetBoxedType() const; + std::string GetBoxedType() const; private: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; + Context* context_; ClassNameResolver* name_resolver_; }; } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MAP_FIELD_LITE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_message.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_message.cc index 209c0b2a..5bbdccee 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_message.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_message.cc @@ -35,7 +35,6 @@ #include #include -#include #include #include #include @@ -53,8 +52,9 @@ #include #include #include -#include #include +#include + namespace google { @@ -66,13 +66,8 @@ using internal::WireFormat; using internal::WireFormatLite; namespace { -bool GenerateHasBits(const Descriptor* descriptor) { - return SupportFieldPresence(descriptor->file()) || - HasRepeatedFields(descriptor); -} - -string MapValueImmutableClassdName(const Descriptor* descriptor, - ClassNameResolver* name_resolver) { +std::string MapValueImmutableClassdName(const Descriptor* descriptor, + ClassNameResolver* name_resolver) { const FieldDescriptor* value_field = descriptor->FindFieldByName("value"); GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, value_field->type()); return name_resolver->GetImmutableClassName(value_field->message_type()); @@ -82,16 +77,17 @@ string MapValueImmutableClassdName(const Descriptor* descriptor, // =================================================================== MessageGenerator::MessageGenerator(const Descriptor* descriptor) - : descriptor_(descriptor) {} + : descriptor_(descriptor) {} MessageGenerator::~MessageGenerator() {} // =================================================================== ImmutableMessageGenerator::ImmutableMessageGenerator( const Descriptor* descriptor, Context* context) - : MessageGenerator(descriptor), context_(context), - name_resolver_(context->GetNameResolver()), - field_generators_(descriptor, context_) { + : MessageGenerator(descriptor), + context_(context), + name_resolver_(context->GetNameResolver()), + field_generators_(descriptor, context_) { GOOGLE_CHECK(HasDescriptorMethods(descriptor->file(), context->EnforceLite())) << "Generator factory error: A non-lite message generator is used to " "generate lite messages."; @@ -108,13 +104,12 @@ void ImmutableMessageGenerator::GenerateStaticVariables( // the outermost class in the file. This way, they will be initialized in // a deterministic order. - std::map vars; + std::map vars; vars["identifier"] = UniqueFileScopeIdentifier(descriptor_); - vars["index"] = SimpleItoa(descriptor_->index()); + vars["index"] = StrCat(descriptor_->index()); vars["classname"] = name_resolver_->GetImmutableClassName(descriptor_); if (descriptor_->containing_type() != NULL) { - vars["parent"] = UniqueFileScopeIdentifier( - descriptor_->containing_type()); + vars["parent"] = UniqueFileScopeIdentifier(descriptor_->containing_type()); } if (MultipleJavaFiles(descriptor_->file(), /* immutable = */ true)) { // We can only make these package-private since the classes that use them @@ -130,12 +125,13 @@ void ImmutableMessageGenerator::GenerateStaticVariables( } // The descriptor for this type. - printer->Print(vars, - // TODO(teboring): final needs to be added back. The way to fix it is to - // generate methods that can construct the types, and then still declare the - // types, and then init them in clinit with the new method calls. - "$private$static $final$com.google.protobuf.Descriptors.Descriptor\n" - " internal_$identifier$_descriptor;\n"); + printer->Print( + vars, + // TODO(teboring): final needs to be added back. The way to fix it is to + // generate methods that can construct the types, and then still declare + // the types, and then init them in clinit with the new method calls. + "$private$static $final$com.google.protobuf.Descriptors.Descriptor\n" + " internal_$identifier$_descriptor;\n"); *bytecode_estimate += 30; // And the FieldAccessorTable. @@ -152,25 +148,25 @@ void ImmutableMessageGenerator::GenerateStaticVariables( int ImmutableMessageGenerator::GenerateStaticVariableInitializers( io::Printer* printer) { int bytecode_estimate = 0; - std::map vars; + std::map vars; vars["identifier"] = UniqueFileScopeIdentifier(descriptor_); - vars["index"] = SimpleItoa(descriptor_->index()); + vars["index"] = StrCat(descriptor_->index()); vars["classname"] = name_resolver_->GetImmutableClassName(descriptor_); if (descriptor_->containing_type() != NULL) { - vars["parent"] = UniqueFileScopeIdentifier( - descriptor_->containing_type()); + vars["parent"] = UniqueFileScopeIdentifier(descriptor_->containing_type()); } // The descriptor for this type. if (descriptor_->containing_type() == NULL) { printer->Print(vars, - "internal_$identifier$_descriptor =\n" - " getDescriptor().getMessageTypes().get($index$);\n"); + "internal_$identifier$_descriptor =\n" + " getDescriptor().getMessageTypes().get($index$);\n"); bytecode_estimate += 30; } else { - printer->Print(vars, - "internal_$identifier$_descriptor =\n" - " internal_$parent$_descriptor.getNestedTypes().get($index$);\n"); + printer->Print( + vars, + "internal_$identifier$_descriptor =\n" + " internal_$parent$_descriptor.getNestedTypes().get($index$);\n"); bytecode_estimate += 30; } @@ -187,9 +183,9 @@ int ImmutableMessageGenerator::GenerateStaticVariableInitializers( return bytecode_estimate; } -void ImmutableMessageGenerator:: -GenerateFieldAccessorTable(io::Printer* printer, int* bytecode_estimate) { - std::map vars; +void ImmutableMessageGenerator::GenerateFieldAccessorTable( + io::Printer* printer, int* bytecode_estimate) { + std::map vars; vars["identifier"] = UniqueFileScopeIdentifier(descriptor_); if (MultipleJavaFiles(descriptor_->file(), /* immutable = */ true)) { // We can only make these package-private since the classes that use them @@ -204,41 +200,38 @@ GenerateFieldAccessorTable(io::Printer* printer, int* bytecode_estimate) { vars["final"] = ""; } vars["ver"] = GeneratedCodeVersionSuffix(); - printer->Print(vars, - "$private$static $final$\n" - " com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n" - " internal_$identifier$_fieldAccessorTable;\n"); + printer->Print( + vars, + "$private$static $final$\n" + " com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n" + " internal_$identifier$_fieldAccessorTable;\n"); // 6 bytes per field and oneof - *bytecode_estimate += 10 + 6 * descriptor_->field_count() - + 6 * descriptor_->oneof_decl_count(); + *bytecode_estimate += + 10 + 6 * descriptor_->field_count() + 6 * descriptor_->oneof_decl_count(); } -int ImmutableMessageGenerator:: -GenerateFieldAccessorTableInitializer(io::Printer* printer) { +int ImmutableMessageGenerator::GenerateFieldAccessorTableInitializer( + io::Printer* printer) { int bytecode_estimate = 10; printer->Print( - "internal_$identifier$_fieldAccessorTable = new\n" - " com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable(\n" - " internal_$identifier$_descriptor,\n" - " new java.lang.String[] { ", - "identifier", UniqueFileScopeIdentifier(descriptor_), - "ver", GeneratedCodeVersionSuffix()); + "internal_$identifier$_fieldAccessorTable = new\n" + " com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable(\n" + " internal_$identifier$_descriptor,\n" + " new java.lang.String[] { ", + "identifier", UniqueFileScopeIdentifier(descriptor_), "ver", + GeneratedCodeVersionSuffix()); for (int i = 0; i < descriptor_->field_count(); i++) { const FieldDescriptor* field = descriptor_->field(i); const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); bytecode_estimate += 6; - printer->Print( - "\"$field_name$\", ", - "field_name", info->capitalized_name); + printer->Print("\"$field_name$\", ", "field_name", info->capitalized_name); } for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { const OneofDescriptor* oneof = descriptor_->oneof_decl(i); const OneofGeneratorInfo* info = context_->GetOneofGeneratorInfo(oneof); bytecode_estimate += 6; - printer->Print( - "\"$oneof_name$\", ", - "oneof_name", info->capitalized_name); + printer->Print("\"$oneof_name$\", ", "oneof_name", info->capitalized_name); } printer->Print("});\n"); return bytecode_estimate; @@ -255,42 +248,40 @@ void ImmutableMessageGenerator::GenerateInterface(io::Printer* printer) { " $extra_interfaces$\n" " com.google.protobuf.GeneratedMessage$ver$.\n" " ExtendableMessageOrBuilder<$classname$> {\n", - "deprecation", descriptor_->options().deprecated() ? - "@java.lang.Deprecated " : "", + "deprecation", + descriptor_->options().deprecated() ? "@java.lang.Deprecated " : "", "extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_), - "classname", descriptor_->name(), - "{", "", "}", "", "ver", GeneratedCodeVersionSuffix()); + "classname", descriptor_->name(), "{", "", "}", "", "ver", + GeneratedCodeVersionSuffix()); } else { printer->Print( "$deprecation$public interface ${$$classname$OrBuilder$}$ extends\n" " $extra_interfaces$\n" " com.google.protobuf.MessageOrBuilder {\n", - "deprecation", descriptor_->options().deprecated() ? - "@java.lang.Deprecated " : "", + "deprecation", + descriptor_->options().deprecated() ? "@java.lang.Deprecated " : "", "extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_), - "classname", descriptor_->name(), - "{", "", "}", ""); + "classname", descriptor_->name(), "{", "", "}", ""); } printer->Annotate("{", "}", descriptor_); printer->Indent(); - for (int i = 0; i < descriptor_->field_count(); i++) { - printer->Print("\n"); - field_generators_.get(descriptor_->field(i)) - .GenerateInterfaceMembers(printer); - } - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "\n" - "public $classname$.$oneof_capitalized_name$Case " - "get$oneof_capitalized_name$Case();\n", - "oneof_capitalized_name", - context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->capitalized_name, - "classname", - context_->GetNameResolver()->GetImmutableClassName( - descriptor_)); - } + for (int i = 0; i < descriptor_->field_count(); i++) { + printer->Print("\n"); + field_generators_.get(descriptor_->field(i)) + .GenerateInterfaceMembers(printer); + } + for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { + printer->Print( + "\n" + "public $classname$.$oneof_capitalized_name$Case " + "get$oneof_capitalized_name$Case();\n", + "oneof_capitalized_name", + context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i)) + ->capitalized_name, + "classname", + context_->GetNameResolver()->GetImmutableClassName(descriptor_)); + } printer->Outdent(); printer->Print("}\n"); @@ -301,20 +292,20 @@ void ImmutableMessageGenerator::GenerateInterface(io::Printer* printer) { void ImmutableMessageGenerator::Generate(io::Printer* printer) { bool is_own_file = IsOwnFile(descriptor_, /* immutable = */ true); - std::map variables; + std::map variables; variables["static"] = is_own_file ? " " : " static "; variables["classname"] = descriptor_->name(); variables["extra_interfaces"] = ExtraMessageInterfaces(descriptor_); variables["ver"] = GeneratedCodeVersionSuffix(); - variables["deprecation"] = descriptor_->options().deprecated() - ? "@java.lang.Deprecated " : ""; + variables["deprecation"] = + descriptor_->options().deprecated() ? "@java.lang.Deprecated " : ""; WriteMessageDocComment(printer, descriptor_); MaybePrintGeneratedAnnotation(context_, printer, descriptor_, /* immutable = */ true); // The builder_type stores the super type name of the nested Builder class. - string builder_type; + std::string builder_type; if (descriptor_->extension_range_count() > 0) { printer->Print( variables, @@ -336,15 +327,14 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) { "$deprecation$public $static$final class $classname$ extends\n"); printer->Annotate("classname", descriptor_); printer->Print(variables, - " com.google.protobuf.GeneratedMessage$ver$ implements\n" - " $extra_interfaces$\n" - " $classname$OrBuilder {\n"); - builder_type = strings::Substitute( - "com.google.protobuf.GeneratedMessage$0.Builder", - GeneratedCodeVersionSuffix()); + " com.google.protobuf.GeneratedMessage$ver$ implements\n" + " $extra_interfaces$\n" + " $classname$OrBuilder {\n"); + builder_type = + strings::Substitute("com.google.protobuf.GeneratedMessage$0.Builder", + GeneratedCodeVersionSuffix()); } - printer->Print( - "private static final long serialVersionUID = 0L;\n"); + printer->Print("private static final long serialVersionUID = 0L;\n"); printer->Indent(); // Using builder_type, instead of Builder, prevents the Builder class from @@ -352,142 +342,137 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) { // This optimizes the PermGen space usage for clients that do not modify // messages. printer->Print( - "// Use $classname$.newBuilder() to construct.\n" - "private $classname$($buildertype$ builder) {\n" - " super(builder);\n" - "}\n", - "classname", descriptor_->name(), - "buildertype", builder_type); - printer->Print( - "private $classname$() {\n", - "classname", descriptor_->name()); + "// Use $classname$.newBuilder() to construct.\n" + "private $classname$($buildertype$ builder) {\n" + " super(builder);\n" + "}\n", + "classname", descriptor_->name(), "buildertype", builder_type); + printer->Print("private $classname$() {\n", "classname", descriptor_->name()); printer->Indent(); GenerateInitializers(printer); printer->Outdent(); printer->Print( - "}\n" - "\n"); + "}\n" + "\n"); + printer->Print(variables, + "@java.lang.Override\n" + "@SuppressWarnings({\"unused\"})\n" + "protected java.lang.Object newInstance(\n" + " UnusedPrivateParameter unused) {\n" + " return new $classname$();\n" + "}\n" + "\n"); printer->Print( - "@java.lang.Override\n" - "public final com.google.protobuf.UnknownFieldSet\n" - "getUnknownFields() {\n" - " return this.unknownFields;\n" - "}\n"); + "@java.lang.Override\n" + "public final com.google.protobuf.UnknownFieldSet\n" + "getUnknownFields() {\n" + " return this.unknownFields;\n" + "}\n"); if (context_->HasGeneratedMethods(descriptor_)) { - if (!EnableExperimentalRuntime(context_) || - IsDescriptorProto(descriptor_)) { - GenerateParsingConstructor(printer); - } + GenerateParsingConstructor(printer); } GenerateDescriptorMethods(printer); // Nested types for (int i = 0; i < descriptor_->enum_type_count(); i++) { - EnumGenerator(descriptor_->enum_type(i), true, context_) - .Generate(printer); + EnumGenerator(descriptor_->enum_type(i), true, context_).Generate(printer); } for (int i = 0; i < descriptor_->nested_type_count(); i++) { // Don't generate Java classes for map entry messages. if (IsMapEntry(descriptor_->nested_type(i))) continue; - ImmutableMessageGenerator messageGenerator( - descriptor_->nested_type(i), context_); + ImmutableMessageGenerator messageGenerator(descriptor_->nested_type(i), + context_); messageGenerator.GenerateInterface(printer); messageGenerator.Generate(printer); } - if (GenerateHasBits(descriptor_)) { - // Integers for bit fields. - int totalBits = 0; - for (int i = 0; i < descriptor_->field_count(); i++) { - totalBits += field_generators_.get(descriptor_->field(i)) - .GetNumBitsForMessage(); - } - int totalInts = (totalBits + 31) / 32; - for (int i = 0; i < totalInts; i++) { - printer->Print("private int $bit_field_name$;\n", - "bit_field_name", GetBitFieldName(i)); - } + // Integers for bit fields. + int totalBits = 0; + for (int i = 0; i < descriptor_->field_count(); i++) { + totalBits += + field_generators_.get(descriptor_->field(i)).GetNumBitsForMessage(); + } + int totalInts = (totalBits + 31) / 32; + for (int i = 0; i < totalInts; i++) { + printer->Print("private int $bit_field_name$;\n", "bit_field_name", + GetBitFieldName(i)); } // oneof - std::map vars; + std::map vars; for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - vars["oneof_name"] = context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name; - vars["oneof_capitalized_name"] = context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->capitalized_name; - vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index()); + vars["oneof_name"] = + context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))->name; + vars["oneof_capitalized_name"] = + context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i)) + ->capitalized_name; + vars["oneof_index"] = StrCat(descriptor_->oneof_decl(i)->index()); // oneofCase_ and oneof_ printer->Print(vars, - "private int $oneof_name$Case_ = 0;\n" - "private java.lang.Object $oneof_name$_;\n"); + "private int $oneof_name$Case_ = 0;\n" + "private java.lang.Object $oneof_name$_;\n"); // OneofCase enum printer->Print(vars, - "public enum $oneof_capitalized_name$Case\n" - " implements com.google.protobuf.Internal.EnumLite {\n"); + "public enum $oneof_capitalized_name$Case\n" + " implements com.google.protobuf.Internal.EnumLite {\n"); printer->Indent(); for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); printer->Print( - "$deprecation$$field_name$($field_number$),\n", - "deprecation", - field->options().deprecated() ? "@java.lang.Deprecated " : "", - "field_name", ToUpper(field->name()), - "field_number", SimpleItoa(field->number())); + "$deprecation$$field_name$($field_number$),\n", "deprecation", + field->options().deprecated() ? "@java.lang.Deprecated " : "", + "field_name", ToUpper(field->name()), "field_number", + StrCat(field->number())); } + printer->Print("$cap_oneof_name$_NOT_SET(0);\n", "cap_oneof_name", + ToUpper(vars["oneof_name"])); + printer->Print(vars, + "private final int value;\n" + "private $oneof_capitalized_name$Case(int value) {\n" + " this.value = value;\n" + "}\n"); printer->Print( - "$cap_oneof_name$_NOT_SET(0);\n", - "cap_oneof_name", - ToUpper(vars["oneof_name"])); - printer->Print(vars, - "private final int value;\n" - "private $oneof_capitalized_name$Case(int value) {\n" - " this.value = value;\n" - "}\n"); - printer->Print(vars, - "/**\n" - " * @deprecated Use {@link #forNumber(int)} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public static $oneof_capitalized_name$Case valueOf(int value) {\n" - " return forNumber(value);\n" - "}\n" - "\n" - "public static $oneof_capitalized_name$Case forNumber(int value) {\n" - " switch (value) {\n"); + vars, + "/**\n" + " * @deprecated Use {@link #forNumber(int)} instead.\n" + " */\n" + "@java.lang.Deprecated\n" + "public static $oneof_capitalized_name$Case valueOf(int value) {\n" + " return forNumber(value);\n" + "}\n" + "\n" + "public static $oneof_capitalized_name$Case forNumber(int value) {\n" + " switch (value) {\n"); for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print( - " case $field_number$: return $field_name$;\n", - "field_number", - SimpleItoa(field->number()), - "field_name", - ToUpper(field->name())); + printer->Print(" case $field_number$: return $field_name$;\n", + "field_number", StrCat(field->number()), + "field_name", ToUpper(field->name())); } printer->Print( - " case 0: return $cap_oneof_name$_NOT_SET;\n" - " default: return null;\n" - " }\n" - "}\n" - "public int getNumber() {\n" - " return this.value;\n" - "}\n", - "cap_oneof_name", ToUpper(vars["oneof_name"])); + " case 0: return $cap_oneof_name$_NOT_SET;\n" + " default: return null;\n" + " }\n" + "}\n" + "public int getNumber() {\n" + " return this.value;\n" + "}\n", + "cap_oneof_name", ToUpper(vars["oneof_name"])); printer->Outdent(); printer->Print("};\n\n"); // oneofCase() printer->Print(vars, - "public $oneof_capitalized_name$Case\n" - "get$oneof_capitalized_name$Case() {\n" - " return $oneof_capitalized_name$Case.forNumber(\n" - " $oneof_name$Case_);\n" - "}\n" - "\n"); + "public $oneof_capitalized_name$Case\n" + "get$oneof_capitalized_name$Case() {\n" + " return $oneof_capitalized_name$Case.forNumber(\n" + " $oneof_name$Case_);\n" + "}\n" + "\n"); } if (IsAnyMessage(descriptor_)) { @@ -497,8 +482,8 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) { // Fields for (int i = 0; i < descriptor_->field_count(); i++) { printer->Print("public static final int $constant_name$ = $number$;\n", - "constant_name", FieldConstantName(descriptor_->field(i)), - "number", SimpleItoa(descriptor_->field(i)->number())); + "constant_name", FieldConstantName(descriptor_->field(i)), + "number", StrCat(descriptor_->field(i)->number())); field_generators_.get(descriptor_->field(i)).GenerateMembers(printer); printer->Print("\n"); } @@ -514,22 +499,21 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) { GenerateBuilder(printer); printer->Print( - "\n" - "// @@protoc_insertion_point(class_scope:$full_name$)\n", - "full_name", descriptor_->full_name()); - + "\n" + "// @@protoc_insertion_point(class_scope:$full_name$)\n", + "full_name", descriptor_->full_name()); // Carefully initialize the default instance in such a way that it doesn't // conflict with other initialization. + printer->Print("private static final $classname$ DEFAULT_INSTANCE;\n", + "classname", + name_resolver_->GetImmutableClassName(descriptor_)); printer->Print( - "private static final $classname$ DEFAULT_INSTANCE;\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - printer->Print( - "static {\n" - " DEFAULT_INSTANCE = new $classname$();\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + "static {\n" + " DEFAULT_INSTANCE = new $classname$();\n" + "}\n" + "\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); printer->Print( "public static $classname$ getDefaultInstance() {\n" @@ -552,12 +536,12 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) { GenerateParser(printer); printer->Print( - "@java.lang.Override\n" - "public $classname$ getDefaultInstanceForType() {\n" - " return DEFAULT_INSTANCE;\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + "@java.lang.Override\n" + "public $classname$ getDefaultInstanceForType() {\n" + " return DEFAULT_INSTANCE;\n" + "}\n" + "\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); // Extensions must be declared after the DEFAULT_INSTANCE is initialized // because the DEFAULT_INSTANCE is used by the extension to lazily retrieve @@ -571,12 +555,11 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) { printer->Print("}\n\n"); } - // =================================================================== -void ImmutableMessageGenerator:: -GenerateMessageSerializationMethods(io::Printer* printer) { - std::unique_ptr sorted_fields( +void ImmutableMessageGenerator::GenerateMessageSerializationMethods( + io::Printer* printer) { + std::unique_ptr sorted_fields( SortFieldsByNumber(descriptor_)); std::vector sorted_extensions; @@ -586,63 +569,59 @@ GenerateMessageSerializationMethods(io::Printer* printer) { std::sort(sorted_extensions.begin(), sorted_extensions.end(), ExtensionRangeOrdering()); printer->Print( - "@java.lang.Override\n" - "public void writeTo(com.google.protobuf.CodedOutputStream output)\n" - " throws java.io.IOException {\n"); + "@java.lang.Override\n" + "public void writeTo(com.google.protobuf.CodedOutputStream output)\n" + " throws java.io.IOException {\n"); printer->Indent(); - if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) { - printer->Print("writeToInternal(output);\n"); - } else { - if (HasPackedFields(descriptor_)) { - // writeTo(CodedOutputStream output) might be invoked without - // getSerializedSize() ever being called, but we need the memoized - // sizes in case this message has packed fields. Rather than emit checks - // for each packed field, just call getSerializedSize() up front. In most - // cases, getSerializedSize() will have already been called anyway by one - // of the wrapper writeTo() methods, making this call cheap. - printer->Print("getSerializedSize();\n"); - } - - if (descriptor_->extension_range_count() > 0) { - if (descriptor_->options().message_set_wire_format()) { - printer->Print( - "com.google.protobuf.GeneratedMessage$ver$\n" - " .ExtendableMessage<$classname$>.ExtensionWriter\n" - " extensionWriter = newMessageSetExtensionWriter();\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "ver", GeneratedCodeVersionSuffix()); - } else { - printer->Print( - "com.google.protobuf.GeneratedMessage$ver$\n" - " .ExtendableMessage<$classname$>.ExtensionWriter\n" - " extensionWriter = newExtensionWriter();\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "ver", GeneratedCodeVersionSuffix()); - } - } - - // Merge the fields and the extension ranges, both sorted by field number. - for (int i = 0, j = 0; - i < descriptor_->field_count() || j < sorted_extensions.size();) { - if (i == descriptor_->field_count()) { - GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]); - } else if (j == sorted_extensions.size()) { - GenerateSerializeOneField(printer, sorted_fields[i++]); - } else if (sorted_fields[i]->number() < sorted_extensions[j]->start) { - GenerateSerializeOneField(printer, sorted_fields[i++]); - } else { - GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]); - } - } + if (HasPackedFields(descriptor_)) { + // writeTo(CodedOutputStream output) might be invoked without + // getSerializedSize() ever being called, but we need the memoized + // sizes in case this message has packed fields. Rather than emit checks + // for each packed field, just call getSerializedSize() up front. In most + // cases, getSerializedSize() will have already been called anyway by one + // of the wrapper writeTo() methods, making this call cheap. + printer->Print("getSerializedSize();\n"); + } + if (descriptor_->extension_range_count() > 0) { if (descriptor_->options().message_set_wire_format()) { - printer->Print("unknownFields.writeAsMessageSetTo(output);\n"); + printer->Print( + "com.google.protobuf.GeneratedMessage$ver$\n" + " .ExtendableMessage<$classname$>.ExtensionWriter\n" + " extensionWriter = newMessageSetExtensionWriter();\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_), + "ver", GeneratedCodeVersionSuffix()); } else { - printer->Print("unknownFields.writeTo(output);\n"); + printer->Print( + "com.google.protobuf.GeneratedMessage$ver$\n" + " .ExtendableMessage<$classname$>.ExtensionWriter\n" + " extensionWriter = newExtensionWriter();\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_), + "ver", GeneratedCodeVersionSuffix()); } } + // Merge the fields and the extension ranges, both sorted by field number. + for (int i = 0, j = 0; + i < descriptor_->field_count() || j < sorted_extensions.size();) { + if (i == descriptor_->field_count()) { + GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]); + } else if (j == sorted_extensions.size()) { + GenerateSerializeOneField(printer, sorted_fields[i++]); + } else if (sorted_fields[i]->number() < sorted_extensions[j]->start) { + GenerateSerializeOneField(printer, sorted_fields[i++]); + } else { + GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]); + } + } + + if (descriptor_->options().message_set_wire_format()) { + printer->Print("unknownFields.writeAsMessageSetTo(output);\n"); + } else { + printer->Print("unknownFields.writeTo(output);\n"); + } + printer->Outdent(); printer->Print( "}\n" @@ -653,123 +632,116 @@ GenerateMessageSerializationMethods(io::Printer* printer) { " if (size != -1) return size;\n" "\n"); printer->Indent(); - if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) { - printer->Print( - "memoizedSize = getSerializedSizeInternal();\n" - "return memoizedSize;\n"); - } else { - printer->Print("size = 0;\n"); + printer->Print("size = 0;\n"); - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(sorted_fields[i]) - .GenerateSerializedSizeCode(printer); - } - - if (descriptor_->extension_range_count() > 0) { - if (descriptor_->options().message_set_wire_format()) { - printer->Print("size += extensionsSerializedSizeAsMessageSet();\n"); - } else { - printer->Print("size += extensionsSerializedSize();\n"); - } - } - - if (descriptor_->options().message_set_wire_format()) { - printer->Print( - "size += unknownFields.getSerializedSizeAsMessageSet();\n"); - } else { - printer->Print("size += unknownFields.getSerializedSize();\n"); - } - - printer->Print( - "memoizedSize = size;\n" - "return size;\n"); + for (int i = 0; i < descriptor_->field_count(); i++) { + field_generators_.get(sorted_fields[i]).GenerateSerializedSizeCode(printer); } + if (descriptor_->extension_range_count() > 0) { + if (descriptor_->options().message_set_wire_format()) { + printer->Print("size += extensionsSerializedSizeAsMessageSet();\n"); + } else { + printer->Print("size += extensionsSerializedSize();\n"); + } + } + + if (descriptor_->options().message_set_wire_format()) { + printer->Print("size += unknownFields.getSerializedSizeAsMessageSet();\n"); + } else { + printer->Print("size += unknownFields.getSerializedSize();\n"); + } + + printer->Print( + "memoizedSize = size;\n" + "return size;\n"); + printer->Outdent(); printer->Print( - "}\n" - "\n"); + "}\n" + "\n"); } -void ImmutableMessageGenerator:: -GenerateParseFromMethods(io::Printer* printer) { +void ImmutableMessageGenerator::GenerateParseFromMethods(io::Printer* printer) { // Note: These are separate from GenerateMessageSerializationMethods() // because they need to be generated even for messages that are optimized // for code size. printer->Print( - "public static $classname$ parseFrom(\n" - " java.nio.ByteBuffer data)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return PARSER.parseFrom(data);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " java.nio.ByteBuffer data,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return PARSER.parseFrom(data, extensionRegistry);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " com.google.protobuf.ByteString data)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return PARSER.parseFrom(data);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " com.google.protobuf.ByteString data,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return PARSER.parseFrom(data, extensionRegistry);\n" - "}\n" - "public static $classname$ parseFrom(byte[] data)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return PARSER.parseFrom(data);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " byte[] data,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return PARSER.parseFrom(data, extensionRegistry);\n" - "}\n" - "public static $classname$ parseFrom(java.io.InputStream input)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage$ver$\n" - " .parseWithIOException(PARSER, input);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " java.io.InputStream input,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage$ver$\n" - " .parseWithIOException(PARSER, input, extensionRegistry);\n" - "}\n" - "public static $classname$ parseDelimitedFrom(java.io.InputStream input)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage$ver$\n" - " .parseDelimitedWithIOException(PARSER, input);\n" - "}\n" - "public static $classname$ parseDelimitedFrom(\n" - " java.io.InputStream input,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage$ver$\n" - " .parseDelimitedWithIOException(PARSER, input, extensionRegistry);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " com.google.protobuf.CodedInputStream input)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage$ver$\n" - " .parseWithIOException(PARSER, input);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " com.google.protobuf.CodedInputStream input,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage$ver$\n" - " .parseWithIOException(PARSER, input, extensionRegistry);\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "ver", GeneratedCodeVersionSuffix()); + "public static $classname$ parseFrom(\n" + " java.nio.ByteBuffer data)\n" + " throws com.google.protobuf.InvalidProtocolBufferException {\n" + " return PARSER.parseFrom(data);\n" + "}\n" + "public static $classname$ parseFrom(\n" + " java.nio.ByteBuffer data,\n" + " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" + " throws com.google.protobuf.InvalidProtocolBufferException {\n" + " return PARSER.parseFrom(data, extensionRegistry);\n" + "}\n" + "public static $classname$ parseFrom(\n" + " com.google.protobuf.ByteString data)\n" + " throws com.google.protobuf.InvalidProtocolBufferException {\n" + " return PARSER.parseFrom(data);\n" + "}\n" + "public static $classname$ parseFrom(\n" + " com.google.protobuf.ByteString data,\n" + " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" + " throws com.google.protobuf.InvalidProtocolBufferException {\n" + " return PARSER.parseFrom(data, extensionRegistry);\n" + "}\n" + "public static $classname$ parseFrom(byte[] data)\n" + " throws com.google.protobuf.InvalidProtocolBufferException {\n" + " return PARSER.parseFrom(data);\n" + "}\n" + "public static $classname$ parseFrom(\n" + " byte[] data,\n" + " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" + " throws com.google.protobuf.InvalidProtocolBufferException {\n" + " return PARSER.parseFrom(data, extensionRegistry);\n" + "}\n" + "public static $classname$ parseFrom(java.io.InputStream input)\n" + " throws java.io.IOException {\n" + " return com.google.protobuf.GeneratedMessage$ver$\n" + " .parseWithIOException(PARSER, input);\n" + "}\n" + "public static $classname$ parseFrom(\n" + " java.io.InputStream input,\n" + " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" + " throws java.io.IOException {\n" + " return com.google.protobuf.GeneratedMessage$ver$\n" + " .parseWithIOException(PARSER, input, extensionRegistry);\n" + "}\n" + "public static $classname$ parseDelimitedFrom(java.io.InputStream " + "input)\n" + " throws java.io.IOException {\n" + " return com.google.protobuf.GeneratedMessage$ver$\n" + " .parseDelimitedWithIOException(PARSER, input);\n" + "}\n" + "public static $classname$ parseDelimitedFrom(\n" + " java.io.InputStream input,\n" + " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" + " throws java.io.IOException {\n" + " return com.google.protobuf.GeneratedMessage$ver$\n" + " .parseDelimitedWithIOException(PARSER, input, " + "extensionRegistry);\n" + "}\n" + "public static $classname$ parseFrom(\n" + " com.google.protobuf.CodedInputStream input)\n" + " throws java.io.IOException {\n" + " return com.google.protobuf.GeneratedMessage$ver$\n" + " .parseWithIOException(PARSER, input);\n" + "}\n" + "public static $classname$ parseFrom(\n" + " com.google.protobuf.CodedInputStream input,\n" + " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" + " throws java.io.IOException {\n" + " return com.google.protobuf.GeneratedMessage$ver$\n" + " .parseWithIOException(PARSER, input, extensionRegistry);\n" + "}\n" + "\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_), "ver", + GeneratedCodeVersionSuffix()); } void ImmutableMessageGenerator::GenerateSerializeOneField( @@ -779,9 +751,8 @@ void ImmutableMessageGenerator::GenerateSerializeOneField( void ImmutableMessageGenerator::GenerateSerializeOneExtensionRange( io::Printer* printer, const Descriptor::ExtensionRange* range) { - printer->Print( - "extensionWriter.writeUntil($end$, output);\n", - "end", SimpleItoa(range->end)); + printer->Print("extensionWriter.writeUntil($end$, output);\n", "end", + StrCat(range->end)); } // =================================================================== @@ -789,48 +760,48 @@ void ImmutableMessageGenerator::GenerateSerializeOneExtensionRange( void ImmutableMessageGenerator::GenerateBuilder(io::Printer* printer) { // LITE_RUNTIME implements this at the GeneratedMessageLite level. printer->Print( - "@java.lang.Override\n" - "public Builder newBuilderForType() { return newBuilder(); }\n"); + "@java.lang.Override\n" + "public Builder newBuilderForType() { return newBuilder(); }\n"); printer->Print( - "public static Builder newBuilder() {\n" - " return DEFAULT_INSTANCE.toBuilder();\n" - "}\n" - "public static Builder newBuilder($classname$ prototype) {\n" - " return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);\n" - "}\n" - "@java.lang.Override\n" - "public Builder toBuilder() {\n" - " return this == DEFAULT_INSTANCE\n" - " ? new Builder() : new Builder().mergeFrom(this);\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + "public static Builder newBuilder() {\n" + " return DEFAULT_INSTANCE.toBuilder();\n" + "}\n" + "public static Builder newBuilder($classname$ prototype) {\n" + " return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);\n" + "}\n" + "@java.lang.Override\n" + "public Builder toBuilder() {\n" + " return this == DEFAULT_INSTANCE\n" + " ? new Builder() : new Builder().mergeFrom(this);\n" + "}\n" + "\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); printer->Print( - "@java.lang.Override\n" - "protected Builder newBuilderForType(\n" - " com.google.protobuf.GeneratedMessage$ver$.BuilderParent parent) {\n" - " Builder builder = new Builder(parent);\n" - " return builder;\n" - "}\n", - "ver", GeneratedCodeVersionSuffix()); + "@java.lang.Override\n" + "protected Builder newBuilderForType(\n" + " com.google.protobuf.GeneratedMessage$ver$.BuilderParent parent) {\n" + " Builder builder = new Builder(parent);\n" + " return builder;\n" + "}\n", + "ver", GeneratedCodeVersionSuffix()); MessageBuilderGenerator builderGenerator(descriptor_, context_); builderGenerator.Generate(printer); } -void ImmutableMessageGenerator:: -GenerateDescriptorMethods(io::Printer* printer) { +void ImmutableMessageGenerator::GenerateDescriptorMethods( + io::Printer* printer) { if (!descriptor_->options().no_standard_descriptor_accessor()) { printer->Print( - "public static final com.google.protobuf.Descriptors.Descriptor\n" - " getDescriptor() {\n" - " return $fileclass$.internal_$identifier$_descriptor;\n" - "}\n" - "\n", - "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()), - "identifier", UniqueFileScopeIdentifier(descriptor_)); + "public static final com.google.protobuf.Descriptors.Descriptor\n" + " getDescriptor() {\n" + " return $fileclass$.internal_$identifier$_descriptor;\n" + "}\n" + "\n", + "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()), + "identifier", UniqueFileScopeIdentifier(descriptor_)); } std::vector map_fields; for (int i = 0; i < descriptor_->field_count(); i++) { @@ -842,21 +813,21 @@ GenerateDescriptorMethods(io::Printer* printer) { } if (!map_fields.empty()) { printer->Print( - "@SuppressWarnings({\"rawtypes\"})\n" - "@java.lang.Override\n" - "protected com.google.protobuf.MapField internalGetMapField(\n" - " int number) {\n" - " switch (number) {\n"); + "@SuppressWarnings({\"rawtypes\"})\n" + "@java.lang.Override\n" + "protected com.google.protobuf.MapField internalGetMapField(\n" + " int number) {\n" + " switch (number) {\n"); printer->Indent(); printer->Indent(); for (int i = 0; i < map_fields.size(); ++i) { const FieldDescriptor* field = map_fields[i]; const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); printer->Print( - "case $number$:\n" - " return internalGet$capitalized_name$();\n", - "number", SimpleItoa(field->number()), - "capitalized_name", info->capitalized_name); + "case $number$:\n" + " return internalGet$capitalized_name$();\n", + "number", StrCat(field->number()), "capitalized_name", + info->capitalized_name); } printer->Print( "default:\n" @@ -869,40 +840,38 @@ GenerateDescriptorMethods(io::Printer* printer) { "}\n"); } printer->Print( - "@java.lang.Override\n" - "protected com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n" - " internalGetFieldAccessorTable() {\n" - " return $fileclass$.internal_$identifier$_fieldAccessorTable\n" - " .ensureFieldAccessorsInitialized(\n" - " $classname$.class, $classname$.Builder.class);\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()), - "identifier", UniqueFileScopeIdentifier(descriptor_), - "ver", GeneratedCodeVersionSuffix()); + "@java.lang.Override\n" + "protected com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n" + " internalGetFieldAccessorTable() {\n" + " return $fileclass$.internal_$identifier$_fieldAccessorTable\n" + " .ensureFieldAccessorsInitialized(\n" + " $classname$.class, $classname$.Builder.class);\n" + "}\n" + "\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_), + "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()), + "identifier", UniqueFileScopeIdentifier(descriptor_), "ver", + GeneratedCodeVersionSuffix()); } // =================================================================== -void ImmutableMessageGenerator::GenerateIsInitialized( - io::Printer* printer) { +void ImmutableMessageGenerator::GenerateIsInitialized(io::Printer* printer) { // Memoizes whether the protocol buffer is fully initialized (has all // required fields). -1 means not yet computed. 0 means false and 1 means // true. + printer->Print("private byte memoizedIsInitialized = -1;\n"); printer->Print( - "private byte memoizedIsInitialized = -1;\n"); - printer->Print( - "@java.lang.Override\n" - "public final boolean isInitialized() {\n"); + "@java.lang.Override\n" + "public final boolean isInitialized() {\n"); printer->Indent(); // Don't directly compare to -1 to avoid an Android x86 JIT bug. printer->Print( - "byte isInitialized = memoizedIsInitialized;\n" - "if (isInitialized == 1) return true;\n" - "if (isInitialized == 0) return false;\n" - "\n"); + "byte isInitialized = memoizedIsInitialized;\n" + "if (isInitialized == 1) return true;\n" + "if (isInitialized == 0) return false;\n" + "\n"); // Check that all required fields in this message are set. // TODO(kenton): We can optimize this when we switch to putting all the @@ -913,11 +882,11 @@ void ImmutableMessageGenerator::GenerateIsInitialized( if (field->is_required()) { printer->Print( - "if (!has$name$()) {\n" - " memoizedIsInitialized = 0;\n" - " return false;\n" - "}\n", - "name", info->capitalized_name); + "if (!has$name$()) {\n" + " memoizedIsInitialized = 0;\n" + " return false;\n" + "}\n", + "name", info->capitalized_name); } } @@ -930,13 +899,13 @@ void ImmutableMessageGenerator::GenerateIsInitialized( switch (field->label()) { case FieldDescriptor::LABEL_REQUIRED: printer->Print( - "if (!get$name$().isInitialized()) {\n" - " memoizedIsInitialized = 0;\n" - " return false;\n" - "}\n", - "type", name_resolver_->GetImmutableClassName( - field->message_type()), - "name", info->capitalized_name); + "if (!get$name$().isInitialized()) {\n" + " memoizedIsInitialized = 0;\n" + " return false;\n" + "}\n", + "type", + name_resolver_->GetImmutableClassName(field->message_type()), + "name", info->capitalized_name); break; case FieldDescriptor::LABEL_OPTIONAL: if (!SupportFieldPresence(descriptor_->file()) && @@ -944,46 +913,45 @@ void ImmutableMessageGenerator::GenerateIsInitialized( const OneofDescriptor* oneof = field->containing_oneof(); const OneofGeneratorInfo* oneof_info = context_->GetOneofGeneratorInfo(oneof); - printer->Print( - "if ($oneof_name$Case_ == $field_number$) {\n", - "oneof_name", oneof_info->name, - "field_number", SimpleItoa(field->number())); + printer->Print("if ($oneof_name$Case_ == $field_number$) {\n", + "oneof_name", oneof_info->name, "field_number", + StrCat(field->number())); } else { - printer->Print( - "if (has$name$()) {\n", - "name", info->capitalized_name); + printer->Print("if (has$name$()) {\n", "name", + info->capitalized_name); } printer->Print( - " if (!get$name$().isInitialized()) {\n" - " memoizedIsInitialized = 0;\n" - " return false;\n" - " }\n" - "}\n", - "name", info->capitalized_name); + " if (!get$name$().isInitialized()) {\n" + " memoizedIsInitialized = 0;\n" + " return false;\n" + " }\n" + "}\n", + "name", info->capitalized_name); break; case FieldDescriptor::LABEL_REPEATED: if (IsMapEntry(field->message_type())) { printer->Print( - "for ($type$ item : get$name$Map().values()) {\n" - " if (!item.isInitialized()) {\n" - " memoizedIsInitialized = 0;\n" - " return false;\n" - " }\n" - "}\n", - "type", MapValueImmutableClassdName(field->message_type(), - name_resolver_), - "name", info->capitalized_name); + "for ($type$ item : get$name$Map().values()) {\n" + " if (!item.isInitialized()) {\n" + " memoizedIsInitialized = 0;\n" + " return false;\n" + " }\n" + "}\n", + "type", + MapValueImmutableClassdName(field->message_type(), + name_resolver_), + "name", info->capitalized_name); } else { printer->Print( - "for (int i = 0; i < get$name$Count(); i++) {\n" - " if (!get$name$(i).isInitialized()) {\n" - " memoizedIsInitialized = 0;\n" - " return false;\n" - " }\n" - "}\n", - "type", name_resolver_->GetImmutableClassName( - field->message_type()), - "name", info->capitalized_name); + "for (int i = 0; i < get$name$Count(); i++) {\n" + " if (!get$name$(i).isInitialized()) {\n" + " memoizedIsInitialized = 0;\n" + " return false;\n" + " }\n" + "}\n", + "type", + name_resolver_->GetImmutableClassName(field->message_type()), + "name", info->capitalized_name); } break; } @@ -992,21 +960,20 @@ void ImmutableMessageGenerator::GenerateIsInitialized( if (descriptor_->extension_range_count() > 0) { printer->Print( - "if (!extensionsAreInitialized()) {\n" - " memoizedIsInitialized = 0;\n" - " return false;\n" - "}\n"); + "if (!extensionsAreInitialized()) {\n" + " memoizedIsInitialized = 0;\n" + " return false;\n" + "}\n"); } printer->Outdent(); - printer->Print( - " memoizedIsInitialized = 1;\n"); + printer->Print(" memoizedIsInitialized = 1;\n"); printer->Print( - " return true;\n" - "}\n" - "\n"); + " return true;\n" + "}\n" + "\n"); } // =================================================================== @@ -1020,28 +987,27 @@ bool CheckHasBitsForEqualsAndHashCode(const FieldDescriptor* field) { return true; } return GetJavaType(field) == JAVATYPE_MESSAGE && - field->containing_oneof() == NULL; + field->containing_oneof() == NULL; } } // namespace -void ImmutableMessageGenerator:: -GenerateEqualsAndHashCode(io::Printer* printer) { +void ImmutableMessageGenerator::GenerateEqualsAndHashCode( + io::Printer* printer) { printer->Print( - "@java.lang.Override\n" - "public boolean equals(final java.lang.Object obj) {\n"); + "@java.lang.Override\n" + "public boolean equals(final java.lang.Object obj) {\n"); printer->Indent(); printer->Print( - "if (obj == this) {\n" - " return true;\n" - "}\n" - "if (!(obj instanceof $classname$)) {\n" - " return super.equals(obj);\n" - "}\n" - "$classname$ other = ($classname$) obj;\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + "if (obj == this) {\n" + " return true;\n" + "}\n" + "if (!(obj instanceof $classname$)) {\n" + " return super.equals(obj);\n" + "}\n" + "$classname$ other = ($classname$) obj;\n" + "\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); - printer->Print("boolean result = true;\n"); for (int i = 0; i < descriptor_->field_count(); i++) { const FieldDescriptor* field = descriptor_->field(i); if (field->containing_oneof() == NULL) { @@ -1049,16 +1015,15 @@ GenerateEqualsAndHashCode(io::Printer* printer) { bool check_has_bits = CheckHasBitsForEqualsAndHashCode(field); if (check_has_bits) { printer->Print( - "result = result && (has$name$() == other.has$name$());\n" - "if (has$name$()) {\n", - "name", info->capitalized_name); + "if (has$name$() != other.has$name$()) return false;\n" + "if (has$name$()) {\n", + "name", info->capitalized_name); printer->Indent(); } field_generators_.get(field).GenerateEqualsCode(printer); if (check_has_bits) { printer->Outdent(); - printer->Print( - "}\n"); + printer->Print("}\n"); } } } @@ -1066,32 +1031,27 @@ GenerateEqualsAndHashCode(io::Printer* printer) { // Compare oneofs. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { printer->Print( - "result = result && get$oneof_capitalized_name$Case().equals(\n" - " other.get$oneof_capitalized_name$Case());\n", - "oneof_capitalized_name", - context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->capitalized_name); + "if (!get$oneof_capitalized_name$Case().equals(" + "other.get$oneof_capitalized_name$Case())) return false;\n", + "oneof_capitalized_name", + context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i)) + ->capitalized_name); printer->Print( - "if (!result) return false;\n" - "switch ($oneof_name$Case_) {\n", - "oneof_name", - context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name); + "switch ($oneof_name$Case_) {\n", "oneof_name", + context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))->name); printer->Indent(); for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print( - "case $field_number$:\n", - "field_number", - SimpleItoa(field->number())); + printer->Print("case $field_number$:\n", "field_number", + StrCat(field->number())); printer->Indent(); field_generators_.get(field).GenerateEqualsCode(printer); printer->Print("break;\n"); printer->Outdent(); } printer->Print( - "case 0:\n" - "default:\n"); + "case 0:\n" + "default:\n"); printer->Outdent(); printer->Print("}\n"); } @@ -1100,32 +1060,29 @@ GenerateEqualsAndHashCode(io::Printer* printer) { // false for non-canonical ordering when running in LITE_RUNTIME but it's // the best we can do. printer->Print( - "result = result && unknownFields.equals(other.unknownFields);\n"); + "if (!unknownFields.equals(other.unknownFields)) return false;\n"); if (descriptor_->extension_range_count() > 0) { printer->Print( - "result = result &&\n" - " getExtensionFields().equals(other.getExtensionFields());\n"); + "if (!getExtensionFields().equals(other.getExtensionFields()))\n" + " return false;\n"); } - printer->Print( - "return result;\n"); + printer->Print("return true;\n"); printer->Outdent(); printer->Print( - "}\n" - "\n"); + "}\n" + "\n"); printer->Print( - "@java.lang.Override\n" - "public int hashCode() {\n"); + "@java.lang.Override\n" + "public int hashCode() {\n"); printer->Indent(); - printer->Print( - "if (memoizedHashCode != 0) {\n"); + printer->Print("if (memoizedHashCode != 0) {\n"); printer->Indent(); - printer->Print( - "return memoizedHashCode;\n"); + printer->Print("return memoizedHashCode;\n"); printer->Outdent(); printer->Print( - "}\n" - "int hash = 41;\n"); + "}\n" + "int hash = 41;\n"); // If we output a getDescriptor() method, use that as it is more efficient. if (descriptor_->options().no_standard_descriptor_accessor()) { @@ -1141,9 +1098,7 @@ GenerateEqualsAndHashCode(io::Printer* printer) { const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); bool check_has_bits = CheckHasBitsForEqualsAndHashCode(field); if (check_has_bits) { - printer->Print( - "if (has$name$()) {\n", - "name", info->capitalized_name); + printer->Print("if (has$name$()) {\n", "name", info->capitalized_name); printer->Indent(); } field_generators_.get(field).GenerateHashCode(printer); @@ -1157,64 +1112,58 @@ GenerateEqualsAndHashCode(io::Printer* printer) { // hashCode oneofs. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { printer->Print( - "switch ($oneof_name$Case_) {\n", - "oneof_name", - context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name); + "switch ($oneof_name$Case_) {\n", "oneof_name", + context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))->name); printer->Indent(); for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print( - "case $field_number$:\n", - "field_number", - SimpleItoa(field->number())); + printer->Print("case $field_number$:\n", "field_number", + StrCat(field->number())); printer->Indent(); field_generators_.get(field).GenerateHashCode(printer); printer->Print("break;\n"); printer->Outdent(); } printer->Print( - "case 0:\n" - "default:\n"); + "case 0:\n" + "default:\n"); printer->Outdent(); printer->Print("}\n"); } if (descriptor_->extension_range_count() > 0) { - printer->Print( - "hash = hashFields(hash, getExtensionFields());\n"); + printer->Print("hash = hashFields(hash, getExtensionFields());\n"); } + printer->Print("hash = (29 * hash) + unknownFields.hashCode();\n"); printer->Print( - "hash = (29 * hash) + unknownFields.hashCode();\n"); - printer->Print( - "memoizedHashCode = hash;\n" - "return hash;\n"); + "memoizedHashCode = hash;\n" + "return hash;\n"); printer->Outdent(); printer->Print( - "}\n" - "\n"); + "}\n" + "\n"); } // =================================================================== -void ImmutableMessageGenerator:: -GenerateExtensionRegistrationCode(io::Printer* printer) { +void ImmutableMessageGenerator::GenerateExtensionRegistrationCode( + io::Printer* printer) { for (int i = 0; i < descriptor_->extension_count(); i++) { ImmutableExtensionGenerator(descriptor_->extension(i), context_) - .GenerateRegistrationCode(printer); + .GenerateRegistrationCode(printer); } for (int i = 0; i < descriptor_->nested_type_count(); i++) { ImmutableMessageGenerator(descriptor_->nested_type(i), context_) - .GenerateExtensionRegistrationCode(printer); + .GenerateExtensionRegistrationCode(printer); } } // =================================================================== -void ImmutableMessageGenerator:: -GenerateParsingConstructor(io::Printer* printer) { - std::unique_ptr sorted_fields( +void ImmutableMessageGenerator::GenerateParsingConstructor( + io::Printer* printer) { + std::unique_ptr sorted_fields( SortFieldsByNumber(descriptor_)); printer->Print( @@ -1241,26 +1190,25 @@ GenerateParsingConstructor(io::Printer* printer) { } int totalBuilderInts = (totalBuilderBits + 31) / 32; for (int i = 0; i < totalBuilderInts; i++) { - printer->Print("int mutable_$bit_field_name$ = 0;\n", - "bit_field_name", GetBitFieldName(i)); + printer->Print("int mutable_$bit_field_name$ = 0;\n", "bit_field_name", + GetBitFieldName(i)); } printer->Print( "com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n" " com.google.protobuf.UnknownFieldSet.newBuilder();\n"); - printer->Print( - "try {\n"); + printer->Print("try {\n"); printer->Indent(); printer->Print( - "boolean done = false;\n" - "while (!done) {\n"); + "boolean done = false;\n" + "while (!done) {\n"); printer->Indent(); printer->Print( - "int tag = input.readTag();\n" - "switch (tag) {\n"); + "int tag = input.readTag();\n" + "switch (tag) {\n"); printer->Indent(); printer->Print( @@ -1270,57 +1218,52 @@ GenerateParsingConstructor(io::Printer* printer) { for (int i = 0; i < descriptor_->field_count(); i++) { const FieldDescriptor* field = sorted_fields[i]; - uint32 tag = WireFormatLite::MakeTag(field->number(), - WireFormat::WireTypeForFieldType(field->type())); + uint32 tag = WireFormatLite::MakeTag( + field->number(), WireFormat::WireTypeForFieldType(field->type())); - printer->Print( - "case $tag$: {\n", - "tag", SimpleItoa(static_cast(tag))); + printer->Print("case $tag$: {\n", "tag", + StrCat(static_cast(tag))); printer->Indent(); field_generators_.get(field).GenerateParsingCode(printer); printer->Outdent(); printer->Print( - " break;\n" - "}\n"); + " break;\n" + "}\n"); if (field->is_packable()) { // To make packed = true wire compatible, we generate parsing code from a // packed version of this field regardless of field->options().packed(). - uint32 packed_tag = WireFormatLite::MakeTag(field->number(), - WireFormatLite::WIRETYPE_LENGTH_DELIMITED); - printer->Print( - "case $tag$: {\n", - "tag", SimpleItoa(static_cast(packed_tag))); + uint32 packed_tag = WireFormatLite::MakeTag( + field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED); + printer->Print("case $tag$: {\n", "tag", + StrCat(static_cast(packed_tag))); printer->Indent(); field_generators_.get(field).GenerateParsingCodeFromPacked(printer); printer->Outdent(); printer->Print( - " break;\n" - "}\n"); + " break;\n" + "}\n"); } } printer->Print( "default: {\n" - " if (!parseUnknownField$suffix$(\n" + " if (!parseUnknownField(\n" " input, unknownFields, extensionRegistry, tag)) {\n" " done = true;\n" // it's an endgroup tag " }\n" " break;\n" - "}\n", - "suffix", - descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 ? "Proto3" - : ""); + "}\n"); printer->Outdent(); printer->Outdent(); printer->Print( - " }\n" // switch (tag) - "}\n"); // while (!done) + " }\n" // switch (tag) + "}\n"); // while (!done) printer->Outdent(); printer->Print( @@ -1342,13 +1285,12 @@ GenerateParsingConstructor(io::Printer* printer) { printer->Print("this.unknownFields = unknownFields.build();\n"); // Make extensions immutable. - printer->Print( - "makeExtensionsImmutable();\n"); + printer->Print("makeExtensionsImmutable();\n"); printer->Outdent(); printer->Outdent(); printer->Print( - " }\n" // finally + " }\n" // finally "}\n"); } @@ -1369,16 +1311,7 @@ void ImmutableMessageGenerator::GenerateParser(io::Printer* printer) { " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" " throws com.google.protobuf.InvalidProtocolBufferException {\n", "classname", descriptor_->name()); - if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) { - printer->Indent(); - printer->Print( - "$classname$ msg = new $classname$();\n" - "msg.mergeFromInternal(input, extensionRegistry);\n" - "msg.makeImmutableInternal();\n" - "return msg;\n", - "classname", descriptor_->name()); - printer->Outdent(); - } else if (context_->HasGeneratedMethods(descriptor_)) { + if (context_->HasGeneratedMethods(descriptor_)) { printer->Print(" return new $classname$(input, extensionRegistry);\n", "classname", descriptor_->name()); } else { @@ -1400,8 +1333,7 @@ void ImmutableMessageGenerator::GenerateParser(io::Printer* printer) { "return builder.buildPartial();\n"); printer->Outdent(); } - printer->Print( - "}\n"); + printer->Print("}\n"); printer->Outdent(); printer->Print( "};\n" @@ -1433,72 +1365,76 @@ void ImmutableMessageGenerator::GenerateInitializers(io::Printer* printer) { void ImmutableMessageGenerator::GenerateAnyMethods(io::Printer* printer) { printer->Print( - "private static String getTypeUrl(\n" - " java.lang.String typeUrlPrefix,\n" - " com.google.protobuf.Descriptors.Descriptor descriptor) {\n" - " return typeUrlPrefix.endsWith(\"/\")\n" - " ? typeUrlPrefix + descriptor.getFullName()\n" - " : typeUrlPrefix + \"/\" + descriptor.getFullName();\n" - "}\n" - "\n" - "private static String getTypeNameFromTypeUrl(\n" - " java.lang.String typeUrl) {\n" - " int pos = typeUrl.lastIndexOf('/');\n" - " return pos == -1 ? \"\" : typeUrl.substring(pos + 1);\n" - "}\n" - "\n" - "public static Any pack(\n" - " T message) {\n" - " return Any.newBuilder()\n" - " .setTypeUrl(getTypeUrl(\"type.googleapis.com\",\n" - " message.getDescriptorForType()))\n" - " .setValue(message.toByteString())\n" - " .build();\n" - "}\n" - "\n" - "/**\n" - " * Packs a message using the given type URL prefix. The type URL will\n" - " * be constructed by concatenating the message type's full name to the\n" - " * prefix with an optional \"/\" separator if the prefix doesn't end\n" - " * with \"/\" already.\n" - " */\n" - "public static Any pack(\n" - " T message, java.lang.String typeUrlPrefix) {\n" - " return Any.newBuilder()\n" - " .setTypeUrl(getTypeUrl(typeUrlPrefix,\n" - " message.getDescriptorForType()))\n" - " .setValue(message.toByteString())\n" - " .build();\n" - "}\n" - "\n" - "public boolean is(\n" - " java.lang.Class clazz) {\n" - " T defaultInstance =\n" - " com.google.protobuf.Internal.getDefaultInstance(clazz);\n" - " return getTypeNameFromTypeUrl(getTypeUrl()).equals(\n" - " defaultInstance.getDescriptorForType().getFullName());\n" - "}\n" - "\n" - "private volatile com.google.protobuf.Message cachedUnpackValue;\n" - "\n" - "@java.lang.SuppressWarnings(\"unchecked\")\n" - "public T unpack(\n" - " java.lang.Class clazz)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " if (!is(clazz)) {\n" - " throw new com.google.protobuf.InvalidProtocolBufferException(\n" - " \"Type of the Any message does not match the given class.\");\n" - " }\n" - " if (cachedUnpackValue != null) {\n" - " return (T) cachedUnpackValue;\n" - " }\n" - " T defaultInstance =\n" - " com.google.protobuf.Internal.getDefaultInstance(clazz);\n" - " T result = (T) defaultInstance.getParserForType()\n" - " .parseFrom(getValue());\n" - " cachedUnpackValue = result;\n" - " return result;\n" - "}\n"); + "private static String getTypeUrl(\n" + " java.lang.String typeUrlPrefix,\n" + " com.google.protobuf.Descriptors.Descriptor descriptor) {\n" + " return typeUrlPrefix.endsWith(\"/\")\n" + " ? typeUrlPrefix + descriptor.getFullName()\n" + " : typeUrlPrefix + \"/\" + descriptor.getFullName();\n" + "}\n" + "\n" + "private static String getTypeNameFromTypeUrl(\n" + " java.lang.String typeUrl) {\n" + " int pos = typeUrl.lastIndexOf('/');\n" + " return pos == -1 ? \"\" : typeUrl.substring(pos + 1);\n" + "}\n" + "\n" + "public static Any pack(\n" + " T message) {\n" + " return Any.newBuilder()\n" + " .setTypeUrl(getTypeUrl(\"type.googleapis.com\",\n" + " message.getDescriptorForType()))\n" + " .setValue(message.toByteString())\n" + " .build();\n" + "}\n" + "\n" + "/**\n" + " * Packs a message using the given type URL prefix. The type URL will\n" + " * be constructed by concatenating the message type's full name to the\n" + " * prefix with an optional \"/\" separator if the prefix doesn't end\n" + " * with \"/\" already.\n" + " */\n" + "public static Any pack(\n" + " T message, java.lang.String typeUrlPrefix) {\n" + " return Any.newBuilder()\n" + " .setTypeUrl(getTypeUrl(typeUrlPrefix,\n" + " message.getDescriptorForType()))\n" + " .setValue(message.toByteString())\n" + " .build();\n" + "}\n" + "\n" + "public boolean is(\n" + " java.lang.Class clazz) {\n" + " T defaultInstance =\n" + " com.google.protobuf.Internal.getDefaultInstance(clazz);\n" + " return getTypeNameFromTypeUrl(getTypeUrl()).equals(\n" + " defaultInstance.getDescriptorForType().getFullName());\n" + "}\n" + "\n" + "private volatile com.google.protobuf.Message cachedUnpackValue;\n" + "\n" + "@java.lang.SuppressWarnings(\"unchecked\")\n" + "public T unpack(\n" + " java.lang.Class clazz)\n" + " throws com.google.protobuf.InvalidProtocolBufferException {\n" + " boolean invalidClazz = false;\n" + " if (cachedUnpackValue != null) {\n" + " if (cachedUnpackValue.getClass() == clazz) {\n" + " return (T) cachedUnpackValue;\n" + " }\n" + " invalidClazz = true;\n" + " }\n" + " if (invalidClazz || !is(clazz)) {\n" + " throw new com.google.protobuf.InvalidProtocolBufferException(\n" + " \"Type of the Any message does not match the given class.\");\n" + " }\n" + " T defaultInstance =\n" + " com.google.protobuf.Internal.getDefaultInstance(clazz);\n" + " T result = (T) defaultInstance.getParserForType()\n" + " .parseFrom(getValue());\n" + " cachedUnpackValue = result;\n" + " return result;\n" + "}\n"); } } // namespace java diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_message.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_message.h index da1447c1..de2f359a 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_message.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_message.h @@ -35,23 +35,25 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_H__ #define GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_H__ -#include #include +#include #include namespace google { namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +namespace io { +class Printer; // printer.h } +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { @@ -66,8 +68,8 @@ class MessageGenerator { // All static variables have to be declared at the top-level of the file // so that we can control initialization order, which is important for // DescriptorProto bootstrapping to work. - virtual void GenerateStaticVariables( - io::Printer* printer, int* bytecode_estimate) = 0; + virtual void GenerateStaticVariables(io::Printer* printer, + int* bytecode_estimate) = 0; // Output code which initializes the static variables generated by // GenerateStaticVariables(). Returns an estimate of bytecode size. @@ -76,7 +78,8 @@ class MessageGenerator { // Generate the class itself. virtual void Generate(io::Printer* printer) = 0; - // Generates the base interface that both the class and its builder implement + // Generates the base interface that both the class and its builder + // implement virtual void GenerateInterface(io::Printer* printer) = 0; // Generate code to register all contained extensions with an @@ -98,14 +101,13 @@ class ImmutableMessageGenerator : public MessageGenerator { virtual void Generate(io::Printer* printer); virtual void GenerateInterface(io::Printer* printer); virtual void GenerateExtensionRegistrationCode(io::Printer* printer); - virtual void GenerateStaticVariables( - io::Printer* printer, int* bytecode_estimate); + virtual void GenerateStaticVariables(io::Printer* printer, + int* bytecode_estimate); // Returns an estimate of the number of bytes the printed code will compile to virtual int GenerateStaticVariableInitializers(io::Printer* printer); private: - void GenerateFieldAccessorTable(io::Printer* printer, int* bytecode_estimate); // Returns an estimate of the number of bytes the printed code will compile to @@ -137,6 +139,6 @@ class ImmutableMessageGenerator : public MessageGenerator { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_builder.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_builder.cc index 4c67e806..aa00a66f 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_builder.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_builder.cc @@ -35,7 +35,6 @@ #include #include -#include #include #include #include @@ -51,8 +50,9 @@ #include #include #include -#include #include +#include + namespace google { @@ -61,24 +61,20 @@ namespace compiler { namespace java { namespace { -bool GenerateHasBits(const Descriptor* descriptor) { - return SupportFieldPresence(descriptor->file()) || - HasRepeatedFields(descriptor); -} - -string MapValueImmutableClassdName(const Descriptor* descriptor, - ClassNameResolver* name_resolver) { +std::string MapValueImmutableClassdName(const Descriptor* descriptor, + ClassNameResolver* name_resolver) { const FieldDescriptor* value_field = descriptor->FindFieldByName("value"); GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, value_field->type()); return name_resolver->GetImmutableClassName(value_field->message_type()); } } // namespace -MessageBuilderGenerator::MessageBuilderGenerator( - const Descriptor* descriptor, Context* context) - : descriptor_(descriptor), context_(context), - name_resolver_(context->GetNameResolver()), - field_generators_(descriptor, context_) { +MessageBuilderGenerator::MessageBuilderGenerator(const Descriptor* descriptor, + Context* context) + : descriptor_(descriptor), + context_(context), + name_resolver_(context->GetNameResolver()), + field_generators_(descriptor, context_) { GOOGLE_CHECK(HasDescriptorMethods(descriptor->file(), context->EnforceLite())) << "Generator factory error: A non-lite message generator is used to " "generate lite messages."; @@ -86,28 +82,28 @@ MessageBuilderGenerator::MessageBuilderGenerator( MessageBuilderGenerator::~MessageBuilderGenerator() {} -void MessageBuilderGenerator:: -Generate(io::Printer* printer) { +void MessageBuilderGenerator::Generate(io::Printer* printer) { WriteMessageDocComment(printer, descriptor_); if (descriptor_->extension_range_count() > 0) { printer->Print( - "public static final class Builder extends\n" - " com.google.protobuf.GeneratedMessage$ver$.ExtendableBuilder<\n" - " $classname$, Builder> implements\n" - " $extra_interfaces$\n" - " $classname$OrBuilder {\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "extra_interfaces", ExtraBuilderInterfaces(descriptor_), - "ver", GeneratedCodeVersionSuffix()); + "public static final class Builder extends\n" + " com.google.protobuf.GeneratedMessage$ver$.ExtendableBuilder<\n" + " $classname$, Builder> implements\n" + " $extra_interfaces$\n" + " $classname$OrBuilder {\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_), + "extra_interfaces", ExtraBuilderInterfaces(descriptor_), "ver", + GeneratedCodeVersionSuffix()); } else { printer->Print( - "public static final class Builder extends\n" - " com.google.protobuf.GeneratedMessage$ver$.Builder implements\n" - " $extra_interfaces$\n" - " $classname$OrBuilder {\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "extra_interfaces", ExtraBuilderInterfaces(descriptor_), - "ver", GeneratedCodeVersionSuffix()); + "public static final class Builder extends\n" + " com.google.protobuf.GeneratedMessage$ver$.Builder " + "implements\n" + " $extra_interfaces$\n" + " $classname$OrBuilder {\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_), + "extra_interfaces", ExtraBuilderInterfaces(descriptor_), "ver", + GeneratedCodeVersionSuffix()); } printer->Indent(); @@ -120,81 +116,77 @@ Generate(io::Printer* printer) { } // oneof - std::map vars; + std::map vars; for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - vars["oneof_name"] = context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name; - vars["oneof_capitalized_name"] = context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->capitalized_name; - vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index()); + vars["oneof_name"] = + context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))->name; + vars["oneof_capitalized_name"] = + context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i)) + ->capitalized_name; + vars["oneof_index"] = StrCat(descriptor_->oneof_decl(i)->index()); // oneofCase_ and oneof_ printer->Print(vars, - "private int $oneof_name$Case_ = 0;\n" - "private java.lang.Object $oneof_name$_;\n"); + "private int $oneof_name$Case_ = 0;\n" + "private java.lang.Object $oneof_name$_;\n"); // oneofCase() and clearOneof() printer->Print(vars, - "public $oneof_capitalized_name$Case\n" - " get$oneof_capitalized_name$Case() {\n" - " return $oneof_capitalized_name$Case.forNumber(\n" - " $oneof_name$Case_);\n" - "}\n" - "\n" - "public Builder clear$oneof_capitalized_name$() {\n" - " $oneof_name$Case_ = 0;\n" - " $oneof_name$_ = null;\n"); + "public $oneof_capitalized_name$Case\n" + " get$oneof_capitalized_name$Case() {\n" + " return $oneof_capitalized_name$Case.forNumber(\n" + " $oneof_name$Case_);\n" + "}\n" + "\n" + "public Builder clear$oneof_capitalized_name$() {\n" + " $oneof_name$Case_ = 0;\n" + " $oneof_name$_ = null;\n"); printer->Print(" onChanged();\n"); printer->Print( - " return this;\n" - "}\n" - "\n"); + " return this;\n" + "}\n" + "\n"); } - if (GenerateHasBits(descriptor_)) { - // Integers for bit fields. - int totalBits = 0; - for (int i = 0; i < descriptor_->field_count(); i++) { - totalBits += field_generators_.get(descriptor_->field(i)) - .GetNumBitsForBuilder(); - } - int totalInts = (totalBits + 31) / 32; - for (int i = 0; i < totalInts; i++) { - printer->Print("private int $bit_field_name$;\n", - "bit_field_name", GetBitFieldName(i)); - } + // Integers for bit fields. + int totalBits = 0; + for (int i = 0; i < descriptor_->field_count(); i++) { + totalBits += + field_generators_.get(descriptor_->field(i)).GetNumBitsForBuilder(); + } + int totalInts = (totalBits + 31) / 32; + for (int i = 0; i < totalInts; i++) { + printer->Print("private int $bit_field_name$;\n", "bit_field_name", + GetBitFieldName(i)); } for (int i = 0; i < descriptor_->field_count(); i++) { printer->Print("\n"); field_generators_.get(descriptor_->field(i)) - .GenerateBuilderMembers(printer); + .GenerateBuilderMembers(printer); } - bool is_proto3 = - descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3; - // Override methods declared in GeneratedMessage to return the concrete - // generated type so callsites won't depend on GeneratedMessage. This - // is needed to keep binary compatibility when we change generated code - // to subclass a different GeneratedMessage class (e.g., in v3.0.0 release - // we changed all generated code to subclass GeneratedMessageV3). + // Override methods declared in GeneratedMessage to return the concrete + // generated type so callsites won't depend on GeneratedMessage. This + // is needed to keep binary compatibility when we change generated code + // to subclass a different GeneratedMessage class (e.g., in v3.0.0 release + // we changed all generated code to subclass GeneratedMessageV3). printer->Print( - "@java.lang.Override\n" - "public final Builder setUnknownFields(\n" - " final com.google.protobuf.UnknownFieldSet unknownFields) {\n" - " return super.setUnknownFields$suffix$(unknownFields);\n" - "}\n" - "\n" - "@java.lang.Override\n" - "public final Builder mergeUnknownFields(\n" - " final com.google.protobuf.UnknownFieldSet unknownFields) {\n" - " return super.mergeUnknownFields(unknownFields);\n" - "}\n" - "\n", - "suffix", is_proto3 ? "Proto3" : ""); + "@java.lang.Override\n" + "public final Builder setUnknownFields(\n" + " final com.google.protobuf.UnknownFieldSet unknownFields) {\n" + " return super.setUnknownFields(unknownFields);\n" + "}\n" + "\n" + "@java.lang.Override\n" + "public final Builder mergeUnknownFields(\n" + " final com.google.protobuf.UnknownFieldSet unknownFields) {\n" + " return super.mergeUnknownFields(unknownFields);\n" + "}\n" + "\n"); printer->Print( - "\n" - "// @@protoc_insertion_point(builder_scope:$full_name$)\n", - "full_name", descriptor_->full_name()); + "\n" + "// @@protoc_insertion_point(builder_scope:$full_name$)\n", + "full_name", descriptor_->full_name()); printer->Outdent(); printer->Print("}\n"); @@ -202,17 +194,16 @@ Generate(io::Printer* printer) { // =================================================================== -void MessageBuilderGenerator:: -GenerateDescriptorMethods(io::Printer* printer) { +void MessageBuilderGenerator::GenerateDescriptorMethods(io::Printer* printer) { if (!descriptor_->options().no_standard_descriptor_accessor()) { printer->Print( - "public static final com.google.protobuf.Descriptors.Descriptor\n" - " getDescriptor() {\n" - " return $fileclass$.internal_$identifier$_descriptor;\n" - "}\n" - "\n", - "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()), - "identifier", UniqueFileScopeIdentifier(descriptor_)); + "public static final com.google.protobuf.Descriptors.Descriptor\n" + " getDescriptor() {\n" + " return $fileclass$.internal_$identifier$_descriptor;\n" + "}\n" + "\n", + "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()), + "identifier", UniqueFileScopeIdentifier(descriptor_)); } std::vector map_fields; for (int i = 0; i < descriptor_->field_count(); i++) { @@ -224,20 +215,20 @@ GenerateDescriptorMethods(io::Printer* printer) { } if (!map_fields.empty()) { printer->Print( - "@SuppressWarnings({\"rawtypes\"})\n" - "protected com.google.protobuf.MapField internalGetMapField(\n" - " int number) {\n" - " switch (number) {\n"); + "@SuppressWarnings({\"rawtypes\"})\n" + "protected com.google.protobuf.MapField internalGetMapField(\n" + " int number) {\n" + " switch (number) {\n"); printer->Indent(); printer->Indent(); for (int i = 0; i < map_fields.size(); ++i) { const FieldDescriptor* field = map_fields[i]; const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); printer->Print( - "case $number$:\n" - " return internalGet$capitalized_name$();\n", - "number", SimpleItoa(field->number()), - "capitalized_name", info->capitalized_name); + "case $number$:\n" + " return internalGet$capitalized_name$();\n", + "number", StrCat(field->number()), "capitalized_name", + info->capitalized_name); } printer->Print( "default:\n" @@ -249,21 +240,20 @@ GenerateDescriptorMethods(io::Printer* printer) { " }\n" "}\n"); printer->Print( - "@SuppressWarnings({\"rawtypes\"})\n" - "protected com.google.protobuf.MapField internalGetMutableMapField(\n" - " int number) {\n" - " switch (number) {\n"); + "@SuppressWarnings({\"rawtypes\"})\n" + "protected com.google.protobuf.MapField internalGetMutableMapField(\n" + " int number) {\n" + " switch (number) {\n"); printer->Indent(); printer->Indent(); for (int i = 0; i < map_fields.size(); ++i) { const FieldDescriptor* field = map_fields[i]; - const FieldGeneratorInfo* info = - context_->GetFieldGeneratorInfo(field); + const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); printer->Print( - "case $number$:\n" - " return internalGetMutable$capitalized_name$();\n", - "number", SimpleItoa(field->number()), - "capitalized_name", info->capitalized_name); + "case $number$:\n" + " return internalGetMutable$capitalized_name$();\n", + "number", StrCat(field->number()), "capitalized_name", + info->capitalized_name); } printer->Print( "default:\n" @@ -276,24 +266,24 @@ GenerateDescriptorMethods(io::Printer* printer) { "}\n"); } printer->Print( - "@java.lang.Override\n" - "protected com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n" - " internalGetFieldAccessorTable() {\n" - " return $fileclass$.internal_$identifier$_fieldAccessorTable\n" - " .ensureFieldAccessorsInitialized(\n" - " $classname$.class, $classname$.Builder.class);\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()), - "identifier", UniqueFileScopeIdentifier(descriptor_), - "ver", GeneratedCodeVersionSuffix()); + "@java.lang.Override\n" + "protected com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n" + " internalGetFieldAccessorTable() {\n" + " return $fileclass$.internal_$identifier$_fieldAccessorTable\n" + " .ensureFieldAccessorsInitialized(\n" + " $classname$.class, $classname$.Builder.class);\n" + "}\n" + "\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_), + "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()), + "identifier", UniqueFileScopeIdentifier(descriptor_), "ver", + GeneratedCodeVersionSuffix()); } // =================================================================== -void MessageBuilderGenerator:: -GenerateCommonBuilderMethods(io::Printer* printer) { +void MessageBuilderGenerator::GenerateCommonBuilderMethods( + io::Printer* printer) { printer->Print( "// Construct using $classname$.newBuilder()\n" "private Builder() {\n" @@ -303,19 +293,19 @@ GenerateCommonBuilderMethods(io::Printer* printer) { "classname", name_resolver_->GetImmutableClassName(descriptor_)); printer->Print( - "private Builder(\n" - " com.google.protobuf.GeneratedMessage$ver$.BuilderParent parent) {\n" - " super(parent);\n" - " maybeForceBuilderInitialization();\n" - "}\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "ver", GeneratedCodeVersionSuffix()); + "private Builder(\n" + " com.google.protobuf.GeneratedMessage$ver$.BuilderParent parent) {\n" + " super(parent);\n" + " maybeForceBuilderInitialization();\n" + "}\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_), "ver", + GeneratedCodeVersionSuffix()); printer->Print( - "private void maybeForceBuilderInitialization() {\n" - " if (com.google.protobuf.GeneratedMessage$ver$\n" - " .alwaysUseFieldBuilders) {\n", - "ver", GeneratedCodeVersionSuffix()); + "private void maybeForceBuilderInitialization() {\n" + " if (com.google.protobuf.GeneratedMessage$ver$\n" + " .alwaysUseFieldBuilders) {\n", + "ver", GeneratedCodeVersionSuffix()); printer->Indent(); printer->Indent(); @@ -329,13 +319,13 @@ GenerateCommonBuilderMethods(io::Printer* printer) { printer->Outdent(); printer->Print( - " }\n" - "}\n"); + " }\n" + "}\n"); printer->Print( - "@java.lang.Override\n" - "public Builder clear() {\n" - " super.clear();\n"); + "@java.lang.Override\n" + "public Builder clear() {\n" + " super.clear();\n"); printer->Indent(); @@ -348,55 +338,55 @@ GenerateCommonBuilderMethods(io::Printer* printer) { for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { printer->Print( - "$oneof_name$Case_ = 0;\n" - "$oneof_name$_ = null;\n", - "oneof_name", context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name); + "$oneof_name$Case_ = 0;\n" + "$oneof_name$_ = null;\n", + "oneof_name", + context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))->name); } printer->Outdent(); printer->Print( - " return this;\n" - "}\n" - "\n"); + " return this;\n" + "}\n" + "\n"); printer->Print( - "@java.lang.Override\n" - "public com.google.protobuf.Descriptors.Descriptor\n" - " getDescriptorForType() {\n" - " return $fileclass$.internal_$identifier$_descriptor;\n" - "}\n" - "\n", - "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()), - "identifier", UniqueFileScopeIdentifier(descriptor_)); + "@java.lang.Override\n" + "public com.google.protobuf.Descriptors.Descriptor\n" + " getDescriptorForType() {\n" + " return $fileclass$.internal_$identifier$_descriptor;\n" + "}\n" + "\n", + "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()), + "identifier", UniqueFileScopeIdentifier(descriptor_)); // LITE runtime implements this in GeneratedMessageLite. printer->Print( - "@java.lang.Override\n" - "public $classname$ getDefaultInstanceForType() {\n" - " return $classname$.getDefaultInstance();\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + "@java.lang.Override\n" + "public $classname$ getDefaultInstanceForType() {\n" + " return $classname$.getDefaultInstance();\n" + "}\n" + "\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); printer->Print( - "@java.lang.Override\n" - "public $classname$ build() {\n" - " $classname$ result = buildPartial();\n" - " if (!result.isInitialized()) {\n" - " throw newUninitializedMessageException(result);\n" - " }\n" - " return result;\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + "@java.lang.Override\n" + "public $classname$ build() {\n" + " $classname$ result = buildPartial();\n" + " if (!result.isInitialized()) {\n" + " throw newUninitializedMessageException(result);\n" + " }\n" + " return result;\n" + "}\n" + "\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); printer->Print( - "@java.lang.Override\n" - "public $classname$ buildPartial() {\n" - " $classname$ result = new $classname$(this);\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + "@java.lang.Override\n" + "public $classname$ buildPartial() {\n" + " $classname$ result = new $classname$(this);\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); printer->Indent(); @@ -411,19 +401,17 @@ GenerateCommonBuilderMethods(io::Printer* printer) { int totalBuilderInts = (totalBuilderBits + 31) / 32; int totalMessageInts = (totalMessageBits + 31) / 32; - if (GenerateHasBits(descriptor_)) { - // Local vars for from and to bit fields to avoid accessing the builder and - // message over and over for these fields. Seems to provide a slight - // perforamance improvement in micro benchmark and this is also what proto1 - // code does. - for (int i = 0; i < totalBuilderInts; i++) { - printer->Print("int from_$bit_field_name$ = $bit_field_name$;\n", - "bit_field_name", GetBitFieldName(i)); - } - for (int i = 0; i < totalMessageInts; i++) { - printer->Print("int to_$bit_field_name$ = 0;\n", - "bit_field_name", GetBitFieldName(i)); - } + // Local vars for from and to bit fields to avoid accessing the builder and + // message over and over for these fields. Seems to provide a slight + // perforamance improvement in micro benchmark and this is also what proto1 + // code does. + for (int i = 0; i < totalBuilderInts; i++) { + printer->Print("int from_$bit_field_name$ = $bit_field_name$;\n", + "bit_field_name", GetBitFieldName(i)); + } + for (int i = 0; i < totalMessageInts; i++) { + printer->Print("int to_$bit_field_name$ = 0;\n", "bit_field_name", + GetBitFieldName(i)); } // Output generation code for each field. @@ -431,30 +419,27 @@ GenerateCommonBuilderMethods(io::Printer* printer) { field_generators_.get(descriptor_->field(i)).GenerateBuildingCode(printer); } - if (GenerateHasBits(descriptor_)) { - // Copy the bit field results to the generated message - for (int i = 0; i < totalMessageInts; i++) { - printer->Print("result.$bit_field_name$ = to_$bit_field_name$;\n", - "bit_field_name", GetBitFieldName(i)); - } + // Copy the bit field results to the generated message + for (int i = 0; i < totalMessageInts; i++) { + printer->Print("result.$bit_field_name$ = to_$bit_field_name$;\n", + "bit_field_name", GetBitFieldName(i)); } for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print("result.$oneof_name$Case_ = $oneof_name$Case_;\n", - "oneof_name", context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name); + printer->Print( + "result.$oneof_name$Case_ = $oneof_name$Case_;\n", "oneof_name", + context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))->name); } printer->Outdent(); - printer->Print( - " onBuilt();\n"); + printer->Print(" onBuilt();\n"); printer->Print( - " return result;\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + " return result;\n" + "}\n" + "\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); // Override methods declared in GeneratedMessage to return the concrete // generated type so callsites won't depend on GeneratedMessage. This @@ -462,190 +447,181 @@ GenerateCommonBuilderMethods(io::Printer* printer) { // to subclass a different GeneratedMessage class (e.g., in v3.0.0 release // we changed all generated code to subclass GeneratedMessageV3). printer->Print( - "@java.lang.Override\n" - "public Builder clone() {\n" - " return (Builder) super.clone();\n" - "}\n" - "@java.lang.Override\n" - "public Builder setField(\n" - " com.google.protobuf.Descriptors.FieldDescriptor field,\n" - " java.lang.Object value) {\n" - " return (Builder) super.setField(field, value);\n" - "}\n" - "@java.lang.Override\n" - "public Builder clearField(\n" - " com.google.protobuf.Descriptors.FieldDescriptor field) {\n" - " return (Builder) super.clearField(field);\n" - "}\n" - "@java.lang.Override\n" - "public Builder clearOneof(\n" - " com.google.protobuf.Descriptors.OneofDescriptor oneof) {\n" - " return (Builder) super.clearOneof(oneof);\n" - "}\n" - "@java.lang.Override\n" - "public Builder setRepeatedField(\n" - " com.google.protobuf.Descriptors.FieldDescriptor field,\n" - " int index, java.lang.Object value) {\n" - " return (Builder) super.setRepeatedField(field, index, value);\n" - "}\n" - "@java.lang.Override\n" - "public Builder addRepeatedField(\n" - " com.google.protobuf.Descriptors.FieldDescriptor field,\n" - " java.lang.Object value) {\n" - " return (Builder) super.addRepeatedField(field, value);\n" - "}\n"); + "@java.lang.Override\n" + "public Builder clone() {\n" + " return super.clone();\n" + "}\n" + "@java.lang.Override\n" + "public Builder setField(\n" + " com.google.protobuf.Descriptors.FieldDescriptor field,\n" + " java.lang.Object value) {\n" + " return super.setField(field, value);\n" + "}\n" + "@java.lang.Override\n" + "public Builder clearField(\n" + " com.google.protobuf.Descriptors.FieldDescriptor field) {\n" + " return super.clearField(field);\n" + "}\n" + "@java.lang.Override\n" + "public Builder clearOneof(\n" + " com.google.protobuf.Descriptors.OneofDescriptor oneof) {\n" + " return super.clearOneof(oneof);\n" + "}\n" + "@java.lang.Override\n" + "public Builder setRepeatedField(\n" + " com.google.protobuf.Descriptors.FieldDescriptor field,\n" + " int index, java.lang.Object value) {\n" + " return super.setRepeatedField(field, index, value);\n" + "}\n" + "@java.lang.Override\n" + "public Builder addRepeatedField(\n" + " com.google.protobuf.Descriptors.FieldDescriptor field,\n" + " java.lang.Object value) {\n" + " return super.addRepeatedField(field, value);\n" + "}\n"); if (descriptor_->extension_range_count() > 0) { printer->Print( - "@java.lang.Override\n" - "public Builder setExtension(\n" - " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" - " $classname$, Type> extension,\n" - " Type value) {\n" - " return (Builder) super.setExtension(extension, value);\n" - "}\n" - "@java.lang.Override\n" - "public Builder setExtension(\n" - " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" - " $classname$, java.util.List> extension,\n" - " int index, Type value) {\n" - " return (Builder) super.setExtension(extension, index, value);\n" - "}\n" - "@java.lang.Override\n" - "public Builder addExtension(\n" - " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" - " $classname$, java.util.List> extension,\n" - " Type value) {\n" - " return (Builder) super.addExtension(extension, value);\n" - "}\n" - "@java.lang.Override\n" - "public Builder clearExtension(\n" - " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" - " $classname$, ?> extension) {\n" - " return (Builder) super.clearExtension(extension);\n" - "}\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + "@java.lang.Override\n" + "public Builder setExtension(\n" + " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" + " $classname$, Type> extension,\n" + " Type value) {\n" + " return super.setExtension(extension, value);\n" + "}\n" + "@java.lang.Override\n" + "public Builder setExtension(\n" + " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" + " $classname$, java.util.List> extension,\n" + " int index, Type value) {\n" + " return super.setExtension(extension, index, value);\n" + "}\n" + "@java.lang.Override\n" + "public Builder addExtension(\n" + " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" + " $classname$, java.util.List> extension,\n" + " Type value) {\n" + " return super.addExtension(extension, value);\n" + "}\n" + "@java.lang.Override\n" + "public Builder clearExtension(\n" + " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" + " $classname$, ?> extension) {\n" + " return super.clearExtension(extension);\n" + "}\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); } // ----------------------------------------------------------------- if (context_->HasGeneratedMethods(descriptor_)) { printer->Print( - "@java.lang.Override\n" - "public Builder mergeFrom(com.google.protobuf.Message other) {\n" - " if (other instanceof $classname$) {\n" - " return mergeFrom(($classname$)other);\n" - " } else {\n" - " super.mergeFrom(other);\n" - " return this;\n" - " }\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + "@java.lang.Override\n" + "public Builder mergeFrom(com.google.protobuf.Message other) {\n" + " if (other instanceof $classname$) {\n" + " return mergeFrom(($classname$)other);\n" + " } else {\n" + " super.mergeFrom(other);\n" + " return this;\n" + " }\n" + "}\n" + "\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); printer->Print( - "public Builder mergeFrom($classname$ other) {\n" - // Optimization: If other is the default instance, we know none of its - // fields are set so we can skip the merge. - " if (other == $classname$.getDefaultInstance()) return this;\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + "public Builder mergeFrom($classname$ other) {\n" + // Optimization: If other is the default instance, we know none of its + // fields are set so we can skip the merge. + " if (other == $classname$.getDefaultInstance()) return this;\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); printer->Indent(); for (int i = 0; i < descriptor_->field_count(); i++) { if (!descriptor_->field(i)->containing_oneof()) { - field_generators_.get( - descriptor_->field(i)).GenerateMergingCode(printer); + field_generators_.get(descriptor_->field(i)) + .GenerateMergingCode(printer); } } // Merge oneof fields. for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) { - printer->Print( - "switch (other.get$oneof_capitalized_name$Case()) {\n", - "oneof_capitalized_name", - context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->capitalized_name); + printer->Print("switch (other.get$oneof_capitalized_name$Case()) {\n", + "oneof_capitalized_name", + context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i)) + ->capitalized_name); printer->Indent(); for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print( - "case $field_name$: {\n", - "field_name", - ToUpper(field->name())); + printer->Print("case $field_name$: {\n", "field_name", + ToUpper(field->name())); printer->Indent(); field_generators_.get(field).GenerateMergingCode(printer); - printer->Print( - "break;\n"); + printer->Print("break;\n"); printer->Outdent(); - printer->Print( - "}\n"); + printer->Print("}\n"); } printer->Print( - "case $cap_oneof_name$_NOT_SET: {\n" - " break;\n" - "}\n", - "cap_oneof_name", - ToUpper(context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name)); + "case $cap_oneof_name$_NOT_SET: {\n" + " break;\n" + "}\n", + "cap_oneof_name", + ToUpper( + context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i)) + ->name)); printer->Outdent(); - printer->Print( - "}\n"); + printer->Print("}\n"); } printer->Outdent(); // if message type has extensions if (descriptor_->extension_range_count() > 0) { - printer->Print( - " this.mergeExtensionFields(other);\n"); + printer->Print(" this.mergeExtensionFields(other);\n"); } - printer->Print( - " this.mergeUnknownFields(other.unknownFields);\n"); + printer->Print(" this.mergeUnknownFields(other.unknownFields);\n"); + + printer->Print(" onChanged();\n"); printer->Print( - " onChanged();\n"); - - printer->Print( - " return this;\n" - "}\n" - "\n"); + " return this;\n" + "}\n" + "\n"); } } // =================================================================== -void MessageBuilderGenerator:: -GenerateBuilderParsingMethods(io::Printer* printer) { +void MessageBuilderGenerator::GenerateBuilderParsingMethods( + io::Printer* printer) { printer->Print( - "@java.lang.Override\n" - "public Builder mergeFrom(\n" - " com.google.protobuf.CodedInputStream input,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws java.io.IOException {\n" - " $classname$ parsedMessage = null;\n" - " try {\n" - " parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n" - " } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n" - " parsedMessage = ($classname$) e.getUnfinishedMessage();\n" - " throw e.unwrapIOException();\n" - " } finally {\n" - " if (parsedMessage != null) {\n" - " mergeFrom(parsedMessage);\n" - " }\n" - " }\n" - " return this;\n" - "}\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + "@java.lang.Override\n" + "public Builder mergeFrom(\n" + " com.google.protobuf.CodedInputStream input,\n" + " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" + " throws java.io.IOException {\n" + " $classname$ parsedMessage = null;\n" + " try {\n" + " parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n" + " } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n" + " parsedMessage = ($classname$) e.getUnfinishedMessage();\n" + " throw e.unwrapIOException();\n" + " } finally {\n" + " if (parsedMessage != null) {\n" + " mergeFrom(parsedMessage);\n" + " }\n" + " }\n" + " return this;\n" + "}\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); } // =================================================================== -void MessageBuilderGenerator::GenerateIsInitialized( - io::Printer* printer) { +void MessageBuilderGenerator::GenerateIsInitialized(io::Printer* printer) { printer->Print( - "@java.lang.Override\n" - "public final boolean isInitialized() {\n"); + "@java.lang.Override\n" + "public final boolean isInitialized() {\n"); printer->Indent(); // Check that all required fields in this message are set. @@ -657,10 +633,10 @@ void MessageBuilderGenerator::GenerateIsInitialized( if (field->is_required()) { printer->Print( - "if (!has$name$()) {\n" - " return false;\n" - "}\n", - "name", info->capitalized_name); + "if (!has$name$()) {\n" + " return false;\n" + "}\n", + "name", info->capitalized_name); } } @@ -673,12 +649,12 @@ void MessageBuilderGenerator::GenerateIsInitialized( switch (field->label()) { case FieldDescriptor::LABEL_REQUIRED: printer->Print( - "if (!get$name$().isInitialized()) {\n" - " return false;\n" - "}\n", - "type", name_resolver_->GetImmutableClassName( - field->message_type()), - "name", info->capitalized_name); + "if (!get$name$().isInitialized()) {\n" + " return false;\n" + "}\n", + "type", + name_resolver_->GetImmutableClassName(field->message_type()), + "name", info->capitalized_name); break; case FieldDescriptor::LABEL_OPTIONAL: if (!SupportFieldPresence(descriptor_->file()) && @@ -686,43 +662,42 @@ void MessageBuilderGenerator::GenerateIsInitialized( const OneofDescriptor* oneof = field->containing_oneof(); const OneofGeneratorInfo* oneof_info = context_->GetOneofGeneratorInfo(oneof); - printer->Print( - "if ($oneof_name$Case_ == $field_number$) {\n", - "oneof_name", oneof_info->name, - "field_number", SimpleItoa(field->number())); + printer->Print("if ($oneof_name$Case_ == $field_number$) {\n", + "oneof_name", oneof_info->name, "field_number", + StrCat(field->number())); } else { - printer->Print( - "if (has$name$()) {\n", - "name", info->capitalized_name); + printer->Print("if (has$name$()) {\n", "name", + info->capitalized_name); } printer->Print( - " if (!get$name$().isInitialized()) {\n" - " return false;\n" - " }\n" - "}\n", - "name", info->capitalized_name); + " if (!get$name$().isInitialized()) {\n" + " return false;\n" + " }\n" + "}\n", + "name", info->capitalized_name); break; case FieldDescriptor::LABEL_REPEATED: if (IsMapEntry(field->message_type())) { printer->Print( - "for ($type$ item : get$name$Map().values()) {\n" - " if (!item.isInitialized()) {\n" - " return false;\n" - " }\n" - "}\n", - "type", MapValueImmutableClassdName(field->message_type(), - name_resolver_), - "name", info->capitalized_name); + "for ($type$ item : get$name$Map().values()) {\n" + " if (!item.isInitialized()) {\n" + " return false;\n" + " }\n" + "}\n", + "type", + MapValueImmutableClassdName(field->message_type(), + name_resolver_), + "name", info->capitalized_name); } else { printer->Print( - "for (int i = 0; i < get$name$Count(); i++) {\n" - " if (!get$name$(i).isInitialized()) {\n" - " return false;\n" - " }\n" - "}\n", - "type", name_resolver_->GetImmutableClassName( - field->message_type()), - "name", info->capitalized_name); + "for (int i = 0; i < get$name$Count(); i++) {\n" + " if (!get$name$(i).isInitialized()) {\n" + " return false;\n" + " }\n" + "}\n", + "type", + name_resolver_->GetImmutableClassName(field->message_type()), + "name", info->capitalized_name); } break; } @@ -731,17 +706,17 @@ void MessageBuilderGenerator::GenerateIsInitialized( if (descriptor_->extension_range_count() > 0) { printer->Print( - "if (!extensionsAreInitialized()) {\n" - " return false;\n" - "}\n"); + "if (!extensionsAreInitialized()) {\n" + " return false;\n" + "}\n"); } printer->Outdent(); printer->Print( - " return true;\n" - "}\n" - "\n"); + " return true;\n" + "}\n" + "\n"); } // =================================================================== diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_builder.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_builder.h index 015ea062..a31d0bad 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_builder.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_builder.h @@ -35,23 +35,25 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_BUILDER_H__ #define GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_BUILDER_H__ -#include #include +#include #include namespace google { namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +namespace io { +class Printer; // printer.h } +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { @@ -81,6 +83,6 @@ class MessageBuilderGenerator { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_BUILDER_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_builder_lite.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_builder_lite.cc index f04d394e..ae344991 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_builder_lite.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_builder_lite.cc @@ -35,7 +35,6 @@ #include #include -#include #include #include #include @@ -51,26 +50,21 @@ #include #include #include -#include #include +#include + namespace google { namespace protobuf { namespace compiler { namespace java { -namespace { -bool GenerateHasBits(const Descriptor* descriptor) { - return SupportFieldPresence(descriptor->file()) || - HasRepeatedFields(descriptor); -} -} // namespace - MessageBuilderLiteGenerator::MessageBuilderLiteGenerator( const Descriptor* descriptor, Context* context) - : descriptor_(descriptor), context_(context), - name_resolver_(context->GetNameResolver()), - field_generators_(descriptor, context_) { + : descriptor_(descriptor), + context_(context), + name_resolver_(context->GetNameResolver()), + field_generators_(descriptor, context_) { GOOGLE_CHECK(!HasDescriptorMethods(descriptor->file(), context->EnforceLite())) << "Generator factory error: A lite message generator is used to " "generate non-lite messages."; @@ -78,72 +72,57 @@ MessageBuilderLiteGenerator::MessageBuilderLiteGenerator( MessageBuilderLiteGenerator::~MessageBuilderLiteGenerator() {} -void MessageBuilderLiteGenerator:: -Generate(io::Printer* printer) { +void MessageBuilderLiteGenerator::Generate(io::Printer* printer) { WriteMessageDocComment(printer, descriptor_); printer->Print( - "public static final class Builder extends\n" - " com.google.protobuf.GeneratedMessageLite.$extendible$Builder<\n" - " $classname$, Builder> implements\n" - " $extra_interfaces$\n" - " $classname$OrBuilder {\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "extra_interfaces", ExtraBuilderInterfaces(descriptor_), - "extendible", - descriptor_->extension_range_count() > 0 ? "Extendable" : ""); + "public static final class Builder extends\n" + " com.google.protobuf.GeneratedMessageLite.$extendible$Builder<\n" + " $classname$, Builder> implements\n" + " $extra_interfaces$\n" + " $classname$OrBuilder {\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_), + "extra_interfaces", ExtraBuilderInterfaces(descriptor_), "extendible", + descriptor_->extension_range_count() > 0 ? "Extendable" : ""); printer->Indent(); GenerateCommonBuilderMethods(printer); // oneof - std::map vars; + std::map vars; for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - vars["oneof_name"] = context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name; - vars["oneof_capitalized_name"] = context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->capitalized_name; - vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index()); + vars["oneof_name"] = + context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))->name; + vars["oneof_capitalized_name"] = + context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i)) + ->capitalized_name; + vars["oneof_index"] = StrCat(descriptor_->oneof_decl(i)->index()); // oneofCase() and clearOneof() printer->Print(vars, - "@java.lang.Override\n" - "public $oneof_capitalized_name$Case\n" - " get$oneof_capitalized_name$Case() {\n" - " return instance.get$oneof_capitalized_name$Case();\n" - "}\n" - "\n" - "public Builder clear$oneof_capitalized_name$() {\n" - " copyOnWrite();\n" - " instance.clear$oneof_capitalized_name$();\n" - " return this;\n" - "}\n" - "\n"); - } - - if (GenerateHasBits(descriptor_)) { - // Integers for bit fields. - int totalBits = 0; - for (int i = 0; i < descriptor_->field_count(); i++) { - totalBits += field_generators_.get(descriptor_->field(i)) - .GetNumBitsForBuilder(); - } - int totalInts = (totalBits + 31) / 32; - for (int i = 0; i < totalInts; i++) { - printer->Print("private int $bit_field_name$;\n", - "bit_field_name", GetBitFieldName(i)); - } + "@java.lang.Override\n" + "public $oneof_capitalized_name$Case\n" + " get$oneof_capitalized_name$Case() {\n" + " return instance.get$oneof_capitalized_name$Case();\n" + "}\n" + "\n" + "public Builder clear$oneof_capitalized_name$() {\n" + " copyOnWrite();\n" + " instance.clear$oneof_capitalized_name$();\n" + " return this;\n" + "}\n" + "\n"); } for (int i = 0; i < descriptor_->field_count(); i++) { printer->Print("\n"); field_generators_.get(descriptor_->field(i)) - .GenerateBuilderMembers(printer); + .GenerateBuilderMembers(printer); } printer->Print( - "\n" - "// @@protoc_insertion_point(builder_scope:$full_name$)\n", - "full_name", descriptor_->full_name()); + "\n" + "// @@protoc_insertion_point(builder_scope:$full_name$)\n", + "full_name", descriptor_->full_name()); printer->Outdent(); printer->Print("}\n"); @@ -151,15 +130,15 @@ Generate(io::Printer* printer) { // =================================================================== -void MessageBuilderLiteGenerator:: -GenerateCommonBuilderMethods(io::Printer* printer) { +void MessageBuilderLiteGenerator::GenerateCommonBuilderMethods( + io::Printer* printer) { printer->Print( - "// Construct using $classname$.newBuilder()\n" - "private Builder() {\n" - " super(DEFAULT_INSTANCE);\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + "// Construct using $classname$.newBuilder()\n" + "private Builder() {\n" + " super(DEFAULT_INSTANCE);\n" + "}\n" + "\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); } // =================================================================== diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_builder_lite.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_builder_lite.h index 8597b2e6..e0a48dc1 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_builder_lite.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_builder_lite.h @@ -35,23 +35,25 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_BUILDER_LITE_H__ #define GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_BUILDER_LITE_H__ -#include #include +#include #include namespace google { namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +namespace io { +class Printer; // printer.h } +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { @@ -59,7 +61,7 @@ namespace java { class MessageBuilderLiteGenerator { public: explicit MessageBuilderLiteGenerator(const Descriptor* descriptor, - Context* context); + Context* context); virtual ~MessageBuilderLiteGenerator(); virtual void Generate(io::Printer* printer); @@ -78,6 +80,6 @@ class MessageBuilderLiteGenerator { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_BUILDER_LITE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_field.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_field.cc index baa7f872..eb3ed51b 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_field.cc @@ -36,9 +36,9 @@ #include #include -#include #include #include +#include #include #include #include @@ -51,12 +51,10 @@ namespace java { namespace { -void SetMessageVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - const FieldGeneratorInfo* info, +void SetMessageVariables(const FieldDescriptor* descriptor, int messageBitIndex, + int builderBitIndex, const FieldGeneratorInfo* info, ClassNameResolver* name_resolver, - std::map* variables) { + std::map* variables) { SetCommonFieldVariables(descriptor, info, variables); (*variables)["type"] = @@ -64,17 +62,17 @@ void SetMessageVariables(const FieldDescriptor* descriptor, (*variables)["mutable_type"] = name_resolver->GetMutableClassName(descriptor->message_type()); (*variables)["group_or_message"] = - (GetType(descriptor) == FieldDescriptor::TYPE_GROUP) ? - "Group" : "Message"; + (GetType(descriptor) == FieldDescriptor::TYPE_GROUP) ? "Group" + : "Message"; // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; + (*variables)["deprecation"] = + descriptor->options().deprecated() ? "@java.lang.Deprecated " : ""; (*variables)["on_changed"] = "onChanged();"; (*variables)["ver"] = GeneratedCodeVersionSuffix(); (*variables)["get_parser"] = - ExposePublicParser(descriptor->message_type()->file()) - ? "PARSER" : "parser()"; + ExposePublicParser(descriptor->message_type()->file()) ? "PARSER" + : "parser()"; if (SupportFieldPresence(descriptor->file())) { // For singular messages and builders, one bit is used for the hasField bit. @@ -121,101 +119,99 @@ void SetMessageVariables(const FieldDescriptor* descriptor, // =================================================================== -ImmutableMessageFieldGenerator:: -ImmutableMessageFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetMessageVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); +ImmutableMessageFieldGenerator::ImmutableMessageFieldGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, + Context* context) + : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) { + SetMessageVariables(descriptor, messageBitIndex, builderBitIndex, + context->GetFieldGeneratorInfo(descriptor), + name_resolver_, &variables_); } ImmutableMessageFieldGenerator::~ImmutableMessageFieldGenerator() {} int ImmutableMessageFieldGenerator::GetNumBitsForMessage() const { - return 1; + return SupportFieldPresence(descriptor_->file()) ? 1 : 0; } int ImmutableMessageFieldGenerator::GetNumBitsForBuilder() const { - return 1; + return GetNumBitsForMessage(); } -void ImmutableMessageFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { +void ImmutableMessageFieldGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { // TODO(jonp): In the future, consider having a method specific to the // interface so that builders can choose dynamically to either return a // message or a nested builder, so that asking for the interface doesn't // cause a message to ever be built. WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); + printer->Print(variables_, "$deprecation$boolean has$capitalized_name$();\n"); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$();\n"); + printer->Print(variables_, "$deprecation$$type$ get$capitalized_name$();\n"); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$OrBuilder get$capitalized_name$OrBuilder();\n"); + printer->Print( + variables_, + "$deprecation$$type$OrBuilder get$capitalized_name$OrBuilder();\n"); } -void ImmutableMessageFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private $type$ $name$_;\n"); +void ImmutableMessageFieldGenerator::GenerateMembers( + io::Printer* printer) const { + printer->Print(variables_, "private $type$ $name$_;\n"); PrintExtraFieldInfo(variables_, printer); if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $get_has_field_bit_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder " - "${$get$capitalized_name$OrBuilder$}$() {\n" - " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public $type$OrBuilder " + "${$get$capitalized_name$OrBuilder$}$() {\n" + " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } else { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $name$_ != null;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $name$_ != null;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public $type$OrBuilder " - "${$get$capitalized_name$OrBuilder$}$() {\n" - " return get$capitalized_name$();\n" - "}\n"); + "$deprecation$public $type$OrBuilder " + "${$get$capitalized_name$OrBuilder$}$() {\n" + " return get$capitalized_name$();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } } void ImmutableMessageFieldGenerator::PrintNestedBuilderCondition( - io::Printer* printer, - const char* regular_case, + io::Printer* printer, const char* regular_case, const char* nested_builder_case) const { printer->Print(variables_, "if ($name$Builder_ == null) {\n"); printer->Indent(); @@ -229,10 +225,8 @@ void ImmutableMessageFieldGenerator::PrintNestedBuilderCondition( } void ImmutableMessageFieldGenerator::PrintNestedBuilderFunction( - io::Printer* printer, - const char* method_prototype, - const char* regular_case, - const char* nested_builder_case, + io::Printer* printer, const char* method_prototype, + const char* regular_case, const char* nested_builder_case, const char* trailing_code) const { printer->Print(variables_, method_prototype); printer->Annotate("{", "}", descriptor_); @@ -246,23 +240,22 @@ void ImmutableMessageFieldGenerator::PrintNestedBuilderFunction( printer->Print("}\n"); } -void ImmutableMessageFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void ImmutableMessageFieldGenerator::GenerateBuilderMembers( + io::Printer* printer) const { // When using nested-builders, the code initially works just like the // non-nested builder case. It only creates a nested builder lazily on // demand and then forever delegates to it after creation. bool support_field_presence = SupportFieldPresence(descriptor_->file()); - printer->Print(variables_, - "private $type$ $name$_ = null;\n"); + printer->Print(variables_, "private $type$ $name$_;\n"); printer->Print(variables_, - // If this builder is non-null, it is used and the other fields are - // ignored. - "private com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;" - "\n"); + // If this builder is non-null, it is used and the other fields + // are ignored. + "private com.google.protobuf.SingleFieldBuilder$ver$<\n" + " $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;" + "\n"); // The comments above the methods below are based on a hypothetical // field of type "Field" called "Field". @@ -270,315 +263,317 @@ GenerateBuilderMembers(io::Printer* printer) const { // boolean hasField() WriteFieldDocComment(printer, descriptor_); if (support_field_presence) { - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_builder$;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $get_has_field_bit_builder$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } else { - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $name$Builder_ != null || $name$_ != null;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $name$Builder_ != null || $name$_ != null;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } // Field getField() WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public $type$ ${$get$capitalized_name$$}$()", - "return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n", - "return $name$Builder_.getMessage();\n", - NULL); + PrintNestedBuilderFunction( + printer, "$deprecation$public $type$ ${$get$capitalized_name$$}$()", + "return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n", + "return $name$Builder_.getMessage();\n", NULL); // Field.Builder setField(Field value) WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value)", + PrintNestedBuilderFunction( + printer, + "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value)", - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "$name$_ = value;\n" - "$on_changed$\n", + "if (value == null) {\n" + " throw new NullPointerException();\n" + "}\n" + "$name$_ = value;\n" + "$on_changed$\n", - "$name$Builder_.setMessage(value);\n", + "$name$Builder_.setMessage(value);\n", - "$set_has_field_bit_builder$\n" - "return this;\n"); + "$set_has_field_bit_builder$\n" + "return this;\n"); // Field.Builder setField(Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " $type$.Builder builderForValue)", + PrintNestedBuilderFunction( + printer, + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " $type$.Builder builderForValue)", - "$name$_ = builderForValue.build();\n" - "$on_changed$\n", + "$name$_ = builderForValue.build();\n" + "$on_changed$\n", - "$name$Builder_.setMessage(builderForValue.build());\n", + "$name$Builder_.setMessage(builderForValue.build());\n", - "$set_has_field_bit_builder$\n" - "return this;\n"); + "$set_has_field_bit_builder$\n" + "return this;\n"); // Field.Builder mergeField(Field value) WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$merge$capitalized_name$$}$($type$ value)", + PrintNestedBuilderFunction( + printer, + "$deprecation$public Builder ${$merge$capitalized_name$$}$($type$ value)", - support_field_presence - ? "if ($get_has_field_bit_builder$ &&\n" - " $name$_ != null &&\n" - " $name$_ != $type$.getDefaultInstance()) {\n" - " $name$_ =\n" - " $type$.newBuilder($name$_).mergeFrom(value).buildPartial();\n" - "} else {\n" - " $name$_ = value;\n" - "}\n" - "$on_changed$\n" - : "if ($name$_ != null) {\n" - " $name$_ =\n" - " $type$.newBuilder($name$_).mergeFrom(value).buildPartial();\n" - "} else {\n" - " $name$_ = value;\n" - "}\n" - "$on_changed$\n", + support_field_presence + ? "if ($get_has_field_bit_builder$ &&\n" + " $name$_ != null &&\n" + " $name$_ != $type$.getDefaultInstance()) {\n" + " $name$_ =\n" + " $type$.newBuilder($name$_).mergeFrom(value).buildPartial();\n" + "} else {\n" + " $name$_ = value;\n" + "}\n" + "$on_changed$\n" + : "if ($name$_ != null) {\n" + " $name$_ =\n" + " $type$.newBuilder($name$_).mergeFrom(value).buildPartial();\n" + "} else {\n" + " $name$_ = value;\n" + "}\n" + "$on_changed$\n", - "$name$Builder_.mergeFrom(value);\n", + "$name$Builder_.mergeFrom(value);\n", - "$set_has_field_bit_builder$\n" - "return this;\n"); + "$set_has_field_bit_builder$\n" + "return this;\n"); // Field.Builder clearField() WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$clear$capitalized_name$$}$()", - - "$name$_ = null;\n" - "$on_changed$\n", - - support_field_presence - ? "$name$Builder_.clear();\n" - : "$name$_ = null;\n" - "$name$Builder_ = null;\n", - - "$clear_has_field_bit_builder$\n" - "return this;\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$.Builder " - "${$get$capitalized_name$Builder$}$() {\n" - " $set_has_field_bit_builder$\n" - " $on_changed$\n" - " return get$capitalized_name$FieldBuilder().getBuilder();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder " - "${$get$capitalized_name$OrBuilder$}$() {\n" - " if ($name$Builder_ != null) {\n" - " return $name$Builder_.getMessageOrBuilder();\n" - " } else {\n" - " return $name$_ == null ?\n" - " $type$.getDefaultInstance() : $name$_;\n" - " }\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> \n" - " get$capitalized_name$FieldBuilder() {\n" - " if ($name$Builder_ == null) {\n" - " $name$Builder_ = new com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder>(\n" - " get$capitalized_name$(),\n" - " getParentForChildren(),\n" - " isClean());\n" - " $name$_ = null;\n" - " }\n" - " return $name$Builder_;\n" - "}\n"); -} - -void ImmutableMessageFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "get$capitalized_name$FieldBuilder();\n"); - } -} - - -void ImmutableMessageFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const {} - -void ImmutableMessageFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - PrintNestedBuilderCondition(printer, - "$name$_ = null;\n", - - "$name$Builder_.clear();\n"); - printer->Print(variables_, "$clear_has_field_bit_builder$\n"); - } else { - PrintNestedBuilderCondition(printer, - "$name$_ = null;\n", + PrintNestedBuilderFunction( + printer, "$deprecation$public Builder ${$clear$capitalized_name$$}$()", "$name$_ = null;\n" - "$name$Builder_ = null;\n"); - } -} + "$on_changed$\n", -void ImmutableMessageFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { + support_field_presence ? "$name$Builder_.clear();\n" + : "$name$_ = null;\n" + "$name$Builder_ = null;\n", + + "$clear_has_field_bit_builder$\n" + "return this;\n"); + + WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "if (other.has$capitalized_name$()) {\n" - " merge$capitalized_name$(other.get$capitalized_name$());\n" - "}\n"); + "$deprecation$public $type$.Builder " + "${$get$capitalized_name$Builder$}$() {\n" + " $set_has_field_bit_builder$\n" + " $on_changed$\n" + " return get$capitalized_name$FieldBuilder().getBuilder();\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$public $type$OrBuilder " + "${$get$capitalized_name$OrBuilder$}$() {\n" + " if ($name$Builder_ != null) {\n" + " return $name$Builder_.getMessageOrBuilder();\n" + " } else {\n" + " return $name$_ == null ?\n" + " $type$.getDefaultInstance() : $name$_;\n" + " }\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "private com.google.protobuf.SingleFieldBuilder$ver$<\n" + " $type$, $type$.Builder, $type$OrBuilder> \n" + " get$capitalized_name$FieldBuilder() {\n" + " if ($name$Builder_ == null) {\n" + " $name$Builder_ = new com.google.protobuf.SingleFieldBuilder$ver$<\n" + " $type$, $type$.Builder, $type$OrBuilder>(\n" + " get$capitalized_name$(),\n" + " getParentForChildren(),\n" + " isClean());\n" + " $name$_ = null;\n" + " }\n" + " return $name$Builder_;\n" + "}\n"); } -void ImmutableMessageFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { +void ImmutableMessageFieldGenerator::GenerateFieldBuilderInitializationCode( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "if ($get_has_field_bit_from_local$) {\n" - " $set_has_field_bit_to_local$;\n" - "}\n"); + printer->Print(variables_, "get$capitalized_name$FieldBuilder();\n"); } - - PrintNestedBuilderCondition(printer, - "result.$name$_ = $name$_;\n", - - "result.$name$_ = $name$Builder_.build();\n"); } -void ImmutableMessageFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { +void ImmutableMessageFieldGenerator::GenerateInitializationCode( + io::Printer* printer) const {} + +void ImmutableMessageFieldGenerator::GenerateBuilderClearCode( + io::Printer* printer) const { + if (SupportFieldPresence(descriptor_->file())) { + PrintNestedBuilderCondition(printer, "$name$_ = null;\n", + + "$name$Builder_.clear();\n"); + printer->Print(variables_, "$clear_has_field_bit_builder$\n"); + } else { + PrintNestedBuilderCondition(printer, "$name$_ = null;\n", + + "$name$_ = null;\n" + "$name$Builder_ = null;\n"); + } +} + +void ImmutableMessageFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { printer->Print(variables_, - "$type$.Builder subBuilder = null;\n" - "if ($is_field_present_message$) {\n" - " subBuilder = $name$_.toBuilder();\n" - "}\n"); + "if (other.has$capitalized_name$()) {\n" + " merge$capitalized_name$(other.get$capitalized_name$());\n" + "}\n"); +} + +void ImmutableMessageFieldGenerator::GenerateBuildingCode( + io::Printer* printer) const { + if (SupportFieldPresence(descriptor_->file())) { + printer->Print(variables_, "if ($get_has_field_bit_from_local$) {\n"); + printer->Indent(); + PrintNestedBuilderCondition(printer, "result.$name$_ = $name$_;\n", + "result.$name$_ = $name$Builder_.build();\n"); + printer->Outdent(); + printer->Print(variables_, + " $set_has_field_bit_to_local$;\n" + "}\n"); + } else { + PrintNestedBuilderCondition(printer, "result.$name$_ = $name$_;\n", + "result.$name$_ = $name$Builder_.build();\n"); + } +} + +void ImmutableMessageFieldGenerator::GenerateParsingCode( + io::Printer* printer) const { + printer->Print(variables_, + "$type$.Builder subBuilder = null;\n" + "if ($is_field_present_message$) {\n" + " subBuilder = $name$_.toBuilder();\n" + "}\n"); if (GetType(descriptor_) == FieldDescriptor::TYPE_GROUP) { printer->Print(variables_, - "$name$_ = input.readGroup($number$, $type$.$get_parser$,\n" - " extensionRegistry);\n"); + "$name$_ = input.readGroup($number$, $type$.$get_parser$,\n" + " extensionRegistry);\n"); } else { printer->Print(variables_, - "$name$_ = input.readMessage($type$.$get_parser$, extensionRegistry);\n"); + "$name$_ = input.readMessage($type$.$get_parser$, " + "extensionRegistry);\n"); } printer->Print(variables_, - "if (subBuilder != null) {\n" - " subBuilder.mergeFrom($name$_);\n" - " $name$_ = subBuilder.buildPartial();\n" - "}\n" - "$set_has_field_bit_message$\n"); + "if (subBuilder != null) {\n" + " subBuilder.mergeFrom($name$_);\n" + " $name$_ = subBuilder.buildPartial();\n" + "}\n" + "$set_has_field_bit_message$\n"); } -void ImmutableMessageFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { +void ImmutableMessageFieldGenerator::GenerateParsingDoneCode( + io::Printer* printer) const { // noop for messages. } -void ImmutableMessageFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " output.write$group_or_message$($number$, get$capitalized_name$());\n" - "}\n"); +void ImmutableMessageFieldGenerator::GenerateSerializationCode( + io::Printer* printer) const { + printer->Print( + variables_, + "if ($is_field_present_message$) {\n" + " output.write$group_or_message$($number$, get$capitalized_name$());\n" + "}\n"); } -void ImmutableMessageFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$group_or_message$Size($number$, get$capitalized_name$());\n" - "}\n"); +void ImmutableMessageFieldGenerator::GenerateSerializedSizeCode( + io::Printer* printer) const { + printer->Print( + variables_, + "if ($is_field_present_message$) {\n" + " size += com.google.protobuf.CodedOutputStream\n" + " .compute$group_or_message$Size($number$, get$capitalized_name$());\n" + "}\n"); } -void ImmutableMessageFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { +void ImmutableMessageFieldGenerator::GenerateEqualsCode( + io::Printer* printer) const { printer->Print(variables_, - "result = result && get$capitalized_name$()\n" - " .equals(other.get$capitalized_name$());\n"); + "if (!get$capitalized_name$()\n" + " .equals(other.get$capitalized_name$())) return false;\n"); } -void ImmutableMessageFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { +void ImmutableMessageFieldGenerator::GenerateHashCode( + io::Printer* printer) const { printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n" - "hash = (53 * hash) + get$capitalized_name$().hashCode();\n"); + "hash = (37 * hash) + $constant_name$;\n" + "hash = (53 * hash) + get$capitalized_name$().hashCode();\n"); } -string ImmutableMessageFieldGenerator::GetBoxedType() const { +std::string ImmutableMessageFieldGenerator::GetBoxedType() const { return name_resolver_->GetImmutableClassName(descriptor_->message_type()); } // =================================================================== -ImmutableMessageOneofFieldGenerator:: -ImmutableMessageOneofFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableMessageFieldGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { +ImmutableMessageOneofFieldGenerator::ImmutableMessageOneofFieldGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, + Context* context) + : ImmutableMessageFieldGenerator(descriptor, messageBitIndex, + builderBitIndex, context) { const OneofGeneratorInfo* info = context->GetOneofGeneratorInfo(descriptor->containing_oneof()); SetCommonOneofVariables(descriptor, info, &variables_); } -ImmutableMessageOneofFieldGenerator:: -~ImmutableMessageOneofFieldGenerator() {} +ImmutableMessageOneofFieldGenerator::~ImmutableMessageOneofFieldGenerator() {} -void ImmutableMessageOneofFieldGenerator:: -GenerateMembers(io::Printer* printer) const { +void ImmutableMessageOneofFieldGenerator::GenerateMembers( + io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $has_oneof_case_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($type$) $oneof_name$_;\n" - " }\n" - " return $type$.getDefaultInstance();\n" - "}\n"); + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " if ($has_oneof_case_message$) {\n" + " return ($type$) $oneof_name$_;\n" + " }\n" + " return $type$.getDefaultInstance();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public $type$OrBuilder " - "${$get$capitalized_name$OrBuilder$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($type$) $oneof_name$_;\n" - " }\n" - " return $type$.getDefaultInstance();\n" - "}\n"); + "$deprecation$public $type$OrBuilder " + "${$get$capitalized_name$OrBuilder$}$() {\n" + " if ($has_oneof_case_message$) {\n" + " return ($type$) $oneof_name$_;\n" + " }\n" + " return $type$.getDefaultInstance();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } -void ImmutableMessageOneofFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void ImmutableMessageOneofFieldGenerator::GenerateBuilderMembers( + io::Printer* printer) const { // When using nested-builders, the code initially works just like the // non-nested builder case. It only creates a nested builder lazily on // demand and then forever delegates to it after creation. printer->Print(variables_, - // If this builder is non-null, it is used and the other fields are - // ignored. - "private com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;" - "\n"); + // If this builder is non-null, it is used and the other fields + // are ignored. + "private com.google.protobuf.SingleFieldBuilder$ver$<\n" + " $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;" + "\n"); // The comments above the methods below are based on a hypothetical // field of type "Field" called "Field". @@ -586,226 +581,228 @@ GenerateBuilderMembers(io::Printer* printer) const { // boolean hasField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $has_oneof_case_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Field getField() WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public $type$ ${$get$capitalized_name$$}$()", + PrintNestedBuilderFunction( + printer, "$deprecation$public $type$ ${$get$capitalized_name$$}$()", - "if ($has_oneof_case_message$) {\n" - " return ($type$) $oneof_name$_;\n" - "}\n" - "return $type$.getDefaultInstance();\n", + "if ($has_oneof_case_message$) {\n" + " return ($type$) $oneof_name$_;\n" + "}\n" + "return $type$.getDefaultInstance();\n", - "if ($has_oneof_case_message$) {\n" - " return $name$Builder_.getMessage();\n" - "}\n" - "return $type$.getDefaultInstance();\n", + "if ($has_oneof_case_message$) {\n" + " return $name$Builder_.getMessage();\n" + "}\n" + "return $type$.getDefaultInstance();\n", - NULL); + NULL); // Field.Builder setField(Field value) WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value)", + PrintNestedBuilderFunction( + printer, + "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value)", - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "$oneof_name$_ = value;\n" - "$on_changed$\n", + "if (value == null) {\n" + " throw new NullPointerException();\n" + "}\n" + "$oneof_name$_ = value;\n" + "$on_changed$\n", - "$name$Builder_.setMessage(value);\n", + "$name$Builder_.setMessage(value);\n", - "$set_oneof_case_message$;\n" - "return this;\n"); + "$set_oneof_case_message$;\n" + "return this;\n"); // Field.Builder setField(Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " $type$.Builder builderForValue)", + PrintNestedBuilderFunction( + printer, + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " $type$.Builder builderForValue)", - "$oneof_name$_ = builderForValue.build();\n" - "$on_changed$\n", + "$oneof_name$_ = builderForValue.build();\n" + "$on_changed$\n", - "$name$Builder_.setMessage(builderForValue.build());\n", + "$name$Builder_.setMessage(builderForValue.build());\n", - "$set_oneof_case_message$;\n" - "return this;\n"); + "$set_oneof_case_message$;\n" + "return this;\n"); // Field.Builder mergeField(Field value) WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$merge$capitalized_name$$}$($type$ value)", + PrintNestedBuilderFunction( + printer, + "$deprecation$public Builder ${$merge$capitalized_name$$}$($type$ value)", - "if ($has_oneof_case_message$ &&\n" - " $oneof_name$_ != $type$.getDefaultInstance()) {\n" - " $oneof_name$_ = $type$.newBuilder(($type$) $oneof_name$_)\n" - " .mergeFrom(value).buildPartial();\n" - "} else {\n" - " $oneof_name$_ = value;\n" - "}\n" - "$on_changed$\n", + "if ($has_oneof_case_message$ &&\n" + " $oneof_name$_ != $type$.getDefaultInstance()) {\n" + " $oneof_name$_ = $type$.newBuilder(($type$) $oneof_name$_)\n" + " .mergeFrom(value).buildPartial();\n" + "} else {\n" + " $oneof_name$_ = value;\n" + "}\n" + "$on_changed$\n", - "if ($has_oneof_case_message$) {\n" - " $name$Builder_.mergeFrom(value);\n" - "}\n" - "$name$Builder_.setMessage(value);\n", + "if ($has_oneof_case_message$) {\n" + " $name$Builder_.mergeFrom(value);\n" + "}\n" + "$name$Builder_.setMessage(value);\n", - "$set_oneof_case_message$;\n" - "return this;\n"); + "$set_oneof_case_message$;\n" + "return this;\n"); // Field.Builder clearField() WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$clear$capitalized_name$$}$()", + PrintNestedBuilderFunction( + printer, "$deprecation$public Builder ${$clear$capitalized_name$$}$()", - "if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " $on_changed$\n" - "}\n", + "if ($has_oneof_case_message$) {\n" + " $clear_oneof_case_message$;\n" + " $oneof_name$_ = null;\n" + " $on_changed$\n" + "}\n", - "if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - "}\n" - "$name$Builder_.clear();\n", + "if ($has_oneof_case_message$) {\n" + " $clear_oneof_case_message$;\n" + " $oneof_name$_ = null;\n" + "}\n" + "$name$Builder_.clear();\n", - "return this;\n"); + "return this;\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public $type$.Builder " - "${$get$capitalized_name$Builder$}$() {\n" - " return get$capitalized_name$FieldBuilder().getBuilder();\n" - "}\n"); + "$deprecation$public $type$.Builder " + "${$get$capitalized_name$Builder$}$() {\n" + " return get$capitalized_name$FieldBuilder().getBuilder();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder " - "${$get$capitalized_name$OrBuilder$}$() {\n" - " if (($has_oneof_case_message$) && ($name$Builder_ != null)) {\n" - " return $name$Builder_.getMessageOrBuilder();\n" - " } else {\n" - " if ($has_oneof_case_message$) {\n" - " return ($type$) $oneof_name$_;\n" - " }\n" - " return $type$.getDefaultInstance();\n" - " }\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public $type$OrBuilder " + "${$get$capitalized_name$OrBuilder$}$() {\n" + " if (($has_oneof_case_message$) && ($name$Builder_ != null)) {\n" + " return $name$Builder_.getMessageOrBuilder();\n" + " } else {\n" + " if ($has_oneof_case_message$) {\n" + " return ($type$) $oneof_name$_;\n" + " }\n" + " return $type$.getDefaultInstance();\n" + " }\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> \n" - " ${$get$capitalized_name$FieldBuilder$}$() {\n" - " if ($name$Builder_ == null) {\n" - " if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = $type$.getDefaultInstance();\n" - " }\n" - " $name$Builder_ = new com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder>(\n" - " ($type$) $oneof_name$_,\n" - " getParentForChildren(),\n" - " isClean());\n" - " $oneof_name$_ = null;\n" - " }\n" - " $set_oneof_case_message$;\n" - " $on_changed$;\n" - " return $name$Builder_;\n" - "}\n"); + printer->Print( + variables_, + "private com.google.protobuf.SingleFieldBuilder$ver$<\n" + " $type$, $type$.Builder, $type$OrBuilder> \n" + " ${$get$capitalized_name$FieldBuilder$}$() {\n" + " if ($name$Builder_ == null) {\n" + " if (!($has_oneof_case_message$)) {\n" + " $oneof_name$_ = $type$.getDefaultInstance();\n" + " }\n" + " $name$Builder_ = new com.google.protobuf.SingleFieldBuilder$ver$<\n" + " $type$, $type$.Builder, $type$OrBuilder>(\n" + " ($type$) $oneof_name$_,\n" + " getParentForChildren(),\n" + " isClean());\n" + " $oneof_name$_ = null;\n" + " }\n" + " $set_oneof_case_message$;\n" + " $on_changed$;\n" + " return $name$Builder_;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } -void ImmutableMessageOneofFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n"); +void ImmutableMessageOneofFieldGenerator::GenerateBuildingCode( + io::Printer* printer) const { + printer->Print(variables_, "if ($has_oneof_case_message$) {\n"); printer->Indent(); - PrintNestedBuilderCondition(printer, - "result.$oneof_name$_ = $oneof_name$_;\n", + PrintNestedBuilderCondition( + printer, "result.$oneof_name$_ = $oneof_name$_;\n", - "result.$oneof_name$_ = $name$Builder_.build();\n"); + "result.$oneof_name$_ = $name$Builder_.build();\n"); printer->Outdent(); printer->Print("}\n"); } -void ImmutableMessageOneofFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { +void ImmutableMessageOneofFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { printer->Print(variables_, - "merge$capitalized_name$(other.get$capitalized_name$());\n"); + "merge$capitalized_name$(other.get$capitalized_name$());\n"); } -void ImmutableMessageOneofFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { +void ImmutableMessageOneofFieldGenerator::GenerateParsingCode( + io::Printer* printer) const { printer->Print(variables_, - "$type$.Builder subBuilder = null;\n" - "if ($has_oneof_case_message$) {\n" - " subBuilder = (($type$) $oneof_name$_).toBuilder();\n" - "}\n"); + "$type$.Builder subBuilder = null;\n" + "if ($has_oneof_case_message$) {\n" + " subBuilder = (($type$) $oneof_name$_).toBuilder();\n" + "}\n"); if (GetType(descriptor_) == FieldDescriptor::TYPE_GROUP) { - printer->Print(variables_, - "$oneof_name$_ = input.readGroup($number$, $type$.$get_parser$,\n" - " extensionRegistry);\n"); + printer->Print( + variables_, + "$oneof_name$_ = input.readGroup($number$, $type$.$get_parser$,\n" + " extensionRegistry);\n"); } else { - printer->Print(variables_, - "$oneof_name$_ =\n" - " input.readMessage($type$.$get_parser$, extensionRegistry);\n"); + printer->Print( + variables_, + "$oneof_name$_ =\n" + " input.readMessage($type$.$get_parser$, extensionRegistry);\n"); } printer->Print(variables_, - "if (subBuilder != null) {\n" - " subBuilder.mergeFrom(($type$) $oneof_name$_);\n" - " $oneof_name$_ = subBuilder.buildPartial();\n" - "}\n"); - printer->Print(variables_, - "$set_oneof_case_message$;\n"); + "if (subBuilder != null) {\n" + " subBuilder.mergeFrom(($type$) $oneof_name$_);\n" + " $oneof_name$_ = subBuilder.buildPartial();\n" + "}\n"); + printer->Print(variables_, "$set_oneof_case_message$;\n"); } -void ImmutableMessageOneofFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.write$group_or_message$($number$, ($type$) $oneof_name$_);\n" - "}\n"); +void ImmutableMessageOneofFieldGenerator::GenerateSerializationCode( + io::Printer* printer) const { + printer->Print( + variables_, + "if ($has_oneof_case_message$) {\n" + " output.write$group_or_message$($number$, ($type$) $oneof_name$_);\n" + "}\n"); } -void ImmutableMessageOneofFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$group_or_message$Size($number$, ($type$) $oneof_name$_);\n" - "}\n"); +void ImmutableMessageOneofFieldGenerator::GenerateSerializedSizeCode( + io::Printer* printer) const { + printer->Print( + variables_, + "if ($has_oneof_case_message$) {\n" + " size += com.google.protobuf.CodedOutputStream\n" + " .compute$group_or_message$Size($number$, ($type$) $oneof_name$_);\n" + "}\n"); } // =================================================================== -RepeatedImmutableMessageFieldGenerator:: -RepeatedImmutableMessageFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { +RepeatedImmutableMessageFieldGenerator::RepeatedImmutableMessageFieldGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, + Context* context) + : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) { SetMessageVariables(descriptor, messageBitIndex, builderBitIndex, context->GetFieldGeneratorInfo(descriptor), name_resolver_, &variables_); } RepeatedImmutableMessageFieldGenerator:: -~RepeatedImmutableMessageFieldGenerator() {} + ~RepeatedImmutableMessageFieldGenerator() {} int RepeatedImmutableMessageFieldGenerator::GetNumBitsForMessage() const { return 0; @@ -815,78 +812,79 @@ int RepeatedImmutableMessageFieldGenerator::GetNumBitsForBuilder() const { return 1; } -void RepeatedImmutableMessageFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { +void RepeatedImmutableMessageFieldGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { // TODO(jonp): In the future, consider having methods specific to the // interface so that builders can choose dynamically to either return a // message or a nested builder, so that asking for the interface doesn't // cause a message to ever be built. WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$java.util.List<$type$> \n" - " get$capitalized_name$List();\n"); + "$deprecation$java.util.List<$type$> \n" + " get$capitalized_name$List();\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$(int index);\n"); + "$deprecation$$type$ get$capitalized_name$(int index);\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); + "$deprecation$int get$capitalized_name$Count();\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$java.util.List \n" - " get$capitalized_name$OrBuilderList();\n"); + "$deprecation$java.util.List \n" + " get$capitalized_name$OrBuilderList();\n"); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$OrBuilder get$capitalized_name$OrBuilder(\n" - " int index);\n"); + printer->Print( + variables_, + "$deprecation$$type$OrBuilder get$capitalized_name$OrBuilder(\n" + " int index);\n"); } -void RepeatedImmutableMessageFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private java.util.List<$type$> $name$_;\n"); +void RepeatedImmutableMessageFieldGenerator::GenerateMembers( + io::Printer* printer) const { + printer->Print(variables_, "private java.util.List<$type$> $name$_;\n"); PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public java.util.List<$type$> " - "${$get$capitalized_name$List$}$() {\n" - " return $name$_;\n" // note: unmodifiable list - "}\n"); + "$deprecation$public java.util.List<$type$> " + "${$get$capitalized_name$List$}$() {\n" + " return $name$_;\n" // note: unmodifiable list + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public java.util.List \n" + " ${$get$capitalized_name$OrBuilderList$}$() {\n" + " return $name$_;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" + " return $name$_.size();\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" + " return $name$_.get(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public java.util.List \n" - " ${$get$capitalized_name$OrBuilderList$}$() {\n" - " return $name$_;\n" - "}\n"); + "$deprecation$public $type$OrBuilder " + "${$get$capitalized_name$OrBuilder$}$(\n" + " int index) {\n" + " return $name$_.get(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder " - "${$get$capitalized_name$OrBuilder$}$(\n" - " int index) {\n" - " return $name$_.get(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } void RepeatedImmutableMessageFieldGenerator::PrintNestedBuilderCondition( - io::Printer* printer, - const char* regular_case, + io::Printer* printer, const char* regular_case, const char* nested_builder_case) const { printer->Print(variables_, "if ($name$Builder_ == null) {\n"); printer->Indent(); @@ -900,10 +898,8 @@ void RepeatedImmutableMessageFieldGenerator::PrintNestedBuilderCondition( } void RepeatedImmutableMessageFieldGenerator::PrintNestedBuilderFunction( - io::Printer* printer, - const char* method_prototype, - const char* regular_case, - const char* nested_builder_case, + io::Printer* printer, const char* method_prototype, + const char* regular_case, const char* nested_builder_case, const char* trailing_code) const { printer->Print(variables_, method_prototype); printer->Annotate("{", "}", descriptor_); @@ -917,409 +913,432 @@ void RepeatedImmutableMessageFieldGenerator::PrintNestedBuilderFunction( printer->Print("}\n"); } -void RepeatedImmutableMessageFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void RepeatedImmutableMessageFieldGenerator::GenerateBuilderMembers( + io::Printer* printer) const { // When using nested-builders, the code initially works just like the // non-nested builder case. It only creates a nested builder lazily on // demand and then forever delegates to it after creation. - printer->Print(variables_, - // Used when the builder is null. - // One field is the list and the other field keeps track of whether the - // list is immutable. If it's immutable, the invariant is that it must - // either an instance of Collections.emptyList() or it's an ArrayList - // wrapped in a Collections.unmodifiableList() wrapper and nobody else has - // a refererence to the underlying ArrayList. This invariant allows us to - // share instances of lists between protocol buffers avoiding expensive - // memory allocations. Note, immutable is a strong guarantee here -- not - // just that the list cannot be modified via the reference but that the - // list can never be modified. - "private java.util.List<$type$> $name$_ =\n" - " java.util.Collections.emptyList();\n" + printer->Print( + variables_, + // Used when the builder is null. + // One field is the list and the other field keeps track of whether the + // list is immutable. If it's immutable, the invariant is that it must + // either an instance of Collections.emptyList() or it's an ArrayList + // wrapped in a Collections.unmodifiableList() wrapper and nobody else has + // a refererence to the underlying ArrayList. This invariant allows us to + // share instances of lists between protocol buffers avoiding expensive + // memory allocations. Note, immutable is a strong guarantee here -- not + // just that the list cannot be modified via the reference but that the + // list can never be modified. + "private java.util.List<$type$> $name$_ =\n" + " java.util.Collections.emptyList();\n" - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$get_mutable_bit_builder$) {\n" - " $name$_ = new java.util.ArrayList<$type$>($name$_);\n" - " $set_mutable_bit_builder$;\n" - " }\n" - "}\n" - "\n"); + "private void ensure$capitalized_name$IsMutable() {\n" + " if (!$get_mutable_bit_builder$) {\n" + " $name$_ = new java.util.ArrayList<$type$>($name$_);\n" + " $set_mutable_bit_builder$;\n" + " }\n" + "}\n" + "\n"); - printer->Print(variables_, - // If this builder is non-null, it is used and the other fields are - // ignored. - "private com.google.protobuf.RepeatedFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;\n" - "\n"); + printer->Print( + variables_, + // If this builder is non-null, it is used and the other fields are + // ignored. + "private com.google.protobuf.RepeatedFieldBuilder$ver$<\n" + " $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;\n" + "\n"); // The comments above the methods below are based on a hypothetical // repeated field of type "Field" called "RepeatedField". // List getRepeatedFieldList() WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public java.util.List<$type$> " - "${$get$capitalized_name$List$}$()", + PrintNestedBuilderFunction( + printer, + "$deprecation$public java.util.List<$type$> " + "${$get$capitalized_name$List$}$()", - "return java.util.Collections.unmodifiableList($name$_);\n", - "return $name$Builder_.getMessageList();\n", + "return java.util.Collections.unmodifiableList($name$_);\n", + "return $name$Builder_.getMessageList();\n", - NULL); + NULL); // int getRepeatedFieldCount() WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public int ${$get$capitalized_name$Count$}$()", + PrintNestedBuilderFunction( + printer, "$deprecation$public int ${$get$capitalized_name$Count$}$()", - "return $name$_.size();\n", - "return $name$Builder_.getCount();\n", + "return $name$_.size();\n", "return $name$Builder_.getCount();\n", - NULL); + NULL); // Field getRepeatedField(int index) WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index)", + PrintNestedBuilderFunction( + printer, + "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index)", - "return $name$_.get(index);\n", + "return $name$_.get(index);\n", - "return $name$Builder_.getMessage(index);\n", + "return $name$Builder_.getMessage(index);\n", - NULL); + NULL); // Builder setRepeatedField(int index, Field value) WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, $type$ value)", - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "ensure$capitalized_name$IsMutable();\n" - "$name$_.set(index, value);\n" - "$on_changed$\n", - "$name$Builder_.setMessage(index, value);\n", - "return this;\n"); + PrintNestedBuilderFunction( + printer, + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " int index, $type$ value)", + "if (value == null) {\n" + " throw new NullPointerException();\n" + "}\n" + "ensure$capitalized_name$IsMutable();\n" + "$name$_.set(index, value);\n" + "$on_changed$\n", + "$name$Builder_.setMessage(index, value);\n", "return this;\n"); // Builder setRepeatedField(int index, Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, $type$.Builder builderForValue)", + PrintNestedBuilderFunction( + printer, + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " int index, $type$.Builder builderForValue)", - "ensure$capitalized_name$IsMutable();\n" - "$name$_.set(index, builderForValue.build());\n" - "$on_changed$\n", + "ensure$capitalized_name$IsMutable();\n" + "$name$_.set(index, builderForValue.build());\n" + "$on_changed$\n", - "$name$Builder_.setMessage(index, builderForValue.build());\n", + "$name$Builder_.setMessage(index, builderForValue.build());\n", - "return this;\n"); + "return this;\n"); // Builder addRepeatedField(Field value) WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value)", + PrintNestedBuilderFunction( + printer, + "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value)", - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "ensure$capitalized_name$IsMutable();\n" - "$name$_.add(value);\n" + "if (value == null) {\n" + " throw new NullPointerException();\n" + "}\n" + "ensure$capitalized_name$IsMutable();\n" + "$name$_.add(value);\n" - "$on_changed$\n", + "$on_changed$\n", - "$name$Builder_.addMessage(value);\n", + "$name$Builder_.addMessage(value);\n", - "return this;\n"); + "return this;\n"); // Builder addRepeatedField(int index, Field value) WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" - " int index, $type$ value)", + PrintNestedBuilderFunction( + printer, + "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" + " int index, $type$ value)", - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "ensure$capitalized_name$IsMutable();\n" - "$name$_.add(index, value);\n" - "$on_changed$\n", + "if (value == null) {\n" + " throw new NullPointerException();\n" + "}\n" + "ensure$capitalized_name$IsMutable();\n" + "$name$_.add(index, value);\n" + "$on_changed$\n", - "$name$Builder_.addMessage(index, value);\n", + "$name$Builder_.addMessage(index, value);\n", - "return this;\n"); + "return this;\n"); // Builder addRepeatedField(Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" - " $type$.Builder builderForValue)", + PrintNestedBuilderFunction( + printer, + "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" + " $type$.Builder builderForValue)", - "ensure$capitalized_name$IsMutable();\n" - "$name$_.add(builderForValue.build());\n" - "$on_changed$\n", + "ensure$capitalized_name$IsMutable();\n" + "$name$_.add(builderForValue.build());\n" + "$on_changed$\n", - "$name$Builder_.addMessage(builderForValue.build());\n", + "$name$Builder_.addMessage(builderForValue.build());\n", - "return this;\n"); + "return this;\n"); // Builder addRepeatedField(int index, Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" - " int index, $type$.Builder builderForValue)", + PrintNestedBuilderFunction( + printer, + "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" + " int index, $type$.Builder builderForValue)", - "ensure$capitalized_name$IsMutable();\n" - "$name$_.add(index, builderForValue.build());\n" - "$on_changed$\n", + "ensure$capitalized_name$IsMutable();\n" + "$name$_.add(index, builderForValue.build());\n" + "$on_changed$\n", - "$name$Builder_.addMessage(index, builderForValue.build());\n", + "$name$Builder_.addMessage(index, builderForValue.build());\n", - "return this;\n"); + "return this;\n"); // Builder addAllRepeatedField(Iterable values) WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" - " java.lang.Iterable values)", + PrintNestedBuilderFunction( + printer, + "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" + " java.lang.Iterable values)", - "ensure$capitalized_name$IsMutable();\n" - "com.google.protobuf.AbstractMessageLite.Builder.addAll(\n" - " values, $name$_);\n" - "$on_changed$\n", + "ensure$capitalized_name$IsMutable();\n" + "com.google.protobuf.AbstractMessageLite.Builder.addAll(\n" + " values, $name$_);\n" + "$on_changed$\n", - "$name$Builder_.addAllMessages(values);\n", + "$name$Builder_.addAllMessages(values);\n", - "return this;\n"); + "return this;\n"); // Builder clearAllRepeatedField() WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$clear$capitalized_name$$}$()", + PrintNestedBuilderFunction( + printer, "$deprecation$public Builder ${$clear$capitalized_name$$}$()", - "$name$_ = java.util.Collections.emptyList();\n" - "$clear_mutable_bit_builder$;\n" - "$on_changed$\n", + "$name$_ = java.util.Collections.emptyList();\n" + "$clear_mutable_bit_builder$;\n" + "$on_changed$\n", - "$name$Builder_.clear();\n", + "$name$Builder_.clear();\n", - "return this;\n"); + "return this;\n"); // Builder removeRepeatedField(int index) WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$remove$capitalized_name$$}$(int index)", + PrintNestedBuilderFunction( + printer, + "$deprecation$public Builder ${$remove$capitalized_name$$}$(int index)", - "ensure$capitalized_name$IsMutable();\n" - "$name$_.remove(index);\n" - "$on_changed$\n", + "ensure$capitalized_name$IsMutable();\n" + "$name$_.remove(index);\n" + "$on_changed$\n", - "$name$Builder_.remove(index);\n", + "$name$Builder_.remove(index);\n", - "return this;\n"); + "return this;\n"); + + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public $type$.Builder ${$get$capitalized_name$Builder$}$(\n" + " int index) {\n" + " return get$capitalized_name$FieldBuilder().getBuilder(index);\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public $type$.Builder ${$get$capitalized_name$Builder$}$(\n" - " int index) {\n" - " return get$capitalized_name$FieldBuilder().getBuilder(index);\n" - "}\n"); + "$deprecation$public $type$OrBuilder " + "${$get$capitalized_name$OrBuilder$}$(\n" + " int index) {\n" + " if ($name$Builder_ == null) {\n" + " return $name$_.get(index);" + " } else {\n" + " return $name$Builder_.getMessageOrBuilder(index);\n" + " }\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder " - "${$get$capitalized_name$OrBuilder$}$(\n" - " int index) {\n" - " if ($name$Builder_ == null) {\n" - " return $name$_.get(index);" - " } else {\n" - " return $name$Builder_.getMessageOrBuilder(index);\n" - " }\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public java.util.List \n" + " ${$get$capitalized_name$OrBuilderList$}$() {\n" + " if ($name$Builder_ != null) {\n" + " return $name$Builder_.getMessageOrBuilderList();\n" + " } else {\n" + " return java.util.Collections.unmodifiableList($name$_);\n" + " }\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List \n" - " ${$get$capitalized_name$OrBuilderList$}$() {\n" - " if ($name$Builder_ != null) {\n" - " return $name$Builder_.getMessageOrBuilderList();\n" - " } else {\n" - " return java.util.Collections.unmodifiableList($name$_);\n" - " }\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$.Builder " - "${$add$capitalized_name$Builder$}$() {\n" - " return get$capitalized_name$FieldBuilder().addBuilder(\n" - " $type$.getDefaultInstance());\n" - "}\n"); + printer->Print(variables_, + "$deprecation$public $type$.Builder " + "${$add$capitalized_name$Builder$}$() {\n" + " return get$capitalized_name$FieldBuilder().addBuilder(\n" + " $type$.getDefaultInstance());\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$.Builder ${$add$capitalized_name$Builder$}$(\n" - " int index) {\n" - " return get$capitalized_name$FieldBuilder().addBuilder(\n" - " index, $type$.getDefaultInstance());\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public $type$.Builder ${$add$capitalized_name$Builder$}$(\n" + " int index) {\n" + " return get$capitalized_name$FieldBuilder().addBuilder(\n" + " index, $type$.getDefaultInstance());\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List<$type$.Builder> \n" - " ${$get$capitalized_name$BuilderList$}$() {\n" - " return get$capitalized_name$FieldBuilder().getBuilderList();\n" - "}\n" - "private com.google.protobuf.RepeatedFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> \n" - " get$capitalized_name$FieldBuilder() {\n" - " if ($name$Builder_ == null) {\n" - " $name$Builder_ = new com.google.protobuf.RepeatedFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder>(\n" - " $name$_,\n" - " $get_mutable_bit_builder$,\n" - " getParentForChildren(),\n" - " isClean());\n" - " $name$_ = null;\n" - " }\n" - " return $name$Builder_;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public java.util.List<$type$.Builder> \n" + " ${$get$capitalized_name$BuilderList$}$() {\n" + " return get$capitalized_name$FieldBuilder().getBuilderList();\n" + "}\n" + "private com.google.protobuf.RepeatedFieldBuilder$ver$<\n" + " $type$, $type$.Builder, $type$OrBuilder> \n" + " get$capitalized_name$FieldBuilder() {\n" + " if ($name$Builder_ == null) {\n" + " $name$Builder_ = new " + "com.google.protobuf.RepeatedFieldBuilder$ver$<\n" + " $type$, $type$.Builder, $type$OrBuilder>(\n" + " $name$_,\n" + " $get_mutable_bit_builder$,\n" + " getParentForChildren(),\n" + " isClean());\n" + " $name$_ = null;\n" + " }\n" + " return $name$Builder_;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } void RepeatedImmutableMessageFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - printer->Print(variables_, - "get$capitalized_name$FieldBuilder();\n"); + GenerateFieldBuilderInitializationCode(io::Printer* printer) const { + printer->Print(variables_, "get$capitalized_name$FieldBuilder();\n"); } -void RepeatedImmutableMessageFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { +void RepeatedImmutableMessageFieldGenerator::GenerateInitializationCode( + io::Printer* printer) const { printer->Print(variables_, "$name$_ = java.util.Collections.emptyList();\n"); } -void RepeatedImmutableMessageFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { +void RepeatedImmutableMessageFieldGenerator::GenerateBuilderClearCode( + io::Printer* printer) const { PrintNestedBuilderCondition(printer, - "$name$_ = java.util.Collections.emptyList();\n" - "$clear_mutable_bit_builder$;\n", + "$name$_ = java.util.Collections.emptyList();\n" + "$clear_mutable_bit_builder$;\n", - "$name$Builder_.clear();\n"); + "$name$Builder_.clear();\n"); } -void RepeatedImmutableMessageFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { +void RepeatedImmutableMessageFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { // The code below does two optimizations (non-nested builder case): // 1. If the other list is empty, there's nothing to do. This ensures we // don't allocate a new array if we already have an immutable one. // 2. If the other list is non-empty and our current list is empty, we can // reuse the other list which is guaranteed to be immutable. - PrintNestedBuilderCondition(printer, - "if (!other.$name$_.isEmpty()) {\n" - " if ($name$_.isEmpty()) {\n" - " $name$_ = other.$name$_;\n" - " $clear_mutable_bit_builder$;\n" - " } else {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.addAll(other.$name$_);\n" - " }\n" - " $on_changed$\n" - "}\n", + PrintNestedBuilderCondition( + printer, + "if (!other.$name$_.isEmpty()) {\n" + " if ($name$_.isEmpty()) {\n" + " $name$_ = other.$name$_;\n" + " $clear_mutable_bit_builder$;\n" + " } else {\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.addAll(other.$name$_);\n" + " }\n" + " $on_changed$\n" + "}\n", - "if (!other.$name$_.isEmpty()) {\n" - " if ($name$Builder_.isEmpty()) {\n" - " $name$Builder_.dispose();\n" - " $name$Builder_ = null;\n" - " $name$_ = other.$name$_;\n" - " $clear_mutable_bit_builder$;\n" - " $name$Builder_ = \n" - " com.google.protobuf.GeneratedMessage$ver$.alwaysUseFieldBuilders ?\n" - " get$capitalized_name$FieldBuilder() : null;\n" - " } else {\n" - " $name$Builder_.addAllMessages(other.$name$_);\n" - " }\n" - "}\n"); + "if (!other.$name$_.isEmpty()) {\n" + " if ($name$Builder_.isEmpty()) {\n" + " $name$Builder_.dispose();\n" + " $name$Builder_ = null;\n" + " $name$_ = other.$name$_;\n" + " $clear_mutable_bit_builder$;\n" + " $name$Builder_ = \n" + " com.google.protobuf.GeneratedMessage$ver$.alwaysUseFieldBuilders " + "?\n" + " get$capitalized_name$FieldBuilder() : null;\n" + " } else {\n" + " $name$Builder_.addAllMessages(other.$name$_);\n" + " }\n" + "}\n"); } -void RepeatedImmutableMessageFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { +void RepeatedImmutableMessageFieldGenerator::GenerateBuildingCode( + io::Printer* printer) const { // The code below (non-nested builder case) ensures that the result has an // immutable list. If our list is immutable, we can just reuse it. If not, // we make it immutable. - PrintNestedBuilderCondition(printer, - "if ($get_mutable_bit_builder$) {\n" - " $name$_ = java.util.Collections.unmodifiableList($name$_);\n" - " $clear_mutable_bit_builder$;\n" - "}\n" - "result.$name$_ = $name$_;\n", + PrintNestedBuilderCondition( + printer, + "if ($get_mutable_bit_builder$) {\n" + " $name$_ = java.util.Collections.unmodifiableList($name$_);\n" + " $clear_mutable_bit_builder$;\n" + "}\n" + "result.$name$_ = $name$_;\n", - "result.$name$_ = $name$Builder_.build();\n"); + "result.$name$_ = $name$Builder_.build();\n"); } -void RepeatedImmutableMessageFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { +void RepeatedImmutableMessageFieldGenerator::GenerateParsingCode( + io::Printer* printer) const { printer->Print(variables_, - "if (!$get_mutable_bit_parser$) {\n" - " $name$_ = new java.util.ArrayList<$type$>();\n" - " $set_mutable_bit_parser$;\n" - "}\n"); + "if (!$get_mutable_bit_parser$) {\n" + " $name$_ = new java.util.ArrayList<$type$>();\n" + " $set_mutable_bit_parser$;\n" + "}\n"); if (GetType(descriptor_) == FieldDescriptor::TYPE_GROUP) { - printer->Print(variables_, - "$name$_.add(input.readGroup($number$, $type$.$get_parser$,\n" - " extensionRegistry));\n"); + printer->Print( + variables_, + "$name$_.add(input.readGroup($number$, $type$.$get_parser$,\n" + " extensionRegistry));\n"); } else { - printer->Print(variables_, - "$name$_.add(\n" - " input.readMessage($type$.$get_parser$, extensionRegistry));\n"); + printer->Print( + variables_, + "$name$_.add(\n" + " input.readMessage($type$.$get_parser$, extensionRegistry));\n"); } } -void RepeatedImmutableMessageFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($get_mutable_bit_parser$) {\n" - " $name$_ = java.util.Collections.unmodifiableList($name$_);\n" - "}\n"); +void RepeatedImmutableMessageFieldGenerator::GenerateParsingDoneCode( + io::Printer* printer) const { + printer->Print( + variables_, + "if ($get_mutable_bit_parser$) {\n" + " $name$_ = java.util.Collections.unmodifiableList($name$_);\n" + "}\n"); } -void RepeatedImmutableMessageFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { +void RepeatedImmutableMessageFieldGenerator::GenerateSerializationCode( + io::Printer* printer) const { printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.write$group_or_message$($number$, $name$_.get(i));\n" - "}\n"); + "for (int i = 0; i < $name$_.size(); i++) {\n" + " output.write$group_or_message$($number$, $name$_.get(i));\n" + "}\n"); } -void RepeatedImmutableMessageFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$group_or_message$Size($number$, $name$_.get(i));\n" - "}\n"); +void RepeatedImmutableMessageFieldGenerator::GenerateSerializedSizeCode( + io::Printer* printer) const { + printer->Print( + variables_, + "for (int i = 0; i < $name$_.size(); i++) {\n" + " size += com.google.protobuf.CodedOutputStream\n" + " .compute$group_or_message$Size($number$, $name$_.get(i));\n" + "}\n"); } -void RepeatedImmutableMessageFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && get$capitalized_name$List()\n" - " .equals(other.get$capitalized_name$List());\n"); +void RepeatedImmutableMessageFieldGenerator::GenerateEqualsCode( + io::Printer* printer) const { + printer->Print( + variables_, + "if (!get$capitalized_name$List()\n" + " .equals(other.get$capitalized_name$List())) return false;\n"); } -void RepeatedImmutableMessageFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "if (get$capitalized_name$Count() > 0) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + get$capitalized_name$List().hashCode();\n" - "}\n"); +void RepeatedImmutableMessageFieldGenerator::GenerateHashCode( + io::Printer* printer) const { + printer->Print( + variables_, + "if (get$capitalized_name$Count() > 0) {\n" + " hash = (37 * hash) + $constant_name$;\n" + " hash = (53 * hash) + get$capitalized_name$List().hashCode();\n" + "}\n"); } -string RepeatedImmutableMessageFieldGenerator::GetBoxedType() const { +std::string RepeatedImmutableMessageFieldGenerator::GetBoxedType() const { return name_resolver_->GetImmutableClassName(descriptor_->message_type()); } diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_field.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_field.h index 7ee0edb2..36fa4920 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_field.h @@ -41,26 +41,30 @@ namespace google { namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } -} +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { class ImmutableMessageFieldGenerator : public ImmutableFieldGenerator { public: - explicit ImmutableMessageFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + explicit ImmutableMessageFieldGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, + int builderBitIndex, + Context* context); ~ImmutableMessageFieldGenerator(); - // implements ImmutableFieldGenerator --------------------------------------- + // implements ImmutableFieldGenerator + // --------------------------------------- int GetNumBitsForMessage() const; int GetNumBitsForBuilder() const; void GenerateInterfaceMembers(io::Printer* printer) const; @@ -78,22 +82,21 @@ class ImmutableMessageFieldGenerator : public ImmutableFieldGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; + std::map variables_; ClassNameResolver* name_resolver_; void PrintNestedBuilderCondition(io::Printer* printer, - const char* regular_case, const char* nested_builder_case) const; + const char* regular_case, + const char* nested_builder_case) const; void PrintNestedBuilderFunction(io::Printer* printer, - const char* method_prototype, const char* regular_case, - const char* nested_builder_case, - const char* trailing_code) const; + const char* method_prototype, + const char* regular_case, + const char* nested_builder_case, + const char* trailing_code) const; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableMessageFieldGenerator); @@ -102,9 +105,9 @@ class ImmutableMessageFieldGenerator : public ImmutableFieldGenerator { class ImmutableMessageOneofFieldGenerator : public ImmutableMessageFieldGenerator { public: - ImmutableMessageOneofFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + ImmutableMessageOneofFieldGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, int builderBitIndex, + Context* context); ~ImmutableMessageOneofFieldGenerator(); void GenerateMembers(io::Printer* printer) const; @@ -144,22 +147,21 @@ class RepeatedImmutableMessageFieldGenerator : public ImmutableFieldGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; + std::map variables_; ClassNameResolver* name_resolver_; void PrintNestedBuilderCondition(io::Printer* printer, - const char* regular_case, const char* nested_builder_case) const; + const char* regular_case, + const char* nested_builder_case) const; void PrintNestedBuilderFunction(io::Printer* printer, - const char* method_prototype, const char* regular_case, - const char* nested_builder_case, - const char* trailing_code) const; + const char* method_prototype, + const char* regular_case, + const char* nested_builder_case, + const char* trailing_code) const; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableMessageFieldGenerator); @@ -168,6 +170,6 @@ class RepeatedImmutableMessageFieldGenerator : public ImmutableFieldGenerator { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_FIELD_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_field_lite.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_field_lite.cc index 9cf6f363..3a6909fc 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_field_lite.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_field_lite.cc @@ -36,14 +36,15 @@ #include #include -#include #include #include +#include #include #include #include #include + namespace google { namespace protobuf { namespace compiler { @@ -51,12 +52,10 @@ namespace java { namespace { -void SetMessageVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - const FieldGeneratorInfo* info, +void SetMessageVariables(const FieldDescriptor* descriptor, int messageBitIndex, + int builderBitIndex, const FieldGeneratorInfo* info, ClassNameResolver* name_resolver, - std::map* variables) { + std::map* variables) { SetCommonFieldVariables(descriptor, info, variables); (*variables)["type"] = @@ -64,12 +63,12 @@ void SetMessageVariables(const FieldDescriptor* descriptor, (*variables)["mutable_type"] = name_resolver->GetMutableClassName(descriptor->message_type()); (*variables)["group_or_message"] = - (GetType(descriptor) == FieldDescriptor::TYPE_GROUP) ? - "Group" : "Message"; + (GetType(descriptor) == FieldDescriptor::TYPE_GROUP) ? "Group" + : "Message"; // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; + (*variables)["deprecation"] = + descriptor->options().deprecated() ? "@java.lang.Deprecated " : ""; (*variables)["required"] = descriptor->is_required() ? "true" : "false"; if (SupportFieldPresence(descriptor->file())) { @@ -104,890 +103,701 @@ void SetMessageVariables(const FieldDescriptor* descriptor, // =================================================================== -ImmutableMessageFieldLiteGenerator:: -ImmutableMessageFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetMessageVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); +ImmutableMessageFieldLiteGenerator::ImmutableMessageFieldLiteGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, Context* context) + : descriptor_(descriptor), + messageBitIndex_(messageBitIndex), + name_resolver_(context->GetNameResolver()) { + SetMessageVariables(descriptor, messageBitIndex, 0, + context->GetFieldGeneratorInfo(descriptor), + name_resolver_, &variables_); } ImmutableMessageFieldLiteGenerator::~ImmutableMessageFieldLiteGenerator() {} int ImmutableMessageFieldLiteGenerator::GetNumBitsForMessage() const { - return 1; + return SupportFieldPresence(descriptor_->file()) ? 1 : 0; } -int ImmutableMessageFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { +void ImmutableMessageFieldLiteGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); + printer->Print(variables_, "$deprecation$boolean has$capitalized_name$();\n"); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$();\n"); + printer->Print(variables_, "$deprecation$$type$ get$capitalized_name$();\n"); } -void ImmutableMessageFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { +void ImmutableMessageFieldLiteGenerator::GenerateMembers( + io::Printer* printer) const { - printer->Print(variables_, - "private $type$ $name$_;\n"); + printer->Print(variables_, "private $type$ $name$_;\n"); PrintExtraFieldInfo(variables_, printer); if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $get_has_field_bit_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } else { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $name$_ != null;\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $name$_ != null;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } // Field.Builder setField(Field value) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void set$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " $name$_ = value;\n" - " $set_has_field_bit_message$\n" - " }\n"); + "private void set$capitalized_name$($type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" + " $name$_ = value;\n" + " $set_has_field_bit_message$\n" + " }\n"); // Field.Builder setField(Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void set$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " $name$_ = builderForValue.build();\n" - " $set_has_field_bit_message$\n" - "}\n"); + "private void set$capitalized_name$(\n" + " $type$.Builder builderForValue) {\n" + " $name$_ = builderForValue.build();\n" + " $set_has_field_bit_message$\n" + "}\n"); // Field.Builder mergeField(Field value) WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.SuppressWarnings({\"ReferenceEquality\"})\n" - "private void merge$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " if ($name$_ != null &&\n" - " $name$_ != $type$.getDefaultInstance()) {\n" - " $name$_ =\n" - " $type$.newBuilder($name$_).mergeFrom(value).buildPartial();\n" - " } else {\n" - " $name$_ = value;\n" - " }\n" - " $set_has_field_bit_message$\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.SuppressWarnings({\"ReferenceEquality\"})\n" + "private void merge$capitalized_name$($type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" + " if ($name$_ != null &&\n" + " $name$_ != $type$.getDefaultInstance()) {\n" + " $name$_ =\n" + " $type$.newBuilder($name$_).mergeFrom(value).buildPartial();\n" + " } else {\n" + " $name$_ = value;\n" + " }\n" + " $set_has_field_bit_message$\n" + "}\n"); // Field.Builder clearField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void clear$capitalized_name$() {" - " $name$_ = null;\n" - " $clear_has_field_bit_message$\n" - "}\n"); + "private void clear$capitalized_name$() {" + " $name$_ = null;\n" + " $clear_has_field_bit_message$\n" + "}\n"); } -void ImmutableMessageFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void ImmutableMessageFieldLiteGenerator::GenerateBuilderMembers( + io::Printer* printer) const { // The comments above the methods below are based on a hypothetical // field of type "Field" called "Field". // boolean hasField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return instance.has$capitalized_name$();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Field getField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " return instance.get$capitalized_name$();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Field.Builder setField(Field value) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - " }\n"); + "$deprecation$public Builder " + "${$set$capitalized_name$$}$($type$ value) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$(value);\n" + " return this;\n" + " }\n"); printer->Annotate("{", "}", descriptor_); // Field.Builder setField(Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(builderForValue);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " $type$.Builder builderForValue) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$(builderForValue);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Field.Builder mergeField(Field value) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder " - "${$merge$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.merge$capitalized_name$(value);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder " + "${$merge$capitalized_name$$}$($type$ value) {\n" + " copyOnWrite();\n" + " instance.merge$capitalized_name$(value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Field.Builder clearField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {" + " copyOnWrite();\n" + " instance.clear$capitalized_name$();\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } -void ImmutableMessageFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { + +void ImmutableMessageFieldLiteGenerator::GenerateFieldInfo( + io::Printer* printer, std::vector* output) const { + WriteIntToUtf16CharSequence(descriptor_->number(), output); + WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_), + output); if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "get$capitalized_name$FieldBuilder();\n"); + WriteIntToUtf16CharSequence(messageBitIndex_, output); } + printer->Print(variables_, "\"$name$_\",\n"); } +void ImmutableMessageFieldLiteGenerator::GenerateInitializationCode( + io::Printer* printer) const {} -void ImmutableMessageFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const {} - -void ImmutableMessageFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_ = visitor.visitMessage($name$_, other.$name$_);\n"); -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - // noop for scalars -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - // TODO(dweis): Update this code to avoid the builder allocation and instead - // only allocate a submessage that isn't made immutable. Rely on the top - // message calling makeImmutable once done to actually traverse the tree and - // finalize state. This will avoid: - // - transitive builder allocations - // - the extra transitive iteration for streamed fields - // - reallocations for copying repeated fields - printer->Print(variables_, - "$type$.Builder subBuilder = null;\n" - "if ($is_field_present_message$) {\n" - " subBuilder = $name$_.toBuilder();\n" - "}\n"); - - if (GetType(descriptor_) == FieldDescriptor::TYPE_GROUP) { - printer->Print(variables_, - "$name$_ = input.readGroup($number$, $type$.parser(),\n" - " extensionRegistry);\n"); - } else { - printer->Print(variables_, - "$name$_ = input.readMessage($type$.parser(), extensionRegistry);\n"); - } - - printer->Print(variables_, - "if (subBuilder != null) {\n" - " subBuilder.mergeFrom($name$_);\n" - " $name$_ = subBuilder.buildPartial();\n" - "}\n" - "$set_has_field_bit_message$\n"); -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - // noop for messages. -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " output.write$group_or_message$($number$, get$capitalized_name$());\n" - "}\n"); -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$group_or_message$Size($number$, get$capitalized_name$());\n" - "}\n"); -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && get$capitalized_name$()\n" - " .equals(other.get$capitalized_name$());\n"); -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n" - "hash = (53 * hash) + get$capitalized_name$().hashCode();\n"); -} - -string ImmutableMessageFieldLiteGenerator::GetBoxedType() const { +std::string ImmutableMessageFieldLiteGenerator::GetBoxedType() const { return name_resolver_->GetImmutableClassName(descriptor_->message_type()); } // =================================================================== ImmutableMessageOneofFieldLiteGenerator:: -ImmutableMessageOneofFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableMessageFieldLiteGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { + ImmutableMessageOneofFieldLiteGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, + Context* context) + : ImmutableMessageFieldLiteGenerator(descriptor, messageBitIndex, context) { const OneofGeneratorInfo* info = context->GetOneofGeneratorInfo(descriptor->containing_oneof()); SetCommonOneofVariables(descriptor, info, &variables_); } ImmutableMessageOneofFieldLiteGenerator:: -~ImmutableMessageOneofFieldLiteGenerator() {} + ~ImmutableMessageOneofFieldLiteGenerator() {} -void ImmutableMessageOneofFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { +void ImmutableMessageOneofFieldLiteGenerator::GenerateMembers( + io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $has_oneof_case_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($type$) $oneof_name$_;\n" - " }\n" - " return $type$.getDefaultInstance();\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " if ($has_oneof_case_message$) {\n" + " return ($type$) $oneof_name$_;\n" + " }\n" + " return $type$.getDefaultInstance();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Field.Builder setField(Field value) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void set$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " $oneof_name$_ = value;\n" - " $set_oneof_case_message$;\n" - "}\n"); + "private void set$capitalized_name$($type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" + " $oneof_name$_ = value;\n" + " $set_oneof_case_message$;\n" + "}\n"); // Field.Builder setField(Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void set$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " $oneof_name$_ = builderForValue.build();\n" - " $set_oneof_case_message$;\n" - "}\n"); + "private void set$capitalized_name$(\n" + " $type$.Builder builderForValue) {\n" + " $oneof_name$_ = builderForValue.build();\n" + " $set_oneof_case_message$;\n" + "}\n"); // Field.Builder mergeField(Field value) WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void merge$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " if ($has_oneof_case_message$ &&\n" - " $oneof_name$_ != $type$.getDefaultInstance()) {\n" - " $oneof_name$_ = $type$.newBuilder(($type$) $oneof_name$_)\n" - " .mergeFrom(value).buildPartial();\n" - " } else {\n" - " $oneof_name$_ = value;\n" - " }\n" - " $set_oneof_case_message$;\n" - "}\n"); + printer->Print( + variables_, + "private void merge$capitalized_name$($type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" + " if ($has_oneof_case_message$ &&\n" + " $oneof_name$_ != $type$.getDefaultInstance()) {\n" + " $oneof_name$_ = $type$.newBuilder(($type$) $oneof_name$_)\n" + " .mergeFrom(value).buildPartial();\n" + " } else {\n" + " $oneof_name$_ = value;\n" + " }\n" + " $set_oneof_case_message$;\n" + "}\n"); // Field.Builder clearField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " }\n" - "}\n"); + "private void clear$capitalized_name$() {\n" + " if ($has_oneof_case_message$) {\n" + " $clear_oneof_case_message$;\n" + " $oneof_name$_ = null;\n" + " }\n" + "}\n"); } +void ImmutableMessageOneofFieldLiteGenerator::GenerateFieldInfo( + io::Printer* printer, std::vector* output) const { + WriteIntToUtf16CharSequence(descriptor_->number(), output); + WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_), + output); + WriteIntToUtf16CharSequence(descriptor_->containing_oneof()->index(), output); + printer->Print(variables_, "$oneof_stored_type$.class,\n"); +} -void ImmutableMessageOneofFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void ImmutableMessageOneofFieldLiteGenerator::GenerateBuilderMembers( + io::Printer* printer) const { // The comments above the methods below are based on a hypothetical // field of type "Field" called "Field". // boolean hasField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return instance.has$capitalized_name$();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Field getField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " return instance.get$capitalized_name$();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Field.Builder setField(Field value) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder " + "${$set$capitalized_name$$}$($type$ value) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$(value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Field.Builder setField(Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(builderForValue);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " $type$.Builder builderForValue) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$(builderForValue);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Field.Builder mergeField(Field value) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder " - "${$merge$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.merge$capitalized_name$(value);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder " + "${$merge$capitalized_name$$}$($type$ value) {\n" + " copyOnWrite();\n" + " instance.merge$capitalized_name$(value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Field.Builder clearField() WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " copyOnWrite();\n" + " instance.clear$capitalized_name$();\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } -void ImmutableMessageOneofFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$oneof_name$_ = visitor.visitOneofMessage(\n" - " $has_oneof_case_message$,\n" - " $oneof_name$_,\n" - " other.$oneof_name$_);\n"); -} - -void ImmutableMessageOneofFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "$type$.Builder subBuilder = null;\n" - "if ($has_oneof_case_message$) {\n" - " subBuilder = (($type$) $oneof_name$_).toBuilder();\n" - "}\n"); - - if (GetType(descriptor_) == FieldDescriptor::TYPE_GROUP) { - printer->Print(variables_, - "$oneof_name$_ = input.readGroup($number$, $type$.parser(),\n" - " extensionRegistry);\n"); - } else { - printer->Print(variables_, - "$oneof_name$_ =\n" - " input.readMessage($type$.parser(), extensionRegistry);\n"); - } - - printer->Print(variables_, - "if (subBuilder != null) {\n" - " subBuilder.mergeFrom(($type$) $oneof_name$_);\n" - " $oneof_name$_ = subBuilder.buildPartial();\n" - "}\n"); - printer->Print(variables_, - "$set_oneof_case_message$;\n"); -} - -void ImmutableMessageOneofFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.write$group_or_message$($number$, ($type$) $oneof_name$_);\n" - "}\n"); -} - -void ImmutableMessageOneofFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$group_or_message$Size($number$, ($type$) $oneof_name$_);\n" - "}\n"); -} - // =================================================================== RepeatedImmutableMessageFieldLiteGenerator:: -RepeatedImmutableMessageFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetMessageVariables(descriptor, messageBitIndex, builderBitIndex, + RepeatedImmutableMessageFieldLiteGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, + Context* context) + : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) { + SetMessageVariables(descriptor, messageBitIndex, 0, context->GetFieldGeneratorInfo(descriptor), name_resolver_, &variables_); } RepeatedImmutableMessageFieldLiteGenerator:: -~RepeatedImmutableMessageFieldLiteGenerator() {} + ~RepeatedImmutableMessageFieldLiteGenerator() {} int RepeatedImmutableMessageFieldLiteGenerator::GetNumBitsForMessage() const { return 0; } -int RepeatedImmutableMessageFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { +void RepeatedImmutableMessageFieldLiteGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { // TODO(jonp): In the future, consider having methods specific to the // interface so that builders can choose dynamically to either return a // message or a nested builder, so that asking for the interface doesn't // cause a message to ever be built. WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$java.util.List<$type$> \n" - " get$capitalized_name$List();\n"); + "$deprecation$java.util.List<$type$> \n" + " get$capitalized_name$List();\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$(int index);\n"); + "$deprecation$$type$ get$capitalized_name$(int index);\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); + "$deprecation$int get$capitalized_name$Count();\n"); } -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private com.google.protobuf.Internal.ProtobufList<$type$> $name$_;\n"); +void RepeatedImmutableMessageFieldLiteGenerator::GenerateMembers( + io::Printer* printer) const { + printer->Print( + variables_, + "private com.google.protobuf.Internal.ProtobufList<$type$> $name$_;\n"); PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List<$type$> " - "${$get$capitalized_name$List$}$() {\n" - " return $name$_;\n" // note: unmodifiable list - "}\n"); + "@java.lang.Override\n" + "$deprecation$public java.util.List<$type$> " + "${$get$capitalized_name$List$}$() {\n" + " return $name$_;\n" // note: unmodifiable list + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public java.util.List \n" + " ${$get$capitalized_name$OrBuilderList$}$() {\n" + " return $name$_;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" + " return $name$_.size();\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" + " return $name$_.get(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public java.util.List \n" - " ${$get$capitalized_name$OrBuilderList$}$() {\n" - " return $name$_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder " - "${$get$capitalized_name$OrBuilder$}$(\n" - " int index) {\n" - " return $name$_.get(index);\n" - "}\n"); + "$deprecation$public $type$OrBuilder " + "${$get$capitalized_name$OrBuilder$}$(\n" + " int index) {\n" + " return $name$_.get(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - " }\n" - "}\n" - "\n"); + printer->Print( + variables_, + "private void ensure$capitalized_name$IsMutable() {\n" + " if (!$is_mutable$) {\n" + " $name$_ =\n" + " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" + " }\n" + "}\n" + "\n"); // Builder setRepeatedField(int index, Field value) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void set$capitalized_name$(\n" - " int index, $type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(index, value);\n" - "}\n"); + "private void set$capitalized_name$(\n" + " int index, $type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.set(index, value);\n" + "}\n"); // Builder setRepeatedField(int index, Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void set$capitalized_name$(\n" - " int index, $type$.Builder builderForValue) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(index, builderForValue.build());\n" - "}\n"); + "private void set$capitalized_name$(\n" + " int index, $type$.Builder builderForValue) {\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.set(index, builderForValue.build());\n" + "}\n"); // Builder addRepeatedField(Field value) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void add$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(value);\n" - "}\n"); + "private void add$capitalized_name$($type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.add(value);\n" + "}\n"); // Builder addRepeatedField(int index, Field value) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void add$capitalized_name$(\n" - " int index, $type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(index, value);\n" - "}\n"); + "private void add$capitalized_name$(\n" + " int index, $type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.add(index, value);\n" + "}\n"); // Builder addRepeatedField(Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void add$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(builderForValue.build());\n" - "}\n"); + "private void add$capitalized_name$(\n" + " $type$.Builder builderForValue) {\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.add(builderForValue.build());\n" + "}\n"); // Builder addRepeatedField(int index, Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void add$capitalized_name$(\n" - " int index, $type$.Builder builderForValue) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(index, builderForValue.build());\n" - "}\n"); + "private void add$capitalized_name$(\n" + " int index, $type$.Builder builderForValue) {\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.add(index, builderForValue.build());\n" + "}\n"); // Builder addAllRepeatedField(Iterable values) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void addAll$capitalized_name$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " com.google.protobuf.AbstractMessageLite.addAll(\n" - " values, $name$_);\n" - "}\n"); + "private void addAll$capitalized_name$(\n" + " java.lang.Iterable values) {\n" + " ensure$capitalized_name$IsMutable();\n" + " com.google.protobuf.AbstractMessageLite.addAll(\n" + " values, $name$_);\n" + "}\n"); // Builder clearAllRepeatedField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $name$_ = emptyProtobufList();\n" - "}\n"); + "private void clear$capitalized_name$() {\n" + " $name$_ = emptyProtobufList();\n" + "}\n"); // Builder removeRepeatedField(int index) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void remove$capitalized_name$(int index) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.remove(index);\n" - "}\n"); + "private void remove$capitalized_name$(int index) {\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.remove(index);\n" + "}\n"); } -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void RepeatedImmutableMessageFieldLiteGenerator::GenerateBuilderMembers( + io::Printer* printer) const { // The comments above the methods below are based on a hypothetical // repeated field of type "Field" called "RepeatedField". // List getRepeatedFieldList() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List<$type$> " - "${$get$capitalized_name$List$}$() {\n" - " return java.util.Collections.unmodifiableList(\n" - " instance.get$capitalized_name$List());\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public java.util.List<$type$> " + "${$get$capitalized_name$List$}$() {\n" + " return java.util.Collections.unmodifiableList(\n" + " instance.get$capitalized_name$List());\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // int getRepeatedFieldCount() WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return instance.get$capitalized_name$Count();\n" - "}"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" + " return instance.get$capitalized_name$Count();\n" + "}"); printer->Annotate("{", "}", descriptor_); // Field getRepeatedField(int index) WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return instance.get$capitalized_name$(index);\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" + " return instance.get$capitalized_name$(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Builder setRepeatedField(int index, Field value) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, $type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(index, value);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " int index, $type$ value) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$(index, value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Builder setRepeatedField(int index, Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(index, builderForValue);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " int index, $type$.Builder builderForValue) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$(index, builderForValue);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Builder addRepeatedField(Field value) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(value);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder " + "${$add$capitalized_name$$}$($type$ value) {\n" + " copyOnWrite();\n" + " instance.add$capitalized_name$(value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Builder addRepeatedField(int index, Field value) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" - " int index, $type$ value) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(index, value);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" + " int index, $type$ value) {\n" + " copyOnWrite();\n" + " instance.add$capitalized_name$(index, value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Builder addRepeatedField(Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" - " $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(builderForValue);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" + " $type$.Builder builderForValue) {\n" + " copyOnWrite();\n" + " instance.add$capitalized_name$(builderForValue);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Builder addRepeatedField(int index, Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" - " int index, $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(index, builderForValue);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" + " int index, $type$.Builder builderForValue) {\n" + " copyOnWrite();\n" + " instance.add$capitalized_name$(index, builderForValue);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Builder addAllRepeatedField(Iterable values) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" - " java.lang.Iterable values) {\n" - " copyOnWrite();\n" - " instance.addAll$capitalized_name$(values);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" + " java.lang.Iterable values) {\n" + " copyOnWrite();\n" + " instance.addAll$capitalized_name$(values);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Builder clearAllRepeatedField() WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " copyOnWrite();\n" + " instance.clear$capitalized_name$();\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); // Builder removeRepeatedField(int index) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$remove$capitalized_name$$}$(int index) {\n" - " copyOnWrite();\n" - " instance.remove$capitalized_name$(index);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder " + "${$remove$capitalized_name$$}$(int index) {\n" + " copyOnWrite();\n" + " instance.remove$capitalized_name$(index);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { + +void RepeatedImmutableMessageFieldLiteGenerator::GenerateFieldInfo( + io::Printer* printer, std::vector* output) const { + WriteIntToUtf16CharSequence(descriptor_->number(), output); + WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_), + output); printer->Print(variables_, - "get$capitalized_name$FieldBuilder();\n"); + "\"$name$_\",\n" + "$type$.class,\n"); } - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const { +void RepeatedImmutableMessageFieldLiteGenerator::GenerateInitializationCode( + io::Printer* printer) const { printer->Print(variables_, "$name$_ = emptyProtobufList();\n"); } -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_= visitor.visitList($name$_, other.$name$_);\n"); -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_.makeImmutable();\n"); -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - "}\n"); - - if (GetType(descriptor_) == FieldDescriptor::TYPE_GROUP) { - printer->Print(variables_, - "$name$_.add(input.readGroup($number$, $type$.parser(),\n" - " extensionRegistry));\n"); - } else { - printer->Print(variables_, - "$name$_.add(\n" - " input.readMessage($type$.parser(), extensionRegistry));\n"); - } -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_mutable$) {\n" - " $name$_.makeImmutable();\n" - "}\n"); -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.write$group_or_message$($number$, $name$_.get(i));\n" - "}\n"); -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$group_or_message$Size($number$, $name$_.get(i));\n" - "}\n"); -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && get$capitalized_name$List()\n" - " .equals(other.get$capitalized_name$List());\n"); -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "if (get$capitalized_name$Count() > 0) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + get$capitalized_name$List().hashCode();\n" - "}\n"); -} - -string RepeatedImmutableMessageFieldLiteGenerator::GetBoxedType() const { +std::string RepeatedImmutableMessageFieldLiteGenerator::GetBoxedType() const { return name_resolver_->GetImmutableClassName(descriptor_->message_type()); } diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_field_lite.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_field_lite.h index 7c814c6d..c0a9b37f 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_field_lite.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_field_lite.h @@ -41,50 +41,43 @@ namespace google { namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } -} +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { class ImmutableMessageFieldLiteGenerator : public ImmutableFieldLiteGenerator { public: - explicit ImmutableMessageFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + explicit ImmutableMessageFieldLiteGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, + Context* context); ~ImmutableMessageFieldLiteGenerator(); - // implements ImmutableFieldLiteGenerator ------------------------------------ + // implements ImmutableFieldLiteGenerator + // ------------------------------------ int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; void GenerateInterfaceMembers(io::Printer* printer) const; void GenerateMembers(io::Printer* printer) const; void GenerateBuilderMembers(io::Printer* printer) const; void GenerateInitializationCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; + void GenerateFieldInfo(io::Printer* printer, + std::vector* output) const; - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; ClassNameResolver* name_resolver_; private: @@ -94,18 +87,15 @@ class ImmutableMessageFieldLiteGenerator : public ImmutableFieldLiteGenerator { class ImmutableMessageOneofFieldLiteGenerator : public ImmutableMessageFieldLiteGenerator { public: - ImmutableMessageOneofFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + ImmutableMessageOneofFieldLiteGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, + Context* context); ~ImmutableMessageOneofFieldLiteGenerator(); void GenerateMembers(io::Printer* printer) const; void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - + void GenerateFieldInfo(io::Printer* printer, + std::vector* output) const; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableMessageOneofFieldLiteGenerator); @@ -115,36 +105,23 @@ class RepeatedImmutableMessageFieldLiteGenerator : public ImmutableFieldLiteGenerator { public: explicit RepeatedImmutableMessageFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + const FieldDescriptor* descriptor, int messageBitIndex, Context* context); ~RepeatedImmutableMessageFieldLiteGenerator(); // implements ImmutableFieldLiteGenerator ------------------------------------ int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; void GenerateInterfaceMembers(io::Printer* printer) const; void GenerateMembers(io::Printer* printer) const; void GenerateBuilderMembers(io::Printer* printer) const; void GenerateInitializationCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; + void GenerateFieldInfo(io::Printer* printer, + std::vector* output) const; - - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; + std::map variables_; ClassNameResolver* name_resolver_; private: @@ -154,6 +131,6 @@ class RepeatedImmutableMessageFieldLiteGenerator } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_FIELD_LITE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_lite.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_lite.cc index 3a512e8d..73e0b9db 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_lite.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_lite.cc @@ -35,7 +35,6 @@ #include #include -#include #include #include #include @@ -53,8 +52,9 @@ #include #include #include -#include #include +#include + namespace google { @@ -65,34 +65,13 @@ namespace java { using internal::WireFormat; using internal::WireFormatLite; -namespace { -bool EnableExperimentalRuntimeForLite() { -#ifdef PROTOBUF_EXPERIMENT - return PROTOBUF_EXPERIMENT; -#else // PROTOBUF_EXPERIMENT - return false; -#endif // !PROTOBUF_EXPERIMENT -} - -bool GenerateHasBits(const Descriptor* descriptor) { - return SupportFieldPresence(descriptor->file()) || - HasRepeatedFields(descriptor); -} - -string MapValueImmutableClassdName(const Descriptor* descriptor, - ClassNameResolver* name_resolver) { - const FieldDescriptor* value_field = descriptor->FindFieldByName("value"); - GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, value_field->type()); - return name_resolver->GetImmutableClassName(value_field->message_type()); -} -} // namespace - // =================================================================== ImmutableMessageLiteGenerator::ImmutableMessageLiteGenerator( const Descriptor* descriptor, Context* context) - : MessageGenerator(descriptor), context_(context), - name_resolver_(context->GetNameResolver()), - field_generators_(descriptor, context_) { + : MessageGenerator(descriptor), + context_(context), + name_resolver_(context->GetNameResolver()), + field_generators_(descriptor, context_) { GOOGLE_CHECK(!HasDescriptorMethods(descriptor->file(), context->EnforceLite())) << "Generator factory error: A lite message generator is used to " "generate non-lite messages."; @@ -135,41 +114,39 @@ void ImmutableMessageLiteGenerator::GenerateInterface(io::Printer* printer) { " com.google.protobuf.GeneratedMessageLite.\n" " ExtendableMessageOrBuilder<\n" " $classname$, $classname$.Builder> {\n", - "deprecation", descriptor_->options().deprecated() ? - "@java.lang.Deprecated " : "", + "deprecation", + descriptor_->options().deprecated() ? "@java.lang.Deprecated " : "", "extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_), - "classname", descriptor_->name(), - "{", "", "}", ""); + "classname", descriptor_->name(), "{", "", "}", ""); } else { printer->Print( "$deprecation$public interface ${$$classname$OrBuilder$}$ extends\n" " $extra_interfaces$\n" " com.google.protobuf.MessageLiteOrBuilder {\n", - "deprecation", descriptor_->options().deprecated() ? - "@java.lang.Deprecated " : "", + "deprecation", + descriptor_->options().deprecated() ? "@java.lang.Deprecated " : "", "extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_), - "classname", descriptor_->name(), - "{", "", "}", ""); + "classname", descriptor_->name(), "{", "", "}", ""); } printer->Annotate("{", "}", descriptor_); printer->Indent(); - for (int i = 0; i < descriptor_->field_count(); i++) { - printer->Print("\n"); - field_generators_.get(descriptor_->field(i)) - .GenerateInterfaceMembers(printer); - } - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "\n" - "public $classname$.$oneof_capitalized_name$Case " - "get$oneof_capitalized_name$Case();\n", - "oneof_capitalized_name", - context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->capitalized_name, - "classname", - context_->GetNameResolver()->GetImmutableClassName(descriptor_)); - } + for (int i = 0; i < descriptor_->field_count(); i++) { + printer->Print("\n"); + field_generators_.get(descriptor_->field(i)) + .GenerateInterfaceMembers(printer); + } + for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { + printer->Print( + "\n" + "public $classname$.$oneof_capitalized_name$Case " + "get$oneof_capitalized_name$Case();\n", + "oneof_capitalized_name", + context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i)) + ->capitalized_name, + "classname", + context_->GetNameResolver()->GetImmutableClassName(descriptor_)); + } printer->Outdent(); printer->Print("}\n"); @@ -180,12 +157,12 @@ void ImmutableMessageLiteGenerator::GenerateInterface(io::Printer* printer) { void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { bool is_own_file = IsOwnFile(descriptor_, /* immutable = */ true); - std::map variables; + std::map variables; variables["static"] = is_own_file ? " " : " static "; variables["classname"] = descriptor_->name(); variables["extra_interfaces"] = ExtraMessageInterfaces(descriptor_); - variables["deprecation"] = descriptor_->options().deprecated() - ? "@java.lang.Deprecated " : ""; + variables["deprecation"] = + descriptor_->options().deprecated() ? "@java.lang.Deprecated " : ""; WriteMessageDocComment(printer, descriptor_); MaybePrintGeneratedAnnotation(context_, printer, descriptor_, @@ -193,19 +170,21 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { // The builder_type stores the super type name of the nested Builder class. - string builder_type; + std::string builder_type; if (descriptor_->extension_range_count() > 0) { - printer->Print(variables, - "$deprecation$public $static$final class $classname$ extends\n" - " com.google.protobuf.GeneratedMessageLite.ExtendableMessage<\n" - " $classname$, $classname$.Builder> implements\n" - " $extra_interfaces$\n" - " $classname$OrBuilder {\n"); + printer->Print( + variables, + "$deprecation$public $static$final class $classname$ extends\n" + " com.google.protobuf.GeneratedMessageLite.ExtendableMessage<\n" + " $classname$, $classname$.Builder> implements\n" + " $extra_interfaces$\n" + " $classname$OrBuilder {\n"); builder_type = strings::Substitute( "com.google.protobuf.GeneratedMessageLite.ExtendableBuilder<$0, ?>", name_resolver_->GetImmutableClassName(descriptor_)); } else { - printer->Print(variables, + printer->Print( + variables, "$deprecation$public $static$final class $classname$ extends\n" " com.google.protobuf.GeneratedMessageLite<\n" " $classname$, $classname$.Builder> implements\n" @@ -227,122 +206,109 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { for (int i = 0; i < descriptor_->nested_type_count(); i++) { // Don't generate Java classes for map entry messages. if (IsMapEntry(descriptor_->nested_type(i))) continue; - ImmutableMessageLiteGenerator messageGenerator( - descriptor_->nested_type(i), context_); + ImmutableMessageLiteGenerator messageGenerator(descriptor_->nested_type(i), + context_); messageGenerator.GenerateInterface(printer); messageGenerator.Generate(printer); } - if (GenerateHasBits(descriptor_)) { - // Integers for bit fields. - int totalBits = 0; - for (int i = 0; i < descriptor_->field_count(); i++) { - totalBits += field_generators_.get(descriptor_->field(i)) - .GetNumBitsForMessage(); - } - int totalInts = (totalBits + 31) / 32; - for (int i = 0; i < totalInts; i++) { - printer->Print("private int $bit_field_name$;\n", - "bit_field_name", GetBitFieldName(i)); - } + // Integers for bit fields. + int totalBits = 0; + for (int i = 0; i < descriptor_->field_count(); i++) { + totalBits += + field_generators_.get(descriptor_->field(i)).GetNumBitsForMessage(); + } + int totalInts = (totalBits + 31) / 32; + for (int i = 0; i < totalInts; i++) { + printer->Print("private int $bit_field_name$;\n", "bit_field_name", + GetBitFieldName(i)); } // oneof - std::map vars; + std::map vars; for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { const OneofDescriptor* oneof = descriptor_->oneof_decl(i); vars["oneof_name"] = context_->GetOneofGeneratorInfo(oneof)->name; - vars["oneof_capitalized_name"] = context_->GetOneofGeneratorInfo( - oneof)->capitalized_name; - vars["oneof_index"] = SimpleItoa(oneof->index()); + vars["oneof_capitalized_name"] = + context_->GetOneofGeneratorInfo(oneof)->capitalized_name; + vars["oneof_index"] = StrCat(oneof->index()); // oneofCase_ and oneof_ printer->Print(vars, - "private int $oneof_name$Case_ = 0;\n" - "private java.lang.Object $oneof_name$_;\n"); + "private int $oneof_name$Case_ = 0;\n" + "private java.lang.Object $oneof_name$_;\n"); // OneofCase enum printer->Print(vars, - "public enum $oneof_capitalized_name$Case\n" - " implements com.google.protobuf.Internal.EnumLite {\n"); + "public enum $oneof_capitalized_name$Case\n" + " implements com.google.protobuf.Internal.EnumLite {\n"); printer->Indent(); for (int j = 0; j < oneof->field_count(); j++) { const FieldDescriptor* field = oneof->field(j); - printer->Print( - "$field_name$($field_number$),\n", - "field_name", - ToUpper(field->name()), - "field_number", - SimpleItoa(field->number())); + printer->Print("$field_name$($field_number$),\n", "field_name", + ToUpper(field->name()), "field_number", + StrCat(field->number())); } + printer->Print("$cap_oneof_name$_NOT_SET(0);\n", "cap_oneof_name", + ToUpper(vars["oneof_name"])); + printer->Print(vars, + "private final int value;\n" + "private $oneof_capitalized_name$Case(int value) {\n" + " this.value = value;\n" + "}\n"); printer->Print( - "$cap_oneof_name$_NOT_SET(0);\n", - "cap_oneof_name", - ToUpper(vars["oneof_name"])); - printer->Print(vars, - "private final int value;\n" - "private $oneof_capitalized_name$Case(int value) {\n" - " this.value = value;\n" - "}\n"); - printer->Print(vars, - "/**\n" - " * @deprecated Use {@link #forNumber(int)} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public static $oneof_capitalized_name$Case valueOf(int value) {\n" - " return forNumber(value);\n" - "}\n" - "\n" - "public static $oneof_capitalized_name$Case forNumber(int value) {\n" - " switch (value) {\n"); + vars, + "/**\n" + " * @deprecated Use {@link #forNumber(int)} instead.\n" + " */\n" + "@java.lang.Deprecated\n" + "public static $oneof_capitalized_name$Case valueOf(int value) {\n" + " return forNumber(value);\n" + "}\n" + "\n" + "public static $oneof_capitalized_name$Case forNumber(int value) {\n" + " switch (value) {\n"); for (int j = 0; j < oneof->field_count(); j++) { const FieldDescriptor* field = oneof->field(j); - printer->Print( - " case $field_number$: return $field_name$;\n", - "field_number", - SimpleItoa(field->number()), - "field_name", - ToUpper(field->name())); + printer->Print(" case $field_number$: return $field_name$;\n", + "field_number", StrCat(field->number()), + "field_name", ToUpper(field->name())); } printer->Print( - " case 0: return $cap_oneof_name$_NOT_SET;\n" - " default: return null;\n" - " }\n" - "}\n" - "@java.lang.Override\n" - "public int getNumber() {\n" - " return this.value;\n" - "}\n", - "cap_oneof_name", ToUpper(vars["oneof_name"])); + " case 0: return $cap_oneof_name$_NOT_SET;\n" + " default: return null;\n" + " }\n" + "}\n" + "@java.lang.Override\n" + "public int getNumber() {\n" + " return this.value;\n" + "}\n", + "cap_oneof_name", ToUpper(vars["oneof_name"])); printer->Outdent(); printer->Print("};\n\n"); // oneofCase() printer->Print(vars, - "@java.lang.Override\n" - "public $oneof_capitalized_name$Case\n" - "get$oneof_capitalized_name$Case() {\n" - " return $oneof_capitalized_name$Case.forNumber(\n" - " $oneof_name$Case_);\n" - "}\n" - "\n" - "private void clear$oneof_capitalized_name$() {\n" - " $oneof_name$Case_ = 0;\n" - " $oneof_name$_ = null;\n" - "}\n" - "\n"); + "@java.lang.Override\n" + "public $oneof_capitalized_name$Case\n" + "get$oneof_capitalized_name$Case() {\n" + " return $oneof_capitalized_name$Case.forNumber(\n" + " $oneof_name$Case_);\n" + "}\n" + "\n" + "private void clear$oneof_capitalized_name$() {\n" + " $oneof_name$Case_ = 0;\n" + " $oneof_name$_ = null;\n" + "}\n" + "\n"); } // Fields for (int i = 0; i < descriptor_->field_count(); i++) { printer->Print("public static final int $constant_name$ = $number$;\n", - "constant_name", FieldConstantName(descriptor_->field(i)), - "number", SimpleItoa(descriptor_->field(i)->number())); + "constant_name", FieldConstantName(descriptor_->field(i)), + "number", StrCat(descriptor_->field(i)->number())); field_generators_.get(descriptor_->field(i)).GenerateMembers(printer); printer->Print("\n"); } - if (!EnableExperimentalRuntime(context_)) { - GenerateMessageSerializationMethods(printer); - } - GenerateParseFromMethods(printer); GenerateBuilder(printer); @@ -350,8 +316,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { // Memoizes whether the protocol buffer is fully initialized (has all // required fields). 0 means false, 1 means true, and all other values // mean not yet computed. - printer->Print( - "private byte memoizedIsInitialized = 2;\n"); + printer->Print("private byte memoizedIsInitialized = 2;\n"); } printer->Print( @@ -369,74 +334,46 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { printer->Indent(); printer->Indent(); - printer->Print( - "case NEW_BUILDER: {\n"); + printer->Print("case NEW_BUILDER: {\n"); printer->Indent(); GenerateDynamicMethodNewBuilder(printer); printer->Outdent(); - if (!EnableExperimentalRuntimeForLite()) { - printer->Print( + printer->Print( "}\n" - "case IS_INITIALIZED: {\n"); - printer->Indent(); - GenerateDynamicMethodIsInitialized(printer); - printer->Outdent(); - - printer->Print("}\n"); - - printer->Print( - "case MAKE_IMMUTABLE: {\n"); - - printer->Indent(); - GenerateDynamicMethodMakeImmutable(printer); - printer->Outdent(); - - printer->Print( - "}\n" - "case VISIT: {\n"); - - printer->Indent(); - GenerateDynamicMethodVisit(printer); - printer->Outdent(); - - printer->Print( - "}\n" - "case MERGE_FROM_STREAM: {\n"); - - printer->Indent(); - GenerateDynamicMethodMergeFromStream(printer); - printer->Outdent(); - } + "case BUILD_MESSAGE_INFO: {\n"); + printer->Indent(); + GenerateDynamicMethodNewBuildMessageInfo(printer); + printer->Outdent(); printer->Print( - "}\n" - "// fall through\n" - "case GET_DEFAULT_INSTANCE: {\n" - " return DEFAULT_INSTANCE;\n" - "}\n" - "case GET_PARSER: {\n" - // Generally one would use the lazy initialization holder pattern for - // manipulating static fields but that has exceptional cost on Android as - // it will generate an extra class for every message. Instead, use the - // double-check locking pattern which works just as well. - // - // The "parser" temporary mirrors the "PARSER" field to eliminate a read - // at the final return statement. - " com.google.protobuf.Parser<$classname$> parser = PARSER;\n" - " if (parser == null) {\n" - " synchronized ($classname$.class) {\n" - " parser = PARSER;\n" - " if (parser == null) {\n" - " parser = new DefaultInstanceBasedParser(DEFAULT_INSTANCE);\n" - " PARSER = parser;\n" - " }\n" - " }\n" - " }\n" - " return parser;\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + "}\n" + "// fall through\n" + "case GET_DEFAULT_INSTANCE: {\n" + " return DEFAULT_INSTANCE;\n" + "}\n" + "case GET_PARSER: {\n" + // Generally one would use the lazy initialization holder pattern for + // manipulating static fields but that has exceptional cost on Android as + // it will generate an extra class for every message. Instead, use the + // double-check locking pattern which works just as well. + // + // The "parser" temporary mirrors the "PARSER" field to eliminate a read + // at the final return statement. + " com.google.protobuf.Parser<$classname$> parser = PARSER;\n" + " if (parser == null) {\n" + " synchronized ($classname$.class) {\n" + " parser = PARSER;\n" + " if (parser == null) {\n" + " parser = new DefaultInstanceBasedParser(DEFAULT_INSTANCE);\n" + " PARSER = parser;\n" + " }\n" + " }\n" + " }\n" + " return parser;\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); printer->Outdent(); @@ -463,43 +400,40 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { printer->Outdent(); printer->Print( - " }\n" - " throw new UnsupportedOperationException();\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + " }\n" + " throw new UnsupportedOperationException();\n" + "}\n" + "\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); printer->Print( - "\n" - "// @@protoc_insertion_point(class_scope:$full_name$)\n", - "full_name", descriptor_->full_name()); - + "\n" + "// @@protoc_insertion_point(class_scope:$full_name$)\n", + "full_name", descriptor_->full_name()); // Carefully initialize the default instance in such a way that it doesn't // conflict with other initialization. - printer->Print( - "private static final $classname$ DEFAULT_INSTANCE;\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + printer->Print("private static final $classname$ DEFAULT_INSTANCE;\n", + "classname", + name_resolver_->GetImmutableClassName(descriptor_)); printer->Print( - "static {\n" - " // New instances are implicitly immutable so no need to make\n" - " // immutable.\n" - " DEFAULT_INSTANCE = new $classname$();\n" - "}\n" - "\n", - "classname", descriptor_->name()); - if (EnableExperimentalRuntimeForLite()) { - // Register the default instance in a map. This map will be used by - // experimental runtime to lookup default instance given a class instance - // without using Java reflection. - printer->Print( - "static {\n" - " com.google.protobuf.GeneratedMessageLite.registerDefaultInstance(\n" - " $classname$.class, DEFAULT_INSTANCE);\n" - "}\n", - "classname", descriptor_->name()); - } + "static {\n" + " // New instances are implicitly immutable so no need to make\n" + " // immutable.\n" + " DEFAULT_INSTANCE = new $classname$();\n" + "}\n" + "\n", + "classname", descriptor_->name()); + // Register the default instance in a map. This map will be used by + // experimental runtime to lookup default instance given a class instance + // without using Java reflection. + printer->Print( + "static {\n" + " com.google.protobuf.GeneratedMessageLite.registerDefaultInstance(\n" + " $classname$.class, DEFAULT_INSTANCE);\n" + "}\n", + "classname", descriptor_->name()); printer->Print( "public static $classname$ getDefaultInstance() {\n" @@ -529,231 +463,208 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { .Generate(printer); } - printer->Outdent(); printer->Print("}\n\n"); } +void ImmutableMessageLiteGenerator::GenerateDynamicMethodNewBuildMessageInfo( + io::Printer* printer) { + printer->Indent(); + + // Collect field info into a sequence of UTF-16 chars. It will be embedded + // as a Java string in the generated code. + std::vector chars; + + int flags = 0; + if (SupportFieldPresence(descriptor_->file())) { + flags |= 0x1; + } + if (descriptor_->options().message_set_wire_format()) { + flags |= 0x2; + } + WriteIntToUtf16CharSequence(flags, &chars); + WriteIntToUtf16CharSequence(descriptor_->field_count(), &chars); + + if (descriptor_->field_count() == 0) { + printer->Print("java.lang.Object[] objects = null;"); + } else { + // A single array of all fields (including oneof, oneofCase, hasBits). + printer->Print("java.lang.Object[] objects = new java.lang.Object[] {\n"); + printer->Indent(); + + // Record the number of oneofs. + WriteIntToUtf16CharSequence(descriptor_->oneof_decl_count(), &chars); + for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { + const OneofDescriptor* oneof = descriptor_->oneof_decl(i); + printer->Print( + "\"$oneof_name$_\",\n" + "\"$oneof_name$Case_\",\n", + "oneof_name", context_->GetOneofGeneratorInfo(oneof)->name); + } + + // Integers for bit fields. + int total_bits = 0; + for (int i = 0; i < descriptor_->field_count(); i++) { + total_bits += + field_generators_.get(descriptor_->field(i)).GetNumBitsForMessage(); + } + int total_ints = (total_bits + 31) / 32; + for (int i = 0; i < total_ints; i++) { + printer->Print("\"$bit_field_name$\",\n", "bit_field_name", + GetBitFieldName(i)); + } + WriteIntToUtf16CharSequence(total_ints, &chars); + + int map_count = 0; + int repeated_count = 0; + std::unique_ptr sorted_fields( + SortFieldsByNumber(descriptor_)); + for (int i = 0; i < descriptor_->field_count(); i++) { + const FieldDescriptor* field = sorted_fields[i]; + if (field->is_map()) { + map_count++; + } else if (field->is_repeated()) { + repeated_count++; + } + } + + WriteIntToUtf16CharSequence(sorted_fields[0]->number(), &chars); + WriteIntToUtf16CharSequence( + sorted_fields[descriptor_->field_count() - 1]->number(), &chars); + WriteIntToUtf16CharSequence(descriptor_->field_count(), &chars); + WriteIntToUtf16CharSequence(map_count, &chars); + WriteIntToUtf16CharSequence(repeated_count, &chars); + + std::vector fields_for_is_initialized_check; + for (int i = 0; i < descriptor_->field_count(); i++) { + if (descriptor_->field(i)->is_required() || + (GetJavaType(descriptor_->field(i)) == JAVATYPE_MESSAGE && + HasRequiredFields(descriptor_->field(i)->message_type()))) { + fields_for_is_initialized_check.push_back(descriptor_->field(i)); + } + } + WriteIntToUtf16CharSequence(fields_for_is_initialized_check.size(), &chars); + + for (int i = 0; i < descriptor_->field_count(); i++) { + const FieldDescriptor* field = sorted_fields[i]; + field_generators_.get(field).GenerateFieldInfo(printer, &chars); + } + printer->Outdent(); + printer->Print("};\n"); + } + + printer->Print("java.lang.String info =\n"); + std::string line; + for (size_t i = 0; i < chars.size(); i++) { + uint16 code = chars[i]; + EscapeUtf16ToString(code, &line); + if (line.size() >= 80) { + printer->Print(" \"$string$\" +\n", "string", line); + line.clear(); + } + } + printer->Print(" \"$string$\";\n", "string", line); + + printer->Print("return newMessageInfo(DEFAULT_INSTANCE, info, objects);\n"); + printer->Outdent(); +} // =================================================================== -void ImmutableMessageLiteGenerator:: -GenerateMessageSerializationMethods(io::Printer* printer) { - if (EnableExperimentalRuntimeForLite()) { - return; - } - - std::unique_ptr sorted_fields( - SortFieldsByNumber(descriptor_)); - - std::vector sorted_extensions; - for (int i = 0; i < descriptor_->extension_range_count(); ++i) { - sorted_extensions.push_back(descriptor_->extension_range(i)); - } - std::sort(sorted_extensions.begin(), sorted_extensions.end(), - ExtensionRangeOrdering()); - - printer->Print( - "@java.lang.Override\n" - "public void writeTo(com.google.protobuf.CodedOutputStream output)\n" - " throws java.io.IOException {\n"); - printer->Indent(); - if (HasPackedFields(descriptor_)) { - // writeTo(CodedOutputStream output) might be invoked without - // getSerializedSize() ever being called, but we need the memoized - // sizes in case this message has packed fields. Rather than emit checks - // for each packed field, just call getSerializedSize() up front. In most - // cases, getSerializedSize() will have already been called anyway by one - // of the wrapper writeTo() methods, making this call cheap. - printer->Print("getSerializedSize();\n"); - } - - if (descriptor_->extension_range_count() > 0) { - if (descriptor_->options().message_set_wire_format()) { - printer->Print( - "com.google.protobuf.GeneratedMessageLite\n" - " .ExtendableMessage<$classname$, $classname$.Builder>\n" - " .ExtensionWriter extensionWriter =\n" - " newMessageSetExtensionWriter();\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - } else { - printer->Print( - "com.google.protobuf.GeneratedMessageLite\n" - " .ExtendableMessage<$classname$, $classname$.Builder>\n" - " .ExtensionWriter extensionWriter =\n" - " newExtensionWriter();\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - } - } - - // Merge the fields and the extension ranges, both sorted by field number. - for (int i = 0, j = 0; - i < descriptor_->field_count() || j < sorted_extensions.size();) { - if (i == descriptor_->field_count()) { - GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]); - } else if (j == sorted_extensions.size()) { - GenerateSerializeOneField(printer, sorted_fields[i++]); - } else if (sorted_fields[i]->number() < sorted_extensions[j]->start) { - GenerateSerializeOneField(printer, sorted_fields[i++]); - } else { - GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]); - } - } - - if (descriptor_->options().message_set_wire_format()) { - printer->Print("unknownFields.writeAsMessageSetTo(output);\n"); - } else { - printer->Print("unknownFields.writeTo(output);\n"); - } - - printer->Outdent(); +void ImmutableMessageLiteGenerator::GenerateParseFromMethods( + io::Printer* printer) { printer->Print( + "public static $classname$ parseFrom(\n" + " java.nio.ByteBuffer data)\n" + " throws com.google.protobuf.InvalidProtocolBufferException {\n" + " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" + " DEFAULT_INSTANCE, data);\n" "}\n" - "\n" - "@java.lang.Override\n" - "public int getSerializedSize() {\n" - " int size = memoizedSerializedSize;\n" - " if (size != -1) return size;\n" - "\n"); - printer->Indent(); - printer->Print( - "size = 0;\n"); - - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(sorted_fields[i]).GenerateSerializedSizeCode(printer); - } - - if (descriptor_->extension_range_count() > 0) { - if (descriptor_->options().message_set_wire_format()) { - printer->Print("size += extensionsSerializedSizeAsMessageSet();\n"); - } else { - printer->Print("size += extensionsSerializedSize();\n"); - } - } - - if (descriptor_->options().message_set_wire_format()) { - printer->Print("size += unknownFields.getSerializedSizeAsMessageSet();\n"); - } else { - printer->Print("size += unknownFields.getSerializedSize();\n"); - } - - printer->Print( - "memoizedSerializedSize = size;\n" - "return size;\n"); - - printer->Outdent(); - printer->Print( - "}\n" - "\n"); -} - -void ImmutableMessageLiteGenerator:: -GenerateParseFromMethods(io::Printer* printer) { - // Note: These are separate from GenerateMessageSerializationMethods() - // because they need to be generated even for messages that are optimized - // for code size. - printer->Print( - "public static $classname$ parseFrom(\n" - " java.nio.ByteBuffer data)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, data);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " java.nio.ByteBuffer data,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, data, extensionRegistry);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " com.google.protobuf.ByteString data)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, data);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " com.google.protobuf.ByteString data,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, data, extensionRegistry);\n" - "}\n" - "public static $classname$ parseFrom(byte[] data)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, data);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " byte[] data,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, data, extensionRegistry);\n" - "}\n" - "public static $classname$ parseFrom(java.io.InputStream input)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, input);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " java.io.InputStream input,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, input, extensionRegistry);\n" - "}\n" - "public static $classname$ parseDelimitedFrom(java.io.InputStream input)\n" - " throws java.io.IOException {\n" - " return parseDelimitedFrom(DEFAULT_INSTANCE, input);\n" - "}\n" - "public static $classname$ parseDelimitedFrom(\n" - " java.io.InputStream input,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws java.io.IOException {\n" - " return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " com.google.protobuf.CodedInputStream input)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, input);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " com.google.protobuf.CodedInputStream input,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, input, extensionRegistry);\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); -} - -void ImmutableMessageLiteGenerator::GenerateSerializeOneField( - io::Printer* printer, const FieldDescriptor* field) { - field_generators_.get(field).GenerateSerializationCode(printer); -} - -void ImmutableMessageLiteGenerator::GenerateSerializeOneExtensionRange( - io::Printer* printer, const Descriptor::ExtensionRange* range) { - printer->Print( - "extensionWriter.writeUntil($end$, output);\n", - "end", SimpleItoa(range->end)); + "public static $classname$ parseFrom(\n" + " java.nio.ByteBuffer data,\n" + " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" + " throws com.google.protobuf.InvalidProtocolBufferException {\n" + " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" + " DEFAULT_INSTANCE, data, extensionRegistry);\n" + "}\n" + "public static $classname$ parseFrom(\n" + " com.google.protobuf.ByteString data)\n" + " throws com.google.protobuf.InvalidProtocolBufferException {\n" + " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" + " DEFAULT_INSTANCE, data);\n" + "}\n" + "public static $classname$ parseFrom(\n" + " com.google.protobuf.ByteString data,\n" + " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" + " throws com.google.protobuf.InvalidProtocolBufferException {\n" + " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" + " DEFAULT_INSTANCE, data, extensionRegistry);\n" + "}\n" + "public static $classname$ parseFrom(byte[] data)\n" + " throws com.google.protobuf.InvalidProtocolBufferException {\n" + " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" + " DEFAULT_INSTANCE, data);\n" + "}\n" + "public static $classname$ parseFrom(\n" + " byte[] data,\n" + " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" + " throws com.google.protobuf.InvalidProtocolBufferException {\n" + " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" + " DEFAULT_INSTANCE, data, extensionRegistry);\n" + "}\n" + "public static $classname$ parseFrom(java.io.InputStream input)\n" + " throws java.io.IOException {\n" + " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" + " DEFAULT_INSTANCE, input);\n" + "}\n" + "public static $classname$ parseFrom(\n" + " java.io.InputStream input,\n" + " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" + " throws java.io.IOException {\n" + " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" + " DEFAULT_INSTANCE, input, extensionRegistry);\n" + "}\n" + "public static $classname$ parseDelimitedFrom(java.io.InputStream " + "input)\n" + " throws java.io.IOException {\n" + " return parseDelimitedFrom(DEFAULT_INSTANCE, input);\n" + "}\n" + "public static $classname$ parseDelimitedFrom(\n" + " java.io.InputStream input,\n" + " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" + " throws java.io.IOException {\n" + " return parseDelimitedFrom(DEFAULT_INSTANCE, input, " + "extensionRegistry);\n" + "}\n" + "public static $classname$ parseFrom(\n" + " com.google.protobuf.CodedInputStream input)\n" + " throws java.io.IOException {\n" + " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" + " DEFAULT_INSTANCE, input);\n" + "}\n" + "public static $classname$ parseFrom(\n" + " com.google.protobuf.CodedInputStream input,\n" + " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" + " throws java.io.IOException {\n" + " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" + " DEFAULT_INSTANCE, input, extensionRegistry);\n" + "}\n" + "\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); } // =================================================================== void ImmutableMessageLiteGenerator::GenerateBuilder(io::Printer* printer) { printer->Print( - "public static Builder newBuilder() {\n" - " return (Builder) DEFAULT_INSTANCE.createBuilder();\n" - "}\n" - "public static Builder newBuilder($classname$ prototype) {\n" - " return (Builder) DEFAULT_INSTANCE.createBuilder(prototype);\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + "public static Builder newBuilder() {\n" + " return (Builder) DEFAULT_INSTANCE.createBuilder();\n" + "}\n" + "public static Builder newBuilder($classname$ prototype) {\n" + " return (Builder) DEFAULT_INSTANCE.createBuilder(prototype);\n" + "}\n" + "\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); MessageBuilderLiteGenerator builderGenerator(descriptor_, context_); builderGenerator.Generate(printer); @@ -761,393 +672,43 @@ void ImmutableMessageLiteGenerator::GenerateBuilder(io::Printer* printer) { // =================================================================== -void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized( - io::Printer* printer) { - // Returns null for false, DEFAULT_INSTANCE for true. - if (!HasRequiredFields(descriptor_)) { - printer->Print("return DEFAULT_INSTANCE;\n"); - return; - } - - // TODO(xiaofeng): Remove this when b/64445758 is fixed. We don't need to - // check memoizedIsInitialized here because the caller does that already, - // but right now proguard proto shrinker asserts on the bytecode layout of - // this code so it can't be removed until proguard is updated. - printer->Print( - "byte isInitialized = memoizedIsInitialized;\n" - "if (isInitialized == 1) return DEFAULT_INSTANCE;\n" - "if (isInitialized == 0) return null;\n" - "\n" - "boolean shouldMemoize = ((Boolean) arg0).booleanValue();\n"); - - // Check that all required fields in this message are set. - // TODO(kenton): We can optimize this when we switch to putting all the - // "has" fields into a single bitfield. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); - - if (field->is_required()) { - printer->Print( - "if (!has$name$()) {\n" - " return null;\n" - "}\n", - "name", info->capitalized_name); - } - } - - // Now check that all embedded messages are initialized. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); - if (GetJavaType(field) == JAVATYPE_MESSAGE && - HasRequiredFields(field->message_type())) { - switch (field->label()) { - case FieldDescriptor::LABEL_REQUIRED: - printer->Print( - "if (!get$name$().isInitialized()) {\n" - " return null;\n" - "}\n", - "type", name_resolver_->GetImmutableClassName( - field->message_type()), - "name", info->capitalized_name); - break; - case FieldDescriptor::LABEL_OPTIONAL: - if (!SupportFieldPresence(descriptor_->file()) && - field->containing_oneof() != NULL) { - const OneofDescriptor* oneof = field->containing_oneof(); - const OneofGeneratorInfo* oneof_info = - context_->GetOneofGeneratorInfo(oneof); - printer->Print( - "if ($oneof_name$Case_ == $field_number$) {\n", - "oneof_name", oneof_info->name, - "field_number", SimpleItoa(field->number())); - } else { - printer->Print( - "if (has$name$()) {\n", - "name", info->capitalized_name); - } - printer->Print( - " if (!get$name$().isInitialized()) {\n" - " return null;\n" - " }\n" - "}\n", - "name", info->capitalized_name); - break; - case FieldDescriptor::LABEL_REPEATED: - if (IsMapEntry(field->message_type())) { - printer->Print( - "for ($type$ item : get$name$Map().values()) {\n" - " if (!item.isInitialized()) {\n" - " return null;\n" - " }\n" - "}\n", - "type", MapValueImmutableClassdName(field->message_type(), - name_resolver_), - "name", info->capitalized_name); - } else { - printer->Print( - "for (int i = 0; i < get$name$Count(); i++) {\n" - " if (!get$name$(i).isInitialized()) {\n" - " return null;\n" - " }\n" - "}\n", - "type", name_resolver_->GetImmutableClassName( - field->message_type()), - "name", info->capitalized_name); - } - break; - } - } - } - - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "if (!extensionsAreInitialized()) {\n" - " return null;\n" - "}\n"); - } - - printer->Print( - "return DEFAULT_INSTANCE;\n" - "\n"); -} - -// =================================================================== - -void ImmutableMessageLiteGenerator::GenerateDynamicMethodMakeImmutable( - io::Printer* printer) { - - // Output generation code for each field. - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(descriptor_->field(i)) - .GenerateDynamicMethodMakeImmutableCode(printer); - } - - printer->Print( - "return null;\n"); -} - -// =================================================================== - void ImmutableMessageLiteGenerator::GenerateDynamicMethodNewBuilder( io::Printer* printer) { - printer->Print( - "return new Builder();\n"); + printer->Print("return new Builder();\n"); } // =================================================================== -void ImmutableMessageLiteGenerator::GenerateDynamicMethodVisit( +void ImmutableMessageLiteGenerator::GenerateExtensionRegistrationCode( io::Printer* printer) { - printer->Print( - "Visitor visitor = (Visitor) arg0;\n" - "$classname$ other = ($classname$) arg1;\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - for (int i = 0; i < descriptor_->field_count(); i++) { - if (!descriptor_->field(i)->containing_oneof()) { - field_generators_.get( - descriptor_->field(i)).GenerateVisitCode(printer); - } - } - - // Merge oneof fields. - for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) { - printer->Print( - "switch (other.get$oneof_capitalized_name$Case()) {\n", - "oneof_capitalized_name", - context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->capitalized_name); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print( - "case $field_name$: {\n", - "field_name", - ToUpper(field->name())); - printer->Indent(); - field_generators_.get(field).GenerateVisitCode(printer); - printer->Print( - "break;\n"); - printer->Outdent(); - printer->Print( - "}\n"); - } - printer->Print( - "case $cap_oneof_name$_NOT_SET: {\n" - " visitor.visitOneofNotSet($oneof_name$Case_ != 0);\n" - " break;\n" - "}\n", - "cap_oneof_name", - ToUpper(context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name), - "oneof_name", - context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name); - printer->Outdent(); - printer->Print( - "}\n"); - } - - printer->Print( - "if (visitor == com.google.protobuf.GeneratedMessageLite.MergeFromVisitor\n" - " .INSTANCE) {\n"); - printer->Indent(); - for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) { - const OneofDescriptor* field = descriptor_->oneof_decl(i); - printer->Print( - "if (other.$oneof_name$Case_ != 0) {\n" - " $oneof_name$Case_ = other.$oneof_name$Case_;\n" - "}\n", - "oneof_name", context_->GetOneofGeneratorInfo(field)->name); - } - - if (GenerateHasBits(descriptor_)) { - // Integers for bit fields. - int totalBits = 0; - for (int i = 0; i < descriptor_->field_count(); i++) { - totalBits += field_generators_.get(descriptor_->field(i)) - .GetNumBitsForMessage(); - } - int totalInts = (totalBits + 31) / 32; - - for (int i = 0; i < totalInts; i++) { - printer->Print( - "$bit_field_name$ |= other.$bit_field_name$;\n", - "bit_field_name", GetBitFieldName(i)); - } - } - printer->Outdent(); - printer->Print( - "}\n"); - - - printer->Print( - "return this;\n"); -} - -// =================================================================== - -void ImmutableMessageLiteGenerator::GenerateDynamicMethodMergeFromStream( - io::Printer* printer) { - printer->Print( - "com.google.protobuf.CodedInputStream input =\n" - " (com.google.protobuf.CodedInputStream) arg0;\n" - "com.google.protobuf.ExtensionRegistryLite extensionRegistry =\n" - " (com.google.protobuf.ExtensionRegistryLite) arg1;\n" - "if (extensionRegistry == null) {\n" - " throw new java.lang.NullPointerException();\n" - "}\n"); - printer->Print( - "try {\n"); - printer->Indent(); - if (EnableExperimentalRuntime(context_)) { - printer->Print( - "mergeFromInternal(input, extensionRegistry);\n" - "return DEFAULT_INSTANCE;\n"); - } else { - printer->Print( - "boolean done = false;\n" - "while (!done) {\n"); - printer->Indent(); - - printer->Print( - "int tag = input.readTag();\n" - "switch (tag) {\n"); - printer->Indent(); - - printer->Print( - "case 0:\n" // zero signals EOF / limit reached - " done = true;\n" - " break;\n"); - - std::unique_ptr sorted_fields( - SortFieldsByNumber(descriptor_)); - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = sorted_fields[i]; - uint32 tag = WireFormatLite::MakeTag( - field->number(), WireFormat::WireTypeForFieldType(field->type())); - - printer->Print("case $tag$: {\n", "tag", - SimpleItoa(static_cast(tag))); - printer->Indent(); - - field_generators_.get(field).GenerateParsingCode(printer); - - printer->Outdent(); - printer->Print( - " break;\n" - "}\n"); - - if (field->is_packable()) { - // To make packed = true wire compatible, we generate parsing code from - // a packed version of this field regardless of - // field->options().packed(). - uint32 packed_tag = WireFormatLite::MakeTag( - field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED); - printer->Print("case $tag$: {\n", "tag", - SimpleItoa(static_cast(packed_tag))); - printer->Indent(); - - field_generators_.get(field).GenerateParsingCodeFromPacked(printer); - - printer->Outdent(); - printer->Print( - " break;\n" - "}\n"); - } - } - - if (descriptor_->extension_range_count() > 0) { - if (descriptor_->options().message_set_wire_format()) { - printer->Print( - "default: {\n" - " if (!parseUnknownFieldAsMessageSet(\n" - " getDefaultInstanceForType(), input, extensionRegistry,\n" - " tag)) {\n" - " done = true;\n" // it's an endgroup tag - " }\n" - " break;\n" - "}\n"); - } else { - printer->Print( - "default: {\n" - " if (!parseUnknownField(getDefaultInstanceForType(),\n" - " input, extensionRegistry, tag)) {\n" - " done = true;\n" // it's an endgroup tag - " }\n" - " break;\n" - "}\n"); - } - } else { - printer->Print( - "default: {\n" - " if (!parseUnknownField(tag, input)) {\n" - " done = true;\n" // it's an endgroup tag - " }\n" - " break;\n" - "}\n"); - } - - printer->Outdent(); - printer->Outdent(); - printer->Print( - " }\n" // switch (tag) - "}\n"); // while (!done) - } - - printer->Outdent(); - printer->Print( - "} catch (com.google.protobuf.InvalidProtocolBufferException e) {\n" - " throw new RuntimeException(e.setUnfinishedMessage(this));\n" - "} catch (java.io.IOException e) {\n" - " throw new RuntimeException(\n" - " new com.google.protobuf.InvalidProtocolBufferException(\n" - " e.getMessage()).setUnfinishedMessage(this));\n" - "} finally {\n"); - printer->Indent(); - - printer->Outdent(); - printer->Print( - "}\n"); // finally -} - -// =================================================================== - -void ImmutableMessageLiteGenerator:: -GenerateExtensionRegistrationCode(io::Printer* printer) { for (int i = 0; i < descriptor_->extension_count(); i++) { ImmutableExtensionLiteGenerator(descriptor_->extension(i), context_) - .GenerateRegistrationCode(printer); + .GenerateRegistrationCode(printer); } for (int i = 0; i < descriptor_->nested_type_count(); i++) { ImmutableMessageLiteGenerator(descriptor_->nested_type(i), context_) - .GenerateExtensionRegistrationCode(printer); + .GenerateExtensionRegistrationCode(printer); } } // =================================================================== -void ImmutableMessageLiteGenerator:: -GenerateConstructor(io::Printer* printer) { - printer->Print( - "private $classname$() {\n", - "classname", descriptor_->name()); +void ImmutableMessageLiteGenerator::GenerateConstructor(io::Printer* printer) { + printer->Print("private $classname$() {\n", "classname", descriptor_->name()); printer->Indent(); // Initialize all fields to default. GenerateInitializers(printer); printer->Outdent(); - printer->Print( - "}\n"); + printer->Print("}\n"); } // =================================================================== void ImmutableMessageLiteGenerator::GenerateParser(io::Printer* printer) { printer->Print( - "private static volatile com.google.protobuf.Parser<$classname$> PARSER;\n" + "private static volatile com.google.protobuf.Parser<$classname$> " + "PARSER;\n" "\n" "public static com.google.protobuf.Parser<$classname$> parser() {\n" " return DEFAULT_INSTANCE.getParserForType();\n" diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_lite.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_lite.h index 1e319c6d..5290b1e6 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_message_lite.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_message_lite.h @@ -35,8 +35,8 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_LITE_H__ #define GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_LITE_H__ -#include #include +#include #include #include @@ -53,29 +53,19 @@ class ImmutableMessageLiteGenerator : public MessageGenerator { virtual void Generate(io::Printer* printer); virtual void GenerateInterface(io::Printer* printer); virtual void GenerateExtensionRegistrationCode(io::Printer* printer); - virtual void GenerateStaticVariables( - io::Printer* printer, int* bytecode_estimate); + virtual void GenerateStaticVariables(io::Printer* printer, + int* bytecode_estimate); virtual int GenerateStaticVariableInitializers(io::Printer* printer); private: - - void GenerateMessageSerializationMethods(io::Printer* printer); void GenerateParseFromMethods(io::Printer* printer); - void GenerateSerializeOneField(io::Printer* printer, - const FieldDescriptor* field); - void GenerateSerializeOneExtensionRange( - io::Printer* printer, const Descriptor::ExtensionRange* range); void GenerateBuilder(io::Printer* printer); - void GenerateDynamicMethodIsInitialized(io::Printer* printer); - void GenerateDynamicMethodMakeImmutable(io::Printer* printer); - void GenerateDynamicMethodVisit(io::Printer* printer); - void GenerateDynamicMethodMergeFromStream(io::Printer* printer); void GenerateDynamicMethodNewBuilder(io::Printer* printer); void GenerateInitializers(io::Printer* printer); - void GenerateEqualsAndHashCode(io::Printer* printer); void GenerateParser(io::Printer* printer); void GenerateConstructor(io::Printer* printer); + void GenerateDynamicMethodNewBuildMessageInfo(io::Printer* printer); Context* context_; ClassNameResolver* name_resolver_; @@ -87,6 +77,6 @@ class ImmutableMessageLiteGenerator : public MessageGenerator { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_LITE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_name_resolver.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_name_resolver.cc index 1673b4ee..d07c628e 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_name_resolver.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_name_resolver.cc @@ -37,6 +37,7 @@ #include #include + namespace google { namespace protobuf { namespace compiler { @@ -52,8 +53,8 @@ const char* kOuterClassNameSuffix = "OuterClass"; // Full name : foo.Bar.Baz // Package name: foo // After strip : Bar.Baz -string StripPackageName(const string& full_name, - const FileDescriptor* file) { +std::string StripPackageName(const std::string& full_name, + const FileDescriptor* file) { if (file->package().empty()) { return full_name; } else { @@ -63,46 +64,61 @@ string StripPackageName(const string& full_name, } // Get the name of a message's Java class without package name prefix. -string ClassNameWithoutPackage(const Descriptor* descriptor, - bool immutable) { - return StripPackageName(descriptor->full_name(), - descriptor->file()); +std::string ClassNameWithoutPackage(const Descriptor* descriptor, + bool immutable) { + return StripPackageName(descriptor->full_name(), descriptor->file()); } // Get the name of an enum's Java class without package name prefix. -string ClassNameWithoutPackage(const EnumDescriptor* descriptor, - bool immutable) { +std::string ClassNameWithoutPackage(const EnumDescriptor* descriptor, + bool immutable) { // Doesn't append "Mutable" for enum type's name. const Descriptor* message_descriptor = descriptor->containing_type(); if (message_descriptor == NULL) { return descriptor->name(); } else { - return ClassNameWithoutPackage(message_descriptor, immutable) + - "." + descriptor->name(); + return ClassNameWithoutPackage(message_descriptor, immutable) + "." + + descriptor->name(); } } // Get the name of a service's Java class without package name prefix. -string ClassNameWithoutPackage(const ServiceDescriptor* descriptor, - bool immutable) { - string full_name = StripPackageName(descriptor->full_name(), - descriptor->file()); +std::string ClassNameWithoutPackage(const ServiceDescriptor* descriptor, + bool immutable) { + std::string full_name = + StripPackageName(descriptor->full_name(), descriptor->file()); // We don't allow nested service definitions. - GOOGLE_CHECK(full_name.find('.') == string::npos); + GOOGLE_CHECK(full_name.find('.') == std::string::npos); return full_name; } +// Return true if a and b are equals (case insensitive). +NameEquality CheckNameEquality(const string& a, const string& b) { + if (ToUpper(a) == ToUpper(b)) { + if (a == b) { + return NameEquality::EXACT_EQUAL; + } + return NameEquality::EQUAL_IGNORE_CASE; + } + return NameEquality::NO_MATCH; +} + // Check whether a given message or its nested types has the given class name. bool MessageHasConflictingClassName(const Descriptor* message, - const string& classname) { - if (message->name() == classname) return true; + const std::string& classname, + NameEquality equality_mode) { + if (CheckNameEquality(message->name(), classname) == equality_mode) { + return true; + } for (int i = 0; i < message->nested_type_count(); ++i) { - if (MessageHasConflictingClassName(message->nested_type(i), classname)) { + if (MessageHasConflictingClassName(message->nested_type(i), classname, + equality_mode)) { return true; } } for (int i = 0; i < message->enum_type_count(); ++i) { - if (message->enum_type(i)->name() == classname) { + if (CheckNameEquality(message->enum_type(i)->name(), classname) == + equality_mode) { return true; } } @@ -111,17 +127,15 @@ bool MessageHasConflictingClassName(const Descriptor* message, } // namespace -ClassNameResolver::ClassNameResolver() { -} +ClassNameResolver::ClassNameResolver() {} -ClassNameResolver::~ClassNameResolver() { -} +ClassNameResolver::~ClassNameResolver() {} -string ClassNameResolver::GetFileDefaultImmutableClassName( +std::string ClassNameResolver::GetFileDefaultImmutableClassName( const FileDescriptor* file) { - string basename; - string::size_type last_slash = file->name().find_last_of('/'); - if (last_slash == string::npos) { + std::string basename; + std::string::size_type last_slash = file->name().find_last_of('/'); + if (last_slash == std::string::npos) { basename = file->name(); } else { basename = file->name().substr(last_slash + 1); @@ -129,15 +143,16 @@ string ClassNameResolver::GetFileDefaultImmutableClassName( return UnderscoresToCamelCase(StripProto(basename), true); } -string ClassNameResolver::GetFileImmutableClassName( +std::string ClassNameResolver::GetFileImmutableClassName( const FileDescriptor* file) { - string& class_name = file_immutable_outer_class_names_[file]; + std::string& class_name = file_immutable_outer_class_names_[file]; if (class_name.empty()) { if (file->options().has_java_outer_classname()) { class_name = file->options().java_outer_classname(); } else { class_name = GetFileDefaultImmutableClassName(file); - if (HasConflictingClassName(file, class_name)) { + if (HasConflictingClassName(file, class_name, + NameEquality::EXACT_EQUAL)) { class_name += kOuterClassNameSuffix; } } @@ -145,8 +160,8 @@ string ClassNameResolver::GetFileImmutableClassName( return class_name; } -string ClassNameResolver::GetFileClassName(const FileDescriptor* file, - bool immutable) { +std::string ClassNameResolver::GetFileClassName(const FileDescriptor* file, + bool immutable) { if (immutable) { return GetFileImmutableClassName(file); } else { @@ -156,34 +171,38 @@ string ClassNameResolver::GetFileClassName(const FileDescriptor* file, // Check whether there is any type defined in the proto file that has // the given class name. -bool ClassNameResolver::HasConflictingClassName( - const FileDescriptor* file, const string& classname) { +bool ClassNameResolver::HasConflictingClassName(const FileDescriptor* file, + const std::string& classname, + NameEquality equality_mode) { for (int i = 0; i < file->enum_type_count(); i++) { - if (file->enum_type(i)->name() == classname) { + if (CheckNameEquality(file->enum_type(i)->name(), classname) == + equality_mode) { return true; } } for (int i = 0; i < file->service_count(); i++) { - if (file->service(i)->name() == classname) { + if (CheckNameEquality(file->service(i)->name(), classname) == + equality_mode) { return true; } } for (int i = 0; i < file->message_type_count(); i++) { - if (MessageHasConflictingClassName(file->message_type(i), classname)) { + if (MessageHasConflictingClassName(file->message_type(i), classname, + equality_mode)) { return true; } } return false; } -string ClassNameResolver::GetDescriptorClassName( +std::string ClassNameResolver::GetDescriptorClassName( const FileDescriptor* descriptor) { return GetFileImmutableClassName(descriptor); } -string ClassNameResolver::GetClassName(const FileDescriptor* descriptor, - bool immutable) { - string result = FileJavaPackage(descriptor, immutable); +std::string ClassNameResolver::GetClassName(const FileDescriptor* descriptor, + bool immutable) { + std::string result = FileJavaPackage(descriptor, immutable); if (!result.empty()) result += '.'; result += GetFileClassName(descriptor, immutable); return result; @@ -191,11 +210,10 @@ string ClassNameResolver::GetClassName(const FileDescriptor* descriptor, // Get the full name of a Java class by prepending the Java package name // or outer class name. -string ClassNameResolver::GetClassFullName(const string& name_without_package, - const FileDescriptor* file, - bool immutable, - bool multiple_files) { - string result; +std::string ClassNameResolver::GetClassFullName( + const std::string& name_without_package, const FileDescriptor* file, + bool immutable, bool multiple_files) { + std::string result; if (multiple_files) { result = FileJavaPackage(file, immutable); } else { @@ -208,33 +226,32 @@ string ClassNameResolver::GetClassFullName(const string& name_without_package, return result; } -string ClassNameResolver::GetClassName(const Descriptor* descriptor, - bool immutable) { +std::string ClassNameResolver::GetClassName(const Descriptor* descriptor, + bool immutable) { return GetClassFullName(ClassNameWithoutPackage(descriptor, immutable), descriptor->file(), immutable, MultipleJavaFiles(descriptor->file(), immutable)); } -string ClassNameResolver::GetClassName(const EnumDescriptor* descriptor, - bool immutable) { +std::string ClassNameResolver::GetClassName(const EnumDescriptor* descriptor, + bool immutable) { return GetClassFullName(ClassNameWithoutPackage(descriptor, immutable), descriptor->file(), immutable, MultipleJavaFiles(descriptor->file(), immutable)); } -string ClassNameResolver::GetClassName(const ServiceDescriptor* descriptor, - bool immutable) { +std::string ClassNameResolver::GetClassName(const ServiceDescriptor* descriptor, + bool immutable) { return GetClassFullName(ClassNameWithoutPackage(descriptor, immutable), descriptor->file(), immutable, MultipleJavaFiles(descriptor->file(), immutable)); } // Get the Java Class style full name of a message. -string ClassNameResolver::GetJavaClassFullName( - const string& name_without_package, - const FileDescriptor* file, +std::string ClassNameResolver::GetJavaClassFullName( + const std::string& name_without_package, const FileDescriptor* file, bool immutable) { - string result; + std::string result; if (MultipleJavaFiles(file, immutable)) { result = FileJavaPackage(file, immutable); if (!result.empty()) result += '.'; @@ -246,25 +263,22 @@ string ClassNameResolver::GetJavaClassFullName( return result; } -string ClassNameResolver::GetExtensionIdentifierName( +std::string ClassNameResolver::GetExtensionIdentifierName( const FieldDescriptor* descriptor, bool immutable) { return GetClassName(descriptor->containing_type(), immutable) + "." + descriptor->name(); } - -string ClassNameResolver::GetJavaImmutableClassName( +std::string ClassNameResolver::GetJavaImmutableClassName( const Descriptor* descriptor) { - return GetJavaClassFullName( - ClassNameWithoutPackage(descriptor, true), - descriptor->file(), true); + return GetJavaClassFullName(ClassNameWithoutPackage(descriptor, true), + descriptor->file(), true); } -string ClassNameResolver::GetJavaImmutableClassName( +std::string ClassNameResolver::GetJavaImmutableClassName( const EnumDescriptor* descriptor) { - return GetJavaClassFullName( - ClassNameWithoutPackage(descriptor, true), - descriptor->file(), true); + return GetJavaClassFullName(ClassNameWithoutPackage(descriptor, true), + descriptor->file(), true); } diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_name_resolver.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_name_resolver.h index 28b049d1..89bcb597 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_name_resolver.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_name_resolver.h @@ -47,6 +47,9 @@ class ServiceDescriptor; namespace compiler { namespace java { +// Indicates how closely the two class names match. +enum NameEquality { NO_MATCH, EXACT_EQUAL, EQUAL_IGNORE_CASE }; + // Used to get the Java class related names for a given descriptor. It caches // the results to avoid redundant calculation across multiple name queries. // Thread-safety note: This class is *not* thread-safe. @@ -56,63 +59,62 @@ class ClassNameResolver { ~ClassNameResolver(); // Gets the unqualified outer class name for the file. - string GetFileClassName(const FileDescriptor* file, bool immutable); + std::string GetFileClassName(const FileDescriptor* file, bool immutable); // Gets the unqualified immutable outer class name of a file. - string GetFileImmutableClassName(const FileDescriptor* file); + std::string GetFileImmutableClassName(const FileDescriptor* file); // Gets the unqualified default immutable outer class name of a file // (converted from the proto file's name). - string GetFileDefaultImmutableClassName(const FileDescriptor* file); + std::string GetFileDefaultImmutableClassName(const FileDescriptor* file); // Check whether there is any type defined in the proto file that has // the given class name. bool HasConflictingClassName(const FileDescriptor* file, - const string& classname); + const std::string& classname, + NameEquality equality_mode); // Gets the name of the outer class that holds descriptor information. // Descriptors are shared between immutable messages and mutable messages. // Since both of them are generated optionally, the descriptors need to be // put in another common place. - string GetDescriptorClassName(const FileDescriptor* file); + std::string GetDescriptorClassName(const FileDescriptor* file); // Gets the fully-qualified class name corresponding to the given descriptor. - string GetClassName(const Descriptor* descriptor, bool immutable); - string GetClassName(const EnumDescriptor* descriptor, bool immutable); - string GetClassName(const ServiceDescriptor* descriptor, bool immutable); - string GetClassName(const FileDescriptor* descriptor, bool immutable); + std::string GetClassName(const Descriptor* descriptor, bool immutable); + std::string GetClassName(const EnumDescriptor* descriptor, bool immutable); + std::string GetClassName(const ServiceDescriptor* descriptor, bool immutable); + std::string GetClassName(const FileDescriptor* descriptor, bool immutable); - template - string GetImmutableClassName(const DescriptorType* descriptor) { + template + std::string GetImmutableClassName(const DescriptorType* descriptor) { return GetClassName(descriptor, true); } - template - string GetMutableClassName(const DescriptorType* descriptor) { + template + std::string GetMutableClassName(const DescriptorType* descriptor) { return GetClassName(descriptor, false); } // Gets the fully qualified name of an extension identifier. - string GetExtensionIdentifierName(const FieldDescriptor* descriptor, - bool immutable); + std::string GetExtensionIdentifierName(const FieldDescriptor* descriptor, + bool immutable); // Gets the fully qualified name for generated classes in Java convention. // Nested classes will be separated using '$' instead of '.' // For example: // com.package.OuterClass$OuterMessage$InnerMessage - string GetJavaImmutableClassName(const Descriptor* descriptor); - string GetJavaImmutableClassName(const EnumDescriptor* descriptor); + std::string GetJavaImmutableClassName(const Descriptor* descriptor); + std::string GetJavaImmutableClassName(const EnumDescriptor* descriptor); private: // Get the full name of a Java class by prepending the Java package name // or outer class name. - string GetClassFullName(const string& name_without_package, - const FileDescriptor* file, - bool immutable, - bool multiple_files); + std::string GetClassFullName(const std::string& name_without_package, + const FileDescriptor* file, bool immutable, + bool multiple_files); // Get the Java Class style full name of a message. - string GetJavaClassFullName( - const string& name_without_package, - const FileDescriptor* file, - bool immutable); + std::string GetJavaClassFullName(const std::string& name_without_package, + const FileDescriptor* file, bool immutable); // Caches the result to provide better performance. - std::map file_immutable_outer_class_names_; + std::map + file_immutable_outer_class_names_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ClassNameResolver); }; @@ -120,6 +122,6 @@ class ClassNameResolver { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_NAME_RESOLVER_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_names.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_names.h index 0d614335..a8efbb49 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_names.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_names.h @@ -46,6 +46,7 @@ namespace protobuf { class Descriptor; class EnumDescriptor; class FileDescriptor; +class FieldDescriptor; class ServiceDescriptor; namespace compiler { @@ -56,32 +57,56 @@ namespace java { // // Returns: // The fully-qualified Java class name. -string ClassName(const Descriptor* descriptor); +std::string ClassName(const Descriptor* descriptor); // Requires: // descriptor != NULL // // Returns: // The fully-qualified Java class name. -string ClassName(const EnumDescriptor* descriptor); +std::string ClassName(const EnumDescriptor* descriptor); // Requires: // descriptor != NULL // // Returns: // The fully-qualified Java class name. -string ClassName(const FileDescriptor* descriptor); +std::string ClassName(const FileDescriptor* descriptor); // Requires: // descriptor != NULL // // Returns: // The fully-qualified Java class name. -string ClassName(const ServiceDescriptor* descriptor); +std::string ClassName(const ServiceDescriptor* descriptor); + +// Requires: +// descriptor != NULL +// +// Returns: +// Java package name. +std::string FileJavaPackage(const FileDescriptor* descriptor); + +// Requires: +// descriptor != NULL +// Returns: +// Captialized camel case name field name. +std::string CapitalizedFieldName(const FieldDescriptor* descriptor); + +// Requires: +// descriptor != NULL +// Returns: +// Primitive Java type name for the field. +const char* PrimitiveTypeName(const FieldDescriptor* descriptor); + +// Requires: +// descriptor != NULL +// Returns: +// Boes primitive Java type name for the field. +const char* BoxedPrimitiveTypeName(const FieldDescriptor* descriptor); } // namespace java } // namespace compiler } // namespace protobuf } // namespace google - #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_NAMES_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_options.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_options.h index e4e7d5e2..6c29be15 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_options.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_options.h @@ -68,6 +68,6 @@ struct Options { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_OPTIONS_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_plugin_unittest.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_plugin_unittest.cc index 87f687da..744b2c8b 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_plugin_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_plugin_unittest.cc @@ -38,8 +38,8 @@ #include #include -#include #include +#include #include #include @@ -58,10 +58,9 @@ class TestGenerator : public CodeGenerator { ~TestGenerator() {} virtual bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const { - string filename = "Test.java"; + const std::string& parameter, GeneratorContext* context, + std::string* error) const { + std::string filename = "Test.java"; TryInsert(filename, "outer_class_scope", context); TryInsert(filename, "class_scope:foo.Bar", context); TryInsert(filename, "class_scope:foo.Bar.Baz", context); @@ -71,7 +70,8 @@ class TestGenerator : public CodeGenerator { return true; } - void TryInsert(const string& filename, const string& insertion_point, + void TryInsert(const std::string& filename, + const std::string& insertion_point, GeneratorContext* context) const { std::unique_ptr output( context->OpenForInsert(filename, insertion_point)); @@ -95,7 +95,7 @@ TEST(JavaPluginTest, PluginTest) { "enum Qux { BLAH = 1; }\n", true)); - google::protobuf::compiler::CommandLineInterface cli; + CommandLineInterface cli; cli.SetInputsAreProtoPathRelative(true); JavaGenerator java_generator; @@ -103,17 +103,12 @@ TEST(JavaPluginTest, PluginTest) { cli.RegisterGenerator("--java_out", &java_generator, ""); cli.RegisterGenerator("--test_out", &test_generator, ""); - string proto_path = "-I" + TestTempDir(); - string java_out = "--java_out=" + TestTempDir(); - string test_out = "--test_out=" + TestTempDir(); + std::string proto_path = "-I" + TestTempDir(); + std::string java_out = "--java_out=" + TestTempDir(); + std::string test_out = "--test_out=" + TestTempDir(); - const char* argv[] = { - "protoc", - proto_path.c_str(), - java_out.c_str(), - test_out.c_str(), - "test.proto" - }; + const char* argv[] = {"protoc", proto_path.c_str(), java_out.c_str(), + test_out.c_str(), "test.proto"}; EXPECT_EQ(0, cli.Run(5, argv)); } diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_primitive_field.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_primitive_field.cc index 71ee0992..9aef29bd 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_primitive_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_primitive_field.cc @@ -46,6 +46,7 @@ #include #include + namespace google { namespace protobuf { namespace compiler { @@ -57,27 +58,63 @@ using internal::WireFormatLite; namespace { void SetPrimitiveVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, + int messageBitIndex, int builderBitIndex, const FieldGeneratorInfo* info, ClassNameResolver* name_resolver, - std::map* variables) { + std::map* variables) { SetCommonFieldVariables(descriptor, info, variables); + JavaType javaType = GetJavaType(descriptor); - (*variables)["type"] = PrimitiveTypeName(GetJavaType(descriptor)); - (*variables)["boxed_type"] = BoxedPrimitiveTypeName(GetJavaType(descriptor)); + (*variables)["type"] = PrimitiveTypeName(javaType); + (*variables)["boxed_type"] = BoxedPrimitiveTypeName(javaType); (*variables)["field_type"] = (*variables)["type"]; - (*variables)["field_list_type"] = "java.util.List<" + - (*variables)["boxed_type"] + ">"; - (*variables)["empty_list"] = "java.util.Collections.emptyList()"; + + if (javaType == JAVATYPE_BOOLEAN || javaType == JAVATYPE_DOUBLE || + javaType == JAVATYPE_FLOAT || javaType == JAVATYPE_INT || + javaType == JAVATYPE_LONG) { + std::string capitalized_type = UnderscoresToCamelCase( + PrimitiveTypeName(javaType), /*cap_first_letter=*/true); + (*variables)["field_list_type"] = + "com.google.protobuf.Internal." + capitalized_type + "List"; + (*variables)["empty_list"] = "empty" + capitalized_type + "List()"; + (*variables)["create_list"] = "new" + capitalized_type + "List()"; + (*variables)["mutable_copy_list"] = + "mutableCopy(" + (*variables)["name"] + "_)"; + (*variables)["name_make_immutable"] = + (*variables)["name"] + "_.makeImmutable()"; + (*variables)["repeated_get"] = + (*variables)["name"] + "_.get" + capitalized_type; + (*variables)["repeated_add"] = + (*variables)["name"] + "_.add" + capitalized_type; + (*variables)["repeated_set"] = + (*variables)["name"] + "_.set" + capitalized_type; + } else { + (*variables)["field_list_type"] = + "java.util.List<" + (*variables)["boxed_type"] + ">"; + (*variables)["create_list"] = + "new java.util.ArrayList<" + (*variables)["boxed_type"] + ">()"; + (*variables)["mutable_copy_list"] = "new java.util.ArrayList<" + + (*variables)["boxed_type"] + ">(" + + (*variables)["name"] + "_)"; + (*variables)["empty_list"] = "java.util.Collections.emptyList()"; + (*variables)["name_make_immutable"] = + (*variables)["name"] + "_ = java.util.Collections.unmodifiableList(" + + (*variables)["name"] + "_)"; + (*variables)["repeated_get"] = (*variables)["name"] + "_.get"; + (*variables)["repeated_add"] = (*variables)["name"] + "_.add"; + (*variables)["repeated_set"] = (*variables)["name"] + "_.set"; + } + (*variables)["default"] = ImmutableDefaultValue(descriptor, name_resolver); - (*variables)["default_init"] = IsDefaultValueJavaDefault(descriptor) ? - "" : ("= " + ImmutableDefaultValue(descriptor, name_resolver)); + (*variables)["default_init"] = + IsDefaultValueJavaDefault(descriptor) + ? "" + : ("= " + ImmutableDefaultValue(descriptor, name_resolver)); (*variables)["capitalized_type"] = GetCapitalizedType(descriptor, /* immutable = */ true); (*variables)["tag"] = - SimpleItoa(static_cast(WireFormat::MakeTag(descriptor))); - (*variables)["tag_size"] = SimpleItoa( + StrCat(static_cast(WireFormat::MakeTag(descriptor))); + (*variables)["tag_size"] = StrCat( WireFormat::TagSize(descriptor->number(), GetType(descriptor))); if (IsReferenceType(GetJavaType(descriptor))) { (*variables)["null_check"] = @@ -89,11 +126,11 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor, } // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; + (*variables)["deprecation"] = + descriptor->options().deprecated() ? "@java.lang.Deprecated " : ""; int fixed_size = FixedSize(GetType(descriptor)); if (fixed_size != -1) { - (*variables)["fixed_size"] = SimpleItoa(fixed_size); + (*variables)["fixed_size"] = StrCat(fixed_size); } (*variables)["on_changed"] = "onChanged();"; @@ -147,14 +184,10 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor, // =================================================================== -ImmutablePrimitiveFieldGenerator:: -ImmutablePrimitiveFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { +ImmutablePrimitiveFieldGenerator::ImmutablePrimitiveFieldGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, + Context* context) + : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) { SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex, context->GetFieldGeneratorInfo(descriptor), name_resolver_, &variables_); @@ -163,205 +196,218 @@ ImmutablePrimitiveFieldGenerator(const FieldDescriptor* descriptor, ImmutablePrimitiveFieldGenerator::~ImmutablePrimitiveFieldGenerator() {} int ImmutablePrimitiveFieldGenerator::GetNumBitsForMessage() const { - return 1; + return SupportFieldPresence(descriptor_->file()) ? 1 : 0; } int ImmutablePrimitiveFieldGenerator::GetNumBitsForBuilder() const { - return 1; + return GetNumBitsForMessage(); } -void ImmutablePrimitiveFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { +void ImmutablePrimitiveFieldGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); + "$deprecation$boolean has$capitalized_name$();\n"); } WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$();\n"); + printer->Print(variables_, "$deprecation$$type$ get$capitalized_name$();\n"); } -void ImmutablePrimitiveFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private $field_type$ $name$_;\n"); +void ImmutablePrimitiveFieldGenerator::GenerateMembers( + io::Printer* printer) const { + printer->Print(variables_, "private $field_type$ $name$_;\n"); PrintExtraFieldInfo(variables_, printer); if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $get_has_field_bit_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return $name$_;\n" - "}\n"); + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " return $name$_;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } -void ImmutablePrimitiveFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - printer->Print(variables_, - "private $field_type$ $name$_ $default_init$;\n"); +void ImmutablePrimitiveFieldGenerator::GenerateBuilderMembers( + io::Printer* printer) const { + printer->Print(variables_, "private $field_type$ $name$_ $default_init$;\n"); if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_builder$;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $get_has_field_bit_builder$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return $name$_;\n" - "}\n"); + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " return $name$_;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - "$null_check$" - " $set_has_field_bit_builder$\n" - " $name$_ = value;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder " + "${$set$capitalized_name$$}$($type$ value) {\n" + "$null_check$" + " $set_has_field_bit_builder$\n" + " $name$_ = value;\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " $clear_has_field_bit_builder$\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " $clear_has_field_bit_builder$\n"); printer->Annotate("{", "}", descriptor_); JavaType type = GetJavaType(descriptor_); if (type == JAVATYPE_STRING || type == JAVATYPE_BYTES) { // The default value is not a simple literal so we want to avoid executing // it multiple times. Instead, get the default out of the default instance. - printer->Print(variables_, - " $name$_ = getDefaultInstance().get$capitalized_name$();\n"); + printer->Print( + variables_, + " $name$_ = getDefaultInstance().get$capitalized_name$();\n"); } else { - printer->Print(variables_, - " $name$_ = $default$;\n"); + printer->Print(variables_, " $name$_ = $default$;\n"); } printer->Print(variables_, - " $on_changed$\n" - " return this;\n" - "}\n"); + " $on_changed$\n" + " return this;\n" + "}\n"); } -void ImmutablePrimitiveFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { +void ImmutablePrimitiveFieldGenerator::GenerateFieldBuilderInitializationCode( + io::Printer* printer) const { // noop for primitives } -void ImmutablePrimitiveFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $default$;\n"); +void ImmutablePrimitiveFieldGenerator::GenerateInitializationCode( + io::Printer* printer) const { + if (!IsDefaultValueJavaDefault(descriptor_)) { + printer->Print(variables_, "$name$_ = $default$;\n"); + } } -void ImmutablePrimitiveFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { +void ImmutablePrimitiveFieldGenerator::GenerateBuilderClearCode( + io::Printer* printer) const { printer->Print(variables_, - "$name$_ = $default$;\n" - "$clear_has_field_bit_builder$\n"); + "$name$_ = $default$;\n" + "$clear_has_field_bit_builder$\n"); } -void ImmutablePrimitiveFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { +void ImmutablePrimitiveFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { printer->Print(variables_, - "if (other.has$capitalized_name$()) {\n" - " set$capitalized_name$(other.get$capitalized_name$());\n" - "}\n"); + "if (other.has$capitalized_name$()) {\n" + " set$capitalized_name$(other.get$capitalized_name$());\n" + "}\n"); } else { printer->Print(variables_, - "if (other.get$capitalized_name$() != $default$) {\n" - " set$capitalized_name$(other.get$capitalized_name$());\n" - "}\n"); + "if (other.get$capitalized_name$() != $default$) {\n" + " set$capitalized_name$(other.get$capitalized_name$());\n" + "}\n"); } } -void ImmutablePrimitiveFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { +void ImmutablePrimitiveFieldGenerator::GenerateBuildingCode( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "if ($get_has_field_bit_from_local$) {\n" - " $set_has_field_bit_to_local$;\n" - "}\n"); + if (IsDefaultValueJavaDefault(descriptor_)) { + printer->Print(variables_, + "if ($get_has_field_bit_from_local$) {\n" + " result.$name$_ = $name$_;\n" + " $set_has_field_bit_to_local$;\n" + "}\n"); + } else { + printer->Print(variables_, + "if ($get_has_field_bit_from_local$) {\n" + " $set_has_field_bit_to_local$;\n" + "}\n" + "result.$name$_ = $name$_;\n"); + } + } else { + printer->Print(variables_, "result.$name$_ = $name$_;\n"); } - printer->Print(variables_, - "result.$name$_ = $name$_;\n"); } -void ImmutablePrimitiveFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { +void ImmutablePrimitiveFieldGenerator::GenerateParsingCode( + io::Printer* printer) const { printer->Print(variables_, - "$set_has_field_bit_message$\n" - "$name$_ = input.read$capitalized_type$();\n"); + "$set_has_field_bit_message$\n" + "$name$_ = input.read$capitalized_type$();\n"); } -void ImmutablePrimitiveFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { +void ImmutablePrimitiveFieldGenerator::GenerateParsingDoneCode( + io::Printer* printer) const { // noop for primitives. } -void ImmutablePrimitiveFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { +void ImmutablePrimitiveFieldGenerator::GenerateSerializationCode( + io::Printer* printer) const { printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " output.write$capitalized_type$($number$, $name$_);\n" - "}\n"); + "if ($is_field_present_message$) {\n" + " output.write$capitalized_type$($number$, $name$_);\n" + "}\n"); } -void ImmutablePrimitiveFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { +void ImmutablePrimitiveFieldGenerator::GenerateSerializedSizeCode( + io::Printer* printer) const { printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$capitalized_type$Size($number$, $name$_);\n" - "}\n"); + "if ($is_field_present_message$) {\n" + " size += com.google.protobuf.CodedOutputStream\n" + " .compute$capitalized_type$Size($number$, $name$_);\n" + "}\n"); } -void ImmutablePrimitiveFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { +void ImmutablePrimitiveFieldGenerator::GenerateEqualsCode( + io::Printer* printer) const { switch (GetJavaType(descriptor_)) { case JAVATYPE_INT: case JAVATYPE_LONG: case JAVATYPE_BOOLEAN: printer->Print(variables_, - "result = result && (get$capitalized_name$()\n" - " == other.get$capitalized_name$());\n"); + "if (get$capitalized_name$()\n" + " != other.get$capitalized_name$()) return false;\n"); break; case JAVATYPE_FLOAT: - printer->Print(variables_, - "result = result && (\n" - " java.lang.Float.floatToIntBits(get$capitalized_name$())\n" - " == java.lang.Float.floatToIntBits(\n" - " other.get$capitalized_name$()));\n"); + printer->Print( + variables_, + "if (java.lang.Float.floatToIntBits(get$capitalized_name$())\n" + " != java.lang.Float.floatToIntBits(\n" + " other.get$capitalized_name$())) return false;\n"); break; case JAVATYPE_DOUBLE: - printer->Print(variables_, - "result = result && (\n" - " java.lang.Double.doubleToLongBits(get$capitalized_name$())\n" - " == java.lang.Double.doubleToLongBits(\n" - " other.get$capitalized_name$()));\n"); + printer->Print( + variables_, + "if (java.lang.Double.doubleToLongBits(get$capitalized_name$())\n" + " != java.lang.Double.doubleToLongBits(\n" + " other.get$capitalized_name$())) return false;\n"); break; case JAVATYPE_STRING: case JAVATYPE_BYTES: - printer->Print(variables_, - "result = result && get$capitalized_name$()\n" - " .equals(other.get$capitalized_name$());\n"); + printer->Print( + variables_, + "if (!get$capitalized_name$()\n" + " .equals(other.get$capitalized_name$())) return false;\n"); break; case JAVATYPE_ENUM: @@ -372,44 +418,47 @@ GenerateEqualsCode(io::Printer* printer) const { } } -void ImmutablePrimitiveFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n"); +void ImmutablePrimitiveFieldGenerator::GenerateHashCode( + io::Printer* printer) const { + printer->Print(variables_, "hash = (37 * hash) + $constant_name$;\n"); switch (GetJavaType(descriptor_)) { case JAVATYPE_INT: printer->Print(variables_, - "hash = (53 * hash) + get$capitalized_name$();\n"); + "hash = (53 * hash) + get$capitalized_name$();\n"); break; case JAVATYPE_LONG: - printer->Print(variables_, - "hash = (53 * hash) + com.google.protobuf.Internal.hashLong(\n" - " get$capitalized_name$());\n"); + printer->Print( + variables_, + "hash = (53 * hash) + com.google.protobuf.Internal.hashLong(\n" + " get$capitalized_name$());\n"); break; case JAVATYPE_BOOLEAN: - printer->Print(variables_, - "hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(\n" - " get$capitalized_name$());\n"); + printer->Print( + variables_, + "hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(\n" + " get$capitalized_name$());\n"); break; case JAVATYPE_FLOAT: printer->Print(variables_, - "hash = (53 * hash) + java.lang.Float.floatToIntBits(\n" - " get$capitalized_name$());\n"); + "hash = (53 * hash) + java.lang.Float.floatToIntBits(\n" + " get$capitalized_name$());\n"); break; case JAVATYPE_DOUBLE: - printer->Print(variables_, - "hash = (53 * hash) + com.google.protobuf.Internal.hashLong(\n" - " java.lang.Double.doubleToLongBits(get$capitalized_name$()));\n"); + printer->Print( + variables_, + "hash = (53 * hash) + com.google.protobuf.Internal.hashLong(\n" + " java.lang.Double.doubleToLongBits(get$capitalized_name$()));\n"); break; case JAVATYPE_STRING: case JAVATYPE_BYTES: - printer->Print(variables_, - "hash = (53 * hash) + get$capitalized_name$().hashCode();\n"); + printer->Print( + variables_, + "hash = (53 * hash) + get$capitalized_name$().hashCode();\n"); break; case JAVATYPE_ENUM: @@ -420,171 +469,168 @@ GenerateHashCode(io::Printer* printer) const { } } -string ImmutablePrimitiveFieldGenerator::GetBoxedType() const { +std::string ImmutablePrimitiveFieldGenerator::GetBoxedType() const { return BoxedPrimitiveTypeName(GetJavaType(descriptor_)); } // =================================================================== -ImmutablePrimitiveOneofFieldGenerator:: -ImmutablePrimitiveOneofFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutablePrimitiveFieldGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { +ImmutablePrimitiveOneofFieldGenerator::ImmutablePrimitiveOneofFieldGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, + Context* context) + : ImmutablePrimitiveFieldGenerator(descriptor, messageBitIndex, + builderBitIndex, context) { const OneofGeneratorInfo* info = context->GetOneofGeneratorInfo(descriptor->containing_oneof()); SetCommonOneofVariables(descriptor, info, &variables_); } ImmutablePrimitiveOneofFieldGenerator:: -~ImmutablePrimitiveOneofFieldGenerator() {} + ~ImmutablePrimitiveOneofFieldGenerator() {} -void ImmutablePrimitiveOneofFieldGenerator:: -GenerateMembers(io::Printer* printer) const { +void ImmutablePrimitiveOneofFieldGenerator::GenerateMembers( + io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $has_oneof_case_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($boxed_type$) $oneof_name$_;\n" - " }\n" - " return $default$;\n" - "}\n"); + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " if ($has_oneof_case_message$) {\n" + " return ($boxed_type$) $oneof_name$_;\n" + " }\n" + " return $default$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } - -void ImmutablePrimitiveOneofFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void ImmutablePrimitiveOneofFieldGenerator::GenerateBuilderMembers( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $has_oneof_case_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($boxed_type$) $oneof_name$_;\n" - " }\n" - " return $default$;\n" - "}\n"); + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " if ($has_oneof_case_message$) {\n" + " return ($boxed_type$) $oneof_name$_;\n" + " }\n" + " return $default$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - "$null_check$" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder " + "${$set$capitalized_name$$}$($type$ value) {\n" + "$null_check$" + " $set_oneof_case_message$;\n" + " $oneof_name$_ = value;\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " $on_changed$\n" - " }\n" - " return this;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " if ($has_oneof_case_message$) {\n" + " $clear_oneof_case_message$;\n" + " $oneof_name$_ = null;\n" + " $on_changed$\n" + " }\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } -void ImmutablePrimitiveOneofFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { +void ImmutablePrimitiveOneofFieldGenerator::GenerateBuildingCode( + io::Printer* printer) const { printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " result.$oneof_name$_ = $oneof_name$_;\n" - "}\n"); + "if ($has_oneof_case_message$) {\n" + " result.$oneof_name$_ = $oneof_name$_;\n" + "}\n"); } -void ImmutablePrimitiveOneofFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { +void ImmutablePrimitiveOneofFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { printer->Print(variables_, - "set$capitalized_name$(other.get$capitalized_name$());\n"); + "set$capitalized_name$(other.get$capitalized_name$());\n"); } -void ImmutablePrimitiveOneofFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { +void ImmutablePrimitiveOneofFieldGenerator::GenerateParsingCode( + io::Printer* printer) const { printer->Print(variables_, - "$set_oneof_case_message$;\n" - "$oneof_name$_ = input.read$capitalized_type$();\n"); + "$set_oneof_case_message$;\n" + "$oneof_name$_ = input.read$capitalized_type$();\n"); } -void ImmutablePrimitiveOneofFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { +void ImmutablePrimitiveOneofFieldGenerator::GenerateSerializationCode( + io::Printer* printer) const { printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.write$capitalized_type$(\n"); + "if ($has_oneof_case_message$) {\n" + " output.write$capitalized_type$(\n"); // $type$ and $boxed_type$ is the same for bytes fields so we don't need to // do redundant casts. if (GetJavaType(descriptor_) == JAVATYPE_BYTES) { - printer->Print(variables_, - " $number$, ($type$) $oneof_name$_);\n"); + printer->Print(variables_, " $number$, ($type$) $oneof_name$_);\n"); } else { - printer->Print(variables_, - " $number$, ($type$)(($boxed_type$) $oneof_name$_));\n"); + printer->Print( + variables_, + " $number$, ($type$)(($boxed_type$) $oneof_name$_));\n"); } - printer->Print( - "}\n"); + printer->Print("}\n"); } -void ImmutablePrimitiveOneofFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { +void ImmutablePrimitiveOneofFieldGenerator::GenerateSerializedSizeCode( + io::Printer* printer) const { printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$capitalized_type$Size(\n"); + "if ($has_oneof_case_message$) {\n" + " size += com.google.protobuf.CodedOutputStream\n" + " .compute$capitalized_type$Size(\n"); // $type$ and $boxed_type$ is the same for bytes fields so we don't need to // do redundant casts. if (GetJavaType(descriptor_) == JAVATYPE_BYTES) { - printer->Print(variables_, - " $number$, ($type$) $oneof_name$_);\n"); + printer->Print(variables_, " $number$, ($type$) $oneof_name$_);\n"); } else { - printer->Print(variables_, - " $number$, ($type$)(($boxed_type$) $oneof_name$_));\n"); + printer->Print( + variables_, + " $number$, ($type$)(($boxed_type$) $oneof_name$_));\n"); } - printer->Print( - "}\n"); + printer->Print("}\n"); } // =================================================================== RepeatedImmutablePrimitiveFieldGenerator:: -RepeatedImmutablePrimitiveFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { + RepeatedImmutablePrimitiveFieldGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, + int builderBitIndex, + Context* context) + : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) { SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex, context->GetFieldGeneratorInfo(descriptor), name_resolver_, &variables_); } RepeatedImmutablePrimitiveFieldGenerator:: -~RepeatedImmutablePrimitiveFieldGenerator() {} + ~RepeatedImmutablePrimitiveFieldGenerator() {} int RepeatedImmutablePrimitiveFieldGenerator::GetNumBitsForMessage() const { return 0; @@ -594,53 +640,54 @@ int RepeatedImmutablePrimitiveFieldGenerator::GetNumBitsForBuilder() const { return 1; } -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { +void RepeatedImmutablePrimitiveFieldGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$java.util.List<$boxed_type$> get$capitalized_name$List();\n"); + "$deprecation$java.util.List<$boxed_type$> " + "get$capitalized_name$List();\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); + "$deprecation$int get$capitalized_name$Count();\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$(int index);\n"); + "$deprecation$$type$ get$capitalized_name$(int index);\n"); } - -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private $field_list_type$ $name$_;\n"); +void RepeatedImmutablePrimitiveFieldGenerator::GenerateMembers( + io::Printer* printer) const { + printer->Print(variables_, "private $field_list_type$ $name$_;\n"); PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public java.util.List<$boxed_type$>\n" - " ${$get$capitalized_name$List$}$() {\n" - " return $name$_;\n" // note: unmodifiable list - "}\n"); + "$deprecation$public java.util.List<$boxed_type$>\n" + " ${$get$capitalized_name$List$}$() {\n" + " return $name$_;\n" // note: unmodifiable list + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" + " return $name$_.size();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" + " return $repeated_get$(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); if (descriptor_->is_packed()) { printer->Print(variables_, - "private int $name$MemoizedSerializedSize = -1;\n"); + "private int $name$MemoizedSerializedSize = -1;\n"); } } -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void RepeatedImmutablePrimitiveFieldGenerator::GenerateBuilderMembers( + io::Printer* printer) const { // One field is the list and the bit field keeps track of whether the // list is immutable. If it's immutable, the invariant is that it must // either an instance of Collections.emptyList() or it's an ArrayList @@ -651,246 +698,257 @@ GenerateBuilderMembers(io::Printer* printer) const { // just that the list cannot be modified via the reference but that the // list can never be modified. printer->Print(variables_, - "private $field_list_type$ $name$_ = $empty_list$;\n"); + "private $field_list_type$ $name$_ = $empty_list$;\n"); printer->Print(variables_, - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$get_mutable_bit_builder$) {\n" - " $name$_ = new java.util.ArrayList<$boxed_type$>($name$_);\n" - " $set_mutable_bit_builder$;\n" - " }\n" - "}\n"); + "private void ensure$capitalized_name$IsMutable() {\n" + " if (!$get_mutable_bit_builder$) {\n" + " $name$_ = $mutable_copy_list$;\n" + " $set_mutable_bit_builder$;\n" + " }\n" + "}\n"); - // Note: We return an unmodifiable list because otherwise the caller - // could hold on to the returned list and modify it after the message - // has been built, thus mutating the message which is supposed to be - // immutable. + // Note: We return an unmodifiable list because otherwise the caller + // could hold on to the returned list and modify it after the message + // has been built, thus mutating the message which is supposed to be + // immutable. WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List<$boxed_type$>\n" - " ${$get$capitalized_name$List$}$() {\n" - " return java.util.Collections.unmodifiableList($name$_);\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public java.util.List<$boxed_type$>\n" + " ${$get$capitalized_name$List$}$() {\n" + " return $get_mutable_bit_builder$ ?\n" + " java.util.Collections.unmodifiableList($name$_) : $name$_;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" + " return $name$_.size();\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" + " return $repeated_get$(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " int index, $type$ value) {\n" + "$null_check$" + " ensure$capitalized_name$IsMutable();\n" + " $repeated_set$(index, value);\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); + "$deprecation$public Builder " + "${$add$capitalized_name$$}$($type$ value) {\n" + "$null_check$" + " ensure$capitalized_name$IsMutable();\n" + " $repeated_add$(value);\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, $type$ value) {\n" - "$null_check$" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(index, value);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" + " java.lang.Iterable values) {\n" + " ensure$capitalized_name$IsMutable();\n" + " com.google.protobuf.AbstractMessageLite.Builder.addAll(\n" + " values, $name$_);\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n" - "$null_check$" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(value);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " com.google.protobuf.AbstractMessageLite.Builder.addAll(\n" - " values, $name$_);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " $name$_ = $empty_list$;\n" - " $clear_mutable_bit_builder$;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " $name$_ = $empty_list$;\n" + " $clear_mutable_bit_builder$;\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { + GenerateFieldBuilderInitializationCode(io::Printer* printer) const { // noop for primitives } -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { +void RepeatedImmutablePrimitiveFieldGenerator::GenerateInitializationCode( + io::Printer* printer) const { printer->Print(variables_, "$name$_ = $empty_list$;\n"); } -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { +void RepeatedImmutablePrimitiveFieldGenerator::GenerateBuilderClearCode( + io::Printer* printer) const { printer->Print(variables_, - "$name$_ = $empty_list$;\n" - "$clear_mutable_bit_builder$;\n"); + "$name$_ = $empty_list$;\n" + "$clear_mutable_bit_builder$;\n"); } -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { +void RepeatedImmutablePrimitiveFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { // The code below does two optimizations: // 1. If the other list is empty, there's nothing to do. This ensures we // don't allocate a new array if we already have an immutable one. // 2. If the other list is non-empty and our current list is empty, we can // reuse the other list which is guaranteed to be immutable. printer->Print(variables_, - "if (!other.$name$_.isEmpty()) {\n" - " if ($name$_.isEmpty()) {\n" - " $name$_ = other.$name$_;\n" - " $clear_mutable_bit_builder$;\n" - " } else {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.addAll(other.$name$_);\n" - " }\n" - " $on_changed$\n" - "}\n"); + "if (!other.$name$_.isEmpty()) {\n" + " if ($name$_.isEmpty()) {\n" + " $name$_ = other.$name$_;\n" + " $clear_mutable_bit_builder$;\n" + " } else {\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.addAll(other.$name$_);\n" + " }\n" + " $on_changed$\n" + "}\n"); } -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { +void RepeatedImmutablePrimitiveFieldGenerator::GenerateBuildingCode( + io::Printer* printer) const { // The code below ensures that the result has an immutable list. If our // list is immutable, we can just reuse it. If not, we make it immutable. printer->Print(variables_, - "if ($get_mutable_bit_builder$) {\n" - " $name$_ = java.util.Collections.unmodifiableList($name$_);\n" - " $clear_mutable_bit_builder$;\n" - "}\n" - "result.$name$_ = $name$_;\n"); + "if ($get_mutable_bit_builder$) {\n" + " $name_make_immutable$;\n" + " $clear_mutable_bit_builder$;\n" + "}\n" + "result.$name$_ = $name$_;\n"); } -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { +void RepeatedImmutablePrimitiveFieldGenerator::GenerateParsingCode( + io::Printer* printer) const { printer->Print(variables_, - "if (!$get_mutable_bit_parser$) {\n" - " $name$_ = new java.util.ArrayList<$boxed_type$>();\n" - " $set_mutable_bit_parser$;\n" - "}\n" - "$name$_.add(input.read$capitalized_type$());\n"); + "if (!$get_mutable_bit_parser$) {\n" + " $name$_ = $create_list$;\n" + " $set_mutable_bit_parser$;\n" + "}\n" + "$repeated_add$(input.read$capitalized_type$());\n"); } -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateParsingCodeFromPacked(io::Printer* printer) const { +void RepeatedImmutablePrimitiveFieldGenerator::GenerateParsingCodeFromPacked( + io::Printer* printer) const { + printer->Print( + variables_, + "int length = input.readRawVarint32();\n" + "int limit = input.pushLimit(length);\n" + "if (!$get_mutable_bit_parser$ && input.getBytesUntilLimit() > 0) {\n" + " $name$_ = $create_list$;\n" + " $set_mutable_bit_parser$;\n" + "}\n" + "while (input.getBytesUntilLimit() > 0) {\n" + " $repeated_add$(input.read$capitalized_type$());\n" + "}\n" + "input.popLimit(limit);\n"); +} + +void RepeatedImmutablePrimitiveFieldGenerator::GenerateParsingDoneCode( + io::Printer* printer) const { printer->Print(variables_, - "int length = input.readRawVarint32();\n" - "int limit = input.pushLimit(length);\n" - "if (!$get_mutable_bit_parser$ && input.getBytesUntilLimit() > 0) {\n" - " $name$_ = new java.util.ArrayList<$boxed_type$>();\n" - " $set_mutable_bit_parser$;\n" - "}\n" - "while (input.getBytesUntilLimit() > 0) {\n" - " $name$_.add(input.read$capitalized_type$());\n" - "}\n" - "input.popLimit(limit);\n"); + "if ($get_mutable_bit_parser$) {\n" + " $name_make_immutable$; // C\n" + "}\n"); } -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($get_mutable_bit_parser$) {\n" - " $name$_ = java.util.Collections.unmodifiableList($name$_);\n" - "}\n"); -} - -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { +void RepeatedImmutablePrimitiveFieldGenerator::GenerateSerializationCode( + io::Printer* printer) const { if (descriptor_->is_packed()) { // We invoke getSerializedSize in writeTo for messages that have packed // fields in ImmutableMessageGenerator::GenerateMessageSerializationMethods. // That makes it safe to rely on the memoized size here. printer->Print(variables_, - "if (get$capitalized_name$List().size() > 0) {\n" - " output.writeUInt32NoTag($tag$);\n" - " output.writeUInt32NoTag($name$MemoizedSerializedSize);\n" - "}\n" - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.write$capitalized_type$NoTag($name$_.get(i));\n" - "}\n"); + "if (get$capitalized_name$List().size() > 0) {\n" + " output.writeUInt32NoTag($tag$);\n" + " output.writeUInt32NoTag($name$MemoizedSerializedSize);\n" + "}\n" + "for (int i = 0; i < $name$_.size(); i++) {\n" + " output.write$capitalized_type$NoTag($repeated_get$(i));\n" + "}\n"); } else { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.write$capitalized_type$($number$, $name$_.get(i));\n" - "}\n"); + printer->Print( + variables_, + "for (int i = 0; i < $name$_.size(); i++) {\n" + " output.write$capitalized_type$($number$, $repeated_get$(i));\n" + "}\n"); } } -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { +void RepeatedImmutablePrimitiveFieldGenerator::GenerateSerializedSizeCode( + io::Printer* printer) const { printer->Print(variables_, - "{\n" - " int dataSize = 0;\n"); + "{\n" + " int dataSize = 0;\n"); printer->Indent(); if (FixedSize(GetType(descriptor_)) == -1) { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " dataSize += com.google.protobuf.CodedOutputStream\n" - " .compute$capitalized_type$SizeNoTag($name$_.get(i));\n" - "}\n"); + printer->Print( + variables_, + "for (int i = 0; i < $name$_.size(); i++) {\n" + " dataSize += com.google.protobuf.CodedOutputStream\n" + " .compute$capitalized_type$SizeNoTag($repeated_get$(i));\n" + "}\n"); } else { - printer->Print(variables_, - "dataSize = $fixed_size$ * get$capitalized_name$List().size();\n"); + printer->Print( + variables_, + "dataSize = $fixed_size$ * get$capitalized_name$List().size();\n"); } - printer->Print( - "size += dataSize;\n"); + printer->Print("size += dataSize;\n"); if (descriptor_->is_packed()) { printer->Print(variables_, - "if (!get$capitalized_name$List().isEmpty()) {\n" - " size += $tag_size$;\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeInt32SizeNoTag(dataSize);\n" - "}\n"); + "if (!get$capitalized_name$List().isEmpty()) {\n" + " size += $tag_size$;\n" + " size += com.google.protobuf.CodedOutputStream\n" + " .computeInt32SizeNoTag(dataSize);\n" + "}\n"); } else { - printer->Print(variables_, - "size += $tag_size$ * get$capitalized_name$List().size();\n"); + printer->Print( + variables_, + "size += $tag_size$ * get$capitalized_name$List().size();\n"); } // cache the data size for packed fields. if (descriptor_->is_packed()) { - printer->Print(variables_, - "$name$MemoizedSerializedSize = dataSize;\n"); + printer->Print(variables_, "$name$MemoizedSerializedSize = dataSize;\n"); } printer->Outdent(); printer->Print("}\n"); } -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && get$capitalized_name$List()\n" - " .equals(other.get$capitalized_name$List());\n"); +void RepeatedImmutablePrimitiveFieldGenerator::GenerateEqualsCode( + io::Printer* printer) const { + printer->Print( + variables_, + "if (!get$capitalized_name$List()\n" + " .equals(other.get$capitalized_name$List())) return false;\n"); } -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "if (get$capitalized_name$Count() > 0) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + get$capitalized_name$List().hashCode();\n" - "}\n"); +void RepeatedImmutablePrimitiveFieldGenerator::GenerateHashCode( + io::Printer* printer) const { + printer->Print( + variables_, + "if (get$capitalized_name$Count() > 0) {\n" + " hash = (37 * hash) + $constant_name$;\n" + " hash = (53 * hash) + get$capitalized_name$List().hashCode();\n" + "}\n"); } -string RepeatedImmutablePrimitiveFieldGenerator::GetBoxedType() const { +std::string RepeatedImmutablePrimitiveFieldGenerator::GetBoxedType() const { return BoxedPrimitiveTypeName(GetJavaType(descriptor_)); } diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_primitive_field.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_primitive_field.h index 7ac9bbfb..db20750e 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_primitive_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_primitive_field.h @@ -41,26 +41,30 @@ namespace google { namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } -} +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { class ImmutablePrimitiveFieldGenerator : public ImmutableFieldGenerator { public: - explicit ImmutablePrimitiveFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + explicit ImmutablePrimitiveFieldGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, + int builderBitIndex, + Context* context); ~ImmutablePrimitiveFieldGenerator(); - // implements ImmutableFieldGenerator --------------------------------------- + // implements ImmutableFieldGenerator + // --------------------------------------- int GetNumBitsForMessage() const; int GetNumBitsForBuilder() const; void GenerateInterfaceMembers(io::Printer* printer) const; @@ -78,14 +82,11 @@ class ImmutablePrimitiveFieldGenerator : public ImmutableFieldGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; + std::map variables_; ClassNameResolver* name_resolver_; private: @@ -95,9 +96,9 @@ class ImmutablePrimitiveFieldGenerator : public ImmutableFieldGenerator { class ImmutablePrimitiveOneofFieldGenerator : public ImmutablePrimitiveFieldGenerator { public: - ImmutablePrimitiveOneofFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + ImmutablePrimitiveOneofFieldGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, + int builderBitIndex, Context* context); ~ImmutablePrimitiveOneofFieldGenerator(); void GenerateMembers(io::Printer* printer) const; @@ -139,14 +140,11 @@ class RepeatedImmutablePrimitiveFieldGenerator void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; private: const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; + std::map variables_; ClassNameResolver* name_resolver_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutablePrimitiveFieldGenerator); @@ -155,6 +153,6 @@ class RepeatedImmutablePrimitiveFieldGenerator } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_PRIMITIVE_FIELD_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_primitive_field_lite.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_primitive_field_lite.cc index d2ebc567..880bd92d 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_primitive_field_lite.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_primitive_field_lite.cc @@ -46,6 +46,7 @@ #include #include + namespace google { namespace protobuf { namespace compiler { @@ -55,13 +56,19 @@ using internal::WireFormat; using internal::WireFormatLite; namespace { +bool EnableExperimentalRuntimeForLite() { +#ifdef PROTOBUF_EXPERIMENT + return PROTOBUF_EXPERIMENT; +#else // PROTOBUF_EXPERIMENT + return false; +#endif // !PROTOBUF_EXPERIMENT +} void SetPrimitiveVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, + int messageBitIndex, int builderBitIndex, const FieldGeneratorInfo* info, ClassNameResolver* name_resolver, - std::map* variables) { + std::map* variables) { SetCommonFieldVariables(descriptor, info, variables); JavaType javaType = GetJavaType(descriptor); (*variables)["type"] = PrimitiveTypeName(javaType); @@ -71,13 +78,13 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor, (*variables)["capitalized_type"] = GetCapitalizedType(descriptor, /* immutable = */ true); (*variables)["tag"] = - SimpleItoa(static_cast(WireFormat::MakeTag(descriptor))); - (*variables)["tag_size"] = SimpleItoa( + StrCat(static_cast(WireFormat::MakeTag(descriptor))); + (*variables)["tag_size"] = StrCat( WireFormat::TagSize(descriptor->number(), GetType(descriptor))); (*variables)["required"] = descriptor->is_required() ? "true" : "false"; - string capitalized_type = UnderscoresToCamelCase(PrimitiveTypeName(javaType), - true /* cap_next_letter */); + std::string capitalized_type = UnderscoresToCamelCase( + PrimitiveTypeName(javaType), true /* cap_next_letter */); switch (javaType) { case JAVATYPE_INT: case JAVATYPE_LONG: @@ -127,11 +134,11 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor, } // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; + (*variables)["deprecation"] = + descriptor->options().deprecated() ? "@java.lang.Deprecated " : ""; int fixed_size = FixedSize(GetType(descriptor)); if (fixed_size != -1) { - (*variables)["fixed_size"] = SimpleItoa(fixed_size); + (*variables)["fixed_size"] = StrCat(fixed_size); } if (SupportFieldPresence(descriptor->file())) { @@ -172,15 +179,12 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor, // =================================================================== -ImmutablePrimitiveFieldLiteGenerator:: -ImmutablePrimitiveFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex, +ImmutablePrimitiveFieldLiteGenerator::ImmutablePrimitiveFieldLiteGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, Context* context) + : descriptor_(descriptor), + messageBitIndex_(messageBitIndex), + name_resolver_(context->GetNameResolver()) { + SetPrimitiveVariables(descriptor, messageBitIndex, 0, context->GetFieldGeneratorInfo(descriptor), name_resolver_, &variables_); } @@ -188,27 +192,22 @@ ImmutablePrimitiveFieldLiteGenerator(const FieldDescriptor* descriptor, ImmutablePrimitiveFieldLiteGenerator::~ImmutablePrimitiveFieldLiteGenerator() {} int ImmutablePrimitiveFieldLiteGenerator::GetNumBitsForMessage() const { - return 1; + return SupportFieldPresence(descriptor_->file()) ? 1 : 0; } -int ImmutablePrimitiveFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { +void ImmutablePrimitiveFieldLiteGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); + "$deprecation$boolean has$capitalized_name$();\n"); } WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$();\n"); + printer->Print(variables_, "$deprecation$$type$ get$capitalized_name$();\n"); } -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { +void ImmutablePrimitiveFieldLiteGenerator::GenerateMembers( + io::Printer* printer) const { if (IsByteStringWithCustomDefaultValue(descriptor_)) { // allocate this once statically since we know ByteStrings are immutable // values that can be reused. @@ -216,100 +215,107 @@ GenerateMembers(io::Printer* printer) const { variables_, "private static final $field_type$ $bytes_default$ = $default$;\n"); } - printer->Print(variables_, - "private $field_type$ $name$_;\n"); + printer->Print(variables_, "private $field_type$ $name$_;\n"); PrintExtraFieldInfo(variables_, printer); if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $get_has_field_bit_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return $name$_;\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " return $name$_;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void set$capitalized_name$($type$ value) {\n" - "$null_check$" - " $set_has_field_bit_message$\n" - " $name$_ = value;\n" - "}\n"); + "private void set$capitalized_name$($type$ value) {\n" + "$null_check$" + " $set_has_field_bit_message$\n" + " $name$_ = value;\n" + "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $clear_has_field_bit_message$\n"); + "private void clear$capitalized_name$() {\n" + " $clear_has_field_bit_message$\n"); JavaType type = GetJavaType(descriptor_); if (type == JAVATYPE_STRING || type == JAVATYPE_BYTES) { // The default value is not a simple literal so we want to avoid executing // it multiple times. Instead, get the default out of the default instance. - printer->Print(variables_, - " $name$_ = getDefaultInstance().get$capitalized_name$();\n"); + printer->Print( + variables_, + " $name$_ = getDefaultInstance().get$capitalized_name$();\n"); } else { - printer->Print(variables_, - " $name$_ = $default$;\n"); + printer->Print(variables_, " $name$_ = $default$;\n"); } - printer->Print(variables_, - "}\n"); + printer->Print(variables_, "}\n"); } -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void ImmutablePrimitiveFieldLiteGenerator::GenerateBuilderMembers( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return instance.has$capitalized_name$();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " return instance.get$capitalized_name$();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder " + "${$set$capitalized_name$$}$($type$ value) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$(value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " copyOnWrite();\n" + " instance.clear$capitalized_name$();\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for primitives +void ImmutablePrimitiveFieldLiteGenerator::GenerateFieldInfo( + io::Printer* printer, std::vector* output) const { + WriteIntToUtf16CharSequence(descriptor_->number(), output); + WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_), + output); + if (SupportFieldPresence(descriptor_->file())) { + WriteIntToUtf16CharSequence(messageBitIndex_, output); + } + printer->Print(variables_, "\"$name$_\",\n"); } - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const { +void ImmutablePrimitiveFieldLiteGenerator::GenerateInitializationCode( + io::Printer* printer) const { if (IsByteStringWithCustomDefaultValue(descriptor_)) { printer->Print(variables_, "$name$_ = $bytes_default$;\n"); } else if (!IsDefaultValueJavaDefault(descriptor_)) { @@ -317,634 +323,307 @@ GenerateInitializationCode(io::Printer* printer) const { } } -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { - // noop for primitives -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "$name$_ = visitor.visit$visit_type$(\n" - " has$capitalized_name$(), $name$_,\n" - " other.has$capitalized_name$(), other.$name$_);\n"); - } else { - printer->Print(variables_, - "$name$_ = visitor.visit$visit_type$($name$_ != $default$, $name$_,\n" - " other.$name$_ != $default$, other.$name$_);\n"); - } -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - // noop for primitives -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - // noop for scalars -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "$set_has_field_bit_message$\n" - "$name$_ = input.read$capitalized_type$();\n"); -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - // noop for primitives. -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " output.write$capitalized_type$($number$, $name$_);\n" - "}\n"); -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$capitalized_type$Size($number$, $name$_);\n" - "}\n"); -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - switch (GetJavaType(descriptor_)) { - case JAVATYPE_INT: - case JAVATYPE_LONG: - case JAVATYPE_BOOLEAN: - printer->Print(variables_, - "result = result && (get$capitalized_name$()\n" - " == other.get$capitalized_name$());\n"); - break; - - case JAVATYPE_FLOAT: - printer->Print(variables_, - "result = result && (\n" - " java.lang.Float.floatToIntBits(get$capitalized_name$())\n" - " == java.lang.Float.floatToIntBits(\n" - " other.get$capitalized_name$()));\n"); - break; - - case JAVATYPE_DOUBLE: - printer->Print(variables_, - "result = result && (\n" - " java.lang.Double.doubleToLongBits(get$capitalized_name$())\n" - " == java.lang.Double.doubleToLongBits(\n" - " other.get$capitalized_name$()));\n"); - break; - - case JAVATYPE_STRING: - case JAVATYPE_BYTES: - printer->Print(variables_, - "result = result && get$capitalized_name$()\n" - " .equals(other.get$capitalized_name$());\n"); - break; - - case JAVATYPE_ENUM: - case JAVATYPE_MESSAGE: - default: - GOOGLE_LOG(FATAL) << "Can't get here."; - break; - } -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n"); - switch (GetJavaType(descriptor_)) { - case JAVATYPE_INT: - printer->Print(variables_, - "hash = (53 * hash) + get$capitalized_name$();\n"); - break; - - case JAVATYPE_LONG: - printer->Print(variables_, - "hash = (53 * hash) + com.google.protobuf.Internal.hashLong(\n" - " get$capitalized_name$());\n"); - break; - - case JAVATYPE_BOOLEAN: - printer->Print(variables_, - "hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(\n" - " get$capitalized_name$());\n"); - break; - - case JAVATYPE_FLOAT: - printer->Print(variables_, - "hash = (53 * hash) + java.lang.Float.floatToIntBits(\n" - " get$capitalized_name$());\n"); - break; - - case JAVATYPE_DOUBLE: - printer->Print(variables_, - "hash = (53 * hash) + com.google.protobuf.Internal.hashLong(\n" - " java.lang.Double.doubleToLongBits(get$capitalized_name$()));\n"); - break; - - case JAVATYPE_STRING: - case JAVATYPE_BYTES: - printer->Print(variables_, - "hash = (53 * hash) + get$capitalized_name$().hashCode();\n"); - break; - - case JAVATYPE_ENUM: - case JAVATYPE_MESSAGE: - default: - GOOGLE_LOG(FATAL) << "Can't get here."; - break; - } -} - -string ImmutablePrimitiveFieldLiteGenerator::GetBoxedType() const { +std::string ImmutablePrimitiveFieldLiteGenerator::GetBoxedType() const { return BoxedPrimitiveTypeName(GetJavaType(descriptor_)); } // =================================================================== ImmutablePrimitiveOneofFieldLiteGenerator:: -ImmutablePrimitiveOneofFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutablePrimitiveFieldLiteGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { + ImmutablePrimitiveOneofFieldLiteGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, + Context* context) + : ImmutablePrimitiveFieldLiteGenerator(descriptor, messageBitIndex, + context) { const OneofGeneratorInfo* info = context->GetOneofGeneratorInfo(descriptor->containing_oneof()); SetCommonOneofVariables(descriptor, info, &variables_); } ImmutablePrimitiveOneofFieldLiteGenerator:: -~ImmutablePrimitiveOneofFieldLiteGenerator() {} + ~ImmutablePrimitiveOneofFieldLiteGenerator() {} -void ImmutablePrimitiveOneofFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { +void ImmutablePrimitiveOneofFieldLiteGenerator::GenerateMembers( + io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $has_oneof_case_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($boxed_type$) $oneof_name$_;\n" - " }\n" - " return $default$;\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " if ($has_oneof_case_message$) {\n" + " return ($boxed_type$) $oneof_name$_;\n" + " }\n" + " return $default$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void set$capitalized_name$($type$ value) {\n" - "$null_check$" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value;\n" - "}\n"); + "private void set$capitalized_name$($type$ value) {\n" + "$null_check$" + " $set_oneof_case_message$;\n" + " $oneof_name$_ = value;\n" + "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " }\n" - "}\n"); + "private void clear$capitalized_name$() {\n" + " if ($has_oneof_case_message$) {\n" + " $clear_oneof_case_message$;\n" + " $oneof_name$_ = null;\n" + " }\n" + "}\n"); } +void ImmutablePrimitiveOneofFieldLiteGenerator::GenerateFieldInfo( + io::Printer* printer, std::vector* output) const { + WriteIntToUtf16CharSequence(descriptor_->number(), output); + WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_), + output); + WriteIntToUtf16CharSequence(descriptor_->containing_oneof()->index(), output); +} -void ImmutablePrimitiveOneofFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void ImmutablePrimitiveOneofFieldLiteGenerator::GenerateBuilderMembers( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return instance.has$capitalized_name$();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" + " return instance.get$capitalized_name$();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder " + "${$set$capitalized_name$$}$($type$ value) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$(value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " copyOnWrite();\n" + " instance.clear$capitalized_name$();\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } -void ImmutablePrimitiveOneofFieldLiteGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - // noop for primitives -} - -void ImmutablePrimitiveOneofFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$oneof_name$_ = visitor.visitOneof$visit_type$(\n" - " $has_oneof_case_message$, $oneof_name$_, other.$oneof_name$_);\n"); -} - -void ImmutablePrimitiveOneofFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "$set_oneof_case_message$;\n" - "$oneof_name$_ = input.read$capitalized_type$();\n"); -} - -void ImmutablePrimitiveOneofFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.write$capitalized_type$(\n" - " $number$, ($type$)(($boxed_type$) $oneof_name$_));\n" - "}\n"); -} - -void ImmutablePrimitiveOneofFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$capitalized_type$Size(\n" - " $number$, ($type$)(($boxed_type$) $oneof_name$_));\n" - "}\n"); -} - // =================================================================== RepeatedImmutablePrimitiveFieldLiteGenerator:: -RepeatedImmutablePrimitiveFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex, + RepeatedImmutablePrimitiveFieldLiteGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, + Context* context) + : descriptor_(descriptor), + context_(context), + name_resolver_(context->GetNameResolver()) { + SetPrimitiveVariables(descriptor, messageBitIndex, 0, context->GetFieldGeneratorInfo(descriptor), name_resolver_, &variables_); } RepeatedImmutablePrimitiveFieldLiteGenerator:: -~RepeatedImmutablePrimitiveFieldLiteGenerator() {} + ~RepeatedImmutablePrimitiveFieldLiteGenerator() {} int RepeatedImmutablePrimitiveFieldLiteGenerator::GetNumBitsForMessage() const { return 0; } -int RepeatedImmutablePrimitiveFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; +void RepeatedImmutablePrimitiveFieldLiteGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$java.util.List<$boxed_type$> " + "get$capitalized_name$List();\n"); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$int get$capitalized_name$Count();\n"); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$$type$ get$capitalized_name$(int index);\n"); } -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.util.List<$boxed_type$> get$capitalized_name$List();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$(int index);\n"); -} - - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private $field_list_type$ $name$_;\n"); +void RepeatedImmutablePrimitiveFieldLiteGenerator::GenerateMembers( + io::Printer* printer) const { + printer->Print(variables_, "private $field_list_type$ $name$_;\n"); PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List<$boxed_type$>\n" - " ${$get$capitalized_name$List$}$() {\n" - " return $name$_;\n" // note: unmodifiable list - "}\n"); + "@java.lang.Override\n" + "$deprecation$public java.util.List<$boxed_type$>\n" + " ${$get$capitalized_name$List$}$() {\n" + " return $name$_;\n" // note: unmodifiable list + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" + " return $name$_.size();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return $repeated_get$(index);\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" + " return $repeated_get$(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); - if (descriptor_->is_packed() && + if (!EnableExperimentalRuntimeForLite() && descriptor_->is_packed() && context_->HasGeneratedMethods(descriptor_->containing_type())) { printer->Print(variables_, - "private int $name$MemoizedSerializedSize = -1;\n"); - } - - printer->Print(variables_, - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - " }\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " int index, $type$ value) {\n" - "$null_check$" - " ensure$capitalized_name$IsMutable();\n" - " $repeated_set$(index, value);\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$($type$ value) {\n" - "$null_check$" - " ensure$capitalized_name$IsMutable();\n" - " $repeated_add$(value);\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void addAll$capitalized_name$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " com.google.protobuf.AbstractMessageLite.addAll(\n" - " values, $name$_);\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $name$_ = $empty_list$;\n" - "}\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List<$boxed_type$>\n" - " ${$get$capitalized_name$List$}$() {\n" - " return java.util.Collections.unmodifiableList(\n" - " instance.get$capitalized_name$List());\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return instance.get$capitalized_name$Count();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return instance.get$capitalized_name$(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, $type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(index, value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" - " java.lang.Iterable values) {\n" - " copyOnWrite();\n" - " instance.addAll$capitalized_name$(values);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for primitives -} - - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $empty_list$;\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { - // noop for primitives -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_= visitor.$visit_type_list$($name$_, other.$name$_);\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - // noop for primitives -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_.makeImmutable();\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - // TODO(dweis): Scan the input buffer to count, then initialize - // appropriately. - // TODO(dweis): Scan the input buffer to count and ensure capacity. - printer->Print(variables_, - "if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - "}\n" - "$repeated_add$(input.read$capitalized_type$());\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateParsingCodeFromPacked(io::Printer* printer) const { - printer->Print(variables_, - "int length = input.readRawVarint32();\n" - "int limit = input.pushLimit(length);\n" - "if (!$is_mutable$ && input.getBytesUntilLimit() > 0) {\n"); - - int fixed_size = FixedSize(GetType(descriptor_)); - if (fixed_size == -1) { - // TODO(dweis): Scan the input buffer to count, then initialize - // appropriately. - printer->Print(variables_, - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n"); - } else { - printer->Print(variables_, - " final int currentSize = $name$_.size();\n" - " $name$_ = $name$_.mutableCopyWithCapacity(\n" - " currentSize + (length/$fixed_size$));\n"); - } - - // TODO(dweis): Scan the input buffer to count and ensure capacity. - printer->Print(variables_, - "}\n" - "while (input.getBytesUntilLimit() > 0) {\n" - " $repeated_add$(input.read$capitalized_type$());\n" - "}\n" - "input.popLimit(limit);\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_mutable$) {\n" - " $make_name_unmodifiable$;\n" - "}\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - if (descriptor_->is_packed()) { - // We invoke getSerializedSize in writeTo for messages that have packed - // fields in ImmutableMessageGenerator::GenerateMessageSerializationMethods. - // That makes it safe to rely on the memoized size here. - printer->Print(variables_, - "if (get$capitalized_name$List().size() > 0) {\n" - " output.writeUInt32NoTag($tag$);\n" - " output.writeUInt32NoTag($name$MemoizedSerializedSize);\n" - "}\n" - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.write$capitalized_type$NoTag($repeated_get$(i));\n" - "}\n"); - } else { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.write$capitalized_type$($number$, $repeated_get$(i));\n" - "}\n"); - } -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "{\n" - " int dataSize = 0;\n"); - printer->Indent(); - - if (FixedSize(GetType(descriptor_)) == -1) { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " dataSize += com.google.protobuf.CodedOutputStream\n" - " .compute$capitalized_type$SizeNoTag($repeated_get$(i));\n" - "}\n"); - } else { - printer->Print(variables_, - "dataSize = $fixed_size$ * get$capitalized_name$List().size();\n"); + "private int $name$MemoizedSerializedSize = -1;\n"); } printer->Print( - "size += dataSize;\n"); - - if (descriptor_->is_packed()) { - printer->Print(variables_, - "if (!get$capitalized_name$List().isEmpty()) {\n" - " size += $tag_size$;\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeInt32SizeNoTag(dataSize);\n" + variables_, + "private void ensure$capitalized_name$IsMutable() {\n" + " if (!$is_mutable$) {\n" + " $name$_ =\n" + " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" + " }\n" "}\n"); - } else { - printer->Print(variables_, - "size += $tag_size$ * get$capitalized_name$List().size();\n"); - } - // cache the data size for packed fields. - if (descriptor_->is_packed()) { - printer->Print(variables_, - "$name$MemoizedSerializedSize = dataSize;\n"); - } - - printer->Outdent(); - printer->Print("}\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { + WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "result = result && get$capitalized_name$List()\n" - " .equals(other.get$capitalized_name$List());\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { + "private void set$capitalized_name$(\n" + " int index, $type$ value) {\n" + "$null_check$" + " ensure$capitalized_name$IsMutable();\n" + " $repeated_set$(index, value);\n" + "}\n"); + WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "if (get$capitalized_name$Count() > 0) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + get$capitalized_name$List().hashCode();\n" - "}\n"); + "private void add$capitalized_name$($type$ value) {\n" + "$null_check$" + " ensure$capitalized_name$IsMutable();\n" + " $repeated_add$(value);\n" + "}\n"); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "private void addAll$capitalized_name$(\n" + " java.lang.Iterable values) {\n" + " ensure$capitalized_name$IsMutable();\n" + " com.google.protobuf.AbstractMessageLite.addAll(\n" + " values, $name$_);\n" + "}\n"); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "private void clear$capitalized_name$() {\n" + " $name$_ = $empty_list$;\n" + "}\n"); } -string RepeatedImmutablePrimitiveFieldLiteGenerator::GetBoxedType() const { +void RepeatedImmutablePrimitiveFieldLiteGenerator::GenerateBuilderMembers( + io::Printer* printer) const { + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "@java.lang.Override\n" + "$deprecation$public java.util.List<$boxed_type$>\n" + " ${$get$capitalized_name$List$}$() {\n" + " return java.util.Collections.unmodifiableList(\n" + " instance.get$capitalized_name$List());\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" + " return instance.get$capitalized_name$Count();\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" + " return instance.get$capitalized_name$(index);\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " int index, $type$ value) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$(index, value);\n" + " return this;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$public Builder " + "${$add$capitalized_name$$}$($type$ value) {\n" + " copyOnWrite();\n" + " instance.add$capitalized_name$(value);\n" + " return this;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" + " java.lang.Iterable values) {\n" + " copyOnWrite();\n" + " instance.addAll$capitalized_name$(values);\n" + " return this;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " copyOnWrite();\n" + " instance.clear$capitalized_name$();\n" + " return this;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); +} + +void RepeatedImmutablePrimitiveFieldLiteGenerator::GenerateFieldInfo( + io::Printer* printer, std::vector* output) const { + WriteIntToUtf16CharSequence(descriptor_->number(), output); + WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_), + output); + printer->Print(variables_, "\"$name$_\",\n"); +} + +void RepeatedImmutablePrimitiveFieldLiteGenerator::GenerateInitializationCode( + io::Printer* printer) const { + printer->Print(variables_, "$name$_ = $empty_list$;\n"); +} + +std::string RepeatedImmutablePrimitiveFieldLiteGenerator::GetBoxedType() const { return BoxedPrimitiveTypeName(GetJavaType(descriptor_)); } diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_primitive_field_lite.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_primitive_field_lite.h index 93416f0b..5867cee7 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_primitive_field_lite.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_primitive_field_lite.h @@ -41,14 +41,16 @@ namespace google { namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } -} +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { @@ -57,38 +59,25 @@ class ImmutablePrimitiveFieldLiteGenerator : public ImmutableFieldLiteGenerator { public: explicit ImmutablePrimitiveFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + const FieldDescriptor* descriptor, int messageBitIndex, Context* context); ~ImmutablePrimitiveFieldLiteGenerator(); - // implements ImmutableFieldLiteGenerator ------------------------------------ + // implements ImmutableFieldLiteGenerator + // ------------------------------------ int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; void GenerateInterfaceMembers(io::Printer* printer) const; void GenerateMembers(io::Printer* printer) const; void GenerateBuilderMembers(io::Printer* printer) const; void GenerateInitializationCode(io::Printer* printer) const; - void GenerateBuilderClearCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; + void GenerateFieldInfo(io::Printer* printer, + std::vector* output) const; - - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; ClassNameResolver* name_resolver_; private: @@ -98,19 +87,16 @@ class ImmutablePrimitiveFieldLiteGenerator class ImmutablePrimitiveOneofFieldLiteGenerator : public ImmutablePrimitiveFieldLiteGenerator { public: - ImmutablePrimitiveOneofFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + ImmutablePrimitiveOneofFieldLiteGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, + Context* context); ~ImmutablePrimitiveOneofFieldLiteGenerator(); void GenerateMembers(io::Printer* printer) const; void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; + void GenerateFieldInfo(io::Printer* printer, + std::vector* output) const; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutablePrimitiveOneofFieldLiteGenerator); @@ -120,38 +106,23 @@ class RepeatedImmutablePrimitiveFieldLiteGenerator : public ImmutableFieldLiteGenerator { public: explicit RepeatedImmutablePrimitiveFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + const FieldDescriptor* descriptor, int messageBitIndex, Context* context); virtual ~RepeatedImmutablePrimitiveFieldLiteGenerator(); // implements ImmutableFieldLiteGenerator ------------------------------------ int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; void GenerateInterfaceMembers(io::Printer* printer) const; void GenerateMembers(io::Printer* printer) const; void GenerateBuilderMembers(io::Printer* printer) const; void GenerateInitializationCode(io::Printer* printer) const; - void GenerateBuilderClearCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingCodeFromPacked(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; + void GenerateFieldInfo(io::Printer* printer, + std::vector* output) const; - - string GetBoxedType() const; + std::string GetBoxedType() const; private: const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; + std::map variables_; Context* context_; ClassNameResolver* name_resolver_; @@ -161,6 +132,6 @@ class RepeatedImmutablePrimitiveFieldLiteGenerator } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_PRIMITIVE_FIELD_LITE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_service.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_service.cc index 988e1942..17d8e707 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_service.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_service.cc @@ -41,21 +41,23 @@ #include #include + namespace google { namespace protobuf { namespace compiler { namespace java { ServiceGenerator::ServiceGenerator(const ServiceDescriptor* descriptor) - : descriptor_(descriptor) {} + : descriptor_(descriptor) {} ServiceGenerator::~ServiceGenerator() {} // =================================================================== ImmutableServiceGenerator::ImmutableServiceGenerator( const ServiceDescriptor* descriptor, Context* context) - : ServiceGenerator(descriptor), context_(context), - name_resolver_(context->GetNameResolver()) {} + : ServiceGenerator(descriptor), + context_(context), + name_resolver_(context->GetNameResolver()) {} ImmutableServiceGenerator::~ImmutableServiceGenerator() {} @@ -65,15 +67,13 @@ void ImmutableServiceGenerator::Generate(io::Printer* printer) { MaybePrintGeneratedAnnotation(context_, printer, descriptor_, /* immutable = */ true); printer->Print( - "public $static$ abstract class $classname$\n" - " implements com.google.protobuf.Service {\n", - "static", is_own_file ? "" : "static", - "classname", descriptor_->name()); + "public $static$ abstract class $classname$\n" + " implements com.google.protobuf.Service {\n", + "static", is_own_file ? "" : "static", "classname", descriptor_->name()); printer->Indent(); - printer->Print( - "protected $classname$() {}\n\n", - "classname", descriptor_->name()); + printer->Print("protected $classname$() {}\n\n", "classname", + descriptor_->name()); GenerateInterface(printer); @@ -84,13 +84,13 @@ void ImmutableServiceGenerator::Generate(io::Printer* printer) { // Generate getDescriptor() and getDescriptorForType(). printer->Print( - "public static final\n" - " com.google.protobuf.Descriptors.ServiceDescriptor\n" - " getDescriptor() {\n" - " return $file$.getDescriptor().getServices().get($index$);\n" - "}\n", - "file", name_resolver_->GetImmutableClassName(descriptor_->file()), - "index", SimpleItoa(descriptor_->index())); + "public static final\n" + " com.google.protobuf.Descriptors.ServiceDescriptor\n" + " getDescriptor() {\n" + " return $file$.getDescriptor().getServices().get($index$);\n" + "}\n", + "file", name_resolver_->GetImmutableClassName(descriptor_->file()), + "index", StrCat(descriptor_->index())); GenerateGetDescriptorForType(printer); // Generate more stuff. @@ -102,9 +102,9 @@ void ImmutableServiceGenerator::Generate(io::Printer* printer) { // Add an insertion point. printer->Print( - "\n" - "// @@protoc_insertion_point(class_scope:$full_name$)\n", - "full_name", descriptor_->full_name()); + "\n" + "// @@protoc_insertion_point(class_scope:$full_name$)\n", + "full_name", descriptor_->full_name()); printer->Outdent(); printer->Print("}\n\n"); @@ -113,10 +113,10 @@ void ImmutableServiceGenerator::Generate(io::Printer* printer) { void ImmutableServiceGenerator::GenerateGetDescriptorForType( io::Printer* printer) { printer->Print( - "public final com.google.protobuf.Descriptors.ServiceDescriptor\n" - " getDescriptorForType() {\n" - " return getDescriptor();\n" - "}\n"); + "public final com.google.protobuf.Descriptors.ServiceDescriptor\n" + " getDescriptorForType() {\n" + " return getDescriptor();\n" + "}\n"); } void ImmutableServiceGenerator::GenerateInterface(io::Printer* printer) { @@ -130,10 +130,10 @@ void ImmutableServiceGenerator::GenerateInterface(io::Printer* printer) { void ImmutableServiceGenerator::GenerateNewReflectiveServiceMethod( io::Printer* printer) { printer->Print( - "public static com.google.protobuf.Service newReflectiveService(\n" - " final Interface impl) {\n" - " return new $classname$() {\n", - "classname", descriptor_->name()); + "public static com.google.protobuf.Service newReflectiveService(\n" + " final Interface impl) {\n" + " return new $classname$() {\n", + "classname", descriptor_->name()); printer->Indent(); printer->Indent(); @@ -142,10 +142,10 @@ void ImmutableServiceGenerator::GenerateNewReflectiveServiceMethod( printer->Print("@java.lang.Override\n"); GenerateMethodSignature(printer, method, IS_CONCRETE); printer->Print( - " {\n" - " impl.$method$(controller, request, done);\n" - "}\n\n", - "method", UnderscoresToCamelCase(method)); + " {\n" + " impl.$method$(controller, request, done);\n" + "}\n\n", + "method", UnderscoresToCamelCase(method)); } printer->Outdent(); @@ -157,9 +157,9 @@ void ImmutableServiceGenerator::GenerateNewReflectiveServiceMethod( void ImmutableServiceGenerator::GenerateNewReflectiveBlockingServiceMethod( io::Printer* printer) { printer->Print( - "public static com.google.protobuf.BlockingService\n" - " newReflectiveBlockingService(final BlockingInterface impl) {\n" - " return new com.google.protobuf.BlockingService() {\n"); + "public static com.google.protobuf.BlockingService\n" + " newReflectiveBlockingService(final BlockingInterface impl) {\n" + " return new com.google.protobuf.BlockingService() {\n"); printer->Indent(); printer->Indent(); @@ -184,167 +184,170 @@ void ImmutableServiceGenerator::GenerateAbstractMethods(io::Printer* printer) { } } -string ImmutableServiceGenerator::GetOutput(const MethodDescriptor* method) { +std::string ImmutableServiceGenerator::GetOutput( + const MethodDescriptor* method) { return name_resolver_->GetImmutableClassName(method->output_type()); } void ImmutableServiceGenerator::GenerateCallMethod(io::Printer* printer) { printer->Print( - "\n" - "public final void callMethod(\n" - " com.google.protobuf.Descriptors.MethodDescriptor method,\n" - " com.google.protobuf.RpcController controller,\n" - " com.google.protobuf.Message request,\n" - " com.google.protobuf.RpcCallback<\n" - " com.google.protobuf.Message> done) {\n" - " if (method.getService() != getDescriptor()) {\n" - " throw new java.lang.IllegalArgumentException(\n" - " \"Service.callMethod() given method descriptor for wrong \" +\n" - " \"service type.\");\n" - " }\n" - " switch(method.getIndex()) {\n"); + "\n" + "public final void callMethod(\n" + " com.google.protobuf.Descriptors.MethodDescriptor method,\n" + " com.google.protobuf.RpcController controller,\n" + " com.google.protobuf.Message request,\n" + " com.google.protobuf.RpcCallback<\n" + " com.google.protobuf.Message> done) {\n" + " if (method.getService() != getDescriptor()) {\n" + " throw new java.lang.IllegalArgumentException(\n" + " \"Service.callMethod() given method descriptor for wrong \" +\n" + " \"service type.\");\n" + " }\n" + " switch(method.getIndex()) {\n"); printer->Indent(); printer->Indent(); for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); - std::map vars; - vars["index"] = SimpleItoa(i); + std::map vars; + vars["index"] = StrCat(i); vars["method"] = UnderscoresToCamelCase(method); - vars["input"] = name_resolver_->GetImmutableClassName( - method->input_type()); + vars["input"] = name_resolver_->GetImmutableClassName(method->input_type()); vars["output"] = GetOutput(method); - printer->Print(vars, - "case $index$:\n" - " this.$method$(controller, ($input$)request,\n" - " com.google.protobuf.RpcUtil.<$output$>specializeCallback(\n" - " done));\n" - " return;\n"); + printer->Print( + vars, + "case $index$:\n" + " this.$method$(controller, ($input$)request,\n" + " com.google.protobuf.RpcUtil.<$output$>specializeCallback(\n" + " done));\n" + " return;\n"); } printer->Print( - "default:\n" - " throw new java.lang.AssertionError(\"Can't get here.\");\n"); + "default:\n" + " throw new java.lang.AssertionError(\"Can't get here.\");\n"); printer->Outdent(); printer->Outdent(); printer->Print( - " }\n" - "}\n" - "\n"); + " }\n" + "}\n" + "\n"); } void ImmutableServiceGenerator::GenerateCallBlockingMethod( io::Printer* printer) { printer->Print( - "\n" - "public final com.google.protobuf.Message callBlockingMethod(\n" - " com.google.protobuf.Descriptors.MethodDescriptor method,\n" - " com.google.protobuf.RpcController controller,\n" - " com.google.protobuf.Message request)\n" - " throws com.google.protobuf.ServiceException {\n" - " if (method.getService() != getDescriptor()) {\n" - " throw new java.lang.IllegalArgumentException(\n" - " \"Service.callBlockingMethod() given method descriptor for \" +\n" - " \"wrong service type.\");\n" - " }\n" - " switch(method.getIndex()) {\n"); + "\n" + "public final com.google.protobuf.Message callBlockingMethod(\n" + " com.google.protobuf.Descriptors.MethodDescriptor method,\n" + " com.google.protobuf.RpcController controller,\n" + " com.google.protobuf.Message request)\n" + " throws com.google.protobuf.ServiceException {\n" + " if (method.getService() != getDescriptor()) {\n" + " throw new java.lang.IllegalArgumentException(\n" + " \"Service.callBlockingMethod() given method descriptor for \" +\n" + " \"wrong service type.\");\n" + " }\n" + " switch(method.getIndex()) {\n"); printer->Indent(); printer->Indent(); for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); - std::map vars; - vars["index"] = SimpleItoa(i); + std::map vars; + vars["index"] = StrCat(i); vars["method"] = UnderscoresToCamelCase(method); - vars["input"] = name_resolver_->GetImmutableClassName( - method->input_type()); + vars["input"] = name_resolver_->GetImmutableClassName(method->input_type()); vars["output"] = GetOutput(method); printer->Print(vars, - "case $index$:\n" - " return impl.$method$(controller, ($input$)request);\n"); + "case $index$:\n" + " return impl.$method$(controller, ($input$)request);\n"); } printer->Print( - "default:\n" - " throw new java.lang.AssertionError(\"Can't get here.\");\n"); + "default:\n" + " throw new java.lang.AssertionError(\"Can't get here.\");\n"); printer->Outdent(); printer->Outdent(); printer->Print( - " }\n" - "}\n" - "\n"); + " }\n" + "}\n" + "\n"); } void ImmutableServiceGenerator::GenerateGetPrototype(RequestOrResponse which, - io::Printer* printer) { + io::Printer* printer) { /* * TODO(cpovirk): The exception message says "Service.foo" when it may be * "BlockingService.foo." Consider fixing. */ printer->Print( - "public final com.google.protobuf.Message\n" - " get$request_or_response$Prototype(\n" - " com.google.protobuf.Descriptors.MethodDescriptor method) {\n" - " if (method.getService() != getDescriptor()) {\n" - " throw new java.lang.IllegalArgumentException(\n" - " \"Service.get$request_or_response$Prototype() given method \" +\n" - " \"descriptor for wrong service type.\");\n" - " }\n" - " switch(method.getIndex()) {\n", - "request_or_response", (which == REQUEST) ? "Request" : "Response"); + "public final com.google.protobuf.Message\n" + " get$request_or_response$Prototype(\n" + " com.google.protobuf.Descriptors.MethodDescriptor method) {\n" + " if (method.getService() != getDescriptor()) {\n" + " throw new java.lang.IllegalArgumentException(\n" + " \"Service.get$request_or_response$Prototype() given method \" +\n" + " \"descriptor for wrong service type.\");\n" + " }\n" + " switch(method.getIndex()) {\n", + "request_or_response", (which == REQUEST) ? "Request" : "Response"); printer->Indent(); printer->Indent(); for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); - std::map vars; - vars["index"] = SimpleItoa(i); - vars["type"] = name_resolver_->GetImmutableClassName( - (which == REQUEST) ? method->input_type() : method->output_type()); + std::map vars; + vars["index"] = StrCat(i); + vars["type"] = + (which == REQUEST) + ? name_resolver_->GetImmutableClassName(method->input_type()) + : GetOutput(method); printer->Print(vars, - "case $index$:\n" - " return $type$.getDefaultInstance();\n"); + "case $index$:\n" + " return $type$.getDefaultInstance();\n"); } printer->Print( - "default:\n" - " throw new java.lang.AssertionError(\"Can't get here.\");\n"); + "default:\n" + " throw new java.lang.AssertionError(\"Can't get here.\");\n"); printer->Outdent(); printer->Outdent(); printer->Print( - " }\n" - "}\n" - "\n"); + " }\n" + "}\n" + "\n"); } void ImmutableServiceGenerator::GenerateStub(io::Printer* printer) { printer->Print( - "public static Stub newStub(\n" - " com.google.protobuf.RpcChannel channel) {\n" - " return new Stub(channel);\n" - "}\n" - "\n" - "public static final class Stub extends $classname$ implements Interface {" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + "public static Stub newStub(\n" + " com.google.protobuf.RpcChannel channel) {\n" + " return new Stub(channel);\n" + "}\n" + "\n" + "public static final class Stub extends $classname$ implements Interface " + "{" + "\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); printer->Indent(); printer->Print( - "private Stub(com.google.protobuf.RpcChannel channel) {\n" - " this.channel = channel;\n" - "}\n" - "\n" - "private final com.google.protobuf.RpcChannel channel;\n" - "\n" - "public com.google.protobuf.RpcChannel getChannel() {\n" - " return channel;\n" - "}\n"); + "private Stub(com.google.protobuf.RpcChannel channel) {\n" + " this.channel = channel;\n" + "}\n" + "\n" + "private final com.google.protobuf.RpcChannel channel;\n" + "\n" + "public com.google.protobuf.RpcChannel getChannel() {\n" + " return channel;\n" + "}\n"); for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); @@ -353,19 +356,19 @@ void ImmutableServiceGenerator::GenerateStub(io::Printer* printer) { printer->Print(" {\n"); printer->Indent(); - std::map vars; - vars["index"] = SimpleItoa(i); + std::map vars; + vars["index"] = StrCat(i); vars["output"] = GetOutput(method); printer->Print(vars, - "channel.callMethod(\n" - " getDescriptor().getMethods().get($index$),\n" - " controller,\n" - " request,\n" - " $output$.getDefaultInstance(),\n" - " com.google.protobuf.RpcUtil.generalizeCallback(\n" - " done,\n" - " $output$.class,\n" - " $output$.getDefaultInstance()));\n"); + "channel.callMethod(\n" + " getDescriptor().getMethods().get($index$),\n" + " controller,\n" + " request,\n" + " $output$.getDefaultInstance(),\n" + " com.google.protobuf.RpcUtil.generalizeCallback(\n" + " done,\n" + " $output$.class,\n" + " $output$.getDefaultInstance()));\n"); printer->Outdent(); printer->Print("}\n"); @@ -373,20 +376,19 @@ void ImmutableServiceGenerator::GenerateStub(io::Printer* printer) { printer->Outdent(); printer->Print( - "}\n" - "\n"); + "}\n" + "\n"); } void ImmutableServiceGenerator::GenerateBlockingStub(io::Printer* printer) { printer->Print( - "public static BlockingInterface newBlockingStub(\n" - " com.google.protobuf.BlockingRpcChannel channel) {\n" - " return new BlockingStub(channel);\n" - "}\n" - "\n"); + "public static BlockingInterface newBlockingStub(\n" + " com.google.protobuf.BlockingRpcChannel channel) {\n" + " return new BlockingStub(channel);\n" + "}\n" + "\n"); - printer->Print( - "public interface BlockingInterface {"); + printer->Print("public interface BlockingInterface {"); printer->Indent(); for (int i = 0; i < descriptor_->method_count(); i++) { @@ -397,19 +399,20 @@ void ImmutableServiceGenerator::GenerateBlockingStub(io::Printer* printer) { printer->Outdent(); printer->Print( - "}\n" - "\n"); + "}\n" + "\n"); printer->Print( - "private static final class BlockingStub implements BlockingInterface {\n"); + "private static final class BlockingStub implements BlockingInterface " + "{\n"); printer->Indent(); printer->Print( - "private BlockingStub(com.google.protobuf.BlockingRpcChannel channel) {\n" - " this.channel = channel;\n" - "}\n" - "\n" - "private final com.google.protobuf.BlockingRpcChannel channel;\n"); + "private BlockingStub(com.google.protobuf.BlockingRpcChannel channel) {\n" + " this.channel = channel;\n" + "}\n" + "\n" + "private final com.google.protobuf.BlockingRpcChannel channel;\n"); for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); @@ -417,54 +420,53 @@ void ImmutableServiceGenerator::GenerateBlockingStub(io::Printer* printer) { printer->Print(" {\n"); printer->Indent(); - std::map vars; - vars["index"] = SimpleItoa(i); + std::map vars; + vars["index"] = StrCat(i); vars["output"] = GetOutput(method); printer->Print(vars, - "return ($output$) channel.callBlockingMethod(\n" - " getDescriptor().getMethods().get($index$),\n" - " controller,\n" - " request,\n" - " $output$.getDefaultInstance());\n"); + "return ($output$) channel.callBlockingMethod(\n" + " getDescriptor().getMethods().get($index$),\n" + " controller,\n" + " request,\n" + " $output$.getDefaultInstance());\n"); printer->Outdent(); printer->Print( - "}\n" - "\n"); + "}\n" + "\n"); } printer->Outdent(); printer->Print("}\n"); } -void ImmutableServiceGenerator::GenerateMethodSignature(io::Printer* printer, - const MethodDescriptor* method, - IsAbstract is_abstract) { - std::map vars; +void ImmutableServiceGenerator::GenerateMethodSignature( + io::Printer* printer, const MethodDescriptor* method, + IsAbstract is_abstract) { + std::map vars; vars["name"] = UnderscoresToCamelCase(method); vars["input"] = name_resolver_->GetImmutableClassName(method->input_type()); vars["output"] = GetOutput(method); vars["abstract"] = (is_abstract == IS_ABSTRACT) ? "abstract" : ""; printer->Print(vars, - "public $abstract$ void $name$(\n" - " com.google.protobuf.RpcController controller,\n" - " $input$ request,\n" - " com.google.protobuf.RpcCallback<$output$> done)"); + "public $abstract$ void $name$(\n" + " com.google.protobuf.RpcController controller,\n" + " $input$ request,\n" + " com.google.protobuf.RpcCallback<$output$> done)"); } void ImmutableServiceGenerator::GenerateBlockingMethodSignature( - io::Printer* printer, - const MethodDescriptor* method) { - std::map vars; + io::Printer* printer, const MethodDescriptor* method) { + std::map vars; vars["method"] = UnderscoresToCamelCase(method); vars["input"] = name_resolver_->GetImmutableClassName(method->input_type()); vars["output"] = GetOutput(method); printer->Print(vars, - "\n" - "public $output$ $method$(\n" - " com.google.protobuf.RpcController controller,\n" - " $input$ request)\n" - " throws com.google.protobuf.ServiceException"); + "\n" + "public $output$ $method$(\n" + " com.google.protobuf.RpcController controller,\n" + " $input$ request)\n" + " throws com.google.protobuf.ServiceException"); } } // namespace java diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_service.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_service.h index 12b3f942..1c82c16c 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_service.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_service.h @@ -40,17 +40,19 @@ namespace google { namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +namespace io { +class Printer; // printer.h } +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { @@ -81,7 +83,6 @@ class ImmutableServiceGenerator : public ServiceGenerator { virtual void Generate(io::Printer* printer); private: - // Generate the getDescriptorForType() method. void GenerateGetDescriptorForType(io::Printer* printer); @@ -123,7 +124,7 @@ class ImmutableServiceGenerator : public ServiceGenerator { const MethodDescriptor* method); // Return the output type of the method. - string GetOutput(const MethodDescriptor* method); + std::string GetOutput(const MethodDescriptor* method); Context* context_; ClassNameResolver* name_resolver_; @@ -133,6 +134,6 @@ class ImmutableServiceGenerator : public ServiceGenerator { } // namespace java } // namespace compiler } // namespace protobuf +} // namespace google #endif // NET_PROTO2_COMPILER_JAVA_SERVICE_H__ -} // namespace google diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_shared_code_generator.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_shared_code_generator.cc index 0cec20b9..f673e683 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_shared_code_generator.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_shared_code_generator.cc @@ -52,19 +52,18 @@ SharedCodeGenerator::SharedCodeGenerator(const FileDescriptor* file, const Options& options) : name_resolver_(new ClassNameResolver), file_(file), options_(options) {} -SharedCodeGenerator::~SharedCodeGenerator() { -} +SharedCodeGenerator::~SharedCodeGenerator() {} -void SharedCodeGenerator::Generate(GeneratorContext* context, - std::vector* file_list, - std::vector* annotation_file_list) { - string java_package = FileJavaPackage(file_); - string package_dir = JavaPackageToDir(java_package); +void SharedCodeGenerator::Generate( + GeneratorContext* context, std::vector* file_list, + std::vector* annotation_file_list) { + std::string java_package = FileJavaPackage(file_); + std::string package_dir = JavaPackageToDir(java_package); if (HasDescriptorMethods(file_, options_.enforce_lite)) { // Generate descriptors. - string classname = name_resolver_->GetDescriptorClassName(file_); - string filename = package_dir + classname + ".java"; + std::string classname = name_resolver_->GetDescriptorClassName(file_); + std::string filename = package_dir + classname + ".java"; file_list->push_back(filename); std::unique_ptr output(context->Open(filename)); GeneratedCodeInfo annotations; @@ -73,8 +72,8 @@ void SharedCodeGenerator::Generate(GeneratorContext* context, std::unique_ptr printer( new io::Printer(output.get(), '$', options_.annotate_code ? &annotation_collector : NULL)); - string info_relative_path = classname + ".java.pb.meta"; - string info_full_path = filename + ".pb.meta"; + std::string info_relative_path = classname + ".java.pb.meta"; + std::string info_full_path = filename + ".pb.meta"; printer->Print( "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" "// source: $filename$\n" @@ -82,9 +81,9 @@ void SharedCodeGenerator::Generate(GeneratorContext* context, "filename", file_->name()); if (!java_package.empty()) { printer->Print( - "package $package$;\n" - "\n", - "package", java_package); + "package $package$;\n" + "\n", + "package", java_package); } PrintGeneratedAnnotation(printer.get(), '$', options_.annotate_code ? info_relative_path : ""); @@ -101,8 +100,8 @@ void SharedCodeGenerator::Generate(GeneratorContext* context, printer->Outdent(); printer->Outdent(); printer->Print( - " }\n" - "}\n"); + " }\n" + "}\n"); if (options_.annotate_code) { std::unique_ptr info_output( @@ -130,11 +129,10 @@ void SharedCodeGenerator::GenerateDescriptors(io::Printer* printer) { FileDescriptorProto file_proto; file_->CopyTo(&file_proto); - string file_data; + std::string file_data; file_proto.SerializeToString(&file_data); - printer->Print( - "java.lang.String[] descriptorData = {\n"); + printer->Print("java.lang.String[] descriptorData = {\n"); printer->Indent(); // Limit the number of bytes per line. @@ -152,40 +150,22 @@ void SharedCodeGenerator::GenerateDescriptors(io::Printer* printer) { printer->Print(" +\n"); } } - printer->Print("\"$data$\"", - "data", CEscape(file_data.substr(i, kBytesPerLine))); + printer->Print("\"$data$\"", "data", + CEscape(file_data.substr(i, kBytesPerLine))); } printer->Outdent(); printer->Print("\n};\n"); - // ----------------------------------------------------------------- - // Create the InternalDescriptorAssigner. - - printer->Print( - "com.google.protobuf.Descriptors.FileDescriptor." - "InternalDescriptorAssigner assigner =\n" - " new com.google.protobuf.Descriptors.FileDescriptor." - " InternalDescriptorAssigner() {\n" - " public com.google.protobuf.ExtensionRegistry assignDescriptors(\n" - " com.google.protobuf.Descriptors.FileDescriptor root) {\n" - " descriptor = root;\n" - // Custom options will be handled when immutable messages' outer class is - // loaded. Here we just return null and let custom options be unknown - // fields. - " return null;\n" - " }\n" - " };\n"); - // ----------------------------------------------------------------- // Find out all dependencies. - std::vector > dependencies; + std::vector > dependencies; for (int i = 0; i < file_->dependency_count(); i++) { - string filename = file_->dependency(i)->name(); - string package = FileJavaPackage(file_->dependency(i)); - string classname = name_resolver_->GetDescriptorClassName( - file_->dependency(i)); - string full_name; + std::string filename = file_->dependency(i)->name(); + std::string package = FileJavaPackage(file_->dependency(i)); + std::string classname = + name_resolver_->GetDescriptorClassName(file_->dependency(i)); + std::string full_name; if (package.empty()) { full_name = classname; } else { @@ -197,20 +177,18 @@ void SharedCodeGenerator::GenerateDescriptors(io::Printer* printer) { // ----------------------------------------------------------------- // Invoke internalBuildGeneratedFileFrom() to build the file. printer->Print( - "com.google.protobuf.Descriptors.FileDescriptor\n" - " .internalBuildGeneratedFileFrom(descriptorData,\n"); + "descriptor = com.google.protobuf.Descriptors.FileDescriptor\n" + " .internalBuildGeneratedFileFrom(descriptorData,\n"); printer->Print( - " new com.google.protobuf.Descriptors.FileDescriptor[] {\n"); + " new com.google.protobuf.Descriptors.FileDescriptor[] {\n"); for (int i = 0; i < dependencies.size(); i++) { - const string& dependency = dependencies[i].second; - printer->Print( - " $dependency$.getDescriptor(),\n", - "dependency", dependency); + const std::string& dependency = dependencies[i].second; + printer->Print(" $dependency$.getDescriptor(),\n", "dependency", + dependency); } - printer->Print( - " }, assigner);\n"); + printer->Print(" });\n"); } } // namespace java diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_shared_code_generator.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_shared_code_generator.h index 58a31f5d..7c79abe2 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_shared_code_generator.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_shared_code_generator.h @@ -44,18 +44,20 @@ namespace google { namespace protobuf { - class FileDescriptor; // descriptor.h - namespace compiler { - class GeneratorContext; // code_generator.h - namespace java { - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } +class FileDescriptor; // descriptor.h +namespace compiler { +class GeneratorContext; // code_generator.h +namespace java { +class ClassNameResolver; // name_resolver.h } +} // namespace compiler +namespace io { +class Printer; // printer.h +} +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { @@ -68,8 +70,8 @@ class SharedCodeGenerator { ~SharedCodeGenerator(); void Generate(GeneratorContext* generator_context, - std::vector* file_list, - std::vector* annotation_file_list); + std::vector* file_list, + std::vector* annotation_file_list); void GenerateDescriptors(io::Printer* printer); @@ -80,10 +82,9 @@ class SharedCodeGenerator { GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SharedCodeGenerator); }; - } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_SHARED_CODE_GENERATOR_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_string_field.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_string_field.cc index 2b6e9381..6ebc3e27 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_string_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_string_field.cc @@ -47,6 +47,7 @@ #include #include + namespace google { namespace protobuf { namespace compiler { @@ -58,11 +59,10 @@ using internal::WireFormatLite; namespace { void SetPrimitiveVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, + int messageBitIndex, int builderBitIndex, const FieldGeneratorInfo* info, ClassNameResolver* name_resolver, - std::map* variables) { + std::map* variables) { SetCommonFieldVariables(descriptor, info, variables); (*variables)["empty_list"] = "com.google.protobuf.LazyStringArrayList.EMPTY"; @@ -72,24 +72,23 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor, "= " + ImmutableDefaultValue(descriptor, name_resolver); (*variables)["capitalized_type"] = "String"; (*variables)["tag"] = - SimpleItoa(static_cast(WireFormat::MakeTag(descriptor))); - (*variables)["tag_size"] = SimpleItoa( + StrCat(static_cast(WireFormat::MakeTag(descriptor))); + (*variables)["tag_size"] = StrCat( WireFormat::TagSize(descriptor->number(), GetType(descriptor))); (*variables)["null_check"] = " if (value == null) {\n" " throw new NullPointerException();\n" " }\n"; - (*variables)["writeString"] = - "com.google.protobuf.GeneratedMessage" + GeneratedCodeVersionSuffix() + - ".writeString"; - (*variables)["computeStringSize"] = - "com.google.protobuf.GeneratedMessage" + GeneratedCodeVersionSuffix() + - ".computeStringSize"; + (*variables)["writeString"] = "com.google.protobuf.GeneratedMessage" + + GeneratedCodeVersionSuffix() + ".writeString"; + (*variables)["computeStringSize"] = "com.google.protobuf.GeneratedMessage" + + GeneratedCodeVersionSuffix() + + ".computeStringSize"; // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; + (*variables)["deprecation"] = + descriptor->options().deprecated() ? "@java.lang.Deprecated " : ""; (*variables)["on_changed"] = "onChanged();"; if (SupportFieldPresence(descriptor->file())) { @@ -137,14 +136,10 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor, // =================================================================== -ImmutableStringFieldGenerator:: -ImmutableStringFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { +ImmutableStringFieldGenerator::ImmutableStringFieldGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, + Context* context) + : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) { SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex, context->GetFieldGeneratorInfo(descriptor), name_resolver_, &variables_); @@ -153,11 +148,11 @@ ImmutableStringFieldGenerator(const FieldDescriptor* descriptor, ImmutableStringFieldGenerator::~ImmutableStringFieldGenerator() {} int ImmutableStringFieldGenerator::GetNumBitsForMessage() const { - return 1; + return SupportFieldPresence(descriptor_->file()) ? 1 : 0; } int ImmutableStringFieldGenerator::GetNumBitsForBuilder() const { - return 1; + return GetNumBitsForMessage(); } // A note about how strings are handled. This code used to just store a String @@ -192,534 +187,531 @@ int ImmutableStringFieldGenerator::GetNumBitsForBuilder() const { // For single fields, the logic for this is done inside the generated code. For // repeated fields, the logic is done in LazyStringArrayList and // UnmodifiableLazyStringList. -void ImmutableStringFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { +void ImmutableStringFieldGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); + "$deprecation$boolean has$capitalized_name$();\n"); } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$java.lang.String get$capitalized_name$();\n"); + "$deprecation$java.lang.String get$capitalized_name$();\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$com.google.protobuf.ByteString\n" - " get$capitalized_name$Bytes();\n"); + "$deprecation$com.google.protobuf.ByteString\n" + " get$capitalized_name$Bytes();\n"); } -void ImmutableStringFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private volatile java.lang.Object $name$_;\n"); +void ImmutableStringFieldGenerator::GenerateMembers( + io::Printer* printer) const { + printer->Print(variables_, "private volatile java.lang.Object $name$_;\n"); PrintExtraFieldInfo(variables_, printer); if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $get_has_field_bit_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" - " java.lang.Object ref = $name$_;\n" - " if (ref instanceof java.lang.String) {\n" - " return (java.lang.String) ref;\n" - " } else {\n" - " com.google.protobuf.ByteString bs = \n" - " (com.google.protobuf.ByteString) ref;\n" + printer->Print( + variables_, + "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" + " java.lang.Object ref = $name$_;\n" + " if (ref instanceof java.lang.String) {\n" + " return (java.lang.String) ref;\n" + " } else {\n" + " com.google.protobuf.ByteString bs = \n" + " (com.google.protobuf.ByteString) ref;\n" " java.lang.String s = bs.toStringUtf8();\n"); printer->Annotate("{", "}", descriptor_); if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " $name$_ = s;\n"); + printer->Print(variables_, " $name$_ = s;\n"); } else { printer->Print(variables_, - " if (bs.isValidUtf8()) {\n" - " $name$_ = s;\n" - " }\n"); + " if (bs.isValidUtf8()) {\n" + " $name$_ = s;\n" + " }\n"); } printer->Print(variables_, - " return s;\n" - " }\n" - "}\n"); + " return s;\n" + " }\n" + "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$() {\n" - " java.lang.Object ref = $name$_;\n" - " if (ref instanceof java.lang.String) {\n" - " com.google.protobuf.ByteString b = \n" - " com.google.protobuf.ByteString.copyFromUtf8(\n" - " (java.lang.String) ref);\n" - " $name$_ = b;\n" - " return b;\n" - " } else {\n" - " return (com.google.protobuf.ByteString) ref;\n" - " }\n" - "}\n"); + "$deprecation$public com.google.protobuf.ByteString\n" + " ${$get$capitalized_name$Bytes$}$() {\n" + " java.lang.Object ref = $name$_;\n" + " if (ref instanceof java.lang.String) {\n" + " com.google.protobuf.ByteString b = \n" + " com.google.protobuf.ByteString.copyFromUtf8(\n" + " (java.lang.String) ref);\n" + " $name$_ = b;\n" + " return b;\n" + " } else {\n" + " return (com.google.protobuf.ByteString) ref;\n" + " }\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } -void ImmutableStringFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void ImmutableStringFieldGenerator::GenerateBuilderMembers( + io::Printer* printer) const { printer->Print(variables_, - "private java.lang.Object $name$_ $default_init$;\n"); + "private java.lang.Object $name$_ $default_init$;\n"); if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_builder$;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $get_has_field_bit_builder$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" - " java.lang.Object ref = $name$_;\n" - " if (!(ref instanceof java.lang.String)) {\n" - " com.google.protobuf.ByteString bs =\n" - " (com.google.protobuf.ByteString) ref;\n" - " java.lang.String s = bs.toStringUtf8();\n"); + printer->Print( + variables_, + "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" + " java.lang.Object ref = $name$_;\n" + " if (!(ref instanceof java.lang.String)) {\n" + " com.google.protobuf.ByteString bs =\n" + " (com.google.protobuf.ByteString) ref;\n" + " java.lang.String s = bs.toStringUtf8();\n"); printer->Annotate("{", "}", descriptor_); if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " $name$_ = s;\n"); + printer->Print(variables_, " $name$_ = s;\n"); } else { printer->Print(variables_, - " if (bs.isValidUtf8()) {\n" - " $name$_ = s;\n" - " }\n"); + " if (bs.isValidUtf8()) {\n" + " $name$_ = s;\n" + " }\n"); } printer->Print(variables_, - " return s;\n" - " } else {\n" - " return (java.lang.String) ref;\n" - " }\n" - "}\n"); + " return s;\n" + " } else {\n" + " return (java.lang.String) ref;\n" + " }\n" + "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$() {\n" - " java.lang.Object ref = $name$_;\n" - " if (ref instanceof String) {\n" - " com.google.protobuf.ByteString b = \n" - " com.google.protobuf.ByteString.copyFromUtf8(\n" - " (java.lang.String) ref);\n" - " $name$_ = b;\n" - " return b;\n" - " } else {\n" - " return (com.google.protobuf.ByteString) ref;\n" - " }\n" - "}\n"); + "$deprecation$public com.google.protobuf.ByteString\n" + " ${$get$capitalized_name$Bytes$}$() {\n" + " java.lang.Object ref = $name$_;\n" + " if (ref instanceof String) {\n" + " com.google.protobuf.ByteString b = \n" + " com.google.protobuf.ByteString.copyFromUtf8(\n" + " (java.lang.String) ref);\n" + " $name$_ = b;\n" + " return b;\n" + " } else {\n" + " return (com.google.protobuf.ByteString) ref;\n" + " }\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " java.lang.String value) {\n" - "$null_check$" - " $set_has_field_bit_builder$\n" - " $name$_ = value;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " java.lang.String value) {\n" + "$null_check$" + " $set_has_field_bit_builder$\n" + " $name$_ = value;\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " $clear_has_field_bit_builder$\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " $clear_has_field_bit_builder$\n"); printer->Annotate("{", "}", descriptor_); // The default value is not a simple literal so we want to avoid executing // it multiple times. Instead, get the default out of the default instance. printer->Print(variables_, - " $name$_ = getDefaultInstance().get$capitalized_name$();\n"); + " $name$_ = getDefaultInstance().get$capitalized_name$();\n"); printer->Print(variables_, - " $on_changed$\n" - " return this;\n" - "}\n"); + " $on_changed$\n" + " return this;\n" + "}\n"); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n" - " com.google.protobuf.ByteString value) {\n" - "$null_check$"); + printer->Print( + variables_, + "$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n" + " com.google.protobuf.ByteString value) {\n" + "$null_check$"); printer->Annotate("{", "}", descriptor_); if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " checkByteStringIsUtf8(value);\n"); + printer->Print(variables_, " checkByteStringIsUtf8(value);\n"); } printer->Print(variables_, - " $set_has_field_bit_builder$\n" - " $name$_ = value;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); + " $set_has_field_bit_builder$\n" + " $name$_ = value;\n" + " $on_changed$\n" + " return this;\n" + "}\n"); } -void ImmutableStringFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { +void ImmutableStringFieldGenerator::GenerateFieldBuilderInitializationCode( + io::Printer* printer) const { // noop for primitives } -void ImmutableStringFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { +void ImmutableStringFieldGenerator::GenerateInitializationCode( + io::Printer* printer) const { printer->Print(variables_, "$name$_ = $default$;\n"); } -void ImmutableStringFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { +void ImmutableStringFieldGenerator::GenerateBuilderClearCode( + io::Printer* printer) const { printer->Print(variables_, - "$name$_ = $default$;\n" - "$clear_has_field_bit_builder$\n"); + "$name$_ = $default$;\n" + "$clear_has_field_bit_builder$\n"); } -void ImmutableStringFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { +void ImmutableStringFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { // Allow a slight breach of abstraction here in order to avoid forcing // all string fields to Strings when copying fields from a Message. printer->Print(variables_, - "if (other.has$capitalized_name$()) {\n" - " $set_has_field_bit_builder$\n" - " $name$_ = other.$name$_;\n" - " $on_changed$\n" - "}\n"); + "if (other.has$capitalized_name$()) {\n" + " $set_has_field_bit_builder$\n" + " $name$_ = other.$name$_;\n" + " $on_changed$\n" + "}\n"); } else { printer->Print(variables_, - "if (!other.get$capitalized_name$().isEmpty()) {\n" - " $name$_ = other.$name$_;\n" - " $on_changed$\n" - "}\n"); + "if (!other.get$capitalized_name$().isEmpty()) {\n" + " $name$_ = other.$name$_;\n" + " $on_changed$\n" + "}\n"); } } -void ImmutableStringFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { +void ImmutableStringFieldGenerator::GenerateBuildingCode( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { printer->Print(variables_, - "if ($get_has_field_bit_from_local$) {\n" - " $set_has_field_bit_to_local$;\n" - "}\n"); + "if ($get_has_field_bit_from_local$) {\n" + " $set_has_field_bit_to_local$;\n" + "}\n"); } - printer->Print(variables_, - "result.$name$_ = $name$_;\n"); + printer->Print(variables_, "result.$name$_ = $name$_;\n"); } -void ImmutableStringFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { +void ImmutableStringFieldGenerator::GenerateParsingCode( + io::Printer* printer) const { if (CheckUtf8(descriptor_)) { printer->Print(variables_, - "java.lang.String s = input.readStringRequireUtf8();\n" - "$set_has_field_bit_message$\n" - "$name$_ = s;\n"); + "java.lang.String s = input.readStringRequireUtf8();\n" + "$set_has_field_bit_message$\n" + "$name$_ = s;\n"); } else { printer->Print(variables_, - "com.google.protobuf.ByteString bs = input.readBytes();\n" - "$set_has_field_bit_message$\n" - "$name$_ = bs;\n"); + "com.google.protobuf.ByteString bs = input.readBytes();\n" + "$set_has_field_bit_message$\n" + "$name$_ = bs;\n"); } } -void ImmutableStringFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { +void ImmutableStringFieldGenerator::GenerateParsingDoneCode( + io::Printer* printer) const { // noop for strings. } -void ImmutableStringFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { +void ImmutableStringFieldGenerator::GenerateSerializationCode( + io::Printer* printer) const { printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " $writeString$(output, $number$, $name$_);\n" - "}\n"); + "if ($is_field_present_message$) {\n" + " $writeString$(output, $number$, $name$_);\n" + "}\n"); } -void ImmutableStringFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { +void ImmutableStringFieldGenerator::GenerateSerializedSizeCode( + io::Printer* printer) const { printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " size += $computeStringSize$($number$, $name$_);\n" - "}\n"); + "if ($is_field_present_message$) {\n" + " size += $computeStringSize$($number$, $name$_);\n" + "}\n"); } -void ImmutableStringFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { +void ImmutableStringFieldGenerator::GenerateEqualsCode( + io::Printer* printer) const { printer->Print(variables_, - "result = result && get$capitalized_name$()\n" - " .equals(other.get$capitalized_name$());\n"); + "if (!get$capitalized_name$()\n" + " .equals(other.get$capitalized_name$())) return false;\n"); } -void ImmutableStringFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { +void ImmutableStringFieldGenerator::GenerateHashCode( + io::Printer* printer) const { + printer->Print(variables_, "hash = (37 * hash) + $constant_name$;\n"); printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n"); - printer->Print(variables_, - "hash = (53 * hash) + get$capitalized_name$().hashCode();\n"); + "hash = (53 * hash) + get$capitalized_name$().hashCode();\n"); } -string ImmutableStringFieldGenerator::GetBoxedType() const { +std::string ImmutableStringFieldGenerator::GetBoxedType() const { return "java.lang.String"; } // =================================================================== -ImmutableStringOneofFieldGenerator:: -ImmutableStringOneofFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableStringFieldGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { +ImmutableStringOneofFieldGenerator::ImmutableStringOneofFieldGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, + Context* context) + : ImmutableStringFieldGenerator(descriptor, messageBitIndex, + builderBitIndex, context) { const OneofGeneratorInfo* info = context->GetOneofGeneratorInfo(descriptor->containing_oneof()); SetCommonOneofVariables(descriptor, info, &variables_); } -ImmutableStringOneofFieldGenerator:: -~ImmutableStringOneofFieldGenerator() {} +ImmutableStringOneofFieldGenerator::~ImmutableStringOneofFieldGenerator() {} -void ImmutableStringOneofFieldGenerator:: -GenerateMembers(io::Printer* printer) const { +void ImmutableStringOneofFieldGenerator::GenerateMembers( + io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" - " java.lang.Object ref $default_init$;\n" - " if ($has_oneof_case_message$) {\n" - " ref = $oneof_name$_;\n" - " }\n" - " if (ref instanceof java.lang.String) {\n" - " return (java.lang.String) ref;\n" - " } else {\n" - " com.google.protobuf.ByteString bs = \n" - " (com.google.protobuf.ByteString) ref;\n" - " java.lang.String s = bs.toStringUtf8();\n"); - printer->Annotate("{", "}", descriptor_); - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " if ($has_oneof_case_message$) {\n" - " $oneof_name$_ = s;\n" - " }\n"); - } else { - printer->Print(variables_, - " if (bs.isValidUtf8() && ($has_oneof_case_message$)) {\n" - " $oneof_name$_ = s;\n" - " }\n"); - } - printer->Print(variables_, - " return s;\n" - " }\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - - printer->Print(variables_, - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$() {\n" - " java.lang.Object ref $default_init$;\n" - " if ($has_oneof_case_message$) {\n" - " ref = $oneof_name$_;\n" - " }\n" - " if (ref instanceof java.lang.String) {\n" - " com.google.protobuf.ByteString b = \n" - " com.google.protobuf.ByteString.copyFromUtf8(\n" - " (java.lang.String) ref);\n" - " if ($has_oneof_case_message$) {\n" - " $oneof_name$_ = b;\n" - " }\n" - " return b;\n" - " } else {\n" - " return (com.google.protobuf.ByteString) ref;\n" - " }\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutableStringOneofFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $has_oneof_case_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" - " java.lang.Object ref $default_init$;\n" - " if ($has_oneof_case_message$) {\n" - " ref = $oneof_name$_;\n" - " }\n" - " if (!(ref instanceof java.lang.String)) {\n" - " com.google.protobuf.ByteString bs =\n" - " (com.google.protobuf.ByteString) ref;\n" - " java.lang.String s = bs.toStringUtf8();\n" - " if ($has_oneof_case_message$) {\n"); + printer->Print( + variables_, + "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" + " java.lang.Object ref $default_init$;\n" + " if ($has_oneof_case_message$) {\n" + " ref = $oneof_name$_;\n" + " }\n" + " if (ref instanceof java.lang.String) {\n" + " return (java.lang.String) ref;\n" + " } else {\n" + " com.google.protobuf.ByteString bs = \n" + " (com.google.protobuf.ByteString) ref;\n" + " java.lang.String s = bs.toStringUtf8();\n"); printer->Annotate("{", "}", descriptor_); if (CheckUtf8(descriptor_)) { printer->Print(variables_, - " $oneof_name$_ = s;\n"); + " if ($has_oneof_case_message$) {\n" + " $oneof_name$_ = s;\n" + " }\n"); } else { printer->Print(variables_, - " if (bs.isValidUtf8()) {\n" - " $oneof_name$_ = s;\n" - " }\n"); + " if (bs.isValidUtf8() && ($has_oneof_case_message$)) {\n" + " $oneof_name$_ = s;\n" + " }\n"); } printer->Print(variables_, - " }\n" - " return s;\n" - " } else {\n" - " return (java.lang.String) ref;\n" - " }\n" - "}\n"); + " return s;\n" + " }\n" + "}\n"); + WriteFieldDocComment(printer, descriptor_); - WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$() {\n" - " java.lang.Object ref $default_init$;\n" - " if ($has_oneof_case_message$) {\n" - " ref = $oneof_name$_;\n" - " }\n" - " if (ref instanceof String) {\n" - " com.google.protobuf.ByteString b = \n" - " com.google.protobuf.ByteString.copyFromUtf8(\n" - " (java.lang.String) ref);\n" - " if ($has_oneof_case_message$) {\n" - " $oneof_name$_ = b;\n" - " }\n" - " return b;\n" - " } else {\n" - " return (com.google.protobuf.ByteString) ref;\n" - " }\n" - "}\n"); + "$deprecation$public com.google.protobuf.ByteString\n" + " ${$get$capitalized_name$Bytes$}$() {\n" + " java.lang.Object ref $default_init$;\n" + " if ($has_oneof_case_message$) {\n" + " ref = $oneof_name$_;\n" + " }\n" + " if (ref instanceof java.lang.String) {\n" + " com.google.protobuf.ByteString b = \n" + " com.google.protobuf.ByteString.copyFromUtf8(\n" + " (java.lang.String) ref);\n" + " if ($has_oneof_case_message$) {\n" + " $oneof_name$_ = b;\n" + " }\n" + " return b;\n" + " } else {\n" + " return (com.google.protobuf.ByteString) ref;\n" + " }\n" + "}\n"); printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " java.lang.String value) {\n" - "$null_check$" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " $on_changed$\n" - " }\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n" - " com.google.protobuf.ByteString value) {\n" - "$null_check$"); - printer->Annotate("{", "}", descriptor_); - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " checkByteStringIsUtf8(value);\n"); - } - printer->Print(variables_, - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); } -void ImmutableStringOneofFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { +void ImmutableStringOneofFieldGenerator::GenerateBuilderMembers( + io::Printer* printer) const { + if (SupportFieldPresence(descriptor_->file())) { + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $has_oneof_case_message$;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + } + + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" + " java.lang.Object ref $default_init$;\n" + " if ($has_oneof_case_message$) {\n" + " ref = $oneof_name$_;\n" + " }\n" + " if (!(ref instanceof java.lang.String)) {\n" + " com.google.protobuf.ByteString bs =\n" + " (com.google.protobuf.ByteString) ref;\n" + " java.lang.String s = bs.toStringUtf8();\n" + " if ($has_oneof_case_message$) {\n"); + printer->Annotate("{", "}", descriptor_); + if (CheckUtf8(descriptor_)) { + printer->Print(variables_, " $oneof_name$_ = s;\n"); + } else { + printer->Print(variables_, + " if (bs.isValidUtf8()) {\n" + " $oneof_name$_ = s;\n" + " }\n"); + } + printer->Print(variables_, + " }\n" + " return s;\n" + " } else {\n" + " return (java.lang.String) ref;\n" + " }\n" + "}\n"); + + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$public com.google.protobuf.ByteString\n" + " ${$get$capitalized_name$Bytes$}$() {\n" + " java.lang.Object ref $default_init$;\n" + " if ($has_oneof_case_message$) {\n" + " ref = $oneof_name$_;\n" + " }\n" + " if (ref instanceof String) {\n" + " com.google.protobuf.ByteString b = \n" + " com.google.protobuf.ByteString.copyFromUtf8(\n" + " (java.lang.String) ref);\n" + " if ($has_oneof_case_message$) {\n" + " $oneof_name$_ = b;\n" + " }\n" + " return b;\n" + " } else {\n" + " return (com.google.protobuf.ByteString) ref;\n" + " }\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " java.lang.String value) {\n" + "$null_check$" + " $set_oneof_case_message$;\n" + " $oneof_name$_ = value;\n" + " $on_changed$\n" + " return this;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " if ($has_oneof_case_message$) {\n" + " $clear_oneof_case_message$;\n" + " $oneof_name$_ = null;\n" + " $on_changed$\n" + " }\n" + " return this;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n" + " com.google.protobuf.ByteString value) {\n" + "$null_check$"); + printer->Annotate("{", "}", descriptor_); + if (CheckUtf8(descriptor_)) { + printer->Print(variables_, " checkByteStringIsUtf8(value);\n"); + } + printer->Print(variables_, + " $set_oneof_case_message$;\n" + " $oneof_name$_ = value;\n" + " $on_changed$\n" + " return this;\n" + "}\n"); +} + +void ImmutableStringOneofFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { // Allow a slight breach of abstraction here in order to avoid forcing // all string fields to Strings when copying fields from a Message. printer->Print(variables_, - "$set_oneof_case_message$;\n" - "$oneof_name$_ = other.$oneof_name$_;\n" - "$on_changed$\n"); + "$set_oneof_case_message$;\n" + "$oneof_name$_ = other.$oneof_name$_;\n" + "$on_changed$\n"); } -void ImmutableStringOneofFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { +void ImmutableStringOneofFieldGenerator::GenerateBuildingCode( + io::Printer* printer) const { printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " result.$oneof_name$_ = $oneof_name$_;\n" - "}\n"); + "if ($has_oneof_case_message$) {\n" + " result.$oneof_name$_ = $oneof_name$_;\n" + "}\n"); } -void ImmutableStringOneofFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { +void ImmutableStringOneofFieldGenerator::GenerateParsingCode( + io::Printer* printer) const { if (CheckUtf8(descriptor_)) { printer->Print(variables_, - "java.lang.String s = input.readStringRequireUtf8();\n" - "$set_oneof_case_message$;\n" - "$oneof_name$_ = s;\n"); + "java.lang.String s = input.readStringRequireUtf8();\n" + "$set_oneof_case_message$;\n" + "$oneof_name$_ = s;\n"); } else { printer->Print(variables_, - "com.google.protobuf.ByteString bs = input.readBytes();\n" - "$set_oneof_case_message$;\n" - "$oneof_name$_ = bs;\n"); + "com.google.protobuf.ByteString bs = input.readBytes();\n" + "$set_oneof_case_message$;\n" + "$oneof_name$_ = bs;\n"); } } -void ImmutableStringOneofFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { +void ImmutableStringOneofFieldGenerator::GenerateSerializationCode( + io::Printer* printer) const { printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " $writeString$(output, $number$, $oneof_name$_);\n" - "}\n"); + "if ($has_oneof_case_message$) {\n" + " $writeString$(output, $number$, $oneof_name$_);\n" + "}\n"); } -void ImmutableStringOneofFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { +void ImmutableStringOneofFieldGenerator::GenerateSerializedSizeCode( + io::Printer* printer) const { printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += $computeStringSize$($number$, $oneof_name$_);\n" - "}\n"); + "if ($has_oneof_case_message$) {\n" + " size += $computeStringSize$($number$, $oneof_name$_);\n" + "}\n"); } // =================================================================== -RepeatedImmutableStringFieldGenerator:: -RepeatedImmutableStringFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { +RepeatedImmutableStringFieldGenerator::RepeatedImmutableStringFieldGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, + Context* context) + : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) { SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex, context->GetFieldGeneratorInfo(descriptor), name_resolver_, &variables_); } RepeatedImmutableStringFieldGenerator:: -~RepeatedImmutableStringFieldGenerator() {} + ~RepeatedImmutableStringFieldGenerator() {} int RepeatedImmutableStringFieldGenerator::GetNumBitsForMessage() const { return 0; @@ -729,67 +721,69 @@ int RepeatedImmutableStringFieldGenerator::GetNumBitsForBuilder() const { return 1; } -void RepeatedImmutableStringFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { +void RepeatedImmutableStringFieldGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + // NOTE: the same method in the implementation class actually returns + // com.google.protobuf.ProtocolStringList (a subclass of List). It's + // changed between protobuf 2.5.0 release and protobuf 2.6.1 release. + // To retain binary compatibility with both 2.5.0 and 2.6.1 generated + // code, we make this interface method return List so both methods + // with different return types exist in the compiled byte code. + "$deprecation$java.util.List\n" + " get$capitalized_name$List();\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - // NOTE: the same method in the implementation class actually returns - // com.google.protobuf.ProtocolStringList (a subclass of List). It's - // changed between protobuf 2.5.0 release and protobuf 2.6.1 release. - // To retain binary compatibility with both 2.5.0 and 2.6.1 generated - // code, we make this interface method return List so both methods - // with different return types exist in the compiled byte code. - "$deprecation$java.util.List\n" - " get$capitalized_name$List();\n"); + "$deprecation$int get$capitalized_name$Count();\n"); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$java.lang.String get$capitalized_name$(int index);\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.lang.String get$capitalized_name$(int index);\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$com.google.protobuf.ByteString\n" - " get$capitalized_name$Bytes(int index);\n"); + "$deprecation$com.google.protobuf.ByteString\n" + " get$capitalized_name$Bytes(int index);\n"); } - -void RepeatedImmutableStringFieldGenerator:: -GenerateMembers(io::Printer* printer) const { +void RepeatedImmutableStringFieldGenerator::GenerateMembers( + io::Printer* printer) const { printer->Print(variables_, - "private com.google.protobuf.LazyStringList $name$_;\n"); + "private com.google.protobuf.LazyStringList $name$_;\n"); PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public com.google.protobuf.ProtocolStringList\n" - " ${$get$capitalized_name$List$}$() {\n" - " return $name$_;\n" // note: unmodifiable list - "}\n"); + "$deprecation$public com.google.protobuf.ProtocolStringList\n" + " ${$get$capitalized_name$List$}$() {\n" + " return $name$_;\n" // note: unmodifiable list + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" + " return $name$_.size();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); + "$deprecation$public java.lang.String " + "${$get$capitalized_name$$}$(int index) {\n" + " return $name$_.get(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public java.lang.String " - "${$get$capitalized_name$$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$(int index) {\n" - " return $name$_.getByteString(index);\n" - "}\n"); + "$deprecation$public com.google.protobuf.ByteString\n" + " ${$get$capitalized_name$Bytes$}$(int index) {\n" + " return $name$_.getByteString(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } -void RepeatedImmutableStringFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void RepeatedImmutableStringFieldGenerator::GenerateBuilderMembers( + io::Printer* printer) const { // One field is the list and the bit field keeps track of whether the // list is immutable. If it's immutable, the invariant is that it must // either an instance of Collections.emptyList() or it's an ArrayList @@ -799,237 +793,240 @@ GenerateBuilderMembers(io::Printer* printer) const { // memory allocations. Note, immutable is a strong guarantee here -- not // just that the list cannot be modified via the reference but that the // list can never be modified. - printer->Print(variables_, - "private com.google.protobuf.LazyStringList $name$_ = $empty_list$;\n"); + printer->Print( + variables_, + "private com.google.protobuf.LazyStringList $name$_ = $empty_list$;\n"); - printer->Print(variables_, - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$get_mutable_bit_builder$) {\n" - " $name$_ = new com.google.protobuf.LazyStringArrayList($name$_);\n" - " $set_mutable_bit_builder$;\n" - " }\n" - "}\n"); + printer->Print( + variables_, + "private void ensure$capitalized_name$IsMutable() {\n" + " if (!$get_mutable_bit_builder$) {\n" + " $name$_ = new com.google.protobuf.LazyStringArrayList($name$_);\n" + " $set_mutable_bit_builder$;\n" + " }\n" + "}\n"); - // Note: We return an unmodifiable list because otherwise the caller - // could hold on to the returned list and modify it after the message - // has been built, thus mutating the message which is supposed to be - // immutable. + // Note: We return an unmodifiable list because otherwise the caller + // could hold on to the returned list and modify it after the message + // has been built, thus mutating the message which is supposed to be + // immutable. WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public com.google.protobuf.ProtocolStringList\n" - " ${$get$capitalized_name$List$}$() {\n" - " return $name$_.getUnmodifiableView();\n" - "}\n"); + "$deprecation$public com.google.protobuf.ProtocolStringList\n" + " ${$get$capitalized_name$List$}$() {\n" + " return $name$_.getUnmodifiableView();\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" + " return $name$_.size();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); + "$deprecation$public java.lang.String " + "${$get$capitalized_name$$}$(int index) {\n" + " return $name$_.get(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public java.lang.String " - "${$get$capitalized_name$$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); + "$deprecation$public com.google.protobuf.ByteString\n" + " ${$get$capitalized_name$Bytes$}$(int index) {\n" + " return $name$_.getByteString(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$(int index) {\n" - " return $name$_.getByteString(index);\n" - "}\n"); + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " int index, java.lang.String value) {\n" + "$null_check$" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.set(index, value);\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, java.lang.String value) {\n" - "$null_check$" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(index, value);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" + " java.lang.String value) {\n" + "$null_check$" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.add(value);\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" - " java.lang.String value) {\n" - "$null_check$" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(value);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" + " java.lang.Iterable values) {\n" + " ensure$capitalized_name$IsMutable();\n" + " com.google.protobuf.AbstractMessageLite.Builder.addAll(\n" + " values, $name$_);\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " com.google.protobuf.AbstractMessageLite.Builder.addAll(\n" - " values, $name$_);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " $name$_ = $empty_list$;\n" - " $clear_mutable_bit_builder$;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " $name$_ = $empty_list$;\n" + " $clear_mutable_bit_builder$;\n" + " $on_changed$\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$Bytes$}$(\n" - " com.google.protobuf.ByteString value) {\n" - "$null_check$"); + printer->Print( + variables_, + "$deprecation$public Builder ${$add$capitalized_name$Bytes$}$(\n" + " com.google.protobuf.ByteString value) {\n" + "$null_check$"); printer->Annotate("{", "}", descriptor_); if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " checkByteStringIsUtf8(value);\n"); + printer->Print(variables_, " checkByteStringIsUtf8(value);\n"); } printer->Print(variables_, - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(value);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); + " ensure$capitalized_name$IsMutable();\n" + " $name$_.add(value);\n" + " $on_changed$\n" + " return this;\n" + "}\n"); } void RepeatedImmutableStringFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { + GenerateFieldBuilderInitializationCode(io::Printer* printer) const { // noop for primitives } -void RepeatedImmutableStringFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { +void RepeatedImmutableStringFieldGenerator::GenerateInitializationCode( + io::Printer* printer) const { printer->Print(variables_, "$name$_ = $empty_list$;\n"); } -void RepeatedImmutableStringFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { +void RepeatedImmutableStringFieldGenerator::GenerateBuilderClearCode( + io::Printer* printer) const { printer->Print(variables_, - "$name$_ = $empty_list$;\n" - "$clear_mutable_bit_builder$;\n"); + "$name$_ = $empty_list$;\n" + "$clear_mutable_bit_builder$;\n"); } -void RepeatedImmutableStringFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { +void RepeatedImmutableStringFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { // The code below does two optimizations: // 1. If the other list is empty, there's nothing to do. This ensures we // don't allocate a new array if we already have an immutable one. // 2. If the other list is non-empty and our current list is empty, we can // reuse the other list which is guaranteed to be immutable. printer->Print(variables_, - "if (!other.$name$_.isEmpty()) {\n" - " if ($name$_.isEmpty()) {\n" - " $name$_ = other.$name$_;\n" - " $clear_mutable_bit_builder$;\n" - " } else {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.addAll(other.$name$_);\n" - " }\n" - " $on_changed$\n" - "}\n"); + "if (!other.$name$_.isEmpty()) {\n" + " if ($name$_.isEmpty()) {\n" + " $name$_ = other.$name$_;\n" + " $clear_mutable_bit_builder$;\n" + " } else {\n" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.addAll(other.$name$_);\n" + " }\n" + " $on_changed$\n" + "}\n"); } -void RepeatedImmutableStringFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { +void RepeatedImmutableStringFieldGenerator::GenerateBuildingCode( + io::Printer* printer) const { // The code below ensures that the result has an immutable list. If our // list is immutable, we can just reuse it. If not, we make it immutable. printer->Print(variables_, - "if ($get_mutable_bit_builder$) {\n" - " $name$_ = $name$_.getUnmodifiableView();\n" - " $clear_mutable_bit_builder$;\n" - "}\n" - "result.$name$_ = $name$_;\n"); + "if ($get_mutable_bit_builder$) {\n" + " $name$_ = $name$_.getUnmodifiableView();\n" + " $clear_mutable_bit_builder$;\n" + "}\n" + "result.$name$_ = $name$_;\n"); } -void RepeatedImmutableStringFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { +void RepeatedImmutableStringFieldGenerator::GenerateParsingCode( + io::Printer* printer) const { if (CheckUtf8(descriptor_)) { printer->Print(variables_, - "java.lang.String s = input.readStringRequireUtf8();\n"); + "java.lang.String s = input.readStringRequireUtf8();\n"); } else { printer->Print(variables_, - "com.google.protobuf.ByteString bs = input.readBytes();\n"); + "com.google.protobuf.ByteString bs = input.readBytes();\n"); } printer->Print(variables_, - "if (!$get_mutable_bit_parser$) {\n" - " $name$_ = new com.google.protobuf.LazyStringArrayList();\n" - " $set_mutable_bit_parser$;\n" - "}\n"); + "if (!$get_mutable_bit_parser$) {\n" + " $name$_ = new com.google.protobuf.LazyStringArrayList();\n" + " $set_mutable_bit_parser$;\n" + "}\n"); if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - "$name$_.add(s);\n"); + printer->Print(variables_, "$name$_.add(s);\n"); } else { - printer->Print(variables_, - "$name$_.add(bs);\n"); + printer->Print(variables_, "$name$_.add(bs);\n"); } } -void RepeatedImmutableStringFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { +void RepeatedImmutableStringFieldGenerator::GenerateParsingDoneCode( + io::Printer* printer) const { printer->Print(variables_, - "if ($get_mutable_bit_parser$) {\n" - " $name$_ = $name$_.getUnmodifiableView();\n" - "}\n"); + "if ($get_mutable_bit_parser$) {\n" + " $name$_ = $name$_.getUnmodifiableView();\n" + "}\n"); } -void RepeatedImmutableStringFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { +void RepeatedImmutableStringFieldGenerator::GenerateSerializationCode( + io::Printer* printer) const { printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " $writeString$(output, $number$, $name$_.getRaw(i));\n" - "}\n"); + "for (int i = 0; i < $name$_.size(); i++) {\n" + " $writeString$(output, $number$, $name$_.getRaw(i));\n" + "}\n"); } -void RepeatedImmutableStringFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { +void RepeatedImmutableStringFieldGenerator::GenerateSerializedSizeCode( + io::Printer* printer) const { printer->Print(variables_, - "{\n" - " int dataSize = 0;\n"); + "{\n" + " int dataSize = 0;\n"); printer->Indent(); printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " dataSize += computeStringSizeNoTag($name$_.getRaw(i));\n" - "}\n"); + "for (int i = 0; i < $name$_.size(); i++) {\n" + " dataSize += computeStringSizeNoTag($name$_.getRaw(i));\n" + "}\n"); - printer->Print( - "size += dataSize;\n"); + printer->Print("size += dataSize;\n"); printer->Print(variables_, - "size += $tag_size$ * get$capitalized_name$List().size();\n"); + "size += $tag_size$ * get$capitalized_name$List().size();\n"); printer->Outdent(); printer->Print("}\n"); } -void RepeatedImmutableStringFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && get$capitalized_name$List()\n" - " .equals(other.get$capitalized_name$List());\n"); +void RepeatedImmutableStringFieldGenerator::GenerateEqualsCode( + io::Printer* printer) const { + printer->Print( + variables_, + "if (!get$capitalized_name$List()\n" + " .equals(other.get$capitalized_name$List())) return false;\n"); } -void RepeatedImmutableStringFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "if (get$capitalized_name$Count() > 0) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + get$capitalized_name$List().hashCode();\n" - "}\n"); +void RepeatedImmutableStringFieldGenerator::GenerateHashCode( + io::Printer* printer) const { + printer->Print( + variables_, + "if (get$capitalized_name$Count() > 0) {\n" + " hash = (37 * hash) + $constant_name$;\n" + " hash = (53 * hash) + get$capitalized_name$List().hashCode();\n" + "}\n"); } -string RepeatedImmutableStringFieldGenerator::GetBoxedType() const { +std::string RepeatedImmutableStringFieldGenerator::GetBoxedType() const { return "String"; } diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_string_field.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_string_field.h index 0f7c705b..1c00ae81 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_string_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_string_field.h @@ -42,26 +42,29 @@ namespace google { namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } -} +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { class ImmutableStringFieldGenerator : public ImmutableFieldGenerator { public: - explicit ImmutableStringFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + explicit ImmutableStringFieldGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, + int builderBitIndex, Context* context); ~ImmutableStringFieldGenerator(); - // implements ImmutableFieldGenerator --------------------------------------- + // implements ImmutableFieldGenerator + // --------------------------------------- int GetNumBitsForMessage() const; int GetNumBitsForBuilder() const; void GenerateInterfaceMembers(io::Printer* printer) const; @@ -79,14 +82,11 @@ class ImmutableStringFieldGenerator : public ImmutableFieldGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; + std::map variables_; ClassNameResolver* name_resolver_; private: @@ -96,9 +96,9 @@ class ImmutableStringFieldGenerator : public ImmutableFieldGenerator { class ImmutableStringOneofFieldGenerator : public ImmutableStringFieldGenerator { public: - ImmutableStringOneofFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + ImmutableStringOneofFieldGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, int builderBitIndex, + Context* context); ~ImmutableStringOneofFieldGenerator(); private: @@ -138,14 +138,11 @@ class RepeatedImmutableStringFieldGenerator : public ImmutableFieldGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; private: const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; + std::map variables_; ClassNameResolver* name_resolver_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableStringFieldGenerator); @@ -154,6 +151,6 @@ class RepeatedImmutableStringFieldGenerator : public ImmutableFieldGenerator { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_STRING_FIELD_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_string_field_lite.cc b/third_party/protobuf/src/google/protobuf/compiler/java/java_string_field_lite.cc index a238c67d..40868fac 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_string_field_lite.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_string_field_lite.cc @@ -47,6 +47,7 @@ #include #include + namespace google { namespace protobuf { namespace compiler { @@ -58,11 +59,10 @@ using internal::WireFormatLite; namespace { void SetPrimitiveVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, + int messageBitIndex, int builderBitIndex, const FieldGeneratorInfo* info, ClassNameResolver* name_resolver, - std::map* variables) { + std::map* variables) { SetCommonFieldVariables(descriptor, info, variables); (*variables)["empty_list"] = @@ -73,8 +73,8 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor, "= " + ImmutableDefaultValue(descriptor, name_resolver); (*variables)["capitalized_type"] = "java.lang.String"; (*variables)["tag"] = - SimpleItoa(static_cast(WireFormat::MakeTag(descriptor))); - (*variables)["tag_size"] = SimpleItoa( + StrCat(static_cast(WireFormat::MakeTag(descriptor))); + (*variables)["tag_size"] = StrCat( WireFormat::TagSize(descriptor->number(), GetType(descriptor))); (*variables)["null_check"] = " if (value == null) {\n" @@ -83,8 +83,8 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor, // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; + (*variables)["deprecation"] = + descriptor->options().deprecated() ? "@java.lang.Deprecated " : ""; (*variables)["required"] = descriptor->is_required() ? "true" : "false"; if (SupportFieldPresence(descriptor->file())) { @@ -119,15 +119,12 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor, // =================================================================== -ImmutableStringFieldLiteGenerator:: -ImmutableStringFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex, +ImmutableStringFieldLiteGenerator::ImmutableStringFieldLiteGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, Context* context) + : descriptor_(descriptor), + messageBitIndex_(messageBitIndex), + name_resolver_(context->GetNameResolver()) { + SetPrimitiveVariables(descriptor, messageBitIndex, 0, context->GetFieldGeneratorInfo(descriptor), name_resolver_, &variables_); } @@ -135,11 +132,7 @@ ImmutableStringFieldLiteGenerator(const FieldDescriptor* descriptor, ImmutableStringFieldLiteGenerator::~ImmutableStringFieldLiteGenerator() {} int ImmutableStringFieldLiteGenerator::GetNumBitsForMessage() const { - return 1; -} - -int ImmutableStringFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; + return SupportFieldPresence(descriptor_->file()) ? 1 : 0; } // A note about how strings are handled. In the SPEED and CODE_SIZE runtimes, @@ -167,765 +160,558 @@ int ImmutableStringFieldLiteGenerator::GetNumBitsForBuilder() const { // TODO(dweis): Consider dropping all of the *Bytes() methods. They really // shouldn't be necessary or used on devices. -void ImmutableStringFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { +void ImmutableStringFieldLiteGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); + "$deprecation$boolean has$capitalized_name$();\n"); } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$java.lang.String get$capitalized_name$();\n"); + "$deprecation$java.lang.String get$capitalized_name$();\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$com.google.protobuf.ByteString\n" - " get$capitalized_name$Bytes();\n"); + "$deprecation$com.google.protobuf.ByteString\n" + " get$capitalized_name$Bytes();\n"); } -void ImmutableStringFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private java.lang.String $name$_;\n"); +void ImmutableStringFieldLiteGenerator::GenerateMembers( + io::Printer* printer) const { + printer->Print(variables_, "private java.lang.String $name$_;\n"); PrintExtraFieldInfo(variables_, printer); if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $get_has_field_bit_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" - " return $name$_;\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" + " return $name$_;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$() {\n" - " return com.google.protobuf.ByteString.copyFromUtf8($name$_);\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public com.google.protobuf.ByteString\n" + " ${$get$capitalized_name$Bytes$}$() {\n" + " return com.google.protobuf.ByteString.copyFromUtf8($name$_);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void set$capitalized_name$(\n" - " java.lang.String value) {\n" - "$null_check$" - " $set_has_field_bit_message$\n" - " $name$_ = value;\n" - "}\n"); + "private void set$capitalized_name$(\n" + " java.lang.String value) {\n" + "$null_check$" + " $set_has_field_bit_message$\n" + " $name$_ = value;\n" + "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $clear_has_field_bit_message$\n" - // The default value is not a simple literal so we want to avoid executing - // it multiple times. Instead, get the default out of the default instance. - " $name$_ = getDefaultInstance().get$capitalized_name$();\n" - "}\n"); + "private void clear$capitalized_name$() {\n" + " $clear_has_field_bit_message$\n" + // The default value is not a simple literal so we want to + // avoid executing it multiple times. Instead, get the default + // out of the default instance. + " $name$_ = getDefaultInstance().get$capitalized_name$();\n" + "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void set$capitalized_name$Bytes(\n" - " com.google.protobuf.ByteString value) {\n" - "$null_check$"); + "private void set$capitalized_name$Bytes(\n" + " com.google.protobuf.ByteString value) {\n" + "$null_check$"); if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " checkByteStringIsUtf8(value);\n"); + printer->Print(variables_, " checkByteStringIsUtf8(value);\n"); } printer->Print(variables_, - " $set_has_field_bit_message$\n" - " $name$_ = value.toStringUtf8();\n" - "}\n"); + " $set_has_field_bit_message$\n" + " $name$_ = value.toStringUtf8();\n" + "}\n"); } -void ImmutableStringFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void ImmutableStringFieldLiteGenerator::GenerateBuilderMembers( + io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return instance.has$capitalized_name$();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" + " return instance.get$capitalized_name$();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$() {\n" - " return instance.get$capitalized_name$Bytes();\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public com.google.protobuf.ByteString\n" + " ${$get$capitalized_name$Bytes$}$() {\n" + " return instance.get$capitalized_name$Bytes();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " java.lang.String value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " java.lang.String value) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$(value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " copyOnWrite();\n" + " instance.clear$capitalized_name$();\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n" - " com.google.protobuf.ByteString value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$Bytes(value);\n" - " return this;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n" + " com.google.protobuf.ByteString value) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$Bytes(value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } -void ImmutableStringFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for strings +void ImmutableStringFieldLiteGenerator::GenerateFieldInfo( + io::Printer* printer, std::vector* output) const { + WriteIntToUtf16CharSequence(descriptor_->number(), output); + WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_), + output); + if (SupportFieldPresence(descriptor_->file())) { + WriteIntToUtf16CharSequence(messageBitIndex_, output); + } + printer->Print(variables_, "\"$name$_\",\n"); } - -void ImmutableStringFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const { +void ImmutableStringFieldLiteGenerator::GenerateInitializationCode( + io::Printer* printer) const { printer->Print(variables_, "$name$_ = $default$;\n"); } -void ImmutableStringFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "$name$_ = visitor.visitString(\n" - " has$capitalized_name$(), $name$_,\n" - " other.has$capitalized_name$(), other.$name$_);\n"); - } else { - printer->Print(variables_, - "$name$_ = visitor.visitString(!$name$_.isEmpty(), $name$_,\n" - " !other.$name$_.isEmpty(), other.$name$_);\n"); - } -} - -void ImmutableStringFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - // noop for scalars -} - -void ImmutableStringFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - "java.lang.String s = input.readStringRequireUtf8();\n" - "$set_has_field_bit_message$\n" - "$name$_ = s;\n"); - } else { - // Lite runtime should attempt to reduce allocations by attempting to - // construct the string directly from the input stream buffer. This avoids - // spurious intermediary ByteString allocations, cutting overall allocations - // in half. - printer->Print(variables_, - "java.lang.String s = input.readString();\n" - "$set_has_field_bit_message$\n" - "$name$_ = s;\n"); - } -} - -void ImmutableStringFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - // noop for strings -} - -void ImmutableStringFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - // Lite runtime should reduce allocations by serializing the string directly. - // This avoids spurious intermediary ByteString allocations, cutting overall - // allocations in half. - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " output.writeString($number$, get$capitalized_name$());\n" - "}\n"); -} - -void ImmutableStringFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - // Lite runtime should reduce allocations by computing on the string directly. - // This avoids spurious intermediary ByteString allocations, cutting overall - // allocations in half. - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeStringSize($number$, get$capitalized_name$());\n" - "}\n"); -} - -void ImmutableStringFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && get$capitalized_name$()\n" - " .equals(other.get$capitalized_name$());\n"); -} - -void ImmutableStringFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n"); - printer->Print(variables_, - "hash = (53 * hash) + get$capitalized_name$().hashCode();\n"); -} - -string ImmutableStringFieldLiteGenerator::GetBoxedType() const { +std::string ImmutableStringFieldLiteGenerator::GetBoxedType() const { return "java.lang.String"; } // =================================================================== -ImmutableStringOneofFieldLiteGenerator:: -ImmutableStringOneofFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableStringFieldLiteGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { +ImmutableStringOneofFieldLiteGenerator::ImmutableStringOneofFieldLiteGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, Context* context) + : ImmutableStringFieldLiteGenerator(descriptor, messageBitIndex, context) { const OneofGeneratorInfo* info = context->GetOneofGeneratorInfo(descriptor->containing_oneof()); SetCommonOneofVariables(descriptor, info, &variables_); } ImmutableStringOneofFieldLiteGenerator:: -~ImmutableStringOneofFieldLiteGenerator() {} + ~ImmutableStringOneofFieldLiteGenerator() {} -void ImmutableStringOneofFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { +void ImmutableStringOneofFieldLiteGenerator::GenerateMembers( + io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" - " java.lang.String ref $default_init$;\n" - " if ($has_oneof_case_message$) {\n" - " ref = (java.lang.String) $oneof_name$_;\n" - " }\n" - " return ref;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$() {\n" - " java.lang.String ref $default_init$;\n" - " if ($has_oneof_case_message$) {\n" - " ref = (java.lang.String) $oneof_name$_;\n" - " }\n" - " return com.google.protobuf.ByteString.copyFromUtf8(ref);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void ${$set$capitalized_name$$}$(\n" - " java.lang.String value) {\n" - "$null_check$" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void ${$clear$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " }\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void ${$set$capitalized_name$Bytes$}$(\n" - " com.google.protobuf.ByteString value) {\n" - "$null_check$"); - printer->Annotate("{", "}", descriptor_); - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " checkByteStringIsUtf8(value);\n"); - } - printer->Print(variables_, - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value.toStringUtf8();\n" - "}\n"); -} - - -void ImmutableStringOneofFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return $has_oneof_case_message$;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" + " java.lang.String ref $default_init$;\n" + " if ($has_oneof_case_message$) {\n" + " ref = (java.lang.String) $oneof_name$_;\n" + " }\n" + " return ref;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public com.google.protobuf.ByteString\n" + " ${$get$capitalized_name$Bytes$}$() {\n" + " java.lang.String ref $default_init$;\n" + " if ($has_oneof_case_message$) {\n" + " ref = (java.lang.String) $oneof_name$_;\n" + " }\n" + " return com.google.protobuf.ByteString.copyFromUtf8(ref);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$() {\n" - " return instance.get$capitalized_name$Bytes();\n" - "}\n"); + "private void ${$set$capitalized_name$$}$(\n" + " java.lang.String value) {\n" + "$null_check$" + " $set_oneof_case_message$;\n" + " $oneof_name$_ = value;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "private void ${$clear$capitalized_name$$}$() {\n" + " if ($has_oneof_case_message$) {\n" + " $clear_oneof_case_message$;\n" + " $oneof_name$_ = null;\n" + " }\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " java.lang.String value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); + "private void ${$set$capitalized_name$Bytes$}$(\n" + " com.google.protobuf.ByteString value) {\n" + "$null_check$"); printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n" - " com.google.protobuf.ByteString value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$Bytes(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutableStringOneofFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$oneof_name$_ = visitor.visitOneofString(\n" - " $has_oneof_case_message$, $oneof_name$_, other.$oneof_name$_);\n"); -} - -void ImmutableStringOneofFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - "java.lang.String s = input.readStringRequireUtf8();\n" - "$set_oneof_case_message$;\n" - "$oneof_name$_ = s;\n"); - } else { - // Lite runtime should attempt to reduce allocations by attempting to - // construct the string directly from the input stream buffer. This avoids - // spurious intermediary ByteString allocations, cutting overall allocations - // in half. - printer->Print(variables_, - "java.lang.String s = input.readString();\n" - "$set_oneof_case_message$;\n" - "$oneof_name$_ = s;\n"); + printer->Print(variables_, " checkByteStringIsUtf8(value);\n"); } + printer->Print(variables_, + " $set_oneof_case_message$;\n" + " $oneof_name$_ = value.toStringUtf8();\n" + "}\n"); } -void ImmutableStringOneofFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - // Lite runtime should reduce allocations by serializing the string directly. - // This avoids spurious intermediary ByteString allocations, cutting overall - // allocations in half. - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.writeString($number$, get$capitalized_name$());\n" - "}\n"); +void ImmutableStringOneofFieldLiteGenerator::GenerateFieldInfo( + io::Printer* printer, std::vector* output) const { + WriteIntToUtf16CharSequence(descriptor_->number(), output); + WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_), + output); + WriteIntToUtf16CharSequence(descriptor_->containing_oneof()->index(), output); } -void ImmutableStringOneofFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - // Lite runtime should reduce allocations by computing on the string directly. - // This avoids spurious intermediary ByteString allocations, cutting overall - // allocations in half. +void ImmutableStringOneofFieldLiteGenerator::GenerateBuilderMembers( + io::Printer* printer) const { + if (SupportFieldPresence(descriptor_->file())) { + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" + " return instance.has$capitalized_name$();\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + } + + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" + " return instance.get$capitalized_name$();\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + + WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeStringSize($number$, get$capitalized_name$());\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public com.google.protobuf.ByteString\n" + " ${$get$capitalized_name$Bytes$}$() {\n" + " return instance.get$capitalized_name$Bytes();\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " java.lang.String value) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$(value);\n" + " return this;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " copyOnWrite();\n" + " instance.clear$capitalized_name$();\n" + " return this;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n" + " com.google.protobuf.ByteString value) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$Bytes(value);\n" + " return this;\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); } // =================================================================== RepeatedImmutableStringFieldLiteGenerator:: -RepeatedImmutableStringFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex, + RepeatedImmutableStringFieldLiteGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, + Context* context) + : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) { + SetPrimitiveVariables(descriptor, messageBitIndex, 0, context->GetFieldGeneratorInfo(descriptor), name_resolver_, &variables_); } RepeatedImmutableStringFieldLiteGenerator:: -~RepeatedImmutableStringFieldLiteGenerator() {} + ~RepeatedImmutableStringFieldLiteGenerator() {} int RepeatedImmutableStringFieldLiteGenerator::GetNumBitsForMessage() const { return 0; } -int RepeatedImmutableStringFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; +void RepeatedImmutableStringFieldLiteGenerator::GenerateInterfaceMembers( + io::Printer* printer) const { + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$java.util.List\n" + " get$capitalized_name$List();\n"); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$int get$capitalized_name$Count();\n"); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "$deprecation$java.lang.String get$capitalized_name$(int index);\n"); + WriteFieldDocComment(printer, descriptor_); + printer->Print(variables_, + "$deprecation$com.google.protobuf.ByteString\n" + " get$capitalized_name$Bytes(int index);\n"); } -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.util.List\n" - " get$capitalized_name$List();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.lang.String get$capitalized_name$(int index);\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$com.google.protobuf.ByteString\n" - " get$capitalized_name$Bytes(int index);\n"); -} - - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private com.google.protobuf.Internal.ProtobufList " - "$name$_;\n"); +void RepeatedImmutableStringFieldLiteGenerator::GenerateMembers( + io::Printer* printer) const { + printer->Print( + variables_, + "private com.google.protobuf.Internal.ProtobufList " + "$name$_;\n"); PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List " - "${$get$capitalized_name$List$}$() {\n" - " return $name$_;\n" // note: unmodifiable list - "}\n"); + "@java.lang.Override\n" + "$deprecation$public java.util.List " + "${$get$capitalized_name$List$}$() {\n" + " return $name$_;\n" // note: unmodifiable list + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" + " return $name$_.size();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public java.lang.String " + "${$get$capitalized_name$$}$(int index) {\n" + " return $name$_.get(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.lang.String " - "${$get$capitalized_name$$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$(int index) {\n" - " return com.google.protobuf.ByteString.copyFromUtf8(\n" - " $name$_.get(index));\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public com.google.protobuf.ByteString\n" + " ${$get$capitalized_name$Bytes$}$(int index) {\n" + " return com.google.protobuf.ByteString.copyFromUtf8(\n" + " $name$_.get(index));\n" + "}\n"); printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - " }\n" - "}\n"); + printer->Print( + variables_, + "private void ensure$capitalized_name$IsMutable() {\n" + " if (!$is_mutable$) {\n" + " $name$_ =\n" + " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" + " }\n" + "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void set$capitalized_name$(\n" - " int index, java.lang.String value) {\n" - "$null_check$" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(index, value);\n" - "}\n"); + "private void set$capitalized_name$(\n" + " int index, java.lang.String value) {\n" + "$null_check$" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.set(index, value);\n" + "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void add$capitalized_name$(\n" - " java.lang.String value) {\n" - "$null_check$" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(value);\n" - "}\n"); + "private void add$capitalized_name$(\n" + " java.lang.String value) {\n" + "$null_check$" + " ensure$capitalized_name$IsMutable();\n" + " $name$_.add(value);\n" + "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void addAll$capitalized_name$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " com.google.protobuf.AbstractMessageLite.addAll(\n" - " values, $name$_);\n" - "}\n"); + "private void addAll$capitalized_name$(\n" + " java.lang.Iterable values) {\n" + " ensure$capitalized_name$IsMutable();\n" + " com.google.protobuf.AbstractMessageLite.addAll(\n" + " values, $name$_);\n" + "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $name$_ = $empty_list$;\n" - "}\n"); + "private void clear$capitalized_name$() {\n" + " $name$_ = $empty_list$;\n" + "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "private void add$capitalized_name$Bytes(\n" - " com.google.protobuf.ByteString value) {\n" - "$null_check$"); + "private void add$capitalized_name$Bytes(\n" + " com.google.protobuf.ByteString value) {\n" + "$null_check$"); if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " checkByteStringIsUtf8(value);\n"); + printer->Print(variables_, " checkByteStringIsUtf8(value);\n"); } printer->Print(variables_, - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(value.toStringUtf8());\n" - "}\n"); + " ensure$capitalized_name$IsMutable();\n" + " $name$_.add(value.toStringUtf8());\n" + "}\n"); } -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { +void RepeatedImmutableStringFieldLiteGenerator::GenerateBuilderMembers( + io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List\n" - " ${$get$capitalized_name$List$}$() {\n" - " return java.util.Collections.unmodifiableList(\n" - " instance.get$capitalized_name$List());\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public java.util.List\n" + " ${$get$capitalized_name$List$}$() {\n" + " return java.util.Collections.unmodifiableList(\n" + " instance.get$capitalized_name$List());\n" + "}\n"); + printer->Annotate("{", "}", descriptor_); + WriteFieldDocComment(printer, descriptor_); + printer->Print( + variables_, + "@java.lang.Override\n" + "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" + " return instance.get$capitalized_name$Count();\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return instance.get$capitalized_name$Count();\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public java.lang.String " + "${$get$capitalized_name$$}$(int index) {\n" + " return instance.get$capitalized_name$(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.lang.String " - "${$get$capitalized_name$$}$(int index) {\n" - " return instance.get$capitalized_name$(index);\n" - "}\n"); + "@java.lang.Override\n" + "$deprecation$public com.google.protobuf.ByteString\n" + " ${$get$capitalized_name$Bytes$}$(int index) {\n" + " return instance.get$capitalized_name$Bytes(index);\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$(int index) {\n" - " return instance.get$capitalized_name$Bytes(index);\n" - "}\n"); + "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" + " int index, java.lang.String value) {\n" + " copyOnWrite();\n" + " instance.set$capitalized_name$(index, value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, java.lang.String value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(index, value);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" + " java.lang.String value) {\n" + " copyOnWrite();\n" + " instance.add$capitalized_name$(value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" - " java.lang.String value) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(value);\n" - " return this;\n" - "}\n"); + "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" + " java.lang.Iterable values) {\n" + " copyOnWrite();\n" + " instance.addAll$capitalized_name$(values);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" - " java.lang.Iterable values) {\n" - " copyOnWrite();\n" - " instance.addAll$capitalized_name$(values);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" + " copyOnWrite();\n" + " instance.clear$capitalized_name$();\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$Bytes$}$(\n" - " com.google.protobuf.ByteString value) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$Bytes(value);\n" - " return this;\n" - "}\n"); + printer->Print( + variables_, + "$deprecation$public Builder ${$add$capitalized_name$Bytes$}$(\n" + " com.google.protobuf.ByteString value) {\n" + " copyOnWrite();\n" + " instance.add$capitalized_name$Bytes(value);\n" + " return this;\n" + "}\n"); printer->Annotate("{", "}", descriptor_); } -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for strings +void RepeatedImmutableStringFieldLiteGenerator::GenerateFieldInfo( + io::Printer* printer, std::vector* output) const { + WriteIntToUtf16CharSequence(descriptor_->number(), output); + WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_), + output); + printer->Print(variables_, "\"$name$_\",\n"); } - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const { +void RepeatedImmutableStringFieldLiteGenerator::GenerateInitializationCode( + io::Printer* printer) const { printer->Print(variables_, "$name$_ = $empty_list$;\n"); } -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_= visitor.visitList($name$_, other.$name$_);\n"); -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_.makeImmutable();\n"); -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - "java.lang.String s = input.readStringRequireUtf8();\n"); - } else { - // Lite runtime should attempt to reduce allocations by attempting to - // construct the string directly from the input stream buffer. This avoids - // spurious intermediary ByteString allocations, cutting overall allocations - // in half. - printer->Print(variables_, - "java.lang.String s = input.readString();\n"); - } - printer->Print(variables_, - "if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - "}\n"); - printer->Print(variables_, - "$name$_.add(s);\n"); -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_mutable$) {\n" - " $name$_.makeImmutable();\n" - "}\n"); -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - // Lite runtime should reduce allocations by serializing the string directly. - // This avoids spurious intermediary ByteString allocations, cutting overall - // allocations in half. - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.writeString($number$, $name$_.get(i));\n" - "}\n"); -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - // Lite runtime should reduce allocations by computing on the string directly. - // This avoids spurious intermediary ByteString allocations, cutting overall - // allocations in half. - printer->Print(variables_, - "{\n" - " int dataSize = 0;\n"); - printer->Indent(); - - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " dataSize += com.google.protobuf.CodedOutputStream\n" - " .computeStringSizeNoTag($name$_.get(i));\n" - "}\n"); - - printer->Print( - "size += dataSize;\n"); - - - printer->Print(variables_, - "size += $tag_size$ * get$capitalized_name$List().size();\n"); - - printer->Outdent(); - printer->Print("}\n"); -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && get$capitalized_name$List()\n" - " .equals(other.get$capitalized_name$List());\n"); -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "if (get$capitalized_name$Count() > 0) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + get$capitalized_name$List().hashCode();\n" - "}\n"); -} - -string RepeatedImmutableStringFieldLiteGenerator::GetBoxedType() const { +std::string RepeatedImmutableStringFieldLiteGenerator::GetBoxedType() const { return "java.lang.String"; } diff --git a/third_party/protobuf/src/google/protobuf/compiler/java/java_string_field_lite.h b/third_party/protobuf/src/google/protobuf/compiler/java/java_string_field_lite.h index b7fb6409..b67135cd 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/java/java_string_field_lite.h +++ b/third_party/protobuf/src/google/protobuf/compiler/java/java_string_field_lite.h @@ -42,51 +42,43 @@ namespace google { namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } -} +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace java { class ImmutableStringFieldLiteGenerator : public ImmutableFieldLiteGenerator { public: - explicit ImmutableStringFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + explicit ImmutableStringFieldLiteGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, + Context* context); ~ImmutableStringFieldLiteGenerator(); - // implements ImmutableFieldLiteGenerator ------------------------------------ + // implements ImmutableFieldLiteGenerator + // ------------------------------------ int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; void GenerateInterfaceMembers(io::Printer* printer) const; void GenerateMembers(io::Printer* printer) const; void GenerateBuilderMembers(io::Printer* printer) const; void GenerateInitializationCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; + void GenerateFieldInfo(io::Printer* printer, + std::vector* output) const; - - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; ClassNameResolver* name_resolver_; private: @@ -96,19 +88,15 @@ class ImmutableStringFieldLiteGenerator : public ImmutableFieldLiteGenerator { class ImmutableStringOneofFieldLiteGenerator : public ImmutableStringFieldLiteGenerator { public: - ImmutableStringOneofFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + ImmutableStringOneofFieldLiteGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, Context* context); ~ImmutableStringOneofFieldLiteGenerator(); private: void GenerateMembers(io::Printer* printer) const; void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - + void GenerateFieldInfo(io::Printer* printer, + std::vector* output) const; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableStringOneofFieldLiteGenerator); }; @@ -117,36 +105,23 @@ class RepeatedImmutableStringFieldLiteGenerator : public ImmutableFieldLiteGenerator { public: explicit RepeatedImmutableStringFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); + const FieldDescriptor* descriptor, int messageBitIndex, Context* context); ~RepeatedImmutableStringFieldLiteGenerator(); // implements ImmutableFieldLiteGenerator ------------------------------------ int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; void GenerateInterfaceMembers(io::Printer* printer) const; void GenerateMembers(io::Printer* printer) const; void GenerateBuilderMembers(io::Printer* printer) const; void GenerateInitializationCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; + void GenerateFieldInfo(io::Printer* printer, + std::vector* output) const; - - string GetBoxedType() const; + std::string GetBoxedType() const; private: const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; + std::map variables_; ClassNameResolver* name_resolver_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableStringFieldLiteGenerator); @@ -155,6 +130,6 @@ class RepeatedImmutableStringFieldLiteGenerator } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_STRING_FIELD_LITE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/js/js_generator.cc b/third_party/protobuf/src/google/protobuf/compiler/js/js_generator.cc old mode 100755 new mode 100644 index b5771f26..7b12dde9 --- a/third_party/protobuf/src/google/protobuf/compiler/js/js_generator.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/js/js_generator.cc @@ -42,12 +42,14 @@ #include #include #include +#include + +#include #include #include #include #include #include -#include namespace google { @@ -58,64 +60,18 @@ namespace js { // Sorted list of JavaScript keywords. These cannot be used as names. If they // appear, we prefix them with "pb_". const char* kKeyword[] = { - "abstract", - "boolean", - "break", - "byte", - "case", - "catch", - "char", - "class", - "const", - "continue", - "debugger", - "default", - "delete", - "do", - "double", - "else", - "enum", - "export", - "extends", - "false", - "final", - "finally", - "float", - "for", - "function", - "goto", - "if", - "implements", - "import", - "in", - "instanceof", - "int", - "interface", - "long", - "native", - "new", - "null", - "package", - "private", - "protected", - "public", - "return", - "short", - "static", - "super", - "switch", - "synchronized", - "this", - "throw", - "throws", - "transient", - "try", - "typeof", - "var", - "void", - "volatile", - "while", - "with", + "abstract", "boolean", "break", "byte", "case", + "catch", "char", "class", "const", "continue", + "debugger", "default", "delete", "do", "double", + "else", "enum", "export", "extends", "false", + "final", "finally", "float", "for", "function", + "goto", "if", "implements", "import", "in", + "instanceof", "int", "interface", "long", "native", + "new", "null", "package", "private", "protected", + "public", "return", "short", "static", "super", + "switch", "synchronized", "this", "throw", "throws", + "transient", "try", "typeof", "var", "void", + "volatile", "while", "with", }; static const int kNumKeyword = sizeof(kKeyword) / sizeof(char*); @@ -132,7 +88,7 @@ enum BytesMode { BYTES_U8, // Explicitly coerce to Uint8Array where needed. }; -bool IsReserved(const string& ident) { +bool IsReserved(const std::string& ident) { for (int i = 0; i < kNumKeyword; i++) { if (ident == kKeyword[i]) { return true; @@ -148,21 +104,29 @@ bool StrEndsWith(StringPiece sp, StringPiece x) { // Returns a copy of |filename| with any trailing ".protodevel" or ".proto // suffix stripped. // TODO(haberman): Unify with copy in compiler/cpp/internal/helpers.cc. -string StripProto(const string& filename) { +std::string StripProto(const std::string& filename) { const char* suffix = StrEndsWith(filename, ".protodevel") ? ".protodevel" : ".proto"; return StripSuffixString(filename, suffix); } +std::string GetSnakeFilename(const std::string& filename) { + std::string snake_name = filename; + ReplaceCharacters(&snake_name, "/", '_'); + return snake_name; +} + // Given a filename like foo/bar/baz.proto, returns the corresponding JavaScript // file foo/bar/baz.js. -string GetJSFilename(const GeneratorOptions& options, const string& filename) { +std::string GetJSFilename(const GeneratorOptions& options, + const std::string& filename) { return StripProto(filename) + options.GetFileNameExtension(); } // Given a filename like foo/bar/baz.proto, returns the root directory // path ../../ -string GetRootPath(const string& from_filename, const string& to_filename) { +string GetRootPath(const std::string& from_filename, + const std::string& to_filename) { if (to_filename.find("google/protobuf") == 0) { // Well-known types (.proto files in the google/protobuf directory) are // assumed to come from the 'google-protobuf' npm package. We may want to @@ -175,7 +139,7 @@ string GetRootPath(const string& from_filename, const string& to_filename) { if (slashes == 0) { return "./"; } - string result = ""; + std::string result = ""; for (size_t i = 0; i < slashes; i++) { result += "../"; } @@ -184,7 +148,7 @@ string GetRootPath(const string& from_filename, const string& to_filename) { // Returns the alias we assign to the module of the given .proto filename // when importing. -string ModuleAlias(const string& filename) { +std::string ModuleAlias(const std::string& filename) { // This scheme could technically cause problems if a file includes any 2 of: // foo/bar_baz.proto // foo_bar_baz.proto @@ -192,17 +156,17 @@ string ModuleAlias(const string& filename) { // // We'll worry about this problem if/when we actually see it. This name isn't // exposed to users so we can change it later if we need to. - string basename = StripProto(filename); + std::string basename = StripProto(filename); ReplaceCharacters(&basename, "-", '$'); ReplaceCharacters(&basename, "/", '_'); ReplaceCharacters(&basename, ".", '_'); return basename + "_pb"; } -// Returns the fully normalized JavaScript path for the given +// Returns the fully normalized JavaScript namespace for the given // file descriptor's package. -string GetFilePath(const GeneratorOptions& options, - const FileDescriptor* file) { +std::string GetNamespace(const GeneratorOptions& options, + const FileDescriptor* file) { if (!options.namespace_prefix.empty()) { return options.namespace_prefix; } else if (!file->package().empty()) { @@ -216,12 +180,12 @@ string GetFilePath(const GeneratorOptions& options, // nesting, for example ".OuterMessage.InnerMessage", or returns empty if // descriptor is null. This function does not handle namespacing, only message // nesting. -string GetNestedMessageName(const Descriptor* descriptor) { +std::string GetNestedMessageName(const Descriptor* descriptor) { if (descriptor == NULL) { return ""; } - string result = - StripPrefixString(descriptor->full_name(), descriptor->file()->package()); + std::string result = StripPrefixString( + descriptor->full_name(), descriptor->file()->package()); // Add a leading dot if one is not already present. if (!result.empty() && result[0] != '.') { result = "." + result; @@ -231,11 +195,11 @@ string GetNestedMessageName(const Descriptor* descriptor) { // Returns the path prefix for a message or enumeration that // lives under the given file and containing type. -string GetPrefix(const GeneratorOptions& options, - const FileDescriptor* file_descriptor, - const Descriptor* containing_type) { - string prefix = GetFilePath(options, file_descriptor) + - GetNestedMessageName(containing_type); +std::string GetPrefix(const GeneratorOptions& options, + const FileDescriptor* file_descriptor, + const Descriptor* containing_type) { + std::string prefix = GetNamespace(options, file_descriptor) + + GetNestedMessageName(containing_type); if (!prefix.empty()) { prefix += "."; } @@ -244,39 +208,38 @@ string GetPrefix(const GeneratorOptions& options, // Returns the fully normalized JavaScript path prefix for the given // message descriptor. -string GetMessagePathPrefix(const GeneratorOptions& options, - const Descriptor* descriptor) { - return GetPrefix( - options, descriptor->file(), - descriptor->containing_type()); +std::string GetMessagePathPrefix(const GeneratorOptions& options, + const Descriptor* descriptor) { + return GetPrefix(options, descriptor->file(), descriptor->containing_type()); } // Returns the fully normalized JavaScript path for the given // message descriptor. -string GetMessagePath(const GeneratorOptions& options, - const Descriptor* descriptor) { +std::string GetMessagePath(const GeneratorOptions& options, + const Descriptor* descriptor) { return GetMessagePathPrefix(options, descriptor) + descriptor->name(); } // Returns the fully normalized JavaScript path prefix for the given // enumeration descriptor. -string GetEnumPathPrefix(const GeneratorOptions& options, - const EnumDescriptor* enum_descriptor) { +std::string GetEnumPathPrefix(const GeneratorOptions& options, + const EnumDescriptor* enum_descriptor) { return GetPrefix(options, enum_descriptor->file(), - enum_descriptor->containing_type()); + enum_descriptor->containing_type()); } // Returns the fully normalized JavaScript path for the given // enumeration descriptor. -string GetEnumPath(const GeneratorOptions& options, - const EnumDescriptor* enum_descriptor) { +std::string GetEnumPath(const GeneratorOptions& options, + const EnumDescriptor* enum_descriptor) { return GetEnumPathPrefix(options, enum_descriptor) + enum_descriptor->name(); } -string MaybeCrossFileRef(const GeneratorOptions& options, - const FileDescriptor* from_file, - const Descriptor* to_message) { - if (options.import_style == GeneratorOptions::kImportCommonJs && +std::string MaybeCrossFileRef(const GeneratorOptions& options, + const FileDescriptor* from_file, + const Descriptor* to_message) { + if ((options.import_style == GeneratorOptions::kImportCommonJs || + options.import_style == GeneratorOptions::kImportCommonJsStrict) && from_file != to_message->file()) { // Cross-file ref in CommonJS needs to use the module alias instead of // the global name. @@ -289,8 +252,8 @@ string MaybeCrossFileRef(const GeneratorOptions& options, } } -string SubmessageTypeRef(const GeneratorOptions& options, - const FieldDescriptor* field) { +std::string SubmessageTypeRef(const GeneratorOptions& options, + const FieldDescriptor* field) { GOOGLE_CHECK(field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE); return MaybeCrossFileRef(options, field->file(), field->message_type()); } @@ -312,9 +275,9 @@ char ToLowerASCII(char c) { } } -std::vector ParseLowerUnderscore(const string& input) { - std::vector words; - string running = ""; +std::vector ParseLowerUnderscore(const std::string& input) { + std::vector words; + std::string running = ""; for (int i = 0; i < input.size(); i++) { if (input[i] == '_') { if (!running.empty()) { @@ -331,9 +294,9 @@ std::vector ParseLowerUnderscore(const string& input) { return words; } -std::vector ParseUpperCamel(const string& input) { - std::vector words; - string running = ""; +std::vector ParseUpperCamel(const std::string& input) { + std::vector words; + std::string running = ""; for (int i = 0; i < input.size(); i++) { if (input[i] >= 'A' && input[i] <= 'Z' && !running.empty()) { words.push_back(running); @@ -347,10 +310,10 @@ std::vector ParseUpperCamel(const string& input) { return words; } -string ToLowerCamel(const std::vector& words) { - string result; +std::string ToLowerCamel(const std::vector& words) { + std::string result; for (int i = 0; i < words.size(); i++) { - string word = words[i]; + std::string word = words[i]; if (i == 0 && (word[0] >= 'A' && word[0] <= 'Z')) { word[0] = (word[0] - 'A') + 'a'; } else if (i != 0 && (word[0] >= 'a' && word[0] <= 'z')) { @@ -361,10 +324,10 @@ string ToLowerCamel(const std::vector& words) { return result; } -string ToUpperCamel(const std::vector& words) { - string result; +std::string ToUpperCamel(const std::vector& words) { + std::string result; for (int i = 0; i < words.size(); i++) { - string word = words[i]; + std::string word = words[i]; if (word[0] >= 'a' && word[0] <= 'z') { word[0] = (word[0] - 'a') + 'A'; } @@ -376,8 +339,8 @@ string ToUpperCamel(const std::vector& words) { // Based on code from descriptor.cc (Thanks Kenton!) // Uppercases the entire string, turning ValueName into // VALUENAME. -string ToEnumCase(const string& input) { - string result; +std::string ToEnumCase(const std::string& input) { + std::string result; result.reserve(input.size()); for (int i = 0; i < input.size(); i++) { @@ -391,8 +354,8 @@ string ToEnumCase(const string& input) { return result; } -string ToFileName(const string& input) { - string result; +std::string ToLower(const std::string& input) { + std::string result; result.reserve(input.size()); for (int i = 0; i < input.size(); i++) { @@ -406,41 +369,90 @@ string ToFileName(const string& input) { return result; } -// When we're generating one output file per type name, this is the filename +// When we're generating one output file per SCC, this is the filename // that top-level extensions should go in. -string GetExtensionFileName(const GeneratorOptions& options, - const FileDescriptor* file) { - return options.output_dir + "/" + ToFileName(GetFilePath(options, file)) + +// e.g. one proto file (test.proto): +// package a; +// extends Foo { +// ... +// } +// If "with_filename" equals true, the extension filename will be +// "proto.a_test_extensions.js", otherwise will be "proto.a.js" +std::string GetExtensionFileName(const GeneratorOptions& options, + const FileDescriptor* file, + bool with_filename) { + std::string snake_name = StripProto(GetSnakeFilename(file->name())); + return options.output_dir + "/" + ToLower(GetNamespace(options, file)) + + (with_filename ? ("_" + snake_name + "_extensions") : "") + + options.GetFileNameExtension(); +} +// When we're generating one output file per SCC, this is the filename +// that all messages in the SCC should go in. +// If with_package equals true, filename will have package prefix, +// If the filename length is longer than 200, the filename will be the +// SCC's proto filename with suffix "_long_sccs_(index)" (if with_package equals +// true it still has package prefix) +std::string GetMessagesFileName(const GeneratorOptions& options, const SCC* scc, + bool with_package) { + static std::map* long_name_dict = + new std::map(); + std::string package_base = + with_package + ? ToLower(GetNamespace(options, scc->GetRepresentative()->file()) + + "_") + : ""; + std::string filename_base = ""; + std::vector all_message_names; + for (auto one_desc : scc->descriptors) { + if (one_desc->containing_type() == nullptr) { + all_message_names.push_back(ToLower(one_desc->name())); + } + } + sort(all_message_names.begin(), all_message_names.end()); + for (auto one_message : all_message_names) { + if (!filename_base.empty()) { + filename_base += "_"; + } + filename_base += one_message; + } + if (filename_base.size() + package_base.size() > 200) { + if ((*long_name_dict).find(scc->GetRepresentative()) == + (*long_name_dict).end()) { + std::string snake_name = StripProto( + GetSnakeFilename(scc->GetRepresentative()->file()->name())); + (*long_name_dict)[scc->GetRepresentative()] = + StrCat(snake_name, "_long_sccs_", + static_cast((*long_name_dict).size())); + } + filename_base = (*long_name_dict)[scc->GetRepresentative()]; + } + return options.output_dir + "/" + package_base + filename_base + options.GetFileNameExtension(); } // When we're generating one output file per type name, this is the filename -// that a top-level message should go in. -string GetMessageFileName(const GeneratorOptions& options, - const Descriptor* desc) { - return options.output_dir + "/" + ToFileName(desc->name()) + - options.GetFileNameExtension(); -} - -// When we're generating one output file per type name, this is the filename -// that a top-level message should go in. -string GetEnumFileName(const GeneratorOptions& options, - const EnumDescriptor* desc) { - return options.output_dir + "/" + ToFileName(desc->name()) + - options.GetFileNameExtension(); +// that a top-level enum should go in. +// If with_package equals true, filename will have package prefix. +std::string GetEnumFileName(const GeneratorOptions& options, + const EnumDescriptor* desc, bool with_package) { + return options.output_dir + "/" + + (with_package ? ToLower(GetNamespace(options, desc->file()) + "_") + : "") + + ToLower(desc->name()) + options.GetFileNameExtension(); } // Returns the message/response ID, if set. -string GetMessageId(const Descriptor* desc) { - return string(); +std::string GetMessageId(const Descriptor* desc) { + return std::string(); } bool IgnoreExtensionField(const FieldDescriptor* field) { // Exclude descriptor extensions from output "to avoid clutter" (from original // codegen). - return field->is_extension() && - field->containing_type()->file()->name() == - "google/protobuf/descriptor.proto"; + if (!field->is_extension()) return false; + const FileDescriptor* file = field->containing_type()->file(); + return file->name() == "net/proto2/proto/descriptor.proto" || + file->name() == "google/protobuf/descriptor.proto"; } @@ -452,20 +464,8 @@ bool IgnoreField(const FieldDescriptor* field) { } -// Used inside Google only -- do not remove. -bool ShouldTreatMapsAsRepeatedFields(const FileDescriptor& descriptor) { - return false; -} - // Do we ignore this message type? -bool IgnoreMessage(const GeneratorOptions& options, const Descriptor* d) { - return d->options().map_entry() && - !ShouldTreatMapsAsRepeatedFields(*d->file()); -} - -bool IsMap(const GeneratorOptions& options, const FieldDescriptor* field) { - return field->is_map() && !ShouldTreatMapsAsRepeatedFields(*field->file()); -} +bool IgnoreMessage(const Descriptor* d) { return d->options().map_entry(); } // Does JSPB ignore this entire oneof? True only if all fields are ignored. bool IgnoreOneof(const OneofDescriptor* oneof) { @@ -477,19 +477,19 @@ bool IgnoreOneof(const OneofDescriptor* oneof) { return true; } -string JSIdent(const GeneratorOptions& options, const FieldDescriptor* field, - bool is_upper_camel, bool is_map, bool drop_list) { - string result; +std::string JSIdent(const GeneratorOptions& options, + const FieldDescriptor* field, bool is_upper_camel, + bool is_map, bool drop_list) { + std::string result; if (field->type() == FieldDescriptor::TYPE_GROUP) { - result = is_upper_camel ? - ToUpperCamel(ParseUpperCamel(field->message_type()->name())) : - ToLowerCamel(ParseUpperCamel(field->message_type()->name())); + result = is_upper_camel + ? ToUpperCamel(ParseUpperCamel(field->message_type()->name())) + : ToLowerCamel(ParseUpperCamel(field->message_type()->name())); } else { - result = is_upper_camel ? - ToUpperCamel(ParseLowerUnderscore(field->name())) : - ToLowerCamel(ParseLowerUnderscore(field->name())); + result = is_upper_camel ? ToUpperCamel(ParseLowerUnderscore(field->name())) + : ToLowerCamel(ParseLowerUnderscore(field->name())); } - if (is_map || IsMap(options, field)) { + if (is_map || field->is_map()) { // JSPB-style or proto3-style map. result += "Map"; } else if (!drop_list && field->is_repeated()) { @@ -499,19 +499,19 @@ string JSIdent(const GeneratorOptions& options, const FieldDescriptor* field, return result; } -string JSObjectFieldName(const GeneratorOptions& options, - const FieldDescriptor* field) { - string name = JSIdent(options, field, - /* is_upper_camel = */ false, - /* is_map = */ false, - /* drop_list = */ false); +std::string JSObjectFieldName(const GeneratorOptions& options, + const FieldDescriptor* field) { + std::string name = JSIdent(options, field, + /* is_upper_camel = */ false, + /* is_map = */ false, + /* drop_list = */ false); if (IsReserved(name)) { name = "pb_" + name; } return name; } -string JSByteGetterSuffix(BytesMode bytes_mode) { +std::string JSByteGetterSuffix(BytesMode bytes_mode) { switch (bytes_mode) { case BYTES_DEFAULT: return ""; @@ -527,15 +527,15 @@ string JSByteGetterSuffix(BytesMode bytes_mode) { // Returns the field name as a capitalized portion of a getter/setter method // name, e.g. MyField for .getMyField(). -string JSGetterName(const GeneratorOptions& options, - const FieldDescriptor* field, - BytesMode bytes_mode = BYTES_DEFAULT, - bool drop_list = false) { - string name = JSIdent(options, field, - /* is_upper_camel = */ true, - /* is_map = */ false, drop_list); +std::string JSGetterName(const GeneratorOptions& options, + const FieldDescriptor* field, + BytesMode bytes_mode = BYTES_DEFAULT, + bool drop_list = false) { + std::string name = JSIdent(options, field, + /* is_upper_camel = */ true, + /* is_map = */ false, drop_list); if (field->type() == FieldDescriptor::TYPE_BYTES) { - string suffix = JSByteGetterSuffix(bytes_mode); + std::string suffix = JSByteGetterSuffix(bytes_mode); if (!suffix.empty()) { name += "_as" + suffix; } @@ -548,14 +548,13 @@ string JSGetterName(const GeneratorOptions& options, } - -string JSOneofName(const OneofDescriptor* oneof) { +std::string JSOneofName(const OneofDescriptor* oneof) { return ToUpperCamel(ParseLowerUnderscore(oneof->name())); } // Returns the index corresponding to this field in the JSPB array (underlying // data storage array). -string JSFieldIndex(const FieldDescriptor* field) { +std::string JSFieldIndex(const FieldDescriptor* field) { // Determine whether this field is a member of a group. Group fields are a bit // wonky: their "containing type" is a message type created just for the // group, and that type's parent type has a field with the group-message type @@ -568,14 +567,14 @@ string JSFieldIndex(const FieldDescriptor* field) { for (int i = 0; i < parent_type->field_count(); i++) { if (parent_type->field(i)->type() == FieldDescriptor::TYPE_GROUP && parent_type->field(i)->message_type() == containing_type) { - return SimpleItoa(field->number() - parent_type->field(i)->number()); + return StrCat(field->number() - parent_type->field(i)->number()); } } } - return SimpleItoa(field->number()); + return StrCat(field->number()); } -string JSOneofIndex(const OneofDescriptor* oneof) { +std::string JSOneofIndex(const OneofDescriptor* oneof) { int index = -1; for (int i = 0; i < oneof->containing_type()->oneof_decl_count(); i++) { const OneofDescriptor* o = oneof->containing_type()->oneof_decl(i); @@ -591,7 +590,7 @@ string JSOneofIndex(const OneofDescriptor* oneof) { break; } } - return SimpleItoa(index); + return StrCat(index); } // Decodes a codepoint in \x0000 -- \xFFFF. @@ -620,13 +619,15 @@ uint16 DecodeUTF8Codepoint(uint8* bytes, size_t* length) { *length = expected; switch (expected) { - case 1: return bytes[0]; - case 2: return ((bytes[0] & 0x1F) << 6) | - ((bytes[1] & 0x3F) << 0); - case 3: return ((bytes[0] & 0x0F) << 12) | - ((bytes[1] & 0x3F) << 6) | - ((bytes[2] & 0x3F) << 0); - default: return 0; + case 1: + return bytes[0]; + case 2: + return ((bytes[0] & 0x1F) << 6) | ((bytes[1] & 0x3F) << 0); + case 3: + return ((bytes[0] & 0x0F) << 12) | ((bytes[1] & 0x3F) << 6) | + ((bytes[2] & 0x3F) << 0); + default: + return 0; } } @@ -634,8 +635,8 @@ uint16 DecodeUTF8Codepoint(uint8* bytes, size_t* length) { // JavaScript. The input data should be a UTF-8 encoded C++ string of chars. // Returns false if |out| was truncated because |in| contained invalid UTF-8 or // codepoints outside the BMP. -// TODO(lukestebbing): Support codepoints outside the BMP. -bool EscapeJSString(const string& in, string* out) { +// TODO(b/115551870): Support codepoints outside the BMP. +bool EscapeJSString(const std::string& in, std::string* out) { size_t decoded = 0; for (size_t i = 0; i < in.size(); i += decoded) { uint16 codepoint = 0; @@ -653,20 +654,44 @@ bool EscapeJSString(const string& in, string* out) { decoded = have_bytes; switch (codepoint) { - case '\'': *out += "\\x27"; break; - case '"': *out += "\\x22"; break; - case '<': *out += "\\x3c"; break; - case '=': *out += "\\x3d"; break; - case '>': *out += "\\x3e"; break; - case '&': *out += "\\x26"; break; - case '\b': *out += "\\b"; break; - case '\t': *out += "\\t"; break; - case '\n': *out += "\\n"; break; - case '\f': *out += "\\f"; break; - case '\r': *out += "\\r"; break; - case '\\': *out += "\\\\"; break; + case '\'': + *out += "\\x27"; + break; + case '"': + *out += "\\x22"; + break; + case '<': + *out += "\\x3c"; + break; + case '=': + *out += "\\x3d"; + break; + case '>': + *out += "\\x3e"; + break; + case '&': + *out += "\\x26"; + break; + case '\b': + *out += "\\b"; + break; + case '\t': + *out += "\\t"; + break; + case '\n': + *out += "\\n"; + break; + case '\f': + *out += "\\f"; + break; + case '\r': + *out += "\\r"; + break; + case '\\': + *out += "\\\\"; + break; default: - // TODO(lukestebbing): Once we're supporting codepoints outside the BMP, + // TODO(b/115551870): Once we're supporting codepoints outside the BMP, // use a single Unicode codepoint escape if the output language is // ECMAScript 2015 or above. Otherwise, use a surrogate pair. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals @@ -683,24 +708,23 @@ bool EscapeJSString(const string& in, string* out) { return true; } -string EscapeBase64(const string& in) { +std::string EscapeBase64(const std::string& in) { static const char* kAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - string result; + std::string result; for (size_t i = 0; i < in.size(); i += 3) { - int value = (in[i] << 16) | - (((i + 1) < in.size()) ? (in[i + 1] << 8) : 0) | - (((i + 2) < in.size()) ? (in[i + 2] << 0) : 0); + int value = (in[i] << 16) | (((i + 1) < in.size()) ? (in[i + 1] << 8) : 0) | + (((i + 2) < in.size()) ? (in[i + 2] << 0) : 0); result += kAlphabet[(value >> 18) & 0x3f]; result += kAlphabet[(value >> 12) & 0x3f]; if ((i + 1) < in.size()) { - result += kAlphabet[(value >> 6) & 0x3f]; + result += kAlphabet[(value >> 6) & 0x3f]; } else { result += '='; } if ((i + 2) < in.size()) { - result += kAlphabet[(value >> 0) & 0x3f]; + result += kAlphabet[(value >> 0) & 0x3f]; } else { result += '='; } @@ -712,7 +736,7 @@ string EscapeBase64(const string& in) { // Post-process the result of SimpleFtoa/SimpleDtoa to *exactly* match the // original codegen's formatting (which is just .toString() on java.lang.Double // or java.lang.Float). -string PostProcessFloat(string result) { +std::string PostProcessFloat(std::string result) { // If inf, -inf or nan, replace with +Infinity, -Infinity or NaN. if (result == "inf") { return "Infinity"; @@ -726,13 +750,13 @@ string PostProcessFloat(string result) { // ensure that the mantissa (portion prior to the "e") has at least one // fractional digit (after the decimal point), and (iii) strip any unnecessary // leading zeroes and/or '+' signs from the exponent. - string::size_type exp_pos = result.find('e'); - if (exp_pos != string::npos) { - string mantissa = result.substr(0, exp_pos); - string exponent = result.substr(exp_pos + 1); + std::string::size_type exp_pos = result.find('e'); + if (exp_pos != std::string::npos) { + std::string mantissa = result.substr(0, exp_pos); + std::string exponent = result.substr(exp_pos + 1); // Add ".0" to mantissa if no fractional part exists. - if (mantissa.find('.') == string::npos) { + if (mantissa.find('.') == std::string::npos) { mantissa += ".0"; } @@ -755,20 +779,20 @@ string PostProcessFloat(string result) { // Otherwise, this is an ordinary decimal number. Append ".0" if result has no // decimal/fractional part in order to match output of original codegen. - if (result.find('.') == string::npos) { + if (result.find('.') == std::string::npos) { result += ".0"; } return result; } -string FloatToString(float value) { - string result = SimpleFtoa(value); +std::string FloatToString(float value) { + std::string result = SimpleFtoa(value); return PostProcessFloat(result); } -string DoubleToString(double value) { - string result = SimpleDtoa(value); +std::string DoubleToString(double value) { + std::string result = SimpleDtoa(value); return PostProcessFloat(result); } @@ -780,40 +804,43 @@ bool IsIntegralFieldWithStringJSType(const FieldDescriptor* field) { case FieldDescriptor::CPPTYPE_UINT64: // The default value of JSType is JS_NORMAL, which behaves the same as // JS_NUMBER. - return field->options().jstype() == google::protobuf::FieldOptions::JS_STRING; + return field->options().jstype() == FieldOptions::JS_STRING; default: return false; } } -string MaybeNumberString(const FieldDescriptor* field, const string& orig) { +std::string MaybeNumberString(const FieldDescriptor* field, + const std::string& orig) { return IsIntegralFieldWithStringJSType(field) ? ("\"" + orig + "\"") : orig; } -string JSFieldDefault(const FieldDescriptor* field) { +std::string JSFieldDefault(const FieldDescriptor* field) { if (field->is_repeated()) { return "[]"; } switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_INT32: - return MaybeNumberString( - field, SimpleItoa(field->default_value_int32())); + return MaybeNumberString(field, + StrCat(field->default_value_int32())); case FieldDescriptor::CPPTYPE_UINT32: // The original codegen is in Java, and Java protobufs store unsigned // integer values as signed integer values. In order to exactly match the // output, we need to reinterpret as base-2 signed. Ugh. return MaybeNumberString( - field, SimpleItoa(static_cast(field->default_value_uint32()))); + field, + StrCat(static_cast(field->default_value_uint32()))); case FieldDescriptor::CPPTYPE_INT64: - return MaybeNumberString( - field, SimpleItoa(field->default_value_int64())); + return MaybeNumberString(field, + StrCat(field->default_value_int64())); case FieldDescriptor::CPPTYPE_UINT64: // See above note for uint32 -- reinterpreting as signed. return MaybeNumberString( - field, SimpleItoa(static_cast(field->default_value_uint64()))); + field, + StrCat(static_cast(field->default_value_uint64()))); case FieldDescriptor::CPPTYPE_ENUM: - return SimpleItoa(field->default_value_enum()->number()); + return StrCat(field->default_value_enum()->number()); case FieldDescriptor::CPPTYPE_BOOL: return field->default_value_bool() ? "true" : "false"; case FieldDescriptor::CPPTYPE_FLOAT: @@ -822,10 +849,10 @@ string JSFieldDefault(const FieldDescriptor* field) { return DoubleToString(field->default_value_double()); case FieldDescriptor::CPPTYPE_STRING: if (field->type() == FieldDescriptor::TYPE_STRING) { - string out; + std::string out; bool is_valid = EscapeJSString(field->default_value_string(), &out); if (!is_valid) { - // TODO(lukestebbing): Decide whether this should be a hard error. + // TODO(b/115551870): Decide whether this should be a hard error. GOOGLE_LOG(WARNING) << "The default value for field " << field->full_name() << " was truncated since it contained invalid UTF-8 or" " codepoints outside the basic multilingual plane."; @@ -841,8 +868,8 @@ string JSFieldDefault(const FieldDescriptor* field) { return ""; } -string ProtoTypeName(const GeneratorOptions& options, - const FieldDescriptor* field) { +std::string ProtoTypeName(const GeneratorOptions& options, + const FieldDescriptor* field) { switch (field->type()) { case FieldDescriptor::TYPE_BOOL: return "bool"; @@ -885,13 +912,13 @@ string ProtoTypeName(const GeneratorOptions& options, } } -string JSIntegerTypeName(const FieldDescriptor* field) { +std::string JSIntegerTypeName(const FieldDescriptor* field) { return IsIntegralFieldWithStringJSType(field) ? "string" : "number"; } -string JSStringTypeName(const GeneratorOptions& options, - const FieldDescriptor* field, - BytesMode bytes_mode) { +std::string JSStringTypeName(const GeneratorOptions& options, + const FieldDescriptor* field, + BytesMode bytes_mode) { if (field->type() == FieldDescriptor::TYPE_BYTES) { switch (bytes_mode) { case BYTES_DEFAULT: @@ -907,9 +934,8 @@ string JSStringTypeName(const GeneratorOptions& options, return "string"; } -string JSTypeName(const GeneratorOptions& options, - const FieldDescriptor* field, - BytesMode bytes_mode) { +std::string JSTypeName(const GeneratorOptions& options, + const FieldDescriptor* field, BytesMode bytes_mode) { switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_BOOL: return "boolean"; @@ -943,8 +969,8 @@ bool UseBrokenPresenceSemantics(const GeneratorOptions& options, } // Returns true for fields that return "null" from accessors when they are -// unset. This should normally only be true for non-repeated submessages, but -// we have legacy users who relied on old behavior where accessors behaved this +// unset. This should normally only be true for non-repeated submessages, but we +// have legacy users who relied on old behavior where accessors behaved this // way. bool ReturnsNullWhenUnset(const GeneratorOptions& options, const FieldDescriptor* field) { @@ -1003,21 +1029,20 @@ bool SetterAcceptsNull(const GeneratorOptions& options, // Returns types which are known to by non-nullable by default. // The style guide requires that we omit "!" in this case. -bool IsPrimitive(const string& type) { +bool IsPrimitive(const std::string& type) { return type == "undefined" || type == "string" || type == "number" || type == "boolean"; } -string JSFieldTypeAnnotation(const GeneratorOptions& options, - const FieldDescriptor* field, - bool is_setter_argument, - bool force_present, - bool singular_if_not_packed, - BytesMode bytes_mode = BYTES_DEFAULT) { - GOOGLE_CHECK(!(is_setter_argument && force_present)); - string jstype = JSTypeName(options, field, bytes_mode); +std::string JSFieldTypeAnnotation(const GeneratorOptions& options, + const FieldDescriptor* field, + bool is_setter_argument, bool force_present, + bool singular_if_not_packed, + BytesMode bytes_mode = BYTES_DEFAULT, + bool force_singular = false) { + std::string jstype = JSTypeName(options, field, bytes_mode); - if (field->is_repeated() && + if (!force_singular && field->is_repeated() && (field->is_packed() || !singular_if_not_packed)) { if (field->type() == FieldDescriptor::TYPE_BYTES && bytes_mode == BYTES_DEFAULT) { @@ -1058,17 +1083,17 @@ string JSFieldTypeAnnotation(const GeneratorOptions& options, return jstype; } -string JSBinaryReaderMethodType(const FieldDescriptor* field) { - string name = field->type_name(); +std::string JSBinaryReaderMethodType(const FieldDescriptor* field) { + std::string name = field->type_name(); if (name[0] >= 'a' && name[0] <= 'z') { name[0] = (name[0] - 'a') + 'A'; } return IsIntegralFieldWithStringJSType(field) ? (name + "String") : name; } -string JSBinaryReadWriteMethodName(const FieldDescriptor* field, - bool is_writer) { - string name = JSBinaryReaderMethodType(field); +std::string JSBinaryReadWriteMethodName(const FieldDescriptor* field, + bool is_writer) { + std::string name = JSBinaryReaderMethodType(field); if (field->is_packed()) { name = "Packed" + name; } else if (is_writer && field->is_repeated()) { @@ -1077,23 +1102,27 @@ string JSBinaryReadWriteMethodName(const FieldDescriptor* field, return name; } -string JSBinaryReaderMethodName(const GeneratorOptions& options, - const FieldDescriptor* field) { +std::string JSBinaryReaderMethodName(const GeneratorOptions& options, + const FieldDescriptor* field) { return "jspb.BinaryReader.prototype.read" + JSBinaryReadWriteMethodName(field, /* is_writer = */ false); } -string JSBinaryWriterMethodName(const GeneratorOptions& options, - const FieldDescriptor* field) { +std::string JSBinaryWriterMethodName(const GeneratorOptions& options, + const FieldDescriptor* field) { + if (field->containing_type() && + field->containing_type()->options().message_set_wire_format()) { + return "jspb.BinaryWriter.prototype.writeMessageSet"; + } return "jspb.BinaryWriter.prototype.write" + JSBinaryReadWriteMethodName(field, /* is_writer = */ true); } -string JSReturnClause(const FieldDescriptor* desc) { +std::string JSReturnClause(const FieldDescriptor* desc) { return ""; } -string JSTypeTag(const FieldDescriptor* desc) { +std::string JSTypeTag(const FieldDescriptor* desc) { switch (desc->type()) { case FieldDescriptor::TYPE_DOUBLE: case FieldDescriptor::TYPE_FLOAT: @@ -1127,15 +1156,15 @@ string JSTypeTag(const FieldDescriptor* desc) { return ""; } -string JSReturnDoc(const GeneratorOptions& options, - const FieldDescriptor* desc) { +std::string JSReturnDoc(const GeneratorOptions& options, + const FieldDescriptor* desc) { return ""; } bool HasRepeatedFields(const GeneratorOptions& options, const Descriptor* desc) { for (int i = 0; i < desc->field_count(); i++) { - if (desc->field(i)->is_repeated() && !IsMap(options, desc->field(i))) { + if (desc->field(i)->is_repeated() && !desc->field(i)->is_map()) { return true; } } @@ -1144,8 +1173,8 @@ bool HasRepeatedFields(const GeneratorOptions& options, static const char* kRepeatedFieldArrayName = ".repeatedFields_"; -string RepeatedFieldsArrayName(const GeneratorOptions& options, - const Descriptor* desc) { +std::string RepeatedFieldsArrayName(const GeneratorOptions& options, + const Descriptor* desc) { return HasRepeatedFields(options, desc) ? (GetMessagePath(options, desc) + kRepeatedFieldArrayName) : "null"; @@ -1162,34 +1191,34 @@ bool HasOneofFields(const Descriptor* desc) { static const char* kOneofGroupArrayName = ".oneofGroups_"; -string OneofFieldsArrayName(const GeneratorOptions& options, - const Descriptor* desc) { +std::string OneofFieldsArrayName(const GeneratorOptions& options, + const Descriptor* desc) { return HasOneofFields(desc) ? (GetMessagePath(options, desc) + kOneofGroupArrayName) : "null"; } -string RepeatedFieldNumberList(const GeneratorOptions& options, - const Descriptor* desc) { - std::vector numbers; +std::string RepeatedFieldNumberList(const GeneratorOptions& options, + const Descriptor* desc) { + std::vector numbers; for (int i = 0; i < desc->field_count(); i++) { - if (desc->field(i)->is_repeated() && !IsMap(options, desc->field(i))) { + if (desc->field(i)->is_repeated() && !desc->field(i)->is_map()) { numbers.push_back(JSFieldIndex(desc->field(i))); } } return "[" + Join(numbers, ",") + "]"; } -string OneofGroupList(const Descriptor* desc) { +std::string OneofGroupList(const Descriptor* desc) { // List of arrays (one per oneof), each of which is a list of field indices - std::vector oneof_entries; + std::vector oneof_entries; for (int i = 0; i < desc->oneof_decl_count(); i++) { const OneofDescriptor* oneof = desc->oneof_decl(i); if (IgnoreOneof(oneof)) { continue; } - std::vector oneof_fields; + std::vector oneof_fields; for (int j = 0; j < oneof->field_count(); j++) { if (IgnoreField(oneof->field(j))) { continue; @@ -1201,21 +1230,22 @@ string OneofGroupList(const Descriptor* desc) { return "[" + Join(oneof_entries, ",") + "]"; } -string JSOneofArray(const GeneratorOptions& options, - const FieldDescriptor* field) { +std::string JSOneofArray(const GeneratorOptions& options, + const FieldDescriptor* field) { return OneofFieldsArrayName(options, field->containing_type()) + "[" + - JSOneofIndex(field->containing_oneof()) + "]"; + JSOneofIndex(field->containing_oneof()) + "]"; } -string RelativeTypeName(const FieldDescriptor* field) { +std::string RelativeTypeName(const FieldDescriptor* field) { assert(field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM || field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE); // For a field with an enum or message type, compute a name relative to the // path name of the message type containing this field. - string package = field->file()->package(); - string containing_type = field->containing_type()->full_name() + "."; - string type = (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) ? - field->enum_type()->full_name() : field->message_type()->full_name(); + std::string package = field->file()->package(); + std::string containing_type = field->containing_type()->full_name() + "."; + std::string type = (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) + ? field->enum_type()->full_name() + : field->message_type()->full_name(); // |prefix| is advanced as we find separators '.' past the common package // prefix that yield common prefixes in the containing type's name and this @@ -1233,9 +1263,9 @@ string RelativeTypeName(const FieldDescriptor* field) { return type.substr(prefix); } -string JSExtensionsObjectName(const GeneratorOptions& options, - const FileDescriptor* from_file, - const Descriptor* desc) { +std::string JSExtensionsObjectName(const GeneratorOptions& options, + const FileDescriptor* from_file, + const Descriptor* desc) { if (desc->full_name() == "google.protobuf.bridge.MessageSet") { // TODO(haberman): fix this for the kImportCommonJs case. return "jspb.Message.messageSetExtensions"; @@ -1257,28 +1287,27 @@ const FieldDescriptor* MapFieldValue(const FieldDescriptor* field) { return field->message_type()->FindFieldByNumber(kMapValueField); } -string FieldDefinition(const GeneratorOptions& options, - const FieldDescriptor* field) { - if (IsMap(options, field)) { +std::string FieldDefinition(const GeneratorOptions& options, + const FieldDescriptor* field) { + if (field->is_map()) { const FieldDescriptor* key_field = MapFieldKey(field); const FieldDescriptor* value_field = MapFieldValue(field); - string key_type = ProtoTypeName(options, key_field); - string value_type; + std::string key_type = ProtoTypeName(options, key_field); + std::string value_type; if (value_field->type() == FieldDescriptor::TYPE_ENUM || value_field->type() == FieldDescriptor::TYPE_MESSAGE) { value_type = RelativeTypeName(value_field); } else { value_type = ProtoTypeName(options, value_field); } - return StringPrintf("map<%s, %s> %s = %d;", - key_type.c_str(), - value_type.c_str(), - field->name().c_str(), + return StringPrintf("map<%s, %s> %s = %d;", key_type.c_str(), + value_type.c_str(), field->name().c_str(), field->number()); } else { - string qualifier = field->is_repeated() ? "repeated" : - (field->is_optional() ? "optional" : "required"); - string type, name; + std::string qualifier = + field->is_repeated() ? "repeated" + : (field->is_optional() ? "optional" : "required"); + std::string type, name; if (field->type() == FieldDescriptor::TYPE_ENUM || field->type() == FieldDescriptor::TYPE_MESSAGE) { type = RelativeTypeName(field); @@ -1290,23 +1319,13 @@ string FieldDefinition(const GeneratorOptions& options, type = ProtoTypeName(options, field); name = field->name(); } - return StringPrintf("%s %s %s = %d;", - qualifier.c_str(), - type.c_str(), - name.c_str(), - field->number()); + return StringPrintf("%s %s %s = %d;", qualifier.c_str(), type.c_str(), + name.c_str(), field->number()); } } -string FieldComments(const FieldDescriptor* field, BytesMode bytes_mode) { - string comments; - if (field->cpp_type() == FieldDescriptor::CPPTYPE_BOOL) { - comments += - " * Note that Boolean fields may be set to 0/1 when serialized from " - "a Java server.\n" - " * You should avoid comparisons like {@code val === true/false} in " - "those cases.\n"; - } +std::string FieldComments(const FieldDescriptor* field, BytesMode bytes_mode) { + std::string comments; if (field->type() == FieldDescriptor::TYPE_BYTES && bytes_mode == BYTES_U8) { comments += " * Note that Uint8Array is not supported on all browsers.\n" @@ -1316,9 +1335,7 @@ string FieldComments(const FieldDescriptor* field, BytesMode bytes_mode) { } bool ShouldGenerateExtension(const FieldDescriptor* field) { - return - field->is_extension() && - !IgnoreField(field); + return field->is_extension() && !IgnoreField(field); } bool HasExtensions(const Descriptor* desc) { @@ -1351,7 +1368,7 @@ bool HasExtensions(const FileDescriptor* file) { bool HasMap(const GeneratorOptions& options, const Descriptor* desc) { for (int i = 0; i < desc->field_count(); i++) { - if (IsMap(options, desc->field(i))) { + if (desc->field(i)->is_map()) { return true; } } @@ -1378,7 +1395,7 @@ bool IsExtendable(const Descriptor* desc) { // Returns the max index in the underlying data storage array beyond which the // extension object is used. -string GetPivot(const Descriptor* desc) { +std::string GetPivot(const Descriptor* desc) { static const int kDefaultPivot = 500; // Find the max field number @@ -1392,11 +1409,11 @@ string GetPivot(const Descriptor* desc) { int pivot = -1; if (IsExtendable(desc) || (max_field_number >= kDefaultPivot)) { - pivot = ((max_field_number + 1) < kDefaultPivot) ? - (max_field_number + 1) : kDefaultPivot; + pivot = ((max_field_number + 1) < kDefaultPivot) ? (max_field_number + 1) + : kDefaultPivot; } - return SimpleItoa(pivot); + return StrCat(pivot); } // Whether this field represents presence. For fields with presence, we @@ -1420,37 +1437,56 @@ bool HasFieldPresence(const GeneratorOptions& options, } // We use this to implement the semantics that same file can be generated -// multiple times, but the last one wins. We never actually write the files, -// but we keep a set of which descriptors were the final one for a given -// filename. +// multiple times, but only the last one keep the short name. Others all use +// long name with extra information to distinguish (For message and enum, the +// extra information is package name, for file level extension, the extra +// information is proto's filename). +// We never actually write the files, but we keep a set of which descriptors +// were the final one for a given filename. class FileDeduplicator { public: explicit FileDeduplicator(const GeneratorOptions& options) : error_on_conflict_(options.error_on_name_conflict) {} - bool AddFile(const string& filename, const void* desc, string* error) { - if (descs_by_filename_.find(filename) != descs_by_filename_.end()) { + // params: + // filenames: a pair of {short filename, full filename} + // (short filename don't have extra information, full filename + // contains extra information) + // desc: The Descriptor or SCC pointer or EnumDescriptor. + // error: The returned error information. + bool AddFile(const std::pair filenames, + const void* desc, std::string* error) { + if (descs_by_shortname_.find(filenames.first) != + descs_by_shortname_.end()) { if (error_on_conflict_) { - *error = "Name conflict: file name " + filename + + *error = "Name conflict: file name " + filenames.first + " would be generated by two descriptors"; return false; } - allowed_descs_.erase(descs_by_filename_[filename]); + // Change old pointer's actual name to full name. + auto short_name_desc = descs_by_shortname_[filenames.first]; + allowed_descs_actual_name_[short_name_desc] = + allowed_descs_full_name_[short_name_desc]; } + descs_by_shortname_[filenames.first] = desc; + allowed_descs_actual_name_[desc] = filenames.first; + allowed_descs_full_name_[desc] = filenames.second; - descs_by_filename_[filename] = desc; - allowed_descs_.insert(desc); return true; } - void GetAllowedSet(std::set* allowed_set) { - *allowed_set = allowed_descs_; + void GetAllowedMap(std::map* allowed_set) { + *allowed_set = allowed_descs_actual_name_; } private: bool error_on_conflict_; - std::map descs_by_filename_; - std::set allowed_descs_; + // The map that restores all the descs that are using short name as filename. + std::map descs_by_shortname_; + // The final actual filename map. + std::map allowed_descs_actual_name_; + // The full name map. + std::map allowed_descs_full_name_; }; void DepthFirstSearch(const FileDescriptor* file, @@ -1511,25 +1547,58 @@ void GenerateJspbFileOrder(const std::vector& input, // by choosing the last descriptor that writes each filename and permitting // only those to generate code. -bool GenerateJspbAllowedSet(const GeneratorOptions& options, +struct DepsGenerator { + std::vector operator()(const Descriptor* desc) const { + std::vector deps; + auto maybe_add = [&](const Descriptor* d) { + if (d) deps.push_back(d); + }; + for (int i = 0; i < desc->field_count(); i++) { + if (!IgnoreField(desc->field(i))) { + maybe_add(desc->field(i)->message_type()); + } + } + for (int i = 0; i < desc->extension_count(); i++) { + maybe_add(desc->extension(i)->message_type()); + maybe_add(desc->extension(i)->containing_type()); + } + for (int i = 0; i < desc->nested_type_count(); i++) { + maybe_add(desc->nested_type(i)); + } + maybe_add(desc->containing_type()); + + return deps; + } +}; + +bool GenerateJspbAllowedMap(const GeneratorOptions& options, const std::vector& files, - std::set* allowed_set, - string* error) { + std::map* allowed_set, + SCCAnalyzer* analyzer, + std::string* error) { std::vector files_ordered; GenerateJspbFileOrder(files, &files_ordered); // Choose the last descriptor for each filename. FileDeduplicator dedup(options); + std::set added; for (int i = 0; i < files_ordered.size(); i++) { for (int j = 0; j < files_ordered[i]->message_type_count(); j++) { const Descriptor* desc = files_ordered[i]->message_type(j); - if (!dedup.AddFile(GetMessageFileName(options, desc), desc, error)) { + if (added.insert(analyzer->GetSCC(desc)).second && + !dedup.AddFile( + std::make_pair( + GetMessagesFileName(options, analyzer->GetSCC(desc), false), + GetMessagesFileName(options, analyzer->GetSCC(desc), true)), + analyzer->GetSCC(desc), error)) { return false; } } for (int j = 0; j < files_ordered[i]->enum_type_count(); j++) { const EnumDescriptor* desc = files_ordered[i]->enum_type(j); - if (!dedup.AddFile(GetEnumFileName(options, desc), desc, error)) { + if (!dedup.AddFile(std::make_pair(GetEnumFileName(options, desc, false), + GetEnumFileName(options, desc, true)), + desc, error)) { return false; } } @@ -1544,14 +1613,17 @@ bool GenerateJspbAllowedSet(const GeneratorOptions& options, } if (has_extension) { - if (!dedup.AddFile(GetExtensionFileName(options, files_ordered[i]), - files_ordered[i], error)) { + if (!dedup.AddFile( + std::make_pair( + GetExtensionFileName(options, files_ordered[i], false), + GetExtensionFileName(options, files_ordered[i], true)), + files_ordered[i], error)) { return false; } } } - dedup.GetAllowedSet(allowed_set); + dedup.GetAllowedMap(allowed_set); return true; } @@ -1561,9 +1633,9 @@ bool GenerateJspbAllowedSet(const GeneratorOptions& options, void EmbedCodeAnnotations(const GeneratedCodeInfo& annotations, io::Printer* printer) { // Serialize annotations proto into base64 string. - string meta_content; + std::string meta_content; annotations.SerializeToString(&meta_content); - string meta_64; + std::string meta_64; Base64Escape(meta_content, &meta_64); // Print base64 encoded annotations at the end of output file in @@ -1572,27 +1644,32 @@ void EmbedCodeAnnotations(const GeneratedCodeInfo& annotations, printer->Print("\n// $encoded_proto$\n", "encoded_proto", meta_64); } +bool IsWellKnownTypeFile(const FileDescriptor* file) { + return HasPrefixString(file->name(), "google/protobuf/"); +} + } // anonymous namespace void Generator::GenerateHeader(const GeneratorOptions& options, io::Printer* printer) const { - printer->Print("/**\n" - " * @fileoverview\n" - " * @enhanceable\n" - " * @suppress {messageConventions} JS Compiler reports an " - "error if a variable or\n" - " * field starts with 'MSG_' and isn't a translatable " - "message.\n" - " * @public\n" - " */\n" - "// GENERATED CODE -- DO NOT EDIT!\n" - "\n"); + printer->Print( + "/**\n" + " * @fileoverview\n" + " * @enhanceable\n" + " * @suppress {messageConventions} JS Compiler reports an " + "error if a variable or\n" + " * field starts with 'MSG_' and isn't a translatable " + "message.\n" + " * @public\n" + " */\n" + "// GENERATED CODE -- DO NOT EDIT!\n" + "\n"); } void Generator::FindProvidesForFile(const GeneratorOptions& options, io::Printer* printer, const FileDescriptor* file, - std::set* provided) const { + std::set* provided) const { for (int i = 0; i < file->message_type_count(); i++) { FindProvidesForMessage(options, printer, file->message_type(i), provided); } @@ -1604,7 +1681,7 @@ void Generator::FindProvidesForFile(const GeneratorOptions& options, void Generator::FindProvides(const GeneratorOptions& options, io::Printer* printer, const std::vector& files, - std::set* provided) const { + std::set* provided) const { for (int i = 0; i < files.size(); i++) { FindProvidesForFile(options, printer, files[i], provided); } @@ -1612,41 +1689,37 @@ void Generator::FindProvides(const GeneratorOptions& options, printer->Print("\n"); } -void Generator::FindProvidesForMessage( - const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc, - std::set* provided) const { - if (IgnoreMessage(options, desc)) { +void Generator::FindProvidesForMessage(const GeneratorOptions& options, + io::Printer* printer, + const Descriptor* desc, + std::set* provided) const { + if (IgnoreMessage(desc)) { return; } - string name = GetMessagePath(options, desc); + std::string name = GetMessagePath(options, desc); provided->insert(name); for (int i = 0; i < desc->enum_type_count(); i++) { - FindProvidesForEnum(options, printer, desc->enum_type(i), - provided); + FindProvidesForEnum(options, printer, desc->enum_type(i), provided); } for (int i = 0; i < desc->nested_type_count(); i++) { - FindProvidesForMessage(options, printer, desc->nested_type(i), - provided); + FindProvidesForMessage(options, printer, desc->nested_type(i), provided); } } void Generator::FindProvidesForEnum(const GeneratorOptions& options, io::Printer* printer, const EnumDescriptor* enumdesc, - std::set* provided) const { - string name = GetEnumPath(options, enumdesc); + std::set* provided) const { + std::string name = GetEnumPath(options, enumdesc); provided->insert(name); } void Generator::FindProvidesForFields( - const GeneratorOptions& options, - io::Printer* printer, + const GeneratorOptions& options, io::Printer* printer, const std::vector& fields, - std::set* provided) const { + std::set* provided) const { for (int i = 0; i < fields.size(); i++) { const FieldDescriptor* field = fields[i]; @@ -1654,16 +1727,16 @@ void Generator::FindProvidesForFields( continue; } - string name = GetFilePath(options, field->file()) + "." + - JSObjectFieldName(options, field); + std::string name = GetNamespace(options, field->file()) + "." + + JSObjectFieldName(options, field); provided->insert(name); } } void Generator::GenerateProvides(const GeneratorOptions& options, io::Printer* printer, - std::set* provided) const { - for (std::set::iterator it = provided->begin(); + std::set* provided) const { + for (std::set::iterator it = provided->begin(); it != provided->end(); ++it) { if (options.import_style == GeneratorOptions::kImportClosure) { printer->Print("goog.provide('$name$');\n", "name", *it); @@ -1675,36 +1748,54 @@ void Generator::GenerateProvides(const GeneratorOptions& options, // // // Later generated code expects foo.bar = {} to exist: // foo.bar.Baz = function() { /* ... */ } - printer->Print("goog.exportSymbol('$name$', null, global);\n", "name", - *it); + + // Do not use global scope in strict mode + if (options.import_style == GeneratorOptions::kImportCommonJsStrict) { + std::string namespaceObject = *it; + // Remove "proto." from the namespace object + GOOGLE_CHECK_EQ(0, namespaceObject.compare(0, 6, "proto.")); + namespaceObject.erase(0, 6); + printer->Print("goog.exportSymbol('$name$', null, proto);\n", "name", + namespaceObject); + } else { + printer->Print("goog.exportSymbol('$name$', null, global);\n", "name", + *it); + } } } } -void Generator::GenerateRequiresForMessage(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc, - std::set* provided) const { - std::set required; - std::set forwards; +void Generator::GenerateRequiresForSCC(const GeneratorOptions& options, + io::Printer* printer, const SCC* scc, + std::set* provided) const { + std::set required; + std::set forwards; bool have_message = false; - FindRequiresForMessage(options, desc, - &required, &forwards, &have_message); + bool has_extension = false; + bool has_map = false; + for (auto desc : scc->descriptors) { + if (desc->containing_type() == nullptr) { + FindRequiresForMessage(options, desc, &required, &forwards, + &have_message); + has_extension = (has_extension || HasExtensions(desc)); + has_map = (has_map || HasMap(options, desc)); + } + } GenerateRequiresImpl(options, printer, &required, &forwards, provided, /* require_jspb = */ have_message, - /* require_extension = */ HasExtensions(desc), - /* require_map = */ HasMap(options, desc)); + /* require_extension = */ has_extension, + /* require_map = */ has_map); } void Generator::GenerateRequiresForLibrary( const GeneratorOptions& options, io::Printer* printer, const std::vector& files, - std::set* provided) const { + std::set* provided) const { GOOGLE_CHECK_EQ(options.import_style, GeneratorOptions::kImportClosure); // For Closure imports we need to import every message type individually. - std::set required; - std::set forwards; + std::set required; + std::set forwards; bool have_extensions = false; bool have_map = false; bool have_message = false; @@ -1712,7 +1803,7 @@ void Generator::GenerateRequiresForLibrary( for (int i = 0; i < files.size(); i++) { for (int j = 0; j < files[i]->message_type_count(); j++) { const Descriptor* desc = files[i]->message_type(j); - if (!IgnoreMessage(options, desc)) { + if (!IgnoreMessage(desc)) { FindRequiresForMessage(options, desc, &required, &forwards, &have_message); } @@ -1732,7 +1823,7 @@ void Generator::GenerateRequiresForLibrary( continue; } if (extension->containing_type()->full_name() != - "google.protobuf.bridge.MessageSet") { + "google.protobuf.bridge.MessageSet") { required.insert(GetMessagePath(options, extension->containing_type())); } FindRequiresForField(options, extension, &required, &forwards); @@ -1749,9 +1840,9 @@ void Generator::GenerateRequiresForLibrary( void Generator::GenerateRequiresForExtensions( const GeneratorOptions& options, io::Printer* printer, const std::vector& fields, - std::set* provided) const { - std::set required; - std::set forwards; + std::set* provided) const { + std::set required; + std::set forwards; for (int i = 0; i < fields.size(); i++) { const FieldDescriptor* field = fields[i]; if (IgnoreField(field)) { @@ -1768,9 +1859,9 @@ void Generator::GenerateRequiresForExtensions( void Generator::GenerateRequiresImpl(const GeneratorOptions& options, io::Printer* printer, - std::set* required, - std::set* forwards, - std::set* provided, + std::set* required, + std::set* forwards, + std::set* provided, bool require_jspb, bool require_extension, bool require_map) const { if (require_jspb) { @@ -1786,13 +1877,12 @@ void Generator::GenerateRequiresImpl(const GeneratorOptions& options, required->insert("jspb.Map"); } - std::set::iterator it; + std::set::iterator it; for (it = required->begin(); it != required->end(); ++it) { if (provided->find(*it) != provided->end()) { continue; } - printer->Print("goog.require('$name$');\n", - "name", *it); + printer->Print("goog.require('$name$');\n", "name", *it); } printer->Print("\n"); @@ -1801,8 +1891,7 @@ void Generator::GenerateRequiresImpl(const GeneratorOptions& options, if (provided->find(*it) != provided->end()) { continue; } - printer->Print("goog.forwardDeclare('$name$');\n", - "name", *it); + printer->Print("goog.forwardDeclare('$name$');\n", "name", *it); } } @@ -1810,13 +1899,11 @@ bool NamespaceOnly(const Descriptor* desc) { return false; } -void Generator::FindRequiresForMessage( - const GeneratorOptions& options, - const Descriptor* desc, - std::set* required, - std::set* forwards, - bool* have_message) const { - +void Generator::FindRequiresForMessage(const GeneratorOptions& options, + const Descriptor* desc, + std::set* required, + std::set* forwards, + bool* have_message) const { if (!NamespaceOnly(desc)) { *have_message = true; @@ -1845,32 +1932,31 @@ void Generator::FindRequiresForMessage( void Generator::FindRequiresForField(const GeneratorOptions& options, const FieldDescriptor* field, - std::set* required, - std::set* forwards) const { - if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM && - // N.B.: file-level extensions with enum type do *not* create - // dependencies, as per original codegen. - !(field->is_extension() && field->extension_scope() == NULL)) { - if (options.add_require_for_enums) { - required->insert(GetEnumPath(options, field->enum_type())); - } else { - forwards->insert(GetEnumPath(options, field->enum_type())); - } - } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - if (!IgnoreMessage(options, field->message_type())) { - required->insert(GetMessagePath(options, field->message_type())); - } + std::set* required, + std::set* forwards) const { + if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM && + // N.B.: file-level extensions with enum type do *not* create + // dependencies, as per original codegen. + !(field->is_extension() && field->extension_scope() == nullptr)) { + if (options.add_require_for_enums) { + required->insert(GetEnumPath(options, field->enum_type())); + } else { + forwards->insert(GetEnumPath(options, field->enum_type())); } + } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { + if (!IgnoreMessage(field->message_type())) { + required->insert(GetMessagePath(options, field->message_type())); + } + } } -void Generator::FindRequiresForExtension(const GeneratorOptions& options, - const FieldDescriptor* field, - std::set* required, - std::set* forwards) const { - if (field->containing_type()->full_name() != "google.protobuf.bridge.MessageSet") { - required->insert(GetMessagePath(options, field->containing_type())); - } - FindRequiresForField(options, field, required, forwards); +void Generator::FindRequiresForExtension( + const GeneratorOptions& options, const FieldDescriptor* field, + std::set* required, std::set* forwards) const { + if (field->containing_type()->full_name() != "google.protobuf.bridge.MessageSet") { + required->insert(GetMessagePath(options, field->containing_type())); + } + FindRequiresForField(options, field, required, forwards); } void Generator::GenerateTestOnly(const GeneratorOptions& options, @@ -1884,6 +1970,10 @@ void Generator::GenerateTestOnly(const GeneratorOptions& options, void Generator::GenerateClassesAndEnums(const GeneratorOptions& options, io::Printer* printer, const FileDescriptor* file) const { + for (int i = 0; i < file->message_type_count(); i++) { + GenerateClassConstructorAndDeclareExtensionFieldInfo(options, printer, + file->message_type(i)); + } for (int i = 0; i < file->message_type_count(); i++) { GenerateClass(options, printer, file->message_type(i)); } @@ -1895,13 +1985,12 @@ void Generator::GenerateClassesAndEnums(const GeneratorOptions& options, void Generator::GenerateClass(const GeneratorOptions& options, io::Printer* printer, const Descriptor* desc) const { - if (IgnoreMessage(options, desc)) { + if (IgnoreMessage(desc)) { return; } if (!NamespaceOnly(desc)) { printer->Print("\n"); - GenerateClassConstructor(options, printer, desc); GenerateClassFieldInfo(options, printer, desc); @@ -1927,9 +2016,6 @@ void Generator::GenerateClass(const GeneratorOptions& options, if (!NamespaceOnly(desc)) { GenerateClassRegistration(options, printer, desc); GenerateClassFields(options, printer, desc); - if (IsExtendable(desc) && desc->full_name() != "google.protobuf.bridge.MessageSet") { - GenerateClassExtensionFieldInfo(options, printer, desc); - } if (options.import_style != GeneratorOptions::kImportClosure) { for (int i = 0; i < desc->extension_count(); i++) { @@ -1958,28 +2044,51 @@ void Generator::GenerateClassConstructor(const GeneratorOptions& options, " * @constructor\n" " */\n" "$classprefix$$classname$ = function(opt_data) {\n", - "classprefix", GetMessagePathPrefix(options, desc), - "classname", desc->name()); + "classprefix", GetMessagePathPrefix(options, desc), "classname", + desc->name()); printer->Annotate("classname", desc); - string message_id = GetMessageId(desc); + std::string message_id = GetMessageId(desc); printer->Print( " jspb.Message.initialize(this, opt_data, $messageId$, $pivot$, " "$rptfields$, $oneoffields$);\n", - "messageId", !message_id.empty() ? - ("'" + message_id + "'") : - (IsResponse(desc) ? "''" : "0"), - "pivot", GetPivot(desc), - "rptfields", RepeatedFieldsArrayName(options, desc), - "oneoffields", OneofFieldsArrayName(options, desc)); + "messageId", + !message_id.empty() ? ("'" + message_id + "'") + : (IsResponse(desc) ? "''" : "0"), + "pivot", GetPivot(desc), "rptfields", + RepeatedFieldsArrayName(options, desc), "oneoffields", + OneofFieldsArrayName(options, desc)); printer->Print( "};\n" "goog.inherits($classname$, jspb.Message);\n" "if (goog.DEBUG && !COMPILED) {\n" + // displayName overrides Function.prototype.displayName + // http://google3/javascript/externs/es3.js?l=511 + " /**\n" + " * @public\n" + " * @override\n" + " */\n" " $classname$.displayName = '$classname$';\n" "}\n", "classname", GetMessagePath(options, desc)); } +void Generator::GenerateClassConstructorAndDeclareExtensionFieldInfo( + const GeneratorOptions& options, io::Printer* printer, + const Descriptor* desc) const { + if (!NamespaceOnly(desc)) { + GenerateClassConstructor(options, printer, desc); + if (IsExtendable(desc) && desc->full_name() != "google.protobuf.bridge.MessageSet") { + GenerateClassExtensionFieldInfo(options, printer, desc); + } + } + for (int i = 0; i < desc->nested_type_count(); i++) { + if (!IgnoreMessage(desc->nested_type(i))) { + GenerateClassConstructorAndDeclareExtensionFieldInfo( + options, printer, desc->nested_type(i)); + } + } +} + void Generator::GenerateClassFieldInfo(const GeneratorOptions& options, io::Printer* printer, const Descriptor* desc) const { @@ -1992,9 +2101,9 @@ void Generator::GenerateClassFieldInfo(const GeneratorOptions& options, " */\n" "$classname$$rptfieldarray$ = $rptfields$;\n" "\n", - "classname", GetMessagePath(options, desc), - "rptfieldarray", kRepeatedFieldArrayName, - "rptfields", RepeatedFieldNumberList(options, desc)); + "classname", GetMessagePath(options, desc), "rptfieldarray", + kRepeatedFieldArrayName, "rptfields", + RepeatedFieldNumberList(options, desc)); } if (HasOneofFields(desc)) { @@ -2013,9 +2122,8 @@ void Generator::GenerateClassFieldInfo(const GeneratorOptions& options, " */\n" "$classname$$oneofgrouparray$ = $oneofgroups$;\n" "\n", - "classname", GetMessagePath(options, desc), - "oneofgrouparray", kOneofGroupArrayName, - "oneofgroups", OneofGroupList(desc)); + "classname", GetMessagePath(options, desc), "oneofgrouparray", + kOneofGroupArrayName, "oneofgroups", OneofGroupList(desc)); for (int i = 0; i < desc->oneof_decl_count(); i++) { if (IgnoreOneof(desc->oneof_decl(i))) { @@ -2037,8 +2145,7 @@ void Generator::GenerateClassXid(const GeneratorOptions& options, } void Generator::GenerateOneofCaseDefinition( - const GeneratorOptions& options, - io::Printer* printer, + const GeneratorOptions& options, io::Printer* printer, const OneofDescriptor* oneof) const { printer->Print( "/**\n" @@ -2046,9 +2153,8 @@ void Generator::GenerateOneofCaseDefinition( " */\n" "$classname$.$oneof$Case = {\n" " $upcase$_NOT_SET: 0", - "classname", GetMessagePath(options, oneof->containing_type()), - "oneof", JSOneofName(oneof), - "upcase", ToEnumCase(oneof->name())); + "classname", GetMessagePath(options, oneof->containing_type()), "oneof", + JSOneofName(oneof), "upcase", ToEnumCase(oneof->name())); for (int i = 0; i < oneof->field_count(); i++) { if (IgnoreField(oneof->field(i))) { @@ -2058,8 +2164,8 @@ void Generator::GenerateOneofCaseDefinition( printer->Print( ",\n" " $upcase$: $number$", - "upcase", ToEnumCase(oneof->field(i)->name()), - "number", JSFieldIndex(oneof->field(i))); + "upcase", ToEnumCase(oneof->field(i)->name()), "number", + JSFieldIndex(oneof->field(i))); printer->Annotate("upcase", oneof->field(i)); } @@ -2075,9 +2181,8 @@ void Generator::GenerateOneofCaseDefinition( "computeOneofCase(this, $class$.oneofGroups_[$oneofindex$]));\n" "};\n" "\n", - "class", GetMessagePath(options, oneof->containing_type()), - "oneof", JSOneofName(oneof), - "oneofindex", JSOneofIndex(oneof)); + "class", GetMessagePath(options, oneof->containing_type()), "oneof", + JSOneofName(oneof), "oneofindex", JSOneofIndex(oneof)); } void Generator::GenerateClassToObject(const GeneratorOptions& options, @@ -2088,17 +2193,17 @@ void Generator::GenerateClassToObject(const GeneratorOptions& options, "\n" "if (jspb.Message.GENERATE_TO_OBJECT) {\n" "/**\n" - " * Creates an object representation of this proto suitable for use in " - "Soy templates.\n" + " * Creates an object representation of this proto.\n" " * Field names that are reserved in JavaScript and will be renamed to " "pb_name.\n" + " * Optional fields that are not set will be set to undefined.\n" " * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n" " * For the list of reserved names please see:\n" - " * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS.\n" - " * @param {boolean=} opt_includeInstance Whether to include the JSPB " - "instance\n" - " * for transitional soy proto support: http://goto/soy-param-" - "migration\n" + " * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n" + " * @param {boolean=} opt_includeInstance Deprecated. whether to include " + "the\n" + " * JSPB instance for transitional soy proto support:\n" + " * http://goto/soy-param-migration\n" " * @return {!Object}\n" " */\n" "$classname$.prototype.toObject = function(opt_includeInstance) {\n" @@ -2108,9 +2213,9 @@ void Generator::GenerateClassToObject(const GeneratorOptions& options, "\n" "/**\n" " * Static version of the {@see toObject} method.\n" - " * @param {boolean|undefined} includeInstance Whether to include the " - "JSPB\n" - " * instance for transitional soy proto support:\n" + " * @param {boolean|undefined} includeInstance Deprecated. Whether to " + "include\n" + " * the JSPB instance for transitional soy proto support:\n" " * http://goto/soy-param-migration\n" " * @param {!$classname$} msg The msg instance to transform.\n" " * @return {!Object}\n" @@ -2166,62 +2271,64 @@ void Generator::GenerateClassToObject(const GeneratorOptions& options, } void Generator::GenerateFieldValueExpression(io::Printer* printer, - const char *obj_reference, + const char* obj_reference, const FieldDescriptor* field, bool use_default) const { - bool is_float_or_double = + const bool is_float_or_double = field->cpp_type() == FieldDescriptor::CPPTYPE_FLOAT || field->cpp_type() == FieldDescriptor::CPPTYPE_DOUBLE; - if (use_default) { - if (is_float_or_double) { - // Coerce "Nan" and "Infinity" to actual float values. - // - // This will change null to 0, but that doesn't matter since we're getting - // with a default. - printer->Print("+"); - } + const bool is_boolean = field->cpp_type() == FieldDescriptor::CPPTYPE_BOOL; + const string with_default = use_default ? "WithDefault" : ""; + const string default_arg = + use_default ? StrCat(", ", JSFieldDefault(field)) : ""; + const string cardinality = field->is_repeated() ? "Repeated" : ""; + string type = ""; + if (is_float_or_double) { + type = "FloatingPoint"; + } + if (is_boolean) { + type = "Boolean"; + } + + // Prints the appropriate function, among: + // - getField + // - getBooleanField + // - getFloatingPointField => Replaced by getOptionalFloatingPointField to + // preserve backward compatibility. + // - getFieldWithDefault + // - getBooleanFieldWithDefault + // - getFloatingPointFieldWithDefault + // - getRepeatedField + // - getRepeatedBooleanField + // - getRepeatedFloatingPointField + if (is_float_or_double && !field->is_repeated() && !use_default) { printer->Print( - "jspb.Message.getFieldWithDefault($obj$, $index$, $default$)", - "obj", obj_reference, - "index", JSFieldIndex(field), - "default", JSFieldDefault(field)); + "jspb.Message.getOptionalFloatingPointField($obj$, " + "$index$$default$)", + "obj", obj_reference, "index", JSFieldIndex(field), "default", + default_arg); } else { - if (is_float_or_double) { - if (field->is_required()) { - // Use "+" to convert all fields to numeric (including null). - printer->Print( - "+jspb.Message.getField($obj$, $index$)", - "index", JSFieldIndex(field), - "obj", obj_reference); - } else { - // Converts "NaN" and "Infinity" while preserving null. - printer->Print( - "jspb.Message.get$cardinality$FloatingPointField($obj$, $index$)", - "cardinality", field->is_repeated() ? "Repeated" : "Optional", - "index", JSFieldIndex(field), - "obj", obj_reference); - } - } else { - printer->Print("jspb.Message.get$cardinality$Field($obj$, $index$)", - "cardinality", field->is_repeated() ? "Repeated" : "", - "index", JSFieldIndex(field), - "obj", obj_reference); - } + printer->Print( + "jspb.Message.get$cardinality$$type$Field$with_default$($obj$, " + "$index$$default$)", + "cardinality", cardinality, "type", type, "with_default", with_default, + "obj", obj_reference, "index", JSFieldIndex(field), "default", + default_arg); } } void Generator::GenerateClassFieldToObject(const GeneratorOptions& options, io::Printer* printer, const FieldDescriptor* field) const { - printer->Print("$fieldname$: ", - "fieldname", JSObjectFieldName(options, field)); + printer->Print("$fieldname$: ", "fieldname", + JSObjectFieldName(options, field)); - if (IsMap(options, field)) { + if (field->is_map()) { const FieldDescriptor* value_field = MapFieldValue(field); // If the map values are of a message type, we must provide their static // toObject() method; otherwise we pass undefined for that argument. - string value_to_object; + std::string value_to_object; if (value_field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { value_to_object = GetMessagePath(options, value_field->message_type()) + ".toObject"; @@ -2236,21 +2343,23 @@ void Generator::GenerateClassFieldToObject(const GeneratorOptions& options, // Message field. if (field->is_repeated()) { { - printer->Print("jspb.Message.toObjectList(msg.get$getter$(),\n" - " $type$.toObject, includeInstance)", - "getter", JSGetterName(options, field), - "type", SubmessageTypeRef(options, field)); + printer->Print( + "jspb.Message.toObjectList(msg.get$getter$(),\n" + " $type$.toObject, includeInstance)", + "getter", JSGetterName(options, field), "type", + SubmessageTypeRef(options, field)); } } else { - printer->Print("(f = msg.get$getter$()) && " - "$type$.toObject(includeInstance, f)", - "getter", JSGetterName(options, field), - "type", SubmessageTypeRef(options, field)); + printer->Print( + "(f = msg.get$getter$()) && " + "$type$.toObject(includeInstance, f)", + "getter", JSGetterName(options, field), "type", + SubmessageTypeRef(options, field)); } } else if (field->type() == FieldDescriptor::TYPE_BYTES) { // For bytes fields we want to always return the B64 data. - printer->Print("msg.get$getter$()", - "getter", JSGetterName(options, field, BYTES_B64)); + printer->Print("msg.get$getter$()", "getter", + JSGetterName(options, field, BYTES_B64)); } else { bool use_default = field->has_default_value(); @@ -2269,91 +2378,128 @@ void Generator::GenerateClassFieldToObject(const GeneratorOptions& options, // We are migrating the accessors to return defaults instead of null, but // it may take longer to migrate toObject (or we might not want to do it at // all). So we want to generate independent code. + // The accessor for unset optional values without default should return + // null. Those are converted to undefined in the generated object. + if (!use_default) { + printer->Print("(f = "); + } GenerateFieldValueExpression(printer, "msg", field, use_default); + if (!use_default) { + printer->Print(") == null ? undefined : f"); + } + } +} + +void Generator::GenerateObjectTypedef(const GeneratorOptions& options, + io::Printer* printer, + const Descriptor* desc) const { + // TODO(b/122687752): Consider renaming nested messages called ObjectFormat + // to prevent collisions. + const std::string type_name = GetMessagePath(options, desc) + ".ObjectFormat"; + + printer->Print( + "/**\n" + " * The raw object form of $messageName$ as accepted by the `fromObject` " + "method.\n" + " * @record\n" + " */\n" + "$typeName$ = function() {};\n\n", + "messageName", desc->name(), "typeName", type_name); + + for (int i = 0; i < desc->field_count(); i++) { + printer->Print( + "/** @type {$fieldType$|undefined} */\n" + "$typeName$.prototype.$fieldName$;\n\n", + "typeName", type_name, "fieldName", + JSObjectFieldName(options, desc->field(i)), + // TODO(b/121097361): Add type checking for field values. + "fieldType", "?"); } } void Generator::GenerateClassFromObject(const GeneratorOptions& options, io::Printer* printer, const Descriptor* desc) const { + printer->Print("if (jspb.Message.GENERATE_FROM_OBJECT) {\n\n"); + + GenerateObjectTypedef(options, printer, desc); + printer->Print( - "if (jspb.Message.GENERATE_FROM_OBJECT) {\n" "/**\n" " * Loads data from an object into a new instance of this proto.\n" - " * @param {!Object} obj The object representation of this proto to\n" - " * load the data from.\n" + " * @param {!$classname$.ObjectFormat} obj\n" + " * The object representation of this proto to load the data from.\n" " * @return {!$classname$}\n" " */\n" "$classname$.fromObject = function(obj) {\n" - " var f, msg = new $classname$();\n", + " var msg = new $classname$();\n", "classname", GetMessagePath(options, desc)); for (int i = 0; i < desc->field_count(); i++) { const FieldDescriptor* field = desc->field(i); - GenerateClassFieldFromObject(options, printer, field); + if (!IgnoreField(field)) { + GenerateClassFieldFromObject(options, printer, field); + } } printer->Print( " return msg;\n" "};\n" - "}\n"); + "}\n\n"); } void Generator::GenerateClassFieldFromObject( - const GeneratorOptions& options, - io::Printer* printer, + const GeneratorOptions& options, io::Printer* printer, const FieldDescriptor* field) const { - if (IsMap(options, field)) { + if (field->is_map()) { const FieldDescriptor* value_field = MapFieldValue(field); if (value_field->type() == FieldDescriptor::TYPE_MESSAGE) { // Since the map values are of message type, we have to do some extra work // to recursively call fromObject() on them before setting the map field. printer->Print( - " goog.isDef(obj.$name$) && jspb.Message.setWrapperField(\n" + " obj.$name$ && jspb.Message.setWrapperField(\n" " msg, $index$, jspb.Map.fromObject(obj.$name$, $fieldclass$, " "$fieldclass$.fromObject));\n", - "name", JSObjectFieldName(options, field), - "index", JSFieldIndex(field), - "fieldclass", GetMessagePath(options, value_field->message_type())); + "name", JSObjectFieldName(options, field), "index", + JSFieldIndex(field), "fieldclass", + GetMessagePath(options, value_field->message_type())); } else { // `msg` is a newly-constructed message object that has not yet built any // map containers wrapping underlying arrays, so we can simply directly // set the array here without fear of a stale wrapper. printer->Print( - " goog.isDef(obj.$name$) && " + " obj.$name$ && " "jspb.Message.setField(msg, $index$, obj.$name$);\n", - "name", JSObjectFieldName(options, field), - "index", JSFieldIndex(field)); + "name", JSObjectFieldName(options, field), "index", + JSFieldIndex(field)); } } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { // Message field (singular or repeated) if (field->is_repeated()) { { printer->Print( - " goog.isDef(obj.$name$) && " + " obj.$name$ && " "jspb.Message.setRepeatedWrapperField(\n" - " msg, $index$, goog.array.map(obj.$name$, function(i) {\n" - " return $fieldclass$.fromObject(i);\n" - " }));\n", - "name", JSObjectFieldName(options, field), - "index", JSFieldIndex(field), - "fieldclass", SubmessageTypeRef(options, field)); + " msg, $index$, obj.$name$.map(\n" + " $fieldclass$.fromObject));\n", + "name", JSObjectFieldName(options, field), "index", + JSFieldIndex(field), "fieldclass", + SubmessageTypeRef(options, field)); } } else { printer->Print( - " goog.isDef(obj.$name$) && jspb.Message.setWrapperField(\n" + " obj.$name$ && jspb.Message.setWrapperField(\n" " msg, $index$, $fieldclass$.fromObject(obj.$name$));\n", - "name", JSObjectFieldName(options, field), - "index", JSFieldIndex(field), - "fieldclass", SubmessageTypeRef(options, field)); + "name", JSObjectFieldName(options, field), "index", + JSFieldIndex(field), "fieldclass", SubmessageTypeRef(options, field)); } } else { // Simple (primitive) field. printer->Print( - " goog.isDef(obj.$name$) && jspb.Message.setField(msg, $index$, " + " obj.$name$ != null && jspb.Message.setField(msg, $index$, " "obj.$name$);\n", - "name", JSObjectFieldName(options, field), - "index", JSFieldIndex(field)); + "name", JSObjectFieldName(options, field), "index", + JSFieldIndex(field)); } } @@ -2380,15 +2526,13 @@ void Generator::GenerateClassFields(const GeneratorOptions& options, } } -void GenerateBytesWrapper(const GeneratorOptions& options, - io::Printer* printer, - const FieldDescriptor* field, - BytesMode bytes_mode) { - string type = JSFieldTypeAnnotation( - options, field, - /* is_setter_argument = */ false, - /* force_present = */ false, - /* singular_if_not_packed = */ false, bytes_mode); +void GenerateBytesWrapper(const GeneratorOptions& options, io::Printer* printer, + const FieldDescriptor* field, BytesMode bytes_mode) { + std::string type = + JSFieldTypeAnnotation(options, field, + /* is_setter_argument = */ false, + /* force_present = */ false, + /* singular_if_not_packed = */ false, bytes_mode); printer->Print( "/**\n" " * $fielddef$\n" @@ -2402,35 +2546,32 @@ void GenerateBytesWrapper(const GeneratorOptions& options, "};\n" "\n" "\n", - "fielddef", FieldDefinition(options, field), - "comment", FieldComments(field, bytes_mode), - "type", type, - "class", GetMessagePath(options, field->containing_type()), - "name", JSGetterName(options, field, bytes_mode), - "list", field->is_repeated() ? "List" : "", - "suffix", JSByteGetterSuffix(bytes_mode), - "defname", JSGetterName(options, field, BYTES_DEFAULT)); + "fielddef", FieldDefinition(options, field), "comment", + FieldComments(field, bytes_mode), "type", type, "class", + GetMessagePath(options, field->containing_type()), "name", + JSGetterName(options, field, bytes_mode), "list", + field->is_repeated() ? "List" : "", "suffix", + JSByteGetterSuffix(bytes_mode), "defname", + JSGetterName(options, field, BYTES_DEFAULT)); } void Generator::GenerateClassField(const GeneratorOptions& options, io::Printer* printer, const FieldDescriptor* field) const { - if (IsMap(options, field)) { + if (field->is_map()) { const FieldDescriptor* key_field = MapFieldKey(field); const FieldDescriptor* value_field = MapFieldValue(field); // Map field: special handling to instantiate the map object on demand. - string key_type = - JSFieldTypeAnnotation( - options, key_field, - /* is_setter_argument = */ false, - /* force_present = */ true, - /* singular_if_not_packed = */ false); - string value_type = - JSFieldTypeAnnotation( - options, value_field, - /* is_setter_argument = */ false, - /* force_present = */ true, - /* singular_if_not_packed = */ false); + std::string key_type = + JSFieldTypeAnnotation(options, key_field, + /* is_setter_argument = */ false, + /* force_present = */ true, + /* singular_if_not_packed = */ false); + std::string value_type = + JSFieldTypeAnnotation(options, value_field, + /* is_setter_argument = */ false, + /* force_present = */ true, + /* singular_if_not_packed = */ false); printer->Print( "/**\n" @@ -2439,15 +2580,13 @@ void Generator::GenerateClassField(const GeneratorOptions& options, " * empty, instead returning `undefined`\n" " * @return {!jspb.Map<$keytype$,$valuetype$>}\n" " */\n", - "fielddef", FieldDefinition(options, field), - "keytype", key_type, + "fielddef", FieldDefinition(options, field), "keytype", key_type, "valuetype", value_type); printer->Print( "$class$.prototype.$gettername$ = function(opt_noLazyCreate) {\n" " return /** @type {!jspb.Map<$keytype$,$valuetype$>} */ (\n", "class", GetMessagePath(options, field->containing_type()), - "gettername", "get" + JSGetterName(options, field), - "keytype", key_type, + "gettername", "get" + JSGetterName(options, field), "keytype", key_type, "valuetype", value_type); printer->Annotate("gettername", field); printer->Print( @@ -2460,12 +2599,12 @@ void Generator::GenerateClassField(const GeneratorOptions& options, " $messageType$", "messageType", GetMessagePath(options, value_field->message_type())); } else { - printer->Print(",\n" + printer->Print( + ",\n" " null"); } - printer->Print( - "));\n"); + printer->Print("));\n"); printer->Print( "};\n" @@ -2481,12 +2620,12 @@ void Generator::GenerateClassField(const GeneratorOptions& options, "$comment$" " * @return {$type$}\n" " */\n", - "fielddef", FieldDefinition(options, field), - "comment", FieldComments(field, BYTES_DEFAULT), - "type", JSFieldTypeAnnotation(options, field, - /* is_setter_argument = */ false, - /* force_present = */ false, - /* singular_if_not_packed = */ false)); + "fielddef", FieldDefinition(options, field), "comment", + FieldComments(field, BYTES_DEFAULT), "type", + JSFieldTypeAnnotation(options, field, + /* is_setter_argument = */ false, + /* force_present = */ false, + /* singular_if_not_packed = */ false)); printer->Print( "$class$.prototype.$gettername$ = function() {\n" " return /** @type{$type$} */ (\n" @@ -2496,16 +2635,15 @@ void Generator::GenerateClassField(const GeneratorOptions& options, "\n" "\n", "class", GetMessagePath(options, field->containing_type()), - "gettername", "get" + JSGetterName(options, field), - "type", JSFieldTypeAnnotation(options, field, - /* is_setter_argument = */ false, - /* force_present = */ false, - /* singular_if_not_packed = */ false), - "rpt", (field->is_repeated() ? "Repeated" : ""), - "index", JSFieldIndex(field), - "wrapperclass", SubmessageTypeRef(options, field), - "required", (field->label() == FieldDescriptor::LABEL_REQUIRED ? - ", 1" : "")); + "gettername", "get" + JSGetterName(options, field), "type", + JSFieldTypeAnnotation(options, field, + /* is_setter_argument = */ false, + /* force_present = */ false, + /* singular_if_not_packed = */ false), + "rpt", (field->is_repeated() ? "Repeated" : ""), "index", + JSFieldIndex(field), "wrapperclass", SubmessageTypeRef(options, field), + "required", + (field->label() == FieldDescriptor::LABEL_REQUIRED ? ", 1" : "")); printer->Annotate("gettername", field); printer->Print( "/** @param {$optionaltype$} value$returndoc$ */\n" @@ -2516,11 +2654,11 @@ void Generator::GenerateClassField(const GeneratorOptions& options, /* is_setter_argument = */ true, /* force_present = */ false, /* singular_if_not_packed = */ false), - "returndoc", JSReturnDoc(options, field), - "class", GetMessagePath(options, field->containing_type()), - "settername", "set" + JSGetterName(options, field), - "oneoftag", (field->containing_oneof() ? "Oneof" : ""), - "repeatedtag", (field->is_repeated() ? "Repeated" : "")); + "returndoc", JSReturnDoc(options, field), "class", + GetMessagePath(options, field->containing_type()), "settername", + "set" + JSGetterName(options, field), "oneoftag", + (field->containing_oneof() ? "Oneof" : ""), "repeatedtag", + (field->is_repeated() ? "Repeated" : "")); printer->Annotate("settername", field); printer->Print( @@ -2528,9 +2666,9 @@ void Generator::GenerateClassField(const GeneratorOptions& options, "};\n" "\n" "\n", - "index", JSFieldIndex(field), - "oneofgroup", (field->containing_oneof() ? - (", " + JSOneofArray(options, field)) : ""), + "index", JSFieldIndex(field), "oneofgroup", + (field->containing_oneof() ? (", " + JSOneofArray(options, field)) + : ""), "returnvalue", JSReturnClause(field)); if (field->is_repeated()) { @@ -2547,14 +2685,15 @@ void Generator::GenerateClassField(const GeneratorOptions& options, // at this point we "lie" to non-binary users and tell the return // type is always base64 string, pending a LSC to migrate to typed getters. BytesMode bytes_mode = - field->type() == FieldDescriptor::TYPE_BYTES && !options.binary ? - BYTES_B64 : BYTES_DEFAULT; - string typed_annotation = JSFieldTypeAnnotation( - options, field, - /* is_setter_argument = */ false, - /* force_present = */ false, - /* singular_if_not_packed = */ false, - /* bytes_mode = */ bytes_mode); + field->type() == FieldDescriptor::TYPE_BYTES && !options.binary + ? BYTES_B64 + : BYTES_DEFAULT; + std::string typed_annotation = + JSFieldTypeAnnotation(options, field, + /* is_setter_argument = */ false, + /* force_present = */ false, + /* singular_if_not_packed = */ false, + /* bytes_mode = */ bytes_mode); if (untyped) { printer->Print( "/**\n" @@ -2567,24 +2706,20 @@ void Generator::GenerateClassField(const GeneratorOptions& options, "$comment$" " * @return {$type$}\n" " */\n", - "fielddef", FieldDefinition(options, field), - "comment", FieldComments(field, bytes_mode), - "type", typed_annotation); + "fielddef", FieldDefinition(options, field), "comment", + FieldComments(field, bytes_mode), "type", typed_annotation); } - printer->Print( - "$class$.prototype.$gettername$ = function() {\n", - "class", GetMessagePath(options, field->containing_type()), - "gettername", "get" + JSGetterName(options, field)); + printer->Print("$class$.prototype.$gettername$ = function() {\n", "class", + GetMessagePath(options, field->containing_type()), + "gettername", "get" + JSGetterName(options, field)); printer->Annotate("gettername", field); if (untyped) { - printer->Print( - " return "); + printer->Print(" return "); } else { - printer->Print( - " return /** @type {$type$} */ (", - "type", typed_annotation); + printer->Print(" return /** @type {$type$} */ (", "type", + typed_annotation); } bool use_default = !ReturnsNullWhenUnset(options, field); @@ -2630,11 +2765,10 @@ void Generator::GenerateClassField(const GeneratorOptions& options, } else { printer->Print( "/** @param {$optionaltype$} value$returndoc$ */\n", "optionaltype", - JSFieldTypeAnnotation( - options, field, - /* is_setter_argument = */ true, - /* force_present = */ false, - /* singular_if_not_packed = */ false), + JSFieldTypeAnnotation(options, field, + /* is_setter_argument = */ true, + /* force_present = */ false, + /* singular_if_not_packed = */ false), "returndoc", JSReturnDoc(options, field)); } @@ -2687,7 +2821,6 @@ void Generator::GenerateClassField(const GeneratorOptions& options, "returndoc", JSReturnDoc(options, field)); } - if (field->is_repeated()) { GenerateRepeatedPrimitiveHelperMethods(options, printer, field, untyped); } @@ -2695,47 +2828,70 @@ void Generator::GenerateClassField(const GeneratorOptions& options, // Generate clearFoo() method for map fields, repeated fields, and other // fields with presence. - if (IsMap(options, field)) { + if (field->is_map()) { + // clang-format off printer->Print( + "/**\n" + " * Clears values from the map. The map will be non-null." + "$returndoc$\n" + " */\n" "$class$.prototype.$clearername$ = function() {\n" " this.$gettername$().clear();$returnvalue$\n" "};\n" "\n" "\n", + "returndoc", JSReturnDoc(options, field), "class", GetMessagePath(options, field->containing_type()), "clearername", "clear" + JSGetterName(options, field), "gettername", "get" + JSGetterName(options, field), "returnvalue", JSReturnClause(field)); + // clang-format on printer->Annotate("clearername", field); } else if (field->is_repeated() || (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && !field->is_required())) { // Fields where we can delegate to the regular setter. + // clang-format off printer->Print( + "/**\n" + " * $jsdoc$$returndoc$\n" + " */\n" "$class$.prototype.$clearername$ = function() {\n" " this.$settername$($clearedvalue$);$returnvalue$\n" "};\n" "\n" "\n", + "jsdoc", field->is_repeated() + ? "Clears the list making it empty but non-null." + : "Clears the message field making it undefined.", + "returndoc", JSReturnDoc(options, field), "class", GetMessagePath(options, field->containing_type()), "clearername", "clear" + JSGetterName(options, field), "settername", "set" + JSGetterName(options, field), "clearedvalue", (field->is_repeated() ? "[]" : "undefined"), "returnvalue", JSReturnClause(field)); + // clang-format on printer->Annotate("clearername", field); } else if (HasFieldPresence(options, field)) { // Fields where we can't delegate to the regular setter because it doesn't // accept "undefined" as an argument. + // clang-format off printer->Print( + "/**\n" + " * Clears the field making it undefined.$returndoc$\n" + " */\n" "$class$.prototype.$clearername$ = function() {\n" " jspb.Message.set$maybeoneof$Field(this, " "$index$$maybeoneofgroup$, ", + "returndoc", JSReturnDoc(options, field), "class", GetMessagePath(options, field->containing_type()), "clearername", "clear" + JSGetterName(options, field), "maybeoneof", (field->containing_oneof() ? "Oneof" : ""), - "maybeoneofgroup", (field->containing_oneof() ? - (", " + JSOneofArray(options, field)) : ""), + "maybeoneofgroup", (field->containing_oneof() + ? (", " + JSOneofArray(options, field)) + : ""), "index", JSFieldIndex(field)); + // clang-format on printer->Annotate("clearername", field); printer->Print( "$clearedvalue$);$returnvalue$\n" @@ -2750,16 +2906,15 @@ void Generator::GenerateClassField(const GeneratorOptions& options, printer->Print( "/**\n" " * Returns whether this field is set.\n" - " * @return {!boolean}\n" + " * @return {boolean}\n" " */\n" "$class$.prototype.$hasername$ = function() {\n" " return jspb.Message.getField(this, $index$) != null;\n" "};\n" "\n" "\n", - "class", GetMessagePath(options, field->containing_type()), - "hasername", "has" + JSGetterName(options, field), - "index", JSFieldIndex(field)); + "class", GetMessagePath(options, field->containing_type()), "hasername", + "has" + JSGetterName(options, field), "index", JSFieldIndex(field)); printer->Annotate("hasername", field); } } @@ -2770,7 +2925,7 @@ void Generator::GenerateRepeatedPrimitiveHelperMethods( // clang-format off printer->Print( "/**\n" - " * @param {!$optionaltype$} value\n" + " * @param {$optionaltype$} value\n" " * @param {number=} opt_index$returndoc$\n" " */\n" "$class$.prototype.$addername$ = function(value, opt_index) {\n" @@ -2778,7 +2933,14 @@ void Generator::GenerateRepeatedPrimitiveHelperMethods( "class", GetMessagePath(options, field->containing_type()), "addername", "add" + JSGetterName(options, field, BYTES_DEFAULT, /* drop_list = */ true), - "optionaltype", JSTypeName(options, field, BYTES_DEFAULT), + "optionaltype", + JSFieldTypeAnnotation( + options, field, + /* is_setter_argument = */ false, + /* force_present = */ true, + /* singular_if_not_packed = */ false, + BYTES_DEFAULT, + /* force_singular = */ true), "index", JSFieldIndex(field), "returndoc", JSReturnDoc(options, field)); printer->Annotate("addername", field); @@ -2805,14 +2967,15 @@ void Generator::GenerateRepeatedMessageHelperMethods( " * @param {number=} opt_index\n" " * @return {!$optionaltype$}\n" " */\n" - "$class$.prototype.add$name$ = function(opt_value, opt_index) {\n" + "$class$.prototype.$addername$ = function(opt_value, opt_index) {\n" " return jspb.Message.addTo$repeatedtag$WrapperField(", - "optionaltype", JSTypeName(options, field, BYTES_DEFAULT), - "class", GetMessagePath(options, field->containing_type()), - "name", JSGetterName(options, field, BYTES_DEFAULT, - /* drop_list = */ true), + "optionaltype", JSTypeName(options, field, BYTES_DEFAULT), "class", + GetMessagePath(options, field->containing_type()), "addername", + "add" + JSGetterName(options, field, BYTES_DEFAULT, + /* drop_list = */ true), "repeatedtag", (field->is_repeated() ? "Repeated" : "")); + printer->Annotate("addername", field); printer->Print( "this, $index$$oneofgroup$, opt_value, $ctor$, opt_index);\n" "};\n" @@ -2899,38 +3062,40 @@ void Generator::GenerateClassDeserializeBinary(const GeneratorOptions& options, " * @return {!$class$}\n" " */\n" "$class$.deserializeBinaryFromReader = function(msg, reader) {\n" - " while (reader.nextField()) {\n" - " if (reader.isEndGroup()) {\n" - " break;\n" - " }\n" - " var field = reader.getFieldNumber();\n" - " switch (field) {\n", + " while (reader.nextField()) {\n", "class", GetMessagePath(options, desc)); + printer->Print( + " if (reader.isEndGroup()) {\n" + " break;\n" + " }\n" + " var field = reader.getFieldNumber();\n" + " switch (field) {\n"); - for (int i = 0; i < desc->field_count(); i++) { - if (!IgnoreField(desc->field(i))) { - GenerateClassDeserializeBinaryField(options, printer, desc->field(i)); + for (int i = 0; i < desc->field_count(); i++) { + if (!IgnoreField(desc->field(i))) { + GenerateClassDeserializeBinaryField(options, printer, desc->field(i)); + } + } + + printer->Print(" default:\n"); + if (IsExtendable(desc)) { + printer->Print( + " jspb.Message.readBinaryExtension(msg, reader,\n" + " $extobj$Binary,\n" + " $class$.prototype.getExtension,\n" + " $class$.prototype.setExtension);\n" + " break;\n" + " }\n", + "extobj", JSExtensionsObjectName(options, desc->file(), desc), + "class", GetMessagePath(options, desc)); + } else { + printer->Print( + " reader.skipField();\n" + " break;\n" + " }\n"); } - } printer->Print( - " default:\n"); - if (IsExtendable(desc)) { - printer->Print( - " jspb.Message.readBinaryExtension(msg, reader, $extobj$Binary,\n" - " $class$.prototype.getExtension,\n" - " $class$.prototype.setExtension);\n" - " break;\n", - "extobj", JSExtensionsObjectName(options, desc->file(), desc), - "class", GetMessagePath(options, desc)); - } else { - printer->Print( - " reader.skipField();\n" - " break;\n"); - } - - printer->Print( - " }\n" " }\n" " return msg;\n" "};\n" @@ -2939,14 +3104,11 @@ void Generator::GenerateClassDeserializeBinary(const GeneratorOptions& options, } void Generator::GenerateClassDeserializeBinaryField( - const GeneratorOptions& options, - io::Printer* printer, + const GeneratorOptions& options, io::Printer* printer, const FieldDescriptor* field) const { + printer->Print(" case $num$:\n", "num", StrCat(field->number())); - printer->Print(" case $num$:\n", - "num", SimpleItoa(field->number())); - - if (IsMap(options, field)) { + if (field->is_map()) { const FieldDescriptor* key_field = MapFieldKey(field); const FieldDescriptor* value_field = MapFieldValue(field); printer->Print( @@ -2954,20 +3116,20 @@ void Generator::GenerateClassDeserializeBinaryField( " reader.readMessage(value, function(message, reader) {\n", "name", JSGetterName(options, field)); - printer->Print(" jspb.Map.deserializeBinary(message, reader, " - "$keyReaderFn$, $valueReaderFn$", - "keyReaderFn", JSBinaryReaderMethodName(options, key_field), - "valueReaderFn", JSBinaryReaderMethodName(options, value_field)); + printer->Print( + " jspb.Map.deserializeBinary(message, reader, " + "$keyReaderFn$, $valueReaderFn$", + "keyReaderFn", JSBinaryReaderMethodName(options, key_field), + "valueReaderFn", JSBinaryReaderMethodName(options, value_field)); if (value_field->type() == FieldDescriptor::TYPE_MESSAGE) { printer->Print(", $messageType$.deserializeBinaryFromReader", - "messageType", GetMessagePath(options, value_field->message_type())); + "messageType", + GetMessagePath(options, value_field->message_type())); } else { printer->Print(", null"); } - printer->Print(", $defaultKey$", - "defaultKey", JSFieldDefault(key_field) - ); + printer->Print(", $defaultKey$", "defaultKey", JSFieldDefault(key_field)); printer->Print(");\n"); printer->Print(" });\n"); } else { @@ -2976,18 +3138,19 @@ void Generator::GenerateClassDeserializeBinaryField( " var value = new $fieldclass$;\n" " reader.read$msgOrGroup$($grpfield$value," "$fieldclass$.deserializeBinaryFromReader);\n", - "fieldclass", SubmessageTypeRef(options, field), - "msgOrGroup", (field->type() == FieldDescriptor::TYPE_GROUP) ? - "Group" : "Message", - "grpfield", (field->type() == FieldDescriptor::TYPE_GROUP) ? - (SimpleItoa(field->number()) + ", ") : ""); + "fieldclass", SubmessageTypeRef(options, field), "msgOrGroup", + (field->type() == FieldDescriptor::TYPE_GROUP) ? "Group" : "Message", + "grpfield", + (field->type() == FieldDescriptor::TYPE_GROUP) + ? (StrCat(field->number()) + ", ") + : ""); } else { printer->Print( " var value = /** @type {$fieldtype$} */ " "(reader.read$reader$());\n", - "fieldtype", JSFieldTypeAnnotation(options, field, false, true, - /* singular_if_not_packed */ true, - BYTES_U8), + "fieldtype", + JSFieldTypeAnnotation(options, field, false, true, + /* singular_if_not_packed */ true, BYTES_U8), "reader", JSBinaryReadWriteMethodName(field, /* is_writer = */ false)); } @@ -3000,9 +3163,8 @@ void Generator::GenerateClassDeserializeBinaryField( // Singular fields, and packed repeated fields, receive a |value| either // as the field's value or as the array of all the field's values; set // this as the field's value directly. - printer->Print( - " msg.set$name$(value);\n", - "name", JSGetterName(options, field)); + printer->Print(" msg.set$name$(value);\n", "name", + JSGetterName(options, field)); } } @@ -3046,8 +3208,8 @@ void Generator::GenerateClassSerializeBinary(const GeneratorOptions& options, printer->Print( " jspb.Message.serializeBinaryExtensions(message, writer,\n" " $extobj$Binary, $class$.prototype.getExtension);\n", - "extobj", JSExtensionsObjectName(options, desc->file(), desc), - "class", GetMessagePath(options, desc)); + "extobj", JSExtensionsObjectName(options, desc->file(), desc), "class", + GetMessagePath(options, desc)); } printer->Print( @@ -3057,42 +3219,37 @@ void Generator::GenerateClassSerializeBinary(const GeneratorOptions& options, } void Generator::GenerateClassSerializeBinaryField( - const GeneratorOptions& options, - io::Printer* printer, + const GeneratorOptions& options, io::Printer* printer, const FieldDescriptor* field) const { if (HasFieldPresence(options, field) && field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) { - string typed_annotation = JSFieldTypeAnnotation( - options, field, - /* is_setter_argument = */ false, - /* force_present = */ false, - /* singular_if_not_packed = */ false, - /* bytes_mode = */ BYTES_DEFAULT); + std::string typed_annotation = + JSFieldTypeAnnotation(options, field, + /* is_setter_argument = */ false, + /* force_present = */ false, + /* singular_if_not_packed = */ false, + /* bytes_mode = */ BYTES_DEFAULT); printer->Print( " f = /** @type {$type$} */ " "(jspb.Message.getField(message, $index$));\n", - "index", JSFieldIndex(field), - "type", typed_annotation); + "index", JSFieldIndex(field), "type", typed_annotation); } else { printer->Print( - " f = message.get$name$($nolazy$);\n", - "name", JSGetterName(options, field, BYTES_U8), + " f = message.get$name$($nolazy$);\n", "name", + JSGetterName(options, field, BYTES_U8), // No lazy creation for maps containers -- fastpath the empty case. - "nolazy", IsMap(options, field) ? "true" : ""); + "nolazy", field->is_map() ? "true" : ""); } // Print an `if (condition)` statement that evaluates to true if the field // goes on the wire. - if (IsMap(options, field)) { - printer->Print( - " if (f && f.getLength() > 0) {\n"); + if (field->is_map()) { + printer->Print(" if (f && f.getLength() > 0) {\n"); } else if (field->is_repeated()) { - printer->Print( - " if (f.length > 0) {\n"); + printer->Print(" if (f.length > 0) {\n"); } else { if (HasFieldPresence(options, field)) { - printer->Print( - " if (f != null) {\n"); + printer->Print(" if (f != null) {\n"); } else { // No field presence: serialize onto the wire only if value is // non-default. Defaults are documented here: @@ -3117,16 +3274,13 @@ void Generator::GenerateClassSerializeBinaryField( case FieldDescriptor::CPPTYPE_ENUM: case FieldDescriptor::CPPTYPE_FLOAT: case FieldDescriptor::CPPTYPE_DOUBLE: - printer->Print( - " if (f !== 0.0) {\n"); + printer->Print(" if (f !== 0.0) {\n"); break; case FieldDescriptor::CPPTYPE_BOOL: - printer->Print( - " if (f) {\n"); + printer->Print(" if (f) {\n"); break; case FieldDescriptor::CPPTYPE_STRING: - printer->Print( - " if (f.length > 0) {\n"); + printer->Print(" if (f.length > 0) {\n"); break; default: assert(false); @@ -3136,19 +3290,19 @@ void Generator::GenerateClassSerializeBinaryField( } // Write the field on the wire. - if (IsMap(options, field)) { + if (field->is_map()) { const FieldDescriptor* key_field = MapFieldKey(field); const FieldDescriptor* value_field = MapFieldValue(field); printer->Print( " f.serializeBinary($index$, writer, " - "$keyWriterFn$, $valueWriterFn$", - "index", SimpleItoa(field->number()), - "keyWriterFn", JSBinaryWriterMethodName(options, key_field), - "valueWriterFn", JSBinaryWriterMethodName(options, value_field)); + "$keyWriterFn$, $valueWriterFn$", + "index", StrCat(field->number()), "keyWriterFn", + JSBinaryWriterMethodName(options, key_field), "valueWriterFn", + JSBinaryWriterMethodName(options, value_field)); if (value_field->type() == FieldDescriptor::TYPE_MESSAGE) { - printer->Print(", $messageType$.serializeBinaryToWriter", - "messageType", GetMessagePath(options, value_field->message_type())); + printer->Print(", $messageType$.serializeBinaryToWriter", "messageType", + GetMessagePath(options, value_field->message_type())); } printer->Print(");\n"); @@ -3158,25 +3312,23 @@ void Generator::GenerateClassSerializeBinaryField( " $index$,\n" " f", "method", JSBinaryReadWriteMethodName(field, /* is_writer = */ true), - "index", SimpleItoa(field->number())); + "index", StrCat(field->number())); if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && - !IsMap(options, field)) { + !field->is_map()) { printer->Print( ",\n" " $submsg$.serializeBinaryToWriter\n", - "submsg", SubmessageTypeRef(options, field)); + "submsg", SubmessageTypeRef(options, field)); } else { printer->Print("\n"); } - printer->Print( - " );\n"); + printer->Print(" );\n"); } // Close the `if`. - printer->Print( - " }\n"); + printer->Print(" }\n"); } void Generator::GenerateEnum(const GeneratorOptions& options, @@ -3187,17 +3339,16 @@ void Generator::GenerateEnum(const GeneratorOptions& options, " * @enum {number}\n" " */\n" "$enumprefix$$name$ = {\n", - "enumprefix", GetEnumPathPrefix(options, enumdesc), - "name", enumdesc->name()); + "enumprefix", GetEnumPathPrefix(options, enumdesc), "name", + enumdesc->name()); printer->Annotate("name", enumdesc); for (int i = 0; i < enumdesc->value_count(); i++) { const EnumValueDescriptor* value = enumdesc->value(i); - printer->Print( - " $name$: $value$$comma$\n", - "name", ToEnumCase(value->name()), - "value", SimpleItoa(value->number()), - "comma", (i == enumdesc->value_count() - 1) ? "" : ","); + printer->Print(" $name$: $value$$comma$\n", "name", + ToEnumCase(value->name()), "value", + StrCat(value->number()), "comma", + (i == enumdesc->value_count() - 1) ? "" : ","); printer->Annotate("name", value); } @@ -3209,12 +3360,12 @@ void Generator::GenerateEnum(const GeneratorOptions& options, void Generator::GenerateExtension(const GeneratorOptions& options, io::Printer* printer, const FieldDescriptor* field) const { - string extension_scope = + std::string extension_scope = (field->extension_scope() ? GetMessagePath(options, field->extension_scope()) - : GetFilePath(options, field->file())); + : GetNamespace(options, field->file())); - const string extension_object_name = JSObjectFieldName(options, field); + const std::string extension_object_name = JSObjectFieldName(options, field); printer->Print( "\n" "/**\n" @@ -3223,14 +3374,12 @@ void Generator::GenerateExtension(const GeneratorOptions& options, " * @type {!jspb.ExtensionFieldInfo<$extensionType$>}\n" " */\n" "$class$.$name$ = new jspb.ExtensionFieldInfo(\n", - "nameInComment", extension_object_name, - "name", extension_object_name, - "class", extension_scope, - "extensionType", JSFieldTypeAnnotation( - options, field, - /* is_setter_argument = */ false, - /* force_present = */ true, - /* singular_if_not_packed = */ false)); + "nameInComment", extension_object_name, "name", extension_object_name, + "class", extension_scope, "extensionType", + JSFieldTypeAnnotation(options, field, + /* is_setter_argument = */ false, + /* force_present = */ true, + /* singular_if_not_packed = */ false)); printer->Annotate("name", field); printer->Print( " $index$,\n" @@ -3240,13 +3389,15 @@ void Generator::GenerateExtension(const GeneratorOptions& options, "!Object} */ (\n" " $toObject$),\n" " $repeated$);\n", - "index", SimpleItoa(field->number()), - "name", extension_object_name, - "ctor", (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ? - SubmessageTypeRef(options, field) : string("null")), - "toObject", (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ? - (SubmessageTypeRef(options, field) + ".toObject") : - string("null")), + "index", StrCat(field->number()), "name", extension_object_name, + "ctor", + (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE + ? SubmessageTypeRef(options, field) + : std::string("null")), + "toObject", + (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE + ? (SubmessageTypeRef(options, field) + ".toObject") + : std::string("null")), "repeated", (field->is_repeated() ? "1" : "0")); printer->Print( @@ -3259,7 +3410,7 @@ void Generator::GenerateExtension(const GeneratorOptions& options, " $binaryMessageDeserializeFn$,\n", "extendName", JSExtensionsObjectName(options, field->file(), field->containing_type()), - "index", SimpleItoa(field->number()), "class", extension_scope, "name", + "index", StrCat(field->number()), "class", extension_scope, "name", extension_object_name, "binaryReaderFn", JSBinaryReaderMethodName(options, field), "binaryWriterFn", JSBinaryWriterMethodName(options, field), "binaryMessageSerializeFn", @@ -3279,16 +3430,15 @@ void Generator::GenerateExtension(const GeneratorOptions& options, "// toObject() will function correctly.\n" "$extendName$[$index$] = $class$.$name$;\n" "\n", - "extendName", JSExtensionsObjectName(options, field->file(), - field->containing_type()), - "index", SimpleItoa(field->number()), - "class", extension_scope, - "name", extension_object_name); + "extendName", + JSExtensionsObjectName(options, field->file(), field->containing_type()), + "index", StrCat(field->number()), "class", extension_scope, "name", + extension_object_name); } bool GeneratorOptions::ParseFromOptions( - const std::vector< std::pair< string, string > >& options, - string* error) { + const std::vector >& options, + std::string* error) { for (int i = 0; i < options.size(); i++) { if (options[i].first == "add_require_for_enums") { if (options[i].second != "") { @@ -3325,6 +3475,8 @@ bool GeneratorOptions::ParseFromOptions( import_style = kImportClosure; } else if (options[i].second == "commonjs") { import_style = kImportCommonJs; + } else if (options[i].second == "commonjs_strict") { + import_style = kImportCommonJsStrict; } else if (options[i].second == "browser") { import_style = kImportBrowser; } else if (options[i].second == "es6") { @@ -3384,13 +3536,12 @@ GeneratorOptions::OutputMode GeneratorOptions::output_mode() const { return kEverythingInOneFile; } - // Otherwise, we create one output file per type. - return kOneOutputFilePerType; + // Otherwise, we create one output file per SCC. + return kOneOutputFilePerSCC; } void Generator::GenerateFilesInDepOrder( - const GeneratorOptions& options, - io::Printer* printer, + const GeneratorOptions& options, io::Printer* printer, const std::vector& files) const { // Build a std::set over all files so that the DFS can detect when it recurses // into a dep not specified in the user's command line. @@ -3403,10 +3554,8 @@ void Generator::GenerateFilesInDepOrder( } void Generator::GenerateFileAndDeps( - const GeneratorOptions& options, - io::Printer* printer, - const FileDescriptor* root, - std::set* all_files, + const GeneratorOptions& options, io::Printer* printer, + const FileDescriptor* root, std::set* all_files, std::set* generated) const { // Skip if already generated. if (generated->find(root) != generated->end()) { @@ -3428,28 +3577,65 @@ void Generator::GenerateFileAndDeps( } } +bool Generator::GenerateFile(const FileDescriptor* file, + const GeneratorOptions& options, + GeneratorContext* context, + bool use_short_name) const { + std::string filename = + options.output_dir + "/" + + GetJSFilename(options, use_short_name + ? file->name().substr(file->name().rfind('/')) + : file->name()); + std::unique_ptr output(context->Open(filename)); + GOOGLE_CHECK(output); + GeneratedCodeInfo annotations; + io::AnnotationProtoCollector annotation_collector( + &annotations); + io::Printer printer(output.get(), '$', + options.annotate_code ? &annotation_collector : nullptr); + + GenerateFile(options, &printer, file); + + if (printer.failed()) { + return false; + } + + if (options.annotate_code) { + EmbedCodeAnnotations(annotations, &printer); + } + + return true; +} + void Generator::GenerateFile(const GeneratorOptions& options, io::Printer* printer, const FileDescriptor* file) const { GenerateHeader(options, printer); // Generate "require" statements. - if (options.import_style == GeneratorOptions::kImportCommonJs) { + if ((options.import_style == GeneratorOptions::kImportCommonJs || + options.import_style == GeneratorOptions::kImportCommonJsStrict)) { printer->Print("var jspb = require('google-protobuf');\n"); printer->Print("var goog = jspb;\n"); - printer->Print("var global = Function('return this')();\n\n"); + + // Do not use global scope in strict mode + if (options.import_style == GeneratorOptions::kImportCommonJsStrict) { + printer->Print("var proto = {};\n\n"); + } else { + printer->Print("var global = Function('return this')();\n\n"); + } for (int i = 0; i < file->dependency_count(); i++) { - const string& name = file->dependency(i)->name(); + const std::string& name = file->dependency(i)->name(); printer->Print( - "var $alias$ = require('$file$');\n", - "alias", ModuleAlias(name), - "file", + "var $alias$ = require('$file$');\n" + "goog.object.extend(proto, $alias$);\n", + "alias", ModuleAlias(name), "file", GetRootPath(file->name(), name) + GetJSFilename(options, name)); } } - std::set provided; + std::set provided; std::set extensions; for (int i = 0; i < file->extension_count(); i++) { // We honor the jspb::ignore option here only when working with @@ -3459,7 +3645,7 @@ void Generator::GenerateFile(const GeneratorOptions& options, IgnoreField(file->extension(i))) { continue; } - provided.insert(GetFilePath(options, file) + "." + + provided.insert(GetNamespace(options, file) + "." + JSObjectFieldName(options, file->extension(i))); extensions.insert(file->extension(i)); } @@ -3481,14 +3667,19 @@ void Generator::GenerateFile(const GeneratorOptions& options, GenerateExtension(options, printer, *it); } - if (options.import_style == GeneratorOptions::kImportCommonJs) { - printer->Print("goog.object.extend(exports, $package$);\n", - "package", GetFilePath(options, file)); + // if provided is empty, do not export anything + if (options.import_style == GeneratorOptions::kImportCommonJs && + !provided.empty()) { + printer->Print("goog.object.extend(exports, $package$);\n", "package", + GetNamespace(options, file)); + } else if (options.import_style == GeneratorOptions::kImportCommonJsStrict) { + printer->Print("goog.object.extend(exports, proto);\n", "package", + GetNamespace(options, file)); } // Emit well-known type methods. for (FileToc* toc = well_known_types_js; toc->name != NULL; toc++) { - string name = string("google/protobuf/") + toc->name; + std::string name = std::string("google/protobuf/") + toc->name; if (name == StripProto(file->name()) + ".js") { printer->Print(toc->data); } @@ -3496,10 +3687,10 @@ void Generator::GenerateFile(const GeneratorOptions& options, } bool Generator::GenerateAll(const std::vector& files, - const string& parameter, + const std::string& parameter, GeneratorContext* context, - string* error) const { - std::vector< std::pair< string, string > > option_pairs; + std::string* error) const { + std::vector > option_pairs; ParseGeneratorParameter(parameter, &option_pairs); GeneratorOptions options; if (!options.ParseFromOptions(option_pairs, error)) { @@ -3509,8 +3700,8 @@ bool Generator::GenerateAll(const std::vector& files, if (options.output_mode() == GeneratorOptions::kEverythingInOneFile) { // All output should go in a single file. - string filename = options.output_dir + "/" + options.library + - options.GetFileNameExtension(); + std::string filename = options.output_dir + "/" + options.library + + options.GetFileNameExtension(); std::unique_ptr output(context->Open(filename)); GOOGLE_CHECK(output.get()); io::Printer printer(output.get(), '$'); @@ -3527,7 +3718,7 @@ bool Generator::GenerateAll(const std::vector& files, GenerateHeader(options, &printer); - std::set provided; + std::set provided; FindProvides(options, &printer, files, &provided); FindProvidesForFields(options, &printer, extensions, &provided); GenerateProvides(options, &printer, &provided); @@ -3545,55 +3736,102 @@ bool Generator::GenerateAll(const std::vector& files, if (printer.failed()) { return false; } - } else if (options.output_mode() == GeneratorOptions::kOneOutputFilePerType) { - std::set allowed_set; - if (!GenerateJspbAllowedSet(options, files, &allowed_set, error)) { + } else if (options.output_mode() == GeneratorOptions::kOneOutputFilePerSCC) { + std::set have_printed; + SCCAnalyzer analyzer; + std::map allowed_map; + if (!GenerateJspbAllowedMap(options, files, &allowed_map, &analyzer, + error)) { return false; } + bool generated = false; for (int i = 0; i < files.size(); i++) { const FileDescriptor* file = files[i]; + // Force well known type to generate in a whole file. + if (IsWellKnownTypeFile(file)) { + if (!GenerateFile(file, options, context, true)) { + return false; + } + generated = true; + continue; + } for (int j = 0; j < file->message_type_count(); j++) { const Descriptor* desc = file->message_type(j); - if (allowed_set.count(desc) == 0) { + if (have_printed.count(desc) || + allowed_map.count(analyzer.GetSCC(desc)) == 0) { continue; } - string filename = GetMessageFileName(options, desc); + generated = true; + const SCC* scc = analyzer.GetSCC(desc); + const std::string& filename = allowed_map[scc]; std::unique_ptr output( context->Open(filename)); GOOGLE_CHECK(output.get()); - io::Printer printer(output.get(), '$'); + GeneratedCodeInfo annotations; + io::AnnotationProtoCollector annotation_collector( + &annotations); + io::Printer printer( + output.get(), '$', + options.annotate_code ? &annotation_collector : nullptr); GenerateHeader(options, &printer); - std::set provided; - FindProvidesForMessage(options, &printer, desc, &provided); + std::set provided; + for (auto one_desc : scc->descriptors) { + if (one_desc->containing_type() == nullptr) { + FindProvidesForMessage(options, &printer, one_desc, &provided); + } + } GenerateProvides(options, &printer, &provided); GenerateTestOnly(options, &printer); - GenerateRequiresForMessage(options, &printer, desc, &provided); + GenerateRequiresForSCC(options, &printer, scc, &provided); - GenerateClass(options, &printer, desc); + for (auto one_desc : scc->descriptors) { + if (one_desc->containing_type() == nullptr) { + GenerateClassConstructorAndDeclareExtensionFieldInfo( + options, &printer, one_desc); + } + } + for (auto one_desc : scc->descriptors) { + if (one_desc->containing_type() == nullptr) { + GenerateClass(options, &printer, one_desc); + } + } + + for (auto one_desc : scc->descriptors) { + have_printed.insert(one_desc); + } if (printer.failed()) { return false; } + if (options.annotate_code) { + EmbedCodeAnnotations(annotations, &printer); + } } for (int j = 0; j < file->enum_type_count(); j++) { const EnumDescriptor* enumdesc = file->enum_type(j); - if (allowed_set.count(enumdesc) == 0) { + if (allowed_map.count(enumdesc) == 0) { continue; } - string filename = GetEnumFileName(options, enumdesc); + generated = true; + const std::string& filename = allowed_map[enumdesc]; std::unique_ptr output( context->Open(filename)); GOOGLE_CHECK(output.get()); - io::Printer printer(output.get(), '$'); + GeneratedCodeInfo annotations; + io::AnnotationProtoCollector annotation_collector( + &annotations); + io::Printer printer( + output.get(), '$', + options.annotate_code ? &annotation_collector : nullptr); GenerateHeader(options, &printer); - std::set provided; + std::set provided; FindProvidesForEnum(options, &printer, enumdesc, &provided); GenerateProvides(options, &printer, &provided); GenerateTestOnly(options, &printer); @@ -3603,20 +3841,29 @@ bool Generator::GenerateAll(const std::vector& files, if (printer.failed()) { return false; } + if (options.annotate_code) { + EmbedCodeAnnotations(annotations, &printer); + } } // File-level extensions (message-level extensions are generated under // the enclosing message). - if (allowed_set.count(file) == 1) { - string filename = GetExtensionFileName(options, file); + if (allowed_map.count(file) == 1) { + generated = true; + const std::string& filename = allowed_map[file]; std::unique_ptr output( context->Open(filename)); GOOGLE_CHECK(output.get()); - io::Printer printer(output.get(), '$'); + GeneratedCodeInfo annotations; + io::AnnotationProtoCollector annotation_collector( + &annotations); + io::Printer printer( + output.get(), '$', + options.annotate_code ? &annotation_collector : nullptr); GenerateHeader(options, &printer); - std::set provided; + std::set provided; std::vector fields; for (int j = 0; j < files[i]->extension_count(); j++) { @@ -3635,34 +3882,25 @@ bool Generator::GenerateAll(const std::vector& files, GenerateExtension(options, &printer, files[i]->extension(j)); } } + if (options.annotate_code) { + EmbedCodeAnnotations(annotations, &printer); + } } } + if (!generated) { + std::string filename = options.output_dir + "/" + + "empty_no_content_void_file" + + options.GetFileNameExtension(); + std::unique_ptr output(context->Open(filename)); + } } else /* options.output_mode() == kOneOutputFilePerInputFile */ { // Generate one output file per input (.proto) file. for (int i = 0; i < files.size(); i++) { - const google::protobuf::FileDescriptor* file = files[i]; - - string filename = - options.output_dir + "/" + GetJSFilename(options, file->name()); - std::unique_ptr output(context->Open(filename)); - GOOGLE_CHECK(output.get()); - GeneratedCodeInfo annotations; - io::AnnotationProtoCollector annotation_collector( - &annotations); - io::Printer printer(output.get(), '$', - options.annotate_code ? &annotation_collector : NULL); - - - GenerateFile(options, &printer, file); - - if (printer.failed()) { + const FileDescriptor* file = files[i]; + if (!GenerateFile(file, options, context, false)) { return false; } - - if (options.annotate_code) { - EmbedCodeAnnotations(annotations, &printer); - } } } return true; diff --git a/third_party/protobuf/src/google/protobuf/compiler/js/js_generator.h b/third_party/protobuf/src/google/protobuf/compiler/js/js_generator.h old mode 100755 new mode 100644 index 3cc60e22..7895b0b0 --- a/third_party/protobuf/src/google/protobuf/compiler/js/js_generator.h +++ b/third_party/protobuf/src/google/protobuf/compiler/js/js_generator.h @@ -33,13 +33,16 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_JS_GENERATOR_H__ #define GOOGLE_PROTOBUF_COMPILER_JS_GENERATOR_H__ -#include #include +#include #include #include +#include #include +#include + namespace google { namespace protobuf { @@ -49,24 +52,27 @@ class FieldDescriptor; class OneofDescriptor; class FileDescriptor; -namespace io { class Printer; } +namespace io { +class Printer; +} namespace compiler { namespace js { struct GeneratorOptions { // Output path. - string output_dir; + std::string output_dir; // Namespace prefix. - string namespace_prefix; + std::string namespace_prefix; // Enable binary-format support? bool binary; // What style of imports should be used. enum ImportStyle { - kImportClosure, // goog.require() - kImportCommonJs, // require() - kImportBrowser, // no import statements - kImportEs6, // import { member } from '' + kImportClosure, // goog.require() + kImportCommonJs, // require() + kImportCommonJsStrict, // require() with no global export + kImportBrowser, // no import statements + kImportEs6, // import { member } from '' } import_style; GeneratorOptions() @@ -83,11 +89,11 @@ struct GeneratorOptions { annotate_code(false) {} bool ParseFromOptions( - const std::vector< std::pair< string, string > >& options, - string* error); + const std::vector >& options, + std::string* error); // Returns the file name extension to use for generated code. - string GetFileNameExtension() const { + std::string GetFileNameExtension() const { return import_style == kImportClosure ? extension : "_pb.js"; } @@ -95,7 +101,7 @@ struct GeneratorOptions { // Create an output file for each input .proto file. kOneOutputFilePerInputFile, // Create an output file for each type. - kOneOutputFilePerType, + kOneOutputFilePerSCC, // Put everything in a single file named by the library option. kEverythingInOneFile, }; @@ -112,15 +118,18 @@ struct GeneratorOptions { bool testonly; // Create a library with name _lib.js rather than a separate .js file // per type? - string library; + std::string library; // Error if there are two types that would generate the same output file? bool error_on_name_conflict; // The extension to use for output file names. - string extension; + std::string extension; // Create a separate output file for each input file? bool one_output_file_per_input_file; - // If true, we should build .meta files that contain annotations for - // generated code. See GeneratedCodeInfo in descriptor.proto. + // If true, we should append annotations as commen on the last line for + // generated .js file. Annotations used by tools like https://kythe.io + // to provide cross-references between .js and .proto files. Annotations + // are enced as base64 proto of GeneratedCodeInfo message (see + // descriptor.proto). bool annotate_code; }; @@ -128,15 +137,14 @@ struct GeneratorOptions { // header. If you create your own protocol compiler binary and you want it to // support JavaScript output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT Generator : public CodeGenerator { +class PROTOC_EXPORT Generator : public CodeGenerator { public: Generator() {} virtual ~Generator() {} virtual bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const { + const std::string& parameter, GeneratorContext* context, + std::string* error) const { *error = "Unimplemented Generate() method. Call GenerateAll() instead."; return false; } @@ -144,40 +152,34 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { virtual bool HasGenerateAll() const { return true; } virtual bool GenerateAll(const std::vector& files, - const string& parameter, - GeneratorContext* context, - string* error) const; + const std::string& parameter, + GeneratorContext* context, std::string* error) const; private: void GenerateHeader(const GeneratorOptions& options, io::Printer* printer) const; // Generate goog.provides() calls. - void FindProvides(const GeneratorOptions& options, - io::Printer* printer, + void FindProvides(const GeneratorOptions& options, io::Printer* printer, const std::vector& file, - std::set* provided) const; + std::set* provided) const; void FindProvidesForFile(const GeneratorOptions& options, - io::Printer* printer, - const FileDescriptor* file, - std::set* provided) const; + io::Printer* printer, const FileDescriptor* file, + std::set* provided) const; void FindProvidesForMessage(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc, - std::set* provided) const; + io::Printer* printer, const Descriptor* desc, + std::set* provided) const; void FindProvidesForEnum(const GeneratorOptions& options, - io::Printer* printer, - const EnumDescriptor* enumdesc, - std::set* provided) const; + io::Printer* printer, const EnumDescriptor* enumdesc, + std::set* provided) const; // For extension fields at file scope. void FindProvidesForFields(const GeneratorOptions& options, io::Printer* printer, const std::vector& fields, - std::set* provided) const; + std::set* provided) const; // Print the goog.provides() found by the methods above. - void GenerateProvides(const GeneratorOptions& options, - io::Printer* printer, - std::set* provided) const; + void GenerateProvides(const GeneratorOptions& options, io::Printer* printer, + std::set* provided) const; // Generate goog.setTestOnly() if indicated. void GenerateTestOnly(const GeneratorOptions& options, @@ -187,37 +189,40 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { void GenerateRequiresForLibrary( const GeneratorOptions& options, io::Printer* printer, const std::vector& files, - std::set* provided) const; - void GenerateRequiresForMessage(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc, - std::set* provided) const; + std::set* provided) const; + void GenerateRequiresForSCC(const GeneratorOptions& options, + io::Printer* printer, const SCC* scc, + std::set* provided) const; // For extension fields at file scope. void GenerateRequiresForExtensions( const GeneratorOptions& options, io::Printer* printer, const std::vector& fields, - std::set* provided) const; + std::set* provided) const; void GenerateRequiresImpl(const GeneratorOptions& options, - io::Printer* printer, std::set* required, - std::set* forwards, - std::set* provided, bool require_jspb, + io::Printer* printer, + std::set* required, + std::set* forwards, + std::set* provided, bool require_jspb, bool require_extension, bool require_map) const; void FindRequiresForMessage(const GeneratorOptions& options, const Descriptor* desc, - std::set* required, - std::set* forwards, + std::set* required, + std::set* forwards, bool* have_message) const; void FindRequiresForField(const GeneratorOptions& options, const FieldDescriptor* field, - std::set* required, - std::set* forwards) const; + std::set* required, + std::set* forwards) const; void FindRequiresForExtension(const GeneratorOptions& options, const FieldDescriptor* field, - std::set* required, - std::set* forwards) const; - - void GenerateFile(const GeneratorOptions& options, - io::Printer* printer, + std::set* required, + std::set* forwards) const; + // Generate all things in a proto file into one file. + // If use_short_name is true, the generated file's name will only be short + // name that without directory, otherwise filename equals file->name() + bool GenerateFile(const FileDescriptor* file, const GeneratorOptions& options, + GeneratorContext* context, bool use_short_name) const; + void GenerateFile(const GeneratorOptions& options, io::Printer* printer, const FileDescriptor* file) const; // Generate definitions for all message classes and enums in all files, @@ -227,8 +232,7 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { const std::vector& file) const; // Helper for above. void GenerateFileAndDeps(const GeneratorOptions& options, - io::Printer* printer, - const FileDescriptor* root, + io::Printer* printer, const FileDescriptor* root, std::set* all_files, std::set* generated) const; @@ -243,8 +247,7 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { bool use_default) const; // Generate definition for one class. - void GenerateClass(const GeneratorOptions& options, - io::Printer* printer, + void GenerateClass(const GeneratorOptions& options, io::Printer* printer, const Descriptor* desc) const; void GenerateClassConstructor(const GeneratorOptions& options, io::Printer* printer, @@ -252,12 +255,17 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { void GenerateClassFieldInfo(const GeneratorOptions& options, io::Printer* printer, const Descriptor* desc) const; - void GenerateClassXid(const GeneratorOptions& options, - io::Printer* printer, + void GenerateClassConstructorAndDeclareExtensionFieldInfo( + const GeneratorOptions& options, io::Printer* printer, + const Descriptor* desc) const; + void GenerateClassXid(const GeneratorOptions& options, io::Printer* printer, const Descriptor* desc) const; void GenerateOneofCaseDefinition(const GeneratorOptions& options, io::Printer* printer, const OneofDescriptor* oneof) const; + void GenerateObjectTypedef(const GeneratorOptions& options, + io::Printer* printer, + const Descriptor* desc) const; void GenerateClassToObject(const GeneratorOptions& options, io::Printer* printer, const Descriptor* desc) const; @@ -270,17 +278,12 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { void GenerateClassFieldFromObject(const GeneratorOptions& options, io::Printer* printer, const FieldDescriptor* field) const; - void GenerateClassClone(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc) const; void GenerateClassRegistration(const GeneratorOptions& options, io::Printer* printer, const Descriptor* desc) const; void GenerateClassFields(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc) const; - void GenerateClassField(const GeneratorOptions& options, - io::Printer* printer, + io::Printer* printer, const Descriptor* desc) const; + void GenerateClassField(const GeneratorOptions& options, io::Printer* printer, const FieldDescriptor* desc) const; void GenerateClassExtensionFieldInfo(const GeneratorOptions& options, io::Printer* printer, @@ -302,13 +305,11 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { const FieldDescriptor* field) const; // Generate definition for one enum. - void GenerateEnum(const GeneratorOptions& options, - io::Printer* printer, + void GenerateEnum(const GeneratorOptions& options, io::Printer* printer, const EnumDescriptor* enumdesc) const; // Generate an extension definition. - void GenerateExtension(const GeneratorOptions& options, - io::Printer* printer, + void GenerateExtension(const GeneratorOptions& options, io::Printer* printer, const FieldDescriptor* field) const; // Generate addFoo() method for repeated primitive fields. @@ -328,6 +329,8 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { } // namespace js } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_JS_GENERATOR_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/js/well_known_types_embed.cc b/third_party/protobuf/src/google/protobuf/compiler/js/well_known_types_embed.cc index e5ee5510..5cb73657 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/js/well_known_types_embed.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/js/well_known_types_embed.cc @@ -1,3 +1,33 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + #include struct FileToc well_known_types_js[] = { @@ -16,6 +46,7 @@ struct FileToc well_known_types_js[] = { "\n" "/**\n" " * Packs the given message instance into this Any.\n" + " * For binary format usage only.\n" " * @param {!Uint8Array} serialized The serialized data to pack.\n" " * @param {string} name The type name of this message object.\n" " * @param {string=} opt_typeUrlPrefix the type URL prefix.\n" @@ -55,7 +86,8 @@ struct FileToc well_known_types_js[] = { " } else {\n" " return null;\n" " }\n" - "};\n"}, + "};\n" + }, {"timestamp.js", "/* This code will be inserted into generated code for\n" " * google/protobuf/timestamp.proto. */\n" @@ -79,6 +111,19 @@ struct FileToc well_known_types_js[] = { "proto.google.protobuf.Timestamp.prototype.fromDate = function(value) {\n" " this.setSeconds(Math.floor(value.getTime() / 1000));\n" " this.setNanos(value.getMilliseconds() * 1000000);\n" + "};\n" + "\n" + "\n" + "/**\n" + " * Factory method that returns a Timestamp object with value equal to\n" + " * the given Date.\n" + " * @param {!Date} value The value to set.\n" + " * @return {!proto.google.protobuf.Timestamp}\n" + " */\n" + "proto.google.protobuf.Timestamp.fromDate = function(value) {\n" + " var timestamp = new proto.google.protobuf.Timestamp();\n" + " timestamp.fromDate(value);\n" + " return timestamp;\n" "};\n"}, {"struct.js", "/* This code will be inserted into generated code for\n" diff --git a/third_party/protobuf/src/google/protobuf/compiler/main.cc b/third_party/protobuf/src/google/protobuf/compiler/main.cc index 1db35441..e1c539ae 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/main.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/main.cc @@ -30,71 +30,81 @@ // Author: kenton@google.com (Kenton Varda) -#include #include - -#ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP -#include #include -#endif // ! OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP +#include +#include -#ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP #include #include #include #include #include -#endif // ! OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP -int main(int argc, char* argv[]) { +#include - google::protobuf::compiler::CommandLineInterface cli; +namespace google { +namespace protobuf { +namespace compiler { + +int ProtobufMain(int argc, char* argv[]) { + + CommandLineInterface cli; cli.AllowPlugins("protoc-"); // Proto2 C++ - google::protobuf::compiler::cpp::CppGenerator cpp_generator; + cpp::CppGenerator cpp_generator; cli.RegisterGenerator("--cpp_out", "--cpp_opt", &cpp_generator, "Generate C++ header and source."); -#ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP +#ifdef GOOGLE_PROTOBUF_RUNTIME_INCLUDE_BASE + cpp_generator.set_opensource_runtime(true); + cpp_generator.set_runtime_include_base(GOOGLE_PROTOBUF_RUNTIME_INCLUDE_BASE); +#endif + // Proto2 Java - google::protobuf::compiler::java::JavaGenerator java_generator; + java::JavaGenerator java_generator; cli.RegisterGenerator("--java_out", "--java_opt", &java_generator, "Generate Java source file."); -#endif // !OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP -#ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP // Proto2 Python - google::protobuf::compiler::python::Generator py_generator; + python::Generator py_generator; cli.RegisterGenerator("--python_out", &py_generator, "Generate Python source file."); // PHP - google::protobuf::compiler::php::Generator php_generator; + php::Generator php_generator; cli.RegisterGenerator("--php_out", &php_generator, "Generate PHP source file."); // Ruby - google::protobuf::compiler::ruby::Generator rb_generator; + ruby::Generator rb_generator; cli.RegisterGenerator("--ruby_out", &rb_generator, "Generate Ruby source file."); // CSharp - google::protobuf::compiler::csharp::Generator csharp_generator; + csharp::Generator csharp_generator; cli.RegisterGenerator("--csharp_out", "--csharp_opt", &csharp_generator, "Generate C# source file."); // Objective C - google::protobuf::compiler::objectivec::ObjectiveCGenerator objc_generator; + objectivec::ObjectiveCGenerator objc_generator; cli.RegisterGenerator("--objc_out", "--objc_opt", &objc_generator, "Generate Objective C header and source."); // JavaScript - google::protobuf::compiler::js::Generator js_generator; + js::Generator js_generator; cli.RegisterGenerator("--js_out", &js_generator, "Generate JavaScript source."); -#endif // !OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP return cli.Run(argc, argv); } + +} // namespace compiler +} // namespace protobuf +} // namespace google + +int main(int argc, char* argv[]) { + return PROTOBUF_NAMESPACE_ID::compiler::ProtobufMain(argc, argv); +} diff --git a/third_party/protobuf/src/google/protobuf/compiler/mock_code_generator.cc b/third_party/protobuf/src/google/protobuf/compiler/mock_code_generator.cc index e150f97d..07760649 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/mock_code_generator.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/mock_code_generator.cc @@ -36,10 +36,10 @@ #include #include #include - - #include + + #include #include #include @@ -67,8 +67,9 @@ namespace compiler { // Returns the list of the names of files in all_files in the form of a // comma-separated string. -string CommaSeparatedList(const std::vector& all_files) { - std::vector names; +std::string CommaSeparatedList( + const std::vector& all_files) { + std::vector names; for (size_t i = 0; i < all_files.size(); i++) { names.push_back(all_files[i]->name()); } @@ -82,25 +83,23 @@ static const char* kFirstInsertionPoint = static const char* kSecondInsertionPoint = " # @@protoc_insertion_point(second_mock_insertion_point) is here\n"; -MockCodeGenerator::MockCodeGenerator(const string& name) - : name_(name) {} +MockCodeGenerator::MockCodeGenerator(const std::string& name) : name_(name) {} MockCodeGenerator::~MockCodeGenerator() {} void MockCodeGenerator::ExpectGenerated( - const string& name, - const string& parameter, - const string& insertions, - const string& file, - const string& first_message_name, - const string& first_parsed_file_name, - const string& output_directory) { - string content; + const std::string& name, const std::string& parameter, + const std::string& insertions, const std::string& file, + const std::string& first_message_name, + const std::string& first_parsed_file_name, + const std::string& output_directory) { + std::string content; GOOGLE_CHECK_OK( File::GetContents(output_directory + "/" + GetOutputFileName(name, file), &content, true)); - std::vector lines = Split(content, "\n", true); + std::vector lines = + Split(content, "\n", true); while (!lines.empty() && lines.back().empty()) { lines.pop_back(); @@ -109,22 +108,22 @@ void MockCodeGenerator::ExpectGenerated( lines[i] += "\n"; } - std::vector insertion_list; + std::vector insertion_list; if (!insertions.empty()) { SplitStringUsing(insertions, ",", &insertion_list); } EXPECT_EQ(lines.size(), 3 + insertion_list.size() * 2); - EXPECT_EQ(GetOutputFileContent(name, parameter, file, - first_parsed_file_name, first_message_name), + EXPECT_EQ(GetOutputFileContent(name, parameter, file, first_parsed_file_name, + first_message_name), lines[0]); EXPECT_EQ(kFirstInsertionPoint, lines[1 + insertion_list.size()]); EXPECT_EQ(kSecondInsertionPoint, lines[2 + insertion_list.size() * 2]); for (size_t i = 0; i < insertion_list.size(); i++) { - EXPECT_EQ(GetOutputFileContent(insertion_list[i], "first_insert", - file, file, first_message_name), + EXPECT_EQ(GetOutputFileContent(insertion_list[i], "first_insert", file, + file, first_message_name), lines[1 + i]); // Second insertion point is indented, so the inserted text should // automatically be indented too. @@ -135,9 +134,9 @@ void MockCodeGenerator::ExpectGenerated( } namespace { -void CheckSingleAnnotation(const string& expected_file, - const string& expected_text, - const string& file_content, +void CheckSingleAnnotation(const std::string& expected_file, + const std::string& expected_text, + const std::string& file_content, const GeneratedCodeInfo::Annotation& annotation) { EXPECT_EQ(expected_file, annotation.source_file()); ASSERT_GE(file_content.size(), annotation.begin()); @@ -150,12 +149,13 @@ void CheckSingleAnnotation(const string& expected_file, } // anonymous namespace void MockCodeGenerator::CheckGeneratedAnnotations( - const string& name, const string& file, const string& output_directory) { - string file_content; + const string& name, const std::string& file, + const std::string& output_directory) { + std::string file_content; GOOGLE_CHECK_OK( File::GetContents(output_directory + "/" + GetOutputFileName(name, file), &file_content, true)); - string meta_content; + std::string meta_content; GOOGLE_CHECK_OK(File::GetContents( output_directory + "/" + GetOutputFileName(name, file) + ".meta", &meta_content, true)); @@ -170,16 +170,15 @@ void MockCodeGenerator::CheckGeneratedAnnotations( annotations.annotation(2)); } -bool MockCodeGenerator::Generate( - const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const { +bool MockCodeGenerator::Generate(const FileDescriptor* file, + const std::string& parameter, + GeneratorContext* context, + std::string* error) const { bool annotate = false; for (int i = 0; i < file->message_type_count(); i++) { if (HasPrefixString(file->message_type(i)->name(), "MockCodeGenerator_")) { - string command = StripPrefixString(file->message_type(i)->name(), - "MockCodeGenerator_"); + std::string command = StripPrefixString( + file->message_type(i)->name(), "MockCodeGenerator_"); if (command == "Error") { *error = "Saw message type MockCodeGenerator_Error."; return false; @@ -201,8 +200,8 @@ bool MockCodeGenerator::Generate( } else if (command == "HasJsonName") { FieldDescriptorProto field_descriptor_proto; file->message_type(i)->field(0)->CopyTo(&field_descriptor_proto); - std::cerr << "Saw json_name: " - << field_descriptor_proto.has_json_name() << std::endl; + std::cerr << "Saw json_name: " << field_descriptor_proto.has_json_name() + << std::endl; abort(); } else if (command == "Annotate") { annotate = true; @@ -211,8 +210,8 @@ bool MockCodeGenerator::Generate( context->GetCompilerVersion(&compiler_version); std::cerr << "Saw compiler_version: " << compiler_version.major() * 1000000 + - compiler_version.minor() * 1000 + - compiler_version.patch() + compiler_version.minor() * 1000 + + compiler_version.patch() << " " << compiler_version.suffix() << std::endl; abort(); } else { @@ -222,17 +221,17 @@ bool MockCodeGenerator::Generate( } if (HasPrefixString(parameter, "insert=")) { - std::vector insert_into; - SplitStringUsing(StripPrefixString(parameter, "insert="), - ",", &insert_into); + std::vector insert_into; + SplitStringUsing(StripPrefixString(parameter, "insert="), ",", + &insert_into); for (size_t i = 0; i < insert_into.size(); i++) { { std::unique_ptr output(context->OpenForInsert( GetOutputFileName(insert_into[i], file), kFirstInsertionPointName)); io::Printer printer(output.get(), '$'); - printer.PrintRaw(GetOutputFileContent(name_, "first_insert", - file, context)); + printer.PrintRaw( + GetOutputFileContent(name_, "first_insert", file, context)); if (printer.failed()) { *error = "MockCodeGenerator detected write error."; return false; @@ -244,8 +243,8 @@ bool MockCodeGenerator::Generate( context->OpenForInsert(GetOutputFileName(insert_into[i], file), kSecondInsertionPointName)); io::Printer printer(output.get(), '$'); - printer.PrintRaw(GetOutputFileContent(name_, "second_insert", - file, context)); + printer.PrintRaw( + GetOutputFileContent(name_, "second_insert", file, context)); if (printer.failed()) { *error = "MockCodeGenerator detected write error."; return false; @@ -262,7 +261,7 @@ bool MockCodeGenerator::Generate( io::Printer printer(output.get(), '$', annotate ? &annotation_collector : NULL); printer.PrintRaw(GetOutputFileContent(name_, parameter, file, context)); - string annotate_suffix = "_annotation"; + std::string annotate_suffix = "_annotation"; if (annotate) { printer.Print("$p$", "p", "first"); printer.Annotate("p", "first" + annotate_suffix); @@ -295,39 +294,33 @@ bool MockCodeGenerator::Generate( return true; } -string MockCodeGenerator::GetOutputFileName(const string& generator_name, - const FileDescriptor* file) { +std::string MockCodeGenerator::GetOutputFileName( + const std::string& generator_name, const FileDescriptor* file) { return GetOutputFileName(generator_name, file->name()); } -string MockCodeGenerator::GetOutputFileName(const string& generator_name, - const string& file) { +std::string MockCodeGenerator::GetOutputFileName( + const std::string& generator_name, const std::string& file) { return file + ".MockCodeGenerator." + generator_name; } -string MockCodeGenerator::GetOutputFileContent( - const string& generator_name, - const string& parameter, - const FileDescriptor* file, - GeneratorContext *context) { +std::string MockCodeGenerator::GetOutputFileContent( + const std::string& generator_name, const std::string& parameter, + const FileDescriptor* file, GeneratorContext* context) { std::vector all_files; context->ListParsedFiles(&all_files); return GetOutputFileContent( - generator_name, parameter, file->name(), - CommaSeparatedList(all_files), - file->message_type_count() > 0 ? - file->message_type(0)->name() : "(none)"); + generator_name, parameter, file->name(), CommaSeparatedList(all_files), + file->message_type_count() > 0 ? file->message_type(0)->name() + : "(none)"); } -string MockCodeGenerator::GetOutputFileContent( - const string& generator_name, - const string& parameter, - const string& file, - const string& parsed_file_list, - const string& first_message_name) { - return strings::Substitute("$0: $1, $2, $3, $4\n", - generator_name, parameter, file, - first_message_name, parsed_file_list); +std::string MockCodeGenerator::GetOutputFileContent( + const std::string& generator_name, const std::string& parameter, + const std::string& file, const std::string& parsed_file_list, + const std::string& first_message_name) { + return strings::Substitute("$0: $1, $2, $3, $4\n", generator_name, parameter, + file, first_message_name, parsed_file_list); } } // namespace compiler diff --git a/third_party/protobuf/src/google/protobuf/compiler/mock_code_generator.h b/third_party/protobuf/src/google/protobuf/compiler/mock_code_generator.h index cdd9138c..082ba18d 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/mock_code_generator.h +++ b/third_party/protobuf/src/google/protobuf/compiler/mock_code_generator.h @@ -41,7 +41,9 @@ namespace google { namespace protobuf { class FileDescriptor; } // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { @@ -72,7 +74,7 @@ namespace compiler { // that can later be verified with CheckGeneratedAnnotations. class MockCodeGenerator : public CodeGenerator { public: - MockCodeGenerator(const string& name); + MockCodeGenerator(const std::string& name); virtual ~MockCodeGenerator(); // Expect (via gTest) that a MockCodeGenerator with the given name was called @@ -82,49 +84,47 @@ class MockCodeGenerator : public CodeGenerator { // should have inserted lines into this file. // |parsed_file_list| is a comma-separated list of names of the files // that are being compiled together in this run. - static void ExpectGenerated(const string& name, - const string& parameter, - const string& insertions, - const string& file, - const string& first_message_name, - const string& parsed_file_list, - const string& output_directory); + static void ExpectGenerated(const std::string& name, + const std::string& parameter, + const std::string& insertions, + const std::string& file, + const std::string& first_message_name, + const std::string& parsed_file_list, + const std::string& output_directory); // Checks that the correct text ranges were annotated by the // MockCodeGenerator_Annotate directive. - static void CheckGeneratedAnnotations(const string& name, - const string& file, - const string& output_directory); + static void CheckGeneratedAnnotations(const std::string& name, + const std::string& file, + const std::string& output_directory); // Get the name of the file which would be written by the given generator. - static string GetOutputFileName(const string& generator_name, - const FileDescriptor* file); - static string GetOutputFileName(const string& generator_name, - const string& file); + static std::string GetOutputFileName(const std::string& generator_name, + const FileDescriptor* file); + static std::string GetOutputFileName(const std::string& generator_name, + const std::string& file); // implements CodeGenerator ---------------------------------------- virtual bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const; + const std::string& parameter, GeneratorContext* context, + std::string* error) const; private: - string name_; + std::string name_; - static string GetOutputFileContent(const string& generator_name, - const string& parameter, - const FileDescriptor* file, - GeneratorContext *context); - static string GetOutputFileContent(const string& generator_name, - const string& parameter, - const string& file, - const string& parsed_file_list, - const string& first_message_name); + static std::string GetOutputFileContent(const std::string& generator_name, + const std::string& parameter, + const FileDescriptor* file, + GeneratorContext* context); + static std::string GetOutputFileContent( + const std::string& generator_name, const std::string& parameter, + const std::string& file, const std::string& parsed_file_list, + const std::string& first_message_name); }; } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_MOCK_CODE_GENERATOR_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_enum.cc b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_enum.cc index 978e985c..f2967683 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_enum.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_enum.cc @@ -35,6 +35,7 @@ #include #include #include +#include // std::find() namespace google { namespace protobuf { @@ -44,6 +45,17 @@ namespace objectivec { EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor) : descriptor_(descriptor), name_(EnumName(descriptor_)) { + // Track the names for the enum values, and if an alias overlaps a base + // value, skip making a name for it. Likewise if two alias overlap, the + // first one wins. + // The one gap in this logic is if two base values overlap, but for that + // to happen you have to have "Foo" and "FOO" or "FOO_BAR" and "FooBar", + // and if an enum has that, it is already going to be confusing and a + // compile error is just fine. + // The values are still tracked to support the reflection apis and + // TextFormat handing since they are different there. + std::set value_names; + for (int i = 0; i < descriptor_->value_count(); i++) { const EnumValueDescriptor* value = descriptor_->value(i); const EnumValueDescriptor* canonical_value = @@ -51,6 +63,14 @@ EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor) if (value == canonical_value) { base_values_.push_back(value); + value_names.insert(EnumValueName(value)); + } else { + string value_name(EnumValueName(value)); + if (value_names.find(value_name) != value_names.end()) { + alias_values_to_skip_.insert(value); + } else { + value_names.insert(value_name); + } } all_values_.push_back(value); } @@ -72,6 +92,20 @@ void EnumGenerator::GenerateHeader(io::Printer* printer) { "\n", "name", name_); + // Swift 5 included SE0192 "Handling Future Enum Cases" + // https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md + // Since a .proto file can get new values added to an enum at any time, they + // are effectively "non-frozen". Even in a proto3 syntax file where there is + // support for the unknown value, an edit to the file can always add a new + // value moving something from unknown to known. Since Swift is now ABI + // stable, it also means a binary could contain Swift compiled against one + // version of the .pbobjc.h file, but finally linked against an enum with + // more cases. So the Swift code will always have to treat ObjC Proto Enums + // as "non-frozen". The default behavior in SE0192 is for all objc enums to + // be "non-frozen" unless marked as otherwise, so this means this generation + // doesn't have to bother with the `enum_extensibility` attribute, as the + // default will be what is needed. + printer->Print("$comments$typedef$deprecated_attribute$ GPB_ENUM($name$) {\n", "comments", enum_comments, "deprecated_attribute", GetOptionalDeprecatedAttribute(descriptor_, descriptor_->file()), @@ -90,6 +124,9 @@ void EnumGenerator::GenerateHeader(io::Printer* printer) { "name", name_); } for (int i = 0; i < all_values_.size(); i++) { + if (alias_values_to_skip_.find(all_values_[i]) != alias_values_to_skip_.end()) { + continue; + } SourceLocation location; if (all_values_[i]->GetSourceLocation(&location)) { string comments = BuildCommentsString(location, true).c_str(); @@ -105,7 +142,7 @@ void EnumGenerator::GenerateHeader(io::Printer* printer) { "$name$$deprecated_attribute$ = $value$,\n", "name", EnumValueName(all_values_[i]), "deprecated_attribute", GetOptionalDeprecatedAttribute(all_values_[i]), - "value", SimpleItoa(all_values_[i]->number())); + "value", StrCat(all_values_[i]->number())); } printer->Outdent(); printer->Print( diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_enum.h b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_enum.h index f52e9e68..50a65644 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_enum.h +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_enum.h @@ -35,14 +35,9 @@ #include #include #include +#include namespace google { -namespace protobuf { -namespace io { -class Printer; // printer.h -} -} - namespace protobuf { namespace compiler { namespace objectivec { @@ -52,6 +47,9 @@ class EnumGenerator { explicit EnumGenerator(const EnumDescriptor* descriptor); ~EnumGenerator(); + EnumGenerator(const EnumGenerator&) = delete; + EnumGenerator& operator=(const EnumGenerator&) = delete; + void GenerateHeader(io::Printer* printer); void GenerateSource(io::Printer* printer); @@ -61,13 +59,13 @@ class EnumGenerator { const EnumDescriptor* descriptor_; std::vector base_values_; std::vector all_values_; + std::set alias_values_to_skip_; const string name_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator); }; } // namespace objectivec } // namespace compiler } // namespace protobuf } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_ENUM_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc index 8899a13a..9890d0a1 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc @@ -32,11 +32,9 @@ #include #include -#include #include #include #include -#include namespace google { namespace protobuf { diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_enum_field.h b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_enum_field.h index ae56c069..5a69c978 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_enum_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_enum_field.h @@ -44,6 +44,9 @@ class EnumFieldGenerator : public SingleFieldGenerator { friend FieldGenerator* FieldGenerator::Make(const FieldDescriptor* field, const Options& options); + EnumFieldGenerator(const EnumFieldGenerator&) = delete; + EnumFieldGenerator& operator=(const EnumFieldGenerator&) = delete; + public: virtual void GenerateCFunctionDeclarations(io::Printer* printer) const; virtual void GenerateCFunctionImplementations(io::Printer* printer) const; @@ -52,9 +55,6 @@ class EnumFieldGenerator : public SingleFieldGenerator { protected: EnumFieldGenerator(const FieldDescriptor* descriptor, const Options& options); virtual ~EnumFieldGenerator(); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator); }; class RepeatedEnumFieldGenerator : public RepeatedFieldGenerator { @@ -68,9 +68,6 @@ class RepeatedEnumFieldGenerator : public RepeatedFieldGenerator { RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor, const Options& options); virtual ~RepeatedEnumFieldGenerator(); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator); }; } // namespace objectivec diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_extension.cc b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_extension.cc index b788d0a3..bf65de3b 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_extension.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_extension.cc @@ -61,6 +61,11 @@ ExtensionGenerator::~ExtensionGenerator() {} void ExtensionGenerator::GenerateMembersHeader(io::Printer* printer) { std::map vars; vars["method_name"] = method_name_; + if (IsRetainedName(method_name_)) { + vars["storage_attribute"] = " NS_RETURNS_NOT_RETAINED"; + } else { + vars["storage_attribute"] = ""; + } SourceLocation location; if (descriptor_->GetSourceLocation(&location)) { vars["comments"] = BuildCommentsString(location, true); @@ -72,7 +77,7 @@ void ExtensionGenerator::GenerateMembersHeader(io::Printer* printer) { vars["deprecated_attribute"] = GetOptionalDeprecatedAttribute(descriptor_, descriptor_->file()); printer->Print(vars, "$comments$" - "+ (GPBExtensionDescriptor *)$method_name$$deprecated_attribute$;\n"); + "+ (GPBExtensionDescriptor *)$method_name$$storage_attribute$$deprecated_attribute$;\n"); } void ExtensionGenerator::GenerateStaticVariablesInitialization( @@ -80,7 +85,7 @@ void ExtensionGenerator::GenerateStaticVariablesInitialization( std::map vars; vars["root_class_and_method_name"] = root_class_and_method_name_; vars["extended_type"] = ClassName(descriptor_->containing_type()); - vars["number"] = SimpleItoa(descriptor_->number()); + vars["number"] = StrCat(descriptor_->number()); std::vector options; if (descriptor_->is_repeated()) options.push_back("GPBExtensionRepeated"); diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_extension.h b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_extension.h index e361e639..d49a4f1c 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_extension.h +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_extension.h @@ -31,16 +31,10 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_EXTENSION_H__ #define GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_EXTENSION_H__ -#include +#include +#include namespace google { -namespace protobuf { -class FieldDescriptor; // descriptor.h -namespace io { -class Printer; // printer.h -} -} - namespace protobuf { namespace compiler { namespace objectivec { @@ -51,6 +45,9 @@ class ExtensionGenerator { const FieldDescriptor* descriptor); ~ExtensionGenerator(); + ExtensionGenerator(const ExtensionGenerator&) = delete; + ExtensionGenerator& operator=(const ExtensionGenerator&) = delete; + void GenerateMembersHeader(io::Printer* printer); void GenerateStaticVariablesInitialization(io::Printer* printer); void GenerateRegistrationSource(io::Printer* printer); @@ -59,11 +56,11 @@ class ExtensionGenerator { string method_name_; string root_class_and_method_name_; const FieldDescriptor* descriptor_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator); }; + } // namespace objectivec } // namespace compiler } // namespace protobuf } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_MESSAGE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_field.cc b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_field.cc index f74599ba..f585941e 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_field.cc @@ -38,7 +38,6 @@ #include #include #include -#include #include namespace google { @@ -76,7 +75,7 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor, (*variables)["raw_field_name"] = raw_field_name; (*variables)["field_number_name"] = classname + "_FieldNumber_" + capitalized_name; - (*variables)["field_number"] = SimpleItoa(descriptor->number()); + (*variables)["field_number"] = StrCat(descriptor->number()); (*variables)["field_type"] = GetCapitalizedType(descriptor); (*variables)["deprecated_attribute"] = GetOptionalDeprecatedAttribute(descriptor); std::vector field_flags; @@ -214,7 +213,7 @@ void FieldGenerator::GenerateFieldDescription( } void FieldGenerator::SetRuntimeHasBit(int has_index) { - variables_["has_index"] = SimpleItoa(has_index); + variables_["has_index"] = StrCat(has_index); } void FieldGenerator::SetNoHasBit(void) { @@ -237,7 +236,7 @@ void FieldGenerator::SetOneofIndexBase(int index_base) { if (descriptor_->containing_oneof() != NULL) { int index = descriptor_->containing_oneof()->index() + index_base; // Flip the sign to mark it as a oneof. - variables_["has_index"] = SimpleItoa(-index); + variables_["has_index"] = StrCat(-index); } } diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_field.h b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_field.h index 216034d0..24465d0a 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_field.h @@ -34,16 +34,11 @@ #include #include #include -#include #include +#include namespace google { namespace protobuf { - -namespace io { -class Printer; // printer.h -} // namespace io - namespace compiler { namespace objectivec { @@ -54,6 +49,9 @@ class FieldGenerator { virtual ~FieldGenerator(); + FieldGenerator(const FieldGenerator&) = delete; + FieldGenerator& operator=(const FieldGenerator&) = delete; + // Exposed for subclasses to fill in. virtual void GenerateFieldStorageDeclaration(io::Printer* printer) const = 0; virtual void GeneratePropertyDeclaration(io::Printer* printer) const = 0; @@ -101,15 +99,15 @@ class FieldGenerator { const FieldDescriptor* descriptor_; std::map variables_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator); }; class SingleFieldGenerator : public FieldGenerator { public: virtual ~SingleFieldGenerator(); + SingleFieldGenerator(const SingleFieldGenerator&) = delete; + SingleFieldGenerator& operator=(const SingleFieldGenerator&) = delete; + virtual void GenerateFieldStorageDeclaration(io::Printer* printer) const; virtual void GeneratePropertyDeclaration(io::Printer* printer) const; @@ -121,9 +119,6 @@ class SingleFieldGenerator : public FieldGenerator { SingleFieldGenerator(const FieldDescriptor* descriptor, const Options& options); virtual bool WantsHasProperty(void) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SingleFieldGenerator); }; // Subclass with common support for when the field ends up as an ObjC Object. @@ -131,21 +126,24 @@ class ObjCObjFieldGenerator : public SingleFieldGenerator { public: virtual ~ObjCObjFieldGenerator(); + ObjCObjFieldGenerator(const ObjCObjFieldGenerator&) = delete; + ObjCObjFieldGenerator& operator=(const ObjCObjFieldGenerator&) = delete; + virtual void GenerateFieldStorageDeclaration(io::Printer* printer) const; virtual void GeneratePropertyDeclaration(io::Printer* printer) const; protected: ObjCObjFieldGenerator(const FieldDescriptor* descriptor, const Options& options); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ObjCObjFieldGenerator); }; class RepeatedFieldGenerator : public ObjCObjFieldGenerator { public: virtual ~RepeatedFieldGenerator(); + RepeatedFieldGenerator(const RepeatedFieldGenerator&) = delete; + RepeatedFieldGenerator& operator=(const RepeatedFieldGenerator&) = delete; + virtual void GenerateFieldStorageDeclaration(io::Printer* printer) const; virtual void GeneratePropertyDeclaration(io::Printer* printer) const; @@ -158,9 +156,6 @@ class RepeatedFieldGenerator : public ObjCObjFieldGenerator { const Options& options); virtual void FinishInitialization(void); virtual bool WantsHasProperty(void) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedFieldGenerator); }; // Convenience class which constructs FieldGenerators for a Descriptor. @@ -169,6 +164,9 @@ class FieldGeneratorMap { FieldGeneratorMap(const Descriptor* descriptor, const Options& options); ~FieldGeneratorMap(); + FieldGeneratorMap(const FieldGeneratorMap&) = delete; + FieldGeneratorMap& operator=(const FieldGeneratorMap&) = delete; + const FieldGenerator& get(const FieldDescriptor* field) const; const FieldGenerator& get_extension(int index) const; @@ -184,11 +182,11 @@ class FieldGeneratorMap { const Descriptor* descriptor_; std::vector> field_generators_; std::vector> extension_generators_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap); }; + } // namespace objectivec } // namespace compiler } // namespace protobuf } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_FIELD_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_file.cc b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_file.cc index f0d9b4d5..d4a4d708 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_file.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_file.cc @@ -241,7 +241,7 @@ void FileGenerator::GenerateHeader(io::Printer *printer) { "#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources.\n" "#endif\n" "\n", - "google_protobuf_objc_version", SimpleItoa(GOOGLE_PROTOBUF_OBJC_VERSION)); + "google_protobuf_objc_version", StrCat(GOOGLE_PROTOBUF_OBJC_VERSION)); // #import any headers for "public imports" in the proto file. { diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_file.h b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_file.h index 1754fc0a..ed7fad80 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_file.h +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_file.h @@ -35,16 +35,10 @@ #include #include #include -#include +#include +#include namespace google { -namespace protobuf { -class FileDescriptor; // descriptor.h -namespace io { -class Printer; // printer.h -} -} - namespace protobuf { namespace compiler { namespace objectivec { @@ -58,6 +52,9 @@ class FileGenerator { FileGenerator(const FileDescriptor* file, const Options& options); ~FileGenerator(); + FileGenerator(const FileGenerator&) = delete; + FileGenerator& operator=(const FileGenerator&) = delete; + void GenerateSource(io::Printer* printer); void GenerateHeader(io::Printer* printer); @@ -76,8 +73,6 @@ class FileGenerator { void PrintFileRuntimePreamble( io::Printer* printer, const std::set& headers_to_import) const; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator); }; } // namespace objectivec diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_generator.cc b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_generator.cc index e0597cc7..25338ad9 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_generator.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_generator.cc @@ -89,6 +89,12 @@ bool ObjectiveCGenerator::GenerateAll(const std::vector& // There is no validation that the prefixes are good prefixes, it is // assumed that they are when you create the file. generation_options.expected_prefixes_path = options[i].second; + } else if (options[i].first == "expected_prefixes_suppressions") { + // A semicolon delimited string that lists the paths of .proto files to + // exclude from the package prefix validations (expected_prefixes_path). + // This is provided as an "out", to skip some files being checked. + SplitStringUsing(options[i].second, ";", + &generation_options.expected_prefixes_suppressions); } else if (options[i].first == "generate_for_named_framework") { // The name of the framework that protos are being generated for. This // will cause the #import statements to be framework based using this diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_generator.h b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_generator.h index 3e43f732..d10efc20 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_generator.h +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_generator.h @@ -35,6 +35,9 @@ #include #include +#include + +#include namespace google { namespace protobuf { @@ -45,11 +48,14 @@ namespace objectivec { // header. If you create your own protocol compiler binary and you want it to // support ObjectiveC output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT ObjectiveCGenerator : public CodeGenerator { +class PROTOC_EXPORT ObjectiveCGenerator : public CodeGenerator { public: ObjectiveCGenerator(); ~ObjectiveCGenerator(); + ObjectiveCGenerator(const ObjectiveCGenerator&) = delete; + ObjectiveCGenerator& operator=(const ObjectiveCGenerator&) = delete; + // implements CodeGenerator ---------------------------------------- bool HasGenerateAll() const; bool Generate(const FileDescriptor* file, @@ -60,13 +66,13 @@ class LIBPROTOC_EXPORT ObjectiveCGenerator : public CodeGenerator { const string& parameter, GeneratorContext* context, string* error) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ObjectiveCGenerator); }; } // namespace objectivec } // namespace compiler } // namespace protobuf } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_GENERATOR_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc index df71c8bb..e8d6d9e1 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc @@ -38,19 +38,19 @@ #include #include #include +#include #include -#include #include +#include #include #include #include #include -#include -#include +#include +#include #include - // NOTE: src/google/protobuf/compiler/plugin.cc makes use of cerr for some // error cases, so it seems to be ok to use as a back door for errors. @@ -63,7 +63,7 @@ namespace objectivec { // in this port namespace to avoid ambiguous definition. namespace posix { #ifdef _WIN32 -using ::google::protobuf::internal::win32::open; +using ::google::protobuf::io::win32::open; #else using ::open; #endif @@ -75,12 +75,16 @@ Options::Options() { if (file_path) { expected_prefixes_path = file_path; } + const char* suppressions = getenv("GPB_OBJC_EXPECTED_PACKAGE_PREFIXES_SUPPRESSIONS"); + if (suppressions) { + SplitStringUsing(suppressions, ";", &expected_prefixes_suppressions); + } } namespace { -hash_set MakeWordsMap(const char* const words[], size_t num_words) { - hash_set result; +std::unordered_set MakeWordsMap(const char* const words[], size_t num_words) { + std::unordered_set result; for (int i = 0; i < num_words; i++) { result.insert(words[i]); } @@ -89,7 +93,7 @@ hash_set MakeWordsMap(const char* const words[], size_t num_words) { const char* const kUpperSegmentsList[] = {"url", "http", "https"}; -hash_set kUpperSegments = +std::unordered_set kUpperSegments = MakeWordsMap(kUpperSegmentsList, GOOGLE_ARRAYSIZE(kUpperSegmentsList)); bool ascii_isnewline(char c) { @@ -165,70 +169,111 @@ string UnderscoresToCamelCase(const string& input, bool first_capitalized) { } const char* const kReservedWordList[] = { - // Objective C "keywords" that aren't in C - // From - // http://stackoverflow.com/questions/1873630/reserved-keywords-in-objective-c - "id", "_cmd", "super", "in", "out", "inout", "bycopy", "byref", "oneway", - "self", + // Note NSObject Methods: + // These are brought in from objectivec_nsobject_methods.h that is generated + // using method_dump.sh. See kNSObjectMethods below. - // C/C++ keywords (Incl C++ 0x11) - // From http://en.cppreference.com/w/cpp/keywords - "and", "and_eq", "alignas", "alignof", "asm", "auto", "bitand", "bitor", - "bool", "break", "case", "catch", "char", "char16_t", "char32_t", "class", - "compl", "const", "constexpr", "const_cast", "continue", "decltype", - "default", "delete", "double", "dynamic_cast", "else", "enum", "explicit", - "export", "extern ", "false", "float", "for", "friend", "goto", "if", - "inline", "int", "long", "mutable", "namespace", "new", "noexcept", "not", - "not_eq", "nullptr", "operator", "or", "or_eq", "private", "protected", - "public", "register", "reinterpret_cast", "return", "short", "signed", - "sizeof", "static", "static_assert", "static_cast", "struct", "switch", - "template", "this", "thread_local", "throw", "true", "try", "typedef", - "typeid", "typename", "union", "unsigned", "using", "virtual", "void", - "volatile", "wchar_t", "while", "xor", "xor_eq", + // Objective C "keywords" that aren't in C + // From + // http://stackoverflow.com/questions/1873630/reserved-keywords-in-objective-c + // with some others added on. + "id", "_cmd", "super", "in", "out", "inout", "bycopy", "byref", "oneway", + "self", "instancetype", "nullable", "nonnull", "nil", "Nil", + "YES", "NO", "weak", - // C99 keywords - // From - // http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fkeyw.htm - "restrict", + // C/C++ keywords (Incl C++ 0x11) + // From http://en.cppreference.com/w/cpp/keywords + "and", "and_eq", "alignas", "alignof", "asm", "auto", "bitand", "bitor", + "bool", "break", "case", "catch", "char", "char16_t", "char32_t", "class", + "compl", "const", "constexpr", "const_cast", "continue", "decltype", + "default", "delete", "double", "dynamic_cast", "else", "enum", "explicit", + "export", "extern ", "false", "float", "for", "friend", "goto", "if", + "inline", "int", "long", "mutable", "namespace", "new", "noexcept", "not", + "not_eq", "nullptr", "operator", "or", "or_eq", "private", "protected", + "public", "register", "reinterpret_cast", "return", "short", "signed", + "sizeof", "static", "static_assert", "static_cast", "struct", "switch", + "template", "this", "thread_local", "throw", "true", "try", "typedef", + "typeid", "typename", "union", "unsigned", "using", "virtual", "void", + "volatile", "wchar_t", "while", "xor", "xor_eq", - // Objective-C Runtime typedefs - // From - "Category", "Ivar", "Method", "Protocol", + // C99 keywords + // From + // http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fkeyw.htm + "restrict", - // NSObject Methods - // new is covered by C++ keywords. - "description", "debugDescription", "finalize", "hash", "dealloc", "init", - "class", "superclass", "retain", "release", "autorelease", "retainCount", - "zone", "isProxy", "copy", "mutableCopy", "classForCoder", + // GCC/Clang extension + "typeof", - // GPBMessage Methods - // Only need to add instance methods that may conflict with - // method declared in protos. The main cases are methods - // that take no arguments, or setFoo:/hasFoo: type methods. - "clear", "data", "delimitedData", "descriptor", "extensionRegistry", - "extensionsCurrentlySet", "initialized", "isInitialized", "serializedSize", - "sortedExtensionsInUse", "unknownFields", + // Not a keyword, but will break you + "NULL", - // MacTypes.h names - "Fixed", "Fract", "Size", "LogicalAddress", "PhysicalAddress", "ByteCount", - "ByteOffset", "Duration", "AbsoluteTime", "OptionBits", "ItemCount", - "PBVersion", "ScriptCode", "LangCode", "RegionCode", "OSType", - "ProcessSerialNumber", "Point", "Rect", "FixedPoint", "FixedRect", "Style", - "StyleParameter", "StyleField", "TimeScale", "TimeBase", "TimeRecord", + // Objective-C Runtime typedefs + // From + "Category", "Ivar", "Method", "Protocol", + + // GPBMessage Methods + // Only need to add instance methods that may conflict with + // method declared in protos. The main cases are methods + // that take no arguments, or setFoo:/hasFoo: type methods. + "clear", "data", "delimitedData", "descriptor", "extensionRegistry", + "extensionsCurrentlySet", "initialized", "isInitialized", "serializedSize", + "sortedExtensionsInUse", "unknownFields", + + // MacTypes.h names + "Fixed", "Fract", "Size", "LogicalAddress", "PhysicalAddress", "ByteCount", + "ByteOffset", "Duration", "AbsoluteTime", "OptionBits", "ItemCount", + "PBVersion", "ScriptCode", "LangCode", "RegionCode", "OSType", + "ProcessSerialNumber", "Point", "Rect", "FixedPoint", "FixedRect", "Style", + "StyleParameter", "StyleField", "TimeScale", "TimeBase", "TimeRecord", }; -hash_set kReservedWords = - MakeWordsMap(kReservedWordList, GOOGLE_ARRAYSIZE(kReservedWordList)); +// returns true is input starts with __ or _[A-Z] which are reserved identifiers +// in C/ C++. All calls should go through UnderscoresToCamelCase before getting here +// but this verifies and allows for future expansion if we decide to redefine what a +// reserved C identifier is (for example the GNU list +// https://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html ) +bool IsReservedCIdentifier(const string& input) { + if (input.length() > 2) { + if (input.at(0) == '_') { + if (isupper(input.at(1)) || input.at(1) == '_') { + return true; + } + } + } + return false; +} -string SanitizeNameForObjC(const string& input, +string SanitizeNameForObjC(const string& prefix, + const string& input, const string& extension, string* out_suffix_added) { - if (kReservedWords.count(input) > 0) { + static const std::unordered_set kReservedWords = + MakeWordsMap(kReservedWordList, GOOGLE_ARRAYSIZE(kReservedWordList)); + static const std::unordered_set kNSObjectMethods = + MakeWordsMap(kNSObjectMethodsList, GOOGLE_ARRAYSIZE(kNSObjectMethodsList)); + string sanitized; + // We add the prefix in the cases where the string is missing a prefix. + // We define "missing a prefix" as where 'input': + // a) Doesn't start with the prefix or + // b) Isn't equivalent to the prefix or + // c) Has the prefix, but the letter after the prefix is lowercase + if (HasPrefixString(input, prefix)) { + if (input.length() == prefix.length() || !ascii_isupper(input[prefix.length()])) { + sanitized = prefix + input; + } else { + sanitized = input; + } + } else { + sanitized = prefix + input; + } + if (IsReservedCIdentifier(sanitized) || + (kReservedWords.count(sanitized) > 0) || + (kNSObjectMethods.count(sanitized) > 0)) { if (out_suffix_added) *out_suffix_added = extension; - return input + extension; + return sanitized + extension; } if (out_suffix_added) out_suffix_added->clear(); - return input; + return sanitized; } string NameFromFieldDescriptor(const FieldDescriptor* field) { @@ -319,7 +364,7 @@ string StripProto(const string& filename) { } } -void StringPieceTrimWhitespace(StringPiece* input) { +void TrimWhitespace(StringPiece* input) { while (!input->empty() && ascii_isspace(*input->data())) { input->remove_prefix(1); } @@ -387,12 +432,11 @@ string FilePathBasename(const FileDescriptor* file) { } string FileClassName(const FileDescriptor* file) { - string name = FileClassPrefix(file); - name += UnderscoresToCamelCase(StripProto(BaseFileName(file)), true); - name += "Root"; + const string prefix = FileClassPrefix(file); + const string name = UnderscoresToCamelCase(StripProto(BaseFileName(file)), true) + "Root"; // There aren't really any reserved words that end in "Root", but playing // it safe and checking. - return SanitizeNameForObjC(name, "_RootClass", NULL); + return SanitizeNameForObjC(prefix, name, "_RootClass", NULL); } string ClassNameWorker(const Descriptor* descriptor) { @@ -420,9 +464,9 @@ string ClassName(const Descriptor* descriptor) { string ClassName(const Descriptor* descriptor, string* out_suffix_added) { // 1. Message names are used as is (style calls for CamelCase, trust it). // 2. Check for reserved word at the very end and then suffix things. - string prefix = FileClassPrefix(descriptor->file()); - string name = ClassNameWorker(descriptor); - return SanitizeNameForObjC(prefix + name, "_Class", out_suffix_added); + const string prefix = FileClassPrefix(descriptor->file()); + const string name = ClassNameWorker(descriptor); + return SanitizeNameForObjC(prefix, name, "_Class", out_suffix_added); } string EnumName(const EnumDescriptor* descriptor) { @@ -434,9 +478,9 @@ string EnumName(const EnumDescriptor* descriptor) { // ... // } // yields Fixed_Class, Fixed_Size. - string name = FileClassPrefix(descriptor->file()); - name += ClassNameWorker(descriptor); - return SanitizeNameForObjC(name, "_Enum", NULL); + const string prefix = FileClassPrefix(descriptor->file()); + const string name = ClassNameWorker(descriptor); + return SanitizeNameForObjC(prefix, name, "_Enum", NULL); } string EnumValueName(const EnumValueDescriptor* descriptor) { @@ -446,12 +490,12 @@ string EnumValueName(const EnumValueDescriptor* descriptor) { // FOO = 1 // } // yields Fixed_Enum and Fixed_Enum_Foo (not Fixed_Foo). - const string& class_name = EnumName(descriptor->type()); - const string& value_str = UnderscoresToCamelCase(descriptor->name(), true); - const string& name = class_name + "_" + value_str; + const string class_name = EnumName(descriptor->type()); + const string value_str = UnderscoresToCamelCase(descriptor->name(), true); + const string name = class_name + "_" + value_str; // There aren't really any reserved words with an underscore and a leading // capital letter, but playing it safe and checking. - return SanitizeNameForObjC(name, "_Value", NULL); + return SanitizeNameForObjC("", name, "_Value", NULL); } string EnumValueShortName(const EnumValueDescriptor* descriptor) { @@ -467,9 +511,9 @@ string EnumValueShortName(const EnumValueDescriptor* descriptor) { // So the right way to get the short name is to take the full enum name // and then strip off the enum name (leaving the value name and anything // done by sanitize). - const string& class_name = EnumName(descriptor->type()); - const string& long_name_prefix = class_name + "_"; - const string& long_name = EnumValueName(descriptor); + const string class_name = EnumName(descriptor->type()); + const string long_name_prefix = class_name + "_"; + const string long_name = EnumValueName(descriptor); return StripPrefixString(long_name, long_name_prefix); } @@ -486,13 +530,13 @@ string UnCamelCaseEnumShortName(const string& name) { } string ExtensionMethodName(const FieldDescriptor* descriptor) { - const string& name = NameFromFieldDescriptor(descriptor); - const string& result = UnderscoresToCamelCase(name, false); - return SanitizeNameForObjC(result, "_Extension", NULL); + const string name = NameFromFieldDescriptor(descriptor); + const string result = UnderscoresToCamelCase(name, false); + return SanitizeNameForObjC("", result, "_Extension", NULL); } string FieldName(const FieldDescriptor* field) { - const string& name = NameFromFieldDescriptor(field); + const string name = NameFromFieldDescriptor(field); string result = UnderscoresToCamelCase(name, false); if (field->is_repeated() && !field->is_map()) { // Add "Array" before do check for reserved worlds. @@ -503,7 +547,7 @@ string FieldName(const FieldDescriptor* field) { result += "_p"; } } - return SanitizeNameForObjC(result, "_p", NULL); + return SanitizeNameForObjC("", result, "_p", NULL); } string FieldNameCapitalized(const FieldDescriptor* field) { @@ -615,7 +659,7 @@ string GetCapitalizedType(const FieldDescriptor* field) { // Some compilers report reaching end of function even though all cases of // the enum are handed in the switch. GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; + return string(); } ObjectiveCType GetObjectiveCType(FieldDescriptor::Type field_type) { @@ -743,7 +787,7 @@ string GPBGenericValueFieldName(const FieldDescriptor* field) { // Some compilers report reaching end of function even though all cases of // the enum are handed in the switch. GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; + return string(); } @@ -761,17 +805,17 @@ string DefaultValue(const FieldDescriptor* field) { if (field->default_value_int32() == INT_MIN) { return "-0x80000000"; } - return SimpleItoa(field->default_value_int32()); + return StrCat(field->default_value_int32()); case FieldDescriptor::CPPTYPE_UINT32: - return SimpleItoa(field->default_value_uint32()) + "U"; + return StrCat(field->default_value_uint32()) + "U"; case FieldDescriptor::CPPTYPE_INT64: // gcc and llvm reject the decimal form of kint32min and kint64min. if (field->default_value_int64() == LLONG_MIN) { return "-0x8000000000000000LL"; } - return SimpleItoa(field->default_value_int64()) + "LL"; + return StrCat(field->default_value_int64()) + "LL"; case FieldDescriptor::CPPTYPE_UINT64: - return SimpleItoa(field->default_value_uint64()) + "ULL"; + return StrCat(field->default_value_uint64()) + "ULL"; case FieldDescriptor::CPPTYPE_DOUBLE: return HandleExtremeFloatingPoint( SimpleDtoa(field->default_value_double()), false); @@ -815,7 +859,7 @@ string DefaultValue(const FieldDescriptor* field) { // Some compilers report reaching end of function even though all cases of // the enum are handed in the switch. GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; + return string(); } bool HasNonZeroDefaultValue(const FieldDescriptor* field) { @@ -1003,18 +1047,17 @@ bool ExpectedPrefixesCollector::ConsumeLine( const StringPiece& line, string* out_error) { int offset = line.find('='); if (offset == StringPiece::npos) { - *out_error = - string("Expected prefixes file line without equal sign: '") + - line.ToString() + "'."; + *out_error = string("Expected prefixes file line without equal sign: '") + + string(line) + "'."; return false; } - StringPiece package(line, 0, offset); - StringPiece prefix(line, offset + 1, line.length() - offset - 1); - StringPieceTrimWhitespace(&package); - StringPieceTrimWhitespace(&prefix); + StringPiece package = line.substr(0, offset); + StringPiece prefix = line.substr(offset + 1); + TrimWhitespace(&package); + TrimWhitespace(&prefix); // Don't really worry about error checking the package/prefix for // being valid. Assume the file is validated when it is created/edited. - (*prefix_map_)[package.ToString()] = prefix.ToString(); + (*prefix_map_)[string(package)] = string(prefix); return true; } @@ -1168,6 +1211,15 @@ bool ValidateObjCClassPrefixes(const std::vector& files, } for (int i = 0; i < files.size(); i++) { + bool should_skip = + (std::find(generation_options.expected_prefixes_suppressions.begin(), + generation_options.expected_prefixes_suppressions.end(), + files[i]->name()) + != generation_options.expected_prefixes_suppressions.end()); + if (should_skip) { + continue; + } + bool is_valid = ValidateObjCClassPrefix(files[i], generation_options.expected_prefixes_path, @@ -1421,7 +1473,7 @@ class Parser { bool Parser::ParseChunk(StringPiece chunk) { if (!leftover_.empty()) { - chunk.AppendToString(&leftover_); + leftover_ += string(chunk); p_ = StringPiece(leftover_); } else { p_ = chunk; @@ -1430,7 +1482,7 @@ bool Parser::ParseChunk(StringPiece chunk) { if (p_.empty()) { leftover_.clear(); } else { - leftover_ = p_.ToString(); + leftover_ = string(p_); } return result; } @@ -1453,7 +1505,7 @@ bool Parser::ParseLoop() { while (ReadLine(&p_, &line)) { ++line_; RemoveComment(&line); - StringPieceTrimWhitespace(&line); + TrimWhitespace(&line); if (line.size() == 0) { continue; // Blank line. } @@ -1495,7 +1547,7 @@ bool ParseSimpleFile( if (!parser.ParseChunk(StringPiece(static_cast(buf), buf_len))) { *out_error = string("error: ") + path + - " Line " + SimpleItoa(parser.last_line()) + ", " + parser.error_str(); + " Line " + StrCat(parser.last_line()) + ", " + parser.error_str(); return false; } } @@ -1640,12 +1692,12 @@ bool ImportWriter::ProtoFrameworkCollector::ConsumeLine( if (offset == StringPiece::npos) { *out_error = string("Framework/proto file mapping line without colon sign: '") + - line.ToString() + "'."; + string(line) + "'."; return false; } - StringPiece framework_name(line, 0, offset); - StringPiece proto_file_list(line, offset + 1, line.length() - offset - 1); - StringPieceTrimWhitespace(&framework_name); + StringPiece framework_name = line.substr(0, offset); + StringPiece proto_file_list = line.substr(offset + 1); + TrimWhitespace(&framework_name); int start = 0; while (start < proto_file_list.length()) { @@ -1654,25 +1706,27 @@ bool ImportWriter::ProtoFrameworkCollector::ConsumeLine( offset = proto_file_list.length(); } - StringPiece proto_file(proto_file_list, start, offset - start); - StringPieceTrimWhitespace(&proto_file); + StringPiece proto_file = proto_file_list.substr(start, offset - start); + TrimWhitespace(&proto_file); if (proto_file.size() != 0) { std::map::iterator existing_entry = - map_->find(proto_file.ToString()); + map_->find(string(proto_file)); if (existing_entry != map_->end()) { - std::cerr << "warning: duplicate proto file reference, replacing framework entry for '" - << proto_file.ToString() << "' with '" << framework_name.ToString() - << "' (was '" << existing_entry->second << "')." << std::endl; + std::cerr << "warning: duplicate proto file reference, replacing " + "framework entry for '" + << string(proto_file) << "' with '" << string(framework_name) + << "' (was '" << existing_entry->second << "')." << std::endl; std::cerr.flush(); } if (proto_file.find(' ') != StringPiece::npos) { - std::cerr << "note: framework mapping file had a proto file with a space in, hopefully that isn't a missing comma: '" - << proto_file.ToString() << "'" << std::endl; + std::cerr << "note: framework mapping file had a proto file with a " + "space in, hopefully that isn't a missing comma: '" + << string(proto_file) << "'" << std::endl; std::cerr.flush(); } - (*map_)[proto_file.ToString()] = framework_name.ToString(); + (*map_)[string(proto_file)] = string(framework_name); } start = offset + 1; diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_helpers.h b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_helpers.h index 8999aa59..98ec7db8 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_helpers.h +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_helpers.h @@ -39,6 +39,8 @@ #include #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -48,71 +50,73 @@ namespace objectivec { struct Options { Options(); string expected_prefixes_path; + std::vector expected_prefixes_suppressions; string generate_for_named_framework; string named_framework_to_proto_path_mappings_path; }; // Escape C++ trigraphs by escaping question marks to "\?". -string LIBPROTOC_EXPORT EscapeTrigraphs(const string& to_escape); +string PROTOC_EXPORT EscapeTrigraphs(const string& to_escape); // Strips ".proto" or ".protodevel" from the end of a filename. -string LIBPROTOC_EXPORT StripProto(const string& filename); +string PROTOC_EXPORT StripProto(const string& filename); // Remove white space from either end of a StringPiece. -void LIBPROTOC_EXPORT StringPieceTrimWhitespace(StringPiece* input); +void PROTOC_EXPORT TrimWhitespace(StringPiece* input); // Returns true if the name requires a ns_returns_not_retained attribute applied // to it. -bool LIBPROTOC_EXPORT IsRetainedName(const string& name); +bool PROTOC_EXPORT IsRetainedName(const string& name); // Returns true if the name starts with "init" and will need to have special // handling under ARC. -bool LIBPROTOC_EXPORT IsInitName(const string& name); +bool PROTOC_EXPORT IsInitName(const string& name); // Gets the objc_class_prefix. -string LIBPROTOC_EXPORT FileClassPrefix(const FileDescriptor* file); +string PROTOC_EXPORT FileClassPrefix(const FileDescriptor* file); // Gets the path of the file we're going to generate (sans the .pb.h // extension). The path will be dependent on the objectivec package // declared in the proto package. -string LIBPROTOC_EXPORT FilePath(const FileDescriptor* file); +string PROTOC_EXPORT FilePath(const FileDescriptor* file); // Just like FilePath(), but without the directory part. -string LIBPROTOC_EXPORT FilePathBasename(const FileDescriptor* file); +string PROTOC_EXPORT FilePathBasename(const FileDescriptor* file); // Gets the name of the root class we'll generate in the file. This class // is not meant for external consumption, but instead contains helpers that // the rest of the classes need -string LIBPROTOC_EXPORT FileClassName(const FileDescriptor* file); +string PROTOC_EXPORT FileClassName(const FileDescriptor* file); // These return the fully-qualified class name corresponding to the given // descriptor. -string LIBPROTOC_EXPORT ClassName(const Descriptor* descriptor); -string LIBPROTOC_EXPORT ClassName(const Descriptor* descriptor, string* out_suffix_added); -string LIBPROTOC_EXPORT EnumName(const EnumDescriptor* descriptor); +string PROTOC_EXPORT ClassName(const Descriptor* descriptor); +string PROTOC_EXPORT ClassName(const Descriptor* descriptor, + string* out_suffix_added); +string PROTOC_EXPORT EnumName(const EnumDescriptor* descriptor); // Returns the fully-qualified name of the enum value corresponding to the // the descriptor. -string LIBPROTOC_EXPORT EnumValueName(const EnumValueDescriptor* descriptor); +string PROTOC_EXPORT EnumValueName(const EnumValueDescriptor* descriptor); // Returns the name of the enum value corresponding to the descriptor. -string LIBPROTOC_EXPORT EnumValueShortName(const EnumValueDescriptor* descriptor); +string PROTOC_EXPORT EnumValueShortName(const EnumValueDescriptor* descriptor); // Reverse what an enum does. -string LIBPROTOC_EXPORT UnCamelCaseEnumShortName(const string& name); +string PROTOC_EXPORT UnCamelCaseEnumShortName(const string& name); // Returns the name to use for the extension (used as the method off the file's // Root class). -string LIBPROTOC_EXPORT ExtensionMethodName(const FieldDescriptor* descriptor); +string PROTOC_EXPORT ExtensionMethodName(const FieldDescriptor* descriptor); // Returns the transformed field name. -string LIBPROTOC_EXPORT FieldName(const FieldDescriptor* field); -string LIBPROTOC_EXPORT FieldNameCapitalized(const FieldDescriptor* field); +string PROTOC_EXPORT FieldName(const FieldDescriptor* field); +string PROTOC_EXPORT FieldNameCapitalized(const FieldDescriptor* field); // Returns the transformed oneof name. -string LIBPROTOC_EXPORT OneofEnumName(const OneofDescriptor* descriptor); -string LIBPROTOC_EXPORT OneofName(const OneofDescriptor* descriptor); -string LIBPROTOC_EXPORT OneofNameCapitalized(const OneofDescriptor* descriptor); +string PROTOC_EXPORT OneofEnumName(const OneofDescriptor* descriptor); +string PROTOC_EXPORT OneofName(const OneofDescriptor* descriptor); +string PROTOC_EXPORT OneofNameCapitalized(const OneofDescriptor* descriptor); inline bool HasFieldPresence(const FileDescriptor* file) { return file->syntax() != FileDescriptor::SYNTAX_PROTO3; @@ -127,7 +131,8 @@ inline bool IsMapEntryMessage(const Descriptor* descriptor) { } // Reverse of the above. -string LIBPROTOC_EXPORT UnCamelCaseFieldName(const string& name, const FieldDescriptor* field); +string PROTOC_EXPORT UnCamelCaseFieldName(const string& name, + const FieldDescriptor* field); enum ObjectiveCType { OBJECTIVECTYPE_INT32, @@ -158,11 +163,22 @@ string GetOptionalDeprecatedAttribute( // The file is only passed when checking Messages & Enums, so those types // get tagged. At the moment, it doesn't seem to make sense to tag every // field or enum value with when the file is deprecated. + bool isFileLevelDeprecation = false; if (!isDeprecated && file) { - isDeprecated = file->options().deprecated(); + isFileLevelDeprecation = file->options().deprecated(); + isDeprecated = isFileLevelDeprecation; } if (isDeprecated) { - string result = "DEPRECATED_ATTRIBUTE"; + string message; + const FileDescriptor* sourceFile = descriptor->file(); + if (isFileLevelDeprecation) { + message = sourceFile->name() + " is deprecated."; + } else { + message = descriptor->full_name() + " is deprecated (see " + + sourceFile->name() + ")."; + } + + string result = string("GPB_DEPRECATED_MSG(\"") + message + "\")"; if (preSpace) { result.insert(0, " "); } @@ -175,52 +191,59 @@ string GetOptionalDeprecatedAttribute( } } -string LIBPROTOC_EXPORT GetCapitalizedType(const FieldDescriptor* field); +string PROTOC_EXPORT GetCapitalizedType(const FieldDescriptor* field); -ObjectiveCType LIBPROTOC_EXPORT GetObjectiveCType(FieldDescriptor::Type field_type); +ObjectiveCType PROTOC_EXPORT +GetObjectiveCType(FieldDescriptor::Type field_type); inline ObjectiveCType GetObjectiveCType(const FieldDescriptor* field) { return GetObjectiveCType(field->type()); } -bool LIBPROTOC_EXPORT IsPrimitiveType(const FieldDescriptor* field); -bool LIBPROTOC_EXPORT IsReferenceType(const FieldDescriptor* field); +bool PROTOC_EXPORT IsPrimitiveType(const FieldDescriptor* field); +bool PROTOC_EXPORT IsReferenceType(const FieldDescriptor* field); -string LIBPROTOC_EXPORT GPBGenericValueFieldName(const FieldDescriptor* field); -string LIBPROTOC_EXPORT DefaultValue(const FieldDescriptor* field); -bool LIBPROTOC_EXPORT HasNonZeroDefaultValue(const FieldDescriptor* field); +string PROTOC_EXPORT GPBGenericValueFieldName(const FieldDescriptor* field); +string PROTOC_EXPORT DefaultValue(const FieldDescriptor* field); +bool PROTOC_EXPORT HasNonZeroDefaultValue(const FieldDescriptor* field); -string LIBPROTOC_EXPORT BuildFlagsString(const FlagType type, const std::vector& strings); +string PROTOC_EXPORT BuildFlagsString(const FlagType type, + const std::vector& strings); // Builds HeaderDoc/appledoc style comments out of the comments in the .proto // file. -string LIBPROTOC_EXPORT BuildCommentsString(const SourceLocation& location, - bool prefer_single_line); +string PROTOC_EXPORT BuildCommentsString(const SourceLocation& location, + bool prefer_single_line); // The name the commonly used by the library when built as a framework. // This lines up to the name used in the CocoaPod. -extern LIBPROTOC_EXPORT const char* const ProtobufLibraryFrameworkName; +extern PROTOC_EXPORT const char* const ProtobufLibraryFrameworkName; // Returns the CPP symbol name to use as the gate for framework style imports // for the given framework name to use. -string LIBPROTOC_EXPORT ProtobufFrameworkImportSymbol(const string& framework_name); +string PROTOC_EXPORT +ProtobufFrameworkImportSymbol(const string& framework_name); // Checks if the file is one of the proto's bundled with the library. -bool LIBPROTOC_EXPORT IsProtobufLibraryBundledProtoFile(const FileDescriptor* file); +bool PROTOC_EXPORT +IsProtobufLibraryBundledProtoFile(const FileDescriptor* file); // Checks the prefix for the given files and outputs any warnings as needed. If // there are flat out errors, then out_error is filled in with the first error // and the result is false. -bool LIBPROTOC_EXPORT ValidateObjCClassPrefixes(const std::vector& files, - const Options& generation_options, - string* out_error); +bool PROTOC_EXPORT +ValidateObjCClassPrefixes(const std::vector& files, + const Options& generation_options, string* out_error); // Generate decode data needed for ObjC's GPBDecodeTextFormatName() to transform // the input into the expected output. -class LIBPROTOC_EXPORT TextFormatDecodeData { +class PROTOC_EXPORT TextFormatDecodeData { public: TextFormatDecodeData(); ~TextFormatDecodeData(); + TextFormatDecodeData(const TextFormatDecodeData&) = delete; + TextFormatDecodeData& operator=(const TextFormatDecodeData&) = delete; + void AddString(int32 key, const string& input_for_decode, const string& desired_output); size_t num_entries() const { return entries_.size(); } @@ -230,27 +253,25 @@ class LIBPROTOC_EXPORT TextFormatDecodeData { const string& desired_output); private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TextFormatDecodeData); - typedef std::pair DataEntry; std::vector entries_; }; // Helper for parsing simple files. -class LIBPROTOC_EXPORT LineConsumer { +class PROTOC_EXPORT LineConsumer { public: LineConsumer(); virtual ~LineConsumer(); virtual bool ConsumeLine(const StringPiece& line, string* out_error) = 0; }; -bool LIBPROTOC_EXPORT ParseSimpleFile( - const string& path, LineConsumer* line_consumer, string* out_error); - +bool PROTOC_EXPORT ParseSimpleFile(const string& path, + LineConsumer* line_consumer, + string* out_error); // Helper class for parsing framework import mappings and generating // import statements. -class LIBPROTOC_EXPORT ImportWriter { +class PROTOC_EXPORT ImportWriter { public: ImportWriter(const string& generate_for_named_framework, const string& named_framework_to_proto_path_mappings_path, @@ -290,4 +311,7 @@ class LIBPROTOC_EXPORT ImportWriter { } // namespace compiler } // namespace protobuf } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_HELPERS_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc index bcaf5709..6abad8bd 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc @@ -32,11 +32,8 @@ #include #include -#include #include #include -#include -#include namespace google { namespace protobuf { diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_map_field.h b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_map_field.h index dc7beacf..c3085019 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_map_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_map_field.h @@ -47,6 +47,9 @@ class MapFieldGenerator : public RepeatedFieldGenerator { public: virtual void FinishInitialization(void); + MapFieldGenerator(const MapFieldGenerator&) = delete; + MapFieldGenerator& operator=(const MapFieldGenerator&) = delete; + protected: MapFieldGenerator(const FieldDescriptor* descriptor, const Options& options); virtual ~MapFieldGenerator(); @@ -55,8 +58,6 @@ class MapFieldGenerator : public RepeatedFieldGenerator { private: std::unique_ptr value_field_generator_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldGenerator); }; } // namespace objectivec diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_message.cc b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_message.cc index 83888854..a9e84539 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_message.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_message.cc @@ -32,7 +32,6 @@ #include #include -#include #include #include #include @@ -43,7 +42,7 @@ #include #include #include -#include +#include #include namespace google { @@ -462,7 +461,7 @@ void MessageGenerator::GenerateSource(io::Printer* printer) { "typedef struct $classname$__storage_ {\n" " uint32_t _has_storage_[$sizeof_has_storage$];\n", "classname", class_name_, - "sizeof_has_storage", SimpleItoa(sizeof_has_storage)); + "sizeof_has_storage", StrCat(sizeof_has_storage)); printer->Indent(); for (int i = 0; i < descriptor_->field_count(); i++) { @@ -583,8 +582,8 @@ void MessageGenerator::GenerateSource(io::Printer* printer) { " static const GPBExtensionRange ranges[] = {\n"); for (int i = 0; i < sorted_extensions.size(); i++) { printer->Print(" { .start = $start$, .end = $end$ },\n", - "start", SimpleItoa(sorted_extensions[i]->start), - "end", SimpleItoa(sorted_extensions[i]->end)); + "start", StrCat(sorted_extensions[i]->start), + "end", StrCat(sorted_extensions[i]->end)); } printer->Print( " };\n" @@ -605,7 +604,9 @@ void MessageGenerator::GenerateSource(io::Printer* printer) { "suffix", suffix_added); } printer->Print( - " NSAssert(descriptor == nil, @\"Startup recursed!\");\n" + " #if defined(DEBUG) && DEBUG\n" + " NSAssert(descriptor == nil, @\"Startup recursed!\");\n" + " #endif // DEBUG\n" " descriptor = localDescriptor;\n" " }\n" " return descriptor;\n" diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_message.h b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_message.h index 2de03f12..1d41628f 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_message.h +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_message.h @@ -37,15 +37,11 @@ #include #include #include -#include +#include +#include namespace google { namespace protobuf { - -namespace io { -class Printer; // printer.h -} // namespace io - namespace compiler { namespace objectivec { @@ -59,6 +55,9 @@ class MessageGenerator { const Options& options); ~MessageGenerator(); + MessageGenerator(const MessageGenerator&) = delete; + MessageGenerator& operator=(const MessageGenerator&) = delete; + void GenerateStaticVariablesInitialization(io::Printer* printer); void GenerateEnumHeader(io::Printer* printer); void GenerateMessageHeader(io::Printer* printer); @@ -90,11 +89,11 @@ class MessageGenerator { std::vector enum_generators_; std::vector nested_message_generators_; std::vector oneof_generators_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator); }; + } // namespace objectivec } // namespace compiler } // namespace protobuf } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_MESSAGE_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_message_field.cc b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_message_field.cc index 699d25b3..8a0299e7 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_message_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_message_field.cc @@ -35,7 +35,6 @@ #include #include #include -#include namespace google { namespace protobuf { diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_message_field.h b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_message_field.h index 50f4b6d4..98d45794 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_message_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_message_field.h @@ -47,14 +47,15 @@ class MessageFieldGenerator : public ObjCObjFieldGenerator { protected: MessageFieldGenerator(const FieldDescriptor* descriptor, const Options& options); + + MessageFieldGenerator(const MessageFieldGenerator&) = delete; + MessageFieldGenerator& operator=(const MessageFieldGenerator&) = delete; + virtual ~MessageFieldGenerator(); virtual bool WantsHasProperty(void) const; public: virtual void DetermineForwardDeclarations(std::set* fwd_decls) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator); }; class RepeatedMessageFieldGenerator : public RepeatedFieldGenerator { @@ -66,11 +67,11 @@ class RepeatedMessageFieldGenerator : public RepeatedFieldGenerator { const Options& options); virtual ~RepeatedMessageFieldGenerator(); + RepeatedMessageFieldGenerator(const RepeatedMessageFieldGenerator&) = delete; + RepeatedMessageFieldGenerator operator=(const RepeatedMessageFieldGenerator&) = delete; + public: virtual void DetermineForwardDeclarations(std::set* fwd_decls) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator); }; } // namespace objectivec diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_nsobject_methods.h b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_nsobject_methods.h new file mode 100644 index 00000000..16330466 --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_nsobject_methods.h @@ -0,0 +1,197 @@ +// NSObject methods +// Autogenerated by method_dump.sh. Do not edit by hand. +// Date: Thu Nov 1 14:12:16 PDT 2018 +// macOS: MacOSX10.14.sdk +// iOS: iPhoneSimulator12.1.sdk + +const char* const kNSObjectMethodsList[] = { + "CAMLType", + "CA_copyRenderValue", + "CA_prepareRenderValue", + "NS_copyCGImage", + "NS_tiledLayerVisibleRect", + "___tryRetain_OA", + "__autorelease_OA", + "__dealloc_zombie", + "__release_OA", + "__retain_OA", + "_accessibilityFinalize", + "_accessibilityIsTableViewDescendant", + "_accessibilityUIElementSpecifier", + "_accessibilityUseConvenienceAPI", + "_allowsDirectEncoding", + "_asScriptTerminologyNameArray", + "_asScriptTerminologyNameString", + "_bindingAdaptor", + "_cfTypeID", + "_copyDescription", + "_destroyObserverList", + "_didEndKeyValueObserving", + "_implicitObservationInfo", + "_internalAccessibilityAttributedHint", + "_internalAccessibilityAttributedLabel", + "_internalAccessibilityAttributedValue", + "_isAXConnector", + "_isAccessibilityContainerSectionCandidate", + "_isAccessibilityContentNavigatorSectionCandidate", + "_isAccessibilityContentSectionCandidate", + "_isAccessibilityTopLevelNavigatorSectionCandidate", + "_isDeallocating", + "_isKVOA", + "_isToManyChangeInformation", + "_ivarDescription", + "_localClassNameForClass", + "_methodDescription", + "_observerStorage", + "_overrideUseFastBlockObservers", + "_propertyDescription", + "_releaseBindingAdaptor", + "_scriptingCount", + "_scriptingCountNonrecursively", + "_scriptingDebugDescription", + "_scriptingExists", + "_scriptingShouldCheckObjectIndexes", + "_shortMethodDescription", + "_shouldSearchChildrenForSection", + "_traitStorageList", + "_tryRetain", + "_ui_descriptionBuilder", + "_uikit_variesByTraitCollections", + "_web_description", + "_webkit_invokeOnMainThread", + "_willBeginKeyValueObserving", + "accessibilityActivate", + "accessibilityActivationPoint", + "accessibilityAllowsOverriddenAttributesWhenIgnored", + "accessibilityAssistiveTechnologyFocusedIdentifiers", + "accessibilityAttributedHint", + "accessibilityAttributedLabel", + "accessibilityAttributedValue", + "accessibilityContainer", + "accessibilityContainerType", + "accessibilityCustomActions", + "accessibilityCustomRotors", + "accessibilityDecrement", + "accessibilityDragSourceDescriptors", + "accessibilityDropPointDescriptors", + "accessibilityElementCount", + "accessibilityElementDidBecomeFocused", + "accessibilityElementDidLoseFocus", + "accessibilityElementIsFocused", + "accessibilityElements", + "accessibilityElementsHidden", + "accessibilityFrame", + "accessibilityHeaderElements", + "accessibilityHint", + "accessibilityIdentification", + "accessibilityIdentifier", + "accessibilityIncrement", + "accessibilityLabel", + "accessibilityLanguage", + "accessibilityLocalizedStringKey", + "accessibilityNavigationStyle", + "accessibilityOverriddenAttributes", + "accessibilityParameterizedAttributeNames", + "accessibilityPath", + "accessibilityPerformEscape", + "accessibilityPerformMagicTap", + "accessibilityPresenterProcessIdentifier", + "accessibilityShouldUseUniqueId", + "accessibilitySupportsNotifications", + "accessibilitySupportsOverriddenAttributes", + "accessibilityTemporaryChildren", + "accessibilityTraits", + "accessibilityValue", + "accessibilityViewIsModal", + "accessibilityVisibleArea", + "allPropertyKeys", + "allowsWeakReference", + "attributeKeys", + "autoContentAccessingProxy", + "autorelease", + "awakeFromNib", + "boolValueSafe", + "bs_encoded", + "bs_isPlistableType", + "bs_secureEncoded", + "cl_json_serializeKey", + "class", + "classCode", + "classDescription", + "classForArchiver", + "classForCoder", + "classForKeyedArchiver", + "classForPortCoder", + "className", + "clearProperties", + "copy", + "dealloc", + "debugDescription", + "defaultAccessibilityTraits", + "description", + "doubleValueSafe", + "entityName", + "exposedBindings", + "finalize", + "finishObserving", + "flushKeyBindings", + "hash", + "init", + "int64ValueSafe", + "isAccessibilityElement", + "isAccessibilityElementByDefault", + "isElementAccessibilityExposedToInterfaceBuilder", + "isFault", + "isNSArray__", + "isNSCFConstantString__", + "isNSData__", + "isNSDate__", + "isNSDictionary__", + "isNSNumber__", + "isNSObject__", + "isNSOrderedSet__", + "isNSSet__", + "isNSString__", + "isNSTimeZone__", + "isNSValue__", + "isProxy", + "mutableCopy", + "nilValueForKey", + "objectSpecifier", + "observationInfo", + "pep_onDetachedThread", + "pep_onMainThread", + "pep_onMainThreadIfNecessary", + "prepareForInterfaceBuilder", + "release", + "releaseOnMainThread", + "retain", + "retainCount", + "retainWeakReference", + "scriptingProperties", + "self", + "shouldGroupAccessibilityChildren", + "storedAccessibilityActivationPoint", + "storedAccessibilityContainerType", + "storedAccessibilityElementsHidden", + "storedAccessibilityFrame", + "storedAccessibilityNavigationStyle", + "storedAccessibilityTraits", + "storedAccessibilityViewIsModal", + "storedIsAccessibilityElement", + "storedShouldGroupAccessibilityChildren", + "stringValueSafe", + "superclass", + "toManyRelationshipKeys", + "toOneRelationshipKeys", + "traitStorageList", + "un_safeBoolValue", + "userInterfaceItemIdentifier", + "utf8ValueSafe", + "valuesForKeysWithDictionary", + "zone", +// Protocol: CAAnimatableValue +// Protocol: CARenderValue +// Protocol: NSObject +// Protocol: ROCKRemoteInvocationInterface +}; diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc index 5531ae24..5b37c4e9 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc @@ -46,7 +46,7 @@ OneofGenerator::OneofGenerator(const OneofDescriptor* descriptor) variables_["enum_name"] = OneofEnumName(descriptor_); variables_["name"] = OneofName(descriptor_); variables_["capitalized_name"] = OneofNameCapitalized(descriptor_); - variables_["raw_index"] = SimpleItoa(descriptor_->index()); + variables_["raw_index"] = StrCat(descriptor_->index()); const Descriptor* msg_descriptor = descriptor_->containing_type(); variables_["owning_message_class"] = ClassName(msg_descriptor); @@ -65,7 +65,7 @@ OneofGenerator::~OneofGenerator() {} void OneofGenerator::SetOneofIndexBase(int index_base) { int index = descriptor_->index() + index_base; // Flip the sign to mark it as a oneof. - variables_["index"] = SimpleItoa(-index); + variables_["index"] = StrCat(-index); } void OneofGenerator::GenerateCaseEnum(io::Printer* printer) { @@ -84,7 +84,7 @@ void OneofGenerator::GenerateCaseEnum(io::Printer* printer) { "$enum_name$_$field_name$ = $field_number$,\n", "enum_name", enum_name, "field_name", field_name, - "field_number", SimpleItoa(field->number())); + "field_number", StrCat(field->number())); } printer->Outdent(); printer->Print( diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_oneof.h b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_oneof.h index ff353a6c..852ef022 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_oneof.h +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_oneof.h @@ -35,14 +35,9 @@ #include #include #include +#include namespace google { -namespace protobuf { -namespace io { -class Printer; // printer.h -} -} - namespace protobuf { namespace compiler { namespace objectivec { @@ -52,6 +47,9 @@ class OneofGenerator { explicit OneofGenerator(const OneofDescriptor* descriptor); ~OneofGenerator(); + OneofGenerator(const OneofGenerator&) = delete; + OneofGenerator& operator=(const OneofGenerator&) = delete; + void SetOneofIndexBase(int index_base); void GenerateCaseEnum(io::Printer* printer); @@ -68,12 +66,11 @@ class OneofGenerator { private: const OneofDescriptor* descriptor_; std::map variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(OneofGenerator); }; } // namespace objectivec } // namespace compiler } // namespace protobuf } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_ONEOF_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc index aa8ac324..0511b37d 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc @@ -31,14 +31,12 @@ #include #include -#include -#include #include +#include #include -#include -#include #include -#include +#include +#include namespace google { namespace protobuf { @@ -154,7 +152,7 @@ int PrimitiveFieldGenerator::ExtraRuntimeHasBitsNeeded(void) const { void PrimitiveFieldGenerator::SetExtraRuntimeHasBitsBase(int has_base) { if (GetObjectiveCType(descriptor_) == OBJECTIVECTYPE_BOOLEAN) { // Set into the offset the has bit to use for the actual value. - variables_["storage_offset_value"] = SimpleItoa(has_base); + variables_["storage_offset_value"] = StrCat(has_base); variables_["storage_offset_comment"] = " // Stored in _has_storage_ to save space."; } diff --git a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.h b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.h index 69bb1fdd..642f2d63 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.h +++ b/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.h @@ -49,13 +49,13 @@ class PrimitiveFieldGenerator : public SingleFieldGenerator { const Options& options); virtual ~PrimitiveFieldGenerator(); + PrimitiveFieldGenerator(const PrimitiveFieldGenerator&) = delete; + PrimitiveFieldGenerator& operator=(const PrimitiveFieldGenerator&) = delete; + virtual void GenerateFieldStorageDeclaration(io::Printer* printer) const; virtual int ExtraRuntimeHasBitsNeeded(void) const; virtual void SetExtraRuntimeHasBitsBase(int index_base); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator); }; class PrimitiveObjFieldGenerator : public ObjCObjFieldGenerator { @@ -67,8 +67,9 @@ class PrimitiveObjFieldGenerator : public ObjCObjFieldGenerator { const Options& options); virtual ~PrimitiveObjFieldGenerator(); - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveObjFieldGenerator); + PrimitiveObjFieldGenerator(const PrimitiveObjFieldGenerator&) = delete; + PrimitiveObjFieldGenerator& operator=(const PrimitiveObjFieldGenerator&) = + delete; }; class RepeatedPrimitiveFieldGenerator : public RepeatedFieldGenerator { @@ -80,8 +81,10 @@ class RepeatedPrimitiveFieldGenerator : public RepeatedFieldGenerator { const Options& options); virtual ~RepeatedPrimitiveFieldGenerator(); - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator); + RepeatedPrimitiveFieldGenerator(const RepeatedPrimitiveFieldGenerator&) = + delete; + RepeatedPrimitiveFieldGenerator& operator=( + const RepeatedPrimitiveFieldGenerator&) = delete; }; } // namespace objectivec diff --git a/third_party/protobuf/src/google/protobuf/compiler/package_info.h b/third_party/protobuf/src/google/protobuf/compiler/package_info.h index fb6b473e..105ef601 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/package_info.h +++ b/third_party/protobuf/src/google/protobuf/compiler/package_info.h @@ -37,7 +37,6 @@ // documentation generator. namespace google { - namespace protobuf { // Implementation of the Protocol Buffer compiler. diff --git a/third_party/protobuf/src/google/protobuf/compiler/parser.cc b/third_party/protobuf/src/google/protobuf/compiler/parser.cc index 5c7047a6..235c1024 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/parser.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/parser.cc @@ -35,10 +35,12 @@ // Recursive descent FTW. #include -#include #include +#include +#include + #include #include #include @@ -58,28 +60,28 @@ using internal::WireFormat; namespace { -typedef hash_map TypeNameMap; +typedef std::unordered_map TypeNameMap; TypeNameMap MakeTypeNameTable() { TypeNameMap result; - result["double" ] = FieldDescriptorProto::TYPE_DOUBLE; - result["float" ] = FieldDescriptorProto::TYPE_FLOAT; - result["uint64" ] = FieldDescriptorProto::TYPE_UINT64; - result["fixed64" ] = FieldDescriptorProto::TYPE_FIXED64; - result["fixed32" ] = FieldDescriptorProto::TYPE_FIXED32; - result["bool" ] = FieldDescriptorProto::TYPE_BOOL; - result["string" ] = FieldDescriptorProto::TYPE_STRING; - result["group" ] = FieldDescriptorProto::TYPE_GROUP; + result["double"] = FieldDescriptorProto::TYPE_DOUBLE; + result["float"] = FieldDescriptorProto::TYPE_FLOAT; + result["uint64"] = FieldDescriptorProto::TYPE_UINT64; + result["fixed64"] = FieldDescriptorProto::TYPE_FIXED64; + result["fixed32"] = FieldDescriptorProto::TYPE_FIXED32; + result["bool"] = FieldDescriptorProto::TYPE_BOOL; + result["string"] = FieldDescriptorProto::TYPE_STRING; + result["group"] = FieldDescriptorProto::TYPE_GROUP; - result["bytes" ] = FieldDescriptorProto::TYPE_BYTES; - result["uint32" ] = FieldDescriptorProto::TYPE_UINT32; + result["bytes"] = FieldDescriptorProto::TYPE_BYTES; + result["uint32"] = FieldDescriptorProto::TYPE_UINT32; result["sfixed32"] = FieldDescriptorProto::TYPE_SFIXED32; result["sfixed64"] = FieldDescriptorProto::TYPE_SFIXED64; - result["int32" ] = FieldDescriptorProto::TYPE_INT32; - result["int64" ] = FieldDescriptorProto::TYPE_INT64; - result["sint32" ] = FieldDescriptorProto::TYPE_SINT32; - result["sint64" ] = FieldDescriptorProto::TYPE_SINT64; + result["int32"] = FieldDescriptorProto::TYPE_INT32; + result["int64"] = FieldDescriptorProto::TYPE_INT64; + result["sint32"] = FieldDescriptorProto::TYPE_SINT32; + result["sint64"] = FieldDescriptorProto::TYPE_SINT64; return result; } @@ -88,8 +90,8 @@ const TypeNameMap kTypeNames = MakeTypeNameTable(); // Camel-case the field name and append "Entry" for generated map entry name. // e.g. map foo_map => FooMapEntry -string MapEntryName(const string& field_name) { - string result; +std::string MapEntryName(const std::string& field_name) { + std::string result; static const char kSuffix[] = "Entry"; result.reserve(field_name.size() + sizeof(kSuffix)); bool cap_next = true; @@ -112,26 +114,71 @@ string MapEntryName(const string& field_name) { return result; } +bool IsUppercase(char c) { return c >= 'A' && c <= 'Z'; } + +bool IsLowercase(char c) { return c >= 'a' && c <= 'z'; } + +bool IsNumber(char c) { return c >= '0' && c <= '9'; } + +bool IsUpperCamelCase(const string& name) { + if (name.empty()) { + return true; + } + // Name must start with an upper case character. + if (!IsUppercase(name[0])) { + return false; + } + // Must not contains underscore. + for (int i = 1; i < name.length(); i++) { + if (name[i] == '_') { + return false; + } + } + return true; +} + +bool IsUpperUnderscore(const string& name) { + for (int i = 0; i < name.length(); i++) { + const char c = name[i]; + if (!IsUppercase(c) && c != '_' && !IsNumber(c)) { + return false; + } + } + return true; +} + +bool IsLowerUnderscore(const string& name) { + for (int i = 0; i < name.length(); i++) { + const char c = name[i]; + if (!IsLowercase(c) && c != '_' && !IsNumber(c)) { + return false; + } + } + return true; +} + } // anonymous namespace // Makes code slightly more readable. The meaning of "DO(foo)" is // "Execute foo and fail if it fails.", where failure is indicated by // returning false. -#define DO(STATEMENT) if (STATEMENT) {} else return false +#define DO(STATEMENT) \ + if (STATEMENT) { \ + } else \ + return false // =================================================================== Parser::Parser() - : input_(NULL), - error_collector_(NULL), - source_location_table_(NULL), - had_errors_(false), - require_syntax_identifier_(false), - stop_after_syntax_identifier_(false) { + : input_(NULL), + error_collector_(NULL), + source_location_table_(NULL), + had_errors_(false), + require_syntax_identifier_(false), + stop_after_syntax_identifier_(false) { } -Parser::~Parser() { -} +Parser::~Parser() {} // =================================================================== @@ -143,9 +190,7 @@ inline bool Parser::LookingAtType(io::Tokenizer::TokenType token_type) { return input_->current().type == token_type; } -inline bool Parser::AtEnd() { - return LookingAtType(io::Tokenizer::TYPE_END); -} +inline bool Parser::AtEnd() { return LookingAtType(io::Tokenizer::TYPE_END); } bool Parser::TryConsume(const char* text) { if (LookingAt(text)) { @@ -174,7 +219,7 @@ bool Parser::Consume(const char* text) { } } -bool Parser::ConsumeIdentifier(string* output, const char* error) { +bool Parser::ConsumeIdentifier(std::string* output, const char* error) { if (LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) { *output = input_->current().text; input_->Next(); @@ -188,8 +233,8 @@ bool Parser::ConsumeIdentifier(string* output, const char* error) { bool Parser::ConsumeInteger(int* output, const char* error) { if (LookingAtType(io::Tokenizer::TYPE_INTEGER)) { uint64 value = 0; - if (!io::Tokenizer::ParseInteger(input_->current().text, - kint32max, &value)) { + if (!io::Tokenizer::ParseInteger(input_->current().text, kint32max, + &value)) { AddError("Integer out of range."); // We still return true because we did, in fact, parse an integer. } @@ -241,8 +286,8 @@ bool Parser::ConsumeNumber(double* output, const char* error) { } else if (LookingAtType(io::Tokenizer::TYPE_INTEGER)) { // Also accept integers. uint64 value = 0; - if (!io::Tokenizer::ParseInteger(input_->current().text, - kuint64max, &value)) { + if (!io::Tokenizer::ParseInteger(input_->current().text, kuint64max, + &value)) { AddError("Integer out of range."); // We still return true because we did, in fact, parse a number. } @@ -263,7 +308,7 @@ bool Parser::ConsumeNumber(double* output, const char* error) { } } -bool Parser::ConsumeString(string* output, const char* error) { +bool Parser::ConsumeString(std::string* output, const char* error) { if (LookingAtType(io::Tokenizer::TYPE_STRING)) { io::Tokenizer::ParseString(input_->current().text, output); input_->Next(); @@ -279,11 +324,11 @@ bool Parser::ConsumeString(string* output, const char* error) { } } -bool Parser::TryConsumeEndOfDeclaration( - const char* text, const LocationRecorder* location) { +bool Parser::TryConsumeEndOfDeclaration(const char* text, + const LocationRecorder* location) { if (LookingAt(text)) { - string leading, trailing; - std::vector detached; + std::string leading, trailing; + std::vector detached; input_->NextWithComments(&trailing, &detached, &leading); // Save the leading comments for next time, and recall the leading comments @@ -310,8 +355,8 @@ bool Parser::TryConsumeEndOfDeclaration( } } -bool Parser::ConsumeEndOfDeclaration( - const char* text, const LocationRecorder* location) { +bool Parser::ConsumeEndOfDeclaration(const char* text, + const LocationRecorder* location) { if (TryConsumeEndOfDeclaration(text, location)) { return true; } else { @@ -322,23 +367,30 @@ bool Parser::ConsumeEndOfDeclaration( // ------------------------------------------------------------------- -void Parser::AddError(int line, int column, const string& error) { +void Parser::AddError(int line, int column, const std::string& error) { if (error_collector_ != NULL) { error_collector_->AddError(line, column, error); } had_errors_ = true; } -void Parser::AddError(const string& error) { +void Parser::AddError(const std::string& error) { AddError(input_->current().line, input_->current().column, error); } +void Parser::AddWarning(const string& warning) { + if (error_collector_ != nullptr) { + error_collector_->AddWarning(input_->current().line, + input_->current().column, warning); + } +} + // ------------------------------------------------------------------- Parser::LocationRecorder::LocationRecorder(Parser* parser) - : parser_(parser), - source_code_info_(parser->source_code_info_), - location_(parser_->source_code_info_->add_location()) { + : parser_(parser), + source_code_info_(parser->source_code_info_), + location_(parser_->source_code_info_->add_location()) { location_->add_span(parser_->input_->current().line); location_->add_span(parser_->input_->current().column); } @@ -406,7 +458,8 @@ void Parser::LocationRecorder::EndAt(const io::Tokenizer::Token& token) { location_->add_span(token.end_column); } -void Parser::LocationRecorder::RecordLegacyLocation(const Message* descriptor, +void Parser::LocationRecorder::RecordLegacyLocation( + const Message* descriptor, DescriptorPool::ErrorCollector::ErrorLocation location) { if (parser_->source_location_table_ != NULL) { parser_->source_location_table_->Add( @@ -414,13 +467,21 @@ void Parser::LocationRecorder::RecordLegacyLocation(const Message* descriptor, } } +void Parser::LocationRecorder::RecordLegacyImportLocation( + const Message* descriptor, const string& name) { + if (parser_->source_location_table_ != nullptr) { + parser_->source_location_table_->AddImport( + descriptor, name, location_->span(0), location_->span(1)); + } +} + int Parser::LocationRecorder::CurrentPathSize() const { return location_->path_size(); } void Parser::LocationRecorder::AttachComments( - string* leading, string* trailing, - std::vector* detached_comments) const { + std::string* leading, std::string* trailing, + std::vector* detached_comments) const { GOOGLE_CHECK(!location_->has_leading_comments()); GOOGLE_CHECK(!location_->has_trailing_comments()); @@ -431,8 +492,7 @@ void Parser::LocationRecorder::AttachComments( location_->mutable_trailing_comments()->swap(*trailing); } for (int i = 0; i < detached_comments->size(); ++i) { - location_->add_leading_detached_comments()->swap( - (*detached_comments)[i]); + location_->add_leading_detached_comments()->swap((*detached_comments)[i]); } detached_comments->clear(); } @@ -494,7 +554,7 @@ bool Parser::ValidateEnum(const EnumDescriptorProto* proto) { } if (has_allow_alias && !allow_alias) { - string error = + std::string error = "\"" + proto->name() + "\" declares 'option allow_alias = false;' which has no effect. " "Please remove the declaration."; @@ -506,7 +566,7 @@ bool Parser::ValidateEnum(const EnumDescriptorProto* proto) { std::set used_values; bool has_duplicates = false; for (int i = 0; i < proto->value_size(); ++i) { - const EnumValueDescriptorProto enum_value = proto->value(i); + const EnumValueDescriptorProto& enum_value = proto->value(i); if (used_values.find(enum_value.number()) != used_values.end()) { has_duplicates = true; break; @@ -515,7 +575,7 @@ bool Parser::ValidateEnum(const EnumDescriptorProto* proto) { } } if (allow_alias && !has_duplicates) { - string error = + std::string error = "\"" + proto->name() + "\" declares support for enum aliases but no enum values share field " "numbers. Please remove the unnecessary 'option allow_alias = true;' " @@ -526,6 +586,19 @@ bool Parser::ValidateEnum(const EnumDescriptorProto* proto) { return false; } + // Enforce that enum constants must be UPPER_CASE except in case of + // enum_alias. + if (!allow_alias) { + for (const auto& enum_value : proto->value()) { + if (!IsUpperUnderscore(enum_value.name())) { + AddWarning( + "Enum constant should be in UPPER_CASE. Found: " + + enum_value.name() + + ". See https://developers.google.com/protocol-buffers/docs/style"); + } + } + } + return true; } @@ -549,6 +622,8 @@ bool Parser::Parse(io::Tokenizer* input, FileDescriptorProto* file) { { LocationRecorder root_location(this); + root_location.RecordLegacyLocation(file, + DescriptorPool::ErrorCollector::OTHER); if (require_syntax_identifier_ || LookingAt("syntax")) { if (!ParseSyntaxIdentifier(root_location)) { @@ -559,8 +634,8 @@ bool Parser::Parse(io::Tokenizer* input, FileDescriptorProto* file) { // Store the syntax into the file. if (file != NULL) file->set_syntax(syntax_identifier_); } else if (!stop_after_syntax_identifier_) { - GOOGLE_LOG(WARNING) << "No syntax specified for the proto file: " - << file->name() << ". Please use 'syntax = \"proto2\";' " + GOOGLE_LOG(WARNING) << "No syntax specified for the proto file: " << file->name() + << ". Please use 'syntax = \"proto2\";' " << "or 'syntax = \"proto3\";' to specify a syntax " << "version. (Defaulted to proto2 syntax.)"; syntax_identifier_ = "proto2"; @@ -599,7 +674,7 @@ bool Parser::ParseSyntaxIdentifier(const LocationRecorder& parent) { "File must begin with a syntax statement, e.g. 'syntax = \"proto2\";'.")); DO(Consume("=")); io::Tokenizer::Token syntax_token = input_->current(); - string syntax; + std::string syntax; DO(ConsumeString(&syntax, "Expected syntax identifier.")); DO(ConsumeEndOfDeclaration(";", &syntax_location)); @@ -608,8 +683,9 @@ bool Parser::ParseSyntaxIdentifier(const LocationRecorder& parent) { if (syntax != "proto2" && syntax != "proto3" && !stop_after_syntax_identifier_) { AddError(syntax_token.line, syntax_token.column, - "Unrecognized syntax identifier \"" + syntax + "\". This parser " - "only recognizes \"proto2\" and \"proto3\"."); + "Unrecognized syntax identifier \"" + syntax + + "\". This parser " + "only recognizes \"proto2\" and \"proto3\"."); return false; } @@ -623,34 +699,34 @@ bool Parser::ParseTopLevelStatement(FileDescriptorProto* file, return true; } else if (LookingAt("message")) { LocationRecorder location(root_location, - FileDescriptorProto::kMessageTypeFieldNumber, file->message_type_size()); + FileDescriptorProto::kMessageTypeFieldNumber, + file->message_type_size()); return ParseMessageDefinition(file->add_message_type(), location, file); } else if (LookingAt("enum")) { LocationRecorder location(root_location, - FileDescriptorProto::kEnumTypeFieldNumber, file->enum_type_size()); + FileDescriptorProto::kEnumTypeFieldNumber, + file->enum_type_size()); return ParseEnumDefinition(file->add_enum_type(), location, file); } else if (LookingAt("service")) { LocationRecorder location(root_location, - FileDescriptorProto::kServiceFieldNumber, file->service_size()); + FileDescriptorProto::kServiceFieldNumber, + file->service_size()); return ParseServiceDefinition(file->add_service(), location, file); } else if (LookingAt("extend")) { LocationRecorder location(root_location, - FileDescriptorProto::kExtensionFieldNumber); - return ParseExtend(file->mutable_extension(), - file->mutable_message_type(), - root_location, - FileDescriptorProto::kMessageTypeFieldNumber, - location, file); + FileDescriptorProto::kExtensionFieldNumber); + return ParseExtend( + file->mutable_extension(), file->mutable_message_type(), root_location, + FileDescriptorProto::kMessageTypeFieldNumber, location, file); } else if (LookingAt("import")) { return ParseImport(file->mutable_dependency(), file->mutable_public_dependency(), - file->mutable_weak_dependency(), - root_location, file); + file->mutable_weak_dependency(), root_location, file); } else if (LookingAt("package")) { return ParsePackage(file, root_location, file); } else if (LookingAt("option")) { LocationRecorder location(root_location, - FileDescriptorProto::kOptionsFieldNumber); + FileDescriptorProto::kOptionsFieldNumber); return ParseOption(file->mutable_options(), location, file, OPTION_STATEMENT); } else { @@ -663,16 +739,21 @@ bool Parser::ParseTopLevelStatement(FileDescriptorProto* file, // Messages bool Parser::ParseMessageDefinition( - DescriptorProto* message, - const LocationRecorder& message_location, + DescriptorProto* message, const LocationRecorder& message_location, const FileDescriptorProto* containing_file) { DO(Consume("message")); { LocationRecorder location(message_location, DescriptorProto::kNameFieldNumber); - location.RecordLegacyLocation( - message, DescriptorPool::ErrorCollector::NAME); + location.RecordLegacyLocation(message, + DescriptorPool::ErrorCollector::NAME); DO(ConsumeIdentifier(message->mutable_name(), "Expected message name.")); + if (!IsUpperCamelCase(message->name())) { + AddWarning( + "Message name should be in UpperCamelCase. Found: " + + message->name() + + ". See https://developers.google.com/protocol-buffers/docs/style"); + } } DO(ParseMessageBlock(message, message_location, containing_file)); return true; @@ -700,9 +781,8 @@ bool IsMessageSetWireFormatMessage(const DescriptorProto& message) { // tag number can only be determined after all options have been parsed. void AdjustExtensionRangesWithMaxEndNumber(DescriptorProto* message) { const bool is_message_set = IsMessageSetWireFormatMessage(*message); - const int max_extension_number = is_message_set ? - kint32max : - FieldDescriptor::kMaxNumber + 1; + const int max_extension_number = + is_message_set ? kint32max : FieldDescriptor::kMaxNumber + 1; for (int i = 0; i < message->extension_range_size(); ++i) { if (message->extension_range(i).end() == kMaxRangeSentinel) { message->mutable_extension_range(i)->set_end(max_extension_number); @@ -715,9 +795,8 @@ void AdjustExtensionRangesWithMaxEndNumber(DescriptorProto* message) { // tag number can only be determined after all options have been parsed. void AdjustReservedRangesWithMaxEndNumber(DescriptorProto* message) { const bool is_message_set = IsMessageSetWireFormatMessage(*message); - const int max_field_number = is_message_set ? - kint32max : - FieldDescriptor::kMaxNumber + 1; + const int max_field_number = + is_message_set ? kint32max : FieldDescriptor::kMaxNumber + 1; for (int i = 0; i < message->reserved_range_size(); ++i) { if (message->reserved_range(i).end() == kMaxRangeSentinel) { message->mutable_reserved_range(i)->set_end(max_field_number); @@ -782,34 +861,28 @@ bool Parser::ParseMessageStatement(DescriptorProto* message, LocationRecorder location(message_location, DescriptorProto::kExtensionFieldNumber); return ParseExtend(message->mutable_extension(), - message->mutable_nested_type(), - message_location, - DescriptorProto::kNestedTypeFieldNumber, - location, containing_file); + message->mutable_nested_type(), message_location, + DescriptorProto::kNestedTypeFieldNumber, location, + containing_file); } else if (LookingAt("option")) { LocationRecorder location(message_location, DescriptorProto::kOptionsFieldNumber); - return ParseOption(message->mutable_options(), location, - containing_file, OPTION_STATEMENT); + return ParseOption(message->mutable_options(), location, containing_file, + OPTION_STATEMENT); } else if (LookingAt("oneof")) { int oneof_index = message->oneof_decl_size(); - LocationRecorder oneof_location(message_location, - DescriptorProto::kOneofDeclFieldNumber, - oneof_index); + LocationRecorder oneof_location( + message_location, DescriptorProto::kOneofDeclFieldNumber, oneof_index); - return ParseOneof(message->add_oneof_decl(), message, - oneof_index, oneof_location, message_location, - containing_file); + return ParseOneof(message->add_oneof_decl(), message, oneof_index, + oneof_location, message_location, containing_file); } else { LocationRecorder location(message_location, DescriptorProto::kFieldFieldNumber, message->field_size()); - return ParseMessageField(message->add_field(), - message->mutable_nested_type(), - message_location, - DescriptorProto::kNestedTypeFieldNumber, - location, - containing_file); + return ParseMessageField( + message->add_field(), message->mutable_nested_type(), message_location, + DescriptorProto::kNestedTypeFieldNumber, location, containing_file); } } @@ -837,13 +910,11 @@ bool Parser::ParseMessageField(FieldDescriptorProto* field, return ParseMessageFieldNoLabel(field, messages, parent_location, location_field_number_for_nested_type, - field_location, - containing_file); + field_location, containing_file); } bool Parser::ParseMessageFieldNoLabel( - FieldDescriptorProto* field, - RepeatedPtrField* messages, + FieldDescriptorProto* field, RepeatedPtrField* messages, const LocationRecorder& parent_location, int location_field_number_for_nested_type, const LocationRecorder& field_location, @@ -856,7 +927,7 @@ bool Parser::ParseMessageFieldNoLabel( bool type_parsed = false; FieldDescriptorProto::Type type = FieldDescriptorProto::TYPE_INT32; - string type_name; + std::string type_name; // Special case map field. We only treat the field as a map field if the // field type name starts with the word "map" with a following "<". @@ -927,6 +998,12 @@ bool Parser::ParseMessageFieldNoLabel( FieldDescriptorProto::kNameFieldNumber); location.RecordLegacyLocation(field, DescriptorPool::ErrorCollector::NAME); DO(ConsumeIdentifier(field->mutable_name(), "Expected field name.")); + + if (!IsLowerUnderscore(field->name())) { + AddWarning( + "Field name should be lowercase. Found: " + field->name() + + ". See: https://developers.google.com/protocol-buffers/docs/style"); + } } DO(Consume("=", "Missing field number.")); @@ -934,8 +1011,8 @@ bool Parser::ParseMessageFieldNoLabel( { LocationRecorder location(field_location, FieldDescriptorProto::kNumberFieldNumber); - location.RecordLegacyLocation( - field, DescriptorPool::ErrorCollector::NUMBER); + location.RecordLegacyLocation(field, + DescriptorPool::ErrorCollector::NUMBER); int number; DO(ConsumeInteger(&number, "Expected field number.")); field->set_number(number); @@ -962,8 +1039,8 @@ bool Parser::ParseMessageFieldNoLabel( DescriptorProto::kNameFieldNumber); location.StartAt(name_token); location.EndAt(name_token); - location.RecordLegacyLocation( - group, DescriptorPool::ErrorCollector::NAME); + location.RecordLegacyLocation(group, + DescriptorPool::ErrorCollector::NAME); } // The field's type_name also comes from the name. Confusing! @@ -979,7 +1056,7 @@ bool Parser::ParseMessageFieldNoLabel( // not use groups; it should use nested messages. if (group->name()[0] < 'A' || 'Z' < group->name()[0]) { AddError(name_token.line, name_token.column, - "Group names must start with a capital letter."); + "Group names must start with a capital letter."); } LowerString(field->mutable_name()); @@ -1006,7 +1083,7 @@ void Parser::GenerateMapEntry(const MapField& map_field, FieldDescriptorProto* field, RepeatedPtrField* messages) { DescriptorProto* entry = messages->Add(); - string entry_name = MapEntryName(field->name()); + std::string entry_name = MapEntryName(field->name()); field->set_type_name(entry_name); entry->set_name(entry_name); entry->mutable_options()->set_map_entry(true); @@ -1055,12 +1132,12 @@ void Parser::GenerateMapEntry(const MapField& map_field, option.name(0).name_part() == "enforce_utf8" && !option.name(0).is_extension()) { if (key_field->type() == FieldDescriptorProto::TYPE_STRING) { - key_field->mutable_options()->add_uninterpreted_option() - ->CopyFrom(option); + key_field->mutable_options()->add_uninterpreted_option()->CopyFrom( + option); } if (value_field->type() == FieldDescriptorProto::TYPE_STRING) { - value_field->mutable_options()->add_uninterpreted_option() - ->CopyFrom(option); + value_field->mutable_options()->add_uninterpreted_option()->CopyFrom( + option); } } } @@ -1086,8 +1163,8 @@ bool Parser::ParseFieldOptions(FieldDescriptorProto* field, // Like default value, this "json_name" is not an actual option. DO(ParseJsonName(field, field_location, containing_file)); } else { - DO(ParseOption(field->mutable_options(), location, - containing_file, OPTION_ASSIGNMENT)); + DO(ParseOption(field->mutable_options(), location, containing_file, + OPTION_ASSIGNMENT)); } } while (TryConsume(",")); @@ -1096,8 +1173,7 @@ bool Parser::ParseFieldOptions(FieldDescriptorProto* field, } bool Parser::ParseDefaultAssignment( - FieldDescriptorProto* field, - const LocationRecorder& field_location, + FieldDescriptorProto* field, const LocationRecorder& field_location, const FileDescriptorProto* containing_file) { if (field->has_default_value()) { AddError("Already set option \"default\"."); @@ -1109,9 +1185,9 @@ bool Parser::ParseDefaultAssignment( LocationRecorder location(field_location, FieldDescriptorProto::kDefaultValueFieldNumber); - location.RecordLegacyLocation( - field, DescriptorPool::ErrorCollector::DEFAULT_VALUE); - string* default_value = field->mutable_default_value(); + location.RecordLegacyLocation(field, + DescriptorPool::ErrorCollector::DEFAULT_VALUE); + std::string* default_value = field->mutable_default_value(); if (!field->has_type()) { // The field has a type name, but we don't know if it is a message or an @@ -1153,7 +1229,7 @@ bool Parser::ParseDefaultAssignment( DO(ConsumeInteger64(max_value, &value, "Expected integer for field default value.")); // And stringify it again. - default_value->append(SimpleItoa(value)); + default_value->append(StrCat(value)); break; } @@ -1176,7 +1252,7 @@ bool Parser::ParseDefaultAssignment( DO(ConsumeInteger64(max_value, &value, "Expected integer for field default value.")); // And stringify it again. - default_value->append(SimpleItoa(value)); + default_value->append(StrCat(value)); break; } @@ -1209,7 +1285,8 @@ bool Parser::ParseDefaultAssignment( // Note: When file opton java_string_check_utf8 is true, if a // non-string representation (eg byte[]) is later supported, it must // be checked for UTF-8-ness. - DO(ConsumeString(default_value, "Expected string for field default " + DO(ConsumeString(default_value, + "Expected string for field default " "value.")); break; @@ -1219,8 +1296,9 @@ bool Parser::ParseDefaultAssignment( break; case FieldDescriptorProto::TYPE_ENUM: - DO(ConsumeIdentifier(default_value, "Expected enum identifier for field " - "default value.")); + DO(ConsumeIdentifier(default_value, + "Expected enum identifier for field " + "default value.")); break; case FieldDescriptorProto::TYPE_MESSAGE: @@ -1232,34 +1310,37 @@ bool Parser::ParseDefaultAssignment( return true; } -bool Parser::ParseJsonName( - FieldDescriptorProto* field, - const LocationRecorder& field_location, - const FileDescriptorProto* containing_file) { +bool Parser::ParseJsonName(FieldDescriptorProto* field, + const LocationRecorder& field_location, + const FileDescriptorProto* containing_file) { if (field->has_json_name()) { AddError("Already set option \"json_name\"."); field->clear_json_name(); } + LocationRecorder location(field_location, + FieldDescriptorProto::kJsonNameFieldNumber); + location.RecordLegacyLocation(field, + DescriptorPool::ErrorCollector::OPTION_NAME); + DO(Consume("json_name")); DO(Consume("=")); - LocationRecorder location(field_location, - FieldDescriptorProto::kJsonNameFieldNumber); - location.RecordLegacyLocation( + LocationRecorder value_location(location); + value_location.RecordLegacyLocation( field, DescriptorPool::ErrorCollector::OPTION_VALUE); + DO(ConsumeString(field->mutable_json_name(), "Expected string for JSON name.")); return true; } - bool Parser::ParseOptionNamePart(UninterpretedOption* uninterpreted_option, const LocationRecorder& part_location, const FileDescriptorProto* containing_file) { UninterpretedOption::NamePart* name = uninterpreted_option->add_name(); - string identifier; // We parse identifiers into this string. - if (LookingAt("(")) { // This is an extension. + std::string identifier; // We parse identifiers into this string. + if (LookingAt("(")) { // This is an extension. DO(Consume("(")); { @@ -1291,7 +1372,7 @@ bool Parser::ParseOptionNamePart(UninterpretedOption* uninterpreted_option, return true; } -bool Parser::ParseUninterpretedBlock(string* value) { +bool Parser::ParseUninterpretedBlock(std::string* value) { // Note that enclosing braces are not added to *value. // We do NOT use ConsumeEndOfStatement for this brace because it's delimiting // an expression, not a block of statements. @@ -1323,8 +1404,8 @@ bool Parser::ParseOption(Message* options, const FileDescriptorProto* containing_file, OptionStyle style) { // Create an entry in the uninterpreted_option field. - const FieldDescriptor* uninterpreted_option_field = options->GetDescriptor()-> - FindFieldByName("uninterpreted_option"); + const FieldDescriptor* uninterpreted_option_field = + options->GetDescriptor()->FindFieldByName("uninterpreted_option"); GOOGLE_CHECK(uninterpreted_option_field != NULL) << "No field named \"uninterpreted_option\" in the Options proto."; @@ -1338,9 +1419,9 @@ bool Parser::ParseOption(Message* options, DO(Consume("option")); } - UninterpretedOption* uninterpreted_option = down_cast( - options->GetReflection()->AddMessage(options, - uninterpreted_option_field)); + UninterpretedOption* uninterpreted_option = + down_cast(options->GetReflection()->AddMessage( + options, uninterpreted_option_field)); // Parse dot-separated name. { @@ -1392,7 +1473,7 @@ bool Parser::ParseOption(Message* options, AddError("Invalid '-' symbol before identifier."); return false; } - string value; + std::string value; DO(ConsumeIdentifier(&value, "Expected identifier.")); uninterpreted_option->set_identifier_value(value); break; @@ -1430,7 +1511,7 @@ bool Parser::ParseOption(Message* options, AddError("Invalid '-' symbol before string."); return false; } - string value; + std::string value; DO(ConsumeString(&value, "Expected string.")); uninterpreted_option->set_string_value(value); break; @@ -1471,8 +1552,8 @@ bool Parser::ParseExtensions(DescriptorProto* message, message->extension_range_size()); DescriptorProto::ExtensionRange* range = message->add_extension_range(); - location.RecordLegacyLocation( - range, DescriptorPool::ErrorCollector::NUMBER); + location.RecordLegacyLocation(range, + DescriptorPool::ErrorCollector::NUMBER); int start, end; io::Tokenizer::Token start_token; @@ -1511,7 +1592,6 @@ bool Parser::ParseExtensions(DescriptorProto* message, range->set_end(end); } while (TryConsume(",")); - if (LookingAt("[")) { int range_number_index = extensions_location.CurrentPathSize(); SourceCodeInfo info; @@ -1525,8 +1605,7 @@ bool Parser::ParseExtensions(DescriptorProto* message, extensions_location, 0 /* we fill this in w/ actual index below */, &info); LocationRecorder location( - index_location, - DescriptorProto::ExtensionRange::kOptionsFieldNumber); + index_location, DescriptorProto::ExtensionRange::kOptionsFieldNumber); DO(Consume("[")); do { @@ -1539,19 +1618,19 @@ bool Parser::ParseExtensions(DescriptorProto* message, // Then copy the extension range options to all of the other ranges we've // parsed. for (int i = old_range_size + 1; i < message->extension_range_size(); i++) { - message->mutable_extension_range(i)->mutable_options() - ->CopyFrom(*options); + message->mutable_extension_range(i)->mutable_options()->CopyFrom( + *options); } // and copy source locations to the other ranges, too for (int i = old_range_size; i < message->extension_range_size(); i++) { for (int j = 0; j < info.location_size(); j++) { if (info.location(j).path_size() == range_number_index + 1) { - // this location's path is up to the extension range index, but doesn't - // include options; so it's redundant with location above + // this location's path is up to the extension range index, but + // doesn't include options; so it's redundant with location above continue; } SourceCodeInfo_Location* dest = source_code_info_->add_location(); - dest->CopyFrom(info.location(j)); + *dest = info.location(j); dest->set_path(range_number_index, i); } } @@ -1565,15 +1644,18 @@ bool Parser::ParseExtensions(DescriptorProto* message, // name literals. bool Parser::ParseReserved(DescriptorProto* message, const LocationRecorder& message_location) { + io::Tokenizer::Token start_token = input_->current(); // Parse the declaration. DO(Consume("reserved")); if (LookingAtType(io::Tokenizer::TYPE_STRING)) { LocationRecorder location(message_location, DescriptorProto::kReservedNameFieldNumber); + location.StartAt(start_token); return ParseReservedNames(message, location); } else { LocationRecorder location(message_location, DescriptorProto::kReservedRangeFieldNumber); + location.StartAt(start_token); return ParseReservedNumbers(message, location); } } @@ -1601,9 +1683,8 @@ bool Parser::ParseReservedNumbers(DescriptorProto* message, LocationRecorder start_location( location, DescriptorProto::ReservedRange::kStartFieldNumber); start_token = input_->current(); - DO(ConsumeInteger(&start, (first ? - "Expected field name or number range." : - "Expected field number range."))); + DO(ConsumeInteger(&start, (first ? "Expected field name or number range." + : "Expected field number range."))); } if (TryConsume("to")) { @@ -1639,16 +1720,19 @@ bool Parser::ParseReservedNumbers(DescriptorProto* message, } bool Parser::ParseReserved(EnumDescriptorProto* message, - const LocationRecorder& message_location) { + const LocationRecorder& message_location) { + io::Tokenizer::Token start_token = input_->current(); // Parse the declaration. DO(Consume("reserved")); if (LookingAtType(io::Tokenizer::TYPE_STRING)) { LocationRecorder location(message_location, DescriptorProto::kReservedNameFieldNumber); + location.StartAt(start_token); return ParseReservedNames(message, location); } else { LocationRecorder location(message_location, DescriptorProto::kReservedRangeFieldNumber); + location.StartAt(start_token); return ParseReservedNumbers(message, location); } } @@ -1677,9 +1761,9 @@ bool Parser::ParseReservedNumbers(EnumDescriptorProto* message, LocationRecorder start_location( location, EnumDescriptorProto::EnumReservedRange::kStartFieldNumber); start_token = input_->current(); - DO(ConsumeSignedInteger(&start, (first ? - "Expected enum value or number range." : - "Expected enum number range."))); + DO(ConsumeSignedInteger(&start, + (first ? "Expected enum value or number range." + : "Expected enum number range."))); } if (TryConsume("to")) { @@ -1719,7 +1803,7 @@ bool Parser::ParseExtend(RepeatedPtrField* extensions, // Parse the extendee type. io::Tokenizer::Token extendee_start = input_->current(); - string extendee; + std::string extendee; DO(ParseUserDefinedType(&extendee)); io::Tokenizer::Token extendee_end = input_->previous(); @@ -1755,8 +1839,7 @@ bool Parser::ParseExtend(RepeatedPtrField* extensions, field->set_extendee(extendee); if (!ParseMessageField(field, messages, parent_location, - location_field_number_for_nested_type, - location, + location_field_number_for_nested_type, location, containing_file)) { // This statement failed to parse. Skip it, but keep looping to parse // other statements. @@ -1768,8 +1851,7 @@ bool Parser::ParseExtend(RepeatedPtrField* extensions, } bool Parser::ParseOneof(OneofDescriptorProto* oneof_decl, - DescriptorProto* containing_type, - int oneof_index, + DescriptorProto* containing_type, int oneof_index, const LocationRecorder& oneof_location, const LocationRecorder& containing_type_location, const FileDescriptorProto* containing_file) { @@ -1801,11 +1883,11 @@ bool Parser::ParseOneof(OneofDescriptorProto* oneof_decl, // Print a nice error if the user accidentally tries to place a label // on an individual member of a oneof. - if (LookingAt("required") || - LookingAt("optional") || + if (LookingAt("required") || LookingAt("optional") || LookingAt("repeated")) { - AddError("Fields in oneofs must not have labels (required / optional " - "/ repeated)."); + AddError( + "Fields in oneofs must not have labels (required / optional " + "/ repeated)."); // We can continue parsing here because we understand what the user // meant. The error report will still make parsing fail overall. input_->Next(); @@ -1819,12 +1901,10 @@ bool Parser::ParseOneof(OneofDescriptorProto* oneof_decl, field->set_label(FieldDescriptorProto::LABEL_OPTIONAL); field->set_oneof_index(oneof_index); - if (!ParseMessageFieldNoLabel(field, - containing_type->mutable_nested_type(), + if (!ParseMessageFieldNoLabel(field, containing_type->mutable_nested_type(), containing_type_location, DescriptorProto::kNestedTypeFieldNumber, - field_location, - containing_file)) { + field_location, containing_file)) { // This statement failed to parse. Skip it, but keep looping to parse // other statements. SkipStatement(); @@ -1845,8 +1925,8 @@ bool Parser::ParseEnumDefinition(EnumDescriptorProto* enum_type, { LocationRecorder location(enum_location, EnumDescriptorProto::kNameFieldNumber); - location.RecordLegacyLocation( - enum_type, DescriptorPool::ErrorCollector::NAME); + location.RecordLegacyLocation(enum_type, + DescriptorPool::ErrorCollector::NAME); DO(ConsumeIdentifier(enum_type->mutable_name(), "Expected enum name.")); } @@ -1887,13 +1967,14 @@ bool Parser::ParseEnumStatement(EnumDescriptorProto* enum_type, } else if (LookingAt("option")) { LocationRecorder location(enum_location, EnumDescriptorProto::kOptionsFieldNumber); - return ParseOption(enum_type->mutable_options(), location, - containing_file, OPTION_STATEMENT); + return ParseOption(enum_type->mutable_options(), location, containing_file, + OPTION_STATEMENT); } else if (LookingAt("reserved")) { return ParseReserved(enum_type, enum_location); } else { LocationRecorder location(enum_location, - EnumDescriptorProto::kValueFieldNumber, enum_type->value_size()); + EnumDescriptorProto::kValueFieldNumber, + enum_type->value_size()); return ParseEnumConstant(enum_type->add_value(), location, containing_file); } } @@ -1905,8 +1986,8 @@ bool Parser::ParseEnumConstant(EnumValueDescriptorProto* enum_value, { LocationRecorder location(enum_value_location, EnumValueDescriptorProto::kNameFieldNumber); - location.RecordLegacyLocation( - enum_value, DescriptorPool::ErrorCollector::NAME); + location.RecordLegacyLocation(enum_value, + DescriptorPool::ErrorCollector::NAME); DO(ConsumeIdentifier(enum_value->mutable_name(), "Expected enum constant name.")); } @@ -1915,10 +1996,10 @@ bool Parser::ParseEnumConstant(EnumValueDescriptorProto* enum_value, // Parse value. { - LocationRecorder location( - enum_value_location, EnumValueDescriptorProto::kNumberFieldNumber); - location.RecordLegacyLocation( - enum_value, DescriptorPool::ErrorCollector::NUMBER); + LocationRecorder location(enum_value_location, + EnumValueDescriptorProto::kNumberFieldNumber); + location.RecordLegacyLocation(enum_value, + DescriptorPool::ErrorCollector::NUMBER); int number; DO(ConsumeSignedInteger(&number, "Expected integer.")); @@ -1939,14 +2020,14 @@ bool Parser::ParseEnumConstantOptions( const FileDescriptorProto* containing_file) { if (!LookingAt("[")) return true; - LocationRecorder location( - enum_value_location, EnumValueDescriptorProto::kOptionsFieldNumber); + LocationRecorder location(enum_value_location, + EnumValueDescriptorProto::kOptionsFieldNumber); DO(Consume("[")); do { - DO(ParseOption(value->mutable_options(), location, - containing_file, OPTION_ASSIGNMENT)); + DO(ParseOption(value->mutable_options(), location, containing_file, + OPTION_ASSIGNMENT)); } while (TryConsume(",")); DO(Consume("]")); @@ -1957,16 +2038,15 @@ bool Parser::ParseEnumConstantOptions( // Services bool Parser::ParseServiceDefinition( - ServiceDescriptorProto* service, - const LocationRecorder& service_location, + ServiceDescriptorProto* service, const LocationRecorder& service_location, const FileDescriptorProto* containing_file) { DO(Consume("service")); { LocationRecorder location(service_location, ServiceDescriptorProto::kNameFieldNumber); - location.RecordLegacyLocation( - service, DescriptorPool::ErrorCollector::NAME); + location.RecordLegacyLocation(service, + DescriptorPool::ErrorCollector::NAME); DO(ConsumeIdentifier(service->mutable_name(), "Expected service name.")); } @@ -2002,13 +2082,14 @@ bool Parser::ParseServiceStatement(ServiceDescriptorProto* service, // empty statement; ignore return true; } else if (LookingAt("option")) { - LocationRecorder location( - service_location, ServiceDescriptorProto::kOptionsFieldNumber); - return ParseOption(service->mutable_options(), location, - containing_file, OPTION_STATEMENT); + LocationRecorder location(service_location, + ServiceDescriptorProto::kOptionsFieldNumber); + return ParseOption(service->mutable_options(), location, containing_file, + OPTION_STATEMENT); } else { LocationRecorder location(service_location, - ServiceDescriptorProto::kMethodFieldNumber, service->method_size()); + ServiceDescriptorProto::kMethodFieldNumber, + service->method_size()); return ParseServiceMethod(service->add_method(), location, containing_file); } } @@ -2021,8 +2102,7 @@ bool Parser::ParseServiceMethod(MethodDescriptorProto* method, { LocationRecorder location(method_location, MethodDescriptorProto::kNameFieldNumber); - location.RecordLegacyLocation( - method, DescriptorPool::ErrorCollector::NAME); + location.RecordLegacyLocation(method, DescriptorPool::ErrorCollector::NAME); DO(ConsumeIdentifier(method->mutable_name(), "Expected method name.")); } @@ -2032,16 +2112,16 @@ bool Parser::ParseServiceMethod(MethodDescriptorProto* method, if (LookingAt("stream")) { LocationRecorder location( method_location, MethodDescriptorProto::kClientStreamingFieldNumber); - location.RecordLegacyLocation( - method, DescriptorPool::ErrorCollector::OTHER); + location.RecordLegacyLocation(method, + DescriptorPool::ErrorCollector::OTHER); method->set_client_streaming(true); DO(Consume("stream")); } LocationRecorder location(method_location, MethodDescriptorProto::kInputTypeFieldNumber); - location.RecordLegacyLocation( - method, DescriptorPool::ErrorCollector::INPUT_TYPE); + location.RecordLegacyLocation(method, + DescriptorPool::ErrorCollector::INPUT_TYPE); DO(ParseUserDefinedType(method->mutable_input_type())); } DO(Consume(")")); @@ -2053,16 +2133,16 @@ bool Parser::ParseServiceMethod(MethodDescriptorProto* method, if (LookingAt("stream")) { LocationRecorder location( method_location, MethodDescriptorProto::kServerStreamingFieldNumber); - location.RecordLegacyLocation( - method, DescriptorPool::ErrorCollector::OTHER); + location.RecordLegacyLocation(method, + DescriptorPool::ErrorCollector::OTHER); DO(Consume("stream")); method->set_server_streaming(true); } LocationRecorder location(method_location, MethodDescriptorProto::kOutputTypeFieldNumber); - location.RecordLegacyLocation( - method, DescriptorPool::ErrorCollector::OUTPUT_TYPE); + location.RecordLegacyLocation(method, + DescriptorPool::ErrorCollector::OUTPUT_TYPE); DO(ParseUserDefinedType(method->mutable_output_type())); } DO(Consume(")")); @@ -2095,10 +2175,9 @@ bool Parser::ParseMethodOptions(const LocationRecorder& parent_location, if (TryConsumeEndOfDeclaration(";", NULL)) { // empty statement; ignore } else { - LocationRecorder location(parent_location, - optionsFieldNumber); - if (!ParseOption(mutable_options, location, - containing_file, OPTION_STATEMENT)) { + LocationRecorder location(parent_location, optionsFieldNumber); + if (!ParseOption(mutable_options, location, containing_file, + OPTION_STATEMENT)) { // This statement failed to parse. Skip it, but keep looping to // parse other statements. SkipStatement(); @@ -2127,7 +2206,7 @@ bool Parser::ParseLabel(FieldDescriptorProto::Label* label, } bool Parser::ParseType(FieldDescriptorProto::Type* type, - string* type_name) { + std::string* type_name) { TypeNameMap::const_iterator iter = kTypeNames.find(input_->current().text); if (iter != kTypeNames.end()) { *type = iter->second; @@ -2138,7 +2217,7 @@ bool Parser::ParseType(FieldDescriptorProto::Type* type, return true; } -bool Parser::ParseUserDefinedType(string* type_name) { +bool Parser::ParseUserDefinedType(std::string* type_name) { type_name->clear(); TypeNameMap::const_iterator iter = kTypeNames.find(input_->current().text); @@ -2159,7 +2238,7 @@ bool Parser::ParseUserDefinedType(string* type_name) { if (TryConsume(".")) type_name->append("."); // Consume the first part of the name. - string identifier; + std::string identifier; DO(ConsumeIdentifier(&identifier, "Expected type name.")); type_name->append(identifier); @@ -2185,59 +2264,59 @@ bool Parser::ParsePackage(FileDescriptorProto* file, file->clear_package(); } + LocationRecorder location(root_location, + FileDescriptorProto::kPackageFieldNumber); + location.RecordLegacyLocation(file, DescriptorPool::ErrorCollector::NAME); + DO(Consume("package")); - { - LocationRecorder location(root_location, - FileDescriptorProto::kPackageFieldNumber); - location.RecordLegacyLocation(file, DescriptorPool::ErrorCollector::NAME); - - while (true) { - string identifier; - DO(ConsumeIdentifier(&identifier, "Expected identifier.")); - file->mutable_package()->append(identifier); - if (!TryConsume(".")) break; - file->mutable_package()->append("."); - } - - location.EndAt(input_->previous()); - - DO(ConsumeEndOfDeclaration(";", &location)); + while (true) { + std::string identifier; + DO(ConsumeIdentifier(&identifier, "Expected identifier.")); + file->mutable_package()->append(identifier); + if (!TryConsume(".")) break; + file->mutable_package()->append("."); } + DO(ConsumeEndOfDeclaration(";", &location)); + return true; } -bool Parser::ParseImport(RepeatedPtrField* dependency, +bool Parser::ParseImport(RepeatedPtrField* dependency, RepeatedField* public_dependency, RepeatedField* weak_dependency, const LocationRecorder& root_location, const FileDescriptorProto* containing_file) { + LocationRecorder location(root_location, + FileDescriptorProto::kDependencyFieldNumber, + dependency->size()); + DO(Consume("import")); + if (LookingAt("public")) { - LocationRecorder location( + LocationRecorder public_location( root_location, FileDescriptorProto::kPublicDependencyFieldNumber, public_dependency->size()); DO(Consume("public")); *public_dependency->Add() = dependency->size(); } else if (LookingAt("weak")) { - LocationRecorder location( + LocationRecorder weak_location( root_location, FileDescriptorProto::kWeakDependencyFieldNumber, weak_dependency->size()); + weak_location.RecordLegacyImportLocation(containing_file, "weak"); DO(Consume("weak")); *weak_dependency->Add() = dependency->size(); } - { - LocationRecorder location(root_location, - FileDescriptorProto::kDependencyFieldNumber, - dependency->size()); - DO(ConsumeString(dependency->Add(), - "Expected a string naming the file to import.")); - location.EndAt(input_->previous()); + string import_file; + DO(ConsumeString(&import_file, + "Expected a string naming the file to import.")); + *dependency->Add() = import_file; + location.RecordLegacyImportLocation(containing_file, import_file); + + DO(ConsumeEndOfDeclaration(";", &location)); - DO(ConsumeEndOfDeclaration(";", &location)); - } return true; } @@ -2248,16 +2327,32 @@ SourceLocationTable::~SourceLocationTable() {} bool SourceLocationTable::Find( const Message* descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - int* line, int* column) const { + DescriptorPool::ErrorCollector::ErrorLocation location, int* line, + int* column) const { const std::pair* result = FindOrNull(location_map_, std::make_pair(descriptor, location)); if (result == NULL) { - *line = -1; + *line = -1; *column = 0; return false; } else { - *line = result->first; + *line = result->first; + *column = result->second; + return true; + } +} + +bool SourceLocationTable::FindImport(const Message* descriptor, + const string& name, int* line, + int* column) const { + const std::pair* result = + FindOrNull(import_location_map_, std::make_pair(descriptor, name)); + if (result == nullptr) { + *line = -1; + *column = 0; + return false; + } else { + *line = result->first; *column = result->second; return true; } @@ -2265,17 +2360,20 @@ bool SourceLocationTable::Find( void SourceLocationTable::Add( const Message* descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - int line, int column) { + DescriptorPool::ErrorCollector::ErrorLocation location, int line, + int column) { location_map_[std::make_pair(descriptor, location)] = std::make_pair(line, column); } -void SourceLocationTable::Clear() { - location_map_.clear(); +void SourceLocationTable::AddImport(const Message* descriptor, + const string& name, int line, int column) { + import_location_map_[std::make_pair(descriptor, name)] = + std::make_pair(line, column); } +void SourceLocationTable::Clear() { location_map_.clear(); } + } // namespace compiler } // namespace protobuf - } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/compiler/parser.h b/third_party/protobuf/src/google/protobuf/compiler/parser.h index 5d98e5e1..9e2dc5f5 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/parser.h +++ b/third_party/protobuf/src/google/protobuf/compiler/parser.h @@ -45,10 +45,13 @@ #include #include -namespace google { -namespace protobuf { class Message; } +#include +namespace google { namespace protobuf { + +class Message; + namespace compiler { // Defined in this file. @@ -62,7 +65,7 @@ class SourceLocationTable; // to a FileDescriptorProto. It does not resolve import directives or perform // many other kinds of validation needed to construct a complete // FileDescriptor. -class LIBPROTOBUF_EXPORT Parser { +class PROTOBUF_EXPORT Parser { public: Parser(); ~Parser(); @@ -92,7 +95,7 @@ class LIBPROTOBUF_EXPORT Parser { // Returns the identifier used in the "syntax = " declaration, if one was // seen during the last call to Parse(), or the empty string otherwise. - const string& GetSyntaxIdentifier() { return syntax_identifier_; } + const std::string& GetSyntaxIdentifier() { return syntax_identifier_; } // If set true, input files will be required to begin with a syntax // identifier. Otherwise, files may omit this. If a syntax identifier @@ -162,7 +165,7 @@ class LIBPROTOBUF_EXPORT Parser { // where "text" is the expected token text. bool Consume(const char* text); // Consume a token of type IDENTIFIER and store its text in "output". - bool ConsumeIdentifier(string* output, const char* error); + bool ConsumeIdentifier(std::string* output, const char* error); // Consume an integer and store its value in "output". bool ConsumeInteger(int* output, const char* error); // Consume a signed integer and store its value in "output". @@ -174,7 +177,7 @@ class LIBPROTOBUF_EXPORT Parser { // tokens of either INTEGER or FLOAT type. bool ConsumeNumber(double* output, const char* error); // Consume a string literal and store its (unescaped) value in "output". - bool ConsumeString(string* output, const char* error); + bool ConsumeString(std::string* output, const char* error); // Consume a token representing the end of the statement. Comments between // this token and the next will be harvested for documentation. The given @@ -185,30 +188,34 @@ class LIBPROTOBUF_EXPORT Parser { // have been passed around by const reference, for no particularly good // reason. We should probably go through and change them all to mutable // pointer to make this more intuitive. - bool TryConsumeEndOfDeclaration( - const char* text, const LocationRecorder* location); - bool TryConsumeEndOfDeclarationFinishScope( - const char* text, const LocationRecorder* location); + bool TryConsumeEndOfDeclaration(const char* text, + const LocationRecorder* location); + bool TryConsumeEndOfDeclarationFinishScope(const char* text, + const LocationRecorder* location); - bool ConsumeEndOfDeclaration( - const char* text, const LocationRecorder* location); + bool ConsumeEndOfDeclaration(const char* text, + const LocationRecorder* location); // ----------------------------------------------------------------- // Error logging helpers // Invokes error_collector_->AddError(), if error_collector_ is not NULL. - void AddError(int line, int column, const string& error); + void AddError(int line, int column, const std::string& error); // Invokes error_collector_->AddError() with the line and column number // of the current token. - void AddError(const string& error); + void AddError(const std::string& error); + + // Invokes error_collector_->AddWarning() with the line and column number + // of the current token. + void AddWarning(const string& warning); // Records a location in the SourceCodeInfo.location table (see // descriptor.proto). We use RAII to ensure that the start and end locations // are recorded -- the constructor records the start location and the // destructor records the end location. Since the parser is // recursive-descent, this works out beautifully. - class LIBPROTOBUF_EXPORT LocationRecorder { + class PROTOBUF_EXPORT LocationRecorder { public: // Construct the file's "root" location. LocationRecorder(Parser* parser); @@ -226,7 +233,7 @@ class LIBPROTOBUF_EXPORT Parser { // Creates a recorder that generates locations into given source code info. LocationRecorder(const LocationRecorder& parent, int path1, - SourceCodeInfo* source_code_info); + SourceCodeInfo* source_code_info); ~LocationRecorder(); @@ -251,8 +258,11 @@ class LIBPROTOBUF_EXPORT Parser { // was passed to RecordSourceLocationsTo(), if any. SourceLocationTable // is an older way of keeping track of source locations which is still // used in some places. - void RecordLegacyLocation(const Message* descriptor, + void RecordLegacyLocation( + const Message* descriptor, DescriptorPool::ErrorCollector::ErrorLocation location); + void RecordLegacyImportLocation(const Message* descriptor, + const string& name); // Returns the number of path components in the recorder's current location. int CurrentPathSize() const; @@ -263,8 +273,8 @@ class LIBPROTOBUF_EXPORT Parser { // // TODO(kenton): See comment on TryConsumeEndOfDeclaration(), above, for // why this is const. - void AttachComments(string* leading, string* trailing, - std::vector* detached_comments) const; + void AttachComments(std::string* leading, std::string* trailing, + std::vector* detached_comments) const; private: // Indexes of parent and current location in the parent @@ -312,7 +322,7 @@ class LIBPROTOBUF_EXPORT Parser { bool ParsePackage(FileDescriptorProto* file, const LocationRecorder& root_location, const FileDescriptorProto* containing_file); - bool ParseImport(RepeatedPtrField* dependency, + bool ParseImport(RepeatedPtrField* dependency, RepeatedField* public_dependency, RepeatedField* weak_dependency, const LocationRecorder& root_location, @@ -399,8 +409,7 @@ class LIBPROTOBUF_EXPORT Parser { // oneof_decl->label() since it will have had to parse the label before it // knew it was parsing a oneof. bool ParseOneof(OneofDescriptorProto* oneof_decl, - DescriptorProto* containing_type, - int oneof_index, + DescriptorProto* containing_type, int oneof_index, const LocationRecorder& oneof_location, const LocationRecorder& containing_type_location, const FileDescriptorProto* containing_file); @@ -435,11 +444,10 @@ class LIBPROTOBUF_EXPORT Parser { // Parse a type name and fill in "type" (if it is a primitive) or // "type_name" (if it is not) with the type parsed. - bool ParseType(FieldDescriptorProto::Type* type, - string* type_name); + bool ParseType(FieldDescriptorProto::Type* type, std::string* type_name); // Parse a user-defined type and fill in "type_name" with the name. // If a primitive type is named, it is treated as an error. - bool ParseUserDefinedType(string* type_name); + bool ParseUserDefinedType(std::string* type_name); // Parses field options, i.e. the stuff in square brackets at the end // of a field definition. Also parses default value. @@ -465,8 +473,7 @@ class LIBPROTOBUF_EXPORT Parser { // Parse a single option name/value pair, e.g. "ctype = CORD". The name // identifies a field of the given Message, and the value of that field // is set to the parsed value. - bool ParseOption(Message* options, - const LocationRecorder& options_location, + bool ParseOption(Message* options, const LocationRecorder& options_location, const FileDescriptorProto* containing_file, OptionStyle style); @@ -488,7 +495,7 @@ class LIBPROTOBUF_EXPORT Parser { // REQUIRES: LookingAt("{") // When finished successfully, we are looking at the first token past // the ending brace. - bool ParseUninterpretedBlock(string* value); + bool ParseUninterpretedBlock(std::string* value); struct MapField { // Whether the field is a map field. @@ -497,8 +504,8 @@ class LIBPROTOBUF_EXPORT Parser { FieldDescriptorProto::Type key_type; FieldDescriptorProto::Type value_type; // Or the type names string if the types are customized types. - string key_type_name; - string value_type_name; + std::string key_type_name; + std::string value_type_name; MapField() : is_map_field(false) {} }; @@ -523,18 +530,18 @@ class LIBPROTOBUF_EXPORT Parser { bool had_errors_; bool require_syntax_identifier_; bool stop_after_syntax_identifier_; - string syntax_identifier_; + std::string syntax_identifier_; // Leading doc comments for the next declaration. These are not complete // yet; use ConsumeEndOfDeclaration() to get the complete comments. - string upcoming_doc_comments_; + std::string upcoming_doc_comments_; // Detached comments are not connected to any syntax entities. Elements in // this vector are paragraphs of comments separated by empty lines. The // detached comments will be put into the leading_detached_comments field for // the next element (See SourceCodeInfo.Location in descriptor.proto), when // ConsumeEndOfDeclaration() is called. - std::vector upcoming_detached_comments_; + std::vector upcoming_detached_comments_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Parser); }; @@ -547,7 +554,7 @@ class LIBPROTOBUF_EXPORT Parser { // far more complete information about source locations. However, as of this // writing you still need to use SourceLocationTable when integrating with // DescriptorPool. -class LIBPROTOBUF_EXPORT SourceLocationTable { +class PROTOBUF_EXPORT SourceLocationTable { public: SourceLocationTable(); ~SourceLocationTable(); @@ -558,26 +565,35 @@ class LIBPROTOBUF_EXPORT SourceLocationTable { // location" in the ErrorCollector interface). Returns true if found, false // otherwise. bool Find(const Message* descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - int* line, int* column) const; + DescriptorPool::ErrorCollector::ErrorLocation location, int* line, + int* column) const; + bool FindImport(const Message* descriptor, const string& name, int* line, + int* column) const; // Adds a location to the table. void Add(const Message* descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - int line, int column); + DescriptorPool::ErrorCollector::ErrorLocation location, int line, + int column); + void AddImport(const Message* descriptor, const string& name, int line, + int column); // Clears the contents of the table. void Clear(); private: typedef std::map< - std::pair, - std::pair > LocationMap; + std::pair, + std::pair > + LocationMap; LocationMap location_map_; + std::map, std::pair > + import_location_map_; }; } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_PARSER_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/parser_unittest.cc b/third_party/protobuf/src/google/protobuf/compiler/parser_unittest.cc index 0725a682..80e01a50 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/parser_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/parser_unittest.cc @@ -32,13 +32,14 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include -#include #include #include +#include +#include #include +#include #include #include #include @@ -61,15 +62,14 @@ namespace { class MockErrorCollector : public io::ErrorCollector { public: - MockErrorCollector() {} - ~MockErrorCollector() {} + MockErrorCollector() = default; + ~MockErrorCollector() override = default; - string text_; + std::string text_; // implements ErrorCollector --------------------------------------- - void AddError(int line, int column, const string& message) { - strings::SubstituteAndAppend(&text_, "$0:$1: $2\n", - line, column, message); + void AddError(int line, int column, const std::string& message) override { + strings::SubstituteAndAppend(&text_, "$0:$1: $2\n", line, column, message); } }; @@ -77,18 +77,20 @@ class MockValidationErrorCollector : public DescriptorPool::ErrorCollector { public: MockValidationErrorCollector(const SourceLocationTable& source_locations, io::ErrorCollector* wrapped_collector) - : source_locations_(source_locations), - wrapped_collector_(wrapped_collector) {} + : source_locations_(source_locations), + wrapped_collector_(wrapped_collector) {} ~MockValidationErrorCollector() {} // implements ErrorCollector --------------------------------------- - void AddError(const string& filename, - const string& element_name, - const Message* descriptor, - ErrorLocation location, - const string& message) { + void AddError(const std::string& filename, const std::string& element_name, + const Message* descriptor, ErrorLocation location, + const std::string& message) { int line, column; - source_locations_.Find(descriptor, location, &line, &column); + if (location == DescriptorPool::ErrorCollector::IMPORT) { + source_locations_.FindImport(descriptor, element_name, &line, &column); + } else { + source_locations_.Find(descriptor, location, &line, &column); + } wrapped_collector_->AddError(line, column, message); } @@ -99,8 +101,7 @@ class MockValidationErrorCollector : public DescriptorPool::ErrorCollector { class ParserTest : public testing::Test { protected: - ParserTest() - : require_syntax_identifier_(false) {} + ParserTest() : require_syntax_identifier_(false) {} // Set up the parser to parse the given text. void SetupParser(const char* text) { @@ -165,10 +166,10 @@ class ParserTest : public testing::Test { EXPECT_EQ(io::Tokenizer::TYPE_END, input_->current().type); ASSERT_EQ("", error_collector_.text_); - MockValidationErrorCollector validation_error_collector( - source_locations, &error_collector_); + MockValidationErrorCollector validation_error_collector(source_locations, + &error_collector_); EXPECT_TRUE(pool_.BuildFileCollectingErrors( - file, &validation_error_collector) == NULL); + file, &validation_error_collector) == NULL); EXPECT_EQ(expected_errors, error_collector_.text_); } @@ -185,9 +186,9 @@ class ParserTest : public testing::Test { TEST_F(ParserTest, StopAfterSyntaxIdentifier) { SetupParser( - "// blah\n" - "syntax = \"foobar\";\n" - "this line will not be parsed\n"); + "// blah\n" + "syntax = \"foobar\";\n" + "this line will not be parsed\n"); parser_->SetStopAfterSyntaxIdentifier(true); EXPECT_TRUE(parser_->Parse(input_.get(), NULL)); EXPECT_EQ("", error_collector_.text_); @@ -196,8 +197,8 @@ TEST_F(ParserTest, StopAfterSyntaxIdentifier) { TEST_F(ParserTest, StopAfterOmittedSyntaxIdentifier) { SetupParser( - "// blah\n" - "this line will not be parsed\n"); + "// blah\n" + "this line will not be parsed\n"); parser_->SetStopAfterSyntaxIdentifier(true); EXPECT_TRUE(parser_->Parse(input_.get(), NULL)); EXPECT_EQ("", error_collector_.text_); @@ -206,8 +207,8 @@ TEST_F(ParserTest, StopAfterOmittedSyntaxIdentifier) { TEST_F(ParserTest, StopAfterSyntaxIdentifierWithErrors) { SetupParser( - "// blah\n" - "syntax = error;\n"); + "// blah\n" + "syntax = error;\n"); parser_->SetStopAfterSyntaxIdentifier(true); EXPECT_FALSE(parser_->Parse(input_.get(), NULL)); EXPECT_EQ("1:9: Expected syntax identifier.\n", error_collector_.text_); @@ -218,8 +219,8 @@ TEST_F(ParserTest, WarnIfSyntaxIdentifierOmmitted) { FileDescriptorProto file; CaptureTestStderr(); EXPECT_TRUE(parser_->Parse(input_.get(), &file)); - EXPECT_TRUE( - GetCapturedTestStderr().find("No syntax specified") != string::npos); + EXPECT_TRUE(GetCapturedTestStderr().find("No syntax specified") != + string::npos); } // =================================================================== @@ -227,22 +228,25 @@ TEST_F(ParserTest, WarnIfSyntaxIdentifierOmmitted) { typedef ParserTest ParseMessageTest; TEST_F(ParseMessageTest, IgnoreBOM) { - char input[] = " message TestMessage {\n" + char input[] = + " message TestMessage {\n" " required int32 foo = 1;\n" "}\n"; // Set UTF-8 BOM. input[0] = (char)0xEF; input[1] = (char)0xBB; input[2] = (char)0xBF; - ExpectParsesTo(input, - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" - "}"); + ExpectParsesTo( + input, + "message_type {" + " name: \"TestMessage\"" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" + "}"); } TEST_F(ParseMessageTest, BOMError) { - char input[] = " message TestMessage {\n" + char input[] = + " message TestMessage {\n" " required int32 foo = 1;\n" "}\n"; input[0] = (char)0xEF; @@ -254,590 +258,634 @@ TEST_F(ParseMessageTest, BOMError) { TEST_F(ParseMessageTest, SimpleMessage) { ExpectParsesTo( - "message TestMessage {\n" - " required int32 foo = 1;\n" - "}\n", + "message TestMessage {\n" + " required int32 foo = 1;\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" + "}"); } TEST_F(ParseMessageTest, ImplicitSyntaxIdentifier) { require_syntax_identifier_ = false; ExpectParsesTo( - "message TestMessage {\n" - " required int32 foo = 1;\n" - "}\n", + "message TestMessage {\n" + " required int32 foo = 1;\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" + "}"); EXPECT_EQ("proto2", parser_->GetSyntaxIdentifier()); } TEST_F(ParseMessageTest, ExplicitSyntaxIdentifier) { ExpectParsesTo( - "syntax = \"proto2\";\n" - "message TestMessage {\n" - " required int32 foo = 1;\n" - "}\n", + "syntax = \"proto2\";\n" + "message TestMessage {\n" + " required int32 foo = 1;\n" + "}\n", - "syntax: 'proto2' " - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" - "}"); + "syntax: 'proto2' " + "message_type {" + " name: \"TestMessage\"" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" + "}"); EXPECT_EQ("proto2", parser_->GetSyntaxIdentifier()); } TEST_F(ParseMessageTest, ExplicitRequiredSyntaxIdentifier) { require_syntax_identifier_ = true; ExpectParsesTo( - "syntax = \"proto2\";\n" - "message TestMessage {\n" - " required int32 foo = 1;\n" - "}\n", + "syntax = \"proto2\";\n" + "message TestMessage {\n" + " required int32 foo = 1;\n" + "}\n", - "syntax: 'proto2' " - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" - "}"); + "syntax: 'proto2' " + "message_type {" + " name: \"TestMessage\"" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" + "}"); EXPECT_EQ("proto2", parser_->GetSyntaxIdentifier()); } TEST_F(ParseMessageTest, SimpleFields) { ExpectParsesTo( - "message TestMessage {\n" - " required int32 foo = 15;\n" - " optional int32 bar = 34;\n" - " repeated int32 baz = 3;\n" - "}\n", + "message TestMessage {\n" + " required int32 foo = 15;\n" + " optional int32 bar = 34;\n" + " repeated int32 baz = 3;\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:15 }" - " field { name:\"bar\" label:LABEL_OPTIONAL type:TYPE_INT32 number:34 }" - " field { name:\"baz\" label:LABEL_REPEATED type:TYPE_INT32 number:3 }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:15 }" + " field { name:\"bar\" label:LABEL_OPTIONAL type:TYPE_INT32 number:34 }" + " field { name:\"baz\" label:LABEL_REPEATED type:TYPE_INT32 number:3 }" + "}"); } TEST_F(ParseMessageTest, PrimitiveFieldTypes) { ExpectParsesTo( - "message TestMessage {\n" - " required int32 foo = 1;\n" - " required int64 foo = 1;\n" - " required uint32 foo = 1;\n" - " required uint64 foo = 1;\n" - " required sint32 foo = 1;\n" - " required sint64 foo = 1;\n" - " required fixed32 foo = 1;\n" - " required fixed64 foo = 1;\n" - " required sfixed32 foo = 1;\n" - " required sfixed64 foo = 1;\n" - " required float foo = 1;\n" - " required double foo = 1;\n" - " required string foo = 1;\n" - " required bytes foo = 1;\n" - " required bool foo = 1;\n" - "}\n", + "message TestMessage {\n" + " required int32 foo = 1;\n" + " required int64 foo = 1;\n" + " required uint32 foo = 1;\n" + " required uint64 foo = 1;\n" + " required sint32 foo = 1;\n" + " required sint64 foo = 1;\n" + " required fixed32 foo = 1;\n" + " required fixed64 foo = 1;\n" + " required sfixed32 foo = 1;\n" + " required sfixed64 foo = 1;\n" + " required float foo = 1;\n" + " required double foo = 1;\n" + " required string foo = 1;\n" + " required bytes foo = 1;\n" + " required bool foo = 1;\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT64 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_UINT32 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_UINT64 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_SINT32 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_SINT64 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_FIXED32 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_FIXED64 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_SFIXED32 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_SFIXED64 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_FLOAT number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_DOUBLE number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_STRING number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_BYTES number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_BOOL number:1 }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 " + "}" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT64 number:1 " + "}" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_UINT32 number:1 " + "}" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_UINT64 number:1 " + "}" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_SINT32 number:1 " + "}" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_SINT64 number:1 " + "}" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_FIXED32 number:1 " + "}" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_FIXED64 number:1 " + "}" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_SFIXED32 number:1 " + "}" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_SFIXED64 number:1 " + "}" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_FLOAT number:1 " + "}" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_DOUBLE number:1 " + "}" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_STRING number:1 " + "}" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_BYTES number:1 " + "}" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_BOOL number:1 " + "}" + "}"); } TEST_F(ParseMessageTest, FieldDefaults) { ExpectParsesTo( - "message TestMessage {\n" - " required int32 foo = 1 [default= 1 ];\n" - " required int32 foo = 1 [default= -2 ];\n" - " required int64 foo = 1 [default= 3 ];\n" - " required int64 foo = 1 [default= -4 ];\n" - " required uint32 foo = 1 [default= 5 ];\n" - " required uint64 foo = 1 [default= 6 ];\n" - " required float foo = 1 [default= 7.5];\n" - " required float foo = 1 [default= -8.5];\n" - " required float foo = 1 [default= 9 ];\n" - " required double foo = 1 [default= 10.5];\n" - " required double foo = 1 [default=-11.5];\n" - " required double foo = 1 [default= 12 ];\n" - " required double foo = 1 [default= inf ];\n" - " required double foo = 1 [default=-inf ];\n" - " required double foo = 1 [default= nan ];\n" - " required string foo = 1 [default='13\\001'];\n" - " required string foo = 1 [default='a' \"b\" \n \"c\"];\n" - " required bytes foo = 1 [default='14\\002'];\n" - " required bytes foo = 1 [default='a' \"b\" \n 'c'];\n" - " required bool foo = 1 [default=true ];\n" - " required Foo foo = 1 [default=FOO ];\n" + "message TestMessage {\n" + " required int32 foo = 1 [default= 1 ];\n" + " required int32 foo = 1 [default= -2 ];\n" + " required int64 foo = 1 [default= 3 ];\n" + " required int64 foo = 1 [default= -4 ];\n" + " required uint32 foo = 1 [default= 5 ];\n" + " required uint64 foo = 1 [default= 6 ];\n" + " required float foo = 1 [default= 7.5];\n" + " required float foo = 1 [default= -8.5];\n" + " required float foo = 1 [default= 9 ];\n" + " required double foo = 1 [default= 10.5];\n" + " required double foo = 1 [default=-11.5];\n" + " required double foo = 1 [default= 12 ];\n" + " required double foo = 1 [default= inf ];\n" + " required double foo = 1 [default=-inf ];\n" + " required double foo = 1 [default= nan ];\n" + " required string foo = 1 [default='13\\001'];\n" + " required string foo = 1 [default='a' \"b\" \n \"c\"];\n" + " required bytes foo = 1 [default='14\\002'];\n" + " required bytes foo = 1 [default='a' \"b\" \n 'c'];\n" + " required bool foo = 1 [default=true ];\n" + " required Foo foo = 1 [default=FOO ];\n" - " required int32 foo = 1 [default= 0x7FFFFFFF];\n" - " required int32 foo = 1 [default=-0x80000000];\n" - " required uint32 foo = 1 [default= 0xFFFFFFFF];\n" - " required int64 foo = 1 [default= 0x7FFFFFFFFFFFFFFF];\n" - " required int64 foo = 1 [default=-0x8000000000000000];\n" - " required uint64 foo = 1 [default= 0xFFFFFFFFFFFFFFFF];\n" - " required double foo = 1 [default= 0xabcd];\n" - "}\n", + " required int32 foo = 1 [default= 0x7FFFFFFF];\n" + " required int32 foo = 1 [default=-0x80000000];\n" + " required uint32 foo = 1 [default= 0xFFFFFFFF];\n" + " required int64 foo = 1 [default= 0x7FFFFFFFFFFFFFFF];\n" + " required int64 foo = 1 [default=-0x8000000000000000];\n" + " required uint64 foo = 1 [default= 0xFFFFFFFFFFFFFFFF];\n" + " required double foo = 1 [default= 0xabcd];\n" + "}\n", #define ETC "name:\"foo\" label:LABEL_REQUIRED number:1" - "message_type {" - " name: \"TestMessage\"" - " field { type:TYPE_INT32 default_value:\"1\" " ETC " }" - " field { type:TYPE_INT32 default_value:\"-2\" " ETC " }" - " field { type:TYPE_INT64 default_value:\"3\" " ETC " }" - " field { type:TYPE_INT64 default_value:\"-4\" " ETC " }" - " field { type:TYPE_UINT32 default_value:\"5\" " ETC " }" - " field { type:TYPE_UINT64 default_value:\"6\" " ETC " }" - " field { type:TYPE_FLOAT default_value:\"7.5\" " ETC " }" - " field { type:TYPE_FLOAT default_value:\"-8.5\" " ETC " }" - " field { type:TYPE_FLOAT default_value:\"9\" " ETC " }" - " field { type:TYPE_DOUBLE default_value:\"10.5\" " ETC " }" - " field { type:TYPE_DOUBLE default_value:\"-11.5\" " ETC " }" - " field { type:TYPE_DOUBLE default_value:\"12\" " ETC " }" - " field { type:TYPE_DOUBLE default_value:\"inf\" " ETC " }" - " field { type:TYPE_DOUBLE default_value:\"-inf\" " ETC " }" - " field { type:TYPE_DOUBLE default_value:\"nan\" " ETC " }" - " field { type:TYPE_STRING default_value:\"13\\001\" " ETC " }" - " field { type:TYPE_STRING default_value:\"abc\" " ETC " }" - " field { type:TYPE_BYTES default_value:\"14\\\\002\" " ETC " }" - " field { type:TYPE_BYTES default_value:\"abc\" " ETC " }" - " field { type:TYPE_BOOL default_value:\"true\" " ETC " }" - " field { type_name:\"Foo\" default_value:\"FOO\" " ETC " }" + "message_type {" + " name: \"TestMessage\"" + " field { type:TYPE_INT32 default_value:\"1\" " ETC + " }" + " field { type:TYPE_INT32 default_value:\"-2\" " ETC + " }" + " field { type:TYPE_INT64 default_value:\"3\" " ETC + " }" + " field { type:TYPE_INT64 default_value:\"-4\" " ETC + " }" + " field { type:TYPE_UINT32 default_value:\"5\" " ETC + " }" + " field { type:TYPE_UINT64 default_value:\"6\" " ETC + " }" + " field { type:TYPE_FLOAT default_value:\"7.5\" " ETC + " }" + " field { type:TYPE_FLOAT default_value:\"-8.5\" " ETC + " }" + " field { type:TYPE_FLOAT default_value:\"9\" " ETC + " }" + " field { type:TYPE_DOUBLE default_value:\"10.5\" " ETC + " }" + " field { type:TYPE_DOUBLE default_value:\"-11.5\" " ETC + " }" + " field { type:TYPE_DOUBLE default_value:\"12\" " ETC + " }" + " field { type:TYPE_DOUBLE default_value:\"inf\" " ETC + " }" + " field { type:TYPE_DOUBLE default_value:\"-inf\" " ETC + " }" + " field { type:TYPE_DOUBLE default_value:\"nan\" " ETC + " }" + " field { type:TYPE_STRING default_value:\"13\\001\" " ETC + " }" + " field { type:TYPE_STRING default_value:\"abc\" " ETC + " }" + " field { type:TYPE_BYTES default_value:\"14\\\\002\" " ETC + " }" + " field { type:TYPE_BYTES default_value:\"abc\" " ETC + " }" + " field { type:TYPE_BOOL default_value:\"true\" " ETC + " }" + " field { type_name:\"Foo\" default_value:\"FOO\" " ETC + " }" - " field {" - " type:TYPE_INT32 default_value:\"2147483647\" " ETC - " }" - " field {" - " type:TYPE_INT32 default_value:\"-2147483648\" " ETC - " }" - " field {" - " type:TYPE_UINT32 default_value:\"4294967295\" " ETC - " }" - " field {" - " type:TYPE_INT64 default_value:\"9223372036854775807\" " ETC - " }" - " field {" - " type:TYPE_INT64 default_value:\"-9223372036854775808\" " ETC - " }" - " field {" - " type:TYPE_UINT64 default_value:\"18446744073709551615\" " ETC - " }" - " field {" - " type:TYPE_DOUBLE default_value:\"43981\" " ETC - " }" - "}"); + " field {" + " type:TYPE_INT32 default_value:\"2147483647\" " ETC + " }" + " field {" + " type:TYPE_INT32 default_value:\"-2147483648\" " ETC + " }" + " field {" + " type:TYPE_UINT32 default_value:\"4294967295\" " ETC + " }" + " field {" + " type:TYPE_INT64 default_value:\"9223372036854775807\" " ETC + " }" + " field {" + " type:TYPE_INT64 default_value:\"-9223372036854775808\" " ETC + " }" + " field {" + " type:TYPE_UINT64 default_value:\"18446744073709551615\" " ETC + " }" + " field {" + " type:TYPE_DOUBLE default_value:\"43981\" " ETC + " }" + "}"); #undef ETC } TEST_F(ParseMessageTest, FieldJsonName) { ExpectParsesTo( - "message TestMessage {\n" - " optional string foo = 1 [json_name = \"@type\"];\n" - "}\n", - "message_type {" - " name: \"TestMessage\"" - " field {\n" - " name: \"foo\" label: LABEL_OPTIONAL type: TYPE_STRING number: 1" - " json_name: \"@type\"\n" - " }\n" - "}\n"); + "message TestMessage {\n" + " optional string foo = 1 [json_name = \"@type\"];\n" + "}\n", + "message_type {" + " name: \"TestMessage\"" + " field {\n" + " name: \"foo\" label: LABEL_OPTIONAL type: TYPE_STRING number: 1" + " json_name: \"@type\"\n" + " }\n" + "}\n"); } TEST_F(ParseMessageTest, FieldOptions) { ExpectParsesTo( - "message TestMessage {\n" - " optional string foo = 1\n" - " [ctype=CORD, (foo)=7, foo.(.bar.baz).qux.quux.(corge)=-33, \n" - " (quux)=\"x\040y\", (baz.qux)=hey];\n" - "}\n", + "message TestMessage {\n" + " optional string foo = 1\n" + " [ctype=CORD, (foo)=7, foo.(.bar.baz).qux.quux.(corge)=-33, \n" + " (quux)=\"x\040y\", (baz.qux)=hey];\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " field { name: \"foo\" label: LABEL_OPTIONAL type: TYPE_STRING number: 1" - " options { uninterpreted_option: { name { name_part: \"ctype\" " - " is_extension: false } " - " identifier_value: \"CORD\" }" - " uninterpreted_option: { name { name_part: \"foo\" " - " is_extension: true } " - " positive_int_value: 7 }" - " uninterpreted_option: { name { name_part: \"foo\" " - " is_extension: false } " - " name { name_part: \".bar.baz\"" - " is_extension: true } " - " name { name_part: \"qux\" " - " is_extension: false } " - " name { name_part: \"quux\" " - " is_extension: false } " - " name { name_part: \"corge\" " - " is_extension: true } " - " negative_int_value: -33 }" - " uninterpreted_option: { name { name_part: \"quux\" " - " is_extension: true } " - " string_value: \"x y\" }" - " uninterpreted_option: { name { name_part: \"baz.qux\" " - " is_extension: true } " - " identifier_value: \"hey\" }" - " }" - " }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " field { name: \"foo\" label: LABEL_OPTIONAL type: TYPE_STRING number: " + "1" + " options { uninterpreted_option: { name { name_part: \"ctype\" " + " is_extension: false " + "} " + " identifier_value: \"CORD\" " + "}" + " uninterpreted_option: { name { name_part: \"foo\" " + " is_extension: true } " + " positive_int_value: 7 }" + " uninterpreted_option: { name { name_part: \"foo\" " + " is_extension: false " + "} " + " name { name_part: " + "\".bar.baz\"" + " is_extension: true } " + " name { name_part: \"qux\" " + " is_extension: false " + "} " + " name { name_part: \"quux\" " + " is_extension: false " + "} " + " name { name_part: \"corge\" " + " is_extension: true } " + " negative_int_value: -33 }" + " uninterpreted_option: { name { name_part: \"quux\" " + " is_extension: true } " + " string_value: \"x y\" }" + " uninterpreted_option: { name { name_part: " + "\"baz.qux\" " + " is_extension: true } " + " identifier_value: \"hey\" }" + " }" + " }" + "}"); } TEST_F(ParseMessageTest, Oneof) { ExpectParsesTo( - "message TestMessage {\n" - " oneof foo {\n" - " int32 a = 1;\n" - " string b = 2;\n" - " TestMessage c = 3;\n" - " group D = 4 { optional int32 i = 5; }\n" - " }\n" - "}\n", + "message TestMessage {\n" + " oneof foo {\n" + " int32 a = 1;\n" + " string b = 2;\n" + " TestMessage c = 3;\n" + " group D = 4 { optional int32 i = 5; }\n" + " }\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " field { name:\"a\" label:LABEL_OPTIONAL type:TYPE_INT32 number:1 " - " oneof_index:0 }" - " field { name:\"b\" label:LABEL_OPTIONAL type:TYPE_STRING number:2 " - " oneof_index:0 }" - " field { name:\"c\" label:LABEL_OPTIONAL type_name:\"TestMessage\" " - " number:3 oneof_index:0 }" - " field { name:\"d\" label:LABEL_OPTIONAL type:TYPE_GROUP " - " type_name:\"D\" number:4 oneof_index:0 }" - " oneof_decl {" - " name: \"foo\"" - " }" - " nested_type {" - " name: \"D\"" - " field { name:\"i\" label:LABEL_OPTIONAL type:TYPE_INT32 number:5 }" - " }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " field { name:\"a\" label:LABEL_OPTIONAL type:TYPE_INT32 number:1 " + " oneof_index:0 }" + " field { name:\"b\" label:LABEL_OPTIONAL type:TYPE_STRING number:2 " + " oneof_index:0 }" + " field { name:\"c\" label:LABEL_OPTIONAL type_name:\"TestMessage\" " + " number:3 oneof_index:0 }" + " field { name:\"d\" label:LABEL_OPTIONAL type:TYPE_GROUP " + " type_name:\"D\" number:4 oneof_index:0 }" + " oneof_decl {" + " name: \"foo\"" + " }" + " nested_type {" + " name: \"D\"" + " field { name:\"i\" label:LABEL_OPTIONAL type:TYPE_INT32 number:5 }" + " }" + "}"); } TEST_F(ParseMessageTest, MultipleOneofs) { ExpectParsesTo( - "message TestMessage {\n" - " oneof foo {\n" - " int32 a = 1;\n" - " string b = 2;\n" - " }\n" - " oneof bar {\n" - " int32 c = 3;\n" - " string d = 4;\n" - " }\n" - "}\n", + "message TestMessage {\n" + " oneof foo {\n" + " int32 a = 1;\n" + " string b = 2;\n" + " }\n" + " oneof bar {\n" + " int32 c = 3;\n" + " string d = 4;\n" + " }\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " field { name:\"a\" label:LABEL_OPTIONAL type:TYPE_INT32 number:1 " - " oneof_index:0 }" - " field { name:\"b\" label:LABEL_OPTIONAL type:TYPE_STRING number:2 " - " oneof_index:0 }" - " field { name:\"c\" label:LABEL_OPTIONAL type:TYPE_INT32 number:3 " - " oneof_index:1 }" - " field { name:\"d\" label:LABEL_OPTIONAL type:TYPE_STRING number:4 " - " oneof_index:1 }" - " oneof_decl {" - " name: \"foo\"" - " }" - " oneof_decl {" - " name: \"bar\"" - " }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " field { name:\"a\" label:LABEL_OPTIONAL type:TYPE_INT32 number:1 " + " oneof_index:0 }" + " field { name:\"b\" label:LABEL_OPTIONAL type:TYPE_STRING number:2 " + " oneof_index:0 }" + " field { name:\"c\" label:LABEL_OPTIONAL type:TYPE_INT32 number:3 " + " oneof_index:1 }" + " field { name:\"d\" label:LABEL_OPTIONAL type:TYPE_STRING number:4 " + " oneof_index:1 }" + " oneof_decl {" + " name: \"foo\"" + " }" + " oneof_decl {" + " name: \"bar\"" + " }" + "}"); } TEST_F(ParseMessageTest, Maps) { ExpectParsesTo( - "message TestMessage {\n" - " map primitive_type_map = 1;\n" - " map composite_type_map = 2;\n" - "}\n", + "message TestMessage {\n" + " map primitive_type_map = 1;\n" + " map composite_type_map = 2;\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " nested_type {" - " name: \"PrimitiveTypeMapEntry\"" - " field { " - " name: \"key\" number: 1 label:LABEL_OPTIONAL" - " type:TYPE_INT32" - " }" - " field { " - " name: \"value\" number: 2 label:LABEL_OPTIONAL" - " type:TYPE_STRING" - " }" - " options { map_entry: true }" - " }" - " nested_type {" - " name: \"CompositeTypeMapEntry\"" - " field { " - " name: \"key\" number: 1 label:LABEL_OPTIONAL" - " type_name: \"KeyType\"" - " }" - " field { " - " name: \"value\" number: 2 label:LABEL_OPTIONAL" - " type_name: \"ValueType\"" - " }" - " options { map_entry: true }" - " }" - " field {" - " name: \"primitive_type_map\"" - " label: LABEL_REPEATED" - " type_name: \"PrimitiveTypeMapEntry\"" - " number: 1" - " }" - " field {" - " name: \"composite_type_map\"" - " label: LABEL_REPEATED" - " type_name: \"CompositeTypeMapEntry\"" - " number: 2" - " }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " nested_type {" + " name: \"PrimitiveTypeMapEntry\"" + " field { " + " name: \"key\" number: 1 label:LABEL_OPTIONAL" + " type:TYPE_INT32" + " }" + " field { " + " name: \"value\" number: 2 label:LABEL_OPTIONAL" + " type:TYPE_STRING" + " }" + " options { map_entry: true }" + " }" + " nested_type {" + " name: \"CompositeTypeMapEntry\"" + " field { " + " name: \"key\" number: 1 label:LABEL_OPTIONAL" + " type_name: \"KeyType\"" + " }" + " field { " + " name: \"value\" number: 2 label:LABEL_OPTIONAL" + " type_name: \"ValueType\"" + " }" + " options { map_entry: true }" + " }" + " field {" + " name: \"primitive_type_map\"" + " label: LABEL_REPEATED" + " type_name: \"PrimitiveTypeMapEntry\"" + " number: 1" + " }" + " field {" + " name: \"composite_type_map\"" + " label: LABEL_REPEATED" + " type_name: \"CompositeTypeMapEntry\"" + " number: 2" + " }" + "}"); } TEST_F(ParseMessageTest, Group) { ExpectParsesTo( - "message TestMessage {\n" - " optional group TestGroup = 1 {};\n" - "}\n", + "message TestMessage {\n" + " optional group TestGroup = 1 {};\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " nested_type { name: \"TestGroup\" }" - " field { name:\"testgroup\" label:LABEL_OPTIONAL number:1" - " type:TYPE_GROUP type_name: \"TestGroup\" }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " nested_type { name: \"TestGroup\" }" + " field { name:\"testgroup\" label:LABEL_OPTIONAL number:1" + " type:TYPE_GROUP type_name: \"TestGroup\" }" + "}"); } TEST_F(ParseMessageTest, NestedMessage) { ExpectParsesTo( - "message TestMessage {\n" - " message Nested {}\n" - " optional Nested test_nested = 1;\n" - "}\n", + "message TestMessage {\n" + " message Nested {}\n" + " optional Nested test_nested = 1;\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " nested_type { name: \"Nested\" }" - " field { name:\"test_nested\" label:LABEL_OPTIONAL number:1" - " type_name: \"Nested\" }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " nested_type { name: \"Nested\" }" + " field { name:\"test_nested\" label:LABEL_OPTIONAL number:1" + " type_name: \"Nested\" }" + "}"); } TEST_F(ParseMessageTest, NestedEnum) { ExpectParsesTo( - "message TestMessage {\n" - " enum NestedEnum {}\n" - " optional NestedEnum test_enum = 1;\n" - "}\n", + "message TestMessage {\n" + " enum NestedEnum {}\n" + " optional NestedEnum test_enum = 1;\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " enum_type { name: \"NestedEnum\" }" - " field { name:\"test_enum\" label:LABEL_OPTIONAL number:1" - " type_name: \"NestedEnum\" }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " enum_type { name: \"NestedEnum\" }" + " field { name:\"test_enum\" label:LABEL_OPTIONAL number:1" + " type_name: \"NestedEnum\" }" + "}"); } TEST_F(ParseMessageTest, ReservedRange) { ExpectParsesTo( - "message TestMessage {\n" - " required int32 foo = 1;\n" - " reserved 2, 15, 9 to 11, 3, 20 to max;\n" - "}\n", + "message TestMessage {\n" + " required int32 foo = 1;\n" + " reserved 2, 15, 9 to 11, 3, 20 to max;\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" - " reserved_range { start:2 end:3 }" - " reserved_range { start:15 end:16 }" - " reserved_range { start:9 end:12 }" - " reserved_range { start:3 end:4 }" - " reserved_range { start:20 end:536870912 }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" + " reserved_range { start:2 end:3 }" + " reserved_range { start:15 end:16 }" + " reserved_range { start:9 end:12 }" + " reserved_range { start:3 end:4 }" + " reserved_range { start:20 end:536870912 }" + "}"); } TEST_F(ParseMessageTest, ReservedRangeOnMessageSet) { ExpectParsesTo( - "message TestMessage {\n" - " option message_set_wire_format = true;\n" - " reserved 20 to max;\n" - "}\n", + "message TestMessage {\n" + " option message_set_wire_format = true;\n" + " reserved 20 to max;\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " options {" - " uninterpreted_option {" - " name {" - " name_part: \"message_set_wire_format\"" - " is_extension: false" - " }" - " identifier_value: \"true\"" - " }" - " }" - " reserved_range { start:20 end:2147483647 }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " options {" + " uninterpreted_option {" + " name {" + " name_part: \"message_set_wire_format\"" + " is_extension: false" + " }" + " identifier_value: \"true\"" + " }" + " }" + " reserved_range { start:20 end:2147483647 }" + "}"); } TEST_F(ParseMessageTest, ReservedNames) { ExpectParsesTo( - "message TestMessage {\n" - " reserved \"foo\", \"bar\";\n" - "}\n", + "message TestMessage {\n" + " reserved \"foo\", \"bar\";\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " reserved_name: \"foo\"" - " reserved_name: \"bar\"" - "}"); + "message_type {" + " name: \"TestMessage\"" + " reserved_name: \"foo\"" + " reserved_name: \"bar\"" + "}"); } TEST_F(ParseMessageTest, ExtensionRange) { ExpectParsesTo( - "message TestMessage {\n" - " extensions 10 to 19;\n" - " extensions 30 to max;\n" - "}\n", + "message TestMessage {\n" + " extensions 10 to 19;\n" + " extensions 30 to max;\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " extension_range { start:10 end:20 }" - " extension_range { start:30 end:536870912 }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " extension_range { start:10 end:20 }" + " extension_range { start:30 end:536870912 }" + "}"); } TEST_F(ParseMessageTest, ExtensionRangeWithOptions) { ExpectParsesTo( - "message TestMessage {\n" - " extensions 10 to 19 [(i) = 5];\n" - "}\n", + "message TestMessage {\n" + " extensions 10 to 19 [(i) = 5];\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " extension_range {" - " start:10" - " end:20" - " options {" - " uninterpreted_option {" - " name {" - " name_part: \"i\"" - " is_extension: true" - " }" - " positive_int_value: 5" - " }" - " }" - " }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " extension_range {" + " start:10" + " end:20" + " options {" + " uninterpreted_option {" + " name {" + " name_part: \"i\"" + " is_extension: true" + " }" + " positive_int_value: 5" + " }" + " }" + " }" + "}"); } TEST_F(ParseMessageTest, CompoundExtensionRange) { ExpectParsesTo( - "message TestMessage {\n" - " extensions 2, 15, 9 to 11, 100 to max, 3;\n" - "}\n", + "message TestMessage {\n" + " extensions 2, 15, 9 to 11, 100 to max, 3;\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " extension_range { start:2 end:3 }" - " extension_range { start:15 end:16 }" - " extension_range { start:9 end:12 }" - " extension_range { start:100 end:536870912 }" - " extension_range { start:3 end:4 }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " extension_range { start:2 end:3 }" + " extension_range { start:15 end:16 }" + " extension_range { start:9 end:12 }" + " extension_range { start:100 end:536870912 }" + " extension_range { start:3 end:4 }" + "}"); } TEST_F(ParseMessageTest, CompoundExtensionRangeWithOptions) { ExpectParsesTo( - "message TestMessage {\n" - " extensions 2, 15, 9 to 11, 100 to max, 3 [(i) = 5];\n" - "}\n", + "message TestMessage {\n" + " extensions 2, 15, 9 to 11, 100 to max, 3 [(i) = 5];\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " extension_range {" - " start:2" - " end:3" - " options {" - " uninterpreted_option {" - " name {" - " name_part: \"i\"" - " is_extension: true" - " }" - " positive_int_value: 5" - " }" - " }" - " }" - " extension_range {" - " start:15" - " end:16" - " options {" - " uninterpreted_option {" - " name {" - " name_part: \"i\"" - " is_extension: true" - " }" - " positive_int_value: 5" - " }" - " }" - " }" - " extension_range {" - " start:9" - " end:12" - " options {" - " uninterpreted_option {" - " name {" - " name_part: \"i\"" - " is_extension: true" - " }" - " positive_int_value: 5" - " }" - " }" - " }" - " extension_range {" - " start:100" - " end:536870912" - " options {" - " uninterpreted_option {" - " name {" - " name_part: \"i\"" - " is_extension: true" - " }" - " positive_int_value: 5" - " }" - " }" - " }" - " extension_range {" - " start:3" - " end:4" - " options {" - " uninterpreted_option {" - " name {" - " name_part: \"i\"" - " is_extension: true" - " }" - " positive_int_value: 5" - " }" - " }" - " }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " extension_range {" + " start:2" + " end:3" + " options {" + " uninterpreted_option {" + " name {" + " name_part: \"i\"" + " is_extension: true" + " }" + " positive_int_value: 5" + " }" + " }" + " }" + " extension_range {" + " start:15" + " end:16" + " options {" + " uninterpreted_option {" + " name {" + " name_part: \"i\"" + " is_extension: true" + " }" + " positive_int_value: 5" + " }" + " }" + " }" + " extension_range {" + " start:9" + " end:12" + " options {" + " uninterpreted_option {" + " name {" + " name_part: \"i\"" + " is_extension: true" + " }" + " positive_int_value: 5" + " }" + " }" + " }" + " extension_range {" + " start:100" + " end:536870912" + " options {" + " uninterpreted_option {" + " name {" + " name_part: \"i\"" + " is_extension: true" + " }" + " positive_int_value: 5" + " }" + " }" + " }" + " extension_range {" + " start:3" + " end:4" + " options {" + " uninterpreted_option {" + " name {" + " name_part: \"i\"" + " is_extension: true" + " }" + " positive_int_value: 5" + " }" + " }" + " }" + "}"); } TEST_F(ParseMessageTest, LargerMaxForMessageSetWireFormatMessages) { @@ -845,77 +893,79 @@ TEST_F(ParseMessageTest, LargerMaxForMessageSetWireFormatMessages) { // extension numbers, as the numbers are not encoded as int32 field values // rather than tags. ExpectParsesTo( - "message TestMessage {\n" - " extensions 4 to max;\n" - " option message_set_wire_format = true;\n" - "}\n", + "message TestMessage {\n" + " extensions 4 to max;\n" + " option message_set_wire_format = true;\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " extension_range { start:4 end: 0x7fffffff }" - " options {\n" - " uninterpreted_option { \n" - " name {\n" - " name_part: \"message_set_wire_format\"\n" - " is_extension: false\n" - " }\n" - " identifier_value: \"true\"\n" - " }\n" - " }\n" - "}"); + "message_type {" + " name: \"TestMessage\"" + " extension_range { start:4 end: 0x7fffffff }" + " options {\n" + " uninterpreted_option { \n" + " name {\n" + " name_part: \"message_set_wire_format\"\n" + " is_extension: false\n" + " }\n" + " identifier_value: \"true\"\n" + " }\n" + " }\n" + "}"); } TEST_F(ParseMessageTest, Extensions) { ExpectParsesTo( - "extend Extendee1 { optional int32 foo = 12; }\n" - "extend Extendee2 { repeated TestMessage bar = 22; }\n", + "extend Extendee1 { optional int32 foo = 12; }\n" + "extend Extendee2 { repeated TestMessage bar = 22; }\n", - "extension { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:12" - " extendee: \"Extendee1\" } " - "extension { name:\"bar\" label:LABEL_REPEATED number:22" - " type_name:\"TestMessage\" extendee: \"Extendee2\" }"); + "extension { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:12" + " extendee: \"Extendee1\" } " + "extension { name:\"bar\" label:LABEL_REPEATED number:22" + " type_name:\"TestMessage\" extendee: \"Extendee2\" }"); } TEST_F(ParseMessageTest, ExtensionsInMessageScope) { ExpectParsesTo( - "message TestMessage {\n" - " extend Extendee1 { optional int32 foo = 12; }\n" - " extend Extendee2 { repeated TestMessage bar = 22; }\n" - "}\n", + "message TestMessage {\n" + " extend Extendee1 { optional int32 foo = 12; }\n" + " extend Extendee2 { repeated TestMessage bar = 22; }\n" + "}\n", - "message_type {" - " name: \"TestMessage\"" - " extension { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:12" - " extendee: \"Extendee1\" }" - " extension { name:\"bar\" label:LABEL_REPEATED number:22" - " type_name:\"TestMessage\" extendee: \"Extendee2\" }" - "}"); + "message_type {" + " name: \"TestMessage\"" + " extension { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 " + "number:12" + " extendee: \"Extendee1\" }" + " extension { name:\"bar\" label:LABEL_REPEATED number:22" + " type_name:\"TestMessage\" extendee: \"Extendee2\" }" + "}"); } TEST_F(ParseMessageTest, MultipleExtensionsOneExtendee) { ExpectParsesTo( - "extend Extendee1 {\n" - " optional int32 foo = 12;\n" - " repeated TestMessage bar = 22;\n" - "}\n", + "extend Extendee1 {\n" + " optional int32 foo = 12;\n" + " repeated TestMessage bar = 22;\n" + "}\n", - "extension { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:12" - " extendee: \"Extendee1\" } " - "extension { name:\"bar\" label:LABEL_REPEATED number:22" - " type_name:\"TestMessage\" extendee: \"Extendee1\" }"); + "extension { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:12" + " extendee: \"Extendee1\" } " + "extension { name:\"bar\" label:LABEL_REPEATED number:22" + " type_name:\"TestMessage\" extendee: \"Extendee1\" }"); } TEST_F(ParseMessageTest, OptionalLabelProto3) { ExpectParsesTo( - "syntax = \"proto3\";\n" - "message TestMessage {\n" - " int32 foo = 1;\n" - "}\n", + "syntax = \"proto3\";\n" + "message TestMessage {\n" + " int32 foo = 1;\n" + "}\n", - "syntax: \"proto3\" " - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:1 } }"); + "syntax: \"proto3\" " + "message_type {" + " name: \"TestMessage\"" + " field { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:1 } " + "}"); } // =================================================================== @@ -924,108 +974,109 @@ typedef ParserTest ParseEnumTest; TEST_F(ParseEnumTest, SimpleEnum) { ExpectParsesTo( - "enum TestEnum {\n" - " FOO = 0;\n" - "}\n", + "enum TestEnum {\n" + " FOO = 0;\n" + "}\n", - "enum_type {" - " name: \"TestEnum\"" - " value { name:\"FOO\" number:0 }" - "}"); + "enum_type {" + " name: \"TestEnum\"" + " value { name:\"FOO\" number:0 }" + "}"); } TEST_F(ParseEnumTest, Values) { ExpectParsesTo( - "enum TestEnum {\n" - " FOO = 13;\n" - " BAR = -10;\n" - " BAZ = 500;\n" - " HEX_MAX = 0x7FFFFFFF;\n" - " HEX_MIN = -0x80000000;\n" - " INT_MAX = 2147483647;\n" - " INT_MIN = -2147483648;\n" - "}\n", + "enum TestEnum {\n" + " FOO = 13;\n" + " BAR = -10;\n" + " BAZ = 500;\n" + " HEX_MAX = 0x7FFFFFFF;\n" + " HEX_MIN = -0x80000000;\n" + " INT_MAX = 2147483647;\n" + " INT_MIN = -2147483648;\n" + "}\n", - "enum_type {" - " name: \"TestEnum\"" - " value { name:\"FOO\" number:13 }" - " value { name:\"BAR\" number:-10 }" - " value { name:\"BAZ\" number:500 }" - " value { name:\"HEX_MAX\" number:2147483647 }" - " value { name:\"HEX_MIN\" number:-2147483648 }" - " value { name:\"INT_MAX\" number:2147483647 }" - " value { name:\"INT_MIN\" number:-2147483648 }" - "}"); + "enum_type {" + " name: \"TestEnum\"" + " value { name:\"FOO\" number:13 }" + " value { name:\"BAR\" number:-10 }" + " value { name:\"BAZ\" number:500 }" + " value { name:\"HEX_MAX\" number:2147483647 }" + " value { name:\"HEX_MIN\" number:-2147483648 }" + " value { name:\"INT_MAX\" number:2147483647 }" + " value { name:\"INT_MIN\" number:-2147483648 }" + "}"); } TEST_F(ParseEnumTest, ValueOptions) { ExpectParsesTo( - "enum TestEnum {\n" - " FOO = 13;\n" - " BAR = -10 [ (something.text) = 'abc' ];\n" - " BAZ = 500 [ (something.text) = 'def', other = 1 ];\n" - "}\n", + "enum TestEnum {\n" + " FOO = 13;\n" + " BAR = -10 [ (something.text) = 'abc' ];\n" + " BAZ = 500 [ (something.text) = 'def', other = 1 ];\n" + "}\n", - "enum_type {" - " name: \"TestEnum\"" - " value { name: \"FOO\" number: 13 }" - " value { name: \"BAR\" number: -10 " - " options { " - " uninterpreted_option { " - " name { name_part: \"something.text\" is_extension: true } " - " string_value: \"abc\" " - " } " - " } " - " } " - " value { name: \"BAZ\" number: 500 " - " options { " - " uninterpreted_option { " - " name { name_part: \"something.text\" is_extension: true } " - " string_value: \"def\" " - " } " - " uninterpreted_option { " - " name { name_part: \"other\" is_extension: false } " - " positive_int_value: 1 " - " } " - " } " - " } " - "}"); + "enum_type {" + " name: \"TestEnum\"" + " value { name: \"FOO\" number: 13 }" + " value { name: \"BAR\" number: -10 " + " options { " + " uninterpreted_option { " + " name { name_part: \"something.text\" is_extension: true } " + " string_value: \"abc\" " + " } " + " } " + " } " + " value { name: \"BAZ\" number: 500 " + " options { " + " uninterpreted_option { " + " name { name_part: \"something.text\" is_extension: true } " + " string_value: \"def\" " + " } " + " uninterpreted_option { " + " name { name_part: \"other\" is_extension: false } " + " positive_int_value: 1 " + " } " + " } " + " } " + "}"); } TEST_F(ParseEnumTest, ReservedRange) { ExpectParsesTo( - "enum TestEnum {\n" - " FOO = 0;\n" - " reserved -2147483648, -6 to -4, -1 to 1, 2, 15, 9 to 11, 3, 20 to max;\n" - "}\n", + "enum TestEnum {\n" + " FOO = 0;\n" + " reserved -2147483648, -6 to -4, -1 to 1, 2, 15, 9 to 11, 3, 20 to " + "max;\n" + "}\n", - "enum_type {" - " name: \"TestEnum\"" - " value { name:\"FOO\" number:0 }" - " reserved_range { start:-2147483648 end:-2147483648 }" - " reserved_range { start:-6 end:-4 }" - " reserved_range { start:-1 end:1 }" - " reserved_range { start:2 end:2 }" - " reserved_range { start:15 end:15 }" - " reserved_range { start:9 end:11 }" - " reserved_range { start:3 end:3 }" - " reserved_range { start:20 end:2147483647 }" - "}"); + "enum_type {" + " name: \"TestEnum\"" + " value { name:\"FOO\" number:0 }" + " reserved_range { start:-2147483648 end:-2147483648 }" + " reserved_range { start:-6 end:-4 }" + " reserved_range { start:-1 end:1 }" + " reserved_range { start:2 end:2 }" + " reserved_range { start:15 end:15 }" + " reserved_range { start:9 end:11 }" + " reserved_range { start:3 end:3 }" + " reserved_range { start:20 end:2147483647 }" + "}"); } TEST_F(ParseEnumTest, ReservedNames) { ExpectParsesTo( - "enum TestEnum {\n" - " FOO = 0;\n" - " reserved \"foo\", \"bar\";\n" - "}\n", + "enum TestEnum {\n" + " FOO = 0;\n" + " reserved \"foo\", \"bar\";\n" + "}\n", - "enum_type {" - " name: \"TestEnum\"" - " value { name:\"FOO\" number:0 }" - " reserved_name: \"foo\"" - " reserved_name: \"bar\"" - "}"); + "enum_type {" + " name: \"TestEnum\"" + " value { name:\"FOO\" number:0 }" + " reserved_name: \"foo\"" + " reserved_name: \"bar\"" + "}"); } // =================================================================== @@ -1034,80 +1085,76 @@ typedef ParserTest ParseServiceTest; TEST_F(ParseServiceTest, SimpleService) { ExpectParsesTo( - "service TestService {\n" - " rpc Foo(In) returns (Out);\n" - "}\n", + "service TestService {\n" + " rpc Foo(In) returns (Out);\n" + "}\n", - "service {" - " name: \"TestService\"" - " method { name:\"Foo\" input_type:\"In\" output_type:\"Out\" }" - "}"); + "service {" + " name: \"TestService\"" + " method { name:\"Foo\" input_type:\"In\" output_type:\"Out\" }" + "}"); } TEST_F(ParseServiceTest, MethodsAndStreams) { ExpectParsesTo( - "service TestService {\n" - " rpc Foo(In1) returns (Out1);\n" - " rpc Bar(In2) returns (Out2);\n" - " rpc Baz(In3) returns (Out3);\n" - "}\n", + "service TestService {\n" + " rpc Foo(In1) returns (Out1);\n" + " rpc Bar(In2) returns (Out2);\n" + " rpc Baz(In3) returns (Out3);\n" + "}\n", - "service {" - " name: \"TestService\"" - " method { name:\"Foo\" input_type:\"In1\" output_type:\"Out1\" }" - " method { name:\"Bar\" input_type:\"In2\" output_type:\"Out2\" }" - " method { name:\"Baz\" input_type:\"In3\" output_type:\"Out3\" }" - "}"); + "service {" + " name: \"TestService\"" + " method { name:\"Foo\" input_type:\"In1\" output_type:\"Out1\" }" + " method { name:\"Bar\" input_type:\"In2\" output_type:\"Out2\" }" + " method { name:\"Baz\" input_type:\"In3\" output_type:\"Out3\" }" + "}"); } - // =================================================================== // imports and packages typedef ParserTest ParseMiscTest; TEST_F(ParseMiscTest, ParseImport) { - ExpectParsesTo( - "import \"foo/bar/baz.proto\";\n", - "dependency: \"foo/bar/baz.proto\""); + ExpectParsesTo("import \"foo/bar/baz.proto\";\n", + "dependency: \"foo/bar/baz.proto\""); } TEST_F(ParseMiscTest, ParseMultipleImports) { ExpectParsesTo( - "import \"foo.proto\";\n" - "import \"bar.proto\";\n" - "import \"baz.proto\";\n", - "dependency: \"foo.proto\"" - "dependency: \"bar.proto\"" - "dependency: \"baz.proto\""); + "import \"foo.proto\";\n" + "import \"bar.proto\";\n" + "import \"baz.proto\";\n", + "dependency: \"foo.proto\"" + "dependency: \"bar.proto\"" + "dependency: \"baz.proto\""); } TEST_F(ParseMiscTest, ParsePublicImports) { ExpectParsesTo( - "import \"foo.proto\";\n" - "import public \"bar.proto\";\n" - "import \"baz.proto\";\n" - "import public \"qux.proto\";\n", - "dependency: \"foo.proto\"" - "dependency: \"bar.proto\"" - "dependency: \"baz.proto\"" - "dependency: \"qux.proto\"" - "public_dependency: 1 " - "public_dependency: 3 "); + "import \"foo.proto\";\n" + "import public \"bar.proto\";\n" + "import \"baz.proto\";\n" + "import public \"qux.proto\";\n", + "dependency: \"foo.proto\"" + "dependency: \"bar.proto\"" + "dependency: \"baz.proto\"" + "dependency: \"qux.proto\"" + "public_dependency: 1 " + "public_dependency: 3 "); } TEST_F(ParseMiscTest, ParsePackage) { - ExpectParsesTo( - "package foo.bar.baz;\n", - "package: \"foo.bar.baz\""); + ExpectParsesTo("package foo.bar.baz;\n", "package: \"foo.bar.baz\""); } TEST_F(ParseMiscTest, ParsePackageWithSpaces) { ExpectParsesTo( - "package foo . bar. \n" - " baz;\n", - "package: \"foo.bar.baz\""); + "package foo . bar. \n" + " baz;\n", + "package: \"foo.bar.baz\""); } // =================================================================== @@ -1115,17 +1162,17 @@ TEST_F(ParseMiscTest, ParsePackageWithSpaces) { TEST_F(ParseMiscTest, ParseFileOptions) { ExpectParsesTo( - "option java_package = \"com.google.foo\";\n" - "option optimize_for = CODE_SIZE;", + "option java_package = \"com.google.foo\";\n" + "option optimize_for = CODE_SIZE;", - "options {" - "uninterpreted_option { name { name_part: \"java_package\" " - " is_extension: false }" - " string_value: \"com.google.foo\"} " - "uninterpreted_option { name { name_part: \"optimize_for\" " - " is_extension: false }" - " identifier_value: \"CODE_SIZE\" } " - "}"); + "options {" + "uninterpreted_option { name { name_part: \"java_package\" " + " is_extension: false }" + " string_value: \"com.google.foo\"} " + "uninterpreted_option { name { name_part: \"optimize_for\" " + " is_extension: false }" + " identifier_value: \"CODE_SIZE\" } " + "}"); } // =================================================================== @@ -1150,341 +1197,335 @@ TEST_F(ParseErrorTest, MissingSyntaxIdentifier) { TEST_F(ParseErrorTest, UnknownSyntaxIdentifier) { ExpectHasEarlyExitErrors( - "syntax = \"no_such_syntax\";", - "0:9: Unrecognized syntax identifier \"no_such_syntax\". This parser " + "syntax = \"no_such_syntax\";", + "0:9: Unrecognized syntax identifier \"no_such_syntax\". This parser " "only recognizes \"proto2\" and \"proto3\".\n"); EXPECT_EQ("no_such_syntax", parser_->GetSyntaxIdentifier()); } TEST_F(ParseErrorTest, SimpleSyntaxError) { - ExpectHasErrors( - "message TestMessage @#$ { blah }", - "0:20: Expected \"{\".\n"); + ExpectHasErrors("message TestMessage @#$ { blah }", + "0:20: Expected \"{\".\n"); EXPECT_EQ("proto2", parser_->GetSyntaxIdentifier()); } TEST_F(ParseErrorTest, ExpectedTopLevel) { - ExpectHasErrors( - "blah;", - "0:0: Expected top-level statement (e.g. \"message\").\n"); + ExpectHasErrors("blah;", + "0:0: Expected top-level statement (e.g. \"message\").\n"); } TEST_F(ParseErrorTest, UnmatchedCloseBrace) { // This used to cause an infinite loop. Doh. - ExpectHasErrors( - "}", - "0:0: Expected top-level statement (e.g. \"message\").\n" - "0:0: Unmatched \"}\".\n"); + ExpectHasErrors("}", + "0:0: Expected top-level statement (e.g. \"message\").\n" + "0:0: Unmatched \"}\".\n"); } // ------------------------------------------------------------------- // Message errors TEST_F(ParseErrorTest, MessageMissingName) { - ExpectHasErrors( - "message {}", - "0:8: Expected message name.\n"); + ExpectHasErrors("message {}", "0:8: Expected message name.\n"); } TEST_F(ParseErrorTest, MessageMissingBody) { - ExpectHasErrors( - "message TestMessage;", - "0:19: Expected \"{\".\n"); + ExpectHasErrors("message TestMessage;", "0:19: Expected \"{\".\n"); } TEST_F(ParseErrorTest, EofInMessage) { ExpectHasErrors( - "message TestMessage {", - "0:21: Reached end of input in message definition (missing '}').\n"); + "message TestMessage {", + "0:21: Reached end of input in message definition (missing '}').\n"); } TEST_F(ParseErrorTest, MissingFieldNumber) { ExpectHasErrors( - "message TestMessage {\n" - " optional int32 foo;\n" - "}\n", - "1:20: Missing field number.\n"); + "message TestMessage {\n" + " optional int32 foo;\n" + "}\n", + "1:20: Missing field number.\n"); } TEST_F(ParseErrorTest, ExpectedFieldNumber) { ExpectHasErrors( - "message TestMessage {\n" - " optional int32 foo = ;\n" - "}\n", - "1:23: Expected field number.\n"); + "message TestMessage {\n" + " optional int32 foo = ;\n" + "}\n", + "1:23: Expected field number.\n"); } TEST_F(ParseErrorTest, FieldNumberOutOfRange) { ExpectHasErrors( - "message TestMessage {\n" - " optional int32 foo = 0x100000000;\n" - "}\n", - "1:23: Integer out of range.\n"); + "message TestMessage {\n" + " optional int32 foo = 0x100000000;\n" + "}\n", + "1:23: Integer out of range.\n"); } TEST_F(ParseErrorTest, MissingLabel) { ExpectHasErrors( - "message TestMessage {\n" - " int32 foo = 1;\n" - "}\n", - "1:2: Expected \"required\", \"optional\", or \"repeated\".\n"); + "message TestMessage {\n" + " int32 foo = 1;\n" + "}\n", + "1:2: Expected \"required\", \"optional\", or \"repeated\".\n"); } TEST_F(ParseErrorTest, ExpectedOptionName) { ExpectHasErrors( - "message TestMessage {\n" - " optional uint32 foo = 1 [];\n" - "}\n", - "1:27: Expected identifier.\n"); + "message TestMessage {\n" + " optional uint32 foo = 1 [];\n" + "}\n", + "1:27: Expected identifier.\n"); } TEST_F(ParseErrorTest, NonExtensionOptionNameBeginningWithDot) { ExpectHasErrors( - "message TestMessage {\n" - " optional uint32 foo = 1 [.foo=1];\n" - "}\n", - "1:27: Expected identifier.\n"); + "message TestMessage {\n" + " optional uint32 foo = 1 [.foo=1];\n" + "}\n", + "1:27: Expected identifier.\n"); } TEST_F(ParseErrorTest, DefaultValueTypeMismatch) { ExpectHasErrors( - "message TestMessage {\n" - " optional uint32 foo = 1 [default=true];\n" - "}\n", - "1:35: Expected integer for field default value.\n"); + "message TestMessage {\n" + " optional uint32 foo = 1 [default=true];\n" + "}\n", + "1:35: Expected integer for field default value.\n"); } TEST_F(ParseErrorTest, DefaultValueNotBoolean) { ExpectHasErrors( - "message TestMessage {\n" - " optional bool foo = 1 [default=blah];\n" - "}\n", - "1:33: Expected \"true\" or \"false\".\n"); + "message TestMessage {\n" + " optional bool foo = 1 [default=blah];\n" + "}\n", + "1:33: Expected \"true\" or \"false\".\n"); } TEST_F(ParseErrorTest, DefaultValueNotString) { ExpectHasErrors( - "message TestMessage {\n" - " optional string foo = 1 [default=1];\n" - "}\n", - "1:35: Expected string for field default value.\n"); + "message TestMessage {\n" + " optional string foo = 1 [default=1];\n" + "}\n", + "1:35: Expected string for field default value.\n"); } TEST_F(ParseErrorTest, DefaultValueUnsignedNegative) { ExpectHasErrors( - "message TestMessage {\n" - " optional uint32 foo = 1 [default=-1];\n" - "}\n", - "1:36: Unsigned field can't have negative default value.\n"); + "message TestMessage {\n" + " optional uint32 foo = 1 [default=-1];\n" + "}\n", + "1:36: Unsigned field can't have negative default value.\n"); } TEST_F(ParseErrorTest, DefaultValueTooLarge) { ExpectHasErrors( - "message TestMessage {\n" - " optional int32 foo = 1 [default= 0x80000000];\n" - " optional int32 foo = 1 [default=-0x80000001];\n" - " optional uint32 foo = 1 [default= 0x100000000];\n" - " optional int64 foo = 1 [default= 0x80000000000000000];\n" - " optional int64 foo = 1 [default=-0x80000000000000001];\n" - " optional uint64 foo = 1 [default= 0x100000000000000000];\n" - "}\n", - "1:36: Integer out of range.\n" - "2:36: Integer out of range.\n" - "3:36: Integer out of range.\n" - "4:36: Integer out of range.\n" - "5:36: Integer out of range.\n" - "6:36: Integer out of range.\n"); + "message TestMessage {\n" + " optional int32 foo = 1 [default= 0x80000000];\n" + " optional int32 foo = 1 [default=-0x80000001];\n" + " optional uint32 foo = 1 [default= 0x100000000];\n" + " optional int64 foo = 1 [default= 0x80000000000000000];\n" + " optional int64 foo = 1 [default=-0x80000000000000001];\n" + " optional uint64 foo = 1 [default= 0x100000000000000000];\n" + "}\n", + "1:36: Integer out of range.\n" + "2:36: Integer out of range.\n" + "3:36: Integer out of range.\n" + "4:36: Integer out of range.\n" + "5:36: Integer out of range.\n" + "6:36: Integer out of range.\n"); } TEST_F(ParseErrorTest, JsonNameNotString) { ExpectHasErrors( - "message TestMessage {\n" - " optional string foo = 1 [json_name=1];\n" - "}\n", - "1:37: Expected string for JSON name.\n"); + "message TestMessage {\n" + " optional string foo = 1 [json_name=1];\n" + "}\n", + "1:37: Expected string for JSON name.\n"); } TEST_F(ParseErrorTest, DuplicateJsonName) { ExpectHasErrors( - "message TestMessage {\n" - " optional uint32 foo = 1 [json_name=\"a\",json_name=\"b\"];\n" - "}\n", - "1:41: Already set option \"json_name\".\n"); + "message TestMessage {\n" + " optional uint32 foo = 1 [json_name=\"a\",json_name=\"b\"];\n" + "}\n", + "1:41: Already set option \"json_name\".\n"); } TEST_F(ParseErrorTest, EnumValueOutOfRange) { ExpectHasErrors( - "enum TestEnum {\n" - " HEX_TOO_BIG = 0x80000000;\n" - " HEX_TOO_SMALL = -0x80000001;\n" - " INT_TOO_BIG = 2147483648;\n" - " INT_TOO_SMALL = -2147483649;\n" - "}\n", - "1:19: Integer out of range.\n" - "2:19: Integer out of range.\n" - "3:19: Integer out of range.\n" - "4:19: Integer out of range.\n"); + "enum TestEnum {\n" + " HEX_TOO_BIG = 0x80000000;\n" + " HEX_TOO_SMALL = -0x80000001;\n" + " INT_TOO_BIG = 2147483648;\n" + " INT_TOO_SMALL = -2147483649;\n" + "}\n", + "1:19: Integer out of range.\n" + "2:19: Integer out of range.\n" + "3:19: Integer out of range.\n" + "4:19: Integer out of range.\n"); } TEST_F(ParseErrorTest, EnumAllowAliasFalse) { ExpectHasErrors( - "enum Foo {\n" - " option allow_alias = false;\n" - " BAR = 1;\n" - " BAZ = 2;\n" - "}\n", - "5:0: \"Foo\" declares 'option allow_alias = false;' which has no effect. " - "Please remove the declaration.\n"); + "enum Foo {\n" + " option allow_alias = false;\n" + " BAR = 1;\n" + " BAZ = 2;\n" + "}\n", + "5:0: \"Foo\" declares 'option allow_alias = false;' which has no " + "effect. " + "Please remove the declaration.\n"); } TEST_F(ParseErrorTest, UnnecessaryEnumAllowAlias) { ExpectHasErrors( - "enum Foo {\n" - " option allow_alias = true;\n" - " BAR = 1;\n" - " BAZ = 2;\n" - "}\n", - "5:0: \"Foo\" declares support for enum aliases but no enum values share " - "field numbers. Please remove the unnecessary 'option allow_alias = true;' " - "declaration.\n"); + "enum Foo {\n" + " option allow_alias = true;\n" + " BAR = 1;\n" + " BAZ = 2;\n" + "}\n", + "5:0: \"Foo\" declares support for enum aliases but no enum values share " + "field numbers. Please remove the unnecessary 'option allow_alias = " + "true;' " + "declaration.\n"); } TEST_F(ParseErrorTest, DefaultValueMissing) { ExpectHasErrors( - "message TestMessage {\n" - " optional uint32 foo = 1 [default=];\n" - "}\n", - "1:35: Expected integer for field default value.\n"); + "message TestMessage {\n" + " optional uint32 foo = 1 [default=];\n" + "}\n", + "1:35: Expected integer for field default value.\n"); } TEST_F(ParseErrorTest, DefaultValueForGroup) { ExpectHasErrors( - "message TestMessage {\n" - " optional group Foo = 1 [default=blah] {}\n" - "}\n", - "1:34: Messages can't have default values.\n"); + "message TestMessage {\n" + " optional group Foo = 1 [default=blah] {}\n" + "}\n", + "1:34: Messages can't have default values.\n"); } TEST_F(ParseErrorTest, DuplicateDefaultValue) { ExpectHasErrors( - "message TestMessage {\n" - " optional uint32 foo = 1 [default=1,default=2];\n" - "}\n", - "1:37: Already set option \"default\".\n"); + "message TestMessage {\n" + " optional uint32 foo = 1 [default=1,default=2];\n" + "}\n", + "1:37: Already set option \"default\".\n"); } TEST_F(ParseErrorTest, MissingOneofName) { ExpectHasErrors( - "message TestMessage {\n" - " oneof {\n" - " int32 bar = 1;\n" - " }\n" - "}\n", - "1:8: Expected oneof name.\n"); + "message TestMessage {\n" + " oneof {\n" + " int32 bar = 1;\n" + " }\n" + "}\n", + "1:8: Expected oneof name.\n"); } TEST_F(ParseErrorTest, LabelInOneof) { ExpectHasErrors( - "message TestMessage {\n" - " oneof foo {\n" - " optional int32 bar = 1;\n" - " }\n" - "}\n", - "2:4: Fields in oneofs must not have labels (required / optional " + "message TestMessage {\n" + " oneof foo {\n" + " optional int32 bar = 1;\n" + " }\n" + "}\n", + "2:4: Fields in oneofs must not have labels (required / optional " "/ repeated).\n"); } TEST_F(ParseErrorTest, MapInOneof) { ExpectHasErrors( - "message TestMessage {\n" - " oneof foo {\n" - " map foo_map = 1;\n" - " map message_field = 2;\n" // a normal message field is OK - " }\n" - "}\n", - "2:7: Map fields are not allowed in oneofs.\n"); + "message TestMessage {\n" + " oneof foo {\n" + " map foo_map = 1;\n" + " map message_field = 2;\n" // a normal message field is OK + " }\n" + "}\n", + "2:7: Map fields are not allowed in oneofs.\n"); } TEST_F(ParseErrorTest, LabelForMap) { ExpectHasErrors( - "message TestMessage {\n" - " optional map int_map = 1;\n" - " required map int_map2 = 2;\n" - " repeated map int_map3 = 3;\n" - " optional map map_message = 4;\n" // a normal message field is OK - "}\n", - "1:14: Field labels (required/optional/repeated) are not allowed on map " - "fields.\n" - "2:14: Field labels (required/optional/repeated) are not allowed on map " - "fields.\n" - "3:14: Field labels (required/optional/repeated) are not allowed on map " - "fields.\n"); + "message TestMessage {\n" + " optional map int_map = 1;\n" + " required map int_map2 = 2;\n" + " repeated map int_map3 = 3;\n" + " optional map map_message = 4;\n" // a normal message field is OK + "}\n", + "1:14: Field labels (required/optional/repeated) are not allowed on map " + "fields.\n" + "2:14: Field labels (required/optional/repeated) are not allowed on map " + "fields.\n" + "3:14: Field labels (required/optional/repeated) are not allowed on map " + "fields.\n"); } TEST_F(ParseErrorTest, MalformedMaps) { ExpectHasErrors( - "message TestMessage {\n" - " map map_message = 1;\n" // a normal message field lacking label - " map str_map = 2;\n" - " map str_map2 = 3;\n" - " map<,string> str_map3 = 4;\n" - " map<> empty_map = 5;\n" - " map int_map = 1;\n" - "}", - "1:6: Expected \"required\", \"optional\", or \"repeated\".\n" - "2:12: Expected \",\".\n" - "3:13: Expected type name.\n" - "4:6: Expected type name.\n" - "5:6: Expected type name.\n" - "6:20: Expected \">\".\n" - "8:5: Map fields are not allowed to be extensions.\n"); + "message TestMessage {\n" + " map map_message = 1;\n" // a normal message field lacking label + " map str_map = 2;\n" + " map str_map2 = 3;\n" + " map<,string> str_map3 = 4;\n" + " map<> empty_map = 5;\n" + " map int_map = 1;\n" + "}", + "1:6: Expected \"required\", \"optional\", or \"repeated\".\n" + "2:12: Expected \",\".\n" + "3:13: Expected type name.\n" + "4:6: Expected type name.\n" + "5:6: Expected type name.\n" + "6:20: Expected \">\".\n" + "8:5: Map fields are not allowed to be extensions.\n"); } TEST_F(ParseErrorTest, GroupNotCapitalized) { ExpectHasErrors( - "message TestMessage {\n" - " optional group foo = 1 {}\n" - "}\n", - "1:17: Group names must start with a capital letter.\n"); + "message TestMessage {\n" + " optional group foo = 1 {}\n" + "}\n", + "1:17: Group names must start with a capital letter.\n"); } TEST_F(ParseErrorTest, GroupMissingBody) { ExpectHasErrors( - "message TestMessage {\n" - " optional group Foo = 1;\n" - "}\n", - "1:24: Missing group body.\n"); + "message TestMessage {\n" + " optional group Foo = 1;\n" + "}\n", + "1:24: Missing group body.\n"); } TEST_F(ParseErrorTest, ExtendingPrimitive) { - ExpectHasErrors( - "extend int32 { optional string foo = 4; }\n", - "0:7: Expected message type.\n"); + ExpectHasErrors("extend int32 { optional string foo = 4; }\n", + "0:7: Expected message type.\n"); } TEST_F(ParseErrorTest, ErrorInExtension) { ExpectHasErrors( - "message Foo { extensions 100 to 199; }\n" - "extend Foo { optional string foo; }\n", - "1:32: Missing field number.\n"); + "message Foo { extensions 100 to 199; }\n" + "extend Foo { optional string foo; }\n", + "1:32: Missing field number.\n"); } TEST_F(ParseErrorTest, MultipleParseErrors) { // When a statement has a parse error, the parser should be able to continue // parsing at the next statement. ExpectHasErrors( - "message TestMessage {\n" - " optional int32 foo;\n" - " !invalid statement ending in a block { blah blah { blah } blah }\n" - " optional int32 bar = 3 {}\n" - "}\n", - "1:20: Missing field number.\n" - "2:2: Expected \"required\", \"optional\", or \"repeated\".\n" - "2:2: Expected type name.\n" - "3:25: Expected \";\".\n"); + "message TestMessage {\n" + " optional int32 foo;\n" + " !invalid statement ending in a block { blah blah { blah } blah }\n" + " optional int32 bar = 3 {}\n" + "}\n", + "1:20: Missing field number.\n" + "2:2: Expected \"required\", \"optional\", or \"repeated\".\n" + "2:2: Expected type name.\n" + "3:25: Expected \";\".\n"); } TEST_F(ParseErrorTest, EofInAggregateValue) { @@ -1504,67 +1545,66 @@ TEST_F(ParseErrorTest, ExplicitOptionalLabelProto3) { "label, as fields are 'optional' by default.\n"); } - // ------------------------------------------------------------------- // Enum errors TEST_F(ParseErrorTest, EofInEnum) { ExpectHasErrors( - "enum TestEnum {", - "0:15: Reached end of input in enum definition (missing '}').\n"); + "enum TestEnum {", + "0:15: Reached end of input in enum definition (missing '}').\n"); } TEST_F(ParseErrorTest, EnumValueMissingNumber) { ExpectHasErrors( - "enum TestEnum {\n" - " FOO;\n" - "}\n", - "1:5: Missing numeric value for enum constant.\n"); + "enum TestEnum {\n" + " FOO;\n" + "}\n", + "1:5: Missing numeric value for enum constant.\n"); } TEST_F(ParseErrorTest, EnumReservedStandaloneMaxNotAllowed) { ExpectHasErrors( - "enum TestEnum {\n" - " FOO = 1;\n" - " reserved max;\n" - "}\n", - "2:11: Expected enum value or number range.\n"); + "enum TestEnum {\n" + " FOO = 1;\n" + " reserved max;\n" + "}\n", + "2:11: Expected enum value or number range.\n"); } TEST_F(ParseErrorTest, EnumReservedMixNameAndNumber) { ExpectHasErrors( - "enum TestEnum {\n" - " FOO = 1;\n" - " reserved 10, \"foo\";\n" - "}\n", - "2:15: Expected enum number range.\n"); + "enum TestEnum {\n" + " FOO = 1;\n" + " reserved 10, \"foo\";\n" + "}\n", + "2:15: Expected enum number range.\n"); } TEST_F(ParseErrorTest, EnumReservedPositiveNumberOutOfRange) { ExpectHasErrors( - "enum TestEnum {\n" - "FOO = 1;\n" - " reserved 2147483648;\n" - "}\n", - "2:11: Integer out of range.\n"); + "enum TestEnum {\n" + "FOO = 1;\n" + " reserved 2147483648;\n" + "}\n", + "2:11: Integer out of range.\n"); } TEST_F(ParseErrorTest, EnumReservedNegativeNumberOutOfRange) { ExpectHasErrors( - "enum TestEnum {\n" - "FOO = 1;\n" - " reserved -2147483649;\n" - "}\n", - "2:12: Integer out of range.\n"); + "enum TestEnum {\n" + "FOO = 1;\n" + " reserved -2147483649;\n" + "}\n", + "2:12: Integer out of range.\n"); } TEST_F(ParseErrorTest, EnumReservedMissingQuotes) { ExpectHasErrors( - "enum TestEnum {\n" - " FOO = 1;\n" - " reserved foo;\n" - "}\n", - "2:11: Expected enum value or number range.\n"); + "enum TestEnum {\n" + " FOO = 1;\n" + " reserved foo;\n" + "}\n", + "2:11: Expected enum value or number range.\n"); } // ------------------------------------------------------------------- @@ -1572,90 +1612,89 @@ TEST_F(ParseErrorTest, EnumReservedMissingQuotes) { TEST_F(ParseErrorTest, ReservedStandaloneMaxNotAllowed) { ExpectHasErrors( - "message Foo {\n" - " reserved max;\n" - "}\n", - "1:11: Expected field name or number range.\n"); + "message Foo {\n" + " reserved max;\n" + "}\n", + "1:11: Expected field name or number range.\n"); } TEST_F(ParseErrorTest, ReservedMixNameAndNumber) { ExpectHasErrors( - "message Foo {\n" - " reserved 10, \"foo\";\n" - "}\n", - "1:15: Expected field number range.\n"); + "message Foo {\n" + " reserved 10, \"foo\";\n" + "}\n", + "1:15: Expected field number range.\n"); } TEST_F(ParseErrorTest, ReservedMissingQuotes) { ExpectHasErrors( - "message Foo {\n" - " reserved foo;\n" - "}\n", - "1:11: Expected field name or number range.\n"); + "message Foo {\n" + " reserved foo;\n" + "}\n", + "1:11: Expected field name or number range.\n"); } TEST_F(ParseErrorTest, ReservedNegativeNumber) { ExpectHasErrors( - "message Foo {\n" - " reserved -10;\n" - "}\n", - "1:11: Expected field name or number range.\n"); + "message Foo {\n" + " reserved -10;\n" + "}\n", + "1:11: Expected field name or number range.\n"); } TEST_F(ParseErrorTest, ReservedNumberOutOfRange) { ExpectHasErrors( - "message Foo {\n" - " reserved 2147483648;\n" - "}\n", - "1:11: Integer out of range.\n"); + "message Foo {\n" + " reserved 2147483648;\n" + "}\n", + "1:11: Integer out of range.\n"); } - // ------------------------------------------------------------------- // Service errors TEST_F(ParseErrorTest, EofInService) { ExpectHasErrors( - "service TestService {", - "0:21: Reached end of input in service definition (missing '}').\n"); + "service TestService {", + "0:21: Reached end of input in service definition (missing '}').\n"); } TEST_F(ParseErrorTest, ServiceMethodPrimitiveParams) { ExpectHasErrors( - "service TestService {\n" - " rpc Foo(int32) returns (string);\n" - "}\n", - "1:10: Expected message type.\n" - "1:26: Expected message type.\n"); + "service TestService {\n" + " rpc Foo(int32) returns (string);\n" + "}\n", + "1:10: Expected message type.\n" + "1:26: Expected message type.\n"); } TEST_F(ParseErrorTest, EofInMethodOptions) { ExpectHasErrors( - "service TestService {\n" - " rpc Foo(Bar) returns(Bar) {", - "1:29: Reached end of input in method options (missing '}').\n" - "1:29: Reached end of input in service definition (missing '}').\n"); + "service TestService {\n" + " rpc Foo(Bar) returns(Bar) {", + "1:29: Reached end of input in method options (missing '}').\n" + "1:29: Reached end of input in service definition (missing '}').\n"); } TEST_F(ParseErrorTest, PrimitiveMethodInput) { ExpectHasErrors( - "service TestService {\n" - " rpc Foo(int32) returns(Bar);\n" - "}\n", - "1:10: Expected message type.\n"); + "service TestService {\n" + " rpc Foo(int32) returns(Bar);\n" + "}\n", + "1:10: Expected message type.\n"); } TEST_F(ParseErrorTest, MethodOptionTypeError) { // This used to cause an infinite loop. ExpectHasErrors( - "message Baz {}\n" - "service Foo {\n" - " rpc Bar(Baz) returns(Baz) { option invalid syntax; }\n" - "}\n", - "2:45: Expected \"=\".\n"); + "message Baz {}\n" + "service Foo {\n" + " rpc Bar(Baz) returns(Baz) { option invalid syntax; }\n" + "}\n", + "2:45: Expected \"=\".\n"); } @@ -1663,16 +1702,15 @@ TEST_F(ParseErrorTest, MethodOptionTypeError) { // Import and package errors TEST_F(ParseErrorTest, ImportNotQuoted) { - ExpectHasErrors( - "import foo;\n", - "0:7: Expected a string naming the file to import.\n"); + ExpectHasErrors("import foo;\n", + "0:7: Expected a string naming the file to import.\n"); } TEST_F(ParseErrorTest, MultiplePackagesInFile) { ExpectHasErrors( - "package foo;\n" - "package bar;\n", - "1:0: Multiple package definitions.\n"); + "package foo;\n" + "package bar;\n", + "1:0: Multiple package definitions.\n"); } // =================================================================== @@ -1691,147 +1729,272 @@ TEST_F(ParserValidationErrorTest, PackageNameError) { // Now try to define it as a package. ExpectHasValidationErrors( - "package foo.bar;", - "0:8: \"foo\" is already defined (as something other than a package) " + "package foo.bar;", + "0:0: \"foo\" is already defined (as something other than a package) " "in file \"bar.proto\".\n"); } +TEST_F(ParserValidationErrorTest, ImportUnloadedError) { + ExpectHasValidationErrors( + "package test;\n" + "\n" + "import \"unloaded.proto\";", + "2:0: Import \"unloaded.proto\" has not been loaded.\n"); +} + +TEST_F(ParserValidationErrorTest, ImportTwice) { + FileDescriptorProto other_file; + other_file.set_name("bar.proto"); + other_file.add_message_type()->set_name("foo"); + EXPECT_TRUE(pool_.BuildFile(other_file) != nullptr); + + ExpectHasValidationErrors( + "package test;\n" + "\n" + "import \"bar.proto\";\n" + " import \"bar.proto\";", + "3:2: Import \"bar.proto\" was listed twice.\n"); +} + +TEST_F(ParserValidationErrorTest, DuplicateFileError) { + FileDescriptorProto other_file; + other_file.set_name("foo.proto"); + EXPECT_TRUE(pool_.BuildFile(other_file) != nullptr); + + ExpectHasValidationErrors( + "package test;", "0:0: A file with this name is already in the pool.\n"); +} + TEST_F(ParserValidationErrorTest, MessageNameError) { ExpectHasValidationErrors( - "message Foo {}\n" - "message Foo {}\n", - "1:8: \"Foo\" is already defined.\n"); + "message Foo {}\n" + "message Foo {}\n", + "1:8: \"Foo\" is already defined.\n"); } TEST_F(ParserValidationErrorTest, FieldNameError) { ExpectHasValidationErrors( - "message Foo {\n" - " optional int32 bar = 1;\n" - " optional int32 bar = 2;\n" - "}\n", - "2:17: \"bar\" is already defined in \"Foo\".\n"); + "message Foo {\n" + " optional int32 bar = 1;\n" + " optional int32 bar = 2;\n" + "}\n", + "2:17: \"bar\" is already defined in \"Foo\".\n"); } TEST_F(ParserValidationErrorTest, FieldTypeError) { ExpectHasValidationErrors( - "message Foo {\n" - " optional Baz bar = 1;\n" - "}\n", - "1:11: \"Baz\" is not defined.\n"); + "message Foo {\n" + " optional Baz bar = 1;\n" + "}\n", + "1:11: \"Baz\" is not defined.\n"); } TEST_F(ParserValidationErrorTest, FieldNumberError) { ExpectHasValidationErrors( - "message Foo {\n" - " optional int32 bar = 0;\n" - "}\n", - "1:23: Field numbers must be positive integers.\n"); + "message Foo {\n" + " optional int32 bar = 0;\n" + "}\n", + "1:23: Field numbers must be positive integers.\n"); } TEST_F(ParserValidationErrorTest, FieldExtendeeError) { + ExpectHasValidationErrors("extend Baz { optional int32 bar = 1; }\n", + "0:7: \"Baz\" is not defined.\n"); +} + +TEST_F(ParserValidationErrorTest, ExtensionJsonNameError) { ExpectHasValidationErrors( - "extend Baz { optional int32 bar = 1; }\n", - "0:7: \"Baz\" is not defined.\n"); + "message TestMessage {\n" + " extensions 1 to 100;\n" + "}\n" + "extend TestMessage {\n" + " optional int32 foo = 12 [json_name = \"bar\"];\n" + "}", + "4:27: option json_name is not allowed on extension fields.\n"); } TEST_F(ParserValidationErrorTest, FieldDefaultValueError) { ExpectHasValidationErrors( - "enum Baz { QUX = 1; }\n" - "message Foo {\n" - " optional Baz bar = 1 [default=NO_SUCH_VALUE];\n" - "}\n", - "2:32: Enum type \"Baz\" has no value named \"NO_SUCH_VALUE\".\n"); + "enum Baz { QUX = 1; }\n" + "message Foo {\n" + " optional Baz bar = 1 [default=NO_SUCH_VALUE];\n" + "}\n", + "2:32: Enum type \"Baz\" has no value named \"NO_SUCH_VALUE\".\n"); } TEST_F(ParserValidationErrorTest, FileOptionNameError) { ExpectHasValidationErrors( - "option foo = 5;", - "0:7: Option \"foo\" unknown.\n"); + "option foo = 5;", + "0:7: Option \"foo\" unknown. Ensure that your proto definition file " + "imports the proto which defines the option.\n"); } TEST_F(ParserValidationErrorTest, FileOptionValueError) { ExpectHasValidationErrors( - "option java_outer_classname = 5;", - "0:30: Value must be quoted string for string option " - "\"google.protobuf.FileOptions.java_outer_classname\".\n"); + "option java_outer_classname = 5;", + "0:30: Value must be quoted string for string option " + "\"google.protobuf.FileOptions.java_outer_classname\".\n"); } TEST_F(ParserValidationErrorTest, FieldOptionNameError) { ExpectHasValidationErrors( - "message Foo {\n" - " optional bool bar = 1 [foo=1];\n" - "}\n", - "1:25: Option \"foo\" unknown.\n"); + "message Foo {\n" + " optional bool bar = 1 [foo=1];\n" + "}\n", + "1:25: Option \"foo\" unknown. Ensure that your proto definition file " + "imports the proto which defines the option.\n"); } TEST_F(ParserValidationErrorTest, FieldOptionValueError) { ExpectHasValidationErrors( - "message Foo {\n" - " optional int32 bar = 1 [ctype=1];\n" - "}\n", - "1:32: Value must be identifier for enum-valued option " - "\"google.protobuf.FieldOptions.ctype\".\n"); + "message Foo {\n" + " optional int32 bar = 1 [ctype=1];\n" + "}\n", + "1:32: Value must be identifier for enum-valued option " + "\"google.protobuf.FieldOptions.ctype\".\n"); } TEST_F(ParserValidationErrorTest, ExtensionRangeNumberError) { ExpectHasValidationErrors( - "message Foo {\n" - " extensions 0;\n" - "}\n", - "1:13: Extension numbers must be positive integers.\n"); + "message Foo {\n" + " extensions 0;\n" + "}\n", + "1:13: Extension numbers must be positive integers.\n"); +} + +TEST_F(ParserValidationErrorTest, Proto3ExtensionError) { + ExpectHasValidationErrors( + "syntax = 'proto3';\n" + "message Foo { \n" + " extensions 100 to 199;\n" + "}\n" + "extend Foo { string foo = 101; }\n", + "4:7: Extensions in proto3 are only allowed for defining options.\n" + "2:13: Extension ranges are not allowed in proto3.\n"); +} + +TEST_F(ParserValidationErrorTest, Proto3MessageSet) { + ExpectHasValidationErrors( + "syntax = 'proto3';\n" + "message Foo { \n" + " option message_set_wire_format = true;\n" + "}\n", + "1:8: MessageSet is not supported in proto3.\n"); +} + +TEST_F(ParserValidationErrorTest, Proto3Required) { + ExpectHasValidationErrors( + "syntax = 'proto3';\n" + "message Foo { \n" + " required int32 field = 1;" + "}\n", + "2:11: Required fields are not allowed in proto3.\n"); +} + +TEST_F(ParserValidationErrorTest, Proto3Default) { + ExpectHasValidationErrors( + "syntax = 'proto3';\n" + "message Foo { \n" + " int32 field = 1 [default = 12];" + "}\n", + "2:29: Explicit default values are not allowed in proto3.\n"); +} + +TEST_F(ParserValidationErrorTest, Proto3JsonConflictError) { + ExpectHasValidationErrors( + "syntax = 'proto3';\n" + "message TestMessage {\n" + " uint32 foo = 1;\n" + " uint32 Foo = 2;\n" + "}\n", + "3:9: The JSON camel-case name of field \"Foo\" conflicts with field " + "\"foo\". This is not allowed in proto3.\n"); } TEST_F(ParserValidationErrorTest, EnumNameError) { ExpectHasValidationErrors( - "enum Foo {A = 1;}\n" - "enum Foo {B = 1;}\n", - "1:5: \"Foo\" is already defined.\n"); + "enum Foo {A = 1;}\n" + "enum Foo {B = 1;}\n", + "1:5: \"Foo\" is already defined.\n"); +} + +TEST_F(ParserValidationErrorTest, Proto3EnumError) { + ExpectHasValidationErrors( + "syntax = 'proto3';\n" + "enum Foo {A = 1;}\n", + "1:14: The first enum value must be zero in proto3.\n"); } TEST_F(ParserValidationErrorTest, EnumValueNameError) { ExpectHasValidationErrors( - "enum Foo {\n" - " BAR = 1;\n" - " BAR = 1;\n" - "}\n", - "2:2: \"BAR\" is already defined.\n"); + "enum Foo {\n" + " BAR = 1;\n" + " BAR = 1;\n" + "}\n", + "2:2: \"BAR\" is already defined.\n"); +} + +TEST_F(ParserValidationErrorTest, EnumValueAliasError) { + ExpectHasValidationErrors( + "enum Foo {\n" + " BAR = 1;\n" + " BAZ = 1;\n" + "}\n", + "2:8: \"BAZ\" uses the same enum value as \"BAR\". If this is " + "intended, set 'option allow_alias = true;' to the enum " + "definition.\n"); +} + +TEST_F(ParserValidationErrorTest, ExplicitlyMapEntryError) { + ExpectHasValidationErrors( + "message Foo {\n" + " message ValueEntry {\n" + " option map_entry = true;\n" + " optional int32 key = 1;\n" + " optional int32 value = 2;\n" + " extensions 99 to 999;\n" + " }\n" + " repeated ValueEntry value = 1;\n" + "}", + "7:11: map_entry should not be set explicitly. Use " + "map instead.\n"); } TEST_F(ParserValidationErrorTest, ServiceNameError) { ExpectHasValidationErrors( - "service Foo {}\n" - "service Foo {}\n", - "1:8: \"Foo\" is already defined.\n"); + "service Foo {}\n" + "service Foo {}\n", + "1:8: \"Foo\" is already defined.\n"); } TEST_F(ParserValidationErrorTest, MethodNameError) { ExpectHasValidationErrors( - "message Baz {}\n" - "service Foo {\n" - " rpc Bar(Baz) returns(Baz);\n" - " rpc Bar(Baz) returns(Baz);\n" - "}\n", - "3:6: \"Bar\" is already defined in \"Foo\".\n"); + "message Baz {}\n" + "service Foo {\n" + " rpc Bar(Baz) returns(Baz);\n" + " rpc Bar(Baz) returns(Baz);\n" + "}\n", + "3:6: \"Bar\" is already defined in \"Foo\".\n"); } TEST_F(ParserValidationErrorTest, MethodInputTypeError) { ExpectHasValidationErrors( - "message Baz {}\n" - "service Foo {\n" - " rpc Bar(Qux) returns(Baz);\n" - "}\n", - "2:10: \"Qux\" is not defined.\n"); + "message Baz {}\n" + "service Foo {\n" + " rpc Bar(Qux) returns(Baz);\n" + "}\n", + "2:10: \"Qux\" is not defined.\n"); } TEST_F(ParserValidationErrorTest, MethodOutputTypeError) { ExpectHasValidationErrors( - "message Baz {}\n" - "service Foo {\n" - " rpc Bar(Baz) returns(Qux);\n" - "}\n", - "2:23: \"Qux\" is not defined.\n"); + "message Baz {}\n" + "service Foo {\n" + " rpc Bar(Baz) returns(Qux);\n" + "}\n", + "2:23: \"Qux\" is not defined.\n"); } @@ -1846,16 +2009,16 @@ TEST_F(ParserValidationErrorTest, ResovledUndefinedError) { // Define "foo.base" and try "base.bar". // "base.bar" is resolved to "foo.base.bar" which is not defined. ExpectHasValidationErrors( - "package foo.base;\n" - "import \"base.proto\";\n" - "message qux {\n" - " optional base.bar baz = 1;\n" - " optional .base.bar quz = 2;\n" - "}\n", - "3:11: \"base.bar\" is resolved to \"foo.base.bar\"," - " which is not defined. The innermost scope is searched first " - "in name resolution. Consider using a leading '.'(i.e., \".base.bar\")" - " to start from the outermost scope.\n"); + "package foo.base;\n" + "import \"base.proto\";\n" + "message qux {\n" + " optional base.bar baz = 1;\n" + " optional .base.bar quz = 2;\n" + "}\n", + "3:11: \"base.bar\" is resolved to \"foo.base.bar\"," + " which is not defined. The innermost scope is searched first " + "in name resolution. Consider using a leading '.'(i.e., \".base.bar\")" + " to start from the outermost scope.\n"); } TEST_F(ParserValidationErrorTest, ResovledUndefinedOptionError) { @@ -1866,7 +2029,7 @@ TEST_F(ParserValidationErrorTest, ResovledUndefinedOptionError) { // base2.proto: // package baz - // import google/protobuf/descriptor.proto + // import net/proto2/proto/descriptor.proto // message Bar { optional int32 foo = 1; } // extend FileOptions { optional Bar bar = 7672757; } FileDescriptorProto other_file; @@ -1927,35 +2090,35 @@ class CompareDescriptorNames { }; // Sorts nested DescriptorProtos of a DescriptoProto, by name. -void SortMessages(DescriptorProto *descriptor_proto) { +void SortMessages(DescriptorProto* descriptor_proto) { int size = descriptor_proto->nested_type_size(); // recursively sort; we can't guarantee the order of nested messages either for (int i = 0; i < size; ++i) { SortMessages(descriptor_proto->mutable_nested_type(i)); } - DescriptorProto **data = - descriptor_proto->mutable_nested_type()->mutable_data(); + DescriptorProto** data = + descriptor_proto->mutable_nested_type()->mutable_data(); std::sort(data, data + size, CompareDescriptorNames()); } // Sorts DescriptorProtos belonging to a FileDescriptorProto, by name. -void SortMessages(FileDescriptorProto *file_descriptor_proto) { +void SortMessages(FileDescriptorProto* file_descriptor_proto) { int size = file_descriptor_proto->message_type_size(); // recursively sort; we can't guarantee the order of nested messages either for (int i = 0; i < size; ++i) { SortMessages(file_descriptor_proto->mutable_message_type(i)); } - DescriptorProto **data = - file_descriptor_proto->mutable_message_type()->mutable_data(); + DescriptorProto** data = + file_descriptor_proto->mutable_message_type()->mutable_data(); std::sort(data, data + size, CompareDescriptorNames()); } // Strips the message and enum field type names for comparison purpose only. void StripFieldTypeName(DescriptorProto* proto) { for (int i = 0; i < proto->field_size(); ++i) { - string type_name = proto->field(i).type_name(); - string::size_type pos = type_name.find_last_of("."); - if (pos != string::npos) { + std::string type_name = proto->field(i).type_name(); + std::string::size_type pos = type_name.find_last_of("."); + if (pos != std::string::npos) { proto->mutable_field(i)->mutable_type_name()->assign( type_name.begin() + pos + 1, type_name.end()); } @@ -1973,26 +2136,26 @@ void StripFieldTypeName(FileDescriptorProto* file_proto) { TEST_F(ParseDescriptorDebugTest, TestAllDescriptorTypes) { const FileDescriptor* original_file = - protobuf_unittest::TestAllTypes::descriptor()->file(); + protobuf_unittest::TestAllTypes::descriptor()->file(); FileDescriptorProto expected; original_file->CopyTo(&expected); // Get the DebugString of the unittest.proto FileDecriptor, which includes // all other descriptor types - string debug_string = original_file->DebugString(); + std::string debug_string = original_file->DebugString(); // Parse the debug string SetupParser(debug_string.c_str()); FileDescriptorProto parsed; parser_->Parse(input_.get(), &parsed); EXPECT_EQ(io::Tokenizer::TYPE_END, input_->current().type); - ASSERT_EQ("", error_collector_.text_) - << "Failed to parse:\n" << debug_string; + ASSERT_EQ("", error_collector_.text_) << "Failed to parse:\n" << debug_string; // We now have a FileDescriptorProto, but to compare with the expected we // need to link to a FileDecriptor, then output back to a proto. We'll // also need to give it the same name as the original. - parsed.set_name("google/protobuf/unittest.proto"); + parsed.set_name( + TestUtil::MaybeTranslatePath("net/proto2/internal/unittest.proto")); // We need the imported dependency before we can build our parsed proto const FileDescriptor* public_import = protobuf_unittest_import::PublicImportMessage::descriptor()->file(); @@ -2000,14 +2163,13 @@ TEST_F(ParseDescriptorDebugTest, TestAllDescriptorTypes) { public_import->CopyTo(&public_import_proto); ASSERT_TRUE(pool_.BuildFile(public_import_proto) != NULL); const FileDescriptor* import = - protobuf_unittest_import::ImportMessage::descriptor()->file(); + protobuf_unittest_import::ImportMessage::descriptor()->file(); FileDescriptorProto import_proto; import->CopyTo(&import_proto); ASSERT_TRUE(pool_.BuildFile(import_proto) != NULL); const FileDescriptor* actual = pool_.BuildFile(parsed); parsed.Clear(); - ASSERT_TRUE(actual != NULL) - << "Failed to validate:\n" << debug_string; + ASSERT_TRUE(actual != NULL) << "Failed to validate:\n" << debug_string; actual->CopyTo(&parsed); ASSERT_TRUE(actual != NULL); @@ -2025,11 +2187,11 @@ TEST_F(ParseDescriptorDebugTest, TestAllDescriptorTypes) { TEST_F(ParseDescriptorDebugTest, TestCustomOptions) { const FileDescriptor* original_file = - protobuf_unittest::AggregateMessage::descriptor()->file(); + protobuf_unittest::AggregateMessage::descriptor()->file(); FileDescriptorProto expected; original_file->CopyTo(&expected); - string debug_string = original_file->DebugString(); + std::string debug_string = original_file->DebugString(); // Parse the debug string SetupParser(debug_string.c_str()); @@ -2137,37 +2299,38 @@ TEST_F(ParseDescriptorDebugTest, TestCommentsInDebugString) { // We don't test the exact comment placement or formatting, because we do not // want to be too fragile here. const char* expected_comments[] = { - "Detached comment before syntax.", - "Syntax comment.", - "Detached comment before package.", - "Package comment.", - "Detached comment before TestMessage1.", - "Message comment.", - "More detail in message comment.", - "Detached comment before foo.", - "Field comment", - "Detached comment before NestedMessage.", - "Nested-message comment", - "Detached comment before MyEnumType.", - "Enum comment", - "Detached comment before ASDF.", - "Enum-value comment", - "Detached comment before MyService.", - "Service comment", - "Detached comment before MyRPCCall.", - "RPC comment", + "Detached comment before syntax.", + "Syntax comment.", + "Detached comment before package.", + "Package comment.", + "Detached comment before TestMessage1.", + "Message comment.", + "More detail in message comment.", + "Detached comment before foo.", + "Field comment", + "Detached comment before NestedMessage.", + "Nested-message comment", + "Detached comment before MyEnumType.", + "Enum comment", + "Detached comment before ASDF.", + "Enum-value comment", + "Detached comment before MyService.", + "Service comment", + "Detached comment before MyRPCCall.", + "RPC comment", }; DebugStringOptions debug_string_options; debug_string_options.include_comments = true; { - const string debug_string = + const std::string debug_string = descriptor->DebugStringWithOptions(debug_string_options); for (int i = 0; i < GOOGLE_ARRAYSIZE(expected_comments); ++i) { - string::size_type found_pos = debug_string.find(expected_comments[i]); - EXPECT_TRUE(found_pos != string::npos) + std::string::size_type found_pos = + debug_string.find(expected_comments[i]); + EXPECT_TRUE(found_pos != std::string::npos) << "\"" << expected_comments[i] << "\" not found."; } @@ -2176,8 +2339,8 @@ TEST_F(ParseDescriptorDebugTest, TestCommentsInDebugString) { FileDescriptorProto parsed; parser_->Parse(input_.get(), &parsed); EXPECT_EQ(io::Tokenizer::TYPE_END, input_->current().type); - ASSERT_EQ("", error_collector_.text_) - << "Failed to parse:\n" << debug_string; + ASSERT_EQ("", error_collector_.text_) << "Failed to parse:\n" + << debug_string; } } @@ -2198,7 +2361,7 @@ TEST_F(ParseDescriptorDebugTest, TestMaps) { // Make sure the debug string uses map syntax and does not have the auto // generated entry. - string debug_string = file->DebugString(); + std::string debug_string = file->DebugString(); EXPECT_TRUE(debug_string.find("map<") != string::npos); EXPECT_TRUE(debug_string.find("option map_entry") == string::npos); EXPECT_TRUE(debug_string.find("MapEntry") == string::npos); @@ -2231,11 +2394,9 @@ TEST_F(ParseDescriptorDebugTest, TestMaps) { // *output_field to the descriptor of the field, and *output_index to -1. // Returns true if the path was valid, false otherwise. A gTest failure is // recorded before returning false. -bool FollowPath(const Message& root, - const int* path_begin, const int* path_end, +bool FollowPath(const Message& root, const int* path_begin, const int* path_end, const Message** output_message, - const FieldDescriptor** output_field, - int* output_index) { + const FieldDescriptor** output_field, int* output_index) { if (path_begin == path_end) { // Path refers to this whole message. *output_message = &root; @@ -2250,8 +2411,8 @@ bool FollowPath(const Message& root, const FieldDescriptor* field = descriptor->FindFieldByNumber(*path_begin); if (field == NULL) { - ADD_FAILURE() << descriptor->name() << " has no field number: " - << *path_begin; + ADD_FAILURE() << descriptor->name() + << " has no field number: " << *path_begin; return false; } @@ -2271,16 +2432,16 @@ bool FollowPath(const Message& root, if (index >= size) { ADD_FAILURE() << descriptor->name() << "." << field->name() - << " has size " << size << ", but path contained index: " - << index; + << " has size " << size + << ", but path contained index: " << index; return false; } if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { // Descend into child message. const Message& child = reflection->GetRepeatedMessage(root, field, index); - return FollowPath(child, path_begin, path_end, - output_message, output_field, output_index); + return FollowPath(child, path_begin, path_end, output_message, + output_field, output_index); } else if (path_begin == path_end) { // Path refers to this element. *output_message = &root; @@ -2295,8 +2456,8 @@ bool FollowPath(const Message& root, } else { if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { const Message& child = reflection->GetMessage(root, field); - return FollowPath(child, path_begin, path_end, - output_message, output_field, output_index); + return FollowPath(child, path_begin, path_end, output_message, + output_field, output_index); } else if (path_begin == path_end) { // Path refers to this field. *output_message = &root; @@ -2356,9 +2517,8 @@ class SourceInfoTest : public ParserTest { } virtual void TearDown() { - EXPECT_TRUE(spans_.empty()) - << "Forgot to call HasSpan() for:\n" - << spans_.begin()->second->DebugString(); + EXPECT_TRUE(spans_.empty()) << "Forgot to call HasSpan() for:\n" + << spans_.begin()->second->DebugString(); } // ----------------------------------------------------------------- @@ -2369,8 +2529,8 @@ class SourceInfoTest : public ParserTest { bool HasSpan(char start_marker, char end_marker, const Message& descriptor_proto) { - return HasSpanWithComment( - start_marker, end_marker, descriptor_proto, NULL, -1, NULL, NULL, NULL); + return HasSpanWithComment(start_marker, end_marker, descriptor_proto, NULL, + -1, NULL, NULL, NULL); } bool HasSpanWithComment(char start_marker, char end_marker, @@ -2378,28 +2538,27 @@ class SourceInfoTest : public ParserTest { const char* expected_leading_comments, const char* expected_trailing_comments, const char* expected_leading_detached_comments) { - return HasSpanWithComment( - start_marker, end_marker, descriptor_proto, NULL, -1, - expected_leading_comments, expected_trailing_comments, - expected_leading_detached_comments); + return HasSpanWithComment(start_marker, end_marker, descriptor_proto, NULL, + -1, expected_leading_comments, + expected_trailing_comments, + expected_leading_detached_comments); } bool HasSpan(char start_marker, char end_marker, - const Message& descriptor_proto, const string& field_name) { + const Message& descriptor_proto, const std::string& field_name) { return HasSpan(start_marker, end_marker, descriptor_proto, field_name, -1); } bool HasSpan(char start_marker, char end_marker, - const Message& descriptor_proto, const string& field_name, + const Message& descriptor_proto, const std::string& field_name, int index) { - return HasSpan(start_marker, end_marker, descriptor_proto, - field_name, index, NULL, NULL, NULL); + return HasSpan(start_marker, end_marker, descriptor_proto, field_name, + index, NULL, NULL, NULL); } bool HasSpan(char start_marker, char end_marker, - const Message& descriptor_proto, - const string& field_name, int index, - const char* expected_leading_comments, + const Message& descriptor_proto, const std::string& field_name, + int index, const char* expected_leading_comments, const char* expected_trailing_comments, const char* expected_leading_detached_comments) { const FieldDescriptor* field = @@ -2410,32 +2569,27 @@ class SourceInfoTest : public ParserTest { return false; } - return HasSpanWithComment( - start_marker, end_marker, descriptor_proto, field, index, - expected_leading_comments, expected_trailing_comments, - expected_leading_detached_comments); + return HasSpanWithComment(start_marker, end_marker, descriptor_proto, field, + index, expected_leading_comments, + expected_trailing_comments, + expected_leading_detached_comments); } bool HasSpan(const Message& descriptor_proto) { - return HasSpanWithComment( - '\0', '\0', descriptor_proto, NULL, -1, NULL, NULL, NULL); + return HasSpanWithComment('\0', '\0', descriptor_proto, NULL, -1, NULL, + NULL, NULL); } - bool HasSpan(const Message& descriptor_proto, const string& field_name) { + bool HasSpan(const Message& descriptor_proto, const std::string& field_name) { return HasSpan('\0', '\0', descriptor_proto, field_name, -1); } - bool HasSpan(const Message& descriptor_proto, const string& field_name, - int index) { - return HasSpan('\0', '\0', descriptor_proto, field_name, index); - } - - bool HasSpanWithComment( - char start_marker, char end_marker, const Message& descriptor_proto, - const FieldDescriptor* field, int index, - const char* expected_leading_comments, - const char* expected_trailing_comments, - const char* expected_leading_detached_comments) { + bool HasSpanWithComment(char start_marker, char end_marker, + const Message& descriptor_proto, + const FieldDescriptor* field, int index, + const char* expected_leading_comments, + const char* expected_trailing_comments, + const char* expected_leading_detached_comments) { std::pair range = spans_.equal_range(SpanKey(descriptor_proto, field, index)); @@ -2499,9 +2653,9 @@ class SourceInfoTest : public ParserTest { inline SpanKey() {} inline SpanKey(const Message& descriptor_proto_param, - const FieldDescriptor* field_param, - int index_param) - : descriptor_proto(&descriptor_proto_param), field(field_param), + const FieldDescriptor* field_param, int index_param) + : descriptor_proto(&descriptor_proto_param), + field(field_param), index(index_param) {} inline bool operator<(const SpanKey& other) const { @@ -2516,7 +2670,7 @@ class SourceInfoTest : public ParserTest { typedef std::multimap SpanMap; SpanMap spans_; std::map > markers_; - string text_without_markers_; + std::string text_without_markers_; void ExtractMarkers(const char* text) { markers_.clear(); @@ -2549,25 +2703,31 @@ class SourceInfoTest : public ParserTest { }; TEST_F(SourceInfoTest, BasicFileDecls) { - EXPECT_TRUE(Parse( - "$a$syntax = \"proto2\";$i$\n" - "package $b$foo.bar$c$;\n" - "import $d$\"baz.proto\"$e$;\n" - "import $f$\"qux.proto\"$g$;$h$\n" - "\n" - "// comment ignored\n")); + EXPECT_TRUE( + Parse("$a$syntax = \"proto2\";$i$\n" + "$b$package foo.bar;$c$\n" + "$d$import \"baz.proto\";$e$\n" + "$f$import\"qux.proto\";$h$\n" + "$j$import $k$public$l$ \"bar.proto\";$m$\n" + "$n$import $o$weak$p$ \"bar.proto\";$q$\n" + "\n" + "// comment ignored\n")); - EXPECT_TRUE(HasSpan('a', 'h', file_)); + EXPECT_TRUE(HasSpan('a', 'q', file_)); EXPECT_TRUE(HasSpan('b', 'c', file_, "package")); EXPECT_TRUE(HasSpan('d', 'e', file_, "dependency", 0)); - EXPECT_TRUE(HasSpan('f', 'g', file_, "dependency", 1)); + EXPECT_TRUE(HasSpan('f', 'h', file_, "dependency", 1)); + EXPECT_TRUE(HasSpan('j', 'm', file_, "dependency", 2)); + EXPECT_TRUE(HasSpan('k', 'l', file_, "public_dependency", 0)); + EXPECT_TRUE(HasSpan('n', 'q', file_, "dependency", 3)); + EXPECT_TRUE(HasSpan('o', 'p', file_, "weak_dependency", 0)); EXPECT_TRUE(HasSpan('a', 'i', file_, "syntax")); } TEST_F(SourceInfoTest, Messages) { - EXPECT_TRUE(Parse( - "$a$message $b$Foo$c$ {}$d$\n" - "$e$message $f$Bar$g$ {}$h$\n")); + EXPECT_TRUE( + Parse("$a$message $b$Foo$c$ {}$d$\n" + "$e$message $f$Bar$g$ {}$h$\n")); EXPECT_TRUE(HasSpan('a', 'd', file_.message_type(0))); EXPECT_TRUE(HasSpan('b', 'c', file_.message_type(0), "name")); @@ -2579,11 +2739,11 @@ TEST_F(SourceInfoTest, Messages) { } TEST_F(SourceInfoTest, Fields) { - EXPECT_TRUE(Parse( - "message Foo {\n" - " $a$optional$b$ $c$int32$d$ $e$bar$f$ = $g$1$h$;$i$\n" - " $j$repeated$k$ $l$X.Y$m$ $n$baz$o$ = $p$2$q$;$r$\n" - "}\n")); + EXPECT_TRUE( + Parse("message Foo {\n" + " $a$optional$b$ $c$int32$d$ $e$bar$f$ = $g$1$h$;$i$\n" + " $j$repeated$k$ $l$X.Y$m$ $n$baz$o$ = $p$2$q$;$r$\n" + "}\n")); const FieldDescriptorProto& field1 = file_.message_type(0).field(0); const FieldDescriptorProto& field2 = file_.message_type(0).field(1); @@ -2607,14 +2767,14 @@ TEST_F(SourceInfoTest, Fields) { } TEST_F(SourceInfoTest, Extensions) { - EXPECT_TRUE(Parse( - "$a$extend $b$Foo$c$ {\n" - " $d$optional$e$ int32 bar = 1;$f$\n" - " $g$repeated$h$ X.Y baz = 2;$i$\n" - "}$j$\n" - "$k$extend $l$Bar$m$ {\n" - " $n$optional int32 qux = 1;$o$\n" - "}$p$\n")); + EXPECT_TRUE( + Parse("$a$extend $b$Foo$c$ {\n" + " $d$optional$e$ int32 bar = 1;$f$\n" + " $g$repeated$h$ X.Y baz = 2;$i$\n" + "}$j$\n" + "$k$extend $l$Bar$m$ {\n" + " $n$optional int32 qux = 1;$o$\n" + "}$p$\n")); const FieldDescriptorProto& field1 = file_.extension(0); const FieldDescriptorProto& field2 = file_.extension(1); @@ -2649,16 +2809,16 @@ TEST_F(SourceInfoTest, Extensions) { } TEST_F(SourceInfoTest, NestedExtensions) { - EXPECT_TRUE(Parse( - "message Message {\n" - " $a$extend $b$Foo$c$ {\n" - " $d$optional$e$ int32 bar = 1;$f$\n" - " $g$repeated$h$ X.Y baz = 2;$i$\n" - " }$j$\n" - " $k$extend $l$Bar$m$ {\n" - " $n$optional int32 qux = 1;$o$\n" - " }$p$\n" - "}\n")); + EXPECT_TRUE( + Parse("message Message {\n" + " $a$extend $b$Foo$c$ {\n" + " $d$optional$e$ int32 bar = 1;$f$\n" + " $g$repeated$h$ X.Y baz = 2;$i$\n" + " }$j$\n" + " $k$extend $l$Bar$m$ {\n" + " $n$optional int32 qux = 1;$o$\n" + " }$p$\n" + "}\n")); const FieldDescriptorProto& field1 = file_.message_type(0).extension(0); const FieldDescriptorProto& field2 = file_.message_type(0).extension(1); @@ -2695,11 +2855,11 @@ TEST_F(SourceInfoTest, NestedExtensions) { } TEST_F(SourceInfoTest, ExtensionRanges) { - EXPECT_TRUE(Parse( - "message Message {\n" - " $a$extensions $b$1$c$ to $d$4$e$, $f$6$g$;$h$\n" - " $i$extensions $j$8$k$ to $l$max$m$;$n$\n" - "}\n")); + EXPECT_TRUE( + Parse("message Message {\n" + " $a$extensions $b$1$c$ to $d$4$e$, $f$6$g$;$h$\n" + " $i$extensions $j$8$k$ to $l$max$m$;$n$\n" + "}\n")); const DescriptorProto::ExtensionRange& range1 = file_.message_type(0).extension_range(0); @@ -2729,13 +2889,40 @@ TEST_F(SourceInfoTest, ExtensionRanges) { EXPECT_TRUE(HasSpan(file_.message_type(0), "name")); } +TEST_F(SourceInfoTest, ReservedRanges) { + EXPECT_TRUE( + Parse("message Message {\n" + " $a$reserved $b$1$c$ to $d$4$e$, $f$6$g$;$h$\n" + "}\n")); + + const DescriptorProto::ReservedRange& range1 = + file_.message_type(0).reserved_range(0); + const DescriptorProto::ReservedRange& range2 = + file_.message_type(0).reserved_range(1); + + EXPECT_TRUE(HasSpan('a', 'h', file_.message_type(0), "reserved_range")); + + EXPECT_TRUE(HasSpan('b', 'e', range1)); + EXPECT_TRUE(HasSpan('b', 'c', range1, "start")); + EXPECT_TRUE(HasSpan('d', 'e', range1, "end")); + + EXPECT_TRUE(HasSpan('f', 'g', range2)); + EXPECT_TRUE(HasSpan('f', 'g', range2, "start")); + EXPECT_TRUE(HasSpan('f', 'g', range2, "end")); + + // Ignore these. + EXPECT_TRUE(HasSpan(file_)); + EXPECT_TRUE(HasSpan(file_.message_type(0))); + EXPECT_TRUE(HasSpan(file_.message_type(0), "name")); +} + TEST_F(SourceInfoTest, Oneofs) { - EXPECT_TRUE(Parse( - "message Foo {\n" - " $a$oneof $c$foo$d$ {\n" - " $e$int32$f$ $g$a$h$ = $i$1$j$;$k$\n" - " }$r$\n" - "}\n")); + EXPECT_TRUE( + Parse("message Foo {\n" + " $a$oneof $c$foo$d$ {\n" + " $e$int32$f$ $g$a$h$ = $i$1$j$;$k$\n" + " }$r$\n" + "}\n")); const OneofDescriptorProto& oneof_decl = file_.message_type(0).oneof_decl(0); const FieldDescriptorProto& field = file_.message_type(0).field(0); @@ -2755,13 +2942,13 @@ TEST_F(SourceInfoTest, Oneofs) { } TEST_F(SourceInfoTest, NestedMessages) { - EXPECT_TRUE(Parse( - "message Foo {\n" - " $a$message $b$Bar$c$ {\n" - " $d$message $e$Baz$f$ {}$g$\n" - " }$h$\n" - " $i$message $j$Qux$k$ {}$l$\n" - "}\n")); + EXPECT_TRUE( + Parse("message Foo {\n" + " $a$message $b$Bar$c$ {\n" + " $d$message $e$Baz$f$ {}$g$\n" + " }$h$\n" + " $i$message $j$Qux$k$ {}$l$\n" + "}\n")); const DescriptorProto& bar = file_.message_type(0).nested_type(0); const DescriptorProto& baz = bar.nested_type(0); @@ -2781,13 +2968,13 @@ TEST_F(SourceInfoTest, NestedMessages) { } TEST_F(SourceInfoTest, Groups) { - EXPECT_TRUE(Parse( - "message Foo {\n" - " message Bar {}\n" - " $a$optional$b$ $c$group$d$ $e$Baz$f$ = $g$1$h$ {\n" - " $i$message Qux {}$j$\n" - " }$k$\n" - "}\n")); + EXPECT_TRUE( + Parse("message Foo {\n" + " message Bar {}\n" + " $a$optional$b$ $c$group$d$ $e$Baz$f$ = $g$1$h$ {\n" + " $i$message Qux {}$j$\n" + " }$k$\n" + "}\n")); const DescriptorProto& bar = file_.message_type(0).nested_type(0); const DescriptorProto& baz = file_.message_type(0).nested_type(1); @@ -2815,9 +3002,9 @@ TEST_F(SourceInfoTest, Groups) { } TEST_F(SourceInfoTest, Enums) { - EXPECT_TRUE(Parse( - "$a$enum $b$Foo$c$ {}$d$\n" - "$e$enum $f$Bar$g$ {}$h$\n")); + EXPECT_TRUE( + Parse("$a$enum $b$Foo$c$ {}$d$\n" + "$e$enum $f$Bar$g$ {}$h$\n")); EXPECT_TRUE(HasSpan('a', 'd', file_.enum_type(0))); EXPECT_TRUE(HasSpan('b', 'c', file_.enum_type(0), "name")); @@ -2829,11 +3016,11 @@ TEST_F(SourceInfoTest, Enums) { } TEST_F(SourceInfoTest, EnumValues) { - EXPECT_TRUE(Parse( - "enum Foo {\n" - " $a$BAR$b$ = $c$1$d$;$e$\n" - " $f$BAZ$g$ = $h$2$i$;$j$\n" - "}")); + EXPECT_TRUE( + Parse("enum Foo {\n" + " $a$BAR$b$ = $c$1$d$;$e$\n" + " $f$BAZ$g$ = $h$2$i$;$j$\n" + "}")); const EnumValueDescriptorProto& bar = file_.enum_type(0).value(0); const EnumValueDescriptorProto& baz = file_.enum_type(0).value(1); @@ -2852,11 +3039,11 @@ TEST_F(SourceInfoTest, EnumValues) { } TEST_F(SourceInfoTest, NestedEnums) { - EXPECT_TRUE(Parse( - "message Foo {\n" - " $a$enum $b$Bar$c$ {}$d$\n" - " $e$enum $f$Baz$g$ {}$h$\n" - "}\n")); + EXPECT_TRUE( + Parse("message Foo {\n" + " $a$enum $b$Bar$c$ {}$d$\n" + " $e$enum $f$Baz$g$ {}$h$\n" + "}\n")); const EnumDescriptorProto& bar = file_.message_type(0).enum_type(0); const EnumDescriptorProto& baz = file_.message_type(0).enum_type(1); @@ -2873,9 +3060,9 @@ TEST_F(SourceInfoTest, NestedEnums) { } TEST_F(SourceInfoTest, Services) { - EXPECT_TRUE(Parse( - "$a$service $b$Foo$c$ {}$d$\n" - "$e$service $f$Bar$g$ {}$h$\n")); + EXPECT_TRUE( + Parse("$a$service $b$Foo$c$ {}$d$\n" + "$e$service $f$Bar$g$ {}$h$\n")); EXPECT_TRUE(HasSpan('a', 'd', file_.service(0))); EXPECT_TRUE(HasSpan('b', 'c', file_.service(0), "name")); @@ -2887,11 +3074,11 @@ TEST_F(SourceInfoTest, Services) { } TEST_F(SourceInfoTest, MethodsAndStreams) { - EXPECT_TRUE(Parse( - "service Foo {\n" - " $a$rpc $b$Bar$c$($d$X$e$) returns($f$Y$g$);$h$" - " $i$rpc $j$Baz$k$($l$Z$m$) returns($n$W$o$);$p$" - "}")); + EXPECT_TRUE( + Parse("service Foo {\n" + " $a$rpc $b$Bar$c$($d$X$e$) returns($f$Y$g$);$h$" + " $i$rpc $j$Baz$k$($l$Z$m$) returns($n$W$o$);$p$" + "}")); const MethodDescriptorProto& bar = file_.service(0).method(0); const MethodDescriptorProto& baz = file_.service(0).method(1); @@ -2914,15 +3101,14 @@ TEST_F(SourceInfoTest, MethodsAndStreams) { TEST_F(SourceInfoTest, Options) { - EXPECT_TRUE(Parse( - "$a$option $b$foo$c$.$d$($e$bar.baz$f$)$g$ = " - "$h$123$i$;$j$\n" - "$k$option qux = $l$-123$m$;$n$\n" - "$o$option corge = $p$abc$q$;$r$\n" - "$s$option grault = $t$'blah'$u$;$v$\n" - "$w$option garply = $x${ yadda yadda }$y$;$z$\n" - "$0$option waldo = $1$123.0$2$;$3$\n" - )); + EXPECT_TRUE( + Parse("$a$option $b$foo$c$.$d$($e$bar.baz$f$)$g$ = " + "$h$123$i$;$j$\n" + "$k$option qux = $l$-123$m$;$n$\n" + "$o$option corge = $p$abc$q$;$r$\n" + "$s$option grault = $t$'blah'$u$;$v$\n" + "$w$option garply = $x${ yadda yadda }$y$;$z$\n" + "$0$option waldo = $1$123.0$2$;$3$\n")); const UninterpretedOption& option1 = file_.options().uninterpreted_option(0); const UninterpretedOption& option2 = file_.options().uninterpreted_option(1); @@ -2980,22 +3166,22 @@ TEST_F(SourceInfoTest, Options) { } TEST_F(SourceInfoTest, ScopedOptions) { - EXPECT_TRUE(Parse( - "message Foo {\n" - " $a$option mopt = 1;$b$\n" - "}\n" - "enum Bar {\n" - " $c$option eopt = 1;$d$\n" - "}\n" - "service Baz {\n" - " $e$option sopt = 1;$f$\n" - " rpc M(X) returns(Y) {\n" - " $g$option mopt = 1;$h$\n" - " }\n" - " rpc MS4($1$stream$2$ X) returns($3$stream$4$ Y) {\n" - " $k$option mopt = 1;$l$\n" - " }\n" - "}\n")); + EXPECT_TRUE( + Parse("message Foo {\n" + " $a$option mopt = 1;$b$\n" + "}\n" + "enum Bar {\n" + " $c$option eopt = 1;$d$\n" + "}\n" + "service Baz {\n" + " $e$option sopt = 1;$f$\n" + " rpc M(X) returns(Y) {\n" + " $g$option mopt = 1;$h$\n" + " }\n" + " rpc MS4($1$stream$2$ X) returns($3$stream$4$ Y) {\n" + " $k$option mopt = 1;$l$\n" + " }\n" + "}\n")); EXPECT_TRUE(HasSpan('a', 'b', file_.message_type(0).options())); EXPECT_TRUE(HasSpan('c', 'd', file_.enum_type(0).options())); @@ -3006,87 +3192,89 @@ TEST_F(SourceInfoTest, ScopedOptions) { EXPECT_TRUE(HasSpan(file_)); EXPECT_TRUE(HasSpan(file_.message_type(0))); EXPECT_TRUE(HasSpan(file_.message_type(0), "name")); - EXPECT_TRUE(HasSpan(file_.message_type(0).options() - .uninterpreted_option(0))); - EXPECT_TRUE(HasSpan(file_.message_type(0).options() - .uninterpreted_option(0), "name")); - EXPECT_TRUE(HasSpan(file_.message_type(0).options() - .uninterpreted_option(0).name(0))); - EXPECT_TRUE(HasSpan(file_.message_type(0).options() - .uninterpreted_option(0).name(0), "name_part")); - EXPECT_TRUE(HasSpan(file_.message_type(0).options() - .uninterpreted_option(0), "positive_int_value")); + EXPECT_TRUE(HasSpan(file_.message_type(0).options().uninterpreted_option(0))); + EXPECT_TRUE( + HasSpan(file_.message_type(0).options().uninterpreted_option(0), "name")); + EXPECT_TRUE( + HasSpan(file_.message_type(0).options().uninterpreted_option(0).name(0))); + EXPECT_TRUE( + HasSpan(file_.message_type(0).options().uninterpreted_option(0).name(0), + "name_part")); + EXPECT_TRUE(HasSpan(file_.message_type(0).options().uninterpreted_option(0), + "positive_int_value")); EXPECT_TRUE(HasSpan(file_.enum_type(0))); EXPECT_TRUE(HasSpan(file_.enum_type(0), "name")); - EXPECT_TRUE(HasSpan(file_.enum_type(0).options() - .uninterpreted_option(0))); - EXPECT_TRUE(HasSpan(file_.enum_type(0).options() - .uninterpreted_option(0), "name")); - EXPECT_TRUE(HasSpan(file_.enum_type(0).options() - .uninterpreted_option(0).name(0))); - EXPECT_TRUE(HasSpan(file_.enum_type(0).options() - .uninterpreted_option(0).name(0), "name_part")); - EXPECT_TRUE(HasSpan(file_.enum_type(0).options() - .uninterpreted_option(0), "positive_int_value")); + EXPECT_TRUE(HasSpan(file_.enum_type(0).options().uninterpreted_option(0))); + EXPECT_TRUE( + HasSpan(file_.enum_type(0).options().uninterpreted_option(0), "name")); + EXPECT_TRUE( + HasSpan(file_.enum_type(0).options().uninterpreted_option(0).name(0))); + EXPECT_TRUE( + HasSpan(file_.enum_type(0).options().uninterpreted_option(0).name(0), + "name_part")); + EXPECT_TRUE(HasSpan(file_.enum_type(0).options().uninterpreted_option(0), + "positive_int_value")); EXPECT_TRUE(HasSpan(file_.service(0))); EXPECT_TRUE(HasSpan(file_.service(0), "name")); EXPECT_TRUE(HasSpan(file_.service(0).method(0))); - EXPECT_TRUE(HasSpan(file_.service(0).options() - .uninterpreted_option(0))); - EXPECT_TRUE(HasSpan(file_.service(0).options() - .uninterpreted_option(0), "name")); - EXPECT_TRUE(HasSpan(file_.service(0).options() - .uninterpreted_option(0).name(0))); - EXPECT_TRUE(HasSpan(file_.service(0).options() - .uninterpreted_option(0).name(0), "name_part")); - EXPECT_TRUE(HasSpan(file_.service(0).options() - .uninterpreted_option(0), "positive_int_value")); + EXPECT_TRUE(HasSpan(file_.service(0).options().uninterpreted_option(0))); + EXPECT_TRUE( + HasSpan(file_.service(0).options().uninterpreted_option(0), "name")); + EXPECT_TRUE( + HasSpan(file_.service(0).options().uninterpreted_option(0).name(0))); + EXPECT_TRUE(HasSpan( + file_.service(0).options().uninterpreted_option(0).name(0), "name_part")); + EXPECT_TRUE(HasSpan(file_.service(0).options().uninterpreted_option(0), + "positive_int_value")); EXPECT_TRUE(HasSpan(file_.service(0).method(0), "name")); EXPECT_TRUE(HasSpan(file_.service(0).method(0), "input_type")); EXPECT_TRUE(HasSpan(file_.service(0).method(0), "output_type")); - EXPECT_TRUE(HasSpan(file_.service(0).method(0).options() - .uninterpreted_option(0))); - EXPECT_TRUE(HasSpan(file_.service(0).method(0).options() - .uninterpreted_option(0), "name")); - EXPECT_TRUE(HasSpan(file_.service(0).method(0).options() - .uninterpreted_option(0).name(0))); - EXPECT_TRUE(HasSpan(file_.service(0).method(0).options() - .uninterpreted_option(0).name(0), "name_part")); - EXPECT_TRUE(HasSpan(file_.service(0).method(0).options() - .uninterpreted_option(0), "positive_int_value")); + EXPECT_TRUE( + HasSpan(file_.service(0).method(0).options().uninterpreted_option(0))); + EXPECT_TRUE(HasSpan( + file_.service(0).method(0).options().uninterpreted_option(0), "name")); + EXPECT_TRUE(HasSpan( + file_.service(0).method(0).options().uninterpreted_option(0).name(0))); + EXPECT_TRUE(HasSpan( + file_.service(0).method(0).options().uninterpreted_option(0).name(0), + "name_part")); + EXPECT_TRUE( + HasSpan(file_.service(0).method(0).options().uninterpreted_option(0), + "positive_int_value")); EXPECT_TRUE(HasSpan('k', 'l', file_.service(0).method(1).options())); EXPECT_TRUE(HasSpan(file_.service(0).method(1))); EXPECT_TRUE(HasSpan(file_.service(0).method(1), "name")); EXPECT_TRUE(HasSpan(file_.service(0).method(1), "input_type")); EXPECT_TRUE(HasSpan(file_.service(0).method(1), "output_type")); - EXPECT_TRUE(HasSpan(file_.service(0).method(1).options() - .uninterpreted_option(0))); - EXPECT_TRUE(HasSpan(file_.service(0).method(1).options() - .uninterpreted_option(0), "name")); - EXPECT_TRUE(HasSpan(file_.service(0).method(1).options() - .uninterpreted_option(0).name(0))); - EXPECT_TRUE(HasSpan(file_.service(0).method(1).options() - .uninterpreted_option(0).name(0), "name_part")); - EXPECT_TRUE(HasSpan(file_.service(0).method(1).options() - .uninterpreted_option(0), "positive_int_value")); - EXPECT_TRUE(HasSpan('1', '2', file_.service(0).method(1), - "client_streaming")); - EXPECT_TRUE(HasSpan('3', '4', file_.service(0).method(1), - "server_streaming")); + EXPECT_TRUE( + HasSpan(file_.service(0).method(1).options().uninterpreted_option(0))); + EXPECT_TRUE(HasSpan( + file_.service(0).method(1).options().uninterpreted_option(0), "name")); + EXPECT_TRUE(HasSpan( + file_.service(0).method(1).options().uninterpreted_option(0).name(0))); + EXPECT_TRUE(HasSpan( + file_.service(0).method(1).options().uninterpreted_option(0).name(0), + "name_part")); + EXPECT_TRUE( + HasSpan(file_.service(0).method(1).options().uninterpreted_option(0), + "positive_int_value")); + EXPECT_TRUE( + HasSpan('1', '2', file_.service(0).method(1), "client_streaming")); + EXPECT_TRUE( + HasSpan('3', '4', file_.service(0).method(1), "server_streaming")); } TEST_F(SourceInfoTest, FieldOptions) { // The actual "name = value" pairs are parsed by the same code as for // top-level options so we won't re-test that -- just make sure that the // syntax used for field options is understood. - EXPECT_TRUE(Parse( - "message Foo {" - " optional int32 bar = 1 " - "$a$[default=$b$123$c$,$d$opt1=123$e$," - "$f$opt2='hi'$g$]$h$;" - "}\n" - )); + EXPECT_TRUE( + Parse("message Foo {" + " optional int32 bar = 1 " + "$a$[default=$b$123$c$,$d$opt1=123$e$," + "$f$opt2='hi'$g$]$h$;" + "}\n")); const FieldDescriptorProto& field = file_.message_type(0).field(0); const UninterpretedOption& option1 = field.options().uninterpreted_option(0); @@ -3120,11 +3308,10 @@ TEST_F(SourceInfoTest, EnumValueOptions) { // The actual "name = value" pairs are parsed by the same code as for // top-level options so we won't re-test that -- just make sure that the // syntax used for enum options is understood. - EXPECT_TRUE(Parse( - "enum Foo {" - " BAR = 1 $a$[$b$opt1=123$c$,$d$opt2='hi'$e$]$f$;" - "}\n" - )); + EXPECT_TRUE( + Parse("enum Foo {" + " BAR = 1 $a$[$b$opt1=123$c$,$d$opt2='hi'$e$]$f$;" + "}\n")); const EnumValueDescriptorProto& value = file_.enum_type(0).value(0); const UninterpretedOption& option1 = value.options().uninterpreted_option(0); @@ -3152,33 +3339,28 @@ TEST_F(SourceInfoTest, EnumValueOptions) { } TEST_F(SourceInfoTest, DocComments) { - EXPECT_TRUE(Parse( - "// Foo leading\n" - "// line 2\n" - "$a$message Foo {\n" - " // Foo trailing\n" - " // line 2\n" - "\n" - " // detached\n" - "\n" - " // bar leading\n" - " $b$optional int32 bar = 1;$c$\n" - " // bar trailing\n" - "}$d$\n" - "// ignored\n" - )); + EXPECT_TRUE( + Parse("// Foo leading\n" + "// line 2\n" + "$a$message Foo {\n" + " // Foo trailing\n" + " // line 2\n" + "\n" + " // detached\n" + "\n" + " // bar leading\n" + " $b$optional int32 bar = 1;$c$\n" + " // bar trailing\n" + "}$d$\n" + "// ignored\n")); const DescriptorProto& foo = file_.message_type(0); const FieldDescriptorProto& bar = foo.field(0); - EXPECT_TRUE(HasSpanWithComment('a', 'd', foo, - " Foo leading\n line 2\n", - " Foo trailing\n line 2\n", - NULL)); - EXPECT_TRUE(HasSpanWithComment('b', 'c', bar, - " bar leading\n", - " bar trailing\n", - " detached\n")); + EXPECT_TRUE(HasSpanWithComment('a', 'd', foo, " Foo leading\n line 2\n", + " Foo trailing\n line 2\n", NULL)); + EXPECT_TRUE(HasSpanWithComment('b', 'c', bar, " bar leading\n", + " bar trailing\n", " detached\n")); // Ignore these. EXPECT_TRUE(HasSpan(file_)); @@ -3190,45 +3372,40 @@ TEST_F(SourceInfoTest, DocComments) { } TEST_F(SourceInfoTest, DocComments2) { - EXPECT_TRUE(Parse( - "// detached before message.\n" - "\n" - "// Foo leading\n" - "// line 2\n" - "$a$message Foo {\n" - " /* Foo trailing\n" - " * line 2 */\n" - " // detached\n" - " /* bar leading\n" - " */" - " $b$optional int32 bar = 1;$c$ // bar trailing\n" - " // ignored detached\n" - "}$d$\n" - "// ignored\n" - "\n" - "// detached before option\n" - "\n" - "// option leading\n" - "$e$option baz = 123;$f$\n" - "// option trailing\n" - )); + EXPECT_TRUE( + Parse("// detached before message.\n" + "\n" + "// Foo leading\n" + "// line 2\n" + "$a$message Foo {\n" + " /* Foo trailing\n" + " * line 2 */\n" + " // detached\n" + " /* bar leading\n" + " */" + " $b$optional int32 bar = 1;$c$ // bar trailing\n" + " // ignored detached\n" + "}$d$\n" + "// ignored\n" + "\n" + "// detached before option\n" + "\n" + "// option leading\n" + "$e$option baz = 123;$f$\n" + "// option trailing\n")); const DescriptorProto& foo = file_.message_type(0); const FieldDescriptorProto& bar = foo.field(0); const UninterpretedOption& baz = file_.options().uninterpreted_option(0); - EXPECT_TRUE(HasSpanWithComment('a', 'd', foo, - " Foo leading\n line 2\n", - " Foo trailing\n line 2 ", - " detached before message.\n")); - EXPECT_TRUE(HasSpanWithComment('b', 'c', bar, - " bar leading\n", - " bar trailing\n", - " detached\n")); - EXPECT_TRUE(HasSpanWithComment('e', 'f', baz, - " option leading\n", - " option trailing\n", - " detached before option\n")); + EXPECT_TRUE(HasSpanWithComment('a', 'd', foo, " Foo leading\n line 2\n", + " Foo trailing\n line 2 ", + " detached before message.\n")); + EXPECT_TRUE(HasSpanWithComment('b', 'c', bar, " bar leading\n", + " bar trailing\n", " detached\n")); + EXPECT_TRUE(HasSpanWithComment('e', 'f', baz, " option leading\n", + " option trailing\n", + " detached before option\n")); // Ignore these. EXPECT_TRUE(HasSpan(file_)); @@ -3245,22 +3422,19 @@ TEST_F(SourceInfoTest, DocComments2) { } TEST_F(SourceInfoTest, DocComments3) { - EXPECT_TRUE(Parse( - "$a$message Foo {\n" - " // bar leading\n" - " $b$optional int32 bar = 1 [(baz.qux) = {}];$c$\n" - " // bar trailing\n" - "}$d$\n" - "// ignored\n" - )); + EXPECT_TRUE( + Parse("$a$message Foo {\n" + " // bar leading\n" + " $b$optional int32 bar = 1 [(baz.qux) = {}];$c$\n" + " // bar trailing\n" + "}$d$\n" + "// ignored\n")); const DescriptorProto& foo = file_.message_type(0); const FieldDescriptorProto& bar = foo.field(0); - EXPECT_TRUE(HasSpanWithComment('b', 'c', bar, - " bar leading\n", - " bar trailing\n", - NULL)); + EXPECT_TRUE(HasSpanWithComment('b', 'c', bar, " bar leading\n", + " bar trailing\n", NULL)); // Ignore these. EXPECT_TRUE(HasSpan(file_)); @@ -3274,88 +3448,82 @@ TEST_F(SourceInfoTest, DocComments3) { EXPECT_TRUE(HasSpan(bar.options().uninterpreted_option(0))); EXPECT_TRUE(HasSpan(bar.options().uninterpreted_option(0), "name")); EXPECT_TRUE(HasSpan(bar.options().uninterpreted_option(0).name(0))); - EXPECT_TRUE(HasSpan( - bar.options().uninterpreted_option(0).name(0), "name_part")); - EXPECT_TRUE(HasSpan( - bar.options().uninterpreted_option(0), "aggregate_value")); + EXPECT_TRUE( + HasSpan(bar.options().uninterpreted_option(0).name(0), "name_part")); + EXPECT_TRUE( + HasSpan(bar.options().uninterpreted_option(0), "aggregate_value")); } TEST_F(SourceInfoTest, DocCommentsTopLevel) { - EXPECT_TRUE(Parse( - "// detached before syntax paragraph 1\n" - "\n" - "// detached before syntax paragraph 2\n" - "\n" - "// syntax leading\n" - "$a$syntax = \"proto2\";$b$\n" - "// syntax trailing\n" - "\n" - "// syntax-package detached comments\n" - "\n" - ";\n" - "\n" - "// detached after empty before package\n" - "\n" - "// package leading\n" - "package $c$foo$d$;\n" - "// package trailing\n" - "\n" - "// ignored detach\n" - "\n")); + EXPECT_TRUE( + Parse("// detached before syntax paragraph 1\n" + "\n" + "// detached before syntax paragraph 2\n" + "\n" + "// syntax leading\n" + "$a$syntax = \"proto2\";$b$\n" + "// syntax trailing\n" + "\n" + "// syntax-package detached comments\n" + "\n" + ";\n" + "\n" + "// detached after empty before package\n" + "\n" + "// package leading\n" + "$c$package foo;$d$\n" + "// package trailing\n" + "\n" + "// ignored detach\n" + "\n")); - EXPECT_TRUE(HasSpan('a', 'b', file_, "syntax", -1, - " syntax leading\n", - " syntax trailing\n", - " detached before syntax paragraph 1\n" - "\n" - " detached before syntax paragraph 2\n")); - EXPECT_TRUE(HasSpan('c', 'd', file_, "package", -1, - " package leading\n", - " package trailing\n", - " syntax-package detached comments\n" - "\n" - " detached after empty before package\n")); + EXPECT_TRUE(HasSpan('a', 'b', file_, "syntax", -1, " syntax leading\n", + " syntax trailing\n", + " detached before syntax paragraph 1\n" + "\n" + " detached before syntax paragraph 2\n")); + EXPECT_TRUE(HasSpan('c', 'd', file_, "package", -1, " package leading\n", + " package trailing\n", + " syntax-package detached comments\n" + "\n" + " detached after empty before package\n")); // ignore these. EXPECT_TRUE(HasSpan(file_)); } TEST_F(SourceInfoTest, DocCommentsOneof) { - EXPECT_TRUE(Parse( - "// Foo leading\n" - "$a$message Foo {\n" - " /* Foo trailing\n" - " */\n" - " // detached before oneof\n" - " /* bar leading\n" - " * line 2 */\n" - " $b$oneof bar {\n" - " /* bar trailing\n" - " * line 2 */\n" - " // detached before bar_int\n" - " /* bar_int leading\n" - " */\n" - " $c$int32 bar_int = 1;$d$ // bar_int trailing\n" - " // detach comment ignored\n" - " }$e$\n" - "}$f$\n")); + EXPECT_TRUE( + Parse("// Foo leading\n" + "$a$message Foo {\n" + " /* Foo trailing\n" + " */\n" + " // detached before oneof\n" + " /* bar leading\n" + " * line 2 */\n" + " $b$oneof bar {\n" + " /* bar trailing\n" + " * line 2 */\n" + " // detached before bar_int\n" + " /* bar_int leading\n" + " */\n" + " $c$int32 bar_int = 1;$d$ // bar_int trailing\n" + " // detach comment ignored\n" + " }$e$\n" + "}$f$\n")); const DescriptorProto& foo = file_.message_type(0); const OneofDescriptorProto& bar = foo.oneof_decl(0); const FieldDescriptorProto& bar_int = foo.field(0); - EXPECT_TRUE(HasSpanWithComment('a', 'f', foo, - " Foo leading\n", - " Foo trailing\n", - NULL)); - EXPECT_TRUE(HasSpanWithComment('b', 'e', bar, - " bar leading\n line 2 ", - " bar trailing\n line 2 ", - " detached before oneof\n")); - EXPECT_TRUE(HasSpanWithComment('c', 'd', bar_int, - " bar_int leading\n", - " bar_int trailing\n", - " detached before bar_int\n")); + EXPECT_TRUE(HasSpanWithComment('a', 'f', foo, " Foo leading\n", + " Foo trailing\n", NULL)); + EXPECT_TRUE(HasSpanWithComment('b', 'e', bar, " bar leading\n line 2 ", + " bar trailing\n line 2 ", + " detached before oneof\n")); + EXPECT_TRUE(HasSpanWithComment('c', 'd', bar_int, " bar_int leading\n", + " bar_int trailing\n", + " detached before bar_int\n")); // Ignore these. EXPECT_TRUE(HasSpan(file_)); diff --git a/third_party/protobuf/src/google/protobuf/compiler/php/php_generator.cc b/third_party/protobuf/src/google/protobuf/compiler/php/php_generator.cc index a58e1754..8e405608 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/php/php_generator.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/php/php_generator.cc @@ -99,6 +99,10 @@ void GenerateMessageConstructorDocComment(io::Printer* printer, int is_descriptor); void GenerateFieldDocComment(io::Printer* printer, const FieldDescriptor* field, int is_descriptor, int function_type); +void GenerateWrapperFieldGetterDocComment(io::Printer* printer, + const FieldDescriptor* field); +void GenerateWrapperFieldSetterDocComment(io::Printer* printer, + const FieldDescriptor* field); void GenerateEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_, int is_descriptor); void GenerateEnumValueDocComment(io::Printer* printer, @@ -651,35 +655,88 @@ void GenerateOneofField(const OneofDescriptor* oneof, io::Printer* printer) { void GenerateFieldAccessor(const FieldDescriptor* field, bool is_descriptor, io::Printer* printer) { + bool need_other_name_for_accessor = false; + bool need_other_name_for_wrapper_accessor = false; + const Descriptor* desc = field->containing_type(); + + if (!field->is_repeated() && + field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && + IsWrapperType(field)) { + // Check if there is any field called xxx_value + const FieldDescriptor* other = + desc->FindFieldByName(StrCat(field->name(), "_value")); + if (other != NULL) { + need_other_name_for_wrapper_accessor = true; + } + } + + if (strings::EndsWith(field->name(), "_value")) { + std::size_t pos = (field->name()).find("_value"); + string name = (field->name()).substr(0, pos); + const FieldDescriptor* other = desc->FindFieldByName(name); + if (other != NULL && + !other->is_repeated() && + other->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && + IsWrapperType(other)) { + need_other_name_for_accessor = true; + } + } + const OneofDescriptor* oneof = field->containing_oneof(); // Generate getter. if (oneof != NULL) { GenerateFieldDocComment(printer, field, is_descriptor, kFieldGetter); printer->Print( - "public function get^camel_name^()\n" + "public function get^camel_name^^field_number^()\n" "{\n" " return $this->readOneof(^number^);\n" "}\n\n", "camel_name", UnderscoresToCamelCase(field->name(), true), - "number", IntToString(field->number())); + "number", IntToString(field->number()), + "field_number", need_other_name_for_accessor ? + StrCat(field->number()) : ""); } else { GenerateFieldDocComment(printer, field, is_descriptor, kFieldGetter); printer->Print( - "public function get^camel_name^()\n" + "public function get^camel_name^^field_number^()\n" "{\n" " return $this->^name^;\n" "}\n\n", - "camel_name", UnderscoresToCamelCase(field->name(), true), "name", - field->name()); + "camel_name", UnderscoresToCamelCase(field->name(), true), + "name", field->name(), + "field_number", need_other_name_for_accessor ? + StrCat(field->number()) : ""); + } + + // For wrapper types, generate an additional getXXXValue getter + if (!field->is_map() && + !field->is_repeated() && + field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && + IsWrapperType(field)) { + GenerateWrapperFieldGetterDocComment(printer, field); + + printer->Print( + "public function get^camel_name^Value^field_number1^()\n" + "{\n" + " $wrapper = $this->get^camel_name^^field_number2^();\n" + " return is_null($wrapper) ? null : $wrapper->getValue();\n" + "}\n\n", + "camel_name", UnderscoresToCamelCase(field->name(), true), + "field_number1", need_other_name_for_wrapper_accessor ? + StrCat(field->number()) : "", + "field_number2", need_other_name_for_accessor ? + StrCat(field->number()) : ""); } // Generate setter. GenerateFieldDocComment(printer, field, is_descriptor, kFieldSetter); printer->Print( - "public function set^camel_name^($var)\n" + "public function set^camel_name^^field_number^($var)\n" "{\n", - "camel_name", UnderscoresToCamelCase(field->name(), true)); + "camel_name", UnderscoresToCamelCase(field->name(), true), + "field_number", need_other_name_for_accessor ? + StrCat(field->number()) : ""); Indent(printer); @@ -772,6 +829,26 @@ void GenerateFieldAccessor(const FieldDescriptor* field, bool is_descriptor, printer->Print( "}\n\n"); + // For wrapper types, generate an additional setXXXValue getter + if (!field->is_map() && + !field->is_repeated() && + field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && + IsWrapperType(field)) { + GenerateWrapperFieldSetterDocComment(printer, field); + printer->Print( + "public function set^camel_name^Value^field_number1^($var)\n" + "{\n" + " $wrappedVar = is_null($var) ? null : new \\^wrapper_type^(['value' => $var]);\n" + " return $this->set^camel_name^^field_number2^($wrappedVar);\n" + "}\n\n", + "camel_name", UnderscoresToCamelCase(field->name(), true), + "wrapper_type", LegacyFullClassName(field->message_type(), is_descriptor), + "field_number1", need_other_name_for_wrapper_accessor ? + StrCat(field->number()) : "", + "field_number2", need_other_name_for_accessor ? + StrCat(field->number()) : ""); + } + // Generate has method for proto2 only. if (is_descriptor) { printer->Print( @@ -975,7 +1052,7 @@ void GenerateAddFileToPool(const FileDescriptor* file, bool is_descriptor, Outdent(printer); printer->Print( - "));\n\n"); + "), true);\n\n"); } printer->Print( "static::$is_initialized = true;\n"); @@ -1109,14 +1186,18 @@ void GenerateEnumFile(const FileDescriptor* file, const EnumDescriptor* en, printer.Print( "namespace ^name^;\n\n", "name", fullname.substr(0, lastindex)); + + // We only need this 'use' statement if the enum has a namespace. + // Otherwise, we get a warning that the use statement has no effect. + printer.Print("use UnexpectedValueException;\n\n"); } + GenerateEnumDocComment(&printer, en, is_descriptor); + if (lastindex != string::npos) { fullname = fullname.substr(lastindex + 1); } - GenerateEnumDocComment(&printer, en, is_descriptor); - printer.Print( "class ^name^\n" "{\n", @@ -1131,6 +1212,53 @@ void GenerateEnumFile(const FileDescriptor* file, const EnumDescriptor* en, "number", IntToString(value->number())); } + printer.Print("\nprivate static $valueToName = [\n"); + Indent(&printer); + for (int i = 0; i < en->value_count(); i++) { + const EnumValueDescriptor* value = en->value(i); + printer.Print("self::^name^ => '^name^',\n", + "name", ConstantNamePrefix(value->name()) + value->name()); + } + Outdent(&printer); + printer.Print("];\n"); + + printer.Print( + "\npublic static function name($value)\n" + "{\n"); + Indent(&printer); + printer.Print("if (!isset(self::$valueToName[$value])) {\n"); + Indent(&printer); + printer.Print("throw new UnexpectedValueException(sprintf(\n"); + Indent(&printer); + Indent(&printer); + printer.Print("'Enum %s has no name defined for value %s', __CLASS__, $value));\n"); + Outdent(&printer); + Outdent(&printer); + Outdent(&printer); + printer.Print("}\n" + "return self::$valueToName[$value];\n"); + Outdent(&printer); + printer.Print("}\n\n"); + + printer.Print( + "\npublic static function value($name)\n" + "{\n"); + Indent(&printer); + printer.Print("$const = __CLASS__ . '::' . strtoupper($name);\n" + "if (!defined($const)) {\n"); + Indent(&printer); + printer.Print("throw new UnexpectedValueException(sprintf(\n"); + Indent(&printer); + Indent(&printer); + printer.Print("'Enum %s has no value defined for name %s', __CLASS__, $name));\n"); + Outdent(&printer); + Outdent(&printer); + Outdent(&printer); + printer.Print("}\n" + "return constant($const);\n"); + Outdent(&printer); + printer.Print("}\n"); + Outdent(&printer); printer.Print("}\n\n"); @@ -1497,6 +1625,41 @@ void GenerateFieldDocComment(io::Printer* printer, const FieldDescriptor* field, printer->Print(" */\n"); } +void GenerateWrapperFieldGetterDocComment(io::Printer* printer, const FieldDescriptor* field) { + // Generate a doc comment for the special getXXXValue methods that are + // generated for wrapper types. + const FieldDescriptor* primitiveField = field->message_type()->FindFieldByName("value"); + printer->Print("/**\n"); + printer->Print( + " * Returns the unboxed value from get^camel_name^()\n\n", + "camel_name", UnderscoresToCamelCase(field->name(), true)); + GenerateDocCommentBody(printer, field); + printer->Print( + " * Generated from protobuf field ^def^\n", + "def", EscapePhpdoc(FirstLineOf(field->DebugString()))); + printer->Print(" * @return ^php_type^|null\n", + "php_type", PhpGetterTypeName(primitiveField, false)); + printer->Print(" */\n"); +} + +void GenerateWrapperFieldSetterDocComment(io::Printer* printer, const FieldDescriptor* field) { + // Generate a doc comment for the special setXXXValue methods that are + // generated for wrapper types. + const FieldDescriptor* primitiveField = field->message_type()->FindFieldByName("value"); + printer->Print("/**\n"); + printer->Print( + " * Sets the field by wrapping a primitive type in a ^message_name^ object.\n\n", + "message_name", LegacyFullClassName(field->message_type(), false)); + GenerateDocCommentBody(printer, field); + printer->Print( + " * Generated from protobuf field ^def^\n", + "def", EscapePhpdoc(FirstLineOf(field->DebugString()))); + printer->Print(" * @param ^php_type^|null $var\n", + "php_type", PhpSetterTypeName(primitiveField, false)); + printer->Print(" * @return $this\n"); + printer->Print(" */\n"); +} + void GenerateEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_, int is_descriptor) { printer->Print("/**\n"); diff --git a/third_party/protobuf/src/google/protobuf/compiler/php/php_generator.h b/third_party/protobuf/src/google/protobuf/compiler/php/php_generator.h index b851d9b4..ef708ab5 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/php/php_generator.h +++ b/third_party/protobuf/src/google/protobuf/compiler/php/php_generator.h @@ -36,13 +36,14 @@ #include +#include + namespace google { namespace protobuf { namespace compiler { namespace php { -class LIBPROTOC_EXPORT Generator - : public google::protobuf::compiler::CodeGenerator { +class PROTOC_EXPORT Generator : public CodeGenerator { virtual bool Generate( const FileDescriptor* file, const string& parameter, @@ -53,16 +54,20 @@ class LIBPROTOC_EXPORT Generator // To skip reserved keywords in php, some generated classname are prefixed. // Other code generators may need following API to figure out the actual // classname. -LIBPROTOC_EXPORT std::string GeneratedClassName( - const google::protobuf::Descriptor* desc); -LIBPROTOC_EXPORT std::string GeneratedClassName( - const google::protobuf::EnumDescriptor* desc); -LIBPROTOC_EXPORT std::string GeneratedClassName( - const google::protobuf::ServiceDescriptor* desc); +PROTOC_EXPORT std::string GeneratedClassName(const Descriptor* desc); +PROTOC_EXPORT std::string GeneratedClassName(const EnumDescriptor* desc); +PROTOC_EXPORT std::string GeneratedClassName(const ServiceDescriptor* desc); + +inline bool IsWrapperType(const FieldDescriptor* descriptor) { + return descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && + descriptor->message_type()->file()->name() == "google/protobuf/wrappers.proto"; +} } // namespace php } // namespace compiler } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_PHP_GENERATOR_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/plugin.cc b/third_party/protobuf/src/google/protobuf/compiler/plugin.cc index 9c1c757c..ac383f88 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/plugin.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/plugin.cc @@ -45,9 +45,9 @@ #include #include #include +#include #include #include -#include namespace google { @@ -57,14 +57,13 @@ namespace compiler { #if defined(_WIN32) // DO NOT include , instead create functions in io_win32.{h,cc} and import // them like we do below. -using google::protobuf::internal::win32::setmode; +using google::protobuf::io::win32::setmode; #endif class GeneratorResponseContext : public GeneratorContext { public: GeneratorResponseContext( - const Version& compiler_version, - CodeGeneratorResponse* response, + const Version& compiler_version, CodeGeneratorResponse* response, const std::vector& parsed_files) : compiler_version_(compiler_version), response_(response), @@ -73,14 +72,14 @@ class GeneratorResponseContext : public GeneratorContext { // implements GeneratorContext -------------------------------------- - virtual io::ZeroCopyOutputStream* Open(const string& filename) { + virtual io::ZeroCopyOutputStream* Open(const std::string& filename) { CodeGeneratorResponse::File* file = response_->add_file(); file->set_name(filename); return new io::StringOutputStream(file->mutable_content()); } virtual io::ZeroCopyOutputStream* OpenForInsert( - const string& filename, const string& insertion_point) { + const std::string& filename, const std::string& insertion_point) { CodeGeneratorResponse::File* file = response_->add_file(); file->set_name(filename); file->set_insertion_point(insertion_point); @@ -102,8 +101,8 @@ class GeneratorResponseContext : public GeneratorContext { }; bool GenerateCode(const CodeGeneratorRequest& request, - const CodeGenerator& generator, CodeGeneratorResponse* response, - string* error_msg) { + const CodeGenerator& generator, + CodeGeneratorResponse* response, std::string* error_msg) { DescriptorPool pool; for (int i = 0; i < request.proto_file_size(); i++) { const FileDescriptor* file = pool.BuildFile(request.proto_file(i)); @@ -117,24 +116,26 @@ bool GenerateCode(const CodeGeneratorRequest& request, for (int i = 0; i < request.file_to_generate_size(); i++) { parsed_files.push_back(pool.FindFileByName(request.file_to_generate(i))); if (parsed_files.back() == NULL) { - *error_msg = "protoc asked plugin to generate a file but " - "did not provide a descriptor for the file: " + - request.file_to_generate(i); + *error_msg = + "protoc asked plugin to generate a file but " + "did not provide a descriptor for the file: " + + request.file_to_generate(i); return false; } } - GeneratorResponseContext context( - request.compiler_version(), response, parsed_files); + GeneratorResponseContext context(request.compiler_version(), response, + parsed_files); - string error; - bool succeeded = generator.GenerateAll( - parsed_files, request.parameter(), &context, &error); + std::string error; + bool succeeded = generator.GenerateAll(parsed_files, request.parameter(), + &context, &error); if (!succeeded && error.empty()) { - error = "Code generator returned false but provided no error " - "description."; + error = + "Code generator returned false but provided no error " + "description."; } if (!error.empty()) { response->set_error(error); @@ -162,7 +163,7 @@ int PluginMain(int argc, char* argv[], const CodeGenerator* generator) { return 1; } - string error_msg; + std::string error_msg; CodeGeneratorResponse response; if (GenerateCode(request, *generator, &response, &error_msg)) { diff --git a/third_party/protobuf/src/google/protobuf/compiler/plugin.h b/third_party/protobuf/src/google/protobuf/compiler/plugin.h index d2793a9f..69c5d3f5 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/plugin.h +++ b/third_party/protobuf/src/google/protobuf/compiler/plugin.h @@ -64,27 +64,31 @@ #include -#include +#include + namespace google { namespace protobuf { namespace compiler { -class CodeGenerator; // code_generator.h +class CodeGenerator; // code_generator.h class CodeGeneratorRequest; class CodeGeneratorResponse; // Implements main() for a protoc plugin exposing the given code generator. -LIBPROTOC_EXPORT int PluginMain(int argc, char* argv[], const CodeGenerator* generator); +PROTOC_EXPORT int PluginMain(int argc, char* argv[], + const CodeGenerator* generator); // Generates code using the given code generator. Returns true if the code // generation is successful. If the code geneartion fails, error_msg may be // populated to describe the failure cause. bool GenerateCode(const CodeGeneratorRequest& request, - const CodeGenerator& generator, CodeGeneratorResponse* response, - string* error_msg); + const CodeGenerator& generator, + CodeGeneratorResponse* response, std::string* error_msg); } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_PLUGIN_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/plugin.pb.cc b/third_party/protobuf/src/google/protobuf/compiler/plugin.pb.cc index ef52def3..4cb497f9 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/plugin.pb.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/plugin.pb.cc @@ -6,247 +6,225 @@ #include #include -#include #include -#include +#include +#include #include #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) - -namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto { -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_CodeGeneratorResponse_File; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Version; -} // namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto -namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto { -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto; -} // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto -namespace google { -namespace protobuf { +#include +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<6> scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fcompiler_2fplugin_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_CodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fcompiler_2fplugin_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto; +PROTOBUF_NAMESPACE_OPEN namespace compiler { class VersionDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _Version_default_instance_; class CodeGeneratorRequestDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _CodeGeneratorRequest_default_instance_; class CodeGeneratorResponse_FileDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _CodeGeneratorResponse_File_default_instance_; class CodeGeneratorResponseDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _CodeGeneratorResponse_default_instance_; } // namespace compiler -} // namespace protobuf -} // namespace google -namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto { -static void InitDefaultsVersion() { +PROTOBUF_NAMESPACE_CLOSE +static void InitDefaultsscc_info_CodeGeneratorRequest_google_2fprotobuf_2fcompiler_2fplugin_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::compiler::_Version_default_instance_; - new (ptr) ::google::protobuf::compiler::Version(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::compiler::_CodeGeneratorRequest_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::compiler::Version::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest::InitAsDefaultInstance(); } -LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Version = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsVersion}, {}}; +PROTOC_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<2> scc_info_CodeGeneratorRequest_google_2fprotobuf_2fcompiler_2fplugin_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsscc_info_CodeGeneratorRequest_google_2fprotobuf_2fcompiler_2fplugin_2eproto}, { + &scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base,}}; -static void InitDefaultsCodeGeneratorRequest() { +static void InitDefaultsscc_info_CodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplugin_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::compiler::_CodeGeneratorRequest_default_instance_; - new (ptr) ::google::protobuf::compiler::CodeGeneratorRequest(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::compiler::_CodeGeneratorResponse_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::compiler::CodeGeneratorRequest::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse::InitAsDefaultInstance(); } -LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<2> scc_info_CodeGeneratorRequest = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsCodeGeneratorRequest}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base, - &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_Version.base,}}; +PROTOC_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_CodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplugin_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_CodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplugin_2eproto}, { + &scc_info_CodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base,}}; -static void InitDefaultsCodeGeneratorResponse_File() { +static void InitDefaultsscc_info_CodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::compiler::_CodeGeneratorResponse_File_default_instance_; - new (ptr) ::google::protobuf::compiler::CodeGeneratorResponse_File(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::compiler::_CodeGeneratorResponse_File_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::compiler::CodeGeneratorResponse_File::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File::InitAsDefaultInstance(); } -LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_CodeGeneratorResponse_File = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCodeGeneratorResponse_File}, {}}; +PROTOC_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_CodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_CodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto}, {}}; -static void InitDefaultsCodeGeneratorResponse() { +static void InitDefaultsscc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::compiler::_CodeGeneratorResponse_default_instance_; - new (ptr) ::google::protobuf::compiler::CodeGeneratorResponse(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::compiler::_Version_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::compiler::Version(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::compiler::CodeGeneratorResponse::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::compiler::Version::InitAsDefaultInstance(); } -LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_CodeGeneratorResponse = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsCodeGeneratorResponse}, { - &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse_File.base,}}; +PROTOC_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto}, {}}; -void InitDefaults() { - ::google::protobuf::internal::InitSCC(&scc_info_Version.base); - ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorRequest.base); - ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorResponse_File.base); - ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorResponse.base); -} +static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_google_2fprotobuf_2fcompiler_2fplugin_2eproto[4]; +static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto = nullptr; +static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto = nullptr; -::google::protobuf::Metadata file_level_metadata[4]; - -const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, _internal_metadata_), +const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::Version, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::Version, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, major_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, minor_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, patch_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, suffix_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::Version, major_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::Version, minor_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::Version, patch_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::Version, suffix_), 1, 2, 3, 0, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, file_to_generate_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, parameter_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, proto_file_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, compiler_version_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest, file_to_generate_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest, parameter_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest, proto_file_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest, compiler_version_), ~0u, 0, ~0u, 1, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, insertion_point_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, content_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File, name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File, insertion_point_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File, content_), 0, 1, 2, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, error_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, file_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse, error_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse, file_), 0, ~0u, }; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - { 0, 9, sizeof(::google::protobuf::compiler::Version)}, - { 13, 22, sizeof(::google::protobuf::compiler::CodeGeneratorRequest)}, - { 26, 34, sizeof(::google::protobuf::compiler::CodeGeneratorResponse_File)}, - { 37, 44, sizeof(::google::protobuf::compiler::CodeGeneratorResponse)}, +static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, 9, sizeof(PROTOBUF_NAMESPACE_ID::compiler::Version)}, + { 13, 22, sizeof(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest)}, + { 26, 34, sizeof(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File)}, + { 37, 44, sizeof(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse)}, }; -static ::google::protobuf::Message const * const file_default_instances[] = { - reinterpret_cast(&::google::protobuf::compiler::_Version_default_instance_), - reinterpret_cast(&::google::protobuf::compiler::_CodeGeneratorRequest_default_instance_), - reinterpret_cast(&::google::protobuf::compiler::_CodeGeneratorResponse_File_default_instance_), - reinterpret_cast(&::google::protobuf::compiler::_CodeGeneratorResponse_default_instance_), +static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::compiler::_Version_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::compiler::_CodeGeneratorRequest_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::compiler::_CodeGeneratorResponse_File_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::compiler::_CodeGeneratorResponse_default_instance_), }; -void protobuf_AssignDescriptors() { - AddDescriptors(); - AssignDescriptors( - "google/protobuf/compiler/plugin.proto", schemas, file_default_instances, TableStruct::offsets, - file_level_metadata, NULL, NULL); -} +const char descriptor_table_protodef_google_2fprotobuf_2fcompiler_2fplugin_2eproto[] = + "\n%google/protobuf/compiler/plugin.proto\022" + "\030google.protobuf.compiler\032 google/protob" + "uf/descriptor.proto\"F\n\007Version\022\r\n\005major\030" + "\001 \001(\005\022\r\n\005minor\030\002 \001(\005\022\r\n\005patch\030\003 \001(\005\022\016\n\006s" + "uffix\030\004 \001(\t\"\272\001\n\024CodeGeneratorRequest\022\030\n\020" + "file_to_generate\030\001 \003(\t\022\021\n\tparameter\030\002 \001(" + "\t\0228\n\nproto_file\030\017 \003(\0132$.google.protobuf." + "FileDescriptorProto\022;\n\020compiler_version\030" + "\003 \001(\0132!.google.protobuf.compiler.Version" + "\"\252\001\n\025CodeGeneratorResponse\022\r\n\005error\030\001 \001(" + "\t\022B\n\004file\030\017 \003(\01324.google.protobuf.compil" + "er.CodeGeneratorResponse.File\032>\n\004File\022\014\n" + "\004name\030\001 \001(\t\022\027\n\017insertion_point\030\002 \001(\t\022\017\n\007" + "content\030\017 \001(\tBg\n\034com.google.protobuf.com" + "pilerB\014PluginProtosZ9github.com/golang/p" + "rotobuf/protoc-gen-go/plugin;plugin_go" + ; +static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto_deps[1] = { + &::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto, +}; +static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto_sccs[4] = { + &scc_info_CodeGeneratorRequest_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base, + &scc_info_CodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base, + &scc_info_CodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base, + &scc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base, +}; +static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto_once; +static bool descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto_initialized = false; +const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto = { + &descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fcompiler_2fplugin_2eproto, "google/protobuf/compiler/plugin.proto", 638, + &descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto_once, descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto_sccs, descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto_deps, 4, 1, + schemas, file_default_instances, TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2fcompiler_2fplugin_2eproto, 4, file_level_enum_descriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto, file_level_service_descriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto, +}; -void protobuf_AssignDescriptorsOnce() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); -} - -void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 4); -} - -void AddDescriptorsImpl() { - InitDefaults(); - static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - "\n%google/protobuf/compiler/plugin.proto\022" - "\030google.protobuf.compiler\032 google/protob" - "uf/descriptor.proto\"F\n\007Version\022\r\n\005major\030" - "\001 \001(\005\022\r\n\005minor\030\002 \001(\005\022\r\n\005patch\030\003 \001(\005\022\016\n\006s" - "uffix\030\004 \001(\t\"\272\001\n\024CodeGeneratorRequest\022\030\n\020" - "file_to_generate\030\001 \003(\t\022\021\n\tparameter\030\002 \001(" - "\t\0228\n\nproto_file\030\017 \003(\0132$.google.protobuf." - "FileDescriptorProto\022;\n\020compiler_version\030" - "\003 \001(\0132!.google.protobuf.compiler.Version" - "\"\252\001\n\025CodeGeneratorResponse\022\r\n\005error\030\001 \001(" - "\t\022B\n\004file\030\017 \003(\01324.google.protobuf.compil" - "er.CodeGeneratorResponse.File\032>\n\004File\022\014\n" - "\004name\030\001 \001(\t\022\027\n\017insertion_point\030\002 \001(\t\022\017\n\007" - "content\030\017 \001(\tBg\n\034com.google.protobuf.com" - "pilerB\014PluginProtosZ9github.com/golang/p" - "rotobuf/protoc-gen-go/plugin;plugin_go" - }; - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - descriptor, 638); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "google/protobuf/compiler/plugin.proto", &protobuf_RegisterTypes); - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::AddDescriptors(); -} - -void AddDescriptors() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); -} -// Force AddDescriptors() to be called at dynamic initialization time. -struct StaticDescriptorInitializer { - StaticDescriptorInitializer() { - AddDescriptors(); - } -} static_descriptor_initializer; -} // namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto -namespace google { -namespace protobuf { +// Force running AddDescriptors() at dynamic initialization time. +static bool dynamic_init_dummy_google_2fprotobuf_2fcompiler_2fplugin_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto), true); +PROTOBUF_NAMESPACE_OPEN namespace compiler { // =================================================================== void Version::InitAsDefaultInstance() { } +class Version::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_major(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } + static void set_has_minor(HasBits* has_bits) { + (*has_bits)[0] |= 4u; + } + static void set_has_patch(HasBits* has_bits) { + (*has_bits)[0] |= 8u; + } + static void set_has_suffix(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Version::kMajorFieldNumber; const int Version::kMinorFieldNumber; @@ -255,20 +233,18 @@ const int Version::kSuffixFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Version::Version() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_Version.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.compiler.Version) } Version::Version(const Version& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - suffix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + suffix_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_suffix()) { - suffix_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.suffix_); + suffix_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.suffix_); } ::memcpy(&major_, &from.major_, static_cast(reinterpret_cast(&patch_) - @@ -277,7 +253,8 @@ Version::Version(const Version& from) } void Version::SharedCtor() { - suffix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base); + suffix_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(&major_, 0, static_cast( reinterpret_cast(&patch_) - reinterpret_cast(&major_)) + sizeof(patch_)); @@ -289,26 +266,21 @@ Version::~Version() { } void Version::SharedDtor() { - suffix_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + suffix_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void Version::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* Version::descriptor() { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const Version& Version::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_Version.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base); return *internal_default_instance(); } void Version::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.compiler.Version) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -316,7 +288,7 @@ void Version::Clear() { if (cached_has_bits & 0x00000001u) { suffix_.ClearNonDefaultToEmptyNoArena(); } - if (cached_has_bits & 14u) { + if (cached_has_bits & 0x0000000eu) { ::memset(&major_, 0, static_cast( reinterpret_cast(&patch_) - reinterpret_cast(&major_)) + sizeof(patch_)); @@ -325,23 +297,83 @@ void Version::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* Version::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional int32 major = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { + HasBitSetters::set_has_major(&has_bits); + major_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional int32 minor = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { + HasBitSetters::set_has_minor(&has_bits); + minor_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional int32 patch = 3; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) { + HasBitSetters::set_has_patch(&has_bits); + patch_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string suffix = 4; + case 4: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_suffix(), ptr, ctx, "google.protobuf.compiler.Version.suffix"); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Version::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.compiler.Version) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional int32 major = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { - set_has_major(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) { + HasBitSetters::set_has_major(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &major_))); } else { goto handle_unusual; @@ -351,11 +383,10 @@ bool Version::MergePartialFromCodedStream( // optional int32 minor = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { - set_has_minor(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (16 & 0xFF)) { + HasBitSetters::set_has_minor(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &minor_))); } else { goto handle_unusual; @@ -365,11 +396,10 @@ bool Version::MergePartialFromCodedStream( // optional int32 patch = 3; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { - set_has_patch(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (24 & 0xFF)) { + HasBitSetters::set_has_patch(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &patch_))); } else { goto handle_unusual; @@ -379,13 +409,12 @@ bool Version::MergePartialFromCodedStream( // optional string suffix = 4; case 4: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (34 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_suffix())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->suffix().data(), static_cast(this->suffix().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.compiler.Version.suffix"); } else { goto handle_unusual; @@ -398,7 +427,7 @@ bool Version::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -412,82 +441,82 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void Version::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.compiler.Version) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional int32 major = 1; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->major(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(1, this->major(), output); } // optional int32 minor = 2; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->minor(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(2, this->minor(), output); } // optional int32 patch = 3; if (cached_has_bits & 0x00000008u) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->patch(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(3, this->patch(), output); } // optional string suffix = 4; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->suffix().data(), static_cast(this->suffix().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.compiler.Version.suffix"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 4, this->suffix(), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.compiler.Version) } -::google::protobuf::uint8* Version::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* Version::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.compiler.Version) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional int32 major = 1; if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->major(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(1, this->major(), target); } // optional int32 minor = 2; if (cached_has_bits & 0x00000004u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->minor(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(2, this->minor(), target); } // optional int32 patch = 3; if (cached_has_bits & 0x00000008u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->patch(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(3, this->patch(), target); } // optional string suffix = 4; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->suffix().data(), static_cast(this->suffix().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.compiler.Version.suffix"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 4, this->suffix(), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.compiler.Version) @@ -500,53 +529,58 @@ size_t Version::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } - if (_has_bits_[0 / 32] & 15u) { + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x0000000fu) { // optional string suffix = 4; - if (has_suffix()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->suffix()); } // optional int32 major = 1; - if (has_major()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->major()); } // optional int32 minor = 2; - if (has_minor()) { + if (cached_has_bits & 0x00000004u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->minor()); } // optional int32 patch = 3; - if (has_patch()) { + if (cached_has_bits & 0x00000008u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->patch()); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void Version::MergeFrom(const ::google::protobuf::Message& from) { +void Version::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.compiler.Version) GOOGLE_DCHECK_NE(&from, this); const Version* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.compiler.Version) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.compiler.Version) MergeFrom(*source); @@ -557,14 +591,14 @@ void Version::MergeFrom(const Version& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.Version) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 15u) { + if (cached_has_bits & 0x0000000fu) { if (cached_has_bits & 0x00000001u) { - set_has_suffix(); - suffix_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.suffix_); + _has_bits_[0] |= 0x00000001u; + suffix_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.suffix_); } if (cached_has_bits & 0x00000002u) { major_ = from.major_; @@ -579,7 +613,7 @@ void Version::MergeFrom(const Version& from) { } } -void Version::CopyFrom(const ::google::protobuf::Message& from) { +void Version::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.compiler.Version) if (&from == this) return; Clear(); @@ -603,26 +637,41 @@ void Version::Swap(Version* other) { } void Version::InternalSwap(Version* other) { using std::swap; - suffix_.Swap(&other->suffix_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); + suffix_.Swap(&other->suffix_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(major_, other->major_); swap(minor_, other->minor_); swap(patch_, other->patch_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata Version::GetMetadata() const { - protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata Version::GetMetadata() const { + return GetMetadataStatic(); } // =================================================================== void CodeGeneratorRequest::InitAsDefaultInstance() { - ::google::protobuf::compiler::_CodeGeneratorRequest_default_instance_._instance.get_mutable()->compiler_version_ = const_cast< ::google::protobuf::compiler::Version*>( - ::google::protobuf::compiler::Version::internal_default_instance()); + PROTOBUF_NAMESPACE_ID::compiler::_CodeGeneratorRequest_default_instance_._instance.get_mutable()->compiler_version_ = const_cast< PROTOBUF_NAMESPACE_ID::compiler::Version*>( + PROTOBUF_NAMESPACE_ID::compiler::Version::internal_default_instance()); +} +class CodeGeneratorRequest::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_parameter(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static const PROTOBUF_NAMESPACE_ID::compiler::Version& compiler_version(const CodeGeneratorRequest* msg); + static void set_has_compiler_version(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } +}; + +const PROTOBUF_NAMESPACE_ID::compiler::Version& +CodeGeneratorRequest::HasBitSetters::compiler_version(const CodeGeneratorRequest* msg) { + return *msg->compiler_version_; } void CodeGeneratorRequest::clear_proto_file() { proto_file_.Clear(); @@ -635,34 +684,33 @@ const int CodeGeneratorRequest::kCompilerVersionFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CodeGeneratorRequest::CodeGeneratorRequest() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorRequest.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorRequest) } CodeGeneratorRequest::CodeGeneratorRequest(const CodeGeneratorRequest& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), file_to_generate_(from.file_to_generate_), proto_file_(from.proto_file_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - parameter_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + parameter_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_parameter()) { - parameter_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.parameter_); + parameter_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.parameter_); } if (from.has_compiler_version()) { - compiler_version_ = new ::google::protobuf::compiler::Version(*from.compiler_version_); + compiler_version_ = new PROTOBUF_NAMESPACE_ID::compiler::Version(*from.compiler_version_); } else { - compiler_version_ = NULL; + compiler_version_ = nullptr; } // @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.CodeGeneratorRequest) } void CodeGeneratorRequest::SharedCtor() { - parameter_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - compiler_version_ = NULL; + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_CodeGeneratorRequest_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base); + parameter_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + compiler_version_ = nullptr; } CodeGeneratorRequest::~CodeGeneratorRequest() { @@ -671,39 +719,34 @@ CodeGeneratorRequest::~CodeGeneratorRequest() { } void CodeGeneratorRequest::SharedDtor() { - parameter_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + parameter_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete compiler_version_; } void CodeGeneratorRequest::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* CodeGeneratorRequest::descriptor() { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const CodeGeneratorRequest& CodeGeneratorRequest::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorRequest.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_CodeGeneratorRequest_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base); return *internal_default_instance(); } void CodeGeneratorRequest::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.compiler.CodeGeneratorRequest) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; file_to_generate_.Clear(); proto_file_.Clear(); cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { parameter_.ClearNonDefaultToEmptyNoArena(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(compiler_version_ != NULL); + GOOGLE_DCHECK(compiler_version_ != nullptr); compiler_version_->Clear(); } } @@ -711,26 +754,93 @@ void CodeGeneratorRequest::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* CodeGeneratorRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // repeated string file_to_generate = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr -= 1; + do { + ptr += 1; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(add_file_to_generate(), ptr, ctx, "google.protobuf.compiler.CodeGeneratorRequest.file_to_generate"); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 10); + } else goto handle_unusual; + continue; + // optional string parameter = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_parameter(), ptr, ctx, "google.protobuf.compiler.CodeGeneratorRequest.parameter"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional .google.protobuf.compiler.Version compiler_version = 3; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { + ptr = ctx->ParseMessage(mutable_compiler_version(), ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.FileDescriptorProto proto_file = 15; + case 15: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 122)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_proto_file(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 122); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CodeGeneratorRequest::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorRequest) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated string file_to_generate = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->add_file_to_generate())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->file_to_generate(this->file_to_generate_size() - 1).data(), static_cast(this->file_to_generate(this->file_to_generate_size() - 1).length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.compiler.CodeGeneratorRequest.file_to_generate"); } else { goto handle_unusual; @@ -740,13 +850,12 @@ bool CodeGeneratorRequest::MergePartialFromCodedStream( // optional string parameter = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_parameter())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->parameter().data(), static_cast(this->parameter().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.compiler.CodeGeneratorRequest.parameter"); } else { goto handle_unusual; @@ -756,9 +865,8 @@ bool CodeGeneratorRequest::MergePartialFromCodedStream( // optional .google.protobuf.compiler.Version compiler_version = 3; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, mutable_compiler_version())); } else { goto handle_unusual; @@ -768,9 +876,8 @@ bool CodeGeneratorRequest::MergePartialFromCodedStream( // repeated .google.protobuf.FileDescriptorProto proto_file = 15; case 15: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(122u /* 122 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (122 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_proto_file())); } else { goto handle_unusual; @@ -783,7 +890,7 @@ bool CodeGeneratorRequest::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -797,102 +904,102 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void CodeGeneratorRequest::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.compiler.CodeGeneratorRequest) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated string file_to_generate = 1; for (int i = 0, n = this->file_to_generate_size(); i < n; i++) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->file_to_generate(i).data(), static_cast(this->file_to_generate(i).length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.compiler.CodeGeneratorRequest.file_to_generate"); - ::google::protobuf::internal::WireFormatLite::WriteString( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteString( 1, this->file_to_generate(i), output); } cached_has_bits = _has_bits_[0]; // optional string parameter = 2; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->parameter().data(), static_cast(this->parameter().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.compiler.CodeGeneratorRequest.parameter"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->parameter(), output); } // optional .google.protobuf.compiler.Version compiler_version = 3; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, this->_internal_compiler_version(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( + 3, HasBitSetters::compiler_version(this), output); } // repeated .google.protobuf.FileDescriptorProto proto_file = 15; for (unsigned int i = 0, n = static_cast(this->proto_file_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 15, this->proto_file(static_cast(i)), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.compiler.CodeGeneratorRequest) } -::google::protobuf::uint8* CodeGeneratorRequest::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* CodeGeneratorRequest::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.compiler.CodeGeneratorRequest) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated string file_to_generate = 1; for (int i = 0, n = this->file_to_generate_size(); i < n; i++) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->file_to_generate(i).data(), static_cast(this->file_to_generate(i).length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.compiler.CodeGeneratorRequest.file_to_generate"); - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: WriteStringToArray(1, this->file_to_generate(i), target); } cached_has_bits = _has_bits_[0]; // optional string parameter = 2; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->parameter().data(), static_cast(this->parameter().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.compiler.CodeGeneratorRequest.parameter"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 2, this->parameter(), target); } // optional .google.protobuf.compiler.Version compiler_version = 3; if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 3, this->_internal_compiler_version(), deterministic, target); + 3, HasBitSetters::compiler_version(this), target); } // repeated .google.protobuf.FileDescriptorProto proto_file = 15; for (unsigned int i = 0, n = static_cast(this->proto_file_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 15, this->proto_file(static_cast(i)), deterministic, target); + 15, this->proto_file(static_cast(i)), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.compiler.CodeGeneratorRequest) @@ -905,14 +1012,18 @@ size_t CodeGeneratorRequest::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated string file_to_generate = 1; total_size += 1 * - ::google::protobuf::internal::FromIntSize(this->file_to_generate_size()); + ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->file_to_generate_size()); for (int i = 0, n = this->file_to_generate_size(); i < n; i++) { - total_size += ::google::protobuf::internal::WireFormatLite::StringSize( + total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->file_to_generate(i)); } @@ -922,41 +1033,42 @@ size_t CodeGeneratorRequest::ByteSizeLong() const { total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->proto_file(static_cast(i))); } } - if (_has_bits_[0 / 32] & 3u) { + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x00000003u) { // optional string parameter = 2; - if (has_parameter()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->parameter()); } // optional .google.protobuf.compiler.Version compiler_version = 3; - if (has_compiler_version()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *compiler_version_); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void CodeGeneratorRequest::MergeFrom(const ::google::protobuf::Message& from) { +void CodeGeneratorRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.compiler.CodeGeneratorRequest) GOOGLE_DCHECK_NE(&from, this); const CodeGeneratorRequest* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.compiler.CodeGeneratorRequest) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.compiler.CodeGeneratorRequest) MergeFrom(*source); @@ -967,24 +1079,24 @@ void CodeGeneratorRequest::MergeFrom(const CodeGeneratorRequest& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.CodeGeneratorRequest) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; file_to_generate_.MergeFrom(from.file_to_generate_); proto_file_.MergeFrom(from.proto_file_); cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { - set_has_parameter(); - parameter_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.parameter_); + _has_bits_[0] |= 0x00000001u; + parameter_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.parameter_); } if (cached_has_bits & 0x00000002u) { - mutable_compiler_version()->::google::protobuf::compiler::Version::MergeFrom(from.compiler_version()); + mutable_compiler_version()->PROTOBUF_NAMESPACE_ID::compiler::Version::MergeFrom(from.compiler_version()); } } } -void CodeGeneratorRequest::CopyFrom(const ::google::protobuf::Message& from) { +void CodeGeneratorRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.compiler.CodeGeneratorRequest) if (&from == this) return; Clear(); @@ -999,7 +1111,7 @@ void CodeGeneratorRequest::CopyFrom(const CodeGeneratorRequest& from) { } bool CodeGeneratorRequest::IsInitialized() const { - if (!::google::protobuf::internal::AllAreInitialized(this->proto_file())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->proto_file())) return false; return true; } @@ -1009,18 +1121,17 @@ void CodeGeneratorRequest::Swap(CodeGeneratorRequest* other) { } void CodeGeneratorRequest::InternalSwap(CodeGeneratorRequest* other) { using std::swap; + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); file_to_generate_.InternalSwap(CastToBase(&other->file_to_generate_)); CastToBase(&proto_file_)->InternalSwap(CastToBase(&other->proto_file_)); - parameter_.Swap(&other->parameter_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + parameter_.Swap(&other->parameter_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(compiler_version_, other->compiler_version_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata CodeGeneratorRequest::GetMetadata() const { - protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata CodeGeneratorRequest::GetMetadata() const { + return GetMetadataStatic(); } @@ -1028,6 +1139,20 @@ void CodeGeneratorRequest::InternalSwap(CodeGeneratorRequest* other) { void CodeGeneratorResponse_File::InitAsDefaultInstance() { } +class CodeGeneratorResponse_File::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_name(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static void set_has_insertion_point(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } + static void set_has_content(HasBits* has_bits) { + (*has_bits)[0] |= 4u; + } +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CodeGeneratorResponse_File::kNameFieldNumber; const int CodeGeneratorResponse_File::kInsertionPointFieldNumber; @@ -1035,36 +1160,35 @@ const int CodeGeneratorResponse_File::kContentFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CodeGeneratorResponse_File::CodeGeneratorResponse_File() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse_File.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorResponse.File) } CodeGeneratorResponse_File::CodeGeneratorResponse_File(const CodeGeneratorResponse_File& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); + name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name_); } - insertion_point_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + insertion_point_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_insertion_point()) { - insertion_point_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.insertion_point_); + insertion_point_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.insertion_point_); } - content_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + content_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_content()) { - content_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.content_); + content_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.content_); } // @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.CodeGeneratorResponse.File) } void CodeGeneratorResponse_File::SharedCtor() { - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - insertion_point_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - content_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_CodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + insertion_point_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + content_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } CodeGeneratorResponse_File::~CodeGeneratorResponse_File() { @@ -1073,33 +1197,28 @@ CodeGeneratorResponse_File::~CodeGeneratorResponse_File() { } void CodeGeneratorResponse_File::SharedDtor() { - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - insertion_point_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - content_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + insertion_point_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + content_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void CodeGeneratorResponse_File::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* CodeGeneratorResponse_File::descriptor() { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const CodeGeneratorResponse_File& CodeGeneratorResponse_File::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse_File.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_CodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base); return *internal_default_instance(); } void CodeGeneratorResponse_File::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.compiler.CodeGeneratorResponse.File) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 7u) { + if (cached_has_bits & 0x00000007u) { if (cached_has_bits & 0x00000001u) { name_.ClearNonDefaultToEmptyNoArena(); } @@ -1114,25 +1233,75 @@ void CodeGeneratorResponse_File::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* CodeGeneratorResponse_File::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional string name = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_name(), ptr, ctx, "google.protobuf.compiler.CodeGeneratorResponse.File.name"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string insertion_point = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_insertion_point(), ptr, ctx, "google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string content = 15; + case 15: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 122)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_content(), ptr, ctx, "google.protobuf.compiler.CodeGeneratorResponse.File.content"); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CodeGeneratorResponse_File::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorResponse.File) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional string name = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.compiler.CodeGeneratorResponse.File.name"); } else { goto handle_unusual; @@ -1142,13 +1311,12 @@ bool CodeGeneratorResponse_File::MergePartialFromCodedStream( // optional string insertion_point = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_insertion_point())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->insertion_point().data(), static_cast(this->insertion_point().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point"); } else { goto handle_unusual; @@ -1158,13 +1326,12 @@ bool CodeGeneratorResponse_File::MergePartialFromCodedStream( // optional string content = 15; case 15: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(122u /* 122 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (122 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_content())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->content().data(), static_cast(this->content().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.compiler.CodeGeneratorResponse.File.content"); } else { goto handle_unusual; @@ -1177,7 +1344,7 @@ bool CodeGeneratorResponse_File::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -1191,94 +1358,94 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void CodeGeneratorResponse_File::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.compiler.CodeGeneratorResponse.File) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.compiler.CodeGeneratorResponse.File.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // optional string insertion_point = 2; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->insertion_point().data(), static_cast(this->insertion_point().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->insertion_point(), output); } // optional string content = 15; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->content().data(), static_cast(this->content().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.compiler.CodeGeneratorResponse.File.content"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 15, this->content(), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.compiler.CodeGeneratorResponse.File) } -::google::protobuf::uint8* CodeGeneratorResponse_File::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* CodeGeneratorResponse_File::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.compiler.CodeGeneratorResponse.File) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.compiler.CodeGeneratorResponse.File.name"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // optional string insertion_point = 2; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->insertion_point().data(), static_cast(this->insertion_point().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 2, this->insertion_point(), target); } // optional string content = 15; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->content().data(), static_cast(this->content().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.compiler.CodeGeneratorResponse.File.content"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 15, this->content(), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.compiler.CodeGeneratorResponse.File) @@ -1291,46 +1458,51 @@ size_t CodeGeneratorResponse_File::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } - if (_has_bits_[0 / 32] & 7u) { + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x00000007u) { // optional string name = 1; - if (has_name()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->name()); } // optional string insertion_point = 2; - if (has_insertion_point()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->insertion_point()); } // optional string content = 15; - if (has_content()) { + if (cached_has_bits & 0x00000004u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->content()); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void CodeGeneratorResponse_File::MergeFrom(const ::google::protobuf::Message& from) { +void CodeGeneratorResponse_File::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse.File) GOOGLE_DCHECK_NE(&from, this); const CodeGeneratorResponse_File* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.compiler.CodeGeneratorResponse.File) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.compiler.CodeGeneratorResponse.File) MergeFrom(*source); @@ -1341,27 +1513,27 @@ void CodeGeneratorResponse_File::MergeFrom(const CodeGeneratorResponse_File& fro // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse.File) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 7u) { + if (cached_has_bits & 0x00000007u) { if (cached_has_bits & 0x00000001u) { - set_has_name(); - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); + _has_bits_[0] |= 0x00000001u; + name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name_); } if (cached_has_bits & 0x00000002u) { - set_has_insertion_point(); - insertion_point_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.insertion_point_); + _has_bits_[0] |= 0x00000002u; + insertion_point_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.insertion_point_); } if (cached_has_bits & 0x00000004u) { - set_has_content(); - content_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.content_); + _has_bits_[0] |= 0x00000004u; + content_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.content_); } } } -void CodeGeneratorResponse_File::CopyFrom(const ::google::protobuf::Message& from) { +void CodeGeneratorResponse_File::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.compiler.CodeGeneratorResponse.File) if (&from == this) return; Clear(); @@ -1385,19 +1557,18 @@ void CodeGeneratorResponse_File::Swap(CodeGeneratorResponse_File* other) { } void CodeGeneratorResponse_File::InternalSwap(CodeGeneratorResponse_File* other) { using std::swap; - name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - insertion_point_.Swap(&other->insertion_point_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - content_.Swap(&other->content_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); + name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + insertion_point_.Swap(&other->insertion_point_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + content_.Swap(&other->content_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); } -::google::protobuf::Metadata CodeGeneratorResponse_File::GetMetadata() const { - protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata CodeGeneratorResponse_File::GetMetadata() const { + return GetMetadataStatic(); } @@ -1405,33 +1576,40 @@ void CodeGeneratorResponse_File::InternalSwap(CodeGeneratorResponse_File* other) void CodeGeneratorResponse::InitAsDefaultInstance() { } +class CodeGeneratorResponse::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_error(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CodeGeneratorResponse::kErrorFieldNumber; const int CodeGeneratorResponse::kFileFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CodeGeneratorResponse::CodeGeneratorResponse() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorResponse) } CodeGeneratorResponse::CodeGeneratorResponse(const CodeGeneratorResponse& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), file_(from.file_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - error_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + error_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_error()) { - error_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.error_); + error_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.error_); } // @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.CodeGeneratorResponse) } void CodeGeneratorResponse::SharedCtor() { - error_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_CodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base); + error_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } CodeGeneratorResponse::~CodeGeneratorResponse() { @@ -1440,26 +1618,21 @@ CodeGeneratorResponse::~CodeGeneratorResponse() { } void CodeGeneratorResponse::SharedDtor() { - error_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + error_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void CodeGeneratorResponse::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* CodeGeneratorResponse::descriptor() { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const CodeGeneratorResponse& CodeGeneratorResponse::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_CodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base); return *internal_default_instance(); } void CodeGeneratorResponse::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.compiler.CodeGeneratorResponse) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -1472,25 +1645,73 @@ void CodeGeneratorResponse::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* CodeGeneratorResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional string error = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_error(), ptr, ctx, "google.protobuf.compiler.CodeGeneratorResponse.error"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15; + case 15: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 122)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_file(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 122); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CodeGeneratorResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorResponse) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional string error = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_error())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->error().data(), static_cast(this->error().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.compiler.CodeGeneratorResponse.error"); } else { goto handle_unusual; @@ -1500,9 +1721,8 @@ bool CodeGeneratorResponse::MergePartialFromCodedStream( // repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15; case 15: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(122u /* 122 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (122 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_file())); } else { goto handle_unusual; @@ -1515,7 +1735,7 @@ bool CodeGeneratorResponse::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -1529,69 +1749,69 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void CodeGeneratorResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.compiler.CodeGeneratorResponse) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string error = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->error().data(), static_cast(this->error().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.compiler.CodeGeneratorResponse.error"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->error(), output); } // repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15; for (unsigned int i = 0, n = static_cast(this->file_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 15, this->file(static_cast(i)), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.compiler.CodeGeneratorResponse) } -::google::protobuf::uint8* CodeGeneratorResponse::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* CodeGeneratorResponse::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.compiler.CodeGeneratorResponse) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string error = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->error().data(), static_cast(this->error().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.compiler.CodeGeneratorResponse.error"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 1, this->error(), target); } // repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15; for (unsigned int i = 0, n = static_cast(this->file_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 15, this->file(static_cast(i)), deterministic, target); + 15, this->file(static_cast(i)), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.compiler.CodeGeneratorResponse) @@ -1604,41 +1824,46 @@ size_t CodeGeneratorResponse::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15; { unsigned int count = static_cast(this->file_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->file(static_cast(i))); } } // optional string error = 1; - if (has_error()) { + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->error()); } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void CodeGeneratorResponse::MergeFrom(const ::google::protobuf::Message& from) { +void CodeGeneratorResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse) GOOGLE_DCHECK_NE(&from, this); const CodeGeneratorResponse* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.compiler.CodeGeneratorResponse) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.compiler.CodeGeneratorResponse) MergeFrom(*source); @@ -1649,17 +1874,17 @@ void CodeGeneratorResponse::MergeFrom(const CodeGeneratorResponse& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; file_.MergeFrom(from.file_); if (from.has_error()) { - set_has_error(); - error_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.error_); + _has_bits_[0] |= 0x00000001u; + error_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.error_); } } -void CodeGeneratorResponse::CopyFrom(const ::google::protobuf::Message& from) { +void CodeGeneratorResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.compiler.CodeGeneratorResponse) if (&from == this) return; Clear(); @@ -1683,38 +1908,35 @@ void CodeGeneratorResponse::Swap(CodeGeneratorResponse* other) { } void CodeGeneratorResponse::InternalSwap(CodeGeneratorResponse* other) { using std::swap; - CastToBase(&file_)->InternalSwap(CastToBase(&other->file_)); - error_.Swap(&other->error_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); + CastToBase(&file_)->InternalSwap(CastToBase(&other->file_)); + error_.Swap(&other->error_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); } -::google::protobuf::Metadata CodeGeneratorResponse::GetMetadata() const { - protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata CodeGeneratorResponse::GetMetadata() const { + return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) } // namespace compiler -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::Version* Arena::CreateMaybeMessage< ::google::protobuf::compiler::Version >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::compiler::Version >(arena); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::compiler::Version* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::compiler::Version >(Arena* arena) { + return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::compiler::Version >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorRequest >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorRequest >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest >(Arena* arena) { + return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse_File >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorResponse_File >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File >(Arena* arena) { + return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorResponse >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse >(Arena* arena) { + return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse >(arena); } -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) +#include diff --git a/third_party/protobuf/src/google/protobuf/compiler/plugin.pb.h b/third_party/protobuf/src/google/protobuf/compiler/plugin.pb.h index 78d3bba3..9bcb1383 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/plugin.pb.h +++ b/third_party/protobuf/src/google/protobuf/compiler/plugin.pb.h @@ -1,24 +1,25 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/compiler/plugin.proto -#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto -#define PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto +#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto +#include #include -#include - -#if GOOGLE_PROTOBUF_VERSION < 3006001 +#include +#if PROTOBUF_VERSION < 3008000 #error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update +#error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3008000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please +#error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include @@ -26,81 +27,83 @@ #include #include #include +#include #include #include // IWYU pragma: export #include // IWYU pragma: export #include #include // @@protoc_insertion_point(includes) -#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto LIBPROTOC_EXPORT +#include +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fcompiler_2fplugin_2eproto PROTOC_EXPORT #ifdef major #undef major #endif #ifdef minor #undef minor #endif +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE -namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto { // Internal implementation detail -- do not use these members. -struct LIBPROTOC_EXPORT TableStruct { - static const ::google::protobuf::internal::ParseTableField entries[]; - static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; - static const ::google::protobuf::internal::ParseTable schema[4]; - static const ::google::protobuf::internal::FieldMetadata field_metadata[]; - static const ::google::protobuf::internal::SerializationTable serialization_table[]; - static const ::google::protobuf::uint32 offsets[]; +struct PROTOC_EXPORT TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto { + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[4] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; + static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; + static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; -void LIBPROTOC_EXPORT AddDescriptors(); -} // namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto -namespace google { -namespace protobuf { +extern PROTOC_EXPORT const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto; +PROTOBUF_NAMESPACE_OPEN namespace compiler { class CodeGeneratorRequest; class CodeGeneratorRequestDefaultTypeInternal; -LIBPROTOC_EXPORT extern CodeGeneratorRequestDefaultTypeInternal _CodeGeneratorRequest_default_instance_; +PROTOC_EXPORT extern CodeGeneratorRequestDefaultTypeInternal _CodeGeneratorRequest_default_instance_; class CodeGeneratorResponse; class CodeGeneratorResponseDefaultTypeInternal; -LIBPROTOC_EXPORT extern CodeGeneratorResponseDefaultTypeInternal _CodeGeneratorResponse_default_instance_; +PROTOC_EXPORT extern CodeGeneratorResponseDefaultTypeInternal _CodeGeneratorResponse_default_instance_; class CodeGeneratorResponse_File; class CodeGeneratorResponse_FileDefaultTypeInternal; -LIBPROTOC_EXPORT extern CodeGeneratorResponse_FileDefaultTypeInternal _CodeGeneratorResponse_File_default_instance_; +PROTOC_EXPORT extern CodeGeneratorResponse_FileDefaultTypeInternal _CodeGeneratorResponse_File_default_instance_; class Version; class VersionDefaultTypeInternal; -LIBPROTOC_EXPORT extern VersionDefaultTypeInternal _Version_default_instance_; +PROTOC_EXPORT extern VersionDefaultTypeInternal _Version_default_instance_; } // namespace compiler -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorRequest>(Arena*); -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse>(Arena*); -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse_File>(Arena*); -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::Version* Arena::CreateMaybeMessage<::google::protobuf::compiler::Version>(Arena*); -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOC_EXPORT PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage(Arena*); +template<> PROTOC_EXPORT PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage(Arena*); +template<> PROTOC_EXPORT PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage(Arena*); +template<> PROTOC_EXPORT PROTOBUF_NAMESPACE_ID::compiler::Version* Arena::CreateMaybeMessage(Arena*); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN namespace compiler { // =================================================================== -class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.Version) */ { +class PROTOC_EXPORT Version : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.Version) */ { public: Version(); virtual ~Version(); Version(const Version& from); - - inline Version& operator=(const Version& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 Version(Version&& from) noexcept : Version() { *this = ::std::move(from); } + inline Version& operator=(const Version& from) { + CopyFrom(from); + return *this; + } inline Version& operator=(Version&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -109,15 +112,23 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_ } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const Version& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -136,43 +147,58 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_ // implements Message ---------------------------------------------- inline Version* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - Version* New(::google::protobuf::Arena* arena) const final { + Version* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const Version& from); void MergeFrom(const Version& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Version* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.compiler.Version"; + } private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { + return nullptr; } inline void* MaybeArenaPtr() const { - return NULL; + return nullptr; } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto); + return ::descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -182,77 +208,67 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_ bool has_suffix() const; void clear_suffix(); static const int kSuffixFieldNumber = 4; - const ::std::string& suffix() const; - void set_suffix(const ::std::string& value); - #if LANG_CXX11 - void set_suffix(::std::string&& value); - #endif + const std::string& suffix() const; + void set_suffix(const std::string& value); + void set_suffix(std::string&& value); void set_suffix(const char* value); void set_suffix(const char* value, size_t size); - ::std::string* mutable_suffix(); - ::std::string* release_suffix(); - void set_allocated_suffix(::std::string* suffix); + std::string* mutable_suffix(); + std::string* release_suffix(); + void set_allocated_suffix(std::string* suffix); // optional int32 major = 1; bool has_major() const; void clear_major(); static const int kMajorFieldNumber = 1; - ::google::protobuf::int32 major() const; - void set_major(::google::protobuf::int32 value); + ::PROTOBUF_NAMESPACE_ID::int32 major() const; + void set_major(::PROTOBUF_NAMESPACE_ID::int32 value); // optional int32 minor = 2; bool has_minor() const; void clear_minor(); static const int kMinorFieldNumber = 2; - ::google::protobuf::int32 minor() const; - void set_minor(::google::protobuf::int32 value); + ::PROTOBUF_NAMESPACE_ID::int32 minor() const; + void set_minor(::PROTOBUF_NAMESPACE_ID::int32 value); // optional int32 patch = 3; bool has_patch() const; void clear_patch(); static const int kPatchFieldNumber = 3; - ::google::protobuf::int32 patch() const; - void set_patch(::google::protobuf::int32 value); + ::PROTOBUF_NAMESPACE_ID::int32 patch() const; + void set_patch(::PROTOBUF_NAMESPACE_ID::int32 value); // @@protoc_insertion_point(class_scope:google.protobuf.compiler.Version) private: - void set_has_major(); - void clear_has_major(); - void set_has_minor(); - void clear_has_minor(); - void set_has_patch(); - void clear_has_patch(); - void set_has_suffix(); - void clear_has_suffix(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::internal::ArenaStringPtr suffix_; - ::google::protobuf::int32 major_; - ::google::protobuf::int32 minor_; - ::google::protobuf::int32 patch_; - friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr suffix_; + ::PROTOBUF_NAMESPACE_ID::int32 major_; + ::PROTOBUF_NAMESPACE_ID::int32 minor_; + ::PROTOBUF_NAMESPACE_ID::int32 patch_; + friend struct ::TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorRequest) */ { +class PROTOC_EXPORT CodeGeneratorRequest : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorRequest) */ { public: CodeGeneratorRequest(); virtual ~CodeGeneratorRequest(); CodeGeneratorRequest(const CodeGeneratorRequest& from); - - inline CodeGeneratorRequest& operator=(const CodeGeneratorRequest& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 CodeGeneratorRequest(CodeGeneratorRequest&& from) noexcept : CodeGeneratorRequest() { *this = ::std::move(from); } + inline CodeGeneratorRequest& operator=(const CodeGeneratorRequest& from) { + CopyFrom(from); + return *this; + } inline CodeGeneratorRequest& operator=(CodeGeneratorRequest&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -261,15 +277,23 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const CodeGeneratorRequest& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -288,43 +312,58 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message // implements Message ---------------------------------------------- inline CodeGeneratorRequest* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - CodeGeneratorRequest* New(::google::protobuf::Arena* arena) const final { + CodeGeneratorRequest* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const CodeGeneratorRequest& from); void MergeFrom(const CodeGeneratorRequest& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CodeGeneratorRequest* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.compiler.CodeGeneratorRequest"; + } private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { + return nullptr; } inline void* MaybeArenaPtr() const { - return NULL; + return nullptr; } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto); + return ::descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -334,98 +373,85 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message int file_to_generate_size() const; void clear_file_to_generate(); static const int kFileToGenerateFieldNumber = 1; - const ::std::string& file_to_generate(int index) const; - ::std::string* mutable_file_to_generate(int index); - void set_file_to_generate(int index, const ::std::string& value); - #if LANG_CXX11 - void set_file_to_generate(int index, ::std::string&& value); - #endif + const std::string& file_to_generate(int index) const; + std::string* mutable_file_to_generate(int index); + void set_file_to_generate(int index, const std::string& value); + void set_file_to_generate(int index, std::string&& value); void set_file_to_generate(int index, const char* value); void set_file_to_generate(int index, const char* value, size_t size); - ::std::string* add_file_to_generate(); - void add_file_to_generate(const ::std::string& value); - #if LANG_CXX11 - void add_file_to_generate(::std::string&& value); - #endif + std::string* add_file_to_generate(); + void add_file_to_generate(const std::string& value); + void add_file_to_generate(std::string&& value); void add_file_to_generate(const char* value); void add_file_to_generate(const char* value, size_t size); - const ::google::protobuf::RepeatedPtrField< ::std::string>& file_to_generate() const; - ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_file_to_generate(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& file_to_generate() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* mutable_file_to_generate(); // repeated .google.protobuf.FileDescriptorProto proto_file = 15; int proto_file_size() const; void clear_proto_file(); static const int kProtoFileFieldNumber = 15; - ::google::protobuf::FileDescriptorProto* mutable_proto_file(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >* + PROTOBUF_NAMESPACE_ID::FileDescriptorProto* mutable_proto_file(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FileDescriptorProto >* mutable_proto_file(); - const ::google::protobuf::FileDescriptorProto& proto_file(int index) const; - ::google::protobuf::FileDescriptorProto* add_proto_file(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >& + const PROTOBUF_NAMESPACE_ID::FileDescriptorProto& proto_file(int index) const; + PROTOBUF_NAMESPACE_ID::FileDescriptorProto* add_proto_file(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FileDescriptorProto >& proto_file() const; // optional string parameter = 2; bool has_parameter() const; void clear_parameter(); static const int kParameterFieldNumber = 2; - const ::std::string& parameter() const; - void set_parameter(const ::std::string& value); - #if LANG_CXX11 - void set_parameter(::std::string&& value); - #endif + const std::string& parameter() const; + void set_parameter(const std::string& value); + void set_parameter(std::string&& value); void set_parameter(const char* value); void set_parameter(const char* value, size_t size); - ::std::string* mutable_parameter(); - ::std::string* release_parameter(); - void set_allocated_parameter(::std::string* parameter); + std::string* mutable_parameter(); + std::string* release_parameter(); + void set_allocated_parameter(std::string* parameter); // optional .google.protobuf.compiler.Version compiler_version = 3; bool has_compiler_version() const; void clear_compiler_version(); static const int kCompilerVersionFieldNumber = 3; - private: - const ::google::protobuf::compiler::Version& _internal_compiler_version() const; - public: - const ::google::protobuf::compiler::Version& compiler_version() const; - ::google::protobuf::compiler::Version* release_compiler_version(); - ::google::protobuf::compiler::Version* mutable_compiler_version(); - void set_allocated_compiler_version(::google::protobuf::compiler::Version* compiler_version); + const PROTOBUF_NAMESPACE_ID::compiler::Version& compiler_version() const; + PROTOBUF_NAMESPACE_ID::compiler::Version* release_compiler_version(); + PROTOBUF_NAMESPACE_ID::compiler::Version* mutable_compiler_version(); + void set_allocated_compiler_version(PROTOBUF_NAMESPACE_ID::compiler::Version* compiler_version); // @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorRequest) private: - void set_has_parameter(); - void clear_has_parameter(); - void set_has_compiler_version(); - void clear_has_compiler_version(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::std::string> file_to_generate_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto > proto_file_; - ::google::protobuf::internal::ArenaStringPtr parameter_; - ::google::protobuf::compiler::Version* compiler_version_; - friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField file_to_generate_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FileDescriptorProto > proto_file_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr parameter_; + PROTOBUF_NAMESPACE_ID::compiler::Version* compiler_version_; + friend struct ::TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse.File) */ { +class PROTOC_EXPORT CodeGeneratorResponse_File : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse.File) */ { public: CodeGeneratorResponse_File(); virtual ~CodeGeneratorResponse_File(); CodeGeneratorResponse_File(const CodeGeneratorResponse_File& from); - - inline CodeGeneratorResponse_File& operator=(const CodeGeneratorResponse_File& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 CodeGeneratorResponse_File(CodeGeneratorResponse_File&& from) noexcept : CodeGeneratorResponse_File() { *this = ::std::move(from); } + inline CodeGeneratorResponse_File& operator=(const CodeGeneratorResponse_File& from) { + CopyFrom(from); + return *this; + } inline CodeGeneratorResponse_File& operator=(CodeGeneratorResponse_File&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -434,15 +460,23 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const CodeGeneratorResponse_File& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -461,43 +495,58 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M // implements Message ---------------------------------------------- inline CodeGeneratorResponse_File* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - CodeGeneratorResponse_File* New(::google::protobuf::Arena* arena) const final { + CodeGeneratorResponse_File* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const CodeGeneratorResponse_File& from); void MergeFrom(const CodeGeneratorResponse_File& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CodeGeneratorResponse_File* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.compiler.CodeGeneratorResponse.File"; + } private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { + return nullptr; } inline void* MaybeArenaPtr() const { - return NULL; + return nullptr; } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto); + return ::descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -507,83 +556,71 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M bool has_name() const; void clear_name(); static const int kNameFieldNumber = 1; - const ::std::string& name() const; - void set_name(const ::std::string& value); - #if LANG_CXX11 - void set_name(::std::string&& value); - #endif + const std::string& name() const; + void set_name(const std::string& value); + void set_name(std::string&& value); void set_name(const char* value); void set_name(const char* value, size_t size); - ::std::string* mutable_name(); - ::std::string* release_name(); - void set_allocated_name(::std::string* name); + std::string* mutable_name(); + std::string* release_name(); + void set_allocated_name(std::string* name); // optional string insertion_point = 2; bool has_insertion_point() const; void clear_insertion_point(); static const int kInsertionPointFieldNumber = 2; - const ::std::string& insertion_point() const; - void set_insertion_point(const ::std::string& value); - #if LANG_CXX11 - void set_insertion_point(::std::string&& value); - #endif + const std::string& insertion_point() const; + void set_insertion_point(const std::string& value); + void set_insertion_point(std::string&& value); void set_insertion_point(const char* value); void set_insertion_point(const char* value, size_t size); - ::std::string* mutable_insertion_point(); - ::std::string* release_insertion_point(); - void set_allocated_insertion_point(::std::string* insertion_point); + std::string* mutable_insertion_point(); + std::string* release_insertion_point(); + void set_allocated_insertion_point(std::string* insertion_point); // optional string content = 15; bool has_content() const; void clear_content(); static const int kContentFieldNumber = 15; - const ::std::string& content() const; - void set_content(const ::std::string& value); - #if LANG_CXX11 - void set_content(::std::string&& value); - #endif + const std::string& content() const; + void set_content(const std::string& value); + void set_content(std::string&& value); void set_content(const char* value); void set_content(const char* value, size_t size); - ::std::string* mutable_content(); - ::std::string* release_content(); - void set_allocated_content(::std::string* content); + std::string* mutable_content(); + std::string* release_content(); + void set_allocated_content(std::string* content); // @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorResponse.File) private: - void set_has_name(); - void clear_has_name(); - void set_has_insertion_point(); - void clear_has_insertion_point(); - void set_has_content(); - void clear_has_content(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::internal::ArenaStringPtr name_; - ::google::protobuf::internal::ArenaStringPtr insertion_point_; - ::google::protobuf::internal::ArenaStringPtr content_; - friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr insertion_point_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr content_; + friend struct ::TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse) */ { +class PROTOC_EXPORT CodeGeneratorResponse : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse) */ { public: CodeGeneratorResponse(); virtual ~CodeGeneratorResponse(); CodeGeneratorResponse(const CodeGeneratorResponse& from); - - inline CodeGeneratorResponse& operator=(const CodeGeneratorResponse& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 CodeGeneratorResponse(CodeGeneratorResponse&& from) noexcept : CodeGeneratorResponse() { *this = ::std::move(from); } + inline CodeGeneratorResponse& operator=(const CodeGeneratorResponse& from) { + CopyFrom(from); + return *this; + } inline CodeGeneratorResponse& operator=(CodeGeneratorResponse&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -592,15 +629,23 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const CodeGeneratorResponse& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -619,43 +664,58 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag // implements Message ---------------------------------------------- inline CodeGeneratorResponse* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - CodeGeneratorResponse* New(::google::protobuf::Arena* arena) const final { + CodeGeneratorResponse* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const CodeGeneratorResponse& from); void MergeFrom(const CodeGeneratorResponse& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CodeGeneratorResponse* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.compiler.CodeGeneratorResponse"; + } private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { + return nullptr; } inline void* MaybeArenaPtr() const { - return NULL; + return nullptr; } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto); + return ::descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -667,40 +727,37 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag int file_size() const; void clear_file(); static const int kFileFieldNumber = 15; - ::google::protobuf::compiler::CodeGeneratorResponse_File* mutable_file(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File >* + PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* mutable_file(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File >* mutable_file(); - const ::google::protobuf::compiler::CodeGeneratorResponse_File& file(int index) const; - ::google::protobuf::compiler::CodeGeneratorResponse_File* add_file(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File >& + const PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File& file(int index) const; + PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* add_file(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File >& file() const; // optional string error = 1; bool has_error() const; void clear_error(); static const int kErrorFieldNumber = 1; - const ::std::string& error() const; - void set_error(const ::std::string& value); - #if LANG_CXX11 - void set_error(::std::string&& value); - #endif + const std::string& error() const; + void set_error(const std::string& value); + void set_error(std::string&& value); void set_error(const char* value); void set_error(const char* value, size_t size); - ::std::string* mutable_error(); - ::std::string* release_error(); - void set_allocated_error(::std::string* error); + std::string* mutable_error(); + std::string* release_error(); + void set_allocated_error(std::string* error); // @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorResponse) private: - void set_has_error(); - void clear_has_error(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File > file_; - ::google::protobuf::internal::ArenaStringPtr error_; - friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File > file_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr error_; + friend struct ::TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto; }; // =================================================================== @@ -717,22 +774,16 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag inline bool Version::has_major() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void Version::set_has_major() { - _has_bits_[0] |= 0x00000002u; -} -inline void Version::clear_has_major() { - _has_bits_[0] &= ~0x00000002u; -} inline void Version::clear_major() { major_ = 0; - clear_has_major(); + _has_bits_[0] &= ~0x00000002u; } -inline ::google::protobuf::int32 Version::major() const { +inline ::PROTOBUF_NAMESPACE_ID::int32 Version::major() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.major) return major_; } -inline void Version::set_major(::google::protobuf::int32 value) { - set_has_major(); +inline void Version::set_major(::PROTOBUF_NAMESPACE_ID::int32 value) { + _has_bits_[0] |= 0x00000002u; major_ = value; // @@protoc_insertion_point(field_set:google.protobuf.compiler.Version.major) } @@ -741,22 +792,16 @@ inline void Version::set_major(::google::protobuf::int32 value) { inline bool Version::has_minor() const { return (_has_bits_[0] & 0x00000004u) != 0; } -inline void Version::set_has_minor() { - _has_bits_[0] |= 0x00000004u; -} -inline void Version::clear_has_minor() { - _has_bits_[0] &= ~0x00000004u; -} inline void Version::clear_minor() { minor_ = 0; - clear_has_minor(); + _has_bits_[0] &= ~0x00000004u; } -inline ::google::protobuf::int32 Version::minor() const { +inline ::PROTOBUF_NAMESPACE_ID::int32 Version::minor() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.minor) return minor_; } -inline void Version::set_minor(::google::protobuf::int32 value) { - set_has_minor(); +inline void Version::set_minor(::PROTOBUF_NAMESPACE_ID::int32 value) { + _has_bits_[0] |= 0x00000004u; minor_ = value; // @@protoc_insertion_point(field_set:google.protobuf.compiler.Version.minor) } @@ -765,22 +810,16 @@ inline void Version::set_minor(::google::protobuf::int32 value) { inline bool Version::has_patch() const { return (_has_bits_[0] & 0x00000008u) != 0; } -inline void Version::set_has_patch() { - _has_bits_[0] |= 0x00000008u; -} -inline void Version::clear_has_patch() { - _has_bits_[0] &= ~0x00000008u; -} inline void Version::clear_patch() { patch_ = 0; - clear_has_patch(); + _has_bits_[0] &= ~0x00000008u; } -inline ::google::protobuf::int32 Version::patch() const { +inline ::PROTOBUF_NAMESPACE_ID::int32 Version::patch() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.patch) return patch_; } -inline void Version::set_patch(::google::protobuf::int32 value) { - set_has_patch(); +inline void Version::set_patch(::PROTOBUF_NAMESPACE_ID::int32 value) { + _has_bits_[0] |= 0x00000008u; patch_ = value; // @@protoc_insertion_point(field_set:google.protobuf.compiler.Version.patch) } @@ -789,65 +828,57 @@ inline void Version::set_patch(::google::protobuf::int32 value) { inline bool Version::has_suffix() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void Version::set_has_suffix() { - _has_bits_[0] |= 0x00000001u; -} -inline void Version::clear_has_suffix() { +inline void Version::clear_suffix() { + suffix_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); _has_bits_[0] &= ~0x00000001u; } -inline void Version::clear_suffix() { - suffix_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_suffix(); -} -inline const ::std::string& Version::suffix() const { +inline const std::string& Version::suffix() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.suffix) return suffix_.GetNoArena(); } -inline void Version::set_suffix(const ::std::string& value) { - set_has_suffix(); - suffix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +inline void Version::set_suffix(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + suffix_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.protobuf.compiler.Version.suffix) } -#if LANG_CXX11 -inline void Version::set_suffix(::std::string&& value) { - set_has_suffix(); +inline void Version::set_suffix(std::string&& value) { + _has_bits_[0] |= 0x00000001u; suffix_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.Version.suffix) } -#endif inline void Version::set_suffix(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_suffix(); - suffix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000001u; + suffix_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.Version.suffix) } inline void Version::set_suffix(const char* value, size_t size) { - set_has_suffix(); - suffix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + _has_bits_[0] |= 0x00000001u; + suffix_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.Version.suffix) } -inline ::std::string* Version::mutable_suffix() { - set_has_suffix(); +inline std::string* Version::mutable_suffix() { + _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.Version.suffix) - return suffix_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return suffix_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline ::std::string* Version::release_suffix() { +inline std::string* Version::release_suffix() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.Version.suffix) if (!has_suffix()) { - return NULL; + return nullptr; } - clear_has_suffix(); - return suffix_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + _has_bits_[0] &= ~0x00000001u; + return suffix_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline void Version::set_allocated_suffix(::std::string* suffix) { - if (suffix != NULL) { - set_has_suffix(); +inline void Version::set_allocated_suffix(std::string* suffix) { + if (suffix != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_suffix(); + _has_bits_[0] &= ~0x00000001u; } - suffix_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), suffix); + suffix_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), suffix); // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.Version.suffix) } @@ -862,26 +893,24 @@ inline int CodeGeneratorRequest::file_to_generate_size() const { inline void CodeGeneratorRequest::clear_file_to_generate() { file_to_generate_.Clear(); } -inline const ::std::string& CodeGeneratorRequest::file_to_generate(int index) const { +inline const std::string& CodeGeneratorRequest::file_to_generate(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) return file_to_generate_.Get(index); } -inline ::std::string* CodeGeneratorRequest::mutable_file_to_generate(int index) { +inline std::string* CodeGeneratorRequest::mutable_file_to_generate(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) return file_to_generate_.Mutable(index); } -inline void CodeGeneratorRequest::set_file_to_generate(int index, const ::std::string& value) { +inline void CodeGeneratorRequest::set_file_to_generate(int index, const std::string& value) { // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) file_to_generate_.Mutable(index)->assign(value); } -#if LANG_CXX11 -inline void CodeGeneratorRequest::set_file_to_generate(int index, ::std::string&& value) { +inline void CodeGeneratorRequest::set_file_to_generate(int index, std::string&& value) { // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) file_to_generate_.Mutable(index)->assign(std::move(value)); } -#endif inline void CodeGeneratorRequest::set_file_to_generate(int index, const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); file_to_generate_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } @@ -890,22 +919,20 @@ inline void CodeGeneratorRequest::set_file_to_generate(int index, const char* va reinterpret_cast(value), size); // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } -inline ::std::string* CodeGeneratorRequest::add_file_to_generate() { +inline std::string* CodeGeneratorRequest::add_file_to_generate() { // @@protoc_insertion_point(field_add_mutable:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) return file_to_generate_.Add(); } -inline void CodeGeneratorRequest::add_file_to_generate(const ::std::string& value) { +inline void CodeGeneratorRequest::add_file_to_generate(const std::string& value) { file_to_generate_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } -#if LANG_CXX11 -inline void CodeGeneratorRequest::add_file_to_generate(::std::string&& value) { +inline void CodeGeneratorRequest::add_file_to_generate(std::string&& value) { file_to_generate_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } -#endif inline void CodeGeneratorRequest::add_file_to_generate(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); file_to_generate_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } @@ -913,12 +940,12 @@ inline void CodeGeneratorRequest::add_file_to_generate(const char* value, size_t file_to_generate_.Add()->assign(reinterpret_cast(value), size); // @@protoc_insertion_point(field_add_pointer:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } -inline const ::google::protobuf::RepeatedPtrField< ::std::string>& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& CodeGeneratorRequest::file_to_generate() const { // @@protoc_insertion_point(field_list:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) return file_to_generate_; } -inline ::google::protobuf::RepeatedPtrField< ::std::string>* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* CodeGeneratorRequest::mutable_file_to_generate() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) return &file_to_generate_; @@ -928,65 +955,57 @@ CodeGeneratorRequest::mutable_file_to_generate() { inline bool CodeGeneratorRequest::has_parameter() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void CodeGeneratorRequest::set_has_parameter() { - _has_bits_[0] |= 0x00000001u; -} -inline void CodeGeneratorRequest::clear_has_parameter() { +inline void CodeGeneratorRequest::clear_parameter() { + parameter_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); _has_bits_[0] &= ~0x00000001u; } -inline void CodeGeneratorRequest::clear_parameter() { - parameter_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_parameter(); -} -inline const ::std::string& CodeGeneratorRequest::parameter() const { +inline const std::string& CodeGeneratorRequest::parameter() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.parameter) return parameter_.GetNoArena(); } -inline void CodeGeneratorRequest::set_parameter(const ::std::string& value) { - set_has_parameter(); - parameter_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +inline void CodeGeneratorRequest::set_parameter(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + parameter_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorRequest.parameter) } -#if LANG_CXX11 -inline void CodeGeneratorRequest::set_parameter(::std::string&& value) { - set_has_parameter(); +inline void CodeGeneratorRequest::set_parameter(std::string&& value) { + _has_bits_[0] |= 0x00000001u; parameter_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorRequest.parameter) } -#endif inline void CodeGeneratorRequest::set_parameter(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_parameter(); - parameter_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000001u; + parameter_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorRequest.parameter) } inline void CodeGeneratorRequest::set_parameter(const char* value, size_t size) { - set_has_parameter(); - parameter_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + _has_bits_[0] |= 0x00000001u; + parameter_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorRequest.parameter) } -inline ::std::string* CodeGeneratorRequest::mutable_parameter() { - set_has_parameter(); +inline std::string* CodeGeneratorRequest::mutable_parameter() { + _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.parameter) - return parameter_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return parameter_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline ::std::string* CodeGeneratorRequest::release_parameter() { +inline std::string* CodeGeneratorRequest::release_parameter() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorRequest.parameter) if (!has_parameter()) { - return NULL; + return nullptr; } - clear_has_parameter(); - return parameter_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + _has_bits_[0] &= ~0x00000001u; + return parameter_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline void CodeGeneratorRequest::set_allocated_parameter(::std::string* parameter) { - if (parameter != NULL) { - set_has_parameter(); +inline void CodeGeneratorRequest::set_allocated_parameter(std::string* parameter) { + if (parameter != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_parameter(); + _has_bits_[0] &= ~0x00000001u; } - parameter_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), parameter); + parameter_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), parameter); // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorRequest.parameter) } @@ -994,24 +1013,24 @@ inline void CodeGeneratorRequest::set_allocated_parameter(::std::string* paramet inline int CodeGeneratorRequest::proto_file_size() const { return proto_file_.size(); } -inline ::google::protobuf::FileDescriptorProto* CodeGeneratorRequest::mutable_proto_file(int index) { +inline PROTOBUF_NAMESPACE_ID::FileDescriptorProto* CodeGeneratorRequest::mutable_proto_file(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.proto_file) return proto_file_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FileDescriptorProto >* CodeGeneratorRequest::mutable_proto_file() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.compiler.CodeGeneratorRequest.proto_file) return &proto_file_; } -inline const ::google::protobuf::FileDescriptorProto& CodeGeneratorRequest::proto_file(int index) const { +inline const PROTOBUF_NAMESPACE_ID::FileDescriptorProto& CodeGeneratorRequest::proto_file(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.proto_file) return proto_file_.Get(index); } -inline ::google::protobuf::FileDescriptorProto* CodeGeneratorRequest::add_proto_file() { +inline PROTOBUF_NAMESPACE_ID::FileDescriptorProto* CodeGeneratorRequest::add_proto_file() { // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorRequest.proto_file) return proto_file_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FileDescriptorProto >& CodeGeneratorRequest::proto_file() const { // @@protoc_insertion_point(field_list:google.protobuf.compiler.CodeGeneratorRequest.proto_file) return proto_file_; @@ -1021,55 +1040,46 @@ CodeGeneratorRequest::proto_file() const { inline bool CodeGeneratorRequest::has_compiler_version() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void CodeGeneratorRequest::set_has_compiler_version() { - _has_bits_[0] |= 0x00000002u; -} -inline void CodeGeneratorRequest::clear_has_compiler_version() { +inline void CodeGeneratorRequest::clear_compiler_version() { + if (compiler_version_ != nullptr) compiler_version_->Clear(); _has_bits_[0] &= ~0x00000002u; } -inline void CodeGeneratorRequest::clear_compiler_version() { - if (compiler_version_ != NULL) compiler_version_->Clear(); - clear_has_compiler_version(); -} -inline const ::google::protobuf::compiler::Version& CodeGeneratorRequest::_internal_compiler_version() const { - return *compiler_version_; -} -inline const ::google::protobuf::compiler::Version& CodeGeneratorRequest::compiler_version() const { - const ::google::protobuf::compiler::Version* p = compiler_version_; +inline const PROTOBUF_NAMESPACE_ID::compiler::Version& CodeGeneratorRequest::compiler_version() const { + const PROTOBUF_NAMESPACE_ID::compiler::Version* p = compiler_version_; // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.compiler_version) - return p != NULL ? *p : *reinterpret_cast( - &::google::protobuf::compiler::_Version_default_instance_); + return p != nullptr ? *p : *reinterpret_cast( + &PROTOBUF_NAMESPACE_ID::compiler::_Version_default_instance_); } -inline ::google::protobuf::compiler::Version* CodeGeneratorRequest::release_compiler_version() { +inline PROTOBUF_NAMESPACE_ID::compiler::Version* CodeGeneratorRequest::release_compiler_version() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorRequest.compiler_version) - clear_has_compiler_version(); - ::google::protobuf::compiler::Version* temp = compiler_version_; - compiler_version_ = NULL; + _has_bits_[0] &= ~0x00000002u; + PROTOBUF_NAMESPACE_ID::compiler::Version* temp = compiler_version_; + compiler_version_ = nullptr; return temp; } -inline ::google::protobuf::compiler::Version* CodeGeneratorRequest::mutable_compiler_version() { - set_has_compiler_version(); - if (compiler_version_ == NULL) { - auto* p = CreateMaybeMessage<::google::protobuf::compiler::Version>(GetArenaNoVirtual()); +inline PROTOBUF_NAMESPACE_ID::compiler::Version* CodeGeneratorRequest::mutable_compiler_version() { + _has_bits_[0] |= 0x00000002u; + if (compiler_version_ == nullptr) { + auto* p = CreateMaybeMessage(GetArenaNoVirtual()); compiler_version_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.compiler_version) return compiler_version_; } -inline void CodeGeneratorRequest::set_allocated_compiler_version(::google::protobuf::compiler::Version* compiler_version) { - ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); - if (message_arena == NULL) { +inline void CodeGeneratorRequest::set_allocated_compiler_version(PROTOBUF_NAMESPACE_ID::compiler::Version* compiler_version) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); + if (message_arena == nullptr) { delete compiler_version_; } if (compiler_version) { - ::google::protobuf::Arena* submessage_arena = NULL; + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { - compiler_version = ::google::protobuf::internal::GetOwnedMessage( + compiler_version = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, compiler_version, submessage_arena); } - set_has_compiler_version(); + _has_bits_[0] |= 0x00000002u; } else { - clear_has_compiler_version(); + _has_bits_[0] &= ~0x00000002u; } compiler_version_ = compiler_version; // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorRequest.compiler_version) @@ -1083,65 +1093,57 @@ inline void CodeGeneratorRequest::set_allocated_compiler_version(::google::proto inline bool CodeGeneratorResponse_File::has_name() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void CodeGeneratorResponse_File::set_has_name() { - _has_bits_[0] |= 0x00000001u; -} -inline void CodeGeneratorResponse_File::clear_has_name() { +inline void CodeGeneratorResponse_File::clear_name() { + name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); _has_bits_[0] &= ~0x00000001u; } -inline void CodeGeneratorResponse_File::clear_name() { - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_name(); -} -inline const ::std::string& CodeGeneratorResponse_File::name() const { +inline const std::string& CodeGeneratorResponse_File::name() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.name) return name_.GetNoArena(); } -inline void CodeGeneratorResponse_File::set_name(const ::std::string& value) { - set_has_name(); - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +inline void CodeGeneratorResponse_File::set_name(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.name) } -#if LANG_CXX11 -inline void CodeGeneratorResponse_File::set_name(::std::string&& value) { - set_has_name(); +inline void CodeGeneratorResponse_File::set_name(std::string&& value) { + _has_bits_[0] |= 0x00000001u; name_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.File.name) } -#endif inline void CodeGeneratorResponse_File::set_name(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_name(); - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000001u; + name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.name) } inline void CodeGeneratorResponse_File::set_name(const char* value, size_t size) { - set_has_name(); - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + _has_bits_[0] |= 0x00000001u; + name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.File.name) } -inline ::std::string* CodeGeneratorResponse_File::mutable_name() { - set_has_name(); +inline std::string* CodeGeneratorResponse_File::mutable_name() { + _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.File.name) - return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return name_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline ::std::string* CodeGeneratorResponse_File::release_name() { +inline std::string* CodeGeneratorResponse_File::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.name) if (!has_name()) { - return NULL; + return nullptr; } - clear_has_name(); - return name_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + _has_bits_[0] &= ~0x00000001u; + return name_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline void CodeGeneratorResponse_File::set_allocated_name(::std::string* name) { - if (name != NULL) { - set_has_name(); +inline void CodeGeneratorResponse_File::set_allocated_name(std::string* name) { + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name); + name_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name); // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.name) } @@ -1149,65 +1151,57 @@ inline void CodeGeneratorResponse_File::set_allocated_name(::std::string* name) inline bool CodeGeneratorResponse_File::has_insertion_point() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void CodeGeneratorResponse_File::set_has_insertion_point() { - _has_bits_[0] |= 0x00000002u; -} -inline void CodeGeneratorResponse_File::clear_has_insertion_point() { +inline void CodeGeneratorResponse_File::clear_insertion_point() { + insertion_point_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); _has_bits_[0] &= ~0x00000002u; } -inline void CodeGeneratorResponse_File::clear_insertion_point() { - insertion_point_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_insertion_point(); -} -inline const ::std::string& CodeGeneratorResponse_File::insertion_point() const { +inline const std::string& CodeGeneratorResponse_File::insertion_point() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) return insertion_point_.GetNoArena(); } -inline void CodeGeneratorResponse_File::set_insertion_point(const ::std::string& value) { - set_has_insertion_point(); - insertion_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +inline void CodeGeneratorResponse_File::set_insertion_point(const std::string& value) { + _has_bits_[0] |= 0x00000002u; + insertion_point_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) } -#if LANG_CXX11 -inline void CodeGeneratorResponse_File::set_insertion_point(::std::string&& value) { - set_has_insertion_point(); +inline void CodeGeneratorResponse_File::set_insertion_point(std::string&& value) { + _has_bits_[0] |= 0x00000002u; insertion_point_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) } -#endif inline void CodeGeneratorResponse_File::set_insertion_point(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_insertion_point(); - insertion_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000002u; + insertion_point_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) } inline void CodeGeneratorResponse_File::set_insertion_point(const char* value, size_t size) { - set_has_insertion_point(); - insertion_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + _has_bits_[0] |= 0x00000002u; + insertion_point_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) } -inline ::std::string* CodeGeneratorResponse_File::mutable_insertion_point() { - set_has_insertion_point(); +inline std::string* CodeGeneratorResponse_File::mutable_insertion_point() { + _has_bits_[0] |= 0x00000002u; // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) - return insertion_point_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return insertion_point_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline ::std::string* CodeGeneratorResponse_File::release_insertion_point() { +inline std::string* CodeGeneratorResponse_File::release_insertion_point() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) if (!has_insertion_point()) { - return NULL; + return nullptr; } - clear_has_insertion_point(); - return insertion_point_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + _has_bits_[0] &= ~0x00000002u; + return insertion_point_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline void CodeGeneratorResponse_File::set_allocated_insertion_point(::std::string* insertion_point) { - if (insertion_point != NULL) { - set_has_insertion_point(); +inline void CodeGeneratorResponse_File::set_allocated_insertion_point(std::string* insertion_point) { + if (insertion_point != nullptr) { + _has_bits_[0] |= 0x00000002u; } else { - clear_has_insertion_point(); + _has_bits_[0] &= ~0x00000002u; } - insertion_point_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), insertion_point); + insertion_point_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), insertion_point); // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) } @@ -1215,65 +1209,57 @@ inline void CodeGeneratorResponse_File::set_allocated_insertion_point(::std::str inline bool CodeGeneratorResponse_File::has_content() const { return (_has_bits_[0] & 0x00000004u) != 0; } -inline void CodeGeneratorResponse_File::set_has_content() { - _has_bits_[0] |= 0x00000004u; -} -inline void CodeGeneratorResponse_File::clear_has_content() { +inline void CodeGeneratorResponse_File::clear_content() { + content_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); _has_bits_[0] &= ~0x00000004u; } -inline void CodeGeneratorResponse_File::clear_content() { - content_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_content(); -} -inline const ::std::string& CodeGeneratorResponse_File::content() const { +inline const std::string& CodeGeneratorResponse_File::content() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.content) return content_.GetNoArena(); } -inline void CodeGeneratorResponse_File::set_content(const ::std::string& value) { - set_has_content(); - content_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +inline void CodeGeneratorResponse_File::set_content(const std::string& value) { + _has_bits_[0] |= 0x00000004u; + content_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.content) } -#if LANG_CXX11 -inline void CodeGeneratorResponse_File::set_content(::std::string&& value) { - set_has_content(); +inline void CodeGeneratorResponse_File::set_content(std::string&& value) { + _has_bits_[0] |= 0x00000004u; content_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.File.content) } -#endif inline void CodeGeneratorResponse_File::set_content(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_content(); - content_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000004u; + content_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.content) } inline void CodeGeneratorResponse_File::set_content(const char* value, size_t size) { - set_has_content(); - content_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + _has_bits_[0] |= 0x00000004u; + content_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.File.content) } -inline ::std::string* CodeGeneratorResponse_File::mutable_content() { - set_has_content(); +inline std::string* CodeGeneratorResponse_File::mutable_content() { + _has_bits_[0] |= 0x00000004u; // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.File.content) - return content_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return content_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline ::std::string* CodeGeneratorResponse_File::release_content() { +inline std::string* CodeGeneratorResponse_File::release_content() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.content) if (!has_content()) { - return NULL; + return nullptr; } - clear_has_content(); - return content_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + _has_bits_[0] &= ~0x00000004u; + return content_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline void CodeGeneratorResponse_File::set_allocated_content(::std::string* content) { - if (content != NULL) { - set_has_content(); +inline void CodeGeneratorResponse_File::set_allocated_content(std::string* content) { + if (content != nullptr) { + _has_bits_[0] |= 0x00000004u; } else { - clear_has_content(); + _has_bits_[0] &= ~0x00000004u; } - content_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), content); + content_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), content); // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.content) } @@ -1285,65 +1271,57 @@ inline void CodeGeneratorResponse_File::set_allocated_content(::std::string* con inline bool CodeGeneratorResponse::has_error() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void CodeGeneratorResponse::set_has_error() { - _has_bits_[0] |= 0x00000001u; -} -inline void CodeGeneratorResponse::clear_has_error() { +inline void CodeGeneratorResponse::clear_error() { + error_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); _has_bits_[0] &= ~0x00000001u; } -inline void CodeGeneratorResponse::clear_error() { - error_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_error(); -} -inline const ::std::string& CodeGeneratorResponse::error() const { +inline const std::string& CodeGeneratorResponse::error() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.error) return error_.GetNoArena(); } -inline void CodeGeneratorResponse::set_error(const ::std::string& value) { - set_has_error(); - error_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +inline void CodeGeneratorResponse::set_error(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + error_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.error) } -#if LANG_CXX11 -inline void CodeGeneratorResponse::set_error(::std::string&& value) { - set_has_error(); +inline void CodeGeneratorResponse::set_error(std::string&& value) { + _has_bits_[0] |= 0x00000001u; error_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.error) } -#endif inline void CodeGeneratorResponse::set_error(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_error(); - error_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000001u; + error_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.error) } inline void CodeGeneratorResponse::set_error(const char* value, size_t size) { - set_has_error(); - error_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + _has_bits_[0] |= 0x00000001u; + error_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.error) } -inline ::std::string* CodeGeneratorResponse::mutable_error() { - set_has_error(); +inline std::string* CodeGeneratorResponse::mutable_error() { + _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.error) - return error_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return error_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline ::std::string* CodeGeneratorResponse::release_error() { +inline std::string* CodeGeneratorResponse::release_error() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.error) if (!has_error()) { - return NULL; + return nullptr; } - clear_has_error(); - return error_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + _has_bits_[0] &= ~0x00000001u; + return error_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline void CodeGeneratorResponse::set_allocated_error(::std::string* error) { - if (error != NULL) { - set_has_error(); +inline void CodeGeneratorResponse::set_allocated_error(std::string* error) { + if (error != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_error(); + _has_bits_[0] &= ~0x00000001u; } - error_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), error); + error_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), error); // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.error) } @@ -1354,24 +1332,24 @@ inline int CodeGeneratorResponse::file_size() const { inline void CodeGeneratorResponse::clear_file() { file_.Clear(); } -inline ::google::protobuf::compiler::CodeGeneratorResponse_File* CodeGeneratorResponse::mutable_file(int index) { +inline PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* CodeGeneratorResponse::mutable_file(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.file) return file_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File >* CodeGeneratorResponse::mutable_file() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.compiler.CodeGeneratorResponse.file) return &file_; } -inline const ::google::protobuf::compiler::CodeGeneratorResponse_File& CodeGeneratorResponse::file(int index) const { +inline const PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File& CodeGeneratorResponse::file(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.file) return file_.Get(index); } -inline ::google::protobuf::compiler::CodeGeneratorResponse_File* CodeGeneratorResponse::add_file() { +inline PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* CodeGeneratorResponse::add_file() { // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorResponse.file) return file_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File >& CodeGeneratorResponse::file() const { // @@protoc_insertion_point(field_list:google.protobuf.compiler.CodeGeneratorResponse.file) return file_; @@ -1390,9 +1368,9 @@ CodeGeneratorResponse::file() const { // @@protoc_insertion_point(namespace_scope) } // namespace compiler -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto diff --git a/third_party/protobuf/src/google/protobuf/compiler/plugin.proto b/third_party/protobuf/src/google/protobuf/compiler/plugin.proto index 5b557452..665e5a72 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/plugin.proto +++ b/third_party/protobuf/src/google/protobuf/compiler/plugin.proto @@ -45,6 +45,7 @@ // flag "--${NAME}_out" is passed to protoc. syntax = "proto2"; + package google.protobuf.compiler; option java_package = "com.google.protobuf.compiler"; option java_outer_classname = "PluginProtos"; diff --git a/third_party/protobuf/src/google/protobuf/compiler/python/python_generator.cc b/third_party/protobuf/src/google/protobuf/compiler/python/python_generator.cc index 01f28b37..cf5b7f65 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/python/python_generator.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/python/python_generator.cc @@ -45,7 +45,6 @@ // directly. #include -#include #include #include #include @@ -66,6 +65,7 @@ #include + namespace google { namespace protobuf { namespace compiler { @@ -73,11 +73,6 @@ namespace python { namespace { -// Reimplemented here because we can't bring in -// absl/strings/string_view_utils.h because it needs C++11. -bool StrStartsWith(StringPiece sp, StringPiece x) { - return sp.size() >= x.size() && sp.substr(0, x.size()) == x; -} bool StrEndsWith(StringPiece sp, StringPiece x) { return sp.size() >= x.size() && sp.substr(sp.size() - x.size()) == x; } @@ -85,28 +80,26 @@ bool StrEndsWith(StringPiece sp, StringPiece x) { // Returns a copy of |filename| with any trailing ".protodevel" or ".proto // suffix stripped. // TODO(robinson): Unify with copy in compiler/cpp/internal/helpers.cc. -string StripProto(const string& filename) { +std::string StripProto(const std::string& filename) { const char* suffix = StrEndsWith(filename, ".protodevel") ? ".protodevel" : ".proto"; return StripSuffixString(filename, suffix); } - // Returns the Python module name expected for a given .proto filename. -string ModuleName(const string& filename) { - string basename = StripProto(filename); +std::string ModuleName(const std::string& filename) { + std::string basename = StripProto(filename); ReplaceCharacters(&basename, "-", '_'); ReplaceCharacters(&basename, "/", '.'); return basename + "_pb2"; } - // Returns the alias we assign to the module of the given .proto filename // when importing. See testPackageInitializationImport in -// google/protobuf/python/reflection_test.py +// net/proto2/python/internal/reflection_test.py // to see why we need the alias. -string ModuleAlias(const string& filename) { - string module_name = ModuleName(filename); +std::string ModuleAlias(const std::string& filename) { + std::string module_name = ModuleName(filename); // We can't have dots in the module name, so we replace each with _dot_. // But that could lead to a collision between a.b and a_dot_b, so we also // duplicate each underscore. @@ -121,13 +114,13 @@ const char* const kKeywords[] = { "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", - "return", "try", "while", "with", "yield", + "return", "try", "while", "with", "yield", "print", }; const char* const* kKeywordsEnd = kKeywords + (sizeof(kKeywords) / sizeof(kKeywords[0])); -bool ContainsPythonKeyword(const string& module_name) { - std::vector tokens = Split(module_name, "."); +bool ContainsPythonKeyword(const std::string& module_name) { + std::vector tokens = Split(module_name, "."); for (int i = 0; i < tokens.size(); ++i) { if (std::find(kKeywords, kKeywordsEnd, tokens[i]) != kKeywordsEnd) { return true; @@ -136,51 +129,66 @@ bool ContainsPythonKeyword(const string& module_name) { return false; } +inline bool IsPythonKeyword(const string& name) { + return (std::find(kKeywords, kKeywordsEnd, name) != kKeywordsEnd); +} + +std::string ResolveKeyword(const std::string& name) { + if (IsPythonKeyword(name)) { + return "globals()['" + name + "']"; + } + return name; +} // Returns the name of all containing types for descriptor, // in order from outermost to innermost, followed by descriptor's // own name. Each name is separated by |separator|. template -string NamePrefixedWithNestedTypes(const DescriptorT& descriptor, - const string& separator) { - string name = descriptor.name(); - for (const Descriptor* current = descriptor.containing_type(); - current != NULL; current = current->containing_type()) { - name = current->name() + separator + name; +std::string NamePrefixedWithNestedTypes(const DescriptorT& descriptor, + const std::string& separator) { + std::string name = descriptor.name(); + const Descriptor* parent = descriptor.containing_type(); + if (parent != nullptr) { + std::string prefix = NamePrefixedWithNestedTypes(*parent, separator); + if (separator == "." && IsPythonKeyword(name)) { + return "getattr(" + prefix + ", '" + name + "')"; + } else { + return prefix + separator + name; + } + } + if (separator == ".") { + name = ResolveKeyword(name); } return name; } - // Name of the class attribute where we store the Python // descriptor.Descriptor instance for the generated class. // Must stay consistent with the _DESCRIPTOR_KEY constant // in proto2/public/reflection.py. const char kDescriptorKey[] = "DESCRIPTOR"; - // Does the file have top-level enums? -inline bool HasTopLevelEnums(const FileDescriptor *file) { +inline bool HasTopLevelEnums(const FileDescriptor* file) { return file->enum_type_count() > 0; } - // Should we generate generic services for this file? -inline bool HasGenericServices(const FileDescriptor *file) { - return file->service_count() > 0 && - file->options().py_generic_services(); +inline bool HasGenericServices(const FileDescriptor* file) { + return file->service_count() > 0 && file->options().py_generic_services(); } - // Prints the common boilerplate needed at the top of every .py // file output by this generator. -void PrintTopBoilerplate( - io::Printer* printer, const FileDescriptor* file, bool descriptor_proto) { +void PrintTopBoilerplate(io::Printer* printer, const FileDescriptor* file, + bool descriptor_proto) { // TODO(robinson): Allow parameterization of Python version? printer->Print( + "# -*- coding: utf-8 -*-\n" "# Generated by the protocol buffer compiler. DO NOT EDIT!\n" "# source: $filename$\n" - "\nimport sys\n_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))" //##PY25 + "\nimport sys\n_b=sys.version_info[0]<3 and (lambda x:x) or (lambda " + "x:x.encode('latin1'))" //##PY25 "\n", "filename", file->name()); if (HasTopLevelEnums(file)) { @@ -205,7 +213,6 @@ void PrintTopBoilerplate( printer->Print("\n\n"); } - // Returns a Python literal giving the default value for a field. // If the field specifies no explicit default value, we'll return // the default default value for the field type (zero for numbers, @@ -216,20 +223,20 @@ void PrintTopBoilerplate( // //compiler/cpp/internal/primitive_field.cc // //compiler/cpp/internal/enum_field.cc // //compiler/cpp/internal/string_field.cc -string StringifyDefaultValue(const FieldDescriptor& field) { +std::string StringifyDefaultValue(const FieldDescriptor& field) { if (field.is_repeated()) { return "[]"; } switch (field.cpp_type()) { case FieldDescriptor::CPPTYPE_INT32: - return SimpleItoa(field.default_value_int32()); + return StrCat(field.default_value_int32()); case FieldDescriptor::CPPTYPE_UINT32: - return SimpleItoa(field.default_value_uint32()); + return StrCat(field.default_value_uint32()); case FieldDescriptor::CPPTYPE_INT64: - return SimpleItoa(field.default_value_int64()); + return StrCat(field.default_value_int64()); case FieldDescriptor::CPPTYPE_UINT64: - return SimpleItoa(field.default_value_uint64()); + return StrCat(field.default_value_uint64()); case FieldDescriptor::CPPTYPE_DOUBLE: { double value = field.default_value_double(); if (value == std::numeric_limits::infinity()) { @@ -265,14 +272,16 @@ string StringifyDefaultValue(const FieldDescriptor& field) { case FieldDescriptor::CPPTYPE_BOOL: return field.default_value_bool() ? "True" : "False"; case FieldDescriptor::CPPTYPE_ENUM: - return SimpleItoa(field.default_value_enum()->number()); + return StrCat(field.default_value_enum()->number()); case FieldDescriptor::CPPTYPE_STRING: -//##!PY25 return "b\"" + CEscape(field.default_value_string()) + -//##!PY25 (field.type() != FieldDescriptor::TYPE_STRING ? "\"" : -//##!PY25 "\".decode('utf-8')"); + //##!PY25 return "b\"" + CEscape(field.default_value_string()) + //+ + //##!PY25 (field.type() != FieldDescriptor::TYPE_STRING ? "\"" + //: + //##!PY25 "\".decode('utf-8')"); return "_b(\"" + CEscape(field.default_value_string()) + //##PY25 (field.type() != FieldDescriptor::TYPE_STRING ? "\")" : //##PY25 - "\").decode('utf-8')"); //##PY25 + "\").decode('utf-8')"); //##PY25 case FieldDescriptor::CPPTYPE_MESSAGE: return "None"; } @@ -282,7 +291,7 @@ string StringifyDefaultValue(const FieldDescriptor& field) { return ""; } -string StringifySyntax(FileDescriptor::Syntax syntax) { +std::string StringifySyntax(FileDescriptor::Syntax syntax) { switch (syntax) { case FileDescriptor::SYNTAX_PROTO2: return "proto2"; @@ -296,20 +305,15 @@ string StringifySyntax(FileDescriptor::Syntax syntax) { } } - } // namespace +Generator::Generator() : file_(NULL) {} -Generator::Generator() : file_(NULL) { -} - -Generator::~Generator() { -} +Generator::~Generator() {} bool Generator::Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const { + const std::string& parameter, + GeneratorContext* context, std::string* error) const { // Completely serialize all Generate() calls on this instance. The // thread-safety constraints of the CodeGenerator interface aren't clear so @@ -320,8 +324,8 @@ bool Generator::Generate(const FileDescriptor* file, // to have any mutable members. Then it is implicitly thread-safe. MutexLock lock(&mutex_); file_ = file; - string module_name = ModuleName(file->name()); - string filename = module_name; + std::string module_name = ModuleName(file->name()); + std::string filename = module_name; ReplaceCharacters(&filename, ".", '/'); filename += ".py"; @@ -359,19 +363,35 @@ bool Generator::Generate(const FileDescriptor* file, PrintServices(); } - printer.Print( - "# @@protoc_insertion_point(module_scope)\n"); + printer.Print("# @@protoc_insertion_point(module_scope)\n"); return !printer.failed(); } +// BEGIN GOOGLE-INTERNAL +// Strip the google3.third_party.py. prefix off of a module name as we +// NEVER want that invalid module import path to be generated in google3. +// Our sys.path has google3/third_party/py/ in it. All modules from +// that tree need to be imported using just their own name. +// See http://go/ThirdPartyPython +void StripThirdPartyPy(std::string* module_name) { + const std::string third_party_py_prefix = "google3.third_party.py."; + int len = third_party_py_prefix.length(); + if (module_name->compare(0, len, third_party_py_prefix, 0, len) == 0) { + *module_name = module_name->erase(0, len); + } +} +// END GOOGLE-INTERNAL // Prints Python imports for all modules imported by |file|. void Generator::PrintImports() const { for (int i = 0; i < file_->dependency_count(); ++i) { - const string& filename = file_->dependency(i)->name(); + const std::string& filename = file_->dependency(i)->name(); - string module_name = ModuleName(filename); - string module_alias = ModuleAlias(filename); + std::string module_name = ModuleName(filename); + std::string module_alias = ModuleAlias(filename); + // BEGIN GOOGLE-INTERNAL + StripThirdPartyPy(&module_name); + // END GOOGLE-INTERNAL if (ContainsPythonKeyword(module_name)) { // If the module path contains a Python keyword, we have to quote the // module name and import it using importlib. Otherwise the usual kind of @@ -382,8 +402,8 @@ void Generator::PrintImports() const { module_alias, "name", module_name); } else { int last_dot_pos = module_name.rfind('.'); - string import_statement; - if (last_dot_pos == string::npos) { + std::string import_statement; + if (last_dot_pos == std::string::npos) { // NOTE(petya): this is not tested as it would require a protocol buffer // outside of any package, and I don't think that is easily achievable. import_statement = "import " + module_name; @@ -401,7 +421,10 @@ void Generator::PrintImports() const { // Print public imports. for (int i = 0; i < file_->public_dependency_count(); ++i) { - string module_name = ModuleName(file_->public_dependency(i)->name()); + std::string module_name = ModuleName(file_->public_dependency(i)->name()); + // BEGIN GOOGLE-INTERNAL + StripThirdPartyPy(&module_name); + // END GOOGLE-INTERNAL printer_->Print("from $module$ import *\n", "module", module_name); } printer_->Print("\n"); @@ -409,7 +432,7 @@ void Generator::PrintImports() const { // Prints the single file descriptor for this file. void Generator::PrintFileDescriptor() const { - std::map m; + std::map m; m["descriptor_name"] = kDescriptorKey; m["name"] = file_->name(); m["package"] = file_->package(); @@ -424,13 +447,13 @@ void Generator::PrintFileDescriptor() const { printer_->Print(m, file_descriptor_template); printer_->Indent(); printer_->Print( -//##!PY25 "serialized_pb=b'$value$'\n", + //##!PY25 "serialized_pb=b'$value$'\n", "serialized_pb=_b('$value$')\n", //##PY25 "value", strings::CHexEscape(file_descriptor_serialized_)); if (file_->dependency_count() != 0) { printer_->Print(",\ndependencies=["); for (int i = 0; i < file_->dependency_count(); ++i) { - string module_alias = ModuleAlias(file_->dependency(i)->name()); + std::string module_alias = ModuleAlias(file_->dependency(i)->name()); printer_->Print("$module_alias$.DESCRIPTOR,", "module_alias", module_alias); } @@ -439,7 +462,8 @@ void Generator::PrintFileDescriptor() const { if (file_->public_dependency_count() > 0) { printer_->Print(",\npublic_dependencies=["); for (int i = 0; i < file_->public_dependency_count(); ++i) { - string module_alias = ModuleAlias(file_->public_dependency(i)->name()); + std::string module_alias = + ModuleAlias(file_->public_dependency(i)->name()); printer_->Print("$module_alias$.DESCRIPTOR,", "module_alias", module_alias); } @@ -457,15 +481,15 @@ void Generator::PrintFileDescriptor() const { // Prints descriptors and module-level constants for all top-level // enums defined in |file|. void Generator::PrintTopLevelEnums() const { - std::vector > top_level_enum_values; + std::vector > top_level_enum_values; for (int i = 0; i < file_->enum_type_count(); ++i) { const EnumDescriptor& enum_descriptor = *file_->enum_type(i); PrintEnum(enum_descriptor); - printer_->Print("$name$ = " - "enum_type_wrapper.EnumTypeWrapper($descriptor_name$)", - "name", enum_descriptor.name(), - "descriptor_name", - ModuleLevelDescriptorName(enum_descriptor)); + printer_->Print( + "$name$ = " + "enum_type_wrapper.EnumTypeWrapper($descriptor_name$)", + "name", ResolveKeyword(enum_descriptor.name()), "descriptor_name", + ModuleLevelDescriptorName(enum_descriptor)); printer_->Print("\n"); for (int j = 0; j < enum_descriptor.value_count(); ++j) { @@ -476,9 +500,9 @@ void Generator::PrintTopLevelEnums() const { } for (int i = 0; i < top_level_enum_values.size(); ++i) { - printer_->Print("$name$ = $value$\n", - "name", top_level_enum_values[i].first, - "value", SimpleItoa(top_level_enum_values[i].second)); + printer_->Print("$name$ = $value$\n", "name", + ResolveKeyword(top_level_enum_values[i].first), "value", + StrCat(top_level_enum_values[i].second)); } printer_->Print("\n"); } @@ -494,8 +518,8 @@ void Generator::PrintAllNestedEnumsInFile() const { // enum name to a Python EnumDescriptor object equivalent to // enum_descriptor. void Generator::PrintEnum(const EnumDescriptor& enum_descriptor) const { - std::map m; - string module_level_descriptor_name = + std::map m; + std::string module_level_descriptor_name = ModuleLevelDescriptorName(enum_descriptor); m["descriptor_name"] = module_level_descriptor_name; m["name"] = enum_descriptor.name(); @@ -508,7 +532,7 @@ void Generator::PrintEnum(const EnumDescriptor& enum_descriptor) const { " filename=None,\n" " file=$file$,\n" " values=[\n"; - string options_string; + std::string options_string; enum_descriptor.options().SerializeToString(&options_string); printer_->Print(m, enum_descriptor_template); printer_->Indent(); @@ -520,8 +544,7 @@ void Generator::PrintEnum(const EnumDescriptor& enum_descriptor) const { printer_->Outdent(); printer_->Print("],\n"); printer_->Print("containing_type=None,\n"); - printer_->Print("serialized_options=$options_value$,\n", - "options_value", + printer_->Print("serialized_options=$options_value$,\n", "options_value", OptionsValue(options_string)); EnumDescriptorProto edp; PrintSerializedPbInterval(enum_descriptor, edp); @@ -548,12 +571,13 @@ void Generator::PrintTopLevelExtensions() const { const bool is_extension = true; for (int i = 0; i < file_->extension_count(); ++i) { const FieldDescriptor& extension_field = *file_->extension(i); - string constant_name = extension_field.name() + "_FIELD_NUMBER"; + std::string constant_name = extension_field.name() + "_FIELD_NUMBER"; UpperString(&constant_name); - printer_->Print("$constant_name$ = $number$\n", - "constant_name", constant_name, - "number", SimpleItoa(extension_field.number())); - printer_->Print("$name$ = ", "name", extension_field.name()); + printer_->Print("$constant_name$ = $number$\n", "constant_name", + constant_name, "number", + StrCat(extension_field.number())); + printer_->Print("$name$ = ", "name", + ResolveKeyword(extension_field.name())); PrintFieldDescriptor(extension_field, is_extension); printer_->Print("\n"); } @@ -587,19 +611,18 @@ void Generator::PrintServices() const { void Generator::PrintServiceDescriptor( const ServiceDescriptor& descriptor) const { printer_->Print("\n"); - string service_name = ModuleLevelServiceDescriptorName(descriptor); - string options_string; + std::string service_name = ModuleLevelServiceDescriptorName(descriptor); + std::string options_string; descriptor.options().SerializeToString(&options_string); - printer_->Print( - "$service_name$ = _descriptor.ServiceDescriptor(\n", - "service_name", service_name); + printer_->Print("$service_name$ = _descriptor.ServiceDescriptor(\n", + "service_name", service_name); printer_->Indent(); - std::map m; + std::map m; m["name"] = descriptor.name(); m["full_name"] = descriptor.full_name(); m["file"] = kDescriptorKey; - m["index"] = SimpleItoa(descriptor.index()); + m["index"] = StrCat(descriptor.index()); m["options_value"] = OptionsValue(options_string); const char required_function_arguments[] = "name='$name$',\n" @@ -620,22 +643,21 @@ void Generator::PrintServiceDescriptor( m.clear(); m["name"] = method->name(); m["full_name"] = method->full_name(); - m["index"] = SimpleItoa(method->index()); + m["index"] = StrCat(method->index()); m["serialized_options"] = CEscape(options_string); m["input_type"] = ModuleLevelDescriptorName(*(method->input_type())); m["output_type"] = ModuleLevelDescriptorName(*(method->output_type())); m["options_value"] = OptionsValue(options_string); printer_->Print("_descriptor.MethodDescriptor(\n"); printer_->Indent(); - printer_->Print( - m, - "name='$name$',\n" - "full_name='$full_name$',\n" - "index=$index$,\n" - "containing_service=None,\n" - "input_type=$input_type$,\n" - "output_type=$output_type$,\n" - "serialized_options=$options_value$,\n"); + printer_->Print(m, + "name='$name$',\n" + "full_name='$full_name$',\n" + "index=$index$,\n" + "containing_service=None,\n" + "input_type=$input_type$,\n" + "output_type=$output_type$,\n" + "serialized_options=$options_value$,\n"); printer_->Outdent(); printer_->Print("),\n"); } @@ -647,23 +669,21 @@ void Generator::PrintServiceDescriptor( printer_->Print("\n"); } - void Generator::PrintDescriptorKeyAndModuleName( const ServiceDescriptor& descriptor) const { - printer_->Print( - "$descriptor_key$ = $descriptor_name$,\n", - "descriptor_key", kDescriptorKey, - "descriptor_name", ModuleLevelServiceDescriptorName(descriptor)); - printer_->Print( - "__module__ = '$module_name$'\n", - "module_name", ModuleName(file_->name())); + printer_->Print("$descriptor_key$ = $descriptor_name$,\n", "descriptor_key", + kDescriptorKey, "descriptor_name", + ModuleLevelServiceDescriptorName(descriptor)); + printer_->Print("__module__ = '$module_name$'\n", "module_name", + ModuleName(file_->name())); } void Generator::PrintServiceClass(const ServiceDescriptor& descriptor) const { // Print the service. - printer_->Print("$class_name$ = service_reflection.GeneratedServiceType(" - "'$class_name$', (_service.Service,), dict(\n", - "class_name", descriptor.name()); + printer_->Print( + "$class_name$ = service_reflection.GeneratedServiceType(" + "'$class_name$', (_service.Service,), dict(\n", + "class_name", descriptor.name()); printer_->Indent(); Generator::PrintDescriptorKeyAndModuleName(descriptor); printer_->Print("))\n\n"); @@ -672,10 +692,11 @@ void Generator::PrintServiceClass(const ServiceDescriptor& descriptor) const { void Generator::PrintServiceStub(const ServiceDescriptor& descriptor) const { // Print the service stub. - printer_->Print("$class_name$_Stub = " - "service_reflection.GeneratedServiceStubType(" - "'$class_name$_Stub', ($class_name$,), dict(\n", - "class_name", descriptor.name()); + printer_->Print( + "$class_name$_Stub = " + "service_reflection.GeneratedServiceStubType(" + "'$class_name$_Stub', ($class_name$,), dict(\n", + "class_name", descriptor.name()); printer_->Indent(); Generator::PrintDescriptorKeyAndModuleName(descriptor); printer_->Print("))\n\n"); @@ -694,7 +715,7 @@ void Generator::PrintDescriptor(const Descriptor& message_descriptor) const { "descriptor_name", ModuleLevelDescriptorName(message_descriptor)); printer_->Indent(); - std::map m; + std::map m; m["name"] = message_descriptor.name(); m["full_name"] = message_descriptor.full_name(); m["file"] = kDescriptorKey; @@ -711,8 +732,8 @@ void Generator::PrintDescriptor(const Descriptor& message_descriptor) const { // Nested types printer_->Print("nested_types=["); for (int i = 0; i < message_descriptor.nested_type_count(); ++i) { - const string nested_name = ModuleLevelDescriptorName( - *message_descriptor.nested_type(i)); + const std::string nested_name = + ModuleLevelDescriptorName(*message_descriptor.nested_type(i)); printer_->Print("$name$, ", "name", nested_name); } printer_->Print("],\n"); @@ -721,22 +742,21 @@ void Generator::PrintDescriptor(const Descriptor& message_descriptor) const { printer_->Print("enum_types=[\n"); printer_->Indent(); for (int i = 0; i < message_descriptor.enum_type_count(); ++i) { - const string descriptor_name = ModuleLevelDescriptorName( - *message_descriptor.enum_type(i)); + const std::string descriptor_name = + ModuleLevelDescriptorName(*message_descriptor.enum_type(i)); printer_->Print(descriptor_name.c_str()); printer_->Print(",\n"); } printer_->Outdent(); printer_->Print("],\n"); - string options_string; + std::string options_string; message_descriptor.options().SerializeToString(&options_string); printer_->Print( "serialized_options=$options_value$,\n" "is_extendable=$extendable$,\n" "syntax='$syntax$'", - "options_value", OptionsValue(options_string), - "extendable", message_descriptor.extension_range_count() > 0 ? - "True" : "False", + "options_value", OptionsValue(options_string), "extendable", + message_descriptor.extension_range_count() > 0 ? "True" : "False", "syntax", StringifySyntax(message_descriptor.file()->syntax())); printer_->Print(",\n"); @@ -745,32 +765,30 @@ void Generator::PrintDescriptor(const Descriptor& message_descriptor) const { for (int i = 0; i < message_descriptor.extension_range_count(); ++i) { const Descriptor::ExtensionRange* range = message_descriptor.extension_range(i); - printer_->Print("($start$, $end$), ", - "start", SimpleItoa(range->start), - "end", SimpleItoa(range->end)); + printer_->Print("($start$, $end$), ", "start", StrCat(range->start), + "end", StrCat(range->end)); } printer_->Print("],\n"); printer_->Print("oneofs=[\n"); printer_->Indent(); for (int i = 0; i < message_descriptor.oneof_decl_count(); ++i) { const OneofDescriptor* desc = message_descriptor.oneof_decl(i); - std::map m; + std::map m; m["name"] = desc->name(); m["full_name"] = desc->full_name(); - m["index"] = SimpleItoa(desc->index()); - string options_string = + m["index"] = StrCat(desc->index()); + std::string options_string = OptionsValue(desc->options().SerializeAsString()); if (options_string == "None") { m["serialized_options"] = ""; } else { m["serialized_options"] = ", serialized_options=" + options_string; } - printer_->Print( - m, - "_descriptor.OneofDescriptor(\n" - " name='$name$', full_name='$full_name$',\n" - " index=$index$, containing_type=None, " - "fields=[]$serialized_options$),\n"); + printer_->Print(m, + "_descriptor.OneofDescriptor(\n" + " name='$name$', full_name='$full_name$',\n" + " index=$index$, containing_type=None, " + "fields=[]$serialized_options$),\n"); } printer_->Outdent(); printer_->Print("],\n"); @@ -796,11 +814,11 @@ void Generator::PrintNestedDescriptors( // Prints all messages in |file|. void Generator::PrintMessages() const { for (int i = 0; i < file_->message_type_count(); ++i) { - std::vector to_register; - PrintMessage(*file_->message_type(i), "", &to_register); + std::vector to_register; + PrintMessage(*file_->message_type(i), "", &to_register, false); for (int j = 0; j < to_register.size(); ++j) { printer_->Print("_sym_db.RegisterMessage($name$)\n", "name", - to_register[j]); + ResolveKeyword(to_register[j])); } printer_->Print("\n"); } @@ -815,37 +833,54 @@ void Generator::PrintMessages() const { // Mutually recursive with PrintNestedMessages(). // Collect nested message names to_register for the symbol_database. void Generator::PrintMessage(const Descriptor& message_descriptor, - const string& prefix, - std::vector* to_register) const { - string qualified_name(prefix + message_descriptor.name()); - to_register->push_back(qualified_name); - printer_->Print( - "$name$ = _reflection.GeneratedProtocolMessageType('$name$', " - "(_message.Message,), dict(\n", - "name", message_descriptor.name()); + const std::string& prefix, + std::vector* to_register, + bool is_nested) const { + std::string qualified_name; + if (is_nested) { + if (IsPythonKeyword(message_descriptor.name())) { + qualified_name = + "getattr(" + prefix + ", '" + message_descriptor.name() + "')"; + } else { + qualified_name = prefix + "." + message_descriptor.name(); + } + printer_->Print( + "'$name$' : _reflection.GeneratedProtocolMessageType('$name$', " + "(_message.Message,), {\n", + "name", message_descriptor.name()); + } else { + qualified_name = ResolveKeyword(message_descriptor.name()); + printer_->Print( + "$qualified_name$ = _reflection.GeneratedProtocolMessageType('$name$', " + "(_message.Message,), {\n", + "qualified_name", qualified_name, "name", message_descriptor.name()); + } printer_->Indent(); - PrintNestedMessages(message_descriptor, qualified_name + ".", to_register); - std::map m; + to_register->push_back(qualified_name); + + PrintNestedMessages(message_descriptor, qualified_name, to_register); + std::map m; m["descriptor_key"] = kDescriptorKey; m["descriptor_name"] = ModuleLevelDescriptorName(message_descriptor); - printer_->Print(m, "$descriptor_key$ = $descriptor_name$,\n"); - printer_->Print("__module__ = '$module_name$'\n", - "module_name", ModuleName(file_->name())); + printer_->Print(m, "'$descriptor_key$' : $descriptor_name$,\n"); + printer_->Print("'__module__' : '$module_name$'\n", "module_name", + ModuleName(file_->name())); printer_->Print("# @@protoc_insertion_point(class_scope:$full_name$)\n", "full_name", message_descriptor.full_name()); - printer_->Print("))\n"); + printer_->Print("})\n"); printer_->Outdent(); } // Prints all nested messages within |containing_descriptor|. // Mutually recursive with PrintMessage(). -void Generator::PrintNestedMessages(const Descriptor& containing_descriptor, - const string& prefix, - std::vector* to_register) const { +void Generator::PrintNestedMessages( + const Descriptor& containing_descriptor, const std::string& prefix, + std::vector* to_register) const { for (int i = 0; i < containing_descriptor.nested_type_count(); ++i) { printer_->Print("\n"); - PrintMessage(*containing_descriptor.nested_type(i), prefix, to_register); + PrintMessage(*containing_descriptor.nested_type(i), prefix, to_register, + true); printer_->Print(",\n"); } } @@ -875,7 +910,7 @@ void Generator::FixForeignFieldsInDescriptor( FixContainingTypeInDescriptor(enum_descriptor, &descriptor); } for (int i = 0; i < descriptor.oneof_decl_count(); ++i) { - std::map m; + std::map m; const OneofDescriptor* oneof = descriptor.oneof_decl(i); m["descriptor_name"] = ModuleLevelDescriptorName(descriptor); m["oneof_name"] = oneof->name(); @@ -894,7 +929,7 @@ void Generator::FixForeignFieldsInDescriptor( } void Generator::AddMessageToFileDescriptor(const Descriptor& descriptor) const { - std::map m; + std::map m; m["descriptor_name"] = kDescriptorKey; m["message_name"] = descriptor.name(); m["message_descriptor_name"] = ModuleLevelDescriptorName(descriptor); @@ -906,7 +941,7 @@ void Generator::AddMessageToFileDescriptor(const Descriptor& descriptor) const { void Generator::AddServiceToFileDescriptor( const ServiceDescriptor& descriptor) const { - std::map m; + std::map m; m["descriptor_name"] = kDescriptorKey; m["service_name"] = descriptor.name(); m["service_descriptor_name"] = ModuleLevelServiceDescriptorName(descriptor); @@ -918,7 +953,7 @@ void Generator::AddServiceToFileDescriptor( void Generator::AddEnumToFileDescriptor( const EnumDescriptor& descriptor) const { - std::map m; + std::map m; m["descriptor_name"] = kDescriptorKey; m["enum_name"] = descriptor.name(); m["enum_descriptor_name"] = ModuleLevelDescriptorName(descriptor); @@ -930,12 +965,13 @@ void Generator::AddEnumToFileDescriptor( void Generator::AddExtensionToFileDescriptor( const FieldDescriptor& descriptor) const { - std::map m; + std::map m; m["descriptor_name"] = kDescriptorKey; m["field_name"] = descriptor.name(); + m["resolved_name"] = ResolveKeyword(descriptor.name()); const char file_descriptor_template[] = "$descriptor_name$.extensions_by_name['$field_name$'] = " - "$field_name$\n"; + "$resolved_name$\n"; printer_->Print(m, file_descriptor_template); } @@ -948,12 +984,12 @@ void Generator::AddExtensionToFileDescriptor( // look the field up in the containing type. (e.g., fields_by_name // or extensions_by_name). We ignore python_dict_name if containing_type // is NULL. -void Generator::FixForeignFieldsInField(const Descriptor* containing_type, - const FieldDescriptor& field, - const string& python_dict_name) const { - const string field_referencing_expression = FieldReferencingExpression( - containing_type, field, python_dict_name); - std::map m; +void Generator::FixForeignFieldsInField( + const Descriptor* containing_type, const FieldDescriptor& field, + const std::string& python_dict_name) const { + const std::string field_referencing_expression = + FieldReferencingExpression(containing_type, field, python_dict_name); + std::map m; m["field_ref"] = field_referencing_expression; const Descriptor* foreign_message_type = field.message_type(); if (foreign_message_type) { @@ -976,21 +1012,19 @@ void Generator::FixForeignFieldsInField(const Descriptor* containing_type, // look the field up in the containing type. (e.g., fields_by_name // or extensions_by_name). We ignore python_dict_name if containing_type // is NULL. -string Generator::FieldReferencingExpression( - const Descriptor* containing_type, - const FieldDescriptor& field, - const string& python_dict_name) const { +std::string Generator::FieldReferencingExpression( + const Descriptor* containing_type, const FieldDescriptor& field, + const std::string& python_dict_name) const { // We should only ever be looking up fields in the current file. // The only things we refer to from other files are message descriptors. - GOOGLE_CHECK_EQ(field.file(), file_) << field.file()->name() << " vs. " - << file_->name(); + GOOGLE_CHECK_EQ(field.file(), file_) + << field.file()->name() << " vs. " << file_->name(); if (!containing_type) { - return field.name(); + return ResolveKeyword(field.name()); } - return strings::Substitute( - "$0.$1['$2']", - ModuleLevelDescriptorName(*containing_type), - python_dict_name, field.name()); + return strings::Substitute("$0.$1['$2']", + ModuleLevelDescriptorName(*containing_type), + python_dict_name, field.name()); } // Prints containing_type for nested descriptors or enum descriptors. @@ -999,13 +1033,11 @@ void Generator::FixContainingTypeInDescriptor( const DescriptorT& descriptor, const Descriptor* containing_descriptor) const { if (containing_descriptor != NULL) { - const string nested_name = ModuleLevelDescriptorName(descriptor); - const string parent_name = ModuleLevelDescriptorName( - *containing_descriptor); - printer_->Print( - "$nested_name$.containing_type = $parent_name$\n", - "nested_name", nested_name, - "parent_name", parent_name); + const std::string nested_name = ModuleLevelDescriptorName(descriptor); + const std::string parent_name = + ModuleLevelDescriptorName(*containing_descriptor); + printer_->Print("$nested_name$.containing_type = $parent_name$\n", + "nested_name", nested_name, "parent_name", parent_name); } } @@ -1056,16 +1088,15 @@ void Generator::FixForeignFieldsInExtension( FixForeignFieldsInField(extension_field.extension_scope(), extension_field, "extensions_by_name"); - std::map m; + std::map m; // Confusingly, for FieldDescriptors that happen to be extensions, // containing_type() means "extended type." // On the other hand, extension_scope() will give us what we normally // mean by containing_type(). - m["extended_message_class"] = ModuleLevelMessageName( - *extension_field.containing_type()); - m["field"] = FieldReferencingExpression(extension_field.extension_scope(), - extension_field, - "extensions_by_name"); + m["extended_message_class"] = + ModuleLevelMessageName(*extension_field.containing_type()); + m["field"] = FieldReferencingExpression( + extension_field.extension_scope(), extension_field, "extensions_by_name"); printer_->Print(m, "$extended_message_class$.RegisterExtension($field$)\n"); } @@ -1087,76 +1118,74 @@ void Generator::PrintEnumValueDescriptor( const EnumValueDescriptor& descriptor) const { // TODO(robinson): Fix up EnumValueDescriptor "type" fields. // More circular references. ::sigh:: - string options_string; + std::string options_string; descriptor.options().SerializeToString(&options_string); - std::map m; + std::map m; m["name"] = descriptor.name(); - m["index"] = SimpleItoa(descriptor.index()); - m["number"] = SimpleItoa(descriptor.number()); + m["index"] = StrCat(descriptor.index()); + m["number"] = StrCat(descriptor.number()); m["options"] = OptionsValue(options_string); - printer_->Print( - m, - "_descriptor.EnumValueDescriptor(\n" - " name='$name$', index=$index$, number=$number$,\n" - " serialized_options=$options$,\n" - " type=None)"); + printer_->Print(m, + "_descriptor.EnumValueDescriptor(\n" + " name='$name$', index=$index$, number=$number$,\n" + " serialized_options=$options$,\n" + " type=None)"); } // Returns a CEscaped string of serialized_options. -string Generator::OptionsValue(const string& serialized_options) const { +std::string Generator::OptionsValue( + const std::string& serialized_options) const { if (serialized_options.length() == 0 || GeneratingDescriptorProto()) { return "None"; } else { -//##!PY25 return "b'('" + CEscape(serialized_options)+ "')"; - return "_b('"+ CEscape(serialized_options) + "')"; //##PY25 + //##!PY25 return "b'('" + CEscape(serialized_options)+ "')"; + return "_b('" + CEscape(serialized_options) + "')"; //##PY25 } } // Prints an expression for a Python FieldDescriptor for |field|. -void Generator::PrintFieldDescriptor( - const FieldDescriptor& field, bool is_extension) const { - string options_string; +void Generator::PrintFieldDescriptor(const FieldDescriptor& field, + bool is_extension) const { + std::string options_string; field.options().SerializeToString(&options_string); - std::map m; + std::map m; m["name"] = field.name(); m["full_name"] = field.full_name(); - m["index"] = SimpleItoa(field.index()); - m["number"] = SimpleItoa(field.number()); - m["type"] = SimpleItoa(field.type()); - m["cpp_type"] = SimpleItoa(field.cpp_type()); - m["label"] = SimpleItoa(field.label()); + m["index"] = StrCat(field.index()); + m["number"] = StrCat(field.number()); + m["type"] = StrCat(field.type()); + m["cpp_type"] = StrCat(field.cpp_type()); + m["label"] = StrCat(field.label()); m["has_default_value"] = field.has_default_value() ? "True" : "False"; m["default_value"] = StringifyDefaultValue(field); m["is_extension"] = is_extension ? "True" : "False"; m["serialized_options"] = OptionsValue(options_string); - m["json_name"] = field.has_json_name() ? - ", json_name='" + field.json_name() + "'": ""; + m["json_name"] = + field.has_json_name() ? ", json_name='" + field.json_name() + "'" : ""; // We always set message_type and enum_type to None at this point, and then // these fields in correctly after all referenced descriptors have been // defined and/or imported (see FixForeignFieldsInDescriptors()). const char field_descriptor_decl[] = - "_descriptor.FieldDescriptor(\n" - " name='$name$', full_name='$full_name$', index=$index$,\n" - " number=$number$, type=$type$, cpp_type=$cpp_type$, label=$label$,\n" - " has_default_value=$has_default_value$, default_value=$default_value$,\n" - " message_type=None, enum_type=None, containing_type=None,\n" - " is_extension=$is_extension$, extension_scope=None,\n" - " serialized_options=$serialized_options$$json_name$, file=DESCRIPTOR)"; + "_descriptor.FieldDescriptor(\n" + " name='$name$', full_name='$full_name$', index=$index$,\n" + " number=$number$, type=$type$, cpp_type=$cpp_type$, label=$label$,\n" + " has_default_value=$has_default_value$, " + "default_value=$default_value$,\n" + " message_type=None, enum_type=None, containing_type=None,\n" + " is_extension=$is_extension$, extension_scope=None,\n" + " serialized_options=$serialized_options$$json_name$, file=DESCRIPTOR)"; printer_->Print(m, field_descriptor_decl); } // Helper for Print{Fields,Extensions}InDescriptor(). void Generator::PrintFieldDescriptorsInDescriptor( - const Descriptor& message_descriptor, - bool is_extension, - const string& list_variable_name, - int (Descriptor::*CountFn)() const, - const FieldDescriptor* (Descriptor::*GetterFn)(int) const) const { + const Descriptor& message_descriptor, bool is_extension, + const std::string& list_variable_name, int (Descriptor::*CountFn)() const, + const FieldDescriptor* (Descriptor::*GetterFn)(int)const) const { printer_->Print("$list$=[\n", "list", list_variable_name); printer_->Indent(); for (int i = 0; i < (message_descriptor.*CountFn)(); ++i) { - PrintFieldDescriptor(*(message_descriptor.*GetterFn)(i), - is_extension); + PrintFieldDescriptor(*(message_descriptor.*GetterFn)(i), is_extension); printer_->Print(",\n"); } printer_->Outdent(); @@ -1168,9 +1197,9 @@ void Generator::PrintFieldDescriptorsInDescriptor( void Generator::PrintFieldsInDescriptor( const Descriptor& message_descriptor) const { const bool is_extension = false; - PrintFieldDescriptorsInDescriptor( - message_descriptor, is_extension, "fields", - &Descriptor::field_count, &Descriptor::field); + PrintFieldDescriptorsInDescriptor(message_descriptor, is_extension, "fields", + &Descriptor::field_count, + &Descriptor::field); } // Prints a statement assigning "extensions" to a list of Python @@ -1178,20 +1207,21 @@ void Generator::PrintFieldsInDescriptor( void Generator::PrintExtensionsInDescriptor( const Descriptor& message_descriptor) const { const bool is_extension = true; - PrintFieldDescriptorsInDescriptor( - message_descriptor, is_extension, "extensions", - &Descriptor::extension_count, &Descriptor::extension); + PrintFieldDescriptorsInDescriptor(message_descriptor, is_extension, + "extensions", &Descriptor::extension_count, + &Descriptor::extension); } bool Generator::GeneratingDescriptorProto() const { - return file_->name() == "google/protobuf/descriptor.proto"; + return file_->name() == "net/proto2/proto/descriptor.proto" || + file_->name() == "google/protobuf/descriptor.proto"; } // Returns the unique Python module-level identifier given to a descriptor. // This name is module-qualified iff the given descriptor describes an // entity that doesn't come from the current file. template -string Generator::ModuleLevelDescriptorName( +std::string Generator::ModuleLevelDescriptorName( const DescriptorT& descriptor) const { // FIXME(robinson): // We currently don't worry about collisions with underscores in the type @@ -1205,7 +1235,7 @@ string Generator::ModuleLevelDescriptorName( // // The C++ implementation doesn't guard against this either. Leaving // it for now... - string name = NamePrefixedWithNestedTypes(descriptor, "_"); + std::string name = NamePrefixedWithNestedTypes(descriptor, "_"); UpperString(&name); // Module-private for now. Easy to make public later; almost impossible // to make private later. @@ -1222,8 +1252,9 @@ string Generator::ModuleLevelDescriptorName( // Like ModuleLevelDescriptorName(), module-qualifies the name iff // the given descriptor describes an entity that doesn't come from // the current file. -string Generator::ModuleLevelMessageName(const Descriptor& descriptor) const { - string name = NamePrefixedWithNestedTypes(descriptor, "."); +std::string Generator::ModuleLevelMessageName( + const Descriptor& descriptor) const { + std::string name = NamePrefixedWithNestedTypes(descriptor, "."); if (descriptor.file() != file_) { name = ModuleAlias(descriptor.file()->name()) + "." + name; } @@ -1232,9 +1263,9 @@ string Generator::ModuleLevelMessageName(const Descriptor& descriptor) const { // Returns the unique Python module-level identifier given to a service // descriptor. -string Generator::ModuleLevelServiceDescriptorName( +std::string Generator::ModuleLevelServiceDescriptorName( const ServiceDescriptor& descriptor) const { - string name = descriptor.name(); + std::string name = descriptor.name(); UpperString(&name); name = "_" + name; if (descriptor.file() != file_) { @@ -1252,36 +1283,35 @@ string Generator::ModuleLevelServiceDescriptorName( // serialized_end=43, // template -void Generator::PrintSerializedPbInterval( - const DescriptorT& descriptor, DescriptorProtoT& proto) const { +void Generator::PrintSerializedPbInterval(const DescriptorT& descriptor, + DescriptorProtoT& proto) const { descriptor.CopyTo(&proto); - string sp; + std::string sp; proto.SerializeToString(&sp); int offset = file_descriptor_serialized_.find(sp); GOOGLE_CHECK_GE(offset, 0); - printer_->Print("serialized_start=$serialized_start$,\n" - "serialized_end=$serialized_end$,\n", - "serialized_start", SimpleItoa(offset), - "serialized_end", SimpleItoa(offset + sp.size())); + printer_->Print( + "serialized_start=$serialized_start$,\n" + "serialized_end=$serialized_end$,\n", + "serialized_start", StrCat(offset), "serialized_end", + StrCat(offset + sp.size())); } namespace { -void PrintDescriptorOptionsFixingCode(const string& descriptor, - const string& options, +void PrintDescriptorOptionsFixingCode(const std::string& descriptor, + const std::string& options, io::Printer* printer) { // Reset the _options to None thus DescriptorBase.GetOptions() can // parse _options again after extensions are registered. - printer->Print( - "$descriptor$._options = None\n", - "descriptor", descriptor); + printer->Print("$descriptor$._options = None\n", "descriptor", descriptor); } } // namespace // Prints expressions that set the options field of all descriptors. void Generator::FixAllDescriptorOptions() const { // Prints an expression that sets the file descriptor's options. - string file_options = OptionsValue(file_->options().SerializeAsString()); + std::string file_options = OptionsValue(file_->options().SerializeAsString()); if (file_options != "None") { PrintDescriptorOptionsFixingCode(kDescriptorKey, file_options, printer_); } @@ -1303,11 +1333,10 @@ void Generator::FixAllDescriptorOptions() const { } void Generator::FixOptionsForOneof(const OneofDescriptor& oneof) const { - string oneof_options = OptionsValue(oneof.options().SerializeAsString()); + std::string oneof_options = OptionsValue(oneof.options().SerializeAsString()); if (oneof_options != "None") { - string oneof_name = strings::Substitute( - "$0.$1['$2']", - ModuleLevelDescriptorName(*oneof.containing_type()), + std::string oneof_name = strings::Substitute( + "$0.$1['$2']", ModuleLevelDescriptorName(*oneof.containing_type()), "oneofs_by_name", oneof.name()); PrintDescriptorOptionsFixingCode(oneof_name, oneof_options, printer_); } @@ -1316,16 +1345,16 @@ void Generator::FixOptionsForOneof(const OneofDescriptor& oneof) const { // Prints expressions that set the options for an enum descriptor and its // value descriptors. void Generator::FixOptionsForEnum(const EnumDescriptor& enum_descriptor) const { - string descriptor_name = ModuleLevelDescriptorName(enum_descriptor); - string enum_options = OptionsValue( - enum_descriptor.options().SerializeAsString()); + std::string descriptor_name = ModuleLevelDescriptorName(enum_descriptor); + std::string enum_options = + OptionsValue(enum_descriptor.options().SerializeAsString()); if (enum_options != "None") { PrintDescriptorOptionsFixingCode(descriptor_name, enum_options, printer_); } for (int i = 0; i < enum_descriptor.value_count(); ++i) { const EnumValueDescriptor& value_descriptor = *enum_descriptor.value(i); - string value_options = OptionsValue( - value_descriptor.options().SerializeAsString()); + std::string value_options = + OptionsValue(value_descriptor.options().SerializeAsString()); if (value_options != "None") { PrintDescriptorOptionsFixingCode( StringPrintf("%s.values_by_name[\"%s\"]", descriptor_name.c_str(), @@ -1337,22 +1366,21 @@ void Generator::FixOptionsForEnum(const EnumDescriptor& enum_descriptor) const { // Prints expressions that set the options for field descriptors (including // extensions). -void Generator::FixOptionsForField( - const FieldDescriptor& field) const { - string field_options = OptionsValue(field.options().SerializeAsString()); +void Generator::FixOptionsForField(const FieldDescriptor& field) const { + std::string field_options = OptionsValue(field.options().SerializeAsString()); if (field_options != "None") { - string field_name; + std::string field_name; if (field.is_extension()) { if (field.extension_scope() == NULL) { // Top level extensions. field_name = field.name(); } else { - field_name = FieldReferencingExpression( - field.extension_scope(), field, "extensions_by_name"); + field_name = FieldReferencingExpression(field.extension_scope(), field, + "extensions_by_name"); } } else { - field_name = FieldReferencingExpression( - field.containing_type(), field, "fields_by_name"); + field_name = FieldReferencingExpression(field.containing_type(), field, + "fields_by_name"); } PrintDescriptorOptionsFixingCode(field_name, field_options, printer_); } @@ -1384,12 +1412,11 @@ void Generator::FixOptionsForMessage(const Descriptor& descriptor) const { FixOptionsForField(field); } // Message option for this message. - string message_options = OptionsValue( - descriptor.options().SerializeAsString()); + std::string message_options = + OptionsValue(descriptor.options().SerializeAsString()); if (message_options != "None") { - string descriptor_name = ModuleLevelDescriptorName(descriptor); - PrintDescriptorOptionsFixingCode(descriptor_name, - message_options, + std::string descriptor_name = ModuleLevelDescriptorName(descriptor); + PrintDescriptorOptionsFixingCode(descriptor_name, message_options, printer_); } } @@ -1397,20 +1424,19 @@ void Generator::FixOptionsForMessage(const Descriptor& descriptor) const { // If a dependency forwards other files through public dependencies, let's // copy over the corresponding module aliases. void Generator::CopyPublicDependenciesAliases( - const string& copy_from, const FileDescriptor* file) const { + const std::string& copy_from, const FileDescriptor* file) const { for (int i = 0; i < file->public_dependency_count(); ++i) { - string module_name = ModuleName(file->public_dependency(i)->name()); - string module_alias = ModuleAlias(file->public_dependency(i)->name()); + std::string module_name = ModuleName(file->public_dependency(i)->name()); + std::string module_alias = ModuleAlias(file->public_dependency(i)->name()); // There's no module alias in the dependent file if it was generated by // an old protoc (less than 3.0.0-alpha-1). Use module name in this // situation. - printer_->Print("try:\n" - " $alias$ = $copy_from$.$alias$\n" - "except AttributeError:\n" - " $alias$ = $copy_from$.$module$\n", - "alias", module_alias, - "module", module_name, - "copy_from", copy_from); + printer_->Print( + "try:\n" + " $alias$ = $copy_from$.$alias$\n" + "except AttributeError:\n" + " $alias$ = $copy_from$.$module$\n", + "alias", module_alias, "module", module_name, "copy_from", copy_from); CopyPublicDependenciesAliases(copy_from, file->public_dependency(i)); } } diff --git a/third_party/protobuf/src/google/protobuf/compiler/python/python_generator.h b/third_party/protobuf/src/google/protobuf/compiler/python/python_generator.h index 8e4050de..46306717 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/python/python_generator.h +++ b/third_party/protobuf/src/google/protobuf/compiler/python/python_generator.h @@ -39,7 +39,8 @@ #include #include -#include + +#include namespace google { namespace protobuf { @@ -51,7 +52,9 @@ class FieldDescriptor; class OneofDescriptor; class ServiceDescriptor; -namespace io { class Printer; } +namespace io { +class Printer; +} namespace compiler { namespace python { @@ -60,16 +63,16 @@ namespace python { // If you create your own protocol compiler binary and you want it to support // Python output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT Generator : public CodeGenerator { +class PROTOC_EXPORT Generator : public CodeGenerator { public: Generator(); virtual ~Generator(); // CodeGenerator methods. virtual bool Generate(const FileDescriptor* file, - const string& parameter, + const std::string& parameter, GeneratorContext* generator_context, - string* error) const; + std::string* error) const; private: void PrintImports() const; @@ -81,14 +84,12 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { void PrintTopLevelExtensions() const; - void PrintFieldDescriptor( - const FieldDescriptor& field, bool is_extension) const; + void PrintFieldDescriptor(const FieldDescriptor& field, + bool is_extension) const; void PrintFieldDescriptorsInDescriptor( - const Descriptor& message_descriptor, - bool is_extension, - const string& list_variable_name, - int (Descriptor::*CountFn)() const, - const FieldDescriptor* (Descriptor::*GetterFn)(int) const) const; + const Descriptor& message_descriptor, bool is_extension, + const std::string& list_variable_name, int (Descriptor::*CountFn)() const, + const FieldDescriptor* (Descriptor::*GetterFn)(int)const) const; void PrintFieldsInDescriptor(const Descriptor& message_descriptor) const; void PrintExtensionsInDescriptor(const Descriptor& message_descriptor) const; void PrintMessageDescriptors() const; @@ -96,11 +97,13 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { void PrintNestedDescriptors(const Descriptor& containing_descriptor) const; void PrintMessages() const; - void PrintMessage(const Descriptor& message_descriptor, const string& prefix, - std::vector* to_register) const; + void PrintMessage(const Descriptor& message_descriptor, + const std::string& prefix, + std::vector* to_register, + bool is_nested) const; void PrintNestedMessages(const Descriptor& containing_descriptor, - const string& prefix, - std::vector* to_register) const; + const std::string& prefix, + std::vector* to_register) const; void FixForeignFieldsInDescriptors() const; void FixForeignFieldsInDescriptor( @@ -108,14 +111,14 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { const Descriptor* containing_descriptor) const; void FixForeignFieldsInField(const Descriptor* containing_type, const FieldDescriptor& field, - const string& python_dict_name) const; + const std::string& python_dict_name) const; void AddMessageToFileDescriptor(const Descriptor& descriptor) const; void AddEnumToFileDescriptor(const EnumDescriptor& descriptor) const; void AddExtensionToFileDescriptor(const FieldDescriptor& descriptor) const; void AddServiceToFileDescriptor(const ServiceDescriptor& descriptor) const; - string FieldReferencingExpression(const Descriptor* containing_type, - const FieldDescriptor& field, - const string& python_dict_name) const; + std::string FieldReferencingExpression( + const Descriptor* containing_type, const FieldDescriptor& field, + const std::string& python_dict_name) const; template void FixContainingTypeInDescriptor( const DescriptorT& descriptor, @@ -135,18 +138,18 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { const ServiceDescriptor& descriptor) const; void PrintEnumValueDescriptor(const EnumValueDescriptor& descriptor) const; - string OptionsValue(const string& serialized_options) const; + std::string OptionsValue(const std::string& serialized_options) const; bool GeneratingDescriptorProto() const; template - string ModuleLevelDescriptorName(const DescriptorT& descriptor) const; - string ModuleLevelMessageName(const Descriptor& descriptor) const; - string ModuleLevelServiceDescriptorName( + std::string ModuleLevelDescriptorName(const DescriptorT& descriptor) const; + std::string ModuleLevelMessageName(const Descriptor& descriptor) const; + std::string ModuleLevelServiceDescriptorName( const ServiceDescriptor& descriptor) const; template - void PrintSerializedPbInterval( - const DescriptorT& descriptor, DescriptorProtoT& proto) const; + void PrintSerializedPbInterval(const DescriptorT& descriptor, + DescriptorProtoT& proto) const; void FixAllDescriptorOptions() const; void FixOptionsForField(const FieldDescriptor& field) const; @@ -154,14 +157,14 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { void FixOptionsForEnum(const EnumDescriptor& descriptor) const; void FixOptionsForMessage(const Descriptor& descriptor) const; - void CopyPublicDependenciesAliases( - const string& copy_from, const FileDescriptor* file) const; + void CopyPublicDependenciesAliases(const std::string& copy_from, + const FileDescriptor* file) const; // Very coarse-grained lock to ensure that Generate() is reentrant. // Guards file_, printer_ and file_descriptor_serialized_. mutable Mutex mutex_; mutable const FileDescriptor* file_; // Set in Generate(). Under mutex_. - mutable string file_descriptor_serialized_; + mutable std::string file_descriptor_serialized_; mutable io::Printer* printer_; // Set in Generate(). Under mutex_. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Generator); @@ -170,6 +173,8 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { } // namespace python } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_PYTHON_GENERATOR_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/python/python_plugin_unittest.cc b/third_party/protobuf/src/google/protobuf/compiler/python/python_plugin_unittest.cc index 2f096808..8d7ef98b 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/python/python_plugin_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/python/python_plugin_unittest.cc @@ -36,10 +36,10 @@ #include -#include #include -#include +#include #include +#include #include #include @@ -59,9 +59,8 @@ class TestGenerator : public CodeGenerator { ~TestGenerator() {} virtual bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const { + const std::string& parameter, GeneratorContext* context, + std::string* error) const { TryInsert("test_pb2.py", "imports", context); TryInsert("test_pb2.py", "module_scope", context); TryInsert("test_pb2.py", "class_scope:foo.Bar", context); @@ -69,7 +68,8 @@ class TestGenerator : public CodeGenerator { return true; } - void TryInsert(const string& filename, const string& insertion_point, + void TryInsert(const std::string& filename, + const std::string& insertion_point, GeneratorContext* context) const { std::unique_ptr output( context->OpenForInsert(filename, insertion_point)); @@ -90,7 +90,7 @@ TEST(PythonPluginTest, PluginTest) { "}\n", true)); - google::protobuf::compiler::CommandLineInterface cli; + compiler::CommandLineInterface cli; cli.SetInputsAreProtoPathRelative(true); python::Generator python_generator; @@ -98,17 +98,12 @@ TEST(PythonPluginTest, PluginTest) { cli.RegisterGenerator("--python_out", &python_generator, ""); cli.RegisterGenerator("--test_out", &test_generator, ""); - string proto_path = "-I" + TestTempDir(); - string python_out = "--python_out=" + TestTempDir(); - string test_out = "--test_out=" + TestTempDir(); + std::string proto_path = "-I" + TestTempDir(); + std::string python_out = "--python_out=" + TestTempDir(); + std::string test_out = "--test_out=" + TestTempDir(); - const char* argv[] = { - "protoc", - proto_path.c_str(), - python_out.c_str(), - test_out.c_str(), - "test.proto" - }; + const char* argv[] = {"protoc", proto_path.c_str(), python_out.c_str(), + test_out.c_str(), "test.proto"}; EXPECT_EQ(0, cli.Run(5, argv)); } @@ -133,29 +128,29 @@ TEST(PythonPluginTest, ImportTest) { "message Message2 {}\n", true)); - google::protobuf::compiler::CommandLineInterface cli; + compiler::CommandLineInterface cli; cli.SetInputsAreProtoPathRelative(true); python::Generator python_generator; cli.RegisterGenerator("--python_out", &python_generator, ""); - string proto_path = "-I" + TestTempDir(); - string python_out = "--python_out=" + TestTempDir(); + std::string proto_path = "-I" + TestTempDir(); + std::string python_out = "--python_out=" + TestTempDir(); const char* argv[] = {"protoc", proto_path.c_str(), "-I.", python_out.c_str(), "test1.proto"}; ASSERT_EQ(0, cli.Run(5, argv)); // Loop over the lines of the generated code and verify that we find an // ordinary Python import but do not find the string "importlib". - string output; + std::string output; GOOGLE_CHECK_OK(File::GetContents(TestTempDir() + "/test1_pb2.py", &output, true)); - std::vector lines = Split(output, "\n"); - string expected_import = "import test2_pb2"; + std::vector lines = Split(output, "\n"); + std::string expected_import = "import test2_pb2"; bool found_expected_import = false; for (int i = 0; i < lines.size(); ++i) { - if (lines[i].find(expected_import) != string::npos) { + if (lines[i].find(expected_import) != std::string::npos) { found_expected_import = true; } - EXPECT_EQ(string::npos, lines[i].find("importlib")); + EXPECT_EQ(std::string::npos, lines[i].find("importlib")); } EXPECT_TRUE(found_expected_import); } diff --git a/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_code_pb.rb b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_code_pb.rb index 49b23fbe..0c9ed6fb 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_code_pb.rb +++ b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_code_pb.rb @@ -4,62 +4,64 @@ require 'google/protobuf' Google::Protobuf::DescriptorPool.generated_pool.build do - add_message "A.B.C.TestMessage" do - optional :optional_int32, :int32, 1 - optional :optional_int64, :int64, 2 - optional :optional_uint32, :uint32, 3 - optional :optional_uint64, :uint64, 4 - optional :optional_bool, :bool, 5 - optional :optional_double, :double, 6 - optional :optional_float, :float, 7 - optional :optional_string, :string, 8 - optional :optional_bytes, :bytes, 9 - optional :optional_enum, :enum, 10, "A.B.C.TestEnum" - optional :optional_msg, :message, 11, "A.B.C.TestMessage" - repeated :repeated_int32, :int32, 21 - repeated :repeated_int64, :int64, 22 - repeated :repeated_uint32, :uint32, 23 - repeated :repeated_uint64, :uint64, 24 - repeated :repeated_bool, :bool, 25 - repeated :repeated_double, :double, 26 - repeated :repeated_float, :float, 27 - repeated :repeated_string, :string, 28 - repeated :repeated_bytes, :bytes, 29 - repeated :repeated_enum, :enum, 30, "A.B.C.TestEnum" - repeated :repeated_msg, :message, 31, "A.B.C.TestMessage" - map :map_int32_string, :int32, :string, 61 - map :map_int64_string, :int64, :string, 62 - map :map_uint32_string, :uint32, :string, 63 - map :map_uint64_string, :uint64, :string, 64 - map :map_bool_string, :bool, :string, 65 - map :map_string_string, :string, :string, 66 - map :map_string_msg, :string, :message, 67, "A.B.C.TestMessage" - map :map_string_enum, :string, :enum, 68, "A.B.C.TestEnum" - map :map_string_int32, :string, :int32, 69 - map :map_string_bool, :string, :bool, 70 - optional :nested_message, :message, 80, "A.B.C.TestMessage.NestedMessage" - oneof :my_oneof do - optional :oneof_int32, :int32, 41 - optional :oneof_int64, :int64, 42 - optional :oneof_uint32, :uint32, 43 - optional :oneof_uint64, :uint64, 44 - optional :oneof_bool, :bool, 45 - optional :oneof_double, :double, 46 - optional :oneof_float, :float, 47 - optional :oneof_string, :string, 48 - optional :oneof_bytes, :bytes, 49 - optional :oneof_enum, :enum, 50, "A.B.C.TestEnum" - optional :oneof_msg, :message, 51, "A.B.C.TestMessage" + add_file("ruby_generated_code.proto", :syntax => :proto3) do + add_message "A.B.C.TestMessage" do + optional :optional_int32, :int32, 1 + optional :optional_int64, :int64, 2 + optional :optional_uint32, :uint32, 3 + optional :optional_uint64, :uint64, 4 + optional :optional_bool, :bool, 5 + optional :optional_double, :double, 6 + optional :optional_float, :float, 7 + optional :optional_string, :string, 8 + optional :optional_bytes, :bytes, 9 + optional :optional_enum, :enum, 10, "A.B.C.TestEnum" + optional :optional_msg, :message, 11, "A.B.C.TestMessage" + repeated :repeated_int32, :int32, 21 + repeated :repeated_int64, :int64, 22 + repeated :repeated_uint32, :uint32, 23 + repeated :repeated_uint64, :uint64, 24 + repeated :repeated_bool, :bool, 25 + repeated :repeated_double, :double, 26 + repeated :repeated_float, :float, 27 + repeated :repeated_string, :string, 28 + repeated :repeated_bytes, :bytes, 29 + repeated :repeated_enum, :enum, 30, "A.B.C.TestEnum" + repeated :repeated_msg, :message, 31, "A.B.C.TestMessage" + map :map_int32_string, :int32, :string, 61 + map :map_int64_string, :int64, :string, 62 + map :map_uint32_string, :uint32, :string, 63 + map :map_uint64_string, :uint64, :string, 64 + map :map_bool_string, :bool, :string, 65 + map :map_string_string, :string, :string, 66 + map :map_string_msg, :string, :message, 67, "A.B.C.TestMessage" + map :map_string_enum, :string, :enum, 68, "A.B.C.TestEnum" + map :map_string_int32, :string, :int32, 69 + map :map_string_bool, :string, :bool, 70 + optional :nested_message, :message, 80, "A.B.C.TestMessage.NestedMessage" + oneof :my_oneof do + optional :oneof_int32, :int32, 41 + optional :oneof_int64, :int64, 42 + optional :oneof_uint32, :uint32, 43 + optional :oneof_uint64, :uint64, 44 + optional :oneof_bool, :bool, 45 + optional :oneof_double, :double, 46 + optional :oneof_float, :float, 47 + optional :oneof_string, :string, 48 + optional :oneof_bytes, :bytes, 49 + optional :oneof_enum, :enum, 50, "A.B.C.TestEnum" + optional :oneof_msg, :message, 51, "A.B.C.TestMessage" + end + end + add_message "A.B.C.TestMessage.NestedMessage" do + optional :foo, :int32, 1 + end + add_enum "A.B.C.TestEnum" do + value :Default, 0 + value :A, 1 + value :B, 2 + value :C, 3 end - end - add_message "A.B.C.TestMessage.NestedMessage" do - optional :foo, :int32, 1 - end - add_enum "A.B.C.TestEnum" do - value :Default, 0 - value :A, 1 - value :B, 2 - value :C, 3 end end diff --git a/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_code_proto2.proto b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_code_proto2.proto new file mode 100644 index 00000000..8d3cc13e --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_code_proto2.proto @@ -0,0 +1,68 @@ +syntax = "proto2"; + +package A.B.C; + +message TestMessage { + optional int32 optional_int32 = 1 [default = 1]; + optional int64 optional_int64 = 2 [default = 2]; + optional uint32 optional_uint32 = 3 [default = 3]; + optional uint64 optional_uint64 = 4 [default = 4]; + optional bool optional_bool = 5 [default = true]; + optional double optional_double = 6 [default = 6.0]; + optional float optional_float = 7 [default = 7.0]; + optional string optional_string = 8 [default = "default str"]; + optional bytes optional_bytes = 9 [default = "\0\1\2\100fubar"]; + optional TestEnum optional_enum = 10 [default = A]; + optional TestMessage optional_msg = 11; + + repeated int32 repeated_int32 = 21; + repeated int64 repeated_int64 = 22; + repeated uint32 repeated_uint32 = 23; + repeated uint64 repeated_uint64 = 24; + repeated bool repeated_bool = 25; + repeated double repeated_double = 26; + repeated float repeated_float = 27; + repeated string repeated_string = 28; + repeated bytes repeated_bytes = 29; + repeated TestEnum repeated_enum = 30; + repeated TestMessage repeated_msg = 31; + + required int32 required_int32 = 41; + required int64 required_int64 = 42; + required uint32 required_uint32 = 43; + required uint64 required_uint64 = 44; + required bool required_bool = 45; + required double required_double = 46; + required float required_float = 47; + required string required_string = 48; + required bytes required_bytes = 49; + required TestEnum required_enum = 50; + required TestMessage required_msg = 51; + + oneof my_oneof { + int32 oneof_int32 = 61; + int64 oneof_int64 = 62; + uint32 oneof_uint32 = 63; + uint64 oneof_uint64 = 64; + bool oneof_bool = 65; + double oneof_double = 66; + float oneof_float = 67; + string oneof_string = 68; + bytes oneof_bytes = 69; + TestEnum oneof_enum = 70; + TestMessage oneof_msg = 71; + } + + message NestedMessage { + optional int32 foo = 1; + } + + optional NestedMessage nested_message = 80; +} + +enum TestEnum { + Default = 0; + A = 1; + B = 2; + C = 3; +} diff --git a/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_code_proto2_pb.rb b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_code_proto2_pb.rb new file mode 100644 index 00000000..15b340ad --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_code_proto2_pb.rb @@ -0,0 +1,77 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: ruby_generated_code_proto2.proto + +require 'google/protobuf' + +Google::Protobuf::DescriptorPool.generated_pool.build do + add_file("ruby_generated_code_proto2.proto", :syntax => :proto2) do + add_message "A.B.C.TestMessage" do + optional :optional_int32, :int32, 1, default: 1 + optional :optional_int64, :int64, 2, default: 2 + optional :optional_uint32, :uint32, 3, default: 3 + optional :optional_uint64, :uint64, 4, default: 4 + optional :optional_bool, :bool, 5, default: true + optional :optional_double, :double, 6, default: 6 + optional :optional_float, :float, 7, default: 7 + optional :optional_string, :string, 8, default: "default str" + optional :optional_bytes, :bytes, 9, default: "\x00\x01\x02\x40\x66\x75\x62\x61\x72".force_encoding("ASCII-8BIT") + optional :optional_enum, :enum, 10, "A.B.C.TestEnum", default: 1 + optional :optional_msg, :message, 11, "A.B.C.TestMessage" + repeated :repeated_int32, :int32, 21 + repeated :repeated_int64, :int64, 22 + repeated :repeated_uint32, :uint32, 23 + repeated :repeated_uint64, :uint64, 24 + repeated :repeated_bool, :bool, 25 + repeated :repeated_double, :double, 26 + repeated :repeated_float, :float, 27 + repeated :repeated_string, :string, 28 + repeated :repeated_bytes, :bytes, 29 + repeated :repeated_enum, :enum, 30, "A.B.C.TestEnum" + repeated :repeated_msg, :message, 31, "A.B.C.TestMessage" + required :required_int32, :int32, 41 + required :required_int64, :int64, 42 + required :required_uint32, :uint32, 43 + required :required_uint64, :uint64, 44 + required :required_bool, :bool, 45 + required :required_double, :double, 46 + required :required_float, :float, 47 + required :required_string, :string, 48 + required :required_bytes, :bytes, 49 + required :required_enum, :enum, 50, "A.B.C.TestEnum" + required :required_msg, :message, 51, "A.B.C.TestMessage" + optional :nested_message, :message, 80, "A.B.C.TestMessage.NestedMessage" + oneof :my_oneof do + optional :oneof_int32, :int32, 61 + optional :oneof_int64, :int64, 62 + optional :oneof_uint32, :uint32, 63 + optional :oneof_uint64, :uint64, 64 + optional :oneof_bool, :bool, 65 + optional :oneof_double, :double, 66 + optional :oneof_float, :float, 67 + optional :oneof_string, :string, 68 + optional :oneof_bytes, :bytes, 69 + optional :oneof_enum, :enum, 70, "A.B.C.TestEnum" + optional :oneof_msg, :message, 71, "A.B.C.TestMessage" + end + end + add_message "A.B.C.TestMessage.NestedMessage" do + optional :foo, :int32, 1 + end + add_enum "A.B.C.TestEnum" do + value :Default, 0 + value :A, 1 + value :B, 2 + value :C, 3 + end + end +end + +module A + module B + module C + TestMessage = Google::Protobuf::DescriptorPool.generated_pool.lookup("A.B.C.TestMessage").msgclass + TestMessage::NestedMessage = Google::Protobuf::DescriptorPool.generated_pool.lookup("A.B.C.TestMessage.NestedMessage").msgclass + TestEnum = Google::Protobuf::DescriptorPool.generated_pool.lookup("A.B.C.TestEnum").enummodule + end + end +end diff --git a/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit.proto b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit.proto new file mode 100644 index 00000000..8d7c948a --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit.proto @@ -0,0 +1,9 @@ +syntax = "proto3"; + +package one.two.a_three; + +option ruby_package = "A::B::C"; + +message Four { + string a_string = 1; +} diff --git a/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy.proto b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy.proto new file mode 100644 index 00000000..7a0d2608 --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy.proto @@ -0,0 +1,9 @@ +syntax = "proto3"; + +package one.two.a_three.and; + +option ruby_package = "AA.BB.CC"; + +message Four { + string another_string = 1; +} diff --git a/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy_pb.rb b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy_pb.rb new file mode 100644 index 00000000..74f3bf3d --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy_pb.rb @@ -0,0 +1,20 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: ruby_generated_pkg_explicit_legacy.proto + +require 'google/protobuf' + +Google::Protobuf::DescriptorPool.generated_pool.build do + add_file("ruby_generated_pkg_explicit_legacy.proto", :syntax => :proto3) do + add_message "one.two.a_three.and.Four" do + optional :another_string, :string, 1 + end + end +end + +module AA + module BB + module CC + Four = Google::Protobuf::DescriptorPool.generated_pool.lookup("one.two.a_three.and.Four").msgclass + end + end +end diff --git a/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_pb.rb b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_pb.rb new file mode 100644 index 00000000..24ff21e1 --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_pb.rb @@ -0,0 +1,20 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: ruby_generated_pkg_explicit.proto + +require 'google/protobuf' + +Google::Protobuf::DescriptorPool.generated_pool.build do + add_file("ruby_generated_pkg_explicit.proto", :syntax => :proto3) do + add_message "one.two.a_three.Four" do + optional :a_string, :string, 1 + end + end +end + +module A + module B + module C + Four = Google::Protobuf::DescriptorPool.generated_pool.lookup("one.two.a_three.Four").msgclass + end + end +end diff --git a/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_implicit.proto b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_implicit.proto new file mode 100644 index 00000000..544db64d --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_implicit.proto @@ -0,0 +1,7 @@ +syntax = "proto3"; + +package one.two.a_three; + +message Four { + string a_string = 1; +} diff --git a/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_implicit_pb.rb b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_implicit_pb.rb new file mode 100644 index 00000000..3a1dd67d --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_implicit_pb.rb @@ -0,0 +1,20 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: ruby_generated_pkg_implicit.proto + +require 'google/protobuf' + +Google::Protobuf::DescriptorPool.generated_pool.build do + add_file("ruby_generated_pkg_implicit.proto", :syntax => :proto3) do + add_message "one.two.a_three.Four" do + optional :a_string, :string, 1 + end + end +end + +module One + module Two + module AThree + Four = Google::Protobuf::DescriptorPool.generated_pool.lookup("one.two.a_three.Four").msgclass + end + end +end diff --git a/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generator.cc b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generator.cc index bd737c02..23091c8f 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generator.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generator.cc @@ -28,6 +28,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#include #include #include @@ -45,24 +46,22 @@ namespace compiler { namespace ruby { // Forward decls. -std::string IntToString(int32 value); +template +std::string NumberToString(numeric_type value); std::string GetRequireName(const std::string& proto_file); -std::string LabelForField(google::protobuf::FieldDescriptor* field); -std::string TypeName(google::protobuf::FieldDescriptor* field); -void GenerateMessage(const google::protobuf::Descriptor* message, - google::protobuf::io::Printer* printer); -void GenerateEnum(const google::protobuf::EnumDescriptor* en, - google::protobuf::io::Printer* printer); -void GenerateMessageAssignment( - const std::string& prefix, - const google::protobuf::Descriptor* message, - google::protobuf::io::Printer* printer); -void GenerateEnumAssignment( - const std::string& prefix, - const google::protobuf::EnumDescriptor* en, - google::protobuf::io::Printer* printer); +std::string LabelForField(FieldDescriptor* field); +std::string TypeName(FieldDescriptor* field); +bool GenerateMessage(const Descriptor* message, io::Printer* printer, + std::string* error); +void GenerateEnum(const EnumDescriptor* en, io::Printer* printer); +void GenerateMessageAssignment(const std::string& prefix, + const Descriptor* message, io::Printer* printer); +void GenerateEnumAssignment(const std::string& prefix, const EnumDescriptor* en, + io::Printer* printer); +std::string DefaultValueForField(const FieldDescriptor* field); -std::string IntToString(int32 value) { +template +std::string NumberToString(numeric_type value) { std::ostringstream os; os << value; return os.str(); @@ -77,7 +76,7 @@ std::string GetOutputFilename(const std::string& proto_file) { return GetRequireName(proto_file) + ".rb"; } -std::string LabelForField(const google::protobuf::FieldDescriptor* field) { +std::string LabelForField(const FieldDescriptor* field) { switch (field->label()) { case FieldDescriptor::LABEL_OPTIONAL: return "optional"; case FieldDescriptor::LABEL_REQUIRED: return "required"; @@ -86,7 +85,7 @@ std::string LabelForField(const google::protobuf::FieldDescriptor* field) { } } -std::string TypeName(const google::protobuf::FieldDescriptor* field) { +std::string TypeName(const FieldDescriptor* field) { switch (field->type()) { case FieldDescriptor::TYPE_INT32: return "int32"; case FieldDescriptor::TYPE_INT64: return "int64"; @@ -110,9 +109,63 @@ std::string TypeName(const google::protobuf::FieldDescriptor* field) { } } -void GenerateField(const google::protobuf::FieldDescriptor* field, - google::protobuf::io::Printer* printer) { +string StringifySyntax(FileDescriptor::Syntax syntax) { + switch (syntax) { + case FileDescriptor::SYNTAX_PROTO2: + return "proto2"; + case FileDescriptor::SYNTAX_PROTO3: + return "proto3"; + case FileDescriptor::SYNTAX_UNKNOWN: + default: + GOOGLE_LOG(FATAL) << "Unsupported syntax; this generator only supports " + "proto2 and proto3 syntax."; + return ""; + } +} +std::string DefaultValueForField(const FieldDescriptor* field) { + switch(field->cpp_type()) { + case FieldDescriptor::CPPTYPE_INT32: + return NumberToString(field->default_value_int32()); + case FieldDescriptor::CPPTYPE_INT64: + return NumberToString(field->default_value_int64()); + case FieldDescriptor::CPPTYPE_UINT32: + return NumberToString(field->default_value_uint32()); + case FieldDescriptor::CPPTYPE_UINT64: + return NumberToString(field->default_value_uint64()); + case FieldDescriptor::CPPTYPE_FLOAT: + return NumberToString(field->default_value_float()); + case FieldDescriptor::CPPTYPE_DOUBLE: + return NumberToString(field->default_value_double()); + case FieldDescriptor::CPPTYPE_BOOL: + return field->default_value_bool() ? "true" : "false"; + case FieldDescriptor::CPPTYPE_ENUM: + return NumberToString(field->default_value_enum()->number()); + case FieldDescriptor::CPPTYPE_STRING: { + std::ostringstream os; + string default_str = field->default_value_string(); + + if (field->type() == FieldDescriptor::TYPE_STRING) { + os << "\"" << default_str << "\""; + } else if (field->type() == FieldDescriptor::TYPE_BYTES) { + os << "\""; + + os.fill('0'); + for (int i = 0; i < default_str.length(); ++i) { + // Write the hex form of each byte. + os << "\\x" << std::hex << std::setw(2) + << ((uint16)((unsigned char)default_str.at(i))); + } + os << "\".force_encoding(\"ASCII-8BIT\")"; + } + + return os.str(); + } + default: assert(false); return ""; + } +} + +void GenerateField(const FieldDescriptor* field, io::Printer* printer) { if (field->is_map()) { const FieldDescriptor* key_field = field->message_type()->FindFieldByNumber(1); @@ -124,7 +177,7 @@ void GenerateField(const google::protobuf::FieldDescriptor* field, "name", field->name(), "key_type", TypeName(key_field), "value_type", TypeName(value_field), - "number", IntToString(field->number())); + "number", NumberToString(field->number())); if (value_field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { printer->Print( @@ -146,24 +199,28 @@ void GenerateField(const google::protobuf::FieldDescriptor* field, printer->Print( ":$type$, $number$", "type", TypeName(field), - "number", IntToString(field->number())); + "number", NumberToString(field->number())); if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { printer->Print( - ", \"$subtype$\"\n", + ", \"$subtype$\"", "subtype", field->message_type()->full_name()); } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { printer->Print( - ", \"$subtype$\"\n", + ", \"$subtype$\"", "subtype", field->enum_type()->full_name()); - } else { - printer->Print("\n"); } + + if (field->has_default_value()) { + printer->Print(", default: $default$", "default", + DefaultValueForField(field)); + } + + printer->Print("\n"); } } -void GenerateOneof(const google::protobuf::OneofDescriptor* oneof, - google::protobuf::io::Printer* printer) { +void GenerateOneof(const OneofDescriptor* oneof, io::Printer* printer) { printer->Print( "oneof :$name$ do\n", "name", oneof->name()); @@ -178,13 +235,17 @@ void GenerateOneof(const google::protobuf::OneofDescriptor* oneof, printer->Print("end\n"); } -void GenerateMessage(const google::protobuf::Descriptor* message, - google::protobuf::io::Printer* printer) { +bool GenerateMessage(const Descriptor* message, io::Printer* printer, + std::string* error) { + if (message->extension_range_count() > 0 || message->extension_count() > 0) { + *error = "Extensions are not yet supported for proto2 .proto files."; + return false; + } // Don't generate MapEntry messages -- we use the Ruby extension's native // support for map fields instead. if (message->options().map_entry()) { - return; + return true; } printer->Print( @@ -208,15 +269,18 @@ void GenerateMessage(const google::protobuf::Descriptor* message, printer->Print("end\n"); for (int i = 0; i < message->nested_type_count(); i++) { - GenerateMessage(message->nested_type(i), printer); + if (!GenerateMessage(message->nested_type(i), printer, error)) { + return false; + } } for (int i = 0; i < message->enum_type_count(); i++) { GenerateEnum(message->enum_type(i), printer); } + + return true; } -void GenerateEnum(const google::protobuf::EnumDescriptor* en, - google::protobuf::io::Printer* printer) { +void GenerateEnum(const EnumDescriptor* en, io::Printer* printer) { printer->Print( "add_enum \"$name$\" do\n", "name", en->full_name()); @@ -227,7 +291,7 @@ void GenerateEnum(const google::protobuf::EnumDescriptor* en, printer->Print( "value :$name$, $number$\n", "name", value->name(), - "number", IntToString(value->number())); + "number", NumberToString(value->number())); } printer->Outdent(); @@ -242,7 +306,7 @@ bool IsUpper(char ch) { return ch >= 'A' && ch <= 'Z'; } bool IsAlpha(char ch) { return IsLower(ch) || IsUpper(ch); } -char ToUpper(char ch) { return IsLower(ch) ? (ch - 'a' + 'A') : ch; } +char UpperChar(char ch) { return IsLower(ch) ? (ch - 'a' + 'A') : ch; } // Package names in protobuf are snake_case by convention, but Ruby module @@ -259,7 +323,7 @@ std::string PackageToModule(const std::string& name) { next_upper = true; } else { if (next_upper) { - result.push_back(ToUpper(name[i])); + result.push_back(UpperChar(name[i])); } else { result.push_back(name[i]); } @@ -279,7 +343,7 @@ std::string RubifyConstant(const std::string& name) { if (!ret.empty()) { if (IsLower(ret[0])) { // If it starts with a lowercase letter, capitalize it. - ret[0] = ToUpper(ret[0]); + ret[0] = UpperChar(ret[0]); } else if (!IsAlpha(ret[0])) { // Otherwise (e.g. if it begins with an underscore), we need to come up // with some prefix that starts with a capital letter. We could be smarter @@ -293,11 +357,9 @@ std::string RubifyConstant(const std::string& name) { return ret; } -void GenerateMessageAssignment( - const std::string& prefix, - const google::protobuf::Descriptor* message, - google::protobuf::io::Printer* printer) { - +void GenerateMessageAssignment(const std::string& prefix, + const Descriptor* message, + io::Printer* printer) { // Don't generate MapEntry messages -- we use the Ruby extension's native // support for map fields instead. if (message->options().map_entry()) { @@ -313,7 +375,7 @@ void GenerateMessageAssignment( "lookup(\"$full_name$\").msgclass\n", "full_name", message->full_name()); - std::string nested_prefix = prefix + message->name() + "::"; + std::string nested_prefix = prefix + RubifyConstant(message->name()) + "::"; for (int i = 0; i < message->nested_type_count(); i++) { GenerateMessageAssignment(nested_prefix, message->nested_type(i), printer); } @@ -322,10 +384,8 @@ void GenerateMessageAssignment( } } -void GenerateEnumAssignment( - const std::string& prefix, - const google::protobuf::EnumDescriptor* en, - google::protobuf::io::Printer* printer) { +void GenerateEnumAssignment(const std::string& prefix, const EnumDescriptor* en, + io::Printer* printer) { printer->Print( "$prefix$$name$ = ", "prefix", prefix, @@ -336,30 +396,45 @@ void GenerateEnumAssignment( "full_name", en->full_name()); } -int GeneratePackageModules( - const FileDescriptor* file, - google::protobuf::io::Printer* printer) { +int GeneratePackageModules(const FileDescriptor* file, io::Printer* printer) { int levels = 0; - bool need_change_to_module; + bool need_change_to_module = true; std::string package_name; + // Determine the name to use in either format: + // proto package: one.two.three + // option ruby_package: One::Two::Three if (file->options().has_ruby_package()) { package_name = file->options().ruby_package(); - need_change_to_module = false; + + // If :: is in the package use the Ruby formated name as-is + // -> A::B::C + // otherwise, use the dot seperator + // -> A.B.C + if (package_name.find("::") != std::string::npos) { + need_change_to_module = false; + } else { + GOOGLE_LOG(WARNING) << "ruby_package option should be in the form of:" + << " 'A::B::C' and not 'A.B.C'"; + } } else { package_name = file->package(); - need_change_to_module = true; } + // Use the appropriate delimter + string delimiter = need_change_to_module ? "." : "::"; + int delimiter_size = need_change_to_module ? 1 : 2; + + // Extract each module name and indent while (!package_name.empty()) { - size_t dot_index = package_name.find("."); + size_t dot_index = package_name.find(delimiter); string component; if (dot_index == string::npos) { component = package_name; package_name = ""; } else { component = package_name.substr(0, dot_index); - package_name = package_name.substr(dot_index + 1); + package_name = package_name.substr(dot_index + delimiter_size); } if (need_change_to_module) { component = PackageToModule(component); @@ -373,9 +448,7 @@ int GeneratePackageModules( return levels; } -void EndPackageModules( - int levels, - google::protobuf::io::Printer* printer) { +void EndPackageModules(int levels, io::Printer* printer) { while (levels > 0) { levels--; printer->Outdent(); @@ -423,7 +496,8 @@ bool MaybeEmitDependency(const FileDescriptor* import, const FileDescriptor* from, io::Printer* printer, string* error) { - if (import->syntax() == FileDescriptor::SYNTAX_PROTO2) { + if (from->syntax() == FileDescriptor::SYNTAX_PROTO3 && + import->syntax() == FileDescriptor::SYNTAX_PROTO2) { for (int i = 0; i < from->message_type_count(); i++) { if (UsesTypeFromFile(from->message_type(i), import, error)) { // Error text was already set by UsesTypeFromFile(). @@ -462,16 +536,29 @@ bool GenerateFile(const FileDescriptor* file, io::Printer* printer, } } - printer->Print( - "Google::Protobuf::DescriptorPool.generated_pool.build do\n"); + // TODO: Remove this when ruby supports extensions for proto2 syntax. + if (file->extension_count() > 0) { + *error = "Extensions are not yet supported for proto2 .proto files."; + return false; + } + + printer->Print("Google::Protobuf::DescriptorPool.generated_pool.build do\n"); + printer->Indent(); + printer->Print("add_file(\"$filename$\", :syntax => :$syntax$) do\n", + "filename", file->name(), "syntax", + StringifySyntax(file->syntax())); printer->Indent(); for (int i = 0; i < file->message_type_count(); i++) { - GenerateMessage(file->message_type(i), printer); + if (!GenerateMessage(file->message_type(i), printer, error)) { + return false; + } } for (int i = 0; i < file->enum_type_count(); i++) { GenerateEnum(file->enum_type(i), printer); } printer->Outdent(); + printer->Print("end\n"); + printer->Outdent(); printer->Print( "end\n\n"); @@ -492,10 +579,9 @@ bool Generator::Generate( GeneratorContext* generator_context, string* error) const { - if (file->syntax() != FileDescriptor::SYNTAX_PROTO3) { - *error = - "Can only generate Ruby code for proto3 .proto files.\n" - "Please add 'syntax = \"proto3\";' to the top of your .proto file.\n"; + if (file->syntax() != FileDescriptor::SYNTAX_PROTO3 && + file->syntax() != FileDescriptor::SYNTAX_PROTO2) { + *error = "Invalid or unsupported proto syntax"; return false; } diff --git a/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generator.h b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generator.h index 8c1dfa26..731a81a5 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generator.h +++ b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generator.h @@ -37,6 +37,8 @@ #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -46,8 +48,7 @@ namespace ruby { // If you create your own protocol compiler binary and you want it to support // Ruby output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT Generator - : public google::protobuf::compiler::CodeGenerator { +class PROTOC_EXPORT Generator : public CodeGenerator { virtual bool Generate( const FileDescriptor* file, const string& parameter, @@ -60,5 +61,7 @@ class LIBPROTOC_EXPORT Generator } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_RUBY_GENERATOR_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generator_unittest.cc b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generator_unittest.cc index 1aabe8aa..d93a68d9 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generator_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/ruby/ruby_generator_unittest.cc @@ -29,6 +29,7 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include +#include #include #include @@ -56,7 +57,7 @@ string FindRubyTestDir() { // Some day, we may integrate build systems between protoc and the language // extensions to the point where we can do this test in a more automated way. -TEST(RubyGeneratorTest, GeneratorTest) { +void RubyTest(string proto_file) { string ruby_tests = FindRubyTestDir(); google::protobuf::compiler::CommandLineInterface cli; @@ -68,40 +69,61 @@ TEST(RubyGeneratorTest, GeneratorTest) { // Copy generated_code.proto to the temporary test directory. string test_input; GOOGLE_CHECK_OK(File::GetContents( - ruby_tests + "/ruby_generated_code.proto", + ruby_tests + proto_file + ".proto", &test_input, true)); GOOGLE_CHECK_OK(File::SetContents( - TestTempDir() + "/ruby_generated_code.proto", + TestTempDir() + proto_file + ".proto", test_input, true)); // Invoke the proto compiler (we will be inside TestTempDir() at this point). string ruby_out = "--ruby_out=" + TestTempDir(); string proto_path = "--proto_path=" + TestTempDir(); + string proto_target = TestTempDir() + proto_file + ".proto"; const char* argv[] = { "protoc", ruby_out.c_str(), proto_path.c_str(), - "ruby_generated_code.proto", + proto_target.c_str(), }; EXPECT_EQ(0, cli.Run(4, argv)); // Load the generated output and compare to the expected result. string output; - GOOGLE_CHECK_OK(File::GetContents( - TestTempDir() + "/ruby_generated_code_pb.rb", + GOOGLE_CHECK_OK(File::GetContentsAsText( + TestTempDir() + proto_file + "_pb.rb", &output, true)); string expected_output; - GOOGLE_CHECK_OK(File::GetContents( - ruby_tests + "/ruby_generated_code_pb.rb", + GOOGLE_CHECK_OK(File::GetContentsAsText( + ruby_tests + proto_file + "_pb.rb", &expected_output, true)); EXPECT_EQ(expected_output, output); } +TEST(RubyGeneratorTest, Proto3GeneratorTest) { + RubyTest("/ruby_generated_code"); +} + +TEST(RubyGeneratorTest, Proto2GeneratorTest) { + RubyTest("/ruby_generated_code_proto2"); +} + +TEST(RubyGeneratorTest, Proto3ImplicitPackageTest) { + RubyTest("/ruby_generated_pkg_implicit"); +} + +TEST(RubyGeneratorTest, Proto3ExplictPackageTest) { + RubyTest("/ruby_generated_pkg_explicit"); +} + +TEST(RubyGeneratorTest, Proto3ExplictLegacyPackageTest) { + RubyTest("/ruby_generated_pkg_explicit_legacy"); +} + } // namespace } // namespace ruby } // namespace compiler diff --git a/third_party/protobuf/src/google/protobuf/compiler/scc.h b/third_party/protobuf/src/google/protobuf/compiler/scc.h new file mode 100644 index 00000000..a1394602 --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/compiler/scc.h @@ -0,0 +1,164 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#ifndef GOOGLE_PROTOBUF_COMPILER_SCC_H__ +#define GOOGLE_PROTOBUF_COMPILER_SCC_H__ + +#include + +#include +#include +#include + +#include + +namespace google { +namespace protobuf { +namespace compiler { + +// Description of each strongly connected component. Note that the order +// of both the descriptors in this SCC and the order of children is +// deterministic. +struct SCC { + std::vector descriptors; + std::vector children; + + const Descriptor* GetRepresentative() const { return descriptors[0]; } + + // All messages must necessarily be in the same file. + const FileDescriptor* GetFile() const { return descriptors[0]->file(); } +}; + +// This class is used for analyzing the SCC for each message, to ensure linear +// instead of quadratic performance, if we do this per message we would get +// O(V*(V+E)). +template +class PROTOC_EXPORT SCCAnalyzer { + public: + explicit SCCAnalyzer() : index_(0) {} + + const SCC* GetSCC(const Descriptor* descriptor) { + if (cache_.count(descriptor)) return cache_[descriptor].scc; + return DFS(descriptor).scc; + } + + private: + struct NodeData { + const SCC* scc; // if null it means its still on the stack + int index; + int lowlink; + }; + + std::map cache_; + std::vector stack_; + int index_; + std::vector> garbage_bin_; + + SCC* CreateSCC() { + garbage_bin_.emplace_back(new SCC()); + return garbage_bin_.back().get(); + } + + // Tarjan's Strongly Connected Components algo + NodeData DFS(const Descriptor* descriptor) { + // Must not have visited already. + GOOGLE_DCHECK_EQ(cache_.count(descriptor), 0); + + // Mark visited by inserting in map. + NodeData& result = cache_[descriptor]; + // Initialize data structures. + result.index = result.lowlink = index_++; + stack_.push_back(descriptor); + + // Recurse the fields / nodes in graph + for (auto dep : DepsGenerator()(descriptor)) { + GOOGLE_CHECK(dep); + if (cache_.count(dep) == 0) { + // unexplored node + NodeData child_data = DFS(dep); + result.lowlink = std::min(result.lowlink, child_data.lowlink); + } else { + NodeData child_data = cache_[dep]; + if (child_data.scc == nullptr) { + // Still in the stack_ so we found a back edge + result.lowlink = std::min(result.lowlink, child_data.index); + } + } + } + if (result.index == result.lowlink) { + // This is the root of a strongly connected component + SCC* scc = CreateSCC(); + while (true) { + const Descriptor* scc_desc = stack_.back(); + scc->descriptors.push_back(scc_desc); + // Remove from stack + stack_.pop_back(); + cache_[scc_desc].scc = scc; + + if (scc_desc == descriptor) break; + } + + // The order of descriptors is random and depends how this SCC was + // discovered. In-order to ensure maximum stability we sort it by name. + std::sort(scc->descriptors.begin(), scc->descriptors.end(), + [](const Descriptor* a, const Descriptor* b) { + return a->full_name() < b->full_name(); + }); + AddChildren(scc); + } + return result; + } + + // Add the SCC's that are children of this SCC to its children. + void AddChildren(SCC* scc) { + std::set seen; + for (auto descriptor : scc->descriptors) { + for (auto child_msg : DepsGenerator()(descriptor)) { + GOOGLE_CHECK(child_msg); + const SCC* child = GetSCC(child_msg); + if (child == scc) continue; + if (seen.insert(child).second) { + scc->children.push_back(child); + } + } + } + } + + // This is necessary for compiler bug in msvc2015. + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SCCAnalyzer); +}; + +} // namespace compiler +} // namespace protobuf +} // namespace google + +#include + +#endif // GOOGLE_PROTOBUF_COMPILER_SCC_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/subprocess.cc b/third_party/protobuf/src/google/protobuf/compiler/subprocess.cc index 2e5a89ac..b920b2dd 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/subprocess.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/subprocess.cc @@ -38,9 +38,9 @@ #ifndef _WIN32 #include +#include #include #include -#include #endif #include @@ -54,7 +54,7 @@ namespace compiler { namespace { char* portable_strdup(const char* s) { - char* ns = (char*) malloc(strlen(s) + 1); + char* ns = (char*)malloc(strlen(s) + 1); if (ns != NULL) { strcpy(ns, s); } @@ -73,7 +73,9 @@ static void CloseHandleOrDie(HANDLE handle) { Subprocess::Subprocess() : process_start_error_(ERROR_SUCCESS), - child_handle_(NULL), child_stdin_(NULL), child_stdout_(NULL) {} + child_handle_(NULL), + child_stdin_(NULL), + child_stdout_(NULL) {} Subprocess::~Subprocess() { if (child_stdin_ != NULL) { @@ -84,7 +86,7 @@ Subprocess::~Subprocess() { } } -void Subprocess::Start(const string& program, SearchMode search_mode) { +void Subprocess::Start(const std::string& program, SearchMode search_mode) { // Create the pipes. HANDLE stdin_pipe_read; HANDLE stdin_pipe_write; @@ -99,13 +101,13 @@ void Subprocess::Start(const string& program, SearchMode search_mode) { } // Make child side of the pipes inheritable. - if (!SetHandleInformation(stdin_pipe_read, - HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) { + if (!SetHandleInformation(stdin_pipe_read, HANDLE_FLAG_INHERIT, + HANDLE_FLAG_INHERIT)) { GOOGLE_LOG(FATAL) << "SetHandleInformation: " << Win32ErrorMessage(GetLastError()); } - if (!SetHandleInformation(stdout_pipe_write, - HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) { + if (!SetHandleInformation(stdout_pipe_write, HANDLE_FLAG_INHERIT, + HANDLE_FLAG_INHERIT)) { GOOGLE_LOG(FATAL) << "SetHandleInformation: " << Win32ErrorMessage(GetLastError()); } @@ -120,26 +122,27 @@ void Subprocess::Start(const string& program, SearchMode search_mode) { startup_info.hStdError = GetStdHandle(STD_ERROR_HANDLE); if (startup_info.hStdError == INVALID_HANDLE_VALUE) { - GOOGLE_LOG(FATAL) << "GetStdHandle: " - << Win32ErrorMessage(GetLastError()); + GOOGLE_LOG(FATAL) << "GetStdHandle: " << Win32ErrorMessage(GetLastError()); } - // CreateProcess() mutates its second parameter. WTF? - char* name_copy = portable_strdup(program.c_str()); + // Invoking cmd.exe allows for '.bat' files from the path as well as '.exe'. + // Using a malloc'ed string because CreateProcess() can mutate its second + // parameter. + char* command_line = + portable_strdup(("cmd.exe /c \"" + program + "\"").c_str()); // Create the process. PROCESS_INFORMATION process_info; if (CreateProcessA((search_mode == SEARCH_PATH) ? NULL : program.c_str(), - (search_mode == SEARCH_PATH) ? name_copy : NULL, + (search_mode == SEARCH_PATH) ? command_line : NULL, NULL, // process security attributes NULL, // thread security attributes TRUE, // inherit handles? 0, // obscure creation flags NULL, // environment (inherit from parent) NULL, // current directory (inherit from parent) - &startup_info, - &process_info)) { + &startup_info, &process_info)) { child_handle_ = process_info.hProcess; CloseHandleOrDie(process_info.hThread); child_stdin_ = stdin_pipe_write; @@ -152,11 +155,11 @@ void Subprocess::Start(const string& program, SearchMode search_mode) { CloseHandleOrDie(stdin_pipe_read); CloseHandleOrDie(stdout_pipe_write); - free(name_copy); + free(command_line); } bool Subprocess::Communicate(const Message& input, Message* output, - string* error) { + std::string* error) { if (process_start_error_ != ERROR_SUCCESS) { *error = Win32ErrorMessage(process_start_error_); return false; @@ -164,8 +167,8 @@ bool Subprocess::Communicate(const Message& input, Message* output, GOOGLE_CHECK(child_handle_ != NULL) << "Must call Start() first."; - string input_data = input.SerializeAsString(); - string output_data; + std::string input_data = input.SerializeAsString(); + std::string output_data; int input_pos = 0; @@ -197,10 +200,8 @@ bool Subprocess::Communicate(const Message& input, Message* output, if (signaled_handle == child_stdin_) { DWORD n; - if (!WriteFile(child_stdin_, - input_data.data() + input_pos, - input_data.size() - input_pos, - &n, NULL)) { + if (!WriteFile(child_stdin_, input_data.data() + input_pos, + input_data.size() - input_pos, &n, NULL)) { // Child closed pipe. Presumably it will report an error later. // Pretend we're done for now. input_pos = input_data.size(); @@ -254,8 +255,8 @@ bool Subprocess::Communicate(const Message& input, Message* output, child_handle_ = NULL; if (exit_code != 0) { - *error = strings::Substitute( - "Plugin failed with status code $0.", exit_code); + *error = + strings::Substitute("Plugin failed with status code $0.", exit_code); return false; } @@ -267,7 +268,7 @@ bool Subprocess::Communicate(const Message& input, Message* output, return true; } -string Subprocess::Win32ErrorMessage(DWORD error_code) { +std::string Subprocess::Win32ErrorMessage(DWORD error_code) { char* message; // WTF? @@ -277,7 +278,7 @@ string Subprocess::Win32ErrorMessage(DWORD error_code) { (LPSTR)&message, // NOT A BUG! 0, NULL); - string result = message; + std::string result = message; LocalFree(message); return result; } @@ -298,7 +299,7 @@ Subprocess::~Subprocess() { } } -void Subprocess::Start(const string& program, SearchMode search_mode) { +void Subprocess::Start(const std::string& program, SearchMode search_mode) { // Note that we assume that there are no other threads, thus we don't have to // do crazy stuff like using socket pairs or avoiding libc locks. @@ -309,7 +310,7 @@ void Subprocess::Start(const string& program, SearchMode search_mode) { GOOGLE_CHECK(pipe(stdin_pipe) != -1); GOOGLE_CHECK(pipe(stdout_pipe) != -1); - char* argv[2] = { portable_strdup(program.c_str()), NULL }; + char* argv[2] = {portable_strdup(program.c_str()), NULL}; child_pid_ = fork(); if (child_pid_ == -1) { @@ -339,7 +340,7 @@ void Subprocess::Start(const string& program, SearchMode search_mode) { ignored = write(STDERR_FILENO, argv[0], strlen(argv[0])); const char* message = ": program not found or is not executable\n"; ignored = write(STDERR_FILENO, message, strlen(message)); - (void) ignored; + (void)ignored; // Must use _exit() rather than exit() to avoid flushing output buffers // that will also be flushed by the parent. @@ -356,7 +357,7 @@ void Subprocess::Start(const string& program, SearchMode search_mode) { } bool Subprocess::Communicate(const Message& input, Message* output, - string* error) { + std::string* error) { GOOGLE_CHECK_NE(child_stdin_, -1) << "Must call Start() first."; // The "sighandler_t" typedef is GNU-specific, so define our own. @@ -365,8 +366,8 @@ bool Subprocess::Communicate(const Message& input, Message* output, // Make sure SIGPIPE is disabled so that if the child dies it doesn't kill us. SignalHandler* old_pipe_handler = signal(SIGPIPE, SIG_IGN); - string input_data = input.SerializeAsString(); - string output_data; + std::string input_data = input.SerializeAsString(); + std::string output_data; int input_pos = 0; int max_fd = std::max(child_stdin_, child_stdout_); @@ -394,7 +395,7 @@ bool Subprocess::Communicate(const Message& input, Message* output, if (child_stdin_ != -1 && FD_ISSET(child_stdin_, &write_fds)) { int n = write(child_stdin_, input_data.data() + input_pos, - input_data.size() - input_pos); + input_data.size() - input_pos); if (n < 0) { // Child closed pipe. Presumably it will report an error later. // Pretend we're done for now. @@ -444,14 +445,13 @@ bool Subprocess::Communicate(const Message& input, Message* output, if (WIFEXITED(status)) { if (WEXITSTATUS(status) != 0) { int error_code = WEXITSTATUS(status); - *error = strings::Substitute( - "Plugin failed with status code $0.", error_code); + *error = + strings::Substitute("Plugin failed with status code $0.", error_code); return false; } } else if (WIFSIGNALED(status)) { int signal = WTERMSIG(status); - *error = strings::Substitute( - "Plugin killed by signal $0.", signal); + *error = strings::Substitute("Plugin killed by signal $0.", signal); return false; } else { *error = "Neither WEXITSTATUS nor WTERMSIG is true?"; diff --git a/third_party/protobuf/src/google/protobuf/compiler/subprocess.h b/third_party/protobuf/src/google/protobuf/compiler/subprocess.h index 9d980b06..9c4f8b76 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/subprocess.h +++ b/third_party/protobuf/src/google/protobuf/compiler/subprocess.h @@ -34,7 +34,7 @@ #define GOOGLE_PROTOBUF_COMPILER_SUBPROCESS_H__ #ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN // right... +#define WIN32_LEAN_AND_MEAN // right... #include #else // _WIN32 #include @@ -44,6 +44,8 @@ #include +#include + namespace google { namespace protobuf { @@ -52,31 +54,31 @@ class Message; namespace compiler { // Utility class for launching sub-processes. -class LIBPROTOC_EXPORT Subprocess { +class PROTOC_EXPORT Subprocess { public: Subprocess(); ~Subprocess(); enum SearchMode { - SEARCH_PATH, // Use PATH environment variable. - EXACT_NAME // Program is an exact file name; don't use the PATH. + SEARCH_PATH, // Use PATH environment variable. + EXACT_NAME // Program is an exact file name; don't use the PATH. }; // Start the subprocess. Currently we don't provide a way to specify // arguments as protoc plugins don't have any. - void Start(const string& program, SearchMode search_mode); + void Start(const std::string& program, SearchMode search_mode); // Serialize the input message and pipe it to the subprocess's stdin, then // close the pipe. Meanwhile, read from the subprocess's stdout and parse // the data into *output. All this is done carefully to avoid deadlocks. // Returns true if successful. On any sort of error, returns false and sets // *error to a description of the problem. - bool Communicate(const Message& input, Message* output, string* error); + bool Communicate(const Message& input, Message* output, std::string* error); #ifdef _WIN32 // Given an error code, returns a human-readable error message. This is // defined here so that CommandLineInterface can share it. - static string Win32ErrorMessage(DWORD error_code); + static std::string Win32ErrorMessage(DWORD error_code); #endif private: @@ -102,6 +104,8 @@ class LIBPROTOC_EXPORT Subprocess { } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_SUBPROCESS_H__ diff --git a/third_party/protobuf/src/google/protobuf/compiler/test_plugin.cc b/third_party/protobuf/src/google/protobuf/compiler/test_plugin.cc index c676ce8c..6b561700 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/test_plugin.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/test_plugin.cc @@ -33,10 +33,23 @@ // This is a dummy code generator plugin used by // command_line_interface_unittest. -#include #include -#include +#include #include +#include + +namespace google { +namespace protobuf { +namespace compiler { + +int ProtobufMain(int argc, char* argv[]) { + MockCodeGenerator generator("test_plugin"); + return PluginMain(argc, argv, &generator); +} + +} // namespace compiler +} // namespace protobuf +} // namespace google int main(int argc, char* argv[]) { #ifdef _MSC_VER @@ -44,7 +57,5 @@ int main(int argc, char* argv[]) { // please. _set_abort_behavior(0, ~0); #endif // !_MSC_VER - - google::protobuf::compiler::MockCodeGenerator generator("test_plugin"); - return google::protobuf::compiler::PluginMain(argc, argv, &generator); + return google::protobuf::compiler::ProtobufMain(argc, argv); } diff --git a/third_party/protobuf/src/google/protobuf/compiler/zip_writer.cc b/third_party/protobuf/src/google/protobuf/compiler/zip_writer.cc index 1799af6a..872dd9ed 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/zip_writer.cc +++ b/third_party/protobuf/src/google/protobuf/compiler/zip_writer.cc @@ -75,52 +75,51 @@ namespace compiler { static const uint16 kDosEpoch = 1 << 5 | 1; static const uint32 kCRC32Table[256] = { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, - 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, - 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, - 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, - 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, - 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, - 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, - 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, - 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, - 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, - 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, - 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, - 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, - 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, - 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, - 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, - 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, - 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, - 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, - 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, - 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, - 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, - 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, - 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, - 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, - 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, - 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, - 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, - 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, - 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, - 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, - 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, - 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, - 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, - 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d -}; + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, + 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, + 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, + 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, + 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, + 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, + 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, + 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, + 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, + 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, + 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, + 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, + 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, + 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, + 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, + 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, + 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, + 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, + 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, + 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, + 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, + 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, + 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, + 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, + 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, + 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, + 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, + 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, + 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, + 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, + 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, + 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, + 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, + 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, + 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, + 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, + 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, + 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, + 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, + 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, + 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, + 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d}; -static uint32 ComputeCRC32(const string &buf) { +static uint32 ComputeCRC32(const std::string& buf) { uint32 x = ~0U; for (int i = 0; i < buf.size(); ++i) { unsigned char c = buf[i]; @@ -129,7 +128,7 @@ static uint32 ComputeCRC32(const string &buf) { return ~x; } -static void WriteShort(io::CodedOutputStream *out, uint16 val) { +static void WriteShort(io::CodedOutputStream* out, uint16 val) { uint8 p[2]; p[0] = static_cast(val); p[1] = static_cast(val >> 8); @@ -137,10 +136,11 @@ static void WriteShort(io::CodedOutputStream *out, uint16 val) { } ZipWriter::ZipWriter(io::ZeroCopyOutputStream* raw_output) - : raw_output_(raw_output) {} + : raw_output_(raw_output) {} ZipWriter::~ZipWriter() {} -bool ZipWriter::Write(const string& filename, const string& contents) { +bool ZipWriter::Write(const std::string& filename, + const std::string& contents) { FileInfo info; info.name = filename; @@ -154,18 +154,18 @@ bool ZipWriter::Write(const string& filename, const string& contents) { // write file header io::CodedOutputStream output(raw_output_); output.WriteLittleEndian32(0x04034b50); // magic - WriteShort(&output, 10); // version needed to extract - WriteShort(&output, 0); // flags - WriteShort(&output, 0); // compression method: stored - WriteShort(&output, 0); // last modified time - WriteShort(&output, kDosEpoch); // last modified date + WriteShort(&output, 10); // version needed to extract + WriteShort(&output, 0); // flags + WriteShort(&output, 0); // compression method: stored + WriteShort(&output, 0); // last modified time + WriteShort(&output, kDosEpoch); // last modified date output.WriteLittleEndian32(info.crc32); // crc-32 - output.WriteLittleEndian32(info.size); // compressed size - output.WriteLittleEndian32(info.size); // uncompressed size - WriteShort(&output, filename_size); // file name length - WriteShort(&output, 0); // extra field length - output.WriteString(filename); // file name - output.WriteString(contents); // file data + output.WriteLittleEndian32(info.size); // compressed size + output.WriteLittleEndian32(info.size); // uncompressed size + WriteShort(&output, filename_size); // file name length + WriteShort(&output, 0); // extra field length + output.WriteString(filename); // file name + output.WriteString(contents); // file data return !output.HadError(); } @@ -177,42 +177,42 @@ bool ZipWriter::WriteDirectory() { // write central directory io::CodedOutputStream output(raw_output_); for (int i = 0; i < num_entries; ++i) { - const string &filename = files_[i].name; + const std::string& filename = files_[i].name; uint16 filename_size = filename.size(); uint32 crc32 = files_[i].crc32; uint32 size = files_[i].size; uint32 offset = files_[i].offset; output.WriteLittleEndian32(0x02014b50); // magic - WriteShort(&output, 10); // version made by - WriteShort(&output, 10); // version needed to extract - WriteShort(&output, 0); // flags - WriteShort(&output, 0); // compression method: stored - WriteShort(&output, 0); // last modified time - WriteShort(&output, kDosEpoch); // last modified date - output.WriteLittleEndian32(crc32); // crc-32 - output.WriteLittleEndian32(size); // compressed size - output.WriteLittleEndian32(size); // uncompressed size - WriteShort(&output, filename_size); // file name length - WriteShort(&output, 0); // extra field length - WriteShort(&output, 0); // file comment length - WriteShort(&output, 0); // starting disk number - WriteShort(&output, 0); // internal file attributes - output.WriteLittleEndian32(0); // external file attributes - output.WriteLittleEndian32(offset); // local header offset - output.WriteString(filename); // file name + WriteShort(&output, 10); // version made by + WriteShort(&output, 10); // version needed to extract + WriteShort(&output, 0); // flags + WriteShort(&output, 0); // compression method: stored + WriteShort(&output, 0); // last modified time + WriteShort(&output, kDosEpoch); // last modified date + output.WriteLittleEndian32(crc32); // crc-32 + output.WriteLittleEndian32(size); // compressed size + output.WriteLittleEndian32(size); // uncompressed size + WriteShort(&output, filename_size); // file name length + WriteShort(&output, 0); // extra field length + WriteShort(&output, 0); // file comment length + WriteShort(&output, 0); // starting disk number + WriteShort(&output, 0); // internal file attributes + output.WriteLittleEndian32(0); // external file attributes + output.WriteLittleEndian32(offset); // local header offset + output.WriteString(filename); // file name } uint32 dir_len = output.ByteCount(); // write end of central directory marker output.WriteLittleEndian32(0x06054b50); // magic - WriteShort(&output, 0); // disk number - WriteShort(&output, 0); // disk with start of central directory - WriteShort(&output, num_entries); // central directory entries (this disk) - WriteShort(&output, num_entries); // central directory entries (total) + WriteShort(&output, 0); // disk number + WriteShort(&output, 0); // disk with start of central directory + WriteShort(&output, num_entries); // central directory entries (this disk) + WriteShort(&output, num_entries); // central directory entries (total) output.WriteLittleEndian32(dir_len); // central directory byte size output.WriteLittleEndian32(dir_ofs); // central directory offset - WriteShort(&output, 0); // comment length + WriteShort(&output, 0); // comment length return output.HadError(); } diff --git a/third_party/protobuf/src/google/protobuf/compiler/zip_writer.h b/third_party/protobuf/src/google/protobuf/compiler/zip_writer.h index 03db4d57..a99bb78c 100644 --- a/third_party/protobuf/src/google/protobuf/compiler/zip_writer.h +++ b/third_party/protobuf/src/google/protobuf/compiler/zip_writer.h @@ -73,12 +73,12 @@ class ZipWriter { ZipWriter(io::ZeroCopyOutputStream* raw_output); ~ZipWriter(); - bool Write(const string& filename, const string& contents); + bool Write(const std::string& filename, const std::string& contents); bool WriteDirectory(); private: struct FileInfo { - string name; + std::string name; uint32 offset; uint32 size; uint32 crc32; diff --git a/third_party/protobuf/src/google/protobuf/descriptor.cc b/third_party/protobuf/src/google/protobuf/descriptor.cc index fc3a9c77..735c519f 100644 --- a/third_party/protobuf/src/google/protobuf/descriptor.cc +++ b/third_party/protobuf/src/google/protobuf/descriptor.cc @@ -34,19 +34,17 @@ #include #include -#include #include #include #include #include #include +#include +#include #include -#include #include #include -#include -#include #include #include #include @@ -62,15 +60,20 @@ #include #include #include +#include + #include #include +#include #undef PACKAGE // autoheader #defines this. :( -namespace google { +#include + +namespace google { namespace protobuf { struct Symbol { @@ -147,73 +150,73 @@ struct Symbol { }; const FieldDescriptor::CppType -FieldDescriptor::kTypeToCppTypeMap[MAX_TYPE + 1] = { - static_cast(0), // 0 is reserved for errors + FieldDescriptor::kTypeToCppTypeMap[MAX_TYPE + 1] = { + static_cast(0), // 0 is reserved for errors - CPPTYPE_DOUBLE, // TYPE_DOUBLE - CPPTYPE_FLOAT, // TYPE_FLOAT - CPPTYPE_INT64, // TYPE_INT64 - CPPTYPE_UINT64, // TYPE_UINT64 - CPPTYPE_INT32, // TYPE_INT32 - CPPTYPE_UINT64, // TYPE_FIXED64 - CPPTYPE_UINT32, // TYPE_FIXED32 - CPPTYPE_BOOL, // TYPE_BOOL - CPPTYPE_STRING, // TYPE_STRING - CPPTYPE_MESSAGE, // TYPE_GROUP - CPPTYPE_MESSAGE, // TYPE_MESSAGE - CPPTYPE_STRING, // TYPE_BYTES - CPPTYPE_UINT32, // TYPE_UINT32 - CPPTYPE_ENUM, // TYPE_ENUM - CPPTYPE_INT32, // TYPE_SFIXED32 - CPPTYPE_INT64, // TYPE_SFIXED64 - CPPTYPE_INT32, // TYPE_SINT32 - CPPTYPE_INT64, // TYPE_SINT64 + CPPTYPE_DOUBLE, // TYPE_DOUBLE + CPPTYPE_FLOAT, // TYPE_FLOAT + CPPTYPE_INT64, // TYPE_INT64 + CPPTYPE_UINT64, // TYPE_UINT64 + CPPTYPE_INT32, // TYPE_INT32 + CPPTYPE_UINT64, // TYPE_FIXED64 + CPPTYPE_UINT32, // TYPE_FIXED32 + CPPTYPE_BOOL, // TYPE_BOOL + CPPTYPE_STRING, // TYPE_STRING + CPPTYPE_MESSAGE, // TYPE_GROUP + CPPTYPE_MESSAGE, // TYPE_MESSAGE + CPPTYPE_STRING, // TYPE_BYTES + CPPTYPE_UINT32, // TYPE_UINT32 + CPPTYPE_ENUM, // TYPE_ENUM + CPPTYPE_INT32, // TYPE_SFIXED32 + CPPTYPE_INT64, // TYPE_SFIXED64 + CPPTYPE_INT32, // TYPE_SINT32 + CPPTYPE_INT64, // TYPE_SINT64 }; -const char * const FieldDescriptor::kTypeToName[MAX_TYPE + 1] = { - "ERROR", // 0 is reserved for errors +const char* const FieldDescriptor::kTypeToName[MAX_TYPE + 1] = { + "ERROR", // 0 is reserved for errors - "double", // TYPE_DOUBLE - "float", // TYPE_FLOAT - "int64", // TYPE_INT64 - "uint64", // TYPE_UINT64 - "int32", // TYPE_INT32 - "fixed64", // TYPE_FIXED64 - "fixed32", // TYPE_FIXED32 - "bool", // TYPE_BOOL - "string", // TYPE_STRING - "group", // TYPE_GROUP - "message", // TYPE_MESSAGE - "bytes", // TYPE_BYTES - "uint32", // TYPE_UINT32 - "enum", // TYPE_ENUM - "sfixed32", // TYPE_SFIXED32 - "sfixed64", // TYPE_SFIXED64 - "sint32", // TYPE_SINT32 - "sint64", // TYPE_SINT64 + "double", // TYPE_DOUBLE + "float", // TYPE_FLOAT + "int64", // TYPE_INT64 + "uint64", // TYPE_UINT64 + "int32", // TYPE_INT32 + "fixed64", // TYPE_FIXED64 + "fixed32", // TYPE_FIXED32 + "bool", // TYPE_BOOL + "string", // TYPE_STRING + "group", // TYPE_GROUP + "message", // TYPE_MESSAGE + "bytes", // TYPE_BYTES + "uint32", // TYPE_UINT32 + "enum", // TYPE_ENUM + "sfixed32", // TYPE_SFIXED32 + "sfixed64", // TYPE_SFIXED64 + "sint32", // TYPE_SINT32 + "sint64", // TYPE_SINT64 }; -const char * const FieldDescriptor::kCppTypeToName[MAX_CPPTYPE + 1] = { - "ERROR", // 0 is reserved for errors +const char* const FieldDescriptor::kCppTypeToName[MAX_CPPTYPE + 1] = { + "ERROR", // 0 is reserved for errors - "int32", // CPPTYPE_INT32 - "int64", // CPPTYPE_INT64 - "uint32", // CPPTYPE_UINT32 - "uint64", // CPPTYPE_UINT64 - "double", // CPPTYPE_DOUBLE - "float", // CPPTYPE_FLOAT - "bool", // CPPTYPE_BOOL - "enum", // CPPTYPE_ENUM - "string", // CPPTYPE_STRING - "message", // CPPTYPE_MESSAGE + "int32", // CPPTYPE_INT32 + "int64", // CPPTYPE_INT64 + "uint32", // CPPTYPE_UINT32 + "uint64", // CPPTYPE_UINT64 + "double", // CPPTYPE_DOUBLE + "float", // CPPTYPE_FLOAT + "bool", // CPPTYPE_BOOL + "enum", // CPPTYPE_ENUM + "string", // CPPTYPE_STRING + "message", // CPPTYPE_MESSAGE }; -const char * const FieldDescriptor::kLabelToName[MAX_LABEL + 1] = { - "ERROR", // 0 is reserved for errors +const char* const FieldDescriptor::kLabelToName[MAX_LABEL + 1] = { + "ERROR", // 0 is reserved for errors - "optional", // LABEL_OPTIONAL - "required", // LABEL_REQUIRED - "repeated", // LABEL_REPEATED + "optional", // LABEL_OPTIONAL + "required", // LABEL_REQUIRED + "repeated", // LABEL_REPEATED }; const char* FileDescriptor::SyntaxName(FileDescriptor::Syntax syntax) { @@ -229,7 +232,7 @@ const char* FileDescriptor::SyntaxName(FileDescriptor::Syntax syntax) { return NULL; } -static const char * const kNonLinkedWeakMessageReplacementName = "google.protobuf.Empty"; +static const char* const kNonLinkedWeakMessageReplacementName = "google.protobuf.Empty"; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int FieldDescriptor::kMaxNumber; @@ -248,9 +251,9 @@ char ToLower(char ch) { return (ch >= 'A' && ch <= 'Z') ? (ch - 'A' + 'a') : ch; } -string ToCamelCase(const string& input, bool lower_first) { +std::string ToCamelCase(const std::string& input, bool lower_first) { bool capitalize_next = !lower_first; - string result; + std::string result; result.reserve(input.size()); for (int i = 0; i < input.size(); i++) { @@ -272,9 +275,9 @@ string ToCamelCase(const string& input, bool lower_first) { return result; } -string ToJsonName(const string& input) { +std::string ToJsonName(const std::string& input) { bool capitalize_next = false; - string result; + std::string result; result.reserve(input.size()); for (int i = 0; i < input.size(); i++) { @@ -291,9 +294,9 @@ string ToJsonName(const string& input) { return result; } -string EnumValueToPascalCase(const string& input) { +std::string EnumValueToPascalCase(const std::string& input) { bool next_upper = true; - string result; + std::string result; result.reserve(input.size()); for (int i = 0; i < input.size(); i++) { @@ -326,7 +329,7 @@ class PrefixRemover { // Tries to remove the enum prefix from this enum value. // If this is not possible, returns the input verbatim. - string MaybeRemove(StringPiece str) { + std::string MaybeRemove(StringPiece str) { // We can't just lowercase and strip str and look for a prefix. // We need to properly recognize the difference between: // @@ -346,14 +349,14 @@ class PrefixRemover { } if (ascii_tolower(str[i]) != prefix_[j++]) { - return string(str); + return std::string(str); } } // If we didn't make it through the prefix, we've failed to strip the // prefix. if (j < prefix_.size()) { - return string(str); + return std::string(str); } // Skip underscores between prefix and further characters. @@ -363,16 +366,16 @@ class PrefixRemover { // Enum label can't be the empty string. if (i == str.size()) { - return string(str); + return std::string(str); } // We successfully stripped the prefix. str.remove_prefix(i); - return string(str); + return std::string(str); } private: - string prefix_; + std::string prefix_; }; // A DescriptorPool contains a bunch of hash-maps to implement the @@ -399,16 +402,17 @@ struct PointerStringPairEqual { typedef std::pair DescriptorIntPair; typedef std::pair EnumIntPair; -#define HASH_MAP hash_map -#define HASH_SET hash_set +#define HASH_MAP std::unordered_map +#define HASH_SET std::unordered_set #define HASH_FXN hash -template +template struct PointerIntegerPairHash { size_t operator()(const PairType& p) const { - // FIXME(kenton): What is the best way to compute this hash? I have - // no idea! This seems a bit better than an XOR. - return reinterpret_cast(p.first) * ((1 << 16) - 1) + p.second; + static const size_t prime1 = 16777499; + static const size_t prime2 = 16777619; + return reinterpret_cast(p.first) * prime1 ^ + static_cast(p.second) * prime2; } #ifdef _MSC_VER @@ -417,18 +421,16 @@ struct PointerIntegerPairHash { static const size_t min_buckets = 8; #endif inline bool operator()(const PairType& a, const PairType& b) const { - return a.first < b.first || - (a.first == b.first && a.second < b.second); + return a.first < b.first || (a.first == b.first && a.second < b.second); } }; struct PointerStringPairHash { size_t operator()(const PointerStringPair& p) const { - // FIXME(kenton): What is the best way to compute this hash? I have - // no idea! This seems a bit better than an XOR. + static const size_t prime = 16777619; hash cstring_hash; - return reinterpret_cast(p.first) * ((1 << 16) - 1) + - cstring_hash(p.second); + return reinterpret_cast(p.first) * prime ^ + static_cast(cstring_hash(p.second)); } #ifdef _MSC_VER @@ -464,35 +466,37 @@ typedef HASH_MAP, - std::equal_to > + std::equal_to> FieldsByNumberMap; typedef HASH_MAP, - std::equal_to > + std::equal_to> EnumValuesByNumberMap; // This is a map rather than a hash-map, since we use it to iterate // through all the extensions that extend a given Descriptor, and an // ordered data structure that implements lower_bound is convenient // for that. typedef std::map - ExtensionsGroupedByDescriptorMap; -typedef HASH_MAP LocationsByPathMap; + ExtensionsGroupedByDescriptorMap; +typedef HASH_MAP + LocationsByPathMap; -std::set* NewAllowedProto3Extendee() { - auto allowed_proto3_extendees = new std::set; +std::set* NewAllowedProto3Extendee() { + auto allowed_proto3_extendees = new std::set; const char* kOptionNames[] = { - "FileOptions", "MessageOptions", "FieldOptions", "EnumOptions", + "FileOptions", "MessageOptions", "FieldOptions", "EnumOptions", "EnumValueOptions", "ServiceOptions", "MethodOptions", "OneofOptions"}; for (int i = 0; i < GOOGLE_ARRAYSIZE(kOptionNames); ++i) { // descriptor.proto has a different package name in opensource. We allow // both so the opensource protocol compiler can also compile internal // proto3 files with custom options. See: b/27567912 - allowed_proto3_extendees->insert(string("google.protobuf.") + - kOptionNames[i]); + allowed_proto3_extendees->insert(std::string("google.protobuf.") + + kOptionNames[i]); // Split the word to trick the opensource processing scripts so they // will keep the origial package name. - allowed_proto3_extendees->insert(string("proto") + "2." + kOptionNames[i]); + allowed_proto3_extendees->insert(std::string("proto") + "2." + + kOptionNames[i]); } return allowed_proto3_extendees; } @@ -501,7 +505,7 @@ std::set* NewAllowedProto3Extendee() { // Only extensions to descriptor options are allowed. We use name comparison // instead of comparing the descriptor directly because the extensions may be // defined in a different pool. -bool AllowedExtendeeInProto3(const string& name) { +bool AllowedExtendeeInProto3(const std::string& name) { static auto allowed_proto3_extendees = internal::OnShutdownDelete(NewAllowedProto3Extendee()); return allowed_proto3_extendees->find(name) != @@ -558,20 +562,20 @@ class DescriptorPool::Tables { // The stack of files which are currently being built. Used to detect // cyclic dependencies when loading files from a DescriptorDatabase. Not // used when fallback_database_ == NULL. - std::vector pending_files_; + std::vector pending_files_; // A set of files which we have tried to load from the fallback database // and encountered errors. We will not attempt to load them again during // execution of the current public API call, but for compatibility with // legacy clients, this is cleared at the beginning of each public API call. // Not used when fallback_database_ == NULL. - HASH_SET known_bad_files_; + HASH_SET known_bad_files_; // A set of symbols which we have tried to load from the fallback database // and encountered errors. We will not attempt to load them again during // execution of the current public API call, but for compatibility with // legacy clients, this is cleared at the beginning of each public API call. - HASH_SET known_bad_symbols_; + HASH_SET known_bad_symbols_; // The set of descriptors for which we've already loaded the full // set of extensions numbers from fallback_database_. @@ -582,17 +586,16 @@ class DescriptorPool::Tables { // Find symbols. This returns a null Symbol (symbol.IsNull() is true) // if not found. - inline Symbol FindSymbol(const string& key) const; + inline Symbol FindSymbol(const std::string& key) const; // This implements the body of DescriptorPool::Find*ByName(). It should // really be a private method of DescriptorPool, but that would require // declaring Symbol in descriptor.h, which would drag all kinds of other // stuff into the header. Yay C++. - Symbol FindByNameHelper( - const DescriptorPool* pool, const string& name); + Symbol FindByNameHelper(const DescriptorPool* pool, const std::string& name); // These return NULL if not found. - inline const FileDescriptor* FindFile(const string& key) const; + inline const FileDescriptor* FindFile(const std::string& key) const; inline const FieldDescriptor* FindExtension(const Descriptor* extendee, int number) const; inline void FindAllExtensions(const Descriptor* extendee, @@ -605,7 +608,7 @@ class DescriptorPool::Tables { // the key already exists in the table. For AddSymbol(), the string passed // in must be one that was constructed using AllocateString(), as it will // be used as a key in the symbols_by_name_ map without copying. - bool AddSymbol(const string& full_name, Symbol symbol); + bool AddSymbol(const std::string& full_name, Symbol symbol); bool AddFile(const FileDescriptor* file); bool AddExtension(const FieldDescriptor* field); @@ -616,40 +619,43 @@ class DescriptorPool::Tables { // destroyed. Note that the object's destructor will never be called, // so its fields must be plain old data (primitive data types and // pointers). All of the descriptor types are such objects. - template Type* Allocate(); + template + Type* Allocate(); // Allocate an array of objects which will be reclaimed when the // pool in destroyed. Again, destructors are never called. - template Type* AllocateArray(int count); + template + Type* AllocateArray(int count); // Allocate a string which will be destroyed when the pool is destroyed. // The string is initialized to the given value for convenience. - string* AllocateString(const string& value); + std::string* AllocateString(const std::string& value); - // Allocate a GoogleOnceDynamic which will be destroyed when the pool is + // Allocate a internal::call_once which will be destroyed when the pool is // destroyed. - GoogleOnceDynamic* AllocateOnceDynamic(); + internal::once_flag* AllocateOnceDynamic(); // Allocate a protocol message object. Some older versions of GCC have // trouble understanding explicit template instantiations in some cases, so // in those cases we have to pass a dummy pointer of the right type as the // parameter instead of specifying the type explicitly. - template Type* AllocateMessage(Type* dummy = NULL); + template + Type* AllocateMessage(Type* dummy = NULL); // Allocate a FileDescriptorTables object. FileDescriptorTables* AllocateFileTables(); private: - std::vector strings_; // All strings in the pool. - std::vector messages_; // All messages in the pool. - std::vector - once_dynamics_; // All GoogleOnceDynamics in the pool. + std::vector strings_; // All strings in the pool. + std::vector messages_; // All messages in the pool. + std::vector + once_dynamics_; // All internal::call_onces in the pool. std::vector file_tables_; // All file tables in the pool. std::vector allocations_; // All other memory allocated in the pool. - SymbolsByNameMap symbols_by_name_; - FilesByNameMap files_by_name_; + SymbolsByNameMap symbols_by_name_; + FilesByNameMap files_by_name_; ExtensionsGroupedByDescriptorMap extensions_; struct CheckPoint { @@ -675,8 +681,8 @@ class DescriptorPool::Tables { int pending_extensions_before_checkpoint; }; std::vector checkpoints_; - std::vector symbols_after_checkpoint_; - std::vector files_after_checkpoint_; + std::vector symbols_after_checkpoint_; + std::vector files_after_checkpoint_; std::vector extensions_after_checkpoint_; // Allocate some bytes which will be reclaimed when the pool is @@ -707,20 +713,20 @@ class FileDescriptorTables { // Find symbols. These return a null Symbol (symbol.IsNull() is true) // if not found. inline Symbol FindNestedSymbol(const void* parent, - const string& name) const; + const std::string& name) const; inline Symbol FindNestedSymbolOfType(const void* parent, - const string& name, + const std::string& name, const Symbol::Type type) const; // These return NULL if not found. - inline const FieldDescriptor* FindFieldByNumber( - const Descriptor* parent, int number) const; + inline const FieldDescriptor* FindFieldByNumber(const Descriptor* parent, + int number) const; inline const FieldDescriptor* FindFieldByLowercaseName( - const void* parent, const string& lowercase_name) const; + const void* parent, const std::string& lowercase_name) const; inline const FieldDescriptor* FindFieldByCamelcaseName( - const void* parent, const string& camelcase_name) const; + const void* parent, const std::string& camelcase_name) const; inline const EnumValueDescriptor* FindEnumValueByNumber( - const EnumDescriptor* parent, int number) const; + const EnumDescriptor* parent, int number) const; // This creates a new EnumValueDescriptor if not found, in a thread-safe way. inline const EnumValueDescriptor* FindEnumValueByNumberCreatingIfUnknown( const EnumDescriptor* parent, int number) const; @@ -732,7 +738,7 @@ class FileDescriptorTables { // the key already exists in the table. For AddAliasUnderParent(), the // string passed in must be one that was constructed using AllocateString(), // as it will be used as a key in the symbols_by_parent_ map without copying. - bool AddAliasUnderParent(const void* parent, const string& name, + bool AddAliasUnderParent(const void* parent, const std::string& name, Symbol symbol); bool AddFieldByNumber(const FieldDescriptor* field); bool AddEnumValueByNumber(const EnumValueDescriptor* value); @@ -742,7 +748,7 @@ class FileDescriptorTables { void AddFieldByStylizedNames(const FieldDescriptor* field); // Populates p->first->locations_by_path_ from p->second. - // Unusual signature dictated by GoogleOnceDynamic. + // Unusual signature dictated by internal::call_once. static void BuildLocationsByPath( std::pair* p); @@ -769,22 +775,22 @@ class FileDescriptorTables { SymbolsByParentMap symbols_by_parent_; mutable FieldsByNameMap fields_by_lowercase_name_; std::unique_ptr fields_by_lowercase_name_tmp_; - mutable GoogleOnceDynamic fields_by_lowercase_name_once_; + mutable internal::once_flag fields_by_lowercase_name_once_; mutable FieldsByNameMap fields_by_camelcase_name_; std::unique_ptr fields_by_camelcase_name_tmp_; - mutable GoogleOnceDynamic fields_by_camelcase_name_once_; + mutable internal::once_flag fields_by_camelcase_name_once_; FieldsByNumberMap fields_by_number_; // Not including extensions. EnumValuesByNumberMap enum_values_by_number_; mutable EnumValuesByNumberMap unknown_enum_values_by_number_ - GOOGLE_GUARDED_BY(unknown_enum_values_mu_); + PROTOBUF_GUARDED_BY(unknown_enum_values_mu_); // Populated on first request to save space, hence constness games. - mutable GoogleOnceDynamic locations_by_path_once_; + mutable internal::once_flag locations_by_path_once_; mutable LocationsByPathMap locations_by_path_; // Mutex to protect the unknown-enum-value map due to dynamic // EnumValueDescriptor creation on unknown values. - mutable Mutex unknown_enum_values_mu_; + mutable internal::WrappedMutex unknown_enum_values_mu_; }; DescriptorPool::Tables::Tables() @@ -849,18 +855,15 @@ void DescriptorPool::Tables::RollbackToLastCheckpoint() { const CheckPoint& checkpoint = checkpoints_.back(); for (int i = checkpoint.pending_symbols_before_checkpoint; - i < symbols_after_checkpoint_.size(); - i++) { + i < symbols_after_checkpoint_.size(); i++) { symbols_by_name_.erase(symbols_after_checkpoint_[i]); } for (int i = checkpoint.pending_files_before_checkpoint; - i < files_after_checkpoint_.size(); - i++) { + i < files_after_checkpoint_.size(); i++) { files_by_name_.erase(files_after_checkpoint_[i]); } for (int i = checkpoint.pending_extensions_before_checkpoint; - i < extensions_after_checkpoint_.size(); - i++) { + i < extensions_after_checkpoint_.size(); i++) { extensions_.erase(extensions_after_checkpoint_[i]); } @@ -882,8 +885,7 @@ void DescriptorPool::Tables::RollbackToLastCheckpoint() { file_tables_.begin() + checkpoint.file_tables_before_checkpoint, file_tables_.end()); for (int i = checkpoint.allocations_before_checkpoint; - i < allocations_.size(); - i++) { + i < allocations_.size(); i++) { operator delete(allocations_[i]); } @@ -897,7 +899,7 @@ void DescriptorPool::Tables::RollbackToLastCheckpoint() { // ------------------------------------------------------------------- -inline Symbol DescriptorPool::Tables::FindSymbol(const string& key) const { +inline Symbol DescriptorPool::Tables::FindSymbol(const std::string& key) const { const Symbol* result = FindOrNull(symbols_by_name_, key.c_str()); if (result == NULL) { return kNullSymbol; @@ -907,9 +909,9 @@ inline Symbol DescriptorPool::Tables::FindSymbol(const string& key) const { } inline Symbol FileDescriptorTables::FindNestedSymbol( - const void* parent, const string& name) const { - const Symbol* result = - FindOrNull(symbols_by_parent_, PointerStringPair(parent, name.c_str())); + const void* parent, const std::string& name) const { + const Symbol* result = FindOrNull( + symbols_by_parent_, PointerStringPair(parent, name.c_str())); if (result == NULL) { return kNullSymbol; } else { @@ -918,14 +920,15 @@ inline Symbol FileDescriptorTables::FindNestedSymbol( } inline Symbol FileDescriptorTables::FindNestedSymbolOfType( - const void* parent, const string& name, const Symbol::Type type) const { + const void* parent, const std::string& name, + const Symbol::Type type) const { Symbol result = FindNestedSymbol(parent, name); if (result.type != type) return kNullSymbol; return result; } -Symbol DescriptorPool::Tables::FindByNameHelper( - const DescriptorPool* pool, const string& name) { +Symbol DescriptorPool::Tables::FindByNameHelper(const DescriptorPool* pool, + const std::string& name) { MutexLockMaybe lock(pool->mutex_); if (pool->fallback_database_ != NULL) { known_bad_symbols_.clear(); @@ -935,8 +938,7 @@ Symbol DescriptorPool::Tables::FindByNameHelper( if (result.IsNull() && pool->underlay_ != NULL) { // Symbol not found; check the underlay. - result = - pool->underlay_->tables_->FindByNameHelper(pool->underlay_, name); + result = pool->underlay_->tables_->FindByNameHelper(pool->underlay_, name); } if (result.IsNull()) { @@ -950,7 +952,7 @@ Symbol DescriptorPool::Tables::FindByNameHelper( } inline const FileDescriptor* DescriptorPool::Tables::FindFile( - const string& key) const { + const std::string& key) const { return FindPtrOrNull(files_by_name_, key.c_str()); } @@ -982,16 +984,18 @@ void FileDescriptorTables::FieldsByLowercaseNamesLazyInitInternal() const { it != fields_by_number_.end(); it++) { PointerStringPair lowercase_key(FindParentForFieldsByMap(it->second), it->second->lowercase_name().c_str()); - InsertIfNotPresent(&fields_by_lowercase_name_, lowercase_key, it->second); + InsertIfNotPresent(&fields_by_lowercase_name_, lowercase_key, + it->second); } } inline const FieldDescriptor* FileDescriptorTables::FindFieldByLowercaseName( - const void* parent, const string& lowercase_name) const { - fields_by_lowercase_name_once_.Init( + const void* parent, const std::string& lowercase_name) const { + internal::call_once( + fields_by_lowercase_name_once_, &FileDescriptorTables::FieldsByLowercaseNamesLazyInitStatic, this); return FindPtrOrNull(fields_by_lowercase_name_, - PointerStringPair(parent, lowercase_name.c_str())); + PointerStringPair(parent, lowercase_name.c_str())); } void FileDescriptorTables::FieldsByCamelcaseNamesLazyInitStatic( @@ -1004,21 +1008,24 @@ void FileDescriptorTables::FieldsByCamelcaseNamesLazyInitInternal() const { it != fields_by_number_.end(); it++) { PointerStringPair camelcase_key(FindParentForFieldsByMap(it->second), it->second->camelcase_name().c_str()); - InsertIfNotPresent(&fields_by_camelcase_name_, camelcase_key, it->second); + InsertIfNotPresent(&fields_by_camelcase_name_, camelcase_key, + it->second); } } inline const FieldDescriptor* FileDescriptorTables::FindFieldByCamelcaseName( - const void* parent, const string& camelcase_name) const { - fields_by_camelcase_name_once_.Init( - &FileDescriptorTables::FieldsByCamelcaseNamesLazyInitStatic, this); + const void* parent, const std::string& camelcase_name) const { + internal::call_once( + fields_by_camelcase_name_once_, + FileDescriptorTables::FieldsByCamelcaseNamesLazyInitStatic, this); return FindPtrOrNull(fields_by_camelcase_name_, - PointerStringPair(parent, camelcase_name.c_str())); + PointerStringPair(parent, camelcase_name.c_str())); } inline const EnumValueDescriptor* FileDescriptorTables::FindEnumValueByNumber( const EnumDescriptor* parent, int number) const { - return FindPtrOrNull(enum_values_by_number_, std::make_pair(parent, number)); + return FindPtrOrNull(enum_values_by_number_, + std::make_pair(parent, number)); } inline const EnumValueDescriptor* @@ -1026,8 +1033,8 @@ FileDescriptorTables::FindEnumValueByNumberCreatingIfUnknown( const EnumDescriptor* parent, int number) const { // First try, with map of compiled-in values. { - const EnumValueDescriptor* desc = - FindPtrOrNull(enum_values_by_number_, std::make_pair(parent, number)); + const EnumValueDescriptor* desc = FindPtrOrNull( + enum_values_by_number_, std::make_pair(parent, number)); if (desc != NULL) { return desc; } @@ -1055,25 +1062,23 @@ FileDescriptorTables::FindEnumValueByNumberCreatingIfUnknown( // EnumDescriptor (it's not a part of the enum as originally defined), but // we do insert it into the table so that we can return the same pointer // later. - string enum_value_name = StringPrintf( - "UNKNOWN_ENUM_VALUE_%s_%d", parent->name().c_str(), number); - DescriptorPool::Tables* tables = - const_cast(DescriptorPool::generated_pool()-> - tables_.get()); + std::string enum_value_name = StringPrintf("UNKNOWN_ENUM_VALUE_%s_%d", + parent->name().c_str(), number); + DescriptorPool::Tables* tables = const_cast( + DescriptorPool::generated_pool()->tables_.get()); EnumValueDescriptor* result = tables->Allocate(); result->name_ = tables->AllocateString(enum_value_name); - result->full_name_ = tables->AllocateString(parent->full_name() + - "." + enum_value_name); + result->full_name_ = + tables->AllocateString(parent->full_name() + "." + enum_value_name); result->number_ = number; result->type_ = parent; result->options_ = &EnumValueOptions::default_instance(); InsertIfNotPresent(&unknown_enum_values_by_number_, - std::make_pair(parent, number), result); + std::make_pair(parent, number), result); return result; } } - inline const FieldDescriptor* DescriptorPool::Tables::FindExtension( const Descriptor* extendee, int number) const { return FindPtrOrNull(extensions_, std::make_pair(extendee, number)); @@ -1091,8 +1096,8 @@ inline void DescriptorPool::Tables::FindAllExtensions( // ------------------------------------------------------------------- -bool DescriptorPool::Tables::AddSymbol( - const string& full_name, Symbol symbol) { +bool DescriptorPool::Tables::AddSymbol(const std::string& full_name, + Symbol symbol) { if (InsertIfNotPresent(&symbols_by_name_, full_name.c_str(), symbol)) { symbols_after_checkpoint_.push_back(full_name.c_str()); return true; @@ -1101,8 +1106,9 @@ bool DescriptorPool::Tables::AddSymbol( } } -bool FileDescriptorTables::AddAliasUnderParent( - const void* parent, const string& name, Symbol symbol) { +bool FileDescriptorTables::AddAliasUnderParent(const void* parent, + const std::string& name, + Symbol symbol) { PointerStringPair by_parent_key(parent, name.c_str()); return InsertIfNotPresent(&symbols_by_parent_, by_parent_key, symbol); } @@ -1134,16 +1140,16 @@ void FileDescriptorTables::AddFieldByStylizedNames( // entries from fields_by_number_. PointerStringPair lowercase_key(parent, field->lowercase_name().c_str()); - if (!InsertIfNotPresent(fields_by_lowercase_name_tmp_.get(), lowercase_key, - field)) { + if (!InsertIfNotPresent(fields_by_lowercase_name_tmp_.get(), + lowercase_key, field)) { InsertIfNotPresent( &fields_by_lowercase_name_, lowercase_key, FindPtrOrNull(*fields_by_lowercase_name_tmp_, lowercase_key)); } PointerStringPair camelcase_key(parent, field->camelcase_name().c_str()); - if (!InsertIfNotPresent(fields_by_camelcase_name_tmp_.get(), camelcase_key, - field)) { + if (!InsertIfNotPresent(fields_by_camelcase_name_tmp_.get(), + camelcase_key, field)) { InsertIfNotPresent( &fields_by_camelcase_name_, camelcase_key, FindPtrOrNull(*fields_by_camelcase_name_tmp_, camelcase_key)); @@ -1173,29 +1179,29 @@ bool DescriptorPool::Tables::AddExtension(const FieldDescriptor* field) { // ------------------------------------------------------------------- -template +template Type* DescriptorPool::Tables::Allocate() { return reinterpret_cast(AllocateBytes(sizeof(Type))); } -template +template Type* DescriptorPool::Tables::AllocateArray(int count) { return reinterpret_cast(AllocateBytes(sizeof(Type) * count)); } -string* DescriptorPool::Tables::AllocateString(const string& value) { - string* result = new string(value); +std::string* DescriptorPool::Tables::AllocateString(const std::string& value) { + std::string* result = new std::string(value); strings_.push_back(result); return result; } -GoogleOnceDynamic* DescriptorPool::Tables::AllocateOnceDynamic() { - GoogleOnceDynamic* result = new GoogleOnceDynamic(); +internal::once_flag* DescriptorPool::Tables::AllocateOnceDynamic() { + internal::once_flag* result = new internal::once_flag(); once_dynamics_.push_back(result); return result; } -template +template Type* DescriptorPool::Tables::AllocateMessage(Type* /* dummy */) { Type* result = new Type; messages_.push_back(result); @@ -1232,7 +1238,8 @@ const SourceCodeInfo_Location* FileDescriptorTables::GetSourceLocation( const std::vector& path, const SourceCodeInfo* info) const { std::pair p( std::make_pair(this, info)); - locations_by_path_once_.Init(&FileDescriptorTables::BuildLocationsByPath, &p); + internal::call_once(locations_by_path_once_, + FileDescriptorTables::BuildLocationsByPath, &p); return FindPtrOrNull(locations_by_path_, Join(path, ",")); } @@ -1242,42 +1249,41 @@ const SourceCodeInfo_Location* FileDescriptorTables::GetSourceLocation( DescriptorPool::ErrorCollector::~ErrorCollector() {} DescriptorPool::DescriptorPool() - : mutex_(NULL), - fallback_database_(NULL), - default_error_collector_(NULL), - underlay_(NULL), - tables_(new Tables), - enforce_dependencies_(true), - lazily_build_dependencies_(false), - allow_unknown_(false), - enforce_weak_(false), - disallow_enforce_utf8_(false) {} + : mutex_(NULL), + fallback_database_(NULL), + default_error_collector_(NULL), + underlay_(NULL), + tables_(new Tables), + enforce_dependencies_(true), + lazily_build_dependencies_(false), + allow_unknown_(false), + enforce_weak_(false), + disallow_enforce_utf8_(false) {} DescriptorPool::DescriptorPool(DescriptorDatabase* fallback_database, ErrorCollector* error_collector) - : mutex_(new Mutex), - fallback_database_(fallback_database), - default_error_collector_(error_collector), - underlay_(NULL), - tables_(new Tables), - enforce_dependencies_(true), - lazily_build_dependencies_(false), - allow_unknown_(false), - enforce_weak_(false), - disallow_enforce_utf8_(false) { -} + : mutex_(new internal::WrappedMutex), + fallback_database_(fallback_database), + default_error_collector_(error_collector), + underlay_(NULL), + tables_(new Tables), + enforce_dependencies_(true), + lazily_build_dependencies_(false), + allow_unknown_(false), + enforce_weak_(false), + disallow_enforce_utf8_(false) {} DescriptorPool::DescriptorPool(const DescriptorPool* underlay) - : mutex_(NULL), - fallback_database_(NULL), - default_error_collector_(NULL), - underlay_(underlay), - tables_(new Tables), - enforce_dependencies_(true), - lazily_build_dependencies_(false), - allow_unknown_(false), - enforce_weak_(false), - disallow_enforce_utf8_(false) {} + : mutex_(NULL), + fallback_database_(NULL), + default_error_collector_(NULL), + underlay_(underlay), + tables_(new Tables), + enforce_dependencies_(true), + lazily_build_dependencies_(false), + allow_unknown_(false), + enforce_weak_(false), + disallow_enforce_utf8_(false) {} DescriptorPool::~DescriptorPool() { if (mutex_ != NULL) delete mutex_; @@ -1290,7 +1296,7 @@ void DescriptorPool::InternalDontEnforceDependencies() { enforce_dependencies_ = false; } -void DescriptorPool::AddUnusedImportTrackFile(const string& file_name) { +void DescriptorPool::AddUnusedImportTrackFile(const std::string& file_name) { unused_import_track_files_.insert(file_name); } @@ -1298,7 +1304,7 @@ void DescriptorPool::ClearUnusedImportTrackFiles() { unused_import_track_files_.clear(); } -bool DescriptorPool::InternalIsFileLoaded(const string& filename) const { +bool DescriptorPool::InternalIsFileLoaded(const std::string& filename) const { MutexLockMaybe lock(mutex_); return tables_->FindFile(filename) != NULL; } @@ -1307,6 +1313,7 @@ bool DescriptorPool::InternalIsFileLoaded(const string& filename) const { namespace { + EncodedDescriptorDatabase* GeneratedDatabase() { static auto generated_database = internal::OnShutdownDelete(new EncodedDescriptorDatabase()); @@ -1331,6 +1338,8 @@ const DescriptorPool* DescriptorPool::generated_pool() { return internal_generated_pool(); } + + void DescriptorPool::InternalAddGeneratedFile( const void* encoded_file_descriptor, int size) { // So, this function is called in the process of initializing the @@ -1365,7 +1374,8 @@ void DescriptorPool::InternalAddGeneratedFile( // there's any good way to factor it out. Think about this some time when // there's nothing more important to do (read: never). -const FileDescriptor* DescriptorPool::FindFileByName(const string& name) const { +const FileDescriptor* DescriptorPool::FindFileByName( + const std::string& name) const { MutexLockMaybe lock(mutex_); if (fallback_database_ != NULL) { tables_->known_bad_symbols_.clear(); @@ -1385,7 +1395,7 @@ const FileDescriptor* DescriptorPool::FindFileByName(const string& name) const { } const FileDescriptor* DescriptorPool::FindFileContainingSymbol( - const string& symbol_name) const { + const std::string& symbol_name) const { MutexLockMaybe lock(mutex_); if (fallback_database_ != NULL) { tables_->known_bad_symbols_.clear(); @@ -1395,7 +1405,7 @@ const FileDescriptor* DescriptorPool::FindFileContainingSymbol( if (!result.IsNull()) return result.GetFile(); if (underlay_ != NULL) { const FileDescriptor* file_result = - underlay_->FindFileContainingSymbol(symbol_name); + underlay_->FindFileContainingSymbol(symbol_name); if (file_result != NULL) return file_result; } if (TryFindSymbolInFallbackDatabase(symbol_name)) { @@ -1406,13 +1416,13 @@ const FileDescriptor* DescriptorPool::FindFileContainingSymbol( } const Descriptor* DescriptorPool::FindMessageTypeByName( - const string& name) const { + const std::string& name) const { Symbol result = tables_->FindByNameHelper(this, name); return (result.type == Symbol::MESSAGE) ? result.descriptor : NULL; } const FieldDescriptor* DescriptorPool::FindFieldByName( - const string& name) const { + const std::string& name) const { Symbol result = tables_->FindByNameHelper(this, name); if (result.type == Symbol::FIELD && !result.field_descriptor->is_extension()) { @@ -1423,10 +1433,9 @@ const FieldDescriptor* DescriptorPool::FindFieldByName( } const FieldDescriptor* DescriptorPool::FindExtensionByName( - const string& name) const { + const std::string& name) const { Symbol result = tables_->FindByNameHelper(this, name); - if (result.type == Symbol::FIELD && - result.field_descriptor->is_extension()) { + if (result.type == Symbol::FIELD && result.field_descriptor->is_extension()) { return result.field_descriptor; } else { return NULL; @@ -1434,32 +1443,32 @@ const FieldDescriptor* DescriptorPool::FindExtensionByName( } const OneofDescriptor* DescriptorPool::FindOneofByName( - const string& name) const { + const std::string& name) const { Symbol result = tables_->FindByNameHelper(this, name); return (result.type == Symbol::ONEOF) ? result.oneof_descriptor : NULL; } const EnumDescriptor* DescriptorPool::FindEnumTypeByName( - const string& name) const { + const std::string& name) const { Symbol result = tables_->FindByNameHelper(this, name); return (result.type == Symbol::ENUM) ? result.enum_descriptor : NULL; } const EnumValueDescriptor* DescriptorPool::FindEnumValueByName( - const string& name) const { + const std::string& name) const { Symbol result = tables_->FindByNameHelper(this, name); - return (result.type == Symbol::ENUM_VALUE) ? - result.enum_value_descriptor : NULL; + return (result.type == Symbol::ENUM_VALUE) ? result.enum_value_descriptor + : NULL; } const ServiceDescriptor* DescriptorPool::FindServiceByName( - const string& name) const { + const std::string& name) const { Symbol result = tables_->FindByNameHelper(this, name); return (result.type == Symbol::SERVICE) ? result.service_descriptor : NULL; } const MethodDescriptor* DescriptorPool::FindMethodByName( - const string& name) const { + const std::string& name) const { Symbol result = tables_->FindByNameHelper(this, name); return (result.type == Symbol::METHOD) ? result.method_descriptor : NULL; } @@ -1532,10 +1541,8 @@ void DescriptorPool::FindAllExtensions( // ------------------------------------------------------------------- -const FieldDescriptor* -Descriptor::FindFieldByNumber(int key) const { - const FieldDescriptor* result = - file()->tables_->FindFieldByNumber(this, key); +const FieldDescriptor* Descriptor::FindFieldByNumber(int key) const { + const FieldDescriptor* result = file()->tables_->FindFieldByNumber(this, key); if (result == NULL || result->is_extension()) { return NULL; } else { @@ -1543,10 +1550,10 @@ Descriptor::FindFieldByNumber(int key) const { } } -const FieldDescriptor* -Descriptor::FindFieldByLowercaseName(const string& key) const { +const FieldDescriptor* Descriptor::FindFieldByLowercaseName( + const std::string& key) const { const FieldDescriptor* result = - file()->tables_->FindFieldByLowercaseName(this, key); + file()->tables_->FindFieldByLowercaseName(this, key); if (result == NULL || result->is_extension()) { return NULL; } else { @@ -1554,10 +1561,10 @@ Descriptor::FindFieldByLowercaseName(const string& key) const { } } -const FieldDescriptor* -Descriptor::FindFieldByCamelcaseName(const string& key) const { +const FieldDescriptor* Descriptor::FindFieldByCamelcaseName( + const std::string& key) const { const FieldDescriptor* result = - file()->tables_->FindFieldByCamelcaseName(this, key); + file()->tables_->FindFieldByCamelcaseName(this, key); if (result == NULL || result->is_extension()) { return NULL; } else { @@ -1565,10 +1572,10 @@ Descriptor::FindFieldByCamelcaseName(const string& key) const { } } -const FieldDescriptor* -Descriptor::FindFieldByName(const string& key) const { +const FieldDescriptor* Descriptor::FindFieldByName( + const std::string& key) const { Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::FIELD); + file()->tables_->FindNestedSymbolOfType(this, key, Symbol::FIELD); if (!result.IsNull() && !result.field_descriptor->is_extension()) { return result.field_descriptor; } else { @@ -1576,10 +1583,10 @@ Descriptor::FindFieldByName(const string& key) const { } } -const OneofDescriptor* -Descriptor::FindOneofByName(const string& key) const { +const OneofDescriptor* Descriptor::FindOneofByName( + const std::string& key) const { Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ONEOF); + file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ONEOF); if (!result.IsNull()) { return result.oneof_descriptor; } else { @@ -1587,10 +1594,10 @@ Descriptor::FindOneofByName(const string& key) const { } } -const FieldDescriptor* -Descriptor::FindExtensionByName(const string& key) const { +const FieldDescriptor* Descriptor::FindExtensionByName( + const std::string& key) const { Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::FIELD); + file()->tables_->FindNestedSymbolOfType(this, key, Symbol::FIELD); if (!result.IsNull() && result.field_descriptor->is_extension()) { return result.field_descriptor; } else { @@ -1598,10 +1605,10 @@ Descriptor::FindExtensionByName(const string& key) const { } } -const FieldDescriptor* -Descriptor::FindExtensionByLowercaseName(const string& key) const { +const FieldDescriptor* Descriptor::FindExtensionByLowercaseName( + const std::string& key) const { const FieldDescriptor* result = - file()->tables_->FindFieldByLowercaseName(this, key); + file()->tables_->FindFieldByLowercaseName(this, key); if (result == NULL || !result->is_extension()) { return NULL; } else { @@ -1609,10 +1616,10 @@ Descriptor::FindExtensionByLowercaseName(const string& key) const { } } -const FieldDescriptor* -Descriptor::FindExtensionByCamelcaseName(const string& key) const { +const FieldDescriptor* Descriptor::FindExtensionByCamelcaseName( + const std::string& key) const { const FieldDescriptor* result = - file()->tables_->FindFieldByCamelcaseName(this, key); + file()->tables_->FindFieldByCamelcaseName(this, key); if (result == NULL || !result->is_extension()) { return NULL; } else { @@ -1620,10 +1627,10 @@ Descriptor::FindExtensionByCamelcaseName(const string& key) const { } } -const Descriptor* -Descriptor::FindNestedTypeByName(const string& key) const { +const Descriptor* Descriptor::FindNestedTypeByName( + const std::string& key) const { Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::MESSAGE); + file()->tables_->FindNestedSymbolOfType(this, key, Symbol::MESSAGE); if (!result.IsNull()) { return result.descriptor; } else { @@ -1631,10 +1638,10 @@ Descriptor::FindNestedTypeByName(const string& key) const { } } -const EnumDescriptor* -Descriptor::FindEnumTypeByName(const string& key) const { +const EnumDescriptor* Descriptor::FindEnumTypeByName( + const std::string& key) const { Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM); + file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM); if (!result.IsNull()) { return result.enum_descriptor; } else { @@ -1642,10 +1649,10 @@ Descriptor::FindEnumTypeByName(const string& key) const { } } -const EnumValueDescriptor* -Descriptor::FindEnumValueByName(const string& key) const { +const EnumValueDescriptor* Descriptor::FindEnumValueByName( + const std::string& key) const { Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE); + file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE); if (!result.IsNull()) { return result.enum_value_descriptor; } else { @@ -1653,10 +1660,10 @@ Descriptor::FindEnumValueByName(const string& key) const { } } -const EnumValueDescriptor* -EnumDescriptor::FindValueByName(const string& key) const { +const EnumValueDescriptor* EnumDescriptor::FindValueByName( + const std::string& key) const { Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE); + file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE); if (!result.IsNull()) { return result.enum_value_descriptor; } else { @@ -1664,20 +1671,19 @@ EnumDescriptor::FindValueByName(const string& key) const { } } -const EnumValueDescriptor* -EnumDescriptor::FindValueByNumber(int key) const { +const EnumValueDescriptor* EnumDescriptor::FindValueByNumber(int key) const { return file()->tables_->FindEnumValueByNumber(this, key); } -const EnumValueDescriptor* -EnumDescriptor::FindValueByNumberCreatingIfUnknown(int key) const { +const EnumValueDescriptor* EnumDescriptor::FindValueByNumberCreatingIfUnknown( + int key) const { return file()->tables_->FindEnumValueByNumberCreatingIfUnknown(this, key); } -const MethodDescriptor* -ServiceDescriptor::FindMethodByName(const string& key) const { +const MethodDescriptor* ServiceDescriptor::FindMethodByName( + const std::string& key) const { Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::METHOD); + file()->tables_->FindNestedSymbolOfType(this, key, Symbol::METHOD); if (!result.IsNull()) { return result.method_descriptor; } else { @@ -1685,8 +1691,8 @@ ServiceDescriptor::FindMethodByName(const string& key) const { } } -const Descriptor* -FileDescriptor::FindMessageTypeByName(const string& key) const { +const Descriptor* FileDescriptor::FindMessageTypeByName( + const std::string& key) const { Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::MESSAGE); if (!result.IsNull()) { return result.descriptor; @@ -1695,8 +1701,8 @@ FileDescriptor::FindMessageTypeByName(const string& key) const { } } -const EnumDescriptor* -FileDescriptor::FindEnumTypeByName(const string& key) const { +const EnumDescriptor* FileDescriptor::FindEnumTypeByName( + const std::string& key) const { Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM); if (!result.IsNull()) { return result.enum_descriptor; @@ -1705,10 +1711,10 @@ FileDescriptor::FindEnumTypeByName(const string& key) const { } } -const EnumValueDescriptor* -FileDescriptor::FindEnumValueByName(const string& key) const { +const EnumValueDescriptor* FileDescriptor::FindEnumValueByName( + const std::string& key) const { Symbol result = - tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE); + tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE); if (!result.IsNull()) { return result.enum_value_descriptor; } else { @@ -1716,8 +1722,8 @@ FileDescriptor::FindEnumValueByName(const string& key) const { } } -const ServiceDescriptor* -FileDescriptor::FindServiceByName(const string& key) const { +const ServiceDescriptor* FileDescriptor::FindServiceByName( + const std::string& key) const { Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::SERVICE); if (!result.IsNull()) { return result.service_descriptor; @@ -1726,8 +1732,8 @@ FileDescriptor::FindServiceByName(const string& key) const { } } -const FieldDescriptor* -FileDescriptor::FindExtensionByName(const string& key) const { +const FieldDescriptor* FileDescriptor::FindExtensionByName( + const std::string& key) const { Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::FIELD); if (!result.IsNull() && result.field_descriptor->is_extension()) { return result.field_descriptor; @@ -1736,8 +1742,8 @@ FileDescriptor::FindExtensionByName(const string& key) const { } } -const FieldDescriptor* -FileDescriptor::FindExtensionByLowercaseName(const string& key) const { +const FieldDescriptor* FileDescriptor::FindExtensionByLowercaseName( + const std::string& key) const { const FieldDescriptor* result = tables_->FindFieldByLowercaseName(this, key); if (result == NULL || !result->is_extension()) { return NULL; @@ -1746,8 +1752,8 @@ FileDescriptor::FindExtensionByLowercaseName(const string& key) const { } } -const FieldDescriptor* -FileDescriptor::FindExtensionByCamelcaseName(const string& key) const { +const FieldDescriptor* FileDescriptor::FindExtensionByCamelcaseName( + const std::string& key) const { const FieldDescriptor* result = tables_->FindFieldByCamelcaseName(this, key); if (result == NULL || !result->is_extension()) { return NULL; @@ -1760,7 +1766,7 @@ void Descriptor::ExtensionRange::CopyTo( DescriptorProto_ExtensionRange* proto) const { proto->set_start(this->start); proto->set_end(this->end); - if (options_ != &google::protobuf::ExtensionRangeOptions::default_instance()) { + if (options_ != &ExtensionRangeOptions::default_instance()) { *proto->mutable_options() = *options_; } } @@ -1771,19 +1777,18 @@ Descriptor::FindExtensionRangeContainingNumber(int number) const { // more than a couple extension ranges. for (int i = 0; i < extension_range_count(); i++) { if (number >= extension_range(i)->start && - number < extension_range(i)->end) { + number < extension_range(i)->end) { return extension_range(i); } } return NULL; } -const Descriptor::ReservedRange* -Descriptor::FindReservedRangeContainingNumber(int number) const { +const Descriptor::ReservedRange* Descriptor::FindReservedRangeContainingNumber( + int number) const { // TODO(chrisn): Consider a non-linear search. for (int i = 0; i < reserved_range_count(); i++) { - if (number >= reserved_range(i)->start && - number < reserved_range(i)->end) { + if (number >= reserved_range(i)->start && number < reserved_range(i)->end) { return reserved_range(i); } } @@ -1804,7 +1809,8 @@ EnumDescriptor::FindReservedRangeContainingNumber(int number) const { // ------------------------------------------------------------------- -bool DescriptorPool::TryFindFileInFallbackDatabase(const string& name) const { +bool DescriptorPool::TryFindFileInFallbackDatabase( + const std::string& name) const { if (fallback_database_ == NULL) return false; if (tables_->known_bad_files_.count(name) > 0) return false; @@ -1818,11 +1824,11 @@ bool DescriptorPool::TryFindFileInFallbackDatabase(const string& name) const { return true; } -bool DescriptorPool::IsSubSymbolOfBuiltType(const string& name) const { - string prefix = name; +bool DescriptorPool::IsSubSymbolOfBuiltType(const std::string& name) const { + std::string prefix = name; for (;;) { - string::size_type dot_pos = prefix.find_last_of('.'); - if (dot_pos == string::npos) { + std::string::size_type dot_pos = prefix.find_last_of('.'); + if (dot_pos == std::string::npos) { break; } prefix = prefix.substr(0, dot_pos); @@ -1840,28 +1846,29 @@ bool DescriptorPool::IsSubSymbolOfBuiltType(const string& name) const { return false; } -bool DescriptorPool::TryFindSymbolInFallbackDatabase(const string& name) const { +bool DescriptorPool::TryFindSymbolInFallbackDatabase( + const std::string& name) const { if (fallback_database_ == NULL) return false; if (tables_->known_bad_symbols_.count(name) > 0) return false; FileDescriptorProto file_proto; - if (// We skip looking in the fallback database if the name is a sub-symbol - // of any descriptor that already exists in the descriptor pool (except - // for package descriptors). This is valid because all symbols except - // for packages are defined in a single file, so if the symbol exists - // then we should already have its definition. - // - // The other reason to do this is to support "overriding" type - // definitions by merging two databases that define the same type. (Yes, - // people do this.) The main difficulty with making this work is that - // FindFileContainingSymbol() is allowed to return both false positives - // (e.g., SimpleDescriptorDatabase, UpgradedDescriptorDatabase) and false - // negatives (e.g. ProtoFileParser, SourceTreeDescriptorDatabase). - // When two such databases are merged, looking up a non-existent - // sub-symbol of a type that already exists in the descriptor pool can - // result in an attempt to load multiple definitions of the same type. - // The check below avoids this. + if ( // We skip looking in the fallback database if the name is a sub-symbol + // of any descriptor that already exists in the descriptor pool (except + // for package descriptors). This is valid because all symbols except + // for packages are defined in a single file, so if the symbol exists + // then we should already have its definition. + // + // The other reason to do this is to support "overriding" type + // definitions by merging two databases that define the same type. (Yes, + // people do this.) The main difficulty with making this work is that + // FindFileContainingSymbol() is allowed to return both false positives + // (e.g., SimpleDescriptorDatabase, UpgradedDescriptorDatabase) and + // false negatives (e.g. ProtoFileParser, SourceTreeDescriptorDatabase). + // When two such databases are merged, looking up a non-existent + // sub-symbol of a type that already exists in the descriptor pool can + // result in an attempt to load multiple definitions of the same type. + // The check below avoids this. IsSubSymbolOfBuiltType(name) // Look up file containing this symbol in fallback database. @@ -1887,7 +1894,7 @@ bool DescriptorPool::TryFindExtensionInFallbackDatabase( FileDescriptorProto file_proto; if (!fallback_database_->FindFileContainingExtension( - containing_type->full_name(), field_number, &file_proto)) { + containing_type->full_name(), field_number, &file_proto)) { return false; } @@ -1911,20 +1918,21 @@ bool FieldDescriptor::is_map_message_type() const { return message_type_->options().map_entry(); } -string FieldDescriptor::DefaultValueAsString(bool quote_string_type) const { +std::string FieldDescriptor::DefaultValueAsString( + bool quote_string_type) const { GOOGLE_CHECK(has_default_value()) << "No default value"; switch (cpp_type()) { case CPPTYPE_INT32: - return SimpleItoa(default_value_int32()); + return StrCat(default_value_int32()); break; case CPPTYPE_INT64: - return SimpleItoa(default_value_int64()); + return StrCat(default_value_int64()); break; case CPPTYPE_UINT32: - return SimpleItoa(default_value_uint32()); + return StrCat(default_value_uint32()); break; case CPPTYPE_UINT64: - return SimpleItoa(default_value_uint64()); + return StrCat(default_value_uint64()); break; case CPPTYPE_FLOAT: return SimpleFtoa(default_value_float()); @@ -2079,9 +2087,9 @@ void FieldDescriptor::CopyTo(FieldDescriptorProto* proto) const { // Some compilers do not allow static_cast directly between two enum types, // so we must cast to int first. proto->set_label(static_cast( - implicit_cast(label()))); + implicit_cast(label()))); proto->set_type(static_cast( - implicit_cast(type()))); + implicit_cast(type()))); if (is_extension()) { if (!containing_type()->is_unqualified_placeholder_) { @@ -2202,8 +2210,9 @@ void MethodDescriptor::CopyTo(MethodDescriptorProto* proto) const { namespace { -bool RetrieveOptionsAssumingRightPool(int depth, const Message& options, - std::vector* option_entries) { +bool RetrieveOptionsAssumingRightPool( + int depth, const Message& options, + std::vector* option_entries) { option_entries->clear(); const Reflection* reflection = options.GetReflection(); std::vector fields; @@ -2216,13 +2225,13 @@ bool RetrieveOptionsAssumingRightPool(int depth, const Message& options, repeated = true; } for (int j = 0; j < count; j++) { - string fieldval; + std::string fieldval; if (fields[i]->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - string tmp; + std::string tmp; TextFormat::Printer printer; printer.SetInitialIndentLevel(depth + 1); - printer.PrintFieldValueToString(options, fields[i], - repeated ? j : -1, &tmp); + printer.PrintFieldValueToString(options, fields[i], repeated ? j : -1, + &tmp); fieldval.append("{\n"); fieldval.append(tmp); fieldval.append(depth * 2, ' '); @@ -2231,7 +2240,7 @@ bool RetrieveOptionsAssumingRightPool(int depth, const Message& options, TextFormat::PrintFieldValueToString(options, fields[i], repeated ? j : -1, &fieldval); } - string name; + std::string name; if (fields[i]->is_extension()) { name = "(." + fields[i]->full_name() + ")"; } else { @@ -2246,7 +2255,7 @@ bool RetrieveOptionsAssumingRightPool(int depth, const Message& options, // Used by each of the option formatters. bool RetrieveOptions(int depth, const Message& options, const DescriptorPool* pool, - std::vector* option_entries) { + std::vector* option_entries) { // When printing custom options for a descriptor, we must use an options // message built on top of the same DescriptorPool where the descriptor // is coming from. This is to ensure we are interpreting custom options @@ -2257,9 +2266,8 @@ bool RetrieveOptions(int depth, const Message& options, const Descriptor* option_descriptor = pool->FindMessageTypeByName(options.GetDescriptor()->full_name()); if (option_descriptor == NULL) { - // google/protobuf/descriptor.proto is not in the pool. This means no - // custom options are used so we are safe to proceed with the compiled - // options message type. + // descriptor.proto is not in the pool. This means no custom options are + // used so we are safe to proceed with the compiled options message type. return RetrieveOptionsAssumingRightPool(depth, options, option_entries); } DynamicMessageFactory factory; @@ -2279,8 +2287,8 @@ bool RetrieveOptions(int depth, const Message& options, // Formats options that all appear together in brackets. Does not include // brackets. bool FormatBracketedOptions(int depth, const Message& options, - const DescriptorPool* pool, string* output) { - std::vector all_options; + const DescriptorPool* pool, std::string* output) { + std::vector all_options; if (RetrieveOptions(depth, options, pool, &all_options)) { output->append(Join(all_options, ", ")); } @@ -2289,13 +2297,13 @@ bool FormatBracketedOptions(int depth, const Message& options, // Formats options one per line bool FormatLineOptions(int depth, const Message& options, - const DescriptorPool* pool, string* output) { - string prefix(depth * 2, ' '); - std::vector all_options; + const DescriptorPool* pool, std::string* output) { + std::string prefix(depth * 2, ' '); + std::vector all_options; if (RetrieveOptions(depth, options, pool, &all_options)) { for (int i = 0; i < all_options.size(); i++) { - strings::SubstituteAndAppend(output, "$0option $1;\n", - prefix, all_options[i]); + strings::SubstituteAndAppend(output, "$0option $1;\n", prefix, + all_options[i]); } } return !all_options.empty(); @@ -2303,30 +2311,29 @@ bool FormatLineOptions(int depth, const Message& options, class SourceLocationCommentPrinter { public: - template - SourceLocationCommentPrinter(const DescType* desc, - const string& prefix, + template + SourceLocationCommentPrinter(const DescType* desc, const std::string& prefix, const DebugStringOptions& options) : options_(options), prefix_(prefix) { // Perform the SourceLocation lookup only if we're including user comments, // because the lookup is fairly expensive. - have_source_loc_ = options.include_comments && - desc->GetSourceLocation(&source_loc_); + have_source_loc_ = + options.include_comments && desc->GetSourceLocation(&source_loc_); } SourceLocationCommentPrinter(const FileDescriptor* file, const std::vector& path, - const string& prefix, + const std::string& prefix, const DebugStringOptions& options) : options_(options), prefix_(prefix) { // Perform the SourceLocation lookup only if we're including user comments, // because the lookup is fairly expensive. - have_source_loc_ = options.include_comments && - file->GetSourceLocation(path, &source_loc_); + have_source_loc_ = + options.include_comments && file->GetSourceLocation(path, &source_loc_); } - void AddPreComment(string* output) { + void AddPreComment(std::string* output) { if (have_source_loc_) { // Detached leading comments. - for (int i = 0 ; i < source_loc_.leading_detached_comments.size(); ++i) { + for (int i = 0; i < source_loc_.leading_detached_comments.size(); ++i) { *output += FormatComment(source_loc_.leading_detached_comments[i]); *output += "\n"; } @@ -2336,7 +2343,7 @@ class SourceLocationCommentPrinter { } } } - void AddPostComment(string* output) { + void AddPostComment(std::string* output) { if (have_source_loc_ && source_loc_.trailing_comments.size() > 0) { *output += FormatComment(source_loc_.trailing_comments); } @@ -2344,13 +2351,13 @@ class SourceLocationCommentPrinter { // Format comment such that each line becomes a full-line C++-style comment in // the DebugString() output. - string FormatComment(const string& comment_text) { - string stripped_comment = comment_text; + std::string FormatComment(const std::string& comment_text) { + std::string stripped_comment = comment_text; StripWhitespace(&stripped_comment); - std::vector lines = Split(stripped_comment, "\n"); - string output; + std::vector lines = Split(stripped_comment, "\n"); + std::string output; for (int i = 0; i < lines.size(); ++i) { - const string& line = lines[i]; + const std::string& line = lines[i]; strings::SubstituteAndAppend(&output, "$0// $1\n", prefix_, line); } return output; @@ -2361,32 +2368,31 @@ class SourceLocationCommentPrinter { bool have_source_loc_; SourceLocation source_loc_; DebugStringOptions options_; - string prefix_; + std::string prefix_; }; } // anonymous namespace -string FileDescriptor::DebugString() const { +std::string FileDescriptor::DebugString() const { DebugStringOptions options; // default options return DebugStringWithOptions(options); } -string FileDescriptor::DebugStringWithOptions( +std::string FileDescriptor::DebugStringWithOptions( const DebugStringOptions& debug_string_options) const { - string contents; + std::string contents; { std::vector path; path.push_back(FileDescriptorProto::kSyntaxFieldNumber); - SourceLocationCommentPrinter syntax_comment( - this, path, "", debug_string_options); + SourceLocationCommentPrinter syntax_comment(this, path, "", + debug_string_options); syntax_comment.AddPreComment(&contents); strings::SubstituteAndAppend(&contents, "syntax = \"$0\";\n\n", SyntaxName(syntax())); syntax_comment.AddPostComment(&contents); } - SourceLocationCommentPrinter - comment_printer(this, "", debug_string_options); + SourceLocationCommentPrinter comment_printer(this, "", debug_string_options); comment_printer.AddPreComment(&contents); std::set public_dependencies; @@ -2412,8 +2418,8 @@ string FileDescriptor::DebugStringWithOptions( if (!package().empty()) { std::vector path; path.push_back(FileDescriptorProto::kPackageFieldNumber); - SourceLocationCommentPrinter package_comment( - this, path, "", debug_string_options); + SourceLocationCommentPrinter package_comment(this, path, "", + debug_string_options); package_comment.AddPreComment(&contents); strings::SubstituteAndAppend(&contents, "package $0;\n\n", package()); package_comment.AddPostComment(&contents); @@ -2468,31 +2474,30 @@ string FileDescriptor::DebugStringWithOptions( return contents; } -string Descriptor::DebugString() const { +std::string Descriptor::DebugString() const { DebugStringOptions options; // default options return DebugStringWithOptions(options); } -string Descriptor::DebugStringWithOptions( +std::string Descriptor::DebugStringWithOptions( const DebugStringOptions& options) const { - string contents; + std::string contents; DebugString(0, &contents, options, /* include_opening_clause */ true); return contents; } -void Descriptor::DebugString(int depth, string *contents, - const DebugStringOptions& - debug_string_options, +void Descriptor::DebugString(int depth, std::string* contents, + const DebugStringOptions& debug_string_options, bool include_opening_clause) const { if (options().map_entry()) { // Do not generate debug string for auto-generated map-entry type. return; } - string prefix(depth * 2, ' '); + std::string prefix(depth * 2, ' '); ++depth; - SourceLocationCommentPrinter - comment_printer(this, prefix, debug_string_options); + SourceLocationCommentPrinter comment_printer(this, prefix, + debug_string_options); comment_printer.AddPreComment(contents); if (include_opening_clause) { @@ -2538,8 +2543,7 @@ void Descriptor::DebugString(int depth, string *contents, } for (int i = 0; i < extension_range_count(); i++) { - strings::SubstituteAndAppend(contents, "$0 extensions $1 to $2;\n", - prefix, + strings::SubstituteAndAppend(contents, "$0 extensions $1 to $2;\n", prefix, extension_range(i)->start, extension_range(i)->end - 1); } @@ -2550,12 +2554,11 @@ void Descriptor::DebugString(int depth, string *contents, if (extension(i)->containing_type() != containing_type) { if (i > 0) strings::SubstituteAndAppend(contents, "$0 }\n", prefix); containing_type = extension(i)->containing_type(); - strings::SubstituteAndAppend(contents, "$0 extend .$1 {\n", - prefix, containing_type->full_name()); + strings::SubstituteAndAppend(contents, "$0 extend .$1 {\n", prefix, + containing_type->full_name()); } - extension(i)->DebugString( - depth + 1, FieldDescriptor::PRINT_LABEL, contents, - debug_string_options); + extension(i)->DebugString(depth + 1, FieldDescriptor::PRINT_LABEL, contents, + debug_string_options); } if (extension_count() > 0) strings::SubstituteAndAppend(contents, "$0 }\n", prefix); @@ -2567,8 +2570,8 @@ void Descriptor::DebugString(int depth, string *contents, if (range->end == range->start + 1) { strings::SubstituteAndAppend(contents, "$0, ", range->start); } else { - strings::SubstituteAndAppend(contents, "$0 to $1, ", - range->start, range->end - 1); + strings::SubstituteAndAppend(contents, "$0 to $1, ", range->start, + range->end - 1); } } contents->replace(contents->size() - 2, 2, ";\n"); @@ -2587,14 +2590,14 @@ void Descriptor::DebugString(int depth, string *contents, comment_printer.AddPostComment(contents); } -string FieldDescriptor::DebugString() const { +std::string FieldDescriptor::DebugString() const { DebugStringOptions options; // default options return DebugStringWithOptions(options); } -string FieldDescriptor::DebugStringWithOptions( +std::string FieldDescriptor::DebugStringWithOptions( const DebugStringOptions& debug_string_options) const { - string contents; + std::string contents; int depth = 0; if (is_extension()) { strings::SubstituteAndAppend(&contents, "extend .$0 {\n", @@ -2609,8 +2612,8 @@ string FieldDescriptor::DebugStringWithOptions( } // The field type string used in FieldDescriptor::DebugString() -string FieldDescriptor::FieldTypeNameDebugString() const { - switch(type()) { +std::string FieldDescriptor::FieldTypeNameDebugString() const { + switch (type()) { case TYPE_MESSAGE: return "." + message_type()->full_name(); case TYPE_ENUM: @@ -2620,13 +2623,11 @@ string FieldDescriptor::FieldTypeNameDebugString() const { } } -void FieldDescriptor::DebugString(int depth, - PrintLabelFlag print_label_flag, - string *contents, - const DebugStringOptions& - debug_string_options) const { - string prefix(depth * 2, ' '); - string field_type; +void FieldDescriptor::DebugString( + int depth, PrintLabelFlag print_label_flag, std::string* contents, + const DebugStringOptions& debug_string_options) const { + std::string prefix(depth * 2, ' '); + std::string field_type; // Special case map fields. if (is_map()) { @@ -2648,23 +2649,19 @@ void FieldDescriptor::DebugString(int depth, } else if (is_map()) { print_label = false; } - string label; + std::string label; if (print_label) { label = kLabelToName[this->label()]; label.push_back(' '); } - SourceLocationCommentPrinter - comment_printer(this, prefix, debug_string_options); + SourceLocationCommentPrinter comment_printer(this, prefix, + debug_string_options); comment_printer.AddPreComment(contents); - strings::SubstituteAndAppend(contents, "$0$1$2 $3 = $4", - prefix, - label, - field_type, - type() == TYPE_GROUP ? message_type()->name() : - name(), - number()); + strings::SubstituteAndAppend( + contents, "$0$1$2 $3 = $4", prefix, label, field_type, + type() == TYPE_GROUP ? message_type()->name() : name(), number()); bool bracketed = false; if (has_default_value()) { @@ -2684,7 +2681,7 @@ void FieldDescriptor::DebugString(int depth, contents->append("\""); } - string formatted_options; + std::string formatted_options; if (FormatBracketedOptions(depth, options(), file()->pool(), &formatted_options)) { contents->append(bracketed ? ", " : " ["); @@ -2710,25 +2707,25 @@ void FieldDescriptor::DebugString(int depth, comment_printer.AddPostComment(contents); } -string OneofDescriptor::DebugString() const { +std::string OneofDescriptor::DebugString() const { DebugStringOptions options; // default values return DebugStringWithOptions(options); } -string OneofDescriptor::DebugStringWithOptions( +std::string OneofDescriptor::DebugStringWithOptions( const DebugStringOptions& options) const { - string contents; + std::string contents; DebugString(0, &contents, options); return contents; } -void OneofDescriptor::DebugString(int depth, string* contents, - const DebugStringOptions& - debug_string_options) const { - string prefix(depth * 2, ' '); +void OneofDescriptor::DebugString( + int depth, std::string* contents, + const DebugStringOptions& debug_string_options) const { + std::string prefix(depth * 2, ' '); ++depth; - SourceLocationCommentPrinter - comment_printer(this, prefix, debug_string_options); + SourceLocationCommentPrinter comment_printer(this, prefix, + debug_string_options); comment_printer.AddPreComment(contents); strings::SubstituteAndAppend(contents, "$0oneof $1 {", prefix, name()); @@ -2748,30 +2745,29 @@ void OneofDescriptor::DebugString(int depth, string* contents, comment_printer.AddPostComment(contents); } -string EnumDescriptor::DebugString() const { +std::string EnumDescriptor::DebugString() const { DebugStringOptions options; // default values return DebugStringWithOptions(options); } -string EnumDescriptor::DebugStringWithOptions( +std::string EnumDescriptor::DebugStringWithOptions( const DebugStringOptions& options) const { - string contents; + std::string contents; DebugString(0, &contents, options); return contents; } -void EnumDescriptor::DebugString(int depth, string *contents, - const DebugStringOptions& - debug_string_options) const { - string prefix(depth * 2, ' '); +void EnumDescriptor::DebugString( + int depth, std::string* contents, + const DebugStringOptions& debug_string_options) const { + std::string prefix(depth * 2, ' '); ++depth; - SourceLocationCommentPrinter - comment_printer(this, prefix, debug_string_options); + SourceLocationCommentPrinter comment_printer(this, prefix, + debug_string_options); comment_printer.AddPreComment(contents); - strings::SubstituteAndAppend(contents, "$0enum $1 {\n", - prefix, name()); + strings::SubstituteAndAppend(contents, "$0enum $1 {\n", prefix, name()); FormatLineOptions(depth, options(), file()->pool(), contents); @@ -2786,8 +2782,8 @@ void EnumDescriptor::DebugString(int depth, string *contents, if (range->end == range->start) { strings::SubstituteAndAppend(contents, "$0, ", range->start); } else { - strings::SubstituteAndAppend(contents, "$0 to $1, ", - range->start, range->end); + strings::SubstituteAndAppend(contents, "$0 to $1, ", range->start, + range->end); } } contents->replace(contents->size() - 2, 2, ";\n"); @@ -2807,31 +2803,30 @@ void EnumDescriptor::DebugString(int depth, string *contents, comment_printer.AddPostComment(contents); } -string EnumValueDescriptor::DebugString() const { +std::string EnumValueDescriptor::DebugString() const { DebugStringOptions options; // default values return DebugStringWithOptions(options); } -string EnumValueDescriptor::DebugStringWithOptions( +std::string EnumValueDescriptor::DebugStringWithOptions( const DebugStringOptions& options) const { - string contents; + std::string contents; DebugString(0, &contents, options); return contents; } -void EnumValueDescriptor::DebugString(int depth, string *contents, - const DebugStringOptions& - debug_string_options) const { - string prefix(depth * 2, ' '); +void EnumValueDescriptor::DebugString( + int depth, std::string* contents, + const DebugStringOptions& debug_string_options) const { + std::string prefix(depth * 2, ' '); - SourceLocationCommentPrinter - comment_printer(this, prefix, debug_string_options); + SourceLocationCommentPrinter comment_printer(this, prefix, + debug_string_options); comment_printer.AddPreComment(contents); - strings::SubstituteAndAppend(contents, "$0$1 = $2", - prefix, name(), number()); + strings::SubstituteAndAppend(contents, "$0$1 = $2", prefix, name(), number()); - string formatted_options; + std::string formatted_options; if (FormatBracketedOptions(depth, options(), type()->file()->pool(), &formatted_options)) { strings::SubstituteAndAppend(contents, " [$0]", formatted_options); @@ -2841,23 +2836,23 @@ void EnumValueDescriptor::DebugString(int depth, string *contents, comment_printer.AddPostComment(contents); } -string ServiceDescriptor::DebugString() const { +std::string ServiceDescriptor::DebugString() const { DebugStringOptions options; // default values return DebugStringWithOptions(options); } -string ServiceDescriptor::DebugStringWithOptions( +std::string ServiceDescriptor::DebugStringWithOptions( const DebugStringOptions& options) const { - string contents; + std::string contents; DebugString(&contents, options); return contents; } -void ServiceDescriptor::DebugString(string *contents, - const DebugStringOptions& - debug_string_options) const { - SourceLocationCommentPrinter - comment_printer(this, /* prefix */ "", debug_string_options); +void ServiceDescriptor::DebugString( + std::string* contents, + const DebugStringOptions& debug_string_options) const { + SourceLocationCommentPrinter comment_printer(this, /* prefix */ "", + debug_string_options); comment_printer.AddPreComment(contents); strings::SubstituteAndAppend(contents, "service $0 {\n", name()); @@ -2873,40 +2868,38 @@ void ServiceDescriptor::DebugString(string *contents, comment_printer.AddPostComment(contents); } -string MethodDescriptor::DebugString() const { +std::string MethodDescriptor::DebugString() const { DebugStringOptions options; // default values return DebugStringWithOptions(options); } -string MethodDescriptor::DebugStringWithOptions( +std::string MethodDescriptor::DebugStringWithOptions( const DebugStringOptions& options) const { - string contents; + std::string contents; DebugString(0, &contents, options); return contents; } -void MethodDescriptor::DebugString(int depth, string *contents, - const DebugStringOptions& - debug_string_options) const { - string prefix(depth * 2, ' '); +void MethodDescriptor::DebugString( + int depth, std::string* contents, + const DebugStringOptions& debug_string_options) const { + std::string prefix(depth * 2, ' '); ++depth; - SourceLocationCommentPrinter - comment_printer(this, prefix, debug_string_options); + SourceLocationCommentPrinter comment_printer(this, prefix, + debug_string_options); comment_printer.AddPreComment(contents); - strings::SubstituteAndAppend(contents, "$0rpc $1($4.$2) returns ($5.$3)", - prefix, name(), - input_type()->full_name(), - output_type()->full_name(), - client_streaming() ? "stream " : "", - server_streaming() ? "stream " : ""); + strings::SubstituteAndAppend( + contents, "$0rpc $1($4.$2) returns ($5.$3)", prefix, name(), + input_type()->full_name(), output_type()->full_name(), + client_streaming() ? "stream " : "", server_streaming() ? "stream " : ""); - string formatted_options; + std::string formatted_options; if (FormatLineOptions(depth, options(), service()->file()->pool(), &formatted_options)) { - strings::SubstituteAndAppend(contents, " {\n$0$1}\n", - formatted_options, prefix); + strings::SubstituteAndAppend(contents, " {\n$0$1}\n", formatted_options, + prefix); } else { contents->append(";\n"); } @@ -2919,16 +2912,16 @@ void MethodDescriptor::DebugString(int depth, string *contents, bool FileDescriptor::GetSourceLocation(const std::vector& path, SourceLocation* out_location) const { - GOOGLE_CHECK_NOTNULL(out_location); + GOOGLE_CHECK(out_location != nullptr); if (source_code_info_) { if (const SourceCodeInfo_Location* loc = - tables_->GetSourceLocation(path, source_code_info_)) { + tables_->GetSourceLocation(path, source_code_info_)) { const RepeatedField& span = loc->span(); if (span.size() == 3 || span.size() == 4) { - out_location->start_line = span.Get(0); + out_location->start_line = span.Get(0); out_location->start_column = span.Get(1); - out_location->end_line = span.Get(span.size() == 3 ? 0 : 2); - out_location->end_column = span.Get(span.size() - 1); + out_location->end_line = span.Get(span.size() == 3 ? 0 : 2); + out_location->end_column = span.Get(span.size() - 1); out_location->leading_comments = loc->leading_comments(); out_location->trailing_comments = loc->trailing_comments(); @@ -3071,19 +3064,16 @@ namespace { // pointers in the original options, not the mutable copy). The Message must be // one of the Options messages in descriptor.proto. struct OptionsToInterpret { - OptionsToInterpret(const string& ns, - const string& el, - std::vector& path, - const Message* orig_opt, + OptionsToInterpret(const std::string& ns, const std::string& el, + const std::vector& path, const Message* orig_opt, Message* opt) : name_scope(ns), element_name(el), element_path(path), original_options(orig_opt), - options(opt) { - } - string name_scope; - string element_name; + options(opt) {} + std::string name_scope; + std::string element_name; std::vector element_path; const Message* original_options; Message* options; @@ -3093,8 +3083,7 @@ struct OptionsToInterpret { class DescriptorBuilder { public: - DescriptorBuilder(const DescriptorPool* pool, - DescriptorPool::Tables* tables, + DescriptorBuilder(const DescriptorPool* pool, DescriptorPool::Tables* tables, DescriptorPool::ErrorCollector* error_collector); ~DescriptorBuilder(); @@ -3116,7 +3105,7 @@ class DescriptorBuilder { std::vector options_to_interpret_; bool had_errors_; - string filename_; + std::string filename_; FileDescriptor* file_; FileDescriptorTables* file_tables_; std::set dependencies_; @@ -3133,19 +3122,17 @@ class DescriptorBuilder { // actually found in possible_undeclared_dependency_, which may be a parent // of the symbol actually looked for. const FileDescriptor* possible_undeclared_dependency_; - string possible_undeclared_dependency_name_; + std::string possible_undeclared_dependency_name_; // If LookupSymbol() could resolve a symbol which is not defined, // record the resolved name. This is only used by AddNotDefinedError() // to report a more useful error message. - string undefine_resolved_name_; + std::string undefine_resolved_name_; - void AddError(const string& element_name, - const Message& descriptor, + void AddError(const std::string& element_name, const Message& descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, - const string& error); - void AddError(const string& element_name, - const Message& descriptor, + const std::string& error); + void AddError(const std::string& element_name, const Message& descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, const char* error); void AddRecursiveImportError(const FileDescriptorProto& proto, int from_here); @@ -3155,19 +3142,18 @@ class DescriptorBuilder { // Adds an error indicating that undefined_symbol was not defined. Must // only be called after LookupSymbol() fails. void AddNotDefinedError( - const string& element_name, - const Message& descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - const string& undefined_symbol); + const std::string& element_name, const Message& descriptor, + DescriptorPool::ErrorCollector::ErrorLocation location, + const std::string& undefined_symbol); - void AddWarning(const string& element_name, const Message& descriptor, + void AddWarning(const std::string& element_name, const Message& descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, - const string& error); + const std::string& error); // Silly helper which determines if the given file is in the given package. // I.e., either file->package() == package_name or file->package() is a // nested package within package_name. - bool IsInPackage(const FileDescriptor* file, const string& package_name); + bool IsInPackage(const FileDescriptor* file, const std::string& package_name); // Helper function which finds all public dependencies of the given file, and // stores the them in the dependencies_ set in the builder. @@ -3177,15 +3163,16 @@ class DescriptorBuilder { // - Search the pool's underlay if not found in tables_. // - Insure that the resulting Symbol is from one of the file's declared // dependencies. - Symbol FindSymbol(const string& name, bool build_it = true); + Symbol FindSymbol(const std::string& name, bool build_it = true); // Like FindSymbol() but does not require that the symbol is in one of the // file's declared dependencies. - Symbol FindSymbolNotEnforcingDeps(const string& name, bool build_it = true); + Symbol FindSymbolNotEnforcingDeps(const std::string& name, + bool build_it = true); // This implements the body of FindSymbolNotEnforcingDeps(). Symbol FindSymbolNotEnforcingDepsHelper(const DescriptorPool* pool, - const string& name, + const std::string& name, bool build_it = true); // Like FindSymbol(), but looks up the name relative to some other symbol @@ -3202,10 +3189,8 @@ class DescriptorBuilder { // that LookupSymbol may still return a non-type symbol in LOOKUP_TYPES mode, // if it believes that's all it could refer to. The caller should always // check that it receives the type of symbol it was expecting. - enum ResolveMode { - LOOKUP_ALL, LOOKUP_TYPES - }; - Symbol LookupSymbol(const string& name, const string& relative_to, + enum ResolveMode { LOOKUP_ALL, LOOKUP_TYPES }; + Symbol LookupSymbol(const std::string& name, const std::string& relative_to, DescriptorPool::PlaceholderType placeholder_type = DescriptorPool::PLACEHOLDER_MESSAGE, ResolveMode resolve_mode = LOOKUP_ALL, @@ -3213,29 +3198,28 @@ class DescriptorBuilder { // Like LookupSymbol() but will not return a placeholder even if // AllowUnknownDependencies() has been used. - Symbol LookupSymbolNoPlaceholder(const string& name, - const string& relative_to, + Symbol LookupSymbolNoPlaceholder(const std::string& name, + const std::string& relative_to, ResolveMode resolve_mode = LOOKUP_ALL, bool build_it = true); // Calls tables_->AddSymbol() and records an error if it fails. Returns // true if successful or false if failed, though most callers can ignore // the return value since an error has already been recorded. - bool AddSymbol(const string& full_name, - const void* parent, const string& name, - const Message& proto, Symbol symbol); + bool AddSymbol(const std::string& full_name, const void* parent, + const std::string& name, const Message& proto, Symbol symbol); // Like AddSymbol(), but succeeds if the symbol is already defined as long // as the existing definition is also a package (because it's OK to define // the same package in two different files). Also adds all parents of the // packgae to the symbol table (e.g. AddPackage("foo.bar", ...) will add // "foo.bar" and "foo" to the table). - void AddPackage(const string& name, const Message& proto, + void AddPackage(const std::string& name, const Message& proto, const FileDescriptor* file); // Checks that the symbol name contains only alphanumeric characters and // underscores. Records an error otherwise. - void ValidateSymbolName(const string& name, const string& full_name, + void ValidateSymbolName(const std::string& name, const std::string& full_name, const Message& proto); // Used by BUILD_ARRAY macro (below) to avoid having to have the type @@ -3249,66 +3233,57 @@ class DescriptorBuilder { // descriptor. Remembers its uninterpreted options, to be interpreted // later. DescriptorT must be one of the Descriptor messages from // descriptor.proto. - template void AllocateOptions( - const typename DescriptorT::OptionsType& orig_options, - DescriptorT* descriptor, int options_field_tag); + template + void AllocateOptions(const typename DescriptorT::OptionsType& orig_options, + DescriptorT* descriptor, int options_field_tag); // Specialization for FileOptions. void AllocateOptions(const FileOptions& orig_options, FileDescriptor* descriptor); // Implementation for AllocateOptions(). Don't call this directly. - template void AllocateOptionsImpl( - const string& name_scope, - const string& element_name, + template + void AllocateOptionsImpl( + const std::string& name_scope, const std::string& element_name, const typename DescriptorT::OptionsType& orig_options, - DescriptorT* descriptor, - std::vector& options_path); + DescriptorT* descriptor, const std::vector& options_path); // These methods all have the same signature for the sake of the BUILD_ARRAY // macro, below. - void BuildMessage(const DescriptorProto& proto, - const Descriptor* parent, + void BuildMessage(const DescriptorProto& proto, const Descriptor* parent, Descriptor* result); void BuildFieldOrExtension(const FieldDescriptorProto& proto, - const Descriptor* parent, - FieldDescriptor* result, + const Descriptor* parent, FieldDescriptor* result, bool is_extension); - void BuildField(const FieldDescriptorProto& proto, - const Descriptor* parent, + void BuildField(const FieldDescriptorProto& proto, const Descriptor* parent, FieldDescriptor* result) { BuildFieldOrExtension(proto, parent, result, false); } void BuildExtension(const FieldDescriptorProto& proto, - const Descriptor* parent, - FieldDescriptor* result) { + const Descriptor* parent, FieldDescriptor* result) { BuildFieldOrExtension(proto, parent, result, true); } void BuildExtensionRange(const DescriptorProto::ExtensionRange& proto, const Descriptor* parent, Descriptor::ExtensionRange* result); void BuildReservedRange(const DescriptorProto::ReservedRange& proto, - const Descriptor* parent, - Descriptor::ReservedRange* result); + const Descriptor* parent, + Descriptor::ReservedRange* result); void BuildReservedRange(const EnumDescriptorProto::EnumReservedRange& proto, const EnumDescriptor* parent, EnumDescriptor::ReservedRange* result); - void BuildOneof(const OneofDescriptorProto& proto, - Descriptor* parent, + void BuildOneof(const OneofDescriptorProto& proto, Descriptor* parent, OneofDescriptor* result); void CheckEnumValueUniqueness(const EnumDescriptorProto& proto, const EnumDescriptor* result); - void BuildEnum(const EnumDescriptorProto& proto, - const Descriptor* parent, + void BuildEnum(const EnumDescriptorProto& proto, const Descriptor* parent, EnumDescriptor* result); void BuildEnumValue(const EnumValueDescriptorProto& proto, const EnumDescriptor* parent, EnumValueDescriptor* result); - void BuildService(const ServiceDescriptorProto& proto, - const void* dummy, + void BuildService(const ServiceDescriptorProto& proto, const void* dummy, ServiceDescriptor* result); void BuildMethod(const MethodDescriptorProto& proto, - const ServiceDescriptor* parent, - MethodDescriptor* result); + const ServiceDescriptor* parent, MethodDescriptor* result); void LogUnusedDependency(const FileDescriptorProto& proto, const FileDescriptor* result); @@ -3364,8 +3339,9 @@ class DescriptorBuilder { // location path to the uninterpreted option, and options_path is the // source location path to the options message. The location paths are // recorded and then used in UpdateSourceCodeInfo. - bool InterpretSingleOption(Message* options, std::vector& src_path, - std::vector& options_path); + bool InterpretSingleOption(Message* options, + const std::vector& src_path, + const std::vector& options_path); // Adds the uninterpreted_option to the given options message verbatim. // Used when AllowUnknownDependencies() is in effect and we can't find @@ -3381,7 +3357,8 @@ class DescriptorBuilder { intermediate_fields_iter, std::vector::const_iterator intermediate_fields_end, - const FieldDescriptor* innermost_field, const string& debug_msg_name, + const FieldDescriptor* innermost_field, + const std::string& debug_msg_name, const UnknownFieldSet& unknown_fields); // Validates the value for the option field of the currently interpreted @@ -3408,7 +3385,7 @@ class DescriptorBuilder { // A helper function that adds an error at the specified location of the // option we're currently interpreting, and returns false. bool AddOptionError(DescriptorPool::ErrorCollector::ErrorLocation location, - const string& msg) { + const std::string& msg) { builder_->AddError(options_to_interpret_->element_name, *uninterpreted_option_, location, msg); return false; @@ -3416,13 +3393,13 @@ class DescriptorBuilder { // A helper function that adds an error at the location of the option name // and returns false. - bool AddNameError(const string& msg) { + bool AddNameError(const std::string& msg) { return AddOptionError(DescriptorPool::ErrorCollector::OPTION_NAME, msg); } // A helper function that adds an error at the location of the option name // and returns false. - bool AddValueError(const string& msg) { + bool AddValueError(const std::string& msg) { return AddOptionError(DescriptorPool::ErrorCollector::OPTION_VALUE, msg); } @@ -3502,10 +3479,8 @@ class DescriptorBuilder { const ServiceDescriptorProto& proto); void ValidateMethodOptions(MethodDescriptor* method, const MethodDescriptorProto& proto); - void ValidateProto3(FileDescriptor* file, - const FileDescriptorProto& proto); - void ValidateProto3Message(Descriptor* message, - const DescriptorProto& proto); + void ValidateProto3(FileDescriptor* file, const FileDescriptorProto& proto); + void ValidateProto3Message(Descriptor* message, const DescriptorProto& proto); void ValidateProto3Field(FieldDescriptor* field, const FieldDescriptorProto& proto); void ValidateProto3Enum(EnumDescriptor* enm, @@ -3528,27 +3503,26 @@ class DescriptorBuilder { const FileDescriptor* DescriptorPool::BuildFile( const FileDescriptorProto& proto) { GOOGLE_CHECK(fallback_database_ == NULL) - << "Cannot call BuildFile on a DescriptorPool that uses a " - "DescriptorDatabase. You must instead find a way to get your file " - "into the underlying database."; - GOOGLE_CHECK(mutex_ == NULL); // Implied by the above GOOGLE_CHECK. + << "Cannot call BuildFile on a DescriptorPool that uses a " + "DescriptorDatabase. You must instead find a way to get your file " + "into the underlying database."; + GOOGLE_CHECK(mutex_ == NULL); // Implied by the above GOOGLE_CHECK. tables_->known_bad_symbols_.clear(); tables_->known_bad_files_.clear(); return DescriptorBuilder(this, tables_.get(), NULL).BuildFile(proto); } const FileDescriptor* DescriptorPool::BuildFileCollectingErrors( - const FileDescriptorProto& proto, - ErrorCollector* error_collector) { + const FileDescriptorProto& proto, ErrorCollector* error_collector) { GOOGLE_CHECK(fallback_database_ == NULL) - << "Cannot call BuildFile on a DescriptorPool that uses a " - "DescriptorDatabase. You must instead find a way to get your file " - "into the underlying database."; - GOOGLE_CHECK(mutex_ == NULL); // Implied by the above GOOGLE_CHECK. + << "Cannot call BuildFile on a DescriptorPool that uses a " + "DescriptorDatabase. You must instead find a way to get your file " + "into the underlying database."; + GOOGLE_CHECK(mutex_ == NULL); // Implied by the above GOOGLE_CHECK. tables_->known_bad_symbols_.clear(); tables_->known_bad_files_.clear(); - return DescriptorBuilder(this, tables_.get(), - error_collector).BuildFile(proto); + return DescriptorBuilder(this, tables_.get(), error_collector) + .BuildFile(proto); } const FileDescriptor* DescriptorPool::BuildFileFromDatabase( @@ -3558,8 +3532,8 @@ const FileDescriptor* DescriptorPool::BuildFileFromDatabase( return NULL; } const FileDescriptor* result = - DescriptorBuilder(this, tables_.get(), - default_error_collector_).BuildFile(proto); + DescriptorBuilder(this, tables_.get(), default_error_collector_) + .BuildFile(proto); if (result == NULL) { tables_->known_bad_files_.insert(proto.name()); } @@ -3567,23 +3541,21 @@ const FileDescriptor* DescriptorPool::BuildFileFromDatabase( } DescriptorBuilder::DescriptorBuilder( - const DescriptorPool* pool, - DescriptorPool::Tables* tables, + const DescriptorPool* pool, DescriptorPool::Tables* tables, DescriptorPool::ErrorCollector* error_collector) - : pool_(pool), - tables_(tables), - error_collector_(error_collector), - had_errors_(false), - possible_undeclared_dependency_(NULL), - undefine_resolved_name_("") {} + : pool_(pool), + tables_(tables), + error_collector_(error_collector), + had_errors_(false), + possible_undeclared_dependency_(NULL), + undefine_resolved_name_("") {} DescriptorBuilder::~DescriptorBuilder() {} void DescriptorBuilder::AddError( - const string& element_name, - const Message& descriptor, + const std::string& element_name, const Message& descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, - const string& error) { + const std::string& error) { if (error_collector_ == NULL) { if (!had_errors_) { GOOGLE_LOG(ERROR) << "Invalid proto descriptor for file \"" << filename_ @@ -3591,25 +3563,22 @@ void DescriptorBuilder::AddError( } GOOGLE_LOG(ERROR) << " " << element_name << ": " << error; } else { - error_collector_->AddError(filename_, element_name, - &descriptor, location, error); + error_collector_->AddError(filename_, element_name, &descriptor, location, + error); } had_errors_ = true; } void DescriptorBuilder::AddError( - const string& element_name, - const Message& descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - const char* error) { - AddError(element_name, descriptor, location, string(error)); + const std::string& element_name, const Message& descriptor, + DescriptorPool::ErrorCollector::ErrorLocation location, const char* error) { + AddError(element_name, descriptor, location, std::string(error)); } void DescriptorBuilder::AddNotDefinedError( - const string& element_name, - const Message& descriptor, + const std::string& element_name, const Message& descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, - const string& undefined_symbol) { + const std::string& undefined_symbol) { if (possible_undeclared_dependency_ == NULL && undefine_resolved_name_.empty()) { AddError(element_name, descriptor, location, @@ -3618,27 +3587,30 @@ void DescriptorBuilder::AddNotDefinedError( if (possible_undeclared_dependency_ != NULL) { AddError(element_name, descriptor, location, "\"" + possible_undeclared_dependency_name_ + - "\" seems to be defined in \"" + - possible_undeclared_dependency_->name() + "\", which is not " - "imported by \"" + filename_ + "\". To use it here, please " - "add the necessary import."); + "\" seems to be defined in \"" + + possible_undeclared_dependency_->name() + + "\", which is not " + "imported by \"" + + filename_ + + "\". To use it here, please " + "add the necessary import."); } if (!undefine_resolved_name_.empty()) { AddError(element_name, descriptor, location, "\"" + undefined_symbol + "\" is resolved to \"" + - undefine_resolved_name_ + "\", which is not defined. " - "The innermost scope is searched first in name resolution. " - "Consider using a leading '.'(i.e., \"." - + undefined_symbol + - "\") to start from the outermost scope."); + undefine_resolved_name_ + + "\", which is not defined. " + "The innermost scope is searched first in name resolution. " + "Consider using a leading '.'(i.e., \"." + + undefined_symbol + "\") to start from the outermost scope."); } } } void DescriptorBuilder::AddWarning( - const string& element_name, const Message& descriptor, + const std::string& element_name, const Message& descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, - const string& error) { + const std::string& error) { if (error_collector_ == NULL) { GOOGLE_LOG(WARNING) << filename_ << " " << element_name << ": " << error; } else { @@ -3648,7 +3620,7 @@ void DescriptorBuilder::AddWarning( } bool DescriptorBuilder::IsInPackage(const FileDescriptor* file, - const string& package_name) { + const std::string& package_name) { return HasPrefixString(file->package(), package_name) && (file->package().size() == package_name.size() || file->package()[package_name.size()] == '.'); @@ -3662,7 +3634,7 @@ void DescriptorBuilder::RecordPublicDependencies(const FileDescriptor* file) { } Symbol DescriptorBuilder::FindSymbolNotEnforcingDepsHelper( - const DescriptorPool* pool, const string& name, bool build_it) { + const DescriptorPool* pool, const std::string& name, bool build_it) { // If we are looking at an underlay, we must lock its mutex_, since we are // accessing the underlay's tables_ directly. MutexLockMaybe lock((pool == pool_) ? NULL : pool->mutex_); @@ -3689,12 +3661,12 @@ Symbol DescriptorBuilder::FindSymbolNotEnforcingDepsHelper( return result; } -Symbol DescriptorBuilder::FindSymbolNotEnforcingDeps(const string& name, +Symbol DescriptorBuilder::FindSymbolNotEnforcingDeps(const std::string& name, bool build_it) { return FindSymbolNotEnforcingDepsHelper(pool_, name, build_it); } -Symbol DescriptorBuilder::FindSymbol(const string& name, bool build_it) { +Symbol DescriptorBuilder::FindSymbol(const std::string& name, bool build_it) { Symbol result = FindSymbolNotEnforcingDeps(name, build_it); if (result.IsNull()) return result; @@ -3734,10 +3706,9 @@ Symbol DescriptorBuilder::FindSymbol(const string& name, bool build_it) { return kNullSymbol; } -Symbol DescriptorBuilder::LookupSymbolNoPlaceholder(const string& name, - const string& relative_to, - ResolveMode resolve_mode, - bool build_it) { +Symbol DescriptorBuilder::LookupSymbolNoPlaceholder( + const std::string& name, const std::string& relative_to, + ResolveMode resolve_mode, bool build_it) { possible_undeclared_dependency_ = NULL; undefine_resolved_name_.clear(); @@ -3757,27 +3728,27 @@ Symbol DescriptorBuilder::LookupSymbolNoPlaceholder(const string& name, // } // So, we look for just "Foo" first, then look for "Bar.baz" within it if // found. - string::size_type name_dot_pos = name.find_first_of('.'); - string first_part_of_name; - if (name_dot_pos == string::npos) { + std::string::size_type name_dot_pos = name.find_first_of('.'); + std::string first_part_of_name; + if (name_dot_pos == std::string::npos) { first_part_of_name = name; } else { first_part_of_name = name.substr(0, name_dot_pos); } - string scope_to_try(relative_to); + std::string scope_to_try(relative_to); while (true) { // Chop off the last component of the scope. - string::size_type dot_pos = scope_to_try.find_last_of('.'); - if (dot_pos == string::npos) { + std::string::size_type dot_pos = scope_to_try.find_last_of('.'); + if (dot_pos == std::string::npos) { return FindSymbol(name, build_it); } else { scope_to_try.erase(dot_pos); } // Append ".first_part_of_name" and try to find. - string::size_type old_size = scope_to_try.size(); + std::string::size_type old_size = scope_to_try.size(); scope_to_try.append(1, '.'); scope_to_try.append(first_part_of_name); Symbol result = FindSymbol(scope_to_try, build_it); @@ -3811,7 +3782,7 @@ Symbol DescriptorBuilder::LookupSymbolNoPlaceholder(const string& name, } Symbol DescriptorBuilder::LookupSymbol( - const string& name, const string& relative_to, + const std::string& name, const std::string& relative_to, DescriptorPool::PlaceholderType placeholder_type, ResolveMode resolve_mode, bool build_it) { Symbol result = @@ -3824,7 +3795,7 @@ Symbol DescriptorBuilder::LookupSymbol( return result; } -static bool ValidateQualifiedName(const string& name) { +static bool ValidateQualifiedName(const std::string& name) { bool last_was_period = false; for (int i = 0; i < name.size(); i++) { @@ -3844,21 +3815,21 @@ static bool ValidateQualifiedName(const string& name) { return !name.empty() && !last_was_period; } -Symbol DescriptorPool::NewPlaceholder(const string& name, +Symbol DescriptorPool::NewPlaceholder(const std::string& name, PlaceholderType placeholder_type) const { MutexLockMaybe lock(mutex_); return NewPlaceholderWithMutexHeld(name, placeholder_type); } Symbol DescriptorPool::NewPlaceholderWithMutexHeld( - const string& name, PlaceholderType placeholder_type) const { + const std::string& name, PlaceholderType placeholder_type) const { if (mutex_) { mutex_->AssertHeld(); } // Compute names. - const string* placeholder_full_name; - const string* placeholder_name; - const string* placeholder_package; + const std::string* placeholder_full_name; + const std::string* placeholder_name; + const std::string* placeholder_package; if (!ValidateQualifiedName(name)) return kNullSymbol; if (name[0] == '.') { @@ -3868,12 +3839,12 @@ Symbol DescriptorPool::NewPlaceholderWithMutexHeld( placeholder_full_name = tables_->AllocateString(name); } - string::size_type dotpos = placeholder_full_name->find_last_of('.'); - if (dotpos != string::npos) { - placeholder_package = tables_->AllocateString( - placeholder_full_name->substr(0, dotpos)); - placeholder_name = tables_->AllocateString( - placeholder_full_name->substr(dotpos + 1)); + std::string::size_type dotpos = placeholder_full_name->find_last_of('.'); + if (dotpos != std::string::npos) { + placeholder_package = + tables_->AllocateString(placeholder_full_name->substr(0, dotpos)); + placeholder_name = + tables_->AllocateString(placeholder_full_name->substr(dotpos + 1)); } else { placeholder_package = &internal::GetEmptyString(); placeholder_name = placeholder_full_name; @@ -3886,11 +3857,10 @@ Symbol DescriptorPool::NewPlaceholderWithMutexHeld( if (placeholder_type == PLACEHOLDER_ENUM) { placeholder_file->enum_type_count_ = 1; - placeholder_file->enum_types_ = - tables_->AllocateArray(1); + placeholder_file->enum_types_ = tables_->AllocateArray(1); EnumDescriptor* placeholder_enum = &placeholder_file->enum_types_[0]; - memset(placeholder_enum, 0, sizeof(*placeholder_enum)); + memset(static_cast(placeholder_enum), 0, sizeof(*placeholder_enum)); placeholder_enum->full_name_ = placeholder_full_name; placeholder_enum->name_ = placeholder_name; @@ -3904,13 +3874,16 @@ Symbol DescriptorPool::NewPlaceholderWithMutexHeld( placeholder_enum->values_ = tables_->AllocateArray(1); EnumValueDescriptor* placeholder_value = &placeholder_enum->values_[0]; - memset(placeholder_value, 0, sizeof(*placeholder_value)); + memset(static_cast(placeholder_value), 0, + sizeof(*placeholder_value)); placeholder_value->name_ = tables_->AllocateString("PLACEHOLDER_VALUE"); // Note that enum value names are siblings of their type, not children. placeholder_value->full_name_ = - placeholder_package->empty() ? placeholder_value->name_ : - tables_->AllocateString(*placeholder_package + ".PLACEHOLDER_VALUE"); + placeholder_package->empty() + ? placeholder_value->name_ + : tables_->AllocateString(*placeholder_package + + ".PLACEHOLDER_VALUE"); placeholder_value->number_ = 0; placeholder_value->type_ = placeholder_enum; @@ -3919,11 +3892,11 @@ Symbol DescriptorPool::NewPlaceholderWithMutexHeld( return Symbol(placeholder_enum); } else { placeholder_file->message_type_count_ = 1; - placeholder_file->message_types_ = - tables_->AllocateArray(1); + placeholder_file->message_types_ = tables_->AllocateArray(1); Descriptor* placeholder_message = &placeholder_file->message_types_[0]; - memset(placeholder_message, 0, sizeof(*placeholder_message)); + memset(static_cast(placeholder_message), 0, + sizeof(*placeholder_message)); placeholder_message->full_name_ = placeholder_full_name; placeholder_message->name_ = placeholder_name; @@ -3935,29 +3908,30 @@ Symbol DescriptorPool::NewPlaceholderWithMutexHeld( if (placeholder_type == PLACEHOLDER_EXTENDABLE_MESSAGE) { placeholder_message->extension_range_count_ = 1; placeholder_message->extension_ranges_ = - tables_->AllocateArray(1); + tables_->AllocateArray(1); placeholder_message->extension_ranges_->start = 1; // kMaxNumber + 1 because ExtensionRange::end is exclusive. placeholder_message->extension_ranges_->end = - FieldDescriptor::kMaxNumber + 1; + FieldDescriptor::kMaxNumber + 1; } return Symbol(placeholder_message); } } -FileDescriptor* DescriptorPool::NewPlaceholderFile(const string& name) const { +FileDescriptor* DescriptorPool::NewPlaceholderFile( + const std::string& name) const { MutexLockMaybe lock(mutex_); return NewPlaceholderFileWithMutexHeld(name); } FileDescriptor* DescriptorPool::NewPlaceholderFileWithMutexHeld( - const string& name) const { + const std::string& name) const { if (mutex_) { mutex_->AssertHeld(); } FileDescriptor* placeholder = tables_->Allocate(); - memset(placeholder, 0, sizeof(*placeholder)); + memset(static_cast(placeholder), 0, sizeof(*placeholder)); placeholder->name_ = tables_->AllocateString(name); placeholder->package_ = &internal::GetEmptyString(); @@ -3973,9 +3947,9 @@ FileDescriptor* DescriptorPool::NewPlaceholderFileWithMutexHeld( return placeholder; } -bool DescriptorBuilder::AddSymbol( - const string& full_name, const void* parent, const string& name, - const Message& proto, Symbol symbol) { +bool DescriptorBuilder::AddSymbol(const std::string& full_name, + const void* parent, const std::string& name, + const Message& proto, Symbol symbol) { // If the caller passed NULL for the parent, the symbol is at file scope. // Use its file as the parent instead. if (parent == NULL) parent = file_; @@ -3985,7 +3959,8 @@ bool DescriptorBuilder::AddSymbol( // This is only possible if there was already an error adding something of // the same name. if (!had_errors_) { - GOOGLE_LOG(DFATAL) << "\"" << full_name << "\" not previously defined in " + GOOGLE_LOG(DFATAL) << "\"" << full_name + << "\" not previously defined in " "symbols_by_name_, but was defined in " "symbols_by_parent_; this shouldn't be possible."; } @@ -3995,37 +3970,39 @@ bool DescriptorBuilder::AddSymbol( } else { const FileDescriptor* other_file = tables_->FindSymbol(full_name).GetFile(); if (other_file == file_) { - string::size_type dot_pos = full_name.find_last_of('.'); - if (dot_pos == string::npos) { + std::string::size_type dot_pos = full_name.find_last_of('.'); + if (dot_pos == std::string::npos) { AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, "\"" + full_name + "\" is already defined."); } else { AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, "\"" + full_name.substr(dot_pos + 1) + - "\" is already defined in \"" + - full_name.substr(0, dot_pos) + "\"."); + "\" is already defined in \"" + + full_name.substr(0, dot_pos) + "\"."); } } else { // Symbol seems to have been defined in a different file. AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, "\"" + full_name + "\" is already defined in file \"" + - other_file->name() + "\"."); + other_file->name() + "\"."); } return false; } } -void DescriptorBuilder::AddPackage( - const string& name, const Message& proto, const FileDescriptor* file) { +void DescriptorBuilder::AddPackage(const std::string& name, + const Message& proto, + const FileDescriptor* file) { if (tables_->AddSymbol(name, Symbol(file))) { // Success. Also add parent package, if any. - string::size_type dot_pos = name.find_last_of('.'); - if (dot_pos == string::npos) { + std::string::size_type dot_pos = name.find_last_of('.'); + if (dot_pos == std::string::npos) { // No parents. ValidateSymbolName(name, name, proto); } else { // Has parent. - string* parent_name = tables_->AllocateString(name.substr(0, dot_pos)); + std::string* parent_name = + tables_->AllocateString(name.substr(0, dot_pos)); AddPackage(*parent_name, proto, file); ValidateSymbolName(name.substr(dot_pos + 1), name, proto); } @@ -4035,15 +4012,17 @@ void DescriptorBuilder::AddPackage( if (existing_symbol.type != Symbol::PACKAGE) { // Symbol seems to have been defined in a different file. AddError(name, proto, DescriptorPool::ErrorCollector::NAME, - "\"" + name + "\" is already defined (as something other than " - "a package) in file \"" + existing_symbol.GetFile()->name() + - "\"."); + "\"" + name + + "\" is already defined (as something other than " + "a package) in file \"" + + existing_symbol.GetFile()->name() + "\"."); } } } -void DescriptorBuilder::ValidateSymbolName( - const string& name, const string& full_name, const Message& proto) { +void DescriptorBuilder::ValidateSymbolName(const std::string& name, + const std::string& full_name, + const Message& proto) { if (name.empty()) { AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, "Missing name."); @@ -4052,8 +4031,7 @@ void DescriptorBuilder::ValidateSymbolName( // I don't trust isalnum() due to locales. :( if ((name[i] < 'a' || 'z' < name[i]) && (name[i] < 'A' || 'Z' < name[i]) && - (name[i] < '0' || '9' < name[i]) && - (name[i] != '_')) { + (name[i] < '0' || '9' < name[i]) && (name[i] != '_')) { AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, "\"" + name + "\" is not a valid identifier."); } @@ -4065,7 +4043,8 @@ void DescriptorBuilder::ValidateSymbolName( // This generic implementation is good for all descriptors except // FileDescriptor. -template void DescriptorBuilder::AllocateOptions( +template +void DescriptorBuilder::AllocateOptions( const typename DescriptorT::OptionsType& orig_options, DescriptorT* descriptor, int options_field_tag) { std::vector options_path; @@ -4085,18 +4064,25 @@ void DescriptorBuilder::AllocateOptions(const FileOptions& orig_options, orig_options, descriptor, options_path); } -template void DescriptorBuilder::AllocateOptionsImpl( - const string& name_scope, - const string& element_name, +template +void DescriptorBuilder::AllocateOptionsImpl( + const std::string& name_scope, const std::string& element_name, const typename DescriptorT::OptionsType& orig_options, - DescriptorT* descriptor, - std::vector& options_path) { + DescriptorT* descriptor, const std::vector& options_path) { // We need to use a dummy pointer to work around a bug in older versions of // GCC. Otherwise, the following two lines could be replaced with: // typename DescriptorT::OptionsType* options = // tables_->AllocateMessage(); typename DescriptorT::OptionsType* const dummy = NULL; typename DescriptorT::OptionsType* options = tables_->AllocateMessage(dummy); + + if (!orig_options.IsInitialized()) { + AddError(name_scope + "." + element_name, orig_options, + DescriptorPool::ErrorCollector::OPTION_NAME, + "Uninterpreted option is missing name or value."); + return; + } + // Avoid using MergeFrom()/CopyFrom() in this class to make it -fno-rtti // friendly. Without RTTI, MergeFrom() and CopyFrom() will fallback to the // reflection based method, which requires the Descriptor. However, we are in @@ -4112,52 +4098,56 @@ template void DescriptorBuilder::AllocateOptionsImpl( // OptionsType::GetDescriptor() to be called which may then deadlock since // we're still trying to build it. if (options->uninterpreted_option_size() > 0) { - options_to_interpret_.push_back( - OptionsToInterpret(name_scope, element_name, options_path, - &orig_options, options)); + options_to_interpret_.push_back(OptionsToInterpret( + name_scope, element_name, options_path, &orig_options, options)); } } - // A common pattern: We want to convert a repeated field in the descriptor // to an array of values, calling some method to build each value. -#define BUILD_ARRAY(INPUT, OUTPUT, NAME, METHOD, PARENT) \ - OUTPUT->NAME##_count_ = INPUT.NAME##_size(); \ - AllocateArray(INPUT.NAME##_size(), &OUTPUT->NAME##s_); \ - for (int i = 0; i < INPUT.NAME##_size(); i++) { \ - METHOD(INPUT.NAME(i), PARENT, OUTPUT->NAME##s_ + i); \ +#define BUILD_ARRAY(INPUT, OUTPUT, NAME, METHOD, PARENT) \ + OUTPUT->NAME##_count_ = INPUT.NAME##_size(); \ + AllocateArray(INPUT.NAME##_size(), &OUTPUT->NAME##s_); \ + for (int i = 0; i < INPUT.NAME##_size(); i++) { \ + METHOD(INPUT.NAME(i), PARENT, OUTPUT->NAME##s_ + i); \ } void DescriptorBuilder::AddRecursiveImportError( const FileDescriptorProto& proto, int from_here) { - string error_message("File recursively imports itself: "); + std::string error_message("File recursively imports itself: "); for (int i = from_here; i < tables_->pending_files_.size(); i++) { error_message.append(tables_->pending_files_[i]); error_message.append(" -> "); } error_message.append(proto.name()); - AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER, - error_message); + if (from_here < tables_->pending_files_.size() - 1) { + AddError(tables_->pending_files_[from_here + 1], proto, + DescriptorPool::ErrorCollector::IMPORT, error_message); + } else { + AddError(proto.name(), proto, DescriptorPool::ErrorCollector::IMPORT, + error_message); + } } void DescriptorBuilder::AddTwiceListedError(const FileDescriptorProto& proto, int index) { - AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER, + AddError(proto.dependency(index), proto, + DescriptorPool::ErrorCollector::IMPORT, "Import \"" + proto.dependency(index) + "\" was listed twice."); } void DescriptorBuilder::AddImportError(const FileDescriptorProto& proto, int index) { - string message; + std::string message; if (pool_->fallback_database_ == NULL) { - message = "Import \"" + proto.dependency(index) + - "\" has not been loaded."; + message = "Import \"" + proto.dependency(index) + "\" has not been loaded."; } else { message = "Import \"" + proto.dependency(index) + "\" was not found or had errors."; } - AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER, message); + AddError(proto.dependency(index), proto, + DescriptorPool::ErrorCollector::IMPORT, message); } static bool ExistingFileMatchesProto(const FileDescriptor* existing_file, @@ -4252,7 +4242,7 @@ FileDescriptor* DescriptorBuilder::BuildFileImpl( result->is_placeholder_ = false; result->finished_building_ = false; - SourceCodeInfo *info = NULL; + SourceCodeInfo* info = nullptr; if (proto.has_source_code_info()) { info = tables_->AllocateMessage(); info->CopyFrom(proto.source_code_info()); @@ -4306,14 +4296,14 @@ FileDescriptor* DescriptorBuilder::BuildFileImpl( } // Make sure all dependencies are loaded. - std::set seen_dependencies; + std::set seen_dependencies; result->dependency_count_ = proto.dependency_size(); result->dependencies_ = tables_->AllocateArray(proto.dependency_size()); if (pool_->lazily_build_dependencies_) { result->dependencies_once_ = tables_->AllocateOnceDynamic(); result->dependencies_names_ = - tables_->AllocateArray(proto.dependency_size()); + tables_->AllocateArray(proto.dependency_size()); if (proto.dependency_size() > 0) { memset(result->dependencies_names_, 0, sizeof(*result->dependencies_names_) * proto.dependency_size()); @@ -4374,8 +4364,8 @@ FileDescriptor* DescriptorBuilder::BuildFileImpl( // Check public dependencies. int public_dependency_count = 0; - result->public_dependencies_ = tables_->AllocateArray( - proto.public_dependency_size()); + result->public_dependencies_ = + tables_->AllocateArray(proto.public_dependency_size()); for (int i = 0; i < proto.public_dependency_size(); i++) { // Only put valid public dependency indexes. int index = proto.public_dependency(i); @@ -4389,8 +4379,7 @@ FileDescriptor* DescriptorBuilder::BuildFileImpl( unused_dependency_.erase(result->dependency(index)); } } else { - AddError(proto.name(), proto, - DescriptorPool::ErrorCollector::OTHER, + AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER, "Invalid public dependency index."); } } @@ -4409,25 +4398,24 @@ FileDescriptor* DescriptorBuilder::BuildFileImpl( // Check weak dependencies. int weak_dependency_count = 0; - result->weak_dependencies_ = tables_->AllocateArray( - proto.weak_dependency_size()); + result->weak_dependencies_ = + tables_->AllocateArray(proto.weak_dependency_size()); for (int i = 0; i < proto.weak_dependency_size(); i++) { int index = proto.weak_dependency(i); if (index >= 0 && index < proto.dependency_size()) { result->weak_dependencies_[weak_dependency_count++] = index; } else { - AddError(proto.name(), proto, - DescriptorPool::ErrorCollector::OTHER, + AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER, "Invalid weak dependency index."); } } result->weak_dependency_count_ = weak_dependency_count; // Convert children. - BUILD_ARRAY(proto, result, message_type, BuildMessage , NULL); - BUILD_ARRAY(proto, result, enum_type , BuildEnum , NULL); - BUILD_ARRAY(proto, result, service , BuildService , NULL); - BUILD_ARRAY(proto, result, extension , BuildExtension, NULL); + BUILD_ARRAY(proto, result, message_type, BuildMessage, NULL); + BUILD_ARRAY(proto, result, enum_type, BuildEnum, NULL); + BUILD_ARRAY(proto, result, service, BuildService, NULL); + BUILD_ARRAY(proto, result, extension, BuildExtension, NULL); // Copy options. if (!proto.has_options()) { @@ -4452,8 +4440,7 @@ FileDescriptor* DescriptorBuilder::BuildFileImpl( option_interpreter.InterpretOptions(&(*iter)); } options_to_interpret_.clear(); - - if (info != NULL) { + if (info != nullptr) { option_interpreter.UpdateSourceCodeInfo(info); } } @@ -4486,38 +4473,39 @@ FileDescriptor* DescriptorBuilder::BuildFileImpl( } } + void DescriptorBuilder::BuildMessage(const DescriptorProto& proto, const Descriptor* parent, Descriptor* result) { - const string& scope = (parent == NULL) ? - file_->package() : parent->full_name(); - string* full_name = tables_->AllocateString(scope); + const std::string& scope = + (parent == NULL) ? file_->package() : parent->full_name(); + std::string* full_name = tables_->AllocateString(scope); if (!full_name->empty()) full_name->append(1, '.'); full_name->append(proto.name()); ValidateSymbolName(proto.name(), *full_name, proto); - result->name_ = tables_->AllocateString(proto.name()); - result->full_name_ = full_name; - result->file_ = file_; + result->name_ = tables_->AllocateString(proto.name()); + result->full_name_ = full_name; + result->file_ = file_; result->containing_type_ = parent; - result->is_placeholder_ = false; + result->is_placeholder_ = false; result->is_unqualified_placeholder_ = false; // Build oneofs first so that fields and extension ranges can refer to them. - BUILD_ARRAY(proto, result, oneof_decl , BuildOneof , result); - BUILD_ARRAY(proto, result, field , BuildField , result); - BUILD_ARRAY(proto, result, nested_type , BuildMessage , result); - BUILD_ARRAY(proto, result, enum_type , BuildEnum , result); + BUILD_ARRAY(proto, result, oneof_decl, BuildOneof, result); + BUILD_ARRAY(proto, result, field, BuildField, result); + BUILD_ARRAY(proto, result, nested_type, BuildMessage, result); + BUILD_ARRAY(proto, result, enum_type, BuildEnum, result); BUILD_ARRAY(proto, result, extension_range, BuildExtensionRange, result); - BUILD_ARRAY(proto, result, extension , BuildExtension , result); - BUILD_ARRAY(proto, result, reserved_range , BuildReservedRange , result); + BUILD_ARRAY(proto, result, extension, BuildExtension, result); + BUILD_ARRAY(proto, result, reserved_range, BuildReservedRange, result); // Copy reserved names. int reserved_name_count = proto.reserved_name_size(); result->reserved_name_count_ = reserved_name_count; result->reserved_names_ = - tables_->AllocateArray(reserved_name_count); + tables_->AllocateArray(reserved_name_count); for (int i = 0; i < reserved_name_count; ++i) { result->reserved_names_[i] = tables_->AllocateString(proto.reserved_name(i)); @@ -4528,11 +4516,11 @@ void DescriptorBuilder::BuildMessage(const DescriptorProto& proto, result->options_ = NULL; // Will set to default_instance later. } else { AllocateOptions(proto.options(), result, - DescriptorProto::kOptionsFieldNumber); + DescriptorProto::kOptionsFieldNumber); } - AddSymbol(result->full_name(), parent, result->name(), - proto, Symbol(result)); + AddSymbol(result->full_name(), parent, result->name(), proto, Symbol(result)); + for (int i = 0; i < proto.reserved_range_size(); i++) { const DescriptorProto_ReservedRange& range1 = proto.reserved_range(i); @@ -4549,16 +4537,15 @@ void DescriptorBuilder::BuildMessage(const DescriptorProto& proto, } } - HASH_SET reserved_name_set; + HASH_SET reserved_name_set; for (int i = 0; i < proto.reserved_name_size(); i++) { - const string& name = proto.reserved_name(i); + const std::string& name = proto.reserved_name(i); if (reserved_name_set.find(name) == reserved_name_set.end()) { reserved_name_set.insert(name); } else { AddError(name, proto, DescriptorPool::ErrorCollector::NAME, strings::Substitute( - "Field name \"$0\" is reserved multiple times.", - name)); + "Field name \"$0\" is reserved multiple times.", name)); } } @@ -4567,12 +4554,12 @@ void DescriptorBuilder::BuildMessage(const DescriptorProto& proto, for (int j = 0; j < result->extension_range_count(); j++) { const Descriptor::ExtensionRange* range = result->extension_range(j); if (range->start <= field->number() && field->number() < range->end) { - AddError(field->full_name(), proto.extension_range(j), - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute( - "Extension range $0 to $1 includes field \"$2\" ($3).", - range->start, range->end - 1, - field->name(), field->number())); + AddError( + field->full_name(), proto.extension_range(j), + DescriptorPool::ErrorCollector::NUMBER, + strings::Substitute( + "Extension range $0 to $1 includes field \"$2\" ($3).", + range->start, range->end - 1, field->name(), field->number())); } } for (int j = 0; j < result->reserved_range_count(); j++) { @@ -4580,16 +4567,15 @@ void DescriptorBuilder::BuildMessage(const DescriptorProto& proto, if (range->start <= field->number() && field->number() < range->end) { AddError(field->full_name(), proto.reserved_range(j), DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute( - "Field \"$0\" uses reserved number $1.", - field->name(), field->number())); + strings::Substitute("Field \"$0\" uses reserved number $1.", + field->name(), field->number())); } } if (reserved_name_set.find(field->name()) != reserved_name_set.end()) { - AddError(field->full_name(), proto.field(i), - DescriptorPool::ErrorCollector::NAME, - strings::Substitute( - "Field name \"$0\" is reserved.", field->name())); + AddError( + field->full_name(), proto.field(i), + DescriptorPool::ErrorCollector::NAME, + strings::Substitute("Field name \"$0\" is reserved.", field->name())); } } @@ -4622,29 +4608,28 @@ void DescriptorBuilder::BuildMessage(const DescriptorProto& proto, } } - void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto, const Descriptor* parent, FieldDescriptor* result, bool is_extension) { - const string& scope = (parent == NULL) ? - file_->package() : parent->full_name(); - string* full_name = tables_->AllocateString(scope); + const std::string& scope = + (parent == NULL) ? file_->package() : parent->full_name(); + std::string* full_name = tables_->AllocateString(scope); if (!full_name->empty()) full_name->append(1, '.'); full_name->append(proto.name()); ValidateSymbolName(proto.name(), *full_name, proto); - result->name_ = tables_->AllocateString(proto.name()); - result->full_name_ = full_name; - result->file_ = file_; - result->number_ = proto.number(); + result->name_ = tables_->AllocateString(proto.name()); + result->full_name_ = full_name; + result->file_ = file_; + result->number_ = proto.number(); result->is_extension_ = is_extension; // If .proto files follow the style guide then the name should already be - // lower-cased. If that's the case we can just reuse the string we already - // allocated rather than allocate a new one. - string lowercase_name(proto.name()); + // lower-cased. If that's the case we can just reuse the string we + // already allocated rather than allocate a new one. + std::string lowercase_name(proto.name()); LowerString(&lowercase_name); if (lowercase_name == proto.name()) { result->lowercase_name_ = result->name_; @@ -4669,10 +4654,10 @@ void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto, // Some compilers do not allow static_cast directly between two enum types, // so we must cast to int first. - result->type_ = static_cast( - implicit_cast(proto.type())); + result->type_ = static_cast( + implicit_cast(proto.type())); result->label_ = static_cast( - implicit_cast(proto.label())); + implicit_cast(proto.label())); // An extension cannot have a required field (b/13365836). if (result->is_extension_ && @@ -4710,19 +4695,19 @@ void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto, switch (result->cpp_type()) { case FieldDescriptor::CPPTYPE_INT32: result->default_value_int32_ = - strtol(proto.default_value().c_str(), &end_pos, 0); + strtol(proto.default_value().c_str(), &end_pos, 0); break; case FieldDescriptor::CPPTYPE_INT64: result->default_value_int64_ = - strto64(proto.default_value().c_str(), &end_pos, 0); + strto64(proto.default_value().c_str(), &end_pos, 0); break; case FieldDescriptor::CPPTYPE_UINT32: result->default_value_uint32_ = - strtoul(proto.default_value().c_str(), &end_pos, 0); + strtoul(proto.default_value().c_str(), &end_pos, 0); break; case FieldDescriptor::CPPTYPE_UINT64: result->default_value_uint64_ = - strtou64(proto.default_value().c_str(), &end_pos, 0); + strtou64(proto.default_value().c_str(), &end_pos, 0); break; case FieldDescriptor::CPPTYPE_FLOAT: if (proto.default_value() == "inf") { @@ -4734,7 +4719,7 @@ void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto, } else if (proto.default_value() == "nan") { result->default_value_float_ = std::numeric_limits::quiet_NaN(); - } else { + } else { result->default_value_float_ = io::SafeDoubleToFloat( io::NoLocaleStrtod(proto.default_value().c_str(), &end_pos)); } @@ -4749,7 +4734,7 @@ void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto, } else if (proto.default_value() == "nan") { result->default_value_double_ = std::numeric_limits::quiet_NaN(); - } else { + } else { result->default_value_double_ = io::NoLocaleStrtod(proto.default_value().c_str(), &end_pos); } @@ -4772,7 +4757,7 @@ void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto, case FieldDescriptor::CPPTYPE_STRING: if (result->type() == FieldDescriptor::TYPE_BYTES) { result->default_value_string_ = tables_->AllocateString( - UnescapeCEscapeString(proto.default_value())); + UnescapeCEscapeString(proto.default_value())); } else { result->default_value_string_ = tables_->AllocateString(proto.default_value()); @@ -4794,7 +4779,7 @@ void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto, AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::DEFAULT_VALUE, "Couldn't parse default value \"" + proto.default_value() + - "\"."); + "\"."); } } } else { @@ -4853,10 +4838,10 @@ void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto, result->number() <= FieldDescriptor::kLastReservedNumber) { AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, strings::Substitute( - "Field numbers $0 through $1 are reserved for the protocol " - "buffer library implementation.", - FieldDescriptor::kFirstReservedNumber, - FieldDescriptor::kLastReservedNumber)); + "Field numbers $0 through $1 are reserved for the protocol " + "buffer library implementation.", + FieldDescriptor::kFirstReservedNumber, + FieldDescriptor::kLastReservedNumber)); } if (is_extension) { @@ -4869,8 +4854,7 @@ void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto, result->extension_scope_ = parent; if (proto.has_oneof_index()) { - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::OTHER, + AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, "FieldDescriptorProto.oneof_index should not be set for " "extensions."); } @@ -4890,11 +4874,10 @@ void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto, if (proto.oneof_index() < 0 || proto.oneof_index() >= parent->oneof_decl_count()) { AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::OTHER, + DescriptorPool::ErrorCollector::TYPE, strings::Substitute("FieldDescriptorProto.oneof_index $0 is " "out of range for type \"$1\".", - proto.oneof_index(), - parent->name())); + proto.oneof_index(), parent->name())); result->containing_oneof_ = NULL; } else { result->containing_oneof_ = parent->oneof_decl(proto.oneof_index()); @@ -4909,23 +4892,20 @@ void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto, result->options_ = NULL; // Will set to default_instance later. } else { AllocateOptions(proto.options(), result, - FieldDescriptorProto::kOptionsFieldNumber); + FieldDescriptorProto::kOptionsFieldNumber); } - AddSymbol(result->full_name(), parent, result->name(), - proto, Symbol(result)); + AddSymbol(result->full_name(), parent, result->name(), proto, Symbol(result)); } void DescriptorBuilder::BuildExtensionRange( - const DescriptorProto::ExtensionRange& proto, - const Descriptor* parent, + const DescriptorProto::ExtensionRange& proto, const Descriptor* parent, Descriptor::ExtensionRange* result) { result->start = proto.start(); result->end = proto.end(); if (result->start <= 0) { - AddError(parent->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, + AddError(parent->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, "Extension numbers must be positive integers."); } @@ -4935,8 +4915,7 @@ void DescriptorBuilder::BuildExtensionRange( // numbers are actually used as int32s in the message_set_wire_format. if (result->start >= result->end) { - AddError(parent->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, + AddError(parent->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, "Extension range end number must be greater than start number."); } @@ -4948,7 +4927,8 @@ void DescriptorBuilder::BuildExtensionRange( options_path.push_back(DescriptorProto::kExtensionRangeFieldNumber); // find index of this extension range in order to compute path int index; - for (index = 0; parent->extension_ranges_ + index != result; index++); + for (index = 0; parent->extension_ranges_ + index != result; index++) { + } options_path.push_back(index); options_path.push_back(DescriptorProto_ExtensionRange::kOptionsFieldNumber); AllocateOptionsImpl(parent->full_name(), parent->full_name(), @@ -4957,14 +4937,12 @@ void DescriptorBuilder::BuildExtensionRange( } void DescriptorBuilder::BuildReservedRange( - const DescriptorProto::ReservedRange& proto, - const Descriptor* parent, + const DescriptorProto::ReservedRange& proto, const Descriptor* parent, Descriptor::ReservedRange* result) { result->start = proto.start(); result->end = proto.end(); if (result->start <= 0) { - AddError(parent->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, + AddError(parent->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, "Reserved numbers must be positive integers."); } } @@ -4976,8 +4954,7 @@ void DescriptorBuilder::BuildReservedRange( result->end = proto.end(); if (result->start > result->end) { - AddError(parent->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, + AddError(parent->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, "Reserved range end number must be greater than start number."); } } @@ -4985,7 +4962,7 @@ void DescriptorBuilder::BuildReservedRange( void DescriptorBuilder::BuildOneof(const OneofDescriptorProto& proto, Descriptor* parent, OneofDescriptor* result) { - string* full_name = tables_->AllocateString(parent->full_name()); + std::string* full_name = tables_->AllocateString(parent->full_name()); full_name->append(1, '.'); full_name->append(proto.name()); @@ -5005,11 +4982,10 @@ void DescriptorBuilder::BuildOneof(const OneofDescriptorProto& proto, result->options_ = NULL; // Will set to default_instance later. } else { AllocateOptions(proto.options(), result, - OneofDescriptorProto::kOptionsFieldNumber); + OneofDescriptorProto::kOptionsFieldNumber); } - AddSymbol(result->full_name(), parent, result->name(), - proto, Symbol(result)); + AddSymbol(result->full_name(), parent, result->name(), proto, Symbol(result)); } void DescriptorBuilder::CheckEnumValueUniqueness( @@ -5041,13 +5017,12 @@ void DescriptorBuilder::CheckEnumValueUniqueness( // NAME_TYPE_LAST_NAME = 2, // } PrefixRemover remover(result->name()); - std::map values; + std::map values; for (int i = 0; i < result->value_count(); i++) { - const google::protobuf::EnumValueDescriptor* value = result->value(i); - string stripped = + const EnumValueDescriptor* value = result->value(i); + std::string stripped = EnumValueToPascalCase(remover.MaybeRemove(value->name())); - std::pair::iterator, - bool> + std::pair::iterator, bool> insert_result = values.insert(std::make_pair(stripped, value)); bool inserted = insert_result.second; @@ -5059,11 +5034,13 @@ void DescriptorBuilder::CheckEnumValueUniqueness( // stripping should de-dup the labels in this case). if (!inserted && insert_result.first->second->name() != value->name() && insert_result.first->second->number() != value->number()) { - string error_message = - "When enum name is stripped and label is PascalCased (" + stripped + - "), this value label conflicts with " + values[stripped]->name() + - ". This will make the proto fail to compile for some languages, such " - "as C#."; + std::string error_message = + "Enum name " + value->name() + " has the same name as " + + values[stripped]->name() + + " if you ignore case and strip out the enum name prefix (if any). " + "This is error-prone and can lead to undefined behavior. " + "Please avoid doing this. If you are using allow_alias, please " + "assign the same numeric value to both enums."; // There are proto2 enums out there with conflicting names, so to preserve // compatibility we issue only a warning for proto2. if (result->file()->syntax() == FileDescriptor::SYNTAX_PROTO2) { @@ -5080,26 +5057,25 @@ void DescriptorBuilder::CheckEnumValueUniqueness( void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto, const Descriptor* parent, EnumDescriptor* result) { - const string& scope = (parent == NULL) ? - file_->package() : parent->full_name(); - string* full_name = tables_->AllocateString(scope); + const std::string& scope = + (parent == NULL) ? file_->package() : parent->full_name(); + std::string* full_name = tables_->AllocateString(scope); if (!full_name->empty()) full_name->append(1, '.'); full_name->append(proto.name()); ValidateSymbolName(proto.name(), *full_name, proto); - result->name_ = tables_->AllocateString(proto.name()); - result->full_name_ = full_name; - result->file_ = file_; + result->name_ = tables_->AllocateString(proto.name()); + result->full_name_ = full_name; + result->file_ = file_; result->containing_type_ = parent; - result->is_placeholder_ = false; + result->is_placeholder_ = false; result->is_unqualified_placeholder_ = false; if (proto.value_size() == 0) { // We cannot allow enums with no values because this would mean there // would be no valid default value for fields of this type. - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, + AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NAME, "Enums must contain at least one value."); } @@ -5110,7 +5086,7 @@ void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto, int reserved_name_count = proto.reserved_name_size(); result->reserved_name_count_ = reserved_name_count; result->reserved_names_ = - tables_->AllocateArray(reserved_name_count); + tables_->AllocateArray(reserved_name_count); for (int i = 0; i < reserved_name_count; ++i) { result->reserved_names_[i] = tables_->AllocateString(proto.reserved_name(i)); @@ -5123,11 +5099,10 @@ void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto, result->options_ = NULL; // Will set to default_instance later. } else { AllocateOptions(proto.options(), result, - EnumDescriptorProto::kOptionsFieldNumber); + EnumDescriptorProto::kOptionsFieldNumber); } - AddSymbol(result->full_name(), parent, result->name(), - proto, Symbol(result)); + AddSymbol(result->full_name(), parent, result->name(), proto, Symbol(result)); for (int i = 0; i < proto.reserved_range_size(); i++) { const EnumDescriptorProto_EnumReservedRange& range1 = @@ -5146,16 +5121,15 @@ void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto, } } - HASH_SET reserved_name_set; + HASH_SET reserved_name_set; for (int i = 0; i < proto.reserved_name_size(); i++) { - const string& name = proto.reserved_name(i); + const std::string& name = proto.reserved_name(i); if (reserved_name_set.find(name) == reserved_name_set.end()) { reserved_name_set.insert(name); } else { AddError(name, proto, DescriptorPool::ErrorCollector::NAME, strings::Substitute( - "Enum value \"$0\" is reserved multiple times.", - name)); + "Enum value \"$0\" is reserved multiple times.", name)); } } @@ -5164,18 +5138,18 @@ void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto, for (int j = 0; j < result->reserved_range_count(); j++) { const EnumDescriptor::ReservedRange* range = result->reserved_range(j); if (range->start <= value->number() && value->number() <= range->end) { - AddError(value->full_name(), proto.reserved_range(j), - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute( - "Enum value \"$0\" uses reserved number $1.", - value->name(), value->number())); + AddError( + value->full_name(), proto.reserved_range(j), + DescriptorPool::ErrorCollector::NUMBER, + strings::Substitute("Enum value \"$0\" uses reserved number $1.", + value->name(), value->number())); } } if (reserved_name_set.find(value->name()) != reserved_name_set.end()) { - AddError(value->full_name(), proto.value(i), - DescriptorPool::ErrorCollector::NAME, - strings::Substitute( - "Enum value \"$0\" is reserved.", value->name())); + AddError( + value->full_name(), proto.value(i), + DescriptorPool::ErrorCollector::NAME, + strings::Substitute("Enum value \"$0\" is reserved.", value->name())); } } } @@ -5183,13 +5157,13 @@ void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto, void DescriptorBuilder::BuildEnumValue(const EnumValueDescriptorProto& proto, const EnumDescriptor* parent, EnumValueDescriptor* result) { - result->name_ = tables_->AllocateString(proto.name()); + result->name_ = tables_->AllocateString(proto.name()); result->number_ = proto.number(); - result->type_ = parent; + result->type_ = parent; // Note: full_name for enum values is a sibling to the parent's name, not a // child of it. - string* full_name = tables_->AllocateString(*parent->full_name_); + std::string* full_name = tables_->AllocateString(*parent->full_name_); full_name->resize(full_name->size() - parent->name_->size()); full_name->append(*result->name_); result->full_name_ = full_name; @@ -5201,28 +5175,28 @@ void DescriptorBuilder::BuildEnumValue(const EnumValueDescriptorProto& proto, result->options_ = NULL; // Will set to default_instance later. } else { AllocateOptions(proto.options(), result, - EnumValueDescriptorProto::kOptionsFieldNumber); + EnumValueDescriptorProto::kOptionsFieldNumber); } // Again, enum values are weird because we makes them appear as siblings // of the enum type instead of children of it. So, we use // parent->containing_type() as the value's parent. bool added_to_outer_scope = - AddSymbol(result->full_name(), parent->containing_type(), result->name(), - proto, Symbol(result)); + AddSymbol(result->full_name(), parent->containing_type(), result->name(), + proto, Symbol(result)); // However, we also want to be able to search for values within a single // enum type, so we add it as a child of the enum type itself, too. // Note: This could fail, but if it does, the error has already been // reported by the above AddSymbol() call, so we ignore the return code. bool added_to_inner_scope = - file_tables_->AddAliasUnderParent(parent, result->name(), Symbol(result)); + file_tables_->AddAliasUnderParent(parent, result->name(), Symbol(result)); if (added_to_inner_scope && !added_to_outer_scope) { // This value did not conflict with any values defined in the same enum, // but it did conflict with some other symbol defined in the enum type's // scope. Let's print an additional error to explain this. - string outer_scope; + std::string outer_scope; if (parent->containing_type() == NULL) { outer_scope = file_->package(); } else { @@ -5235,12 +5209,12 @@ void DescriptorBuilder::BuildEnumValue(const EnumValueDescriptorProto& proto, outer_scope = "\"" + outer_scope + "\""; } - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, + AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NAME, "Note that enum values use C++ scoping rules, meaning that " "enum values are siblings of their type, not children of it. " - "Therefore, \"" + result->name() + "\" must be unique within " - + outer_scope + ", not just within \"" + parent->name() + "\"."); + "Therefore, \"" + + result->name() + "\" must be unique within " + outer_scope + + ", not just within \"" + parent->name() + "\"."); } // An enum is allowed to define two numbers that refer to the same value. @@ -5252,15 +5226,15 @@ void DescriptorBuilder::BuildEnumValue(const EnumValueDescriptorProto& proto, void DescriptorBuilder::BuildService(const ServiceDescriptorProto& proto, const void* /* dummy */, ServiceDescriptor* result) { - string* full_name = tables_->AllocateString(file_->package()); + std::string* full_name = tables_->AllocateString(file_->package()); if (!full_name->empty()) full_name->append(1, '.'); full_name->append(proto.name()); ValidateSymbolName(proto.name(), *full_name, proto); - result->name_ = tables_->AllocateString(proto.name()); + result->name_ = tables_->AllocateString(proto.name()); result->full_name_ = full_name; - result->file_ = file_; + result->file_ = file_; BUILD_ARRAY(proto, result, method, BuildMethod, result); @@ -5269,20 +5243,19 @@ void DescriptorBuilder::BuildService(const ServiceDescriptorProto& proto, result->options_ = NULL; // Will set to default_instance later. } else { AllocateOptions(proto.options(), result, - ServiceDescriptorProto::kOptionsFieldNumber); + ServiceDescriptorProto::kOptionsFieldNumber); } - AddSymbol(result->full_name(), NULL, result->name(), - proto, Symbol(result)); + AddSymbol(result->full_name(), NULL, result->name(), proto, Symbol(result)); } void DescriptorBuilder::BuildMethod(const MethodDescriptorProto& proto, const ServiceDescriptor* parent, MethodDescriptor* result) { - result->name_ = tables_->AllocateString(proto.name()); + result->name_ = tables_->AllocateString(proto.name()); result->service_ = parent; - string* full_name = tables_->AllocateString(parent->full_name()); + std::string* full_name = tables_->AllocateString(parent->full_name()); full_name->append(1, '.'); full_name->append(*result->name_); result->full_name_ = full_name; @@ -5298,22 +5271,21 @@ void DescriptorBuilder::BuildMethod(const MethodDescriptorProto& proto, result->options_ = NULL; // Will set to default_instance later. } else { AllocateOptions(proto.options(), result, - MethodDescriptorProto::kOptionsFieldNumber); + MethodDescriptorProto::kOptionsFieldNumber); } result->client_streaming_ = proto.client_streaming(); result->server_streaming_ = proto.server_streaming(); - AddSymbol(result->full_name(), parent, result->name(), - proto, Symbol(result)); + AddSymbol(result->full_name(), parent, result->name(), proto, Symbol(result)); } #undef BUILD_ARRAY // ------------------------------------------------------------------- -void DescriptorBuilder::CrossLinkFile( - FileDescriptor* file, const FileDescriptorProto& proto) { +void DescriptorBuilder::CrossLinkFile(FileDescriptor* file, + const FileDescriptorProto& proto) { if (file->options_ == NULL) { file->options_ = &FileOptions::default_instance(); } @@ -5335,8 +5307,8 @@ void DescriptorBuilder::CrossLinkFile( } } -void DescriptorBuilder::CrossLinkMessage( - Descriptor* message, const DescriptorProto& proto) { +void DescriptorBuilder::CrossLinkMessage(Descriptor* message, + const DescriptorProto& proto) { if (message->options_ == NULL) { message->options_ = &MessageOptions::default_instance(); } @@ -5376,14 +5348,13 @@ void DescriptorBuilder::CrossLinkMessage( // safe. if (oneof_decl->field_count() > 0 && message->field(i - 1)->containing_oneof() != oneof_decl) { - AddError( - message->full_name() + "." + message->field(i - 1)->name(), - proto.field(i - 1), DescriptorPool::ErrorCollector::OTHER, - strings::Substitute( - "Fields in the same oneof must be defined consecutively. " - "\"$0\" cannot be defined before the completion of the " - "\"$1\" oneof definition.", - message->field(i - 1)->name(), oneof_decl->name())); + AddError(message->full_name() + "." + message->field(i - 1)->name(), + proto.field(i - 1), DescriptorPool::ErrorCollector::TYPE, + strings::Substitute( + "Fields in the same oneof must be defined consecutively. " + "\"$0\" cannot be defined before the completion of the " + "\"$1\" oneof definition.", + message->field(i - 1)->name(), oneof_decl->name())); } // Must go through oneof_decls_ array to get a non-const version of the // OneofDescriptor. @@ -5397,13 +5368,12 @@ void DescriptorBuilder::CrossLinkMessage( if (oneof_decl->field_count() == 0) { AddError(message->full_name() + "." + oneof_decl->name(), - proto.oneof_decl(i), - DescriptorPool::ErrorCollector::NAME, + proto.oneof_decl(i), DescriptorPool::ErrorCollector::NAME, "Oneof must have at least one field."); } - oneof_decl->fields_ = - tables_->AllocateArray(oneof_decl->field_count_); + oneof_decl->fields_ = tables_->AllocateArray( + oneof_decl->field_count_); oneof_decl->field_count_ = 0; if (oneof_decl->options_ == NULL) { @@ -5432,8 +5402,8 @@ void DescriptorBuilder::CrossLinkExtensionRange( } } -void DescriptorBuilder::CrossLinkField( - FieldDescriptor* field, const FieldDescriptorProto& proto) { +void DescriptorBuilder::CrossLinkField(FieldDescriptor* field, + const FieldDescriptorProto& proto) { if (field->options_ == NULL) { field->options_ = &FieldOptions::default_instance(); } @@ -5458,8 +5428,9 @@ void DescriptorBuilder::CrossLinkField( } field->containing_type_ = extendee.descriptor; - const Descriptor::ExtensionRange* extension_range = field->containing_type() - ->FindExtensionRangeContainingNumber(field->number()); + const Descriptor::ExtensionRange* extension_range = + field->containing_type()->FindExtensionRangeContainingNumber( + field->number()); if (extension_range == NULL) { AddError(field->full_name(), proto, @@ -5476,8 +5447,7 @@ void DescriptorBuilder::CrossLinkField( // Note that this error will never happen when parsing .proto files. // It can only happen if you manually construct a FileDescriptorProto // that is incorrect. - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, + AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::NAME, "Fields of oneofs must themselves have label LABEL_OPTIONAL."); } } @@ -5509,7 +5479,7 @@ void DescriptorBuilder::CrossLinkField( if (is_lazy) { // Save the symbol names for later for lookup, and allocate the once // object needed for the accessors. - string name = proto.type_name(); + std::string name = proto.type_name(); field->type_once_ = tables_->AllocateOnceDynamic(); field->type_name_ = tables_->AllocateString(name); if (proto.has_default_value()) { @@ -5598,20 +5568,19 @@ void DescriptorBuilder::CrossLinkField( // We can't just use field->enum_type()->FindValueByName() here // because that locks the pool's mutex, which we have already locked // at this point. - Symbol default_value = - LookupSymbolNoPlaceholder(proto.default_value(), - field->enum_type()->full_name()); + Symbol default_value = LookupSymbolNoPlaceholder( + proto.default_value(), field->enum_type()->full_name()); if (default_value.type == Symbol::ENUM_VALUE && default_value.enum_value_descriptor->type() == - field->enum_type()) { + field->enum_type()) { field->default_value_enum_ = default_value.enum_value_descriptor; } else { AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::DEFAULT_VALUE, "Enum type \"" + field->enum_type()->full_name() + - "\" has no value named \"" + proto.default_value() + - "\"."); + "\" has no value named \"" + proto.default_value() + + "\"."); } } } else if (field->enum_type()->value_count() > 0) { @@ -5639,27 +5608,25 @@ void DescriptorBuilder::CrossLinkField( // risk to calling containing_type() or other accessors that will build // dependencies. if (!file_tables_->AddFieldByNumber(field)) { - const FieldDescriptor* conflicting_field = - file_tables_->FindFieldByNumber(field->containing_type(), - field->number()); - string containing_type_name = field->containing_type() == NULL - ? "unknown" - : field->containing_type()->full_name(); + const FieldDescriptor* conflicting_field = file_tables_->FindFieldByNumber( + field->containing_type(), field->number()); + std::string containing_type_name = + field->containing_type() == NULL + ? "unknown" + : field->containing_type()->full_name(); if (field->is_extension()) { AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, strings::Substitute("Extension number $0 has already been used " "in \"$1\" by extension \"$2\".", - field->number(), - containing_type_name, + field->number(), containing_type_name, conflicting_field->full_name())); } else { AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, strings::Substitute("Field number $0 has already been used in " "\"$1\" by field \"$2\".", - field->number(), - containing_type_name, + field->number(), containing_type_name, conflicting_field->name())); } } else { @@ -5667,11 +5634,11 @@ void DescriptorBuilder::CrossLinkField( if (!tables_->AddExtension(field)) { const FieldDescriptor* conflicting_field = tables_->FindExtension(field->containing_type(), field->number()); - string containing_type_name = + std::string containing_type_name = field->containing_type() == NULL ? "unknown" : field->containing_type()->full_name(); - string error_msg = strings::Substitute( + std::string error_msg = strings::Substitute( "Extension number $0 has already been used in \"$1\" by extension " "\"$2\" defined in $3.", field->number(), containing_type_name, @@ -5687,8 +5654,8 @@ void DescriptorBuilder::CrossLinkField( } } -void DescriptorBuilder::CrossLinkEnum( - EnumDescriptor* enum_type, const EnumDescriptorProto& proto) { +void DescriptorBuilder::CrossLinkEnum(EnumDescriptor* enum_type, + const EnumDescriptorProto& proto) { if (enum_type->options_ == NULL) { enum_type->options_ = &EnumOptions::default_instance(); } @@ -5706,8 +5673,8 @@ void DescriptorBuilder::CrossLinkEnumValue( } } -void DescriptorBuilder::CrossLinkService( - ServiceDescriptor* service, const ServiceDescriptorProto& proto) { +void DescriptorBuilder::CrossLinkService(ServiceDescriptor* service, + const ServiceDescriptorProto& proto) { if (service->options_ == NULL) { service->options_ = &ServiceOptions::default_instance(); } @@ -5717,8 +5684,8 @@ void DescriptorBuilder::CrossLinkService( } } -void DescriptorBuilder::CrossLinkMethod( - MethodDescriptor* method, const MethodDescriptorProto& proto) { +void DescriptorBuilder::CrossLinkMethod(MethodDescriptor* method, + const MethodDescriptorProto& proto) { if (method->options_ == NULL) { method->options_ = &MethodOptions::default_instance(); } @@ -5766,10 +5733,10 @@ void DescriptorBuilder::CrossLinkMethod( // ------------------------------------------------------------------- -#define VALIDATE_OPTIONS_FROM_ARRAY(descriptor, array_name, type) \ - for (int i = 0; i < descriptor->array_name##_count(); ++i) { \ - Validate##type##Options(descriptor->array_name##s_ + i, \ - proto.array_name(i)); \ +#define VALIDATE_OPTIONS_FROM_ARRAY(descriptor, array_name, type) \ + for (int i = 0; i < descriptor->array_name##_count(); ++i) { \ + Validate##type##Options(descriptor->array_name##s_ + i, \ + proto.array_name(i)); \ } // Determine if the file uses optimize_for = LITE_RUNTIME, being careful to @@ -5777,8 +5744,7 @@ void DescriptorBuilder::CrossLinkMethod( static bool IsLite(const FileDescriptor* file) { // TODO(kenton): I don't even remember how many of these conditions are // actually possible. I'm just being super-safe. - return file != NULL && - &file->options() != &FileOptions::default_instance() && + return file != NULL && &file->options() != &FileOptions::default_instance() && file->options().optimize_for() == FileOptions::LITE_RUNTIME; } @@ -5794,11 +5760,12 @@ void DescriptorBuilder::ValidateFileOptions(FileDescriptor* file, for (int i = 0; i < file->dependency_count(); i++) { if (IsLite(file->dependency(i))) { AddError( - file->name(), proto, - DescriptorPool::ErrorCollector::OTHER, - "Files that do not use optimize_for = LITE_RUNTIME cannot import " - "files which do use this option. This file is not lite, but it " - "imports \"" + file->dependency(i)->name() + "\" which is."); + file->dependency(i)->name(), proto, + DescriptorPool::ErrorCollector::IMPORT, + "Files that do not use optimize_for = LITE_RUNTIME cannot import " + "files which do use this option. This file is not lite, but it " + "imports \"" + + file->dependency(i)->name() + "\" which is."); break; } } @@ -5808,8 +5775,8 @@ void DescriptorBuilder::ValidateFileOptions(FileDescriptor* file, } } -void DescriptorBuilder::ValidateProto3( - FileDescriptor* file, const FileDescriptorProto& proto) { +void DescriptorBuilder::ValidateProto3(FileDescriptor* file, + const FileDescriptorProto& proto) { for (int i = 0; i < file->extension_count(); ++i) { ValidateProto3Field(file->extensions_ + i, proto.extension(i)); } @@ -5821,8 +5788,8 @@ void DescriptorBuilder::ValidateProto3( } } -static string ToLowercaseWithoutUnderscores(const string& name) { - string result; +static std::string ToLowercaseWithoutUnderscores(const std::string& name) { + std::string result; for (int i = 0; i < name.size(); ++i) { if (name[i] != '_') { if (name[i] >= 'A' && name[i] <= 'Z') { @@ -5835,97 +5802,91 @@ static string ToLowercaseWithoutUnderscores(const string& name) { return result; } -void DescriptorBuilder::ValidateProto3Message( - Descriptor* message, const DescriptorProto& proto) { +void DescriptorBuilder::ValidateProto3Message(Descriptor* message, + const DescriptorProto& proto) { for (int i = 0; i < message->nested_type_count(); ++i) { - ValidateProto3Message(message->nested_types_ + i, - proto.nested_type(i)); + ValidateProto3Message(message->nested_types_ + i, proto.nested_type(i)); } for (int i = 0; i < message->enum_type_count(); ++i) { - ValidateProto3Enum(message->enum_types_ + i, - proto.enum_type(i)); + ValidateProto3Enum(message->enum_types_ + i, proto.enum_type(i)); } for (int i = 0; i < message->field_count(); ++i) { ValidateProto3Field(message->fields_ + i, proto.field(i)); } for (int i = 0; i < message->extension_count(); ++i) { - ValidateProto3Field(message->extensions_ +i, proto.extension(i)); + ValidateProto3Field(message->extensions_ + i, proto.extension(i)); } if (message->extension_range_count() > 0) { - AddError(message->full_name(), proto, - DescriptorPool::ErrorCollector::OTHER, + AddError(message->full_name(), proto.extension_range(0), + DescriptorPool::ErrorCollector::NUMBER, "Extension ranges are not allowed in proto3."); } if (message->options().message_set_wire_format()) { // Using MessageSet doesn't make sense since we disallow extensions. - AddError(message->full_name(), proto, - DescriptorPool::ErrorCollector::OTHER, + AddError(message->full_name(), proto, DescriptorPool::ErrorCollector::NAME, "MessageSet is not supported in proto3."); } // In proto3, we reject field names if they conflict in camelCase. // Note that we currently enforce a stricter rule: Field names must be // unique after being converted to lowercase with underscores removed. - std::map name_to_field; + std::map name_to_field; for (int i = 0; i < message->field_count(); ++i) { - string lowercase_name = ToLowercaseWithoutUnderscores( - message->field(i)->name()); + std::string lowercase_name = + ToLowercaseWithoutUnderscores(message->field(i)->name()); if (name_to_field.find(lowercase_name) != name_to_field.end()) { - AddError(message->full_name(), proto, - DescriptorPool::ErrorCollector::OTHER, + AddError(message->full_name(), proto.field(i), + DescriptorPool::ErrorCollector::NAME, "The JSON camel-case name of field \"" + - message->field(i)->name() + "\" conflicts with field \"" + - name_to_field[lowercase_name]->name() + "\". This is not " + - "allowed in proto3."); + message->field(i)->name() + "\" conflicts with field \"" + + name_to_field[lowercase_name]->name() + "\". This is not " + + "allowed in proto3."); } else { name_to_field[lowercase_name] = message->field(i); } } } -void DescriptorBuilder::ValidateProto3Field( - FieldDescriptor* field, const FieldDescriptorProto& proto) { +void DescriptorBuilder::ValidateProto3Field(FieldDescriptor* field, + const FieldDescriptorProto& proto) { if (field->is_extension() && !AllowedExtendeeInProto3(field->containing_type()->full_name())) { AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::OTHER, + DescriptorPool::ErrorCollector::EXTENDEE, "Extensions in proto3 are only allowed for defining options."); } if (field->is_required()) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::OTHER, + AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, "Required fields are not allowed in proto3."); } if (field->has_default_value()) { - AddError( - field->full_name(), proto, DescriptorPool::ErrorCollector::OTHER, - "Explicit default values are not allowed in proto3."); + AddError(field->full_name(), proto, + DescriptorPool::ErrorCollector::DEFAULT_VALUE, + "Explicit default values are not allowed in proto3."); } if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM && field->enum_type() && field->enum_type()->file()->syntax() != FileDescriptor::SYNTAX_PROTO3) { // Proto3 messages can only use Proto3 enum types; otherwise we can't // guarantee that the default value is zero. - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, + AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, "Enum type \"" + field->enum_type()->full_name() + - "\" is not a proto3 enum, but is used in \"" + - field->containing_type()->full_name() + - "\" which is a proto3 message type."); + "\" is not a proto3 enum, but is used in \"" + + field->containing_type()->full_name() + + "\" which is a proto3 message type."); } if (field->type() == FieldDescriptor::TYPE_GROUP) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, + AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, "Groups are not supported in proto3 syntax."); } } -void DescriptorBuilder::ValidateProto3Enum( - EnumDescriptor* enm, const EnumDescriptorProto& proto) { +void DescriptorBuilder::ValidateProto3Enum(EnumDescriptor* enm, + const EnumDescriptorProto& proto) { if (enm->value_count() > 0 && enm->value(0)->number() != 0) { - AddError( - enm->full_name(), proto, DescriptorPool::ErrorCollector::OTHER, - "The first enum value must be zero in proto3."); + AddError(enm->full_name(), proto.value(0), + DescriptorPool::ErrorCollector::NUMBER, + "The first enum value must be zero in proto3."); } } @@ -5937,9 +5898,9 @@ void DescriptorBuilder::ValidateMessageOptions(Descriptor* message, VALIDATE_OPTIONS_FROM_ARRAY(message, extension, Field); const int64 max_extension_range = - static_cast(message->options().message_set_wire_format() ? - kint32max : - FieldDescriptor::kMaxNumber); + static_cast(message->options().message_set_wire_format() + ? kint32max + : FieldDescriptor::kMaxNumber); for (int i = 0; i < message->extension_range_count(); ++i) { if (message->extension_range(i)->end > max_extension_range + 1) { AddError( @@ -5952,16 +5913,15 @@ void DescriptorBuilder::ValidateMessageOptions(Descriptor* message, } -void DescriptorBuilder::ValidateFieldOptions(FieldDescriptor* field, - const FieldDescriptorProto& proto) { +void DescriptorBuilder::ValidateFieldOptions( + FieldDescriptor* field, const FieldDescriptorProto& proto) { if (pool_->lazily_build_dependencies_ && (!field || !field->message_type())) { return; } // Only message type fields may be lazy. if (field->options().lazy()) { if (field->type() != FieldDescriptor::TYPE_MESSAGE) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, + AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, "[lazy = true] can only be specified for submessage fields."); } } @@ -5969,16 +5929,15 @@ void DescriptorBuilder::ValidateFieldOptions(FieldDescriptor* field, // Only repeated primitive fields may be packed. if (field->options().packed() && !field->is_packable()) { AddError( - field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, - "[packed = true] can only be specified for repeated primitive fields."); + field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, + "[packed = true] can only be specified for repeated primitive fields."); } // Note: Default instance may not yet be initialized here, so we have to // avoid reading from it. if (field->containing_type_ != NULL && &field->containing_type()->options() != - &MessageOptions::default_instance() && + &MessageOptions::default_instance() && field->containing_type()->options().message_set_wire_format()) { if (field->is_extension()) { if (!field->is_optional() || @@ -5988,15 +5947,13 @@ void DescriptorBuilder::ValidateFieldOptions(FieldDescriptor* field, "Extensions of MessageSets must be optional messages."); } } else { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, + AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::NAME, "MessageSets cannot have fields, only extensions."); } } // Lite extensions can only be of Lite types. - if (IsLite(field->file()) && - field->containing_type_ != NULL && + if (IsLite(field->file()) && field->containing_type_ != NULL && !IsLite(field->containing_type()->file())) { AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::EXTENDEE, @@ -6008,8 +5965,7 @@ void DescriptorBuilder::ValidateFieldOptions(FieldDescriptor* field, // Validate map types. if (field->is_map()) { if (!ValidateMapEntry(field, proto)) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::OTHER, + AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, "map_entry should not be set explicitly. Use map instead."); } @@ -6017,30 +5973,43 @@ void DescriptorBuilder::ValidateFieldOptions(FieldDescriptor* field, ValidateJSType(field, proto); + // json_name option is not allowed on extension fields. Note that the + // json_name field in FieldDescriptorProto is always populated by protoc + // when it sends descriptor data to plugins (caculated from field name if + // the option is not explicitly set) so we can't rely on its presence to + // determine whether the json_name option is set on the field. Here we + // compare it against the default calculated json_name value and consider + // the option set if they are different. This won't catch the case when + // an user explicitly sets json_name to the default value, but should be + // good enough to catch common misuses. + if (field->is_extension() && + (field->has_json_name() && + field->json_name() != ToJsonName(field->name()))) { + AddError(field->full_name(), proto, + DescriptorPool::ErrorCollector::OPTION_NAME, + "option json_name is not allowed on extension fields."); + } + } void DescriptorBuilder::ValidateEnumOptions(EnumDescriptor* enm, const EnumDescriptorProto& proto) { VALIDATE_OPTIONS_FROM_ARRAY(enm, value, EnumValue); if (!enm->options().has_allow_alias() || !enm->options().allow_alias()) { - std::map used_values; + std::map used_values; for (int i = 0; i < enm->value_count(); ++i) { const EnumValueDescriptor* enum_value = enm->value(i); if (used_values.find(enum_value->number()) != used_values.end()) { - string error = + std::string error = "\"" + enum_value->full_name() + "\" uses the same enum value as \"" + - used_values[enum_value->number()] + "\". If this is intended, set " + used_values[enum_value->number()] + + "\". If this is intended, set " "'option allow_alias = true;' to the enum definition."; if (!enm->options().allow_alias()) { // Generate error if duplicated enum values are explicitly disallowed. - AddError(enm->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, - error); - } else { - // Generate warning if duplicated values are found but the option - // isn't set. - GOOGLE_LOG(ERROR) << error; + AddError(enm->full_name(), proto.value(i), + DescriptorPool::ErrorCollector::NUMBER, error); } } else { used_values[enum_value->number()] = enum_value->full_name(); @@ -6054,13 +6023,12 @@ void DescriptorBuilder::ValidateEnumValueOptions( const EnumValueDescriptorProto& /* proto */) { // Nothing to do so far. } -void DescriptorBuilder::ValidateServiceOptions(ServiceDescriptor* service, - const ServiceDescriptorProto& proto) { +void DescriptorBuilder::ValidateServiceOptions( + ServiceDescriptor* service, const ServiceDescriptorProto& proto) { if (IsLite(service->file()) && (service->file()->options().cc_generic_services() || service->file()->options().java_generic_services())) { - AddError(service->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, + AddError(service->full_name(), proto, DescriptorPool::ErrorCollector::NAME, "Files with optimize_for = LITE_RUNTIME cannot define services " "unless you set both options cc_generic_services and " "java_generic_sevices to false."); @@ -6069,16 +6037,16 @@ void DescriptorBuilder::ValidateServiceOptions(ServiceDescriptor* service, VALIDATE_OPTIONS_FROM_ARRAY(service, method, Method); } -void DescriptorBuilder::ValidateMethodOptions(MethodDescriptor* /* method */, - const MethodDescriptorProto& /* proto */) { +void DescriptorBuilder::ValidateMethodOptions( + MethodDescriptor* /* method */, const MethodDescriptorProto& /* proto */) { // Nothing to do so far. } bool DescriptorBuilder::ValidateMapEntry(FieldDescriptor* field, const FieldDescriptorProto& proto) { const Descriptor* message = field->message_type(); - if (// Must not contain extensions, extension range or nested message or - // enums + if ( // Must not contain extensions, extension range or nested message or + // enums message->extension_count() != 0 || field->label() != FieldDescriptor::LABEL_REPEATED || message->extension_range_count() != 0 || @@ -6106,9 +6074,8 @@ bool DescriptorBuilder::ValidateMapEntry(FieldDescriptor* field, // Check key types are legal. switch (key->type()) { case FieldDescriptor::TYPE_ENUM: - AddError( - field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, - "Key in map fields cannot be enum types."); + AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, + "Key in map fields cannot be enum types."); break; case FieldDescriptor::TYPE_FLOAT: case FieldDescriptor::TYPE_DOUBLE: @@ -6133,15 +6100,14 @@ bool DescriptorBuilder::ValidateMapEntry(FieldDescriptor* field, case FieldDescriptor::TYPE_SFIXED64: // Legal cases break; - // Do not add a default, so that the compiler will complain when new types - // are added. + // Do not add a default, so that the compiler will complain when new types + // are added. } if (value->type() == FieldDescriptor::TYPE_ENUM) { if (value->enum_type()->value(0)->number() != 0) { - AddError( - field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, - "Enum value in map must define 0 as the first value."); + AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, + "Enum value in map must define 0 as the first value."); } } @@ -6150,10 +6116,10 @@ bool DescriptorBuilder::ValidateMapEntry(FieldDescriptor* field, void DescriptorBuilder::DetectMapConflicts(const Descriptor* message, const DescriptorProto& proto) { - std::map seen_types; + std::map seen_types; for (int i = 0; i < message->nested_type_count(); ++i) { const Descriptor* nested = message->nested_type(i); - std::pair::iterator, bool> result = + std::pair::iterator, bool> result = seen_types.insert(std::make_pair(nested->name(), nested)); if (!result.second) { if (result.first->second->options().map_entry() || @@ -6161,7 +6127,7 @@ void DescriptorBuilder::DetectMapConflicts(const Descriptor* message, AddError(message->full_name(), proto, DescriptorPool::ErrorCollector::NAME, "Expanded map entry type " + nested->name() + - " conflicts with an existing nested message type."); + " conflicts with an existing nested message type."); } } // Recursively test on the nested types. @@ -6170,37 +6136,37 @@ void DescriptorBuilder::DetectMapConflicts(const Descriptor* message, // Check for conflicted field names. for (int i = 0; i < message->field_count(); ++i) { const FieldDescriptor* field = message->field(i); - std::map::iterator iter = + std::map::iterator iter = seen_types.find(field->name()); if (iter != seen_types.end() && iter->second->options().map_entry()) { AddError(message->full_name(), proto, DescriptorPool::ErrorCollector::NAME, "Expanded map entry type " + iter->second->name() + - " conflicts with an existing field."); + " conflicts with an existing field."); } } // Check for conflicted enum names. for (int i = 0; i < message->enum_type_count(); ++i) { const EnumDescriptor* enum_desc = message->enum_type(i); - std::map::iterator iter = + std::map::iterator iter = seen_types.find(enum_desc->name()); if (iter != seen_types.end() && iter->second->options().map_entry()) { AddError(message->full_name(), proto, DescriptorPool::ErrorCollector::NAME, "Expanded map entry type " + iter->second->name() + - " conflicts with an existing enum type."); + " conflicts with an existing enum type."); } } // Check for conflicted oneof names. for (int i = 0; i < message->oneof_decl_count(); ++i) { const OneofDescriptor* oneof_desc = message->oneof_decl(i); - std::map::iterator iter = + std::map::iterator iter = seen_types.find(oneof_desc->name()); if (iter != seen_types.end() && iter->second->options().map_entry()) { AddError(message->full_name(), proto, DescriptorPool::ErrorCollector::NAME, "Expanded map entry type " + iter->second->name() + - " conflicts with an existing oneof type."); + " conflicts with an existing oneof type."); } } } @@ -6228,7 +6194,7 @@ void DescriptorBuilder::ValidateJSType(FieldDescriptor* field, AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, "Illegal jstype for int64, uint64, sint64, fixed64 " "or sfixed64 field: " + - FieldOptions_JSType_descriptor()->value(jstype)->name()); + FieldOptions_JSType_descriptor()->value(jstype)->name()); break; // No other types permit a jstype option. @@ -6245,12 +6211,12 @@ void DescriptorBuilder::ValidateJSType(FieldDescriptor* field, // ------------------------------------------------------------------- DescriptorBuilder::OptionInterpreter::OptionInterpreter( - DescriptorBuilder* builder) : builder_(builder) { + DescriptorBuilder* builder) + : builder_(builder) { GOOGLE_CHECK(builder_); } -DescriptorBuilder::OptionInterpreter::~OptionInterpreter() { -} +DescriptorBuilder::OptionInterpreter::~OptionInterpreter() {} bool DescriptorBuilder::OptionInterpreter::InterpretOptions( OptionsToInterpret* options_to_interpret) { @@ -6275,13 +6241,14 @@ bool DescriptorBuilder::OptionInterpreter::InterpretOptions( // Find the uninterpreted_option field in the original options. const FieldDescriptor* original_uninterpreted_options_field = - original_options->GetDescriptor()-> - FindFieldByName("uninterpreted_option"); + original_options->GetDescriptor()->FindFieldByName( + "uninterpreted_option"); GOOGLE_CHECK(original_uninterpreted_options_field != NULL) << "No field named \"uninterpreted_option\" in the Options proto."; - const int num_uninterpreted_options = original_options->GetReflection()-> - FieldSize(*original_options, original_uninterpreted_options_field); + const int num_uninterpreted_options = + original_options->GetReflection()->FieldSize( + *original_options, original_uninterpreted_options_field); for (int i = 0; i < num_uninterpreted_options; ++i) { src_path.push_back(i); uninterpreted_option_ = down_cast( @@ -6308,25 +6275,34 @@ bool DescriptorBuilder::OptionInterpreter::InterpretOptions( // If they are not known, that's OK too. They will get reparsed into the // UnknownFieldSet and wait there until the message is parsed by something // that does know about the options. - string buf; - GOOGLE_CHECK(options->AppendPartialToString(&buf)) - << "Protocol message could not be serialized."; - GOOGLE_CHECK(options->ParsePartialFromString(buf)) - << "Protocol message serialized itself in invalid fashion."; - if (!options->IsInitialized()) { - builder_->AddWarning( + + // Keep the unparsed options around in case the reparsing fails. + std::unique_ptr unparsed_options(options->New()); + options->GetReflection()->Swap(unparsed_options.get(), options); + + std::string buf; + if (!unparsed_options->AppendToString(&buf) || + !options->ParseFromString(buf)) { + builder_->AddError( options_to_interpret->element_name, *original_options, DescriptorPool::ErrorCollector::OTHER, - "Options could not be fully parsed using the proto descriptors " - "compiled into this binary. Missing required fields: " + - options->InitializationErrorString()); + "Some options could not be correctly parsed using the proto " + "descriptors compiled into this binary.\n" + "Unparsed options: " + + unparsed_options->ShortDebugString() + + "\n" + "Parsing attempt: " + + options->ShortDebugString()); + // Restore the unparsed options. + options->GetReflection()->Swap(unparsed_options.get(), options); } } return !failed; } bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( - Message* options, std::vector& src_path, std::vector& opts_path) { + Message* options, const std::vector& src_path, + const std::vector& options_path) { // First do some basic validation. if (uninterpreted_option_->name_size() == 0) { // This should never happen unless the parser has gone seriously awry or @@ -6334,15 +6310,16 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( return AddNameError("Option must have a name."); } if (uninterpreted_option_->name(0).name_part() == "uninterpreted_option") { - return AddNameError("Option must not use reserved name " - "\"uninterpreted_option\"."); + return AddNameError( + "Option must not use reserved name " + "\"uninterpreted_option\"."); } const Descriptor* options_descriptor = NULL; // Get the options message's descriptor from the builder's pool, so that we - // get the version that knows about any extension options declared in the - // file we're currently building. The descriptor should be there as long as - // the file we're building imported "google/protobuf/descriptors.proto". + // get the version that knows about any extension options declared in the file + // we're currently building. The descriptor should be there as long as the + // file we're building imported descriptor.proto. // Note that we use DescriptorBuilder::FindSymbolNotEnforcingDeps(), not // DescriptorPool::FindMessageTypeByName() because we're already holding the @@ -6350,7 +6327,7 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( // FindSymbol() because files that use custom options only need to depend on // the file that defines the option, not descriptor.proto itself. Symbol symbol = builder_->FindSymbolNotEnforcingDeps( - options->GetDescriptor()->full_name()); + options->GetDescriptor()->full_name()); if (!symbol.IsNull() && symbol.type == Symbol::MESSAGE) { options_descriptor = symbol.descriptor; } else { @@ -6370,12 +6347,12 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( const Descriptor* descriptor = options_descriptor; const FieldDescriptor* field = NULL; std::vector intermediate_fields; - string debug_msg_name = ""; + std::string debug_msg_name = ""; - std::vector dest_path = opts_path; + std::vector dest_path = options_path; for (int i = 0; i < uninterpreted_option_->name_size(); ++i) { - const string& name_part = uninterpreted_option_->name(i).name_part(); + const std::string& name_part = uninterpreted_option_->name(i).name_part(); if (debug_msg_name.size() > 0) { debug_msg_name += "."; } @@ -6386,8 +6363,8 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( // DescriptorPool::FindExtensionByName(), for two reasons: 1) It allows // relative lookups, and 2) because we're already holding the pool's // mutex, and the latter method locks it again. - symbol = builder_->LookupSymbol(name_part, - options_to_interpret_->name_scope); + symbol = + builder_->LookupSymbol(name_part, options_to_interpret_->name_scope); if (!symbol.IsNull() && symbol.type == Symbol::FIELD) { field = symbol.field_descriptor; } @@ -6417,7 +6394,10 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( debug_msg_name.substr(1) + "\") to start from the outermost scope."); } else { - return AddNameError("Option \"" + debug_msg_name + "\" unknown."); + return AddNameError( + "Option \"" + debug_msg_name + + "\" unknown. Ensure that your proto" + + " definition file imports the proto which defines the option."); } } else if (field->containing_type() != descriptor) { if (get_is_placeholder(field->containing_type())) { @@ -6442,7 +6422,7 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( if (i < uninterpreted_option_->name_size() - 1) { if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) { - return AddNameError("Option \"" + debug_msg_name + + return AddNameError("Option \"" + debug_msg_name + "\" is an atomic type, not a message."); } else if (field->is_repeated()) { return AddNameError("Option field \"" + debug_msg_name + @@ -6466,10 +6446,10 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( // known will populate them correctly. // First see if the option is already set. - if (!field->is_repeated() && !ExamineIfOptionIsSet( - intermediate_fields.begin(), - intermediate_fields.end(), - field, debug_msg_name, + if (!field->is_repeated() && + !ExamineIfOptionIsSet( + intermediate_fields.begin(), intermediate_fields.end(), field, + debug_msg_name, options->GetReflection()->GetUnknownFields(*options))) { return false; // ExamineIfOptionIsSet() already added the error. } @@ -6501,8 +6481,8 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( } case FieldDescriptor::TYPE_GROUP: { - parent_unknown_fields->AddGroup((*iter)->number()) - ->MergeFrom(*unknown_fields); + parent_unknown_fields->AddGroup((*iter)->number()) + ->MergeFrom(*unknown_fields); break; } @@ -6531,7 +6511,6 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( void DescriptorBuilder::OptionInterpreter::UpdateSourceCodeInfo( SourceCodeInfo* info) { - if (interpreted_paths_.empty()) { // nothing to do! return; @@ -6556,7 +6535,6 @@ void DescriptorBuilder::OptionInterpreter::UpdateSourceCodeInfo( for (RepeatedPtrField::iterator loc = locs->begin(); loc != locs->end(); loc++) { - if (matched) { // see if this location is in the range to remove bool loc_matches = true; @@ -6590,7 +6568,7 @@ void DescriptorBuilder::OptionInterpreter::UpdateSourceCodeInfo( if (entry == interpreted_paths_.end()) { // not a match if (copying) { - new_locs.Add()->CopyFrom(*loc); + *new_locs.Add() = *loc; } continue; } @@ -6602,14 +6580,15 @@ void DescriptorBuilder::OptionInterpreter::UpdateSourceCodeInfo( copying = true; new_locs.Reserve(locs->size()); for (RepeatedPtrField::iterator it = - locs->begin(); it != loc; it++) { - new_locs.Add()->CopyFrom(*it); + locs->begin(); + it != loc; it++) { + *new_locs.Add() = *it; } } // add replacement and update its path SourceCodeInfo_Location* replacement = new_locs.Add(); - replacement->CopyFrom(*loc); + *replacement = *loc; replacement->clear_path(); for (std::vector::iterator rit = entry->second.begin(); rit != entry->second.end(); rit++) { @@ -6626,18 +6605,19 @@ void DescriptorBuilder::OptionInterpreter::UpdateSourceCodeInfo( void DescriptorBuilder::OptionInterpreter::AddWithoutInterpreting( const UninterpretedOption& uninterpreted_option, Message* options) { const FieldDescriptor* field = - options->GetDescriptor()->FindFieldByName("uninterpreted_option"); + options->GetDescriptor()->FindFieldByName("uninterpreted_option"); GOOGLE_CHECK(field != NULL); - options->GetReflection()->AddMessage(options, field) - ->CopyFrom(uninterpreted_option); + options->GetReflection() + ->AddMessage(options, field) + ->CopyFrom(uninterpreted_option); } bool DescriptorBuilder::OptionInterpreter::ExamineIfOptionIsSet( std::vector::const_iterator intermediate_fields_iter, std::vector::const_iterator intermediate_fields_end, - const FieldDescriptor* innermost_field, const string& debug_msg_name, + const FieldDescriptor* innermost_field, const std::string& debug_msg_name, const UnknownFieldSet& unknown_fields) { // We do linear searches of the UnknownFieldSet and its sub-groups. This // should be fine since it's unlikely that any one options structure will @@ -6667,8 +6647,8 @@ bool DescriptorBuilder::OptionInterpreter::ExamineIfOptionIsSet( if (intermediate_unknown_fields.ParseFromString( unknown_field->length_delimited()) && !ExamineIfOptionIsSet(intermediate_fields_iter + 1, - intermediate_fields_end, - innermost_field, debug_msg_name, + intermediate_fields_end, innermost_field, + debug_msg_name, intermediate_unknown_fields)) { return false; // Error already added. } @@ -6678,9 +6658,8 @@ bool DescriptorBuilder::OptionInterpreter::ExamineIfOptionIsSet( case FieldDescriptor::TYPE_GROUP: if (unknown_field->type() == UnknownField::TYPE_GROUP) { if (!ExamineIfOptionIsSet(intermediate_fields_iter + 1, - intermediate_fields_end, - innermost_field, debug_msg_name, - unknown_field->group())) { + intermediate_fields_end, innermost_field, + debug_msg_name, unknown_field->group())) { return false; // Error already added. } } @@ -6696,11 +6675,9 @@ bool DescriptorBuilder::OptionInterpreter::ExamineIfOptionIsSet( } bool DescriptorBuilder::OptionInterpreter::SetOptionValue( - const FieldDescriptor* option_field, - UnknownFieldSet* unknown_fields) { + const FieldDescriptor* option_field, UnknownFieldSet* unknown_fields) { // We switch on the CppType to validate. switch (option_field->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: if (uninterpreted_option_->has_positive_int_value()) { if (uninterpreted_option_->positive_int_value() > @@ -6760,8 +6737,10 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( option_field->type(), unknown_fields); } } else { - return AddValueError("Value must be non-negative integer for uint32 " - "option \"" + option_field->full_name() + "\"."); + return AddValueError( + "Value must be non-negative integer for uint32 " + "option \"" + + option_field->full_name() + "\"."); } break; @@ -6771,8 +6750,10 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( uninterpreted_option_->positive_int_value(), option_field->type(), unknown_fields); } else { - return AddValueError("Value must be non-negative integer for uint64 " - "option \"" + option_field->full_name() + "\"."); + return AddValueError( + "Value must be non-negative integer for uint64 " + "option \"" + + option_field->full_name() + "\"."); } break; @@ -6789,7 +6770,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( option_field->full_name() + "\"."); } unknown_fields->AddFixed32(option_field->number(), - google::protobuf::internal::WireFormatLite::EncodeFloat(value)); + internal::WireFormatLite::EncodeFloat(value)); break; } @@ -6806,40 +6787,46 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( option_field->full_name() + "\"."); } unknown_fields->AddFixed64(option_field->number(), - google::protobuf::internal::WireFormatLite::EncodeDouble(value)); + internal::WireFormatLite::EncodeDouble(value)); break; } case FieldDescriptor::CPPTYPE_BOOL: uint64 value; if (!uninterpreted_option_->has_identifier_value()) { - return AddValueError("Value must be identifier for boolean option " - "\"" + option_field->full_name() + "\"."); + return AddValueError( + "Value must be identifier for boolean option " + "\"" + + option_field->full_name() + "\"."); } if (uninterpreted_option_->identifier_value() == "true") { value = 1; } else if (uninterpreted_option_->identifier_value() == "false") { value = 0; } else { - return AddValueError("Value must be \"true\" or \"false\" for boolean " - "option \"" + option_field->full_name() + "\"."); + return AddValueError( + "Value must be \"true\" or \"false\" for boolean " + "option \"" + + option_field->full_name() + "\"."); } unknown_fields->AddVarint(option_field->number(), value); break; case FieldDescriptor::CPPTYPE_ENUM: { if (!uninterpreted_option_->has_identifier_value()) { - return AddValueError("Value must be identifier for enum-valued option " - "\"" + option_field->full_name() + "\"."); + return AddValueError( + "Value must be identifier for enum-valued option " + "\"" + + option_field->full_name() + "\"."); } const EnumDescriptor* enum_type = option_field->enum_type(); - const string& value_name = uninterpreted_option_->identifier_value(); + const std::string& value_name = uninterpreted_option_->identifier_value(); const EnumValueDescriptor* enum_value = NULL; if (enum_type->file()->pool() != DescriptorPool::generated_pool()) { // Note that the enum value's fully-qualified name is a sibling of the // enum's name, not a child of it. - string fully_qualified_name = enum_type->full_name(); + std::string fully_qualified_name = enum_type->full_name(); fully_qualified_name.resize(fully_qualified_name.size() - enum_type->name().size()); fully_qualified_name += value_name; @@ -6849,10 +6836,11 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( // DescriptorPool::FindEnumValueByName() because we're already holding // the pool's mutex, and the latter method locks it again. Symbol symbol = - builder_->FindSymbolNotEnforcingDeps(fully_qualified_name); + builder_->FindSymbolNotEnforcingDeps(fully_qualified_name); if (!symbol.IsNull() && symbol.type == Symbol::ENUM_VALUE) { if (symbol.enum_value_descriptor->type() != enum_type) { - return AddValueError("Enum type \"" + enum_type->full_name() + + return AddValueError( + "Enum type \"" + enum_type->full_name() + "\" has no value named \"" + value_name + "\" for option \"" + option_field->full_name() + "\". This appears to be a value from a sibling type."); @@ -6869,25 +6857,30 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( if (enum_value == NULL) { return AddValueError("Enum type \"" + option_field->enum_type()->full_name() + - "\" has no value named \"" + value_name + "\" for " - "option \"" + option_field->full_name() + "\"."); + "\" has no value named \"" + value_name + + "\" for " + "option \"" + + option_field->full_name() + "\"."); } else { // Sign-extension is not a problem, since we cast directly from int32 to // uint64, without first going through uint32. - unknown_fields->AddVarint(option_field->number(), - static_cast(static_cast(enum_value->number()))); + unknown_fields->AddVarint( + option_field->number(), + static_cast(static_cast(enum_value->number()))); } break; } case FieldDescriptor::CPPTYPE_STRING: if (!uninterpreted_option_->has_string_value()) { - return AddValueError("Value must be quoted string for string option " - "\"" + option_field->full_name() + "\"."); + return AddValueError( + "Value must be quoted string for string option " + "\"" + + option_field->full_name() + "\"."); } // The string has already been unquoted and unescaped by the parser. unknown_fields->AddLengthDelimited(option_field->number(), - uninterpreted_option_->string_value()); + uninterpreted_option_->string_value()); break; case FieldDescriptor::CPPTYPE_MESSAGE: @@ -6905,12 +6898,12 @@ class DescriptorBuilder::OptionInterpreter::AggregateOptionFinder public: DescriptorBuilder* builder_; - virtual const FieldDescriptor* FindExtension( - Message* message, const string& name) const { + const FieldDescriptor* FindExtension(Message* message, + const std::string& name) const override { assert_mutex_held(builder_->pool_); const Descriptor* descriptor = message->GetDescriptor(); - Symbol result = builder_->LookupSymbolNoPlaceholder( - name, descriptor->full_name()); + Symbol result = + builder_->LookupSymbolNoPlaceholder(name, descriptor->full_name()); if (result.type == Symbol::FIELD && result.field_descriptor->is_extension()) { return result.field_descriptor; @@ -6941,37 +6934,37 @@ class DescriptorBuilder::OptionInterpreter::AggregateOptionFinder namespace { class AggregateErrorCollector : public io::ErrorCollector { public: - string error_; + std::string error_; - virtual void AddError(int /* line */, int /* column */, - const string& message) { + void AddError(int /* line */, int /* column */, + const std::string& message) override { if (!error_.empty()) { error_ += "; "; } error_ += message; } - virtual void AddWarning(int /* line */, int /* column */, - const string& /* message */) { + void AddWarning(int /* line */, int /* column */, + const std::string& /* message */) override { // Ignore warnings } }; -} +} // namespace // We construct a dynamic message of the type corresponding to // option_field, parse the supplied text-format string into this // message, and serialize the resulting message to produce the value. bool DescriptorBuilder::OptionInterpreter::SetAggregateOption( - const FieldDescriptor* option_field, - UnknownFieldSet* unknown_fields) { + const FieldDescriptor* option_field, UnknownFieldSet* unknown_fields) { if (!uninterpreted_option_->has_aggregate_value()) { return AddValueError("Option \"" + option_field->full_name() + "\" is a message. To set the entire message, use " - "syntax like \"" + option_field->name() + + "syntax like \"" + + option_field->name() + " = { }\". " "To set fields within it, use " - "syntax like \"" + option_field->name() + - ".foo = value\"."); + "syntax like \"" + + option_field->name() + ".foo = value\"."); } const Descriptor* type = option_field->message_type(); @@ -6991,12 +6984,12 @@ bool DescriptorBuilder::OptionInterpreter::SetAggregateOption( option_field->name() + "\": " + collector.error_); return false; } else { - string serial; + std::string serial; dynamic->SerializeToString(&serial); // Never fails if (option_field->type() == FieldDescriptor::TYPE_MESSAGE) { unknown_fields->AddLengthDelimited(option_field->number(), serial); } else { - GOOGLE_CHECK_EQ(option_field->type(), FieldDescriptor::TYPE_GROUP); + GOOGLE_CHECK_EQ(option_field->type(), FieldDescriptor::TYPE_GROUP); UnknownFieldSet* group = unknown_fields->AddGroup(option_field->number()); group->ParseFromString(serial); } @@ -7004,12 +6997,13 @@ bool DescriptorBuilder::OptionInterpreter::SetAggregateOption( } } -void DescriptorBuilder::OptionInterpreter::SetInt32(int number, int32 value, - FieldDescriptor::Type type, UnknownFieldSet* unknown_fields) { +void DescriptorBuilder::OptionInterpreter::SetInt32( + int number, int32 value, FieldDescriptor::Type type, + UnknownFieldSet* unknown_fields) { switch (type) { case FieldDescriptor::TYPE_INT32: unknown_fields->AddVarint(number, - static_cast(static_cast(value))); + static_cast(static_cast(value))); break; case FieldDescriptor::TYPE_SFIXED32: @@ -7017,8 +7011,8 @@ void DescriptorBuilder::OptionInterpreter::SetInt32(int number, int32 value, break; case FieldDescriptor::TYPE_SINT32: - unknown_fields->AddVarint(number, - google::protobuf::internal::WireFormatLite::ZigZagEncode32(value)); + unknown_fields->AddVarint( + number, internal::WireFormatLite::ZigZagEncode32(value)); break; default: @@ -7027,8 +7021,9 @@ void DescriptorBuilder::OptionInterpreter::SetInt32(int number, int32 value, } } -void DescriptorBuilder::OptionInterpreter::SetInt64(int number, int64 value, - FieldDescriptor::Type type, UnknownFieldSet* unknown_fields) { +void DescriptorBuilder::OptionInterpreter::SetInt64( + int number, int64 value, FieldDescriptor::Type type, + UnknownFieldSet* unknown_fields) { switch (type) { case FieldDescriptor::TYPE_INT64: unknown_fields->AddVarint(number, static_cast(value)); @@ -7039,8 +7034,8 @@ void DescriptorBuilder::OptionInterpreter::SetInt64(int number, int64 value, break; case FieldDescriptor::TYPE_SINT64: - unknown_fields->AddVarint(number, - google::protobuf::internal::WireFormatLite::ZigZagEncode64(value)); + unknown_fields->AddVarint( + number, internal::WireFormatLite::ZigZagEncode64(value)); break; default: @@ -7049,8 +7044,9 @@ void DescriptorBuilder::OptionInterpreter::SetInt64(int number, int64 value, } } -void DescriptorBuilder::OptionInterpreter::SetUInt32(int number, uint32 value, - FieldDescriptor::Type type, UnknownFieldSet* unknown_fields) { +void DescriptorBuilder::OptionInterpreter::SetUInt32( + int number, uint32 value, FieldDescriptor::Type type, + UnknownFieldSet* unknown_fields) { switch (type) { case FieldDescriptor::TYPE_UINT32: unknown_fields->AddVarint(number, static_cast(value)); @@ -7066,8 +7062,9 @@ void DescriptorBuilder::OptionInterpreter::SetUInt32(int number, uint32 value, } } -void DescriptorBuilder::OptionInterpreter::SetUInt64(int number, uint64 value, - FieldDescriptor::Type type, UnknownFieldSet* unknown_fields) { +void DescriptorBuilder::OptionInterpreter::SetUInt64( + int number, uint64 value, FieldDescriptor::Type type, + UnknownFieldSet* unknown_fields) { switch (type) { case FieldDescriptor::TYPE_UINT64: unknown_fields->AddVarint(number, value); @@ -7087,7 +7084,7 @@ void DescriptorBuilder::LogUnusedDependency(const FileDescriptorProto& proto, const FileDescriptor* result) { if (!unused_dependency_.empty()) { - std::set annotation_extensions; + std::set annotation_extensions; annotation_extensions.insert("google.protobuf.MessageOptions"); annotation_extensions.insert("google.protobuf.FileOptions"); annotation_extensions.insert("google.protobuf.FieldOptions"); @@ -7097,31 +7094,32 @@ void DescriptorBuilder::LogUnusedDependency(const FileDescriptorProto& proto, annotation_extensions.insert("google.protobuf.ServiceOptions"); annotation_extensions.insert("google.protobuf.MethodOptions"); annotation_extensions.insert("google.protobuf.StreamOptions"); - for (std::set::const_iterator - it = unused_dependency_.begin(); + for (std::set::const_iterator it = + unused_dependency_.begin(); it != unused_dependency_.end(); ++it) { // Do not log warnings for proto files which extend annotations. int i; - for (i = 0 ; i < (*it)->extension_count(); ++i) { + for (i = 0; i < (*it)->extension_count(); ++i) { if (annotation_extensions.find( - (*it)->extension(i)->containing_type()->full_name()) - != annotation_extensions.end()) { + (*it)->extension(i)->containing_type()->full_name()) != + annotation_extensions.end()) { break; } } // Log warnings for unused imported files. if (i == (*it)->extension_count()) { - string error_message = "Import " + (*it)->name() + " but not used."; - AddWarning((*it)->name(), proto, DescriptorPool::ErrorCollector::OTHER, + std::string error_message = + "Import " + (*it)->name() + " but not used."; + AddWarning((*it)->name(), proto, DescriptorPool::ErrorCollector::IMPORT, error_message); } } } } -Symbol DescriptorPool::CrossLinkOnDemandHelper(const string& name, +Symbol DescriptorPool::CrossLinkOnDemandHelper(const std::string& name, bool expecting_enum) const { - string lookup_name = name; + std::string lookup_name = name; if (!lookup_name.empty() && lookup_name[0] == '.') { lookup_name = lookup_name.substr(1); } @@ -7150,10 +7148,10 @@ void FieldDescriptor::InternalTypeOnceInit() const { if (default_value_enum_name_) { // Have to build the full name now instead of at CrossLink time, // because enum_type_ may not be known at the time. - string name = enum_type_->full_name(); + std::string name = enum_type_->full_name(); // Enum values reside in the same scope as the enum type. - string::size_type last_dot = name.find_last_of('.'); - if (last_dot != string::npos) { + std::string::size_type last_dot = name.find_last_of('.'); + if (last_dot != std::string::npos) { name = name.substr(0, last_dot) + "." + *default_value_enum_name_; } else { name = *default_value_enum_name_; @@ -7177,25 +7175,25 @@ void FieldDescriptor::TypeOnceInit(const FieldDescriptor* to_init) { } // message_type(), enum_type(), default_value_enum(), and type() -// all share the same GoogleOnceDynamic init path to do lazy +// all share the same internal::call_once init path to do lazy // import building and cross linking of a field of a message. const Descriptor* FieldDescriptor::message_type() const { if (type_once_) { - type_once_->Init(&FieldDescriptor::TypeOnceInit, this); + internal::call_once(*type_once_, FieldDescriptor::TypeOnceInit, this); } return message_type_; } const EnumDescriptor* FieldDescriptor::enum_type() const { if (type_once_) { - type_once_->Init(&FieldDescriptor::TypeOnceInit, this); + internal::call_once(*type_once_, FieldDescriptor::TypeOnceInit, this); } return enum_type_; } const EnumValueDescriptor* FieldDescriptor::default_value_enum() const { if (type_once_) { - type_once_->Init(&FieldDescriptor::TypeOnceInit, this); + internal::call_once(*type_once_, FieldDescriptor::TypeOnceInit, this); } return default_value_enum_; } @@ -7216,8 +7214,9 @@ void FileDescriptor::DependenciesOnceInit(const FileDescriptor* to_init) { const FileDescriptor* FileDescriptor::dependency(int index) const { if (dependencies_once_) { // Do once init for all indicies, as it's unlikely only a single index would - // be called, and saves on GoogleOnceDynamic allocations. - dependencies_once_->Init(&FileDescriptor::DependenciesOnceInit, this); + // be called, and saves on internal::call_once allocations. + internal::call_once(*dependencies_once_, + FileDescriptor::DependenciesOnceInit, this); } return dependencies_[index]; } @@ -7239,7 +7238,8 @@ void LazyDescriptor::Set(const Descriptor* descriptor) { descriptor_ = descriptor; } -void LazyDescriptor::SetLazy(const string& name, const FileDescriptor* file) { +void LazyDescriptor::SetLazy(const std::string& name, + const FileDescriptor* file) { // verify Init() has been called and Set hasn't been called yet. GOOGLE_CHECK(!descriptor_); GOOGLE_CHECK(!file_); @@ -7255,7 +7255,7 @@ void LazyDescriptor::SetLazy(const string& name, const FileDescriptor* file) { void LazyDescriptor::Once() { if (once_) { - once_->Init(&LazyDescriptor::OnceStatic, this); + internal::call_once(*once_, LazyDescriptor::OnceStatic, this); } } diff --git a/third_party/protobuf/src/google/protobuf/descriptor.h b/third_party/protobuf/src/google/protobuf/descriptor.h index 115d4ddc..7a873f0e 100644 --- a/third_party/protobuf/src/google/protobuf/descriptor.h +++ b/third_party/protobuf/src/google/protobuf/descriptor.h @@ -62,11 +62,18 @@ #include #include +#include + // TYPE_BOOL is defined in the MacOS's ConditionalMacros.h. #ifdef TYPE_BOOL #undef TYPE_BOOL #endif // TYPE_BOOL +#ifdef SWIG +#define PROTOBUF_EXPORT +#endif + + namespace google { namespace protobuf { @@ -123,6 +130,10 @@ class GeneratedMessageReflection; // Defined in command_line_interface.cc namespace compiler { class CommandLineInterface; +namespace cpp { +// Defined in helpers.h +class Formatter; +} // namespace cpp } // namespace compiler namespace descriptor_unittest { @@ -143,9 +154,9 @@ struct SourceLocation { // Doc comments found at the source location. // See the comments in SourceCodeInfo.Location (descriptor.proto) for details. - string leading_comments; - string trailing_comments; - std::vector leading_detached_comments; + std::string leading_comments; + std::string trailing_comments; + std::vector leading_detached_comments; }; // Options when generating machine-parsable output from a descriptor with @@ -163,7 +174,8 @@ struct DebugStringOptions { DebugStringOptions() : include_comments(false), elide_group_body(false), - elide_oneof_body(false) {} + elide_oneof_body(false) { + } }; // A class to handle the simplest cases of a lazily linked descriptor @@ -171,7 +183,7 @@ struct DebugStringOptions { // which is needed when a pool has lazily_build_dependencies_ set. // Must be instantiated as mutable in a descriptor. namespace internal { -class LIBPROTOBUF_EXPORT LazyDescriptor { +class PROTOBUF_EXPORT LazyDescriptor { public: // Init function to be called at init time of a descriptor containing // a LazyDescriptor. @@ -193,7 +205,7 @@ class LIBPROTOBUF_EXPORT LazyDescriptor { // build time if the symbol wasn't found and building of the file containing // that type is delayed because lazily_build_dependencies_ is set on the pool. // Should not be called after Set() has been called. - void SetLazy(const string& name, const FileDescriptor* file); + void SetLazy(const std::string& name, const FileDescriptor* file); // Returns the current value of the descriptor, thread-safe. If SetLazy(...) // has been called, will do a one-time cross link of the type specified, @@ -209,8 +221,8 @@ class LIBPROTOBUF_EXPORT LazyDescriptor { void Once(); const Descriptor* descriptor_; - const string* name_; - GoogleOnceDynamic* once_; + const std::string* name_; + internal::once_flag* once_; const FileDescriptor* file_; }; } // namespace internal @@ -220,17 +232,19 @@ class LIBPROTOBUF_EXPORT LazyDescriptor { // Message::GetDescriptor(). Generated message classes also have a // static method called descriptor() which returns the type's descriptor. // Use DescriptorPool to construct your own descriptors. -class LIBPROTOBUF_EXPORT Descriptor { +class PROTOBUF_EXPORT Descriptor { public: + typedef DescriptorProto Proto; + // The name of the message type, not including its scope. - const string& name() const; + const std::string& name() const; // The fully-qualified name of the message type, scope delimited by // periods. For example, message type "Foo" which is declared in package // "bar" has full name "bar.Foo". If a type "Baz" is nested within // Foo, Baz's full_name is "bar.Foo.Baz". To get only the part that // comes after the last '.', use name(). - const string& full_name() const; + const std::string& full_name() const; // Index of this descriptor within the file or containing type's message // type array. @@ -245,9 +259,8 @@ class LIBPROTOBUF_EXPORT Descriptor { // Get options for this message type. These are specified in the .proto file // by placing lines like "option foo = 1234;" in the message definition. - // Allowed options are defined by MessageOptions in - // google/protobuf/descriptor.proto, and any available extensions of that - // message. + // Allowed options are defined by MessageOptions in descriptor.proto, and any + // available extensions of that message. const MessageOptions& options() const; // Write the contents of this Descriptor into the given DescriptorProto. @@ -257,11 +270,11 @@ class LIBPROTOBUF_EXPORT Descriptor { // Write the contents of this decriptor in a human-readable form. Output // will be suitable for re-parsing. - string DebugString() const; + std::string DebugString() const; // Similar to DebugString(), but additionally takes options (e.g., // include original user comments in output). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Returns true if this is a placeholder for an unknown type. This will // only be the case if this descriptor comes from a DescriptorPool @@ -280,20 +293,20 @@ class LIBPROTOBUF_EXPORT Descriptor { // exists. const FieldDescriptor* FindFieldByNumber(int number) const; // Looks up a field by name. Returns NULL if no such field exists. - const FieldDescriptor* FindFieldByName(const string& name) const; + const FieldDescriptor* FindFieldByName(const std::string& name) const; // Looks up a field by lowercased name (as returned by lowercase_name()). // This lookup may be ambiguous if multiple field names differ only by case, // in which case the field returned is chosen arbitrarily from the matches. const FieldDescriptor* FindFieldByLowercaseName( - const string& lowercase_name) const; + const std::string& lowercase_name) const; // Looks up a field by camel-case name (as returned by camelcase_name()). // This lookup may be ambiguous if multiple field names differ in a way that // leads them to have identical camel-case names, in which case the field // returned is chosen arbitrarily from the matches. const FieldDescriptor* FindFieldByCamelcaseName( - const string& camelcase_name) const; + const std::string& camelcase_name) const; // The number of oneofs in this message type. int oneof_decl_count() const; @@ -302,7 +315,7 @@ class LIBPROTOBUF_EXPORT Descriptor { const OneofDescriptor* oneof_decl(int index) const; // Looks up a oneof by name. Returns NULL if no such oneof exists. - const OneofDescriptor* FindOneofByName(const string& name) const; + const OneofDescriptor* FindOneofByName(const std::string& name) const; // Nested type stuff ----------------------------------------------- @@ -314,7 +327,7 @@ class LIBPROTOBUF_EXPORT Descriptor { // Looks up a nested type by name. Returns NULL if no such nested type // exists. - const Descriptor* FindNestedTypeByName(const string& name) const; + const Descriptor* FindNestedTypeByName(const std::string& name) const; // Enum stuff ------------------------------------------------------ @@ -325,17 +338,19 @@ class LIBPROTOBUF_EXPORT Descriptor { const EnumDescriptor* enum_type(int index) const; // Looks up an enum type by name. Returns NULL if no such enum type exists. - const EnumDescriptor* FindEnumTypeByName(const string& name) const; + const EnumDescriptor* FindEnumTypeByName(const std::string& name) const; // Looks up an enum value by name, among all enum types in this message. // Returns NULL if no such value exists. - const EnumValueDescriptor* FindEnumValueByName(const string& name) const; + const EnumValueDescriptor* FindEnumValueByName(const std::string& name) const; // Extensions ------------------------------------------------------ // A range of field numbers which are designated for third-party // extensions. struct ExtensionRange { + typedef DescriptorProto_ExtensionRange Proto; + typedef ExtensionRangeOptions OptionsType; // See Descriptor::CopyTo(). @@ -369,15 +384,17 @@ class LIBPROTOBUF_EXPORT Descriptor { // Looks up a named extension (which extends some *other* message type) // defined within this message type's scope. - const FieldDescriptor* FindExtensionByName(const string& name) const; + const FieldDescriptor* FindExtensionByName(const std::string& name) const; // Similar to FindFieldByLowercaseName(), but finds extensions defined within // this message type's scope. - const FieldDescriptor* FindExtensionByLowercaseName(const string& name) const; + const FieldDescriptor* FindExtensionByLowercaseName( + const std::string& name) const; // Similar to FindFieldByCamelcaseName(), but finds extensions defined within // this message type's scope. - const FieldDescriptor* FindExtensionByCamelcaseName(const string& name) const; + const FieldDescriptor* FindExtensionByCamelcaseName( + const std::string& name) const; // Reserved fields ------------------------------------------------- @@ -404,10 +421,10 @@ class LIBPROTOBUF_EXPORT Descriptor { int reserved_name_count() const; // Gets a reserved name by index, where 0 <= index < reserved_name_count(). - const string& reserved_name(int index) const; + const std::string& reserved_name(int index) const; // Returns true if the field name is reserved. - bool IsReservedName(const string& name) const; + bool IsReservedName(const std::string& name) const; // Source Location --------------------------------------------------- @@ -420,10 +437,11 @@ class LIBPROTOBUF_EXPORT Descriptor { typedef MessageOptions OptionsType; // Allows tests to test CopyTo(proto, true). - friend class ::google::protobuf::descriptor_unittest::DescriptorTest; + friend class descriptor_unittest::DescriptorTest; // Allows access to GetLocationPath for annotations. - friend class ::google::protobuf::io::Printer; + friend class io::Printer; + friend class compiler::cpp::Formatter; // Fill the json_name field of FieldDescriptorProto. void CopyJsonNameTo(DescriptorProto* proto) const; @@ -432,7 +450,7 @@ class LIBPROTOBUF_EXPORT Descriptor { // correct depth. Takes |options| to control debug-string options, and // |include_opening_clause| to indicate whether the "message ... " part of the // clause has already been generated (this varies depending on context). - void DebugString(int depth, string *contents, + void DebugString(int depth, std::string* contents, const DebugStringOptions& options, bool include_opening_clause) const; @@ -440,8 +458,8 @@ class LIBPROTOBUF_EXPORT Descriptor { // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; + const std::string* name_; + const std::string* full_name_; const FileDescriptor* file_; const Descriptor* containing_type_; const MessageOptions* options_; @@ -454,7 +472,7 @@ class LIBPROTOBUF_EXPORT Descriptor { ExtensionRange* extension_ranges_; FieldDescriptor* extensions_; ReservedRange* reserved_ranges_; - const string** reserved_names_; + const std::string** reserved_names_; int field_count_; int oneof_decl_count_; @@ -499,67 +517,69 @@ class LIBPROTOBUF_EXPORT Descriptor { // Reflection::FindKnownExtensionByName() or // Reflection::FindKnownExtensionByNumber(). // Use DescriptorPool to construct your own descriptors. -class LIBPROTOBUF_EXPORT FieldDescriptor { +class PROTOBUF_EXPORT FieldDescriptor { public: + typedef FieldDescriptorProto Proto; + // Identifies a field type. 0 is reserved for errors. The order is weird // for historical reasons. Types 12 and up are new in proto2. enum Type { - TYPE_DOUBLE = 1, // double, exactly eight bytes on the wire. - TYPE_FLOAT = 2, // float, exactly four bytes on the wire. - TYPE_INT64 = 3, // int64, varint on the wire. Negative numbers - // take 10 bytes. Use TYPE_SINT64 if negative - // values are likely. - TYPE_UINT64 = 4, // uint64, varint on the wire. - TYPE_INT32 = 5, // int32, varint on the wire. Negative numbers - // take 10 bytes. Use TYPE_SINT32 if negative - // values are likely. - TYPE_FIXED64 = 6, // uint64, exactly eight bytes on the wire. - TYPE_FIXED32 = 7, // uint32, exactly four bytes on the wire. - TYPE_BOOL = 8, // bool, varint on the wire. - TYPE_STRING = 9, // UTF-8 text. - TYPE_GROUP = 10, // Tag-delimited message. Deprecated. - TYPE_MESSAGE = 11, // Length-delimited message. + TYPE_DOUBLE = 1, // double, exactly eight bytes on the wire. + TYPE_FLOAT = 2, // float, exactly four bytes on the wire. + TYPE_INT64 = 3, // int64, varint on the wire. Negative numbers + // take 10 bytes. Use TYPE_SINT64 if negative + // values are likely. + TYPE_UINT64 = 4, // uint64, varint on the wire. + TYPE_INT32 = 5, // int32, varint on the wire. Negative numbers + // take 10 bytes. Use TYPE_SINT32 if negative + // values are likely. + TYPE_FIXED64 = 6, // uint64, exactly eight bytes on the wire. + TYPE_FIXED32 = 7, // uint32, exactly four bytes on the wire. + TYPE_BOOL = 8, // bool, varint on the wire. + TYPE_STRING = 9, // UTF-8 text. + TYPE_GROUP = 10, // Tag-delimited message. Deprecated. + TYPE_MESSAGE = 11, // Length-delimited message. - TYPE_BYTES = 12, // Arbitrary byte array. - TYPE_UINT32 = 13, // uint32, varint on the wire - TYPE_ENUM = 14, // Enum, varint on the wire - TYPE_SFIXED32 = 15, // int32, exactly four bytes on the wire - TYPE_SFIXED64 = 16, // int64, exactly eight bytes on the wire - TYPE_SINT32 = 17, // int32, ZigZag-encoded varint on the wire - TYPE_SINT64 = 18, // int64, ZigZag-encoded varint on the wire + TYPE_BYTES = 12, // Arbitrary byte array. + TYPE_UINT32 = 13, // uint32, varint on the wire + TYPE_ENUM = 14, // Enum, varint on the wire + TYPE_SFIXED32 = 15, // int32, exactly four bytes on the wire + TYPE_SFIXED64 = 16, // int64, exactly eight bytes on the wire + TYPE_SINT32 = 17, // int32, ZigZag-encoded varint on the wire + TYPE_SINT64 = 18, // int64, ZigZag-encoded varint on the wire - MAX_TYPE = 18, // Constant useful for defining lookup tables - // indexed by Type. + MAX_TYPE = 18, // Constant useful for defining lookup tables + // indexed by Type. }; // Specifies the C++ data type used to represent the field. There is a // fixed mapping from Type to CppType where each Type maps to exactly one // CppType. 0 is reserved for errors. enum CppType { - CPPTYPE_INT32 = 1, // TYPE_INT32, TYPE_SINT32, TYPE_SFIXED32 - CPPTYPE_INT64 = 2, // TYPE_INT64, TYPE_SINT64, TYPE_SFIXED64 - CPPTYPE_UINT32 = 3, // TYPE_UINT32, TYPE_FIXED32 - CPPTYPE_UINT64 = 4, // TYPE_UINT64, TYPE_FIXED64 - CPPTYPE_DOUBLE = 5, // TYPE_DOUBLE - CPPTYPE_FLOAT = 6, // TYPE_FLOAT - CPPTYPE_BOOL = 7, // TYPE_BOOL - CPPTYPE_ENUM = 8, // TYPE_ENUM - CPPTYPE_STRING = 9, // TYPE_STRING, TYPE_BYTES - CPPTYPE_MESSAGE = 10, // TYPE_MESSAGE, TYPE_GROUP + CPPTYPE_INT32 = 1, // TYPE_INT32, TYPE_SINT32, TYPE_SFIXED32 + CPPTYPE_INT64 = 2, // TYPE_INT64, TYPE_SINT64, TYPE_SFIXED64 + CPPTYPE_UINT32 = 3, // TYPE_UINT32, TYPE_FIXED32 + CPPTYPE_UINT64 = 4, // TYPE_UINT64, TYPE_FIXED64 + CPPTYPE_DOUBLE = 5, // TYPE_DOUBLE + CPPTYPE_FLOAT = 6, // TYPE_FLOAT + CPPTYPE_BOOL = 7, // TYPE_BOOL + CPPTYPE_ENUM = 8, // TYPE_ENUM + CPPTYPE_STRING = 9, // TYPE_STRING, TYPE_BYTES + CPPTYPE_MESSAGE = 10, // TYPE_MESSAGE, TYPE_GROUP - MAX_CPPTYPE = 10, // Constant useful for defining lookup tables - // indexed by CppType. + MAX_CPPTYPE = 10, // Constant useful for defining lookup tables + // indexed by CppType. }; // Identifies whether the field is optional, required, or repeated. 0 is // reserved for errors. enum Label { - LABEL_OPTIONAL = 1, // optional - LABEL_REQUIRED = 2, // required - LABEL_REPEATED = 3, // repeated + LABEL_OPTIONAL = 1, // optional + LABEL_REQUIRED = 2, // required + LABEL_REPEATED = 3, // repeated - MAX_LABEL = 3, // Constant useful for defining lookup tables - // indexed by Label. + MAX_LABEL = 3, // Constant useful for defining lookup tables + // indexed by Label. }; // Valid field numbers are positive integers up to kMaxNumber. @@ -570,14 +590,14 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { static const int kFirstReservedNumber = 19000; // Last field number reserved for the protocol buffer library implementation. // Users may not declare fields that use reserved numbers. - static const int kLastReservedNumber = 19999; + static const int kLastReservedNumber = 19999; - const string& name() const; // Name of this field within the message. - const string& full_name() const; // Fully-qualified name of the field. - const string& json_name() const; // JSON name of this field. - const FileDescriptor* file() const;// File in which this field was defined. - bool is_extension() const; // Is this an extension field? - int number() const; // Declared tag number. + const std::string& name() const; // Name of this field within the message. + const std::string& full_name() const; // Fully-qualified name of the field. + const std::string& json_name() const; // JSON name of this field. + const FileDescriptor* file() const; // File in which this field was defined. + bool is_extension() const; // Is this an extension field? + int number() const; // Declared tag number. // Same as name() except converted to lower-case. This (and especially the // FindFieldByLowercaseName() method) can be useful when parsing formats @@ -585,7 +605,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // field names should be lowercased anyway according to the protobuf style // guide, so this only makes a difference when dealing with old .proto files // which do not follow the guide.) - const string& lowercase_name() const; + const std::string& lowercase_name() const; // Same as name() except converted to camel-case. In this conversion, any // time an underscore appears in the name, it is removed and the next @@ -596,7 +616,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // fooBar -> fooBar // This (and especially the FindFieldByCamelcaseName() method) can be useful // when parsing formats which prefer to use camel-case naming style. - const string& camelcase_name() const; + const std::string& camelcase_name() const; Type type() const; // Declared type of this field. const char* type_name() const; // Name of the declared type. @@ -604,15 +624,15 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { const char* cpp_type_name() const; // Name of the C++ type. Label label() const; // optional/required/repeated - bool is_required() const; // shorthand for label() == LABEL_REQUIRED - bool is_optional() const; // shorthand for label() == LABEL_OPTIONAL - bool is_repeated() const; // shorthand for label() == LABEL_REPEATED - bool is_packable() const; // shorthand for is_repeated() && - // IsTypePackable(type()) - bool is_packed() const; // shorthand for is_packable() && - // options().packed() - bool is_map() const; // shorthand for type() == TYPE_MESSAGE && - // message_type()->options().map_entry() + bool is_required() const; // shorthand for label() == LABEL_REQUIRED + bool is_optional() const; // shorthand for label() == LABEL_OPTIONAL + bool is_repeated() const; // shorthand for label() == LABEL_REPEATED + bool is_packable() const; // shorthand for is_repeated() && + // IsTypePackable(type()) + bool is_packed() const; // shorthand for is_packable() && + // options().packed() + bool is_map() const; // shorthand for type() == TYPE_MESSAGE && + // message_type()->options().map_entry() // Index of this field within the message's field array, or the file or // extension scope's extensions array. @@ -653,7 +673,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { const EnumValueDescriptor* default_value_enum() const; // Get the field default value if cpp_type() == CPPTYPE_STRING. If no // explicit default was defined, the default is the empty string. - const string& default_value_string() const; + const std::string& default_value_string() const; // The Descriptor for the message of which this is a field. For extensions, // this is the extended type. Never NULL. @@ -683,19 +703,18 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // Get the FieldOptions for this field. This includes things listed in // square brackets after the field definition. E.g., the field: // optional string text = 1 [ctype=CORD]; - // has the "ctype" option set. Allowed options are defined by FieldOptions - // in google/protobuf/descriptor.proto, and any available extensions of that - // message. + // has the "ctype" option set. Allowed options are defined by FieldOptions in + // descriptor.proto, and any available extensions of that message. const FieldOptions& options() const; // See Descriptor::CopyTo(). void CopyTo(FieldDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Helper method to get the CppType for a particular Type. static CppType TypeToCppType(Type type); @@ -720,7 +739,8 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { typedef FieldOptions OptionsType; // Allows access to GetLocationPath for annotations. - friend class ::google::protobuf::io::Printer; + friend class io::Printer; + friend class compiler::cpp::Formatter; // Fill the json_name field of FieldDescriptorProto. void CopyJsonNameTo(FieldDescriptorProto* proto) const; @@ -728,15 +748,16 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // See Descriptor::DebugString(). enum PrintLabelFlag { PRINT_LABEL, OMIT_LABEL }; void DebugString(int depth, PrintLabelFlag print_label_flag, - string* contents, const DebugStringOptions& options) const; + std::string* contents, + const DebugStringOptions& options) const; // formats the default value appropriately and returns it as a string. // Must have a default value to call this. If quote_string_type is true, then // types of CPPTYPE_STRING whill be surrounded by quotes and CEscaped. - string DefaultValueAsString(bool quote_string_type) const; + std::string DefaultValueAsString(bool quote_string_type) const; // Helper function that returns the field type name for DebugString. - string FieldTypeNameDebugString() const; + std::string FieldTypeNameDebugString() const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. @@ -745,15 +766,15 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // Returns true if this is a map message type. bool is_map_message_type() const; - const string* name_; - const string* full_name_; - const string* lowercase_name_; - const string* camelcase_name_; + const std::string* name_; + const std::string* full_name_; + const std::string* lowercase_name_; + const std::string* camelcase_name_; // If has_json_name_ is true, it's the value specified by the user. // Otherwise, it has the same value as camelcase_name_. - const string* json_name_; + const std::string* json_name_; const FileDescriptor* file_; - GoogleOnceDynamic* type_once_; + internal::once_flag* type_once_; static void TypeOnceInit(const FieldDescriptor* to_init); void InternalTypeOnceInit() const; mutable Type type_; @@ -771,32 +792,32 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { mutable const Descriptor* message_type_; mutable const EnumDescriptor* enum_type_; const FieldOptions* options_; - const string* type_name_; - const string* default_value_enum_name_; + const std::string* type_name_; + const std::string* default_value_enum_name_; // IMPORTANT: If you add a new field, make sure to search for all instances // of Allocate() and AllocateArray() in // descriptor.cc and update them to initialize the field. union { - int32 default_value_int32_; - int64 default_value_int64_; + int32 default_value_int32_; + int64 default_value_int64_; uint32 default_value_uint32_; uint64 default_value_uint64_; - float default_value_float_; + float default_value_float_; double default_value_double_; - bool default_value_bool_; + bool default_value_bool_; mutable const EnumValueDescriptor* default_value_enum_; - const string* default_value_string_; + const std::string* default_value_string_; }; static const CppType kTypeToCppTypeMap[MAX_TYPE + 1]; - static const char * const kTypeToName[MAX_TYPE + 1]; + static const char* const kTypeToName[MAX_TYPE + 1]; - static const char * const kCppTypeToName[MAX_CPPTYPE + 1]; + static const char* const kCppTypeToName[MAX_CPPTYPE + 1]; - static const char * const kLabelToName[MAX_LABEL + 1]; + static const char* const kLabelToName[MAX_LABEL + 1]; // Must be constructed using DescriptorPool. FieldDescriptor() {} @@ -809,10 +830,12 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // Describes a oneof defined in a message type. -class LIBPROTOBUF_EXPORT OneofDescriptor { +class PROTOBUF_EXPORT OneofDescriptor { public: - const string& name() const; // Name of this oneof. - const string& full_name() const; // Fully-qualified name of the oneof. + typedef OneofDescriptorProto Proto; + + const std::string& name() const; // Name of this oneof. + const std::string& full_name() const; // Fully-qualified name of the oneof. // Index of this oneof within the message's oneof array. int index() const; @@ -834,10 +857,10 @@ class LIBPROTOBUF_EXPORT OneofDescriptor { void CopyTo(OneofDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Source Location --------------------------------------------------- @@ -850,20 +873,20 @@ class LIBPROTOBUF_EXPORT OneofDescriptor { typedef OneofOptions OptionsType; // Allows access to GetLocationPath for annotations. - friend class ::google::protobuf::io::Printer; + friend class io::Printer; + friend class compiler::cpp::Formatter; // See Descriptor::DebugString(). - void DebugString(int depth, string* contents, + void DebugString(int depth, std::string* contents, const DebugStringOptions& options) const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; + const std::string* name_; + const std::string* full_name_; const Descriptor* containing_type_; - bool is_extendable_; int field_count_; const FieldDescriptor** fields_; const OneofOptions* options_; @@ -882,13 +905,15 @@ class LIBPROTOBUF_EXPORT OneofDescriptor { // Describes an enum type defined in a .proto file. To get the EnumDescriptor // for a generated enum type, call TypeName_descriptor(). Use DescriptorPool // to construct your own descriptors. -class LIBPROTOBUF_EXPORT EnumDescriptor { +class PROTOBUF_EXPORT EnumDescriptor { public: + typedef EnumDescriptorProto Proto; + // The name of this enum type in the containing scope. - const string& name() const; + const std::string& name() const; // The fully-qualified name of the enum type, scope delimited by periods. - const string& full_name() const; + const std::string& full_name() const; // Index of this enum within the file or containing message's enum array. int index() const; @@ -904,7 +929,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { const EnumValueDescriptor* value(int index) const; // Looks up a value by name. Returns NULL if no such value exists. - const EnumValueDescriptor* FindValueByName(const string& name) const; + const EnumValueDescriptor* FindValueByName(const std::string& name) const; // Looks up a value by number. Returns NULL if no such value exists. If // multiple values have this number, the first one defined is returned. const EnumValueDescriptor* FindValueByNumber(int number) const; @@ -915,18 +940,18 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { // Get options for this enum type. These are specified in the .proto file by // placing lines like "option foo = 1234;" in the enum definition. Allowed - // options are defined by EnumOptions in google/protobuf/descriptor.proto, - // and any available extensions of that message. + // options are defined by EnumOptions in descriptor.proto, and any available + // extensions of that message. const EnumOptions& options() const; // See Descriptor::CopyTo(). void CopyTo(EnumDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Returns true if this is a placeholder for an unknown enum. This will // only be the case if this descriptor comes from a DescriptorPool @@ -952,17 +977,17 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { bool IsReservedNumber(int number) const; // Returns NULL if no reserved range contains the given number. - const EnumDescriptor::ReservedRange* - FindReservedRangeContainingNumber(int number) const; + const EnumDescriptor::ReservedRange* FindReservedRangeContainingNumber( + int number) const; // The number of reserved field names in this message type. int reserved_name_count() const; // Gets a reserved name by index, where 0 <= index < reserved_name_count(). - const string& reserved_name(int index) const; + const std::string& reserved_name(int index) const; // Returns true if the field name is reserved. - bool IsReservedName(const string& name) const; + bool IsReservedName(const std::string& name) const; // Source Location --------------------------------------------------- @@ -975,7 +1000,8 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { typedef EnumOptions OptionsType; // Allows access to GetLocationPath for annotations. - friend class ::google::protobuf::io::Printer; + friend class io::Printer; + friend class compiler::cpp::Formatter; // Looks up a value by number. If the value does not exist, dynamically // creates a new EnumValueDescriptor for that value, assuming that it was @@ -985,20 +1011,19 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { // This is private but is used by GeneratedMessageReflection (which is // friended below) to return a valid EnumValueDescriptor from GetEnum() when // this feature is enabled. - const EnumValueDescriptor* - FindValueByNumberCreatingIfUnknown(int number) const; - + const EnumValueDescriptor* FindValueByNumberCreatingIfUnknown( + int number) const; // See Descriptor::DebugString(). - void DebugString(int depth, string *contents, + void DebugString(int depth, std::string* contents, const DebugStringOptions& options) const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; + const std::string* name_; + const std::string* full_name_; const FileDescriptor* file_; const Descriptor* containing_type_; const EnumOptions* options_; @@ -1014,7 +1039,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { int reserved_range_count_; int reserved_name_count_; EnumDescriptor::ReservedRange* reserved_ranges_; - const string** reserved_names_; + const std::string** reserved_names_; // IMPORTANT: If you add a new field, make sure to search for all instances // of Allocate() and AllocateArray() in @@ -1037,40 +1062,40 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { // for its type, then use EnumDescriptor::FindValueByName() or // EnumDescriptor::FindValueByNumber(). Use DescriptorPool to construct // your own descriptors. -class LIBPROTOBUF_EXPORT EnumValueDescriptor { +class PROTOBUF_EXPORT EnumValueDescriptor { public: - const string& name() const; // Name of this enum constant. - int index() const; // Index within the enums's Descriptor. - int number() const; // Numeric value of this enum constant. + typedef EnumValueDescriptorProto Proto; + + const std::string& name() const; // Name of this enum constant. + int index() const; // Index within the enums's Descriptor. + int number() const; // Numeric value of this enum constant. // The full_name of an enum value is a sibling symbol of the enum type. // e.g. the full name of FieldDescriptorProto::TYPE_INT32 is actually // "google.protobuf.FieldDescriptorProto.TYPE_INT32", NOT // "google.protobuf.FieldDescriptorProto.Type.TYPE_INT32". This is to conform // with C++ scoping rules for enums. - const string& full_name() const; + const std::string& full_name() const; // The .proto file in which this value was defined. Never NULL. const FileDescriptor* file() const; // The type of this value. Never NULL. const EnumDescriptor* type() const; - // Get options for this enum value. These are specified in the .proto file - // by adding text like "[foo = 1234]" after an enum value definition. - // Allowed options are defined by EnumValueOptions in - // google/protobuf/descriptor.proto, and any available extensions of that - // message. + // Get options for this enum value. These are specified in the .proto file by + // adding text like "[foo = 1234]" after an enum value definition. Allowed + // options are defined by EnumValueOptions in descriptor.proto, and any + // available extensions of that message. const EnumValueOptions& options() const; // See Descriptor::CopyTo(). void CopyTo(EnumValueDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; - + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Source Location --------------------------------------------------- @@ -1083,18 +1108,19 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptor { typedef EnumValueOptions OptionsType; // Allows access to GetLocationPath for annotations. - friend class ::google::protobuf::io::Printer; + friend class io::Printer; + friend class compiler::cpp::Formatter; // See Descriptor::DebugString(). - void DebugString(int depth, string *contents, + void DebugString(int depth, std::string* contents, const DebugStringOptions& options) const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; + const std::string* name_; + const std::string* full_name_; int number_; const EnumDescriptor* type_; const EnumValueOptions* options_; @@ -1111,16 +1137,16 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptor { GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumValueDescriptor); }; -// Describes an RPC service. To get the ServiceDescriptor for a service, -// call Service::GetDescriptor(). Generated service classes also have a -// static method called descriptor() which returns the type's -// ServiceDescriptor. Use DescriptorPool to construct your own descriptors. -class LIBPROTOBUF_EXPORT ServiceDescriptor { +// Describes an RPC service. Use DescriptorPool to construct your own +// descriptors. +class PROTOBUF_EXPORT ServiceDescriptor { public: + typedef ServiceDescriptorProto Proto; + // The name of the service, not including its containing scope. - const string& name() const; + const std::string& name() const; // The fully-qualified name of the service, scope delimited by periods. - const string& full_name() const; + const std::string& full_name() const; // Index of this service within the file's services array. int index() const; @@ -1129,9 +1155,8 @@ class LIBPROTOBUF_EXPORT ServiceDescriptor { // Get options for this service type. These are specified in the .proto file // by placing lines like "option foo = 1234;" in the service definition. - // Allowed options are defined by ServiceOptions in - // google/protobuf/descriptor.proto, and any available extensions of that - // message. + // Allowed options are defined by ServiceOptions in descriptor.proto, and any + // available extensions of that message. const ServiceOptions& options() const; // The number of methods this service defines. @@ -1141,16 +1166,15 @@ class LIBPROTOBUF_EXPORT ServiceDescriptor { const MethodDescriptor* method(int index) const; // Look up a MethodDescriptor by name. - const MethodDescriptor* FindMethodByName(const string& name) const; + const MethodDescriptor* FindMethodByName(const std::string& name) const; // See Descriptor::CopyTo(). void CopyTo(ServiceDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; - + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Source Location --------------------------------------------------- @@ -1163,17 +1187,19 @@ class LIBPROTOBUF_EXPORT ServiceDescriptor { typedef ServiceOptions OptionsType; // Allows access to GetLocationPath for annotations. - friend class ::google::protobuf::io::Printer; + friend class io::Printer; + friend class compiler::cpp::Formatter; // See Descriptor::DebugString(). - void DebugString(string *contents, const DebugStringOptions& options) const; + void DebugString(std::string* contents, + const DebugStringOptions& options) const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; + const std::string* name_; + const std::string* full_name_; const FileDescriptor* file_; const ServiceOptions* options_; MethodDescriptor* methods_; @@ -1195,12 +1221,14 @@ class LIBPROTOBUF_EXPORT ServiceDescriptor { // a service, first get its ServiceDescriptor, then call // ServiceDescriptor::FindMethodByName(). Use DescriptorPool to construct your // own descriptors. -class LIBPROTOBUF_EXPORT MethodDescriptor { +class PROTOBUF_EXPORT MethodDescriptor { public: + typedef MethodDescriptorProto Proto; + // Name of this method, not including containing scope. - const string& name() const; + const std::string& name() const; // The fully-qualified name of the method, scope delimited by periods. - const string& full_name() const; + const std::string& full_name() const; // Index within the service's Descriptor. int index() const; @@ -1222,19 +1250,17 @@ class LIBPROTOBUF_EXPORT MethodDescriptor { // Get options for this method. These are specified in the .proto file by // placing lines like "option foo = 1234;" in curly-braces after a method // declaration. Allowed options are defined by MethodOptions in - // google/protobuf/descriptor.proto, and any available extensions of that - // message. + // descriptor.proto, and any available extensions of that message. const MethodOptions& options() const; // See Descriptor::CopyTo(). void CopyTo(MethodDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; - + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Source Location --------------------------------------------------- @@ -1247,18 +1273,19 @@ class LIBPROTOBUF_EXPORT MethodDescriptor { typedef MethodOptions OptionsType; // Allows access to GetLocationPath for annotations. - friend class ::google::protobuf::io::Printer; + friend class io::Printer; + friend class compiler::cpp::Formatter; // See Descriptor::DebugString(). - void DebugString(int depth, string *contents, + void DebugString(int depth, std::string* contents, const DebugStringOptions& options) const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; + const std::string* name_; + const std::string* full_name_; const ServiceDescriptor* service_; mutable internal::LazyDescriptor input_type_; mutable internal::LazyDescriptor output_type_; @@ -1280,14 +1307,16 @@ class LIBPROTOBUF_EXPORT MethodDescriptor { // Describes a whole .proto file. To get the FileDescriptor for a compiled-in // file, get the descriptor for something defined in that file and call // descriptor->file(). Use DescriptorPool to construct your own descriptors. -class LIBPROTOBUF_EXPORT FileDescriptor { +class PROTOBUF_EXPORT FileDescriptor { public: + typedef FileDescriptorProto Proto; + // The filename, relative to the source tree. - // e.g. "google/protobuf/descriptor.proto" - const string& name() const; + // e.g. "foo/bar/baz.proto" + const std::string& name() const; // The package, e.g. "google.protobuf.compiler". - const string& package() const; + const std::string& package() const; // The DescriptorPool in which this FileDescriptor and all its contents were // allocated. Never NULL. @@ -1345,36 +1374,37 @@ class LIBPROTOBUF_EXPORT FileDescriptor { // Get options for this file. These are specified in the .proto file by // placing lines like "option foo = 1234;" at the top level, outside of any // other definitions. Allowed options are defined by FileOptions in - // google/protobuf/descriptor.proto, and any available extensions of that - // message. + // descriptor.proto, and any available extensions of that message. const FileOptions& options() const; // Syntax of this file. enum Syntax { SYNTAX_UNKNOWN = 0, - SYNTAX_PROTO2 = 2, - SYNTAX_PROTO3 = 3, + SYNTAX_PROTO2 = 2, + SYNTAX_PROTO3 = 3, }; Syntax syntax() const; static const char* SyntaxName(Syntax syntax); // Find a top-level message type by name. Returns NULL if not found. - const Descriptor* FindMessageTypeByName(const string& name) const; + const Descriptor* FindMessageTypeByName(const std::string& name) const; // Find a top-level enum type by name. Returns NULL if not found. - const EnumDescriptor* FindEnumTypeByName(const string& name) const; + const EnumDescriptor* FindEnumTypeByName(const std::string& name) const; // Find an enum value defined in any top-level enum by name. Returns NULL if // not found. - const EnumValueDescriptor* FindEnumValueByName(const string& name) const; + const EnumValueDescriptor* FindEnumValueByName(const std::string& name) const; // Find a service definition by name. Returns NULL if not found. - const ServiceDescriptor* FindServiceByName(const string& name) const; + const ServiceDescriptor* FindServiceByName(const std::string& name) const; // Find a top-level extension definition by name. Returns NULL if not found. - const FieldDescriptor* FindExtensionByName(const string& name) const; + const FieldDescriptor* FindExtensionByName(const std::string& name) const; // Similar to FindExtensionByName(), but searches by lowercased-name. See // Descriptor::FindFieldByLowercaseName(). - const FieldDescriptor* FindExtensionByLowercaseName(const string& name) const; + const FieldDescriptor* FindExtensionByLowercaseName( + const std::string& name) const; // Similar to FindExtensionByName(), but searches by camelcased-name. See // Descriptor::FindFieldByCamelcaseName(). - const FieldDescriptor* FindExtensionByCamelcaseName(const string& name) const; + const FieldDescriptor* FindExtensionByCamelcaseName( + const std::string& name) const; // See Descriptor::CopyTo(). // Notes: @@ -1389,10 +1419,10 @@ class LIBPROTOBUF_EXPORT FileDescriptor { void CopyJsonNameTo(FileDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Returns true if this is a placeholder for an unknown file. This will // only be the case if this descriptor comes from a DescriptorPool @@ -1414,10 +1444,10 @@ class LIBPROTOBUF_EXPORT FileDescriptor { private: typedef FileOptions OptionsType; - const string* name_; - const string* package_; + const std::string* name_; + const std::string* package_; const DescriptorPool* pool_; - GoogleOnceDynamic* dependencies_once_; + internal::once_flag* dependencies_once_; static void DependenciesOnceInit(const FileDescriptor* to_init); void InternalDependenciesOnceInit() const; @@ -1438,7 +1468,7 @@ class LIBPROTOBUF_EXPORT FileDescriptor { bool finished_building_; mutable const FileDescriptor** dependencies_; - const string** dependencies_names_; + const std::string** dependencies_names_; int* public_dependencies_; int* weak_dependencies_; Descriptor* message_types_; @@ -1495,7 +1525,7 @@ class LIBPROTOBUF_EXPORT FileDescriptor { // // You can also search for descriptors within a DescriptorPool by name, and // extensions by number. -class LIBPROTOBUF_EXPORT DescriptorPool { +class PROTOBUF_EXPORT DescriptorPool { public: // Create a normal, empty DescriptorPool. DescriptorPool(); @@ -1537,28 +1567,28 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // Find a FileDescriptor in the pool by file name. Returns NULL if not // found. - const FileDescriptor* FindFileByName(const string& name) const; + const FileDescriptor* FindFileByName(const std::string& name) const; // Find the FileDescriptor in the pool which defines the given symbol. // If any of the Find*ByName() methods below would succeed, then this is // equivalent to calling that method and calling the result's file() method. // Otherwise this returns NULL. const FileDescriptor* FindFileContainingSymbol( - const string& symbol_name) const; + const std::string& symbol_name) const; // Looking up descriptors ------------------------------------------ // These find descriptors by fully-qualified name. These will find both // top-level descriptors and nested descriptors. They return NULL if not // found. - const Descriptor* FindMessageTypeByName(const string& name) const; - const FieldDescriptor* FindFieldByName(const string& name) const; - const FieldDescriptor* FindExtensionByName(const string& name) const; - const OneofDescriptor* FindOneofByName(const string& name) const; - const EnumDescriptor* FindEnumTypeByName(const string& name) const; - const EnumValueDescriptor* FindEnumValueByName(const string& name) const; - const ServiceDescriptor* FindServiceByName(const string& name) const; - const MethodDescriptor* FindMethodByName(const string& name) const; + const Descriptor* FindMessageTypeByName(const std::string& name) const; + const FieldDescriptor* FindFieldByName(const std::string& name) const; + const FieldDescriptor* FindExtensionByName(const std::string& name) const; + const OneofDescriptor* FindOneofByName(const std::string& name) const; + const EnumDescriptor* FindEnumTypeByName(const std::string& name) const; + const EnumValueDescriptor* FindEnumValueByName(const std::string& name) const; + const ServiceDescriptor* FindServiceByName(const std::string& name) const; + const MethodDescriptor* FindMethodByName(const std::string& name) const; // Finds an extension of the given type by number. The extendee must be // a member of this DescriptorPool or one of its underlays. @@ -1578,7 +1608,7 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // When converting a FileDescriptorProto to a FileDescriptor, various // errors might be detected in the input. The caller may handle these // programmatically by implementing an ErrorCollector. - class LIBPROTOBUF_EXPORT ErrorCollector { + class PROTOBUF_EXPORT ErrorCollector { public: inline ErrorCollector() {} virtual ~ErrorCollector(); @@ -1587,37 +1617,40 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // This is useful e.g. for mapping the error back to an exact location // in a .proto file. enum ErrorLocation { - NAME, // the symbol name, or the package name for files - NUMBER, // field or extension range number - TYPE, // field type - EXTENDEE, // field extendee - DEFAULT_VALUE, // field default value - INPUT_TYPE, // method input type - OUTPUT_TYPE, // method output type - OPTION_NAME, // name in assignment - OPTION_VALUE, // value in option assignment - OTHER // some other problem + NAME, // the symbol name, or the package name for files + NUMBER, // field or extension range number + TYPE, // field type + EXTENDEE, // field extendee + DEFAULT_VALUE, // field default value + INPUT_TYPE, // method input type + OUTPUT_TYPE, // method output type + OPTION_NAME, // name in assignment + OPTION_VALUE, // value in option assignment + IMPORT, // import error + OTHER // some other problem }; // Reports an error in the FileDescriptorProto. Use this function if the // problem occurred should interrupt building the FileDescriptorProto. virtual void AddError( - const string& filename, // File name in which the error occurred. - const string& element_name, // Full name of the erroneous element. - const Message* descriptor, // Descriptor of the erroneous element. - ErrorLocation location, // One of the location constants, above. - const string& message // Human-readable error message. - ) = 0; + const std::string& filename, // File name in which the error occurred. + const std::string& element_name, // Full name of the erroneous element. + const Message* descriptor, // Descriptor of the erroneous element. + ErrorLocation location, // One of the location constants, above. + const std::string& message // Human-readable error message. + ) = 0; // Reports a warning in the FileDescriptorProto. Use this function if the // problem occurred should NOT interrupt building the FileDescriptorProto. virtual void AddWarning( - const string& /*filename*/, // File name in which the error occurred. - const string& /*element_name*/, // Full name of the erroneous element. - const Message* /*descriptor*/, // Descriptor of the erroneous element. - ErrorLocation /*location*/, // One of the location constants, above. - const string& /*message*/ // Human-readable error message. - ) {} + const std::string& /*filename*/, // File name in which the error + // occurred. + const std::string& /*element_name*/, // Full name of the erroneous + // element. + const Message* /*descriptor*/, // Descriptor of the erroneous element. + ErrorLocation /*location*/, // One of the location constants, above. + const std::string& /*message*/ // Human-readable error message. + ) {} private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ErrorCollector); @@ -1632,8 +1665,7 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // Same as BuildFile() except errors are sent to the given ErrorCollector. const FileDescriptor* BuildFileCollectingErrors( - const FileDescriptorProto& proto, - ErrorCollector* error_collector); + const FileDescriptorProto& proto, ErrorCollector* error_collector); // By default, it is an error if a FileDescriptorProto contains references // to types or other files that are not found in the DescriptorPool (or its @@ -1688,8 +1720,8 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // Called by generated classes at init time to add their descriptors to // generated_pool. Do NOT call this in your own code! filename must be a // permanent string (e.g. a string literal). - static void InternalAddGeneratedFile( - const void* encoded_file_descriptor, int size); + static void InternalAddGeneratedFile(const void* encoded_file_descriptor, + int size); // Disallow [enforce_utf8 = false] in .proto files. void DisallowEnforceUtf8() { disallow_enforce_utf8_ = true; } @@ -1729,12 +1761,11 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // For internal (unit test) use only: Returns true if a FileDescriptor has // been constructed for the given file, false otherwise. Useful for testing // lazy descriptor initialization behavior. - bool InternalIsFileLoaded(const string& filename) const; - + bool InternalIsFileLoaded(const std::string& filename) const; // Add a file to unused_import_track_files_. DescriptorBuilder will log // warnings for those files if there is any unused import. - void AddUnusedImportTrackFile(const string& file_name); + void AddUnusedImportTrackFile(const std::string& file_name); void ClearUnusedImportTrackFiles(); private: @@ -1752,14 +1783,14 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // Return true if the given name is a sub-symbol of any non-package // descriptor that already exists in the descriptor pool. (The full // definition of such types is already known.) - bool IsSubSymbolOfBuiltType(const string& name) const; + bool IsSubSymbolOfBuiltType(const std::string& name) const; // Tries to find something in the fallback database and link in the // corresponding proto file. Returns true if successful, in which case // the caller should search for the thing again. These are declared // const because they are called by (semantically) const methods. - bool TryFindFileInFallbackDatabase(const string& name) const; - bool TryFindSymbolInFallbackDatabase(const string& name) const; + bool TryFindFileInFallbackDatabase(const std::string& name) const; + bool TryFindSymbolInFallbackDatabase(const std::string& name) const; bool TryFindExtensionInFallbackDatabase(const Descriptor* containing_type, int field_number) const; @@ -1767,18 +1798,20 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // fallback_database_. Declared const because it is called by (semantically) // const methods. const FileDescriptor* BuildFileFromDatabase( - const FileDescriptorProto& proto) const; + const FileDescriptorProto& proto) const; // Helper for when lazily_build_dependencies_ is set, can look up a symbol // after the file's descriptor is built, and can build the file where that // symbol is defined if necessary. Will create a placeholder if the type // doesn't exist in the fallback database, or the file doesn't build // successfully. - Symbol CrossLinkOnDemandHelper(const string& name, bool expecting_enum) const; + Symbol CrossLinkOnDemandHelper(const std::string& name, + bool expecting_enum) const; // Create a placeholder FileDescriptor of the specified name - FileDescriptor* NewPlaceholderFile(const string& name) const; - FileDescriptor* NewPlaceholderFileWithMutexHeld(const string& name) const; + FileDescriptor* NewPlaceholderFile(const std::string& name) const; + FileDescriptor* NewPlaceholderFileWithMutexHeld( + const std::string& name) const; enum PlaceholderType { PLACEHOLDER_MESSAGE, @@ -1786,14 +1819,14 @@ class LIBPROTOBUF_EXPORT DescriptorPool { PLACEHOLDER_EXTENDABLE_MESSAGE }; // Create a placeholder Descriptor of the specified name - Symbol NewPlaceholder(const string& name, + Symbol NewPlaceholder(const std::string& name, PlaceholderType placeholder_type) const; - Symbol NewPlaceholderWithMutexHeld(const string& name, + Symbol NewPlaceholderWithMutexHeld(const std::string& name, PlaceholderType placeholder_type) const; // If fallback_database_ is NULL, this is NULL. Otherwise, this is a mutex // which must be locked while accessing tables_. - Mutex* mutex_; + internal::WrappedMutex* mutex_; // See constructor. DescriptorDatabase* fallback_database_; @@ -1810,7 +1843,7 @@ class LIBPROTOBUF_EXPORT DescriptorPool { bool allow_unknown_; bool enforce_weak_; bool disallow_enforce_utf8_; - std::set unused_import_track_files_; + std::set unused_import_track_files_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DescriptorPool); }; @@ -1824,7 +1857,7 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // Strings fields are stored as pointers but returned as const references. #define PROTOBUF_DEFINE_STRING_ACCESSOR(CLASS, FIELD) \ - inline const string& CLASS::FIELD() const { return *FIELD##_; } + inline const std::string& CLASS::FIELD() const { return *FIELD##_; } // Arrays take an index parameter, obviously. #define PROTOBUF_DEFINE_ARRAY_ACCESSOR(CLASS, FIELD, TYPE) \ @@ -1852,8 +1885,7 @@ PROTOBUF_DEFINE_ACCESSOR(Descriptor, extension_range_count, int) PROTOBUF_DEFINE_ACCESSOR(Descriptor, extension_count, int) PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, extension_range, const Descriptor::ExtensionRange*) -PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, extension, - const FieldDescriptor*) +PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, extension, const FieldDescriptor*) PROTOBUF_DEFINE_ACCESSOR(Descriptor, reserved_range_count, int) PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, reserved_range, @@ -1880,13 +1912,13 @@ PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, extension_scope, const Descriptor*) PROTOBUF_DEFINE_OPTIONS_ACCESSOR(FieldDescriptor, FieldOptions) PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, has_default_value, bool) PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, has_json_name, bool) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int32 , int32 ) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int64 , int64 ) +PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int32, int32) +PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int64, int64) PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_uint32, uint32) PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_uint64, uint64) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_float , float ) +PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_float, float) PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_double, double) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_bool , bool ) +PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_bool, bool) PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, default_value_string) PROTOBUF_DEFINE_STRING_ACCESSOR(OneofDescriptor, name) @@ -1964,7 +1996,7 @@ inline bool Descriptor::IsReservedNumber(int number) const { return FindReservedRangeContainingNumber(number) != NULL; } -inline bool Descriptor::IsReservedName(const string& name) const { +inline bool Descriptor::IsReservedName(const std::string& name) const { for (int i = 0; i < reserved_name_count(); i++) { if (name == reserved_name(i)) { return true; @@ -1975,7 +2007,7 @@ inline bool Descriptor::IsReservedName(const string& name) const { // Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because reserved_names_ is actually // an array of pointers rather than the usual array of objects. -inline const string& Descriptor::reserved_name(int index) const { +inline const std::string& Descriptor::reserved_name(int index) const { return *reserved_names_[index]; } @@ -1983,7 +2015,7 @@ inline bool EnumDescriptor::IsReservedNumber(int number) const { return FindReservedRangeContainingNumber(number) != NULL; } -inline bool EnumDescriptor::IsReservedName(const string& name) const { +inline bool EnumDescriptor::IsReservedName(const std::string& name) const { for (int i = 0; i < reserved_name_count(); i++) { if (name == reserved_name(i)) { return true; @@ -1994,13 +2026,13 @@ inline bool EnumDescriptor::IsReservedName(const string& name) const { // Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because reserved_names_ is actually // an array of pointers rather than the usual array of objects. -inline const string& EnumDescriptor::reserved_name(int index) const { +inline const std::string& EnumDescriptor::reserved_name(int index) const { return *reserved_names_[index]; } inline FieldDescriptor::Type FieldDescriptor::type() const { if (type_once_) { - type_once_->Init(&FieldDescriptor::TypeOnceInit, this); + internal::call_once(*type_once_, &FieldDescriptor::TypeOnceInit, this); } return type_; } @@ -2117,14 +2149,11 @@ inline const FileDescriptor* FileDescriptor::public_dependency( return dependency(public_dependencies_[index]); } -inline const FileDescriptor* FileDescriptor::weak_dependency( - int index) const { +inline const FileDescriptor* FileDescriptor::weak_dependency(int index) const { return dependency(weak_dependencies_[index]); } -inline FileDescriptor::Syntax FileDescriptor::syntax() const { - return syntax_; -} +inline FileDescriptor::Syntax FileDescriptor::syntax() const { return syntax_; } // Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because fields_ is actually an array // of pointers rather than the usual array of objects. @@ -2133,6 +2162,8 @@ inline const FieldDescriptor* OneofDescriptor::field(int index) const { } } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_DESCRIPTOR_H__ diff --git a/third_party/protobuf/src/google/protobuf/descriptor.pb.cc b/third_party/protobuf/src/google/protobuf/descriptor.pb.cc index 59b04aba..6924023d 100644 --- a/third_party/protobuf/src/google/protobuf/descriptor.pb.cc +++ b/third_party/protobuf/src/google/protobuf/descriptor.pb.cc @@ -6,657 +6,592 @@ #include #include -#include #include -#include +#include +#include #include #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) - -namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto { -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_DescriptorProto_ReservedRange; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_EnumDescriptorProto_EnumReservedRange; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_GeneratedCodeInfo_Annotation; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceCodeInfo_Location; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_UninterpretedOption_NamePart; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_DescriptorProto_ExtensionRange; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumOptions; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueDescriptorProto; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueOptions; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_ExtensionRangeOptions; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FieldDescriptorProto; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FieldOptions; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FileOptions; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_MessageOptions; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_MethodDescriptorProto; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_MethodOptions; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_OneofDescriptorProto; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_OneofOptions; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_ServiceOptions; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_SourceCodeInfo; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_UninterpretedOption; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_ServiceDescriptorProto; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<3> scc_info_EnumDescriptorProto; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<6> scc_info_DescriptorProto; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto; -} // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto -namespace google { -namespace protobuf { +#include +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<6> scc_info_DescriptorProto_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_DescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_DescriptorProto_ReservedRange_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<3> scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_EnumDescriptorProto_EnumReservedRange_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_EnumOptions_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_EnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_EnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_ExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_FieldOptions_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<6> scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_FileOptions_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_GeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_MessageOptions_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_MethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_MethodOptions_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_OneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_OneofOptions_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<2> scc_info_ServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_ServiceOptions_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_SourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_SourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto; +PROTOBUF_NAMESPACE_OPEN class FileDescriptorSetDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _FileDescriptorSet_default_instance_; class FileDescriptorProtoDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _FileDescriptorProto_default_instance_; class DescriptorProto_ExtensionRangeDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _DescriptorProto_ExtensionRange_default_instance_; class DescriptorProto_ReservedRangeDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _DescriptorProto_ReservedRange_default_instance_; class DescriptorProtoDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _DescriptorProto_default_instance_; class ExtensionRangeOptionsDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _ExtensionRangeOptions_default_instance_; class FieldDescriptorProtoDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _FieldDescriptorProto_default_instance_; class OneofDescriptorProtoDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _OneofDescriptorProto_default_instance_; class EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _EnumDescriptorProto_EnumReservedRange_default_instance_; class EnumDescriptorProtoDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _EnumDescriptorProto_default_instance_; class EnumValueDescriptorProtoDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _EnumValueDescriptorProto_default_instance_; class ServiceDescriptorProtoDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _ServiceDescriptorProto_default_instance_; class MethodDescriptorProtoDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _MethodDescriptorProto_default_instance_; class FileOptionsDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _FileOptions_default_instance_; class MessageOptionsDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _MessageOptions_default_instance_; class FieldOptionsDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _FieldOptions_default_instance_; class OneofOptionsDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _OneofOptions_default_instance_; class EnumOptionsDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _EnumOptions_default_instance_; class EnumValueOptionsDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _EnumValueOptions_default_instance_; class ServiceOptionsDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _ServiceOptions_default_instance_; class MethodOptionsDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _MethodOptions_default_instance_; class UninterpretedOption_NamePartDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _UninterpretedOption_NamePart_default_instance_; class UninterpretedOptionDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _UninterpretedOption_default_instance_; class SourceCodeInfo_LocationDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _SourceCodeInfo_Location_default_instance_; class SourceCodeInfoDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _SourceCodeInfo_default_instance_; class GeneratedCodeInfo_AnnotationDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _GeneratedCodeInfo_Annotation_default_instance_; class GeneratedCodeInfoDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _GeneratedCodeInfo_default_instance_; -} // namespace protobuf -} // namespace google -namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto { -static void InitDefaultsFileDescriptorSet() { +PROTOBUF_NAMESPACE_CLOSE +static void InitDefaultsscc_info_DescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_FileDescriptorSet_default_instance_; - new (ptr) ::google::protobuf::FileDescriptorSet(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_DescriptorProto_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::DescriptorProto(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::FileDescriptorSet::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::DescriptorProto::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FileDescriptorSet = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFileDescriptorSet}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<6> scc_info_DescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 6, InitDefaultsscc_info_DescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_DescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_OneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_MessageOptions_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_DescriptorProto_ReservedRange_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsFileDescriptorProto() { +static void InitDefaultsscc_info_DescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_FileDescriptorProto_default_instance_; - new (ptr) ::google::protobuf::FileDescriptorProto(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_DescriptorProto_ExtensionRange_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::FileDescriptorProto::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 6, InitDefaultsFileDescriptorProto}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base, - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base, - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base, - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base, - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base, - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_DescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_DescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_ExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsDescriptorProto_ExtensionRange() { +static void InitDefaultsscc_info_DescriptorProto_ReservedRange_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_DescriptorProto_ExtensionRange_default_instance_; - new (ptr) ::google::protobuf::DescriptorProto_ExtensionRange(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_DescriptorProto_ReservedRange_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::DescriptorProto_ExtensionRange::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_DescriptorProto_ExtensionRange = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsDescriptorProto_ExtensionRange}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_DescriptorProto_ReservedRange_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_DescriptorProto_ReservedRange_google_2fprotobuf_2fdescriptor_2eproto}, {}}; -static void InitDefaultsDescriptorProto_ReservedRange() { +static void InitDefaultsscc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_DescriptorProto_ReservedRange_default_instance_; - new (ptr) ::google::protobuf::DescriptorProto_ReservedRange(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_EnumDescriptorProto_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::EnumDescriptorProto(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::DescriptorProto_ReservedRange::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::EnumDescriptorProto::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_DescriptorProto_ReservedRange = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDescriptorProto_ReservedRange}, {}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<3> scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsscc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_EnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_EnumOptions_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_EnumDescriptorProto_EnumReservedRange_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsDescriptorProto() { +static void InitDefaultsscc_info_EnumDescriptorProto_EnumReservedRange_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_DescriptorProto_default_instance_; - new (ptr) ::google::protobuf::DescriptorProto(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_EnumDescriptorProto_EnumReservedRange_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::DescriptorProto::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<6> scc_info_DescriptorProto = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 6, InitDefaultsDescriptorProto}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base, - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base, - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ExtensionRange.base, - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base, - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base, - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ReservedRange.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_EnumDescriptorProto_EnumReservedRange_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_EnumDescriptorProto_EnumReservedRange_google_2fprotobuf_2fdescriptor_2eproto}, {}}; -static void InitDefaultsExtensionRangeOptions() { +static void InitDefaultsscc_info_EnumOptions_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_ExtensionRangeOptions_default_instance_; - new (ptr) ::google::protobuf::ExtensionRangeOptions(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_EnumOptions_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::EnumOptions(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::ExtensionRangeOptions::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::EnumOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_ExtensionRangeOptions = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsExtensionRangeOptions}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_EnumOptions_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_EnumOptions_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsFieldDescriptorProto() { +static void InitDefaultsscc_info_EnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_FieldDescriptorProto_default_instance_; - new (ptr) ::google::protobuf::FieldDescriptorProto(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_EnumValueDescriptorProto_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::FieldDescriptorProto::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FieldDescriptorProto = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFieldDescriptorProto}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_EnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_EnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_EnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsOneofDescriptorProto() { +static void InitDefaultsscc_info_EnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_OneofDescriptorProto_default_instance_; - new (ptr) ::google::protobuf::OneofDescriptorProto(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_EnumValueOptions_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::EnumValueOptions(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::OneofDescriptorProto::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::EnumValueOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_OneofDescriptorProto = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsOneofDescriptorProto}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_EnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_EnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsEnumDescriptorProto_EnumReservedRange() { +static void InitDefaultsscc_info_ExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_EnumDescriptorProto_EnumReservedRange_default_instance_; - new (ptr) ::google::protobuf::EnumDescriptorProto_EnumReservedRange(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_ExtensionRangeOptions_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::EnumDescriptorProto_EnumReservedRange::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_EnumDescriptorProto_EnumReservedRange = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsEnumDescriptorProto_EnumReservedRange}, {}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_ExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_ExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsEnumDescriptorProto() { +static void InitDefaultsscc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_EnumDescriptorProto_default_instance_; - new (ptr) ::google::protobuf::EnumDescriptorProto(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_FieldDescriptorProto_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::FieldDescriptorProto(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::EnumDescriptorProto::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::FieldDescriptorProto::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<3> scc_info_EnumDescriptorProto = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsEnumDescriptorProto}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base, - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base, - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto_EnumReservedRange.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_FieldOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsEnumValueDescriptorProto() { +static void InitDefaultsscc_info_FieldOptions_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_EnumValueDescriptorProto_default_instance_; - new (ptr) ::google::protobuf::EnumValueDescriptorProto(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_FieldOptions_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::FieldOptions(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::EnumValueDescriptorProto::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::FieldOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueDescriptorProto = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumValueDescriptorProto}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_FieldOptions_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_FieldOptions_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsServiceDescriptorProto() { +static void InitDefaultsscc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_ServiceDescriptorProto_default_instance_; - new (ptr) ::google::protobuf::ServiceDescriptorProto(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_FileDescriptorProto_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::FileDescriptorProto(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::ServiceDescriptorProto::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::FileDescriptorProto::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<2> scc_info_ServiceDescriptorProto = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsServiceDescriptorProto}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base, - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<6> scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 6, InitDefaultsscc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_DescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_ServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_FileOptions_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_SourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsMethodDescriptorProto() { +static void InitDefaultsscc_info_FileDescriptorSet_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_MethodDescriptorProto_default_instance_; - new (ptr) ::google::protobuf::MethodDescriptorProto(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_FileDescriptorSet_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::FileDescriptorSet(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::MethodDescriptorProto::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::FileDescriptorSet::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MethodDescriptorProto = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethodDescriptorProto}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_FileDescriptorSet_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_FileDescriptorSet_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsFileOptions() { +static void InitDefaultsscc_info_FileOptions_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_FileOptions_default_instance_; - new (ptr) ::google::protobuf::FileOptions(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_FileOptions_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::FileOptions(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::FileOptions::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::FileOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FileOptions = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFileOptions}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_FileOptions_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_FileOptions_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsMessageOptions() { +static void InitDefaultsscc_info_GeneratedCodeInfo_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_MessageOptions_default_instance_; - new (ptr) ::google::protobuf::MessageOptions(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_GeneratedCodeInfo_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::MessageOptions::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MessageOptions = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMessageOptions}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_GeneratedCodeInfo_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_GeneratedCodeInfo_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_GeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsFieldOptions() { +static void InitDefaultsscc_info_GeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_FieldOptions_default_instance_; - new (ptr) ::google::protobuf::FieldOptions(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_GeneratedCodeInfo_Annotation_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::FieldOptions::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FieldOptions = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFieldOptions}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_GeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_GeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto}, {}}; -static void InitDefaultsOneofOptions() { +static void InitDefaultsscc_info_MessageOptions_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_OneofOptions_default_instance_; - new (ptr) ::google::protobuf::OneofOptions(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_MessageOptions_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::MessageOptions(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::OneofOptions::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::MessageOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_OneofOptions = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsOneofOptions}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_MessageOptions_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_MessageOptions_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsEnumOptions() { +static void InitDefaultsscc_info_MethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_EnumOptions_default_instance_; - new (ptr) ::google::protobuf::EnumOptions(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_MethodDescriptorProto_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::MethodDescriptorProto(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::EnumOptions::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::MethodDescriptorProto::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumOptions = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumOptions}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_MethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_MethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_MethodOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsEnumValueOptions() { +static void InitDefaultsscc_info_MethodOptions_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_EnumValueOptions_default_instance_; - new (ptr) ::google::protobuf::EnumValueOptions(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_MethodOptions_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::MethodOptions(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::EnumValueOptions::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::MethodOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueOptions = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumValueOptions}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_MethodOptions_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_MethodOptions_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsServiceOptions() { +static void InitDefaultsscc_info_OneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_ServiceOptions_default_instance_; - new (ptr) ::google::protobuf::ServiceOptions(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_OneofDescriptorProto_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::OneofDescriptorProto(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::ServiceOptions::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::OneofDescriptorProto::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_ServiceOptions = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsServiceOptions}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_OneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_OneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_OneofOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsMethodOptions() { +static void InitDefaultsscc_info_OneofOptions_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_MethodOptions_default_instance_; - new (ptr) ::google::protobuf::MethodOptions(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_OneofOptions_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::OneofOptions(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::MethodOptions::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::OneofOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MethodOptions = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethodOptions}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_OneofOptions_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_OneofOptions_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsUninterpretedOption_NamePart() { +static void InitDefaultsscc_info_ServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_UninterpretedOption_NamePart_default_instance_; - new (ptr) ::google::protobuf::UninterpretedOption_NamePart(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_ServiceDescriptorProto_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::UninterpretedOption_NamePart::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_UninterpretedOption_NamePart = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsUninterpretedOption_NamePart}, {}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<2> scc_info_ServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsscc_info_ServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_MethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_ServiceOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsUninterpretedOption() { +static void InitDefaultsscc_info_ServiceOptions_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_UninterpretedOption_default_instance_; - new (ptr) ::google::protobuf::UninterpretedOption(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_ServiceOptions_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::ServiceOptions(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::UninterpretedOption::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::ServiceOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_UninterpretedOption = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsUninterpretedOption}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption_NamePart.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_ServiceOptions_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_ServiceOptions_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsSourceCodeInfo_Location() { +static void InitDefaultsscc_info_SourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_SourceCodeInfo_Location_default_instance_; - new (ptr) ::google::protobuf::SourceCodeInfo_Location(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_SourceCodeInfo_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::SourceCodeInfo(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::SourceCodeInfo_Location::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::SourceCodeInfo::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_SourceCodeInfo_Location = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsSourceCodeInfo_Location}, {}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_SourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_SourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_SourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsSourceCodeInfo() { +static void InitDefaultsscc_info_SourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_SourceCodeInfo_default_instance_; - new (ptr) ::google::protobuf::SourceCodeInfo(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_SourceCodeInfo_Location_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::SourceCodeInfo::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_SourceCodeInfo = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsSourceCodeInfo}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_SourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_SourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto}, {}}; -static void InitDefaultsGeneratedCodeInfo_Annotation() { +static void InitDefaultsscc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_GeneratedCodeInfo_Annotation_default_instance_; - new (ptr) ::google::protobuf::GeneratedCodeInfo_Annotation(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_UninterpretedOption_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::UninterpretedOption(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::GeneratedCodeInfo_Annotation::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::UninterpretedOption::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_GeneratedCodeInfo_Annotation = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsGeneratedCodeInfo_Annotation}, {}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto}, { + &scc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto.base,}}; -static void InitDefaultsGeneratedCodeInfo() { +static void InitDefaultsscc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_GeneratedCodeInfo_default_instance_; - new (ptr) ::google::protobuf::GeneratedCodeInfo(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_UninterpretedOption_NamePart_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::GeneratedCodeInfo::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_GeneratedCodeInfo = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsGeneratedCodeInfo}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base,}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto}, {}}; -void InitDefaults() { - ::google::protobuf::internal::InitSCC(&scc_info_FileDescriptorSet.base); - ::google::protobuf::internal::InitSCC(&scc_info_FileDescriptorProto.base); - ::google::protobuf::internal::InitSCC(&scc_info_DescriptorProto_ExtensionRange.base); - ::google::protobuf::internal::InitSCC(&scc_info_DescriptorProto_ReservedRange.base); - ::google::protobuf::internal::InitSCC(&scc_info_DescriptorProto.base); - ::google::protobuf::internal::InitSCC(&scc_info_ExtensionRangeOptions.base); - ::google::protobuf::internal::InitSCC(&scc_info_FieldDescriptorProto.base); - ::google::protobuf::internal::InitSCC(&scc_info_OneofDescriptorProto.base); - ::google::protobuf::internal::InitSCC(&scc_info_EnumDescriptorProto_EnumReservedRange.base); - ::google::protobuf::internal::InitSCC(&scc_info_EnumDescriptorProto.base); - ::google::protobuf::internal::InitSCC(&scc_info_EnumValueDescriptorProto.base); - ::google::protobuf::internal::InitSCC(&scc_info_ServiceDescriptorProto.base); - ::google::protobuf::internal::InitSCC(&scc_info_MethodDescriptorProto.base); - ::google::protobuf::internal::InitSCC(&scc_info_FileOptions.base); - ::google::protobuf::internal::InitSCC(&scc_info_MessageOptions.base); - ::google::protobuf::internal::InitSCC(&scc_info_FieldOptions.base); - ::google::protobuf::internal::InitSCC(&scc_info_OneofOptions.base); - ::google::protobuf::internal::InitSCC(&scc_info_EnumOptions.base); - ::google::protobuf::internal::InitSCC(&scc_info_EnumValueOptions.base); - ::google::protobuf::internal::InitSCC(&scc_info_ServiceOptions.base); - ::google::protobuf::internal::InitSCC(&scc_info_MethodOptions.base); - ::google::protobuf::internal::InitSCC(&scc_info_UninterpretedOption_NamePart.base); - ::google::protobuf::internal::InitSCC(&scc_info_UninterpretedOption.base); - ::google::protobuf::internal::InitSCC(&scc_info_SourceCodeInfo_Location.base); - ::google::protobuf::internal::InitSCC(&scc_info_SourceCodeInfo.base); - ::google::protobuf::internal::InitSCC(&scc_info_GeneratedCodeInfo_Annotation.base); - ::google::protobuf::internal::InitSCC(&scc_info_GeneratedCodeInfo.base); -} +static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[27]; +static const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto[6]; +static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fdescriptor_2eproto = nullptr; -::google::protobuf::Metadata file_level_metadata[27]; -const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[6]; - -const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorSet, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorSet, _internal_metadata_), +const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_google_2fprotobuf_2fdescriptor_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorSet, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorSet, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorSet, file_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorSet, file_), ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, package_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, dependency_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, public_dependency_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, weak_dependency_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, message_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, enum_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, service_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, extension_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, options_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, source_code_info_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, syntax_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorProto, name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorProto, package_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorProto, dependency_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorProto, public_dependency_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorProto, weak_dependency_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorProto, message_type_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorProto, enum_type_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorProto, service_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorProto, extension_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorProto, source_code_info_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorProto, syntax_), 0, 1, ~0u, @@ -669,41 +604,41 @@ const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUT 3, 4, 2, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, start_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, end_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, options_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange, start_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange, end_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange, options_), 1, 2, 0, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, start_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, end_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange, start_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange, end_), 0, 1, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, field_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, extension_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, nested_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, enum_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, extension_range_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, oneof_decl_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, options_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, reserved_range_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, reserved_name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto, name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto, field_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto, extension_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto, nested_type_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto, enum_type_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto, extension_range_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto, oneof_decl_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto, reserved_range_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::DescriptorProto, reserved_name_), 0, ~0u, ~0u, @@ -714,28 +649,28 @@ const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUT 1, ~0u, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions, uninterpreted_option_), ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, number_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, label_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, type_name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, extendee_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, default_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, oneof_index_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, json_name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, number_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, label_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, type_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, type_name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, extendee_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, default_value_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, oneof_index_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, json_name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, options_), 0, 6, 8, @@ -746,104 +681,104 @@ const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUT 7, 4, 5, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::OneofDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::OneofDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::OneofDescriptorProto, name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::OneofDescriptorProto, options_), 0, 1, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, start_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, end_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange, start_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange, end_), 0, 1, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, options_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, reserved_range_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, reserved_name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, value_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, reserved_range_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, reserved_name_), 0, ~0u, 1, ~0u, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, number_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto, name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto, number_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto, options_), 0, 2, 1, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, method_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto, name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto, method_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto, options_), 0, ~0u, 1, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, input_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, output_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, options_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, client_streaming_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, server_streaming_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, input_type_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, output_type_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, client_streaming_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, server_streaming_), 0, 1, 2, 3, 4, 5, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_package_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_outer_classname_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_multiple_files_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_generate_equals_and_hash_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_string_check_utf8_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, optimize_for_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, go_package_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, cc_generic_services_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_generic_services_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, py_generic_services_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, php_generic_services_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, deprecated_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, cc_enable_arenas_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, objc_class_prefix_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, csharp_namespace_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, swift_prefix_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, php_class_prefix_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, php_namespace_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, php_metadata_namespace_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, ruby_package_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, java_package_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, java_outer_classname_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, java_multiple_files_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, java_generate_equals_and_hash_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, java_string_check_utf8_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, optimize_for_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, go_package_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, cc_generic_services_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, java_generic_services_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, py_generic_services_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, php_generic_services_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, deprecated_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, cc_enable_arenas_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, objc_class_prefix_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, csharp_namespace_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, swift_prefix_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, php_class_prefix_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, php_namespace_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, php_metadata_namespace_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, ruby_package_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileOptions, uninterpreted_option_), 0, 1, 10, @@ -865,33 +800,33 @@ const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUT 8, 9, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MessageOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MessageOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MessageOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, message_set_wire_format_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, no_standard_descriptor_accessor_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, deprecated_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, map_entry_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MessageOptions, message_set_wire_format_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MessageOptions, no_standard_descriptor_accessor_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MessageOptions, deprecated_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MessageOptions, map_entry_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MessageOptions, uninterpreted_option_), 0, 1, 2, 3, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, ctype_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, packed_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, jstype_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, lazy_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, deprecated_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, weak_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldOptions, ctype_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldOptions, packed_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldOptions, jstype_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldOptions, lazy_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldOptions, deprecated_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldOptions, weak_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldOptions, uninterpreted_option_), 0, 1, 5, @@ -899,74 +834,74 @@ const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUT 3, 4, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::OneofOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::OneofOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::OneofOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::OneofOptions, uninterpreted_option_), ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, allow_alias_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, deprecated_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumOptions, allow_alias_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumOptions, deprecated_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumOptions, uninterpreted_option_), 0, 1, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumValueOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumValueOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumValueOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueOptions, deprecated_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumValueOptions, deprecated_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumValueOptions, uninterpreted_option_), 0, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ServiceOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ServiceOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ServiceOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceOptions, deprecated_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ServiceOptions, deprecated_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ServiceOptions, uninterpreted_option_), 0, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MethodOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MethodOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MethodOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, deprecated_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, idempotency_level_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MethodOptions, deprecated_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MethodOptions, idempotency_level_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::MethodOptions, uninterpreted_option_), 0, 1, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, name_part_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, is_extension_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart, name_part_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart, is_extension_), 0, 1, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::UninterpretedOption, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::UninterpretedOption, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, identifier_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, positive_int_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, negative_int_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, double_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, string_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, aggregate_value_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::UninterpretedOption, name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::UninterpretedOption, identifier_value_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::UninterpretedOption, positive_int_value_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::UninterpretedOption, negative_int_value_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::UninterpretedOption, double_value_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::UninterpretedOption, string_value_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::UninterpretedOption, aggregate_value_), ~0u, 0, 3, @@ -974,304 +909,308 @@ const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUT 5, 1, 2, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, path_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, span_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, leading_comments_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, trailing_comments_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, leading_detached_comments_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, path_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, span_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, leading_comments_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, trailing_comments_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, leading_detached_comments_), ~0u, ~0u, 0, 1, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::SourceCodeInfo, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::SourceCodeInfo, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo, location_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::SourceCodeInfo, location_), ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, path_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, source_file_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, begin_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, end_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, path_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, source_file_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, begin_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, end_), ~0u, 0, 1, 2, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo, annotation_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo, annotation_), ~0u, }; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - { 0, 6, sizeof(::google::protobuf::FileDescriptorSet)}, - { 7, 24, sizeof(::google::protobuf::FileDescriptorProto)}, - { 36, 44, sizeof(::google::protobuf::DescriptorProto_ExtensionRange)}, - { 47, 54, sizeof(::google::protobuf::DescriptorProto_ReservedRange)}, - { 56, 71, sizeof(::google::protobuf::DescriptorProto)}, - { 81, 87, sizeof(::google::protobuf::ExtensionRangeOptions)}, - { 88, 103, sizeof(::google::protobuf::FieldDescriptorProto)}, - { 113, 120, sizeof(::google::protobuf::OneofDescriptorProto)}, - { 122, 129, sizeof(::google::protobuf::EnumDescriptorProto_EnumReservedRange)}, - { 131, 141, sizeof(::google::protobuf::EnumDescriptorProto)}, - { 146, 154, sizeof(::google::protobuf::EnumValueDescriptorProto)}, - { 157, 165, sizeof(::google::protobuf::ServiceDescriptorProto)}, - { 168, 179, sizeof(::google::protobuf::MethodDescriptorProto)}, - { 185, 211, sizeof(::google::protobuf::FileOptions)}, - { 232, 242, sizeof(::google::protobuf::MessageOptions)}, - { 247, 259, sizeof(::google::protobuf::FieldOptions)}, - { 266, 272, sizeof(::google::protobuf::OneofOptions)}, - { 273, 281, sizeof(::google::protobuf::EnumOptions)}, - { 284, 291, sizeof(::google::protobuf::EnumValueOptions)}, - { 293, 300, sizeof(::google::protobuf::ServiceOptions)}, - { 302, 310, sizeof(::google::protobuf::MethodOptions)}, - { 313, 320, sizeof(::google::protobuf::UninterpretedOption_NamePart)}, - { 322, 334, sizeof(::google::protobuf::UninterpretedOption)}, - { 341, 351, sizeof(::google::protobuf::SourceCodeInfo_Location)}, - { 356, 362, sizeof(::google::protobuf::SourceCodeInfo)}, - { 363, 372, sizeof(::google::protobuf::GeneratedCodeInfo_Annotation)}, - { 376, 382, sizeof(::google::protobuf::GeneratedCodeInfo)}, +static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, 6, sizeof(PROTOBUF_NAMESPACE_ID::FileDescriptorSet)}, + { 7, 24, sizeof(PROTOBUF_NAMESPACE_ID::FileDescriptorProto)}, + { 36, 44, sizeof(PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange)}, + { 47, 54, sizeof(PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange)}, + { 56, 71, sizeof(PROTOBUF_NAMESPACE_ID::DescriptorProto)}, + { 81, 87, sizeof(PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions)}, + { 88, 103, sizeof(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto)}, + { 113, 120, sizeof(PROTOBUF_NAMESPACE_ID::OneofDescriptorProto)}, + { 122, 129, sizeof(PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange)}, + { 131, 141, sizeof(PROTOBUF_NAMESPACE_ID::EnumDescriptorProto)}, + { 146, 154, sizeof(PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto)}, + { 157, 165, sizeof(PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto)}, + { 168, 179, sizeof(PROTOBUF_NAMESPACE_ID::MethodDescriptorProto)}, + { 185, 211, sizeof(PROTOBUF_NAMESPACE_ID::FileOptions)}, + { 232, 242, sizeof(PROTOBUF_NAMESPACE_ID::MessageOptions)}, + { 247, 259, sizeof(PROTOBUF_NAMESPACE_ID::FieldOptions)}, + { 266, 272, sizeof(PROTOBUF_NAMESPACE_ID::OneofOptions)}, + { 273, 281, sizeof(PROTOBUF_NAMESPACE_ID::EnumOptions)}, + { 284, 291, sizeof(PROTOBUF_NAMESPACE_ID::EnumValueOptions)}, + { 293, 300, sizeof(PROTOBUF_NAMESPACE_ID::ServiceOptions)}, + { 302, 310, sizeof(PROTOBUF_NAMESPACE_ID::MethodOptions)}, + { 313, 320, sizeof(PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart)}, + { 322, 334, sizeof(PROTOBUF_NAMESPACE_ID::UninterpretedOption)}, + { 341, 351, sizeof(PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location)}, + { 356, 362, sizeof(PROTOBUF_NAMESPACE_ID::SourceCodeInfo)}, + { 363, 372, sizeof(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation)}, + { 376, 382, sizeof(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo)}, }; -static ::google::protobuf::Message const * const file_default_instances[] = { - reinterpret_cast(&::google::protobuf::_FileDescriptorSet_default_instance_), - reinterpret_cast(&::google::protobuf::_FileDescriptorProto_default_instance_), - reinterpret_cast(&::google::protobuf::_DescriptorProto_ExtensionRange_default_instance_), - reinterpret_cast(&::google::protobuf::_DescriptorProto_ReservedRange_default_instance_), - reinterpret_cast(&::google::protobuf::_DescriptorProto_default_instance_), - reinterpret_cast(&::google::protobuf::_ExtensionRangeOptions_default_instance_), - reinterpret_cast(&::google::protobuf::_FieldDescriptorProto_default_instance_), - reinterpret_cast(&::google::protobuf::_OneofDescriptorProto_default_instance_), - reinterpret_cast(&::google::protobuf::_EnumDescriptorProto_EnumReservedRange_default_instance_), - reinterpret_cast(&::google::protobuf::_EnumDescriptorProto_default_instance_), - reinterpret_cast(&::google::protobuf::_EnumValueDescriptorProto_default_instance_), - reinterpret_cast(&::google::protobuf::_ServiceDescriptorProto_default_instance_), - reinterpret_cast(&::google::protobuf::_MethodDescriptorProto_default_instance_), - reinterpret_cast(&::google::protobuf::_FileOptions_default_instance_), - reinterpret_cast(&::google::protobuf::_MessageOptions_default_instance_), - reinterpret_cast(&::google::protobuf::_FieldOptions_default_instance_), - reinterpret_cast(&::google::protobuf::_OneofOptions_default_instance_), - reinterpret_cast(&::google::protobuf::_EnumOptions_default_instance_), - reinterpret_cast(&::google::protobuf::_EnumValueOptions_default_instance_), - reinterpret_cast(&::google::protobuf::_ServiceOptions_default_instance_), - reinterpret_cast(&::google::protobuf::_MethodOptions_default_instance_), - reinterpret_cast(&::google::protobuf::_UninterpretedOption_NamePart_default_instance_), - reinterpret_cast(&::google::protobuf::_UninterpretedOption_default_instance_), - reinterpret_cast(&::google::protobuf::_SourceCodeInfo_Location_default_instance_), - reinterpret_cast(&::google::protobuf::_SourceCodeInfo_default_instance_), - reinterpret_cast(&::google::protobuf::_GeneratedCodeInfo_Annotation_default_instance_), - reinterpret_cast(&::google::protobuf::_GeneratedCodeInfo_default_instance_), +static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_FileDescriptorSet_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_FileDescriptorProto_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_DescriptorProto_ExtensionRange_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_DescriptorProto_ReservedRange_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_DescriptorProto_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_ExtensionRangeOptions_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_FieldDescriptorProto_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_OneofDescriptorProto_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_EnumDescriptorProto_EnumReservedRange_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_EnumDescriptorProto_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_EnumValueDescriptorProto_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_ServiceDescriptorProto_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_MethodDescriptorProto_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_FileOptions_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_MessageOptions_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_FieldOptions_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_OneofOptions_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_EnumOptions_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_EnumValueOptions_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_ServiceOptions_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_MethodOptions_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_UninterpretedOption_NamePart_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_UninterpretedOption_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_SourceCodeInfo_Location_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_SourceCodeInfo_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_GeneratedCodeInfo_Annotation_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_GeneratedCodeInfo_default_instance_), }; -void protobuf_AssignDescriptors() { - AddDescriptors(); - AssignDescriptors( - "google/protobuf/descriptor.proto", schemas, file_default_instances, TableStruct::offsets, - file_level_metadata, file_level_enum_descriptors, NULL); -} +const char descriptor_table_protodef_google_2fprotobuf_2fdescriptor_2eproto[] = + "\n google/protobuf/descriptor.proto\022\017goog" + "le.protobuf\"G\n\021FileDescriptorSet\0222\n\004file" + "\030\001 \003(\0132$.google.protobuf.FileDescriptorP" + "roto\"\333\003\n\023FileDescriptorProto\022\014\n\004name\030\001 \001" + "(\t\022\017\n\007package\030\002 \001(\t\022\022\n\ndependency\030\003 \003(\t\022" + "\031\n\021public_dependency\030\n \003(\005\022\027\n\017weak_depen" + "dency\030\013 \003(\005\0226\n\014message_type\030\004 \003(\0132 .goog" + "le.protobuf.DescriptorProto\0227\n\tenum_type" + "\030\005 \003(\0132$.google.protobuf.EnumDescriptorP" + "roto\0228\n\007service\030\006 \003(\0132\'.google.protobuf." + "ServiceDescriptorProto\0228\n\textension\030\007 \003(" + "\0132%.google.protobuf.FieldDescriptorProto" + "\022-\n\007options\030\010 \001(\0132\034.google.protobuf.File" + "Options\0229\n\020source_code_info\030\t \001(\0132\037.goog" + "le.protobuf.SourceCodeInfo\022\016\n\006syntax\030\014 \001" + "(\t\"\251\005\n\017DescriptorProto\022\014\n\004name\030\001 \001(\t\0224\n\005" + "field\030\002 \003(\0132%.google.protobuf.FieldDescr" + "iptorProto\0228\n\textension\030\006 \003(\0132%.google.p" + "rotobuf.FieldDescriptorProto\0225\n\013nested_t" + "ype\030\003 \003(\0132 .google.protobuf.DescriptorPr" + "oto\0227\n\tenum_type\030\004 \003(\0132$.google.protobuf" + ".EnumDescriptorProto\022H\n\017extension_range\030" + "\005 \003(\0132/.google.protobuf.DescriptorProto." + "ExtensionRange\0229\n\noneof_decl\030\010 \003(\0132%.goo" + "gle.protobuf.OneofDescriptorProto\0220\n\007opt" + "ions\030\007 \001(\0132\037.google.protobuf.MessageOpti" + "ons\022F\n\016reserved_range\030\t \003(\0132..google.pro" + "tobuf.DescriptorProto.ReservedRange\022\025\n\rr" + "eserved_name\030\n \003(\t\032e\n\016ExtensionRange\022\r\n\005" + "start\030\001 \001(\005\022\013\n\003end\030\002 \001(\005\0227\n\007options\030\003 \001(" + "\0132&.google.protobuf.ExtensionRangeOption" + "s\032+\n\rReservedRange\022\r\n\005start\030\001 \001(\005\022\013\n\003end" + "\030\002 \001(\005\"g\n\025ExtensionRangeOptions\022C\n\024unint" + "erpreted_option\030\347\007 \003(\0132$.google.protobuf" + ".UninterpretedOption*\t\010\350\007\020\200\200\200\200\002\"\274\005\n\024Fiel" + "dDescriptorProto\022\014\n\004name\030\001 \001(\t\022\016\n\006number" + "\030\003 \001(\005\022:\n\005label\030\004 \001(\0162+.google.protobuf." + "FieldDescriptorProto.Label\0228\n\004type\030\005 \001(\016" + "2*.google.protobuf.FieldDescriptorProto." + "Type\022\021\n\ttype_name\030\006 \001(\t\022\020\n\010extendee\030\002 \001(" + "\t\022\025\n\rdefault_value\030\007 \001(\t\022\023\n\013oneof_index\030" + "\t \001(\005\022\021\n\tjson_name\030\n \001(\t\022.\n\007options\030\010 \001(" + "\0132\035.google.protobuf.FieldOptions\"\266\002\n\004Typ" + "e\022\017\n\013TYPE_DOUBLE\020\001\022\016\n\nTYPE_FLOAT\020\002\022\016\n\nTY" + "PE_INT64\020\003\022\017\n\013TYPE_UINT64\020\004\022\016\n\nTYPE_INT3" + "2\020\005\022\020\n\014TYPE_FIXED64\020\006\022\020\n\014TYPE_FIXED32\020\007\022" + "\r\n\tTYPE_BOOL\020\010\022\017\n\013TYPE_STRING\020\t\022\016\n\nTYPE_" + "GROUP\020\n\022\020\n\014TYPE_MESSAGE\020\013\022\016\n\nTYPE_BYTES\020" + "\014\022\017\n\013TYPE_UINT32\020\r\022\r\n\tTYPE_ENUM\020\016\022\021\n\rTYP" + "E_SFIXED32\020\017\022\021\n\rTYPE_SFIXED64\020\020\022\017\n\013TYPE_" + "SINT32\020\021\022\017\n\013TYPE_SINT64\020\022\"C\n\005Label\022\022\n\016LA" + "BEL_OPTIONAL\020\001\022\022\n\016LABEL_REQUIRED\020\002\022\022\n\016LA" + "BEL_REPEATED\020\003\"T\n\024OneofDescriptorProto\022\014" + "\n\004name\030\001 \001(\t\022.\n\007options\030\002 \001(\0132\035.google.p" + "rotobuf.OneofOptions\"\244\002\n\023EnumDescriptorP" + "roto\022\014\n\004name\030\001 \001(\t\0228\n\005value\030\002 \003(\0132).goog" + "le.protobuf.EnumValueDescriptorProto\022-\n\007" + "options\030\003 \001(\0132\034.google.protobuf.EnumOpti" + "ons\022N\n\016reserved_range\030\004 \003(\01326.google.pro" + "tobuf.EnumDescriptorProto.EnumReservedRa" + "nge\022\025\n\rreserved_name\030\005 \003(\t\032/\n\021EnumReserv" + "edRange\022\r\n\005start\030\001 \001(\005\022\013\n\003end\030\002 \001(\005\"l\n\030E" + "numValueDescriptorProto\022\014\n\004name\030\001 \001(\t\022\016\n" + "\006number\030\002 \001(\005\0222\n\007options\030\003 \001(\0132!.google." + "protobuf.EnumValueOptions\"\220\001\n\026ServiceDes" + "criptorProto\022\014\n\004name\030\001 \001(\t\0226\n\006method\030\002 \003" + "(\0132&.google.protobuf.MethodDescriptorPro" + "to\0220\n\007options\030\003 \001(\0132\037.google.protobuf.Se" + "rviceOptions\"\301\001\n\025MethodDescriptorProto\022\014" + "\n\004name\030\001 \001(\t\022\022\n\ninput_type\030\002 \001(\t\022\023\n\013outp" + "ut_type\030\003 \001(\t\022/\n\007options\030\004 \001(\0132\036.google." + "protobuf.MethodOptions\022\037\n\020client_streami" + "ng\030\005 \001(\010:\005false\022\037\n\020server_streaming\030\006 \001(" + "\010:\005false\"\246\006\n\013FileOptions\022\024\n\014java_package" + "\030\001 \001(\t\022\034\n\024java_outer_classname\030\010 \001(\t\022\"\n\023" + "java_multiple_files\030\n \001(\010:\005false\022)\n\035java" + "_generate_equals_and_hash\030\024 \001(\010B\002\030\001\022%\n\026j" + "ava_string_check_utf8\030\033 \001(\010:\005false\022F\n\014op" + "timize_for\030\t \001(\0162).google.protobuf.FileO" + "ptions.OptimizeMode:\005SPEED\022\022\n\ngo_package" + "\030\013 \001(\t\022\"\n\023cc_generic_services\030\020 \001(\010:\005fal" + "se\022$\n\025java_generic_services\030\021 \001(\010:\005false" + "\022\"\n\023py_generic_services\030\022 \001(\010:\005false\022#\n\024" + "php_generic_services\030* \001(\010:\005false\022\031\n\ndep" + "recated\030\027 \001(\010:\005false\022\037\n\020cc_enable_arenas" + "\030\037 \001(\010:\005false\022\031\n\021objc_class_prefix\030$ \001(\t" + "\022\030\n\020csharp_namespace\030% \001(\t\022\024\n\014swift_pref" + "ix\030\' \001(\t\022\030\n\020php_class_prefix\030( \001(\t\022\025\n\rph" + "p_namespace\030) \001(\t\022\036\n\026php_metadata_namesp" + "ace\030, \001(\t\022\024\n\014ruby_package\030- \001(\t\022C\n\024unint" + "erpreted_option\030\347\007 \003(\0132$.google.protobuf" + ".UninterpretedOption\":\n\014OptimizeMode\022\t\n\005" + "SPEED\020\001\022\r\n\tCODE_SIZE\020\002\022\020\n\014LITE_RUNTIME\020\003" + "*\t\010\350\007\020\200\200\200\200\002J\004\010&\020\'\"\362\001\n\016MessageOptions\022&\n\027" + "message_set_wire_format\030\001 \001(\010:\005false\022.\n\037" + "no_standard_descriptor_accessor\030\002 \001(\010:\005f" + "alse\022\031\n\ndeprecated\030\003 \001(\010:\005false\022\021\n\tmap_e" + "ntry\030\007 \001(\010\022C\n\024uninterpreted_option\030\347\007 \003(" + "\0132$.google.protobuf.UninterpretedOption*" + "\t\010\350\007\020\200\200\200\200\002J\004\010\010\020\tJ\004\010\t\020\n\"\236\003\n\014FieldOptions\022" + ":\n\005ctype\030\001 \001(\0162#.google.protobuf.FieldOp" + "tions.CType:\006STRING\022\016\n\006packed\030\002 \001(\010\022\?\n\006j" + "stype\030\006 \001(\0162$.google.protobuf.FieldOptio" + "ns.JSType:\tJS_NORMAL\022\023\n\004lazy\030\005 \001(\010:\005fals" + "e\022\031\n\ndeprecated\030\003 \001(\010:\005false\022\023\n\004weak\030\n \001" + "(\010:\005false\022C\n\024uninterpreted_option\030\347\007 \003(\013" + "2$.google.protobuf.UninterpretedOption\"/" + "\n\005CType\022\n\n\006STRING\020\000\022\010\n\004CORD\020\001\022\020\n\014STRING_" + "PIECE\020\002\"5\n\006JSType\022\r\n\tJS_NORMAL\020\000\022\r\n\tJS_S" + "TRING\020\001\022\r\n\tJS_NUMBER\020\002*\t\010\350\007\020\200\200\200\200\002J\004\010\004\020\005\"" + "^\n\014OneofOptions\022C\n\024uninterpreted_option\030" + "\347\007 \003(\0132$.google.protobuf.UninterpretedOp" + "tion*\t\010\350\007\020\200\200\200\200\002\"\223\001\n\013EnumOptions\022\023\n\013allow" + "_alias\030\002 \001(\010\022\031\n\ndeprecated\030\003 \001(\010:\005false\022" + "C\n\024uninterpreted_option\030\347\007 \003(\0132$.google." + "protobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002J" + "\004\010\005\020\006\"}\n\020EnumValueOptions\022\031\n\ndeprecated\030" + "\001 \001(\010:\005false\022C\n\024uninterpreted_option\030\347\007 " + "\003(\0132$.google.protobuf.UninterpretedOptio" + "n*\t\010\350\007\020\200\200\200\200\002\"{\n\016ServiceOptions\022\031\n\ndeprec" + "ated\030! \001(\010:\005false\022C\n\024uninterpreted_optio" + "n\030\347\007 \003(\0132$.google.protobuf.Uninterpreted" + "Option*\t\010\350\007\020\200\200\200\200\002\"\255\002\n\rMethodOptions\022\031\n\nd" + "eprecated\030! \001(\010:\005false\022_\n\021idempotency_le" + "vel\030\" \001(\0162/.google.protobuf.MethodOption" + "s.IdempotencyLevel:\023IDEMPOTENCY_UNKNOWN\022" + "C\n\024uninterpreted_option\030\347\007 \003(\0132$.google." + "protobuf.UninterpretedOption\"P\n\020Idempote" + "ncyLevel\022\027\n\023IDEMPOTENCY_UNKNOWN\020\000\022\023\n\017NO_" + "SIDE_EFFECTS\020\001\022\016\n\nIDEMPOTENT\020\002*\t\010\350\007\020\200\200\200\200" + "\002\"\236\002\n\023UninterpretedOption\022;\n\004name\030\002 \003(\0132" + "-.google.protobuf.UninterpretedOption.Na" + "mePart\022\030\n\020identifier_value\030\003 \001(\t\022\032\n\022posi" + "tive_int_value\030\004 \001(\004\022\032\n\022negative_int_val" + "ue\030\005 \001(\003\022\024\n\014double_value\030\006 \001(\001\022\024\n\014string" + "_value\030\007 \001(\014\022\027\n\017aggregate_value\030\010 \001(\t\0323\n" + "\010NamePart\022\021\n\tname_part\030\001 \002(\t\022\024\n\014is_exten" + "sion\030\002 \002(\010\"\325\001\n\016SourceCodeInfo\022:\n\010locatio" + "n\030\001 \003(\0132(.google.protobuf.SourceCodeInfo" + ".Location\032\206\001\n\010Location\022\020\n\004path\030\001 \003(\005B\002\020\001" + "\022\020\n\004span\030\002 \003(\005B\002\020\001\022\030\n\020leading_comments\030\003" + " \001(\t\022\031\n\021trailing_comments\030\004 \001(\t\022!\n\031leadi" + "ng_detached_comments\030\006 \003(\t\"\247\001\n\021Generated" + "CodeInfo\022A\n\nannotation\030\001 \003(\0132-.google.pr" + "otobuf.GeneratedCodeInfo.Annotation\032O\n\nA" + "nnotation\022\020\n\004path\030\001 \003(\005B\002\020\001\022\023\n\013source_fi" + "le\030\002 \001(\t\022\r\n\005begin\030\003 \001(\005\022\013\n\003end\030\004 \001(\005B\217\001\n" + "\023com.google.protobufB\020DescriptorProtosH\001" + "Z>github.com/golang/protobuf/protoc-gen-" + "go/descriptor;descriptor\370\001\001\242\002\003GPB\252\002\032Goog" + "le.Protobuf.Reflection" + ; +static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_google_2fprotobuf_2fdescriptor_2eproto_deps[1] = { +}; +static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_google_2fprotobuf_2fdescriptor_2eproto_sccs[27] = { + &scc_info_DescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_DescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_DescriptorProto_ReservedRange_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_EnumDescriptorProto_EnumReservedRange_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_EnumOptions_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_EnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_EnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_ExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_FieldOptions_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_FileDescriptorSet_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_FileOptions_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_GeneratedCodeInfo_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_GeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_MessageOptions_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_MethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_MethodOptions_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_OneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_OneofOptions_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_ServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_ServiceOptions_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_SourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_SourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base, + &scc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto.base, +}; +static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fdescriptor_2eproto_once; +static bool descriptor_table_google_2fprotobuf_2fdescriptor_2eproto_initialized = false; +const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fdescriptor_2eproto = { + &descriptor_table_google_2fprotobuf_2fdescriptor_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fdescriptor_2eproto, "google/protobuf/descriptor.proto", 6022, + &descriptor_table_google_2fprotobuf_2fdescriptor_2eproto_once, descriptor_table_google_2fprotobuf_2fdescriptor_2eproto_sccs, descriptor_table_google_2fprotobuf_2fdescriptor_2eproto_deps, 27, 0, + schemas, file_default_instances, TableStruct_google_2fprotobuf_2fdescriptor_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto, 27, file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto, file_level_service_descriptors_google_2fprotobuf_2fdescriptor_2eproto, +}; -void protobuf_AssignDescriptorsOnce() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); -} - -void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 27); -} - -void AddDescriptorsImpl() { - InitDefaults(); - static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - "\n google/protobuf/descriptor.proto\022\017goog" - "le.protobuf\"G\n\021FileDescriptorSet\0222\n\004file" - "\030\001 \003(\0132$.google.protobuf.FileDescriptorP" - "roto\"\333\003\n\023FileDescriptorProto\022\014\n\004name\030\001 \001" - "(\t\022\017\n\007package\030\002 \001(\t\022\022\n\ndependency\030\003 \003(\t\022" - "\031\n\021public_dependency\030\n \003(\005\022\027\n\017weak_depen" - "dency\030\013 \003(\005\0226\n\014message_type\030\004 \003(\0132 .goog" - "le.protobuf.DescriptorProto\0227\n\tenum_type" - "\030\005 \003(\0132$.google.protobuf.EnumDescriptorP" - "roto\0228\n\007service\030\006 \003(\0132\'.google.protobuf." - "ServiceDescriptorProto\0228\n\textension\030\007 \003(" - "\0132%.google.protobuf.FieldDescriptorProto" - "\022-\n\007options\030\010 \001(\0132\034.google.protobuf.File" - "Options\0229\n\020source_code_info\030\t \001(\0132\037.goog" - "le.protobuf.SourceCodeInfo\022\016\n\006syntax\030\014 \001" - "(\t\"\251\005\n\017DescriptorProto\022\014\n\004name\030\001 \001(\t\0224\n\005" - "field\030\002 \003(\0132%.google.protobuf.FieldDescr" - "iptorProto\0228\n\textension\030\006 \003(\0132%.google.p" - "rotobuf.FieldDescriptorProto\0225\n\013nested_t" - "ype\030\003 \003(\0132 .google.protobuf.DescriptorPr" - "oto\0227\n\tenum_type\030\004 \003(\0132$.google.protobuf" - ".EnumDescriptorProto\022H\n\017extension_range\030" - "\005 \003(\0132/.google.protobuf.DescriptorProto." - "ExtensionRange\0229\n\noneof_decl\030\010 \003(\0132%.goo" - "gle.protobuf.OneofDescriptorProto\0220\n\007opt" - "ions\030\007 \001(\0132\037.google.protobuf.MessageOpti" - "ons\022F\n\016reserved_range\030\t \003(\0132..google.pro" - "tobuf.DescriptorProto.ReservedRange\022\025\n\rr" - "eserved_name\030\n \003(\t\032e\n\016ExtensionRange\022\r\n\005" - "start\030\001 \001(\005\022\013\n\003end\030\002 \001(\005\0227\n\007options\030\003 \001(" - "\0132&.google.protobuf.ExtensionRangeOption" - "s\032+\n\rReservedRange\022\r\n\005start\030\001 \001(\005\022\013\n\003end" - "\030\002 \001(\005\"g\n\025ExtensionRangeOptions\022C\n\024unint" - "erpreted_option\030\347\007 \003(\0132$.google.protobuf" - ".UninterpretedOption*\t\010\350\007\020\200\200\200\200\002\"\274\005\n\024Fiel" - "dDescriptorProto\022\014\n\004name\030\001 \001(\t\022\016\n\006number" - "\030\003 \001(\005\022:\n\005label\030\004 \001(\0162+.google.protobuf." - "FieldDescriptorProto.Label\0228\n\004type\030\005 \001(\016" - "2*.google.protobuf.FieldDescriptorProto." - "Type\022\021\n\ttype_name\030\006 \001(\t\022\020\n\010extendee\030\002 \001(" - "\t\022\025\n\rdefault_value\030\007 \001(\t\022\023\n\013oneof_index\030" - "\t \001(\005\022\021\n\tjson_name\030\n \001(\t\022.\n\007options\030\010 \001(" - "\0132\035.google.protobuf.FieldOptions\"\266\002\n\004Typ" - "e\022\017\n\013TYPE_DOUBLE\020\001\022\016\n\nTYPE_FLOAT\020\002\022\016\n\nTY" - "PE_INT64\020\003\022\017\n\013TYPE_UINT64\020\004\022\016\n\nTYPE_INT3" - "2\020\005\022\020\n\014TYPE_FIXED64\020\006\022\020\n\014TYPE_FIXED32\020\007\022" - "\r\n\tTYPE_BOOL\020\010\022\017\n\013TYPE_STRING\020\t\022\016\n\nTYPE_" - "GROUP\020\n\022\020\n\014TYPE_MESSAGE\020\013\022\016\n\nTYPE_BYTES\020" - "\014\022\017\n\013TYPE_UINT32\020\r\022\r\n\tTYPE_ENUM\020\016\022\021\n\rTYP" - "E_SFIXED32\020\017\022\021\n\rTYPE_SFIXED64\020\020\022\017\n\013TYPE_" - "SINT32\020\021\022\017\n\013TYPE_SINT64\020\022\"C\n\005Label\022\022\n\016LA" - "BEL_OPTIONAL\020\001\022\022\n\016LABEL_REQUIRED\020\002\022\022\n\016LA" - "BEL_REPEATED\020\003\"T\n\024OneofDescriptorProto\022\014" - "\n\004name\030\001 \001(\t\022.\n\007options\030\002 \001(\0132\035.google.p" - "rotobuf.OneofOptions\"\244\002\n\023EnumDescriptorP" - "roto\022\014\n\004name\030\001 \001(\t\0228\n\005value\030\002 \003(\0132).goog" - "le.protobuf.EnumValueDescriptorProto\022-\n\007" - "options\030\003 \001(\0132\034.google.protobuf.EnumOpti" - "ons\022N\n\016reserved_range\030\004 \003(\01326.google.pro" - "tobuf.EnumDescriptorProto.EnumReservedRa" - "nge\022\025\n\rreserved_name\030\005 \003(\t\032/\n\021EnumReserv" - "edRange\022\r\n\005start\030\001 \001(\005\022\013\n\003end\030\002 \001(\005\"l\n\030E" - "numValueDescriptorProto\022\014\n\004name\030\001 \001(\t\022\016\n" - "\006number\030\002 \001(\005\0222\n\007options\030\003 \001(\0132!.google." - "protobuf.EnumValueOptions\"\220\001\n\026ServiceDes" - "criptorProto\022\014\n\004name\030\001 \001(\t\0226\n\006method\030\002 \003" - "(\0132&.google.protobuf.MethodDescriptorPro" - "to\0220\n\007options\030\003 \001(\0132\037.google.protobuf.Se" - "rviceOptions\"\301\001\n\025MethodDescriptorProto\022\014" - "\n\004name\030\001 \001(\t\022\022\n\ninput_type\030\002 \001(\t\022\023\n\013outp" - "ut_type\030\003 \001(\t\022/\n\007options\030\004 \001(\0132\036.google." - "protobuf.MethodOptions\022\037\n\020client_streami" - "ng\030\005 \001(\010:\005false\022\037\n\020server_streaming\030\006 \001(" - "\010:\005false\"\246\006\n\013FileOptions\022\024\n\014java_package" - "\030\001 \001(\t\022\034\n\024java_outer_classname\030\010 \001(\t\022\"\n\023" - "java_multiple_files\030\n \001(\010:\005false\022)\n\035java" - "_generate_equals_and_hash\030\024 \001(\010B\002\030\001\022%\n\026j" - "ava_string_check_utf8\030\033 \001(\010:\005false\022F\n\014op" - "timize_for\030\t \001(\0162).google.protobuf.FileO" - "ptions.OptimizeMode:\005SPEED\022\022\n\ngo_package" - "\030\013 \001(\t\022\"\n\023cc_generic_services\030\020 \001(\010:\005fal" - "se\022$\n\025java_generic_services\030\021 \001(\010:\005false" - "\022\"\n\023py_generic_services\030\022 \001(\010:\005false\022#\n\024" - "php_generic_services\030* \001(\010:\005false\022\031\n\ndep" - "recated\030\027 \001(\010:\005false\022\037\n\020cc_enable_arenas" - "\030\037 \001(\010:\005false\022\031\n\021objc_class_prefix\030$ \001(\t" - "\022\030\n\020csharp_namespace\030% \001(\t\022\024\n\014swift_pref" - "ix\030\' \001(\t\022\030\n\020php_class_prefix\030( \001(\t\022\025\n\rph" - "p_namespace\030) \001(\t\022\036\n\026php_metadata_namesp" - "ace\030, \001(\t\022\024\n\014ruby_package\030- \001(\t\022C\n\024unint" - "erpreted_option\030\347\007 \003(\0132$.google.protobuf" - ".UninterpretedOption\":\n\014OptimizeMode\022\t\n\005" - "SPEED\020\001\022\r\n\tCODE_SIZE\020\002\022\020\n\014LITE_RUNTIME\020\003" - "*\t\010\350\007\020\200\200\200\200\002J\004\010&\020\'\"\362\001\n\016MessageOptions\022&\n\027" - "message_set_wire_format\030\001 \001(\010:\005false\022.\n\037" - "no_standard_descriptor_accessor\030\002 \001(\010:\005f" - "alse\022\031\n\ndeprecated\030\003 \001(\010:\005false\022\021\n\tmap_e" - "ntry\030\007 \001(\010\022C\n\024uninterpreted_option\030\347\007 \003(" - "\0132$.google.protobuf.UninterpretedOption*" - "\t\010\350\007\020\200\200\200\200\002J\004\010\010\020\tJ\004\010\t\020\n\"\236\003\n\014FieldOptions\022" - ":\n\005ctype\030\001 \001(\0162#.google.protobuf.FieldOp" - "tions.CType:\006STRING\022\016\n\006packed\030\002 \001(\010\022\?\n\006j" - "stype\030\006 \001(\0162$.google.protobuf.FieldOptio" - "ns.JSType:\tJS_NORMAL\022\023\n\004lazy\030\005 \001(\010:\005fals" - "e\022\031\n\ndeprecated\030\003 \001(\010:\005false\022\023\n\004weak\030\n \001" - "(\010:\005false\022C\n\024uninterpreted_option\030\347\007 \003(\013" - "2$.google.protobuf.UninterpretedOption\"/" - "\n\005CType\022\n\n\006STRING\020\000\022\010\n\004CORD\020\001\022\020\n\014STRING_" - "PIECE\020\002\"5\n\006JSType\022\r\n\tJS_NORMAL\020\000\022\r\n\tJS_S" - "TRING\020\001\022\r\n\tJS_NUMBER\020\002*\t\010\350\007\020\200\200\200\200\002J\004\010\004\020\005\"" - "^\n\014OneofOptions\022C\n\024uninterpreted_option\030" - "\347\007 \003(\0132$.google.protobuf.UninterpretedOp" - "tion*\t\010\350\007\020\200\200\200\200\002\"\223\001\n\013EnumOptions\022\023\n\013allow" - "_alias\030\002 \001(\010\022\031\n\ndeprecated\030\003 \001(\010:\005false\022" - "C\n\024uninterpreted_option\030\347\007 \003(\0132$.google." - "protobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002J" - "\004\010\005\020\006\"}\n\020EnumValueOptions\022\031\n\ndeprecated\030" - "\001 \001(\010:\005false\022C\n\024uninterpreted_option\030\347\007 " - "\003(\0132$.google.protobuf.UninterpretedOptio" - "n*\t\010\350\007\020\200\200\200\200\002\"{\n\016ServiceOptions\022\031\n\ndeprec" - "ated\030! \001(\010:\005false\022C\n\024uninterpreted_optio" - "n\030\347\007 \003(\0132$.google.protobuf.Uninterpreted" - "Option*\t\010\350\007\020\200\200\200\200\002\"\255\002\n\rMethodOptions\022\031\n\nd" - "eprecated\030! \001(\010:\005false\022_\n\021idempotency_le" - "vel\030\" \001(\0162/.google.protobuf.MethodOption" - "s.IdempotencyLevel:\023IDEMPOTENCY_UNKNOWN\022" - "C\n\024uninterpreted_option\030\347\007 \003(\0132$.google." - "protobuf.UninterpretedOption\"P\n\020Idempote" - "ncyLevel\022\027\n\023IDEMPOTENCY_UNKNOWN\020\000\022\023\n\017NO_" - "SIDE_EFFECTS\020\001\022\016\n\nIDEMPOTENT\020\002*\t\010\350\007\020\200\200\200\200" - "\002\"\236\002\n\023UninterpretedOption\022;\n\004name\030\002 \003(\0132" - "-.google.protobuf.UninterpretedOption.Na" - "mePart\022\030\n\020identifier_value\030\003 \001(\t\022\032\n\022posi" - "tive_int_value\030\004 \001(\004\022\032\n\022negative_int_val" - "ue\030\005 \001(\003\022\024\n\014double_value\030\006 \001(\001\022\024\n\014string" - "_value\030\007 \001(\014\022\027\n\017aggregate_value\030\010 \001(\t\0323\n" - "\010NamePart\022\021\n\tname_part\030\001 \002(\t\022\024\n\014is_exten" - "sion\030\002 \002(\010\"\325\001\n\016SourceCodeInfo\022:\n\010locatio" - "n\030\001 \003(\0132(.google.protobuf.SourceCodeInfo" - ".Location\032\206\001\n\010Location\022\020\n\004path\030\001 \003(\005B\002\020\001" - "\022\020\n\004span\030\002 \003(\005B\002\020\001\022\030\n\020leading_comments\030\003" - " \001(\t\022\031\n\021trailing_comments\030\004 \001(\t\022!\n\031leadi" - "ng_detached_comments\030\006 \003(\t\"\247\001\n\021Generated" - "CodeInfo\022A\n\nannotation\030\001 \003(\0132-.google.pr" - "otobuf.GeneratedCodeInfo.Annotation\032O\n\nA" - "nnotation\022\020\n\004path\030\001 \003(\005B\002\020\001\022\023\n\013source_fi" - "le\030\002 \001(\t\022\r\n\005begin\030\003 \001(\005\022\013\n\003end\030\004 \001(\005B\217\001\n" - "\023com.google.protobufB\020DescriptorProtosH\001" - "Z>github.com/golang/protobuf/protoc-gen-" - "go/descriptor;descriptor\370\001\001\242\002\003GPB\252\002\032Goog" - "le.Protobuf.Reflection" - }; - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - descriptor, 6022); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "google/protobuf/descriptor.proto", &protobuf_RegisterTypes); -} - -void AddDescriptors() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); -} -// Force AddDescriptors() to be called at dynamic initialization time. -struct StaticDescriptorInitializer { - StaticDescriptorInitializer() { - AddDescriptors(); - } -} static_descriptor_initializer; -} // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto -namespace google { -namespace protobuf { -const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Type_descriptor() { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[0]; +// Force running AddDescriptors() at dynamic initialization time. +static bool dynamic_init_dummy_google_2fprotobuf_2fdescriptor_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fdescriptor_2eproto), true); +PROTOBUF_NAMESPACE_OPEN +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* FieldDescriptorProto_Type_descriptor() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto[0]; } bool FieldDescriptorProto_Type_IsValid(int value) { switch (value) { @@ -1299,32 +1238,32 @@ bool FieldDescriptorProto_Type_IsValid(int value) { } } -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_DOUBLE; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_FLOAT; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_INT64; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_UINT64; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_INT32; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_FIXED64; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_FIXED32; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_BOOL; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_STRING; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_GROUP; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_MESSAGE; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_BYTES; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_UINT32; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_ENUM; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_SFIXED32; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_SFIXED64; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_SINT32; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_SINT64; -const FieldDescriptorProto_Type FieldDescriptorProto::Type_MIN; -const FieldDescriptorProto_Type FieldDescriptorProto::Type_MAX; -const int FieldDescriptorProto::Type_ARRAYSIZE; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 -const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Label_descriptor() { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[1]; +#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900) +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_DOUBLE; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_FLOAT; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_INT64; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_UINT64; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_INT32; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_FIXED64; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_FIXED32; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_BOOL; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_STRING; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_GROUP; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_MESSAGE; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_BYTES; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_UINT32; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_ENUM; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_SFIXED32; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_SFIXED64; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_SINT32; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::TYPE_SINT64; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::Type_MIN; +constexpr FieldDescriptorProto_Type FieldDescriptorProto::Type_MAX; +constexpr int FieldDescriptorProto::Type_ARRAYSIZE; +#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900) +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* FieldDescriptorProto_Label_descriptor() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto[1]; } bool FieldDescriptorProto_Label_IsValid(int value) { switch (value) { @@ -1337,17 +1276,17 @@ bool FieldDescriptorProto_Label_IsValid(int value) { } } -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const FieldDescriptorProto_Label FieldDescriptorProto::LABEL_OPTIONAL; -const FieldDescriptorProto_Label FieldDescriptorProto::LABEL_REQUIRED; -const FieldDescriptorProto_Label FieldDescriptorProto::LABEL_REPEATED; -const FieldDescriptorProto_Label FieldDescriptorProto::Label_MIN; -const FieldDescriptorProto_Label FieldDescriptorProto::Label_MAX; -const int FieldDescriptorProto::Label_ARRAYSIZE; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 -const ::google::protobuf::EnumDescriptor* FileOptions_OptimizeMode_descriptor() { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[2]; +#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900) +constexpr FieldDescriptorProto_Label FieldDescriptorProto::LABEL_OPTIONAL; +constexpr FieldDescriptorProto_Label FieldDescriptorProto::LABEL_REQUIRED; +constexpr FieldDescriptorProto_Label FieldDescriptorProto::LABEL_REPEATED; +constexpr FieldDescriptorProto_Label FieldDescriptorProto::Label_MIN; +constexpr FieldDescriptorProto_Label FieldDescriptorProto::Label_MAX; +constexpr int FieldDescriptorProto::Label_ARRAYSIZE; +#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900) +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* FileOptions_OptimizeMode_descriptor() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto[2]; } bool FileOptions_OptimizeMode_IsValid(int value) { switch (value) { @@ -1360,17 +1299,17 @@ bool FileOptions_OptimizeMode_IsValid(int value) { } } -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const FileOptions_OptimizeMode FileOptions::SPEED; -const FileOptions_OptimizeMode FileOptions::CODE_SIZE; -const FileOptions_OptimizeMode FileOptions::LITE_RUNTIME; -const FileOptions_OptimizeMode FileOptions::OptimizeMode_MIN; -const FileOptions_OptimizeMode FileOptions::OptimizeMode_MAX; -const int FileOptions::OptimizeMode_ARRAYSIZE; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 -const ::google::protobuf::EnumDescriptor* FieldOptions_CType_descriptor() { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[3]; +#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900) +constexpr FileOptions_OptimizeMode FileOptions::SPEED; +constexpr FileOptions_OptimizeMode FileOptions::CODE_SIZE; +constexpr FileOptions_OptimizeMode FileOptions::LITE_RUNTIME; +constexpr FileOptions_OptimizeMode FileOptions::OptimizeMode_MIN; +constexpr FileOptions_OptimizeMode FileOptions::OptimizeMode_MAX; +constexpr int FileOptions::OptimizeMode_ARRAYSIZE; +#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900) +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* FieldOptions_CType_descriptor() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto[3]; } bool FieldOptions_CType_IsValid(int value) { switch (value) { @@ -1383,17 +1322,17 @@ bool FieldOptions_CType_IsValid(int value) { } } -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const FieldOptions_CType FieldOptions::STRING; -const FieldOptions_CType FieldOptions::CORD; -const FieldOptions_CType FieldOptions::STRING_PIECE; -const FieldOptions_CType FieldOptions::CType_MIN; -const FieldOptions_CType FieldOptions::CType_MAX; -const int FieldOptions::CType_ARRAYSIZE; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 -const ::google::protobuf::EnumDescriptor* FieldOptions_JSType_descriptor() { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[4]; +#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900) +constexpr FieldOptions_CType FieldOptions::STRING; +constexpr FieldOptions_CType FieldOptions::CORD; +constexpr FieldOptions_CType FieldOptions::STRING_PIECE; +constexpr FieldOptions_CType FieldOptions::CType_MIN; +constexpr FieldOptions_CType FieldOptions::CType_MAX; +constexpr int FieldOptions::CType_ARRAYSIZE; +#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900) +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* FieldOptions_JSType_descriptor() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto[4]; } bool FieldOptions_JSType_IsValid(int value) { switch (value) { @@ -1406,17 +1345,17 @@ bool FieldOptions_JSType_IsValid(int value) { } } -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const FieldOptions_JSType FieldOptions::JS_NORMAL; -const FieldOptions_JSType FieldOptions::JS_STRING; -const FieldOptions_JSType FieldOptions::JS_NUMBER; -const FieldOptions_JSType FieldOptions::JSType_MIN; -const FieldOptions_JSType FieldOptions::JSType_MAX; -const int FieldOptions::JSType_ARRAYSIZE; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 -const ::google::protobuf::EnumDescriptor* MethodOptions_IdempotencyLevel_descriptor() { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[5]; +#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900) +constexpr FieldOptions_JSType FieldOptions::JS_NORMAL; +constexpr FieldOptions_JSType FieldOptions::JS_STRING; +constexpr FieldOptions_JSType FieldOptions::JS_NUMBER; +constexpr FieldOptions_JSType FieldOptions::JSType_MIN; +constexpr FieldOptions_JSType FieldOptions::JSType_MAX; +constexpr int FieldOptions::JSType_ARRAYSIZE; +#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900) +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* MethodOptions_IdempotencyLevel_descriptor() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto[5]; } bool MethodOptions_IdempotencyLevel_IsValid(int value) { switch (value) { @@ -1429,42 +1368,44 @@ bool MethodOptions_IdempotencyLevel_IsValid(int value) { } } -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const MethodOptions_IdempotencyLevel MethodOptions::IDEMPOTENCY_UNKNOWN; -const MethodOptions_IdempotencyLevel MethodOptions::NO_SIDE_EFFECTS; -const MethodOptions_IdempotencyLevel MethodOptions::IDEMPOTENT; -const MethodOptions_IdempotencyLevel MethodOptions::IdempotencyLevel_MIN; -const MethodOptions_IdempotencyLevel MethodOptions::IdempotencyLevel_MAX; -const int MethodOptions::IdempotencyLevel_ARRAYSIZE; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 +#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900) +constexpr MethodOptions_IdempotencyLevel MethodOptions::IDEMPOTENCY_UNKNOWN; +constexpr MethodOptions_IdempotencyLevel MethodOptions::NO_SIDE_EFFECTS; +constexpr MethodOptions_IdempotencyLevel MethodOptions::IDEMPOTENT; +constexpr MethodOptions_IdempotencyLevel MethodOptions::IdempotencyLevel_MIN; +constexpr MethodOptions_IdempotencyLevel MethodOptions::IdempotencyLevel_MAX; +constexpr int MethodOptions::IdempotencyLevel_ARRAYSIZE; +#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900) // =================================================================== void FileDescriptorSet::InitAsDefaultInstance() { } +class FileDescriptorSet::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int FileDescriptorSet::kFileFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 FileDescriptorSet::FileDescriptorSet() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorSet.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FileDescriptorSet) } -FileDescriptorSet::FileDescriptorSet(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +FileDescriptorSet::FileDescriptorSet(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena), file_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorSet.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.FileDescriptorSet) } FileDescriptorSet::FileDescriptorSet(const FileDescriptorSet& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), file_(from.file_) { _internal_metadata_.MergeFrom(from._internal_metadata_); @@ -1472,6 +1413,7 @@ FileDescriptorSet::FileDescriptorSet(const FileDescriptorSet& from) } void FileDescriptorSet::SharedCtor() { + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_FileDescriptorSet_google_2fprotobuf_2fdescriptor_2eproto.base); } FileDescriptorSet::~FileDescriptorSet() { @@ -1480,32 +1422,27 @@ FileDescriptorSet::~FileDescriptorSet() { } void FileDescriptorSet::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void FileDescriptorSet::ArenaDtor(void* object) { FileDescriptorSet* _this = reinterpret_cast< FileDescriptorSet* >(object); (void)_this; } -void FileDescriptorSet::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void FileDescriptorSet::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void FileDescriptorSet::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* FileDescriptorSet::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const FileDescriptorSet& FileDescriptorSet::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorSet.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_FileDescriptorSet_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void FileDescriptorSet::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.FileDescriptorSet) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -1514,21 +1451,61 @@ void FileDescriptorSet::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* FileDescriptorSet::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // repeated .google.protobuf.FileDescriptorProto file = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_file(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 10); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool FileDescriptorSet::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FileDescriptorSet) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .google.protobuf.FileDescriptorProto file = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_file())); } else { goto handle_unusual; @@ -1541,7 +1518,7 @@ bool FileDescriptorSet::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -1555,46 +1532,46 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void FileDescriptorSet::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.FileDescriptorSet) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .google.protobuf.FileDescriptorProto file = 1; for (unsigned int i = 0, n = static_cast(this->file_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->file(static_cast(i)), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.FileDescriptorSet) } -::google::protobuf::uint8* FileDescriptorSet::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* FileDescriptorSet::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FileDescriptorSet) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .google.protobuf.FileDescriptorProto file = 1; for (unsigned int i = 0, n = static_cast(this->file_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 1, this->file(static_cast(i)), deterministic, target); + 1, this->file(static_cast(i)), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FileDescriptorSet) @@ -1607,34 +1584,38 @@ size_t FileDescriptorSet::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.FileDescriptorProto file = 1; { unsigned int count = static_cast(this->file_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->file(static_cast(i))); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void FileDescriptorSet::MergeFrom(const ::google::protobuf::Message& from) { +void FileDescriptorSet::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FileDescriptorSet) GOOGLE_DCHECK_NE(&from, this); const FileDescriptorSet* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.FileDescriptorSet) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.FileDescriptorSet) MergeFrom(*source); @@ -1645,13 +1626,13 @@ void FileDescriptorSet::MergeFrom(const FileDescriptorSet& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FileDescriptorSet) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; file_.MergeFrom(from.file_); } -void FileDescriptorSet::CopyFrom(const ::google::protobuf::Message& from) { +void FileDescriptorSet::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.FileDescriptorSet) if (&from == this) return; Clear(); @@ -1666,7 +1647,7 @@ void FileDescriptorSet::CopyFrom(const FileDescriptorSet& from) { } bool FileDescriptorSet::IsInitialized() const { - if (!::google::protobuf::internal::AllAreInitialized(this->file())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->file())) return false; return true; } @@ -1679,7 +1660,7 @@ void FileDescriptorSet::Swap(FileDescriptorSet* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -1691,48 +1672,77 @@ void FileDescriptorSet::UnsafeArenaSwap(FileDescriptorSet* other) { } void FileDescriptorSet::InternalSwap(FileDescriptorSet* other) { using std::swap; - CastToBase(&file_)->InternalSwap(CastToBase(&other->file_)); - swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); + CastToBase(&file_)->InternalSwap(CastToBase(&other->file_)); } -::google::protobuf::Metadata FileDescriptorSet::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata FileDescriptorSet::GetMetadata() const { + return GetMetadataStatic(); } // =================================================================== void FileDescriptorProto::InitAsDefaultInstance() { - ::google::protobuf::_FileDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::FileOptions*>( - ::google::protobuf::FileOptions::internal_default_instance()); - ::google::protobuf::_FileDescriptorProto_default_instance_._instance.get_mutable()->source_code_info_ = const_cast< ::google::protobuf::SourceCodeInfo*>( - ::google::protobuf::SourceCodeInfo::internal_default_instance()); + PROTOBUF_NAMESPACE_ID::_FileDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< PROTOBUF_NAMESPACE_ID::FileOptions*>( + PROTOBUF_NAMESPACE_ID::FileOptions::internal_default_instance()); + PROTOBUF_NAMESPACE_ID::_FileDescriptorProto_default_instance_._instance.get_mutable()->source_code_info_ = const_cast< PROTOBUF_NAMESPACE_ID::SourceCodeInfo*>( + PROTOBUF_NAMESPACE_ID::SourceCodeInfo::internal_default_instance()); +} +class FileDescriptorProto::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_name(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static void set_has_package(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } + static const PROTOBUF_NAMESPACE_ID::FileOptions& options(const FileDescriptorProto* msg); + static void set_has_options(HasBits* has_bits) { + (*has_bits)[0] |= 8u; + } + static const PROTOBUF_NAMESPACE_ID::SourceCodeInfo& source_code_info(const FileDescriptorProto* msg); + static void set_has_source_code_info(HasBits* has_bits) { + (*has_bits)[0] |= 16u; + } + static void set_has_syntax(HasBits* has_bits) { + (*has_bits)[0] |= 4u; + } +}; + +const PROTOBUF_NAMESPACE_ID::FileOptions& +FileDescriptorProto::HasBitSetters::options(const FileDescriptorProto* msg) { + return *msg->options_; +} +const PROTOBUF_NAMESPACE_ID::SourceCodeInfo& +FileDescriptorProto::HasBitSetters::source_code_info(const FileDescriptorProto* msg) { + return *msg->source_code_info_; } void FileDescriptorProto::unsafe_arena_set_allocated_options( - ::google::protobuf::FileOptions* options) { - if (GetArenaNoVirtual() == NULL) { + PROTOBUF_NAMESPACE_ID::FileOptions* options) { + if (GetArenaNoVirtual() == nullptr) { delete options_; } options_ = options; if (options) { - set_has_options(); + _has_bits_[0] |= 0x00000008u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000008u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.options) } void FileDescriptorProto::unsafe_arena_set_allocated_source_code_info( - ::google::protobuf::SourceCodeInfo* source_code_info) { - if (GetArenaNoVirtual() == NULL) { + PROTOBUF_NAMESPACE_ID::SourceCodeInfo* source_code_info) { + if (GetArenaNoVirtual() == nullptr) { delete source_code_info_; } source_code_info_ = source_code_info; if (source_code_info) { - set_has_source_code_info(); + _has_bits_[0] |= 0x00000010u; } else { - clear_has_source_code_info(); + _has_bits_[0] &= ~0x00000010u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.source_code_info) } @@ -1752,14 +1762,12 @@ const int FileDescriptorProto::kSyntaxFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 FileDescriptorProto::FileDescriptorProto() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FileDescriptorProto) } -FileDescriptorProto::FileDescriptorProto(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +FileDescriptorProto::FileDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena), dependency_(arena), message_type_(arena), @@ -1768,14 +1776,13 @@ FileDescriptorProto::FileDescriptorProto(::google::protobuf::Arena* arena) extension_(arena), public_dependency_(arena), weak_dependency_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.FileDescriptorProto) } FileDescriptorProto::FileDescriptorProto(const FileDescriptorProto& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), dependency_(from.dependency_), message_type_(from.message_type_), @@ -1785,38 +1792,39 @@ FileDescriptorProto::FileDescriptorProto(const FileDescriptorProto& from) public_dependency_(from.public_dependency_), weak_dependency_(from.weak_dependency_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(), + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name(), GetArenaNoVirtual()); } - package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_package()) { - package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.package(), + package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.package(), GetArenaNoVirtual()); } - syntax_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + syntax_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_syntax()) { - syntax_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.syntax(), + syntax_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.syntax(), GetArenaNoVirtual()); } if (from.has_options()) { - options_ = new ::google::protobuf::FileOptions(*from.options_); + options_ = new PROTOBUF_NAMESPACE_ID::FileOptions(*from.options_); } else { - options_ = NULL; + options_ = nullptr; } if (from.has_source_code_info()) { - source_code_info_ = new ::google::protobuf::SourceCodeInfo(*from.source_code_info_); + source_code_info_ = new PROTOBUF_NAMESPACE_ID::SourceCodeInfo(*from.source_code_info_); } else { - source_code_info_ = NULL; + source_code_info_ = nullptr; } // @@protoc_insertion_point(copy_constructor:google.protobuf.FileDescriptorProto) } void FileDescriptorProto::SharedCtor() { - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - syntax_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + syntax_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(&options_, 0, static_cast( reinterpret_cast(&source_code_info_) - reinterpret_cast(&options_)) + sizeof(source_code_info_)); @@ -1828,10 +1836,10 @@ FileDescriptorProto::~FileDescriptorProto() { } void FileDescriptorProto::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - package_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - syntax_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); + name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + package_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + syntax_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete options_; if (this != internal_default_instance()) delete source_code_info_; } @@ -1840,25 +1848,20 @@ void FileDescriptorProto::ArenaDtor(void* object) { FileDescriptorProto* _this = reinterpret_cast< FileDescriptorProto* >(object); (void)_this; } -void FileDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void FileDescriptorProto::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void FileDescriptorProto::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* FileDescriptorProto::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const FileDescriptorProto& FileDescriptorProto::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void FileDescriptorProto::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.FileDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -1870,7 +1873,7 @@ void FileDescriptorProto::Clear() { public_dependency_.Clear(); weak_dependency_.Clear(); cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 31u) { + if (cached_has_bits & 0x0000001fu) { if (cached_has_bits & 0x00000001u) { name_.ClearNonDefaultToEmpty(); } @@ -1881,11 +1884,11 @@ void FileDescriptorProto::Clear() { syntax_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { - GOOGLE_DCHECK(options_ != NULL); + GOOGLE_DCHECK(options_ != nullptr); options_->Clear(); } if (cached_has_bits & 0x00000010u) { - GOOGLE_DCHECK(source_code_info_ != NULL); + GOOGLE_DCHECK(source_code_info_ != nullptr); source_code_info_->Clear(); } } @@ -1893,25 +1896,180 @@ void FileDescriptorProto::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* FileDescriptorProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional string name = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_name(), ptr, ctx, "google.protobuf.FileDescriptorProto.name"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string package = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_package(), ptr, ctx, "google.protobuf.FileDescriptorProto.package"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated string dependency = 3; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { + ptr -= 1; + do { + ptr += 1; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(add_dependency(), ptr, ctx, "google.protobuf.FileDescriptorProto.dependency"); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 26); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.DescriptorProto message_type = 4; + case 4: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_message_type(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 34); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.EnumDescriptorProto enum_type = 5; + case 5: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_enum_type(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 42); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.ServiceDescriptorProto service = 6; + case 6: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_service(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 50); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.FieldDescriptorProto extension = 7; + case 7: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_extension(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 58); + } else goto handle_unusual; + continue; + // optional .google.protobuf.FileOptions options = 8; + case 8: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 66)) { + ptr = ctx->ParseMessage(mutable_options(), ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional .google.protobuf.SourceCodeInfo source_code_info = 9; + case 9: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 74)) { + ptr = ctx->ParseMessage(mutable_source_code_info(), ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated int32 public_dependency = 10; + case 10: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 80)) { + ptr -= 1; + do { + ptr += 1; + add_public_dependency(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr)); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 80); + } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 82) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedInt32Parser(mutable_public_dependency(), ptr, ctx); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated int32 weak_dependency = 11; + case 11: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 88)) { + ptr -= 1; + do { + ptr += 1; + add_weak_dependency(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr)); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 88); + } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 90) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedInt32Parser(mutable_weak_dependency(), ptr, ctx); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string syntax = 12; + case 12: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 98)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_syntax(), ptr, ctx, "google.protobuf.FileDescriptorProto.syntax"); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool FileDescriptorProto::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FileDescriptorProto) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional string name = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FileDescriptorProto.name"); } else { goto handle_unusual; @@ -1921,13 +2079,12 @@ bool FileDescriptorProto::MergePartialFromCodedStream( // optional string package = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_package())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->package().data(), static_cast(this->package().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FileDescriptorProto.package"); } else { goto handle_unusual; @@ -1937,14 +2094,13 @@ bool FileDescriptorProto::MergePartialFromCodedStream( // repeated string dependency = 3; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->add_dependency())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->dependency(this->dependency_size() - 1).data(), static_cast(this->dependency(this->dependency_size() - 1).length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FileDescriptorProto.dependency"); } else { goto handle_unusual; @@ -1954,9 +2110,8 @@ bool FileDescriptorProto::MergePartialFromCodedStream( // repeated .google.protobuf.DescriptorProto message_type = 4; case 4: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (34 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_message_type())); } else { goto handle_unusual; @@ -1966,9 +2121,8 @@ bool FileDescriptorProto::MergePartialFromCodedStream( // repeated .google.protobuf.EnumDescriptorProto enum_type = 5; case 5: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (42 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_enum_type())); } else { goto handle_unusual; @@ -1978,9 +2132,8 @@ bool FileDescriptorProto::MergePartialFromCodedStream( // repeated .google.protobuf.ServiceDescriptorProto service = 6; case 6: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (50 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_service())); } else { goto handle_unusual; @@ -1990,9 +2143,8 @@ bool FileDescriptorProto::MergePartialFromCodedStream( // repeated .google.protobuf.FieldDescriptorProto extension = 7; case 7: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (58 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_extension())); } else { goto handle_unusual; @@ -2002,9 +2154,8 @@ bool FileDescriptorProto::MergePartialFromCodedStream( // optional .google.protobuf.FileOptions options = 8; case 8: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (66 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, mutable_options())); } else { goto handle_unusual; @@ -2014,9 +2165,8 @@ bool FileDescriptorProto::MergePartialFromCodedStream( // optional .google.protobuf.SourceCodeInfo source_code_info = 9; case 9: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(74u /* 74 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (74 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, mutable_source_code_info())); } else { goto handle_unusual; @@ -2026,16 +2176,13 @@ bool FileDescriptorProto::MergePartialFromCodedStream( // repeated int32 public_dependency = 10; case 10: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(80u /* 80 & 0xFF */)) { - DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (80 & 0xFF)) { + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadRepeatedPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( 1, 80u, input, this->mutable_public_dependency()))); - } else if ( - static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(82u /* 82 & 0xFF */)) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitiveNoInline< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + } else if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (82 & 0xFF)) { + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPackedPrimitiveNoInline< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, this->mutable_public_dependency()))); } else { goto handle_unusual; @@ -2045,16 +2192,13 @@ bool FileDescriptorProto::MergePartialFromCodedStream( // repeated int32 weak_dependency = 11; case 11: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(88u /* 88 & 0xFF */)) { - DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (88 & 0xFF)) { + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadRepeatedPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( 1, 88u, input, this->mutable_weak_dependency()))); - } else if ( - static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(90u /* 90 & 0xFF */)) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitiveNoInline< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + } else if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (90 & 0xFF)) { + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPackedPrimitiveNoInline< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, this->mutable_weak_dependency()))); } else { goto handle_unusual; @@ -2064,13 +2208,12 @@ bool FileDescriptorProto::MergePartialFromCodedStream( // optional string syntax = 12; case 12: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(98u /* 98 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (98 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_syntax())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->syntax().data(), static_cast(this->syntax().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FileDescriptorProto.syntax"); } else { goto handle_unusual; @@ -2083,7 +2226,7 @@ bool FileDescriptorProto::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -2097,48 +2240,49 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void FileDescriptorProto::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.FileDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileDescriptorProto.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // optional string package = 2; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->package().data(), static_cast(this->package().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileDescriptorProto.package"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->package(), output); } // repeated string dependency = 3; for (int i = 0, n = this->dependency_size(); i < n; i++) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->dependency(i).data(), static_cast(this->dependency(i).length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileDescriptorProto.dependency"); - ::google::protobuf::internal::WireFormatLite::WriteString( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteString( 3, this->dependency(i), output); } // repeated .google.protobuf.DescriptorProto message_type = 4; for (unsigned int i = 0, n = static_cast(this->message_type_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 4, this->message_type(static_cast(i)), output); @@ -2147,7 +2291,7 @@ void FileDescriptorProto::SerializeWithCachedSizes( // repeated .google.protobuf.EnumDescriptorProto enum_type = 5; for (unsigned int i = 0, n = static_cast(this->enum_type_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 5, this->enum_type(static_cast(i)), output); @@ -2156,7 +2300,7 @@ void FileDescriptorProto::SerializeWithCachedSizes( // repeated .google.protobuf.ServiceDescriptorProto service = 6; for (unsigned int i = 0, n = static_cast(this->service_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 6, this->service(static_cast(i)), output); @@ -2165,7 +2309,7 @@ void FileDescriptorProto::SerializeWithCachedSizes( // repeated .google.protobuf.FieldDescriptorProto extension = 7; for (unsigned int i = 0, n = static_cast(this->extension_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 7, this->extension(static_cast(i)), output); @@ -2173,152 +2317,151 @@ void FileDescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.FileOptions options = 8; if (cached_has_bits & 0x00000008u) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 8, this->_internal_options(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( + 8, HasBitSetters::options(this), output); } // optional .google.protobuf.SourceCodeInfo source_code_info = 9; if (cached_has_bits & 0x00000010u) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 9, this->_internal_source_code_info(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( + 9, HasBitSetters::source_code_info(this), output); } // repeated int32 public_dependency = 10; for (int i = 0, n = this->public_dependency_size(); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteInt32( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32( 10, this->public_dependency(i), output); } // repeated int32 weak_dependency = 11; for (int i = 0, n = this->weak_dependency_size(); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteInt32( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32( 11, this->weak_dependency(i), output); } // optional string syntax = 12; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->syntax().data(), static_cast(this->syntax().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileDescriptorProto.syntax"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 12, this->syntax(), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.FileDescriptorProto) } -::google::protobuf::uint8* FileDescriptorProto::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* FileDescriptorProto::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FileDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileDescriptorProto.name"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // optional string package = 2; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->package().data(), static_cast(this->package().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileDescriptorProto.package"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 2, this->package(), target); } // repeated string dependency = 3; for (int i = 0, n = this->dependency_size(); i < n; i++) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->dependency(i).data(), static_cast(this->dependency(i).length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileDescriptorProto.dependency"); - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: WriteStringToArray(3, this->dependency(i), target); } // repeated .google.protobuf.DescriptorProto message_type = 4; for (unsigned int i = 0, n = static_cast(this->message_type_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 4, this->message_type(static_cast(i)), deterministic, target); + 4, this->message_type(static_cast(i)), target); } // repeated .google.protobuf.EnumDescriptorProto enum_type = 5; for (unsigned int i = 0, n = static_cast(this->enum_type_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 5, this->enum_type(static_cast(i)), deterministic, target); + 5, this->enum_type(static_cast(i)), target); } // repeated .google.protobuf.ServiceDescriptorProto service = 6; for (unsigned int i = 0, n = static_cast(this->service_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 6, this->service(static_cast(i)), deterministic, target); + 6, this->service(static_cast(i)), target); } // repeated .google.protobuf.FieldDescriptorProto extension = 7; for (unsigned int i = 0, n = static_cast(this->extension_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 7, this->extension(static_cast(i)), deterministic, target); + 7, this->extension(static_cast(i)), target); } // optional .google.protobuf.FileOptions options = 8; if (cached_has_bits & 0x00000008u) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 8, this->_internal_options(), deterministic, target); + 8, HasBitSetters::options(this), target); } // optional .google.protobuf.SourceCodeInfo source_code_info = 9; if (cached_has_bits & 0x00000010u) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 9, this->_internal_source_code_info(), deterministic, target); + 9, HasBitSetters::source_code_info(this), target); } // repeated int32 public_dependency = 10; - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: WriteInt32ToArray(10, this->public_dependency_, target); // repeated int32 weak_dependency = 11; - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: WriteInt32ToArray(11, this->weak_dependency_, target); // optional string syntax = 12; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->syntax().data(), static_cast(this->syntax().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileDescriptorProto.syntax"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 12, this->syntax(), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FileDescriptorProto) @@ -2331,14 +2474,18 @@ size_t FileDescriptorProto::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated string dependency = 3; total_size += 1 * - ::google::protobuf::internal::FromIntSize(this->dependency_size()); + ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->dependency_size()); for (int i = 0, n = this->dependency_size(); i < n; i++) { - total_size += ::google::protobuf::internal::WireFormatLite::StringSize( + total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->dependency(i)); } @@ -2348,7 +2495,7 @@ size_t FileDescriptorProto::ByteSizeLong() const { total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->message_type(static_cast(i))); } } @@ -2359,7 +2506,7 @@ size_t FileDescriptorProto::ByteSizeLong() const { total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->enum_type(static_cast(i))); } } @@ -2370,7 +2517,7 @@ size_t FileDescriptorProto::ByteSizeLong() const { total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->service(static_cast(i))); } } @@ -2381,80 +2528,81 @@ size_t FileDescriptorProto::ByteSizeLong() const { total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->extension(static_cast(i))); } } // repeated int32 public_dependency = 10; { - size_t data_size = ::google::protobuf::internal::WireFormatLite:: + size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: Int32Size(this->public_dependency_); total_size += 1 * - ::google::protobuf::internal::FromIntSize(this->public_dependency_size()); + ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->public_dependency_size()); total_size += data_size; } // repeated int32 weak_dependency = 11; { - size_t data_size = ::google::protobuf::internal::WireFormatLite:: + size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: Int32Size(this->weak_dependency_); total_size += 1 * - ::google::protobuf::internal::FromIntSize(this->weak_dependency_size()); + ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->weak_dependency_size()); total_size += data_size; } - if (_has_bits_[0 / 32] & 31u) { + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x0000001fu) { // optional string name = 1; - if (has_name()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->name()); } // optional string package = 2; - if (has_package()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->package()); } // optional string syntax = 12; - if (has_syntax()) { + if (cached_has_bits & 0x00000004u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->syntax()); } // optional .google.protobuf.FileOptions options = 8; - if (has_options()) { + if (cached_has_bits & 0x00000008u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *options_); } // optional .google.protobuf.SourceCodeInfo source_code_info = 9; - if (has_source_code_info()) { + if (cached_has_bits & 0x00000010u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *source_code_info_); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void FileDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) { +void FileDescriptorProto::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FileDescriptorProto) GOOGLE_DCHECK_NE(&from, this); const FileDescriptorProto* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.FileDescriptorProto) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.FileDescriptorProto) MergeFrom(*source); @@ -2465,7 +2613,7 @@ void FileDescriptorProto::MergeFrom(const FileDescriptorProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FileDescriptorProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; dependency_.MergeFrom(from.dependency_); @@ -2476,7 +2624,7 @@ void FileDescriptorProto::MergeFrom(const FileDescriptorProto& from) { public_dependency_.MergeFrom(from.public_dependency_); weak_dependency_.MergeFrom(from.weak_dependency_); cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 31u) { + if (cached_has_bits & 0x0000001fu) { if (cached_has_bits & 0x00000001u) { set_name(from.name()); } @@ -2487,15 +2635,15 @@ void FileDescriptorProto::MergeFrom(const FileDescriptorProto& from) { set_syntax(from.syntax()); } if (cached_has_bits & 0x00000008u) { - mutable_options()->::google::protobuf::FileOptions::MergeFrom(from.options()); + mutable_options()->PROTOBUF_NAMESPACE_ID::FileOptions::MergeFrom(from.options()); } if (cached_has_bits & 0x00000010u) { - mutable_source_code_info()->::google::protobuf::SourceCodeInfo::MergeFrom(from.source_code_info()); + mutable_source_code_info()->PROTOBUF_NAMESPACE_ID::SourceCodeInfo::MergeFrom(from.source_code_info()); } } } -void FileDescriptorProto::CopyFrom(const ::google::protobuf::Message& from) { +void FileDescriptorProto::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.FileDescriptorProto) if (&from == this) return; Clear(); @@ -2510,10 +2658,10 @@ void FileDescriptorProto::CopyFrom(const FileDescriptorProto& from) { } bool FileDescriptorProto::IsInitialized() const { - if (!::google::protobuf::internal::AllAreInitialized(this->message_type())) return false; - if (!::google::protobuf::internal::AllAreInitialized(this->enum_type())) return false; - if (!::google::protobuf::internal::AllAreInitialized(this->service())) return false; - if (!::google::protobuf::internal::AllAreInitialized(this->extension())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->message_type())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->enum_type())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->service())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->extension())) return false; if (has_options()) { if (!this->options_->IsInitialized()) return false; } @@ -2529,7 +2677,7 @@ void FileDescriptorProto::Swap(FileDescriptorProto* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -2541,6 +2689,8 @@ void FileDescriptorProto::UnsafeArenaSwap(FileDescriptorProto* other) { } void FileDescriptorProto::InternalSwap(FileDescriptorProto* other) { using std::swap; + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); dependency_.InternalSwap(CastToBase(&other->dependency_)); CastToBase(&message_type_)->InternalSwap(CastToBase(&other->message_type_)); CastToBase(&enum_type_)->InternalSwap(CastToBase(&other->enum_type_)); @@ -2548,40 +2698,56 @@ void FileDescriptorProto::InternalSwap(FileDescriptorProto* other) { CastToBase(&extension_)->InternalSwap(CastToBase(&other->extension_)); public_dependency_.InternalSwap(&other->public_dependency_); weak_dependency_.InternalSwap(&other->weak_dependency_); - name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - package_.Swap(&other->package_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + package_.Swap(&other->package_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - syntax_.Swap(&other->syntax_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + syntax_.Swap(&other->syntax_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(options_, other->options_); swap(source_code_info_, other->source_code_info_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata FileDescriptorProto::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata FileDescriptorProto::GetMetadata() const { + return GetMetadataStatic(); } // =================================================================== void DescriptorProto_ExtensionRange::InitAsDefaultInstance() { - ::google::protobuf::_DescriptorProto_ExtensionRange_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::ExtensionRangeOptions*>( - ::google::protobuf::ExtensionRangeOptions::internal_default_instance()); + PROTOBUF_NAMESPACE_ID::_DescriptorProto_ExtensionRange_default_instance_._instance.get_mutable()->options_ = const_cast< PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions*>( + PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions::internal_default_instance()); +} +class DescriptorProto_ExtensionRange::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_start(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } + static void set_has_end(HasBits* has_bits) { + (*has_bits)[0] |= 4u; + } + static const PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions& options(const DescriptorProto_ExtensionRange* msg); + static void set_has_options(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } +}; + +const PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions& +DescriptorProto_ExtensionRange::HasBitSetters::options(const DescriptorProto_ExtensionRange* msg) { + return *msg->options_; } void DescriptorProto_ExtensionRange::unsafe_arena_set_allocated_options( - ::google::protobuf::ExtensionRangeOptions* options) { - if (GetArenaNoVirtual() == NULL) { + PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* options) { + if (GetArenaNoVirtual() == nullptr) { delete options_; } options_ = options; if (options) { - set_has_options(); + _has_bits_[0] |= 0x00000001u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000001u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.DescriptorProto.ExtensionRange.options) } @@ -2592,29 +2758,26 @@ const int DescriptorProto_ExtensionRange::kOptionsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ExtensionRange.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto.ExtensionRange) } -DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ExtensionRange.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto.ExtensionRange) } DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(const DescriptorProto_ExtensionRange& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_options()) { - options_ = new ::google::protobuf::ExtensionRangeOptions(*from.options_); + options_ = new PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions(*from.options_); } else { - options_ = NULL; + options_ = nullptr; } ::memcpy(&start_, &from.start_, static_cast(reinterpret_cast(&end_) - @@ -2623,6 +2786,7 @@ DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(const DescriptorP } void DescriptorProto_ExtensionRange::SharedCtor() { + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_DescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto.base); ::memset(&options_, 0, static_cast( reinterpret_cast(&end_) - reinterpret_cast(&options_)) + sizeof(end_)); @@ -2634,7 +2798,7 @@ DescriptorProto_ExtensionRange::~DescriptorProto_ExtensionRange() { } void DescriptorProto_ExtensionRange::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); if (this != internal_default_instance()) delete options_; } @@ -2642,34 +2806,29 @@ void DescriptorProto_ExtensionRange::ArenaDtor(void* object) { DescriptorProto_ExtensionRange* _this = reinterpret_cast< DescriptorProto_ExtensionRange* >(object); (void)_this; } -void DescriptorProto_ExtensionRange::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void DescriptorProto_ExtensionRange::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void DescriptorProto_ExtensionRange::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* DescriptorProto_ExtensionRange::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const DescriptorProto_ExtensionRange& DescriptorProto_ExtensionRange::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ExtensionRange.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_DescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void DescriptorProto_ExtensionRange::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.DescriptorProto.ExtensionRange) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(options_ != NULL); + GOOGLE_DCHECK(options_ != nullptr); options_->Clear(); } - if (cached_has_bits & 6u) { + if (cached_has_bits & 0x00000006u) { ::memset(&start_, 0, static_cast( reinterpret_cast(&end_) - reinterpret_cast(&start_)) + sizeof(end_)); @@ -2678,23 +2837,76 @@ void DescriptorProto_ExtensionRange::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* DescriptorProto_ExtensionRange::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional int32 start = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { + HasBitSetters::set_has_start(&has_bits); + start_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional int32 end = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { + HasBitSetters::set_has_end(&has_bits); + end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional .google.protobuf.ExtensionRangeOptions options = 3; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { + ptr = ctx->ParseMessage(mutable_options(), ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto.ExtensionRange) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional int32 start = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { - set_has_start(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) { + HasBitSetters::set_has_start(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &start_))); } else { goto handle_unusual; @@ -2704,11 +2916,10 @@ bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream( // optional int32 end = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { - set_has_end(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (16 & 0xFF)) { + HasBitSetters::set_has_end(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &end_))); } else { goto handle_unusual; @@ -2718,9 +2929,8 @@ bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream( // optional .google.protobuf.ExtensionRangeOptions options = 3; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, mutable_options())); } else { goto handle_unusual; @@ -2733,7 +2943,7 @@ bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -2747,64 +2957,64 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void DescriptorProto_ExtensionRange::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.DescriptorProto.ExtensionRange) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional int32 start = 1; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->start(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(1, this->start(), output); } // optional int32 end = 2; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->end(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(2, this->end(), output); } // optional .google.protobuf.ExtensionRangeOptions options = 3; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, this->_internal_options(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( + 3, HasBitSetters::options(this), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.DescriptorProto.ExtensionRange) } -::google::protobuf::uint8* DescriptorProto_ExtensionRange::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* DescriptorProto_ExtensionRange::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.DescriptorProto.ExtensionRange) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional int32 start = 1; if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->start(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(1, this->start(), target); } // optional int32 end = 2; if (cached_has_bits & 0x00000004u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->end(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(2, this->end(), target); } // optional .google.protobuf.ExtensionRangeOptions options = 3; if (cached_has_bits & 0x00000001u) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 3, this->_internal_options(), deterministic, target); + 3, HasBitSetters::options(this), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.DescriptorProto.ExtensionRange) @@ -2817,46 +3027,51 @@ size_t DescriptorProto_ExtensionRange::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } - if (_has_bits_[0 / 32] & 7u) { + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x00000007u) { // optional .google.protobuf.ExtensionRangeOptions options = 3; - if (has_options()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *options_); } // optional int32 start = 1; - if (has_start()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->start()); } // optional int32 end = 2; - if (has_end()) { + if (cached_has_bits & 0x00000004u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->end()); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void DescriptorProto_ExtensionRange::MergeFrom(const ::google::protobuf::Message& from) { +void DescriptorProto_ExtensionRange::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.DescriptorProto.ExtensionRange) GOOGLE_DCHECK_NE(&from, this); const DescriptorProto_ExtensionRange* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.DescriptorProto.ExtensionRange) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.DescriptorProto.ExtensionRange) MergeFrom(*source); @@ -2867,13 +3082,13 @@ void DescriptorProto_ExtensionRange::MergeFrom(const DescriptorProto_ExtensionRa // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.DescriptorProto.ExtensionRange) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 7u) { + if (cached_has_bits & 0x00000007u) { if (cached_has_bits & 0x00000001u) { - mutable_options()->::google::protobuf::ExtensionRangeOptions::MergeFrom(from.options()); + mutable_options()->PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions::MergeFrom(from.options()); } if (cached_has_bits & 0x00000002u) { start_ = from.start_; @@ -2885,7 +3100,7 @@ void DescriptorProto_ExtensionRange::MergeFrom(const DescriptorProto_ExtensionRa } } -void DescriptorProto_ExtensionRange::CopyFrom(const ::google::protobuf::Message& from) { +void DescriptorProto_ExtensionRange::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.DescriptorProto.ExtensionRange) if (&from == this) return; Clear(); @@ -2915,7 +3130,7 @@ void DescriptorProto_ExtensionRange::Swap(DescriptorProto_ExtensionRange* other) temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -2927,16 +3142,15 @@ void DescriptorProto_ExtensionRange::UnsafeArenaSwap(DescriptorProto_ExtensionRa } void DescriptorProto_ExtensionRange::InternalSwap(DescriptorProto_ExtensionRange* other) { using std::swap; + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); swap(options_, other->options_); swap(start_, other->start_); swap(end_, other->end_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata DescriptorProto_ExtensionRange::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata DescriptorProto_ExtensionRange::GetMetadata() const { + return GetMetadataStatic(); } @@ -2944,29 +3158,37 @@ void DescriptorProto_ExtensionRange::InternalSwap(DescriptorProto_ExtensionRange void DescriptorProto_ReservedRange::InitAsDefaultInstance() { } +class DescriptorProto_ReservedRange::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_start(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static void set_has_end(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int DescriptorProto_ReservedRange::kStartFieldNumber; const int DescriptorProto_ReservedRange::kEndFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 DescriptorProto_ReservedRange::DescriptorProto_ReservedRange() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ReservedRange.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto.ReservedRange) } -DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ReservedRange.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto.ReservedRange) } DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(const DescriptorProto_ReservedRange& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&start_, &from.start_, @@ -2987,37 +3209,32 @@ DescriptorProto_ReservedRange::~DescriptorProto_ReservedRange() { } void DescriptorProto_ReservedRange::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void DescriptorProto_ReservedRange::ArenaDtor(void* object) { DescriptorProto_ReservedRange* _this = reinterpret_cast< DescriptorProto_ReservedRange* >(object); (void)_this; } -void DescriptorProto_ReservedRange::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void DescriptorProto_ReservedRange::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void DescriptorProto_ReservedRange::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* DescriptorProto_ReservedRange::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const DescriptorProto_ReservedRange& DescriptorProto_ReservedRange::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ReservedRange.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_DescriptorProto_ReservedRange_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void DescriptorProto_ReservedRange::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.DescriptorProto.ReservedRange) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { ::memset(&start_, 0, static_cast( reinterpret_cast(&end_) - reinterpret_cast(&start_)) + sizeof(end_)); @@ -3026,23 +3243,69 @@ void DescriptorProto_ReservedRange::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* DescriptorProto_ReservedRange::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional int32 start = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { + HasBitSetters::set_has_start(&has_bits); + start_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional int32 end = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { + HasBitSetters::set_has_end(&has_bits); + end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool DescriptorProto_ReservedRange::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto.ReservedRange) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional int32 start = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { - set_has_start(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) { + HasBitSetters::set_has_start(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &start_))); } else { goto handle_unusual; @@ -3052,11 +3315,10 @@ bool DescriptorProto_ReservedRange::MergePartialFromCodedStream( // optional int32 end = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { - set_has_end(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (16 & 0xFF)) { + HasBitSetters::set_has_end(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &end_))); } else { goto handle_unusual; @@ -3069,7 +3331,7 @@ bool DescriptorProto_ReservedRange::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -3083,51 +3345,51 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void DescriptorProto_ReservedRange::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.DescriptorProto.ReservedRange) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional int32 start = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->start(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(1, this->start(), output); } // optional int32 end = 2; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->end(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(2, this->end(), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.DescriptorProto.ReservedRange) } -::google::protobuf::uint8* DescriptorProto_ReservedRange::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* DescriptorProto_ReservedRange::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.DescriptorProto.ReservedRange) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional int32 start = 1; if (cached_has_bits & 0x00000001u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->start(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(1, this->start(), target); } // optional int32 end = 2; if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->end(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(2, this->end(), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.DescriptorProto.ReservedRange) @@ -3140,39 +3402,44 @@ size_t DescriptorProto_ReservedRange::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } - if (_has_bits_[0 / 32] & 3u) { + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x00000003u) { // optional int32 start = 1; - if (has_start()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->start()); } // optional int32 end = 2; - if (has_end()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->end()); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void DescriptorProto_ReservedRange::MergeFrom(const ::google::protobuf::Message& from) { +void DescriptorProto_ReservedRange::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.DescriptorProto.ReservedRange) GOOGLE_DCHECK_NE(&from, this); const DescriptorProto_ReservedRange* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.DescriptorProto.ReservedRange) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.DescriptorProto.ReservedRange) MergeFrom(*source); @@ -3183,11 +3450,11 @@ void DescriptorProto_ReservedRange::MergeFrom(const DescriptorProto_ReservedRang // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.DescriptorProto.ReservedRange) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { start_ = from.start_; } @@ -3198,7 +3465,7 @@ void DescriptorProto_ReservedRange::MergeFrom(const DescriptorProto_ReservedRang } } -void DescriptorProto_ReservedRange::CopyFrom(const ::google::protobuf::Message& from) { +void DescriptorProto_ReservedRange::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.DescriptorProto.ReservedRange) if (&from == this) return; Clear(); @@ -3225,7 +3492,7 @@ void DescriptorProto_ReservedRange::Swap(DescriptorProto_ReservedRange* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -3237,34 +3504,49 @@ void DescriptorProto_ReservedRange::UnsafeArenaSwap(DescriptorProto_ReservedRang } void DescriptorProto_ReservedRange::InternalSwap(DescriptorProto_ReservedRange* other) { using std::swap; + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); swap(start_, other->start_); swap(end_, other->end_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata DescriptorProto_ReservedRange::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata DescriptorProto_ReservedRange::GetMetadata() const { + return GetMetadataStatic(); } // =================================================================== void DescriptorProto::InitAsDefaultInstance() { - ::google::protobuf::_DescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::MessageOptions*>( - ::google::protobuf::MessageOptions::internal_default_instance()); + PROTOBUF_NAMESPACE_ID::_DescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< PROTOBUF_NAMESPACE_ID::MessageOptions*>( + PROTOBUF_NAMESPACE_ID::MessageOptions::internal_default_instance()); +} +class DescriptorProto::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_name(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static const PROTOBUF_NAMESPACE_ID::MessageOptions& options(const DescriptorProto* msg); + static void set_has_options(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } +}; + +const PROTOBUF_NAMESPACE_ID::MessageOptions& +DescriptorProto::HasBitSetters::options(const DescriptorProto* msg) { + return *msg->options_; } void DescriptorProto::unsafe_arena_set_allocated_options( - ::google::protobuf::MessageOptions* options) { - if (GetArenaNoVirtual() == NULL) { + PROTOBUF_NAMESPACE_ID::MessageOptions* options) { + if (GetArenaNoVirtual() == nullptr) { delete options_; } options_ = options; if (options) { - set_has_options(); + _has_bits_[0] |= 0x00000002u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000002u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.DescriptorProto.options) } @@ -3282,14 +3564,12 @@ const int DescriptorProto::kReservedNameFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 DescriptorProto::DescriptorProto() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto) } -DescriptorProto::DescriptorProto(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +DescriptorProto::DescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena), field_(arena), nested_type_(arena), @@ -3299,14 +3579,13 @@ DescriptorProto::DescriptorProto(::google::protobuf::Arena* arena) oneof_decl_(arena), reserved_range_(arena), reserved_name_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto) } DescriptorProto::DescriptorProto(const DescriptorProto& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), field_(from.field_), nested_type_(from.nested_type_), @@ -3317,22 +3596,23 @@ DescriptorProto::DescriptorProto(const DescriptorProto& from) reserved_range_(from.reserved_range_), reserved_name_(from.reserved_name_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(), + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name(), GetArenaNoVirtual()); } if (from.has_options()) { - options_ = new ::google::protobuf::MessageOptions(*from.options_); + options_ = new PROTOBUF_NAMESPACE_ID::MessageOptions(*from.options_); } else { - options_ = NULL; + options_ = nullptr; } // @@protoc_insertion_point(copy_constructor:google.protobuf.DescriptorProto) } void DescriptorProto::SharedCtor() { - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - options_ = NULL; + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_DescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + options_ = nullptr; } DescriptorProto::~DescriptorProto() { @@ -3341,8 +3621,8 @@ DescriptorProto::~DescriptorProto() { } void DescriptorProto::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); + name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete options_; } @@ -3350,25 +3630,20 @@ void DescriptorProto::ArenaDtor(void* object) { DescriptorProto* _this = reinterpret_cast< DescriptorProto* >(object); (void)_this; } -void DescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void DescriptorProto::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void DescriptorProto::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* DescriptorProto::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const DescriptorProto& DescriptorProto::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_DescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void DescriptorProto::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.DescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -3381,12 +3656,12 @@ void DescriptorProto::Clear() { reserved_range_.Clear(); reserved_name_.Clear(); cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(options_ != NULL); + GOOGLE_DCHECK(options_ != nullptr); options_->Clear(); } } @@ -3394,25 +3669,165 @@ void DescriptorProto::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* DescriptorProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional string name = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_name(), ptr, ctx, "google.protobuf.DescriptorProto.name"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.FieldDescriptorProto field = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_field(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 18); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.DescriptorProto nested_type = 3; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_nested_type(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 26); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.EnumDescriptorProto enum_type = 4; + case 4: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_enum_type(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 34); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; + case 5: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_extension_range(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 42); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.FieldDescriptorProto extension = 6; + case 6: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_extension(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 50); + } else goto handle_unusual; + continue; + // optional .google.protobuf.MessageOptions options = 7; + case 7: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { + ptr = ctx->ParseMessage(mutable_options(), ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8; + case 8: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 66)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_oneof_decl(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 66); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9; + case 9: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 74)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_reserved_range(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 74); + } else goto handle_unusual; + continue; + // repeated string reserved_name = 10; + case 10: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 82)) { + ptr -= 1; + do { + ptr += 1; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(add_reserved_name(), ptr, ctx, "google.protobuf.DescriptorProto.reserved_name"); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 82); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool DescriptorProto::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional string name = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.DescriptorProto.name"); } else { goto handle_unusual; @@ -3422,9 +3837,8 @@ bool DescriptorProto::MergePartialFromCodedStream( // repeated .google.protobuf.FieldDescriptorProto field = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_field())); } else { goto handle_unusual; @@ -3434,9 +3848,8 @@ bool DescriptorProto::MergePartialFromCodedStream( // repeated .google.protobuf.DescriptorProto nested_type = 3; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_nested_type())); } else { goto handle_unusual; @@ -3446,9 +3859,8 @@ bool DescriptorProto::MergePartialFromCodedStream( // repeated .google.protobuf.EnumDescriptorProto enum_type = 4; case 4: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (34 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_enum_type())); } else { goto handle_unusual; @@ -3458,9 +3870,8 @@ bool DescriptorProto::MergePartialFromCodedStream( // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; case 5: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (42 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_extension_range())); } else { goto handle_unusual; @@ -3470,9 +3881,8 @@ bool DescriptorProto::MergePartialFromCodedStream( // repeated .google.protobuf.FieldDescriptorProto extension = 6; case 6: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (50 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_extension())); } else { goto handle_unusual; @@ -3482,9 +3892,8 @@ bool DescriptorProto::MergePartialFromCodedStream( // optional .google.protobuf.MessageOptions options = 7; case 7: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (58 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, mutable_options())); } else { goto handle_unusual; @@ -3494,9 +3903,8 @@ bool DescriptorProto::MergePartialFromCodedStream( // repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8; case 8: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (66 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_oneof_decl())); } else { goto handle_unusual; @@ -3506,9 +3914,8 @@ bool DescriptorProto::MergePartialFromCodedStream( // repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9; case 9: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(74u /* 74 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (74 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_reserved_range())); } else { goto handle_unusual; @@ -3518,14 +3925,13 @@ bool DescriptorProto::MergePartialFromCodedStream( // repeated string reserved_name = 10; case 10: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(82u /* 82 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (82 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->add_reserved_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->reserved_name(this->reserved_name_size() - 1).data(), static_cast(this->reserved_name(this->reserved_name_size() - 1).length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.DescriptorProto.reserved_name"); } else { goto handle_unusual; @@ -3538,7 +3944,7 @@ bool DescriptorProto::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -3552,28 +3958,29 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void DescriptorProto::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.DescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.DescriptorProto.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // repeated .google.protobuf.FieldDescriptorProto field = 2; for (unsigned int i = 0, n = static_cast(this->field_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->field(static_cast(i)), output); @@ -3582,7 +3989,7 @@ void DescriptorProto::SerializeWithCachedSizes( // repeated .google.protobuf.DescriptorProto nested_type = 3; for (unsigned int i = 0, n = static_cast(this->nested_type_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->nested_type(static_cast(i)), output); @@ -3591,7 +3998,7 @@ void DescriptorProto::SerializeWithCachedSizes( // repeated .google.protobuf.EnumDescriptorProto enum_type = 4; for (unsigned int i = 0, n = static_cast(this->enum_type_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 4, this->enum_type(static_cast(i)), output); @@ -3600,7 +4007,7 @@ void DescriptorProto::SerializeWithCachedSizes( // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; for (unsigned int i = 0, n = static_cast(this->extension_range_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 5, this->extension_range(static_cast(i)), output); @@ -3609,7 +4016,7 @@ void DescriptorProto::SerializeWithCachedSizes( // repeated .google.protobuf.FieldDescriptorProto extension = 6; for (unsigned int i = 0, n = static_cast(this->extension_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 6, this->extension(static_cast(i)), output); @@ -3617,14 +4024,14 @@ void DescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.MessageOptions options = 7; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 7, this->_internal_options(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( + 7, HasBitSetters::options(this), output); } // repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8; for (unsigned int i = 0, n = static_cast(this->oneof_decl_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 8, this->oneof_decl(static_cast(i)), output); @@ -3633,7 +4040,7 @@ void DescriptorProto::SerializeWithCachedSizes( // repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9; for (unsigned int i = 0, n = static_cast(this->reserved_range_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 9, this->reserved_range(static_cast(i)), output); @@ -3641,115 +4048,114 @@ void DescriptorProto::SerializeWithCachedSizes( // repeated string reserved_name = 10; for (int i = 0, n = this->reserved_name_size(); i < n; i++) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->reserved_name(i).data(), static_cast(this->reserved_name(i).length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.DescriptorProto.reserved_name"); - ::google::protobuf::internal::WireFormatLite::WriteString( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteString( 10, this->reserved_name(i), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.DescriptorProto) } -::google::protobuf::uint8* DescriptorProto::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* DescriptorProto::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.DescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.DescriptorProto.name"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // repeated .google.protobuf.FieldDescriptorProto field = 2; for (unsigned int i = 0, n = static_cast(this->field_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 2, this->field(static_cast(i)), deterministic, target); + 2, this->field(static_cast(i)), target); } // repeated .google.protobuf.DescriptorProto nested_type = 3; for (unsigned int i = 0, n = static_cast(this->nested_type_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 3, this->nested_type(static_cast(i)), deterministic, target); + 3, this->nested_type(static_cast(i)), target); } // repeated .google.protobuf.EnumDescriptorProto enum_type = 4; for (unsigned int i = 0, n = static_cast(this->enum_type_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 4, this->enum_type(static_cast(i)), deterministic, target); + 4, this->enum_type(static_cast(i)), target); } // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; for (unsigned int i = 0, n = static_cast(this->extension_range_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 5, this->extension_range(static_cast(i)), deterministic, target); + 5, this->extension_range(static_cast(i)), target); } // repeated .google.protobuf.FieldDescriptorProto extension = 6; for (unsigned int i = 0, n = static_cast(this->extension_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 6, this->extension(static_cast(i)), deterministic, target); + 6, this->extension(static_cast(i)), target); } // optional .google.protobuf.MessageOptions options = 7; if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 7, this->_internal_options(), deterministic, target); + 7, HasBitSetters::options(this), target); } // repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8; for (unsigned int i = 0, n = static_cast(this->oneof_decl_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 8, this->oneof_decl(static_cast(i)), deterministic, target); + 8, this->oneof_decl(static_cast(i)), target); } // repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9; for (unsigned int i = 0, n = static_cast(this->reserved_range_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 9, this->reserved_range(static_cast(i)), deterministic, target); + 9, this->reserved_range(static_cast(i)), target); } // repeated string reserved_name = 10; for (int i = 0, n = this->reserved_name_size(); i < n; i++) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->reserved_name(i).data(), static_cast(this->reserved_name(i).length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.DescriptorProto.reserved_name"); - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: WriteStringToArray(10, this->reserved_name(i), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.DescriptorProto) @@ -3762,16 +4168,20 @@ size_t DescriptorProto::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.FieldDescriptorProto field = 2; { unsigned int count = static_cast(this->field_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->field(static_cast(i))); } } @@ -3782,7 +4192,7 @@ size_t DescriptorProto::ByteSizeLong() const { total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->nested_type(static_cast(i))); } } @@ -3793,7 +4203,7 @@ size_t DescriptorProto::ByteSizeLong() const { total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->enum_type(static_cast(i))); } } @@ -3804,7 +4214,7 @@ size_t DescriptorProto::ByteSizeLong() const { total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->extension_range(static_cast(i))); } } @@ -3815,7 +4225,7 @@ size_t DescriptorProto::ByteSizeLong() const { total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->extension(static_cast(i))); } } @@ -3826,7 +4236,7 @@ size_t DescriptorProto::ByteSizeLong() const { total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->oneof_decl(static_cast(i))); } } @@ -3837,49 +4247,50 @@ size_t DescriptorProto::ByteSizeLong() const { total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->reserved_range(static_cast(i))); } } // repeated string reserved_name = 10; total_size += 1 * - ::google::protobuf::internal::FromIntSize(this->reserved_name_size()); + ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->reserved_name_size()); for (int i = 0, n = this->reserved_name_size(); i < n; i++) { - total_size += ::google::protobuf::internal::WireFormatLite::StringSize( + total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->reserved_name(i)); } - if (_has_bits_[0 / 32] & 3u) { + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x00000003u) { // optional string name = 1; - if (has_name()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->name()); } // optional .google.protobuf.MessageOptions options = 7; - if (has_options()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *options_); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void DescriptorProto::MergeFrom(const ::google::protobuf::Message& from) { +void DescriptorProto::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.DescriptorProto) GOOGLE_DCHECK_NE(&from, this); const DescriptorProto* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.DescriptorProto) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.DescriptorProto) MergeFrom(*source); @@ -3890,7 +4301,7 @@ void DescriptorProto::MergeFrom(const DescriptorProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.DescriptorProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; field_.MergeFrom(from.field_); @@ -3902,17 +4313,17 @@ void DescriptorProto::MergeFrom(const DescriptorProto& from) { reserved_range_.MergeFrom(from.reserved_range_); reserved_name_.MergeFrom(from.reserved_name_); cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { set_name(from.name()); } if (cached_has_bits & 0x00000002u) { - mutable_options()->::google::protobuf::MessageOptions::MergeFrom(from.options()); + mutable_options()->PROTOBUF_NAMESPACE_ID::MessageOptions::MergeFrom(from.options()); } } } -void DescriptorProto::CopyFrom(const ::google::protobuf::Message& from) { +void DescriptorProto::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.DescriptorProto) if (&from == this) return; Clear(); @@ -3927,12 +4338,12 @@ void DescriptorProto::CopyFrom(const DescriptorProto& from) { } bool DescriptorProto::IsInitialized() const { - if (!::google::protobuf::internal::AllAreInitialized(this->field())) return false; - if (!::google::protobuf::internal::AllAreInitialized(this->nested_type())) return false; - if (!::google::protobuf::internal::AllAreInitialized(this->enum_type())) return false; - if (!::google::protobuf::internal::AllAreInitialized(this->extension_range())) return false; - if (!::google::protobuf::internal::AllAreInitialized(this->extension())) return false; - if (!::google::protobuf::internal::AllAreInitialized(this->oneof_decl())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->field())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->nested_type())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->enum_type())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->extension_range())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->extension())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->oneof_decl())) return false; if (has_options()) { if (!this->options_->IsInitialized()) return false; } @@ -3948,7 +4359,7 @@ void DescriptorProto::Swap(DescriptorProto* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -3960,6 +4371,8 @@ void DescriptorProto::UnsafeArenaSwap(DescriptorProto* other) { } void DescriptorProto::InternalSwap(DescriptorProto* other) { using std::swap; + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); CastToBase(&field_)->InternalSwap(CastToBase(&other->field_)); CastToBase(&nested_type_)->InternalSwap(CastToBase(&other->nested_type_)); CastToBase(&enum_type_)->InternalSwap(CastToBase(&other->enum_type_)); @@ -3968,16 +4381,13 @@ void DescriptorProto::InternalSwap(DescriptorProto* other) { CastToBase(&oneof_decl_)->InternalSwap(CastToBase(&other->oneof_decl_)); CastToBase(&reserved_range_)->InternalSwap(CastToBase(&other->reserved_range_)); reserved_name_.InternalSwap(CastToBase(&other->reserved_name_)); - name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(options_, other->options_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata DescriptorProto::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata DescriptorProto::GetMetadata() const { + return GetMetadataStatic(); } @@ -3985,30 +4395,32 @@ void DescriptorProto::InternalSwap(DescriptorProto* other) { void ExtensionRangeOptions::InitAsDefaultInstance() { } +class ExtensionRangeOptions::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int ExtensionRangeOptions::kUninterpretedOptionFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 ExtensionRangeOptions::ExtensionRangeOptions() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.ExtensionRangeOptions) } -ExtensionRangeOptions::ExtensionRangeOptions(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +ExtensionRangeOptions::ExtensionRangeOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.ExtensionRangeOptions) } ExtensionRangeOptions::ExtensionRangeOptions(const ExtensionRangeOptions& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); @@ -4017,6 +4429,7 @@ ExtensionRangeOptions::ExtensionRangeOptions(const ExtensionRangeOptions& from) } void ExtensionRangeOptions::SharedCtor() { + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_ExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto.base); } ExtensionRangeOptions::~ExtensionRangeOptions() { @@ -4025,32 +4438,27 @@ ExtensionRangeOptions::~ExtensionRangeOptions() { } void ExtensionRangeOptions::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void ExtensionRangeOptions::ArenaDtor(void* object) { ExtensionRangeOptions* _this = reinterpret_cast< ExtensionRangeOptions* >(object); (void)_this; } -void ExtensionRangeOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void ExtensionRangeOptions::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void ExtensionRangeOptions::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* ExtensionRangeOptions::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const ExtensionRangeOptions& ExtensionRangeOptions::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_ExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void ExtensionRangeOptions::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.ExtensionRangeOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -4060,21 +4468,67 @@ void ExtensionRangeOptions::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* ExtensionRangeOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; + case 999: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { + ptr -= 2; + do { + ptr += 2; + ptr = ctx->ParseMessage(add_uninterpreted_option(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint16>(ptr) == 16058); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + if ((8000u <= tag)) { + ptr = _extensions_.ParseField(tag, ptr, + internal_default_instance(), &_internal_metadata_, ctx); + CHK_(ptr != nullptr); + continue; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool ExtensionRangeOptions::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.ExtensionRangeOptions) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; case 999: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (7994 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_uninterpreted_option())); } else { goto handle_unusual; @@ -4093,7 +4547,7 @@ bool ExtensionRangeOptions::MergePartialFromCodedStream( _internal_metadata_.mutable_unknown_fields())); continue; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -4107,54 +4561,53 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void ExtensionRangeOptions::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.ExtensionRangeOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 999, this->uninterpreted_option(static_cast(i)), output); } // Extension range [1000, 536870912) - _extensions_.SerializeWithCachedSizes( - 1000, 536870912, output); + _extensions_.SerializeWithCachedSizes(1000, 536870912, output); if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.ExtensionRangeOptions) } -::google::protobuf::uint8* ExtensionRangeOptions::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* ExtensionRangeOptions::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.ExtensionRangeOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 999, this->uninterpreted_option(static_cast(i)), deterministic, target); + 999, this->uninterpreted_option(static_cast(i)), target); } // Extension range [1000, 536870912) target = _extensions_.InternalSerializeWithCachedSizesToArray( - 1000, 536870912, deterministic, target); + 1000, 536870912, target); if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.ExtensionRangeOptions) @@ -4169,34 +4622,38 @@ size_t ExtensionRangeOptions::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; { unsigned int count = static_cast(this->uninterpreted_option_size()); total_size += 2UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->uninterpreted_option(static_cast(i))); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void ExtensionRangeOptions::MergeFrom(const ::google::protobuf::Message& from) { +void ExtensionRangeOptions::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.ExtensionRangeOptions) GOOGLE_DCHECK_NE(&from, this); const ExtensionRangeOptions* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.ExtensionRangeOptions) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.ExtensionRangeOptions) MergeFrom(*source); @@ -4208,13 +4665,13 @@ void ExtensionRangeOptions::MergeFrom(const ExtensionRangeOptions& from) { GOOGLE_DCHECK_NE(&from, this); _extensions_.MergeFrom(from._extensions_); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; uninterpreted_option_.MergeFrom(from.uninterpreted_option_); } -void ExtensionRangeOptions::CopyFrom(const ::google::protobuf::Message& from) { +void ExtensionRangeOptions::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.ExtensionRangeOptions) if (&from == this) return; Clear(); @@ -4233,7 +4690,7 @@ bool ExtensionRangeOptions::IsInitialized() const { return false; } - if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->uninterpreted_option())) return false; return true; } @@ -4246,7 +4703,7 @@ void ExtensionRangeOptions::Swap(ExtensionRangeOptions* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -4258,34 +4715,73 @@ void ExtensionRangeOptions::UnsafeArenaSwap(ExtensionRangeOptions* other) { } void ExtensionRangeOptions::InternalSwap(ExtensionRangeOptions* other) { using std::swap; - CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_)); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); _extensions_.Swap(&other->_extensions_); + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); + CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_)); } -::google::protobuf::Metadata ExtensionRangeOptions::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata ExtensionRangeOptions::GetMetadata() const { + return GetMetadataStatic(); } // =================================================================== void FieldDescriptorProto::InitAsDefaultInstance() { - ::google::protobuf::_FieldDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::FieldOptions*>( - ::google::protobuf::FieldOptions::internal_default_instance()); + PROTOBUF_NAMESPACE_ID::_FieldDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< PROTOBUF_NAMESPACE_ID::FieldOptions*>( + PROTOBUF_NAMESPACE_ID::FieldOptions::internal_default_instance()); +} +class FieldDescriptorProto::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_name(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static void set_has_number(HasBits* has_bits) { + (*has_bits)[0] |= 64u; + } + static void set_has_label(HasBits* has_bits) { + (*has_bits)[0] |= 256u; + } + static void set_has_type(HasBits* has_bits) { + (*has_bits)[0] |= 512u; + } + static void set_has_type_name(HasBits* has_bits) { + (*has_bits)[0] |= 4u; + } + static void set_has_extendee(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } + static void set_has_default_value(HasBits* has_bits) { + (*has_bits)[0] |= 8u; + } + static void set_has_oneof_index(HasBits* has_bits) { + (*has_bits)[0] |= 128u; + } + static void set_has_json_name(HasBits* has_bits) { + (*has_bits)[0] |= 16u; + } + static const PROTOBUF_NAMESPACE_ID::FieldOptions& options(const FieldDescriptorProto* msg); + static void set_has_options(HasBits* has_bits) { + (*has_bits)[0] |= 32u; + } +}; + +const PROTOBUF_NAMESPACE_ID::FieldOptions& +FieldDescriptorProto::HasBitSetters::options(const FieldDescriptorProto* msg) { + return *msg->options_; } void FieldDescriptorProto::unsafe_arena_set_allocated_options( - ::google::protobuf::FieldOptions* options) { - if (GetArenaNoVirtual() == NULL) { + PROTOBUF_NAMESPACE_ID::FieldOptions* options) { + if (GetArenaNoVirtual() == nullptr) { delete options_; } options_ = options; if (options) { - set_has_options(); + _has_bits_[0] |= 0x00000020u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000020u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.options) } @@ -4303,54 +4799,51 @@ const int FieldDescriptorProto::kOptionsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 FieldDescriptorProto::FieldDescriptorProto() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FieldDescriptorProto) } -FieldDescriptorProto::FieldDescriptorProto(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +FieldDescriptorProto::FieldDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.FieldDescriptorProto) } FieldDescriptorProto::FieldDescriptorProto(const FieldDescriptorProto& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(), + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name(), GetArenaNoVirtual()); } - extendee_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + extendee_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_extendee()) { - extendee_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.extendee(), + extendee_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.extendee(), GetArenaNoVirtual()); } - type_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + type_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_type_name()) { - type_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.type_name(), + type_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.type_name(), GetArenaNoVirtual()); } - default_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + default_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_default_value()) { - default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.default_value(), + default_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.default_value(), GetArenaNoVirtual()); } - json_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + json_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_json_name()) { - json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.json_name(), + json_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.json_name(), GetArenaNoVirtual()); } if (from.has_options()) { - options_ = new ::google::protobuf::FieldOptions(*from.options_); + options_ = new PROTOBUF_NAMESPACE_ID::FieldOptions(*from.options_); } else { - options_ = NULL; + options_ = nullptr; } ::memcpy(&number_, &from.number_, static_cast(reinterpret_cast(&type_) - @@ -4359,11 +4852,12 @@ FieldDescriptorProto::FieldDescriptorProto(const FieldDescriptorProto& from) } void FieldDescriptorProto::SharedCtor() { - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - extendee_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - type_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - default_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - json_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + extendee_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + type_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + default_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + json_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(&options_, 0, static_cast( reinterpret_cast(&oneof_index_) - reinterpret_cast(&options_)) + sizeof(oneof_index_)); @@ -4377,12 +4871,12 @@ FieldDescriptorProto::~FieldDescriptorProto() { } void FieldDescriptorProto::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - extendee_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - type_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - default_value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - json_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); + name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + extendee_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + type_name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + default_value_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + json_name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete options_; } @@ -4390,30 +4884,25 @@ void FieldDescriptorProto::ArenaDtor(void* object) { FieldDescriptorProto* _this = reinterpret_cast< FieldDescriptorProto* >(object); (void)_this; } -void FieldDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void FieldDescriptorProto::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void FieldDescriptorProto::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* FieldDescriptorProto::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const FieldDescriptorProto& FieldDescriptorProto::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void FieldDescriptorProto::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.FieldDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 63u) { + if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { name_.ClearNonDefaultToEmpty(); } @@ -4430,16 +4919,16 @@ void FieldDescriptorProto::Clear() { json_name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000020u) { - GOOGLE_DCHECK(options_ != NULL); + GOOGLE_DCHECK(options_ != nullptr); options_->Clear(); } } - if (cached_has_bits & 192u) { + if (cached_has_bits & 0x000000c0u) { ::memset(&number_, 0, static_cast( reinterpret_cast(&oneof_index_) - reinterpret_cast(&number_)) + sizeof(oneof_index_)); } - if (cached_has_bits & 768u) { + if (cached_has_bits & 0x00000300u) { label_ = 1; type_ = 1; } @@ -4447,25 +4936,137 @@ void FieldDescriptorProto::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* FieldDescriptorProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional string name = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_name(), ptr, ctx, "google.protobuf.FieldDescriptorProto.name"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string extendee = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_extendee(), ptr, ctx, "google.protobuf.FieldDescriptorProto.extendee"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional int32 number = 3; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) { + HasBitSetters::set_has_number(&has_bits); + number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional .google.protobuf.FieldDescriptorProto.Label label = 4; + case 4: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { + ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + if (PROTOBUF_PREDICT_TRUE(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label_IsValid(val))) { + set_label(static_cast(val)); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::WriteVarint(4, val, mutable_unknown_fields()); + } + } else goto handle_unusual; + continue; + // optional .google.protobuf.FieldDescriptorProto.Type type = 5; + case 5: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { + ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + if (PROTOBUF_PREDICT_TRUE(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type_IsValid(val))) { + set_type(static_cast(val)); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::WriteVarint(5, val, mutable_unknown_fields()); + } + } else goto handle_unusual; + continue; + // optional string type_name = 6; + case 6: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_type_name(), ptr, ctx, "google.protobuf.FieldDescriptorProto.type_name"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string default_value = 7; + case 7: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_default_value(), ptr, ctx, "google.protobuf.FieldDescriptorProto.default_value"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional .google.protobuf.FieldOptions options = 8; + case 8: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 66)) { + ptr = ctx->ParseMessage(mutable_options(), ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional int32 oneof_index = 9; + case 9: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 72)) { + HasBitSetters::set_has_oneof_index(&has_bits); + oneof_index_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string json_name = 10; + case 10: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 82)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_json_name(), ptr, ctx, "google.protobuf.FieldDescriptorProto.json_name"); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool FieldDescriptorProto::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FieldDescriptorProto) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional string name = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FieldDescriptorProto.name"); } else { goto handle_unusual; @@ -4475,13 +5076,12 @@ bool FieldDescriptorProto::MergePartialFromCodedStream( // optional string extendee = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_extendee())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->extendee().data(), static_cast(this->extendee().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FieldDescriptorProto.extendee"); } else { goto handle_unusual; @@ -4491,11 +5091,10 @@ bool FieldDescriptorProto::MergePartialFromCodedStream( // optional int32 number = 3; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { - set_has_number(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (24 & 0xFF)) { + HasBitSetters::set_has_number(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &number_))); } else { goto handle_unusual; @@ -4505,17 +5104,16 @@ bool FieldDescriptorProto::MergePartialFromCodedStream( // optional .google.protobuf.FieldDescriptorProto.Label label = 4; case 4: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) { - int value; - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (32 & 0xFF)) { + int value = 0; + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>( input, &value))); - if (::google::protobuf::FieldDescriptorProto_Label_IsValid(value)) { - set_label(static_cast< ::google::protobuf::FieldDescriptorProto_Label >(value)); + if (PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label_IsValid(value)) { + set_label(static_cast< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label >(value)); } else { mutable_unknown_fields()->AddVarint( - 4, static_cast< ::google::protobuf::uint64>(value)); + 4, static_cast<::PROTOBUF_NAMESPACE_ID::uint64>(value)); } } else { goto handle_unusual; @@ -4525,17 +5123,16 @@ bool FieldDescriptorProto::MergePartialFromCodedStream( // optional .google.protobuf.FieldDescriptorProto.Type type = 5; case 5: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { - int value; - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (40 & 0xFF)) { + int value = 0; + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>( input, &value))); - if (::google::protobuf::FieldDescriptorProto_Type_IsValid(value)) { - set_type(static_cast< ::google::protobuf::FieldDescriptorProto_Type >(value)); + if (PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type_IsValid(value)) { + set_type(static_cast< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type >(value)); } else { mutable_unknown_fields()->AddVarint( - 5, static_cast< ::google::protobuf::uint64>(value)); + 5, static_cast<::PROTOBUF_NAMESPACE_ID::uint64>(value)); } } else { goto handle_unusual; @@ -4545,13 +5142,12 @@ bool FieldDescriptorProto::MergePartialFromCodedStream( // optional string type_name = 6; case 6: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (50 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_type_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->type_name().data(), static_cast(this->type_name().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FieldDescriptorProto.type_name"); } else { goto handle_unusual; @@ -4561,13 +5157,12 @@ bool FieldDescriptorProto::MergePartialFromCodedStream( // optional string default_value = 7; case 7: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (58 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_default_value())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->default_value().data(), static_cast(this->default_value().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FieldDescriptorProto.default_value"); } else { goto handle_unusual; @@ -4577,9 +5172,8 @@ bool FieldDescriptorProto::MergePartialFromCodedStream( // optional .google.protobuf.FieldOptions options = 8; case 8: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (66 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, mutable_options())); } else { goto handle_unusual; @@ -4589,11 +5183,10 @@ bool FieldDescriptorProto::MergePartialFromCodedStream( // optional int32 oneof_index = 9; case 9: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(72u /* 72 & 0xFF */)) { - set_has_oneof_index(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (72 & 0xFF)) { + HasBitSetters::set_has_oneof_index(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &oneof_index_))); } else { goto handle_unusual; @@ -4603,13 +5196,12 @@ bool FieldDescriptorProto::MergePartialFromCodedStream( // optional string json_name = 10; case 10: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(82u /* 82 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (82 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_json_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->json_name().data(), static_cast(this->json_name().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FieldDescriptorProto.json_name"); } else { goto handle_unusual; @@ -4622,7 +5214,7 @@ bool FieldDescriptorProto::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -4636,193 +5228,193 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void FieldDescriptorProto::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.FieldDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FieldDescriptorProto.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // optional string extendee = 2; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->extendee().data(), static_cast(this->extendee().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FieldDescriptorProto.extendee"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->extendee(), output); } // optional int32 number = 3; if (cached_has_bits & 0x00000040u) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->number(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(3, this->number(), output); } // optional .google.protobuf.FieldDescriptorProto.Label label = 4; if (cached_has_bits & 0x00000100u) { - ::google::protobuf::internal::WireFormatLite::WriteEnum( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum( 4, this->label(), output); } // optional .google.protobuf.FieldDescriptorProto.Type type = 5; if (cached_has_bits & 0x00000200u) { - ::google::protobuf::internal::WireFormatLite::WriteEnum( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum( 5, this->type(), output); } // optional string type_name = 6; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->type_name().data(), static_cast(this->type_name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FieldDescriptorProto.type_name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 6, this->type_name(), output); } // optional string default_value = 7; if (cached_has_bits & 0x00000008u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->default_value().data(), static_cast(this->default_value().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FieldDescriptorProto.default_value"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 7, this->default_value(), output); } // optional .google.protobuf.FieldOptions options = 8; if (cached_has_bits & 0x00000020u) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 8, this->_internal_options(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( + 8, HasBitSetters::options(this), output); } // optional int32 oneof_index = 9; if (cached_has_bits & 0x00000080u) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(9, this->oneof_index(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(9, this->oneof_index(), output); } // optional string json_name = 10; if (cached_has_bits & 0x00000010u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->json_name().data(), static_cast(this->json_name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FieldDescriptorProto.json_name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 10, this->json_name(), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.FieldDescriptorProto) } -::google::protobuf::uint8* FieldDescriptorProto::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* FieldDescriptorProto::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FieldDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FieldDescriptorProto.name"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // optional string extendee = 2; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->extendee().data(), static_cast(this->extendee().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FieldDescriptorProto.extendee"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 2, this->extendee(), target); } // optional int32 number = 3; if (cached_has_bits & 0x00000040u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->number(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(3, this->number(), target); } // optional .google.protobuf.FieldDescriptorProto.Label label = 4; if (cached_has_bits & 0x00000100u) { - target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray( 4, this->label(), target); } // optional .google.protobuf.FieldDescriptorProto.Type type = 5; if (cached_has_bits & 0x00000200u) { - target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray( 5, this->type(), target); } // optional string type_name = 6; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->type_name().data(), static_cast(this->type_name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FieldDescriptorProto.type_name"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 6, this->type_name(), target); } // optional string default_value = 7; if (cached_has_bits & 0x00000008u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->default_value().data(), static_cast(this->default_value().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FieldDescriptorProto.default_value"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 7, this->default_value(), target); } // optional .google.protobuf.FieldOptions options = 8; if (cached_has_bits & 0x00000020u) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 8, this->_internal_options(), deterministic, target); + 8, HasBitSetters::options(this), target); } // optional int32 oneof_index = 9; if (cached_has_bits & 0x00000080u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(9, this->oneof_index(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(9, this->oneof_index(), target); } // optional string json_name = 10; if (cached_has_bits & 0x00000010u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->json_name().data(), static_cast(this->json_name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FieldDescriptorProto.json_name"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 10, this->json_name(), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FieldDescriptorProto) @@ -4835,95 +5427,100 @@ size_t FieldDescriptorProto::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } - if (_has_bits_[0 / 32] & 255u) { + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x000000ffu) { // optional string name = 1; - if (has_name()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->name()); } // optional string extendee = 2; - if (has_extendee()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->extendee()); } // optional string type_name = 6; - if (has_type_name()) { + if (cached_has_bits & 0x00000004u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->type_name()); } // optional string default_value = 7; - if (has_default_value()) { + if (cached_has_bits & 0x00000008u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->default_value()); } // optional string json_name = 10; - if (has_json_name()) { + if (cached_has_bits & 0x00000010u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->json_name()); } // optional .google.protobuf.FieldOptions options = 8; - if (has_options()) { + if (cached_has_bits & 0x00000020u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *options_); } // optional int32 number = 3; - if (has_number()) { + if (cached_has_bits & 0x00000040u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->number()); } // optional int32 oneof_index = 9; - if (has_oneof_index()) { + if (cached_has_bits & 0x00000080u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->oneof_index()); } } - if (_has_bits_[8 / 32] & 768u) { + if (cached_has_bits & 0x00000300u) { // optional .google.protobuf.FieldDescriptorProto.Label label = 4; - if (has_label()) { + if (cached_has_bits & 0x00000100u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::EnumSize(this->label()); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->label()); } // optional .google.protobuf.FieldDescriptorProto.Type type = 5; - if (has_type()) { + if (cached_has_bits & 0x00000200u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::EnumSize(this->type()); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->type()); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void FieldDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) { +void FieldDescriptorProto::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FieldDescriptorProto) GOOGLE_DCHECK_NE(&from, this); const FieldDescriptorProto* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.FieldDescriptorProto) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.FieldDescriptorProto) MergeFrom(*source); @@ -4934,11 +5531,11 @@ void FieldDescriptorProto::MergeFrom(const FieldDescriptorProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FieldDescriptorProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 255u) { + if (cached_has_bits & 0x000000ffu) { if (cached_has_bits & 0x00000001u) { set_name(from.name()); } @@ -4955,7 +5552,7 @@ void FieldDescriptorProto::MergeFrom(const FieldDescriptorProto& from) { set_json_name(from.json_name()); } if (cached_has_bits & 0x00000020u) { - mutable_options()->::google::protobuf::FieldOptions::MergeFrom(from.options()); + mutable_options()->PROTOBUF_NAMESPACE_ID::FieldOptions::MergeFrom(from.options()); } if (cached_has_bits & 0x00000040u) { number_ = from.number_; @@ -4965,7 +5562,7 @@ void FieldDescriptorProto::MergeFrom(const FieldDescriptorProto& from) { } _has_bits_[0] |= cached_has_bits; } - if (cached_has_bits & 768u) { + if (cached_has_bits & 0x00000300u) { if (cached_has_bits & 0x00000100u) { label_ = from.label_; } @@ -4976,7 +5573,7 @@ void FieldDescriptorProto::MergeFrom(const FieldDescriptorProto& from) { } } -void FieldDescriptorProto::CopyFrom(const ::google::protobuf::Message& from) { +void FieldDescriptorProto::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.FieldDescriptorProto) if (&from == this) return; Clear(); @@ -5006,7 +5603,7 @@ void FieldDescriptorProto::Swap(FieldDescriptorProto* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -5018,47 +5615,62 @@ void FieldDescriptorProto::UnsafeArenaSwap(FieldDescriptorProto* other) { } void FieldDescriptorProto::InternalSwap(FieldDescriptorProto* other) { using std::swap; - name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); + name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - extendee_.Swap(&other->extendee_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + extendee_.Swap(&other->extendee_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - type_name_.Swap(&other->type_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + type_name_.Swap(&other->type_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - default_value_.Swap(&other->default_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + default_value_.Swap(&other->default_value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - json_name_.Swap(&other->json_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + json_name_.Swap(&other->json_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(options_, other->options_); swap(number_, other->number_); swap(oneof_index_, other->oneof_index_); swap(label_, other->label_); swap(type_, other->type_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata FieldDescriptorProto::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata FieldDescriptorProto::GetMetadata() const { + return GetMetadataStatic(); } // =================================================================== void OneofDescriptorProto::InitAsDefaultInstance() { - ::google::protobuf::_OneofDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::OneofOptions*>( - ::google::protobuf::OneofOptions::internal_default_instance()); + PROTOBUF_NAMESPACE_ID::_OneofDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< PROTOBUF_NAMESPACE_ID::OneofOptions*>( + PROTOBUF_NAMESPACE_ID::OneofOptions::internal_default_instance()); +} +class OneofDescriptorProto::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_name(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static const PROTOBUF_NAMESPACE_ID::OneofOptions& options(const OneofDescriptorProto* msg); + static void set_has_options(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } +}; + +const PROTOBUF_NAMESPACE_ID::OneofOptions& +OneofDescriptorProto::HasBitSetters::options(const OneofDescriptorProto* msg) { + return *msg->options_; } void OneofDescriptorProto::unsafe_arena_set_allocated_options( - ::google::protobuf::OneofOptions* options) { - if (GetArenaNoVirtual() == NULL) { + PROTOBUF_NAMESPACE_ID::OneofOptions* options) { + if (GetArenaNoVirtual() == nullptr) { delete options_; } options_ = options; if (options) { - set_has_options(); + _has_bits_[0] |= 0x00000002u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000002u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.OneofDescriptorProto.options) } @@ -5068,41 +5680,39 @@ const int OneofDescriptorProto::kOptionsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 OneofDescriptorProto::OneofDescriptorProto() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.OneofDescriptorProto) } -OneofDescriptorProto::OneofDescriptorProto(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +OneofDescriptorProto::OneofDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.OneofDescriptorProto) } OneofDescriptorProto::OneofDescriptorProto(const OneofDescriptorProto& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(), + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name(), GetArenaNoVirtual()); } if (from.has_options()) { - options_ = new ::google::protobuf::OneofOptions(*from.options_); + options_ = new PROTOBUF_NAMESPACE_ID::OneofOptions(*from.options_); } else { - options_ = NULL; + options_ = nullptr; } // @@protoc_insertion_point(copy_constructor:google.protobuf.OneofDescriptorProto) } void OneofDescriptorProto::SharedCtor() { - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - options_ = NULL; + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_OneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + options_ = nullptr; } OneofDescriptorProto::~OneofDescriptorProto() { @@ -5111,8 +5721,8 @@ OneofDescriptorProto::~OneofDescriptorProto() { } void OneofDescriptorProto::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); + name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete options_; } @@ -5120,35 +5730,30 @@ void OneofDescriptorProto::ArenaDtor(void* object) { OneofDescriptorProto* _this = reinterpret_cast< OneofDescriptorProto* >(object); (void)_this; } -void OneofDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void OneofDescriptorProto::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void OneofDescriptorProto::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* OneofDescriptorProto::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const OneofDescriptorProto& OneofDescriptorProto::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_OneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void OneofDescriptorProto::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.OneofDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(options_ != NULL); + GOOGLE_DCHECK(options_ != nullptr); options_->Clear(); } } @@ -5156,25 +5761,69 @@ void OneofDescriptorProto::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* OneofDescriptorProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional string name = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_name(), ptr, ctx, "google.protobuf.OneofDescriptorProto.name"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional .google.protobuf.OneofOptions options = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { + ptr = ctx->ParseMessage(mutable_options(), ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool OneofDescriptorProto::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.OneofDescriptorProto) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional string name = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.OneofDescriptorProto.name"); } else { goto handle_unusual; @@ -5184,9 +5833,8 @@ bool OneofDescriptorProto::MergePartialFromCodedStream( // optional .google.protobuf.OneofOptions options = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, mutable_options())); } else { goto handle_unusual; @@ -5199,7 +5847,7 @@ bool OneofDescriptorProto::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -5213,65 +5861,65 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void OneofDescriptorProto::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.OneofDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.OneofDescriptorProto.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // optional .google.protobuf.OneofOptions options = 2; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 2, this->_internal_options(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( + 2, HasBitSetters::options(this), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.OneofDescriptorProto) } -::google::protobuf::uint8* OneofDescriptorProto::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* OneofDescriptorProto::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.OneofDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.OneofDescriptorProto.name"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // optional .google.protobuf.OneofOptions options = 2; if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 2, this->_internal_options(), deterministic, target); + 2, HasBitSetters::options(this), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.OneofDescriptorProto) @@ -5284,39 +5932,44 @@ size_t OneofDescriptorProto::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } - if (_has_bits_[0 / 32] & 3u) { + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x00000003u) { // optional string name = 1; - if (has_name()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->name()); } // optional .google.protobuf.OneofOptions options = 2; - if (has_options()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *options_); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void OneofDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) { +void OneofDescriptorProto::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.OneofDescriptorProto) GOOGLE_DCHECK_NE(&from, this); const OneofDescriptorProto* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.OneofDescriptorProto) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.OneofDescriptorProto) MergeFrom(*source); @@ -5327,21 +5980,21 @@ void OneofDescriptorProto::MergeFrom(const OneofDescriptorProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.OneofDescriptorProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { set_name(from.name()); } if (cached_has_bits & 0x00000002u) { - mutable_options()->::google::protobuf::OneofOptions::MergeFrom(from.options()); + mutable_options()->PROTOBUF_NAMESPACE_ID::OneofOptions::MergeFrom(from.options()); } } } -void OneofDescriptorProto::CopyFrom(const ::google::protobuf::Message& from) { +void OneofDescriptorProto::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.OneofDescriptorProto) if (&from == this) return; Clear(); @@ -5371,7 +6024,7 @@ void OneofDescriptorProto::Swap(OneofDescriptorProto* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -5383,16 +6036,15 @@ void OneofDescriptorProto::UnsafeArenaSwap(OneofDescriptorProto* other) { } void OneofDescriptorProto::InternalSwap(OneofDescriptorProto* other) { using std::swap; - name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); + name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(options_, other->options_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata OneofDescriptorProto::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata OneofDescriptorProto::GetMetadata() const { + return GetMetadataStatic(); } @@ -5400,29 +6052,37 @@ void OneofDescriptorProto::InternalSwap(OneofDescriptorProto* other) { void EnumDescriptorProto_EnumReservedRange::InitAsDefaultInstance() { } +class EnumDescriptorProto_EnumReservedRange::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_start(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static void set_has_end(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int EnumDescriptorProto_EnumReservedRange::kStartFieldNumber; const int EnumDescriptorProto_EnumReservedRange::kEndFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto_EnumReservedRange.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.EnumDescriptorProto.EnumReservedRange) } -EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto_EnumReservedRange.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumDescriptorProto.EnumReservedRange) } EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(const EnumDescriptorProto_EnumReservedRange& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&start_, &from.start_, @@ -5443,37 +6103,32 @@ EnumDescriptorProto_EnumReservedRange::~EnumDescriptorProto_EnumReservedRange() } void EnumDescriptorProto_EnumReservedRange::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void EnumDescriptorProto_EnumReservedRange::ArenaDtor(void* object) { EnumDescriptorProto_EnumReservedRange* _this = reinterpret_cast< EnumDescriptorProto_EnumReservedRange* >(object); (void)_this; } -void EnumDescriptorProto_EnumReservedRange::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void EnumDescriptorProto_EnumReservedRange::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void EnumDescriptorProto_EnumReservedRange::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* EnumDescriptorProto_EnumReservedRange::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const EnumDescriptorProto_EnumReservedRange& EnumDescriptorProto_EnumReservedRange::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto_EnumReservedRange.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_EnumDescriptorProto_EnumReservedRange_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void EnumDescriptorProto_EnumReservedRange::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.EnumDescriptorProto.EnumReservedRange) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { ::memset(&start_, 0, static_cast( reinterpret_cast(&end_) - reinterpret_cast(&start_)) + sizeof(end_)); @@ -5482,23 +6137,69 @@ void EnumDescriptorProto_EnumReservedRange::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* EnumDescriptorProto_EnumReservedRange::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional int32 start = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { + HasBitSetters::set_has_start(&has_bits); + start_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional int32 end = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { + HasBitSetters::set_has_end(&has_bits); + end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool EnumDescriptorProto_EnumReservedRange::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumDescriptorProto.EnumReservedRange) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional int32 start = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { - set_has_start(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) { + HasBitSetters::set_has_start(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &start_))); } else { goto handle_unusual; @@ -5508,11 +6209,10 @@ bool EnumDescriptorProto_EnumReservedRange::MergePartialFromCodedStream( // optional int32 end = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { - set_has_end(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (16 & 0xFF)) { + HasBitSetters::set_has_end(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &end_))); } else { goto handle_unusual; @@ -5525,7 +6225,7 @@ bool EnumDescriptorProto_EnumReservedRange::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -5539,51 +6239,51 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void EnumDescriptorProto_EnumReservedRange::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.EnumDescriptorProto.EnumReservedRange) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional int32 start = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->start(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(1, this->start(), output); } // optional int32 end = 2; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->end(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(2, this->end(), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.EnumDescriptorProto.EnumReservedRange) } -::google::protobuf::uint8* EnumDescriptorProto_EnumReservedRange::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* EnumDescriptorProto_EnumReservedRange::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.EnumDescriptorProto.EnumReservedRange) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional int32 start = 1; if (cached_has_bits & 0x00000001u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->start(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(1, this->start(), target); } // optional int32 end = 2; if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->end(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(2, this->end(), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumDescriptorProto.EnumReservedRange) @@ -5596,39 +6296,44 @@ size_t EnumDescriptorProto_EnumReservedRange::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } - if (_has_bits_[0 / 32] & 3u) { + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x00000003u) { // optional int32 start = 1; - if (has_start()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->start()); } // optional int32 end = 2; - if (has_end()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->end()); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void EnumDescriptorProto_EnumReservedRange::MergeFrom(const ::google::protobuf::Message& from) { +void EnumDescriptorProto_EnumReservedRange::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.EnumDescriptorProto.EnumReservedRange) GOOGLE_DCHECK_NE(&from, this); const EnumDescriptorProto_EnumReservedRange* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.EnumDescriptorProto.EnumReservedRange) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.EnumDescriptorProto.EnumReservedRange) MergeFrom(*source); @@ -5639,11 +6344,11 @@ void EnumDescriptorProto_EnumReservedRange::MergeFrom(const EnumDescriptorProto_ // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumDescriptorProto.EnumReservedRange) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { start_ = from.start_; } @@ -5654,7 +6359,7 @@ void EnumDescriptorProto_EnumReservedRange::MergeFrom(const EnumDescriptorProto_ } } -void EnumDescriptorProto_EnumReservedRange::CopyFrom(const ::google::protobuf::Message& from) { +void EnumDescriptorProto_EnumReservedRange::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.EnumDescriptorProto.EnumReservedRange) if (&from == this) return; Clear(); @@ -5681,7 +6386,7 @@ void EnumDescriptorProto_EnumReservedRange::Swap(EnumDescriptorProto_EnumReserve temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -5693,34 +6398,49 @@ void EnumDescriptorProto_EnumReservedRange::UnsafeArenaSwap(EnumDescriptorProto_ } void EnumDescriptorProto_EnumReservedRange::InternalSwap(EnumDescriptorProto_EnumReservedRange* other) { using std::swap; + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); swap(start_, other->start_); swap(end_, other->end_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata EnumDescriptorProto_EnumReservedRange::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata EnumDescriptorProto_EnumReservedRange::GetMetadata() const { + return GetMetadataStatic(); } // =================================================================== void EnumDescriptorProto::InitAsDefaultInstance() { - ::google::protobuf::_EnumDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::EnumOptions*>( - ::google::protobuf::EnumOptions::internal_default_instance()); + PROTOBUF_NAMESPACE_ID::_EnumDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< PROTOBUF_NAMESPACE_ID::EnumOptions*>( + PROTOBUF_NAMESPACE_ID::EnumOptions::internal_default_instance()); +} +class EnumDescriptorProto::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_name(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static const PROTOBUF_NAMESPACE_ID::EnumOptions& options(const EnumDescriptorProto* msg); + static void set_has_options(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } +}; + +const PROTOBUF_NAMESPACE_ID::EnumOptions& +EnumDescriptorProto::HasBitSetters::options(const EnumDescriptorProto* msg) { + return *msg->options_; } void EnumDescriptorProto::unsafe_arena_set_allocated_options( - ::google::protobuf::EnumOptions* options) { - if (GetArenaNoVirtual() == NULL) { + PROTOBUF_NAMESPACE_ID::EnumOptions* options) { + if (GetArenaNoVirtual() == nullptr) { delete options_; } options_ = options; if (options) { - set_has_options(); + _has_bits_[0] |= 0x00000002u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000002u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumDescriptorProto.options) } @@ -5733,47 +6453,45 @@ const int EnumDescriptorProto::kReservedNameFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 EnumDescriptorProto::EnumDescriptorProto() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.EnumDescriptorProto) } -EnumDescriptorProto::EnumDescriptorProto(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +EnumDescriptorProto::EnumDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena), value_(arena), reserved_range_(arena), reserved_name_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumDescriptorProto) } EnumDescriptorProto::EnumDescriptorProto(const EnumDescriptorProto& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), value_(from.value_), reserved_range_(from.reserved_range_), reserved_name_(from.reserved_name_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(), + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name(), GetArenaNoVirtual()); } if (from.has_options()) { - options_ = new ::google::protobuf::EnumOptions(*from.options_); + options_ = new PROTOBUF_NAMESPACE_ID::EnumOptions(*from.options_); } else { - options_ = NULL; + options_ = nullptr; } // @@protoc_insertion_point(copy_constructor:google.protobuf.EnumDescriptorProto) } void EnumDescriptorProto::SharedCtor() { - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - options_ = NULL; + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + options_ = nullptr; } EnumDescriptorProto::~EnumDescriptorProto() { @@ -5782,8 +6500,8 @@ EnumDescriptorProto::~EnumDescriptorProto() { } void EnumDescriptorProto::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); + name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete options_; } @@ -5791,25 +6509,20 @@ void EnumDescriptorProto::ArenaDtor(void* object) { EnumDescriptorProto* _this = reinterpret_cast< EnumDescriptorProto* >(object); (void)_this; } -void EnumDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void EnumDescriptorProto::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void EnumDescriptorProto::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* EnumDescriptorProto::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const EnumDescriptorProto& EnumDescriptorProto::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void EnumDescriptorProto::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.EnumDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -5817,12 +6530,12 @@ void EnumDescriptorProto::Clear() { reserved_range_.Clear(); reserved_name_.Clear(); cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(options_ != NULL); + GOOGLE_DCHECK(options_ != nullptr); options_->Clear(); } } @@ -5830,25 +6543,105 @@ void EnumDescriptorProto::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* EnumDescriptorProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional string name = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_name(), ptr, ctx, "google.protobuf.EnumDescriptorProto.name"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.EnumValueDescriptorProto value = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_value(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 18); + } else goto handle_unusual; + continue; + // optional .google.protobuf.EnumOptions options = 3; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { + ptr = ctx->ParseMessage(mutable_options(), ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4; + case 4: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_reserved_range(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 34); + } else goto handle_unusual; + continue; + // repeated string reserved_name = 5; + case 5: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) { + ptr -= 1; + do { + ptr += 1; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(add_reserved_name(), ptr, ctx, "google.protobuf.EnumDescriptorProto.reserved_name"); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 42); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool EnumDescriptorProto::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumDescriptorProto) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional string name = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.EnumDescriptorProto.name"); } else { goto handle_unusual; @@ -5858,9 +6651,8 @@ bool EnumDescriptorProto::MergePartialFromCodedStream( // repeated .google.protobuf.EnumValueDescriptorProto value = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_value())); } else { goto handle_unusual; @@ -5870,9 +6662,8 @@ bool EnumDescriptorProto::MergePartialFromCodedStream( // optional .google.protobuf.EnumOptions options = 3; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, mutable_options())); } else { goto handle_unusual; @@ -5882,9 +6673,8 @@ bool EnumDescriptorProto::MergePartialFromCodedStream( // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4; case 4: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (34 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_reserved_range())); } else { goto handle_unusual; @@ -5894,14 +6684,13 @@ bool EnumDescriptorProto::MergePartialFromCodedStream( // repeated string reserved_name = 5; case 5: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (42 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->add_reserved_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->reserved_name(this->reserved_name_size() - 1).data(), static_cast(this->reserved_name(this->reserved_name_size() - 1).length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.EnumDescriptorProto.reserved_name"); } else { goto handle_unusual; @@ -5914,7 +6703,7 @@ bool EnumDescriptorProto::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -5928,28 +6717,29 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void EnumDescriptorProto::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.EnumDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.EnumDescriptorProto.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // repeated .google.protobuf.EnumValueDescriptorProto value = 2; for (unsigned int i = 0, n = static_cast(this->value_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->value(static_cast(i)), output); @@ -5957,14 +6747,14 @@ void EnumDescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.EnumOptions options = 3; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, this->_internal_options(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( + 3, HasBitSetters::options(this), output); } // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4; for (unsigned int i = 0, n = static_cast(this->reserved_range_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 4, this->reserved_range(static_cast(i)), output); @@ -5972,75 +6762,74 @@ void EnumDescriptorProto::SerializeWithCachedSizes( // repeated string reserved_name = 5; for (int i = 0, n = this->reserved_name_size(); i < n; i++) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->reserved_name(i).data(), static_cast(this->reserved_name(i).length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.EnumDescriptorProto.reserved_name"); - ::google::protobuf::internal::WireFormatLite::WriteString( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteString( 5, this->reserved_name(i), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.EnumDescriptorProto) } -::google::protobuf::uint8* EnumDescriptorProto::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* EnumDescriptorProto::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.EnumDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.EnumDescriptorProto.name"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // repeated .google.protobuf.EnumValueDescriptorProto value = 2; for (unsigned int i = 0, n = static_cast(this->value_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 2, this->value(static_cast(i)), deterministic, target); + 2, this->value(static_cast(i)), target); } // optional .google.protobuf.EnumOptions options = 3; if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 3, this->_internal_options(), deterministic, target); + 3, HasBitSetters::options(this), target); } // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4; for (unsigned int i = 0, n = static_cast(this->reserved_range_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 4, this->reserved_range(static_cast(i)), deterministic, target); + 4, this->reserved_range(static_cast(i)), target); } // repeated string reserved_name = 5; for (int i = 0, n = this->reserved_name_size(); i < n; i++) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->reserved_name(i).data(), static_cast(this->reserved_name(i).length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.EnumDescriptorProto.reserved_name"); - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: WriteStringToArray(5, this->reserved_name(i), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumDescriptorProto) @@ -6053,16 +6842,20 @@ size_t EnumDescriptorProto::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.EnumValueDescriptorProto value = 2; { unsigned int count = static_cast(this->value_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->value(static_cast(i))); } } @@ -6073,49 +6866,50 @@ size_t EnumDescriptorProto::ByteSizeLong() const { total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->reserved_range(static_cast(i))); } } // repeated string reserved_name = 5; total_size += 1 * - ::google::protobuf::internal::FromIntSize(this->reserved_name_size()); + ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->reserved_name_size()); for (int i = 0, n = this->reserved_name_size(); i < n; i++) { - total_size += ::google::protobuf::internal::WireFormatLite::StringSize( + total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->reserved_name(i)); } - if (_has_bits_[0 / 32] & 3u) { + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x00000003u) { // optional string name = 1; - if (has_name()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->name()); } // optional .google.protobuf.EnumOptions options = 3; - if (has_options()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *options_); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void EnumDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) { +void EnumDescriptorProto::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.EnumDescriptorProto) GOOGLE_DCHECK_NE(&from, this); const EnumDescriptorProto* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.EnumDescriptorProto) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.EnumDescriptorProto) MergeFrom(*source); @@ -6126,24 +6920,24 @@ void EnumDescriptorProto::MergeFrom(const EnumDescriptorProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumDescriptorProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; value_.MergeFrom(from.value_); reserved_range_.MergeFrom(from.reserved_range_); reserved_name_.MergeFrom(from.reserved_name_); cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { set_name(from.name()); } if (cached_has_bits & 0x00000002u) { - mutable_options()->::google::protobuf::EnumOptions::MergeFrom(from.options()); + mutable_options()->PROTOBUF_NAMESPACE_ID::EnumOptions::MergeFrom(from.options()); } } } -void EnumDescriptorProto::CopyFrom(const ::google::protobuf::Message& from) { +void EnumDescriptorProto::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.EnumDescriptorProto) if (&from == this) return; Clear(); @@ -6158,7 +6952,7 @@ void EnumDescriptorProto::CopyFrom(const EnumDescriptorProto& from) { } bool EnumDescriptorProto::IsInitialized() const { - if (!::google::protobuf::internal::AllAreInitialized(this->value())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->value())) return false; if (has_options()) { if (!this->options_->IsInitialized()) return false; } @@ -6174,7 +6968,7 @@ void EnumDescriptorProto::Swap(EnumDescriptorProto* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -6186,38 +6980,56 @@ void EnumDescriptorProto::UnsafeArenaSwap(EnumDescriptorProto* other) { } void EnumDescriptorProto::InternalSwap(EnumDescriptorProto* other) { using std::swap; + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); CastToBase(&value_)->InternalSwap(CastToBase(&other->value_)); CastToBase(&reserved_range_)->InternalSwap(CastToBase(&other->reserved_range_)); reserved_name_.InternalSwap(CastToBase(&other->reserved_name_)); - name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(options_, other->options_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata EnumDescriptorProto::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata EnumDescriptorProto::GetMetadata() const { + return GetMetadataStatic(); } // =================================================================== void EnumValueDescriptorProto::InitAsDefaultInstance() { - ::google::protobuf::_EnumValueDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::EnumValueOptions*>( - ::google::protobuf::EnumValueOptions::internal_default_instance()); + PROTOBUF_NAMESPACE_ID::_EnumValueDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< PROTOBUF_NAMESPACE_ID::EnumValueOptions*>( + PROTOBUF_NAMESPACE_ID::EnumValueOptions::internal_default_instance()); +} +class EnumValueDescriptorProto::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_name(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static void set_has_number(HasBits* has_bits) { + (*has_bits)[0] |= 4u; + } + static const PROTOBUF_NAMESPACE_ID::EnumValueOptions& options(const EnumValueDescriptorProto* msg); + static void set_has_options(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } +}; + +const PROTOBUF_NAMESPACE_ID::EnumValueOptions& +EnumValueDescriptorProto::HasBitSetters::options(const EnumValueDescriptorProto* msg) { + return *msg->options_; } void EnumValueDescriptorProto::unsafe_arena_set_allocated_options( - ::google::protobuf::EnumValueOptions* options) { - if (GetArenaNoVirtual() == NULL) { + PROTOBUF_NAMESPACE_ID::EnumValueOptions* options) { + if (GetArenaNoVirtual() == nullptr) { delete options_; } options_ = options; if (options) { - set_has_options(); + _has_bits_[0] |= 0x00000002u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000002u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumValueDescriptorProto.options) } @@ -6228,41 +7040,39 @@ const int EnumValueDescriptorProto::kOptionsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 EnumValueDescriptorProto::EnumValueDescriptorProto() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.EnumValueDescriptorProto) } -EnumValueDescriptorProto::EnumValueDescriptorProto(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +EnumValueDescriptorProto::EnumValueDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValueDescriptorProto) } EnumValueDescriptorProto::EnumValueDescriptorProto(const EnumValueDescriptorProto& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(), + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name(), GetArenaNoVirtual()); } if (from.has_options()) { - options_ = new ::google::protobuf::EnumValueOptions(*from.options_); + options_ = new PROTOBUF_NAMESPACE_ID::EnumValueOptions(*from.options_); } else { - options_ = NULL; + options_ = nullptr; } number_ = from.number_; // @@protoc_insertion_point(copy_constructor:google.protobuf.EnumValueDescriptorProto) } void EnumValueDescriptorProto::SharedCtor() { - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_EnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(&options_, 0, static_cast( reinterpret_cast(&number_) - reinterpret_cast(&options_)) + sizeof(number_)); @@ -6274,8 +7084,8 @@ EnumValueDescriptorProto::~EnumValueDescriptorProto() { } void EnumValueDescriptorProto::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); + name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete options_; } @@ -6283,35 +7093,30 @@ void EnumValueDescriptorProto::ArenaDtor(void* object) { EnumValueDescriptorProto* _this = reinterpret_cast< EnumValueDescriptorProto* >(object); (void)_this; } -void EnumValueDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void EnumValueDescriptorProto::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void EnumValueDescriptorProto::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* EnumValueDescriptorProto::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const EnumValueDescriptorProto& EnumValueDescriptorProto::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_EnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void EnumValueDescriptorProto::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.EnumValueDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(options_ != NULL); + GOOGLE_DCHECK(options_ != nullptr); options_->Clear(); } } @@ -6320,25 +7125,77 @@ void EnumValueDescriptorProto::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* EnumValueDescriptorProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional string name = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_name(), ptr, ctx, "google.protobuf.EnumValueDescriptorProto.name"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional int32 number = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { + HasBitSetters::set_has_number(&has_bits); + number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional .google.protobuf.EnumValueOptions options = 3; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { + ptr = ctx->ParseMessage(mutable_options(), ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool EnumValueDescriptorProto::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumValueDescriptorProto) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional string name = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.EnumValueDescriptorProto.name"); } else { goto handle_unusual; @@ -6348,11 +7205,10 @@ bool EnumValueDescriptorProto::MergePartialFromCodedStream( // optional int32 number = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { - set_has_number(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (16 & 0xFF)) { + HasBitSetters::set_has_number(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &number_))); } else { goto handle_unusual; @@ -6362,9 +7218,8 @@ bool EnumValueDescriptorProto::MergePartialFromCodedStream( // optional .google.protobuf.EnumValueOptions options = 3; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, mutable_options())); } else { goto handle_unusual; @@ -6377,7 +7232,7 @@ bool EnumValueDescriptorProto::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -6391,75 +7246,75 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void EnumValueDescriptorProto::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.EnumValueDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.EnumValueDescriptorProto.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // optional int32 number = 2; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->number(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(2, this->number(), output); } // optional .google.protobuf.EnumValueOptions options = 3; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, this->_internal_options(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( + 3, HasBitSetters::options(this), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.EnumValueDescriptorProto) } -::google::protobuf::uint8* EnumValueDescriptorProto::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* EnumValueDescriptorProto::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.EnumValueDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.EnumValueDescriptorProto.name"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // optional int32 number = 2; if (cached_has_bits & 0x00000004u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->number(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(2, this->number(), target); } // optional .google.protobuf.EnumValueOptions options = 3; if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 3, this->_internal_options(), deterministic, target); + 3, HasBitSetters::options(this), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumValueDescriptorProto) @@ -6472,46 +7327,51 @@ size_t EnumValueDescriptorProto::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } - if (_has_bits_[0 / 32] & 7u) { + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x00000007u) { // optional string name = 1; - if (has_name()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->name()); } // optional .google.protobuf.EnumValueOptions options = 3; - if (has_options()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *options_); } // optional int32 number = 2; - if (has_number()) { + if (cached_has_bits & 0x00000004u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->number()); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void EnumValueDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) { +void EnumValueDescriptorProto::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.EnumValueDescriptorProto) GOOGLE_DCHECK_NE(&from, this); const EnumValueDescriptorProto* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.EnumValueDescriptorProto) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.EnumValueDescriptorProto) MergeFrom(*source); @@ -6522,16 +7382,16 @@ void EnumValueDescriptorProto::MergeFrom(const EnumValueDescriptorProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumValueDescriptorProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 7u) { + if (cached_has_bits & 0x00000007u) { if (cached_has_bits & 0x00000001u) { set_name(from.name()); } if (cached_has_bits & 0x00000002u) { - mutable_options()->::google::protobuf::EnumValueOptions::MergeFrom(from.options()); + mutable_options()->PROTOBUF_NAMESPACE_ID::EnumValueOptions::MergeFrom(from.options()); } if (cached_has_bits & 0x00000004u) { number_ = from.number_; @@ -6540,7 +7400,7 @@ void EnumValueDescriptorProto::MergeFrom(const EnumValueDescriptorProto& from) { } } -void EnumValueDescriptorProto::CopyFrom(const ::google::protobuf::Message& from) { +void EnumValueDescriptorProto::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.EnumValueDescriptorProto) if (&from == this) return; Clear(); @@ -6570,7 +7430,7 @@ void EnumValueDescriptorProto::Swap(EnumValueDescriptorProto* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -6582,36 +7442,51 @@ void EnumValueDescriptorProto::UnsafeArenaSwap(EnumValueDescriptorProto* other) } void EnumValueDescriptorProto::InternalSwap(EnumValueDescriptorProto* other) { using std::swap; - name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); + name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(options_, other->options_); swap(number_, other->number_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata EnumValueDescriptorProto::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata EnumValueDescriptorProto::GetMetadata() const { + return GetMetadataStatic(); } // =================================================================== void ServiceDescriptorProto::InitAsDefaultInstance() { - ::google::protobuf::_ServiceDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::ServiceOptions*>( - ::google::protobuf::ServiceOptions::internal_default_instance()); + PROTOBUF_NAMESPACE_ID::_ServiceDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< PROTOBUF_NAMESPACE_ID::ServiceOptions*>( + PROTOBUF_NAMESPACE_ID::ServiceOptions::internal_default_instance()); +} +class ServiceDescriptorProto::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_name(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static const PROTOBUF_NAMESPACE_ID::ServiceOptions& options(const ServiceDescriptorProto* msg); + static void set_has_options(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } +}; + +const PROTOBUF_NAMESPACE_ID::ServiceOptions& +ServiceDescriptorProto::HasBitSetters::options(const ServiceDescriptorProto* msg) { + return *msg->options_; } void ServiceDescriptorProto::unsafe_arena_set_allocated_options( - ::google::protobuf::ServiceOptions* options) { - if (GetArenaNoVirtual() == NULL) { + PROTOBUF_NAMESPACE_ID::ServiceOptions* options) { + if (GetArenaNoVirtual() == nullptr) { delete options_; } options_ = options; if (options) { - set_has_options(); + _has_bits_[0] |= 0x00000002u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000002u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.ServiceDescriptorProto.options) } @@ -6622,43 +7497,41 @@ const int ServiceDescriptorProto::kOptionsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 ServiceDescriptorProto::ServiceDescriptorProto() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.ServiceDescriptorProto) } -ServiceDescriptorProto::ServiceDescriptorProto(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +ServiceDescriptorProto::ServiceDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena), method_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.ServiceDescriptorProto) } ServiceDescriptorProto::ServiceDescriptorProto(const ServiceDescriptorProto& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), method_(from.method_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(), + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name(), GetArenaNoVirtual()); } if (from.has_options()) { - options_ = new ::google::protobuf::ServiceOptions(*from.options_); + options_ = new PROTOBUF_NAMESPACE_ID::ServiceOptions(*from.options_); } else { - options_ = NULL; + options_ = nullptr; } // @@protoc_insertion_point(copy_constructor:google.protobuf.ServiceDescriptorProto) } void ServiceDescriptorProto::SharedCtor() { - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - options_ = NULL; + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_ServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + options_ = nullptr; } ServiceDescriptorProto::~ServiceDescriptorProto() { @@ -6667,8 +7540,8 @@ ServiceDescriptorProto::~ServiceDescriptorProto() { } void ServiceDescriptorProto::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); + name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete options_; } @@ -6676,36 +7549,31 @@ void ServiceDescriptorProto::ArenaDtor(void* object) { ServiceDescriptorProto* _this = reinterpret_cast< ServiceDescriptorProto* >(object); (void)_this; } -void ServiceDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void ServiceDescriptorProto::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void ServiceDescriptorProto::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* ServiceDescriptorProto::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const ServiceDescriptorProto& ServiceDescriptorProto::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_ServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void ServiceDescriptorProto::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.ServiceDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; method_.Clear(); cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(options_ != NULL); + GOOGLE_DCHECK(options_ != nullptr); options_->Clear(); } } @@ -6713,25 +7581,81 @@ void ServiceDescriptorProto::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* ServiceDescriptorProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional string name = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_name(), ptr, ctx, "google.protobuf.ServiceDescriptorProto.name"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.MethodDescriptorProto method = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_method(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 18); + } else goto handle_unusual; + continue; + // optional .google.protobuf.ServiceOptions options = 3; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { + ptr = ctx->ParseMessage(mutable_options(), ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool ServiceDescriptorProto::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.ServiceDescriptorProto) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional string name = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.ServiceDescriptorProto.name"); } else { goto handle_unusual; @@ -6741,9 +7665,8 @@ bool ServiceDescriptorProto::MergePartialFromCodedStream( // repeated .google.protobuf.MethodDescriptorProto method = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_method())); } else { goto handle_unusual; @@ -6753,9 +7676,8 @@ bool ServiceDescriptorProto::MergePartialFromCodedStream( // optional .google.protobuf.ServiceOptions options = 3; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, mutable_options())); } else { goto handle_unusual; @@ -6768,7 +7690,7 @@ bool ServiceDescriptorProto::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -6782,28 +7704,29 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void ServiceDescriptorProto::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.ServiceDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.ServiceDescriptorProto.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // repeated .google.protobuf.MethodDescriptorProto method = 2; for (unsigned int i = 0, n = static_cast(this->method_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->method(static_cast(i)), output); @@ -6811,53 +7734,52 @@ void ServiceDescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.ServiceOptions options = 3; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, this->_internal_options(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( + 3, HasBitSetters::options(this), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.ServiceDescriptorProto) } -::google::protobuf::uint8* ServiceDescriptorProto::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* ServiceDescriptorProto::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.ServiceDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.ServiceDescriptorProto.name"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // repeated .google.protobuf.MethodDescriptorProto method = 2; for (unsigned int i = 0, n = static_cast(this->method_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 2, this->method(static_cast(i)), deterministic, target); + 2, this->method(static_cast(i)), target); } // optional .google.protobuf.ServiceOptions options = 3; if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 3, this->_internal_options(), deterministic, target); + 3, HasBitSetters::options(this), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.ServiceDescriptorProto) @@ -6870,50 +7792,55 @@ size_t ServiceDescriptorProto::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.MethodDescriptorProto method = 2; { unsigned int count = static_cast(this->method_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->method(static_cast(i))); } } - if (_has_bits_[0 / 32] & 3u) { + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x00000003u) { // optional string name = 1; - if (has_name()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->name()); } // optional .google.protobuf.ServiceOptions options = 3; - if (has_options()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *options_); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void ServiceDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) { +void ServiceDescriptorProto::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.ServiceDescriptorProto) GOOGLE_DCHECK_NE(&from, this); const ServiceDescriptorProto* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.ServiceDescriptorProto) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.ServiceDescriptorProto) MergeFrom(*source); @@ -6924,22 +7851,22 @@ void ServiceDescriptorProto::MergeFrom(const ServiceDescriptorProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.ServiceDescriptorProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; method_.MergeFrom(from.method_); cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { set_name(from.name()); } if (cached_has_bits & 0x00000002u) { - mutable_options()->::google::protobuf::ServiceOptions::MergeFrom(from.options()); + mutable_options()->PROTOBUF_NAMESPACE_ID::ServiceOptions::MergeFrom(from.options()); } } } -void ServiceDescriptorProto::CopyFrom(const ::google::protobuf::Message& from) { +void ServiceDescriptorProto::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.ServiceDescriptorProto) if (&from == this) return; Clear(); @@ -6954,7 +7881,7 @@ void ServiceDescriptorProto::CopyFrom(const ServiceDescriptorProto& from) { } bool ServiceDescriptorProto::IsInitialized() const { - if (!::google::protobuf::internal::AllAreInitialized(this->method())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->method())) return false; if (has_options()) { if (!this->options_->IsInitialized()) return false; } @@ -6970,7 +7897,7 @@ void ServiceDescriptorProto::Swap(ServiceDescriptorProto* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -6982,36 +7909,63 @@ void ServiceDescriptorProto::UnsafeArenaSwap(ServiceDescriptorProto* other) { } void ServiceDescriptorProto::InternalSwap(ServiceDescriptorProto* other) { using std::swap; + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); CastToBase(&method_)->InternalSwap(CastToBase(&other->method_)); - name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(options_, other->options_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata ServiceDescriptorProto::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata ServiceDescriptorProto::GetMetadata() const { + return GetMetadataStatic(); } // =================================================================== void MethodDescriptorProto::InitAsDefaultInstance() { - ::google::protobuf::_MethodDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::MethodOptions*>( - ::google::protobuf::MethodOptions::internal_default_instance()); + PROTOBUF_NAMESPACE_ID::_MethodDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< PROTOBUF_NAMESPACE_ID::MethodOptions*>( + PROTOBUF_NAMESPACE_ID::MethodOptions::internal_default_instance()); +} +class MethodDescriptorProto::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_name(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static void set_has_input_type(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } + static void set_has_output_type(HasBits* has_bits) { + (*has_bits)[0] |= 4u; + } + static const PROTOBUF_NAMESPACE_ID::MethodOptions& options(const MethodDescriptorProto* msg); + static void set_has_options(HasBits* has_bits) { + (*has_bits)[0] |= 8u; + } + static void set_has_client_streaming(HasBits* has_bits) { + (*has_bits)[0] |= 16u; + } + static void set_has_server_streaming(HasBits* has_bits) { + (*has_bits)[0] |= 32u; + } +}; + +const PROTOBUF_NAMESPACE_ID::MethodOptions& +MethodDescriptorProto::HasBitSetters::options(const MethodDescriptorProto* msg) { + return *msg->options_; } void MethodDescriptorProto::unsafe_arena_set_allocated_options( - ::google::protobuf::MethodOptions* options) { - if (GetArenaNoVirtual() == NULL) { + PROTOBUF_NAMESPACE_ID::MethodOptions* options) { + if (GetArenaNoVirtual() == nullptr) { delete options_; } options_ = options; if (options) { - set_has_options(); + _has_bits_[0] |= 0x00000008u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000008u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.MethodDescriptorProto.options) } @@ -7025,44 +7979,41 @@ const int MethodDescriptorProto::kServerStreamingFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 MethodDescriptorProto::MethodDescriptorProto() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.MethodDescriptorProto) } -MethodDescriptorProto::MethodDescriptorProto(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +MethodDescriptorProto::MethodDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.MethodDescriptorProto) } MethodDescriptorProto::MethodDescriptorProto(const MethodDescriptorProto& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(), + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name(), GetArenaNoVirtual()); } - input_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + input_type_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_input_type()) { - input_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.input_type(), + input_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.input_type(), GetArenaNoVirtual()); } - output_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + output_type_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_output_type()) { - output_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.output_type(), + output_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.output_type(), GetArenaNoVirtual()); } if (from.has_options()) { - options_ = new ::google::protobuf::MethodOptions(*from.options_); + options_ = new PROTOBUF_NAMESPACE_ID::MethodOptions(*from.options_); } else { - options_ = NULL; + options_ = nullptr; } ::memcpy(&client_streaming_, &from.client_streaming_, static_cast(reinterpret_cast(&server_streaming_) - @@ -7071,9 +8022,10 @@ MethodDescriptorProto::MethodDescriptorProto(const MethodDescriptorProto& from) } void MethodDescriptorProto::SharedCtor() { - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - input_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - output_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_MethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base); + name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + input_type_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + output_type_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(&options_, 0, static_cast( reinterpret_cast(&server_streaming_) - reinterpret_cast(&options_)) + sizeof(server_streaming_)); @@ -7085,10 +8037,10 @@ MethodDescriptorProto::~MethodDescriptorProto() { } void MethodDescriptorProto::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - input_type_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - output_type_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); + name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + input_type_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + output_type_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete options_; } @@ -7096,30 +8048,25 @@ void MethodDescriptorProto::ArenaDtor(void* object) { MethodDescriptorProto* _this = reinterpret_cast< MethodDescriptorProto* >(object); (void)_this; } -void MethodDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void MethodDescriptorProto::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void MethodDescriptorProto::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* MethodDescriptorProto::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const MethodDescriptorProto& MethodDescriptorProto::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_MethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void MethodDescriptorProto::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.MethodDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 15u) { + if (cached_has_bits & 0x0000000fu) { if (cached_has_bits & 0x00000001u) { name_.ClearNonDefaultToEmpty(); } @@ -7130,7 +8077,7 @@ void MethodDescriptorProto::Clear() { output_type_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { - GOOGLE_DCHECK(options_ != NULL); + GOOGLE_DCHECK(options_ != nullptr); options_->Clear(); } } @@ -7141,25 +8088,99 @@ void MethodDescriptorProto::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* MethodDescriptorProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional string name = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_name(), ptr, ctx, "google.protobuf.MethodDescriptorProto.name"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string input_type = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_input_type(), ptr, ctx, "google.protobuf.MethodDescriptorProto.input_type"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string output_type = 3; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_output_type(), ptr, ctx, "google.protobuf.MethodDescriptorProto.output_type"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional .google.protobuf.MethodOptions options = 4; + case 4: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { + ptr = ctx->ParseMessage(mutable_options(), ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional bool client_streaming = 5 [default = false]; + case 5: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { + HasBitSetters::set_has_client_streaming(&has_bits); + client_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional bool server_streaming = 6 [default = false]; + case 6: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) { + HasBitSetters::set_has_server_streaming(&has_bits); + server_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool MethodDescriptorProto::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.MethodDescriptorProto) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional string name = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.MethodDescriptorProto.name"); } else { goto handle_unusual; @@ -7169,13 +8190,12 @@ bool MethodDescriptorProto::MergePartialFromCodedStream( // optional string input_type = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_input_type())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->input_type().data(), static_cast(this->input_type().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.MethodDescriptorProto.input_type"); } else { goto handle_unusual; @@ -7185,13 +8205,12 @@ bool MethodDescriptorProto::MergePartialFromCodedStream( // optional string output_type = 3; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_output_type())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->output_type().data(), static_cast(this->output_type().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.MethodDescriptorProto.output_type"); } else { goto handle_unusual; @@ -7201,9 +8220,8 @@ bool MethodDescriptorProto::MergePartialFromCodedStream( // optional .google.protobuf.MethodOptions options = 4; case 4: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (34 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, mutable_options())); } else { goto handle_unusual; @@ -7213,11 +8231,10 @@ bool MethodDescriptorProto::MergePartialFromCodedStream( // optional bool client_streaming = 5 [default = false]; case 5: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { - set_has_client_streaming(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (40 & 0xFF)) { + HasBitSetters::set_has_client_streaming(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &client_streaming_))); } else { goto handle_unusual; @@ -7227,11 +8244,10 @@ bool MethodDescriptorProto::MergePartialFromCodedStream( // optional bool server_streaming = 6 [default = false]; case 6: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) { - set_has_server_streaming(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (48 & 0xFF)) { + HasBitSetters::set_has_server_streaming(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &server_streaming_))); } else { goto handle_unusual; @@ -7244,7 +8260,7 @@ bool MethodDescriptorProto::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -7258,127 +8274,127 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void MethodDescriptorProto::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.MethodDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.MethodDescriptorProto.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // optional string input_type = 2; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->input_type().data(), static_cast(this->input_type().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.MethodDescriptorProto.input_type"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->input_type(), output); } // optional string output_type = 3; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->output_type().data(), static_cast(this->output_type().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.MethodDescriptorProto.output_type"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 3, this->output_type(), output); } // optional .google.protobuf.MethodOptions options = 4; if (cached_has_bits & 0x00000008u) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 4, this->_internal_options(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( + 4, HasBitSetters::options(this), output); } // optional bool client_streaming = 5 [default = false]; if (cached_has_bits & 0x00000010u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(5, this->client_streaming(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(5, this->client_streaming(), output); } // optional bool server_streaming = 6 [default = false]; if (cached_has_bits & 0x00000020u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(6, this->server_streaming(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(6, this->server_streaming(), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.MethodDescriptorProto) } -::google::protobuf::uint8* MethodDescriptorProto::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* MethodDescriptorProto::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.MethodDescriptorProto) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.MethodDescriptorProto.name"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // optional string input_type = 2; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->input_type().data(), static_cast(this->input_type().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.MethodDescriptorProto.input_type"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 2, this->input_type(), target); } // optional string output_type = 3; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->output_type().data(), static_cast(this->output_type().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.MethodDescriptorProto.output_type"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 3, this->output_type(), target); } // optional .google.protobuf.MethodOptions options = 4; if (cached_has_bits & 0x00000008u) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 4, this->_internal_options(), deterministic, target); + 4, HasBitSetters::options(this), target); } // optional bool client_streaming = 5 [default = false]; if (cached_has_bits & 0x00000010u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(5, this->client_streaming(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(5, this->client_streaming(), target); } // optional bool server_streaming = 6 [default = false]; if (cached_has_bits & 0x00000020u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(6, this->server_streaming(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(6, this->server_streaming(), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.MethodDescriptorProto) @@ -7391,63 +8407,68 @@ size_t MethodDescriptorProto::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } - if (_has_bits_[0 / 32] & 63u) { + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x0000003fu) { // optional string name = 1; - if (has_name()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->name()); } // optional string input_type = 2; - if (has_input_type()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->input_type()); } // optional string output_type = 3; - if (has_output_type()) { + if (cached_has_bits & 0x00000004u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->output_type()); } // optional .google.protobuf.MethodOptions options = 4; - if (has_options()) { + if (cached_has_bits & 0x00000008u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *options_); } // optional bool client_streaming = 5 [default = false]; - if (has_client_streaming()) { + if (cached_has_bits & 0x00000010u) { total_size += 1 + 1; } // optional bool server_streaming = 6 [default = false]; - if (has_server_streaming()) { + if (cached_has_bits & 0x00000020u) { total_size += 1 + 1; } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void MethodDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) { +void MethodDescriptorProto::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.MethodDescriptorProto) GOOGLE_DCHECK_NE(&from, this); const MethodDescriptorProto* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.MethodDescriptorProto) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.MethodDescriptorProto) MergeFrom(*source); @@ -7458,11 +8479,11 @@ void MethodDescriptorProto::MergeFrom(const MethodDescriptorProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.MethodDescriptorProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 63u) { + if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { set_name(from.name()); } @@ -7473,7 +8494,7 @@ void MethodDescriptorProto::MergeFrom(const MethodDescriptorProto& from) { set_output_type(from.output_type()); } if (cached_has_bits & 0x00000008u) { - mutable_options()->::google::protobuf::MethodOptions::MergeFrom(from.options()); + mutable_options()->PROTOBUF_NAMESPACE_ID::MethodOptions::MergeFrom(from.options()); } if (cached_has_bits & 0x00000010u) { client_streaming_ = from.client_streaming_; @@ -7485,7 +8506,7 @@ void MethodDescriptorProto::MergeFrom(const MethodDescriptorProto& from) { } } -void MethodDescriptorProto::CopyFrom(const ::google::protobuf::Message& from) { +void MethodDescriptorProto::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.MethodDescriptorProto) if (&from == this) return; Clear(); @@ -7515,7 +8536,7 @@ void MethodDescriptorProto::Swap(MethodDescriptorProto* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -7527,22 +8548,21 @@ void MethodDescriptorProto::UnsafeArenaSwap(MethodDescriptorProto* other) { } void MethodDescriptorProto::InternalSwap(MethodDescriptorProto* other) { using std::swap; - name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); + name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - input_type_.Swap(&other->input_type_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + input_type_.Swap(&other->input_type_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - output_type_.Swap(&other->output_type_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + output_type_.Swap(&other->output_type_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(options_, other->options_); swap(client_streaming_, other->client_streaming_); swap(server_streaming_, other->server_streaming_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata MethodDescriptorProto::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata MethodDescriptorProto::GetMetadata() const { + return GetMetadataStatic(); } @@ -7550,6 +8570,71 @@ void MethodDescriptorProto::InternalSwap(MethodDescriptorProto* other) { void FileOptions::InitAsDefaultInstance() { } +class FileOptions::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_java_package(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static void set_has_java_outer_classname(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } + static void set_has_java_multiple_files(HasBits* has_bits) { + (*has_bits)[0] |= 1024u; + } + static void set_has_java_generate_equals_and_hash(HasBits* has_bits) { + (*has_bits)[0] |= 2048u; + } + static void set_has_java_string_check_utf8(HasBits* has_bits) { + (*has_bits)[0] |= 4096u; + } + static void set_has_optimize_for(HasBits* has_bits) { + (*has_bits)[0] |= 524288u; + } + static void set_has_go_package(HasBits* has_bits) { + (*has_bits)[0] |= 4u; + } + static void set_has_cc_generic_services(HasBits* has_bits) { + (*has_bits)[0] |= 8192u; + } + static void set_has_java_generic_services(HasBits* has_bits) { + (*has_bits)[0] |= 16384u; + } + static void set_has_py_generic_services(HasBits* has_bits) { + (*has_bits)[0] |= 32768u; + } + static void set_has_php_generic_services(HasBits* has_bits) { + (*has_bits)[0] |= 65536u; + } + static void set_has_deprecated(HasBits* has_bits) { + (*has_bits)[0] |= 131072u; + } + static void set_has_cc_enable_arenas(HasBits* has_bits) { + (*has_bits)[0] |= 262144u; + } + static void set_has_objc_class_prefix(HasBits* has_bits) { + (*has_bits)[0] |= 8u; + } + static void set_has_csharp_namespace(HasBits* has_bits) { + (*has_bits)[0] |= 16u; + } + static void set_has_swift_prefix(HasBits* has_bits) { + (*has_bits)[0] |= 32u; + } + static void set_has_php_class_prefix(HasBits* has_bits) { + (*has_bits)[0] |= 64u; + } + static void set_has_php_namespace(HasBits* has_bits) { + (*has_bits)[0] |= 128u; + } + static void set_has_php_metadata_namespace(HasBits* has_bits) { + (*has_bits)[0] |= 256u; + } + static void set_has_ruby_package(HasBits* has_bits) { + (*has_bits)[0] |= 512u; + } +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int FileOptions::kJavaPackageFieldNumber; const int FileOptions::kJavaOuterClassnameFieldNumber; @@ -7575,77 +8660,74 @@ const int FileOptions::kUninterpretedOptionFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 FileOptions::FileOptions() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FileOptions) } -FileOptions::FileOptions(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +FileOptions::FileOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.FileOptions) } FileOptions::FileOptions(const FileOptions& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); - java_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + java_package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_java_package()) { - java_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.java_package(), + java_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.java_package(), GetArenaNoVirtual()); } - java_outer_classname_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + java_outer_classname_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_java_outer_classname()) { - java_outer_classname_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.java_outer_classname(), + java_outer_classname_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.java_outer_classname(), GetArenaNoVirtual()); } - go_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + go_package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_go_package()) { - go_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.go_package(), + go_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.go_package(), GetArenaNoVirtual()); } - objc_class_prefix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + objc_class_prefix_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_objc_class_prefix()) { - objc_class_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.objc_class_prefix(), + objc_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.objc_class_prefix(), GetArenaNoVirtual()); } - csharp_namespace_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + csharp_namespace_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_csharp_namespace()) { - csharp_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.csharp_namespace(), + csharp_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.csharp_namespace(), GetArenaNoVirtual()); } - swift_prefix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + swift_prefix_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_swift_prefix()) { - swift_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.swift_prefix(), + swift_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.swift_prefix(), GetArenaNoVirtual()); } - php_class_prefix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + php_class_prefix_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_php_class_prefix()) { - php_class_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.php_class_prefix(), + php_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.php_class_prefix(), GetArenaNoVirtual()); } - php_namespace_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + php_namespace_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_php_namespace()) { - php_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.php_namespace(), + php_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.php_namespace(), GetArenaNoVirtual()); } - php_metadata_namespace_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + php_metadata_namespace_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_php_metadata_namespace()) { - php_metadata_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.php_metadata_namespace(), + php_metadata_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.php_metadata_namespace(), GetArenaNoVirtual()); } - ruby_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ruby_package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_ruby_package()) { - ruby_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.ruby_package(), + ruby_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.ruby_package(), GetArenaNoVirtual()); } ::memcpy(&java_multiple_files_, &from.java_multiple_files_, @@ -7655,16 +8737,17 @@ FileOptions::FileOptions(const FileOptions& from) } void FileOptions::SharedCtor() { - java_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - java_outer_classname_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - go_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - objc_class_prefix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - csharp_namespace_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - swift_prefix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - php_class_prefix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - php_namespace_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - php_metadata_namespace_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ruby_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_FileOptions_google_2fprotobuf_2fdescriptor_2eproto.base); + java_package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + java_outer_classname_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + go_package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + objc_class_prefix_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + csharp_namespace_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + swift_prefix_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + php_class_prefix_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + php_namespace_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + php_metadata_namespace_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + ruby_package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(&java_multiple_files_, 0, static_cast( reinterpret_cast(&cc_enable_arenas_) - reinterpret_cast(&java_multiple_files_)) + sizeof(cc_enable_arenas_)); @@ -7677,49 +8760,44 @@ FileOptions::~FileOptions() { } void FileOptions::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); - java_package_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - java_outer_classname_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - go_package_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - objc_class_prefix_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - csharp_namespace_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - swift_prefix_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - php_class_prefix_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - php_namespace_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - php_metadata_namespace_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ruby_package_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); + java_package_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + java_outer_classname_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + go_package_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + objc_class_prefix_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + csharp_namespace_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + swift_prefix_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + php_class_prefix_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + php_namespace_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + php_metadata_namespace_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + ruby_package_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void FileOptions::ArenaDtor(void* object) { FileOptions* _this = reinterpret_cast< FileOptions* >(object); (void)_this; } -void FileOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void FileOptions::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void FileOptions::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* FileOptions::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const FileOptions& FileOptions::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_FileOptions_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void FileOptions::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.FileOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; _extensions_.Clear(); uninterpreted_option_.Clear(); cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 255u) { + if (cached_has_bits & 0x000000ffu) { if (cached_has_bits & 0x00000001u) { java_package_.ClearNonDefaultToEmpty(); } @@ -7745,7 +8823,7 @@ void FileOptions::Clear() { php_namespace_.ClearNonDefaultToEmpty(); } } - if (cached_has_bits & 768u) { + if (cached_has_bits & 0x00000300u) { if (cached_has_bits & 0x00000100u) { php_metadata_namespace_.ClearNonDefaultToEmpty(); } @@ -7753,12 +8831,12 @@ void FileOptions::Clear() { ruby_package_.ClearNonDefaultToEmpty(); } } - if (cached_has_bits & 64512u) { + if (cached_has_bits & 0x0000fc00u) { ::memset(&java_multiple_files_, 0, static_cast( reinterpret_cast(&py_generic_services_) - reinterpret_cast(&java_multiple_files_)) + sizeof(py_generic_services_)); } - if (cached_has_bits & 983040u) { + if (cached_has_bits & 0x000f0000u) { ::memset(&php_generic_services_, 0, static_cast( reinterpret_cast(&cc_enable_arenas_) - reinterpret_cast(&php_generic_services_)) + sizeof(cc_enable_arenas_)); @@ -7768,25 +8846,227 @@ void FileOptions::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* FileOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional string java_package = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_java_package(), ptr, ctx, "google.protobuf.FileOptions.java_package"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string java_outer_classname = 8; + case 8: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 66)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_java_outer_classname(), ptr, ctx, "google.protobuf.FileOptions.java_outer_classname"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; + case 9: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 72)) { + ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + if (PROTOBUF_PREDICT_TRUE(PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode_IsValid(val))) { + set_optimize_for(static_cast(val)); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::WriteVarint(9, val, mutable_unknown_fields()); + } + } else goto handle_unusual; + continue; + // optional bool java_multiple_files = 10 [default = false]; + case 10: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 80)) { + HasBitSetters::set_has_java_multiple_files(&has_bits); + java_multiple_files_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string go_package = 11; + case 11: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 90)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_go_package(), ptr, ctx, "google.protobuf.FileOptions.go_package"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional bool cc_generic_services = 16 [default = false]; + case 16: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 128)) { + HasBitSetters::set_has_cc_generic_services(&has_bits); + cc_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional bool java_generic_services = 17 [default = false]; + case 17: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 136)) { + HasBitSetters::set_has_java_generic_services(&has_bits); + java_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional bool py_generic_services = 18 [default = false]; + case 18: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 144)) { + HasBitSetters::set_has_py_generic_services(&has_bits); + py_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional bool java_generate_equals_and_hash = 20 [deprecated = true]; + case 20: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 160)) { + HasBitSetters::set_has_java_generate_equals_and_hash(&has_bits); + java_generate_equals_and_hash_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional bool deprecated = 23 [default = false]; + case 23: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 184)) { + HasBitSetters::set_has_deprecated(&has_bits); + deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional bool java_string_check_utf8 = 27 [default = false]; + case 27: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 216)) { + HasBitSetters::set_has_java_string_check_utf8(&has_bits); + java_string_check_utf8_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional bool cc_enable_arenas = 31 [default = false]; + case 31: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 248)) { + HasBitSetters::set_has_cc_enable_arenas(&has_bits); + cc_enable_arenas_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string objc_class_prefix = 36; + case 36: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_objc_class_prefix(), ptr, ctx, "google.protobuf.FileOptions.objc_class_prefix"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string csharp_namespace = 37; + case 37: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_csharp_namespace(), ptr, ctx, "google.protobuf.FileOptions.csharp_namespace"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string swift_prefix = 39; + case 39: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_swift_prefix(), ptr, ctx, "google.protobuf.FileOptions.swift_prefix"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string php_class_prefix = 40; + case 40: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 66)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_php_class_prefix(), ptr, ctx, "google.protobuf.FileOptions.php_class_prefix"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string php_namespace = 41; + case 41: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 74)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_php_namespace(), ptr, ctx, "google.protobuf.FileOptions.php_namespace"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional bool php_generic_services = 42 [default = false]; + case 42: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 80)) { + HasBitSetters::set_has_php_generic_services(&has_bits); + php_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string php_metadata_namespace = 44; + case 44: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 98)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_php_metadata_namespace(), ptr, ctx, "google.protobuf.FileOptions.php_metadata_namespace"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string ruby_package = 45; + case 45: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 106)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_ruby_package(), ptr, ctx, "google.protobuf.FileOptions.ruby_package"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; + case 999: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { + ptr -= 2; + do { + ptr += 2; + ptr = ctx->ParseMessage(add_uninterpreted_option(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint16>(ptr) == 16058); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + if ((8000u <= tag)) { + ptr = _extensions_.ParseField(tag, ptr, + internal_default_instance(), &_internal_metadata_, ctx); + CHK_(ptr != nullptr); + continue; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool FileOptions::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FileOptions) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional string java_package = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_java_package())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->java_package().data(), static_cast(this->java_package().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FileOptions.java_package"); } else { goto handle_unusual; @@ -7796,13 +9076,12 @@ bool FileOptions::MergePartialFromCodedStream( // optional string java_outer_classname = 8; case 8: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (66 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_java_outer_classname())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->java_outer_classname().data(), static_cast(this->java_outer_classname().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FileOptions.java_outer_classname"); } else { goto handle_unusual; @@ -7812,17 +9091,16 @@ bool FileOptions::MergePartialFromCodedStream( // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; case 9: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(72u /* 72 & 0xFF */)) { - int value; - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (72 & 0xFF)) { + int value = 0; + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>( input, &value))); - if (::google::protobuf::FileOptions_OptimizeMode_IsValid(value)) { - set_optimize_for(static_cast< ::google::protobuf::FileOptions_OptimizeMode >(value)); + if (PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode_IsValid(value)) { + set_optimize_for(static_cast< PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode >(value)); } else { mutable_unknown_fields()->AddVarint( - 9, static_cast< ::google::protobuf::uint64>(value)); + 9, static_cast<::PROTOBUF_NAMESPACE_ID::uint64>(value)); } } else { goto handle_unusual; @@ -7832,11 +9110,10 @@ bool FileOptions::MergePartialFromCodedStream( // optional bool java_multiple_files = 10 [default = false]; case 10: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(80u /* 80 & 0xFF */)) { - set_has_java_multiple_files(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (80 & 0xFF)) { + HasBitSetters::set_has_java_multiple_files(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &java_multiple_files_))); } else { goto handle_unusual; @@ -7846,13 +9123,12 @@ bool FileOptions::MergePartialFromCodedStream( // optional string go_package = 11; case 11: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(90u /* 90 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (90 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_go_package())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->go_package().data(), static_cast(this->go_package().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FileOptions.go_package"); } else { goto handle_unusual; @@ -7862,11 +9138,10 @@ bool FileOptions::MergePartialFromCodedStream( // optional bool cc_generic_services = 16 [default = false]; case 16: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(128u /* 128 & 0xFF */)) { - set_has_cc_generic_services(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (128 & 0xFF)) { + HasBitSetters::set_has_cc_generic_services(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &cc_generic_services_))); } else { goto handle_unusual; @@ -7876,11 +9151,10 @@ bool FileOptions::MergePartialFromCodedStream( // optional bool java_generic_services = 17 [default = false]; case 17: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(136u /* 136 & 0xFF */)) { - set_has_java_generic_services(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (136 & 0xFF)) { + HasBitSetters::set_has_java_generic_services(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &java_generic_services_))); } else { goto handle_unusual; @@ -7890,11 +9164,10 @@ bool FileOptions::MergePartialFromCodedStream( // optional bool py_generic_services = 18 [default = false]; case 18: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(144u /* 144 & 0xFF */)) { - set_has_py_generic_services(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (144 & 0xFF)) { + HasBitSetters::set_has_py_generic_services(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &py_generic_services_))); } else { goto handle_unusual; @@ -7904,11 +9177,10 @@ bool FileOptions::MergePartialFromCodedStream( // optional bool java_generate_equals_and_hash = 20 [deprecated = true]; case 20: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(160u /* 160 & 0xFF */)) { - set_has_java_generate_equals_and_hash(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (160 & 0xFF)) { + HasBitSetters::set_has_java_generate_equals_and_hash(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &java_generate_equals_and_hash_))); } else { goto handle_unusual; @@ -7918,11 +9190,10 @@ bool FileOptions::MergePartialFromCodedStream( // optional bool deprecated = 23 [default = false]; case 23: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(184u /* 184 & 0xFF */)) { - set_has_deprecated(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (184 & 0xFF)) { + HasBitSetters::set_has_deprecated(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &deprecated_))); } else { goto handle_unusual; @@ -7932,11 +9203,10 @@ bool FileOptions::MergePartialFromCodedStream( // optional bool java_string_check_utf8 = 27 [default = false]; case 27: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(216u /* 216 & 0xFF */)) { - set_has_java_string_check_utf8(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (216 & 0xFF)) { + HasBitSetters::set_has_java_string_check_utf8(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &java_string_check_utf8_))); } else { goto handle_unusual; @@ -7946,11 +9216,10 @@ bool FileOptions::MergePartialFromCodedStream( // optional bool cc_enable_arenas = 31 [default = false]; case 31: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(248u /* 248 & 0xFF */)) { - set_has_cc_enable_arenas(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (248 & 0xFF)) { + HasBitSetters::set_has_cc_enable_arenas(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &cc_enable_arenas_))); } else { goto handle_unusual; @@ -7960,13 +9229,12 @@ bool FileOptions::MergePartialFromCodedStream( // optional string objc_class_prefix = 36; case 36: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(34u /* 290 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (290 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_objc_class_prefix())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->objc_class_prefix().data(), static_cast(this->objc_class_prefix().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FileOptions.objc_class_prefix"); } else { goto handle_unusual; @@ -7976,13 +9244,12 @@ bool FileOptions::MergePartialFromCodedStream( // optional string csharp_namespace = 37; case 37: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(42u /* 298 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (298 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_csharp_namespace())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->csharp_namespace().data(), static_cast(this->csharp_namespace().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FileOptions.csharp_namespace"); } else { goto handle_unusual; @@ -7992,13 +9259,12 @@ bool FileOptions::MergePartialFromCodedStream( // optional string swift_prefix = 39; case 39: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(58u /* 314 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (314 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_swift_prefix())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->swift_prefix().data(), static_cast(this->swift_prefix().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FileOptions.swift_prefix"); } else { goto handle_unusual; @@ -8008,13 +9274,12 @@ bool FileOptions::MergePartialFromCodedStream( // optional string php_class_prefix = 40; case 40: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(66u /* 322 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (322 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_php_class_prefix())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->php_class_prefix().data(), static_cast(this->php_class_prefix().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FileOptions.php_class_prefix"); } else { goto handle_unusual; @@ -8024,13 +9289,12 @@ bool FileOptions::MergePartialFromCodedStream( // optional string php_namespace = 41; case 41: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(74u /* 330 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (330 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_php_namespace())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->php_namespace().data(), static_cast(this->php_namespace().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FileOptions.php_namespace"); } else { goto handle_unusual; @@ -8040,11 +9304,10 @@ bool FileOptions::MergePartialFromCodedStream( // optional bool php_generic_services = 42 [default = false]; case 42: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(80u /* 336 & 0xFF */)) { - set_has_php_generic_services(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (336 & 0xFF)) { + HasBitSetters::set_has_php_generic_services(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &php_generic_services_))); } else { goto handle_unusual; @@ -8054,13 +9317,12 @@ bool FileOptions::MergePartialFromCodedStream( // optional string php_metadata_namespace = 44; case 44: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(98u /* 354 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (354 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_php_metadata_namespace())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->php_metadata_namespace().data(), static_cast(this->php_metadata_namespace().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FileOptions.php_metadata_namespace"); } else { goto handle_unusual; @@ -8070,13 +9332,12 @@ bool FileOptions::MergePartialFromCodedStream( // optional string ruby_package = 45; case 45: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(106u /* 362 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (362 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_ruby_package())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->ruby_package().data(), static_cast(this->ruby_package().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.FileOptions.ruby_package"); } else { goto handle_unusual; @@ -8086,9 +9347,8 @@ bool FileOptions::MergePartialFromCodedStream( // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; case 999: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (7994 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_uninterpreted_option())); } else { goto handle_unusual; @@ -8107,7 +9367,7 @@ bool FileOptions::MergePartialFromCodedStream( _internal_metadata_.mutable_unknown_fields())); continue; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -8121,368 +9381,367 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void FileOptions::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.FileOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string java_package = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->java_package().data(), static_cast(this->java_package().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.java_package"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->java_package(), output); } // optional string java_outer_classname = 8; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->java_outer_classname().data(), static_cast(this->java_outer_classname().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.java_outer_classname"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 8, this->java_outer_classname(), output); } // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; if (cached_has_bits & 0x00080000u) { - ::google::protobuf::internal::WireFormatLite::WriteEnum( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum( 9, this->optimize_for(), output); } // optional bool java_multiple_files = 10 [default = false]; if (cached_has_bits & 0x00000400u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(10, this->java_multiple_files(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(10, this->java_multiple_files(), output); } // optional string go_package = 11; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->go_package().data(), static_cast(this->go_package().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.go_package"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 11, this->go_package(), output); } // optional bool cc_generic_services = 16 [default = false]; if (cached_has_bits & 0x00002000u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(16, this->cc_generic_services(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(16, this->cc_generic_services(), output); } // optional bool java_generic_services = 17 [default = false]; if (cached_has_bits & 0x00004000u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(17, this->java_generic_services(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(17, this->java_generic_services(), output); } // optional bool py_generic_services = 18 [default = false]; if (cached_has_bits & 0x00008000u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(18, this->py_generic_services(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(18, this->py_generic_services(), output); } // optional bool java_generate_equals_and_hash = 20 [deprecated = true]; if (cached_has_bits & 0x00000800u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(20, this->java_generate_equals_and_hash(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(20, this->java_generate_equals_and_hash(), output); } // optional bool deprecated = 23 [default = false]; if (cached_has_bits & 0x00020000u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(23, this->deprecated(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(23, this->deprecated(), output); } // optional bool java_string_check_utf8 = 27 [default = false]; if (cached_has_bits & 0x00001000u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(27, this->java_string_check_utf8(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(27, this->java_string_check_utf8(), output); } // optional bool cc_enable_arenas = 31 [default = false]; if (cached_has_bits & 0x00040000u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(31, this->cc_enable_arenas(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(31, this->cc_enable_arenas(), output); } // optional string objc_class_prefix = 36; if (cached_has_bits & 0x00000008u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->objc_class_prefix().data(), static_cast(this->objc_class_prefix().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.objc_class_prefix"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 36, this->objc_class_prefix(), output); } // optional string csharp_namespace = 37; if (cached_has_bits & 0x00000010u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->csharp_namespace().data(), static_cast(this->csharp_namespace().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.csharp_namespace"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 37, this->csharp_namespace(), output); } // optional string swift_prefix = 39; if (cached_has_bits & 0x00000020u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->swift_prefix().data(), static_cast(this->swift_prefix().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.swift_prefix"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 39, this->swift_prefix(), output); } // optional string php_class_prefix = 40; if (cached_has_bits & 0x00000040u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->php_class_prefix().data(), static_cast(this->php_class_prefix().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.php_class_prefix"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 40, this->php_class_prefix(), output); } // optional string php_namespace = 41; if (cached_has_bits & 0x00000080u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->php_namespace().data(), static_cast(this->php_namespace().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.php_namespace"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 41, this->php_namespace(), output); } // optional bool php_generic_services = 42 [default = false]; if (cached_has_bits & 0x00010000u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(42, this->php_generic_services(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(42, this->php_generic_services(), output); } // optional string php_metadata_namespace = 44; if (cached_has_bits & 0x00000100u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->php_metadata_namespace().data(), static_cast(this->php_metadata_namespace().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.php_metadata_namespace"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 44, this->php_metadata_namespace(), output); } // optional string ruby_package = 45; if (cached_has_bits & 0x00000200u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->ruby_package().data(), static_cast(this->ruby_package().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.ruby_package"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 45, this->ruby_package(), output); } // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 999, this->uninterpreted_option(static_cast(i)), output); } // Extension range [1000, 536870912) - _extensions_.SerializeWithCachedSizes( - 1000, 536870912, output); + _extensions_.SerializeWithCachedSizes(1000, 536870912, output); if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.FileOptions) } -::google::protobuf::uint8* FileOptions::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* FileOptions::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FileOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string java_package = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->java_package().data(), static_cast(this->java_package().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.java_package"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 1, this->java_package(), target); } // optional string java_outer_classname = 8; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->java_outer_classname().data(), static_cast(this->java_outer_classname().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.java_outer_classname"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 8, this->java_outer_classname(), target); } // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; if (cached_has_bits & 0x00080000u) { - target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray( 9, this->optimize_for(), target); } // optional bool java_multiple_files = 10 [default = false]; if (cached_has_bits & 0x00000400u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(10, this->java_multiple_files(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(10, this->java_multiple_files(), target); } // optional string go_package = 11; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->go_package().data(), static_cast(this->go_package().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.go_package"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 11, this->go_package(), target); } // optional bool cc_generic_services = 16 [default = false]; if (cached_has_bits & 0x00002000u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(16, this->cc_generic_services(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(16, this->cc_generic_services(), target); } // optional bool java_generic_services = 17 [default = false]; if (cached_has_bits & 0x00004000u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(17, this->java_generic_services(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(17, this->java_generic_services(), target); } // optional bool py_generic_services = 18 [default = false]; if (cached_has_bits & 0x00008000u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(18, this->py_generic_services(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(18, this->py_generic_services(), target); } // optional bool java_generate_equals_and_hash = 20 [deprecated = true]; if (cached_has_bits & 0x00000800u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(20, this->java_generate_equals_and_hash(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(20, this->java_generate_equals_and_hash(), target); } // optional bool deprecated = 23 [default = false]; if (cached_has_bits & 0x00020000u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(23, this->deprecated(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(23, this->deprecated(), target); } // optional bool java_string_check_utf8 = 27 [default = false]; if (cached_has_bits & 0x00001000u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(27, this->java_string_check_utf8(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(27, this->java_string_check_utf8(), target); } // optional bool cc_enable_arenas = 31 [default = false]; if (cached_has_bits & 0x00040000u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(31, this->cc_enable_arenas(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(31, this->cc_enable_arenas(), target); } // optional string objc_class_prefix = 36; if (cached_has_bits & 0x00000008u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->objc_class_prefix().data(), static_cast(this->objc_class_prefix().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.objc_class_prefix"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 36, this->objc_class_prefix(), target); } // optional string csharp_namespace = 37; if (cached_has_bits & 0x00000010u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->csharp_namespace().data(), static_cast(this->csharp_namespace().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.csharp_namespace"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 37, this->csharp_namespace(), target); } // optional string swift_prefix = 39; if (cached_has_bits & 0x00000020u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->swift_prefix().data(), static_cast(this->swift_prefix().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.swift_prefix"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 39, this->swift_prefix(), target); } // optional string php_class_prefix = 40; if (cached_has_bits & 0x00000040u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->php_class_prefix().data(), static_cast(this->php_class_prefix().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.php_class_prefix"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 40, this->php_class_prefix(), target); } // optional string php_namespace = 41; if (cached_has_bits & 0x00000080u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->php_namespace().data(), static_cast(this->php_namespace().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.php_namespace"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 41, this->php_namespace(), target); } // optional bool php_generic_services = 42 [default = false]; if (cached_has_bits & 0x00010000u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(42, this->php_generic_services(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(42, this->php_generic_services(), target); } // optional string php_metadata_namespace = 44; if (cached_has_bits & 0x00000100u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->php_metadata_namespace().data(), static_cast(this->php_metadata_namespace().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.php_metadata_namespace"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 44, this->php_metadata_namespace(), target); } // optional string ruby_package = 45; if (cached_has_bits & 0x00000200u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->ruby_package().data(), static_cast(this->ruby_package().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.FileOptions.ruby_package"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 45, this->ruby_package(), target); } // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 999, this->uninterpreted_option(static_cast(i)), deterministic, target); + 999, this->uninterpreted_option(static_cast(i)), target); } // Extension range [1000, 536870912) target = _extensions_.InternalSerializeWithCachedSizesToArray( - 1000, 536870912, deterministic, target); + 1000, 536870912, target); if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FileOptions) @@ -8497,161 +9756,166 @@ size_t FileOptions::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; { unsigned int count = static_cast(this->uninterpreted_option_size()); total_size += 2UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->uninterpreted_option(static_cast(i))); } } - if (_has_bits_[0 / 32] & 255u) { + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x000000ffu) { // optional string java_package = 1; - if (has_java_package()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->java_package()); } // optional string java_outer_classname = 8; - if (has_java_outer_classname()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->java_outer_classname()); } // optional string go_package = 11; - if (has_go_package()) { + if (cached_has_bits & 0x00000004u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->go_package()); } // optional string objc_class_prefix = 36; - if (has_objc_class_prefix()) { + if (cached_has_bits & 0x00000008u) { total_size += 2 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->objc_class_prefix()); } // optional string csharp_namespace = 37; - if (has_csharp_namespace()) { + if (cached_has_bits & 0x00000010u) { total_size += 2 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->csharp_namespace()); } // optional string swift_prefix = 39; - if (has_swift_prefix()) { + if (cached_has_bits & 0x00000020u) { total_size += 2 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->swift_prefix()); } // optional string php_class_prefix = 40; - if (has_php_class_prefix()) { + if (cached_has_bits & 0x00000040u) { total_size += 2 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->php_class_prefix()); } // optional string php_namespace = 41; - if (has_php_namespace()) { + if (cached_has_bits & 0x00000080u) { total_size += 2 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->php_namespace()); } } - if (_has_bits_[8 / 32] & 65280u) { + if (cached_has_bits & 0x0000ff00u) { // optional string php_metadata_namespace = 44; - if (has_php_metadata_namespace()) { + if (cached_has_bits & 0x00000100u) { total_size += 2 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->php_metadata_namespace()); } // optional string ruby_package = 45; - if (has_ruby_package()) { + if (cached_has_bits & 0x00000200u) { total_size += 2 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->ruby_package()); } // optional bool java_multiple_files = 10 [default = false]; - if (has_java_multiple_files()) { + if (cached_has_bits & 0x00000400u) { total_size += 1 + 1; } // optional bool java_generate_equals_and_hash = 20 [deprecated = true]; - if (has_java_generate_equals_and_hash()) { + if (cached_has_bits & 0x00000800u) { total_size += 2 + 1; } // optional bool java_string_check_utf8 = 27 [default = false]; - if (has_java_string_check_utf8()) { + if (cached_has_bits & 0x00001000u) { total_size += 2 + 1; } // optional bool cc_generic_services = 16 [default = false]; - if (has_cc_generic_services()) { + if (cached_has_bits & 0x00002000u) { total_size += 2 + 1; } // optional bool java_generic_services = 17 [default = false]; - if (has_java_generic_services()) { + if (cached_has_bits & 0x00004000u) { total_size += 2 + 1; } // optional bool py_generic_services = 18 [default = false]; - if (has_py_generic_services()) { + if (cached_has_bits & 0x00008000u) { total_size += 2 + 1; } } - if (_has_bits_[16 / 32] & 983040u) { + if (cached_has_bits & 0x000f0000u) { // optional bool php_generic_services = 42 [default = false]; - if (has_php_generic_services()) { + if (cached_has_bits & 0x00010000u) { total_size += 2 + 1; } // optional bool deprecated = 23 [default = false]; - if (has_deprecated()) { + if (cached_has_bits & 0x00020000u) { total_size += 2 + 1; } // optional bool cc_enable_arenas = 31 [default = false]; - if (has_cc_enable_arenas()) { + if (cached_has_bits & 0x00040000u) { total_size += 2 + 1; } // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; - if (has_optimize_for()) { + if (cached_has_bits & 0x00080000u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::EnumSize(this->optimize_for()); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->optimize_for()); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void FileOptions::MergeFrom(const ::google::protobuf::Message& from) { +void FileOptions::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FileOptions) GOOGLE_DCHECK_NE(&from, this); const FileOptions* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.FileOptions) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.FileOptions) MergeFrom(*source); @@ -8663,12 +9927,12 @@ void FileOptions::MergeFrom(const FileOptions& from) { GOOGLE_DCHECK_NE(&from, this); _extensions_.MergeFrom(from._extensions_); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; uninterpreted_option_.MergeFrom(from.uninterpreted_option_); cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 255u) { + if (cached_has_bits & 0x000000ffu) { if (cached_has_bits & 0x00000001u) { set_java_package(from.java_package()); } @@ -8694,7 +9958,7 @@ void FileOptions::MergeFrom(const FileOptions& from) { set_php_namespace(from.php_namespace()); } } - if (cached_has_bits & 65280u) { + if (cached_has_bits & 0x0000ff00u) { if (cached_has_bits & 0x00000100u) { set_php_metadata_namespace(from.php_metadata_namespace()); } @@ -8721,7 +9985,7 @@ void FileOptions::MergeFrom(const FileOptions& from) { } _has_bits_[0] |= cached_has_bits; } - if (cached_has_bits & 983040u) { + if (cached_has_bits & 0x000f0000u) { if (cached_has_bits & 0x00010000u) { php_generic_services_ = from.php_generic_services_; } @@ -8738,7 +10002,7 @@ void FileOptions::MergeFrom(const FileOptions& from) { } } -void FileOptions::CopyFrom(const ::google::protobuf::Message& from) { +void FileOptions::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.FileOptions) if (&from == this) return; Clear(); @@ -8757,7 +10021,7 @@ bool FileOptions::IsInitialized() const { return false; } - if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->uninterpreted_option())) return false; return true; } @@ -8770,7 +10034,7 @@ void FileOptions::Swap(FileOptions* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -8782,26 +10046,29 @@ void FileOptions::UnsafeArenaSwap(FileOptions* other) { } void FileOptions::InternalSwap(FileOptions* other) { using std::swap; + _extensions_.Swap(&other->_extensions_); + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_)); - java_package_.Swap(&other->java_package_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + java_package_.Swap(&other->java_package_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - java_outer_classname_.Swap(&other->java_outer_classname_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + java_outer_classname_.Swap(&other->java_outer_classname_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - go_package_.Swap(&other->go_package_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + go_package_.Swap(&other->go_package_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - objc_class_prefix_.Swap(&other->objc_class_prefix_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + objc_class_prefix_.Swap(&other->objc_class_prefix_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - csharp_namespace_.Swap(&other->csharp_namespace_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + csharp_namespace_.Swap(&other->csharp_namespace_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - swift_prefix_.Swap(&other->swift_prefix_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + swift_prefix_.Swap(&other->swift_prefix_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - php_class_prefix_.Swap(&other->php_class_prefix_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + php_class_prefix_.Swap(&other->php_class_prefix_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - php_namespace_.Swap(&other->php_namespace_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + php_namespace_.Swap(&other->php_namespace_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - php_metadata_namespace_.Swap(&other->php_metadata_namespace_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + php_metadata_namespace_.Swap(&other->php_metadata_namespace_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - ruby_package_.Swap(&other->ruby_package_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + ruby_package_.Swap(&other->ruby_package_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(java_multiple_files_, other->java_multiple_files_); swap(java_generate_equals_and_hash_, other->java_generate_equals_and_hash_); @@ -8813,14 +10080,10 @@ void FileOptions::InternalSwap(FileOptions* other) { swap(deprecated_, other->deprecated_); swap(cc_enable_arenas_, other->cc_enable_arenas_); swap(optimize_for_, other->optimize_for_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); - _extensions_.Swap(&other->_extensions_); } -::google::protobuf::Metadata FileOptions::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata FileOptions::GetMetadata() const { + return GetMetadataStatic(); } @@ -8828,6 +10091,23 @@ void FileOptions::InternalSwap(FileOptions* other) { void MessageOptions::InitAsDefaultInstance() { } +class MessageOptions::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_message_set_wire_format(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static void set_has_no_standard_descriptor_accessor(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } + static void set_has_deprecated(HasBits* has_bits) { + (*has_bits)[0] |= 4u; + } + static void set_has_map_entry(HasBits* has_bits) { + (*has_bits)[0] |= 8u; + } +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int MessageOptions::kMessageSetWireFormatFieldNumber; const int MessageOptions::kNoStandardDescriptorAccessorFieldNumber; @@ -8837,25 +10117,22 @@ const int MessageOptions::kUninterpretedOptionFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 MessageOptions::MessageOptions() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.MessageOptions) } -MessageOptions::MessageOptions(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +MessageOptions::MessageOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.MessageOptions) } MessageOptions::MessageOptions(const MessageOptions& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); @@ -8867,6 +10144,7 @@ MessageOptions::MessageOptions(const MessageOptions& from) } void MessageOptions::SharedCtor() { + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_MessageOptions_google_2fprotobuf_2fdescriptor_2eproto.base); ::memset(&message_set_wire_format_, 0, static_cast( reinterpret_cast(&map_entry_) - reinterpret_cast(&message_set_wire_format_)) + sizeof(map_entry_)); @@ -8878,32 +10156,27 @@ MessageOptions::~MessageOptions() { } void MessageOptions::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void MessageOptions::ArenaDtor(void* object) { MessageOptions* _this = reinterpret_cast< MessageOptions* >(object); (void)_this; } -void MessageOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void MessageOptions::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void MessageOptions::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* MessageOptions::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const MessageOptions& MessageOptions::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_MessageOptions_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void MessageOptions::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.MessageOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -8916,23 +10189,103 @@ void MessageOptions::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* MessageOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional bool message_set_wire_format = 1 [default = false]; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { + HasBitSetters::set_has_message_set_wire_format(&has_bits); + message_set_wire_format_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional bool no_standard_descriptor_accessor = 2 [default = false]; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { + HasBitSetters::set_has_no_standard_descriptor_accessor(&has_bits); + no_standard_descriptor_accessor_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional bool deprecated = 3 [default = false]; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) { + HasBitSetters::set_has_deprecated(&has_bits); + deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional bool map_entry = 7; + case 7: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 56)) { + HasBitSetters::set_has_map_entry(&has_bits); + map_entry_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; + case 999: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { + ptr -= 2; + do { + ptr += 2; + ptr = ctx->ParseMessage(add_uninterpreted_option(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint16>(ptr) == 16058); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + if ((8000u <= tag)) { + ptr = _extensions_.ParseField(tag, ptr, + internal_default_instance(), &_internal_metadata_, ctx); + CHK_(ptr != nullptr); + continue; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool MessageOptions::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.MessageOptions) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional bool message_set_wire_format = 1 [default = false]; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { - set_has_message_set_wire_format(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) { + HasBitSetters::set_has_message_set_wire_format(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &message_set_wire_format_))); } else { goto handle_unusual; @@ -8942,11 +10295,10 @@ bool MessageOptions::MergePartialFromCodedStream( // optional bool no_standard_descriptor_accessor = 2 [default = false]; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { - set_has_no_standard_descriptor_accessor(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (16 & 0xFF)) { + HasBitSetters::set_has_no_standard_descriptor_accessor(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &no_standard_descriptor_accessor_))); } else { goto handle_unusual; @@ -8956,11 +10308,10 @@ bool MessageOptions::MergePartialFromCodedStream( // optional bool deprecated = 3 [default = false]; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { - set_has_deprecated(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (24 & 0xFF)) { + HasBitSetters::set_has_deprecated(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &deprecated_))); } else { goto handle_unusual; @@ -8970,11 +10321,10 @@ bool MessageOptions::MergePartialFromCodedStream( // optional bool map_entry = 7; case 7: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) { - set_has_map_entry(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (56 & 0xFF)) { + HasBitSetters::set_has_map_entry(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &map_entry_))); } else { goto handle_unusual; @@ -8984,9 +10334,8 @@ bool MessageOptions::MergePartialFromCodedStream( // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; case 999: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (7994 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_uninterpreted_option())); } else { goto handle_unusual; @@ -9005,7 +10354,7 @@ bool MessageOptions::MergePartialFromCodedStream( _internal_metadata_.mutable_unknown_fields())); continue; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -9019,96 +10368,95 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void MessageOptions::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.MessageOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional bool message_set_wire_format = 1 [default = false]; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(1, this->message_set_wire_format(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(1, this->message_set_wire_format(), output); } // optional bool no_standard_descriptor_accessor = 2 [default = false]; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(2, this->no_standard_descriptor_accessor(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(2, this->no_standard_descriptor_accessor(), output); } // optional bool deprecated = 3 [default = false]; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(3, this->deprecated(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(3, this->deprecated(), output); } // optional bool map_entry = 7; if (cached_has_bits & 0x00000008u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(7, this->map_entry(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(7, this->map_entry(), output); } // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 999, this->uninterpreted_option(static_cast(i)), output); } // Extension range [1000, 536870912) - _extensions_.SerializeWithCachedSizes( - 1000, 536870912, output); + _extensions_.SerializeWithCachedSizes(1000, 536870912, output); if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.MessageOptions) } -::google::protobuf::uint8* MessageOptions::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* MessageOptions::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.MessageOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional bool message_set_wire_format = 1 [default = false]; if (cached_has_bits & 0x00000001u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(1, this->message_set_wire_format(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(1, this->message_set_wire_format(), target); } // optional bool no_standard_descriptor_accessor = 2 [default = false]; if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->no_standard_descriptor_accessor(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(2, this->no_standard_descriptor_accessor(), target); } // optional bool deprecated = 3 [default = false]; if (cached_has_bits & 0x00000004u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->deprecated(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(3, this->deprecated(), target); } // optional bool map_entry = 7; if (cached_has_bits & 0x00000008u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(7, this->map_entry(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(7, this->map_entry(), target); } // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 999, this->uninterpreted_option(static_cast(i)), deterministic, target); + 999, this->uninterpreted_option(static_cast(i)), target); } // Extension range [1000, 536870912) target = _extensions_.InternalSerializeWithCachedSizesToArray( - 1000, 536870912, deterministic, target); + 1000, 536870912, target); if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.MessageOptions) @@ -9123,56 +10471,61 @@ size_t MessageOptions::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; { unsigned int count = static_cast(this->uninterpreted_option_size()); total_size += 2UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->uninterpreted_option(static_cast(i))); } } - if (_has_bits_[0 / 32] & 15u) { + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x0000000fu) { // optional bool message_set_wire_format = 1 [default = false]; - if (has_message_set_wire_format()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + 1; } // optional bool no_standard_descriptor_accessor = 2 [default = false]; - if (has_no_standard_descriptor_accessor()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + 1; } // optional bool deprecated = 3 [default = false]; - if (has_deprecated()) { + if (cached_has_bits & 0x00000004u) { total_size += 1 + 1; } // optional bool map_entry = 7; - if (has_map_entry()) { + if (cached_has_bits & 0x00000008u) { total_size += 1 + 1; } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void MessageOptions::MergeFrom(const ::google::protobuf::Message& from) { +void MessageOptions::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.MessageOptions) GOOGLE_DCHECK_NE(&from, this); const MessageOptions* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.MessageOptions) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.MessageOptions) MergeFrom(*source); @@ -9184,12 +10537,12 @@ void MessageOptions::MergeFrom(const MessageOptions& from) { GOOGLE_DCHECK_NE(&from, this); _extensions_.MergeFrom(from._extensions_); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; uninterpreted_option_.MergeFrom(from.uninterpreted_option_); cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 15u) { + if (cached_has_bits & 0x0000000fu) { if (cached_has_bits & 0x00000001u) { message_set_wire_format_ = from.message_set_wire_format_; } @@ -9206,7 +10559,7 @@ void MessageOptions::MergeFrom(const MessageOptions& from) { } } -void MessageOptions::CopyFrom(const ::google::protobuf::Message& from) { +void MessageOptions::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.MessageOptions) if (&from == this) return; Clear(); @@ -9225,7 +10578,7 @@ bool MessageOptions::IsInitialized() const { return false; } - if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->uninterpreted_option())) return false; return true; } @@ -9238,7 +10591,7 @@ void MessageOptions::Swap(MessageOptions* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -9250,19 +10603,18 @@ void MessageOptions::UnsafeArenaSwap(MessageOptions* other) { } void MessageOptions::InternalSwap(MessageOptions* other) { using std::swap; + _extensions_.Swap(&other->_extensions_); + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_)); swap(message_set_wire_format_, other->message_set_wire_format_); swap(no_standard_descriptor_accessor_, other->no_standard_descriptor_accessor_); swap(deprecated_, other->deprecated_); swap(map_entry_, other->map_entry_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); - _extensions_.Swap(&other->_extensions_); } -::google::protobuf::Metadata MessageOptions::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata MessageOptions::GetMetadata() const { + return GetMetadataStatic(); } @@ -9270,6 +10622,29 @@ void MessageOptions::InternalSwap(MessageOptions* other) { void FieldOptions::InitAsDefaultInstance() { } +class FieldOptions::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_ctype(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static void set_has_packed(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } + static void set_has_jstype(HasBits* has_bits) { + (*has_bits)[0] |= 32u; + } + static void set_has_lazy(HasBits* has_bits) { + (*has_bits)[0] |= 4u; + } + static void set_has_deprecated(HasBits* has_bits) { + (*has_bits)[0] |= 8u; + } + static void set_has_weak(HasBits* has_bits) { + (*has_bits)[0] |= 16u; + } +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int FieldOptions::kCtypeFieldNumber; const int FieldOptions::kPackedFieldNumber; @@ -9281,25 +10656,22 @@ const int FieldOptions::kUninterpretedOptionFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 FieldOptions::FieldOptions() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FieldOptions) } -FieldOptions::FieldOptions(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +FieldOptions::FieldOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.FieldOptions) } FieldOptions::FieldOptions(const FieldOptions& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); @@ -9311,6 +10683,7 @@ FieldOptions::FieldOptions(const FieldOptions& from) } void FieldOptions::SharedCtor() { + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_FieldOptions_google_2fprotobuf_2fdescriptor_2eproto.base); ::memset(&ctype_, 0, static_cast( reinterpret_cast(&jstype_) - reinterpret_cast(&ctype_)) + sizeof(jstype_)); @@ -9322,39 +10695,34 @@ FieldOptions::~FieldOptions() { } void FieldOptions::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void FieldOptions::ArenaDtor(void* object) { FieldOptions* _this = reinterpret_cast< FieldOptions* >(object); (void)_this; } -void FieldOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void FieldOptions::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void FieldOptions::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* FieldOptions::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const FieldOptions& FieldOptions::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_FieldOptions_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void FieldOptions::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.FieldOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; _extensions_.Clear(); uninterpreted_option_.Clear(); cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 63u) { + if (cached_has_bits & 0x0000003fu) { ::memset(&ctype_, 0, static_cast( reinterpret_cast(&jstype_) - reinterpret_cast(&ctype_)) + sizeof(jstype_)); @@ -9363,29 +10731,133 @@ void FieldOptions::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* FieldOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING]; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { + ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + if (PROTOBUF_PREDICT_TRUE(PROTOBUF_NAMESPACE_ID::FieldOptions_CType_IsValid(val))) { + set_ctype(static_cast(val)); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::WriteVarint(1, val, mutable_unknown_fields()); + } + } else goto handle_unusual; + continue; + // optional bool packed = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { + HasBitSetters::set_has_packed(&has_bits); + packed_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional bool deprecated = 3 [default = false]; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) { + HasBitSetters::set_has_deprecated(&has_bits); + deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional bool lazy = 5 [default = false]; + case 5: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { + HasBitSetters::set_has_lazy(&has_bits); + lazy_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL]; + case 6: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) { + ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + if (PROTOBUF_PREDICT_TRUE(PROTOBUF_NAMESPACE_ID::FieldOptions_JSType_IsValid(val))) { + set_jstype(static_cast(val)); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::WriteVarint(6, val, mutable_unknown_fields()); + } + } else goto handle_unusual; + continue; + // optional bool weak = 10 [default = false]; + case 10: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 80)) { + HasBitSetters::set_has_weak(&has_bits); + weak_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; + case 999: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { + ptr -= 2; + do { + ptr += 2; + ptr = ctx->ParseMessage(add_uninterpreted_option(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint16>(ptr) == 16058); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + if ((8000u <= tag)) { + ptr = _extensions_.ParseField(tag, ptr, + internal_default_instance(), &_internal_metadata_, ctx); + CHK_(ptr != nullptr); + continue; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool FieldOptions::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FieldOptions) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING]; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { - int value; - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) { + int value = 0; + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>( input, &value))); - if (::google::protobuf::FieldOptions_CType_IsValid(value)) { - set_ctype(static_cast< ::google::protobuf::FieldOptions_CType >(value)); + if (PROTOBUF_NAMESPACE_ID::FieldOptions_CType_IsValid(value)) { + set_ctype(static_cast< PROTOBUF_NAMESPACE_ID::FieldOptions_CType >(value)); } else { mutable_unknown_fields()->AddVarint( - 1, static_cast< ::google::protobuf::uint64>(value)); + 1, static_cast<::PROTOBUF_NAMESPACE_ID::uint64>(value)); } } else { goto handle_unusual; @@ -9395,11 +10867,10 @@ bool FieldOptions::MergePartialFromCodedStream( // optional bool packed = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { - set_has_packed(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (16 & 0xFF)) { + HasBitSetters::set_has_packed(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &packed_))); } else { goto handle_unusual; @@ -9409,11 +10880,10 @@ bool FieldOptions::MergePartialFromCodedStream( // optional bool deprecated = 3 [default = false]; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { - set_has_deprecated(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (24 & 0xFF)) { + HasBitSetters::set_has_deprecated(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &deprecated_))); } else { goto handle_unusual; @@ -9423,11 +10893,10 @@ bool FieldOptions::MergePartialFromCodedStream( // optional bool lazy = 5 [default = false]; case 5: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { - set_has_lazy(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (40 & 0xFF)) { + HasBitSetters::set_has_lazy(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &lazy_))); } else { goto handle_unusual; @@ -9437,17 +10906,16 @@ bool FieldOptions::MergePartialFromCodedStream( // optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL]; case 6: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) { - int value; - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (48 & 0xFF)) { + int value = 0; + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>( input, &value))); - if (::google::protobuf::FieldOptions_JSType_IsValid(value)) { - set_jstype(static_cast< ::google::protobuf::FieldOptions_JSType >(value)); + if (PROTOBUF_NAMESPACE_ID::FieldOptions_JSType_IsValid(value)) { + set_jstype(static_cast< PROTOBUF_NAMESPACE_ID::FieldOptions_JSType >(value)); } else { mutable_unknown_fields()->AddVarint( - 6, static_cast< ::google::protobuf::uint64>(value)); + 6, static_cast<::PROTOBUF_NAMESPACE_ID::uint64>(value)); } } else { goto handle_unusual; @@ -9457,11 +10925,10 @@ bool FieldOptions::MergePartialFromCodedStream( // optional bool weak = 10 [default = false]; case 10: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(80u /* 80 & 0xFF */)) { - set_has_weak(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (80 & 0xFF)) { + HasBitSetters::set_has_weak(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &weak_))); } else { goto handle_unusual; @@ -9471,9 +10938,8 @@ bool FieldOptions::MergePartialFromCodedStream( // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; case 999: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (7994 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_uninterpreted_option())); } else { goto handle_unusual; @@ -9492,7 +10958,7 @@ bool FieldOptions::MergePartialFromCodedStream( _internal_metadata_.mutable_unknown_fields())); continue; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -9506,120 +10972,119 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void FieldOptions::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.FieldOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING]; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormatLite::WriteEnum( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum( 1, this->ctype(), output); } // optional bool packed = 2; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(2, this->packed(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(2, this->packed(), output); } // optional bool deprecated = 3 [default = false]; if (cached_has_bits & 0x00000008u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(3, this->deprecated(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(3, this->deprecated(), output); } // optional bool lazy = 5 [default = false]; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(5, this->lazy(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(5, this->lazy(), output); } // optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL]; if (cached_has_bits & 0x00000020u) { - ::google::protobuf::internal::WireFormatLite::WriteEnum( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum( 6, this->jstype(), output); } // optional bool weak = 10 [default = false]; if (cached_has_bits & 0x00000010u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(10, this->weak(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(10, this->weak(), output); } // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 999, this->uninterpreted_option(static_cast(i)), output); } // Extension range [1000, 536870912) - _extensions_.SerializeWithCachedSizes( - 1000, 536870912, output); + _extensions_.SerializeWithCachedSizes(1000, 536870912, output); if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.FieldOptions) } -::google::protobuf::uint8* FieldOptions::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* FieldOptions::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FieldOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING]; if (cached_has_bits & 0x00000001u) { - target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray( 1, this->ctype(), target); } // optional bool packed = 2; if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->packed(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(2, this->packed(), target); } // optional bool deprecated = 3 [default = false]; if (cached_has_bits & 0x00000008u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->deprecated(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(3, this->deprecated(), target); } // optional bool lazy = 5 [default = false]; if (cached_has_bits & 0x00000004u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(5, this->lazy(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(5, this->lazy(), target); } // optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL]; if (cached_has_bits & 0x00000020u) { - target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray( 6, this->jstype(), target); } // optional bool weak = 10 [default = false]; if (cached_has_bits & 0x00000010u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(10, this->weak(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(10, this->weak(), target); } // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 999, this->uninterpreted_option(static_cast(i)), deterministic, target); + 999, this->uninterpreted_option(static_cast(i)), target); } // Extension range [1000, 536870912) target = _extensions_.InternalSerializeWithCachedSizesToArray( - 1000, 536870912, deterministic, target); + 1000, 536870912, target); if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FieldOptions) @@ -9634,68 +11099,73 @@ size_t FieldOptions::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; { unsigned int count = static_cast(this->uninterpreted_option_size()); total_size += 2UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->uninterpreted_option(static_cast(i))); } } - if (_has_bits_[0 / 32] & 63u) { + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x0000003fu) { // optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING]; - if (has_ctype()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::EnumSize(this->ctype()); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->ctype()); } // optional bool packed = 2; - if (has_packed()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + 1; } // optional bool lazy = 5 [default = false]; - if (has_lazy()) { + if (cached_has_bits & 0x00000004u) { total_size += 1 + 1; } // optional bool deprecated = 3 [default = false]; - if (has_deprecated()) { + if (cached_has_bits & 0x00000008u) { total_size += 1 + 1; } // optional bool weak = 10 [default = false]; - if (has_weak()) { + if (cached_has_bits & 0x00000010u) { total_size += 1 + 1; } // optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL]; - if (has_jstype()) { + if (cached_has_bits & 0x00000020u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::EnumSize(this->jstype()); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->jstype()); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void FieldOptions::MergeFrom(const ::google::protobuf::Message& from) { +void FieldOptions::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FieldOptions) GOOGLE_DCHECK_NE(&from, this); const FieldOptions* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.FieldOptions) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.FieldOptions) MergeFrom(*source); @@ -9707,12 +11177,12 @@ void FieldOptions::MergeFrom(const FieldOptions& from) { GOOGLE_DCHECK_NE(&from, this); _extensions_.MergeFrom(from._extensions_); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; uninterpreted_option_.MergeFrom(from.uninterpreted_option_); cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 63u) { + if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { ctype_ = from.ctype_; } @@ -9735,7 +11205,7 @@ void FieldOptions::MergeFrom(const FieldOptions& from) { } } -void FieldOptions::CopyFrom(const ::google::protobuf::Message& from) { +void FieldOptions::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.FieldOptions) if (&from == this) return; Clear(); @@ -9754,7 +11224,7 @@ bool FieldOptions::IsInitialized() const { return false; } - if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->uninterpreted_option())) return false; return true; } @@ -9767,7 +11237,7 @@ void FieldOptions::Swap(FieldOptions* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -9779,6 +11249,9 @@ void FieldOptions::UnsafeArenaSwap(FieldOptions* other) { } void FieldOptions::InternalSwap(FieldOptions* other) { using std::swap; + _extensions_.Swap(&other->_extensions_); + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_)); swap(ctype_, other->ctype_); swap(packed_, other->packed_); @@ -9786,14 +11259,10 @@ void FieldOptions::InternalSwap(FieldOptions* other) { swap(deprecated_, other->deprecated_); swap(weak_, other->weak_); swap(jstype_, other->jstype_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); - _extensions_.Swap(&other->_extensions_); } -::google::protobuf::Metadata FieldOptions::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata FieldOptions::GetMetadata() const { + return GetMetadataStatic(); } @@ -9801,30 +11270,32 @@ void FieldOptions::InternalSwap(FieldOptions* other) { void OneofOptions::InitAsDefaultInstance() { } +class OneofOptions::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int OneofOptions::kUninterpretedOptionFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 OneofOptions::OneofOptions() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.OneofOptions) } -OneofOptions::OneofOptions(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +OneofOptions::OneofOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.OneofOptions) } OneofOptions::OneofOptions(const OneofOptions& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); @@ -9833,6 +11304,7 @@ OneofOptions::OneofOptions(const OneofOptions& from) } void OneofOptions::SharedCtor() { + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_OneofOptions_google_2fprotobuf_2fdescriptor_2eproto.base); } OneofOptions::~OneofOptions() { @@ -9841,32 +11313,27 @@ OneofOptions::~OneofOptions() { } void OneofOptions::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void OneofOptions::ArenaDtor(void* object) { OneofOptions* _this = reinterpret_cast< OneofOptions* >(object); (void)_this; } -void OneofOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void OneofOptions::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void OneofOptions::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* OneofOptions::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const OneofOptions& OneofOptions::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_OneofOptions_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void OneofOptions::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.OneofOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -9876,21 +11343,67 @@ void OneofOptions::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* OneofOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; + case 999: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { + ptr -= 2; + do { + ptr += 2; + ptr = ctx->ParseMessage(add_uninterpreted_option(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint16>(ptr) == 16058); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + if ((8000u <= tag)) { + ptr = _extensions_.ParseField(tag, ptr, + internal_default_instance(), &_internal_metadata_, ctx); + CHK_(ptr != nullptr); + continue; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool OneofOptions::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.OneofOptions) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; case 999: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (7994 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_uninterpreted_option())); } else { goto handle_unusual; @@ -9909,7 +11422,7 @@ bool OneofOptions::MergePartialFromCodedStream( _internal_metadata_.mutable_unknown_fields())); continue; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -9923,54 +11436,53 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void OneofOptions::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.OneofOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 999, this->uninterpreted_option(static_cast(i)), output); } // Extension range [1000, 536870912) - _extensions_.SerializeWithCachedSizes( - 1000, 536870912, output); + _extensions_.SerializeWithCachedSizes(1000, 536870912, output); if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.OneofOptions) } -::google::protobuf::uint8* OneofOptions::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* OneofOptions::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.OneofOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 999, this->uninterpreted_option(static_cast(i)), deterministic, target); + 999, this->uninterpreted_option(static_cast(i)), target); } // Extension range [1000, 536870912) target = _extensions_.InternalSerializeWithCachedSizesToArray( - 1000, 536870912, deterministic, target); + 1000, 536870912, target); if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.OneofOptions) @@ -9985,34 +11497,38 @@ size_t OneofOptions::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; { unsigned int count = static_cast(this->uninterpreted_option_size()); total_size += 2UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->uninterpreted_option(static_cast(i))); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void OneofOptions::MergeFrom(const ::google::protobuf::Message& from) { +void OneofOptions::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.OneofOptions) GOOGLE_DCHECK_NE(&from, this); const OneofOptions* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.OneofOptions) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.OneofOptions) MergeFrom(*source); @@ -10024,13 +11540,13 @@ void OneofOptions::MergeFrom(const OneofOptions& from) { GOOGLE_DCHECK_NE(&from, this); _extensions_.MergeFrom(from._extensions_); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; uninterpreted_option_.MergeFrom(from.uninterpreted_option_); } -void OneofOptions::CopyFrom(const ::google::protobuf::Message& from) { +void OneofOptions::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.OneofOptions) if (&from == this) return; Clear(); @@ -10049,7 +11565,7 @@ bool OneofOptions::IsInitialized() const { return false; } - if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->uninterpreted_option())) return false; return true; } @@ -10062,7 +11578,7 @@ void OneofOptions::Swap(OneofOptions* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -10074,15 +11590,14 @@ void OneofOptions::UnsafeArenaSwap(OneofOptions* other) { } void OneofOptions::InternalSwap(OneofOptions* other) { using std::swap; - CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_)); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); _extensions_.Swap(&other->_extensions_); + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); + CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_)); } -::google::protobuf::Metadata OneofOptions::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata OneofOptions::GetMetadata() const { + return GetMetadataStatic(); } @@ -10090,6 +11605,17 @@ void OneofOptions::InternalSwap(OneofOptions* other) { void EnumOptions::InitAsDefaultInstance() { } +class EnumOptions::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_allow_alias(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static void set_has_deprecated(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int EnumOptions::kAllowAliasFieldNumber; const int EnumOptions::kDeprecatedFieldNumber; @@ -10097,25 +11623,22 @@ const int EnumOptions::kUninterpretedOptionFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 EnumOptions::EnumOptions() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.EnumOptions) } -EnumOptions::EnumOptions(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +EnumOptions::EnumOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumOptions) } EnumOptions::EnumOptions(const EnumOptions& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); @@ -10127,6 +11650,7 @@ EnumOptions::EnumOptions(const EnumOptions& from) } void EnumOptions::SharedCtor() { + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_EnumOptions_google_2fprotobuf_2fdescriptor_2eproto.base); ::memset(&allow_alias_, 0, static_cast( reinterpret_cast(&deprecated_) - reinterpret_cast(&allow_alias_)) + sizeof(deprecated_)); @@ -10138,32 +11662,27 @@ EnumOptions::~EnumOptions() { } void EnumOptions::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void EnumOptions::ArenaDtor(void* object) { EnumOptions* _this = reinterpret_cast< EnumOptions* >(object); (void)_this; } -void EnumOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void EnumOptions::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void EnumOptions::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* EnumOptions::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const EnumOptions& EnumOptions::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_EnumOptions_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void EnumOptions::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.EnumOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -10176,23 +11695,87 @@ void EnumOptions::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* EnumOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional bool allow_alias = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { + HasBitSetters::set_has_allow_alias(&has_bits); + allow_alias_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional bool deprecated = 3 [default = false]; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) { + HasBitSetters::set_has_deprecated(&has_bits); + deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; + case 999: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { + ptr -= 2; + do { + ptr += 2; + ptr = ctx->ParseMessage(add_uninterpreted_option(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint16>(ptr) == 16058); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + if ((8000u <= tag)) { + ptr = _extensions_.ParseField(tag, ptr, + internal_default_instance(), &_internal_metadata_, ctx); + CHK_(ptr != nullptr); + continue; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool EnumOptions::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumOptions) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional bool allow_alias = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { - set_has_allow_alias(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (16 & 0xFF)) { + HasBitSetters::set_has_allow_alias(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &allow_alias_))); } else { goto handle_unusual; @@ -10202,11 +11785,10 @@ bool EnumOptions::MergePartialFromCodedStream( // optional bool deprecated = 3 [default = false]; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { - set_has_deprecated(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (24 & 0xFF)) { + HasBitSetters::set_has_deprecated(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &deprecated_))); } else { goto handle_unusual; @@ -10216,9 +11798,8 @@ bool EnumOptions::MergePartialFromCodedStream( // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; case 999: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (7994 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_uninterpreted_option())); } else { goto handle_unusual; @@ -10237,7 +11818,7 @@ bool EnumOptions::MergePartialFromCodedStream( _internal_metadata_.mutable_unknown_fields())); continue; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -10251,76 +11832,75 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void EnumOptions::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.EnumOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional bool allow_alias = 2; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(2, this->allow_alias(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(2, this->allow_alias(), output); } // optional bool deprecated = 3 [default = false]; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(3, this->deprecated(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(3, this->deprecated(), output); } // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 999, this->uninterpreted_option(static_cast(i)), output); } // Extension range [1000, 536870912) - _extensions_.SerializeWithCachedSizes( - 1000, 536870912, output); + _extensions_.SerializeWithCachedSizes(1000, 536870912, output); if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.EnumOptions) } -::google::protobuf::uint8* EnumOptions::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* EnumOptions::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.EnumOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional bool allow_alias = 2; if (cached_has_bits & 0x00000001u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->allow_alias(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(2, this->allow_alias(), target); } // optional bool deprecated = 3 [default = false]; if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->deprecated(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(3, this->deprecated(), target); } // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 999, this->uninterpreted_option(static_cast(i)), deterministic, target); + 999, this->uninterpreted_option(static_cast(i)), target); } // Extension range [1000, 536870912) target = _extensions_.InternalSerializeWithCachedSizesToArray( - 1000, 536870912, deterministic, target); + 1000, 536870912, target); if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumOptions) @@ -10335,46 +11915,51 @@ size_t EnumOptions::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; { unsigned int count = static_cast(this->uninterpreted_option_size()); total_size += 2UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->uninterpreted_option(static_cast(i))); } } - if (_has_bits_[0 / 32] & 3u) { + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x00000003u) { // optional bool allow_alias = 2; - if (has_allow_alias()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + 1; } // optional bool deprecated = 3 [default = false]; - if (has_deprecated()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + 1; } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void EnumOptions::MergeFrom(const ::google::protobuf::Message& from) { +void EnumOptions::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.EnumOptions) GOOGLE_DCHECK_NE(&from, this); const EnumOptions* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.EnumOptions) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.EnumOptions) MergeFrom(*source); @@ -10386,12 +11971,12 @@ void EnumOptions::MergeFrom(const EnumOptions& from) { GOOGLE_DCHECK_NE(&from, this); _extensions_.MergeFrom(from._extensions_); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; uninterpreted_option_.MergeFrom(from.uninterpreted_option_); cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { allow_alias_ = from.allow_alias_; } @@ -10402,7 +11987,7 @@ void EnumOptions::MergeFrom(const EnumOptions& from) { } } -void EnumOptions::CopyFrom(const ::google::protobuf::Message& from) { +void EnumOptions::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.EnumOptions) if (&from == this) return; Clear(); @@ -10421,7 +12006,7 @@ bool EnumOptions::IsInitialized() const { return false; } - if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->uninterpreted_option())) return false; return true; } @@ -10434,7 +12019,7 @@ void EnumOptions::Swap(EnumOptions* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -10446,17 +12031,16 @@ void EnumOptions::UnsafeArenaSwap(EnumOptions* other) { } void EnumOptions::InternalSwap(EnumOptions* other) { using std::swap; + _extensions_.Swap(&other->_extensions_); + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_)); swap(allow_alias_, other->allow_alias_); swap(deprecated_, other->deprecated_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); - _extensions_.Swap(&other->_extensions_); } -::google::protobuf::Metadata EnumOptions::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata EnumOptions::GetMetadata() const { + return GetMetadataStatic(); } @@ -10464,31 +12048,36 @@ void EnumOptions::InternalSwap(EnumOptions* other) { void EnumValueOptions::InitAsDefaultInstance() { } +class EnumValueOptions::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_deprecated(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int EnumValueOptions::kDeprecatedFieldNumber; const int EnumValueOptions::kUninterpretedOptionFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 EnumValueOptions::EnumValueOptions() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.EnumValueOptions) } -EnumValueOptions::EnumValueOptions(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +EnumValueOptions::EnumValueOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValueOptions) } EnumValueOptions::EnumValueOptions(const EnumValueOptions& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); @@ -10498,6 +12087,7 @@ EnumValueOptions::EnumValueOptions(const EnumValueOptions& from) } void EnumValueOptions::SharedCtor() { + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_EnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto.base); deprecated_ = false; } @@ -10507,32 +12097,27 @@ EnumValueOptions::~EnumValueOptions() { } void EnumValueOptions::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void EnumValueOptions::ArenaDtor(void* object) { EnumValueOptions* _this = reinterpret_cast< EnumValueOptions* >(object); (void)_this; } -void EnumValueOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void EnumValueOptions::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void EnumValueOptions::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* EnumValueOptions::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const EnumValueOptions& EnumValueOptions::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_EnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void EnumValueOptions::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.EnumValueOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -10543,23 +12128,79 @@ void EnumValueOptions::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* EnumValueOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional bool deprecated = 1 [default = false]; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { + HasBitSetters::set_has_deprecated(&has_bits); + deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; + case 999: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { + ptr -= 2; + do { + ptr += 2; + ptr = ctx->ParseMessage(add_uninterpreted_option(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint16>(ptr) == 16058); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + if ((8000u <= tag)) { + ptr = _extensions_.ParseField(tag, ptr, + internal_default_instance(), &_internal_metadata_, ctx); + CHK_(ptr != nullptr); + continue; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool EnumValueOptions::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumValueOptions) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional bool deprecated = 1 [default = false]; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { - set_has_deprecated(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) { + HasBitSetters::set_has_deprecated(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &deprecated_))); } else { goto handle_unusual; @@ -10569,9 +12210,8 @@ bool EnumValueOptions::MergePartialFromCodedStream( // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; case 999: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (7994 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_uninterpreted_option())); } else { goto handle_unusual; @@ -10590,7 +12230,7 @@ bool EnumValueOptions::MergePartialFromCodedStream( _internal_metadata_.mutable_unknown_fields())); continue; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -10604,66 +12244,65 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void EnumValueOptions::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.EnumValueOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional bool deprecated = 1 [default = false]; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(1, this->deprecated(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(1, this->deprecated(), output); } // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 999, this->uninterpreted_option(static_cast(i)), output); } // Extension range [1000, 536870912) - _extensions_.SerializeWithCachedSizes( - 1000, 536870912, output); + _extensions_.SerializeWithCachedSizes(1000, 536870912, output); if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.EnumValueOptions) } -::google::protobuf::uint8* EnumValueOptions::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* EnumValueOptions::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.EnumValueOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional bool deprecated = 1 [default = false]; if (cached_has_bits & 0x00000001u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(1, this->deprecated(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(1, this->deprecated(), target); } // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 999, this->uninterpreted_option(static_cast(i)), deterministic, target); + 999, this->uninterpreted_option(static_cast(i)), target); } // Extension range [1000, 536870912) target = _extensions_.InternalSerializeWithCachedSizesToArray( - 1000, 536870912, deterministic, target); + 1000, 536870912, target); if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumValueOptions) @@ -10678,39 +12317,44 @@ size_t EnumValueOptions::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; { unsigned int count = static_cast(this->uninterpreted_option_size()); total_size += 2UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->uninterpreted_option(static_cast(i))); } } // optional bool deprecated = 1 [default = false]; - if (has_deprecated()) { + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x00000001u) { total_size += 1 + 1; } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void EnumValueOptions::MergeFrom(const ::google::protobuf::Message& from) { +void EnumValueOptions::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.EnumValueOptions) GOOGLE_DCHECK_NE(&from, this); const EnumValueOptions* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.EnumValueOptions) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.EnumValueOptions) MergeFrom(*source); @@ -10722,7 +12366,7 @@ void EnumValueOptions::MergeFrom(const EnumValueOptions& from) { GOOGLE_DCHECK_NE(&from, this); _extensions_.MergeFrom(from._extensions_); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; uninterpreted_option_.MergeFrom(from.uninterpreted_option_); @@ -10731,7 +12375,7 @@ void EnumValueOptions::MergeFrom(const EnumValueOptions& from) { } } -void EnumValueOptions::CopyFrom(const ::google::protobuf::Message& from) { +void EnumValueOptions::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.EnumValueOptions) if (&from == this) return; Clear(); @@ -10750,7 +12394,7 @@ bool EnumValueOptions::IsInitialized() const { return false; } - if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->uninterpreted_option())) return false; return true; } @@ -10763,7 +12407,7 @@ void EnumValueOptions::Swap(EnumValueOptions* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -10775,16 +12419,15 @@ void EnumValueOptions::UnsafeArenaSwap(EnumValueOptions* other) { } void EnumValueOptions::InternalSwap(EnumValueOptions* other) { using std::swap; + _extensions_.Swap(&other->_extensions_); + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_)); swap(deprecated_, other->deprecated_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); - _extensions_.Swap(&other->_extensions_); } -::google::protobuf::Metadata EnumValueOptions::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata EnumValueOptions::GetMetadata() const { + return GetMetadataStatic(); } @@ -10792,31 +12435,36 @@ void EnumValueOptions::InternalSwap(EnumValueOptions* other) { void ServiceOptions::InitAsDefaultInstance() { } +class ServiceOptions::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_deprecated(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int ServiceOptions::kDeprecatedFieldNumber; const int ServiceOptions::kUninterpretedOptionFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 ServiceOptions::ServiceOptions() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.ServiceOptions) } -ServiceOptions::ServiceOptions(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +ServiceOptions::ServiceOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.ServiceOptions) } ServiceOptions::ServiceOptions(const ServiceOptions& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); @@ -10826,6 +12474,7 @@ ServiceOptions::ServiceOptions(const ServiceOptions& from) } void ServiceOptions::SharedCtor() { + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_ServiceOptions_google_2fprotobuf_2fdescriptor_2eproto.base); deprecated_ = false; } @@ -10835,32 +12484,27 @@ ServiceOptions::~ServiceOptions() { } void ServiceOptions::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void ServiceOptions::ArenaDtor(void* object) { ServiceOptions* _this = reinterpret_cast< ServiceOptions* >(object); (void)_this; } -void ServiceOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void ServiceOptions::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void ServiceOptions::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* ServiceOptions::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const ServiceOptions& ServiceOptions::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_ServiceOptions_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void ServiceOptions::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.ServiceOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -10871,23 +12515,79 @@ void ServiceOptions::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* ServiceOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional bool deprecated = 33 [default = false]; + case 33: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { + HasBitSetters::set_has_deprecated(&has_bits); + deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; + case 999: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { + ptr -= 2; + do { + ptr += 2; + ptr = ctx->ParseMessage(add_uninterpreted_option(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint16>(ptr) == 16058); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + if ((8000u <= tag)) { + ptr = _extensions_.ParseField(tag, ptr, + internal_default_instance(), &_internal_metadata_, ctx); + CHK_(ptr != nullptr); + continue; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool ServiceOptions::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.ServiceOptions) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional bool deprecated = 33 [default = false]; case 33: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(8u /* 264 & 0xFF */)) { - set_has_deprecated(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (264 & 0xFF)) { + HasBitSetters::set_has_deprecated(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &deprecated_))); } else { goto handle_unusual; @@ -10897,9 +12597,8 @@ bool ServiceOptions::MergePartialFromCodedStream( // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; case 999: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (7994 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_uninterpreted_option())); } else { goto handle_unusual; @@ -10918,7 +12617,7 @@ bool ServiceOptions::MergePartialFromCodedStream( _internal_metadata_.mutable_unknown_fields())); continue; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -10932,66 +12631,65 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void ServiceOptions::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.ServiceOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional bool deprecated = 33 [default = false]; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(33, this->deprecated(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(33, this->deprecated(), output); } // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 999, this->uninterpreted_option(static_cast(i)), output); } // Extension range [1000, 536870912) - _extensions_.SerializeWithCachedSizes( - 1000, 536870912, output); + _extensions_.SerializeWithCachedSizes(1000, 536870912, output); if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.ServiceOptions) } -::google::protobuf::uint8* ServiceOptions::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* ServiceOptions::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.ServiceOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional bool deprecated = 33 [default = false]; if (cached_has_bits & 0x00000001u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(33, this->deprecated(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(33, this->deprecated(), target); } // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 999, this->uninterpreted_option(static_cast(i)), deterministic, target); + 999, this->uninterpreted_option(static_cast(i)), target); } // Extension range [1000, 536870912) target = _extensions_.InternalSerializeWithCachedSizesToArray( - 1000, 536870912, deterministic, target); + 1000, 536870912, target); if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.ServiceOptions) @@ -11006,39 +12704,44 @@ size_t ServiceOptions::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; { unsigned int count = static_cast(this->uninterpreted_option_size()); total_size += 2UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->uninterpreted_option(static_cast(i))); } } // optional bool deprecated = 33 [default = false]; - if (has_deprecated()) { + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x00000001u) { total_size += 2 + 1; } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void ServiceOptions::MergeFrom(const ::google::protobuf::Message& from) { +void ServiceOptions::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.ServiceOptions) GOOGLE_DCHECK_NE(&from, this); const ServiceOptions* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.ServiceOptions) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.ServiceOptions) MergeFrom(*source); @@ -11050,7 +12753,7 @@ void ServiceOptions::MergeFrom(const ServiceOptions& from) { GOOGLE_DCHECK_NE(&from, this); _extensions_.MergeFrom(from._extensions_); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; uninterpreted_option_.MergeFrom(from.uninterpreted_option_); @@ -11059,7 +12762,7 @@ void ServiceOptions::MergeFrom(const ServiceOptions& from) { } } -void ServiceOptions::CopyFrom(const ::google::protobuf::Message& from) { +void ServiceOptions::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.ServiceOptions) if (&from == this) return; Clear(); @@ -11078,7 +12781,7 @@ bool ServiceOptions::IsInitialized() const { return false; } - if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->uninterpreted_option())) return false; return true; } @@ -11091,7 +12794,7 @@ void ServiceOptions::Swap(ServiceOptions* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -11103,16 +12806,15 @@ void ServiceOptions::UnsafeArenaSwap(ServiceOptions* other) { } void ServiceOptions::InternalSwap(ServiceOptions* other) { using std::swap; + _extensions_.Swap(&other->_extensions_); + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_)); swap(deprecated_, other->deprecated_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); - _extensions_.Swap(&other->_extensions_); } -::google::protobuf::Metadata ServiceOptions::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata ServiceOptions::GetMetadata() const { + return GetMetadataStatic(); } @@ -11120,6 +12822,17 @@ void ServiceOptions::InternalSwap(ServiceOptions* other) { void MethodOptions::InitAsDefaultInstance() { } +class MethodOptions::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_deprecated(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static void set_has_idempotency_level(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int MethodOptions::kDeprecatedFieldNumber; const int MethodOptions::kIdempotencyLevelFieldNumber; @@ -11127,25 +12840,22 @@ const int MethodOptions::kUninterpretedOptionFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 MethodOptions::MethodOptions() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.MethodOptions) } -MethodOptions::MethodOptions(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +MethodOptions::MethodOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.MethodOptions) } MethodOptions::MethodOptions(const MethodOptions& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); @@ -11157,6 +12867,7 @@ MethodOptions::MethodOptions(const MethodOptions& from) } void MethodOptions::SharedCtor() { + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_MethodOptions_google_2fprotobuf_2fdescriptor_2eproto.base); ::memset(&deprecated_, 0, static_cast( reinterpret_cast(&idempotency_level_) - reinterpret_cast(&deprecated_)) + sizeof(idempotency_level_)); @@ -11168,39 +12879,34 @@ MethodOptions::~MethodOptions() { } void MethodOptions::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void MethodOptions::ArenaDtor(void* object) { MethodOptions* _this = reinterpret_cast< MethodOptions* >(object); (void)_this; } -void MethodOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void MethodOptions::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void MethodOptions::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* MethodOptions::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const MethodOptions& MethodOptions::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_MethodOptions_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void MethodOptions::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.MethodOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; _extensions_.Clear(); uninterpreted_option_.Clear(); cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { ::memset(&deprecated_, 0, static_cast( reinterpret_cast(&idempotency_level_) - reinterpret_cast(&deprecated_)) + sizeof(idempotency_level_)); @@ -11209,23 +12915,91 @@ void MethodOptions::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* MethodOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // optional bool deprecated = 33 [default = false]; + case 33: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { + HasBitSetters::set_has_deprecated(&has_bits); + deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN]; + case 34: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { + ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + if (PROTOBUF_PREDICT_TRUE(PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel_IsValid(val))) { + set_idempotency_level(static_cast(val)); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::WriteVarint(34, val, mutable_unknown_fields()); + } + } else goto handle_unusual; + continue; + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; + case 999: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { + ptr -= 2; + do { + ptr += 2; + ptr = ctx->ParseMessage(add_uninterpreted_option(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint16>(ptr) == 16058); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + if ((8000u <= tag)) { + ptr = _extensions_.ParseField(tag, ptr, + internal_default_instance(), &_internal_metadata_, ctx); + CHK_(ptr != nullptr); + continue; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool MethodOptions::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.MethodOptions) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional bool deprecated = 33 [default = false]; case 33: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(8u /* 264 & 0xFF */)) { - set_has_deprecated(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (264 & 0xFF)) { + HasBitSetters::set_has_deprecated(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &deprecated_))); } else { goto handle_unusual; @@ -11235,17 +13009,16 @@ bool MethodOptions::MergePartialFromCodedStream( // optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN]; case 34: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(16u /* 272 & 0xFF */)) { - int value; - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (272 & 0xFF)) { + int value = 0; + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>( input, &value))); - if (::google::protobuf::MethodOptions_IdempotencyLevel_IsValid(value)) { - set_idempotency_level(static_cast< ::google::protobuf::MethodOptions_IdempotencyLevel >(value)); + if (PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel_IsValid(value)) { + set_idempotency_level(static_cast< PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel >(value)); } else { mutable_unknown_fields()->AddVarint( - 34, static_cast< ::google::protobuf::uint64>(value)); + 34, static_cast<::PROTOBUF_NAMESPACE_ID::uint64>(value)); } } else { goto handle_unusual; @@ -11255,9 +13028,8 @@ bool MethodOptions::MergePartialFromCodedStream( // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; case 999: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (7994 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_uninterpreted_option())); } else { goto handle_unusual; @@ -11276,7 +13048,7 @@ bool MethodOptions::MergePartialFromCodedStream( _internal_metadata_.mutable_unknown_fields())); continue; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -11290,78 +13062,77 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void MethodOptions::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.MethodOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional bool deprecated = 33 [default = false]; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(33, this->deprecated(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(33, this->deprecated(), output); } // optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN]; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteEnum( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum( 34, this->idempotency_level(), output); } // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 999, this->uninterpreted_option(static_cast(i)), output); } // Extension range [1000, 536870912) - _extensions_.SerializeWithCachedSizes( - 1000, 536870912, output); + _extensions_.SerializeWithCachedSizes(1000, 536870912, output); if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.MethodOptions) } -::google::protobuf::uint8* MethodOptions::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* MethodOptions::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.MethodOptions) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional bool deprecated = 33 [default = false]; if (cached_has_bits & 0x00000001u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(33, this->deprecated(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(33, this->deprecated(), target); } // optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN]; if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray( 34, this->idempotency_level(), target); } // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast(this->uninterpreted_option_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 999, this->uninterpreted_option(static_cast(i)), deterministic, target); + 999, this->uninterpreted_option(static_cast(i)), target); } // Extension range [1000, 536870912) target = _extensions_.InternalSerializeWithCachedSizesToArray( - 1000, 536870912, deterministic, target); + 1000, 536870912, target); if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.MethodOptions) @@ -11376,47 +13147,52 @@ size_t MethodOptions::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; { unsigned int count = static_cast(this->uninterpreted_option_size()); total_size += 2UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->uninterpreted_option(static_cast(i))); } } - if (_has_bits_[0 / 32] & 3u) { + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x00000003u) { // optional bool deprecated = 33 [default = false]; - if (has_deprecated()) { + if (cached_has_bits & 0x00000001u) { total_size += 2 + 1; } // optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN]; - if (has_idempotency_level()) { + if (cached_has_bits & 0x00000002u) { total_size += 2 + - ::google::protobuf::internal::WireFormatLite::EnumSize(this->idempotency_level()); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->idempotency_level()); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void MethodOptions::MergeFrom(const ::google::protobuf::Message& from) { +void MethodOptions::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.MethodOptions) GOOGLE_DCHECK_NE(&from, this); const MethodOptions* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.MethodOptions) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.MethodOptions) MergeFrom(*source); @@ -11428,12 +13204,12 @@ void MethodOptions::MergeFrom(const MethodOptions& from) { GOOGLE_DCHECK_NE(&from, this); _extensions_.MergeFrom(from._extensions_); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; uninterpreted_option_.MergeFrom(from.uninterpreted_option_); cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { deprecated_ = from.deprecated_; } @@ -11444,7 +13220,7 @@ void MethodOptions::MergeFrom(const MethodOptions& from) { } } -void MethodOptions::CopyFrom(const ::google::protobuf::Message& from) { +void MethodOptions::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.MethodOptions) if (&from == this) return; Clear(); @@ -11463,7 +13239,7 @@ bool MethodOptions::IsInitialized() const { return false; } - if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->uninterpreted_option())) return false; return true; } @@ -11476,7 +13252,7 @@ void MethodOptions::Swap(MethodOptions* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -11488,17 +13264,16 @@ void MethodOptions::UnsafeArenaSwap(MethodOptions* other) { } void MethodOptions::InternalSwap(MethodOptions* other) { using std::swap; + _extensions_.Swap(&other->_extensions_); + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_)); swap(deprecated_, other->deprecated_); swap(idempotency_level_, other->idempotency_level_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); - _extensions_.Swap(&other->_extensions_); } -::google::protobuf::Metadata MethodOptions::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata MethodOptions::GetMetadata() const { + return GetMetadataStatic(); } @@ -11506,34 +13281,42 @@ void MethodOptions::InternalSwap(MethodOptions* other) { void UninterpretedOption_NamePart::InitAsDefaultInstance() { } +class UninterpretedOption_NamePart::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_name_part(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static void set_has_is_extension(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int UninterpretedOption_NamePart::kNamePartFieldNumber; const int UninterpretedOption_NamePart::kIsExtensionFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 UninterpretedOption_NamePart::UninterpretedOption_NamePart() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption_NamePart.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.UninterpretedOption.NamePart) } -UninterpretedOption_NamePart::UninterpretedOption_NamePart(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +UninterpretedOption_NamePart::UninterpretedOption_NamePart(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption_NamePart.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.UninterpretedOption.NamePart) } UninterpretedOption_NamePart::UninterpretedOption_NamePart(const UninterpretedOption_NamePart& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - name_part_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_part_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_name_part()) { - name_part_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_part(), + name_part_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name_part(), GetArenaNoVirtual()); } is_extension_ = from.is_extension_; @@ -11541,7 +13324,8 @@ UninterpretedOption_NamePart::UninterpretedOption_NamePart(const UninterpretedOp } void UninterpretedOption_NamePart::SharedCtor() { - name_part_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto.base); + name_part_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); is_extension_ = false; } @@ -11551,33 +13335,28 @@ UninterpretedOption_NamePart::~UninterpretedOption_NamePart() { } void UninterpretedOption_NamePart::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); - name_part_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); + name_part_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void UninterpretedOption_NamePart::ArenaDtor(void* object) { UninterpretedOption_NamePart* _this = reinterpret_cast< UninterpretedOption_NamePart* >(object); (void)_this; } -void UninterpretedOption_NamePart::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void UninterpretedOption_NamePart::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void UninterpretedOption_NamePart::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* UninterpretedOption_NamePart::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const UninterpretedOption_NamePart& UninterpretedOption_NamePart::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption_NamePart.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void UninterpretedOption_NamePart::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.UninterpretedOption.NamePart) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -11590,25 +13369,70 @@ void UninterpretedOption_NamePart::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* UninterpretedOption_NamePart::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // required string name_part = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_name_part(), ptr, ctx, "google.protobuf.UninterpretedOption.NamePart.name_part"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // required bool is_extension = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { + HasBitSetters::set_has_is_extension(&has_bits); + is_extension_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool UninterpretedOption_NamePart::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.UninterpretedOption.NamePart) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required string name_part = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_name_part())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name_part().data(), static_cast(this->name_part().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.UninterpretedOption.NamePart.name_part"); } else { goto handle_unusual; @@ -11618,11 +13442,10 @@ bool UninterpretedOption_NamePart::MergePartialFromCodedStream( // required bool is_extension = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { - set_has_is_extension(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (16 & 0xFF)) { + HasBitSetters::set_has_is_extension(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &is_extension_))); } else { goto handle_unusual; @@ -11635,7 +13458,7 @@ bool UninterpretedOption_NamePart::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -11649,62 +13472,62 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void UninterpretedOption_NamePart::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.UninterpretedOption.NamePart) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required string name_part = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name_part().data(), static_cast(this->name_part().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.UninterpretedOption.NamePart.name_part"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name_part(), output); } // required bool is_extension = 2; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteBool(2, this->is_extension(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(2, this->is_extension(), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.UninterpretedOption.NamePart) } -::google::protobuf::uint8* UninterpretedOption_NamePart::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* UninterpretedOption_NamePart::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.UninterpretedOption.NamePart) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required string name_part = 1; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->name_part().data(), static_cast(this->name_part().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.UninterpretedOption.NamePart.name_part"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 1, this->name_part(), target); } // required bool is_extension = 2; if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->is_extension(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(2, this->is_extension(), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.UninterpretedOption.NamePart) @@ -11718,7 +13541,7 @@ size_t UninterpretedOption_NamePart::RequiredFieldsByteSizeFallback() const { if (has_name_part()) { // required string name_part = 1; total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->name_part()); } @@ -11735,13 +13558,13 @@ size_t UninterpretedOption_NamePart::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present. // required string name_part = 1; total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->name_part()); // required bool is_extension = 2; @@ -11750,20 +13573,24 @@ size_t UninterpretedOption_NamePart::ByteSizeLong() const { } else { total_size += RequiredFieldsByteSizeFallback(); } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void UninterpretedOption_NamePart::MergeFrom(const ::google::protobuf::Message& from) { +void UninterpretedOption_NamePart::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.UninterpretedOption.NamePart) GOOGLE_DCHECK_NE(&from, this); const UninterpretedOption_NamePart* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.UninterpretedOption.NamePart) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.UninterpretedOption.NamePart) MergeFrom(*source); @@ -11774,11 +13601,11 @@ void UninterpretedOption_NamePart::MergeFrom(const UninterpretedOption_NamePart& // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.UninterpretedOption.NamePart) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { set_name_part(from.name_part()); } @@ -11789,7 +13616,7 @@ void UninterpretedOption_NamePart::MergeFrom(const UninterpretedOption_NamePart& } } -void UninterpretedOption_NamePart::CopyFrom(const ::google::protobuf::Message& from) { +void UninterpretedOption_NamePart::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.UninterpretedOption.NamePart) if (&from == this) return; Clear(); @@ -11817,7 +13644,7 @@ void UninterpretedOption_NamePart::Swap(UninterpretedOption_NamePart* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -11829,16 +13656,15 @@ void UninterpretedOption_NamePart::UnsafeArenaSwap(UninterpretedOption_NamePart* } void UninterpretedOption_NamePart::InternalSwap(UninterpretedOption_NamePart* other) { using std::swap; - name_part_.Swap(&other->name_part_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); + name_part_.Swap(&other->name_part_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(is_extension_, other->is_extension_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata UninterpretedOption_NamePart::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata UninterpretedOption_NamePart::GetMetadata() const { + return GetMetadataStatic(); } @@ -11846,6 +13672,29 @@ void UninterpretedOption_NamePart::InternalSwap(UninterpretedOption_NamePart* ot void UninterpretedOption::InitAsDefaultInstance() { } +class UninterpretedOption::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_identifier_value(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static void set_has_positive_int_value(HasBits* has_bits) { + (*has_bits)[0] |= 8u; + } + static void set_has_negative_int_value(HasBits* has_bits) { + (*has_bits)[0] |= 16u; + } + static void set_has_double_value(HasBits* has_bits) { + (*has_bits)[0] |= 32u; + } + static void set_has_string_value(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } + static void set_has_aggregate_value(HasBits* has_bits) { + (*has_bits)[0] |= 4u; + } +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int UninterpretedOption::kNameFieldNumber; const int UninterpretedOption::kIdentifierValueFieldNumber; @@ -11857,40 +13706,37 @@ const int UninterpretedOption::kAggregateValueFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 UninterpretedOption::UninterpretedOption() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.UninterpretedOption) } -UninterpretedOption::UninterpretedOption(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +UninterpretedOption::UninterpretedOption(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena), name_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.UninterpretedOption) } UninterpretedOption::UninterpretedOption(const UninterpretedOption& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), name_(from.name_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - identifier_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + identifier_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_identifier_value()) { - identifier_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.identifier_value(), + identifier_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.identifier_value(), GetArenaNoVirtual()); } - string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_string_value()) { - string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.string_value(), + string_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.string_value(), GetArenaNoVirtual()); } - aggregate_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + aggregate_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_aggregate_value()) { - aggregate_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.aggregate_value(), + aggregate_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.aggregate_value(), GetArenaNoVirtual()); } ::memcpy(&positive_int_value_, &from.positive_int_value_, @@ -11900,9 +13746,10 @@ UninterpretedOption::UninterpretedOption(const UninterpretedOption& from) } void UninterpretedOption::SharedCtor() { - identifier_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - aggregate_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base); + identifier_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + aggregate_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(&positive_int_value_, 0, static_cast( reinterpret_cast(&double_value_) - reinterpret_cast(&positive_int_value_)) + sizeof(double_value_)); @@ -11914,41 +13761,36 @@ UninterpretedOption::~UninterpretedOption() { } void UninterpretedOption::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); - identifier_value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - string_value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - aggregate_value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); + identifier_value_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + string_value_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + aggregate_value_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void UninterpretedOption::ArenaDtor(void* object) { UninterpretedOption* _this = reinterpret_cast< UninterpretedOption* >(object); (void)_this; } -void UninterpretedOption::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void UninterpretedOption::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void UninterpretedOption::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* UninterpretedOption::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const UninterpretedOption& UninterpretedOption::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void UninterpretedOption::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.UninterpretedOption) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; name_.Clear(); cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 7u) { + if (cached_has_bits & 0x00000007u) { if (cached_has_bits & 0x00000001u) { identifier_value_.ClearNonDefaultToEmpty(); } @@ -11959,7 +13801,7 @@ void UninterpretedOption::Clear() { aggregate_value_.ClearNonDefaultToEmpty(); } } - if (cached_has_bits & 56u) { + if (cached_has_bits & 0x00000038u) { ::memset(&positive_int_value_, 0, static_cast( reinterpret_cast(&double_value_) - reinterpret_cast(&positive_int_value_)) + sizeof(double_value_)); @@ -11968,21 +13810,108 @@ void UninterpretedOption::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* UninterpretedOption::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // repeated .google.protobuf.UninterpretedOption.NamePart name = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_name(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 18); + } else goto handle_unusual; + continue; + // optional string identifier_value = 3; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_identifier_value(), ptr, ctx, "google.protobuf.UninterpretedOption.identifier_value"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional uint64 positive_int_value = 4; + case 4: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { + HasBitSetters::set_has_positive_int_value(&has_bits); + positive_int_value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional int64 negative_int_value = 5; + case 5: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { + HasBitSetters::set_has_negative_int_value(&has_bits); + negative_int_value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional double double_value = 6; + case 6: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 49)) { + HasBitSetters::set_has_double_value(&has_bits); + double_value_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad(ptr); + ptr += sizeof(double); + } else goto handle_unusual; + continue; + // optional bytes string_value = 7; + case 7: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(mutable_string_value(), ptr, ctx); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string aggregate_value = 8; + case 8: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 66)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_aggregate_value(), ptr, ctx, "google.protobuf.UninterpretedOption.aggregate_value"); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool UninterpretedOption::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.UninterpretedOption) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .google.protobuf.UninterpretedOption.NamePart name = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_name())); } else { goto handle_unusual; @@ -11992,13 +13921,12 @@ bool UninterpretedOption::MergePartialFromCodedStream( // optional string identifier_value = 3; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_identifier_value())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->identifier_value().data(), static_cast(this->identifier_value().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.UninterpretedOption.identifier_value"); } else { goto handle_unusual; @@ -12008,11 +13936,10 @@ bool UninterpretedOption::MergePartialFromCodedStream( // optional uint64 positive_int_value = 4; case 4: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) { - set_has_positive_int_value(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (32 & 0xFF)) { + HasBitSetters::set_has_positive_int_value(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64>( input, &positive_int_value_))); } else { goto handle_unusual; @@ -12022,11 +13949,10 @@ bool UninterpretedOption::MergePartialFromCodedStream( // optional int64 negative_int_value = 5; case 5: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { - set_has_negative_int_value(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (40 & 0xFF)) { + HasBitSetters::set_has_negative_int_value(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64>( input, &negative_int_value_))); } else { goto handle_unusual; @@ -12036,11 +13962,10 @@ bool UninterpretedOption::MergePartialFromCodedStream( // optional double double_value = 6; case 6: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(49u /* 49 & 0xFF */)) { - set_has_double_value(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (49 & 0xFF)) { + HasBitSetters::set_has_double_value(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + double, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_DOUBLE>( input, &double_value_))); } else { goto handle_unusual; @@ -12050,9 +13975,8 @@ bool UninterpretedOption::MergePartialFromCodedStream( // optional bytes string_value = 7; case 7: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (58 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadBytes( input, this->mutable_string_value())); } else { goto handle_unusual; @@ -12062,13 +13986,12 @@ bool UninterpretedOption::MergePartialFromCodedStream( // optional string aggregate_value = 8; case 8: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (66 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_aggregate_value())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->aggregate_value().data(), static_cast(this->aggregate_value().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.UninterpretedOption.aggregate_value"); } else { goto handle_unusual; @@ -12081,7 +14004,7 @@ bool UninterpretedOption::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -12095,17 +14018,18 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void UninterpretedOption::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.UninterpretedOption) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .google.protobuf.UninterpretedOption.NamePart name = 2; for (unsigned int i = 0, n = static_cast(this->name_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->name(static_cast(i)), output); @@ -12114,114 +14038,113 @@ void UninterpretedOption::SerializeWithCachedSizes( cached_has_bits = _has_bits_[0]; // optional string identifier_value = 3; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->identifier_value().data(), static_cast(this->identifier_value().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.UninterpretedOption.identifier_value"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 3, this->identifier_value(), output); } // optional uint64 positive_int_value = 4; if (cached_has_bits & 0x00000008u) { - ::google::protobuf::internal::WireFormatLite::WriteUInt64(4, this->positive_int_value(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64(4, this->positive_int_value(), output); } // optional int64 negative_int_value = 5; if (cached_has_bits & 0x00000010u) { - ::google::protobuf::internal::WireFormatLite::WriteInt64(5, this->negative_int_value(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt64(5, this->negative_int_value(), output); } // optional double double_value = 6; if (cached_has_bits & 0x00000020u) { - ::google::protobuf::internal::WireFormatLite::WriteDouble(6, this->double_value(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteDouble(6, this->double_value(), output); } // optional bytes string_value = 7; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesMaybeAliased( 7, this->string_value(), output); } // optional string aggregate_value = 8; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->aggregate_value().data(), static_cast(this->aggregate_value().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.UninterpretedOption.aggregate_value"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 8, this->aggregate_value(), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.UninterpretedOption) } -::google::protobuf::uint8* UninterpretedOption::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* UninterpretedOption::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.UninterpretedOption) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .google.protobuf.UninterpretedOption.NamePart name = 2; for (unsigned int i = 0, n = static_cast(this->name_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 2, this->name(static_cast(i)), deterministic, target); + 2, this->name(static_cast(i)), target); } cached_has_bits = _has_bits_[0]; // optional string identifier_value = 3; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->identifier_value().data(), static_cast(this->identifier_value().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.UninterpretedOption.identifier_value"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 3, this->identifier_value(), target); } // optional uint64 positive_int_value = 4; if (cached_has_bits & 0x00000008u) { - target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(4, this->positive_int_value(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64ToArray(4, this->positive_int_value(), target); } // optional int64 negative_int_value = 5; if (cached_has_bits & 0x00000010u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(5, this->negative_int_value(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt64ToArray(5, this->negative_int_value(), target); } // optional double double_value = 6; if (cached_has_bits & 0x00000020u) { - target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(6, this->double_value(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteDoubleToArray(6, this->double_value(), target); } // optional bytes string_value = 7; if (cached_has_bits & 0x00000002u) { target = - ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesToArray( 7, this->string_value(), target); } // optional string aggregate_value = 8; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->aggregate_value().data(), static_cast(this->aggregate_value().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.UninterpretedOption.aggregate_value"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 8, this->aggregate_value(), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.UninterpretedOption) @@ -12234,76 +14157,81 @@ size_t UninterpretedOption::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.UninterpretedOption.NamePart name = 2; { unsigned int count = static_cast(this->name_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->name(static_cast(i))); } } - if (_has_bits_[0 / 32] & 63u) { + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x0000003fu) { // optional string identifier_value = 3; - if (has_identifier_value()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->identifier_value()); } // optional bytes string_value = 7; - if (has_string_value()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::BytesSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->string_value()); } // optional string aggregate_value = 8; - if (has_aggregate_value()) { + if (cached_has_bits & 0x00000004u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->aggregate_value()); } // optional uint64 positive_int_value = 4; - if (has_positive_int_value()) { + if (cached_has_bits & 0x00000008u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt64Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt64Size( this->positive_int_value()); } // optional int64 negative_int_value = 5; - if (has_negative_int_value()) { + if (cached_has_bits & 0x00000010u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int64Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int64Size( this->negative_int_value()); } // optional double double_value = 6; - if (has_double_value()) { + if (cached_has_bits & 0x00000020u) { total_size += 1 + 8; } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void UninterpretedOption::MergeFrom(const ::google::protobuf::Message& from) { +void UninterpretedOption::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.UninterpretedOption) GOOGLE_DCHECK_NE(&from, this); const UninterpretedOption* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.UninterpretedOption) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.UninterpretedOption) MergeFrom(*source); @@ -12314,12 +14242,12 @@ void UninterpretedOption::MergeFrom(const UninterpretedOption& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.UninterpretedOption) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; name_.MergeFrom(from.name_); cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 63u) { + if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { set_identifier_value(from.identifier_value()); } @@ -12342,7 +14270,7 @@ void UninterpretedOption::MergeFrom(const UninterpretedOption& from) { } } -void UninterpretedOption::CopyFrom(const ::google::protobuf::Message& from) { +void UninterpretedOption::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.UninterpretedOption) if (&from == this) return; Clear(); @@ -12357,7 +14285,7 @@ void UninterpretedOption::CopyFrom(const UninterpretedOption& from) { } bool UninterpretedOption::IsInitialized() const { - if (!::google::protobuf::internal::AllAreInitialized(this->name())) return false; + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(this->name())) return false; return true; } @@ -12370,7 +14298,7 @@ void UninterpretedOption::Swap(UninterpretedOption* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -12382,23 +14310,22 @@ void UninterpretedOption::UnsafeArenaSwap(UninterpretedOption* other) { } void UninterpretedOption::InternalSwap(UninterpretedOption* other) { using std::swap; + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); CastToBase(&name_)->InternalSwap(CastToBase(&other->name_)); - identifier_value_.Swap(&other->identifier_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + identifier_value_.Swap(&other->identifier_value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - string_value_.Swap(&other->string_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + string_value_.Swap(&other->string_value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - aggregate_value_.Swap(&other->aggregate_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + aggregate_value_.Swap(&other->aggregate_value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(positive_int_value_, other->positive_int_value_); swap(negative_int_value_, other->negative_int_value_); swap(double_value_, other->double_value_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata UninterpretedOption::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata UninterpretedOption::GetMetadata() const { + return GetMetadataStatic(); } @@ -12406,6 +14333,17 @@ void UninterpretedOption::InternalSwap(UninterpretedOption* other) { void SourceCodeInfo_Location::InitAsDefaultInstance() { } +class SourceCodeInfo_Location::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_leading_comments(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static void set_has_trailing_comments(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int SourceCodeInfo_Location::kPathFieldNumber; const int SourceCodeInfo_Location::kSpanFieldNumber; @@ -12415,47 +14353,45 @@ const int SourceCodeInfo_Location::kLeadingDetachedCommentsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 SourceCodeInfo_Location::SourceCodeInfo_Location() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.SourceCodeInfo.Location) } -SourceCodeInfo_Location::SourceCodeInfo_Location(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +SourceCodeInfo_Location::SourceCodeInfo_Location(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena), path_(arena), span_(arena), leading_detached_comments_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.SourceCodeInfo.Location) } SourceCodeInfo_Location::SourceCodeInfo_Location(const SourceCodeInfo_Location& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), path_(from.path_), span_(from.span_), leading_detached_comments_(from.leading_detached_comments_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - leading_comments_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + leading_comments_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_leading_comments()) { - leading_comments_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.leading_comments(), + leading_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.leading_comments(), GetArenaNoVirtual()); } - trailing_comments_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + trailing_comments_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_trailing_comments()) { - trailing_comments_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.trailing_comments(), + trailing_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.trailing_comments(), GetArenaNoVirtual()); } // @@protoc_insertion_point(copy_constructor:google.protobuf.SourceCodeInfo.Location) } void SourceCodeInfo_Location::SharedCtor() { - leading_comments_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - trailing_comments_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_SourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto.base); + leading_comments_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + trailing_comments_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } SourceCodeInfo_Location::~SourceCodeInfo_Location() { @@ -12464,34 +14400,29 @@ SourceCodeInfo_Location::~SourceCodeInfo_Location() { } void SourceCodeInfo_Location::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); - leading_comments_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - trailing_comments_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); + leading_comments_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + trailing_comments_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void SourceCodeInfo_Location::ArenaDtor(void* object) { SourceCodeInfo_Location* _this = reinterpret_cast< SourceCodeInfo_Location* >(object); (void)_this; } -void SourceCodeInfo_Location::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void SourceCodeInfo_Location::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void SourceCodeInfo_Location::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* SourceCodeInfo_Location::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const SourceCodeInfo_Location& SourceCodeInfo_Location::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_SourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void SourceCodeInfo_Location::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.SourceCodeInfo.Location) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -12499,7 +14430,7 @@ void SourceCodeInfo_Location::Clear() { span_.Clear(); leading_detached_comments_.Clear(); cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { leading_comments_.ClearNonDefaultToEmpty(); } @@ -12511,28 +14442,102 @@ void SourceCodeInfo_Location::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* SourceCodeInfo_Location::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // repeated int32 path = 1 [packed = true]; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedInt32Parser(mutable_path(), ptr, ctx); + CHK_(ptr); + } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8) { + add_path(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr)); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated int32 span = 2 [packed = true]; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedInt32Parser(mutable_span(), ptr, ctx); + CHK_(ptr); + } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16) { + add_span(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr)); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string leading_comments = 3; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_leading_comments(), ptr, ctx, "google.protobuf.SourceCodeInfo.Location.leading_comments"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string trailing_comments = 4; + case 4: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_trailing_comments(), ptr, ctx, "google.protobuf.SourceCodeInfo.Location.trailing_comments"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // repeated string leading_detached_comments = 6; + case 6: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) { + ptr -= 1; + do { + ptr += 1; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(add_leading_detached_comments(), ptr, ctx, "google.protobuf.SourceCodeInfo.Location.leading_detached_comments"); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 50); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool SourceCodeInfo_Location::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.SourceCodeInfo.Location) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated int32 path = 1 [packed = true]; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPackedPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, this->mutable_path()))); - } else if ( - static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { - DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + } else if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) { + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( 1, 10u, input, this->mutable_path()))); } else { goto handle_unusual; @@ -12542,16 +14547,13 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream( // repeated int32 span = 2 [packed = true]; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPackedPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, this->mutable_span()))); - } else if ( - static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { - DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + } else if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (16 & 0xFF)) { + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( 1, 18u, input, this->mutable_span()))); } else { goto handle_unusual; @@ -12561,13 +14563,12 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream( // optional string leading_comments = 3; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_leading_comments())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->leading_comments().data(), static_cast(this->leading_comments().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.SourceCodeInfo.Location.leading_comments"); } else { goto handle_unusual; @@ -12577,13 +14578,12 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream( // optional string trailing_comments = 4; case 4: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (34 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_trailing_comments())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->trailing_comments().data(), static_cast(this->trailing_comments().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.SourceCodeInfo.Location.trailing_comments"); } else { goto handle_unusual; @@ -12593,14 +14593,13 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream( // repeated string leading_detached_comments = 6; case 6: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (50 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->add_leading_detached_comments())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->leading_detached_comments(this->leading_detached_comments_size() - 1).data(), static_cast(this->leading_detached_comments(this->leading_detached_comments_size() - 1).length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.SourceCodeInfo.Location.leading_detached_comments"); } else { goto handle_unusual; @@ -12613,7 +14612,7 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -12627,141 +14626,141 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SourceCodeInfo_Location::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.SourceCodeInfo.Location) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated int32 path = 1 [packed = true]; if (this->path_size() > 0) { - ::google::protobuf::internal::WireFormatLite::WriteTag(1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); - output->WriteVarint32(static_cast< ::google::protobuf::uint32>( - _path_cached_byte_size_)); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteTag(1, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); + output->WriteVarint32(_path_cached_byte_size_.load( + std::memory_order_relaxed)); } for (int i = 0, n = this->path_size(); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteInt32NoTag( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32NoTag( this->path(i), output); } // repeated int32 span = 2 [packed = true]; if (this->span_size() > 0) { - ::google::protobuf::internal::WireFormatLite::WriteTag(2, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); - output->WriteVarint32(static_cast< ::google::protobuf::uint32>( - _span_cached_byte_size_)); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteTag(2, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); + output->WriteVarint32(_span_cached_byte_size_.load( + std::memory_order_relaxed)); } for (int i = 0, n = this->span_size(); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteInt32NoTag( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32NoTag( this->span(i), output); } cached_has_bits = _has_bits_[0]; // optional string leading_comments = 3; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->leading_comments().data(), static_cast(this->leading_comments().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.SourceCodeInfo.Location.leading_comments"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 3, this->leading_comments(), output); } // optional string trailing_comments = 4; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->trailing_comments().data(), static_cast(this->trailing_comments().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.SourceCodeInfo.Location.trailing_comments"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 4, this->trailing_comments(), output); } // repeated string leading_detached_comments = 6; for (int i = 0, n = this->leading_detached_comments_size(); i < n; i++) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->leading_detached_comments(i).data(), static_cast(this->leading_detached_comments(i).length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.SourceCodeInfo.Location.leading_detached_comments"); - ::google::protobuf::internal::WireFormatLite::WriteString( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteString( 6, this->leading_detached_comments(i), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.SourceCodeInfo.Location) } -::google::protobuf::uint8* SourceCodeInfo_Location::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* SourceCodeInfo_Location::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.SourceCodeInfo.Location) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated int32 path = 1 [packed = true]; if (this->path_size() > 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteTagToArray( 1, - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); - target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( - static_cast< ::google::protobuf::int32>( - _path_cached_byte_size_), target); - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream::WriteVarint32ToArray( + _path_cached_byte_size_.load(std::memory_order_relaxed), + target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: WriteInt32NoTagToArray(this->path_, target); } // repeated int32 span = 2 [packed = true]; if (this->span_size() > 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteTagToArray( 2, - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); - target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( - static_cast< ::google::protobuf::int32>( - _span_cached_byte_size_), target); - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream::WriteVarint32ToArray( + _span_cached_byte_size_.load(std::memory_order_relaxed), + target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: WriteInt32NoTagToArray(this->span_, target); } cached_has_bits = _has_bits_[0]; // optional string leading_comments = 3; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->leading_comments().data(), static_cast(this->leading_comments().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.SourceCodeInfo.Location.leading_comments"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 3, this->leading_comments(), target); } // optional string trailing_comments = 4; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->trailing_comments().data(), static_cast(this->trailing_comments().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.SourceCodeInfo.Location.trailing_comments"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 4, this->trailing_comments(), target); } // repeated string leading_detached_comments = 6; for (int i = 0, n = this->leading_detached_comments_size(); i < n; i++) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->leading_detached_comments(i).data(), static_cast(this->leading_detached_comments(i).length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.SourceCodeInfo.Location.leading_detached_comments"); - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: WriteStringToArray(6, this->leading_detached_comments(i), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.SourceCodeInfo.Location) @@ -12774,79 +14773,82 @@ size_t SourceCodeInfo_Location::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated int32 path = 1 [packed = true]; { - size_t data_size = ::google::protobuf::internal::WireFormatLite:: + size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: Int32Size(this->path_); if (data_size > 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - static_cast< ::google::protobuf::int32>(data_size)); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( + static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } - int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _path_cached_byte_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); + _path_cached_byte_size_.store(cached_size, + std::memory_order_relaxed); total_size += data_size; } // repeated int32 span = 2 [packed = true]; { - size_t data_size = ::google::protobuf::internal::WireFormatLite:: + size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: Int32Size(this->span_); if (data_size > 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - static_cast< ::google::protobuf::int32>(data_size)); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( + static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } - int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _span_cached_byte_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); + _span_cached_byte_size_.store(cached_size, + std::memory_order_relaxed); total_size += data_size; } // repeated string leading_detached_comments = 6; total_size += 1 * - ::google::protobuf::internal::FromIntSize(this->leading_detached_comments_size()); + ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->leading_detached_comments_size()); for (int i = 0, n = this->leading_detached_comments_size(); i < n; i++) { - total_size += ::google::protobuf::internal::WireFormatLite::StringSize( + total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->leading_detached_comments(i)); } - if (_has_bits_[0 / 32] & 3u) { + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x00000003u) { // optional string leading_comments = 3; - if (has_leading_comments()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->leading_comments()); } // optional string trailing_comments = 4; - if (has_trailing_comments()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->trailing_comments()); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void SourceCodeInfo_Location::MergeFrom(const ::google::protobuf::Message& from) { +void SourceCodeInfo_Location::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.SourceCodeInfo.Location) GOOGLE_DCHECK_NE(&from, this); const SourceCodeInfo_Location* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.SourceCodeInfo.Location) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.SourceCodeInfo.Location) MergeFrom(*source); @@ -12857,14 +14859,14 @@ void SourceCodeInfo_Location::MergeFrom(const SourceCodeInfo_Location& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.SourceCodeInfo.Location) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; path_.MergeFrom(from.path_); span_.MergeFrom(from.span_); leading_detached_comments_.MergeFrom(from.leading_detached_comments_); cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 3u) { + if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { set_leading_comments(from.leading_comments()); } @@ -12874,7 +14876,7 @@ void SourceCodeInfo_Location::MergeFrom(const SourceCodeInfo_Location& from) { } } -void SourceCodeInfo_Location::CopyFrom(const ::google::protobuf::Message& from) { +void SourceCodeInfo_Location::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.SourceCodeInfo.Location) if (&from == this) return; Clear(); @@ -12901,7 +14903,7 @@ void SourceCodeInfo_Location::Swap(SourceCodeInfo_Location* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -12913,20 +14915,19 @@ void SourceCodeInfo_Location::UnsafeArenaSwap(SourceCodeInfo_Location* other) { } void SourceCodeInfo_Location::InternalSwap(SourceCodeInfo_Location* other) { using std::swap; + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); path_.InternalSwap(&other->path_); span_.InternalSwap(&other->span_); leading_detached_comments_.InternalSwap(CastToBase(&other->leading_detached_comments_)); - leading_comments_.Swap(&other->leading_comments_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + leading_comments_.Swap(&other->leading_comments_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - trailing_comments_.Swap(&other->trailing_comments_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + trailing_comments_.Swap(&other->trailing_comments_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata SourceCodeInfo_Location::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata SourceCodeInfo_Location::GetMetadata() const { + return GetMetadataStatic(); } @@ -12934,29 +14935,31 @@ void SourceCodeInfo_Location::InternalSwap(SourceCodeInfo_Location* other) { void SourceCodeInfo::InitAsDefaultInstance() { } +class SourceCodeInfo::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int SourceCodeInfo::kLocationFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 SourceCodeInfo::SourceCodeInfo() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.SourceCodeInfo) } -SourceCodeInfo::SourceCodeInfo(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +SourceCodeInfo::SourceCodeInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena), location_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.SourceCodeInfo) } SourceCodeInfo::SourceCodeInfo(const SourceCodeInfo& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), location_(from.location_) { _internal_metadata_.MergeFrom(from._internal_metadata_); @@ -12964,6 +14967,7 @@ SourceCodeInfo::SourceCodeInfo(const SourceCodeInfo& from) } void SourceCodeInfo::SharedCtor() { + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_SourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto.base); } SourceCodeInfo::~SourceCodeInfo() { @@ -12972,32 +14976,27 @@ SourceCodeInfo::~SourceCodeInfo() { } void SourceCodeInfo::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void SourceCodeInfo::ArenaDtor(void* object) { SourceCodeInfo* _this = reinterpret_cast< SourceCodeInfo* >(object); (void)_this; } -void SourceCodeInfo::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void SourceCodeInfo::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void SourceCodeInfo::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* SourceCodeInfo::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const SourceCodeInfo& SourceCodeInfo::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_SourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void SourceCodeInfo::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.SourceCodeInfo) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -13006,21 +15005,61 @@ void SourceCodeInfo::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* SourceCodeInfo::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // repeated .google.protobuf.SourceCodeInfo.Location location = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_location(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 10); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool SourceCodeInfo::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.SourceCodeInfo) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .google.protobuf.SourceCodeInfo.Location location = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_location())); } else { goto handle_unusual; @@ -13033,7 +15072,7 @@ bool SourceCodeInfo::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -13047,46 +15086,46 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SourceCodeInfo::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.SourceCodeInfo) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .google.protobuf.SourceCodeInfo.Location location = 1; for (unsigned int i = 0, n = static_cast(this->location_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->location(static_cast(i)), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.SourceCodeInfo) } -::google::protobuf::uint8* SourceCodeInfo::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* SourceCodeInfo::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.SourceCodeInfo) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .google.protobuf.SourceCodeInfo.Location location = 1; for (unsigned int i = 0, n = static_cast(this->location_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 1, this->location(static_cast(i)), deterministic, target); + 1, this->location(static_cast(i)), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.SourceCodeInfo) @@ -13099,34 +15138,38 @@ size_t SourceCodeInfo::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.SourceCodeInfo.Location location = 1; { unsigned int count = static_cast(this->location_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->location(static_cast(i))); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void SourceCodeInfo::MergeFrom(const ::google::protobuf::Message& from) { +void SourceCodeInfo::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.SourceCodeInfo) GOOGLE_DCHECK_NE(&from, this); const SourceCodeInfo* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.SourceCodeInfo) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.SourceCodeInfo) MergeFrom(*source); @@ -13137,13 +15180,13 @@ void SourceCodeInfo::MergeFrom(const SourceCodeInfo& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.SourceCodeInfo) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; location_.MergeFrom(from.location_); } -void SourceCodeInfo::CopyFrom(const ::google::protobuf::Message& from) { +void SourceCodeInfo::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.SourceCodeInfo) if (&from == this) return; Clear(); @@ -13170,7 +15213,7 @@ void SourceCodeInfo::Swap(SourceCodeInfo* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -13182,14 +15225,13 @@ void SourceCodeInfo::UnsafeArenaSwap(SourceCodeInfo* other) { } void SourceCodeInfo::InternalSwap(SourceCodeInfo* other) { using std::swap; - CastToBase(&location_)->InternalSwap(CastToBase(&other->location_)); - swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); + CastToBase(&location_)->InternalSwap(CastToBase(&other->location_)); } -::google::protobuf::Metadata SourceCodeInfo::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata SourceCodeInfo::GetMetadata() const { + return GetMetadataStatic(); } @@ -13197,6 +15239,20 @@ void SourceCodeInfo::InternalSwap(SourceCodeInfo* other) { void GeneratedCodeInfo_Annotation::InitAsDefaultInstance() { } +class GeneratedCodeInfo_Annotation::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); + static void set_has_source_file(HasBits* has_bits) { + (*has_bits)[0] |= 1u; + } + static void set_has_begin(HasBits* has_bits) { + (*has_bits)[0] |= 2u; + } + static void set_has_end(HasBits* has_bits) { + (*has_bits)[0] |= 4u; + } +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int GeneratedCodeInfo_Annotation::kPathFieldNumber; const int GeneratedCodeInfo_Annotation::kSourceFileFieldNumber; @@ -13205,30 +15261,27 @@ const int GeneratedCodeInfo_Annotation::kEndFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.GeneratedCodeInfo.Annotation) } -GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena), path_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.GeneratedCodeInfo.Annotation) } GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(const GeneratedCodeInfo_Annotation& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), path_(from.path_) { _internal_metadata_.MergeFrom(from._internal_metadata_); - source_file_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + source_file_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.has_source_file()) { - source_file_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.source_file(), + source_file_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.source_file(), GetArenaNoVirtual()); } ::memcpy(&begin_, &from.begin_, @@ -13238,7 +15291,8 @@ GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(const GeneratedCodeIn } void GeneratedCodeInfo_Annotation::SharedCtor() { - source_file_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_GeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto.base); + source_file_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(&begin_, 0, static_cast( reinterpret_cast(&end_) - reinterpret_cast(&begin_)) + sizeof(end_)); @@ -13250,33 +15304,28 @@ GeneratedCodeInfo_Annotation::~GeneratedCodeInfo_Annotation() { } void GeneratedCodeInfo_Annotation::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); - source_file_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); + source_file_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void GeneratedCodeInfo_Annotation::ArenaDtor(void* object) { GeneratedCodeInfo_Annotation* _this = reinterpret_cast< GeneratedCodeInfo_Annotation* >(object); (void)_this; } -void GeneratedCodeInfo_Annotation::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void GeneratedCodeInfo_Annotation::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void GeneratedCodeInfo_Annotation::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* GeneratedCodeInfo_Annotation::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const GeneratedCodeInfo_Annotation& GeneratedCodeInfo_Annotation::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_GeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void GeneratedCodeInfo_Annotation::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.GeneratedCodeInfo.Annotation) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -13285,7 +15334,7 @@ void GeneratedCodeInfo_Annotation::Clear() { if (cached_has_bits & 0x00000001u) { source_file_.ClearNonDefaultToEmpty(); } - if (cached_has_bits & 6u) { + if (cached_has_bits & 0x00000006u) { ::memset(&begin_, 0, static_cast( reinterpret_cast(&end_) - reinterpret_cast(&begin_)) + sizeof(end_)); @@ -13294,28 +15343,89 @@ void GeneratedCodeInfo_Annotation::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* GeneratedCodeInfo_Annotation::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + HasBitSetters::HasBits has_bits{}; + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // repeated int32 path = 1 [packed = true]; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedInt32Parser(mutable_path(), ptr, ctx); + CHK_(ptr); + } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8) { + add_path(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr)); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional string source_file = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8Verify(mutable_source_file(), ptr, ctx, "google.protobuf.GeneratedCodeInfo.Annotation.source_file"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional int32 begin = 3; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) { + HasBitSetters::set_has_begin(&has_bits); + begin_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // optional int32 end = 4; + case 4: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { + HasBitSetters::set_has_end(&has_bits); + end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + _has_bits_.Or(has_bits); + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.GeneratedCodeInfo.Annotation) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated int32 path = 1 [packed = true]; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPackedPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, this->mutable_path()))); - } else if ( - static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { - DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + } else if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) { + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( 1, 10u, input, this->mutable_path()))); } else { goto handle_unusual; @@ -13325,13 +15435,12 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream( // optional string source_file = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_source_file())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->source_file().data(), static_cast(this->source_file().length()), - ::google::protobuf::internal::WireFormat::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::PARSE, "google.protobuf.GeneratedCodeInfo.Annotation.source_file"); } else { goto handle_unusual; @@ -13341,11 +15450,10 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream( // optional int32 begin = 3; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { - set_has_begin(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (24 & 0xFF)) { + HasBitSetters::set_has_begin(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &begin_))); } else { goto handle_unusual; @@ -13355,11 +15463,10 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream( // optional int32 end = 4; case 4: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) { - set_has_end(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (32 & 0xFF)) { + HasBitSetters::set_has_end(&_has_bits_); + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &end_))); } else { goto handle_unusual; @@ -13372,7 +15479,7 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -13386,96 +15493,96 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void GeneratedCodeInfo_Annotation::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.GeneratedCodeInfo.Annotation) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated int32 path = 1 [packed = true]; if (this->path_size() > 0) { - ::google::protobuf::internal::WireFormatLite::WriteTag(1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); - output->WriteVarint32(static_cast< ::google::protobuf::uint32>( - _path_cached_byte_size_)); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteTag(1, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); + output->WriteVarint32(_path_cached_byte_size_.load( + std::memory_order_relaxed)); } for (int i = 0, n = this->path_size(); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteInt32NoTag( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32NoTag( this->path(i), output); } cached_has_bits = _has_bits_[0]; // optional string source_file = 2; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->source_file().data(), static_cast(this->source_file().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.GeneratedCodeInfo.Annotation.source_file"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->source_file(), output); } // optional int32 begin = 3; if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->begin(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(3, this->begin(), output); } // optional int32 end = 4; if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(4, this->end(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(4, this->end(), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.GeneratedCodeInfo.Annotation) } -::google::protobuf::uint8* GeneratedCodeInfo_Annotation::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* GeneratedCodeInfo_Annotation::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.GeneratedCodeInfo.Annotation) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated int32 path = 1 [packed = true]; if (this->path_size() > 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteTagToArray( 1, - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); - target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( - static_cast< ::google::protobuf::int32>( - _path_cached_byte_size_), target); - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream::WriteVarint32ToArray( + _path_cached_byte_size_.load(std::memory_order_relaxed), + target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: WriteInt32NoTagToArray(this->path_, target); } cached_has_bits = _has_bits_[0]; // optional string source_file = 2; if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->source_file().data(), static_cast(this->source_file().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "google.protobuf.GeneratedCodeInfo.Annotation.source_file"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 2, this->source_file(), target); } // optional int32 begin = 3; if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->begin(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(3, this->begin(), target); } // optional int32 end = 4; if (cached_has_bits & 0x00000004u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(4, this->end(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->end(), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.GeneratedCodeInfo.Annotation) @@ -13488,62 +15595,66 @@ size_t GeneratedCodeInfo_Annotation::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated int32 path = 1 [packed = true]; { - size_t data_size = ::google::protobuf::internal::WireFormatLite:: + size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: Int32Size(this->path_); if (data_size > 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - static_cast< ::google::protobuf::int32>(data_size)); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( + static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } - int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _path_cached_byte_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); + _path_cached_byte_size_.store(cached_size, + std::memory_order_relaxed); total_size += data_size; } - if (_has_bits_[0 / 32] & 7u) { + cached_has_bits = _has_bits_[0]; + if (cached_has_bits & 0x00000007u) { // optional string source_file = 2; - if (has_source_file()) { + if (cached_has_bits & 0x00000001u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->source_file()); } // optional int32 begin = 3; - if (has_begin()) { + if (cached_has_bits & 0x00000002u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->begin()); } // optional int32 end = 4; - if (has_end()) { + if (cached_has_bits & 0x00000004u) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->end()); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void GeneratedCodeInfo_Annotation::MergeFrom(const ::google::protobuf::Message& from) { +void GeneratedCodeInfo_Annotation::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.GeneratedCodeInfo.Annotation) GOOGLE_DCHECK_NE(&from, this); const GeneratedCodeInfo_Annotation* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.GeneratedCodeInfo.Annotation) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.GeneratedCodeInfo.Annotation) MergeFrom(*source); @@ -13554,12 +15665,12 @@ void GeneratedCodeInfo_Annotation::MergeFrom(const GeneratedCodeInfo_Annotation& // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.GeneratedCodeInfo.Annotation) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; path_.MergeFrom(from.path_); cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 7u) { + if (cached_has_bits & 0x00000007u) { if (cached_has_bits & 0x00000001u) { set_source_file(from.source_file()); } @@ -13573,7 +15684,7 @@ void GeneratedCodeInfo_Annotation::MergeFrom(const GeneratedCodeInfo_Annotation& } } -void GeneratedCodeInfo_Annotation::CopyFrom(const ::google::protobuf::Message& from) { +void GeneratedCodeInfo_Annotation::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.GeneratedCodeInfo.Annotation) if (&from == this) return; Clear(); @@ -13600,7 +15711,7 @@ void GeneratedCodeInfo_Annotation::Swap(GeneratedCodeInfo_Annotation* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -13612,18 +15723,17 @@ void GeneratedCodeInfo_Annotation::UnsafeArenaSwap(GeneratedCodeInfo_Annotation* } void GeneratedCodeInfo_Annotation::InternalSwap(GeneratedCodeInfo_Annotation* other) { using std::swap; + _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); path_.InternalSwap(&other->path_); - source_file_.Swap(&other->source_file_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + source_file_.Swap(&other->source_file_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(begin_, other->begin_); swap(end_, other->end_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata GeneratedCodeInfo_Annotation::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata GeneratedCodeInfo_Annotation::GetMetadata() const { + return GetMetadataStatic(); } @@ -13631,29 +15741,31 @@ void GeneratedCodeInfo_Annotation::InternalSwap(GeneratedCodeInfo_Annotation* ot void GeneratedCodeInfo::InitAsDefaultInstance() { } +class GeneratedCodeInfo::HasBitSetters { + public: + using HasBits = decltype(std::declval()._has_bits_); +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int GeneratedCodeInfo::kAnnotationFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 GeneratedCodeInfo::GeneratedCodeInfo() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.GeneratedCodeInfo) } -GeneratedCodeInfo::GeneratedCodeInfo(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +GeneratedCodeInfo::GeneratedCodeInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena), annotation_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.GeneratedCodeInfo) } GeneratedCodeInfo::GeneratedCodeInfo(const GeneratedCodeInfo& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), _has_bits_(from._has_bits_), annotation_(from.annotation_) { _internal_metadata_.MergeFrom(from._internal_metadata_); @@ -13661,6 +15773,7 @@ GeneratedCodeInfo::GeneratedCodeInfo(const GeneratedCodeInfo& from) } void GeneratedCodeInfo::SharedCtor() { + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_GeneratedCodeInfo_google_2fprotobuf_2fdescriptor_2eproto.base); } GeneratedCodeInfo::~GeneratedCodeInfo() { @@ -13669,32 +15782,27 @@ GeneratedCodeInfo::~GeneratedCodeInfo() { } void GeneratedCodeInfo::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void GeneratedCodeInfo::ArenaDtor(void* object) { GeneratedCodeInfo* _this = reinterpret_cast< GeneratedCodeInfo* >(object); (void)_this; } -void GeneratedCodeInfo::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void GeneratedCodeInfo::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void GeneratedCodeInfo::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* GeneratedCodeInfo::descriptor() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const GeneratedCodeInfo& GeneratedCodeInfo::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_GeneratedCodeInfo_google_2fprotobuf_2fdescriptor_2eproto.base); return *internal_default_instance(); } void GeneratedCodeInfo::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.GeneratedCodeInfo) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -13703,21 +15811,61 @@ void GeneratedCodeInfo::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* GeneratedCodeInfo::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_annotation(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 10); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool GeneratedCodeInfo::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.GeneratedCodeInfo) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_annotation())); } else { goto handle_unusual; @@ -13730,7 +15878,7 @@ bool GeneratedCodeInfo::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -13744,46 +15892,46 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void GeneratedCodeInfo::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.GeneratedCodeInfo) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1; for (unsigned int i = 0, n = static_cast(this->annotation_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->annotation(static_cast(i)), output); } if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.GeneratedCodeInfo) } -::google::protobuf::uint8* GeneratedCodeInfo::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* GeneratedCodeInfo::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.GeneratedCodeInfo) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1; for (unsigned int i = 0, n = static_cast(this->annotation_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 1, this->annotation(static_cast(i)), deterministic, target); + 1, this->annotation(static_cast(i)), target); } if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.GeneratedCodeInfo) @@ -13796,34 +15944,38 @@ size_t GeneratedCodeInfo::ByteSizeLong() const { if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1; { unsigned int count = static_cast(this->annotation_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->annotation(static_cast(i))); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void GeneratedCodeInfo::MergeFrom(const ::google::protobuf::Message& from) { +void GeneratedCodeInfo::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.GeneratedCodeInfo) GOOGLE_DCHECK_NE(&from, this); const GeneratedCodeInfo* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.GeneratedCodeInfo) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.GeneratedCodeInfo) MergeFrom(*source); @@ -13834,13 +15986,13 @@ void GeneratedCodeInfo::MergeFrom(const GeneratedCodeInfo& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.GeneratedCodeInfo) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; annotation_.MergeFrom(from.annotation_); } -void GeneratedCodeInfo::CopyFrom(const ::google::protobuf::Message& from) { +void GeneratedCodeInfo::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.GeneratedCodeInfo) if (&from == this) return; Clear(); @@ -13867,7 +16019,7 @@ void GeneratedCodeInfo::Swap(GeneratedCodeInfo* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -13879,104 +16031,101 @@ void GeneratedCodeInfo::UnsafeArenaSwap(GeneratedCodeInfo* other) { } void GeneratedCodeInfo::InternalSwap(GeneratedCodeInfo* other) { using std::swap; - CastToBase(&annotation_)->InternalSwap(CastToBase(&other->annotation_)); - swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); + swap(_has_bits_[0], other->_has_bits_[0]); + CastToBase(&annotation_)->InternalSwap(CastToBase(&other->annotation_)); } -::google::protobuf::Metadata GeneratedCodeInfo::GetMetadata() const { - protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata GeneratedCodeInfo::GetMetadata() const { + return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileDescriptorSet* Arena::CreateMaybeMessage< ::google::protobuf::FileDescriptorSet >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::FileDescriptorSet >(arena); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::FileDescriptorSet* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::FileDescriptorSet >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::FileDescriptorSet >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::FileDescriptorProto >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::FileDescriptorProto >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::FileDescriptorProto* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::FileDescriptorProto >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::FileDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto_ExtensionRange >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::DescriptorProto_ExtensionRange >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto_ReservedRange >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::DescriptorProto_ReservedRange >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::DescriptorProto >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::DescriptorProto* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::DescriptorProto >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::DescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ExtensionRangeOptions* Arena::CreateMaybeMessage< ::google::protobuf::ExtensionRangeOptions >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::ExtensionRangeOptions >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::FieldDescriptorProto >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::FieldDescriptorProto >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::OneofDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::OneofDescriptorProto >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::OneofDescriptorProto >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::OneofDescriptorProto* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::OneofDescriptorProto >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::OneofDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMaybeMessage< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::EnumDescriptorProto >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::EnumDescriptorProto >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::EnumValueDescriptorProto >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::EnumValueDescriptorProto >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ServiceDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::ServiceDescriptorProto >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::ServiceDescriptorProto >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MethodDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::MethodDescriptorProto >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::MethodDescriptorProto >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::MethodDescriptorProto* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::MethodDescriptorProto >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::MethodDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileOptions* Arena::CreateMaybeMessage< ::google::protobuf::FileOptions >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::FileOptions >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::FileOptions* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::FileOptions >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::FileOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MessageOptions* Arena::CreateMaybeMessage< ::google::protobuf::MessageOptions >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::MessageOptions >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::MessageOptions* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::MessageOptions >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::MessageOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldOptions* Arena::CreateMaybeMessage< ::google::protobuf::FieldOptions >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::FieldOptions >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::FieldOptions* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::FieldOptions >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::FieldOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::OneofOptions* Arena::CreateMaybeMessage< ::google::protobuf::OneofOptions >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::OneofOptions >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::OneofOptions* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::OneofOptions >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::OneofOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumOptions* Arena::CreateMaybeMessage< ::google::protobuf::EnumOptions >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::EnumOptions >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::EnumOptions* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::EnumOptions >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::EnumOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValueOptions* Arena::CreateMaybeMessage< ::google::protobuf::EnumValueOptions >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::EnumValueOptions >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::EnumValueOptions* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::EnumValueOptions >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::EnumValueOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ServiceOptions* Arena::CreateMaybeMessage< ::google::protobuf::ServiceOptions >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::ServiceOptions >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::ServiceOptions* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::ServiceOptions >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::ServiceOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MethodOptions* Arena::CreateMaybeMessage< ::google::protobuf::MethodOptions >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::MethodOptions >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::MethodOptions* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::MethodOptions >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::MethodOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMaybeMessage< ::google::protobuf::UninterpretedOption_NamePart >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::UninterpretedOption_NamePart >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UninterpretedOption* Arena::CreateMaybeMessage< ::google::protobuf::UninterpretedOption >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::UninterpretedOption >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::UninterpretedOption* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::UninterpretedOption >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::UninterpretedOption >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMaybeMessage< ::google::protobuf::SourceCodeInfo_Location >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::SourceCodeInfo_Location >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceCodeInfo* Arena::CreateMaybeMessage< ::google::protobuf::SourceCodeInfo >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::SourceCodeInfo >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::SourceCodeInfo* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::SourceCodeInfo >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::SourceCodeInfo >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMaybeMessage< ::google::protobuf::GeneratedCodeInfo_Annotation >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::GeneratedCodeInfo_Annotation >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::GeneratedCodeInfo* Arena::CreateMaybeMessage< ::google::protobuf::GeneratedCodeInfo >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::GeneratedCodeInfo >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo >(arena); } -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) +#include diff --git a/third_party/protobuf/src/google/protobuf/descriptor.pb.h b/third_party/protobuf/src/google/protobuf/descriptor.pb.h index d7b2270b..43c20a85 100644 --- a/third_party/protobuf/src/google/protobuf/descriptor.pb.h +++ b/third_party/protobuf/src/google/protobuf/descriptor.pb.h @@ -1,24 +1,25 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/descriptor.proto -#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto -#define PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto +#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto +#include #include -#include - -#if GOOGLE_PROTOBUF_VERSION < 3006001 +#include +#if PROTOBUF_VERSION < 3008000 #error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update +#error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3008000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please +#error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include @@ -26,146 +27,149 @@ #include #include #include +#include #include #include // IWYU pragma: export #include // IWYU pragma: export #include #include // @@protoc_insertion_point(includes) -#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto LIBPROTOBUF_EXPORT +#include +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto PROTOBUF_EXPORT +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE -namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto { // Internal implementation detail -- do not use these members. -struct LIBPROTOBUF_EXPORT TableStruct { - static const ::google::protobuf::internal::ParseTableField entries[]; - static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; - static const ::google::protobuf::internal::ParseTable schema[27]; - static const ::google::protobuf::internal::FieldMetadata field_metadata[]; - static const ::google::protobuf::internal::SerializationTable serialization_table[]; - static const ::google::protobuf::uint32 offsets[]; +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fdescriptor_2eproto { + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[27] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; + static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; + static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; -void LIBPROTOBUF_EXPORT AddDescriptors(); -} // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto -namespace google { -namespace protobuf { +extern PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fdescriptor_2eproto; +PROTOBUF_NAMESPACE_OPEN class DescriptorProto; class DescriptorProtoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern DescriptorProtoDefaultTypeInternal _DescriptorProto_default_instance_; +PROTOBUF_EXPORT extern DescriptorProtoDefaultTypeInternal _DescriptorProto_default_instance_; class DescriptorProto_ExtensionRange; class DescriptorProto_ExtensionRangeDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern DescriptorProto_ExtensionRangeDefaultTypeInternal _DescriptorProto_ExtensionRange_default_instance_; +PROTOBUF_EXPORT extern DescriptorProto_ExtensionRangeDefaultTypeInternal _DescriptorProto_ExtensionRange_default_instance_; class DescriptorProto_ReservedRange; class DescriptorProto_ReservedRangeDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern DescriptorProto_ReservedRangeDefaultTypeInternal _DescriptorProto_ReservedRange_default_instance_; +PROTOBUF_EXPORT extern DescriptorProto_ReservedRangeDefaultTypeInternal _DescriptorProto_ReservedRange_default_instance_; class EnumDescriptorProto; class EnumDescriptorProtoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern EnumDescriptorProtoDefaultTypeInternal _EnumDescriptorProto_default_instance_; +PROTOBUF_EXPORT extern EnumDescriptorProtoDefaultTypeInternal _EnumDescriptorProto_default_instance_; class EnumDescriptorProto_EnumReservedRange; class EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal _EnumDescriptorProto_EnumReservedRange_default_instance_; +PROTOBUF_EXPORT extern EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal _EnumDescriptorProto_EnumReservedRange_default_instance_; class EnumOptions; class EnumOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern EnumOptionsDefaultTypeInternal _EnumOptions_default_instance_; +PROTOBUF_EXPORT extern EnumOptionsDefaultTypeInternal _EnumOptions_default_instance_; class EnumValueDescriptorProto; class EnumValueDescriptorProtoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern EnumValueDescriptorProtoDefaultTypeInternal _EnumValueDescriptorProto_default_instance_; +PROTOBUF_EXPORT extern EnumValueDescriptorProtoDefaultTypeInternal _EnumValueDescriptorProto_default_instance_; class EnumValueOptions; class EnumValueOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern EnumValueOptionsDefaultTypeInternal _EnumValueOptions_default_instance_; +PROTOBUF_EXPORT extern EnumValueOptionsDefaultTypeInternal _EnumValueOptions_default_instance_; class ExtensionRangeOptions; class ExtensionRangeOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern ExtensionRangeOptionsDefaultTypeInternal _ExtensionRangeOptions_default_instance_; +PROTOBUF_EXPORT extern ExtensionRangeOptionsDefaultTypeInternal _ExtensionRangeOptions_default_instance_; class FieldDescriptorProto; class FieldDescriptorProtoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern FieldDescriptorProtoDefaultTypeInternal _FieldDescriptorProto_default_instance_; +PROTOBUF_EXPORT extern FieldDescriptorProtoDefaultTypeInternal _FieldDescriptorProto_default_instance_; class FieldOptions; class FieldOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern FieldOptionsDefaultTypeInternal _FieldOptions_default_instance_; +PROTOBUF_EXPORT extern FieldOptionsDefaultTypeInternal _FieldOptions_default_instance_; class FileDescriptorProto; class FileDescriptorProtoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern FileDescriptorProtoDefaultTypeInternal _FileDescriptorProto_default_instance_; +PROTOBUF_EXPORT extern FileDescriptorProtoDefaultTypeInternal _FileDescriptorProto_default_instance_; class FileDescriptorSet; class FileDescriptorSetDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern FileDescriptorSetDefaultTypeInternal _FileDescriptorSet_default_instance_; +PROTOBUF_EXPORT extern FileDescriptorSetDefaultTypeInternal _FileDescriptorSet_default_instance_; class FileOptions; class FileOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern FileOptionsDefaultTypeInternal _FileOptions_default_instance_; +PROTOBUF_EXPORT extern FileOptionsDefaultTypeInternal _FileOptions_default_instance_; class GeneratedCodeInfo; class GeneratedCodeInfoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern GeneratedCodeInfoDefaultTypeInternal _GeneratedCodeInfo_default_instance_; +PROTOBUF_EXPORT extern GeneratedCodeInfoDefaultTypeInternal _GeneratedCodeInfo_default_instance_; class GeneratedCodeInfo_Annotation; class GeneratedCodeInfo_AnnotationDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern GeneratedCodeInfo_AnnotationDefaultTypeInternal _GeneratedCodeInfo_Annotation_default_instance_; +PROTOBUF_EXPORT extern GeneratedCodeInfo_AnnotationDefaultTypeInternal _GeneratedCodeInfo_Annotation_default_instance_; class MessageOptions; class MessageOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern MessageOptionsDefaultTypeInternal _MessageOptions_default_instance_; +PROTOBUF_EXPORT extern MessageOptionsDefaultTypeInternal _MessageOptions_default_instance_; class MethodDescriptorProto; class MethodDescriptorProtoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern MethodDescriptorProtoDefaultTypeInternal _MethodDescriptorProto_default_instance_; +PROTOBUF_EXPORT extern MethodDescriptorProtoDefaultTypeInternal _MethodDescriptorProto_default_instance_; class MethodOptions; class MethodOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern MethodOptionsDefaultTypeInternal _MethodOptions_default_instance_; +PROTOBUF_EXPORT extern MethodOptionsDefaultTypeInternal _MethodOptions_default_instance_; class OneofDescriptorProto; class OneofDescriptorProtoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern OneofDescriptorProtoDefaultTypeInternal _OneofDescriptorProto_default_instance_; +PROTOBUF_EXPORT extern OneofDescriptorProtoDefaultTypeInternal _OneofDescriptorProto_default_instance_; class OneofOptions; class OneofOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern OneofOptionsDefaultTypeInternal _OneofOptions_default_instance_; +PROTOBUF_EXPORT extern OneofOptionsDefaultTypeInternal _OneofOptions_default_instance_; class ServiceDescriptorProto; class ServiceDescriptorProtoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern ServiceDescriptorProtoDefaultTypeInternal _ServiceDescriptorProto_default_instance_; +PROTOBUF_EXPORT extern ServiceDescriptorProtoDefaultTypeInternal _ServiceDescriptorProto_default_instance_; class ServiceOptions; class ServiceOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern ServiceOptionsDefaultTypeInternal _ServiceOptions_default_instance_; +PROTOBUF_EXPORT extern ServiceOptionsDefaultTypeInternal _ServiceOptions_default_instance_; class SourceCodeInfo; class SourceCodeInfoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern SourceCodeInfoDefaultTypeInternal _SourceCodeInfo_default_instance_; +PROTOBUF_EXPORT extern SourceCodeInfoDefaultTypeInternal _SourceCodeInfo_default_instance_; class SourceCodeInfo_Location; class SourceCodeInfo_LocationDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern SourceCodeInfo_LocationDefaultTypeInternal _SourceCodeInfo_Location_default_instance_; +PROTOBUF_EXPORT extern SourceCodeInfo_LocationDefaultTypeInternal _SourceCodeInfo_Location_default_instance_; class UninterpretedOption; class UninterpretedOptionDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern UninterpretedOptionDefaultTypeInternal _UninterpretedOption_default_instance_; +PROTOBUF_EXPORT extern UninterpretedOptionDefaultTypeInternal _UninterpretedOption_default_instance_; class UninterpretedOption_NamePart; class UninterpretedOption_NamePartDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern UninterpretedOption_NamePartDefaultTypeInternal _UninterpretedOption_NamePart_default_instance_; -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto_ExtensionRange>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto_ReservedRange>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::EnumDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMaybeMessage<::google::protobuf::EnumDescriptorProto_EnumReservedRange>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumOptions* Arena::CreateMaybeMessage<::google::protobuf::EnumOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::EnumValueDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueOptions* Arena::CreateMaybeMessage<::google::protobuf::EnumValueOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::ExtensionRangeOptions* Arena::CreateMaybeMessage<::google::protobuf::ExtensionRangeOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::FieldDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldOptions* Arena::CreateMaybeMessage<::google::protobuf::FieldOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::FileDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorSet* Arena::CreateMaybeMessage<::google::protobuf::FileDescriptorSet>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileOptions* Arena::CreateMaybeMessage<::google::protobuf::FileOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo* Arena::CreateMaybeMessage<::google::protobuf::GeneratedCodeInfo>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMaybeMessage<::google::protobuf::GeneratedCodeInfo_Annotation>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::MessageOptions* Arena::CreateMaybeMessage<::google::protobuf::MessageOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::MethodDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodOptions* Arena::CreateMaybeMessage<::google::protobuf::MethodOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::OneofDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofOptions* Arena::CreateMaybeMessage<::google::protobuf::OneofOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::ServiceDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceOptions* Arena::CreateMaybeMessage<::google::protobuf::ServiceOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo* Arena::CreateMaybeMessage<::google::protobuf::SourceCodeInfo>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMaybeMessage<::google::protobuf::SourceCodeInfo_Location>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption* Arena::CreateMaybeMessage<::google::protobuf::UninterpretedOption>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMaybeMessage<::google::protobuf::UninterpretedOption_NamePart>(Arena*); -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { +PROTOBUF_EXPORT extern UninterpretedOption_NamePartDefaultTypeInternal _UninterpretedOption_NamePart_default_instance_; +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::DescriptorProto* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::EnumOptions* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::EnumValueOptions* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::FieldOptions* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::FileDescriptorProto* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::FileDescriptorSet* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::FileOptions* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::MessageOptions* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::MethodDescriptorProto* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::MethodOptions* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::OneofDescriptorProto* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::OneofOptions* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::ServiceOptions* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::SourceCodeInfo* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::UninterpretedOption* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart* Arena::CreateMaybeMessage(Arena*); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN -enum FieldDescriptorProto_Type { +enum FieldDescriptorProto_Type : int { FieldDescriptorProto_Type_TYPE_DOUBLE = 1, FieldDescriptorProto_Type_TYPE_FLOAT = 2, FieldDescriptorProto_Type_TYPE_INT64 = 3, @@ -185,140 +189,163 @@ enum FieldDescriptorProto_Type { FieldDescriptorProto_Type_TYPE_SINT32 = 17, FieldDescriptorProto_Type_TYPE_SINT64 = 18 }; -LIBPROTOBUF_EXPORT bool FieldDescriptorProto_Type_IsValid(int value); -const FieldDescriptorProto_Type FieldDescriptorProto_Type_Type_MIN = FieldDescriptorProto_Type_TYPE_DOUBLE; -const FieldDescriptorProto_Type FieldDescriptorProto_Type_Type_MAX = FieldDescriptorProto_Type_TYPE_SINT64; -const int FieldDescriptorProto_Type_Type_ARRAYSIZE = FieldDescriptorProto_Type_Type_MAX + 1; +PROTOBUF_EXPORT bool FieldDescriptorProto_Type_IsValid(int value); +constexpr FieldDescriptorProto_Type FieldDescriptorProto_Type_Type_MIN = FieldDescriptorProto_Type_TYPE_DOUBLE; +constexpr FieldDescriptorProto_Type FieldDescriptorProto_Type_Type_MAX = FieldDescriptorProto_Type_TYPE_SINT64; +constexpr int FieldDescriptorProto_Type_Type_ARRAYSIZE = FieldDescriptorProto_Type_Type_MAX + 1; -LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Type_descriptor(); -inline const ::std::string& FieldDescriptorProto_Type_Name(FieldDescriptorProto_Type value) { - return ::google::protobuf::internal::NameOfEnum( - FieldDescriptorProto_Type_descriptor(), value); +PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* FieldDescriptorProto_Type_descriptor(); +template +inline const std::string& FieldDescriptorProto_Type_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function FieldDescriptorProto_Type_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + FieldDescriptorProto_Type_descriptor(), enum_t_value); } inline bool FieldDescriptorProto_Type_Parse( - const ::std::string& name, FieldDescriptorProto_Type* value) { - return ::google::protobuf::internal::ParseNamedEnum( + const std::string& name, FieldDescriptorProto_Type* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( FieldDescriptorProto_Type_descriptor(), name, value); } -enum FieldDescriptorProto_Label { +enum FieldDescriptorProto_Label : int { FieldDescriptorProto_Label_LABEL_OPTIONAL = 1, FieldDescriptorProto_Label_LABEL_REQUIRED = 2, FieldDescriptorProto_Label_LABEL_REPEATED = 3 }; -LIBPROTOBUF_EXPORT bool FieldDescriptorProto_Label_IsValid(int value); -const FieldDescriptorProto_Label FieldDescriptorProto_Label_Label_MIN = FieldDescriptorProto_Label_LABEL_OPTIONAL; -const FieldDescriptorProto_Label FieldDescriptorProto_Label_Label_MAX = FieldDescriptorProto_Label_LABEL_REPEATED; -const int FieldDescriptorProto_Label_Label_ARRAYSIZE = FieldDescriptorProto_Label_Label_MAX + 1; +PROTOBUF_EXPORT bool FieldDescriptorProto_Label_IsValid(int value); +constexpr FieldDescriptorProto_Label FieldDescriptorProto_Label_Label_MIN = FieldDescriptorProto_Label_LABEL_OPTIONAL; +constexpr FieldDescriptorProto_Label FieldDescriptorProto_Label_Label_MAX = FieldDescriptorProto_Label_LABEL_REPEATED; +constexpr int FieldDescriptorProto_Label_Label_ARRAYSIZE = FieldDescriptorProto_Label_Label_MAX + 1; -LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Label_descriptor(); -inline const ::std::string& FieldDescriptorProto_Label_Name(FieldDescriptorProto_Label value) { - return ::google::protobuf::internal::NameOfEnum( - FieldDescriptorProto_Label_descriptor(), value); +PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* FieldDescriptorProto_Label_descriptor(); +template +inline const std::string& FieldDescriptorProto_Label_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function FieldDescriptorProto_Label_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + FieldDescriptorProto_Label_descriptor(), enum_t_value); } inline bool FieldDescriptorProto_Label_Parse( - const ::std::string& name, FieldDescriptorProto_Label* value) { - return ::google::protobuf::internal::ParseNamedEnum( + const std::string& name, FieldDescriptorProto_Label* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( FieldDescriptorProto_Label_descriptor(), name, value); } -enum FileOptions_OptimizeMode { +enum FileOptions_OptimizeMode : int { FileOptions_OptimizeMode_SPEED = 1, FileOptions_OptimizeMode_CODE_SIZE = 2, FileOptions_OptimizeMode_LITE_RUNTIME = 3 }; -LIBPROTOBUF_EXPORT bool FileOptions_OptimizeMode_IsValid(int value); -const FileOptions_OptimizeMode FileOptions_OptimizeMode_OptimizeMode_MIN = FileOptions_OptimizeMode_SPEED; -const FileOptions_OptimizeMode FileOptions_OptimizeMode_OptimizeMode_MAX = FileOptions_OptimizeMode_LITE_RUNTIME; -const int FileOptions_OptimizeMode_OptimizeMode_ARRAYSIZE = FileOptions_OptimizeMode_OptimizeMode_MAX + 1; +PROTOBUF_EXPORT bool FileOptions_OptimizeMode_IsValid(int value); +constexpr FileOptions_OptimizeMode FileOptions_OptimizeMode_OptimizeMode_MIN = FileOptions_OptimizeMode_SPEED; +constexpr FileOptions_OptimizeMode FileOptions_OptimizeMode_OptimizeMode_MAX = FileOptions_OptimizeMode_LITE_RUNTIME; +constexpr int FileOptions_OptimizeMode_OptimizeMode_ARRAYSIZE = FileOptions_OptimizeMode_OptimizeMode_MAX + 1; -LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FileOptions_OptimizeMode_descriptor(); -inline const ::std::string& FileOptions_OptimizeMode_Name(FileOptions_OptimizeMode value) { - return ::google::protobuf::internal::NameOfEnum( - FileOptions_OptimizeMode_descriptor(), value); +PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* FileOptions_OptimizeMode_descriptor(); +template +inline const std::string& FileOptions_OptimizeMode_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function FileOptions_OptimizeMode_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + FileOptions_OptimizeMode_descriptor(), enum_t_value); } inline bool FileOptions_OptimizeMode_Parse( - const ::std::string& name, FileOptions_OptimizeMode* value) { - return ::google::protobuf::internal::ParseNamedEnum( + const std::string& name, FileOptions_OptimizeMode* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( FileOptions_OptimizeMode_descriptor(), name, value); } -enum FieldOptions_CType { +enum FieldOptions_CType : int { FieldOptions_CType_STRING = 0, FieldOptions_CType_CORD = 1, FieldOptions_CType_STRING_PIECE = 2 }; -LIBPROTOBUF_EXPORT bool FieldOptions_CType_IsValid(int value); -const FieldOptions_CType FieldOptions_CType_CType_MIN = FieldOptions_CType_STRING; -const FieldOptions_CType FieldOptions_CType_CType_MAX = FieldOptions_CType_STRING_PIECE; -const int FieldOptions_CType_CType_ARRAYSIZE = FieldOptions_CType_CType_MAX + 1; +PROTOBUF_EXPORT bool FieldOptions_CType_IsValid(int value); +constexpr FieldOptions_CType FieldOptions_CType_CType_MIN = FieldOptions_CType_STRING; +constexpr FieldOptions_CType FieldOptions_CType_CType_MAX = FieldOptions_CType_STRING_PIECE; +constexpr int FieldOptions_CType_CType_ARRAYSIZE = FieldOptions_CType_CType_MAX + 1; -LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldOptions_CType_descriptor(); -inline const ::std::string& FieldOptions_CType_Name(FieldOptions_CType value) { - return ::google::protobuf::internal::NameOfEnum( - FieldOptions_CType_descriptor(), value); +PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* FieldOptions_CType_descriptor(); +template +inline const std::string& FieldOptions_CType_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function FieldOptions_CType_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + FieldOptions_CType_descriptor(), enum_t_value); } inline bool FieldOptions_CType_Parse( - const ::std::string& name, FieldOptions_CType* value) { - return ::google::protobuf::internal::ParseNamedEnum( + const std::string& name, FieldOptions_CType* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( FieldOptions_CType_descriptor(), name, value); } -enum FieldOptions_JSType { +enum FieldOptions_JSType : int { FieldOptions_JSType_JS_NORMAL = 0, FieldOptions_JSType_JS_STRING = 1, FieldOptions_JSType_JS_NUMBER = 2 }; -LIBPROTOBUF_EXPORT bool FieldOptions_JSType_IsValid(int value); -const FieldOptions_JSType FieldOptions_JSType_JSType_MIN = FieldOptions_JSType_JS_NORMAL; -const FieldOptions_JSType FieldOptions_JSType_JSType_MAX = FieldOptions_JSType_JS_NUMBER; -const int FieldOptions_JSType_JSType_ARRAYSIZE = FieldOptions_JSType_JSType_MAX + 1; +PROTOBUF_EXPORT bool FieldOptions_JSType_IsValid(int value); +constexpr FieldOptions_JSType FieldOptions_JSType_JSType_MIN = FieldOptions_JSType_JS_NORMAL; +constexpr FieldOptions_JSType FieldOptions_JSType_JSType_MAX = FieldOptions_JSType_JS_NUMBER; +constexpr int FieldOptions_JSType_JSType_ARRAYSIZE = FieldOptions_JSType_JSType_MAX + 1; -LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldOptions_JSType_descriptor(); -inline const ::std::string& FieldOptions_JSType_Name(FieldOptions_JSType value) { - return ::google::protobuf::internal::NameOfEnum( - FieldOptions_JSType_descriptor(), value); +PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* FieldOptions_JSType_descriptor(); +template +inline const std::string& FieldOptions_JSType_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function FieldOptions_JSType_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + FieldOptions_JSType_descriptor(), enum_t_value); } inline bool FieldOptions_JSType_Parse( - const ::std::string& name, FieldOptions_JSType* value) { - return ::google::protobuf::internal::ParseNamedEnum( + const std::string& name, FieldOptions_JSType* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( FieldOptions_JSType_descriptor(), name, value); } -enum MethodOptions_IdempotencyLevel { +enum MethodOptions_IdempotencyLevel : int { MethodOptions_IdempotencyLevel_IDEMPOTENCY_UNKNOWN = 0, MethodOptions_IdempotencyLevel_NO_SIDE_EFFECTS = 1, MethodOptions_IdempotencyLevel_IDEMPOTENT = 2 }; -LIBPROTOBUF_EXPORT bool MethodOptions_IdempotencyLevel_IsValid(int value); -const MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel_IdempotencyLevel_MIN = MethodOptions_IdempotencyLevel_IDEMPOTENCY_UNKNOWN; -const MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel_IdempotencyLevel_MAX = MethodOptions_IdempotencyLevel_IDEMPOTENT; -const int MethodOptions_IdempotencyLevel_IdempotencyLevel_ARRAYSIZE = MethodOptions_IdempotencyLevel_IdempotencyLevel_MAX + 1; +PROTOBUF_EXPORT bool MethodOptions_IdempotencyLevel_IsValid(int value); +constexpr MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel_IdempotencyLevel_MIN = MethodOptions_IdempotencyLevel_IDEMPOTENCY_UNKNOWN; +constexpr MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel_IdempotencyLevel_MAX = MethodOptions_IdempotencyLevel_IDEMPOTENT; +constexpr int MethodOptions_IdempotencyLevel_IdempotencyLevel_ARRAYSIZE = MethodOptions_IdempotencyLevel_IdempotencyLevel_MAX + 1; -LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* MethodOptions_IdempotencyLevel_descriptor(); -inline const ::std::string& MethodOptions_IdempotencyLevel_Name(MethodOptions_IdempotencyLevel value) { - return ::google::protobuf::internal::NameOfEnum( - MethodOptions_IdempotencyLevel_descriptor(), value); +PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* MethodOptions_IdempotencyLevel_descriptor(); +template +inline const std::string& MethodOptions_IdempotencyLevel_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function MethodOptions_IdempotencyLevel_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + MethodOptions_IdempotencyLevel_descriptor(), enum_t_value); } inline bool MethodOptions_IdempotencyLevel_Parse( - const ::std::string& name, MethodOptions_IdempotencyLevel* value) { - return ::google::protobuf::internal::ParseNamedEnum( + const std::string& name, MethodOptions_IdempotencyLevel* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( MethodOptions_IdempotencyLevel_descriptor(), name, value); } // =================================================================== -class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileDescriptorSet) */ { +class PROTOBUF_EXPORT FileDescriptorSet : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileDescriptorSet) */ { public: FileDescriptorSet(); virtual ~FileDescriptorSet(); FileDescriptorSet(const FileDescriptorSet& from); - - inline FileDescriptorSet& operator=(const FileDescriptorSet& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 FileDescriptorSet(FileDescriptorSet&& from) noexcept : FileDescriptorSet() { *this = ::std::move(from); } + inline FileDescriptorSet& operator=(const FileDescriptorSet& from) { + CopyFrom(from); + return *this; + } inline FileDescriptorSet& operator=(FileDescriptorSet&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -327,21 +354,29 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const FileDescriptorSet& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -361,40 +396,48 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message // implements Message ---------------------------------------------- inline FileDescriptorSet* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - FileDescriptorSet* New(::google::protobuf::Arena* arena) const final { + FileDescriptorSet* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const FileDescriptorSet& from); void MergeFrom(const FileDescriptorSet& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(FileDescriptorSet* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.FileDescriptorSet"; + } protected: - explicit FileDescriptorSet(::google::protobuf::Arena* arena); + explicit FileDescriptorSet(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -402,7 +445,14 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -412,45 +462,45 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message int file_size() const; void clear_file(); static const int kFileFieldNumber = 1; - ::google::protobuf::FileDescriptorProto* mutable_file(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >* + PROTOBUF_NAMESPACE_ID::FileDescriptorProto* mutable_file(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FileDescriptorProto >* mutable_file(); - const ::google::protobuf::FileDescriptorProto& file(int index) const; - ::google::protobuf::FileDescriptorProto* add_file(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >& + const PROTOBUF_NAMESPACE_ID::FileDescriptorProto& file(int index) const; + PROTOBUF_NAMESPACE_ID::FileDescriptorProto* add_file(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FileDescriptorProto >& file() const; // @@protoc_insertion_point(class_scope:google.protobuf.FileDescriptorSet) private: + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto > file_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FileDescriptorProto > file_; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileDescriptorProto) */ { +class PROTOBUF_EXPORT FileDescriptorProto : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileDescriptorProto) */ { public: FileDescriptorProto(); virtual ~FileDescriptorProto(); FileDescriptorProto(const FileDescriptorProto& from); - - inline FileDescriptorProto& operator=(const FileDescriptorProto& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 FileDescriptorProto(FileDescriptorProto&& from) noexcept : FileDescriptorProto() { *this = ::std::move(from); } + inline FileDescriptorProto& operator=(const FileDescriptorProto& from) { + CopyFrom(from); + return *this; + } inline FileDescriptorProto& operator=(FileDescriptorProto&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -459,21 +509,29 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const FileDescriptorProto& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -493,40 +551,48 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag // implements Message ---------------------------------------------- inline FileDescriptorProto* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - FileDescriptorProto* New(::google::protobuf::Arena* arena) const final { + FileDescriptorProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const FileDescriptorProto& from); void MergeFrom(const FileDescriptorProto& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(FileDescriptorProto* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.FileDescriptorProto"; + } protected: - explicit FileDescriptorProto(::google::protobuf::Arena* arena); + explicit FileDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -534,7 +600,14 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -544,250 +617,224 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag int dependency_size() const; void clear_dependency(); static const int kDependencyFieldNumber = 3; - const ::std::string& dependency(int index) const; - ::std::string* mutable_dependency(int index); - void set_dependency(int index, const ::std::string& value); - #if LANG_CXX11 - void set_dependency(int index, ::std::string&& value); - #endif + const std::string& dependency(int index) const; + std::string* mutable_dependency(int index); + void set_dependency(int index, const std::string& value); + void set_dependency(int index, std::string&& value); void set_dependency(int index, const char* value); void set_dependency(int index, const char* value, size_t size); - ::std::string* add_dependency(); - void add_dependency(const ::std::string& value); - #if LANG_CXX11 - void add_dependency(::std::string&& value); - #endif + std::string* add_dependency(); + void add_dependency(const std::string& value); + void add_dependency(std::string&& value); void add_dependency(const char* value); void add_dependency(const char* value, size_t size); - const ::google::protobuf::RepeatedPtrField< ::std::string>& dependency() const; - ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_dependency(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& dependency() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* mutable_dependency(); // repeated .google.protobuf.DescriptorProto message_type = 4; int message_type_size() const; void clear_message_type(); static const int kMessageTypeFieldNumber = 4; - ::google::protobuf::DescriptorProto* mutable_message_type(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >* + PROTOBUF_NAMESPACE_ID::DescriptorProto* mutable_message_type(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto >* mutable_message_type(); - const ::google::protobuf::DescriptorProto& message_type(int index) const; - ::google::protobuf::DescriptorProto* add_message_type(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >& + const PROTOBUF_NAMESPACE_ID::DescriptorProto& message_type(int index) const; + PROTOBUF_NAMESPACE_ID::DescriptorProto* add_message_type(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto >& message_type() const; // repeated .google.protobuf.EnumDescriptorProto enum_type = 5; int enum_type_size() const; void clear_enum_type(); static const int kEnumTypeFieldNumber = 5; - ::google::protobuf::EnumDescriptorProto* mutable_enum_type(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >* + PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* mutable_enum_type(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto >* mutable_enum_type(); - const ::google::protobuf::EnumDescriptorProto& enum_type(int index) const; - ::google::protobuf::EnumDescriptorProto* add_enum_type(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >& + const PROTOBUF_NAMESPACE_ID::EnumDescriptorProto& enum_type(int index) const; + PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* add_enum_type(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto >& enum_type() const; // repeated .google.protobuf.ServiceDescriptorProto service = 6; int service_size() const; void clear_service(); static const int kServiceFieldNumber = 6; - ::google::protobuf::ServiceDescriptorProto* mutable_service(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto >* + PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto* mutable_service(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto >* mutable_service(); - const ::google::protobuf::ServiceDescriptorProto& service(int index) const; - ::google::protobuf::ServiceDescriptorProto* add_service(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto >& + const PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto& service(int index) const; + PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto* add_service(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto >& service() const; // repeated .google.protobuf.FieldDescriptorProto extension = 7; int extension_size() const; void clear_extension(); static const int kExtensionFieldNumber = 7; - ::google::protobuf::FieldDescriptorProto* mutable_extension(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >* + PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* mutable_extension(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >* mutable_extension(); - const ::google::protobuf::FieldDescriptorProto& extension(int index) const; - ::google::protobuf::FieldDescriptorProto* add_extension(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >& + const PROTOBUF_NAMESPACE_ID::FieldDescriptorProto& extension(int index) const; + PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* add_extension(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >& extension() const; // repeated int32 public_dependency = 10; int public_dependency_size() const; void clear_public_dependency(); static const int kPublicDependencyFieldNumber = 10; - ::google::protobuf::int32 public_dependency(int index) const; - void set_public_dependency(int index, ::google::protobuf::int32 value); - void add_public_dependency(::google::protobuf::int32 value); - const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& + ::PROTOBUF_NAMESPACE_ID::int32 public_dependency(int index) const; + void set_public_dependency(int index, ::PROTOBUF_NAMESPACE_ID::int32 value); + void add_public_dependency(::PROTOBUF_NAMESPACE_ID::int32 value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >& public_dependency() const; - ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* + ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >* mutable_public_dependency(); // repeated int32 weak_dependency = 11; int weak_dependency_size() const; void clear_weak_dependency(); static const int kWeakDependencyFieldNumber = 11; - ::google::protobuf::int32 weak_dependency(int index) const; - void set_weak_dependency(int index, ::google::protobuf::int32 value); - void add_weak_dependency(::google::protobuf::int32 value); - const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& + ::PROTOBUF_NAMESPACE_ID::int32 weak_dependency(int index) const; + void set_weak_dependency(int index, ::PROTOBUF_NAMESPACE_ID::int32 value); + void add_weak_dependency(::PROTOBUF_NAMESPACE_ID::int32 value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >& weak_dependency() const; - ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* + ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >* mutable_weak_dependency(); // optional string name = 1; bool has_name() const; void clear_name(); static const int kNameFieldNumber = 1; - const ::std::string& name() const; - void set_name(const ::std::string& value); - #if LANG_CXX11 - void set_name(::std::string&& value); - #endif + const std::string& name() const; + void set_name(const std::string& value); + void set_name(std::string&& value); void set_name(const char* value); void set_name(const char* value, size_t size); - ::std::string* mutable_name(); - ::std::string* release_name(); - void set_allocated_name(::std::string* name); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_name(); + std::string* release_name(); + void set_allocated_name(std::string* name); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_name(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_name(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_name( - ::std::string* name); + std::string* name); // optional string package = 2; bool has_package() const; void clear_package(); static const int kPackageFieldNumber = 2; - const ::std::string& package() const; - void set_package(const ::std::string& value); - #if LANG_CXX11 - void set_package(::std::string&& value); - #endif + const std::string& package() const; + void set_package(const std::string& value); + void set_package(std::string&& value); void set_package(const char* value); void set_package(const char* value, size_t size); - ::std::string* mutable_package(); - ::std::string* release_package(); - void set_allocated_package(::std::string* package); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_package(); + std::string* release_package(); + void set_allocated_package(std::string* package); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_package(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_package(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_package( - ::std::string* package); + std::string* package); // optional string syntax = 12; bool has_syntax() const; void clear_syntax(); static const int kSyntaxFieldNumber = 12; - const ::std::string& syntax() const; - void set_syntax(const ::std::string& value); - #if LANG_CXX11 - void set_syntax(::std::string&& value); - #endif + const std::string& syntax() const; + void set_syntax(const std::string& value); + void set_syntax(std::string&& value); void set_syntax(const char* value); void set_syntax(const char* value, size_t size); - ::std::string* mutable_syntax(); - ::std::string* release_syntax(); - void set_allocated_syntax(::std::string* syntax); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_syntax(); + std::string* release_syntax(); + void set_allocated_syntax(std::string* syntax); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_syntax(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_syntax(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_syntax( - ::std::string* syntax); + std::string* syntax); // optional .google.protobuf.FileOptions options = 8; bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 8; - private: - const ::google::protobuf::FileOptions& _internal_options() const; - public: - const ::google::protobuf::FileOptions& options() const; - ::google::protobuf::FileOptions* release_options(); - ::google::protobuf::FileOptions* mutable_options(); - void set_allocated_options(::google::protobuf::FileOptions* options); + const PROTOBUF_NAMESPACE_ID::FileOptions& options() const; + PROTOBUF_NAMESPACE_ID::FileOptions* release_options(); + PROTOBUF_NAMESPACE_ID::FileOptions* mutable_options(); + void set_allocated_options(PROTOBUF_NAMESPACE_ID::FileOptions* options); void unsafe_arena_set_allocated_options( - ::google::protobuf::FileOptions* options); - ::google::protobuf::FileOptions* unsafe_arena_release_options(); + PROTOBUF_NAMESPACE_ID::FileOptions* options); + PROTOBUF_NAMESPACE_ID::FileOptions* unsafe_arena_release_options(); // optional .google.protobuf.SourceCodeInfo source_code_info = 9; bool has_source_code_info() const; void clear_source_code_info(); static const int kSourceCodeInfoFieldNumber = 9; - private: - const ::google::protobuf::SourceCodeInfo& _internal_source_code_info() const; - public: - const ::google::protobuf::SourceCodeInfo& source_code_info() const; - ::google::protobuf::SourceCodeInfo* release_source_code_info(); - ::google::protobuf::SourceCodeInfo* mutable_source_code_info(); - void set_allocated_source_code_info(::google::protobuf::SourceCodeInfo* source_code_info); + const PROTOBUF_NAMESPACE_ID::SourceCodeInfo& source_code_info() const; + PROTOBUF_NAMESPACE_ID::SourceCodeInfo* release_source_code_info(); + PROTOBUF_NAMESPACE_ID::SourceCodeInfo* mutable_source_code_info(); + void set_allocated_source_code_info(PROTOBUF_NAMESPACE_ID::SourceCodeInfo* source_code_info); void unsafe_arena_set_allocated_source_code_info( - ::google::protobuf::SourceCodeInfo* source_code_info); - ::google::protobuf::SourceCodeInfo* unsafe_arena_release_source_code_info(); + PROTOBUF_NAMESPACE_ID::SourceCodeInfo* source_code_info); + PROTOBUF_NAMESPACE_ID::SourceCodeInfo* unsafe_arena_release_source_code_info(); // @@protoc_insertion_point(class_scope:google.protobuf.FileDescriptorProto) private: - void set_has_name(); - void clear_has_name(); - void set_has_package(); - void clear_has_package(); - void set_has_options(); - void clear_has_options(); - void set_has_source_code_info(); - void clear_has_source_code_info(); - void set_has_syntax(); - void clear_has_syntax(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::std::string> dependency_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto > message_type_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto > enum_type_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto > service_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto > extension_; - ::google::protobuf::RepeatedField< ::google::protobuf::int32 > public_dependency_; - ::google::protobuf::RepeatedField< ::google::protobuf::int32 > weak_dependency_; - ::google::protobuf::internal::ArenaStringPtr name_; - ::google::protobuf::internal::ArenaStringPtr package_; - ::google::protobuf::internal::ArenaStringPtr syntax_; - ::google::protobuf::FileOptions* options_; - ::google::protobuf::SourceCodeInfo* source_code_info_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField dependency_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto > message_type_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto > enum_type_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto > service_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto > extension_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 > public_dependency_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 > weak_dependency_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr package_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr syntax_; + PROTOBUF_NAMESPACE_ID::FileOptions* options_; + PROTOBUF_NAMESPACE_ID::SourceCodeInfo* source_code_info_; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto.ExtensionRange) */ { +class PROTOBUF_EXPORT DescriptorProto_ExtensionRange : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto.ExtensionRange) */ { public: DescriptorProto_ExtensionRange(); virtual ~DescriptorProto_ExtensionRange(); DescriptorProto_ExtensionRange(const DescriptorProto_ExtensionRange& from); - - inline DescriptorProto_ExtensionRange& operator=(const DescriptorProto_ExtensionRange& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 DescriptorProto_ExtensionRange(DescriptorProto_ExtensionRange&& from) noexcept : DescriptorProto_ExtensionRange() { *this = ::std::move(from); } + inline DescriptorProto_ExtensionRange& operator=(const DescriptorProto_ExtensionRange& from) { + CopyFrom(from); + return *this; + } inline DescriptorProto_ExtensionRange& operator=(DescriptorProto_ExtensionRange&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -796,21 +843,29 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const DescriptorProto_ExtensionRange& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -830,40 +885,48 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto // implements Message ---------------------------------------------- inline DescriptorProto_ExtensionRange* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - DescriptorProto_ExtensionRange* New(::google::protobuf::Arena* arena) const final { + DescriptorProto_ExtensionRange* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const DescriptorProto_ExtensionRange& from); void MergeFrom(const DescriptorProto_ExtensionRange& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(DescriptorProto_ExtensionRange* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.DescriptorProto.ExtensionRange"; + } protected: - explicit DescriptorProto_ExtensionRange(::google::protobuf::Arena* arena); + explicit DescriptorProto_ExtensionRange(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -871,7 +934,14 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -881,70 +951,61 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 3; - private: - const ::google::protobuf::ExtensionRangeOptions& _internal_options() const; - public: - const ::google::protobuf::ExtensionRangeOptions& options() const; - ::google::protobuf::ExtensionRangeOptions* release_options(); - ::google::protobuf::ExtensionRangeOptions* mutable_options(); - void set_allocated_options(::google::protobuf::ExtensionRangeOptions* options); + const PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions& options() const; + PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* release_options(); + PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* mutable_options(); + void set_allocated_options(PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* options); void unsafe_arena_set_allocated_options( - ::google::protobuf::ExtensionRangeOptions* options); - ::google::protobuf::ExtensionRangeOptions* unsafe_arena_release_options(); + PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* options); + PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* unsafe_arena_release_options(); // optional int32 start = 1; bool has_start() const; void clear_start(); static const int kStartFieldNumber = 1; - ::google::protobuf::int32 start() const; - void set_start(::google::protobuf::int32 value); + ::PROTOBUF_NAMESPACE_ID::int32 start() const; + void set_start(::PROTOBUF_NAMESPACE_ID::int32 value); // optional int32 end = 2; bool has_end() const; void clear_end(); static const int kEndFieldNumber = 2; - ::google::protobuf::int32 end() const; - void set_end(::google::protobuf::int32 value); + ::PROTOBUF_NAMESPACE_ID::int32 end() const; + void set_end(::PROTOBUF_NAMESPACE_ID::int32 value); // @@protoc_insertion_point(class_scope:google.protobuf.DescriptorProto.ExtensionRange) private: - void set_has_start(); - void clear_has_start(); - void set_has_end(); - void clear_has_end(); - void set_has_options(); - void clear_has_options(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::ExtensionRangeOptions* options_; - ::google::protobuf::int32 start_; - ::google::protobuf::int32 end_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* options_; + ::PROTOBUF_NAMESPACE_ID::int32 start_; + ::PROTOBUF_NAMESPACE_ID::int32 end_; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto.ReservedRange) */ { +class PROTOBUF_EXPORT DescriptorProto_ReservedRange : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto.ReservedRange) */ { public: DescriptorProto_ReservedRange(); virtual ~DescriptorProto_ReservedRange(); DescriptorProto_ReservedRange(const DescriptorProto_ReservedRange& from); - - inline DescriptorProto_ReservedRange& operator=(const DescriptorProto_ReservedRange& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 DescriptorProto_ReservedRange(DescriptorProto_ReservedRange&& from) noexcept : DescriptorProto_ReservedRange() { *this = ::std::move(from); } + inline DescriptorProto_ReservedRange& operator=(const DescriptorProto_ReservedRange& from) { + CopyFrom(from); + return *this; + } inline DescriptorProto_ReservedRange& operator=(DescriptorProto_ReservedRange&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -953,21 +1014,29 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const DescriptorProto_ReservedRange& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -987,40 +1056,48 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob // implements Message ---------------------------------------------- inline DescriptorProto_ReservedRange* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - DescriptorProto_ReservedRange* New(::google::protobuf::Arena* arena) const final { + DescriptorProto_ReservedRange* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const DescriptorProto_ReservedRange& from); void MergeFrom(const DescriptorProto_ReservedRange& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(DescriptorProto_ReservedRange* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.DescriptorProto.ReservedRange"; + } protected: - explicit DescriptorProto_ReservedRange(::google::protobuf::Arena* arena); + explicit DescriptorProto_ReservedRange(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -1028,7 +1105,14 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -1038,52 +1122,48 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob bool has_start() const; void clear_start(); static const int kStartFieldNumber = 1; - ::google::protobuf::int32 start() const; - void set_start(::google::protobuf::int32 value); + ::PROTOBUF_NAMESPACE_ID::int32 start() const; + void set_start(::PROTOBUF_NAMESPACE_ID::int32 value); // optional int32 end = 2; bool has_end() const; void clear_end(); static const int kEndFieldNumber = 2; - ::google::protobuf::int32 end() const; - void set_end(::google::protobuf::int32 value); + ::PROTOBUF_NAMESPACE_ID::int32 end() const; + void set_end(::PROTOBUF_NAMESPACE_ID::int32 value); // @@protoc_insertion_point(class_scope:google.protobuf.DescriptorProto.ReservedRange) private: - void set_has_start(); - void clear_has_start(); - void set_has_end(); - void clear_has_end(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::int32 start_; - ::google::protobuf::int32 end_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::int32 start_; + ::PROTOBUF_NAMESPACE_ID::int32 end_; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto) */ { +class PROTOBUF_EXPORT DescriptorProto : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto) */ { public: DescriptorProto(); virtual ~DescriptorProto(); DescriptorProto(const DescriptorProto& from); - - inline DescriptorProto& operator=(const DescriptorProto& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 DescriptorProto(DescriptorProto&& from) noexcept : DescriptorProto() { *this = ::std::move(from); } + inline DescriptorProto& operator=(const DescriptorProto& from) { + CopyFrom(from); + return *this; + } inline DescriptorProto& operator=(DescriptorProto&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -1092,21 +1172,29 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const DescriptorProto& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -1126,40 +1214,48 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* // implements Message ---------------------------------------------- inline DescriptorProto* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - DescriptorProto* New(::google::protobuf::Arena* arena) const final { + DescriptorProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const DescriptorProto& from); void MergeFrom(const DescriptorProto& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(DescriptorProto* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.DescriptorProto"; + } protected: - explicit DescriptorProto(::google::protobuf::Arena* arena); + explicit DescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -1167,7 +1263,14 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -1180,191 +1283,178 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* int field_size() const; void clear_field(); static const int kFieldFieldNumber = 2; - ::google::protobuf::FieldDescriptorProto* mutable_field(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >* + PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* mutable_field(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >* mutable_field(); - const ::google::protobuf::FieldDescriptorProto& field(int index) const; - ::google::protobuf::FieldDescriptorProto* add_field(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >& + const PROTOBUF_NAMESPACE_ID::FieldDescriptorProto& field(int index) const; + PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* add_field(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >& field() const; // repeated .google.protobuf.DescriptorProto nested_type = 3; int nested_type_size() const; void clear_nested_type(); static const int kNestedTypeFieldNumber = 3; - ::google::protobuf::DescriptorProto* mutable_nested_type(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >* + PROTOBUF_NAMESPACE_ID::DescriptorProto* mutable_nested_type(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto >* mutable_nested_type(); - const ::google::protobuf::DescriptorProto& nested_type(int index) const; - ::google::protobuf::DescriptorProto* add_nested_type(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >& + const PROTOBUF_NAMESPACE_ID::DescriptorProto& nested_type(int index) const; + PROTOBUF_NAMESPACE_ID::DescriptorProto* add_nested_type(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto >& nested_type() const; // repeated .google.protobuf.EnumDescriptorProto enum_type = 4; int enum_type_size() const; void clear_enum_type(); static const int kEnumTypeFieldNumber = 4; - ::google::protobuf::EnumDescriptorProto* mutable_enum_type(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >* + PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* mutable_enum_type(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto >* mutable_enum_type(); - const ::google::protobuf::EnumDescriptorProto& enum_type(int index) const; - ::google::protobuf::EnumDescriptorProto* add_enum_type(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >& + const PROTOBUF_NAMESPACE_ID::EnumDescriptorProto& enum_type(int index) const; + PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* add_enum_type(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto >& enum_type() const; // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; int extension_range_size() const; void clear_extension_range(); static const int kExtensionRangeFieldNumber = 5; - ::google::protobuf::DescriptorProto_ExtensionRange* mutable_extension_range(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange >* + PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange* mutable_extension_range(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange >* mutable_extension_range(); - const ::google::protobuf::DescriptorProto_ExtensionRange& extension_range(int index) const; - ::google::protobuf::DescriptorProto_ExtensionRange* add_extension_range(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange >& + const PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange& extension_range(int index) const; + PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange* add_extension_range(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange >& extension_range() const; // repeated .google.protobuf.FieldDescriptorProto extension = 6; int extension_size() const; void clear_extension(); static const int kExtensionFieldNumber = 6; - ::google::protobuf::FieldDescriptorProto* mutable_extension(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >* + PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* mutable_extension(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >* mutable_extension(); - const ::google::protobuf::FieldDescriptorProto& extension(int index) const; - ::google::protobuf::FieldDescriptorProto* add_extension(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >& + const PROTOBUF_NAMESPACE_ID::FieldDescriptorProto& extension(int index) const; + PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* add_extension(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >& extension() const; // repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8; int oneof_decl_size() const; void clear_oneof_decl(); static const int kOneofDeclFieldNumber = 8; - ::google::protobuf::OneofDescriptorProto* mutable_oneof_decl(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::OneofDescriptorProto >* + PROTOBUF_NAMESPACE_ID::OneofDescriptorProto* mutable_oneof_decl(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::OneofDescriptorProto >* mutable_oneof_decl(); - const ::google::protobuf::OneofDescriptorProto& oneof_decl(int index) const; - ::google::protobuf::OneofDescriptorProto* add_oneof_decl(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::OneofDescriptorProto >& + const PROTOBUF_NAMESPACE_ID::OneofDescriptorProto& oneof_decl(int index) const; + PROTOBUF_NAMESPACE_ID::OneofDescriptorProto* add_oneof_decl(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::OneofDescriptorProto >& oneof_decl() const; // repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9; int reserved_range_size() const; void clear_reserved_range(); static const int kReservedRangeFieldNumber = 9; - ::google::protobuf::DescriptorProto_ReservedRange* mutable_reserved_range(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ReservedRange >* + PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange* mutable_reserved_range(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange >* mutable_reserved_range(); - const ::google::protobuf::DescriptorProto_ReservedRange& reserved_range(int index) const; - ::google::protobuf::DescriptorProto_ReservedRange* add_reserved_range(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ReservedRange >& + const PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange& reserved_range(int index) const; + PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange* add_reserved_range(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange >& reserved_range() const; // repeated string reserved_name = 10; int reserved_name_size() const; void clear_reserved_name(); static const int kReservedNameFieldNumber = 10; - const ::std::string& reserved_name(int index) const; - ::std::string* mutable_reserved_name(int index); - void set_reserved_name(int index, const ::std::string& value); - #if LANG_CXX11 - void set_reserved_name(int index, ::std::string&& value); - #endif + const std::string& reserved_name(int index) const; + std::string* mutable_reserved_name(int index); + void set_reserved_name(int index, const std::string& value); + void set_reserved_name(int index, std::string&& value); void set_reserved_name(int index, const char* value); void set_reserved_name(int index, const char* value, size_t size); - ::std::string* add_reserved_name(); - void add_reserved_name(const ::std::string& value); - #if LANG_CXX11 - void add_reserved_name(::std::string&& value); - #endif + std::string* add_reserved_name(); + void add_reserved_name(const std::string& value); + void add_reserved_name(std::string&& value); void add_reserved_name(const char* value); void add_reserved_name(const char* value, size_t size); - const ::google::protobuf::RepeatedPtrField< ::std::string>& reserved_name() const; - ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_reserved_name(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& reserved_name() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* mutable_reserved_name(); // optional string name = 1; bool has_name() const; void clear_name(); static const int kNameFieldNumber = 1; - const ::std::string& name() const; - void set_name(const ::std::string& value); - #if LANG_CXX11 - void set_name(::std::string&& value); - #endif + const std::string& name() const; + void set_name(const std::string& value); + void set_name(std::string&& value); void set_name(const char* value); void set_name(const char* value, size_t size); - ::std::string* mutable_name(); - ::std::string* release_name(); - void set_allocated_name(::std::string* name); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_name(); + std::string* release_name(); + void set_allocated_name(std::string* name); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_name(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_name(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_name( - ::std::string* name); + std::string* name); // optional .google.protobuf.MessageOptions options = 7; bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 7; - private: - const ::google::protobuf::MessageOptions& _internal_options() const; - public: - const ::google::protobuf::MessageOptions& options() const; - ::google::protobuf::MessageOptions* release_options(); - ::google::protobuf::MessageOptions* mutable_options(); - void set_allocated_options(::google::protobuf::MessageOptions* options); + const PROTOBUF_NAMESPACE_ID::MessageOptions& options() const; + PROTOBUF_NAMESPACE_ID::MessageOptions* release_options(); + PROTOBUF_NAMESPACE_ID::MessageOptions* mutable_options(); + void set_allocated_options(PROTOBUF_NAMESPACE_ID::MessageOptions* options); void unsafe_arena_set_allocated_options( - ::google::protobuf::MessageOptions* options); - ::google::protobuf::MessageOptions* unsafe_arena_release_options(); + PROTOBUF_NAMESPACE_ID::MessageOptions* options); + PROTOBUF_NAMESPACE_ID::MessageOptions* unsafe_arena_release_options(); // @@protoc_insertion_point(class_scope:google.protobuf.DescriptorProto) private: - void set_has_name(); - void clear_has_name(); - void set_has_options(); - void clear_has_options(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto > field_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto > nested_type_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto > enum_type_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange > extension_range_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto > extension_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::OneofDescriptorProto > oneof_decl_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ReservedRange > reserved_range_; - ::google::protobuf::RepeatedPtrField< ::std::string> reserved_name_; - ::google::protobuf::internal::ArenaStringPtr name_; - ::google::protobuf::MessageOptions* options_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto > field_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto > nested_type_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto > enum_type_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange > extension_range_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto > extension_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::OneofDescriptorProto > oneof_decl_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange > reserved_range_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField reserved_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + PROTOBUF_NAMESPACE_ID::MessageOptions* options_; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ExtensionRangeOptions) */ { +class PROTOBUF_EXPORT ExtensionRangeOptions : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ExtensionRangeOptions) */ { public: ExtensionRangeOptions(); virtual ~ExtensionRangeOptions(); ExtensionRangeOptions(const ExtensionRangeOptions& from); - - inline ExtensionRangeOptions& operator=(const ExtensionRangeOptions& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 ExtensionRangeOptions(ExtensionRangeOptions&& from) noexcept : ExtensionRangeOptions() { *this = ::std::move(from); } + inline ExtensionRangeOptions& operator=(const ExtensionRangeOptions& from) { + CopyFrom(from); + return *this; + } inline ExtensionRangeOptions& operator=(ExtensionRangeOptions&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -1373,21 +1463,29 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const ExtensionRangeOptions& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -1407,40 +1505,48 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess // implements Message ---------------------------------------------- inline ExtensionRangeOptions* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - ExtensionRangeOptions* New(::google::protobuf::Arena* arena) const final { + ExtensionRangeOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const ExtensionRangeOptions& from); void MergeFrom(const ExtensionRangeOptions& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(ExtensionRangeOptions* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.ExtensionRangeOptions"; + } protected: - explicit ExtensionRangeOptions(::google::protobuf::Arena* arena); + explicit ExtensionRangeOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -1448,7 +1554,14 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -1458,48 +1571,48 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess int uninterpreted_option_size() const; void clear_uninterpreted_option(); static const int kUninterpretedOptionFieldNumber = 999; - ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* + PROTOBUF_NAMESPACE_ID::UninterpretedOption* mutable_uninterpreted_option(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* mutable_uninterpreted_option(); - const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const; - ::google::protobuf::UninterpretedOption* add_uninterpreted_option(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& + const PROTOBUF_NAMESPACE_ID::UninterpretedOption& uninterpreted_option(int index) const; + PROTOBUF_NAMESPACE_ID::UninterpretedOption* add_uninterpreted_option(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& uninterpreted_option() const; GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(ExtensionRangeOptions) // @@protoc_insertion_point(class_scope:google.protobuf.ExtensionRangeOptions) private: + class HasBitSetters; - ::google::protobuf::internal::ExtensionSet _extensions_; + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption > uninterpreted_option_; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldDescriptorProto) */ { +class PROTOBUF_EXPORT FieldDescriptorProto : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldDescriptorProto) */ { public: FieldDescriptorProto(); virtual ~FieldDescriptorProto(); FieldDescriptorProto(const FieldDescriptorProto& from); - - inline FieldDescriptorProto& operator=(const FieldDescriptorProto& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 FieldDescriptorProto(FieldDescriptorProto&& from) noexcept : FieldDescriptorProto() { *this = ::std::move(from); } + inline FieldDescriptorProto& operator=(const FieldDescriptorProto& from) { + CopyFrom(from); + return *this; + } inline FieldDescriptorProto& operator=(FieldDescriptorProto&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -1508,21 +1621,29 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const FieldDescriptorProto& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -1542,40 +1663,48 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa // implements Message ---------------------------------------------- inline FieldDescriptorProto* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - FieldDescriptorProto* New(::google::protobuf::Arena* arena) const final { + FieldDescriptorProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const FieldDescriptorProto& from); void MergeFrom(const FieldDescriptorProto& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(FieldDescriptorProto* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.FieldDescriptorProto"; + } protected: - explicit FieldDescriptorProto(::google::protobuf::Arena* arena); + explicit FieldDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -1583,92 +1712,107 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- typedef FieldDescriptorProto_Type Type; - static const Type TYPE_DOUBLE = + static constexpr Type TYPE_DOUBLE = FieldDescriptorProto_Type_TYPE_DOUBLE; - static const Type TYPE_FLOAT = + static constexpr Type TYPE_FLOAT = FieldDescriptorProto_Type_TYPE_FLOAT; - static const Type TYPE_INT64 = + static constexpr Type TYPE_INT64 = FieldDescriptorProto_Type_TYPE_INT64; - static const Type TYPE_UINT64 = + static constexpr Type TYPE_UINT64 = FieldDescriptorProto_Type_TYPE_UINT64; - static const Type TYPE_INT32 = + static constexpr Type TYPE_INT32 = FieldDescriptorProto_Type_TYPE_INT32; - static const Type TYPE_FIXED64 = + static constexpr Type TYPE_FIXED64 = FieldDescriptorProto_Type_TYPE_FIXED64; - static const Type TYPE_FIXED32 = + static constexpr Type TYPE_FIXED32 = FieldDescriptorProto_Type_TYPE_FIXED32; - static const Type TYPE_BOOL = + static constexpr Type TYPE_BOOL = FieldDescriptorProto_Type_TYPE_BOOL; - static const Type TYPE_STRING = + static constexpr Type TYPE_STRING = FieldDescriptorProto_Type_TYPE_STRING; - static const Type TYPE_GROUP = + static constexpr Type TYPE_GROUP = FieldDescriptorProto_Type_TYPE_GROUP; - static const Type TYPE_MESSAGE = + static constexpr Type TYPE_MESSAGE = FieldDescriptorProto_Type_TYPE_MESSAGE; - static const Type TYPE_BYTES = + static constexpr Type TYPE_BYTES = FieldDescriptorProto_Type_TYPE_BYTES; - static const Type TYPE_UINT32 = + static constexpr Type TYPE_UINT32 = FieldDescriptorProto_Type_TYPE_UINT32; - static const Type TYPE_ENUM = + static constexpr Type TYPE_ENUM = FieldDescriptorProto_Type_TYPE_ENUM; - static const Type TYPE_SFIXED32 = + static constexpr Type TYPE_SFIXED32 = FieldDescriptorProto_Type_TYPE_SFIXED32; - static const Type TYPE_SFIXED64 = + static constexpr Type TYPE_SFIXED64 = FieldDescriptorProto_Type_TYPE_SFIXED64; - static const Type TYPE_SINT32 = + static constexpr Type TYPE_SINT32 = FieldDescriptorProto_Type_TYPE_SINT32; - static const Type TYPE_SINT64 = + static constexpr Type TYPE_SINT64 = FieldDescriptorProto_Type_TYPE_SINT64; static inline bool Type_IsValid(int value) { return FieldDescriptorProto_Type_IsValid(value); } - static const Type Type_MIN = + static constexpr Type Type_MIN = FieldDescriptorProto_Type_Type_MIN; - static const Type Type_MAX = + static constexpr Type Type_MAX = FieldDescriptorProto_Type_Type_MAX; - static const int Type_ARRAYSIZE = + static constexpr int Type_ARRAYSIZE = FieldDescriptorProto_Type_Type_ARRAYSIZE; - static inline const ::google::protobuf::EnumDescriptor* + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Type_descriptor() { return FieldDescriptorProto_Type_descriptor(); } - static inline const ::std::string& Type_Name(Type value) { - return FieldDescriptorProto_Type_Name(value); + template + static inline const std::string& Type_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function Type_Name."); + return FieldDescriptorProto_Type_Name(enum_t_value); } - static inline bool Type_Parse(const ::std::string& name, + static inline bool Type_Parse(const std::string& name, Type* value) { return FieldDescriptorProto_Type_Parse(name, value); } typedef FieldDescriptorProto_Label Label; - static const Label LABEL_OPTIONAL = + static constexpr Label LABEL_OPTIONAL = FieldDescriptorProto_Label_LABEL_OPTIONAL; - static const Label LABEL_REQUIRED = + static constexpr Label LABEL_REQUIRED = FieldDescriptorProto_Label_LABEL_REQUIRED; - static const Label LABEL_REPEATED = + static constexpr Label LABEL_REPEATED = FieldDescriptorProto_Label_LABEL_REPEATED; static inline bool Label_IsValid(int value) { return FieldDescriptorProto_Label_IsValid(value); } - static const Label Label_MIN = + static constexpr Label Label_MIN = FieldDescriptorProto_Label_Label_MIN; - static const Label Label_MAX = + static constexpr Label Label_MAX = FieldDescriptorProto_Label_Label_MAX; - static const int Label_ARRAYSIZE = + static constexpr int Label_ARRAYSIZE = FieldDescriptorProto_Label_Label_ARRAYSIZE; - static inline const ::google::protobuf::EnumDescriptor* + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Label_descriptor() { return FieldDescriptorProto_Label_descriptor(); } - static inline const ::std::string& Label_Name(Label value) { - return FieldDescriptorProto_Label_Name(value); + template + static inline const std::string& Label_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function Label_Name."); + return FieldDescriptorProto_Label_Name(enum_t_value); } - static inline bool Label_Parse(const ::std::string& name, + static inline bool Label_Parse(const std::string& name, Label* value) { return FieldDescriptorProto_Label_Parse(name, value); } @@ -1679,225 +1823,192 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa bool has_name() const; void clear_name(); static const int kNameFieldNumber = 1; - const ::std::string& name() const; - void set_name(const ::std::string& value); - #if LANG_CXX11 - void set_name(::std::string&& value); - #endif + const std::string& name() const; + void set_name(const std::string& value); + void set_name(std::string&& value); void set_name(const char* value); void set_name(const char* value, size_t size); - ::std::string* mutable_name(); - ::std::string* release_name(); - void set_allocated_name(::std::string* name); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_name(); + std::string* release_name(); + void set_allocated_name(std::string* name); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_name(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_name(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_name( - ::std::string* name); + std::string* name); // optional string extendee = 2; bool has_extendee() const; void clear_extendee(); static const int kExtendeeFieldNumber = 2; - const ::std::string& extendee() const; - void set_extendee(const ::std::string& value); - #if LANG_CXX11 - void set_extendee(::std::string&& value); - #endif + const std::string& extendee() const; + void set_extendee(const std::string& value); + void set_extendee(std::string&& value); void set_extendee(const char* value); void set_extendee(const char* value, size_t size); - ::std::string* mutable_extendee(); - ::std::string* release_extendee(); - void set_allocated_extendee(::std::string* extendee); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_extendee(); + std::string* release_extendee(); + void set_allocated_extendee(std::string* extendee); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_extendee(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_extendee(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_extendee( - ::std::string* extendee); + std::string* extendee); // optional string type_name = 6; bool has_type_name() const; void clear_type_name(); static const int kTypeNameFieldNumber = 6; - const ::std::string& type_name() const; - void set_type_name(const ::std::string& value); - #if LANG_CXX11 - void set_type_name(::std::string&& value); - #endif + const std::string& type_name() const; + void set_type_name(const std::string& value); + void set_type_name(std::string&& value); void set_type_name(const char* value); void set_type_name(const char* value, size_t size); - ::std::string* mutable_type_name(); - ::std::string* release_type_name(); - void set_allocated_type_name(::std::string* type_name); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_type_name(); + std::string* release_type_name(); + void set_allocated_type_name(std::string* type_name); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_type_name(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_type_name(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_type_name( - ::std::string* type_name); + std::string* type_name); // optional string default_value = 7; bool has_default_value() const; void clear_default_value(); static const int kDefaultValueFieldNumber = 7; - const ::std::string& default_value() const; - void set_default_value(const ::std::string& value); - #if LANG_CXX11 - void set_default_value(::std::string&& value); - #endif + const std::string& default_value() const; + void set_default_value(const std::string& value); + void set_default_value(std::string&& value); void set_default_value(const char* value); void set_default_value(const char* value, size_t size); - ::std::string* mutable_default_value(); - ::std::string* release_default_value(); - void set_allocated_default_value(::std::string* default_value); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_default_value(); + std::string* release_default_value(); + void set_allocated_default_value(std::string* default_value); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_default_value(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_default_value(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_default_value( - ::std::string* default_value); + std::string* default_value); // optional string json_name = 10; bool has_json_name() const; void clear_json_name(); static const int kJsonNameFieldNumber = 10; - const ::std::string& json_name() const; - void set_json_name(const ::std::string& value); - #if LANG_CXX11 - void set_json_name(::std::string&& value); - #endif + const std::string& json_name() const; + void set_json_name(const std::string& value); + void set_json_name(std::string&& value); void set_json_name(const char* value); void set_json_name(const char* value, size_t size); - ::std::string* mutable_json_name(); - ::std::string* release_json_name(); - void set_allocated_json_name(::std::string* json_name); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_json_name(); + std::string* release_json_name(); + void set_allocated_json_name(std::string* json_name); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_json_name(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_json_name(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_json_name( - ::std::string* json_name); + std::string* json_name); // optional .google.protobuf.FieldOptions options = 8; bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 8; - private: - const ::google::protobuf::FieldOptions& _internal_options() const; - public: - const ::google::protobuf::FieldOptions& options() const; - ::google::protobuf::FieldOptions* release_options(); - ::google::protobuf::FieldOptions* mutable_options(); - void set_allocated_options(::google::protobuf::FieldOptions* options); + const PROTOBUF_NAMESPACE_ID::FieldOptions& options() const; + PROTOBUF_NAMESPACE_ID::FieldOptions* release_options(); + PROTOBUF_NAMESPACE_ID::FieldOptions* mutable_options(); + void set_allocated_options(PROTOBUF_NAMESPACE_ID::FieldOptions* options); void unsafe_arena_set_allocated_options( - ::google::protobuf::FieldOptions* options); - ::google::protobuf::FieldOptions* unsafe_arena_release_options(); + PROTOBUF_NAMESPACE_ID::FieldOptions* options); + PROTOBUF_NAMESPACE_ID::FieldOptions* unsafe_arena_release_options(); // optional int32 number = 3; bool has_number() const; void clear_number(); static const int kNumberFieldNumber = 3; - ::google::protobuf::int32 number() const; - void set_number(::google::protobuf::int32 value); + ::PROTOBUF_NAMESPACE_ID::int32 number() const; + void set_number(::PROTOBUF_NAMESPACE_ID::int32 value); // optional int32 oneof_index = 9; bool has_oneof_index() const; void clear_oneof_index(); static const int kOneofIndexFieldNumber = 9; - ::google::protobuf::int32 oneof_index() const; - void set_oneof_index(::google::protobuf::int32 value); + ::PROTOBUF_NAMESPACE_ID::int32 oneof_index() const; + void set_oneof_index(::PROTOBUF_NAMESPACE_ID::int32 value); // optional .google.protobuf.FieldDescriptorProto.Label label = 4; bool has_label() const; void clear_label(); static const int kLabelFieldNumber = 4; - ::google::protobuf::FieldDescriptorProto_Label label() const; - void set_label(::google::protobuf::FieldDescriptorProto_Label value); + PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label label() const; + void set_label(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label value); // optional .google.protobuf.FieldDescriptorProto.Type type = 5; bool has_type() const; void clear_type(); static const int kTypeFieldNumber = 5; - ::google::protobuf::FieldDescriptorProto_Type type() const; - void set_type(::google::protobuf::FieldDescriptorProto_Type value); + PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type type() const; + void set_type(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type value); // @@protoc_insertion_point(class_scope:google.protobuf.FieldDescriptorProto) private: - void set_has_name(); - void clear_has_name(); - void set_has_number(); - void clear_has_number(); - void set_has_label(); - void clear_has_label(); - void set_has_type(); - void clear_has_type(); - void set_has_type_name(); - void clear_has_type_name(); - void set_has_extendee(); - void clear_has_extendee(); - void set_has_default_value(); - void clear_has_default_value(); - void set_has_oneof_index(); - void clear_has_oneof_index(); - void set_has_json_name(); - void clear_has_json_name(); - void set_has_options(); - void clear_has_options(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::internal::ArenaStringPtr name_; - ::google::protobuf::internal::ArenaStringPtr extendee_; - ::google::protobuf::internal::ArenaStringPtr type_name_; - ::google::protobuf::internal::ArenaStringPtr default_value_; - ::google::protobuf::internal::ArenaStringPtr json_name_; - ::google::protobuf::FieldOptions* options_; - ::google::protobuf::int32 number_; - ::google::protobuf::int32 oneof_index_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr extendee_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr type_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr default_value_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr json_name_; + PROTOBUF_NAMESPACE_ID::FieldOptions* options_; + ::PROTOBUF_NAMESPACE_ID::int32 number_; + ::PROTOBUF_NAMESPACE_ID::int32 oneof_index_; int label_; int type_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.OneofDescriptorProto) */ { +class PROTOBUF_EXPORT OneofDescriptorProto : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.OneofDescriptorProto) */ { public: OneofDescriptorProto(); virtual ~OneofDescriptorProto(); OneofDescriptorProto(const OneofDescriptorProto& from); - - inline OneofDescriptorProto& operator=(const OneofDescriptorProto& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 OneofDescriptorProto(OneofDescriptorProto&& from) noexcept : OneofDescriptorProto() { *this = ::std::move(from); } + inline OneofDescriptorProto& operator=(const OneofDescriptorProto& from) { + CopyFrom(from); + return *this; + } inline OneofDescriptorProto& operator=(OneofDescriptorProto&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -1906,21 +2017,29 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const OneofDescriptorProto& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -1940,40 +2059,48 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa // implements Message ---------------------------------------------- inline OneofDescriptorProto* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - OneofDescriptorProto* New(::google::protobuf::Arena* arena) const final { + OneofDescriptorProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const OneofDescriptorProto& from); void MergeFrom(const OneofDescriptorProto& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(OneofDescriptorProto* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.OneofDescriptorProto"; + } protected: - explicit OneofDescriptorProto(::google::protobuf::Arena* arena); + explicit OneofDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -1981,7 +2108,14 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -1991,77 +2125,68 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa bool has_name() const; void clear_name(); static const int kNameFieldNumber = 1; - const ::std::string& name() const; - void set_name(const ::std::string& value); - #if LANG_CXX11 - void set_name(::std::string&& value); - #endif + const std::string& name() const; + void set_name(const std::string& value); + void set_name(std::string&& value); void set_name(const char* value); void set_name(const char* value, size_t size); - ::std::string* mutable_name(); - ::std::string* release_name(); - void set_allocated_name(::std::string* name); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_name(); + std::string* release_name(); + void set_allocated_name(std::string* name); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_name(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_name(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_name( - ::std::string* name); + std::string* name); // optional .google.protobuf.OneofOptions options = 2; bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 2; - private: - const ::google::protobuf::OneofOptions& _internal_options() const; - public: - const ::google::protobuf::OneofOptions& options() const; - ::google::protobuf::OneofOptions* release_options(); - ::google::protobuf::OneofOptions* mutable_options(); - void set_allocated_options(::google::protobuf::OneofOptions* options); + const PROTOBUF_NAMESPACE_ID::OneofOptions& options() const; + PROTOBUF_NAMESPACE_ID::OneofOptions* release_options(); + PROTOBUF_NAMESPACE_ID::OneofOptions* mutable_options(); + void set_allocated_options(PROTOBUF_NAMESPACE_ID::OneofOptions* options); void unsafe_arena_set_allocated_options( - ::google::protobuf::OneofOptions* options); - ::google::protobuf::OneofOptions* unsafe_arena_release_options(); + PROTOBUF_NAMESPACE_ID::OneofOptions* options); + PROTOBUF_NAMESPACE_ID::OneofOptions* unsafe_arena_release_options(); // @@protoc_insertion_point(class_scope:google.protobuf.OneofDescriptorProto) private: - void set_has_name(); - void clear_has_name(); - void set_has_options(); - void clear_has_options(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::internal::ArenaStringPtr name_; - ::google::protobuf::OneofOptions* options_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + PROTOBUF_NAMESPACE_ID::OneofOptions* options_; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumDescriptorProto.EnumReservedRange) */ { +class PROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumDescriptorProto.EnumReservedRange) */ { public: EnumDescriptorProto_EnumReservedRange(); virtual ~EnumDescriptorProto_EnumReservedRange(); EnumDescriptorProto_EnumReservedRange(const EnumDescriptorProto_EnumReservedRange& from); - - inline EnumDescriptorProto_EnumReservedRange& operator=(const EnumDescriptorProto_EnumReservedRange& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 EnumDescriptorProto_EnumReservedRange(EnumDescriptorProto_EnumReservedRange&& from) noexcept : EnumDescriptorProto_EnumReservedRange() { *this = ::std::move(from); } + inline EnumDescriptorProto_EnumReservedRange& operator=(const EnumDescriptorProto_EnumReservedRange& from) { + CopyFrom(from); + return *this; + } inline EnumDescriptorProto_EnumReservedRange& operator=(EnumDescriptorProto_EnumReservedRange&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -2070,21 +2195,29 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const EnumDescriptorProto_EnumReservedRange& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -2104,40 +2237,48 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google // implements Message ---------------------------------------------- inline EnumDescriptorProto_EnumReservedRange* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - EnumDescriptorProto_EnumReservedRange* New(::google::protobuf::Arena* arena) const final { + EnumDescriptorProto_EnumReservedRange* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const EnumDescriptorProto_EnumReservedRange& from); void MergeFrom(const EnumDescriptorProto_EnumReservedRange& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(EnumDescriptorProto_EnumReservedRange* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.EnumDescriptorProto.EnumReservedRange"; + } protected: - explicit EnumDescriptorProto_EnumReservedRange(::google::protobuf::Arena* arena); + explicit EnumDescriptorProto_EnumReservedRange(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -2145,7 +2286,14 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -2155,52 +2303,48 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google bool has_start() const; void clear_start(); static const int kStartFieldNumber = 1; - ::google::protobuf::int32 start() const; - void set_start(::google::protobuf::int32 value); + ::PROTOBUF_NAMESPACE_ID::int32 start() const; + void set_start(::PROTOBUF_NAMESPACE_ID::int32 value); // optional int32 end = 2; bool has_end() const; void clear_end(); static const int kEndFieldNumber = 2; - ::google::protobuf::int32 end() const; - void set_end(::google::protobuf::int32 value); + ::PROTOBUF_NAMESPACE_ID::int32 end() const; + void set_end(::PROTOBUF_NAMESPACE_ID::int32 value); // @@protoc_insertion_point(class_scope:google.protobuf.EnumDescriptorProto.EnumReservedRange) private: - void set_has_start(); - void clear_has_start(); - void set_has_end(); - void clear_has_end(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::int32 start_; - ::google::protobuf::int32 end_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::int32 start_; + ::PROTOBUF_NAMESPACE_ID::int32 end_; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumDescriptorProto) */ { +class PROTOBUF_EXPORT EnumDescriptorProto : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumDescriptorProto) */ { public: EnumDescriptorProto(); virtual ~EnumDescriptorProto(); EnumDescriptorProto(const EnumDescriptorProto& from); - - inline EnumDescriptorProto& operator=(const EnumDescriptorProto& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 EnumDescriptorProto(EnumDescriptorProto&& from) noexcept : EnumDescriptorProto() { *this = ::std::move(from); } + inline EnumDescriptorProto& operator=(const EnumDescriptorProto& from) { + CopyFrom(from); + return *this; + } inline EnumDescriptorProto& operator=(EnumDescriptorProto&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -2209,21 +2353,29 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const EnumDescriptorProto& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -2243,40 +2395,48 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag // implements Message ---------------------------------------------- inline EnumDescriptorProto* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - EnumDescriptorProto* New(::google::protobuf::Arena* arena) const final { + EnumDescriptorProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const EnumDescriptorProto& from); void MergeFrom(const EnumDescriptorProto& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(EnumDescriptorProto* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.EnumDescriptorProto"; + } protected: - explicit EnumDescriptorProto(::google::protobuf::Arena* arena); + explicit EnumDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -2284,7 +2444,14 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -2296,126 +2463,113 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag int value_size() const; void clear_value(); static const int kValueFieldNumber = 2; - ::google::protobuf::EnumValueDescriptorProto* mutable_value(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto >* + PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto* mutable_value(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto >* mutable_value(); - const ::google::protobuf::EnumValueDescriptorProto& value(int index) const; - ::google::protobuf::EnumValueDescriptorProto* add_value(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto >& + const PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto& value(int index) const; + PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto* add_value(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto >& value() const; // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4; int reserved_range_size() const; void clear_reserved_range(); static const int kReservedRangeFieldNumber = 4; - ::google::protobuf::EnumDescriptorProto_EnumReservedRange* mutable_reserved_range(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >* + PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange* mutable_reserved_range(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange >* mutable_reserved_range(); - const ::google::protobuf::EnumDescriptorProto_EnumReservedRange& reserved_range(int index) const; - ::google::protobuf::EnumDescriptorProto_EnumReservedRange* add_reserved_range(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >& + const PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange& reserved_range(int index) const; + PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange* add_reserved_range(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange >& reserved_range() const; // repeated string reserved_name = 5; int reserved_name_size() const; void clear_reserved_name(); static const int kReservedNameFieldNumber = 5; - const ::std::string& reserved_name(int index) const; - ::std::string* mutable_reserved_name(int index); - void set_reserved_name(int index, const ::std::string& value); - #if LANG_CXX11 - void set_reserved_name(int index, ::std::string&& value); - #endif + const std::string& reserved_name(int index) const; + std::string* mutable_reserved_name(int index); + void set_reserved_name(int index, const std::string& value); + void set_reserved_name(int index, std::string&& value); void set_reserved_name(int index, const char* value); void set_reserved_name(int index, const char* value, size_t size); - ::std::string* add_reserved_name(); - void add_reserved_name(const ::std::string& value); - #if LANG_CXX11 - void add_reserved_name(::std::string&& value); - #endif + std::string* add_reserved_name(); + void add_reserved_name(const std::string& value); + void add_reserved_name(std::string&& value); void add_reserved_name(const char* value); void add_reserved_name(const char* value, size_t size); - const ::google::protobuf::RepeatedPtrField< ::std::string>& reserved_name() const; - ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_reserved_name(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& reserved_name() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* mutable_reserved_name(); // optional string name = 1; bool has_name() const; void clear_name(); static const int kNameFieldNumber = 1; - const ::std::string& name() const; - void set_name(const ::std::string& value); - #if LANG_CXX11 - void set_name(::std::string&& value); - #endif + const std::string& name() const; + void set_name(const std::string& value); + void set_name(std::string&& value); void set_name(const char* value); void set_name(const char* value, size_t size); - ::std::string* mutable_name(); - ::std::string* release_name(); - void set_allocated_name(::std::string* name); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_name(); + std::string* release_name(); + void set_allocated_name(std::string* name); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_name(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_name(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_name( - ::std::string* name); + std::string* name); // optional .google.protobuf.EnumOptions options = 3; bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 3; - private: - const ::google::protobuf::EnumOptions& _internal_options() const; - public: - const ::google::protobuf::EnumOptions& options() const; - ::google::protobuf::EnumOptions* release_options(); - ::google::protobuf::EnumOptions* mutable_options(); - void set_allocated_options(::google::protobuf::EnumOptions* options); + const PROTOBUF_NAMESPACE_ID::EnumOptions& options() const; + PROTOBUF_NAMESPACE_ID::EnumOptions* release_options(); + PROTOBUF_NAMESPACE_ID::EnumOptions* mutable_options(); + void set_allocated_options(PROTOBUF_NAMESPACE_ID::EnumOptions* options); void unsafe_arena_set_allocated_options( - ::google::protobuf::EnumOptions* options); - ::google::protobuf::EnumOptions* unsafe_arena_release_options(); + PROTOBUF_NAMESPACE_ID::EnumOptions* options); + PROTOBUF_NAMESPACE_ID::EnumOptions* unsafe_arena_release_options(); // @@protoc_insertion_point(class_scope:google.protobuf.EnumDescriptorProto) private: - void set_has_name(); - void clear_has_name(); - void set_has_options(); - void clear_has_options(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto > value_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto_EnumReservedRange > reserved_range_; - ::google::protobuf::RepeatedPtrField< ::std::string> reserved_name_; - ::google::protobuf::internal::ArenaStringPtr name_; - ::google::protobuf::EnumOptions* options_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto > value_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange > reserved_range_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField reserved_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + PROTOBUF_NAMESPACE_ID::EnumOptions* options_; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValueDescriptorProto) */ { +class PROTOBUF_EXPORT EnumValueDescriptorProto : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValueDescriptorProto) */ { public: EnumValueDescriptorProto(); virtual ~EnumValueDescriptorProto(); EnumValueDescriptorProto(const EnumValueDescriptorProto& from); - - inline EnumValueDescriptorProto& operator=(const EnumValueDescriptorProto& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 EnumValueDescriptorProto(EnumValueDescriptorProto&& from) noexcept : EnumValueDescriptorProto() { *this = ::std::move(from); } + inline EnumValueDescriptorProto& operator=(const EnumValueDescriptorProto& from) { + CopyFrom(from); + return *this; + } inline EnumValueDescriptorProto& operator=(EnumValueDescriptorProto&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -2424,21 +2578,29 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const EnumValueDescriptorProto& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -2458,40 +2620,48 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M // implements Message ---------------------------------------------- inline EnumValueDescriptorProto* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - EnumValueDescriptorProto* New(::google::protobuf::Arena* arena) const final { + EnumValueDescriptorProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const EnumValueDescriptorProto& from); void MergeFrom(const EnumValueDescriptorProto& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(EnumValueDescriptorProto* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.EnumValueDescriptorProto"; + } protected: - explicit EnumValueDescriptorProto(::google::protobuf::Arena* arena); + explicit EnumValueDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -2499,7 +2669,14 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -2509,87 +2686,76 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M bool has_name() const; void clear_name(); static const int kNameFieldNumber = 1; - const ::std::string& name() const; - void set_name(const ::std::string& value); - #if LANG_CXX11 - void set_name(::std::string&& value); - #endif + const std::string& name() const; + void set_name(const std::string& value); + void set_name(std::string&& value); void set_name(const char* value); void set_name(const char* value, size_t size); - ::std::string* mutable_name(); - ::std::string* release_name(); - void set_allocated_name(::std::string* name); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_name(); + std::string* release_name(); + void set_allocated_name(std::string* name); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_name(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_name(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_name( - ::std::string* name); + std::string* name); // optional .google.protobuf.EnumValueOptions options = 3; bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 3; - private: - const ::google::protobuf::EnumValueOptions& _internal_options() const; - public: - const ::google::protobuf::EnumValueOptions& options() const; - ::google::protobuf::EnumValueOptions* release_options(); - ::google::protobuf::EnumValueOptions* mutable_options(); - void set_allocated_options(::google::protobuf::EnumValueOptions* options); + const PROTOBUF_NAMESPACE_ID::EnumValueOptions& options() const; + PROTOBUF_NAMESPACE_ID::EnumValueOptions* release_options(); + PROTOBUF_NAMESPACE_ID::EnumValueOptions* mutable_options(); + void set_allocated_options(PROTOBUF_NAMESPACE_ID::EnumValueOptions* options); void unsafe_arena_set_allocated_options( - ::google::protobuf::EnumValueOptions* options); - ::google::protobuf::EnumValueOptions* unsafe_arena_release_options(); + PROTOBUF_NAMESPACE_ID::EnumValueOptions* options); + PROTOBUF_NAMESPACE_ID::EnumValueOptions* unsafe_arena_release_options(); // optional int32 number = 2; bool has_number() const; void clear_number(); static const int kNumberFieldNumber = 2; - ::google::protobuf::int32 number() const; - void set_number(::google::protobuf::int32 value); + ::PROTOBUF_NAMESPACE_ID::int32 number() const; + void set_number(::PROTOBUF_NAMESPACE_ID::int32 value); // @@protoc_insertion_point(class_scope:google.protobuf.EnumValueDescriptorProto) private: - void set_has_name(); - void clear_has_name(); - void set_has_number(); - void clear_has_number(); - void set_has_options(); - void clear_has_options(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::internal::ArenaStringPtr name_; - ::google::protobuf::EnumValueOptions* options_; - ::google::protobuf::int32 number_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + PROTOBUF_NAMESPACE_ID::EnumValueOptions* options_; + ::PROTOBUF_NAMESPACE_ID::int32 number_; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ServiceDescriptorProto) */ { +class PROTOBUF_EXPORT ServiceDescriptorProto : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ServiceDescriptorProto) */ { public: ServiceDescriptorProto(); virtual ~ServiceDescriptorProto(); ServiceDescriptorProto(const ServiceDescriptorProto& from); - - inline ServiceDescriptorProto& operator=(const ServiceDescriptorProto& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 ServiceDescriptorProto(ServiceDescriptorProto&& from) noexcept : ServiceDescriptorProto() { *this = ::std::move(from); } + inline ServiceDescriptorProto& operator=(const ServiceDescriptorProto& from) { + CopyFrom(from); + return *this; + } inline ServiceDescriptorProto& operator=(ServiceDescriptorProto&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -2598,21 +2764,29 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const ServiceDescriptorProto& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -2632,40 +2806,48 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes // implements Message ---------------------------------------------- inline ServiceDescriptorProto* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - ServiceDescriptorProto* New(::google::protobuf::Arena* arena) const final { + ServiceDescriptorProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const ServiceDescriptorProto& from); void MergeFrom(const ServiceDescriptorProto& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(ServiceDescriptorProto* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.ServiceDescriptorProto"; + } protected: - explicit ServiceDescriptorProto(::google::protobuf::Arena* arena); + explicit ServiceDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -2673,7 +2855,14 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -2683,90 +2872,81 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes int method_size() const; void clear_method(); static const int kMethodFieldNumber = 2; - ::google::protobuf::MethodDescriptorProto* mutable_method(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto >* + PROTOBUF_NAMESPACE_ID::MethodDescriptorProto* mutable_method(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::MethodDescriptorProto >* mutable_method(); - const ::google::protobuf::MethodDescriptorProto& method(int index) const; - ::google::protobuf::MethodDescriptorProto* add_method(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto >& + const PROTOBUF_NAMESPACE_ID::MethodDescriptorProto& method(int index) const; + PROTOBUF_NAMESPACE_ID::MethodDescriptorProto* add_method(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::MethodDescriptorProto >& method() const; // optional string name = 1; bool has_name() const; void clear_name(); static const int kNameFieldNumber = 1; - const ::std::string& name() const; - void set_name(const ::std::string& value); - #if LANG_CXX11 - void set_name(::std::string&& value); - #endif + const std::string& name() const; + void set_name(const std::string& value); + void set_name(std::string&& value); void set_name(const char* value); void set_name(const char* value, size_t size); - ::std::string* mutable_name(); - ::std::string* release_name(); - void set_allocated_name(::std::string* name); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_name(); + std::string* release_name(); + void set_allocated_name(std::string* name); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_name(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_name(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_name( - ::std::string* name); + std::string* name); // optional .google.protobuf.ServiceOptions options = 3; bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 3; - private: - const ::google::protobuf::ServiceOptions& _internal_options() const; - public: - const ::google::protobuf::ServiceOptions& options() const; - ::google::protobuf::ServiceOptions* release_options(); - ::google::protobuf::ServiceOptions* mutable_options(); - void set_allocated_options(::google::protobuf::ServiceOptions* options); + const PROTOBUF_NAMESPACE_ID::ServiceOptions& options() const; + PROTOBUF_NAMESPACE_ID::ServiceOptions* release_options(); + PROTOBUF_NAMESPACE_ID::ServiceOptions* mutable_options(); + void set_allocated_options(PROTOBUF_NAMESPACE_ID::ServiceOptions* options); void unsafe_arena_set_allocated_options( - ::google::protobuf::ServiceOptions* options); - ::google::protobuf::ServiceOptions* unsafe_arena_release_options(); + PROTOBUF_NAMESPACE_ID::ServiceOptions* options); + PROTOBUF_NAMESPACE_ID::ServiceOptions* unsafe_arena_release_options(); // @@protoc_insertion_point(class_scope:google.protobuf.ServiceDescriptorProto) private: - void set_has_name(); - void clear_has_name(); - void set_has_options(); - void clear_has_options(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto > method_; - ::google::protobuf::internal::ArenaStringPtr name_; - ::google::protobuf::ServiceOptions* options_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::MethodDescriptorProto > method_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + PROTOBUF_NAMESPACE_ID::ServiceOptions* options_; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MethodDescriptorProto) */ { +class PROTOBUF_EXPORT MethodDescriptorProto : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MethodDescriptorProto) */ { public: MethodDescriptorProto(); virtual ~MethodDescriptorProto(); MethodDescriptorProto(const MethodDescriptorProto& from); - - inline MethodDescriptorProto& operator=(const MethodDescriptorProto& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 MethodDescriptorProto(MethodDescriptorProto&& from) noexcept : MethodDescriptorProto() { *this = ::std::move(from); } + inline MethodDescriptorProto& operator=(const MethodDescriptorProto& from) { + CopyFrom(from); + return *this; + } inline MethodDescriptorProto& operator=(MethodDescriptorProto&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -2775,21 +2955,29 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const MethodDescriptorProto& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -2809,40 +2997,48 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess // implements Message ---------------------------------------------- inline MethodDescriptorProto* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - MethodDescriptorProto* New(::google::protobuf::Arena* arena) const final { + MethodDescriptorProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const MethodDescriptorProto& from); void MergeFrom(const MethodDescriptorProto& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(MethodDescriptorProto* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.MethodDescriptorProto"; + } protected: - explicit MethodDescriptorProto(::google::protobuf::Arena* arena); + explicit MethodDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -2850,7 +3046,14 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -2860,88 +3063,79 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess bool has_name() const; void clear_name(); static const int kNameFieldNumber = 1; - const ::std::string& name() const; - void set_name(const ::std::string& value); - #if LANG_CXX11 - void set_name(::std::string&& value); - #endif + const std::string& name() const; + void set_name(const std::string& value); + void set_name(std::string&& value); void set_name(const char* value); void set_name(const char* value, size_t size); - ::std::string* mutable_name(); - ::std::string* release_name(); - void set_allocated_name(::std::string* name); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_name(); + std::string* release_name(); + void set_allocated_name(std::string* name); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_name(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_name(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_name( - ::std::string* name); + std::string* name); // optional string input_type = 2; bool has_input_type() const; void clear_input_type(); static const int kInputTypeFieldNumber = 2; - const ::std::string& input_type() const; - void set_input_type(const ::std::string& value); - #if LANG_CXX11 - void set_input_type(::std::string&& value); - #endif + const std::string& input_type() const; + void set_input_type(const std::string& value); + void set_input_type(std::string&& value); void set_input_type(const char* value); void set_input_type(const char* value, size_t size); - ::std::string* mutable_input_type(); - ::std::string* release_input_type(); - void set_allocated_input_type(::std::string* input_type); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_input_type(); + std::string* release_input_type(); + void set_allocated_input_type(std::string* input_type); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_input_type(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_input_type(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_input_type( - ::std::string* input_type); + std::string* input_type); // optional string output_type = 3; bool has_output_type() const; void clear_output_type(); static const int kOutputTypeFieldNumber = 3; - const ::std::string& output_type() const; - void set_output_type(const ::std::string& value); - #if LANG_CXX11 - void set_output_type(::std::string&& value); - #endif + const std::string& output_type() const; + void set_output_type(const std::string& value); + void set_output_type(std::string&& value); void set_output_type(const char* value); void set_output_type(const char* value, size_t size); - ::std::string* mutable_output_type(); - ::std::string* release_output_type(); - void set_allocated_output_type(::std::string* output_type); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_output_type(); + std::string* release_output_type(); + void set_allocated_output_type(std::string* output_type); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_output_type(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_output_type(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_output_type( - ::std::string* output_type); + std::string* output_type); // optional .google.protobuf.MethodOptions options = 4; bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 4; - private: - const ::google::protobuf::MethodOptions& _internal_options() const; - public: - const ::google::protobuf::MethodOptions& options() const; - ::google::protobuf::MethodOptions* release_options(); - ::google::protobuf::MethodOptions* mutable_options(); - void set_allocated_options(::google::protobuf::MethodOptions* options); + const PROTOBUF_NAMESPACE_ID::MethodOptions& options() const; + PROTOBUF_NAMESPACE_ID::MethodOptions* release_options(); + PROTOBUF_NAMESPACE_ID::MethodOptions* mutable_options(); + void set_allocated_options(PROTOBUF_NAMESPACE_ID::MethodOptions* options); void unsafe_arena_set_allocated_options( - ::google::protobuf::MethodOptions* options); - ::google::protobuf::MethodOptions* unsafe_arena_release_options(); + PROTOBUF_NAMESPACE_ID::MethodOptions* options); + PROTOBUF_NAMESPACE_ID::MethodOptions* unsafe_arena_release_options(); // optional bool client_streaming = 5 [default = false]; bool has_client_streaming() const; @@ -2959,52 +3153,40 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess // @@protoc_insertion_point(class_scope:google.protobuf.MethodDescriptorProto) private: - void set_has_name(); - void clear_has_name(); - void set_has_input_type(); - void clear_has_input_type(); - void set_has_output_type(); - void clear_has_output_type(); - void set_has_options(); - void clear_has_options(); - void set_has_client_streaming(); - void clear_has_client_streaming(); - void set_has_server_streaming(); - void clear_has_server_streaming(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::internal::ArenaStringPtr name_; - ::google::protobuf::internal::ArenaStringPtr input_type_; - ::google::protobuf::internal::ArenaStringPtr output_type_; - ::google::protobuf::MethodOptions* options_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr input_type_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr output_type_; + PROTOBUF_NAMESPACE_ID::MethodOptions* options_; bool client_streaming_; bool server_streaming_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileOptions) */ { +class PROTOBUF_EXPORT FileOptions : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileOptions) */ { public: FileOptions(); virtual ~FileOptions(); FileOptions(const FileOptions& from); - - inline FileOptions& operator=(const FileOptions& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 FileOptions(FileOptions&& from) noexcept : FileOptions() { *this = ::std::move(from); } + inline FileOptions& operator=(const FileOptions& from) { + CopyFrom(from); + return *this; + } inline FileOptions& operator=(FileOptions&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -3013,21 +3195,29 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const FileOptions& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -3047,40 +3237,48 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p // implements Message ---------------------------------------------- inline FileOptions* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - FileOptions* New(::google::protobuf::Arena* arena) const final { + FileOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const FileOptions& from); void MergeFrom(const FileOptions& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(FileOptions* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.FileOptions"; + } protected: - explicit FileOptions(::google::protobuf::Arena* arena); + explicit FileOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -3088,34 +3286,45 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- typedef FileOptions_OptimizeMode OptimizeMode; - static const OptimizeMode SPEED = + static constexpr OptimizeMode SPEED = FileOptions_OptimizeMode_SPEED; - static const OptimizeMode CODE_SIZE = + static constexpr OptimizeMode CODE_SIZE = FileOptions_OptimizeMode_CODE_SIZE; - static const OptimizeMode LITE_RUNTIME = + static constexpr OptimizeMode LITE_RUNTIME = FileOptions_OptimizeMode_LITE_RUNTIME; static inline bool OptimizeMode_IsValid(int value) { return FileOptions_OptimizeMode_IsValid(value); } - static const OptimizeMode OptimizeMode_MIN = + static constexpr OptimizeMode OptimizeMode_MIN = FileOptions_OptimizeMode_OptimizeMode_MIN; - static const OptimizeMode OptimizeMode_MAX = + static constexpr OptimizeMode OptimizeMode_MAX = FileOptions_OptimizeMode_OptimizeMode_MAX; - static const int OptimizeMode_ARRAYSIZE = + static constexpr int OptimizeMode_ARRAYSIZE = FileOptions_OptimizeMode_OptimizeMode_ARRAYSIZE; - static inline const ::google::protobuf::EnumDescriptor* + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* OptimizeMode_descriptor() { return FileOptions_OptimizeMode_descriptor(); } - static inline const ::std::string& OptimizeMode_Name(OptimizeMode value) { - return FileOptions_OptimizeMode_Name(value); + template + static inline const std::string& OptimizeMode_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function OptimizeMode_Name."); + return FileOptions_OptimizeMode_Name(enum_t_value); } - static inline bool OptimizeMode_Parse(const ::std::string& name, + static inline bool OptimizeMode_Parse(const std::string& name, OptimizeMode* value) { return FileOptions_OptimizeMode_Parse(name, value); } @@ -3126,253 +3335,233 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p int uninterpreted_option_size() const; void clear_uninterpreted_option(); static const int kUninterpretedOptionFieldNumber = 999; - ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* + PROTOBUF_NAMESPACE_ID::UninterpretedOption* mutable_uninterpreted_option(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* mutable_uninterpreted_option(); - const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const; - ::google::protobuf::UninterpretedOption* add_uninterpreted_option(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& + const PROTOBUF_NAMESPACE_ID::UninterpretedOption& uninterpreted_option(int index) const; + PROTOBUF_NAMESPACE_ID::UninterpretedOption* add_uninterpreted_option(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& uninterpreted_option() const; // optional string java_package = 1; bool has_java_package() const; void clear_java_package(); static const int kJavaPackageFieldNumber = 1; - const ::std::string& java_package() const; - void set_java_package(const ::std::string& value); - #if LANG_CXX11 - void set_java_package(::std::string&& value); - #endif + const std::string& java_package() const; + void set_java_package(const std::string& value); + void set_java_package(std::string&& value); void set_java_package(const char* value); void set_java_package(const char* value, size_t size); - ::std::string* mutable_java_package(); - ::std::string* release_java_package(); - void set_allocated_java_package(::std::string* java_package); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_java_package(); + std::string* release_java_package(); + void set_allocated_java_package(std::string* java_package); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_java_package(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_java_package(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_java_package( - ::std::string* java_package); + std::string* java_package); // optional string java_outer_classname = 8; bool has_java_outer_classname() const; void clear_java_outer_classname(); static const int kJavaOuterClassnameFieldNumber = 8; - const ::std::string& java_outer_classname() const; - void set_java_outer_classname(const ::std::string& value); - #if LANG_CXX11 - void set_java_outer_classname(::std::string&& value); - #endif + const std::string& java_outer_classname() const; + void set_java_outer_classname(const std::string& value); + void set_java_outer_classname(std::string&& value); void set_java_outer_classname(const char* value); void set_java_outer_classname(const char* value, size_t size); - ::std::string* mutable_java_outer_classname(); - ::std::string* release_java_outer_classname(); - void set_allocated_java_outer_classname(::std::string* java_outer_classname); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_java_outer_classname(); + std::string* release_java_outer_classname(); + void set_allocated_java_outer_classname(std::string* java_outer_classname); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_java_outer_classname(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_java_outer_classname(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_java_outer_classname( - ::std::string* java_outer_classname); + std::string* java_outer_classname); // optional string go_package = 11; bool has_go_package() const; void clear_go_package(); static const int kGoPackageFieldNumber = 11; - const ::std::string& go_package() const; - void set_go_package(const ::std::string& value); - #if LANG_CXX11 - void set_go_package(::std::string&& value); - #endif + const std::string& go_package() const; + void set_go_package(const std::string& value); + void set_go_package(std::string&& value); void set_go_package(const char* value); void set_go_package(const char* value, size_t size); - ::std::string* mutable_go_package(); - ::std::string* release_go_package(); - void set_allocated_go_package(::std::string* go_package); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_go_package(); + std::string* release_go_package(); + void set_allocated_go_package(std::string* go_package); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_go_package(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_go_package(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_go_package( - ::std::string* go_package); + std::string* go_package); // optional string objc_class_prefix = 36; bool has_objc_class_prefix() const; void clear_objc_class_prefix(); static const int kObjcClassPrefixFieldNumber = 36; - const ::std::string& objc_class_prefix() const; - void set_objc_class_prefix(const ::std::string& value); - #if LANG_CXX11 - void set_objc_class_prefix(::std::string&& value); - #endif + const std::string& objc_class_prefix() const; + void set_objc_class_prefix(const std::string& value); + void set_objc_class_prefix(std::string&& value); void set_objc_class_prefix(const char* value); void set_objc_class_prefix(const char* value, size_t size); - ::std::string* mutable_objc_class_prefix(); - ::std::string* release_objc_class_prefix(); - void set_allocated_objc_class_prefix(::std::string* objc_class_prefix); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_objc_class_prefix(); + std::string* release_objc_class_prefix(); + void set_allocated_objc_class_prefix(std::string* objc_class_prefix); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_objc_class_prefix(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_objc_class_prefix(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_objc_class_prefix( - ::std::string* objc_class_prefix); + std::string* objc_class_prefix); // optional string csharp_namespace = 37; bool has_csharp_namespace() const; void clear_csharp_namespace(); static const int kCsharpNamespaceFieldNumber = 37; - const ::std::string& csharp_namespace() const; - void set_csharp_namespace(const ::std::string& value); - #if LANG_CXX11 - void set_csharp_namespace(::std::string&& value); - #endif + const std::string& csharp_namespace() const; + void set_csharp_namespace(const std::string& value); + void set_csharp_namespace(std::string&& value); void set_csharp_namespace(const char* value); void set_csharp_namespace(const char* value, size_t size); - ::std::string* mutable_csharp_namespace(); - ::std::string* release_csharp_namespace(); - void set_allocated_csharp_namespace(::std::string* csharp_namespace); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_csharp_namespace(); + std::string* release_csharp_namespace(); + void set_allocated_csharp_namespace(std::string* csharp_namespace); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_csharp_namespace(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_csharp_namespace(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_csharp_namespace( - ::std::string* csharp_namespace); + std::string* csharp_namespace); // optional string swift_prefix = 39; bool has_swift_prefix() const; void clear_swift_prefix(); static const int kSwiftPrefixFieldNumber = 39; - const ::std::string& swift_prefix() const; - void set_swift_prefix(const ::std::string& value); - #if LANG_CXX11 - void set_swift_prefix(::std::string&& value); - #endif + const std::string& swift_prefix() const; + void set_swift_prefix(const std::string& value); + void set_swift_prefix(std::string&& value); void set_swift_prefix(const char* value); void set_swift_prefix(const char* value, size_t size); - ::std::string* mutable_swift_prefix(); - ::std::string* release_swift_prefix(); - void set_allocated_swift_prefix(::std::string* swift_prefix); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_swift_prefix(); + std::string* release_swift_prefix(); + void set_allocated_swift_prefix(std::string* swift_prefix); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_swift_prefix(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_swift_prefix(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_swift_prefix( - ::std::string* swift_prefix); + std::string* swift_prefix); // optional string php_class_prefix = 40; bool has_php_class_prefix() const; void clear_php_class_prefix(); static const int kPhpClassPrefixFieldNumber = 40; - const ::std::string& php_class_prefix() const; - void set_php_class_prefix(const ::std::string& value); - #if LANG_CXX11 - void set_php_class_prefix(::std::string&& value); - #endif + const std::string& php_class_prefix() const; + void set_php_class_prefix(const std::string& value); + void set_php_class_prefix(std::string&& value); void set_php_class_prefix(const char* value); void set_php_class_prefix(const char* value, size_t size); - ::std::string* mutable_php_class_prefix(); - ::std::string* release_php_class_prefix(); - void set_allocated_php_class_prefix(::std::string* php_class_prefix); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_php_class_prefix(); + std::string* release_php_class_prefix(); + void set_allocated_php_class_prefix(std::string* php_class_prefix); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_php_class_prefix(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_php_class_prefix(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_php_class_prefix( - ::std::string* php_class_prefix); + std::string* php_class_prefix); // optional string php_namespace = 41; bool has_php_namespace() const; void clear_php_namespace(); static const int kPhpNamespaceFieldNumber = 41; - const ::std::string& php_namespace() const; - void set_php_namespace(const ::std::string& value); - #if LANG_CXX11 - void set_php_namespace(::std::string&& value); - #endif + const std::string& php_namespace() const; + void set_php_namespace(const std::string& value); + void set_php_namespace(std::string&& value); void set_php_namespace(const char* value); void set_php_namespace(const char* value, size_t size); - ::std::string* mutable_php_namespace(); - ::std::string* release_php_namespace(); - void set_allocated_php_namespace(::std::string* php_namespace); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_php_namespace(); + std::string* release_php_namespace(); + void set_allocated_php_namespace(std::string* php_namespace); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_php_namespace(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_php_namespace(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_php_namespace( - ::std::string* php_namespace); + std::string* php_namespace); // optional string php_metadata_namespace = 44; bool has_php_metadata_namespace() const; void clear_php_metadata_namespace(); static const int kPhpMetadataNamespaceFieldNumber = 44; - const ::std::string& php_metadata_namespace() const; - void set_php_metadata_namespace(const ::std::string& value); - #if LANG_CXX11 - void set_php_metadata_namespace(::std::string&& value); - #endif + const std::string& php_metadata_namespace() const; + void set_php_metadata_namespace(const std::string& value); + void set_php_metadata_namespace(std::string&& value); void set_php_metadata_namespace(const char* value); void set_php_metadata_namespace(const char* value, size_t size); - ::std::string* mutable_php_metadata_namespace(); - ::std::string* release_php_metadata_namespace(); - void set_allocated_php_metadata_namespace(::std::string* php_metadata_namespace); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_php_metadata_namespace(); + std::string* release_php_metadata_namespace(); + void set_allocated_php_metadata_namespace(std::string* php_metadata_namespace); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_php_metadata_namespace(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_php_metadata_namespace(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_php_metadata_namespace( - ::std::string* php_metadata_namespace); + std::string* php_metadata_namespace); // optional string ruby_package = 45; bool has_ruby_package() const; void clear_ruby_package(); static const int kRubyPackageFieldNumber = 45; - const ::std::string& ruby_package() const; - void set_ruby_package(const ::std::string& value); - #if LANG_CXX11 - void set_ruby_package(::std::string&& value); - #endif + const std::string& ruby_package() const; + void set_ruby_package(const std::string& value); + void set_ruby_package(std::string&& value); void set_ruby_package(const char* value); void set_ruby_package(const char* value, size_t size); - ::std::string* mutable_ruby_package(); - ::std::string* release_ruby_package(); - void set_allocated_ruby_package(::std::string* ruby_package); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_ruby_package(); + std::string* release_ruby_package(); + void set_allocated_ruby_package(std::string* ruby_package); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_ruby_package(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_ruby_package(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_ruby_package( - ::std::string* ruby_package); + std::string* ruby_package); // optional bool java_multiple_files = 10 [default = false]; bool has_java_multiple_files() const; @@ -3382,11 +3571,11 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p void set_java_multiple_files(bool value); // optional bool java_generate_equals_and_hash = 20 [deprecated = true]; - GOOGLE_PROTOBUF_DEPRECATED_ATTR bool has_java_generate_equals_and_hash() const; - GOOGLE_PROTOBUF_DEPRECATED_ATTR void clear_java_generate_equals_and_hash(); - GOOGLE_PROTOBUF_DEPRECATED_ATTR static const int kJavaGenerateEqualsAndHashFieldNumber = 20; - GOOGLE_PROTOBUF_DEPRECATED_ATTR bool java_generate_equals_and_hash() const; - GOOGLE_PROTOBUF_DEPRECATED_ATTR void set_java_generate_equals_and_hash(bool value); + PROTOBUF_DEPRECATED bool has_java_generate_equals_and_hash() const; + PROTOBUF_DEPRECATED void clear_java_generate_equals_and_hash(); + PROTOBUF_DEPRECATED static const int kJavaGenerateEqualsAndHashFieldNumber = 20; + PROTOBUF_DEPRECATED bool java_generate_equals_and_hash() const; + PROTOBUF_DEPRECATED void set_java_generate_equals_and_hash(bool value); // optional bool java_string_check_utf8 = 27 [default = false]; bool has_java_string_check_utf8() const; @@ -3441,72 +3630,33 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p bool has_optimize_for() const; void clear_optimize_for(); static const int kOptimizeForFieldNumber = 9; - ::google::protobuf::FileOptions_OptimizeMode optimize_for() const; - void set_optimize_for(::google::protobuf::FileOptions_OptimizeMode value); + PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode optimize_for() const; + void set_optimize_for(PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode value); GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(FileOptions) // @@protoc_insertion_point(class_scope:google.protobuf.FileOptions) private: - void set_has_java_package(); - void clear_has_java_package(); - void set_has_java_outer_classname(); - void clear_has_java_outer_classname(); - void set_has_java_multiple_files(); - void clear_has_java_multiple_files(); - void set_has_java_generate_equals_and_hash(); - void clear_has_java_generate_equals_and_hash(); - void set_has_java_string_check_utf8(); - void clear_has_java_string_check_utf8(); - void set_has_optimize_for(); - void clear_has_optimize_for(); - void set_has_go_package(); - void clear_has_go_package(); - void set_has_cc_generic_services(); - void clear_has_cc_generic_services(); - void set_has_java_generic_services(); - void clear_has_java_generic_services(); - void set_has_py_generic_services(); - void clear_has_py_generic_services(); - void set_has_php_generic_services(); - void clear_has_php_generic_services(); - void set_has_deprecated(); - void clear_has_deprecated(); - void set_has_cc_enable_arenas(); - void clear_has_cc_enable_arenas(); - void set_has_objc_class_prefix(); - void clear_has_objc_class_prefix(); - void set_has_csharp_namespace(); - void clear_has_csharp_namespace(); - void set_has_swift_prefix(); - void clear_has_swift_prefix(); - void set_has_php_class_prefix(); - void clear_has_php_class_prefix(); - void set_has_php_namespace(); - void clear_has_php_namespace(); - void set_has_php_metadata_namespace(); - void clear_has_php_metadata_namespace(); - void set_has_ruby_package(); - void clear_has_ruby_package(); + class HasBitSetters; - ::google::protobuf::internal::ExtensionSet _extensions_; + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; - ::google::protobuf::internal::ArenaStringPtr java_package_; - ::google::protobuf::internal::ArenaStringPtr java_outer_classname_; - ::google::protobuf::internal::ArenaStringPtr go_package_; - ::google::protobuf::internal::ArenaStringPtr objc_class_prefix_; - ::google::protobuf::internal::ArenaStringPtr csharp_namespace_; - ::google::protobuf::internal::ArenaStringPtr swift_prefix_; - ::google::protobuf::internal::ArenaStringPtr php_class_prefix_; - ::google::protobuf::internal::ArenaStringPtr php_namespace_; - ::google::protobuf::internal::ArenaStringPtr php_metadata_namespace_; - ::google::protobuf::internal::ArenaStringPtr ruby_package_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption > uninterpreted_option_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr java_package_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr java_outer_classname_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr go_package_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr objc_class_prefix_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr csharp_namespace_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr swift_prefix_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr php_class_prefix_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr php_namespace_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr php_metadata_namespace_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr ruby_package_; bool java_multiple_files_; bool java_generate_equals_and_hash_; bool java_string_check_utf8_; @@ -3517,27 +3667,26 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p bool deprecated_; bool cc_enable_arenas_; int optimize_for_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MessageOptions) */ { +class PROTOBUF_EXPORT MessageOptions : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MessageOptions) */ { public: MessageOptions(); virtual ~MessageOptions(); MessageOptions(const MessageOptions& from); - - inline MessageOptions& operator=(const MessageOptions& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 MessageOptions(MessageOptions&& from) noexcept : MessageOptions() { *this = ::std::move(from); } + inline MessageOptions& operator=(const MessageOptions& from) { + CopyFrom(from); + return *this; + } inline MessageOptions& operator=(MessageOptions&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -3546,21 +3695,29 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const MessageOptions& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -3580,40 +3737,48 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* // implements Message ---------------------------------------------- inline MessageOptions* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - MessageOptions* New(::google::protobuf::Arena* arena) const final { + MessageOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const MessageOptions& from); void MergeFrom(const MessageOptions& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(MessageOptions* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.MessageOptions"; + } protected: - explicit MessageOptions(::google::protobuf::Arena* arena); + explicit MessageOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -3621,7 +3786,14 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -3631,12 +3803,12 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* int uninterpreted_option_size() const; void clear_uninterpreted_option(); static const int kUninterpretedOptionFieldNumber = 999; - ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* + PROTOBUF_NAMESPACE_ID::UninterpretedOption* mutable_uninterpreted_option(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* mutable_uninterpreted_option(); - const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const; - ::google::protobuf::UninterpretedOption* add_uninterpreted_option(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& + const PROTOBUF_NAMESPACE_ID::UninterpretedOption& uninterpreted_option(int index) const; + PROTOBUF_NAMESPACE_ID::UninterpretedOption* add_uninterpreted_option(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& uninterpreted_option() const; // optional bool message_set_wire_format = 1 [default = false]; @@ -3670,49 +3842,41 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(MessageOptions) // @@protoc_insertion_point(class_scope:google.protobuf.MessageOptions) private: - void set_has_message_set_wire_format(); - void clear_has_message_set_wire_format(); - void set_has_no_standard_descriptor_accessor(); - void clear_has_no_standard_descriptor_accessor(); - void set_has_deprecated(); - void clear_has_deprecated(); - void set_has_map_entry(); - void clear_has_map_entry(); + class HasBitSetters; - ::google::protobuf::internal::ExtensionSet _extensions_; + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption > uninterpreted_option_; bool message_set_wire_format_; bool no_standard_descriptor_accessor_; bool deprecated_; bool map_entry_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldOptions) */ { +class PROTOBUF_EXPORT FieldOptions : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldOptions) */ { public: FieldOptions(); virtual ~FieldOptions(); FieldOptions(const FieldOptions& from); - - inline FieldOptions& operator=(const FieldOptions& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 FieldOptions(FieldOptions&& from) noexcept : FieldOptions() { *this = ::std::move(from); } + inline FieldOptions& operator=(const FieldOptions& from) { + CopyFrom(from); + return *this; + } inline FieldOptions& operator=(FieldOptions&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -3721,21 +3885,29 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const FieldOptions& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -3755,40 +3927,48 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ // implements Message ---------------------------------------------- inline FieldOptions* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - FieldOptions* New(::google::protobuf::Arena* arena) const final { + FieldOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const FieldOptions& from); void MergeFrom(const FieldOptions& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(FieldOptions* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.FieldOptions"; + } protected: - explicit FieldOptions(::google::protobuf::Arena* arena); + explicit FieldOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -3796,62 +3976,77 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- typedef FieldOptions_CType CType; - static const CType STRING = + static constexpr CType STRING = FieldOptions_CType_STRING; - static const CType CORD = + static constexpr CType CORD = FieldOptions_CType_CORD; - static const CType STRING_PIECE = + static constexpr CType STRING_PIECE = FieldOptions_CType_STRING_PIECE; static inline bool CType_IsValid(int value) { return FieldOptions_CType_IsValid(value); } - static const CType CType_MIN = + static constexpr CType CType_MIN = FieldOptions_CType_CType_MIN; - static const CType CType_MAX = + static constexpr CType CType_MAX = FieldOptions_CType_CType_MAX; - static const int CType_ARRAYSIZE = + static constexpr int CType_ARRAYSIZE = FieldOptions_CType_CType_ARRAYSIZE; - static inline const ::google::protobuf::EnumDescriptor* + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* CType_descriptor() { return FieldOptions_CType_descriptor(); } - static inline const ::std::string& CType_Name(CType value) { - return FieldOptions_CType_Name(value); + template + static inline const std::string& CType_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function CType_Name."); + return FieldOptions_CType_Name(enum_t_value); } - static inline bool CType_Parse(const ::std::string& name, + static inline bool CType_Parse(const std::string& name, CType* value) { return FieldOptions_CType_Parse(name, value); } typedef FieldOptions_JSType JSType; - static const JSType JS_NORMAL = + static constexpr JSType JS_NORMAL = FieldOptions_JSType_JS_NORMAL; - static const JSType JS_STRING = + static constexpr JSType JS_STRING = FieldOptions_JSType_JS_STRING; - static const JSType JS_NUMBER = + static constexpr JSType JS_NUMBER = FieldOptions_JSType_JS_NUMBER; static inline bool JSType_IsValid(int value) { return FieldOptions_JSType_IsValid(value); } - static const JSType JSType_MIN = + static constexpr JSType JSType_MIN = FieldOptions_JSType_JSType_MIN; - static const JSType JSType_MAX = + static constexpr JSType JSType_MAX = FieldOptions_JSType_JSType_MAX; - static const int JSType_ARRAYSIZE = + static constexpr int JSType_ARRAYSIZE = FieldOptions_JSType_JSType_ARRAYSIZE; - static inline const ::google::protobuf::EnumDescriptor* + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* JSType_descriptor() { return FieldOptions_JSType_descriptor(); } - static inline const ::std::string& JSType_Name(JSType value) { - return FieldOptions_JSType_Name(value); + template + static inline const std::string& JSType_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function JSType_Name."); + return FieldOptions_JSType_Name(enum_t_value); } - static inline bool JSType_Parse(const ::std::string& name, + static inline bool JSType_Parse(const std::string& name, JSType* value) { return FieldOptions_JSType_Parse(name, value); } @@ -3862,20 +4057,20 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ int uninterpreted_option_size() const; void clear_uninterpreted_option(); static const int kUninterpretedOptionFieldNumber = 999; - ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* + PROTOBUF_NAMESPACE_ID::UninterpretedOption* mutable_uninterpreted_option(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* mutable_uninterpreted_option(); - const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const; - ::google::protobuf::UninterpretedOption* add_uninterpreted_option(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& + const PROTOBUF_NAMESPACE_ID::UninterpretedOption& uninterpreted_option(int index) const; + PROTOBUF_NAMESPACE_ID::UninterpretedOption* add_uninterpreted_option(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& uninterpreted_option() const; // optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING]; bool has_ctype() const; void clear_ctype(); static const int kCtypeFieldNumber = 1; - ::google::protobuf::FieldOptions_CType ctype() const; - void set_ctype(::google::protobuf::FieldOptions_CType value); + PROTOBUF_NAMESPACE_ID::FieldOptions_CType ctype() const; + void set_ctype(PROTOBUF_NAMESPACE_ID::FieldOptions_CType value); // optional bool packed = 2; bool has_packed() const; @@ -3909,61 +4104,49 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ bool has_jstype() const; void clear_jstype(); static const int kJstypeFieldNumber = 6; - ::google::protobuf::FieldOptions_JSType jstype() const; - void set_jstype(::google::protobuf::FieldOptions_JSType value); + PROTOBUF_NAMESPACE_ID::FieldOptions_JSType jstype() const; + void set_jstype(PROTOBUF_NAMESPACE_ID::FieldOptions_JSType value); GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(FieldOptions) // @@protoc_insertion_point(class_scope:google.protobuf.FieldOptions) private: - void set_has_ctype(); - void clear_has_ctype(); - void set_has_packed(); - void clear_has_packed(); - void set_has_jstype(); - void clear_has_jstype(); - void set_has_lazy(); - void clear_has_lazy(); - void set_has_deprecated(); - void clear_has_deprecated(); - void set_has_weak(); - void clear_has_weak(); + class HasBitSetters; - ::google::protobuf::internal::ExtensionSet _extensions_; + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption > uninterpreted_option_; int ctype_; bool packed_; bool lazy_; bool deprecated_; bool weak_; int jstype_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.OneofOptions) */ { +class PROTOBUF_EXPORT OneofOptions : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.OneofOptions) */ { public: OneofOptions(); virtual ~OneofOptions(); OneofOptions(const OneofOptions& from); - - inline OneofOptions& operator=(const OneofOptions& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 OneofOptions(OneofOptions&& from) noexcept : OneofOptions() { *this = ::std::move(from); } + inline OneofOptions& operator=(const OneofOptions& from) { + CopyFrom(from); + return *this; + } inline OneofOptions& operator=(OneofOptions&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -3972,21 +4155,29 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@ } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const OneofOptions& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -4006,40 +4197,48 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@ // implements Message ---------------------------------------------- inline OneofOptions* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - OneofOptions* New(::google::protobuf::Arena* arena) const final { + OneofOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const OneofOptions& from); void MergeFrom(const OneofOptions& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(OneofOptions* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.OneofOptions"; + } protected: - explicit OneofOptions(::google::protobuf::Arena* arena); + explicit OneofOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -4047,7 +4246,14 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@ } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -4057,48 +4263,48 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@ int uninterpreted_option_size() const; void clear_uninterpreted_option(); static const int kUninterpretedOptionFieldNumber = 999; - ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* + PROTOBUF_NAMESPACE_ID::UninterpretedOption* mutable_uninterpreted_option(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* mutable_uninterpreted_option(); - const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const; - ::google::protobuf::UninterpretedOption* add_uninterpreted_option(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& + const PROTOBUF_NAMESPACE_ID::UninterpretedOption& uninterpreted_option(int index) const; + PROTOBUF_NAMESPACE_ID::UninterpretedOption* add_uninterpreted_option(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& uninterpreted_option() const; GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(OneofOptions) // @@protoc_insertion_point(class_scope:google.protobuf.OneofOptions) private: + class HasBitSetters; - ::google::protobuf::internal::ExtensionSet _extensions_; + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption > uninterpreted_option_; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumOptions) */ { +class PROTOBUF_EXPORT EnumOptions : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumOptions) */ { public: EnumOptions(); virtual ~EnumOptions(); EnumOptions(const EnumOptions& from); - - inline EnumOptions& operator=(const EnumOptions& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 EnumOptions(EnumOptions&& from) noexcept : EnumOptions() { *this = ::std::move(from); } + inline EnumOptions& operator=(const EnumOptions& from) { + CopyFrom(from); + return *this; + } inline EnumOptions& operator=(EnumOptions&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -4107,21 +4313,29 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const EnumOptions& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -4141,40 +4355,48 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p // implements Message ---------------------------------------------- inline EnumOptions* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - EnumOptions* New(::google::protobuf::Arena* arena) const final { + EnumOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const EnumOptions& from); void MergeFrom(const EnumOptions& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(EnumOptions* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.EnumOptions"; + } protected: - explicit EnumOptions(::google::protobuf::Arena* arena); + explicit EnumOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -4182,7 +4404,14 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -4192,12 +4421,12 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p int uninterpreted_option_size() const; void clear_uninterpreted_option(); static const int kUninterpretedOptionFieldNumber = 999; - ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* + PROTOBUF_NAMESPACE_ID::UninterpretedOption* mutable_uninterpreted_option(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* mutable_uninterpreted_option(); - const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const; - ::google::protobuf::UninterpretedOption* add_uninterpreted_option(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& + const PROTOBUF_NAMESPACE_ID::UninterpretedOption& uninterpreted_option(int index) const; + PROTOBUF_NAMESPACE_ID::UninterpretedOption* add_uninterpreted_option(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& uninterpreted_option() const; // optional bool allow_alias = 2; @@ -4217,43 +4446,39 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(EnumOptions) // @@protoc_insertion_point(class_scope:google.protobuf.EnumOptions) private: - void set_has_allow_alias(); - void clear_has_allow_alias(); - void set_has_deprecated(); - void clear_has_deprecated(); + class HasBitSetters; - ::google::protobuf::internal::ExtensionSet _extensions_; + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption > uninterpreted_option_; bool allow_alias_; bool deprecated_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValueOptions) */ { +class PROTOBUF_EXPORT EnumValueOptions : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValueOptions) */ { public: EnumValueOptions(); virtual ~EnumValueOptions(); EnumValueOptions(const EnumValueOptions& from); - - inline EnumValueOptions& operator=(const EnumValueOptions& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 EnumValueOptions(EnumValueOptions&& from) noexcept : EnumValueOptions() { *this = ::std::move(from); } + inline EnumValueOptions& operator=(const EnumValueOptions& from) { + CopyFrom(from); + return *this; + } inline EnumValueOptions& operator=(EnumValueOptions&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -4262,21 +4487,29 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message / } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const EnumValueOptions& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -4296,40 +4529,48 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message / // implements Message ---------------------------------------------- inline EnumValueOptions* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - EnumValueOptions* New(::google::protobuf::Arena* arena) const final { + EnumValueOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const EnumValueOptions& from); void MergeFrom(const EnumValueOptions& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(EnumValueOptions* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.EnumValueOptions"; + } protected: - explicit EnumValueOptions(::google::protobuf::Arena* arena); + explicit EnumValueOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -4337,7 +4578,14 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message / } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -4347,12 +4595,12 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message / int uninterpreted_option_size() const; void clear_uninterpreted_option(); static const int kUninterpretedOptionFieldNumber = 999; - ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* + PROTOBUF_NAMESPACE_ID::UninterpretedOption* mutable_uninterpreted_option(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* mutable_uninterpreted_option(); - const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const; - ::google::protobuf::UninterpretedOption* add_uninterpreted_option(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& + const PROTOBUF_NAMESPACE_ID::UninterpretedOption& uninterpreted_option(int index) const; + PROTOBUF_NAMESPACE_ID::UninterpretedOption* add_uninterpreted_option(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& uninterpreted_option() const; // optional bool deprecated = 1 [default = false]; @@ -4365,40 +4613,38 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message / GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(EnumValueOptions) // @@protoc_insertion_point(class_scope:google.protobuf.EnumValueOptions) private: - void set_has_deprecated(); - void clear_has_deprecated(); + class HasBitSetters; - ::google::protobuf::internal::ExtensionSet _extensions_; + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption > uninterpreted_option_; bool deprecated_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ServiceOptions) */ { +class PROTOBUF_EXPORT ServiceOptions : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ServiceOptions) */ { public: ServiceOptions(); virtual ~ServiceOptions(); ServiceOptions(const ServiceOptions& from); - - inline ServiceOptions& operator=(const ServiceOptions& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 ServiceOptions(ServiceOptions&& from) noexcept : ServiceOptions() { *this = ::std::move(from); } + inline ServiceOptions& operator=(const ServiceOptions& from) { + CopyFrom(from); + return *this; + } inline ServiceOptions& operator=(ServiceOptions&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -4407,21 +4653,29 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const ServiceOptions& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -4441,40 +4695,48 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* // implements Message ---------------------------------------------- inline ServiceOptions* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - ServiceOptions* New(::google::protobuf::Arena* arena) const final { + ServiceOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const ServiceOptions& from); void MergeFrom(const ServiceOptions& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(ServiceOptions* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.ServiceOptions"; + } protected: - explicit ServiceOptions(::google::protobuf::Arena* arena); + explicit ServiceOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -4482,7 +4744,14 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -4492,12 +4761,12 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* int uninterpreted_option_size() const; void clear_uninterpreted_option(); static const int kUninterpretedOptionFieldNumber = 999; - ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* + PROTOBUF_NAMESPACE_ID::UninterpretedOption* mutable_uninterpreted_option(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* mutable_uninterpreted_option(); - const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const; - ::google::protobuf::UninterpretedOption* add_uninterpreted_option(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& + const PROTOBUF_NAMESPACE_ID::UninterpretedOption& uninterpreted_option(int index) const; + PROTOBUF_NAMESPACE_ID::UninterpretedOption* add_uninterpreted_option(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& uninterpreted_option() const; // optional bool deprecated = 33 [default = false]; @@ -4510,40 +4779,38 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(ServiceOptions) // @@protoc_insertion_point(class_scope:google.protobuf.ServiceOptions) private: - void set_has_deprecated(); - void clear_has_deprecated(); + class HasBitSetters; - ::google::protobuf::internal::ExtensionSet _extensions_; + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption > uninterpreted_option_; bool deprecated_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MethodOptions) */ { +class PROTOBUF_EXPORT MethodOptions : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MethodOptions) */ { public: MethodOptions(); virtual ~MethodOptions(); MethodOptions(const MethodOptions& from); - - inline MethodOptions& operator=(const MethodOptions& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 MethodOptions(MethodOptions&& from) noexcept : MethodOptions() { *this = ::std::move(from); } + inline MethodOptions& operator=(const MethodOptions& from) { + CopyFrom(from); + return *this; + } inline MethodOptions& operator=(MethodOptions&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -4552,21 +4819,29 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @ } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const MethodOptions& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -4586,40 +4861,48 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @ // implements Message ---------------------------------------------- inline MethodOptions* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - MethodOptions* New(::google::protobuf::Arena* arena) const final { + MethodOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const MethodOptions& from); void MergeFrom(const MethodOptions& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(MethodOptions* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.MethodOptions"; + } protected: - explicit MethodOptions(::google::protobuf::Arena* arena); + explicit MethodOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -4627,34 +4910,45 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @ } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- typedef MethodOptions_IdempotencyLevel IdempotencyLevel; - static const IdempotencyLevel IDEMPOTENCY_UNKNOWN = + static constexpr IdempotencyLevel IDEMPOTENCY_UNKNOWN = MethodOptions_IdempotencyLevel_IDEMPOTENCY_UNKNOWN; - static const IdempotencyLevel NO_SIDE_EFFECTS = + static constexpr IdempotencyLevel NO_SIDE_EFFECTS = MethodOptions_IdempotencyLevel_NO_SIDE_EFFECTS; - static const IdempotencyLevel IDEMPOTENT = + static constexpr IdempotencyLevel IDEMPOTENT = MethodOptions_IdempotencyLevel_IDEMPOTENT; static inline bool IdempotencyLevel_IsValid(int value) { return MethodOptions_IdempotencyLevel_IsValid(value); } - static const IdempotencyLevel IdempotencyLevel_MIN = + static constexpr IdempotencyLevel IdempotencyLevel_MIN = MethodOptions_IdempotencyLevel_IdempotencyLevel_MIN; - static const IdempotencyLevel IdempotencyLevel_MAX = + static constexpr IdempotencyLevel IdempotencyLevel_MAX = MethodOptions_IdempotencyLevel_IdempotencyLevel_MAX; - static const int IdempotencyLevel_ARRAYSIZE = + static constexpr int IdempotencyLevel_ARRAYSIZE = MethodOptions_IdempotencyLevel_IdempotencyLevel_ARRAYSIZE; - static inline const ::google::protobuf::EnumDescriptor* + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* IdempotencyLevel_descriptor() { return MethodOptions_IdempotencyLevel_descriptor(); } - static inline const ::std::string& IdempotencyLevel_Name(IdempotencyLevel value) { - return MethodOptions_IdempotencyLevel_Name(value); + template + static inline const std::string& IdempotencyLevel_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function IdempotencyLevel_Name."); + return MethodOptions_IdempotencyLevel_Name(enum_t_value); } - static inline bool IdempotencyLevel_Parse(const ::std::string& name, + static inline bool IdempotencyLevel_Parse(const std::string& name, IdempotencyLevel* value) { return MethodOptions_IdempotencyLevel_Parse(name, value); } @@ -4665,12 +4959,12 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @ int uninterpreted_option_size() const; void clear_uninterpreted_option(); static const int kUninterpretedOptionFieldNumber = 999; - ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* + PROTOBUF_NAMESPACE_ID::UninterpretedOption* mutable_uninterpreted_option(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* mutable_uninterpreted_option(); - const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const; - ::google::protobuf::UninterpretedOption* add_uninterpreted_option(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& + const PROTOBUF_NAMESPACE_ID::UninterpretedOption& uninterpreted_option(int index) const; + PROTOBUF_NAMESPACE_ID::UninterpretedOption* add_uninterpreted_option(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& uninterpreted_option() const; // optional bool deprecated = 33 [default = false]; @@ -4684,49 +4978,45 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @ bool has_idempotency_level() const; void clear_idempotency_level(); static const int kIdempotencyLevelFieldNumber = 34; - ::google::protobuf::MethodOptions_IdempotencyLevel idempotency_level() const; - void set_idempotency_level(::google::protobuf::MethodOptions_IdempotencyLevel value); + PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel idempotency_level() const; + void set_idempotency_level(PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel value); GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(MethodOptions) // @@protoc_insertion_point(class_scope:google.protobuf.MethodOptions) private: - void set_has_deprecated(); - void clear_has_deprecated(); - void set_has_idempotency_level(); - void clear_has_idempotency_level(); + class HasBitSetters; - ::google::protobuf::internal::ExtensionSet _extensions_; + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption > uninterpreted_option_; bool deprecated_; int idempotency_level_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UninterpretedOption.NamePart) */ { +class PROTOBUF_EXPORT UninterpretedOption_NamePart : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UninterpretedOption.NamePart) */ { public: UninterpretedOption_NamePart(); virtual ~UninterpretedOption_NamePart(); UninterpretedOption_NamePart(const UninterpretedOption_NamePart& from); - - inline UninterpretedOption_NamePart& operator=(const UninterpretedOption_NamePart& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 UninterpretedOption_NamePart(UninterpretedOption_NamePart&& from) noexcept : UninterpretedOption_NamePart() { *this = ::std::move(from); } + inline UninterpretedOption_NamePart& operator=(const UninterpretedOption_NamePart& from) { + CopyFrom(from); + return *this; + } inline UninterpretedOption_NamePart& operator=(UninterpretedOption_NamePart&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -4735,21 +5025,29 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const UninterpretedOption_NamePart& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -4769,40 +5067,48 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu // implements Message ---------------------------------------------- inline UninterpretedOption_NamePart* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - UninterpretedOption_NamePart* New(::google::protobuf::Arena* arena) const final { + UninterpretedOption_NamePart* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const UninterpretedOption_NamePart& from); void MergeFrom(const UninterpretedOption_NamePart& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(UninterpretedOption_NamePart* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.UninterpretedOption.NamePart"; + } protected: - explicit UninterpretedOption_NamePart(::google::protobuf::Arena* arena); + explicit UninterpretedOption_NamePart(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -4810,7 +5116,14 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -4820,25 +5133,23 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu bool has_name_part() const; void clear_name_part(); static const int kNamePartFieldNumber = 1; - const ::std::string& name_part() const; - void set_name_part(const ::std::string& value); - #if LANG_CXX11 - void set_name_part(::std::string&& value); - #endif + const std::string& name_part() const; + void set_name_part(const std::string& value); + void set_name_part(std::string&& value); void set_name_part(const char* value); void set_name_part(const char* value, size_t size); - ::std::string* mutable_name_part(); - ::std::string* release_name_part(); - void set_allocated_name_part(::std::string* name_part); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_name_part(); + std::string* release_name_part(); + void set_allocated_name_part(std::string* name_part); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_name_part(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_name_part(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_name_part( - ::std::string* name_part); + std::string* name_part); // required bool is_extension = 2; bool has_is_extension() const; @@ -4849,43 +5160,39 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu // @@protoc_insertion_point(class_scope:google.protobuf.UninterpretedOption.NamePart) private: - void set_has_name_part(); - void clear_has_name_part(); - void set_has_is_extension(); - void clear_has_is_extension(); + class HasBitSetters; // helper for ByteSizeLong() size_t RequiredFieldsByteSizeFallback() const; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::internal::ArenaStringPtr name_part_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_part_; bool is_extension_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UninterpretedOption) */ { +class PROTOBUF_EXPORT UninterpretedOption : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UninterpretedOption) */ { public: UninterpretedOption(); virtual ~UninterpretedOption(); UninterpretedOption(const UninterpretedOption& from); - - inline UninterpretedOption& operator=(const UninterpretedOption& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 UninterpretedOption(UninterpretedOption&& from) noexcept : UninterpretedOption() { *this = ::std::move(from); } + inline UninterpretedOption& operator=(const UninterpretedOption& from) { + CopyFrom(from); + return *this; + } inline UninterpretedOption& operator=(UninterpretedOption&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -4894,21 +5201,29 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const UninterpretedOption& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -4928,40 +5243,48 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag // implements Message ---------------------------------------------- inline UninterpretedOption* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - UninterpretedOption* New(::google::protobuf::Arena* arena) const final { + UninterpretedOption* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const UninterpretedOption& from); void MergeFrom(const UninterpretedOption& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(UninterpretedOption* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.UninterpretedOption"; + } protected: - explicit UninterpretedOption(::google::protobuf::Arena* arena); + explicit UninterpretedOption(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -4969,7 +5292,14 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -4981,99 +5311,93 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag int name_size() const; void clear_name(); static const int kNameFieldNumber = 2; - ::google::protobuf::UninterpretedOption_NamePart* mutable_name(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart >* + PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart* mutable_name(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart >* mutable_name(); - const ::google::protobuf::UninterpretedOption_NamePart& name(int index) const; - ::google::protobuf::UninterpretedOption_NamePart* add_name(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart >& + const PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart& name(int index) const; + PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart* add_name(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart >& name() const; // optional string identifier_value = 3; bool has_identifier_value() const; void clear_identifier_value(); static const int kIdentifierValueFieldNumber = 3; - const ::std::string& identifier_value() const; - void set_identifier_value(const ::std::string& value); - #if LANG_CXX11 - void set_identifier_value(::std::string&& value); - #endif + const std::string& identifier_value() const; + void set_identifier_value(const std::string& value); + void set_identifier_value(std::string&& value); void set_identifier_value(const char* value); void set_identifier_value(const char* value, size_t size); - ::std::string* mutable_identifier_value(); - ::std::string* release_identifier_value(); - void set_allocated_identifier_value(::std::string* identifier_value); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_identifier_value(); + std::string* release_identifier_value(); + void set_allocated_identifier_value(std::string* identifier_value); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_identifier_value(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_identifier_value(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_identifier_value( - ::std::string* identifier_value); + std::string* identifier_value); // optional bytes string_value = 7; bool has_string_value() const; void clear_string_value(); static const int kStringValueFieldNumber = 7; - const ::std::string& string_value() const; - void set_string_value(const ::std::string& value); - #if LANG_CXX11 - void set_string_value(::std::string&& value); - #endif + const std::string& string_value() const; + void set_string_value(const std::string& value); + void set_string_value(std::string&& value); void set_string_value(const char* value); void set_string_value(const void* value, size_t size); - ::std::string* mutable_string_value(); - ::std::string* release_string_value(); - void set_allocated_string_value(::std::string* string_value); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_string_value(); + std::string* release_string_value(); + void set_allocated_string_value(std::string* string_value); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_string_value(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_string_value(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_string_value( - ::std::string* string_value); + std::string* string_value); // optional string aggregate_value = 8; bool has_aggregate_value() const; void clear_aggregate_value(); static const int kAggregateValueFieldNumber = 8; - const ::std::string& aggregate_value() const; - void set_aggregate_value(const ::std::string& value); - #if LANG_CXX11 - void set_aggregate_value(::std::string&& value); - #endif + const std::string& aggregate_value() const; + void set_aggregate_value(const std::string& value); + void set_aggregate_value(std::string&& value); void set_aggregate_value(const char* value); void set_aggregate_value(const char* value, size_t size); - ::std::string* mutable_aggregate_value(); - ::std::string* release_aggregate_value(); - void set_allocated_aggregate_value(::std::string* aggregate_value); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_aggregate_value(); + std::string* release_aggregate_value(); + void set_allocated_aggregate_value(std::string* aggregate_value); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_aggregate_value(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_aggregate_value(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_aggregate_value( - ::std::string* aggregate_value); + std::string* aggregate_value); // optional uint64 positive_int_value = 4; bool has_positive_int_value() const; void clear_positive_int_value(); static const int kPositiveIntValueFieldNumber = 4; - ::google::protobuf::uint64 positive_int_value() const; - void set_positive_int_value(::google::protobuf::uint64 value); + ::PROTOBUF_NAMESPACE_ID::uint64 positive_int_value() const; + void set_positive_int_value(::PROTOBUF_NAMESPACE_ID::uint64 value); // optional int64 negative_int_value = 5; bool has_negative_int_value() const; void clear_negative_int_value(); static const int kNegativeIntValueFieldNumber = 5; - ::google::protobuf::int64 negative_int_value() const; - void set_negative_int_value(::google::protobuf::int64 value); + ::PROTOBUF_NAMESPACE_ID::int64 negative_int_value() const; + void set_negative_int_value(::PROTOBUF_NAMESPACE_ID::int64 value); // optional double double_value = 6; bool has_double_value() const; @@ -5084,53 +5408,41 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag // @@protoc_insertion_point(class_scope:google.protobuf.UninterpretedOption) private: - void set_has_identifier_value(); - void clear_has_identifier_value(); - void set_has_positive_int_value(); - void clear_has_positive_int_value(); - void set_has_negative_int_value(); - void clear_has_negative_int_value(); - void set_has_double_value(); - void clear_has_double_value(); - void set_has_string_value(); - void clear_has_string_value(); - void set_has_aggregate_value(); - void clear_has_aggregate_value(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart > name_; - ::google::protobuf::internal::ArenaStringPtr identifier_value_; - ::google::protobuf::internal::ArenaStringPtr string_value_; - ::google::protobuf::internal::ArenaStringPtr aggregate_value_; - ::google::protobuf::uint64 positive_int_value_; - ::google::protobuf::int64 negative_int_value_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart > name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr identifier_value_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr string_value_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr aggregate_value_; + ::PROTOBUF_NAMESPACE_ID::uint64 positive_int_value_; + ::PROTOBUF_NAMESPACE_ID::int64 negative_int_value_; double double_value_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceCodeInfo.Location) */ { +class PROTOBUF_EXPORT SourceCodeInfo_Location : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceCodeInfo.Location) */ { public: SourceCodeInfo_Location(); virtual ~SourceCodeInfo_Location(); SourceCodeInfo_Location(const SourceCodeInfo_Location& from); - - inline SourceCodeInfo_Location& operator=(const SourceCodeInfo_Location& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 SourceCodeInfo_Location(SourceCodeInfo_Location&& from) noexcept : SourceCodeInfo_Location() { *this = ::std::move(from); } + inline SourceCodeInfo_Location& operator=(const SourceCodeInfo_Location& from) { + CopyFrom(from); + return *this; + } inline SourceCodeInfo_Location& operator=(SourceCodeInfo_Location&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -5139,21 +5451,29 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const SourceCodeInfo_Location& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -5173,40 +5493,48 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me // implements Message ---------------------------------------------- inline SourceCodeInfo_Location* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - SourceCodeInfo_Location* New(::google::protobuf::Arena* arena) const final { + SourceCodeInfo_Location* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const SourceCodeInfo_Location& from); void MergeFrom(const SourceCodeInfo_Location& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(SourceCodeInfo_Location* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.SourceCodeInfo.Location"; + } protected: - explicit SourceCodeInfo_Location(::google::protobuf::Arena* arena); + explicit SourceCodeInfo_Location(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -5214,7 +5542,14 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -5224,137 +5559,125 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me int path_size() const; void clear_path(); static const int kPathFieldNumber = 1; - ::google::protobuf::int32 path(int index) const; - void set_path(int index, ::google::protobuf::int32 value); - void add_path(::google::protobuf::int32 value); - const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& + ::PROTOBUF_NAMESPACE_ID::int32 path(int index) const; + void set_path(int index, ::PROTOBUF_NAMESPACE_ID::int32 value); + void add_path(::PROTOBUF_NAMESPACE_ID::int32 value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >& path() const; - ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* + ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >* mutable_path(); // repeated int32 span = 2 [packed = true]; int span_size() const; void clear_span(); static const int kSpanFieldNumber = 2; - ::google::protobuf::int32 span(int index) const; - void set_span(int index, ::google::protobuf::int32 value); - void add_span(::google::protobuf::int32 value); - const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& + ::PROTOBUF_NAMESPACE_ID::int32 span(int index) const; + void set_span(int index, ::PROTOBUF_NAMESPACE_ID::int32 value); + void add_span(::PROTOBUF_NAMESPACE_ID::int32 value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >& span() const; - ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* + ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >* mutable_span(); // repeated string leading_detached_comments = 6; int leading_detached_comments_size() const; void clear_leading_detached_comments(); static const int kLeadingDetachedCommentsFieldNumber = 6; - const ::std::string& leading_detached_comments(int index) const; - ::std::string* mutable_leading_detached_comments(int index); - void set_leading_detached_comments(int index, const ::std::string& value); - #if LANG_CXX11 - void set_leading_detached_comments(int index, ::std::string&& value); - #endif + const std::string& leading_detached_comments(int index) const; + std::string* mutable_leading_detached_comments(int index); + void set_leading_detached_comments(int index, const std::string& value); + void set_leading_detached_comments(int index, std::string&& value); void set_leading_detached_comments(int index, const char* value); void set_leading_detached_comments(int index, const char* value, size_t size); - ::std::string* add_leading_detached_comments(); - void add_leading_detached_comments(const ::std::string& value); - #if LANG_CXX11 - void add_leading_detached_comments(::std::string&& value); - #endif + std::string* add_leading_detached_comments(); + void add_leading_detached_comments(const std::string& value); + void add_leading_detached_comments(std::string&& value); void add_leading_detached_comments(const char* value); void add_leading_detached_comments(const char* value, size_t size); - const ::google::protobuf::RepeatedPtrField< ::std::string>& leading_detached_comments() const; - ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_leading_detached_comments(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& leading_detached_comments() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* mutable_leading_detached_comments(); // optional string leading_comments = 3; bool has_leading_comments() const; void clear_leading_comments(); static const int kLeadingCommentsFieldNumber = 3; - const ::std::string& leading_comments() const; - void set_leading_comments(const ::std::string& value); - #if LANG_CXX11 - void set_leading_comments(::std::string&& value); - #endif + const std::string& leading_comments() const; + void set_leading_comments(const std::string& value); + void set_leading_comments(std::string&& value); void set_leading_comments(const char* value); void set_leading_comments(const char* value, size_t size); - ::std::string* mutable_leading_comments(); - ::std::string* release_leading_comments(); - void set_allocated_leading_comments(::std::string* leading_comments); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_leading_comments(); + std::string* release_leading_comments(); + void set_allocated_leading_comments(std::string* leading_comments); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_leading_comments(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_leading_comments(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_leading_comments( - ::std::string* leading_comments); + std::string* leading_comments); // optional string trailing_comments = 4; bool has_trailing_comments() const; void clear_trailing_comments(); static const int kTrailingCommentsFieldNumber = 4; - const ::std::string& trailing_comments() const; - void set_trailing_comments(const ::std::string& value); - #if LANG_CXX11 - void set_trailing_comments(::std::string&& value); - #endif + const std::string& trailing_comments() const; + void set_trailing_comments(const std::string& value); + void set_trailing_comments(std::string&& value); void set_trailing_comments(const char* value); void set_trailing_comments(const char* value, size_t size); - ::std::string* mutable_trailing_comments(); - ::std::string* release_trailing_comments(); - void set_allocated_trailing_comments(::std::string* trailing_comments); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_trailing_comments(); + std::string* release_trailing_comments(); + void set_allocated_trailing_comments(std::string* trailing_comments); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_trailing_comments(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_trailing_comments(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_trailing_comments( - ::std::string* trailing_comments); + std::string* trailing_comments); // @@protoc_insertion_point(class_scope:google.protobuf.SourceCodeInfo.Location) private: - void set_has_leading_comments(); - void clear_has_leading_comments(); - void set_has_trailing_comments(); - void clear_has_trailing_comments(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedField< ::google::protobuf::int32 > path_; - mutable int _path_cached_byte_size_; - ::google::protobuf::RepeatedField< ::google::protobuf::int32 > span_; - mutable int _span_cached_byte_size_; - ::google::protobuf::RepeatedPtrField< ::std::string> leading_detached_comments_; - ::google::protobuf::internal::ArenaStringPtr leading_comments_; - ::google::protobuf::internal::ArenaStringPtr trailing_comments_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 > path_; + mutable std::atomic _path_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 > span_; + mutable std::atomic _span_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField leading_detached_comments_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr leading_comments_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr trailing_comments_; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceCodeInfo) */ { +class PROTOBUF_EXPORT SourceCodeInfo : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceCodeInfo) */ { public: SourceCodeInfo(); virtual ~SourceCodeInfo(); SourceCodeInfo(const SourceCodeInfo& from); - - inline SourceCodeInfo& operator=(const SourceCodeInfo& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 SourceCodeInfo(SourceCodeInfo&& from) noexcept : SourceCodeInfo() { *this = ::std::move(from); } + inline SourceCodeInfo& operator=(const SourceCodeInfo& from) { + CopyFrom(from); + return *this; + } inline SourceCodeInfo& operator=(SourceCodeInfo&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -5363,21 +5686,29 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const SourceCodeInfo& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -5397,40 +5728,48 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* // implements Message ---------------------------------------------- inline SourceCodeInfo* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - SourceCodeInfo* New(::google::protobuf::Arena* arena) const final { + SourceCodeInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const SourceCodeInfo& from); void MergeFrom(const SourceCodeInfo& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(SourceCodeInfo* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.SourceCodeInfo"; + } protected: - explicit SourceCodeInfo(::google::protobuf::Arena* arena); + explicit SourceCodeInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -5438,7 +5777,14 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -5450,45 +5796,45 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* int location_size() const; void clear_location(); static const int kLocationFieldNumber = 1; - ::google::protobuf::SourceCodeInfo_Location* mutable_location(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceCodeInfo_Location >* + PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location* mutable_location(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location >* mutable_location(); - const ::google::protobuf::SourceCodeInfo_Location& location(int index) const; - ::google::protobuf::SourceCodeInfo_Location* add_location(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceCodeInfo_Location >& + const PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location& location(int index) const; + PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location* add_location(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location >& location() const; // @@protoc_insertion_point(class_scope:google.protobuf.SourceCodeInfo) private: + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceCodeInfo_Location > location_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location > location_; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.GeneratedCodeInfo.Annotation) */ { +class PROTOBUF_EXPORT GeneratedCodeInfo_Annotation : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.GeneratedCodeInfo.Annotation) */ { public: GeneratedCodeInfo_Annotation(); virtual ~GeneratedCodeInfo_Annotation(); GeneratedCodeInfo_Annotation(const GeneratedCodeInfo_Annotation& from); - - inline GeneratedCodeInfo_Annotation& operator=(const GeneratedCodeInfo_Annotation& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 GeneratedCodeInfo_Annotation(GeneratedCodeInfo_Annotation&& from) noexcept : GeneratedCodeInfo_Annotation() { *this = ::std::move(from); } + inline GeneratedCodeInfo_Annotation& operator=(const GeneratedCodeInfo_Annotation& from) { + CopyFrom(from); + return *this; + } inline GeneratedCodeInfo_Annotation& operator=(GeneratedCodeInfo_Annotation&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -5497,21 +5843,29 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const GeneratedCodeInfo_Annotation& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -5531,40 +5885,48 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu // implements Message ---------------------------------------------- inline GeneratedCodeInfo_Annotation* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - GeneratedCodeInfo_Annotation* New(::google::protobuf::Arena* arena) const final { + GeneratedCodeInfo_Annotation* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const GeneratedCodeInfo_Annotation& from); void MergeFrom(const GeneratedCodeInfo_Annotation& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(GeneratedCodeInfo_Annotation* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.GeneratedCodeInfo.Annotation"; + } protected: - explicit GeneratedCodeInfo_Annotation(::google::protobuf::Arena* arena); + explicit GeneratedCodeInfo_Annotation(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -5572,7 +5934,14 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -5582,93 +5951,85 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu int path_size() const; void clear_path(); static const int kPathFieldNumber = 1; - ::google::protobuf::int32 path(int index) const; - void set_path(int index, ::google::protobuf::int32 value); - void add_path(::google::protobuf::int32 value); - const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& + ::PROTOBUF_NAMESPACE_ID::int32 path(int index) const; + void set_path(int index, ::PROTOBUF_NAMESPACE_ID::int32 value); + void add_path(::PROTOBUF_NAMESPACE_ID::int32 value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >& path() const; - ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* + ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >* mutable_path(); // optional string source_file = 2; bool has_source_file() const; void clear_source_file(); static const int kSourceFileFieldNumber = 2; - const ::std::string& source_file() const; - void set_source_file(const ::std::string& value); - #if LANG_CXX11 - void set_source_file(::std::string&& value); - #endif + const std::string& source_file() const; + void set_source_file(const std::string& value); + void set_source_file(std::string&& value); void set_source_file(const char* value); void set_source_file(const char* value, size_t size); - ::std::string* mutable_source_file(); - ::std::string* release_source_file(); - void set_allocated_source_file(::std::string* source_file); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_source_file(); + std::string* release_source_file(); + void set_allocated_source_file(std::string* source_file); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_source_file(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_source_file(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_source_file( - ::std::string* source_file); + std::string* source_file); // optional int32 begin = 3; bool has_begin() const; void clear_begin(); static const int kBeginFieldNumber = 3; - ::google::protobuf::int32 begin() const; - void set_begin(::google::protobuf::int32 value); + ::PROTOBUF_NAMESPACE_ID::int32 begin() const; + void set_begin(::PROTOBUF_NAMESPACE_ID::int32 value); // optional int32 end = 4; bool has_end() const; void clear_end(); static const int kEndFieldNumber = 4; - ::google::protobuf::int32 end() const; - void set_end(::google::protobuf::int32 value); + ::PROTOBUF_NAMESPACE_ID::int32 end() const; + void set_end(::PROTOBUF_NAMESPACE_ID::int32 value); // @@protoc_insertion_point(class_scope:google.protobuf.GeneratedCodeInfo.Annotation) private: - void set_has_source_file(); - void clear_has_source_file(); - void set_has_begin(); - void clear_has_begin(); - void set_has_end(); - void clear_has_end(); + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedField< ::google::protobuf::int32 > path_; - mutable int _path_cached_byte_size_; - ::google::protobuf::internal::ArenaStringPtr source_file_; - ::google::protobuf::int32 begin_; - ::google::protobuf::int32 end_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 > path_; + mutable std::atomic _path_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr source_file_; + ::PROTOBUF_NAMESPACE_ID::int32 begin_; + ::PROTOBUF_NAMESPACE_ID::int32 end_; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.GeneratedCodeInfo) */ { +class PROTOBUF_EXPORT GeneratedCodeInfo : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.GeneratedCodeInfo) */ { public: GeneratedCodeInfo(); virtual ~GeneratedCodeInfo(); GeneratedCodeInfo(const GeneratedCodeInfo& from); - - inline GeneratedCodeInfo& operator=(const GeneratedCodeInfo& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 GeneratedCodeInfo(GeneratedCodeInfo&& from) noexcept : GeneratedCodeInfo() { *this = ::std::move(from); } + inline GeneratedCodeInfo& operator=(const GeneratedCodeInfo& from) { + CopyFrom(from); + return *this; + } inline GeneratedCodeInfo& operator=(GeneratedCodeInfo&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -5677,21 +6038,29 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const final { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const GeneratedCodeInfo& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -5711,40 +6080,48 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message // implements Message ---------------------------------------------- inline GeneratedCodeInfo* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - GeneratedCodeInfo* New(::google::protobuf::Arena* arena) const final { + GeneratedCodeInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const GeneratedCodeInfo& from); void MergeFrom(const GeneratedCodeInfo& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(GeneratedCodeInfo* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.GeneratedCodeInfo"; + } protected: - explicit GeneratedCodeInfo(::google::protobuf::Arena* arena); + explicit GeneratedCodeInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -5752,7 +6129,14 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto); + return ::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -5764,25 +6148,26 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message int annotation_size() const; void clear_annotation(); static const int kAnnotationFieldNumber = 1; - ::google::protobuf::GeneratedCodeInfo_Annotation* mutable_annotation(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::GeneratedCodeInfo_Annotation >* + PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation* mutable_annotation(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation >* mutable_annotation(); - const ::google::protobuf::GeneratedCodeInfo_Annotation& annotation(int index) const; - ::google::protobuf::GeneratedCodeInfo_Annotation* add_annotation(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::GeneratedCodeInfo_Annotation >& + const PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation& annotation(int index) const; + PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation* add_annotation(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation >& annotation() const; // @@protoc_insertion_point(class_scope:google.protobuf.GeneratedCodeInfo) private: + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::GeneratedCodeInfo_Annotation > annotation_; - friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation > annotation_; + friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // =================================================================== @@ -5802,24 +6187,24 @@ inline int FileDescriptorSet::file_size() const { inline void FileDescriptorSet::clear_file() { file_.Clear(); } -inline ::google::protobuf::FileDescriptorProto* FileDescriptorSet::mutable_file(int index) { +inline PROTOBUF_NAMESPACE_ID::FileDescriptorProto* FileDescriptorSet::mutable_file(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorSet.file) return file_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FileDescriptorProto >* FileDescriptorSet::mutable_file() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorSet.file) return &file_; } -inline const ::google::protobuf::FileDescriptorProto& FileDescriptorSet::file(int index) const { +inline const PROTOBUF_NAMESPACE_ID::FileDescriptorProto& FileDescriptorSet::file(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorSet.file) return file_.Get(index); } -inline ::google::protobuf::FileDescriptorProto* FileDescriptorSet::add_file() { +inline PROTOBUF_NAMESPACE_ID::FileDescriptorProto* FileDescriptorSet::add_file() { // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorSet.file) return file_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FileDescriptorProto >& FileDescriptorSet::file() const { // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorSet.file) return file_; @@ -5833,86 +6218,78 @@ FileDescriptorSet::file() const { inline bool FileDescriptorProto::has_name() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void FileDescriptorProto::set_has_name() { - _has_bits_[0] |= 0x00000001u; -} -inline void FileDescriptorProto::clear_has_name() { +inline void FileDescriptorProto::clear_name() { + name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000001u; } -inline void FileDescriptorProto::clear_name() { - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_name(); -} -inline const ::std::string& FileDescriptorProto::name() const { +inline const std::string& FileDescriptorProto::name() const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.name) return name_.Get(); } -inline void FileDescriptorProto::set_name(const ::std::string& value) { - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FileDescriptorProto::set_name(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.name) } -#if LANG_CXX11 -inline void FileDescriptorProto::set_name(::std::string&& value) { - set_has_name(); +inline void FileDescriptorProto::set_name(std::string&& value) { + _has_bits_[0] |= 0x00000001u; name_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileDescriptorProto.name) } -#endif inline void FileDescriptorProto::set_name(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.name) } inline void FileDescriptorProto::set_name(const char* value, size_t size) { - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.name) } -inline ::std::string* FileDescriptorProto::mutable_name() { - set_has_name(); +inline std::string* FileDescriptorProto::mutable_name() { + _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.name) - return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FileDescriptorProto::release_name() { +inline std::string* FileDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.name) if (!has_name()) { - return NULL; + return nullptr; } - clear_has_name(); - return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000001u; + return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FileDescriptorProto::set_allocated_name(::std::string* name) { - if (name != NULL) { - set_has_name(); +inline void FileDescriptorProto::set_allocated_name(std::string* name) { + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name, + name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.name) } -inline ::std::string* FileDescriptorProto::unsafe_arena_release_name() { +inline std::string* FileDescriptorProto::unsafe_arena_release_name() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileDescriptorProto.name) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_name(); - return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000001u; + return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileDescriptorProto::unsafe_arena_set_allocated_name( - ::std::string* name) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (name != NULL) { - set_has_name(); + std::string* name) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.name) } @@ -5921,86 +6298,78 @@ inline void FileDescriptorProto::unsafe_arena_set_allocated_name( inline bool FileDescriptorProto::has_package() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void FileDescriptorProto::set_has_package() { - _has_bits_[0] |= 0x00000002u; -} -inline void FileDescriptorProto::clear_has_package() { +inline void FileDescriptorProto::clear_package() { + package_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000002u; } -inline void FileDescriptorProto::clear_package() { - package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_package(); -} -inline const ::std::string& FileDescriptorProto::package() const { +inline const std::string& FileDescriptorProto::package() const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.package) return package_.Get(); } -inline void FileDescriptorProto::set_package(const ::std::string& value) { - set_has_package(); - package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FileDescriptorProto::set_package(const std::string& value) { + _has_bits_[0] |= 0x00000002u; + package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.package) } -#if LANG_CXX11 -inline void FileDescriptorProto::set_package(::std::string&& value) { - set_has_package(); +inline void FileDescriptorProto::set_package(std::string&& value) { + _has_bits_[0] |= 0x00000002u; package_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileDescriptorProto.package) } -#endif inline void FileDescriptorProto::set_package(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_package(); - package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000002u; + package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.package) } inline void FileDescriptorProto::set_package(const char* value, size_t size) { - set_has_package(); - package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000002u; + package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.package) } -inline ::std::string* FileDescriptorProto::mutable_package() { - set_has_package(); +inline std::string* FileDescriptorProto::mutable_package() { + _has_bits_[0] |= 0x00000002u; // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.package) - return package_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return package_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FileDescriptorProto::release_package() { +inline std::string* FileDescriptorProto::release_package() { // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.package) if (!has_package()) { - return NULL; + return nullptr; } - clear_has_package(); - return package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000002u; + return package_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FileDescriptorProto::set_allocated_package(::std::string* package) { - if (package != NULL) { - set_has_package(); +inline void FileDescriptorProto::set_allocated_package(std::string* package) { + if (package != nullptr) { + _has_bits_[0] |= 0x00000002u; } else { - clear_has_package(); + _has_bits_[0] &= ~0x00000002u; } - package_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), package, + package_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), package, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.package) } -inline ::std::string* FileDescriptorProto::unsafe_arena_release_package() { +inline std::string* FileDescriptorProto::unsafe_arena_release_package() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileDescriptorProto.package) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_package(); - return package_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000002u; + return package_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileDescriptorProto::unsafe_arena_set_allocated_package( - ::std::string* package) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (package != NULL) { - set_has_package(); + std::string* package) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (package != nullptr) { + _has_bits_[0] |= 0x00000002u; } else { - clear_has_package(); + _has_bits_[0] &= ~0x00000002u; } - package_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + package_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), package, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.package) } @@ -6012,26 +6381,24 @@ inline int FileDescriptorProto::dependency_size() const { inline void FileDescriptorProto::clear_dependency() { dependency_.Clear(); } -inline const ::std::string& FileDescriptorProto::dependency(int index) const { +inline const std::string& FileDescriptorProto::dependency(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.dependency) return dependency_.Get(index); } -inline ::std::string* FileDescriptorProto::mutable_dependency(int index) { +inline std::string* FileDescriptorProto::mutable_dependency(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.dependency) return dependency_.Mutable(index); } -inline void FileDescriptorProto::set_dependency(int index, const ::std::string& value) { +inline void FileDescriptorProto::set_dependency(int index, const std::string& value) { // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.dependency) dependency_.Mutable(index)->assign(value); } -#if LANG_CXX11 -inline void FileDescriptorProto::set_dependency(int index, ::std::string&& value) { +inline void FileDescriptorProto::set_dependency(int index, std::string&& value) { // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.dependency) dependency_.Mutable(index)->assign(std::move(value)); } -#endif inline void FileDescriptorProto::set_dependency(int index, const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); dependency_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.dependency) } @@ -6040,22 +6407,20 @@ inline void FileDescriptorProto::set_dependency(int index, const char* value, si reinterpret_cast(value), size); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.dependency) } -inline ::std::string* FileDescriptorProto::add_dependency() { +inline std::string* FileDescriptorProto::add_dependency() { // @@protoc_insertion_point(field_add_mutable:google.protobuf.FileDescriptorProto.dependency) return dependency_.Add(); } -inline void FileDescriptorProto::add_dependency(const ::std::string& value) { +inline void FileDescriptorProto::add_dependency(const std::string& value) { dependency_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.dependency) } -#if LANG_CXX11 -inline void FileDescriptorProto::add_dependency(::std::string&& value) { +inline void FileDescriptorProto::add_dependency(std::string&& value) { dependency_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.dependency) } -#endif inline void FileDescriptorProto::add_dependency(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); dependency_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.protobuf.FileDescriptorProto.dependency) } @@ -6063,12 +6428,12 @@ inline void FileDescriptorProto::add_dependency(const char* value, size_t size) dependency_.Add()->assign(reinterpret_cast(value), size); // @@protoc_insertion_point(field_add_pointer:google.protobuf.FileDescriptorProto.dependency) } -inline const ::google::protobuf::RepeatedPtrField< ::std::string>& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& FileDescriptorProto::dependency() const { // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.dependency) return dependency_; } -inline ::google::protobuf::RepeatedPtrField< ::std::string>* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* FileDescriptorProto::mutable_dependency() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.dependency) return &dependency_; @@ -6081,24 +6446,24 @@ inline int FileDescriptorProto::public_dependency_size() const { inline void FileDescriptorProto::clear_public_dependency() { public_dependency_.Clear(); } -inline ::google::protobuf::int32 FileDescriptorProto::public_dependency(int index) const { +inline ::PROTOBUF_NAMESPACE_ID::int32 FileDescriptorProto::public_dependency(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.public_dependency) return public_dependency_.Get(index); } -inline void FileDescriptorProto::set_public_dependency(int index, ::google::protobuf::int32 value) { +inline void FileDescriptorProto::set_public_dependency(int index, ::PROTOBUF_NAMESPACE_ID::int32 value) { public_dependency_.Set(index, value); // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.public_dependency) } -inline void FileDescriptorProto::add_public_dependency(::google::protobuf::int32 value) { +inline void FileDescriptorProto::add_public_dependency(::PROTOBUF_NAMESPACE_ID::int32 value) { public_dependency_.Add(value); // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.public_dependency) } -inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >& FileDescriptorProto::public_dependency() const { // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.public_dependency) return public_dependency_; } -inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >* FileDescriptorProto::mutable_public_dependency() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.public_dependency) return &public_dependency_; @@ -6111,24 +6476,24 @@ inline int FileDescriptorProto::weak_dependency_size() const { inline void FileDescriptorProto::clear_weak_dependency() { weak_dependency_.Clear(); } -inline ::google::protobuf::int32 FileDescriptorProto::weak_dependency(int index) const { +inline ::PROTOBUF_NAMESPACE_ID::int32 FileDescriptorProto::weak_dependency(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.weak_dependency) return weak_dependency_.Get(index); } -inline void FileDescriptorProto::set_weak_dependency(int index, ::google::protobuf::int32 value) { +inline void FileDescriptorProto::set_weak_dependency(int index, ::PROTOBUF_NAMESPACE_ID::int32 value) { weak_dependency_.Set(index, value); // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.weak_dependency) } -inline void FileDescriptorProto::add_weak_dependency(::google::protobuf::int32 value) { +inline void FileDescriptorProto::add_weak_dependency(::PROTOBUF_NAMESPACE_ID::int32 value) { weak_dependency_.Add(value); // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.weak_dependency) } -inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >& FileDescriptorProto::weak_dependency() const { // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.weak_dependency) return weak_dependency_; } -inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >* FileDescriptorProto::mutable_weak_dependency() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.weak_dependency) return &weak_dependency_; @@ -6141,24 +6506,24 @@ inline int FileDescriptorProto::message_type_size() const { inline void FileDescriptorProto::clear_message_type() { message_type_.Clear(); } -inline ::google::protobuf::DescriptorProto* FileDescriptorProto::mutable_message_type(int index) { +inline PROTOBUF_NAMESPACE_ID::DescriptorProto* FileDescriptorProto::mutable_message_type(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.message_type) return message_type_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto >* FileDescriptorProto::mutable_message_type() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.message_type) return &message_type_; } -inline const ::google::protobuf::DescriptorProto& FileDescriptorProto::message_type(int index) const { +inline const PROTOBUF_NAMESPACE_ID::DescriptorProto& FileDescriptorProto::message_type(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.message_type) return message_type_.Get(index); } -inline ::google::protobuf::DescriptorProto* FileDescriptorProto::add_message_type() { +inline PROTOBUF_NAMESPACE_ID::DescriptorProto* FileDescriptorProto::add_message_type() { // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.message_type) return message_type_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto >& FileDescriptorProto::message_type() const { // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.message_type) return message_type_; @@ -6171,24 +6536,24 @@ inline int FileDescriptorProto::enum_type_size() const { inline void FileDescriptorProto::clear_enum_type() { enum_type_.Clear(); } -inline ::google::protobuf::EnumDescriptorProto* FileDescriptorProto::mutable_enum_type(int index) { +inline PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* FileDescriptorProto::mutable_enum_type(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.enum_type) return enum_type_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto >* FileDescriptorProto::mutable_enum_type() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.enum_type) return &enum_type_; } -inline const ::google::protobuf::EnumDescriptorProto& FileDescriptorProto::enum_type(int index) const { +inline const PROTOBUF_NAMESPACE_ID::EnumDescriptorProto& FileDescriptorProto::enum_type(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.enum_type) return enum_type_.Get(index); } -inline ::google::protobuf::EnumDescriptorProto* FileDescriptorProto::add_enum_type() { +inline PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* FileDescriptorProto::add_enum_type() { // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.enum_type) return enum_type_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto >& FileDescriptorProto::enum_type() const { // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.enum_type) return enum_type_; @@ -6201,24 +6566,24 @@ inline int FileDescriptorProto::service_size() const { inline void FileDescriptorProto::clear_service() { service_.Clear(); } -inline ::google::protobuf::ServiceDescriptorProto* FileDescriptorProto::mutable_service(int index) { +inline PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto* FileDescriptorProto::mutable_service(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.service) return service_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto >* FileDescriptorProto::mutable_service() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.service) return &service_; } -inline const ::google::protobuf::ServiceDescriptorProto& FileDescriptorProto::service(int index) const { +inline const PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto& FileDescriptorProto::service(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.service) return service_.Get(index); } -inline ::google::protobuf::ServiceDescriptorProto* FileDescriptorProto::add_service() { +inline PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto* FileDescriptorProto::add_service() { // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.service) return service_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto >& FileDescriptorProto::service() const { // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.service) return service_; @@ -6231,24 +6596,24 @@ inline int FileDescriptorProto::extension_size() const { inline void FileDescriptorProto::clear_extension() { extension_.Clear(); } -inline ::google::protobuf::FieldDescriptorProto* FileDescriptorProto::mutable_extension(int index) { +inline PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* FileDescriptorProto::mutable_extension(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.extension) return extension_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >* FileDescriptorProto::mutable_extension() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.extension) return &extension_; } -inline const ::google::protobuf::FieldDescriptorProto& FileDescriptorProto::extension(int index) const { +inline const PROTOBUF_NAMESPACE_ID::FieldDescriptorProto& FileDescriptorProto::extension(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.extension) return extension_.Get(index); } -inline ::google::protobuf::FieldDescriptorProto* FileDescriptorProto::add_extension() { +inline PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* FileDescriptorProto::add_extension() { // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.extension) return extension_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >& FileDescriptorProto::extension() const { // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.extension) return extension_; @@ -6258,66 +6623,57 @@ FileDescriptorProto::extension() const { inline bool FileDescriptorProto::has_options() const { return (_has_bits_[0] & 0x00000008u) != 0; } -inline void FileDescriptorProto::set_has_options() { - _has_bits_[0] |= 0x00000008u; -} -inline void FileDescriptorProto::clear_has_options() { +inline void FileDescriptorProto::clear_options() { + if (options_ != nullptr) options_->Clear(); _has_bits_[0] &= ~0x00000008u; } -inline void FileDescriptorProto::clear_options() { - if (options_ != NULL) options_->Clear(); - clear_has_options(); -} -inline const ::google::protobuf::FileOptions& FileDescriptorProto::_internal_options() const { - return *options_; -} -inline const ::google::protobuf::FileOptions& FileDescriptorProto::options() const { - const ::google::protobuf::FileOptions* p = options_; +inline const PROTOBUF_NAMESPACE_ID::FileOptions& FileDescriptorProto::options() const { + const PROTOBUF_NAMESPACE_ID::FileOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.options) - return p != NULL ? *p : *reinterpret_cast( - &::google::protobuf::_FileOptions_default_instance_); + return p != nullptr ? *p : *reinterpret_cast( + &PROTOBUF_NAMESPACE_ID::_FileOptions_default_instance_); } -inline ::google::protobuf::FileOptions* FileDescriptorProto::release_options() { +inline PROTOBUF_NAMESPACE_ID::FileOptions* FileDescriptorProto::release_options() { // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.options) - clear_has_options(); - ::google::protobuf::FileOptions* temp = options_; - if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); + _has_bits_[0] &= ~0x00000008u; + PROTOBUF_NAMESPACE_ID::FileOptions* temp = options_; + if (GetArenaNoVirtual() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } - options_ = NULL; + options_ = nullptr; return temp; } -inline ::google::protobuf::FileOptions* FileDescriptorProto::unsafe_arena_release_options() { +inline PROTOBUF_NAMESPACE_ID::FileOptions* FileDescriptorProto::unsafe_arena_release_options() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileDescriptorProto.options) - clear_has_options(); - ::google::protobuf::FileOptions* temp = options_; - options_ = NULL; + _has_bits_[0] &= ~0x00000008u; + PROTOBUF_NAMESPACE_ID::FileOptions* temp = options_; + options_ = nullptr; return temp; } -inline ::google::protobuf::FileOptions* FileDescriptorProto::mutable_options() { - set_has_options(); - if (options_ == NULL) { - auto* p = CreateMaybeMessage<::google::protobuf::FileOptions>(GetArenaNoVirtual()); +inline PROTOBUF_NAMESPACE_ID::FileOptions* FileDescriptorProto::mutable_options() { + _has_bits_[0] |= 0x00000008u; + if (options_ == nullptr) { + auto* p = CreateMaybeMessage(GetArenaNoVirtual()); options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.options) return options_; } -inline void FileDescriptorProto::set_allocated_options(::google::protobuf::FileOptions* options) { - ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); - if (message_arena == NULL) { +inline void FileDescriptorProto::set_allocated_options(PROTOBUF_NAMESPACE_ID::FileOptions* options) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); + if (message_arena == nullptr) { delete options_; } if (options) { - ::google::protobuf::Arena* submessage_arena = - ::google::protobuf::Arena::GetArena(options); + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::GetArena(options); if (message_arena != submessage_arena) { - options = ::google::protobuf::internal::GetOwnedMessage( + options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - set_has_options(); + _has_bits_[0] |= 0x00000008u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000008u; } options_ = options; // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.options) @@ -6327,66 +6683,57 @@ inline void FileDescriptorProto::set_allocated_options(::google::protobuf::FileO inline bool FileDescriptorProto::has_source_code_info() const { return (_has_bits_[0] & 0x00000010u) != 0; } -inline void FileDescriptorProto::set_has_source_code_info() { - _has_bits_[0] |= 0x00000010u; -} -inline void FileDescriptorProto::clear_has_source_code_info() { +inline void FileDescriptorProto::clear_source_code_info() { + if (source_code_info_ != nullptr) source_code_info_->Clear(); _has_bits_[0] &= ~0x00000010u; } -inline void FileDescriptorProto::clear_source_code_info() { - if (source_code_info_ != NULL) source_code_info_->Clear(); - clear_has_source_code_info(); -} -inline const ::google::protobuf::SourceCodeInfo& FileDescriptorProto::_internal_source_code_info() const { - return *source_code_info_; -} -inline const ::google::protobuf::SourceCodeInfo& FileDescriptorProto::source_code_info() const { - const ::google::protobuf::SourceCodeInfo* p = source_code_info_; +inline const PROTOBUF_NAMESPACE_ID::SourceCodeInfo& FileDescriptorProto::source_code_info() const { + const PROTOBUF_NAMESPACE_ID::SourceCodeInfo* p = source_code_info_; // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.source_code_info) - return p != NULL ? *p : *reinterpret_cast( - &::google::protobuf::_SourceCodeInfo_default_instance_); + return p != nullptr ? *p : *reinterpret_cast( + &PROTOBUF_NAMESPACE_ID::_SourceCodeInfo_default_instance_); } -inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::release_source_code_info() { +inline PROTOBUF_NAMESPACE_ID::SourceCodeInfo* FileDescriptorProto::release_source_code_info() { // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.source_code_info) - clear_has_source_code_info(); - ::google::protobuf::SourceCodeInfo* temp = source_code_info_; - if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); + _has_bits_[0] &= ~0x00000010u; + PROTOBUF_NAMESPACE_ID::SourceCodeInfo* temp = source_code_info_; + if (GetArenaNoVirtual() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } - source_code_info_ = NULL; + source_code_info_ = nullptr; return temp; } -inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::unsafe_arena_release_source_code_info() { +inline PROTOBUF_NAMESPACE_ID::SourceCodeInfo* FileDescriptorProto::unsafe_arena_release_source_code_info() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileDescriptorProto.source_code_info) - clear_has_source_code_info(); - ::google::protobuf::SourceCodeInfo* temp = source_code_info_; - source_code_info_ = NULL; + _has_bits_[0] &= ~0x00000010u; + PROTOBUF_NAMESPACE_ID::SourceCodeInfo* temp = source_code_info_; + source_code_info_ = nullptr; return temp; } -inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::mutable_source_code_info() { - set_has_source_code_info(); - if (source_code_info_ == NULL) { - auto* p = CreateMaybeMessage<::google::protobuf::SourceCodeInfo>(GetArenaNoVirtual()); +inline PROTOBUF_NAMESPACE_ID::SourceCodeInfo* FileDescriptorProto::mutable_source_code_info() { + _has_bits_[0] |= 0x00000010u; + if (source_code_info_ == nullptr) { + auto* p = CreateMaybeMessage(GetArenaNoVirtual()); source_code_info_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.source_code_info) return source_code_info_; } -inline void FileDescriptorProto::set_allocated_source_code_info(::google::protobuf::SourceCodeInfo* source_code_info) { - ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); - if (message_arena == NULL) { +inline void FileDescriptorProto::set_allocated_source_code_info(PROTOBUF_NAMESPACE_ID::SourceCodeInfo* source_code_info) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); + if (message_arena == nullptr) { delete source_code_info_; } if (source_code_info) { - ::google::protobuf::Arena* submessage_arena = - ::google::protobuf::Arena::GetArena(source_code_info); + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::GetArena(source_code_info); if (message_arena != submessage_arena) { - source_code_info = ::google::protobuf::internal::GetOwnedMessage( + source_code_info = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, source_code_info, submessage_arena); } - set_has_source_code_info(); + _has_bits_[0] |= 0x00000010u; } else { - clear_has_source_code_info(); + _has_bits_[0] &= ~0x00000010u; } source_code_info_ = source_code_info; // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.source_code_info) @@ -6396,86 +6743,78 @@ inline void FileDescriptorProto::set_allocated_source_code_info(::google::protob inline bool FileDescriptorProto::has_syntax() const { return (_has_bits_[0] & 0x00000004u) != 0; } -inline void FileDescriptorProto::set_has_syntax() { - _has_bits_[0] |= 0x00000004u; -} -inline void FileDescriptorProto::clear_has_syntax() { +inline void FileDescriptorProto::clear_syntax() { + syntax_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000004u; } -inline void FileDescriptorProto::clear_syntax() { - syntax_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_syntax(); -} -inline const ::std::string& FileDescriptorProto::syntax() const { +inline const std::string& FileDescriptorProto::syntax() const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.syntax) return syntax_.Get(); } -inline void FileDescriptorProto::set_syntax(const ::std::string& value) { - set_has_syntax(); - syntax_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FileDescriptorProto::set_syntax(const std::string& value) { + _has_bits_[0] |= 0x00000004u; + syntax_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.syntax) } -#if LANG_CXX11 -inline void FileDescriptorProto::set_syntax(::std::string&& value) { - set_has_syntax(); +inline void FileDescriptorProto::set_syntax(std::string&& value) { + _has_bits_[0] |= 0x00000004u; syntax_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileDescriptorProto.syntax) } -#endif inline void FileDescriptorProto::set_syntax(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_syntax(); - syntax_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000004u; + syntax_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.syntax) } inline void FileDescriptorProto::set_syntax(const char* value, size_t size) { - set_has_syntax(); - syntax_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000004u; + syntax_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.syntax) } -inline ::std::string* FileDescriptorProto::mutable_syntax() { - set_has_syntax(); +inline std::string* FileDescriptorProto::mutable_syntax() { + _has_bits_[0] |= 0x00000004u; // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.syntax) - return syntax_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return syntax_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FileDescriptorProto::release_syntax() { +inline std::string* FileDescriptorProto::release_syntax() { // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.syntax) if (!has_syntax()) { - return NULL; + return nullptr; } - clear_has_syntax(); - return syntax_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000004u; + return syntax_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FileDescriptorProto::set_allocated_syntax(::std::string* syntax) { - if (syntax != NULL) { - set_has_syntax(); +inline void FileDescriptorProto::set_allocated_syntax(std::string* syntax) { + if (syntax != nullptr) { + _has_bits_[0] |= 0x00000004u; } else { - clear_has_syntax(); + _has_bits_[0] &= ~0x00000004u; } - syntax_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), syntax, + syntax_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), syntax, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.syntax) } -inline ::std::string* FileDescriptorProto::unsafe_arena_release_syntax() { +inline std::string* FileDescriptorProto::unsafe_arena_release_syntax() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileDescriptorProto.syntax) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_syntax(); - return syntax_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000004u; + return syntax_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileDescriptorProto::unsafe_arena_set_allocated_syntax( - ::std::string* syntax) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (syntax != NULL) { - set_has_syntax(); + std::string* syntax) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (syntax != nullptr) { + _has_bits_[0] |= 0x00000004u; } else { - clear_has_syntax(); + _has_bits_[0] &= ~0x00000004u; } - syntax_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + syntax_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), syntax, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.syntax) } @@ -6488,22 +6827,16 @@ inline void FileDescriptorProto::unsafe_arena_set_allocated_syntax( inline bool DescriptorProto_ExtensionRange::has_start() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void DescriptorProto_ExtensionRange::set_has_start() { - _has_bits_[0] |= 0x00000002u; -} -inline void DescriptorProto_ExtensionRange::clear_has_start() { - _has_bits_[0] &= ~0x00000002u; -} inline void DescriptorProto_ExtensionRange::clear_start() { start_ = 0; - clear_has_start(); + _has_bits_[0] &= ~0x00000002u; } -inline ::google::protobuf::int32 DescriptorProto_ExtensionRange::start() const { +inline ::PROTOBUF_NAMESPACE_ID::int32 DescriptorProto_ExtensionRange::start() const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ExtensionRange.start) return start_; } -inline void DescriptorProto_ExtensionRange::set_start(::google::protobuf::int32 value) { - set_has_start(); +inline void DescriptorProto_ExtensionRange::set_start(::PROTOBUF_NAMESPACE_ID::int32 value) { + _has_bits_[0] |= 0x00000002u; start_ = value; // @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ExtensionRange.start) } @@ -6512,22 +6845,16 @@ inline void DescriptorProto_ExtensionRange::set_start(::google::protobuf::int32 inline bool DescriptorProto_ExtensionRange::has_end() const { return (_has_bits_[0] & 0x00000004u) != 0; } -inline void DescriptorProto_ExtensionRange::set_has_end() { - _has_bits_[0] |= 0x00000004u; -} -inline void DescriptorProto_ExtensionRange::clear_has_end() { - _has_bits_[0] &= ~0x00000004u; -} inline void DescriptorProto_ExtensionRange::clear_end() { end_ = 0; - clear_has_end(); + _has_bits_[0] &= ~0x00000004u; } -inline ::google::protobuf::int32 DescriptorProto_ExtensionRange::end() const { +inline ::PROTOBUF_NAMESPACE_ID::int32 DescriptorProto_ExtensionRange::end() const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ExtensionRange.end) return end_; } -inline void DescriptorProto_ExtensionRange::set_end(::google::protobuf::int32 value) { - set_has_end(); +inline void DescriptorProto_ExtensionRange::set_end(::PROTOBUF_NAMESPACE_ID::int32 value) { + _has_bits_[0] |= 0x00000004u; end_ = value; // @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ExtensionRange.end) } @@ -6536,66 +6863,57 @@ inline void DescriptorProto_ExtensionRange::set_end(::google::protobuf::int32 va inline bool DescriptorProto_ExtensionRange::has_options() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void DescriptorProto_ExtensionRange::set_has_options() { - _has_bits_[0] |= 0x00000001u; -} -inline void DescriptorProto_ExtensionRange::clear_has_options() { +inline void DescriptorProto_ExtensionRange::clear_options() { + if (options_ != nullptr) options_->Clear(); _has_bits_[0] &= ~0x00000001u; } -inline void DescriptorProto_ExtensionRange::clear_options() { - if (options_ != NULL) options_->Clear(); - clear_has_options(); -} -inline const ::google::protobuf::ExtensionRangeOptions& DescriptorProto_ExtensionRange::_internal_options() const { - return *options_; -} -inline const ::google::protobuf::ExtensionRangeOptions& DescriptorProto_ExtensionRange::options() const { - const ::google::protobuf::ExtensionRangeOptions* p = options_; +inline const PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions& DescriptorProto_ExtensionRange::options() const { + const PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ExtensionRange.options) - return p != NULL ? *p : *reinterpret_cast( - &::google::protobuf::_ExtensionRangeOptions_default_instance_); + return p != nullptr ? *p : *reinterpret_cast( + &PROTOBUF_NAMESPACE_ID::_ExtensionRangeOptions_default_instance_); } -inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange::release_options() { +inline PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* DescriptorProto_ExtensionRange::release_options() { // @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.ExtensionRange.options) - clear_has_options(); - ::google::protobuf::ExtensionRangeOptions* temp = options_; - if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); + _has_bits_[0] &= ~0x00000001u; + PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* temp = options_; + if (GetArenaNoVirtual() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } - options_ = NULL; + options_ = nullptr; return temp; } -inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange::unsafe_arena_release_options() { +inline PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* DescriptorProto_ExtensionRange::unsafe_arena_release_options() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.DescriptorProto.ExtensionRange.options) - clear_has_options(); - ::google::protobuf::ExtensionRangeOptions* temp = options_; - options_ = NULL; + _has_bits_[0] &= ~0x00000001u; + PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* temp = options_; + options_ = nullptr; return temp; } -inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange::mutable_options() { - set_has_options(); - if (options_ == NULL) { - auto* p = CreateMaybeMessage<::google::protobuf::ExtensionRangeOptions>(GetArenaNoVirtual()); +inline PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* DescriptorProto_ExtensionRange::mutable_options() { + _has_bits_[0] |= 0x00000001u; + if (options_ == nullptr) { + auto* p = CreateMaybeMessage(GetArenaNoVirtual()); options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.ExtensionRange.options) return options_; } -inline void DescriptorProto_ExtensionRange::set_allocated_options(::google::protobuf::ExtensionRangeOptions* options) { - ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); - if (message_arena == NULL) { +inline void DescriptorProto_ExtensionRange::set_allocated_options(PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* options) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); + if (message_arena == nullptr) { delete options_; } if (options) { - ::google::protobuf::Arena* submessage_arena = - ::google::protobuf::Arena::GetArena(options); + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::GetArena(options); if (message_arena != submessage_arena) { - options = ::google::protobuf::internal::GetOwnedMessage( + options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - set_has_options(); + _has_bits_[0] |= 0x00000001u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000001u; } options_ = options; // @@protoc_insertion_point(field_set_allocated:google.protobuf.DescriptorProto.ExtensionRange.options) @@ -6609,22 +6927,16 @@ inline void DescriptorProto_ExtensionRange::set_allocated_options(::google::prot inline bool DescriptorProto_ReservedRange::has_start() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void DescriptorProto_ReservedRange::set_has_start() { - _has_bits_[0] |= 0x00000001u; -} -inline void DescriptorProto_ReservedRange::clear_has_start() { - _has_bits_[0] &= ~0x00000001u; -} inline void DescriptorProto_ReservedRange::clear_start() { start_ = 0; - clear_has_start(); + _has_bits_[0] &= ~0x00000001u; } -inline ::google::protobuf::int32 DescriptorProto_ReservedRange::start() const { +inline ::PROTOBUF_NAMESPACE_ID::int32 DescriptorProto_ReservedRange::start() const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ReservedRange.start) return start_; } -inline void DescriptorProto_ReservedRange::set_start(::google::protobuf::int32 value) { - set_has_start(); +inline void DescriptorProto_ReservedRange::set_start(::PROTOBUF_NAMESPACE_ID::int32 value) { + _has_bits_[0] |= 0x00000001u; start_ = value; // @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ReservedRange.start) } @@ -6633,22 +6945,16 @@ inline void DescriptorProto_ReservedRange::set_start(::google::protobuf::int32 v inline bool DescriptorProto_ReservedRange::has_end() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void DescriptorProto_ReservedRange::set_has_end() { - _has_bits_[0] |= 0x00000002u; -} -inline void DescriptorProto_ReservedRange::clear_has_end() { - _has_bits_[0] &= ~0x00000002u; -} inline void DescriptorProto_ReservedRange::clear_end() { end_ = 0; - clear_has_end(); + _has_bits_[0] &= ~0x00000002u; } -inline ::google::protobuf::int32 DescriptorProto_ReservedRange::end() const { +inline ::PROTOBUF_NAMESPACE_ID::int32 DescriptorProto_ReservedRange::end() const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ReservedRange.end) return end_; } -inline void DescriptorProto_ReservedRange::set_end(::google::protobuf::int32 value) { - set_has_end(); +inline void DescriptorProto_ReservedRange::set_end(::PROTOBUF_NAMESPACE_ID::int32 value) { + _has_bits_[0] |= 0x00000002u; end_ = value; // @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ReservedRange.end) } @@ -6661,86 +6967,78 @@ inline void DescriptorProto_ReservedRange::set_end(::google::protobuf::int32 val inline bool DescriptorProto::has_name() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void DescriptorProto::set_has_name() { - _has_bits_[0] |= 0x00000001u; -} -inline void DescriptorProto::clear_has_name() { +inline void DescriptorProto::clear_name() { + name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000001u; } -inline void DescriptorProto::clear_name() { - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_name(); -} -inline const ::std::string& DescriptorProto::name() const { +inline const std::string& DescriptorProto::name() const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.name) return name_.Get(); } -inline void DescriptorProto::set_name(const ::std::string& value) { - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void DescriptorProto::set_name(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.name) } -#if LANG_CXX11 -inline void DescriptorProto::set_name(::std::string&& value) { - set_has_name(); +inline void DescriptorProto::set_name(std::string&& value) { + _has_bits_[0] |= 0x00000001u; name_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.DescriptorProto.name) } -#endif inline void DescriptorProto::set_name(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.DescriptorProto.name) } inline void DescriptorProto::set_name(const char* value, size_t size) { - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.DescriptorProto.name) } -inline ::std::string* DescriptorProto::mutable_name() { - set_has_name(); +inline std::string* DescriptorProto::mutable_name() { + _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.name) - return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* DescriptorProto::release_name() { +inline std::string* DescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.name) if (!has_name()) { - return NULL; + return nullptr; } - clear_has_name(); - return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000001u; + return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void DescriptorProto::set_allocated_name(::std::string* name) { - if (name != NULL) { - set_has_name(); +inline void DescriptorProto::set_allocated_name(std::string* name) { + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name, + name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.DescriptorProto.name) } -inline ::std::string* DescriptorProto::unsafe_arena_release_name() { +inline std::string* DescriptorProto::unsafe_arena_release_name() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.DescriptorProto.name) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_name(); - return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000001u; + return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void DescriptorProto::unsafe_arena_set_allocated_name( - ::std::string* name) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (name != NULL) { - set_has_name(); + std::string* name) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.DescriptorProto.name) } @@ -6752,24 +7050,24 @@ inline int DescriptorProto::field_size() const { inline void DescriptorProto::clear_field() { field_.Clear(); } -inline ::google::protobuf::FieldDescriptorProto* DescriptorProto::mutable_field(int index) { +inline PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* DescriptorProto::mutable_field(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.field) return field_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >* DescriptorProto::mutable_field() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.field) return &field_; } -inline const ::google::protobuf::FieldDescriptorProto& DescriptorProto::field(int index) const { +inline const PROTOBUF_NAMESPACE_ID::FieldDescriptorProto& DescriptorProto::field(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.field) return field_.Get(index); } -inline ::google::protobuf::FieldDescriptorProto* DescriptorProto::add_field() { +inline PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* DescriptorProto::add_field() { // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.field) return field_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >& DescriptorProto::field() const { // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.field) return field_; @@ -6782,24 +7080,24 @@ inline int DescriptorProto::extension_size() const { inline void DescriptorProto::clear_extension() { extension_.Clear(); } -inline ::google::protobuf::FieldDescriptorProto* DescriptorProto::mutable_extension(int index) { +inline PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* DescriptorProto::mutable_extension(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.extension) return extension_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >* DescriptorProto::mutable_extension() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.extension) return &extension_; } -inline const ::google::protobuf::FieldDescriptorProto& DescriptorProto::extension(int index) const { +inline const PROTOBUF_NAMESPACE_ID::FieldDescriptorProto& DescriptorProto::extension(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.extension) return extension_.Get(index); } -inline ::google::protobuf::FieldDescriptorProto* DescriptorProto::add_extension() { +inline PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* DescriptorProto::add_extension() { // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.extension) return extension_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >& DescriptorProto::extension() const { // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.extension) return extension_; @@ -6812,24 +7110,24 @@ inline int DescriptorProto::nested_type_size() const { inline void DescriptorProto::clear_nested_type() { nested_type_.Clear(); } -inline ::google::protobuf::DescriptorProto* DescriptorProto::mutable_nested_type(int index) { +inline PROTOBUF_NAMESPACE_ID::DescriptorProto* DescriptorProto::mutable_nested_type(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.nested_type) return nested_type_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto >* DescriptorProto::mutable_nested_type() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.nested_type) return &nested_type_; } -inline const ::google::protobuf::DescriptorProto& DescriptorProto::nested_type(int index) const { +inline const PROTOBUF_NAMESPACE_ID::DescriptorProto& DescriptorProto::nested_type(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.nested_type) return nested_type_.Get(index); } -inline ::google::protobuf::DescriptorProto* DescriptorProto::add_nested_type() { +inline PROTOBUF_NAMESPACE_ID::DescriptorProto* DescriptorProto::add_nested_type() { // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.nested_type) return nested_type_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto >& DescriptorProto::nested_type() const { // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.nested_type) return nested_type_; @@ -6842,24 +7140,24 @@ inline int DescriptorProto::enum_type_size() const { inline void DescriptorProto::clear_enum_type() { enum_type_.Clear(); } -inline ::google::protobuf::EnumDescriptorProto* DescriptorProto::mutable_enum_type(int index) { +inline PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* DescriptorProto::mutable_enum_type(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.enum_type) return enum_type_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto >* DescriptorProto::mutable_enum_type() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.enum_type) return &enum_type_; } -inline const ::google::protobuf::EnumDescriptorProto& DescriptorProto::enum_type(int index) const { +inline const PROTOBUF_NAMESPACE_ID::EnumDescriptorProto& DescriptorProto::enum_type(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.enum_type) return enum_type_.Get(index); } -inline ::google::protobuf::EnumDescriptorProto* DescriptorProto::add_enum_type() { +inline PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* DescriptorProto::add_enum_type() { // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.enum_type) return enum_type_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto >& DescriptorProto::enum_type() const { // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.enum_type) return enum_type_; @@ -6872,24 +7170,24 @@ inline int DescriptorProto::extension_range_size() const { inline void DescriptorProto::clear_extension_range() { extension_range_.Clear(); } -inline ::google::protobuf::DescriptorProto_ExtensionRange* DescriptorProto::mutable_extension_range(int index) { +inline PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange* DescriptorProto::mutable_extension_range(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.extension_range) return extension_range_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange >* DescriptorProto::mutable_extension_range() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.extension_range) return &extension_range_; } -inline const ::google::protobuf::DescriptorProto_ExtensionRange& DescriptorProto::extension_range(int index) const { +inline const PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange& DescriptorProto::extension_range(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.extension_range) return extension_range_.Get(index); } -inline ::google::protobuf::DescriptorProto_ExtensionRange* DescriptorProto::add_extension_range() { +inline PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange* DescriptorProto::add_extension_range() { // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.extension_range) return extension_range_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange >& DescriptorProto::extension_range() const { // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.extension_range) return extension_range_; @@ -6902,24 +7200,24 @@ inline int DescriptorProto::oneof_decl_size() const { inline void DescriptorProto::clear_oneof_decl() { oneof_decl_.Clear(); } -inline ::google::protobuf::OneofDescriptorProto* DescriptorProto::mutable_oneof_decl(int index) { +inline PROTOBUF_NAMESPACE_ID::OneofDescriptorProto* DescriptorProto::mutable_oneof_decl(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.oneof_decl) return oneof_decl_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::OneofDescriptorProto >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::OneofDescriptorProto >* DescriptorProto::mutable_oneof_decl() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.oneof_decl) return &oneof_decl_; } -inline const ::google::protobuf::OneofDescriptorProto& DescriptorProto::oneof_decl(int index) const { +inline const PROTOBUF_NAMESPACE_ID::OneofDescriptorProto& DescriptorProto::oneof_decl(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.oneof_decl) return oneof_decl_.Get(index); } -inline ::google::protobuf::OneofDescriptorProto* DescriptorProto::add_oneof_decl() { +inline PROTOBUF_NAMESPACE_ID::OneofDescriptorProto* DescriptorProto::add_oneof_decl() { // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.oneof_decl) return oneof_decl_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::OneofDescriptorProto >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::OneofDescriptorProto >& DescriptorProto::oneof_decl() const { // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.oneof_decl) return oneof_decl_; @@ -6929,66 +7227,57 @@ DescriptorProto::oneof_decl() const { inline bool DescriptorProto::has_options() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void DescriptorProto::set_has_options() { - _has_bits_[0] |= 0x00000002u; -} -inline void DescriptorProto::clear_has_options() { +inline void DescriptorProto::clear_options() { + if (options_ != nullptr) options_->Clear(); _has_bits_[0] &= ~0x00000002u; } -inline void DescriptorProto::clear_options() { - if (options_ != NULL) options_->Clear(); - clear_has_options(); -} -inline const ::google::protobuf::MessageOptions& DescriptorProto::_internal_options() const { - return *options_; -} -inline const ::google::protobuf::MessageOptions& DescriptorProto::options() const { - const ::google::protobuf::MessageOptions* p = options_; +inline const PROTOBUF_NAMESPACE_ID::MessageOptions& DescriptorProto::options() const { + const PROTOBUF_NAMESPACE_ID::MessageOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.options) - return p != NULL ? *p : *reinterpret_cast( - &::google::protobuf::_MessageOptions_default_instance_); + return p != nullptr ? *p : *reinterpret_cast( + &PROTOBUF_NAMESPACE_ID::_MessageOptions_default_instance_); } -inline ::google::protobuf::MessageOptions* DescriptorProto::release_options() { +inline PROTOBUF_NAMESPACE_ID::MessageOptions* DescriptorProto::release_options() { // @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.options) - clear_has_options(); - ::google::protobuf::MessageOptions* temp = options_; - if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); + _has_bits_[0] &= ~0x00000002u; + PROTOBUF_NAMESPACE_ID::MessageOptions* temp = options_; + if (GetArenaNoVirtual() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } - options_ = NULL; + options_ = nullptr; return temp; } -inline ::google::protobuf::MessageOptions* DescriptorProto::unsafe_arena_release_options() { +inline PROTOBUF_NAMESPACE_ID::MessageOptions* DescriptorProto::unsafe_arena_release_options() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.DescriptorProto.options) - clear_has_options(); - ::google::protobuf::MessageOptions* temp = options_; - options_ = NULL; + _has_bits_[0] &= ~0x00000002u; + PROTOBUF_NAMESPACE_ID::MessageOptions* temp = options_; + options_ = nullptr; return temp; } -inline ::google::protobuf::MessageOptions* DescriptorProto::mutable_options() { - set_has_options(); - if (options_ == NULL) { - auto* p = CreateMaybeMessage<::google::protobuf::MessageOptions>(GetArenaNoVirtual()); +inline PROTOBUF_NAMESPACE_ID::MessageOptions* DescriptorProto::mutable_options() { + _has_bits_[0] |= 0x00000002u; + if (options_ == nullptr) { + auto* p = CreateMaybeMessage(GetArenaNoVirtual()); options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.options) return options_; } -inline void DescriptorProto::set_allocated_options(::google::protobuf::MessageOptions* options) { - ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); - if (message_arena == NULL) { +inline void DescriptorProto::set_allocated_options(PROTOBUF_NAMESPACE_ID::MessageOptions* options) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); + if (message_arena == nullptr) { delete options_; } if (options) { - ::google::protobuf::Arena* submessage_arena = - ::google::protobuf::Arena::GetArena(options); + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::GetArena(options); if (message_arena != submessage_arena) { - options = ::google::protobuf::internal::GetOwnedMessage( + options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - set_has_options(); + _has_bits_[0] |= 0x00000002u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000002u; } options_ = options; // @@protoc_insertion_point(field_set_allocated:google.protobuf.DescriptorProto.options) @@ -7001,24 +7290,24 @@ inline int DescriptorProto::reserved_range_size() const { inline void DescriptorProto::clear_reserved_range() { reserved_range_.Clear(); } -inline ::google::protobuf::DescriptorProto_ReservedRange* DescriptorProto::mutable_reserved_range(int index) { +inline PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange* DescriptorProto::mutable_reserved_range(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.reserved_range) return reserved_range_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ReservedRange >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange >* DescriptorProto::mutable_reserved_range() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.reserved_range) return &reserved_range_; } -inline const ::google::protobuf::DescriptorProto_ReservedRange& DescriptorProto::reserved_range(int index) const { +inline const PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange& DescriptorProto::reserved_range(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.reserved_range) return reserved_range_.Get(index); } -inline ::google::protobuf::DescriptorProto_ReservedRange* DescriptorProto::add_reserved_range() { +inline PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange* DescriptorProto::add_reserved_range() { // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.reserved_range) return reserved_range_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ReservedRange >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange >& DescriptorProto::reserved_range() const { // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.reserved_range) return reserved_range_; @@ -7031,26 +7320,24 @@ inline int DescriptorProto::reserved_name_size() const { inline void DescriptorProto::clear_reserved_name() { reserved_name_.Clear(); } -inline const ::std::string& DescriptorProto::reserved_name(int index) const { +inline const std::string& DescriptorProto::reserved_name(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.reserved_name) return reserved_name_.Get(index); } -inline ::std::string* DescriptorProto::mutable_reserved_name(int index) { +inline std::string* DescriptorProto::mutable_reserved_name(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.reserved_name) return reserved_name_.Mutable(index); } -inline void DescriptorProto::set_reserved_name(int index, const ::std::string& value) { +inline void DescriptorProto::set_reserved_name(int index, const std::string& value) { // @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.reserved_name) reserved_name_.Mutable(index)->assign(value); } -#if LANG_CXX11 -inline void DescriptorProto::set_reserved_name(int index, ::std::string&& value) { +inline void DescriptorProto::set_reserved_name(int index, std::string&& value) { // @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.reserved_name) reserved_name_.Mutable(index)->assign(std::move(value)); } -#endif inline void DescriptorProto::set_reserved_name(int index, const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); reserved_name_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.protobuf.DescriptorProto.reserved_name) } @@ -7059,22 +7346,20 @@ inline void DescriptorProto::set_reserved_name(int index, const char* value, siz reinterpret_cast(value), size); // @@protoc_insertion_point(field_set_pointer:google.protobuf.DescriptorProto.reserved_name) } -inline ::std::string* DescriptorProto::add_reserved_name() { +inline std::string* DescriptorProto::add_reserved_name() { // @@protoc_insertion_point(field_add_mutable:google.protobuf.DescriptorProto.reserved_name) return reserved_name_.Add(); } -inline void DescriptorProto::add_reserved_name(const ::std::string& value) { +inline void DescriptorProto::add_reserved_name(const std::string& value) { reserved_name_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.reserved_name) } -#if LANG_CXX11 -inline void DescriptorProto::add_reserved_name(::std::string&& value) { +inline void DescriptorProto::add_reserved_name(std::string&& value) { reserved_name_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.reserved_name) } -#endif inline void DescriptorProto::add_reserved_name(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); reserved_name_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.protobuf.DescriptorProto.reserved_name) } @@ -7082,12 +7367,12 @@ inline void DescriptorProto::add_reserved_name(const char* value, size_t size) { reserved_name_.Add()->assign(reinterpret_cast(value), size); // @@protoc_insertion_point(field_add_pointer:google.protobuf.DescriptorProto.reserved_name) } -inline const ::google::protobuf::RepeatedPtrField< ::std::string>& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& DescriptorProto::reserved_name() const { // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.reserved_name) return reserved_name_; } -inline ::google::protobuf::RepeatedPtrField< ::std::string>* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* DescriptorProto::mutable_reserved_name() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.reserved_name) return &reserved_name_; @@ -7104,24 +7389,24 @@ inline int ExtensionRangeOptions::uninterpreted_option_size() const { inline void ExtensionRangeOptions::clear_uninterpreted_option() { uninterpreted_option_.Clear(); } -inline ::google::protobuf::UninterpretedOption* ExtensionRangeOptions::mutable_uninterpreted_option(int index) { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* ExtensionRangeOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.ExtensionRangeOptions.uninterpreted_option) return uninterpreted_option_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* ExtensionRangeOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.ExtensionRangeOptions.uninterpreted_option) return &uninterpreted_option_; } -inline const ::google::protobuf::UninterpretedOption& ExtensionRangeOptions::uninterpreted_option(int index) const { +inline const PROTOBUF_NAMESPACE_ID::UninterpretedOption& ExtensionRangeOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.ExtensionRangeOptions.uninterpreted_option) return uninterpreted_option_.Get(index); } -inline ::google::protobuf::UninterpretedOption* ExtensionRangeOptions::add_uninterpreted_option() { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* ExtensionRangeOptions::add_uninterpreted_option() { // @@protoc_insertion_point(field_add:google.protobuf.ExtensionRangeOptions.uninterpreted_option) return uninterpreted_option_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& ExtensionRangeOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.ExtensionRangeOptions.uninterpreted_option) return uninterpreted_option_; @@ -7135,86 +7420,78 @@ ExtensionRangeOptions::uninterpreted_option() const { inline bool FieldDescriptorProto::has_name() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void FieldDescriptorProto::set_has_name() { - _has_bits_[0] |= 0x00000001u; -} -inline void FieldDescriptorProto::clear_has_name() { +inline void FieldDescriptorProto::clear_name() { + name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000001u; } -inline void FieldDescriptorProto::clear_name() { - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_name(); -} -inline const ::std::string& FieldDescriptorProto::name() const { +inline const std::string& FieldDescriptorProto::name() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.name) return name_.Get(); } -inline void FieldDescriptorProto::set_name(const ::std::string& value) { - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FieldDescriptorProto::set_name(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.name) } -#if LANG_CXX11 -inline void FieldDescriptorProto::set_name(::std::string&& value) { - set_has_name(); +inline void FieldDescriptorProto::set_name(std::string&& value) { + _has_bits_[0] |= 0x00000001u; name_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.name) } -#endif inline void FieldDescriptorProto::set_name(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.name) } inline void FieldDescriptorProto::set_name(const char* value, size_t size) { - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.name) } -inline ::std::string* FieldDescriptorProto::mutable_name() { - set_has_name(); +inline std::string* FieldDescriptorProto::mutable_name() { + _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.name) - return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FieldDescriptorProto::release_name() { +inline std::string* FieldDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.name) if (!has_name()) { - return NULL; + return nullptr; } - clear_has_name(); - return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000001u; + return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FieldDescriptorProto::set_allocated_name(::std::string* name) { - if (name != NULL) { - set_has_name(); +inline void FieldDescriptorProto::set_allocated_name(std::string* name) { + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name, + name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.name) } -inline ::std::string* FieldDescriptorProto::unsafe_arena_release_name() { +inline std::string* FieldDescriptorProto::unsafe_arena_release_name() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.name) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_name(); - return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000001u; + return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FieldDescriptorProto::unsafe_arena_set_allocated_name( - ::std::string* name) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (name != NULL) { - set_has_name(); + std::string* name) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.name) } @@ -7223,22 +7500,16 @@ inline void FieldDescriptorProto::unsafe_arena_set_allocated_name( inline bool FieldDescriptorProto::has_number() const { return (_has_bits_[0] & 0x00000040u) != 0; } -inline void FieldDescriptorProto::set_has_number() { - _has_bits_[0] |= 0x00000040u; -} -inline void FieldDescriptorProto::clear_has_number() { - _has_bits_[0] &= ~0x00000040u; -} inline void FieldDescriptorProto::clear_number() { number_ = 0; - clear_has_number(); + _has_bits_[0] &= ~0x00000040u; } -inline ::google::protobuf::int32 FieldDescriptorProto::number() const { +inline ::PROTOBUF_NAMESPACE_ID::int32 FieldDescriptorProto::number() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.number) return number_; } -inline void FieldDescriptorProto::set_number(::google::protobuf::int32 value) { - set_has_number(); +inline void FieldDescriptorProto::set_number(::PROTOBUF_NAMESPACE_ID::int32 value) { + _has_bits_[0] |= 0x00000040u; number_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.number) } @@ -7247,23 +7518,17 @@ inline void FieldDescriptorProto::set_number(::google::protobuf::int32 value) { inline bool FieldDescriptorProto::has_label() const { return (_has_bits_[0] & 0x00000100u) != 0; } -inline void FieldDescriptorProto::set_has_label() { - _has_bits_[0] |= 0x00000100u; -} -inline void FieldDescriptorProto::clear_has_label() { - _has_bits_[0] &= ~0x00000100u; -} inline void FieldDescriptorProto::clear_label() { label_ = 1; - clear_has_label(); + _has_bits_[0] &= ~0x00000100u; } -inline ::google::protobuf::FieldDescriptorProto_Label FieldDescriptorProto::label() const { +inline PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label FieldDescriptorProto::label() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.label) - return static_cast< ::google::protobuf::FieldDescriptorProto_Label >(label_); + return static_cast< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label >(label_); } -inline void FieldDescriptorProto::set_label(::google::protobuf::FieldDescriptorProto_Label value) { - assert(::google::protobuf::FieldDescriptorProto_Label_IsValid(value)); - set_has_label(); +inline void FieldDescriptorProto::set_label(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label value) { + assert(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label_IsValid(value)); + _has_bits_[0] |= 0x00000100u; label_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.label) } @@ -7272,23 +7537,17 @@ inline void FieldDescriptorProto::set_label(::google::protobuf::FieldDescriptorP inline bool FieldDescriptorProto::has_type() const { return (_has_bits_[0] & 0x00000200u) != 0; } -inline void FieldDescriptorProto::set_has_type() { - _has_bits_[0] |= 0x00000200u; -} -inline void FieldDescriptorProto::clear_has_type() { - _has_bits_[0] &= ~0x00000200u; -} inline void FieldDescriptorProto::clear_type() { type_ = 1; - clear_has_type(); + _has_bits_[0] &= ~0x00000200u; } -inline ::google::protobuf::FieldDescriptorProto_Type FieldDescriptorProto::type() const { +inline PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type FieldDescriptorProto::type() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.type) - return static_cast< ::google::protobuf::FieldDescriptorProto_Type >(type_); + return static_cast< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type >(type_); } -inline void FieldDescriptorProto::set_type(::google::protobuf::FieldDescriptorProto_Type value) { - assert(::google::protobuf::FieldDescriptorProto_Type_IsValid(value)); - set_has_type(); +inline void FieldDescriptorProto::set_type(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type value) { + assert(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type_IsValid(value)); + _has_bits_[0] |= 0x00000200u; type_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.type) } @@ -7297,86 +7556,78 @@ inline void FieldDescriptorProto::set_type(::google::protobuf::FieldDescriptorPr inline bool FieldDescriptorProto::has_type_name() const { return (_has_bits_[0] & 0x00000004u) != 0; } -inline void FieldDescriptorProto::set_has_type_name() { - _has_bits_[0] |= 0x00000004u; -} -inline void FieldDescriptorProto::clear_has_type_name() { +inline void FieldDescriptorProto::clear_type_name() { + type_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000004u; } -inline void FieldDescriptorProto::clear_type_name() { - type_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_type_name(); -} -inline const ::std::string& FieldDescriptorProto::type_name() const { +inline const std::string& FieldDescriptorProto::type_name() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.type_name) return type_name_.Get(); } -inline void FieldDescriptorProto::set_type_name(const ::std::string& value) { - set_has_type_name(); - type_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FieldDescriptorProto::set_type_name(const std::string& value) { + _has_bits_[0] |= 0x00000004u; + type_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.type_name) } -#if LANG_CXX11 -inline void FieldDescriptorProto::set_type_name(::std::string&& value) { - set_has_type_name(); +inline void FieldDescriptorProto::set_type_name(std::string&& value) { + _has_bits_[0] |= 0x00000004u; type_name_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.type_name) } -#endif inline void FieldDescriptorProto::set_type_name(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_type_name(); - type_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000004u; + type_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.type_name) } inline void FieldDescriptorProto::set_type_name(const char* value, size_t size) { - set_has_type_name(); - type_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000004u; + type_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.type_name) } -inline ::std::string* FieldDescriptorProto::mutable_type_name() { - set_has_type_name(); +inline std::string* FieldDescriptorProto::mutable_type_name() { + _has_bits_[0] |= 0x00000004u; // @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.type_name) - return type_name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return type_name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FieldDescriptorProto::release_type_name() { +inline std::string* FieldDescriptorProto::release_type_name() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.type_name) if (!has_type_name()) { - return NULL; + return nullptr; } - clear_has_type_name(); - return type_name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000004u; + return type_name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FieldDescriptorProto::set_allocated_type_name(::std::string* type_name) { - if (type_name != NULL) { - set_has_type_name(); +inline void FieldDescriptorProto::set_allocated_type_name(std::string* type_name) { + if (type_name != nullptr) { + _has_bits_[0] |= 0x00000004u; } else { - clear_has_type_name(); + _has_bits_[0] &= ~0x00000004u; } - type_name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type_name, + type_name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), type_name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.type_name) } -inline ::std::string* FieldDescriptorProto::unsafe_arena_release_type_name() { +inline std::string* FieldDescriptorProto::unsafe_arena_release_type_name() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.type_name) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_type_name(); - return type_name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000004u; + return type_name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FieldDescriptorProto::unsafe_arena_set_allocated_type_name( - ::std::string* type_name) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (type_name != NULL) { - set_has_type_name(); + std::string* type_name) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (type_name != nullptr) { + _has_bits_[0] |= 0x00000004u; } else { - clear_has_type_name(); + _has_bits_[0] &= ~0x00000004u; } - type_name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + type_name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), type_name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.type_name) } @@ -7385,86 +7636,78 @@ inline void FieldDescriptorProto::unsafe_arena_set_allocated_type_name( inline bool FieldDescriptorProto::has_extendee() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void FieldDescriptorProto::set_has_extendee() { - _has_bits_[0] |= 0x00000002u; -} -inline void FieldDescriptorProto::clear_has_extendee() { +inline void FieldDescriptorProto::clear_extendee() { + extendee_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000002u; } -inline void FieldDescriptorProto::clear_extendee() { - extendee_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_extendee(); -} -inline const ::std::string& FieldDescriptorProto::extendee() const { +inline const std::string& FieldDescriptorProto::extendee() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.extendee) return extendee_.Get(); } -inline void FieldDescriptorProto::set_extendee(const ::std::string& value) { - set_has_extendee(); - extendee_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FieldDescriptorProto::set_extendee(const std::string& value) { + _has_bits_[0] |= 0x00000002u; + extendee_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.extendee) } -#if LANG_CXX11 -inline void FieldDescriptorProto::set_extendee(::std::string&& value) { - set_has_extendee(); +inline void FieldDescriptorProto::set_extendee(std::string&& value) { + _has_bits_[0] |= 0x00000002u; extendee_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.extendee) } -#endif inline void FieldDescriptorProto::set_extendee(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_extendee(); - extendee_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000002u; + extendee_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.extendee) } inline void FieldDescriptorProto::set_extendee(const char* value, size_t size) { - set_has_extendee(); - extendee_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000002u; + extendee_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.extendee) } -inline ::std::string* FieldDescriptorProto::mutable_extendee() { - set_has_extendee(); +inline std::string* FieldDescriptorProto::mutable_extendee() { + _has_bits_[0] |= 0x00000002u; // @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.extendee) - return extendee_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return extendee_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FieldDescriptorProto::release_extendee() { +inline std::string* FieldDescriptorProto::release_extendee() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.extendee) if (!has_extendee()) { - return NULL; + return nullptr; } - clear_has_extendee(); - return extendee_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000002u; + return extendee_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FieldDescriptorProto::set_allocated_extendee(::std::string* extendee) { - if (extendee != NULL) { - set_has_extendee(); +inline void FieldDescriptorProto::set_allocated_extendee(std::string* extendee) { + if (extendee != nullptr) { + _has_bits_[0] |= 0x00000002u; } else { - clear_has_extendee(); + _has_bits_[0] &= ~0x00000002u; } - extendee_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), extendee, + extendee_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), extendee, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.extendee) } -inline ::std::string* FieldDescriptorProto::unsafe_arena_release_extendee() { +inline std::string* FieldDescriptorProto::unsafe_arena_release_extendee() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.extendee) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_extendee(); - return extendee_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000002u; + return extendee_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FieldDescriptorProto::unsafe_arena_set_allocated_extendee( - ::std::string* extendee) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (extendee != NULL) { - set_has_extendee(); + std::string* extendee) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (extendee != nullptr) { + _has_bits_[0] |= 0x00000002u; } else { - clear_has_extendee(); + _has_bits_[0] &= ~0x00000002u; } - extendee_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + extendee_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), extendee, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.extendee) } @@ -7473,86 +7716,78 @@ inline void FieldDescriptorProto::unsafe_arena_set_allocated_extendee( inline bool FieldDescriptorProto::has_default_value() const { return (_has_bits_[0] & 0x00000008u) != 0; } -inline void FieldDescriptorProto::set_has_default_value() { - _has_bits_[0] |= 0x00000008u; -} -inline void FieldDescriptorProto::clear_has_default_value() { +inline void FieldDescriptorProto::clear_default_value() { + default_value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000008u; } -inline void FieldDescriptorProto::clear_default_value() { - default_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_default_value(); -} -inline const ::std::string& FieldDescriptorProto::default_value() const { +inline const std::string& FieldDescriptorProto::default_value() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.default_value) return default_value_.Get(); } -inline void FieldDescriptorProto::set_default_value(const ::std::string& value) { - set_has_default_value(); - default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FieldDescriptorProto::set_default_value(const std::string& value) { + _has_bits_[0] |= 0x00000008u; + default_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.default_value) } -#if LANG_CXX11 -inline void FieldDescriptorProto::set_default_value(::std::string&& value) { - set_has_default_value(); +inline void FieldDescriptorProto::set_default_value(std::string&& value) { + _has_bits_[0] |= 0x00000008u; default_value_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.default_value) } -#endif inline void FieldDescriptorProto::set_default_value(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_default_value(); - default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000008u; + default_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.default_value) } inline void FieldDescriptorProto::set_default_value(const char* value, size_t size) { - set_has_default_value(); - default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000008u; + default_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.default_value) } -inline ::std::string* FieldDescriptorProto::mutable_default_value() { - set_has_default_value(); +inline std::string* FieldDescriptorProto::mutable_default_value() { + _has_bits_[0] |= 0x00000008u; // @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.default_value) - return default_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return default_value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FieldDescriptorProto::release_default_value() { +inline std::string* FieldDescriptorProto::release_default_value() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.default_value) if (!has_default_value()) { - return NULL; + return nullptr; } - clear_has_default_value(); - return default_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000008u; + return default_value_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FieldDescriptorProto::set_allocated_default_value(::std::string* default_value) { - if (default_value != NULL) { - set_has_default_value(); +inline void FieldDescriptorProto::set_allocated_default_value(std::string* default_value) { + if (default_value != nullptr) { + _has_bits_[0] |= 0x00000008u; } else { - clear_has_default_value(); + _has_bits_[0] &= ~0x00000008u; } - default_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), default_value, + default_value_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), default_value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.default_value) } -inline ::std::string* FieldDescriptorProto::unsafe_arena_release_default_value() { +inline std::string* FieldDescriptorProto::unsafe_arena_release_default_value() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.default_value) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_default_value(); - return default_value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000008u; + return default_value_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FieldDescriptorProto::unsafe_arena_set_allocated_default_value( - ::std::string* default_value) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (default_value != NULL) { - set_has_default_value(); + std::string* default_value) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (default_value != nullptr) { + _has_bits_[0] |= 0x00000008u; } else { - clear_has_default_value(); + _has_bits_[0] &= ~0x00000008u; } - default_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + default_value_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), default_value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.default_value) } @@ -7561,22 +7796,16 @@ inline void FieldDescriptorProto::unsafe_arena_set_allocated_default_value( inline bool FieldDescriptorProto::has_oneof_index() const { return (_has_bits_[0] & 0x00000080u) != 0; } -inline void FieldDescriptorProto::set_has_oneof_index() { - _has_bits_[0] |= 0x00000080u; -} -inline void FieldDescriptorProto::clear_has_oneof_index() { - _has_bits_[0] &= ~0x00000080u; -} inline void FieldDescriptorProto::clear_oneof_index() { oneof_index_ = 0; - clear_has_oneof_index(); + _has_bits_[0] &= ~0x00000080u; } -inline ::google::protobuf::int32 FieldDescriptorProto::oneof_index() const { +inline ::PROTOBUF_NAMESPACE_ID::int32 FieldDescriptorProto::oneof_index() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.oneof_index) return oneof_index_; } -inline void FieldDescriptorProto::set_oneof_index(::google::protobuf::int32 value) { - set_has_oneof_index(); +inline void FieldDescriptorProto::set_oneof_index(::PROTOBUF_NAMESPACE_ID::int32 value) { + _has_bits_[0] |= 0x00000080u; oneof_index_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.oneof_index) } @@ -7585,86 +7814,78 @@ inline void FieldDescriptorProto::set_oneof_index(::google::protobuf::int32 valu inline bool FieldDescriptorProto::has_json_name() const { return (_has_bits_[0] & 0x00000010u) != 0; } -inline void FieldDescriptorProto::set_has_json_name() { - _has_bits_[0] |= 0x00000010u; -} -inline void FieldDescriptorProto::clear_has_json_name() { +inline void FieldDescriptorProto::clear_json_name() { + json_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000010u; } -inline void FieldDescriptorProto::clear_json_name() { - json_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_json_name(); -} -inline const ::std::string& FieldDescriptorProto::json_name() const { +inline const std::string& FieldDescriptorProto::json_name() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.json_name) return json_name_.Get(); } -inline void FieldDescriptorProto::set_json_name(const ::std::string& value) { - set_has_json_name(); - json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FieldDescriptorProto::set_json_name(const std::string& value) { + _has_bits_[0] |= 0x00000010u; + json_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.json_name) } -#if LANG_CXX11 -inline void FieldDescriptorProto::set_json_name(::std::string&& value) { - set_has_json_name(); +inline void FieldDescriptorProto::set_json_name(std::string&& value) { + _has_bits_[0] |= 0x00000010u; json_name_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.json_name) } -#endif inline void FieldDescriptorProto::set_json_name(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_json_name(); - json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000010u; + json_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.json_name) } inline void FieldDescriptorProto::set_json_name(const char* value, size_t size) { - set_has_json_name(); - json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000010u; + json_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.json_name) } -inline ::std::string* FieldDescriptorProto::mutable_json_name() { - set_has_json_name(); +inline std::string* FieldDescriptorProto::mutable_json_name() { + _has_bits_[0] |= 0x00000010u; // @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.json_name) - return json_name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return json_name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FieldDescriptorProto::release_json_name() { +inline std::string* FieldDescriptorProto::release_json_name() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.json_name) if (!has_json_name()) { - return NULL; + return nullptr; } - clear_has_json_name(); - return json_name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000010u; + return json_name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FieldDescriptorProto::set_allocated_json_name(::std::string* json_name) { - if (json_name != NULL) { - set_has_json_name(); +inline void FieldDescriptorProto::set_allocated_json_name(std::string* json_name) { + if (json_name != nullptr) { + _has_bits_[0] |= 0x00000010u; } else { - clear_has_json_name(); + _has_bits_[0] &= ~0x00000010u; } - json_name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), json_name, + json_name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), json_name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.json_name) } -inline ::std::string* FieldDescriptorProto::unsafe_arena_release_json_name() { +inline std::string* FieldDescriptorProto::unsafe_arena_release_json_name() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.json_name) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_json_name(); - return json_name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000010u; + return json_name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FieldDescriptorProto::unsafe_arena_set_allocated_json_name( - ::std::string* json_name) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (json_name != NULL) { - set_has_json_name(); + std::string* json_name) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (json_name != nullptr) { + _has_bits_[0] |= 0x00000010u; } else { - clear_has_json_name(); + _has_bits_[0] &= ~0x00000010u; } - json_name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + json_name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), json_name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.json_name) } @@ -7673,66 +7894,57 @@ inline void FieldDescriptorProto::unsafe_arena_set_allocated_json_name( inline bool FieldDescriptorProto::has_options() const { return (_has_bits_[0] & 0x00000020u) != 0; } -inline void FieldDescriptorProto::set_has_options() { - _has_bits_[0] |= 0x00000020u; -} -inline void FieldDescriptorProto::clear_has_options() { +inline void FieldDescriptorProto::clear_options() { + if (options_ != nullptr) options_->Clear(); _has_bits_[0] &= ~0x00000020u; } -inline void FieldDescriptorProto::clear_options() { - if (options_ != NULL) options_->Clear(); - clear_has_options(); -} -inline const ::google::protobuf::FieldOptions& FieldDescriptorProto::_internal_options() const { - return *options_; -} -inline const ::google::protobuf::FieldOptions& FieldDescriptorProto::options() const { - const ::google::protobuf::FieldOptions* p = options_; +inline const PROTOBUF_NAMESPACE_ID::FieldOptions& FieldDescriptorProto::options() const { + const PROTOBUF_NAMESPACE_ID::FieldOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.options) - return p != NULL ? *p : *reinterpret_cast( - &::google::protobuf::_FieldOptions_default_instance_); + return p != nullptr ? *p : *reinterpret_cast( + &PROTOBUF_NAMESPACE_ID::_FieldOptions_default_instance_); } -inline ::google::protobuf::FieldOptions* FieldDescriptorProto::release_options() { +inline PROTOBUF_NAMESPACE_ID::FieldOptions* FieldDescriptorProto::release_options() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.options) - clear_has_options(); - ::google::protobuf::FieldOptions* temp = options_; - if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); + _has_bits_[0] &= ~0x00000020u; + PROTOBUF_NAMESPACE_ID::FieldOptions* temp = options_; + if (GetArenaNoVirtual() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } - options_ = NULL; + options_ = nullptr; return temp; } -inline ::google::protobuf::FieldOptions* FieldDescriptorProto::unsafe_arena_release_options() { +inline PROTOBUF_NAMESPACE_ID::FieldOptions* FieldDescriptorProto::unsafe_arena_release_options() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.options) - clear_has_options(); - ::google::protobuf::FieldOptions* temp = options_; - options_ = NULL; + _has_bits_[0] &= ~0x00000020u; + PROTOBUF_NAMESPACE_ID::FieldOptions* temp = options_; + options_ = nullptr; return temp; } -inline ::google::protobuf::FieldOptions* FieldDescriptorProto::mutable_options() { - set_has_options(); - if (options_ == NULL) { - auto* p = CreateMaybeMessage<::google::protobuf::FieldOptions>(GetArenaNoVirtual()); +inline PROTOBUF_NAMESPACE_ID::FieldOptions* FieldDescriptorProto::mutable_options() { + _has_bits_[0] |= 0x00000020u; + if (options_ == nullptr) { + auto* p = CreateMaybeMessage(GetArenaNoVirtual()); options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.options) return options_; } -inline void FieldDescriptorProto::set_allocated_options(::google::protobuf::FieldOptions* options) { - ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); - if (message_arena == NULL) { +inline void FieldDescriptorProto::set_allocated_options(PROTOBUF_NAMESPACE_ID::FieldOptions* options) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); + if (message_arena == nullptr) { delete options_; } if (options) { - ::google::protobuf::Arena* submessage_arena = - ::google::protobuf::Arena::GetArena(options); + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::GetArena(options); if (message_arena != submessage_arena) { - options = ::google::protobuf::internal::GetOwnedMessage( + options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - set_has_options(); + _has_bits_[0] |= 0x00000020u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000020u; } options_ = options; // @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.options) @@ -7746,86 +7958,78 @@ inline void FieldDescriptorProto::set_allocated_options(::google::protobuf::Fiel inline bool OneofDescriptorProto::has_name() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void OneofDescriptorProto::set_has_name() { - _has_bits_[0] |= 0x00000001u; -} -inline void OneofDescriptorProto::clear_has_name() { +inline void OneofDescriptorProto::clear_name() { + name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000001u; } -inline void OneofDescriptorProto::clear_name() { - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_name(); -} -inline const ::std::string& OneofDescriptorProto::name() const { +inline const std::string& OneofDescriptorProto::name() const { // @@protoc_insertion_point(field_get:google.protobuf.OneofDescriptorProto.name) return name_.Get(); } -inline void OneofDescriptorProto::set_name(const ::std::string& value) { - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void OneofDescriptorProto::set_name(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.OneofDescriptorProto.name) } -#if LANG_CXX11 -inline void OneofDescriptorProto::set_name(::std::string&& value) { - set_has_name(); +inline void OneofDescriptorProto::set_name(std::string&& value) { + _has_bits_[0] |= 0x00000001u; name_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.OneofDescriptorProto.name) } -#endif inline void OneofDescriptorProto::set_name(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.OneofDescriptorProto.name) } inline void OneofDescriptorProto::set_name(const char* value, size_t size) { - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.OneofDescriptorProto.name) } -inline ::std::string* OneofDescriptorProto::mutable_name() { - set_has_name(); +inline std::string* OneofDescriptorProto::mutable_name() { + _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:google.protobuf.OneofDescriptorProto.name) - return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* OneofDescriptorProto::release_name() { +inline std::string* OneofDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.OneofDescriptorProto.name) if (!has_name()) { - return NULL; + return nullptr; } - clear_has_name(); - return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000001u; + return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void OneofDescriptorProto::set_allocated_name(::std::string* name) { - if (name != NULL) { - set_has_name(); +inline void OneofDescriptorProto::set_allocated_name(std::string* name) { + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name, + name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.OneofDescriptorProto.name) } -inline ::std::string* OneofDescriptorProto::unsafe_arena_release_name() { +inline std::string* OneofDescriptorProto::unsafe_arena_release_name() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.OneofDescriptorProto.name) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_name(); - return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000001u; + return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void OneofDescriptorProto::unsafe_arena_set_allocated_name( - ::std::string* name) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (name != NULL) { - set_has_name(); + std::string* name) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.OneofDescriptorProto.name) } @@ -7834,66 +8038,57 @@ inline void OneofDescriptorProto::unsafe_arena_set_allocated_name( inline bool OneofDescriptorProto::has_options() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void OneofDescriptorProto::set_has_options() { - _has_bits_[0] |= 0x00000002u; -} -inline void OneofDescriptorProto::clear_has_options() { +inline void OneofDescriptorProto::clear_options() { + if (options_ != nullptr) options_->Clear(); _has_bits_[0] &= ~0x00000002u; } -inline void OneofDescriptorProto::clear_options() { - if (options_ != NULL) options_->Clear(); - clear_has_options(); -} -inline const ::google::protobuf::OneofOptions& OneofDescriptorProto::_internal_options() const { - return *options_; -} -inline const ::google::protobuf::OneofOptions& OneofDescriptorProto::options() const { - const ::google::protobuf::OneofOptions* p = options_; +inline const PROTOBUF_NAMESPACE_ID::OneofOptions& OneofDescriptorProto::options() const { + const PROTOBUF_NAMESPACE_ID::OneofOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.OneofDescriptorProto.options) - return p != NULL ? *p : *reinterpret_cast( - &::google::protobuf::_OneofOptions_default_instance_); + return p != nullptr ? *p : *reinterpret_cast( + &PROTOBUF_NAMESPACE_ID::_OneofOptions_default_instance_); } -inline ::google::protobuf::OneofOptions* OneofDescriptorProto::release_options() { +inline PROTOBUF_NAMESPACE_ID::OneofOptions* OneofDescriptorProto::release_options() { // @@protoc_insertion_point(field_release:google.protobuf.OneofDescriptorProto.options) - clear_has_options(); - ::google::protobuf::OneofOptions* temp = options_; - if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); + _has_bits_[0] &= ~0x00000002u; + PROTOBUF_NAMESPACE_ID::OneofOptions* temp = options_; + if (GetArenaNoVirtual() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } - options_ = NULL; + options_ = nullptr; return temp; } -inline ::google::protobuf::OneofOptions* OneofDescriptorProto::unsafe_arena_release_options() { +inline PROTOBUF_NAMESPACE_ID::OneofOptions* OneofDescriptorProto::unsafe_arena_release_options() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.OneofDescriptorProto.options) - clear_has_options(); - ::google::protobuf::OneofOptions* temp = options_; - options_ = NULL; + _has_bits_[0] &= ~0x00000002u; + PROTOBUF_NAMESPACE_ID::OneofOptions* temp = options_; + options_ = nullptr; return temp; } -inline ::google::protobuf::OneofOptions* OneofDescriptorProto::mutable_options() { - set_has_options(); - if (options_ == NULL) { - auto* p = CreateMaybeMessage<::google::protobuf::OneofOptions>(GetArenaNoVirtual()); +inline PROTOBUF_NAMESPACE_ID::OneofOptions* OneofDescriptorProto::mutable_options() { + _has_bits_[0] |= 0x00000002u; + if (options_ == nullptr) { + auto* p = CreateMaybeMessage(GetArenaNoVirtual()); options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.OneofDescriptorProto.options) return options_; } -inline void OneofDescriptorProto::set_allocated_options(::google::protobuf::OneofOptions* options) { - ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); - if (message_arena == NULL) { +inline void OneofDescriptorProto::set_allocated_options(PROTOBUF_NAMESPACE_ID::OneofOptions* options) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); + if (message_arena == nullptr) { delete options_; } if (options) { - ::google::protobuf::Arena* submessage_arena = - ::google::protobuf::Arena::GetArena(options); + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::GetArena(options); if (message_arena != submessage_arena) { - options = ::google::protobuf::internal::GetOwnedMessage( + options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - set_has_options(); + _has_bits_[0] |= 0x00000002u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000002u; } options_ = options; // @@protoc_insertion_point(field_set_allocated:google.protobuf.OneofDescriptorProto.options) @@ -7907,22 +8102,16 @@ inline void OneofDescriptorProto::set_allocated_options(::google::protobuf::Oneo inline bool EnumDescriptorProto_EnumReservedRange::has_start() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void EnumDescriptorProto_EnumReservedRange::set_has_start() { - _has_bits_[0] |= 0x00000001u; -} -inline void EnumDescriptorProto_EnumReservedRange::clear_has_start() { - _has_bits_[0] &= ~0x00000001u; -} inline void EnumDescriptorProto_EnumReservedRange::clear_start() { start_ = 0; - clear_has_start(); + _has_bits_[0] &= ~0x00000001u; } -inline ::google::protobuf::int32 EnumDescriptorProto_EnumReservedRange::start() const { +inline ::PROTOBUF_NAMESPACE_ID::int32 EnumDescriptorProto_EnumReservedRange::start() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.EnumReservedRange.start) return start_; } -inline void EnumDescriptorProto_EnumReservedRange::set_start(::google::protobuf::int32 value) { - set_has_start(); +inline void EnumDescriptorProto_EnumReservedRange::set_start(::PROTOBUF_NAMESPACE_ID::int32 value) { + _has_bits_[0] |= 0x00000001u; start_ = value; // @@protoc_insertion_point(field_set:google.protobuf.EnumDescriptorProto.EnumReservedRange.start) } @@ -7931,22 +8120,16 @@ inline void EnumDescriptorProto_EnumReservedRange::set_start(::google::protobuf: inline bool EnumDescriptorProto_EnumReservedRange::has_end() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void EnumDescriptorProto_EnumReservedRange::set_has_end() { - _has_bits_[0] |= 0x00000002u; -} -inline void EnumDescriptorProto_EnumReservedRange::clear_has_end() { - _has_bits_[0] &= ~0x00000002u; -} inline void EnumDescriptorProto_EnumReservedRange::clear_end() { end_ = 0; - clear_has_end(); + _has_bits_[0] &= ~0x00000002u; } -inline ::google::protobuf::int32 EnumDescriptorProto_EnumReservedRange::end() const { +inline ::PROTOBUF_NAMESPACE_ID::int32 EnumDescriptorProto_EnumReservedRange::end() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.EnumReservedRange.end) return end_; } -inline void EnumDescriptorProto_EnumReservedRange::set_end(::google::protobuf::int32 value) { - set_has_end(); +inline void EnumDescriptorProto_EnumReservedRange::set_end(::PROTOBUF_NAMESPACE_ID::int32 value) { + _has_bits_[0] |= 0x00000002u; end_ = value; // @@protoc_insertion_point(field_set:google.protobuf.EnumDescriptorProto.EnumReservedRange.end) } @@ -7959,86 +8142,78 @@ inline void EnumDescriptorProto_EnumReservedRange::set_end(::google::protobuf::i inline bool EnumDescriptorProto::has_name() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void EnumDescriptorProto::set_has_name() { - _has_bits_[0] |= 0x00000001u; -} -inline void EnumDescriptorProto::clear_has_name() { +inline void EnumDescriptorProto::clear_name() { + name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000001u; } -inline void EnumDescriptorProto::clear_name() { - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_name(); -} -inline const ::std::string& EnumDescriptorProto::name() const { +inline const std::string& EnumDescriptorProto::name() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.name) return name_.Get(); } -inline void EnumDescriptorProto::set_name(const ::std::string& value) { - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void EnumDescriptorProto::set_name(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.EnumDescriptorProto.name) } -#if LANG_CXX11 -inline void EnumDescriptorProto::set_name(::std::string&& value) { - set_has_name(); +inline void EnumDescriptorProto::set_name(std::string&& value) { + _has_bits_[0] |= 0x00000001u; name_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.EnumDescriptorProto.name) } -#endif inline void EnumDescriptorProto::set_name(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.EnumDescriptorProto.name) } inline void EnumDescriptorProto::set_name(const char* value, size_t size) { - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.EnumDescriptorProto.name) } -inline ::std::string* EnumDescriptorProto::mutable_name() { - set_has_name(); +inline std::string* EnumDescriptorProto::mutable_name() { + _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.name) - return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* EnumDescriptorProto::release_name() { +inline std::string* EnumDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.EnumDescriptorProto.name) if (!has_name()) { - return NULL; + return nullptr; } - clear_has_name(); - return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000001u; + return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void EnumDescriptorProto::set_allocated_name(::std::string* name) { - if (name != NULL) { - set_has_name(); +inline void EnumDescriptorProto::set_allocated_name(std::string* name) { + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name, + name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumDescriptorProto.name) } -inline ::std::string* EnumDescriptorProto::unsafe_arena_release_name() { +inline std::string* EnumDescriptorProto::unsafe_arena_release_name() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumDescriptorProto.name) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_name(); - return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000001u; + return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void EnumDescriptorProto::unsafe_arena_set_allocated_name( - ::std::string* name) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (name != NULL) { - set_has_name(); + std::string* name) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumDescriptorProto.name) } @@ -8050,24 +8225,24 @@ inline int EnumDescriptorProto::value_size() const { inline void EnumDescriptorProto::clear_value() { value_.Clear(); } -inline ::google::protobuf::EnumValueDescriptorProto* EnumDescriptorProto::mutable_value(int index) { +inline PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto* EnumDescriptorProto::mutable_value(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.value) return value_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto >* EnumDescriptorProto::mutable_value() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumDescriptorProto.value) return &value_; } -inline const ::google::protobuf::EnumValueDescriptorProto& EnumDescriptorProto::value(int index) const { +inline const PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto& EnumDescriptorProto::value(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.value) return value_.Get(index); } -inline ::google::protobuf::EnumValueDescriptorProto* EnumDescriptorProto::add_value() { +inline PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto* EnumDescriptorProto::add_value() { // @@protoc_insertion_point(field_add:google.protobuf.EnumDescriptorProto.value) return value_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto >& EnumDescriptorProto::value() const { // @@protoc_insertion_point(field_list:google.protobuf.EnumDescriptorProto.value) return value_; @@ -8077,66 +8252,57 @@ EnumDescriptorProto::value() const { inline bool EnumDescriptorProto::has_options() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void EnumDescriptorProto::set_has_options() { - _has_bits_[0] |= 0x00000002u; -} -inline void EnumDescriptorProto::clear_has_options() { +inline void EnumDescriptorProto::clear_options() { + if (options_ != nullptr) options_->Clear(); _has_bits_[0] &= ~0x00000002u; } -inline void EnumDescriptorProto::clear_options() { - if (options_ != NULL) options_->Clear(); - clear_has_options(); -} -inline const ::google::protobuf::EnumOptions& EnumDescriptorProto::_internal_options() const { - return *options_; -} -inline const ::google::protobuf::EnumOptions& EnumDescriptorProto::options() const { - const ::google::protobuf::EnumOptions* p = options_; +inline const PROTOBUF_NAMESPACE_ID::EnumOptions& EnumDescriptorProto::options() const { + const PROTOBUF_NAMESPACE_ID::EnumOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.options) - return p != NULL ? *p : *reinterpret_cast( - &::google::protobuf::_EnumOptions_default_instance_); + return p != nullptr ? *p : *reinterpret_cast( + &PROTOBUF_NAMESPACE_ID::_EnumOptions_default_instance_); } -inline ::google::protobuf::EnumOptions* EnumDescriptorProto::release_options() { +inline PROTOBUF_NAMESPACE_ID::EnumOptions* EnumDescriptorProto::release_options() { // @@protoc_insertion_point(field_release:google.protobuf.EnumDescriptorProto.options) - clear_has_options(); - ::google::protobuf::EnumOptions* temp = options_; - if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); + _has_bits_[0] &= ~0x00000002u; + PROTOBUF_NAMESPACE_ID::EnumOptions* temp = options_; + if (GetArenaNoVirtual() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } - options_ = NULL; + options_ = nullptr; return temp; } -inline ::google::protobuf::EnumOptions* EnumDescriptorProto::unsafe_arena_release_options() { +inline PROTOBUF_NAMESPACE_ID::EnumOptions* EnumDescriptorProto::unsafe_arena_release_options() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumDescriptorProto.options) - clear_has_options(); - ::google::protobuf::EnumOptions* temp = options_; - options_ = NULL; + _has_bits_[0] &= ~0x00000002u; + PROTOBUF_NAMESPACE_ID::EnumOptions* temp = options_; + options_ = nullptr; return temp; } -inline ::google::protobuf::EnumOptions* EnumDescriptorProto::mutable_options() { - set_has_options(); - if (options_ == NULL) { - auto* p = CreateMaybeMessage<::google::protobuf::EnumOptions>(GetArenaNoVirtual()); +inline PROTOBUF_NAMESPACE_ID::EnumOptions* EnumDescriptorProto::mutable_options() { + _has_bits_[0] |= 0x00000002u; + if (options_ == nullptr) { + auto* p = CreateMaybeMessage(GetArenaNoVirtual()); options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.options) return options_; } -inline void EnumDescriptorProto::set_allocated_options(::google::protobuf::EnumOptions* options) { - ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); - if (message_arena == NULL) { +inline void EnumDescriptorProto::set_allocated_options(PROTOBUF_NAMESPACE_ID::EnumOptions* options) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); + if (message_arena == nullptr) { delete options_; } if (options) { - ::google::protobuf::Arena* submessage_arena = - ::google::protobuf::Arena::GetArena(options); + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::GetArena(options); if (message_arena != submessage_arena) { - options = ::google::protobuf::internal::GetOwnedMessage( + options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - set_has_options(); + _has_bits_[0] |= 0x00000002u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000002u; } options_ = options; // @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumDescriptorProto.options) @@ -8149,24 +8315,24 @@ inline int EnumDescriptorProto::reserved_range_size() const { inline void EnumDescriptorProto::clear_reserved_range() { reserved_range_.Clear(); } -inline ::google::protobuf::EnumDescriptorProto_EnumReservedRange* EnumDescriptorProto::mutable_reserved_range(int index) { +inline PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange* EnumDescriptorProto::mutable_reserved_range(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.reserved_range) return reserved_range_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange >* EnumDescriptorProto::mutable_reserved_range() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumDescriptorProto.reserved_range) return &reserved_range_; } -inline const ::google::protobuf::EnumDescriptorProto_EnumReservedRange& EnumDescriptorProto::reserved_range(int index) const { +inline const PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange& EnumDescriptorProto::reserved_range(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.reserved_range) return reserved_range_.Get(index); } -inline ::google::protobuf::EnumDescriptorProto_EnumReservedRange* EnumDescriptorProto::add_reserved_range() { +inline PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange* EnumDescriptorProto::add_reserved_range() { // @@protoc_insertion_point(field_add:google.protobuf.EnumDescriptorProto.reserved_range) return reserved_range_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange >& EnumDescriptorProto::reserved_range() const { // @@protoc_insertion_point(field_list:google.protobuf.EnumDescriptorProto.reserved_range) return reserved_range_; @@ -8179,26 +8345,24 @@ inline int EnumDescriptorProto::reserved_name_size() const { inline void EnumDescriptorProto::clear_reserved_name() { reserved_name_.Clear(); } -inline const ::std::string& EnumDescriptorProto::reserved_name(int index) const { +inline const std::string& EnumDescriptorProto::reserved_name(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.reserved_name) return reserved_name_.Get(index); } -inline ::std::string* EnumDescriptorProto::mutable_reserved_name(int index) { +inline std::string* EnumDescriptorProto::mutable_reserved_name(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.reserved_name) return reserved_name_.Mutable(index); } -inline void EnumDescriptorProto::set_reserved_name(int index, const ::std::string& value) { +inline void EnumDescriptorProto::set_reserved_name(int index, const std::string& value) { // @@protoc_insertion_point(field_set:google.protobuf.EnumDescriptorProto.reserved_name) reserved_name_.Mutable(index)->assign(value); } -#if LANG_CXX11 -inline void EnumDescriptorProto::set_reserved_name(int index, ::std::string&& value) { +inline void EnumDescriptorProto::set_reserved_name(int index, std::string&& value) { // @@protoc_insertion_point(field_set:google.protobuf.EnumDescriptorProto.reserved_name) reserved_name_.Mutable(index)->assign(std::move(value)); } -#endif inline void EnumDescriptorProto::set_reserved_name(int index, const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); reserved_name_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.protobuf.EnumDescriptorProto.reserved_name) } @@ -8207,22 +8371,20 @@ inline void EnumDescriptorProto::set_reserved_name(int index, const char* value, reinterpret_cast(value), size); // @@protoc_insertion_point(field_set_pointer:google.protobuf.EnumDescriptorProto.reserved_name) } -inline ::std::string* EnumDescriptorProto::add_reserved_name() { +inline std::string* EnumDescriptorProto::add_reserved_name() { // @@protoc_insertion_point(field_add_mutable:google.protobuf.EnumDescriptorProto.reserved_name) return reserved_name_.Add(); } -inline void EnumDescriptorProto::add_reserved_name(const ::std::string& value) { +inline void EnumDescriptorProto::add_reserved_name(const std::string& value) { reserved_name_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.protobuf.EnumDescriptorProto.reserved_name) } -#if LANG_CXX11 -inline void EnumDescriptorProto::add_reserved_name(::std::string&& value) { +inline void EnumDescriptorProto::add_reserved_name(std::string&& value) { reserved_name_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.protobuf.EnumDescriptorProto.reserved_name) } -#endif inline void EnumDescriptorProto::add_reserved_name(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); reserved_name_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.protobuf.EnumDescriptorProto.reserved_name) } @@ -8230,12 +8392,12 @@ inline void EnumDescriptorProto::add_reserved_name(const char* value, size_t siz reserved_name_.Add()->assign(reinterpret_cast(value), size); // @@protoc_insertion_point(field_add_pointer:google.protobuf.EnumDescriptorProto.reserved_name) } -inline const ::google::protobuf::RepeatedPtrField< ::std::string>& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& EnumDescriptorProto::reserved_name() const { // @@protoc_insertion_point(field_list:google.protobuf.EnumDescriptorProto.reserved_name) return reserved_name_; } -inline ::google::protobuf::RepeatedPtrField< ::std::string>* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* EnumDescriptorProto::mutable_reserved_name() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumDescriptorProto.reserved_name) return &reserved_name_; @@ -8249,86 +8411,78 @@ EnumDescriptorProto::mutable_reserved_name() { inline bool EnumValueDescriptorProto::has_name() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void EnumValueDescriptorProto::set_has_name() { - _has_bits_[0] |= 0x00000001u; -} -inline void EnumValueDescriptorProto::clear_has_name() { +inline void EnumValueDescriptorProto::clear_name() { + name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000001u; } -inline void EnumValueDescriptorProto::clear_name() { - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_name(); -} -inline const ::std::string& EnumValueDescriptorProto::name() const { +inline const std::string& EnumValueDescriptorProto::name() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.name) return name_.Get(); } -inline void EnumValueDescriptorProto::set_name(const ::std::string& value) { - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void EnumValueDescriptorProto::set_name(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.EnumValueDescriptorProto.name) } -#if LANG_CXX11 -inline void EnumValueDescriptorProto::set_name(::std::string&& value) { - set_has_name(); +inline void EnumValueDescriptorProto::set_name(std::string&& value) { + _has_bits_[0] |= 0x00000001u; name_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.EnumValueDescriptorProto.name) } -#endif inline void EnumValueDescriptorProto::set_name(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.EnumValueDescriptorProto.name) } inline void EnumValueDescriptorProto::set_name(const char* value, size_t size) { - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.EnumValueDescriptorProto.name) } -inline ::std::string* EnumValueDescriptorProto::mutable_name() { - set_has_name(); +inline std::string* EnumValueDescriptorProto::mutable_name() { + _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:google.protobuf.EnumValueDescriptorProto.name) - return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* EnumValueDescriptorProto::release_name() { +inline std::string* EnumValueDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.EnumValueDescriptorProto.name) if (!has_name()) { - return NULL; + return nullptr; } - clear_has_name(); - return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000001u; + return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void EnumValueDescriptorProto::set_allocated_name(::std::string* name) { - if (name != NULL) { - set_has_name(); +inline void EnumValueDescriptorProto::set_allocated_name(std::string* name) { + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name, + name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValueDescriptorProto.name) } -inline ::std::string* EnumValueDescriptorProto::unsafe_arena_release_name() { +inline std::string* EnumValueDescriptorProto::unsafe_arena_release_name() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumValueDescriptorProto.name) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_name(); - return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000001u; + return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void EnumValueDescriptorProto::unsafe_arena_set_allocated_name( - ::std::string* name) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (name != NULL) { - set_has_name(); + std::string* name) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumValueDescriptorProto.name) } @@ -8337,22 +8491,16 @@ inline void EnumValueDescriptorProto::unsafe_arena_set_allocated_name( inline bool EnumValueDescriptorProto::has_number() const { return (_has_bits_[0] & 0x00000004u) != 0; } -inline void EnumValueDescriptorProto::set_has_number() { - _has_bits_[0] |= 0x00000004u; -} -inline void EnumValueDescriptorProto::clear_has_number() { - _has_bits_[0] &= ~0x00000004u; -} inline void EnumValueDescriptorProto::clear_number() { number_ = 0; - clear_has_number(); + _has_bits_[0] &= ~0x00000004u; } -inline ::google::protobuf::int32 EnumValueDescriptorProto::number() const { +inline ::PROTOBUF_NAMESPACE_ID::int32 EnumValueDescriptorProto::number() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.number) return number_; } -inline void EnumValueDescriptorProto::set_number(::google::protobuf::int32 value) { - set_has_number(); +inline void EnumValueDescriptorProto::set_number(::PROTOBUF_NAMESPACE_ID::int32 value) { + _has_bits_[0] |= 0x00000004u; number_ = value; // @@protoc_insertion_point(field_set:google.protobuf.EnumValueDescriptorProto.number) } @@ -8361,66 +8509,57 @@ inline void EnumValueDescriptorProto::set_number(::google::protobuf::int32 value inline bool EnumValueDescriptorProto::has_options() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void EnumValueDescriptorProto::set_has_options() { - _has_bits_[0] |= 0x00000002u; -} -inline void EnumValueDescriptorProto::clear_has_options() { +inline void EnumValueDescriptorProto::clear_options() { + if (options_ != nullptr) options_->Clear(); _has_bits_[0] &= ~0x00000002u; } -inline void EnumValueDescriptorProto::clear_options() { - if (options_ != NULL) options_->Clear(); - clear_has_options(); -} -inline const ::google::protobuf::EnumValueOptions& EnumValueDescriptorProto::_internal_options() const { - return *options_; -} -inline const ::google::protobuf::EnumValueOptions& EnumValueDescriptorProto::options() const { - const ::google::protobuf::EnumValueOptions* p = options_; +inline const PROTOBUF_NAMESPACE_ID::EnumValueOptions& EnumValueDescriptorProto::options() const { + const PROTOBUF_NAMESPACE_ID::EnumValueOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.options) - return p != NULL ? *p : *reinterpret_cast( - &::google::protobuf::_EnumValueOptions_default_instance_); + return p != nullptr ? *p : *reinterpret_cast( + &PROTOBUF_NAMESPACE_ID::_EnumValueOptions_default_instance_); } -inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::release_options() { +inline PROTOBUF_NAMESPACE_ID::EnumValueOptions* EnumValueDescriptorProto::release_options() { // @@protoc_insertion_point(field_release:google.protobuf.EnumValueDescriptorProto.options) - clear_has_options(); - ::google::protobuf::EnumValueOptions* temp = options_; - if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); + _has_bits_[0] &= ~0x00000002u; + PROTOBUF_NAMESPACE_ID::EnumValueOptions* temp = options_; + if (GetArenaNoVirtual() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } - options_ = NULL; + options_ = nullptr; return temp; } -inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::unsafe_arena_release_options() { +inline PROTOBUF_NAMESPACE_ID::EnumValueOptions* EnumValueDescriptorProto::unsafe_arena_release_options() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumValueDescriptorProto.options) - clear_has_options(); - ::google::protobuf::EnumValueOptions* temp = options_; - options_ = NULL; + _has_bits_[0] &= ~0x00000002u; + PROTOBUF_NAMESPACE_ID::EnumValueOptions* temp = options_; + options_ = nullptr; return temp; } -inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::mutable_options() { - set_has_options(); - if (options_ == NULL) { - auto* p = CreateMaybeMessage<::google::protobuf::EnumValueOptions>(GetArenaNoVirtual()); +inline PROTOBUF_NAMESPACE_ID::EnumValueOptions* EnumValueDescriptorProto::mutable_options() { + _has_bits_[0] |= 0x00000002u; + if (options_ == nullptr) { + auto* p = CreateMaybeMessage(GetArenaNoVirtual()); options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.EnumValueDescriptorProto.options) return options_; } -inline void EnumValueDescriptorProto::set_allocated_options(::google::protobuf::EnumValueOptions* options) { - ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); - if (message_arena == NULL) { +inline void EnumValueDescriptorProto::set_allocated_options(PROTOBUF_NAMESPACE_ID::EnumValueOptions* options) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); + if (message_arena == nullptr) { delete options_; } if (options) { - ::google::protobuf::Arena* submessage_arena = - ::google::protobuf::Arena::GetArena(options); + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::GetArena(options); if (message_arena != submessage_arena) { - options = ::google::protobuf::internal::GetOwnedMessage( + options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - set_has_options(); + _has_bits_[0] |= 0x00000002u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000002u; } options_ = options; // @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValueDescriptorProto.options) @@ -8434,86 +8573,78 @@ inline void EnumValueDescriptorProto::set_allocated_options(::google::protobuf:: inline bool ServiceDescriptorProto::has_name() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void ServiceDescriptorProto::set_has_name() { - _has_bits_[0] |= 0x00000001u; -} -inline void ServiceDescriptorProto::clear_has_name() { +inline void ServiceDescriptorProto::clear_name() { + name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000001u; } -inline void ServiceDescriptorProto::clear_name() { - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_name(); -} -inline const ::std::string& ServiceDescriptorProto::name() const { +inline const std::string& ServiceDescriptorProto::name() const { // @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.name) return name_.Get(); } -inline void ServiceDescriptorProto::set_name(const ::std::string& value) { - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void ServiceDescriptorProto::set_name(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.ServiceDescriptorProto.name) } -#if LANG_CXX11 -inline void ServiceDescriptorProto::set_name(::std::string&& value) { - set_has_name(); +inline void ServiceDescriptorProto::set_name(std::string&& value) { + _has_bits_[0] |= 0x00000001u; name_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.ServiceDescriptorProto.name) } -#endif inline void ServiceDescriptorProto::set_name(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.ServiceDescriptorProto.name) } inline void ServiceDescriptorProto::set_name(const char* value, size_t size) { - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.ServiceDescriptorProto.name) } -inline ::std::string* ServiceDescriptorProto::mutable_name() { - set_has_name(); +inline std::string* ServiceDescriptorProto::mutable_name() { + _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:google.protobuf.ServiceDescriptorProto.name) - return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* ServiceDescriptorProto::release_name() { +inline std::string* ServiceDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.ServiceDescriptorProto.name) if (!has_name()) { - return NULL; + return nullptr; } - clear_has_name(); - return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000001u; + return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void ServiceDescriptorProto::set_allocated_name(::std::string* name) { - if (name != NULL) { - set_has_name(); +inline void ServiceDescriptorProto::set_allocated_name(std::string* name) { + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name, + name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.ServiceDescriptorProto.name) } -inline ::std::string* ServiceDescriptorProto::unsafe_arena_release_name() { +inline std::string* ServiceDescriptorProto::unsafe_arena_release_name() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.ServiceDescriptorProto.name) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_name(); - return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000001u; + return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void ServiceDescriptorProto::unsafe_arena_set_allocated_name( - ::std::string* name) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (name != NULL) { - set_has_name(); + std::string* name) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.ServiceDescriptorProto.name) } @@ -8525,24 +8656,24 @@ inline int ServiceDescriptorProto::method_size() const { inline void ServiceDescriptorProto::clear_method() { method_.Clear(); } -inline ::google::protobuf::MethodDescriptorProto* ServiceDescriptorProto::mutable_method(int index) { +inline PROTOBUF_NAMESPACE_ID::MethodDescriptorProto* ServiceDescriptorProto::mutable_method(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.ServiceDescriptorProto.method) return method_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::MethodDescriptorProto >* ServiceDescriptorProto::mutable_method() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.ServiceDescriptorProto.method) return &method_; } -inline const ::google::protobuf::MethodDescriptorProto& ServiceDescriptorProto::method(int index) const { +inline const PROTOBUF_NAMESPACE_ID::MethodDescriptorProto& ServiceDescriptorProto::method(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.method) return method_.Get(index); } -inline ::google::protobuf::MethodDescriptorProto* ServiceDescriptorProto::add_method() { +inline PROTOBUF_NAMESPACE_ID::MethodDescriptorProto* ServiceDescriptorProto::add_method() { // @@protoc_insertion_point(field_add:google.protobuf.ServiceDescriptorProto.method) return method_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::MethodDescriptorProto >& ServiceDescriptorProto::method() const { // @@protoc_insertion_point(field_list:google.protobuf.ServiceDescriptorProto.method) return method_; @@ -8552,66 +8683,57 @@ ServiceDescriptorProto::method() const { inline bool ServiceDescriptorProto::has_options() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void ServiceDescriptorProto::set_has_options() { - _has_bits_[0] |= 0x00000002u; -} -inline void ServiceDescriptorProto::clear_has_options() { +inline void ServiceDescriptorProto::clear_options() { + if (options_ != nullptr) options_->Clear(); _has_bits_[0] &= ~0x00000002u; } -inline void ServiceDescriptorProto::clear_options() { - if (options_ != NULL) options_->Clear(); - clear_has_options(); -} -inline const ::google::protobuf::ServiceOptions& ServiceDescriptorProto::_internal_options() const { - return *options_; -} -inline const ::google::protobuf::ServiceOptions& ServiceDescriptorProto::options() const { - const ::google::protobuf::ServiceOptions* p = options_; +inline const PROTOBUF_NAMESPACE_ID::ServiceOptions& ServiceDescriptorProto::options() const { + const PROTOBUF_NAMESPACE_ID::ServiceOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.options) - return p != NULL ? *p : *reinterpret_cast( - &::google::protobuf::_ServiceOptions_default_instance_); + return p != nullptr ? *p : *reinterpret_cast( + &PROTOBUF_NAMESPACE_ID::_ServiceOptions_default_instance_); } -inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::release_options() { +inline PROTOBUF_NAMESPACE_ID::ServiceOptions* ServiceDescriptorProto::release_options() { // @@protoc_insertion_point(field_release:google.protobuf.ServiceDescriptorProto.options) - clear_has_options(); - ::google::protobuf::ServiceOptions* temp = options_; - if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); + _has_bits_[0] &= ~0x00000002u; + PROTOBUF_NAMESPACE_ID::ServiceOptions* temp = options_; + if (GetArenaNoVirtual() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } - options_ = NULL; + options_ = nullptr; return temp; } -inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::unsafe_arena_release_options() { +inline PROTOBUF_NAMESPACE_ID::ServiceOptions* ServiceDescriptorProto::unsafe_arena_release_options() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.ServiceDescriptorProto.options) - clear_has_options(); - ::google::protobuf::ServiceOptions* temp = options_; - options_ = NULL; + _has_bits_[0] &= ~0x00000002u; + PROTOBUF_NAMESPACE_ID::ServiceOptions* temp = options_; + options_ = nullptr; return temp; } -inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::mutable_options() { - set_has_options(); - if (options_ == NULL) { - auto* p = CreateMaybeMessage<::google::protobuf::ServiceOptions>(GetArenaNoVirtual()); +inline PROTOBUF_NAMESPACE_ID::ServiceOptions* ServiceDescriptorProto::mutable_options() { + _has_bits_[0] |= 0x00000002u; + if (options_ == nullptr) { + auto* p = CreateMaybeMessage(GetArenaNoVirtual()); options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.ServiceDescriptorProto.options) return options_; } -inline void ServiceDescriptorProto::set_allocated_options(::google::protobuf::ServiceOptions* options) { - ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); - if (message_arena == NULL) { +inline void ServiceDescriptorProto::set_allocated_options(PROTOBUF_NAMESPACE_ID::ServiceOptions* options) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); + if (message_arena == nullptr) { delete options_; } if (options) { - ::google::protobuf::Arena* submessage_arena = - ::google::protobuf::Arena::GetArena(options); + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::GetArena(options); if (message_arena != submessage_arena) { - options = ::google::protobuf::internal::GetOwnedMessage( + options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - set_has_options(); + _has_bits_[0] |= 0x00000002u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000002u; } options_ = options; // @@protoc_insertion_point(field_set_allocated:google.protobuf.ServiceDescriptorProto.options) @@ -8625,86 +8747,78 @@ inline void ServiceDescriptorProto::set_allocated_options(::google::protobuf::Se inline bool MethodDescriptorProto::has_name() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void MethodDescriptorProto::set_has_name() { - _has_bits_[0] |= 0x00000001u; -} -inline void MethodDescriptorProto::clear_has_name() { +inline void MethodDescriptorProto::clear_name() { + name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000001u; } -inline void MethodDescriptorProto::clear_name() { - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_name(); -} -inline const ::std::string& MethodDescriptorProto::name() const { +inline const std::string& MethodDescriptorProto::name() const { // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.name) return name_.Get(); } -inline void MethodDescriptorProto::set_name(const ::std::string& value) { - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void MethodDescriptorProto::set_name(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.name) } -#if LANG_CXX11 -inline void MethodDescriptorProto::set_name(::std::string&& value) { - set_has_name(); +inline void MethodDescriptorProto::set_name(std::string&& value) { + _has_bits_[0] |= 0x00000001u; name_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.MethodDescriptorProto.name) } -#endif inline void MethodDescriptorProto::set_name(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.MethodDescriptorProto.name) } inline void MethodDescriptorProto::set_name(const char* value, size_t size) { - set_has_name(); - name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000001u; + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.MethodDescriptorProto.name) } -inline ::std::string* MethodDescriptorProto::mutable_name() { - set_has_name(); +inline std::string* MethodDescriptorProto::mutable_name() { + _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.name) - return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* MethodDescriptorProto::release_name() { +inline std::string* MethodDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.name) if (!has_name()) { - return NULL; + return nullptr; } - clear_has_name(); - return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000001u; + return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void MethodDescriptorProto::set_allocated_name(::std::string* name) { - if (name != NULL) { - set_has_name(); +inline void MethodDescriptorProto::set_allocated_name(std::string* name) { + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name, + name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.name) } -inline ::std::string* MethodDescriptorProto::unsafe_arena_release_name() { +inline std::string* MethodDescriptorProto::unsafe_arena_release_name() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.MethodDescriptorProto.name) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_name(); - return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000001u; + return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void MethodDescriptorProto::unsafe_arena_set_allocated_name( - ::std::string* name) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (name != NULL) { - set_has_name(); + std::string* name) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.MethodDescriptorProto.name) } @@ -8713,86 +8827,78 @@ inline void MethodDescriptorProto::unsafe_arena_set_allocated_name( inline bool MethodDescriptorProto::has_input_type() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void MethodDescriptorProto::set_has_input_type() { - _has_bits_[0] |= 0x00000002u; -} -inline void MethodDescriptorProto::clear_has_input_type() { +inline void MethodDescriptorProto::clear_input_type() { + input_type_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000002u; } -inline void MethodDescriptorProto::clear_input_type() { - input_type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_input_type(); -} -inline const ::std::string& MethodDescriptorProto::input_type() const { +inline const std::string& MethodDescriptorProto::input_type() const { // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.input_type) return input_type_.Get(); } -inline void MethodDescriptorProto::set_input_type(const ::std::string& value) { - set_has_input_type(); - input_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void MethodDescriptorProto::set_input_type(const std::string& value) { + _has_bits_[0] |= 0x00000002u; + input_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.input_type) } -#if LANG_CXX11 -inline void MethodDescriptorProto::set_input_type(::std::string&& value) { - set_has_input_type(); +inline void MethodDescriptorProto::set_input_type(std::string&& value) { + _has_bits_[0] |= 0x00000002u; input_type_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.MethodDescriptorProto.input_type) } -#endif inline void MethodDescriptorProto::set_input_type(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_input_type(); - input_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000002u; + input_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.MethodDescriptorProto.input_type) } inline void MethodDescriptorProto::set_input_type(const char* value, size_t size) { - set_has_input_type(); - input_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000002u; + input_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.MethodDescriptorProto.input_type) } -inline ::std::string* MethodDescriptorProto::mutable_input_type() { - set_has_input_type(); +inline std::string* MethodDescriptorProto::mutable_input_type() { + _has_bits_[0] |= 0x00000002u; // @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.input_type) - return input_type_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return input_type_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* MethodDescriptorProto::release_input_type() { +inline std::string* MethodDescriptorProto::release_input_type() { // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.input_type) if (!has_input_type()) { - return NULL; + return nullptr; } - clear_has_input_type(); - return input_type_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000002u; + return input_type_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void MethodDescriptorProto::set_allocated_input_type(::std::string* input_type) { - if (input_type != NULL) { - set_has_input_type(); +inline void MethodDescriptorProto::set_allocated_input_type(std::string* input_type) { + if (input_type != nullptr) { + _has_bits_[0] |= 0x00000002u; } else { - clear_has_input_type(); + _has_bits_[0] &= ~0x00000002u; } - input_type_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), input_type, + input_type_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), input_type, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.input_type) } -inline ::std::string* MethodDescriptorProto::unsafe_arena_release_input_type() { +inline std::string* MethodDescriptorProto::unsafe_arena_release_input_type() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.MethodDescriptorProto.input_type) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_input_type(); - return input_type_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000002u; + return input_type_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void MethodDescriptorProto::unsafe_arena_set_allocated_input_type( - ::std::string* input_type) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (input_type != NULL) { - set_has_input_type(); + std::string* input_type) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (input_type != nullptr) { + _has_bits_[0] |= 0x00000002u; } else { - clear_has_input_type(); + _has_bits_[0] &= ~0x00000002u; } - input_type_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + input_type_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), input_type, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.MethodDescriptorProto.input_type) } @@ -8801,86 +8907,78 @@ inline void MethodDescriptorProto::unsafe_arena_set_allocated_input_type( inline bool MethodDescriptorProto::has_output_type() const { return (_has_bits_[0] & 0x00000004u) != 0; } -inline void MethodDescriptorProto::set_has_output_type() { - _has_bits_[0] |= 0x00000004u; -} -inline void MethodDescriptorProto::clear_has_output_type() { +inline void MethodDescriptorProto::clear_output_type() { + output_type_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000004u; } -inline void MethodDescriptorProto::clear_output_type() { - output_type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_output_type(); -} -inline const ::std::string& MethodDescriptorProto::output_type() const { +inline const std::string& MethodDescriptorProto::output_type() const { // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.output_type) return output_type_.Get(); } -inline void MethodDescriptorProto::set_output_type(const ::std::string& value) { - set_has_output_type(); - output_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void MethodDescriptorProto::set_output_type(const std::string& value) { + _has_bits_[0] |= 0x00000004u; + output_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.output_type) } -#if LANG_CXX11 -inline void MethodDescriptorProto::set_output_type(::std::string&& value) { - set_has_output_type(); +inline void MethodDescriptorProto::set_output_type(std::string&& value) { + _has_bits_[0] |= 0x00000004u; output_type_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.MethodDescriptorProto.output_type) } -#endif inline void MethodDescriptorProto::set_output_type(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_output_type(); - output_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000004u; + output_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.MethodDescriptorProto.output_type) } inline void MethodDescriptorProto::set_output_type(const char* value, size_t size) { - set_has_output_type(); - output_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000004u; + output_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.MethodDescriptorProto.output_type) } -inline ::std::string* MethodDescriptorProto::mutable_output_type() { - set_has_output_type(); +inline std::string* MethodDescriptorProto::mutable_output_type() { + _has_bits_[0] |= 0x00000004u; // @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.output_type) - return output_type_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return output_type_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* MethodDescriptorProto::release_output_type() { +inline std::string* MethodDescriptorProto::release_output_type() { // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.output_type) if (!has_output_type()) { - return NULL; + return nullptr; } - clear_has_output_type(); - return output_type_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000004u; + return output_type_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void MethodDescriptorProto::set_allocated_output_type(::std::string* output_type) { - if (output_type != NULL) { - set_has_output_type(); +inline void MethodDescriptorProto::set_allocated_output_type(std::string* output_type) { + if (output_type != nullptr) { + _has_bits_[0] |= 0x00000004u; } else { - clear_has_output_type(); + _has_bits_[0] &= ~0x00000004u; } - output_type_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), output_type, + output_type_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), output_type, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.output_type) } -inline ::std::string* MethodDescriptorProto::unsafe_arena_release_output_type() { +inline std::string* MethodDescriptorProto::unsafe_arena_release_output_type() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.MethodDescriptorProto.output_type) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_output_type(); - return output_type_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000004u; + return output_type_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void MethodDescriptorProto::unsafe_arena_set_allocated_output_type( - ::std::string* output_type) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (output_type != NULL) { - set_has_output_type(); + std::string* output_type) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (output_type != nullptr) { + _has_bits_[0] |= 0x00000004u; } else { - clear_has_output_type(); + _has_bits_[0] &= ~0x00000004u; } - output_type_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + output_type_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), output_type, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.MethodDescriptorProto.output_type) } @@ -8889,66 +8987,57 @@ inline void MethodDescriptorProto::unsafe_arena_set_allocated_output_type( inline bool MethodDescriptorProto::has_options() const { return (_has_bits_[0] & 0x00000008u) != 0; } -inline void MethodDescriptorProto::set_has_options() { - _has_bits_[0] |= 0x00000008u; -} -inline void MethodDescriptorProto::clear_has_options() { +inline void MethodDescriptorProto::clear_options() { + if (options_ != nullptr) options_->Clear(); _has_bits_[0] &= ~0x00000008u; } -inline void MethodDescriptorProto::clear_options() { - if (options_ != NULL) options_->Clear(); - clear_has_options(); -} -inline const ::google::protobuf::MethodOptions& MethodDescriptorProto::_internal_options() const { - return *options_; -} -inline const ::google::protobuf::MethodOptions& MethodDescriptorProto::options() const { - const ::google::protobuf::MethodOptions* p = options_; +inline const PROTOBUF_NAMESPACE_ID::MethodOptions& MethodDescriptorProto::options() const { + const PROTOBUF_NAMESPACE_ID::MethodOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.options) - return p != NULL ? *p : *reinterpret_cast( - &::google::protobuf::_MethodOptions_default_instance_); + return p != nullptr ? *p : *reinterpret_cast( + &PROTOBUF_NAMESPACE_ID::_MethodOptions_default_instance_); } -inline ::google::protobuf::MethodOptions* MethodDescriptorProto::release_options() { +inline PROTOBUF_NAMESPACE_ID::MethodOptions* MethodDescriptorProto::release_options() { // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.options) - clear_has_options(); - ::google::protobuf::MethodOptions* temp = options_; - if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); + _has_bits_[0] &= ~0x00000008u; + PROTOBUF_NAMESPACE_ID::MethodOptions* temp = options_; + if (GetArenaNoVirtual() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } - options_ = NULL; + options_ = nullptr; return temp; } -inline ::google::protobuf::MethodOptions* MethodDescriptorProto::unsafe_arena_release_options() { +inline PROTOBUF_NAMESPACE_ID::MethodOptions* MethodDescriptorProto::unsafe_arena_release_options() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.MethodDescriptorProto.options) - clear_has_options(); - ::google::protobuf::MethodOptions* temp = options_; - options_ = NULL; + _has_bits_[0] &= ~0x00000008u; + PROTOBUF_NAMESPACE_ID::MethodOptions* temp = options_; + options_ = nullptr; return temp; } -inline ::google::protobuf::MethodOptions* MethodDescriptorProto::mutable_options() { - set_has_options(); - if (options_ == NULL) { - auto* p = CreateMaybeMessage<::google::protobuf::MethodOptions>(GetArenaNoVirtual()); +inline PROTOBUF_NAMESPACE_ID::MethodOptions* MethodDescriptorProto::mutable_options() { + _has_bits_[0] |= 0x00000008u; + if (options_ == nullptr) { + auto* p = CreateMaybeMessage(GetArenaNoVirtual()); options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.options) return options_; } -inline void MethodDescriptorProto::set_allocated_options(::google::protobuf::MethodOptions* options) { - ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); - if (message_arena == NULL) { +inline void MethodDescriptorProto::set_allocated_options(PROTOBUF_NAMESPACE_ID::MethodOptions* options) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); + if (message_arena == nullptr) { delete options_; } if (options) { - ::google::protobuf::Arena* submessage_arena = - ::google::protobuf::Arena::GetArena(options); + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::GetArena(options); if (message_arena != submessage_arena) { - options = ::google::protobuf::internal::GetOwnedMessage( + options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - set_has_options(); + _has_bits_[0] |= 0x00000008u; } else { - clear_has_options(); + _has_bits_[0] &= ~0x00000008u; } options_ = options; // @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.options) @@ -8958,22 +9047,16 @@ inline void MethodDescriptorProto::set_allocated_options(::google::protobuf::Met inline bool MethodDescriptorProto::has_client_streaming() const { return (_has_bits_[0] & 0x00000010u) != 0; } -inline void MethodDescriptorProto::set_has_client_streaming() { - _has_bits_[0] |= 0x00000010u; -} -inline void MethodDescriptorProto::clear_has_client_streaming() { - _has_bits_[0] &= ~0x00000010u; -} inline void MethodDescriptorProto::clear_client_streaming() { client_streaming_ = false; - clear_has_client_streaming(); + _has_bits_[0] &= ~0x00000010u; } inline bool MethodDescriptorProto::client_streaming() const { // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.client_streaming) return client_streaming_; } inline void MethodDescriptorProto::set_client_streaming(bool value) { - set_has_client_streaming(); + _has_bits_[0] |= 0x00000010u; client_streaming_ = value; // @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.client_streaming) } @@ -8982,22 +9065,16 @@ inline void MethodDescriptorProto::set_client_streaming(bool value) { inline bool MethodDescriptorProto::has_server_streaming() const { return (_has_bits_[0] & 0x00000020u) != 0; } -inline void MethodDescriptorProto::set_has_server_streaming() { - _has_bits_[0] |= 0x00000020u; -} -inline void MethodDescriptorProto::clear_has_server_streaming() { - _has_bits_[0] &= ~0x00000020u; -} inline void MethodDescriptorProto::clear_server_streaming() { server_streaming_ = false; - clear_has_server_streaming(); + _has_bits_[0] &= ~0x00000020u; } inline bool MethodDescriptorProto::server_streaming() const { // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.server_streaming) return server_streaming_; } inline void MethodDescriptorProto::set_server_streaming(bool value) { - set_has_server_streaming(); + _has_bits_[0] |= 0x00000020u; server_streaming_ = value; // @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.server_streaming) } @@ -9010,86 +9087,78 @@ inline void MethodDescriptorProto::set_server_streaming(bool value) { inline bool FileOptions::has_java_package() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void FileOptions::set_has_java_package() { - _has_bits_[0] |= 0x00000001u; -} -inline void FileOptions::clear_has_java_package() { +inline void FileOptions::clear_java_package() { + java_package_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000001u; } -inline void FileOptions::clear_java_package() { - java_package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_java_package(); -} -inline const ::std::string& FileOptions::java_package() const { +inline const std::string& FileOptions::java_package() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_package) return java_package_.Get(); } -inline void FileOptions::set_java_package(const ::std::string& value) { - set_has_java_package(); - java_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FileOptions::set_java_package(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + java_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_package) } -#if LANG_CXX11 -inline void FileOptions::set_java_package(::std::string&& value) { - set_has_java_package(); +inline void FileOptions::set_java_package(std::string&& value) { + _has_bits_[0] |= 0x00000001u; java_package_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.java_package) } -#endif inline void FileOptions::set_java_package(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_java_package(); - java_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000001u; + java_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.java_package) } inline void FileOptions::set_java_package(const char* value, size_t size) { - set_has_java_package(); - java_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000001u; + java_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.java_package) } -inline ::std::string* FileOptions::mutable_java_package() { - set_has_java_package(); +inline std::string* FileOptions::mutable_java_package() { + _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.java_package) - return java_package_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return java_package_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FileOptions::release_java_package() { +inline std::string* FileOptions::release_java_package() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_package) if (!has_java_package()) { - return NULL; + return nullptr; } - clear_has_java_package(); - return java_package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000001u; + return java_package_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FileOptions::set_allocated_java_package(::std::string* java_package) { - if (java_package != NULL) { - set_has_java_package(); +inline void FileOptions::set_allocated_java_package(std::string* java_package) { + if (java_package != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_java_package(); + _has_bits_[0] &= ~0x00000001u; } - java_package_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), java_package, + java_package_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), java_package, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.java_package) } -inline ::std::string* FileOptions::unsafe_arena_release_java_package() { +inline std::string* FileOptions::unsafe_arena_release_java_package() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.java_package) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_java_package(); - return java_package_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000001u; + return java_package_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::unsafe_arena_set_allocated_java_package( - ::std::string* java_package) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (java_package != NULL) { - set_has_java_package(); + std::string* java_package) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (java_package != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_java_package(); + _has_bits_[0] &= ~0x00000001u; } - java_package_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + java_package_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), java_package, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.java_package) } @@ -9098,86 +9167,78 @@ inline void FileOptions::unsafe_arena_set_allocated_java_package( inline bool FileOptions::has_java_outer_classname() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void FileOptions::set_has_java_outer_classname() { - _has_bits_[0] |= 0x00000002u; -} -inline void FileOptions::clear_has_java_outer_classname() { +inline void FileOptions::clear_java_outer_classname() { + java_outer_classname_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000002u; } -inline void FileOptions::clear_java_outer_classname() { - java_outer_classname_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_java_outer_classname(); -} -inline const ::std::string& FileOptions::java_outer_classname() const { +inline const std::string& FileOptions::java_outer_classname() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_outer_classname) return java_outer_classname_.Get(); } -inline void FileOptions::set_java_outer_classname(const ::std::string& value) { - set_has_java_outer_classname(); - java_outer_classname_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FileOptions::set_java_outer_classname(const std::string& value) { + _has_bits_[0] |= 0x00000002u; + java_outer_classname_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_outer_classname) } -#if LANG_CXX11 -inline void FileOptions::set_java_outer_classname(::std::string&& value) { - set_has_java_outer_classname(); +inline void FileOptions::set_java_outer_classname(std::string&& value) { + _has_bits_[0] |= 0x00000002u; java_outer_classname_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.java_outer_classname) } -#endif inline void FileOptions::set_java_outer_classname(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_java_outer_classname(); - java_outer_classname_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000002u; + java_outer_classname_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.java_outer_classname) } inline void FileOptions::set_java_outer_classname(const char* value, size_t size) { - set_has_java_outer_classname(); - java_outer_classname_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000002u; + java_outer_classname_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.java_outer_classname) } -inline ::std::string* FileOptions::mutable_java_outer_classname() { - set_has_java_outer_classname(); +inline std::string* FileOptions::mutable_java_outer_classname() { + _has_bits_[0] |= 0x00000002u; // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.java_outer_classname) - return java_outer_classname_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return java_outer_classname_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FileOptions::release_java_outer_classname() { +inline std::string* FileOptions::release_java_outer_classname() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_outer_classname) if (!has_java_outer_classname()) { - return NULL; + return nullptr; } - clear_has_java_outer_classname(); - return java_outer_classname_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000002u; + return java_outer_classname_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FileOptions::set_allocated_java_outer_classname(::std::string* java_outer_classname) { - if (java_outer_classname != NULL) { - set_has_java_outer_classname(); +inline void FileOptions::set_allocated_java_outer_classname(std::string* java_outer_classname) { + if (java_outer_classname != nullptr) { + _has_bits_[0] |= 0x00000002u; } else { - clear_has_java_outer_classname(); + _has_bits_[0] &= ~0x00000002u; } - java_outer_classname_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), java_outer_classname, + java_outer_classname_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), java_outer_classname, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.java_outer_classname) } -inline ::std::string* FileOptions::unsafe_arena_release_java_outer_classname() { +inline std::string* FileOptions::unsafe_arena_release_java_outer_classname() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.java_outer_classname) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_java_outer_classname(); - return java_outer_classname_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000002u; + return java_outer_classname_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::unsafe_arena_set_allocated_java_outer_classname( - ::std::string* java_outer_classname) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (java_outer_classname != NULL) { - set_has_java_outer_classname(); + std::string* java_outer_classname) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (java_outer_classname != nullptr) { + _has_bits_[0] |= 0x00000002u; } else { - clear_has_java_outer_classname(); + _has_bits_[0] &= ~0x00000002u; } - java_outer_classname_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + java_outer_classname_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), java_outer_classname, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.java_outer_classname) } @@ -9186,22 +9247,16 @@ inline void FileOptions::unsafe_arena_set_allocated_java_outer_classname( inline bool FileOptions::has_java_multiple_files() const { return (_has_bits_[0] & 0x00000400u) != 0; } -inline void FileOptions::set_has_java_multiple_files() { - _has_bits_[0] |= 0x00000400u; -} -inline void FileOptions::clear_has_java_multiple_files() { - _has_bits_[0] &= ~0x00000400u; -} inline void FileOptions::clear_java_multiple_files() { java_multiple_files_ = false; - clear_has_java_multiple_files(); + _has_bits_[0] &= ~0x00000400u; } inline bool FileOptions::java_multiple_files() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_multiple_files) return java_multiple_files_; } inline void FileOptions::set_java_multiple_files(bool value) { - set_has_java_multiple_files(); + _has_bits_[0] |= 0x00000400u; java_multiple_files_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_multiple_files) } @@ -9210,22 +9265,16 @@ inline void FileOptions::set_java_multiple_files(bool value) { inline bool FileOptions::has_java_generate_equals_and_hash() const { return (_has_bits_[0] & 0x00000800u) != 0; } -inline void FileOptions::set_has_java_generate_equals_and_hash() { - _has_bits_[0] |= 0x00000800u; -} -inline void FileOptions::clear_has_java_generate_equals_and_hash() { - _has_bits_[0] &= ~0x00000800u; -} inline void FileOptions::clear_java_generate_equals_and_hash() { java_generate_equals_and_hash_ = false; - clear_has_java_generate_equals_and_hash(); + _has_bits_[0] &= ~0x00000800u; } inline bool FileOptions::java_generate_equals_and_hash() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_generate_equals_and_hash) return java_generate_equals_and_hash_; } inline void FileOptions::set_java_generate_equals_and_hash(bool value) { - set_has_java_generate_equals_and_hash(); + _has_bits_[0] |= 0x00000800u; java_generate_equals_and_hash_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_generate_equals_and_hash) } @@ -9234,22 +9283,16 @@ inline void FileOptions::set_java_generate_equals_and_hash(bool value) { inline bool FileOptions::has_java_string_check_utf8() const { return (_has_bits_[0] & 0x00001000u) != 0; } -inline void FileOptions::set_has_java_string_check_utf8() { - _has_bits_[0] |= 0x00001000u; -} -inline void FileOptions::clear_has_java_string_check_utf8() { - _has_bits_[0] &= ~0x00001000u; -} inline void FileOptions::clear_java_string_check_utf8() { java_string_check_utf8_ = false; - clear_has_java_string_check_utf8(); + _has_bits_[0] &= ~0x00001000u; } inline bool FileOptions::java_string_check_utf8() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_string_check_utf8) return java_string_check_utf8_; } inline void FileOptions::set_java_string_check_utf8(bool value) { - set_has_java_string_check_utf8(); + _has_bits_[0] |= 0x00001000u; java_string_check_utf8_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_string_check_utf8) } @@ -9258,23 +9301,17 @@ inline void FileOptions::set_java_string_check_utf8(bool value) { inline bool FileOptions::has_optimize_for() const { return (_has_bits_[0] & 0x00080000u) != 0; } -inline void FileOptions::set_has_optimize_for() { - _has_bits_[0] |= 0x00080000u; -} -inline void FileOptions::clear_has_optimize_for() { - _has_bits_[0] &= ~0x00080000u; -} inline void FileOptions::clear_optimize_for() { optimize_for_ = 1; - clear_has_optimize_for(); + _has_bits_[0] &= ~0x00080000u; } -inline ::google::protobuf::FileOptions_OptimizeMode FileOptions::optimize_for() const { +inline PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode FileOptions::optimize_for() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.optimize_for) - return static_cast< ::google::protobuf::FileOptions_OptimizeMode >(optimize_for_); + return static_cast< PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode >(optimize_for_); } -inline void FileOptions::set_optimize_for(::google::protobuf::FileOptions_OptimizeMode value) { - assert(::google::protobuf::FileOptions_OptimizeMode_IsValid(value)); - set_has_optimize_for(); +inline void FileOptions::set_optimize_for(PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode value) { + assert(PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode_IsValid(value)); + _has_bits_[0] |= 0x00080000u; optimize_for_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.optimize_for) } @@ -9283,86 +9320,78 @@ inline void FileOptions::set_optimize_for(::google::protobuf::FileOptions_Optimi inline bool FileOptions::has_go_package() const { return (_has_bits_[0] & 0x00000004u) != 0; } -inline void FileOptions::set_has_go_package() { - _has_bits_[0] |= 0x00000004u; -} -inline void FileOptions::clear_has_go_package() { +inline void FileOptions::clear_go_package() { + go_package_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000004u; } -inline void FileOptions::clear_go_package() { - go_package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_go_package(); -} -inline const ::std::string& FileOptions::go_package() const { +inline const std::string& FileOptions::go_package() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.go_package) return go_package_.Get(); } -inline void FileOptions::set_go_package(const ::std::string& value) { - set_has_go_package(); - go_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FileOptions::set_go_package(const std::string& value) { + _has_bits_[0] |= 0x00000004u; + go_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.go_package) } -#if LANG_CXX11 -inline void FileOptions::set_go_package(::std::string&& value) { - set_has_go_package(); +inline void FileOptions::set_go_package(std::string&& value) { + _has_bits_[0] |= 0x00000004u; go_package_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.go_package) } -#endif inline void FileOptions::set_go_package(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_go_package(); - go_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000004u; + go_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.go_package) } inline void FileOptions::set_go_package(const char* value, size_t size) { - set_has_go_package(); - go_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000004u; + go_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.go_package) } -inline ::std::string* FileOptions::mutable_go_package() { - set_has_go_package(); +inline std::string* FileOptions::mutable_go_package() { + _has_bits_[0] |= 0x00000004u; // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.go_package) - return go_package_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return go_package_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FileOptions::release_go_package() { +inline std::string* FileOptions::release_go_package() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.go_package) if (!has_go_package()) { - return NULL; + return nullptr; } - clear_has_go_package(); - return go_package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000004u; + return go_package_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FileOptions::set_allocated_go_package(::std::string* go_package) { - if (go_package != NULL) { - set_has_go_package(); +inline void FileOptions::set_allocated_go_package(std::string* go_package) { + if (go_package != nullptr) { + _has_bits_[0] |= 0x00000004u; } else { - clear_has_go_package(); + _has_bits_[0] &= ~0x00000004u; } - go_package_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), go_package, + go_package_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), go_package, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.go_package) } -inline ::std::string* FileOptions::unsafe_arena_release_go_package() { +inline std::string* FileOptions::unsafe_arena_release_go_package() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.go_package) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_go_package(); - return go_package_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000004u; + return go_package_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::unsafe_arena_set_allocated_go_package( - ::std::string* go_package) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (go_package != NULL) { - set_has_go_package(); + std::string* go_package) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (go_package != nullptr) { + _has_bits_[0] |= 0x00000004u; } else { - clear_has_go_package(); + _has_bits_[0] &= ~0x00000004u; } - go_package_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + go_package_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), go_package, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.go_package) } @@ -9371,22 +9400,16 @@ inline void FileOptions::unsafe_arena_set_allocated_go_package( inline bool FileOptions::has_cc_generic_services() const { return (_has_bits_[0] & 0x00002000u) != 0; } -inline void FileOptions::set_has_cc_generic_services() { - _has_bits_[0] |= 0x00002000u; -} -inline void FileOptions::clear_has_cc_generic_services() { - _has_bits_[0] &= ~0x00002000u; -} inline void FileOptions::clear_cc_generic_services() { cc_generic_services_ = false; - clear_has_cc_generic_services(); + _has_bits_[0] &= ~0x00002000u; } inline bool FileOptions::cc_generic_services() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.cc_generic_services) return cc_generic_services_; } inline void FileOptions::set_cc_generic_services(bool value) { - set_has_cc_generic_services(); + _has_bits_[0] |= 0x00002000u; cc_generic_services_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.cc_generic_services) } @@ -9395,22 +9418,16 @@ inline void FileOptions::set_cc_generic_services(bool value) { inline bool FileOptions::has_java_generic_services() const { return (_has_bits_[0] & 0x00004000u) != 0; } -inline void FileOptions::set_has_java_generic_services() { - _has_bits_[0] |= 0x00004000u; -} -inline void FileOptions::clear_has_java_generic_services() { - _has_bits_[0] &= ~0x00004000u; -} inline void FileOptions::clear_java_generic_services() { java_generic_services_ = false; - clear_has_java_generic_services(); + _has_bits_[0] &= ~0x00004000u; } inline bool FileOptions::java_generic_services() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_generic_services) return java_generic_services_; } inline void FileOptions::set_java_generic_services(bool value) { - set_has_java_generic_services(); + _has_bits_[0] |= 0x00004000u; java_generic_services_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_generic_services) } @@ -9419,22 +9436,16 @@ inline void FileOptions::set_java_generic_services(bool value) { inline bool FileOptions::has_py_generic_services() const { return (_has_bits_[0] & 0x00008000u) != 0; } -inline void FileOptions::set_has_py_generic_services() { - _has_bits_[0] |= 0x00008000u; -} -inline void FileOptions::clear_has_py_generic_services() { - _has_bits_[0] &= ~0x00008000u; -} inline void FileOptions::clear_py_generic_services() { py_generic_services_ = false; - clear_has_py_generic_services(); + _has_bits_[0] &= ~0x00008000u; } inline bool FileOptions::py_generic_services() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.py_generic_services) return py_generic_services_; } inline void FileOptions::set_py_generic_services(bool value) { - set_has_py_generic_services(); + _has_bits_[0] |= 0x00008000u; py_generic_services_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.py_generic_services) } @@ -9443,22 +9454,16 @@ inline void FileOptions::set_py_generic_services(bool value) { inline bool FileOptions::has_php_generic_services() const { return (_has_bits_[0] & 0x00010000u) != 0; } -inline void FileOptions::set_has_php_generic_services() { - _has_bits_[0] |= 0x00010000u; -} -inline void FileOptions::clear_has_php_generic_services() { - _has_bits_[0] &= ~0x00010000u; -} inline void FileOptions::clear_php_generic_services() { php_generic_services_ = false; - clear_has_php_generic_services(); + _has_bits_[0] &= ~0x00010000u; } inline bool FileOptions::php_generic_services() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.php_generic_services) return php_generic_services_; } inline void FileOptions::set_php_generic_services(bool value) { - set_has_php_generic_services(); + _has_bits_[0] |= 0x00010000u; php_generic_services_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.php_generic_services) } @@ -9467,22 +9472,16 @@ inline void FileOptions::set_php_generic_services(bool value) { inline bool FileOptions::has_deprecated() const { return (_has_bits_[0] & 0x00020000u) != 0; } -inline void FileOptions::set_has_deprecated() { - _has_bits_[0] |= 0x00020000u; -} -inline void FileOptions::clear_has_deprecated() { - _has_bits_[0] &= ~0x00020000u; -} inline void FileOptions::clear_deprecated() { deprecated_ = false; - clear_has_deprecated(); + _has_bits_[0] &= ~0x00020000u; } inline bool FileOptions::deprecated() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.deprecated) return deprecated_; } inline void FileOptions::set_deprecated(bool value) { - set_has_deprecated(); + _has_bits_[0] |= 0x00020000u; deprecated_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.deprecated) } @@ -9491,22 +9490,16 @@ inline void FileOptions::set_deprecated(bool value) { inline bool FileOptions::has_cc_enable_arenas() const { return (_has_bits_[0] & 0x00040000u) != 0; } -inline void FileOptions::set_has_cc_enable_arenas() { - _has_bits_[0] |= 0x00040000u; -} -inline void FileOptions::clear_has_cc_enable_arenas() { - _has_bits_[0] &= ~0x00040000u; -} inline void FileOptions::clear_cc_enable_arenas() { cc_enable_arenas_ = false; - clear_has_cc_enable_arenas(); + _has_bits_[0] &= ~0x00040000u; } inline bool FileOptions::cc_enable_arenas() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.cc_enable_arenas) return cc_enable_arenas_; } inline void FileOptions::set_cc_enable_arenas(bool value) { - set_has_cc_enable_arenas(); + _has_bits_[0] |= 0x00040000u; cc_enable_arenas_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.cc_enable_arenas) } @@ -9515,86 +9508,78 @@ inline void FileOptions::set_cc_enable_arenas(bool value) { inline bool FileOptions::has_objc_class_prefix() const { return (_has_bits_[0] & 0x00000008u) != 0; } -inline void FileOptions::set_has_objc_class_prefix() { - _has_bits_[0] |= 0x00000008u; -} -inline void FileOptions::clear_has_objc_class_prefix() { +inline void FileOptions::clear_objc_class_prefix() { + objc_class_prefix_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000008u; } -inline void FileOptions::clear_objc_class_prefix() { - objc_class_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_objc_class_prefix(); -} -inline const ::std::string& FileOptions::objc_class_prefix() const { +inline const std::string& FileOptions::objc_class_prefix() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.objc_class_prefix) return objc_class_prefix_.Get(); } -inline void FileOptions::set_objc_class_prefix(const ::std::string& value) { - set_has_objc_class_prefix(); - objc_class_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FileOptions::set_objc_class_prefix(const std::string& value) { + _has_bits_[0] |= 0x00000008u; + objc_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.objc_class_prefix) } -#if LANG_CXX11 -inline void FileOptions::set_objc_class_prefix(::std::string&& value) { - set_has_objc_class_prefix(); +inline void FileOptions::set_objc_class_prefix(std::string&& value) { + _has_bits_[0] |= 0x00000008u; objc_class_prefix_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.objc_class_prefix) } -#endif inline void FileOptions::set_objc_class_prefix(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_objc_class_prefix(); - objc_class_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000008u; + objc_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.objc_class_prefix) } inline void FileOptions::set_objc_class_prefix(const char* value, size_t size) { - set_has_objc_class_prefix(); - objc_class_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000008u; + objc_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.objc_class_prefix) } -inline ::std::string* FileOptions::mutable_objc_class_prefix() { - set_has_objc_class_prefix(); +inline std::string* FileOptions::mutable_objc_class_prefix() { + _has_bits_[0] |= 0x00000008u; // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.objc_class_prefix) - return objc_class_prefix_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return objc_class_prefix_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FileOptions::release_objc_class_prefix() { +inline std::string* FileOptions::release_objc_class_prefix() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.objc_class_prefix) if (!has_objc_class_prefix()) { - return NULL; + return nullptr; } - clear_has_objc_class_prefix(); - return objc_class_prefix_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000008u; + return objc_class_prefix_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FileOptions::set_allocated_objc_class_prefix(::std::string* objc_class_prefix) { - if (objc_class_prefix != NULL) { - set_has_objc_class_prefix(); +inline void FileOptions::set_allocated_objc_class_prefix(std::string* objc_class_prefix) { + if (objc_class_prefix != nullptr) { + _has_bits_[0] |= 0x00000008u; } else { - clear_has_objc_class_prefix(); + _has_bits_[0] &= ~0x00000008u; } - objc_class_prefix_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), objc_class_prefix, + objc_class_prefix_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), objc_class_prefix, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.objc_class_prefix) } -inline ::std::string* FileOptions::unsafe_arena_release_objc_class_prefix() { +inline std::string* FileOptions::unsafe_arena_release_objc_class_prefix() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.objc_class_prefix) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_objc_class_prefix(); - return objc_class_prefix_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000008u; + return objc_class_prefix_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::unsafe_arena_set_allocated_objc_class_prefix( - ::std::string* objc_class_prefix) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (objc_class_prefix != NULL) { - set_has_objc_class_prefix(); + std::string* objc_class_prefix) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (objc_class_prefix != nullptr) { + _has_bits_[0] |= 0x00000008u; } else { - clear_has_objc_class_prefix(); + _has_bits_[0] &= ~0x00000008u; } - objc_class_prefix_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + objc_class_prefix_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), objc_class_prefix, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.objc_class_prefix) } @@ -9603,86 +9588,78 @@ inline void FileOptions::unsafe_arena_set_allocated_objc_class_prefix( inline bool FileOptions::has_csharp_namespace() const { return (_has_bits_[0] & 0x00000010u) != 0; } -inline void FileOptions::set_has_csharp_namespace() { - _has_bits_[0] |= 0x00000010u; -} -inline void FileOptions::clear_has_csharp_namespace() { +inline void FileOptions::clear_csharp_namespace() { + csharp_namespace_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000010u; } -inline void FileOptions::clear_csharp_namespace() { - csharp_namespace_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_csharp_namespace(); -} -inline const ::std::string& FileOptions::csharp_namespace() const { +inline const std::string& FileOptions::csharp_namespace() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.csharp_namespace) return csharp_namespace_.Get(); } -inline void FileOptions::set_csharp_namespace(const ::std::string& value) { - set_has_csharp_namespace(); - csharp_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FileOptions::set_csharp_namespace(const std::string& value) { + _has_bits_[0] |= 0x00000010u; + csharp_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.csharp_namespace) } -#if LANG_CXX11 -inline void FileOptions::set_csharp_namespace(::std::string&& value) { - set_has_csharp_namespace(); +inline void FileOptions::set_csharp_namespace(std::string&& value) { + _has_bits_[0] |= 0x00000010u; csharp_namespace_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.csharp_namespace) } -#endif inline void FileOptions::set_csharp_namespace(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_csharp_namespace(); - csharp_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000010u; + csharp_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.csharp_namespace) } inline void FileOptions::set_csharp_namespace(const char* value, size_t size) { - set_has_csharp_namespace(); - csharp_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000010u; + csharp_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.csharp_namespace) } -inline ::std::string* FileOptions::mutable_csharp_namespace() { - set_has_csharp_namespace(); +inline std::string* FileOptions::mutable_csharp_namespace() { + _has_bits_[0] |= 0x00000010u; // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.csharp_namespace) - return csharp_namespace_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return csharp_namespace_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FileOptions::release_csharp_namespace() { +inline std::string* FileOptions::release_csharp_namespace() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.csharp_namespace) if (!has_csharp_namespace()) { - return NULL; + return nullptr; } - clear_has_csharp_namespace(); - return csharp_namespace_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000010u; + return csharp_namespace_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FileOptions::set_allocated_csharp_namespace(::std::string* csharp_namespace) { - if (csharp_namespace != NULL) { - set_has_csharp_namespace(); +inline void FileOptions::set_allocated_csharp_namespace(std::string* csharp_namespace) { + if (csharp_namespace != nullptr) { + _has_bits_[0] |= 0x00000010u; } else { - clear_has_csharp_namespace(); + _has_bits_[0] &= ~0x00000010u; } - csharp_namespace_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), csharp_namespace, + csharp_namespace_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), csharp_namespace, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.csharp_namespace) } -inline ::std::string* FileOptions::unsafe_arena_release_csharp_namespace() { +inline std::string* FileOptions::unsafe_arena_release_csharp_namespace() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.csharp_namespace) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_csharp_namespace(); - return csharp_namespace_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000010u; + return csharp_namespace_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::unsafe_arena_set_allocated_csharp_namespace( - ::std::string* csharp_namespace) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (csharp_namespace != NULL) { - set_has_csharp_namespace(); + std::string* csharp_namespace) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (csharp_namespace != nullptr) { + _has_bits_[0] |= 0x00000010u; } else { - clear_has_csharp_namespace(); + _has_bits_[0] &= ~0x00000010u; } - csharp_namespace_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + csharp_namespace_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), csharp_namespace, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.csharp_namespace) } @@ -9691,86 +9668,78 @@ inline void FileOptions::unsafe_arena_set_allocated_csharp_namespace( inline bool FileOptions::has_swift_prefix() const { return (_has_bits_[0] & 0x00000020u) != 0; } -inline void FileOptions::set_has_swift_prefix() { - _has_bits_[0] |= 0x00000020u; -} -inline void FileOptions::clear_has_swift_prefix() { +inline void FileOptions::clear_swift_prefix() { + swift_prefix_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000020u; } -inline void FileOptions::clear_swift_prefix() { - swift_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_swift_prefix(); -} -inline const ::std::string& FileOptions::swift_prefix() const { +inline const std::string& FileOptions::swift_prefix() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.swift_prefix) return swift_prefix_.Get(); } -inline void FileOptions::set_swift_prefix(const ::std::string& value) { - set_has_swift_prefix(); - swift_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FileOptions::set_swift_prefix(const std::string& value) { + _has_bits_[0] |= 0x00000020u; + swift_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.swift_prefix) } -#if LANG_CXX11 -inline void FileOptions::set_swift_prefix(::std::string&& value) { - set_has_swift_prefix(); +inline void FileOptions::set_swift_prefix(std::string&& value) { + _has_bits_[0] |= 0x00000020u; swift_prefix_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.swift_prefix) } -#endif inline void FileOptions::set_swift_prefix(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_swift_prefix(); - swift_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000020u; + swift_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.swift_prefix) } inline void FileOptions::set_swift_prefix(const char* value, size_t size) { - set_has_swift_prefix(); - swift_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000020u; + swift_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.swift_prefix) } -inline ::std::string* FileOptions::mutable_swift_prefix() { - set_has_swift_prefix(); +inline std::string* FileOptions::mutable_swift_prefix() { + _has_bits_[0] |= 0x00000020u; // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.swift_prefix) - return swift_prefix_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return swift_prefix_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FileOptions::release_swift_prefix() { +inline std::string* FileOptions::release_swift_prefix() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.swift_prefix) if (!has_swift_prefix()) { - return NULL; + return nullptr; } - clear_has_swift_prefix(); - return swift_prefix_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000020u; + return swift_prefix_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FileOptions::set_allocated_swift_prefix(::std::string* swift_prefix) { - if (swift_prefix != NULL) { - set_has_swift_prefix(); +inline void FileOptions::set_allocated_swift_prefix(std::string* swift_prefix) { + if (swift_prefix != nullptr) { + _has_bits_[0] |= 0x00000020u; } else { - clear_has_swift_prefix(); + _has_bits_[0] &= ~0x00000020u; } - swift_prefix_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), swift_prefix, + swift_prefix_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), swift_prefix, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.swift_prefix) } -inline ::std::string* FileOptions::unsafe_arena_release_swift_prefix() { +inline std::string* FileOptions::unsafe_arena_release_swift_prefix() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.swift_prefix) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_swift_prefix(); - return swift_prefix_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000020u; + return swift_prefix_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::unsafe_arena_set_allocated_swift_prefix( - ::std::string* swift_prefix) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (swift_prefix != NULL) { - set_has_swift_prefix(); + std::string* swift_prefix) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (swift_prefix != nullptr) { + _has_bits_[0] |= 0x00000020u; } else { - clear_has_swift_prefix(); + _has_bits_[0] &= ~0x00000020u; } - swift_prefix_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + swift_prefix_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), swift_prefix, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.swift_prefix) } @@ -9779,86 +9748,78 @@ inline void FileOptions::unsafe_arena_set_allocated_swift_prefix( inline bool FileOptions::has_php_class_prefix() const { return (_has_bits_[0] & 0x00000040u) != 0; } -inline void FileOptions::set_has_php_class_prefix() { - _has_bits_[0] |= 0x00000040u; -} -inline void FileOptions::clear_has_php_class_prefix() { +inline void FileOptions::clear_php_class_prefix() { + php_class_prefix_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000040u; } -inline void FileOptions::clear_php_class_prefix() { - php_class_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_php_class_prefix(); -} -inline const ::std::string& FileOptions::php_class_prefix() const { +inline const std::string& FileOptions::php_class_prefix() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.php_class_prefix) return php_class_prefix_.Get(); } -inline void FileOptions::set_php_class_prefix(const ::std::string& value) { - set_has_php_class_prefix(); - php_class_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FileOptions::set_php_class_prefix(const std::string& value) { + _has_bits_[0] |= 0x00000040u; + php_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.php_class_prefix) } -#if LANG_CXX11 -inline void FileOptions::set_php_class_prefix(::std::string&& value) { - set_has_php_class_prefix(); +inline void FileOptions::set_php_class_prefix(std::string&& value) { + _has_bits_[0] |= 0x00000040u; php_class_prefix_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.php_class_prefix) } -#endif inline void FileOptions::set_php_class_prefix(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_php_class_prefix(); - php_class_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000040u; + php_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.php_class_prefix) } inline void FileOptions::set_php_class_prefix(const char* value, size_t size) { - set_has_php_class_prefix(); - php_class_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000040u; + php_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.php_class_prefix) } -inline ::std::string* FileOptions::mutable_php_class_prefix() { - set_has_php_class_prefix(); +inline std::string* FileOptions::mutable_php_class_prefix() { + _has_bits_[0] |= 0x00000040u; // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.php_class_prefix) - return php_class_prefix_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return php_class_prefix_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FileOptions::release_php_class_prefix() { +inline std::string* FileOptions::release_php_class_prefix() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_class_prefix) if (!has_php_class_prefix()) { - return NULL; + return nullptr; } - clear_has_php_class_prefix(); - return php_class_prefix_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000040u; + return php_class_prefix_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FileOptions::set_allocated_php_class_prefix(::std::string* php_class_prefix) { - if (php_class_prefix != NULL) { - set_has_php_class_prefix(); +inline void FileOptions::set_allocated_php_class_prefix(std::string* php_class_prefix) { + if (php_class_prefix != nullptr) { + _has_bits_[0] |= 0x00000040u; } else { - clear_has_php_class_prefix(); + _has_bits_[0] &= ~0x00000040u; } - php_class_prefix_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), php_class_prefix, + php_class_prefix_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), php_class_prefix, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.php_class_prefix) } -inline ::std::string* FileOptions::unsafe_arena_release_php_class_prefix() { +inline std::string* FileOptions::unsafe_arena_release_php_class_prefix() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.php_class_prefix) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_php_class_prefix(); - return php_class_prefix_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000040u; + return php_class_prefix_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::unsafe_arena_set_allocated_php_class_prefix( - ::std::string* php_class_prefix) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (php_class_prefix != NULL) { - set_has_php_class_prefix(); + std::string* php_class_prefix) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (php_class_prefix != nullptr) { + _has_bits_[0] |= 0x00000040u; } else { - clear_has_php_class_prefix(); + _has_bits_[0] &= ~0x00000040u; } - php_class_prefix_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + php_class_prefix_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), php_class_prefix, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.php_class_prefix) } @@ -9867,86 +9828,78 @@ inline void FileOptions::unsafe_arena_set_allocated_php_class_prefix( inline bool FileOptions::has_php_namespace() const { return (_has_bits_[0] & 0x00000080u) != 0; } -inline void FileOptions::set_has_php_namespace() { - _has_bits_[0] |= 0x00000080u; -} -inline void FileOptions::clear_has_php_namespace() { +inline void FileOptions::clear_php_namespace() { + php_namespace_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000080u; } -inline void FileOptions::clear_php_namespace() { - php_namespace_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_php_namespace(); -} -inline const ::std::string& FileOptions::php_namespace() const { +inline const std::string& FileOptions::php_namespace() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.php_namespace) return php_namespace_.Get(); } -inline void FileOptions::set_php_namespace(const ::std::string& value) { - set_has_php_namespace(); - php_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FileOptions::set_php_namespace(const std::string& value) { + _has_bits_[0] |= 0x00000080u; + php_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.php_namespace) } -#if LANG_CXX11 -inline void FileOptions::set_php_namespace(::std::string&& value) { - set_has_php_namespace(); +inline void FileOptions::set_php_namespace(std::string&& value) { + _has_bits_[0] |= 0x00000080u; php_namespace_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.php_namespace) } -#endif inline void FileOptions::set_php_namespace(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_php_namespace(); - php_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000080u; + php_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.php_namespace) } inline void FileOptions::set_php_namespace(const char* value, size_t size) { - set_has_php_namespace(); - php_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000080u; + php_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.php_namespace) } -inline ::std::string* FileOptions::mutable_php_namespace() { - set_has_php_namespace(); +inline std::string* FileOptions::mutable_php_namespace() { + _has_bits_[0] |= 0x00000080u; // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.php_namespace) - return php_namespace_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return php_namespace_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FileOptions::release_php_namespace() { +inline std::string* FileOptions::release_php_namespace() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_namespace) if (!has_php_namespace()) { - return NULL; + return nullptr; } - clear_has_php_namespace(); - return php_namespace_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000080u; + return php_namespace_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FileOptions::set_allocated_php_namespace(::std::string* php_namespace) { - if (php_namespace != NULL) { - set_has_php_namespace(); +inline void FileOptions::set_allocated_php_namespace(std::string* php_namespace) { + if (php_namespace != nullptr) { + _has_bits_[0] |= 0x00000080u; } else { - clear_has_php_namespace(); + _has_bits_[0] &= ~0x00000080u; } - php_namespace_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), php_namespace, + php_namespace_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), php_namespace, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.php_namespace) } -inline ::std::string* FileOptions::unsafe_arena_release_php_namespace() { +inline std::string* FileOptions::unsafe_arena_release_php_namespace() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.php_namespace) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_php_namespace(); - return php_namespace_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000080u; + return php_namespace_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::unsafe_arena_set_allocated_php_namespace( - ::std::string* php_namespace) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (php_namespace != NULL) { - set_has_php_namespace(); + std::string* php_namespace) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (php_namespace != nullptr) { + _has_bits_[0] |= 0x00000080u; } else { - clear_has_php_namespace(); + _has_bits_[0] &= ~0x00000080u; } - php_namespace_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + php_namespace_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), php_namespace, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.php_namespace) } @@ -9955,86 +9908,78 @@ inline void FileOptions::unsafe_arena_set_allocated_php_namespace( inline bool FileOptions::has_php_metadata_namespace() const { return (_has_bits_[0] & 0x00000100u) != 0; } -inline void FileOptions::set_has_php_metadata_namespace() { - _has_bits_[0] |= 0x00000100u; -} -inline void FileOptions::clear_has_php_metadata_namespace() { +inline void FileOptions::clear_php_metadata_namespace() { + php_metadata_namespace_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000100u; } -inline void FileOptions::clear_php_metadata_namespace() { - php_metadata_namespace_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_php_metadata_namespace(); -} -inline const ::std::string& FileOptions::php_metadata_namespace() const { +inline const std::string& FileOptions::php_metadata_namespace() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.php_metadata_namespace) return php_metadata_namespace_.Get(); } -inline void FileOptions::set_php_metadata_namespace(const ::std::string& value) { - set_has_php_metadata_namespace(); - php_metadata_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FileOptions::set_php_metadata_namespace(const std::string& value) { + _has_bits_[0] |= 0x00000100u; + php_metadata_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.php_metadata_namespace) } -#if LANG_CXX11 -inline void FileOptions::set_php_metadata_namespace(::std::string&& value) { - set_has_php_metadata_namespace(); +inline void FileOptions::set_php_metadata_namespace(std::string&& value) { + _has_bits_[0] |= 0x00000100u; php_metadata_namespace_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.php_metadata_namespace) } -#endif inline void FileOptions::set_php_metadata_namespace(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_php_metadata_namespace(); - php_metadata_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000100u; + php_metadata_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.php_metadata_namespace) } inline void FileOptions::set_php_metadata_namespace(const char* value, size_t size) { - set_has_php_metadata_namespace(); - php_metadata_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000100u; + php_metadata_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.php_metadata_namespace) } -inline ::std::string* FileOptions::mutable_php_metadata_namespace() { - set_has_php_metadata_namespace(); +inline std::string* FileOptions::mutable_php_metadata_namespace() { + _has_bits_[0] |= 0x00000100u; // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.php_metadata_namespace) - return php_metadata_namespace_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return php_metadata_namespace_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FileOptions::release_php_metadata_namespace() { +inline std::string* FileOptions::release_php_metadata_namespace() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_metadata_namespace) if (!has_php_metadata_namespace()) { - return NULL; + return nullptr; } - clear_has_php_metadata_namespace(); - return php_metadata_namespace_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000100u; + return php_metadata_namespace_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FileOptions::set_allocated_php_metadata_namespace(::std::string* php_metadata_namespace) { - if (php_metadata_namespace != NULL) { - set_has_php_metadata_namespace(); +inline void FileOptions::set_allocated_php_metadata_namespace(std::string* php_metadata_namespace) { + if (php_metadata_namespace != nullptr) { + _has_bits_[0] |= 0x00000100u; } else { - clear_has_php_metadata_namespace(); + _has_bits_[0] &= ~0x00000100u; } - php_metadata_namespace_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), php_metadata_namespace, + php_metadata_namespace_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), php_metadata_namespace, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.php_metadata_namespace) } -inline ::std::string* FileOptions::unsafe_arena_release_php_metadata_namespace() { +inline std::string* FileOptions::unsafe_arena_release_php_metadata_namespace() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.php_metadata_namespace) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_php_metadata_namespace(); - return php_metadata_namespace_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000100u; + return php_metadata_namespace_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::unsafe_arena_set_allocated_php_metadata_namespace( - ::std::string* php_metadata_namespace) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (php_metadata_namespace != NULL) { - set_has_php_metadata_namespace(); + std::string* php_metadata_namespace) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (php_metadata_namespace != nullptr) { + _has_bits_[0] |= 0x00000100u; } else { - clear_has_php_metadata_namespace(); + _has_bits_[0] &= ~0x00000100u; } - php_metadata_namespace_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + php_metadata_namespace_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), php_metadata_namespace, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.php_metadata_namespace) } @@ -10043,86 +9988,78 @@ inline void FileOptions::unsafe_arena_set_allocated_php_metadata_namespace( inline bool FileOptions::has_ruby_package() const { return (_has_bits_[0] & 0x00000200u) != 0; } -inline void FileOptions::set_has_ruby_package() { - _has_bits_[0] |= 0x00000200u; -} -inline void FileOptions::clear_has_ruby_package() { +inline void FileOptions::clear_ruby_package() { + ruby_package_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000200u; } -inline void FileOptions::clear_ruby_package() { - ruby_package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_ruby_package(); -} -inline const ::std::string& FileOptions::ruby_package() const { +inline const std::string& FileOptions::ruby_package() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.ruby_package) return ruby_package_.Get(); } -inline void FileOptions::set_ruby_package(const ::std::string& value) { - set_has_ruby_package(); - ruby_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void FileOptions::set_ruby_package(const std::string& value) { + _has_bits_[0] |= 0x00000200u; + ruby_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.ruby_package) } -#if LANG_CXX11 -inline void FileOptions::set_ruby_package(::std::string&& value) { - set_has_ruby_package(); +inline void FileOptions::set_ruby_package(std::string&& value) { + _has_bits_[0] |= 0x00000200u; ruby_package_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.ruby_package) } -#endif inline void FileOptions::set_ruby_package(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_ruby_package(); - ruby_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000200u; + ruby_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.ruby_package) } inline void FileOptions::set_ruby_package(const char* value, size_t size) { - set_has_ruby_package(); - ruby_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000200u; + ruby_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.ruby_package) } -inline ::std::string* FileOptions::mutable_ruby_package() { - set_has_ruby_package(); +inline std::string* FileOptions::mutable_ruby_package() { + _has_bits_[0] |= 0x00000200u; // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.ruby_package) - return ruby_package_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return ruby_package_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* FileOptions::release_ruby_package() { +inline std::string* FileOptions::release_ruby_package() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.ruby_package) if (!has_ruby_package()) { - return NULL; + return nullptr; } - clear_has_ruby_package(); - return ruby_package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000200u; + return ruby_package_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void FileOptions::set_allocated_ruby_package(::std::string* ruby_package) { - if (ruby_package != NULL) { - set_has_ruby_package(); +inline void FileOptions::set_allocated_ruby_package(std::string* ruby_package) { + if (ruby_package != nullptr) { + _has_bits_[0] |= 0x00000200u; } else { - clear_has_ruby_package(); + _has_bits_[0] &= ~0x00000200u; } - ruby_package_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ruby_package, + ruby_package_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ruby_package, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.ruby_package) } -inline ::std::string* FileOptions::unsafe_arena_release_ruby_package() { +inline std::string* FileOptions::unsafe_arena_release_ruby_package() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.ruby_package) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_ruby_package(); - return ruby_package_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000200u; + return ruby_package_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::unsafe_arena_set_allocated_ruby_package( - ::std::string* ruby_package) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (ruby_package != NULL) { - set_has_ruby_package(); + std::string* ruby_package) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (ruby_package != nullptr) { + _has_bits_[0] |= 0x00000200u; } else { - clear_has_ruby_package(); + _has_bits_[0] &= ~0x00000200u; } - ruby_package_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + ruby_package_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ruby_package, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.ruby_package) } @@ -10134,24 +10071,24 @@ inline int FileOptions::uninterpreted_option_size() const { inline void FileOptions::clear_uninterpreted_option() { uninterpreted_option_.Clear(); } -inline ::google::protobuf::UninterpretedOption* FileOptions::mutable_uninterpreted_option(int index) { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* FileOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.uninterpreted_option) return uninterpreted_option_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* FileOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileOptions.uninterpreted_option) return &uninterpreted_option_; } -inline const ::google::protobuf::UninterpretedOption& FileOptions::uninterpreted_option(int index) const { +inline const PROTOBUF_NAMESPACE_ID::UninterpretedOption& FileOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.uninterpreted_option) return uninterpreted_option_.Get(index); } -inline ::google::protobuf::UninterpretedOption* FileOptions::add_uninterpreted_option() { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* FileOptions::add_uninterpreted_option() { // @@protoc_insertion_point(field_add:google.protobuf.FileOptions.uninterpreted_option) return uninterpreted_option_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& FileOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.FileOptions.uninterpreted_option) return uninterpreted_option_; @@ -10165,22 +10102,16 @@ FileOptions::uninterpreted_option() const { inline bool MessageOptions::has_message_set_wire_format() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void MessageOptions::set_has_message_set_wire_format() { - _has_bits_[0] |= 0x00000001u; -} -inline void MessageOptions::clear_has_message_set_wire_format() { - _has_bits_[0] &= ~0x00000001u; -} inline void MessageOptions::clear_message_set_wire_format() { message_set_wire_format_ = false; - clear_has_message_set_wire_format(); + _has_bits_[0] &= ~0x00000001u; } inline bool MessageOptions::message_set_wire_format() const { // @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.message_set_wire_format) return message_set_wire_format_; } inline void MessageOptions::set_message_set_wire_format(bool value) { - set_has_message_set_wire_format(); + _has_bits_[0] |= 0x00000001u; message_set_wire_format_ = value; // @@protoc_insertion_point(field_set:google.protobuf.MessageOptions.message_set_wire_format) } @@ -10189,22 +10120,16 @@ inline void MessageOptions::set_message_set_wire_format(bool value) { inline bool MessageOptions::has_no_standard_descriptor_accessor() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void MessageOptions::set_has_no_standard_descriptor_accessor() { - _has_bits_[0] |= 0x00000002u; -} -inline void MessageOptions::clear_has_no_standard_descriptor_accessor() { - _has_bits_[0] &= ~0x00000002u; -} inline void MessageOptions::clear_no_standard_descriptor_accessor() { no_standard_descriptor_accessor_ = false; - clear_has_no_standard_descriptor_accessor(); + _has_bits_[0] &= ~0x00000002u; } inline bool MessageOptions::no_standard_descriptor_accessor() const { // @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.no_standard_descriptor_accessor) return no_standard_descriptor_accessor_; } inline void MessageOptions::set_no_standard_descriptor_accessor(bool value) { - set_has_no_standard_descriptor_accessor(); + _has_bits_[0] |= 0x00000002u; no_standard_descriptor_accessor_ = value; // @@protoc_insertion_point(field_set:google.protobuf.MessageOptions.no_standard_descriptor_accessor) } @@ -10213,22 +10138,16 @@ inline void MessageOptions::set_no_standard_descriptor_accessor(bool value) { inline bool MessageOptions::has_deprecated() const { return (_has_bits_[0] & 0x00000004u) != 0; } -inline void MessageOptions::set_has_deprecated() { - _has_bits_[0] |= 0x00000004u; -} -inline void MessageOptions::clear_has_deprecated() { - _has_bits_[0] &= ~0x00000004u; -} inline void MessageOptions::clear_deprecated() { deprecated_ = false; - clear_has_deprecated(); + _has_bits_[0] &= ~0x00000004u; } inline bool MessageOptions::deprecated() const { // @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.deprecated) return deprecated_; } inline void MessageOptions::set_deprecated(bool value) { - set_has_deprecated(); + _has_bits_[0] |= 0x00000004u; deprecated_ = value; // @@protoc_insertion_point(field_set:google.protobuf.MessageOptions.deprecated) } @@ -10237,22 +10156,16 @@ inline void MessageOptions::set_deprecated(bool value) { inline bool MessageOptions::has_map_entry() const { return (_has_bits_[0] & 0x00000008u) != 0; } -inline void MessageOptions::set_has_map_entry() { - _has_bits_[0] |= 0x00000008u; -} -inline void MessageOptions::clear_has_map_entry() { - _has_bits_[0] &= ~0x00000008u; -} inline void MessageOptions::clear_map_entry() { map_entry_ = false; - clear_has_map_entry(); + _has_bits_[0] &= ~0x00000008u; } inline bool MessageOptions::map_entry() const { // @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.map_entry) return map_entry_; } inline void MessageOptions::set_map_entry(bool value) { - set_has_map_entry(); + _has_bits_[0] |= 0x00000008u; map_entry_ = value; // @@protoc_insertion_point(field_set:google.protobuf.MessageOptions.map_entry) } @@ -10264,24 +10177,24 @@ inline int MessageOptions::uninterpreted_option_size() const { inline void MessageOptions::clear_uninterpreted_option() { uninterpreted_option_.Clear(); } -inline ::google::protobuf::UninterpretedOption* MessageOptions::mutable_uninterpreted_option(int index) { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* MessageOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.MessageOptions.uninterpreted_option) return uninterpreted_option_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* MessageOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.MessageOptions.uninterpreted_option) return &uninterpreted_option_; } -inline const ::google::protobuf::UninterpretedOption& MessageOptions::uninterpreted_option(int index) const { +inline const PROTOBUF_NAMESPACE_ID::UninterpretedOption& MessageOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.uninterpreted_option) return uninterpreted_option_.Get(index); } -inline ::google::protobuf::UninterpretedOption* MessageOptions::add_uninterpreted_option() { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* MessageOptions::add_uninterpreted_option() { // @@protoc_insertion_point(field_add:google.protobuf.MessageOptions.uninterpreted_option) return uninterpreted_option_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& MessageOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.MessageOptions.uninterpreted_option) return uninterpreted_option_; @@ -10295,23 +10208,17 @@ MessageOptions::uninterpreted_option() const { inline bool FieldOptions::has_ctype() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void FieldOptions::set_has_ctype() { - _has_bits_[0] |= 0x00000001u; -} -inline void FieldOptions::clear_has_ctype() { - _has_bits_[0] &= ~0x00000001u; -} inline void FieldOptions::clear_ctype() { ctype_ = 0; - clear_has_ctype(); + _has_bits_[0] &= ~0x00000001u; } -inline ::google::protobuf::FieldOptions_CType FieldOptions::ctype() const { +inline PROTOBUF_NAMESPACE_ID::FieldOptions_CType FieldOptions::ctype() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.ctype) - return static_cast< ::google::protobuf::FieldOptions_CType >(ctype_); + return static_cast< PROTOBUF_NAMESPACE_ID::FieldOptions_CType >(ctype_); } -inline void FieldOptions::set_ctype(::google::protobuf::FieldOptions_CType value) { - assert(::google::protobuf::FieldOptions_CType_IsValid(value)); - set_has_ctype(); +inline void FieldOptions::set_ctype(PROTOBUF_NAMESPACE_ID::FieldOptions_CType value) { + assert(PROTOBUF_NAMESPACE_ID::FieldOptions_CType_IsValid(value)); + _has_bits_[0] |= 0x00000001u; ctype_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.ctype) } @@ -10320,22 +10227,16 @@ inline void FieldOptions::set_ctype(::google::protobuf::FieldOptions_CType value inline bool FieldOptions::has_packed() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void FieldOptions::set_has_packed() { - _has_bits_[0] |= 0x00000002u; -} -inline void FieldOptions::clear_has_packed() { - _has_bits_[0] &= ~0x00000002u; -} inline void FieldOptions::clear_packed() { packed_ = false; - clear_has_packed(); + _has_bits_[0] &= ~0x00000002u; } inline bool FieldOptions::packed() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.packed) return packed_; } inline void FieldOptions::set_packed(bool value) { - set_has_packed(); + _has_bits_[0] |= 0x00000002u; packed_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.packed) } @@ -10344,23 +10245,17 @@ inline void FieldOptions::set_packed(bool value) { inline bool FieldOptions::has_jstype() const { return (_has_bits_[0] & 0x00000020u) != 0; } -inline void FieldOptions::set_has_jstype() { - _has_bits_[0] |= 0x00000020u; -} -inline void FieldOptions::clear_has_jstype() { - _has_bits_[0] &= ~0x00000020u; -} inline void FieldOptions::clear_jstype() { jstype_ = 0; - clear_has_jstype(); + _has_bits_[0] &= ~0x00000020u; } -inline ::google::protobuf::FieldOptions_JSType FieldOptions::jstype() const { +inline PROTOBUF_NAMESPACE_ID::FieldOptions_JSType FieldOptions::jstype() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.jstype) - return static_cast< ::google::protobuf::FieldOptions_JSType >(jstype_); + return static_cast< PROTOBUF_NAMESPACE_ID::FieldOptions_JSType >(jstype_); } -inline void FieldOptions::set_jstype(::google::protobuf::FieldOptions_JSType value) { - assert(::google::protobuf::FieldOptions_JSType_IsValid(value)); - set_has_jstype(); +inline void FieldOptions::set_jstype(PROTOBUF_NAMESPACE_ID::FieldOptions_JSType value) { + assert(PROTOBUF_NAMESPACE_ID::FieldOptions_JSType_IsValid(value)); + _has_bits_[0] |= 0x00000020u; jstype_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.jstype) } @@ -10369,22 +10264,16 @@ inline void FieldOptions::set_jstype(::google::protobuf::FieldOptions_JSType val inline bool FieldOptions::has_lazy() const { return (_has_bits_[0] & 0x00000004u) != 0; } -inline void FieldOptions::set_has_lazy() { - _has_bits_[0] |= 0x00000004u; -} -inline void FieldOptions::clear_has_lazy() { - _has_bits_[0] &= ~0x00000004u; -} inline void FieldOptions::clear_lazy() { lazy_ = false; - clear_has_lazy(); + _has_bits_[0] &= ~0x00000004u; } inline bool FieldOptions::lazy() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.lazy) return lazy_; } inline void FieldOptions::set_lazy(bool value) { - set_has_lazy(); + _has_bits_[0] |= 0x00000004u; lazy_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.lazy) } @@ -10393,22 +10282,16 @@ inline void FieldOptions::set_lazy(bool value) { inline bool FieldOptions::has_deprecated() const { return (_has_bits_[0] & 0x00000008u) != 0; } -inline void FieldOptions::set_has_deprecated() { - _has_bits_[0] |= 0x00000008u; -} -inline void FieldOptions::clear_has_deprecated() { - _has_bits_[0] &= ~0x00000008u; -} inline void FieldOptions::clear_deprecated() { deprecated_ = false; - clear_has_deprecated(); + _has_bits_[0] &= ~0x00000008u; } inline bool FieldOptions::deprecated() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.deprecated) return deprecated_; } inline void FieldOptions::set_deprecated(bool value) { - set_has_deprecated(); + _has_bits_[0] |= 0x00000008u; deprecated_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.deprecated) } @@ -10417,22 +10300,16 @@ inline void FieldOptions::set_deprecated(bool value) { inline bool FieldOptions::has_weak() const { return (_has_bits_[0] & 0x00000010u) != 0; } -inline void FieldOptions::set_has_weak() { - _has_bits_[0] |= 0x00000010u; -} -inline void FieldOptions::clear_has_weak() { - _has_bits_[0] &= ~0x00000010u; -} inline void FieldOptions::clear_weak() { weak_ = false; - clear_has_weak(); + _has_bits_[0] &= ~0x00000010u; } inline bool FieldOptions::weak() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.weak) return weak_; } inline void FieldOptions::set_weak(bool value) { - set_has_weak(); + _has_bits_[0] |= 0x00000010u; weak_ = value; // @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.weak) } @@ -10444,24 +10321,24 @@ inline int FieldOptions::uninterpreted_option_size() const { inline void FieldOptions::clear_uninterpreted_option() { uninterpreted_option_.Clear(); } -inline ::google::protobuf::UninterpretedOption* FieldOptions::mutable_uninterpreted_option(int index) { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* FieldOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FieldOptions.uninterpreted_option) return uninterpreted_option_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* FieldOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FieldOptions.uninterpreted_option) return &uninterpreted_option_; } -inline const ::google::protobuf::UninterpretedOption& FieldOptions::uninterpreted_option(int index) const { +inline const PROTOBUF_NAMESPACE_ID::UninterpretedOption& FieldOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.uninterpreted_option) return uninterpreted_option_.Get(index); } -inline ::google::protobuf::UninterpretedOption* FieldOptions::add_uninterpreted_option() { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* FieldOptions::add_uninterpreted_option() { // @@protoc_insertion_point(field_add:google.protobuf.FieldOptions.uninterpreted_option) return uninterpreted_option_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& FieldOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.FieldOptions.uninterpreted_option) return uninterpreted_option_; @@ -10478,24 +10355,24 @@ inline int OneofOptions::uninterpreted_option_size() const { inline void OneofOptions::clear_uninterpreted_option() { uninterpreted_option_.Clear(); } -inline ::google::protobuf::UninterpretedOption* OneofOptions::mutable_uninterpreted_option(int index) { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* OneofOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.OneofOptions.uninterpreted_option) return uninterpreted_option_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* OneofOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.OneofOptions.uninterpreted_option) return &uninterpreted_option_; } -inline const ::google::protobuf::UninterpretedOption& OneofOptions::uninterpreted_option(int index) const { +inline const PROTOBUF_NAMESPACE_ID::UninterpretedOption& OneofOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.OneofOptions.uninterpreted_option) return uninterpreted_option_.Get(index); } -inline ::google::protobuf::UninterpretedOption* OneofOptions::add_uninterpreted_option() { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* OneofOptions::add_uninterpreted_option() { // @@protoc_insertion_point(field_add:google.protobuf.OneofOptions.uninterpreted_option) return uninterpreted_option_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& OneofOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.OneofOptions.uninterpreted_option) return uninterpreted_option_; @@ -10509,22 +10386,16 @@ OneofOptions::uninterpreted_option() const { inline bool EnumOptions::has_allow_alias() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void EnumOptions::set_has_allow_alias() { - _has_bits_[0] |= 0x00000001u; -} -inline void EnumOptions::clear_has_allow_alias() { - _has_bits_[0] &= ~0x00000001u; -} inline void EnumOptions::clear_allow_alias() { allow_alias_ = false; - clear_has_allow_alias(); + _has_bits_[0] &= ~0x00000001u; } inline bool EnumOptions::allow_alias() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumOptions.allow_alias) return allow_alias_; } inline void EnumOptions::set_allow_alias(bool value) { - set_has_allow_alias(); + _has_bits_[0] |= 0x00000001u; allow_alias_ = value; // @@protoc_insertion_point(field_set:google.protobuf.EnumOptions.allow_alias) } @@ -10533,22 +10404,16 @@ inline void EnumOptions::set_allow_alias(bool value) { inline bool EnumOptions::has_deprecated() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void EnumOptions::set_has_deprecated() { - _has_bits_[0] |= 0x00000002u; -} -inline void EnumOptions::clear_has_deprecated() { - _has_bits_[0] &= ~0x00000002u; -} inline void EnumOptions::clear_deprecated() { deprecated_ = false; - clear_has_deprecated(); + _has_bits_[0] &= ~0x00000002u; } inline bool EnumOptions::deprecated() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumOptions.deprecated) return deprecated_; } inline void EnumOptions::set_deprecated(bool value) { - set_has_deprecated(); + _has_bits_[0] |= 0x00000002u; deprecated_ = value; // @@protoc_insertion_point(field_set:google.protobuf.EnumOptions.deprecated) } @@ -10560,24 +10425,24 @@ inline int EnumOptions::uninterpreted_option_size() const { inline void EnumOptions::clear_uninterpreted_option() { uninterpreted_option_.Clear(); } -inline ::google::protobuf::UninterpretedOption* EnumOptions::mutable_uninterpreted_option(int index) { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* EnumOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.EnumOptions.uninterpreted_option) return uninterpreted_option_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* EnumOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumOptions.uninterpreted_option) return &uninterpreted_option_; } -inline const ::google::protobuf::UninterpretedOption& EnumOptions::uninterpreted_option(int index) const { +inline const PROTOBUF_NAMESPACE_ID::UninterpretedOption& EnumOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.EnumOptions.uninterpreted_option) return uninterpreted_option_.Get(index); } -inline ::google::protobuf::UninterpretedOption* EnumOptions::add_uninterpreted_option() { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* EnumOptions::add_uninterpreted_option() { // @@protoc_insertion_point(field_add:google.protobuf.EnumOptions.uninterpreted_option) return uninterpreted_option_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& EnumOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.EnumOptions.uninterpreted_option) return uninterpreted_option_; @@ -10591,22 +10456,16 @@ EnumOptions::uninterpreted_option() const { inline bool EnumValueOptions::has_deprecated() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void EnumValueOptions::set_has_deprecated() { - _has_bits_[0] |= 0x00000001u; -} -inline void EnumValueOptions::clear_has_deprecated() { - _has_bits_[0] &= ~0x00000001u; -} inline void EnumValueOptions::clear_deprecated() { deprecated_ = false; - clear_has_deprecated(); + _has_bits_[0] &= ~0x00000001u; } inline bool EnumValueOptions::deprecated() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumValueOptions.deprecated) return deprecated_; } inline void EnumValueOptions::set_deprecated(bool value) { - set_has_deprecated(); + _has_bits_[0] |= 0x00000001u; deprecated_ = value; // @@protoc_insertion_point(field_set:google.protobuf.EnumValueOptions.deprecated) } @@ -10618,24 +10477,24 @@ inline int EnumValueOptions::uninterpreted_option_size() const { inline void EnumValueOptions::clear_uninterpreted_option() { uninterpreted_option_.Clear(); } -inline ::google::protobuf::UninterpretedOption* EnumValueOptions::mutable_uninterpreted_option(int index) { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* EnumValueOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.EnumValueOptions.uninterpreted_option) return uninterpreted_option_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* EnumValueOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumValueOptions.uninterpreted_option) return &uninterpreted_option_; } -inline const ::google::protobuf::UninterpretedOption& EnumValueOptions::uninterpreted_option(int index) const { +inline const PROTOBUF_NAMESPACE_ID::UninterpretedOption& EnumValueOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.EnumValueOptions.uninterpreted_option) return uninterpreted_option_.Get(index); } -inline ::google::protobuf::UninterpretedOption* EnumValueOptions::add_uninterpreted_option() { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* EnumValueOptions::add_uninterpreted_option() { // @@protoc_insertion_point(field_add:google.protobuf.EnumValueOptions.uninterpreted_option) return uninterpreted_option_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& EnumValueOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.EnumValueOptions.uninterpreted_option) return uninterpreted_option_; @@ -10649,22 +10508,16 @@ EnumValueOptions::uninterpreted_option() const { inline bool ServiceOptions::has_deprecated() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void ServiceOptions::set_has_deprecated() { - _has_bits_[0] |= 0x00000001u; -} -inline void ServiceOptions::clear_has_deprecated() { - _has_bits_[0] &= ~0x00000001u; -} inline void ServiceOptions::clear_deprecated() { deprecated_ = false; - clear_has_deprecated(); + _has_bits_[0] &= ~0x00000001u; } inline bool ServiceOptions::deprecated() const { // @@protoc_insertion_point(field_get:google.protobuf.ServiceOptions.deprecated) return deprecated_; } inline void ServiceOptions::set_deprecated(bool value) { - set_has_deprecated(); + _has_bits_[0] |= 0x00000001u; deprecated_ = value; // @@protoc_insertion_point(field_set:google.protobuf.ServiceOptions.deprecated) } @@ -10676,24 +10529,24 @@ inline int ServiceOptions::uninterpreted_option_size() const { inline void ServiceOptions::clear_uninterpreted_option() { uninterpreted_option_.Clear(); } -inline ::google::protobuf::UninterpretedOption* ServiceOptions::mutable_uninterpreted_option(int index) { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* ServiceOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.ServiceOptions.uninterpreted_option) return uninterpreted_option_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* ServiceOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.ServiceOptions.uninterpreted_option) return &uninterpreted_option_; } -inline const ::google::protobuf::UninterpretedOption& ServiceOptions::uninterpreted_option(int index) const { +inline const PROTOBUF_NAMESPACE_ID::UninterpretedOption& ServiceOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.ServiceOptions.uninterpreted_option) return uninterpreted_option_.Get(index); } -inline ::google::protobuf::UninterpretedOption* ServiceOptions::add_uninterpreted_option() { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* ServiceOptions::add_uninterpreted_option() { // @@protoc_insertion_point(field_add:google.protobuf.ServiceOptions.uninterpreted_option) return uninterpreted_option_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& ServiceOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.ServiceOptions.uninterpreted_option) return uninterpreted_option_; @@ -10707,22 +10560,16 @@ ServiceOptions::uninterpreted_option() const { inline bool MethodOptions::has_deprecated() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void MethodOptions::set_has_deprecated() { - _has_bits_[0] |= 0x00000001u; -} -inline void MethodOptions::clear_has_deprecated() { - _has_bits_[0] &= ~0x00000001u; -} inline void MethodOptions::clear_deprecated() { deprecated_ = false; - clear_has_deprecated(); + _has_bits_[0] &= ~0x00000001u; } inline bool MethodOptions::deprecated() const { // @@protoc_insertion_point(field_get:google.protobuf.MethodOptions.deprecated) return deprecated_; } inline void MethodOptions::set_deprecated(bool value) { - set_has_deprecated(); + _has_bits_[0] |= 0x00000001u; deprecated_ = value; // @@protoc_insertion_point(field_set:google.protobuf.MethodOptions.deprecated) } @@ -10731,23 +10578,17 @@ inline void MethodOptions::set_deprecated(bool value) { inline bool MethodOptions::has_idempotency_level() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void MethodOptions::set_has_idempotency_level() { - _has_bits_[0] |= 0x00000002u; -} -inline void MethodOptions::clear_has_idempotency_level() { - _has_bits_[0] &= ~0x00000002u; -} inline void MethodOptions::clear_idempotency_level() { idempotency_level_ = 0; - clear_has_idempotency_level(); + _has_bits_[0] &= ~0x00000002u; } -inline ::google::protobuf::MethodOptions_IdempotencyLevel MethodOptions::idempotency_level() const { +inline PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel MethodOptions::idempotency_level() const { // @@protoc_insertion_point(field_get:google.protobuf.MethodOptions.idempotency_level) - return static_cast< ::google::protobuf::MethodOptions_IdempotencyLevel >(idempotency_level_); + return static_cast< PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel >(idempotency_level_); } -inline void MethodOptions::set_idempotency_level(::google::protobuf::MethodOptions_IdempotencyLevel value) { - assert(::google::protobuf::MethodOptions_IdempotencyLevel_IsValid(value)); - set_has_idempotency_level(); +inline void MethodOptions::set_idempotency_level(PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel value) { + assert(PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel_IsValid(value)); + _has_bits_[0] |= 0x00000002u; idempotency_level_ = value; // @@protoc_insertion_point(field_set:google.protobuf.MethodOptions.idempotency_level) } @@ -10759,24 +10600,24 @@ inline int MethodOptions::uninterpreted_option_size() const { inline void MethodOptions::clear_uninterpreted_option() { uninterpreted_option_.Clear(); } -inline ::google::protobuf::UninterpretedOption* MethodOptions::mutable_uninterpreted_option(int index) { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* MethodOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.MethodOptions.uninterpreted_option) return uninterpreted_option_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >* MethodOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.MethodOptions.uninterpreted_option) return &uninterpreted_option_; } -inline const ::google::protobuf::UninterpretedOption& MethodOptions::uninterpreted_option(int index) const { +inline const PROTOBUF_NAMESPACE_ID::UninterpretedOption& MethodOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.MethodOptions.uninterpreted_option) return uninterpreted_option_.Get(index); } -inline ::google::protobuf::UninterpretedOption* MethodOptions::add_uninterpreted_option() { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption* MethodOptions::add_uninterpreted_option() { // @@protoc_insertion_point(field_add:google.protobuf.MethodOptions.uninterpreted_option) return uninterpreted_option_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption >& MethodOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.MethodOptions.uninterpreted_option) return uninterpreted_option_; @@ -10790,86 +10631,78 @@ MethodOptions::uninterpreted_option() const { inline bool UninterpretedOption_NamePart::has_name_part() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void UninterpretedOption_NamePart::set_has_name_part() { - _has_bits_[0] |= 0x00000001u; -} -inline void UninterpretedOption_NamePart::clear_has_name_part() { +inline void UninterpretedOption_NamePart::clear_name_part() { + name_part_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000001u; } -inline void UninterpretedOption_NamePart::clear_name_part() { - name_part_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_name_part(); -} -inline const ::std::string& UninterpretedOption_NamePart::name_part() const { +inline const std::string& UninterpretedOption_NamePart::name_part() const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.NamePart.name_part) return name_part_.Get(); } -inline void UninterpretedOption_NamePart::set_name_part(const ::std::string& value) { - set_has_name_part(); - name_part_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void UninterpretedOption_NamePart::set_name_part(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + name_part_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.NamePart.name_part) } -#if LANG_CXX11 -inline void UninterpretedOption_NamePart::set_name_part(::std::string&& value) { - set_has_name_part(); +inline void UninterpretedOption_NamePart::set_name_part(std::string&& value) { + _has_bits_[0] |= 0x00000001u; name_part_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.UninterpretedOption.NamePart.name_part) } -#endif inline void UninterpretedOption_NamePart::set_name_part(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_name_part(); - name_part_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000001u; + name_part_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.NamePart.name_part) } inline void UninterpretedOption_NamePart::set_name_part(const char* value, size_t size) { - set_has_name_part(); - name_part_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000001u; + name_part_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.NamePart.name_part) } -inline ::std::string* UninterpretedOption_NamePart::mutable_name_part() { - set_has_name_part(); +inline std::string* UninterpretedOption_NamePart::mutable_name_part() { + _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.NamePart.name_part) - return name_part_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_part_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* UninterpretedOption_NamePart::release_name_part() { +inline std::string* UninterpretedOption_NamePart::release_name_part() { // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.NamePart.name_part) if (!has_name_part()) { - return NULL; + return nullptr; } - clear_has_name_part(); - return name_part_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000001u; + return name_part_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void UninterpretedOption_NamePart::set_allocated_name_part(::std::string* name_part) { - if (name_part != NULL) { - set_has_name_part(); +inline void UninterpretedOption_NamePart::set_allocated_name_part(std::string* name_part) { + if (name_part != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name_part(); + _has_bits_[0] &= ~0x00000001u; } - name_part_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name_part, + name_part_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name_part, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.NamePart.name_part) } -inline ::std::string* UninterpretedOption_NamePart::unsafe_arena_release_name_part() { +inline std::string* UninterpretedOption_NamePart::unsafe_arena_release_name_part() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.UninterpretedOption.NamePart.name_part) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_name_part(); - return name_part_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000001u; + return name_part_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void UninterpretedOption_NamePart::unsafe_arena_set_allocated_name_part( - ::std::string* name_part) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (name_part != NULL) { - set_has_name_part(); + std::string* name_part) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (name_part != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name_part(); + _has_bits_[0] &= ~0x00000001u; } - name_part_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + name_part_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name_part, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.UninterpretedOption.NamePart.name_part) } @@ -10878,22 +10711,16 @@ inline void UninterpretedOption_NamePart::unsafe_arena_set_allocated_name_part( inline bool UninterpretedOption_NamePart::has_is_extension() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void UninterpretedOption_NamePart::set_has_is_extension() { - _has_bits_[0] |= 0x00000002u; -} -inline void UninterpretedOption_NamePart::clear_has_is_extension() { - _has_bits_[0] &= ~0x00000002u; -} inline void UninterpretedOption_NamePart::clear_is_extension() { is_extension_ = false; - clear_has_is_extension(); + _has_bits_[0] &= ~0x00000002u; } inline bool UninterpretedOption_NamePart::is_extension() const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.NamePart.is_extension) return is_extension_; } inline void UninterpretedOption_NamePart::set_is_extension(bool value) { - set_has_is_extension(); + _has_bits_[0] |= 0x00000002u; is_extension_ = value; // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.NamePart.is_extension) } @@ -10909,24 +10736,24 @@ inline int UninterpretedOption::name_size() const { inline void UninterpretedOption::clear_name() { name_.Clear(); } -inline ::google::protobuf::UninterpretedOption_NamePart* UninterpretedOption::mutable_name(int index) { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart* UninterpretedOption::mutable_name(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.name) return name_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart >* UninterpretedOption::mutable_name() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.UninterpretedOption.name) return &name_; } -inline const ::google::protobuf::UninterpretedOption_NamePart& UninterpretedOption::name(int index) const { +inline const PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart& UninterpretedOption::name(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.name) return name_.Get(index); } -inline ::google::protobuf::UninterpretedOption_NamePart* UninterpretedOption::add_name() { +inline PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart* UninterpretedOption::add_name() { // @@protoc_insertion_point(field_add:google.protobuf.UninterpretedOption.name) return name_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart >& UninterpretedOption::name() const { // @@protoc_insertion_point(field_list:google.protobuf.UninterpretedOption.name) return name_; @@ -10936,86 +10763,78 @@ UninterpretedOption::name() const { inline bool UninterpretedOption::has_identifier_value() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void UninterpretedOption::set_has_identifier_value() { - _has_bits_[0] |= 0x00000001u; -} -inline void UninterpretedOption::clear_has_identifier_value() { +inline void UninterpretedOption::clear_identifier_value() { + identifier_value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000001u; } -inline void UninterpretedOption::clear_identifier_value() { - identifier_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_identifier_value(); -} -inline const ::std::string& UninterpretedOption::identifier_value() const { +inline const std::string& UninterpretedOption::identifier_value() const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.identifier_value) return identifier_value_.Get(); } -inline void UninterpretedOption::set_identifier_value(const ::std::string& value) { - set_has_identifier_value(); - identifier_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void UninterpretedOption::set_identifier_value(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + identifier_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.identifier_value) } -#if LANG_CXX11 -inline void UninterpretedOption::set_identifier_value(::std::string&& value) { - set_has_identifier_value(); +inline void UninterpretedOption::set_identifier_value(std::string&& value) { + _has_bits_[0] |= 0x00000001u; identifier_value_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.UninterpretedOption.identifier_value) } -#endif inline void UninterpretedOption::set_identifier_value(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_identifier_value(); - identifier_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000001u; + identifier_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.identifier_value) } inline void UninterpretedOption::set_identifier_value(const char* value, size_t size) { - set_has_identifier_value(); - identifier_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000001u; + identifier_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.identifier_value) } -inline ::std::string* UninterpretedOption::mutable_identifier_value() { - set_has_identifier_value(); +inline std::string* UninterpretedOption::mutable_identifier_value() { + _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.identifier_value) - return identifier_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return identifier_value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* UninterpretedOption::release_identifier_value() { +inline std::string* UninterpretedOption::release_identifier_value() { // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.identifier_value) if (!has_identifier_value()) { - return NULL; + return nullptr; } - clear_has_identifier_value(); - return identifier_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000001u; + return identifier_value_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void UninterpretedOption::set_allocated_identifier_value(::std::string* identifier_value) { - if (identifier_value != NULL) { - set_has_identifier_value(); +inline void UninterpretedOption::set_allocated_identifier_value(std::string* identifier_value) { + if (identifier_value != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_identifier_value(); + _has_bits_[0] &= ~0x00000001u; } - identifier_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), identifier_value, + identifier_value_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), identifier_value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.identifier_value) } -inline ::std::string* UninterpretedOption::unsafe_arena_release_identifier_value() { +inline std::string* UninterpretedOption::unsafe_arena_release_identifier_value() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.UninterpretedOption.identifier_value) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_identifier_value(); - return identifier_value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000001u; + return identifier_value_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void UninterpretedOption::unsafe_arena_set_allocated_identifier_value( - ::std::string* identifier_value) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (identifier_value != NULL) { - set_has_identifier_value(); + std::string* identifier_value) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (identifier_value != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_identifier_value(); + _has_bits_[0] &= ~0x00000001u; } - identifier_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + identifier_value_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), identifier_value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.UninterpretedOption.identifier_value) } @@ -11024,22 +10843,16 @@ inline void UninterpretedOption::unsafe_arena_set_allocated_identifier_value( inline bool UninterpretedOption::has_positive_int_value() const { return (_has_bits_[0] & 0x00000008u) != 0; } -inline void UninterpretedOption::set_has_positive_int_value() { - _has_bits_[0] |= 0x00000008u; -} -inline void UninterpretedOption::clear_has_positive_int_value() { +inline void UninterpretedOption::clear_positive_int_value() { + positive_int_value_ = PROTOBUF_ULONGLONG(0); _has_bits_[0] &= ~0x00000008u; } -inline void UninterpretedOption::clear_positive_int_value() { - positive_int_value_ = GOOGLE_ULONGLONG(0); - clear_has_positive_int_value(); -} -inline ::google::protobuf::uint64 UninterpretedOption::positive_int_value() const { +inline ::PROTOBUF_NAMESPACE_ID::uint64 UninterpretedOption::positive_int_value() const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.positive_int_value) return positive_int_value_; } -inline void UninterpretedOption::set_positive_int_value(::google::protobuf::uint64 value) { - set_has_positive_int_value(); +inline void UninterpretedOption::set_positive_int_value(::PROTOBUF_NAMESPACE_ID::uint64 value) { + _has_bits_[0] |= 0x00000008u; positive_int_value_ = value; // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.positive_int_value) } @@ -11048,22 +10861,16 @@ inline void UninterpretedOption::set_positive_int_value(::google::protobuf::uint inline bool UninterpretedOption::has_negative_int_value() const { return (_has_bits_[0] & 0x00000010u) != 0; } -inline void UninterpretedOption::set_has_negative_int_value() { - _has_bits_[0] |= 0x00000010u; -} -inline void UninterpretedOption::clear_has_negative_int_value() { +inline void UninterpretedOption::clear_negative_int_value() { + negative_int_value_ = PROTOBUF_LONGLONG(0); _has_bits_[0] &= ~0x00000010u; } -inline void UninterpretedOption::clear_negative_int_value() { - negative_int_value_ = GOOGLE_LONGLONG(0); - clear_has_negative_int_value(); -} -inline ::google::protobuf::int64 UninterpretedOption::negative_int_value() const { +inline ::PROTOBUF_NAMESPACE_ID::int64 UninterpretedOption::negative_int_value() const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.negative_int_value) return negative_int_value_; } -inline void UninterpretedOption::set_negative_int_value(::google::protobuf::int64 value) { - set_has_negative_int_value(); +inline void UninterpretedOption::set_negative_int_value(::PROTOBUF_NAMESPACE_ID::int64 value) { + _has_bits_[0] |= 0x00000010u; negative_int_value_ = value; // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.negative_int_value) } @@ -11072,22 +10879,16 @@ inline void UninterpretedOption::set_negative_int_value(::google::protobuf::int6 inline bool UninterpretedOption::has_double_value() const { return (_has_bits_[0] & 0x00000020u) != 0; } -inline void UninterpretedOption::set_has_double_value() { - _has_bits_[0] |= 0x00000020u; -} -inline void UninterpretedOption::clear_has_double_value() { - _has_bits_[0] &= ~0x00000020u; -} inline void UninterpretedOption::clear_double_value() { double_value_ = 0; - clear_has_double_value(); + _has_bits_[0] &= ~0x00000020u; } inline double UninterpretedOption::double_value() const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.double_value) return double_value_; } inline void UninterpretedOption::set_double_value(double value) { - set_has_double_value(); + _has_bits_[0] |= 0x00000020u; double_value_ = value; // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.double_value) } @@ -11096,86 +10897,78 @@ inline void UninterpretedOption::set_double_value(double value) { inline bool UninterpretedOption::has_string_value() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void UninterpretedOption::set_has_string_value() { - _has_bits_[0] |= 0x00000002u; -} -inline void UninterpretedOption::clear_has_string_value() { +inline void UninterpretedOption::clear_string_value() { + string_value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000002u; } -inline void UninterpretedOption::clear_string_value() { - string_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_string_value(); -} -inline const ::std::string& UninterpretedOption::string_value() const { +inline const std::string& UninterpretedOption::string_value() const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.string_value) return string_value_.Get(); } -inline void UninterpretedOption::set_string_value(const ::std::string& value) { - set_has_string_value(); - string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void UninterpretedOption::set_string_value(const std::string& value) { + _has_bits_[0] |= 0x00000002u; + string_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.string_value) } -#if LANG_CXX11 -inline void UninterpretedOption::set_string_value(::std::string&& value) { - set_has_string_value(); +inline void UninterpretedOption::set_string_value(std::string&& value) { + _has_bits_[0] |= 0x00000002u; string_value_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.UninterpretedOption.string_value) } -#endif inline void UninterpretedOption::set_string_value(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_string_value(); - string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000002u; + string_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.string_value) } inline void UninterpretedOption::set_string_value(const void* value, size_t size) { - set_has_string_value(); - string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000002u; + string_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.string_value) } -inline ::std::string* UninterpretedOption::mutable_string_value() { - set_has_string_value(); +inline std::string* UninterpretedOption::mutable_string_value() { + _has_bits_[0] |= 0x00000002u; // @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.string_value) - return string_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return string_value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* UninterpretedOption::release_string_value() { +inline std::string* UninterpretedOption::release_string_value() { // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.string_value) if (!has_string_value()) { - return NULL; + return nullptr; } - clear_has_string_value(); - return string_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000002u; + return string_value_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void UninterpretedOption::set_allocated_string_value(::std::string* string_value) { - if (string_value != NULL) { - set_has_string_value(); +inline void UninterpretedOption::set_allocated_string_value(std::string* string_value) { + if (string_value != nullptr) { + _has_bits_[0] |= 0x00000002u; } else { - clear_has_string_value(); + _has_bits_[0] &= ~0x00000002u; } - string_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), string_value, + string_value_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), string_value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.string_value) } -inline ::std::string* UninterpretedOption::unsafe_arena_release_string_value() { +inline std::string* UninterpretedOption::unsafe_arena_release_string_value() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.UninterpretedOption.string_value) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_string_value(); - return string_value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000002u; + return string_value_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void UninterpretedOption::unsafe_arena_set_allocated_string_value( - ::std::string* string_value) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (string_value != NULL) { - set_has_string_value(); + std::string* string_value) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (string_value != nullptr) { + _has_bits_[0] |= 0x00000002u; } else { - clear_has_string_value(); + _has_bits_[0] &= ~0x00000002u; } - string_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + string_value_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), string_value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.UninterpretedOption.string_value) } @@ -11184,86 +10977,78 @@ inline void UninterpretedOption::unsafe_arena_set_allocated_string_value( inline bool UninterpretedOption::has_aggregate_value() const { return (_has_bits_[0] & 0x00000004u) != 0; } -inline void UninterpretedOption::set_has_aggregate_value() { - _has_bits_[0] |= 0x00000004u; -} -inline void UninterpretedOption::clear_has_aggregate_value() { +inline void UninterpretedOption::clear_aggregate_value() { + aggregate_value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000004u; } -inline void UninterpretedOption::clear_aggregate_value() { - aggregate_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_aggregate_value(); -} -inline const ::std::string& UninterpretedOption::aggregate_value() const { +inline const std::string& UninterpretedOption::aggregate_value() const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.aggregate_value) return aggregate_value_.Get(); } -inline void UninterpretedOption::set_aggregate_value(const ::std::string& value) { - set_has_aggregate_value(); - aggregate_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void UninterpretedOption::set_aggregate_value(const std::string& value) { + _has_bits_[0] |= 0x00000004u; + aggregate_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.aggregate_value) } -#if LANG_CXX11 -inline void UninterpretedOption::set_aggregate_value(::std::string&& value) { - set_has_aggregate_value(); +inline void UninterpretedOption::set_aggregate_value(std::string&& value) { + _has_bits_[0] |= 0x00000004u; aggregate_value_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.UninterpretedOption.aggregate_value) } -#endif inline void UninterpretedOption::set_aggregate_value(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_aggregate_value(); - aggregate_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000004u; + aggregate_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.aggregate_value) } inline void UninterpretedOption::set_aggregate_value(const char* value, size_t size) { - set_has_aggregate_value(); - aggregate_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000004u; + aggregate_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.aggregate_value) } -inline ::std::string* UninterpretedOption::mutable_aggregate_value() { - set_has_aggregate_value(); +inline std::string* UninterpretedOption::mutable_aggregate_value() { + _has_bits_[0] |= 0x00000004u; // @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.aggregate_value) - return aggregate_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return aggregate_value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* UninterpretedOption::release_aggregate_value() { +inline std::string* UninterpretedOption::release_aggregate_value() { // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.aggregate_value) if (!has_aggregate_value()) { - return NULL; + return nullptr; } - clear_has_aggregate_value(); - return aggregate_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000004u; + return aggregate_value_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void UninterpretedOption::set_allocated_aggregate_value(::std::string* aggregate_value) { - if (aggregate_value != NULL) { - set_has_aggregate_value(); +inline void UninterpretedOption::set_allocated_aggregate_value(std::string* aggregate_value) { + if (aggregate_value != nullptr) { + _has_bits_[0] |= 0x00000004u; } else { - clear_has_aggregate_value(); + _has_bits_[0] &= ~0x00000004u; } - aggregate_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), aggregate_value, + aggregate_value_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), aggregate_value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.aggregate_value) } -inline ::std::string* UninterpretedOption::unsafe_arena_release_aggregate_value() { +inline std::string* UninterpretedOption::unsafe_arena_release_aggregate_value() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.UninterpretedOption.aggregate_value) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_aggregate_value(); - return aggregate_value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000004u; + return aggregate_value_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void UninterpretedOption::unsafe_arena_set_allocated_aggregate_value( - ::std::string* aggregate_value) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (aggregate_value != NULL) { - set_has_aggregate_value(); + std::string* aggregate_value) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (aggregate_value != nullptr) { + _has_bits_[0] |= 0x00000004u; } else { - clear_has_aggregate_value(); + _has_bits_[0] &= ~0x00000004u; } - aggregate_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + aggregate_value_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), aggregate_value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.UninterpretedOption.aggregate_value) } @@ -11279,24 +11064,24 @@ inline int SourceCodeInfo_Location::path_size() const { inline void SourceCodeInfo_Location::clear_path() { path_.Clear(); } -inline ::google::protobuf::int32 SourceCodeInfo_Location::path(int index) const { +inline ::PROTOBUF_NAMESPACE_ID::int32 SourceCodeInfo_Location::path(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.path) return path_.Get(index); } -inline void SourceCodeInfo_Location::set_path(int index, ::google::protobuf::int32 value) { +inline void SourceCodeInfo_Location::set_path(int index, ::PROTOBUF_NAMESPACE_ID::int32 value) { path_.Set(index, value); // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.path) } -inline void SourceCodeInfo_Location::add_path(::google::protobuf::int32 value) { +inline void SourceCodeInfo_Location::add_path(::PROTOBUF_NAMESPACE_ID::int32 value) { path_.Add(value); // @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.Location.path) } -inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >& SourceCodeInfo_Location::path() const { // @@protoc_insertion_point(field_list:google.protobuf.SourceCodeInfo.Location.path) return path_; } -inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >* SourceCodeInfo_Location::mutable_path() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.SourceCodeInfo.Location.path) return &path_; @@ -11309,24 +11094,24 @@ inline int SourceCodeInfo_Location::span_size() const { inline void SourceCodeInfo_Location::clear_span() { span_.Clear(); } -inline ::google::protobuf::int32 SourceCodeInfo_Location::span(int index) const { +inline ::PROTOBUF_NAMESPACE_ID::int32 SourceCodeInfo_Location::span(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.span) return span_.Get(index); } -inline void SourceCodeInfo_Location::set_span(int index, ::google::protobuf::int32 value) { +inline void SourceCodeInfo_Location::set_span(int index, ::PROTOBUF_NAMESPACE_ID::int32 value) { span_.Set(index, value); // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.span) } -inline void SourceCodeInfo_Location::add_span(::google::protobuf::int32 value) { +inline void SourceCodeInfo_Location::add_span(::PROTOBUF_NAMESPACE_ID::int32 value) { span_.Add(value); // @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.Location.span) } -inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >& SourceCodeInfo_Location::span() const { // @@protoc_insertion_point(field_list:google.protobuf.SourceCodeInfo.Location.span) return span_; } -inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >* SourceCodeInfo_Location::mutable_span() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.SourceCodeInfo.Location.span) return &span_; @@ -11336,86 +11121,78 @@ SourceCodeInfo_Location::mutable_span() { inline bool SourceCodeInfo_Location::has_leading_comments() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void SourceCodeInfo_Location::set_has_leading_comments() { - _has_bits_[0] |= 0x00000001u; -} -inline void SourceCodeInfo_Location::clear_has_leading_comments() { +inline void SourceCodeInfo_Location::clear_leading_comments() { + leading_comments_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000001u; } -inline void SourceCodeInfo_Location::clear_leading_comments() { - leading_comments_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_leading_comments(); -} -inline const ::std::string& SourceCodeInfo_Location::leading_comments() const { +inline const std::string& SourceCodeInfo_Location::leading_comments() const { // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.leading_comments) return leading_comments_.Get(); } -inline void SourceCodeInfo_Location::set_leading_comments(const ::std::string& value) { - set_has_leading_comments(); - leading_comments_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void SourceCodeInfo_Location::set_leading_comments(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + leading_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.leading_comments) } -#if LANG_CXX11 -inline void SourceCodeInfo_Location::set_leading_comments(::std::string&& value) { - set_has_leading_comments(); +inline void SourceCodeInfo_Location::set_leading_comments(std::string&& value) { + _has_bits_[0] |= 0x00000001u; leading_comments_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.SourceCodeInfo.Location.leading_comments) } -#endif inline void SourceCodeInfo_Location::set_leading_comments(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_leading_comments(); - leading_comments_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000001u; + leading_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.SourceCodeInfo.Location.leading_comments) } inline void SourceCodeInfo_Location::set_leading_comments(const char* value, size_t size) { - set_has_leading_comments(); - leading_comments_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000001u; + leading_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceCodeInfo.Location.leading_comments) } -inline ::std::string* SourceCodeInfo_Location::mutable_leading_comments() { - set_has_leading_comments(); +inline std::string* SourceCodeInfo_Location::mutable_leading_comments() { + _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.Location.leading_comments) - return leading_comments_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return leading_comments_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* SourceCodeInfo_Location::release_leading_comments() { +inline std::string* SourceCodeInfo_Location::release_leading_comments() { // @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.leading_comments) if (!has_leading_comments()) { - return NULL; + return nullptr; } - clear_has_leading_comments(); - return leading_comments_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000001u; + return leading_comments_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void SourceCodeInfo_Location::set_allocated_leading_comments(::std::string* leading_comments) { - if (leading_comments != NULL) { - set_has_leading_comments(); +inline void SourceCodeInfo_Location::set_allocated_leading_comments(std::string* leading_comments) { + if (leading_comments != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_leading_comments(); + _has_bits_[0] &= ~0x00000001u; } - leading_comments_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), leading_comments, + leading_comments_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), leading_comments, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceCodeInfo.Location.leading_comments) } -inline ::std::string* SourceCodeInfo_Location::unsafe_arena_release_leading_comments() { +inline std::string* SourceCodeInfo_Location::unsafe_arena_release_leading_comments() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.SourceCodeInfo.Location.leading_comments) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_leading_comments(); - return leading_comments_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000001u; + return leading_comments_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void SourceCodeInfo_Location::unsafe_arena_set_allocated_leading_comments( - ::std::string* leading_comments) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (leading_comments != NULL) { - set_has_leading_comments(); + std::string* leading_comments) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (leading_comments != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_leading_comments(); + _has_bits_[0] &= ~0x00000001u; } - leading_comments_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + leading_comments_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), leading_comments, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.SourceCodeInfo.Location.leading_comments) } @@ -11424,86 +11201,78 @@ inline void SourceCodeInfo_Location::unsafe_arena_set_allocated_leading_comments inline bool SourceCodeInfo_Location::has_trailing_comments() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void SourceCodeInfo_Location::set_has_trailing_comments() { - _has_bits_[0] |= 0x00000002u; -} -inline void SourceCodeInfo_Location::clear_has_trailing_comments() { +inline void SourceCodeInfo_Location::clear_trailing_comments() { + trailing_comments_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000002u; } -inline void SourceCodeInfo_Location::clear_trailing_comments() { - trailing_comments_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_trailing_comments(); -} -inline const ::std::string& SourceCodeInfo_Location::trailing_comments() const { +inline const std::string& SourceCodeInfo_Location::trailing_comments() const { // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.trailing_comments) return trailing_comments_.Get(); } -inline void SourceCodeInfo_Location::set_trailing_comments(const ::std::string& value) { - set_has_trailing_comments(); - trailing_comments_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void SourceCodeInfo_Location::set_trailing_comments(const std::string& value) { + _has_bits_[0] |= 0x00000002u; + trailing_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.trailing_comments) } -#if LANG_CXX11 -inline void SourceCodeInfo_Location::set_trailing_comments(::std::string&& value) { - set_has_trailing_comments(); +inline void SourceCodeInfo_Location::set_trailing_comments(std::string&& value) { + _has_bits_[0] |= 0x00000002u; trailing_comments_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.SourceCodeInfo.Location.trailing_comments) } -#endif inline void SourceCodeInfo_Location::set_trailing_comments(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_trailing_comments(); - trailing_comments_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000002u; + trailing_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.SourceCodeInfo.Location.trailing_comments) } inline void SourceCodeInfo_Location::set_trailing_comments(const char* value, size_t size) { - set_has_trailing_comments(); - trailing_comments_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000002u; + trailing_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceCodeInfo.Location.trailing_comments) } -inline ::std::string* SourceCodeInfo_Location::mutable_trailing_comments() { - set_has_trailing_comments(); +inline std::string* SourceCodeInfo_Location::mutable_trailing_comments() { + _has_bits_[0] |= 0x00000002u; // @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.Location.trailing_comments) - return trailing_comments_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return trailing_comments_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* SourceCodeInfo_Location::release_trailing_comments() { +inline std::string* SourceCodeInfo_Location::release_trailing_comments() { // @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.trailing_comments) if (!has_trailing_comments()) { - return NULL; + return nullptr; } - clear_has_trailing_comments(); - return trailing_comments_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000002u; + return trailing_comments_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void SourceCodeInfo_Location::set_allocated_trailing_comments(::std::string* trailing_comments) { - if (trailing_comments != NULL) { - set_has_trailing_comments(); +inline void SourceCodeInfo_Location::set_allocated_trailing_comments(std::string* trailing_comments) { + if (trailing_comments != nullptr) { + _has_bits_[0] |= 0x00000002u; } else { - clear_has_trailing_comments(); + _has_bits_[0] &= ~0x00000002u; } - trailing_comments_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), trailing_comments, + trailing_comments_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), trailing_comments, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceCodeInfo.Location.trailing_comments) } -inline ::std::string* SourceCodeInfo_Location::unsafe_arena_release_trailing_comments() { +inline std::string* SourceCodeInfo_Location::unsafe_arena_release_trailing_comments() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.SourceCodeInfo.Location.trailing_comments) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_trailing_comments(); - return trailing_comments_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000002u; + return trailing_comments_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void SourceCodeInfo_Location::unsafe_arena_set_allocated_trailing_comments( - ::std::string* trailing_comments) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (trailing_comments != NULL) { - set_has_trailing_comments(); + std::string* trailing_comments) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (trailing_comments != nullptr) { + _has_bits_[0] |= 0x00000002u; } else { - clear_has_trailing_comments(); + _has_bits_[0] &= ~0x00000002u; } - trailing_comments_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + trailing_comments_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), trailing_comments, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.SourceCodeInfo.Location.trailing_comments) } @@ -11515,26 +11284,24 @@ inline int SourceCodeInfo_Location::leading_detached_comments_size() const { inline void SourceCodeInfo_Location::clear_leading_detached_comments() { leading_detached_comments_.Clear(); } -inline const ::std::string& SourceCodeInfo_Location::leading_detached_comments(int index) const { +inline const std::string& SourceCodeInfo_Location::leading_detached_comments(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) return leading_detached_comments_.Get(index); } -inline ::std::string* SourceCodeInfo_Location::mutable_leading_detached_comments(int index) { +inline std::string* SourceCodeInfo_Location::mutable_leading_detached_comments(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) return leading_detached_comments_.Mutable(index); } -inline void SourceCodeInfo_Location::set_leading_detached_comments(int index, const ::std::string& value) { +inline void SourceCodeInfo_Location::set_leading_detached_comments(int index, const std::string& value) { // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) leading_detached_comments_.Mutable(index)->assign(value); } -#if LANG_CXX11 -inline void SourceCodeInfo_Location::set_leading_detached_comments(int index, ::std::string&& value) { +inline void SourceCodeInfo_Location::set_leading_detached_comments(int index, std::string&& value) { // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) leading_detached_comments_.Mutable(index)->assign(std::move(value)); } -#endif inline void SourceCodeInfo_Location::set_leading_detached_comments(int index, const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); leading_detached_comments_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) } @@ -11543,22 +11310,20 @@ inline void SourceCodeInfo_Location::set_leading_detached_comments(int index, co reinterpret_cast(value), size); // @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) } -inline ::std::string* SourceCodeInfo_Location::add_leading_detached_comments() { +inline std::string* SourceCodeInfo_Location::add_leading_detached_comments() { // @@protoc_insertion_point(field_add_mutable:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) return leading_detached_comments_.Add(); } -inline void SourceCodeInfo_Location::add_leading_detached_comments(const ::std::string& value) { +inline void SourceCodeInfo_Location::add_leading_detached_comments(const std::string& value) { leading_detached_comments_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) } -#if LANG_CXX11 -inline void SourceCodeInfo_Location::add_leading_detached_comments(::std::string&& value) { +inline void SourceCodeInfo_Location::add_leading_detached_comments(std::string&& value) { leading_detached_comments_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) } -#endif inline void SourceCodeInfo_Location::add_leading_detached_comments(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); leading_detached_comments_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) } @@ -11566,12 +11331,12 @@ inline void SourceCodeInfo_Location::add_leading_detached_comments(const char* v leading_detached_comments_.Add()->assign(reinterpret_cast(value), size); // @@protoc_insertion_point(field_add_pointer:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) } -inline const ::google::protobuf::RepeatedPtrField< ::std::string>& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& SourceCodeInfo_Location::leading_detached_comments() const { // @@protoc_insertion_point(field_list:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) return leading_detached_comments_; } -inline ::google::protobuf::RepeatedPtrField< ::std::string>* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* SourceCodeInfo_Location::mutable_leading_detached_comments() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) return &leading_detached_comments_; @@ -11588,24 +11353,24 @@ inline int SourceCodeInfo::location_size() const { inline void SourceCodeInfo::clear_location() { location_.Clear(); } -inline ::google::protobuf::SourceCodeInfo_Location* SourceCodeInfo::mutable_location(int index) { +inline PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location* SourceCodeInfo::mutable_location(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.location) return location_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceCodeInfo_Location >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location >* SourceCodeInfo::mutable_location() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.SourceCodeInfo.location) return &location_; } -inline const ::google::protobuf::SourceCodeInfo_Location& SourceCodeInfo::location(int index) const { +inline const PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location& SourceCodeInfo::location(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.location) return location_.Get(index); } -inline ::google::protobuf::SourceCodeInfo_Location* SourceCodeInfo::add_location() { +inline PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location* SourceCodeInfo::add_location() { // @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.location) return location_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceCodeInfo_Location >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location >& SourceCodeInfo::location() const { // @@protoc_insertion_point(field_list:google.protobuf.SourceCodeInfo.location) return location_; @@ -11622,24 +11387,24 @@ inline int GeneratedCodeInfo_Annotation::path_size() const { inline void GeneratedCodeInfo_Annotation::clear_path() { path_.Clear(); } -inline ::google::protobuf::int32 GeneratedCodeInfo_Annotation::path(int index) const { +inline ::PROTOBUF_NAMESPACE_ID::int32 GeneratedCodeInfo_Annotation::path(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.path) return path_.Get(index); } -inline void GeneratedCodeInfo_Annotation::set_path(int index, ::google::protobuf::int32 value) { +inline void GeneratedCodeInfo_Annotation::set_path(int index, ::PROTOBUF_NAMESPACE_ID::int32 value) { path_.Set(index, value); // @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.path) } -inline void GeneratedCodeInfo_Annotation::add_path(::google::protobuf::int32 value) { +inline void GeneratedCodeInfo_Annotation::add_path(::PROTOBUF_NAMESPACE_ID::int32 value) { path_.Add(value); // @@protoc_insertion_point(field_add:google.protobuf.GeneratedCodeInfo.Annotation.path) } -inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >& GeneratedCodeInfo_Annotation::path() const { // @@protoc_insertion_point(field_list:google.protobuf.GeneratedCodeInfo.Annotation.path) return path_; } -inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >* GeneratedCodeInfo_Annotation::mutable_path() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.GeneratedCodeInfo.Annotation.path) return &path_; @@ -11649,86 +11414,78 @@ GeneratedCodeInfo_Annotation::mutable_path() { inline bool GeneratedCodeInfo_Annotation::has_source_file() const { return (_has_bits_[0] & 0x00000001u) != 0; } -inline void GeneratedCodeInfo_Annotation::set_has_source_file() { - _has_bits_[0] |= 0x00000001u; -} -inline void GeneratedCodeInfo_Annotation::clear_has_source_file() { +inline void GeneratedCodeInfo_Annotation::clear_source_file() { + source_file_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _has_bits_[0] &= ~0x00000001u; } -inline void GeneratedCodeInfo_Annotation::clear_source_file() { - source_file_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); - clear_has_source_file(); -} -inline const ::std::string& GeneratedCodeInfo_Annotation::source_file() const { +inline const std::string& GeneratedCodeInfo_Annotation::source_file() const { // @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.source_file) return source_file_.Get(); } -inline void GeneratedCodeInfo_Annotation::set_source_file(const ::std::string& value) { - set_has_source_file(); - source_file_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); +inline void GeneratedCodeInfo_Annotation::set_source_file(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + source_file_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.source_file) } -#if LANG_CXX11 -inline void GeneratedCodeInfo_Annotation::set_source_file(::std::string&& value) { - set_has_source_file(); +inline void GeneratedCodeInfo_Annotation::set_source_file(std::string&& value) { + _has_bits_[0] |= 0x00000001u; source_file_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.GeneratedCodeInfo.Annotation.source_file) } -#endif inline void GeneratedCodeInfo_Annotation::set_source_file(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_source_file(); - source_file_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GOOGLE_DCHECK(value != nullptr); + _has_bits_[0] |= 0x00000001u; + source_file_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.GeneratedCodeInfo.Annotation.source_file) } inline void GeneratedCodeInfo_Annotation::set_source_file(const char* value, size_t size) { - set_has_source_file(); - source_file_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + _has_bits_[0] |= 0x00000001u; + source_file_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.GeneratedCodeInfo.Annotation.source_file) } -inline ::std::string* GeneratedCodeInfo_Annotation::mutable_source_file() { - set_has_source_file(); +inline std::string* GeneratedCodeInfo_Annotation::mutable_source_file() { + _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:google.protobuf.GeneratedCodeInfo.Annotation.source_file) - return source_file_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return source_file_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline ::std::string* GeneratedCodeInfo_Annotation::release_source_file() { +inline std::string* GeneratedCodeInfo_Annotation::release_source_file() { // @@protoc_insertion_point(field_release:google.protobuf.GeneratedCodeInfo.Annotation.source_file) if (!has_source_file()) { - return NULL; + return nullptr; } - clear_has_source_file(); - return source_file_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + _has_bits_[0] &= ~0x00000001u; + return source_file_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } -inline void GeneratedCodeInfo_Annotation::set_allocated_source_file(::std::string* source_file) { - if (source_file != NULL) { - set_has_source_file(); +inline void GeneratedCodeInfo_Annotation::set_allocated_source_file(std::string* source_file) { + if (source_file != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_source_file(); + _has_bits_[0] &= ~0x00000001u; } - source_file_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), source_file, + source_file_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), source_file, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:google.protobuf.GeneratedCodeInfo.Annotation.source_file) } -inline ::std::string* GeneratedCodeInfo_Annotation::unsafe_arena_release_source_file() { +inline std::string* GeneratedCodeInfo_Annotation::unsafe_arena_release_source_file() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.GeneratedCodeInfo.Annotation.source_file) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - clear_has_source_file(); - return source_file_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + _has_bits_[0] &= ~0x00000001u; + return source_file_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void GeneratedCodeInfo_Annotation::unsafe_arena_set_allocated_source_file( - ::std::string* source_file) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); - if (source_file != NULL) { - set_has_source_file(); + std::string* source_file) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); + if (source_file != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_source_file(); + _has_bits_[0] &= ~0x00000001u; } - source_file_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + source_file_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), source_file, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.GeneratedCodeInfo.Annotation.source_file) } @@ -11737,22 +11494,16 @@ inline void GeneratedCodeInfo_Annotation::unsafe_arena_set_allocated_source_file inline bool GeneratedCodeInfo_Annotation::has_begin() const { return (_has_bits_[0] & 0x00000002u) != 0; } -inline void GeneratedCodeInfo_Annotation::set_has_begin() { - _has_bits_[0] |= 0x00000002u; -} -inline void GeneratedCodeInfo_Annotation::clear_has_begin() { - _has_bits_[0] &= ~0x00000002u; -} inline void GeneratedCodeInfo_Annotation::clear_begin() { begin_ = 0; - clear_has_begin(); + _has_bits_[0] &= ~0x00000002u; } -inline ::google::protobuf::int32 GeneratedCodeInfo_Annotation::begin() const { +inline ::PROTOBUF_NAMESPACE_ID::int32 GeneratedCodeInfo_Annotation::begin() const { // @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.begin) return begin_; } -inline void GeneratedCodeInfo_Annotation::set_begin(::google::protobuf::int32 value) { - set_has_begin(); +inline void GeneratedCodeInfo_Annotation::set_begin(::PROTOBUF_NAMESPACE_ID::int32 value) { + _has_bits_[0] |= 0x00000002u; begin_ = value; // @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.begin) } @@ -11761,22 +11512,16 @@ inline void GeneratedCodeInfo_Annotation::set_begin(::google::protobuf::int32 va inline bool GeneratedCodeInfo_Annotation::has_end() const { return (_has_bits_[0] & 0x00000004u) != 0; } -inline void GeneratedCodeInfo_Annotation::set_has_end() { - _has_bits_[0] |= 0x00000004u; -} -inline void GeneratedCodeInfo_Annotation::clear_has_end() { - _has_bits_[0] &= ~0x00000004u; -} inline void GeneratedCodeInfo_Annotation::clear_end() { end_ = 0; - clear_has_end(); + _has_bits_[0] &= ~0x00000004u; } -inline ::google::protobuf::int32 GeneratedCodeInfo_Annotation::end() const { +inline ::PROTOBUF_NAMESPACE_ID::int32 GeneratedCodeInfo_Annotation::end() const { // @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.end) return end_; } -inline void GeneratedCodeInfo_Annotation::set_end(::google::protobuf::int32 value) { - set_has_end(); +inline void GeneratedCodeInfo_Annotation::set_end(::PROTOBUF_NAMESPACE_ID::int32 value) { + _has_bits_[0] |= 0x00000004u; end_ = value; // @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.end) } @@ -11792,24 +11537,24 @@ inline int GeneratedCodeInfo::annotation_size() const { inline void GeneratedCodeInfo::clear_annotation() { annotation_.Clear(); } -inline ::google::protobuf::GeneratedCodeInfo_Annotation* GeneratedCodeInfo::mutable_annotation(int index) { +inline PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation* GeneratedCodeInfo::mutable_annotation(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.GeneratedCodeInfo.annotation) return annotation_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::GeneratedCodeInfo_Annotation >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation >* GeneratedCodeInfo::mutable_annotation() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.GeneratedCodeInfo.annotation) return &annotation_; } -inline const ::google::protobuf::GeneratedCodeInfo_Annotation& GeneratedCodeInfo::annotation(int index) const { +inline const PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation& GeneratedCodeInfo::annotation(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.annotation) return annotation_.Get(index); } -inline ::google::protobuf::GeneratedCodeInfo_Annotation* GeneratedCodeInfo::add_annotation() { +inline PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation* GeneratedCodeInfo::add_annotation() { // @@protoc_insertion_point(field_add:google.protobuf.GeneratedCodeInfo.annotation) return annotation_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::GeneratedCodeInfo_Annotation >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation >& GeneratedCodeInfo::annotation() const { // @@protoc_insertion_point(field_list:google.protobuf.GeneratedCodeInfo.annotation) return annotation_; @@ -11873,46 +11618,44 @@ GeneratedCodeInfo::annotation() const { // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE -namespace google { -namespace protobuf { +PROTOBUF_NAMESPACE_OPEN -template <> struct is_proto_enum< ::google::protobuf::FieldDescriptorProto_Type> : ::std::true_type {}; +template <> struct is_proto_enum< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type> : ::std::true_type {}; template <> -inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldDescriptorProto_Type>() { - return ::google::protobuf::FieldDescriptorProto_Type_descriptor(); +inline const EnumDescriptor* GetEnumDescriptor< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type>() { + return PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type_descriptor(); } -template <> struct is_proto_enum< ::google::protobuf::FieldDescriptorProto_Label> : ::std::true_type {}; +template <> struct is_proto_enum< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label> : ::std::true_type {}; template <> -inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldDescriptorProto_Label>() { - return ::google::protobuf::FieldDescriptorProto_Label_descriptor(); +inline const EnumDescriptor* GetEnumDescriptor< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label>() { + return PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label_descriptor(); } -template <> struct is_proto_enum< ::google::protobuf::FileOptions_OptimizeMode> : ::std::true_type {}; +template <> struct is_proto_enum< PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode> : ::std::true_type {}; template <> -inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FileOptions_OptimizeMode>() { - return ::google::protobuf::FileOptions_OptimizeMode_descriptor(); +inline const EnumDescriptor* GetEnumDescriptor< PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode>() { + return PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode_descriptor(); } -template <> struct is_proto_enum< ::google::protobuf::FieldOptions_CType> : ::std::true_type {}; +template <> struct is_proto_enum< PROTOBUF_NAMESPACE_ID::FieldOptions_CType> : ::std::true_type {}; template <> -inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldOptions_CType>() { - return ::google::protobuf::FieldOptions_CType_descriptor(); +inline const EnumDescriptor* GetEnumDescriptor< PROTOBUF_NAMESPACE_ID::FieldOptions_CType>() { + return PROTOBUF_NAMESPACE_ID::FieldOptions_CType_descriptor(); } -template <> struct is_proto_enum< ::google::protobuf::FieldOptions_JSType> : ::std::true_type {}; +template <> struct is_proto_enum< PROTOBUF_NAMESPACE_ID::FieldOptions_JSType> : ::std::true_type {}; template <> -inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldOptions_JSType>() { - return ::google::protobuf::FieldOptions_JSType_descriptor(); +inline const EnumDescriptor* GetEnumDescriptor< PROTOBUF_NAMESPACE_ID::FieldOptions_JSType>() { + return PROTOBUF_NAMESPACE_ID::FieldOptions_JSType_descriptor(); } -template <> struct is_proto_enum< ::google::protobuf::MethodOptions_IdempotencyLevel> : ::std::true_type {}; +template <> struct is_proto_enum< PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel> : ::std::true_type {}; template <> -inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::MethodOptions_IdempotencyLevel>() { - return ::google::protobuf::MethodOptions_IdempotencyLevel_descriptor(); +inline const EnumDescriptor* GetEnumDescriptor< PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel>() { + return PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel_descriptor(); } -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto diff --git a/third_party/protobuf/src/google/protobuf/descriptor.proto b/third_party/protobuf/src/google/protobuf/descriptor.proto index ed08fcbc..d5d794f5 100644 --- a/third_party/protobuf/src/google/protobuf/descriptor.proto +++ b/third_party/protobuf/src/google/protobuf/descriptor.proto @@ -40,6 +40,7 @@ syntax = "proto2"; package google.protobuf; + option go_package = "github.com/golang/protobuf/protoc-gen-go/descriptor;descriptor"; option java_package = "com.google.protobuf"; option java_outer_classname = "DescriptorProtos"; @@ -59,8 +60,8 @@ message FileDescriptorSet { // Describes a complete .proto file. message FileDescriptorProto { - optional string name = 1; // file name, relative to root of source tree - optional string package = 2; // e.g. "foo", "foo.bar", etc. + optional string name = 1; // file name, relative to root of source tree + optional string package = 2; // e.g. "foo", "foo.bar", etc. // Names of files imported by this file. repeated string dependency = 3; @@ -115,8 +116,8 @@ message DescriptorProto { // fields or extension ranges in the same message. Reserved ranges may // not overlap. message ReservedRange { - optional int32 start = 1; // Inclusive. - optional int32 end = 2; // Exclusive. + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Exclusive. } repeated ReservedRange reserved_range = 9; // Reserved field names, which may not be used by fields in the same message. @@ -137,42 +138,42 @@ message FieldDescriptorProto { enum Type { // 0 is reserved for errors. // Order is weird for historical reasons. - TYPE_DOUBLE = 1; - TYPE_FLOAT = 2; + TYPE_DOUBLE = 1; + TYPE_FLOAT = 2; // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if // negative values are likely. - TYPE_INT64 = 3; - TYPE_UINT64 = 4; + TYPE_INT64 = 3; + TYPE_UINT64 = 4; // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if // negative values are likely. - TYPE_INT32 = 5; - TYPE_FIXED64 = 6; - TYPE_FIXED32 = 7; - TYPE_BOOL = 8; - TYPE_STRING = 9; + TYPE_INT32 = 5; + TYPE_FIXED64 = 6; + TYPE_FIXED32 = 7; + TYPE_BOOL = 8; + TYPE_STRING = 9; // Tag-delimited aggregate. // Group type is deprecated and not supported in proto3. However, Proto3 // implementations should still be able to parse the group wire format and // treat group fields as unknown fields. - TYPE_GROUP = 10; - TYPE_MESSAGE = 11; // Length-delimited aggregate. + TYPE_GROUP = 10; + TYPE_MESSAGE = 11; // Length-delimited aggregate. // New in version 2. - TYPE_BYTES = 12; - TYPE_UINT32 = 13; - TYPE_ENUM = 14; - TYPE_SFIXED32 = 15; - TYPE_SFIXED64 = 16; - TYPE_SINT32 = 17; // Uses ZigZag encoding. - TYPE_SINT64 = 18; // Uses ZigZag encoding. - }; + TYPE_BYTES = 12; + TYPE_UINT32 = 13; + TYPE_ENUM = 14; + TYPE_SFIXED32 = 15; + TYPE_SFIXED64 = 16; + TYPE_SINT32 = 17; // Uses ZigZag encoding. + TYPE_SINT64 = 18; // Uses ZigZag encoding. + } enum Label { // 0 is reserved for errors - LABEL_OPTIONAL = 1; - LABEL_REQUIRED = 2; - LABEL_REPEATED = 3; - }; + LABEL_OPTIONAL = 1; + LABEL_REQUIRED = 2; + LABEL_REPEATED = 3; + } optional string name = 1; optional int32 number = 3; @@ -234,8 +235,8 @@ message EnumDescriptorProto { // is inclusive such that it can appropriately represent the entire int32 // domain. message EnumReservedRange { - optional int32 start = 1; // Inclusive. - optional int32 end = 2; // Inclusive. + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Inclusive. } // Range of reserved numeric values. Reserved numeric values may not be used @@ -276,9 +277,9 @@ message MethodDescriptorProto { optional MethodOptions options = 4; // Identifies if client streams multiple client messages - optional bool client_streaming = 5 [default=false]; + optional bool client_streaming = 5 [default = false]; // Identifies if server streams multiple server messages - optional bool server_streaming = 6 [default=false]; + optional bool server_streaming = 6 [default = false]; } @@ -314,7 +315,6 @@ message MethodDescriptorProto { // If this turns out to be popular, a web service will be set up // to automatically assign option numbers. - message FileOptions { // Sets the Java package where classes generated from this .proto will be @@ -337,7 +337,7 @@ message FileOptions { // named by java_outer_classname. However, the outer class will still be // generated to contain the file's getDescriptor() method as well as any // top-level extensions defined in the file. - optional bool java_multiple_files = 10 [default=false]; + optional bool java_multiple_files = 10 [default = false]; // This option does nothing. optional bool java_generate_equals_and_hash = 20 [deprecated=true]; @@ -348,17 +348,17 @@ message FileOptions { // Message reflection will do the same. // However, an extension field still accepts non-UTF-8 byte sequences. // This option has no effect on when used with the lite runtime. - optional bool java_string_check_utf8 = 27 [default=false]; + optional bool java_string_check_utf8 = 27 [default = false]; // Generated classes can be optimized for speed or code size. enum OptimizeMode { - SPEED = 1; // Generate complete code for parsing, serialization, - // etc. - CODE_SIZE = 2; // Use ReflectionOps to implement these methods. - LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. + SPEED = 1; // Generate complete code for parsing, serialization, + // etc. + CODE_SIZE = 2; // Use ReflectionOps to implement these methods. + LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. } - optional OptimizeMode optimize_for = 9 [default=SPEED]; + optional OptimizeMode optimize_for = 9 [default = SPEED]; // Sets the Go package where structs generated from this .proto will be // placed. If omitted, the Go package will be derived from the following: @@ -379,20 +379,20 @@ message FileOptions { // that generate code specific to your particular RPC system. Therefore, // these default to false. Old code which depends on generic services should // explicitly set them to true. - optional bool cc_generic_services = 16 [default=false]; - optional bool java_generic_services = 17 [default=false]; - optional bool py_generic_services = 18 [default=false]; - optional bool php_generic_services = 42 [default=false]; + optional bool cc_generic_services = 16 [default = false]; + optional bool java_generic_services = 17 [default = false]; + optional bool py_generic_services = 18 [default = false]; + optional bool php_generic_services = 42 [default = false]; // Is this file deprecated? // Depending on the target platform, this can emit Deprecated annotations // for everything in the file, or it will be completely ignored; in the very // least, this is a formalization for deprecating files. - optional bool deprecated = 23 [default=false]; + optional bool deprecated = 23 [default = false]; // Enables the use of arenas for the proto messages in this file. This applies // only to generated classes for C++. - optional bool cc_enable_arenas = 31 [default=false]; + optional bool cc_enable_arenas = 31 [default = false]; // Sets the objective c class prefix which is prepended to all objective c @@ -417,10 +417,9 @@ message FileOptions { // determining the namespace. optional string php_namespace = 41; - // Use this option to change the namespace of php generated metadata classes. - // Default is empty. When this option is empty, the proto file name will be used - // for determining the namespace. + // Default is empty. When this option is empty, the proto file name will be + // used for determining the namespace. optional string php_metadata_namespace = 44; // Use this option to change the package of ruby generated classes. Default @@ -458,18 +457,18 @@ message MessageOptions { // // Because this is an option, the above two restrictions are not enforced by // the protocol compiler. - optional bool message_set_wire_format = 1 [default=false]; + optional bool message_set_wire_format = 1 [default = false]; // Disables the generation of the standard "descriptor()" accessor, which can // conflict with a field of the same name. This is meant to make migration // from proto1 easier; new code should avoid fields named "descriptor". - optional bool no_standard_descriptor_accessor = 2 [default=false]; + optional bool no_standard_descriptor_accessor = 2 [default = false]; // Is this message deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the message, or it will be completely ignored; in the very least, // this is a formalization for deprecating messages. - optional bool deprecated = 3 [default=false]; + optional bool deprecated = 3 [default = false]; // Whether the message is an automatically generated map entry type for the // maps field. @@ -486,7 +485,7 @@ message MessageOptions { // // Implementations may choose not to generate the map_entry=true message, but // use a native map in the target language to hold the keys and values. - // The reflection APIs in such implementions still need to work as + // The reflection APIs in such implementations still need to work as // if the field is a repeated message field. // // NOTE: Do not set the option in .proto files. Always use the maps syntax @@ -576,16 +575,16 @@ message FieldOptions { // implementation must either *always* check its required fields, or *never* // check its required fields, regardless of whether or not the message has // been parsed. - optional bool lazy = 5 [default=false]; + optional bool lazy = 5 [default = false]; // Is this field deprecated? // Depending on the target platform, this can emit Deprecated annotations // for accessors, or it will be completely ignored; in the very least, this // is a formalization for deprecating fields. - optional bool deprecated = 3 [default=false]; + optional bool deprecated = 3 [default = false]; // For Google-internal migration only. Do not use. - optional bool weak = 10 [default=false]; + optional bool weak = 10 [default = false]; // The parser stores options it doesn't recognize here. See above. @@ -615,7 +614,7 @@ message EnumOptions { // Depending on the target platform, this can emit Deprecated annotations // for the enum, or it will be completely ignored; in the very least, this // is a formalization for deprecating enums. - optional bool deprecated = 3 [default=false]; + optional bool deprecated = 3 [default = false]; reserved 5; // javanano_as_lite @@ -631,7 +630,7 @@ message EnumValueOptions { // Depending on the target platform, this can emit Deprecated annotations // for the enum value, or it will be completely ignored; in the very least, // this is a formalization for deprecating enum values. - optional bool deprecated = 1 [default=false]; + optional bool deprecated = 1 [default = false]; // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; @@ -651,7 +650,7 @@ message ServiceOptions { // Depending on the target platform, this can emit Deprecated annotations // for the service, or it will be completely ignored; in the very least, // this is a formalization for deprecating services. - optional bool deprecated = 33 [default=false]; + optional bool deprecated = 33 [default = false]; // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; @@ -671,18 +670,18 @@ message MethodOptions { // Depending on the target platform, this can emit Deprecated annotations // for the method, or it will be completely ignored; in the very least, // this is a formalization for deprecating methods. - optional bool deprecated = 33 [default=false]; + optional bool deprecated = 33 [default = false]; // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, // or neither? HTTP based RPC implementation may choose GET verb for safe // methods, and PUT verb for idempotent methods instead of the default POST. enum IdempotencyLevel { IDEMPOTENCY_UNKNOWN = 0; - NO_SIDE_EFFECTS = 1; // implies idempotent - IDEMPOTENT = 2; // idempotent, but may have side effects + NO_SIDE_EFFECTS = 1; // implies idempotent + IDEMPOTENT = 2; // idempotent, but may have side effects } - optional IdempotencyLevel idempotency_level = - 34 [default=IDEMPOTENCY_UNKNOWN]; + optional IdempotencyLevel idempotency_level = 34 + [default = IDEMPOTENCY_UNKNOWN]; // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; @@ -763,7 +762,7 @@ message SourceCodeInfo { // beginning of the "extend" block and is shared by all extensions within // the block. // - Just because a location's span is a subset of some other location's span - // does not mean that it is a descendent. For example, a "group" defines + // does not mean that it is a descendant. For example, a "group" defines // both a type and a field in a single declaration. Thus, the locations // corresponding to the type and field and their components will overlap. // - Code which tries to interpret locations should probably be designed to @@ -794,14 +793,14 @@ message SourceCodeInfo { // [ 4, 3, 2, 7 ] // this path refers to the whole field declaration (from the beginning // of the label to the terminating semicolon). - repeated int32 path = 1 [packed=true]; + repeated int32 path = 1 [packed = true]; // Always has exactly three or four elements: start line, start column, // end line (optional, otherwise assumed same as start line), end column. // These are packed into a single field for efficiency. Note that line // and column numbers are zero-based -- typically you will want to add // 1 to each before displaying to a user. - repeated int32 span = 2 [packed=true]; + repeated int32 span = 2 [packed = true]; // If this SourceCodeInfo represents a complete declaration, these are any // comments appearing before and after the declaration which appear to be @@ -866,7 +865,7 @@ message GeneratedCodeInfo { message Annotation { // Identifies the element in the original source .proto file. This field // is formatted the same as SourceCodeInfo.Location.path. - repeated int32 path = 1 [packed=true]; + repeated int32 path = 1 [packed = true]; // Identifies the filesystem path to the original source .proto. optional string source_file = 2; diff --git a/third_party/protobuf/src/google/protobuf/descriptor_database.cc b/third_party/protobuf/src/google/protobuf/descriptor_database.cc index ba85ef13..4f2a7669 100644 --- a/third_party/protobuf/src/google/protobuf/descriptor_database.cc +++ b/third_party/protobuf/src/google/protobuf/descriptor_database.cc @@ -37,7 +37,6 @@ #include #include -#include #include #include @@ -46,14 +45,75 @@ namespace google { namespace protobuf { +namespace { +void RecordMessageNames(const DescriptorProto& desc_proto, + const std::string& prefix, + std::set* output) { + GOOGLE_CHECK(desc_proto.has_name()); + std::string full_name = prefix.empty() + ? desc_proto.name() + : StrCat(prefix, ".", desc_proto.name()); + output->insert(full_name); + + for (const auto& d : desc_proto.nested_type()) { + RecordMessageNames(d, full_name, output); + } +} + +void RecordMessageNames(const FileDescriptorProto& file_proto, + std::set* output) { + for (const auto& d : file_proto.message_type()) { + RecordMessageNames(d, file_proto.package(), output); + } +} + +template +bool ForAllFileProtos(DescriptorDatabase* db, Fn callback, + std::vector* output) { + std::vector file_names; + if (!db->FindAllFileNames(&file_names)) { + return false; + } + std::set set; + FileDescriptorProto file_proto; + for (const auto& f : file_names) { + file_proto.Clear(); + if (!db->FindFileByName(f, &file_proto)) { + GOOGLE_LOG(ERROR) << "File not found in database (unexpected): " << f; + return false; + } + callback(file_proto, &set); + } + output->insert(output->end(), set.begin(), set.end()); + return true; +} +} // namespace + DescriptorDatabase::~DescriptorDatabase() {} +bool DescriptorDatabase::FindAllPackageNames(std::vector* output) { + return ForAllFileProtos( + this, + [](const FileDescriptorProto& file_proto, std::set* set) { + set->insert(file_proto.package()); + }, + output); +} + +bool DescriptorDatabase::FindAllMessageNames(std::vector* output) { + return ForAllFileProtos( + this, + [](const FileDescriptorProto& file_proto, std::set* set) { + RecordMessageNames(file_proto, set); + }, + output); +} + // =================================================================== template bool SimpleDescriptorDatabase::DescriptorIndex::AddFile( - const FileDescriptorProto& file, - Value value) { + const FileDescriptorProto& file, Value value) { if (!InsertIfNotPresent(&by_name_, file.name(), value)) { GOOGLE_LOG(ERROR) << "File already exists in database: " << file.name(); return false; @@ -62,7 +122,7 @@ bool SimpleDescriptorDatabase::DescriptorIndex::AddFile( // We must be careful here -- calling file.package() if file.has_package() is // false could access an uninitialized static-storage variable if we are being // run at startup time. - string path = file.has_package() ? file.package() : string(); + std::string path = file.has_package() ? file.package() : std::string(); if (!path.empty()) path += '.'; for (int i = 0; i < file.message_type_size(); i++) { @@ -85,7 +145,7 @@ bool SimpleDescriptorDatabase::DescriptorIndex::AddFile( template bool SimpleDescriptorDatabase::DescriptorIndex::AddSymbol( - const string& name, Value value) { + const std::string& name, Value value) { // We need to make sure not to violate our map invariant. // If the symbol name is invalid it could break our lookup algorithm (which @@ -98,18 +158,21 @@ bool SimpleDescriptorDatabase::DescriptorIndex::AddSymbol( // Try to look up the symbol to make sure a super-symbol doesn't already // exist. - typename std::map::iterator iter = FindLastLessOrEqual(name); + typename std::map::iterator iter = + FindLastLessOrEqual(name); if (iter == by_symbol_.end()) { // Apparently the map is currently empty. Just insert and be done with it. by_symbol_.insert( - typename std::map::value_type(name, value)); + typename std::map::value_type(name, value)); return true; } if (IsSubSymbol(iter->first, name)) { - GOOGLE_LOG(ERROR) << "Symbol name \"" << name << "\" conflicts with the existing " - "symbol \"" << iter->first << "\"."; + GOOGLE_LOG(ERROR) << "Symbol name \"" << name + << "\" conflicts with the existing " + "symbol \"" + << iter->first << "\"."; return false; } @@ -121,8 +184,10 @@ bool SimpleDescriptorDatabase::DescriptorIndex::AddSymbol( ++iter; if (iter != by_symbol_.end() && IsSubSymbol(name, iter->first)) { - GOOGLE_LOG(ERROR) << "Symbol name \"" << name << "\" conflicts with the existing " - "symbol \"" << iter->first << "\"."; + GOOGLE_LOG(ERROR) << "Symbol name \"" << name + << "\" conflicts with the existing " + "symbol \"" + << iter->first << "\"."; return false; } @@ -130,16 +195,15 @@ bool SimpleDescriptorDatabase::DescriptorIndex::AddSymbol( // Insert the new symbol using the iterator as a hint, the new entry will // appear immediately before the one the iterator is pointing at. - by_symbol_.insert(iter, - typename std::map::value_type(name, value)); + by_symbol_.insert( + iter, typename std::map::value_type(name, value)); return true; } template bool SimpleDescriptorDatabase::DescriptorIndex::AddNestedExtensions( - const DescriptorProto& message_type, - Value value) { + const DescriptorProto& message_type, Value value) { for (int i = 0; i < message_type.nested_type_size(); i++) { if (!AddNestedExtensions(message_type.nested_type(i), value)) return false; } @@ -151,8 +215,7 @@ bool SimpleDescriptorDatabase::DescriptorIndex::AddNestedExtensions( template bool SimpleDescriptorDatabase::DescriptorIndex::AddExtension( - const FieldDescriptorProto& field, - Value value) { + const FieldDescriptorProto& field, Value value) { if (!field.extendee().empty() && field.extendee()[0] == '.') { // The extension is fully-qualified. We can use it as a lookup key in // the by_symbol_ table. @@ -161,8 +224,9 @@ bool SimpleDescriptorDatabase::DescriptorIndex::AddExtension( std::make_pair(field.extendee().substr(1), field.number()), value)) { GOOGLE_LOG(ERROR) << "Extension conflicts with extension already in database: " - "extend " << field.extendee() << " { " - << field.name() << " = " << field.number() << " }"; + "extend " + << field.extendee() << " { " << field.name() << " = " + << field.number() << " }"; return false; } } else { @@ -175,32 +239,32 @@ bool SimpleDescriptorDatabase::DescriptorIndex::AddExtension( template Value SimpleDescriptorDatabase::DescriptorIndex::FindFile( - const string& filename) { + const std::string& filename) { return FindWithDefault(by_name_, filename, Value()); } template Value SimpleDescriptorDatabase::DescriptorIndex::FindSymbol( - const string& name) { - typename std::map::iterator iter = FindLastLessOrEqual(name); + const std::string& name) { + typename std::map::iterator iter = + FindLastLessOrEqual(name); - return (iter != by_symbol_.end() && IsSubSymbol(iter->first, name)) ? - iter->second : Value(); + return (iter != by_symbol_.end() && IsSubSymbol(iter->first, name)) + ? iter->second + : Value(); } template Value SimpleDescriptorDatabase::DescriptorIndex::FindExtension( - const string& containing_type, - int field_number) { + const std::string& containing_type, int field_number) { return FindWithDefault( by_extension_, std::make_pair(containing_type, field_number), Value()); } template bool SimpleDescriptorDatabase::DescriptorIndex::FindAllExtensionNumbers( - const string& containing_type, - std::vector* output) { - typename std::map, Value>::const_iterator it = + const std::string& containing_type, std::vector* output) { + typename std::map, Value>::const_iterator it = by_extension_.lower_bound(std::make_pair(containing_type, 0)); bool success = false; @@ -214,13 +278,24 @@ bool SimpleDescriptorDatabase::DescriptorIndex::FindAllExtensionNumbers( } template -typename std::map::iterator +void SimpleDescriptorDatabase::DescriptorIndex::FindAllFileNames( + std::vector* output) { + output->resize(by_name_.size()); + int i = 0; + for (const auto& kv : by_name_) { + (*output)[i] = kv.first; + i++; + } +} + +template +typename std::map::iterator SimpleDescriptorDatabase::DescriptorIndex::FindLastLessOrEqual( - const string& name) { + const std::string& name) { // Find the last key in the map which sorts less than or equal to the // symbol name. Since upper_bound() returns the *first* key that sorts // *greater* than the input, we want the element immediately before that. - typename std::map::iterator iter = + typename std::map::iterator iter = by_symbol_.upper_bound(name); if (iter != by_symbol_.begin()) --iter; return iter; @@ -228,7 +303,7 @@ SimpleDescriptorDatabase::DescriptorIndex::FindLastLessOrEqual( template bool SimpleDescriptorDatabase::DescriptorIndex::IsSubSymbol( - const string& sub_symbol, const string& super_symbol) { + const std::string& sub_symbol, const std::string& super_symbol) { return sub_symbol == super_symbol || (HasPrefixString(super_symbol, sub_symbol) && super_symbol[sub_symbol.size()] == '.'); @@ -236,13 +311,11 @@ bool SimpleDescriptorDatabase::DescriptorIndex::IsSubSymbol( template bool SimpleDescriptorDatabase::DescriptorIndex::ValidateSymbolName( - const string& name) { + const std::string& name) { for (int i = 0; i < name.size(); i++) { // I don't trust ctype.h due to locales. :( - if (name[i] != '.' && name[i] != '_' && - (name[i] < '0' || name[i] > '9') && - (name[i] < 'A' || name[i] > 'Z') && - (name[i] < 'a' || name[i] > 'z')) { + if (name[i] != '.' && name[i] != '_' && (name[i] < '0' || name[i] > '9') && + (name[i] < 'A' || name[i] > 'Z') && (name[i] < 'a' || name[i] > 'z')) { return false; } } @@ -267,32 +340,34 @@ bool SimpleDescriptorDatabase::AddAndOwn(const FileDescriptorProto* file) { return index_.AddFile(*file, file); } -bool SimpleDescriptorDatabase::FindFileByName( - const string& filename, - FileDescriptorProto* output) { +bool SimpleDescriptorDatabase::FindFileByName(const std::string& filename, + FileDescriptorProto* output) { return MaybeCopy(index_.FindFile(filename), output); } bool SimpleDescriptorDatabase::FindFileContainingSymbol( - const string& symbol_name, - FileDescriptorProto* output) { + const std::string& symbol_name, FileDescriptorProto* output) { return MaybeCopy(index_.FindSymbol(symbol_name), output); } bool SimpleDescriptorDatabase::FindFileContainingExtension( - const string& containing_type, - int field_number, + const std::string& containing_type, int field_number, FileDescriptorProto* output) { return MaybeCopy(index_.FindExtension(containing_type, field_number), output); } bool SimpleDescriptorDatabase::FindAllExtensionNumbers( - const string& extendee_type, - std::vector* output) { + const std::string& extendee_type, std::vector* output) { return index_.FindAllExtensionNumbers(extendee_type, output); } +bool SimpleDescriptorDatabase::FindAllFileNames( + std::vector* output) { + index_.FindAllFileNames(output); + return true; +} + bool SimpleDescriptorDatabase::MaybeCopy(const FileDescriptorProto* file, FileDescriptorProto* output) { if (file == NULL) return false; @@ -309,8 +384,8 @@ EncodedDescriptorDatabase::~EncodedDescriptorDatabase() { } } -bool EncodedDescriptorDatabase::Add( - const void* encoded_file_descriptor, int size) { +bool EncodedDescriptorDatabase::Add(const void* encoded_file_descriptor, + int size) { FileDescriptorProto file; if (file.ParseFromArray(encoded_file_descriptor, size)) { return index_.AddFile(file, std::make_pair(encoded_file_descriptor, size)); @@ -321,29 +396,26 @@ bool EncodedDescriptorDatabase::Add( } } -bool EncodedDescriptorDatabase::AddCopy( - const void* encoded_file_descriptor, int size) { +bool EncodedDescriptorDatabase::AddCopy(const void* encoded_file_descriptor, + int size) { void* copy = operator new(size); memcpy(copy, encoded_file_descriptor, size); files_to_delete_.push_back(copy); return Add(copy, size); } -bool EncodedDescriptorDatabase::FindFileByName( - const string& filename, - FileDescriptorProto* output) { +bool EncodedDescriptorDatabase::FindFileByName(const std::string& filename, + FileDescriptorProto* output) { return MaybeParse(index_.FindFile(filename), output); } bool EncodedDescriptorDatabase::FindFileContainingSymbol( - const string& symbol_name, - FileDescriptorProto* output) { + const std::string& symbol_name, FileDescriptorProto* output) { return MaybeParse(index_.FindSymbol(symbol_name), output); } bool EncodedDescriptorDatabase::FindNameOfFileContainingSymbol( - const string& symbol_name, - string* output) { + const std::string& symbol_name, std::string* output) { std::pair encoded_file = index_.FindSymbol(symbol_name); if (encoded_file.first == NULL) return false; @@ -371,22 +443,19 @@ bool EncodedDescriptorDatabase::FindNameOfFileContainingSymbol( } bool EncodedDescriptorDatabase::FindFileContainingExtension( - const string& containing_type, - int field_number, + const std::string& containing_type, int field_number, FileDescriptorProto* output) { return MaybeParse(index_.FindExtension(containing_type, field_number), output); } bool EncodedDescriptorDatabase::FindAllExtensionNumbers( - const string& extendee_type, - std::vector* output) { + const std::string& extendee_type, std::vector* output) { return index_.FindAllExtensionNumbers(extendee_type, output); } bool EncodedDescriptorDatabase::MaybeParse( - std::pair encoded_file, - FileDescriptorProto* output) { + std::pair encoded_file, FileDescriptorProto* output) { if (encoded_file.first == NULL) return false; return output->ParseFromArray(encoded_file.first, encoded_file.second); } @@ -394,12 +463,11 @@ bool EncodedDescriptorDatabase::MaybeParse( // =================================================================== DescriptorPoolDatabase::DescriptorPoolDatabase(const DescriptorPool& pool) - : pool_(pool) {} + : pool_(pool) {} DescriptorPoolDatabase::~DescriptorPoolDatabase() {} -bool DescriptorPoolDatabase::FindFileByName( - const string& filename, - FileDescriptorProto* output) { +bool DescriptorPoolDatabase::FindFileByName(const std::string& filename, + FileDescriptorProto* output) { const FileDescriptor* file = pool_.FindFileByName(filename); if (file == NULL) return false; output->Clear(); @@ -408,8 +476,7 @@ bool DescriptorPoolDatabase::FindFileByName( } bool DescriptorPoolDatabase::FindFileContainingSymbol( - const string& symbol_name, - FileDescriptorProto* output) { + const std::string& symbol_name, FileDescriptorProto* output) { const FileDescriptor* file = pool_.FindFileContainingSymbol(symbol_name); if (file == NULL) return false; output->Clear(); @@ -418,14 +485,13 @@ bool DescriptorPoolDatabase::FindFileContainingSymbol( } bool DescriptorPoolDatabase::FindFileContainingExtension( - const string& containing_type, - int field_number, + const std::string& containing_type, int field_number, FileDescriptorProto* output) { const Descriptor* extendee = pool_.FindMessageTypeByName(containing_type); if (extendee == NULL) return false; const FieldDescriptor* extension = - pool_.FindExtensionByNumber(extendee, field_number); + pool_.FindExtensionByNumber(extendee, field_number); if (extension == NULL) return false; output->Clear(); @@ -434,8 +500,7 @@ bool DescriptorPoolDatabase::FindFileContainingExtension( } bool DescriptorPoolDatabase::FindAllExtensionNumbers( - const string& extendee_type, - std::vector* output) { + const std::string& extendee_type, std::vector* output) { const Descriptor* extendee = pool_.FindMessageTypeByName(extendee_type); if (extendee == NULL) return false; @@ -452,19 +517,17 @@ bool DescriptorPoolDatabase::FindAllExtensionNumbers( // =================================================================== MergedDescriptorDatabase::MergedDescriptorDatabase( - DescriptorDatabase* source1, - DescriptorDatabase* source2) { + DescriptorDatabase* source1, DescriptorDatabase* source2) { sources_.push_back(source1); sources_.push_back(source2); } MergedDescriptorDatabase::MergedDescriptorDatabase( const std::vector& sources) - : sources_(sources) {} + : sources_(sources) {} MergedDescriptorDatabase::~MergedDescriptorDatabase() {} -bool MergedDescriptorDatabase::FindFileByName( - const string& filename, - FileDescriptorProto* output) { +bool MergedDescriptorDatabase::FindFileByName(const std::string& filename, + FileDescriptorProto* output) { for (int i = 0; i < sources_.size(); i++) { if (sources_[i]->FindFileByName(filename, output)) { return true; @@ -474,8 +537,7 @@ bool MergedDescriptorDatabase::FindFileByName( } bool MergedDescriptorDatabase::FindFileContainingSymbol( - const string& symbol_name, - FileDescriptorProto* output) { + const std::string& symbol_name, FileDescriptorProto* output) { for (int i = 0; i < sources_.size(); i++) { if (sources_[i]->FindFileContainingSymbol(symbol_name, output)) { // The symbol was found in source i. However, if one of the previous @@ -496,12 +558,11 @@ bool MergedDescriptorDatabase::FindFileContainingSymbol( } bool MergedDescriptorDatabase::FindFileContainingExtension( - const string& containing_type, - int field_number, + const std::string& containing_type, int field_number, FileDescriptorProto* output) { for (int i = 0; i < sources_.size(); i++) { - if (sources_[i]->FindFileContainingExtension( - containing_type, field_number, output)) { + if (sources_[i]->FindFileContainingExtension(containing_type, field_number, + output)) { // The symbol was found in source i. However, if one of the previous // sources defines a file with the same name (which presumably doesn't // contain the symbol, since it wasn't found in that source), then we @@ -520,8 +581,7 @@ bool MergedDescriptorDatabase::FindFileContainingExtension( } bool MergedDescriptorDatabase::FindAllExtensionNumbers( - const string& extendee_type, - std::vector* output) { + const std::string& extendee_type, std::vector* output) { std::set merged_results; std::vector results; bool success = false; diff --git a/third_party/protobuf/src/google/protobuf/descriptor_database.h b/third_party/protobuf/src/google/protobuf/descriptor_database.h index d61f2a6a..b79cfadd 100644 --- a/third_party/protobuf/src/google/protobuf/descriptor_database.h +++ b/third_party/protobuf/src/google/protobuf/descriptor_database.h @@ -44,6 +44,12 @@ #include #include +#include + +#ifdef SWIG +#define PROTOBUF_EXPORT +#endif + namespace google { namespace protobuf { @@ -62,27 +68,27 @@ class MergedDescriptorDatabase; // calling DescriptorPool::BuildFile() for each one. Instead, a DescriptorPool // can be created which wraps a DescriptorDatabase and only builds particular // descriptors when they are needed. -class LIBPROTOBUF_EXPORT DescriptorDatabase { +class PROTOBUF_EXPORT DescriptorDatabase { public: inline DescriptorDatabase() {} virtual ~DescriptorDatabase(); // Find a file by file name. Fills in in *output and returns true if found. // Otherwise, returns false, leaving the contents of *output undefined. - virtual bool FindFileByName(const string& filename, + virtual bool FindFileByName(const std::string& filename, FileDescriptorProto* output) = 0; // Find the file that declares the given fully-qualified symbol name. // If found, fills in *output and returns true, otherwise returns false // and leaves *output undefined. - virtual bool FindFileContainingSymbol(const string& symbol_name, + virtual bool FindFileContainingSymbol(const std::string& symbol_name, FileDescriptorProto* output) = 0; // Find the file which defines an extension extending the given message type // with the given field number. If found, fills in *output and returns true, // otherwise returns false and leaves *output undefined. containing_type // must be a fully-qualified type name. - virtual bool FindFileContainingExtension(const string& containing_type, + virtual bool FindFileContainingExtension(const std::string& containing_type, int field_number, FileDescriptorProto* output) = 0; @@ -96,7 +102,7 @@ class LIBPROTOBUF_EXPORT DescriptorDatabase { // // This method has a default implementation that always returns // false. - virtual bool FindAllExtensionNumbers(const string& /* extendee_type */, + virtual bool FindAllExtensionNumbers(const std::string& /* extendee_type */, std::vector* /* output */) { return false; } @@ -110,10 +116,24 @@ class LIBPROTOBUF_EXPORT DescriptorDatabase { // // This method has a default implementation that always returns // false. - virtual bool FindAllFileNames(std::vector* output) { + virtual bool FindAllFileNames(std::vector* output) { return false; } + // Finds the package names and appends them to the output in an + // undefined order. This method is best-effort: it's not guaranteed that the + // database will find all packages. Returns true if the database supports + // searching all package names, otherwise returns false and leaves output + // unchanged. + bool FindAllPackageNames(std::vector* output); + + // Finds the message names and appends them to the output in an + // undefined order. This method is best-effort: it's not guaranteed that the + // database will find all messages. Returns true if the database supports + // searching all message names, otherwise returns false and leaves output + // unchanged. + bool FindAllMessageNames(std::vector* output); + private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DescriptorDatabase); }; @@ -139,10 +159,10 @@ class LIBPROTOBUF_EXPORT DescriptorDatabase { // FileDescriptor::CopyTo()) will always use fully-qualified names for all // types. You only need to worry if you are constructing FileDescriptorProtos // yourself, or are calling compiler::Parser directly. -class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase { +class PROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase { public: SimpleDescriptorDatabase(); - ~SimpleDescriptorDatabase(); + ~SimpleDescriptorDatabase() override; // Adds the FileDescriptorProto to the database, making a copy. The object // can be deleted after Add() returns. Returns false if the file conflicted @@ -154,15 +174,17 @@ class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase { bool AddAndOwn(const FileDescriptorProto* file); // implements DescriptorDatabase ----------------------------------- - bool FindFileByName(const string& filename, - FileDescriptorProto* output); - bool FindFileContainingSymbol(const string& symbol_name, - FileDescriptorProto* output); - bool FindFileContainingExtension(const string& containing_type, + bool FindFileByName(const std::string& filename, + FileDescriptorProto* output) override; + bool FindFileContainingSymbol(const std::string& symbol_name, + FileDescriptorProto* output) override; + bool FindFileContainingExtension(const std::string& containing_type, int field_number, - FileDescriptorProto* output); - bool FindAllExtensionNumbers(const string& extendee_type, - std::vector* output); + FileDescriptorProto* output) override; + bool FindAllExtensionNumbers(const std::string& extendee_type, + std::vector* output) override; + + bool FindAllFileNames(std::vector* output) override; private: // So that it can use DescriptorIndex. @@ -175,24 +197,22 @@ class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase { public: // Helpers to recursively add particular descriptors and all their contents // to the index. - bool AddFile(const FileDescriptorProto& file, - Value value); - bool AddSymbol(const string& name, Value value); - bool AddNestedExtensions(const DescriptorProto& message_type, - Value value); - bool AddExtension(const FieldDescriptorProto& field, - Value value); + bool AddFile(const FileDescriptorProto& file, Value value); + bool AddSymbol(const std::string& name, Value value); + bool AddNestedExtensions(const DescriptorProto& message_type, Value value); + bool AddExtension(const FieldDescriptorProto& field, Value value); - Value FindFile(const string& filename); - Value FindSymbol(const string& name); - Value FindExtension(const string& containing_type, int field_number); - bool FindAllExtensionNumbers(const string& containing_type, + Value FindFile(const std::string& filename); + Value FindSymbol(const std::string& name); + Value FindExtension(const std::string& containing_type, int field_number); + bool FindAllExtensionNumbers(const std::string& containing_type, std::vector* output); + void FindAllFileNames(std::vector* output); private: - std::map by_name_; - std::map by_symbol_; - std::map, Value> by_extension_; + std::map by_name_; + std::map by_symbol_; + std::map, Value> by_extension_; // Invariant: The by_symbol_ map does not contain any symbols which are // prefixes of other symbols in the map. For example, "foo.bar" is a @@ -247,27 +267,26 @@ class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase { // Find the last entry in the by_symbol_ map whose key is less than or // equal to the given name. - typename std::map::iterator FindLastLessOrEqual( - const string& name); + typename std::map::iterator FindLastLessOrEqual( + const std::string& name); // True if either the arguments are equal or super_symbol identifies a // parent symbol of sub_symbol (e.g. "foo.bar" is a parent of // "foo.bar.baz", but not a parent of "foo.barbaz"). - bool IsSubSymbol(const string& sub_symbol, const string& super_symbol); + bool IsSubSymbol(const std::string& sub_symbol, + const std::string& super_symbol); // Returns true if and only if all characters in the name are alphanumerics, // underscores, or periods. - bool ValidateSymbolName(const string& name); + bool ValidateSymbolName(const std::string& name); }; - DescriptorIndex index_; std::vector files_to_delete_; // If file is non-NULL, copy it into *output and return true, otherwise // return false. - bool MaybeCopy(const FileDescriptorProto* file, - FileDescriptorProto* output); + bool MaybeCopy(const FileDescriptorProto* file, FileDescriptorProto* output); GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SimpleDescriptorDatabase); }; @@ -277,10 +296,10 @@ class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase { // // The same caveats regarding FindFileContainingExtension() apply as with // SimpleDescriptorDatabase. -class LIBPROTOBUF_EXPORT EncodedDescriptorDatabase : public DescriptorDatabase { +class PROTOBUF_EXPORT EncodedDescriptorDatabase : public DescriptorDatabase { public: EncodedDescriptorDatabase(); - ~EncodedDescriptorDatabase(); + ~EncodedDescriptorDatabase() override; // Adds the FileDescriptorProto to the database. The descriptor is provided // in encoded form. The database does not make a copy of the bytes, nor @@ -295,19 +314,19 @@ class LIBPROTOBUF_EXPORT EncodedDescriptorDatabase : public DescriptorDatabase { bool AddCopy(const void* encoded_file_descriptor, int size); // Like FindFileContainingSymbol but returns only the name of the file. - bool FindNameOfFileContainingSymbol(const string& symbol_name, - string* output); + bool FindNameOfFileContainingSymbol(const std::string& symbol_name, + std::string* output); // implements DescriptorDatabase ----------------------------------- - bool FindFileByName(const string& filename, - FileDescriptorProto* output); - bool FindFileContainingSymbol(const string& symbol_name, - FileDescriptorProto* output); - bool FindFileContainingExtension(const string& containing_type, + bool FindFileByName(const std::string& filename, + FileDescriptorProto* output) override; + bool FindFileContainingSymbol(const std::string& symbol_name, + FileDescriptorProto* output) override; + bool FindFileContainingExtension(const std::string& containing_type, int field_number, - FileDescriptorProto* output); - bool FindAllExtensionNumbers(const string& extendee_type, - std::vector* output); + FileDescriptorProto* output) override; + bool FindAllExtensionNumbers(const std::string& extendee_type, + std::vector* output) override; private: SimpleDescriptorDatabase::DescriptorIndex > @@ -323,21 +342,21 @@ class LIBPROTOBUF_EXPORT EncodedDescriptorDatabase : public DescriptorDatabase { }; // A DescriptorDatabase that fetches files from a given pool. -class LIBPROTOBUF_EXPORT DescriptorPoolDatabase : public DescriptorDatabase { +class PROTOBUF_EXPORT DescriptorPoolDatabase : public DescriptorDatabase { public: explicit DescriptorPoolDatabase(const DescriptorPool& pool); - ~DescriptorPoolDatabase(); + ~DescriptorPoolDatabase() override; // implements DescriptorDatabase ----------------------------------- - bool FindFileByName(const string& filename, - FileDescriptorProto* output); - bool FindFileContainingSymbol(const string& symbol_name, - FileDescriptorProto* output); - bool FindFileContainingExtension(const string& containing_type, + bool FindFileByName(const std::string& filename, + FileDescriptorProto* output) override; + bool FindFileContainingSymbol(const std::string& symbol_name, + FileDescriptorProto* output) override; + bool FindFileContainingExtension(const std::string& containing_type, int field_number, - FileDescriptorProto* output); - bool FindAllExtensionNumbers(const string& extendee_type, - std::vector* output); + FileDescriptorProto* output) override; + bool FindAllExtensionNumbers(const std::string& extendee_type, + std::vector* output) override; private: const DescriptorPool& pool_; @@ -346,7 +365,7 @@ class LIBPROTOBUF_EXPORT DescriptorPoolDatabase : public DescriptorDatabase { // A DescriptorDatabase that wraps two or more others. It first searches the // first database and, if that fails, tries the second, and so on. -class LIBPROTOBUF_EXPORT MergedDescriptorDatabase : public DescriptorDatabase { +class PROTOBUF_EXPORT MergedDescriptorDatabase : public DescriptorDatabase { public: // Merge just two databases. The sources remain property of the caller. MergedDescriptorDatabase(DescriptorDatabase* source1, @@ -356,20 +375,20 @@ class LIBPROTOBUF_EXPORT MergedDescriptorDatabase : public DescriptorDatabase { // DescriptorDatabases need to stick around. explicit MergedDescriptorDatabase( const std::vector& sources); - ~MergedDescriptorDatabase(); + ~MergedDescriptorDatabase() override; // implements DescriptorDatabase ----------------------------------- - bool FindFileByName(const string& filename, - FileDescriptorProto* output); - bool FindFileContainingSymbol(const string& symbol_name, - FileDescriptorProto* output); - bool FindFileContainingExtension(const string& containing_type, + bool FindFileByName(const std::string& filename, + FileDescriptorProto* output) override; + bool FindFileContainingSymbol(const std::string& symbol_name, + FileDescriptorProto* output) override; + bool FindFileContainingExtension(const std::string& containing_type, int field_number, - FileDescriptorProto* output); + FileDescriptorProto* output) override; // Merges the results of calling all databases. Returns true iff any // of the databases returned true. - bool FindAllExtensionNumbers(const string& extendee_type, - std::vector* output); + bool FindAllExtensionNumbers(const std::string& extendee_type, + std::vector* output) override; private: @@ -378,6 +397,8 @@ class LIBPROTOBUF_EXPORT MergedDescriptorDatabase : public DescriptorDatabase { }; } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_DESCRIPTOR_DATABASE_H__ diff --git a/third_party/protobuf/src/google/protobuf/descriptor_database_unittest.cc b/third_party/protobuf/src/google/protobuf/descriptor_database_unittest.cc index 083ef8f2..8653193a 100644 --- a/third_party/protobuf/src/google/protobuf/descriptor_database_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/descriptor_database_unittest.cc @@ -44,6 +44,7 @@ #include #include +#include #include #include @@ -59,12 +60,11 @@ static void AddToDatabase(SimpleDescriptorDatabase* database, } static void ExpectContainsType(const FileDescriptorProto& proto, - const string& type_name) { + const std::string& type_name) { for (int i = 0; i < proto.message_type_size(); i++) { if (proto.message_type(i).name() == type_name) return; } - ADD_FAILURE() << "\"" << proto.name() - << "\" did not contain expected type \"" + ADD_FAILURE() << "\"" << proto.name() << "\" did not contain expected type \"" << type_name << "\"."; } @@ -77,7 +77,7 @@ static void ExpectContainsType(const FileDescriptorProto& proto, // three nearly-identical sets of tests, we use parameterized tests to apply // the same code to all three. -// The parameterized test runs against a DescriptarDatabaseTestCase. We have +// The parameterized test runs against a DescriptorDatabaseTestCase. We have // implementations for each of the three classes we want to test. class DescriptorDatabaseTestCase { public: @@ -99,9 +99,7 @@ class SimpleDescriptorDatabaseTestCase : public DescriptorDatabaseTestCase { virtual ~SimpleDescriptorDatabaseTestCase() {} - virtual DescriptorDatabase* GetDatabase() { - return &database_; - } + virtual DescriptorDatabase* GetDatabase() { return &database_; } virtual bool AddToDatabase(const FileDescriptorProto& file) { return database_.Add(file); } @@ -119,11 +117,9 @@ class EncodedDescriptorDatabaseTestCase : public DescriptorDatabaseTestCase { virtual ~EncodedDescriptorDatabaseTestCase() {} - virtual DescriptorDatabase* GetDatabase() { - return &database_; - } + virtual DescriptorDatabase* GetDatabase() { return &database_; } virtual bool AddToDatabase(const FileDescriptorProto& file) { - string data; + std::string data; file.SerializeToString(&data); return database_.AddCopy(data.data(), data.size()); } @@ -142,9 +138,7 @@ class DescriptorPoolDatabaseTestCase : public DescriptorDatabaseTestCase { DescriptorPoolDatabaseTestCase() : database_(pool_) {} virtual ~DescriptorPoolDatabaseTestCase() {} - virtual DescriptorDatabase* GetDatabase() { - return &database_; - } + virtual DescriptorDatabase* GetDatabase() { return &database_; } virtual bool AddToDatabase(const FileDescriptorProto& file) { return pool_.BuildFile(file); } @@ -182,11 +176,11 @@ class DescriptorDatabaseTest TEST_P(DescriptorDatabaseTest, FindFileByName) { AddToDatabase( - "name: \"foo.proto\" " - "message_type { name:\"Foo\" }"); + "name: \"foo.proto\" " + "message_type { name:\"Foo\" }"); AddToDatabase( - "name: \"bar.proto\" " - "message_type { name:\"Bar\" }"); + "name: \"bar.proto\" " + "message_type { name:\"Bar\" }"); { FileDescriptorProto file; @@ -211,27 +205,26 @@ TEST_P(DescriptorDatabaseTest, FindFileByName) { TEST_P(DescriptorDatabaseTest, FindFileContainingSymbol) { AddToDatabase( - "name: \"foo.proto\" " - "message_type { " - " name: \"Foo\" " - " field { name:\"qux\" }" - " nested_type { name: \"Grault\" } " - " enum_type { name: \"Garply\" } " - "} " - "enum_type { " - " name: \"Waldo\" " - " value { name:\"FRED\" } " - "} " - "extension { name: \"plugh\" } " - "service { " - " name: \"Xyzzy\" " - " method { name: \"Thud\" } " - "}" - ); + "name: \"foo.proto\" " + "message_type { " + " name: \"Foo\" " + " field { name:\"qux\" }" + " nested_type { name: \"Grault\" } " + " enum_type { name: \"Garply\" } " + "} " + "enum_type { " + " name: \"Waldo\" " + " value { name:\"FRED\" } " + "} " + "extension { name: \"plugh\" } " + "service { " + " name: \"Xyzzy\" " + " method { name: \"Thud\" } " + "}"); AddToDatabase( - "name: \"bar.proto\" " - "package: \"corge\" " - "message_type { name: \"Bar\" }"); + "name: \"bar.proto\" " + "package: \"corge\" " + "message_type { name: \"Bar\" }"); { FileDescriptorProto file; @@ -246,8 +239,8 @@ TEST_P(DescriptorDatabaseTest, FindFileContainingSymbol) { EXPECT_EQ("foo.proto", file.name()); // Non-existent field under a valid top level symbol can also be // found. - EXPECT_TRUE(database_->FindFileContainingSymbol("Foo.none_field.none", - &file)); + EXPECT_TRUE( + database_->FindFileContainingSymbol("Foo.none_field.none", &file)); } { @@ -321,24 +314,25 @@ TEST_P(DescriptorDatabaseTest, FindFileContainingSymbol) { TEST_P(DescriptorDatabaseTest, FindFileContainingExtension) { AddToDatabase( - "name: \"foo.proto\" " - "message_type { " - " name: \"Foo\" " - " extension_range { start: 1 end: 1000 } " - " extension { name:\"qux\" label:LABEL_OPTIONAL type:TYPE_INT32 number:5 " - " extendee: \".Foo\" }" - "}"); + "name: \"foo.proto\" " + "message_type { " + " name: \"Foo\" " + " extension_range { start: 1 end: 1000 } " + " extension { name:\"qux\" label:LABEL_OPTIONAL type:TYPE_INT32 " + "number:5 " + " extendee: \".Foo\" }" + "}"); AddToDatabase( - "name: \"bar.proto\" " - "package: \"corge\" " - "dependency: \"foo.proto\" " - "message_type { " - " name: \"Bar\" " - " extension_range { start: 1 end: 1000 } " - "} " - "extension { name:\"grault\" extendee: \".Foo\" number:32 } " - "extension { name:\"garply\" extendee: \".corge.Bar\" number:70 } " - "extension { name:\"waldo\" extendee: \"Bar\" number:56 } "); + "name: \"bar.proto\" " + "package: \"corge\" " + "dependency: \"foo.proto\" " + "message_type { " + " name: \"Bar\" " + " extension_range { start: 1 end: 1000 } " + "} " + "extension { name:\"grault\" extendee: \".Foo\" number:32 } " + "extension { name:\"garply\" extendee: \".corge.Bar\" number:70 } " + "extension { name:\"waldo\" extendee: \"Bar\" number:56 } "); { FileDescriptorProto file; @@ -390,24 +384,25 @@ TEST_P(DescriptorDatabaseTest, FindFileContainingExtension) { TEST_P(DescriptorDatabaseTest, FindAllExtensionNumbers) { AddToDatabase( - "name: \"foo.proto\" " - "message_type { " - " name: \"Foo\" " - " extension_range { start: 1 end: 1000 } " - " extension { name:\"qux\" label:LABEL_OPTIONAL type:TYPE_INT32 number:5 " - " extendee: \".Foo\" }" - "}"); + "name: \"foo.proto\" " + "message_type { " + " name: \"Foo\" " + " extension_range { start: 1 end: 1000 } " + " extension { name:\"qux\" label:LABEL_OPTIONAL type:TYPE_INT32 " + "number:5 " + " extendee: \".Foo\" }" + "}"); AddToDatabase( - "name: \"bar.proto\" " - "package: \"corge\" " - "dependency: \"foo.proto\" " - "message_type { " - " name: \"Bar\" " - " extension_range { start: 1 end: 1000 } " - "} " - "extension { name:\"grault\" extendee: \".Foo\" number:32 } " - "extension { name:\"garply\" extendee: \".corge.Bar\" number:70 } " - "extension { name:\"waldo\" extendee: \"Bar\" number:56 } "); + "name: \"bar.proto\" " + "package: \"corge\" " + "dependency: \"foo.proto\" " + "message_type { " + " name: \"Bar\" " + " extension_range { start: 1 end: 1000 } " + "} " + "extension { name:\"grault\" extendee: \".Foo\" number:32 } " + "extension { name:\"garply\" extendee: \".corge.Bar\" number:70 } " + "extension { name:\"waldo\" extendee: \"Bar\" number:56 } "); { std::vector numbers; @@ -441,47 +436,49 @@ TEST_P(DescriptorDatabaseTest, FindAllExtensionNumbers) { TEST_P(DescriptorDatabaseTest, ConflictingFileError) { AddToDatabase( - "name: \"foo.proto\" " - "message_type { " - " name: \"Foo\" " - "}"); + "name: \"foo.proto\" " + "message_type { " + " name: \"Foo\" " + "}"); AddToDatabaseWithError( - "name: \"foo.proto\" " - "message_type { " - " name: \"Bar\" " - "}"); + "name: \"foo.proto\" " + "message_type { " + " name: \"Bar\" " + "}"); } TEST_P(DescriptorDatabaseTest, ConflictingTypeError) { AddToDatabase( - "name: \"foo.proto\" " - "message_type { " - " name: \"Foo\" " - "}"); + "name: \"foo.proto\" " + "message_type { " + " name: \"Foo\" " + "}"); AddToDatabaseWithError( - "name: \"bar.proto\" " - "message_type { " - " name: \"Foo\" " - "}"); + "name: \"bar.proto\" " + "message_type { " + " name: \"Foo\" " + "}"); } TEST_P(DescriptorDatabaseTest, ConflictingExtensionError) { AddToDatabase( - "name: \"foo.proto\" " - "extension { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:5 " - " extendee: \".Foo\" }"); + "name: \"foo.proto\" " + "extension { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:5 " + " extendee: \".Foo\" }"); AddToDatabaseWithError( - "name: \"bar.proto\" " - "extension { name:\"bar\" label:LABEL_OPTIONAL type:TYPE_INT32 number:5 " - " extendee: \".Foo\" }"); + "name: \"bar.proto\" " + "extension { name:\"bar\" label:LABEL_OPTIONAL type:TYPE_INT32 number:5 " + " extendee: \".Foo\" }"); } -INSTANTIATE_TEST_CASE_P(Simple, DescriptorDatabaseTest, +INSTANTIATE_TEST_CASE_P( + Simple, DescriptorDatabaseTest, testing::Values(&SimpleDescriptorDatabaseTestCase::New)); -INSTANTIATE_TEST_CASE_P(MemoryConserving, DescriptorDatabaseTest, +INSTANTIATE_TEST_CASE_P( + MemoryConserving, DescriptorDatabaseTest, testing::Values(&EncodedDescriptorDatabaseTestCase::New)); INSTANTIATE_TEST_CASE_P(Pool, DescriptorDatabaseTest, - testing::Values(&DescriptorPoolDatabaseTestCase::New)); + testing::Values(&DescriptorPoolDatabaseTestCase::New)); #endif // GTEST_HAS_PARAM_TEST @@ -496,10 +493,10 @@ TEST(EncodedDescriptorDatabaseExtraTest, FindNameOfFileContainingSymbol) { file2b.add_message_type()->set_name("Bar"); // Normal serialization allows our optimization to kick in. - string data1 = file1.SerializeAsString(); + std::string data1 = file1.SerializeAsString(); // Force out-of-order serialization to test slow path. - string data2 = file2b.SerializeAsString() + file2a.SerializeAsString(); + std::string data2 = file2b.SerializeAsString() + file2a.SerializeAsString(); // Create EncodedDescriptorDatabase containing both files. EncodedDescriptorDatabase db; @@ -507,7 +504,7 @@ TEST(EncodedDescriptorDatabaseExtraTest, FindNameOfFileContainingSymbol) { db.Add(data2.data(), data2.size()); // Test! - string filename; + std::string filename; EXPECT_TRUE(db.FindNameOfFileContainingSymbol("foo.Foo", &filename)); EXPECT_EQ("foo.proto", filename); EXPECT_TRUE(db.FindNameOfFileContainingSymbol("foo.Foo.Blah", &filename)); @@ -519,41 +516,100 @@ TEST(EncodedDescriptorDatabaseExtraTest, FindNameOfFileContainingSymbol) { EXPECT_FALSE(db.FindNameOfFileContainingSymbol("baz.Baz", &filename)); } +TEST(SimpleDescriptorDatabaseExtraTest, FindAllFileNames) { + FileDescriptorProto f; + f.set_name("foo.proto"); + f.set_package("foo"); + f.add_message_type()->set_name("Foo"); + + SimpleDescriptorDatabase db; + db.Add(f); + + // Test! + std::vector all_files; + db.FindAllFileNames(&all_files); + EXPECT_THAT(all_files, testing::ElementsAre("foo.proto")); +} + +TEST(SimpleDescriptorDatabaseExtraTest, FindAllPackageNames) { + FileDescriptorProto f; + f.set_name("foo.proto"); + f.set_package("foo"); + f.add_message_type()->set_name("Foo"); + + FileDescriptorProto b; + b.set_name("bar.proto"); + b.set_package(""); + b.add_message_type()->set_name("Bar"); + + SimpleDescriptorDatabase db; + db.Add(f); + db.Add(b); + + std::vector packages; + EXPECT_TRUE(db.FindAllPackageNames(&packages)); + EXPECT_THAT(packages, ::testing::UnorderedElementsAre("foo", "")); +} + +TEST(SimpleDescriptorDatabaseExtraTest, FindAllMessageNames) { + FileDescriptorProto f; + f.set_name("foo.proto"); + f.set_package("foo"); + f.add_message_type()->set_name("Foo"); + + FileDescriptorProto b; + b.set_name("bar.proto"); + b.set_package(""); + b.add_message_type()->set_name("Bar"); + + SimpleDescriptorDatabase db; + db.Add(f); + db.Add(b); + + std::vector messages; + EXPECT_TRUE(db.FindAllMessageNames(&messages)); + EXPECT_THAT(messages, ::testing::UnorderedElementsAre("foo.Foo", "Bar")); +} + // =================================================================== class MergedDescriptorDatabaseTest : public testing::Test { protected: MergedDescriptorDatabaseTest() - : forward_merged_(&database1_, &database2_), - reverse_merged_(&database2_, &database1_) {} + : forward_merged_(&database1_, &database2_), + reverse_merged_(&database2_, &database1_) {} virtual void SetUp() { - AddToDatabase(&database1_, - "name: \"foo.proto\" " - "message_type { name:\"Foo\" extension_range { start: 1 end: 100 } } " - "extension { name:\"foo_ext\" extendee: \".Foo\" number:3 " - " label:LABEL_OPTIONAL type:TYPE_INT32 } "); - AddToDatabase(&database2_, - "name: \"bar.proto\" " - "message_type { name:\"Bar\" extension_range { start: 1 end: 100 } } " - "extension { name:\"bar_ext\" extendee: \".Bar\" number:5 " - " label:LABEL_OPTIONAL type:TYPE_INT32 } "); + AddToDatabase( + &database1_, + "name: \"foo.proto\" " + "message_type { name:\"Foo\" extension_range { start: 1 end: 100 } } " + "extension { name:\"foo_ext\" extendee: \".Foo\" number:3 " + " label:LABEL_OPTIONAL type:TYPE_INT32 } "); + AddToDatabase( + &database2_, + "name: \"bar.proto\" " + "message_type { name:\"Bar\" extension_range { start: 1 end: 100 } } " + "extension { name:\"bar_ext\" extendee: \".Bar\" number:5 " + " label:LABEL_OPTIONAL type:TYPE_INT32 } "); // baz.proto exists in both pools, with different definitions. - AddToDatabase(&database1_, - "name: \"baz.proto\" " - "message_type { name:\"Baz\" extension_range { start: 1 end: 100 } } " - "message_type { name:\"FromPool1\" } " - "extension { name:\"baz_ext\" extendee: \".Baz\" number:12 " - " label:LABEL_OPTIONAL type:TYPE_INT32 } " - "extension { name:\"database1_only_ext\" extendee: \".Baz\" number:13 " - " label:LABEL_OPTIONAL type:TYPE_INT32 } "); - AddToDatabase(&database2_, - "name: \"baz.proto\" " - "message_type { name:\"Baz\" extension_range { start: 1 end: 100 } } " - "message_type { name:\"FromPool2\" } " - "extension { name:\"baz_ext\" extendee: \".Baz\" number:12 " - " label:LABEL_OPTIONAL type:TYPE_INT32 } "); + AddToDatabase( + &database1_, + "name: \"baz.proto\" " + "message_type { name:\"Baz\" extension_range { start: 1 end: 100 } } " + "message_type { name:\"FromPool1\" } " + "extension { name:\"baz_ext\" extendee: \".Baz\" number:12 " + " label:LABEL_OPTIONAL type:TYPE_INT32 } " + "extension { name:\"database1_only_ext\" extendee: \".Baz\" number:13 " + " label:LABEL_OPTIONAL type:TYPE_INT32 } "); + AddToDatabase( + &database2_, + "name: \"baz.proto\" " + "message_type { name:\"Baz\" extension_range { start: 1 end: 100 } } " + "message_type { name:\"FromPool2\" } " + "extension { name:\"baz_ext\" extendee: \".Baz\" number:12 " + " label:LABEL_OPTIONAL type:TYPE_INT32 } "); } SimpleDescriptorDatabase database1_; @@ -647,8 +703,7 @@ TEST_F(MergedDescriptorDatabaseTest, FindFileContainingSymbol) { { // Can't find non-existent symbol. FileDescriptorProto file; - EXPECT_FALSE( - forward_merged_.FindFileContainingSymbol("NoSuchType", &file)); + EXPECT_FALSE(forward_merged_.FindFileContainingSymbol("NoSuchType", &file)); } } @@ -656,8 +711,7 @@ TEST_F(MergedDescriptorDatabaseTest, FindFileContainingExtension) { { // Can find file that is only in database1_. FileDescriptorProto file; - EXPECT_TRUE( - forward_merged_.FindFileContainingExtension("Foo", 3, &file)); + EXPECT_TRUE(forward_merged_.FindFileContainingExtension("Foo", 3, &file)); EXPECT_EQ("foo.proto", file.name()); ExpectContainsType(file, "Foo"); } @@ -665,8 +719,7 @@ TEST_F(MergedDescriptorDatabaseTest, FindFileContainingExtension) { { // Can find file that is only in database2_. FileDescriptorProto file; - EXPECT_TRUE( - forward_merged_.FindFileContainingExtension("Bar", 5, &file)); + EXPECT_TRUE(forward_merged_.FindFileContainingExtension("Bar", 5, &file)); EXPECT_EQ("bar.proto", file.name()); ExpectContainsType(file, "Bar"); } @@ -674,8 +727,7 @@ TEST_F(MergedDescriptorDatabaseTest, FindFileContainingExtension) { { // In forward_merged_, database1_'s baz.proto takes precedence. FileDescriptorProto file; - EXPECT_TRUE( - forward_merged_.FindFileContainingExtension("Baz", 12, &file)); + EXPECT_TRUE(forward_merged_.FindFileContainingExtension("Baz", 12, &file)); EXPECT_EQ("baz.proto", file.name()); ExpectContainsType(file, "FromPool1"); } @@ -683,8 +735,7 @@ TEST_F(MergedDescriptorDatabaseTest, FindFileContainingExtension) { { // In reverse_merged_, database2_'s baz.proto takes precedence. FileDescriptorProto file; - EXPECT_TRUE( - reverse_merged_.FindFileContainingExtension("Baz", 12, &file)); + EXPECT_TRUE(reverse_merged_.FindFileContainingExtension("Baz", 12, &file)); EXPECT_EQ("baz.proto", file.name()); ExpectContainsType(file, "FromPool2"); } @@ -700,8 +751,7 @@ TEST_F(MergedDescriptorDatabaseTest, FindFileContainingExtension) { { // Can't find non-existent extension. FileDescriptorProto file; - EXPECT_FALSE( - forward_merged_.FindFileContainingExtension("Foo", 6, &file)); + EXPECT_FALSE(forward_merged_.FindFileContainingExtension("Foo", 6, &file)); } } diff --git a/third_party/protobuf/src/google/protobuf/descriptor_unittest.cc b/third_party/protobuf/src/google/protobuf/descriptor_unittest.cc index 54da095a..f87947ff 100644 --- a/third_party/protobuf/src/google/protobuf/descriptor_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/descriptor_unittest.cc @@ -57,10 +57,13 @@ #include #include #include +#include #include #include +#include + namespace google { namespace protobuf { @@ -68,41 +71,43 @@ namespace protobuf { namespace descriptor_unittest { // Some helpers to make assembling descriptors faster. -DescriptorProto* AddMessage(FileDescriptorProto* file, const string& name) { +DescriptorProto* AddMessage(FileDescriptorProto* file, + const std::string& name) { DescriptorProto* result = file->add_message_type(); result->set_name(name); return result; } -DescriptorProto* AddNestedMessage(DescriptorProto* parent, const string& name) { +DescriptorProto* AddNestedMessage(DescriptorProto* parent, + const std::string& name) { DescriptorProto* result = parent->add_nested_type(); result->set_name(name); return result; } -EnumDescriptorProto* AddEnum(FileDescriptorProto* file, const string& name) { +EnumDescriptorProto* AddEnum(FileDescriptorProto* file, + const std::string& name) { EnumDescriptorProto* result = file->add_enum_type(); result->set_name(name); return result; } EnumDescriptorProto* AddNestedEnum(DescriptorProto* parent, - const string& name) { + const std::string& name) { EnumDescriptorProto* result = parent->add_enum_type(); result->set_name(name); return result; } ServiceDescriptorProto* AddService(FileDescriptorProto* file, - const string& name) { + const std::string& name) { ServiceDescriptorProto* result = file->add_service(); result->set_name(name); return result; } -FieldDescriptorProto* AddField(DescriptorProto* parent, - const string& name, int number, - FieldDescriptorProto::Label label, +FieldDescriptorProto* AddField(DescriptorProto* parent, const std::string& name, + int number, FieldDescriptorProto::Label label, FieldDescriptorProto::Type type) { FieldDescriptorProto* result = parent->add_field(); result->set_name(name); @@ -113,8 +118,8 @@ FieldDescriptorProto* AddField(DescriptorProto* parent, } FieldDescriptorProto* AddExtension(FileDescriptorProto* file, - const string& extendee, - const string& name, int number, + const std::string& extendee, + const std::string& name, int number, FieldDescriptorProto::Label label, FieldDescriptorProto::Type type) { FieldDescriptorProto* result = file->add_extension(); @@ -127,8 +132,8 @@ FieldDescriptorProto* AddExtension(FileDescriptorProto* file, } FieldDescriptorProto* AddNestedExtension(DescriptorProto* parent, - const string& extendee, - const string& name, int number, + const std::string& extendee, + const std::string& name, int number, FieldDescriptorProto::Label label, FieldDescriptorProto::Type type) { FieldDescriptorProto* result = parent->add_extension(); @@ -165,7 +170,7 @@ EnumDescriptorProto::EnumReservedRange* AddReservedRange( } EnumValueDescriptorProto* AddEnumValue(EnumDescriptorProto* enum_proto, - const string& name, int number) { + const std::string& name, int number) { EnumValueDescriptorProto* result = enum_proto->add_value(); result->set_name(name); result->set_number(number); @@ -173,9 +178,9 @@ EnumValueDescriptorProto* AddEnumValue(EnumDescriptorProto* enum_proto, } MethodDescriptorProto* AddMethod(ServiceDescriptorProto* service, - const string& name, - const string& input_type, - const string& output_type) { + const std::string& name, + const std::string& input_type, + const std::string& output_type) { MethodDescriptorProto* result = service->add_method(); result->set_name(name); result->set_input_type(input_type); @@ -185,7 +190,7 @@ MethodDescriptorProto* AddMethod(ServiceDescriptorProto* service, // Empty enums technically aren't allowed. We need to insert a dummy value // into them. -void AddEmptyEnum(FileDescriptorProto* file, const string& name) { +void AddEmptyEnum(FileDescriptorProto* file, const std::string& name) { AddEnumValue(AddEnum(file, name), name + "_DUMMY", 1); } @@ -194,53 +199,97 @@ class MockErrorCollector : public DescriptorPool::ErrorCollector { MockErrorCollector() {} ~MockErrorCollector() {} - string text_; - string warning_text_; + std::string text_; + std::string warning_text_; // implements ErrorCollector --------------------------------------- - void AddError(const string& filename, - const string& element_name, const Message* descriptor, - ErrorLocation location, const string& message) { + void AddError(const std::string& filename, const std::string& element_name, + const Message* descriptor, ErrorLocation location, + const std::string& message) { const char* location_name = NULL; switch (location) { - case NAME : location_name = "NAME" ; break; - case NUMBER : location_name = "NUMBER" ; break; - case TYPE : location_name = "TYPE" ; break; - case EXTENDEE : location_name = "EXTENDEE" ; break; - case DEFAULT_VALUE: location_name = "DEFAULT_VALUE"; break; - case OPTION_NAME : location_name = "OPTION_NAME" ; break; - case OPTION_VALUE : location_name = "OPTION_VALUE" ; break; - case INPUT_TYPE : location_name = "INPUT_TYPE" ; break; - case OUTPUT_TYPE : location_name = "OUTPUT_TYPE" ; break; - case OTHER : location_name = "OTHER" ; break; + case NAME: + location_name = "NAME"; + break; + case NUMBER: + location_name = "NUMBER"; + break; + case TYPE: + location_name = "TYPE"; + break; + case EXTENDEE: + location_name = "EXTENDEE"; + break; + case DEFAULT_VALUE: + location_name = "DEFAULT_VALUE"; + break; + case OPTION_NAME: + location_name = "OPTION_NAME"; + break; + case OPTION_VALUE: + location_name = "OPTION_VALUE"; + break; + case INPUT_TYPE: + location_name = "INPUT_TYPE"; + break; + case OUTPUT_TYPE: + location_name = "OUTPUT_TYPE"; + break; + case IMPORT: + location_name = "IMPORT"; + break; + case OTHER: + location_name = "OTHER"; + break; } - strings::SubstituteAndAppend( - &text_, "$0: $1: $2: $3\n", - filename, element_name, location_name, message); + strings::SubstituteAndAppend(&text_, "$0: $1: $2: $3\n", filename, + element_name, location_name, message); } // implements ErrorCollector --------------------------------------- - void AddWarning(const string& filename, const string& element_name, + void AddWarning(const std::string& filename, const std::string& element_name, const Message* descriptor, ErrorLocation location, - const string& message) { + const std::string& message) { const char* location_name = NULL; switch (location) { - case NAME : location_name = "NAME" ; break; - case NUMBER : location_name = "NUMBER" ; break; - case TYPE : location_name = "TYPE" ; break; - case EXTENDEE : location_name = "EXTENDEE" ; break; - case DEFAULT_VALUE: location_name = "DEFAULT_VALUE"; break; - case OPTION_NAME : location_name = "OPTION_NAME" ; break; - case OPTION_VALUE : location_name = "OPTION_VALUE" ; break; - case INPUT_TYPE : location_name = "INPUT_TYPE" ; break; - case OUTPUT_TYPE : location_name = "OUTPUT_TYPE" ; break; - case OTHER : location_name = "OTHER" ; break; + case NAME: + location_name = "NAME"; + break; + case NUMBER: + location_name = "NUMBER"; + break; + case TYPE: + location_name = "TYPE"; + break; + case EXTENDEE: + location_name = "EXTENDEE"; + break; + case DEFAULT_VALUE: + location_name = "DEFAULT_VALUE"; + break; + case OPTION_NAME: + location_name = "OPTION_NAME"; + break; + case OPTION_VALUE: + location_name = "OPTION_VALUE"; + break; + case INPUT_TYPE: + location_name = "INPUT_TYPE"; + break; + case OUTPUT_TYPE: + location_name = "OUTPUT_TYPE"; + break; + case IMPORT: + location_name = "IMPORT"; + break; + case OTHER: + location_name = "OTHER"; + break; } - strings::SubstituteAndAppend( - &warning_text_, "$0: $1: $2: $3\n", - filename, element_name, location_name, message); + strings::SubstituteAndAppend(&warning_text_, "$0: $1: $2: $3\n", filename, + element_name, location_name, message); } }; @@ -331,17 +380,17 @@ class FileDescriptorTest : public testing::Test { const FileDescriptor* bar_file_; const FileDescriptor* baz_file_; - const Descriptor* foo_message_; - const EnumDescriptor* foo_enum_; + const Descriptor* foo_message_; + const EnumDescriptor* foo_enum_; const EnumValueDescriptor* foo_enum_value_; - const ServiceDescriptor* foo_service_; - const FieldDescriptor* foo_extension_; + const ServiceDescriptor* foo_service_; + const FieldDescriptor* foo_extension_; - const Descriptor* bar_message_; - const EnumDescriptor* bar_enum_; + const Descriptor* bar_message_; + const EnumDescriptor* bar_enum_; const EnumValueDescriptor* bar_enum_value_; - const ServiceDescriptor* bar_service_; - const FieldDescriptor* bar_extension_; + const ServiceDescriptor* bar_service_; + const FieldDescriptor* bar_extension_; }; TEST_F(FileDescriptorTest, Name) { @@ -501,8 +550,8 @@ TEST_F(FileDescriptorTest, Syntax) { } void ExtractDebugString( - const FileDescriptor* file, std::set* visited, - std::vector >* debug_strings) { + const FileDescriptor* file, std::set* visited, + std::vector>* debug_strings) { if (!visited->insert(file->name()).second) { return; } @@ -512,23 +561,23 @@ void ExtractDebugString( debug_strings->push_back(std::make_pair(file->name(), file->DebugString())); } -class SimpleErrorCollector : public google::protobuf::io::ErrorCollector { +class SimpleErrorCollector : public io::ErrorCollector { public: // implements ErrorCollector --------------------------------------- - void AddError(int line, int column, const string& message) { + void AddError(int line, int column, const std::string& message) { last_error_ = StringPrintf("%d:%d:", line, column) + message; } - const string& last_error() { return last_error_; } + const std::string& last_error() { return last_error_; } private: - string last_error_; + std::string last_error_; }; // Test that the result of FileDescriptor::DebugString() can be used to create // the original descriptors. TEST_F(FileDescriptorTest, DebugStringRoundTrip) { - std::set visited; - std::vector > debug_strings; + std::set visited; + std::vector> debug_strings; ExtractDebugString(protobuf_unittest::TestAllTypes::descriptor()->file(), &visited, &debug_strings); ExtractDebugString( @@ -540,12 +589,12 @@ TEST_F(FileDescriptorTest, DebugStringRoundTrip) { DescriptorPool pool; for (int i = 0; i < debug_strings.size(); ++i) { - const string& name = debug_strings[i].first; - const string& content = debug_strings[i].second; - google::protobuf::io::ArrayInputStream input_stream(content.data(), content.size()); + const std::string& name = debug_strings[i].first; + const std::string& content = debug_strings[i].second; + io::ArrayInputStream input_stream(content.data(), content.size()); SimpleErrorCollector error_collector; - google::protobuf::io::Tokenizer tokenizer(&input_stream, &error_collector); - google::protobuf::compiler::Parser parser; + io::Tokenizer tokenizer(&input_stream, &error_collector); + compiler::Parser parser; parser.RecordErrorsTo(&error_collector); FileDescriptorProto proto; ASSERT_TRUE(parser.Parse(&tokenizer, &proto)) @@ -617,35 +666,28 @@ class DescriptorTest : public testing::Test { AddEmptyEnum(&foo_file, "TestEnum"); DescriptorProto* message = AddMessage(&foo_file, "TestMessage"); - AddField(message, "foo", 1, - FieldDescriptorProto::LABEL_REQUIRED, + AddField(message, "foo", 1, FieldDescriptorProto::LABEL_REQUIRED, FieldDescriptorProto::TYPE_STRING); - AddField(message, "bar", 6, - FieldDescriptorProto::LABEL_OPTIONAL, + AddField(message, "bar", 6, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_ENUM) - ->set_type_name("TestEnum"); - AddField(message, "baz", 500000000, - FieldDescriptorProto::LABEL_REPEATED, + ->set_type_name("TestEnum"); + AddField(message, "baz", 500000000, FieldDescriptorProto::LABEL_REPEATED, FieldDescriptorProto::TYPE_MESSAGE) - ->set_type_name("TestForeign"); - AddField(message, "qux", 15, - FieldDescriptorProto::LABEL_OPTIONAL, + ->set_type_name("TestForeign"); + AddField(message, "qux", 15, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_GROUP) - ->set_type_name("TestForeign"); + ->set_type_name("TestForeign"); FileDescriptorProto bar_file; bar_file.set_name("bar.proto"); bar_file.set_package("corge.grault"); DescriptorProto* message2 = AddMessage(&bar_file, "TestMessage2"); - AddField(message2, "foo", 1, - FieldDescriptorProto::LABEL_REQUIRED, + AddField(message2, "foo", 1, FieldDescriptorProto::LABEL_REQUIRED, FieldDescriptorProto::TYPE_STRING); - AddField(message2, "bar", 2, - FieldDescriptorProto::LABEL_REQUIRED, + AddField(message2, "bar", 2, FieldDescriptorProto::LABEL_REQUIRED, FieldDescriptorProto::TYPE_STRING); - AddField(message2, "quux", 6, - FieldDescriptorProto::LABEL_REQUIRED, + AddField(message2, "quux", 6, FieldDescriptorProto::LABEL_REQUIRED, FieldDescriptorProto::TYPE_STRING); FileDescriptorProto map_file; @@ -653,11 +695,9 @@ class DescriptorTest : public testing::Test { DescriptorProto* message3 = AddMessage(&map_file, "TestMessage3"); DescriptorProto* entry = AddNestedMessage(message3, "MapInt32Int32Entry"); - AddField(entry, "key", 1, - FieldDescriptorProto::LABEL_OPTIONAL, + AddField(entry, "key", 1, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_INT32); - AddField(entry, "value", 2, - FieldDescriptorProto::LABEL_OPTIONAL, + AddField(entry, "value", 2, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_INT32); entry->mutable_options()->set_map_entry(true); @@ -670,23 +710,17 @@ class DescriptorTest : public testing::Test { json_file.set_name("json.proto"); json_file.set_syntax("proto3"); DescriptorProto* message4 = AddMessage(&json_file, "TestMessage4"); - AddField(message4, "field_name1", 1, - FieldDescriptorProto::LABEL_OPTIONAL, + AddField(message4, "field_name1", 1, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_INT32); - AddField(message4, "fieldName2", 2, - FieldDescriptorProto::LABEL_OPTIONAL, + AddField(message4, "fieldName2", 2, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_INT32); - AddField(message4, "FieldName3", 3, - FieldDescriptorProto::LABEL_OPTIONAL, + AddField(message4, "FieldName3", 3, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_INT32); - AddField(message4, "_field_name4", 4, - FieldDescriptorProto::LABEL_OPTIONAL, + AddField(message4, "_field_name4", 4, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_INT32); - AddField(message4, "FIELD_NAME5", 5, - FieldDescriptorProto::LABEL_OPTIONAL, + AddField(message4, "FIELD_NAME5", 5, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_INT32); - AddField(message4, "field_name6", 6, - FieldDescriptorProto::LABEL_OPTIONAL, + AddField(message4, "field_name6", 6, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_INT32) ->set_json_name("@type"); @@ -720,15 +754,15 @@ class DescriptorTest : public testing::Test { message2_ = bar_file_->message_type(0); ASSERT_EQ(3, message2_->field_count()); - foo2_ = message2_->field(0); - bar2_ = message2_->field(1); + foo2_ = message2_->field(0); + bar2_ = message2_->field(1); quux2_ = message2_->field(2); ASSERT_EQ(1, map_file_->message_type_count()); message3_ = map_file_->message_type(0); ASSERT_EQ(1, message3_->field_count()); - map_ = message3_->field(0); + map_ = message3_->field(0); ASSERT_EQ(1, json_file_->message_type_count()); message4_ = json_file_->message_type(0); @@ -801,8 +835,8 @@ TEST_F(DescriptorTest, FindFieldByName) { EXPECT_TRUE(message_->FindFieldByName("no_such_field") == NULL); EXPECT_TRUE(message_->FindFieldByName("quux") == NULL); - EXPECT_EQ(foo2_ , message2_->FindFieldByName("foo" )); - EXPECT_EQ(bar2_ , message2_->FindFieldByName("bar" )); + EXPECT_EQ(foo2_, message2_->FindFieldByName("foo")); + EXPECT_EQ(bar2_, message2_->FindFieldByName("bar")); EXPECT_EQ(quux2_, message2_->FindFieldByName("quux")); EXPECT_TRUE(message2_->FindFieldByName("baz") == NULL); EXPECT_TRUE(message2_->FindFieldByName("qux") == NULL); @@ -816,8 +850,8 @@ TEST_F(DescriptorTest, FindFieldByNumber) { EXPECT_TRUE(message_->FindFieldByNumber(837592) == NULL); EXPECT_TRUE(message_->FindFieldByNumber(2) == NULL); - EXPECT_EQ(foo2_ , message2_->FindFieldByNumber(1)); - EXPECT_EQ(bar2_ , message2_->FindFieldByNumber(2)); + EXPECT_EQ(foo2_, message2_->FindFieldByNumber(1)); + EXPECT_EQ(bar2_, message2_->FindFieldByNumber(2)); EXPECT_EQ(quux2_, message2_->FindFieldByNumber(6)); EXPECT_TRUE(message2_->FindFieldByNumber(15) == NULL); EXPECT_TRUE(message2_->FindFieldByNumber(500000000) == NULL); @@ -899,17 +933,17 @@ TEST_F(DescriptorTest, FieldIndex) { } TEST_F(DescriptorTest, FieldNumber) { - EXPECT_EQ( 1, foo_->number()); - EXPECT_EQ( 6, bar_->number()); + EXPECT_EQ(1, foo_->number()); + EXPECT_EQ(6, bar_->number()); EXPECT_EQ(500000000, baz_->number()); - EXPECT_EQ( 15, qux_->number()); + EXPECT_EQ(15, qux_->number()); } TEST_F(DescriptorTest, FieldType) { - EXPECT_EQ(FieldDescriptor::TYPE_STRING , foo_->type()); - EXPECT_EQ(FieldDescriptor::TYPE_ENUM , bar_->type()); + EXPECT_EQ(FieldDescriptor::TYPE_STRING, foo_->type()); + EXPECT_EQ(FieldDescriptor::TYPE_ENUM, bar_->type()); EXPECT_EQ(FieldDescriptor::TYPE_MESSAGE, baz_->type()); - EXPECT_EQ(FieldDescriptor::TYPE_GROUP , qux_->type()); + EXPECT_EQ(FieldDescriptor::TYPE_GROUP, qux_->type()); } TEST_F(DescriptorTest, FieldLabel) { @@ -918,17 +952,17 @@ TEST_F(DescriptorTest, FieldLabel) { EXPECT_EQ(FieldDescriptor::LABEL_REPEATED, baz_->label()); EXPECT_EQ(FieldDescriptor::LABEL_OPTIONAL, qux_->label()); - EXPECT_TRUE (foo_->is_required()); + EXPECT_TRUE(foo_->is_required()); EXPECT_FALSE(foo_->is_optional()); EXPECT_FALSE(foo_->is_repeated()); EXPECT_FALSE(bar_->is_required()); - EXPECT_TRUE (bar_->is_optional()); + EXPECT_TRUE(bar_->is_optional()); EXPECT_FALSE(bar_->is_repeated()); EXPECT_FALSE(baz_->is_required()); EXPECT_FALSE(baz_->is_optional()); - EXPECT_TRUE (baz_->is_repeated()); + EXPECT_TRUE(baz_->is_repeated()); } TEST_F(DescriptorTest, IsMap) { @@ -950,8 +984,8 @@ TEST_F(DescriptorTest, FieldContainingType) { EXPECT_EQ(message_, baz_->containing_type()); EXPECT_EQ(message_, qux_->containing_type()); - EXPECT_EQ(message2_, foo2_ ->containing_type()); - EXPECT_EQ(message2_, bar2_ ->containing_type()); + EXPECT_EQ(message2_, foo2_->containing_type()); + EXPECT_EQ(message2_, bar2_->containing_type()); EXPECT_EQ(message2_, quux2_->containing_type()); } @@ -1000,21 +1034,17 @@ class OneofDescriptorTest : public testing::Test { oneof_message->add_oneof_decl()->set_name("foo"); oneof_message->add_oneof_decl()->set_name("bar"); - AddField(oneof_message, "a", 1, - FieldDescriptorProto::LABEL_OPTIONAL, + AddField(oneof_message, "a", 1, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_INT32); - AddField(oneof_message, "b", 2, - FieldDescriptorProto::LABEL_OPTIONAL, + AddField(oneof_message, "b", 2, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_STRING); oneof_message->mutable_field(1)->set_oneof_index(0); - AddField(oneof_message, "c", 3, - FieldDescriptorProto::LABEL_OPTIONAL, + AddField(oneof_message, "c", 3, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_MESSAGE); oneof_message->mutable_field(2)->set_oneof_index(0); oneof_message->mutable_field(2)->set_type_name("TestOneof"); - AddField(oneof_message, "d", 4, - FieldDescriptorProto::LABEL_OPTIONAL, + AddField(oneof_message, "d", 4, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_FLOAT); oneof_message->mutable_field(3)->set_oneof_index(1); @@ -1081,14 +1111,11 @@ class StylizedFieldNamesTest : public testing::Test { AddExtensionRange(AddMessage(&file, "ExtendableMessage"), 1, 1000); DescriptorProto* message = AddMessage(&file, "TestMessage"); - AddField(message, "foo_foo", 1, - FieldDescriptorProto::LABEL_OPTIONAL, + AddField(message, "foo_foo", 1, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_INT32); - AddField(message, "FooBar", 2, - FieldDescriptorProto::LABEL_OPTIONAL, + AddField(message, "FooBar", 2, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_INT32); - AddField(message, "fooBaz", 3, - FieldDescriptorProto::LABEL_OPTIONAL, + AddField(message, "fooBaz", 3, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_INT32); AddField(message, "fooFoo", 4, // Camel-case conflict with foo_foo. FieldDescriptorProto::LABEL_OPTIONAL, @@ -1146,22 +1173,22 @@ class StylizedFieldNamesTest : public testing::Test { TEST_F(StylizedFieldNamesTest, LowercaseName) { EXPECT_EQ("foo_foo", message_->field(0)->lowercase_name()); - EXPECT_EQ("foobar" , message_->field(1)->lowercase_name()); - EXPECT_EQ("foobaz" , message_->field(2)->lowercase_name()); - EXPECT_EQ("foofoo" , message_->field(3)->lowercase_name()); - EXPECT_EQ("foobar" , message_->field(4)->lowercase_name()); + EXPECT_EQ("foobar", message_->field(1)->lowercase_name()); + EXPECT_EQ("foobaz", message_->field(2)->lowercase_name()); + EXPECT_EQ("foofoo", message_->field(3)->lowercase_name()); + EXPECT_EQ("foobar", message_->field(4)->lowercase_name()); EXPECT_EQ("bar_foo", message_->extension(0)->lowercase_name()); - EXPECT_EQ("barbar" , message_->extension(1)->lowercase_name()); - EXPECT_EQ("barbaz" , message_->extension(2)->lowercase_name()); - EXPECT_EQ("barfoo" , message_->extension(3)->lowercase_name()); - EXPECT_EQ("barbar" , message_->extension(4)->lowercase_name()); + EXPECT_EQ("barbar", message_->extension(1)->lowercase_name()); + EXPECT_EQ("barbaz", message_->extension(2)->lowercase_name()); + EXPECT_EQ("barfoo", message_->extension(3)->lowercase_name()); + EXPECT_EQ("barbar", message_->extension(4)->lowercase_name()); EXPECT_EQ("baz_foo", file_->extension(0)->lowercase_name()); - EXPECT_EQ("bazbar" , file_->extension(1)->lowercase_name()); - EXPECT_EQ("bazbaz" , file_->extension(2)->lowercase_name()); - EXPECT_EQ("bazfoo" , file_->extension(3)->lowercase_name()); - EXPECT_EQ("bazbar" , file_->extension(4)->lowercase_name()); + EXPECT_EQ("bazbar", file_->extension(1)->lowercase_name()); + EXPECT_EQ("bazbaz", file_->extension(2)->lowercase_name()); + EXPECT_EQ("bazfoo", file_->extension(3)->lowercase_name()); + EXPECT_EQ("bazbar", file_->extension(4)->lowercase_name()); } TEST_F(StylizedFieldNamesTest, CamelcaseName) { @@ -1185,12 +1212,9 @@ TEST_F(StylizedFieldNamesTest, CamelcaseName) { } TEST_F(StylizedFieldNamesTest, FindByLowercaseName) { - EXPECT_EQ(message_->field(0), - message_->FindFieldByLowercaseName("foo_foo")); - EXPECT_EQ(message_->field(1), - message_->FindFieldByLowercaseName("foobar")); - EXPECT_EQ(message_->field(2), - message_->FindFieldByLowercaseName("foobaz")); + EXPECT_EQ(message_->field(0), message_->FindFieldByLowercaseName("foo_foo")); + EXPECT_EQ(message_->field(1), message_->FindFieldByLowercaseName("foobar")); + EXPECT_EQ(message_->field(2), message_->FindFieldByLowercaseName("foobaz")); EXPECT_TRUE(message_->FindFieldByLowercaseName("FooBar") == NULL); EXPECT_TRUE(message_->FindFieldByLowercaseName("fooBaz") == NULL); EXPECT_TRUE(message_->FindFieldByLowercaseName("bar_foo") == NULL); @@ -1209,22 +1233,17 @@ TEST_F(StylizedFieldNamesTest, FindByLowercaseName) { EXPECT_EQ(file_->extension(0), file_->FindExtensionByLowercaseName("baz_foo")); - EXPECT_EQ(file_->extension(1), - file_->FindExtensionByLowercaseName("bazbar")); - EXPECT_EQ(file_->extension(2), - file_->FindExtensionByLowercaseName("bazbaz")); + EXPECT_EQ(file_->extension(1), file_->FindExtensionByLowercaseName("bazbar")); + EXPECT_EQ(file_->extension(2), file_->FindExtensionByLowercaseName("bazbaz")); EXPECT_TRUE(file_->FindExtensionByLowercaseName("BazBar") == NULL); EXPECT_TRUE(file_->FindExtensionByLowercaseName("bazBaz") == NULL); EXPECT_TRUE(file_->FindExtensionByLowercaseName("nosuchfield") == NULL); } TEST_F(StylizedFieldNamesTest, FindByCamelcaseName) { - EXPECT_EQ(message_->field(0), - message_->FindFieldByCamelcaseName("fooFoo")); - EXPECT_EQ(message_->field(1), - message_->FindFieldByCamelcaseName("fooBar")); - EXPECT_EQ(message_->field(2), - message_->FindFieldByCamelcaseName("fooBaz")); + EXPECT_EQ(message_->field(0), message_->FindFieldByCamelcaseName("fooFoo")); + EXPECT_EQ(message_->field(1), message_->FindFieldByCamelcaseName("fooBar")); + EXPECT_EQ(message_->field(2), message_->FindFieldByCamelcaseName("fooBaz")); EXPECT_TRUE(message_->FindFieldByCamelcaseName("foo_foo") == NULL); EXPECT_TRUE(message_->FindFieldByCamelcaseName("FooBar") == NULL); EXPECT_TRUE(message_->FindFieldByCamelcaseName("barFoo") == NULL); @@ -1241,12 +1260,9 @@ TEST_F(StylizedFieldNamesTest, FindByCamelcaseName) { EXPECT_TRUE(message_->FindExtensionByCamelcaseName("fooFoo") == NULL); EXPECT_TRUE(message_->FindExtensionByCamelcaseName("nosuchfield") == NULL); - EXPECT_EQ(file_->extension(0), - file_->FindExtensionByCamelcaseName("bazFoo")); - EXPECT_EQ(file_->extension(1), - file_->FindExtensionByCamelcaseName("bazBar")); - EXPECT_EQ(file_->extension(2), - file_->FindExtensionByCamelcaseName("bazBaz")); + EXPECT_EQ(file_->extension(0), file_->FindExtensionByCamelcaseName("bazFoo")); + EXPECT_EQ(file_->extension(1), file_->FindExtensionByCamelcaseName("bazBar")); + EXPECT_EQ(file_->extension(2), file_->FindExtensionByCamelcaseName("bazBaz")); EXPECT_TRUE(file_->FindExtensionByCamelcaseName("baz_foo") == NULL); EXPECT_TRUE(file_->FindExtensionByCamelcaseName("BazBar") == NULL); EXPECT_TRUE(file_->FindExtensionByCamelcaseName("nosuchfield") == NULL); @@ -1353,24 +1369,24 @@ TEST_F(EnumDescriptorTest, ValuesByIndex) { } TEST_F(EnumDescriptorTest, FindValueByName) { - EXPECT_EQ(foo_ , enum_ ->FindValueByName("FOO")); - EXPECT_EQ(bar_ , enum_ ->FindValueByName("BAR")); + EXPECT_EQ(foo_, enum_->FindValueByName("FOO")); + EXPECT_EQ(bar_, enum_->FindValueByName("BAR")); EXPECT_EQ(foo2_, enum2_->FindValueByName("FOO")); EXPECT_EQ(baz2_, enum2_->FindValueByName("BAZ")); - EXPECT_TRUE(enum_ ->FindValueByName("NO_SUCH_VALUE") == NULL); - EXPECT_TRUE(enum_ ->FindValueByName("BAZ" ) == NULL); - EXPECT_TRUE(enum2_->FindValueByName("BAR" ) == NULL); + EXPECT_TRUE(enum_->FindValueByName("NO_SUCH_VALUE") == NULL); + EXPECT_TRUE(enum_->FindValueByName("BAZ") == NULL); + EXPECT_TRUE(enum2_->FindValueByName("BAR") == NULL); } TEST_F(EnumDescriptorTest, FindValueByNumber) { - EXPECT_EQ(foo_ , enum_ ->FindValueByNumber(1)); - EXPECT_EQ(bar_ , enum_ ->FindValueByNumber(2)); + EXPECT_EQ(foo_, enum_->FindValueByNumber(1)); + EXPECT_EQ(bar_, enum_->FindValueByNumber(2)); EXPECT_EQ(foo2_, enum2_->FindValueByNumber(1)); EXPECT_EQ(baz2_, enum2_->FindValueByNumber(3)); - EXPECT_TRUE(enum_ ->FindValueByNumber(416) == NULL); - EXPECT_TRUE(enum_ ->FindValueByNumber(3) == NULL); + EXPECT_TRUE(enum_->FindValueByNumber(416) == NULL); + EXPECT_TRUE(enum_->FindValueByNumber(3) == NULL); EXPECT_TRUE(enum2_->FindValueByNumber(2) == NULL); } @@ -1397,8 +1413,8 @@ TEST_F(EnumDescriptorTest, ValueNumber) { } TEST_F(EnumDescriptorTest, ValueType) { - EXPECT_EQ(enum_ , foo_ ->type()); - EXPECT_EQ(enum_ , bar_ ->type()); + EXPECT_EQ(enum_, foo_->type()); + EXPECT_EQ(enum_, bar_->type()); EXPECT_EQ(enum2_, foo2_->type()); EXPECT_EQ(enum2_, baz2_->type()); } @@ -1461,11 +1477,11 @@ class ServiceDescriptorTest : public testing::Test { ASSERT_TRUE(bar_file_ != NULL); ASSERT_EQ(6, foo_file_->message_type_count()); - foo_request_ = foo_file_->message_type(0); + foo_request_ = foo_file_->message_type(0); foo_response_ = foo_file_->message_type(1); - bar_request_ = foo_file_->message_type(2); + bar_request_ = foo_file_->message_type(2); bar_response_ = foo_file_->message_type(3); - baz_request_ = foo_file_->message_type(4); + baz_request_ = foo_file_->message_type(4); baz_response_ = foo_file_->message_type(5); ASSERT_EQ(1, foo_file_->service_count()); @@ -1522,14 +1538,14 @@ TEST_F(ServiceDescriptorTest, MethodsByIndex) { } TEST_F(ServiceDescriptorTest, FindMethodByName) { - EXPECT_EQ(foo_ , service_ ->FindMethodByName("Foo")); - EXPECT_EQ(bar_ , service_ ->FindMethodByName("Bar")); + EXPECT_EQ(foo_, service_->FindMethodByName("Foo")); + EXPECT_EQ(bar_, service_->FindMethodByName("Bar")); EXPECT_EQ(foo2_, service2_->FindMethodByName("Foo")); EXPECT_EQ(baz2_, service2_->FindMethodByName("Baz")); - EXPECT_TRUE(service_ ->FindMethodByName("NoSuchMethod") == NULL); - EXPECT_TRUE(service_ ->FindMethodByName("Baz" ) == NULL); - EXPECT_TRUE(service2_->FindMethodByName("Bar" ) == NULL); + EXPECT_TRUE(service_->FindMethodByName("NoSuchMethod") == NULL); + EXPECT_TRUE(service_->FindMethodByName("Baz") == NULL); + EXPECT_TRUE(service2_->FindMethodByName("Bar") == NULL); } TEST_F(ServiceDescriptorTest, MethodName) { @@ -1683,8 +1699,8 @@ class NestedDescriptorTest : public testing::Test { }; TEST_F(NestedDescriptorTest, MessageName) { - EXPECT_EQ("Foo", foo_ ->name()); - EXPECT_EQ("Bar", bar_ ->name()); + EXPECT_EQ("Foo", foo_->name()); + EXPECT_EQ("Bar", bar_->name()); EXPECT_EQ("Foo", foo2_->name()); EXPECT_EQ("Baz", baz2_->name()); @@ -1695,8 +1711,8 @@ TEST_F(NestedDescriptorTest, MessageName) { } TEST_F(NestedDescriptorTest, MessageContainingType) { - EXPECT_EQ(message_ , foo_ ->containing_type()); - EXPECT_EQ(message_ , bar_ ->containing_type()); + EXPECT_EQ(message_, foo_->containing_type()); + EXPECT_EQ(message_, bar_->containing_type()); EXPECT_EQ(message2_, foo2_->containing_type()); EXPECT_EQ(message2_, baz2_->containing_type()); } @@ -1715,34 +1731,34 @@ TEST_F(NestedDescriptorTest, FindFieldByNameDoesntFindNestedTypes) { } TEST_F(NestedDescriptorTest, FindNestedTypeByName) { - EXPECT_EQ(foo_ , message_ ->FindNestedTypeByName("Foo")); - EXPECT_EQ(bar_ , message_ ->FindNestedTypeByName("Bar")); + EXPECT_EQ(foo_, message_->FindNestedTypeByName("Foo")); + EXPECT_EQ(bar_, message_->FindNestedTypeByName("Bar")); EXPECT_EQ(foo2_, message2_->FindNestedTypeByName("Foo")); EXPECT_EQ(baz2_, message2_->FindNestedTypeByName("Baz")); - EXPECT_TRUE(message_ ->FindNestedTypeByName("NoSuchType") == NULL); - EXPECT_TRUE(message_ ->FindNestedTypeByName("Baz" ) == NULL); - EXPECT_TRUE(message2_->FindNestedTypeByName("Bar" ) == NULL); + EXPECT_TRUE(message_->FindNestedTypeByName("NoSuchType") == NULL); + EXPECT_TRUE(message_->FindNestedTypeByName("Baz") == NULL); + EXPECT_TRUE(message2_->FindNestedTypeByName("Bar") == NULL); EXPECT_TRUE(message_->FindNestedTypeByName("Qux") == NULL); } TEST_F(NestedDescriptorTest, EnumName) { - EXPECT_EQ("Baz" , baz_ ->name()); - EXPECT_EQ("Qux" , qux_ ->name()); - EXPECT_EQ("Qux" , qux2_->name()); + EXPECT_EQ("Baz", baz_->name()); + EXPECT_EQ("Qux", qux_->name()); + EXPECT_EQ("Qux", qux2_->name()); EXPECT_EQ("Quux", quux2_->name()); EXPECT_EQ("TestMessage.Baz", baz_->full_name()); EXPECT_EQ("TestMessage.Qux", qux_->full_name()); - EXPECT_EQ("corge.grault.TestMessage2.Qux" , qux2_ ->full_name()); + EXPECT_EQ("corge.grault.TestMessage2.Qux", qux2_->full_name()); EXPECT_EQ("corge.grault.TestMessage2.Quux", quux2_->full_name()); } TEST_F(NestedDescriptorTest, EnumContainingType) { - EXPECT_EQ(message_ , baz_ ->containing_type()); - EXPECT_EQ(message_ , qux_ ->containing_type()); - EXPECT_EQ(message2_, qux2_ ->containing_type()); + EXPECT_EQ(message_, baz_->containing_type()); + EXPECT_EQ(message_, qux_->containing_type()); + EXPECT_EQ(message2_, qux2_->containing_type()); EXPECT_EQ(message2_, quux2_->containing_type()); } @@ -1753,27 +1769,27 @@ TEST_F(NestedDescriptorTest, NestedEnumsByIndex) { } TEST_F(NestedDescriptorTest, FindEnumTypeByName) { - EXPECT_EQ(baz_ , message_ ->FindEnumTypeByName("Baz" )); - EXPECT_EQ(qux_ , message_ ->FindEnumTypeByName("Qux" )); - EXPECT_EQ(qux2_ , message2_->FindEnumTypeByName("Qux" )); + EXPECT_EQ(baz_, message_->FindEnumTypeByName("Baz")); + EXPECT_EQ(qux_, message_->FindEnumTypeByName("Qux")); + EXPECT_EQ(qux2_, message2_->FindEnumTypeByName("Qux")); EXPECT_EQ(quux2_, message2_->FindEnumTypeByName("Quux")); - EXPECT_TRUE(message_ ->FindEnumTypeByName("NoSuchType") == NULL); - EXPECT_TRUE(message_ ->FindEnumTypeByName("Quux" ) == NULL); - EXPECT_TRUE(message2_->FindEnumTypeByName("Baz" ) == NULL); + EXPECT_TRUE(message_->FindEnumTypeByName("NoSuchType") == NULL); + EXPECT_TRUE(message_->FindEnumTypeByName("Quux") == NULL); + EXPECT_TRUE(message2_->FindEnumTypeByName("Baz") == NULL); EXPECT_TRUE(message_->FindEnumTypeByName("Foo") == NULL); } TEST_F(NestedDescriptorTest, FindEnumValueByName) { - EXPECT_EQ(a_ , message_ ->FindEnumValueByName("A")); - EXPECT_EQ(b_ , message_ ->FindEnumValueByName("B")); + EXPECT_EQ(a_, message_->FindEnumValueByName("A")); + EXPECT_EQ(b_, message_->FindEnumValueByName("B")); EXPECT_EQ(a2_, message2_->FindEnumValueByName("A")); EXPECT_EQ(c2_, message2_->FindEnumValueByName("C")); - EXPECT_TRUE(message_ ->FindEnumValueByName("NO_SUCH_VALUE") == NULL); - EXPECT_TRUE(message_ ->FindEnumValueByName("C" ) == NULL); - EXPECT_TRUE(message2_->FindEnumValueByName("B" ) == NULL); + EXPECT_TRUE(message_->FindEnumValueByName("NO_SUCH_VALUE") == NULL); + EXPECT_TRUE(message_->FindEnumValueByName("C") == NULL); + EXPECT_TRUE(message2_->FindEnumValueByName("B") == NULL); EXPECT_TRUE(message_->FindEnumValueByName("Foo") == NULL); } @@ -1817,17 +1833,17 @@ class ExtensionDescriptorTest : public testing::Test { AddExtension(&foo_file, "Foo", "foo_enum", 19, FieldDescriptorProto::LABEL_REPEATED, FieldDescriptorProto::TYPE_ENUM) - ->set_type_name("Baz"); + ->set_type_name("Baz"); DescriptorProto* bar = AddMessage(&foo_file, "Bar"); AddNestedExtension(bar, "Foo", "foo_message", 30, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_MESSAGE) - ->set_type_name("Qux"); + ->set_type_name("Qux"); AddNestedExtension(bar, "Foo", "foo_group", 39, FieldDescriptorProto::LABEL_REPEATED, FieldDescriptorProto::TYPE_GROUP) - ->set_type_name("Qux"); + ->set_type_name("Qux"); // Build the descriptors and get the pointers. foo_file_ = pool_.BuildFile(foo_file); @@ -1873,20 +1889,20 @@ TEST_F(ExtensionDescriptorTest, Extensions) { EXPECT_TRUE(bar_->extension(0)->is_extension()); EXPECT_TRUE(bar_->extension(1)->is_extension()); - EXPECT_EQ("foo_int32" , foo_file_->extension(0)->name()); - EXPECT_EQ("foo_enum" , foo_file_->extension(1)->name()); + EXPECT_EQ("foo_int32", foo_file_->extension(0)->name()); + EXPECT_EQ("foo_enum", foo_file_->extension(1)->name()); EXPECT_EQ("foo_message", bar_->extension(0)->name()); - EXPECT_EQ("foo_group" , bar_->extension(1)->name()); + EXPECT_EQ("foo_group", bar_->extension(1)->name()); EXPECT_EQ(10, foo_file_->extension(0)->number()); EXPECT_EQ(19, foo_file_->extension(1)->number()); EXPECT_EQ(30, bar_->extension(0)->number()); EXPECT_EQ(39, bar_->extension(1)->number()); - EXPECT_EQ(FieldDescriptor::TYPE_INT32 , foo_file_->extension(0)->type()); - EXPECT_EQ(FieldDescriptor::TYPE_ENUM , foo_file_->extension(1)->type()); + EXPECT_EQ(FieldDescriptor::TYPE_INT32, foo_file_->extension(0)->type()); + EXPECT_EQ(FieldDescriptor::TYPE_ENUM, foo_file_->extension(1)->type()); EXPECT_EQ(FieldDescriptor::TYPE_MESSAGE, bar_->extension(0)->type()); - EXPECT_EQ(FieldDescriptor::TYPE_GROUP , bar_->extension(1)->type()); + EXPECT_EQ(FieldDescriptor::TYPE_GROUP, bar_->extension(1)->type()); EXPECT_EQ(baz_, foo_file_->extension(1)->enum_type()); EXPECT_EQ(qux_, bar_->extension(0)->message_type()); @@ -1909,13 +1925,13 @@ TEST_F(ExtensionDescriptorTest, Extensions) { }; TEST_F(ExtensionDescriptorTest, IsExtensionNumber) { - EXPECT_FALSE(foo_->IsExtensionNumber( 9)); - EXPECT_TRUE (foo_->IsExtensionNumber(10)); - EXPECT_TRUE (foo_->IsExtensionNumber(19)); + EXPECT_FALSE(foo_->IsExtensionNumber(9)); + EXPECT_TRUE(foo_->IsExtensionNumber(10)); + EXPECT_TRUE(foo_->IsExtensionNumber(19)); EXPECT_FALSE(foo_->IsExtensionNumber(20)); EXPECT_FALSE(foo_->IsExtensionNumber(29)); - EXPECT_TRUE (foo_->IsExtensionNumber(30)); - EXPECT_TRUE (foo_->IsExtensionNumber(39)); + EXPECT_TRUE(foo_->IsExtensionNumber(30)); + EXPECT_TRUE(foo_->IsExtensionNumber(39)); EXPECT_FALSE(foo_->IsExtensionNumber(40)); } @@ -1925,7 +1941,7 @@ TEST_F(ExtensionDescriptorTest, FindExtensionByName) { ASSERT_EQ(2, bar_->extension_count()); EXPECT_EQ(bar_->extension(0), bar_->FindExtensionByName("foo_message")); - EXPECT_EQ(bar_->extension(1), bar_->FindExtensionByName("foo_group" )); + EXPECT_EQ(bar_->extension(1), bar_->FindExtensionByName("foo_group")); EXPECT_TRUE(bar_->FindExtensionByName("no_such_extension") == NULL); EXPECT_TRUE(foo_->FindExtensionByName("foo_int32") == NULL); @@ -2029,16 +2045,16 @@ TEST_F(ReservedDescriptorTest, ReservedRanges) { TEST_F(ReservedDescriptorTest, IsReservedNumber) { EXPECT_FALSE(foo_->IsReservedNumber(1)); - EXPECT_TRUE (foo_->IsReservedNumber(2)); + EXPECT_TRUE(foo_->IsReservedNumber(2)); EXPECT_FALSE(foo_->IsReservedNumber(3)); EXPECT_FALSE(foo_->IsReservedNumber(8)); - EXPECT_TRUE (foo_->IsReservedNumber(9)); - EXPECT_TRUE (foo_->IsReservedNumber(10)); - EXPECT_TRUE (foo_->IsReservedNumber(11)); + EXPECT_TRUE(foo_->IsReservedNumber(9)); + EXPECT_TRUE(foo_->IsReservedNumber(10)); + EXPECT_TRUE(foo_->IsReservedNumber(11)); EXPECT_FALSE(foo_->IsReservedNumber(12)); EXPECT_FALSE(foo_->IsReservedNumber(13)); EXPECT_FALSE(foo_->IsReservedNumber(14)); - EXPECT_TRUE (foo_->IsReservedNumber(15)); + EXPECT_TRUE(foo_->IsReservedNumber(15)); EXPECT_FALSE(foo_->IsReservedNumber(16)); }; @@ -2050,8 +2066,8 @@ TEST_F(ReservedDescriptorTest, ReservedNames) { }; TEST_F(ReservedDescriptorTest, IsReservedName) { - EXPECT_TRUE (foo_->IsReservedName("foo")); - EXPECT_TRUE (foo_->IsReservedName("bar")); + EXPECT_TRUE(foo_->IsReservedName("foo")); + EXPECT_TRUE(foo_->IsReservedName("bar")); EXPECT_FALSE(foo_->IsReservedName("baz")); }; @@ -2148,17 +2164,17 @@ TEST_F(ReservedEnumDescriptorTest, IsReservedNumber) { EXPECT_TRUE(foo_->IsReservedNumber(-1)); EXPECT_TRUE(foo_->IsReservedNumber(0)); EXPECT_TRUE(foo_->IsReservedNumber(1)); - EXPECT_TRUE (foo_->IsReservedNumber(2)); + EXPECT_TRUE(foo_->IsReservedNumber(2)); EXPECT_TRUE(foo_->IsReservedNumber(3)); EXPECT_FALSE(foo_->IsReservedNumber(8)); - EXPECT_TRUE (foo_->IsReservedNumber(9)); - EXPECT_TRUE (foo_->IsReservedNumber(10)); - EXPECT_TRUE (foo_->IsReservedNumber(11)); + EXPECT_TRUE(foo_->IsReservedNumber(9)); + EXPECT_TRUE(foo_->IsReservedNumber(10)); + EXPECT_TRUE(foo_->IsReservedNumber(11)); EXPECT_TRUE(foo_->IsReservedNumber(12)); EXPECT_FALSE(foo_->IsReservedNumber(13)); EXPECT_FALSE(foo_->IsReservedNumber(13)); EXPECT_FALSE(foo_->IsReservedNumber(14)); - EXPECT_TRUE (foo_->IsReservedNumber(15)); + EXPECT_TRUE(foo_->IsReservedNumber(15)); EXPECT_TRUE(foo_->IsReservedNumber(16)); EXPECT_FALSE(foo_->IsReservedNumber(17)); @@ -2181,8 +2197,8 @@ TEST_F(ReservedEnumDescriptorTest, ReservedNames) { } TEST_F(ReservedEnumDescriptorTest, IsReservedName) { - EXPECT_TRUE (foo_->IsReservedName("foo")); - EXPECT_TRUE (foo_->IsReservedName("bar")); + EXPECT_TRUE(foo_->IsReservedName("foo")); + EXPECT_TRUE(foo_->IsReservedName("bar")); EXPECT_FALSE(foo_->IsReservedName("baz")); } @@ -2197,9 +2213,9 @@ class MiscTest : public testing::Test { AddEmptyEnum(&file_proto, "DummyEnum"); DescriptorProto* message = AddMessage(&file_proto, "TestMessage"); - FieldDescriptorProto* field = - AddField(message, "foo", 1, FieldDescriptorProto::LABEL_OPTIONAL, - static_cast(static_cast(type))); + FieldDescriptorProto* field = AddField( + message, "foo", 1, FieldDescriptorProto::LABEL_OPTIONAL, + static_cast(static_cast(type))); if (type == FieldDescriptor::TYPE_MESSAGE || type == FieldDescriptor::TYPE_GROUP) { @@ -2212,8 +2228,7 @@ class MiscTest : public testing::Test { pool_.reset(new DescriptorPool()); const FileDescriptor* file = pool_->BuildFile(file_proto); - if (file != NULL && - file->message_type_count() == 1 && + if (file != NULL && file->message_type_count() == 1 && file->message_type(0)->field_count() == 1) { return file->message_type(0)->field(0); } else { @@ -2228,8 +2243,8 @@ class MiscTest : public testing::Test { FieldDescriptor::CppType GetCppTypeForFieldType(FieldDescriptor::Type type) { const FieldDescriptor* field = GetFieldDescriptorOfType(type); - return field != NULL ? field->cpp_type() : - static_cast(0); + return field != NULL ? field->cpp_type() + : static_cast(0); } const char* GetCppTypeNameForFieldType(FieldDescriptor::Type type) { @@ -2244,7 +2259,7 @@ class MiscTest : public testing::Test { } const EnumDescriptor* GetEnumDescriptorForFieldType( - FieldDescriptor::Type type) { + FieldDescriptor::Type type) { const FieldDescriptor* field = GetFieldDescriptorOfType(type); return field != NULL ? field->enum_type() : NULL; } @@ -2257,24 +2272,24 @@ TEST_F(MiscTest, TypeNames) { typedef FieldDescriptor FD; // avoid ugly line wrapping - EXPECT_STREQ("double" , GetTypeNameForFieldType(FD::TYPE_DOUBLE )); - EXPECT_STREQ("float" , GetTypeNameForFieldType(FD::TYPE_FLOAT )); - EXPECT_STREQ("int64" , GetTypeNameForFieldType(FD::TYPE_INT64 )); - EXPECT_STREQ("uint64" , GetTypeNameForFieldType(FD::TYPE_UINT64 )); - EXPECT_STREQ("int32" , GetTypeNameForFieldType(FD::TYPE_INT32 )); - EXPECT_STREQ("fixed64" , GetTypeNameForFieldType(FD::TYPE_FIXED64 )); - EXPECT_STREQ("fixed32" , GetTypeNameForFieldType(FD::TYPE_FIXED32 )); - EXPECT_STREQ("bool" , GetTypeNameForFieldType(FD::TYPE_BOOL )); - EXPECT_STREQ("string" , GetTypeNameForFieldType(FD::TYPE_STRING )); - EXPECT_STREQ("group" , GetTypeNameForFieldType(FD::TYPE_GROUP )); - EXPECT_STREQ("message" , GetTypeNameForFieldType(FD::TYPE_MESSAGE )); - EXPECT_STREQ("bytes" , GetTypeNameForFieldType(FD::TYPE_BYTES )); - EXPECT_STREQ("uint32" , GetTypeNameForFieldType(FD::TYPE_UINT32 )); - EXPECT_STREQ("enum" , GetTypeNameForFieldType(FD::TYPE_ENUM )); + EXPECT_STREQ("double", GetTypeNameForFieldType(FD::TYPE_DOUBLE)); + EXPECT_STREQ("float", GetTypeNameForFieldType(FD::TYPE_FLOAT)); + EXPECT_STREQ("int64", GetTypeNameForFieldType(FD::TYPE_INT64)); + EXPECT_STREQ("uint64", GetTypeNameForFieldType(FD::TYPE_UINT64)); + EXPECT_STREQ("int32", GetTypeNameForFieldType(FD::TYPE_INT32)); + EXPECT_STREQ("fixed64", GetTypeNameForFieldType(FD::TYPE_FIXED64)); + EXPECT_STREQ("fixed32", GetTypeNameForFieldType(FD::TYPE_FIXED32)); + EXPECT_STREQ("bool", GetTypeNameForFieldType(FD::TYPE_BOOL)); + EXPECT_STREQ("string", GetTypeNameForFieldType(FD::TYPE_STRING)); + EXPECT_STREQ("group", GetTypeNameForFieldType(FD::TYPE_GROUP)); + EXPECT_STREQ("message", GetTypeNameForFieldType(FD::TYPE_MESSAGE)); + EXPECT_STREQ("bytes", GetTypeNameForFieldType(FD::TYPE_BYTES)); + EXPECT_STREQ("uint32", GetTypeNameForFieldType(FD::TYPE_UINT32)); + EXPECT_STREQ("enum", GetTypeNameForFieldType(FD::TYPE_ENUM)); EXPECT_STREQ("sfixed32", GetTypeNameForFieldType(FD::TYPE_SFIXED32)); EXPECT_STREQ("sfixed64", GetTypeNameForFieldType(FD::TYPE_SFIXED64)); - EXPECT_STREQ("sint32" , GetTypeNameForFieldType(FD::TYPE_SINT32 )); - EXPECT_STREQ("sint64" , GetTypeNameForFieldType(FD::TYPE_SINT64 )); + EXPECT_STREQ("sint32", GetTypeNameForFieldType(FD::TYPE_SINT32)); + EXPECT_STREQ("sint64", GetTypeNameForFieldType(FD::TYPE_SINT64)); } TEST_F(MiscTest, StaticTypeNames) { @@ -2282,24 +2297,24 @@ TEST_F(MiscTest, StaticTypeNames) { typedef FieldDescriptor FD; // avoid ugly line wrapping - EXPECT_STREQ("double" , FD::TypeName(FD::TYPE_DOUBLE )); - EXPECT_STREQ("float" , FD::TypeName(FD::TYPE_FLOAT )); - EXPECT_STREQ("int64" , FD::TypeName(FD::TYPE_INT64 )); - EXPECT_STREQ("uint64" , FD::TypeName(FD::TYPE_UINT64 )); - EXPECT_STREQ("int32" , FD::TypeName(FD::TYPE_INT32 )); - EXPECT_STREQ("fixed64" , FD::TypeName(FD::TYPE_FIXED64 )); - EXPECT_STREQ("fixed32" , FD::TypeName(FD::TYPE_FIXED32 )); - EXPECT_STREQ("bool" , FD::TypeName(FD::TYPE_BOOL )); - EXPECT_STREQ("string" , FD::TypeName(FD::TYPE_STRING )); - EXPECT_STREQ("group" , FD::TypeName(FD::TYPE_GROUP )); - EXPECT_STREQ("message" , FD::TypeName(FD::TYPE_MESSAGE )); - EXPECT_STREQ("bytes" , FD::TypeName(FD::TYPE_BYTES )); - EXPECT_STREQ("uint32" , FD::TypeName(FD::TYPE_UINT32 )); - EXPECT_STREQ("enum" , FD::TypeName(FD::TYPE_ENUM )); + EXPECT_STREQ("double", FD::TypeName(FD::TYPE_DOUBLE)); + EXPECT_STREQ("float", FD::TypeName(FD::TYPE_FLOAT)); + EXPECT_STREQ("int64", FD::TypeName(FD::TYPE_INT64)); + EXPECT_STREQ("uint64", FD::TypeName(FD::TYPE_UINT64)); + EXPECT_STREQ("int32", FD::TypeName(FD::TYPE_INT32)); + EXPECT_STREQ("fixed64", FD::TypeName(FD::TYPE_FIXED64)); + EXPECT_STREQ("fixed32", FD::TypeName(FD::TYPE_FIXED32)); + EXPECT_STREQ("bool", FD::TypeName(FD::TYPE_BOOL)); + EXPECT_STREQ("string", FD::TypeName(FD::TYPE_STRING)); + EXPECT_STREQ("group", FD::TypeName(FD::TYPE_GROUP)); + EXPECT_STREQ("message", FD::TypeName(FD::TYPE_MESSAGE)); + EXPECT_STREQ("bytes", FD::TypeName(FD::TYPE_BYTES)); + EXPECT_STREQ("uint32", FD::TypeName(FD::TYPE_UINT32)); + EXPECT_STREQ("enum", FD::TypeName(FD::TYPE_ENUM)); EXPECT_STREQ("sfixed32", FD::TypeName(FD::TYPE_SFIXED32)); EXPECT_STREQ("sfixed64", FD::TypeName(FD::TYPE_SFIXED64)); - EXPECT_STREQ("sint32" , FD::TypeName(FD::TYPE_SINT32 )); - EXPECT_STREQ("sint64" , FD::TypeName(FD::TYPE_SINT64 )); + EXPECT_STREQ("sint32", FD::TypeName(FD::TYPE_SINT32)); + EXPECT_STREQ("sint64", FD::TypeName(FD::TYPE_SINT64)); } TEST_F(MiscTest, CppTypes) { @@ -2307,24 +2322,24 @@ TEST_F(MiscTest, CppTypes) { typedef FieldDescriptor FD; // avoid ugly line wrapping - EXPECT_EQ(FD::CPPTYPE_DOUBLE , GetCppTypeForFieldType(FD::TYPE_DOUBLE )); - EXPECT_EQ(FD::CPPTYPE_FLOAT , GetCppTypeForFieldType(FD::TYPE_FLOAT )); - EXPECT_EQ(FD::CPPTYPE_INT64 , GetCppTypeForFieldType(FD::TYPE_INT64 )); - EXPECT_EQ(FD::CPPTYPE_UINT64 , GetCppTypeForFieldType(FD::TYPE_UINT64 )); - EXPECT_EQ(FD::CPPTYPE_INT32 , GetCppTypeForFieldType(FD::TYPE_INT32 )); - EXPECT_EQ(FD::CPPTYPE_UINT64 , GetCppTypeForFieldType(FD::TYPE_FIXED64 )); - EXPECT_EQ(FD::CPPTYPE_UINT32 , GetCppTypeForFieldType(FD::TYPE_FIXED32 )); - EXPECT_EQ(FD::CPPTYPE_BOOL , GetCppTypeForFieldType(FD::TYPE_BOOL )); - EXPECT_EQ(FD::CPPTYPE_STRING , GetCppTypeForFieldType(FD::TYPE_STRING )); - EXPECT_EQ(FD::CPPTYPE_MESSAGE, GetCppTypeForFieldType(FD::TYPE_GROUP )); - EXPECT_EQ(FD::CPPTYPE_MESSAGE, GetCppTypeForFieldType(FD::TYPE_MESSAGE )); - EXPECT_EQ(FD::CPPTYPE_STRING , GetCppTypeForFieldType(FD::TYPE_BYTES )); - EXPECT_EQ(FD::CPPTYPE_UINT32 , GetCppTypeForFieldType(FD::TYPE_UINT32 )); - EXPECT_EQ(FD::CPPTYPE_ENUM , GetCppTypeForFieldType(FD::TYPE_ENUM )); - EXPECT_EQ(FD::CPPTYPE_INT32 , GetCppTypeForFieldType(FD::TYPE_SFIXED32)); - EXPECT_EQ(FD::CPPTYPE_INT64 , GetCppTypeForFieldType(FD::TYPE_SFIXED64)); - EXPECT_EQ(FD::CPPTYPE_INT32 , GetCppTypeForFieldType(FD::TYPE_SINT32 )); - EXPECT_EQ(FD::CPPTYPE_INT64 , GetCppTypeForFieldType(FD::TYPE_SINT64 )); + EXPECT_EQ(FD::CPPTYPE_DOUBLE, GetCppTypeForFieldType(FD::TYPE_DOUBLE)); + EXPECT_EQ(FD::CPPTYPE_FLOAT, GetCppTypeForFieldType(FD::TYPE_FLOAT)); + EXPECT_EQ(FD::CPPTYPE_INT64, GetCppTypeForFieldType(FD::TYPE_INT64)); + EXPECT_EQ(FD::CPPTYPE_UINT64, GetCppTypeForFieldType(FD::TYPE_UINT64)); + EXPECT_EQ(FD::CPPTYPE_INT32, GetCppTypeForFieldType(FD::TYPE_INT32)); + EXPECT_EQ(FD::CPPTYPE_UINT64, GetCppTypeForFieldType(FD::TYPE_FIXED64)); + EXPECT_EQ(FD::CPPTYPE_UINT32, GetCppTypeForFieldType(FD::TYPE_FIXED32)); + EXPECT_EQ(FD::CPPTYPE_BOOL, GetCppTypeForFieldType(FD::TYPE_BOOL)); + EXPECT_EQ(FD::CPPTYPE_STRING, GetCppTypeForFieldType(FD::TYPE_STRING)); + EXPECT_EQ(FD::CPPTYPE_MESSAGE, GetCppTypeForFieldType(FD::TYPE_GROUP)); + EXPECT_EQ(FD::CPPTYPE_MESSAGE, GetCppTypeForFieldType(FD::TYPE_MESSAGE)); + EXPECT_EQ(FD::CPPTYPE_STRING, GetCppTypeForFieldType(FD::TYPE_BYTES)); + EXPECT_EQ(FD::CPPTYPE_UINT32, GetCppTypeForFieldType(FD::TYPE_UINT32)); + EXPECT_EQ(FD::CPPTYPE_ENUM, GetCppTypeForFieldType(FD::TYPE_ENUM)); + EXPECT_EQ(FD::CPPTYPE_INT32, GetCppTypeForFieldType(FD::TYPE_SFIXED32)); + EXPECT_EQ(FD::CPPTYPE_INT64, GetCppTypeForFieldType(FD::TYPE_SFIXED64)); + EXPECT_EQ(FD::CPPTYPE_INT32, GetCppTypeForFieldType(FD::TYPE_SINT32)); + EXPECT_EQ(FD::CPPTYPE_INT64, GetCppTypeForFieldType(FD::TYPE_SINT64)); } TEST_F(MiscTest, CppTypeNames) { @@ -2332,24 +2347,24 @@ TEST_F(MiscTest, CppTypeNames) { typedef FieldDescriptor FD; // avoid ugly line wrapping - EXPECT_STREQ("double" , GetCppTypeNameForFieldType(FD::TYPE_DOUBLE )); - EXPECT_STREQ("float" , GetCppTypeNameForFieldType(FD::TYPE_FLOAT )); - EXPECT_STREQ("int64" , GetCppTypeNameForFieldType(FD::TYPE_INT64 )); - EXPECT_STREQ("uint64" , GetCppTypeNameForFieldType(FD::TYPE_UINT64 )); - EXPECT_STREQ("int32" , GetCppTypeNameForFieldType(FD::TYPE_INT32 )); - EXPECT_STREQ("uint64" , GetCppTypeNameForFieldType(FD::TYPE_FIXED64 )); - EXPECT_STREQ("uint32" , GetCppTypeNameForFieldType(FD::TYPE_FIXED32 )); - EXPECT_STREQ("bool" , GetCppTypeNameForFieldType(FD::TYPE_BOOL )); - EXPECT_STREQ("string" , GetCppTypeNameForFieldType(FD::TYPE_STRING )); - EXPECT_STREQ("message", GetCppTypeNameForFieldType(FD::TYPE_GROUP )); - EXPECT_STREQ("message", GetCppTypeNameForFieldType(FD::TYPE_MESSAGE )); - EXPECT_STREQ("string" , GetCppTypeNameForFieldType(FD::TYPE_BYTES )); - EXPECT_STREQ("uint32" , GetCppTypeNameForFieldType(FD::TYPE_UINT32 )); - EXPECT_STREQ("enum" , GetCppTypeNameForFieldType(FD::TYPE_ENUM )); - EXPECT_STREQ("int32" , GetCppTypeNameForFieldType(FD::TYPE_SFIXED32)); - EXPECT_STREQ("int64" , GetCppTypeNameForFieldType(FD::TYPE_SFIXED64)); - EXPECT_STREQ("int32" , GetCppTypeNameForFieldType(FD::TYPE_SINT32 )); - EXPECT_STREQ("int64" , GetCppTypeNameForFieldType(FD::TYPE_SINT64 )); + EXPECT_STREQ("double", GetCppTypeNameForFieldType(FD::TYPE_DOUBLE)); + EXPECT_STREQ("float", GetCppTypeNameForFieldType(FD::TYPE_FLOAT)); + EXPECT_STREQ("int64", GetCppTypeNameForFieldType(FD::TYPE_INT64)); + EXPECT_STREQ("uint64", GetCppTypeNameForFieldType(FD::TYPE_UINT64)); + EXPECT_STREQ("int32", GetCppTypeNameForFieldType(FD::TYPE_INT32)); + EXPECT_STREQ("uint64", GetCppTypeNameForFieldType(FD::TYPE_FIXED64)); + EXPECT_STREQ("uint32", GetCppTypeNameForFieldType(FD::TYPE_FIXED32)); + EXPECT_STREQ("bool", GetCppTypeNameForFieldType(FD::TYPE_BOOL)); + EXPECT_STREQ("string", GetCppTypeNameForFieldType(FD::TYPE_STRING)); + EXPECT_STREQ("message", GetCppTypeNameForFieldType(FD::TYPE_GROUP)); + EXPECT_STREQ("message", GetCppTypeNameForFieldType(FD::TYPE_MESSAGE)); + EXPECT_STREQ("string", GetCppTypeNameForFieldType(FD::TYPE_BYTES)); + EXPECT_STREQ("uint32", GetCppTypeNameForFieldType(FD::TYPE_UINT32)); + EXPECT_STREQ("enum", GetCppTypeNameForFieldType(FD::TYPE_ENUM)); + EXPECT_STREQ("int32", GetCppTypeNameForFieldType(FD::TYPE_SFIXED32)); + EXPECT_STREQ("int64", GetCppTypeNameForFieldType(FD::TYPE_SFIXED64)); + EXPECT_STREQ("int32", GetCppTypeNameForFieldType(FD::TYPE_SINT32)); + EXPECT_STREQ("int64", GetCppTypeNameForFieldType(FD::TYPE_SINT64)); } TEST_F(MiscTest, StaticCppTypeNames) { @@ -2357,15 +2372,15 @@ TEST_F(MiscTest, StaticCppTypeNames) { typedef FieldDescriptor FD; // avoid ugly line wrapping - EXPECT_STREQ("int32" , FD::CppTypeName(FD::CPPTYPE_INT32 )); - EXPECT_STREQ("int64" , FD::CppTypeName(FD::CPPTYPE_INT64 )); - EXPECT_STREQ("uint32" , FD::CppTypeName(FD::CPPTYPE_UINT32 )); - EXPECT_STREQ("uint64" , FD::CppTypeName(FD::CPPTYPE_UINT64 )); - EXPECT_STREQ("double" , FD::CppTypeName(FD::CPPTYPE_DOUBLE )); - EXPECT_STREQ("float" , FD::CppTypeName(FD::CPPTYPE_FLOAT )); - EXPECT_STREQ("bool" , FD::CppTypeName(FD::CPPTYPE_BOOL )); - EXPECT_STREQ("enum" , FD::CppTypeName(FD::CPPTYPE_ENUM )); - EXPECT_STREQ("string" , FD::CppTypeName(FD::CPPTYPE_STRING )); + EXPECT_STREQ("int32", FD::CppTypeName(FD::CPPTYPE_INT32)); + EXPECT_STREQ("int64", FD::CppTypeName(FD::CPPTYPE_INT64)); + EXPECT_STREQ("uint32", FD::CppTypeName(FD::CPPTYPE_UINT32)); + EXPECT_STREQ("uint64", FD::CppTypeName(FD::CPPTYPE_UINT64)); + EXPECT_STREQ("double", FD::CppTypeName(FD::CPPTYPE_DOUBLE)); + EXPECT_STREQ("float", FD::CppTypeName(FD::CPPTYPE_FLOAT)); + EXPECT_STREQ("bool", FD::CppTypeName(FD::CPPTYPE_BOOL)); + EXPECT_STREQ("enum", FD::CppTypeName(FD::CPPTYPE_ENUM)); + EXPECT_STREQ("string", FD::CppTypeName(FD::CPPTYPE_STRING)); EXPECT_STREQ("message", FD::CppTypeName(FD::CPPTYPE_MESSAGE)); } @@ -2374,24 +2389,24 @@ TEST_F(MiscTest, MessageType) { typedef FieldDescriptor FD; // avoid ugly line wrapping - EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_DOUBLE )); - EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_FLOAT )); - EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_INT64 )); - EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_UINT64 )); - EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_INT32 )); - EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_FIXED64 )); - EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_FIXED32 )); - EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_BOOL )); - EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_STRING )); - EXPECT_TRUE(NULL != GetMessageDescriptorForFieldType(FD::TYPE_GROUP )); - EXPECT_TRUE(NULL != GetMessageDescriptorForFieldType(FD::TYPE_MESSAGE )); - EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_BYTES )); - EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_UINT32 )); - EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_ENUM )); + EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_DOUBLE)); + EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_FLOAT)); + EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_INT64)); + EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_UINT64)); + EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_INT32)); + EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_FIXED64)); + EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_FIXED32)); + EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_BOOL)); + EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_STRING)); + EXPECT_TRUE(NULL != GetMessageDescriptorForFieldType(FD::TYPE_GROUP)); + EXPECT_TRUE(NULL != GetMessageDescriptorForFieldType(FD::TYPE_MESSAGE)); + EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_BYTES)); + EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_UINT32)); + EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_ENUM)); EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_SFIXED32)); EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_SFIXED64)); - EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_SINT32 )); - EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_SINT64 )); + EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_SINT32)); + EXPECT_TRUE(NULL == GetMessageDescriptorForFieldType(FD::TYPE_SINT64)); } TEST_F(MiscTest, EnumType) { @@ -2399,27 +2414,26 @@ TEST_F(MiscTest, EnumType) { typedef FieldDescriptor FD; // avoid ugly line wrapping - EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_DOUBLE )); - EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_FLOAT )); - EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_INT64 )); - EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_UINT64 )); - EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_INT32 )); - EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_FIXED64 )); - EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_FIXED32 )); - EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_BOOL )); - EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_STRING )); - EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_GROUP )); - EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_MESSAGE )); - EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_BYTES )); - EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_UINT32 )); - EXPECT_TRUE(NULL != GetEnumDescriptorForFieldType(FD::TYPE_ENUM )); + EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_DOUBLE)); + EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_FLOAT)); + EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_INT64)); + EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_UINT64)); + EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_INT32)); + EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_FIXED64)); + EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_FIXED32)); + EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_BOOL)); + EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_STRING)); + EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_GROUP)); + EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_MESSAGE)); + EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_BYTES)); + EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_UINT32)); + EXPECT_TRUE(NULL != GetEnumDescriptorForFieldType(FD::TYPE_ENUM)); EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_SFIXED32)); EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_SFIXED64)); - EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_SINT32 )); - EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_SINT64 )); + EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_SINT32)); + EXPECT_TRUE(NULL == GetEnumDescriptorForFieldType(FD::TYPE_SINT64)); } - TEST_F(MiscTest, DefaultValues) { // Test that setting default values works. FileDescriptorProto file_proto; @@ -2435,47 +2449,47 @@ TEST_F(MiscTest, DefaultValues) { const FD::Label label = FD::LABEL_OPTIONAL; // Create fields of every CPP type with default values. - AddField(message_proto, "int32" , 1, label, FD::TYPE_INT32 ) - ->set_default_value("-1"); - AddField(message_proto, "int64" , 2, label, FD::TYPE_INT64 ) - ->set_default_value("-1000000000000"); + AddField(message_proto, "int32", 1, label, FD::TYPE_INT32) + ->set_default_value("-1"); + AddField(message_proto, "int64", 2, label, FD::TYPE_INT64) + ->set_default_value("-1000000000000"); AddField(message_proto, "uint32", 3, label, FD::TYPE_UINT32) - ->set_default_value("42"); + ->set_default_value("42"); AddField(message_proto, "uint64", 4, label, FD::TYPE_UINT64) - ->set_default_value("2000000000000"); - AddField(message_proto, "float" , 5, label, FD::TYPE_FLOAT ) - ->set_default_value("4.5"); + ->set_default_value("2000000000000"); + AddField(message_proto, "float", 5, label, FD::TYPE_FLOAT) + ->set_default_value("4.5"); AddField(message_proto, "double", 6, label, FD::TYPE_DOUBLE) - ->set_default_value("10e100"); - AddField(message_proto, "bool" , 7, label, FD::TYPE_BOOL ) - ->set_default_value("true"); + ->set_default_value("10e100"); + AddField(message_proto, "bool", 7, label, FD::TYPE_BOOL) + ->set_default_value("true"); AddField(message_proto, "string", 8, label, FD::TYPE_STRING) - ->set_default_value("hello"); - AddField(message_proto, "data" , 9, label, FD::TYPE_BYTES ) - ->set_default_value("\\001\\002\\003"); + ->set_default_value("hello"); + AddField(message_proto, "data", 9, label, FD::TYPE_BYTES) + ->set_default_value("\\001\\002\\003"); FieldDescriptorProto* enum_field = - AddField(message_proto, "enum", 10, label, FD::TYPE_ENUM); + AddField(message_proto, "enum", 10, label, FD::TYPE_ENUM); enum_field->set_type_name("DummyEnum"); enum_field->set_default_value("B"); // Strings are allowed to have empty defaults. (At one point, due to // a bug, empty defaults for strings were rejected. Oops.) AddField(message_proto, "empty_string", 11, label, FD::TYPE_STRING) - ->set_default_value(""); + ->set_default_value(""); // Add a second set of fields with implicit defalut values. - AddField(message_proto, "implicit_int32" , 21, label, FD::TYPE_INT32 ); - AddField(message_proto, "implicit_int64" , 22, label, FD::TYPE_INT64 ); + AddField(message_proto, "implicit_int32", 21, label, FD::TYPE_INT32); + AddField(message_proto, "implicit_int64", 22, label, FD::TYPE_INT64); AddField(message_proto, "implicit_uint32", 23, label, FD::TYPE_UINT32); AddField(message_proto, "implicit_uint64", 24, label, FD::TYPE_UINT64); - AddField(message_proto, "implicit_float" , 25, label, FD::TYPE_FLOAT ); + AddField(message_proto, "implicit_float", 25, label, FD::TYPE_FLOAT); AddField(message_proto, "implicit_double", 26, label, FD::TYPE_DOUBLE); - AddField(message_proto, "implicit_bool" , 27, label, FD::TYPE_BOOL ); + AddField(message_proto, "implicit_bool", 27, label, FD::TYPE_BOOL); AddField(message_proto, "implicit_string", 28, label, FD::TYPE_STRING); - AddField(message_proto, "implicit_data" , 29, label, FD::TYPE_BYTES ); - AddField(message_proto, "implicit_enum" , 30, label, FD::TYPE_ENUM) - ->set_type_name("DummyEnum"); + AddField(message_proto, "implicit_data", 29, label, FD::TYPE_BYTES); + AddField(message_proto, "implicit_enum", 30, label, FD::TYPE_ENUM) + ->set_type_name("DummyEnum"); // Build it. DescriptorPool pool; @@ -2506,19 +2520,19 @@ TEST_F(MiscTest, DefaultValues) { ASSERT_TRUE(message->field(9)->has_default_value()); ASSERT_TRUE(message->field(10)->has_default_value()); - EXPECT_EQ(-1 , message->field(0)->default_value_int32 ()); - EXPECT_EQ(-GOOGLE_ULONGLONG(1000000000000), - message->field(1)->default_value_int64 ()); - EXPECT_EQ(42 , message->field(2)->default_value_uint32()); - EXPECT_EQ(GOOGLE_ULONGLONG(2000000000000), + EXPECT_EQ(-1, message->field(0)->default_value_int32()); + EXPECT_EQ(-PROTOBUF_ULONGLONG(1000000000000), + message->field(1)->default_value_int64()); + EXPECT_EQ(42, message->field(2)->default_value_uint32()); + EXPECT_EQ(PROTOBUF_ULONGLONG(2000000000000), message->field(3)->default_value_uint64()); - EXPECT_EQ(4.5 , message->field(4)->default_value_float ()); - EXPECT_EQ(10e100 , message->field(5)->default_value_double()); - EXPECT_TRUE( message->field(6)->default_value_bool ()); - EXPECT_EQ("hello" , message->field(7)->default_value_string()); - EXPECT_EQ("\001\002\003" , message->field(8)->default_value_string()); - EXPECT_EQ(enum_value_b , message->field(9)->default_value_enum ()); - EXPECT_EQ("" , message->field(10)->default_value_string()); + EXPECT_EQ(4.5, message->field(4)->default_value_float()); + EXPECT_EQ(10e100, message->field(5)->default_value_double()); + EXPECT_TRUE(message->field(6)->default_value_bool()); + EXPECT_EQ("hello", message->field(7)->default_value_string()); + EXPECT_EQ("\001\002\003", message->field(8)->default_value_string()); + EXPECT_EQ(enum_value_b, message->field(9)->default_value_enum()); + EXPECT_EQ("", message->field(10)->default_value_string()); ASSERT_FALSE(message->field(11)->has_default_value()); ASSERT_FALSE(message->field(12)->has_default_value()); @@ -2531,15 +2545,15 @@ TEST_F(MiscTest, DefaultValues) { ASSERT_FALSE(message->field(19)->has_default_value()); ASSERT_FALSE(message->field(20)->has_default_value()); - EXPECT_EQ(0 , message->field(11)->default_value_int32 ()); - EXPECT_EQ(0 , message->field(12)->default_value_int64 ()); - EXPECT_EQ(0 , message->field(13)->default_value_uint32()); - EXPECT_EQ(0 , message->field(14)->default_value_uint64()); - EXPECT_EQ(0.0f , message->field(15)->default_value_float ()); - EXPECT_EQ(0.0 , message->field(16)->default_value_double()); - EXPECT_FALSE( message->field(17)->default_value_bool ()); - EXPECT_EQ("" , message->field(18)->default_value_string()); - EXPECT_EQ("" , message->field(19)->default_value_string()); + EXPECT_EQ(0, message->field(11)->default_value_int32()); + EXPECT_EQ(0, message->field(12)->default_value_int64()); + EXPECT_EQ(0, message->field(13)->default_value_uint32()); + EXPECT_EQ(0, message->field(14)->default_value_uint64()); + EXPECT_EQ(0.0f, message->field(15)->default_value_float()); + EXPECT_EQ(0.0, message->field(16)->default_value_double()); + EXPECT_FALSE(message->field(17)->default_value_bool()); + EXPECT_EQ("", message->field(18)->default_value_string()); + EXPECT_EQ("", message->field(19)->default_value_string()); EXPECT_EQ(enum_value_a, message->field(20)->default_value_enum()); } @@ -2550,13 +2564,11 @@ TEST_F(MiscTest, FieldOptions) { file_proto.set_name("foo.proto"); DescriptorProto* message_proto = AddMessage(&file_proto, "TestMessage"); - AddField(message_proto, "foo", 1, - FieldDescriptorProto::LABEL_OPTIONAL, + AddField(message_proto, "foo", 1, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_INT32); FieldDescriptorProto* bar_proto = - AddField(message_proto, "bar", 2, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); + AddField(message_proto, "bar", 2, FieldDescriptorProto::LABEL_OPTIONAL, + FieldDescriptorProto::TYPE_INT32); FieldOptions* options = bar_proto->mutable_options(); options->set_ctype(FieldOptions::CORD); @@ -2583,17 +2595,12 @@ TEST_F(MiscTest, FieldOptions) { } // =================================================================== -enum DescriptorPoolMode { - NO_DATABASE, - FALLBACK_DATABASE -}; +enum DescriptorPoolMode { NO_DATABASE, FALLBACK_DATABASE }; class AllowUnknownDependenciesTest : public testing::TestWithParam { protected: - DescriptorPoolMode mode() { - return GetParam(); - } + DescriptorPoolMode mode() { return GetParam(); } virtual void SetUp() { FileDescriptorProto foo_proto, bar_proto; @@ -2610,32 +2617,32 @@ class AllowUnknownDependenciesTest pool_->AllowUnknownDependencies(); ASSERT_TRUE(TextFormat::ParseFromString( - "name: 'foo.proto'" - "dependency: 'bar.proto'" - "dependency: 'baz.proto'" - "message_type {" - " name: 'Foo'" - " field { name:'bar' number:1 label:LABEL_OPTIONAL type_name:'Bar' }" - " field { name:'baz' number:2 label:LABEL_OPTIONAL type_name:'Baz' }" - " field { name:'qux' number:3 label:LABEL_OPTIONAL" - " type_name: '.corge.Qux'" - " type: TYPE_ENUM" - " options {" - " uninterpreted_option {" - " name {" - " name_part: 'grault'" - " is_extension: true" - " }" - " positive_int_value: 1234" - " }" - " }" - " }" - "}", - &foo_proto)); - ASSERT_TRUE(TextFormat::ParseFromString( - "name: 'bar.proto'" - "message_type { name: 'Bar' }", - &bar_proto)); + "name: 'foo.proto'" + "dependency: 'bar.proto'" + "dependency: 'baz.proto'" + "message_type {" + " name: 'Foo'" + " field { name:'bar' number:1 label:LABEL_OPTIONAL type_name:'Bar' }" + " field { name:'baz' number:2 label:LABEL_OPTIONAL type_name:'Baz' }" + " field { name:'qux' number:3 label:LABEL_OPTIONAL" + " type_name: '.corge.Qux'" + " type: TYPE_ENUM" + " options {" + " uninterpreted_option {" + " name {" + " name_part: 'grault'" + " is_extension: true" + " }" + " positive_int_value: 1234" + " }" + " }" + " }" + "}", + &foo_proto)); + ASSERT_TRUE( + TextFormat::ParseFromString("name: 'bar.proto'" + "message_type { name: 'Bar' }", + &bar_proto)); // Collect pointers to stuff. bar_file_ = BuildFile(bar_proto); @@ -2678,7 +2685,7 @@ class AllowUnknownDependenciesTest const FieldDescriptor* baz_field_; const FieldDescriptor* qux_field_; - SimpleDescriptorDatabase db_; // used if in FALLBACK_DATABASE mode. + SimpleDescriptorDatabase db_; // used if in FALLBACK_DATABASE mode. std::unique_ptr pool_; }; @@ -2754,7 +2761,7 @@ TEST_P(AllowUnknownDependenciesTest, CustomOptions) { // Qux should still have the uninterpreted option attached. ASSERT_EQ(1, qux_field_->options().uninterpreted_option_size()); const UninterpretedOption& option = - qux_field_->options().uninterpreted_option(0); + qux_field_->options().uninterpreted_option(0); ASSERT_EQ(1, option.name_size()); EXPECT_EQ("grault", option.name(0).name_part()); } @@ -2766,10 +2773,10 @@ TEST_P(AllowUnknownDependenciesTest, UnknownExtendee) { FileDescriptorProto extension_proto; ASSERT_TRUE(TextFormat::ParseFromString( - "name: 'extension.proto'" - "extension { extendee: 'UnknownType' name:'some_extension' number:123" - " label:LABEL_OPTIONAL type:TYPE_INT32 }", - &extension_proto)); + "name: 'extension.proto'" + "extension { extendee: 'UnknownType' name:'some_extension' number:123" + " label:LABEL_OPTIONAL type:TYPE_INT32 }", + &extension_proto)); const FileDescriptor* file = BuildFile(extension_proto); ASSERT_TRUE(file != NULL); @@ -2790,39 +2797,39 @@ TEST_P(AllowUnknownDependenciesTest, CustomOption) { FileDescriptorProto option_proto; ASSERT_TRUE(TextFormat::ParseFromString( - "name: \"unknown_custom_options.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { " - " extendee: \"google.protobuf.FileOptions\" " - " name: \"some_option\" " - " number: 123456 " - " label: LABEL_OPTIONAL " - " type: TYPE_INT32 " - "} " - "options { " - " uninterpreted_option { " - " name { " - " name_part: \"some_option\" " - " is_extension: true " - " } " - " positive_int_value: 1234 " - " } " - " uninterpreted_option { " - " name { " - " name_part: \"unknown_option\" " - " is_extension: true " - " } " - " positive_int_value: 1234 " - " } " - " uninterpreted_option { " - " name { " - " name_part: \"optimize_for\" " - " is_extension: false " - " } " - " identifier_value: \"SPEED\" " - " } " - "}", - &option_proto)); + "name: \"unknown_custom_options.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "extension { " + " extendee: \"google.protobuf.FileOptions\" " + " name: \"some_option\" " + " number: 123456 " + " label: LABEL_OPTIONAL " + " type: TYPE_INT32 " + "} " + "options { " + " uninterpreted_option { " + " name { " + " name_part: \"some_option\" " + " is_extension: true " + " } " + " positive_int_value: 1234 " + " } " + " uninterpreted_option { " + " name { " + " name_part: \"unknown_option\" " + " is_extension: true " + " } " + " positive_int_value: 1234 " + " } " + " uninterpreted_option { " + " name { " + " name_part: \"optimize_for\" " + " is_extension: false " + " } " + " identifier_value: \"SPEED\" " + " } " + "}", + &option_proto)); const FileDescriptor* file = BuildFile(option_proto); ASSERT_TRUE(file != NULL); @@ -2849,18 +2856,18 @@ TEST_P(AllowUnknownDependenciesTest, FileDescriptorProto undeclared_dep_proto; // We make this file fail to build by giving it two fields with tag 1. ASSERT_TRUE(TextFormat::ParseFromString( - "name: \"invalid_file_as_undeclared_dep.proto\" " - "package: \"undeclared\" " - "message_type: { " - " name: \"Quux\" " - " field { " - " name:'qux' number:1 label:LABEL_OPTIONAL type: TYPE_INT32 " - " }" - " field { " - " name:'quux' number:1 label:LABEL_OPTIONAL type: TYPE_INT64 " - " }" - "}", - &undeclared_dep_proto)); + "name: \"invalid_file_as_undeclared_dep.proto\" " + "package: \"undeclared\" " + "message_type: { " + " name: \"Quux\" " + " field { " + " name:'qux' number:1 label:LABEL_OPTIONAL type: TYPE_INT32 " + " }" + " field { " + " name:'quux' number:1 label:LABEL_OPTIONAL type: TYPE_INT64 " + " }" + "}", + &undeclared_dep_proto)); // We can't use the BuildFile() helper because we don't actually want to build // it into the descriptor pool in the fallback database case: it just needs to // be sitting in the database so that it gets built during the building of @@ -2877,15 +2884,15 @@ TEST_P(AllowUnknownDependenciesTest, FileDescriptorProto test_proto; ASSERT_TRUE(TextFormat::ParseFromString( - "name: \"test.proto\" " - "message_type: { " - " name: \"Corge\" " - " field { " - " name:'quux' number:1 label: LABEL_OPTIONAL " - " type_name:'undeclared.Quux' type: TYPE_MESSAGE " - " }" - "}", - &test_proto)); + "name: \"test.proto\" " + "message_type: { " + " name: \"Corge\" " + " field { " + " name:'quux' number:1 label: LABEL_OPTIONAL " + " type_name:'undeclared.Quux' type: TYPE_MESSAGE " + " }" + "}", + &test_proto)); const FileDescriptor* file = BuildFile(test_proto); ASSERT_TRUE(file != NULL); @@ -2907,9 +2914,8 @@ TEST_P(AllowUnknownDependenciesTest, ASSERT_TRUE(pool_->FindMessageTypeByName("undeclared.Quux") == NULL); } -INSTANTIATE_TEST_CASE_P(DatabaseSource, - AllowUnknownDependenciesTest, - testing::Values(NO_DATABASE, FALLBACK_DATABASE)); +INSTANTIATE_TEST_SUITE_P(DatabaseSource, AllowUnknownDependenciesTest, + testing::Values(NO_DATABASE, FALLBACK_DATABASE)); // =================================================================== @@ -2925,22 +2931,19 @@ TEST(CustomOptions, OptionLocations) { file->FindServiceByName("TestServiceWithCustomOptions"); const MethodDescriptor* method = service->FindMethodByName("Foo"); - EXPECT_EQ(GOOGLE_LONGLONG(9876543210), + EXPECT_EQ(PROTOBUF_LONGLONG(9876543210), file->options().GetExtension(protobuf_unittest::file_opt1)); EXPECT_EQ(-56, message->options().GetExtension(protobuf_unittest::message_opt1)); - EXPECT_EQ(GOOGLE_LONGLONG(8765432109), + EXPECT_EQ(PROTOBUF_LONGLONG(8765432109), field->options().GetExtension(protobuf_unittest::field_opt1)); EXPECT_EQ(42, // Check that we get the default for an option we don't set. field->options().GetExtension(protobuf_unittest::field_opt2)); - EXPECT_EQ(-99, - oneof->options().GetExtension(protobuf_unittest::oneof_opt1)); - EXPECT_EQ(-789, - enm->options().GetExtension(protobuf_unittest::enum_opt1)); - EXPECT_EQ(123, - enm->value(1)->options().GetExtension( - protobuf_unittest::enum_value_opt1)); - EXPECT_EQ(GOOGLE_LONGLONG(-9876543210), + EXPECT_EQ(-99, oneof->options().GetExtension(protobuf_unittest::oneof_opt1)); + EXPECT_EQ(-789, enm->options().GetExtension(protobuf_unittest::enum_opt1)); + EXPECT_EQ(123, enm->value(1)->options().GetExtension( + protobuf_unittest::enum_value_opt1)); + EXPECT_EQ(PROTOBUF_LONGLONG(-9876543210), service->options().GetExtension(protobuf_unittest::service_opt1)); EXPECT_EQ(protobuf_unittest::METHODOPT1_VAL2, method->options().GetExtension(protobuf_unittest::method_opt1)); @@ -2955,34 +2958,33 @@ TEST(CustomOptions, OptionTypes) { options = &protobuf_unittest::CustomOptionMinIntegerValues::descriptor()->options(); - EXPECT_EQ(false , options->GetExtension(protobuf_unittest::bool_opt)); + EXPECT_EQ(false, options->GetExtension(protobuf_unittest::bool_opt)); EXPECT_EQ(kint32min, options->GetExtension(protobuf_unittest::int32_opt)); EXPECT_EQ(kint64min, options->GetExtension(protobuf_unittest::int64_opt)); - EXPECT_EQ(0 , options->GetExtension(protobuf_unittest::uint32_opt)); - EXPECT_EQ(0 , options->GetExtension(protobuf_unittest::uint64_opt)); + EXPECT_EQ(0, options->GetExtension(protobuf_unittest::uint32_opt)); + EXPECT_EQ(0, options->GetExtension(protobuf_unittest::uint64_opt)); EXPECT_EQ(kint32min, options->GetExtension(protobuf_unittest::sint32_opt)); EXPECT_EQ(kint64min, options->GetExtension(protobuf_unittest::sint64_opt)); - EXPECT_EQ(0 , options->GetExtension(protobuf_unittest::fixed32_opt)); - EXPECT_EQ(0 , options->GetExtension(protobuf_unittest::fixed64_opt)); + EXPECT_EQ(0, options->GetExtension(protobuf_unittest::fixed32_opt)); + EXPECT_EQ(0, options->GetExtension(protobuf_unittest::fixed64_opt)); EXPECT_EQ(kint32min, options->GetExtension(protobuf_unittest::sfixed32_opt)); EXPECT_EQ(kint64min, options->GetExtension(protobuf_unittest::sfixed64_opt)); options = &protobuf_unittest::CustomOptionMaxIntegerValues::descriptor()->options(); - EXPECT_EQ(true , options->GetExtension(protobuf_unittest::bool_opt)); - EXPECT_EQ(kint32max , options->GetExtension(protobuf_unittest::int32_opt)); - EXPECT_EQ(kint64max , options->GetExtension(protobuf_unittest::int64_opt)); + EXPECT_EQ(true, options->GetExtension(protobuf_unittest::bool_opt)); + EXPECT_EQ(kint32max, options->GetExtension(protobuf_unittest::int32_opt)); + EXPECT_EQ(kint64max, options->GetExtension(protobuf_unittest::int64_opt)); EXPECT_EQ(kuint32max, options->GetExtension(protobuf_unittest::uint32_opt)); EXPECT_EQ(kuint64max, options->GetExtension(protobuf_unittest::uint64_opt)); - EXPECT_EQ(kint32max , options->GetExtension(protobuf_unittest::sint32_opt)); - EXPECT_EQ(kint64max , options->GetExtension(protobuf_unittest::sint64_opt)); + EXPECT_EQ(kint32max, options->GetExtension(protobuf_unittest::sint32_opt)); + EXPECT_EQ(kint64max, options->GetExtension(protobuf_unittest::sint64_opt)); EXPECT_EQ(kuint32max, options->GetExtension(protobuf_unittest::fixed32_opt)); EXPECT_EQ(kuint64max, options->GetExtension(protobuf_unittest::fixed64_opt)); - EXPECT_EQ(kint32max , options->GetExtension(protobuf_unittest::sfixed32_opt)); - EXPECT_EQ(kint64max , options->GetExtension(protobuf_unittest::sfixed64_opt)); + EXPECT_EQ(kint32max, options->GetExtension(protobuf_unittest::sfixed32_opt)); + EXPECT_EQ(kint64max, options->GetExtension(protobuf_unittest::sfixed64_opt)); - options = - &protobuf_unittest::CustomOptionOtherValues::descriptor()->options(); + options = &protobuf_unittest::CustomOptionOtherValues::descriptor()->options(); EXPECT_EQ(-100, options->GetExtension(protobuf_unittest::int32_opt)); EXPECT_FLOAT_EQ(12.3456789, options->GetExtension(protobuf_unittest::float_opt)); @@ -2991,7 +2993,7 @@ TEST(CustomOptions, OptionTypes) { EXPECT_EQ("Hello, \"World\"", options->GetExtension(protobuf_unittest::string_opt)); - EXPECT_EQ(string("Hello\0World", 11), + EXPECT_EQ(std::string("Hello\0World", 11), options->GetExtension(protobuf_unittest::bytes_opt)); EXPECT_EQ(protobuf_unittest::DummyMessageContainingEnum::TEST_OPTION_ENUM_TYPE2, @@ -3012,35 +3014,52 @@ TEST(CustomOptions, ComplexExtensionOptions) { const MessageOptions* options = &protobuf_unittest::VariousComplexOptions::descriptor()->options(); EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt1).foo(), 42); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt1). - GetExtension(protobuf_unittest::quux), 324); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt1). - GetExtension(protobuf_unittest::corge).qux(), 876); + EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt1) + .GetExtension(protobuf_unittest::quux), + 324); + EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt1) + .GetExtension(protobuf_unittest::corge) + .qux(), + 876); EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2).baz(), 987); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2). - GetExtension(protobuf_unittest::grault), 654); + EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2) + .GetExtension(protobuf_unittest::grault), + 654); EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2).bar().foo(), 743); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2).bar(). - GetExtension(protobuf_unittest::quux), 1999); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2).bar(). - GetExtension(protobuf_unittest::corge).qux(), 2008); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2). - GetExtension(protobuf_unittest::garply).foo(), 741); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2). - GetExtension(protobuf_unittest::garply). - GetExtension(protobuf_unittest::quux), 1998); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2). - GetExtension(protobuf_unittest::garply). - GetExtension(protobuf_unittest::corge).qux(), 2121); - EXPECT_EQ(options->GetExtension( - protobuf_unittest::ComplexOptionType2::ComplexOptionType4::complex_opt4). - waldo(), 1971); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2). - fred().waldo(), 321); + EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2) + .bar() + .GetExtension(protobuf_unittest::quux), + 1999); + EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2) + .bar() + .GetExtension(protobuf_unittest::corge) + .qux(), + 2008); + EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2) + .GetExtension(protobuf_unittest::garply) + .foo(), + 741); + EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2) + .GetExtension(protobuf_unittest::garply) + .GetExtension(protobuf_unittest::quux), + 1998); + EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2) + .GetExtension(protobuf_unittest::garply) + .GetExtension(protobuf_unittest::corge) + .qux(), + 2121); + EXPECT_EQ(options + ->GetExtension(protobuf_unittest::ComplexOptionType2:: + ComplexOptionType4::complex_opt4) + .waldo(), + 1971); + EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2).fred().waldo(), + 321); EXPECT_EQ(9, options->GetExtension(protobuf_unittest::complex_opt3).qux()); - EXPECT_EQ(22, options->GetExtension(protobuf_unittest::complex_opt3). - complexoptiontype5().plugh()); + EXPECT_EQ(22, options->GetExtension(protobuf_unittest::complex_opt3) + .complexoptiontype5() + .plugh()); EXPECT_EQ(24, options->GetExtension(protobuf_unittest::complexopt6).xyzzy()); } @@ -3053,43 +3072,42 @@ TEST(CustomOptions, OptionsFromOtherFile) { FileDescriptorProto::descriptor()->file()->CopyTo(&file_proto); ASSERT_TRUE(pool.BuildFile(file_proto) != NULL); - protobuf_unittest::TestMessageWithCustomOptions::descriptor() - ->file()->CopyTo(&file_proto); + protobuf_unittest::TestMessageWithCustomOptions::descriptor()->file()->CopyTo( + &file_proto); ASSERT_TRUE(pool.BuildFile(file_proto) != NULL); ASSERT_TRUE(TextFormat::ParseFromString( - "name: \"custom_options_import.proto\" " - "package: \"protobuf_unittest\" " - "dependency: \"google/protobuf/unittest_custom_options.proto\" " - "options { " - " uninterpreted_option { " - " name { " - " name_part: \"file_opt1\" " - " is_extension: true " - " } " - " positive_int_value: 1234 " - " } " - // Test a non-extension option too. (At one point this failed due to a - // bug.) - " uninterpreted_option { " - " name { " - " name_part: \"java_package\" " - " is_extension: false " - " } " - " string_value: \"foo\" " - " } " - // Test that enum-typed options still work too. (At one point this also - // failed due to a bug.) - " uninterpreted_option { " - " name { " - " name_part: \"optimize_for\" " - " is_extension: false " - " } " - " identifier_value: \"SPEED\" " - " } " - "}" - , - &file_proto)); + "name: \"custom_options_import.proto\" " + "package: \"protobuf_unittest\" " + "dependency: \"google/protobuf/unittest_custom_options.proto\" " + "options { " + " uninterpreted_option { " + " name { " + " name_part: \"file_opt1\" " + " is_extension: true " + " } " + " positive_int_value: 1234 " + " } " + // Test a non-extension option too. (At one point this failed due to a + // bug.) + " uninterpreted_option { " + " name { " + " name_part: \"java_package\" " + " is_extension: false " + " } " + " string_value: \"foo\" " + " } " + // Test that enum-typed options still work too. (At one point this also + // failed due to a bug.) + " uninterpreted_option { " + " name { " + " name_part: \"optimize_for\" " + " is_extension: false " + " } " + " identifier_value: \"SPEED\" " + " } " + "}", + &file_proto)); const FileDescriptor* file = pool.BuildFile(file_proto); ASSERT_TRUE(file != NULL); @@ -3112,8 +3130,8 @@ TEST(CustomOptions, MessageOptionThreeFieldsSet) { FileDescriptorProto::descriptor()->file()->CopyTo(&file_proto); ASSERT_TRUE(pool.BuildFile(file_proto) != NULL); - protobuf_unittest::TestMessageWithCustomOptions::descriptor() - ->file()->CopyTo(&file_proto); + protobuf_unittest::TestMessageWithCustomOptions::descriptor()->file()->CopyTo( + &file_proto); ASSERT_TRUE(pool.BuildFile(file_proto) != NULL); // The following represents the definition: @@ -3126,48 +3144,48 @@ TEST(CustomOptions, MessageOptionThreeFieldsSet) { // option (complex_opt1).foo3 = 1234; // } ASSERT_TRUE(TextFormat::ParseFromString( - "name: \"custom_options_import.proto\" " - "package: \"protobuf_unittest\" " - "dependency: \"google/protobuf/unittest_custom_options.proto\" " - "message_type { " - " name: \"Foo\" " - " options { " - " uninterpreted_option { " - " name { " - " name_part: \"complex_opt1\" " - " is_extension: true " - " } " - " name { " - " name_part: \"foo\" " - " is_extension: false " - " } " - " positive_int_value: 1234 " - " } " - " uninterpreted_option { " - " name { " - " name_part: \"complex_opt1\" " - " is_extension: true " - " } " - " name { " - " name_part: \"foo2\" " - " is_extension: false " - " } " - " positive_int_value: 1234 " - " } " - " uninterpreted_option { " - " name { " - " name_part: \"complex_opt1\" " - " is_extension: true " - " } " - " name { " - " name_part: \"foo3\" " - " is_extension: false " - " } " - " positive_int_value: 1234 " - " } " - " } " - "}", - &file_proto)); + "name: \"custom_options_import.proto\" " + "package: \"protobuf_unittest\" " + "dependency: \"google/protobuf/unittest_custom_options.proto\" " + "message_type { " + " name: \"Foo\" " + " options { " + " uninterpreted_option { " + " name { " + " name_part: \"complex_opt1\" " + " is_extension: true " + " } " + " name { " + " name_part: \"foo\" " + " is_extension: false " + " } " + " positive_int_value: 1234 " + " } " + " uninterpreted_option { " + " name { " + " name_part: \"complex_opt1\" " + " is_extension: true " + " } " + " name { " + " name_part: \"foo2\" " + " is_extension: false " + " } " + " positive_int_value: 1234 " + " } " + " uninterpreted_option { " + " name { " + " name_part: \"complex_opt1\" " + " is_extension: true " + " } " + " name { " + " name_part: \"foo3\" " + " is_extension: false " + " } " + " positive_int_value: 1234 " + " } " + " } " + "}", + &file_proto)); const FileDescriptor* file = pool.BuildFile(file_proto); ASSERT_TRUE(file != NULL); @@ -3189,8 +3207,8 @@ TEST(CustomOptions, MessageOptionRepeatedLeafFieldSet) { FileDescriptorProto::descriptor()->file()->CopyTo(&file_proto); ASSERT_TRUE(pool.BuildFile(file_proto) != NULL); - protobuf_unittest::TestMessageWithCustomOptions::descriptor() - ->file()->CopyTo(&file_proto); + protobuf_unittest::TestMessageWithCustomOptions::descriptor()->file()->CopyTo( + &file_proto); ASSERT_TRUE(pool.BuildFile(file_proto) != NULL); // The following represents the definition: @@ -3203,48 +3221,48 @@ TEST(CustomOptions, MessageOptionRepeatedLeafFieldSet) { // option (complex_opt1).foo4 = 56; // } ASSERT_TRUE(TextFormat::ParseFromString( - "name: \"custom_options_import.proto\" " - "package: \"protobuf_unittest\" " - "dependency: \"google/protobuf/unittest_custom_options.proto\" " - "message_type { " - " name: \"Foo\" " - " options { " - " uninterpreted_option { " - " name { " - " name_part: \"complex_opt1\" " - " is_extension: true " - " } " - " name { " - " name_part: \"foo4\" " - " is_extension: false " - " } " - " positive_int_value: 12 " - " } " - " uninterpreted_option { " - " name { " - " name_part: \"complex_opt1\" " - " is_extension: true " - " } " - " name { " - " name_part: \"foo4\" " - " is_extension: false " - " } " - " positive_int_value: 34 " - " } " - " uninterpreted_option { " - " name { " - " name_part: \"complex_opt1\" " - " is_extension: true " - " } " - " name { " - " name_part: \"foo4\" " - " is_extension: false " - " } " - " positive_int_value: 56 " - " } " - " } " - "}", - &file_proto)); + "name: \"custom_options_import.proto\" " + "package: \"protobuf_unittest\" " + "dependency: \"google/protobuf/unittest_custom_options.proto\" " + "message_type { " + " name: \"Foo\" " + " options { " + " uninterpreted_option { " + " name { " + " name_part: \"complex_opt1\" " + " is_extension: true " + " } " + " name { " + " name_part: \"foo4\" " + " is_extension: false " + " } " + " positive_int_value: 12 " + " } " + " uninterpreted_option { " + " name { " + " name_part: \"complex_opt1\" " + " is_extension: true " + " } " + " name { " + " name_part: \"foo4\" " + " is_extension: false " + " } " + " positive_int_value: 34 " + " } " + " uninterpreted_option { " + " name { " + " name_part: \"complex_opt1\" " + " is_extension: true " + " } " + " name { " + " name_part: \"foo4\" " + " is_extension: false " + " } " + " positive_int_value: 56 " + " } " + " } " + "}", + &file_proto)); const FileDescriptor* file = pool.BuildFile(file_proto); ASSERT_TRUE(file != NULL); @@ -3269,8 +3287,8 @@ TEST(CustomOptions, MessageOptionRepeatedMsgFieldSet) { FileDescriptorProto::descriptor()->file()->CopyTo(&file_proto); ASSERT_TRUE(pool.BuildFile(file_proto) != NULL); - protobuf_unittest::TestMessageWithCustomOptions::descriptor() - ->file()->CopyTo(&file_proto); + protobuf_unittest::TestMessageWithCustomOptions::descriptor()->file()->CopyTo( + &file_proto); ASSERT_TRUE(pool.BuildFile(file_proto) != NULL); // The following represents the definition: @@ -3283,62 +3301,64 @@ TEST(CustomOptions, MessageOptionRepeatedMsgFieldSet) { // option (complex_opt2).barney = {waldo: 100}; // } ASSERT_TRUE(TextFormat::ParseFromString( - "name: \"custom_options_import.proto\" " - "package: \"protobuf_unittest\" " - "dependency: \"google/protobuf/unittest_custom_options.proto\" " - "message_type { " - " name: \"Foo\" " - " options { " - " uninterpreted_option { " - " name { " - " name_part: \"complex_opt2\" " - " is_extension: true " - " } " - " name { " - " name_part: \"barney\" " - " is_extension: false " - " } " - " aggregate_value: \"waldo: 1\" " - " } " - " uninterpreted_option { " - " name { " - " name_part: \"complex_opt2\" " - " is_extension: true " - " } " - " name { " - " name_part: \"barney\" " - " is_extension: false " - " } " - " aggregate_value: \"waldo: 10\" " - " } " - " uninterpreted_option { " - " name { " - " name_part: \"complex_opt2\" " - " is_extension: true " - " } " - " name { " - " name_part: \"barney\" " - " is_extension: false " - " } " - " aggregate_value: \"waldo: 100\" " - " } " - " } " - "}", - &file_proto)); + "name: \"custom_options_import.proto\" " + "package: \"protobuf_unittest\" " + "dependency: \"google/protobuf/unittest_custom_options.proto\" " + "message_type { " + " name: \"Foo\" " + " options { " + " uninterpreted_option { " + " name { " + " name_part: \"complex_opt2\" " + " is_extension: true " + " } " + " name { " + " name_part: \"barney\" " + " is_extension: false " + " } " + " aggregate_value: \"waldo: 1\" " + " } " + " uninterpreted_option { " + " name { " + " name_part: \"complex_opt2\" " + " is_extension: true " + " } " + " name { " + " name_part: \"barney\" " + " is_extension: false " + " } " + " aggregate_value: \"waldo: 10\" " + " } " + " uninterpreted_option { " + " name { " + " name_part: \"complex_opt2\" " + " is_extension: true " + " } " + " name { " + " name_part: \"barney\" " + " is_extension: false " + " } " + " aggregate_value: \"waldo: 100\" " + " } " + " } " + "}", + &file_proto)); const FileDescriptor* file = pool.BuildFile(file_proto); ASSERT_TRUE(file != NULL); ASSERT_EQ(1, file->message_type_count()); const MessageOptions& options = file->message_type(0)->options(); - EXPECT_EQ(3, options.GetExtension( - protobuf_unittest::complex_opt2).barney_size()); - EXPECT_EQ(1,options.GetExtension( - protobuf_unittest::complex_opt2).barney(0).waldo()); - EXPECT_EQ(10, options.GetExtension( - protobuf_unittest::complex_opt2).barney(1).waldo()); - EXPECT_EQ(100, options.GetExtension( - protobuf_unittest::complex_opt2).barney(2).waldo()); + EXPECT_EQ(3, + options.GetExtension(protobuf_unittest::complex_opt2).barney_size()); + EXPECT_EQ( + 1, options.GetExtension(protobuf_unittest::complex_opt2).barney(0).waldo()); + EXPECT_EQ( + 10, + options.GetExtension(protobuf_unittest::complex_opt2).barney(1).waldo()); + EXPECT_EQ( + 100, + options.GetExtension(protobuf_unittest::complex_opt2).barney(2).waldo()); } // Check that aggregate options were parsed and saved correctly in @@ -3349,8 +3369,8 @@ TEST(CustomOptions, AggregateOptions) { const FieldDescriptor* field = msg->FindFieldByName("fieldname"); const EnumDescriptor* enumd = file->FindEnumTypeByName("AggregateEnum"); const EnumValueDescriptor* enumv = enumd->FindValueByName("VALUE"); - const ServiceDescriptor* service = file->FindServiceByName( - "AggregateService"); + const ServiceDescriptor* service = + file->FindServiceByName("AggregateService"); const MethodDescriptor* method = service->FindMethodByName("Method"); // Tests for the different types of data embedded in fileopt @@ -3362,9 +3382,10 @@ TEST(CustomOptions, AggregateOptions) { EXPECT_EQ("FileExtensionAnnotation", file_options.file().GetExtension(protobuf_unittest::fileopt).s()); EXPECT_EQ("EmbeddedMessageSetElement", - file_options.mset().GetExtension( - protobuf_unittest::AggregateMessageSetElement - ::message_set_extension).s()); + file_options.mset() + .GetExtension(protobuf_unittest::AggregateMessageSetElement :: + message_set_extension) + .s()); // Simple tests for all the other types of annotations EXPECT_EQ("MessageAnnotation", @@ -3388,16 +3409,16 @@ TEST(CustomOptions, UnusedImportWarning) { FileDescriptorProto::descriptor()->file()->CopyTo(&file_proto); ASSERT_TRUE(pool.BuildFile(file_proto) != NULL); - protobuf_unittest::TestMessageWithCustomOptions::descriptor() - ->file()->CopyTo(&file_proto); + protobuf_unittest::TestMessageWithCustomOptions::descriptor()->file()->CopyTo( + &file_proto); ASSERT_TRUE(pool.BuildFile(file_proto) != NULL); pool.AddUnusedImportTrackFile("custom_options_import.proto"); ASSERT_TRUE(TextFormat::ParseFromString( - "name: \"custom_options_import.proto\" " - "package: \"protobuf_unittest\" " - "dependency: \"google/protobuf/unittest_custom_options.proto\" ", - &file_proto)); + "name: \"custom_options_import.proto\" " + "package: \"protobuf_unittest\" " + "dependency: \"google/protobuf/unittest_custom_options.proto\" ", + &file_proto)); MockErrorCollector error_collector; EXPECT_TRUE(pool.BuildFileCollectingErrors(file_proto, &error_collector)); @@ -3407,7 +3428,7 @@ TEST(CustomOptions, UnusedImportWarning) { // Verifies that proto files can correctly be parsed, even if the // custom options defined in the file are incompatible with those // compiled in the binary. See http://b/19276250. -TEST(CustomOptions, OptionsWithRequiredEnums) { +TEST(CustomOptions, OptionsWithIncompatibleDescriptors) { DescriptorPool pool; FileDescriptorProto file_proto; @@ -3423,61 +3444,36 @@ TEST(CustomOptions, OptionsWithRequiredEnums) { // Add the "required_enum_opt" extension. FieldDescriptorProto* extension = file_proto.add_extension(); - protobuf_unittest::OldOptionType::descriptor()->file() - ->FindExtensionByName("required_enum_opt")->CopyTo(extension); + protobuf_unittest::OldOptionType::descriptor() + ->file() + ->FindExtensionByName("required_enum_opt") + ->CopyTo(extension); // Add a test message that uses the "required_enum_opt" option. DescriptorProto* test_message_type = file_proto.add_message_type(); - protobuf_unittest::TestMessageWithRequiredEnumOption::descriptor() - ->CopyTo(test_message_type); + protobuf_unittest::TestMessageWithRequiredEnumOption::descriptor()->CopyTo( + test_message_type); // Instruct the extension to use NewOptionType instead of // OldOptionType, and add the descriptor of NewOptionType. extension->set_type_name(".protobuf_unittest.NewOptionType"); DescriptorProto* new_option_type = file_proto.add_message_type(); - protobuf_unittest::NewOptionType::descriptor() - ->CopyTo(new_option_type); + protobuf_unittest::NewOptionType::descriptor()->CopyTo(new_option_type); // Replace the value of the "required_enum_opt" option used in the // test message with an enum value that only exists in NewOptionType. - ASSERT_TRUE(TextFormat::ParseFromString( - "uninterpreted_option { " - " name { " - " name_part: 'required_enum_opt' " - " is_extension: true " - " } " - " aggregate_value: 'value: NEW_VALUE' " - "}", - test_message_type->mutable_options())); - - // Add the file descriptor to the pool. - ASSERT_TRUE(pool.BuildFile(file_proto) != NULL); - - // Find the test message. - const Descriptor* test_message = pool.FindMessageTypeByName( - "protobuf_unittest.TestMessageWithRequiredEnumOption"); - ASSERT_TRUE(test_message != NULL); - - const MessageOptions& options = test_message->options(); - // Extract the "required_enum_opt" option. Since the binary does not - // know that the extension was updated, this will still return an - // OldOptionType message. ASSERT_TRUE( - options.HasExtension(protobuf_unittest::required_enum_opt)); - const protobuf_unittest::OldOptionType& old_enum_opt = - options.GetExtension(protobuf_unittest::required_enum_opt); + TextFormat::ParseFromString("uninterpreted_option { " + " name { " + " name_part: 'required_enum_opt' " + " is_extension: true " + " } " + " aggregate_value: 'value: NEW_VALUE'" + "}", + test_message_type->mutable_options())); - // Confirm that the required enum field is missing. - EXPECT_FALSE(old_enum_opt.IsInitialized()); - EXPECT_FALSE(old_enum_opt.has_value()); - - string buf; - // Verify that the required enum field does show up when the option - // is re-parsed as a NewOptionType message; - protobuf_unittest::NewOptionType new_enum_opt; - EXPECT_TRUE(old_enum_opt.AppendPartialToString(&buf)); - EXPECT_TRUE(new_enum_opt.ParseFromString(buf)); - EXPECT_EQ(protobuf_unittest::NewOptionType::NEW_VALUE, new_enum_opt.value()); + // Adding the file descriptor to the pool should fail. + EXPECT_TRUE(pool.BuildFile(file_proto) == NULL); } // Test that FileDescriptor::DebugString() formats custom options correctly. @@ -3565,7 +3561,7 @@ class ValidationErrorTest : public testing::Test { protected: // Parse file_text as a FileDescriptorProto in text format and add it // to the DescriptorPool. Expect no errors. - const FileDescriptor* BuildFile(const string& file_text) { + const FileDescriptor* BuildFile(const std::string& file_text) { FileDescriptorProto file_proto; EXPECT_TRUE(TextFormat::ParseFromString(file_text, &file_proto)); return GOOGLE_CHECK_NOTNULL(pool_.BuildFile(file_proto)); @@ -3574,22 +3570,22 @@ class ValidationErrorTest : public testing::Test { // Parse file_text as a FileDescriptorProto in text format and add it // to the DescriptorPool. Expect errors to be produced which match the // given error text. - void BuildFileWithErrors(const string& file_text, - const string& expected_errors) { + void BuildFileWithErrors(const std::string& file_text, + const std::string& expected_errors) { FileDescriptorProto file_proto; ASSERT_TRUE(TextFormat::ParseFromString(file_text, &file_proto)); MockErrorCollector error_collector; - EXPECT_TRUE( - pool_.BuildFileCollectingErrors(file_proto, &error_collector) == NULL); + EXPECT_TRUE(pool_.BuildFileCollectingErrors(file_proto, &error_collector) == + NULL); EXPECT_EQ(expected_errors, error_collector.text_); } // Parse file_text as a FileDescriptorProto in text format and add it // to the DescriptorPool. Expect errors to be produced which match the // given warning text. - void BuildFileWithWarnings(const string& file_text, - const string& expected_warnings) { + void BuildFileWithWarnings(const std::string& file_text, + const std::string& expected_warnings) { FileDescriptorProto file_proto; ASSERT_TRUE(TextFormat::ParseFromString(file_text, &file_proto)); @@ -3616,57 +3612,57 @@ class ValidationErrorTest : public testing::Test { TEST_F(ValidationErrorTest, AlreadyDefined) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" }" - "message_type { name: \"Foo\" }", + "name: \"foo.proto\" " + "message_type { name: \"Foo\" }" + "message_type { name: \"Foo\" }", - "foo.proto: Foo: NAME: \"Foo\" is already defined.\n"); + "foo.proto: Foo: NAME: \"Foo\" is already defined.\n"); } TEST_F(ValidationErrorTest, AlreadyDefinedInPackage) { BuildFileWithErrors( - "name: \"foo.proto\" " - "package: \"foo.bar\" " - "message_type { name: \"Foo\" }" - "message_type { name: \"Foo\" }", + "name: \"foo.proto\" " + "package: \"foo.bar\" " + "message_type { name: \"Foo\" }" + "message_type { name: \"Foo\" }", - "foo.proto: foo.bar.Foo: NAME: \"Foo\" is already defined in " + "foo.proto: foo.bar.Foo: NAME: \"Foo\" is already defined in " "\"foo.bar\".\n"); } TEST_F(ValidationErrorTest, AlreadyDefinedInOtherFile) { BuildFile( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" }"); + "name: \"foo.proto\" " + "message_type { name: \"Foo\" }"); BuildFileWithErrors( - "name: \"bar.proto\" " - "message_type { name: \"Foo\" }", + "name: \"bar.proto\" " + "message_type { name: \"Foo\" }", - "bar.proto: Foo: NAME: \"Foo\" is already defined in file " + "bar.proto: Foo: NAME: \"Foo\" is already defined in file " "\"foo.proto\".\n"); } TEST_F(ValidationErrorTest, PackageAlreadyDefined) { BuildFile( - "name: \"foo.proto\" " - "message_type { name: \"foo\" }"); + "name: \"foo.proto\" " + "message_type { name: \"foo\" }"); BuildFileWithErrors( - "name: \"bar.proto\" " - "package: \"foo.bar\"", + "name: \"bar.proto\" " + "package: \"foo.bar\"", - "bar.proto: foo: NAME: \"foo\" is already defined (as something other " + "bar.proto: foo: NAME: \"foo\" is already defined (as something other " "than a package) in file \"foo.proto\".\n"); } TEST_F(ValidationErrorTest, EnumValueAlreadyDefinedInParent) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type { name: \"Foo\" value { name: \"FOO\" number: 1 } } " - "enum_type { name: \"Bar\" value { name: \"FOO\" number: 1 } } ", + "name: \"foo.proto\" " + "enum_type { name: \"Foo\" value { name: \"FOO\" number: 1 } } " + "enum_type { name: \"Bar\" value { name: \"FOO\" number: 1 } } ", - "foo.proto: FOO: NAME: \"FOO\" is already defined.\n" - "foo.proto: FOO: NAME: Note that enum values use C++ scoping rules, " + "foo.proto: FOO: NAME: \"FOO\" is already defined.\n" + "foo.proto: FOO: NAME: Note that enum values use C++ scoping rules, " "meaning that enum values are siblings of their type, not children of " "it. Therefore, \"FOO\" must be unique within the global scope, not " "just within \"Bar\".\n"); @@ -3674,13 +3670,13 @@ TEST_F(ValidationErrorTest, EnumValueAlreadyDefinedInParent) { TEST_F(ValidationErrorTest, EnumValueAlreadyDefinedInParentNonGlobal) { BuildFileWithErrors( - "name: \"foo.proto\" " - "package: \"pkg\" " - "enum_type { name: \"Foo\" value { name: \"FOO\" number: 1 } } " - "enum_type { name: \"Bar\" value { name: \"FOO\" number: 1 } } ", + "name: \"foo.proto\" " + "package: \"pkg\" " + "enum_type { name: \"Foo\" value { name: \"FOO\" number: 1 } } " + "enum_type { name: \"Bar\" value { name: \"FOO\" number: 1 } } ", - "foo.proto: pkg.FOO: NAME: \"FOO\" is already defined in \"pkg\".\n" - "foo.proto: pkg.FOO: NAME: Note that enum values use C++ scoping rules, " + "foo.proto: pkg.FOO: NAME: \"FOO\" is already defined in \"pkg\".\n" + "foo.proto: pkg.FOO: NAME: Note that enum values use C++ scoping rules, " "meaning that enum values are siblings of their type, not children of " "it. Therefore, \"FOO\" must be unique within \"pkg\", not just within " "\"Bar\".\n"); @@ -3688,60 +3684,60 @@ TEST_F(ValidationErrorTest, EnumValueAlreadyDefinedInParentNonGlobal) { TEST_F(ValidationErrorTest, MissingName) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { }", + "name: \"foo.proto\" " + "message_type { }", - "foo.proto: : NAME: Missing name.\n"); + "foo.proto: : NAME: Missing name.\n"); } TEST_F(ValidationErrorTest, InvalidName) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { name: \"$\" }", + "name: \"foo.proto\" " + "message_type { name: \"$\" }", - "foo.proto: $: NAME: \"$\" is not a valid identifier.\n"); + "foo.proto: $: NAME: \"$\" is not a valid identifier.\n"); } TEST_F(ValidationErrorTest, InvalidPackageName) { BuildFileWithErrors( - "name: \"foo.proto\" " - "package: \"foo.$\"", + "name: \"foo.proto\" " + "package: \"foo.$\"", - "foo.proto: foo.$: NAME: \"$\" is not a valid identifier.\n"); + "foo.proto: foo.$: NAME: \"$\" is not a valid identifier.\n"); } TEST_F(ValidationErrorTest, MissingFileName) { - BuildFileWithErrors( - "", + BuildFileWithErrors("", - ": : OTHER: Missing field: FileDescriptorProto.name.\n"); + ": : OTHER: Missing field: FileDescriptorProto.name.\n"); } TEST_F(ValidationErrorTest, DupeDependency) { BuildFile("name: \"foo.proto\""); BuildFileWithErrors( - "name: \"bar.proto\" " - "dependency: \"foo.proto\" " - "dependency: \"foo.proto\" ", + "name: \"bar.proto\" " + "dependency: \"foo.proto\" " + "dependency: \"foo.proto\" ", - "bar.proto: bar.proto: OTHER: Import \"foo.proto\" was listed twice.\n"); + "bar.proto: foo.proto: IMPORT: Import \"foo.proto\" was listed twice.\n"); } TEST_F(ValidationErrorTest, UnknownDependency) { BuildFileWithErrors( - "name: \"bar.proto\" " - "dependency: \"foo.proto\" ", + "name: \"bar.proto\" " + "dependency: \"foo.proto\" ", - "bar.proto: bar.proto: OTHER: Import \"foo.proto\" has not been loaded.\n"); + "bar.proto: foo.proto: IMPORT: Import \"foo.proto\" has not been " + "loaded.\n"); } TEST_F(ValidationErrorTest, InvalidPublicDependencyIndex) { BuildFile("name: \"foo.proto\""); BuildFileWithErrors( - "name: \"bar.proto\" " - "dependency: \"foo.proto\" " - "public_dependency: 1", - "bar.proto: bar.proto: OTHER: Invalid public dependency index.\n"); + "name: \"bar.proto\" " + "dependency: \"foo.proto\" " + "public_dependency: 1", + "bar.proto: bar.proto: OTHER: Invalid public dependency index.\n"); } TEST_F(ValidationErrorTest, ForeignUnimportedPackageNoCrash) { @@ -3751,475 +3747,494 @@ TEST_F(ValidationErrorTest, ForeignUnimportedPackageNoCrash) { // include that parent package in the name (i.e. we do a relative lookup)... // Yes, really. BuildFile( - "name: 'foo.proto' " - "package: 'outer.foo' "); + "name: 'foo.proto' " + "package: 'outer.foo' "); BuildFileWithErrors( - "name: 'bar.proto' " - "dependency: 'baz.proto' " - "package: 'outer.bar' " - "message_type { " - " name: 'Bar' " - " field { name:'bar' number:1 label:LABEL_OPTIONAL type_name:'foo.Foo' }" - "}", + "name: 'bar.proto' " + "dependency: 'baz.proto' " + "package: 'outer.bar' " + "message_type { " + " name: 'Bar' " + " field { name:'bar' number:1 label:LABEL_OPTIONAL type_name:'foo.Foo' }" + "}", - "bar.proto: bar.proto: OTHER: Import \"baz.proto\" has not been loaded.\n" - "bar.proto: outer.bar.Bar.bar: TYPE: \"outer.foo\" seems to be defined in " + "bar.proto: baz.proto: IMPORT: Import \"baz.proto\" has not been " + "loaded.\n" + "bar.proto: outer.bar.Bar.bar: TYPE: \"outer.foo\" seems to be defined " + "in " "\"foo.proto\", which is not imported by \"bar.proto\". To use it here, " "please add the necessary import.\n"); } TEST_F(ValidationErrorTest, DupeFile) { BuildFile( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" }"); + "name: \"foo.proto\" " + "message_type { name: \"Foo\" }"); // Note: We should *not* get redundant errors about "Foo" already being // defined. BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" } " - // Add another type so that the files aren't identical (in which case there - // would be no error). - "enum_type { name: \"Bar\" }", + "name: \"foo.proto\" " + "message_type { name: \"Foo\" } " + // Add another type so that the files aren't identical (in which case + // there would be no error). + "enum_type { name: \"Bar\" }", - "foo.proto: foo.proto: OTHER: A file with this name is already in the " + "foo.proto: foo.proto: OTHER: A file with this name is already in the " "pool.\n"); } TEST_F(ValidationErrorTest, FieldInExtensionRange) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name: \"foo\" number: 9 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " field { name: \"bar\" number: 10 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " field { name: \"baz\" number: 19 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " field { name: \"qux\" number: 20 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " extension_range { start: 10 end: 20 }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name: \"foo\" number: 9 label:LABEL_OPTIONAL type:TYPE_INT32 " + "}" + " field { name: \"bar\" number: 10 label:LABEL_OPTIONAL type:TYPE_INT32 " + "}" + " field { name: \"baz\" number: 19 label:LABEL_OPTIONAL type:TYPE_INT32 " + "}" + " field { name: \"qux\" number: 20 label:LABEL_OPTIONAL type:TYPE_INT32 " + "}" + " extension_range { start: 10 end: 20 }" + "}", - "foo.proto: Foo.bar: NUMBER: Extension range 10 to 19 includes field " + "foo.proto: Foo.bar: NUMBER: Extension range 10 to 19 includes field " "\"bar\" (10).\n" - "foo.proto: Foo.baz: NUMBER: Extension range 10 to 19 includes field " + "foo.proto: Foo.baz: NUMBER: Extension range 10 to 19 includes field " "\"baz\" (19).\n"); } TEST_F(ValidationErrorTest, OverlappingExtensionRanges) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " extension_range { start: 10 end: 20 }" - " extension_range { start: 20 end: 30 }" - " extension_range { start: 19 end: 21 }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " extension_range { start: 10 end: 20 }" + " extension_range { start: 20 end: 30 }" + " extension_range { start: 19 end: 21 }" + "}", - "foo.proto: Foo: NUMBER: Extension range 19 to 20 overlaps with " + "foo.proto: Foo: NUMBER: Extension range 19 to 20 overlaps with " "already-defined range 10 to 19.\n" - "foo.proto: Foo: NUMBER: Extension range 19 to 20 overlaps with " + "foo.proto: Foo: NUMBER: Extension range 19 to 20 overlaps with " "already-defined range 20 to 29.\n"); } TEST_F(ValidationErrorTest, ReservedFieldError) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name: \"foo\" number: 15 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " reserved_range { start: 10 end: 20 }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name: \"foo\" number: 15 label:LABEL_OPTIONAL type:TYPE_INT32 " + "}" + " reserved_range { start: 10 end: 20 }" + "}", - "foo.proto: Foo.foo: NUMBER: Field \"foo\" uses reserved number 15.\n"); + "foo.proto: Foo.foo: NUMBER: Field \"foo\" uses reserved number 15.\n"); } TEST_F(ValidationErrorTest, ReservedExtensionRangeError) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " extension_range { start: 10 end: 20 }" - " reserved_range { start: 5 end: 15 }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " extension_range { start: 10 end: 20 }" + " reserved_range { start: 5 end: 15 }" + "}", - "foo.proto: Foo: NUMBER: Extension range 10 to 19" - " overlaps with reserved range 5 to 14.\n"); + "foo.proto: Foo: NUMBER: Extension range 10 to 19" + " overlaps with reserved range 5 to 14.\n"); } TEST_F(ValidationErrorTest, ReservedExtensionRangeAdjacent) { BuildFile( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " extension_range { start: 10 end: 20 }" - " reserved_range { start: 5 end: 10 }" - "}"); + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " extension_range { start: 10 end: 20 }" + " reserved_range { start: 5 end: 10 }" + "}"); } TEST_F(ValidationErrorTest, ReservedRangeOverlap) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " reserved_range { start: 10 end: 20 }" - " reserved_range { start: 5 end: 15 }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " reserved_range { start: 10 end: 20 }" + " reserved_range { start: 5 end: 15 }" + "}", - "foo.proto: Foo: NUMBER: Reserved range 5 to 14" - " overlaps with already-defined range 10 to 19.\n"); + "foo.proto: Foo: NUMBER: Reserved range 5 to 14" + " overlaps with already-defined range 10 to 19.\n"); } TEST_F(ValidationErrorTest, ReservedNameError) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name: \"foo\" number: 15 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " field { name: \"bar\" number: 16 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " field { name: \"baz\" number: 17 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " reserved_name: \"foo\"" - " reserved_name: \"bar\"" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name: \"foo\" number: 15 label:LABEL_OPTIONAL type:TYPE_INT32 " + "}" + " field { name: \"bar\" number: 16 label:LABEL_OPTIONAL type:TYPE_INT32 " + "}" + " field { name: \"baz\" number: 17 label:LABEL_OPTIONAL type:TYPE_INT32 " + "}" + " reserved_name: \"foo\"" + " reserved_name: \"bar\"" + "}", - "foo.proto: Foo.foo: NAME: Field name \"foo\" is reserved.\n" - "foo.proto: Foo.bar: NAME: Field name \"bar\" is reserved.\n"); + "foo.proto: Foo.foo: NAME: Field name \"foo\" is reserved.\n" + "foo.proto: Foo.bar: NAME: Field name \"bar\" is reserved.\n"); } TEST_F(ValidationErrorTest, ReservedNameRedundant) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " reserved_name: \"foo\"" - " reserved_name: \"foo\"" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " reserved_name: \"foo\"" + " reserved_name: \"foo\"" + "}", - "foo.proto: foo: NAME: Field name \"foo\" is reserved multiple times.\n"); + "foo.proto: foo: NAME: Field name \"foo\" is reserved multiple times.\n"); } TEST_F(ValidationErrorTest, ReservedFieldsDebugString) { const FileDescriptor* file = BuildFile( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " reserved_name: \"foo\"" - " reserved_name: \"bar\"" - " reserved_range { start: 5 end: 6 }" - " reserved_range { start: 10 end: 20 }" - "}"); + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " reserved_name: \"foo\"" + " reserved_name: \"bar\"" + " reserved_range { start: 5 end: 6 }" + " reserved_range { start: 10 end: 20 }" + "}"); ASSERT_EQ( - "syntax = \"proto2\";\n\n" - "message Foo {\n" - " reserved 5, 10 to 19;\n" - " reserved \"foo\", \"bar\";\n" - "}\n\n", - file->DebugString()); + "syntax = \"proto2\";\n\n" + "message Foo {\n" + " reserved 5, 10 to 19;\n" + " reserved \"foo\", \"bar\";\n" + "}\n\n", + file->DebugString()); } TEST_F(ValidationErrorTest, EnumReservedFieldError) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type {" - " name: \"Foo\"" - " value { name:\"BAR\" number:15 }" - " reserved_range { start: 10 end: 20 }" - "}", + "name: \"foo.proto\" " + "enum_type {" + " name: \"Foo\"" + " value { name:\"BAR\" number:15 }" + " reserved_range { start: 10 end: 20 }" + "}", - "foo.proto: BAR: NUMBER: Enum value \"BAR\" uses reserved number 15.\n"); + "foo.proto: BAR: NUMBER: Enum value \"BAR\" uses reserved number 15.\n"); } TEST_F(ValidationErrorTest, EnumNegativeReservedFieldError) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type {" - " name: \"Foo\"" - " value { name:\"BAR\" number:-15 }" - " reserved_range { start: -20 end: -10 }" - "}", + "name: \"foo.proto\" " + "enum_type {" + " name: \"Foo\"" + " value { name:\"BAR\" number:-15 }" + " reserved_range { start: -20 end: -10 }" + "}", - "foo.proto: BAR: NUMBER: Enum value \"BAR\" uses reserved number -15.\n"); + "foo.proto: BAR: NUMBER: Enum value \"BAR\" uses reserved number -15.\n"); } TEST_F(ValidationErrorTest, EnumReservedRangeOverlap) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type {" - " name: \"Foo\"" - " value { name:\"BAR\" number:0 }" - " reserved_range { start: 10 end: 20 }" - " reserved_range { start: 5 end: 15 }" - "}", + "name: \"foo.proto\" " + "enum_type {" + " name: \"Foo\"" + " value { name:\"BAR\" number:0 }" + " reserved_range { start: 10 end: 20 }" + " reserved_range { start: 5 end: 15 }" + "}", - "foo.proto: Foo: NUMBER: Reserved range 5 to 15" - " overlaps with already-defined range 10 to 20.\n"); + "foo.proto: Foo: NUMBER: Reserved range 5 to 15" + " overlaps with already-defined range 10 to 20.\n"); } TEST_F(ValidationErrorTest, EnumReservedRangeOverlapByOne) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type {" - " name: \"Foo\"" - " value { name:\"BAR\" number:0 }" - " reserved_range { start: 10 end: 20 }" - " reserved_range { start: 5 end: 10 }" - "}", + "name: \"foo.proto\" " + "enum_type {" + " name: \"Foo\"" + " value { name:\"BAR\" number:0 }" + " reserved_range { start: 10 end: 20 }" + " reserved_range { start: 5 end: 10 }" + "}", - "foo.proto: Foo: NUMBER: Reserved range 5 to 10" - " overlaps with already-defined range 10 to 20.\n"); + "foo.proto: Foo: NUMBER: Reserved range 5 to 10" + " overlaps with already-defined range 10 to 20.\n"); } TEST_F(ValidationErrorTest, EnumNegativeReservedRangeOverlap) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type {" - " name: \"Foo\"" - " value { name:\"BAR\" number:0 }" - " reserved_range { start: -20 end: -10 }" - " reserved_range { start: -15 end: -5 }" - "}", + "name: \"foo.proto\" " + "enum_type {" + " name: \"Foo\"" + " value { name:\"BAR\" number:0 }" + " reserved_range { start: -20 end: -10 }" + " reserved_range { start: -15 end: -5 }" + "}", - "foo.proto: Foo: NUMBER: Reserved range -15 to -5" - " overlaps with already-defined range -20 to -10.\n"); + "foo.proto: Foo: NUMBER: Reserved range -15 to -5" + " overlaps with already-defined range -20 to -10.\n"); } TEST_F(ValidationErrorTest, EnumMixedReservedRangeOverlap) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type {" - " name: \"Foo\"" - " value { name:\"BAR\" number:20 }" - " reserved_range { start: -20 end: 10 }" - " reserved_range { start: -15 end: 5 }" - "}", + "name: \"foo.proto\" " + "enum_type {" + " name: \"Foo\"" + " value { name:\"BAR\" number:20 }" + " reserved_range { start: -20 end: 10 }" + " reserved_range { start: -15 end: 5 }" + "}", - "foo.proto: Foo: NUMBER: Reserved range -15 to 5" - " overlaps with already-defined range -20 to 10.\n"); + "foo.proto: Foo: NUMBER: Reserved range -15 to 5" + " overlaps with already-defined range -20 to 10.\n"); } TEST_F(ValidationErrorTest, EnumMixedReservedRangeOverlap2) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type {" - " name: \"Foo\"" - " value { name:\"BAR\" number:20 }" - " reserved_range { start: -20 end: 10 }" - " reserved_range { start: 10 end: 10 }" - "}", + "name: \"foo.proto\" " + "enum_type {" + " name: \"Foo\"" + " value { name:\"BAR\" number:20 }" + " reserved_range { start: -20 end: 10 }" + " reserved_range { start: 10 end: 10 }" + "}", - "foo.proto: Foo: NUMBER: Reserved range 10 to 10" - " overlaps with already-defined range -20 to 10.\n"); + "foo.proto: Foo: NUMBER: Reserved range 10 to 10" + " overlaps with already-defined range -20 to 10.\n"); } TEST_F(ValidationErrorTest, EnumReservedRangeStartGreaterThanEnd) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type {" - " name: \"Foo\"" - " value { name:\"BAR\" number:20 }" - " reserved_range { start: 11 end: 10 }" - "}", + "name: \"foo.proto\" " + "enum_type {" + " name: \"Foo\"" + " value { name:\"BAR\" number:20 }" + " reserved_range { start: 11 end: 10 }" + "}", - "foo.proto: Foo: NUMBER: Reserved range end number must be greater" - " than start number.\n"); + "foo.proto: Foo: NUMBER: Reserved range end number must be greater" + " than start number.\n"); } TEST_F(ValidationErrorTest, EnumReservedNameError) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type {" - " name: \"Foo\"" - " value { name:\"FOO\" number:15 }" - " value { name:\"BAR\" number:15 }" - " reserved_name: \"FOO\"" - " reserved_name: \"BAR\"" - "}", + "name: \"foo.proto\" " + "enum_type {" + " name: \"Foo\"" + " value { name:\"FOO\" number:15 }" + " value { name:\"BAR\" number:15 }" + " reserved_name: \"FOO\"" + " reserved_name: \"BAR\"" + "}", - "foo.proto: FOO: NAME: Enum value \"FOO\" is reserved.\n" - "foo.proto: BAR: NAME: Enum value \"BAR\" is reserved.\n"); + "foo.proto: FOO: NAME: Enum value \"FOO\" is reserved.\n" + "foo.proto: BAR: NAME: Enum value \"BAR\" is reserved.\n"); } TEST_F(ValidationErrorTest, EnumReservedNameRedundant) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type {" - " name: \"Foo\"" - " value { name:\"FOO\" number:15 }" - " reserved_name: \"foo\"" - " reserved_name: \"foo\"" - "}", + "name: \"foo.proto\" " + "enum_type {" + " name: \"Foo\"" + " value { name:\"FOO\" number:15 }" + " reserved_name: \"foo\"" + " reserved_name: \"foo\"" + "}", - "foo.proto: foo: NAME: Enum value \"foo\" is reserved multiple times.\n"); + "foo.proto: foo: NAME: Enum value \"foo\" is reserved multiple times.\n"); } TEST_F(ValidationErrorTest, EnumReservedFieldsDebugString) { const FileDescriptor* file = BuildFile( - "name: \"foo.proto\" " - "enum_type {" - " name: \"Foo\"" - " value { name:\"FOO\" number:3 }" - " reserved_name: \"foo\"" - " reserved_name: \"bar\"" - " reserved_range { start: -6 end: -6 }" - " reserved_range { start: -5 end: -4 }" - " reserved_range { start: -1 end: 1 }" - " reserved_range { start: 5 end: 5 }" - " reserved_range { start: 10 end: 19 }" - "}"); + "name: \"foo.proto\" " + "enum_type {" + " name: \"Foo\"" + " value { name:\"FOO\" number:3 }" + " reserved_name: \"foo\"" + " reserved_name: \"bar\"" + " reserved_range { start: -6 end: -6 }" + " reserved_range { start: -5 end: -4 }" + " reserved_range { start: -1 end: 1 }" + " reserved_range { start: 5 end: 5 }" + " reserved_range { start: 10 end: 19 }" + "}"); ASSERT_EQ( - "syntax = \"proto2\";\n\n" - "enum Foo {\n" - " FOO = 3;\n" - " reserved -6, -5 to -4, -1 to 1, 5, 10 to 19;\n" - " reserved \"foo\", \"bar\";\n" - "}\n\n", - file->DebugString()); + "syntax = \"proto2\";\n\n" + "enum Foo {\n" + " FOO = 3;\n" + " reserved -6, -5 to -4, -1 to 1, 5, 10 to 19;\n" + " reserved \"foo\", \"bar\";\n" + "}\n\n", + file->DebugString()); } TEST_F(ValidationErrorTest, InvalidDefaults) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" - // Invalid number. - " field { name: \"foo\" number: 1 label: LABEL_OPTIONAL type: TYPE_INT32" - " default_value: \"abc\" }" + // Invalid number. + " field { name: \"foo\" number: 1 label: LABEL_OPTIONAL type: TYPE_INT32" + " default_value: \"abc\" }" - // Empty default value. - " field { name: \"bar\" number: 2 label: LABEL_OPTIONAL type: TYPE_INT32" - " default_value: \"\" }" + // Empty default value. + " field { name: \"bar\" number: 2 label: LABEL_OPTIONAL type: TYPE_INT32" + " default_value: \"\" }" - // Invalid boolean. - " field { name: \"baz\" number: 3 label: LABEL_OPTIONAL type: TYPE_BOOL" - " default_value: \"abc\" }" + // Invalid boolean. + " field { name: \"baz\" number: 3 label: LABEL_OPTIONAL type: TYPE_BOOL" + " default_value: \"abc\" }" - // Messages can't have defaults. - " field { name: \"qux\" number: 4 label: LABEL_OPTIONAL type: TYPE_MESSAGE" - " default_value: \"abc\" type_name: \"Foo\" }" + // Messages can't have defaults. + " field { name: \"qux\" number: 4 label: LABEL_OPTIONAL type: " + "TYPE_MESSAGE" + " default_value: \"abc\" type_name: \"Foo\" }" - // Same thing, but we don't know that this field has message type until - // we look up the type name. - " field { name: \"quux\" number: 5 label: LABEL_OPTIONAL" - " default_value: \"abc\" type_name: \"Foo\" }" + // Same thing, but we don't know that this field has message type until + // we look up the type name. + " field { name: \"quux\" number: 5 label: LABEL_OPTIONAL" + " default_value: \"abc\" type_name: \"Foo\" }" - // Repeateds can't have defaults. - " field { name: \"corge\" number: 6 label: LABEL_REPEATED type: TYPE_INT32" - " default_value: \"1\" }" - "}", + // Repeateds can't have defaults. + " field { name: \"corge\" number: 6 label: LABEL_REPEATED type: " + "TYPE_INT32" + " default_value: \"1\" }" + "}", - "foo.proto: Foo.foo: DEFAULT_VALUE: Couldn't parse default value \"abc\".\n" - "foo.proto: Foo.bar: DEFAULT_VALUE: Couldn't parse default value \"\".\n" - "foo.proto: Foo.baz: DEFAULT_VALUE: Boolean default must be true or " + "foo.proto: Foo.foo: DEFAULT_VALUE: Couldn't parse default value " + "\"abc\".\n" + "foo.proto: Foo.bar: DEFAULT_VALUE: Couldn't parse default value \"\".\n" + "foo.proto: Foo.baz: DEFAULT_VALUE: Boolean default must be true or " "false.\n" - "foo.proto: Foo.qux: DEFAULT_VALUE: Messages can't have default values.\n" - "foo.proto: Foo.corge: DEFAULT_VALUE: Repeated fields can't have default " + "foo.proto: Foo.qux: DEFAULT_VALUE: Messages can't have default values.\n" + "foo.proto: Foo.corge: DEFAULT_VALUE: Repeated fields can't have default " "values.\n" - // This ends up being reported later because the error is detected at - // cross-linking time. - "foo.proto: Foo.quux: DEFAULT_VALUE: Messages can't have default " + // This ends up being reported later because the error is detected at + // cross-linking time. + "foo.proto: Foo.quux: DEFAULT_VALUE: Messages can't have default " "values.\n"); } TEST_F(ValidationErrorTest, NegativeFieldNumber) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name: \"foo\" number: -1 label:LABEL_OPTIONAL type:TYPE_INT32 }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name: \"foo\" number: -1 label:LABEL_OPTIONAL type:TYPE_INT32 " + "}" + "}", - "foo.proto: Foo.foo: NUMBER: Field numbers must be positive integers.\n"); + "foo.proto: Foo.foo: NUMBER: Field numbers must be positive integers.\n"); } TEST_F(ValidationErrorTest, HugeFieldNumber) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name: \"foo\" number: 0x70000000 " - " label:LABEL_OPTIONAL type:TYPE_INT32 }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name: \"foo\" number: 0x70000000 " + " label:LABEL_OPTIONAL type:TYPE_INT32 }" + "}", - "foo.proto: Foo.foo: NUMBER: Field numbers cannot be greater than " + "foo.proto: Foo.foo: NUMBER: Field numbers cannot be greater than " "536870911.\n"); } TEST_F(ValidationErrorTest, ReservedFieldNumber) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field {name:\"foo\" number: 18999 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " field {name:\"bar\" number: 19000 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " field {name:\"baz\" number: 19999 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " field {name:\"qux\" number: 20000 label:LABEL_OPTIONAL type:TYPE_INT32 }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " field {name:\"foo\" number: 18999 label:LABEL_OPTIONAL " + "type:TYPE_INT32 }" + " field {name:\"bar\" number: 19000 label:LABEL_OPTIONAL " + "type:TYPE_INT32 }" + " field {name:\"baz\" number: 19999 label:LABEL_OPTIONAL " + "type:TYPE_INT32 }" + " field {name:\"qux\" number: 20000 label:LABEL_OPTIONAL " + "type:TYPE_INT32 }" + "}", - "foo.proto: Foo.bar: NUMBER: Field numbers 19000 through 19999 are " + "foo.proto: Foo.bar: NUMBER: Field numbers 19000 through 19999 are " "reserved for the protocol buffer library implementation.\n" - "foo.proto: Foo.baz: NUMBER: Field numbers 19000 through 19999 are " + "foo.proto: Foo.baz: NUMBER: Field numbers 19000 through 19999 are " "reserved for the protocol buffer library implementation.\n"); } TEST_F(ValidationErrorTest, ExtensionMissingExtendee) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " extension { name: \"foo\" number: 1 label: LABEL_OPTIONAL" - " type_name: \"Foo\" }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " extension { name: \"foo\" number: 1 label: LABEL_OPTIONAL" + " type_name: \"Foo\" }" + "}", - "foo.proto: Foo.foo: EXTENDEE: FieldDescriptorProto.extendee not set for " + "foo.proto: Foo.foo: EXTENDEE: FieldDescriptorProto.extendee not set for " "extension field.\n"); } TEST_F(ValidationErrorTest, NonExtensionWithExtendee) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Bar\"" - " extension_range { start: 1 end: 2 }" - "}" - "message_type {" - " name: \"Foo\"" - " field { name: \"foo\" number: 1 label: LABEL_OPTIONAL" - " type_name: \"Foo\" extendee: \"Bar\" }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Bar\"" + " extension_range { start: 1 end: 2 }" + "}" + "message_type {" + " name: \"Foo\"" + " field { name: \"foo\" number: 1 label: LABEL_OPTIONAL" + " type_name: \"Foo\" extendee: \"Bar\" }" + "}", - "foo.proto: Foo.foo: EXTENDEE: FieldDescriptorProto.extendee set for " + "foo.proto: Foo.foo: EXTENDEE: FieldDescriptorProto.extendee set for " "non-extension field.\n"); } TEST_F(ValidationErrorTest, FieldOneofIndexTooLarge) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_INT32 " - " oneof_index: 1 }" - " field { name:\"dummy\" number:2 label:LABEL_OPTIONAL type:TYPE_INT32 " - " oneof_index: 0 }" - " oneof_decl { name:\"bar\" }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_INT32 " + " oneof_index: 1 }" + " field { name:\"dummy\" number:2 label:LABEL_OPTIONAL type:TYPE_INT32 " + " oneof_index: 0 }" + " oneof_decl { name:\"bar\" }" + "}", - "foo.proto: Foo.foo: OTHER: FieldDescriptorProto.oneof_index 1 is out of " + "foo.proto: Foo.foo: TYPE: FieldDescriptorProto.oneof_index 1 is out of " "range for type \"Foo\".\n"); } TEST_F(ValidationErrorTest, FieldOneofIndexNegative) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_INT32 " - " oneof_index: -1 }" - " field { name:\"dummy\" number:2 label:LABEL_OPTIONAL type:TYPE_INT32 " - " oneof_index: 0 }" - " oneof_decl { name:\"bar\" }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_INT32 " + " oneof_index: -1 }" + " field { name:\"dummy\" number:2 label:LABEL_OPTIONAL type:TYPE_INT32 " + " oneof_index: 0 }" + " oneof_decl { name:\"bar\" }" + "}", - "foo.proto: Foo.foo: OTHER: FieldDescriptorProto.oneof_index -1 is out of " + "foo.proto: Foo.foo: TYPE: FieldDescriptorProto.oneof_index -1 is out " + "of " "range for type \"Foo\".\n"); } @@ -4237,7 +4252,7 @@ TEST_F(ValidationErrorTest, OneofFieldsConsecutiveDefinition) { " oneof_decl { name:\"foos\" }" "}", - "foo.proto: Foo.bar: OTHER: Fields in the same oneof must be defined " + "foo.proto: Foo.bar: TYPE: Fields in the same oneof must be defined " "consecutively. \"bar\" cannot be defined before the completion of the " "\"foos\" oneof definition.\n"); @@ -4257,10 +4272,10 @@ TEST_F(ValidationErrorTest, OneofFieldsConsecutiveDefinition) { " oneof_decl { name:\"foos\" }" " oneof_decl { name:\"bars\" }" "}", - "foo2.proto: Foo2.bar1: OTHER: Fields in the same oneof must be defined " + "foo2.proto: Foo2.bar1: TYPE: Fields in the same oneof must be defined " "consecutively. \"bar1\" cannot be defined before the completion of the " "\"foos\" oneof definition.\n" - "foo2.proto: Foo2.foo2: OTHER: Fields in the same oneof must be defined " + "foo2.proto: Foo2.foo2: TYPE: Fields in the same oneof must be defined " "consecutively. \"foo2\" cannot be defined before the completion of the " "\"bars\" oneof definition.\n"); @@ -4279,202 +4294,205 @@ TEST_F(ValidationErrorTest, OneofFieldsConsecutiveDefinition) { " oneof_decl { name:\"foos\" }" " oneof_decl { name:\"bars\" }" "}", - "foo3.proto: Foo3.baz: OTHER: Fields in the same oneof must be defined " + "foo3.proto: Foo3.baz: TYPE: Fields in the same oneof must be defined " "consecutively. \"baz\" cannot be defined before the completion of the " "\"foos\" oneof definition.\n"); } TEST_F(ValidationErrorTest, FieldNumberConflict) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name: \"foo\" number: 1 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " field { name: \"bar\" number: 1 label:LABEL_OPTIONAL type:TYPE_INT32 }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name: \"foo\" number: 1 label:LABEL_OPTIONAL type:TYPE_INT32 }" + " field { name: \"bar\" number: 1 label:LABEL_OPTIONAL type:TYPE_INT32 }" + "}", - "foo.proto: Foo.bar: NUMBER: Field number 1 has already been used in " + "foo.proto: Foo.bar: NUMBER: Field number 1 has already been used in " "\"Foo\" by field \"foo\".\n"); } TEST_F(ValidationErrorTest, BadMessageSetExtensionType) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"MessageSet\"" - " options { message_set_wire_format: true }" - " extension_range { start: 4 end: 5 }" - "}" - "message_type {" - " name: \"Foo\"" - " extension { name:\"foo\" number:4 label:LABEL_OPTIONAL type:TYPE_INT32" - " extendee: \"MessageSet\" }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"MessageSet\"" + " options { message_set_wire_format: true }" + " extension_range { start: 4 end: 5 }" + "}" + "message_type {" + " name: \"Foo\"" + " extension { name:\"foo\" number:4 label:LABEL_OPTIONAL type:TYPE_INT32" + " extendee: \"MessageSet\" }" + "}", - "foo.proto: Foo.foo: TYPE: Extensions of MessageSets must be optional " + "foo.proto: Foo.foo: TYPE: Extensions of MessageSets must be optional " "messages.\n"); } TEST_F(ValidationErrorTest, BadMessageSetExtensionLabel) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"MessageSet\"" - " options { message_set_wire_format: true }" - " extension_range { start: 4 end: 5 }" - "}" - "message_type {" - " name: \"Foo\"" - " extension { name:\"foo\" number:4 label:LABEL_REPEATED type:TYPE_MESSAGE" - " type_name: \"Foo\" extendee: \"MessageSet\" }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"MessageSet\"" + " options { message_set_wire_format: true }" + " extension_range { start: 4 end: 5 }" + "}" + "message_type {" + " name: \"Foo\"" + " extension { name:\"foo\" number:4 label:LABEL_REPEATED " + "type:TYPE_MESSAGE" + " type_name: \"Foo\" extendee: \"MessageSet\" }" + "}", - "foo.proto: Foo.foo: TYPE: Extensions of MessageSets must be optional " + "foo.proto: Foo.foo: TYPE: Extensions of MessageSets must be optional " "messages.\n"); } TEST_F(ValidationErrorTest, FieldInMessageSet) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " options { message_set_wire_format: true }" - " field { name: \"foo\" number: 1 label:LABEL_OPTIONAL type:TYPE_INT32 }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " options { message_set_wire_format: true }" + " field { name: \"foo\" number: 1 label:LABEL_OPTIONAL type:TYPE_INT32 }" + "}", - "foo.proto: Foo.foo: NAME: MessageSets cannot have fields, only " + "foo.proto: Foo.foo: NAME: MessageSets cannot have fields, only " "extensions.\n"); } TEST_F(ValidationErrorTest, NegativeExtensionRangeNumber) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " extension_range { start: -10 end: -1 }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " extension_range { start: -10 end: -1 }" + "}", - "foo.proto: Foo: NUMBER: Extension numbers must be positive integers.\n"); + "foo.proto: Foo: NUMBER: Extension numbers must be positive integers.\n"); } TEST_F(ValidationErrorTest, HugeExtensionRangeNumber) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " extension_range { start: 1 end: 0x70000000 }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " extension_range { start: 1 end: 0x70000000 }" + "}", - "foo.proto: Foo: NUMBER: Extension numbers cannot be greater than " + "foo.proto: Foo: NUMBER: Extension numbers cannot be greater than " "536870911.\n"); } TEST_F(ValidationErrorTest, ExtensionRangeEndBeforeStart) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " extension_range { start: 10 end: 10 }" - " extension_range { start: 10 end: 5 }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " extension_range { start: 10 end: 10 }" + " extension_range { start: 10 end: 5 }" + "}", - "foo.proto: Foo: NUMBER: Extension range end number must be greater than " + "foo.proto: Foo: NUMBER: Extension range end number must be greater than " "start number.\n" - "foo.proto: Foo: NUMBER: Extension range end number must be greater than " + "foo.proto: Foo: NUMBER: Extension range end number must be greater than " "start number.\n"); } TEST_F(ValidationErrorTest, EmptyEnum) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type { name: \"Foo\" }" - // Also use the empty enum in a message to make sure there are no crashes - // during validation (possible if the code attempts to derive a default - // value for the field). - "message_type {" - " name: \"Bar\"" - " field { name: \"foo\" number: 1 label:LABEL_OPTIONAL type_name:\"Foo\" }" - " field { name: \"bar\" number: 2 label:LABEL_OPTIONAL type_name:\"Foo\" " - " default_value: \"NO_SUCH_VALUE\" }" - "}", + "name: \"foo.proto\" " + "enum_type { name: \"Foo\" }" + // Also use the empty enum in a message to make sure there are no crashes + // during validation (possible if the code attempts to derive a default + // value for the field). + "message_type {" + " name: \"Bar\"" + " field { name: \"foo\" number: 1 label:LABEL_OPTIONAL " + "type_name:\"Foo\" }" + " field { name: \"bar\" number: 2 label:LABEL_OPTIONAL " + "type_name:\"Foo\" " + " default_value: \"NO_SUCH_VALUE\" }" + "}", - "foo.proto: Foo: NAME: Enums must contain at least one value.\n" - "foo.proto: Bar.bar: DEFAULT_VALUE: Enum type \"Foo\" has no value named " + "foo.proto: Foo: NAME: Enums must contain at least one value.\n" + "foo.proto: Bar.bar: DEFAULT_VALUE: Enum type \"Foo\" has no value named " "\"NO_SUCH_VALUE\".\n"); } TEST_F(ValidationErrorTest, UndefinedExtendee) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " extension { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_INT32" - " extendee: \"Bar\" }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " extension { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_INT32" + " extendee: \"Bar\" }" + "}", - "foo.proto: Foo.foo: EXTENDEE: \"Bar\" is not defined.\n"); + "foo.proto: Foo.foo: EXTENDEE: \"Bar\" is not defined.\n"); } TEST_F(ValidationErrorTest, NonMessageExtendee) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type { name: \"Bar\" value { name:\"DUMMY\" number:0 } }" - "message_type {" - " name: \"Foo\"" - " extension { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_INT32" - " extendee: \"Bar\" }" - "}", + "name: \"foo.proto\" " + "enum_type { name: \"Bar\" value { name:\"DUMMY\" number:0 } }" + "message_type {" + " name: \"Foo\"" + " extension { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_INT32" + " extendee: \"Bar\" }" + "}", - "foo.proto: Foo.foo: EXTENDEE: \"Bar\" is not a message type.\n"); + "foo.proto: Foo.foo: EXTENDEE: \"Bar\" is not a message type.\n"); } TEST_F(ValidationErrorTest, NotAnExtensionNumber) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Bar\"" - "}" - "message_type {" - " name: \"Foo\"" - " extension { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_INT32" - " extendee: \"Bar\" }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Bar\"" + "}" + "message_type {" + " name: \"Foo\"" + " extension { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_INT32" + " extendee: \"Bar\" }" + "}", - "foo.proto: Foo.foo: NUMBER: \"Bar\" does not declare 1 as an extension " + "foo.proto: Foo.foo: NUMBER: \"Bar\" does not declare 1 as an extension " "number.\n"); } TEST_F(ValidationErrorTest, RequiredExtension) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Bar\"" - " extension_range { start: 1000 end: 10000 }" - "}" - "message_type {" - " name: \"Foo\"" - " extension {" - " name:\"foo\"" - " number:1000" - " label:LABEL_REQUIRED" - " type:TYPE_INT32" - " extendee: \"Bar\"" - " }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Bar\"" + " extension_range { start: 1000 end: 10000 }" + "}" + "message_type {" + " name: \"Foo\"" + " extension {" + " name:\"foo\"" + " number:1000" + " label:LABEL_REQUIRED" + " type:TYPE_INT32" + " extendee: \"Bar\"" + " }" + "}", - "foo.proto: Foo.foo: TYPE: Message extensions cannot have required " - "fields.\n"); + "foo.proto: Foo.foo: TYPE: Message extensions cannot have required " + "fields.\n"); } TEST_F(ValidationErrorTest, UndefinedFieldType) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\" }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\" }" + "}", - "foo.proto: Foo.foo: TYPE: \"Bar\" is not defined.\n"); + "foo.proto: Foo.foo: TYPE: \"Bar\" is not defined.\n"); } TEST_F(ValidationErrorTest, UndefinedFieldTypeWithDefault) { @@ -4483,42 +4501,42 @@ TEST_F(ValidationErrorTest, UndefinedFieldTypeWithDefault) { // error message. We want this input to yield a validation error instead, // since the unknown type is the primary problem. BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"int\" " - " default_value:\"1\" }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"int\" " + " default_value:\"1\" }" + "}", - "foo.proto: Foo.foo: TYPE: \"int\" is not defined.\n"); + "foo.proto: Foo.foo: TYPE: \"int\" is not defined.\n"); } TEST_F(ValidationErrorTest, UndefinedNestedFieldType) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " nested_type { name:\"Baz\" }" - " field { name:\"foo\" number:1" - " label:LABEL_OPTIONAL" - " type_name:\"Foo.Baz.Bar\" }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " nested_type { name:\"Baz\" }" + " field { name:\"foo\" number:1" + " label:LABEL_OPTIONAL" + " type_name:\"Foo.Baz.Bar\" }" + "}", - "foo.proto: Foo.foo: TYPE: \"Foo.Baz.Bar\" is not defined.\n"); + "foo.proto: Foo.foo: TYPE: \"Foo.Baz.Bar\" is not defined.\n"); } TEST_F(ValidationErrorTest, FieldTypeDefinedInUndeclaredDependency) { BuildFile( - "name: \"bar.proto\" " - "message_type { name: \"Bar\" } "); + "name: \"bar.proto\" " + "message_type { name: \"Bar\" } "); BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\" }" - "}", - "foo.proto: Foo.foo: TYPE: \"Bar\" seems to be defined in \"bar.proto\", " + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\" }" + "}", + "foo.proto: Foo.foo: TYPE: \"Bar\" seems to be defined in \"bar.proto\", " "which is not imported by \"foo.proto\". To use it here, please add the " "necessary import.\n"); } @@ -4539,21 +4557,21 @@ TEST_F(ValidationErrorTest, FieldTypeDefinedInIndirectDependency) { // } // BuildFile( - "name: \"bar.proto\" " - "message_type { name: \"Bar\" }"); + "name: \"bar.proto\" " + "message_type { name: \"Bar\" }"); BuildFile( - "name: \"forward.proto\"" - "dependency: \"bar.proto\""); + "name: \"forward.proto\"" + "dependency: \"bar.proto\""); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"forward.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\" }" - "}", - "foo.proto: Foo.foo: TYPE: \"Bar\" seems to be defined in \"bar.proto\", " + "name: \"foo.proto\" " + "dependency: \"forward.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\" }" + "}", + "foo.proto: Foo.foo: TYPE: \"Bar\" seems to be defined in \"bar.proto\", " "which is not imported by \"foo.proto\". To use it here, please add the " "necessary import.\n"); } @@ -4576,21 +4594,21 @@ TEST_F(ValidationErrorTest, FieldTypeDefinedInPublicDependency) { // } // BuildFile( - "name: \"bar.proto\" " - "message_type { name: \"Bar\" }"); + "name: \"bar.proto\" " + "message_type { name: \"Bar\" }"); BuildFile( - "name: \"forward.proto\"" - "dependency: \"bar.proto\" " - "public_dependency: 0"); + "name: \"forward.proto\"" + "dependency: \"bar.proto\" " + "public_dependency: 0"); BuildFile( - "name: \"foo.proto\" " - "dependency: \"forward.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\" }" - "}"); + "name: \"foo.proto\" " + "dependency: \"forward.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\" }" + "}"); } TEST_F(ValidationErrorTest, FieldTypeDefinedInTransitivePublicDependency) { @@ -4612,26 +4630,26 @@ TEST_F(ValidationErrorTest, FieldTypeDefinedInTransitivePublicDependency) { // } // BuildFile( - "name: \"bar.proto\" " - "message_type { name: \"Bar\" }"); + "name: \"bar.proto\" " + "message_type { name: \"Bar\" }"); BuildFile( - "name: \"forward.proto\"" - "dependency: \"bar.proto\" " - "public_dependency: 0"); + "name: \"forward.proto\"" + "dependency: \"bar.proto\" " + "public_dependency: 0"); BuildFile( - "name: \"forward2.proto\"" - "dependency: \"forward.proto\" " - "public_dependency: 0"); + "name: \"forward2.proto\"" + "dependency: \"forward.proto\" " + "public_dependency: 0"); BuildFile( - "name: \"foo.proto\" " - "dependency: \"forward2.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\" }" - "}"); + "name: \"foo.proto\" " + "dependency: \"forward2.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\" }" + "}"); } TEST_F(ValidationErrorTest, @@ -4656,26 +4674,26 @@ TEST_F(ValidationErrorTest, // } // BuildFile( - "name: \"bar.proto\" " - "message_type { name: \"Bar\" }"); + "name: \"bar.proto\" " + "message_type { name: \"Bar\" }"); BuildFile( - "name: \"forward.proto\"" - "dependency: \"bar.proto\""); + "name: \"forward.proto\"" + "dependency: \"bar.proto\""); BuildFile( - "name: \"forward2.proto\"" - "dependency: \"forward.proto\" " - "public_dependency: 0"); + "name: \"forward2.proto\"" + "dependency: \"forward.proto\" " + "public_dependency: 0"); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"forward2.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\" }" - "}", - "foo.proto: Foo.foo: TYPE: \"Bar\" seems to be defined in \"bar.proto\", " + "name: \"foo.proto\" " + "dependency: \"forward2.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\" }" + "}", + "foo.proto: Foo.foo: TYPE: \"Bar\" seems to be defined in \"bar.proto\", " "which is not imported by \"foo.proto\". To use it here, please add the " "necessary import.\n"); } @@ -4697,22 +4715,22 @@ TEST_F(ValidationErrorTest, SearchMostLocalFirst) { // fail, and ten try "Bar.Baz" and succeed, even though "Bar" should actually // refer to the inner Bar, not the outer one. BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Bar\"" - " nested_type { name: \"Baz\" }" - "}" - "message_type {" - " name: \"Foo\"" - " nested_type { name: \"Bar\" }" - " field { name:\"baz\" number:1 label:LABEL_OPTIONAL" - " type_name:\"Bar.Baz\" }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Bar\"" + " nested_type { name: \"Baz\" }" + "}" + "message_type {" + " name: \"Foo\"" + " nested_type { name: \"Bar\" }" + " field { name:\"baz\" number:1 label:LABEL_OPTIONAL" + " type_name:\"Bar.Baz\" }" + "}", - "foo.proto: Foo.baz: TYPE: \"Bar.Baz\" is resolved to \"Foo.Bar.Baz\"," - " which is not defined. The innermost scope is searched first in name " - "resolution. Consider using a leading '.'(i.e., \".Bar.Baz\") to start " - "from the outermost scope.\n"); + "foo.proto: Foo.baz: TYPE: \"Bar.Baz\" is resolved to \"Foo.Bar.Baz\"," + " which is not defined. The innermost scope is searched first in name " + "resolution. Consider using a leading '.'(i.e., \".Bar.Baz\") to start " + "from the outermost scope.\n"); } TEST_F(ValidationErrorTest, SearchMostLocalFirst2) { @@ -4720,17 +4738,17 @@ TEST_F(ValidationErrorTest, SearchMostLocalFirst2) { // proceeds to find the outer one because the inner one's not an // aggregate. BuildFile( - "name: \"foo.proto\" " - "message_type {" - " name: \"Bar\"" - " nested_type { name: \"Baz\" }" - "}" - "message_type {" - " name: \"Foo\"" - " field { name: \"Bar\" number:1 type:TYPE_BYTES } " - " field { name:\"baz\" number:2 label:LABEL_OPTIONAL" - " type_name:\"Bar.Baz\" }" - "}"); + "name: \"foo.proto\" " + "message_type {" + " name: \"Bar\"" + " nested_type { name: \"Baz\" }" + "}" + "message_type {" + " name: \"Foo\"" + " field { name: \"Bar\" number:1 type:TYPE_BYTES } " + " field { name:\"baz\" number:2 label:LABEL_OPTIONAL" + " type_name:\"Bar.Baz\" }" + "}"); } TEST_F(ValidationErrorTest, PackageOriginallyDeclaredInTransitiveDependent) { @@ -4756,349 +4774,348 @@ TEST_F(ValidationErrorTest, PackageOriginallyDeclaredInTransitiveDependent) { // prevent it from finding "foo.bar". BuildFile( - "name: \"foo.proto\" " - "package: \"foo.bar\" "); + "name: \"foo.proto\" " + "package: \"foo.bar\" "); BuildFile( - "name: \"bar.proto\" " - "package: \"foo.bar\" " - "dependency: \"foo.proto\" " - "message_type { name: \"Bar\" }"); + "name: \"bar.proto\" " + "package: \"foo.bar\" " + "dependency: \"foo.proto\" " + "message_type { name: \"Bar\" }"); BuildFile( - "name: \"baz.proto\" " - "package: \"foo\" " - "dependency: \"bar.proto\" " - "message_type { " - " name: \"Baz\" " - " field { name:\"qux\" number:1 label:LABEL_OPTIONAL " - " type_name:\"bar.Bar\" }" - "}"); + "name: \"baz.proto\" " + "package: \"foo\" " + "dependency: \"bar.proto\" " + "message_type { " + " name: \"Baz\" " + " field { name:\"qux\" number:1 label:LABEL_OPTIONAL " + " type_name:\"bar.Bar\" }" + "}"); } TEST_F(ValidationErrorTest, FieldTypeNotAType) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL " - " type_name:\".Foo.bar\" }" - " field { name:\"bar\" number:2 label:LABEL_OPTIONAL type:TYPE_INT32 }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL " + " type_name:\".Foo.bar\" }" + " field { name:\"bar\" number:2 label:LABEL_OPTIONAL type:TYPE_INT32 }" + "}", - "foo.proto: Foo.foo: TYPE: \".Foo.bar\" is not a type.\n"); + "foo.proto: Foo.foo: TYPE: \".Foo.bar\" is not a type.\n"); } TEST_F(ValidationErrorTest, RelativeFieldTypeNotAType) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " nested_type {" - " name: \"Bar\"" - " field { name:\"Baz\" number:2 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " }" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL " - " type_name:\"Bar.Baz\" }" - "}", - "foo.proto: Foo.foo: TYPE: \"Bar.Baz\" is not a type.\n"); + "name: \"foo.proto\" " + "message_type {" + " nested_type {" + " name: \"Bar\"" + " field { name:\"Baz\" number:2 label:LABEL_OPTIONAL type:TYPE_INT32 }" + " }" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL " + " type_name:\"Bar.Baz\" }" + "}", + "foo.proto: Foo.foo: TYPE: \"Bar.Baz\" is not a type.\n"); } TEST_F(ValidationErrorTest, FieldTypeMayBeItsName) { BuildFile( - "name: \"foo.proto\" " - "message_type {" - " name: \"Bar\"" - "}" - "message_type {" - " name: \"Foo\"" - " field { name:\"Bar\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\" }" - "}"); + "name: \"foo.proto\" " + "message_type {" + " name: \"Bar\"" + "}" + "message_type {" + " name: \"Foo\"" + " field { name:\"Bar\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\" }" + "}"); } TEST_F(ValidationErrorTest, EnumFieldTypeIsMessage) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { name: \"Bar\" } " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_ENUM" - " type_name:\"Bar\" }" - "}", + "name: \"foo.proto\" " + "message_type { name: \"Bar\" } " + "message_type {" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_ENUM" + " type_name:\"Bar\" }" + "}", - "foo.proto: Foo.foo: TYPE: \"Bar\" is not an enum type.\n"); + "foo.proto: Foo.foo: TYPE: \"Bar\" is not an enum type.\n"); } TEST_F(ValidationErrorTest, MessageFieldTypeIsEnum) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type { name: \"Bar\" value { name:\"DUMMY\" number:0 } } " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_MESSAGE" - " type_name:\"Bar\" }" - "}", + "name: \"foo.proto\" " + "enum_type { name: \"Bar\" value { name:\"DUMMY\" number:0 } } " + "message_type {" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_MESSAGE" + " type_name:\"Bar\" }" + "}", - "foo.proto: Foo.foo: TYPE: \"Bar\" is not a message type.\n"); + "foo.proto: Foo.foo: TYPE: \"Bar\" is not a message type.\n"); } TEST_F(ValidationErrorTest, BadEnumDefaultValue) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type { name: \"Bar\" value { name:\"DUMMY\" number:0 } } " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\"" - " default_value:\"NO_SUCH_VALUE\" }" - "}", + "name: \"foo.proto\" " + "enum_type { name: \"Bar\" value { name:\"DUMMY\" number:0 } } " + "message_type {" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\"" + " default_value:\"NO_SUCH_VALUE\" }" + "}", - "foo.proto: Foo.foo: DEFAULT_VALUE: Enum type \"Bar\" has no value named " + "foo.proto: Foo.foo: DEFAULT_VALUE: Enum type \"Bar\" has no value named " "\"NO_SUCH_VALUE\".\n"); } TEST_F(ValidationErrorTest, EnumDefaultValueIsInteger) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type { name: \"Bar\" value { name:\"DUMMY\" number:0 } } " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\"" - " default_value:\"0\" }" - "}", + "name: \"foo.proto\" " + "enum_type { name: \"Bar\" value { name:\"DUMMY\" number:0 } } " + "message_type {" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\"" + " default_value:\"0\" }" + "}", - "foo.proto: Foo.foo: DEFAULT_VALUE: Default value for an enum field must " - "be an identifier.\n"); + "foo.proto: Foo.foo: DEFAULT_VALUE: Default value for an enum field must " + "be an identifier.\n"); } TEST_F(ValidationErrorTest, PrimitiveWithTypeName) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_INT32" - " type_name:\"Foo\" }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_INT32" + " type_name:\"Foo\" }" + "}", - "foo.proto: Foo.foo: TYPE: Field with primitive type has type_name.\n"); + "foo.proto: Foo.foo: TYPE: Field with primitive type has type_name.\n"); } TEST_F(ValidationErrorTest, NonPrimitiveWithoutTypeName) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_MESSAGE }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_MESSAGE }" + "}", - "foo.proto: Foo.foo: TYPE: Field with message or enum type missing " + "foo.proto: Foo.foo: TYPE: Field with message or enum type missing " "type_name.\n"); } TEST_F(ValidationErrorTest, OneofWithNoFields) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " oneof_decl { name:\"bar\" }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " oneof_decl { name:\"bar\" }" + "}", - "foo.proto: Foo.bar: NAME: Oneof must have at least one field.\n"); + "foo.proto: Foo.bar: NAME: Oneof must have at least one field.\n"); } TEST_F(ValidationErrorTest, OneofLabelMismatch) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_REPEATED type:TYPE_INT32 " - " oneof_index:0 }" - " oneof_decl { name:\"bar\" }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"Foo\"" + " field { name:\"foo\" number:1 label:LABEL_REPEATED type:TYPE_INT32 " + " oneof_index:0 }" + " oneof_decl { name:\"bar\" }" + "}", - "foo.proto: Foo.foo: NAME: Fields of oneofs must themselves have label " + "foo.proto: Foo.foo: NAME: Fields of oneofs must themselves have label " "LABEL_OPTIONAL.\n"); } TEST_F(ValidationErrorTest, InputTypeNotDefined) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" } " - "service {" - " name: \"TestService\"" - " method { name: \"A\" input_type: \"Bar\" output_type: \"Foo\" }" - "}", + "name: \"foo.proto\" " + "message_type { name: \"Foo\" } " + "service {" + " name: \"TestService\"" + " method { name: \"A\" input_type: \"Bar\" output_type: \"Foo\" }" + "}", - "foo.proto: TestService.A: INPUT_TYPE: \"Bar\" is not defined.\n" - ); + "foo.proto: TestService.A: INPUT_TYPE: \"Bar\" is not defined.\n" + ); } TEST_F(ValidationErrorTest, InputTypeNotAMessage) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" } " - "enum_type { name: \"Bar\" value { name:\"DUMMY\" number:0 } } " - "service {" - " name: \"TestService\"" - " method { name: \"A\" input_type: \"Bar\" output_type: \"Foo\" }" - "}", + "name: \"foo.proto\" " + "message_type { name: \"Foo\" } " + "enum_type { name: \"Bar\" value { name:\"DUMMY\" number:0 } } " + "service {" + " name: \"TestService\"" + " method { name: \"A\" input_type: \"Bar\" output_type: \"Foo\" }" + "}", - "foo.proto: TestService.A: INPUT_TYPE: \"Bar\" is not a message type.\n" - ); + "foo.proto: TestService.A: INPUT_TYPE: \"Bar\" is not a message type.\n" + ); } TEST_F(ValidationErrorTest, OutputTypeNotDefined) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" } " - "service {" - " name: \"TestService\"" - " method { name: \"A\" input_type: \"Foo\" output_type: \"Bar\" }" - "}", + "name: \"foo.proto\" " + "message_type { name: \"Foo\" } " + "service {" + " name: \"TestService\"" + " method { name: \"A\" input_type: \"Foo\" output_type: \"Bar\" }" + "}", - "foo.proto: TestService.A: OUTPUT_TYPE: \"Bar\" is not defined.\n" - ); + "foo.proto: TestService.A: OUTPUT_TYPE: \"Bar\" is not defined.\n" + ); } TEST_F(ValidationErrorTest, OutputTypeNotAMessage) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" } " - "enum_type { name: \"Bar\" value { name:\"DUMMY\" number:0 } } " - "service {" - " name: \"TestService\"" - " method { name: \"A\" input_type: \"Foo\" output_type: \"Bar\" }" - "}", + "name: \"foo.proto\" " + "message_type { name: \"Foo\" } " + "enum_type { name: \"Bar\" value { name:\"DUMMY\" number:0 } } " + "service {" + " name: \"TestService\"" + " method { name: \"A\" input_type: \"Foo\" output_type: \"Bar\" }" + "}", - "foo.proto: TestService.A: OUTPUT_TYPE: \"Bar\" is not a message type.\n" - ); + "foo.proto: TestService.A: OUTPUT_TYPE: \"Bar\" is not a message type.\n" + ); } TEST_F(ValidationErrorTest, IllegalPackedField) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {\n" - " name: \"Foo\"" - " field { name:\"packed_string\" number:1 label:LABEL_REPEATED " - " type:TYPE_STRING " - " options { uninterpreted_option {" - " name { name_part: \"packed\" is_extension: false }" - " identifier_value: \"true\" }}}\n" - " field { name:\"packed_message\" number:3 label:LABEL_REPEATED " - " type_name: \"Foo\"" - " options { uninterpreted_option {" - " name { name_part: \"packed\" is_extension: false }" - " identifier_value: \"true\" }}}\n" - " field { name:\"optional_int32\" number: 4 label: LABEL_OPTIONAL " - " type:TYPE_INT32 " - " options { uninterpreted_option {" - " name { name_part: \"packed\" is_extension: false }" - " identifier_value: \"true\" }}}\n" - "}", + "name: \"foo.proto\" " + "message_type {\n" + " name: \"Foo\"" + " field { name:\"packed_string\" number:1 label:LABEL_REPEATED " + " type:TYPE_STRING " + " options { uninterpreted_option {" + " name { name_part: \"packed\" is_extension: false }" + " identifier_value: \"true\" }}}\n" + " field { name:\"packed_message\" number:3 label:LABEL_REPEATED " + " type_name: \"Foo\"" + " options { uninterpreted_option {" + " name { name_part: \"packed\" is_extension: false }" + " identifier_value: \"true\" }}}\n" + " field { name:\"optional_int32\" number: 4 label: LABEL_OPTIONAL " + " type:TYPE_INT32 " + " options { uninterpreted_option {" + " name { name_part: \"packed\" is_extension: false }" + " identifier_value: \"true\" }}}\n" + "}", - "foo.proto: Foo.packed_string: TYPE: [packed = true] can only be " - "specified for repeated primitive fields.\n" - "foo.proto: Foo.packed_message: TYPE: [packed = true] can only be " - "specified for repeated primitive fields.\n" - "foo.proto: Foo.optional_int32: TYPE: [packed = true] can only be " - "specified for repeated primitive fields.\n" - ); + "foo.proto: Foo.packed_string: TYPE: [packed = true] can only be " + "specified for repeated primitive fields.\n" + "foo.proto: Foo.packed_message: TYPE: [packed = true] can only be " + "specified for repeated primitive fields.\n" + "foo.proto: Foo.optional_int32: TYPE: [packed = true] can only be " + "specified for repeated primitive fields.\n"); } TEST_F(ValidationErrorTest, OptionWrongType) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { " - " name: \"TestMessage\" " - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_STRING " - " options { uninterpreted_option { name { name_part: \"ctype\" " - " is_extension: false }" - " positive_int_value: 1 }" - " }" - " }" - "}\n", + "name: \"foo.proto\" " + "message_type { " + " name: \"TestMessage\" " + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_STRING " + " options { uninterpreted_option { name { name_part: \"ctype\" " + " is_extension: false }" + " positive_int_value: 1 }" + " }" + " }" + "}\n", - "foo.proto: TestMessage.foo: OPTION_VALUE: Value must be identifier for " - "enum-valued option \"google.protobuf.FieldOptions.ctype\".\n"); + "foo.proto: TestMessage.foo: OPTION_VALUE: Value must be identifier for " + "enum-valued option \"google.protobuf.FieldOptions.ctype\".\n"); } TEST_F(ValidationErrorTest, OptionExtendsAtomicType) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { " - " name: \"TestMessage\" " - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_STRING " - " options { uninterpreted_option { name { name_part: \"ctype\" " - " is_extension: false }" - " name { name_part: \"foo\" " - " is_extension: true }" - " positive_int_value: 1 }" - " }" - " }" - "}\n", + "name: \"foo.proto\" " + "message_type { " + " name: \"TestMessage\" " + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_STRING " + " options { uninterpreted_option { name { name_part: \"ctype\" " + " is_extension: false }" + " name { name_part: \"foo\" " + " is_extension: true }" + " positive_int_value: 1 }" + " }" + " }" + "}\n", - "foo.proto: TestMessage.foo: OPTION_NAME: Option \"ctype\" is an " - "atomic type, not a message.\n"); + "foo.proto: TestMessage.foo: OPTION_NAME: Option \"ctype\" is an " + "atomic type, not a message.\n"); } TEST_F(ValidationErrorTest, DupOption) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { " - " name: \"TestMessage\" " - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_UINT32 " - " options { uninterpreted_option { name { name_part: \"ctype\" " - " is_extension: false }" - " identifier_value: \"CORD\" }" - " uninterpreted_option { name { name_part: \"ctype\" " - " is_extension: false }" - " identifier_value: \"CORD\" }" - " }" - " }" - "}\n", + "name: \"foo.proto\" " + "message_type { " + " name: \"TestMessage\" " + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_UINT32 " + " options { uninterpreted_option { name { name_part: \"ctype\" " + " is_extension: false }" + " identifier_value: \"CORD\" }" + " uninterpreted_option { name { name_part: \"ctype\" " + " is_extension: false }" + " identifier_value: \"CORD\" }" + " }" + " }" + "}\n", - "foo.proto: TestMessage.foo: OPTION_NAME: Option \"ctype\" was " - "already set.\n"); + "foo.proto: TestMessage.foo: OPTION_NAME: Option \"ctype\" was " + "already set.\n"); } TEST_F(ValidationErrorTest, InvalidOptionName) { BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { " - " name: \"TestMessage\" " - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_BOOL " - " options { uninterpreted_option { " - " name { name_part: \"uninterpreted_option\" " - " is_extension: false }" - " positive_int_value: 1 " - " }" - " }" - " }" - "}\n", + "name: \"foo.proto\" " + "message_type { " + " name: \"TestMessage\" " + " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_BOOL " + " options { uninterpreted_option { " + " name { name_part: \"uninterpreted_option\" " + " is_extension: false }" + " positive_int_value: 1 " + " }" + " }" + " }" + "}\n", - "foo.proto: TestMessage.foo: OPTION_NAME: Option must not use " - "reserved name \"uninterpreted_option\".\n"); + "foo.proto: TestMessage.foo: OPTION_NAME: Option must not use " + "reserved name \"uninterpreted_option\".\n"); } TEST_F(ValidationErrorTest, RepeatedMessageOption) { BuildDescriptorMessagesInTestPool(); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "message_type: { name: \"Bar\" field: { " - " name: \"foo\" number: 1 label: LABEL_OPTIONAL type: TYPE_INT32 } " - "} " - "extension { name: \"bar\" number: 7672757 label: LABEL_REPEATED " - " type: TYPE_MESSAGE type_name: \"Bar\" " - " extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"bar\" " - " is_extension: true } " - " name { name_part: \"foo\" " - " is_extension: false } " - " positive_int_value: 1 } }", + "name: \"foo.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "message_type: { name: \"Bar\" field: { " + " name: \"foo\" number: 1 label: LABEL_OPTIONAL type: TYPE_INT32 } " + "} " + "extension { name: \"bar\" number: 7672757 label: LABEL_REPEATED " + " type: TYPE_MESSAGE type_name: \"Bar\" " + " extendee: \"google.protobuf.FileOptions\" }" + "options { uninterpreted_option { name { name_part: \"bar\" " + " is_extension: true } " + " name { name_part: \"foo\" " + " is_extension: false } " + " positive_int_value: 1 } }", - "foo.proto: foo.proto: OPTION_NAME: Option field \"(bar)\" is a " - "repeated message. Repeated message options must be initialized " - "using an aggregate value.\n"); + "foo.proto: foo.proto: OPTION_NAME: Option field \"(bar)\" is a " + "repeated message. Repeated message options must be initialized " + "using an aggregate value.\n"); } TEST_F(ValidationErrorTest, ResolveUndefinedOption) { @@ -5120,313 +5137,338 @@ TEST_F(ValidationErrorTest, ResolveUndefinedOption) { BuildDescriptorMessagesInTestPool(); BuildFile( - "name: \"foo.proto\" " - "package: \"baz\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "message_type: { name: \"Bar\" field: { " - " name: \"foo\" number: 1 label: LABEL_OPTIONAL type: TYPE_INT32 } " - "} " - "extension { name: \"bar\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_MESSAGE type_name: \"Bar\" " - " extendee: \"google.protobuf.FileOptions\" }"); + "name: \"foo.proto\" " + "package: \"baz\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "message_type: { name: \"Bar\" field: { " + " name: \"foo\" number: 1 label: LABEL_OPTIONAL type: TYPE_INT32 } " + "} " + "extension { name: \"bar\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_MESSAGE type_name: \"Bar\" " + " extendee: \"google.protobuf.FileOptions\" }"); BuildFileWithErrors( - "name: \"qux.proto\" " - "package: \"qux.baz\" " - "options { uninterpreted_option { name { name_part: \"baz.bar\" " - " is_extension: true } " - " name { name_part: \"foo\" " - " is_extension: false } " - " positive_int_value: 1 } }", + "name: \"qux.proto\" " + "package: \"qux.baz\" " + "options { uninterpreted_option { name { name_part: \"baz.bar\" " + " is_extension: true } " + " name { name_part: \"foo\" " + " is_extension: false } " + " positive_int_value: 1 } }", - "qux.proto: qux.proto: OPTION_NAME: Option \"(baz.bar)\" is resolved to " - "\"(qux.baz.bar)\"," - " which is not defined. The innermost scope is searched first in name " - "resolution. Consider using a leading '.'(i.e., \"(.baz.bar)\") to start " - "from the outermost scope.\n"); + "qux.proto: qux.proto: OPTION_NAME: Option \"(baz.bar)\" is resolved to " + "\"(qux.baz.bar)\"," + " which is not defined. The innermost scope is searched first in name " + "resolution. Consider using a leading '.'(i.e., \"(.baz.bar)\") to start " + "from the outermost scope.\n"); } TEST_F(ValidationErrorTest, UnknownOption) { BuildFileWithErrors( - "name: \"qux.proto\" " - "package: \"qux.baz\" " - "options { uninterpreted_option { name { name_part: \"baaz.bar\" " - " is_extension: true } " - " name { name_part: \"foo\" " - " is_extension: false } " - " positive_int_value: 1 } }", + "name: \"qux.proto\" " + "package: \"qux.baz\" " + "options { uninterpreted_option { name { name_part: \"baaz.bar\" " + " is_extension: true } " + " name { name_part: \"foo\" " + " is_extension: false } " + " positive_int_value: 1 } }", - "qux.proto: qux.proto: OPTION_NAME: Option \"(baaz.bar)\" unknown.\n"); + "qux.proto: qux.proto: OPTION_NAME: Option \"(baaz.bar)\" unknown. " + "Ensure " + "that your proto definition file imports the proto which defines the " + "option.\n"); } TEST_F(ValidationErrorTest, CustomOptionConflictingFieldNumber) { BuildDescriptorMessagesInTestPool(); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo1\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_INT32 extendee: \"google.protobuf.FieldOptions\" }" - "extension { name: \"foo2\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_INT32 extendee: \"google.protobuf.FieldOptions\" }", + "name: \"foo.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "extension { name: \"foo1\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_INT32 extendee: \"google.protobuf.FieldOptions\" }" + "extension { name: \"foo2\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_INT32 extendee: \"google.protobuf.FieldOptions\" }", - "foo.proto: foo2: NUMBER: Extension number 7672757 has already been used " - "in \"google.protobuf.FieldOptions\" by extension \"foo1\".\n"); + "foo.proto: foo2: NUMBER: Extension number 7672757 has already been used " + "in \"google.protobuf.FieldOptions\" by extension \"foo1\".\n"); } TEST_F(ValidationErrorTest, Int32OptionValueOutOfPositiveRange) { BuildDescriptorMessagesInTestPool(); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_INT32 extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " positive_int_value: 0x80000000 } " - "}", + "name: \"foo.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_INT32 extendee: \"google.protobuf.FileOptions\" }" + "options { uninterpreted_option { name { name_part: \"foo\" " + " is_extension: true } " + " positive_int_value: 0x80000000 } " + "}", - "foo.proto: foo.proto: OPTION_VALUE: Value out of range " - "for int32 option \"foo\".\n"); + "foo.proto: foo.proto: OPTION_VALUE: Value out of range " + "for int32 option \"foo\".\n"); } TEST_F(ValidationErrorTest, Int32OptionValueOutOfNegativeRange) { BuildDescriptorMessagesInTestPool(); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_INT32 extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " negative_int_value: -0x80000001 } " - "}", + "name: \"foo.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_INT32 extendee: \"google.protobuf.FileOptions\" }" + "options { uninterpreted_option { name { name_part: \"foo\" " + " is_extension: true } " + " negative_int_value: -0x80000001 } " + "}", - "foo.proto: foo.proto: OPTION_VALUE: Value out of range " - "for int32 option \"foo\".\n"); + "foo.proto: foo.proto: OPTION_VALUE: Value out of range " + "for int32 option \"foo\".\n"); } TEST_F(ValidationErrorTest, Int32OptionValueIsNotPositiveInt) { BuildDescriptorMessagesInTestPool(); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_INT32 extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " string_value: \"5\" } }", + "name: \"foo.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_INT32 extendee: \"google.protobuf.FileOptions\" }" + "options { uninterpreted_option { name { name_part: \"foo\" " + " is_extension: true } " + " string_value: \"5\" } }", - "foo.proto: foo.proto: OPTION_VALUE: Value must be integer " - "for int32 option \"foo\".\n"); + "foo.proto: foo.proto: OPTION_VALUE: Value must be integer " + "for int32 option \"foo\".\n"); } TEST_F(ValidationErrorTest, Int64OptionValueOutOfRange) { BuildDescriptorMessagesInTestPool(); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_INT64 extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " positive_int_value: 0x8000000000000000 } " - "}", + "name: \"foo.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_INT64 extendee: \"google.protobuf.FileOptions\" }" + "options { uninterpreted_option { name { name_part: \"foo\" " + " is_extension: true } " + " positive_int_value: 0x8000000000000000 " + "} " + "}", - "foo.proto: foo.proto: OPTION_VALUE: Value out of range " - "for int64 option \"foo\".\n"); + "foo.proto: foo.proto: OPTION_VALUE: Value out of range " + "for int64 option \"foo\".\n"); } TEST_F(ValidationErrorTest, Int64OptionValueIsNotPositiveInt) { BuildDescriptorMessagesInTestPool(); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_INT64 extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " identifier_value: \"5\" } }", + "name: \"foo.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_INT64 extendee: \"google.protobuf.FileOptions\" }" + "options { uninterpreted_option { name { name_part: \"foo\" " + " is_extension: true } " + " identifier_value: \"5\" } }", - "foo.proto: foo.proto: OPTION_VALUE: Value must be integer " - "for int64 option \"foo\".\n"); + "foo.proto: foo.proto: OPTION_VALUE: Value must be integer " + "for int64 option \"foo\".\n"); } TEST_F(ValidationErrorTest, UInt32OptionValueOutOfRange) { BuildDescriptorMessagesInTestPool(); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_UINT32 extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " positive_int_value: 0x100000000 } }", + "name: \"foo.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_UINT32 extendee: \"google.protobuf.FileOptions\" }" + "options { uninterpreted_option { name { name_part: \"foo\" " + " is_extension: true } " + " positive_int_value: 0x100000000 } }", - "foo.proto: foo.proto: OPTION_VALUE: Value out of range " - "for uint32 option \"foo\".\n"); + "foo.proto: foo.proto: OPTION_VALUE: Value out of range " + "for uint32 option \"foo\".\n"); } TEST_F(ValidationErrorTest, UInt32OptionValueIsNotPositiveInt) { BuildDescriptorMessagesInTestPool(); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_UINT32 extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " double_value: -5.6 } }", + "name: \"foo.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_UINT32 extendee: \"google.protobuf.FileOptions\" }" + "options { uninterpreted_option { name { name_part: \"foo\" " + " is_extension: true } " + " double_value: -5.6 } }", - "foo.proto: foo.proto: OPTION_VALUE: Value must be non-negative integer " - "for uint32 option \"foo\".\n"); + "foo.proto: foo.proto: OPTION_VALUE: Value must be non-negative integer " + "for uint32 option \"foo\".\n"); } TEST_F(ValidationErrorTest, UInt64OptionValueIsNotPositiveInt) { BuildDescriptorMessagesInTestPool(); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_UINT64 extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " negative_int_value: -5 } }", + "name: \"foo.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_UINT64 extendee: \"google.protobuf.FileOptions\" }" + "options { uninterpreted_option { name { name_part: \"foo\" " + " is_extension: true } " + " negative_int_value: -5 } }", - "foo.proto: foo.proto: OPTION_VALUE: Value must be non-negative integer " - "for uint64 option \"foo\".\n"); + "foo.proto: foo.proto: OPTION_VALUE: Value must be non-negative integer " + "for uint64 option \"foo\".\n"); } TEST_F(ValidationErrorTest, FloatOptionValueIsNotNumber) { BuildDescriptorMessagesInTestPool(); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_FLOAT extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " string_value: \"bar\" } }", + "name: \"foo.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_FLOAT extendee: \"google.protobuf.FileOptions\" }" + "options { uninterpreted_option { name { name_part: \"foo\" " + " is_extension: true } " + " string_value: \"bar\" } }", - "foo.proto: foo.proto: OPTION_VALUE: Value must be number " - "for float option \"foo\".\n"); + "foo.proto: foo.proto: OPTION_VALUE: Value must be number " + "for float option \"foo\".\n"); } TEST_F(ValidationErrorTest, DoubleOptionValueIsNotNumber) { BuildDescriptorMessagesInTestPool(); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_DOUBLE extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " string_value: \"bar\" } }", + "name: \"foo.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_DOUBLE extendee: \"google.protobuf.FileOptions\" }" + "options { uninterpreted_option { name { name_part: \"foo\" " + " is_extension: true } " + " string_value: \"bar\" } }", - "foo.proto: foo.proto: OPTION_VALUE: Value must be number " - "for double option \"foo\".\n"); + "foo.proto: foo.proto: OPTION_VALUE: Value must be number " + "for double option \"foo\".\n"); } TEST_F(ValidationErrorTest, BoolOptionValueIsNotTrueOrFalse) { BuildDescriptorMessagesInTestPool(); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_BOOL extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " identifier_value: \"bar\" } }", + "name: \"foo.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_BOOL extendee: \"google.protobuf.FileOptions\" }" + "options { uninterpreted_option { name { name_part: \"foo\" " + " is_extension: true } " + " identifier_value: \"bar\" } }", - "foo.proto: foo.proto: OPTION_VALUE: Value must be \"true\" or \"false\" " - "for boolean option \"foo\".\n"); + "foo.proto: foo.proto: OPTION_VALUE: Value must be \"true\" or \"false\" " + "for boolean option \"foo\".\n"); } TEST_F(ValidationErrorTest, EnumOptionValueIsNotIdentifier) { BuildDescriptorMessagesInTestPool(); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "enum_type { name: \"FooEnum\" value { name: \"BAR\" number: 1 } " - " value { name: \"BAZ\" number: 2 } }" - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_ENUM type_name: \"FooEnum\" " - " extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " string_value: \"QUUX\" } }", + "name: \"foo.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "enum_type { name: \"FooEnum\" value { name: \"BAR\" number: 1 } " + " value { name: \"BAZ\" number: 2 } }" + "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_ENUM type_name: \"FooEnum\" " + " extendee: \"google.protobuf.FileOptions\" }" + "options { uninterpreted_option { name { name_part: \"foo\" " + " is_extension: true } " + " string_value: \"QUUX\" } }", - "foo.proto: foo.proto: OPTION_VALUE: Value must be identifier for " - "enum-valued option \"foo\".\n"); + "foo.proto: foo.proto: OPTION_VALUE: Value must be identifier for " + "enum-valued option \"foo\".\n"); } TEST_F(ValidationErrorTest, EnumOptionValueIsNotEnumValueName) { BuildDescriptorMessagesInTestPool(); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "enum_type { name: \"FooEnum\" value { name: \"BAR\" number: 1 } " - " value { name: \"BAZ\" number: 2 } }" - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_ENUM type_name: \"FooEnum\" " - " extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " identifier_value: \"QUUX\" } }", + "name: \"foo.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "enum_type { name: \"FooEnum\" value { name: \"BAR\" number: 1 } " + " value { name: \"BAZ\" number: 2 } }" + "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_ENUM type_name: \"FooEnum\" " + " extendee: \"google.protobuf.FileOptions\" }" + "options { uninterpreted_option { name { name_part: \"foo\" " + " is_extension: true } " + " identifier_value: \"QUUX\" } }", - "foo.proto: foo.proto: OPTION_VALUE: Enum type \"FooEnum\" has no value " - "named \"QUUX\" for option \"foo\".\n"); + "foo.proto: foo.proto: OPTION_VALUE: Enum type \"FooEnum\" has no value " + "named \"QUUX\" for option \"foo\".\n"); } TEST_F(ValidationErrorTest, EnumOptionValueIsSiblingEnumValueName) { BuildDescriptorMessagesInTestPool(); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "enum_type { name: \"FooEnum1\" value { name: \"BAR\" number: 1 } " - " value { name: \"BAZ\" number: 2 } }" - "enum_type { name: \"FooEnum2\" value { name: \"QUX\" number: 1 } " - " value { name: \"QUUX\" number: 2 } }" - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_ENUM type_name: \"FooEnum1\" " - " extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " identifier_value: \"QUUX\" } }", + "name: \"foo.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "enum_type { name: \"FooEnum1\" value { name: \"BAR\" number: 1 } " + " value { name: \"BAZ\" number: 2 } }" + "enum_type { name: \"FooEnum2\" value { name: \"QUX\" number: 1 } " + " value { name: \"QUUX\" number: 2 } }" + "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_ENUM type_name: \"FooEnum1\" " + " extendee: \"google.protobuf.FileOptions\" }" + "options { uninterpreted_option { name { name_part: \"foo\" " + " is_extension: true } " + " identifier_value: \"QUUX\" } }", - "foo.proto: foo.proto: OPTION_VALUE: Enum type \"FooEnum1\" has no value " - "named \"QUUX\" for option \"foo\". This appears to be a value from a " - "sibling type.\n"); + "foo.proto: foo.proto: OPTION_VALUE: Enum type \"FooEnum1\" has no value " + "named \"QUUX\" for option \"foo\". This appears to be a value from a " + "sibling type.\n"); } TEST_F(ValidationErrorTest, StringOptionValueIsNotString) { BuildDescriptorMessagesInTestPool(); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_STRING extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " identifier_value: \"QUUX\" } }", + "name: \"foo.proto\" " + "dependency: \"google/protobuf/descriptor.proto\" " + "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " + " type: TYPE_STRING extendee: \"google.protobuf.FileOptions\" }" + "options { uninterpreted_option { name { name_part: \"foo\" " + " is_extension: true } " + " identifier_value: \"QUUX\" } }", - "foo.proto: foo.proto: OPTION_VALUE: Value must be quoted string for " - "string option \"foo\".\n"); + "foo.proto: foo.proto: OPTION_VALUE: Value must be quoted string " + "for " + "string option \"foo\".\n"); +} + +TEST_F(ValidationErrorTest, JsonNameOptionOnExtensions) { + BuildFileWithErrors( + "name: \"foo.proto\" " + "package: \"foo\" " + "message_type {" + " name: \"Foo\"" + " extension_range { start: 10 end: 20 }" + "}" + "extension {" + " name: \"value\"" + " number: 10" + " label: LABEL_OPTIONAL" + " type: TYPE_INT32" + " extendee: \"foo.Foo\"" + " json_name: \"myName\"" + "}", + "foo.proto: foo.value: OPTION_NAME: option json_name is not allowed on " + "extension fields.\n"); } TEST_F(ValidationErrorTest, DuplicateExtensionFieldNumber) { @@ -5451,7 +5493,7 @@ TEST_F(ValidationErrorTest, DuplicateExtensionFieldNumber) { // Helper function for tests that check for aggregate value parsing // errors. The "value" argument is embedded inside the // "uninterpreted_option" portion of the result. -static string EmbedAggregateValue(const char* value) { +static std::string EmbedAggregateValue(const char* value) { return strings::Substitute( "name: \"foo.proto\" " "dependency: \"google/protobuf/descriptor.proto\" " @@ -5496,60 +5538,60 @@ TEST_F(ValidationErrorTest, AggregateValueUnknownFields) { TEST_F(ValidationErrorTest, NotLiteImportsLite) { BuildFile( - "name: \"bar.proto\" " - "options { optimize_for: LITE_RUNTIME } "); + "name: \"bar.proto\" " + "options { optimize_for: LITE_RUNTIME } "); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"bar.proto\" ", + "name: \"foo.proto\" " + "dependency: \"bar.proto\" ", - "foo.proto: foo.proto: OTHER: Files that do not use optimize_for = " + "foo.proto: bar.proto: IMPORT: Files that do not use optimize_for = " "LITE_RUNTIME cannot import files which do use this option. This file " "is not lite, but it imports \"bar.proto\" which is.\n"); } TEST_F(ValidationErrorTest, LiteExtendsNotLite) { BuildFile( - "name: \"bar.proto\" " - "message_type: {" - " name: \"Bar\"" - " extension_range { start: 1 end: 1000 }" - "}"); + "name: \"bar.proto\" " + "message_type: {" + " name: \"Bar\"" + " extension_range { start: 1 end: 1000 }" + "}"); BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"bar.proto\" " - "options { optimize_for: LITE_RUNTIME } " - "extension { name: \"ext\" number: 123 label: LABEL_OPTIONAL " - " type: TYPE_INT32 extendee: \"Bar\" }", + "name: \"foo.proto\" " + "dependency: \"bar.proto\" " + "options { optimize_for: LITE_RUNTIME } " + "extension { name: \"ext\" number: 123 label: LABEL_OPTIONAL " + " type: TYPE_INT32 extendee: \"Bar\" }", - "foo.proto: ext: EXTENDEE: Extensions to non-lite types can only be " + "foo.proto: ext: EXTENDEE: Extensions to non-lite types can only be " "declared in non-lite files. Note that you cannot extend a non-lite " "type to contain a lite type, but the reverse is allowed.\n"); } TEST_F(ValidationErrorTest, NoLiteServices) { BuildFileWithErrors( - "name: \"foo.proto\" " - "options {" - " optimize_for: LITE_RUNTIME" - " cc_generic_services: true" - " java_generic_services: true" - "} " - "service { name: \"Foo\" }", + "name: \"foo.proto\" " + "options {" + " optimize_for: LITE_RUNTIME" + " cc_generic_services: true" + " java_generic_services: true" + "} " + "service { name: \"Foo\" }", - "foo.proto: Foo: NAME: Files with optimize_for = LITE_RUNTIME cannot " - "define services unless you set both options cc_generic_services and " - "java_generic_sevices to false.\n"); + "foo.proto: Foo: NAME: Files with optimize_for = LITE_RUNTIME cannot " + "define services unless you set both options cc_generic_services and " + "java_generic_sevices to false.\n"); BuildFile( - "name: \"bar.proto\" " - "options {" - " optimize_for: LITE_RUNTIME" - " cc_generic_services: false" - " java_generic_services: false" - "} " - "service { name: \"Bar\" }"); + "name: \"bar.proto\" " + "options {" + " optimize_for: LITE_RUNTIME" + " cc_generic_services: false" + " java_generic_services: false" + "} " + "service { name: \"Bar\" }"); } TEST_F(ValidationErrorTest, RollbackAfterError) { @@ -5558,47 +5600,47 @@ TEST_F(ValidationErrorTest, RollbackAfterError) { // before the undefined type error is noticed. The DescriptorPool will then // have to roll everything back. BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:1 }" - "} " - "enum_type {" - " name: \"TestEnum\"" - " value { name:\"BAR\" number:1 }" - "} " - "service {" - " name: \"TestService\"" - " method {" - " name: \"Baz\"" - " input_type: \"NoSuchType\"" // error - " output_type: \"TestMessage\"" - " }" - "}", + "name: \"foo.proto\" " + "message_type {" + " name: \"TestMessage\"" + " field { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:1 }" + "} " + "enum_type {" + " name: \"TestEnum\"" + " value { name:\"BAR\" number:1 }" + "} " + "service {" + " name: \"TestService\"" + " method {" + " name: \"Baz\"" + " input_type: \"NoSuchType\"" // error + " output_type: \"TestMessage\"" + " }" + "}", - "foo.proto: TestService.Baz: INPUT_TYPE: \"NoSuchType\" is not defined.\n" - ); + "foo.proto: TestService.Baz: INPUT_TYPE: \"NoSuchType\" is not defined.\n" + ); // Make sure that if we build the same file again with the error fixed, // it works. If the above rollback was incomplete, then some symbols will // be left defined, and this second attempt will fail since it tries to // re-define the same symbols. BuildFile( - "name: \"foo.proto\" " - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:1 }" - "} " - "enum_type {" - " name: \"TestEnum\"" - " value { name:\"BAR\" number:1 }" - "} " - "service {" - " name: \"TestService\"" - " method { name:\"Baz\"" - " input_type:\"TestMessage\"" - " output_type:\"TestMessage\" }" - "}"); + "name: \"foo.proto\" " + "message_type {" + " name: \"TestMessage\"" + " field { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:1 }" + "} " + "enum_type {" + " name: \"TestEnum\"" + " value { name:\"BAR\" number:1 }" + "} " + "service {" + " name: \"TestService\"" + " method { name:\"Baz\"" + " input_type:\"TestMessage\"" + " output_type:\"TestMessage\" }" + "}"); } TEST_F(ValidationErrorTest, ErrorsReportedToLogError) { @@ -5606,13 +5648,13 @@ TEST_F(ValidationErrorTest, ErrorsReportedToLogError) { // provided. FileDescriptorProto file_proto; - ASSERT_TRUE(TextFormat::ParseFromString( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" } " - "message_type { name: \"Foo\" } ", - &file_proto)); + ASSERT_TRUE( + TextFormat::ParseFromString("name: \"foo.proto\" " + "message_type { name: \"Foo\" } " + "message_type { name: \"Foo\" } ", + &file_proto)); - std::vector errors; + std::vector errors; { ScopedMemoryLog log; @@ -5628,50 +5670,50 @@ TEST_F(ValidationErrorTest, ErrorsReportedToLogError) { TEST_F(ValidationErrorTest, DisallowEnumAlias) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type {" - " name: \"Bar\"" - " value { name:\"ENUM_A\" number:0 }" - " value { name:\"ENUM_B\" number:0 }" - "}", - "foo.proto: Bar: NUMBER: " - "\"ENUM_B\" uses the same enum value as \"ENUM_A\". " - "If this is intended, set 'option allow_alias = true;' to the enum " - "definition.\n"); + "name: \"foo.proto\" " + "enum_type {" + " name: \"Bar\"" + " value { name:\"ENUM_A\" number:0 }" + " value { name:\"ENUM_B\" number:0 }" + "}", + "foo.proto: Bar: NUMBER: " + "\"ENUM_B\" uses the same enum value as \"ENUM_A\". " + "If this is intended, set 'option allow_alias = true;' to the enum " + "definition.\n"); } TEST_F(ValidationErrorTest, AllowEnumAlias) { BuildFile( - "name: \"foo.proto\" " - "enum_type {" - " name: \"Bar\"" - " value { name:\"ENUM_A\" number:0 }" - " value { name:\"ENUM_B\" number:0 }" - " options { allow_alias: true }" - "}"); + "name: \"foo.proto\" " + "enum_type {" + " name: \"Bar\"" + " value { name:\"ENUM_A\" number:0 }" + " value { name:\"ENUM_B\" number:0 }" + " options { allow_alias: true }" + "}"); } TEST_F(ValidationErrorTest, UnusedImportWarning) { pool_.AddUnusedImportTrackFile("bar.proto"); BuildFile( - "name: \"bar.proto\" " - "message_type { name: \"Bar\" }"); + "name: \"bar.proto\" " + "message_type { name: \"Bar\" }"); pool_.AddUnusedImportTrackFile("base.proto"); BuildFile( - "name: \"base.proto\" " - "message_type { name: \"Base\" }"); + "name: \"base.proto\" " + "message_type { name: \"Base\" }"); pool_.AddUnusedImportTrackFile("baz.proto"); BuildFile( - "name: \"baz.proto\" " - "message_type { name: \"Baz\" }"); + "name: \"baz.proto\" " + "message_type { name: \"Baz\" }"); pool_.AddUnusedImportTrackFile("public.proto"); BuildFile( - "name: \"public.proto\" " - "dependency: \"bar.proto\"" - "public_dependency: 0"); + "name: \"public.proto\" " + "dependency: \"bar.proto\"" + "public_dependency: 0"); // // forward.proto // import "base.proto" // No warning: Base message is used. @@ -5684,17 +5726,18 @@ TEST_F(ValidationErrorTest, UnusedImportWarning) { // pool_.AddUnusedImportTrackFile("forward.proto"); BuildFileWithWarnings( - "name: \"forward.proto\"" - "dependency: \"base.proto\"" - "dependency: \"bar.proto\"" - "dependency: \"baz.proto\"" - "dependency: \"public.proto\"" - "public_dependency: 2 " - "message_type {" - " name: \"Forward\"" - " field { name:\"base\" number:1 label:LABEL_OPTIONAL type_name:\"Base\" }" - "}", - "forward.proto: bar.proto: OTHER: Import bar.proto but not used.\n"); + "name: \"forward.proto\"" + "dependency: \"base.proto\"" + "dependency: \"bar.proto\"" + "dependency: \"baz.proto\"" + "dependency: \"public.proto\"" + "public_dependency: 2 " + "message_type {" + " name: \"Forward\"" + " field { name:\"base\" number:1 label:LABEL_OPTIONAL " + "type_name:\"Base\" }" + "}", + "forward.proto: bar.proto: IMPORT: Import bar.proto but not used.\n"); } namespace { @@ -5725,7 +5768,7 @@ void FillValidMapEntry(FileDescriptorProto* file_proto) { file_proto)); } static const char* kMapEntryErrorMessage = - "foo.proto: Foo.foo_map: OTHER: map_entry should not be set explicitly. " + "foo.proto: Foo.foo_map: TYPE: map_entry should not be set explicitly. " "Use map instead.\n"; static const char* kMapEntryKeyTypeErrorMessage = "foo.proto: Foo.foo_map: TYPE: Key in map fields cannot be float/double, " @@ -5829,9 +5872,9 @@ TEST_F(ValidationErrorTest, MapEntryDifferentContainingType) { TEST_F(ValidationErrorTest, MapEntryKeyName) { FileDescriptorProto file_proto; FillValidMapEntry(&file_proto); - FieldDescriptorProto* key = file_proto.mutable_message_type(0) - ->mutable_nested_type(0) - ->mutable_field(0); + FieldDescriptorProto* key = + file_proto.mutable_message_type(0)->mutable_nested_type(0)->mutable_field( + 0); key->set_name("Key"); BuildFileWithErrors(file_proto.DebugString(), kMapEntryErrorMessage); } @@ -5839,9 +5882,9 @@ TEST_F(ValidationErrorTest, MapEntryKeyName) { TEST_F(ValidationErrorTest, MapEntryKeyLabel) { FileDescriptorProto file_proto; FillValidMapEntry(&file_proto); - FieldDescriptorProto* key = file_proto.mutable_message_type(0) - ->mutable_nested_type(0) - ->mutable_field(0); + FieldDescriptorProto* key = + file_proto.mutable_message_type(0)->mutable_nested_type(0)->mutable_field( + 0); key->set_label(FieldDescriptorProto::LABEL_REQUIRED); BuildFileWithErrors(file_proto.DebugString(), kMapEntryErrorMessage); } @@ -5849,9 +5892,9 @@ TEST_F(ValidationErrorTest, MapEntryKeyLabel) { TEST_F(ValidationErrorTest, MapEntryKeyNumber) { FileDescriptorProto file_proto; FillValidMapEntry(&file_proto); - FieldDescriptorProto* key = file_proto.mutable_message_type(0) - ->mutable_nested_type(0) - ->mutable_field(0); + FieldDescriptorProto* key = + file_proto.mutable_message_type(0)->mutable_nested_type(0)->mutable_field( + 0); key->set_number(3); BuildFileWithErrors(file_proto.DebugString(), kMapEntryErrorMessage); } @@ -5859,9 +5902,9 @@ TEST_F(ValidationErrorTest, MapEntryKeyNumber) { TEST_F(ValidationErrorTest, MapEntryValueName) { FileDescriptorProto file_proto; FillValidMapEntry(&file_proto); - FieldDescriptorProto* value = file_proto.mutable_message_type(0) - ->mutable_nested_type(0) - ->mutable_field(1); + FieldDescriptorProto* value = + file_proto.mutable_message_type(0)->mutable_nested_type(0)->mutable_field( + 1); value->set_name("Value"); BuildFileWithErrors(file_proto.DebugString(), kMapEntryErrorMessage); } @@ -5869,9 +5912,9 @@ TEST_F(ValidationErrorTest, MapEntryValueName) { TEST_F(ValidationErrorTest, MapEntryValueLabel) { FileDescriptorProto file_proto; FillValidMapEntry(&file_proto); - FieldDescriptorProto* value = file_proto.mutable_message_type(0) - ->mutable_nested_type(0) - ->mutable_field(1); + FieldDescriptorProto* value = + file_proto.mutable_message_type(0)->mutable_nested_type(0)->mutable_field( + 1); value->set_label(FieldDescriptorProto::LABEL_REQUIRED); BuildFileWithErrors(file_proto.DebugString(), kMapEntryErrorMessage); } @@ -5879,9 +5922,9 @@ TEST_F(ValidationErrorTest, MapEntryValueLabel) { TEST_F(ValidationErrorTest, MapEntryValueNumber) { FileDescriptorProto file_proto; FillValidMapEntry(&file_proto); - FieldDescriptorProto* value = file_proto.mutable_message_type(0) - ->mutable_nested_type(0) - ->mutable_field(1); + FieldDescriptorProto* value = + file_proto.mutable_message_type(0)->mutable_nested_type(0)->mutable_field( + 1); value->set_number(3); BuildFileWithErrors(file_proto.DebugString(), kMapEntryErrorMessage); } @@ -5889,9 +5932,9 @@ TEST_F(ValidationErrorTest, MapEntryValueNumber) { TEST_F(ValidationErrorTest, MapEntryKeyTypeFloat) { FileDescriptorProto file_proto; FillValidMapEntry(&file_proto); - FieldDescriptorProto* key = file_proto.mutable_message_type(0) - ->mutable_nested_type(0) - ->mutable_field(0); + FieldDescriptorProto* key = + file_proto.mutable_message_type(0)->mutable_nested_type(0)->mutable_field( + 0); key->set_type(FieldDescriptorProto::TYPE_FLOAT); BuildFileWithErrors(file_proto.DebugString(), kMapEntryKeyTypeErrorMessage); } @@ -5899,9 +5942,9 @@ TEST_F(ValidationErrorTest, MapEntryKeyTypeFloat) { TEST_F(ValidationErrorTest, MapEntryKeyTypeDouble) { FileDescriptorProto file_proto; FillValidMapEntry(&file_proto); - FieldDescriptorProto* key = file_proto.mutable_message_type(0) - ->mutable_nested_type(0) - ->mutable_field(0); + FieldDescriptorProto* key = + file_proto.mutable_message_type(0)->mutable_nested_type(0)->mutable_field( + 0); key->set_type(FieldDescriptorProto::TYPE_DOUBLE); BuildFileWithErrors(file_proto.DebugString(), kMapEntryKeyTypeErrorMessage); } @@ -5909,9 +5952,9 @@ TEST_F(ValidationErrorTest, MapEntryKeyTypeDouble) { TEST_F(ValidationErrorTest, MapEntryKeyTypeBytes) { FileDescriptorProto file_proto; FillValidMapEntry(&file_proto); - FieldDescriptorProto* key = file_proto.mutable_message_type(0) - ->mutable_nested_type(0) - ->mutable_field(0); + FieldDescriptorProto* key = + file_proto.mutable_message_type(0)->mutable_nested_type(0)->mutable_field( + 0); key->set_type(FieldDescriptorProto::TYPE_BYTES); BuildFileWithErrors(file_proto.DebugString(), kMapEntryKeyTypeErrorMessage); } @@ -5919,9 +5962,9 @@ TEST_F(ValidationErrorTest, MapEntryKeyTypeBytes) { TEST_F(ValidationErrorTest, MapEntryKeyTypeEnum) { FileDescriptorProto file_proto; FillValidMapEntry(&file_proto); - FieldDescriptorProto* key = file_proto.mutable_message_type(0) - ->mutable_nested_type(0) - ->mutable_field(0); + FieldDescriptorProto* key = + file_proto.mutable_message_type(0)->mutable_nested_type(0)->mutable_field( + 0); key->clear_type(); key->set_type_name("BarEnum"); EnumDescriptorProto* enum_proto = file_proto.add_enum_type(); @@ -5941,13 +5984,12 @@ TEST_F(ValidationErrorTest, MapEntryKeyTypeEnum) { "be enum types.\n"); } - TEST_F(ValidationErrorTest, MapEntryKeyTypeMessage) { FileDescriptorProto file_proto; FillValidMapEntry(&file_proto); - FieldDescriptorProto* key = file_proto.mutable_message_type(0) - ->mutable_nested_type(0) - ->mutable_field(0); + FieldDescriptorProto* key = + file_proto.mutable_message_type(0)->mutable_nested_type(0)->mutable_field( + 0); key->clear_type(); key->set_type_name(".Bar"); BuildFileWithErrors(file_proto.DebugString(), kMapEntryKeyTypeErrorMessage); @@ -6006,6 +6048,34 @@ TEST_F(ValidationErrorTest, MapEntryConflictsWithEnum) { "with an existing enum type.\n"); } +TEST_F(ValidationErrorTest, EnumValuesConflictWithDifferentCasing) { + BuildFileWithErrors( + "syntax: 'proto3'" + "name: 'foo.proto' " + "enum_type {" + " name: 'FooEnum' " + " value { name: 'BAR' number: 0 }" + " value { name: 'bar' number: 1 }" + "}", + "foo.proto: bar: NAME: Enum name bar has the same name as BAR " + "if you ignore case and strip out the enum name prefix (if any). " + "This is error-prone and can lead to undefined behavior. " + "Please avoid doing this. If you are using allow_alias, please assign " + "the same numeric value to both enums.\n"); + + // Not an error because both enums are mapped to the same value. + BuildFile( + "syntax: 'proto3'" + "name: 'foo.proto' " + "enum_type {" + " name: 'FooEnum' " + " options { allow_alias: true }" + " value { name: 'UNKNOWN' number: 0 }" + " value { name: 'BAR' number: 1 }" + " value { name: 'bar' number: 1 }" + "}"); +} + TEST_F(ValidationErrorTest, EnumValuesConflictWhenPrefixesStripped) { BuildFileWithErrors( "syntax: 'proto3'" @@ -6015,9 +6085,11 @@ TEST_F(ValidationErrorTest, EnumValuesConflictWhenPrefixesStripped) { " value { name: 'FOO_ENUM_BAZ' number: 0 }" " value { name: 'BAZ' number: 1 }" "}", - "foo.proto: BAZ: NAME: When enum name is stripped and label is " - "PascalCased (Baz), this value label conflicts with FOO_ENUM_BAZ. This " - "will make the proto fail to compile for some languages, such as C#.\n"); + "foo.proto: BAZ: NAME: Enum name BAZ has the same name as FOO_ENUM_BAZ " + "if you ignore case and strip out the enum name prefix (if any). " + "This is error-prone and can lead to undefined behavior. " + "Please avoid doing this. If you are using allow_alias, please assign " + "the same numeric value to both enums.\n"); BuildFileWithErrors( "syntax: 'proto3'" @@ -6027,9 +6099,11 @@ TEST_F(ValidationErrorTest, EnumValuesConflictWhenPrefixesStripped) { " value { name: 'FOOENUM_BAZ' number: 0 }" " value { name: 'BAZ' number: 1 }" "}", - "foo.proto: BAZ: NAME: When enum name is stripped and label is " - "PascalCased (Baz), this value label conflicts with FOOENUM_BAZ. This " - "will make the proto fail to compile for some languages, such as C#.\n"); + "foo.proto: BAZ: NAME: Enum name BAZ has the same name as FOOENUM_BAZ " + "if you ignore case and strip out the enum name prefix (if any). " + "This is error-prone and can lead to undefined behavior. " + "Please avoid doing this. If you are using allow_alias, please assign " + "the same numeric value to both enums.\n"); BuildFileWithErrors( "syntax: 'proto3'" @@ -6039,10 +6113,11 @@ TEST_F(ValidationErrorTest, EnumValuesConflictWhenPrefixesStripped) { " value { name: 'FOO_ENUM_BAR_BAZ' number: 0 }" " value { name: 'BAR__BAZ' number: 1 }" "}", - "foo.proto: BAR__BAZ: NAME: When enum name is stripped and label is " - "PascalCased (BarBaz), this value label conflicts with " - "FOO_ENUM_BAR_BAZ. This will make the proto fail to compile for some " - "languages, such as C#.\n"); + "foo.proto: BAR__BAZ: NAME: Enum name BAR__BAZ has the same name as " + "FOO_ENUM_BAR_BAZ if you ignore case and strip out the enum name prefix " + "(if any). This is error-prone and can lead to undefined behavior. " + "Please avoid doing this. If you are using allow_alias, please assign " + "the same numeric value to both enums.\n"); BuildFileWithErrors( "syntax: 'proto3'" @@ -6052,10 +6127,11 @@ TEST_F(ValidationErrorTest, EnumValuesConflictWhenPrefixesStripped) { " value { name: 'FOO_ENUM__BAR_BAZ' number: 0 }" " value { name: 'BAR_BAZ' number: 1 }" "}", - "foo.proto: BAR_BAZ: NAME: When enum name is stripped and label is " - "PascalCased (BarBaz), this value label conflicts with " - "FOO_ENUM__BAR_BAZ. This will make the proto fail to compile for some " - "languages, such as C#.\n"); + "foo.proto: BAR_BAZ: NAME: Enum name BAR_BAZ has the same name as " + "FOO_ENUM__BAR_BAZ if you ignore case and strip out the enum name prefix " + "(if any). This is error-prone and can lead to undefined behavior. " + "Please avoid doing this. If you are using allow_alias, please assign " + "the same numeric value to both enums.\n"); // This isn't an error because the underscore will cause the PascalCase to // differ by case (BarBaz vs. Barbaz). @@ -6095,31 +6171,31 @@ TEST_F(ValidationErrorTest, MapEntryConflictsWithOneof) { TEST_F(ValidationErrorTest, MapEntryUsesNoneZeroEnumDefaultValue) { BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type {" - " name: \"Bar\"" - " value { name:\"ENUM_A\" number:1 }" - " value { name:\"ENUM_B\" number:2 }" - "}" - "message_type {" - " name: 'Foo' " - " field { " - " name: 'foo_map' number: 1 label:LABEL_REPEATED " - " type_name: 'FooMapEntry' " - " } " - " nested_type { " - " name: 'FooMapEntry' " - " options { map_entry: true } " - " field { " - " name: 'key' number: 1 type:TYPE_INT32 label:LABEL_OPTIONAL " - " } " - " field { " - " name: 'value' number: 2 type_name:\"Bar\" label:LABEL_OPTIONAL " - " } " - " } " - "}", - "foo.proto: Foo.foo_map: " - "TYPE: Enum value in map must define 0 as the first value.\n"); + "name: \"foo.proto\" " + "enum_type {" + " name: \"Bar\"" + " value { name:\"ENUM_A\" number:1 }" + " value { name:\"ENUM_B\" number:2 }" + "}" + "message_type {" + " name: 'Foo' " + " field { " + " name: 'foo_map' number: 1 label:LABEL_REPEATED " + " type_name: 'FooMapEntry' " + " } " + " nested_type { " + " name: 'FooMapEntry' " + " options { map_entry: true } " + " field { " + " name: 'key' number: 1 type:TYPE_INT32 label:LABEL_OPTIONAL " + " } " + " field { " + " name: 'value' number: 2 type_name:\"Bar\" label:LABEL_OPTIONAL " + " } " + " } " + "}", + "foo.proto: Foo.foo_map: " + "TYPE: Enum value in map must define 0 as the first value.\n"); } TEST_F(ValidationErrorTest, Proto3RequiredFields) { @@ -6130,7 +6206,7 @@ TEST_F(ValidationErrorTest, Proto3RequiredFields) { " name: 'Foo' " " field { name:'foo' number:1 label:LABEL_REQUIRED type:TYPE_INT32 } " "}", - "foo.proto: Foo.foo: OTHER: Required fields are not allowed in " + "foo.proto: Foo.foo: TYPE: Required fields are not allowed in " "proto3.\n"); // applied to nested types as well. @@ -6144,7 +6220,7 @@ TEST_F(ValidationErrorTest, Proto3RequiredFields) { " field { name:'bar' number:1 label:LABEL_REQUIRED type:TYPE_INT32 } " " } " "}", - "foo.proto: Foo.Bar.bar: OTHER: Required fields are not allowed in " + "foo.proto: Foo.Bar.bar: TYPE: Required fields are not allowed in " "proto3.\n"); // optional and repeated fields are OK. @@ -6167,8 +6243,8 @@ TEST_F(ValidationErrorTest, ValidateProto3DefaultValue) { " field { name:'foo' number:1 label:LABEL_OPTIONAL type:TYPE_INT32 " " default_value: '1' }" "}", - "foo.proto: Foo.foo: OTHER: Explicit default values are not allowed in " - "proto3.\n"); + "foo.proto: Foo.foo: DEFAULT_VALUE: Explicit default values are not " + "allowed in proto3.\n"); BuildFileWithErrors( "name: 'foo.proto' " @@ -6181,8 +6257,8 @@ TEST_F(ValidationErrorTest, ValidateProto3DefaultValue) { " default_value: '1' }" " } " "}", - "foo.proto: Foo.Bar.bar: OTHER: Explicit default values are not allowed " - "in proto3.\n"); + "foo.proto: Foo.Bar.bar: DEFAULT_VALUE: Explicit default values are not " + "allowed in proto3.\n"); } TEST_F(ValidationErrorTest, ValidateProto3ExtensionRange) { @@ -6194,7 +6270,7 @@ TEST_F(ValidationErrorTest, ValidateProto3ExtensionRange) { " field { name:'foo' number:1 label:LABEL_OPTIONAL type:TYPE_INT32 } " " extension_range { start:10 end:100 } " "}", - "foo.proto: Foo: OTHER: Extension ranges are not allowed in " + "foo.proto: Foo: NUMBER: Extension ranges are not allowed in " "proto3.\n"); BuildFileWithErrors( @@ -6208,7 +6284,7 @@ TEST_F(ValidationErrorTest, ValidateProto3ExtensionRange) { " extension_range { start:10 end:100 } " " } " "}", - "foo.proto: Foo.Bar: OTHER: Extension ranges are not allowed in " + "foo.proto: Foo.Bar: NUMBER: Extension ranges are not allowed in " "proto3.\n"); } @@ -6220,7 +6296,7 @@ TEST_F(ValidationErrorTest, ValidateProto3MessageSetWireFormat) { " name: 'Foo' " " options { message_set_wire_format: true } " "}", - "foo.proto: Foo: OTHER: MessageSet is not supported " + "foo.proto: Foo: NAME: MessageSet is not supported " "in proto3.\n"); } @@ -6232,7 +6308,7 @@ TEST_F(ValidationErrorTest, ValidateProto3Enum) { " name: 'FooEnum' " " value { name: 'FOO_FOO' number:1 } " "}", - "foo.proto: FooEnum: OTHER: The first enum value must be " + "foo.proto: FooEnum: NUMBER: The first enum value must be " "zero in proto3.\n"); BuildFileWithErrors( @@ -6245,7 +6321,7 @@ TEST_F(ValidationErrorTest, ValidateProto3Enum) { " value { name: 'FOO_FOO' number:1 } " " } " "}", - "foo.proto: Foo.FooEnum: OTHER: The first enum value must be " + "foo.proto: Foo.FooEnum: NUMBER: The first enum value must be " "zero in proto3.\n"); // valid case. @@ -6337,7 +6413,7 @@ TEST_F(ValidationErrorTest, ValidateProto3Extension) { " name: 'bar' number: 1 label: LABEL_OPTIONAL type: TYPE_INT32 " " extendee: 'Container' " "}", - "bar.proto: bar: OTHER: Extensions in proto3 are only allowed for " + "bar.proto: bar: EXTENDEE: Extensions in proto3 are only allowed for " "defining options.\n"); } @@ -6352,7 +6428,7 @@ TEST_F(ValidationErrorTest, ValidateProto3JsonName) { " field { name:'name' number:1 label:LABEL_OPTIONAL type:TYPE_INT32 }" " field { name:'Name' number:2 label:LABEL_OPTIONAL type:TYPE_INT32 }" "}", - "foo.proto: Foo: OTHER: The JSON camel-case name of field \"Name\" " + "foo.proto: Foo: NAME: The JSON camel-case name of field \"Name\" " "conflicts with field \"name\". This is not allowed in proto3.\n"); // Underscores are ignored. BuildFileWithErrors( @@ -6363,7 +6439,7 @@ TEST_F(ValidationErrorTest, ValidateProto3JsonName) { " field { name:'ab' number:1 label:LABEL_OPTIONAL type:TYPE_INT32 }" " field { name:'_a__b_' number:2 label:LABEL_OPTIONAL type:TYPE_INT32 }" "}", - "foo.proto: Foo: OTHER: The JSON camel-case name of field \"_a__b_\" " + "foo.proto: Foo: NAME: The JSON camel-case name of field \"_a__b_\" " "conflicts with field \"ab\". This is not allowed in proto3.\n"); } @@ -6385,24 +6461,26 @@ class DatabaseBackedPoolTest : public testing::Test { SimpleDescriptorDatabase database_; virtual void SetUp() { + AddToDatabase( + &database_, + "name: 'foo.proto' " + "message_type { name:'Foo' extension_range { start: 1 end: 100 } } " + "enum_type { name:'TestEnum' value { name:'DUMMY' number:0 } } " + "service { name:'TestService' } "); AddToDatabase(&database_, - "name: 'foo.proto' " - "message_type { name:'Foo' extension_range { start: 1 end: 100 } } " - "enum_type { name:'TestEnum' value { name:'DUMMY' number:0 } } " - "service { name:'TestService' } "); - AddToDatabase(&database_, - "name: 'bar.proto' " - "dependency: 'foo.proto' " - "message_type { name:'Bar' } " - "extension { name:'foo_ext' extendee: '.Foo' number:5 " - " label:LABEL_OPTIONAL type:TYPE_INT32 } "); + "name: 'bar.proto' " + "dependency: 'foo.proto' " + "message_type { name:'Bar' } " + "extension { name:'foo_ext' extendee: '.Foo' number:5 " + " label:LABEL_OPTIONAL type:TYPE_INT32 } "); // Baz has an undeclared dependency on Foo. - AddToDatabase(&database_, - "name: 'baz.proto' " - "message_type { " - " name:'Baz' " - " field { name:'foo' number:1 label:LABEL_OPTIONAL type_name:'Foo' } " - "}"); + AddToDatabase( + &database_, + "name: 'baz.proto' " + "message_type { " + " name:'Baz' " + " field { name:'foo' number:1 label:LABEL_OPTIONAL type_name:'Foo' } " + "}"); } // We can't inject a file containing errors into a DescriptorPool, so we @@ -6413,7 +6491,7 @@ class DatabaseBackedPoolTest : public testing::Test { ~ErrorDescriptorDatabase() {} // implements DescriptorDatabase --------------------------------- - bool FindFileByName(const string& filename, + bool FindFileByName(const std::string& filename, FileDescriptorProto* output) { // error.proto and error2.proto cyclically import each other. if (filename == "error.proto") { @@ -6430,11 +6508,11 @@ class DatabaseBackedPoolTest : public testing::Test { return false; } } - bool FindFileContainingSymbol(const string& symbol_name, + bool FindFileContainingSymbol(const std::string& symbol_name, FileDescriptorProto* output) { return false; } - bool FindFileContainingExtension(const string& containing_type, + bool FindFileContainingExtension(const std::string& containing_type, int field_number, FileDescriptorProto* output) { return false; @@ -6446,7 +6524,7 @@ class DatabaseBackedPoolTest : public testing::Test { class CallCountingDatabase : public DescriptorDatabase { public: CallCountingDatabase(DescriptorDatabase* wrapped_db) - : wrapped_db_(wrapped_db) { + : wrapped_db_(wrapped_db) { Clear(); } ~CallCountingDatabase() {} @@ -6455,27 +6533,25 @@ class DatabaseBackedPoolTest : public testing::Test { int call_count_; - void Clear() { - call_count_ = 0; - } + void Clear() { call_count_ = 0; } // implements DescriptorDatabase --------------------------------- - bool FindFileByName(const string& filename, + bool FindFileByName(const std::string& filename, FileDescriptorProto* output) { ++call_count_; return wrapped_db_->FindFileByName(filename, output); } - bool FindFileContainingSymbol(const string& symbol_name, + bool FindFileContainingSymbol(const std::string& symbol_name, FileDescriptorProto* output) { ++call_count_; return wrapped_db_->FindFileContainingSymbol(symbol_name, output); } - bool FindFileContainingExtension(const string& containing_type, + bool FindFileContainingExtension(const std::string& containing_type, int field_number, FileDescriptorProto* output) { ++call_count_; - return wrapped_db_->FindFileContainingExtension( - containing_type, field_number, output); + return wrapped_db_->FindFileContainingExtension(containing_type, + field_number, output); } }; @@ -6485,21 +6561,21 @@ class DatabaseBackedPoolTest : public testing::Test { class FalsePositiveDatabase : public DescriptorDatabase { public: FalsePositiveDatabase(DescriptorDatabase* wrapped_db) - : wrapped_db_(wrapped_db) {} + : wrapped_db_(wrapped_db) {} ~FalsePositiveDatabase() {} DescriptorDatabase* wrapped_db_; // implements DescriptorDatabase --------------------------------- - bool FindFileByName(const string& filename, + bool FindFileByName(const std::string& filename, FileDescriptorProto* output) { return wrapped_db_->FindFileByName(filename, output); } - bool FindFileContainingSymbol(const string& symbol_name, + bool FindFileContainingSymbol(const std::string& symbol_name, FileDescriptorProto* output) { return FindFileByName("foo.proto", output); } - bool FindFileContainingExtension(const string& containing_type, + bool FindFileContainingExtension(const std::string& containing_type, int field_number, FileDescriptorProto* output) { return FindFileByName("foo.proto", output); @@ -6614,7 +6690,7 @@ TEST_F(DatabaseBackedPoolTest, ErrorWithoutErrorCollector) { ErrorDescriptorDatabase error_database; DescriptorPool pool(&error_database); - std::vector errors; + std::vector errors; { ScopedMemoryLog log; @@ -6632,13 +6708,13 @@ TEST_F(DatabaseBackedPoolTest, ErrorWithErrorCollector) { EXPECT_TRUE(pool.FindFileByName("error.proto") == NULL); EXPECT_EQ( - "error.proto: error.proto: OTHER: File recursively imports itself: " + "error.proto: error2.proto: IMPORT: File recursively imports itself: " "error.proto -> error2.proto -> error.proto\n" - "error2.proto: error2.proto: OTHER: Import \"error.proto\" was not " + "error2.proto: error.proto: IMPORT: Import \"error.proto\" was not " "found or had errors.\n" - "error.proto: error.proto: OTHER: Import \"error2.proto\" was not " + "error.proto: error2.proto: IMPORT: Import \"error2.proto\" was not " "found or had errors.\n", - error_collector.text_); + error_collector.text_); } TEST_F(DatabaseBackedPoolTest, UndeclaredDependencyOnUnbuiltType) { @@ -6648,10 +6724,10 @@ TEST_F(DatabaseBackedPoolTest, UndeclaredDependencyOnUnbuiltType) { DescriptorPool pool(&database_, &error_collector); EXPECT_TRUE(pool.FindMessageTypeByName("Baz") == NULL); EXPECT_EQ( - "baz.proto: Baz.foo: TYPE: \"Foo\" seems to be defined in \"foo.proto\", " - "which is not imported by \"baz.proto\". To use it here, please add " - "the necessary import.\n", - error_collector.text_); + "baz.proto: Baz.foo: TYPE: \"Foo\" seems to be defined in \"foo.proto\", " + "which is not imported by \"baz.proto\". To use it here, please add " + "the necessary import.\n", + error_collector.text_); } TEST_F(DatabaseBackedPoolTest, RollbackAfterError) { @@ -6673,12 +6749,12 @@ TEST_F(DatabaseBackedPoolTest, UnittestProto) { // thoroughly test all paths through DescriptorBuilder to insure that there // are no deadlocking problems when pool_->mutex_ is non-NULL. const FileDescriptor* original_file = - protobuf_unittest::TestAllTypes::descriptor()->file(); + protobuf_unittest::TestAllTypes::descriptor()->file(); DescriptorPoolDatabase database(*DescriptorPool::generated_pool()); DescriptorPool pool(&database); const FileDescriptor* file_from_database = - pool.FindFileByName(original_file->name()); + pool.FindFileByName(original_file->name()); ASSERT_TRUE(file_from_database != NULL); @@ -6692,8 +6768,7 @@ TEST_F(DatabaseBackedPoolTest, UnittestProto) { file_from_database_proto.DebugString()); // Also verify that CopyTo() did not omit any information. - EXPECT_EQ(original_file->DebugString(), - file_from_database->DebugString()); + EXPECT_EQ(original_file->DebugString(), file_from_database->DebugString()); } TEST_F(DatabaseBackedPoolTest, DoesntRetryDbUnnecessarily) { @@ -6777,7 +6852,7 @@ class ExponentialErrorDatabase : public DescriptorDatabase { ~ExponentialErrorDatabase() {} // implements DescriptorDatabase --------------------------------- - bool FindFileByName(const string& filename, + bool FindFileByName(const std::string& filename, FileDescriptorProto* output) { int file_num = -1; FullMatch(filename, "file", ".proto", &file_num); @@ -6787,7 +6862,7 @@ class ExponentialErrorDatabase : public DescriptorDatabase { return false; } } - bool FindFileContainingSymbol(const string& symbol_name, + bool FindFileContainingSymbol(const std::string& symbol_name, FileDescriptorProto* output) { int file_num = -1; FullMatch(symbol_name, "Message", "", &file_num); @@ -6797,25 +6872,23 @@ class ExponentialErrorDatabase : public DescriptorDatabase { return false; } } - bool FindFileContainingExtension(const string& containing_type, + bool FindFileContainingExtension(const std::string& containing_type, int field_number, FileDescriptorProto* output) { return false; } private: - void FullMatch(const string& name, - const string& begin_with, - const string& end_with, - int* file_num) { + void FullMatch(const std::string& name, const std::string& begin_with, + const std::string& end_with, int* file_num) { int begin_size = begin_with.size(); int end_size = end_with.size(); if (name.substr(0, begin_size) != begin_with || - name.substr(name.size()- end_size, end_size) != end_with) { + name.substr(name.size() - end_size, end_size) != end_with) { return; } - safe_strto32(name.substr(begin_size, name.size() - end_size - begin_size), - file_num); + safe_strto32( + name.substr(begin_size, name.size() - end_size - begin_size), file_num); } bool PopulateFile(int file_num, FileDescriptorProto* output) { @@ -6885,15 +6958,14 @@ class AbortingErrorCollector : public DescriptorPool::ErrorCollector { public: AbortingErrorCollector() {} - virtual void AddError( - const string &filename, - const string &element_name, - const Message *message, - ErrorLocation location, - const string &error_message) { + virtual void AddError(const std::string& filename, + const std::string& element_name, const Message* message, + ErrorLocation location, + const std::string& error_message) { GOOGLE_LOG(FATAL) << "AddError() called unexpectedly: " << filename << " [" << element_name << "]: " << error_message; } + private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(AbortingErrorCollector); }; @@ -6901,98 +6973,98 @@ class AbortingErrorCollector : public DescriptorPool::ErrorCollector { // A source tree containing only one file. class SingletonSourceTree : public compiler::SourceTree { public: - SingletonSourceTree(const string& filename, const string& contents) + SingletonSourceTree(const std::string& filename, const std::string& contents) : filename_(filename), contents_(contents) {} - virtual io::ZeroCopyInputStream* Open(const string& filename) { - return filename == filename_ ? - new io::ArrayInputStream(contents_.data(), contents_.size()) : NULL; + virtual io::ZeroCopyInputStream* Open(const std::string& filename) { + return filename == filename_ + ? new io::ArrayInputStream(contents_.data(), contents_.size()) + : NULL; } private: - const string filename_; - const string contents_; + const std::string filename_; + const std::string contents_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SingletonSourceTree); }; -const char *const kSourceLocationTestInput = - "syntax = \"proto2\";\n" - "option java_package = \"com.foo.bar\";\n" - "option (test_file_opt) = \"foobar\";\n" - "message A {\n" - " option (test_msg_opt) = \"foobar\";\n" - " optional int32 a = 1 [deprecated = true];\n" - " message B {\n" - " required double b = 1 [(test_field_opt) = \"foobar\"];\n" - " }\n" - " oneof c {\n" - " option (test_oneof_opt) = \"foobar\";\n" - " string d = 2;\n" - " string e = 3;\n" - " string f = 4;\n" - " }\n" - "}\n" - "enum Indecision {\n" - " option (test_enum_opt) = 21;\n" - " option (test_enum_opt) = 42;\n" - " option (test_enum_opt) = 63;\n" - " YES = 1 [(test_enumval_opt).a = 100];\n" - " NO = 2 [(test_enumval_opt) = {a:200}];\n" - " MAYBE = 3;\n" - "}\n" - "service S {\n" - " option (test_svc_opt) = {a:100};\n" - " option (test_svc_opt) = {a:200};\n" - " option (test_svc_opt) = {a:300};\n" - " rpc Method(A) returns (A.B);\n" - // Put an empty line here to make the source location range match. - "\n" - " rpc OtherMethod(A) returns (A) {\n" - " option deprecated = true;\n" - " option (test_method_opt) = \"foobar\";\n" - " }\n" - "}\n" - "message MessageWithExtensions {\n" - " extensions 1000 to 2000, 2001 to max [(test_ext_opt) = \"foobar\"];\n" - "}\n" - "extend MessageWithExtensions {\n" - " repeated int32 int32_extension = 1001 [packed=true];\n" - "}\n" - "message C {\n" - " extend MessageWithExtensions {\n" - " optional C message_extension = 1002;\n" - " }\n" - "}\n" - "import \"google/protobuf/descriptor.proto\";\n" - "extend google.protobuf.FileOptions {\n" - " optional string test_file_opt = 10101;\n" - "}\n" - "extend google.protobuf.MessageOptions {\n" - " optional string test_msg_opt = 10101;\n" - "}\n" - "extend google.protobuf.FieldOptions {\n" - " optional string test_field_opt = 10101;\n" - "}\n" - "extend google.protobuf.EnumOptions {\n" - " repeated int32 test_enum_opt = 10101;\n" - "}\n" - "extend google.protobuf.EnumValueOptions {\n" - " optional A test_enumval_opt = 10101;\n" - "}\n" - "extend google.protobuf.ServiceOptions {\n" - " repeated A test_svc_opt = 10101;\n" - "}\n" - "extend google.protobuf.MethodOptions {\n" - " optional string test_method_opt = 10101;\n" - "}\n" - "extend google.protobuf.OneofOptions {\n" - " optional string test_oneof_opt = 10101;\n" - "}\n" - "extend google.protobuf.ExtensionRangeOptions {\n" - " optional string test_ext_opt = 10101;\n" - "}\n" - ; +const char* const kSourceLocationTestInput = + "syntax = \"proto2\";\n" + "option java_package = \"com.foo.bar\";\n" + "option (test_file_opt) = \"foobar\";\n" + "message A {\n" + " option (test_msg_opt) = \"foobar\";\n" + " optional int32 a = 1 [deprecated = true];\n" + " message B {\n" + " required double b = 1 [(test_field_opt) = \"foobar\"];\n" + " }\n" + " oneof c {\n" + " option (test_oneof_opt) = \"foobar\";\n" + " string d = 2;\n" + " string e = 3;\n" + " string f = 4;\n" + " }\n" + "}\n" + "enum Indecision {\n" + " option (test_enum_opt) = 21;\n" + " option (test_enum_opt) = 42;\n" + " option (test_enum_opt) = 63;\n" + " YES = 1 [(test_enumval_opt).a = 100];\n" + " NO = 2 [(test_enumval_opt) = {a:200}];\n" + " MAYBE = 3;\n" + "}\n" + "service S {\n" + " option (test_svc_opt) = {a:100};\n" + " option (test_svc_opt) = {a:200};\n" + " option (test_svc_opt) = {a:300};\n" + " rpc Method(A) returns (A.B);\n" + // Put an empty line here to make the source location range match. + "\n" + " rpc OtherMethod(A) returns (A) {\n" + " option deprecated = true;\n" + " option (test_method_opt) = \"foobar\";\n" + " }\n" + "}\n" + "message MessageWithExtensions {\n" + " extensions 1000 to 2000, 2001 to max [(test_ext_opt) = \"foobar\"];\n" + "}\n" + "extend MessageWithExtensions {\n" + " repeated int32 int32_extension = 1001 [packed=true];\n" + "}\n" + "message C {\n" + " extend MessageWithExtensions {\n" + " optional C message_extension = 1002;\n" + " }\n" + "}\n" + "import \"google/protobuf/descriptor.proto\";\n" + "extend google.protobuf.FileOptions {\n" + " optional string test_file_opt = 10101;\n" + "}\n" + "extend google.protobuf.MessageOptions {\n" + " optional string test_msg_opt = 10101;\n" + "}\n" + "extend google.protobuf.FieldOptions {\n" + " optional string test_field_opt = 10101;\n" + "}\n" + "extend google.protobuf.EnumOptions {\n" + " repeated int32 test_enum_opt = 10101;\n" + "}\n" + "extend google.protobuf.EnumValueOptions {\n" + " optional A test_enumval_opt = 10101;\n" + "}\n" + "extend google.protobuf.ServiceOptions {\n" + " repeated A test_svc_opt = 10101;\n" + "}\n" + "extend google.protobuf.MethodOptions {\n" + " optional string test_method_opt = 10101;\n" + "}\n" + "extend google.protobuf.OneofOptions {\n" + " optional string test_oneof_opt = 10101;\n" + "}\n" + "extend google.protobuf.ExtensionRangeOptions {\n" + " optional string test_ext_opt = 10101;\n" + "}\n"; class SourceLocationTest : public testing::Test { public: @@ -7008,11 +7080,9 @@ class SourceLocationTest : public testing::Test { simple_db_.Add(file_proto_); } - static string PrintSourceLocation(const SourceLocation &loc) { - return strings::Substitute("$0:$1-$2:$3", - 1 + loc.start_line, - 1 + loc.start_column, - 1 + loc.end_line, + static std::string PrintSourceLocation(const SourceLocation& loc) { + return strings::Substitute("$0:$1-$2:$3", 1 + loc.start_line, + 1 + loc.start_column, 1 + loc.end_line, 1 + loc.end_column); } @@ -7020,9 +7090,9 @@ class SourceLocationTest : public testing::Test { FileDescriptorProto file_proto_; AbortingErrorCollector collector_; SingletonSourceTree source_tree_; - SimpleDescriptorDatabase simple_db_; // contains descriptor.proto - compiler::SourceTreeDescriptorDatabase source_tree_db_; // loads test.proto - MergedDescriptorDatabase merged_db_; // combines above two dbs + SimpleDescriptorDatabase simple_db_; // contains descriptor.proto + compiler::SourceTreeDescriptorDatabase source_tree_db_; // loads test.proto + MergedDescriptorDatabase merged_db_; // combines above two dbs protected: DescriptorPool pool_; @@ -7030,7 +7100,7 @@ class SourceLocationTest : public testing::Test { // tag number of all custom options in above test file static const int kCustomOptionFieldNumber = 10101; // tag number of field "a" in message type "A" in above test file - static const int kA_aFieldNumber = 1; + static const int kAFieldNumber = 1; }; // TODO(adonovan): implement support for option fields and for @@ -7039,30 +7109,30 @@ class SourceLocationTest : public testing::Test { TEST_F(SourceLocationTest, GetSourceLocation) { SourceLocation loc; - const FileDescriptor *file_desc = + const FileDescriptor* file_desc = GOOGLE_CHECK_NOTNULL(pool_.FindFileByName("/test/test.proto")); - const Descriptor *a_desc = file_desc->FindMessageTypeByName("A"); + const Descriptor* a_desc = file_desc->FindMessageTypeByName("A"); EXPECT_TRUE(a_desc->GetSourceLocation(&loc)); EXPECT_EQ("4:1-16:2", PrintSourceLocation(loc)); - const Descriptor *a_b_desc = a_desc->FindNestedTypeByName("B"); + const Descriptor* a_b_desc = a_desc->FindNestedTypeByName("B"); EXPECT_TRUE(a_b_desc->GetSourceLocation(&loc)); EXPECT_EQ("7:3-9:4", PrintSourceLocation(loc)); - const EnumDescriptor *e_desc = file_desc->FindEnumTypeByName("Indecision"); + const EnumDescriptor* e_desc = file_desc->FindEnumTypeByName("Indecision"); EXPECT_TRUE(e_desc->GetSourceLocation(&loc)); EXPECT_EQ("17:1-24:2", PrintSourceLocation(loc)); - const EnumValueDescriptor *yes_desc = e_desc->FindValueByName("YES"); + const EnumValueDescriptor* yes_desc = e_desc->FindValueByName("YES"); EXPECT_TRUE(yes_desc->GetSourceLocation(&loc)); EXPECT_EQ("21:3-21:42", PrintSourceLocation(loc)); - const ServiceDescriptor *s_desc = file_desc->FindServiceByName("S"); + const ServiceDescriptor* s_desc = file_desc->FindServiceByName("S"); EXPECT_TRUE(s_desc->GetSourceLocation(&loc)); EXPECT_EQ("25:1-35:2", PrintSourceLocation(loc)); - const MethodDescriptor *m_desc = s_desc->FindMethodByName("Method"); + const MethodDescriptor* m_desc = s_desc->FindMethodByName("Method"); EXPECT_TRUE(m_desc->GetSourceLocation(&loc)); EXPECT_EQ("29:3-29:31", PrintSourceLocation(loc)); @@ -7071,24 +7141,23 @@ TEST_F(SourceLocationTest, GetSourceLocation) { TEST_F(SourceLocationTest, ExtensionSourceLocation) { SourceLocation loc; - const FileDescriptor *file_desc = + const FileDescriptor* file_desc = GOOGLE_CHECK_NOTNULL(pool_.FindFileByName("/test/test.proto")); - const FieldDescriptor *int32_extension_desc = + const FieldDescriptor* int32_extension_desc = file_desc->FindExtensionByName("int32_extension"); EXPECT_TRUE(int32_extension_desc->GetSourceLocation(&loc)); EXPECT_EQ("40:3-40:55", PrintSourceLocation(loc)); - const Descriptor *c_desc = file_desc->FindMessageTypeByName("C"); + const Descriptor* c_desc = file_desc->FindMessageTypeByName("C"); EXPECT_TRUE(c_desc->GetSourceLocation(&loc)); EXPECT_EQ("42:1-46:2", PrintSourceLocation(loc)); - const FieldDescriptor *message_extension_desc = + const FieldDescriptor* message_extension_desc = c_desc->FindExtensionByName("message_extension"); EXPECT_TRUE(message_extension_desc->GetSourceLocation(&loc)); EXPECT_EQ("44:5-44:41", PrintSourceLocation(loc)); } - TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { // This one's a doozy. It checks every kind of option, including // extension range options. @@ -7099,16 +7168,15 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { SourceLocation loc; - const FileDescriptor *file_desc = + const FileDescriptor* file_desc = GOOGLE_CHECK_NOTNULL(pool_.FindFileByName("/test/test.proto")); // File options { - int path[] = {FileDescriptorProto::kOptionsFieldNumber, - FileOptions::kJavaPackageFieldNumber}; + int path[] = {FileDescriptorProto::kOptionsFieldNumber, + FileOptions::kJavaPackageFieldNumber}; int unint[] = {FileDescriptorProto::kOptionsFieldNumber, - FileOptions::kUninterpretedOptionFieldNumber, - 0}; + FileOptions::kUninterpretedOptionFieldNumber, 0}; std::vector vpath(path, path + 2); EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); @@ -7118,11 +7186,10 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); } { - int path[] = {FileDescriptorProto::kOptionsFieldNumber, - kCustomOptionFieldNumber}; + int path[] = {FileDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber}; int unint[] = {FileDescriptorProto::kOptionsFieldNumber, - FileOptions::kUninterpretedOptionFieldNumber, - 1}; + FileOptions::kUninterpretedOptionFieldNumber, 1}; std::vector vpath(path, path + 2); EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); EXPECT_EQ("3:1-3:35", PrintSourceLocation(loc)); @@ -7133,15 +7200,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { // Message option { - int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, - 0, + int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, 0, + DescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber}; + int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber, 0, DescriptorProto::kOptionsFieldNumber, - kCustomOptionFieldNumber}; - int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber, - 0, - DescriptorProto::kOptionsFieldNumber, - MessageOptions::kUninterpretedOptionFieldNumber, - 0}; + MessageOptions::kUninterpretedOptionFieldNumber, 0}; std::vector vpath(path, path + 4); EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); EXPECT_EQ("5:3-5:36", PrintSourceLocation(loc)); @@ -7152,12 +7216,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { // Field option { - int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, - 0, - DescriptorProto::kFieldFieldNumber, - 0, - FieldDescriptorProto::kOptionsFieldNumber, - FieldOptions::kDeprecatedFieldNumber}; + int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, + 0, + DescriptorProto::kFieldFieldNumber, + 0, + FieldDescriptorProto::kOptionsFieldNumber, + FieldOptions::kDeprecatedFieldNumber}; int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber, 0, DescriptorProto::kFieldFieldNumber, @@ -7175,14 +7239,11 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { // Nested message option { - int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, - 0, - DescriptorProto::kNestedTypeFieldNumber, - 0, - DescriptorProto::kFieldFieldNumber, - 0, - FieldDescriptorProto::kOptionsFieldNumber, - kCustomOptionFieldNumber}; + int path[] = { + FileDescriptorProto::kMessageTypeFieldNumber, 0, + DescriptorProto::kNestedTypeFieldNumber, 0, + DescriptorProto::kFieldFieldNumber, 0, + FieldDescriptorProto::kOptionsFieldNumber, kCustomOptionFieldNumber}; int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber, 0, DescriptorProto::kNestedTypeFieldNumber, @@ -7202,12 +7263,10 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { // One-of option { - int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, - 0, - DescriptorProto::kOneofDeclFieldNumber, - 0, - OneofDescriptorProto::kOptionsFieldNumber, - kCustomOptionFieldNumber}; + int path[] = { + FileDescriptorProto::kMessageTypeFieldNumber, 0, + DescriptorProto::kOneofDeclFieldNumber, 0, + OneofDescriptorProto::kOptionsFieldNumber, kCustomOptionFieldNumber}; int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber, 0, DescriptorProto::kOneofDeclFieldNumber, @@ -7225,16 +7284,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { // Enum option, repeated options { - int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, - 0, + int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, 0, + EnumDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber, 0}; + int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber, 0, EnumDescriptorProto::kOptionsFieldNumber, - kCustomOptionFieldNumber, - 0}; - int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber, - 0, - EnumDescriptorProto::kOptionsFieldNumber, - EnumOptions::kUninterpretedOptionFieldNumber, - 0}; + EnumOptions::kUninterpretedOptionFieldNumber, 0}; std::vector vpath(path, path + 5); EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); EXPECT_EQ("18:3-18:31", PrintSourceLocation(loc)); @@ -7243,16 +7298,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); } { - int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, - 0, + int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, 0, + EnumDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber, 1}; + int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber, 0, EnumDescriptorProto::kOptionsFieldNumber, - kCustomOptionFieldNumber, - 1}; - int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber, - 0, - EnumDescriptorProto::kOptionsFieldNumber, - EnumOptions::kUninterpretedOptionFieldNumber, - 1}; + EnumOptions::kUninterpretedOptionFieldNumber, 1}; std::vector vpath(path, path + 5); EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); EXPECT_EQ("19:3-19:31", PrintSourceLocation(loc)); @@ -7261,16 +7312,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); } { - int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, - 0, + int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, 0, + EnumDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber, 2}; + int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber, 0, EnumDescriptorProto::kOptionsFieldNumber, - kCustomOptionFieldNumber, - 2}; - int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber, - 0, - EnumDescriptorProto::kOptionsFieldNumber, - OneofOptions::kUninterpretedOptionFieldNumber, - 2}; + OneofOptions::kUninterpretedOptionFieldNumber, 2}; std::vector vpath(path, path + 5); EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); EXPECT_EQ("20:3-20:31", PrintSourceLocation(loc)); @@ -7282,13 +7329,13 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { // Enum value options { // option w/ message type that directly sets field - int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, - 0, - EnumDescriptorProto::kValueFieldNumber, - 0, - EnumValueDescriptorProto::kOptionsFieldNumber, - kCustomOptionFieldNumber, - kA_aFieldNumber}; + int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, + 0, + EnumDescriptorProto::kValueFieldNumber, + 0, + EnumValueDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber, + kAFieldNumber}; int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber, 0, EnumDescriptorProto::kValueFieldNumber, @@ -7304,12 +7351,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); } { - int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, - 0, - EnumDescriptorProto::kValueFieldNumber, - 1, - EnumValueDescriptorProto::kOptionsFieldNumber, - kCustomOptionFieldNumber}; + int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, + 0, + EnumDescriptorProto::kValueFieldNumber, + 1, + EnumValueDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber}; int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber, 0, EnumDescriptorProto::kValueFieldNumber, @@ -7327,16 +7374,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { // Service option, repeated options { - int path[] = {FileDescriptorProto::kServiceFieldNumber, - 0, + int path[] = {FileDescriptorProto::kServiceFieldNumber, 0, + ServiceDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber, 0}; + int unint[] = {FileDescriptorProto::kServiceFieldNumber, 0, ServiceDescriptorProto::kOptionsFieldNumber, - kCustomOptionFieldNumber, - 0}; - int unint[] = {FileDescriptorProto::kServiceFieldNumber, - 0, - ServiceDescriptorProto::kOptionsFieldNumber, - ServiceOptions::kUninterpretedOptionFieldNumber, - 0}; + ServiceOptions::kUninterpretedOptionFieldNumber, 0}; std::vector vpath(path, path + 5); EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); EXPECT_EQ("26:3-26:35", PrintSourceLocation(loc)); @@ -7345,16 +7388,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); } { - int path[] = {FileDescriptorProto::kServiceFieldNumber, - 0, + int path[] = {FileDescriptorProto::kServiceFieldNumber, 0, + ServiceDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber, 1}; + int unint[] = {FileDescriptorProto::kServiceFieldNumber, 0, ServiceDescriptorProto::kOptionsFieldNumber, - kCustomOptionFieldNumber, - 1}; - int unint[] = {FileDescriptorProto::kServiceFieldNumber, - 0, - ServiceDescriptorProto::kOptionsFieldNumber, - ServiceOptions::kUninterpretedOptionFieldNumber, - 1}; + ServiceOptions::kUninterpretedOptionFieldNumber, 1}; std::vector vpath(path, path + 5); EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); EXPECT_EQ("27:3-27:35", PrintSourceLocation(loc)); @@ -7363,16 +7402,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); } { - int path[] = {FileDescriptorProto::kServiceFieldNumber, - 0, + int path[] = {FileDescriptorProto::kServiceFieldNumber, 0, + ServiceDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber, 2}; + int unint[] = {FileDescriptorProto::kServiceFieldNumber, 0, ServiceDescriptorProto::kOptionsFieldNumber, - kCustomOptionFieldNumber, - 2}; - int unint[] = {FileDescriptorProto::kServiceFieldNumber, - 0, - ServiceDescriptorProto::kOptionsFieldNumber, - ServiceOptions::kUninterpretedOptionFieldNumber, - 2}; + ServiceOptions::kUninterpretedOptionFieldNumber, 2}; std::vector vpath(path, path + 5); EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); EXPECT_EQ("28:3-28:35", PrintSourceLocation(loc)); @@ -7383,12 +7418,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { // Method options { - int path[] = {FileDescriptorProto::kServiceFieldNumber, - 0, - ServiceDescriptorProto::kMethodFieldNumber, - 1, - MethodDescriptorProto::kOptionsFieldNumber, - MethodOptions::kDeprecatedFieldNumber}; + int path[] = {FileDescriptorProto::kServiceFieldNumber, + 0, + ServiceDescriptorProto::kMethodFieldNumber, + 1, + MethodDescriptorProto::kOptionsFieldNumber, + MethodOptions::kDeprecatedFieldNumber}; int unint[] = {FileDescriptorProto::kServiceFieldNumber, 0, ServiceDescriptorProto::kMethodFieldNumber, @@ -7404,12 +7439,10 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); } { - int path[] = {FileDescriptorProto::kServiceFieldNumber, - 0, - ServiceDescriptorProto::kMethodFieldNumber, - 1, - MethodDescriptorProto::kOptionsFieldNumber, - kCustomOptionFieldNumber}; + int path[] = { + FileDescriptorProto::kServiceFieldNumber, 0, + ServiceDescriptorProto::kMethodFieldNumber, 1, + MethodDescriptorProto::kOptionsFieldNumber, kCustomOptionFieldNumber}; int unint[] = {FileDescriptorProto::kServiceFieldNumber, 0, ServiceDescriptorProto::kMethodFieldNumber, @@ -7427,22 +7460,20 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { // Extension range options { - int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, - 1, - DescriptorProto::kExtensionRangeFieldNumber, - 0, - DescriptorProto_ExtensionRange::kOptionsFieldNumber}; + int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, 1, + DescriptorProto::kExtensionRangeFieldNumber, 0, + DescriptorProto_ExtensionRange::kOptionsFieldNumber}; std::vector vpath(path, path + 5); EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); EXPECT_EQ("37:40-37:67", PrintSourceLocation(loc)); } { - int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, - 1, - DescriptorProto::kExtensionRangeFieldNumber, - 0, - DescriptorProto_ExtensionRange::kOptionsFieldNumber, - kCustomOptionFieldNumber}; + int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, + 1, + DescriptorProto::kExtensionRangeFieldNumber, + 0, + DescriptorProto_ExtensionRange::kOptionsFieldNumber, + kCustomOptionFieldNumber}; int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber, 1, DescriptorProto::kExtensionRangeFieldNumber, @@ -7458,12 +7489,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); } { - int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, - 1, - DescriptorProto::kExtensionRangeFieldNumber, - 1, - DescriptorProto_ExtensionRange::kOptionsFieldNumber, - kCustomOptionFieldNumber}; + int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, + 1, + DescriptorProto::kExtensionRangeFieldNumber, + 1, + DescriptorProto_ExtensionRange::kOptionsFieldNumber, + kCustomOptionFieldNumber}; int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber, 1, DescriptorProto::kExtensionRangeFieldNumber, @@ -7481,15 +7512,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { // Field option on extension { - int path[] = {FileDescriptorProto::kExtensionFieldNumber, - 0, + int path[] = {FileDescriptorProto::kExtensionFieldNumber, 0, + FieldDescriptorProto::kOptionsFieldNumber, + FieldOptions::kPackedFieldNumber}; + int unint[] = {FileDescriptorProto::kExtensionFieldNumber, 0, FieldDescriptorProto::kOptionsFieldNumber, - FieldOptions::kPackedFieldNumber}; - int unint[] = {FileDescriptorProto::kExtensionFieldNumber, - 0, - FieldDescriptorProto::kOptionsFieldNumber, - FieldOptions::kUninterpretedOptionFieldNumber, - 0}; + FieldOptions::kUninterpretedOptionFieldNumber, 0}; std::vector vpath(path, path + 4); EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); EXPECT_EQ("40:42-40:53", PrintSourceLocation(loc)); @@ -7503,7 +7531,7 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { TEST_F(SourceLocationTest, GetSourceLocation_MissingSourceCodeInfo) { SourceLocation loc; - const FileDescriptor *file_desc = + const FileDescriptor* file_desc = GOOGLE_CHECK_NOTNULL(pool_.FindFileByName("/test/test.proto")); FileDescriptorProto proto; @@ -7513,7 +7541,7 @@ TEST_F(SourceLocationTest, GetSourceLocation_MissingSourceCodeInfo) { DescriptorPool bad1_pool(&pool_); const FileDescriptor* bad1_file_desc = GOOGLE_CHECK_NOTNULL(bad1_pool.BuildFile(proto)); - const Descriptor *bad1_a_desc = bad1_file_desc->FindMessageTypeByName("A"); + const Descriptor* bad1_a_desc = bad1_file_desc->FindMessageTypeByName("A"); EXPECT_FALSE(bad1_a_desc->GetSourceLocation(&loc)); } @@ -7521,13 +7549,13 @@ TEST_F(SourceLocationTest, GetSourceLocation_MissingSourceCodeInfo) { TEST_F(SourceLocationTest, GetSourceLocation_BogusSourceCodeInfo) { SourceLocation loc; - const FileDescriptor *file_desc = + const FileDescriptor* file_desc = GOOGLE_CHECK_NOTNULL(pool_.FindFileByName("/test/test.proto")); FileDescriptorProto proto; file_desc->CopyTo(&proto); // Note, this discards the SourceCodeInfo. EXPECT_FALSE(proto.has_source_code_info()); - SourceCodeInfo_Location *loc_msg = + SourceCodeInfo_Location* loc_msg = proto.mutable_source_code_info()->add_location(); loc_msg->add_path(1); loc_msg->add_path(2); @@ -7539,15 +7567,15 @@ TEST_F(SourceLocationTest, GetSourceLocation_BogusSourceCodeInfo) { DescriptorPool bad2_pool(&pool_); const FileDescriptor* bad2_file_desc = GOOGLE_CHECK_NOTNULL(bad2_pool.BuildFile(proto)); - const Descriptor *bad2_a_desc = bad2_file_desc->FindMessageTypeByName("A"); + const Descriptor* bad2_a_desc = bad2_file_desc->FindMessageTypeByName("A"); EXPECT_FALSE(bad2_a_desc->GetSourceLocation(&loc)); } // =================================================================== const char* const kCopySourceCodeInfoToTestInput = - "syntax = \"proto2\";\n" - "message Foo {}\n"; + "syntax = \"proto2\";\n" + "message Foo {}\n"; // Required since source code information is not preserved by // FileDescriptorTest. @@ -7611,7 +7639,7 @@ class LazilyBuildDependenciesTest : public testing::Test { db_.Add(tmp); } - void ParseProtoAndAddToDb(const string& proto) { + void ParseProtoAndAddToDb(const std::string& proto) { FileDescriptorProto tmp; ASSERT_TRUE(TextFormat::ParseFromString(proto, &tmp)); db_.Add(tmp); @@ -7619,12 +7647,12 @@ class LazilyBuildDependenciesTest : public testing::Test { void AddSimpleMessageProtoFileToDb(const char* file_name, const char* message_name) { - ParseProtoAndAddToDb("name: '" + string(file_name) + + ParseProtoAndAddToDb("name: '" + std::string(file_name) + ".proto' " "package: \"protobuf_unittest\" " "message_type { " " name:'" + - string(message_name) + + std::string(message_name) + "' " " field { name:'a' number:1 " " label:LABEL_OPTIONAL " @@ -7634,15 +7662,15 @@ class LazilyBuildDependenciesTest : public testing::Test { void AddSimpleEnumProtoFileToDb(const char* file_name, const char* enum_name, const char* enum_value_name) { - ParseProtoAndAddToDb("name: '" + string(file_name) + + ParseProtoAndAddToDb("name: '" + std::string(file_name) + ".proto' " "package: 'protobuf_unittest' " "enum_type { " " name:'" + - string(enum_name) + + std::string(enum_name) + "' " " value { name:'" + - string(enum_value_name) + + std::string(enum_value_name) + "' number:1 } " "}"); } @@ -7890,7 +7918,7 @@ TEST_F(LazilyBuildDependenciesTest, GeneratedFile) { // Verify custom options work when defined in an import that isn't loaded, // and that a non-default value of a custom option doesn't load the file // where that enum is defined. - const google::protobuf::MessageOptions& options = + const MessageOptions& options = protobuf_unittest::lazy_imports::MessageCustomOption::descriptor() ->options(); protobuf_unittest::lazy_imports::LazyEnum custom_option_value = @@ -7902,7 +7930,7 @@ TEST_F(LazilyBuildDependenciesTest, GeneratedFile) { "google/protobuf/unittest_lazy_dependencies_enum.proto")); EXPECT_EQ(custom_option_value, protobuf_unittest::lazy_imports::LAZY_ENUM_1); - const google::protobuf::MessageOptions& options2 = + const MessageOptions& options2 = protobuf_unittest::lazy_imports::MessageCustomOption2::descriptor() ->options(); custom_option_value = diff --git a/third_party/protobuf/src/google/protobuf/drop_unknown_fields_test.cc b/third_party/protobuf/src/google/protobuf/drop_unknown_fields_test.cc index 437a04e7..55b9ecd3 100644 --- a/third_party/protobuf/src/google/protobuf/drop_unknown_fields_test.cc +++ b/third_party/protobuf/src/google/protobuf/drop_unknown_fields_test.cc @@ -35,35 +35,13 @@ #include #include -namespace google { using unittest_drop_unknown_fields::Foo; using unittest_drop_unknown_fields::FooWithExtraFields; +namespace google { namespace protobuf { -TEST(DropUnknownFieldsTest, GeneratedMessageDefaultDrop) { - ::google::protobuf::internal::SetProto3PreserveUnknownsDefault(false); - FooWithExtraFields foo_with_extra_fields; - foo_with_extra_fields.set_int32_value(1); - foo_with_extra_fields.set_enum_value(FooWithExtraFields::QUX); - foo_with_extra_fields.set_extra_int32_value(2); - - Foo foo; - ASSERT_TRUE(foo.ParseFromString(foo_with_extra_fields.SerializeAsString())); - EXPECT_EQ(1, foo.int32_value()); - EXPECT_EQ(static_cast(FooWithExtraFields::QUX), - static_cast(foo.enum_value())); - EXPECT_TRUE(foo.GetReflection()->GetUnknownFields(foo).empty()); - - ASSERT_TRUE(foo_with_extra_fields.ParseFromString(foo.SerializeAsString())); - EXPECT_EQ(1, foo_with_extra_fields.int32_value()); - EXPECT_EQ(FooWithExtraFields::QUX, foo_with_extra_fields.enum_value()); - // The "extra_int32_value" field should be lost. - EXPECT_EQ(0, foo_with_extra_fields.extra_int32_value()); -} - -TEST(DropUnknownFieldsTest, GeneratedMessageDefaultPreserve) { - ::google::protobuf::internal::SetProto3PreserveUnknownsDefault(true); +TEST(DropUnknownFieldsTest, GeneratedMessage) { FooWithExtraFields foo_with_extra_fields; foo_with_extra_fields.set_int32_value(1); foo_with_extra_fields.set_enum_value(FooWithExtraFields::QUX); @@ -83,36 +61,14 @@ TEST(DropUnknownFieldsTest, GeneratedMessageDefaultPreserve) { EXPECT_EQ(2, foo_with_extra_fields.extra_int32_value()); } -TEST(DropUnknownFieldsTest, DynamicMessageDefaultDrop) { - internal::SetProto3PreserveUnknownsDefault(false); +TEST(DropUnknownFieldsTest, DynamicMessage) { FooWithExtraFields foo_with_extra_fields; foo_with_extra_fields.set_int32_value(1); foo_with_extra_fields.set_enum_value(FooWithExtraFields::QUX); foo_with_extra_fields.set_extra_int32_value(2); - google::protobuf::DynamicMessageFactory factory; - std::unique_ptr foo( - factory.GetPrototype(Foo::descriptor())->New()); - ASSERT_TRUE(foo->ParseFromString(foo_with_extra_fields.SerializeAsString())); - EXPECT_TRUE(foo->GetReflection()->GetUnknownFields(*foo).empty()); - - ASSERT_TRUE(foo_with_extra_fields.ParseFromString(foo->SerializeAsString())); - EXPECT_EQ(1, foo_with_extra_fields.int32_value()); - EXPECT_EQ(FooWithExtraFields::QUX, foo_with_extra_fields.enum_value()); - // The "extra_int32_value" field should be lost. - EXPECT_EQ(0, foo_with_extra_fields.extra_int32_value()); -} - -TEST(DropUnknownFieldsTest, DynamicMessageDefaultPreserve) { - internal::SetProto3PreserveUnknownsDefault(true); - FooWithExtraFields foo_with_extra_fields; - foo_with_extra_fields.set_int32_value(1); - foo_with_extra_fields.set_enum_value(FooWithExtraFields::QUX); - foo_with_extra_fields.set_extra_int32_value(2); - - google::protobuf::DynamicMessageFactory factory; - std::unique_ptr foo( - factory.GetPrototype(Foo::descriptor())->New()); + DynamicMessageFactory factory; + std::unique_ptr foo(factory.GetPrototype(Foo::descriptor())->New()); ASSERT_TRUE(foo->ParseFromString(foo_with_extra_fields.SerializeAsString())); EXPECT_FALSE(foo->GetReflection()->GetUnknownFields(*foo).empty()); diff --git a/third_party/protobuf/src/google/protobuf/duration.pb.cc b/third_party/protobuf/src/google/protobuf/duration.pb.cc index ddc063db..ae476deb 100644 --- a/third_party/protobuf/src/google/protobuf/duration.pb.cc +++ b/third_party/protobuf/src/google/protobuf/duration.pb.cc @@ -6,141 +6,110 @@ #include #include -#include #include -#include +#include +#include #include #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) - -namespace google { -namespace protobuf { +#include +PROTOBUF_NAMESPACE_OPEN class DurationDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _Duration_default_instance_; -} // namespace protobuf -} // namespace google -namespace protobuf_google_2fprotobuf_2fduration_2eproto { -static void InitDefaultsDuration() { +PROTOBUF_NAMESPACE_CLOSE +static void InitDefaultsscc_info_Duration_google_2fprotobuf_2fduration_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_Duration_default_instance_; - new (ptr) ::google::protobuf::Duration(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_Duration_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::Duration(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::Duration::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::Duration::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Duration = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDuration}, {}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Duration_google_2fprotobuf_2fduration_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_Duration_google_2fprotobuf_2fduration_2eproto}, {}}; -void InitDefaults() { - ::google::protobuf::internal::InitSCC(&scc_info_Duration.base); -} +static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_google_2fprotobuf_2fduration_2eproto[1]; +static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fduration_2eproto = nullptr; +static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fduration_2eproto = nullptr; -::google::protobuf::Metadata file_level_metadata[1]; - -const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_google_2fprotobuf_2fduration_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Duration, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Duration, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Duration, seconds_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Duration, nanos_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Duration, seconds_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Duration, nanos_), }; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, sizeof(::google::protobuf::Duration)}, +static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, -1, sizeof(PROTOBUF_NAMESPACE_ID::Duration)}, }; -static ::google::protobuf::Message const * const file_default_instances[] = { - reinterpret_cast(&::google::protobuf::_Duration_default_instance_), +static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_Duration_default_instance_), }; -void protobuf_AssignDescriptors() { - AddDescriptors(); - AssignDescriptors( - "google/protobuf/duration.proto", schemas, file_default_instances, TableStruct::offsets, - file_level_metadata, NULL, NULL); -} +const char descriptor_table_protodef_google_2fprotobuf_2fduration_2eproto[] = + "\n\036google/protobuf/duration.proto\022\017google" + ".protobuf\"*\n\010Duration\022\017\n\007seconds\030\001 \001(\003\022\r" + "\n\005nanos\030\002 \001(\005B|\n\023com.google.protobufB\rDu" + "rationProtoP\001Z*github.com/golang/protobu" + "f/ptypes/duration\370\001\001\242\002\003GPB\252\002\036Google.Prot" + "obuf.WellKnownTypesb\006proto3" + ; +static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_google_2fprotobuf_2fduration_2eproto_deps[1] = { +}; +static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_google_2fprotobuf_2fduration_2eproto_sccs[1] = { + &scc_info_Duration_google_2fprotobuf_2fduration_2eproto.base, +}; +static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fduration_2eproto_once; +static bool descriptor_table_google_2fprotobuf_2fduration_2eproto_initialized = false; +const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fduration_2eproto = { + &descriptor_table_google_2fprotobuf_2fduration_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fduration_2eproto, "google/protobuf/duration.proto", 227, + &descriptor_table_google_2fprotobuf_2fduration_2eproto_once, descriptor_table_google_2fprotobuf_2fduration_2eproto_sccs, descriptor_table_google_2fprotobuf_2fduration_2eproto_deps, 1, 0, + schemas, file_default_instances, TableStruct_google_2fprotobuf_2fduration_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2fduration_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2fduration_2eproto, file_level_service_descriptors_google_2fprotobuf_2fduration_2eproto, +}; -void protobuf_AssignDescriptorsOnce() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); -} - -void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1); -} - -void AddDescriptorsImpl() { - InitDefaults(); - static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - "\n\036google/protobuf/duration.proto\022\017google" - ".protobuf\"*\n\010Duration\022\017\n\007seconds\030\001 \001(\003\022\r" - "\n\005nanos\030\002 \001(\005B|\n\023com.google.protobufB\rDu" - "rationProtoP\001Z*github.com/golang/protobu" - "f/ptypes/duration\370\001\001\242\002\003GPB\252\002\036Google.Prot" - "obuf.WellKnownTypesb\006proto3" - }; - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - descriptor, 227); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "google/protobuf/duration.proto", &protobuf_RegisterTypes); -} - -void AddDescriptors() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); -} -// Force AddDescriptors() to be called at dynamic initialization time. -struct StaticDescriptorInitializer { - StaticDescriptorInitializer() { - AddDescriptors(); - } -} static_descriptor_initializer; -} // namespace protobuf_google_2fprotobuf_2fduration_2eproto -namespace google { -namespace protobuf { +// Force running AddDescriptors() at dynamic initialization time. +static bool dynamic_init_dummy_google_2fprotobuf_2fduration_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fduration_2eproto), true); +PROTOBUF_NAMESPACE_OPEN // =================================================================== void Duration::InitAsDefaultInstance() { } +class Duration::HasBitSetters { + public: +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Duration::kSecondsFieldNumber; const int Duration::kNanosFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Duration::Duration() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fduration_2eproto::scc_info_Duration.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Duration) } -Duration::Duration(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +Duration::Duration(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fduration_2eproto::scc_info_Duration.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Duration) } Duration::Duration(const Duration& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&seconds_, &from.seconds_, static_cast(reinterpret_cast(&nanos_) - @@ -160,32 +129,27 @@ Duration::~Duration() { } void Duration::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void Duration::ArenaDtor(void* object) { Duration* _this = reinterpret_cast< Duration* >(object); (void)_this; } -void Duration::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void Duration::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void Duration::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* Duration::descriptor() { - ::protobuf_google_2fprotobuf_2fduration_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fduration_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const Duration& Duration::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fduration_2eproto::scc_info_Duration.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_Duration_google_2fprotobuf_2fduration_2eproto.base); return *internal_default_instance(); } void Duration::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.Duration) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -195,23 +159,65 @@ void Duration::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* Duration::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // int64 seconds = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { + seconds_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // int32 nanos = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { + nanos_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Duration::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Duration) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int64 seconds = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64>( input, &seconds_))); } else { goto handle_unusual; @@ -221,11 +227,10 @@ bool Duration::MergePartialFromCodedStream( // int32 nanos = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (16 & 0xFF)) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &nanos_))); } else { goto handle_unusual; @@ -238,7 +243,7 @@ bool Duration::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -252,50 +257,50 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void Duration::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.Duration) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 seconds = 1; if (this->seconds() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->seconds(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt64(1, this->seconds(), output); } // int32 nanos = 2; if (this->nanos() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->nanos(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(2, this->nanos(), output); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); + if (_internal_metadata_.have_unknown_fields()) { + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( + _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.Duration) } -::google::protobuf::uint8* Duration::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* Duration::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Duration) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 seconds = 1; if (this->seconds() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->seconds(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt64ToArray(1, this->seconds(), target); } // int32 nanos = 2; if (this->nanos() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->nanos(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(2, this->nanos(), target); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); + if (_internal_metadata_.have_unknown_fields()) { + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( + _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Duration) return target; @@ -305,39 +310,43 @@ size_t Duration::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.protobuf.Duration) size_t total_size = 0; - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { + if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( + _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // int64 seconds = 1; if (this->seconds() != 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int64Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int64Size( this->seconds()); } // int32 nanos = 2; if (this->nanos() != 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->nanos()); } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void Duration::MergeFrom(const ::google::protobuf::Message& from) { +void Duration::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Duration) GOOGLE_DCHECK_NE(&from, this); const Duration* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Duration) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Duration) MergeFrom(*source); @@ -348,7 +357,7 @@ void Duration::MergeFrom(const Duration& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Duration) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.seconds() != 0) { @@ -359,7 +368,7 @@ void Duration::MergeFrom(const Duration& from) { } } -void Duration::CopyFrom(const ::google::protobuf::Message& from) { +void Duration::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Duration) if (&from == this) return; Clear(); @@ -386,7 +395,7 @@ void Duration::Swap(Duration* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -398,26 +407,23 @@ void Duration::UnsafeArenaSwap(Duration* other) { } void Duration::InternalSwap(Duration* other) { using std::swap; + _internal_metadata_.Swap(&other->_internal_metadata_); swap(seconds_, other->seconds_); swap(nanos_, other->nanos_); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata Duration::GetMetadata() const { - protobuf_google_2fprotobuf_2fduration_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fduration_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata Duration::GetMetadata() const { + return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Duration* Arena::CreateMaybeMessage< ::google::protobuf::Duration >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::Duration >(arena); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::Duration* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Duration >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::Duration >(arena); } -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) +#include diff --git a/third_party/protobuf/src/google/protobuf/duration.pb.h b/third_party/protobuf/src/google/protobuf/duration.pb.h index 19241ebc..b117a0a7 100644 --- a/third_party/protobuf/src/google/protobuf/duration.pb.h +++ b/third_party/protobuf/src/google/protobuf/duration.pb.h @@ -1,24 +1,25 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/duration.proto -#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto -#define PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto +#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto +#include #include -#include - -#if GOOGLE_PROTOBUF_VERSION < 3006001 +#include +#if PROTOBUF_VERSION < 3008000 #error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update +#error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3008000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please +#error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include @@ -26,59 +27,61 @@ #include #include #include +#include #include #include // IWYU pragma: export #include // IWYU pragma: export #include // @@protoc_insertion_point(includes) -#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fduration_2eproto LIBPROTOBUF_EXPORT +#include +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fduration_2eproto PROTOBUF_EXPORT +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE -namespace protobuf_google_2fprotobuf_2fduration_2eproto { // Internal implementation detail -- do not use these members. -struct LIBPROTOBUF_EXPORT TableStruct { - static const ::google::protobuf::internal::ParseTableField entries[]; - static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; - static const ::google::protobuf::internal::ParseTable schema[1]; - static const ::google::protobuf::internal::FieldMetadata field_metadata[]; - static const ::google::protobuf::internal::SerializationTable serialization_table[]; - static const ::google::protobuf::uint32 offsets[]; +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fduration_2eproto { + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; + static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; + static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; -void LIBPROTOBUF_EXPORT AddDescriptors(); -} // namespace protobuf_google_2fprotobuf_2fduration_2eproto -namespace google { -namespace protobuf { +extern PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fduration_2eproto; +PROTOBUF_NAMESPACE_OPEN class Duration; class DurationDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern DurationDefaultTypeInternal _Duration_default_instance_; -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Duration* Arena::CreateMaybeMessage<::google::protobuf::Duration>(Arena*); -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { +PROTOBUF_EXPORT extern DurationDefaultTypeInternal _Duration_default_instance_; +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::Duration* Arena::CreateMaybeMessage(Arena*); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN // =================================================================== -class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Duration) */ { +class PROTOBUF_EXPORT Duration : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Duration) */ { public: Duration(); virtual ~Duration(); Duration(const Duration& from); - - inline Duration& operator=(const Duration& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 Duration(Duration&& from) noexcept : Duration() { *this = ::std::move(from); } + inline Duration& operator=(const Duration& from) { + CopyFrom(from); + return *this; + } inline Duration& operator=(Duration&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -87,14 +90,22 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot } return *this; } - #endif - inline ::google::protobuf::Arena* GetArena() const final { + + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const Duration& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -114,40 +125,48 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot // implements Message ---------------------------------------------- inline Duration* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - Duration* New(::google::protobuf::Arena* arena) const final { + Duration* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const Duration& from); void MergeFrom(const Duration& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Duration* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Duration"; + } protected: - explicit Duration(::google::protobuf::Arena* arena); + explicit Duration(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -155,7 +174,14 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fduration_2eproto); + return ::descriptor_table_google_2fprotobuf_2fduration_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -164,26 +190,27 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot // int64 seconds = 1; void clear_seconds(); static const int kSecondsFieldNumber = 1; - ::google::protobuf::int64 seconds() const; - void set_seconds(::google::protobuf::int64 value); + ::PROTOBUF_NAMESPACE_ID::int64 seconds() const; + void set_seconds(::PROTOBUF_NAMESPACE_ID::int64 value); // int32 nanos = 2; void clear_nanos(); static const int kNanosFieldNumber = 2; - ::google::protobuf::int32 nanos() const; - void set_nanos(::google::protobuf::int32 value); + ::PROTOBUF_NAMESPACE_ID::int32 nanos() const; + void set_nanos(::PROTOBUF_NAMESPACE_ID::int32 value); // @@protoc_insertion_point(class_scope:google.protobuf.Duration) private: + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::int64 seconds_; - ::google::protobuf::int32 nanos_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - friend struct ::protobuf_google_2fprotobuf_2fduration_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::int64 seconds_; + ::PROTOBUF_NAMESPACE_ID::int32 nanos_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2fduration_2eproto; }; // =================================================================== @@ -198,13 +225,13 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot // int64 seconds = 1; inline void Duration::clear_seconds() { - seconds_ = GOOGLE_LONGLONG(0); + seconds_ = PROTOBUF_LONGLONG(0); } -inline ::google::protobuf::int64 Duration::seconds() const { +inline ::PROTOBUF_NAMESPACE_ID::int64 Duration::seconds() const { // @@protoc_insertion_point(field_get:google.protobuf.Duration.seconds) return seconds_; } -inline void Duration::set_seconds(::google::protobuf::int64 value) { +inline void Duration::set_seconds(::PROTOBUF_NAMESPACE_ID::int64 value) { seconds_ = value; // @@protoc_insertion_point(field_set:google.protobuf.Duration.seconds) @@ -214,11 +241,11 @@ inline void Duration::set_seconds(::google::protobuf::int64 value) { inline void Duration::clear_nanos() { nanos_ = 0; } -inline ::google::protobuf::int32 Duration::nanos() const { +inline ::PROTOBUF_NAMESPACE_ID::int32 Duration::nanos() const { // @@protoc_insertion_point(field_get:google.protobuf.Duration.nanos) return nanos_; } -inline void Duration::set_nanos(::google::protobuf::int32 value) { +inline void Duration::set_nanos(::PROTOBUF_NAMESPACE_ID::int32 value) { nanos_ = value; // @@protoc_insertion_point(field_set:google.protobuf.Duration.nanos) @@ -230,9 +257,9 @@ inline void Duration::set_nanos(::google::protobuf::int32 value) { // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto diff --git a/third_party/protobuf/src/google/protobuf/duration.proto b/third_party/protobuf/src/google/protobuf/duration.proto index 975fce41..9d8a52de 100644 --- a/third_party/protobuf/src/google/protobuf/duration.proto +++ b/third_party/protobuf/src/google/protobuf/duration.proto @@ -101,7 +101,6 @@ option objc_class_prefix = "GPB"; // // message Duration { - // Signed seconds of the span of time. Must be from -315,576,000,000 // to +315,576,000,000 inclusive. Note: these bounds are computed from: // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years diff --git a/third_party/protobuf/src/google/protobuf/dynamic_message.cc b/third_party/protobuf/src/google/protobuf/dynamic_message.cc index ceedf500..5890f78e 100644 --- a/third_party/protobuf/src/google/protobuf/dynamic_message.cc +++ b/third_party/protobuf/src/google/protobuf/dynamic_message.cc @@ -63,16 +63,16 @@ // I don't have the book on me right now so I'm not sure. #include -#include #include +#include -#include +#include -#include -#include #include -#include +#include +#include #include +#include #include #include #include @@ -82,7 +82,6 @@ #include #include - namespace google { namespace protobuf { @@ -100,23 +99,29 @@ using internal::ArenaStringPtr; namespace { -bool IsMapFieldInApi(const FieldDescriptor* field) { - return field->is_map(); -} +bool IsMapFieldInApi(const FieldDescriptor* field) { return field->is_map(); } // Compute the byte size of the in-memory representation of the field. int FieldSpaceUsed(const FieldDescriptor* field) { typedef FieldDescriptor FD; // avoid line wrapping if (field->label() == FD::LABEL_REPEATED) { switch (field->cpp_type()) { - case FD::CPPTYPE_INT32 : return sizeof(RepeatedField); - case FD::CPPTYPE_INT64 : return sizeof(RepeatedField); - case FD::CPPTYPE_UINT32 : return sizeof(RepeatedField); - case FD::CPPTYPE_UINT64 : return sizeof(RepeatedField); - case FD::CPPTYPE_DOUBLE : return sizeof(RepeatedField); - case FD::CPPTYPE_FLOAT : return sizeof(RepeatedField); - case FD::CPPTYPE_BOOL : return sizeof(RepeatedField); - case FD::CPPTYPE_ENUM : return sizeof(RepeatedField); + case FD::CPPTYPE_INT32: + return sizeof(RepeatedField); + case FD::CPPTYPE_INT64: + return sizeof(RepeatedField); + case FD::CPPTYPE_UINT32: + return sizeof(RepeatedField); + case FD::CPPTYPE_UINT64: + return sizeof(RepeatedField); + case FD::CPPTYPE_DOUBLE: + return sizeof(RepeatedField); + case FD::CPPTYPE_FLOAT: + return sizeof(RepeatedField); + case FD::CPPTYPE_BOOL: + return sizeof(RepeatedField); + case FD::CPPTYPE_ENUM: + return sizeof(RepeatedField); case FD::CPPTYPE_MESSAGE: if (IsMapFieldInApi(field)) { return sizeof(DynamicMapField); @@ -128,20 +133,28 @@ int FieldSpaceUsed(const FieldDescriptor* field) { switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: - return sizeof(RepeatedPtrField); + return sizeof(RepeatedPtrField); } break; } } else { switch (field->cpp_type()) { - case FD::CPPTYPE_INT32 : return sizeof(int32 ); - case FD::CPPTYPE_INT64 : return sizeof(int64 ); - case FD::CPPTYPE_UINT32 : return sizeof(uint32 ); - case FD::CPPTYPE_UINT64 : return sizeof(uint64 ); - case FD::CPPTYPE_DOUBLE : return sizeof(double ); - case FD::CPPTYPE_FLOAT : return sizeof(float ); - case FD::CPPTYPE_BOOL : return sizeof(bool ); - case FD::CPPTYPE_ENUM : return sizeof(int ); + case FD::CPPTYPE_INT32: + return sizeof(int32); + case FD::CPPTYPE_INT64: + return sizeof(int64); + case FD::CPPTYPE_UINT32: + return sizeof(uint32); + case FD::CPPTYPE_UINT64: + return sizeof(uint64); + case FD::CPPTYPE_DOUBLE: + return sizeof(double); + case FD::CPPTYPE_FLOAT: + return sizeof(float); + case FD::CPPTYPE_BOOL: + return sizeof(bool); + case FD::CPPTYPE_ENUM: + return sizeof(int); case FD::CPPTYPE_MESSAGE: return sizeof(Message*); @@ -165,14 +178,22 @@ int FieldSpaceUsed(const FieldDescriptor* field) { int OneofFieldSpaceUsed(const FieldDescriptor* field) { typedef FieldDescriptor FD; // avoid line wrapping switch (field->cpp_type()) { - case FD::CPPTYPE_INT32 : return sizeof(int32 ); - case FD::CPPTYPE_INT64 : return sizeof(int64 ); - case FD::CPPTYPE_UINT32 : return sizeof(uint32 ); - case FD::CPPTYPE_UINT64 : return sizeof(uint64 ); - case FD::CPPTYPE_DOUBLE : return sizeof(double ); - case FD::CPPTYPE_FLOAT : return sizeof(float ); - case FD::CPPTYPE_BOOL : return sizeof(bool ); - case FD::CPPTYPE_ENUM : return sizeof(int ); + case FD::CPPTYPE_INT32: + return sizeof(int32); + case FD::CPPTYPE_INT64: + return sizeof(int64); + case FD::CPPTYPE_UINT32: + return sizeof(uint32); + case FD::CPPTYPE_UINT64: + return sizeof(uint64); + case FD::CPPTYPE_DOUBLE: + return sizeof(double); + case FD::CPPTYPE_FLOAT: + return sizeof(float); + case FD::CPPTYPE_BOOL: + return sizeof(bool); + case FD::CPPTYPE_ENUM: + return sizeof(int); case FD::CPPTYPE_MESSAGE: return sizeof(Message*); @@ -190,9 +211,7 @@ int OneofFieldSpaceUsed(const FieldDescriptor* field) { return 0; } -inline int DivideRoundingUp(int i, int j) { - return (i + (j - 1)) / j; -} +inline int DivideRoundingUp(int i, int j) { return (i + (j - 1)) / j; } static const int kSafeAlignment = sizeof(uint64); static const int kMaxOneofUnionSize = sizeof(uint64); @@ -203,9 +222,7 @@ inline int AlignTo(int offset, int alignment) { // Rounds the given byte offset up to the next offset aligned such that any // type may be stored at it. -inline int AlignOffset(int offset) { - return AlignTo(offset, kSafeAlignment); -} +inline int AlignOffset(int offset) { return AlignTo(offset, kSafeAlignment); } #define bitsizeof(T) (sizeof(T) * 8) @@ -241,15 +258,13 @@ class DynamicMessage : public Message { TypeInfo() : prototype(NULL) {} - ~TypeInfo() { - delete prototype; - } + ~TypeInfo() { delete prototype; } }; DynamicMessage(const TypeInfo* type_info); // This should only be used by GetPrototypeNoLock() to avoid dead lock. - DynamicMessage(const TypeInfo* type_info, bool lock_factory); + DynamicMessage(TypeInfo* type_info, bool lock_factory); ~DynamicMessage(); @@ -258,14 +273,14 @@ class DynamicMessage : public Message { // implements Message ---------------------------------------------- - Message* New() const; - Message* New(::google::protobuf::Arena* arena) const; - ::google::protobuf::Arena* GetArena() const { return arena_; } + Message* New() const override; + Message* New(Arena* arena) const override; + Arena* GetArena() const override { return arena_; } - int GetCachedSize() const; - void SetCachedSize(int size) const; + int GetCachedSize() const override; + void SetCachedSize(int size) const override; - Metadata GetMetadata() const; + Metadata GetMetadata() const override; // We actually allocate more memory than sizeof(*this) when this // class's memory is allocated via the global operator new. Thus, we need to @@ -273,13 +288,11 @@ class DynamicMessage : public Message { // care of for us. This makes DynamicMessage compatible with -fsized-delete. // It doesn't work for MSVC though. #ifndef _MSC_VER - static void operator delete(void* ptr) { - ::operator delete(ptr); - } + static void operator delete(void* ptr) { ::operator delete(ptr); } #endif // !_MSC_VER private: - DynamicMessage(const TypeInfo* type_info, ::google::protobuf::Arena* arena); + DynamicMessage(const TypeInfo* type_info, Arena* arena); void SharedCtor(bool lock_factory); @@ -299,8 +312,7 @@ class DynamicMessage : public Message { const TypeInfo* type_info_; Arena* const arena_; - // TODO(kenton): Make this an atomic when C++ supports it. - mutable int cached_byte_size_; + mutable std::atomic cached_byte_size_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMessage); }; @@ -309,14 +321,20 @@ DynamicMessage::DynamicMessage(const TypeInfo* type_info) SharedCtor(true); } -DynamicMessage::DynamicMessage(const TypeInfo* type_info, - ::google::protobuf::Arena* arena) +DynamicMessage::DynamicMessage(const TypeInfo* type_info, Arena* arena) : type_info_(type_info), arena_(arena), cached_byte_size_(0) { SharedCtor(true); } -DynamicMessage::DynamicMessage(const TypeInfo* type_info, bool lock_factory) +DynamicMessage::DynamicMessage(TypeInfo* type_info, bool lock_factory) : type_info_(type_info), arena_(NULL), cached_byte_size_(0) { + // The prototype in type_info has to be set before creating the prototype + // instance on memory. e.g., message Foo { map a = 1; }. When + // creating prototype for Foo, prototype of the map entry will also be + // created, which needs the address of the prototype of Foo (the value in + // map). To break the cyclic dependency, we have to assign the address of + // prototype into type_info first. + type_info->prototype = this; SharedCtor(lock_factory); } @@ -332,7 +350,7 @@ void DynamicMessage::SharedCtor(bool lock_factory) { const Descriptor* descriptor = type_info_->type; // Initialize oneof cases. - for (int i = 0 ; i < descriptor->oneof_decl_count(); ++i) { + for (int i = 0; i < descriptor->oneof_decl_count(); ++i) { new (OffsetToPointer(type_info_->oneof_case_offset + sizeof(uint32) * i)) uint32(0); } @@ -359,18 +377,18 @@ void DynamicMessage::SharedCtor(bool lock_factory) { } \ break; - HANDLE_TYPE(INT32 , int32 ); - HANDLE_TYPE(INT64 , int64 ); + HANDLE_TYPE(INT32, int32); + HANDLE_TYPE(INT64, int64); HANDLE_TYPE(UINT32, uint32); HANDLE_TYPE(UINT64, uint64); HANDLE_TYPE(DOUBLE, double); - HANDLE_TYPE(FLOAT , float ); - HANDLE_TYPE(BOOL , bool ); + HANDLE_TYPE(FLOAT, float); + HANDLE_TYPE(BOOL, bool); #undef HANDLE_TYPE case FieldDescriptor::CPPTYPE_ENUM: if (!field->is_repeated()) { - new(field_ptr) int(field->default_value_enum()->number()); + new (field_ptr) int(field->default_value_enum()->number()); } else { new (field_ptr) RepeatedField(arena_); } @@ -381,7 +399,7 @@ void DynamicMessage::SharedCtor(bool lock_factory) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: if (!field->is_repeated()) { - const string* default_value; + const std::string* default_value; if (is_prototype()) { default_value = &field->default_value_string(); } else { @@ -390,10 +408,10 @@ void DynamicMessage::SharedCtor(bool lock_factory) { type_info_->offsets[i])) ->Get()); } - ArenaStringPtr* asp = new(field_ptr) ArenaStringPtr(); + ArenaStringPtr* asp = new (field_ptr) ArenaStringPtr(); asp->UnsafeSetDefault(default_value); } else { - new (field_ptr) RepeatedPtrField(arena_); + new (field_ptr) RepeatedPtrField(arena_); } break; } @@ -401,7 +419,7 @@ void DynamicMessage::SharedCtor(bool lock_factory) { case FieldDescriptor::CPPTYPE_MESSAGE: { if (!field->is_repeated()) { - new(field_ptr) Message*(NULL); + new (field_ptr) Message*(NULL); } else { if (IsMapFieldInApi(field)) { // We need to lock in most cases to avoid data racing. Only not lock @@ -447,7 +465,8 @@ DynamicMessage::~DynamicMessage() { if (type_info_->extensions_offset != -1) { reinterpret_cast( - OffsetToPointer(type_info_->extensions_offset))->~ExtensionSet(); + OffsetToPointer(type_info_->extensions_offset)) + ->~ExtensionSet(); } // We need to manually run the destructors for repeated fields and strings, @@ -461,21 +480,20 @@ DynamicMessage::~DynamicMessage() { for (int i = 0; i < descriptor->field_count(); i++) { const FieldDescriptor* field = descriptor->field(i); if (field->containing_oneof()) { - void* field_ptr = OffsetToPointer( - type_info_->oneof_case_offset - + sizeof(uint32) * field->containing_oneof()->index()); - if (*(reinterpret_cast(field_ptr)) == - field->number()) { - field_ptr = OffsetToPointer(type_info_->offsets[ - descriptor->field_count() + field->containing_oneof()->index()]); + void* field_ptr = + OffsetToPointer(type_info_->oneof_case_offset + + sizeof(uint32) * field->containing_oneof()->index()); + if (*(reinterpret_cast(field_ptr)) == field->number()) { + field_ptr = OffsetToPointer( + type_info_->offsets[descriptor->field_count() + + field->containing_oneof()->index()]); if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) { switch (field->options().ctype()) { default: case FieldOptions::STRING: { - const ::std::string* default_value = + const std::string* default_value = &(reinterpret_cast( - reinterpret_cast( - type_info_->prototype) + + reinterpret_cast(type_info_->prototype) + type_info_->offsets[i]) ->Get()); reinterpret_cast(field_ptr)->Destroy( @@ -493,28 +511,28 @@ DynamicMessage::~DynamicMessage() { if (field->is_repeated()) { switch (field->cpp_type()) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case FieldDescriptor::CPPTYPE_##UPPERCASE : \ - reinterpret_cast*>(field_ptr) \ - ->~RepeatedField(); \ - break +#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ + case FieldDescriptor::CPPTYPE_##UPPERCASE: \ + reinterpret_cast*>(field_ptr) \ + ->~RepeatedField(); \ + break - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); + HANDLE_TYPE(INT32, int32); + HANDLE_TYPE(INT64, int64); HANDLE_TYPE(UINT32, uint32); HANDLE_TYPE(UINT64, uint64); HANDLE_TYPE(DOUBLE, double); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, int); + HANDLE_TYPE(FLOAT, float); + HANDLE_TYPE(BOOL, bool); + HANDLE_TYPE(ENUM, int); #undef HANDLE_TYPE case FieldDescriptor::CPPTYPE_STRING: switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: - reinterpret_cast*>(field_ptr) - ->~RepeatedPtrField(); + reinterpret_cast*>(field_ptr) + ->~RepeatedPtrField(); break; } break; @@ -533,18 +551,18 @@ DynamicMessage::~DynamicMessage() { switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: { - const ::std::string* default_value = + const std::string* default_value = &(reinterpret_cast( type_info_->prototype->OffsetToPointer( type_info_->offsets[i])) ->Get()); - reinterpret_cast(field_ptr)->Destroy( - default_value, NULL); + reinterpret_cast(field_ptr)->Destroy(default_value, + NULL); break; } } } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - if (!is_prototype()) { + if (!is_prototype()) { Message* message = *reinterpret_cast(field_ptr); if (message != NULL) { delete message; @@ -572,14 +590,14 @@ void DynamicMessage::CrossLinkPrototypes() { // For singular fields, the field is just a pointer which should // point to the prototype. *reinterpret_cast(field_ptr) = - factory->GetPrototypeNoLock(field->message_type()); + factory->GetPrototypeNoLock(field->message_type()); } } } Message* DynamicMessage::New() const { return New(NULL); } -Message* DynamicMessage::New(::google::protobuf::Arena* arena) const { +Message* DynamicMessage::New(Arena* arena) const { if (arena != NULL) { void* new_base = Arena::CreateArray(arena, type_info_->size); memset(new_base, 0, type_info_->size); @@ -592,16 +610,11 @@ Message* DynamicMessage::New(::google::protobuf::Arena* arena) const { } int DynamicMessage::GetCachedSize() const { - return cached_byte_size_; + return cached_byte_size_.load(std::memory_order_relaxed); } void DynamicMessage::SetCachedSize(int size) const { - // This is theoretically not thread-compatible, but in practice it works - // because if multiple threads write this simultaneously, they will be - // writing the exact same value. - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - cached_byte_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + cached_byte_size_.store(size, std::memory_order_relaxed); } Metadata DynamicMessage::GetMetadata() const { @@ -614,25 +627,25 @@ Metadata DynamicMessage::GetMetadata() const { // =================================================================== struct DynamicMessageFactory::PrototypeMap { - typedef hash_map Map; + typedef std::unordered_map + Map; Map map_; }; DynamicMessageFactory::DynamicMessageFactory() - : pool_(NULL), delegate_to_generated_factory_(false), - prototypes_(new PrototypeMap) { -} + : pool_(NULL), + delegate_to_generated_factory_(false), + prototypes_(new PrototypeMap) {} DynamicMessageFactory::DynamicMessageFactory(const DescriptorPool* pool) - : pool_(pool), delegate_to_generated_factory_(false), - prototypes_(new PrototypeMap) { -} + : pool_(pool), + delegate_to_generated_factory_(false), + prototypes_(new PrototypeMap) {} DynamicMessageFactory::~DynamicMessageFactory() { for (PrototypeMap::Map::iterator iter = prototypes_->map_.begin(); iter != prototypes_->map_.end(); ++iter) { - DeleteDefaultOneofInstance(iter->second->type, - iter->second->offsets.get(), + DeleteDefaultOneofInstance(iter->second->type, iter->second->offsets.get(), iter->second->prototype); delete iter->second; } @@ -672,8 +685,7 @@ const Message* DynamicMessageFactory::GetPrototypeNoLock( // or not that field is set. // Compute size and offsets. - uint32* offsets = - new uint32[type->field_count() + type->oneof_decl_count()]; + uint32* offsets = new uint32[type->field_count() + type->oneof_decl_count()]; type_info->offsets.reset(offsets); // Decide all field offsets by packing in order. @@ -688,7 +700,7 @@ const Message* DynamicMessageFactory::GetPrototypeNoLock( } else { type_info->has_bits_offset = size; int has_bits_array_size = - DivideRoundingUp(type->field_count(), bitsizeof(uint32)); + DivideRoundingUp(type->field_count(), bitsizeof(uint32)); size += has_bits_array_size * sizeof(uint32); size = AlignOffset(size); @@ -749,7 +761,6 @@ const Message* DynamicMessageFactory::GetPrototypeNoLock( // alignment is not necessary. type_info->size = size; - // Construct the reflection object. if (type->oneof_decl_count() > 0) { @@ -770,35 +781,25 @@ const Message* DynamicMessageFactory::GetPrototypeNoLock( void* base = operator new(size); memset(base, 0, size); - // The prototype in type_info has to be set before creating the prototype - // instance on memory. e.g., message Foo { map a = 1; }. When - // creating prototype for Foo, prototype of the map entry will also be - // created, which needs the address of the prototype of Foo (the value in - // map). To break the cyclic dependency, we have to assgin the address of - // prototype into type_info first. - type_info->prototype = static_cast(base); - // We have already locked the factory so we should not lock in the constructor // of dynamic message to avoid dead lock. DynamicMessage* prototype = new (base) DynamicMessage(type_info, false); if (type->oneof_decl_count() > 0 || num_weak_fields > 0) { // Construct default oneof instance. - ConstructDefaultOneofInstance(type_info->type, - type_info->offsets.get(), + ConstructDefaultOneofInstance(type_info->type, type_info->offsets.get(), prototype); } - internal::ReflectionSchema schema = { - type_info->prototype, - type_info->offsets.get(), - type_info->has_bits_indices.get(), - type_info->has_bits_offset, - type_info->internal_metadata_offset, - type_info->extensions_offset, - type_info->oneof_case_offset, - type_info->size, - type_info->weak_field_map_offset}; + internal::ReflectionSchema schema = {type_info->prototype, + type_info->offsets.get(), + type_info->has_bits_indices.get(), + type_info->has_bits_offset, + type_info->internal_metadata_offset, + type_info->extensions_offset, + type_info->oneof_case_offset, + type_info->size, + type_info->weak_field_map_offset}; type_info->reflection.reset(new GeneratedMessageReflection( type_info->type, schema, type_info->pool, this)); @@ -810,31 +811,31 @@ const Message* DynamicMessageFactory::GetPrototypeNoLock( } void DynamicMessageFactory::ConstructDefaultOneofInstance( - const Descriptor* type, - const uint32 offsets[], + const Descriptor* type, const uint32 offsets[], void* default_oneof_or_weak_instance) { for (int i = 0; i < type->oneof_decl_count(); i++) { for (int j = 0; j < type->oneof_decl(i)->field_count(); j++) { const FieldDescriptor* field = type->oneof_decl(i)->field(j); - void* field_ptr = reinterpret_cast( - default_oneof_or_weak_instance) + offsets[field->index()]; + void* field_ptr = + reinterpret_cast(default_oneof_or_weak_instance) + + offsets[field->index()]; switch (field->cpp_type()) { -#define HANDLE_TYPE(CPPTYPE, TYPE) \ - case FieldDescriptor::CPPTYPE_##CPPTYPE: \ - new(field_ptr) TYPE(field->default_value_##TYPE()); \ - break; +#define HANDLE_TYPE(CPPTYPE, TYPE) \ + case FieldDescriptor::CPPTYPE_##CPPTYPE: \ + new (field_ptr) TYPE(field->default_value_##TYPE()); \ + break; - HANDLE_TYPE(INT32 , int32 ); - HANDLE_TYPE(INT64 , int64 ); + HANDLE_TYPE(INT32, int32); + HANDLE_TYPE(INT64, int64); HANDLE_TYPE(UINT32, uint32); HANDLE_TYPE(UINT64, uint64); HANDLE_TYPE(DOUBLE, double); - HANDLE_TYPE(FLOAT , float ); - HANDLE_TYPE(BOOL , bool ); + HANDLE_TYPE(FLOAT, float); + HANDLE_TYPE(BOOL, bool); #undef HANDLE_TYPE case FieldDescriptor::CPPTYPE_ENUM: - new(field_ptr) int(field->default_value_enum()->number()); + new (field_ptr) int(field->default_value_enum()->number()); break; case FieldDescriptor::CPPTYPE_STRING: switch (field->options().ctype()) { @@ -847,7 +848,7 @@ void DynamicMessageFactory::ConstructDefaultOneofInstance( break; case FieldDescriptor::CPPTYPE_MESSAGE: { - new(field_ptr) Message*(NULL); + new (field_ptr) Message*(NULL); break; } } @@ -856,8 +857,7 @@ void DynamicMessageFactory::ConstructDefaultOneofInstance( } void DynamicMessageFactory::DeleteDefaultOneofInstance( - const Descriptor* type, - const uint32 offsets[], + const Descriptor* type, const uint32 offsets[], const void* default_oneof_instance) { for (int i = 0; i < type->oneof_decl_count(); i++) { for (int j = 0; j < type->oneof_decl(i)->field_count(); j++) { diff --git a/third_party/protobuf/src/google/protobuf/dynamic_message.h b/third_party/protobuf/src/google/protobuf/dynamic_message.h index d84cc8af..765f9e3a 100644 --- a/third_party/protobuf/src/google/protobuf/dynamic_message.h +++ b/third_party/protobuf/src/google/protobuf/dynamic_message.h @@ -42,17 +42,23 @@ #include #include -#include -#include #include +#include #include +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + +#include namespace google { namespace protobuf { // Defined in other files. -class Descriptor; // descriptor.h -class DescriptorPool; // descriptor.h +class Descriptor; // descriptor.h +class DescriptorPool; // descriptor.h // Constructs implementations of Message which can emulate types which are not // known at compile-time. @@ -71,7 +77,7 @@ class DescriptorPool; // descriptor.h // encapsulates this "cache". All DynamicMessages of the same type created // from the same factory will share the same support data. Any Descriptors // used with a particular factory must outlive the factory. -class LIBPROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory { +class PROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory { public: // Construct a DynamicMessageFactory that will search for extensions in // the DescriptorPool in which the extendee is defined. @@ -115,20 +121,20 @@ class LIBPROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory { // outlive the DynamicMessageFactory. // // The method is thread-safe. - const Message* GetPrototype(const Descriptor* type); + const Message* GetPrototype(const Descriptor* type) override; private: const DescriptorPool* pool_; bool delegate_to_generated_factory_; - // This struct just contains a hash_map. We can't #include from + // This struct just contains a hash_map. We can't #include from // this header due to hacks needed for hash_map portability in the open source // release. Namely, stubs/hash.h, which defines hash_map portably, is not a // public header (for good reason), but dynamic_message.h is, and public // headers may only #include other public headers. struct PrototypeMap; std::unique_ptr prototypes_; - mutable Mutex prototypes_mutex_; + mutable internal::WrappedMutex prototypes_mutex_; friend class DynamicMessage; const Message* GetPrototypeNoLock(const Descriptor* type); @@ -147,10 +153,9 @@ class LIBPROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory { }; // Helper for computing a sorted list of map entries via reflection. -class LIBPROTOBUF_EXPORT DynamicMapSorter { +class PROTOBUF_EXPORT DynamicMapSorter { public: - static std::vector Sort(const Message& message, - int map_size, + static std::vector Sort(const Message& message, int map_size, const Reflection* reflection, const FieldDescriptor* field) { std::vector result(static_cast(map_size)); @@ -158,7 +163,8 @@ class LIBPROTOBUF_EXPORT DynamicMapSorter { reflection->GetRepeatedPtrField(message, field); size_t i = 0; for (RepeatedPtrField::const_pointer_iterator it = - map_field.pointer_begin(); it != map_field.pointer_end(); ) { + map_field.pointer_begin(); + it != map_field.pointer_end();) { result[i++] = *it++; } GOOGLE_DCHECK_EQ(result.size(), i); @@ -168,9 +174,9 @@ class LIBPROTOBUF_EXPORT DynamicMapSorter { #ifndef NDEBUG for (size_t j = 1; j < static_cast(map_size); j++) { if (!comparator(result[j - 1], result[j])) { - GOOGLE_LOG(ERROR) << (comparator(result[j], result[j - 1]) ? - "internal error in map key sorting" : - "map keys are not unique"); + GOOGLE_LOG(ERROR) << (comparator(result[j], result[j - 1]) + ? "internal error in map key sorting" + : "map keys are not unique"); } } #endif @@ -178,7 +184,7 @@ class LIBPROTOBUF_EXPORT DynamicMapSorter { } private: - class LIBPROTOBUF_EXPORT MapEntryMessageComparator { + class PROTOBUF_EXPORT MapEntryMessageComparator { public: explicit MapEntryMessageComparator(const Descriptor* descriptor) : field_(descriptor->field(0)) {} @@ -212,8 +218,8 @@ class LIBPROTOBUF_EXPORT DynamicMapSorter { return first < second; } case FieldDescriptor::CPPTYPE_STRING: { - string first = reflection->GetString(*a, field_); - string second = reflection->GetString(*b, field_); + std::string first = reflection->GetString(*a, field_); + std::string second = reflection->GetString(*b, field_); return first < second; } default: @@ -228,6 +234,8 @@ class LIBPROTOBUF_EXPORT DynamicMapSorter { }; } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_DYNAMIC_MESSAGE_H__ diff --git a/third_party/protobuf/src/google/protobuf/dynamic_message_unittest.cc b/third_party/protobuf/src/google/protobuf/dynamic_message_unittest.cc index 94446b08..42759de7 100644 --- a/third_party/protobuf/src/google/protobuf/dynamic_message_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/dynamic_message_unittest.cc @@ -72,7 +72,7 @@ class DynamicMessageTest : public ::testing::TestWithParam { const Descriptor* proto3_descriptor_; const Message* proto3_prototype_; - DynamicMessageTest(): factory_(&pool_) {} + DynamicMessageTest() : factory_(&pool_) {} virtual void SetUp() { // We want to make sure that DynamicMessage works (particularly with @@ -86,11 +86,11 @@ class DynamicMessageTest : public ::testing::TestWithParam { unittest::TestAllTypes::descriptor()->file()->CopyTo(&unittest_file); unittest_import::ImportMessage::descriptor()->file()->CopyTo( - &unittest_import_file); + &unittest_import_file); unittest_import::PublicImportMessage::descriptor()->file()->CopyTo( - &unittest_import_public_file); - proto2_nofieldpresence_unittest::TestAllTypes::descriptor()-> - file()->CopyTo(&unittest_no_field_presence_file); + &unittest_import_public_file); + proto2_nofieldpresence_unittest::TestAllTypes::descriptor()->file()->CopyTo( + &unittest_no_field_presence_file); ASSERT_TRUE(pool_.BuildFile(unittest_import_public_file) != NULL); ASSERT_TRUE(pool_.BuildFile(unittest_import_file) != NULL); @@ -102,23 +102,22 @@ class DynamicMessageTest : public ::testing::TestWithParam { prototype_ = factory_.GetPrototype(descriptor_); extensions_descriptor_ = - pool_.FindMessageTypeByName("protobuf_unittest.TestAllExtensions"); + pool_.FindMessageTypeByName("protobuf_unittest.TestAllExtensions"); ASSERT_TRUE(extensions_descriptor_ != NULL); extensions_prototype_ = factory_.GetPrototype(extensions_descriptor_); packed_descriptor_ = - pool_.FindMessageTypeByName("protobuf_unittest.TestPackedTypes"); + pool_.FindMessageTypeByName("protobuf_unittest.TestPackedTypes"); ASSERT_TRUE(packed_descriptor_ != NULL); packed_prototype_ = factory_.GetPrototype(packed_descriptor_); oneof_descriptor_ = - pool_.FindMessageTypeByName("protobuf_unittest.TestOneof2"); + pool_.FindMessageTypeByName("protobuf_unittest.TestOneof2"); ASSERT_TRUE(oneof_descriptor_ != NULL); oneof_prototype_ = factory_.GetPrototype(oneof_descriptor_); - proto3_descriptor_ = - pool_.FindMessageTypeByName( - "proto2_nofieldpresence_unittest.TestAllTypes"); + proto3_descriptor_ = pool_.FindMessageTypeByName( + "proto2_nofieldpresence_unittest.TestAllTypes"); ASSERT_TRUE(proto3_descriptor_ != NULL); proto3_prototype_ = factory_.GetPrototype(proto3_descriptor_); } @@ -146,7 +145,7 @@ TEST_P(DynamicMessageTest, IndependentOffsets) { // one to a unique value then checking that they all still have those // unique values (i.e. they don't stomp each other). Arena arena; - Message* message = prototype_->New(GetParam()? &arena : NULL); + Message* message = prototype_->New(GetParam() ? &arena : NULL); TestUtil::ReflectionTester reflection_tester(descriptor_); reflection_tester.SetAllFieldsViaReflection(message); @@ -160,7 +159,7 @@ TEST_P(DynamicMessageTest, IndependentOffsets) { TEST_P(DynamicMessageTest, Extensions) { // Check that extensions work. Arena arena; - Message* message = extensions_prototype_->New(GetParam()? &arena : NULL); + Message* message = extensions_prototype_->New(GetParam() ? &arena : NULL); TestUtil::ReflectionTester reflection_tester(extensions_descriptor_); reflection_tester.SetAllFieldsViaReflection(message); @@ -174,7 +173,7 @@ TEST_P(DynamicMessageTest, Extensions) { TEST_P(DynamicMessageTest, PackedFields) { // Check that packed fields work properly. Arena arena; - Message* message = packed_prototype_->New(GetParam()? &arena : NULL); + Message* message = packed_prototype_->New(GetParam() ? &arena : NULL); TestUtil::ReflectionTester reflection_tester(packed_descriptor_); reflection_tester.SetPackedFieldsViaReflection(message); @@ -188,23 +187,25 @@ TEST_P(DynamicMessageTest, PackedFields) { TEST_P(DynamicMessageTest, Oneof) { // Check that oneof fields work properly. Arena arena; - Message* message = oneof_prototype_->New(GetParam()? &arena : NULL); + Message* message = oneof_prototype_->New(GetParam() ? &arena : NULL); // Check default values. const Descriptor* descriptor = message->GetDescriptor(); const Reflection* reflection = message->GetReflection(); - EXPECT_EQ(0, reflection->GetInt32( - *message, descriptor->FindFieldByName("foo_int"))); + EXPECT_EQ(0, reflection->GetInt32(*message, + descriptor->FindFieldByName("foo_int"))); EXPECT_EQ("", reflection->GetString( - *message, descriptor->FindFieldByName("foo_string"))); + *message, descriptor->FindFieldByName("foo_string"))); + EXPECT_EQ("", reflection->GetString(*message, + descriptor->FindFieldByName("foo_cord"))); EXPECT_EQ("", reflection->GetString( - *message, descriptor->FindFieldByName("foo_cord"))); + *message, descriptor->FindFieldByName("foo_string_piece"))); EXPECT_EQ("", reflection->GetString( - *message, descriptor->FindFieldByName("foo_string_piece"))); - EXPECT_EQ("", reflection->GetString( - *message, descriptor->FindFieldByName("foo_bytes"))); - EXPECT_EQ(unittest::TestOneof2::FOO, reflection->GetEnum( - *message, descriptor->FindFieldByName("foo_enum"))->number()); + *message, descriptor->FindFieldByName("foo_bytes"))); + EXPECT_EQ( + unittest::TestOneof2::FOO, + reflection->GetEnum(*message, descriptor->FindFieldByName("foo_enum")) + ->number()); const Descriptor* nested_descriptor; const Message* nested_prototype; nested_descriptor = @@ -219,23 +220,26 @@ TEST_P(DynamicMessageTest, Oneof) { pool_.FindMessageTypeByName("protobuf_unittest.TestOneof2.FooGroup"); foogroup_prototype = factory_.GetPrototype(foogroup_descriptor); EXPECT_EQ(foogroup_prototype, - &reflection->GetMessage( - *message, descriptor->FindFieldByName("foogroup"))); + &reflection->GetMessage(*message, + descriptor->FindFieldByName("foogroup"))); EXPECT_NE(foogroup_prototype, &reflection->GetMessage( *message, descriptor->FindFieldByName("foo_lazy_message"))); - EXPECT_EQ(5, reflection->GetInt32( - *message, descriptor->FindFieldByName("bar_int"))); + EXPECT_EQ(5, reflection->GetInt32(*message, + descriptor->FindFieldByName("bar_int"))); EXPECT_EQ("STRING", reflection->GetString( - *message, descriptor->FindFieldByName("bar_string"))); + *message, descriptor->FindFieldByName("bar_string"))); EXPECT_EQ("CORD", reflection->GetString( - *message, descriptor->FindFieldByName("bar_cord"))); - EXPECT_EQ("SPIECE", reflection->GetString( - *message, descriptor->FindFieldByName("bar_string_piece"))); + *message, descriptor->FindFieldByName("bar_cord"))); + EXPECT_EQ("SPIECE", + reflection->GetString( + *message, descriptor->FindFieldByName("bar_string_piece"))); EXPECT_EQ("BYTES", reflection->GetString( - *message, descriptor->FindFieldByName("bar_bytes"))); - EXPECT_EQ(unittest::TestOneof2::BAR, reflection->GetEnum( - *message, descriptor->FindFieldByName("bar_enum"))->number()); + *message, descriptor->FindFieldByName("bar_bytes"))); + EXPECT_EQ( + unittest::TestOneof2::BAR, + reflection->GetEnum(*message, descriptor->FindFieldByName("bar_enum")) + ->number()); // Check set functions. TestUtil::ReflectionTester reflection_tester(oneof_descriptor_); @@ -254,7 +258,7 @@ TEST_P(DynamicMessageTest, SpaceUsed) { // to test very much here. Just make sure it appears to be working. Arena arena; - Message* message = prototype_->New(GetParam()? &arena : NULL); + Message* message = prototype_->New(GetParam() ? &arena : NULL); TestUtil::ReflectionTester reflection_tester(descriptor_); int initial_space_used = message->SpaceUsed(); @@ -316,7 +320,7 @@ TEST_F(DynamicMessageTest, Proto3) { delete message; } -INSTANTIATE_TEST_CASE_P(UseArena, DynamicMessageTest, ::testing::Bool()); +INSTANTIATE_TEST_SUITE_P(UseArena, DynamicMessageTest, ::testing::Bool()); } // namespace protobuf } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/empty.pb.cc b/third_party/protobuf/src/google/protobuf/empty.pb.cc index 9b53c546..eb1e4667 100644 --- a/third_party/protobuf/src/google/protobuf/empty.pb.cc +++ b/third_party/protobuf/src/google/protobuf/empty.pb.cc @@ -6,136 +6,105 @@ #include #include -#include #include -#include +#include +#include #include #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) - -namespace google { -namespace protobuf { +#include +PROTOBUF_NAMESPACE_OPEN class EmptyDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _Empty_default_instance_; -} // namespace protobuf -} // namespace google -namespace protobuf_google_2fprotobuf_2fempty_2eproto { -static void InitDefaultsEmpty() { +PROTOBUF_NAMESPACE_CLOSE +static void InitDefaultsscc_info_Empty_google_2fprotobuf_2fempty_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_Empty_default_instance_; - new (ptr) ::google::protobuf::Empty(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_Empty_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::Empty(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::Empty::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::Empty::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Empty = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsEmpty}, {}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Empty_google_2fprotobuf_2fempty_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_Empty_google_2fprotobuf_2fempty_2eproto}, {}}; -void InitDefaults() { - ::google::protobuf::internal::InitSCC(&scc_info_Empty.base); -} +static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_google_2fprotobuf_2fempty_2eproto[1]; +static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fempty_2eproto = nullptr; +static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fempty_2eproto = nullptr; -::google::protobuf::Metadata file_level_metadata[1]; - -const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_google_2fprotobuf_2fempty_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Empty, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Empty, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ }; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, sizeof(::google::protobuf::Empty)}, +static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, -1, sizeof(PROTOBUF_NAMESPACE_ID::Empty)}, }; -static ::google::protobuf::Message const * const file_default_instances[] = { - reinterpret_cast(&::google::protobuf::_Empty_default_instance_), +static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_Empty_default_instance_), }; -void protobuf_AssignDescriptors() { - AddDescriptors(); - AssignDescriptors( - "google/protobuf/empty.proto", schemas, file_default_instances, TableStruct::offsets, - file_level_metadata, NULL, NULL); -} +const char descriptor_table_protodef_google_2fprotobuf_2fempty_2eproto[] = + "\n\033google/protobuf/empty.proto\022\017google.pr" + "otobuf\"\007\n\005EmptyBv\n\023com.google.protobufB\n" + "EmptyProtoP\001Z\'github.com/golang/protobuf" + "/ptypes/empty\370\001\001\242\002\003GPB\252\002\036Google.Protobuf" + ".WellKnownTypesb\006proto3" + ; +static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_google_2fprotobuf_2fempty_2eproto_deps[1] = { +}; +static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_google_2fprotobuf_2fempty_2eproto_sccs[1] = { + &scc_info_Empty_google_2fprotobuf_2fempty_2eproto.base, +}; +static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fempty_2eproto_once; +static bool descriptor_table_google_2fprotobuf_2fempty_2eproto_initialized = false; +const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fempty_2eproto = { + &descriptor_table_google_2fprotobuf_2fempty_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fempty_2eproto, "google/protobuf/empty.proto", 183, + &descriptor_table_google_2fprotobuf_2fempty_2eproto_once, descriptor_table_google_2fprotobuf_2fempty_2eproto_sccs, descriptor_table_google_2fprotobuf_2fempty_2eproto_deps, 1, 0, + schemas, file_default_instances, TableStruct_google_2fprotobuf_2fempty_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2fempty_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2fempty_2eproto, file_level_service_descriptors_google_2fprotobuf_2fempty_2eproto, +}; -void protobuf_AssignDescriptorsOnce() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); -} - -void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1); -} - -void AddDescriptorsImpl() { - InitDefaults(); - static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - "\n\033google/protobuf/empty.proto\022\017google.pr" - "otobuf\"\007\n\005EmptyBv\n\023com.google.protobufB\n" - "EmptyProtoP\001Z\'github.com/golang/protobuf" - "/ptypes/empty\370\001\001\242\002\003GPB\252\002\036Google.Protobuf" - ".WellKnownTypesb\006proto3" - }; - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - descriptor, 183); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "google/protobuf/empty.proto", &protobuf_RegisterTypes); -} - -void AddDescriptors() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); -} -// Force AddDescriptors() to be called at dynamic initialization time. -struct StaticDescriptorInitializer { - StaticDescriptorInitializer() { - AddDescriptors(); - } -} static_descriptor_initializer; -} // namespace protobuf_google_2fprotobuf_2fempty_2eproto -namespace google { -namespace protobuf { +// Force running AddDescriptors() at dynamic initialization time. +static bool dynamic_init_dummy_google_2fprotobuf_2fempty_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fempty_2eproto), true); +PROTOBUF_NAMESPACE_OPEN // =================================================================== void Empty::InitAsDefaultInstance() { } +class Empty::HasBitSetters { + public: +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Empty::Empty() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fempty_2eproto::scc_info_Empty.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Empty) } -Empty::Empty(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +Empty::Empty(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fempty_2eproto::scc_info_Empty.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Empty) } Empty::Empty(const Empty& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.Empty) } @@ -149,52 +118,75 @@ Empty::~Empty() { } void Empty::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void Empty::ArenaDtor(void* object) { Empty* _this = reinterpret_cast< Empty* >(object); (void)_this; } -void Empty::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void Empty::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void Empty::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* Empty::descriptor() { - ::protobuf_google_2fprotobuf_2fempty_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fempty_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const Empty& Empty::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fempty_2eproto::scc_info_Empty.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_Empty_google_2fprotobuf_2fempty_2eproto.base); return *internal_default_instance(); } void Empty::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.Empty) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* Empty::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + default: { + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Empty::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Empty) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; handle_unusual: if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); } success: @@ -205,30 +197,30 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void Empty::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.Empty) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); + if (_internal_metadata_.have_unknown_fields()) { + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( + _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.Empty) } -::google::protobuf::uint8* Empty::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* Empty::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Empty) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); + if (_internal_metadata_.have_unknown_fields()) { + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( + _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Empty) return target; @@ -238,25 +230,29 @@ size_t Empty::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.protobuf.Empty) size_t total_size = 0; - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { + if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( + _internal_metadata_.unknown_fields()); } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void Empty::MergeFrom(const ::google::protobuf::Message& from) { +void Empty::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Empty) GOOGLE_DCHECK_NE(&from, this); const Empty* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Empty) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Empty) MergeFrom(*source); @@ -267,12 +263,12 @@ void Empty::MergeFrom(const Empty& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Empty) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; } -void Empty::CopyFrom(const ::google::protobuf::Message& from) { +void Empty::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Empty) if (&from == this) return; Clear(); @@ -299,7 +295,7 @@ void Empty::Swap(Empty* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -314,21 +310,18 @@ void Empty::InternalSwap(Empty* other) { _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata Empty::GetMetadata() const { - protobuf_google_2fprotobuf_2fempty_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fempty_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata Empty::GetMetadata() const { + return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Empty* Arena::CreateMaybeMessage< ::google::protobuf::Empty >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::Empty >(arena); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::Empty* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Empty >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::Empty >(arena); } -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) +#include diff --git a/third_party/protobuf/src/google/protobuf/empty.pb.h b/third_party/protobuf/src/google/protobuf/empty.pb.h index 4d651080..8d48bb9e 100644 --- a/third_party/protobuf/src/google/protobuf/empty.pb.h +++ b/third_party/protobuf/src/google/protobuf/empty.pb.h @@ -1,24 +1,25 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/empty.proto -#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto -#define PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto +#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto +#include #include -#include - -#if GOOGLE_PROTOBUF_VERSION < 3006001 +#include +#if PROTOBUF_VERSION < 3008000 #error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update +#error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3008000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please +#error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include @@ -26,59 +27,61 @@ #include #include #include +#include #include #include // IWYU pragma: export #include // IWYU pragma: export #include // @@protoc_insertion_point(includes) -#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fempty_2eproto LIBPROTOBUF_EXPORT +#include +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fempty_2eproto PROTOBUF_EXPORT +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE -namespace protobuf_google_2fprotobuf_2fempty_2eproto { // Internal implementation detail -- do not use these members. -struct LIBPROTOBUF_EXPORT TableStruct { - static const ::google::protobuf::internal::ParseTableField entries[]; - static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; - static const ::google::protobuf::internal::ParseTable schema[1]; - static const ::google::protobuf::internal::FieldMetadata field_metadata[]; - static const ::google::protobuf::internal::SerializationTable serialization_table[]; - static const ::google::protobuf::uint32 offsets[]; +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fempty_2eproto { + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; + static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; + static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; -void LIBPROTOBUF_EXPORT AddDescriptors(); -} // namespace protobuf_google_2fprotobuf_2fempty_2eproto -namespace google { -namespace protobuf { +extern PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fempty_2eproto; +PROTOBUF_NAMESPACE_OPEN class Empty; class EmptyDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern EmptyDefaultTypeInternal _Empty_default_instance_; -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Empty* Arena::CreateMaybeMessage<::google::protobuf::Empty>(Arena*); -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { +PROTOBUF_EXPORT extern EmptyDefaultTypeInternal _Empty_default_instance_; +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::Empty* Arena::CreateMaybeMessage(Arena*); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN // =================================================================== -class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Empty) */ { +class PROTOBUF_EXPORT Empty : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Empty) */ { public: Empty(); virtual ~Empty(); Empty(const Empty& from); - - inline Empty& operator=(const Empty& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 Empty(Empty&& from) noexcept : Empty() { *this = ::std::move(from); } + inline Empty& operator=(const Empty& from) { + CopyFrom(from); + return *this; + } inline Empty& operator=(Empty&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -87,14 +90,22 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_ } return *this; } - #endif - inline ::google::protobuf::Arena* GetArena() const final { + + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const Empty& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -114,40 +125,48 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_ // implements Message ---------------------------------------------- inline Empty* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - Empty* New(::google::protobuf::Arena* arena) const final { + Empty* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const Empty& from); void MergeFrom(const Empty& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Empty* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Empty"; + } protected: - explicit Empty(::google::protobuf::Arena* arena); + explicit Empty(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -155,7 +174,14 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_ } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fempty_2eproto); + return ::descriptor_table_google_2fprotobuf_2fempty_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -163,13 +189,14 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_ // @@protoc_insertion_point(class_scope:google.protobuf.Empty) private: + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - friend struct ::protobuf_google_2fprotobuf_2fempty_2eproto::TableStruct; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2fempty_2eproto; }; // =================================================================== @@ -188,9 +215,9 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_ // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto diff --git a/third_party/protobuf/src/google/protobuf/extension_set.cc b/third_party/protobuf/src/google/protobuf/extension_set.cc index cb205c4f..67b0fcab 100644 --- a/third_party/protobuf/src/google/protobuf/extension_set.cc +++ b/third_party/protobuf/src/google/protobuf/extension_set.cc @@ -32,16 +32,23 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include +#include + #include +#include #include #include -#include -#include +#include +#include #include -#include +#include +#include +#include #include #include +#include + +#include namespace google { namespace protobuf { @@ -69,38 +76,47 @@ inline bool is_packable(WireFormatLite::WireType type) { case WireFormatLite::WIRETYPE_END_GROUP: return false; - // Do not add a default statement. Let the compiler complain when someone - // adds a new wire type. + // Do not add a default statement. Let the compiler complain when someone + // adds a new wire type. } GOOGLE_LOG(FATAL) << "can't reach here."; return false; } // Registry stuff. -typedef hash_map, - ExtensionInfo> ExtensionRegistry; +struct ExtensionHasher { + std::size_t operator()(const std::pair& p) const { + return std::hash{}(p.first) ^ + std::hash{}(p.second); + } +}; + +typedef std::unordered_map, ExtensionInfo, + ExtensionHasher> + ExtensionRegistry; static const ExtensionRegistry* global_registry = nullptr; // This function is only called at startup, so there is no need for thread- // safety. -void Register(const MessageLite* containing_type, - int number, ExtensionInfo info) { +void Register(const MessageLite* containing_type, int number, + ExtensionInfo info) { static auto local_static_registry = OnShutdownDelete(new ExtensionRegistry); global_registry = local_static_registry; if (!InsertIfNotPresent(local_static_registry, - std::make_pair(containing_type, number), info)) { + std::make_pair(containing_type, number), info)) { GOOGLE_LOG(FATAL) << "Multiple extension registrations for type \"" - << containing_type->GetTypeName() - << "\", field number " << number << "."; + << containing_type->GetTypeName() << "\", field number " + << number << "."; } } -const ExtensionInfo* FindRegisteredExtension( - const MessageLite* containing_type, int number) { +const ExtensionInfo* FindRegisteredExtension(const MessageLite* containing_type, + int number) { return global_registry == nullptr - ? nullptr - : FindOrNull(*global_registry, std::make_pair(containing_type, number)); + ? nullptr + : FindOrNull(*global_registry, + std::make_pair(containing_type, number)); } } // namespace @@ -160,7 +176,7 @@ void ExtensionSet::RegisterMessageExtension(const MessageLite* containing_type, GOOGLE_CHECK(type == WireFormatLite::TYPE_MESSAGE || type == WireFormatLite::TYPE_GROUP); ExtensionInfo info(type, is_repeated, is_packed); - info.message_prototype = prototype; + info.message_info = {prototype}; Register(containing_type, number, info); } @@ -168,34 +184,50 @@ void ExtensionSet::RegisterMessageExtension(const MessageLite* containing_type, // =================================================================== // Constructors and basic methods. -ExtensionSet::ExtensionSet(::google::protobuf::Arena* arena) +ExtensionSet::ExtensionSet(Arena* arena) : arena_(arena), flat_capacity_(0), flat_size_(0), - map_{flat_capacity_ == 0 ? NULL - : ::google::protobuf::Arena::CreateArray( - arena_, flat_capacity_)} {} + map_{flat_capacity_ == 0 + ? NULL + : Arena::CreateArray(arena_, flat_capacity_)} {} ExtensionSet::ExtensionSet() : arena_(NULL), flat_capacity_(0), flat_size_(0), - map_{flat_capacity_ == 0 ? NULL - : ::google::protobuf::Arena::CreateArray( - arena_, flat_capacity_)} {} + map_{flat_capacity_ == 0 + ? NULL + : Arena::CreateArray(arena_, flat_capacity_)} {} ExtensionSet::~ExtensionSet() { // Deletes all allocated extensions. if (arena_ == NULL) { ForEach([](int /* number */, Extension& ext) { ext.Free(); }); - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { delete map_.large; } else { - delete[] map_.flat; + DeleteFlatMap(map_.flat, flat_capacity_); } } } +void ExtensionSet::DeleteFlatMap(const ExtensionSet::KeyValue* flat, + uint16 flat_capacity) { +#ifdef __cpp_sized_deallocation + // Arena::CreateArray already requires a trivially destructible type, but + // ensure this constraint is not violated in the future. + static_assert(std::is_trivially_destructible::value, + "CreateArray requires a trivially destructible type"); + // A const-cast is needed, but this is safe as we are about to deallocate the + // array. + ::operator delete[](const_cast(flat), + sizeof(*flat) * flat_capacity); +#else // !__cpp_sized_deallocation + delete[] flat; +#endif // !__cpp_sized_deallocation +} + // Defined in extension_set_heavy.cc. // void ExtensionSet::AppendToList(const Descriptor* containing_type, // const DescriptorPool* pool, @@ -246,88 +278,88 @@ void ExtensionSet::ClearExtension(int number) { namespace { -enum Cardinality { - REPEATED, - OPTIONAL -}; +enum { REPEATED_FIELD, OPTIONAL_FIELD }; } // namespace -#define GOOGLE_DCHECK_TYPE(EXTENSION, LABEL, CPPTYPE) \ - GOOGLE_DCHECK_EQ((EXTENSION).is_repeated ? REPEATED : OPTIONAL, LABEL); \ +#define GOOGLE_DCHECK_TYPE(EXTENSION, LABEL, CPPTYPE) \ + GOOGLE_DCHECK_EQ((EXTENSION).is_repeated ? REPEATED_FIELD : OPTIONAL_FIELD, LABEL); \ GOOGLE_DCHECK_EQ(cpp_type((EXTENSION).type), WireFormatLite::CPPTYPE_##CPPTYPE) // ------------------------------------------------------------------- // Primitives -#define PRIMITIVE_ACCESSORS(UPPERCASE, LOWERCASE, CAMELCASE) \ - \ -LOWERCASE ExtensionSet::Get##CAMELCASE(int number, \ - LOWERCASE default_value) const { \ - const Extension* extension = FindOrNull(number); \ - if (extension == NULL || extension->is_cleared) { \ - return default_value; \ - } else { \ - GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, UPPERCASE); \ - return extension->LOWERCASE##_value; \ - } \ -} \ - \ -void ExtensionSet::Set##CAMELCASE(int number, FieldType type, \ - LOWERCASE value, \ - const FieldDescriptor* descriptor) { \ - Extension* extension; \ - if (MaybeNewExtension(number, descriptor, &extension)) { \ - extension->type = type; \ - GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_##UPPERCASE); \ - extension->is_repeated = false; \ - } else { \ - GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, UPPERCASE); \ - } \ - extension->is_cleared = false; \ - extension->LOWERCASE##_value = value; \ -} \ - \ -LOWERCASE ExtensionSet::GetRepeated##CAMELCASE(int number, int index) const { \ - const Extension* extension = FindOrNull(number); \ - GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; \ - GOOGLE_DCHECK_TYPE(*extension, REPEATED, UPPERCASE); \ - return extension->repeated_##LOWERCASE##_value->Get(index); \ -} \ - \ -void ExtensionSet::SetRepeated##CAMELCASE( \ - int number, int index, LOWERCASE value) { \ - Extension* extension = FindOrNull(number); \ - GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; \ - GOOGLE_DCHECK_TYPE(*extension, REPEATED, UPPERCASE); \ - extension->repeated_##LOWERCASE##_value->Set(index, value); \ -} \ - \ -void ExtensionSet::Add##CAMELCASE(int number, FieldType type, \ - bool packed, LOWERCASE value, \ - const FieldDescriptor* descriptor) { \ - Extension* extension; \ - if (MaybeNewExtension(number, descriptor, &extension)) { \ - extension->type = type; \ - GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_##UPPERCASE); \ - extension->is_repeated = true; \ - extension->is_packed = packed; \ - extension->repeated_##LOWERCASE##_value = \ - Arena::CreateMessage >(arena_); \ - } else { \ - GOOGLE_DCHECK_TYPE(*extension, REPEATED, UPPERCASE); \ - GOOGLE_DCHECK_EQ(extension->is_packed, packed); \ - } \ - extension->repeated_##LOWERCASE##_value->Add(value); \ -} +#define PRIMITIVE_ACCESSORS(UPPERCASE, LOWERCASE, CAMELCASE) \ + \ + LOWERCASE ExtensionSet::Get##CAMELCASE(int number, LOWERCASE default_value) \ + const { \ + const Extension* extension = FindOrNull(number); \ + if (extension == NULL || extension->is_cleared) { \ + return default_value; \ + } else { \ + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL_FIELD, UPPERCASE); \ + return extension->LOWERCASE##_value; \ + } \ + } \ + \ + void ExtensionSet::Set##CAMELCASE(int number, FieldType type, \ + LOWERCASE value, \ + const FieldDescriptor* descriptor) { \ + Extension* extension; \ + if (MaybeNewExtension(number, descriptor, &extension)) { \ + extension->type = type; \ + GOOGLE_DCHECK_EQ(cpp_type(extension->type), \ + WireFormatLite::CPPTYPE_##UPPERCASE); \ + extension->is_repeated = false; \ + } else { \ + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL_FIELD, UPPERCASE); \ + } \ + extension->is_cleared = false; \ + extension->LOWERCASE##_value = value; \ + } \ + \ + LOWERCASE ExtensionSet::GetRepeated##CAMELCASE(int number, int index) \ + const { \ + const Extension* extension = FindOrNull(number); \ + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; \ + GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, UPPERCASE); \ + return extension->repeated_##LOWERCASE##_value->Get(index); \ + } \ + \ + void ExtensionSet::SetRepeated##CAMELCASE(int number, int index, \ + LOWERCASE value) { \ + Extension* extension = FindOrNull(number); \ + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; \ + GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, UPPERCASE); \ + extension->repeated_##LOWERCASE##_value->Set(index, value); \ + } \ + \ + void ExtensionSet::Add##CAMELCASE(int number, FieldType type, bool packed, \ + LOWERCASE value, \ + const FieldDescriptor* descriptor) { \ + Extension* extension; \ + if (MaybeNewExtension(number, descriptor, &extension)) { \ + extension->type = type; \ + GOOGLE_DCHECK_EQ(cpp_type(extension->type), \ + WireFormatLite::CPPTYPE_##UPPERCASE); \ + extension->is_repeated = true; \ + extension->is_packed = packed; \ + extension->repeated_##LOWERCASE##_value = \ + Arena::CreateMessage>(arena_); \ + } else { \ + GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, UPPERCASE); \ + GOOGLE_DCHECK_EQ(extension->is_packed, packed); \ + } \ + extension->repeated_##LOWERCASE##_value->Add(value); \ + } -PRIMITIVE_ACCESSORS( INT32, int32, Int32) -PRIMITIVE_ACCESSORS( INT64, int64, Int64) +PRIMITIVE_ACCESSORS(INT32, int32, Int32) +PRIMITIVE_ACCESSORS(INT64, int64, Int64) PRIMITIVE_ACCESSORS(UINT32, uint32, UInt32) PRIMITIVE_ACCESSORS(UINT64, uint64, UInt64) -PRIMITIVE_ACCESSORS( FLOAT, float, Float) +PRIMITIVE_ACCESSORS(FLOAT, float, Float) PRIMITIVE_ACCESSORS(DOUBLE, double, Double) -PRIMITIVE_ACCESSORS( BOOL, bool, Bool) +PRIMITIVE_ACCESSORS(BOOL, bool, Bool) #undef PRIMITIVE_ACCESSORS @@ -358,43 +390,43 @@ void* ExtensionSet::MutableRawRepeatedField(int number, FieldType field_type, static_cast(field_type))) { case WireFormatLite::CPPTYPE_INT32: extension->repeated_int32_value = - Arena::CreateMessage >(arena_); + Arena::CreateMessage>(arena_); break; case WireFormatLite::CPPTYPE_INT64: extension->repeated_int64_value = - Arena::CreateMessage >(arena_); + Arena::CreateMessage>(arena_); break; case WireFormatLite::CPPTYPE_UINT32: extension->repeated_uint32_value = - Arena::CreateMessage >(arena_); + Arena::CreateMessage>(arena_); break; case WireFormatLite::CPPTYPE_UINT64: extension->repeated_uint64_value = - Arena::CreateMessage >(arena_); + Arena::CreateMessage>(arena_); break; case WireFormatLite::CPPTYPE_DOUBLE: extension->repeated_double_value = - Arena::CreateMessage >(arena_); + Arena::CreateMessage>(arena_); break; case WireFormatLite::CPPTYPE_FLOAT: extension->repeated_float_value = - Arena::CreateMessage >(arena_); + Arena::CreateMessage>(arena_); break; case WireFormatLite::CPPTYPE_BOOL: extension->repeated_bool_value = - Arena::CreateMessage >(arena_); + Arena::CreateMessage>(arena_); break; case WireFormatLite::CPPTYPE_ENUM: extension->repeated_enum_value = - Arena::CreateMessage >(arena_); + Arena::CreateMessage>(arena_); break; case WireFormatLite::CPPTYPE_STRING: extension->repeated_string_value = - Arena::CreateMessage >(arena_); + Arena::CreateMessage>(arena_); break; case WireFormatLite::CPPTYPE_MESSAGE: extension->repeated_message_value = - Arena::CreateMessage >(arena_); + Arena::CreateMessage>(arena_); break; } } @@ -414,7 +446,6 @@ void* ExtensionSet::MutableRawRepeatedField(int number) { return extension->repeated_int32_value; } - // ------------------------------------------------------------------- // Enums @@ -424,7 +455,7 @@ int ExtensionSet::GetEnum(int number, int default_value) const { // Not present. Return the default value. return default_value; } else { - GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, ENUM); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL_FIELD, ENUM); return extension->enum_value; } } @@ -437,7 +468,7 @@ void ExtensionSet::SetEnum(int number, FieldType type, int value, GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_ENUM); extension->is_repeated = false; } else { - GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, ENUM); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL_FIELD, ENUM); } extension->is_cleared = false; extension->enum_value = value; @@ -446,19 +477,18 @@ void ExtensionSet::SetEnum(int number, FieldType type, int value, int ExtensionSet::GetRepeatedEnum(int number, int index) const { const Extension* extension = FindOrNull(number); GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(*extension, REPEATED, ENUM); + GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, ENUM); return extension->repeated_enum_value->Get(index); } void ExtensionSet::SetRepeatedEnum(int number, int index, int value) { Extension* extension = FindOrNull(number); GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(*extension, REPEATED, ENUM); + GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, ENUM); extension->repeated_enum_value->Set(index, value); } -void ExtensionSet::AddEnum(int number, FieldType type, - bool packed, int value, +void ExtensionSet::AddEnum(int number, FieldType type, bool packed, int value, const FieldDescriptor* descriptor) { Extension* extension; if (MaybeNewExtension(number, descriptor, &extension)) { @@ -467,9 +497,9 @@ void ExtensionSet::AddEnum(int number, FieldType type, extension->is_repeated = true; extension->is_packed = packed; extension->repeated_enum_value = - Arena::CreateMessage >(arena_); + Arena::CreateMessage>(arena_); } else { - GOOGLE_DCHECK_TYPE(*extension, REPEATED, ENUM); + GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, ENUM); GOOGLE_DCHECK_EQ(extension->is_packed, packed); } extension->repeated_enum_value->Add(value); @@ -478,49 +508,50 @@ void ExtensionSet::AddEnum(int number, FieldType type, // ------------------------------------------------------------------- // Strings -const string& ExtensionSet::GetString(int number, - const string& default_value) const { +const std::string& ExtensionSet::GetString( + int number, const std::string& default_value) const { const Extension* extension = FindOrNull(number); if (extension == NULL || extension->is_cleared) { // Not present. Return the default value. return default_value; } else { - GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, STRING); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL_FIELD, STRING); return *extension->string_value; } } -string* ExtensionSet::MutableString(int number, FieldType type, - const FieldDescriptor* descriptor) { +std::string* ExtensionSet::MutableString(int number, FieldType type, + const FieldDescriptor* descriptor) { Extension* extension; if (MaybeNewExtension(number, descriptor, &extension)) { extension->type = type; GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_STRING); extension->is_repeated = false; - extension->string_value = Arena::Create(arena_); + extension->string_value = Arena::Create(arena_); } else { - GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, STRING); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL_FIELD, STRING); } extension->is_cleared = false; return extension->string_value; } -const string& ExtensionSet::GetRepeatedString(int number, int index) const { +const std::string& ExtensionSet::GetRepeatedString(int number, + int index) const { const Extension* extension = FindOrNull(number); GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(*extension, REPEATED, STRING); + GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, STRING); return extension->repeated_string_value->Get(index); } -string* ExtensionSet::MutableRepeatedString(int number, int index) { +std::string* ExtensionSet::MutableRepeatedString(int number, int index) { Extension* extension = FindOrNull(number); GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(*extension, REPEATED, STRING); + GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, STRING); return extension->repeated_string_value->Mutable(index); } -string* ExtensionSet::AddString(int number, FieldType type, - const FieldDescriptor* descriptor) { +std::string* ExtensionSet::AddString(int number, FieldType type, + const FieldDescriptor* descriptor) { Extension* extension; if (MaybeNewExtension(number, descriptor, &extension)) { extension->type = type; @@ -528,9 +559,9 @@ string* ExtensionSet::AddString(int number, FieldType type, extension->is_repeated = true; extension->is_packed = false; extension->repeated_string_value = - Arena::CreateMessage >(arena_); + Arena::CreateMessage>(arena_); } else { - GOOGLE_DCHECK_TYPE(*extension, REPEATED, STRING); + GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, STRING); } return extension->repeated_string_value->Add(); } @@ -545,7 +576,7 @@ const MessageLite& ExtensionSet::GetMessage( // Not present. Return the default value. return default_value; } else { - GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL_FIELD, MESSAGE); if (extension->is_lazy) { return extension->lazymessage_value->GetMessage(default_value); } else { @@ -572,7 +603,7 @@ MessageLite* ExtensionSet::MutableMessage(int number, FieldType type, extension->is_cleared = false; return extension->message_value; } else { - GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL_FIELD, MESSAGE); extension->is_cleared = false; if (extension->is_lazy) { return extension->lazymessage_value->MutableMessage(prototype); @@ -594,7 +625,7 @@ void ExtensionSet::SetAllocatedMessage(int number, FieldType type, ClearExtension(number); return; } - ::google::protobuf::Arena* message_arena = message->GetArena(); + Arena* message_arena = message->GetArena(); Extension* extension; if (MaybeNewExtension(number, descriptor, &extension)) { extension->type = type; @@ -611,7 +642,7 @@ void ExtensionSet::SetAllocatedMessage(int number, FieldType type, extension->message_value->CheckTypeAndMergeFrom(*message); } } else { - GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL_FIELD, MESSAGE); if (extension->is_lazy) { extension->lazymessage_value->SetAllocatedMessage(message); } else { @@ -647,7 +678,7 @@ void ExtensionSet::UnsafeArenaSetAllocatedMessage( extension->is_lazy = false; extension->message_value = message; } else { - GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL_FIELD, MESSAGE); if (extension->is_lazy) { extension->lazymessage_value->UnsafeArenaSetAllocatedMessage(message); } else { @@ -667,7 +698,7 @@ MessageLite* ExtensionSet::ReleaseMessage(int number, // Not present. Return NULL. return NULL; } else { - GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL_FIELD, MESSAGE); MessageLite* ret = NULL; if (extension->is_lazy) { ret = extension->lazymessage_value->ReleaseMessage(prototype); @@ -696,7 +727,7 @@ MessageLite* ExtensionSet::UnsafeArenaReleaseMessage( // Not present. Return NULL. return NULL; } else { - GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL_FIELD, MESSAGE); MessageLite* ret = NULL; if (extension->is_lazy) { ret = extension->lazymessage_value->UnsafeArenaReleaseMessage(prototype); @@ -715,18 +746,18 @@ MessageLite* ExtensionSet::UnsafeArenaReleaseMessage( // MessageLite* ExtensionSet::ReleaseMessage(const FieldDescriptor* descriptor, // MessageFactory* factory); -const MessageLite& ExtensionSet::GetRepeatedMessage( - int number, int index) const { +const MessageLite& ExtensionSet::GetRepeatedMessage(int number, + int index) const { const Extension* extension = FindOrNull(number); GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(*extension, REPEATED, MESSAGE); + GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, MESSAGE); return extension->repeated_message_value->Get(index); } MessageLite* ExtensionSet::MutableRepeatedMessage(int number, int index) { Extension* extension = FindOrNull(number); GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(*extension, REPEATED, MESSAGE); + GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, MESSAGE); return extension->repeated_message_value->Mutable(index); } @@ -739,17 +770,16 @@ MessageLite* ExtensionSet::AddMessage(int number, FieldType type, GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_MESSAGE); extension->is_repeated = true; extension->repeated_message_value = - Arena::CreateMessage >(arena_); + Arena::CreateMessage>(arena_); } else { - GOOGLE_DCHECK_TYPE(*extension, REPEATED, MESSAGE); + GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, MESSAGE); } // RepeatedPtrField does not know how to Add() since it cannot // allocate an abstract object, so we have to be tricky. - MessageLite* result = - reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( - extension->repeated_message_value) - ->AddFromCleared >(); + MessageLite* result = reinterpret_cast( + extension->repeated_message_value) + ->AddFromCleared>(); if (result == NULL) { result = prototype.New(arena_); extension->repeated_message_value->AddAllocated(result); @@ -769,7 +799,7 @@ void ExtensionSet::RemoveLast(int number) { GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; GOOGLE_DCHECK(extension->is_repeated); - switch(cpp_type(extension->type)) { + switch (cpp_type(extension->type)) { case WireFormatLite::CPPTYPE_INT32: extension->repeated_int32_value->RemoveLast(); break; @@ -816,7 +846,7 @@ void ExtensionSet::SwapElements(int number, int index1, int index2) { GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; GOOGLE_DCHECK(extension->is_repeated); - switch(cpp_type(extension->type)) { + switch (cpp_type(extension->type)) { case WireFormatLite::CPPTYPE_INT32: extension->repeated_int32_value->SwapElements(index1, index2); break; @@ -879,8 +909,8 @@ size_t SizeOfUnion(ItX it_xs, ItX end_xs, ItY it_ys, ItY end_ys) { } // namespace void ExtensionSet::MergeFrom(const ExtensionSet& other) { - if (GOOGLE_PREDICT_TRUE(!is_large())) { - if (GOOGLE_PREDICT_TRUE(!other.is_large())) { + if (PROTOBUF_PREDICT_TRUE(!is_large())) { + if (PROTOBUF_PREDICT_TRUE(!other.is_large())) { GrowCapacity(SizeOfUnion(flat_begin(), flat_end(), other.flat_begin(), other.flat_end())); } else { @@ -895,11 +925,11 @@ void ExtensionSet::MergeFrom(const ExtensionSet& other) { } void ExtensionSet::InternalExtensionMergeFrom( - int number, const Extension& other_extension) { + int number, const Extension& other_extension) { if (other_extension.is_repeated) { Extension* extension; - bool is_new = MaybeNewExtension(number, other_extension.descriptor, - &extension); + bool is_new = + MaybeNewExtension(number, other_extension.descriptor, &extension); if (is_new) { // Extension did not already exist in set. extension->type = other_extension.type; @@ -912,31 +942,31 @@ void ExtensionSet::InternalExtensionMergeFrom( } switch (cpp_type(other_extension.type)) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE, REPEATED_TYPE) \ - case WireFormatLite::CPPTYPE_##UPPERCASE: \ - if (is_new) { \ - extension->repeated_##LOWERCASE##_value = \ - Arena::CreateMessage(arena_); \ - } \ - extension->repeated_##LOWERCASE##_value->MergeFrom( \ - *other_extension.repeated_##LOWERCASE##_value); \ - break; +#define HANDLE_TYPE(UPPERCASE, LOWERCASE, REPEATED_TYPE) \ + case WireFormatLite::CPPTYPE_##UPPERCASE: \ + if (is_new) { \ + extension->repeated_##LOWERCASE##_value = \ + Arena::CreateMessage(arena_); \ + } \ + extension->repeated_##LOWERCASE##_value->MergeFrom( \ + *other_extension.repeated_##LOWERCASE##_value); \ + break; - HANDLE_TYPE( INT32, int32, RepeatedField < int32>); - HANDLE_TYPE( INT64, int64, RepeatedField < int64>); - HANDLE_TYPE( UINT32, uint32, RepeatedField < uint32>); - HANDLE_TYPE( UINT64, uint64, RepeatedField < uint64>); - HANDLE_TYPE( FLOAT, float, RepeatedField < float>); - HANDLE_TYPE( DOUBLE, double, RepeatedField < double>); - HANDLE_TYPE( BOOL, bool, RepeatedField < bool>); - HANDLE_TYPE( ENUM, enum, RepeatedField < int>); - HANDLE_TYPE( STRING, string, RepeatedPtrField< string>); + HANDLE_TYPE(INT32, int32, RepeatedField); + HANDLE_TYPE(INT64, int64, RepeatedField); + HANDLE_TYPE(UINT32, uint32, RepeatedField); + HANDLE_TYPE(UINT64, uint64, RepeatedField); + HANDLE_TYPE(FLOAT, float, RepeatedField); + HANDLE_TYPE(DOUBLE, double, RepeatedField); + HANDLE_TYPE(BOOL, bool, RepeatedField); + HANDLE_TYPE(ENUM, enum, RepeatedField); + HANDLE_TYPE(STRING, string, RepeatedPtrField); #undef HANDLE_TYPE case WireFormatLite::CPPTYPE_MESSAGE: if (is_new) { extension->repeated_message_value = - Arena::CreateMessage >(arena_); + Arena::CreateMessage>(arena_); } // We can't call RepeatedPtrField::MergeFrom() because // it would attempt to allocate new objects. @@ -945,9 +975,9 @@ void ExtensionSet::InternalExtensionMergeFrom( for (int i = 0; i < other_repeated_message->size(); i++) { const MessageLite& other_message = other_repeated_message->Get(i); MessageLite* target = - reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( + reinterpret_cast( extension->repeated_message_value) - ->AddFromCleared >(); + ->AddFromCleared>(); if (target == NULL) { target = other_message.New(arena_); extension->repeated_message_value->AddAllocated(target); @@ -959,32 +989,30 @@ void ExtensionSet::InternalExtensionMergeFrom( } else { if (!other_extension.is_cleared) { switch (cpp_type(other_extension.type)) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE, CAMELCASE) \ - case WireFormatLite::CPPTYPE_##UPPERCASE: \ - Set##CAMELCASE(number, other_extension.type, \ - other_extension.LOWERCASE##_value, \ - other_extension.descriptor); \ - break; +#define HANDLE_TYPE(UPPERCASE, LOWERCASE, CAMELCASE) \ + case WireFormatLite::CPPTYPE_##UPPERCASE: \ + Set##CAMELCASE(number, other_extension.type, \ + other_extension.LOWERCASE##_value, \ + other_extension.descriptor); \ + break; - HANDLE_TYPE( INT32, int32, Int32); - HANDLE_TYPE( INT64, int64, Int64); + HANDLE_TYPE(INT32, int32, Int32); + HANDLE_TYPE(INT64, int64, Int64); HANDLE_TYPE(UINT32, uint32, UInt32); HANDLE_TYPE(UINT64, uint64, UInt64); - HANDLE_TYPE( FLOAT, float, Float); + HANDLE_TYPE(FLOAT, float, Float); HANDLE_TYPE(DOUBLE, double, Double); - HANDLE_TYPE( BOOL, bool, Bool); - HANDLE_TYPE( ENUM, enum, Enum); + HANDLE_TYPE(BOOL, bool, Bool); + HANDLE_TYPE(ENUM, enum, Enum); #undef HANDLE_TYPE case WireFormatLite::CPPTYPE_STRING: - SetString(number, other_extension.type, - *other_extension.string_value, + SetString(number, other_extension.type, *other_extension.string_value, other_extension.descriptor); break; case WireFormatLite::CPPTYPE_MESSAGE: { Extension* extension; - bool is_new = MaybeNewExtension(number, - other_extension.descriptor, - &extension); + bool is_new = + MaybeNewExtension(number, other_extension.descriptor, &extension); if (is_new) { extension->type = other_extension.type; extension->is_packed = other_extension.is_packed; @@ -1004,7 +1032,7 @@ void ExtensionSet::InternalExtensionMergeFrom( } } else { GOOGLE_DCHECK_EQ(extension->type, other_extension.type); - GOOGLE_DCHECK_EQ(extension->is_packed,other_extension.is_packed); + GOOGLE_DCHECK_EQ(extension->is_packed, other_extension.is_packed); GOOGLE_DCHECK(!extension->is_repeated); if (other_extension.is_lazy) { if (extension->is_lazy) { @@ -1017,9 +1045,9 @@ void ExtensionSet::InternalExtensionMergeFrom( } } else { if (extension->is_lazy) { - extension->lazymessage_value->MutableMessage( - *other_extension.message_value)->CheckTypeAndMergeFrom( - *other_extension.message_value); + extension->lazymessage_value + ->MutableMessage(*other_extension.message_value) + ->CheckTypeAndMergeFrom(*other_extension.message_value); } else { extension->message_value->CheckTypeAndMergeFrom( *other_extension.message_value); @@ -1053,8 +1081,7 @@ void ExtensionSet::Swap(ExtensionSet* x) { } } -void ExtensionSet::SwapExtension(ExtensionSet* other, - int number) { +void ExtensionSet::SwapExtension(ExtensionSet* other, int number) { if (this == other) return; Extension* this_ext = FindOrNull(number); Extension* other_ext = other->FindOrNull(number); @@ -1108,7 +1135,7 @@ void ExtensionSet::SwapExtension(ExtensionSet* other, bool ExtensionSet::IsInitialized() const { // Extensions are never required. However, we need to check that all // embedded messages are initialized. - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { for (const auto& kv : *map_.large) { if (!kv.second.IsInitialized()) return false; } @@ -1120,9 +1147,11 @@ bool ExtensionSet::IsInitialized() const { return true; } -bool ExtensionSet::FindExtensionInfoFromTag( - uint32 tag, ExtensionFinder* extension_finder, int* field_number, - ExtensionInfo* extension, bool* was_packed_on_wire) { +bool ExtensionSet::FindExtensionInfoFromTag(uint32 tag, + ExtensionFinder* extension_finder, + int* field_number, + ExtensionInfo* extension, + bool* was_packed_on_wire) { *field_number = WireFormatLite::GetTagFieldNumber(tag); WireFormatLite::WireType wire_type = WireFormatLite::GetTagWireType(tag); return FindExtensionInfoFromFieldNumber(wire_type, *field_number, @@ -1158,19 +1187,46 @@ bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input, int number; bool was_packed_on_wire; ExtensionInfo extension; - if (!FindExtensionInfoFromTag( - tag, extension_finder, &number, &extension, &was_packed_on_wire)) { + if (!FindExtensionInfoFromTag(tag, extension_finder, &number, &extension, + &was_packed_on_wire)) { return field_skipper->SkipField(input, tag); } else { - return ParseFieldWithExtensionInfo( - number, was_packed_on_wire, extension, input, field_skipper); + return ParseFieldWithExtensionInfo(number, was_packed_on_wire, extension, + input, field_skipper); } } -bool ExtensionSet::ParseFieldWithExtensionInfo( - int number, bool was_packed_on_wire, const ExtensionInfo& extension, - io::CodedInputStream* input, - FieldSkipper* field_skipper) { +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* ExtensionSet::ParseField( + uint64 tag, const char* ptr, const MessageLite* containing_type, + internal::InternalMetadataWithArenaLite* metadata, + internal::ParseContext* ctx) { + GeneratedExtensionFinder finder(containing_type); + int number = tag >> 3; + bool was_packed_on_wire; + ExtensionInfo extension; + if (!FindExtensionInfoFromFieldNumber(tag & 7, number, &finder, &extension, + &was_packed_on_wire)) { + return UnknownFieldParse(tag, metadata->mutable_unknown_fields(), ptr, ctx); + } + return ParseFieldWithExtensionInfo(number, was_packed_on_wire, extension, + metadata, ptr, ctx); +} + +const char* ExtensionSet::ParseMessageSetItem( + const char* ptr, const MessageLite* containing_type, + internal::InternalMetadataWithArenaLite* metadata, + internal::ParseContext* ctx) { + return ParseMessageSetItemTmpl(ptr, containing_type, metadata, ctx); +} + +#endif + +bool ExtensionSet::ParseFieldWithExtensionInfo(int number, + bool was_packed_on_wire, + const ExtensionInfo& extension, + io::CodedInputStream* input, + FieldSkipper* field_skipper) { // Explicitly not read extension.is_packed, instead check whether the field // was encoded in packed form on the wire. if (was_packed_on_wire) { @@ -1179,39 +1235,40 @@ bool ExtensionSet::ParseFieldWithExtensionInfo( io::CodedInputStream::Limit limit = input->PushLimit(size); switch (extension.type) { -#define HANDLE_TYPE(UPPERCASE, CPP_CAMELCASE, CPP_LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - while (input->BytesUntilLimit() > 0) { \ - CPP_LOWERCASE value; \ - if (!WireFormatLite::ReadPrimitive< \ - CPP_LOWERCASE, WireFormatLite::TYPE_##UPPERCASE>( \ - input, &value)) return false; \ - Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \ - extension.is_packed, value, \ - extension.descriptor); \ - } \ - break +#define HANDLE_TYPE(UPPERCASE, CPP_CAMELCASE, CPP_LOWERCASE) \ + case WireFormatLite::TYPE_##UPPERCASE: \ + while (input->BytesUntilLimit() > 0) { \ + CPP_LOWERCASE value; \ + if (!WireFormatLite::ReadPrimitive( \ + input, &value)) \ + return false; \ + Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \ + extension.is_packed, value, extension.descriptor); \ + } \ + break - HANDLE_TYPE( INT32, Int32, int32); - HANDLE_TYPE( INT64, Int64, int64); - HANDLE_TYPE( UINT32, UInt32, uint32); - HANDLE_TYPE( UINT64, UInt64, uint64); - HANDLE_TYPE( SINT32, Int32, int32); - HANDLE_TYPE( SINT64, Int64, int64); - HANDLE_TYPE( FIXED32, UInt32, uint32); - HANDLE_TYPE( FIXED64, UInt64, uint64); - HANDLE_TYPE(SFIXED32, Int32, int32); - HANDLE_TYPE(SFIXED64, Int64, int64); - HANDLE_TYPE( FLOAT, Float, float); - HANDLE_TYPE( DOUBLE, Double, double); - HANDLE_TYPE( BOOL, Bool, bool); + HANDLE_TYPE(INT32, Int32, int32); + HANDLE_TYPE(INT64, Int64, int64); + HANDLE_TYPE(UINT32, UInt32, uint32); + HANDLE_TYPE(UINT64, UInt64, uint64); + HANDLE_TYPE(SINT32, Int32, int32); + HANDLE_TYPE(SINT64, Int64, int64); + HANDLE_TYPE(FIXED32, UInt32, uint32); + HANDLE_TYPE(FIXED64, UInt64, uint64); + HANDLE_TYPE(SFIXED32, Int32, int32); + HANDLE_TYPE(SFIXED64, Int64, int64); + HANDLE_TYPE(FLOAT, Float, float); + HANDLE_TYPE(DOUBLE, Double, double); + HANDLE_TYPE(BOOL, Bool, bool); #undef HANDLE_TYPE case WireFormatLite::TYPE_ENUM: while (input->BytesUntilLimit() > 0) { int value; if (!WireFormatLite::ReadPrimitive( - input, &value)) return false; + input, &value)) + return false; if (extension.enum_validity_check.func( extension.enum_validity_check.arg, value)) { AddEnum(number, WireFormatLite::TYPE_ENUM, extension.is_packed, @@ -1234,41 +1291,42 @@ bool ExtensionSet::ParseFieldWithExtensionInfo( input->PopLimit(limit); } else { switch (extension.type) { -#define HANDLE_TYPE(UPPERCASE, CPP_CAMELCASE, CPP_LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: { \ - CPP_LOWERCASE value; \ - if (!WireFormatLite::ReadPrimitive< \ - CPP_LOWERCASE, WireFormatLite::TYPE_##UPPERCASE>( \ - input, &value)) return false; \ - if (extension.is_repeated) { \ - Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \ - extension.is_packed, value, \ - extension.descriptor); \ - } else { \ - Set##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, value, \ - extension.descriptor); \ - } \ - } break +#define HANDLE_TYPE(UPPERCASE, CPP_CAMELCASE, CPP_LOWERCASE) \ + case WireFormatLite::TYPE_##UPPERCASE: { \ + CPP_LOWERCASE value; \ + if (!WireFormatLite::ReadPrimitive( \ + input, &value)) \ + return false; \ + if (extension.is_repeated) { \ + Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \ + extension.is_packed, value, extension.descriptor); \ + } else { \ + Set##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, value, \ + extension.descriptor); \ + } \ + } break - HANDLE_TYPE( INT32, Int32, int32); - HANDLE_TYPE( INT64, Int64, int64); - HANDLE_TYPE( UINT32, UInt32, uint32); - HANDLE_TYPE( UINT64, UInt64, uint64); - HANDLE_TYPE( SINT32, Int32, int32); - HANDLE_TYPE( SINT64, Int64, int64); - HANDLE_TYPE( FIXED32, UInt32, uint32); - HANDLE_TYPE( FIXED64, UInt64, uint64); - HANDLE_TYPE(SFIXED32, Int32, int32); - HANDLE_TYPE(SFIXED64, Int64, int64); - HANDLE_TYPE( FLOAT, Float, float); - HANDLE_TYPE( DOUBLE, Double, double); - HANDLE_TYPE( BOOL, Bool, bool); + HANDLE_TYPE(INT32, Int32, int32); + HANDLE_TYPE(INT64, Int64, int64); + HANDLE_TYPE(UINT32, UInt32, uint32); + HANDLE_TYPE(UINT64, UInt64, uint64); + HANDLE_TYPE(SINT32, Int32, int32); + HANDLE_TYPE(SINT64, Int64, int64); + HANDLE_TYPE(FIXED32, UInt32, uint32); + HANDLE_TYPE(FIXED64, UInt64, uint64); + HANDLE_TYPE(SFIXED32, Int32, int32); + HANDLE_TYPE(SFIXED64, Int64, int64); + HANDLE_TYPE(FLOAT, Float, float); + HANDLE_TYPE(DOUBLE, Double, double); + HANDLE_TYPE(BOOL, Bool, bool); #undef HANDLE_TYPE case WireFormatLite::TYPE_ENUM: { int value; if (!WireFormatLite::ReadPrimitive( - input, &value)) return false; + input, &value)) + return false; if (!extension.enum_validity_check.func( extension.enum_validity_check.arg, value)) { @@ -1284,40 +1342,50 @@ bool ExtensionSet::ParseFieldWithExtensionInfo( break; } - case WireFormatLite::TYPE_STRING: { - string* value = extension.is_repeated ? - AddString(number, WireFormatLite::TYPE_STRING, extension.descriptor) : - MutableString(number, WireFormatLite::TYPE_STRING, - extension.descriptor); + case WireFormatLite::TYPE_STRING: { + std::string* value = + extension.is_repeated + ? AddString(number, WireFormatLite::TYPE_STRING, + extension.descriptor) + : MutableString(number, WireFormatLite::TYPE_STRING, + extension.descriptor); if (!WireFormatLite::ReadString(input, value)) return false; break; } - case WireFormatLite::TYPE_BYTES: { - string* value = extension.is_repeated ? - AddString(number, WireFormatLite::TYPE_BYTES, extension.descriptor) : - MutableString(number, WireFormatLite::TYPE_BYTES, - extension.descriptor); + case WireFormatLite::TYPE_BYTES: { + std::string* value = + extension.is_repeated + ? AddString(number, WireFormatLite::TYPE_BYTES, + extension.descriptor) + : MutableString(number, WireFormatLite::TYPE_BYTES, + extension.descriptor); if (!WireFormatLite::ReadBytes(input, value)) return false; break; } case WireFormatLite::TYPE_GROUP: { - MessageLite* value = extension.is_repeated ? - AddMessage(number, WireFormatLite::TYPE_GROUP, - *extension.message_prototype, extension.descriptor) : - MutableMessage(number, WireFormatLite::TYPE_GROUP, - *extension.message_prototype, extension.descriptor); + MessageLite* value = + extension.is_repeated + ? AddMessage(number, WireFormatLite::TYPE_GROUP, + *extension.message_info.prototype, + extension.descriptor) + : MutableMessage(number, WireFormatLite::TYPE_GROUP, + *extension.message_info.prototype, + extension.descriptor); if (!WireFormatLite::ReadGroup(number, input, value)) return false; break; } case WireFormatLite::TYPE_MESSAGE: { - MessageLite* value = extension.is_repeated ? - AddMessage(number, WireFormatLite::TYPE_MESSAGE, - *extension.message_prototype, extension.descriptor) : - MutableMessage(number, WireFormatLite::TYPE_MESSAGE, - *extension.message_prototype, extension.descriptor); + MessageLite* value = + extension.is_repeated + ? AddMessage(number, WireFormatLite::TYPE_MESSAGE, + *extension.message_info.prototype, + extension.descriptor) + : MutableMessage(number, WireFormatLite::TYPE_MESSAGE, + *extension.message_info.prototype, + extension.descriptor); if (!WireFormatLite::ReadMessage(input, value)) return false; break; } @@ -1342,20 +1410,65 @@ bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input, return ParseField(tag, input, &finder, &skipper); } -// Defined in extension_set_heavy.cc. -// bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input, -// const MessageLite* containing_type, -// UnknownFieldSet* unknown_fields) +bool ExtensionSet::ParseMessageSetLite(io::CodedInputStream* input, + ExtensionFinder* extension_finder, + FieldSkipper* field_skipper) { + while (true) { + const uint32 tag = input->ReadTag(); + switch (tag) { + case 0: + return true; + case WireFormatLite::kMessageSetItemStartTag: + if (!ParseMessageSetItemLite(input, extension_finder, field_skipper)) { + return false; + } + break; + default: + if (!ParseField(tag, input, extension_finder, field_skipper)) { + return false; + } + break; + } + } +} -// Defined in extension_set_heavy.cc. -// bool ExtensionSet::ParseMessageSet(io::CodedInputStream* input, -// const MessageLite* containing_type, -// UnknownFieldSet* unknown_fields); +bool ExtensionSet::ParseMessageSetItemLite(io::CodedInputStream* input, + ExtensionFinder* extension_finder, + FieldSkipper* field_skipper) { + struct MSLite { + bool ParseField(int type_id, io::CodedInputStream* input) { + return me->ParseField( + WireFormatLite::WIRETYPE_LENGTH_DELIMITED + 8 * type_id, input, + extension_finder, field_skipper); + } + + bool SkipField(uint32 tag, io::CodedInputStream* input) { + return field_skipper->SkipField(input, tag); + } + + ExtensionSet* me; + ExtensionFinder* extension_finder; + FieldSkipper* field_skipper; + }; + + return ParseMessageSetItemImpl(input, + MSLite{this, extension_finder, field_skipper}); +} + +bool ExtensionSet::ParseMessageSet(io::CodedInputStream* input, + const MessageLite* containing_type, + std::string* unknown_fields) { + io::StringOutputStream zcis(unknown_fields); + io::CodedOutputStream output(&zcis); + CodedOutputStreamFieldSkipper skipper(&output); + GeneratedExtensionFinder finder(containing_type); + return ParseMessageSetLite(input, &finder, &skipper); +} void ExtensionSet::SerializeWithCachedSizes( int start_field_number, int end_field_number, io::CodedOutputStream* output) const { - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { const auto& end = map_.large->end(); for (auto it = map_.large->lower_bound(start_field_number); it != end && it->first < end_field_number; ++it) { @@ -1397,20 +1510,20 @@ bool ExtensionSet::MaybeNewExtension(int number, void ExtensionSet::Extension::Clear() { if (is_repeated) { switch (cpp_type(type)) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case WireFormatLite::CPPTYPE_##UPPERCASE: \ - repeated_##LOWERCASE##_value->Clear(); \ - break +#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ + case WireFormatLite::CPPTYPE_##UPPERCASE: \ + repeated_##LOWERCASE##_value->Clear(); \ + break - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); - HANDLE_TYPE( UINT32, uint32); - HANDLE_TYPE( UINT64, uint64); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( DOUBLE, double); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, enum); - HANDLE_TYPE( STRING, string); + HANDLE_TYPE(INT32, int32); + HANDLE_TYPE(INT64, int64); + HANDLE_TYPE(UINT32, uint32); + HANDLE_TYPE(UINT64, uint64); + HANDLE_TYPE(FLOAT, float); + HANDLE_TYPE(DOUBLE, double); + HANDLE_TYPE(BOOL, bool); + HANDLE_TYPE(ENUM, enum); + HANDLE_TYPE(STRING, string); HANDLE_TYPE(MESSAGE, message); #undef HANDLE_TYPE } @@ -1440,39 +1553,38 @@ void ExtensionSet::Extension::Clear() { } void ExtensionSet::Extension::SerializeFieldWithCachedSizes( - int number, - io::CodedOutputStream* output) const { + int number, io::CodedOutputStream* output) const { if (is_repeated) { if (is_packed) { if (cached_size == 0) return; - WireFormatLite::WriteTag(number, - WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); + WireFormatLite::WriteTag( + number, WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(cached_size); switch (real_type(type)) { -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ - WireFormatLite::Write##CAMELCASE##NoTag( \ - repeated_##LOWERCASE##_value->Get(i), output); \ - } \ - break +#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ + case WireFormatLite::TYPE_##UPPERCASE: \ + for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ + WireFormatLite::Write##CAMELCASE##NoTag( \ + repeated_##LOWERCASE##_value->Get(i), output); \ + } \ + break - HANDLE_TYPE( INT32, Int32, int32); - HANDLE_TYPE( INT64, Int64, int64); - HANDLE_TYPE( UINT32, UInt32, uint32); - HANDLE_TYPE( UINT64, UInt64, uint64); - HANDLE_TYPE( SINT32, SInt32, int32); - HANDLE_TYPE( SINT64, SInt64, int64); - HANDLE_TYPE( FIXED32, Fixed32, uint32); - HANDLE_TYPE( FIXED64, Fixed64, uint64); - HANDLE_TYPE(SFIXED32, SFixed32, int32); - HANDLE_TYPE(SFIXED64, SFixed64, int64); - HANDLE_TYPE( FLOAT, Float, float); - HANDLE_TYPE( DOUBLE, Double, double); - HANDLE_TYPE( BOOL, Bool, bool); - HANDLE_TYPE( ENUM, Enum, enum); + HANDLE_TYPE(INT32, Int32, int32); + HANDLE_TYPE(INT64, Int64, int64); + HANDLE_TYPE(UINT32, UInt32, uint32); + HANDLE_TYPE(UINT64, UInt64, uint64); + HANDLE_TYPE(SINT32, SInt32, int32); + HANDLE_TYPE(SINT64, SInt64, int64); + HANDLE_TYPE(FIXED32, Fixed32, uint32); + HANDLE_TYPE(FIXED64, Fixed64, uint64); + HANDLE_TYPE(SFIXED32, SFixed32, int32); + HANDLE_TYPE(SFIXED64, SFixed64, int64); + HANDLE_TYPE(FLOAT, Float, float); + HANDLE_TYPE(DOUBLE, Double, double); + HANDLE_TYPE(BOOL, Bool, bool); + HANDLE_TYPE(ENUM, Enum, enum); #undef HANDLE_TYPE case WireFormatLite::TYPE_STRING: @@ -1484,59 +1596,59 @@ void ExtensionSet::Extension::SerializeFieldWithCachedSizes( } } else { switch (real_type(type)) { -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ - WireFormatLite::Write##CAMELCASE(number, \ - repeated_##LOWERCASE##_value->Get(i), output); \ - } \ - break +#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ + case WireFormatLite::TYPE_##UPPERCASE: \ + for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ + WireFormatLite::Write##CAMELCASE( \ + number, repeated_##LOWERCASE##_value->Get(i), output); \ + } \ + break - HANDLE_TYPE( INT32, Int32, int32); - HANDLE_TYPE( INT64, Int64, int64); - HANDLE_TYPE( UINT32, UInt32, uint32); - HANDLE_TYPE( UINT64, UInt64, uint64); - HANDLE_TYPE( SINT32, SInt32, int32); - HANDLE_TYPE( SINT64, SInt64, int64); - HANDLE_TYPE( FIXED32, Fixed32, uint32); - HANDLE_TYPE( FIXED64, Fixed64, uint64); - HANDLE_TYPE(SFIXED32, SFixed32, int32); - HANDLE_TYPE(SFIXED64, SFixed64, int64); - HANDLE_TYPE( FLOAT, Float, float); - HANDLE_TYPE( DOUBLE, Double, double); - HANDLE_TYPE( BOOL, Bool, bool); - HANDLE_TYPE( STRING, String, string); - HANDLE_TYPE( BYTES, Bytes, string); - HANDLE_TYPE( ENUM, Enum, enum); - HANDLE_TYPE( GROUP, Group, message); - HANDLE_TYPE( MESSAGE, Message, message); + HANDLE_TYPE(INT32, Int32, int32); + HANDLE_TYPE(INT64, Int64, int64); + HANDLE_TYPE(UINT32, UInt32, uint32); + HANDLE_TYPE(UINT64, UInt64, uint64); + HANDLE_TYPE(SINT32, SInt32, int32); + HANDLE_TYPE(SINT64, SInt64, int64); + HANDLE_TYPE(FIXED32, Fixed32, uint32); + HANDLE_TYPE(FIXED64, Fixed64, uint64); + HANDLE_TYPE(SFIXED32, SFixed32, int32); + HANDLE_TYPE(SFIXED64, SFixed64, int64); + HANDLE_TYPE(FLOAT, Float, float); + HANDLE_TYPE(DOUBLE, Double, double); + HANDLE_TYPE(BOOL, Bool, bool); + HANDLE_TYPE(STRING, String, string); + HANDLE_TYPE(BYTES, Bytes, string); + HANDLE_TYPE(ENUM, Enum, enum); + HANDLE_TYPE(GROUP, Group, message); + HANDLE_TYPE(MESSAGE, Message, message); #undef HANDLE_TYPE } } } else if (!is_cleared) { switch (real_type(type)) { -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, VALUE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - WireFormatLite::Write##CAMELCASE(number, VALUE, output); \ - break +#define HANDLE_TYPE(UPPERCASE, CAMELCASE, VALUE) \ + case WireFormatLite::TYPE_##UPPERCASE: \ + WireFormatLite::Write##CAMELCASE(number, VALUE, output); \ + break - HANDLE_TYPE( INT32, Int32, int32_value); - HANDLE_TYPE( INT64, Int64, int64_value); - HANDLE_TYPE( UINT32, UInt32, uint32_value); - HANDLE_TYPE( UINT64, UInt64, uint64_value); - HANDLE_TYPE( SINT32, SInt32, int32_value); - HANDLE_TYPE( SINT64, SInt64, int64_value); - HANDLE_TYPE( FIXED32, Fixed32, uint32_value); - HANDLE_TYPE( FIXED64, Fixed64, uint64_value); - HANDLE_TYPE(SFIXED32, SFixed32, int32_value); - HANDLE_TYPE(SFIXED64, SFixed64, int64_value); - HANDLE_TYPE( FLOAT, Float, float_value); - HANDLE_TYPE( DOUBLE, Double, double_value); - HANDLE_TYPE( BOOL, Bool, bool_value); - HANDLE_TYPE( STRING, String, *string_value); - HANDLE_TYPE( BYTES, Bytes, *string_value); - HANDLE_TYPE( ENUM, Enum, enum_value); - HANDLE_TYPE( GROUP, Group, *message_value); + HANDLE_TYPE(INT32, Int32, int32_value); + HANDLE_TYPE(INT64, Int64, int64_value); + HANDLE_TYPE(UINT32, UInt32, uint32_value); + HANDLE_TYPE(UINT64, UInt64, uint64_value); + HANDLE_TYPE(SINT32, SInt32, int32_value); + HANDLE_TYPE(SINT64, SInt64, int64_value); + HANDLE_TYPE(FIXED32, Fixed32, uint32_value); + HANDLE_TYPE(FIXED64, Fixed64, uint64_value); + HANDLE_TYPE(SFIXED32, SFixed32, int32_value); + HANDLE_TYPE(SFIXED64, SFixed64, int64_value); + HANDLE_TYPE(FLOAT, Float, float_value); + HANDLE_TYPE(DOUBLE, Double, double_value); + HANDLE_TYPE(BOOL, Bool, bool_value); + HANDLE_TYPE(STRING, String, *string_value); + HANDLE_TYPE(BYTES, Bytes, *string_value); + HANDLE_TYPE(ENUM, Enum, enum_value); + HANDLE_TYPE(GROUP, Group, *message_value); #undef HANDLE_TYPE case WireFormatLite::TYPE_MESSAGE: if (is_lazy) { @@ -1555,36 +1667,36 @@ size_t ExtensionSet::Extension::ByteSize(int number) const { if (is_repeated) { if (is_packed) { switch (real_type(type)) { -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ - result += WireFormatLite::CAMELCASE##Size( \ - repeated_##LOWERCASE##_value->Get(i)); \ - } \ - break +#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ + case WireFormatLite::TYPE_##UPPERCASE: \ + for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ + result += WireFormatLite::CAMELCASE##Size( \ + repeated_##LOWERCASE##_value->Get(i)); \ + } \ + break - HANDLE_TYPE( INT32, Int32, int32); - HANDLE_TYPE( INT64, Int64, int64); - HANDLE_TYPE( UINT32, UInt32, uint32); - HANDLE_TYPE( UINT64, UInt64, uint64); - HANDLE_TYPE( SINT32, SInt32, int32); - HANDLE_TYPE( SINT64, SInt64, int64); - HANDLE_TYPE( ENUM, Enum, enum); + HANDLE_TYPE(INT32, Int32, int32); + HANDLE_TYPE(INT64, Int64, int64); + HANDLE_TYPE(UINT32, UInt32, uint32); + HANDLE_TYPE(UINT64, UInt64, uint64); + HANDLE_TYPE(SINT32, SInt32, int32); + HANDLE_TYPE(SINT64, SInt64, int64); + HANDLE_TYPE(ENUM, Enum, enum); #undef HANDLE_TYPE // Stuff with fixed size. -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - result += WireFormatLite::k##CAMELCASE##Size * \ - FromIntSize(repeated_##LOWERCASE##_value->size()); \ - break - HANDLE_TYPE( FIXED32, Fixed32, uint32); - HANDLE_TYPE( FIXED64, Fixed64, uint64); - HANDLE_TYPE(SFIXED32, SFixed32, int32); - HANDLE_TYPE(SFIXED64, SFixed64, int64); - HANDLE_TYPE( FLOAT, Float, float); - HANDLE_TYPE( DOUBLE, Double, double); - HANDLE_TYPE( BOOL, Bool, bool); +#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ + case WireFormatLite::TYPE_##UPPERCASE: \ + result += WireFormatLite::k##CAMELCASE##Size * \ + FromIntSize(repeated_##LOWERCASE##_value->size()); \ + break + HANDLE_TYPE(FIXED32, Fixed32, uint32); + HANDLE_TYPE(FIXED64, Fixed64, uint64); + HANDLE_TYPE(SFIXED32, SFixed32, int32); + HANDLE_TYPE(SFIXED64, SFixed64, int64); + HANDLE_TYPE(FLOAT, Float, float); + HANDLE_TYPE(DOUBLE, Double, double); + HANDLE_TYPE(BOOL, Bool, bool); #undef HANDLE_TYPE case WireFormatLite::TYPE_STRING: @@ -1598,71 +1710,69 @@ size_t ExtensionSet::Extension::ByteSize(int number) const { cached_size = ToCachedSize(result); if (result > 0) { result += io::CodedOutputStream::VarintSize32(result); - result += io::CodedOutputStream::VarintSize32( - WireFormatLite::MakeTag(number, - WireFormatLite::WIRETYPE_LENGTH_DELIMITED)); + result += io::CodedOutputStream::VarintSize32(WireFormatLite::MakeTag( + number, WireFormatLite::WIRETYPE_LENGTH_DELIMITED)); } } else { size_t tag_size = WireFormatLite::TagSize(number, real_type(type)); switch (real_type(type)) { #define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - result += tag_size * \ - FromIntSize(repeated_##LOWERCASE##_value->size()); \ - for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ - result += WireFormatLite::CAMELCASE##Size( \ - repeated_##LOWERCASE##_value->Get(i)); \ - } \ - break + case WireFormatLite::TYPE_##UPPERCASE: \ + result += tag_size * FromIntSize(repeated_##LOWERCASE##_value->size()); \ + for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ + result += WireFormatLite::CAMELCASE##Size( \ + repeated_##LOWERCASE##_value->Get(i)); \ + } \ + break - HANDLE_TYPE( INT32, Int32, int32); - HANDLE_TYPE( INT64, Int64, int64); - HANDLE_TYPE( UINT32, UInt32, uint32); - HANDLE_TYPE( UINT64, UInt64, uint64); - HANDLE_TYPE( SINT32, SInt32, int32); - HANDLE_TYPE( SINT64, SInt64, int64); - HANDLE_TYPE( STRING, String, string); - HANDLE_TYPE( BYTES, Bytes, string); - HANDLE_TYPE( ENUM, Enum, enum); - HANDLE_TYPE( GROUP, Group, message); - HANDLE_TYPE( MESSAGE, Message, message); + HANDLE_TYPE(INT32, Int32, int32); + HANDLE_TYPE(INT64, Int64, int64); + HANDLE_TYPE(UINT32, UInt32, uint32); + HANDLE_TYPE(UINT64, UInt64, uint64); + HANDLE_TYPE(SINT32, SInt32, int32); + HANDLE_TYPE(SINT64, SInt64, int64); + HANDLE_TYPE(STRING, String, string); + HANDLE_TYPE(BYTES, Bytes, string); + HANDLE_TYPE(ENUM, Enum, enum); + HANDLE_TYPE(GROUP, Group, message); + HANDLE_TYPE(MESSAGE, Message, message); #undef HANDLE_TYPE // Stuff with fixed size. -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - result += (tag_size + WireFormatLite::k##CAMELCASE##Size) * \ - FromIntSize(repeated_##LOWERCASE##_value->size()); \ - break - HANDLE_TYPE( FIXED32, Fixed32, uint32); - HANDLE_TYPE( FIXED64, Fixed64, uint64); - HANDLE_TYPE(SFIXED32, SFixed32, int32); - HANDLE_TYPE(SFIXED64, SFixed64, int64); - HANDLE_TYPE( FLOAT, Float, float); - HANDLE_TYPE( DOUBLE, Double, double); - HANDLE_TYPE( BOOL, Bool, bool); +#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ + case WireFormatLite::TYPE_##UPPERCASE: \ + result += (tag_size + WireFormatLite::k##CAMELCASE##Size) * \ + FromIntSize(repeated_##LOWERCASE##_value->size()); \ + break + HANDLE_TYPE(FIXED32, Fixed32, uint32); + HANDLE_TYPE(FIXED64, Fixed64, uint64); + HANDLE_TYPE(SFIXED32, SFixed32, int32); + HANDLE_TYPE(SFIXED64, SFixed64, int64); + HANDLE_TYPE(FLOAT, Float, float); + HANDLE_TYPE(DOUBLE, Double, double); + HANDLE_TYPE(BOOL, Bool, bool); #undef HANDLE_TYPE } } } else if (!is_cleared) { result += WireFormatLite::TagSize(number, real_type(type)); switch (real_type(type)) { -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - result += WireFormatLite::CAMELCASE##Size(LOWERCASE); \ - break +#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ + case WireFormatLite::TYPE_##UPPERCASE: \ + result += WireFormatLite::CAMELCASE##Size(LOWERCASE); \ + break - HANDLE_TYPE( INT32, Int32, int32_value); - HANDLE_TYPE( INT64, Int64, int64_value); - HANDLE_TYPE( UINT32, UInt32, uint32_value); - HANDLE_TYPE( UINT64, UInt64, uint64_value); - HANDLE_TYPE( SINT32, SInt32, int32_value); - HANDLE_TYPE( SINT64, SInt64, int64_value); - HANDLE_TYPE( STRING, String, *string_value); - HANDLE_TYPE( BYTES, Bytes, *string_value); - HANDLE_TYPE( ENUM, Enum, enum_value); - HANDLE_TYPE( GROUP, Group, *message_value); + HANDLE_TYPE(INT32, Int32, int32_value); + HANDLE_TYPE(INT64, Int64, int64_value); + HANDLE_TYPE(UINT32, UInt32, uint32_value); + HANDLE_TYPE(UINT64, UInt64, uint64_value); + HANDLE_TYPE(SINT32, SInt32, int32_value); + HANDLE_TYPE(SINT64, SInt64, int64_value); + HANDLE_TYPE(STRING, String, *string_value); + HANDLE_TYPE(BYTES, Bytes, *string_value); + HANDLE_TYPE(ENUM, Enum, enum_value); + HANDLE_TYPE(GROUP, Group, *message_value); #undef HANDLE_TYPE case WireFormatLite::TYPE_MESSAGE: { if (is_lazy) { @@ -1675,17 +1785,17 @@ size_t ExtensionSet::Extension::ByteSize(int number) const { } // Stuff with fixed size. -#define HANDLE_TYPE(UPPERCASE, CAMELCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - result += WireFormatLite::k##CAMELCASE##Size; \ - break - HANDLE_TYPE( FIXED32, Fixed32); - HANDLE_TYPE( FIXED64, Fixed64); - HANDLE_TYPE(SFIXED32, SFixed32); - HANDLE_TYPE(SFIXED64, SFixed64); - HANDLE_TYPE( FLOAT, Float); - HANDLE_TYPE( DOUBLE, Double); - HANDLE_TYPE( BOOL, Bool); +#define HANDLE_TYPE(UPPERCASE, CAMELCASE) \ + case WireFormatLite::TYPE_##UPPERCASE: \ + result += WireFormatLite::k##CAMELCASE##Size; \ + break + HANDLE_TYPE(FIXED32, Fixed32); + HANDLE_TYPE(FIXED64, Fixed64); + HANDLE_TYPE(SFIXED32, SFixed32); + HANDLE_TYPE(SFIXED64, SFixed64); + HANDLE_TYPE(FLOAT, Float); + HANDLE_TYPE(DOUBLE, Double); + HANDLE_TYPE(BOOL, Bool); #undef HANDLE_TYPE } } @@ -1696,19 +1806,19 @@ size_t ExtensionSet::Extension::ByteSize(int number) const { int ExtensionSet::Extension::GetSize() const { GOOGLE_DCHECK(is_repeated); switch (cpp_type(type)) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case WireFormatLite::CPPTYPE_##UPPERCASE: \ - return repeated_##LOWERCASE##_value->size() +#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ + case WireFormatLite::CPPTYPE_##UPPERCASE: \ + return repeated_##LOWERCASE##_value->size() - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); - HANDLE_TYPE( UINT32, uint32); - HANDLE_TYPE( UINT64, uint64); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( DOUBLE, double); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, enum); - HANDLE_TYPE( STRING, string); + HANDLE_TYPE(INT32, int32); + HANDLE_TYPE(INT64, int64); + HANDLE_TYPE(UINT32, uint32); + HANDLE_TYPE(UINT64, uint64); + HANDLE_TYPE(FLOAT, float); + HANDLE_TYPE(DOUBLE, double); + HANDLE_TYPE(BOOL, bool); + HANDLE_TYPE(ENUM, enum); + HANDLE_TYPE(STRING, string); HANDLE_TYPE(MESSAGE, message); #undef HANDLE_TYPE } @@ -1722,20 +1832,20 @@ int ExtensionSet::Extension::GetSize() const { void ExtensionSet::Extension::Free() { if (is_repeated) { switch (cpp_type(type)) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case WireFormatLite::CPPTYPE_##UPPERCASE: \ - delete repeated_##LOWERCASE##_value; \ - break +#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ + case WireFormatLite::CPPTYPE_##UPPERCASE: \ + delete repeated_##LOWERCASE##_value; \ + break - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); - HANDLE_TYPE( UINT32, uint32); - HANDLE_TYPE( UINT64, uint64); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( DOUBLE, double); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, enum); - HANDLE_TYPE( STRING, string); + HANDLE_TYPE(INT32, int32); + HANDLE_TYPE(INT64, int64); + HANDLE_TYPE(UINT32, uint32); + HANDLE_TYPE(UINT64, uint64); + HANDLE_TYPE(FLOAT, float); + HANDLE_TYPE(DOUBLE, double); + HANDLE_TYPE(BOOL, bool); + HANDLE_TYPE(ENUM, enum); + HANDLE_TYPE(STRING, string); HANDLE_TYPE(MESSAGE, message); #undef HANDLE_TYPE } @@ -1785,7 +1895,7 @@ bool ExtensionSet::Extension::IsInitialized() const { void ExtensionSet::LazyMessageExtension::UnusedKeyMethod() {} const ExtensionSet::Extension* ExtensionSet::FindOrNull(int key) const { - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { return FindOrNullInLargeMap(key); } const KeyValue* end = flat_end(); @@ -1808,7 +1918,7 @@ const ExtensionSet::Extension* ExtensionSet::FindOrNullInLargeMap( } ExtensionSet::Extension* ExtensionSet::FindOrNull(int key) { - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { return FindOrNullInLargeMap(key); } KeyValue* end = flat_end(); @@ -1830,7 +1940,7 @@ ExtensionSet::Extension* ExtensionSet::FindOrNullInLargeMap(int key) { } std::pair ExtensionSet::Insert(int key) { - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { auto maybe = map_.large->insert({key, Extension()}); return {&maybe.first->second, maybe.second}; } @@ -1852,13 +1962,15 @@ std::pair ExtensionSet::Insert(int key) { } void ExtensionSet::GrowCapacity(size_t minimum_new_capacity) { - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { return; // LargeMap does not have a "reserve" method. } if (flat_capacity_ >= minimum_new_capacity) { return; } + const auto old_flat_capacity = flat_capacity_; + do { flat_capacity_ = flat_capacity_ == 0 ? 1 : flat_capacity_ * 4; } while (flat_capacity_ < minimum_new_capacity); @@ -1867,24 +1979,26 @@ void ExtensionSet::GrowCapacity(size_t minimum_new_capacity) { const KeyValue* end = flat_end(); if (flat_capacity_ > kMaximumFlatCapacity) { // Switch to LargeMap - map_.large = ::google::protobuf::Arena::Create(arena_); + map_.large = Arena::Create(arena_); LargeMap::iterator hint = map_.large->begin(); for (const KeyValue* it = begin; it != end; ++it) { hint = map_.large->insert(hint, {it->first, it->second}); } flat_size_ = 0; } else { - map_.flat = ::google::protobuf::Arena::CreateArray(arena_, flat_capacity_); + map_.flat = Arena::CreateArray(arena_, flat_capacity_); std::copy(begin, end, map_.flat); } - if (arena_ == NULL) delete[] begin; + if (arena_ == nullptr) { + DeleteFlatMap(begin, old_flat_capacity); + } } // static constexpr uint16 ExtensionSet::kMaximumFlatCapacity; void ExtensionSet::Erase(int key) { - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { map_.large->erase(key); return; } @@ -1911,6 +2025,78 @@ RepeatedStringTypeTraits::GetDefaultRepeatedField() { return instance; } +void ExtensionSet::Extension::SerializeMessageSetItemWithCachedSizes( + int number, io::CodedOutputStream* output) const { + if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) { + // Not a valid MessageSet extension, but serialize it the normal way. + SerializeFieldWithCachedSizes(number, output); + return; + } + + if (is_cleared) return; + + // Start group. + output->WriteTag(WireFormatLite::kMessageSetItemStartTag); + + // Write type ID. + WireFormatLite::WriteUInt32(WireFormatLite::kMessageSetTypeIdNumber, number, + output); + // Write message. + if (is_lazy) { + lazymessage_value->WriteMessage(WireFormatLite::kMessageSetMessageNumber, + output); + } else { + WireFormatLite::WriteMessageMaybeToArray( + WireFormatLite::kMessageSetMessageNumber, *message_value, output); + } + + // End group. + output->WriteTag(WireFormatLite::kMessageSetItemEndTag); +} + +size_t ExtensionSet::Extension::MessageSetItemByteSize(int number) const { + if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) { + // Not a valid MessageSet extension, but compute the byte size for it the + // normal way. + return ByteSize(number); + } + + if (is_cleared) return 0; + + size_t our_size = WireFormatLite::kMessageSetItemTagsSize; + + // type_id + our_size += io::CodedOutputStream::VarintSize32(number); + + // message + size_t message_size = 0; + if (is_lazy) { + message_size = lazymessage_value->ByteSizeLong(); + } else { + message_size = message_value->ByteSizeLong(); + } + + our_size += io::CodedOutputStream::VarintSize32(message_size); + our_size += message_size; + + return our_size; +} + +void ExtensionSet::SerializeMessageSetWithCachedSizes( + io::CodedOutputStream* output) const { + ForEach([output](int number, const Extension& ext) { + ext.SerializeMessageSetItemWithCachedSizes(number, output); + }); +} + +size_t ExtensionSet::MessageSetByteSize() const { + size_t total_size = 0; + ForEach([&total_size](int number, const Extension& ext) { + total_size += ext.MessageSetItemByteSize(number); + }); + return total_size; +} + } // namespace internal } // namespace protobuf } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/extension_set.h b/third_party/protobuf/src/google/protobuf/extension_set.h index a1535baa..a3696624 100644 --- a/third_party/protobuf/src/google/protobuf/extension_set.h +++ b/third_party/protobuf/src/google/protobuf/extension_set.h @@ -47,32 +47,45 @@ #include #include -#include +#include +#include +#include #include +#include + +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif namespace google { - namespace protobuf { - class Arena; - class Descriptor; // descriptor.h - class FieldDescriptor; // descriptor.h - class DescriptorPool; // descriptor.h - class MessageLite; // message_lite.h - class Message; // message.h - class MessageFactory; // message.h - class UnknownFieldSet; // unknown_field_set.h - namespace io { - class CodedInputStream; // coded_stream.h - class CodedOutputStream; // coded_stream.h - } - namespace internal { - class FieldSkipper; // wire_format_lite.h - } +class Arena; +class Descriptor; // descriptor.h +class FieldDescriptor; // descriptor.h +class DescriptorPool; // descriptor.h +class MessageLite; // message_lite.h +class Message; // message.h +class MessageFactory; // message.h +class UnknownFieldSet; // unknown_field_set.h +namespace io { +class CodedInputStream; // coded_stream.h +class CodedOutputStream; // coded_stream.h +} // namespace io +namespace internal { +class FieldSkipper; // wire_format_lite.h } +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace internal { +class InternalMetadataWithArenaLite; +class InternalMetadataWithArena; + // Used to store values of type WireFormatLite::FieldType without having to // #include wire_format_lite.h. Also, ensures that we use only one byte to // store these values, which is important to keep the layout of @@ -92,7 +105,9 @@ typedef bool EnumValidityFuncWithArg(const void* arg, int number); struct ExtensionInfo { inline ExtensionInfo() {} inline ExtensionInfo(FieldType type_param, bool isrepeated, bool ispacked) - : type(type_param), is_repeated(isrepeated), is_packed(ispacked), + : type(type_param), + is_repeated(isrepeated), + is_packed(ispacked), descriptor(NULL) {} FieldType type; @@ -104,9 +119,13 @@ struct ExtensionInfo { const void* arg; }; + struct MessageInfo { + const MessageLite* prototype; + }; + union { EnumValidityCheck enum_validity_check; - const MessageLite* message_prototype; + MessageInfo message_info; }; // The descriptor for this extension, if one exists and is known. May be @@ -117,7 +136,7 @@ struct ExtensionInfo { // Abstract interface for an object which looks up extension definitions. Used // when parsing. -class LIBPROTOBUF_EXPORT ExtensionFinder { +class PROTOBUF_EXPORT ExtensionFinder { public: virtual ~ExtensionFinder(); @@ -127,14 +146,14 @@ class LIBPROTOBUF_EXPORT ExtensionFinder { // Implementation of ExtensionFinder which finds extensions defined in .proto // files which have been compiled into the binary. -class LIBPROTOBUF_EXPORT GeneratedExtensionFinder : public ExtensionFinder { +class PROTOBUF_EXPORT GeneratedExtensionFinder : public ExtensionFinder { public: GeneratedExtensionFinder(const MessageLite* containing_type) : containing_type_(containing_type) {} virtual ~GeneratedExtensionFinder() {} // Returns true and fills in *output if found, otherwise returns false. - virtual bool Find(int number, ExtensionInfo* output); + bool Find(int number, ExtensionInfo* output) override; private: const MessageLite* containing_type_; @@ -157,10 +176,10 @@ class MessageSetFieldSkipper; // ExtensionSet. When parsing, if a tag number is encountered which is // inside one of the message type's extension ranges, the tag is passed // off to the ExtensionSet for parsing. Etc. -class LIBPROTOBUF_EXPORT ExtensionSet { +class PROTOBUF_EXPORT ExtensionSet { public: ExtensionSet(); - explicit ExtensionSet(::google::protobuf::Arena* arena); + explicit ExtensionSet(Arena* arena); ~ExtensionSet(); // These are called at startup by protocol-compiler-generated code to @@ -168,9 +187,9 @@ class LIBPROTOBUF_EXPORT ExtensionSet { // to look up extensions for parsed field numbers. Note that dynamic parsing // does not use ParseField(); only protocol-compiler-generated parsing // methods do. - static void RegisterExtension(const MessageLite* containing_type, - int number, FieldType type, - bool is_repeated, bool is_packed); + static void RegisterExtension(const MessageLite* containing_type, int number, + FieldType type, bool is_repeated, + bool is_packed); static void RegisterEnumExtension(const MessageLite* containing_type, int number, FieldType type, bool is_repeated, bool is_packed, @@ -219,22 +238,23 @@ class LIBPROTOBUF_EXPORT ExtensionSet { // - Strings provide Mutable() in addition to Set() accessors. bool Has(int number) const; - int ExtensionSize(int number) const; // Size of a repeated extension. - int NumExtensions() const; // The number of extensions + int ExtensionSize(int number) const; // Size of a repeated extension. + int NumExtensions() const; // The number of extensions FieldType ExtensionType(int number) const; void ClearExtension(int number); // singular fields ------------------------------------------------- - int32 GetInt32 (int number, int32 default_value) const; - int64 GetInt64 (int number, int64 default_value) const; + int32 GetInt32(int number, int32 default_value) const; + int64 GetInt64(int number, int64 default_value) const; uint32 GetUInt32(int number, uint32 default_value) const; uint64 GetUInt64(int number, uint64 default_value) const; - float GetFloat (int number, float default_value) const; + float GetFloat(int number, float default_value) const; double GetDouble(int number, double default_value) const; - bool GetBool (int number, bool default_value) const; - int GetEnum (int number, int default_value) const; - const string & GetString (int number, const string& default_value) const; + bool GetBool(int number, bool default_value) const; + int GetEnum(int number, int default_value) const; + const std::string& GetString(int number, + const std::string& default_value) const; const MessageLite& GetMessage(int number, const MessageLite& default_value) const; const MessageLite& GetMessage(int number, const Descriptor* message_type, @@ -244,16 +264,16 @@ class LIBPROTOBUF_EXPORT ExtensionSet { // the extension lives in the same pool as the descriptor for the containing // type. #define desc const FieldDescriptor* descriptor // avoid line wrapping - void SetInt32 (int number, FieldType type, int32 value, desc); - void SetInt64 (int number, FieldType type, int64 value, desc); + void SetInt32(int number, FieldType type, int32 value, desc); + void SetInt64(int number, FieldType type, int64 value, desc); void SetUInt32(int number, FieldType type, uint32 value, desc); void SetUInt64(int number, FieldType type, uint64 value, desc); - void SetFloat (int number, FieldType type, float value, desc); + void SetFloat(int number, FieldType type, float value, desc); void SetDouble(int number, FieldType type, double value, desc); - void SetBool (int number, FieldType type, bool value, desc); - void SetEnum (int number, FieldType type, int value, desc); - void SetString(int number, FieldType type, const string& value, desc); - string * MutableString (int number, FieldType type, desc); + void SetBool(int number, FieldType type, bool value, desc); + void SetEnum(int number, FieldType type, int value, desc); + void SetString(int number, FieldType type, const std::string& value, desc); + std::string* MutableString(int number, FieldType type, desc); MessageLite* MutableMessage(int number, FieldType type, const MessageLite& prototype, desc); MessageLite* MutableMessage(const FieldDescriptor* decsriptor, @@ -268,15 +288,15 @@ class LIBPROTOBUF_EXPORT ExtensionSet { const FieldDescriptor* descriptor, MessageLite* message); MessageLite* ReleaseMessage(int number, const MessageLite& prototype); - MessageLite* UnsafeArenaReleaseMessage( - int number, const MessageLite& prototype); + MessageLite* UnsafeArenaReleaseMessage(int number, + const MessageLite& prototype); MessageLite* ReleaseMessage(const FieldDescriptor* descriptor, MessageFactory* factory); MessageLite* UnsafeArenaReleaseMessage(const FieldDescriptor* descriptor, MessageFactory* factory); #undef desc - ::google::protobuf::Arena* GetArenaNoVirtual() const { return arena_; } + Arena* GetArenaNoVirtual() const { return arena_; } // repeated fields ------------------------------------------------- @@ -287,8 +307,8 @@ class LIBPROTOBUF_EXPORT ExtensionSet { // Fetches a mutable version of a RepeatedField extension by number, // instantiating one if none exists. Similar to above, user should not use // this directly; it underlies MutableRepeatedExtension(). - void* MutableRawRepeatedField(int number, FieldType field_type, - bool packed, const FieldDescriptor* desc); + void* MutableRawRepeatedField(int number, FieldType field_type, bool packed, + const FieldDescriptor* desc); // This is an overload of MutableRawRepeatedField to maintain compatibility // with old code using a previous API. This version of @@ -296,40 +316,40 @@ class LIBPROTOBUF_EXPORT ExtensionSet { // (E.g.: borg/clients/internal/proto1/proto2_reflection.cc.) void* MutableRawRepeatedField(int number); - int32 GetRepeatedInt32 (int number, int index) const; - int64 GetRepeatedInt64 (int number, int index) const; + int32 GetRepeatedInt32(int number, int index) const; + int64 GetRepeatedInt64(int number, int index) const; uint32 GetRepeatedUInt32(int number, int index) const; uint64 GetRepeatedUInt64(int number, int index) const; - float GetRepeatedFloat (int number, int index) const; + float GetRepeatedFloat(int number, int index) const; double GetRepeatedDouble(int number, int index) const; - bool GetRepeatedBool (int number, int index) const; - int GetRepeatedEnum (int number, int index) const; - const string & GetRepeatedString (int number, int index) const; + bool GetRepeatedBool(int number, int index) const; + int GetRepeatedEnum(int number, int index) const; + const std::string& GetRepeatedString(int number, int index) const; const MessageLite& GetRepeatedMessage(int number, int index) const; - void SetRepeatedInt32 (int number, int index, int32 value); - void SetRepeatedInt64 (int number, int index, int64 value); + void SetRepeatedInt32(int number, int index, int32 value); + void SetRepeatedInt64(int number, int index, int64 value); void SetRepeatedUInt32(int number, int index, uint32 value); void SetRepeatedUInt64(int number, int index, uint64 value); - void SetRepeatedFloat (int number, int index, float value); + void SetRepeatedFloat(int number, int index, float value); void SetRepeatedDouble(int number, int index, double value); - void SetRepeatedBool (int number, int index, bool value); - void SetRepeatedEnum (int number, int index, int value); - void SetRepeatedString(int number, int index, const string& value); - string * MutableRepeatedString (int number, int index); + void SetRepeatedBool(int number, int index, bool value); + void SetRepeatedEnum(int number, int index, int value); + void SetRepeatedString(int number, int index, const std::string& value); + std::string* MutableRepeatedString(int number, int index); MessageLite* MutableRepeatedMessage(int number, int index); #define desc const FieldDescriptor* descriptor // avoid line wrapping - void AddInt32 (int number, FieldType type, bool packed, int32 value, desc); - void AddInt64 (int number, FieldType type, bool packed, int64 value, desc); + void AddInt32(int number, FieldType type, bool packed, int32 value, desc); + void AddInt64(int number, FieldType type, bool packed, int64 value, desc); void AddUInt32(int number, FieldType type, bool packed, uint32 value, desc); void AddUInt64(int number, FieldType type, bool packed, uint64 value, desc); - void AddFloat (int number, FieldType type, bool packed, float value, desc); + void AddFloat(int number, FieldType type, bool packed, float value, desc); void AddDouble(int number, FieldType type, bool packed, double value, desc); - void AddBool (int number, FieldType type, bool packed, bool value, desc); - void AddEnum (int number, FieldType type, bool packed, int value, desc); - void AddString(int number, FieldType type, const string& value, desc); - string * AddString (int number, FieldType type, desc); + void AddBool(int number, FieldType type, bool packed, bool value, desc); + void AddEnum(int number, FieldType type, bool packed, int value, desc); + void AddString(int number, FieldType type, const std::string& value, desc); + std::string* AddString(int number, FieldType type, desc); MessageLite* AddMessage(int number, FieldType type, const MessageLite& prototype, desc); MessageLite* AddMessage(const FieldDescriptor* descriptor, @@ -378,8 +398,53 @@ class LIBPROTOBUF_EXPORT ExtensionSet { const MessageLite* containing_type, io::CodedOutputStream* unknown_fields); +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + // Lite parser + const char* ParseField(uint64 tag, const char* ptr, + const MessageLite* containing_type, + internal::InternalMetadataWithArenaLite* metadata, + internal::ParseContext* ctx); + // Full parser + const char* ParseField(uint64 tag, const char* ptr, + const Message* containing_type, + internal::InternalMetadataWithArena* metadata, + internal::ParseContext* ctx); + template + const char* ParseMessageSet(const char* ptr, const Msg* containing_type, + Metadata* metadata, internal::ParseContext* ctx) { + struct MessageSetItem { + const char* _InternalParse(const char* ptr, ParseContext* ctx) { + return me->ParseMessageSetItem(ptr, containing_type, metadata, ctx); + } + ExtensionSet* me; + const Msg* containing_type; + Metadata* metadata; + } item{this, containing_type, metadata}; + while (!ctx->Done(&ptr)) { + uint32 tag; + ptr = ReadTag(ptr, &tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + if (tag == WireFormatLite::kMessageSetItemStartTag) { + ptr = ctx->ParseGroup(&item, ptr, tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + } else { + if (tag == 0 || (tag & 7) == 4) { + ctx->SetLastTag(tag); + return ptr; + } + ptr = ParseField(tag, ptr, containing_type, metadata, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + } + } + return ptr; + } +#endif + // Parse an entire message in MessageSet format. Such messages have no // fields, only extensions. + bool ParseMessageSetLite(io::CodedInputStream* input, + ExtensionFinder* extension_finder, + FieldSkipper* field_skipper); bool ParseMessageSet(io::CodedInputStream* input, ExtensionFinder* extension_finder, MessageSetFieldSkipper* field_skipper); @@ -387,7 +452,8 @@ class LIBPROTOBUF_EXPORT ExtensionSet { // Specific versions for lite or full messages (constructs the appropriate // FieldSkipper automatically). bool ParseMessageSet(io::CodedInputStream* input, - const MessageLite* containing_type); + const MessageLite* containing_type, + std::string* unknown_fields); bool ParseMessageSet(io::CodedInputStream* input, const Message* containing_type, UnknownFieldSet* unknown_fields); @@ -396,8 +462,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet { // [start_field_number, end_field_number) // to the output stream, using the cached sizes computed when ByteSize() was // last called. Note that the range bounds are inclusive-exclusive. - void SerializeWithCachedSizes(int start_field_number, - int end_field_number, + void SerializeWithCachedSizes(int start_field_number, int end_field_number, io::CodedOutputStream* output) const; // Same as SerializeWithCachedSizes, but without any bounds checking. @@ -407,13 +472,11 @@ class LIBPROTOBUF_EXPORT ExtensionSet { // Returns a pointer past the last written byte. uint8* InternalSerializeWithCachedSizesToArray(int start_field_number, int end_field_number, - bool deterministic, uint8* target) const; // Like above but serializes in MessageSet format. void SerializeMessageSetWithCachedSizes(io::CodedOutputStream* output) const; - uint8* InternalSerializeMessageSetWithCachedSizesToArray(bool deterministic, - uint8* target) const; + uint8* InternalSerializeMessageSetWithCachedSizesToArray(uint8* target) const; // For backward-compatibility, versions of two of the above methods that // serialize deterministically iff SetDefaultSerializationDeterministic() @@ -446,29 +509,26 @@ class LIBPROTOBUF_EXPORT ExtensionSet { int SpaceUsedExcludingSelf() const; private: - // Interface of a lazily parsed singular message extension. - class LIBPROTOBUF_EXPORT LazyMessageExtension { + class PROTOBUF_EXPORT LazyMessageExtension { public: LazyMessageExtension() {} virtual ~LazyMessageExtension() {} - virtual LazyMessageExtension* New(::google::protobuf::Arena* arena) const = 0; + virtual LazyMessageExtension* New(Arena* arena) const = 0; virtual const MessageLite& GetMessage( const MessageLite& prototype) const = 0; virtual MessageLite* MutableMessage(const MessageLite& prototype) = 0; - virtual void SetAllocatedMessage(MessageLite *message) = 0; - virtual void UnsafeArenaSetAllocatedMessage(MessageLite *message) = 0; + virtual void SetAllocatedMessage(MessageLite* message) = 0; + virtual void UnsafeArenaSetAllocatedMessage(MessageLite* message) = 0; virtual MessageLite* ReleaseMessage(const MessageLite& prototype) = 0; virtual MessageLite* UnsafeArenaReleaseMessage( const MessageLite& prototype) = 0; virtual bool IsInitialized() const = 0; - PROTOBUF_RUNTIME_DEPRECATED("Please use ByteSizeLong() instead") - virtual int ByteSize() const { - return internal::ToIntSize(ByteSizeLong()); - } + PROTOBUF_DEPRECATED_MSG("Please use ByteSizeLong() instead") + virtual int ByteSize() const { return internal::ToIntSize(ByteSizeLong()); } virtual size_t ByteSizeLong() const = 0; virtual size_t SpaceUsedLong() const = 0; @@ -477,15 +537,12 @@ class LIBPROTOBUF_EXPORT ExtensionSet { virtual bool ReadMessage(const MessageLite& prototype, io::CodedInputStream* input) = 0; +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + virtual const char* _InternalParse(const char* ptr, ParseContext* ctx) = 0; +#endif virtual void WriteMessage(int number, io::CodedOutputStream* output) const = 0; virtual uint8* WriteMessageToArray(int number, uint8* target) const = 0; - virtual uint8* InternalWriteMessageToArray(int number, bool, - uint8* target) const { - // TODO(gpike): make this pure virtual. This is a placeholder because we - // need to update third_party/upb, for example. - return WriteMessageToArray(number, target); - } private: virtual void UnusedKeyMethod(); // Dummy key method to avoid weak vtable. @@ -496,27 +553,27 @@ class LIBPROTOBUF_EXPORT ExtensionSet { // The order of these fields packs Extension into 24 bytes when using 8 // byte alignment. Consider this when adding or removing fields here. union { - int32 int32_value; - int64 int64_value; - uint32 uint32_value; - uint64 uint64_value; - float float_value; - double double_value; - bool bool_value; - int enum_value; - string* string_value; - MessageLite* message_value; + int32 int32_value; + int64 int64_value; + uint32 uint32_value; + uint64 uint64_value; + float float_value; + double double_value; + bool bool_value; + int enum_value; + std::string* string_value; + MessageLite* message_value; LazyMessageExtension* lazymessage_value; - RepeatedField * repeated_int32_value; - RepeatedField * repeated_int64_value; - RepeatedField * repeated_uint32_value; - RepeatedField * repeated_uint64_value; - RepeatedField * repeated_float_value; - RepeatedField * repeated_double_value; - RepeatedField * repeated_bool_value; - RepeatedField * repeated_enum_value; - RepeatedPtrField* repeated_string_value; + RepeatedField* repeated_int32_value; + RepeatedField* repeated_int64_value; + RepeatedField* repeated_uint32_value; + RepeatedField* repeated_uint64_value; + RepeatedField* repeated_float_value; + RepeatedField* repeated_double_value; + RepeatedField* repeated_bool_value; + RepeatedField* repeated_enum_value; + RepeatedPtrField* repeated_string_value; RepeatedPtrField* repeated_message_value; }; @@ -552,20 +609,14 @@ class LIBPROTOBUF_EXPORT ExtensionSet { const FieldDescriptor* descriptor; // Some helper methods for operations on a single Extension. - void SerializeFieldWithCachedSizes( - int number, - io::CodedOutputStream* output) const; - uint8* InternalSerializeFieldWithCachedSizesToArray( - int number, - bool deterministic, - uint8* target) const; + void SerializeFieldWithCachedSizes(int number, + io::CodedOutputStream* output) const; + uint8* InternalSerializeFieldWithCachedSizesToArray(int number, + uint8* target) const; void SerializeMessageSetItemWithCachedSizes( - int number, - io::CodedOutputStream* output) const; + int number, io::CodedOutputStream* output) const; uint8* InternalSerializeMessageSetItemWithCachedSizesToArray( - int number, - bool deterministic, - uint8* target) const; + int number, uint8* target) const; size_t ByteSize(int number) const; size_t MessageSetItemByteSize(int number) const; void Clear(); @@ -625,7 +676,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet { void Erase(int key); size_t Size() const { - return GOOGLE_PREDICT_FALSE(is_large()) ? map_.large->size() : flat_size_; + return PROTOBUF_PREDICT_FALSE(is_large()) ? map_.large->size() : flat_size_; } // Similar to std::for_each. @@ -641,7 +692,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet { // Applies a functor to the pairs in sorted order. template KeyValueFunctor ForEach(KeyValueFunctor func) { - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { return ForEach(map_.large->begin(), map_.large->end(), std::move(func)); } return ForEach(flat_begin(), flat_end(), std::move(func)); @@ -650,7 +701,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet { // Applies a functor to the pairs in sorted order. template KeyValueFunctor ForEach(KeyValueFunctor func) const { - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { return ForEach(map_.large->begin(), map_.large->end(), std::move(func)); } return ForEach(flat_begin(), flat_end(), std::move(func)); @@ -680,8 +731,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet { // positioned immediately after the wire tag. This method is called in // ParseField() after field number and was_packed_on_wire is extracted from // the wire tag and ExtensionInfo is found by the field number. - bool ParseFieldWithExtensionInfo(int field_number, - bool was_packed_on_wire, + bool ParseFieldWithExtensionInfo(int field_number, bool was_packed_on_wire, const ExtensionInfo& extension, io::CodedInputStream* input, FieldSkipper* field_skipper); @@ -702,12 +752,64 @@ class LIBPROTOBUF_EXPORT ExtensionSet { // it does not exist. Extension* MaybeNewRepeatedExtension(const FieldDescriptor* descriptor); + // Parse a single MessageSet item -- called just after the item group start + // tag has been read. + bool ParseMessageSetItemLite(io::CodedInputStream* input, + ExtensionFinder* extension_finder, + FieldSkipper* field_skipper); // Parse a single MessageSet item -- called just after the item group start // tag has been read. bool ParseMessageSetItem(io::CodedInputStream* input, ExtensionFinder* extension_finder, MessageSetFieldSkipper* field_skipper); +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + bool FindExtension(int wire_type, uint32 field, + const MessageLite* containing_type, + const internal::ParseContext* ctx, + ExtensionInfo* extension, bool* was_packed_on_wire) { + GeneratedExtensionFinder finder(containing_type); + return FindExtensionInfoFromFieldNumber(wire_type, field, &finder, + extension, was_packed_on_wire); + } + inline bool FindExtension(int wire_type, uint32 field, + const Message* containing_type, + const internal::ParseContext* ctx, + ExtensionInfo* extension, bool* was_packed_on_wire); + // Used for MessageSet only + const char* ParseFieldMaybeLazily( + uint64 tag, const char* ptr, const MessageLite* containing_type, + internal::InternalMetadataWithArenaLite* metadata, + internal::ParseContext* ctx) { + // Lite MessageSet doesn't implement lazy. + return ParseField(tag, ptr, containing_type, metadata, ctx); + } + const char* ParseFieldMaybeLazily( + uint64 tag, const char* ptr, const Message* containing_type, + internal::InternalMetadataWithArena* metadata, + internal::ParseContext* ctx); + const char* ParseMessageSetItem( + const char* ptr, const MessageLite* containing_type, + internal::InternalMetadataWithArenaLite* metadata, + internal::ParseContext* ctx); + const char* ParseMessageSetItem(const char* ptr, + const Message* containing_type, + internal::InternalMetadataWithArena* metadata, + internal::ParseContext* ctx); + + // Implemented in extension_set_inl.h to keep code out of the header file. + template + const char* ParseFieldWithExtensionInfo(int number, bool was_packed_on_wire, + const ExtensionInfo& info, + T* metadata, const char* ptr, + internal::ParseContext* ctx); + template + const char* ParseMessageSetItemTmpl(const char* ptr, + const Msg* containing_type, + Metadata* metadata, + internal::ParseContext* ctx); +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + // Hack: RepeatedPtrFieldBase declares ExtensionSet as a friend. This // friendship should automatically extend to ExtensionSet::Extension, but // unfortunately some older compilers (e.g. GCC 3.4.4) do not implement this @@ -735,7 +837,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet { return map_.flat + flat_size_; } - ::google::protobuf::Arena* arena_; + Arena* arena_; // Manual memory-management: // map_.flat is an allocated array of flat_capacity_ elements. @@ -750,21 +852,23 @@ class LIBPROTOBUF_EXPORT ExtensionSet { LargeMap* large; } map_; + static void DeleteFlatMap(const KeyValue* flat, uint16 flat_capacity); + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionSet); }; // These are just for convenience... inline void ExtensionSet::SetString(int number, FieldType type, - const string& value, + const std::string& value, const FieldDescriptor* descriptor) { MutableString(number, type, descriptor)->assign(value); } inline void ExtensionSet::SetRepeatedString(int number, int index, - const string& value) { + const std::string& value) { MutableRepeatedString(number, index)->assign(value); } inline void ExtensionSet::AddString(int number, FieldType type, - const string& value, + const std::string& value, const FieldDescriptor* descriptor) { AddString(number, type, descriptor)->assign(value); } @@ -841,8 +945,8 @@ class PrimitiveTypeTraits { static inline ConstType Get(int number, const ExtensionSet& set, ConstType default_value); - static inline void Set(int number, FieldType field_type, - ConstType value, ExtensionSet* set); + static inline void Set(int number, FieldType field_type, ConstType value, + ExtensionSet* set); template static void Register(int number, FieldType type, bool is_packed) { ExtensionSet::RegisterExtension(&ExtendeeT::default_instance(), number, @@ -861,14 +965,15 @@ class RepeatedPrimitiveTypeTraits { static inline Type Get(int number, const ExtensionSet& set, int index); static inline void Set(int number, int index, Type value, ExtensionSet* set); - static inline void Add(int number, FieldType field_type, - bool is_packed, Type value, ExtensionSet* set); + static inline void Add(int number, FieldType field_type, bool is_packed, + Type value, ExtensionSet* set); - static inline const RepeatedField& - GetRepeated(int number, const ExtensionSet& set); - static inline RepeatedField* - MutableRepeated(int number, FieldType field_type, - bool is_packed, ExtensionSet* set); + static inline const RepeatedField& GetRepeated( + int number, const ExtensionSet& set); + static inline RepeatedField* MutableRepeated(int number, + FieldType field_type, + bool is_packed, + ExtensionSet* set); static const RepeatedFieldType* GetDefaultRepeatedField(); template @@ -878,11 +983,10 @@ class RepeatedPrimitiveTypeTraits { } }; -LIBPROTOBUF_EXPORT extern ProtobufOnceType repeated_primitive_generic_type_traits_once_init_; - -class LIBPROTOBUF_EXPORT RepeatedPrimitiveDefaults { +class PROTOBUF_EXPORT RepeatedPrimitiveDefaults { private: - template friend class RepeatedPrimitiveTypeTraits; + template + friend class RepeatedPrimitiveTypeTraits; static const RepeatedPrimitiveDefaults* default_instance(); RepeatedField default_repeated_field_int32_; RepeatedField default_repeated_field_int64_; @@ -893,57 +997,62 @@ class LIBPROTOBUF_EXPORT RepeatedPrimitiveDefaults { RepeatedField default_repeated_field_bool_; }; -#define PROTOBUF_DEFINE_PRIMITIVE_TYPE(TYPE, METHOD) \ -template<> inline TYPE PrimitiveTypeTraits::Get( \ - int number, const ExtensionSet& set, TYPE default_value) { \ - return set.Get##METHOD(number, default_value); \ -} \ -template<> inline void PrimitiveTypeTraits::Set( \ - int number, FieldType field_type, TYPE value, ExtensionSet* set) { \ - set->Set##METHOD(number, field_type, value, NULL); \ -} \ - \ -template<> inline TYPE RepeatedPrimitiveTypeTraits::Get( \ - int number, const ExtensionSet& set, int index) { \ - return set.GetRepeated##METHOD(number, index); \ -} \ -template<> inline void RepeatedPrimitiveTypeTraits::Set( \ - int number, int index, TYPE value, ExtensionSet* set) { \ - set->SetRepeated##METHOD(number, index, value); \ -} \ -template<> inline void RepeatedPrimitiveTypeTraits::Add( \ - int number, FieldType field_type, bool is_packed, \ - TYPE value, ExtensionSet* set) { \ - set->Add##METHOD(number, field_type, is_packed, value, NULL); \ -} \ -template<> inline const RepeatedField* \ - RepeatedPrimitiveTypeTraits::GetDefaultRepeatedField() { \ - return &RepeatedPrimitiveDefaults::default_instance() \ - ->default_repeated_field_##TYPE##_; \ -} \ -template<> inline const RepeatedField& \ - RepeatedPrimitiveTypeTraits::GetRepeated(int number, \ - const ExtensionSet& set) { \ - return *reinterpret_cast*>( \ - set.GetRawRepeatedField( \ - number, GetDefaultRepeatedField())); \ -} \ -template<> inline RepeatedField* \ - RepeatedPrimitiveTypeTraits::MutableRepeated(int number, \ - FieldType field_type, \ - bool is_packed, \ - ExtensionSet* set) { \ - return reinterpret_cast*>( \ - set->MutableRawRepeatedField(number, field_type, is_packed, NULL)); \ -} +#define PROTOBUF_DEFINE_PRIMITIVE_TYPE(TYPE, METHOD) \ + template <> \ + inline TYPE PrimitiveTypeTraits::Get( \ + int number, const ExtensionSet& set, TYPE default_value) { \ + return set.Get##METHOD(number, default_value); \ + } \ + template <> \ + inline void PrimitiveTypeTraits::Set(int number, FieldType field_type, \ + TYPE value, ExtensionSet* set) { \ + set->Set##METHOD(number, field_type, value, NULL); \ + } \ + \ + template <> \ + inline TYPE RepeatedPrimitiveTypeTraits::Get( \ + int number, const ExtensionSet& set, int index) { \ + return set.GetRepeated##METHOD(number, index); \ + } \ + template <> \ + inline void RepeatedPrimitiveTypeTraits::Set( \ + int number, int index, TYPE value, ExtensionSet* set) { \ + set->SetRepeated##METHOD(number, index, value); \ + } \ + template <> \ + inline void RepeatedPrimitiveTypeTraits::Add( \ + int number, FieldType field_type, bool is_packed, TYPE value, \ + ExtensionSet* set) { \ + set->Add##METHOD(number, field_type, is_packed, value, NULL); \ + } \ + template <> \ + inline const RepeatedField* \ + RepeatedPrimitiveTypeTraits::GetDefaultRepeatedField() { \ + return &RepeatedPrimitiveDefaults::default_instance() \ + ->default_repeated_field_##TYPE##_; \ + } \ + template <> \ + inline const RepeatedField& \ + RepeatedPrimitiveTypeTraits::GetRepeated(int number, \ + const ExtensionSet& set) { \ + return *reinterpret_cast*>( \ + set.GetRawRepeatedField(number, GetDefaultRepeatedField())); \ + } \ + template <> \ + inline RepeatedField* \ + RepeatedPrimitiveTypeTraits::MutableRepeated( \ + int number, FieldType field_type, bool is_packed, ExtensionSet* set) { \ + return reinterpret_cast*>( \ + set->MutableRawRepeatedField(number, field_type, is_packed, NULL)); \ + } -PROTOBUF_DEFINE_PRIMITIVE_TYPE( int32, Int32) -PROTOBUF_DEFINE_PRIMITIVE_TYPE( int64, Int64) +PROTOBUF_DEFINE_PRIMITIVE_TYPE(int32, Int32) +PROTOBUF_DEFINE_PRIMITIVE_TYPE(int64, Int64) PROTOBUF_DEFINE_PRIMITIVE_TYPE(uint32, UInt32) PROTOBUF_DEFINE_PRIMITIVE_TYPE(uint64, UInt64) -PROTOBUF_DEFINE_PRIMITIVE_TYPE( float, Float) +PROTOBUF_DEFINE_PRIMITIVE_TYPE(float, Float) PROTOBUF_DEFINE_PRIMITIVE_TYPE(double, Double) -PROTOBUF_DEFINE_PRIMITIVE_TYPE( bool, Bool) +PROTOBUF_DEFINE_PRIMITIVE_TYPE(bool, Bool) #undef PROTOBUF_DEFINE_PRIMITIVE_TYPE @@ -951,22 +1060,22 @@ PROTOBUF_DEFINE_PRIMITIVE_TYPE( bool, Bool) // StringTypeTraits // Strings support both Set() and Mutable(). -class LIBPROTOBUF_EXPORT StringTypeTraits { +class PROTOBUF_EXPORT StringTypeTraits { public: - typedef const string& ConstType; - typedef string* MutableType; + typedef const std::string& ConstType; + typedef std::string* MutableType; typedef StringTypeTraits Singular; - static inline const string& Get(int number, const ExtensionSet& set, - ConstType default_value) { + static inline const std::string& Get(int number, const ExtensionSet& set, + ConstType default_value) { return set.GetString(number, default_value); } static inline void Set(int number, FieldType field_type, - const string& value, ExtensionSet* set) { + const std::string& value, ExtensionSet* set) { set->SetString(number, field_type, value, NULL); } - static inline string* Mutable(int number, FieldType field_type, - ExtensionSet* set) { + static inline std::string* Mutable(int number, FieldType field_type, + ExtensionSet* set) { return set->MutableString(number, field_type, NULL); } template @@ -976,46 +1085,43 @@ class LIBPROTOBUF_EXPORT StringTypeTraits { } }; -class LIBPROTOBUF_EXPORT RepeatedStringTypeTraits { +class PROTOBUF_EXPORT RepeatedStringTypeTraits { public: - typedef const string& ConstType; - typedef string* MutableType; + typedef const std::string& ConstType; + typedef std::string* MutableType; typedef RepeatedStringTypeTraits Repeated; - typedef RepeatedPtrField RepeatedFieldType; + typedef RepeatedPtrField RepeatedFieldType; - static inline const string& Get(int number, const ExtensionSet& set, - int index) { + static inline const std::string& Get(int number, const ExtensionSet& set, + int index) { return set.GetRepeatedString(number, index); } - static inline void Set(int number, int index, - const string& value, ExtensionSet* set) { + static inline void Set(int number, int index, const std::string& value, + ExtensionSet* set) { set->SetRepeatedString(number, index, value); } - static inline string* Mutable(int number, int index, ExtensionSet* set) { + static inline std::string* Mutable(int number, int index, ExtensionSet* set) { return set->MutableRepeatedString(number, index); } - static inline void Add(int number, FieldType field_type, - bool /*is_packed*/, const string& value, - ExtensionSet* set) { + static inline void Add(int number, FieldType field_type, bool /*is_packed*/, + const std::string& value, ExtensionSet* set) { set->AddString(number, field_type, value, NULL); } - static inline string* Add(int number, FieldType field_type, - ExtensionSet* set) { + static inline std::string* Add(int number, FieldType field_type, + ExtensionSet* set) { return set->AddString(number, field_type, NULL); } - static inline const RepeatedPtrField& - GetRepeated(int number, const ExtensionSet& set) { - return *reinterpret_cast*>( + static inline const RepeatedPtrField& GetRepeated( + int number, const ExtensionSet& set) { + return *reinterpret_cast*>( set.GetRawRepeatedField(number, GetDefaultRepeatedField())); } - static inline RepeatedPtrField* - MutableRepeated(int number, FieldType field_type, - bool is_packed, ExtensionSet* set) { - return reinterpret_cast*>( - set->MutableRawRepeatedField(number, field_type, - is_packed, NULL)); + static inline RepeatedPtrField* MutableRepeated( + int number, FieldType field_type, bool is_packed, ExtensionSet* set) { + return reinterpret_cast*>( + set->MutableRawRepeatedField(number, field_type, is_packed, NULL)); } static const RepeatedFieldType* GetDefaultRepeatedField(); @@ -1047,8 +1153,8 @@ class EnumTypeTraits { ConstType default_value) { return static_cast(set.GetEnum(number, default_value)); } - static inline void Set(int number, FieldType field_type, - ConstType value, ExtensionSet* set) { + static inline void Set(int number, FieldType field_type, ConstType value, + ExtensionSet* set) { GOOGLE_DCHECK(IsValid(value)); set->SetEnum(number, field_type, value, NULL); } @@ -1071,19 +1177,18 @@ class RepeatedEnumTypeTraits { static inline ConstType Get(int number, const ExtensionSet& set, int index) { return static_cast(set.GetRepeatedEnum(number, index)); } - static inline void Set(int number, int index, - ConstType value, ExtensionSet* set) { + static inline void Set(int number, int index, ConstType value, + ExtensionSet* set) { GOOGLE_DCHECK(IsValid(value)); set->SetRepeatedEnum(number, index, value); } - static inline void Add(int number, FieldType field_type, - bool is_packed, ConstType value, ExtensionSet* set) { + static inline void Add(int number, FieldType field_type, bool is_packed, + ConstType value, ExtensionSet* set) { GOOGLE_DCHECK(IsValid(value)); set->AddEnum(number, field_type, is_packed, value, NULL); } - static inline const RepeatedField& GetRepeated(int number, - const ExtensionSet& - set) { + static inline const RepeatedField& GetRepeated( + int number, const ExtensionSet& set) { // Hack: the `Extension` struct stores a RepeatedField for enums. // RepeatedField cannot implicitly convert to RepeatedField // so we need to do some casting magic. See message.h for similar @@ -1132,13 +1237,12 @@ class MessageTypeTraits { static inline ConstType Get(int number, const ExtensionSet& set, ConstType default_value) { - return static_cast( - set.GetMessage(number, default_value)); + return static_cast(set.GetMessage(number, default_value)); } static inline MutableType Mutable(int number, FieldType field_type, ExtensionSet* set) { - return static_cast( - set->MutableMessage(number, field_type, Type::default_instance(), NULL)); + return static_cast(set->MutableMessage( + number, field_type, Type::default_instance(), NULL)); } static inline void SetAllocated(int number, FieldType field_type, MutableType message, ExtensionSet* set) { @@ -1151,14 +1255,14 @@ class MessageTypeTraits { } static inline MutableType Release(int number, FieldType /* field_type */, ExtensionSet* set) { - return static_cast(set->ReleaseMessage( - number, Type::default_instance())); + return static_cast( + set->ReleaseMessage(number, Type::default_instance())); } static inline MutableType UnsafeArenaRelease(int number, FieldType /* field_type */, ExtensionSet* set) { - return static_cast(set->UnsafeArenaReleaseMessage( - number, Type::default_instance())); + return static_cast( + set->UnsafeArenaReleaseMessage(number, Type::default_instance())); } template static void Register(int number, FieldType type, bool is_packed) { @@ -1191,9 +1295,8 @@ class RepeatedMessageTypeTraits { return static_cast( set->AddMessage(number, field_type, Type::default_instance(), NULL)); } - static inline const RepeatedPtrField& GetRepeated(int number, - const ExtensionSet& - set) { + static inline const RepeatedPtrField& GetRepeated( + int number, const ExtensionSet& set) { // See notes above in RepeatedEnumTypeTraits::GetRepeated(): same // casting hack applies here, because a RepeatedPtrField // cannot naturally become a RepeatedPtrType even though Type is @@ -1219,9 +1322,9 @@ class RepeatedMessageTypeTraits { } }; -template inline - const typename RepeatedMessageTypeTraits::RepeatedFieldType* - RepeatedMessageTypeTraits::GetDefaultRepeatedField() { +template +inline const typename RepeatedMessageTypeTraits::RepeatedFieldType* +RepeatedMessageTypeTraits::GetDefaultRepeatedField() { static auto instance = OnShutdownDelete(new RepeatedFieldType); return instance; } @@ -1236,15 +1339,15 @@ template inline // // Note that we could, in theory, supply the field number as a template // parameter, and thus make an instance of ExtensionIdentifier have no -// actual contents. However, if we did that, then using at extension +// actual contents. However, if we did that, then using an extension // identifier would not necessarily cause the compiler to output any sort // of reference to any symbol defined in the extension's .pb.o file. Some // linkers will actually drop object files that are not explicitly referenced, // but that would be bad because it would cause this extension to not be // registered at static initialization, and therefore using it would crash. -template +template class ExtensionIdentifier { public: typedef TypeTraitsType TypeTraits; @@ -1281,182 +1384,214 @@ class ExtensionIdentifier { // // For similar reason, we use "_field_type" and "_is_packed" as parameter names // below, so that "field_type" and "is_packed" can be used as field names. -#define GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(CLASSNAME) \ +#define GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(CLASSNAME) \ /* Has, Size, Clear */ \ template \ inline bool HasExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \ return _extensions_.Has(id.number()); \ } \ \ template \ inline void ClearExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \ _extensions_.ClearExtension(id.number()); \ } \ \ template \ inline int ExtensionSize( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \ return _extensions_.ExtensionSize(id.number()); \ } \ \ /* Singular accessors */ \ template \ inline typename _proto_TypeTraits::Singular::ConstType GetExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \ return _proto_TypeTraits::Get(id.number(), _extensions_, \ id.default_value()); \ } \ \ template \ inline typename _proto_TypeTraits::Singular::MutableType MutableExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \ return _proto_TypeTraits::Mutable(id.number(), _field_type, \ &_extensions_); \ } \ \ template \ inline void SetExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ typename _proto_TypeTraits::Singular::ConstType value) { \ _proto_TypeTraits::Set(id.number(), _field_type, value, &_extensions_); \ } \ \ template \ inline void SetAllocatedExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ typename _proto_TypeTraits::Singular::MutableType value) { \ - _proto_TypeTraits::SetAllocated(id.number(), _field_type, \ - value, &_extensions_); \ + _proto_TypeTraits::SetAllocated(id.number(), _field_type, value, \ + &_extensions_); \ } \ template \ inline void UnsafeArenaSetAllocatedExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ typename _proto_TypeTraits::Singular::MutableType value) { \ _proto_TypeTraits::UnsafeArenaSetAllocated(id.number(), _field_type, \ value, &_extensions_); \ } \ template \ inline typename _proto_TypeTraits::Singular::MutableType ReleaseExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \ return _proto_TypeTraits::Release(id.number(), _field_type, \ &_extensions_); \ } \ template \ inline typename _proto_TypeTraits::Singular::MutableType \ - UnsafeArenaReleaseExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \ + UnsafeArenaReleaseExtension( \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \ return _proto_TypeTraits::UnsafeArenaRelease(id.number(), _field_type, \ &_extensions_); \ } \ \ /* Repeated accessors */ \ template \ inline typename _proto_TypeTraits::Repeated::ConstType GetExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ int index) const { \ return _proto_TypeTraits::Get(id.number(), _extensions_, index); \ } \ \ template \ inline typename _proto_TypeTraits::Repeated::MutableType MutableExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ int index) { \ return _proto_TypeTraits::Mutable(id.number(), index, &_extensions_); \ } \ \ template \ inline void SetExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ int index, typename _proto_TypeTraits::Repeated::ConstType value) { \ _proto_TypeTraits::Set(id.number(), index, value, &_extensions_); \ } \ \ template \ inline typename _proto_TypeTraits::Repeated::MutableType AddExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \ return _proto_TypeTraits::Add(id.number(), _field_type, &_extensions_); \ } \ \ template \ inline void AddExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ typename _proto_TypeTraits::Repeated::ConstType value) { \ - _proto_TypeTraits::Add(id.number(), _field_type, _is_packed, \ - value, &_extensions_); \ + _proto_TypeTraits::Add(id.number(), _field_type, _is_packed, value, \ + &_extensions_); \ } \ \ template \ inline const typename _proto_TypeTraits::Repeated::RepeatedFieldType& \ - GetRepeatedExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, _field_type, \ - _is_packed>& id) const { \ + GetRepeatedExtension( \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \ return _proto_TypeTraits::GetRepeated(id.number(), _extensions_); \ } \ \ template \ inline typename _proto_TypeTraits::Repeated::RepeatedFieldType* \ - MutableRepeatedExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, _field_type, \ - _is_packed>& id) { \ + MutableRepeatedExtension( \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \ return _proto_TypeTraits::MutableRepeated(id.number(), _field_type, \ _is_packed, &_extensions_); \ } } // namespace internal -} // namespace protobuf +// Call this function to ensure that this extensions's reflection is linked into +// the binary: +// +// google::protobuf::LinkExtensionReflection(Foo::my_extension); +// +// This will ensure that the following lookup will succeed: +// +// DescriptorPool::generated_pool()->FindExtensionByName("Foo.my_extension"); +// +// This is often relevant for parsing extensions in text mode. +// +// As a side-effect, it will also guarantee that anything else from the same +// .proto file will also be available for lookup in the generated pool. +// +// This function does not actually register the extension, so it does not need +// to be called before the lookup. However it does need to occur in a function +// that cannot be stripped from the binary (ie. it must be reachable from main). +// +// Best practice is to call this function as close as possible to where the +// reflection is actually needed. This function is very cheap to call, so you +// should not need to worry about its runtime overhead except in tight loops (on +// x86-64 it compiles into two "mov" instructions). +template +void LinkExtensionReflection( + const google::protobuf::internal::ExtensionIdentifier< + ExtendeeType, TypeTraitsType, field_type, is_packed>& extension) { + const void* volatile unused = &extension; + (void)&unused; // Use address to avoid an extra load of volatile variable. +} + +} // namespace protobuf } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_EXTENSION_SET_H__ diff --git a/third_party/protobuf/src/google/protobuf/extension_set_heavy.cc b/third_party/protobuf/src/google/protobuf/extension_set_heavy.cc index a3c84167..32ca4356 100644 --- a/third_party/protobuf/src/google/protobuf/extension_set_heavy.cc +++ b/third_party/protobuf/src/google/protobuf/extension_set_heavy.cc @@ -35,26 +35,30 @@ // Contains methods defined in extension_set.h which cannot be part of the // lite library because they use descriptors or reflection. +#include + #include #include +#include +#include #include #include #include -#include #include #include #include #include -#include +#include + + +#include namespace google { - namespace protobuf { namespace internal { // A FieldSkipper used to store unknown MessageSet fields into UnknownFieldSet. -class MessageSetFieldSkipper - : public UnknownFieldSetFieldSkipper { +class MessageSetFieldSkipper : public UnknownFieldSetFieldSkipper { public: explicit MessageSetFieldSkipper(UnknownFieldSet* unknown_fields) : UnknownFieldSetFieldSkipper(unknown_fields) {} @@ -63,15 +67,15 @@ class MessageSetFieldSkipper virtual bool SkipMessageSetField(io::CodedInputStream* input, int field_number); }; -bool MessageSetFieldSkipper::SkipMessageSetField( - io::CodedInputStream* input, int field_number) { +bool MessageSetFieldSkipper::SkipMessageSetField(io::CodedInputStream* input, + int field_number) { uint32 length; if (!input->ReadVarint32(&length)) return false; if (unknown_fields_ == NULL) { return input->Skip(length); } else { - return input->ReadString( - unknown_fields_->AddLengthDelimited(field_number), length); + return input->ReadString(unknown_fields_->AddLengthDelimited(field_number), + length); } } @@ -85,9 +89,9 @@ class DescriptorPoolExtensionFinder : public ExtensionFinder { MessageFactory* factory, const Descriptor* containing_type) : pool_(pool), factory_(factory), containing_type_(containing_type) {} - virtual ~DescriptorPoolExtensionFinder() {} + ~DescriptorPoolExtensionFinder() override {} - virtual bool Find(int number, ExtensionInfo* output); + bool Find(int number, ExtensionInfo* output) override; private: const DescriptorPool* pool_; @@ -136,10 +140,10 @@ inline WireFormatLite::FieldType field_type(FieldType type) { return static_cast(type); } -#define GOOGLE_DCHECK_TYPE(EXTENSION, LABEL, CPPTYPE) \ - GOOGLE_DCHECK_EQ((EXTENSION).is_repeated ? FieldDescriptor::LABEL_REPEATED \ - : FieldDescriptor::LABEL_OPTIONAL, \ - FieldDescriptor::LABEL_##LABEL); \ +#define GOOGLE_DCHECK_TYPE(EXTENSION, LABEL, CPPTYPE) \ + GOOGLE_DCHECK_EQ((EXTENSION).is_repeated ? FieldDescriptor::LABEL_REPEATED \ + : FieldDescriptor::LABEL_OPTIONAL, \ + FieldDescriptor::LABEL_##LABEL); \ GOOGLE_DCHECK_EQ(cpp_type((EXTENSION).type), FieldDescriptor::CPPTYPE_##CPPTYPE) const MessageLite& ExtensionSet::GetMessage(int number, @@ -237,14 +241,15 @@ MessageLite* ExtensionSet::UnsafeArenaReleaseMessage( } } -ExtensionSet::Extension* ExtensionSet::MaybeNewRepeatedExtension(const FieldDescriptor* descriptor) { +ExtensionSet::Extension* ExtensionSet::MaybeNewRepeatedExtension( + const FieldDescriptor* descriptor) { Extension* extension; if (MaybeNewExtension(descriptor->number(), descriptor, &extension)) { extension->type = descriptor->type(); GOOGLE_DCHECK_EQ(cpp_type(extension->type), FieldDescriptor::CPPTYPE_MESSAGE); extension->is_repeated = true; extension->repeated_message_value = - ::google::protobuf::Arena::CreateMessage >(arena_); + Arena::CreateMessage >(arena_); } else { GOOGLE_DCHECK_TYPE(*extension, REPEATED, MESSAGE); } @@ -258,7 +263,7 @@ MessageLite* ExtensionSet::AddMessage(const FieldDescriptor* descriptor, // RepeatedPtrField does not know how to Add() since it cannot // allocate an abstract object, so we have to be tricky. MessageLite* result = - reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( + reinterpret_cast( extension->repeated_message_value) ->AddFromCleared >(); if (result == NULL) { @@ -283,8 +288,8 @@ void ExtensionSet::AddAllocatedMessage(const FieldDescriptor* descriptor, } static bool ValidateEnumUsingDescriptor(const void* arg, int number) { - return reinterpret_cast(arg) - ->FindValueByNumber(number) != NULL; + return reinterpret_cast(arg)->FindValueByNumber( + number) != NULL; } bool DescriptorPoolExtensionFinder::Find(int number, ExtensionInfo* output) { @@ -298,9 +303,9 @@ bool DescriptorPoolExtensionFinder::Find(int number, ExtensionInfo* output) { output->is_packed = extension->options().packed(); output->descriptor = extension; if (extension->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - output->message_prototype = + output->message_info.prototype = factory_->GetPrototype(extension->message_type()); - GOOGLE_CHECK(output->message_prototype != NULL) + GOOGLE_CHECK(output->message_info.prototype != nullptr) << "Extension factory's GetPrototype() returned NULL for extension: " << extension->full_name(); } else if (extension->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { @@ -312,6 +317,61 @@ bool DescriptorPoolExtensionFinder::Find(int number, ExtensionInfo* output) { } } + +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +bool ExtensionSet::FindExtension(int wire_type, uint32 field, + const Message* containing_type, + const internal::ParseContext* ctx, + ExtensionInfo* extension, + bool* was_packed_on_wire) { + if (ctx->data().pool == nullptr) { + GeneratedExtensionFinder finder(containing_type); + if (!FindExtensionInfoFromFieldNumber(wire_type, field, &finder, extension, + was_packed_on_wire)) { + return false; + } + } else { + DescriptorPoolExtensionFinder finder(ctx->data().pool, ctx->data().factory, + containing_type->GetDescriptor()); + if (!FindExtensionInfoFromFieldNumber(wire_type, field, &finder, extension, + was_packed_on_wire)) { + return false; + } + } + return true; +} + +const char* ExtensionSet::ParseField( + uint64 tag, const char* ptr, const Message* containing_type, + internal::InternalMetadataWithArena* metadata, + internal::ParseContext* ctx) { + int number = tag >> 3; + bool was_packed_on_wire; + ExtensionInfo extension; + if (!FindExtension(tag & 7, number, containing_type, ctx, &extension, + &was_packed_on_wire)) { + return UnknownFieldParse(tag, metadata->mutable_unknown_fields(), ptr, ctx); + } + return ParseFieldWithExtensionInfo(number, was_packed_on_wire, extension, + metadata, ptr, ctx); +} + +const char* ExtensionSet::ParseFieldMaybeLazily( + uint64 tag, const char* ptr, const Message* containing_type, + internal::InternalMetadataWithArena* metadata, + internal::ParseContext* ctx) { + return ParseField(tag, ptr, containing_type, metadata, ctx); +} + +const char* ExtensionSet::ParseMessageSetItem( + const char* ptr, const Message* containing_type, + internal::InternalMetadataWithArena* metadata, + internal::ParseContext* ctx) { + return ParseMessageSetItemTmpl(ptr, containing_type, metadata, ctx); +} + +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input, const Message* containing_type, UnknownFieldSet* unknown_fields) { @@ -369,15 +429,15 @@ size_t ExtensionSet::Extension::SpaceUsedExcludingSelfLong() const { repeated_##LOWERCASE##_value->SpaceUsedExcludingSelfLong(); \ break - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); - HANDLE_TYPE( UINT32, uint32); - HANDLE_TYPE( UINT64, uint64); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( DOUBLE, double); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, enum); - HANDLE_TYPE( STRING, string); + HANDLE_TYPE(INT32, int32); + HANDLE_TYPE(INT64, int64); + HANDLE_TYPE(UINT32, uint32); + HANDLE_TYPE(UINT64, uint64); + HANDLE_TYPE(FLOAT, float); + HANDLE_TYPE(DOUBLE, double); + HANDLE_TYPE(BOOL, bool); + HANDLE_TYPE(ENUM, enum); + HANDLE_TYPE(STRING, string); #undef HANDLE_TYPE case FieldDescriptor::CPPTYPE_MESSAGE: @@ -385,11 +445,10 @@ size_t ExtensionSet::Extension::SpaceUsedExcludingSelfLong() const { // but MessageLite has no SpaceUsedLong(), so we must directly call // RepeatedPtrFieldBase::SpaceUsedExcludingSelfLong() with a different // type handler. - total_size += - sizeof(*repeated_message_value) + - RepeatedMessage_SpaceUsedExcludingSelfLong( - reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( - repeated_message_value)); + total_size += sizeof(*repeated_message_value) + + RepeatedMessage_SpaceUsedExcludingSelfLong( + reinterpret_cast( + repeated_message_value)); break; } } else { @@ -418,28 +477,23 @@ size_t ExtensionSet::Extension::SpaceUsedExcludingSelfLong() const { uint8* ExtensionSet::SerializeWithCachedSizesToArray(int start_field_number, int end_field_number, uint8* target) const { - return InternalSerializeWithCachedSizesToArray( - start_field_number, end_field_number, - google::protobuf::io::CodedOutputStream::IsDefaultSerializationDeterministic(), - target); + return InternalSerializeWithCachedSizesToArray(start_field_number, + end_field_number, target); } uint8* ExtensionSet::SerializeMessageSetWithCachedSizesToArray( uint8* target) const { - return InternalSerializeMessageSetWithCachedSizesToArray( - google::protobuf::io::CodedOutputStream::IsDefaultSerializationDeterministic(), - target); + return InternalSerializeMessageSetWithCachedSizesToArray(target); } uint8* ExtensionSet::InternalSerializeWithCachedSizesToArray( - int start_field_number, int end_field_number, bool deterministic, - uint8* target) const { - if (GOOGLE_PREDICT_FALSE(is_large())) { + int start_field_number, int end_field_number, uint8* target) const { + if (PROTOBUF_PREDICT_FALSE(is_large())) { const auto& end = map_.large->end(); for (auto it = map_.large->lower_bound(start_field_number); it != end && it->first < end_field_number; ++it) { target = it->second.InternalSerializeFieldWithCachedSizesToArray( - it->first, deterministic, target); + it->first, target); } return target; } @@ -447,54 +501,54 @@ uint8* ExtensionSet::InternalSerializeWithCachedSizesToArray( for (const KeyValue* it = std::lower_bound( flat_begin(), end, start_field_number, KeyValue::FirstComparator()); it != end && it->first < end_field_number; ++it) { - target = it->second.InternalSerializeFieldWithCachedSizesToArray( - it->first, deterministic, target); + target = it->second.InternalSerializeFieldWithCachedSizesToArray(it->first, + target); } return target; } uint8* ExtensionSet::InternalSerializeMessageSetWithCachedSizesToArray( - bool deterministic, uint8* target) const { - ForEach([deterministic, &target](int number, const Extension& ext) { - target = ext.InternalSerializeMessageSetItemWithCachedSizesToArray( - number, deterministic, target); + uint8* target) const { + ForEach([&target](int number, const Extension& ext) { + target = ext.InternalSerializeMessageSetItemWithCachedSizesToArray(number, + target); }); return target; } uint8* ExtensionSet::Extension::InternalSerializeFieldWithCachedSizesToArray( - int number, bool deterministic, uint8* target) const { + int number, uint8* target) const { if (is_repeated) { if (is_packed) { if (cached_size == 0) return target; - target = WireFormatLite::WriteTagToArray(number, - WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); + target = WireFormatLite::WriteTagToArray( + number, WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = WireFormatLite::WriteInt32NoTagToArray(cached_size, target); switch (real_type(type)) { -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case FieldDescriptor::TYPE_##UPPERCASE: \ - for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ - target = WireFormatLite::Write##CAMELCASE##NoTagToArray( \ - repeated_##LOWERCASE##_value->Get(i), target); \ - } \ - break +#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ + case FieldDescriptor::TYPE_##UPPERCASE: \ + for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ + target = WireFormatLite::Write##CAMELCASE##NoTagToArray( \ + repeated_##LOWERCASE##_value->Get(i), target); \ + } \ + break - HANDLE_TYPE( INT32, Int32, int32); - HANDLE_TYPE( INT64, Int64, int64); - HANDLE_TYPE( UINT32, UInt32, uint32); - HANDLE_TYPE( UINT64, UInt64, uint64); - HANDLE_TYPE( SINT32, SInt32, int32); - HANDLE_TYPE( SINT64, SInt64, int64); - HANDLE_TYPE( FIXED32, Fixed32, uint32); - HANDLE_TYPE( FIXED64, Fixed64, uint64); - HANDLE_TYPE(SFIXED32, SFixed32, int32); - HANDLE_TYPE(SFIXED64, SFixed64, int64); - HANDLE_TYPE( FLOAT, Float, float); - HANDLE_TYPE( DOUBLE, Double, double); - HANDLE_TYPE( BOOL, Bool, bool); - HANDLE_TYPE( ENUM, Enum, enum); + HANDLE_TYPE(INT32, Int32, int32); + HANDLE_TYPE(INT64, Int64, int64); + HANDLE_TYPE(UINT32, UInt32, uint32); + HANDLE_TYPE(UINT64, UInt64, uint64); + HANDLE_TYPE(SINT32, SInt32, int32); + HANDLE_TYPE(SINT64, SInt64, int64); + HANDLE_TYPE(FIXED32, Fixed32, uint32); + HANDLE_TYPE(FIXED64, Fixed64, uint64); + HANDLE_TYPE(SFIXED32, SFixed32, int32); + HANDLE_TYPE(SFIXED64, SFixed64, int64); + HANDLE_TYPE(FLOAT, Float, float); + HANDLE_TYPE(DOUBLE, Double, double); + HANDLE_TYPE(BOOL, Bool, bool); + HANDLE_TYPE(ENUM, Enum, enum); #undef HANDLE_TYPE case FieldDescriptor::TYPE_STRING: @@ -506,78 +560,75 @@ uint8* ExtensionSet::Extension::InternalSerializeFieldWithCachedSizesToArray( } } else { switch (real_type(type)) { -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case FieldDescriptor::TYPE_##UPPERCASE: \ - for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ - target = WireFormatLite::Write##CAMELCASE##ToArray(number, \ - repeated_##LOWERCASE##_value->Get(i), target); \ - } \ - break +#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ + case FieldDescriptor::TYPE_##UPPERCASE: \ + for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ + target = WireFormatLite::Write##CAMELCASE##ToArray( \ + number, repeated_##LOWERCASE##_value->Get(i), target); \ + } \ + break - HANDLE_TYPE( INT32, Int32, int32); - HANDLE_TYPE( INT64, Int64, int64); - HANDLE_TYPE( UINT32, UInt32, uint32); - HANDLE_TYPE( UINT64, UInt64, uint64); - HANDLE_TYPE( SINT32, SInt32, int32); - HANDLE_TYPE( SINT64, SInt64, int64); - HANDLE_TYPE( FIXED32, Fixed32, uint32); - HANDLE_TYPE( FIXED64, Fixed64, uint64); - HANDLE_TYPE(SFIXED32, SFixed32, int32); - HANDLE_TYPE(SFIXED64, SFixed64, int64); - HANDLE_TYPE( FLOAT, Float, float); - HANDLE_TYPE( DOUBLE, Double, double); - HANDLE_TYPE( BOOL, Bool, bool); - HANDLE_TYPE( STRING, String, string); - HANDLE_TYPE( BYTES, Bytes, string); - HANDLE_TYPE( ENUM, Enum, enum); + HANDLE_TYPE(INT32, Int32, int32); + HANDLE_TYPE(INT64, Int64, int64); + HANDLE_TYPE(UINT32, UInt32, uint32); + HANDLE_TYPE(UINT64, UInt64, uint64); + HANDLE_TYPE(SINT32, SInt32, int32); + HANDLE_TYPE(SINT64, SInt64, int64); + HANDLE_TYPE(FIXED32, Fixed32, uint32); + HANDLE_TYPE(FIXED64, Fixed64, uint64); + HANDLE_TYPE(SFIXED32, SFixed32, int32); + HANDLE_TYPE(SFIXED64, SFixed64, int64); + HANDLE_TYPE(FLOAT, Float, float); + HANDLE_TYPE(DOUBLE, Double, double); + HANDLE_TYPE(BOOL, Bool, bool); + HANDLE_TYPE(STRING, String, string); + HANDLE_TYPE(BYTES, Bytes, string); + HANDLE_TYPE(ENUM, Enum, enum); #undef HANDLE_TYPE -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case FieldDescriptor::TYPE_##UPPERCASE: \ - for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ - target = WireFormatLite::InternalWrite##CAMELCASE##ToArray( \ - number, repeated_##LOWERCASE##_value->Get(i), \ - deterministic, target); \ - } \ - break +#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ + case FieldDescriptor::TYPE_##UPPERCASE: \ + for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ + target = WireFormatLite::InternalWrite##CAMELCASE##ToArray( \ + number, repeated_##LOWERCASE##_value->Get(i), target); \ + } \ + break - HANDLE_TYPE( GROUP, Group, message); - HANDLE_TYPE( MESSAGE, Message, message); + HANDLE_TYPE(GROUP, Group, message); + HANDLE_TYPE(MESSAGE, Message, message); #undef HANDLE_TYPE } } } else if (!is_cleared) { switch (real_type(type)) { -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, VALUE) \ - case FieldDescriptor::TYPE_##UPPERCASE: \ - target = WireFormatLite::Write##CAMELCASE##ToArray( \ - number, VALUE, target); \ - break +#define HANDLE_TYPE(UPPERCASE, CAMELCASE, VALUE) \ + case FieldDescriptor::TYPE_##UPPERCASE: \ + target = WireFormatLite::Write##CAMELCASE##ToArray(number, VALUE, target); \ + break - HANDLE_TYPE( INT32, Int32, int32_value); - HANDLE_TYPE( INT64, Int64, int64_value); - HANDLE_TYPE( UINT32, UInt32, uint32_value); - HANDLE_TYPE( UINT64, UInt64, uint64_value); - HANDLE_TYPE( SINT32, SInt32, int32_value); - HANDLE_TYPE( SINT64, SInt64, int64_value); - HANDLE_TYPE( FIXED32, Fixed32, uint32_value); - HANDLE_TYPE( FIXED64, Fixed64, uint64_value); - HANDLE_TYPE(SFIXED32, SFixed32, int32_value); - HANDLE_TYPE(SFIXED64, SFixed64, int64_value); - HANDLE_TYPE( FLOAT, Float, float_value); - HANDLE_TYPE( DOUBLE, Double, double_value); - HANDLE_TYPE( BOOL, Bool, bool_value); - HANDLE_TYPE( STRING, String, *string_value); - HANDLE_TYPE( BYTES, Bytes, *string_value); - HANDLE_TYPE( ENUM, Enum, enum_value); - HANDLE_TYPE( GROUP, Group, *message_value); + HANDLE_TYPE(INT32, Int32, int32_value); + HANDLE_TYPE(INT64, Int64, int64_value); + HANDLE_TYPE(UINT32, UInt32, uint32_value); + HANDLE_TYPE(UINT64, UInt64, uint64_value); + HANDLE_TYPE(SINT32, SInt32, int32_value); + HANDLE_TYPE(SINT64, SInt64, int64_value); + HANDLE_TYPE(FIXED32, Fixed32, uint32_value); + HANDLE_TYPE(FIXED64, Fixed64, uint64_value); + HANDLE_TYPE(SFIXED32, SFixed32, int32_value); + HANDLE_TYPE(SFIXED64, SFixed64, int64_value); + HANDLE_TYPE(FLOAT, Float, float_value); + HANDLE_TYPE(DOUBLE, Double, double_value); + HANDLE_TYPE(BOOL, Bool, bool_value); + HANDLE_TYPE(STRING, String, *string_value); + HANDLE_TYPE(BYTES, Bytes, *string_value); + HANDLE_TYPE(ENUM, Enum, enum_value); + HANDLE_TYPE(GROUP, Group, *message_value); #undef HANDLE_TYPE case FieldDescriptor::TYPE_MESSAGE: if (is_lazy) { - target = lazymessage_value->InternalWriteMessageToArray( - number, deterministic, target); + target = lazymessage_value->WriteMessageToArray(number, target); } else { target = WireFormatLite::InternalWriteMessageToArray( - number, *message_value, deterministic, target); + number, *message_value, target); } break; } @@ -587,12 +638,11 @@ uint8* ExtensionSet::Extension::InternalSerializeFieldWithCachedSizesToArray( uint8* ExtensionSet::Extension::InternalSerializeMessageSetItemWithCachedSizesToArray( - int number, bool deterministic, uint8* target) const { + int number, uint8* target) const { if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) { // Not a valid MessageSet extension, but serialize it the normal way. GOOGLE_LOG(WARNING) << "Invalid message set extension."; - return InternalSerializeFieldWithCachedSizesToArray(number, deterministic, - target); + return InternalSerializeFieldWithCachedSizesToArray(number, target); } if (is_cleared) return target; @@ -605,12 +655,11 @@ ExtensionSet::Extension::InternalSerializeMessageSetItemWithCachedSizesToArray( WireFormatLite::kMessageSetTypeIdNumber, number, target); // Write message. if (is_lazy) { - target = lazymessage_value->InternalWriteMessageToArray( - WireFormatLite::kMessageSetMessageNumber, deterministic, target); + target = lazymessage_value->WriteMessageToArray( + WireFormatLite::kMessageSetMessageNumber, target); } else { target = WireFormatLite::InternalWriteMessageToArray( - WireFormatLite::kMessageSetMessageNumber, *message_value, deterministic, - target); + WireFormatLite::kMessageSetMessageNumber, *message_value, target); } // End group. target = io::CodedOutputStream::WriteTagToArray( @@ -618,14 +667,13 @@ ExtensionSet::Extension::InternalSerializeMessageSetItemWithCachedSizesToArray( return target; } - bool ExtensionSet::ParseFieldMaybeLazily( int wire_type, int field_number, io::CodedInputStream* input, - ExtensionFinder* extension_finder, - MessageSetFieldSkipper* field_skipper) { - return ParseField(WireFormatLite::MakeTag( - field_number, static_cast(wire_type)), - input, extension_finder, field_skipper); + ExtensionFinder* extension_finder, MessageSetFieldSkipper* field_skipper) { + return ParseField( + WireFormatLite::MakeTag(field_number, + static_cast(wire_type)), + input, extension_finder, field_skipper); } bool ExtensionSet::ParseMessageSet(io::CodedInputStream* input, @@ -650,165 +698,27 @@ bool ExtensionSet::ParseMessageSet(io::CodedInputStream* input, } } -bool ExtensionSet::ParseMessageSet(io::CodedInputStream* input, - const MessageLite* containing_type) { - MessageSetFieldSkipper skipper(NULL); - GeneratedExtensionFinder finder(containing_type); - return ParseMessageSet(input, &finder, &skipper); -} - bool ExtensionSet::ParseMessageSetItem(io::CodedInputStream* input, ExtensionFinder* extension_finder, MessageSetFieldSkipper* field_skipper) { - // TODO(kenton): It would be nice to share code between this and - // WireFormatLite::ParseAndMergeMessageSetItem(), but I think the - // differences would be hard to factor out. - - // This method parses a group which should contain two fields: - // required int32 type_id = 2; - // required data message = 3; - - uint32 last_type_id = 0; - - // If we see message data before the type_id, we'll append it to this so - // we can parse it later. - string message_data; - - while (true) { - const uint32 tag = input->ReadTagNoLastTag(); - if (tag == 0) return false; - - switch (tag) { - case WireFormatLite::kMessageSetTypeIdTag: { - uint32 type_id; - if (!input->ReadVarint32(&type_id)) return false; - last_type_id = type_id; - - if (!message_data.empty()) { - // We saw some message data before the type_id. Have to parse it - // now. - io::CodedInputStream sub_input( - reinterpret_cast(message_data.data()), - message_data.size()); - if (!ParseFieldMaybeLazily(WireFormatLite::WIRETYPE_LENGTH_DELIMITED, - last_type_id, &sub_input, - extension_finder, field_skipper)) { - return false; - } - message_data.clear(); - } - - break; - } - - case WireFormatLite::kMessageSetMessageTag: { - if (last_type_id == 0) { - // We haven't seen a type_id yet. Append this data to message_data. - string temp; - uint32 length; - if (!input->ReadVarint32(&length)) return false; - if (!input->ReadString(&temp, length)) return false; - io::StringOutputStream output_stream(&message_data); - io::CodedOutputStream coded_output(&output_stream); - coded_output.WriteVarint32(length); - coded_output.WriteString(temp); - } else { - // Already saw type_id, so we can parse this directly. - if (!ParseFieldMaybeLazily(WireFormatLite::WIRETYPE_LENGTH_DELIMITED, - last_type_id, input, - extension_finder, field_skipper)) { - return false; - } - } - - break; - } - - case WireFormatLite::kMessageSetItemEndTag: { - return true; - } - - default: { - if (!field_skipper->SkipField(input, tag)) return false; - } + struct MSFull { + bool ParseField(int type_id, io::CodedInputStream* input) { + return me->ParseFieldMaybeLazily( + WireFormatLite::WIRETYPE_LENGTH_DELIMITED, type_id, input, + extension_finder, field_skipper); } - } -} -void ExtensionSet::Extension::SerializeMessageSetItemWithCachedSizes( - int number, - io::CodedOutputStream* output) const { - if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) { - // Not a valid MessageSet extension, but serialize it the normal way. - SerializeFieldWithCachedSizes(number, output); - return; - } + bool SkipField(uint32 tag, io::CodedInputStream* input) { + return field_skipper->SkipField(input, tag); + } - if (is_cleared) return; + ExtensionSet* me; + ExtensionFinder* extension_finder; + MessageSetFieldSkipper* field_skipper; + }; - // Start group. - output->WriteTag(WireFormatLite::kMessageSetItemStartTag); - - // Write type ID. - WireFormatLite::WriteUInt32(WireFormatLite::kMessageSetTypeIdNumber, - number, - output); - // Write message. - if (is_lazy) { - lazymessage_value->WriteMessage( - WireFormatLite::kMessageSetMessageNumber, output); - } else { - WireFormatLite::WriteMessageMaybeToArray( - WireFormatLite::kMessageSetMessageNumber, - *message_value, - output); - } - - // End group. - output->WriteTag(WireFormatLite::kMessageSetItemEndTag); -} - -size_t ExtensionSet::Extension::MessageSetItemByteSize(int number) const { - if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) { - // Not a valid MessageSet extension, but compute the byte size for it the - // normal way. - return ByteSize(number); - } - - if (is_cleared) return 0; - - size_t our_size = WireFormatLite::kMessageSetItemTagsSize; - - // type_id - our_size += io::CodedOutputStream::VarintSize32(number); - - // message - size_t message_size = 0; - if (is_lazy) { - message_size = lazymessage_value->ByteSizeLong(); - } else { - message_size = message_value->ByteSizeLong(); - } - - our_size += io::CodedOutputStream::VarintSize32(message_size); - our_size += message_size; - - return our_size; -} - -void ExtensionSet::SerializeMessageSetWithCachedSizes( - io::CodedOutputStream* output) const { - ForEach([output](int number, const Extension& ext) { - ext.SerializeMessageSetItemWithCachedSizes(number, output); - }); -} - -size_t ExtensionSet::MessageSetByteSize() const { - size_t total_size = 0; - ForEach([&total_size](int number, const Extension& ext) { - total_size += ext.MessageSetItemByteSize(number); - }); - return total_size; + return ParseMessageSetItemImpl(input, + MSFull{this, extension_finder, field_skipper}); } } // namespace internal diff --git a/third_party/protobuf/src/google/protobuf/extension_set_inl.h b/third_party/protobuf/src/google/protobuf/extension_set_inl.h new file mode 100644 index 00000000..4e6995ef --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/extension_set_inl.h @@ -0,0 +1,284 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#ifndef GOOGLE_PROTOBUF_EXTENSION_SET_INL_H__ +#define GOOGLE_PROTOBUF_EXTENSION_SET_INL_H__ + +#include +#include + +namespace google { +namespace protobuf { +namespace internal { + +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +template +const char* ExtensionSet::ParseFieldWithExtensionInfo( + int number, bool was_packed_on_wire, const ExtensionInfo& extension, + T* metadata, const char* ptr, internal::ParseContext* ctx) { + if (was_packed_on_wire) { + switch (extension.type) { +#define HANDLE_TYPE(UPPERCASE, CPP_CAMELCASE) \ + case WireFormatLite::TYPE_##UPPERCASE: \ + return internal::Packed##CPP_CAMELCASE##Parser( \ + MutableRawRepeatedField(number, extension.type, extension.is_packed, \ + extension.descriptor), \ + ptr, ctx); + HANDLE_TYPE(INT32, Int32); + HANDLE_TYPE(INT64, Int64); + HANDLE_TYPE(UINT32, UInt32); + HANDLE_TYPE(UINT64, UInt64); + HANDLE_TYPE(SINT32, SInt32); + HANDLE_TYPE(SINT64, SInt64); + HANDLE_TYPE(FIXED32, Fixed32); + HANDLE_TYPE(FIXED64, Fixed64); + HANDLE_TYPE(SFIXED32, SFixed32); + HANDLE_TYPE(SFIXED64, SFixed64); + HANDLE_TYPE(FLOAT, Float); + HANDLE_TYPE(DOUBLE, Double); + HANDLE_TYPE(BOOL, Bool); +#undef HANDLE_TYPE + + case WireFormatLite::TYPE_ENUM: + return internal::PackedEnumParserArg( + MutableRawRepeatedField(number, extension.type, extension.is_packed, + extension.descriptor), + ptr, ctx, extension.enum_validity_check.func, + extension.enum_validity_check.arg, + metadata->mutable_unknown_fields(), number); + case WireFormatLite::TYPE_STRING: + case WireFormatLite::TYPE_BYTES: + case WireFormatLite::TYPE_GROUP: + case WireFormatLite::TYPE_MESSAGE: + GOOGLE_LOG(FATAL) << "Non-primitive types can't be packed."; + break; + } + } else { + switch (extension.type) { +#define HANDLE_VARINT_TYPE(UPPERCASE, CPP_CAMELCASE) \ + case WireFormatLite::TYPE_##UPPERCASE: { \ + uint64 value; \ + ptr = ParseVarint64(ptr, &value); \ + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); \ + if (extension.is_repeated) { \ + Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \ + extension.is_packed, value, extension.descriptor); \ + } else { \ + Set##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, value, \ + extension.descriptor); \ + } \ + } break + + HANDLE_VARINT_TYPE(INT32, Int32); + HANDLE_VARINT_TYPE(INT64, Int64); + HANDLE_VARINT_TYPE(UINT32, UInt32); + HANDLE_VARINT_TYPE(UINT64, UInt64); +#undef HANDLE_VARINT_TYPE +#define HANDLE_SVARINT_TYPE(UPPERCASE, CPP_CAMELCASE, SIZE) \ + case WireFormatLite::TYPE_##UPPERCASE: { \ + uint64 val; \ + ptr = ParseVarint64(ptr, &val); \ + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); \ + auto value = WireFormatLite::ZigZagDecode##SIZE(val); \ + if (extension.is_repeated) { \ + Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \ + extension.is_packed, value, extension.descriptor); \ + } else { \ + Set##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, value, \ + extension.descriptor); \ + } \ + } break + + HANDLE_SVARINT_TYPE(SINT32, Int32, 32); + HANDLE_SVARINT_TYPE(SINT64, Int64, 64); +#undef HANDLE_SVARINT_TYPE +#define HANDLE_FIXED_TYPE(UPPERCASE, CPP_CAMELCASE, CPPTYPE) \ + case WireFormatLite::TYPE_##UPPERCASE: { \ + CPPTYPE value; \ + std::memcpy(&value, ptr, sizeof(CPPTYPE)); \ + ptr += sizeof(CPPTYPE); \ + if (extension.is_repeated) { \ + Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \ + extension.is_packed, value, extension.descriptor); \ + } else { \ + Set##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, value, \ + extension.descriptor); \ + } \ + } break + + HANDLE_FIXED_TYPE(FIXED32, UInt32, uint32); + HANDLE_FIXED_TYPE(FIXED64, UInt64, uint64); + HANDLE_FIXED_TYPE(SFIXED32, Int32, int32); + HANDLE_FIXED_TYPE(SFIXED64, Int64, int64); + HANDLE_FIXED_TYPE(FLOAT, Float, float); + HANDLE_FIXED_TYPE(DOUBLE, Double, double); + HANDLE_FIXED_TYPE(BOOL, Bool, bool); +#undef HANDLE_FIXED_TYPE + + case WireFormatLite::TYPE_ENUM: { + uint64 val; + ptr = ParseVarint64(ptr, &val); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + int value = val; + + if (!extension.enum_validity_check.func( + extension.enum_validity_check.arg, value)) { + WriteVarint(number, val, metadata->mutable_unknown_fields()); + } else if (extension.is_repeated) { + AddEnum(number, WireFormatLite::TYPE_ENUM, extension.is_packed, value, + extension.descriptor); + } else { + SetEnum(number, WireFormatLite::TYPE_ENUM, value, + extension.descriptor); + } + break; + } + + case WireFormatLite::TYPE_BYTES: + case WireFormatLite::TYPE_STRING: { + std::string* value = + extension.is_repeated + ? AddString(number, WireFormatLite::TYPE_STRING, + extension.descriptor) + : MutableString(number, WireFormatLite::TYPE_STRING, + extension.descriptor); + int size = ReadSize(&ptr); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + return ctx->ReadString(ptr, size, value); + } + + case WireFormatLite::TYPE_GROUP: { + MessageLite* value = + extension.is_repeated + ? AddMessage(number, WireFormatLite::TYPE_GROUP, + *extension.message_info.prototype, + extension.descriptor) + : MutableMessage(number, WireFormatLite::TYPE_GROUP, + *extension.message_info.prototype, + extension.descriptor); + uint32 tag = (number << 3) + WireFormatLite::WIRETYPE_START_GROUP; + return ctx->ParseGroup(value, ptr, tag); + } + + case WireFormatLite::TYPE_MESSAGE: { + MessageLite* value = + extension.is_repeated + ? AddMessage(number, WireFormatLite::TYPE_MESSAGE, + *extension.message_info.prototype, + extension.descriptor) + : MutableMessage(number, WireFormatLite::TYPE_MESSAGE, + *extension.message_info.prototype, + extension.descriptor); + return ctx->ParseMessage(value, ptr); + } + } + } + return ptr; +} + +template +const char* ExtensionSet::ParseMessageSetItemTmpl(const char* ptr, + const Msg* containing_type, + Metadata* metadata, + internal::ParseContext* ctx) { + std::string payload; + uint32 type_id = 0; + while (!ctx->Done(&ptr)) { + uint32 tag = static_cast(*ptr++); + if (tag == WireFormatLite::kMessageSetTypeIdTag) { + uint64 tmp; + ptr = ParseVarint64Inline(ptr, &tmp); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + type_id = tmp; + if (!payload.empty()) { + ExtensionInfo extension; + bool was_packed_on_wire; + if (!FindExtension(2, type_id, containing_type, ctx, &extension, + &was_packed_on_wire)) { + WriteLengthDelimited(type_id, payload, + metadata->mutable_unknown_fields()); + } else { + MessageLite* value = + extension.is_repeated + ? AddMessage(type_id, WireFormatLite::TYPE_MESSAGE, + *extension.message_info.prototype, + extension.descriptor) + : MutableMessage(type_id, WireFormatLite::TYPE_MESSAGE, + *extension.message_info.prototype, + extension.descriptor); + + const char* p; + // We can't use regular parse from string as we have to track + // proper recursion depth and descriptor pools. + ParseContext tmp_ctx(ctx->depth(), false, &p, payload); + tmp_ctx.data().pool = ctx->data().pool; + tmp_ctx.data().factory = ctx->data().factory; + GOOGLE_PROTOBUF_PARSER_ASSERT(value->_InternalParse(p, &tmp_ctx) && + tmp_ctx.EndedAtLimit()); + } + type_id = 0; + } + } else if (tag == WireFormatLite::kMessageSetMessageTag) { + if (type_id != 0) { + ptr = ParseFieldMaybeLazily(static_cast(type_id) * 8 + 2, ptr, + containing_type, metadata, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); + type_id = 0; + } else { + int32 size = ReadSize(&ptr); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + ptr = ctx->ReadString(ptr, size, &payload); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + } + } else { + if (tag >= 128) { + // Parse remainder of tag varint + uint32 tmp; + ptr = VarintParse<4>(ptr, &tmp); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + tag += (tmp - 1) << 7; + } + if (tag == 0 || (tag & 7) == 4) { + ctx->SetLastTag(tag); + return ptr; + } + ptr = ParseField(tag, ptr, containing_type, metadata, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + } + } + return ptr; +} +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + +} // namespace internal +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_EXTENSION_SET_INL_H__ diff --git a/third_party/protobuf/src/google/protobuf/extension_set_unittest.cc b/third_party/protobuf/src/google/protobuf/extension_set_unittest.cc index bc65d295..6dd6f7d8 100644 --- a/third_party/protobuf/src/google/protobuf/extension_set_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/extension_set_unittest.cc @@ -36,6 +36,7 @@ #include #include +#include #include #include #include @@ -53,13 +54,15 @@ #include #include -namespace google { +namespace google { namespace protobuf { namespace internal { namespace { -// This test closely mirrors google/protobuf/compiler/cpp/unittest.cc +using TestUtil::EqualsToSerialized; + +// This test closely mirrors net/proto2/compiler/cpp/internal/unittest.cc // except that it uses extensions rather than regular fields. TEST(ExtensionSetTest, Defaults) { @@ -75,9 +78,9 @@ TEST(ExtensionSetTest, Defaults) { &message.GetExtension(unittest::optionalgroup_extension)); EXPECT_EQ(&unittest::TestAllTypes::NestedMessage::default_instance(), &message.GetExtension(unittest::optional_nested_message_extension)); - EXPECT_EQ(&unittest::ForeignMessage::default_instance(), - &message.GetExtension( - unittest::optional_foreign_message_extension)); + EXPECT_EQ( + &unittest::ForeignMessage::default_instance(), + &message.GetExtension(unittest::optional_foreign_message_extension)); EXPECT_EQ(&unittest_import::ImportMessage::default_instance(), &message.GetExtension(unittest::optional_import_message_extension)); } @@ -111,9 +114,9 @@ TEST(ExtensionSetTest, Clear) { &message.GetExtension(unittest::optionalgroup_extension)); EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(), &message.GetExtension(unittest::optional_nested_message_extension)); - EXPECT_NE(&unittest::ForeignMessage::default_instance(), - &message.GetExtension( - unittest::optional_foreign_message_extension)); + EXPECT_NE( + &unittest::ForeignMessage::default_instance(), + &message.GetExtension(unittest::optional_foreign_message_extension)); EXPECT_NE(&unittest_import::ImportMessage::default_instance(), &message.GetExtension(unittest::optional_import_message_extension)); @@ -130,7 +133,7 @@ TEST(ExtensionSetTest, ClearOneField) { TestUtil::SetAllExtensions(&message); int64 original_value = - message.GetExtension(unittest::optional_int64_extension); + message.GetExtension(unittest::optional_int64_extension); // Clear the field and make sure it shows up as cleared. message.ClearExtension(unittest::optional_int64_extension); @@ -148,20 +151,18 @@ TEST(ExtensionSetTest, ClearOneField) { TEST(ExtensionSetTest, SetAllocatedExtension) { unittest::TestAllExtensions message; - EXPECT_FALSE(message.HasExtension( - unittest::optional_foreign_message_extension)); + EXPECT_FALSE( + message.HasExtension(unittest::optional_foreign_message_extension)); // Add a extension using SetAllocatedExtension unittest::ForeignMessage* foreign_message = new unittest::ForeignMessage(); message.SetAllocatedExtension(unittest::optional_foreign_message_extension, foreign_message); - EXPECT_TRUE(message.HasExtension( - unittest::optional_foreign_message_extension)); - EXPECT_EQ(foreign_message, - message.MutableExtension( - unittest::optional_foreign_message_extension)); - EXPECT_EQ(foreign_message, - &message.GetExtension( - unittest::optional_foreign_message_extension)); + EXPECT_TRUE( + message.HasExtension(unittest::optional_foreign_message_extension)); + EXPECT_EQ(foreign_message, message.MutableExtension( + unittest::optional_foreign_message_extension)); + EXPECT_EQ(foreign_message, &message.GetExtension( + unittest::optional_foreign_message_extension)); // SetAllocatedExtension should delete the previously existing extension. // (We reply on unittest to check memory leaks for this case) @@ -171,8 +172,8 @@ TEST(ExtensionSetTest, SetAllocatedExtension) { // SetAllocatedExtension with a NULL parameter is equivalent to ClearExtenion. message.SetAllocatedExtension(unittest::optional_foreign_message_extension, NULL); - EXPECT_FALSE(message.HasExtension( - unittest::optional_foreign_message_extension)); + EXPECT_FALSE( + message.HasExtension(unittest::optional_foreign_message_extension)); } TEST(ExtensionSetTest, ReleaseExtension) { @@ -183,8 +184,7 @@ TEST(ExtensionSetTest, ReleaseExtension) { unittest::TestMessageSetExtension1* extension = new unittest::TestMessageSetExtension1(); message.SetAllocatedExtension( - unittest::TestMessageSetExtension1::message_set_extension, - extension); + unittest::TestMessageSetExtension1::message_set_extension, extension); EXPECT_TRUE(message.HasExtension( unittest::TestMessageSetExtension1::message_set_extension)); // Release the extension using ReleaseExtension @@ -197,8 +197,7 @@ TEST(ExtensionSetTest, ReleaseExtension) { // ReleaseExtension will return the underlying object even after // ClearExtension is called. message.SetAllocatedExtension( - unittest::TestMessageSetExtension1::message_set_extension, - extension); + unittest::TestMessageSetExtension1::message_set_extension, extension); message.ClearExtension( unittest::TestMessageSetExtension1::message_set_extension); released_extension = message.ReleaseExtension( @@ -208,13 +207,12 @@ TEST(ExtensionSetTest, ReleaseExtension) { } TEST(ExtensionSetTest, ArenaUnsafeArenaSetAllocatedAndRelease) { - ::google::protobuf::Arena arena; + Arena arena; unittest::TestAllExtensions* message = - ::google::protobuf::Arena::CreateMessage(&arena); + Arena::CreateMessage(&arena); unittest::ForeignMessage extension; message->UnsafeArenaSetAllocatedExtension( - unittest::optional_foreign_message_extension, - &extension); + unittest::optional_foreign_message_extension, &extension); // No copy when set. unittest::ForeignMessage* mutable_extension = message->MutableExtension(unittest::optional_foreign_message_extension); @@ -224,21 +222,19 @@ TEST(ExtensionSetTest, ArenaUnsafeArenaSetAllocatedAndRelease) { message->UnsafeArenaReleaseExtension( unittest::optional_foreign_message_extension); EXPECT_EQ(&extension, released_extension); - EXPECT_FALSE(message->HasExtension( - unittest::optional_foreign_message_extension)); + EXPECT_FALSE( + message->HasExtension(unittest::optional_foreign_message_extension)); // Set the ownership back and let the destructors run. It should not take // ownership, so this should not crash. message->UnsafeArenaSetAllocatedExtension( - unittest::optional_foreign_message_extension, - &extension); + unittest::optional_foreign_message_extension, &extension); } TEST(ExtensionSetTest, UnsafeArenaSetAllocatedAndRelease) { unittest::TestAllExtensions message; unittest::ForeignMessage* extension = new unittest::ForeignMessage(); message.UnsafeArenaSetAllocatedExtension( - unittest::optional_foreign_message_extension, - extension); + unittest::optional_foreign_message_extension, extension); // No copy when set. unittest::ForeignMessage* mutable_extension = message.MutableExtension(unittest::optional_foreign_message_extension); @@ -248,31 +244,29 @@ TEST(ExtensionSetTest, UnsafeArenaSetAllocatedAndRelease) { message.UnsafeArenaReleaseExtension( unittest::optional_foreign_message_extension); EXPECT_EQ(extension, released_extension); - EXPECT_FALSE(message.HasExtension( - unittest::optional_foreign_message_extension)); + EXPECT_FALSE( + message.HasExtension(unittest::optional_foreign_message_extension)); // Set the ownership back and let the destructors run. It should take // ownership, so this should not leak. message.UnsafeArenaSetAllocatedExtension( - unittest::optional_foreign_message_extension, - extension); + unittest::optional_foreign_message_extension, extension); } TEST(ExtensionSetTest, ArenaUnsafeArenaReleaseOfHeapAlloc) { - ::google::protobuf::Arena arena; + Arena arena; unittest::TestAllExtensions* message = - ::google::protobuf::Arena::CreateMessage(&arena); + Arena::CreateMessage(&arena); unittest::ForeignMessage* extension = new unittest::ForeignMessage; - message->SetAllocatedExtension( - unittest::optional_foreign_message_extension, - extension); + message->SetAllocatedExtension(unittest::optional_foreign_message_extension, + extension); // The arena should maintain ownership of the heap allocated proto because we // used UnsafeArenaReleaseExtension. The leak checker will ensure this. unittest::ForeignMessage* released_extension = message->UnsafeArenaReleaseExtension( unittest::optional_foreign_message_extension); EXPECT_EQ(extension, released_extension); - EXPECT_FALSE(message->HasExtension( - unittest::optional_foreign_message_extension)); + EXPECT_FALSE( + message->HasExtension(unittest::optional_foreign_message_extension)); } @@ -342,10 +336,8 @@ TEST(ExtensionSetTest, SwapExtension) { TestUtil::ExpectExtensionsClear(message2); // Swap two extensions. - fields.push_back( - reflection->FindKnownExtensionByNumber(12)); - fields.push_back( - reflection->FindKnownExtensionByNumber(25)); + fields.push_back(reflection->FindKnownExtensionByNumber(12)); + fields.push_back(reflection->FindKnownExtensionByNumber(25)); reflection->SwapFields(&message1, &message2, fields); EXPECT_TRUE(message1.HasExtension(unittest::optional_int32_extension)); @@ -392,17 +384,17 @@ TEST(ExtensionSetTest, SwapExtensionBothFull) { } TEST(ExtensionSetTest, ArenaSetAllExtension) { - ::google::protobuf::Arena arena1; + Arena arena1; unittest::TestAllExtensions* message1 = - ::google::protobuf::Arena::CreateMessage(&arena1); + Arena::CreateMessage(&arena1); TestUtil::SetAllExtensions(message1); TestUtil::ExpectAllExtensionsSet(*message1); } TEST(ExtensionSetTest, ArenaCopyConstructor) { - ::google::protobuf::Arena arena1; + Arena arena1; unittest::TestAllExtensions* message1 = - ::google::protobuf::Arena::CreateMessage(&arena1); + Arena::CreateMessage(&arena1); TestUtil::SetAllExtensions(message1); unittest::TestAllExtensions message2(*message1); arena1.Reset(); @@ -410,9 +402,9 @@ TEST(ExtensionSetTest, ArenaCopyConstructor) { } TEST(ExtensionSetTest, ArenaMergeFrom) { - ::google::protobuf::Arena arena1; + Arena arena1; unittest::TestAllExtensions* message1 = - ::google::protobuf::Arena::CreateMessage(&arena1); + Arena::CreateMessage(&arena1); TestUtil::SetAllExtensions(message1); unittest::TestAllExtensions message2; message2.MergeFrom(*message1); @@ -421,31 +413,30 @@ TEST(ExtensionSetTest, ArenaMergeFrom) { } TEST(ExtensionSetTest, ArenaSetAllocatedMessageAndRelease) { - ::google::protobuf::Arena arena; + Arena arena; unittest::TestAllExtensions* message = - ::google::protobuf::Arena::CreateMessage(&arena); - EXPECT_FALSE(message->HasExtension( - unittest::optional_foreign_message_extension)); + Arena::CreateMessage(&arena); + EXPECT_FALSE( + message->HasExtension(unittest::optional_foreign_message_extension)); // Add a extension using SetAllocatedExtension unittest::ForeignMessage* foreign_message = new unittest::ForeignMessage(); message->SetAllocatedExtension(unittest::optional_foreign_message_extension, foreign_message); // foreign_message is now owned by the arena. - EXPECT_EQ(foreign_message, - message->MutableExtension( - unittest::optional_foreign_message_extension)); + EXPECT_EQ(foreign_message, message->MutableExtension( + unittest::optional_foreign_message_extension)); // Underlying message is copied, and returned. - unittest::ForeignMessage* released_message = message->ReleaseExtension( - unittest::optional_foreign_message_extension); + unittest::ForeignMessage* released_message = + message->ReleaseExtension(unittest::optional_foreign_message_extension); delete released_message; - EXPECT_FALSE(message->HasExtension( - unittest::optional_foreign_message_extension)); + EXPECT_FALSE( + message->HasExtension(unittest::optional_foreign_message_extension)); } TEST(ExtensionSetTest, SwapExtensionBothFullWithArena) { - ::google::protobuf::Arena arena1; - std::unique_ptr arena2(new ::google::protobuf::Arena()); + Arena arena1; + std::unique_ptr arena2(new Arena()); unittest::TestAllExtensions* message1 = Arena::CreateMessage(&arena1); @@ -467,7 +458,7 @@ TEST(ExtensionSetTest, SwapExtensionBothFullWithArena) { arena2.reset(NULL); TestUtil::ExpectAllExtensionsSet(*message1); // Test corner cases, when one is empty and other is not. - ::google::protobuf::Arena arena3, arena4; + Arena arena3, arena4; unittest::TestAllExtensions* message3 = Arena::CreateMessage(&arena3); @@ -480,8 +471,8 @@ TEST(ExtensionSetTest, SwapExtensionBothFullWithArena) { } TEST(ExtensionSetTest, SwapFieldsOfExtensionBothFullWithArena) { - google::protobuf::Arena arena1; - google::protobuf::Arena* arena2 = new ::google::protobuf::Arena(); + Arena arena1; + Arena* arena2 = new Arena(); unittest::TestAllExtensions* message1 = Arena::CreateMessage(&arena1); @@ -525,9 +516,9 @@ TEST(ExtensionSetTest, SerializationToArray) { unittest::TestAllTypes destination; TestUtil::SetAllExtensions(&source); int size = source.ByteSize(); - string data; + std::string data; data.resize(size); - uint8* target = reinterpret_cast(string_as_array(&data)); + uint8* target = reinterpret_cast(::google::protobuf::string_as_array(&data)); uint8* end = source.SerializeWithCachedSizesToArray(target); EXPECT_EQ(size, end - target); EXPECT_TRUE(destination.ParseFromString(data)); @@ -546,10 +537,10 @@ TEST(ExtensionSetTest, SerializationToStream) { unittest::TestAllTypes destination; TestUtil::SetAllExtensions(&source); int size = source.ByteSize(); - string data; + std::string data; data.resize(size); { - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1); io::CodedOutputStream output_stream(&array_stream); source.SerializeWithCachedSizes(&output_stream); ASSERT_FALSE(output_stream.HadError()); @@ -569,9 +560,9 @@ TEST(ExtensionSetTest, PackedSerializationToArray) { unittest::TestPackedTypes destination; TestUtil::SetPackedExtensions(&source); int size = source.ByteSize(); - string data; + std::string data; data.resize(size); - uint8* target = reinterpret_cast(string_as_array(&data)); + uint8* target = reinterpret_cast(::google::protobuf::string_as_array(&data)); uint8* end = source.SerializeWithCachedSizesToArray(target); EXPECT_EQ(size, end - target); EXPECT_TRUE(destination.ParseFromString(data)); @@ -590,10 +581,10 @@ TEST(ExtensionSetTest, PackedSerializationToStream) { unittest::TestPackedTypes destination; TestUtil::SetPackedExtensions(&source); int size = source.ByteSize(); - string data; + std::string data; data.resize(size); { - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1); io::CodedOutputStream output_stream(&array_stream); source.SerializeWithCachedSizes(&output_stream); ASSERT_FALSE(output_stream.HadError()); @@ -606,27 +597,33 @@ TEST(ExtensionSetTest, NestedExtensionGroup) { // Serialize as TestGroup and parse as TestGroupExtension. unittest::TestGroup source; unittest::TestGroupExtension destination; - string data; + std::string data; source.mutable_optionalgroup()->set_a(117); source.set_optional_foreign_enum(unittest::FOREIGN_BAZ); source.SerializeToString(&data); EXPECT_TRUE(destination.ParseFromString(data)); - EXPECT_TRUE(destination.GetExtension( - unittest::TestNestedExtension::optionalgroup_extension).has_a()); - EXPECT_EQ(117, destination.GetExtension( - unittest::TestNestedExtension::optionalgroup_extension).a()); + EXPECT_TRUE( + destination + .GetExtension(unittest::TestNestedExtension::optionalgroup_extension) + .has_a()); + EXPECT_EQ(117, destination + .GetExtension( + unittest::TestNestedExtension::optionalgroup_extension) + .a()); EXPECT_TRUE(destination.HasExtension( unittest::TestNestedExtension::optional_foreign_enum_extension)); - EXPECT_EQ(unittest::FOREIGN_BAZ, destination.GetExtension( - unittest::TestNestedExtension::optional_foreign_enum_extension)); + EXPECT_EQ( + unittest::FOREIGN_BAZ, + destination.GetExtension( + unittest::TestNestedExtension::optional_foreign_enum_extension)); } TEST(ExtensionSetTest, Parsing) { // Serialize as TestAllTypes and parse as TestAllExtensions. unittest::TestAllTypes source; unittest::TestAllExtensions destination; - string data; + std::string data; TestUtil::SetAllFields(&source); source.SerializeToString(&data); @@ -639,7 +636,7 @@ TEST(ExtensionSetTest, PackedParsing) { // Serialize as TestPackedTypes and parse as TestPackedExtensions. unittest::TestPackedTypes source; unittest::TestPackedExtensions destination; - string data; + std::string data; TestUtil::SetPackedFields(&source); source.SerializeToString(&data); @@ -650,7 +647,7 @@ TEST(ExtensionSetTest, PackedParsing) { TEST(ExtensionSetTest, PackedToUnpackedParsing) { unittest::TestPackedTypes source; unittest::TestUnpackedExtensions destination; - string data; + std::string data; TestUtil::SetPackedFields(&source); source.SerializeToString(&data); @@ -660,7 +657,10 @@ TEST(ExtensionSetTest, PackedToUnpackedParsing) { // Reserialize unittest::TestUnpackedTypes unpacked; TestUtil::SetUnpackedFields(&unpacked); - EXPECT_TRUE(unpacked.SerializeAsString() == destination.SerializeAsString()); + // Serialized proto has to be the same size and parsed to the same message. + EXPECT_EQ(unpacked.SerializeAsString().size(), + destination.SerializeAsString().size()); + EXPECT_TRUE(EqualsToSerialized(unpacked, destination.SerializeAsString())); // Make sure we can add extensions. destination.AddExtension(unittest::unpacked_int32_extension, 1); @@ -671,7 +671,7 @@ TEST(ExtensionSetTest, PackedToUnpackedParsing) { TEST(ExtensionSetTest, UnpackedToPackedParsing) { unittest::TestUnpackedTypes source; unittest::TestPackedExtensions destination; - string data; + std::string data; TestUtil::SetUnpackedFields(&source); source.SerializeToString(&data); @@ -681,7 +681,10 @@ TEST(ExtensionSetTest, UnpackedToPackedParsing) { // Reserialize unittest::TestPackedTypes packed; TestUtil::SetPackedFields(&packed); - EXPECT_TRUE(packed.SerializeAsString() == destination.SerializeAsString()); + // Serialized proto has to be the same size and parsed to the same message. + EXPECT_EQ(packed.SerializeAsString().size(), + destination.SerializeAsString().size()); + EXPECT_TRUE(EqualsToSerialized(packed, destination.SerializeAsString())); // Make sure we can add extensions. destination.AddExtension(unittest::packed_int32_extension, 1); @@ -734,36 +737,38 @@ TEST(ExtensionSetTest, MutableString) { TEST(ExtensionSetTest, SpaceUsedExcludingSelf) { // Scalar primitive extensions should increase the extension set size by a // minimum of the size of the primitive type. -#define TEST_SCALAR_EXTENSIONS_SPACE_USED(type, value) \ - do { \ - unittest::TestAllExtensions message; \ - const int base_size = message.SpaceUsed(); \ - message.SetExtension(unittest::optional_##type##_extension, value); \ - int min_expected_size = base_size + \ - sizeof(message.GetExtension(unittest::optional_##type##_extension)); \ - EXPECT_LE(min_expected_size, message.SpaceUsed()); \ +#define TEST_SCALAR_EXTENSIONS_SPACE_USED(type, value) \ + do { \ + unittest::TestAllExtensions message; \ + const int base_size = message.SpaceUsed(); \ + message.SetExtension(unittest::optional_##type##_extension, value); \ + int min_expected_size = \ + base_size + \ + sizeof(message.GetExtension(unittest::optional_##type##_extension)); \ + EXPECT_LE(min_expected_size, message.SpaceUsed()); \ } while (0) - TEST_SCALAR_EXTENSIONS_SPACE_USED(int32 , 101); - TEST_SCALAR_EXTENSIONS_SPACE_USED(int64 , 102); - TEST_SCALAR_EXTENSIONS_SPACE_USED(uint32 , 103); - TEST_SCALAR_EXTENSIONS_SPACE_USED(uint64 , 104); - TEST_SCALAR_EXTENSIONS_SPACE_USED(sint32 , 105); - TEST_SCALAR_EXTENSIONS_SPACE_USED(sint64 , 106); - TEST_SCALAR_EXTENSIONS_SPACE_USED(fixed32 , 107); - TEST_SCALAR_EXTENSIONS_SPACE_USED(fixed64 , 108); + TEST_SCALAR_EXTENSIONS_SPACE_USED(int32, 101); + TEST_SCALAR_EXTENSIONS_SPACE_USED(int64, 102); + TEST_SCALAR_EXTENSIONS_SPACE_USED(uint32, 103); + TEST_SCALAR_EXTENSIONS_SPACE_USED(uint64, 104); + TEST_SCALAR_EXTENSIONS_SPACE_USED(sint32, 105); + TEST_SCALAR_EXTENSIONS_SPACE_USED(sint64, 106); + TEST_SCALAR_EXTENSIONS_SPACE_USED(fixed32, 107); + TEST_SCALAR_EXTENSIONS_SPACE_USED(fixed64, 108); TEST_SCALAR_EXTENSIONS_SPACE_USED(sfixed32, 109); TEST_SCALAR_EXTENSIONS_SPACE_USED(sfixed64, 110); - TEST_SCALAR_EXTENSIONS_SPACE_USED(float , 111); - TEST_SCALAR_EXTENSIONS_SPACE_USED(double , 112); - TEST_SCALAR_EXTENSIONS_SPACE_USED(bool , true); + TEST_SCALAR_EXTENSIONS_SPACE_USED(float, 111); + TEST_SCALAR_EXTENSIONS_SPACE_USED(double, 112); + TEST_SCALAR_EXTENSIONS_SPACE_USED(bool, true); #undef TEST_SCALAR_EXTENSIONS_SPACE_USED { unittest::TestAllExtensions message; const int base_size = message.SpaceUsed(); message.SetExtension(unittest::optional_nested_enum_extension, unittest::TestAllTypes::FOO); - int min_expected_size = base_size + + int min_expected_size = + base_size + sizeof(message.GetExtension(unittest::optional_nested_enum_extension)); EXPECT_LE(min_expected_size, message.SpaceUsed()); } @@ -772,8 +777,9 @@ TEST(ExtensionSetTest, SpaceUsedExcludingSelf) { // that gets included as well. unittest::TestAllExtensions message; const int base_size = message.SpaceUsed(); - const string s("this is a fairly large string that will cause some " - "allocation in order to store it in the extension"); + const std::string s( + "this is a fairly large string that will cause some " + "allocation in order to store it in the extension"); message.SetExtension(unittest::optional_string_extension, s); int min_expected_size = base_size + s.length(); EXPECT_LE(min_expected_size, message.SpaceUsed()); @@ -784,8 +790,8 @@ TEST(ExtensionSetTest, SpaceUsedExcludingSelf) { const int base_size = message.SpaceUsed(); unittest::ForeignMessage foreign; foreign.set_c(42); - message.MutableExtension(unittest::optional_foreign_message_extension)-> - CopyFrom(foreign); + message.MutableExtension(unittest::optional_foreign_message_extension) + ->CopyFrom(foreign); int min_expected_size = base_size + foreign.SpaceUsed(); EXPECT_LE(min_expected_size, message.SpaceUsed()); } @@ -800,45 +806,49 @@ TEST(ExtensionSetTest, SpaceUsedExcludingSelf) { // SpaceUsed() // - Adds a large number of values (requiring allocation in the repeated // field), and ensures that that allocation is included in SpaceUsed() -#define TEST_REPEATED_EXTENSIONS_SPACE_USED(type, cpptype, value) \ - do { \ - unittest::TestAllExtensions message; \ - const int base_size = message.SpaceUsed(); \ - int min_expected_size = sizeof(RepeatedField) + base_size; \ - message.AddExtension(unittest::repeated_##type##_extension, value); \ - message.ClearExtension(unittest::repeated_##type##_extension); \ - const int empty_repeated_field_size = message.SpaceUsed(); \ - EXPECT_LE(min_expected_size, empty_repeated_field_size) << #type; \ - message.AddExtension(unittest::repeated_##type##_extension, value); \ - message.AddExtension(unittest::repeated_##type##_extension, value); \ - EXPECT_EQ(empty_repeated_field_size, message.SpaceUsed()) << #type; \ - message.ClearExtension(unittest::repeated_##type##_extension); \ - const int old_capacity = \ - message.GetRepeatedExtension(unittest::repeated_##type##_extension) \ - .Capacity(); \ - EXPECT_GE(old_capacity, kMinRepeatedFieldAllocationSize); \ - for (int i = 0; i < 16; ++i) { \ - message.AddExtension(unittest::repeated_##type##_extension, value); \ - } \ - int expected_size = sizeof(cpptype) * \ - (message.GetRepeatedExtension(unittest::repeated_##type##_extension) \ - .Capacity() - old_capacity) + empty_repeated_field_size; \ - EXPECT_LE(expected_size, message.SpaceUsed()) << #type; \ +#define TEST_REPEATED_EXTENSIONS_SPACE_USED(type, cpptype, value) \ + do { \ + unittest::TestAllExtensions message; \ + const int base_size = message.SpaceUsed(); \ + int min_expected_size = sizeof(RepeatedField) + base_size; \ + message.AddExtension(unittest::repeated_##type##_extension, value); \ + message.ClearExtension(unittest::repeated_##type##_extension); \ + const int empty_repeated_field_size = message.SpaceUsed(); \ + EXPECT_LE(min_expected_size, empty_repeated_field_size) << #type; \ + message.AddExtension(unittest::repeated_##type##_extension, value); \ + message.AddExtension(unittest::repeated_##type##_extension, value); \ + EXPECT_EQ(empty_repeated_field_size, message.SpaceUsed()) << #type; \ + message.ClearExtension(unittest::repeated_##type##_extension); \ + const int old_capacity = \ + message.GetRepeatedExtension(unittest::repeated_##type##_extension) \ + .Capacity(); \ + EXPECT_GE(old_capacity, kMinRepeatedFieldAllocationSize); \ + for (int i = 0; i < 16; ++i) { \ + message.AddExtension(unittest::repeated_##type##_extension, value); \ + } \ + int expected_size = \ + sizeof(cpptype) * \ + (message \ + .GetRepeatedExtension(unittest::repeated_##type##_extension) \ + .Capacity() - \ + old_capacity) + \ + empty_repeated_field_size; \ + EXPECT_LE(expected_size, message.SpaceUsed()) << #type; \ } while (0) - TEST_REPEATED_EXTENSIONS_SPACE_USED(int32 , int32 , 101); - TEST_REPEATED_EXTENSIONS_SPACE_USED(int64 , int64 , 102); - TEST_REPEATED_EXTENSIONS_SPACE_USED(uint32 , uint32, 103); - TEST_REPEATED_EXTENSIONS_SPACE_USED(uint64 , uint64, 104); - TEST_REPEATED_EXTENSIONS_SPACE_USED(sint32 , int32 , 105); - TEST_REPEATED_EXTENSIONS_SPACE_USED(sint64 , int64 , 106); - TEST_REPEATED_EXTENSIONS_SPACE_USED(fixed32 , uint32, 107); - TEST_REPEATED_EXTENSIONS_SPACE_USED(fixed64 , uint64, 108); - TEST_REPEATED_EXTENSIONS_SPACE_USED(sfixed32, int32 , 109); - TEST_REPEATED_EXTENSIONS_SPACE_USED(sfixed64, int64 , 110); - TEST_REPEATED_EXTENSIONS_SPACE_USED(float , float , 111); - TEST_REPEATED_EXTENSIONS_SPACE_USED(double , double, 112); - TEST_REPEATED_EXTENSIONS_SPACE_USED(bool , bool , true); + TEST_REPEATED_EXTENSIONS_SPACE_USED(int32, int32, 101); + TEST_REPEATED_EXTENSIONS_SPACE_USED(int64, int64, 102); + TEST_REPEATED_EXTENSIONS_SPACE_USED(uint32, uint32, 103); + TEST_REPEATED_EXTENSIONS_SPACE_USED(uint64, uint64, 104); + TEST_REPEATED_EXTENSIONS_SPACE_USED(sint32, int32, 105); + TEST_REPEATED_EXTENSIONS_SPACE_USED(sint64, int64, 106); + TEST_REPEATED_EXTENSIONS_SPACE_USED(fixed32, uint32, 107); + TEST_REPEATED_EXTENSIONS_SPACE_USED(fixed64, uint64, 108); + TEST_REPEATED_EXTENSIONS_SPACE_USED(sfixed32, int32, 109); + TEST_REPEATED_EXTENSIONS_SPACE_USED(sfixed64, int64, 110); + TEST_REPEATED_EXTENSIONS_SPACE_USED(float, float, 111); + TEST_REPEATED_EXTENSIONS_SPACE_USED(double, double, 112); + TEST_REPEATED_EXTENSIONS_SPACE_USED(bool, bool, true); TEST_REPEATED_EXTENSIONS_SPACE_USED(nested_enum, int, unittest::TestAllTypes::FOO); #undef TEST_REPEATED_EXTENSIONS_SPACE_USED @@ -846,29 +856,29 @@ TEST(ExtensionSetTest, SpaceUsedExcludingSelf) { { unittest::TestAllExtensions message; const int base_size = message.SpaceUsed(); - int min_expected_size = sizeof(RepeatedPtrField) + base_size; - const string value(256, 'x'); + int min_expected_size = sizeof(RepeatedPtrField) + base_size; + const std::string value(256, 'x'); // Once items are allocated, they may stick around even when cleared so // without the hardcore memory management accessors there isn't a notion of // the empty repeated field memory usage as there is with primitive types. for (int i = 0; i < 16; ++i) { message.AddExtension(unittest::repeated_string_extension, value); } - min_expected_size += (sizeof(value) + value.size()) * - (16 - kMinRepeatedFieldAllocationSize); + min_expected_size += + (sizeof(value) + value.size()) * (16 - kMinRepeatedFieldAllocationSize); EXPECT_LE(min_expected_size, message.SpaceUsed()); } // Repeated messages { unittest::TestAllExtensions message; const int base_size = message.SpaceUsed(); - int min_expected_size = sizeof(RepeatedPtrField) + - base_size; + int min_expected_size = + sizeof(RepeatedPtrField) + base_size; unittest::ForeignMessage prototype; prototype.set_c(2); for (int i = 0; i < 16; ++i) { - message.AddExtension(unittest::repeated_foreign_message_extension)-> - CopyFrom(prototype); + message.AddExtension(unittest::repeated_foreign_message_extension) + ->CopyFrom(prototype); } min_expected_size += (16 - kMinRepeatedFieldAllocationSize) * prototype.SpaceUsed(); @@ -877,7 +887,7 @@ TEST(ExtensionSetTest, SpaceUsedExcludingSelf) { } // N.B.: We do not test range-based for here because we remain C++03 compatible. -template +template inline T SumAllExtensions(const M& message, ID extension, T zero) { T sum = zero; typename RepeatedField::const_iterator iter = @@ -890,12 +900,11 @@ inline T SumAllExtensions(const M& message, ID extension, T zero) { return sum; } -template -inline void IncAllExtensions(M* message, ID extension, - T val) { +template +inline void IncAllExtensions(M* message, ID extension, T val) { typename RepeatedField::iterator iter = message->MutableRepeatedExtension(extension)->begin(); - typename RepeatedField::iterator end = + typename RepeatedField::iterator end = message->MutableRepeatedExtension(extension)->end(); for (; iter != end; ++iter) { *iter += val; @@ -906,14 +915,19 @@ TEST(ExtensionSetTest, RepeatedFields) { unittest::TestAllExtensions message; // Test empty repeated-field case (b/12926163) - ASSERT_EQ(0, message.GetRepeatedExtension( - unittest::repeated_int32_extension).size()); - ASSERT_EQ(0, message.GetRepeatedExtension( - unittest::repeated_nested_enum_extension).size()); - ASSERT_EQ(0, message.GetRepeatedExtension( - unittest::repeated_string_extension).size()); - ASSERT_EQ(0, message.GetRepeatedExtension( - unittest::repeated_nested_message_extension).size()); + ASSERT_EQ( + 0, + message.GetRepeatedExtension(unittest::repeated_int32_extension).size()); + ASSERT_EQ( + 0, message.GetRepeatedExtension(unittest::repeated_nested_enum_extension) + .size()); + ASSERT_EQ( + 0, + message.GetRepeatedExtension(unittest::repeated_string_extension).size()); + ASSERT_EQ( + 0, + message.GetRepeatedExtension(unittest::repeated_nested_message_extension) + .size()); unittest::TestAllTypes::NestedMessage nested_message; nested_message.set_bb(42); @@ -936,114 +950,113 @@ TEST(ExtensionSetTest, RepeatedFields) { message.AddExtension(unittest::repeated_bool_extension, true); message.AddExtension(unittest::repeated_nested_enum_extension, nested_enum); message.AddExtension(unittest::repeated_string_extension, - ::std::string("test")); + std::string("test")); message.AddExtension(unittest::repeated_bytes_extension, - ::std::string("test\xFF")); - message.AddExtension( - unittest::repeated_nested_message_extension)->CopyFrom(nested_message); - message.AddExtension(unittest::repeated_nested_enum_extension, - nested_enum); + std::string("test\xFF")); + message.AddExtension(unittest::repeated_nested_message_extension) + ->CopyFrom(nested_message); + message.AddExtension(unittest::repeated_nested_enum_extension, nested_enum); } - ASSERT_EQ(10, SumAllExtensions( - message, unittest::repeated_int32_extension, 0)); - IncAllExtensions( - &message, unittest::repeated_int32_extension, 1); - ASSERT_EQ(20, SumAllExtensions( - message, unittest::repeated_int32_extension, 0)); + ASSERT_EQ(10, SumAllExtensions(message, + unittest::repeated_int32_extension, 0)); + IncAllExtensions(&message, unittest::repeated_int32_extension, 1); + ASSERT_EQ(20, SumAllExtensions(message, + unittest::repeated_int32_extension, 0)); - ASSERT_EQ(20, SumAllExtensions( - message, unittest::repeated_int64_extension, 0)); - IncAllExtensions( - &message, unittest::repeated_int64_extension, 1); - ASSERT_EQ(30, SumAllExtensions( - message, unittest::repeated_int64_extension, 0)); + ASSERT_EQ(20, SumAllExtensions(message, + unittest::repeated_int64_extension, 0)); + IncAllExtensions(&message, unittest::repeated_int64_extension, 1); + ASSERT_EQ(30, SumAllExtensions(message, + unittest::repeated_int64_extension, 0)); ASSERT_EQ(30, SumAllExtensions( - message, unittest::repeated_uint32_extension, 0)); - IncAllExtensions( - &message, unittest::repeated_uint32_extension, 1); + message, unittest::repeated_uint32_extension, 0)); + IncAllExtensions(&message, unittest::repeated_uint32_extension, 1); ASSERT_EQ(40, SumAllExtensions( - message, unittest::repeated_uint32_extension, 0)); + message, unittest::repeated_uint32_extension, 0)); ASSERT_EQ(40, SumAllExtensions( - message, unittest::repeated_uint64_extension, 0)); - IncAllExtensions( - &message, unittest::repeated_uint64_extension, 1); + message, unittest::repeated_uint64_extension, 0)); + IncAllExtensions(&message, unittest::repeated_uint64_extension, 1); ASSERT_EQ(50, SumAllExtensions( - message, unittest::repeated_uint64_extension, 0)); + message, unittest::repeated_uint64_extension, 0)); ASSERT_EQ(50, SumAllExtensions( - message, unittest::repeated_sint32_extension, 0)); - IncAllExtensions( - &message, unittest::repeated_sint32_extension, 1); + message, unittest::repeated_sint32_extension, 0)); + IncAllExtensions(&message, unittest::repeated_sint32_extension, 1); ASSERT_EQ(60, SumAllExtensions( - message, unittest::repeated_sint32_extension, 0)); + message, unittest::repeated_sint32_extension, 0)); ASSERT_EQ(60, SumAllExtensions( - message, unittest::repeated_sint64_extension, 0)); - IncAllExtensions( - &message, unittest::repeated_sint64_extension, 1); + message, unittest::repeated_sint64_extension, 0)); + IncAllExtensions(&message, unittest::repeated_sint64_extension, 1); ASSERT_EQ(70, SumAllExtensions( - message, unittest::repeated_sint64_extension, 0)); + message, unittest::repeated_sint64_extension, 0)); ASSERT_EQ(70, SumAllExtensions( - message, unittest::repeated_fixed32_extension, 0)); - IncAllExtensions( - &message, unittest::repeated_fixed32_extension, 1); + message, unittest::repeated_fixed32_extension, 0)); + IncAllExtensions(&message, unittest::repeated_fixed32_extension, 1); ASSERT_EQ(80, SumAllExtensions( - message, unittest::repeated_fixed32_extension, 0)); + message, unittest::repeated_fixed32_extension, 0)); ASSERT_EQ(80, SumAllExtensions( - message, unittest::repeated_fixed64_extension, 0)); - IncAllExtensions( - &message, unittest::repeated_fixed64_extension, 1); + message, unittest::repeated_fixed64_extension, 0)); + IncAllExtensions(&message, unittest::repeated_fixed64_extension, 1); ASSERT_EQ(90, SumAllExtensions( - message, unittest::repeated_fixed64_extension, 0)); + message, unittest::repeated_fixed64_extension, 0)); // Usually, floating-point arithmetic cannot be trusted to be exact, so it is // a Bad Idea to assert equality in a test like this. However, we're dealing // with integers with a small number of significant mantissa bits, so we // should actually have exact precision here. - ASSERT_EQ(90, SumAllExtensions( - message, unittest::repeated_float_extension, 0)); - IncAllExtensions( - &message, unittest::repeated_float_extension, 1); + ASSERT_EQ(90, SumAllExtensions(message, + unittest::repeated_float_extension, 0)); + IncAllExtensions(&message, unittest::repeated_float_extension, 1); ASSERT_EQ(100, SumAllExtensions( - message, unittest::repeated_float_extension, 0)); + message, unittest::repeated_float_extension, 0)); ASSERT_EQ(100, SumAllExtensions( - message, unittest::repeated_double_extension, 0)); - IncAllExtensions( - &message, unittest::repeated_double_extension, 1); + message, unittest::repeated_double_extension, 0)); + IncAllExtensions(&message, unittest::repeated_double_extension, 1); ASSERT_EQ(110, SumAllExtensions( - message, unittest::repeated_double_extension, 0)); + message, unittest::repeated_double_extension, 0)); - RepeatedPtrField<::std::string>::iterator string_iter; - RepeatedPtrField<::std::string>::iterator string_end; - for (string_iter = message.MutableRepeatedExtension( - unittest::repeated_string_extension)->begin(), - string_end = message.MutableRepeatedExtension( - unittest::repeated_string_extension)->end(); + RepeatedPtrField::iterator string_iter; + RepeatedPtrField::iterator string_end; + for (string_iter = + message + .MutableRepeatedExtension(unittest::repeated_string_extension) + ->begin(), + string_end = + message + .MutableRepeatedExtension(unittest::repeated_string_extension) + ->end(); string_iter != string_end; ++string_iter) { *string_iter += "test"; } - RepeatedPtrField<::std::string>::const_iterator string_const_iter; - RepeatedPtrField<::std::string>::const_iterator string_const_end; - for (string_const_iter = message.GetRepeatedExtension( - unittest::repeated_string_extension).begin(), - string_const_end = message.GetRepeatedExtension( - unittest::repeated_string_extension).end(); + RepeatedPtrField::const_iterator string_const_iter; + RepeatedPtrField::const_iterator string_const_end; + for (string_const_iter = + message.GetRepeatedExtension(unittest::repeated_string_extension) + .begin(), + string_const_end = + message.GetRepeatedExtension(unittest::repeated_string_extension) + .end(); string_iter != string_end; ++string_iter) { ASSERT_TRUE(*string_iter == "testtest"); } RepeatedField::iterator enum_iter; RepeatedField::iterator enum_end; - for (enum_iter = message.MutableRepeatedExtension( - unittest::repeated_nested_enum_extension)->begin(), - enum_end = message.MutableRepeatedExtension( - unittest::repeated_nested_enum_extension)->end(); + for (enum_iter = message + .MutableRepeatedExtension( + unittest::repeated_nested_enum_extension) + ->begin(), + enum_end = message + .MutableRepeatedExtension( + unittest::repeated_nested_enum_extension) + ->end(); enum_iter != enum_end; ++enum_iter) { *enum_iter = unittest::TestAllTypes::NestedEnum_MAX; } @@ -1051,33 +1064,43 @@ TEST(ExtensionSetTest, RepeatedFields) { enum_const_iter; RepeatedField::const_iterator enum_const_end; - for (enum_const_iter = message.GetRepeatedExtension( - unittest::repeated_nested_enum_extension).begin(), - enum_const_end = message.GetRepeatedExtension( - unittest::repeated_nested_enum_extension).end(); - enum_iter != enum_end; ++enum_iter) { + for (enum_const_iter = + message + .GetRepeatedExtension(unittest::repeated_nested_enum_extension) + .begin(), + enum_const_end = + message + .GetRepeatedExtension(unittest::repeated_nested_enum_extension) + .end(); + enum_const_iter != enum_const_end; ++enum_const_iter) { ASSERT_EQ(*enum_const_iter, unittest::TestAllTypes::NestedEnum_MAX); } - RepeatedPtrField::iterator - msg_iter; - RepeatedPtrField::iterator - msg_end; - for (msg_iter = message.MutableRepeatedExtension( - unittest::repeated_nested_message_extension)->begin(), - msg_end = message.MutableRepeatedExtension( - unittest::repeated_nested_message_extension)->end(); + RepeatedPtrField::iterator msg_iter; + RepeatedPtrField::iterator msg_end; + for (msg_iter = message + .MutableRepeatedExtension( + unittest::repeated_nested_message_extension) + ->begin(), + msg_end = message + .MutableRepeatedExtension( + unittest::repeated_nested_message_extension) + ->end(); msg_iter != msg_end; ++msg_iter) { msg_iter->set_bb(1234); } - RepeatedPtrField:: - const_iterator msg_const_iter; - RepeatedPtrField:: - const_iterator msg_const_end; - for (msg_const_iter = message.GetRepeatedExtension( - unittest::repeated_nested_message_extension).begin(), - msg_const_end = message.GetRepeatedExtension( - unittest::repeated_nested_message_extension).end(); + RepeatedPtrField::const_iterator + msg_const_iter; + RepeatedPtrField::const_iterator + msg_const_end; + for (msg_const_iter = message + .GetRepeatedExtension( + unittest::repeated_nested_message_extension) + .begin(), + msg_const_end = message + .GetRepeatedExtension( + unittest::repeated_nested_message_extension) + .end(); msg_const_iter != msg_const_end; ++msg_const_iter) { ASSERT_EQ(msg_const_iter->bb(), 1234); } @@ -1085,30 +1108,30 @@ TEST(ExtensionSetTest, RepeatedFields) { // Test range-based for as well, but only if compiled as C++11. #if __cplusplus >= 201103L // Test one primitive field. - for (auto& x : *message.MutableRepeatedExtension( - unittest::repeated_int32_extension)) { + for (auto& x : + *message.MutableRepeatedExtension(unittest::repeated_int32_extension)) { x = 4321; } - for (const auto& x : message.GetRepeatedExtension( - unittest::repeated_int32_extension)) { + for (const auto& x : + message.GetRepeatedExtension(unittest::repeated_int32_extension)) { ASSERT_EQ(x, 4321); } // Test one string field. - for (auto& x : *message.MutableRepeatedExtension( - unittest::repeated_string_extension)) { + for (auto& x : + *message.MutableRepeatedExtension(unittest::repeated_string_extension)) { x = "test_range_based_for"; } - for (const auto& x : message.GetRepeatedExtension( - unittest::repeated_string_extension)) { + for (const auto& x : + message.GetRepeatedExtension(unittest::repeated_string_extension)) { ASSERT_TRUE(x == "test_range_based_for"); } // Test one message field. for (auto& x : *message.MutableRepeatedExtension( - unittest::repeated_nested_message_extension)) { + unittest::repeated_nested_message_extension)) { x.set_bb(4321); } for (const auto& x : *message.MutableRepeatedExtension( - unittest::repeated_nested_message_extension)) { + unittest::repeated_nested_message_extension)) { ASSERT_EQ(x.bb(), 4321); } #endif @@ -1118,12 +1141,13 @@ TEST(ExtensionSetTest, RepeatedFields) { TEST(ExtensionSetTest, AbsentExtension) { unittest::TestAllExtensions message; message.MutableRepeatedExtension(unittest::repeated_nested_message_extension) - ->Add()->set_bb(123); - ASSERT_EQ(1, message.ExtensionSize( - unittest::repeated_nested_message_extension)); - EXPECT_EQ( - 123, message.GetExtension( - unittest::repeated_nested_message_extension, 0).bb()); + ->Add() + ->set_bb(123); + ASSERT_EQ(1, + message.ExtensionSize(unittest::repeated_nested_message_extension)); + EXPECT_EQ(123, + message.GetExtension(unittest::repeated_nested_message_extension, 0) + .bb()); } #ifdef PROTOBUF_HAS_DEATH_TEST @@ -1131,9 +1155,9 @@ TEST(ExtensionSetTest, AbsentExtension) { TEST(ExtensionSetTest, InvalidEnumDeath) { unittest::TestAllExtensions message; EXPECT_DEBUG_DEATH( - message.SetExtension(unittest::optional_foreign_enum_extension, - static_cast(53)), - "IsValid"); + message.SetExtension(unittest::optional_foreign_enum_extension, + static_cast(53)), + "IsValid"); } #endif // PROTOBUF_HAS_DEATH_TEST @@ -1169,9 +1193,9 @@ TEST(ExtensionSetTest, DynamicExtensions) { // If the field refers to one of the types nested in TestDynamicExtensions, // make it refer to the type in our dynamic proto instead. - string prefix = "." + template_descriptor->full_name() + "."; + std::string prefix = "." + template_descriptor->full_name() + "."; if (extension->has_type_name()) { - string* type_name = extension->mutable_type_name(); + std::string* type_name = extension->mutable_type_name(); if (HasPrefixString(*type_name, prefix)) { type_name->replace(0, prefix.size(), ".dynamic_extensions."); } @@ -1188,7 +1212,8 @@ TEST(ExtensionSetTest, DynamicExtensions) { // Construct a message that we can parse with the extensions we defined. // Since the extensions were based off of the fields of TestDynamicExtensions, // we can use that message to create this test message. - string data; + std::string data; + unittest::TestDynamicExtensions dynamic_extension; { unittest::TestDynamicExtensions message; message.set_scalar_extension(123); @@ -1208,12 +1233,13 @@ TEST(ExtensionSetTest, DynamicExtensions) { // An unknown enum value (for a known field). message.mutable_unknown_fields()->AddVarint( - unittest::TestDynamicExtensions::kDynamicEnumExtensionFieldNumber, - 12345); + unittest::TestDynamicExtensions::kDynamicEnumExtensionFieldNumber, + 12345); // A regular unknown field. message.mutable_unknown_fields()->AddLengthDelimited(54321, "unknown"); message.SerializeToString(&data); + dynamic_extension = message; } // Now we can parse this using our dynamic extension definitions... @@ -1228,29 +1254,28 @@ TEST(ExtensionSetTest, DynamicExtensions) { // Can we print it? EXPECT_EQ( - "[dynamic_extensions.scalar_extension]: 123\n" - "[dynamic_extensions.enum_extension]: FOREIGN_BAR\n" - "[dynamic_extensions.dynamic_enum_extension]: DYNAMIC_BAZ\n" - "[dynamic_extensions.message_extension] {\n" - " c: 456\n" - "}\n" - "[dynamic_extensions.dynamic_message_extension] {\n" - " dynamic_field: 789\n" - "}\n" - "[dynamic_extensions.repeated_extension]: \"foo\"\n" - "[dynamic_extensions.repeated_extension]: \"bar\"\n" - "[dynamic_extensions.packed_extension]: 12\n" - "[dynamic_extensions.packed_extension]: -34\n" - "[dynamic_extensions.packed_extension]: 56\n" - "[dynamic_extensions.packed_extension]: -78\n" - "2002: 12345\n" - "54321: \"unknown\"\n", - message.DebugString()); + "[dynamic_extensions.scalar_extension]: 123\n" + "[dynamic_extensions.enum_extension]: FOREIGN_BAR\n" + "[dynamic_extensions.dynamic_enum_extension]: DYNAMIC_BAZ\n" + "[dynamic_extensions.message_extension] {\n" + " c: 456\n" + "}\n" + "[dynamic_extensions.dynamic_message_extension] {\n" + " dynamic_field: 789\n" + "}\n" + "[dynamic_extensions.repeated_extension]: \"foo\"\n" + "[dynamic_extensions.repeated_extension]: \"bar\"\n" + "[dynamic_extensions.packed_extension]: 12\n" + "[dynamic_extensions.packed_extension]: -34\n" + "[dynamic_extensions.packed_extension]: 56\n" + "[dynamic_extensions.packed_extension]: -78\n" + "2002: 12345\n" + "54321: \"unknown\"\n", + message.DebugString()); // Can we serialize it? - // (Don't use EXPECT_EQ because we don't want to dump raw binary data to the - // terminal on failure.) - EXPECT_TRUE(message.SerializeAsString() == data); + EXPECT_TRUE( + EqualsToSerialized(dynamic_extension, message.SerializeAsString())); // What if we parse using the reflection-based parser? { @@ -1271,10 +1296,10 @@ TEST(ExtensionSetTest, DynamicExtensions) { const Message& sub_message = message.GetReflection()->GetMessage(message, message_extension); const unittest::ForeignMessage* typed_sub_message = -#ifdef GOOGLE_PROTOBUF_NO_RTTI - static_cast(&sub_message); -#else +#if PROTOBUF_RTTI dynamic_cast(&sub_message); +#else + static_cast(&sub_message); #endif ASSERT_TRUE(typed_sub_message != NULL); EXPECT_EQ(456, typed_sub_message->c()); @@ -1287,9 +1312,8 @@ TEST(ExtensionSetTest, DynamicExtensions) { file->FindExtensionByName("dynamic_message_extension"); ASSERT_TRUE(dynamic_message_extension != NULL); const Message& parent = unittest::TestAllExtensions::default_instance(); - const Message& sub_message = - parent.GetReflection()->GetMessage(parent, dynamic_message_extension, - &dynamic_factory); + const Message& sub_message = parent.GetReflection()->GetMessage( + parent, dynamic_message_extension, &dynamic_factory); const Message* prototype = dynamic_factory.GetPrototype(dynamic_message_extension->message_type()); EXPECT_EQ(prototype, &sub_message); diff --git a/third_party/protobuf/src/google/protobuf/field_mask.pb.cc b/third_party/protobuf/src/google/protobuf/field_mask.pb.cc index 000fa8d3..482bffa5 100644 --- a/third_party/protobuf/src/google/protobuf/field_mask.pb.cc +++ b/third_party/protobuf/src/google/protobuf/field_mask.pb.cc @@ -6,137 +6,116 @@ #include #include -#include #include -#include +#include +#include #include #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) - -namespace google { -namespace protobuf { +#include +PROTOBUF_NAMESPACE_OPEN class FieldMaskDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _FieldMask_default_instance_; -} // namespace protobuf -} // namespace google -namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto { -static void InitDefaultsFieldMask() { +PROTOBUF_NAMESPACE_CLOSE +static void InitDefaultsscc_info_FieldMask_google_2fprotobuf_2ffield_5fmask_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_FieldMask_default_instance_; - new (ptr) ::google::protobuf::FieldMask(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_FieldMask_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::FieldMask(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::FieldMask::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::FieldMask::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_FieldMask = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsFieldMask}, {}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_FieldMask_google_2fprotobuf_2ffield_5fmask_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_FieldMask_google_2fprotobuf_2ffield_5fmask_2eproto}, {}}; -void InitDefaults() { - ::google::protobuf::internal::InitSCC(&scc_info_FieldMask.base); -} +static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_google_2fprotobuf_2ffield_5fmask_2eproto[1]; +static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto = nullptr; +static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto = nullptr; -::google::protobuf::Metadata file_level_metadata[1]; - -const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldMask, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldMask, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldMask, paths_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldMask, paths_), }; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, sizeof(::google::protobuf::FieldMask)}, +static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, -1, sizeof(PROTOBUF_NAMESPACE_ID::FieldMask)}, }; -static ::google::protobuf::Message const * const file_default_instances[] = { - reinterpret_cast(&::google::protobuf::_FieldMask_default_instance_), +static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_FieldMask_default_instance_), }; -void protobuf_AssignDescriptors() { - AddDescriptors(); - AssignDescriptors( - "google/protobuf/field_mask.proto", schemas, file_default_instances, TableStruct::offsets, - file_level_metadata, NULL, NULL); -} +const char descriptor_table_protodef_google_2fprotobuf_2ffield_5fmask_2eproto[] = + "\n google/protobuf/field_mask.proto\022\017goog" + "le.protobuf\"\032\n\tFieldMask\022\r\n\005paths\030\001 \003(\tB" + "\214\001\n\023com.google.protobufB\016FieldMaskProtoP" + "\001Z9google.golang.org/genproto/protobuf/f" + "ield_mask;field_mask\370\001\001\242\002\003GPB\252\002\036Google.P" + "rotobuf.WellKnownTypesb\006proto3" + ; +static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_deps[1] = { +}; +static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_sccs[1] = { + &scc_info_FieldMask_google_2fprotobuf_2ffield_5fmask_2eproto.base, +}; +static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_once; +static bool descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_initialized = false; +const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto = { + &descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2ffield_5fmask_2eproto, "google/protobuf/field_mask.proto", 230, + &descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_once, descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_sccs, descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_deps, 1, 0, + schemas, file_default_instances, TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2ffield_5fmask_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto, file_level_service_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto, +}; -void protobuf_AssignDescriptorsOnce() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); -} - -void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1); -} - -void AddDescriptorsImpl() { - InitDefaults(); - static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - "\n google/protobuf/field_mask.proto\022\017goog" - "le.protobuf\"\032\n\tFieldMask\022\r\n\005paths\030\001 \003(\tB" - "\211\001\n\023com.google.protobufB\016FieldMaskProtoP" - "\001Z9google.golang.org/genproto/protobuf/f" - "ield_mask;field_mask\242\002\003GPB\252\002\036Google.Prot" - "obuf.WellKnownTypesb\006proto3" - }; - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - descriptor, 227); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "google/protobuf/field_mask.proto", &protobuf_RegisterTypes); -} - -void AddDescriptors() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); -} -// Force AddDescriptors() to be called at dynamic initialization time. -struct StaticDescriptorInitializer { - StaticDescriptorInitializer() { - AddDescriptors(); - } -} static_descriptor_initializer; -} // namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto -namespace google { -namespace protobuf { +// Force running AddDescriptors() at dynamic initialization time. +static bool dynamic_init_dummy_google_2fprotobuf_2ffield_5fmask_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto), true); +PROTOBUF_NAMESPACE_OPEN // =================================================================== void FieldMask::InitAsDefaultInstance() { } +class FieldMask::HasBitSetters { + public: +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int FieldMask::kPathsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 FieldMask::FieldMask() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::scc_info_FieldMask.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FieldMask) } +FieldMask::FieldMask(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(arena), + paths_(arena) { + SharedCtor(); + RegisterArenaDtor(arena); + // @@protoc_insertion_point(arena_constructor:google.protobuf.FieldMask) +} FieldMask::FieldMask(const FieldMask& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), paths_(from.paths_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.FieldMask) } void FieldMask::SharedCtor() { + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_FieldMask_google_2fprotobuf_2ffield_5fmask_2eproto.base); } FieldMask::~FieldMask() { @@ -145,25 +124,27 @@ FieldMask::~FieldMask() { } void FieldMask::SharedDtor() { + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } +void FieldMask::ArenaDtor(void* object) { + FieldMask* _this = reinterpret_cast< FieldMask* >(object); + (void)_this; +} +void FieldMask::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { +} void FieldMask::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* FieldMask::descriptor() { - ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const FieldMask& FieldMask::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::scc_info_FieldMask.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_FieldMask_google_2fprotobuf_2ffield_5fmask_2eproto.base); return *internal_default_instance(); } void FieldMask::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.FieldMask) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -171,26 +152,66 @@ void FieldMask::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* FieldMask::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // repeated string paths = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr -= 1; + do { + ptr += 1; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(add_paths(), ptr, ctx, "google.protobuf.FieldMask.paths"); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 10); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool FieldMask::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FieldMask) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated string paths = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->add_paths())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->paths(this->paths_size() - 1).data(), static_cast(this->paths(this->paths_size() - 1).length()), - ::google::protobuf::internal::WireFormatLite::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "google.protobuf.FieldMask.paths")); } else { goto handle_unusual; @@ -203,7 +224,7 @@ bool FieldMask::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -217,50 +238,50 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void FieldMask::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.FieldMask) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated string paths = 1; for (int i = 0, n = this->paths_size(); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->paths(i).data(), static_cast(this->paths(i).length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.FieldMask.paths"); - ::google::protobuf::internal::WireFormatLite::WriteString( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteString( 1, this->paths(i), output); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); + if (_internal_metadata_.have_unknown_fields()) { + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( + _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.FieldMask) } -::google::protobuf::uint8* FieldMask::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* FieldMask::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FieldMask) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated string paths = 1; for (int i = 0, n = this->paths_size(); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->paths(i).data(), static_cast(this->paths(i).length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.FieldMask.paths"); - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: WriteStringToArray(1, this->paths(i), target); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); + if (_internal_metadata_.have_unknown_fields()) { + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( + _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FieldMask) return target; @@ -270,33 +291,37 @@ size_t FieldMask::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.protobuf.FieldMask) size_t total_size = 0; - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { + if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( + _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated string paths = 1; total_size += 1 * - ::google::protobuf::internal::FromIntSize(this->paths_size()); + ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->paths_size()); for (int i = 0, n = this->paths_size(); i < n; i++) { - total_size += ::google::protobuf::internal::WireFormatLite::StringSize( + total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->paths(i)); } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void FieldMask::MergeFrom(const ::google::protobuf::Message& from) { +void FieldMask::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FieldMask) GOOGLE_DCHECK_NE(&from, this); const FieldMask* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.FieldMask) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.FieldMask) MergeFrom(*source); @@ -307,13 +332,13 @@ void FieldMask::MergeFrom(const FieldMask& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FieldMask) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; paths_.MergeFrom(from.paths_); } -void FieldMask::CopyFrom(const ::google::protobuf::Message& from) { +void FieldMask::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.FieldMask) if (&from == this) return; Clear(); @@ -333,29 +358,41 @@ bool FieldMask::IsInitialized() const { void FieldMask::Swap(FieldMask* other) { if (other == this) return; + if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { + InternalSwap(other); + } else { + FieldMask* temp = New(GetArenaNoVirtual()); + temp->MergeFrom(*other); + other->CopyFrom(*this); + InternalSwap(temp); + if (GetArenaNoVirtual() == nullptr) { + delete temp; + } + } +} +void FieldMask::UnsafeArenaSwap(FieldMask* other) { + if (other == this) return; + GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void FieldMask::InternalSwap(FieldMask* other) { using std::swap; - paths_.InternalSwap(CastToBase(&other->paths_)); _internal_metadata_.Swap(&other->_internal_metadata_); + paths_.InternalSwap(CastToBase(&other->paths_)); } -::google::protobuf::Metadata FieldMask::GetMetadata() const { - protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata FieldMask::GetMetadata() const { + return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldMask* Arena::CreateMaybeMessage< ::google::protobuf::FieldMask >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::FieldMask >(arena); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::FieldMask* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::FieldMask >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::FieldMask >(arena); } -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) +#include diff --git a/third_party/protobuf/src/google/protobuf/field_mask.pb.h b/third_party/protobuf/src/google/protobuf/field_mask.pb.h index 54b6372d..bc99ea79 100644 --- a/third_party/protobuf/src/google/protobuf/field_mask.pb.h +++ b/third_party/protobuf/src/google/protobuf/field_mask.pb.h @@ -1,24 +1,25 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/field_mask.proto -#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto -#define PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto +#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto +#include #include -#include - -#if GOOGLE_PROTOBUF_VERSION < 3006001 +#include +#if PROTOBUF_VERSION < 3008000 #error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update +#error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3008000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please +#error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include @@ -26,59 +27,61 @@ #include #include #include +#include #include #include // IWYU pragma: export #include // IWYU pragma: export #include // @@protoc_insertion_point(includes) -#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ffield_5fmask_2eproto LIBPROTOBUF_EXPORT +#include +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ffield_5fmask_2eproto PROTOBUF_EXPORT +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE -namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto { // Internal implementation detail -- do not use these members. -struct LIBPROTOBUF_EXPORT TableStruct { - static const ::google::protobuf::internal::ParseTableField entries[]; - static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; - static const ::google::protobuf::internal::ParseTable schema[1]; - static const ::google::protobuf::internal::FieldMetadata field_metadata[]; - static const ::google::protobuf::internal::SerializationTable serialization_table[]; - static const ::google::protobuf::uint32 offsets[]; +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto { + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; + static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; + static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; -void LIBPROTOBUF_EXPORT AddDescriptors(); -} // namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto -namespace google { -namespace protobuf { +extern PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto; +PROTOBUF_NAMESPACE_OPEN class FieldMask; class FieldMaskDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern FieldMaskDefaultTypeInternal _FieldMask_default_instance_; -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldMask* Arena::CreateMaybeMessage<::google::protobuf::FieldMask>(Arena*); -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { +PROTOBUF_EXPORT extern FieldMaskDefaultTypeInternal _FieldMask_default_instance_; +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::FieldMask* Arena::CreateMaybeMessage(Arena*); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN // =================================================================== -class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldMask) */ { +class PROTOBUF_EXPORT FieldMask : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldMask) */ { public: FieldMask(); virtual ~FieldMask(); FieldMask(const FieldMask& from); - - inline FieldMask& operator=(const FieldMask& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 FieldMask(FieldMask&& from) noexcept : FieldMask() { *this = ::std::move(from); } + inline FieldMask& operator=(const FieldMask& from) { + CopyFrom(from); + return *this; + } inline FieldMask& operator=(FieldMask&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -87,8 +90,22 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro } return *this; } - #endif - static const ::google::protobuf::Descriptor* descriptor(); + + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { + return GetArenaNoVirtual(); + } + inline void* GetMaybeArenaPointer() const final { + return MaybeArenaPtr(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const FieldMask& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -99,6 +116,7 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro static constexpr int kIndexInFileMessages = 0; + void UnsafeArenaSwap(FieldMask* other); void Swap(FieldMask* other); friend void swap(FieldMask& a, FieldMask& b) { a.Swap(&b); @@ -107,43 +125,63 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro // implements Message ---------------------------------------------- inline FieldMask* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - FieldMask* New(::google::protobuf::Arena* arena) const final { + FieldMask* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const FieldMask& from); void MergeFrom(const FieldMask& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(FieldMask* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.FieldMask"; + } + protected: + explicit FieldMask(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; + static void ArenaDtor(void* object); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); + private: + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { + return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { - return NULL; + return _internal_metadata_.raw_arena_ptr(); } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto); + return ::descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -153,31 +191,31 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro int paths_size() const; void clear_paths(); static const int kPathsFieldNumber = 1; - const ::std::string& paths(int index) const; - ::std::string* mutable_paths(int index); - void set_paths(int index, const ::std::string& value); - #if LANG_CXX11 - void set_paths(int index, ::std::string&& value); - #endif + const std::string& paths(int index) const; + std::string* mutable_paths(int index); + void set_paths(int index, const std::string& value); + void set_paths(int index, std::string&& value); void set_paths(int index, const char* value); void set_paths(int index, const char* value, size_t size); - ::std::string* add_paths(); - void add_paths(const ::std::string& value); - #if LANG_CXX11 - void add_paths(::std::string&& value); - #endif + std::string* add_paths(); + void add_paths(const std::string& value); + void add_paths(std::string&& value); void add_paths(const char* value); void add_paths(const char* value, size_t size); - const ::google::protobuf::RepeatedPtrField< ::std::string>& paths() const; - ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_paths(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& paths() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* mutable_paths(); // @@protoc_insertion_point(class_scope:google.protobuf.FieldMask) private: + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::RepeatedPtrField< ::std::string> paths_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - friend struct ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField paths_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto; }; // =================================================================== @@ -197,26 +235,24 @@ inline int FieldMask::paths_size() const { inline void FieldMask::clear_paths() { paths_.Clear(); } -inline const ::std::string& FieldMask::paths(int index) const { +inline const std::string& FieldMask::paths(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FieldMask.paths) return paths_.Get(index); } -inline ::std::string* FieldMask::mutable_paths(int index) { +inline std::string* FieldMask::mutable_paths(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FieldMask.paths) return paths_.Mutable(index); } -inline void FieldMask::set_paths(int index, const ::std::string& value) { +inline void FieldMask::set_paths(int index, const std::string& value) { // @@protoc_insertion_point(field_set:google.protobuf.FieldMask.paths) paths_.Mutable(index)->assign(value); } -#if LANG_CXX11 -inline void FieldMask::set_paths(int index, ::std::string&& value) { +inline void FieldMask::set_paths(int index, std::string&& value) { // @@protoc_insertion_point(field_set:google.protobuf.FieldMask.paths) paths_.Mutable(index)->assign(std::move(value)); } -#endif inline void FieldMask::set_paths(int index, const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); paths_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.protobuf.FieldMask.paths) } @@ -225,22 +261,20 @@ inline void FieldMask::set_paths(int index, const char* value, size_t size) { reinterpret_cast(value), size); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldMask.paths) } -inline ::std::string* FieldMask::add_paths() { +inline std::string* FieldMask::add_paths() { // @@protoc_insertion_point(field_add_mutable:google.protobuf.FieldMask.paths) return paths_.Add(); } -inline void FieldMask::add_paths(const ::std::string& value) { +inline void FieldMask::add_paths(const std::string& value) { paths_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.protobuf.FieldMask.paths) } -#if LANG_CXX11 -inline void FieldMask::add_paths(::std::string&& value) { +inline void FieldMask::add_paths(std::string&& value) { paths_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.protobuf.FieldMask.paths) } -#endif inline void FieldMask::add_paths(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); paths_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.protobuf.FieldMask.paths) } @@ -248,12 +282,12 @@ inline void FieldMask::add_paths(const char* value, size_t size) { paths_.Add()->assign(reinterpret_cast(value), size); // @@protoc_insertion_point(field_add_pointer:google.protobuf.FieldMask.paths) } -inline const ::google::protobuf::RepeatedPtrField< ::std::string>& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& FieldMask::paths() const { // @@protoc_insertion_point(field_list:google.protobuf.FieldMask.paths) return paths_; } -inline ::google::protobuf::RepeatedPtrField< ::std::string>* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* FieldMask::mutable_paths() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FieldMask.paths) return &paths_; @@ -265,9 +299,9 @@ FieldMask::mutable_paths() { // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto diff --git a/third_party/protobuf/src/google/protobuf/field_mask.proto b/third_party/protobuf/src/google/protobuf/field_mask.proto index 76e09f39..4015b1a3 100644 --- a/third_party/protobuf/src/google/protobuf/field_mask.proto +++ b/third_party/protobuf/src/google/protobuf/field_mask.proto @@ -38,6 +38,7 @@ option java_outer_classname = "FieldMaskProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option go_package = "google.golang.org/genproto/protobuf/field_mask;field_mask"; +option cc_enable_arenas = true; // `FieldMask` represents a set of symbolic field paths, for example: // @@ -107,57 +108,49 @@ option go_package = "google.golang.org/genproto/protobuf/field_mask;field_mask"; // describe the updated values, the API ignores the values of all // fields not covered by the mask. // -// If a repeated field is specified for an update operation, the existing -// repeated values in the target resource will be overwritten by the new values. -// Note that a repeated field is only allowed in the last position of a `paths` -// string. +// If a repeated field is specified for an update operation, new values will +// be appended to the existing repeated field in the target resource. Note that +// a repeated field is only allowed in the last position of a `paths` string. // // If a sub-message is specified in the last position of the field mask for an -// update operation, then the existing sub-message in the target resource is -// overwritten. Given the target message: +// update operation, then new value will be merged into the existing sub-message +// in the target resource. +// +// For example, given the target message: // // f { // b { -// d : 1 -// x : 2 +// d: 1 +// x: 2 // } -// c : 1 +// c: [1] // } // // And an update message: // // f { // b { -// d : 10 +// d: 10 // } +// c: [2] // } // // then if the field mask is: // -// paths: "f.b" +// paths: ["f.b", "f.c"] // // then the result will be: // // f { // b { -// d : 10 +// d: 10 +// x: 2 // } -// c : 1 +// c: [1, 2] // } // -// However, if the update mask was: -// -// paths: "f.b.d" -// -// then the result would be: -// -// f { -// b { -// d : 10 -// x : 2 -// } -// c : 1 -// } +// An implementation may provide options to override this default behavior for +// repeated and message fields. // // In order to reset a field's value to the default, the field must // be in the mask and set to the default value in the provided resource. diff --git a/third_party/protobuf/src/google/protobuf/generated_enum_reflection.h b/third_party/protobuf/src/google/protobuf/generated_enum_reflection.h index 983d3185..c25e51bc 100644 --- a/third_party/protobuf/src/google/protobuf/generated_enum_reflection.h +++ b/third_party/protobuf/src/google/protobuf/generated_enum_reflection.h @@ -42,12 +42,21 @@ #include #include +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + +#include namespace google { namespace protobuf { - class EnumDescriptor; +class EnumDescriptor; } // namespace protobuf +} // namespace google +namespace google { namespace protobuf { // Returns the EnumDescriptor for enum type E, which must be a @@ -58,16 +67,14 @@ const EnumDescriptor* GetEnumDescriptor(); namespace internal { -// Helper for EnumType_Parse functions: try to parse the string 'name' as an -// enum name of the given type, returning true and filling in value on success, -// or returning false and leaving value unchanged on failure. -LIBPROTOBUF_EXPORT bool ParseNamedEnum(const EnumDescriptor* descriptor, - const string& name, - int* value); +// Helper for EnumType_Parse functions: try to parse the string 'name' as +// an enum name of the given type, returning true and filling in value on +// success, or returning false and leaving value unchanged on failure. +PROTOBUF_EXPORT bool ParseNamedEnum(const EnumDescriptor* descriptor, + const std::string& name, int* value); -template -bool ParseNamedEnum(const EnumDescriptor* descriptor, - const string& name, +template +bool ParseNamedEnum(const EnumDescriptor* descriptor, const std::string& name, EnumType* value) { int tmp; if (!ParseNamedEnum(descriptor, name, &tmp)) return false; @@ -78,10 +85,13 @@ bool ParseNamedEnum(const EnumDescriptor* descriptor, // Just a wrapper around printing the name of a value. The main point of this // function is not to be inlined, so that you can do this without including // descriptor.h. -LIBPROTOBUF_EXPORT const string& NameOfEnum(const EnumDescriptor* descriptor, int value); +PROTOBUF_EXPORT const std::string& NameOfEnum(const EnumDescriptor* descriptor, + int value); } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_GENERATED_ENUM_REFLECTION_H__ diff --git a/third_party/protobuf/src/google/protobuf/generated_enum_util.h b/third_party/protobuf/src/google/protobuf/generated_enum_util.h index 96b03cc9..55db124c 100644 --- a/third_party/protobuf/src/google/protobuf/generated_enum_util.h +++ b/third_party/protobuf/src/google/protobuf/generated_enum_util.h @@ -33,14 +33,19 @@ #include +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + namespace google { namespace protobuf { // This type trait can be used to cause templates to only match proto2 enum // types. -template struct is_proto_enum : ::std::false_type {}; +template +struct is_proto_enum : ::std::false_type {}; } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_GENERATED_ENUM_UTIL_H__ diff --git a/third_party/protobuf/src/google/protobuf/generated_message_reflection.cc b/third_party/protobuf/src/google/protobuf/generated_message_reflection.cc index 74ad00e7..52e8746d 100644 --- a/third_party/protobuf/src/google/protobuf/generated_message_reflection.cc +++ b/third_party/protobuf/src/google/protobuf/generated_message_reflection.cc @@ -44,10 +44,14 @@ #include #include #include +#include +#include #include #include +#include + #define GOOGLE_PROTOBUF_HAS_ONEOF namespace google { @@ -55,13 +59,10 @@ namespace protobuf { namespace internal { namespace { -bool IsMapFieldInApi(const FieldDescriptor* field) { - return field->is_map(); -} +bool IsMapFieldInApi(const FieldDescriptor* field) { return field->is_map(); } } // anonymous namespace -bool ParseNamedEnum(const EnumDescriptor* descriptor, - const string& name, +bool ParseNamedEnum(const EnumDescriptor* descriptor, const std::string& name, int* value) { const EnumValueDescriptor* d = descriptor->FindValueByName(name); if (d == NULL) return false; @@ -69,7 +70,7 @@ bool ParseNamedEnum(const EnumDescriptor* descriptor, return true; } -const string& NameOfEnum(const EnumDescriptor* descriptor, int value) { +const std::string& NameOfEnum(const EnumDescriptor* descriptor, int value) { const EnumValueDescriptor* d = descriptor->FindValueByNumber(value); return (d == NULL ? GetEmptyString() : d->name()); } @@ -96,89 +97,102 @@ const To& GetConstRefAtOffset(const Message& message, uint32 offset) { return *GetConstPointerAtOffset(&message, offset); } -void ReportReflectionUsageError( - const Descriptor* descriptor, const FieldDescriptor* field, - const char* method, const char* description) { - GOOGLE_LOG(FATAL) - << "Protocol Buffer reflection usage error:\n" - " Method : google::protobuf::Reflection::" << method << "\n" - " Message type: " << descriptor->full_name() << "\n" - " Field : " << field->full_name() << "\n" - " Problem : " << description; +void ReportReflectionUsageError(const Descriptor* descriptor, + const FieldDescriptor* field, + const char* method, const char* description) { + GOOGLE_LOG(FATAL) << "Protocol Buffer reflection usage error:\n" + " Method : google::protobuf::Reflection::" + << method + << "\n" + " Message type: " + << descriptor->full_name() + << "\n" + " Field : " + << field->full_name() + << "\n" + " Problem : " + << description; } const char* cpptype_names_[FieldDescriptor::MAX_CPPTYPE + 1] = { - "INVALID_CPPTYPE", - "CPPTYPE_INT32", - "CPPTYPE_INT64", - "CPPTYPE_UINT32", - "CPPTYPE_UINT64", - "CPPTYPE_DOUBLE", - "CPPTYPE_FLOAT", - "CPPTYPE_BOOL", - "CPPTYPE_ENUM", - "CPPTYPE_STRING", - "CPPTYPE_MESSAGE" -}; + "INVALID_CPPTYPE", "CPPTYPE_INT32", "CPPTYPE_INT64", "CPPTYPE_UINT32", + "CPPTYPE_UINT64", "CPPTYPE_DOUBLE", "CPPTYPE_FLOAT", "CPPTYPE_BOOL", + "CPPTYPE_ENUM", "CPPTYPE_STRING", "CPPTYPE_MESSAGE"}; static void ReportReflectionUsageTypeError( const Descriptor* descriptor, const FieldDescriptor* field, - const char* method, - FieldDescriptor::CppType expected_type) { + const char* method, FieldDescriptor::CppType expected_type) { GOOGLE_LOG(FATAL) - << "Protocol Buffer reflection usage error:\n" - " Method : google::protobuf::Reflection::" << method << "\n" - " Message type: " << descriptor->full_name() << "\n" - " Field : " << field->full_name() << "\n" - " Problem : Field is not the right type for this message:\n" - " Expected : " << cpptype_names_[expected_type] << "\n" - " Field type: " << cpptype_names_[field->cpp_type()]; + << "Protocol Buffer reflection usage error:\n" + " Method : google::protobuf::Reflection::" + << method + << "\n" + " Message type: " + << descriptor->full_name() + << "\n" + " Field : " + << field->full_name() + << "\n" + " Problem : Field is not the right type for this message:\n" + " Expected : " + << cpptype_names_[expected_type] + << "\n" + " Field type: " + << cpptype_names_[field->cpp_type()]; } static void ReportReflectionUsageEnumTypeError( const Descriptor* descriptor, const FieldDescriptor* field, const char* method, const EnumValueDescriptor* value) { - GOOGLE_LOG(FATAL) - << "Protocol Buffer reflection usage error:\n" - " Method : google::protobuf::Reflection::" << method << "\n" - " Message type: " << descriptor->full_name() << "\n" - " Field : " << field->full_name() << "\n" - " Problem : Enum value did not match field type:\n" - " Expected : " << field->enum_type()->full_name() << "\n" - " Actual : " << value->full_name(); + GOOGLE_LOG(FATAL) << "Protocol Buffer reflection usage error:\n" + " Method : google::protobuf::Reflection::" + << method + << "\n" + " Message type: " + << descriptor->full_name() + << "\n" + " Field : " + << field->full_name() + << "\n" + " Problem : Enum value did not match field type:\n" + " Expected : " + << field->enum_type()->full_name() + << "\n" + " Actual : " + << value->full_name(); } -#define USAGE_CHECK(CONDITION, METHOD, ERROR_DESCRIPTION) \ - if (!(CONDITION)) \ - ReportReflectionUsageError(descriptor_, field, #METHOD, ERROR_DESCRIPTION) -#define USAGE_CHECK_EQ(A, B, METHOD, ERROR_DESCRIPTION) \ +#define USAGE_CHECK(CONDITION, METHOD, ERROR_DESCRIPTION) \ + if (!(CONDITION)) \ + ReportReflectionUsageError(descriptor_, field, #METHOD, ERROR_DESCRIPTION) +#define USAGE_CHECK_EQ(A, B, METHOD, ERROR_DESCRIPTION) \ USAGE_CHECK((A) == (B), METHOD, ERROR_DESCRIPTION) -#define USAGE_CHECK_NE(A, B, METHOD, ERROR_DESCRIPTION) \ +#define USAGE_CHECK_NE(A, B, METHOD, ERROR_DESCRIPTION) \ USAGE_CHECK((A) != (B), METHOD, ERROR_DESCRIPTION) -#define USAGE_CHECK_TYPE(METHOD, CPPTYPE) \ - if (field->cpp_type() != FieldDescriptor::CPPTYPE_##CPPTYPE) \ - ReportReflectionUsageTypeError(descriptor_, field, #METHOD, \ - FieldDescriptor::CPPTYPE_##CPPTYPE) +#define USAGE_CHECK_TYPE(METHOD, CPPTYPE) \ + if (field->cpp_type() != FieldDescriptor::CPPTYPE_##CPPTYPE) \ + ReportReflectionUsageTypeError(descriptor_, field, #METHOD, \ + FieldDescriptor::CPPTYPE_##CPPTYPE) -#define USAGE_CHECK_ENUM_VALUE(METHOD) \ - if (value->type() != field->enum_type()) \ - ReportReflectionUsageEnumTypeError(descriptor_, field, #METHOD, value) +#define USAGE_CHECK_ENUM_VALUE(METHOD) \ + if (value->type() != field->enum_type()) \ + ReportReflectionUsageEnumTypeError(descriptor_, field, #METHOD, value) -#define USAGE_CHECK_MESSAGE_TYPE(METHOD) \ - USAGE_CHECK_EQ(field->containing_type(), descriptor_, \ - METHOD, "Field does not match message type."); -#define USAGE_CHECK_SINGULAR(METHOD) \ - USAGE_CHECK_NE(field->label(), FieldDescriptor::LABEL_REPEATED, METHOD, \ +#define USAGE_CHECK_MESSAGE_TYPE(METHOD) \ + USAGE_CHECK_EQ(field->containing_type(), descriptor_, METHOD, \ + "Field does not match message type."); +#define USAGE_CHECK_SINGULAR(METHOD) \ + USAGE_CHECK_NE(field->label(), FieldDescriptor::LABEL_REPEATED, METHOD, \ "Field is repeated; the method requires a singular field.") -#define USAGE_CHECK_REPEATED(METHOD) \ - USAGE_CHECK_EQ(field->label(), FieldDescriptor::LABEL_REPEATED, METHOD, \ +#define USAGE_CHECK_REPEATED(METHOD) \ + USAGE_CHECK_EQ(field->label(), FieldDescriptor::LABEL_REPEATED, METHOD, \ "Field is singular; the method requires a repeated field.") -#define USAGE_CHECK_ALL(METHOD, LABEL, CPPTYPE) \ - USAGE_CHECK_MESSAGE_TYPE(METHOD); \ - USAGE_CHECK_##LABEL(METHOD); \ - USAGE_CHECK_TYPE(METHOD, CPPTYPE) +#define USAGE_CHECK_ALL(METHOD, LABEL, CPPTYPE) \ + USAGE_CHECK_MESSAGE_TYPE(METHOD); \ + USAGE_CHECK_##LABEL(METHOD); \ + USAGE_CHECK_TYPE(METHOD, CPPTYPE) } // namespace @@ -200,15 +214,7 @@ GeneratedMessageReflection::~GeneratedMessageReflection() {} const UnknownFieldSet& GeneratedMessageReflection::GetUnknownFields( const Message& message) const { - if (descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 && - !GetProto3PreserveUnknownsDefault()) { - // We have to ensure that any mutations made to the return value of - // MutableUnknownFields() are not reflected here when Proto3 defaults to - // discard unknowns. - return *UnknownFieldSet::default_instance(); - } else { - return GetInternalMetadataWithArena(message).unknown_fields(); - } + return GetInternalMetadataWithArena(message).unknown_fields(); } UnknownFieldSet* GeneratedMessageReflection::MutableUnknownFields( @@ -231,28 +237,29 @@ size_t GeneratedMessageReflection::SpaceUsedLong(const Message& message) const { const FieldDescriptor* field = descriptor_->field(i); if (field->is_repeated()) { switch (field->cpp_type()) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case FieldDescriptor::CPPTYPE_##UPPERCASE : \ - total_size += GetRaw >(message, field) \ - .SpaceUsedExcludingSelfLong(); \ - break +#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ + case FieldDescriptor::CPPTYPE_##UPPERCASE: \ + total_size += GetRaw >(message, field) \ + .SpaceUsedExcludingSelfLong(); \ + break - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); + HANDLE_TYPE(INT32, int32); + HANDLE_TYPE(INT64, int64); HANDLE_TYPE(UINT32, uint32); HANDLE_TYPE(UINT64, uint64); HANDLE_TYPE(DOUBLE, double); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, int); + HANDLE_TYPE(FLOAT, float); + HANDLE_TYPE(BOOL, bool); + HANDLE_TYPE(ENUM, int); #undef HANDLE_TYPE case FieldDescriptor::CPPTYPE_STRING: switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: - total_size += GetRaw >(message, field) - .SpaceUsedExcludingSelfLong(); + total_size += + GetRaw >(message, field) + .SpaceUsedExcludingSelfLong(); break; } break; @@ -276,14 +283,14 @@ size_t GeneratedMessageReflection::SpaceUsedLong(const Message& message) const { continue; } switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32 : - case FieldDescriptor::CPPTYPE_INT64 : + case FieldDescriptor::CPPTYPE_INT32: + case FieldDescriptor::CPPTYPE_INT64: case FieldDescriptor::CPPTYPE_UINT32: case FieldDescriptor::CPPTYPE_UINT64: case FieldDescriptor::CPPTYPE_DOUBLE: - case FieldDescriptor::CPPTYPE_FLOAT : - case FieldDescriptor::CPPTYPE_BOOL : - case FieldDescriptor::CPPTYPE_ENUM : + case FieldDescriptor::CPPTYPE_FLOAT: + case FieldDescriptor::CPPTYPE_BOOL: + case FieldDescriptor::CPPTYPE_ENUM: // Field is inline, so we've already counted it. break; @@ -292,18 +299,18 @@ size_t GeneratedMessageReflection::SpaceUsedLong(const Message& message) const { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: { if (IsInlined(field)) { - const string* ptr = + const std::string* ptr = &GetField(message, field).GetNoArena(); total_size += StringSpaceUsedExcludingSelfLong(*ptr); break; } - // Initially, the string points to the default value stored in - // the prototype. Only count the string if it has been changed - // from the default value. - const string* default_ptr = + // Initially, the string points to the default value stored + // in the prototype. Only count the string if it has been + // changed from the default value. + const std::string* default_ptr = &DefaultRaw(field).Get(); - const string* ptr = + const std::string* ptr = &GetField(message, field).Get(); if (ptr != default_ptr) { @@ -335,49 +342,44 @@ size_t GeneratedMessageReflection::SpaceUsedLong(const Message& message) const { return total_size; } -void GeneratedMessageReflection::SwapField( - Message* message1, - Message* message2, - const FieldDescriptor* field) const { +void GeneratedMessageReflection::SwapField(Message* message1, Message* message2, + const FieldDescriptor* field) const { if (field->is_repeated()) { switch (field->cpp_type()) { -#define SWAP_ARRAYS(CPPTYPE, TYPE) \ - case FieldDescriptor::CPPTYPE_##CPPTYPE: \ - MutableRaw >(message1, field)->Swap( \ - MutableRaw >(message2, field)); \ - break; +#define SWAP_ARRAYS(CPPTYPE, TYPE) \ + case FieldDescriptor::CPPTYPE_##CPPTYPE: \ + MutableRaw >(message1, field) \ + ->Swap(MutableRaw >(message2, field)); \ + break; - SWAP_ARRAYS(INT32 , int32 ); - SWAP_ARRAYS(INT64 , int64 ); + SWAP_ARRAYS(INT32, int32); + SWAP_ARRAYS(INT64, int64); SWAP_ARRAYS(UINT32, uint32); SWAP_ARRAYS(UINT64, uint64); - SWAP_ARRAYS(FLOAT , float ); + SWAP_ARRAYS(FLOAT, float); SWAP_ARRAYS(DOUBLE, double); - SWAP_ARRAYS(BOOL , bool ); - SWAP_ARRAYS(ENUM , int ); + SWAP_ARRAYS(BOOL, bool); + SWAP_ARRAYS(ENUM, int); #undef SWAP_ARRAYS case FieldDescriptor::CPPTYPE_STRING: switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: - MutableRaw(message1, field)-> - Swap >( + MutableRaw(message1, field) + ->Swap >( MutableRaw(message2, field)); break; } break; case FieldDescriptor::CPPTYPE_MESSAGE: if (IsMapFieldInApi(field)) { - MutableRaw(message1, field)-> - MutableRepeatedField()-> - Swap >( - MutableRaw(message2, field)-> - MutableRepeatedField()); + MutableRaw(message1, field) + ->Swap(MutableRaw(message2, field)); } else { - MutableRaw(message1, field)-> - Swap >( - MutableRaw(message2, field)); + MutableRaw(message1, field) + ->Swap >( + MutableRaw(message2, field)); } break; @@ -386,20 +388,20 @@ void GeneratedMessageReflection::SwapField( } } else { switch (field->cpp_type()) { -#define SWAP_VALUES(CPPTYPE, TYPE) \ - case FieldDescriptor::CPPTYPE_##CPPTYPE: \ - std::swap(*MutableRaw(message1, field), \ - *MutableRaw(message2, field)); \ - break; +#define SWAP_VALUES(CPPTYPE, TYPE) \ + case FieldDescriptor::CPPTYPE_##CPPTYPE: \ + std::swap(*MutableRaw(message1, field), \ + *MutableRaw(message2, field)); \ + break; - SWAP_VALUES(INT32 , int32 ); - SWAP_VALUES(INT64 , int64 ); + SWAP_VALUES(INT32, int32); + SWAP_VALUES(INT64, int64); SWAP_VALUES(UINT32, uint32); SWAP_VALUES(UINT64, uint64); - SWAP_VALUES(FLOAT , float ); + SWAP_VALUES(FLOAT, float); SWAP_VALUES(DOUBLE, double); - SWAP_VALUES(BOOL , bool ); - SWAP_VALUES(ENUM , int ); + SWAP_VALUES(BOOL, bool); + SWAP_VALUES(ENUM, int); #undef SWAP_VALUES case FieldDescriptor::CPPTYPE_MESSAGE: if (GetArena(message1) == GetArena(message2)) { @@ -428,35 +430,33 @@ void GeneratedMessageReflection::SwapField( case FieldDescriptor::CPPTYPE_STRING: switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: - { - Arena* arena1 = GetArena(message1); - Arena* arena2 = GetArena(message2); + case FieldOptions::STRING: { + Arena* arena1 = GetArena(message1); + Arena* arena2 = GetArena(message2); - if (IsInlined(field)) { - InlinedStringField* string1 = - MutableRaw(message1, field); - InlinedStringField* string2 = - MutableRaw(message2, field); - string1->Swap(string2); - break; - } - - ArenaStringPtr* string1 = - MutableRaw(message1, field); - ArenaStringPtr* string2 = - MutableRaw(message2, field); - const string* default_ptr = - &DefaultRaw(field).Get(); - if (arena1 == arena2) { - string1->Swap(string2, default_ptr, arena1); - } else { - const string temp = string1->Get(); - string1->Set(default_ptr, string2->Get(), arena1); - string2->Set(default_ptr, temp, arena2); - } + if (IsInlined(field)) { + InlinedStringField* string1 = + MutableRaw(message1, field); + InlinedStringField* string2 = + MutableRaw(message2, field); + string1->Swap(string2); + break; } - break; + + ArenaStringPtr* string1 = + MutableRaw(message1, field); + ArenaStringPtr* string2 = + MutableRaw(message2, field); + const std::string* default_ptr = + &DefaultRaw(field).Get(); + if (arena1 == arena2) { + string1->Swap(string2, default_ptr, arena1); + } else { + const std::string temp = string1->Get(); + string1->Set(default_ptr, string2->Get(), arena1); + string2->Set(default_ptr, temp, arena2); + } + } break; } break; @@ -467,8 +467,7 @@ void GeneratedMessageReflection::SwapField( } void GeneratedMessageReflection::SwapOneofField( - Message* message1, - Message* message2, + Message* message1, Message* message2, const OneofDescriptor* oneof_descriptor) const { uint32 oneof_case1 = GetOneofCase(*message1, oneof_descriptor); uint32 oneof_case2 = GetOneofCase(*message2, oneof_descriptor); @@ -482,27 +481,27 @@ void GeneratedMessageReflection::SwapOneofField( bool temp_bool; int temp_int; Message* temp_message = NULL; - string temp_string; + std::string temp_string; // Stores message1's oneof field to a temp variable. const FieldDescriptor* field1 = NULL; if (oneof_case1 > 0) { field1 = descriptor_->FindFieldByNumber(oneof_case1); - //oneof_descriptor->field(oneof_case1); + // oneof_descriptor->field(oneof_case1); switch (field1->cpp_type()) { -#define GET_TEMP_VALUE(CPPTYPE, TYPE) \ - case FieldDescriptor::CPPTYPE_##CPPTYPE: \ - temp_##TYPE = GetField(*message1, field1); \ - break; +#define GET_TEMP_VALUE(CPPTYPE, TYPE) \ + case FieldDescriptor::CPPTYPE_##CPPTYPE: \ + temp_##TYPE = GetField(*message1, field1); \ + break; - GET_TEMP_VALUE(INT32 , int32 ); - GET_TEMP_VALUE(INT64 , int64 ); + GET_TEMP_VALUE(INT32, int32); + GET_TEMP_VALUE(INT64, int64); GET_TEMP_VALUE(UINT32, uint32); GET_TEMP_VALUE(UINT64, uint64); - GET_TEMP_VALUE(FLOAT , float ); + GET_TEMP_VALUE(FLOAT, float); GET_TEMP_VALUE(DOUBLE, double); - GET_TEMP_VALUE(BOOL , bool ); - GET_TEMP_VALUE(ENUM , int ); + GET_TEMP_VALUE(BOOL, bool); + GET_TEMP_VALUE(ENUM, int); #undef GET_TEMP_VALUE case FieldDescriptor::CPPTYPE_MESSAGE: temp_message = ReleaseMessage(message1, field1); @@ -519,27 +518,24 @@ void GeneratedMessageReflection::SwapOneofField( // Sets message1's oneof field from the message2's oneof field. if (oneof_case2 > 0) { - const FieldDescriptor* field2 = - descriptor_->FindFieldByNumber(oneof_case2); + const FieldDescriptor* field2 = descriptor_->FindFieldByNumber(oneof_case2); switch (field2->cpp_type()) { -#define SET_ONEOF_VALUE1(CPPTYPE, TYPE) \ - case FieldDescriptor::CPPTYPE_##CPPTYPE: \ - SetField(message1, field2, GetField(*message2, field2)); \ - break; +#define SET_ONEOF_VALUE1(CPPTYPE, TYPE) \ + case FieldDescriptor::CPPTYPE_##CPPTYPE: \ + SetField(message1, field2, GetField(*message2, field2)); \ + break; - SET_ONEOF_VALUE1(INT32 , int32 ); - SET_ONEOF_VALUE1(INT64 , int64 ); + SET_ONEOF_VALUE1(INT32, int32); + SET_ONEOF_VALUE1(INT64, int64); SET_ONEOF_VALUE1(UINT32, uint32); SET_ONEOF_VALUE1(UINT64, uint64); - SET_ONEOF_VALUE1(FLOAT , float ); + SET_ONEOF_VALUE1(FLOAT, float); SET_ONEOF_VALUE1(DOUBLE, double); - SET_ONEOF_VALUE1(BOOL , bool ); - SET_ONEOF_VALUE1(ENUM , int ); + SET_ONEOF_VALUE1(BOOL, bool); + SET_ONEOF_VALUE1(ENUM, int); #undef SET_ONEOF_VALUE1 case FieldDescriptor::CPPTYPE_MESSAGE: - SetAllocatedMessage(message1, - ReleaseMessage(message2, field2), - field2); + SetAllocatedMessage(message1, ReleaseMessage(message2, field2), field2); break; case FieldDescriptor::CPPTYPE_STRING: @@ -556,19 +552,19 @@ void GeneratedMessageReflection::SwapOneofField( // Sets message2's oneof field from the temp variable. if (oneof_case1 > 0) { switch (field1->cpp_type()) { -#define SET_ONEOF_VALUE2(CPPTYPE, TYPE) \ - case FieldDescriptor::CPPTYPE_##CPPTYPE: \ - SetField(message2, field1, temp_##TYPE); \ - break; +#define SET_ONEOF_VALUE2(CPPTYPE, TYPE) \ + case FieldDescriptor::CPPTYPE_##CPPTYPE: \ + SetField(message2, field1, temp_##TYPE); \ + break; - SET_ONEOF_VALUE2(INT32 , int32 ); - SET_ONEOF_VALUE2(INT64 , int64 ); + SET_ONEOF_VALUE2(INT32, int32); + SET_ONEOF_VALUE2(INT64, int64); SET_ONEOF_VALUE2(UINT32, uint32); SET_ONEOF_VALUE2(UINT64, uint64); - SET_ONEOF_VALUE2(FLOAT , float ); + SET_ONEOF_VALUE2(FLOAT, float); SET_ONEOF_VALUE2(DOUBLE, double); - SET_ONEOF_VALUE2(BOOL , bool ); - SET_ONEOF_VALUE2(ENUM , int ); + SET_ONEOF_VALUE2(BOOL, bool); + SET_ONEOF_VALUE2(ENUM, int); #undef SET_ONEOF_VALUE2 case FieldDescriptor::CPPTYPE_MESSAGE: SetAllocatedMessage(message2, temp_message, field1); @@ -586,26 +582,27 @@ void GeneratedMessageReflection::SwapOneofField( } } -void GeneratedMessageReflection::Swap( - Message* message1, - Message* message2) const { +void GeneratedMessageReflection::Swap(Message* message1, + Message* message2) const { if (message1 == message2) return; // TODO(kenton): Other Reflection methods should probably check this too. GOOGLE_CHECK_EQ(message1->GetReflection(), this) - << "First argument to Swap() (of type \"" - << message1->GetDescriptor()->full_name() - << "\") is not compatible with this reflection object (which is for type \"" - << descriptor_->full_name() - << "\"). Note that the exact same class is required; not just the same " - "descriptor."; + << "First argument to Swap() (of type \"" + << message1->GetDescriptor()->full_name() + << "\") is not compatible with this reflection object (which is for type " + "\"" + << descriptor_->full_name() + << "\"). Note that the exact same class is required; not just the same " + "descriptor."; GOOGLE_CHECK_EQ(message2->GetReflection(), this) - << "Second argument to Swap() (of type \"" - << message2->GetDescriptor()->full_name() - << "\") is not compatible with this reflection object (which is for type \"" - << descriptor_->full_name() - << "\"). Note that the exact same class is required; not just the same " - "descriptor."; + << "Second argument to Swap() (of type \"" + << message2->GetDescriptor()->full_name() + << "\") is not compatible with this reflection object (which is for type " + "\"" + << descriptor_->full_name() + << "\"). Note that the exact same class is required; not just the same " + "descriptor."; // Check that both messages are in the same arena (or both on the heap). We // need to copy all data if not, due to ownership semantics. @@ -660,26 +657,27 @@ void GeneratedMessageReflection::Swap( } void GeneratedMessageReflection::SwapFields( - Message* message1, - Message* message2, + Message* message1, Message* message2, const std::vector& fields) const { if (message1 == message2) return; // TODO(kenton): Other Reflection methods should probably check this too. GOOGLE_CHECK_EQ(message1->GetReflection(), this) - << "First argument to SwapFields() (of type \"" - << message1->GetDescriptor()->full_name() - << "\") is not compatible with this reflection object (which is for type \"" - << descriptor_->full_name() - << "\"). Note that the exact same class is required; not just the same " - "descriptor."; + << "First argument to SwapFields() (of type \"" + << message1->GetDescriptor()->full_name() + << "\") is not compatible with this reflection object (which is for type " + "\"" + << descriptor_->full_name() + << "\"). Note that the exact same class is required; not just the same " + "descriptor."; GOOGLE_CHECK_EQ(message2->GetReflection(), this) - << "Second argument to SwapFields() (of type \"" - << message2->GetDescriptor()->full_name() - << "\") is not compatible with this reflection object (which is for type \"" - << descriptor_->full_name() - << "\"). Note that the exact same class is required; not just the same " - "descriptor."; + << "Second argument to SwapFields() (of type \"" + << message2->GetDescriptor()->full_name() + << "\") is not compatible with this reflection object (which is for type " + "\"" + << descriptor_->full_name() + << "\"). Note that the exact same class is required; not just the same " + "descriptor."; std::set swapped_oneof; @@ -688,8 +686,7 @@ void GeneratedMessageReflection::SwapFields( const FieldDescriptor* field = fields[i]; if (field->is_extension()) { MutableExtensionSet(message1)->SwapExtension( - MutableExtensionSet(message2), - field->number()); + MutableExtensionSet(message2), field->number()); } else { if (field->containing_oneof()) { int oneof_index = field->containing_oneof()->index(); @@ -739,18 +736,18 @@ int GeneratedMessageReflection::FieldSize(const Message& message, return GetExtensionSet(message).ExtensionSize(field->number()); } else { switch (field->cpp_type()) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case FieldDescriptor::CPPTYPE_##UPPERCASE : \ - return GetRaw >(message, field).size() +#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ + case FieldDescriptor::CPPTYPE_##UPPERCASE: \ + return GetRaw >(message, field).size() - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); + HANDLE_TYPE(INT32, int32); + HANDLE_TYPE(INT64, int64); HANDLE_TYPE(UINT32, uint32); HANDLE_TYPE(UINT64, uint64); HANDLE_TYPE(DOUBLE, double); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, int); + HANDLE_TYPE(FLOAT, float); + HANDLE_TYPE(BOOL, bool); + HANDLE_TYPE(ENUM, int); #undef HANDLE_TYPE case FieldDescriptor::CPPTYPE_STRING: @@ -791,24 +788,23 @@ void GeneratedMessageReflection::ClearField( // We need to set the field back to its default value. switch (field->cpp_type()) { -#define CLEAR_TYPE(CPPTYPE, TYPE) \ - case FieldDescriptor::CPPTYPE_##CPPTYPE: \ - *MutableRaw(message, field) = \ - field->default_value_##TYPE(); \ - break; +#define CLEAR_TYPE(CPPTYPE, TYPE) \ + case FieldDescriptor::CPPTYPE_##CPPTYPE: \ + *MutableRaw(message, field) = field->default_value_##TYPE(); \ + break; - CLEAR_TYPE(INT32 , int32 ); - CLEAR_TYPE(INT64 , int64 ); + CLEAR_TYPE(INT32, int32); + CLEAR_TYPE(INT64, int64); CLEAR_TYPE(UINT32, uint32); CLEAR_TYPE(UINT64, uint64); - CLEAR_TYPE(FLOAT , float ); + CLEAR_TYPE(FLOAT, float); CLEAR_TYPE(DOUBLE, double); - CLEAR_TYPE(BOOL , bool ); + CLEAR_TYPE(BOOL, bool); #undef CLEAR_TYPE case FieldDescriptor::CPPTYPE_ENUM: *MutableRaw(message, field) = - field->default_value_enum()->number(); + field->default_value_enum()->number(); break; case FieldDescriptor::CPPTYPE_STRING: { @@ -816,17 +812,17 @@ void GeneratedMessageReflection::ClearField( default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: { if (IsInlined(field)) { - const string* default_ptr = + const std::string* default_ptr = &DefaultRaw(field).GetNoArena(); - MutableRaw(message, field)->SetNoArena( - default_ptr, *default_ptr); + MutableRaw(message, field) + ->SetNoArena(default_ptr, *default_ptr); break; } - const string* default_ptr = + const std::string* default_ptr = &DefaultRaw(field).Get(); - MutableRaw(message, field)->SetAllocated( - default_ptr, NULL, GetArena(message)); + MutableRaw(message, field) + ->SetAllocated(default_ptr, NULL, GetArena(message)); break; } } @@ -849,26 +845,26 @@ void GeneratedMessageReflection::ClearField( } } else { switch (field->cpp_type()) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case FieldDescriptor::CPPTYPE_##UPPERCASE : \ - MutableRaw >(message, field)->Clear(); \ - break +#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ + case FieldDescriptor::CPPTYPE_##UPPERCASE: \ + MutableRaw >(message, field)->Clear(); \ + break - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); + HANDLE_TYPE(INT32, int32); + HANDLE_TYPE(INT64, int64); HANDLE_TYPE(UINT32, uint32); HANDLE_TYPE(UINT64, uint64); HANDLE_TYPE(DOUBLE, double); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, int); + HANDLE_TYPE(FLOAT, float); + HANDLE_TYPE(BOOL, bool); + HANDLE_TYPE(ENUM, int); #undef HANDLE_TYPE case FieldDescriptor::CPPTYPE_STRING: { switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: - MutableRaw >(message, field)->Clear(); + MutableRaw >(message, field)->Clear(); break; } break; @@ -876,9 +872,7 @@ void GeneratedMessageReflection::ClearField( case FieldDescriptor::CPPTYPE_MESSAGE: { if (IsMapFieldInApi(field)) { - MutableRaw(message, field) - ->MutableRepeatedField() - ->Clear >(); + MutableRaw(message, field)->Clear(); } else { // We don't know which subclass of RepeatedPtrFieldBase the type is, // so we use RepeatedPtrFieldBase directly. @@ -892,8 +886,7 @@ void GeneratedMessageReflection::ClearField( } void GeneratedMessageReflection::RemoveLast( - Message* message, - const FieldDescriptor* field) const { + Message* message, const FieldDescriptor* field) const { USAGE_CHECK_MESSAGE_TYPE(RemoveLast); USAGE_CHECK_REPEATED(RemoveLast); @@ -901,26 +894,27 @@ void GeneratedMessageReflection::RemoveLast( MutableExtensionSet(message)->RemoveLast(field->number()); } else { switch (field->cpp_type()) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case FieldDescriptor::CPPTYPE_##UPPERCASE : \ - MutableRaw >(message, field)->RemoveLast(); \ - break +#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ + case FieldDescriptor::CPPTYPE_##UPPERCASE: \ + MutableRaw >(message, field)->RemoveLast(); \ + break - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); + HANDLE_TYPE(INT32, int32); + HANDLE_TYPE(INT64, int64); HANDLE_TYPE(UINT32, uint32); HANDLE_TYPE(UINT64, uint64); HANDLE_TYPE(DOUBLE, double); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, int); + HANDLE_TYPE(FLOAT, float); + HANDLE_TYPE(BOOL, bool); + HANDLE_TYPE(ENUM, int); #undef HANDLE_TYPE case FieldDescriptor::CPPTYPE_STRING: switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: - MutableRaw >(message, field)->RemoveLast(); + MutableRaw >(message, field) + ->RemoveLast(); break; } break; @@ -932,7 +926,7 @@ void GeneratedMessageReflection::RemoveLast( ->RemoveLast >(); } else { MutableRaw(message, field) - ->RemoveLast >(); + ->RemoveLast >(); } break; } @@ -940,8 +934,7 @@ void GeneratedMessageReflection::RemoveLast( } Message* GeneratedMessageReflection::ReleaseLast( - Message* message, - const FieldDescriptor* field) const { + Message* message, const FieldDescriptor* field) const { USAGE_CHECK_ALL(ReleaseLast, REPEATED, MESSAGE); if (field->is_extension()) { @@ -954,16 +947,14 @@ Message* GeneratedMessageReflection::ReleaseLast( ->ReleaseLast >(); } else { return MutableRaw(message, field) - ->ReleaseLast >(); + ->ReleaseLast >(); } } } -void GeneratedMessageReflection::SwapElements( - Message* message, - const FieldDescriptor* field, - int index1, - int index2) const { +void GeneratedMessageReflection::SwapElements(Message* message, + const FieldDescriptor* field, + int index1, int index2) const { USAGE_CHECK_MESSAGE_TYPE(Swap); USAGE_CHECK_REPEATED(Swap); @@ -971,20 +962,20 @@ void GeneratedMessageReflection::SwapElements( MutableExtensionSet(message)->SwapElements(field->number(), index1, index2); } else { switch (field->cpp_type()) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case FieldDescriptor::CPPTYPE_##UPPERCASE : \ - MutableRaw >(message, field) \ - ->SwapElements(index1, index2); \ - break +#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ + case FieldDescriptor::CPPTYPE_##UPPERCASE: \ + MutableRaw >(message, field) \ + ->SwapElements(index1, index2); \ + break - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); + HANDLE_TYPE(INT32, int32); + HANDLE_TYPE(INT64, int64); HANDLE_TYPE(UINT32, uint32); HANDLE_TYPE(UINT64, uint64); HANDLE_TYPE(DOUBLE, double); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, int); + HANDLE_TYPE(FLOAT, float); + HANDLE_TYPE(BOOL, bool); + HANDLE_TYPE(ENUM, int); #undef HANDLE_TYPE case FieldDescriptor::CPPTYPE_STRING: @@ -995,7 +986,7 @@ void GeneratedMessageReflection::SwapElements( ->SwapElements(index1, index2); } else { MutableRaw(message, field) - ->SwapElements(index1, index2); + ->SwapElements(index1, index2); } break; } @@ -1011,8 +1002,8 @@ struct FieldNumberSorter { } }; -inline bool IsIndexInHasBitSet( - const uint32* has_bit_set, uint32 has_bit_index) { +inline bool IsIndexInHasBitSet(const uint32* has_bit_set, + uint32 has_bit_index) { GOOGLE_DCHECK_NE(has_bit_index, ~0u); return ((has_bit_set[has_bit_index / 32] >> (has_bit_index % 32)) & static_cast(1)) != 0; @@ -1020,8 +1011,7 @@ inline bool IsIndexInHasBitSet( } // namespace void GeneratedMessageReflection::ListFields( - const Message& message, - std::vector* output) const { + const Message& message, std::vector* output) const { output->clear(); // Optimization: The default instance never has any fields set. @@ -1035,8 +1025,6 @@ void GeneratedMessageReflection::ListFields( const uint32* const has_bits = schema_.HasHasbits() ? GetHasBits(message) : NULL; const uint32* const has_bits_indices = schema_.has_bit_indices_; - const uint32* const oneof_case_array = - GetConstPointerAtOffset(&message, schema_.oneof_case_offset_); output->reserve(descriptor_->field_count()); for (int i = 0; i <= last_non_weak_field_index_; i++) { const FieldDescriptor* field = descriptor_->field(i); @@ -1047,6 +1035,8 @@ void GeneratedMessageReflection::ListFields( } else { const OneofDescriptor* containing_oneof = field->containing_oneof(); if (containing_oneof) { + const uint32* const oneof_case_array = GetConstPointerAtOffset( + &message, schema_.oneof_case_offset_); // Equivalent to: HasOneofField(message, field) if (oneof_case_array[containing_oneof->index()] == field->number()) { output->push_back(field); @@ -1073,79 +1063,76 @@ void GeneratedMessageReflection::ListFields( // ------------------------------------------------------------------- #undef DEFINE_PRIMITIVE_ACCESSORS -#define DEFINE_PRIMITIVE_ACCESSORS(TYPENAME, TYPE, PASSTYPE, CPPTYPE) \ - PASSTYPE GeneratedMessageReflection::Get##TYPENAME( \ - const Message& message, const FieldDescriptor* field) const { \ - USAGE_CHECK_ALL(Get##TYPENAME, SINGULAR, CPPTYPE); \ - if (field->is_extension()) { \ - return GetExtensionSet(message).Get##TYPENAME( \ - field->number(), field->default_value_##PASSTYPE()); \ - } else { \ - return GetField(message, field); \ - } \ - } \ - \ - void GeneratedMessageReflection::Set##TYPENAME( \ - Message* message, const FieldDescriptor* field, \ - PASSTYPE value) const { \ - USAGE_CHECK_ALL(Set##TYPENAME, SINGULAR, CPPTYPE); \ - if (field->is_extension()) { \ - return MutableExtensionSet(message)->Set##TYPENAME( \ - field->number(), field->type(), value, field); \ - } else { \ - SetField(message, field, value); \ - } \ - } \ - \ - PASSTYPE GeneratedMessageReflection::GetRepeated##TYPENAME( \ - const Message& message, \ - const FieldDescriptor* field, int index) const { \ - USAGE_CHECK_ALL(GetRepeated##TYPENAME, REPEATED, CPPTYPE); \ - if (field->is_extension()) { \ - return GetExtensionSet(message).GetRepeated##TYPENAME( \ - field->number(), index); \ - } else { \ - return GetRepeatedField(message, field, index); \ - } \ - } \ - \ - void GeneratedMessageReflection::SetRepeated##TYPENAME( \ - Message* message, const FieldDescriptor* field, \ - int index, PASSTYPE value) const { \ - USAGE_CHECK_ALL(SetRepeated##TYPENAME, REPEATED, CPPTYPE); \ - if (field->is_extension()) { \ - MutableExtensionSet(message)->SetRepeated##TYPENAME( \ - field->number(), index, value); \ - } else { \ - SetRepeatedField(message, field, index, value); \ - } \ - } \ - \ - void GeneratedMessageReflection::Add##TYPENAME( \ - Message* message, const FieldDescriptor* field, \ - PASSTYPE value) const { \ - USAGE_CHECK_ALL(Add##TYPENAME, REPEATED, CPPTYPE); \ - if (field->is_extension()) { \ - MutableExtensionSet(message)->Add##TYPENAME( \ - field->number(), field->type(), field->options().packed(), value, \ - field); \ - } else { \ - AddField(message, field, value); \ - } \ +#define DEFINE_PRIMITIVE_ACCESSORS(TYPENAME, TYPE, PASSTYPE, CPPTYPE) \ + PASSTYPE GeneratedMessageReflection::Get##TYPENAME( \ + const Message& message, const FieldDescriptor* field) const { \ + USAGE_CHECK_ALL(Get##TYPENAME, SINGULAR, CPPTYPE); \ + if (field->is_extension()) { \ + return GetExtensionSet(message).Get##TYPENAME( \ + field->number(), field->default_value_##PASSTYPE()); \ + } else { \ + return GetField(message, field); \ + } \ + } \ + \ + void GeneratedMessageReflection::Set##TYPENAME( \ + Message* message, const FieldDescriptor* field, PASSTYPE value) const { \ + USAGE_CHECK_ALL(Set##TYPENAME, SINGULAR, CPPTYPE); \ + if (field->is_extension()) { \ + return MutableExtensionSet(message)->Set##TYPENAME( \ + field->number(), field->type(), value, field); \ + } else { \ + SetField(message, field, value); \ + } \ + } \ + \ + PASSTYPE GeneratedMessageReflection::GetRepeated##TYPENAME( \ + const Message& message, const FieldDescriptor* field, int index) const { \ + USAGE_CHECK_ALL(GetRepeated##TYPENAME, REPEATED, CPPTYPE); \ + if (field->is_extension()) { \ + return GetExtensionSet(message).GetRepeated##TYPENAME(field->number(), \ + index); \ + } else { \ + return GetRepeatedField(message, field, index); \ + } \ + } \ + \ + void GeneratedMessageReflection::SetRepeated##TYPENAME( \ + Message* message, const FieldDescriptor* field, int index, \ + PASSTYPE value) const { \ + USAGE_CHECK_ALL(SetRepeated##TYPENAME, REPEATED, CPPTYPE); \ + if (field->is_extension()) { \ + MutableExtensionSet(message)->SetRepeated##TYPENAME(field->number(), \ + index, value); \ + } else { \ + SetRepeatedField(message, field, index, value); \ + } \ + } \ + \ + void GeneratedMessageReflection::Add##TYPENAME( \ + Message* message, const FieldDescriptor* field, PASSTYPE value) const { \ + USAGE_CHECK_ALL(Add##TYPENAME, REPEATED, CPPTYPE); \ + if (field->is_extension()) { \ + MutableExtensionSet(message)->Add##TYPENAME( \ + field->number(), field->type(), field->options().packed(), value, \ + field); \ + } else { \ + AddField(message, field, value); \ + } \ } -DEFINE_PRIMITIVE_ACCESSORS(Int32 , int32 , int32 , INT32 ) -DEFINE_PRIMITIVE_ACCESSORS(Int64 , int64 , int64 , INT64 ) +DEFINE_PRIMITIVE_ACCESSORS(Int32, int32, int32, INT32) +DEFINE_PRIMITIVE_ACCESSORS(Int64, int64, int64, INT64) DEFINE_PRIMITIVE_ACCESSORS(UInt32, uint32, uint32, UINT32) DEFINE_PRIMITIVE_ACCESSORS(UInt64, uint64, uint64, UINT64) -DEFINE_PRIMITIVE_ACCESSORS(Float , float , float , FLOAT ) +DEFINE_PRIMITIVE_ACCESSORS(Float, float, float, FLOAT) DEFINE_PRIMITIVE_ACCESSORS(Double, double, double, DOUBLE) -DEFINE_PRIMITIVE_ACCESSORS(Bool , bool , bool , BOOL ) +DEFINE_PRIMITIVE_ACCESSORS(Bool, bool, bool, BOOL) #undef DEFINE_PRIMITIVE_ACCESSORS // ------------------------------------------------------------------- -string GeneratedMessageReflection::GetString( +std::string GeneratedMessageReflection::GetString( const Message& message, const FieldDescriptor* field) const { USAGE_CHECK_ALL(GetString, SINGULAR, STRING); if (field->is_extension()) { @@ -1165,9 +1152,9 @@ string GeneratedMessageReflection::GetString( } } -const string& GeneratedMessageReflection::GetStringReference( - const Message& message, - const FieldDescriptor* field, string* scratch) const { +const std::string& GeneratedMessageReflection::GetStringReference( + const Message& message, const FieldDescriptor* field, + std::string* scratch) const { USAGE_CHECK_ALL(GetStringReference, SINGULAR, STRING); if (field->is_extension()) { return GetExtensionSet(message).GetString(field->number(), @@ -1187,9 +1174,9 @@ const string& GeneratedMessageReflection::GetStringReference( } -void GeneratedMessageReflection::SetString( - Message* message, const FieldDescriptor* field, - const string& value) const { +void GeneratedMessageReflection::SetString(Message* message, + const FieldDescriptor* field, + const std::string& value) const { USAGE_CHECK_ALL(SetString, SINGULAR, STRING); if (field->is_extension()) { return MutableExtensionSet(message)->SetString(field->number(), @@ -1199,19 +1186,21 @@ void GeneratedMessageReflection::SetString( default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: { if (IsInlined(field)) { - MutableField(message, field)->SetNoArena( - NULL, value); + MutableField(message, field) + ->SetNoArena(NULL, value); break; } - const string* default_ptr = &DefaultRaw(field).Get(); + const std::string* default_ptr = + &DefaultRaw(field).Get(); if (field->containing_oneof() && !HasOneofField(*message, field)) { ClearOneof(message, field->containing_oneof()); - MutableField(message, field)->UnsafeSetDefault( - default_ptr); + MutableField(message, field) + ->UnsafeSetDefault(default_ptr); } - MutableField(message, field)->Set(default_ptr, - value, GetArena(message)); + MutableField(message, field) + ->Mutable(default_ptr, GetArena(message)) + ->assign(value); break; } } @@ -1219,7 +1208,7 @@ void GeneratedMessageReflection::SetString( } -string GeneratedMessageReflection::GetRepeatedString( +std::string GeneratedMessageReflection::GetRepeatedString( const Message& message, const FieldDescriptor* field, int index) const { USAGE_CHECK_ALL(GetRepeatedString, REPEATED, STRING); if (field->is_extension()) { @@ -1228,14 +1217,14 @@ string GeneratedMessageReflection::GetRepeatedString( switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: - return GetRepeatedPtrField(message, field, index); + return GetRepeatedPtrField(message, field, index); } } } -const string& GeneratedMessageReflection::GetRepeatedStringReference( - const Message& message, const FieldDescriptor* field, - int index, string* scratch) const { +const std::string& GeneratedMessageReflection::GetRepeatedStringReference( + const Message& message, const FieldDescriptor* field, int index, + std::string* scratch) const { USAGE_CHECK_ALL(GetRepeatedStringReference, REPEATED, STRING); if (field->is_extension()) { return GetExtensionSet(message).GetRepeatedString(field->number(), index); @@ -1243,42 +1232,42 @@ const string& GeneratedMessageReflection::GetRepeatedStringReference( switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: - return GetRepeatedPtrField(message, field, index); + return GetRepeatedPtrField(message, field, index); } } } void GeneratedMessageReflection::SetRepeatedString( - Message* message, const FieldDescriptor* field, - int index, const string& value) const { + Message* message, const FieldDescriptor* field, int index, + const std::string& value) const { USAGE_CHECK_ALL(SetRepeatedString, REPEATED, STRING); if (field->is_extension()) { - MutableExtensionSet(message)->SetRepeatedString( - field->number(), index, value); + MutableExtensionSet(message)->SetRepeatedString(field->number(), index, + value); } else { switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: - *MutableRepeatedField(message, field, index) = value; + *MutableRepeatedField(message, field, index) = value; break; } } } -void GeneratedMessageReflection::AddString( - Message* message, const FieldDescriptor* field, - const string& value) const { +void GeneratedMessageReflection::AddString(Message* message, + const FieldDescriptor* field, + const std::string& value) const { USAGE_CHECK_ALL(AddString, REPEATED, STRING); if (field->is_extension()) { - MutableExtensionSet(message)->AddString(field->number(), - field->type(), value, field); + MutableExtensionSet(message)->AddString(field->number(), field->type(), + value, field); } else { switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: - *AddField(message, field) = value; + *AddField(message, field) = value; break; } } @@ -1305,7 +1294,7 @@ int GeneratedMessageReflection::GetEnumValue( int32 value; if (field->is_extension()) { value = GetExtensionSet(message).GetEnum( - field->number(), field->default_value_enum()->number()); + field->number(), field->default_value_enum()->number()); } else { value = GetField(message, field); } @@ -1320,9 +1309,9 @@ void GeneratedMessageReflection::SetEnum( SetEnumValueInternal(message, field, value->number()); } -void GeneratedMessageReflection::SetEnumValue( - Message* message, const FieldDescriptor* field, - int value) const { +void GeneratedMessageReflection::SetEnumValue(Message* message, + const FieldDescriptor* field, + int value) const { USAGE_CHECK_ALL(SetEnumValue, SINGULAR, ENUM); if (!CreateUnknownEnumValues(descriptor_->file())) { // Check that the value is valid if we don't support direct storage of @@ -1330,22 +1319,18 @@ void GeneratedMessageReflection::SetEnumValue( const EnumValueDescriptor* value_desc = field->enum_type()->FindValueByNumber(value); if (value_desc == NULL) { - GOOGLE_LOG(DFATAL) << "SetEnumValue accepts only valid integer values: value " - << value << " unexpected for field " << field->full_name(); - // In production builds, DFATAL will not terminate the program, so we have - // to do something reasonable: just set the default value. - value = field->default_value_enum()->number(); + MutableUnknownFields(message)->AddVarint(field->number(), value); + return; } } SetEnumValueInternal(message, field, value); } void GeneratedMessageReflection::SetEnumValueInternal( - Message* message, const FieldDescriptor* field, - int value) const { + Message* message, const FieldDescriptor* field, int value) const { if (field->is_extension()) { - MutableExtensionSet(message)->SetEnum(field->number(), field->type(), - value, field); + MutableExtensionSet(message)->SetEnum(field->number(), field->type(), value, + field); } else { SetField(message, field, value); } @@ -1372,8 +1357,7 @@ int GeneratedMessageReflection::GetRepeatedEnumValue( } void GeneratedMessageReflection::SetRepeatedEnum( - Message* message, - const FieldDescriptor* field, int index, + Message* message, const FieldDescriptor* field, int index, const EnumValueDescriptor* value) const { // Usage checked by SetRepeatedEnumValue. USAGE_CHECK_ENUM_VALUE(SetRepeatedEnum); @@ -1381,8 +1365,7 @@ void GeneratedMessageReflection::SetRepeatedEnum( } void GeneratedMessageReflection::SetRepeatedEnumValue( - Message* message, - const FieldDescriptor* field, int index, + Message* message, const FieldDescriptor* field, int index, int value) const { USAGE_CHECK_ALL(SetRepeatedEnum, REPEATED, ENUM); if (!CreateUnknownEnumValues(descriptor_->file())) { @@ -1391,24 +1374,19 @@ void GeneratedMessageReflection::SetRepeatedEnumValue( const EnumValueDescriptor* value_desc = field->enum_type()->FindValueByNumber(value); if (value_desc == NULL) { - GOOGLE_LOG(DFATAL) << "SetRepeatedEnumValue accepts only valid integer values: " - << "value " << value << " unexpected for field " - << field->full_name(); - // In production builds, DFATAL will not terminate the program, so we have - // to do something reasonable: just set the default value. - value = field->default_value_enum()->number(); + MutableUnknownFields(message)->AddVarint(field->number(), value); + return; } } SetRepeatedEnumValueInternal(message, field, index, value); } void GeneratedMessageReflection::SetRepeatedEnumValueInternal( - Message* message, - const FieldDescriptor* field, int index, + Message* message, const FieldDescriptor* field, int index, int value) const { if (field->is_extension()) { - MutableExtensionSet(message)->SetRepeatedEnum( - field->number(), index, value); + MutableExtensionSet(message)->SetRepeatedEnum(field->number(), index, + value); } else { SetRepeatedField(message, field, index, value); } @@ -1422,9 +1400,9 @@ void GeneratedMessageReflection::AddEnum( AddEnumValueInternal(message, field, value->number()); } -void GeneratedMessageReflection::AddEnumValue( - Message* message, const FieldDescriptor* field, - int value) const { +void GeneratedMessageReflection::AddEnumValue(Message* message, + const FieldDescriptor* field, + int value) const { USAGE_CHECK_ALL(AddEnum, REPEATED, ENUM); if (!CreateUnknownEnumValues(descriptor_->file())) { // Check that the value is valid if we don't support direct storage of @@ -1432,23 +1410,19 @@ void GeneratedMessageReflection::AddEnumValue( const EnumValueDescriptor* value_desc = field->enum_type()->FindValueByNumber(value); if (value_desc == NULL) { - GOOGLE_LOG(DFATAL) << "AddEnumValue accepts only valid integer values: value " - << value << " unexpected for field " << field->full_name(); - // In production builds, DFATAL will not terminate the program, so we have - // to do something reasonable: just set the default value. - value = field->default_value_enum()->number(); + MutableUnknownFields(message)->AddVarint(field->number(), value); + return; } } AddEnumValueInternal(message, field, value); } void GeneratedMessageReflection::AddEnumValueInternal( - Message* message, const FieldDescriptor* field, - int value) const { + Message* message, const FieldDescriptor* field, int value) const { if (field->is_extension()) { MutableExtensionSet(message)->AddEnum(field->number(), field->type(), - field->options().packed(), - value, field); + field->options().packed(), value, + field); } else { AddField(message, field, value); } @@ -1464,9 +1438,8 @@ const Message& GeneratedMessageReflection::GetMessage( if (factory == NULL) factory = message_factory_; if (field->is_extension()) { - return static_cast( - GetExtensionSet(message).GetMessage( - field->number(), field->message_type(), factory)); + return static_cast(GetExtensionSet(message).GetMessage( + field->number(), field->message_type(), factory)); } else { const Message* result = GetRaw(message, field); if (result == NULL) { @@ -1512,8 +1485,7 @@ Message* GeneratedMessageReflection::MutableMessage( } void GeneratedMessageReflection::UnsafeArenaSetAllocatedMessage( - Message* message, - Message* sub_message, + Message* message, Message* sub_message, const FieldDescriptor* field) const { USAGE_CHECK_ALL(SetAllocatedMessage, SINGULAR, MESSAGE); @@ -1546,14 +1518,12 @@ void GeneratedMessageReflection::UnsafeArenaSetAllocatedMessage( } void GeneratedMessageReflection::SetAllocatedMessage( - Message* message, - Message* sub_message, + Message* message, Message* sub_message, const FieldDescriptor* field) const { // If message and sub-message are in different memory ownership domains // (different arenas, or one is on heap and one is not), then we may need to // do a copy. - if (sub_message != NULL && - sub_message->GetArena() != message->GetArena()) { + if (sub_message != NULL && sub_message->GetArena() != message->GetArena()) { if (sub_message->GetArena() == NULL && message->GetArena() != NULL) { // Case 1: parent is on an arena and child is heap-allocated. We can add // the child to the arena's Own() list to free on arena destruction, then @@ -1574,8 +1544,7 @@ void GeneratedMessageReflection::SetAllocatedMessage( } Message* GeneratedMessageReflection::UnsafeArenaReleaseMessage( - Message* message, - const FieldDescriptor* field, + Message* message, const FieldDescriptor* field, MessageFactory* factory) const { USAGE_CHECK_ALL(ReleaseMessage, SINGULAR, MESSAGE); @@ -1604,8 +1573,7 @@ Message* GeneratedMessageReflection::UnsafeArenaReleaseMessage( } Message* GeneratedMessageReflection::ReleaseMessage( - Message* message, - const FieldDescriptor* field, + Message* message, const FieldDescriptor* field, MessageFactory* factory) const { Message* released = UnsafeArenaReleaseMessage(message, field, factory); if (GetArena(message) != NULL && released != NULL) { @@ -1641,8 +1609,8 @@ Message* GeneratedMessageReflection::MutableRepeatedMessage( if (field->is_extension()) { return static_cast( - MutableExtensionSet(message)->MutableRepeatedMessage( - field->number(), index)); + MutableExtensionSet(message)->MutableRepeatedMessage(field->number(), + index)); } else { if (IsMapFieldInApi(field)) { return MutableRaw(message, field) @@ -1650,14 +1618,14 @@ Message* GeneratedMessageReflection::MutableRepeatedMessage( ->Mutable >(index); } else { return MutableRaw(message, field) - ->Mutable >(index); + ->Mutable >(index); } } } -Message* GeneratedMessageReflection::AddMessage( - Message* message, const FieldDescriptor* field, - MessageFactory* factory) const { +Message* GeneratedMessageReflection::AddMessage(Message* message, + const FieldDescriptor* field, + MessageFactory* factory) const { USAGE_CHECK_ALL(AddMessage, REPEATED, MESSAGE); if (factory == NULL) factory = message_factory_; @@ -1698,8 +1666,7 @@ Message* GeneratedMessageReflection::AddMessage( } void GeneratedMessageReflection::AddAllocatedMessage( - Message* message, const FieldDescriptor* field, - Message* new_entry) const { + Message* message, const FieldDescriptor* field, Message* new_entry) const { USAGE_CHECK_ALL(AddAllocatedMessage, REPEATED, MESSAGE); if (field->is_extension()) { @@ -1718,14 +1685,11 @@ void GeneratedMessageReflection::AddAllocatedMessage( void* GeneratedMessageReflection::MutableRawRepeatedField( Message* message, const FieldDescriptor* field, - FieldDescriptor::CppType cpptype, - int ctype, const Descriptor* desc) const { + FieldDescriptor::CppType cpptype, int ctype, const Descriptor* desc) const { USAGE_CHECK_REPEATED("MutableRawRepeatedField"); if (field->cpp_type() != cpptype) - ReportReflectionUsageTypeError(descriptor_, - field, "MutableRawRepeatedField", cpptype); - if (ctype >= 0) - GOOGLE_CHECK_EQ(field->options().ctype(), ctype) << "subtype mismatch"; + ReportReflectionUsageTypeError(descriptor_, field, + "MutableRawRepeatedField", cpptype); if (desc != NULL) GOOGLE_CHECK_EQ(field->message_type(), desc) << "wrong submessage type"; if (field->is_extension()) { @@ -1743,12 +1707,11 @@ void* GeneratedMessageReflection::MutableRawRepeatedField( const void* GeneratedMessageReflection::GetRawRepeatedField( const Message& message, const FieldDescriptor* field, - FieldDescriptor::CppType cpptype, - int ctype, const Descriptor* desc) const { + FieldDescriptor::CppType cpptype, int ctype, const Descriptor* desc) const { USAGE_CHECK_REPEATED("GetRawRepeatedField"); if (field->cpp_type() != cpptype) - ReportReflectionUsageTypeError(descriptor_, - field, "GetRawRepeatedField", cpptype); + ReportReflectionUsageTypeError(descriptor_, field, "GetRawRepeatedField", + cpptype); if (ctype >= 0) GOOGLE_CHECK_EQ(field->options().ctype(), ctype) << "subtype mismatch"; if (desc != NULL) @@ -1759,8 +1722,8 @@ const void* GeneratedMessageReflection::GetRawRepeatedField( // Map is not supported in extensions, it is acceptable to use // extension_set::MutableRawRepeatedField which does not change the message. return MutableExtensionSet(const_cast(&message)) - ->MutableRawRepeatedField( - field->number(), field->type(), field->is_packed(), field); + ->MutableRawRepeatedField(field->number(), field->type(), + field->is_packed(), field); } else { // Trigger transform for MapField if (IsMapFieldInApi(field)) { @@ -1771,8 +1734,7 @@ const void* GeneratedMessageReflection::GetRawRepeatedField( } const FieldDescriptor* GeneratedMessageReflection::GetOneofFieldDescriptor( - const Message& message, - const OneofDescriptor* oneof_descriptor) const { + const Message& message, const OneofDescriptor* oneof_descriptor) const { uint32 field_number = GetOneofCase(message, oneof_descriptor); if (field_number == 0) { return NULL; @@ -1780,74 +1742,58 @@ const FieldDescriptor* GeneratedMessageReflection::GetOneofFieldDescriptor( return descriptor_->FindFieldByNumber(field_number); } -bool GeneratedMessageReflection::ContainsMapKey( - const Message& message, - const FieldDescriptor* field, - const MapKey& key) const { - USAGE_CHECK(IsMapFieldInApi(field), - "LookupMapValue", +bool GeneratedMessageReflection::ContainsMapKey(const Message& message, + const FieldDescriptor* field, + const MapKey& key) const { + USAGE_CHECK(IsMapFieldInApi(field), "LookupMapValue", "Field is not a map field."); return GetRaw(message, field).ContainsMapKey(key); } bool GeneratedMessageReflection::InsertOrLookupMapValue( - Message* message, - const FieldDescriptor* field, - const MapKey& key, + Message* message, const FieldDescriptor* field, const MapKey& key, MapValueRef* val) const { - USAGE_CHECK(IsMapFieldInApi(field), - "InsertOrLookupMapValue", + USAGE_CHECK(IsMapFieldInApi(field), "InsertOrLookupMapValue", "Field is not a map field."); val->SetType(field->message_type()->FindFieldByName("value")->cpp_type()); - return MutableRaw(message, field)->InsertOrLookupMapValue( - key, val); + return MutableRaw(message, field) + ->InsertOrLookupMapValue(key, val); } -bool GeneratedMessageReflection::DeleteMapValue( - Message* message, - const FieldDescriptor* field, - const MapKey& key) const { - USAGE_CHECK(IsMapFieldInApi(field), - "DeleteMapValue", +bool GeneratedMessageReflection::DeleteMapValue(Message* message, + const FieldDescriptor* field, + const MapKey& key) const { + USAGE_CHECK(IsMapFieldInApi(field), "DeleteMapValue", "Field is not a map field."); return MutableRaw(message, field)->DeleteMapValue(key); } MapIterator GeneratedMessageReflection::MapBegin( - Message* message, - const FieldDescriptor* field) const { - USAGE_CHECK(IsMapFieldInApi(field), - "MapBegin", - "Field is not a map field."); + Message* message, const FieldDescriptor* field) const { + USAGE_CHECK(IsMapFieldInApi(field), "MapBegin", "Field is not a map field."); MapIterator iter(message, field); GetRaw(*message, field).MapBegin(&iter); return iter; } MapIterator GeneratedMessageReflection::MapEnd( - Message* message, - const FieldDescriptor* field) const { - USAGE_CHECK(IsMapFieldInApi(field), - "MapEnd", - "Field is not a map field."); + Message* message, const FieldDescriptor* field) const { + USAGE_CHECK(IsMapFieldInApi(field), "MapEnd", "Field is not a map field."); MapIterator iter(message, field); GetRaw(*message, field).MapEnd(&iter); return iter; } -int GeneratedMessageReflection::MapSize( - const Message& message, - const FieldDescriptor* field) const { - USAGE_CHECK(IsMapFieldInApi(field), - "MapSize", - "Field is not a map field."); +int GeneratedMessageReflection::MapSize(const Message& message, + const FieldDescriptor* field) const { + USAGE_CHECK(IsMapFieldInApi(field), "MapSize", "Field is not a map field."); return GetRaw(message, field).size(); } // ----------------------------------------------------------------------------- const FieldDescriptor* GeneratedMessageReflection::FindKnownExtensionByName( - const string& name) const { + const std::string& name) const { if (!schema_.HasExtensionSet()) return NULL; const FieldDescriptor* result = descriptor_pool_->FindExtensionByName(name); @@ -1865,8 +1811,7 @@ const FieldDescriptor* GeneratedMessageReflection::FindKnownExtensionByName( const FieldDescriptor* extension = type->extension(i); if (extension->containing_type() == descriptor_ && extension->type() == FieldDescriptor::TYPE_MESSAGE && - extension->is_optional() && - extension->message_type() == type) { + extension->is_optional() && extension->message_type() == type) { // Found it. return extension; } @@ -1921,12 +1866,11 @@ bool GeneratedMessageReflection::IsInlined(const FieldDescriptor* field) const { } template -Type* GeneratedMessageReflection::MutableRaw(Message* message, - const FieldDescriptor* field) const { +Type* GeneratedMessageReflection::MutableRaw( + Message* message, const FieldDescriptor* field) const { return GetPointerAtOffset(message, schema_.GetFieldOffset(field)); } - inline const uint32* GeneratedMessageReflection::GetHasBits( const Message& message) const { GOOGLE_DCHECK(schema_.HasHasbits()); @@ -1999,14 +1943,14 @@ inline bool GeneratedMessageReflection::HasBit( // present only if their message-field pointer is non-NULL. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { return !schema_.IsDefaultInstance(message) && - GetRaw(message, field) != NULL; + GetRaw(message, field) != NULL; } else { // Non-message field (and non-oneof, since that was handled in HasField() // before calling us), and singular (again, checked in HasField). So, this // field must be a scalar. // Scalar primitive (numeric or string/bytes) fields are present if - // their value is non-zero (numeric) or non-empty (string/bytes). N.B.: + // their value is non-zero (numeric) or non-empty (string/bytes). N.B.: // we must use this definition here, rather than the "scalar fields // always present" in the proto3 docs, because MergeFrom() semantics // require presence as "present on wire", and reflection-based merge @@ -2017,7 +1961,8 @@ inline bool GeneratedMessageReflection::HasBit( default: { if (IsInlined(field)) { return !GetField(message, field) - .GetNoArena().empty(); + .GetNoArena() + .empty(); } return GetField(message, field).Get().size() > 0; } @@ -2125,10 +2070,10 @@ inline void GeneratedMessageReflection::ClearOneof( switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: { - const string* default_ptr = + const std::string* default_ptr = &DefaultRaw(field).Get(); - MutableField(message, field)-> - Destroy(default_ptr, GetArena(message)); + MutableField(message, field) + ->Destroy(default_ptr, GetArena(message)); break; } } @@ -2157,21 +2102,22 @@ inline const Type& GeneratedMessageReflection::GetField( } template -inline void GeneratedMessageReflection::SetField( - Message* message, const FieldDescriptor* field, const Type& value) const { +inline void GeneratedMessageReflection::SetField(Message* message, + const FieldDescriptor* field, + const Type& value) const { if (field->containing_oneof() && !HasOneofField(*message, field)) { ClearOneof(message, field->containing_oneof()); } *MutableRaw(message, field) = value; - field->containing_oneof() ? - SetOneofCase(message, field) : SetBit(message, field); + field->containing_oneof() ? SetOneofCase(message, field) + : SetBit(message, field); } template inline Type* GeneratedMessageReflection::MutableField( Message* message, const FieldDescriptor* field) const { - field->containing_oneof() ? - SetOneofCase(message, field) : SetBit(message, field); + field->containing_oneof() ? SetOneofCase(message, field) + : SetBit(message, field); return MutableRaw(message, field); } @@ -2189,8 +2135,8 @@ inline const Type& GeneratedMessageReflection::GetRepeatedPtrField( template inline void GeneratedMessageReflection::SetRepeatedField( - Message* message, const FieldDescriptor* field, - int index, Type value) const { + Message* message, const FieldDescriptor* field, int index, + Type value) const { MutableRaw >(message, field)->Set(index, value); } @@ -2198,13 +2144,14 @@ template inline Type* GeneratedMessageReflection::MutableRepeatedField( Message* message, const FieldDescriptor* field, int index) const { RepeatedPtrField* repeated = - MutableRaw >(message, field); + MutableRaw >(message, field); return repeated->Mutable(index); } template -inline void GeneratedMessageReflection::AddField( - Message* message, const FieldDescriptor* field, const Type& value) const { +inline void GeneratedMessageReflection::AddField(Message* message, + const FieldDescriptor* field, + const Type& value) const { MutableRaw >(message, field)->Add(value); } @@ -2212,7 +2159,7 @@ template inline Type* GeneratedMessageReflection::AddField( Message* message, const FieldDescriptor* field) const { RepeatedPtrField* repeated = - MutableRaw >(message, field); + MutableRaw >(message, field); return repeated->Add(); } @@ -2222,8 +2169,7 @@ MessageFactory* GeneratedMessageReflection::GetMessageFactory() const { void* GeneratedMessageReflection::RepeatedFieldData( Message* message, const FieldDescriptor* field, - FieldDescriptor::CppType cpp_type, - const Descriptor* message_type) const { + FieldDescriptor::CppType cpp_type, const Descriptor* message_type) const { GOOGLE_CHECK(field->is_repeated()); GOOGLE_CHECK(field->cpp_type() == cpp_type || (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM && @@ -2242,14 +2188,20 @@ void* GeneratedMessageReflection::RepeatedFieldData( } } -MapFieldBase* GeneratedMessageReflection::MapData( +MapFieldBase* GeneratedMessageReflection::MutableMapData( Message* message, const FieldDescriptor* field) const { - USAGE_CHECK(IsMapFieldInApi(field), - "GetMapData", + USAGE_CHECK(IsMapFieldInApi(field), "GetMapData", "Field is not a map field."); return MutableRaw(message, field); } +const MapFieldBase* GeneratedMessageReflection::GetMapData( + const Message& message, const FieldDescriptor* field) const { + USAGE_CHECK(IsMapFieldInApi(field), "GetMapData", + "Field is not a map field."); + return &(GetRaw(message, field)); +} + namespace { // Helper function to transform migration schema into reflection schema. @@ -2271,7 +2223,7 @@ ReflectionSchema MigrationToReflectionSchema( return result; } -template +template class AssignDescriptorsHelper { public: AssignDescriptorsHelper(MessageFactory* factory, @@ -2298,7 +2250,7 @@ class AssignDescriptorsHelper { descriptor, MigrationToReflectionSchema(default_instance_data_, offsets_, *schemas_), - ::google::protobuf::DescriptorPool::generated_pool(), factory_); + DescriptorPool::generated_pool(), factory_); for (int i = 0; i < descriptor->enum_type_count(); i++) { AssignEnumDescriptor(descriptor->enum_type(i)); } @@ -2319,7 +2271,7 @@ class AssignDescriptorsHelper { Metadata* file_level_metadata_; const EnumDescriptor** file_level_enum_descriptors_; const Schema* schemas_; - const Message* const * default_instance_data_; + const Message* const* default_instance_data_; const uint32* offsets_; }; @@ -2336,8 +2288,9 @@ struct MetadataOwner { } void AddArray(const Metadata* begin, const Metadata* end) { - MutexLock lock(&mu_); + mu_.Lock(); metadata_arrays_.push_back(std::make_pair(begin, end)); + mu_.Unlock(); } static MetadataOwner* Instance() { @@ -2348,28 +2301,30 @@ struct MetadataOwner { private: MetadataOwner() = default; // private because singleton - Mutex mu_; + WrappedMutex mu_; std::vector > metadata_arrays_; }; -} // namespace - -void AssignDescriptors( - const string& filename, const MigrationSchema* schemas, - const Message* const* default_instances_, const uint32* offsets, - // update the following descriptor arrays. - Metadata* file_level_metadata, - const EnumDescriptor** file_level_enum_descriptors, - const ServiceDescriptor** file_level_service_descriptors) { - const ::google::protobuf::FileDescriptor* file = - ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(filename); +void AssignDescriptorsImpl(const DescriptorTable* table) { + // Ensure the file descriptor is added to the pool. + { + // This only happens once per proto file. So a global mutex to serialize + // calls to AddDescriptors. + static WrappedMutex mu{GOOGLE_PROTOBUF_LINKER_INITIALIZED}; + mu.Lock(); + AddDescriptors(table); + mu.Unlock(); + } + // Fill the arrays with pointers to descriptors and reflection classes. + const FileDescriptor* file = + DescriptorPool::generated_pool()->FindFileByName(table->filename); GOOGLE_CHECK(file != NULL); MessageFactory* factory = MessageFactory::generated_factory(); - AssignDescriptorsHelper helper(factory, file_level_metadata, - file_level_enum_descriptors, schemas, - default_instances_, offsets); + AssignDescriptorsHelper helper( + factory, table->file_level_metadata, table->file_level_enum_descriptors, + table->schemas, table->default_instances, table->offsets); for (int i = 0; i < file->message_type_count(); i++) { helper.AssignMessageDescriptor(file->message_type(i)); @@ -2380,40 +2335,75 @@ void AssignDescriptors( } if (file->options().cc_generic_services()) { for (int i = 0; i < file->service_count(); i++) { - file_level_service_descriptors[i] = file->service(i); + table->file_level_service_descriptors[i] = file->service(i); } } - MetadataOwner::Instance()->AddArray( - file_level_metadata, helper.GetCurrentMetadataPtr()); + MetadataOwner::Instance()->AddArray(table->file_level_metadata, + helper.GetCurrentMetadataPtr()); } +void AddDescriptorsImpl(const DescriptorTable* table) { + // Reflection refers to the default instances so make sure they are + // initialized. + for (int i = 0; i < table->num_sccs; i++) { + internal::InitSCC(table->init_default_instances[i]); + } + + // Ensure all dependent descriptors are registered to the generated descriptor + // pool and message factory. + for (int i = 0; i < table->num_deps; i++) { + // In case of weak fields deps[i] could be null. + if (table->deps[i]) AddDescriptors(table->deps[i]); + } + + // Register the descriptor of this file. + DescriptorPool::InternalAddGeneratedFile(table->descriptor, table->size); + MessageFactory::InternalRegisterGeneratedFile(table); +} + +} // namespace + +void AssignDescriptors(const DescriptorTable* table) { + call_once(*table->once, AssignDescriptorsImpl, table); +} + +void AddDescriptors(const DescriptorTable* table) { + // AddDescriptors is not thread safe. Callers need to ensure calls are + // properly serialized. This function is only called pre-main by global + // descriptors and we can assume single threaded access or it's called + // by AssignDescriptorImpl which uses a mutex to sequence calls. + if (*table->is_initialized) return; + *table->is_initialized = true; + AddDescriptorsImpl(table); +} + +// Separate function because it needs to be a friend of +// GeneratedMessageReflection void RegisterAllTypesInternal(const Metadata* file_level_metadata, int size) { for (int i = 0; i < size; i++) { const GeneratedMessageReflection* reflection = static_cast( - file_level_metadata[i].reflection); - if (reflection) { - // It's not a map type - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - file_level_metadata[i].descriptor, - reflection->schema_.default_instance_); - } + file_level_metadata[i].reflection); + MessageFactory::InternalRegisterGeneratedMessage( + file_level_metadata[i].descriptor, + reflection->schema_.default_instance_); } } -void RegisterAllTypes(const Metadata* file_level_metadata, int size) { - RegisterAllTypesInternal(file_level_metadata, size); +void RegisterFileLevelMetadata(const DescriptorTable* table) { + AssignDescriptors(table); + RegisterAllTypesInternal(table->file_level_metadata, table->num_messages); } void UnknownFieldSetSerializer(const uint8* base, uint32 offset, uint32 tag, uint32 has_offset, - ::google::protobuf::io::CodedOutputStream* output) { + io::CodedOutputStream* output) { const void* ptr = base + offset; const InternalMetadataWithArena* metadata = static_cast(ptr); if (metadata->have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - metadata->unknown_fields(), output); + internal::WireFormat::SerializeUnknownFields(metadata->unknown_fields(), + output); } } diff --git a/third_party/protobuf/src/google/protobuf/generated_message_reflection.h b/third_party/protobuf/src/google/protobuf/generated_message_reflection.h index 31f249b6..a0555b57 100644 --- a/third_party/protobuf/src/google/protobuf/generated_message_reflection.h +++ b/third_party/protobuf/src/google/protobuf/generated_message_reflection.h @@ -47,40 +47,44 @@ #include #include #include +#include +#include #include -namespace google { +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + namespace upb { namespace google_opensource { class GMR_Handlers; } // namespace google_opensource } // namespace upb +namespace google { namespace protobuf { class DescriptorPool; class MapKey; class MapValueRef; } // namespace protobuf +} // namespace google -namespace protobuf { -namespace flat { -class MetadataBuilder; -} // namespace flat -} // namespace protobuf - - +namespace google { namespace protobuf { namespace internal { class DefaultEmptyOneof; +class ReflectionAccessor; // Defined in this file. class GeneratedMessageReflection; // Defined in other files. -class ExtensionSet; // extension_set.h -class WeakFieldMap; // weak_field_map.h +class ExtensionSet; // extension_set.h +class WeakFieldMap; // weak_field_map.h // This struct describes the internal layout of the message, hence this is // used to act on the message reflectively. @@ -98,7 +102,7 @@ class WeakFieldMap; // weak_field_map.h // macro. For each none oneof field, the offset is related to // the start of the message object. These can be computed at // compile time using the -// GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET() macro. +// PROTO2_GENERATED_MESSAGE_FIELD_OFFSET() macro. // Besides offsets for all fields, this array also contains // offsets for oneof unions. The offset of the i-th oneof union // is offsets[descriptor->field_count() + i]. @@ -142,7 +146,7 @@ struct ReflectionSchema { if (field->containing_oneof()) { size_t offset = static_cast(field->containing_type()->field_count() + - field->containing_oneof()->index()); + field->containing_oneof()->index()); return OffsetValue(offsets_[offset], field->type()); } else { return GetFieldOffsetNonOneof(field); @@ -162,8 +166,8 @@ struct ReflectionSchema { uint32 GetOneofCaseOffset(const OneofDescriptor* oneof_descriptor) const { return static_cast(oneof_case_offset_) + - static_cast( - static_cast(oneof_descriptor->index()) * sizeof(uint32)); + static_cast(static_cast(oneof_descriptor->index()) * + sizeof(uint32)); } bool HasHasbits() const { return has_bits_offset_ != -1; } @@ -207,7 +211,7 @@ struct ReflectionSchema { // Returns a pointer to the default value for this field. The size and type // of the underlying data depends on the field's type. - const void *GetFieldDefault(const FieldDescriptor* field) const { + const void* GetFieldDefault(const FieldDescriptor* field) const { return reinterpret_cast(default_instance_) + OffsetValue(offsets_[field->index()], field->type()); } @@ -220,7 +224,7 @@ struct ReflectionSchema { // them, ie. // // ReflectionSchema schema = {a, b, c, d, e, ...}; - // private: + // private: const Message* default_instance_; const uint32* offsets_; const uint32* has_bit_indices_; @@ -276,8 +280,8 @@ struct MigrationSchema { // // It is required that the user represents fields of each type in a standard // way, so that GeneratedMessageReflection can cast the void* pointer to -// the appropriate type. For primitive fields and string fields, each field -// should be represented using the obvious C++ primitive type. Enums and +// the appropriate type. For primitive fields and string fields, each +// field should be represented using the obvious C++ primitive type. Enums and // Messages are different: // - Singular Message fields are stored as a pointer to a Message. These // should start out NULL, except for in the default instance where they @@ -304,199 +308,198 @@ class GeneratedMessageReflection final : public Reflection { const DescriptorPool* pool, MessageFactory* factory); - ~GeneratedMessageReflection(); + ~GeneratedMessageReflection() override; // implements Reflection ------------------------------------------- - const UnknownFieldSet& GetUnknownFields(const Message& message) const; - UnknownFieldSet* MutableUnknownFields(Message* message) const; + const UnknownFieldSet& GetUnknownFields( + const Message& message) const override; + UnknownFieldSet* MutableUnknownFields(Message* message) const override; - size_t SpaceUsedLong(const Message& message) const; + size_t SpaceUsedLong(const Message& message) const override; - bool HasField(const Message& message, const FieldDescriptor* field) const; - int FieldSize(const Message& message, const FieldDescriptor* field) const; - void ClearField(Message* message, const FieldDescriptor* field) const; + bool HasField(const Message& message, + const FieldDescriptor* field) const override; + int FieldSize(const Message& message, + const FieldDescriptor* field) const override; + void ClearField(Message* message, + const FieldDescriptor* field) const override; bool HasOneof(const Message& message, - const OneofDescriptor* oneof_descriptor) const; - void ClearOneof(Message* message, const OneofDescriptor* field) const; - void RemoveLast(Message* message, const FieldDescriptor* field) const; - Message* ReleaseLast(Message* message, const FieldDescriptor* field) const; - void Swap(Message* message1, Message* message2) const; - void SwapFields(Message* message1, Message* message2, - const std::vector& fields) const; - void SwapElements(Message* message, const FieldDescriptor* field, - int index1, int index2) const; + const OneofDescriptor* oneof_descriptor) const override; + void ClearOneof(Message* message, + const OneofDescriptor* oneof_descriptor) const override; + void RemoveLast(Message* message, + const FieldDescriptor* field) const override; + Message* ReleaseLast(Message* message, + const FieldDescriptor* field) const override; + void Swap(Message* message1, Message* message2) const override; + void SwapFields( + Message* message1, Message* message2, + const std::vector& fields) const override; + void SwapElements(Message* message, const FieldDescriptor* field, int index1, + int index2) const override; void ListFields(const Message& message, - std::vector* output) const; - - int32 GetInt32 (const Message& message, - const FieldDescriptor* field) const; - int64 GetInt64 (const Message& message, - const FieldDescriptor* field) const; + std::vector* output) const override; + int32 GetInt32(const Message& message, + const FieldDescriptor* field) const override; + int64 GetInt64(const Message& message, + const FieldDescriptor* field) const override; uint32 GetUInt32(const Message& message, - const FieldDescriptor* field) const; + const FieldDescriptor* field) const override; uint64 GetUInt64(const Message& message, - const FieldDescriptor* field) const; - float GetFloat (const Message& message, - const FieldDescriptor* field) const; + const FieldDescriptor* field) const override; + float GetFloat(const Message& message, + const FieldDescriptor* field) const override; double GetDouble(const Message& message, - const FieldDescriptor* field) const; - bool GetBool (const Message& message, - const FieldDescriptor* field) const; - string GetString(const Message& message, - const FieldDescriptor* field) const; - const string& GetStringReference(const Message& message, - const FieldDescriptor* field, - string* scratch) const; - const EnumValueDescriptor* GetEnum(const Message& message, - const FieldDescriptor* field) const; + const FieldDescriptor* field) const override; + bool GetBool(const Message& message, + const FieldDescriptor* field) const override; + std::string GetString(const Message& message, + const FieldDescriptor* field) const override; + const std::string& GetStringReference(const Message& message, + const FieldDescriptor* field, + std::string* scratch) const override; + const EnumValueDescriptor* GetEnum( + const Message& message, const FieldDescriptor* field) const override; int GetEnumValue(const Message& message, - const FieldDescriptor* field) const; + const FieldDescriptor* field) const override; const Message& GetMessage(const Message& message, const FieldDescriptor* field, - MessageFactory* factory = NULL) const; + MessageFactory* factory = NULL) const override; const FieldDescriptor* GetOneofFieldDescriptor( const Message& message, - const OneofDescriptor* oneof_descriptor) const; + const OneofDescriptor* oneof_descriptor) const override; private: - bool ContainsMapKey(const Message& message, - const FieldDescriptor* field, - const MapKey& key) const; - bool InsertOrLookupMapValue(Message* message, - const FieldDescriptor* field, + bool ContainsMapKey(const Message& message, const FieldDescriptor* field, + const MapKey& key) const override; + bool InsertOrLookupMapValue(Message* message, const FieldDescriptor* field, const MapKey& key, - MapValueRef* val) const; - bool DeleteMapValue(Message* message, - const FieldDescriptor* field, - const MapKey& key) const; - MapIterator MapBegin( - Message* message, - const FieldDescriptor* field) const; - MapIterator MapEnd( - Message* message, - const FieldDescriptor* field) const; - int MapSize(const Message& message, const FieldDescriptor* field) const; + MapValueRef* val) const override; + bool DeleteMapValue(Message* message, const FieldDescriptor* field, + const MapKey& key) const override; + MapIterator MapBegin(Message* message, + const FieldDescriptor* field) const override; + MapIterator MapEnd(Message* message, + const FieldDescriptor* field) const override; + int MapSize(const Message& message, + const FieldDescriptor* field) const override; public: - void SetInt32 (Message* message, - const FieldDescriptor* field, int32 value) const; - void SetInt64 (Message* message, - const FieldDescriptor* field, int64 value) const; - void SetUInt32(Message* message, - const FieldDescriptor* field, uint32 value) const; - void SetUInt64(Message* message, - const FieldDescriptor* field, uint64 value) const; - void SetFloat (Message* message, - const FieldDescriptor* field, float value) const; - void SetDouble(Message* message, - const FieldDescriptor* field, double value) const; - void SetBool (Message* message, - const FieldDescriptor* field, bool value) const; - void SetString(Message* message, - const FieldDescriptor* field, - const string& value) const; - void SetEnum (Message* message, const FieldDescriptor* field, - const EnumValueDescriptor* value) const; + void SetInt32(Message* message, const FieldDescriptor* field, + int32 value) const override; + void SetInt64(Message* message, const FieldDescriptor* field, + int64 value) const override; + void SetUInt32(Message* message, const FieldDescriptor* field, + uint32 value) const override; + void SetUInt64(Message* message, const FieldDescriptor* field, + uint64 value) const override; + void SetFloat(Message* message, const FieldDescriptor* field, + float value) const override; + void SetDouble(Message* message, const FieldDescriptor* field, + double value) const override; + void SetBool(Message* message, const FieldDescriptor* field, + bool value) const override; + void SetString(Message* message, const FieldDescriptor* field, + const std::string& value) const override; + void SetEnum(Message* message, const FieldDescriptor* field, + const EnumValueDescriptor* value) const override; void SetEnumValue(Message* message, const FieldDescriptor* field, - int value) const; + int value) const override; Message* MutableMessage(Message* message, const FieldDescriptor* field, - MessageFactory* factory = NULL) const; - void SetAllocatedMessage(Message* message, - Message* sub_message, - const FieldDescriptor* field) const; + MessageFactory* factory = NULL) const override; + void SetAllocatedMessage(Message* message, Message* sub_message, + const FieldDescriptor* field) const override; Message* ReleaseMessage(Message* message, const FieldDescriptor* field, - MessageFactory* factory = NULL) const; + MessageFactory* factory = NULL) const override; - int32 GetRepeatedInt32 (const Message& message, - const FieldDescriptor* field, int index) const; - int64 GetRepeatedInt64 (const Message& message, - const FieldDescriptor* field, int index) const; - uint32 GetRepeatedUInt32(const Message& message, - const FieldDescriptor* field, int index) const; - uint64 GetRepeatedUInt64(const Message& message, - const FieldDescriptor* field, int index) const; - float GetRepeatedFloat (const Message& message, - const FieldDescriptor* field, int index) const; - double GetRepeatedDouble(const Message& message, - const FieldDescriptor* field, int index) const; - bool GetRepeatedBool (const Message& message, - const FieldDescriptor* field, int index) const; - string GetRepeatedString(const Message& message, - const FieldDescriptor* field, int index) const; - const string& GetRepeatedStringReference(const Message& message, - const FieldDescriptor* field, - int index, string* scratch) const; + int32 GetRepeatedInt32(const Message& message, const FieldDescriptor* field, + int index) const override; + int64 GetRepeatedInt64(const Message& message, const FieldDescriptor* field, + int index) const override; + uint32 GetRepeatedUInt32(const Message& message, const FieldDescriptor* field, + int index) const override; + uint64 GetRepeatedUInt64(const Message& message, const FieldDescriptor* field, + int index) const override; + float GetRepeatedFloat(const Message& message, const FieldDescriptor* field, + int index) const override; + double GetRepeatedDouble(const Message& message, const FieldDescriptor* field, + int index) const override; + bool GetRepeatedBool(const Message& message, const FieldDescriptor* field, + int index) const override; + std::string GetRepeatedString(const Message& message, + const FieldDescriptor* field, + int index) const override; + const std::string& GetRepeatedStringReference( + const Message& message, const FieldDescriptor* field, int index, + std::string* scratch) const override; const EnumValueDescriptor* GetRepeatedEnum(const Message& message, const FieldDescriptor* field, - int index) const; - int GetRepeatedEnumValue(const Message& message, - const FieldDescriptor* field, - int index) const; + int index) const override; + int GetRepeatedEnumValue(const Message& message, const FieldDescriptor* field, + int index) const override; const Message& GetRepeatedMessage(const Message& message, const FieldDescriptor* field, - int index) const; + int index) const override; // Set the value of a field. - void SetRepeatedInt32 (Message* message, - const FieldDescriptor* field, int index, int32 value) const; - void SetRepeatedInt64 (Message* message, - const FieldDescriptor* field, int index, int64 value) const; - void SetRepeatedUInt32(Message* message, - const FieldDescriptor* field, int index, uint32 value) const; - void SetRepeatedUInt64(Message* message, - const FieldDescriptor* field, int index, uint64 value) const; - void SetRepeatedFloat (Message* message, - const FieldDescriptor* field, int index, float value) const; - void SetRepeatedDouble(Message* message, - const FieldDescriptor* field, int index, double value) const; - void SetRepeatedBool (Message* message, - const FieldDescriptor* field, int index, bool value) const; - void SetRepeatedString(Message* message, - const FieldDescriptor* field, int index, - const string& value) const; + void SetRepeatedInt32(Message* message, const FieldDescriptor* field, + int index, int32 value) const override; + void SetRepeatedInt64(Message* message, const FieldDescriptor* field, + int index, int64 value) const override; + void SetRepeatedUInt32(Message* message, const FieldDescriptor* field, + int index, uint32 value) const override; + void SetRepeatedUInt64(Message* message, const FieldDescriptor* field, + int index, uint64 value) const override; + void SetRepeatedFloat(Message* message, const FieldDescriptor* field, + int index, float value) const override; + void SetRepeatedDouble(Message* message, const FieldDescriptor* field, + int index, double value) const override; + void SetRepeatedBool(Message* message, const FieldDescriptor* field, + int index, bool value) const override; + void SetRepeatedString(Message* message, const FieldDescriptor* field, + int index, const std::string& value) const override; void SetRepeatedEnum(Message* message, const FieldDescriptor* field, - int index, const EnumValueDescriptor* value) const; + int index, + const EnumValueDescriptor* value) const override; void SetRepeatedEnumValue(Message* message, const FieldDescriptor* field, - int index, int value) const; + int index, int value) const override; // Get a mutable pointer to a field with a message type. Message* MutableRepeatedMessage(Message* message, const FieldDescriptor* field, - int index) const; + int index) const override; - void AddInt32 (Message* message, - const FieldDescriptor* field, int32 value) const; - void AddInt64 (Message* message, - const FieldDescriptor* field, int64 value) const; - void AddUInt32(Message* message, - const FieldDescriptor* field, uint32 value) const; - void AddUInt64(Message* message, - const FieldDescriptor* field, uint64 value) const; - void AddFloat (Message* message, - const FieldDescriptor* field, float value) const; - void AddDouble(Message* message, - const FieldDescriptor* field, double value) const; - void AddBool (Message* message, - const FieldDescriptor* field, bool value) const; - void AddString(Message* message, - const FieldDescriptor* field, const string& value) const; - void AddEnum(Message* message, - const FieldDescriptor* field, - const EnumValueDescriptor* value) const; - void AddEnumValue(Message* message, - const FieldDescriptor* field, - int value) const; + void AddInt32(Message* message, const FieldDescriptor* field, + int32 value) const override; + void AddInt64(Message* message, const FieldDescriptor* field, + int64 value) const override; + void AddUInt32(Message* message, const FieldDescriptor* field, + uint32 value) const override; + void AddUInt64(Message* message, const FieldDescriptor* field, + uint64 value) const override; + void AddFloat(Message* message, const FieldDescriptor* field, + float value) const override; + void AddDouble(Message* message, const FieldDescriptor* field, + double value) const override; + void AddBool(Message* message, const FieldDescriptor* field, + bool value) const override; + void AddString(Message* message, const FieldDescriptor* field, + const std::string& value) const override; + void AddEnum(Message* message, const FieldDescriptor* field, + const EnumValueDescriptor* value) const override; + void AddEnumValue(Message* message, const FieldDescriptor* field, + int value) const override; Message* AddMessage(Message* message, const FieldDescriptor* field, - MessageFactory* factory = NULL) const; - void AddAllocatedMessage( - Message* message, const FieldDescriptor* field, - Message* new_entry) const; + MessageFactory* factory = NULL) const override; + void AddAllocatedMessage(Message* message, const FieldDescriptor* field, + Message* new_entry) const override; - const FieldDescriptor* FindKnownExtensionByName(const string& name) const; - const FieldDescriptor* FindKnownExtensionByNumber(int number) const; + const FieldDescriptor* FindKnownExtensionByName( + const std::string& name) const override; + const FieldDescriptor* FindKnownExtensionByNumber(int number) const override; - bool SupportsUnknownEnumValues() const; + bool SupportsUnknownEnumValues() const override; // This value for arena_offset_ indicates that there is no arena pointer in // this message (e.g., old generated code). @@ -512,24 +515,23 @@ class GeneratedMessageReflection final : public Reflection { static const int kUnknownFieldSetInMetadata = -1; protected: - void* MutableRawRepeatedField( - Message* message, const FieldDescriptor* field, FieldDescriptor::CppType, - int ctype, const Descriptor* desc) const; + void* MutableRawRepeatedField(Message* message, const FieldDescriptor* field, + FieldDescriptor::CppType, int ctype, + const Descriptor* desc) const override; - const void* GetRawRepeatedField( - const Message& message, const FieldDescriptor* field, - FieldDescriptor::CppType, int ctype, - const Descriptor* desc) const; + const void* GetRawRepeatedField(const Message& message, + const FieldDescriptor* field, + FieldDescriptor::CppType, int ctype, + const Descriptor* desc) const override; - virtual MessageFactory* GetMessageFactory() const; + MessageFactory* GetMessageFactory() const override; - virtual void* RepeatedFieldData( - Message* message, const FieldDescriptor* field, - FieldDescriptor::CppType cpp_type, - const Descriptor* message_type) const; + void* RepeatedFieldData(Message* message, const FieldDescriptor* field, + FieldDescriptor::CppType cpp_type, + const Descriptor* message_type) const override; private: - friend class google::protobuf::flat::MetadataBuilder; + friend class ReflectionAccessor; friend class upb::google_opensource::GMR_Handlers; const Descriptor* const descriptor_; @@ -550,21 +552,18 @@ class GeneratedMessageReflection final : public Reflection { template const Type& GetRaw(const Message& message, - const FieldDescriptor* field) const; + const FieldDescriptor* field) const; template - inline Type* MutableRaw(Message* message, - const FieldDescriptor* field) const; + inline Type* MutableRaw(Message* message, const FieldDescriptor* field) const; template inline const Type& DefaultRaw(const FieldDescriptor* field) const; inline const uint32* GetHasBits(const Message& message) const; inline uint32* MutableHasBits(Message* message) const; - inline uint32 GetOneofCase( - const Message& message, - const OneofDescriptor* oneof_descriptor) const; + inline uint32 GetOneofCase(const Message& message, + const OneofDescriptor* oneof_descriptor) const; inline uint32* MutableOneofCase( - Message* message, - const OneofDescriptor* oneof_descriptor) const; + Message* message, const OneofDescriptor* oneof_descriptor) const; inline const ExtensionSet& GetExtensionSet(const Message& message) const; inline ExtensionSet* MutableExtensionSet(Message* message) const; inline Arena* GetArena(Message* message) const; @@ -572,29 +571,24 @@ class GeneratedMessageReflection final : public Reflection { inline const InternalMetadataWithArena& GetInternalMetadataWithArena( const Message& message) const; - inline InternalMetadataWithArena* - MutableInternalMetadataWithArena(Message* message) const; + inline InternalMetadataWithArena* MutableInternalMetadataWithArena( + Message* message) const; inline bool IsInlined(const FieldDescriptor* field) const; inline bool HasBit(const Message& message, const FieldDescriptor* field) const; - inline void SetBit(Message* message, - const FieldDescriptor* field) const; - inline void ClearBit(Message* message, - const FieldDescriptor* field) const; - inline void SwapBit(Message* message1, - Message* message2, + inline void SetBit(Message* message, const FieldDescriptor* field) const; + inline void ClearBit(Message* message, const FieldDescriptor* field) const; + inline void SwapBit(Message* message1, Message* message2, const FieldDescriptor* field) const; // This function only swaps the field. Should swap corresponding has_bit // before or after using this function. - void SwapField(Message* message1, - Message* message2, + void SwapField(Message* message1, Message* message2, const FieldDescriptor* field) const; - void SwapOneofField(Message* message1, - Message* message2, + void SwapOneofField(Message* message1, Message* message2, const OneofDescriptor* oneof_descriptor) const; inline bool HasOneofField(const Message& message, @@ -608,8 +602,8 @@ class GeneratedMessageReflection final : public Reflection { inline const Type& GetField(const Message& message, const FieldDescriptor* field) const; template - inline void SetField(Message* message, - const FieldDescriptor* field, const Type& value) const; + inline void SetField(Message* message, const FieldDescriptor* field, + const Type& value) const; template inline Type* MutableField(Message* message, const FieldDescriptor* field) const; @@ -622,46 +616,42 @@ class GeneratedMessageReflection final : public Reflection { const FieldDescriptor* field, int index) const; template - inline void SetRepeatedField(Message* message, - const FieldDescriptor* field, int index, - Type value) const; + inline void SetRepeatedField(Message* message, const FieldDescriptor* field, + int index, Type value) const; template inline Type* MutableRepeatedField(Message* message, const FieldDescriptor* field, int index) const; template - inline void AddField(Message* message, - const FieldDescriptor* field, const Type& value) const; + inline void AddField(Message* message, const FieldDescriptor* field, + const Type& value) const; template - inline Type* AddField(Message* message, - const FieldDescriptor* field) const; + inline Type* AddField(Message* message, const FieldDescriptor* field) const; int GetExtensionNumberOrDie(const Descriptor* type) const; // Internal versions of EnumValue API perform no checking. Called after checks // by public methods. - void SetEnumValueInternal(Message* message, - const FieldDescriptor* field, + void SetEnumValueInternal(Message* message, const FieldDescriptor* field, int value) const; void SetRepeatedEnumValueInternal(Message* message, - const FieldDescriptor* field, - int index, + const FieldDescriptor* field, int index, int value) const; - void AddEnumValueInternal(Message* message, - const FieldDescriptor* field, + void AddEnumValueInternal(Message* message, const FieldDescriptor* field, int value) const; - Message* UnsafeArenaReleaseMessage(Message* message, const FieldDescriptor* field, MessageFactory* factory = NULL) const; - void UnsafeArenaSetAllocatedMessage(Message* message, - Message* sub_message, + void UnsafeArenaSetAllocatedMessage(Message* message, Message* sub_message, const FieldDescriptor* field) const; - internal::MapFieldBase* MapData( - Message* message, const FieldDescriptor* field) const; + internal::MapFieldBase* MutableMapData( + Message* message, const FieldDescriptor* field) const override; + + const internal::MapFieldBase* GetMapData( + const Message& message, const FieldDescriptor* field) const override; friend inline // inline so nobody can call this function. void @@ -669,89 +659,49 @@ class GeneratedMessageReflection final : public Reflection { GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(GeneratedMessageReflection); }; -// There are some places in proto2 where dynamic_cast would be useful as an -// optimization. For example, take Message::MergeFrom(const Message& other). -// For a given generated message FooMessage, we generate these two methods: -// void MergeFrom(const FooMessage& other); -// void MergeFrom(const Message& other); -// The former method can be implemented directly in terms of FooMessage's -// inline accessors, but the latter method must work with the reflection -// interface. However, if the parameter to the latter method is actually of -// type FooMessage, then we'd like to be able to just call the other method -// as an optimization. So, we use dynamic_cast to check this. -// -// That said, dynamic_cast requires RTTI, which many people like to disable -// for performance and code size reasons. When RTTI is not available, we -// still need to produce correct results. So, in this case we have to fall -// back to using reflection, which is what we would have done anyway if the -// objects were not of the exact same class. -// -// dynamic_cast_if_available() implements this logic. If RTTI is -// enabled, it does a dynamic_cast. If RTTI is disabled, it just returns -// NULL. -template -inline To dynamic_cast_if_available(From from) { -#ifdef GOOGLE_PROTOBUF_NO_RTTI - // Avoid the compiler warning about unused variables. - (void)from; - return NULL; -#else - return dynamic_cast(from); -#endif -} +struct PROTOBUF_EXPORT DescriptorTable { + bool* is_initialized; + const char* descriptor; + const char* filename; + int size; // of serialized descriptor + once_flag* once; + SCCInfoBase* const* init_default_instances; + const DescriptorTable* const* deps; + int num_sccs; + int num_deps; + const MigrationSchema* schemas; + const Message* const* default_instances; + const uint32* offsets; + // update the following descriptor arrays. + Metadata* file_level_metadata; + int num_messages; + const EnumDescriptor** file_level_enum_descriptors; + const ServiceDescriptor** file_level_service_descriptors; +}; -// Tries to downcast this message to a generated message type. -// Returns NULL if this class is not an instance of T. -// -// This is like dynamic_cast_if_available, except it works even when -// dynamic_cast is not available by using Reflection. However it only works -// with Message objects. -// -// TODO(haberman): can we remove dynamic_cast_if_available in favor of this? -template -T* DynamicCastToGenerated(const Message* from) { - // Compile-time assert that T is a generated type that has a - // default_instance() accessor, but avoid actually calling it. - const T&(*get_default_instance)() = &T::default_instance; - (void)get_default_instance; +// AssignDescriptors() pulls the compiled FileDescriptor from the DescriptorPool +// and uses it to populate all of the global variables which store pointers to +// the descriptor objects. It also constructs the reflection objects. It is +// called the first time anyone calls descriptor() or GetReflection() on one of +// the types defined in the file. AssignDescriptors() is thread-safe. +void PROTOBUF_EXPORT AssignDescriptors(const DescriptorTable* table); - // Compile-time assert that T is a subclass of google::protobuf::Message. - const Message* unused = static_cast(NULL); - (void)unused; - -#ifdef GOOGLE_PROTOBUF_NO_RTTI - bool ok = &T::default_instance() == - from->GetReflection()->GetMessageFactory()->GetPrototype( - from->GetDescriptor()); - return ok ? down_cast(from) : NULL; -#else - return dynamic_cast(from); -#endif -} - -template -T* DynamicCastToGenerated(Message* from) { - const Message* message_const = from; - return const_cast(DynamicCastToGenerated(message_const)); -} - -LIBPROTOBUF_EXPORT void AssignDescriptors( - const string& filename, const MigrationSchema* schemas, - const Message* const* default_instances_, const uint32* offsets, - // update the following descriptor arrays. - Metadata* file_level_metadata, - const EnumDescriptor** file_level_enum_descriptors, - const ServiceDescriptor** file_level_service_descriptors); - -LIBPROTOBUF_EXPORT void RegisterAllTypes(const Metadata* file_level_metadata, int size); +// AddDescriptors() is a file-level procedure which adds the encoded +// FileDescriptorProto for this .proto file to the global DescriptorPool for +// generated files (DescriptorPool::generated_pool()). It ordinarily runs at +// static initialization time, but is not used at all in LITE_RUNTIME mode. +// AddDescriptors() is *not* thread-safe. +void PROTOBUF_EXPORT AddDescriptors(const DescriptorTable* table); // These cannot be in lite so we put them in the reflection. -LIBPROTOBUF_EXPORT void UnknownFieldSetSerializer(const uint8* base, uint32 offset, uint32 tag, - uint32 has_offset, - ::google::protobuf::io::CodedOutputStream* output); +PROTOBUF_EXPORT void UnknownFieldSetSerializer(const uint8* base, uint32 offset, + uint32 tag, uint32 has_offset, + io::CodedOutputStream* output); } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_GENERATED_MESSAGE_REFLECTION_H__ diff --git a/third_party/protobuf/src/google/protobuf/generated_message_reflection_unittest.cc b/third_party/protobuf/src/google/protobuf/generated_message_reflection_unittest.cc index 61eb6603..eea5da53 100644 --- a/third_party/protobuf/src/google/protobuf/generated_message_reflection_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/generated_message_reflection_unittest.cc @@ -61,9 +61,9 @@ namespace protobuf { namespace { // Shorthand to get a FieldDescriptor for a field of unittest::TestAllTypes. -const FieldDescriptor* F(const string& name) { +const FieldDescriptor* F(const std::string& name) { const FieldDescriptor* result = - unittest::TestAllTypes::descriptor()->FindFieldByName(name); + unittest::TestAllTypes::descriptor()->FindFieldByName(name); GOOGLE_CHECK(result != NULL); return result; } @@ -72,7 +72,7 @@ TEST(GeneratedMessageReflectionTest, Defaults) { // Check that all default values are set correctly in the initial message. unittest::TestAllTypes message; TestUtil::ReflectionTester reflection_tester( - unittest::TestAllTypes::descriptor()); + unittest::TestAllTypes::descriptor()); reflection_tester.ExpectClearViaReflection(message); @@ -96,7 +96,7 @@ TEST(GeneratedMessageReflectionTest, Accessors) { // values. unittest::TestAllTypes message; TestUtil::ReflectionTester reflection_tester( - unittest::TestAllTypes::descriptor()); + unittest::TestAllTypes::descriptor()); reflection_tester.SetAllFieldsViaReflection(&message); TestUtil::ExpectAllFieldsSet(message); @@ -107,24 +107,26 @@ TEST(GeneratedMessageReflectionTest, Accessors) { } TEST(GeneratedMessageReflectionTest, GetStringReference) { - // Test that GetStringReference() returns the underlying string when it is - // a normal string field. + // Test that GetStringReference() returns the underlying string when it + // is a normal string field. unittest::TestAllTypes message; message.set_optional_string("foo"); message.add_repeated_string("foo"); const Reflection* reflection = message.GetReflection(); - string scratch; + std::string scratch; - EXPECT_EQ(&message.optional_string(), + EXPECT_EQ( + &message.optional_string(), &reflection->GetStringReference(message, F("optional_string"), &scratch)) - << "For simple string fields, GetStringReference() should return a " - "reference to the underlying string."; + << "For simple string fields, GetStringReference() should return a " + "reference to the underlying string."; EXPECT_EQ(&message.repeated_string(0), - &reflection->GetRepeatedStringReference(message, F("repeated_string"), - 0, &scratch)) - << "For simple string fields, GetRepeatedStringReference() should return " - "a reference to the underlying string."; + &reflection->GetRepeatedStringReference( + message, F("repeated_string"), 0, &scratch)) + << "For simple string fields, GetRepeatedStringReference() should " + "return " + "a reference to the underlying string."; } @@ -133,7 +135,7 @@ TEST(GeneratedMessageReflectionTest, DefaultsAfterClear) { // embedded message does NOT return the default instance. unittest::TestAllTypes message; TestUtil::ReflectionTester reflection_tester( - unittest::TestAllTypes::descriptor()); + unittest::TestAllTypes::descriptor()); TestUtil::SetAllFields(&message); message.Clear(); @@ -150,7 +152,6 @@ TEST(GeneratedMessageReflectionTest, DefaultsAfterClear) { &reflection->GetMessage(message, F("optional_import_message"))); } - TEST(GeneratedMessageReflectionTest, Swap) { unittest::TestAllTypes message1; unittest::TestAllTypes message2; @@ -319,7 +320,7 @@ TEST(GeneratedMessageReflectionTest, SwapFieldsOneof) { TEST(GeneratedMessageReflectionTest, RemoveLast) { unittest::TestAllTypes message; TestUtil::ReflectionTester reflection_tester( - unittest::TestAllTypes::descriptor()); + unittest::TestAllTypes::descriptor()); TestUtil::SetAllFields(&message); @@ -331,7 +332,7 @@ TEST(GeneratedMessageReflectionTest, RemoveLast) { TEST(GeneratedMessageReflectionTest, RemoveLastExtensions) { unittest::TestAllExtensions message; TestUtil::ReflectionTester reflection_tester( - unittest::TestAllExtensions::descriptor()); + unittest::TestAllExtensions::descriptor()); TestUtil::SetAllExtensions(&message); @@ -376,21 +377,20 @@ TEST(GeneratedMessageReflectionTest, ReleaseLastExtensions) { // Now test that we actually release the right message. message.Clear(); TestUtil::SetAllExtensions(&message); - ASSERT_EQ(2, message.ExtensionSize( - unittest::repeated_foreign_message_extension)); - const protobuf_unittest::ForeignMessage* expected = message.MutableExtension( - unittest::repeated_foreign_message_extension, 1); + ASSERT_EQ( + 2, message.ExtensionSize(unittest::repeated_foreign_message_extension)); + const protobuf_unittest::ForeignMessage* expected = + message.MutableExtension(unittest::repeated_foreign_message_extension, 1); std::unique_ptr released(message.GetReflection()->ReleaseLast( &message, descriptor->file()->FindExtensionByName( "repeated_foreign_message_extension"))); EXPECT_EQ(expected, released.get()); - } TEST(GeneratedMessageReflectionTest, SwapRepeatedElements) { unittest::TestAllTypes message; TestUtil::ReflectionTester reflection_tester( - unittest::TestAllTypes::descriptor()); + unittest::TestAllTypes::descriptor()); TestUtil::SetAllFields(&message); @@ -406,7 +406,7 @@ TEST(GeneratedMessageReflectionTest, SwapRepeatedElements) { TEST(GeneratedMessageReflectionTest, SwapRepeatedElementsExtension) { unittest::TestAllExtensions message; TestUtil::ReflectionTester reflection_tester( - unittest::TestAllExtensions::descriptor()); + unittest::TestAllExtensions::descriptor()); TestUtil::SetAllExtensions(&message); @@ -424,7 +424,7 @@ TEST(GeneratedMessageReflectionTest, Extensions) { // values. unittest::TestAllExtensions message; TestUtil::ReflectionTester reflection_tester( - unittest::TestAllExtensions::descriptor()); + unittest::TestAllExtensions::descriptor()); reflection_tester.SetAllFieldsViaReflection(&message); TestUtil::ExpectAllExtensionsSet(message); @@ -436,14 +436,14 @@ TEST(GeneratedMessageReflectionTest, Extensions) { TEST(GeneratedMessageReflectionTest, FindExtensionTypeByNumber) { const Reflection* reflection = - unittest::TestAllExtensions::default_instance().GetReflection(); + unittest::TestAllExtensions::default_instance().GetReflection(); const FieldDescriptor* extension1 = - unittest::TestAllExtensions::descriptor()->file()->FindExtensionByName( - "optional_int32_extension"); + unittest::TestAllExtensions::descriptor()->file()->FindExtensionByName( + "optional_int32_extension"); const FieldDescriptor* extension2 = - unittest::TestAllExtensions::descriptor()->file()->FindExtensionByName( - "repeated_string_extension"); + unittest::TestAllExtensions::descriptor()->file()->FindExtensionByName( + "repeated_string_extension"); EXPECT_EQ(extension1, reflection->FindKnownExtensionByNumber(extension1->number())); @@ -455,20 +455,21 @@ TEST(GeneratedMessageReflectionTest, FindExtensionTypeByNumber) { // Extensions of TestAllExtensions should not show up as extensions of // other types. - EXPECT_TRUE(unittest::TestAllTypes::default_instance().GetReflection()-> - FindKnownExtensionByNumber(extension1->number()) == NULL); + EXPECT_TRUE(unittest::TestAllTypes::default_instance() + .GetReflection() + ->FindKnownExtensionByNumber(extension1->number()) == NULL); } TEST(GeneratedMessageReflectionTest, FindKnownExtensionByName) { const Reflection* reflection = - unittest::TestAllExtensions::default_instance().GetReflection(); + unittest::TestAllExtensions::default_instance().GetReflection(); const FieldDescriptor* extension1 = - unittest::TestAllExtensions::descriptor()->file()->FindExtensionByName( - "optional_int32_extension"); + unittest::TestAllExtensions::descriptor()->file()->FindExtensionByName( + "optional_int32_extension"); const FieldDescriptor* extension2 = - unittest::TestAllExtensions::descriptor()->file()->FindExtensionByName( - "repeated_string_extension"); + unittest::TestAllExtensions::descriptor()->file()->FindExtensionByName( + "repeated_string_extension"); EXPECT_EQ(extension1, reflection->FindKnownExtensionByName(extension1->full_name())); @@ -480,8 +481,9 @@ TEST(GeneratedMessageReflectionTest, FindKnownExtensionByName) { // Extensions of TestAllExtensions should not show up as extensions of // other types. - EXPECT_TRUE(unittest::TestAllTypes::default_instance().GetReflection()-> - FindKnownExtensionByName(extension1->full_name()) == NULL); + EXPECT_TRUE(unittest::TestAllTypes::default_instance() + .GetReflection() + ->FindKnownExtensionByName(extension1->full_name()) == NULL); } TEST(GeneratedMessageReflectionTest, SetAllocatedMessageTest) { @@ -489,7 +491,7 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedMessageTest) { unittest::TestAllTypes from_message2; unittest::TestAllTypes to_message; TestUtil::ReflectionTester reflection_tester( - unittest::TestAllTypes::descriptor()); + unittest::TestAllTypes::descriptor()); reflection_tester.SetAllFieldsViaReflection(&from_message1); reflection_tester.SetAllFieldsViaReflection(&from_message2); @@ -520,11 +522,11 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedMessageTest) { TEST(GeneratedMessageReflectionTest, SetAllocatedMessageOnArenaTest) { unittest::TestAllTypes from_message1; unittest::TestAllTypes from_message2; - ::google::protobuf::Arena arena; + Arena arena; unittest::TestAllTypes* to_message = - ::google::protobuf::Arena::CreateMessage(&arena); + Arena::CreateMessage(&arena); TestUtil::ReflectionTester reflection_tester( - unittest::TestAllTypes::descriptor()); + unittest::TestAllTypes::descriptor()); reflection_tester.SetAllFieldsViaReflection(&from_message1); reflection_tester.SetAllFieldsViaReflection(&from_message2); @@ -557,7 +559,7 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedExtensionMessageTest) { unittest::TestAllExtensions from_message2; unittest::TestAllExtensions to_message; TestUtil::ReflectionTester reflection_tester( - unittest::TestAllExtensions::descriptor()); + unittest::TestAllExtensions::descriptor()); reflection_tester.SetAllFieldsViaReflection(&from_message1); reflection_tester.SetAllFieldsViaReflection(&from_message2); @@ -586,13 +588,13 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedExtensionMessageTest) { } TEST(GeneratedMessageReflectionTest, SetAllocatedExtensionMessageOnArenaTest) { - ::google::protobuf::Arena arena; + Arena arena; unittest::TestAllExtensions* to_message = - ::google::protobuf::Arena::CreateMessage(&arena); + Arena::CreateMessage(&arena); unittest::TestAllExtensions from_message1; unittest::TestAllExtensions from_message2; TestUtil::ReflectionTester reflection_tester( - unittest::TestAllExtensions::descriptor()); + unittest::TestAllExtensions::descriptor()); reflection_tester.SetAllFieldsViaReflection(&from_message1); reflection_tester.SetAllFieldsViaReflection(&from_message2); @@ -631,8 +633,8 @@ TEST(GeneratedMessageReflectionTest, AddRepeatedMessage) { unittest::TestAllTypes::NestedMessage::descriptor()->FindFieldByName( "bb"); - Message* nested = reflection->AddMessage( - &message, F("repeated_nested_message")); + Message* nested = + reflection->AddMessage(&message, F("repeated_nested_message")); nested_reflection->SetInt32(nested, nested_bb, 11); EXPECT_EQ(11, message.repeated_nested_message(0).bb()); @@ -666,7 +668,8 @@ TEST(GeneratedMessageReflectionTest, AddAllocatedMessage) { unittest::TestAllTypes::NestedMessage* nested = new unittest::TestAllTypes::NestedMessage(); nested->set_bb(11); - reflection->AddAllocatedMessage(&message, F("repeated_nested_message"), nested); + reflection->AddAllocatedMessage(&message, F("repeated_nested_message"), + nested); EXPECT_EQ(1, message.repeated_nested_message_size()); EXPECT_EQ(11, message.repeated_nested_message(0).bb()); } @@ -687,62 +690,68 @@ TEST(GeneratedMessageReflectionTest, Oneof) { const Reflection* reflection = message.GetReflection(); // Check default values. - EXPECT_EQ(0, reflection->GetInt32( - message, descriptor->FindFieldByName("foo_int"))); + EXPECT_EQ( + 0, reflection->GetInt32(message, descriptor->FindFieldByName("foo_int"))); EXPECT_EQ("", reflection->GetString( - message, descriptor->FindFieldByName("foo_string"))); + message, descriptor->FindFieldByName("foo_string"))); + EXPECT_EQ("", reflection->GetString(message, + descriptor->FindFieldByName("foo_cord"))); EXPECT_EQ("", reflection->GetString( - message, descriptor->FindFieldByName("foo_cord"))); + message, descriptor->FindFieldByName("foo_string_piece"))); EXPECT_EQ("", reflection->GetString( - message, descriptor->FindFieldByName("foo_string_piece"))); - EXPECT_EQ("", reflection->GetString( - message, descriptor->FindFieldByName("foo_bytes"))); - EXPECT_EQ(unittest::TestOneof2::FOO, reflection->GetEnum( - message, descriptor->FindFieldByName("foo_enum"))->number()); + message, descriptor->FindFieldByName("foo_bytes"))); + EXPECT_EQ( + unittest::TestOneof2::FOO, + reflection->GetEnum(message, descriptor->FindFieldByName("foo_enum")) + ->number()); EXPECT_EQ(&unittest::TestOneof2::NestedMessage::default_instance(), &reflection->GetMessage( message, descriptor->FindFieldByName("foo_message"))); EXPECT_EQ(&unittest::TestOneof2::FooGroup::default_instance(), - &reflection->GetMessage( - message, descriptor->FindFieldByName("foogroup"))); + &reflection->GetMessage(message, + descriptor->FindFieldByName("foogroup"))); EXPECT_NE(&unittest::TestOneof2::FooGroup::default_instance(), &reflection->GetMessage( message, descriptor->FindFieldByName("foo_lazy_message"))); - EXPECT_EQ(5, reflection->GetInt32( - message, descriptor->FindFieldByName("bar_int"))); + EXPECT_EQ( + 5, reflection->GetInt32(message, descriptor->FindFieldByName("bar_int"))); EXPECT_EQ("STRING", reflection->GetString( - message, descriptor->FindFieldByName("bar_string"))); + message, descriptor->FindFieldByName("bar_string"))); EXPECT_EQ("CORD", reflection->GetString( - message, descriptor->FindFieldByName("bar_cord"))); - EXPECT_EQ("SPIECE", reflection->GetString( - message, descriptor->FindFieldByName("bar_string_piece"))); + message, descriptor->FindFieldByName("bar_cord"))); + EXPECT_EQ("SPIECE", + reflection->GetString( + message, descriptor->FindFieldByName("bar_string_piece"))); EXPECT_EQ("BYTES", reflection->GetString( - message, descriptor->FindFieldByName("bar_bytes"))); - EXPECT_EQ(unittest::TestOneof2::BAR, reflection->GetEnum( - message, descriptor->FindFieldByName("bar_enum"))->number()); + message, descriptor->FindFieldByName("bar_bytes"))); + EXPECT_EQ( + unittest::TestOneof2::BAR, + reflection->GetEnum(message, descriptor->FindFieldByName("bar_enum")) + ->number()); // Check Set functions. - reflection->SetInt32( - &message, descriptor->FindFieldByName("foo_int"), 123); - EXPECT_EQ(123, reflection->GetInt32( - message, descriptor->FindFieldByName("foo_int"))); - reflection->SetString( - &message, descriptor->FindFieldByName("foo_string"), "abc"); + reflection->SetInt32(&message, descriptor->FindFieldByName("foo_int"), 123); + EXPECT_EQ(123, reflection->GetInt32(message, + descriptor->FindFieldByName("foo_int"))); + reflection->SetString(&message, descriptor->FindFieldByName("foo_string"), + "abc"); EXPECT_EQ("abc", reflection->GetString( - message, descriptor->FindFieldByName("foo_string"))); - reflection->SetString( - &message, descriptor->FindFieldByName("foo_bytes"), "bytes"); + message, descriptor->FindFieldByName("foo_string"))); + reflection->SetString(&message, descriptor->FindFieldByName("foo_bytes"), + "bytes"); EXPECT_EQ("bytes", reflection->GetString( - message, descriptor->FindFieldByName("foo_bytes"))); - reflection->SetString( - &message, descriptor->FindFieldByName("bar_cord"), "change_cord"); - EXPECT_EQ("change_cord", reflection->GetString( - message, descriptor->FindFieldByName("bar_cord"))); - reflection->SetString( - &message, descriptor->FindFieldByName("bar_string_piece"), - "change_spiece"); - EXPECT_EQ("change_spiece", reflection->GetString( - message, descriptor->FindFieldByName("bar_string_piece"))); + message, descriptor->FindFieldByName("foo_bytes"))); + reflection->SetString(&message, descriptor->FindFieldByName("bar_cord"), + "change_cord"); + EXPECT_EQ( + "change_cord", + reflection->GetString(message, descriptor->FindFieldByName("bar_cord"))); + reflection->SetString(&message, + descriptor->FindFieldByName("bar_string_piece"), + "change_spiece"); + EXPECT_EQ("change_spiece", + reflection->GetString( + message, descriptor->FindFieldByName("bar_string_piece"))); message.clear_foo(); message.clear_bar(); @@ -767,8 +776,8 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageTest) { TestUtil::ReflectionTester::ExpectOneofSetViaReflection(from_message1); TestUtil::ReflectionTester:: - SetAllocatedOptionalMessageFieldsToMessageViaReflection( - &from_message1, &to_message); + SetAllocatedOptionalMessageFieldsToMessageViaReflection(&from_message1, + &to_message); const Message& sub_message = reflection->GetMessage( to_message, descriptor->FindFieldByName("foo_lazy_message")); released = reflection->ReleaseMessage( @@ -779,12 +788,12 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageTest) { TestUtil::ReflectionTester::SetOneofViaReflection(&from_message2); - reflection->MutableMessage( - &from_message2, descriptor->FindFieldByName("foo_message")); + reflection->MutableMessage(&from_message2, + descriptor->FindFieldByName("foo_message")); TestUtil::ReflectionTester:: - SetAllocatedOptionalMessageFieldsToMessageViaReflection( - &from_message2, &to_message); + SetAllocatedOptionalMessageFieldsToMessageViaReflection(&from_message2, + &to_message); const Message& sub_message2 = reflection->GetMessage( to_message, descriptor->FindFieldByName("foo_message")); @@ -798,9 +807,9 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageTest) { TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageOnArenaTest) { unittest::TestOneof2 from_message1; unittest::TestOneof2 from_message2; - ::google::protobuf::Arena arena; + Arena arena; unittest::TestOneof2* to_message = - ::google::protobuf::Arena::CreateMessage(&arena); + Arena::CreateMessage(&arena); const Descriptor* descriptor = unittest::TestOneof2::descriptor(); const Reflection* reflection = to_message->GetReflection(); @@ -815,8 +824,8 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageOnArenaTest) { TestUtil::ReflectionTester::ExpectOneofSetViaReflection(from_message1); TestUtil::ReflectionTester:: - SetAllocatedOptionalMessageFieldsToMessageViaReflection( - &from_message1, to_message); + SetAllocatedOptionalMessageFieldsToMessageViaReflection(&from_message1, + to_message); const Message& sub_message = reflection->GetMessage( *to_message, descriptor->FindFieldByName("foo_lazy_message")); released = reflection->ReleaseMessage( @@ -829,12 +838,12 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageOnArenaTest) { TestUtil::ReflectionTester::SetOneofViaReflection(&from_message2); - reflection->MutableMessage( - &from_message2, descriptor->FindFieldByName("foo_message")); + reflection->MutableMessage(&from_message2, + descriptor->FindFieldByName("foo_message")); TestUtil::ReflectionTester:: - SetAllocatedOptionalMessageFieldsToMessageViaReflection( - &from_message2, to_message); + SetAllocatedOptionalMessageFieldsToMessageViaReflection(&from_message2, + to_message); const Message& sub_message2 = reflection->GetMessage( *to_message, descriptor->FindFieldByName("foo_message")); @@ -847,11 +856,10 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageOnArenaTest) { delete released; } - TEST(GeneratedMessageReflectionTest, ReleaseMessageTest) { unittest::TestAllTypes message; TestUtil::ReflectionTester reflection_tester( - unittest::TestAllTypes::descriptor()); + unittest::TestAllTypes::descriptor()); // When nothing is set, we expect all released messages to be NULL. reflection_tester.ExpectMessagesReleasedViaReflection( @@ -877,7 +885,7 @@ TEST(GeneratedMessageReflectionTest, ReleaseMessageTest) { TEST(GeneratedMessageReflectionTest, ReleaseExtensionMessageTest) { unittest::TestAllExtensions message; TestUtil::ReflectionTester reflection_tester( - unittest::TestAllExtensions::descriptor()); + unittest::TestAllExtensions::descriptor()); // When nothing is set, we expect all released messages to be NULL. reflection_tester.ExpectMessagesReleasedViaReflection( @@ -921,9 +929,9 @@ TEST(GeneratedMessageReflectionTest, ReleaseOneofMessageTest) { } TEST(GeneratedMessageReflectionTest, ArenaReleaseMessageTest) { - ::google::protobuf::Arena arena; + Arena arena; unittest::TestAllTypes* message = - ::google::protobuf::Arena::CreateMessage(&arena); + Arena::CreateMessage(&arena); TestUtil::ReflectionTester reflection_tester( unittest::TestAllTypes::descriptor()); @@ -945,9 +953,9 @@ TEST(GeneratedMessageReflectionTest, ArenaReleaseMessageTest) { } TEST(GeneratedMessageReflectionTest, ArenaReleaseExtensionMessageTest) { - ::google::protobuf::Arena arena; + Arena arena; unittest::TestAllExtensions* message = - ::google::protobuf::Arena::CreateMessage(&arena); + Arena::CreateMessage(&arena); TestUtil::ReflectionTester reflection_tester( unittest::TestAllExtensions::descriptor()); @@ -969,9 +977,9 @@ TEST(GeneratedMessageReflectionTest, ArenaReleaseExtensionMessageTest) { } TEST(GeneratedMessageReflectionTest, ArenaReleaseOneofMessageTest) { - ::google::protobuf::Arena arena; + Arena arena; unittest::TestOneof2* message = - ::google::protobuf::Arena::CreateMessage(&arena); + Arena::CreateMessage(&arena); TestUtil::ReflectionTester::SetOneofViaReflection(message); const Descriptor* descriptor = unittest::TestOneof2::descriptor(); @@ -999,39 +1007,41 @@ TEST(GeneratedMessageReflectionTest, UsageErrors) { // Testing every single failure mode would be too much work. Let's just // check a few. EXPECT_DEATH( - reflection->GetInt32( - message, descriptor->FindFieldByName("optional_int64")), - "Protocol Buffer reflection usage error:\n" - " Method : google::protobuf::Reflection::GetInt32\n" - " Message type: protobuf_unittest\\.TestAllTypes\n" - " Field : protobuf_unittest\\.TestAllTypes\\.optional_int64\n" - " Problem : Field is not the right type for this message:\n" - " Expected : CPPTYPE_INT32\n" - " Field type: CPPTYPE_INT64"); + reflection->GetInt32(message, + descriptor->FindFieldByName("optional_int64")), + "Protocol Buffer reflection usage error:\n" + " Method : google::protobuf::Reflection::GetInt32\n" + " Message type: protobuf_unittest\\.TestAllTypes\n" + " Field : protobuf_unittest\\.TestAllTypes\\.optional_int64\n" + " Problem : Field is not the right type for this message:\n" + " Expected : CPPTYPE_INT32\n" + " Field type: CPPTYPE_INT64"); + EXPECT_DEATH(reflection->GetInt32( + message, descriptor->FindFieldByName("repeated_int32")), + "Protocol Buffer reflection usage error:\n" + " Method : google::protobuf::Reflection::GetInt32\n" + " Message type: protobuf_unittest.TestAllTypes\n" + " Field : protobuf_unittest.TestAllTypes.repeated_int32\n" + " Problem : Field is repeated; the method requires a " + "singular field."); EXPECT_DEATH( - reflection->GetInt32( - message, descriptor->FindFieldByName("repeated_int32")), - "Protocol Buffer reflection usage error:\n" - " Method : google::protobuf::Reflection::GetInt32\n" - " Message type: protobuf_unittest.TestAllTypes\n" - " Field : protobuf_unittest.TestAllTypes.repeated_int32\n" - " Problem : Field is repeated; the method requires a singular field."); + reflection->GetInt32( + message, + unittest::ForeignMessage::descriptor()->FindFieldByName("c")), + "Protocol Buffer reflection usage error:\n" + " Method : google::protobuf::Reflection::GetInt32\n" + " Message type: protobuf_unittest.TestAllTypes\n" + " Field : protobuf_unittest.ForeignMessage.c\n" + " Problem : Field does not match message type."); EXPECT_DEATH( - reflection->GetInt32( - message, unittest::ForeignMessage::descriptor()->FindFieldByName("c")), - "Protocol Buffer reflection usage error:\n" - " Method : google::protobuf::Reflection::GetInt32\n" - " Message type: protobuf_unittest.TestAllTypes\n" - " Field : protobuf_unittest.ForeignMessage.c\n" - " Problem : Field does not match message type."); - EXPECT_DEATH( - reflection->HasField( - message, unittest::ForeignMessage::descriptor()->FindFieldByName("c")), - "Protocol Buffer reflection usage error:\n" - " Method : google::protobuf::Reflection::HasField\n" - " Message type: protobuf_unittest.TestAllTypes\n" - " Field : protobuf_unittest.ForeignMessage.c\n" - " Problem : Field does not match message type."); + reflection->HasField( + message, + unittest::ForeignMessage::descriptor()->FindFieldByName("c")), + "Protocol Buffer reflection usage error:\n" + " Method : google::protobuf::Reflection::HasField\n" + " Message type: protobuf_unittest.TestAllTypes\n" + " Field : protobuf_unittest.ForeignMessage.c\n" + " Problem : Field does not match message type."); #undef f } diff --git a/third_party/protobuf/src/google/protobuf/generated_message_table_driven.cc b/third_party/protobuf/src/google/protobuf/generated_message_table_driven.cc index d4450a6c..fb82a8ec 100644 --- a/third_party/protobuf/src/google/protobuf/generated_message_table_driven.cc +++ b/third_party/protobuf/src/google/protobuf/generated_message_table_driven.cc @@ -39,7 +39,6 @@ #include #include #include -#include namespace google { namespace protobuf { @@ -53,33 +52,35 @@ UnknownFieldSet* MutableUnknownFields(MessageLite* msg, int64 arena_offset) { } struct UnknownFieldHandler { + // TODO(mvels): consider renaming UnknownFieldHandler to (TableDrivenTraits?), + // and conflating InternalMetaData into it, simplifying the template. + static constexpr bool IsLite() { return false; } + static bool Skip(MessageLite* msg, const ParseTable& table, - io::CodedInputStream* input, - int tag) { + io::CodedInputStream* input, int tag) { GOOGLE_DCHECK(table.unknown_field_set); return WireFormat::SkipField(input, tag, - MutableUnknownFields(msg, table.arena_offset)); + MutableUnknownFields(msg, table.arena_offset)); } - static void Varint(MessageLite* msg, const ParseTable& table, - int tag, int value) { + static void Varint(MessageLite* msg, const ParseTable& table, int tag, + int value) { GOOGLE_DCHECK(table.unknown_field_set); - MutableUnknownFields(msg, table.arena_offset)->AddVarint( - WireFormatLite::GetTagFieldNumber(tag), value); + MutableUnknownFields(msg, table.arena_offset) + ->AddVarint(WireFormatLite::GetTagFieldNumber(tag), value); } - static bool ParseExtension( - MessageLite* msg, const ParseTable& table, - io::CodedInputStream* input, int tag) { + static bool ParseExtension(MessageLite* msg, const ParseTable& table, + io::CodedInputStream* input, int tag) { ExtensionSet* extensions = GetExtensionSet(msg, table.extension_offset); if (extensions == NULL) { return false; } - const Message* prototype = down_cast( - table.default_instance()); + const Message* prototype = + down_cast(table.default_instance()); GOOGLE_DCHECK(prototype != NULL); GOOGLE_DCHECK(table.unknown_field_set); @@ -92,8 +93,8 @@ struct UnknownFieldHandler { } // namespace -bool MergePartialFromCodedStream( - MessageLite* msg, const ParseTable& table, io::CodedInputStream* input) { +bool MergePartialFromCodedStream(MessageLite* msg, const ParseTable& table, + io::CodedInputStream* input) { return MergePartialFromCodedStreamImpl(msg, table, input); diff --git a/third_party/protobuf/src/google/protobuf/generated_message_table_driven.h b/third_party/protobuf/src/google/protobuf/generated_message_table_driven.h index 10ca3aaa..1394ab14 100644 --- a/third_party/protobuf/src/google/protobuf/generated_message_table_driven.h +++ b/third_party/protobuf/src/google/protobuf/generated_message_table_driven.h @@ -36,7 +36,6 @@ #include #include #include -#include // We require C++11 and Clang to use constexpr for variables, as GCC 4.8 // requires constexpr to be consistent between declarations of variables @@ -48,6 +47,12 @@ #define PROTOBUF_CONSTEXPR_VAR #endif // !_clang +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + +#include + namespace google { namespace protobuf { namespace internal { @@ -64,6 +69,10 @@ static constexpr const unsigned char kNotPackedMask = 0x10; static constexpr const unsigned char kInvalidMask = 0x20; enum ProcessingTypes { + TYPE_STRING_CORD = 19, + TYPE_STRING_STRING_PIECE = 20, + TYPE_BYTES_CORD = 21, + TYPE_BYTES_STRING_PIECE = 22, TYPE_STRING_INLINED = 23, TYPE_BYTES_INLINED = 24, TYPE_MAP = 25, @@ -71,6 +80,40 @@ enum ProcessingTypes { static_assert(TYPE_MAP < kRepeatedMask, "Invalid enum"); +struct PROTOBUF_EXPORT FieldMetadata { + uint32 offset; // offset of this field in the struct + uint32 tag; // field * 8 + wire_type + // byte offset * 8 + bit_offset; + // if the high bit is set then this is the byte offset of the oneof_case + // for this field. + uint32 has_offset; + uint32 type; // the type of this field. + const void* ptr; // auxiliary data + + // From the serializer point of view each fundamental type can occur in + // 4 different ways. For simplicity we treat all combinations as a cartesion + // product although not all combinations are allowed. + enum FieldTypeClass { + kPresence, + kNoPresence, + kRepeated, + kPacked, + kOneOf, + kNumTypeClasses // must be last enum + }; + // C++ protobuf has 20 fundamental types, were we added Cord and StringPiece + // and also distinquish the same types if they have different wire format. + enum { + kCordType = 19, + kStringPieceType = 20, + kInlinedType = 21, + kNumTypes = 21, + kSpecial = kNumTypes * kNumTypeClasses, + }; + + static int CalculateType(int fundamental_type, FieldTypeClass type_class); +}; + // TODO(ckennelly): Add a static assertion to ensure that these masks do not // conflict with wiretypes. @@ -164,37 +207,133 @@ static_assert(sizeof(ParseTableField) <= 16, "ParseTableField is too large"); // The tables must be composed of POD components to ensure link-time // initialization. static_assert(std::is_pod::value, ""); +static_assert(std::is_pod::value, ""); static_assert(std::is_pod::value, ""); static_assert(std::is_pod::value, ""); static_assert(std::is_pod::value, ""); static_assert(std::is_pod::value, ""); -#ifndef __NVCC__ // This assertion currently fails under NVCC. -static_assert(std::is_pod::value, ""); -#endif - // TODO(ckennelly): Consolidate these implementations into a single one, using // dynamic dispatch to the appropriate unknown field handler. bool MergePartialFromCodedStream(MessageLite* msg, const ParseTable& table, io::CodedInputStream* input); bool MergePartialFromCodedStreamLite(MessageLite* msg, const ParseTable& table, - io::CodedInputStream* input); + io::CodedInputStream* input); template bool ParseMap(io::CodedInputStream* input, void* map_field) { typedef typename MapEntryToMapField::MapFieldType MapFieldType; - typedef google::protobuf::Map + typedef Map MapType; typedef typename Entry::template Parser ParserType; ParserType parser(static_cast(map_field)); - return ::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(input, - &parser); + return WireFormatLite::ReadMessageNoVirtual(input, &parser); +} + +struct SerializationTable { + int num_fields; + const FieldMetadata* field_table; +}; + +PROTOBUF_EXPORT void SerializeInternal(const uint8* base, + const FieldMetadata* table, + int32 num_fields, + io::CodedOutputStream* output); + +inline void TableSerialize(const MessageLite& msg, + const SerializationTable* table, + io::CodedOutputStream* output) { + const FieldMetadata* field_table = table->field_table; + int num_fields = table->num_fields - 1; + const uint8* base = reinterpret_cast(&msg); + // TODO(gerbens) This skips the first test if we could use the fast + // array serialization path, we should make this + // int cached_size = + // *reinterpret_cast(base + field_table->offset); + // SerializeWithCachedSize(msg, field_table + 1, num_fields, cached_size, ...) + // But we keep conformance with the old way for now. + SerializeInternal(base, field_table + 1, num_fields, output); +} + +uint8* SerializeInternalToArray(const uint8* base, const FieldMetadata* table, + int32 num_fields, bool is_deterministic, + uint8* buffer); + +inline uint8* TableSerializeToArray(const MessageLite& msg, + const SerializationTable* table, + bool is_deterministic, uint8* buffer) { + const uint8* base = reinterpret_cast(&msg); + const FieldMetadata* field_table = table->field_table + 1; + int num_fields = table->num_fields - 1; + return SerializeInternalToArray(base, field_table, num_fields, + is_deterministic, buffer); +} + +template +struct CompareHelper { + bool operator()(const T& a, const T& b) const { return a < b; } +}; + +template <> +struct CompareHelper { + bool operator()(const ArenaStringPtr& a, const ArenaStringPtr& b) const { + return a.Get() < b.Get(); + } +}; + +struct CompareMapKey { + template + bool operator()(const MapEntryHelper& a, + const MapEntryHelper& b) const { + return Compare(a.key_, b.key_); + } + template + bool Compare(const T& a, const T& b) const { + return CompareHelper()(a, b); + } +}; + +template +void MapFieldSerializer(const uint8* base, uint32 offset, uint32 tag, + uint32 has_offset, io::CodedOutputStream* output) { + typedef MapEntryHelper Entry; + typedef typename MapFieldType::MapType::const_iterator Iter; + + const MapFieldType& map_field = + *reinterpret_cast(base + offset); + const SerializationTable* t = + table + + has_offset; // has_offset is overloaded for maps to mean table offset + if (!output->IsSerializationDeterministic()) { + for (Iter it = map_field.GetMap().begin(); it != map_field.GetMap().end(); + ++it) { + Entry map_entry(*it); + output->WriteVarint32(tag); + output->WriteVarint32(map_entry._cached_size_); + SerializeInternal(reinterpret_cast(&map_entry), + t->field_table, t->num_fields, output); + } + } else { + std::vector v; + for (Iter it = map_field.GetMap().begin(); it != map_field.GetMap().end(); + ++it) { + v.push_back(Entry(*it)); + } + std::sort(v.begin(), v.end(), CompareMapKey()); + for (int i = 0; i < v.size(); i++) { + output->WriteVarint32(tag); + output->WriteVarint32(v[i]._cached_size_); + SerializeInternal(reinterpret_cast(&v[i]), t->field_table, + t->num_fields, output); + } + } } } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_GENERATED_MESSAGE_TABLE_DRIVEN_H__ diff --git a/third_party/protobuf/src/google/protobuf/generated_message_table_driven_lite.cc b/third_party/protobuf/src/google/protobuf/generated_message_table_driven_lite.cc index 961329f3..82de6bc9 100644 --- a/third_party/protobuf/src/google/protobuf/generated_message_table_driven_lite.cc +++ b/third_party/protobuf/src/google/protobuf/generated_message_table_driven_lite.cc @@ -36,7 +36,6 @@ #include #include #include -#include namespace google { namespace protobuf { @@ -44,40 +43,40 @@ namespace internal { namespace { -string* MutableUnknownFields(MessageLite* msg, int64 arena_offset) { +std::string* MutableUnknownFields(MessageLite* msg, int64 arena_offset) { return Raw(msg, arena_offset) ->mutable_unknown_fields(); } struct UnknownFieldHandlerLite { - static bool Skip(MessageLite* msg, const ParseTable& table, - io::CodedInputStream* input, - int tag) { - GOOGLE_DCHECK(!table.unknown_field_set); - ::google::protobuf::io::StringOutputStream unknown_fields_string( - MutableUnknownFields(msg, table.arena_offset)); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string, false); + // TODO(mvels): consider renaming UnknownFieldHandler to (TableDrivenTraits?), + // and conflating InternalMetaData into it, simplifying the template. + static constexpr bool IsLite() { return true; } - return ::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream); + static bool Skip(MessageLite* msg, const ParseTable& table, + io::CodedInputStream* input, int tag) { + GOOGLE_DCHECK(!table.unknown_field_set); + io::StringOutputStream unknown_fields_string( + MutableUnknownFields(msg, table.arena_offset)); + io::CodedOutputStream unknown_fields_stream(&unknown_fields_string, false); + + return internal::WireFormatLite::SkipField(input, tag, + &unknown_fields_stream); } - static void Varint(MessageLite* msg, const ParseTable& table, - int tag, int value) { + static void Varint(MessageLite* msg, const ParseTable& table, int tag, + int value) { GOOGLE_DCHECK(!table.unknown_field_set); - ::google::protobuf::io::StringOutputStream unknown_fields_string( + io::StringOutputStream unknown_fields_string( MutableUnknownFields(msg, table.arena_offset)); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string, false); + io::CodedOutputStream unknown_fields_stream(&unknown_fields_string, false); unknown_fields_stream.WriteVarint32(tag); unknown_fields_stream.WriteVarint32(value); } - static bool ParseExtension( - MessageLite* msg, const ParseTable& table, - io::CodedInputStream* input, int tag) { + static bool ParseExtension(MessageLite* msg, const ParseTable& table, + io::CodedInputStream* input, int tag) { ExtensionSet* extensions = GetExtensionSet(msg, table.extension_offset); if (extensions == NULL) { return false; @@ -86,19 +85,18 @@ struct UnknownFieldHandlerLite { const MessageLite* prototype = table.default_instance(); GOOGLE_DCHECK(!table.unknown_field_set); - ::google::protobuf::io::StringOutputStream unknown_fields_string( + io::StringOutputStream unknown_fields_string( MutableUnknownFields(msg, table.arena_offset)); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string, false); - return extensions->ParseField( - tag, input, prototype, &unknown_fields_stream); + io::CodedOutputStream unknown_fields_stream(&unknown_fields_string, false); + return extensions->ParseField(tag, input, prototype, + &unknown_fields_stream); } }; } // namespace -bool MergePartialFromCodedStreamLite( - MessageLite* msg, const ParseTable& table, io::CodedInputStream* input) { +bool MergePartialFromCodedStreamLite(MessageLite* msg, const ParseTable& table, + io::CodedInputStream* input) { return MergePartialFromCodedStreamImpl( msg, table, input); diff --git a/third_party/protobuf/src/google/protobuf/generated_message_table_driven_lite.h b/third_party/protobuf/src/google/protobuf/generated_message_table_driven_lite.h index 0d90fe33..b36e51ba 100644 --- a/third_party/protobuf/src/google/protobuf/generated_message_table_driven_lite.h +++ b/third_party/protobuf/src/google/protobuf/generated_message_table_driven_lite.h @@ -40,10 +40,11 @@ #include #include #include -#include #include +#include + namespace google { namespace protobuf { namespace internal { @@ -83,7 +84,7 @@ inline const Type* Raw(const MessageLite* msg, int64 offset) { template inline Arena* GetArena(MessageLite* msg, int64 arena_offset) { - if (GOOGLE_PREDICT_FALSE(arena_offset == -1)) { + if (PROTOBUF_PREDICT_FALSE(arena_offset == -1)) { return NULL; } @@ -101,18 +102,17 @@ inline ExtensionSet* GetExtensionSet(MessageLite* msg, int64 extension_offset) { template inline Type* AddField(MessageLite* msg, int64 offset) { static_assert(std::is_pod::value || - std::is_same::value, + std::is_same::value, "Do not assign"); - google::protobuf::RepeatedField* repeated = - Raw >(msg, offset); + RepeatedField* repeated = Raw>(msg, offset); return repeated->Add(); } template <> -inline string* AddField(MessageLite* msg, int64 offset) { - google::protobuf::RepeatedPtrField* repeated = - Raw >(msg, offset); +inline std::string* AddField(MessageLite* msg, int64 offset) { + RepeatedPtrField* repeated = + Raw>(msg, offset); return repeated->Add(); } @@ -157,7 +157,7 @@ inline void SetOneofField(MessageLite* msg, uint32* oneof_case, // Clears a oneof field. The field argument should correspond to the particular // field that is currently set in the oneof. inline void ClearOneofField(const ParseTableField& field, Arena* arena, - MessageLite* msg) { + MessageLite* msg) { switch (field.processing_type & kTypeMask) { case WireFormatLite::TYPE_MESSAGE: if (arena == NULL) { @@ -168,7 +168,7 @@ inline void ClearOneofField(const ParseTableField& field, Arena* arena, case WireFormatLite::TYPE_STRING: case WireFormatLite::TYPE_BYTES: Raw(msg, field.offset) - ->Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena); + ->Destroy(&GetEmptyStringAlreadyInited(), arena); break; case TYPE_STRING_INLINED: @@ -206,11 +206,11 @@ inline void ResetOneofField(const ParseTable& table, int field_number, switch (field_type) { case ProcessingType_STRING: Raw(msg, offset) - ->UnsafeSetDefault(static_cast(default_ptr)); + ->UnsafeSetDefault(static_cast(default_ptr)); break; case ProcessingType_INLINED: new (Raw(msg, offset)) - InlinedStringField(*static_cast(default_ptr)); + InlinedStringField(*static_cast(default_ptr)); break; case ProcessingType_MESSAGE: MessageLite** submessage = Raw(msg, offset); @@ -221,16 +221,19 @@ inline void ResetOneofField(const ParseTable& table, int field_number, } } -template +template static inline bool HandleString(io::CodedInputStream* input, MessageLite* msg, Arena* arena, uint32* has_bits, uint32 has_bit_index, int64 offset, const void* default_ptr, const char* field_name) { + StringPiece utf8_string_data; #ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED - const char* sdata; - size_t size; -#endif + constexpr bool kValidateUtf8 = is_string_type; +#else + constexpr bool kValidateUtf8 = false; +#endif // GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED switch (ctype) { case StringType_INLINED: { @@ -238,8 +241,8 @@ static inline bool HandleString(io::CodedInputStream* input, MessageLite* msg, switch (cardinality) { case Cardinality_SINGULAR: // TODO(ckennelly): Is this optimal? - s = MutableField( - msg, has_bits, has_bit_index, offset); + s = MutableField(msg, has_bits, has_bit_index, + offset); break; case Cardinality_REPEATED: s = AddField(msg, offset); @@ -249,56 +252,55 @@ static inline bool HandleString(io::CodedInputStream* input, MessageLite* msg, break; } GOOGLE_DCHECK(s != nullptr); - ::std::string* value = s->MutableNoArena(NULL); - - if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) { + std::string* value = s->MutableNoArena(NULL); + if (PROTOBUF_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) { return false; } - -#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED - sdata = value->data(); - size = value->size(); -#endif + utf8_string_data = *value; break; } case StringType_STRING: { - string* value; switch (cardinality) { - case Cardinality_SINGULAR: - // TODO(ckennelly): Is this optimal? - value = - MutableField(msg, has_bits, has_bit_index, offset) - ->Mutable(static_cast(default_ptr), arena); - break; - case Cardinality_REPEATED: - value = AddField(msg, offset); - break; - case Cardinality_ONEOF: - value = Raw(msg, offset) - ->Mutable(static_cast(default_ptr), arena); - break; + case Cardinality_SINGULAR: { + ArenaStringPtr* field = MutableField( + msg, has_bits, has_bit_index, offset); + std::string* value = field->Mutable( + static_cast(default_ptr), arena); + if (PROTOBUF_PREDICT_FALSE( + !WireFormatLite::ReadString(input, value))) { + return false; + } + utf8_string_data = field->Get(); + } break; + case Cardinality_REPEATED: { + std::string* value = AddField(msg, offset); + if (PROTOBUF_PREDICT_FALSE( + !WireFormatLite::ReadString(input, value))) { + return false; + } + utf8_string_data = *value; + } break; + case Cardinality_ONEOF: { + ArenaStringPtr* field = Raw(msg, offset); + std::string* value = field->Mutable( + static_cast(default_ptr), arena); + if (PROTOBUF_PREDICT_FALSE( + !WireFormatLite::ReadString(input, value))) { + return false; + } + utf8_string_data = field->Get(); + } break; } - GOOGLE_DCHECK(value != nullptr); - - if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) { - return false; - } - -#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED - sdata = value->data(); - size = value->size(); -#endif break; } } -#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED - if (validate) { - WireFormatLite::VerifyUtf8String(sdata, size, WireFormatLite::PARSE, - field_name); + if (kValidateUtf8) { + // TODO(b/118759213): fail if proto3 + WireFormatLite::VerifyUtf8String(utf8_string_data.data(), + utf8_string_data.length(), + WireFormatLite::PARSE, field_name); } -#endif - return true; } @@ -309,7 +311,7 @@ inline bool HandleEnum(const ParseTable& table, io::CodedInputStream* input, uint32 presence_index, int64 offset, uint32 tag, int field_number) { int value; - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( (!WireFormatLite::ReadPrimitive( input, &value)))) { return false; @@ -317,7 +319,7 @@ inline bool HandleEnum(const ParseTable& table, io::CodedInputStream* input, AuxillaryParseTableField::EnumValidator validator = table.aux[field_number].enums.validator; - if (validator(value)) { + if (validator == nullptr || validator(value)) { switch (cardinality) { case Cardinality_SINGULAR: SetField(msg, presence, presence_index, offset, value); @@ -370,9 +372,11 @@ class MergePartialFromCodedStreamHelper { } }; -template -bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, - io::CodedInputStream* input) { +template +bool MergePartialFromCodedStreamInlined(MessageLite* msg, + const ParseTable& table, + io::CodedInputStream* input) { // We require that has_bits are present, as to avoid having to check for them // for every field. // @@ -382,20 +386,19 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, GOOGLE_DCHECK(has_bits != NULL); while (true) { - uint32 tag = input->ReadTag(); - + uint32 tag = input->ReadTagWithCutoffNoLastTag(kMaxTag).first; const WireFormatLite::WireType wire_type = WireFormatLite::GetTagWireType(tag); const int field_number = WireFormatLite::GetTagFieldNumber(tag); - if (field_number > table.max_field_number) { + if (PROTOBUF_PREDICT_FALSE(field_number > table.max_field_number)) { // check for possible extensions if (UnknownFieldHandler::ParseExtension(msg, table, input, tag)) { // successfully parsed continue; } - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( !UnknownFieldHandler::Skip(msg, table, input, tag))) { return false; } @@ -423,7 +426,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, #define HANDLE_TYPE(TYPE, CPPTYPE) \ case (WireFormatLite::TYPE_##TYPE): { \ CPPTYPE value; \ - if (GOOGLE_PREDICT_FALSE( \ + if (PROTOBUF_PREDICT_FALSE( \ (!WireFormatLite::ReadPrimitive< \ CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, &value)))) { \ return false; \ @@ -432,10 +435,9 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, break; \ } \ case (WireFormatLite::TYPE_##TYPE) | kRepeatedMask: { \ - google::protobuf::RepeatedField* values = \ - Raw >(msg, offset); \ - if (GOOGLE_PREDICT_FALSE((!WireFormatLite::ReadRepeatedPrimitive< \ - CPPTYPE, WireFormatLite::TYPE_##TYPE>( \ + RepeatedField* values = Raw>(msg, offset); \ + if (PROTOBUF_PREDICT_FALSE((!WireFormatLite::ReadRepeatedPrimitive< \ + CPPTYPE, WireFormatLite::TYPE_##TYPE>( \ data->tag_size, tag, input, values)))) { \ return false; \ } \ @@ -444,7 +446,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, case (WireFormatLite::TYPE_##TYPE) | kOneofMask: { \ uint32* oneof_case = Raw(msg, table.oneof_case_offset); \ CPPTYPE value; \ - if (GOOGLE_PREDICT_FALSE( \ + if (PROTOBUF_PREDICT_FALSE( \ (!WireFormatLite::ReadPrimitive< \ CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, &value)))) { \ return false; \ @@ -476,16 +478,17 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, case WireFormatLite::TYPE_BYTES: #ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED case WireFormatLite::TYPE_STRING: -#endif +#endif // GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED { Arena* const arena = GetArena(msg, table.arena_offset); const void* default_ptr = table.aux[field_number].strings.default_ptr; - if (GOOGLE_PREDICT_FALSE(( - !HandleString( + if (PROTOBUF_PREDICT_FALSE( + (!HandleString( input, msg, arena, has_bits, presence_index, offset, - default_ptr, NULL)))) { + default_ptr, nullptr)))) { return false; } break; @@ -493,16 +496,17 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, case TYPE_BYTES_INLINED: #ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED case TYPE_STRING_INLINED: -#endif +#endif // !GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED { Arena* const arena = GetArena(msg, table.arena_offset); const void* default_ptr = table.aux[field_number].strings.default_ptr; - if (GOOGLE_PREDICT_FALSE((!HandleString( - input, msg, arena, has_bits, presence_index, offset, - default_ptr, NULL)))) { + if (PROTOBUF_PREDICT_FALSE( + (!HandleString( + input, msg, arena, has_bits, presence_index, offset, + default_ptr, nullptr)))) { return false; } break; @@ -510,7 +514,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, case WireFormatLite::TYPE_BYTES | kOneofMask: #ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED case WireFormatLite::TYPE_STRING | kOneofMask: -#endif +#endif // !GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED { Arena* const arena = GetArena(msg, table.arena_offset); @@ -521,10 +525,11 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, table, field_number, arena, msg, oneof_case + presence_index, offset, default_ptr); - if (GOOGLE_PREDICT_FALSE( - (!HandleString( - input, msg, arena, has_bits, presence_index, offset, - default_ptr, NULL)))) { + if (PROTOBUF_PREDICT_FALSE( + (!HandleString(input, msg, arena, has_bits, + presence_index, offset, + default_ptr, nullptr)))) { return false; } break; @@ -534,17 +539,17 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, #ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED case (WireFormatLite::TYPE_STRING) | kRepeatedMask: case TYPE_STRING_INLINED | kRepeatedMask: -#endif +#endif // !GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED { Arena* const arena = GetArena(msg, table.arena_offset); - const void* default_ptr = - table.aux[field_number].strings.default_ptr; + const void* default_ptr = table.aux[field_number].strings.default_ptr; - if (GOOGLE_PREDICT_FALSE(( - !HandleString( + if (PROTOBUF_PREDICT_FALSE( + (!HandleString( input, msg, arena, has_bits, presence_index, offset, - default_ptr, NULL)))) { + default_ptr, nullptr)))) { return false; } break; @@ -556,8 +561,9 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, const void* default_ptr = table.aux[field_number].strings.default_ptr; const char* field_name = table.aux[field_number].strings.field_name; - if (GOOGLE_PREDICT_FALSE( - (!HandleString( + if (PROTOBUF_PREDICT_FALSE( + (!HandleString( input, msg, arena, has_bits, presence_index, offset, default_ptr, field_name)))) { return false; @@ -571,8 +577,9 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, const void* default_ptr = table.aux[field_number].strings.default_ptr; const char* field_name = table.aux[field_number].strings.field_name; - if (GOOGLE_PREDICT_FALSE( - (!HandleString( + if (PROTOBUF_PREDICT_FALSE( + (!HandleString( input, msg, arena, has_bits, presence_index, offset, default_ptr, field_name)))) { return false; @@ -590,17 +597,18 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, table, field_number, arena, msg, oneof_case + presence_index, offset, default_ptr); - if (GOOGLE_PREDICT_FALSE( - (!HandleString( + if (PROTOBUF_PREDICT_FALSE( + (!HandleString( input, msg, arena, has_bits, presence_index, offset, default_ptr, field_name)))) { return false; } break; } -#endif +#endif // GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED case WireFormatLite::TYPE_ENUM: { - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( (!HandleEnum( table, input, msg, has_bits, presence_index, offset, tag, @@ -610,7 +618,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, break; } case WireFormatLite::TYPE_ENUM | kRepeatedMask: { - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( (!HandleEnum( table, input, msg, has_bits, presence_index, offset, tag, @@ -621,7 +629,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, } case WireFormatLite::TYPE_ENUM | kOneofMask: { uint32* oneof_case = Raw(msg, table.oneof_case_offset); - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( (!HandleEnum(table, input, msg, oneof_case, presence_index, offset, tag, @@ -644,7 +652,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, *submsg_holder = submsg; } - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( !WireFormatLite::ReadGroup(field_number, input, submsg))) { return false; } @@ -660,7 +668,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, MessageLite* submsg = MergePartialFromCodedStreamHelper::Add(field, prototype); - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( !WireFormatLite::ReadGroup(field_number, input, submsg))) { return false; } @@ -678,14 +686,14 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, const MessageLite* prototype = table.aux[field_number].messages.default_message(); if (prototype == NULL) { - prototype = - ::google::protobuf::internal::ImplicitWeakMessage::default_instance(); + prototype = ImplicitWeakMessage::default_instance(); } submsg = prototype->New(arena); *submsg_holder = submsg; } - if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadMessage(input, submsg))) { + if (PROTOBUF_PREDICT_FALSE( + !WireFormatLite::ReadMessage(input, submsg))) { return false; } @@ -698,14 +706,14 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, const MessageLite* prototype = table.aux[field_number].messages.default_message(); if (prototype == NULL) { - prototype = - ::google::protobuf::internal::ImplicitWeakMessage::default_instance(); + prototype = ImplicitWeakMessage::default_instance(); } MessageLite* submsg = MergePartialFromCodedStreamHelper::Add(field, prototype); - if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadMessage(input, submsg))) { + if (PROTOBUF_PREDICT_FALSE( + !WireFormatLite::ReadMessage(input, submsg))) { return false; } @@ -721,7 +729,8 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, offset, NULL); MessageLite* submsg = *submsg_holder; - if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadMessage(input, submsg))) { + if (PROTOBUF_PREDICT_FALSE( + !WireFormatLite::ReadMessage(input, submsg))) { return false; } @@ -734,8 +743,9 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, const void* default_ptr = table.aux[field_number].strings.default_ptr; const char* field_name = table.aux[field_number].strings.field_name; - if (GOOGLE_PREDICT_FALSE(( - !HandleString( + if (PROTOBUF_PREDICT_FALSE( + (!HandleString( input, msg, arena, has_bits, presence_index, offset, default_ptr, field_name)))) { return false; @@ -744,7 +754,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, } #endif // GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED case TYPE_MAP: { - if (GOOGLE_PREDICT_FALSE(!(*table.aux[field_number].maps.parse_map)( + if (PROTOBUF_PREDICT_FALSE(!(*table.aux[field_number].maps.parse_map)( input, Raw(msg, offset)))) { return false; } @@ -752,6 +762,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, } case 0: { // Done. + input->SetLastTag(tag); return true; } default: @@ -770,18 +781,17 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, // TODO(ckennelly): Use a computed goto on GCC/LLVM. // // Mask out kRepeatedMask bit, allowing the jump table to be smaller. - switch (static_cast( - processing_type ^ kRepeatedMask)) { -#define HANDLE_PACKED_TYPE(TYPE, CPPTYPE, CPPTYPE_METHOD) \ - case WireFormatLite::TYPE_##TYPE: { \ - google::protobuf::RepeatedField* values = \ - Raw >(msg, offset); \ - if (GOOGLE_PREDICT_FALSE( \ - (!WireFormatLite::ReadPackedPrimitive< \ - CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, values)))) { \ - return false; \ - } \ - break; \ + switch (static_cast(processing_type ^ + kRepeatedMask)) { +#define HANDLE_PACKED_TYPE(TYPE, CPPTYPE, CPPTYPE_METHOD) \ + case WireFormatLite::TYPE_##TYPE: { \ + RepeatedField* values = Raw>(msg, offset); \ + if (PROTOBUF_PREDICT_FALSE( \ + (!WireFormatLite::ReadPackedPrimitive< \ + CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, values)))) { \ + return false; \ + } \ + break; \ } HANDLE_PACKED_TYPE(INT32, int32, Int32) @@ -807,25 +817,24 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, // are valid, we implement our own parser rather than call // WireFormat::ReadPackedEnumPreserveUnknowns. uint32 length; - if (GOOGLE_PREDICT_FALSE(!input->ReadVarint32(&length))) { + if (PROTOBUF_PREDICT_FALSE(!input->ReadVarint32(&length))) { return false; } AuxillaryParseTableField::EnumValidator validator = table.aux[field_number].enums.validator; - google::protobuf::RepeatedField* values = - Raw >(msg, offset); + RepeatedField* values = Raw>(msg, offset); io::CodedInputStream::Limit limit = input->PushLimit(length); while (input->BytesUntilLimit() > 0) { int value; - if (GOOGLE_PREDICT_FALSE( - (!google::protobuf::internal::WireFormatLite::ReadPrimitive< + if (PROTOBUF_PREDICT_FALSE( + (!WireFormatLite::ReadPrimitive< int, WireFormatLite::TYPE_ENUM>(input, &value)))) { return false; } - if (validator(value)) { + if (validator == nullptr || validator(value)) { values->Add(value); } else { // TODO(ckennelly): Consider caching here. @@ -848,6 +857,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, } else { if (wire_type == WireFormatLite::WIRETYPE_END_GROUP) { // Must be the end of the message. + input->SetLastTag(tag); return true; } @@ -858,7 +868,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, } // process unknown field. - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( !UnknownFieldHandler::Skip(msg, table, input, tag))) { return false; } @@ -866,8 +876,30 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, } } +template +bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, + io::CodedInputStream* input) { + // The main beneficial cutoff values are 1 and 2 byte tags. + // Instantiate calls with the appropriate upper tag range + if (table.max_field_number <= (0x7F >> 3)) { + return MergePartialFromCodedStreamInlined( + msg, table, input); + } else if (table.max_field_number <= (0x3FFF >> 3)) { + return MergePartialFromCodedStreamInlined( + msg, table, input); + } else { + return MergePartialFromCodedStreamInlined< + UnknownFieldHandler, InternalMetadata, + std::numeric_limits::max()>(msg, table, input); + } +} + } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_GENERATED_MESSAGE_TABLE_DRIVEN_LITE_H__ diff --git a/third_party/protobuf/src/google/protobuf/generated_message_util.cc b/third_party/protobuf/src/google/protobuf/generated_message_util.cc index e0241361..363eca42 100644 --- a/third_party/protobuf/src/google/protobuf/generated_message_util.cc +++ b/third_party/protobuf/src/google/protobuf/generated_message_util.cc @@ -35,41 +35,42 @@ #include #include + +#ifndef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP // We're only using this as a standard way for getting the thread id. // We're not using any thread functionality. #include // NOLINT +#endif // #ifndef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP + #include #include #include #include #include +#include #include #include #include -#include #include #include -#include + +#include + namespace google { - namespace protobuf { namespace internal { void DestroyMessage(const void* message) { static_cast(message)->~MessageLite(); } -void DestroyString(const void* s) { static_cast(s)->~string(); } +void DestroyString(const void* s) { + static_cast(s)->~string(); +} ExplicitlyConstructed fixed_address_empty_string; -double Infinity() { - return std::numeric_limits::infinity(); -} -double NaN() { - return std::numeric_limits::quiet_NaN(); -} static bool InitProtobufDefaultsImpl() { fixed_address_empty_string.DefaultConstruct(); @@ -82,7 +83,7 @@ void InitProtobufDefaults() { (void)is_inited; } -size_t StringSpaceUsedExcludingSelfLong(const string& str) { +size_t StringSpaceUsedExcludingSelfLong(const std::string& str) { const void* start = &str; const void* end = &str + 1; if (start <= str.data() && str.data() < end) { @@ -108,8 +109,7 @@ struct PrimitiveTypeHelper; template <> struct PrimitiveTypeHelper { typedef bool Type; - static void Serialize(const void* ptr, - ::google::protobuf::io::CodedOutputStream* output) { + static void Serialize(const void* ptr, io::CodedOutputStream* output) { WireFormatLite::WriteBoolNoTag(Get(ptr), output); } static uint8* SerializeToArray(const void* ptr, uint8* buffer) { @@ -120,8 +120,7 @@ struct PrimitiveTypeHelper { template <> struct PrimitiveTypeHelper { typedef int32 Type; - static void Serialize(const void* ptr, - ::google::protobuf::io::CodedOutputStream* output) { + static void Serialize(const void* ptr, io::CodedOutputStream* output) { WireFormatLite::WriteInt32NoTag(Get(ptr), output); } static uint8* SerializeToArray(const void* ptr, uint8* buffer) { @@ -132,8 +131,7 @@ struct PrimitiveTypeHelper { template <> struct PrimitiveTypeHelper { typedef int32 Type; - static void Serialize(const void* ptr, - ::google::protobuf::io::CodedOutputStream* output) { + static void Serialize(const void* ptr, io::CodedOutputStream* output) { WireFormatLite::WriteSInt32NoTag(Get(ptr), output); } static uint8* SerializeToArray(const void* ptr, uint8* buffer) { @@ -144,8 +142,7 @@ struct PrimitiveTypeHelper { template <> struct PrimitiveTypeHelper { typedef uint32 Type; - static void Serialize(const void* ptr, - ::google::protobuf::io::CodedOutputStream* output) { + static void Serialize(const void* ptr, io::CodedOutputStream* output) { WireFormatLite::WriteUInt32NoTag(Get(ptr), output); } static uint8* SerializeToArray(const void* ptr, uint8* buffer) { @@ -155,8 +152,7 @@ struct PrimitiveTypeHelper { template <> struct PrimitiveTypeHelper { typedef int64 Type; - static void Serialize(const void* ptr, - ::google::protobuf::io::CodedOutputStream* output) { + static void Serialize(const void* ptr, io::CodedOutputStream* output) { WireFormatLite::WriteInt64NoTag(Get(ptr), output); } static uint8* SerializeToArray(const void* ptr, uint8* buffer) { @@ -167,8 +163,7 @@ struct PrimitiveTypeHelper { template <> struct PrimitiveTypeHelper { typedef int64 Type; - static void Serialize(const void* ptr, - ::google::protobuf::io::CodedOutputStream* output) { + static void Serialize(const void* ptr, io::CodedOutputStream* output) { WireFormatLite::WriteSInt64NoTag(Get(ptr), output); } static uint8* SerializeToArray(const void* ptr, uint8* buffer) { @@ -178,8 +173,7 @@ struct PrimitiveTypeHelper { template <> struct PrimitiveTypeHelper { typedef uint64 Type; - static void Serialize(const void* ptr, - ::google::protobuf::io::CodedOutputStream* output) { + static void Serialize(const void* ptr, io::CodedOutputStream* output) { WireFormatLite::WriteUInt64NoTag(Get(ptr), output); } static uint8* SerializeToArray(const void* ptr, uint8* buffer) { @@ -190,8 +184,7 @@ struct PrimitiveTypeHelper { template <> struct PrimitiveTypeHelper { typedef uint32 Type; - static void Serialize(const void* ptr, - ::google::protobuf::io::CodedOutputStream* output) { + static void Serialize(const void* ptr, io::CodedOutputStream* output) { WireFormatLite::WriteFixed32NoTag(Get(ptr), output); } static uint8* SerializeToArray(const void* ptr, uint8* buffer) { @@ -202,8 +195,7 @@ struct PrimitiveTypeHelper { template <> struct PrimitiveTypeHelper { typedef uint64 Type; - static void Serialize(const void* ptr, - ::google::protobuf::io::CodedOutputStream* output) { + static void Serialize(const void* ptr, io::CodedOutputStream* output) { WireFormatLite::WriteFixed64NoTag(Get(ptr), output); } static uint8* SerializeToArray(const void* ptr, uint8* buffer) { @@ -238,9 +230,8 @@ struct PrimitiveTypeHelper template <> struct PrimitiveTypeHelper { - typedef string Type; - static void Serialize(const void* ptr, - ::google::protobuf::io::CodedOutputStream* output) { + typedef std::string Type; + static void Serialize(const void* ptr, io::CodedOutputStream* output) { const Type& value = *static_cast(ptr); output->WriteVarint32(value.size()); output->WriteRawMaybeAliased(value.data(), value.size()); @@ -283,9 +274,8 @@ void WriteLengthTo(uint32 length, O* output) { // Specialization for coded output stream template -struct OutputHelper<::google::protobuf::io::CodedOutputStream, type> { - static void Serialize(const void* ptr, - ::google::protobuf::io::CodedOutputStream* output) { +struct OutputHelper { + static void Serialize(const void* ptr, io::CodedOutputStream* output) { PrimitiveTypeHelper::Serialize(ptr, output); } }; @@ -304,35 +294,43 @@ struct OutputHelper { }; void SerializeMessageNoTable(const MessageLite* msg, - ::google::protobuf::io::CodedOutputStream* output) { + io::CodedOutputStream* output) { msg->SerializeWithCachedSizes(output); } void SerializeMessageNoTable(const MessageLite* msg, ArrayOutput* output) { - output->ptr = msg->InternalSerializeWithCachedSizesToArray( - output->is_deterministic, output->ptr); + if (output->is_deterministic) { + io::ArrayOutputStream array_stream(output->ptr, INT_MAX); + io::CodedOutputStream o(&array_stream); + o.SetSerializationDeterministic(true); + msg->SerializeWithCachedSizes(&o); + output->ptr += o.ByteCount(); + } else { + output->ptr = msg->InternalSerializeWithCachedSizesToArray(output->ptr); + } } // Helper to branch to fast path if possible -void SerializeMessageDispatch(const ::google::protobuf::MessageLite& msg, +void SerializeMessageDispatch(const MessageLite& msg, const FieldMetadata* field_table, int num_fields, int32 cached_size, - ::google::protobuf::io::CodedOutputStream* output) { + io::CodedOutputStream* output) { const uint8* base = reinterpret_cast(&msg); - // Try the fast path - uint8* ptr = output->GetDirectBufferForNBytesAndAdvance(cached_size); - if (ptr) { - // We use virtual dispatch to enable dedicated generated code for the - // fast path. - msg.InternalSerializeWithCachedSizesToArray( - output->IsSerializationDeterministic(), ptr); - return; + if (!output->IsSerializationDeterministic()) { + // Try the fast path + uint8* ptr = output->GetDirectBufferForNBytesAndAdvance(cached_size); + if (ptr) { + // We use virtual dispatch to enable dedicated generated code for the + // fast path. + msg.InternalSerializeWithCachedSizesToArray(ptr); + return; + } } SerializeInternal(base, field_table, num_fields, output); } // Helper to branch to fast path if possible -void SerializeMessageDispatch(const ::google::protobuf::MessageLite& msg, +void SerializeMessageDispatch(const MessageLite& msg, const FieldMetadata* field_table, int num_fields, int32 cached_size, ArrayOutput* output) { const uint8* base = reinterpret_cast(&msg); @@ -430,7 +428,7 @@ struct SingularFieldHelper { template static void Serialize(const void* field, const FieldMetadata& md, O* output) { WriteTagTo(md.tag, output); - SerializeTo(&Get<::std::string>(field), output); + SerializeTo(&Get(field), output); } }; @@ -499,8 +497,8 @@ struct RepeatedFieldHelper { for (int i = 0; i < AccessorHelper::Size(array); i++) { WriteTagTo(md.tag, output); SerializeMessageTo( - static_cast(AccessorHelper::Get(array, i)), md.ptr, - output); + static_cast(AccessorHelper::Get(array, i)), + md.ptr, output); } } }; @@ -563,7 +561,7 @@ struct OneOfFieldHelper { template static void Serialize(const void* field, const FieldMetadata& md, O* output) { SingularFieldHelper::Serialize( - Get(field), md, output); + Get(field), md, output); } }; @@ -609,7 +607,7 @@ bool IsNull(const void* ptr) { template <> bool IsNull(const void* ptr) { - return static_cast(ptr)->empty(); + return static_cast(ptr)->empty(); } #define SERIALIZERS_FOR_TYPE(type) \ @@ -635,8 +633,8 @@ bool IsNull(const void* ptr) { void SerializeInternal(const uint8* base, const FieldMetadata* field_metadata_table, - int32 num_fields, - ::google::protobuf::io::CodedOutputStream* output) { + int32 num_fields, io::CodedOutputStream* output) { + SpecialSerializer func = nullptr; for (int i = 0; i < num_fields; i++) { const FieldMetadata& field_metadata = field_metadata_table[i]; const uint8* ptr = base + field_metadata.offset; @@ -663,10 +661,10 @@ void SerializeInternal(const uint8* base, // Special cases case FieldMetadata::kSpecial: - reinterpret_cast( - const_cast(field_metadata.ptr))( - base, field_metadata.offset, field_metadata.tag, - field_metadata.has_offset, output); + func = reinterpret_cast( + const_cast(field_metadata.ptr)); + func(base, field_metadata.offset, field_metadata.tag, + field_metadata.has_offset, output); break; default: // __builtin_unreachable() @@ -681,6 +679,7 @@ uint8* SerializeInternalToArray(const uint8* base, uint8* buffer) { ArrayOutput array_output = {buffer, is_deterministic}; ArrayOutput* output = &array_output; + SpecialSerializer func = nullptr; for (int i = 0; i < num_fields; i++) { const FieldMetadata& field_metadata = field_metadata_table[i]; const uint8* ptr = base + field_metadata.offset; @@ -709,10 +708,10 @@ uint8* SerializeInternalToArray(const uint8* base, io::ArrayOutputStream array_stream(array_output.ptr, INT_MAX); io::CodedOutputStream output(&array_stream); output.SetSerializationDeterministic(is_deterministic); - reinterpret_cast( - const_cast(field_metadata.ptr))( - base, field_metadata.offset, field_metadata.tag, - field_metadata.has_offset, &output); + func = reinterpret_cast( + const_cast(field_metadata.ptr)); + func(base, field_metadata.offset, field_metadata.tag, + field_metadata.has_offset, &output); array_output.ptr += output.ByteCount(); } break; default: @@ -725,15 +724,14 @@ uint8* SerializeInternalToArray(const uint8* base, #undef SERIALIZERS_FOR_TYPE void ExtensionSerializer(const uint8* ptr, uint32 offset, uint32 tag, - uint32 has_offset, - ::google::protobuf::io::CodedOutputStream* output) { + uint32 has_offset, io::CodedOutputStream* output) { reinterpret_cast(ptr + offset) ->SerializeWithCachedSizes(tag, has_offset, output); } void UnknownFieldSerializerLite(const uint8* ptr, uint32 offset, uint32 tag, uint32 has_offset, - ::google::protobuf::io::CodedOutputStream* output) { + io::CodedOutputStream* output) { output->WriteString( reinterpret_cast(ptr + offset) ->unknown_fields()); @@ -770,7 +768,8 @@ namespace { void InitSCC_DFS(SCCInfoBase* scc) { if (scc->visit_status.load(std::memory_order_relaxed) != - SCCInfoBase::kUninitialized) return; + SCCInfoBase::kUninitialized) + return; scc->visit_status.store(SCCInfoBase::kRunning, std::memory_order_relaxed); // Each base is followed by an array of pointers to deps auto deps = reinterpret_cast(scc + 1); @@ -790,8 +789,17 @@ void InitSCCImpl(SCCInfoBase* scc) { static WrappedMutex mu{GOOGLE_PROTOBUF_LINKER_INITIALIZED}; // Either the default in case no initialization is running or the id of the // thread that is currently initializing. +#ifndef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP static std::atomic runner; auto me = std::this_thread::get_id(); +#else + // This is a lightweight replacement for std::thread::id. std::thread does not + // work on Windows XP SP2 with the latest VC++ libraries, because it utilizes + // the Concurrency Runtime that is only supported on Windows XP SP3 and above. + static std::atomic_llong runner(-1); + auto me = ::GetCurrentThreadId(); +#endif // #ifndef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP + // This will only happen because the constructor will call InitSCC while // constructing the default instance. if (runner.load(std::memory_order_relaxed) == me) { @@ -805,7 +813,13 @@ void InitSCCImpl(SCCInfoBase* scc) { mu.Lock(); runner.store(me, std::memory_order_relaxed); InitSCC_DFS(scc); + +#ifndef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP runner.store(std::thread::id{}, std::memory_order_relaxed); +#else + runner.store(-1, std::memory_order_relaxed); +#endif // #ifndef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP + mu.Unlock(); } diff --git a/third_party/protobuf/src/google/protobuf/generated_message_util.h b/third_party/protobuf/src/google/protobuf/generated_message_util.h index 04f68a6e..bf0e5b9b 100644 --- a/third_party/protobuf/src/google/protobuf/generated_message_util.h +++ b/third_party/protobuf/src/google/protobuf/generated_message_util.h @@ -44,86 +44,60 @@ #include #include -#include #include -#include // Add direct dep on port for pb.cc #include #include -#include #include +#include // Add direct dep on port for pb.cc +#include #include +#include +#include + +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif namespace google { - namespace protobuf { class Arena; -namespace io { class CodedInputStream; } +namespace io { +class CodedInputStream; +} namespace internal { - -// Annotation for the compiler to emit a deprecation message if a field marked -// with option 'deprecated=true' is used in the code, or for other things in -// generated code which are deprecated. -// -// For internal use in the pb.cc files, deprecation warnings are suppressed -// there. -#undef DEPRECATED_PROTOBUF_FIELD -#define PROTOBUF_DEPRECATED - -#define GOOGLE_PROTOBUF_DEPRECATED_ATTR +template +inline To DownCast(From* f) { + return PROTOBUF_NAMESPACE_ID::internal::down_cast(f); +} +template +inline To DownCast(From& f) { + return PROTOBUF_NAMESPACE_ID::internal::down_cast(f); +} -// Returns the offset of the given field within the given aggregate type. -// This is equivalent to the ANSI C offsetof() macro. However, according -// to the C++ standard, offsetof() only works on POD types, and GCC -// enforces this requirement with a warning. In practice, this rule is -// unnecessarily strict; there is probably no compiler or platform on -// which the offsets of the direct fields of a class are non-constant. -// Fields inherited from superclasses *can* have non-constant offsets, -// but that's not what this macro will be used for. -#if defined(__clang__) -// For Clang we use __builtin_offsetof() and suppress the warning, -// to avoid Control Flow Integrity and UBSan vptr sanitizers from -// crashing while trying to validate the invalid reinterpet_casts. -#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TYPE, FIELD) \ - _Pragma("clang diagnostic push") \ - _Pragma("clang diagnostic ignored \"-Winvalid-offsetof\"") \ - __builtin_offsetof(TYPE, FIELD) \ - _Pragma("clang diagnostic pop") -#else -// Note that we calculate relative to the pointer value 16 here since if we -// just use zero, GCC complains about dereferencing a NULL pointer. We -// choose 16 rather than some other number just in case the compiler would -// be confused by an unaligned pointer. -#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TYPE, FIELD) \ - static_cast< ::google::protobuf::uint32>( \ - reinterpret_cast( \ - &reinterpret_cast(16)->FIELD) - \ - reinterpret_cast(16)) -#endif - -// Constants for special floating point values. -LIBPROTOBUF_EXPORT double Infinity(); -LIBPROTOBUF_EXPORT double NaN(); - -LIBPROTOBUF_EXPORT void InitProtobufDefaults(); +PROTOBUF_EXPORT void InitProtobufDefaults(); // This used by proto1 -inline const std::string& GetEmptyString() { +PROTOBUF_EXPORT inline const std::string& GetEmptyString() { InitProtobufDefaults(); return GetEmptyStringAlreadyInited(); } + // True if IsInitialized() is true for all elements of t. Type is expected // to be a RepeatedPtrField. It's useful to have this // helper here to keep the protobuf compiler from ever having to emit loops in // IsInitialized() methods. We want the C++ compiler to inline this or not // as it sees fit. -template bool AllAreInitialized(const Type& t) { - for (int i = t.size(); --i >= 0; ) { +template +bool AllAreInitialized(const Type& t) { + for (int i = t.size(); --i >= 0;) { if (!t.Get(i).IsInitialized()) return false; } return true; @@ -133,10 +107,10 @@ template bool AllAreInitialized(const Type& t) { // This version operates on MessageLite to avoid introducing a dependency on the // concrete message type. template -bool AllAreInitializedWeak(const ::google::protobuf::RepeatedPtrField& t) { +bool AllAreInitializedWeak(const RepeatedPtrField& t) { for (int i = t.size(); --i >= 0;) { - if (!reinterpret_cast(t) - .Get<::google::protobuf::internal::ImplicitWeakTypeHandler >(i) + if (!reinterpret_cast(t) + .Get >(i) .IsInitialized()) { return false; } @@ -144,40 +118,6 @@ bool AllAreInitializedWeak(const ::google::protobuf::RepeatedPtrField& t) { return true; } -struct LIBPROTOBUF_EXPORT FieldMetadata { - uint32 offset; // offset of this field in the struct - uint32 tag; // field * 8 + wire_type - // byte offset * 8 + bit_offset; - // if the high bit is set then this is the byte offset of the oneof_case - // for this field. - uint32 has_offset; - uint32 type; // the type of this field. - const void* ptr; // auxiliary data - - // From the serializer point of view each fundamental type can occur in - // 4 different ways. For simplicity we treat all combinations as a cartesion - // product although not all combinations are allowed. - enum FieldTypeClass { - kPresence, - kNoPresence, - kRepeated, - kPacked, - kOneOf, - kNumTypeClasses // must be last enum - }; - // C++ protobuf has 20 fundamental types, were we added Cord and StringPiece - // and also distinquish the same types if they have different wire format. - enum { - kCordType = 19, - kStringPieceType = 20, - kInlinedType = 21, - kNumTypes = 21, - kSpecial = kNumTypes * kNumTypeClasses, - }; - - static int CalculateType(int fundamental_type, FieldTypeClass type_class); -}; - inline bool IsPresent(const void* base, uint32 hasbit) { const uint32* has_bits_array = static_cast(base); return (has_bits_array[hasbit / 32] & (1u << (hasbit & 31))) != 0; @@ -191,116 +131,20 @@ inline bool IsOneofPresent(const void* base, uint32 offset, uint32 tag) { typedef void (*SpecialSerializer)(const uint8* base, uint32 offset, uint32 tag, uint32 has_offset, - ::google::protobuf::io::CodedOutputStream* output); + io::CodedOutputStream* output); -LIBPROTOBUF_EXPORT void ExtensionSerializer(const uint8* base, uint32 offset, uint32 tag, - uint32 has_offset, - ::google::protobuf::io::CodedOutputStream* output); -LIBPROTOBUF_EXPORT void UnknownFieldSerializerLite(const uint8* base, uint32 offset, uint32 tag, - uint32 has_offset, - ::google::protobuf::io::CodedOutputStream* output); +PROTOBUF_EXPORT void ExtensionSerializer(const uint8* base, uint32 offset, + uint32 tag, uint32 has_offset, + io::CodedOutputStream* output); +PROTOBUF_EXPORT void UnknownFieldSerializerLite(const uint8* base, + uint32 offset, uint32 tag, + uint32 has_offset, + io::CodedOutputStream* output); -struct SerializationTable { - int num_fields; - const FieldMetadata* field_table; -}; - -LIBPROTOBUF_EXPORT void SerializeInternal(const uint8* base, const FieldMetadata* table, - int num_fields, ::google::protobuf::io::CodedOutputStream* output); - -inline void TableSerialize(const ::google::protobuf::MessageLite& msg, - const SerializationTable* table, - ::google::protobuf::io::CodedOutputStream* output) { - const FieldMetadata* field_table = table->field_table; - int num_fields = table->num_fields - 1; - const uint8* base = reinterpret_cast(&msg); - // TODO(gerbens) This skips the first test if we could use the fast - // array serialization path, we should make this - // int cached_size = - // *reinterpret_cast(base + field_table->offset); - // SerializeWithCachedSize(msg, field_table + 1, num_fields, cached_size, ...) - // But we keep conformance with the old way for now. - SerializeInternal(base, field_table + 1, num_fields, output); -} - -uint8* SerializeInternalToArray(const uint8* base, const FieldMetadata* table, - int num_fields, bool is_deterministic, - uint8* buffer); - -inline uint8* TableSerializeToArray(const ::google::protobuf::MessageLite& msg, - const SerializationTable* table, - bool is_deterministic, uint8* buffer) { - const uint8* base = reinterpret_cast(&msg); - const FieldMetadata* field_table = table->field_table + 1; - int num_fields = table->num_fields - 1; - return SerializeInternalToArray(base, field_table, num_fields, - is_deterministic, buffer); -} - -template -struct CompareHelper { - bool operator()(const T& a, const T& b) { return a < b; } -}; - -template <> -struct CompareHelper { - bool operator()(const ArenaStringPtr& a, const ArenaStringPtr& b) { - return a.Get() < b.Get(); - } -}; - -struct CompareMapKey { - template - bool operator()(const MapEntryHelper& a, const MapEntryHelper& b) { - return Compare(a.key_, b.key_); - } - template - bool Compare(const T& a, const T& b) { - return CompareHelper()(a, b); - } -}; - -template -void MapFieldSerializer(const uint8* base, uint32 offset, uint32 tag, - uint32 has_offset, - ::google::protobuf::io::CodedOutputStream* output) { - typedef MapEntryHelper Entry; - typedef typename MapFieldType::MapType::const_iterator Iter; - - const MapFieldType& map_field = - *reinterpret_cast(base + offset); - const SerializationTable* t = - table + - has_offset; // has_offset is overloaded for maps to mean table offset - if (!output->IsSerializationDeterministic()) { - for (Iter it = map_field.GetMap().begin(); it != map_field.GetMap().end(); - ++it) { - Entry map_entry(*it); - output->WriteVarint32(tag); - output->WriteVarint32(map_entry._cached_size_); - SerializeInternal(reinterpret_cast(&map_entry), - t->field_table, t->num_fields, output); - } - } else { - std::vector v; - for (Iter it = map_field.GetMap().begin(); it != map_field.GetMap().end(); - ++it) { - v.push_back(Entry(*it)); - } - std::sort(v.begin(), v.end(), CompareMapKey()); - for (int i = 0; i < v.size(); i++) { - output->WriteVarint32(tag); - output->WriteVarint32(v[i]._cached_size_); - SerializeInternal(reinterpret_cast(&v[i]), t->field_table, - t->num_fields, output); - } - } -} - -LIBPROTOBUF_EXPORT MessageLite* DuplicateIfNonNullInternal(MessageLite* message); -LIBPROTOBUF_EXPORT MessageLite* GetOwnedMessageInternal(Arena* message_arena, - MessageLite* submessage, - Arena* submessage_arena); +PROTOBUF_EXPORT MessageLite* DuplicateIfNonNullInternal(MessageLite* message); +PROTOBUF_EXPORT MessageLite* GetOwnedMessageInternal(Arena* message_arena, + MessageLite* submessage, + Arena* submessage_arena); template T* DuplicateIfNonNull(T* message) { @@ -322,17 +166,18 @@ T* GetOwnedMessage(Arena* message_arena, T* submessage, // Hide atomic from the public header and allow easy change to regular int // on platforms where the atomic might have a perf impact. -class LIBPROTOBUF_EXPORT CachedSize { +class PROTOBUF_EXPORT CachedSize { public: int Get() const { return size_.load(std::memory_order_relaxed); } void Set(int size) { size_.store(size, std::memory_order_relaxed); } + private: std::atomic size_{0}; }; // SCCInfo represents information of a strongly connected component of // mutual dependent messages. -struct LIBPROTOBUF_EXPORT SCCInfoBase { +struct PROTOBUF_EXPORT SCCInfoBase { // We use 0 for the Initialized state, because test eax,eax, jnz is smaller // and is subject to macro fusion. enum { @@ -340,15 +185,15 @@ struct LIBPROTOBUF_EXPORT SCCInfoBase { kRunning = 1, kUninitialized = -1, // initial state }; -#ifndef _MSC_VER - std::atomic visit_status; -#else +#if defined(_MSC_VER) && !defined(__clang__) // MSVC doesnt make std::atomic constant initialized. This union trick // makes it so. union { int visit_status_to_make_linker_init; std::atomic visit_status; }; +#else + std::atomic visit_status; #endif int num_deps; void (*init_func)(); @@ -366,26 +211,29 @@ struct SCCInfo { SCCInfoBase* deps[N ? N : 1]; }; -LIBPROTOBUF_EXPORT void InitSCCImpl(SCCInfoBase* scc); +PROTOBUF_EXPORT void InitSCCImpl(SCCInfoBase* scc); inline void InitSCC(SCCInfoBase* scc) { auto status = scc->visit_status.load(std::memory_order_acquire); - if (GOOGLE_PREDICT_FALSE(status != SCCInfoBase::kInitialized)) InitSCCImpl(scc); + if (PROTOBUF_PREDICT_FALSE(status != SCCInfoBase::kInitialized)) + InitSCCImpl(scc); } -LIBPROTOBUF_EXPORT void DestroyMessage(const void* message); -LIBPROTOBUF_EXPORT void DestroyString(const void* s); +PROTOBUF_EXPORT void DestroyMessage(const void* message); +PROTOBUF_EXPORT void DestroyString(const void* s); // Destroy (not delete) the message inline void OnShutdownDestroyMessage(const void* ptr) { OnShutdownRun(DestroyMessage, ptr); } -// Destroy the string (call string destructor) +// Destroy the string (call std::string destructor) inline void OnShutdownDestroyString(const std::string* ptr) { OnShutdownRun(DestroyString, ptr); } } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_GENERATED_MESSAGE_UTIL_H__ diff --git a/third_party/protobuf/src/google/protobuf/has_bits.h b/third_party/protobuf/src/google/protobuf/has_bits.h index e3a0149a..11afde71 100644 --- a/third_party/protobuf/src/google/protobuf/has_bits.h +++ b/third_party/protobuf/src/google/protobuf/has_bits.h @@ -32,27 +32,32 @@ #define GOOGLE_PROTOBUF_HAS_BITS_H__ #include -#include +#include + +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif namespace google { namespace protobuf { namespace internal { -template +template class HasBits { public: - HasBits() GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { Clear(); } + HasBits() PROTOBUF_ALWAYS_INLINE { Clear(); } - void Clear() GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + void Clear() PROTOBUF_ALWAYS_INLINE { memset(has_bits_, 0, sizeof(has_bits_)); } - ::google::protobuf::uint32& operator[](int index) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + uint32& operator[](int index) PROTOBUF_ALWAYS_INLINE { return has_bits_[index]; } - const ::google::protobuf::uint32& operator[](int index) const - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + const uint32& operator[](int index) const PROTOBUF_ALWAYS_INLINE { return has_bits_[index]; } @@ -64,10 +69,14 @@ class HasBits { return !(*this == rhs); } + void Or(const HasBits& rhs) { + for (int i = 0; i < doublewords; i++) has_bits_[i] |= rhs[i]; + } + bool empty() const; private: - ::google::protobuf::uint32 has_bits_[doublewords]; + uint32 has_bits_[doublewords]; }; template <> @@ -100,6 +109,8 @@ inline bool HasBits::empty() const { } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_HAS_BITS_H__ diff --git a/third_party/protobuf/src/google/protobuf/implicit_weak_message.cc b/third_party/protobuf/src/google/protobuf/implicit_weak_message.cc index 7a1d4446..35e64f07 100644 --- a/third_party/protobuf/src/google/protobuf/implicit_weak_message.cc +++ b/third_party/protobuf/src/google/protobuf/implicit_weak_message.cc @@ -30,31 +30,42 @@ #include -#include +#include #include +#include #include +#include + namespace google { namespace protobuf { namespace internal { -bool ImplicitWeakMessage::MergePartialFromCodedStream(io::CodedInputStream* input) { +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* ImplicitWeakMessage::_InternalParse(const char* ptr, + ParseContext* ctx) { + return ctx->AppendString(ptr, &data_); +} +#else +bool ImplicitWeakMessage::MergePartialFromCodedStream( + io::CodedInputStream* input) { io::StringOutputStream string_stream(&data_); io::CodedOutputStream coded_stream(&string_stream, false); return WireFormatLite::SkipMessage(input, &coded_stream); } +#endif -::google::protobuf::internal::ExplicitlyConstructed +ExplicitlyConstructed implicit_weak_message_default_instance; -GOOGLE_PROTOBUF_DECLARE_ONCE(implicit_weak_message_once_init_); +internal::once_flag implicit_weak_message_once_init_; void InitImplicitWeakMessageDefaultInstance() { implicit_weak_message_default_instance.DefaultConstruct(); } const ImplicitWeakMessage* ImplicitWeakMessage::default_instance() { - ::google::protobuf::GoogleOnceInit(&implicit_weak_message_once_init_, - &InitImplicitWeakMessageDefaultInstance); + internal::call_once(implicit_weak_message_once_init_, + InitImplicitWeakMessageDefaultInstance); return &implicit_weak_message_default_instance.get(); } diff --git a/third_party/protobuf/src/google/protobuf/implicit_weak_message.h b/third_party/protobuf/src/google/protobuf/implicit_weak_message.h index 3279bd17..cab5df97 100644 --- a/third_party/protobuf/src/google/protobuf/implicit_weak_message.h +++ b/third_party/protobuf/src/google/protobuf/implicit_weak_message.h @@ -31,10 +31,17 @@ #ifndef GOOGLE_PROTOBUF_IMPLICIT_WEAK_MESSAGE_H__ #define GOOGLE_PROTOBUF_IMPLICIT_WEAK_MESSAGE_H__ +#include #include #include #include +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + // This file is logically internal-only and should only be used by protobuf // generated code. @@ -45,45 +52,49 @@ namespace internal { // An implementation of MessageLite that treats all data as unknown. This type // acts as a placeholder for an implicit weak field in the case where the true // message type does not get linked into the binary. -class LIBPROTOBUF_EXPORT ImplicitWeakMessage : public MessageLite { +class PROTOBUF_EXPORT ImplicitWeakMessage : public MessageLite { public: ImplicitWeakMessage() : arena_(NULL) {} explicit ImplicitWeakMessage(Arena* arena) : arena_(arena) {} static const ImplicitWeakMessage* default_instance(); - string GetTypeName() const { return ""; } + std::string GetTypeName() const override { return ""; } - MessageLite* New() const { return new ImplicitWeakMessage; } - MessageLite* New(Arena* arena) const { + MessageLite* New() const override { return new ImplicitWeakMessage; } + MessageLite* New(Arena* arena) const override { return Arena::CreateMessage(arena); } - Arena* GetArena() const { return arena_; } + Arena* GetArena() const override { return arena_; } - void Clear() { data_.clear(); } + void Clear() override { data_.clear(); } - bool IsInitialized() const { return true; } + bool IsInitialized() const override { return true; } - void CheckTypeAndMergeFrom(const MessageLite& other) { + void CheckTypeAndMergeFrom(const MessageLite& other) override { data_.append(static_cast(other).data_); } - bool MergePartialFromCodedStream(io::CodedInputStream* input); +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ParseContext* ctx) final; +#else + bool MergePartialFromCodedStream(io::CodedInputStream* input) override; +#endif - size_t ByteSizeLong() const { return data_.size(); } + size_t ByteSizeLong() const override { return data_.size(); } - void SerializeWithCachedSizes(io::CodedOutputStream* output) const { + void SerializeWithCachedSizes(io::CodedOutputStream* output) const override { output->WriteString(data_); } - int GetCachedSize() const { return static_cast(data_.size()); } + int GetCachedSize() const override { return static_cast(data_.size()); } typedef void InternalArenaConstructable_; private: Arena* const arena_; - string data_; + std::string data_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImplicitWeakMessage); }; @@ -92,7 +103,7 @@ template class ImplicitWeakTypeHandler { public: typedef ImplicitWeakType Type; - typedef ::google::protobuf::MessageLite WeakType; + typedef MessageLite WeakType; static const bool Moveable = false; // With implicit weak fields, we need separate NewFromPrototype and @@ -100,27 +111,24 @@ class ImplicitWeakTypeHandler { // strong dependency on the message type, and it just delegates to the // GenericTypeHandler. The latter avoids creating a strong dependency, by // simply calling MessageLite::New. - static inline ::google::protobuf::MessageLite* NewFromPrototype( - const ::google::protobuf::MessageLite* prototype, ::google::protobuf::Arena* arena = NULL) { + static inline MessageLite* NewFromPrototype(const MessageLite* prototype, + Arena* arena = NULL) { return prototype->New(arena); } - static inline void Delete(::google::protobuf::MessageLite* value, Arena* arena) { + static inline void Delete(MessageLite* value, Arena* arena) { if (arena == NULL) { delete value; } } - static inline ::google::protobuf::Arena* GetArena(::google::protobuf::MessageLite* value) { + static inline Arena* GetArena(MessageLite* value) { return value->GetArena(); } - static inline void* GetMaybeArenaPointer(::google::protobuf::MessageLite* value) { + static inline void* GetMaybeArenaPointer(MessageLite* value) { return value->GetArena(); } - static inline void Clear(::google::protobuf::MessageLite* value) { - value->Clear(); - } - static void Merge(const ::google::protobuf::MessageLite& from, - ::google::protobuf::MessageLite* to) { + static inline void Clear(MessageLite* value) { value->Clear(); } + static void Merge(const MessageLite& from, MessageLite* to) { to->CheckTypeAndMergeFrom(from); } static inline size_t SpaceUsedLong(const Type& value) { @@ -130,6 +138,8 @@ class ImplicitWeakTypeHandler { } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_IMPLICIT_WEAK_MESSAGE_H__ diff --git a/third_party/protobuf/src/google/protobuf/inlined_string_field.h b/third_party/protobuf/src/google/protobuf/inlined_string_field.h index 95d4687b..781059da 100644 --- a/third_party/protobuf/src/google/protobuf/inlined_string_field.h +++ b/third_party/protobuf/src/google/protobuf/inlined_string_field.h @@ -32,10 +32,17 @@ #define GOOGLE_PROTOBUF_INLINED_STRING_FIELD_H__ #include +#include -#include +#include #include +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + namespace google { namespace protobuf { @@ -43,162 +50,143 @@ class Arena; namespace internal { -// InlinedStringField wraps a ::std::string instance and exposes an API similar to -// ArenaStringPtr's wrapping of a ::std::string* instance. As ::std::string is never -// allocated on the Arena, we expose only the *NoArena methods of +// InlinedStringField wraps a std::string instance and exposes an API similar to +// ArenaStringPtr's wrapping of a std::string* instance. As std::string is +// never allocated on the Arena, we expose only the *NoArena methods of // ArenaStringPtr. // // default_value parameters are taken for consistency with ArenaStringPtr, but // are not used for most methods. With inlining, these should be removed from // the generated binary. -class LIBPROTOBUF_EXPORT InlinedStringField { +class PROTOBUF_EXPORT InlinedStringField { public: - InlinedStringField() - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; - explicit InlinedStringField(const ::std::string& default_value); + InlinedStringField() PROTOBUF_ALWAYS_INLINE; + explicit InlinedStringField(const std::string& default_value); - void AssignWithDefault(const ::std::string* default_value, - const InlinedStringField& from) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + void AssignWithDefault(const std::string* default_value, + const InlinedStringField& from) PROTOBUF_ALWAYS_INLINE; - void ClearToEmpty(const ::std::string* default_value, Arena* arena) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + void ClearToEmpty(const std::string* default_value, + Arena* /*arena*/) PROTOBUF_ALWAYS_INLINE { ClearToEmptyNoArena(default_value); } - void ClearNonDefaultToEmpty() GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + void ClearNonDefaultToEmpty() PROTOBUF_ALWAYS_INLINE { ClearNonDefaultToEmptyNoArena(); } - void ClearToEmptyNoArena(const ::std::string* default_value) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + void ClearToEmptyNoArena(const std::string* /*default_value*/) + PROTOBUF_ALWAYS_INLINE { ClearNonDefaultToEmptyNoArena(); } - void ClearNonDefaultToEmptyNoArena() - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + void ClearNonDefaultToEmptyNoArena() PROTOBUF_ALWAYS_INLINE; - void ClearToDefault(const ::std::string* default_value, Arena* arena) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + void ClearToDefault(const std::string* default_value, + Arena* /*arena*/) PROTOBUF_ALWAYS_INLINE { ClearToDefaultNoArena(default_value); } - void ClearToDefaultNoArena(const ::std::string* default_value) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + void ClearToDefaultNoArena(const std::string* default_value) + PROTOBUF_ALWAYS_INLINE; - void Destroy(const ::std::string* default_value, Arena* arena) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + void Destroy(const std::string* default_value, + Arena* /*arena*/) PROTOBUF_ALWAYS_INLINE { DestroyNoArena(default_value); } - void DestroyNoArena(const ::std::string* default_value) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + void DestroyNoArena(const std::string* default_value) PROTOBUF_ALWAYS_INLINE; - const ::std::string& Get() const GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { - return GetNoArena(); - } - const ::std::string& GetNoArena() const GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + const std::string& Get() const PROTOBUF_ALWAYS_INLINE { return GetNoArena(); } + const std::string& GetNoArena() const PROTOBUF_ALWAYS_INLINE; - ::std::string* Mutable(const ::std::string* default_value, Arena* arena) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + std::string* Mutable(const std::string* default_value, + Arena* /*arena*/) PROTOBUF_ALWAYS_INLINE { return MutableNoArena(default_value); } - ::std::string* MutableNoArena(const ::std::string* default_value) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + std::string* MutableNoArena(const std::string* default_value) + PROTOBUF_ALWAYS_INLINE; - ::std::string* Release(const ::std::string* default_value, Arena* arena) { + std::string* Release(const std::string* default_value, Arena* /*arena*/) { return ReleaseNoArena(default_value); } - ::std::string* ReleaseNonDefault(const ::std::string* default_value, Arena* arena) { + std::string* ReleaseNonDefault(const std::string* default_value, + Arena* /*arena*/) { return ReleaseNonDefaultNoArena(default_value); } - ::std::string* ReleaseNoArena(const ::std::string* default_value) { + std::string* ReleaseNoArena(const std::string* default_value) { return ReleaseNonDefaultNoArena(default_value); } - ::std::string* ReleaseNonDefaultNoArena(const ::std::string* default_value); + std::string* ReleaseNonDefaultNoArena(const std::string* default_value); - void Set(const ::std::string* default_value, - StringPiece value, - Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + void Set(const std::string* default_value, StringPiece value, + Arena* /*arena*/) PROTOBUF_ALWAYS_INLINE { SetNoArena(default_value, value); } - void SetLite(const ::std::string* default_value, - StringPiece value, - Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + void SetLite(const std::string* default_value, StringPiece value, + Arena* /*arena*/) PROTOBUF_ALWAYS_INLINE { SetNoArena(default_value, value); } - void SetNoArena(const ::std::string* default_value, - StringPiece value) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + void SetNoArena(const std::string* default_value, + StringPiece value) PROTOBUF_ALWAYS_INLINE; - void Set(const ::std::string* default_value, - const ::std::string& value, - Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + void Set(const std::string* default_value, const std::string& value, + Arena* /*arena*/) PROTOBUF_ALWAYS_INLINE { SetNoArena(default_value, value); } - void SetLite(const ::std::string* default_value, - const ::std::string& value, - Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + void SetLite(const std::string* default_value, const std::string& value, + Arena* /*arena*/) PROTOBUF_ALWAYS_INLINE { SetNoArena(default_value, value); } - void SetNoArena(const ::std::string* default_value, - const ::std::string& value) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + void SetNoArena(const std::string* default_value, + const std::string& value) PROTOBUF_ALWAYS_INLINE; -#if LANG_CXX11 - void SetNoArena(const ::std::string* default_value, - ::std::string&& value) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; -#endif - void SetAllocated(const ::std::string* default_value, - ::std::string* value, - Arena* arena) { + void SetNoArena(const std::string* default_value, + std::string&& value) PROTOBUF_ALWAYS_INLINE; + void SetAllocated(const std::string* default_value, std::string* value, + Arena* /*arena*/) { SetAllocatedNoArena(default_value, value); } - void SetAllocatedNoArena(const ::std::string* default_value, - ::std::string* value); - void Swap(InlinedStringField* from) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; - ::std::string* UnsafeMutablePointer(); - void UnsafeSetDefault(const ::std::string* default_value); - ::std::string* UnsafeArenaRelease(const ::std::string* default_value, Arena* arena); - void UnsafeArenaSetAllocated( - const ::std::string* default_value, ::std::string* value, Arena* arena); + void SetAllocatedNoArena(const std::string* default_value, + std::string* value); + void Swap(InlinedStringField* from) PROTOBUF_ALWAYS_INLINE; + std::string* UnsafeMutablePointer(); + void UnsafeSetDefault(const std::string* default_value); + std::string* UnsafeArenaRelease(const std::string* default_value, + Arena* arena); + void UnsafeArenaSetAllocated(const std::string* default_value, + std::string* value, Arena* arena); + + bool IsDefault(const std::string* /*default_value*/) { return false; } - bool IsDefault(const ::std::string* default_value) { - return false; - } private: - ::std::string value_; + std::string value_; }; inline InlinedStringField::InlinedStringField() {} -inline InlinedStringField::InlinedStringField(const ::std::string& default_value) : - value_(default_value) {} +inline InlinedStringField::InlinedStringField(const std::string& default_value) + : value_(default_value) {} inline void InlinedStringField::AssignWithDefault( - const ::std::string* default_value, const InlinedStringField& from) { + const std::string* /*default_value*/, const InlinedStringField& from) { value_ = from.value_; } -inline const ::std::string& InlinedStringField::GetNoArena() const { +inline const std::string& InlinedStringField::GetNoArena() const { return value_; } -inline ::std::string* InlinedStringField::MutableNoArena(const ::std::string*) { +inline std::string* InlinedStringField::MutableNoArena(const std::string*) { return &value_; } inline void InlinedStringField::SetAllocatedNoArena( - const ::std::string* default_value, ::std::string* value) { + const std::string* default_value, std::string* value) { if (value == NULL) { value_.assign(*default_value); } else { -#if LANG_CXX11 value_.assign(std::move(*value)); -#else - value_.swap(*value); -#endif delete value; } } -inline void InlinedStringField::DestroyNoArena(const ::std::string*) { +inline void InlinedStringField::DestroyNoArena(const std::string*) { // This is invoked from the generated message's ArenaDtor, which is used to // clean up objects not allocated on the Arena. this->~InlinedStringField(); @@ -209,54 +197,52 @@ inline void InlinedStringField::ClearNonDefaultToEmptyNoArena() { } inline void InlinedStringField::ClearToDefaultNoArena( - const ::std::string* default_value) { + const std::string* default_value) { value_.assign(*default_value); } -inline ::std::string* InlinedStringField::ReleaseNonDefaultNoArena( - const ::std::string* default_value) { - ::std::string* released = new ::std::string(*default_value); +inline std::string* InlinedStringField::ReleaseNonDefaultNoArena( + const std::string* default_value) { + std::string* released = new std::string(*default_value); value_.swap(*released); return released; } -inline void InlinedStringField::SetNoArena( - const ::std::string* default_value, StringPiece value) { +inline void InlinedStringField::SetNoArena(const std::string* /*default_value*/, + StringPiece value) { value_.assign(value.data(), value.length()); } -inline void InlinedStringField::SetNoArena( - const ::std::string* default_value, const ::std::string& value) { +inline void InlinedStringField::SetNoArena(const std::string* /*default_value*/, + const std::string& value) { value_.assign(value); } -#if LANG_CXX11 -inline void InlinedStringField::SetNoArena( - const ::std::string* default_value, ::std::string&& value) { +inline void InlinedStringField::SetNoArena(const std::string* /*default_value*/, + std::string&& value) { value_.assign(std::move(value)); } -#endif inline void InlinedStringField::Swap(InlinedStringField* from) { value_.swap(from->value_); } -inline ::std::string* InlinedStringField::UnsafeMutablePointer() { +inline std::string* InlinedStringField::UnsafeMutablePointer() { return &value_; } inline void InlinedStringField::UnsafeSetDefault( - const ::std::string* default_value) { + const std::string* default_value) { value_.assign(*default_value); } -inline ::std::string* InlinedStringField::UnsafeArenaRelease( - const ::std::string* default_value, Arena* arena) { +inline std::string* InlinedStringField::UnsafeArenaRelease( + const std::string* default_value, Arena* /*arena*/) { return ReleaseNoArena(default_value); } inline void InlinedStringField::UnsafeArenaSetAllocated( - const ::std::string* default_value, ::std::string* value, Arena* arena) { + const std::string* default_value, std::string* value, Arena* /*arena*/) { if (value == NULL) { value_.assign(*default_value); } else { @@ -266,6 +252,8 @@ inline void InlinedStringField::UnsafeArenaSetAllocated( } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_INLINED_STRING_FIELD_H__ diff --git a/third_party/protobuf/src/google/protobuf/io/coded_stream.cc b/third_party/protobuf/src/google/protobuf/io/coded_stream.cc index 0851ff0c..6aaaa0b4 100644 --- a/third_party/protobuf/src/google/protobuf/io/coded_stream.cc +++ b/third_party/protobuf/src/google/protobuf/io/coded_stream.cc @@ -38,17 +38,19 @@ // will not cross the end of the buffer, since we can avoid a lot // of branching in this case. -#include +#include #include #include -#include -#include -#include #include #include +#include +#include +#include #include +#include + namespace google { namespace protobuf { namespace io { @@ -59,8 +61,8 @@ static const int kMaxVarintBytes = 10; static const int kMaxVarint32Bytes = 5; -inline bool NextNonEmpty(ZeroCopyInputStream* input, - const void** data, int* size) { +inline bool NextNonEmpty(ZeroCopyInputStream* input, const void** data, + int* size) { bool success; do { success = input->Next(data, size); @@ -121,9 +123,9 @@ CodedInputStream::Limit CodedInputStream::PushLimit(int byte_limit) { // security: byte_limit is possibly evil, so check for negative values // and overflow. Also check that the new requested limit is before the // previous limit; otherwise we continue to enforce the previous limit. - if (GOOGLE_PREDICT_TRUE(byte_limit >= 0 && - byte_limit <= INT_MAX - current_position && - byte_limit < current_limit_ - current_position)) { + if (PROTOBUF_PREDICT_TRUE(byte_limit >= 0 && + byte_limit <= INT_MAX - current_position && + byte_limit < current_limit_ - current_position)) { current_limit_ = current_position + byte_limit; RecomputeBufferLimits(); } @@ -188,10 +190,11 @@ int CodedInputStream::BytesUntilTotalBytesLimit() const { void CodedInputStream::PrintTotalBytesLimitError() { GOOGLE_LOG(ERROR) << "A protocol message was rejected because it was too " - "big (more than " << total_bytes_limit_ + "big (more than " + << total_bytes_limit_ << " bytes). To increase the limit (or to disable these " "warnings), see CodedInputStream::SetTotalBytesLimit() " - "in google/protobuf/io/coded_stream.h."; + "in net/proto2/io/public/coded_stream.h."; } bool CodedInputStream::SkipFallback(int count, int original_buffer_size) { @@ -237,12 +240,12 @@ bool CodedInputStream::ReadRaw(void* buffer, int size) { return InternalReadRawInline(buffer, size); } -bool CodedInputStream::ReadString(string* buffer, int size) { +bool CodedInputStream::ReadString(std::string* buffer, int size) { if (size < 0) return false; // security: size is often user-supplied return InternalReadStringInline(buffer, size); } -bool CodedInputStream::ReadStringFallback(string* buffer, int size) { +bool CodedInputStream::ReadStringFallback(std::string* buffer, int size) { if (!buffer->empty()) { buffer->clear(); } @@ -312,14 +315,28 @@ bool CodedInputStream::ReadLittleEndian64Fallback(uint64* value) { namespace { +// Decodes varint64 with known size, N, and returns next pointer. Knowing N at +// compile time, compiler can generate optimal code. For example, instead of +// subtracting 0x80 at each iteration, it subtracts properly shifted mask once. +template +const uint8* DecodeVarint64KnownSize(const uint8* buffer, uint64* value) { + GOOGLE_DCHECK_GT(N, 0); + uint64 result = static_cast(buffer[N - 1]) << (7 * (N - 1)); + for (int i = 0, offset = 0; i < N - 1; i++, offset += 7) { + result += static_cast(buffer[i] - 0x80) << offset; + } + *value = result; + return buffer + N; +} + // Read a varint from the given buffer, write it to *value, and return a pair. // The first part of the pair is true iff the read was successful. The second // part is buffer + (number of bytes read). This function is always inlined, // so returning a pair is costless. -GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE -::std::pair ReadVarint32FromArray( - uint32 first_byte, const uint8* buffer, - uint32* value); +PROTOBUF_ALWAYS_INLINE +::std::pair ReadVarint32FromArray(uint32 first_byte, + const uint8* buffer, + uint32* value); inline ::std::pair ReadVarint32FromArray( uint32 first_byte, const uint8* buffer, uint32* value) { // Fast path: We have enough bytes left in the buffer to guarantee that @@ -330,71 +347,72 @@ inline ::std::pair ReadVarint32FromArray( uint32 b; uint32 result = first_byte - 0x80; ++ptr; // We just processed the first byte. Move on to the second. - b = *(ptr++); result += b << 7; if (!(b & 0x80)) goto done; + b = *(ptr++); + result += b << 7; + if (!(b & 0x80)) goto done; result -= 0x80 << 7; - b = *(ptr++); result += b << 14; if (!(b & 0x80)) goto done; + b = *(ptr++); + result += b << 14; + if (!(b & 0x80)) goto done; result -= 0x80 << 14; - b = *(ptr++); result += b << 21; if (!(b & 0x80)) goto done; + b = *(ptr++); + result += b << 21; + if (!(b & 0x80)) goto done; result -= 0x80 << 21; - b = *(ptr++); result += b << 28; if (!(b & 0x80)) goto done; + b = *(ptr++); + result += b << 28; + if (!(b & 0x80)) goto done; // "result -= 0x80 << 28" is irrevelant. // If the input is larger than 32 bits, we still need to read it all // and discard the high-order bits. for (int i = 0; i < kMaxVarintBytes - kMaxVarint32Bytes; i++) { - b = *(ptr++); if (!(b & 0x80)) goto done; + b = *(ptr++); + if (!(b & 0x80)) goto done; } // We have overrun the maximum size of a varint (10 bytes). Assume // the data is corrupt. return std::make_pair(false, ptr); - done: +done: *value = result; return std::make_pair(true, ptr); } -GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE::std::pair -ReadVarint64FromArray(const uint8* buffer, uint64* value); +PROTOBUF_ALWAYS_INLINE::std::pair ReadVarint64FromArray( + const uint8* buffer, uint64* value); inline ::std::pair ReadVarint64FromArray( const uint8* buffer, uint64* value) { - const uint8* ptr = buffer; - uint32 b; + // Assumes varint64 is at least 2 bytes. + GOOGLE_DCHECK_GE(buffer[0], 128); - // Splitting into 32-bit pieces gives better performance on 32-bit - // processors. - uint32 part0 = 0, part1 = 0, part2 = 0; + const uint8* next; + if (buffer[1] < 128) { + next = DecodeVarint64KnownSize<2>(buffer, value); + } else if (buffer[2] < 128) { + next = DecodeVarint64KnownSize<3>(buffer, value); + } else if (buffer[3] < 128) { + next = DecodeVarint64KnownSize<4>(buffer, value); + } else if (buffer[4] < 128) { + next = DecodeVarint64KnownSize<5>(buffer, value); + } else if (buffer[5] < 128) { + next = DecodeVarint64KnownSize<6>(buffer, value); + } else if (buffer[6] < 128) { + next = DecodeVarint64KnownSize<7>(buffer, value); + } else if (buffer[7] < 128) { + next = DecodeVarint64KnownSize<8>(buffer, value); + } else if (buffer[8] < 128) { + next = DecodeVarint64KnownSize<9>(buffer, value); + } else if (buffer[9] < 128) { + next = DecodeVarint64KnownSize<10>(buffer, value); + } else { + // We have overrun the maximum size of a varint (10 bytes). Assume + // the data is corrupt. + return std::make_pair(false, buffer + 11); + } - b = *(ptr++); part0 = b ; if (!(b & 0x80)) goto done; - part0 -= 0x80; - b = *(ptr++); part0 += b << 7; if (!(b & 0x80)) goto done; - part0 -= 0x80 << 7; - b = *(ptr++); part0 += b << 14; if (!(b & 0x80)) goto done; - part0 -= 0x80 << 14; - b = *(ptr++); part0 += b << 21; if (!(b & 0x80)) goto done; - part0 -= 0x80 << 21; - b = *(ptr++); part1 = b ; if (!(b & 0x80)) goto done; - part1 -= 0x80; - b = *(ptr++); part1 += b << 7; if (!(b & 0x80)) goto done; - part1 -= 0x80 << 7; - b = *(ptr++); part1 += b << 14; if (!(b & 0x80)) goto done; - part1 -= 0x80 << 14; - b = *(ptr++); part1 += b << 21; if (!(b & 0x80)) goto done; - part1 -= 0x80 << 21; - b = *(ptr++); part2 = b ; if (!(b & 0x80)) goto done; - part2 -= 0x80; - b = *(ptr++); part2 += b << 7; if (!(b & 0x80)) goto done; - // "part2 -= 0x80 << 7" is irrelevant because (0x80 << 7) << 56 is 0. - - // We have overrun the maximum size of a varint (10 bytes). Assume - // the data is corrupt. - return std::make_pair(false, ptr); - - done: - *value = (static_cast(part0)) | - (static_cast(part1) << 28) | - (static_cast(part2) << 56); - return std::make_pair(true, ptr); + return std::make_pair(true, next); } } // namespace @@ -416,7 +434,7 @@ int64 CodedInputStream::ReadVarint32Fallback(uint32 first_byte_or_zero) { << "Caller should provide us with *buffer_ when buffer is non-empty"; uint32 temp; ::std::pair p = - ReadVarint32FromArray(first_byte_or_zero, buffer_, &temp); + ReadVarint32FromArray(first_byte_or_zero, buffer_, &temp); if (!p.first) return -1; buffer_ = p.second; return temp; @@ -627,13 +645,13 @@ CodedOutputStream::CodedOutputStream(ZeroCopyOutputStream* output) CodedOutputStream::CodedOutputStream(ZeroCopyOutputStream* output, bool do_eager_refresh) - : output_(output), - buffer_(NULL), - buffer_size_(0), - total_bytes_(0), - had_error_(false), - aliasing_enabled_(false), - is_serialization_deterministic_(IsDefaultSerializationDeterministic()) { + : output_(output), + buffer_(NULL), + buffer_size_(0), + total_bytes_(0), + had_error_(false), + aliasing_enabled_(false), + is_serialization_deterministic_(IsDefaultSerializationDeterministic()) { if (do_eager_refresh) { // Eagerly Refresh() so buffer space is immediately available. Refresh(); @@ -644,9 +662,7 @@ CodedOutputStream::CodedOutputStream(ZeroCopyOutputStream* output, } } -CodedOutputStream::~CodedOutputStream() { - Trim(); -} +CodedOutputStream::~CodedOutputStream() { Trim(); } void CodedOutputStream::Trim() { if (buffer_size_ > 0) { @@ -689,8 +705,8 @@ void CodedOutputStream::WriteRaw(const void* data, int size) { Advance(size); } -uint8* CodedOutputStream::WriteRawToArray( - const void* data, int size, uint8* target) { +uint8* CodedOutputStream::WriteRawToArray(const void* data, int size, + uint8* target) { memcpy(target, data, size); return target + size; } @@ -698,7 +714,7 @@ uint8* CodedOutputStream::WriteRawToArray( void CodedOutputStream::WriteAliasedRaw(const void* data, int size) { if (size < buffer_size_ - ) { + ) { WriteRaw(data, size); } else { Trim(); @@ -768,7 +784,7 @@ bool CodedOutputStream::Refresh() { } } -uint8* CodedOutputStream::WriteStringWithSizeToArray(const string& str, +uint8* CodedOutputStream::WriteStringWithSizeToArray(const std::string& str, uint8* target) { GOOGLE_DCHECK_LE(str.size(), kuint32max); target = WriteVarint32ToArray(str.size(), target); diff --git a/third_party/protobuf/src/google/protobuf/io/coded_stream.h b/third_party/protobuf/src/google/protobuf/io/coded_stream.h index 0f70ecde..5d065fc2 100644 --- a/third_party/protobuf/src/google/protobuf/io/coded_stream.h +++ b/third_party/protobuf/src/google/protobuf/io/coded_stream.h @@ -67,7 +67,7 @@ // // Read a file created by the above code. // int fd = open("myfile", O_RDONLY); // ZeroCopyInputStream* raw_input = new FileInputStream(fd); -// CodedInputStream coded_input = new CodedInputStream(raw_input); +// CodedInputStream* coded_input = new CodedInputStream(raw_input); // // coded_input->ReadLittleEndian32(&magic_number); // if (magic_number != 1234) { @@ -115,35 +115,41 @@ #include #include #ifdef _MSC_VER - // Assuming windows is always little-endian. - #if !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) - #define PROTOBUF_LITTLE_ENDIAN 1 - #endif - #if _MSC_VER >= 1300 && !defined(__INTEL_COMPILER) - // If MSVC has "/RTCc" set, it will complain about truncating casts at - // runtime. This file contains some intentional truncating casts. - #pragma runtime_checks("c", off) - #endif +// Assuming windows is always little-endian. +#if !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) +#define PROTOBUF_LITTLE_ENDIAN 1 +#endif +#if _MSC_VER >= 1300 && !defined(__INTEL_COMPILER) +// If MSVC has "/RTCc" set, it will complain about truncating casts at +// runtime. This file contains some intentional truncating casts. +#pragma runtime_checks("c", off) +#endif #else - #include // __BYTE_ORDER - #if ((defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)) || \ - (defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN)) && \ - !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) - #define PROTOBUF_LITTLE_ENDIAN 1 - #endif +#include // __BYTE_ORDER +#if ((defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)) || \ + (defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN)) && \ + !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) +#define PROTOBUF_LITTLE_ENDIAN 1 +#endif #endif #include +#include #include -#include + + +#include namespace google { - namespace protobuf { class DescriptorPool; class MessageFactory; +class ZeroCopyCodedInputStream; -namespace internal { void MapTestForceDeterministic(); } +namespace internal { +void MapTestForceDeterministic(); +class EpsCopyByteStream; +} // namespace internal namespace io { @@ -152,8 +158,8 @@ class CodedInputStream; class CodedOutputStream; // Defined in other files. -class ZeroCopyInputStream; // zero_copy_stream.h -class ZeroCopyOutputStream; // zero_copy_stream.h +class ZeroCopyInputStream; // zero_copy_stream.h +class ZeroCopyOutputStream; // zero_copy_stream.h // Class which reads and decodes binary data which is composed of varint- // encoded integers and fixed-width pieces. Wraps a ZeroCopyInputStream. @@ -162,7 +168,9 @@ class ZeroCopyOutputStream; // zero_copy_stream.h // Most methods of CodedInputStream that return a bool return false if an // underlying I/O error occurs or if the data is malformed. Once such a // failure occurs, the CodedInputStream is broken and is no longer useful. -class LIBPROTOBUF_EXPORT CodedInputStream { +// After a failure, callers also should assume writes to "out" args may have +// occurred, though nothing useful can be determined from those writes. +class PROTOBUF_EXPORT CodedInputStream { public: // Create a CodedInputStream that reads from the given ZeroCopyInputStream. explicit CodedInputStream(ZeroCopyInputStream* input); @@ -198,7 +206,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // Like GetDirectBufferPointer, but this method is inlined, and does not // attempt to Refresh() if the buffer is currently empty. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE + PROTOBUF_ALWAYS_INLINE void GetDirectBufferPointerInline(const void** data, int* size); // Read raw bytes, copying them into the given buffer. @@ -206,15 +214,15 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // Like the above, with inlined optimizations. This should only be used // by the protobuf implementation. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE + PROTOBUF_ALWAYS_INLINE bool InternalReadRawInline(void* buffer, int size); // Like ReadRaw, but reads into a string. - bool ReadString(string* buffer, int size); + bool ReadString(std::string* buffer, int size); // Like the above, with inlined optimizations. This should only be used // by the protobuf implementation. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - bool InternalReadStringInline(string* buffer, int size); + PROTOBUF_ALWAYS_INLINE + bool InternalReadStringInline(std::string* buffer, int size); // Read a 32-bit little-endian integer. @@ -226,10 +234,10 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // responsible for ensuring that the buffer has sufficient space. // Read a 32-bit little-endian integer. static const uint8* ReadLittleEndian32FromArray(const uint8* buffer, - uint32* value); + uint32* value); // Read a 64-bit little-endian integer. static const uint8* ReadLittleEndian64FromArray(const uint8* buffer, - uint64* value); + uint64* value); // Read an unsigned integer with Varint encoding, truncating to 32 bits. // Reading a 32-bit value is equivalent to reading a 64-bit one and casting @@ -257,12 +265,11 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // Always inline because this is only called in one place per parse loop // but it is called for every iteration of said loop, so it should be fast. // GCC doesn't want to inline this by default. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE uint32 ReadTag() { + PROTOBUF_ALWAYS_INLINE uint32 ReadTag() { return last_tag_ = ReadTagNoLastTag(); } - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE uint32 ReadTagNoLastTag(); - + PROTOBUF_ALWAYS_INLINE uint32 ReadTagNoLastTag(); // This usually a faster alternative to ReadTag() when cutoff is a manifest // constant. It does particularly well for cutoff >= 127. The first part @@ -272,14 +279,14 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // above cutoff or is 0. (There's intentional wiggle room when tag is 0, // because that can arise in several ways, and for best performance we want // to avoid an extra "is tag == 0?" check here.) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE + PROTOBUF_ALWAYS_INLINE std::pair ReadTagWithCutoff(uint32 cutoff) { std::pair result = ReadTagWithCutoffNoLastTag(cutoff); last_tag_ = result.first; return result; } - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE + PROTOBUF_ALWAYS_INLINE std::pair ReadTagWithCutoffNoLastTag(uint32 cutoff); // Usually returns true if calling ReadVarint32() now would produce the given @@ -289,7 +296,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // parameter. // Always inline because this collapses to a small number of instructions // when given a constant parameter, but GCC doesn't want to inline by default. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool ExpectTag(uint32 expected); + PROTOBUF_ALWAYS_INLINE bool ExpectTag(uint32 expected); // Like above, except this reads from the specified buffer. The caller is // responsible for ensuring that the buffer is large enough to read a varint @@ -298,7 +305,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // // Returns a pointer beyond the expected tag if it was found, or NULL if it // was not. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE + PROTOBUF_ALWAYS_INLINE static const uint8* ExpectTagFromArray(const uint8* buffer, uint32 expected); // Usually returns true if no more bytes can be read. Always returns false @@ -328,6 +335,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // It also checks for some cases where, due to optimizations, // MergeFromCodedStream() can incorrectly return true. bool ConsumedEntireMessage(); + void SetConsumed() { legitimate_message_end_ = true; } // Limits ---------------------------------------------------------- // Limits are used when parsing length-delimited embedded messages. @@ -384,7 +392,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // This is unrelated to PushLimit()/PopLimit(). void SetTotalBytesLimit(int total_bytes_limit); - PROTOBUF_RUNTIME_DEPRECATED( + PROTOBUF_DEPRECATED_MSG( "Please use the single parameter version of SetTotalBytesLimit(). The " "second parameter is ignored.") void SetTotalBytesLimit(int total_bytes_limit, int) { @@ -403,7 +411,9 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // Sets the maximum recursion depth. The default is 100. void SetRecursionLimit(int limit); + int RecursionBudget() { return recursion_budget_; } + static int GetDefaultRecursionLimit() { return default_recursion_limit_; } // Increments the current recursion depth. Returns true if the depth is // under the limit, false if it has gone over. @@ -527,7 +537,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream { GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CodedInputStream); const uint8* buffer_; - const uint8* buffer_end_; // pointer to the end of the buffer. + const uint8* buffer_end_; // pointer to the end of the buffer. ZeroCopyInputStream* input_; int total_bytes_read_; // total bytes read from input_, including // the current buffer @@ -537,7 +547,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream { int overflow_bytes_; // LastTagWas() stuff. - uint32 last_tag_; // result of last ReadTag() or ReadTagWithCutoff(). + uint32 last_tag_; // result of last ReadTag() or ReadTagWithCutoff(). // This is set true by ReadTag{Fallback/Slow}() if it is called when exactly // at EOF, or by ExpectAtEnd() when it returns true. This happens when we @@ -548,7 +558,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream { bool aliasing_enabled_; // Limits - Limit current_limit_; // if position = -1, no limit is applied + Limit current_limit_; // if position = -1, no limit is applied // For simplicity, if the current buffer crosses a limit (either a normal // limit created by PushLimit() or the total bytes limit), buffer_size_ @@ -621,7 +631,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // stream. uint32 ReadTagFallback(uint32 first_byte_or_zero); uint32 ReadTagSlow(); - bool ReadStringFallback(string* buffer, int size); + bool ReadStringFallback(std::string* buffer, int size); // Return the size of the buffer. int BufferSize() const; @@ -629,6 +639,9 @@ class LIBPROTOBUF_EXPORT CodedInputStream { static const int kDefaultTotalBytesLimit = INT_MAX; static int default_recursion_limit_; // 100 by default. + + friend class google::protobuf::ZeroCopyCodedInputStream; + friend class google::protobuf::internal::EpsCopyByteStream; }; // Class which encodes and writes binary data which is composed of varint- @@ -677,7 +690,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // } // // delete coded_output; -class LIBPROTOBUF_EXPORT CodedOutputStream { +class PROTOBUF_EXPORT CodedOutputStream { public: // Create an CodedOutputStream that writes to the given ZeroCopyOutputStream. explicit CodedOutputStream(ZeroCopyOutputStream* output); @@ -697,6 +710,9 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { // Skips a number of bytes, leaving the bytes unmodified in the underlying // buffer. Returns false if an underlying write error occurs. This is // mainly useful with GetDirectBufferPointer(). + // Note of caution, the skipped bytes may contain uninitialized data. The + // caller must make sure that the skipped bytes are properly initialized, + // otherwise you might leak bytes from your heap. bool Skip(int count); // Sets *data to point directly at the unwritten part of the @@ -731,11 +747,12 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { static uint8* WriteRawToArray(const void* buffer, int size, uint8* target); // Equivalent to WriteRaw(str.data(), str.size()). - void WriteString(const string& str); + void WriteString(const std::string& str); // Like WriteString() but writing directly to the target array. - static uint8* WriteStringToArray(const string& str, uint8* target); + static uint8* WriteStringToArray(const std::string& str, uint8* target); // Write the varint-encoded size of str followed by str. - static uint8* WriteStringWithSizeToArray(const string& str, uint8* target); + static uint8* WriteStringWithSizeToArray(const std::string& str, + uint8* target); // Instructs the CodedOutputStream to allow the underlying @@ -782,7 +799,7 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { // but GCC by default doesn't want to inline this. void WriteTag(uint32 value); // Like WriteTag() but writing directly to the target array. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE + PROTOBUF_ALWAYS_INLINE static uint8* WriteTagToArray(uint32 value, uint8* target); // Returns the number of bytes needed to encode the given value as a varint. @@ -800,12 +817,8 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { (Value < (1 << 7)) ? 1 : (Value < (1 << 14)) - ? 2 - : (Value < (1 << 21)) - ? 3 - : (Value < (1 << 28)) - ? 4 - : 5; + ? 2 + : (Value < (1 << 21)) ? 3 : (Value < (1 << 28)) ? 4 : 5; }; // Returns the total number of bytes written since this object was created. @@ -851,7 +864,8 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { } static bool IsDefaultSerializationDeterministic() { - return default_serialization_deterministic_.load(std::memory_order_relaxed) != 0; + return default_serialization_deterministic_.load( + std::memory_order_relaxed) != 0; } private: @@ -860,8 +874,8 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { ZeroCopyOutputStream* output_; uint8* buffer_; int buffer_size_; - int total_bytes_; // Sum of sizes of all buffers seen so far. - bool had_error_; // Whether an error occurred during output. + int total_bytes_; // Sum of sizes of all buffers seen so far. + bool had_error_; // Whether an error occurred during output. bool aliasing_enabled_; // See EnableAliasing(). bool is_serialization_deterministic_; static std::atomic default_serialization_deterministic_; @@ -889,7 +903,7 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { // that wants deterministic serialization by default needs to call // SetDefaultSerializationDeterministic() or ensure on its own that another // thread has done so. - friend void ::google::protobuf::internal::MapTestForceDeterministic(); + friend void internal::MapTestForceDeterministic(); static void SetDefaultSerializationDeterministic() { default_serialization_deterministic_.store(true, std::memory_order_relaxed); } @@ -901,7 +915,7 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { inline bool CodedInputStream::ReadVarint32(uint32* value) { uint32 v = 0; - if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_)) { + if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_)) { v = *buffer_; if (v < 0x80) { *value = v; @@ -915,7 +929,7 @@ inline bool CodedInputStream::ReadVarint32(uint32* value) { } inline bool CodedInputStream::ReadVarint64(uint64* value) { - if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_) && *buffer_ < 0x80) { + if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_) && *buffer_ < 0x80) { *value = *buffer_; Advance(1); return true; @@ -926,7 +940,7 @@ inline bool CodedInputStream::ReadVarint64(uint64* value) { } inline bool CodedInputStream::ReadVarintSizeAsInt(int* value) { - if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_)) { + if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_)) { int v = *buffer_; if (v < 0x80) { *value = v; @@ -940,14 +954,13 @@ inline bool CodedInputStream::ReadVarintSizeAsInt(int* value) { // static inline const uint8* CodedInputStream::ReadLittleEndian32FromArray( - const uint8* buffer, - uint32* value) { + const uint8* buffer, uint32* value) { #if defined(PROTOBUF_LITTLE_ENDIAN) memcpy(value, buffer, sizeof(*value)); return buffer + sizeof(*value); #else - *value = (static_cast(buffer[0]) ) | - (static_cast(buffer[1]) << 8) | + *value = (static_cast(buffer[0])) | + (static_cast(buffer[1]) << 8) | (static_cast(buffer[2]) << 16) | (static_cast(buffer[3]) << 24); return buffer + sizeof(*value); @@ -955,29 +968,27 @@ inline const uint8* CodedInputStream::ReadLittleEndian32FromArray( } // static inline const uint8* CodedInputStream::ReadLittleEndian64FromArray( - const uint8* buffer, - uint64* value) { + const uint8* buffer, uint64* value) { #if defined(PROTOBUF_LITTLE_ENDIAN) memcpy(value, buffer, sizeof(*value)); return buffer + sizeof(*value); #else - uint32 part0 = (static_cast(buffer[0]) ) | - (static_cast(buffer[1]) << 8) | + uint32 part0 = (static_cast(buffer[0])) | + (static_cast(buffer[1]) << 8) | (static_cast(buffer[2]) << 16) | (static_cast(buffer[3]) << 24); - uint32 part1 = (static_cast(buffer[4]) ) | - (static_cast(buffer[5]) << 8) | + uint32 part1 = (static_cast(buffer[4])) | + (static_cast(buffer[5]) << 8) | (static_cast(buffer[6]) << 16) | (static_cast(buffer[7]) << 24); - *value = static_cast(part0) | - (static_cast(part1) << 32); + *value = static_cast(part0) | (static_cast(part1) << 32); return buffer + sizeof(*value); #endif } inline bool CodedInputStream::ReadLittleEndian32(uint32* value) { #if defined(PROTOBUF_LITTLE_ENDIAN) - if (GOOGLE_PREDICT_TRUE(BufferSize() >= static_cast(sizeof(*value)))) { + if (PROTOBUF_PREDICT_TRUE(BufferSize() >= static_cast(sizeof(*value)))) { buffer_ = ReadLittleEndian32FromArray(buffer_, value); return true; } else { @@ -990,7 +1001,7 @@ inline bool CodedInputStream::ReadLittleEndian32(uint32* value) { inline bool CodedInputStream::ReadLittleEndian64(uint64* value) { #if defined(PROTOBUF_LITTLE_ENDIAN) - if (GOOGLE_PREDICT_TRUE(BufferSize() >= static_cast(sizeof(*value)))) { + if (PROTOBUF_PREDICT_TRUE(BufferSize() >= static_cast(sizeof(*value)))) { buffer_ = ReadLittleEndian64FromArray(buffer_, value); return true; } else { @@ -1003,7 +1014,7 @@ inline bool CodedInputStream::ReadLittleEndian64(uint64* value) { inline uint32 CodedInputStream::ReadTagNoLastTag() { uint32 v = 0; - if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_)) { + if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_)) { v = *buffer_; if (v < 0x80) { Advance(1); @@ -1020,7 +1031,7 @@ inline std::pair CodedInputStream::ReadTagWithCutoffNoLastTag( // constant, and things like "cutoff >= kMax1ByteVarint" to be evaluated at // compile time. uint32 first_byte_or_zero = 0; - if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_)) { + if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_)) { // Hot case: buffer_ non_empty, buffer_[0] in [1, 128). // TODO(gpike): Is it worth rearranging this? E.g., if the number of fields // is large enough then is it better to check for the two-byte case first? @@ -1034,8 +1045,8 @@ inline std::pair CodedInputStream::ReadTagWithCutoffNoLastTag( // Other hot case: cutoff >= 0x80, buffer_ has at least two bytes available, // and tag is two bytes. The latter is tested by bitwise-and-not of the // first byte and the second byte. - if (cutoff >= 0x80 && GOOGLE_PREDICT_TRUE(buffer_ + 1 < buffer_end_) && - GOOGLE_PREDICT_TRUE((buffer_[0] & ~buffer_[1]) >= 0x80)) { + if (cutoff >= 0x80 && PROTOBUF_PREDICT_TRUE(buffer_ + 1 < buffer_end_) && + PROTOBUF_PREDICT_TRUE((buffer_[0] & ~buffer_[1]) >= 0x80)) { const uint32 kMax2ByteVarint = (0x7f << 7) + 0x7f; uint32 tag = (1u << 7) * buffer_[1] + (buffer_[0] - 0x80); Advance(2); @@ -1064,14 +1075,15 @@ inline bool CodedInputStream::ConsumedEntireMessage() { inline bool CodedInputStream::ExpectTag(uint32 expected) { if (expected < (1 << 7)) { - if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_) && buffer_[0] == expected) { + if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_) && + buffer_[0] == expected) { Advance(1); return true; } else { return false; } } else if (expected < (1 << 14)) { - if (GOOGLE_PREDICT_TRUE(BufferSize() >= 2) && + if (PROTOBUF_PREDICT_TRUE(BufferSize() >= 2) && buffer_[0] == static_cast(expected | 0x80) && buffer_[1] == static_cast(expected >> 7)) { Advance(2); @@ -1085,8 +1097,8 @@ inline bool CodedInputStream::ExpectTag(uint32 expected) { } } -inline const uint8* CodedInputStream::ExpectTagFromArray( - const uint8* buffer, uint32 expected) { +inline const uint8* CodedInputStream::ExpectTagFromArray(const uint8* buffer, + uint32 expected) { if (expected < (1 << 7)) { if (buffer[0] == expected) { return buffer + 1; @@ -1110,9 +1122,8 @@ inline bool CodedInputStream::ExpectAtEnd() { // If we are at a limit we know no more bytes can be read. Otherwise, it's // hard to say without calling Refresh(), and we'd rather not do that. - if (buffer_ == buffer_end_ && - ((buffer_size_after_limit_ != 0) || - (total_bytes_read_ == current_limit_))) { + if (buffer_ == buffer_end_ && ((buffer_size_after_limit_ != 0) || + (total_bytes_read_ == current_limit_))) { last_tag_ = 0; // Pretend we called ReadTag()... legitimate_message_end_ = true; // ... and it hit EOF. return true; @@ -1172,7 +1183,7 @@ inline uint8* CodedOutputStream::WriteLittleEndian32ToArray(uint32 value, memcpy(target, &value, sizeof(value)); #else target[0] = static_cast(value); - target[1] = static_cast(value >> 8); + target[1] = static_cast(value >> 8); target[2] = static_cast(value >> 16); target[3] = static_cast(value >> 24); #endif @@ -1188,11 +1199,11 @@ inline uint8* CodedOutputStream::WriteLittleEndian64ToArray(uint64 value, uint32 part1 = static_cast(value >> 32); target[0] = static_cast(part0); - target[1] = static_cast(part0 >> 8); + target[1] = static_cast(part0 >> 8); target[2] = static_cast(part0 >> 16); target[3] = static_cast(part0 >> 24); target[4] = static_cast(part1); - target[5] = static_cast(part1 >> 8); + target[5] = static_cast(part1 >> 8); target[6] = static_cast(part1 >> 16); target[7] = static_cast(part1 >> 24); #endif @@ -1225,12 +1236,9 @@ inline void CodedOutputStream::WriteVarint64(uint64 value) { } } -inline void CodedOutputStream::WriteTag(uint32 value) { - WriteVarint32(value); -} +inline void CodedOutputStream::WriteTag(uint32 value) { WriteVarint32(value); } -inline uint8* CodedOutputStream::WriteTagToArray( - uint32 value, uint8* target) { +inline uint8* CodedOutputStream::WriteTagToArray(uint32 value, uint8* target) { return WriteVarint32ToArray(value, target); } @@ -1256,18 +1264,18 @@ inline size_t CodedOutputStream::VarintSize64(uint64 value) { inline size_t CodedOutputStream::VarintSize32SignExtended(int32 value) { if (value < 0) { - return 10; // TODO(kenton): Make this a symbolic constant. + return 10; // TODO(kenton): Make this a symbolic constant. } else { return VarintSize32(static_cast(value)); } } -inline void CodedOutputStream::WriteString(const string& str) { +inline void CodedOutputStream::WriteString(const std::string& str) { WriteRaw(str.data(), static_cast(str.size())); } -inline void CodedOutputStream::WriteRawMaybeAliased( - const void* data, int size) { +inline void CodedOutputStream::WriteRawMaybeAliased(const void* data, + int size) { if (aliasing_enabled_) { WriteAliasedRaw(data, size); } else { @@ -1275,8 +1283,8 @@ inline void CodedOutputStream::WriteRawMaybeAliased( } } -inline uint8* CodedOutputStream::WriteStringToArray( - const string& str, uint8* target) { +inline uint8* CodedOutputStream::WriteStringToArray(const std::string& str, + uint8* target) { return WriteRawToArray(str.data(), static_cast(str.size()), target); } @@ -1284,9 +1292,7 @@ inline int CodedOutputStream::ByteCount() const { return total_bytes_ - buffer_size_; } -inline void CodedInputStream::Advance(int amount) { - buffer_ += amount; -} +inline void CodedInputStream::Advance(int amount) { buffer_ += amount; } inline void CodedOutputStream::Advance(int amount) { buffer_ += amount; @@ -1331,48 +1337,46 @@ inline int CodedInputStream::BufferSize() const { } inline CodedInputStream::CodedInputStream(ZeroCopyInputStream* input) - : buffer_(NULL), - buffer_end_(NULL), - input_(input), - total_bytes_read_(0), - overflow_bytes_(0), - last_tag_(0), - legitimate_message_end_(false), - aliasing_enabled_(false), - current_limit_(kint32max), - buffer_size_after_limit_(0), - total_bytes_limit_(kDefaultTotalBytesLimit), - recursion_budget_(default_recursion_limit_), - recursion_limit_(default_recursion_limit_), - extension_pool_(NULL), - extension_factory_(NULL) { + : buffer_(NULL), + buffer_end_(NULL), + input_(input), + total_bytes_read_(0), + overflow_bytes_(0), + last_tag_(0), + legitimate_message_end_(false), + aliasing_enabled_(false), + current_limit_(kint32max), + buffer_size_after_limit_(0), + total_bytes_limit_(kDefaultTotalBytesLimit), + recursion_budget_(default_recursion_limit_), + recursion_limit_(default_recursion_limit_), + extension_pool_(NULL), + extension_factory_(NULL) { // Eagerly Refresh() so buffer space is immediately available. Refresh(); } inline CodedInputStream::CodedInputStream(const uint8* buffer, int size) - : buffer_(buffer), - buffer_end_(buffer + size), - input_(NULL), - total_bytes_read_(size), - overflow_bytes_(0), - last_tag_(0), - legitimate_message_end_(false), - aliasing_enabled_(false), - current_limit_(size), - buffer_size_after_limit_(0), - total_bytes_limit_(kDefaultTotalBytesLimit), - recursion_budget_(default_recursion_limit_), - recursion_limit_(default_recursion_limit_), - extension_pool_(NULL), - extension_factory_(NULL) { + : buffer_(buffer), + buffer_end_(buffer + size), + input_(NULL), + total_bytes_read_(size), + overflow_bytes_(0), + last_tag_(0), + legitimate_message_end_(false), + aliasing_enabled_(false), + current_limit_(size), + buffer_size_after_limit_(0), + total_bytes_limit_(kDefaultTotalBytesLimit), + recursion_budget_(default_recursion_limit_), + recursion_limit_(default_recursion_limit_), + extension_pool_(NULL), + extension_factory_(NULL) { // Note that setting current_limit_ == size is important to prevent some // code paths from trying to access input_ and segfaulting. } -inline bool CodedInputStream::IsFlat() const { - return input_ == NULL; -} +inline bool CodedInputStream::IsFlat() const { return input_ == NULL; } inline bool CodedInputStream::Skip(int count) { if (count < 0) return false; // security: count is often user-supplied @@ -1390,11 +1394,12 @@ inline bool CodedInputStream::Skip(int count) { } // namespace io } // namespace protobuf - +} // namespace google #if defined(_MSC_VER) && _MSC_VER >= 1300 && !defined(__INTEL_COMPILER) - #pragma runtime_checks("c", restore) +#pragma runtime_checks("c", restore) #endif // _MSC_VER && !defined(__INTEL_COMPILER) -} // namespace google +#include + #endif // GOOGLE_PROTOBUF_IO_CODED_STREAM_H__ diff --git a/third_party/protobuf/src/google/protobuf/io/coded_stream_inl.h b/third_party/protobuf/src/google/protobuf/io/coded_stream_inl.h index d95b06e0..0c10e655 100644 --- a/third_party/protobuf/src/google/protobuf/io/coded_stream_inl.h +++ b/third_party/protobuf/src/google/protobuf/io/coded_stream_inl.h @@ -36,18 +36,18 @@ #ifndef GOOGLE_PROTOBUF_IO_CODED_STREAM_INL_H__ #define GOOGLE_PROTOBUF_IO_CODED_STREAM_INL_H__ +#include #include #include #include #include -#include #include namespace google { namespace protobuf { namespace io { -inline bool CodedInputStream::InternalReadStringInline(string* buffer, +inline bool CodedInputStream::InternalReadStringInline(std::string* buffer, int size) { if (size < 0) return false; // security: size is often user-supplied diff --git a/third_party/protobuf/src/google/protobuf/io/coded_stream_unittest.cc b/third_party/protobuf/src/google/protobuf/io/coded_stream_unittest.cc index 1c8d3272..26e6a7c5 100644 --- a/third_party/protobuf/src/google/protobuf/io/coded_stream_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/io/coded_stream_unittest.cc @@ -44,18 +44,20 @@ #include #include #include +#include #include #include -#include +#include +#include // This declares an unsigned long long integer literal in a portable way. // (The original macro is way too big and ruins my formatting.) #undef ULL -#define ULL(x) GOOGLE_ULONGLONG(x) +#define ULL(x) PROTOBUF_ULONGLONG(x) + namespace google { - namespace protobuf { namespace io { namespace { @@ -84,57 +86,51 @@ namespace { // TODO(kenton): gTest now supports "parameterized tests" which would be // a better way to accomplish this. Rewrite when time permits. -#define TEST_1D(FIXTURE, NAME, CASES) \ - class FIXTURE##_##NAME##_DD : public FIXTURE { \ - protected: \ - template \ - void DoSingleCase(const CaseType& CASES##_case); \ - }; \ - \ - TEST_F(FIXTURE##_##NAME##_DD, NAME) { \ - for (int i = 0; i < GOOGLE_ARRAYSIZE(CASES); i++) { \ - SCOPED_TRACE(testing::Message() \ - << #CASES " case #" << i << ": " << CASES[i]); \ - DoSingleCase(CASES[i]); \ - } \ - } \ - \ - template \ +#define TEST_1D(FIXTURE, NAME, CASES) \ + class FIXTURE##_##NAME##_DD : public FIXTURE { \ + protected: \ + template \ + void DoSingleCase(const CaseType& CASES##_case); \ + }; \ + \ + TEST_F(FIXTURE##_##NAME##_DD, NAME) { \ + for (int i = 0; i < GOOGLE_ARRAYSIZE(CASES); i++) { \ + SCOPED_TRACE(testing::Message() \ + << #CASES " case #" << i << ": " << CASES[i]); \ + DoSingleCase(CASES[i]); \ + } \ + } \ + \ + template \ void FIXTURE##_##NAME##_DD::DoSingleCase(const CaseType& CASES##_case) -#define TEST_2D(FIXTURE, NAME, CASES1, CASES2) \ - class FIXTURE##_##NAME##_DD : public FIXTURE { \ - protected: \ - template \ - void DoSingleCase(const CaseType1& CASES1##_case, \ - const CaseType2& CASES2##_case); \ - }; \ - \ - TEST_F(FIXTURE##_##NAME##_DD, NAME) { \ - for (int i = 0; i < GOOGLE_ARRAYSIZE(CASES1); i++) { \ - for (int j = 0; j < GOOGLE_ARRAYSIZE(CASES2); j++) { \ - SCOPED_TRACE(testing::Message() \ - << #CASES1 " case #" << i << ": " << CASES1[i] << ", " \ - << #CASES2 " case #" << j << ": " << CASES2[j]); \ - DoSingleCase(CASES1[i], CASES2[j]); \ - } \ - } \ - } \ - \ - template \ - void FIXTURE##_##NAME##_DD::DoSingleCase(const CaseType1& CASES1##_case, \ +#define TEST_2D(FIXTURE, NAME, CASES1, CASES2) \ + class FIXTURE##_##NAME##_DD : public FIXTURE { \ + protected: \ + template \ + void DoSingleCase(const CaseType1& CASES1##_case, \ + const CaseType2& CASES2##_case); \ + }; \ + \ + TEST_F(FIXTURE##_##NAME##_DD, NAME) { \ + for (int i = 0; i < GOOGLE_ARRAYSIZE(CASES1); i++) { \ + for (int j = 0; j < GOOGLE_ARRAYSIZE(CASES2); j++) { \ + SCOPED_TRACE(testing::Message() \ + << #CASES1 " case #" << i << ": " << CASES1[i] << ", " \ + << #CASES2 " case #" << j << ": " << CASES2[j]); \ + DoSingleCase(CASES1[i], CASES2[j]); \ + } \ + } \ + } \ + \ + template \ + void FIXTURE##_##NAME##_DD::DoSingleCase(const CaseType1& CASES1##_case, \ const CaseType2& CASES2##_case) // =================================================================== class CodedStreamTest : public testing::Test { protected: - // Helper method used by tests for bytes warning. See implementation comment - // for further information. - static void SetupTotalBytesLimitWarningTest( - int total_bytes_limit, int warning_threshold, - std::vector* out_errors, std::vector* out_warnings); - // Buffer used during most of the tests. This assumes tests run sequentially. static const int kBufferSize = 1024 * 64; static uint8 buffer_[kBufferSize]; @@ -154,9 +150,9 @@ const int kBlockSizes[] = {1, 2, 3, 5, 7, 13, 32, 1024}; // Varint tests. struct VarintCase { - uint8 bytes[10]; // Encoded bytes. - int size; // Encoded size, in bytes. - uint64 value; // Parsed value. + uint8 bytes[10]; // Encoded bytes. + int size; // Encoded size, in bytes. + uint64 value; // Parsed value. }; inline std::ostream& operator<<(std::ostream& os, const VarintCase& c) { @@ -164,28 +160,32 @@ inline std::ostream& operator<<(std::ostream& os, const VarintCase& c) { } VarintCase kVarintCases[] = { - // 32-bit values - {{0x00} , 1, 0}, - {{0x01} , 1, 1}, - {{0x7f} , 1, 127}, - {{0xa2, 0x74}, 2, (0x22 << 0) | (0x74 << 7)}, // 14882 - {{0xbe, 0xf7, 0x92, 0x84, 0x0b}, 5, // 2961488830 - (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | - (ULL(0x0b) << 28)}, + // 32-bit values + {{0x00}, 1, 0}, + {{0x01}, 1, 1}, + {{0x7f}, 1, 127}, + {{0xa2, 0x74}, 2, (0x22 << 0) | (0x74 << 7)}, // 14882 + {{0xbe, 0xf7, 0x92, 0x84, 0x0b}, + 5, // 2961488830 + (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | + (ULL(0x0b) << 28)}, - // 64-bit - {{0xbe, 0xf7, 0x92, 0x84, 0x1b}, 5, // 7256456126 - (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | - (ULL(0x1b) << 28)}, - {{0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49}, 8, // 41256202580718336 - (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | - (ULL(0x43) << 28) | (ULL(0x49) << 35) | (ULL(0x24) << 42) | - (ULL(0x49) << 49)}, - // 11964378330978735131 - {{0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01}, 10, - (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | - (ULL(0x3b) << 28) | (ULL(0x56) << 35) | (ULL(0x00) << 42) | - (ULL(0x05) << 49) | (ULL(0x26) << 56) | (ULL(0x01) << 63)}, + // 64-bit + {{0xbe, 0xf7, 0x92, 0x84, 0x1b}, + 5, // 7256456126 + (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | + (ULL(0x1b) << 28)}, + {{0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49}, + 8, // 41256202580718336 + (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | + (ULL(0x43) << 28) | (ULL(0x49) << 35) | (ULL(0x24) << 42) | + (ULL(0x49) << 49)}, + // 11964378330978735131 + {{0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01}, + 10, + (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | + (ULL(0x3b) << 28) | (ULL(0x56) << 35) | (ULL(0x00) << 42) | + (ULL(0x05) << 49) | (ULL(0x26) << 56) | (ULL(0x01) << 63)}, }; TEST_2D(CodedStreamTest, ReadVarint32, kVarintCases, kBlockSizes) { @@ -226,15 +226,14 @@ TEST_F(CodedStreamTest, EmptyInputBeforeEos) { class In : public ZeroCopyInputStream { public: In() : count_(0) {} + private: virtual bool Next(const void** data, int* size) { *data = NULL; *size = 0; return count_++ < 2; } - virtual void BackUp(int count) { - GOOGLE_LOG(FATAL) << "Tests never call this."; - } + virtual void BackUp(int count) { GOOGLE_LOG(FATAL) << "Tests never call this."; } virtual bool Skip(int count) { GOOGLE_LOG(FATAL) << "Tests never call this."; return false; @@ -288,9 +287,8 @@ TEST_1D(CodedStreamTest, ExpectTagFromArray, kVarintCases) { // If the expectation succeeds, it should return a pointer past the tag. if (kVarintCases_case.size <= 2) { - EXPECT_TRUE(NULL == - CodedInputStream::ExpectTagFromArray(buffer_, - expected_value + 1)); + EXPECT_TRUE(NULL == CodedInputStream::ExpectTagFromArray( + buffer_, expected_value + 1)); EXPECT_TRUE(buffer_ + kVarintCases_case.size == CodedInputStream::ExpectTagFromArray(buffer_, expected_value)); } else { @@ -333,7 +331,7 @@ TEST_2D(CodedStreamTest, WriteVarint32, kVarintCases, kBlockSizes) { EXPECT_EQ(kVarintCases_case.size, output.ByteCount()); EXPECT_EQ(0, - memcmp(buffer_, kVarintCases_case.bytes, kVarintCases_case.size)); + memcmp(buffer_, kVarintCases_case.bytes, kVarintCases_case.size)); } TEST_2D(CodedStreamTest, WriteVarint64, kVarintCases, kBlockSizes) { @@ -350,19 +348,17 @@ TEST_2D(CodedStreamTest, WriteVarint64, kVarintCases, kBlockSizes) { EXPECT_EQ(kVarintCases_case.size, output.ByteCount()); EXPECT_EQ(0, - memcmp(buffer_, kVarintCases_case.bytes, kVarintCases_case.size)); + memcmp(buffer_, kVarintCases_case.bytes, kVarintCases_case.size)); } // This test causes gcc 3.3.5 (and earlier?) to give the cryptic error: // "sorry, unimplemented: `method_call_expr' not supported by dump_expr" #if !defined(__GNUC__) || __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 3) -int32 kSignExtendedVarintCases[] = { - 0, 1, -1, 1237894, -37895138 -}; +int32 kSignExtendedVarintCases[] = {0, 1, -1, 1237894, -37895138}; -TEST_2D(CodedStreamTest, WriteVarint32SignExtended, - kSignExtendedVarintCases, kBlockSizes) { +TEST_2D(CodedStreamTest, WriteVarint32SignExtended, kSignExtendedVarintCases, + kBlockSizes) { ArrayOutputStream output(buffer_, sizeof(buffer_), kBlockSizes_case); { @@ -416,22 +412,23 @@ inline std::ostream& operator<<(std::ostream& os, const VarintErrorCase& c) { } const VarintErrorCase kVarintErrorCases[] = { - // Control case. (Insures that there isn't something else wrong that - // makes parsing always fail.) - {{0x00}, 1, true}, + // Control case. (Insures that there isn't something else wrong that + // makes parsing always fail.) + {{0x00}, 1, true}, - // No input data. - {{}, 0, false}, + // No input data. + {{}, 0, false}, - // Input ends unexpectedly. - {{0xf0, 0xab}, 2, false}, + // Input ends unexpectedly. + {{0xf0, 0xab}, 2, false}, - // Input ends unexpectedly after 32 bits. - {{0xf0, 0xab, 0xc9, 0x9a, 0xf8, 0xb2}, 6, false}, + // Input ends unexpectedly after 32 bits. + {{0xf0, 0xab, 0xc9, 0x9a, 0xf8, 0xb2}, 6, false}, - // Longer than 10 bytes. - {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01}, - 11, false}, + // Longer than 10 bytes. + {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01}, + 11, + false}, }; TEST_2D(CodedStreamTest, ReadVarint32Error, kVarintErrorCases, kBlockSizes) { @@ -497,14 +494,14 @@ inline std::ostream& operator<<(std::ostream& os, const VarintSizeCase& c) { } VarintSizeCase kVarintSizeCases[] = { - {0u, 1}, - {1u, 1}, - {127u, 1}, - {128u, 2}, - {758923u, 3}, - {4000000000u, 5}, - {ULL(41256202580718336), 8}, - {ULL(11964378330978735131), 10}, + {0u, 1}, + {1u, 1}, + {127u, 1}, + {128u, 2}, + {758923u, 3}, + {4000000000u, 5}, + {ULL(41256202580718336), 8}, + {ULL(11964378330978735131), 10}, }; TEST_1D(CodedStreamTest, VarintSize32, kVarintSizeCases) { @@ -514,13 +511,13 @@ TEST_1D(CodedStreamTest, VarintSize32, kVarintSizeCases) { } EXPECT_EQ(kVarintSizeCases_case.size, - CodedOutputStream::VarintSize32( - static_cast(kVarintSizeCases_case.value))); + CodedOutputStream::VarintSize32( + static_cast(kVarintSizeCases_case.value))); } TEST_1D(CodedStreamTest, VarintSize64, kVarintSizeCases) { EXPECT_EQ(kVarintSizeCases_case.size, - CodedOutputStream::VarintSize64(kVarintSizeCases_case.value)); + CodedOutputStream::VarintSize64(kVarintSizeCases_case.value)); } TEST_F(CodedStreamTest, VarintSize32PowersOfTwo) { @@ -549,13 +546,13 @@ TEST_F(CodedStreamTest, VarintSize64PowersOfTwo) { // Fixed-size int tests struct Fixed32Case { - uint8 bytes[sizeof(uint32)]; // Encoded bytes. - uint32 value; // Parsed value. + uint8 bytes[sizeof(uint32)]; // Encoded bytes. + uint32 value; // Parsed value. }; struct Fixed64Case { - uint8 bytes[sizeof(uint64)]; // Encoded bytes. - uint64 value; // Parsed value. + uint8 bytes[sizeof(uint64)]; // Encoded bytes. + uint64 value; // Parsed value. }; inline std::ostream& operator<<(std::ostream& os, const Fixed32Case& c) { @@ -567,13 +564,13 @@ inline std::ostream& operator<<(std::ostream& os, const Fixed64Case& c) { } Fixed32Case kFixed32Cases[] = { - {{0xef, 0xcd, 0xab, 0x90}, 0x90abcdefu}, - {{0x12, 0x34, 0x56, 0x78}, 0x78563412u}, + {{0xef, 0xcd, 0xab, 0x90}, 0x90abcdefu}, + {{0x12, 0x34, 0x56, 0x78}, 0x78563412u}, }; Fixed64Case kFixed64Cases[] = { - {{0xef, 0xcd, 0xab, 0x90, 0x12, 0x34, 0x56, 0x78}, ULL(0x7856341290abcdef)}, - {{0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}, ULL(0x8877665544332211)}, + {{0xef, 0xcd, 0xab, 0x90, 0x12, 0x34, 0x56, 0x78}, ULL(0x7856341290abcdef)}, + {{0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}, ULL(0x8877665544332211)}, }; TEST_2D(CodedStreamTest, ReadLittleEndian32, kFixed32Cases, kBlockSizes) { @@ -644,8 +641,8 @@ TEST_1D(CodedStreamTest, ReadLittleEndian32FromArray, kFixed32Cases) { memcpy(buffer_, kFixed32Cases_case.bytes, sizeof(kFixed32Cases_case.bytes)); uint32 value; - const uint8* end = CodedInputStream::ReadLittleEndian32FromArray( - buffer_, &value); + const uint8* end = + CodedInputStream::ReadLittleEndian32FromArray(buffer_, &value); EXPECT_EQ(kFixed32Cases_case.value, value); EXPECT_TRUE(end == buffer_ + sizeof(value)); } @@ -654,8 +651,8 @@ TEST_1D(CodedStreamTest, ReadLittleEndian64FromArray, kFixed64Cases) { memcpy(buffer_, kFixed64Cases_case.bytes, sizeof(kFixed64Cases_case.bytes)); uint64 value; - const uint8* end = CodedInputStream::ReadLittleEndian64FromArray( - buffer_, &value); + const uint8* end = + CodedInputStream::ReadLittleEndian64FromArray(buffer_, &value); EXPECT_EQ(kFixed64Cases_case.value, value); EXPECT_TRUE(end == buffer_ + sizeof(value)); } @@ -703,7 +700,7 @@ TEST_1D(CodedStreamTest, ReadString, kBlockSizes) { { CodedInputStream coded_input(&input); - string str; + std::string str; EXPECT_TRUE(coded_input.ReadString(&str, strlen(kRawBytes))); EXPECT_EQ(kRawBytes, str); } @@ -718,7 +715,7 @@ TEST_1D(CodedStreamTest, ReadStringImpossiblyLarge, kBlockSizes) { { CodedInputStream coded_input(&input); - string str; + std::string str; // Try to read a gigabyte. EXPECT_FALSE(coded_input.ReadString(&str, 1 << 30)); } @@ -729,14 +726,14 @@ TEST_F(CodedStreamTest, ReadStringImpossiblyLargeFromStringOnStack) { // crashes while the above did not. uint8 buffer[8]; CodedInputStream coded_input(buffer, 8); - string str; + std::string str; EXPECT_FALSE(coded_input.ReadString(&str, 1 << 30)); } TEST_F(CodedStreamTest, ReadStringImpossiblyLargeFromStringOnHeap) { std::unique_ptr buffer(new uint8[8]); CodedInputStream coded_input(buffer.get(), 8); - string str; + std::string str; EXPECT_FALSE(coded_input.ReadString(&str, 1 << 30)); } @@ -749,7 +746,7 @@ TEST_1D(CodedStreamTest, ReadStringReservesMemoryOnTotalLimit, kBlockSizes) { coded_input.SetTotalBytesLimit(sizeof(kRawBytes), sizeof(kRawBytes)); EXPECT_EQ(sizeof(kRawBytes), coded_input.BytesUntilTotalBytesLimit()); - string str; + std::string str; EXPECT_TRUE(coded_input.ReadString(&str, strlen(kRawBytes))); EXPECT_EQ(sizeof(kRawBytes) - strlen(kRawBytes), coded_input.BytesUntilTotalBytesLimit()); @@ -769,7 +766,7 @@ TEST_1D(CodedStreamTest, ReadStringReservesMemoryOnPushedLimit, kBlockSizes) { CodedInputStream coded_input(&input); coded_input.PushLimit(sizeof(buffer_)); - string str; + std::string str; EXPECT_TRUE(coded_input.ReadString(&str, strlen(kRawBytes))); EXPECT_EQ(kRawBytes, str); // TODO(liujisi): Replace with a more meaningful test (see cl/60966023). @@ -789,7 +786,7 @@ TEST_F(CodedStreamTest, ReadStringNoReservationIfLimitsNotSet) { { CodedInputStream coded_input(&input); - string str; + std::string str; EXPECT_TRUE(coded_input.ReadString(&str, strlen(kRawBytes))); EXPECT_EQ(kRawBytes, str); // Note: this check depends on string class implementation. It @@ -814,12 +811,12 @@ TEST_F(CodedStreamTest, ReadStringNoReservationSizeIsNegative) { CodedInputStream coded_input(&input); coded_input.PushLimit(sizeof(buffer_)); - string str; + std::string str; EXPECT_FALSE(coded_input.ReadString(&str, -1)); // Note: this check depends on string class implementation. It // expects that string will always allocate the same amount of // memory for an empty string. - EXPECT_EQ(string().capacity(), str.capacity()); + EXPECT_EQ(std::string().capacity(), str.capacity()); } } @@ -834,7 +831,7 @@ TEST_F(CodedStreamTest, ReadStringNoReservationSizeIsLarge) { CodedInputStream coded_input(&input); coded_input.PushLimit(sizeof(buffer_)); - string str; + std::string str; EXPECT_FALSE(coded_input.ReadString(&str, 1 << 30)); EXPECT_GT(1 << 30, str.capacity()); } @@ -851,7 +848,7 @@ TEST_F(CodedStreamTest, ReadStringNoReservationSizeIsOverTheLimit) { CodedInputStream coded_input(&input); coded_input.PushLimit(16); - string str; + std::string str; EXPECT_FALSE(coded_input.ReadString(&str, strlen(kRawBytes))); // Note: this check depends on string class implementation. It // expects that string will allocate less than strlen(kRawBytes) @@ -871,7 +868,7 @@ TEST_F(CodedStreamTest, ReadStringNoReservationSizeIsOverTheTotalBytesLimit) { CodedInputStream coded_input(&input); coded_input.SetTotalBytesLimit(16, 16); - string str; + std::string str; EXPECT_FALSE(coded_input.ReadString(&str, strlen(kRawBytes))); // Note: this check depends on string class implementation. It // expects that string will allocate less than strlen(kRawBytes) @@ -893,7 +890,7 @@ TEST_F(CodedStreamTest, coded_input.PushLimit(sizeof(buffer_)); coded_input.SetTotalBytesLimit(16, 16); - string str; + std::string str; EXPECT_FALSE(coded_input.ReadString(&str, strlen(kRawBytes))); // Note: this check depends on string class implementation. It // expects that string will allocate less than strlen(kRawBytes) @@ -916,7 +913,7 @@ TEST_F(CodedStreamTest, coded_input.SetTotalBytesLimit(sizeof(buffer_), sizeof(buffer_)); EXPECT_EQ(sizeof(buffer_), coded_input.BytesUntilTotalBytesLimit()); - string str; + std::string str; EXPECT_FALSE(coded_input.ReadString(&str, strlen(kRawBytes))); // Note: this check depends on string class implementation. It // expects that string will allocate less than strlen(kRawBytes) @@ -930,7 +927,7 @@ TEST_F(CodedStreamTest, // Skip const char kSkipTestBytes[] = - ""; + ""; TEST_1D(CodedStreamTest, SkipInput, kBlockSizes) { memcpy(buffer_, kSkipTestBytes, sizeof(kSkipTestBytes)); @@ -939,7 +936,7 @@ TEST_1D(CodedStreamTest, SkipInput, kBlockSizes) { { CodedInputStream coded_input(&input); - string str; + std::string str; EXPECT_TRUE(coded_input.ReadString(&str, strlen(""))); EXPECT_EQ("", str); EXPECT_TRUE(coded_input.Skip(strlen(""))); @@ -1223,11 +1220,11 @@ TEST_F(CodedStreamTest, TotalBytesLimit) { coded_input.SetTotalBytesLimit(16, -1); EXPECT_EQ(16, coded_input.BytesUntilTotalBytesLimit()); - string str; + std::string str; EXPECT_TRUE(coded_input.ReadString(&str, 16)); EXPECT_EQ(0, coded_input.BytesUntilTotalBytesLimit()); - std::vector errors; + std::vector errors; { ScopedMemoryLog error_log; @@ -1237,7 +1234,8 @@ TEST_F(CodedStreamTest, TotalBytesLimit) { ASSERT_EQ(1, errors.size()); EXPECT_PRED_FORMAT2(testing::IsSubstring, - "A protocol message was rejected because it was too big", errors[0]); + "A protocol message was rejected because it was too big", + errors[0]); coded_input.SetTotalBytesLimit(32, -1); EXPECT_EQ(16, coded_input.BytesUntilTotalBytesLimit()); @@ -1256,7 +1254,7 @@ TEST_F(CodedStreamTest, TotalBytesLimitNotValidMessageEnd) { CodedInputStream::Limit limit = coded_input.PushLimit(16); // Read 16 bytes. - string str; + std::string str; EXPECT_TRUE(coded_input.ReadString(&str, 16)); // Read a tag. Should fail, but report being a valid endpoint since it's @@ -1273,62 +1271,41 @@ TEST_F(CodedStreamTest, TotalBytesLimitNotValidMessageEnd) { EXPECT_FALSE(coded_input.ConsumedEntireMessage()); } -// This method is used by the tests below. -// It constructs a CodedInputStream with the given limits and tries to read 2KiB -// of data from it. Then it returns the logged errors and warnings in the given -// vectors. -void CodedStreamTest::SetupTotalBytesLimitWarningTest( - int total_bytes_limit, int warning_threshold, - std::vector* out_errors, std::vector* out_warnings) { - ArrayInputStream raw_input(buffer_, sizeof(buffer_), 128); - - ScopedMemoryLog scoped_log; - { - CodedInputStream input(&raw_input); - input.SetTotalBytesLimit(total_bytes_limit, warning_threshold); - string str; - EXPECT_TRUE(input.ReadString(&str, 2048)); - } - - *out_errors = scoped_log.GetMessages(ERROR); - *out_warnings = scoped_log.GetMessages(WARNING); -} - TEST_F(CodedStreamTest, RecursionLimit) { ArrayInputStream input(buffer_, sizeof(buffer_)); CodedInputStream coded_input(&input); coded_input.SetRecursionLimit(4); // This is way too much testing for a counter. - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 1 - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 2 - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 3 - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 4 - EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 5 - EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 6 - coded_input.DecrementRecursionDepth(); // 5 - EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 6 - coded_input.DecrementRecursionDepth(); // 5 - coded_input.DecrementRecursionDepth(); // 4 - coded_input.DecrementRecursionDepth(); // 3 - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 4 - EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 5 - coded_input.DecrementRecursionDepth(); // 4 - coded_input.DecrementRecursionDepth(); // 3 - coded_input.DecrementRecursionDepth(); // 2 - coded_input.DecrementRecursionDepth(); // 1 - coded_input.DecrementRecursionDepth(); // 0 - coded_input.DecrementRecursionDepth(); // 0 - coded_input.DecrementRecursionDepth(); // 0 - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 1 - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 2 - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 3 - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 4 - EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 5 + EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 1 + EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 2 + EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 3 + EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 4 + EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 5 + EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 6 + coded_input.DecrementRecursionDepth(); // 5 + EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 6 + coded_input.DecrementRecursionDepth(); // 5 + coded_input.DecrementRecursionDepth(); // 4 + coded_input.DecrementRecursionDepth(); // 3 + EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 4 + EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 5 + coded_input.DecrementRecursionDepth(); // 4 + coded_input.DecrementRecursionDepth(); // 3 + coded_input.DecrementRecursionDepth(); // 2 + coded_input.DecrementRecursionDepth(); // 1 + coded_input.DecrementRecursionDepth(); // 0 + coded_input.DecrementRecursionDepth(); // 0 + coded_input.DecrementRecursionDepth(); // 0 + EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 1 + EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 2 + EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 3 + EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 4 + EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 5 coded_input.SetRecursionLimit(6); - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 6 - EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 7 + EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 6 + EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 7 } @@ -1360,12 +1337,16 @@ class ReallyBigInputStream : public ZeroCopyInputStream { } } - void BackUp(int count) { - backup_amount_ = count; - } + void BackUp(int count) { backup_amount_ = count; } - bool Skip(int count) { GOOGLE_LOG(FATAL) << "Not implemented."; return false; } - int64 ByteCount() const { GOOGLE_LOG(FATAL) << "Not implemented."; return 0; } + bool Skip(int count) { + GOOGLE_LOG(FATAL) << "Not implemented."; + return false; + } + int64 ByteCount() const { + GOOGLE_LOG(FATAL) << "Not implemented."; + return 0; + } int backup_amount_; @@ -1379,12 +1360,12 @@ TEST_F(CodedStreamTest, InputOver2G) { // input.BackUp() with the correct number of bytes on destruction. ReallyBigInputStream input; - std::vector errors; + std::vector errors; { ScopedMemoryLog error_log; CodedInputStream coded_input(&input); - string str; + std::string str; EXPECT_TRUE(coded_input.ReadString(&str, 512)); EXPECT_TRUE(coded_input.ReadString(&str, 1024)); errors = error_log.GetMessages(ERROR); diff --git a/third_party/protobuf/src/google/protobuf/io/gzip_stream.cc b/third_party/protobuf/src/google/protobuf/io/gzip_stream.cc index a569eff0..a3e04384 100644 --- a/third_party/protobuf/src/google/protobuf/io/gzip_stream.cc +++ b/third_party/protobuf/src/google/protobuf/io/gzip_stream.cc @@ -46,8 +46,8 @@ namespace io { static const int kDefaultBufferSize = 65536; -GzipInputStream::GzipInputStream( - ZeroCopyInputStream* sub_stream, Format format, int buffer_size) +GzipInputStream::GzipInputStream(ZeroCopyInputStream* sub_stream, Format format, + int buffer_size) : format_(format), sub_stream_(sub_stream), zerror_(Z_OK), byte_count_(0) { zcontext_.state = Z_NULL; zcontext_.zalloc = Z_NULL; @@ -74,15 +74,21 @@ GzipInputStream::~GzipInputStream() { zerror_ = inflateEnd(&zcontext_); } -static inline int internalInflateInit2( - z_stream* zcontext, GzipInputStream::Format format) { +static inline int internalInflateInit2(z_stream* zcontext, + GzipInputStream::Format format) { int windowBitsFormat = 0; switch (format) { - case GzipInputStream::GZIP: windowBitsFormat = 16; break; - case GzipInputStream::AUTO: windowBitsFormat = 32; break; - case GzipInputStream::ZLIB: windowBitsFormat = 0; break; + case GzipInputStream::GZIP: + windowBitsFormat = 16; + break; + case GzipInputStream::AUTO: + windowBitsFormat = 32; + break; + case GzipInputStream::ZLIB: + windowBitsFormat = 0; + break; } - return inflateInit2(zcontext, /* windowBits */15 | windowBitsFormat); + return inflateInit2(zcontext, /* windowBits */ 15 | windowBitsFormat); } int GzipInputStream::Inflate(int flush) { @@ -122,8 +128,8 @@ void GzipInputStream::DoNextOutput(const void** data, int* size) { // implements ZeroCopyInputStream ---------------------------------- bool GzipInputStream::Next(const void** data, int* size) { - bool ok = (zerror_ == Z_OK) || (zerror_ == Z_STREAM_END) - || (zerror_ == Z_BUF_ERROR); + bool ok = (zerror_ == Z_OK) || (zerror_ == Z_STREAM_END) || + (zerror_ == Z_BUF_ERROR); if ((!ok) || (zcontext_.next_out == NULL)) { return false; } @@ -154,8 +160,8 @@ bool GzipInputStream::Next(const void** data, int* size) { // The underlying stream's Next returned false inside Inflate. return false; } - ok = (zerror_ == Z_OK) || (zerror_ == Z_STREAM_END) - || (zerror_ == Z_BUF_ERROR); + ok = (zerror_ == Z_OK) || (zerror_ == Z_STREAM_END) || + (zerror_ == Z_BUF_ERROR); if (!ok) { return false; } @@ -230,13 +236,10 @@ void GzipOutputStream::Init(ZeroCopyOutputStream* sub_stream, if (options.format == ZLIB) { windowBitsFormat = 0; } - zerror_ = deflateInit2( - &zcontext_, - options.compression_level, - Z_DEFLATED, - /* windowBits */15 | windowBitsFormat, - /* memLevel (default) */8, - options.compression_strategy); + zerror_ = + deflateInit2(&zcontext_, options.compression_level, Z_DEFLATED, + /* windowBits */ 15 | windowBitsFormat, + /* memLevel (default) */ 8, options.compression_strategy); } GzipOutputStream::~GzipOutputStream() { @@ -305,9 +308,9 @@ int64 GzipOutputStream::ByteCount() const { bool GzipOutputStream::Flush() { zerror_ = Deflate(Z_FULL_FLUSH); // Return true if the flush succeeded or if it was a no-op. - return (zerror_ == Z_OK) || - (zerror_ == Z_BUF_ERROR && zcontext_.avail_in == 0 && - zcontext_.avail_out != 0); + return (zerror_ == Z_OK) || + (zerror_ == Z_BUF_ERROR && zcontext_.avail_in == 0 && + zcontext_.avail_out != 0); } bool GzipOutputStream::Close() { diff --git a/third_party/protobuf/src/google/protobuf/io/gzip_stream.h b/third_party/protobuf/src/google/protobuf/io/gzip_stream.h index 15b02fe3..9980e5b4 100644 --- a/third_party/protobuf/src/google/protobuf/io/gzip_stream.h +++ b/third_party/protobuf/src/google/protobuf/io/gzip_stream.h @@ -45,14 +45,17 @@ #include #include +#include #include +#include + namespace google { namespace protobuf { namespace io { // A ZeroCopyInputStream that reads compressed data through zlib -class LIBPROTOBUF_EXPORT GzipInputStream : public ZeroCopyInputStream { +class PROTOBUF_EXPORT GzipInputStream : public ZeroCopyInputStream { public: // Format key for constructor enum Format { @@ -67,19 +70,13 @@ class LIBPROTOBUF_EXPORT GzipInputStream : public ZeroCopyInputStream { }; // buffer_size and format may be -1 for default of 64kB and GZIP format - explicit GzipInputStream( - ZeroCopyInputStream* sub_stream, - Format format = AUTO, - int buffer_size = -1); + explicit GzipInputStream(ZeroCopyInputStream* sub_stream, + Format format = AUTO, int buffer_size = -1); virtual ~GzipInputStream(); // Return last error message or NULL if no error. - inline const char* ZlibErrorMessage() const { - return zcontext_.msg; - } - inline int ZlibErrorCode() const { - return zerror_; - } + inline const char* ZlibErrorMessage() const { return zcontext_.msg; } + inline int ZlibErrorCode() const { return zerror_; } // implements ZeroCopyInputStream ---------------------------------- bool Next(const void** data, int* size); @@ -106,8 +103,7 @@ class LIBPROTOBUF_EXPORT GzipInputStream : public ZeroCopyInputStream { GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(GzipInputStream); }; - -class LIBPROTOBUF_EXPORT GzipOutputStream : public ZeroCopyOutputStream { +class PROTOBUF_EXPORT GzipOutputStream : public ZeroCopyOutputStream { public: // Format key for constructor enum Format { @@ -118,7 +114,7 @@ class LIBPROTOBUF_EXPORT GzipOutputStream : public ZeroCopyOutputStream { ZLIB = 2, }; - struct Options { + struct PROTOBUF_EXPORT Options { // Defaults to GZIP. Format format; @@ -141,19 +137,13 @@ class LIBPROTOBUF_EXPORT GzipOutputStream : public ZeroCopyOutputStream { explicit GzipOutputStream(ZeroCopyOutputStream* sub_stream); // Create a GzipOutputStream with the given options. - GzipOutputStream( - ZeroCopyOutputStream* sub_stream, - const Options& options); + GzipOutputStream(ZeroCopyOutputStream* sub_stream, const Options& options); virtual ~GzipOutputStream(); // Return last error message or NULL if no error. - inline const char* ZlibErrorMessage() const { - return zcontext_.msg; - } - inline int ZlibErrorCode() const { - return zerror_; - } + inline const char* ZlibErrorMessage() const { return zcontext_.msg; } + inline int ZlibErrorCode() const { return zerror_; } // Flushes data written so far to zipped data in the underlying stream. // It is the caller's responsibility to flush the underlying stream if @@ -204,6 +194,8 @@ class LIBPROTOBUF_EXPORT GzipOutputStream : public ZeroCopyOutputStream { } // namespace io } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_IO_GZIP_STREAM_H__ diff --git a/third_party/protobuf/src/google/protobuf/stubs/io_win32.cc b/third_party/protobuf/src/google/protobuf/io/io_win32.cc old mode 100644 new mode 100755 similarity index 94% rename from third_party/protobuf/src/google/protobuf/stubs/io_win32.cc rename to third_party/protobuf/src/google/protobuf/io/io_win32.cc index 4407facb..b8f9bf8f --- a/third_party/protobuf/src/google/protobuf/stubs/io_win32.cc +++ b/third_party/protobuf/src/google/protobuf/io/io_win32.cc @@ -29,7 +29,9 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: laszlocsomor@google.com (Laszlo Csomor) -// +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + // Implementation for long-path-aware open/mkdir/access/etc. on Windows, as well // as for the supporting utility functions. // @@ -58,7 +60,7 @@ #include #include -#include +#include #include #include @@ -67,7 +69,7 @@ namespace google { namespace protobuf { -namespace internal { +namespace io { namespace win32 { namespace { @@ -91,7 +93,7 @@ struct CharTraits { template bool null_or_empty(const char_type* s) { - return s == NULL || *s == 0; + return s == nullptr || *s == 0; } // Returns true if the path starts with a drive letter, e.g. "c:". @@ -225,7 +227,7 @@ bool as_windows_path(const char* path, wstring* result) { if (!is_path_absolute(wpath.c_str())) { - int size = ::GetCurrentDirectoryW(0, NULL); + int size = ::GetCurrentDirectoryW(0, nullptr); if (size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) { return false; } @@ -316,17 +318,17 @@ FILE* fopen(const char* path, const char* mode) { #ifdef SUPPORT_LONGPATHS if (null_or_empty(path)) { errno = EINVAL; - return NULL; + return nullptr; } wstring wpath; if (!as_windows_path(path, &wpath)) { errno = ENOENT; - return NULL; + return nullptr; } wstring wmode; if (!strings::utf8_to_wcs(mode, &wmode)) { errno = EINVAL; - return NULL; + return nullptr; } return ::_wfopen(wpath.c_str(), wmode.c_str()); #else @@ -334,7 +336,7 @@ FILE* fopen(const char* path, const char* mode) { #endif } -int close(int fd) { return ::close(fd); } +int close(int fd) { return ::_close(fd); } int dup(int fd) { return ::_dup(fd); } @@ -365,15 +367,15 @@ bool wcs_to_mbs(const WCHAR* s, string* out, bool outUtf8) { BOOL usedDefaultChar = FALSE; SetLastError(0); int size = WideCharToMultiByte( - outUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, NULL, 0, NULL, - outUtf8 ? NULL : &usedDefaultChar); + outUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, nullptr, 0, nullptr, + outUtf8 ? nullptr : &usedDefaultChar); if ((size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) || usedDefaultChar) { return false; } std::unique_ptr astr(new CHAR[size]); WideCharToMultiByte( - outUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, astr.get(), size, NULL, NULL); + outUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, astr.get(), size, nullptr, nullptr); out->assign(astr.get()); return true; } @@ -386,7 +388,7 @@ bool mbs_to_wcs(const char* s, wstring* out, bool inUtf8) { SetLastError(0); int size = - MultiByteToWideChar(inUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, NULL, 0); + MultiByteToWideChar(inUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, nullptr, 0); if (size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) { return false; } @@ -407,7 +409,7 @@ bool wcs_to_utf8(const wchar_t* input, string* out) { } // namespace strings } // namespace win32 -} // namespace internal +} // namespace io } // namespace protobuf } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/stubs/io_win32.h b/third_party/protobuf/src/google/protobuf/io/io_win32.h old mode 100644 new mode 100755 similarity index 68% rename from third_party/protobuf/src/google/protobuf/stubs/io_win32.h rename to third_party/protobuf/src/google/protobuf/io/io_win32.h index 9e17d253..cf5cb326 --- a/third_party/protobuf/src/google/protobuf/stubs/io_win32.h +++ b/third_party/protobuf/src/google/protobuf/io/io_win32.h @@ -29,68 +29,71 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: laszlocsomor@google.com (Laszlo Csomor) -// +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + // This file contains the declarations for Windows implementations of // commonly used POSIX functions such as open(2) and access(2), as well // as macro definitions for flags of these functions. // // By including this file you'll redefine open/access/etc. to -// ::google::protobuf::internal::win32::{open/access/etc.}. +// ::google::protobuf::io::win32::{open/access/etc.}. // Make sure you don't include a header that attempts to redeclare or // redefine these functions, that'll lead to confusing compilation // errors. It's best to #include this file as the last one to ensure that. // // This file is only used on Windows, it's empty on other platforms. -#ifndef GOOGLE_PROTOBUF_STUBS_IO_WIN32_H__ -#define GOOGLE_PROTOBUF_STUBS_IO_WIN32_H__ +#ifndef GOOGLE_PROTOBUF_IO_IO_WIN32_H__ +#define GOOGLE_PROTOBUF_IO_IO_WIN32_H__ #if defined(_WIN32) #include -#include +#include + +#include // Compilers on Windows other than MSVC (e.g. Cygwin, MinGW32) define the // following functions already, except for mkdir. namespace google { namespace protobuf { -namespace internal { +namespace io { namespace win32 { -LIBPROTOBUF_EXPORT FILE* fopen(const char* path, const char* mode); -LIBPROTOBUF_EXPORT int access(const char* path, int mode); -LIBPROTOBUF_EXPORT int chdir(const char* path); -LIBPROTOBUF_EXPORT int close(int fd); -LIBPROTOBUF_EXPORT int dup(int fd); -LIBPROTOBUF_EXPORT int dup2(int fd1, int fd2); -LIBPROTOBUF_EXPORT int mkdir(const char* path, int _mode); -LIBPROTOBUF_EXPORT int open(const char* path, int flags, int mode = 0); -LIBPROTOBUF_EXPORT int read(int fd, void* buffer, size_t size); -LIBPROTOBUF_EXPORT int setmode(int fd, int mode); -LIBPROTOBUF_EXPORT int stat(const char* path, struct _stat* buffer); -LIBPROTOBUF_EXPORT int write(int fd, const void* buffer, size_t size); -LIBPROTOBUF_EXPORT std::wstring testonly_utf8_to_winpath(const char* path); +PROTOBUF_EXPORT FILE* fopen(const char* path, const char* mode); +PROTOBUF_EXPORT int access(const char* path, int mode); +PROTOBUF_EXPORT int chdir(const char* path); +PROTOBUF_EXPORT int close(int fd); +PROTOBUF_EXPORT int dup(int fd); +PROTOBUF_EXPORT int dup2(int fd1, int fd2); +PROTOBUF_EXPORT int mkdir(const char* path, int _mode); +PROTOBUF_EXPORT int open(const char* path, int flags, int mode = 0); +PROTOBUF_EXPORT int read(int fd, void* buffer, size_t size); +PROTOBUF_EXPORT int setmode(int fd, int mode); +PROTOBUF_EXPORT int stat(const char* path, struct _stat* buffer); +PROTOBUF_EXPORT int write(int fd, const void* buffer, size_t size); +PROTOBUF_EXPORT std::wstring testonly_utf8_to_winpath(const char* path); namespace strings { // Convert from UTF-16 to Active-Code-Page-encoded or to UTF-8-encoded text. -LIBPROTOBUF_EXPORT bool wcs_to_mbs( - const wchar_t* s, std::string* out, bool outUtf8); +PROTOBUF_EXPORT bool wcs_to_mbs(const wchar_t* s, std::string* out, + bool outUtf8); // Convert from Active-Code-Page-encoded or UTF-8-encoded text to UTF-16. -LIBPROTOBUF_EXPORT bool mbs_to_wcs( - const char* s, std::wstring* out, bool inUtf8); +PROTOBUF_EXPORT bool mbs_to_wcs(const char* s, std::wstring* out, bool inUtf8); // Convert from UTF-8-encoded text to UTF-16. -LIBPROTOBUF_EXPORT bool utf8_to_wcs(const char* input, std::wstring* out); +PROTOBUF_EXPORT bool utf8_to_wcs(const char* input, std::wstring* out); // Convert from UTF-16-encoded text to UTF-8. -LIBPROTOBUF_EXPORT bool wcs_to_utf8(const wchar_t* input, std::string* out); +PROTOBUF_EXPORT bool wcs_to_utf8(const wchar_t* input, std::string* out); } // namespace strings } // namespace win32 -} // namespace internal +} // namespace io } // namespace protobuf } // namespace google @@ -110,6 +113,8 @@ LIBPROTOBUF_EXPORT bool wcs_to_utf8(const wchar_t* input, std::string* out); #define STDOUT_FILENO 1 #endif +#include + #endif // defined(_WIN32) -#endif // GOOGLE_PROTOBUF_STUBS_IO_WIN32_H__ +#endif // GOOGLE_PROTOBUF_IO_IO_WIN32_H__ diff --git a/third_party/protobuf/src/google/protobuf/stubs/io_win32_unittest.cc b/third_party/protobuf/src/google/protobuf/io/io_win32_unittest.cc old mode 100644 new mode 100755 similarity index 94% rename from third_party/protobuf/src/google/protobuf/stubs/io_win32_unittest.cc rename to third_party/protobuf/src/google/protobuf/io/io_win32_unittest.cc index c933757c..53aa3339 --- a/third_party/protobuf/src/google/protobuf/stubs/io_win32_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/io/io_win32_unittest.cc @@ -29,7 +29,9 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: laszlocsomor@google.com (Laszlo Csomor) -// +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + // Unit tests for long-path-aware open/mkdir/access/etc. on Windows, as well as // for the supporting utility functions. // @@ -47,7 +49,7 @@ #include #include -#include +#include #include #include @@ -56,24 +58,24 @@ namespace google { namespace protobuf { -namespace internal { +namespace io { namespace win32 { namespace { const char kUtf8Text[] = { 'h', 'i', ' ', // utf-8: 11010000 10011111, utf-16: 100 0001 1111 = 0x041F - 0xd0, 0x9f, + static_cast(0xd0), static_cast(0x9f), // utf-8: 11010001 10000000, utf-16: 100 0100 0000 = 0x0440 - 0xd1, 0x80, + static_cast(0xd1), static_cast(0x80), // utf-8: 11010000 10111000, utf-16: 100 0011 1000 = 0x0438 - 0xd0, 0xb8, + static_cast(0xd0), static_cast(0xb8), // utf-8: 11010000 10110010, utf-16: 100 0011 0010 = 0x0432 - 0xd0, 0xb2, + static_cast(0xd0), static_cast(0xb2), // utf-8: 11010000 10110101, utf-16: 100 0011 0101 = 0x0435 - 0xd0, 0xb5, + static_cast(0xd0), static_cast(0xb5), // utf-8: 11010001 10000010, utf-16: 100 0100 0010 = 0x0442 - 0xd1, 0x82, 0 + static_cast(0xd1), static_cast(0x82), 0 }; const wchar_t kUtf16Text[] = { @@ -112,7 +114,7 @@ void StripTrailingSlashes(string* str) { } bool GetEnvVarAsUtf8(const WCHAR* name, string* result) { - DWORD size = ::GetEnvironmentVariableW(name, NULL, 0); + DWORD size = ::GetEnvironmentVariableW(name, nullptr, 0); if (size > 0 && GetLastError() != ERROR_ENVVAR_NOT_FOUND) { std::unique_ptr wcs(new WCHAR[size]); ::GetEnvironmentVariableW(name, wcs.get(), size); @@ -128,7 +130,7 @@ bool GetEnvVarAsUtf8(const WCHAR* name, string* result) { } bool GetCwdAsUtf8(string* result) { - DWORD size = ::GetCurrentDirectoryW(0, NULL); + DWORD size = ::GetCurrentDirectoryW(0, nullptr); if (size > 0) { std::unique_ptr wcs(new WCHAR[size]); ::GetCurrentDirectoryW(size, wcs.get()); @@ -201,7 +203,7 @@ bool IoWin32Test::CreateAllUnder(wstring path) { if (path.find(L"\\\\?\\") != 0) { path = wstring(L"\\\\?\\") + path; } - if (::CreateDirectoryW(path.c_str(), NULL) || + if (::CreateDirectoryW(path.c_str(), nullptr) || GetLastError() == ERROR_ALREADY_EXISTS || GetLastError() == ERROR_ACCESS_DENIED) { return true; @@ -210,7 +212,7 @@ bool IoWin32Test::CreateAllUnder(wstring path) { size_t pos = path.find_last_of(L'\\'); if (pos != wstring::npos) { wstring parent(path, 0, pos); - if (CreateAllUnder(parent) && CreateDirectoryW(path.c_str(), NULL)) { + if (CreateAllUnder(parent) && CreateDirectoryW(path.c_str(), nullptr)) { return true; } } @@ -352,8 +354,8 @@ TEST_F(IoWin32Test, MkdirTestNonAscii) { // Create a non-ASCII path. // Ensure that we can create the directory using SetCurrentDirectoryW. - EXPECT_TRUE(CreateDirectoryW((wtest_tmpdir + L"\\1").c_str(), NULL)); - EXPECT_TRUE(CreateDirectoryW((wtest_tmpdir + L"\\1\\" + kUtf16Text).c_str(), NULL)); + EXPECT_TRUE(CreateDirectoryW((wtest_tmpdir + L"\\1").c_str(), nullptr)); + EXPECT_TRUE(CreateDirectoryW((wtest_tmpdir + L"\\1\\" + kUtf16Text).c_str(), nullptr)); // Ensure that we can create a very similarly named directory using mkdir. // We don't attemp to delete and recreate the same directory, because on // Windows, deleting files and directories seems to be asynchronous. @@ -386,7 +388,7 @@ TEST_F(IoWin32Test, ChdirTestNonAscii) { wstring wNonAscii(wtest_tmpdir + L"\\" + kUtf16Text); string nonAscii; EXPECT_TRUE(strings::wcs_to_utf8(wNonAscii.c_str(), &nonAscii)); - EXPECT_TRUE(CreateDirectoryW(wNonAscii.c_str(), NULL)); + EXPECT_TRUE(CreateDirectoryW(wNonAscii.c_str(), nullptr)); WCHAR cwd[MAX_PATH]; EXPECT_TRUE(GetCurrentDirectoryW(MAX_PATH, cwd)); // Ensure that we can cd into the path using SetCurrentDirectoryW. @@ -400,7 +402,7 @@ TEST_F(IoWin32Test, ChdirTestNonAscii) { } TEST_F(IoWin32Test, AsWindowsPathTest) { - DWORD size = GetCurrentDirectoryW(0, NULL); + DWORD size = GetCurrentDirectoryW(0, nullptr); std::unique_ptr cwd_str(new wchar_t[size]); EXPECT_GT(GetCurrentDirectoryW(size, cwd_str.get()), 0); wstring cwd = wstring(L"\\\\?\\") + cwd_str.get(); @@ -444,7 +446,7 @@ TEST_F(IoWin32Test, Utf8Utf16ConversionTest) { } // namespace } // namespace win32 -} // namespace internal +} // namespace io } // namespace protobuf } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/io/package_info.h b/third_party/protobuf/src/google/protobuf/io/package_info.h index dc1fc91e..46c3dac9 100644 --- a/third_party/protobuf/src/google/protobuf/io/package_info.h +++ b/third_party/protobuf/src/google/protobuf/io/package_info.h @@ -37,7 +37,6 @@ // documentation generator. namespace google { - namespace protobuf { // Auxiliary classes used for I/O. diff --git a/third_party/protobuf/src/google/protobuf/io/printer.cc b/third_party/protobuf/src/google/protobuf/io/printer.cc index de67cef1..6a86c58c 100644 --- a/third_party/protobuf/src/google/protobuf/io/printer.cc +++ b/third_party/protobuf/src/google/protobuf/io/printer.cc @@ -32,10 +32,12 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include -#include +#include + #include #include +#include +#include namespace google { namespace protobuf { @@ -71,7 +73,7 @@ Printer::~Printer() { bool Printer::GetSubstitutionRange(const char* varname, std::pair* range) { - std::map >::const_iterator iter = + std::map >::const_iterator iter = substitutions_.find(varname); if (iter == substitutions_.end()) { GOOGLE_LOG(DFATAL) << " Undefined variable in annotation: " << varname; @@ -87,7 +89,8 @@ bool Printer::GetSubstitutionRange(const char* varname, } void Printer::Annotate(const char* begin_varname, const char* end_varname, - const string& file_path, const std::vector& path) { + const std::string& file_path, + const std::vector& path) { if (annotation_collector_ == NULL) { // Can't generate signatures with this Printer. return; @@ -106,7 +109,7 @@ void Printer::Annotate(const char* begin_varname, const char* end_varname, } } -void Printer::Print(const std::map& variables, +void Printer::Print(const std::map& variables, const char* text) { int size = strlen(text); int pos = 0; // The number of bytes we've written so far. @@ -140,13 +143,14 @@ void Printer::Print(const std::map& variables, } int endpos = end - text; - string varname(text + pos, endpos - pos); + std::string varname(text + pos, endpos - pos); if (varname.empty()) { // Two delimiters in a row reduce to a literal delimiter character. WriteRaw(&variable_delimiter_, 1); } else { // Replace with the variable's value. - std::map::const_iterator iter = variables.find(varname); + std::map::const_iterator iter = + variables.find(varname); if (iter == variables.end()) { GOOGLE_LOG(DFATAL) << " Undefined variable: " << varname; } else { @@ -154,7 +158,7 @@ void Printer::Print(const std::map& variables, line_start_variables_.push_back(varname); } WriteRaw(iter->second.data(), iter->second.size()); - std::pair >::iterator, + std::pair >::iterator, bool> inserted = substitutions_.insert(std::make_pair( varname, @@ -178,126 +182,7 @@ void Printer::Print(const std::map& variables, WriteRaw(text + pos, size - pos); } -void Printer::Print(const char* text) { - static std::map empty; - Print(empty, text); -} - -void Printer::Print(const char* text, - const char* variable, const string& value) { - std::map vars; - vars[variable] = value; - Print(vars, text); -} - -void Printer::Print(const char* text, - const char* variable1, const string& value1, - const char* variable2, const string& value2) { - std::map vars; - vars[variable1] = value1; - vars[variable2] = value2; - Print(vars, text); -} - -void Printer::Print(const char* text, - const char* variable1, const string& value1, - const char* variable2, const string& value2, - const char* variable3, const string& value3) { - std::map vars; - vars[variable1] = value1; - vars[variable2] = value2; - vars[variable3] = value3; - Print(vars, text); -} - -void Printer::Print(const char* text, - const char* variable1, const string& value1, - const char* variable2, const string& value2, - const char* variable3, const string& value3, - const char* variable4, const string& value4) { - std::map vars; - vars[variable1] = value1; - vars[variable2] = value2; - vars[variable3] = value3; - vars[variable4] = value4; - Print(vars, text); -} - -void Printer::Print(const char* text, - const char* variable1, const string& value1, - const char* variable2, const string& value2, - const char* variable3, const string& value3, - const char* variable4, const string& value4, - const char* variable5, const string& value5) { - std::map vars; - vars[variable1] = value1; - vars[variable2] = value2; - vars[variable3] = value3; - vars[variable4] = value4; - vars[variable5] = value5; - Print(vars, text); -} - -void Printer::Print(const char* text, - const char* variable1, const string& value1, - const char* variable2, const string& value2, - const char* variable3, const string& value3, - const char* variable4, const string& value4, - const char* variable5, const string& value5, - const char* variable6, const string& value6) { - std::map vars; - vars[variable1] = value1; - vars[variable2] = value2; - vars[variable3] = value3; - vars[variable4] = value4; - vars[variable5] = value5; - vars[variable6] = value6; - Print(vars, text); -} - -void Printer::Print(const char* text, - const char* variable1, const string& value1, - const char* variable2, const string& value2, - const char* variable3, const string& value3, - const char* variable4, const string& value4, - const char* variable5, const string& value5, - const char* variable6, const string& value6, - const char* variable7, const string& value7) { - std::map vars; - vars[variable1] = value1; - vars[variable2] = value2; - vars[variable3] = value3; - vars[variable4] = value4; - vars[variable5] = value5; - vars[variable6] = value6; - vars[variable7] = value7; - Print(vars, text); -} - -void Printer::Print(const char* text, - const char* variable1, const string& value1, - const char* variable2, const string& value2, - const char* variable3, const string& value3, - const char* variable4, const string& value4, - const char* variable5, const string& value5, - const char* variable6, const string& value6, - const char* variable7, const string& value7, - const char* variable8, const string& value8) { - std::map vars; - vars[variable1] = value1; - vars[variable2] = value2; - vars[variable3] = value3; - vars[variable4] = value4; - vars[variable5] = value5; - vars[variable6] = value6; - vars[variable7] = value7; - vars[variable8] = value8; - Print(vars, text); -} - -void Printer::Indent() { - indent_ += " "; -} +void Printer::Indent() { indent_ += " "; } void Printer::Outdent() { if (indent_.empty()) { @@ -308,7 +193,7 @@ void Printer::Outdent() { indent_.resize(indent_.size() - 2); } -void Printer::PrintRaw(const string& data) { +void Printer::PrintRaw(const std::string& data) { WriteRaw(data.data(), data.size()); } @@ -328,7 +213,7 @@ void Printer::WriteRaw(const char* data, int size) { if (failed_) return; // Fix up empty variables (e.g., "{") that should be annotated as // coming after the indent. - for (std::vector::iterator i = line_start_variables_.begin(); + for (std::vector::iterator i = line_start_variables_.begin(); i != line_start_variables_.end(); ++i) { substitutions_[*i].first += indent_.size(); substitutions_[*i].second += indent_.size(); @@ -343,6 +228,18 @@ void Printer::WriteRaw(const char* data, int size) { CopyToBuffer(data, size); } +bool Printer::Next() { + do { + void* void_buffer; + if (!output_->Next(&void_buffer, &buffer_size_)) { + failed_ = true; + return false; + } + buffer_ = reinterpret_cast(void_buffer); + } while (buffer_size_ == 0); + return true; +} + void Printer::CopyToBuffer(const char* data, int size) { if (failed_) return; if (size == 0) return; @@ -369,6 +266,134 @@ void Printer::CopyToBuffer(const char* data, int size) { offset_ += size; } +void Printer::IndentIfAtStart() { + if (at_start_of_line_) { + CopyToBuffer(indent_.data(), indent_.size()); + at_start_of_line_ = false; + } +} + +void Printer::FormatInternal(const std::vector& args, + const std::map& vars, + const char* format) { + auto save = format; + int arg_index = 0; + std::vector annotations; + while (*format) { + char c = *format++; + switch (c) { + case '$': + format = WriteVariable(args, vars, format, &arg_index, &annotations); + continue; + case '\n': + at_start_of_line_ = true; + line_start_variables_.clear(); + break; + default: + IndentIfAtStart(); + break; + } + push_back(c); + } + if (arg_index != args.size()) { + GOOGLE_LOG(FATAL) << " Unused arguments. " << save; + } + if (!annotations.empty()) { + GOOGLE_LOG(FATAL) << " Annotation range is not-closed, expect $}$. " << save; + } +} + +const char* Printer::WriteVariable( + const std::vector& args, + const std::map& vars, const char* format, + int* arg_index, std::vector* annotations) { + auto start = format; + auto end = strchr(format, '$'); + if (!end) { + GOOGLE_LOG(FATAL) << " Unclosed variable name."; + } + format = end + 1; + if (end == start) { + // "$$" is an escape for just '$' + IndentIfAtStart(); + push_back('$'); + return format; + } + if (*start == '{') { + GOOGLE_CHECK(std::isdigit(start[1])); + GOOGLE_CHECK_EQ(end - start, 2); + int idx = start[1] - '1'; + if (idx < 0 || idx >= args.size()) { + GOOGLE_LOG(FATAL) << "Annotation ${" << idx + 1 << "$ is out of bounds."; + } + if (idx > *arg_index) { + GOOGLE_LOG(FATAL) << "Annotation arg must be in correct order as given. Expected" + << " ${" << (*arg_index) + 1 << "$ got ${" << idx + 1 << "$."; + } else if (idx == *arg_index) { + (*arg_index)++; + } + IndentIfAtStart(); + annotations->push_back({{offset_, 0}, args[idx]}); + return format; + } else if (*start == '}') { + GOOGLE_CHECK(annotations); + if (annotations->empty()) { + GOOGLE_LOG(FATAL) << "Unexpected end of annotation found."; + } + auto& a = annotations->back(); + a.first.second = offset_; + if (annotation_collector_) annotation_collector_->AddAnnotationNew(a); + annotations->pop_back(); + return format; + } + auto start_var = start; + while (start_var < end && *start_var == ' ') start_var++; + if (start_var == end) { + GOOGLE_LOG(FATAL) << " Empty variable."; + } + auto end_var = end; + while (start_var < end_var && *(end_var - 1) == ' ') end_var--; + std::string var_name{ + start_var, static_cast(end_var - start_var)}; + std::string sub; + if (std::isdigit(var_name[0])) { + GOOGLE_CHECK_EQ(var_name.size(), 1); // No need for multi-digits + int idx = var_name[0] - '1'; // Start counting at 1 + GOOGLE_CHECK_GE(idx, 0); + if (idx >= args.size()) { + GOOGLE_LOG(FATAL) << "Argument $" << idx + 1 << "$ is out of bounds."; + } + if (idx > *arg_index) { + GOOGLE_LOG(FATAL) << "Arguments must be used in same order as given. Expected $" + << (*arg_index) + 1 << "$ got $" << idx + 1 << "$."; + } else if (idx == *arg_index) { + (*arg_index)++; + } + sub = args[idx]; + } else { + auto it = vars.find(var_name); + if (it == vars.end()) { + GOOGLE_LOG(FATAL) << " Unknown variable: " << var_name << "."; + } + sub = it->second; + } + + // By returning here in case of empty we also skip possible spaces inside + // the $...$, i.e. "void$ dllexpor$ f();" -> "void f();" in the empty case. + if (sub.empty()) return format; + + // We're going to write something non-empty so we need a possible indent. + IndentIfAtStart(); + + // Write the possible spaces in front. + CopyToBuffer(start, start_var - start); + // Write a non-empty substituted variable. + CopyToBuffer(sub.c_str(), sub.size()); + // Finish off with writing possible trailing spaces. + CopyToBuffer(end_var, end - end_var); + return format; +} + } // namespace io } // namespace protobuf } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/io/printer.h b/third_party/protobuf/src/google/protobuf/io/printer.h index d11745ce..a55946e9 100644 --- a/third_party/protobuf/src/google/protobuf/io/printer.h +++ b/third_party/protobuf/src/google/protobuf/io/printer.h @@ -37,26 +37,35 @@ #ifndef GOOGLE_PROTOBUF_IO_PRINTER_H__ #define GOOGLE_PROTOBUF_IO_PRINTER_H__ -#include #include +#include #include #include +#include + namespace google { namespace protobuf { namespace io { -class ZeroCopyOutputStream; // zero_copy_stream.h +class ZeroCopyOutputStream; // zero_copy_stream.h // Records annotations about a Printer's output. -class LIBPROTOBUF_EXPORT AnnotationCollector { +class PROTOBUF_EXPORT AnnotationCollector { public: + // Annotation is a ofset range and a payload pair. + typedef std::pair, std::string> Annotation; + // Records that the bytes in file_path beginning with begin_offset and ending // before end_offset are associated with the SourceCodeInfo-style path. virtual void AddAnnotation(size_t begin_offset, size_t end_offset, - const string& file_path, + const std::string& file_path, const std::vector& path) = 0; + // TODO(gerbens) I don't see why we need virtuals here. Just a vector of + // range, payload pairs stored in a context should suffice. + virtual void AddAnnotationNew(Annotation& a) {} + virtual ~AnnotationCollector() {} }; @@ -73,7 +82,7 @@ class AnnotationProtoCollector : public AnnotationCollector { // Override for AnnotationCollector::AddAnnotation. virtual void AddAnnotation(size_t begin_offset, size_t end_offset, - const string& file_path, + const std::string& file_path, const std::vector& path) { typename AnnotationProto::Annotation* annotation = annotation_proto_->add_annotation(); @@ -84,6 +93,13 @@ class AnnotationProtoCollector : public AnnotationCollector { annotation->set_begin(begin_offset); annotation->set_end(end_offset); } + // Override for AnnotationCollector::AddAnnotation. + virtual void AddAnnotationNew(Annotation& a) { + auto* annotation = annotation_proto_->add_annotation(); + annotation->ParseFromString(a.second); + annotation->set_begin(a.first.first); + annotation->set_end(a.first.second); + } private: // The protocol buffer to which new annotations should be added. @@ -162,7 +178,7 @@ class AnnotationProtoCollector : public AnnotationCollector { // This code associates the span covering "call(bar,bar)" in the output with the // call_ descriptor. -class LIBPROTOBUF_EXPORT Printer { +class PROTOBUF_EXPORT Printer { public: // Create a printer that writes text to the given output stream. Use the // given character as the delimiter for variables. @@ -203,7 +219,7 @@ class LIBPROTOBUF_EXPORT Printer { // Link a subsitution variable emitted by the last call to Print to the file // with path file_name. - void Annotate(const char* varname, const string& file_name) { + void Annotate(const char* varname, const std::string& file_name) { Annotate(varname, varname, file_name); } @@ -212,7 +228,7 @@ class LIBPROTOBUF_EXPORT Printer { // at begin_varname's value and ends after the last character of the value // substituted for end_varname. void Annotate(const char* begin_varname, const char* end_varname, - const string& file_name) { + const std::string& file_name) { if (annotation_collector_ == NULL) { // Annotations aren't turned on for this Printer. return; @@ -226,54 +242,15 @@ class LIBPROTOBUF_EXPORT Printer { // substituted are identified by their names surrounded by delimiter // characters (as given to the constructor). The variable bindings are // defined by the given map. - void Print(const std::map& variables, const char* text); + void Print(const std::map& variables, + const char* text); // Like the first Print(), except the substitutions are given as parameters. - void Print(const char* text); - // Like the first Print(), except the substitutions are given as parameters. - void Print(const char* text, const char* variable, const string& value); - // Like the first Print(), except the substitutions are given as parameters. - void Print(const char* text, const char* variable1, const string& value1, - const char* variable2, const string& value2); - // Like the first Print(), except the substitutions are given as parameters. - void Print(const char* text, const char* variable1, const string& value1, - const char* variable2, const string& value2, - const char* variable3, const string& value3); - // Like the first Print(), except the substitutions are given as parameters. - void Print(const char* text, const char* variable1, const string& value1, - const char* variable2, const string& value2, - const char* variable3, const string& value3, - const char* variable4, const string& value4); - // Like the first Print(), except the substitutions are given as parameters. - void Print(const char* text, const char* variable1, const string& value1, - const char* variable2, const string& value2, - const char* variable3, const string& value3, - const char* variable4, const string& value4, - const char* variable5, const string& value5); - // Like the first Print(), except the substitutions are given as parameters. - void Print(const char* text, const char* variable1, const string& value1, - const char* variable2, const string& value2, - const char* variable3, const string& value3, - const char* variable4, const string& value4, - const char* variable5, const string& value5, - const char* variable6, const string& value6); - // Like the first Print(), except the substitutions are given as parameters. - void Print(const char* text, const char* variable1, const string& value1, - const char* variable2, const string& value2, - const char* variable3, const string& value3, - const char* variable4, const string& value4, - const char* variable5, const string& value5, - const char* variable6, const string& value6, - const char* variable7, const string& value7); - // Like the first Print(), except the substitutions are given as parameters. - void Print(const char* text, const char* variable1, const string& value1, - const char* variable2, const string& value2, - const char* variable3, const string& value3, - const char* variable4, const string& value4, - const char* variable5, const string& value5, - const char* variable6, const string& value6, - const char* variable7, const string& value7, - const char* variable8, const string& value8); + template + void Print(const char* text, const Args&... args) { + std::map vars; + PrintInternal(&vars, text, args...); + } // Indent text by two spaces. After calling Indent(), two spaces will be // inserted at the beginning of each line of text. Indent() may be called @@ -286,7 +263,7 @@ class LIBPROTOBUF_EXPORT Printer { // Write a string to the output buffer. // This method does not look for newlines to add indentation. - void PrintRaw(const string& data); + void PrintRaw(const std::string& data); // Write a zero-delimited string to output buffer. // This method does not look for newlines to add indentation. @@ -296,6 +273,15 @@ class LIBPROTOBUF_EXPORT Printer { // This method does not look for newlines to add indentation. void WriteRaw(const char* data, int size); + // FormatInternal is a helper function not meant to use directly, use + // compiler::cpp::Formatter instead. This function is meant to support + // formatting text using named variables (eq. "$foo$) from a lookup map (vars) + // and variables directly supplied by arguments (eq "$1$" meaning first + // argument which is the zero index element of args). + void FormatInternal(const std::vector& args, + const std::map& vars, + const char* format); + // True if any write to the underlying stream failed. (We don't just // crash in this case because this is an I/O failure, not a programming // error.) @@ -309,11 +295,44 @@ class LIBPROTOBUF_EXPORT Printer { // substituted for end_varname. Note that begin_varname and end_varname // may refer to the same variable. void Annotate(const char* begin_varname, const char* end_varname, - const string& file_path, const std::vector& path); + const std::string& file_path, const std::vector& path); + + // Base case + void PrintInternal(std::map* vars, + const char* text) { + Print(*vars, text); + } + + template + void PrintInternal(std::map* vars, const char* text, + const char* key, const std::string& value, + const Args&... args) { + (*vars)[key] = value; + PrintInternal(vars, text, args...); + } // Copy size worth of bytes from data to buffer_. void CopyToBuffer(const char* data, int size); + void push_back(char c) { + if (failed_) return; + if (buffer_size_ == 0) { + if (!Next()) return; + } + *buffer_++ = c; + buffer_size_--; + offset_++; + } + + bool Next(); + + inline void IndentIfAtStart(); + const char* WriteVariable( + const std::vector& args, + const std::map& vars, const char* format, + int* arg_index, + std::vector* annotations); + const char variable_delimiter_; ZeroCopyOutputStream* const output_; @@ -324,7 +343,7 @@ class LIBPROTOBUF_EXPORT Printer { // used to calculate annotation ranges in the substitutions_ map below. size_t offset_; - string indent_; + std::string indent_; bool at_start_of_line_; bool failed_; @@ -335,12 +354,12 @@ class LIBPROTOBUF_EXPORT Printer { // start offset is the beginning of the substitution; the end offset is the // last byte of the substitution plus one (such that (end - start) is the // length of the substituted string). - std::map > substitutions_; + std::map > substitutions_; // Keeps track of the keys in substitutions_ that need to be updated when // indents are inserted. These are keys that refer to the beginning of the // current line. - std::vector line_start_variables_; + std::vector line_start_variables_; // Returns true and sets range to the substitution range in the output for // varname if varname was used once in the last call to Print. If varname @@ -358,6 +377,8 @@ class LIBPROTOBUF_EXPORT Printer { } // namespace io } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_IO_PRINTER_H__ diff --git a/third_party/protobuf/src/google/protobuf/io/printer_unittest.cc b/third_party/protobuf/src/google/protobuf/io/printer_unittest.cc index d0a0ebee..b847fa70 100644 --- a/third_party/protobuf/src/google/protobuf/io/printer_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/io/printer_unittest.cc @@ -46,7 +46,6 @@ namespace google { namespace protobuf { namespace io { -namespace { // Each test repeats over several block sizes in order to test both cases // where particular writes cross a buffer boundary and cases where they do @@ -78,10 +77,11 @@ TEST(Printer, BasicPrinting) { buffer[output.ByteCount()] = '\0'; - EXPECT_STREQ("Hello World! This is the same line.\n" - "But this is a new one.\n" - "And this is another one.", - buffer); + EXPECT_STREQ( + "Hello World! This is the same line.\n" + "But this is a new one.\n" + "And this is another one.", + buffer); } } @@ -92,7 +92,7 @@ TEST(Printer, WriteRaw) { ArrayOutputStream output(buffer, sizeof(buffer), block_size); { - string string_obj = "From an object\n"; + std::string string_obj = "From an object\n"; Printer printer(&output, '$'); printer.WriteRaw("Hello World!", 12); printer.PrintRaw(" This is the same line.\n"); @@ -104,12 +104,13 @@ TEST(Printer, WriteRaw) { buffer[output.ByteCount()] = '\0'; - EXPECT_STREQ("Hello World! This is the same line.\n" - "But this is a new one.\n" - "And this is another one." - "\n" - "From an object\n", - buffer); + EXPECT_STREQ( + "Hello World! This is the same line.\n" + "But this is a new one.\n" + "And this is another one." + "\n" + "From an object\n", + buffer); } } @@ -121,7 +122,7 @@ TEST(Printer, VariableSubstitution) { { Printer printer(&output, '$'); - std::map vars; + std::map vars; vars["foo"] = "World"; vars["bar"] = "$foo$"; @@ -139,13 +140,14 @@ TEST(Printer, VariableSubstitution) { buffer[output.ByteCount()] = '\0'; - EXPECT_STREQ("Hello World!\n" - "bar = $foo$\n" - "RawBit\n" - "1234\n" - "A literal dollar sign: $\n" - "Now foo = blah.", - buffer); + EXPECT_STREQ( + "Hello World!\n" + "bar = $foo$\n" + "RawBit\n" + "1234\n" + "A literal dollar sign: $\n" + "Now foo = blah.", + buffer); } } @@ -164,30 +166,31 @@ TEST(Printer, InlineVariableSubstitution) { buffer[output.ByteCount()] = '\0'; - EXPECT_STREQ("Hello World!\n" - "RawBit\n" - "one two\n", - buffer); + EXPECT_STREQ( + "Hello World!\n" + "RawBit\n" + "one two\n", + buffer); } // MockDescriptorFile defines only those members that Printer uses to write out // annotations. class MockDescriptorFile { public: - explicit MockDescriptorFile(const string& file) : file_(file) {} + explicit MockDescriptorFile(const std::string& file) : file_(file) {} // The mock filename for this file. - const string& name() const { return file_; } + const std::string& name() const { return file_; } private: - string file_; + std::string file_; }; // MockDescriptor defines only those members that Printer uses to write out // annotations. class MockDescriptor { public: - MockDescriptor(const string& file, const std::vector& path) + MockDescriptor(const std::string& file, const std::vector& path) : file_(file), path_(path) {} // The mock file in which this descriptor was defined. @@ -195,7 +198,7 @@ class MockDescriptor { private: // Allows access to GetLocationPath. - friend class ::google::protobuf::io::Printer; + friend class Printer; // Copies the pre-stored path to output. void GetLocationPath(std::vector* output) const { *output = path_; } @@ -211,7 +214,7 @@ TEST(Printer, AnnotateMap) { AnnotationProtoCollector info_collector(&info); { Printer printer(&output, '$', &info_collector); - std::map vars; + std::map vars; vars["foo"] = "3"; vars["bar"] = "5"; printer.Print(vars, "012$foo$4$bar$\n"); @@ -436,7 +439,6 @@ TEST(Printer, AnnotateIndentNewline) { EXPECT_EQ(4, ab->end()); } - TEST(Printer, Indenting) { char buffer[8192]; @@ -445,7 +447,7 @@ TEST(Printer, Indenting) { { Printer printer(&output, '$'); - std::map vars; + std::map vars; vars["newline"] = "\n"; @@ -455,11 +457,13 @@ TEST(Printer, Indenting) { printer.Outdent(); printer.Print("But this is not."); printer.Indent(); - printer.Print(" And this is still the same line.\n" - "But this is indented.\n"); + printer.Print( + " And this is still the same line.\n" + "But this is indented.\n"); printer.PrintRaw("RawBit has indent at start\n"); printer.PrintRaw("but not after a raw newline\n"); - printer.Print(vars, "Note that a newline in a variable will break " + printer.Print(vars, + "Note that a newline in a variable will break " "indenting, as we see$newline$here.\n"); printer.Indent(); printer.Print("And this"); @@ -473,18 +477,18 @@ TEST(Printer, Indenting) { buffer[output.ByteCount()] = '\0'; EXPECT_STREQ( - "This is not indented.\n" - " This is indented\n" - " And so is this\n" - "But this is not. And this is still the same line.\n" - " But this is indented.\n" - " RawBit has indent at start\n" - "but not after a raw newline\n" - "Note that a newline in a variable will break indenting, as we see\n" - "here.\n" - " And this is double-indented\n" - "Back to normal.", - buffer); + "This is not indented.\n" + " This is indented\n" + " And so is this\n" + "But this is not. And this is still the same line.\n" + " But this is indented.\n" + " RawBit has indent at start\n" + "but not after a raw newline\n" + "Note that a newline in a variable will break indenting, as we see\n" + "here.\n" + " And this is double-indented\n" + "Back to normal.", + buffer); } } @@ -594,7 +598,138 @@ TEST(Printer, WriteFailureExact) { EXPECT_EQ("0123456789abcdef", string(buffer, sizeof(buffer))); } -} // namespace +TEST(Printer, FormatInternal) { + std::vector args{"arg1", "arg2"}; + std::map vars{ + {"foo", "bar"}, {"baz", "bla"}, {"empty", ""}}; + // Substitution tests + { + // Direct arg substitution + std::string s; + { + StringOutputStream output(&s); + Printer printer(&output, '$'); + printer.FormatInternal(args, vars, "$1$ $2$"); + } + EXPECT_EQ("arg1 arg2", s); + } + { + // Variable substitution including spaces left + std::string s; + { + StringOutputStream output(&s); + Printer printer(&output, '$'); + printer.FormatInternal({}, vars, "$foo$$ baz$$ empty$"); + } + EXPECT_EQ("bar bla", s); + } + { + // Variable substitution including spaces right + std::string s; + { + StringOutputStream output(&s); + Printer printer(&output, '$'); + printer.FormatInternal({}, vars, "$empty $$foo $$baz$"); + } + EXPECT_EQ("bar bla", s); + } + { + // Mixed variable substitution + std::string s; + { + StringOutputStream output(&s); + Printer printer(&output, '$'); + printer.FormatInternal(args, vars, "$empty $$1$ $foo $$2$ $baz$"); + } + EXPECT_EQ("arg1 bar arg2 bla", s); + } + + // Indentation tests + { + // Empty lines shouldn't indent. + std::string s; + { + StringOutputStream output(&s); + Printer printer(&output, '$'); + printer.Indent(); + printer.FormatInternal(args, vars, "$empty $\n\n$1$ $foo $$2$\n$baz$"); + printer.Outdent(); + } + EXPECT_EQ("\n\n arg1 bar arg2\n bla", s); + } + { + // Annotations should respect indentation. + std::string s; + GeneratedCodeInfo info; + { + StringOutputStream output(&s); + AnnotationProtoCollector info_collector(&info); + Printer printer(&output, '$', &info_collector); + printer.Indent(); + GeneratedCodeInfo::Annotation annotation; + annotation.set_source_file("file.proto"); + annotation.add_path(33); + std::vector args{annotation.SerializeAsString(), "arg1", + "arg2"}; + printer.FormatInternal(args, vars, "$empty $\n\n${1$$2$$}$ $3$\n$baz$"); + printer.Outdent(); + } + EXPECT_EQ("\n\n arg1 arg2\n bla", s); + ASSERT_EQ(1, info.annotation_size()); + const GeneratedCodeInfo::Annotation* arg1 = &info.annotation(0); + ASSERT_EQ(1, arg1->path_size()); + EXPECT_EQ(33, arg1->path(0)); + EXPECT_EQ("file.proto", arg1->source_file()); + EXPECT_EQ(4, arg1->begin()); + EXPECT_EQ(8, arg1->end()); + } +#ifdef PROTOBUF_HAS_DEATH_TEST + // Death tests in case of illegal format strings. + { + // Unused arguments + std::string s; + StringOutputStream output(&s); + Printer printer(&output, '$'); + EXPECT_DEATH(printer.FormatInternal(args, vars, "$empty $$1$"), "Unused"); + } + { + // Wrong order arguments + std::string s; + StringOutputStream output(&s); + Printer printer(&output, '$'); + EXPECT_DEATH(printer.FormatInternal(args, vars, "$2$ $1$"), "order"); + } + { + // Zero is illegal argument + std::string s; + StringOutputStream output(&s); + Printer printer(&output, '$'); + EXPECT_DEATH(printer.FormatInternal(args, vars, "$0$"), "failed"); + } + { + // Argument out of bounds + std::string s; + StringOutputStream output(&s); + Printer printer(&output, '$'); + EXPECT_DEATH(printer.FormatInternal(args, vars, "$1$ $2$ $3$"), "bounds"); + } + { + // Unknown variable + std::string s; + StringOutputStream output(&s); + Printer printer(&output, '$'); + EXPECT_DEATH(printer.FormatInternal(args, vars, "$huh$ $1$$2$"), "Unknown"); + } + { + // Illegal variable + std::string s; + StringOutputStream output(&s); + Printer printer(&output, '$'); + EXPECT_DEATH(printer.FormatInternal({}, vars, "$ $"), "Empty"); + } +#endif // PROTOBUF_HAS_DEATH_TEST +} + } // namespace io } // namespace protobuf } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/io/strtod.cc b/third_party/protobuf/src/google/protobuf/io/strtod.cc index a90bb9a3..01164441 100644 --- a/third_party/protobuf/src/google/protobuf/io/strtod.cc +++ b/third_party/protobuf/src/google/protobuf/io/strtod.cc @@ -49,10 +49,14 @@ namespace io { namespace { +// This approximately 0x1.ffffffp127, but we don't use 0x1.ffffffp127 because +// it won't compile in MSVC. +const double MAX_FLOAT_AS_DOUBLE_ROUNDED = 3.4028235677973366e+38; + // Returns a string identical to *input except that the character pointed to // by radix_pos (which should be '.') is replaced with the locale-specific // radix character. -string LocalizeRadix(const char* input, const char* radix_pos) { +std::string LocalizeRadix(const char* input, const char* radix_pos) { // Determine the locale-specific radix character by calling sprintf() to // print the number 1.5, then stripping off the digits. As far as I can // tell, this is the only portable, thread-safe way to get the C library @@ -61,11 +65,11 @@ string LocalizeRadix(const char* input, const char* radix_pos) { char temp[16]; int size = sprintf(temp, "%.1f", 1.5); GOOGLE_CHECK_EQ(temp[0], '1'); - GOOGLE_CHECK_EQ(temp[size-1], '5'); + GOOGLE_CHECK_EQ(temp[size - 1], '5'); GOOGLE_CHECK_LE(size, 6); // Now replace the '.' in the input with it. - string result; + std::string result; result.reserve(strlen(input) + size - 3); result.append(input, radix_pos); result.append(temp + 1, size - 2); @@ -90,12 +94,11 @@ double NoLocaleStrtod(const char* text, char** original_endptr) { // Parsing halted on a '.'. Perhaps we're in a different locale? Let's // try to replace the '.' with a locale-specific radix character and // try again. - string localized = LocalizeRadix(text, temp_endptr); + std::string localized = LocalizeRadix(text, temp_endptr); const char* localized_cstr = localized.c_str(); char* localized_endptr; result = strtod(localized_cstr, &localized_endptr); - if ((localized_endptr - localized_cstr) > - (temp_endptr - text)) { + if ((localized_endptr - localized_cstr) > (temp_endptr - text)) { // This attempt got further, so replacing the decimal must have helped. // Update original_endptr to point at the right location. if (original_endptr != NULL) { @@ -103,7 +106,7 @@ double NoLocaleStrtod(const char* text, char** original_endptr) { int size_diff = localized.size() - strlen(text); // const_cast is necessary to match the strtod() interface. *original_endptr = const_cast( - text + (localized_endptr - localized_cstr - size_diff)); + text + (localized_endptr - localized_cstr - size_diff)); } } @@ -111,9 +114,24 @@ double NoLocaleStrtod(const char* text, char** original_endptr) { } float SafeDoubleToFloat(double value) { + // static_cast on a number larger than float can result in illegal + // instruction error, so we need to manually convert it to infinity or max. if (value > std::numeric_limits::max()) { + // Max float value is about 3.4028234664E38 when represented as a double. + // However, when printing float as text, it will be rounded as + // 3.4028235e+38. If we parse the value of 3.4028235e+38 from text and + // compare it to 3.4028234664E38, we may think that it is larger, but + // actually, any number between these two numbers could only be represented + // as the same max float number in float, so we should treat them the same + // as max float. + if (value <= MAX_FLOAT_AS_DOUBLE_ROUNDED) { + return std::numeric_limits::max(); + } return std::numeric_limits::infinity(); } else if (value < -std::numeric_limits::max()) { + if (value >= -MAX_FLOAT_AS_DOUBLE_ROUNDED) { + return -std::numeric_limits::max(); + } return -std::numeric_limits::infinity(); } else { return static_cast(value); diff --git a/third_party/protobuf/src/google/protobuf/io/strtod.h b/third_party/protobuf/src/google/protobuf/io/strtod.h index f56e41c8..38f544af 100644 --- a/third_party/protobuf/src/google/protobuf/io/strtod.h +++ b/third_party/protobuf/src/google/protobuf/io/strtod.h @@ -50,6 +50,6 @@ float SafeDoubleToFloat(double value); } // namespace io } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_IO_STRTOD_H__ diff --git a/third_party/protobuf/src/google/protobuf/io/tokenizer.cc b/third_party/protobuf/src/google/protobuf/io/tokenizer.cc index 916d1606..f8cf2ebd 100644 --- a/third_party/protobuf/src/google/protobuf/io/tokenizer.cc +++ b/third_party/protobuf/src/google/protobuf/io/tokenizer.cc @@ -113,39 +113,34 @@ namespace { // Note: No class is allowed to contain '\0', since this is used to mark end- // of-input and is handled specially. -#define CHARACTER_CLASS(NAME, EXPRESSION) \ - class NAME { \ - public: \ - static inline bool InClass(char c) { \ - return EXPRESSION; \ - } \ +#define CHARACTER_CLASS(NAME, EXPRESSION) \ + class NAME { \ + public: \ + static inline bool InClass(char c) { return EXPRESSION; } \ } -CHARACTER_CLASS(Whitespace, c == ' ' || c == '\n' || c == '\t' || - c == '\r' || c == '\v' || c == '\f'); -CHARACTER_CLASS(WhitespaceNoNewline, c == ' ' || c == '\t' || - c == '\r' || c == '\v' || c == '\f'); +CHARACTER_CLASS(Whitespace, c == ' ' || c == '\n' || c == '\t' || c == '\r' || + c == '\v' || c == '\f'); +CHARACTER_CLASS(WhitespaceNoNewline, + c == ' ' || c == '\t' || c == '\r' || c == '\v' || c == '\f'); -CHARACTER_CLASS(Unprintable, c < ' ' && c > '\0'); +CHARACTER_CLASS(Unprintable, c<' ' && c> '\0'); CHARACTER_CLASS(Digit, '0' <= c && c <= '9'); CHARACTER_CLASS(OctalDigit, '0' <= c && c <= '7'); -CHARACTER_CLASS(HexDigit, ('0' <= c && c <= '9') || - ('a' <= c && c <= 'f') || - ('A' <= c && c <= 'F')); +CHARACTER_CLASS(HexDigit, ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || + ('A' <= c && c <= 'F')); -CHARACTER_CLASS(Letter, ('a' <= c && c <= 'z') || - ('A' <= c && c <= 'Z') || - (c == '_')); +CHARACTER_CLASS(Letter, + ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || (c == '_')); CHARACTER_CLASS(Alphanumeric, ('a' <= c && c <= 'z') || - ('A' <= c && c <= 'Z') || - ('0' <= c && c <= '9') || - (c == '_')); + ('A' <= c && c <= 'Z') || + ('0' <= c && c <= '9') || (c == '_')); CHARACTER_CLASS(Escape, c == 'a' || c == 'b' || c == 'f' || c == 'n' || - c == 'r' || c == 't' || c == 'v' || c == '\\' || - c == '?' || c == '\'' || c == '\"'); + c == 'r' || c == 't' || c == 'v' || c == '\\' || + c == '?' || c == '\'' || c == '\"'); #undef CHARACTER_CLASS @@ -161,20 +156,32 @@ inline int DigitValue(char digit) { // Inline because it's only used in one place. inline char TranslateEscape(char c) { switch (c) { - case 'a': return '\a'; - case 'b': return '\b'; - case 'f': return '\f'; - case 'n': return '\n'; - case 'r': return '\r'; - case 't': return '\t'; - case 'v': return '\v'; - case '\\': return '\\'; - case '?': return '\?'; // Trigraphs = :( - case '\'': return '\''; - case '"': return '\"'; + case 'a': + return '\a'; + case 'b': + return '\b'; + case 'f': + return '\f'; + case 'n': + return '\n'; + case 'r': + return '\r'; + case 't': + return '\t'; + case 'v': + return '\v'; + case '\\': + return '\\'; + case '?': + return '\?'; // Trigraphs = :( + case '\'': + return '\''; + case '"': + return '\"'; // We expect escape sequences to have been validated separately. - default: return '?'; + default: + return '?'; } } @@ -186,21 +193,20 @@ ErrorCollector::~ErrorCollector() {} Tokenizer::Tokenizer(ZeroCopyInputStream* input, ErrorCollector* error_collector) - : input_(input), - error_collector_(error_collector), - buffer_(NULL), - buffer_size_(0), - buffer_pos_(0), - read_error_(false), - line_(0), - column_(0), - record_target_(NULL), - record_start_(-1), - allow_f_after_float_(false), - comment_style_(CPP_COMMENT_STYLE), - require_space_after_number_(true), - allow_multiline_strings_(false) { - + : input_(input), + error_collector_(error_collector), + buffer_(NULL), + buffer_size_(0), + buffer_pos_(0), + read_error_(false), + line_(0), + column_(0), + record_target_(NULL), + record_start_(-1), + allow_f_after_float_(false), + comment_style_(CPP_COMMENT_STYLE), + require_space_after_number_(true), + allow_multiline_strings_(false) { current_.line = 0; current_.column = 0; current_.end_column = 0; @@ -249,7 +255,8 @@ void Tokenizer::Refresh() { // If we're in a token, append the rest of the buffer to it. if (record_target_ != NULL && record_start_ < buffer_size_) { - record_target_->append(buffer_ + record_start_, buffer_size_ - record_start_); + record_target_->append(buffer_ + record_start_, + buffer_size_ - record_start_); record_start_ = 0; } @@ -271,7 +278,7 @@ void Tokenizer::Refresh() { current_char_ = buffer_[0]; } -inline void Tokenizer::RecordTo(string* target) { +inline void Tokenizer::RecordTo(std::string* target) { record_target_ = target; record_start_ = buffer_pos_; } @@ -282,14 +289,15 @@ inline void Tokenizer::StopRecording() { // be helpful by detecting the NULL pointer, even though there's nothing // wrong with reading zero bytes from NULL. if (buffer_pos_ != record_start_) { - record_target_->append(buffer_ + record_start_, buffer_pos_ - record_start_); + record_target_->append(buffer_ + record_start_, + buffer_pos_ - record_start_); } record_target_ = NULL; record_start_ = -1; } inline void Tokenizer::StartToken() { - current_.type = TYPE_START; // Just for the sake of initializing it. + current_.type = TYPE_START; // Just for the sake of initializing it. current_.text.clear(); current_.line = line_; current_.column = column_; @@ -304,12 +312,12 @@ inline void Tokenizer::EndToken() { // ------------------------------------------------------------------- // Helper methods that consume characters. -template +template inline bool Tokenizer::LookingAt() { return CharacterClass::InClass(current_char_); } -template +template inline bool Tokenizer::TryConsumeOne() { if (CharacterClass::InClass(current_char_)) { NextChar(); @@ -328,14 +336,14 @@ inline bool Tokenizer::TryConsume(char c) { } } -template +template inline void Tokenizer::ConsumeZeroOrMore() { while (CharacterClass::InClass(current_char_)) { NextChar(); } } -template +template inline void Tokenizer::ConsumeOneOrMore(const char* error) { if (!CharacterClass::InClass(current_char_)) { AddError(error); @@ -381,25 +389,21 @@ void Tokenizer::ConsumeString(char delimiter) { } // Possibly followed by another hex digit, but again we don't care. } else if (TryConsume('u')) { - if (!TryConsumeOne() || - !TryConsumeOne() || - !TryConsumeOne() || - !TryConsumeOne()) { + if (!TryConsumeOne() || !TryConsumeOne() || + !TryConsumeOne() || !TryConsumeOne()) { AddError("Expected four hex digits for \\u escape sequence."); } } else if (TryConsume('U')) { // We expect 8 hex digits; but only the range up to 0x10ffff is // legal. - if (!TryConsume('0') || - !TryConsume('0') || + if (!TryConsume('0') || !TryConsume('0') || !(TryConsume('0') || TryConsume('1')) || - !TryConsumeOne() || - !TryConsumeOne() || - !TryConsumeOne() || - !TryConsumeOne() || + !TryConsumeOne() || !TryConsumeOne() || + !TryConsumeOne() || !TryConsumeOne() || !TryConsumeOne()) { - AddError("Expected eight hex digits up to 10ffff for \\U escape " - "sequence"); + AddError( + "Expected eight hex digits up to 10ffff for \\U escape " + "sequence"); } } else { AddError("Invalid escape sequence in string literal."); @@ -465,7 +469,7 @@ Tokenizer::TokenType Tokenizer::ConsumeNumber(bool started_with_zero, } else if (current_char_ == '.') { if (is_float) { AddError( - "Already saw decimal point or exponent; can't have another one."); + "Already saw decimal point or exponent; can't have another one."); } else { AddError("Hex and octal numbers must be integers."); } @@ -474,7 +478,7 @@ Tokenizer::TokenType Tokenizer::ConsumeNumber(bool started_with_zero, return is_float ? TYPE_FLOAT : TYPE_INTEGER; } -void Tokenizer::ConsumeLineComment(string* content) { +void Tokenizer::ConsumeLineComment(std::string* content) { if (content != NULL) RecordTo(content); while (current_char_ != '\0' && current_char_ != '\n') { @@ -485,17 +489,15 @@ void Tokenizer::ConsumeLineComment(string* content) { if (content != NULL) StopRecording(); } -void Tokenizer::ConsumeBlockComment(string* content) { +void Tokenizer::ConsumeBlockComment(std::string* content) { int start_line = line_; int start_column = column_ - 2; if (content != NULL) RecordTo(content); while (true) { - while (current_char_ != '\0' && - current_char_ != '*' && - current_char_ != '/' && - current_char_ != '\n') { + while (current_char_ != '\0' && current_char_ != '*' && + current_char_ != '/' && current_char_ != '\n') { NextChar(); } @@ -524,11 +526,11 @@ void Tokenizer::ConsumeBlockComment(string* content) { // Note: We didn't consume the '*' because if there is a '/' after it // we want to interpret that as the end of the comment. AddError( - "\"/*\" inside block comment. Block comments cannot be nested."); + "\"/*\" inside block comment. Block comments cannot be nested."); } else if (current_char_ == '\0') { AddError("End-of-file inside block comment."); - error_collector_->AddError( - start_line, start_column, " Comment started here."); + error_collector_->AddError(start_line, start_column, + " Comment started here."); if (content != NULL) StopRecording(); break; } @@ -613,8 +615,9 @@ bool Tokenizer::Next() { current_.line == previous_.line && current_.column == previous_.end_column) { // We don't accept syntax like "blah.123". - error_collector_->AddError(line_, column_ - 2, - "Need space between identifier and decimal point."); + error_collector_->AddError( + line_, column_ - 2, + "Need space between identifier and decimal point."); } current_.type = ConsumeNumber(false, true); } else { @@ -631,7 +634,8 @@ bool Tokenizer::Next() { } else { // Check if the high order bit is set. if (current_char_ & 0x80) { - error_collector_->AddError(line_, column_, + error_collector_->AddError( + line_, column_, StringPrintf("Interpreting non ascii codepoint %d.", static_cast(current_char_))); } @@ -664,9 +668,9 @@ namespace { // next_leading_comments. class CommentCollector { public: - CommentCollector(string* prev_trailing_comments, - std::vector* detached_comments, - string* next_leading_comments) + CommentCollector(std::string* prev_trailing_comments, + std::vector* detached_comments, + std::string* next_leading_comments) : prev_trailing_comments_(prev_trailing_comments), detached_comments_(detached_comments), next_leading_comments_(next_leading_comments), @@ -687,7 +691,7 @@ class CommentCollector { // About to read a line comment. Get the comment buffer pointer in order to // read into it. - string* GetBufferForLineComment() { + std::string* GetBufferForLineComment() { // We want to combine with previous line comments, but not block comments. if (has_comment_ && !is_line_comment_) { Flush(); @@ -699,7 +703,7 @@ class CommentCollector { // About to read a block comment. Get the comment buffer pointer in order to // read into it. - string* GetBufferForBlockComment() { + std::string* GetBufferForBlockComment() { if (has_comment_) { Flush(); } @@ -731,16 +735,14 @@ class CommentCollector { } } - void DetachFromPrev() { - can_attach_to_prev_ = false; - } + void DetachFromPrev() { can_attach_to_prev_ = false; } private: - string* prev_trailing_comments_; - std::vector* detached_comments_; - string* next_leading_comments_; + std::string* prev_trailing_comments_; + std::vector* detached_comments_; + std::string* next_leading_comments_; - string comment_buffer_; + std::string comment_buffer_; // True if any comments were read into comment_buffer_. This can be true even // if comment_buffer_ is empty, namely if the comment was "/**/". @@ -754,11 +756,11 @@ class CommentCollector { bool can_attach_to_prev_; }; -} // namespace +} // namespace -bool Tokenizer::NextWithComments(string* prev_trailing_comments, - std::vector* detached_comments, - string* next_leading_comments) { +bool Tokenizer::NextWithComments(std::string* prev_trailing_comments, + std::vector* detached_comments, + std::string* next_leading_comments) { CommentCollector collector(prev_trailing_comments, detached_comments, next_leading_comments); @@ -767,8 +769,9 @@ bool Tokenizer::NextWithComments(string* prev_trailing_comments, // beginning. Only UTF-8 BOM (0xEF 0xBB 0xBF) is accepted. if (TryConsume((char)0xEF)) { if (!TryConsume((char)0xBB) || !TryConsume((char)0xBF)) { - AddError("Proto file starts with 0xEF but not UTF-8 BOM. " - "Only UTF-8 is accepted for proto file."); + AddError( + "Proto file starts with 0xEF but not UTF-8 BOM. " + "Only UTF-8 is accepted for proto file."); return false; } } @@ -836,9 +839,7 @@ bool Tokenizer::NextWithComments(string* prev_trailing_comments, collector.DetachFromPrev(); } else { bool result = Next(); - if (!result || - current_.text == "}" || - current_.text == "]" || + if (!result || current_.text == "}" || current_.text == "]" || current_.text == ")") { // It looks like we're at the end of a scope. In this case it // makes no sense to attach a comment to the following token. @@ -858,12 +859,12 @@ bool Tokenizer::NextWithComments(string* prev_trailing_comments, // are given is text that the tokenizer actually parsed as a token // of the given type. -bool Tokenizer::ParseInteger(const string& text, uint64 max_value, +bool Tokenizer::ParseInteger(const std::string& text, uint64 max_value, uint64* output) { // Sadly, we can't just use strtoul() since it is only 32-bit and strtoull() // is non-standard. I hate the C standard library. :( -// return strtoull(text.c_str(), NULL, 0); + // return strtoull(text.c_str(), NULL, 0); const char* ptr = text.c_str(); int base = 10; @@ -897,7 +898,7 @@ bool Tokenizer::ParseInteger(const string& text, uint64 max_value, return true; } -double Tokenizer::ParseFloat(const string& text) { +double Tokenizer::ParseFloat(const std::string& text) { const char* start = text.c_str(); char* end; double result = NoLocaleStrtod(start, &end); @@ -917,36 +918,31 @@ double Tokenizer::ParseFloat(const string& text) { } GOOGLE_LOG_IF(DFATAL, end - start != text.size() || *start == '-') - << " Tokenizer::ParseFloat() passed text that could not have been" - " tokenized as a float: " << CEscape(text); + << " Tokenizer::ParseFloat() passed text that could not have been" + " tokenized as a float: " + << CEscape(text); return result; } // Helper to append a Unicode code point to a string as UTF8, without bringing // in any external dependencies. -static void AppendUTF8(uint32 code_point, string* output) { +static void AppendUTF8(uint32 code_point, std::string* output) { uint32 tmp = 0; int len = 0; if (code_point <= 0x7f) { tmp = code_point; len = 1; } else if (code_point <= 0x07ff) { - tmp = 0x0000c080 | - ((code_point & 0x07c0) << 2) | - (code_point & 0x003f); + tmp = 0x0000c080 | ((code_point & 0x07c0) << 2) | (code_point & 0x003f); len = 2; } else if (code_point <= 0xffff) { - tmp = 0x00e08080 | - ((code_point & 0xf000) << 4) | - ((code_point & 0x0fc0) << 2) | - (code_point & 0x003f); + tmp = 0x00e08080 | ((code_point & 0xf000) << 4) | + ((code_point & 0x0fc0) << 2) | (code_point & 0x003f); len = 3; } else if (code_point <= 0x1fffff) { - tmp = 0xf0808080 | - ((code_point & 0x1c0000) << 6) | - ((code_point & 0x03f000) << 4) | - ((code_point & 0x000fc0) << 2) | - (code_point & 0x003f); + tmp = 0xf0808080 | ((code_point & 0x1c0000) << 6) | + ((code_point & 0x03f000) << 4) | ((code_point & 0x000fc0) << 2) | + (code_point & 0x003f); len = 4; } else { // UTF-16 is only defined for code points up to 0x10FFFF, and UTF-8 is @@ -986,7 +982,7 @@ static inline bool IsHeadSurrogate(uint32 code_point) { static inline bool IsTrailSurrogate(uint32 code_point) { return (code_point >= kMinTrailSurrogate) && - (code_point < kMaxTrailSurrogate); + (code_point < kMaxTrailSurrogate); } // Combine a head and trail surrogate into a single Unicode code point. @@ -994,7 +990,7 @@ static uint32 AssembleUTF16(uint32 head_surrogate, uint32 trail_surrogate) { GOOGLE_DCHECK(IsHeadSurrogate(head_surrogate)); GOOGLE_DCHECK(IsTrailSurrogate(trail_surrogate)); return 0x10000 + (((head_surrogate - kMinHeadSurrogate) << 10) | - (trail_surrogate - kMinTrailSurrogate)); + (trail_surrogate - kMinTrailSurrogate)); } // Convert the escape sequence parameter to a number of expected hex digits. @@ -1012,8 +1008,7 @@ static const char* FetchUnicodePoint(const char* ptr, uint32* code_point) { const char* p = ptr; // Fetch the code point. const int len = UnicodeLength(*p++); - if (!ReadHexDigits(p, len, code_point)) - return ptr; + if (!ReadHexDigits(p, len, code_point)) return ptr; p += len; // Check if the code point we read is a "head surrogate." If so, then we @@ -1036,14 +1031,15 @@ static const char* FetchUnicodePoint(const char* ptr, uint32* code_point) { // The text string must begin and end with single or double quote // characters. -void Tokenizer::ParseStringAppend(const string& text, string* output) { +void Tokenizer::ParseStringAppend(const std::string& text, + std::string* output) { // Reminder: text[0] is always a quote character. (If text is // empty, it's invalid, so we'll just return). const size_t text_size = text.size(); if (text_size == 0) { - GOOGLE_LOG(DFATAL) - << " Tokenizer::ParseStringAppend() passed text that could not" - " have been tokenized as a string: " << CEscape(text); + GOOGLE_LOG(DFATAL) << " Tokenizer::ParseStringAppend() passed text that could not" + " have been tokenized as a string: " + << CEscape(text); return; } @@ -1114,23 +1110,19 @@ void Tokenizer::ParseStringAppend(const string& text, string* output) { } } -template -static bool AllInClass(const string& s) { +template +static bool AllInClass(const std::string& s) { for (int i = 0; i < s.size(); ++i) { - if (!CharacterClass::InClass(s[i])) - return false; + if (!CharacterClass::InClass(s[i])) return false; } return true; } -bool Tokenizer::IsIdentifier(const string& text) { +bool Tokenizer::IsIdentifier(const std::string& text) { // Mirrors IDENTIFIER definition in Tokenizer::Next() above. - if (text.size() == 0) - return false; - if (!Letter::InClass(text.at(0))) - return false; - if (!AllInClass(text.substr(1))) - return false; + if (text.size() == 0) return false; + if (!Letter::InClass(text.at(0))) return false; + if (!AllInClass(text.substr(1))) return false; return true; } diff --git a/third_party/protobuf/src/google/protobuf/io/tokenizer.h b/third_party/protobuf/src/google/protobuf/io/tokenizer.h index e80d564c..cb33b931 100644 --- a/third_party/protobuf/src/google/protobuf/io/tokenizer.h +++ b/third_party/protobuf/src/google/protobuf/io/tokenizer.h @@ -42,11 +42,13 @@ #include #include +#include + namespace google { namespace protobuf { namespace io { -class ZeroCopyInputStream; // zero_copy_stream.h +class ZeroCopyInputStream; // zero_copy_stream.h // Defined in this file. class ErrorCollector; @@ -61,7 +63,7 @@ typedef int ColumnNumber; // Abstract interface for an object which collects the errors that occur // during parsing. A typical implementation might simply print the errors // to stdout. -class LIBPROTOBUF_EXPORT ErrorCollector { +class PROTOBUF_EXPORT ErrorCollector { public: inline ErrorCollector() {} virtual ~ErrorCollector(); @@ -70,13 +72,13 @@ class LIBPROTOBUF_EXPORT ErrorCollector { // column numbers. The numbers are zero-based, so you may want to add // 1 to each before printing them. virtual void AddError(int line, ColumnNumber column, - const string& message) = 0; + const std::string& message) = 0; // Indicates that there was a warning in the input at the given line and // column numbers. The numbers are zero-based, so you may want to add // 1 to each before printing them. virtual void AddWarning(int line, ColumnNumber column, - const string& message) { } + const std::string& message) {} private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ErrorCollector); @@ -88,7 +90,7 @@ class LIBPROTOBUF_EXPORT ErrorCollector { // precise descriptions. Whitespace and comments are skipped. By default, // C- and C++-style comments are recognized, but other styles can be used by // calling set_comment_style(). -class LIBPROTOBUF_EXPORT Tokenizer { +class PROTOBUF_EXPORT Tokenizer { public: // Construct a Tokenizer that reads and tokenizes text from the given // input stream and writes errors to the given error_collector. @@ -97,8 +99,8 @@ class LIBPROTOBUF_EXPORT Tokenizer { ~Tokenizer(); enum TokenType { - TYPE_START, // Next() has not yet been called. - TYPE_END, // End of input reached. "text" is empty. + TYPE_START, // Next() has not yet been called. + TYPE_END, // End of input reached. "text" is empty. TYPE_IDENTIFIER, // A sequence of letters, digits, and underscores, not // starting with a digit. It is an error for a number @@ -124,7 +126,7 @@ class LIBPROTOBUF_EXPORT Tokenizer { // Structure representing a token read from the token stream. struct Token { TokenType type; - string text; // The exact text of the token as it appeared in + std::string text; // The exact text of the token as it appeared in // the input. e.g. tokens of TYPE_STRING will still // be escaped and in quotes. @@ -190,31 +192,31 @@ class LIBPROTOBUF_EXPORT Tokenizer { // /* Block comment attached to // * grault. */ // optional int32 grault = 6; - bool NextWithComments(string* prev_trailing_comments, - std::vector* detached_comments, - string* next_leading_comments); + bool NextWithComments(std::string* prev_trailing_comments, + std::vector* detached_comments, + std::string* next_leading_comments); // Parse helpers --------------------------------------------------- // Parses a TYPE_FLOAT token. This never fails, so long as the text actually // comes from a TYPE_FLOAT token parsed by Tokenizer. If it doesn't, the // result is undefined (possibly an assert failure). - static double ParseFloat(const string& text); + static double ParseFloat(const std::string& text); // Parses a TYPE_STRING token. This never fails, so long as the text actually // comes from a TYPE_STRING token parsed by Tokenizer. If it doesn't, the // result is undefined (possibly an assert failure). - static void ParseString(const string& text, string* output); + static void ParseString(const std::string& text, std::string* output); // Identical to ParseString, but appends to output. - static void ParseStringAppend(const string& text, string* output); + static void ParseStringAppend(const std::string& text, std::string* output); // Parses a TYPE_INTEGER token. Returns false if the result would be // greater than max_value. Otherwise, returns true and sets *output to the // result. If the text is not from a Token of type TYPE_INTEGER originally // parsed by a Tokenizer, the result is undefined (possibly an assert // failure). - static bool ParseInteger(const string& text, uint64 max_value, + static bool ParseInteger(const std::string& text, uint64 max_value, uint64* output); // Options --------------------------------------------------------- @@ -250,23 +252,23 @@ class LIBPROTOBUF_EXPORT Tokenizer { } // External helper: validate an identifier. - static bool IsIdentifier(const string& text); + static bool IsIdentifier(const std::string& text); // ----------------------------------------------------------------- private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Tokenizer); - Token current_; // Returned by current(). - Token previous_; // Returned by previous(). + Token current_; // Returned by current(). + Token previous_; // Returned by previous(). ZeroCopyInputStream* input_; ErrorCollector* error_collector_; - char current_char_; // == buffer_[buffer_pos_], updated by NextChar(). - const char* buffer_; // Current buffer returned from input_. - int buffer_size_; // Size of buffer_. - int buffer_pos_; // Current position within the buffer. - bool read_error_; // Did we previously encounter a read error? + char current_char_; // == buffer_[buffer_pos_], updated by NextChar(). + const char* buffer_; // Current buffer returned from input_. + int buffer_size_; // Size of buffer_. + int buffer_pos_; // Current position within the buffer. + bool read_error_; // Did we previously encounter a read error? // Line and column number of current_char_ within the whole input stream. int line_; @@ -276,7 +278,7 @@ class LIBPROTOBUF_EXPORT Tokenizer { // Call RecordTo(&str) to start recording and StopRecording() to stop. // E.g. StartToken() calls RecordTo(¤t_.text). record_start_ is the // position within the current buffer where recording started. - string* record_target_; + std::string* record_target_; int record_start_; // Options. @@ -299,7 +301,7 @@ class LIBPROTOBUF_EXPORT Tokenizer { // Read a new buffer from the input. void Refresh(); - inline void RecordTo(string* target); + inline void RecordTo(std::string* target); inline void StopRecording(); // Called when the current character is the first character of a new @@ -311,7 +313,7 @@ class LIBPROTOBUF_EXPORT Tokenizer { inline void EndToken(); // Convenience method to add an error at the current line and column. - void AddError(const string& message) { + void AddError(const std::string& message) { error_collector_->AddError(line_, column_, message); } @@ -334,9 +336,9 @@ class LIBPROTOBUF_EXPORT Tokenizer { TokenType ConsumeNumber(bool started_with_zero, bool started_with_dot); // Consume the rest of a line. - void ConsumeLineComment(string* content); + void ConsumeLineComment(std::string* content); // Consume until "*/". - void ConsumeBlockComment(string* content); + void ConsumeBlockComment(std::string* content); enum NextCommentStatus { // Started a line comment. @@ -367,45 +369,44 @@ class LIBPROTOBUF_EXPORT Tokenizer { // Returns true if the current character is of the given character // class, but does not consume anything. - template + template inline bool LookingAt(); // If the current character is in the given class, consume it and return // true. Otherwise return false. // e.g. TryConsumeOne() - template + template inline bool TryConsumeOne(); // Like above, but try to consume the specific character indicated. inline bool TryConsume(char c); // Consume zero or more of the given character class. - template + template inline void ConsumeZeroOrMore(); // Consume one or more of the given character class or log the given // error message. // e.g. ConsumeOneOrMore("Expected digits."); - template + template inline void ConsumeOneOrMore(const char* error); }; // inline methods ==================================================== -inline const Tokenizer::Token& Tokenizer::current() { - return current_; -} +inline const Tokenizer::Token& Tokenizer::current() { return current_; } -inline const Tokenizer::Token& Tokenizer::previous() { - return previous_; -} +inline const Tokenizer::Token& Tokenizer::previous() { return previous_; } -inline void Tokenizer::ParseString(const string& text, string* output) { +inline void Tokenizer::ParseString(const std::string& text, + std::string* output) { output->clear(); ParseStringAppend(text, output); } } // namespace io } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_IO_TOKENIZER_H__ diff --git a/third_party/protobuf/src/google/protobuf/io/tokenizer_unittest.cc b/third_party/protobuf/src/google/protobuf/io/tokenizer_unittest.cc index e55288e2..37628ab2 100644 --- a/third_party/protobuf/src/google/protobuf/io/tokenizer_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/io/tokenizer_unittest.cc @@ -75,45 +75,45 @@ namespace { // which failed will be printed. The case type must be printable using // ostream::operator<<. -#define TEST_1D(FIXTURE, NAME, CASES) \ - class FIXTURE##_##NAME##_DD : public FIXTURE { \ - protected: \ - template \ - void DoSingleCase(const CaseType& CASES##_case); \ - }; \ - \ - TEST_F(FIXTURE##_##NAME##_DD, NAME) { \ - for (int i = 0; i < GOOGLE_ARRAYSIZE(CASES); i++) { \ - SCOPED_TRACE(testing::Message() \ - << #CASES " case #" << i << ": " << CASES[i]); \ - DoSingleCase(CASES[i]); \ - } \ - } \ - \ - template \ +#define TEST_1D(FIXTURE, NAME, CASES) \ + class FIXTURE##_##NAME##_DD : public FIXTURE { \ + protected: \ + template \ + void DoSingleCase(const CaseType& CASES##_case); \ + }; \ + \ + TEST_F(FIXTURE##_##NAME##_DD, NAME) { \ + for (int i = 0; i < GOOGLE_ARRAYSIZE(CASES); i++) { \ + SCOPED_TRACE(testing::Message() \ + << #CASES " case #" << i << ": " << CASES[i]); \ + DoSingleCase(CASES[i]); \ + } \ + } \ + \ + template \ void FIXTURE##_##NAME##_DD::DoSingleCase(const CaseType& CASES##_case) -#define TEST_2D(FIXTURE, NAME, CASES1, CASES2) \ - class FIXTURE##_##NAME##_DD : public FIXTURE { \ - protected: \ - template \ - void DoSingleCase(const CaseType1& CASES1##_case, \ - const CaseType2& CASES2##_case); \ - }; \ - \ - TEST_F(FIXTURE##_##NAME##_DD, NAME) { \ - for (int i = 0; i < GOOGLE_ARRAYSIZE(CASES1); i++) { \ - for (int j = 0; j < GOOGLE_ARRAYSIZE(CASES2); j++) { \ - SCOPED_TRACE(testing::Message() \ - << #CASES1 " case #" << i << ": " << CASES1[i] << ", " \ - << #CASES2 " case #" << j << ": " << CASES2[j]); \ - DoSingleCase(CASES1[i], CASES2[j]); \ - } \ - } \ - } \ - \ - template \ - void FIXTURE##_##NAME##_DD::DoSingleCase(const CaseType1& CASES1##_case, \ +#define TEST_2D(FIXTURE, NAME, CASES1, CASES2) \ + class FIXTURE##_##NAME##_DD : public FIXTURE { \ + protected: \ + template \ + void DoSingleCase(const CaseType1& CASES1##_case, \ + const CaseType2& CASES2##_case); \ + }; \ + \ + TEST_F(FIXTURE##_##NAME##_DD, NAME) { \ + for (int i = 0; i < GOOGLE_ARRAYSIZE(CASES1); i++) { \ + for (int j = 0; j < GOOGLE_ARRAYSIZE(CASES2); j++) { \ + SCOPED_TRACE(testing::Message() \ + << #CASES1 " case #" << i << ": " << CASES1[i] << ", " \ + << #CASES2 " case #" << j << ": " << CASES2[j]); \ + DoSingleCase(CASES1[i], CASES2[j]); \ + } \ + } \ + } \ + \ + template \ + void FIXTURE##_##NAME##_DD::DoSingleCase(const CaseType1& CASES1##_case, \ const CaseType2& CASES2##_case) // ------------------------------------------------------------------- @@ -123,7 +123,7 @@ namespace { class TestInputStream : public ZeroCopyInputStream { public: TestInputStream(const void* data, int size, int block_size) - : array_stream_(data, size, block_size), counter_(0) {} + : array_stream_(data, size, block_size), counter_(0) {} ~TestInputStream() {} // implements ZeroCopyInputStream ---------------------------------- @@ -141,9 +141,9 @@ class TestInputStream : public ZeroCopyInputStream { } } - void BackUp(int count) { return array_stream_.BackUp(count); } - bool Skip(int count) { return array_stream_.Skip(count); } - int64 ByteCount() const { return array_stream_.ByteCount(); } + void BackUp(int count) { return array_stream_.BackUp(count); } + bool Skip(int count) { return array_stream_.Skip(count); } + int64 ByteCount() const { return array_stream_.ByteCount(); } private: ArrayInputStream array_stream_; @@ -159,12 +159,11 @@ class TestErrorCollector : public ErrorCollector { TestErrorCollector() {} ~TestErrorCollector() {} - string text_; + std::string text_; // implements ErrorCollector --------------------------------------- - void AddError(int line, int column, const string& message) { - strings::SubstituteAndAppend(&text_, "$0:$1: $2\n", - line, column, message); + void AddError(int line, int column, const std::string& message) { + strings::SubstituteAndAppend(&text_, "$0:$1: $2\n", line, column, message); } }; @@ -179,7 +178,7 @@ const int kBlockSizes[] = {1, 2, 3, 5, 7, 13, 32, 1024}; class TokenizerTest : public testing::Test { protected: // For easy testing. - uint64 ParseInteger(const string& text) { + uint64 ParseInteger(const std::string& text) { uint64 result; EXPECT_TRUE(Tokenizer::ParseInteger(text, kuint64max, &result)); return result; @@ -195,7 +194,7 @@ class TokenizerTest : public testing::Test { // In each test case, the entire input text should parse as a single token // of the given type. struct SimpleTokenCase { - string input; + std::string input; Tokenizer::TokenType type; }; @@ -205,52 +204,51 @@ inline std::ostream& operator<<(std::ostream& out, } SimpleTokenCase kSimpleTokenCases[] = { - // Test identifiers. - { "hello", Tokenizer::TYPE_IDENTIFIER }, + // Test identifiers. + {"hello", Tokenizer::TYPE_IDENTIFIER}, - // Test integers. - { "123", Tokenizer::TYPE_INTEGER }, - { "0xab6", Tokenizer::TYPE_INTEGER }, - { "0XAB6", Tokenizer::TYPE_INTEGER }, - { "0X1234567", Tokenizer::TYPE_INTEGER }, - { "0x89abcdef", Tokenizer::TYPE_INTEGER }, - { "0x89ABCDEF", Tokenizer::TYPE_INTEGER }, - { "01234567", Tokenizer::TYPE_INTEGER }, + // Test integers. + {"123", Tokenizer::TYPE_INTEGER}, + {"0xab6", Tokenizer::TYPE_INTEGER}, + {"0XAB6", Tokenizer::TYPE_INTEGER}, + {"0X1234567", Tokenizer::TYPE_INTEGER}, + {"0x89abcdef", Tokenizer::TYPE_INTEGER}, + {"0x89ABCDEF", Tokenizer::TYPE_INTEGER}, + {"01234567", Tokenizer::TYPE_INTEGER}, - // Test floats. - { "123.45", Tokenizer::TYPE_FLOAT }, - { "1.", Tokenizer::TYPE_FLOAT }, - { "1e3", Tokenizer::TYPE_FLOAT }, - { "1E3", Tokenizer::TYPE_FLOAT }, - { "1e-3", Tokenizer::TYPE_FLOAT }, - { "1e+3", Tokenizer::TYPE_FLOAT }, - { "1.e3", Tokenizer::TYPE_FLOAT }, - { "1.2e3", Tokenizer::TYPE_FLOAT }, - { ".1", Tokenizer::TYPE_FLOAT }, - { ".1e3", Tokenizer::TYPE_FLOAT }, - { ".1e-3", Tokenizer::TYPE_FLOAT }, - { ".1e+3", Tokenizer::TYPE_FLOAT }, + // Test floats. + {"123.45", Tokenizer::TYPE_FLOAT}, + {"1.", Tokenizer::TYPE_FLOAT}, + {"1e3", Tokenizer::TYPE_FLOAT}, + {"1E3", Tokenizer::TYPE_FLOAT}, + {"1e-3", Tokenizer::TYPE_FLOAT}, + {"1e+3", Tokenizer::TYPE_FLOAT}, + {"1.e3", Tokenizer::TYPE_FLOAT}, + {"1.2e3", Tokenizer::TYPE_FLOAT}, + {".1", Tokenizer::TYPE_FLOAT}, + {".1e3", Tokenizer::TYPE_FLOAT}, + {".1e-3", Tokenizer::TYPE_FLOAT}, + {".1e+3", Tokenizer::TYPE_FLOAT}, - // Test strings. - { "'hello'", Tokenizer::TYPE_STRING }, - { "\"foo\"", Tokenizer::TYPE_STRING }, - { "'a\"b'", Tokenizer::TYPE_STRING }, - { "\"a'b\"", Tokenizer::TYPE_STRING }, - { "'a\\'b'", Tokenizer::TYPE_STRING }, - { "\"a\\\"b\"", Tokenizer::TYPE_STRING }, - { "'\\xf'", Tokenizer::TYPE_STRING }, - { "'\\0'", Tokenizer::TYPE_STRING }, + // Test strings. + {"'hello'", Tokenizer::TYPE_STRING}, + {"\"foo\"", Tokenizer::TYPE_STRING}, + {"'a\"b'", Tokenizer::TYPE_STRING}, + {"\"a'b\"", Tokenizer::TYPE_STRING}, + {"'a\\'b'", Tokenizer::TYPE_STRING}, + {"\"a\\\"b\"", Tokenizer::TYPE_STRING}, + {"'\\xf'", Tokenizer::TYPE_STRING}, + {"'\\0'", Tokenizer::TYPE_STRING}, - // Test symbols. - { "+", Tokenizer::TYPE_SYMBOL }, - { ".", Tokenizer::TYPE_SYMBOL }, + // Test symbols. + {"+", Tokenizer::TYPE_SYMBOL}, + {".", Tokenizer::TYPE_SYMBOL}, }; TEST_2D(TokenizerTest, SimpleTokens, kSimpleTokenCases, kBlockSizes) { // Set up the tokenizer. TestInputStream input(kSimpleTokenCases_case.input.data(), - kSimpleTokenCases_case.input.size(), - kBlockSizes_case); + kSimpleTokenCases_case.input.size(), kBlockSizes_case); TestErrorCollector error_collector; Tokenizer tokenizer(&input, &error_collector); @@ -326,7 +324,7 @@ TEST_1D(TokenizerTest, FloatSuffix, kBlockSizes) { // In each case, the input is parsed to produce a list of tokens. The // last token in "output" must have type TYPE_END. struct MultiTokenCase { - string input; + std::string input; Tokenizer::Token output[10]; // The compiler wants a constant array // size for initialization to work. There // is no reason this can't be increased if @@ -339,92 +337,101 @@ inline std::ostream& operator<<(std::ostream& out, } MultiTokenCase kMultiTokenCases[] = { - // Test empty input. - { "", { - { Tokenizer::TYPE_END , "" , 0, 0, 0 }, - }}, + // Test empty input. + {"", + { + {Tokenizer::TYPE_END, "", 0, 0, 0}, + }}, - // Test all token types at the same time. - { "foo 1 1.2 + 'bar'", { - { Tokenizer::TYPE_IDENTIFIER, "foo" , 0, 0, 3 }, - { Tokenizer::TYPE_INTEGER , "1" , 0, 4, 5 }, - { Tokenizer::TYPE_FLOAT , "1.2" , 0, 6, 9 }, - { Tokenizer::TYPE_SYMBOL , "+" , 0, 10, 11 }, - { Tokenizer::TYPE_STRING , "'bar'", 0, 12, 17 }, - { Tokenizer::TYPE_END , "" , 0, 17, 17 }, - }}, + // Test all token types at the same time. + {"foo 1 1.2 + 'bar'", + { + {Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0, 3}, + {Tokenizer::TYPE_INTEGER, "1", 0, 4, 5}, + {Tokenizer::TYPE_FLOAT, "1.2", 0, 6, 9}, + {Tokenizer::TYPE_SYMBOL, "+", 0, 10, 11}, + {Tokenizer::TYPE_STRING, "'bar'", 0, 12, 17}, + {Tokenizer::TYPE_END, "", 0, 17, 17}, + }}, - // Test that consecutive symbols are parsed as separate tokens. - { "!@+%", { - { Tokenizer::TYPE_SYMBOL , "!" , 0, 0, 1 }, - { Tokenizer::TYPE_SYMBOL , "@" , 0, 1, 2 }, - { Tokenizer::TYPE_SYMBOL , "+" , 0, 2, 3 }, - { Tokenizer::TYPE_SYMBOL , "%" , 0, 3, 4 }, - { Tokenizer::TYPE_END , "" , 0, 4, 4 }, - }}, + // Test that consecutive symbols are parsed as separate tokens. + {"!@+%", + { + {Tokenizer::TYPE_SYMBOL, "!", 0, 0, 1}, + {Tokenizer::TYPE_SYMBOL, "@", 0, 1, 2}, + {Tokenizer::TYPE_SYMBOL, "+", 0, 2, 3}, + {Tokenizer::TYPE_SYMBOL, "%", 0, 3, 4}, + {Tokenizer::TYPE_END, "", 0, 4, 4}, + }}, - // Test that newlines affect line numbers correctly. - { "foo bar\nrab oof", { - { Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0, 3 }, - { Tokenizer::TYPE_IDENTIFIER, "bar", 0, 4, 7 }, - { Tokenizer::TYPE_IDENTIFIER, "rab", 1, 0, 3 }, - { Tokenizer::TYPE_IDENTIFIER, "oof", 1, 4, 7 }, - { Tokenizer::TYPE_END , "" , 1, 7, 7 }, - }}, + // Test that newlines affect line numbers correctly. + {"foo bar\nrab oof", + { + {Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0, 3}, + {Tokenizer::TYPE_IDENTIFIER, "bar", 0, 4, 7}, + {Tokenizer::TYPE_IDENTIFIER, "rab", 1, 0, 3}, + {Tokenizer::TYPE_IDENTIFIER, "oof", 1, 4, 7}, + {Tokenizer::TYPE_END, "", 1, 7, 7}, + }}, - // Test that tabs affect column numbers correctly. - { "foo\tbar \tbaz", { - { Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0, 3 }, - { Tokenizer::TYPE_IDENTIFIER, "bar", 0, 8, 11 }, - { Tokenizer::TYPE_IDENTIFIER, "baz", 0, 16, 19 }, - { Tokenizer::TYPE_END , "" , 0, 19, 19 }, - }}, + // Test that tabs affect column numbers correctly. + {"foo\tbar \tbaz", + { + {Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0, 3}, + {Tokenizer::TYPE_IDENTIFIER, "bar", 0, 8, 11}, + {Tokenizer::TYPE_IDENTIFIER, "baz", 0, 16, 19}, + {Tokenizer::TYPE_END, "", 0, 19, 19}, + }}, - // Test that tabs in string literals affect column numbers correctly. - { "\"foo\tbar\" baz", { - { Tokenizer::TYPE_STRING , "\"foo\tbar\"", 0, 0, 12 }, - { Tokenizer::TYPE_IDENTIFIER, "baz" , 0, 13, 16 }, - { Tokenizer::TYPE_END , "" , 0, 16, 16 }, - }}, + // Test that tabs in string literals affect column numbers correctly. + {"\"foo\tbar\" baz", + { + {Tokenizer::TYPE_STRING, "\"foo\tbar\"", 0, 0, 12}, + {Tokenizer::TYPE_IDENTIFIER, "baz", 0, 13, 16}, + {Tokenizer::TYPE_END, "", 0, 16, 16}, + }}, - // Test that line comments are ignored. - { "foo // This is a comment\n" - "bar // This is another comment", { - { Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0, 3 }, - { Tokenizer::TYPE_IDENTIFIER, "bar", 1, 0, 3 }, - { Tokenizer::TYPE_END , "" , 1, 30, 30 }, - }}, + // Test that line comments are ignored. + {"foo // This is a comment\n" + "bar // This is another comment", + { + {Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0, 3}, + {Tokenizer::TYPE_IDENTIFIER, "bar", 1, 0, 3}, + {Tokenizer::TYPE_END, "", 1, 30, 30}, + }}, - // Test that block comments are ignored. - { "foo /* This is a block comment */ bar", { - { Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0, 3 }, - { Tokenizer::TYPE_IDENTIFIER, "bar", 0, 34, 37 }, - { Tokenizer::TYPE_END , "" , 0, 37, 37 }, - }}, + // Test that block comments are ignored. + {"foo /* This is a block comment */ bar", + { + {Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0, 3}, + {Tokenizer::TYPE_IDENTIFIER, "bar", 0, 34, 37}, + {Tokenizer::TYPE_END, "", 0, 37, 37}, + }}, - // Test that sh-style comments are not ignored by default. - { "foo # bar\n" - "baz", { - { Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0, 3 }, - { Tokenizer::TYPE_SYMBOL , "#" , 0, 4, 5 }, - { Tokenizer::TYPE_IDENTIFIER, "bar", 0, 6, 9 }, - { Tokenizer::TYPE_IDENTIFIER, "baz", 1, 0, 3 }, - { Tokenizer::TYPE_END , "" , 1, 3, 3 }, - }}, + // Test that sh-style comments are not ignored by default. + {"foo # bar\n" + "baz", + { + {Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0, 3}, + {Tokenizer::TYPE_SYMBOL, "#", 0, 4, 5}, + {Tokenizer::TYPE_IDENTIFIER, "bar", 0, 6, 9}, + {Tokenizer::TYPE_IDENTIFIER, "baz", 1, 0, 3}, + {Tokenizer::TYPE_END, "", 1, 3, 3}, + }}, - // Test all whitespace chars - { "foo\n\t\r\v\fbar", { - { Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0, 3 }, - { Tokenizer::TYPE_IDENTIFIER, "bar", 1, 11, 14 }, - { Tokenizer::TYPE_END , "" , 1, 14, 14 }, - }}, + // Test all whitespace chars + {"foo\n\t\r\v\fbar", + { + {Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0, 3}, + {Tokenizer::TYPE_IDENTIFIER, "bar", 1, 11, 14}, + {Tokenizer::TYPE_END, "", 1, 14, 14}, + }}, }; TEST_2D(TokenizerTest, MultipleTokens, kMultiTokenCases, kBlockSizes) { // Set up the tokenizer. TestInputStream input(kMultiTokenCases_case.input.data(), - kMultiTokenCases_case.input.size(), - kBlockSizes_case); + kMultiTokenCases_case.input.size(), kBlockSizes_case); TestErrorCollector error_collector; Tokenizer tokenizer(&input, &error_collector); @@ -479,14 +486,14 @@ TEST_2D(TokenizerTest, MultipleTokens, kMultiTokenCases, kBlockSizes) { TEST_1D(TokenizerTest, ShCommentStyle, kBlockSizes) { // Test the "comment_style" option. - const char* text = "foo # bar\n" - "baz // qux\n" - "corge /* grault */\n" - "garply"; + const char* text = + "foo # bar\n" + "baz // qux\n" + "corge /* grault */\n" + "garply"; const char* const kTokens[] = {"foo", // "# bar" is ignored - "baz", "/", "/", "qux", - "corge", "/", "*", "grault", "*", "/", - "garply"}; + "baz", "/", "/", "qux", "corge", "/", + "*", "grault", "*", "/", "garply"}; // Set up the tokenizer. TestInputStream input(text, strlen(text), kBlockSizes_case); @@ -513,7 +520,7 @@ TEST_1D(TokenizerTest, ShCommentStyle, kBlockSizes) { // In each case, the input is expected to have two tokens named "prev" and // "next" with comments in between. struct DocCommentCase { - string input; + std::string input; const char* prev_trailing_comments; const char* detached_comments[10]; @@ -526,164 +533,136 @@ inline std::ostream& operator<<(std::ostream& out, } DocCommentCase kDocCommentCases[] = { - { - "prev next", + {"prev next", - "", - {}, - "" - }, + "", + {}, + ""}, - { - "prev /* ignored */ next", + {"prev /* ignored */ next", - "", - {}, - "" - }, + "", + {}, + ""}, - { - "prev // trailing comment\n" - "next", + {"prev // trailing comment\n" + "next", - " trailing comment\n", - {}, - "" - }, + " trailing comment\n", + {}, + ""}, - { - "prev\n" - "// leading comment\n" - "// line 2\n" - "next", + {"prev\n" + "// leading comment\n" + "// line 2\n" + "next", - "", - {}, - " leading comment\n" - " line 2\n" - }, + "", + {}, + " leading comment\n" + " line 2\n"}, - { - "prev\n" - "// trailing comment\n" - "// line 2\n" - "\n" - "next", + {"prev\n" + "// trailing comment\n" + "// line 2\n" + "\n" + "next", - " trailing comment\n" - " line 2\n", - {}, - "" - }, + " trailing comment\n" + " line 2\n", + {}, + ""}, - { - "prev // trailing comment\n" - "// leading comment\n" - "// line 2\n" - "next", + {"prev // trailing comment\n" + "// leading comment\n" + "// line 2\n" + "next", - " trailing comment\n", - {}, - " leading comment\n" - " line 2\n" - }, + " trailing comment\n", + {}, + " leading comment\n" + " line 2\n"}, - { - "prev /* trailing block comment */\n" - "/* leading block comment\n" - " * line 2\n" - " * line 3 */" - "next", + {"prev /* trailing block comment */\n" + "/* leading block comment\n" + " * line 2\n" + " * line 3 */" + "next", - " trailing block comment ", - {}, - " leading block comment\n" - " line 2\n" - " line 3 " - }, + " trailing block comment ", + {}, + " leading block comment\n" + " line 2\n" + " line 3 "}, - { - "prev\n" - "/* trailing block comment\n" - " * line 2\n" - " * line 3\n" - " */\n" - "/* leading block comment\n" - " * line 2\n" - " * line 3 */" - "next", + {"prev\n" + "/* trailing block comment\n" + " * line 2\n" + " * line 3\n" + " */\n" + "/* leading block comment\n" + " * line 2\n" + " * line 3 */" + "next", - " trailing block comment\n" - " line 2\n" - " line 3\n", - {}, - " leading block comment\n" - " line 2\n" - " line 3 " - }, + " trailing block comment\n" + " line 2\n" + " line 3\n", + {}, + " leading block comment\n" + " line 2\n" + " line 3 "}, - { - "prev\n" - "// trailing comment\n" - "\n" - "// detached comment\n" - "// line 2\n" - "\n" - "// second detached comment\n" - "/* third detached comment\n" - " * line 2 */\n" - "// leading comment\n" - "next", + {"prev\n" + "// trailing comment\n" + "\n" + "// detached comment\n" + "// line 2\n" + "\n" + "// second detached comment\n" + "/* third detached comment\n" + " * line 2 */\n" + "// leading comment\n" + "next", - " trailing comment\n", - { - " detached comment\n" - " line 2\n", - " second detached comment\n", - " third detached comment\n" - " line 2 " - }, - " leading comment\n" - }, + " trailing comment\n", + {" detached comment\n" + " line 2\n", + " second detached comment\n", + " third detached comment\n" + " line 2 "}, + " leading comment\n"}, - { - "prev /**/\n" - "\n" - "// detached comment\n" - "\n" - "// leading comment\n" - "next", + {"prev /**/\n" + "\n" + "// detached comment\n" + "\n" + "// leading comment\n" + "next", - "", - { - " detached comment\n" - }, - " leading comment\n" - }, + "", + {" detached comment\n"}, + " leading comment\n"}, - { - "prev /**/\n" - "// leading comment\n" - "next", + {"prev /**/\n" + "// leading comment\n" + "next", - "", - {}, - " leading comment\n" - }, - }; + "", + {}, + " leading comment\n"}, +}; TEST_2D(TokenizerTest, DocComments, kDocCommentCases, kBlockSizes) { // Set up the tokenizer. TestInputStream input(kDocCommentCases_case.input.data(), - kDocCommentCases_case.input.size(), - kBlockSizes_case); + kDocCommentCases_case.input.size(), kBlockSizes_case); TestErrorCollector error_collector; Tokenizer tokenizer(&input, &error_collector); // Set up a second tokenizer where we'll pass all NULLs to NextWithComments(). TestInputStream input2(kDocCommentCases_case.input.data(), - kDocCommentCases_case.input.size(), - kBlockSizes_case); + kDocCommentCases_case.input.size(), kBlockSizes_case); Tokenizer tokenizer2(&input2, &error_collector); tokenizer.Next(); @@ -692,9 +671,9 @@ TEST_2D(TokenizerTest, DocComments, kDocCommentCases, kBlockSizes) { EXPECT_EQ("prev", tokenizer.current().text); EXPECT_EQ("prev", tokenizer2.current().text); - string prev_trailing_comments; - std::vector detached_comments; - string next_leading_comments; + std::string prev_trailing_comments; + std::vector detached_comments; + std::string next_leading_comments; tokenizer.NextWithComments(&prev_trailing_comments, &detached_comments, &next_leading_comments); tokenizer2.NextWithComments(NULL, NULL, NULL); @@ -707,16 +686,14 @@ TEST_2D(TokenizerTest, DocComments, kDocCommentCases, kBlockSizes) { for (int i = 0; i < detached_comments.size(); i++) { ASSERT_LT(i, GOOGLE_ARRAYSIZE(kDocCommentCases)); ASSERT_TRUE(kDocCommentCases_case.detached_comments[i] != NULL); - EXPECT_EQ(kDocCommentCases_case.detached_comments[i], - detached_comments[i]); + EXPECT_EQ(kDocCommentCases_case.detached_comments[i], detached_comments[i]); } // Verify that we matched all the detached comments. EXPECT_EQ(NULL, - kDocCommentCases_case.detached_comments[detached_comments.size()]); + kDocCommentCases_case.detached_comments[detached_comments.size()]); - EXPECT_EQ(kDocCommentCases_case.next_leading_comments, - next_leading_comments); + EXPECT_EQ(kDocCommentCases_case.next_leading_comments, next_leading_comments); } // ------------------------------------------------------------------- @@ -745,30 +722,30 @@ TEST_F(TokenizerTest, ParseInteger) { EXPECT_FALSE(Tokenizer::ParseInteger("-1", kuint64max, &i)); // Test overflows. - EXPECT_TRUE (Tokenizer::ParseInteger("0", 0, &i)); + EXPECT_TRUE(Tokenizer::ParseInteger("0", 0, &i)); EXPECT_FALSE(Tokenizer::ParseInteger("1", 0, &i)); - EXPECT_TRUE (Tokenizer::ParseInteger("1", 1, &i)); - EXPECT_TRUE (Tokenizer::ParseInteger("12345", 12345, &i)); + EXPECT_TRUE(Tokenizer::ParseInteger("1", 1, &i)); + EXPECT_TRUE(Tokenizer::ParseInteger("12345", 12345, &i)); EXPECT_FALSE(Tokenizer::ParseInteger("12346", 12345, &i)); - EXPECT_TRUE (Tokenizer::ParseInteger("0xFFFFFFFFFFFFFFFF" , kuint64max, &i)); + EXPECT_TRUE(Tokenizer::ParseInteger("0xFFFFFFFFFFFFFFFF", kuint64max, &i)); EXPECT_FALSE(Tokenizer::ParseInteger("0x10000000000000000", kuint64max, &i)); } TEST_F(TokenizerTest, ParseFloat) { - EXPECT_DOUBLE_EQ(1 , Tokenizer::ParseFloat("1.")); - EXPECT_DOUBLE_EQ(1e3 , Tokenizer::ParseFloat("1e3")); - EXPECT_DOUBLE_EQ(1e3 , Tokenizer::ParseFloat("1E3")); + EXPECT_DOUBLE_EQ(1, Tokenizer::ParseFloat("1.")); + EXPECT_DOUBLE_EQ(1e3, Tokenizer::ParseFloat("1e3")); + EXPECT_DOUBLE_EQ(1e3, Tokenizer::ParseFloat("1E3")); EXPECT_DOUBLE_EQ(1.5e3, Tokenizer::ParseFloat("1.5e3")); - EXPECT_DOUBLE_EQ(.1 , Tokenizer::ParseFloat(".1")); - EXPECT_DOUBLE_EQ(.25 , Tokenizer::ParseFloat(".25")); - EXPECT_DOUBLE_EQ(.1e3 , Tokenizer::ParseFloat(".1e3")); + EXPECT_DOUBLE_EQ(.1, Tokenizer::ParseFloat(".1")); + EXPECT_DOUBLE_EQ(.25, Tokenizer::ParseFloat(".25")); + EXPECT_DOUBLE_EQ(.1e3, Tokenizer::ParseFloat(".1e3")); EXPECT_DOUBLE_EQ(.25e3, Tokenizer::ParseFloat(".25e3")); EXPECT_DOUBLE_EQ(.1e+3, Tokenizer::ParseFloat(".1e+3")); EXPECT_DOUBLE_EQ(.1e-3, Tokenizer::ParseFloat(".1e-3")); - EXPECT_DOUBLE_EQ(5 , Tokenizer::ParseFloat("5")); + EXPECT_DOUBLE_EQ(5, Tokenizer::ParseFloat("5")); EXPECT_DOUBLE_EQ(6e-12, Tokenizer::ParseFloat("6e-12")); - EXPECT_DOUBLE_EQ(1.2 , Tokenizer::ParseFloat("1.2")); - EXPECT_DOUBLE_EQ(1.e2 , Tokenizer::ParseFloat("1.e2")); + EXPECT_DOUBLE_EQ(1.2, Tokenizer::ParseFloat("1.2")); + EXPECT_DOUBLE_EQ(1.e2, Tokenizer::ParseFloat("1.e2")); // Test invalid integers that may still be tokenized as integers. EXPECT_DOUBLE_EQ(1, Tokenizer::ParseFloat("1e")); @@ -782,22 +759,25 @@ TEST_F(TokenizerTest, ParseFloat) { // These should parse successfully even though they are out of range. // Overflows become infinity and underflows become zero. - EXPECT_EQ( 0.0, Tokenizer::ParseFloat("1e-9999999999999999999999999999")); + EXPECT_EQ(0.0, Tokenizer::ParseFloat("1e-9999999999999999999999999999")); EXPECT_EQ(HUGE_VAL, Tokenizer::ParseFloat("1e+9999999999999999999999999999")); #ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet // Test invalid integers that will never be tokenized as integers. - EXPECT_DEBUG_DEATH(Tokenizer::ParseFloat("zxy"), - "passed text that could not have been tokenized as a float"); - EXPECT_DEBUG_DEATH(Tokenizer::ParseFloat("1-e0"), - "passed text that could not have been tokenized as a float"); - EXPECT_DEBUG_DEATH(Tokenizer::ParseFloat("-1.0"), - "passed text that could not have been tokenized as a float"); + EXPECT_DEBUG_DEATH( + Tokenizer::ParseFloat("zxy"), + "passed text that could not have been tokenized as a float"); + EXPECT_DEBUG_DEATH( + Tokenizer::ParseFloat("1-e0"), + "passed text that could not have been tokenized as a float"); + EXPECT_DEBUG_DEATH( + Tokenizer::ParseFloat("-1.0"), + "passed text that could not have been tokenized as a float"); #endif // PROTOBUF_HAS_DEATH_TEST } TEST_F(TokenizerTest, ParseString) { - string output; + std::string output; Tokenizer::ParseString("'hello'", &output); EXPECT_EQ("hello", output); Tokenizer::ParseString("\"blah\\nblah2\"", &output); @@ -833,14 +813,15 @@ TEST_F(TokenizerTest, ParseString) { // Test invalid strings that will never be tokenized as strings. #ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet - EXPECT_DEBUG_DEATH(Tokenizer::ParseString("", &output), - "passed text that could not have been tokenized as a string"); + EXPECT_DEBUG_DEATH( + Tokenizer::ParseString("", &output), + "passed text that could not have been tokenized as a string"); #endif // PROTOBUF_HAS_DEATH_TEST } TEST_F(TokenizerTest, ParseStringAppend) { // Check that ParseString and ParseStringAppend differ. - string output("stuff+"); + std::string output("stuff+"); Tokenizer::ParseStringAppend("'hello'", &output); EXPECT_EQ("stuff+hello", output); Tokenizer::ParseString("'hello'", &output); @@ -852,7 +833,7 @@ TEST_F(TokenizerTest, ParseStringAppend) { // Each case parses some input text, ignoring the tokens produced, and // checks that the error output matches what is expected. struct ErrorCase { - string input; + std::string input; bool recoverable; // True if the tokenizer should be able to recover and // parse more tokens after seeing this error. Cases // for which this is true must end with "foo" as @@ -865,93 +846,76 @@ inline std::ostream& operator<<(std::ostream& out, const ErrorCase& test_case) { } ErrorCase kErrorCases[] = { - // String errors. - { "'\\l' foo", true, - "0:2: Invalid escape sequence in string literal.\n" }, - { "'\\X' foo", true, - "0:2: Invalid escape sequence in string literal.\n" }, - { "'\\x' foo", true, - "0:3: Expected hex digits for escape sequence.\n" }, - { "'foo", false, - "0:4: Unexpected end of string.\n" }, - { "'bar\nfoo", true, - "0:4: String literals cannot cross line boundaries.\n" }, - { "'\\u01' foo", true, - "0:5: Expected four hex digits for \\u escape sequence.\n" }, - { "'\\u01' foo", true, - "0:5: Expected four hex digits for \\u escape sequence.\n" }, - { "'\\uXYZ' foo", true, - "0:3: Expected four hex digits for \\u escape sequence.\n" }, + // String errors. + {"'\\l' foo", true, "0:2: Invalid escape sequence in string literal.\n"}, + {"'\\X' foo", true, "0:2: Invalid escape sequence in string literal.\n"}, + {"'\\x' foo", true, "0:3: Expected hex digits for escape sequence.\n"}, + {"'foo", false, "0:4: Unexpected end of string.\n"}, + {"'bar\nfoo", true, "0:4: String literals cannot cross line boundaries.\n"}, + {"'\\u01' foo", true, + "0:5: Expected four hex digits for \\u escape sequence.\n"}, + {"'\\u01' foo", true, + "0:5: Expected four hex digits for \\u escape sequence.\n"}, + {"'\\uXYZ' foo", true, + "0:3: Expected four hex digits for \\u escape sequence.\n"}, - // Integer errors. - { "123foo", true, - "0:3: Need space between number and identifier.\n" }, + // Integer errors. + {"123foo", true, "0:3: Need space between number and identifier.\n"}, - // Hex/octal errors. - { "0x foo", true, - "0:2: \"0x\" must be followed by hex digits.\n" }, - { "0541823 foo", true, - "0:4: Numbers starting with leading zero must be in octal.\n" }, - { "0x123z foo", true, - "0:5: Need space between number and identifier.\n" }, - { "0x123.4 foo", true, - "0:5: Hex and octal numbers must be integers.\n" }, - { "0123.4 foo", true, - "0:4: Hex and octal numbers must be integers.\n" }, + // Hex/octal errors. + {"0x foo", true, "0:2: \"0x\" must be followed by hex digits.\n"}, + {"0541823 foo", true, + "0:4: Numbers starting with leading zero must be in octal.\n"}, + {"0x123z foo", true, "0:5: Need space between number and identifier.\n"}, + {"0x123.4 foo", true, "0:5: Hex and octal numbers must be integers.\n"}, + {"0123.4 foo", true, "0:4: Hex and octal numbers must be integers.\n"}, - // Float errors. - { "1e foo", true, - "0:2: \"e\" must be followed by exponent.\n" }, - { "1e- foo", true, - "0:3: \"e\" must be followed by exponent.\n" }, - { "1.2.3 foo", true, - "0:3: Already saw decimal point or exponent; can't have another one.\n" }, - { "1e2.3 foo", true, - "0:3: Already saw decimal point or exponent; can't have another one.\n" }, - { "a.1 foo", true, - "0:1: Need space between identifier and decimal point.\n" }, - // allow_f_after_float not enabled, so this should be an error. - { "1.0f foo", true, - "0:3: Need space between number and identifier.\n" }, + // Float errors. + {"1e foo", true, "0:2: \"e\" must be followed by exponent.\n"}, + {"1e- foo", true, "0:3: \"e\" must be followed by exponent.\n"}, + {"1.2.3 foo", true, + "0:3: Already saw decimal point or exponent; can't have another one.\n"}, + {"1e2.3 foo", true, + "0:3: Already saw decimal point or exponent; can't have another one.\n"}, + {"a.1 foo", true, + "0:1: Need space between identifier and decimal point.\n"}, + // allow_f_after_float not enabled, so this should be an error. + {"1.0f foo", true, "0:3: Need space between number and identifier.\n"}, - // Block comment errors. - { "/*", false, - "0:2: End-of-file inside block comment.\n" - "0:0: Comment started here.\n"}, - { "/*/*/ foo", true, - "0:3: \"/*\" inside block comment. Block comments cannot be nested.\n"}, + // Block comment errors. + {"/*", false, + "0:2: End-of-file inside block comment.\n" + "0:0: Comment started here.\n"}, + {"/*/*/ foo", true, + "0:3: \"/*\" inside block comment. Block comments cannot be nested.\n"}, - // Control characters. Multiple consecutive control characters should only - // produce one error. - { "\b foo", true, - "0:0: Invalid control characters encountered in text.\n" }, - { "\b\b foo", true, - "0:0: Invalid control characters encountered in text.\n" }, + // Control characters. Multiple consecutive control characters should only + // produce one error. + {"\b foo", true, "0:0: Invalid control characters encountered in text.\n"}, + {"\b\b foo", true, + "0:0: Invalid control characters encountered in text.\n"}, - // Check that control characters at end of input don't result in an - // infinite loop. - { "\b", false, - "0:0: Invalid control characters encountered in text.\n" }, + // Check that control characters at end of input don't result in an + // infinite loop. + {"\b", false, "0:0: Invalid control characters encountered in text.\n"}, - // Check recovery from '\0'. We have to explicitly specify the length of - // these strings because otherwise the string constructor will just call - // strlen() which will see the first '\0' and think that is the end of the - // string. - { string("\0foo", 4), true, - "0:0: Invalid control characters encountered in text.\n" }, - { string("\0\0foo", 5), true, - "0:0: Invalid control characters encountered in text.\n" }, + // Check recovery from '\0'. We have to explicitly specify the length of + // these strings because otherwise the string constructor will just call + // strlen() which will see the first '\0' and think that is the end of the + // string. + {std::string("\0foo", 4), true, + "0:0: Invalid control characters encountered in text.\n"}, + {std::string("\0\0foo", 5), true, + "0:0: Invalid control characters encountered in text.\n"}, - // Check error from high order bits set - { "\300foo", true, - "0:0: Interpreting non ascii codepoint 192.\n" }, + // Check error from high order bits set + {"\300foo", true, "0:0: Interpreting non ascii codepoint 192.\n"}, }; TEST_2D(TokenizerTest, Errors, kErrorCases, kBlockSizes) { // Set up the tokenizer. TestInputStream input(kErrorCases_case.input.data(), - kErrorCases_case.input.size(), - kBlockSizes_case); + kErrorCases_case.input.size(), kBlockSizes_case); TestErrorCollector error_collector; Tokenizer tokenizer(&input, &error_collector); @@ -973,7 +937,7 @@ TEST_2D(TokenizerTest, Errors, kErrorCases, kBlockSizes) { // ------------------------------------------------------------------- TEST_1D(TokenizerTest, BackUpOnDestruction, kBlockSizes) { - string text = "foo bar"; + std::string text = "foo bar"; TestInputStream input(text.data(), text.size(), kBlockSizes_case); // Create a tokenizer, read one token, then destroy it. diff --git a/third_party/protobuf/src/google/protobuf/io/zero_copy_stream.h b/third_party/protobuf/src/google/protobuf/io/zero_copy_stream.h index 62ace7ae..de2374b5 100644 --- a/third_party/protobuf/src/google/protobuf/io/zero_copy_stream.h +++ b/third_party/protobuf/src/google/protobuf/io/zero_copy_stream.h @@ -110,8 +110,10 @@ #include #include -namespace google { +#include + +namespace google { namespace protobuf { namespace io { @@ -121,7 +123,7 @@ class ZeroCopyOutputStream; // Abstract interface similar to an input stream but designed to minimize // copying. -class LIBPROTOBUF_EXPORT ZeroCopyInputStream { +class PROTOBUF_EXPORT ZeroCopyInputStream { public: ZeroCopyInputStream() {} virtual ~ZeroCopyInputStream() {} @@ -178,7 +180,7 @@ class LIBPROTOBUF_EXPORT ZeroCopyInputStream { // Abstract interface similar to an output stream but designed to minimize // copying. -class LIBPROTOBUF_EXPORT ZeroCopyOutputStream { +class PROTOBUF_EXPORT ZeroCopyOutputStream { public: ZeroCopyOutputStream() {} virtual ~ZeroCopyOutputStream() {} @@ -243,6 +245,8 @@ class LIBPROTOBUF_EXPORT ZeroCopyOutputStream { } // namespace io } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_H__ diff --git a/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl.cc b/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl.cc index dd921135..4af76b78 100644 --- a/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl.cc +++ b/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl.cc @@ -33,19 +33,19 @@ // Sanjay Ghemawat, Jeff Dean, and others. #ifndef _MSC_VER -#include -#include -#include #include +#include +#include +#include #endif #include -#include #include -#include +#include #include #include +#include +#include #include -#include namespace google { @@ -58,11 +58,11 @@ namespace io { #define lseek(fd, offset, origin) ((off_t)-1) // DO NOT include , instead create functions in io_win32.{h,cc} and import // them like we do below. -using google::protobuf::internal::win32::access; -using google::protobuf::internal::win32::close; -using google::protobuf::internal::win32::open; -using google::protobuf::internal::win32::read; -using google::protobuf::internal::win32::write; +using google::protobuf::io::win32::access; +using google::protobuf::io::win32::close; +using google::protobuf::io::win32::open; +using google::protobuf::io::win32::read; +using google::protobuf::io::win32::write; #endif namespace { @@ -78,42 +78,30 @@ int close_no_eintr(int fd) { } // namespace - // =================================================================== FileInputStream::FileInputStream(int file_descriptor, int block_size) - : copying_input_(file_descriptor), - impl_(©ing_input_, block_size) { -} + : copying_input_(file_descriptor), impl_(©ing_input_, block_size) {} -bool FileInputStream::Close() { - return copying_input_.Close(); -} +bool FileInputStream::Close() { return copying_input_.Close(); } bool FileInputStream::Next(const void** data, int* size) { return impl_.Next(data, size); } -void FileInputStream::BackUp(int count) { - impl_.BackUp(count); -} +void FileInputStream::BackUp(int count) { impl_.BackUp(count); } -bool FileInputStream::Skip(int count) { - return impl_.Skip(count); -} +bool FileInputStream::Skip(int count) { return impl_.Skip(count); } -int64 FileInputStream::ByteCount() const { - return impl_.ByteCount(); -} +int64 FileInputStream::ByteCount() const { return impl_.ByteCount(); } FileInputStream::CopyingFileInputStream::CopyingFileInputStream( int file_descriptor) - : file_(file_descriptor), - close_on_delete_(false), - is_closed_(false), - errno_(0), - previous_seek_failed_(false) { -} + : file_(file_descriptor), + close_on_delete_(false), + is_closed_(false), + errno_(0), + previous_seek_failed_(false) {} FileInputStream::CopyingFileInputStream::~CopyingFileInputStream() { if (close_on_delete_) { @@ -157,8 +145,7 @@ int FileInputStream::CopyingFileInputStream::Read(void* buffer, int size) { int FileInputStream::CopyingFileInputStream::Skip(int count) { GOOGLE_CHECK(!is_closed_); - if (!previous_seek_failed_ && - lseek(file_, count, SEEK_CUR) != (off_t)-1) { + if (!previous_seek_failed_ && lseek(file_, count, SEEK_CUR) != (off_t)-1) { // Seek succeeded. return count; } else { @@ -176,42 +163,31 @@ int FileInputStream::CopyingFileInputStream::Skip(int count) { // =================================================================== FileOutputStream::FileOutputStream(int file_descriptor, int block_size) - : copying_output_(file_descriptor), - impl_(©ing_output_, block_size) { -} + : copying_output_(file_descriptor), impl_(©ing_output_, block_size) {} -FileOutputStream::~FileOutputStream() { - impl_.Flush(); -} +FileOutputStream::~FileOutputStream() { impl_.Flush(); } bool FileOutputStream::Close() { bool flush_succeeded = impl_.Flush(); return copying_output_.Close() && flush_succeeded; } -bool FileOutputStream::Flush() { - return impl_.Flush(); -} +bool FileOutputStream::Flush() { return impl_.Flush(); } bool FileOutputStream::Next(void** data, int* size) { return impl_.Next(data, size); } -void FileOutputStream::BackUp(int count) { - impl_.BackUp(count); -} +void FileOutputStream::BackUp(int count) { impl_.BackUp(count); } -int64 FileOutputStream::ByteCount() const { - return impl_.ByteCount(); -} +int64 FileOutputStream::ByteCount() const { return impl_.ByteCount(); } FileOutputStream::CopyingFileOutputStream::CopyingFileOutputStream( int file_descriptor) - : file_(file_descriptor), - close_on_delete_(false), - is_closed_(false), - errno_(0) { -} + : file_(file_descriptor), + close_on_delete_(false), + is_closed_(false), + errno_(0) {} FileOutputStream::CopyingFileOutputStream::~CopyingFileOutputStream() { if (close_on_delete_) { @@ -236,8 +212,8 @@ bool FileOutputStream::CopyingFileOutputStream::Close() { return true; } -bool FileOutputStream::CopyingFileOutputStream::Write( - const void* buffer, int size) { +bool FileOutputStream::CopyingFileOutputStream::Write(const void* buffer, + int size) { GOOGLE_CHECK(!is_closed_); int total_written = 0; @@ -280,17 +256,11 @@ bool IstreamInputStream::Next(const void** data, int* size) { return impl_.Next(data, size); } -void IstreamInputStream::BackUp(int count) { - impl_.BackUp(count); -} +void IstreamInputStream::BackUp(int count) { impl_.BackUp(count); } -bool IstreamInputStream::Skip(int count) { - return impl_.Skip(count); -} +bool IstreamInputStream::Skip(int count) { return impl_.Skip(count); } -int64 IstreamInputStream::ByteCount() const { - return impl_.ByteCount(); -} +int64 IstreamInputStream::ByteCount() const { return impl_.ByteCount(); } IstreamInputStream::CopyingIstreamInputStream::CopyingIstreamInputStream( std::istream* input) @@ -298,8 +268,8 @@ IstreamInputStream::CopyingIstreamInputStream::CopyingIstreamInputStream( IstreamInputStream::CopyingIstreamInputStream::~CopyingIstreamInputStream() {} -int IstreamInputStream::CopyingIstreamInputStream::Read( - void* buffer, int size) { +int IstreamInputStream::CopyingIstreamInputStream::Read(void* buffer, + int size) { input_->read(reinterpret_cast(buffer), size); int result = input_->gcount(); if (result == 0 && input_->fail() && !input_->eof()) { @@ -313,21 +283,15 @@ int IstreamInputStream::CopyingIstreamInputStream::Read( OstreamOutputStream::OstreamOutputStream(std::ostream* output, int block_size) : copying_output_(output), impl_(©ing_output_, block_size) {} -OstreamOutputStream::~OstreamOutputStream() { - impl_.Flush(); -} +OstreamOutputStream::~OstreamOutputStream() { impl_.Flush(); } bool OstreamOutputStream::Next(void** data, int* size) { return impl_.Next(data, size); } -void OstreamOutputStream::BackUp(int count) { - impl_.BackUp(count); -} +void OstreamOutputStream::BackUp(int count) { impl_.BackUp(count); } -int64 OstreamOutputStream::ByteCount() const { - return impl_.ByteCount(); -} +int64 OstreamOutputStream::ByteCount() const { return impl_.ByteCount(); } OstreamOutputStream::CopyingOstreamOutputStream::CopyingOstreamOutputStream( std::ostream* output) @@ -336,8 +300,8 @@ OstreamOutputStream::CopyingOstreamOutputStream::CopyingOstreamOutputStream( OstreamOutputStream::CopyingOstreamOutputStream::~CopyingOstreamOutputStream() { } -bool OstreamOutputStream::CopyingOstreamOutputStream::Write( - const void* buffer, int size) { +bool OstreamOutputStream::CopyingOstreamOutputStream::Write(const void* buffer, + int size) { output_->write(reinterpret_cast(buffer), size); return output_->good(); } @@ -346,7 +310,7 @@ bool OstreamOutputStream::CopyingOstreamOutputStream::Write( ConcatenatingInputStream::ConcatenatingInputStream( ZeroCopyInputStream* const streams[], int count) - : streams_(streams), stream_count_(count), bytes_retired_(0) { + : streams_(streams), stream_count_(count), bytes_retired_(0) { } bool ConcatenatingInputStream::Next(const void** data, int* size) { @@ -402,63 +366,6 @@ int64 ConcatenatingInputStream::ByteCount() const { } -// =================================================================== - -LimitingInputStream::LimitingInputStream(ZeroCopyInputStream* input, - int64 limit) - : input_(input), limit_(limit) { - prior_bytes_read_ = input_->ByteCount(); -} - -LimitingInputStream::~LimitingInputStream() { - // If we overshot the limit, back up. - if (limit_ < 0) input_->BackUp(-limit_); -} - -bool LimitingInputStream::Next(const void** data, int* size) { - if (limit_ <= 0) return false; - if (!input_->Next(data, size)) return false; - - limit_ -= *size; - if (limit_ < 0) { - // We overshot the limit. Reduce *size to hide the rest of the buffer. - *size += limit_; - } - return true; -} - -void LimitingInputStream::BackUp(int count) { - if (limit_ < 0) { - input_->BackUp(count - limit_); - limit_ = count; - } else { - input_->BackUp(count); - limit_ += count; - } -} - -bool LimitingInputStream::Skip(int count) { - if (count > limit_) { - if (limit_ < 0) return false; - input_->Skip(limit_); - limit_ = 0; - return false; - } else { - if (!input_->Skip(count)) return false; - limit_ -= count; - return true; - } -} - -int64 LimitingInputStream::ByteCount() const { - if (limit_ < 0) { - return input_->ByteCount() + limit_ - prior_bytes_read_; - } else { - return input_->ByteCount() - prior_bytes_read_; - } -} - - // =================================================================== } // namespace io diff --git a/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl.h b/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl.h index ea978bfb..fd06c06c 100644 --- a/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl.h +++ b/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl.h @@ -40,18 +40,19 @@ #ifndef GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_H__ #define GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_H__ -#include #include +#include +#include #include #include -#include +#include + namespace google { namespace protobuf { namespace io { - // =================================================================== // A ZeroCopyInputStream which reads from a file descriptor. @@ -60,7 +61,7 @@ namespace io { // The latter will introduce an extra layer of buffering, harming performance. // Also, it's conceivable that FileInputStream could someday be enhanced // to use zero-copy file descriptors on OSs which support them. -class LIBPROTOBUF_EXPORT FileInputStream : public ZeroCopyInputStream { +class PROTOBUF_EXPORT FileInputStream : public ZeroCopyInputStream { public: // Creates a stream that reads from the given Unix file descriptor. // If a block_size is given, it specifies the number of bytes that @@ -84,27 +85,27 @@ class LIBPROTOBUF_EXPORT FileInputStream : public ZeroCopyInputStream { // errno from that error. Otherwise, this is zero. Once an error // occurs, the stream is broken and all subsequent operations will // fail. - int GetErrno() { return copying_input_.GetErrno(); } + int GetErrno() const { return copying_input_.GetErrno(); } // implements ZeroCopyInputStream ---------------------------------- - bool Next(const void** data, int* size); - void BackUp(int count); - bool Skip(int count); - int64 ByteCount() const; + bool Next(const void** data, int* size) override; + void BackUp(int count) override; + bool Skip(int count) override; + int64 ByteCount() const override; private: - class LIBPROTOBUF_EXPORT CopyingFileInputStream : public CopyingInputStream { + class PROTOBUF_EXPORT CopyingFileInputStream : public CopyingInputStream { public: CopyingFileInputStream(int file_descriptor); - ~CopyingFileInputStream(); + ~CopyingFileInputStream() override; bool Close(); void SetCloseOnDelete(bool value) { close_on_delete_ = value; } - int GetErrno() { return errno_; } + int GetErrno() const { return errno_; } // implements CopyingInputStream --------------------------------- - int Read(void* buffer, int size); - int Skip(int count); + int Read(void* buffer, int size) override; + int Skip(int count) override; private: // The file descriptor. @@ -137,14 +138,14 @@ class LIBPROTOBUF_EXPORT FileInputStream : public ZeroCopyInputStream { // harming performance. Also, it's conceivable that FileOutputStream could // someday be enhanced to use zero-copy file descriptors on OSs which // support them. -class LIBPROTOBUF_EXPORT FileOutputStream : public ZeroCopyOutputStream { +class PROTOBUF_EXPORT FileOutputStream : public ZeroCopyOutputStream { public: // Creates a stream that writes to the given Unix file descriptor. // If a block_size is given, it specifies the size of the buffers // that should be returned by Next(). Otherwise, a reasonable default // is used. explicit FileOutputStream(int file_descriptor, int block_size = -1); - ~FileOutputStream(); + ~FileOutputStream() override; // Flushes any buffers and closes the underlying file. Returns false if // an error occurs during the process; use GetErrno() to examine the error. @@ -167,25 +168,25 @@ class LIBPROTOBUF_EXPORT FileOutputStream : public ZeroCopyOutputStream { // errno from that error. Otherwise, this is zero. Once an error // occurs, the stream is broken and all subsequent operations will // fail. - int GetErrno() { return copying_output_.GetErrno(); } + int GetErrno() const { return copying_output_.GetErrno(); } // implements ZeroCopyOutputStream --------------------------------- - bool Next(void** data, int* size); - void BackUp(int count); - int64 ByteCount() const; + bool Next(void** data, int* size) override; + void BackUp(int count) override; + int64 ByteCount() const override; private: - class LIBPROTOBUF_EXPORT CopyingFileOutputStream : public CopyingOutputStream { + class PROTOBUF_EXPORT CopyingFileOutputStream : public CopyingOutputStream { public: CopyingFileOutputStream(int file_descriptor); - ~CopyingFileOutputStream(); + ~CopyingFileOutputStream() override; bool Close(); void SetCloseOnDelete(bool value) { close_on_delete_ = value; } - int GetErrno() { return errno_; } + int GetErrno() const { return errno_; } // implements CopyingOutputStream -------------------------------- - bool Write(const void* buffer, int size); + bool Write(const void* buffer, int size) override; private: // The file descriptor. @@ -211,7 +212,7 @@ class LIBPROTOBUF_EXPORT FileOutputStream : public ZeroCopyOutputStream { // // Note that for reading files (or anything represented by a file descriptor), // FileInputStream is more efficient. -class LIBPROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream { +class PROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream { public: // Creates a stream that reads from the given C++ istream. // If a block_size is given, it specifies the number of bytes that @@ -220,19 +221,19 @@ class LIBPROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream { explicit IstreamInputStream(std::istream* stream, int block_size = -1); // implements ZeroCopyInputStream ---------------------------------- - bool Next(const void** data, int* size); - void BackUp(int count); - bool Skip(int count); - int64 ByteCount() const; + bool Next(const void** data, int* size) override; + void BackUp(int count) override; + bool Skip(int count) override; + int64 ByteCount() const override; private: - class LIBPROTOBUF_EXPORT CopyingIstreamInputStream : public CopyingInputStream { + class PROTOBUF_EXPORT CopyingIstreamInputStream : public CopyingInputStream { public: CopyingIstreamInputStream(std::istream* input); - ~CopyingIstreamInputStream(); + ~CopyingIstreamInputStream() override; // implements CopyingInputStream --------------------------------- - int Read(void* buffer, int size); + int Read(void* buffer, int size) override; // (We use the default implementation of Skip().) private: @@ -254,28 +255,29 @@ class LIBPROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream { // // Note that for writing files (or anything represented by a file descriptor), // FileOutputStream is more efficient. -class LIBPROTOBUF_EXPORT OstreamOutputStream : public ZeroCopyOutputStream { +class PROTOBUF_EXPORT OstreamOutputStream : public ZeroCopyOutputStream { public: // Creates a stream that writes to the given C++ ostream. // If a block_size is given, it specifies the size of the buffers // that should be returned by Next(). Otherwise, a reasonable default // is used. explicit OstreamOutputStream(std::ostream* stream, int block_size = -1); - ~OstreamOutputStream(); + ~OstreamOutputStream() override; // implements ZeroCopyOutputStream --------------------------------- - bool Next(void** data, int* size); - void BackUp(int count); - int64 ByteCount() const; + bool Next(void** data, int* size) override; + void BackUp(int count) override; + int64 ByteCount() const override; private: - class LIBPROTOBUF_EXPORT CopyingOstreamOutputStream : public CopyingOutputStream { + class PROTOBUF_EXPORT CopyingOstreamOutputStream + : public CopyingOutputStream { public: CopyingOstreamOutputStream(std::ostream* output); - ~CopyingOstreamOutputStream(); + ~CopyingOstreamOutputStream() override; // implements CopyingOutputStream -------------------------------- - bool Write(const void* buffer, int size); + bool Write(const void* buffer, int size) override; private: // The stream. @@ -299,17 +301,18 @@ class LIBPROTOBUF_EXPORT OstreamOutputStream : public ZeroCopyOutputStream { // ConcatenatingInputStream may do odd things. It is suggested that you do // not use ConcatenatingInputStream on streams that might produce read errors // other than end-of-stream. -class LIBPROTOBUF_EXPORT ConcatenatingInputStream : public ZeroCopyInputStream { +class PROTOBUF_EXPORT ConcatenatingInputStream : public ZeroCopyInputStream { public: // All streams passed in as well as the array itself must remain valid // until the ConcatenatingInputStream is destroyed. ConcatenatingInputStream(ZeroCopyInputStream* const streams[], int count); + ~ConcatenatingInputStream() override = default; // implements ZeroCopyInputStream ---------------------------------- - bool Next(const void** data, int* size); - void BackUp(int count); - bool Skip(int count); - int64 ByteCount() const; + bool Next(const void** data, int* size) override; + void BackUp(int count) override; + bool Skip(int count) override; + int64 ByteCount() const override; private: @@ -324,32 +327,10 @@ class LIBPROTOBUF_EXPORT ConcatenatingInputStream : public ZeroCopyInputStream { // =================================================================== -// A ZeroCopyInputStream which wraps some other stream and limits it to -// a particular byte count. -class LIBPROTOBUF_EXPORT LimitingInputStream : public ZeroCopyInputStream { - public: - LimitingInputStream(ZeroCopyInputStream* input, int64 limit); - ~LimitingInputStream(); - - // implements ZeroCopyInputStream ---------------------------------- - bool Next(const void** data, int* size); - void BackUp(int count); - bool Skip(int count); - int64 ByteCount() const; - - - private: - ZeroCopyInputStream* input_; - int64 limit_; // Decreases as we go, becomes negative if we overshoot. - int64 prior_bytes_read_; // Bytes read on underlying stream at construction - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(LimitingInputStream); -}; - -// =================================================================== - } // namespace io } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_H__ diff --git a/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl_lite.cc b/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl_lite.cc index 66ad49bc..dd45a4cc 100644 --- a/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl_lite.cc +++ b/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl_lite.cc @@ -37,9 +37,9 @@ #include #include -#include #include #include +#include #include namespace google { @@ -55,14 +55,12 @@ static const int kDefaultBlockSize = 8192; // =================================================================== -ArrayInputStream::ArrayInputStream(const void* data, int size, - int block_size) - : data_(reinterpret_cast(data)), - size_(size), - block_size_(block_size > 0 ? block_size : size), - position_(0), - last_returned_size_(0) { -} +ArrayInputStream::ArrayInputStream(const void* data, int size, int block_size) + : data_(reinterpret_cast(data)), + size_(size), + block_size_(block_size > 0 ? block_size : size), + position_(0), + last_returned_size_(0) {} bool ArrayInputStream::Next(const void** data, int* size) { if (position_ < size_) { @@ -73,7 +71,7 @@ bool ArrayInputStream::Next(const void** data, int* size) { return true; } else { // We're at the end of the array. - last_returned_size_ = 0; // Don't let caller back up. + last_returned_size_ = 0; // Don't let caller back up. return false; } } @@ -89,7 +87,7 @@ void ArrayInputStream::BackUp(int count) { bool ArrayInputStream::Skip(int count) { GOOGLE_CHECK_GE(count, 0); - last_returned_size_ = 0; // Don't let caller back up. + last_returned_size_ = 0; // Don't let caller back up. if (count > size_ - position_) { position_ = size_; return false; @@ -99,20 +97,17 @@ bool ArrayInputStream::Skip(int count) { } } -int64 ArrayInputStream::ByteCount() const { - return position_; -} +int64 ArrayInputStream::ByteCount() const { return position_; } // =================================================================== ArrayOutputStream::ArrayOutputStream(void* data, int size, int block_size) - : data_(reinterpret_cast(data)), - size_(size), - block_size_(block_size > 0 ? block_size : size), - position_(0), - last_returned_size_(0) { -} + : data_(reinterpret_cast(data)), + size_(size), + block_size_(block_size > 0 ? block_size : size), + position_(0), + last_returned_size_(0) {} bool ArrayOutputStream::Next(void** data, int* size) { if (position_ < size_) { @@ -123,7 +118,7 @@ bool ArrayOutputStream::Next(void** data, int* size) { return true; } else { // We're at the end of the array. - last_returned_size_ = 0; // Don't let caller back up. + last_returned_size_ = 0; // Don't let caller back up. return false; } } @@ -137,15 +132,11 @@ void ArrayOutputStream::BackUp(int count) { last_returned_size_ = 0; // Don't let caller back up further. } -int64 ArrayOutputStream::ByteCount() const { - return position_; -} +int64 ArrayOutputStream::ByteCount() const { return position_; } // =================================================================== -StringOutputStream::StringOutputStream(string* target) - : target_(target) { -} +StringOutputStream::StringOutputStream(std::string* target) : target_(target) {} bool StringOutputStream::Next(void** data, int* size) { GOOGLE_CHECK(target_ != NULL); @@ -190,18 +181,14 @@ int64 StringOutputStream::ByteCount() const { return target_->size(); } -void StringOutputStream::SetString(string* target) { - target_ = target; -} - // =================================================================== int CopyingInputStream::Skip(int count) { char junk[4096]; int skipped = 0; while (skipped < count) { - int bytes = - Read(junk, std::min(count - skipped, implicit_cast(sizeof(junk)))); + int bytes = Read(junk, std::min(count - skipped, + implicit_cast(sizeof(junk)))); if (bytes <= 0) { // EOF or read error. return skipped; @@ -213,14 +200,13 @@ int CopyingInputStream::Skip(int count) { CopyingInputStreamAdaptor::CopyingInputStreamAdaptor( CopyingInputStream* copying_stream, int block_size) - : copying_stream_(copying_stream), - owns_copying_stream_(false), - failed_(false), - position_(0), - buffer_size_(block_size > 0 ? block_size : kDefaultBlockSize), - buffer_used_(0), - backup_bytes_(0) { -} + : copying_stream_(copying_stream), + owns_copying_stream_(false), + failed_(false), + position_(0), + buffer_size_(block_size > 0 ? block_size : kDefaultBlockSize), + buffer_used_(0), + backup_bytes_(0) {} CopyingInputStreamAdaptor::~CopyingInputStreamAdaptor() { if (owns_copying_stream_) { @@ -264,12 +250,11 @@ bool CopyingInputStreamAdaptor::Next(const void** data, int* size) { void CopyingInputStreamAdaptor::BackUp(int count) { GOOGLE_CHECK(backup_bytes_ == 0 && buffer_.get() != NULL) - << " BackUp() can only be called after Next()."; + << " BackUp() can only be called after Next()."; GOOGLE_CHECK_LE(count, buffer_used_) - << " Can't back up over more bytes than were returned by the last call" - " to Next()."; - GOOGLE_CHECK_GE(count, 0) - << " Parameter to BackUp() can't be negative."; + << " Can't back up over more bytes than were returned by the last call" + " to Next()."; + GOOGLE_CHECK_GE(count, 0) << " Parameter to BackUp() can't be negative."; backup_bytes_ = count; } @@ -317,13 +302,12 @@ void CopyingInputStreamAdaptor::FreeBuffer() { CopyingOutputStreamAdaptor::CopyingOutputStreamAdaptor( CopyingOutputStream* copying_stream, int block_size) - : copying_stream_(copying_stream), - owns_copying_stream_(false), - failed_(false), - position_(0), - buffer_size_(block_size > 0 ? block_size : kDefaultBlockSize), - buffer_used_(0) { -} + : copying_stream_(copying_stream), + owns_copying_stream_(false), + failed_(false), + position_(0), + buffer_size_(block_size > 0 ? block_size : kDefaultBlockSize), + buffer_used_(0) {} CopyingOutputStreamAdaptor::~CopyingOutputStreamAdaptor() { WriteBuffer(); @@ -332,9 +316,7 @@ CopyingOutputStreamAdaptor::~CopyingOutputStreamAdaptor() { } } -bool CopyingOutputStreamAdaptor::Flush() { - return WriteBuffer(); -} +bool CopyingOutputStreamAdaptor::Flush() { return WriteBuffer(); } bool CopyingOutputStreamAdaptor::Next(void** data, int* size) { if (buffer_used_ == buffer_size_) { @@ -352,10 +334,10 @@ bool CopyingOutputStreamAdaptor::Next(void** data, int* size) { void CopyingOutputStreamAdaptor::BackUp(int count) { GOOGLE_CHECK_GE(count, 0); GOOGLE_CHECK_EQ(buffer_used_, buffer_size_) - << " BackUp() can only be called after Next()."; + << " BackUp() can only be called after Next()."; GOOGLE_CHECK_LE(count, buffer_used_) - << " Can't back up over more bytes than were returned by the last call" - " to Next()."; + << " Can't back up over more bytes than were returned by the last call" + " to Next()."; buffer_used_ -= count; } @@ -394,6 +376,63 @@ void CopyingOutputStreamAdaptor::FreeBuffer() { buffer_.reset(); } +// =================================================================== + +LimitingInputStream::LimitingInputStream(ZeroCopyInputStream* input, + int64 limit) + : input_(input), limit_(limit) { + prior_bytes_read_ = input_->ByteCount(); +} + +LimitingInputStream::~LimitingInputStream() { + // If we overshot the limit, back up. + if (limit_ < 0) input_->BackUp(-limit_); +} + +bool LimitingInputStream::Next(const void** data, int* size) { + if (limit_ <= 0) return false; + if (!input_->Next(data, size)) return false; + + limit_ -= *size; + if (limit_ < 0) { + // We overshot the limit. Reduce *size to hide the rest of the buffer. + *size += limit_; + } + return true; +} + +void LimitingInputStream::BackUp(int count) { + if (limit_ < 0) { + input_->BackUp(count - limit_); + limit_ = count; + } else { + input_->BackUp(count); + limit_ += count; + } +} + +bool LimitingInputStream::Skip(int count) { + if (count > limit_) { + if (limit_ < 0) return false; + input_->Skip(limit_); + limit_ = 0; + return false; + } else { + if (!input_->Skip(count)) return false; + limit_ -= count; + return true; + } +} + +int64 LimitingInputStream::ByteCount() const { + if (limit_ < 0) { + return input_->ByteCount() + limit_ - prior_bytes_read_; + } else { + return input_->ByteCount() - prior_bytes_read_; + } +} + + // =================================================================== } // namespace io diff --git a/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl_lite.h b/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl_lite.h index 29f63bf0..ebb20176 100644 --- a/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl_lite.h +++ b/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl_lite.h @@ -44,15 +44,17 @@ #ifndef GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__ #define GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__ +#include #include #include -#include -#include #include #include +#include #include +#include + namespace google { namespace protobuf { namespace io { @@ -60,7 +62,7 @@ namespace io { // =================================================================== // A ZeroCopyInputStream backed by an in-memory array of bytes. -class LIBPROTOBUF_EXPORT ArrayInputStream : public ZeroCopyInputStream { +class PROTOBUF_EXPORT ArrayInputStream : public ZeroCopyInputStream { public: // Create an InputStream that returns the bytes pointed to by "data". // "data" remains the property of the caller but must remain valid until @@ -70,12 +72,13 @@ class LIBPROTOBUF_EXPORT ArrayInputStream : public ZeroCopyInputStream { // useful for testing; in production you would probably never want to set // it. ArrayInputStream(const void* data, int size, int block_size = -1); + ~ArrayInputStream() override = default; // implements ZeroCopyInputStream ---------------------------------- - bool Next(const void** data, int* size); - void BackUp(int count); - bool Skip(int count); - int64 ByteCount() const; + bool Next(const void** data, int* size) override; + void BackUp(int count) override; + bool Skip(int count) override; + int64 ByteCount() const override; private: @@ -84,8 +87,8 @@ class LIBPROTOBUF_EXPORT ArrayInputStream : public ZeroCopyInputStream { const int block_size_; // How many bytes to return at a time. int position_; - int last_returned_size_; // How many bytes we returned last time Next() - // was called (used for error checking only). + int last_returned_size_; // How many bytes we returned last time Next() + // was called (used for error checking only). GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArrayInputStream); }; @@ -93,7 +96,7 @@ class LIBPROTOBUF_EXPORT ArrayInputStream : public ZeroCopyInputStream { // =================================================================== // A ZeroCopyOutputStream backed by an in-memory array of bytes. -class LIBPROTOBUF_EXPORT ArrayOutputStream : public ZeroCopyOutputStream { +class PROTOBUF_EXPORT ArrayOutputStream : public ZeroCopyOutputStream { public: // Create an OutputStream that writes to the bytes pointed to by "data". // "data" remains the property of the caller but must remain valid until @@ -103,20 +106,21 @@ class LIBPROTOBUF_EXPORT ArrayOutputStream : public ZeroCopyOutputStream { // useful for testing; in production you would probably never want to set // it. ArrayOutputStream(void* data, int size, int block_size = -1); + ~ArrayOutputStream() override = default; // implements ZeroCopyOutputStream --------------------------------- - bool Next(void** data, int* size); - void BackUp(int count); - int64 ByteCount() const; + bool Next(void** data, int* size) override; + void BackUp(int count) override; + int64 ByteCount() const override; private: - uint8* const data_; // The byte array. - const int size_; // Total size of the array. - const int block_size_; // How many bytes to return at a time. + uint8* const data_; // The byte array. + const int size_; // Total size of the array. + const int block_size_; // How many bytes to return at a time. int position_; - int last_returned_size_; // How many bytes we returned last time Next() - // was called (used for error checking only). + int last_returned_size_; // How many bytes we returned last time Next() + // was called (used for error checking only). GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArrayOutputStream); }; @@ -124,7 +128,7 @@ class LIBPROTOBUF_EXPORT ArrayOutputStream : public ZeroCopyOutputStream { // =================================================================== // A ZeroCopyOutputStream which appends bytes to a string. -class LIBPROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream { +class PROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream { public: // Create a StringOutputStream which appends bytes to the given string. // The string remains property of the caller, but it is mutated in arbitrary @@ -135,20 +139,18 @@ class LIBPROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream { // Hint: If you call target->reserve(n) before creating the stream, // the first call to Next() will return at least n bytes of buffer // space. - explicit StringOutputStream(string* target); + explicit StringOutputStream(std::string* target); + ~StringOutputStream() override = default; // implements ZeroCopyOutputStream --------------------------------- - bool Next(void** data, int* size); - void BackUp(int count); - int64 ByteCount() const; - - protected: - void SetString(string* target); + bool Next(void** data, int* size) override; + void BackUp(int count) override; + int64 ByteCount() const override; private: static const int kMinimumSize = 16; - string* target_; + std::string* target_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringOutputStream); }; @@ -170,7 +172,7 @@ class LIBPROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream { // CopyingInputStream implementations should avoid buffering if possible. // CopyingInputStreamAdaptor does its own buffering and will read data // in large blocks. -class LIBPROTOBUF_EXPORT CopyingInputStream { +class PROTOBUF_EXPORT CopyingInputStream { public: virtual ~CopyingInputStream() {} @@ -196,7 +198,7 @@ class LIBPROTOBUF_EXPORT CopyingInputStream { // If you want to read from file descriptors or C++ istreams, this is // already implemented for you: use FileInputStream or IstreamInputStream // respectively. -class LIBPROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream { +class PROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream { public: // Creates a stream that reads from the given CopyingInputStream. // If a block_size is given, it specifies the number of bytes that @@ -205,17 +207,17 @@ class LIBPROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream // copying_stream unless SetOwnsCopyingStream(true) is called. explicit CopyingInputStreamAdaptor(CopyingInputStream* copying_stream, int block_size = -1); - ~CopyingInputStreamAdaptor(); + ~CopyingInputStreamAdaptor() override; // Call SetOwnsCopyingStream(true) to tell the CopyingInputStreamAdaptor to // delete the underlying CopyingInputStream when it is destroyed. void SetOwnsCopyingStream(bool value) { owns_copying_stream_ = value; } // implements ZeroCopyInputStream ---------------------------------- - bool Next(const void** data, int* size); - void BackUp(int count); - bool Skip(int count); - int64 ByteCount() const; + bool Next(const void** data, int* size) override; + void BackUp(int count) override; + bool Skip(int count) override; + int64 ByteCount() const override; private: // Insures that buffer_ is not NULL. @@ -264,7 +266,7 @@ class LIBPROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream // CopyingOutputStream implementations should avoid buffering if possible. // CopyingOutputStreamAdaptor does its own buffering and will write data // in large blocks. -class LIBPROTOBUF_EXPORT CopyingOutputStream { +class PROTOBUF_EXPORT CopyingOutputStream { public: virtual ~CopyingOutputStream() {} @@ -280,7 +282,7 @@ class LIBPROTOBUF_EXPORT CopyingOutputStream { // If you want to write to file descriptors or C++ ostreams, this is // already implemented for you: use FileOutputStream or OstreamOutputStream // respectively. -class LIBPROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStream { +class PROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStream { public: // Creates a stream that writes to the given Unix file descriptor. // If a block_size is given, it specifies the size of the buffers @@ -288,7 +290,7 @@ class LIBPROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStrea // is used. explicit CopyingOutputStreamAdaptor(CopyingOutputStream* copying_stream, int block_size = -1); - ~CopyingOutputStreamAdaptor(); + ~CopyingOutputStreamAdaptor() override; // Writes all pending data to the underlying stream. Returns false if a // write error occurred on the underlying stream. (The underlying @@ -300,9 +302,9 @@ class LIBPROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStrea void SetOwnsCopyingStream(bool value) { owns_copying_stream_ = value; } // implements ZeroCopyOutputStream --------------------------------- - bool Next(void** data, int* size); - void BackUp(int count); - int64 ByteCount() const; + bool Next(void** data, int* size) override; + void BackUp(int count) override; + int64 ByteCount() const override; private: // Write the current buffer, if it is present. @@ -336,6 +338,31 @@ class LIBPROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStrea GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CopyingOutputStreamAdaptor); }; +// =================================================================== + +// A ZeroCopyInputStream which wraps some other stream and limits it to +// a particular byte count. +class PROTOBUF_EXPORT LimitingInputStream : public ZeroCopyInputStream { + public: + LimitingInputStream(ZeroCopyInputStream* input, int64 limit); + ~LimitingInputStream() override; + + // implements ZeroCopyInputStream ---------------------------------- + bool Next(const void** data, int* size) override; + void BackUp(int count) override; + bool Skip(int count) override; + int64 ByteCount() const override; + + + private: + ZeroCopyInputStream* input_; + int64 limit_; // Decreases as we go, becomes negative if we overshoot. + int64 prior_bytes_read_; // Bytes read on underlying stream at construction + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(LimitingInputStream); +}; + + // =================================================================== // mutable_string_data() and as_string_data() are workarounds to improve @@ -353,31 +380,25 @@ class LIBPROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStrea // Return a pointer to mutable characters underlying the given string. The // return value is valid until the next time the string is resized. We // trust the caller to treat the return value as an array of length s->size(). -inline char* mutable_string_data(string* s) { -#ifdef LANG_CXX11 +inline char* mutable_string_data(std::string* s) { // This should be simpler & faster than string_as_array() because the latter // is guaranteed to return NULL when *s is empty, so it has to check for that. return &(*s)[0]; -#else - return string_as_array(s); -#endif } // as_string_data(s) is equivalent to // ({ char* p = mutable_string_data(s); make_pair(p, p != NULL); }) // Sometimes it's faster: in some scenarios p cannot be NULL, and then the // code can avoid that check. -inline std::pair as_string_data(string* s) { - char *p = mutable_string_data(s); -#ifdef LANG_CXX11 +inline std::pair as_string_data(std::string* s) { + char* p = mutable_string_data(s); return std::make_pair(p, true); -#else - return std::make_pair(p, p != NULL); -#endif } } // namespace io } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__ diff --git a/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_unittest.cc b/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_unittest.cc index 08de8cb1..5f7b6104 100644 --- a/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/io/zero_copy_stream_unittest.cc @@ -50,15 +50,17 @@ #ifndef _MSC_VER #include #endif -#include -#include -#include -#include #include +#include +#include +#include +#include #include #include #include +#include +#include #include #include @@ -68,10 +70,9 @@ #include #include -#include #include +#include #include -#include namespace google { namespace protobuf { @@ -82,17 +83,17 @@ namespace { #define pipe(fds) _pipe(fds, 4096, O_BINARY) // DO NOT include , instead create functions in io_win32.{h,cc} and import // them like we do below. -using google::protobuf::internal::win32::access; -using google::protobuf::internal::win32::mkdir; -using google::protobuf::internal::win32::open; -using google::protobuf::internal::win32::close; +using google::protobuf::io::win32::access; +using google::protobuf::io::win32::close; +using google::protobuf::io::win32::mkdir; +using google::protobuf::io::win32::open; #endif #ifndef O_BINARY #ifdef _O_BINARY #define O_BINARY _O_BINARY #else -#define O_BINARY 0 // If this isn't defined, the platform doesn't need it. +#define O_BINARY 0 // If this isn't defined, the platform doesn't need it. #endif #endif @@ -105,10 +106,10 @@ class IoTest : public testing::Test { // Helper to read a fixed-length array of data from an input stream. int ReadFromInput(ZeroCopyInputStream* input, void* data, int size); // Write a string to the output stream. - void WriteString(ZeroCopyOutputStream* output, const string& str); + void WriteString(ZeroCopyOutputStream* output, const std::string& str); // Read a number of bytes equal to the size of the given string and checks // that it matches the string. - void ReadString(ZeroCopyInputStream* input, const string& str); + void ReadString(ZeroCopyInputStream* input, const std::string& str); // Writes some text to the output stream in a particular order. Returns // the number of bytes written, incase the caller needs that to set up an // input stream. @@ -124,8 +125,9 @@ class IoTest : public testing::Test { void ReadStuffLarge(ZeroCopyInputStream* input); #if HAVE_ZLIB - string Compress(const string& data, const GzipOutputStream::Options& options); - string Uncompress(const string& data); + std::string Compress(const std::string& data, + const GzipOutputStream::Options& options); + std::string Uncompress(const std::string& data); #endif static const int kBlockSizes[]; @@ -135,8 +137,8 @@ class IoTest : public testing::Test { const int IoTest::kBlockSizes[] = {-1, 1, 2, 5, 7, 10, 23, 64}; const int IoTest::kBlockSizeCount = GOOGLE_ARRAYSIZE(IoTest::kBlockSizes); -bool IoTest::WriteToOutput(ZeroCopyOutputStream* output, - const void* data, int size) { +bool IoTest::WriteToOutput(ZeroCopyOutputStream* output, const void* data, + int size) { const uint8* in = reinterpret_cast(data); int in_size = size; @@ -198,11 +200,11 @@ int IoTest::ReadFromInput(ZeroCopyInputStream* input, void* data, int size) { } } -void IoTest::WriteString(ZeroCopyOutputStream* output, const string& str) { +void IoTest::WriteString(ZeroCopyOutputStream* output, const std::string& str) { EXPECT_TRUE(WriteToOutput(output, str.c_str(), str.size())); } -void IoTest::ReadString(ZeroCopyInputStream* input, const string& str) { +void IoTest::ReadString(ZeroCopyInputStream* input, const std::string& str) { std::unique_ptr buffer(new char[str.size() + 1]); buffer[str.size()] = '\0'; EXPECT_EQ(ReadFromInput(input, buffer.get(), str.size()), str.size()); @@ -245,8 +247,8 @@ int IoTest::WriteStuffLarge(ZeroCopyOutputStream* output) { WriteString(output, "Hello world!\n"); WriteString(output, "Some te"); WriteString(output, "xt. Blah blah."); - WriteString(output, string(100000, 'x')); // A very long string - WriteString(output, string(100000, 'y')); // A very long string + WriteString(output, std::string(100000, 'x')); // A very long string + WriteString(output, std::string(100000, 'y')); // A very long string WriteString(output, "01234567890123456789"); EXPECT_EQ(output->ByteCount(), 200055); @@ -262,7 +264,7 @@ void IoTest::ReadStuffLarge(ZeroCopyInputStream* input) { EXPECT_TRUE(input->Skip(5)); ReadString(input, "blah."); EXPECT_TRUE(input->Skip(100000 - 10)); - ReadString(input, string(10, 'x') + string(100000 - 20000, 'y')); + ReadString(input, std::string(10, 'x') + std::string(100000 - 20000, 'y')); EXPECT_TRUE(input->Skip(20000 - 10)); ReadString(input, "yyyyyyyyyy01234567890123456789"); @@ -298,7 +300,7 @@ TEST_F(IoTest, TwoSessionWrite) { static const char* strA = "0123456789"; static const char* strB = "WhirledPeas"; - const int kBufferSize = 2*1024; + const int kBufferSize = 2 * 1024; uint8* buffer = new uint8[kBufferSize]; char* temp_buffer = new char[40]; @@ -312,8 +314,8 @@ TEST_F(IoTest, TwoSessionWrite) { delete coded_output; // flush int64 pos = output->ByteCount(); delete output; - output = new ArrayOutputStream( - buffer + pos, kBufferSize - pos, kBlockSizes[i]); + output = new ArrayOutputStream(buffer + pos, kBufferSize - pos, + kBlockSizes[i]); coded_output = new CodedOutputStream(output); coded_output->WriteVarint32(strlen(strB)); coded_output->WriteRaw(strB, strlen(strB)); @@ -340,13 +342,13 @@ TEST_F(IoTest, TwoSessionWrite) { } } - delete [] temp_buffer; - delete [] buffer; + delete[] temp_buffer; + delete[] buffer; } #if HAVE_ZLIB TEST_F(IoTest, GzipIo) { - const int kBufferSize = 2*1024; + const int kBufferSize = 2 * 1024; uint8* buffer = new uint8[kBufferSize]; for (int i = 0; i < kBlockSizeCount; i++) { for (int j = 0; j < kBlockSizeCount; j++) { @@ -367,18 +369,17 @@ TEST_F(IoTest, GzipIo) { } { ArrayInputStream input(buffer, size, kBlockSizes[j]); - GzipInputStream gzin( - &input, GzipInputStream::GZIP, gzip_buffer_size); + GzipInputStream gzin(&input, GzipInputStream::GZIP, gzip_buffer_size); ReadStuff(&gzin); } } } } - delete [] buffer; + delete[] buffer; } TEST_F(IoTest, GzipIoWithFlush) { - const int kBufferSize = 2*1024; + const int kBufferSize = 2 * 1024; uint8* buffer = new uint8[kBufferSize]; // We start with i = 4 as we want a block size > 6. With block size <= 6 // Flush() fills up the entire 2K buffer with flush markers and the test @@ -403,18 +404,17 @@ TEST_F(IoTest, GzipIoWithFlush) { } { ArrayInputStream input(buffer, size, kBlockSizes[j]); - GzipInputStream gzin( - &input, GzipInputStream::GZIP, gzip_buffer_size); + GzipInputStream gzin(&input, GzipInputStream::GZIP, gzip_buffer_size); ReadStuff(&gzin); } } } } - delete [] buffer; + delete[] buffer; } TEST_F(IoTest, GzipIoContiguousFlushes) { - const int kBufferSize = 2*1024; + const int kBufferSize = 2 * 1024; uint8* buffer = new uint8[kBufferSize]; int block_size = kBlockSizes[4]; @@ -435,15 +435,14 @@ TEST_F(IoTest, GzipIoContiguousFlushes) { size = output.ByteCount(); ArrayInputStream input(buffer, size, block_size); - GzipInputStream gzin( - &input, GzipInputStream::GZIP, gzip_buffer_size); + GzipInputStream gzin(&input, GzipInputStream::GZIP, gzip_buffer_size); ReadStuff(&gzin); - delete [] buffer; + delete[] buffer; } TEST_F(IoTest, GzipIoReadAfterFlush) { - const int kBufferSize = 2*1024; + const int kBufferSize = 2 * 1024; uint8* buffer = new uint8[kBufferSize]; int block_size = kBlockSizes[4]; @@ -462,17 +461,16 @@ TEST_F(IoTest, GzipIoReadAfterFlush) { size = output.ByteCount(); ArrayInputStream input(buffer, size, block_size); - GzipInputStream gzin( - &input, GzipInputStream::GZIP, gzip_buffer_size); + GzipInputStream gzin(&input, GzipInputStream::GZIP, gzip_buffer_size); ReadStuff(&gzin); gzout.Close(); - delete [] buffer; + delete[] buffer; } TEST_F(IoTest, ZlibIo) { - const int kBufferSize = 2*1024; + const int kBufferSize = 2 * 1024; uint8* buffer = new uint8[kBufferSize]; for (int i = 0; i < kBlockSizeCount; i++) { for (int j = 0; j < kBlockSizeCount; j++) { @@ -493,18 +491,17 @@ TEST_F(IoTest, ZlibIo) { } { ArrayInputStream input(buffer, size, kBlockSizes[j]); - GzipInputStream gzin( - &input, GzipInputStream::ZLIB, gzip_buffer_size); + GzipInputStream gzin(&input, GzipInputStream::ZLIB, gzip_buffer_size); ReadStuff(&gzin); } } } } - delete [] buffer; + delete[] buffer; } TEST_F(IoTest, ZlibIoInputAutodetect) { - const int kBufferSize = 2*1024; + const int kBufferSize = 2 * 1024; uint8* buffer = new uint8[kBufferSize]; int size; { @@ -535,12 +532,12 @@ TEST_F(IoTest, ZlibIoInputAutodetect) { GzipInputStream gzin(&input, GzipInputStream::AUTO); ReadStuff(&gzin); } - delete [] buffer; + delete[] buffer; } -string IoTest::Compress(const string& data, - const GzipOutputStream::Options& options) { - string result; +std::string IoTest::Compress(const std::string& data, + const GzipOutputStream::Options& options) { + std::string result; { StringOutputStream output(&result); GzipOutputStream gzout(&output, options); @@ -549,8 +546,8 @@ string IoTest::Compress(const string& data, return result; } -string IoTest::Uncompress(const string& data) { - string result; +std::string IoTest::Uncompress(const std::string& data) { + std::string result; { ArrayInputStream input(data.data(), data.size()); GzipInputStream gzin(&input); @@ -566,22 +563,21 @@ string IoTest::Uncompress(const string& data) { TEST_F(IoTest, CompressionOptions) { // Some ad-hoc testing of compression options. - string golden; - GOOGLE_CHECK_OK(File::GetContents( - TestSourceDir() + - "/google/protobuf/testdata/golden_message", - &golden, true)); + std::string golden_filename = + TestUtil::GetTestDataPath("net/proto2/internal/testdata/golden_message"); + std::string golden; + GOOGLE_CHECK_OK(File::GetContents(golden_filename, &golden, true)); GzipOutputStream::Options options; - string gzip_compressed = Compress(golden, options); + std::string gzip_compressed = Compress(golden, options); options.compression_level = 0; - string not_compressed = Compress(golden, options); + std::string not_compressed = Compress(golden, options); // Try zlib compression for fun. options = GzipOutputStream::Options(); options.format = GzipOutputStream::ZLIB; - string zlib_compressed = Compress(golden, options); + std::string zlib_compressed = Compress(golden, options); // Uncompressed should be bigger than the original since it should have some // sort of header. @@ -604,7 +600,7 @@ TEST_F(IoTest, TwoSessionWriteGzip) { static const char* strA = "0123456789"; static const char* strB = "QuickBrownFox"; - const int kBufferSize = 2*1024; + const int kBufferSize = 2 * 1024; uint8* buffer = new uint8[kBufferSize]; char* temp_buffer = new char[40]; @@ -618,18 +614,18 @@ TEST_F(IoTest, TwoSessionWriteGzip) { coded_output->WriteVarint32(outlen); coded_output->WriteRaw(strA, outlen); delete coded_output; // flush - delete gzout; // flush + delete gzout; // flush int64 pos = output->ByteCount(); delete output; - output = new ArrayOutputStream( - buffer + pos, kBufferSize - pos, kBlockSizes[i]); + output = new ArrayOutputStream(buffer + pos, kBufferSize - pos, + kBlockSizes[i]); gzout = new GzipOutputStream(output); coded_output = new CodedOutputStream(gzout); outlen = strlen(strB) + 1; coded_output->WriteVarint32(outlen); coded_output->WriteRaw(strB, outlen); delete coded_output; // flush - delete gzout; // flush + delete gzout; // flush int64 size = pos + output->ByteCount(); delete output; @@ -649,10 +645,8 @@ TEST_F(IoTest, TwoSessionWriteGzip) { EXPECT_TRUE(coded_input->ReadRaw(temp_buffer, insize)); EXPECT_EQ(0, memcmp(temp_buffer, strB, insize)) << " out_block_size=" << kBlockSizes[i] - << " in_block_size=" << kBlockSizes[j] - << " pos=" << pos - << " size=" << size - << " strB=" << strB << " in=" << temp_buffer; + << " in_block_size=" << kBlockSizes[j] << " pos=" << pos + << " size=" << size << " strB=" << strB << " in=" << temp_buffer; delete coded_input; delete gzin; @@ -660,13 +654,13 @@ TEST_F(IoTest, TwoSessionWriteGzip) { } } - delete [] temp_buffer; - delete [] buffer; + delete[] temp_buffer; + delete[] buffer; } TEST_F(IoTest, GzipInputByteCountAfterClosed) { - string golden = "abcdefghijklmnopqrstuvwxyz"; - string compressed = Compress(golden, GzipOutputStream::Options()); + std::string golden = "abcdefghijklmnopqrstuvwxyz"; + std::string compressed = Compress(golden, GzipOutputStream::Options()); for (int i = 0; i < kBlockSizeCount; i++) { ArrayInputStream arr_input(compressed.data(), compressed.size(), @@ -682,11 +676,11 @@ TEST_F(IoTest, GzipInputByteCountAfterClosed) { } TEST_F(IoTest, GzipInputByteCountAfterClosedConcatenatedStreams) { - string golden1 = "abcdefghijklmnopqrstuvwxyz"; - string golden2 = "the quick brown fox jumps over the lazy dog"; + std::string golden1 = "abcdefghijklmnopqrstuvwxyz"; + std::string golden2 = "the quick brown fox jumps over the lazy dog"; const size_t total_size = golden1.size() + golden2.size(); - string compressed = Compress(golden1, GzipOutputStream::Options()) + - Compress(golden2, GzipOutputStream::Options()); + std::string compressed = Compress(golden1, GzipOutputStream::Options()) + + Compress(golden2, GzipOutputStream::Options()); for (int i = 0; i < kBlockSizeCount; i++) { ArrayInputStream arr_input(compressed.data(), compressed.size(), @@ -706,7 +700,7 @@ TEST_F(IoTest, GzipInputByteCountAfterClosedConcatenatedStreams) { // explicit block sizes. So, we'll only run one test and we'll use // ArrayInput to read back the results. TEST_F(IoTest, StringIo) { - string str; + std::string str; { StringOutputStream output(&str); WriteStuff(&output); @@ -720,13 +714,13 @@ TEST_F(IoTest, StringIo) { // To test files, we create a temporary file, write, read, truncate, repeat. TEST_F(IoTest, FileIo) { - string filename = TestTempDir() + "/zero_copy_stream_test_file"; + std::string filename = TestTempDir() + "/zero_copy_stream_test_file"; for (int i = 0; i < kBlockSizeCount; i++) { for (int j = 0; j < kBlockSizeCount; j++) { // Make a temporary file. int file = - open(filename.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0777); + open(filename.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0777); ASSERT_GE(file, 0); { @@ -751,13 +745,13 @@ TEST_F(IoTest, FileIo) { #if HAVE_ZLIB TEST_F(IoTest, GzipFileIo) { - string filename = TestTempDir() + "/zero_copy_stream_test_file"; + std::string filename = TestTempDir() + "/zero_copy_stream_test_file"; for (int i = 0; i < kBlockSizeCount; i++) { for (int j = 0; j < kBlockSizeCount; j++) { // Make a temporary file. int file = - open(filename.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0777); + open(filename.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0777); ASSERT_GE(file, 0); { FileOutputStream output(file, kBlockSizes[i]); @@ -799,10 +793,8 @@ class MsvcDebugDisabler { old_mode_ = _CrtSetReportMode(_CRT_ASSERT, old_mode_); } - static void MyHandler(const wchar_t *expr, - const wchar_t *func, - const wchar_t *file, - unsigned int line, + static void MyHandler(const wchar_t* expr, const wchar_t* func, + const wchar_t* file, unsigned int line, uintptr_t pReserved) { // do nothing } @@ -930,19 +922,19 @@ TEST_F(IoTest, ConcatenatingInputStream) { // Now split it up into multiple streams of varying sizes. ASSERT_EQ(68, output.ByteCount()); // Test depends on this. - ArrayInputStream input1(buffer , 12); - ArrayInputStream input2(buffer + 12, 7); - ArrayInputStream input3(buffer + 19, 6); + ArrayInputStream input1(buffer, 12); + ArrayInputStream input2(buffer + 12, 7); + ArrayInputStream input3(buffer + 19, 6); ArrayInputStream input4(buffer + 25, 15); - ArrayInputStream input5(buffer + 40, 0); + ArrayInputStream input5(buffer + 40, 0); // Note: We want to make sure we have a stream boundary somewhere between // bytes 42 and 62, which is the range that it Skip()ed by ReadStuff(). This // tests that a bug that existed in the original code for Skip() is fixed. ArrayInputStream input6(buffer + 40, 10); ArrayInputStream input7(buffer + 50, 18); // Total = 68 bytes. - ZeroCopyInputStream* streams[] = - {&input1, &input2, &input3, &input4, &input5, &input6, &input7}; + ZeroCopyInputStream* streams[] = {&input1, &input2, &input3, &input4, + &input5, &input6, &input7}; // Create the concatenating stream and read. ConcatenatingInputStream input(streams, GOOGLE_ARRAYSIZE(streams)); @@ -985,7 +977,7 @@ TEST_F(IoTest, LimitingInputStreamByteCount) { LimitingInputStream input(&array_input, kHalfBufferSize - 1); EXPECT_EQ(0, input.ByteCount()); EXPECT_TRUE(input.Next(&data, &size)); - EXPECT_EQ(kHalfBufferSize - 1 , input.ByteCount()); + EXPECT_EQ(kHalfBufferSize - 1, input.ByteCount()); } // Check that a zero-size array doesn't confuse the code. diff --git a/third_party/protobuf/src/google/protobuf/lite_arena_unittest.cc b/third_party/protobuf/src/google/protobuf/lite_arena_unittest.cc index 3e88314d..d68c6c9b 100644 --- a/third_party/protobuf/src/google/protobuf/lite_arena_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/lite_arena_unittest.cc @@ -45,38 +45,38 @@ class LiteArenaTest : public testing::Test { arena_.reset(new Arena(options)); // Trigger the allocation of the first arena block, so that further use of // the arena will not require any heap allocations. - google::protobuf::Arena::CreateArray(arena_.get(), 1); + Arena::CreateArray(arena_.get(), 1); } std::unique_ptr arena_; }; TEST_F(LiteArenaTest, MapNoHeapAllocation) { - string data; + std::string data; data.reserve(128 * 1024); { // TODO(teboring): Enable no heap check when ArenaStringPtr is used in // Map. - // google::protobuf::internal::NoHeapChecker no_heap; + // internal::NoHeapChecker no_heap; protobuf_unittest::TestArenaMapLite* from = Arena::CreateMessage(arena_.get()); - google::protobuf::MapLiteTestUtil::SetArenaMapFields(from); + MapLiteTestUtil::SetArenaMapFields(from); from->SerializeToString(&data); protobuf_unittest::TestArenaMapLite* to = Arena::CreateMessage(arena_.get()); to->ParseFromString(data); - google::protobuf::MapLiteTestUtil::ExpectArenaMapFieldsSet(*to); + MapLiteTestUtil::ExpectArenaMapFieldsSet(*to); } } TEST_F(LiteArenaTest, UnknownFieldMemLeak) { protobuf_unittest::ForeignMessageArenaLite* message = - google::protobuf::Arena::CreateMessage( + Arena::CreateMessage( arena_.get()); - string data = "\012\000"; + std::string data = "\012\000"; int original_capacity = data.capacity(); while (data.capacity() <= original_capacity) { data.append("a"); diff --git a/third_party/protobuf/src/google/protobuf/lite_unittest.cc b/third_party/protobuf/src/google/protobuf/lite_unittest.cc index b42a7b14..c16bdf7e 100644 --- a/third_party/protobuf/src/google/protobuf/lite_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/lite_unittest.cc @@ -30,8 +30,8 @@ // Author: kenton@google.com (Kenton Varda) -#include #include +#include #include #include @@ -43,25 +43,22 @@ #include #include #include -#include #include - #include -using std::string; +namespace google { +namespace protobuf { -namespace { // Helper methods to test parsing merge behavior. -void ExpectMessageMerged(const google::protobuf::unittest::TestAllTypesLite& message) { +void ExpectMessageMerged(const unittest::TestAllTypesLite& message) { EXPECT_EQ(message.optional_int32(), 3); EXPECT_EQ(message.optional_int64(), 2); EXPECT_EQ(message.optional_string(), "hello"); } -void AssignParsingMergeMessages( - google::protobuf::unittest::TestAllTypesLite* msg1, - google::protobuf::unittest::TestAllTypesLite* msg2, - google::protobuf::unittest::TestAllTypesLite* msg3) { +void AssignParsingMergeMessages(unittest::TestAllTypesLite* msg1, + unittest::TestAllTypesLite* msg2, + unittest::TestAllTypesLite* msg3) { msg1->set_optional_int32(1); msg2->set_optional_int64(2); msg3->set_optional_int32(3); @@ -69,119 +66,117 @@ void AssignParsingMergeMessages( } void SetAllTypesInEmptyMessageUnknownFields( - google::protobuf::unittest::TestEmptyMessageLite* empty_message) { + unittest::TestEmptyMessageLite* empty_message) { protobuf_unittest::TestAllTypesLite message; - google::protobuf::TestUtilLite::ExpectClear(message); - google::protobuf::TestUtilLite::SetAllFields(&message); - string data = message.SerializeAsString(); + TestUtilLite::ExpectClear(message); + TestUtilLite::SetAllFields(&message); + std::string data = message.SerializeAsString(); empty_message->ParseFromString(data); } void SetSomeTypesInEmptyMessageUnknownFields( - google::protobuf::unittest::TestEmptyMessageLite* empty_message) { + unittest::TestEmptyMessageLite* empty_message) { protobuf_unittest::TestAllTypesLite message; - google::protobuf::TestUtilLite::ExpectClear(message); + TestUtilLite::ExpectClear(message); message.set_optional_int32(101); message.set_optional_int64(102); message.set_optional_uint32(103); message.set_optional_uint64(104); - string data = message.SerializeAsString(); + std::string data = message.SerializeAsString(); empty_message->ParseFromString(data); } -} // namespace - TEST(Lite, AllLite1) { - string data; + std::string data; { protobuf_unittest::TestAllTypesLite message, message2, message3; - google::protobuf::TestUtilLite::ExpectClear(message); - google::protobuf::TestUtilLite::SetAllFields(&message); + TestUtilLite::ExpectClear(message); + TestUtilLite::SetAllFields(&message); message2.CopyFrom(message); data = message.SerializeAsString(); message3.ParseFromString(data); - google::protobuf::TestUtilLite::ExpectAllFieldsSet(message); - google::protobuf::TestUtilLite::ExpectAllFieldsSet(message2); - google::protobuf::TestUtilLite::ExpectAllFieldsSet(message3); - google::protobuf::TestUtilLite::ModifyRepeatedFields(&message); - google::protobuf::TestUtilLite::ExpectRepeatedFieldsModified(message); + TestUtilLite::ExpectAllFieldsSet(message); + TestUtilLite::ExpectAllFieldsSet(message2); + TestUtilLite::ExpectAllFieldsSet(message3); + TestUtilLite::ModifyRepeatedFields(&message); + TestUtilLite::ExpectRepeatedFieldsModified(message); message.Clear(); - google::protobuf::TestUtilLite::ExpectClear(message); + TestUtilLite::ExpectClear(message); } } TEST(Lite, AllLite2) { - string data; + std::string data; { protobuf_unittest::TestAllExtensionsLite message, message2, message3; - google::protobuf::TestUtilLite::ExpectExtensionsClear(message); - google::protobuf::TestUtilLite::SetAllExtensions(&message); + TestUtilLite::ExpectExtensionsClear(message); + TestUtilLite::SetAllExtensions(&message); message2.CopyFrom(message); - string extensions_data = message.SerializeAsString(); + std::string extensions_data = message.SerializeAsString(); message3.ParseFromString(extensions_data); - google::protobuf::TestUtilLite::ExpectAllExtensionsSet(message); - google::protobuf::TestUtilLite::ExpectAllExtensionsSet(message2); - google::protobuf::TestUtilLite::ExpectAllExtensionsSet(message3); - google::protobuf::TestUtilLite::ModifyRepeatedExtensions(&message); - google::protobuf::TestUtilLite::ExpectRepeatedExtensionsModified(message); + TestUtilLite::ExpectAllExtensionsSet(message); + TestUtilLite::ExpectAllExtensionsSet(message2); + TestUtilLite::ExpectAllExtensionsSet(message3); + TestUtilLite::ModifyRepeatedExtensions(&message); + TestUtilLite::ExpectRepeatedExtensionsModified(message); message.Clear(); - google::protobuf::TestUtilLite::ExpectExtensionsClear(message); + TestUtilLite::ExpectExtensionsClear(message); } } TEST(Lite, AllLite3) { - string data, packed_data; + std::string data, packed_data; { protobuf_unittest::TestPackedTypesLite message, message2, message3; - google::protobuf::TestUtilLite::ExpectPackedClear(message); - google::protobuf::TestUtilLite::SetPackedFields(&message); + TestUtilLite::ExpectPackedClear(message); + TestUtilLite::SetPackedFields(&message); message2.CopyFrom(message); packed_data = message.SerializeAsString(); message3.ParseFromString(packed_data); - google::protobuf::TestUtilLite::ExpectPackedFieldsSet(message); - google::protobuf::TestUtilLite::ExpectPackedFieldsSet(message2); - google::protobuf::TestUtilLite::ExpectPackedFieldsSet(message3); - google::protobuf::TestUtilLite::ModifyPackedFields(&message); - google::protobuf::TestUtilLite::ExpectPackedFieldsModified(message); + TestUtilLite::ExpectPackedFieldsSet(message); + TestUtilLite::ExpectPackedFieldsSet(message2); + TestUtilLite::ExpectPackedFieldsSet(message3); + TestUtilLite::ModifyPackedFields(&message); + TestUtilLite::ExpectPackedFieldsModified(message); message.Clear(); - google::protobuf::TestUtilLite::ExpectPackedClear(message); + TestUtilLite::ExpectPackedClear(message); } { protobuf_unittest::TestPackedExtensionsLite message, message2, message3; - google::protobuf::TestUtilLite::ExpectPackedExtensionsClear(message); - google::protobuf::TestUtilLite::SetPackedExtensions(&message); + TestUtilLite::ExpectPackedExtensionsClear(message); + TestUtilLite::SetPackedExtensions(&message); message2.CopyFrom(message); - string packed_extensions_data = message.SerializeAsString(); + std::string packed_extensions_data = message.SerializeAsString(); EXPECT_EQ(packed_extensions_data, packed_data); message3.ParseFromString(packed_extensions_data); - google::protobuf::TestUtilLite::ExpectPackedExtensionsSet(message); - google::protobuf::TestUtilLite::ExpectPackedExtensionsSet(message2); - google::protobuf::TestUtilLite::ExpectPackedExtensionsSet(message3); - google::protobuf::TestUtilLite::ModifyPackedExtensions(&message); - google::protobuf::TestUtilLite::ExpectPackedExtensionsModified(message); + TestUtilLite::ExpectPackedExtensionsSet(message); + TestUtilLite::ExpectPackedExtensionsSet(message2); + TestUtilLite::ExpectPackedExtensionsSet(message3); + TestUtilLite::ModifyPackedExtensions(&message); + TestUtilLite::ExpectPackedExtensionsModified(message); message.Clear(); - google::protobuf::TestUtilLite::ExpectPackedExtensionsClear(message); + TestUtilLite::ExpectPackedExtensionsClear(message); } } TEST(Lite, AllLite5) { - string data; + std::string data; { // Test that if an optional or required message/group field appears multiple // times in the input, they need to be merged. - google::protobuf::unittest::TestParsingMergeLite::RepeatedFieldsGenerator generator; - google::protobuf::unittest::TestAllTypesLite* msg1; - google::protobuf::unittest::TestAllTypesLite* msg2; - google::protobuf::unittest::TestAllTypesLite* msg3; + unittest::TestParsingMergeLite::RepeatedFieldsGenerator generator; + unittest::TestAllTypesLite* msg1; + unittest::TestAllTypesLite* msg2; + unittest::TestAllTypesLite* msg3; -#define ASSIGN_REPEATED_FIELD(FIELD) \ - msg1 = generator.add_##FIELD(); \ - msg2 = generator.add_##FIELD(); \ - msg3 = generator.add_##FIELD(); \ +#define ASSIGN_REPEATED_FIELD(FIELD) \ + msg1 = generator.add_##FIELD(); \ + msg2 = generator.add_##FIELD(); \ + msg3 = generator.add_##FIELD(); \ AssignParsingMergeMessages(msg1, msg2, msg3) ASSIGN_REPEATED_FIELD(field1); @@ -202,9 +197,9 @@ TEST(Lite, AllLite5) { #undef ASSIGN_REPEATED_GROUP - string buffer; + std::string buffer; generator.SerializeToString(&buffer); - google::protobuf::unittest::TestParsingMergeLite parsing_merge; + unittest::TestParsingMergeLite parsing_merge; parsing_merge.ParseFromString(buffer); // Required and optional fields should be merged. @@ -213,100 +208,100 @@ TEST(Lite, AllLite5) { ExpectMessageMerged( parsing_merge.optionalgroup().optional_group_all_types()); ExpectMessageMerged(parsing_merge.GetExtension( - google::protobuf::unittest::TestParsingMergeLite::optional_ext)); + unittest::TestParsingMergeLite::optional_ext)); // Repeated fields should not be merged. EXPECT_EQ(parsing_merge.repeated_all_types_size(), 3); EXPECT_EQ(parsing_merge.repeatedgroup_size(), 3); EXPECT_EQ(parsing_merge.ExtensionSize( - google::protobuf::unittest::TestParsingMergeLite::repeated_ext), + unittest::TestParsingMergeLite::repeated_ext), 3); } } TEST(Lite, AllLite6) { - string data; + std::string data; // Test unknown fields support for lite messages. { protobuf_unittest::TestAllTypesLite message, message2; protobuf_unittest::TestEmptyMessageLite empty_message; - google::protobuf::TestUtilLite::ExpectClear(message); - google::protobuf::TestUtilLite::SetAllFields(&message); + TestUtilLite::ExpectClear(message); + TestUtilLite::SetAllFields(&message); data = message.SerializeAsString(); - empty_message.ParseFromString(data); + ASSERT_TRUE(empty_message.ParseFromString(data)); data.clear(); data = empty_message.SerializeAsString(); - message2.ParseFromString(data); + EXPECT_TRUE(message2.ParseFromString(data)); data = message2.SerializeAsString(); - google::protobuf::TestUtilLite::ExpectAllFieldsSet(message2); + TestUtilLite::ExpectAllFieldsSet(message2); message.Clear(); - google::protobuf::TestUtilLite::ExpectClear(message); + TestUtilLite::ExpectClear(message); } } TEST(Lite, AllLite7) { - string data; + std::string data; { protobuf_unittest::TestAllExtensionsLite message, message2; protobuf_unittest::TestEmptyMessageLite empty_message; - google::protobuf::TestUtilLite::ExpectExtensionsClear(message); - google::protobuf::TestUtilLite::SetAllExtensions(&message); + TestUtilLite::ExpectExtensionsClear(message); + TestUtilLite::SetAllExtensions(&message); data = message.SerializeAsString(); empty_message.ParseFromString(data); data.clear(); data = empty_message.SerializeAsString(); message2.ParseFromString(data); data = message2.SerializeAsString(); - google::protobuf::TestUtilLite::ExpectAllExtensionsSet(message2); + TestUtilLite::ExpectAllExtensionsSet(message2); message.Clear(); - google::protobuf::TestUtilLite::ExpectExtensionsClear(message); + TestUtilLite::ExpectExtensionsClear(message); } } TEST(Lite, AllLite8) { - string data; + std::string data; { protobuf_unittest::TestPackedTypesLite message, message2; protobuf_unittest::TestEmptyMessageLite empty_message; - google::protobuf::TestUtilLite::ExpectPackedClear(message); - google::protobuf::TestUtilLite::SetPackedFields(&message); + TestUtilLite::ExpectPackedClear(message); + TestUtilLite::SetPackedFields(&message); data = message.SerializeAsString(); empty_message.ParseFromString(data); data.clear(); data = empty_message.SerializeAsString(); message2.ParseFromString(data); data = message2.SerializeAsString(); - google::protobuf::TestUtilLite::ExpectPackedFieldsSet(message2); + TestUtilLite::ExpectPackedFieldsSet(message2); message.Clear(); - google::protobuf::TestUtilLite::ExpectPackedClear(message); + TestUtilLite::ExpectPackedClear(message); } } TEST(Lite, AllLite9) { - string data; + std::string data; { protobuf_unittest::TestPackedExtensionsLite message, message2; protobuf_unittest::TestEmptyMessageLite empty_message; - google::protobuf::TestUtilLite::ExpectPackedExtensionsClear(message); - google::protobuf::TestUtilLite::SetPackedExtensions(&message); + TestUtilLite::ExpectPackedExtensionsClear(message); + TestUtilLite::SetPackedExtensions(&message); data = message.SerializeAsString(); empty_message.ParseFromString(data); data.clear(); data = empty_message.SerializeAsString(); message2.ParseFromString(data); data = message2.SerializeAsString(); - google::protobuf::TestUtilLite::ExpectPackedExtensionsSet(message2); + TestUtilLite::ExpectPackedExtensionsSet(message2); message.Clear(); - google::protobuf::TestUtilLite::ExpectPackedExtensionsClear(message); + TestUtilLite::ExpectPackedExtensionsClear(message); } } TEST(Lite, AllLite10) { - string data; + std::string data; { // Test Unknown fields swap @@ -314,7 +309,7 @@ TEST(Lite, AllLite10) { SetAllTypesInEmptyMessageUnknownFields(&empty_message); SetSomeTypesInEmptyMessageUnknownFields(&empty_message2); data = empty_message.SerializeAsString(); - string data2 = empty_message2.SerializeAsString(); + std::string data2 = empty_message2.SerializeAsString(); empty_message.Swap(&empty_message2); EXPECT_EQ(data, empty_message2.SerializeAsString()); EXPECT_EQ(data2, empty_message.SerializeAsString()); @@ -322,7 +317,7 @@ TEST(Lite, AllLite10) { } TEST(Lite, AllLite11) { - string data; + std::string data; { // Test unknown fields swap with self @@ -335,7 +330,7 @@ TEST(Lite, AllLite11) { } TEST(Lite, AllLite12) { - string data; + std::string data; { // Test MergeFrom with unknown fields @@ -343,10 +338,10 @@ TEST(Lite, AllLite12) { protobuf_unittest::TestEmptyMessageLite empty_message, empty_message2; message.set_optional_int32(101); message.add_repeated_int32(201); - message.set_optional_nested_enum(google::protobuf::unittest::TestAllTypesLite::BAZ); + message.set_optional_nested_enum(unittest::TestAllTypesLite::BAZ); message2.set_optional_int64(102); message2.add_repeated_int64(202); - message2.set_optional_foreign_enum(google::protobuf::unittest::FOREIGN_LITE_BAZ); + message2.set_optional_foreign_enum(unittest::FOREIGN_LITE_BAZ); data = message.SerializeAsString(); empty_message.ParseFromString(data); @@ -365,22 +360,22 @@ TEST(Lite, AllLite12) { } TEST(Lite, AllLite13) { - string data; + std::string data; { // Test unknown enum value protobuf_unittest::TestAllTypesLite message; - string buffer; + std::string buffer; { - google::protobuf::io::StringOutputStream output_stream(&buffer); - google::protobuf::io::CodedOutputStream coded_output(&output_stream); - google::protobuf::internal::WireFormatLite::WriteTag( + io::StringOutputStream output_stream(&buffer); + io::CodedOutputStream coded_output(&output_stream); + internal::WireFormatLite::WriteTag( protobuf_unittest::TestAllTypesLite::kOptionalNestedEnumFieldNumber, - google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT, &coded_output); + internal::WireFormatLite::WIRETYPE_VARINT, &coded_output); coded_output.WriteVarint32(10); - google::protobuf::internal::WireFormatLite::WriteTag( + internal::WireFormatLite::WriteTag( protobuf_unittest::TestAllTypesLite::kRepeatedNestedEnumFieldNumber, - google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT, &coded_output); + internal::WireFormatLite::WIRETYPE_VARINT, &coded_output); coded_output.WriteVarint32(20); } message.ParseFromString(buffer); @@ -390,7 +385,7 @@ TEST(Lite, AllLite13) { } TEST(Lite, AllLite14) { - string data; + std::string data; { // Test Clear with unknown fields @@ -404,77 +399,76 @@ TEST(Lite, AllLite14) { // Tests for map lite ============================================= TEST(Lite, AllLite15) { - string data; + std::string data; { // Accessors protobuf_unittest::TestMapLite message; - google::protobuf::MapLiteTestUtil::SetMapFields(&message); - google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message); + MapLiteTestUtil::SetMapFields(&message); + MapLiteTestUtil::ExpectMapFieldsSet(message); - google::protobuf::MapLiteTestUtil::ModifyMapFields(&message); - google::protobuf::MapLiteTestUtil::ExpectMapFieldsModified(message); + MapLiteTestUtil::ModifyMapFields(&message); + MapLiteTestUtil::ExpectMapFieldsModified(message); } } TEST(Lite, AllLite16) { - string data; + std::string data; { // SetMapFieldsInitialized protobuf_unittest::TestMapLite message; - google::protobuf::MapLiteTestUtil::SetMapFieldsInitialized(&message); - google::protobuf::MapLiteTestUtil::ExpectMapFieldsSetInitialized(message); + MapLiteTestUtil::SetMapFieldsInitialized(&message); + MapLiteTestUtil::ExpectMapFieldsSetInitialized(message); } } TEST(Lite, AllLite17) { - string data; + std::string data; { // Clear protobuf_unittest::TestMapLite message; - google::protobuf::MapLiteTestUtil::SetMapFields(&message); + MapLiteTestUtil::SetMapFields(&message); message.Clear(); - google::protobuf::MapLiteTestUtil::ExpectClear(message); + MapLiteTestUtil::ExpectClear(message); } } TEST(Lite, AllLite18) { - string data; + std::string data; { // ClearMessageMap protobuf_unittest::TestMessageMapLite message; // Creates a TestAllTypes with default value - google::protobuf::TestUtilLite::ExpectClear( - (*message.mutable_map_int32_message())[0]); + TestUtilLite::ExpectClear((*message.mutable_map_int32_message())[0]); } } TEST(Lite, AllLite19) { - string data; + std::string data; { // CopyFrom protobuf_unittest::TestMapLite message1, message2; - google::protobuf::MapLiteTestUtil::SetMapFields(&message1); + MapLiteTestUtil::SetMapFields(&message1); message2.CopyFrom(message1); - google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2); + MapLiteTestUtil::ExpectMapFieldsSet(message2); // Copying from self should be a no-op. message2.CopyFrom(message2); - google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2); + MapLiteTestUtil::ExpectMapFieldsSet(message2); } } TEST(Lite, AllLite20) { - string data; + std::string data; { // CopyFromMessageMap @@ -492,93 +486,93 @@ TEST(Lite, AllLite20) { } TEST(Lite, AllLite21) { - string data; + std::string data; { // SwapWithEmpty protobuf_unittest::TestMapLite message1, message2; - google::protobuf::MapLiteTestUtil::SetMapFields(&message1); - google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message1); - google::protobuf::MapLiteTestUtil::ExpectClear(message2); + MapLiteTestUtil::SetMapFields(&message1); + MapLiteTestUtil::ExpectMapFieldsSet(message1); + MapLiteTestUtil::ExpectClear(message2); message1.Swap(&message2); - google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2); - google::protobuf::MapLiteTestUtil::ExpectClear(message1); + MapLiteTestUtil::ExpectMapFieldsSet(message2); + MapLiteTestUtil::ExpectClear(message1); } } TEST(Lite, AllLite22) { - string data; + std::string data; { // SwapWithSelf protobuf_unittest::TestMapLite message; - google::protobuf::MapLiteTestUtil::SetMapFields(&message); - google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message); + MapLiteTestUtil::SetMapFields(&message); + MapLiteTestUtil::ExpectMapFieldsSet(message); message.Swap(&message); - google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message); + MapLiteTestUtil::ExpectMapFieldsSet(message); } } TEST(Lite, AllLite23) { - string data; + std::string data; { // SwapWithOther protobuf_unittest::TestMapLite message1, message2; - google::protobuf::MapLiteTestUtil::SetMapFields(&message1); - google::protobuf::MapLiteTestUtil::SetMapFields(&message2); - google::protobuf::MapLiteTestUtil::ModifyMapFields(&message2); + MapLiteTestUtil::SetMapFields(&message1); + MapLiteTestUtil::SetMapFields(&message2); + MapLiteTestUtil::ModifyMapFields(&message2); message1.Swap(&message2); - google::protobuf::MapLiteTestUtil::ExpectMapFieldsModified(message1); - google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2); + MapLiteTestUtil::ExpectMapFieldsModified(message1); + MapLiteTestUtil::ExpectMapFieldsSet(message2); } } TEST(Lite, AllLite24) { - string data; + std::string data; { // CopyConstructor protobuf_unittest::TestMapLite message1; - google::protobuf::MapLiteTestUtil::SetMapFields(&message1); + MapLiteTestUtil::SetMapFields(&message1); protobuf_unittest::TestMapLite message2(message1); - google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2); + MapLiteTestUtil::ExpectMapFieldsSet(message2); } } TEST(Lite, AllLite25) { - string data; + std::string data; { // CopyAssignmentOperator protobuf_unittest::TestMapLite message1; - google::protobuf::MapLiteTestUtil::SetMapFields(&message1); + MapLiteTestUtil::SetMapFields(&message1); protobuf_unittest::TestMapLite message2; message2 = message1; - google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2); + MapLiteTestUtil::ExpectMapFieldsSet(message2); // Make sure that self-assignment does something sane. message2.operator=(message2); - google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2); + MapLiteTestUtil::ExpectMapFieldsSet(message2); } } TEST(Lite, AllLite26) { - string data; + std::string data; { // NonEmptyMergeFrom protobuf_unittest::TestMapLite message1, message2; - google::protobuf::MapLiteTestUtil::SetMapFields(&message1); + MapLiteTestUtil::SetMapFields(&message1); // This field will test merging into an empty spot. (*message2.mutable_map_int32_int32())[1] = 1; @@ -589,12 +583,12 @@ TEST(Lite, AllLite26) { (*message1.mutable_map_int32_double())[1] = 2; message1.MergeFrom(message2); - google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message1); + MapLiteTestUtil::ExpectMapFieldsSet(message1); } } TEST(Lite, AllLite27) { - string data; + std::string data; { // MergeFromMessageMap @@ -612,50 +606,49 @@ TEST(Lite, AllLite27) { } TEST(Lite, AllLite28) { - string data; + std::string data; { // Test the generated SerializeWithCachedSizesToArray() protobuf_unittest::TestMapLite message1, message2; - string data; - google::protobuf::MapLiteTestUtil::SetMapFields(&message1); + std::string data; + MapLiteTestUtil::SetMapFields(&message1); int size = message1.ByteSize(); data.resize(size); ::google::protobuf::uint8* start = reinterpret_cast<::google::protobuf::uint8*>(::google::protobuf::string_as_array(&data)); ::google::protobuf::uint8* end = message1.SerializeWithCachedSizesToArray(start); EXPECT_EQ(size, end - start); EXPECT_TRUE(message2.ParseFromString(data)); - google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2); + MapLiteTestUtil::ExpectMapFieldsSet(message2); } } TEST(Lite, AllLite29) { - string data; + std::string data; { // Test the generated SerializeWithCachedSizes() protobuf_unittest::TestMapLite message1, message2; - google::protobuf::MapLiteTestUtil::SetMapFields(&message1); + MapLiteTestUtil::SetMapFields(&message1); int size = message1.ByteSize(); - string data; + std::string data; data.resize(size); { // Allow the output stream to buffer only one byte at a time. - google::protobuf::io::ArrayOutputStream array_stream( - ::google::protobuf::string_as_array(&data), size, 1); - google::protobuf::io::CodedOutputStream output_stream(&array_stream); + io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1); + io::CodedOutputStream output_stream(&array_stream); message1.SerializeWithCachedSizes(&output_stream); EXPECT_FALSE(output_stream.HadError()); EXPECT_EQ(size, output_stream.ByteCount()); } EXPECT_TRUE(message2.ParseFromString(data)); - google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2); + MapLiteTestUtil::ExpectMapFieldsSet(message2); } } TEST(Lite, AllLite32) { - string data; + std::string data; { // Proto2UnknownEnum @@ -664,14 +657,14 @@ TEST(Lite, AllLite32) { protobuf_unittest::E_PROTO2_MAP_ENUM_FOO_LITE; (*from.mutable_unknown_map_field())[0] = protobuf_unittest::E_PROTO2_MAP_ENUM_EXTRA_LITE; - string data; + std::string data; from.SerializeToString(&data); protobuf_unittest::TestEnumMapLite to; EXPECT_TRUE(to.ParseFromString(data)); EXPECT_EQ(0, to.unknown_map_field().size()); EXPECT_FALSE(to.mutable_unknown_fields()->empty()); - EXPECT_EQ(1, to.known_map_field().size()); + ASSERT_EQ(1, to.known_map_field().size()); EXPECT_EQ(protobuf_unittest::PROTO2_MAP_ENUM_FOO_LITE, to.known_map_field().at(0)); @@ -679,141 +672,147 @@ TEST(Lite, AllLite32) { from.Clear(); to.SerializeToString(&data); EXPECT_TRUE(from.ParseFromString(data)); - EXPECT_EQ(1, from.known_map_field().size()); + ASSERT_EQ(1, from.known_map_field().size()); EXPECT_EQ(protobuf_unittest::E_PROTO2_MAP_ENUM_FOO_LITE, from.known_map_field().at(0)); - EXPECT_EQ(1, from.unknown_map_field().size()); + ASSERT_EQ(1, from.unknown_map_field().size()); EXPECT_EQ(protobuf_unittest::E_PROTO2_MAP_ENUM_EXTRA_LITE, from.unknown_map_field().at(0)); } } TEST(Lite, AllLite33) { - string data; + std::string data; { // StandardWireFormat protobuf_unittest::TestMapLite message; - string data = "\x0A\x04\x08\x01\x10\x01"; + std::string data = "\x0A\x04\x08\x01\x10\x01"; EXPECT_TRUE(message.ParseFromString(data)); - EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_EQ(1, message.map_int32_int32().size()); EXPECT_EQ(1, message.map_int32_int32().at(1)); } } TEST(Lite, AllLite34) { - string data; + std::string data; { // UnorderedWireFormat protobuf_unittest::TestMapLite message; // put value before key in wire format - string data = "\x0A\x04\x10\x01\x08\x02"; + std::string data = "\x0A\x04\x10\x01\x08\x02"; EXPECT_TRUE(message.ParseFromString(data)); - EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_EQ(1, message.map_int32_int32().size()); + ASSERT_NE(message.map_int32_int32().find(2), + message.map_int32_int32().end()); EXPECT_EQ(1, message.map_int32_int32().at(2)); } } TEST(Lite, AllLite35) { - string data; + std::string data; { // DuplicatedKeyWireFormat protobuf_unittest::TestMapLite message; // Two key fields in wire format - string data = "\x0A\x06\x08\x01\x08\x02\x10\x01"; + std::string data = "\x0A\x06\x08\x01\x08\x02\x10\x01"; EXPECT_TRUE(message.ParseFromString(data)); - EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_EQ(1, message.map_int32_int32().size()); EXPECT_EQ(1, message.map_int32_int32().at(2)); } } TEST(Lite, AllLite36) { - string data; + std::string data; { // DuplicatedValueWireFormat protobuf_unittest::TestMapLite message; // Two value fields in wire format - string data = "\x0A\x06\x08\x01\x10\x01\x10\x02"; + std::string data = "\x0A\x06\x08\x01\x10\x01\x10\x02"; EXPECT_TRUE(message.ParseFromString(data)); - EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_EQ(1, message.map_int32_int32().size()); EXPECT_EQ(2, message.map_int32_int32().at(1)); } } TEST(Lite, AllLite37) { - string data; + std::string data; { // MissedKeyWireFormat protobuf_unittest::TestMapLite message; // No key field in wire format - string data = "\x0A\x02\x10\x01"; + std::string data = "\x0A\x02\x10\x01"; EXPECT_TRUE(message.ParseFromString(data)); - EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_EQ(1, message.map_int32_int32().size()); + ASSERT_NE(message.map_int32_int32().find(0), + message.map_int32_int32().end()); EXPECT_EQ(1, message.map_int32_int32().at(0)); } } TEST(Lite, AllLite38) { - string data; + std::string data; { // MissedValueWireFormat protobuf_unittest::TestMapLite message; // No value field in wire format - string data = "\x0A\x02\x08\x01"; + std::string data = "\x0A\x02\x08\x01"; EXPECT_TRUE(message.ParseFromString(data)); - EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_EQ(1, message.map_int32_int32().size()); + ASSERT_NE(message.map_int32_int32().find(1), + message.map_int32_int32().end()); EXPECT_EQ(0, message.map_int32_int32().at(1)); } } TEST(Lite, AllLite39) { - string data; + std::string data; { // UnknownFieldWireFormat protobuf_unittest::TestMapLite message; // Unknown field in wire format - string data = "\x0A\x06\x08\x02\x10\x03\x18\x01"; + std::string data = "\x0A\x06\x08\x02\x10\x03\x18\x01"; EXPECT_TRUE(message.ParseFromString(data)); - EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_EQ(1, message.map_int32_int32().size()); EXPECT_EQ(3, message.map_int32_int32().at(2)); } } TEST(Lite, AllLite40) { - string data; + std::string data; { // CorruptedWireFormat protobuf_unittest::TestMapLite message; // corrupted data in wire format - string data = "\x0A\x06\x08\x02\x11\x03"; + std::string data = "\x0A\x06\x08\x02\x11\x03"; EXPECT_FALSE(message.ParseFromString(data)); } } TEST(Lite, AllLite41) { - string data; + std::string data; { // IsInitialized @@ -832,33 +831,33 @@ TEST(Lite, AllLite41) { } TEST(Lite, AllLite42) { - string data; + std::string data; { - // Check that adding more values to enum does not corrupt message - // when passed through an old client. - protobuf_unittest::V2MessageLite v2_message; - v2_message.set_int_field(800); - // Set enum field to the value not understood by the old client. - v2_message.set_enum_field(protobuf_unittest::V2_SECOND); - string v2_bytes = v2_message.SerializeAsString(); + // Check that adding more values to enum does not corrupt message + // when passed through an old client. + protobuf_unittest::V2MessageLite v2_message; + v2_message.set_int_field(800); + // Set enum field to the value not understood by the old client. + v2_message.set_enum_field(protobuf_unittest::V2_SECOND); + std::string v2_bytes = v2_message.SerializeAsString(); - protobuf_unittest::V1MessageLite v1_message; - v1_message.ParseFromString(v2_bytes); - EXPECT_TRUE(v1_message.IsInitialized()); - EXPECT_EQ(v1_message.int_field(), v2_message.int_field()); - // V1 client does not understand V2_SECOND value, so it discards it and - // uses default value instead. - EXPECT_EQ(v1_message.enum_field(), protobuf_unittest::V1_FIRST); + protobuf_unittest::V1MessageLite v1_message; + v1_message.ParseFromString(v2_bytes); + EXPECT_TRUE(v1_message.IsInitialized()); + EXPECT_EQ(v1_message.int_field(), v2_message.int_field()); + // V1 client does not understand V2_SECOND value, so it discards it and + // uses default value instead. + EXPECT_EQ(v1_message.enum_field(), protobuf_unittest::V1_FIRST); - // However, when re-serialized, it should preserve enum value. - string v1_bytes = v1_message.SerializeAsString(); + // However, when re-serialized, it should preserve enum value. + std::string v1_bytes = v1_message.SerializeAsString(); - protobuf_unittest::V2MessageLite same_v2_message; - same_v2_message.ParseFromString(v1_bytes); + protobuf_unittest::V2MessageLite same_v2_message; + same_v2_message.ParseFromString(v1_bytes); - EXPECT_EQ(v2_message.int_field(), same_v2_message.int_field()); - EXPECT_EQ(v2_message.enum_field(), same_v2_message.enum_field()); + EXPECT_EQ(v2_message.int_field(), same_v2_message.int_field()); + EXPECT_EQ(v2_message.enum_field(), same_v2_message.enum_field()); } } @@ -868,14 +867,14 @@ TEST(Lite, AllLite43) { protobuf_unittest::TestOneofParsingLite message1; message1.set_oneof_int32(17); - string serialized; + std::string serialized; EXPECT_TRUE(message1.SerializeToString(&serialized)); // Submessage { protobuf_unittest::TestOneofParsingLite message2; message2.mutable_oneof_submessage(); - google::protobuf::io::CodedInputStream input_stream( + io::CodedInputStream input_stream( reinterpret_cast(serialized.data()), serialized.size()); EXPECT_TRUE(message2.MergeFromCodedStream(&input_stream)); EXPECT_EQ(17, message2.oneof_int32()); @@ -885,7 +884,7 @@ TEST(Lite, AllLite43) { { protobuf_unittest::TestOneofParsingLite message2; message2.set_oneof_string("string"); - google::protobuf::io::CodedInputStream input_stream( + io::CodedInputStream input_stream( reinterpret_cast(serialized.data()), serialized.size()); EXPECT_TRUE(message2.MergeFromCodedStream(&input_stream)); EXPECT_EQ(17, message2.oneof_int32()); @@ -895,7 +894,7 @@ TEST(Lite, AllLite43) { { protobuf_unittest::TestOneofParsingLite message2; message2.set_oneof_bytes("bytes"); - google::protobuf::io::CodedInputStream input_stream( + io::CodedInputStream input_stream( reinterpret_cast(serialized.data()), serialized.size()); EXPECT_TRUE(message2.MergeFromCodedStream(&input_stream)); EXPECT_EQ(17, message2.oneof_int32()); @@ -910,11 +909,11 @@ TEST(Lite, AllLite44) { { protobuf_unittest::TestOneofParsingLite original; original.set_oneof_int32(17); - string serialized; + std::string serialized; EXPECT_TRUE(original.SerializeToString(&serialized)); protobuf_unittest::TestOneofParsingLite parsed; for (int i = 0; i < 2; ++i) { - google::protobuf::io::CodedInputStream input_stream( + io::CodedInputStream input_stream( reinterpret_cast(serialized.data()), serialized.size()); EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream)); @@ -926,11 +925,11 @@ TEST(Lite, AllLite44) { { protobuf_unittest::TestOneofParsingLite original; original.mutable_oneof_submessage()->set_optional_int32(5); - string serialized; + std::string serialized; EXPECT_TRUE(original.SerializeToString(&serialized)); protobuf_unittest::TestOneofParsingLite parsed; for (int i = 0; i < 2; ++i) { - google::protobuf::io::CodedInputStream input_stream( + io::CodedInputStream input_stream( reinterpret_cast(serialized.data()), serialized.size()); EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream)); @@ -942,11 +941,11 @@ TEST(Lite, AllLite44) { { protobuf_unittest::TestOneofParsingLite original; original.set_oneof_string("string"); - string serialized; + std::string serialized; EXPECT_TRUE(original.SerializeToString(&serialized)); protobuf_unittest::TestOneofParsingLite parsed; for (int i = 0; i < 2; ++i) { - google::protobuf::io::CodedInputStream input_stream( + io::CodedInputStream input_stream( reinterpret_cast(serialized.data()), serialized.size()); EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream)); @@ -958,11 +957,11 @@ TEST(Lite, AllLite44) { { protobuf_unittest::TestOneofParsingLite original; original.set_oneof_bytes("bytes"); - string serialized; + std::string serialized; EXPECT_TRUE(original.SerializeToString(&serialized)); protobuf_unittest::TestOneofParsingLite parsed; for (int i = 0; i < 2; ++i) { - google::protobuf::io::CodedInputStream input_stream( + io::CodedInputStream input_stream( reinterpret_cast(serialized.data()), serialized.size()); EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream)); @@ -974,11 +973,11 @@ TEST(Lite, AllLite44) { { protobuf_unittest::TestOneofParsingLite original; original.set_oneof_enum(protobuf_unittest::V2_SECOND); - string serialized; + std::string serialized; EXPECT_TRUE(original.SerializeToString(&serialized)); protobuf_unittest::TestOneofParsingLite parsed; for (int i = 0; i < 2; ++i) { - google::protobuf::io::CodedInputStream input_stream( + io::CodedInputStream input_stream( reinterpret_cast(serialized.data()), serialized.size()); EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream)); @@ -991,15 +990,15 @@ TEST(Lite, AllLite44) { TEST(Lite, AllLite45) { // Test unknown fields are not discarded upon parsing. - string data = "\20\1"; // varint 1 with field number 2 + std::string data = "\20\1"; // varint 1 with field number 2 protobuf_unittest::ForeignMessageLite a; EXPECT_TRUE(a.ParseFromString(data)); - google::protobuf::io::CodedInputStream input_stream( + io::CodedInputStream input_stream( reinterpret_cast(data.data()), data.size()); EXPECT_TRUE(a.MergePartialFromCodedStream(&input_stream)); - string serialized = a.SerializeAsString(); + std::string serialized = a.SerializeAsString(); EXPECT_EQ(serialized.substr(0, 2), data); EXPECT_EQ(serialized.substr(2), data); } @@ -1014,7 +1013,7 @@ TEST(Lite, AllLite45) { TEST(Lite, AllLite46) { protobuf_unittest::PackedInt32 packed; packed.add_repeated_int32(42); - string serialized; + std::string serialized; ASSERT_TRUE(packed.SerializeToString(&serialized)); protobuf_unittest::NonPackedInt32 non_packed; @@ -1026,7 +1025,7 @@ TEST(Lite, AllLite46) { TEST(Lite, AllLite47) { protobuf_unittest::NonPackedFixed32 non_packed; non_packed.add_repeated_fixed32(42); - string serialized; + std::string serialized; ASSERT_TRUE(non_packed.SerializeToString(&serialized)); protobuf_unittest::PackedFixed32 packed; @@ -1034,3 +1033,69 @@ TEST(Lite, AllLite47) { ASSERT_EQ(1, packed.repeated_fixed32_size()); EXPECT_EQ(42, packed.repeated_fixed32(0)); } + +TEST(Lite, MapCrash) { + // See b/113635730 + Arena arena; + auto msg = Arena::CreateMessage(&arena); + // Payload for the map with a enum varint that's longer > + // 10 bytes. This causes a parse fail and a subsequent delete. field 16 + // (map) tag = 128+2 = \202 \1 + // 13 long \15 + // int32 key = 1 (\10 \1) + // MapEnumLite value = too long varint (parse error) + EXPECT_FALSE(msg->ParseFromString( + "\202\1\15\10\1\200\200\200\200\200\200\200\200\200\200\1")); +} + +TEST(Lite, CorrectEnding) { + protobuf_unittest::TestAllTypesLite msg; + { + // All proto wireformat parsers should act the same on parsing data in as + // much as it concerns the parsing, ie. not the interpretation of the data. + // TestAllTypesLite is not a group inside another message. So in practice + // will not encounter an end-group tag. However the parser should behave + // like any wire format parser should. + static const char kWireFormat[] = "\204\1"; + io::CodedInputStream cis(reinterpret_cast(kWireFormat), 2); + // The old CodedInputStream parser got an optimization (ReadTagNoLastTag) + // for non-group messages (like TestAllTypesLite) which made it not accept + // end-group. This is not a real big deal, but I think going forward its + // good to have all parse loops behave 'exactly' the same. +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + EXPECT_TRUE(msg.MergePartialFromCodedStream(&cis)); + EXPECT_FALSE(cis.ConsumedEntireMessage()); + EXPECT_TRUE(cis.LastTagWas(132)); +#endif + } + { + // This is an incomplete end-group tag. This should be a genuine parse + // failure. + static const char kWireFormat[] = "\214"; + io::CodedInputStream cis(reinterpret_cast(kWireFormat), 1); + // Unfortunately the old parser detects a parse error in ReadTag and returns + // 0 (as it states 0 is an invalid tag). However 0 is not an invalid tag + // as it can be used to terminate the stream, so this returns true. +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + EXPECT_FALSE(msg.MergePartialFromCodedStream(&cis)); +#endif + } +} + +TEST(Lite, DebugString) { + protobuf_unittest::TestAllTypesLite message1, message2; + EXPECT_TRUE(HasPrefixString(message1.DebugString(), "MessageLite at 0x")); + EXPECT_TRUE(HasPrefixString(message2.DebugString(), "MessageLite at 0x")); + + // DebugString() and ShortDebugString() are the same for now. + EXPECT_EQ(message1.DebugString(), message1.ShortDebugString()); + + // Even identical lite protos should have different DebugString() output. Part + // of the reason for including the memory address is so that we get some + // non-determinism, which should make it easier for us to change the output + // later without breaking any code. + EXPECT_NE(message1.DebugString(), message2.DebugString()); +} + +} // namespace protobuf +} // namespace google diff --git a/third_party/protobuf/src/google/protobuf/map.h b/third_party/protobuf/src/google/protobuf/map.h index 6463ac2e..2750c023 100644 --- a/third_party/protobuf/src/google/protobuf/map.h +++ b/third_party/protobuf/src/google/protobuf/map.h @@ -49,6 +49,12 @@ #include #include +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + +#include + namespace google { namespace protobuf { @@ -57,7 +63,8 @@ class Map; class MapIterator; -template struct is_proto_enum; +template +struct is_proto_enum; namespace internal { template @@ -90,8 +97,7 @@ class MapPair { MapPair(const Key& other_first, const T& other_second) : first(other_first), second(other_second) {} explicit MapPair(const Key& other_first) : first(other_first), second() {} - MapPair(const MapPair& other) - : first(other.first), second(other.second) {} + MapPair(const MapPair& other) : first(other.first), second(other.second) {} ~MapPair() {} @@ -105,11 +111,11 @@ class MapPair { T second; private: - friend class ::google::protobuf::Arena; + friend class Arena; friend class Map; }; -// google::protobuf::Map is an associative container type used to store protobuf map +// Map is an associative container type used to store protobuf map // fields. Each Map instance may or may not use a different hash function, a // different iteration order, and so on. E.g., please don't examine // implementation details to decide if the following would work: @@ -177,11 +183,12 @@ class Map { private: void Init() { - elements_ = Arena::Create(arena_, 0u, hasher(), Allocator(arena_)); + elements_ = + Arena::Create(arena_, 0u, hasher(), Allocator(arena_)); } // re-implement std::allocator to use arena allocator for memory allocation. - // Used for google::protobuf::Map implementation. Users should not use this class + // Used for Map implementation. Users should not use this class // directly. template class MapAllocator { @@ -225,7 +232,7 @@ class Map { #if __cplusplus >= 201103L && !defined(GOOGLE_PROTOBUF_OS_APPLE) && \ !defined(GOOGLE_PROTOBUF_OS_NACL) && \ !defined(GOOGLE_PROTOBUF_OS_EMSCRIPTEN) - template + template void construct(NodeType* p, Args&&... args) { // Clang 3.6 doesn't compile static casting to void* directly. (Issue // #1266) According C++ standard 5.2.9/1: "The static_cast operator shall @@ -235,7 +242,7 @@ class Map { NodeType(std::forward(args)...); } - template + template void destroy(NodeType* p) { p->~NodeType(); } @@ -268,9 +275,7 @@ class Map { // To support gcc-4.4, which does not properly // support templated friend classes - Arena* arena() const { - return arena_; - } + Arena* arena() const { return arena_; } private: typedef void DestructorSkippable_; @@ -408,7 +413,7 @@ class Map { : node_(NodePtrFromKeyPtr(*tree_it)), m_(m), bucket_index_(index) { // Invariant: iterators that use buckets with trees have an even // bucket_index_. - GOOGLE_DCHECK_EQ(bucket_index_ % 2, 0); + GOOGLE_DCHECK_EQ(bucket_index_ % 2, 0u); } // Advance through buckets, looking for the first that isn't empty. @@ -448,7 +453,7 @@ class Map { if (is_list) { SearchFrom(bucket_index_ + 1); } else { - GOOGLE_DCHECK_EQ(bucket_index_ & 1, 0); + GOOGLE_DCHECK_EQ(bucket_index_ & 1, 0u); Tree* tree = static_cast(m_->table_[bucket_index_]); if (++tree_it == tree->end()) { SearchFrom(bucket_index_ + 2); @@ -477,8 +482,7 @@ class Map { // Force bucket_index_ to be in range. bucket_index_ &= (m_->num_buckets_ - 1); // Common case: the bucket we think is relevant points to node_. - if (m_->table_[bucket_index_] == static_cast(node_)) - return true; + if (m_->table_[bucket_index_] == static_cast(node_)) return true; // Less common: the bucket is a linked list with node_ somewhere in it, // but not at the head. if (m_->TableEntryIsNonEmptyList(bucket_index_)) { @@ -553,6 +557,7 @@ class Map { iterator find(const Key& k) { return iterator(FindHelper(k).first); } const_iterator find(const Key& k) const { return find(k, NULL); } + bool contains(const Key& k) const { return find(k) != end(); } // In traditional C++ style, this performs "insert if not present." std::pair insert(const KeyValuePair& kv) { @@ -622,7 +627,7 @@ class Map { } DestroyNode(item); --num_elements_; - if (GOOGLE_PREDICT_FALSE(b == index_of_first_non_null_)) { + if (PROTOBUF_PREDICT_FALSE(b == index_of_first_non_null_)) { while (index_of_first_non_null_ < num_buckets_ && table_[index_of_first_non_null_] == NULL) { ++index_of_first_non_null_; @@ -679,7 +684,7 @@ class Map { if (TableEntryIsEmpty(b)) { result = InsertUniqueInList(b, node); } else if (TableEntryIsNonEmptyList(b)) { - if (GOOGLE_PREDICT_FALSE(TableEntryIsTooLong(b))) { + if (PROTOBUF_PREDICT_FALSE(TableEntryIsTooLong(b))) { TreeConvert(b); result = InsertUniqueInTree(b, node); GOOGLE_DCHECK_EQ(result.bucket_index_, b & ~static_cast(1)); @@ -713,10 +718,9 @@ class Map { GOOGLE_DCHECK_EQ(table_[b], table_[b ^ 1]); // Maintain the invariant that node->next is NULL for all Nodes in Trees. node->next = NULL; - return iterator(static_cast(table_[b]) - ->insert(KeyPtrFromNodePtr(node)) - .first, - this, b & ~static_cast(1)); + return iterator( + static_cast(table_[b])->insert(KeyPtrFromNodePtr(node)).first, + this, b & ~static_cast(1)); } // Returns whether it did resize. Currently this is only used when @@ -734,13 +738,13 @@ class Map { // We don't care how many elements are in trees. If a lot are, // we may resize even though there are many empty buckets. In // practice, this seems fine. - if (GOOGLE_PREDICT_FALSE(new_size >= hi_cutoff)) { + if (PROTOBUF_PREDICT_FALSE(new_size >= hi_cutoff)) { if (num_buckets_ <= max_size() / 2) { Resize(num_buckets_ * 2); return true; } - } else if (GOOGLE_PREDICT_FALSE(new_size <= lo_cutoff && - num_buckets_ > kMinTableSize)) { + } else if (PROTOBUF_PREDICT_FALSE(new_size <= lo_cutoff && + num_buckets_ > kMinTableSize)) { size_type lg2_of_size_reduction_factor = 1; // It's possible we want to shrink a lot here... size() could even be 0. // So, estimate how much to shrink by making sure we don't shrink so @@ -827,7 +831,7 @@ class Map { } static bool TableEntryIsTree(void* const* table, size_type b) { return !TableEntryIsEmpty(table, b) && - !TableEntryIsNonEmptyList(table, b); + !TableEntryIsNonEmptyList(table, b); } static bool TableEntryIsList(void* const* table, size_type b) { return !TableEntryIsTree(table, b); @@ -935,7 +939,7 @@ class Map { size_type s = static_cast(reinterpret_cast(this)); #if defined(__x86_64__) && defined(__GNUC__) uint32 hi, lo; - asm("rdtsc" : "=a" (lo), "=d" (hi)); + asm("rdtsc" : "=a"(lo), "=d"(hi)); s += ((static_cast(hi) << 32) | lo); #endif return s; @@ -965,9 +969,7 @@ class Map { const_iterator() {} explicit const_iterator(const InnerIt& it) : it_(it) {} - const_reference operator*() const { - return *it_->value(); - } + const_reference operator*() const { return *it_->value(); } const_pointer operator->() const { return &(operator*()); } const_iterator& operator++() { @@ -1044,12 +1046,11 @@ class Map { // Element access T& operator[](const key_type& key) { - value_type** value = &(*elements_)[key]; + value_type** value = &(*elements_)[key]; if (*value == NULL) { *value = CreateValueTypeInternal(key); - internal::MapValueInitializer::value, - T>::Initialize((*value)->second, - default_enum_value_); + internal::MapValueInitializer::value, T>::Initialize( + (*value)->second, default_enum_value_); } return (*value)->second; } @@ -1074,6 +1075,7 @@ class Map { return const_iterator(iterator(elements_->find(key))); } iterator find(const key_type& key) { return iterator(elements_->find(key)); } + bool contains(const Key& key) const { return elements_->contains(key); } std::pair equal_range( const key_type& key) const { const_iterator it = find(key); @@ -1203,7 +1205,7 @@ class Map { int default_enum_value_; InnerMap* elements_; - friend class ::google::protobuf::Arena; + friend class Arena; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; template + #endif // GOOGLE_PROTOBUF_MAP_H__ diff --git a/third_party/protobuf/src/google/protobuf/map_entry.h b/third_party/protobuf/src/google/protobuf/map_entry.h index 801def97..666266da 100644 --- a/third_party/protobuf/src/google/protobuf/map_entry.h +++ b/third_party/protobuf/src/google/protobuf/map_entry.h @@ -35,9 +35,16 @@ #include #include #include +#include #include #include -#include +#include + +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif namespace google { namespace protobuf { @@ -48,8 +55,10 @@ template class MapField; } -} +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace internal { @@ -95,10 +104,24 @@ class MapEntry typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; + typedef + typename MapEntryImpl::KeyTypeHandler + KeyTypeHandler; + typedef typename MapEntryImpl< + Derived, Message, Key, Value, kKeyFieldType, kValueFieldType, + default_enum_value>::ValueTypeHandler ValueTypeHandler; + size_t SpaceUsedLong() const override { + size_t size = sizeof(Derived); + size += KeyTypeHandler::SpaceUsedInMapEntryLong(this->key_); + size += ValueTypeHandler::SpaceUsedInMapEntryLong(this->value_); + return size; + } + InternalMetadataWithArena _internal_metadata_; private: - friend class ::google::protobuf::Arena; + friend class ::PROTOBUF_NAMESPACE_ID::Arena; template @@ -135,6 +158,8 @@ struct DeconstructMapEntry > { } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_MAP_ENTRY_H__ diff --git a/third_party/protobuf/src/google/protobuf/map_entry_lite.h b/third_party/protobuf/src/google/protobuf/map_entry_lite.h index 85a0bed7..c7d7558b 100644 --- a/third_party/protobuf/src/google/protobuf/map_entry_lite.h +++ b/third_party/protobuf/src/google/protobuf/map_entry_lite.h @@ -32,14 +32,23 @@ #define GOOGLE_PROTOBUF_MAP_ENTRY_LITE_H__ #include +#include #include +#include +#include #include #include +#include #include #include -#include -#include +#include +#include + +#include +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif namespace google { namespace protobuf { @@ -54,7 +63,9 @@ template (&other)); + void CheckTypeAndMergeFrom(const MessageLite& other) override { + MergeFromInternal(*::google::protobuf::internal::DownCast(&other)); } - bool MergePartialFromCodedStream(::google::protobuf::io::CodedInputStream* input) { +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ParseContext* ctx) final { + while (!ctx->Done(&ptr)) { + uint32 tag; + ptr = ReadTag(ptr, &tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + if (tag == kKeyTag) { + set_has_key(); + KeyMapEntryAccessorType* key = mutable_key(); + ptr = KeyTypeHandler::Read(ptr, ctx, key); + if (!Derived::ValidateKey(key)) return nullptr; + } else if (tag == kValueTag) { + set_has_value(); + ValueMapEntryAccessorType* value = mutable_value(); + ptr = ValueTypeHandler::Read(ptr, ctx, value); + if (!Derived::ValidateValue(value)) return nullptr; + } else { + if (tag == 0 || WireFormatLite::GetTagWireType(tag) == + WireFormatLite::WIRETYPE_END_GROUP) { + ctx->SetLastTag(tag); + return ptr; + } + ptr = UnknownFieldParse(tag, static_cast(nullptr), ptr, ctx); + } + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + } + return ptr; + } +#else + bool MergePartialFromCodedStream(io::CodedInputStream* input) override { uint32 tag; for (;;) { @@ -213,9 +253,8 @@ class MapEntryImpl : public Base { break; default: - if (tag == 0 || - WireFormatLite::GetTagWireType(tag) == - WireFormatLite::WIRETYPE_END_GROUP) { + if (tag == 0 || WireFormatLite::GetTagWireType(tag) == + WireFormatLite::WIRETYPE_END_GROUP) { return true; } if (!WireFormatLite::SkipField(input, tag)) return false; @@ -223,62 +262,59 @@ class MapEntryImpl : public Base { } } } +#endif - size_t ByteSizeLong() const { + size_t ByteSizeLong() const override { size_t size = 0; - size += has_key() ? - kTagSize + static_cast(KeyTypeHandler::ByteSize(key())) : 0; - size += has_value() ? - kTagSize + static_cast(ValueTypeHandler::ByteSize(value())) : 0; + size += has_key() ? kTagSize + + static_cast(KeyTypeHandler::ByteSize(key())) + : 0; + size += has_value() + ? kTagSize + + static_cast(ValueTypeHandler::ByteSize(value())) + : 0; return size; } - void SerializeWithCachedSizes(::google::protobuf::io::CodedOutputStream* output) const { + void SerializeWithCachedSizes(io::CodedOutputStream* output) const override { KeyTypeHandler::Write(kKeyFieldNumber, key(), output); ValueTypeHandler::Write(kValueFieldNumber, value(), output); } - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(bool deterministic, - ::google::protobuf::uint8* output) const { - output = KeyTypeHandler::InternalWriteToArray(kKeyFieldNumber, key(), - deterministic, output); - output = ValueTypeHandler::InternalWriteToArray(kValueFieldNumber, value(), - deterministic, output); + ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( + ::google::protobuf::uint8* output) const override { + output = KeyTypeHandler::WriteToArray(kKeyFieldNumber, key(), output); + output = ValueTypeHandler::WriteToArray(kValueFieldNumber, value(), output); return output; } // Don't override SerializeWithCachedSizesToArray. Use MessageLite's. - int GetCachedSize() const { + int GetCachedSize() const override { int size = 0; - size += has_key() - ? static_cast(kTagSize) + KeyTypeHandler::GetCachedSize(key()) - : 0; - size += has_value() - ? static_cast(kTagSize) + ValueTypeHandler::GetCachedSize(value()) - : 0; + size += has_key() ? static_cast(kTagSize) + + KeyTypeHandler::GetCachedSize(key()) + : 0; + size += has_value() ? static_cast(kTagSize) + + ValueTypeHandler::GetCachedSize(value()) + : 0; return size; } - bool IsInitialized() const { return ValueTypeHandler::IsInitialized(value_); } + bool IsInitialized() const override { + return ValueTypeHandler::IsInitialized(value_); + } - Base* New() const { + Base* New() const override { Derived* entry = new Derived; return entry; } - Base* New(Arena* arena) const { + Base* New(Arena* arena) const override { Derived* entry = Arena::CreateMessage(arena); return entry; } - size_t SpaceUsedLong() const { - size_t size = sizeof(Derived); - size += KeyTypeHandler::SpaceUsedInMapEntryLong(key_); - size += ValueTypeHandler::SpaceUsedInMapEntryLong(value_); - return size; - } - protected: // We can't declare this function directly here as it would hide the other // overload (const Message&). @@ -298,10 +334,10 @@ class MapEntryImpl : public Base { } public: - void Clear() { + void Clear() override { KeyTypeHandler::Clear(&key_, GetArenaNoVirtual()); - ValueTypeHandler::ClearMaybeByDefaultEnum( - &value_, GetArenaNoVirtual(), default_enum_value); + ValueTypeHandler::ClearMaybeByDefaultEnum(&value_, GetArenaNoVirtual(), + default_enum_value); clear_has_key(); clear_has_value(); } @@ -312,20 +348,18 @@ class MapEntryImpl : public Base { ValueTypeHandler::AssignDefaultValue(&d->value_); } - Arena* GetArena() const { - return GetArenaNoVirtual(); - } + Arena* GetArena() const override { return GetArenaNoVirtual(); } - // Create a MapEntryImpl for given key and value from google::protobuf::Map in + // Create a MapEntryImpl for given key and value from Map in // serialization. This function is only called when value is enum. Enum is // treated differently because its type in MapEntry is int and its type in - // google::protobuf::Map is enum. We cannot create a reference to int from an enum. + // Map is enum. We cannot create a reference to int from an enum. static Derived* EnumWrap(const Key& key, const Value value, Arena* arena) { return Arena::CreateMessage(arena, key, value); } // Like above, but for all the other types. This avoids value copy to create - // MapEntryImpl from google::protobuf::Map in serialization. + // MapEntryImpl from Map in serialization. static Derived* Wrap(const Key& key, const Value& value, Arena* arena) { return Arena::CreateMessage(arena, key, value); } @@ -336,11 +370,14 @@ class MapEntryImpl : public Base { class Parser { public: explicit Parser(MapField* mf) : mf_(mf), map_(mf->MutableMap()) {} + ~Parser() { + if (entry_ != nullptr && entry_->GetArena() == nullptr) delete entry_; + } // This does what the typical MergePartialFromCodedStream() is expected to // do, with the additional side-effect that if successful (i.e., if true is // going to be its return value) it inserts the key-value pair into map_. - bool MergePartialFromCodedStream(::google::protobuf::io::CodedInputStream* input) { + bool MergePartialFromCodedStream(io::CodedInputStream* input) { // Look for the expected thing: a key and then a value. If it fails, // invoke the enclosing class's MergePartialFromCodedStream, or return // false if that would be pointless. @@ -353,11 +390,11 @@ class MapEntryImpl : public Base { int size; input->GetDirectBufferPointerInline(&data, &size); // We could use memcmp here, but we don't bother. The tag is one byte. - GOOGLE_COMPILE_ASSERT(kTagSize == 1, tag_size_error); + static_assert(kTagSize == 1, "tag size must be 1"); if (size > 0 && *reinterpret_cast(data) == kValueTag) { typename Map::size_type map_size = map_->size(); value_ptr_ = &(*map_)[key_]; - if (GOOGLE_PREDICT_TRUE(map_size != map_->size())) { + if (PROTOBUF_PREDICT_TRUE(map_size != map_->size())) { // We created a new key-value pair. Fill in the value. typedef typename MapIf::type T; @@ -375,64 +412,118 @@ class MapEntryImpl : public Base { key_ = Key(); } - entry_.reset(mf_->NewEntry()); + NewEntry(); *entry_->mutable_key() = key_; const bool result = entry_->MergePartialFromCodedStream(input); if (result) UseKeyAndValueFromEntry(); - if (entry_->GetArena() != NULL) entry_.release(); return result; } + const char* _InternalParse(const char* ptr, ParseContext* ctx) { + if (PROTOBUF_PREDICT_TRUE(!ctx->Done(&ptr) && *ptr == kKeyTag)) { + ptr = KeyTypeHandler::Read(ptr + 1, ctx, &key_); + if (PROTOBUF_PREDICT_FALSE(!ptr || !Derived::ValidateKey(&key_))) { + return nullptr; + } + if (PROTOBUF_PREDICT_TRUE(!ctx->Done(&ptr) && *ptr == kValueTag)) { + typename Map::size_type map_size = map_->size(); + value_ptr_ = &(*map_)[key_]; + if (PROTOBUF_PREDICT_TRUE(map_size != map_->size())) { + using T = + typename MapIf::type; + ptr = ValueTypeHandler::Read(ptr + 1, ctx, + reinterpret_cast(value_ptr_)); + if (PROTOBUF_PREDICT_FALSE(!ptr || + !Derived::ValidateValue(value_ptr_))) { + map_->erase(key_); // Failure! Undo insertion. + return nullptr; + } + if (PROTOBUF_PREDICT_TRUE(ctx->Done(&ptr))) return ptr; + if (!ptr) return nullptr; + NewEntry(); + ValueMover::Move(value_ptr_, entry_->mutable_value()); + map_->erase(key_); + goto move_key; + } + } else { + if (!ptr) return nullptr; + } + NewEntry(); + move_key: + KeyMover::Move(&key_, entry_->mutable_key()); + } else { + if (!ptr) return nullptr; + NewEntry(); + } + ptr = entry_->_InternalParse(ptr, ctx); + if (ptr) UseKeyAndValueFromEntry(); + return ptr; + } + + template + const char* ParseWithEnumValidation(const char* ptr, ParseContext* ctx, + bool (*is_valid)(int), uint32 field_num, + Metadata* metadata) { + auto entry = NewEntry(); + ptr = entry->_InternalParse(ptr, ctx); + if (!ptr) return nullptr; + if (is_valid(entry->value())) { + UseKeyAndValueFromEntry(); + } else { + WriteLengthDelimited(field_num, entry->SerializeAsString(), + metadata->mutable_unknown_fields()); + } + return ptr; + } + + MapEntryImpl* NewEntry() { return entry_ = mf_->NewEntry(); } + const Key& key() const { return key_; } const Value& value() const { return *value_ptr_; } + const Key& entry_key() const { return entry_->key(); } + const Value& entry_value() const { return entry_->value(); } + private: - void UseKeyAndValueFromEntry() GOOGLE_PROTOBUF_ATTRIBUTE_COLD { + void UseKeyAndValueFromEntry() { // Update key_ in case we need it later (because key() is called). // This is potentially inefficient, especially if the key is // expensive to copy (e.g., a long string), but this is a cold // path, so it's not a big deal. key_ = entry_->key(); value_ptr_ = &(*map_)[key_]; - MoveHelper::Move(entry_->mutable_value(), value_ptr_); + ValueMover::Move(entry_->mutable_value(), value_ptr_); } // After reading a key and value successfully, and inserting that data // into map_, we are not at the end of the input. This is unusual, but // allowed by the spec. - bool ReadBeyondKeyValuePair(::google::protobuf::io::CodedInputStream* input) - GOOGLE_PROTOBUF_ATTRIBUTE_COLD { - typedef MoveHelper KeyMover; - typedef MoveHelper ValueMover; - entry_.reset(mf_->NewEntry()); + bool ReadBeyondKeyValuePair(io::CodedInputStream* input) PROTOBUF_COLD { + NewEntry(); ValueMover::Move(value_ptr_, entry_->mutable_value()); map_->erase(key_); KeyMover::Move(&key_, entry_->mutable_key()); const bool result = entry_->MergePartialFromCodedStream(input); if (result) UseKeyAndValueFromEntry(); - if (entry_->GetArena() != NULL) entry_.release(); return result; } + typedef MoveHelper + KeyMover; + typedef MoveHelper + ValueMover; + MapField* const mf_; Map* const map_; Key key_; Value* value_ptr_; - // On the fast path entry_ is not used. And, when entry_ is used, it's set - // to mf_->NewEntry(), so in the arena case we must call entry_.release. - std::unique_ptr entry_; + MapEntryImpl* entry_ = nullptr; }; protected: @@ -443,11 +534,11 @@ class MapEntryImpl : public Base { bool has_value() const { return (_has_bits_[0] & 0x00000002u) != 0; } void clear_has_value() { _has_bits_[0] &= ~0x00000002u; } - private: + public: // Serializing a generated message containing map field involves serializing - // key-value pairs from google::protobuf::Map. The wire format of each key-value pair + // key-value pairs from Map. The wire format of each key-value pair // after serialization should be the same as that of a MapEntry message - // containing the same key and value inside it. However, google::protobuf::Map doesn't + // containing the same key and value inside it. However, Map doesn't // store key and value as MapEntry message, which disables us to use existing // code to serialize message. In order to use existing code to serialize // message, we need to construct a MapEntry from key-value pair. But it @@ -466,14 +557,16 @@ class MapEntryImpl : public Base { BaseClass::set_has_key(); BaseClass::set_has_value(); } - inline const KeyMapEntryAccessorType& key() const { return key_; } - inline const ValueMapEntryAccessorType& value() const { return value_; } + inline const KeyMapEntryAccessorType& key() const override { return key_; } + inline const ValueMapEntryAccessorType& value() const override { + return value_; + } private: const Key& key_; const Value& value_; - friend class ::google::protobuf::Arena; + friend class ::PROTOBUF_NAMESPACE_ID::Arena; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; }; @@ -503,13 +596,11 @@ class MapEntryImpl : public Base { const KeyMapEntryAccessorType& key_; const ValueMapEntryAccessorType value_; - friend class google::protobuf::Arena; + friend class ::PROTOBUF_NAMESPACE_ID::Arena; typedef void DestructorSkippable_; }; - inline Arena* GetArenaNoVirtual() const { - return arena_; - } + inline Arena* GetArenaNoVirtual() const { return arena_; } public: // Needed for constructing tables KeyOnMemory key_; @@ -518,7 +609,7 @@ class MapEntryImpl : public Base { uint32 _has_bits_[1]; private: - friend class ::google::protobuf::Arena; + friend class ::PROTOBUF_NAMESPACE_ID::Arena; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; template > { // type is relatively small and easy to copy then copying Keys into an // array of SortItems can be beneficial. Then all the data the sorting // algorithm needs to touch is in that one array. -template struct SortItem { +template +struct SortItem { SortItem() {} explicit SortItem(PtrToKeyValuePair p) : first(p->first), second(p) {} @@ -578,16 +670,14 @@ template struct SortItem { PtrToKeyValuePair second; }; -template struct CompareByFirstField { - bool operator()(const T& a, const T& b) const { - return a.first < b.first; - } +template +struct CompareByFirstField { + bool operator()(const T& a, const T& b) const { return a.first < b.first; } }; -template struct CompareByDerefFirst { - bool operator()(const T& a, const T& b) const { - return a->first < b->first; - } +template +struct CompareByDerefFirst { + bool operator()(const T& a, const T& b) const { return a->first < b->first; } }; // Helper for table driven serialization @@ -602,20 +692,20 @@ struct FromHelper { template <> struct FromHelper { - static ArenaStringPtr From(const string& x) { + static ArenaStringPtr From(const std::string& x) { ArenaStringPtr res; - TaggedPtr<::std::string> ptr; - ptr.Set(const_cast(&x)); + TaggedPtr ptr; + ptr.Set(const_cast(&x)); res.UnsafeSetTaggedPointer(ptr); return res; } }; template <> struct FromHelper { - static ArenaStringPtr From(const string& x) { + static ArenaStringPtr From(const std::string& x) { ArenaStringPtr res; - TaggedPtr<::std::string> ptr; - ptr.Set(const_cast(&x)); + TaggedPtr ptr; + ptr.Set(const_cast(&x)); res.UnsafeSetTaggedPointer(ptr); return res; } @@ -666,6 +756,8 @@ struct MapEntryHelper + #endif // GOOGLE_PROTOBUF_MAP_ENTRY_LITE_H__ diff --git a/third_party/protobuf/src/google/protobuf/map_field.cc b/third_party/protobuf/src/google/protobuf/map_field.cc index ac29c7e9..2a71b6b5 100644 --- a/third_party/protobuf/src/google/protobuf/map_field.cc +++ b/third_party/protobuf/src/google/protobuf/map_field.cc @@ -33,6 +33,8 @@ #include +#include + namespace google { namespace protobuf { namespace internal { @@ -43,15 +45,13 @@ MapFieldBase::~MapFieldBase() { const RepeatedPtrFieldBase& MapFieldBase::GetRepeatedField() const { SyncRepeatedFieldWithMap(); - return *reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( - repeated_field_); + return *reinterpret_cast(repeated_field_); } RepeatedPtrFieldBase* MapFieldBase::MutableRepeatedField() { SyncRepeatedFieldWithMap(); SetRepeatedDirty(); - return reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( - repeated_field_); + return reinterpret_cast(repeated_field_); } size_t MapFieldBase::SpaceUsedExcludingSelfLong() const { @@ -98,15 +98,35 @@ void* MapFieldBase::MutableRepeatedPtrField() const { return repeated_field_; } void MapFieldBase::SyncRepeatedFieldWithMap() const { // acquire here matches with release below to ensure that we can only see a // value of CLEAN after all previous changes have been synced. - if (state_.load(std::memory_order_acquire) == STATE_MODIFIED_MAP) { - mutex_.Lock(); - // Double check state, because another thread may have seen the same state - // and done the synchronization before the current thread. - if (state_.load(std::memory_order_relaxed) == STATE_MODIFIED_MAP) { - SyncRepeatedFieldWithMapNoLock(); - state_.store(CLEAN, std::memory_order_release); - } - mutex_.Unlock(); + switch (state_.load(std::memory_order_acquire)) { + case STATE_MODIFIED_MAP: + mutex_.Lock(); + // Double check state, because another thread may have seen the same + // state and done the synchronization before the current thread. + if (state_.load(std::memory_order_relaxed) == STATE_MODIFIED_MAP) { + SyncRepeatedFieldWithMapNoLock(); + state_.store(CLEAN, std::memory_order_release); + } + mutex_.Unlock(); + break; + case CLEAN: + mutex_.Lock(); + // Double check state + if (state_.load(std::memory_order_relaxed) == CLEAN) { + if (repeated_field_ == nullptr) { + if (arena_ == nullptr) { + repeated_field_ = new RepeatedPtrField(); + } else { + repeated_field_ = + Arena::CreateMessage >(arena_); + } + } + state_.store(CLEAN, std::memory_order_release); + } + mutex_.Unlock(); + break; + default: + break; } } @@ -133,15 +153,12 @@ void MapFieldBase::SyncMapWithRepeatedField() const { // ------------------DynamicMapField------------------ DynamicMapField::DynamicMapField(const Message* default_entry) - : default_entry_(default_entry) { -} + : default_entry_(default_entry) {} -DynamicMapField::DynamicMapField(const Message* default_entry, - Arena* arena) +DynamicMapField::DynamicMapField(const Message* default_entry, Arena* arena) : TypeDefinedMapFieldBase(arena), map_(arena), - default_entry_(default_entry) { -} + default_entry_(default_entry) {} DynamicMapField::~DynamicMapField() { // DynamicMapField owns map values. Need to delete them before clearing @@ -153,56 +170,72 @@ DynamicMapField::~DynamicMapField() { map_.clear(); } -int DynamicMapField::size() const { - return GetMap().size(); +int DynamicMapField::size() const { return GetMap().size(); } + +void DynamicMapField::Clear() { + Map* map = &const_cast(this)->map_; + for (Map::iterator iter = map->begin(); + iter != map->end(); ++iter) { + iter->second.DeleteData(); + } + map->clear(); + + if (MapFieldBase::repeated_field_ != nullptr) { + MapFieldBase::repeated_field_->Clear(); + } + // Data in map and repeated field are both empty, but we can't set status + // CLEAN which will invalidate previous reference to map. + MapFieldBase::SetMapDirty(); } -bool DynamicMapField::ContainsMapKey( - const MapKey& map_key) const { +bool DynamicMapField::ContainsMapKey(const MapKey& map_key) const { const Map& map = GetMap(); Map::const_iterator iter = map.find(map_key); return iter != map.end(); } -bool DynamicMapField::InsertOrLookupMapValue( - const MapKey& map_key, MapValueRef* val) { +void DynamicMapField::AllocateMapValue(MapValueRef* map_val) { + const FieldDescriptor* val_des = + default_entry_->GetDescriptor()->FindFieldByName("value"); + map_val->SetType(val_des->cpp_type()); + // Allocate memory for the MapValueRef, and initialize to + // default value. + switch (val_des->cpp_type()) { +#define HANDLE_TYPE(CPPTYPE, TYPE) \ + case FieldDescriptor::CPPTYPE_##CPPTYPE: { \ + TYPE* value = new TYPE(); \ + map_val->SetValue(value); \ + break; \ + } + HANDLE_TYPE(INT32, int32); + HANDLE_TYPE(INT64, int64); + HANDLE_TYPE(UINT32, uint32); + HANDLE_TYPE(UINT64, uint64); + HANDLE_TYPE(DOUBLE, double); + HANDLE_TYPE(FLOAT, float); + HANDLE_TYPE(BOOL, bool); + HANDLE_TYPE(STRING, std::string); + HANDLE_TYPE(ENUM, int32); +#undef HANDLE_TYPE + case FieldDescriptor::CPPTYPE_MESSAGE: { + const Message& message = + default_entry_->GetReflection()->GetMessage(*default_entry_, val_des); + Message* value = message.New(); + map_val->SetValue(value); + break; + } + } +} + +bool DynamicMapField::InsertOrLookupMapValue(const MapKey& map_key, + MapValueRef* val) { // Always use mutable map because users may change the map value by // MapValueRef. Map* map = MutableMap(); Map::iterator iter = map->find(map_key); if (iter == map->end()) { - // Insert - MapValueRef& map_val = (*map)[map_key]; - const FieldDescriptor* val_des = - default_entry_->GetDescriptor()->FindFieldByName("value"); - map_val.SetType(val_des->cpp_type()); - // Allocate memory for the inserted MapValueRef, and initialize to - // default value. - switch (val_des->cpp_type()) { -#define HANDLE_TYPE(CPPTYPE, TYPE) \ - case google::protobuf::FieldDescriptor::CPPTYPE_##CPPTYPE: { \ - TYPE * value = new TYPE(); \ - map_val.SetValue(value); \ - break; \ - } - HANDLE_TYPE(INT32, int32); - HANDLE_TYPE(INT64, int64); - HANDLE_TYPE(UINT32, uint32); - HANDLE_TYPE(UINT64, uint64); - HANDLE_TYPE(DOUBLE, double); - HANDLE_TYPE(FLOAT, float); - HANDLE_TYPE(BOOL, bool); - HANDLE_TYPE(STRING, string); - HANDLE_TYPE(ENUM, int32); -#undef HANDLE_TYPE - case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: { - const Message& message = default_entry_->GetReflection()->GetMessage( - *default_entry_, val_des); - Message* value = message.New(); - map_val.SetValue(value); - break; - } - } + MapValueRef& map_val = map_[map_key]; + AllocateMapValue(&map_val); val->CopyFrom(map_val); return true; } @@ -245,6 +278,83 @@ void DynamicMapField::SetMapIteratorValue(MapIterator* map_iter) const { map_iter->value_.CopyFrom(iter->second); } +void DynamicMapField::MergeFrom(const MapFieldBase& other) { + GOOGLE_DCHECK(IsMapValid() && other.IsMapValid()); + Map* map = MutableMap(); + const DynamicMapField& other_field = + reinterpret_cast(other); + for (typename Map::const_iterator other_it = + other_field.map_.begin(); + other_it != other_field.map_.end(); ++other_it) { + Map::iterator iter = map->find(other_it->first); + MapValueRef* map_val; + if (iter == map->end()) { + map_val = &map_[other_it->first]; + AllocateMapValue(map_val); + } else { + map_val = &iter->second; + } + + // Copy map value + const FieldDescriptor* field_descriptor = + default_entry_->GetDescriptor()->FindFieldByName("value"); + switch (field_descriptor->cpp_type()) { + case FieldDescriptor::CPPTYPE_INT32: { + map_val->SetInt32Value(other_it->second.GetInt32Value()); + break; + } + case FieldDescriptor::CPPTYPE_INT64: { + map_val->SetInt64Value(other_it->second.GetInt64Value()); + break; + } + case FieldDescriptor::CPPTYPE_UINT32: { + map_val->SetUInt32Value(other_it->second.GetUInt32Value()); + break; + } + case FieldDescriptor::CPPTYPE_UINT64: { + map_val->SetUInt64Value(other_it->second.GetUInt64Value()); + break; + } + case FieldDescriptor::CPPTYPE_FLOAT: { + map_val->SetFloatValue(other_it->second.GetFloatValue()); + break; + } + case FieldDescriptor::CPPTYPE_DOUBLE: { + map_val->SetDoubleValue(other_it->second.GetDoubleValue()); + break; + } + case FieldDescriptor::CPPTYPE_BOOL: { + map_val->SetBoolValue(other_it->second.GetBoolValue()); + break; + } + case FieldDescriptor::CPPTYPE_STRING: { + map_val->SetStringValue(other_it->second.GetStringValue()); + break; + } + case FieldDescriptor::CPPTYPE_ENUM: { + map_val->SetEnumValue(other_it->second.GetEnumValue()); + break; + } + case FieldDescriptor::CPPTYPE_MESSAGE: { + map_val->MutableMessageValue()->CopyFrom( + other_it->second.GetMessageValue()); + break; + } + } + } +} + +void DynamicMapField::Swap(MapFieldBase* other) { + DynamicMapField* other_field = down_cast(other); + std::swap(this->MapFieldBase::repeated_field_, other_field->repeated_field_); + map_.swap(other_field->map_); + // a relaxed swap of the atomic + auto other_state = other_field->state_.load(std::memory_order_relaxed); + auto this_state = this->MapFieldBase::state_.load(std::memory_order_relaxed); + other_field->state_.store(this_state, std::memory_order_relaxed); + this->MapFieldBase::state_.store(other_state, std::memory_order_relaxed); +} + void DynamicMapField::SyncRepeatedFieldWithMapNoLock() const { const Reflection* reflection = default_entry_->GetReflection(); const FieldDescriptor* key_des = @@ -269,61 +379,61 @@ void DynamicMapField::SyncRepeatedFieldWithMapNoLock() const { MapFieldBase::repeated_field_->AddAllocated(new_entry); const MapKey& map_key = it->first; switch (key_des->cpp_type()) { - case google::protobuf::FieldDescriptor::CPPTYPE_STRING: + case FieldDescriptor::CPPTYPE_STRING: reflection->SetString(new_entry, key_des, map_key.GetStringValue()); break; - case google::protobuf::FieldDescriptor::CPPTYPE_INT64: + case FieldDescriptor::CPPTYPE_INT64: reflection->SetInt64(new_entry, key_des, map_key.GetInt64Value()); break; - case google::protobuf::FieldDescriptor::CPPTYPE_INT32: + case FieldDescriptor::CPPTYPE_INT32: reflection->SetInt32(new_entry, key_des, map_key.GetInt32Value()); break; - case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: + case FieldDescriptor::CPPTYPE_UINT64: reflection->SetUInt64(new_entry, key_des, map_key.GetUInt64Value()); break; - case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: + case FieldDescriptor::CPPTYPE_UINT32: reflection->SetUInt32(new_entry, key_des, map_key.GetUInt32Value()); break; - case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: + case FieldDescriptor::CPPTYPE_BOOL: reflection->SetBool(new_entry, key_des, map_key.GetBoolValue()); break; - case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: - case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: - case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: - case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: + case FieldDescriptor::CPPTYPE_DOUBLE: + case FieldDescriptor::CPPTYPE_FLOAT: + case FieldDescriptor::CPPTYPE_ENUM: + case FieldDescriptor::CPPTYPE_MESSAGE: GOOGLE_LOG(FATAL) << "Can't get here."; break; } const MapValueRef& map_val = it->second; switch (val_des->cpp_type()) { - case google::protobuf::FieldDescriptor::CPPTYPE_STRING: + case FieldDescriptor::CPPTYPE_STRING: reflection->SetString(new_entry, val_des, map_val.GetStringValue()); break; - case google::protobuf::FieldDescriptor::CPPTYPE_INT64: + case FieldDescriptor::CPPTYPE_INT64: reflection->SetInt64(new_entry, val_des, map_val.GetInt64Value()); break; - case google::protobuf::FieldDescriptor::CPPTYPE_INT32: + case FieldDescriptor::CPPTYPE_INT32: reflection->SetInt32(new_entry, val_des, map_val.GetInt32Value()); break; - case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: + case FieldDescriptor::CPPTYPE_UINT64: reflection->SetUInt64(new_entry, val_des, map_val.GetUInt64Value()); break; - case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: + case FieldDescriptor::CPPTYPE_UINT32: reflection->SetUInt32(new_entry, val_des, map_val.GetUInt32Value()); break; - case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: + case FieldDescriptor::CPPTYPE_BOOL: reflection->SetBool(new_entry, val_des, map_val.GetBoolValue()); break; - case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: + case FieldDescriptor::CPPTYPE_DOUBLE: reflection->SetDouble(new_entry, val_des, map_val.GetDoubleValue()); break; - case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: + case FieldDescriptor::CPPTYPE_FLOAT: reflection->SetFloat(new_entry, val_des, map_val.GetFloatValue()); break; - case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: + case FieldDescriptor::CPPTYPE_ENUM: reflection->SetEnumValue(new_entry, val_des, map_val.GetEnumValue()); break; - case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: { + case FieldDescriptor::CPPTYPE_MESSAGE: { const Message& message = map_val.GetMessageValue(); reflection->MutableMessage(new_entry, val_des)->CopyFrom(message); break; @@ -351,28 +461,28 @@ void DynamicMapField::SyncMapWithRepeatedFieldNoLock() const { it != MapFieldBase::repeated_field_->end(); ++it) { MapKey map_key; switch (key_des->cpp_type()) { - case google::protobuf::FieldDescriptor::CPPTYPE_STRING: + case FieldDescriptor::CPPTYPE_STRING: map_key.SetStringValue(reflection->GetString(*it, key_des)); break; - case google::protobuf::FieldDescriptor::CPPTYPE_INT64: + case FieldDescriptor::CPPTYPE_INT64: map_key.SetInt64Value(reflection->GetInt64(*it, key_des)); break; - case google::protobuf::FieldDescriptor::CPPTYPE_INT32: + case FieldDescriptor::CPPTYPE_INT32: map_key.SetInt32Value(reflection->GetInt32(*it, key_des)); break; - case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: + case FieldDescriptor::CPPTYPE_UINT64: map_key.SetUInt64Value(reflection->GetUInt64(*it, key_des)); break; - case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: + case FieldDescriptor::CPPTYPE_UINT32: map_key.SetUInt32Value(reflection->GetUInt32(*it, key_des)); break; - case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: + case FieldDescriptor::CPPTYPE_BOOL: map_key.SetBoolValue(reflection->GetBool(*it, key_des)); break; - case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: - case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: - case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: - case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: + case FieldDescriptor::CPPTYPE_DOUBLE: + case FieldDescriptor::CPPTYPE_FLOAT: + case FieldDescriptor::CPPTYPE_ENUM: + case FieldDescriptor::CPPTYPE_MESSAGE: GOOGLE_LOG(FATAL) << "Can't get here."; break; } @@ -386,13 +496,13 @@ void DynamicMapField::SyncMapWithRepeatedFieldNoLock() const { MapValueRef& map_val = (*map)[map_key]; map_val.SetType(val_des->cpp_type()); switch (val_des->cpp_type()) { -#define HANDLE_TYPE(CPPTYPE, TYPE, METHOD) \ - case google::protobuf::FieldDescriptor::CPPTYPE_##CPPTYPE: { \ - TYPE * value = new TYPE; \ - *value = reflection->Get##METHOD(*it, val_des); \ - map_val.SetValue(value); \ - break; \ - } +#define HANDLE_TYPE(CPPTYPE, TYPE, METHOD) \ + case FieldDescriptor::CPPTYPE_##CPPTYPE: { \ + TYPE* value = new TYPE; \ + *value = reflection->Get##METHOD(*it, val_des); \ + map_val.SetValue(value); \ + break; \ + } HANDLE_TYPE(INT32, int32, Int32); HANDLE_TYPE(INT64, int64, Int64); HANDLE_TYPE(UINT32, uint32, UInt32); @@ -400,10 +510,10 @@ void DynamicMapField::SyncMapWithRepeatedFieldNoLock() const { HANDLE_TYPE(DOUBLE, double, Double); HANDLE_TYPE(FLOAT, float, Float); HANDLE_TYPE(BOOL, bool, Bool); - HANDLE_TYPE(STRING, string, String); + HANDLE_TYPE(STRING, std::string, String); HANDLE_TYPE(ENUM, int32, EnumValue); #undef HANDLE_TYPE - case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: { + case FieldDescriptor::CPPTYPE_MESSAGE: { const Message& message = reflection->GetMessage(*it, val_des); Message* value = message.New(); value->CopyFrom(message); @@ -426,16 +536,16 @@ size_t DynamicMapField::SpaceUsedExcludingSelfNoLock() const { size += sizeof(it->first) * map_size; size += sizeof(it->second) * map_size; // If key is string, add the allocated space. - if (it->first.type() == google::protobuf::FieldDescriptor::CPPTYPE_STRING) { - size += sizeof(string) * map_size; + if (it->first.type() == FieldDescriptor::CPPTYPE_STRING) { + size += sizeof(std::string) * map_size; } // Add the allocated space in MapValueRef. switch (it->second.type()) { -#define HANDLE_TYPE(CPPTYPE, TYPE) \ - case google::protobuf::FieldDescriptor::CPPTYPE_##CPPTYPE: { \ - size += sizeof(TYPE) * map_size; \ - break; \ - } +#define HANDLE_TYPE(CPPTYPE, TYPE) \ + case FieldDescriptor::CPPTYPE_##CPPTYPE: { \ + size += sizeof(TYPE) * map_size; \ + break; \ + } HANDLE_TYPE(INT32, int32); HANDLE_TYPE(INT64, int64); HANDLE_TYPE(UINT32, uint32); @@ -443,10 +553,10 @@ size_t DynamicMapField::SpaceUsedExcludingSelfNoLock() const { HANDLE_TYPE(DOUBLE, double); HANDLE_TYPE(FLOAT, float); HANDLE_TYPE(BOOL, bool); - HANDLE_TYPE(STRING, string); + HANDLE_TYPE(STRING, std::string); HANDLE_TYPE(ENUM, int32); #undef HANDLE_TYPE - case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: { + case FieldDescriptor::CPPTYPE_MESSAGE: { while (it != map_.end()) { const Message& message = it->second.GetMessageValue(); size += message.GetReflection()->SpaceUsedLong(message); diff --git a/third_party/protobuf/src/google/protobuf/map_field.h b/third_party/protobuf/src/google/protobuf/map_field.h index 494401e1..d804dee7 100644 --- a/third_party/protobuf/src/google/protobuf/map_field.h +++ b/third_party/protobuf/src/google/protobuf/map_field.h @@ -33,23 +33,30 @@ #include -#include -#include -#include #include #include +#include #include #include #include #include +#include +#include #include #include +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + namespace google { namespace protobuf { class DynamicMessage; class MapKey; +class MapIterator; namespace internal { class ContendedMapCleanTest; @@ -59,16 +66,12 @@ class MapFieldAccessor; // This class provides access to map field using reflection, which is the same // as those provided for RepeatedPtrField. It is used for internal // reflection implentation only. Users should never use this directly. -class LIBPROTOBUF_EXPORT MapFieldBase { +class PROTOBUF_EXPORT MapFieldBase { public: MapFieldBase() - : arena_(NULL), - repeated_field_(NULL), - state_(STATE_MODIFIED_MAP) {} + : arena_(NULL), repeated_field_(NULL), state_(STATE_MODIFIED_MAP) {} explicit MapFieldBase(Arena* arena) - : arena_(arena), - repeated_field_(NULL), - state_(STATE_MODIFIED_MAP) { + : arena_(arena), repeated_field_(NULL), state_(STATE_MODIFIED_MAP) { // Mutex's destructor needs to be called explicitly to release resources // acquired in its constructor. arena->OwnDestructor(&mutex_); @@ -76,7 +79,7 @@ class LIBPROTOBUF_EXPORT MapFieldBase { virtual ~MapFieldBase(); // Returns reference to internal repeated field. Data written using - // google::protobuf::Map's api prior to calling this function is guarantted to be + // Map's api prior to calling this function is guarantted to be // included in repeated field. const RepeatedPtrFieldBase& GetRepeatedField() const; @@ -85,8 +88,8 @@ class LIBPROTOBUF_EXPORT MapFieldBase { // Pure virtual map APIs for Map Reflection. virtual bool ContainsMapKey(const MapKey& map_key) const = 0; - virtual bool InsertOrLookupMapValue( - const MapKey& map_key, MapValueRef* val) = 0; + virtual bool InsertOrLookupMapValue(const MapKey& map_key, + MapValueRef* val) = 0; // Returns whether changes to the map are reflected in the repeated field. bool IsRepeatedFieldValid() const; // Insures operations after won't get executed before calling this. @@ -96,8 +99,11 @@ class LIBPROTOBUF_EXPORT MapFieldBase { const MapIterator& b) const = 0; virtual void MapBegin(MapIterator* map_iter) const = 0; virtual void MapEnd(MapIterator* map_iter) const = 0; + virtual void MergeFrom(const MapFieldBase& other) = 0; + virtual void Swap(MapFieldBase* other) = 0; // Sync Map with repeated field and returns the size of map. virtual int size() const = 0; + virtual void Clear() = 0; // Returns the number of bytes used by the repeated field, excluding // sizeof(*this) @@ -135,27 +141,28 @@ class LIBPROTOBUF_EXPORT MapFieldBase { // synchronized to repeated field STATE_MODIFIED_REPEATED = 1, // repeated field has newly added data that // has not been synchronized to map - CLEAN = 2, // data in map and repeated field are same + CLEAN = 2, // data in map and repeated field are same }; Arena* arena_; mutable RepeatedPtrField* repeated_field_; - mutable Mutex mutex_; // The thread to synchronize map and repeated field - // needs to get lock first; + mutable internal::WrappedMutex + mutex_; // The thread to synchronize map and repeated field + // needs to get lock first; mutable std::atomic state_; private: friend class ContendedMapCleanTest; friend class GeneratedMessageReflection; friend class MapFieldAccessor; - friend class ::google::protobuf::DynamicMessage; + friend class DynamicMessage; // Virtual helper methods for MapIterator. MapIterator doesn't have the // type helper for key and value. Call these help methods to deal with // different types. Real helper methods are implemented in // TypeDefinedMapFieldBase. - friend class ::google::protobuf::MapIterator; + friend class ::PROTOBUF_NAMESPACE_ID::MapIterator; // Allocate map<...>::iterator for MapIterator. virtual void InitializeIterator(MapIterator* map_iter) const = 0; @@ -176,15 +183,15 @@ class LIBPROTOBUF_EXPORT MapFieldBase { // This class provides common Map Reflection implementations for generated // message and dynamic message. -template +template class TypeDefinedMapFieldBase : public MapFieldBase { public: TypeDefinedMapFieldBase() {} explicit TypeDefinedMapFieldBase(Arena* arena) : MapFieldBase(arena) {} - ~TypeDefinedMapFieldBase() {} - void MapBegin(MapIterator* map_iter) const; - void MapEnd(MapIterator* map_iter) const; - bool EqualIterator(const MapIterator& a, const MapIterator& b) const; + ~TypeDefinedMapFieldBase() override {} + void MapBegin(MapIterator* map_iter) const override; + void MapEnd(MapIterator* map_iter) const override; + bool EqualIterator(const MapIterator& a, const MapIterator& b) const override; virtual const Map& GetMap() const = 0; virtual Map* MutableMap() = 0; @@ -194,11 +201,11 @@ class TypeDefinedMapFieldBase : public MapFieldBase { const MapIterator* map_iter) const; private: - void InitializeIterator(MapIterator* map_iter) const; - void DeleteIterator(MapIterator* map_iter) const; + void InitializeIterator(MapIterator* map_iter) const override; + void DeleteIterator(MapIterator* map_iter) const override; void CopyIterator(MapIterator* this_iteratorm, - const MapIterator& that_iterator) const; - void IncreaseIterator(MapIterator* map_iter) const; + const MapIterator& that_iterator) const override; + void IncreaseIterator(MapIterator* map_iter) const override; virtual void SetMapIteratorValue(MapIterator* map_iter) const = 0; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TypeDefinedMapFieldBase); @@ -228,7 +235,7 @@ class MapField : public TypeDefinedMapFieldBase { MapFieldLiteType; // Enum needs to be handled differently from other types because it has - // different exposed type in google::protobuf::Map's api and repeated field's api. For + // different exposed type in Map's api and repeated field's api. For // details see the comment in the implementation of // SyncMapWithRepeatedFieldNoLock. static const bool kIsValueEnum = ValueTypeHandler::kIsEnum; @@ -243,27 +250,26 @@ class MapField : public TypeDefinedMapFieldBase { : TypeDefinedMapFieldBase(arena), impl_(arena) {} // Implement MapFieldBase - bool ContainsMapKey(const MapKey& map_key) const; - bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val); - bool DeleteMapValue(const MapKey& map_key); + bool ContainsMapKey(const MapKey& map_key) const override; + bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val) override; + bool DeleteMapValue(const MapKey& map_key) override; - const Map& GetMap() const { + const Map& GetMap() const override { MapFieldBase::SyncMapWithRepeatedField(); return impl_.GetMap(); } - Map* MutableMap() { + Map* MutableMap() override { MapFieldBase::SyncMapWithRepeatedField(); Map* result = impl_.MutableMap(); MapFieldBase::SetMapDirty(); return result; } - // Convenient methods for generated message implementation. - int size() const; - void Clear(); - void MergeFrom(const MapField& other); - void Swap(MapField* other); + int size() const override; + void Clear() override; + void MergeFrom(const MapFieldBase& other) override; + void Swap(MapFieldBase* other) override; // Used in the implementation of parsing. Caller should take the ownership iff // arena_ is NULL. @@ -279,6 +285,17 @@ class MapField : public TypeDefinedMapFieldBase { return impl_.NewEntryWrapper(key, t); } + const char* _InternalParse(const char* ptr, ParseContext* ctx) { + return impl_._InternalParse(ptr, ctx); + } + template + const char* ParseWithEnumValidation(const char* ptr, ParseContext* ctx, + bool (*is_valid)(int), uint32 field_num, + Metadata* metadata) { + return impl_.ParseWithEnumValidation(ptr, ctx, is_valid, field_num, + metadata); + } + private: MapFieldLiteType impl_; @@ -286,13 +303,13 @@ class MapField : public TypeDefinedMapFieldBase { typedef void DestructorSkippable_; // Implements MapFieldBase - void SyncRepeatedFieldWithMapNoLock() const; - void SyncMapWithRepeatedFieldNoLock() const; - size_t SpaceUsedExcludingSelfNoLock() const; + void SyncRepeatedFieldWithMapNoLock() const override; + void SyncMapWithRepeatedFieldNoLock() const override; + size_t SpaceUsedExcludingSelfNoLock() const override; - void SetMapIteratorValue(MapIterator* map_iter) const; + void SetMapIteratorValue(MapIterator* map_iter) const override; - friend class ::google::protobuf::Arena; + friend class ::PROTOBUF_NAMESPACE_ID::Arena; friend class MapFieldStateTest; // For testing, it needs raw access to impl_ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapField); }; @@ -301,62 +318,63 @@ template struct MapEntryToMapField > { + kValueFieldType, default_enum_value>> { typedef MapField MapFieldType; }; -class LIBPROTOBUF_EXPORT DynamicMapField: public TypeDefinedMapFieldBase { +class PROTOBUF_EXPORT DynamicMapField + : public TypeDefinedMapFieldBase { public: explicit DynamicMapField(const Message* default_entry); DynamicMapField(const Message* default_entry, Arena* arena); - ~DynamicMapField(); + ~DynamicMapField() override; // Implement MapFieldBase - bool ContainsMapKey(const MapKey& map_key) const; - bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val); - bool DeleteMapValue(const MapKey& map_key); + bool ContainsMapKey(const MapKey& map_key) const override; + bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val) override; + bool DeleteMapValue(const MapKey& map_key) override; + void MergeFrom(const MapFieldBase& other) override; + void Swap(MapFieldBase* other) override; - const Map& GetMap() const; - Map* MutableMap(); + const Map& GetMap() const override; + Map* MutableMap() override; - int size() const; + int size() const override; + void Clear() override; private: Map map_; const Message* default_entry_; + void AllocateMapValue(MapValueRef* map_val); + // Implements MapFieldBase - void SyncRepeatedFieldWithMapNoLock() const; - void SyncMapWithRepeatedFieldNoLock() const; - size_t SpaceUsedExcludingSelfNoLock() const; - void SetMapIteratorValue(MapIterator* map_iter) const; + void SyncRepeatedFieldWithMapNoLock() const override; + void SyncMapWithRepeatedFieldNoLock() const override; + size_t SpaceUsedExcludingSelfNoLock() const override; + void SetMapIteratorValue(MapIterator* map_iter) const override; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMapField); }; } // namespace internal -#define TYPE_CHECK(EXPECTEDTYPE, METHOD) \ - if (type() != EXPECTEDTYPE) { \ - GOOGLE_LOG(FATAL) \ - << "Protocol Buffer map usage error:\n" \ - << METHOD << " type does not match\n" \ - << " Expected : " \ - << FieldDescriptor::CppTypeName(EXPECTEDTYPE) << "\n" \ - << " Actual : " \ - << FieldDescriptor::CppTypeName(type()); \ +#define TYPE_CHECK(EXPECTEDTYPE, METHOD) \ + if (type() != EXPECTEDTYPE) { \ + GOOGLE_LOG(FATAL) << "Protocol Buffer map usage error:\n" \ + << METHOD << " type does not match\n" \ + << " Expected : " \ + << FieldDescriptor::CppTypeName(EXPECTEDTYPE) << "\n" \ + << " Actual : " << FieldDescriptor::CppTypeName(type()); \ } // MapKey is an union type for representing any possible // map key. -class LIBPROTOBUF_EXPORT MapKey { +class PROTOBUF_EXPORT MapKey { public: - MapKey() : type_(0) { - } - MapKey(const MapKey& other) : type_(0) { - CopyFrom(other); - } + MapKey() : type_(0) {} + MapKey(const MapKey& other) : type_(0) { CopyFrom(other); } MapKey& operator=(const MapKey& other) { CopyFrom(other); return *this; @@ -370,10 +388,9 @@ class LIBPROTOBUF_EXPORT MapKey { FieldDescriptor::CppType type() const { if (type_ == 0) { - GOOGLE_LOG(FATAL) - << "Protocol Buffer map usage error:\n" - << "MapKey::type MapKey is not initialized. " - << "Call set methods to initialize MapKey."; + GOOGLE_LOG(FATAL) << "Protocol Buffer map usage error:\n" + << "MapKey::type MapKey is not initialized. " + << "Call set methods to initialize MapKey."; } return (FieldDescriptor::CppType)type_; } @@ -398,39 +415,33 @@ class LIBPROTOBUF_EXPORT MapKey { SetType(FieldDescriptor::CPPTYPE_BOOL); val_.bool_value_ = value; } - void SetStringValue(const string& val) { + void SetStringValue(const std::string& val) { SetType(FieldDescriptor::CPPTYPE_STRING); *val_.string_value_ = val; } int64 GetInt64Value() const { - TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64, - "MapKey::GetInt64Value"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64, "MapKey::GetInt64Value"); return val_.int64_value_; } uint64 GetUInt64Value() const { - TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64, - "MapKey::GetUInt64Value"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64, "MapKey::GetUInt64Value"); return val_.uint64_value_; } int32 GetInt32Value() const { - TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32, - "MapKey::GetInt32Value"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32, "MapKey::GetInt32Value"); return val_.int32_value_; } uint32 GetUInt32Value() const { - TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32, - "MapKey::GetUInt32Value"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32, "MapKey::GetUInt32Value"); return val_.uint32_value_; } bool GetBoolValue() const { - TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL, - "MapKey::GetBoolValue"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL, "MapKey::GetBoolValue"); return val_.bool_value_; } - const string& GetStringValue() const { - TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING, - "MapKey::GetStringValue"); + const std::string& GetStringValue() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING, "MapKey::GetStringValue"); return *val_.string_value_; } @@ -525,12 +536,12 @@ class LIBPROTOBUF_EXPORT MapKey { private: template friend class internal::TypeDefinedMapFieldBase; - friend class MapIterator; + friend class ::PROTOBUF_NAMESPACE_ID::MapIterator; friend class internal::DynamicMapField; union KeyValue { KeyValue() {} - string* string_value_; + std::string* string_value_; int64 int64_value_; int32 int32_value_; uint64 uint64_value_; @@ -545,7 +556,7 @@ class LIBPROTOBUF_EXPORT MapKey { } type_ = type; if (type_ == FieldDescriptor::CPPTYPE_STRING) { - val_.string_value_ = new string; + val_.string_value_ = new std::string; } } @@ -554,100 +565,82 @@ class LIBPROTOBUF_EXPORT MapKey { }; // MapValueRef points to a map value. -class LIBPROTOBUF_EXPORT MapValueRef { +class PROTOBUF_EXPORT MapValueRef { public: MapValueRef() : data_(NULL), type_(0) {} void SetInt64Value(int64 value) { - TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64, - "MapValueRef::SetInt64Value"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64, "MapValueRef::SetInt64Value"); *reinterpret_cast(data_) = value; } void SetUInt64Value(uint64 value) { - TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64, - "MapValueRef::SetUInt64Value"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64, "MapValueRef::SetUInt64Value"); *reinterpret_cast(data_) = value; } void SetInt32Value(int32 value) { - TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32, - "MapValueRef::SetInt32Value"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32, "MapValueRef::SetInt32Value"); *reinterpret_cast(data_) = value; } void SetUInt32Value(uint32 value) { - TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32, - "MapValueRef::SetUInt32Value"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32, "MapValueRef::SetUInt32Value"); *reinterpret_cast(data_) = value; } void SetBoolValue(bool value) { - TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL, - "MapValueRef::SetBoolValue"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL, "MapValueRef::SetBoolValue"); *reinterpret_cast(data_) = value; } // TODO(jieluo) - Checks that enum is member. void SetEnumValue(int value) { - TYPE_CHECK(FieldDescriptor::CPPTYPE_ENUM, - "MapValueRef::SetEnumValue"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_ENUM, "MapValueRef::SetEnumValue"); *reinterpret_cast(data_) = value; } - void SetStringValue(const string& value) { - TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING, - "MapValueRef::SetStringValue"); - *reinterpret_cast(data_) = value; + void SetStringValue(const std::string& value) { + TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING, "MapValueRef::SetStringValue"); + *reinterpret_cast(data_) = value; } void SetFloatValue(float value) { - TYPE_CHECK(FieldDescriptor::CPPTYPE_FLOAT, - "MapValueRef::SetFloatValue"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_FLOAT, "MapValueRef::SetFloatValue"); *reinterpret_cast(data_) = value; } void SetDoubleValue(double value) { - TYPE_CHECK(FieldDescriptor::CPPTYPE_DOUBLE, - "MapValueRef::SetDoubleValue"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_DOUBLE, "MapValueRef::SetDoubleValue"); *reinterpret_cast(data_) = value; } int64 GetInt64Value() const { - TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64, - "MapValueRef::GetInt64Value"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64, "MapValueRef::GetInt64Value"); return *reinterpret_cast(data_); } uint64 GetUInt64Value() const { - TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64, - "MapValueRef::GetUInt64Value"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64, "MapValueRef::GetUInt64Value"); return *reinterpret_cast(data_); } int32 GetInt32Value() const { - TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32, - "MapValueRef::GetInt32Value"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32, "MapValueRef::GetInt32Value"); return *reinterpret_cast(data_); } uint32 GetUInt32Value() const { - TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32, - "MapValueRef::GetUInt32Value"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32, "MapValueRef::GetUInt32Value"); return *reinterpret_cast(data_); } bool GetBoolValue() const { - TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL, - "MapValueRef::GetBoolValue"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL, "MapValueRef::GetBoolValue"); return *reinterpret_cast(data_); } int GetEnumValue() const { - TYPE_CHECK(FieldDescriptor::CPPTYPE_ENUM, - "MapValueRef::GetEnumValue"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_ENUM, "MapValueRef::GetEnumValue"); return *reinterpret_cast(data_); } - const string& GetStringValue() const { - TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING, - "MapValueRef::GetStringValue"); - return *reinterpret_cast(data_); + const std::string& GetStringValue() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING, "MapValueRef::GetStringValue"); + return *reinterpret_cast(data_); } float GetFloatValue() const { - TYPE_CHECK(FieldDescriptor::CPPTYPE_FLOAT, - "MapValueRef::GetFloatValue"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_FLOAT, "MapValueRef::GetFloatValue"); return *reinterpret_cast(data_); } double GetDoubleValue() const { - TYPE_CHECK(FieldDescriptor::CPPTYPE_DOUBLE, - "MapValueRef::GetDoubleValue"); + TYPE_CHECK(FieldDescriptor::CPPTYPE_DOUBLE, "MapValueRef::GetDoubleValue"); return *reinterpret_cast(data_); } @@ -671,25 +664,20 @@ class LIBPROTOBUF_EXPORT MapValueRef { friend class internal::MapField; template friend class internal::TypeDefinedMapFieldBase; - friend class MapIterator; + friend class ::PROTOBUF_NAMESPACE_ID::MapIterator; friend class internal::GeneratedMessageReflection; friend class internal::DynamicMapField; - void SetType(FieldDescriptor::CppType type) { - type_ = type; - } + void SetType(FieldDescriptor::CppType type) { type_ = type; } FieldDescriptor::CppType type() const { if (type_ == 0 || data_ == NULL) { - GOOGLE_LOG(FATAL) - << "Protocol Buffer map usage error:\n" - << "MapValueRef::type MapValueRef is not initialized."; + GOOGLE_LOG(FATAL) << "Protocol Buffer map usage error:\n" + << "MapValueRef::type MapValueRef is not initialized."; } return (FieldDescriptor::CppType)type_; } - void SetValue(const void* val) { - data_ = const_cast(val); - } + void SetValue(const void* val) { data_ = const_cast(val); } void CopyFrom(const MapValueRef& other) { type_ = other.type_; data_ = other.data_; @@ -697,11 +685,11 @@ class LIBPROTOBUF_EXPORT MapValueRef { // Only used in DynamicMapField void DeleteData() { switch (type_) { -#define HANDLE_TYPE(CPPTYPE, TYPE) \ - case google::protobuf::FieldDescriptor::CPPTYPE_##CPPTYPE: { \ - delete reinterpret_cast(data_); \ - break; \ - } +#define HANDLE_TYPE(CPPTYPE, TYPE) \ + case FieldDescriptor::CPPTYPE_##CPPTYPE: { \ + delete reinterpret_cast(data_); \ + break; \ + } HANDLE_TYPE(INT32, int32); HANDLE_TYPE(INT64, int64); HANDLE_TYPE(UINT32, uint32); @@ -709,7 +697,7 @@ class LIBPROTOBUF_EXPORT MapValueRef { HANDLE_TYPE(DOUBLE, double); HANDLE_TYPE(FLOAT, float); HANDLE_TYPE(BOOL, bool); - HANDLE_TYPE(STRING, string); + HANDLE_TYPE(STRING, std::string); HANDLE_TYPE(ENUM, int32); HANDLE_TYPE(MESSAGE, Message); #undef HANDLE_TYPE @@ -720,16 +708,15 @@ class LIBPROTOBUF_EXPORT MapValueRef { void* data_; // type_ is 0 or a valid FieldDescriptor::CppType. int type_; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapValueRef); }; #undef TYPE_CHECK -class LIBPROTOBUF_EXPORT MapIterator { +class PROTOBUF_EXPORT MapIterator { public: MapIterator(Message* message, const FieldDescriptor* field) { const Reflection* reflection = message->GetReflection(); - map_ = reflection->MapData(message, field); + map_ = reflection->MutableMapData(message, field); key_.SetType(field->message_type()->FindFieldByName("key")->cpp_type()); value_.SetType(field->message_type()->FindFieldByName("value")->cpp_type()); map_->InitializeIterator(this); @@ -739,9 +726,7 @@ class LIBPROTOBUF_EXPORT MapIterator { map_->InitializeIterator(this); map_->CopyIterator(this, other); } - ~MapIterator() { - map_->DeleteIterator(this); - } + ~MapIterator() { map_->DeleteIterator(this); } MapIterator& operator=(const MapIterator& other) { map_ = other.map_; map_->CopyIterator(this, other); @@ -764,12 +749,8 @@ class LIBPROTOBUF_EXPORT MapIterator { map_->IncreaseIterator(this); return *this; } - const MapKey& GetKey() { - return key_; - } - const MapValueRef& GetValueRef() { - return value_; - } + const MapKey& GetKey() { return key_; } + const MapValueRef& GetValueRef() { return value_; } MapValueRef* MutableValueRef() { map_->SetMapDirty(); return &value_; @@ -801,39 +782,39 @@ class LIBPROTOBUF_EXPORT MapIterator { } // namespace google GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_START -template<> -struct hash { - size_t - operator()(const google::protobuf::MapKey& map_key) const { +template <> +struct hash<::PROTOBUF_NAMESPACE_ID::MapKey> { + size_t operator()(const ::PROTOBUF_NAMESPACE_ID::MapKey& map_key) const { switch (map_key.type()) { - case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: - case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: - case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: - case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_DOUBLE: + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_FLOAT: + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_ENUM: + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_MESSAGE: GOOGLE_LOG(FATAL) << "Unsupported"; break; - case google::protobuf::FieldDescriptor::CPPTYPE_STRING: - return hash()(map_key.GetStringValue()); - case google::protobuf::FieldDescriptor::CPPTYPE_INT64: - return hash<::google::protobuf::int64>()(map_key.GetInt64Value()); - case google::protobuf::FieldDescriptor::CPPTYPE_INT32: - return hash<::google::protobuf::int32>()(map_key.GetInt32Value()); - case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: - return hash<::google::protobuf::uint64>()(map_key.GetUInt64Value()); - case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: - return hash<::google::protobuf::uint32>()(map_key.GetUInt32Value()); - case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_STRING: + return hash()(map_key.GetStringValue()); + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_INT64: + return hash()(map_key.GetInt64Value()); + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_INT32: + return hash()(map_key.GetInt32Value()); + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_UINT64: + return hash()(map_key.GetUInt64Value()); + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_UINT32: + return hash()(map_key.GetUInt32Value()); + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_BOOL: return hash()(map_key.GetBoolValue()); } GOOGLE_LOG(FATAL) << "Can't get here."; return 0; } - bool - operator()(const google::protobuf::MapKey& map_key1, - const google::protobuf::MapKey& map_key2) const { + bool operator()(const ::PROTOBUF_NAMESPACE_ID::MapKey& map_key1, + const ::PROTOBUF_NAMESPACE_ID::MapKey& map_key2) const { return map_key1 < map_key2; } }; GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_END +#include + #endif // GOOGLE_PROTOBUF_MAP_FIELD_H__ diff --git a/third_party/protobuf/src/google/protobuf/map_field_inl.h b/third_party/protobuf/src/google/protobuf/map_field_inl.h index d0517792..7baaa5ff 100644 --- a/third_party/protobuf/src/google/protobuf/map_field_inl.h +++ b/third_party/protobuf/src/google/protobuf/map_field_inl.h @@ -38,62 +38,66 @@ #include #include +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + namespace google { namespace protobuf { namespace internal { // UnwrapMapKey template -template +template T UnwrapMapKey(const MapKey& map_key); -template<> +template <> inline int32 UnwrapMapKey(const MapKey& map_key) { return map_key.GetInt32Value(); } -template<> +template <> inline uint32 UnwrapMapKey(const MapKey& map_key) { return map_key.GetUInt32Value(); } -template<> +template <> inline int64 UnwrapMapKey(const MapKey& map_key) { return map_key.GetInt64Value(); } -template<> +template <> inline uint64 UnwrapMapKey(const MapKey& map_key) { return map_key.GetUInt64Value(); } -template<> +template <> inline bool UnwrapMapKey(const MapKey& map_key) { return map_key.GetBoolValue(); } -template<> -inline string UnwrapMapKey(const MapKey& map_key) { +template <> +inline std::string UnwrapMapKey(const MapKey& map_key) { return map_key.GetStringValue(); } // SetMapKey template -template +template inline void SetMapKey(MapKey* map_key, const T& value); -template<> +template <> inline void SetMapKey(MapKey* map_key, const int32& value) { map_key->SetInt32Value(value); } -template<> +template <> inline void SetMapKey(MapKey* map_key, const uint32& value) { map_key->SetUInt32Value(value); } -template<> +template <> inline void SetMapKey(MapKey* map_key, const int64& value) { map_key->SetInt64Value(value); } -template<> +template <> inline void SetMapKey(MapKey* map_key, const uint64& value) { map_key->SetUInt64Value(value); } -template<> +template <> inline void SetMapKey(MapKey* map_key, const bool& value) { map_key->SetBoolValue(value); } -template<> -inline void SetMapKey(MapKey* map_key, const string& value) { +template <> +inline void SetMapKey(MapKey* map_key, const std::string& value) { map_key->SetStringValue(value); } @@ -102,7 +106,7 @@ template typename Map::const_iterator& TypeDefinedMapFieldBase::InternalGetIterator( const MapIterator* map_iter) const { - return *reinterpret_cast::const_iterator *>( + return *reinterpret_cast::const_iterator*>( map_iter->iter_); } @@ -118,15 +122,14 @@ void TypeDefinedMapFieldBase::MapEnd(MapIterator* map_iter) const { } template -bool TypeDefinedMapFieldBase::EqualIterator(const MapIterator& a, - const MapIterator& b) - const { +bool TypeDefinedMapFieldBase::EqualIterator( + const MapIterator& a, const MapIterator& b) const { return InternalGetIterator(&a) == InternalGetIterator(&b); } template -void TypeDefinedMapFieldBase::IncreaseIterator(MapIterator* map_iter) - const { +void TypeDefinedMapFieldBase::IncreaseIterator( + MapIterator* map_iter) const { ++InternalGetIterator(map_iter); SetMapIteratorValue(map_iter); } @@ -139,16 +142,15 @@ void TypeDefinedMapFieldBase::InitializeIterator( } template -void TypeDefinedMapFieldBase::DeleteIterator(MapIterator* map_iter) - const { - delete reinterpret_cast::const_iterator *>( +void TypeDefinedMapFieldBase::DeleteIterator( + MapIterator* map_iter) const { + delete reinterpret_cast::const_iterator*>( map_iter->iter_); } template void TypeDefinedMapFieldBase::CopyIterator( - MapIterator* this_iter, - const MapIterator& that_iter) const { + MapIterator* this_iter, const MapIterator& that_iter) const { InternalGetIterator(this_iter) = InternalGetIterator(&that_iter); this_iter->key_.SetType(that_iter.key_.type()); // MapValueRef::type() fails when containing data is null. However, if @@ -174,8 +176,17 @@ template void MapField::Clear() { - MapFieldBase::SyncMapWithRepeatedField(); + if (this->MapFieldBase::repeated_field_ != nullptr) { + RepeatedPtrField* repeated_field = + reinterpret_cast*>( + this->MapFieldBase::repeated_field_); + repeated_field->Clear(); + } + impl_.MutableMap()->clear(); + // Data in map and repeated field are both empty, but we can't set status + // CLEAN. Because clear is a generated API, we cannot invalidate previous + // reference to map. MapFieldBase::SetMapDirty(); } @@ -238,10 +249,11 @@ template void MapField::MergeFrom(const MapField& other) { + default_enum_value>::MergeFrom(const MapFieldBase& other) { MapFieldBase::SyncMapWithRepeatedField(); - other.SyncMapWithRepeatedField(); - impl_.MergeFrom(other.impl_); + const MapField& other_field = static_cast(other); + other_field.SyncMapWithRepeatedField(); + impl_.MergeFrom(other_field.impl_); MapFieldBase::SetMapDirty(); } @@ -249,13 +261,14 @@ template void MapField::Swap(MapField* other) { - std::swap(this->MapFieldBase::repeated_field_, other->repeated_field_); - impl_.Swap(&other->impl_); + default_enum_value>::Swap(MapFieldBase* other) { + MapField* other_field = down_cast(other); + std::swap(this->MapFieldBase::repeated_field_, other_field->repeated_field_); + impl_.Swap(&other_field->impl_); // a relaxed swap of the atomic - auto other_state = other->state_.load(std::memory_order_relaxed); + auto other_state = other_field->state_.load(std::memory_order_relaxed); auto this_state = this->MapFieldBase::state_.load(std::memory_order_relaxed); - other->state_.store(this_state, std::memory_order_relaxed); + other_field->state_.store(this_state, std::memory_order_relaxed); this->MapFieldBase::state_.store(other_state, std::memory_order_relaxed); } @@ -286,8 +299,8 @@ void MapField::const_iterator it = map.begin(); - it != map.end(); ++it) { + for (typename Map::const_iterator it = map.begin(); it != map.end(); + ++it) { EntryType* new_entry = down_cast(default_entry->New(this->MapFieldBase::arena_)); repeated_field->AddAllocated(new_entry); @@ -308,7 +321,8 @@ void MapFieldMapFieldBase::repeated_field_ != NULL); map->clear(); for (typename RepeatedPtrField::iterator it = - repeated_field->begin(); it != repeated_field->end(); ++it) { + repeated_field->begin(); + it != repeated_field->end(); ++it) { // Cast is needed because Map's api and internal storage is different when // value is enum. For enum, we cannot cast an int to enum. Thus, we have to // copy value. For other types, they have same exposed api type and internal @@ -338,6 +352,6 @@ size_t MapField +#include +#include #include #include +#include #include +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + namespace google { namespace protobuf { namespace internal { @@ -99,15 +109,53 @@ class MapFieldLite { return EntryType::Wrap(key, t, arena_); } + const char* _InternalParse(const char* ptr, ParseContext* ctx) { + typename Derived::template Parser> parser(this); + return parser._InternalParse(ptr, ctx); + } + + template + const char* ParseWithEnumValidation(const char* ptr, ParseContext* ctx, + bool (*is_valid)(int), uint32 field_num, + Metadata* metadata) { + typename Derived::template Parser> parser(this); + return parser.ParseWithEnumValidation(ptr, ctx, is_valid, field_num, + metadata); + } + private: typedef void DestructorSkippable_; Arena* arena_; Map map_; - friend class ::google::protobuf::Arena; + friend class ::PROTOBUF_NAMESPACE_ID::Arena; }; +template +struct EnumParseWrapper { + const char* _InternalParse(const char* ptr, ParseContext* ctx) { + return map_field->ParseWithEnumValidation(ptr, ctx, is_valid, field_num, + metadata); + } + T* map_field; + bool (*is_valid)(int); + uint32 field_num; + Metadata* metadata; +}; + +// Helper function because the typenames of maps are horrendous to print. This +// leverages compiler type deduction, to keep all type data out of the +// generated code +template +EnumParseWrapper InitEnumParseWrapper(T* map_field, + bool (*is_valid)(int), + uint32 field_num, + Metadata* metadata) { + return EnumParseWrapper{map_field, is_valid, field_num, + metadata}; +} + // True if IsInitialized() is true for value field in all elements of t. T is // expected to be message. It's useful to have this helper here to keep the // protobuf compiler from ever having to emit loops in IsInitialized() methods. @@ -128,7 +176,7 @@ template struct MapEntryToMapField > { + kValueFieldType, default_enum_value>> { typedef MapFieldLite, Key, Value, kKeyFieldType, kValueFieldType, @@ -138,6 +186,8 @@ struct MapEntryToMapField + #endif // GOOGLE_PROTOBUF_MAP_FIELD_LITE_H__ diff --git a/third_party/protobuf/src/google/protobuf/map_field_test.cc b/third_party/protobuf/src/google/protobuf/map_field_test.cc index f58d59e5..dd22727d 100644 --- a/third_party/protobuf/src/google/protobuf/map_field_test.cc +++ b/third_party/protobuf/src/google/protobuf/map_field_test.cc @@ -30,22 +30,22 @@ #include #include +#include #include #include +#include +#include +#include +#include #include #include -#include -#include -#include -#include #include #include #include -#include #include -namespace google { +namespace google { namespace protobuf { namespace internal { @@ -65,9 +65,7 @@ class MapFieldBaseStub : public MapFieldBase { MapFieldBase::SyncMapWithRepeatedField(); } // Get underlined repeated field without synchronizing map. - RepeatedPtrField* InternalRepeatedField() { - return repeated_field_; - } + RepeatedPtrField* InternalRepeatedField() { return repeated_field_; } bool IsMapClean() { return state_.load(std::memory_order_relaxed) != STATE_MODIFIED_MAP; } @@ -80,26 +78,27 @@ class MapFieldBaseStub : public MapFieldBase { void SetRepeatedDirty() { state_.store(STATE_MODIFIED_REPEATED, std::memory_order_relaxed); } - bool ContainsMapKey(const MapKey& map_key) const { + bool ContainsMapKey(const MapKey& map_key) const override { return false; } + bool InsertOrLookupMapValue(const MapKey& map_key, + MapValueRef* val) override { return false; } - bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val) { + bool DeleteMapValue(const MapKey& map_key) override { return false; } + bool EqualIterator(const MapIterator& a, + const MapIterator& b) const override { return false; } - bool DeleteMapValue(const MapKey& map_key) { - return false; - } - bool EqualIterator(const MapIterator& a, const MapIterator& b) const { - return false; - } - int size() const { return 0; } - void MapBegin(MapIterator* map_iter) const {} - void MapEnd(MapIterator* map_iter) const {} - void InitializeIterator(MapIterator* map_iter) const {} - void DeleteIterator(MapIterator* map_iter) const {} + int size() const override { return 0; } + void Clear() override {} + void MapBegin(MapIterator* map_iter) const override {} + void MapEnd(MapIterator* map_iter) const override {} + void MergeFrom(const MapFieldBase& other) override {} + void Swap(MapFieldBase* other) override {} + void InitializeIterator(MapIterator* map_iter) const override {} + void DeleteIterator(MapIterator* map_iter) const override {} void CopyIterator(MapIterator* this_iterator, - const MapIterator& other_iterator) const {} - void IncreaseIterator(MapIterator* map_iter) const {} + const MapIterator& other_iterator) const override {} + void IncreaseIterator(MapIterator* map_iter) const override {} void SetDefaultMessageEntry(const Message* message) const {} const Message* GetDefaultMessageEntry() const { return NULL; } }; @@ -207,8 +206,7 @@ namespace { enum State { CLEAN, MAP_DIRTY, REPEATED_DIRTY }; } // anonymous namespace -class MapFieldStateTest - : public testing::TestWithParam { +class MapFieldStateTest : public testing::TestWithParam { public: protected: typedef unittest::TestMap_MapInt32Int32Entry_DoNotUse EntryType; @@ -292,7 +290,11 @@ class MapFieldStateTest if (is_repeated_null) { EXPECT_TRUE(repeated_field == NULL); } else { - EXPECT_EQ(repeated_size, repeated_field->size()); + if (repeated_field == nullptr) { + EXPECT_EQ(repeated_size, 0); + } else { + EXPECT_EQ(repeated_size, repeated_field->size()); + } } } @@ -301,8 +303,8 @@ class MapFieldStateTest State state_; }; -INSTANTIATE_TEST_CASE_P(MapFieldStateTestInstance, MapFieldStateTest, - ::testing::Values(CLEAN, MAP_DIRTY, REPEATED_DIRTY)); +INSTANTIATE_TEST_SUITE_P(MapFieldStateTestInstance, MapFieldStateTest, + ::testing::Values(CLEAN, MAP_DIRTY, REPEATED_DIRTY)); TEST_P(MapFieldStateTest, GetMap) { map_field_->GetMap(); @@ -439,11 +441,7 @@ TEST_P(MapFieldStateTest, SwapRepeatedDirty) { TEST_P(MapFieldStateTest, Clear) { map_field_->Clear(); - if (state_ != MAP_DIRTY) { - Expect(map_field_.get(), MAP_DIRTY, 0, 1, false); - } else { - Expect(map_field_.get(), MAP_DIRTY, 0, 0, true); - } + Expect(map_field_.get(), MAP_DIRTY, 0, 0, false); } TEST_P(MapFieldStateTest, SpaceUsedExcludingSelf) { diff --git a/third_party/protobuf/src/google/protobuf/map_lite_test_util.h b/third_party/protobuf/src/google/protobuf/map_lite_test_util.h index 66dedde5..573de7b2 100644 --- a/third_party/protobuf/src/google/protobuf/map_lite_test_util.h +++ b/third_party/protobuf/src/google/protobuf/map_lite_test_util.h @@ -75,6 +75,6 @@ class MapLiteTestUtil { }; } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_MAP_LITE_TEST_UTIL_H__ diff --git a/third_party/protobuf/src/google/protobuf/map_test.cc b/third_party/protobuf/src/google/protobuf/map_test.cc index 829a60ff..ec13b3c8 100644 --- a/third_party/protobuf/src/google/protobuf/map_test.cc +++ b/third_party/protobuf/src/google/protobuf/map_test.cc @@ -37,14 +37,13 @@ #endif // _WIN32 #include -#include #include #include #include #include +#include #include -#include #include #include #include @@ -54,6 +53,7 @@ #include #include #include +#include #include #include #include @@ -69,26 +69,29 @@ #include #include #include -#include #include #include #include #include #include #include +#include + + +#include namespace google { - -using google::protobuf::unittest::ForeignMessage; -using google::protobuf::unittest::TestAllTypes; -using google::protobuf::unittest::TestMap; -using google::protobuf::unittest::TestRecursiveMapMessage; - namespace protobuf { + +using unittest::ForeignMessage; +using unittest::TestAllTypes; +using unittest::TestMap; +using unittest::TestRecursiveMapMessage; + namespace internal { void MapTestForceDeterministic() { - ::google::protobuf::io::CodedOutputStream::SetDefaultSerializationDeterministic(); + io::CodedOutputStream::SetDefaultSerializationDeterministic(); } // Map API Test ===================================================== @@ -122,15 +125,16 @@ class MapImplTest : public ::testing::Test { // Test map size is correct. EXPECT_EQ(value, map_[key]); EXPECT_EQ(1, map_.count(key)); + EXPECT_TRUE(map_.contains(key)); // Check mutable at and find work correctly. EXPECT_EQ(value, map_.at(key)); Map::iterator it = map_.find(key); // iterator dereferenceable - EXPECT_EQ(key, (*it).first); + EXPECT_EQ(key, (*it).first); EXPECT_EQ(value, (*it).second); - EXPECT_EQ(key, it->first); + EXPECT_EQ(key, it->first); EXPECT_EQ(value, it->second); // iterator mutable @@ -240,8 +244,12 @@ TEST_F(MapImplTest, MapKeyAssignment) { EXPECT_EQ("abc", to.GetStringValue()); } -TEST_F(MapImplTest, CountNonExist) { - EXPECT_EQ(0, map_.count(0)); +TEST_F(MapImplTest, CountNonExist) { EXPECT_EQ(0, map_.count(0)); } + +TEST_F(MapImplTest, ContainNotExist) { EXPECT_FALSE(map_.contains(0)); } + +TEST_F(MapImplTest, ImmutableContainNotExist) { + EXPECT_FALSE(const_map_.contains(0)); } TEST_F(MapImplTest, MutableFindNonExist) { @@ -309,8 +317,8 @@ static int64 median(Iterator i0, Iterator i1) { } static int64 Now() { - return google::protobuf::util::TimeUtil::TimestampToNanoseconds( - google::protobuf::util::TimeUtil::GetCurrentTime()); + return util::TimeUtil::TimestampToNanoseconds( + util::TimeUtil::GetCurrentTime()); } // Arbitrary odd integers for creating test data. @@ -421,8 +429,7 @@ TEST_F(MapImplTest, CopyIteratorStressTest) { } template -static void TestValidityForAllKeysExcept(int key_to_avoid, - const T& check_map, +static void TestValidityForAllKeysExcept(int key_to_avoid, const T& check_map, const U& map) { typedef typename U::value_type value_type; // a key-value pair for (typename U::const_iterator it = map.begin(); it != map.end(); ++it) { @@ -454,7 +461,8 @@ template static void TestOldVersusNewIterator(int skip, Map* m) { const int initial_size = m->size(); IteratorType it = m->begin(); - for (int i = 0; i < skip && it != m->end(); it++, i++) {} + for (int i = 0; i < skip && it != m->end(); it++, i++) { + } if (it == m->end()) return; const IteratorType old = it; GOOGLE_LOG(INFO) << "skip=" << skip << ", old->first=" << old->first; @@ -505,8 +513,8 @@ static void StressTestIterators(int n) { ASSERT_EQ(n, m.size()); // Create maps of pointers and iterators. // These should remain valid even if we modify m. - hash_map::value_type*> mp(n); - hash_map::iterator> mi(n); + std::unordered_map::value_type*> mp(n); + std::unordered_map::iterator> mi(n); for (Map::iterator it = m.begin(); it != m.end(); ++it) { mp[it->first] = &*it; mi[it->first] = it; @@ -621,8 +629,9 @@ bool IsForwardIteratorHelper(T /*t*/) { TEST_F(MapImplTest, IteratorCategory) { EXPECT_TRUE(IsForwardIteratorHelper( std::iterator_traits::iterator>::iterator_category())); - EXPECT_TRUE(IsForwardIteratorHelper(std::iterator_traits< - Map::const_iterator>::iterator_category())); + EXPECT_TRUE(IsForwardIteratorHelper( + std::iterator_traits< + Map::const_iterator>::iterator_category())); } TEST_F(MapImplTest, InsertSingle) { @@ -868,7 +877,7 @@ TEST_F(MapImplTest, Assigner) { EXPECT_TRUE(other.find(key_other) == other.end()); // Self assign - other = other; + other = *&other; // Avoid -Wself-assign. EXPECT_EQ(2, other.size()); EXPECT_EQ(value1, other.at(key1)); EXPECT_EQ(value2, other.at(key2)); @@ -895,8 +904,8 @@ TEST_F(MapImplTest, EqualRange) { int key = 100, key_missing = 101; map_[key] = 100; - std::pair::iterator, - google::protobuf::Map::iterator> range = map_.equal_range(key); + std::pair::iterator, Map::iterator> range = + map_.equal_range(key); EXPECT_TRUE(map_.find(key) == range.first); EXPECT_TRUE(++map_.find(key) == range.second); @@ -904,9 +913,9 @@ TEST_F(MapImplTest, EqualRange) { EXPECT_TRUE(map_.end() == range.first); EXPECT_TRUE(map_.end() == range.second); - std::pair::const_iterator, - google::protobuf::Map::const_iterator> const_range = - const_map_.equal_range(key); + std::pair::const_iterator, + Map::const_iterator> + const_range = const_map_.equal_range(key); EXPECT_TRUE(const_map_.find(key) == const_range.first); EXPECT_TRUE(++const_map_.find(key) == const_range.second); @@ -936,11 +945,10 @@ TEST_F(MapImplTest, SwapBasic) { another[9398] = 41999; another[8070] = 42056; another.swap(map_); - EXPECT_THAT(another, testing::UnorderedElementsAre( - testing::Pair(9398, 41999))); - EXPECT_THAT(map_, testing::UnorderedElementsAre( - testing::Pair(8070, 42056), - testing::Pair(9398, 41999))); + EXPECT_THAT(another, + testing::UnorderedElementsAre(testing::Pair(9398, 41999))); + EXPECT_THAT(map_, testing::UnorderedElementsAre(testing::Pair(8070, 42056), + testing::Pair(9398, 41999))); } TEST_F(MapImplTest, SwapArena) { @@ -953,23 +961,18 @@ TEST_F(MapImplTest, SwapArena) { m2[10244] = 10247; m2[8070] = 42056; m1.swap(map_); - EXPECT_THAT(m1, testing::UnorderedElementsAre( - testing::Pair(9398, 41999))); - EXPECT_THAT(map_, testing::UnorderedElementsAre( - testing::Pair(8070, 42056), - testing::Pair(9398, 41999))); + EXPECT_THAT(m1, testing::UnorderedElementsAre(testing::Pair(9398, 41999))); + EXPECT_THAT(map_, testing::UnorderedElementsAre(testing::Pair(8070, 42056), + testing::Pair(9398, 41999))); m2.swap(m1); - EXPECT_THAT(m1, testing::UnorderedElementsAre( - testing::Pair(8070, 42056), - testing::Pair(10244, 10247))); - EXPECT_THAT(m2, testing::UnorderedElementsAre( - testing::Pair(9398, 41999))); + EXPECT_THAT(m1, testing::UnorderedElementsAre(testing::Pair(8070, 42056), + testing::Pair(10244, 10247))); + EXPECT_THAT(m2, testing::UnorderedElementsAre(testing::Pair(9398, 41999))); } TEST_F(MapImplTest, CopyAssignMapIterator) { TestMap message; - MapReflectionTester reflection_tester( - unittest::TestMap::descriptor()); + MapReflectionTester reflection_tester(unittest::TestMap::descriptor()); reflection_tester.SetMapFieldsViaMapReflection(&message); MapIterator it1 = reflection_tester.MapBegin(&message, "map_int32_int32"); MapIterator it2 = reflection_tester.MapEnd(&message, "map_int32_int32"); @@ -979,17 +982,15 @@ TEST_F(MapImplTest, CopyAssignMapIterator) { // Map Field Reflection Test ======================================== -static int Func(int i, int j) { - return i * j; -} +static int Func(int i, int j) { return i * j; } -static string StrFunc(int i, int j) { - string str; +static std::string StrFunc(int i, int j) { + std::string str; SStringPrintf(&str, "%d", Func(i, j)); return str; } -static int Int(const string& value) { +static int Int(const std::string& value) { int result = 0; std::istringstream(value) >> result; return result; @@ -1012,7 +1013,8 @@ TEST_F(MapFieldReflectionTest, RegularFields) { Map* map_int32_int32 = message.mutable_map_int32_int32(); Map* map_int32_double = message.mutable_map_int32_double(); - Map* map_string_string = message.mutable_map_string_string(); + Map* map_string_string = + message.mutable_map_string_string(); Map* map_int32_foreign_message = message.mutable_map_int32_foreign_message(); @@ -1057,10 +1059,8 @@ TEST_F(MapFieldReflectionTest, RegularFields) { refl->GetRepeatedPtrField(message, fd_map_int32_double); const RepeatedPtrField& mf_string_string = refl->GetRepeatedPtrField(message, fd_map_string_string); - const RepeatedPtrField& - mf_int32_foreign_message = - refl->GetRepeatedPtrField( - message, fd_map_int32_foreign_message); + const RepeatedPtrField& mf_int32_foreign_message = + refl->GetRepeatedPtrField(message, fd_map_int32_foreign_message); // Get mutable RepeatedPtrField objects for all fields of interest. RepeatedPtrField* mmf_int32_int32 = @@ -1070,8 +1070,8 @@ TEST_F(MapFieldReflectionTest, RegularFields) { RepeatedPtrField* mmf_string_string = refl->MutableRepeatedPtrField(&message, fd_map_string_string); RepeatedPtrField* mmf_int32_foreign_message = - refl->MutableRepeatedPtrField( - &message, fd_map_int32_foreign_message); + refl->MutableRepeatedPtrField(&message, + fd_map_int32_foreign_message); // Make sure we can do gets through the RepeatedPtrField objects. for (int i = 0; i < 10; ++i) { @@ -1093,10 +1093,10 @@ TEST_F(MapFieldReflectionTest, RegularFields) { EXPECT_EQ(value_int32_double, Func(key_int32_double, 2)); const Message& message_string_string = mf_string_string.Get(i); - string key_string_string = + std::string key_string_string = message_string_string.GetReflection()->GetString( message_string_string, fd_map_string_string_key); - string value_string_string = + std::string value_string_string = message_string_string.GetReflection()->GetString( message_string_string, fd_map_string_string_value); EXPECT_EQ(value_string_string, StrFunc(Int(key_string_string), 5)); @@ -1106,9 +1106,8 @@ TEST_F(MapFieldReflectionTest, RegularFields) { message_int32_message, fd_map_int32_foreign_message_key); const ForeignMessage& value_int32_message = down_cast( - message_int32_message.GetReflection() - ->GetMessage(message_int32_message, - fd_map_int32_foreign_message_value)); + message_int32_message.GetReflection()->GetMessage( + message_int32_message, fd_map_int32_foreign_message_value)); EXPECT_EQ(value_int32_message.c(), Func(key_int32_message, 6)); } @@ -1130,10 +1129,10 @@ TEST_F(MapFieldReflectionTest, RegularFields) { EXPECT_EQ(value_int32_double, Func(key_int32_double, 2)); const Message& message_string_string = mmf_string_string->Get(i); - string key_string_string = + std::string key_string_string = message_string_string.GetReflection()->GetString( message_string_string, fd_map_string_string_key); - string value_string_string = + std::string value_string_string = message_string_string.GetReflection()->GetString( message_string_string, fd_map_string_string_value); EXPECT_EQ(value_string_string, StrFunc(Int(key_string_string), 5)); @@ -1143,9 +1142,8 @@ TEST_F(MapFieldReflectionTest, RegularFields) { message_int32_message, fd_map_int32_foreign_message_key); const ForeignMessage& value_int32_message = down_cast( - message_int32_message.GetReflection() - ->GetMessage(message_int32_message, - fd_map_int32_foreign_message_value)); + message_int32_message.GetReflection()->GetMessage( + message_int32_message, fd_map_int32_foreign_message_value)); EXPECT_EQ(value_int32_message.c(), Func(key_int32_message, 6)); } } @@ -1168,7 +1166,7 @@ TEST_F(MapFieldReflectionTest, RegularFields) { Func(key_int32_double, -2)); Message* message_string_string = mmf_string_string->Mutable(i); - string key_string_string = + std::string key_string_string = message_string_string->GetReflection()->GetString( *message_string_string, fd_map_string_string_key); message_string_string->GetReflection()->SetString( @@ -1180,9 +1178,8 @@ TEST_F(MapFieldReflectionTest, RegularFields) { message_int32_message->GetReflection()->GetInt32( *message_int32_message, fd_map_int32_foreign_message_key); ForeignMessage* value_int32_message = down_cast( - message_int32_message->GetReflection() - ->MutableMessage(message_int32_message, - fd_map_int32_foreign_message_value)); + message_int32_message->GetReflection()->MutableMessage( + message_int32_message, fd_map_int32_foreign_message_value)); value_int32_message->set_c(Func(key_int32_message, -6)); } } @@ -1203,7 +1200,8 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { Map* map_int32_int32 = message.mutable_map_int32_int32(); Map* map_int32_double = message.mutable_map_int32_double(); - Map* map_string_string = message.mutable_map_string_string(); + Map* map_string_string = + message.mutable_map_string_string(); Map* map_int32_foreign_message = message.mutable_map_int32_foreign_message(); @@ -1258,10 +1256,9 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { refl->GetMutableRepeatedFieldRef(&message, fd_map_int32_double); const MutableRepeatedFieldRef mmf_string_string = refl->GetMutableRepeatedFieldRef(&message, fd_map_string_string); - const MutableRepeatedFieldRef - mmf_int32_foreign_message = - refl->GetMutableRepeatedFieldRef( - &message, fd_map_int32_foreign_message); + const MutableRepeatedFieldRef mmf_int32_foreign_message = + refl->GetMutableRepeatedFieldRef(&message, + fd_map_int32_foreign_message); // Get entry default instances std::unique_ptr entry_int32_int32( @@ -1322,10 +1319,10 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { const Message& message_string_string = mf_string_string.Get(i, entry_string_string.get()); - string key_string_string = + std::string key_string_string = message_string_string.GetReflection()->GetString( message_string_string, fd_map_string_string_key); - string value_string_string = + std::string value_string_string = message_string_string.GetReflection()->GetString( message_string_string, fd_map_string_string_value); EXPECT_EQ(value_string_string, StrFunc(Int(key_string_string), 5)); @@ -1336,9 +1333,8 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { message_int32_message, fd_map_int32_foreign_message_key); const ForeignMessage& value_int32_message = down_cast( - message_int32_message.GetReflection() - ->GetMessage(message_int32_message, - fd_map_int32_foreign_message_value)); + message_int32_message.GetReflection()->GetMessage( + message_int32_message, fd_map_int32_foreign_message_value)); EXPECT_EQ(value_int32_message.c(), Func(key_int32_message, 6)); } @@ -1363,10 +1359,10 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { const Message& message_string_string = mmf_string_string.Get(i, entry_string_string.get()); - string key_string_string = + std::string key_string_string = message_string_string.GetReflection()->GetString( message_string_string, fd_map_string_string_key); - string value_string_string = + std::string value_string_string = message_string_string.GetReflection()->GetString( message_string_string, fd_map_string_string_value); EXPECT_EQ(value_string_string, StrFunc(Int(key_string_string), 5)); @@ -1377,9 +1373,8 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { message_int32_message, fd_map_int32_foreign_message_key); const ForeignMessage& value_int32_message = down_cast( - message_int32_message.GetReflection() - ->GetMessage(message_int32_message, - fd_map_int32_foreign_message_value)); + message_int32_message.GetReflection()->GetMessage( + message_int32_message, fd_map_int32_foreign_message_value)); EXPECT_EQ(value_int32_message.c(), Func(key_int32_message, 6)); } } @@ -1436,7 +1431,7 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { // Test iterators. { int index = 0; - hash_map result; + std::unordered_map result; for (RepeatedFieldRef::iterator it = mf_int32_int32.begin(); it != mf_int32_int32.end(); ++it) { const Message& message = *it; @@ -1448,7 +1443,7 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { ++index; } EXPECT_EQ(10, index); - for (hash_map::const_iterator it = result.begin(); + for (std::unordered_map::const_iterator it = result.begin(); it != result.end(); ++it) { EXPECT_EQ(message.map_int32_int32().at(it->first), it->second); } @@ -1456,7 +1451,7 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { { int index = 0; - hash_map result; + std::unordered_map result; for (RepeatedFieldRef::iterator it = mf_int32_double.begin(); it != mf_int32_double.end(); ++it) { const Message& message = *it; @@ -1468,7 +1463,7 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { ++index; } EXPECT_EQ(10, index); - for (hash_map::const_iterator it = result.begin(); + for (std::unordered_map::const_iterator it = result.begin(); it != result.end(); ++it) { EXPECT_EQ(message.map_int32_double().at(it->first), it->second); } @@ -1476,19 +1471,20 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { { int index = 0; - hash_map result; + std::unordered_map result; for (RepeatedFieldRef::iterator it = mf_string_string.begin(); it != mf_string_string.end(); ++it) { const Message& message = *it; - string key = + std::string key = message.GetReflection()->GetString(message, fd_map_string_string_key); - string value = message.GetReflection()->GetString( + std::string value = message.GetReflection()->GetString( message, fd_map_string_string_value); result[key] = value; ++index; } EXPECT_EQ(10, index); - for (hash_map::const_iterator it = result.begin(); + for (std::unordered_map::const_iterator it = + result.begin(); it != result.end(); ++it) { EXPECT_EQ(message.map_string_string().at(it->first), it->second); } @@ -1503,9 +1499,9 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { const Message& message = *it; int32 key = message.GetReflection()->GetInt32( message, fd_map_int32_foreign_message_key); - const ForeignMessage& sub_message = down_cast( - message.GetReflection() - ->GetMessage(message, fd_map_int32_foreign_message_value)); + const ForeignMessage& sub_message = + down_cast(message.GetReflection()->GetMessage( + message, fd_map_int32_foreign_message_value)); result[key].MergeFrom(sub_message); ++index; } @@ -1537,8 +1533,8 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { EXPECT_EQ(1234.0, message.map_int32_double().at(4321)); entry_string_string->GetReflection()->SetString( - entry_string_string.get(), - fd_map_string_string->message_type()->field(0), "4321"); + entry_string_string.get(), fd_map_string_string->message_type()->field(0), + "4321"); entry_string_string->GetReflection()->SetString( entry_string_string.get(), fd_map_string_string->message_type()->field(1), "1234"); @@ -1560,12 +1556,13 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { EXPECT_EQ(1234, message.map_int32_foreign_message().at(4321).c()); // Test Reflection::AddAllocatedMessage - Message* free_entry_string_string = MessageFactory::generated_factory() - ->GetPrototype(fd_map_string_string->message_type()) - ->New(); + Message* free_entry_string_string = + MessageFactory::generated_factory() + ->GetPrototype(fd_map_string_string->message_type()) + ->New(); entry_string_string->GetReflection()->SetString( - free_entry_string_string, - fd_map_string_string->message_type()->field(0), "4321"); + free_entry_string_string, fd_map_string_string->message_type()->field(0), + "4321"); entry_string_string->GetReflection()->SetString( free_entry_string_string, fd_map_string_string->message_type()->field(1), "1234"); @@ -1632,22 +1629,22 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { { const Message& message0a = mmf_string_string.Get(0, entry_string_string.get()); - string string_value0a = message0a.GetReflection()->GetString( + std::string string_value0a = message0a.GetReflection()->GetString( message0a, fd_map_string_string_value); const Message& message9a = mmf_string_string.Get(9, entry_string_string.get()); - string string_value9a = message9a.GetReflection()->GetString( + std::string string_value9a = message9a.GetReflection()->GetString( message9a, fd_map_string_string_value); mmf_string_string.SwapElements(0, 9); const Message& message0b = mmf_string_string.Get(0, entry_string_string.get()); - string string_value0b = message0b.GetReflection()->GetString( + std::string string_value0b = message0b.GetReflection()->GetString( message0b, fd_map_string_string_value); const Message& message9b = mmf_string_string.Get(9, entry_string_string.get()); - string string_value9b = message9b.GetReflection()->GetString( + std::string string_value9b = message9b.GetReflection()->GetString( message9b, fd_map_string_string_value); EXPECT_EQ(string_value9a, string_value0b); @@ -1657,30 +1654,30 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { { const Message& message0a = mmf_int32_foreign_message.Get(0, entry_int32_foreign_message.get()); - const ForeignMessage& sub_message0a = down_cast( - message0a.GetReflection() - ->GetMessage(message0a, fd_map_int32_foreign_message_value)); + const ForeignMessage& sub_message0a = + down_cast(message0a.GetReflection()->GetMessage( + message0a, fd_map_int32_foreign_message_value)); int32 int32_value0a = sub_message0a.c(); const Message& message9a = mmf_int32_foreign_message.Get(9, entry_int32_foreign_message.get()); - const ForeignMessage& sub_message9a = down_cast( - message9a.GetReflection() - ->GetMessage(message9a, fd_map_int32_foreign_message_value)); + const ForeignMessage& sub_message9a = + down_cast(message9a.GetReflection()->GetMessage( + message9a, fd_map_int32_foreign_message_value)); int32 int32_value9a = sub_message9a.c(); mmf_int32_foreign_message.SwapElements(0, 9); const Message& message0b = mmf_int32_foreign_message.Get(0, entry_int32_foreign_message.get()); - const ForeignMessage& sub_message0b = down_cast( - message0b.GetReflection() - ->GetMessage(message0b, fd_map_int32_foreign_message_value)); + const ForeignMessage& sub_message0b = + down_cast(message0b.GetReflection()->GetMessage( + message0b, fd_map_int32_foreign_message_value)); int32 int32_value0b = sub_message0b.c(); const Message& message9b = mmf_int32_foreign_message.Get(9, entry_int32_foreign_message.get()); - const ForeignMessage& sub_message9b = down_cast( - message9b.GetReflection() - ->GetMessage(message9b, fd_map_int32_foreign_message_value)); + const ForeignMessage& sub_message9b = + down_cast(message9b.GetReflection()->GetMessage( + message9b, fd_map_int32_foreign_message_value)); int32 int32_value9b = sub_message9b.c(); EXPECT_EQ(int32_value9a, int32_value0b); @@ -1719,34 +1716,26 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefMergeFromAndSwap) { const FieldDescriptor* fd_map_int32_foreign_message = desc->FindFieldByName("map_int32_foreign_message"); - // Get MutableRepeatedFieldRef objects for all fields of interest. + // Get MutableRepeatedFieldRef objects for all fields of interest. const MutableRepeatedFieldRef mmf_int32_int32 = - refl->GetMutableRepeatedFieldRef( - &m0, fd_map_int32_int32); + refl->GetMutableRepeatedFieldRef(&m0, fd_map_int32_int32); const MutableRepeatedFieldRef mmf_int32_double = - refl->GetMutableRepeatedFieldRef( - &m0, fd_map_int32_double); + refl->GetMutableRepeatedFieldRef(&m0, fd_map_int32_double); const MutableRepeatedFieldRef mmf_string_string = - refl->GetMutableRepeatedFieldRef( - &m0, fd_map_string_string); - const MutableRepeatedFieldRef - mmf_int32_foreign_message = - refl->GetMutableRepeatedFieldRef( - &m0, fd_map_int32_foreign_message); + refl->GetMutableRepeatedFieldRef(&m0, fd_map_string_string); + const MutableRepeatedFieldRef mmf_int32_foreign_message = + refl->GetMutableRepeatedFieldRef(&m0, + fd_map_int32_foreign_message); // Test MutableRepeatedRef::CopyFrom mmf_int32_int32.CopyFrom( - refl->GetRepeatedFieldRef( - m1, fd_map_int32_int32)); + refl->GetRepeatedFieldRef(m1, fd_map_int32_int32)); mmf_int32_double.CopyFrom( - refl->GetRepeatedFieldRef( - m1, fd_map_int32_double)); + refl->GetRepeatedFieldRef(m1, fd_map_int32_double)); mmf_string_string.CopyFrom( - refl->GetRepeatedFieldRef( - m1, fd_map_string_string)); + refl->GetRepeatedFieldRef(m1, fd_map_string_string)); mmf_int32_foreign_message.CopyFrom( - refl->GetRepeatedFieldRef( - m1, fd_map_int32_foreign_message)); + refl->GetRepeatedFieldRef(m1, fd_map_int32_foreign_message)); for (int i = 0; i < 10; ++i) { EXPECT_EQ(Func(i, 11), m0.map_int32_int32().at(i + 10)); @@ -1757,17 +1746,13 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefMergeFromAndSwap) { // Test MutableRepeatedRef::MergeFrom mmf_int32_int32.MergeFrom( - refl->GetRepeatedFieldRef( - m2, fd_map_int32_int32)); + refl->GetRepeatedFieldRef(m2, fd_map_int32_int32)); mmf_int32_double.MergeFrom( - refl->GetRepeatedFieldRef( - m2, fd_map_int32_double)); + refl->GetRepeatedFieldRef(m2, fd_map_int32_double)); mmf_string_string.MergeFrom( - refl->GetRepeatedFieldRef( - m2, fd_map_string_string)); + refl->GetRepeatedFieldRef(m2, fd_map_string_string)); mmf_int32_foreign_message.MergeFrom( - refl->GetRepeatedFieldRef( - m2, fd_map_int32_foreign_message)); + refl->GetRepeatedFieldRef(m2, fd_map_int32_foreign_message)); for (int i = 0; i < 10; ++i) { EXPECT_EQ(Func(i, 21), m0.map_int32_int32().at(i + 20)); EXPECT_EQ(Func(i, 22), m0.map_int32_double().at(i + 20)); @@ -1778,17 +1763,13 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefMergeFromAndSwap) { // Test MutableRepeatedRef::Swap // Swap between m0 and m2. mmf_int32_int32.Swap( - refl->GetMutableRepeatedFieldRef( - &m2, fd_map_int32_int32)); + refl->GetMutableRepeatedFieldRef(&m2, fd_map_int32_int32)); mmf_int32_double.Swap( - refl->GetMutableRepeatedFieldRef( - &m2, fd_map_int32_double)); + refl->GetMutableRepeatedFieldRef(&m2, fd_map_int32_double)); mmf_string_string.Swap( - refl->GetMutableRepeatedFieldRef( - &m2, fd_map_string_string)); - mmf_int32_foreign_message.Swap( - refl->GetMutableRepeatedFieldRef( - &m2, fd_map_int32_foreign_message)); + refl->GetMutableRepeatedFieldRef(&m2, fd_map_string_string)); + mmf_int32_foreign_message.Swap(refl->GetMutableRepeatedFieldRef( + &m2, fd_map_int32_foreign_message)); for (int i = 0; i < 10; ++i) { // Check the content of m0. EXPECT_EQ(Func(i, 21), m0.map_int32_int32().at(i + 20)); @@ -1975,8 +1956,7 @@ TEST(GeneratedMapFieldTest, CopyAssignmentOperator) { MapTestUtil::ExpectMapFieldsSet(message2); } -#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \ - !defined(GOOGLE_PROTOBUF_NO_RTTI) +#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || PROTOBUF_RTTI TEST(GeneratedMapFieldTest, UpcastCopyFrom) { // Test the CopyFrom method that takes in the generic const Message& // parameter. @@ -2001,10 +1981,8 @@ TEST(GeneratedMapFieldTest, CopyFromDynamicMessage) { // Construct a new version of the dynamic message via the factory. DynamicMessageFactory factory; std::unique_ptr message1; - message1.reset( - factory.GetPrototype(unittest::TestMap::descriptor())->New()); - MapReflectionTester reflection_tester( - unittest::TestMap::descriptor()); + message1.reset(factory.GetPrototype(unittest::TestMap::descriptor())->New()); + MapReflectionTester reflection_tester(unittest::TestMap::descriptor()); reflection_tester.SetMapFieldsViaReflection(message1.get()); reflection_tester.ExpectMapFieldsSetViaReflection(*message1); reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1.get()); @@ -2018,10 +1996,8 @@ TEST(GeneratedMapFieldTest, CopyFromDynamicMessageMapReflection) { // Construct a new version of the dynamic message via the factory. DynamicMessageFactory factory; std::unique_ptr message1; - message1.reset( - factory.GetPrototype(unittest::TestMap::descriptor())->New()); - MapReflectionTester reflection_tester( - unittest::TestMap::descriptor()); + message1.reset(factory.GetPrototype(unittest::TestMap::descriptor())->New()); + MapReflectionTester reflection_tester(unittest::TestMap::descriptor()); reflection_tester.SetMapFieldsViaMapReflection(message1.get()); reflection_tester.ExpectMapFieldsSetViaReflection(*message1); reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1.get()); @@ -2029,6 +2005,38 @@ TEST(GeneratedMapFieldTest, CopyFromDynamicMessageMapReflection) { MapTestUtil::ExpectMapFieldsSet(message2); } +TEST(GeneratedMapFieldTest, DynamicMessageMergeFromDynamicMessage) { + // Construct two dynamic message and sets via map reflection. + DynamicMessageFactory factory; + std::unique_ptr message1; + message1.reset(factory.GetPrototype(unittest::TestMap::descriptor())->New()); + MapReflectionTester reflection_tester(unittest::TestMap::descriptor()); + reflection_tester.SetMapFieldsViaMapReflection(message1.get()); + + // message2 is created by same factory. + std::unique_ptr message2; + message2.reset(factory.GetPrototype(unittest::TestMap::descriptor())->New()); + reflection_tester.SetMapFieldsViaMapReflection(message2.get()); + + // message3 is created by different factory. + DynamicMessageFactory factory3; + std::unique_ptr message3; + message3.reset(factory3.GetPrototype(unittest::TestMap::descriptor())->New()); + reflection_tester.SetMapFieldsViaMapReflection(message3.get()); + + message2->MergeFrom(*message1); + message3->MergeFrom(*message1); + + // Test MergeFrom does not sync to repeated fields and + // there is no duplicate keys in text format. + std::string output1, output2, output3; + TextFormat::PrintToString(*message1, &output1); + TextFormat::PrintToString(*message2, &output2); + TextFormat::PrintToString(*message3, &output3); + EXPECT_EQ(output1, output2); + EXPECT_EQ(output1, output3); +} + TEST(GeneratedMapFieldTest, DynamicMessageCopyFrom) { // Test copying to a DynamicMessage, which must fall back to using reflection. unittest::TestMap message2; @@ -2037,27 +2045,23 @@ TEST(GeneratedMapFieldTest, DynamicMessageCopyFrom) { // Construct a new version of the dynamic message via the factory. DynamicMessageFactory factory; std::unique_ptr message1; - message1.reset( - factory.GetPrototype(unittest::TestMap::descriptor())->New()); + message1.reset(factory.GetPrototype(unittest::TestMap::descriptor())->New()); - MapReflectionTester reflection_tester( - unittest::TestMap::descriptor()); + MapReflectionTester reflection_tester(unittest::TestMap::descriptor()); message1->MergeFrom(message2); reflection_tester.ExpectMapFieldsSetViaReflection(*message1); reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1.get()); } TEST(GeneratedMapFieldTest, DynamicMessageCopyFromMapReflection) { - MapReflectionTester reflection_tester( - unittest::TestMap::descriptor()); + MapReflectionTester reflection_tester(unittest::TestMap::descriptor()); unittest::TestMap message2; reflection_tester.SetMapFieldsViaMapReflection(&message2); // Construct a dynamic message via the factory. DynamicMessageFactory factory; std::unique_ptr message1; - message1.reset( - factory.GetPrototype(unittest::TestMap::descriptor())->New()); + message1.reset(factory.GetPrototype(unittest::TestMap::descriptor())->New()); message1->MergeFrom(message2); reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1.get()); @@ -2066,12 +2070,10 @@ TEST(GeneratedMapFieldTest, DynamicMessageCopyFromMapReflection) { TEST(GeneratedMapFieldTest, SyncDynamicMapWithRepeatedField) { // Construct a dynamic message via the factory. - MapReflectionTester reflection_tester( - unittest::TestMap::descriptor()); + MapReflectionTester reflection_tester(unittest::TestMap::descriptor()); DynamicMessageFactory factory; std::unique_ptr message; - message.reset( - factory.GetPrototype(unittest::TestMap::descriptor())->New()); + message.reset(factory.GetPrototype(unittest::TestMap::descriptor())->New()); reflection_tester.SetMapFieldsViaReflection(message.get()); reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message.get()); reflection_tester.ExpectMapFieldsSetViaReflection(*message); @@ -2094,6 +2096,18 @@ TEST(GeneratedMapFieldTest, NonEmptyMergeFrom) { message1.MergeFrom(message2); MapTestUtil::ExpectMapFieldsSet(message1); + + // Test reflection MergeFrom does not sync to repeated field + // and there is no duplicated keys. + MapTestUtil::SetMapFields(&message1); + MapTestUtil::SetMapFields(&message2); + + message2.MergeFrom(message1); + + std::string output1, output2; + TextFormat::PrintToString(message1, &output1); + TextFormat::PrintToString(message2, &output2); + EXPECT_EQ(output1, output2); } TEST(GeneratedMapFieldTest, MergeFromMessageMap) { @@ -2112,11 +2126,11 @@ TEST(GeneratedMapFieldTest, MergeFromMessageMap) { // Test the generated SerializeWithCachedSizesToArray() TEST(GeneratedMapFieldTest, SerializationToArray) { unittest::TestMap message1, message2; - string data; + std::string data; MapTestUtil::SetMapFields(&message1); int size = message1.ByteSize(); data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); + uint8* start = reinterpret_cast(::google::protobuf::string_as_array(&data)); uint8* end = message1.SerializeWithCachedSizesToArray(start); EXPECT_EQ(size, end - start); EXPECT_TRUE(message2.ParseFromString(data)); @@ -2128,11 +2142,11 @@ TEST(GeneratedMapFieldTest, SerializationToStream) { unittest::TestMap message1, message2; MapTestUtil::SetMapFields(&message1); int size = message1.ByteSize(); - string data; + std::string data; data.resize(size); { // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1); io::CodedOutputStream output_stream(&array_stream); message1.SerializeWithCachedSizes(&output_stream); EXPECT_FALSE(output_stream.HadError()); @@ -2164,7 +2178,7 @@ TEST(GeneratedMapFieldTest, Proto2UnknownEnum) { unittest::TestEnumMapPlusExtra from; (*from.mutable_known_map_field())[0] = unittest::E_PROTO2_MAP_ENUM_FOO; (*from.mutable_unknown_map_field())[0] = unittest::E_PROTO2_MAP_ENUM_EXTRA; - string data; + std::string data; from.SerializeToString(&data); unittest::TestEnumMap to; @@ -2189,7 +2203,7 @@ TEST(GeneratedMapFieldTest, Proto2UnknownEnum) { TEST(GeneratedMapFieldTest, StandardWireFormat) { unittest::TestMap message; - string data = "\x0A\x04\x08\x01\x10\x01"; + std::string data = "\x0A\x04\x08\x01\x10\x01"; EXPECT_TRUE(message.ParseFromString(data)); EXPECT_EQ(1, message.map_int32_int32().size()); @@ -2200,10 +2214,11 @@ TEST(GeneratedMapFieldTest, UnorderedWireFormat) { unittest::TestMap message; // put value before key in wire format - string data = "\x0A\x04\x10\x01\x08\x02"; + std::string data = "\x0A\x04\x10\x01\x08\x02"; EXPECT_TRUE(message.ParseFromString(data)); EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_NE(message.map_int32_int32().find(2), message.map_int32_int32().end()); EXPECT_EQ(1, message.map_int32_int32().at(2)); } @@ -2211,7 +2226,7 @@ TEST(GeneratedMapFieldTest, DuplicatedKeyWireFormat) { unittest::TestMap message; // Two key fields in wire format - string data = "\x0A\x06\x08\x01\x08\x02\x10\x01"; + std::string data = "\x0A\x06\x08\x01\x08\x02\x10\x01"; EXPECT_TRUE(message.ParseFromString(data)); EXPECT_EQ(1, message.map_int32_int32().size()); @@ -2228,14 +2243,14 @@ TEST(GeneratedMapFieldTest, DuplicatedKeyWireFormat) { with_dummy4.set_c(0); with_dummy4.set_dummy4(11); (*map_message.mutable_map_field())[key] = with_dummy4; - string s = map_message.SerializeAsString(); + std::string s = map_message.SerializeAsString(); unittest::TestRequired with_dummy5; with_dummy5.set_a(0); with_dummy5.set_b(0); with_dummy5.set_c(0); with_dummy5.set_dummy5(12); (*map_message.mutable_map_field())[key] = with_dummy5; - string both = s + map_message.SerializeAsString(); + std::string both = s + map_message.SerializeAsString(); // We don't expect a merge now. The "second one wins." ASSERT_TRUE(map_message.ParseFromString(both)); ASSERT_EQ(1, map_message.map_field().size()); @@ -2259,7 +2274,7 @@ TEST(GeneratedMapFieldTest, KeysValuesUnknownsWireFormat) { const char kValueTag = 0x10; const char kJunkTag = 0x20; for (int items = 0; items <= kMaxNumKeysAndValuesAndJunk; items++) { - string data = "\x0A"; + std::string data = "\x0A"; // Encode length of what will follow. data.push_back(items * 2); static const int kBitsOfIPerItem = 4; @@ -2267,22 +2282,33 @@ TEST(GeneratedMapFieldTest, KeysValuesUnknownsWireFormat) { // Each iteration of the following is a test. It uses i as bit vector // encoding the keys and values to put in the wire format. for (int i = 0; i < (1 << (items * kBitsOfIPerItem)); i++) { - string wire_format = data; + std::string wire_format = data; int expected_key = 0; int expected_value = 0; for (int k = i, j = 0; j < items; j++, k >>= kBitsOfIPerItem) { bool is_key = k & 0x1; bool is_value = !is_key && (k & 0x2); - wire_format.push_back(is_key ? kKeyTag : - is_value ? kValueTag : kJunkTag); + wire_format.push_back(is_key ? kKeyTag + : is_value ? kValueTag : kJunkTag); char c = static_cast(k & mask) >> 2; // One char after the tag. wire_format.push_back(c); if (is_key) expected_key = static_cast(c); if (is_value) expected_value = static_cast(c); - ASSERT_TRUE(message.ParseFromString(wire_format)); - ASSERT_EQ(1, message.map_int32_int32().size()); - ASSERT_EQ(expected_key, message.map_int32_int32().begin()->first); - ASSERT_EQ(expected_value, message.map_int32_int32().begin()->second); + bool res = message.ParseFromString(wire_format); + bool expect_success = true; +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + // Unfortunately the old map parser accepts malformed input, the new + // parser accepts only correct input. + if (j != items - 1) expect_success = false; +#endif + if (expect_success) { + ASSERT_TRUE(res); + ASSERT_EQ(1, message.map_int32_int32().size()); + ASSERT_EQ(expected_key, message.map_int32_int32().begin()->first); + ASSERT_EQ(expected_value, message.map_int32_int32().begin()->second); + } else { + ASSERT_FALSE(res); + } } } } @@ -2292,7 +2318,7 @@ TEST(GeneratedMapFieldTest, DuplicatedValueWireFormat) { unittest::TestMap message; // Two value fields in wire format - string data = "\x0A\x06\x08\x01\x10\x01\x10\x02"; + std::string data = "\x0A\x06\x08\x01\x10\x01\x10\x02"; EXPECT_TRUE(message.ParseFromString(data)); EXPECT_EQ(1, message.map_int32_int32().size()); @@ -2303,10 +2329,11 @@ TEST(GeneratedMapFieldTest, MissedKeyWireFormat) { unittest::TestMap message; // No key field in wire format - string data = "\x0A\x02\x10\x01"; + std::string data = "\x0A\x02\x10\x01"; EXPECT_TRUE(message.ParseFromString(data)); EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_NE(message.map_int32_int32().find(0), message.map_int32_int32().end()); EXPECT_EQ(1, message.map_int32_int32().at(0)); } @@ -2314,10 +2341,11 @@ TEST(GeneratedMapFieldTest, MissedValueWireFormat) { unittest::TestMap message; // No value field in wire format - string data = "\x0A\x02\x08\x01"; + std::string data = "\x0A\x02\x08\x01"; EXPECT_TRUE(message.ParseFromString(data)); EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_NE(message.map_int32_int32().find(1), message.map_int32_int32().end()); EXPECT_EQ(0, message.map_int32_int32().at(1)); } @@ -2325,12 +2353,12 @@ TEST(GeneratedMapFieldTest, MissedValueTextFormat) { unittest::TestMap message; // No value field in text format - string text = + std::string text = "map_int32_foreign_message {\n" " key: 1234567890\n" "}"; - EXPECT_TRUE(google::protobuf::TextFormat::ParseFromString(text, &message)); + EXPECT_TRUE(TextFormat::ParseFromString(text, &message)); EXPECT_EQ(1, message.map_int32_foreign_message().size()); EXPECT_EQ(11, message.ByteSize()); } @@ -2339,7 +2367,7 @@ TEST(GeneratedMapFieldTest, UnknownFieldWireFormat) { unittest::TestMap message; // Unknown field in wire format - string data = "\x0A\x06\x08\x02\x10\x03\x18\x01"; + std::string data = "\x0A\x06\x08\x02\x10\x03\x18\x01"; EXPECT_TRUE(message.ParseFromString(data)); EXPECT_EQ(1, message.map_int32_int32().size()); @@ -2350,7 +2378,7 @@ TEST(GeneratedMapFieldTest, CorruptedWireFormat) { unittest::TestMap message; // corrupted data in wire format - string data = "\x0A\x06\x08\x02\x11\x03"; + std::string data = "\x0A\x06\x08\x02\x11\x03"; EXPECT_FALSE(message.ParseFromString(data)); } @@ -2380,14 +2408,14 @@ TEST(GeneratedMapFieldTest, MessagesMustMerge) { EXPECT_TRUE(with_dummy4.IsInitialized()); (*map_message.mutable_map_field())[0] = with_dummy4; EXPECT_TRUE(map_message.IsInitialized()); - string s = map_message.SerializeAsString(); + std::string s = map_message.SerializeAsString(); // Modify s so that there are two values in the entry for key 0. // The first will have no value for c. The second will have no value for a. // Those are required fields. Also, make some other little changes, to // ensure we are merging the two values (because they're messages). ASSERT_EQ(s.size() - 2, s[1]); // encoding of the length of what follows - string encoded_val(s.data() + 4, s.data() + s.size()); + std::string encoded_val(s.data() + 4, s.data() + s.size()); // In s, change the encoding of c to an encoding of dummy32. s[s.size() - 3] -= 8; // Make encoded_val slightly different from what's in s. @@ -2423,10 +2451,10 @@ TEST(GeneratedMapFieldTest, MessagesMustMerge) { EXPECT_EQ(99, map_message.map_field().find(key)->second.dummy5()); // Test key then value then value then key. - s.push_back(s[2]); // Copy the key's tag. + s.push_back(s[2]); // Copy the key's tag. key = 19; - s.push_back(key); // Second key is 19 instead of 0. - s[1] += 2; // Adjust encoded size. + s.push_back(key); // Second key is 19 instead of 0. + s[1] += 2; // Adjust encoded size. ASSERT_TRUE(map_message.ParseFromString(s)); ASSERT_EQ(1, map_message.map_field().size()); ASSERT_EQ(1, map_message.map_field().count(key)); @@ -2441,8 +2469,7 @@ TEST(GeneratedMapFieldTest, MessagesMustMerge) { TEST(GeneratedMapFieldReflectionTest, SpaceUsed) { unittest::TestMap message; - MapReflectionTester reflection_tester( - unittest::TestMap::descriptor()); + MapReflectionTester reflection_tester(unittest::TestMap::descriptor()); reflection_tester.SetMapFieldsViaReflection(&message); EXPECT_LT(0, message.GetReflection()->SpaceUsed(message)); @@ -2452,8 +2479,7 @@ TEST(GeneratedMapFieldReflectionTest, Accessors) { // Set every field to a unique value then go back and check all those // values. unittest::TestMap message; - MapReflectionTester reflection_tester( - unittest::TestMap::descriptor()); + MapReflectionTester reflection_tester(unittest::TestMap::descriptor()); reflection_tester.SetMapFieldsViaReflection(&message); MapTestUtil::ExpectMapFieldsSet(message); reflection_tester.ExpectMapFieldsSetViaReflection(message); @@ -2511,8 +2537,7 @@ TEST(GeneratedMapFieldReflectionTest, ClearField) { MapTestUtil::SetMapFields(&message); MapTestUtil::ExpectMapFieldsSet(message); - MapReflectionTester reflection_tester( - unittest::TestMap::descriptor()); + MapReflectionTester reflection_tester(unittest::TestMap::descriptor()); reflection_tester.ClearMapFieldsViaReflection(&message); reflection_tester.ExpectClearViaReflection(message); reflection_tester.ExpectClearViaReflectionIterator(&message); @@ -2520,8 +2545,7 @@ TEST(GeneratedMapFieldReflectionTest, ClearField) { TEST(GeneratedMapFieldReflectionTest, RemoveLast) { unittest::TestMap message; - MapReflectionTester reflection_tester( - unittest::TestMap::descriptor()); + MapReflectionTester reflection_tester(unittest::TestMap::descriptor()); MapTestUtil::SetMapFields(&message); MapTestUtil::ExpectMapsSize(message, 2); @@ -2568,8 +2592,7 @@ TEST(GeneratedMapFieldReflectionTest, ReleaseLast) { TEST(GeneratedMapFieldReflectionTest, SwapElements) { unittest::TestMap message; - MapReflectionTester reflection_tester( - unittest::TestMap::descriptor()); + MapReflectionTester reflection_tester(unittest::TestMap::descriptor()); MapTestUtil::SetMapFields(&message); @@ -2608,8 +2631,7 @@ TEST(GeneratedMapFieldReflectionTest, SwapElements) { TEST(GeneratedMapFieldReflectionTest, MutableUnknownFields) { unittest::TestMap message; - MapReflectionTester reflection_tester( - unittest::TestMap::descriptor()); + MapReflectionTester reflection_tester(unittest::TestMap::descriptor()); reflection_tester.MutableUnknownFieldsOfMapFieldsViaReflection(&message); } @@ -2664,8 +2686,7 @@ TEST(GeneratedMapFieldReflectionTest, MergeFromClearMapEntry) { TEST(GeneratedMapFieldReflectionTest, MapEntryClear) { unittest::TestMap message; - MapReflectionTester reflection_tester( - unittest::TestMap::descriptor()); + MapReflectionTester reflection_tester(unittest::TestMap::descriptor()); reflection_tester.MutableUnknownFieldsOfMapFieldsViaReflection(&message); } @@ -2686,8 +2707,7 @@ TEST(GeneratedMapFieldReflectionTest, Proto2MapEntryClear) { TEST(GeneratedMapFieldReflectionTest, SetViaMapReflection) { unittest::TestMap message; - MapReflectionTester reflection_tester( - unittest::TestMap::descriptor()); + MapReflectionTester reflection_tester(unittest::TestMap::descriptor()); reflection_tester.SetMapFieldsViaMapReflection(&message); reflection_tester.ExpectMapFieldsSetViaReflection(message); reflection_tester.ExpectMapFieldsSetViaReflectionIterator(&message); @@ -2707,8 +2727,7 @@ class MapFieldInDynamicMessageTest : public testing::Test { : pool_(DescriptorPool::generated_pool()), factory_(pool_) {} virtual void SetUp() { - map_descriptor_ = - pool_->FindMessageTypeByName("protobuf_unittest.TestMap"); + map_descriptor_ = pool_->FindMessageTypeByName("protobuf_unittest.TestMap"); recursive_map_descriptor_ = pool_->FindMessageTypeByName("protobuf_unittest.TestRecursiveMapMessage"); ASSERT_TRUE(map_descriptor_ != NULL); @@ -2756,7 +2775,7 @@ TEST_F(MapFieldInDynamicMessageTest, MapSpaceUsed) { TEST_F(MapFieldInDynamicMessageTest, RecursiveMap) { TestRecursiveMapMessage from; (*from.mutable_a())[""]; - string data = from.SerializeAsString(); + std::string data = from.SerializeAsString(); std::unique_ptr to( factory_.GetPrototype(recursive_map_descriptor_)->New()); ASSERT_TRUE(to->ParseFromString(data)); @@ -2779,7 +2798,7 @@ TEST_F(MapFieldInDynamicMessageTest, MapValueReferernceValidAfterSerialize) { // In previous implementation, calling SerializeToString will cause syncing // from map to repeated field, which will invalidate the submsg we previously // got. - string data; + std::string data; message->SerializeToString(&data); const Reflection* submsg_reflection = submsg->GetReflection(); @@ -2811,7 +2830,7 @@ TEST_F(MapFieldInDynamicMessageTest, MapEntryReferernceValidAfterSerialize) { // In previous implementation, calling SerializeToString will cause syncing // from repeated field to map, which will invalidate the map_entry we // previously got. - string data; + std::string data; message->SerializeToString(&data); const Reflection* submsg_reflection = submsg->GetReflection(); @@ -2876,15 +2895,15 @@ TEST(ReflectionOpsForMapFieldTest, MapDiscardUnknownFields) { MapTestUtil::SetMapFields(&message); // Set some unknown fields in message. - message.GetReflection()->MutableUnknownFields(&message)-> - AddVarint(123456, 654321); + message.GetReflection()->MutableUnknownFields(&message)->AddVarint(123456, + 654321); // Discard them. ReflectionOps::DiscardUnknownFields(&message); MapTestUtil::ExpectMapFieldsSet(message); - EXPECT_EQ(0, message.GetReflection()-> - GetUnknownFields(message).field_count()); + EXPECT_EQ(0, + message.GetReflection()->GetUnknownFields(message).field_count()); } TEST(ReflectionOpsForMapFieldTest, IsInitialized) { @@ -2905,7 +2924,7 @@ TEST(ReflectionOpsForMapFieldTest, IsInitialized) { TEST(WireFormatForMapFieldTest, ParseMap) { unittest::TestMap source, dest; - string data; + std::string data; // Serialize using the generated code. MapTestUtil::SetMapFields(&source); @@ -2932,8 +2951,8 @@ TEST(WireFormatForMapFieldTest, MapByteSize) { TEST(WireFormatForMapFieldTest, SerializeMap) { unittest::TestMap message; - string generated_data; - string dynamic_data; + std::string generated_data; + std::string dynamic_data; MapTestUtil::SetMapFields(&message); @@ -2966,8 +2985,7 @@ TEST(WireFormatForMapFieldTest, SerializeMapDynamicMessage) { std::unique_ptr dynamic_message; dynamic_message.reset( factory.GetPrototype(unittest::TestMap::descriptor())->New()); - MapReflectionTester reflection_tester( - unittest::TestMap::descriptor()); + MapReflectionTester reflection_tester(unittest::TestMap::descriptor()); reflection_tester.SetMapFieldsViaReflection(dynamic_message.get()); reflection_tester.ExpectMapFieldsSetViaReflection(*dynamic_message); @@ -2975,8 +2993,8 @@ TEST(WireFormatForMapFieldTest, SerializeMapDynamicMessage) { MapTestUtil::SetMapFields(&generated_message); MapTestUtil::ExpectMapFieldsSet(generated_message); - string generated_data; - string dynamic_data; + std::string generated_data; + std::string dynamic_data; // Serialize. generated_message.SerializeToString(&generated_data); @@ -2989,7 +3007,7 @@ TEST(WireFormatForMapFieldTest, SerializeMapDynamicMessage) { } TEST(WireFormatForMapFieldTest, MapParseHelpers) { - string data; + std::string data; { // Set up. @@ -3016,7 +3034,7 @@ TEST(WireFormatForMapFieldTest, MapParseHelpers) { { // Test ParseFromBoundedZeroCopyStream. - string data_with_junk(data); + std::string data_with_junk(data); data_with_junk.append("some junk on the end"); io::ArrayInputStream stream(data_with_junk.data(), data_with_junk.size()); protobuf_unittest::TestMap message; @@ -3030,18 +3048,18 @@ TEST(WireFormatForMapFieldTest, MapParseHelpers) { io::ArrayInputStream stream(data.data(), data.size()); protobuf_unittest::TestAllTypes message; EXPECT_FALSE( - message.ParseFromBoundedZeroCopyStream(&stream, data.size() + 1)); + message.ParseFromBoundedZeroCopyStream(&stream, data.size() + 1)); } } // Deterministic Serialization Test ========================================== template -static string DeterministicSerializationWithSerializePartialToCodedStream( +static std::string DeterministicSerializationWithSerializePartialToCodedStream( const T& t) { const int size = t.ByteSize(); - string result(size, '\0'); - io::ArrayOutputStream array_stream(string_as_array(&result), size); + std::string result(size, '\0'); + io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&result), size); io::CodedOutputStream output_stream(&array_stream); output_stream.SetSerializationDeterministic(true); t.SerializePartialToCodedStream(&output_stream); @@ -3051,10 +3069,11 @@ static string DeterministicSerializationWithSerializePartialToCodedStream( } template -static string DeterministicSerializationWithSerializeToCodedStream(const T& t) { +static std::string DeterministicSerializationWithSerializeToCodedStream( + const T& t) { const int size = t.ByteSize(); - string result(size, '\0'); - io::ArrayOutputStream array_stream(string_as_array(&result), size); + std::string result(size, '\0'); + io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&result), size); io::CodedOutputStream output_stream(&array_stream); output_stream.SetSerializationDeterministic(true); t.SerializeToCodedStream(&output_stream); @@ -3064,10 +3083,10 @@ static string DeterministicSerializationWithSerializeToCodedStream(const T& t) { } template -static string DeterministicSerialization(const T& t) { +static std::string DeterministicSerialization(const T& t) { const int size = t.ByteSize(); - string result(size, '\0'); - io::ArrayOutputStream array_stream(string_as_array(&result), size); + std::string result(size, '\0'); + io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&result), size); io::CodedOutputStream output_stream(&array_stream); output_stream.SetSerializationDeterministic(true); t.SerializeWithCachedSizes(&output_stream); @@ -3081,21 +3100,21 @@ static string DeterministicSerialization(const T& t) { // Helper to test the serialization of the first arg against a golden file. static void TestDeterministicSerialization(const protobuf_unittest::TestMaps& t, - const string& filename) { - string expected; + const std::string& filename) { + std::string expected; GOOGLE_CHECK_OK(File::GetContents( - TestSourceDir() + "/google/protobuf/testdata/" + filename, + TestUtil::GetTestDataPath("net/proto2/internal/testdata/" + filename), &expected, true)); - const string actual = DeterministicSerialization(t); + const std::string actual = DeterministicSerialization(t); EXPECT_EQ(expected, actual); protobuf_unittest::TestMaps u; EXPECT_TRUE(u.ParseFromString(actual)); - EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals(u, t)); + EXPECT_TRUE(util::MessageDifferencer::Equals(u, t)); } // Helper for MapSerializationTest. Return a 7-bit ASCII string. -static string ConstructKey(uint64 n) { - string s(n % static_cast(9), '\0'); +static std::string ConstructKey(uint64 n) { + std::string s(n % static_cast(9), '\0'); if (s.empty()) { return StrCat(n); } else { @@ -3121,7 +3140,7 @@ TEST(MapSerializationTest, Deterministic) { const int64 i64 = static_cast(frog); const uint64 u64 = frog * static_cast(187321); const bool b = i32 > 0; - const string s = ConstructKey(frog); + const std::string s = ConstructKey(frog); (*inner.mutable_m())[i] = i32; (*t.mutable_m_int32())[i32] = (*t.mutable_m_sint32())[i32] = (*t.mutable_m_sfixed32())[i32] = inner; @@ -3131,8 +3150,8 @@ TEST(MapSerializationTest, Deterministic) { (*t.mutable_m_uint64())[u64] = (*t.mutable_m_fixed64())[u64] = inner; (*t.mutable_m_bool())[b] = inner; (*t.mutable_m_string())[s] = inner; - (*t.mutable_m_string())[s + string(1 << (u32 % static_cast(9)), - b)] = inner; + (*t.mutable_m_string())[s + std::string(1 << (u32 % static_cast(9)), + b)] = inner; inner.mutable_m()->erase(i); frog = frog * multiplier + i; frog ^= (frog >> 41); @@ -3143,14 +3162,14 @@ TEST(MapSerializationTest, Deterministic) { TEST(MapSerializationTest, DeterministicSubmessage) { protobuf_unittest::TestSubmessageMaps p; protobuf_unittest::TestMaps t; - const string filename = "golden_message_maps"; - string golden; + const std::string filename = "golden_message_maps"; + std::string golden; GOOGLE_CHECK_OK(File::GetContents( - TestSourceDir() + "/google/protobuf/testdata/" + filename, + TestUtil::GetTestDataPath("net/proto2/internal/testdata/" + filename), &golden, true)); t.ParseFromString(golden); *(p.mutable_m()) = t; - std::vector v; + std::vector v; // Use multiple attempts to increase the chance of a failure if something is // buggy. For example, each separate copy of a map might use a different // randomly-chosen hash function. @@ -3167,7 +3186,7 @@ TEST(TextFormatMapTest, SerializeAndParse) { unittest::TestMap source; unittest::TestMap dest; MapTestUtil::SetMapFields(&source); - string output; + std::string output; // Test compact ASCII TextFormat::Printer printer; @@ -3177,18 +3196,35 @@ TEST(TextFormatMapTest, SerializeAndParse) { MapTestUtil::ExpectMapFieldsSet(dest); } +TEST(TextFormatMapTest, DynamicMessage) { + TestMap prototype; + DynamicMessageFactory factory; + std::unique_ptr message( + factory.GetPrototype(prototype.GetDescriptor())->New()); + MapReflectionTester tester(message->GetDescriptor()); + tester.SetMapFieldsViaReflection(message.get()); + + std::string expected_text; + GOOGLE_CHECK_OK( + File::GetContents(TestUtil::GetTestDataPath("net/proto2/internal/" + "testdata/map_test_data.txt"), + &expected_text, true)); + + EXPECT_EQ(message->DebugString(), expected_text); +} + TEST(TextFormatMapTest, Sorted) { unittest::TestMap message; MapReflectionTester tester(message.GetDescriptor()); tester.SetMapFieldsViaReflection(&message); - string expected_text; - GOOGLE_CHECK_OK(File::GetContents( - TestSourceDir() + - "/google/protobuf/" - "testdata/map_test_data.txt", - &expected_text, true)); + std::string expected_text; + GOOGLE_CHECK_OK( + File::GetContents(TestUtil::GetTestDataPath("net/proto2/internal/" + "testdata/map_test_data.txt"), + &expected_text, true)); + CleanStringLineEndings(&expected_text, false); EXPECT_EQ(message.DebugString(), expected_text); // Test again on the reverse order. @@ -3199,17 +3235,88 @@ TEST(TextFormatMapTest, Sorted) { } TEST(TextFormatMapTest, ParseCorruptedString) { - string serialized_message; - GOOGLE_CHECK_OK(File::GetContents( - TestSourceDir() + - "/google/protobuf/testdata/golden_message_maps", - &serialized_message, true)); + std::string serialized_message; + GOOGLE_CHECK_OK( + File::GetContents(TestUtil::GetTestDataPath( + "net/proto2/internal/testdata/golden_message_maps"), + &serialized_message, true)); protobuf_unittest::TestMaps message; GOOGLE_CHECK(message.ParseFromString(serialized_message)); TestParseCorruptedString(message); TestParseCorruptedString(message); } +// Previously, serializing to text format will disable iterator from generated +// API. Now, the iterator can be still used even after serializing to text +// format. +TEST(TextFormatMapTest, NoDisableIterator) { + unittest::TestMap source; + (*source.mutable_map_int32_int32())[1] = 1; + + // Get iterator. + Map::iterator iter = source.mutable_map_int32_int32()->find(1); + + // Serialize message to text format, which will invalidate the previous + // iterator previously. + std::string output; + TextFormat::Printer printer; + printer.PrintToString(source, &output); + + // Modify map via the iterator (invalidated in prvious implementation.). + iter->second = 2; + + // In previous implementation, the new change won't be reflected in text + // format, because the previous iterator has been invalidated. + output.clear(); + printer.PrintToString(source, &output); + std::string expected = + "map_int32_int32 {\n" + " key: 1\n" + " value: 2\n" + "}\n"; + EXPECT_EQ(output, expected); +} + +// Previously, serializing to text format will disable iterator from reflection +// API. +TEST(TextFormatMapTest, NoDisableReflectionIterator) { + unittest::TestMap source; + (*source.mutable_map_int32_int32())[1] = 1; + + // Get iterator. This will also sync internal repeated field with map inside + // of MapField. + const Reflection* reflection = source.GetReflection(); + const FieldDescriptor* field_desc = + source.GetDescriptor()->FindFieldByName("map_int32_int32"); + RepeatedPtrField* map_field = + reflection->MutableRepeatedPtrField(&source, field_desc); + RepeatedPtrField::iterator iter = map_field->begin(); + + // Serialize message to text format, which will invalidate the prvious + // iterator previously. + std::string output; + TextFormat::Printer printer; + printer.PrintToString(source, &output); + + // Modify map via the iterator (invalidated in prvious implementation.). + const Reflection* map_entry_reflection = iter->GetReflection(); + const FieldDescriptor* value_field_desc = + iter->GetDescriptor()->FindFieldByName("value"); + map_entry_reflection->SetInt32(&(*iter), value_field_desc, 2); + GOOGLE_LOG(INFO) << iter->DebugString(); + + // In previous implementation, the new change won't be reflected in text + // format, because the previous iterator has been invalidated. + output.clear(); + printer.PrintToString(source, &output); + std::string expected = + "map_int32_int32 {\n" + " key: 1\n" + " value: 2\n" + "}\n"; + EXPECT_EQ(output, expected); +} + // arena support ================================================= TEST(ArenaTest, ParsingAndSerializingNoHeapAllocation) { @@ -3219,7 +3326,7 @@ TEST(ArenaTest, ParsingAndSerializingNoHeapAllocation) { options.initial_block = &arena_block[0]; options.initial_block_size = arena_block.size(); Arena arena(options); - string data; + std::string data; data.reserve(128 * 1024); { @@ -3241,7 +3348,7 @@ TEST(ArenaTest, ParsingAndSerializingNoHeapAllocation) { // Use text format parsing and serializing to test reflection api. TEST(ArenaTest, ReflectionInTextFormat) { Arena arena; - string data; + std::string data; TextFormat::Printer printer; TextFormat::Parser parser; @@ -3263,7 +3370,7 @@ TEST(ArenaTest, StringMapNoLeak) { Arena arena; unittest::TestArenaMap* message = Arena::CreateMessage(&arena); - string data; + std::string data; // String with length less than 16 will not be allocated from heap. int original_capacity = data.capacity(); while (data.capacity() <= original_capacity) { diff --git a/third_party/protobuf/src/google/protobuf/map_test_util.cc b/third_party/protobuf/src/google/protobuf/map_test_util.cc index 31ac1736..51c73664 100644 --- a/third_party/protobuf/src/google/protobuf/map_test_util.cc +++ b/third_party/protobuf/src/google/protobuf/map_test_util.cc @@ -78,49 +78,59 @@ void MapTestUtil::ExpectMapFieldsSetInitialized( message); } -void MapTestUtil::ExpectMapFieldsModified( - const unittest::TestMap& message) { +void MapTestUtil::ExpectMapFieldsModified(const unittest::TestMap& message) { MapTestUtilImpl::ExpectMapFieldsModified< unittest::MapEnum, unittest::MAP_ENUM_BAR, unittest::MAP_ENUM_FOO>( message); } -void MapTestUtil::ExpectMapsSize( - const unittest::TestMap& message, int size) { +void MapTestUtil::ExpectMapsSize(const unittest::TestMap& message, int size) { const Descriptor* descriptor = message.GetDescriptor(); EXPECT_EQ(size, message.GetReflection()->FieldSize( - message, descriptor->FindFieldByName("map_int32_int32"))); + message, descriptor->FindFieldByName("map_int32_int32"))); EXPECT_EQ(size, message.GetReflection()->FieldSize( - message, descriptor->FindFieldByName("map_int64_int64"))); + message, descriptor->FindFieldByName("map_int64_int64"))); + EXPECT_EQ(size, + message.GetReflection()->FieldSize( + message, descriptor->FindFieldByName("map_uint32_uint32"))); + EXPECT_EQ(size, + message.GetReflection()->FieldSize( + message, descriptor->FindFieldByName("map_uint64_uint64"))); + EXPECT_EQ(size, + message.GetReflection()->FieldSize( + message, descriptor->FindFieldByName("map_sint32_sint32"))); + EXPECT_EQ(size, + message.GetReflection()->FieldSize( + message, descriptor->FindFieldByName("map_sint64_sint64"))); + EXPECT_EQ(size, + message.GetReflection()->FieldSize( + message, descriptor->FindFieldByName("map_fixed32_fixed32"))); + EXPECT_EQ(size, + message.GetReflection()->FieldSize( + message, descriptor->FindFieldByName("map_fixed64_fixed64"))); + EXPECT_EQ(size, + message.GetReflection()->FieldSize( + message, descriptor->FindFieldByName("map_sfixed32_sfixed32"))); + EXPECT_EQ(size, + message.GetReflection()->FieldSize( + message, descriptor->FindFieldByName("map_sfixed64_sfixed64"))); EXPECT_EQ(size, message.GetReflection()->FieldSize( - message, descriptor->FindFieldByName("map_uint32_uint32"))); + message, descriptor->FindFieldByName("map_int32_float"))); + EXPECT_EQ(size, + message.GetReflection()->FieldSize( + message, descriptor->FindFieldByName("map_int32_double"))); EXPECT_EQ(size, message.GetReflection()->FieldSize( - message, descriptor->FindFieldByName("map_uint64_uint64"))); + message, descriptor->FindFieldByName("map_bool_bool"))); + EXPECT_EQ(size, + message.GetReflection()->FieldSize( + message, descriptor->FindFieldByName("map_string_string"))); EXPECT_EQ(size, message.GetReflection()->FieldSize( - message, descriptor->FindFieldByName("map_sint32_sint32"))); - EXPECT_EQ(size, message.GetReflection()->FieldSize( - message, descriptor->FindFieldByName("map_sint64_sint64"))); - EXPECT_EQ(size, message.GetReflection()->FieldSize( - message, descriptor->FindFieldByName("map_fixed32_fixed32"))); - EXPECT_EQ(size, message.GetReflection()->FieldSize( - message, descriptor->FindFieldByName("map_fixed64_fixed64"))); - EXPECT_EQ(size, message.GetReflection()->FieldSize( - message, descriptor->FindFieldByName("map_sfixed32_sfixed32"))); - EXPECT_EQ(size, message.GetReflection()->FieldSize( - message, descriptor->FindFieldByName("map_sfixed64_sfixed64"))); - EXPECT_EQ(size, message.GetReflection()->FieldSize( - message, descriptor->FindFieldByName("map_int32_float"))); - EXPECT_EQ(size, message.GetReflection()->FieldSize( - message, descriptor->FindFieldByName("map_int32_double"))); - EXPECT_EQ(size, message.GetReflection()->FieldSize( - message, descriptor->FindFieldByName("map_bool_bool"))); - EXPECT_EQ(size, message.GetReflection()->FieldSize( - message, descriptor->FindFieldByName("map_string_string"))); - EXPECT_EQ(size, message.GetReflection()->FieldSize( - message, descriptor->FindFieldByName("map_int32_bytes"))); - EXPECT_EQ(size, message.GetReflection()->FieldSize( - message, descriptor->FindFieldByName("map_int32_foreign_message"))); + message, descriptor->FindFieldByName("map_int32_bytes"))); + EXPECT_EQ( + size, + message.GetReflection()->FieldSize( + message, descriptor->FindFieldByName("map_int32_foreign_message"))); } std::vector MapTestUtil::GetMapEntries( @@ -129,39 +139,40 @@ std::vector MapTestUtil::GetMapEntries( std::vector result; result.push_back(&message.GetReflection()->GetRepeatedMessage( - message, descriptor->FindFieldByName("map_int32_int32"), index)); + message, descriptor->FindFieldByName("map_int32_int32"), index)); result.push_back(&message.GetReflection()->GetRepeatedMessage( - message, descriptor->FindFieldByName("map_int64_int64"), index)); + message, descriptor->FindFieldByName("map_int64_int64"), index)); result.push_back(&message.GetReflection()->GetRepeatedMessage( - message, descriptor->FindFieldByName("map_uint32_uint32"), index)); + message, descriptor->FindFieldByName("map_uint32_uint32"), index)); result.push_back(&message.GetReflection()->GetRepeatedMessage( - message, descriptor->FindFieldByName("map_uint64_uint64"), index)); + message, descriptor->FindFieldByName("map_uint64_uint64"), index)); result.push_back(&message.GetReflection()->GetRepeatedMessage( - message, descriptor->FindFieldByName("map_sint32_sint32"), index)); + message, descriptor->FindFieldByName("map_sint32_sint32"), index)); result.push_back(&message.GetReflection()->GetRepeatedMessage( - message, descriptor->FindFieldByName("map_sint64_sint64"), index)); + message, descriptor->FindFieldByName("map_sint64_sint64"), index)); result.push_back(&message.GetReflection()->GetRepeatedMessage( - message, descriptor->FindFieldByName("map_fixed32_fixed32"), index)); + message, descriptor->FindFieldByName("map_fixed32_fixed32"), index)); result.push_back(&message.GetReflection()->GetRepeatedMessage( - message, descriptor->FindFieldByName("map_fixed64_fixed64"), index)); + message, descriptor->FindFieldByName("map_fixed64_fixed64"), index)); result.push_back(&message.GetReflection()->GetRepeatedMessage( - message, descriptor->FindFieldByName("map_sfixed32_sfixed32"), index)); + message, descriptor->FindFieldByName("map_sfixed32_sfixed32"), index)); result.push_back(&message.GetReflection()->GetRepeatedMessage( - message, descriptor->FindFieldByName("map_sfixed64_sfixed64"), index)); + message, descriptor->FindFieldByName("map_sfixed64_sfixed64"), index)); result.push_back(&message.GetReflection()->GetRepeatedMessage( - message, descriptor->FindFieldByName("map_int32_float"), index)); + message, descriptor->FindFieldByName("map_int32_float"), index)); result.push_back(&message.GetReflection()->GetRepeatedMessage( - message, descriptor->FindFieldByName("map_int32_double"), index)); + message, descriptor->FindFieldByName("map_int32_double"), index)); result.push_back(&message.GetReflection()->GetRepeatedMessage( - message, descriptor->FindFieldByName("map_bool_bool"), index)); + message, descriptor->FindFieldByName("map_bool_bool"), index)); result.push_back(&message.GetReflection()->GetRepeatedMessage( - message, descriptor->FindFieldByName("map_string_string"), index)); + message, descriptor->FindFieldByName("map_string_string"), index)); result.push_back(&message.GetReflection()->GetRepeatedMessage( - message, descriptor->FindFieldByName("map_int32_bytes"), index)); + message, descriptor->FindFieldByName("map_int32_bytes"), index)); result.push_back(&message.GetReflection()->GetRepeatedMessage( - message, descriptor->FindFieldByName("map_int32_enum"), index)); + message, descriptor->FindFieldByName("map_int32_enum"), index)); result.push_back(&message.GetReflection()->GetRepeatedMessage( - message, descriptor->FindFieldByName("map_int32_foreign_message"), index)); + message, descriptor->FindFieldByName("map_int32_foreign_message"), + index)); return result; } @@ -172,76 +183,74 @@ std::vector MapTestUtil::GetMapEntriesFromRelease( std::vector result; result.push_back(message->GetReflection()->ReleaseLast( - message, descriptor->FindFieldByName("map_int32_int32"))); + message, descriptor->FindFieldByName("map_int32_int32"))); result.push_back(message->GetReflection()->ReleaseLast( - message, descriptor->FindFieldByName("map_int64_int64"))); + message, descriptor->FindFieldByName("map_int64_int64"))); result.push_back(message->GetReflection()->ReleaseLast( - message, descriptor->FindFieldByName("map_uint32_uint32"))); + message, descriptor->FindFieldByName("map_uint32_uint32"))); result.push_back(message->GetReflection()->ReleaseLast( - message, descriptor->FindFieldByName("map_uint64_uint64"))); + message, descriptor->FindFieldByName("map_uint64_uint64"))); result.push_back(message->GetReflection()->ReleaseLast( - message, descriptor->FindFieldByName("map_sint32_sint32"))); + message, descriptor->FindFieldByName("map_sint32_sint32"))); result.push_back(message->GetReflection()->ReleaseLast( - message, descriptor->FindFieldByName("map_sint64_sint64"))); + message, descriptor->FindFieldByName("map_sint64_sint64"))); result.push_back(message->GetReflection()->ReleaseLast( - message, descriptor->FindFieldByName("map_fixed32_fixed32"))); + message, descriptor->FindFieldByName("map_fixed32_fixed32"))); result.push_back(message->GetReflection()->ReleaseLast( - message, descriptor->FindFieldByName("map_fixed64_fixed64"))); + message, descriptor->FindFieldByName("map_fixed64_fixed64"))); result.push_back(message->GetReflection()->ReleaseLast( - message, descriptor->FindFieldByName("map_sfixed32_sfixed32"))); + message, descriptor->FindFieldByName("map_sfixed32_sfixed32"))); result.push_back(message->GetReflection()->ReleaseLast( - message, descriptor->FindFieldByName("map_sfixed64_sfixed64"))); + message, descriptor->FindFieldByName("map_sfixed64_sfixed64"))); result.push_back(message->GetReflection()->ReleaseLast( - message, descriptor->FindFieldByName("map_int32_float"))); + message, descriptor->FindFieldByName("map_int32_float"))); result.push_back(message->GetReflection()->ReleaseLast( - message, descriptor->FindFieldByName("map_int32_double"))); + message, descriptor->FindFieldByName("map_int32_double"))); result.push_back(message->GetReflection()->ReleaseLast( - message, descriptor->FindFieldByName("map_bool_bool"))); + message, descriptor->FindFieldByName("map_bool_bool"))); result.push_back(message->GetReflection()->ReleaseLast( - message, descriptor->FindFieldByName("map_string_string"))); + message, descriptor->FindFieldByName("map_string_string"))); result.push_back(message->GetReflection()->ReleaseLast( - message, descriptor->FindFieldByName("map_int32_bytes"))); + message, descriptor->FindFieldByName("map_int32_bytes"))); result.push_back(message->GetReflection()->ReleaseLast( - message, descriptor->FindFieldByName("map_int32_enum"))); + message, descriptor->FindFieldByName("map_int32_enum"))); result.push_back(message->GetReflection()->ReleaseLast( - message, descriptor->FindFieldByName("map_int32_foreign_message"))); + message, descriptor->FindFieldByName("map_int32_foreign_message"))); return result; } -MapReflectionTester::MapReflectionTester( - const Descriptor* base_descriptor) - : base_descriptor_(base_descriptor) { +MapReflectionTester::MapReflectionTester(const Descriptor* base_descriptor) + : base_descriptor_(base_descriptor) { const DescriptorPool* pool = base_descriptor->file()->pool(); map_enum_foo_ = pool->FindEnumValueByName("protobuf_unittest.MAP_ENUM_FOO"); map_enum_bar_ = pool->FindEnumValueByName("protobuf_unittest.MAP_ENUM_BAR"); map_enum_baz_ = pool->FindEnumValueByName("protobuf_unittest.MAP_ENUM_BAZ"); - foreign_c_ = pool->FindFieldByName( - "protobuf_unittest.ForeignMessage.c"); - map_int32_int32_key_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapInt32Int32Entry.key"); - map_int32_int32_val_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapInt32Int32Entry.value"); - map_int64_int64_key_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapInt64Int64Entry.key"); - map_int64_int64_val_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapInt64Int64Entry.value"); - map_uint32_uint32_key_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapUint32Uint32Entry.key"); + foreign_c_ = pool->FindFieldByName("protobuf_unittest.ForeignMessage.c"); + map_int32_int32_key_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapInt32Int32Entry.key"); + map_int32_int32_val_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapInt32Int32Entry.value"); + map_int64_int64_key_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapInt64Int64Entry.key"); + map_int64_int64_val_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapInt64Int64Entry.value"); + map_uint32_uint32_key_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapUint32Uint32Entry.key"); map_uint32_uint32_val_ = pool->FindFieldByName( "protobuf_unittest.TestMap.MapUint32Uint32Entry.value"); - map_uint64_uint64_key_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapUint64Uint64Entry.key"); + map_uint64_uint64_key_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapUint64Uint64Entry.key"); map_uint64_uint64_val_ = pool->FindFieldByName( "protobuf_unittest.TestMap.MapUint64Uint64Entry.value"); - map_sint32_sint32_key_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapSint32Sint32Entry.key"); + map_sint32_sint32_key_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapSint32Sint32Entry.key"); map_sint32_sint32_val_ = pool->FindFieldByName( "protobuf_unittest.TestMap.MapSint32Sint32Entry.value"); - map_sint64_sint64_key_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapSint64Sint64Entry.key"); + map_sint64_sint64_key_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapSint64Sint64Entry.key"); map_sint64_sint64_val_ = pool->FindFieldByName( "protobuf_unittest.TestMap.MapSint64Sint64Entry.value"); map_fixed32_fixed32_key_ = pool->FindFieldByName( @@ -260,30 +269,30 @@ MapReflectionTester::MapReflectionTester( "protobuf_unittest.TestMap.MapSfixed64Sfixed64Entry.key"); map_sfixed64_sfixed64_val_ = pool->FindFieldByName( "protobuf_unittest.TestMap.MapSfixed64Sfixed64Entry.value"); - map_int32_float_key_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapInt32FloatEntry.key"); - map_int32_float_val_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapInt32FloatEntry.value"); - map_int32_double_key_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapInt32DoubleEntry.key"); + map_int32_float_key_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapInt32FloatEntry.key"); + map_int32_float_val_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapInt32FloatEntry.value"); + map_int32_double_key_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapInt32DoubleEntry.key"); map_int32_double_val_ = pool->FindFieldByName( "protobuf_unittest.TestMap.MapInt32DoubleEntry.value"); - map_bool_bool_key_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapBoolBoolEntry.key"); - map_bool_bool_val_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapBoolBoolEntry.value"); - map_string_string_key_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapStringStringEntry.key"); + map_bool_bool_key_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapBoolBoolEntry.key"); + map_bool_bool_val_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapBoolBoolEntry.value"); + map_string_string_key_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapStringStringEntry.key"); map_string_string_val_ = pool->FindFieldByName( "protobuf_unittest.TestMap.MapStringStringEntry.value"); - map_int32_bytes_key_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapInt32BytesEntry.key"); - map_int32_bytes_val_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapInt32BytesEntry.value"); - map_int32_enum_key_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapInt32EnumEntry.key"); - map_int32_enum_val_ = pool->FindFieldByName( - "protobuf_unittest.TestMap.MapInt32EnumEntry.value"); + map_int32_bytes_key_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapInt32BytesEntry.key"); + map_int32_bytes_val_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapInt32BytesEntry.value"); + map_int32_enum_key_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapInt32EnumEntry.key"); + map_int32_enum_val_ = + pool->FindFieldByName("protobuf_unittest.TestMap.MapInt32EnumEntry.value"); map_int32_foreign_message_key_ = pool->FindFieldByName( "protobuf_unittest.TestMap.MapInt32ForeignMessageEntry.key"); map_int32_foreign_message_val_ = pool->FindFieldByName( @@ -329,234 +338,210 @@ MapReflectionTester::MapReflectionTester( } // Shorthand to get a FieldDescriptor for a field of unittest::TestMap. -const FieldDescriptor* MapReflectionTester::F(const string& name) { +const FieldDescriptor* MapReflectionTester::F(const std::string& name) { const FieldDescriptor* result = NULL; result = base_descriptor_->FindFieldByName(name); GOOGLE_CHECK(result != NULL); return result; } -void MapReflectionTester::SetMapFieldsViaReflection( - Message* message) { +void MapReflectionTester::SetMapFieldsViaReflection(Message* message) { const Reflection* reflection = message->GetReflection(); Message* sub_message = NULL; Message* sub_foreign_message = NULL; // Add first element. sub_message = reflection->AddMessage(message, F("map_int32_int32")); - sub_message->GetReflection() - ->SetInt32(sub_message, map_int32_int32_key_, 0); - sub_message->GetReflection() - ->SetInt32(sub_message, map_int32_int32_val_, 0); + sub_message->GetReflection()->SetInt32(sub_message, map_int32_int32_key_, 0); + sub_message->GetReflection()->SetInt32(sub_message, map_int32_int32_val_, 0); sub_message = reflection->AddMessage(message, F("map_int64_int64")); - sub_message->GetReflection() - ->SetInt64(sub_message, map_int64_int64_key_, 0); - sub_message->GetReflection() - ->SetInt64(sub_message, map_int64_int64_val_, 0); + sub_message->GetReflection()->SetInt64(sub_message, map_int64_int64_key_, 0); + sub_message->GetReflection()->SetInt64(sub_message, map_int64_int64_val_, 0); sub_message = reflection->AddMessage(message, F("map_uint32_uint32")); - sub_message->GetReflection() - ->SetUInt32(sub_message, map_uint32_uint32_key_, 0); - sub_message->GetReflection() - ->SetUInt32(sub_message, map_uint32_uint32_val_, 0); + sub_message->GetReflection()->SetUInt32(sub_message, map_uint32_uint32_key_, + 0); + sub_message->GetReflection()->SetUInt32(sub_message, map_uint32_uint32_val_, + 0); sub_message = reflection->AddMessage(message, F("map_uint64_uint64")); - sub_message->GetReflection() - ->SetUInt64(sub_message, map_uint64_uint64_key_, 0); - sub_message->GetReflection() - ->SetUInt64(sub_message, map_uint64_uint64_val_, 0); + sub_message->GetReflection()->SetUInt64(sub_message, map_uint64_uint64_key_, + 0); + sub_message->GetReflection()->SetUInt64(sub_message, map_uint64_uint64_val_, + 0); sub_message = reflection->AddMessage(message, F("map_sint32_sint32")); - sub_message->GetReflection() - ->SetInt32(sub_message, map_sint32_sint32_key_, 0); - sub_message->GetReflection() - ->SetInt32(sub_message, map_sint32_sint32_val_, 0); + sub_message->GetReflection()->SetInt32(sub_message, map_sint32_sint32_key_, + 0); + sub_message->GetReflection()->SetInt32(sub_message, map_sint32_sint32_val_, + 0); sub_message = reflection->AddMessage(message, F("map_sint64_sint64")); - sub_message->GetReflection() - ->SetInt64(sub_message, map_sint64_sint64_key_, 0); - sub_message->GetReflection() - ->SetInt64(sub_message, map_sint64_sint64_val_, 0); + sub_message->GetReflection()->SetInt64(sub_message, map_sint64_sint64_key_, + 0); + sub_message->GetReflection()->SetInt64(sub_message, map_sint64_sint64_val_, + 0); sub_message = reflection->AddMessage(message, F("map_fixed32_fixed32")); - sub_message->GetReflection() - ->SetUInt32(sub_message, map_fixed32_fixed32_key_, 0); - sub_message->GetReflection() - ->SetUInt32(sub_message, map_fixed32_fixed32_val_, 0); + sub_message->GetReflection()->SetUInt32(sub_message, map_fixed32_fixed32_key_, + 0); + sub_message->GetReflection()->SetUInt32(sub_message, map_fixed32_fixed32_val_, + 0); sub_message = reflection->AddMessage(message, F("map_fixed64_fixed64")); - sub_message->GetReflection() - ->SetUInt64(sub_message, map_fixed64_fixed64_key_, 0); - sub_message->GetReflection() - ->SetUInt64(sub_message, map_fixed64_fixed64_val_, 0); + sub_message->GetReflection()->SetUInt64(sub_message, map_fixed64_fixed64_key_, + 0); + sub_message->GetReflection()->SetUInt64(sub_message, map_fixed64_fixed64_val_, + 0); sub_message = reflection->AddMessage(message, F("map_sfixed32_sfixed32")); - sub_message->GetReflection() - ->SetInt32(sub_message, map_sfixed32_sfixed32_key_, 0); - sub_message->GetReflection() - ->SetInt32(sub_message, map_sfixed32_sfixed32_val_, 0); + sub_message->GetReflection()->SetInt32(sub_message, + map_sfixed32_sfixed32_key_, 0); + sub_message->GetReflection()->SetInt32(sub_message, + map_sfixed32_sfixed32_val_, 0); sub_message = reflection->AddMessage(message, F("map_sfixed64_sfixed64")); - sub_message->GetReflection() - ->SetInt64(sub_message, map_sfixed64_sfixed64_key_, 0); - sub_message->GetReflection() - ->SetInt64(sub_message, map_sfixed64_sfixed64_val_, 0); + sub_message->GetReflection()->SetInt64(sub_message, + map_sfixed64_sfixed64_key_, 0); + sub_message->GetReflection()->SetInt64(sub_message, + map_sfixed64_sfixed64_val_, 0); sub_message = reflection->AddMessage(message, F("map_int32_float")); - sub_message->GetReflection() - ->SetInt32(sub_message, map_int32_float_key_, 0); - sub_message->GetReflection() - ->SetFloat(sub_message, map_int32_float_val_, 0.0); + sub_message->GetReflection()->SetInt32(sub_message, map_int32_float_key_, 0); + sub_message->GetReflection()->SetFloat(sub_message, map_int32_float_val_, + 0.0); sub_message = reflection->AddMessage(message, F("map_int32_double")); - sub_message->GetReflection() - ->SetInt32(sub_message, map_int32_double_key_, 0); - sub_message->GetReflection() - ->SetDouble(sub_message, map_int32_double_val_, 0.0); + sub_message->GetReflection()->SetInt32(sub_message, map_int32_double_key_, 0); + sub_message->GetReflection()->SetDouble(sub_message, map_int32_double_val_, + 0.0); sub_message = reflection->AddMessage(message, F("map_bool_bool")); - sub_message->GetReflection() - ->SetBool(sub_message, map_bool_bool_key_, false); - sub_message->GetReflection() - ->SetBool(sub_message, map_bool_bool_val_, false); + sub_message->GetReflection()->SetBool(sub_message, map_bool_bool_key_, false); + sub_message->GetReflection()->SetBool(sub_message, map_bool_bool_val_, false); sub_message = reflection->AddMessage(message, F("map_string_string")); - sub_message->GetReflection() - ->SetString(sub_message, map_string_string_key_, "0"); - sub_message->GetReflection() - ->SetString(sub_message, map_string_string_val_, "0"); + sub_message->GetReflection()->SetString(sub_message, map_string_string_key_, + "0"); + sub_message->GetReflection()->SetString(sub_message, map_string_string_val_, + "0"); sub_message = reflection->AddMessage(message, F("map_int32_bytes")); - sub_message->GetReflection() - ->SetInt32(sub_message, map_int32_bytes_key_, 0); - sub_message->GetReflection() - ->SetString(sub_message, map_int32_bytes_val_, "0"); + sub_message->GetReflection()->SetInt32(sub_message, map_int32_bytes_key_, 0); + sub_message->GetReflection()->SetString(sub_message, map_int32_bytes_val_, + "0"); sub_message = reflection->AddMessage(message, F("map_int32_enum")); - sub_message->GetReflection() - ->SetInt32(sub_message, map_int32_enum_key_, 0); - sub_message->GetReflection() - ->SetEnum(sub_message, map_int32_enum_val_, map_enum_bar_); + sub_message->GetReflection()->SetInt32(sub_message, map_int32_enum_key_, 0); + sub_message->GetReflection()->SetEnum(sub_message, map_int32_enum_val_, + map_enum_bar_); - sub_message = reflection - ->AddMessage(message, F("map_int32_foreign_message")); - sub_message->GetReflection() - ->SetInt32(sub_message, map_int32_foreign_message_key_, 0); - sub_foreign_message = sub_message->GetReflection()-> - MutableMessage(sub_message, map_int32_foreign_message_val_, NULL); - sub_foreign_message->GetReflection()-> - SetInt32(sub_foreign_message, foreign_c_, 0); + sub_message = reflection->AddMessage(message, F("map_int32_foreign_message")); + sub_message->GetReflection()->SetInt32(sub_message, + map_int32_foreign_message_key_, 0); + sub_foreign_message = sub_message->GetReflection()->MutableMessage( + sub_message, map_int32_foreign_message_val_, NULL); + sub_foreign_message->GetReflection()->SetInt32(sub_foreign_message, + foreign_c_, 0); // Add second element sub_message = reflection->AddMessage(message, F("map_int32_int32")); - sub_message->GetReflection() - ->SetInt32(sub_message, map_int32_int32_key_, 1); - sub_message->GetReflection() - ->SetInt32(sub_message, map_int32_int32_val_, 1); + sub_message->GetReflection()->SetInt32(sub_message, map_int32_int32_key_, 1); + sub_message->GetReflection()->SetInt32(sub_message, map_int32_int32_val_, 1); sub_message = reflection->AddMessage(message, F("map_int64_int64")); - sub_message->GetReflection() - ->SetInt64(sub_message, map_int64_int64_key_, 1); - sub_message->GetReflection() - ->SetInt64(sub_message, map_int64_int64_val_, 1); + sub_message->GetReflection()->SetInt64(sub_message, map_int64_int64_key_, 1); + sub_message->GetReflection()->SetInt64(sub_message, map_int64_int64_val_, 1); sub_message = reflection->AddMessage(message, F("map_uint32_uint32")); - sub_message->GetReflection() - ->SetUInt32(sub_message, map_uint32_uint32_key_, 1); - sub_message->GetReflection() - ->SetUInt32(sub_message, map_uint32_uint32_val_, 1); + sub_message->GetReflection()->SetUInt32(sub_message, map_uint32_uint32_key_, + 1); + sub_message->GetReflection()->SetUInt32(sub_message, map_uint32_uint32_val_, + 1); sub_message = reflection->AddMessage(message, F("map_uint64_uint64")); - sub_message->GetReflection() - ->SetUInt64(sub_message, map_uint64_uint64_key_, 1); - sub_message->GetReflection() - ->SetUInt64(sub_message, map_uint64_uint64_val_, 1); + sub_message->GetReflection()->SetUInt64(sub_message, map_uint64_uint64_key_, + 1); + sub_message->GetReflection()->SetUInt64(sub_message, map_uint64_uint64_val_, + 1); sub_message = reflection->AddMessage(message, F("map_sint32_sint32")); - sub_message->GetReflection() - ->SetInt32(sub_message, map_sint32_sint32_key_, 1); - sub_message->GetReflection() - ->SetInt32(sub_message, map_sint32_sint32_val_, 1); + sub_message->GetReflection()->SetInt32(sub_message, map_sint32_sint32_key_, + 1); + sub_message->GetReflection()->SetInt32(sub_message, map_sint32_sint32_val_, + 1); sub_message = reflection->AddMessage(message, F("map_sint64_sint64")); - sub_message->GetReflection() - ->SetInt64(sub_message, map_sint64_sint64_key_, 1); - sub_message->GetReflection() - ->SetInt64(sub_message, map_sint64_sint64_val_, 1); + sub_message->GetReflection()->SetInt64(sub_message, map_sint64_sint64_key_, + 1); + sub_message->GetReflection()->SetInt64(sub_message, map_sint64_sint64_val_, + 1); sub_message = reflection->AddMessage(message, F("map_fixed32_fixed32")); - sub_message->GetReflection() - ->SetUInt32(sub_message, map_fixed32_fixed32_key_, 1); - sub_message->GetReflection() - ->SetUInt32(sub_message, map_fixed32_fixed32_val_, 1); + sub_message->GetReflection()->SetUInt32(sub_message, map_fixed32_fixed32_key_, + 1); + sub_message->GetReflection()->SetUInt32(sub_message, map_fixed32_fixed32_val_, + 1); sub_message = reflection->AddMessage(message, F("map_fixed64_fixed64")); - sub_message->GetReflection() - ->SetUInt64(sub_message, map_fixed64_fixed64_key_, 1); - sub_message->GetReflection() - ->SetUInt64(sub_message, map_fixed64_fixed64_val_, 1); + sub_message->GetReflection()->SetUInt64(sub_message, map_fixed64_fixed64_key_, + 1); + sub_message->GetReflection()->SetUInt64(sub_message, map_fixed64_fixed64_val_, + 1); sub_message = reflection->AddMessage(message, F("map_sfixed32_sfixed32")); - sub_message->GetReflection() - ->SetInt32(sub_message, map_sfixed32_sfixed32_key_, 1); - sub_message->GetReflection() - ->SetInt32(sub_message, map_sfixed32_sfixed32_val_, 1); + sub_message->GetReflection()->SetInt32(sub_message, + map_sfixed32_sfixed32_key_, 1); + sub_message->GetReflection()->SetInt32(sub_message, + map_sfixed32_sfixed32_val_, 1); sub_message = reflection->AddMessage(message, F("map_sfixed64_sfixed64")); - sub_message->GetReflection() - ->SetInt64(sub_message, map_sfixed64_sfixed64_key_, 1); - sub_message->GetReflection() - ->SetInt64(sub_message, map_sfixed64_sfixed64_val_, 1); + sub_message->GetReflection()->SetInt64(sub_message, + map_sfixed64_sfixed64_key_, 1); + sub_message->GetReflection()->SetInt64(sub_message, + map_sfixed64_sfixed64_val_, 1); sub_message = reflection->AddMessage(message, F("map_int32_float")); - sub_message->GetReflection() - ->SetInt32(sub_message, map_int32_float_key_, 1); - sub_message->GetReflection() - ->SetFloat(sub_message, map_int32_float_val_, 1.0); + sub_message->GetReflection()->SetInt32(sub_message, map_int32_float_key_, 1); + sub_message->GetReflection()->SetFloat(sub_message, map_int32_float_val_, + 1.0); sub_message = reflection->AddMessage(message, F("map_int32_double")); - sub_message->GetReflection() - ->SetInt32(sub_message, map_int32_double_key_, 1); - sub_message->GetReflection() - ->SetDouble(sub_message, map_int32_double_val_, 1.0); + sub_message->GetReflection()->SetInt32(sub_message, map_int32_double_key_, 1); + sub_message->GetReflection()->SetDouble(sub_message, map_int32_double_val_, + 1.0); sub_message = reflection->AddMessage(message, F("map_bool_bool")); - sub_message->GetReflection() - ->SetBool(sub_message, map_bool_bool_key_, true); - sub_message->GetReflection() - ->SetBool(sub_message, map_bool_bool_val_, true); + sub_message->GetReflection()->SetBool(sub_message, map_bool_bool_key_, true); + sub_message->GetReflection()->SetBool(sub_message, map_bool_bool_val_, true); sub_message = reflection->AddMessage(message, F("map_string_string")); - sub_message->GetReflection() - ->SetString(sub_message, map_string_string_key_, "1"); - sub_message->GetReflection() - ->SetString(sub_message, map_string_string_val_, "1"); + sub_message->GetReflection()->SetString(sub_message, map_string_string_key_, + "1"); + sub_message->GetReflection()->SetString(sub_message, map_string_string_val_, + "1"); sub_message = reflection->AddMessage(message, F("map_int32_bytes")); - sub_message->GetReflection() - ->SetInt32(sub_message, map_int32_bytes_key_, 1); - sub_message->GetReflection() - ->SetString(sub_message, map_int32_bytes_val_, "1"); + sub_message->GetReflection()->SetInt32(sub_message, map_int32_bytes_key_, 1); + sub_message->GetReflection()->SetString(sub_message, map_int32_bytes_val_, + "1"); sub_message = reflection->AddMessage(message, F("map_int32_enum")); - sub_message->GetReflection() - ->SetInt32(sub_message, map_int32_enum_key_, 1); - sub_message->GetReflection() - ->SetEnum(sub_message, map_int32_enum_val_, map_enum_baz_); + sub_message->GetReflection()->SetInt32(sub_message, map_int32_enum_key_, 1); + sub_message->GetReflection()->SetEnum(sub_message, map_int32_enum_val_, + map_enum_baz_); - sub_message = reflection - ->AddMessage(message, F("map_int32_foreign_message")); - sub_message->GetReflection() - ->SetInt32(sub_message, map_int32_foreign_message_key_, 1); - sub_foreign_message = sub_message->GetReflection()-> - MutableMessage(sub_message, map_int32_foreign_message_val_, NULL); - sub_foreign_message->GetReflection()-> - SetInt32(sub_foreign_message, foreign_c_, 1); + sub_message = reflection->AddMessage(message, F("map_int32_foreign_message")); + sub_message->GetReflection()->SetInt32(sub_message, + map_int32_foreign_message_key_, 1); + sub_foreign_message = sub_message->GetReflection()->MutableMessage( + sub_message, map_int32_foreign_message_val_, NULL); + sub_foreign_message->GetReflection()->SetInt32(sub_foreign_message, + foreign_c_, 1); } -void MapReflectionTester::SetMapFieldsViaMapReflection( - Message* message) { +void MapReflectionTester::SetMapFieldsViaMapReflection(Message* message) { const Reflection* reflection = message->GetReflection(); Message* sub_foreign_message = NULL; @@ -565,13 +550,13 @@ void MapReflectionTester::SetMapFieldsViaMapReflection( // Add first element. MapKey map_key; map_key.SetInt32Value(0); - EXPECT_TRUE(reflection->InsertOrLookupMapValue( - message, F("map_int32_int32"), map_key, &map_val)); + EXPECT_TRUE(reflection->InsertOrLookupMapValue(message, F("map_int32_int32"), + map_key, &map_val)); map_val.SetInt32Value(0); map_key.SetInt64Value(0); - EXPECT_TRUE(reflection->InsertOrLookupMapValue( - message, F("map_int64_int64"), map_key, &map_val)); + EXPECT_TRUE(reflection->InsertOrLookupMapValue(message, F("map_int64_int64"), + map_key, &map_val)); map_val.SetInt64Value(0); map_key.SetUInt32Value(0); @@ -615,18 +600,18 @@ void MapReflectionTester::SetMapFieldsViaMapReflection( map_val.SetInt64Value(0); map_key.SetInt32Value(0); - EXPECT_TRUE(reflection->InsertOrLookupMapValue( - message, F("map_int32_float"), map_key, &map_val)); + EXPECT_TRUE(reflection->InsertOrLookupMapValue(message, F("map_int32_float"), + map_key, &map_val)); map_val.SetFloatValue(0.0); map_key.SetInt32Value(0); - EXPECT_TRUE(reflection->InsertOrLookupMapValue( - message, F("map_int32_double"), map_key, &map_val)); + EXPECT_TRUE(reflection->InsertOrLookupMapValue(message, F("map_int32_double"), + map_key, &map_val)); map_val.SetDoubleValue(0.0); map_key.SetBoolValue(false); - EXPECT_TRUE(reflection->InsertOrLookupMapValue( - message, F("map_bool_bool"), map_key, &map_val)); + EXPECT_TRUE(reflection->InsertOrLookupMapValue(message, F("map_bool_bool"), + map_key, &map_val)); map_val.SetBoolValue(false); map_key.SetStringValue("0"); @@ -635,145 +620,142 @@ void MapReflectionTester::SetMapFieldsViaMapReflection( map_val.SetStringValue("0"); map_key.SetInt32Value(0); - EXPECT_TRUE(reflection->InsertOrLookupMapValue( - message, F("map_int32_bytes"), map_key, &map_val)); + EXPECT_TRUE(reflection->InsertOrLookupMapValue(message, F("map_int32_bytes"), + map_key, &map_val)); map_val.SetStringValue("0"); map_key.SetInt32Value(0); - EXPECT_TRUE(reflection->InsertOrLookupMapValue( - message, F("map_int32_enum"), map_key, &map_val)); + EXPECT_TRUE(reflection->InsertOrLookupMapValue(message, F("map_int32_enum"), + map_key, &map_val)); map_val.SetEnumValue(map_enum_bar_->number()); map_key.SetInt32Value(0); EXPECT_TRUE(reflection->InsertOrLookupMapValue( message, F("map_int32_foreign_message"), map_key, &map_val)); sub_foreign_message = map_val.MutableMessageValue(); - sub_foreign_message->GetReflection()->SetInt32( - sub_foreign_message, foreign_c_, 0); + sub_foreign_message->GetReflection()->SetInt32(sub_foreign_message, + foreign_c_, 0); // Add second element map_key.SetInt32Value(1); - EXPECT_TRUE(reflection->InsertOrLookupMapValue( - message, F("map_int32_int32"), map_key, &map_val)); + EXPECT_TRUE(reflection->InsertOrLookupMapValue(message, F("map_int32_int32"), + map_key, &map_val)); map_val.SetInt32Value(1); - EXPECT_FALSE(reflection->InsertOrLookupMapValue( - message, F("map_int32_int32"), map_key, &map_val)); + EXPECT_FALSE(reflection->InsertOrLookupMapValue(message, F("map_int32_int32"), + map_key, &map_val)); map_key.SetInt64Value(1); - EXPECT_TRUE(reflection->InsertOrLookupMapValue( - message, F("map_int64_int64"), map_key, &map_val)); + EXPECT_TRUE(reflection->InsertOrLookupMapValue(message, F("map_int64_int64"), + map_key, &map_val)); map_val.SetInt64Value(1); - EXPECT_FALSE(reflection->InsertOrLookupMapValue( - message, F("map_int64_int64"), map_key, &map_val)); + EXPECT_FALSE(reflection->InsertOrLookupMapValue(message, F("map_int64_int64"), + map_key, &map_val)); map_key.SetUInt32Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_uint32_uint32"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_uint32_uint32"), map_key, + &map_val); map_val.SetUInt32Value(1); map_key.SetUInt64Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_uint64_uint64"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_uint64_uint64"), map_key, + &map_val); map_val.SetUInt64Value(1); map_key.SetInt32Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_sint32_sint32"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_sint32_sint32"), map_key, + &map_val); map_val.SetInt32Value(1); map_key.SetInt64Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_sint64_sint64"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_sint64_sint64"), map_key, + &map_val); map_val.SetInt64Value(1); map_key.SetUInt32Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_fixed32_fixed32"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_fixed32_fixed32"), map_key, + &map_val); map_val.SetUInt32Value(1); map_key.SetUInt64Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_fixed64_fixed64"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_fixed64_fixed64"), map_key, + &map_val); map_val.SetUInt64Value(1); map_key.SetInt32Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_sfixed32_sfixed32"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_sfixed32_sfixed32"), + map_key, &map_val); map_val.SetInt32Value(1); map_key.SetInt64Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_sfixed64_sfixed64"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_sfixed64_sfixed64"), + map_key, &map_val); map_val.SetInt64Value(1); map_key.SetInt32Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_int32_float"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_int32_float"), map_key, + &map_val); map_val.SetFloatValue(1.0); map_key.SetInt32Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_int32_double"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_int32_double"), map_key, + &map_val); map_val.SetDoubleValue(1.0); map_key.SetBoolValue(true); - reflection->InsertOrLookupMapValue( - message, F("map_bool_bool"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_bool_bool"), map_key, + &map_val); map_val.SetBoolValue(true); map_key.SetStringValue("1"); - reflection->InsertOrLookupMapValue( - message, F("map_string_string"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_string_string"), map_key, + &map_val); map_val.SetStringValue("1"); map_key.SetInt32Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_int32_bytes"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_int32_bytes"), map_key, + &map_val); map_val.SetStringValue("1"); map_key.SetInt32Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_int32_enum"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_int32_enum"), map_key, + &map_val); map_val.SetEnumValue(map_enum_baz_->number()); map_key.SetInt32Value(1); EXPECT_TRUE(reflection->InsertOrLookupMapValue( message, F("map_int32_foreign_message"), map_key, &map_val)); sub_foreign_message = map_val.MutableMessageValue(); - sub_foreign_message->GetReflection()->SetInt32( - sub_foreign_message, foreign_c_, 1); + sub_foreign_message->GetReflection()->SetInt32(sub_foreign_message, + foreign_c_, 1); } -void MapReflectionTester::GetMapValueViaMapReflection(Message* message, - const string& field_name, - const MapKey& map_key, - MapValueRef* map_val) { +void MapReflectionTester::GetMapValueViaMapReflection( + Message* message, const std::string& field_name, const MapKey& map_key, + MapValueRef* map_val) { const Reflection* reflection = message->GetReflection(); EXPECT_FALSE(reflection->InsertOrLookupMapValue(message, F(field_name), map_key, map_val)); } -Message* MapReflectionTester::GetMapEntryViaReflection(Message* message, - const string& field_name, - int index) { +Message* MapReflectionTester::GetMapEntryViaReflection( + Message* message, const std::string& field_name, int index) { const Reflection* reflection = message->GetReflection(); return reflection->MutableRepeatedMessage(message, F(field_name), index); } MapIterator MapReflectionTester::MapBegin(Message* message, - const string& field_name) { + const std::string& field_name) { const Reflection* reflection = message->GetReflection(); return reflection->MapBegin(message, F(field_name)); } MapIterator MapReflectionTester::MapEnd(Message* message, - const string& field_name) { + const std::string& field_name) { const Reflection* reflection = message->GetReflection(); return reflection->MapEnd(message, F(field_name)); } -void MapReflectionTester::ClearMapFieldsViaReflection( - Message* message) { +void MapReflectionTester::ClearMapFieldsViaReflection(Message* message) { const Reflection* reflection = message->GetReflection(); reflection->ClearField(message, F("map_int32_int32")); @@ -795,8 +777,7 @@ void MapReflectionTester::ClearMapFieldsViaReflection( reflection->ClearField(message, F("map_int32_foreign_message")); } -void MapReflectionTester::ModifyMapFieldsViaReflection( - Message* message) { +void MapReflectionTester::ModifyMapFieldsViaReflection(Message* message) { const Reflection* reflection = message->GetReflection(); MapValueRef map_val; Message* sub_foreign_message; @@ -804,13 +785,13 @@ void MapReflectionTester::ModifyMapFieldsViaReflection( // Modify the second element MapKey map_key; map_key.SetInt32Value(1); - EXPECT_FALSE(reflection->InsertOrLookupMapValue( - message, F("map_int32_int32"), map_key, &map_val)); + EXPECT_FALSE(reflection->InsertOrLookupMapValue(message, F("map_int32_int32"), + map_key, &map_val)); map_val.SetInt32Value(2); map_key.SetInt64Value(1); - EXPECT_FALSE(reflection->InsertOrLookupMapValue( - message, F("map_int64_int64"), map_key, &map_val)); + EXPECT_FALSE(reflection->InsertOrLookupMapValue(message, F("map_int64_int64"), + map_key, &map_val)); map_val.SetInt64Value(2); map_key.SetUInt32Value(1); @@ -819,80 +800,79 @@ void MapReflectionTester::ModifyMapFieldsViaReflection( map_val.SetUInt32Value(2); map_key.SetUInt64Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_uint64_uint64"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_uint64_uint64"), map_key, + &map_val); map_val.SetUInt64Value(2); map_key.SetInt32Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_sint32_sint32"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_sint32_sint32"), map_key, + &map_val); map_val.SetInt32Value(2); map_key.SetInt64Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_sint64_sint64"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_sint64_sint64"), map_key, + &map_val); map_val.SetInt64Value(2); map_key.SetUInt32Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_fixed32_fixed32"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_fixed32_fixed32"), map_key, + &map_val); map_val.SetUInt32Value(2); map_key.SetUInt64Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_fixed64_fixed64"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_fixed64_fixed64"), map_key, + &map_val); map_val.SetUInt64Value(2); map_key.SetInt32Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_sfixed32_sfixed32"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_sfixed32_sfixed32"), + map_key, &map_val); map_val.SetInt32Value(2); map_key.SetInt64Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_sfixed64_sfixed64"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_sfixed64_sfixed64"), + map_key, &map_val); map_val.SetInt64Value(2); map_key.SetInt32Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_int32_float"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_int32_float"), map_key, + &map_val); map_val.SetFloatValue(2.0); map_key.SetInt32Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_int32_double"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_int32_double"), map_key, + &map_val); map_val.SetDoubleValue(2.0); map_key.SetBoolValue(true); - reflection->InsertOrLookupMapValue( - message, F("map_bool_bool"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_bool_bool"), map_key, + &map_val); map_val.SetBoolValue(false); map_key.SetStringValue("1"); - reflection->InsertOrLookupMapValue( - message, F("map_string_string"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_string_string"), map_key, + &map_val); map_val.SetStringValue("2"); map_key.SetInt32Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_int32_bytes"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_int32_bytes"), map_key, + &map_val); map_val.SetStringValue("2"); map_key.SetInt32Value(1); - reflection->InsertOrLookupMapValue( - message, F("map_int32_enum"), map_key, &map_val); + reflection->InsertOrLookupMapValue(message, F("map_int32_enum"), map_key, + &map_val); map_val.SetEnumValue(map_enum_foo_->number()); map_key.SetInt32Value(1); EXPECT_FALSE(reflection->InsertOrLookupMapValue( message, F("map_int32_foreign_message"), map_key, &map_val)); sub_foreign_message = map_val.MutableMessageValue(); - sub_foreign_message->GetReflection()->SetInt32( - sub_foreign_message, foreign_c_, 2); + sub_foreign_message->GetReflection()->SetInt32(sub_foreign_message, + foreign_c_, 2); } -void MapReflectionTester::RemoveLastMapsViaReflection( - Message* message) { +void MapReflectionTester::RemoveLastMapsViaReflection(Message* message) { const Reflection* reflection = message->GetReflection(); std::vector output; @@ -904,8 +884,7 @@ void MapReflectionTester::RemoveLastMapsViaReflection( } } -void MapReflectionTester::ReleaseLastMapsViaReflection( - Message* message) { +void MapReflectionTester::ReleaseLastMapsViaReflection(Message* message) { const Reflection* reflection = message->GetReflection(); std::vector output; @@ -916,8 +895,8 @@ void MapReflectionTester::ReleaseLastMapsViaReflection( if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) continue; Message* released = reflection->ReleaseLast(message, field); - ASSERT_TRUE(released != NULL) << "ReleaseLast returned NULL for: " - << field->name(); + ASSERT_TRUE(released != NULL) + << "ReleaseLast returned NULL for: " << field->name(); delete released; } } @@ -933,8 +912,8 @@ void MapReflectionTester::SwapMapsViaReflection(Message* message) { } } -void MapReflectionTester:: - MutableUnknownFieldsOfMapFieldsViaReflection(Message* message) { +void MapReflectionTester::MutableUnknownFieldsOfMapFieldsViaReflection( + Message* message) { const Reflection* reflection = message->GetReflection(); Message* sub_message = NULL; @@ -993,7 +972,7 @@ void MapReflectionTester:: void MapReflectionTester::ExpectMapFieldsSetViaReflection( const Message& message) { - string scratch; + std::string scratch; const Reflection* reflection = message.GetReflection(); const Message* sub_message; MapKey map_key; @@ -1026,15 +1005,15 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflection( // Check with RepeatedField Reflection sub_message = &reflection->GetRepeatedMessage(message, F("map_int32_int32"), i); - int32 key = sub_message->GetReflection()->GetInt32( - *sub_message, map_int32_int32_key_); - int32 val = sub_message->GetReflection()->GetInt32( - *sub_message, map_int32_int32_val_); + int32 key = sub_message->GetReflection()->GetInt32(*sub_message, + map_int32_int32_key_); + int32 val = sub_message->GetReflection()->GetInt32(*sub_message, + map_int32_int32_val_); EXPECT_EQ(map[key], val); // Check with Map Reflection map_key.SetInt32Value(key); - EXPECT_TRUE(reflection->ContainsMapKey( - message, F("map_int32_int32"), map_key)); + EXPECT_TRUE( + reflection->ContainsMapKey(message, F("map_int32_int32"), map_key)); } } { @@ -1045,15 +1024,15 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflection( // Check with RepeatedField Reflection sub_message = &reflection->GetRepeatedMessage(message, F("map_int64_int64"), i); - int64 key = sub_message->GetReflection()->GetInt64( - *sub_message, map_int64_int64_key_); - int64 val = sub_message->GetReflection()->GetInt64( - *sub_message, map_int64_int64_val_); + int64 key = sub_message->GetReflection()->GetInt64(*sub_message, + map_int64_int64_key_); + int64 val = sub_message->GetReflection()->GetInt64(*sub_message, + map_int64_int64_val_); EXPECT_EQ(map[key], val); // Check with Map Reflection map_key.SetInt64Value(key); - EXPECT_TRUE(reflection->ContainsMapKey( - message, F("map_int64_int64"), map_key)); + EXPECT_TRUE( + reflection->ContainsMapKey(message, F("map_int64_int64"), map_key)); } } { @@ -1071,8 +1050,8 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflection( EXPECT_EQ(map[key], val); // Check with Map Reflection map_key.SetUInt32Value(key); - EXPECT_TRUE(reflection->ContainsMapKey( - message, F("map_uint32_uint32"), map_key)); + EXPECT_TRUE( + reflection->ContainsMapKey(message, F("map_uint32_uint32"), map_key)); } } { @@ -1089,8 +1068,8 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflection( EXPECT_EQ(map[key], val); // Check with Map Reflection map_key.SetUInt64Value(key); - EXPECT_TRUE(reflection->ContainsMapKey( - message, F("map_uint64_uint64"), map_key)); + EXPECT_TRUE( + reflection->ContainsMapKey(message, F("map_uint64_uint64"), map_key)); } } { @@ -1108,7 +1087,7 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflection( // Check with Map Reflection map_key.SetInt32Value(key); EXPECT_EQ(true, reflection->ContainsMapKey( - message, F("map_sint32_sint32"), map_key)); + message, F("map_sint32_sint32"), map_key)); } } { @@ -1126,7 +1105,7 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflection( // Check with Map Reflection map_key.SetInt64Value(key); EXPECT_EQ(true, reflection->ContainsMapKey( - message, F("map_sint64_sint64"), map_key)); + message, F("map_sint64_sint64"), map_key)); } } { @@ -1144,7 +1123,7 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflection( // Check with Map Reflection map_key.SetUInt32Value(key); EXPECT_EQ(true, reflection->ContainsMapKey( - message, F("map_fixed32_fixed32"), map_key)); + message, F("map_fixed32_fixed32"), map_key)); } } { @@ -1162,7 +1141,7 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflection( // Check with Map Reflection map_key.SetUInt64Value(key); EXPECT_EQ(true, reflection->ContainsMapKey( - message, F("map_fixed64_fixed64"), map_key)); + message, F("map_fixed64_fixed64"), map_key)); } } { @@ -1180,7 +1159,7 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflection( // Check with Map Reflection map_key.SetInt32Value(key); EXPECT_EQ(true, reflection->ContainsMapKey( - message, F("map_sfixed32_sfixed32"), map_key)); + message, F("map_sfixed32_sfixed32"), map_key)); } } { @@ -1198,7 +1177,7 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflection( // Check with Map Reflection map_key.SetInt64Value(key); EXPECT_EQ(true, reflection->ContainsMapKey( - message, F("map_sfixed64_sfixed64"), map_key)); + message, F("map_sfixed64_sfixed64"), map_key)); } } { @@ -1208,15 +1187,15 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflection( for (int i = 0; i < 2; i++) { sub_message = &reflection->GetRepeatedMessage(message, F("map_int32_float"), i); - int32 key = sub_message->GetReflection()->GetInt32( - *sub_message, map_int32_float_key_); - float val = sub_message->GetReflection()->GetFloat( - *sub_message, map_int32_float_val_); + int32 key = sub_message->GetReflection()->GetInt32(*sub_message, + map_int32_float_key_); + float val = sub_message->GetReflection()->GetFloat(*sub_message, + map_int32_float_val_); EXPECT_EQ(map[key], val); // Check with Map Reflection map_key.SetInt32Value(key); - EXPECT_EQ(true, reflection->ContainsMapKey( - message, F("map_int32_float"), map_key)); + EXPECT_EQ(true, reflection->ContainsMapKey(message, F("map_int32_float"), + map_key)); } } { @@ -1226,15 +1205,15 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflection( for (int i = 0; i < 2; i++) { sub_message = &reflection->GetRepeatedMessage(message, F("map_int32_double"), i); - int32 key = sub_message->GetReflection()->GetInt32( - *sub_message, map_int32_double_key_); + int32 key = sub_message->GetReflection()->GetInt32(*sub_message, + map_int32_double_key_); double val = sub_message->GetReflection()->GetDouble( *sub_message, map_int32_double_val_); EXPECT_EQ(map[key], val); // Check with Map Reflection map_key.SetInt32Value(key); - EXPECT_EQ(true, reflection->ContainsMapKey( - message, F("map_int32_double"), map_key)); + EXPECT_EQ(true, reflection->ContainsMapKey(message, F("map_int32_double"), + map_key)); } } { @@ -1244,51 +1223,51 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflection( for (int i = 0; i < 2; i++) { sub_message = &reflection->GetRepeatedMessage(message, F("map_bool_bool"), i); - bool key = sub_message->GetReflection()->GetBool( - *sub_message, map_bool_bool_key_); - bool val = sub_message->GetReflection()->GetBool( - *sub_message, map_bool_bool_val_); + bool key = sub_message->GetReflection()->GetBool(*sub_message, + map_bool_bool_key_); + bool val = sub_message->GetReflection()->GetBool(*sub_message, + map_bool_bool_val_); EXPECT_EQ(map[key], val); // Check with Map Reflection map_key.SetBoolValue(key); - EXPECT_EQ(true, reflection->ContainsMapKey( - message, F("map_bool_bool"), map_key)); + EXPECT_EQ(true, reflection->ContainsMapKey(message, F("map_bool_bool"), + map_key)); } } { - std::map map; + std::map map; map["0"] = "0"; map["1"] = "1"; for (int i = 0; i < 2; i++) { sub_message = &reflection->GetRepeatedMessage(message, F("map_string_string"), i); - string key = sub_message->GetReflection()->GetString( + std::string key = sub_message->GetReflection()->GetString( *sub_message, map_string_string_key_); - string val = sub_message->GetReflection()->GetString( + std::string val = sub_message->GetReflection()->GetString( *sub_message, map_string_string_val_); EXPECT_EQ(map[key], val); // Check with Map Reflection map_key.SetStringValue(key); EXPECT_EQ(true, reflection->ContainsMapKey( - message, F("map_string_string"), map_key)); + message, F("map_string_string"), map_key)); } } { - std::map map; + std::map map; map[0] = "0"; map[1] = "1"; for (int i = 0; i < 2; i++) { sub_message = &reflection->GetRepeatedMessage(message, F("map_int32_bytes"), i); - int32 key = sub_message->GetReflection()->GetInt32( - *sub_message, map_int32_bytes_key_); - string val = sub_message->GetReflection()->GetString( + int32 key = sub_message->GetReflection()->GetInt32(*sub_message, + map_int32_bytes_key_); + std::string val = sub_message->GetReflection()->GetString( *sub_message, map_int32_bytes_val_); EXPECT_EQ(map[key], val); // Check with Map Reflection map_key.SetInt32Value(key); - EXPECT_EQ(true, reflection->ContainsMapKey( - message, F("map_int32_bytes"), map_key)); + EXPECT_EQ(true, reflection->ContainsMapKey(message, F("map_int32_bytes"), + map_key)); } } { @@ -1296,17 +1275,17 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflection( map[0] = map_enum_bar_; map[1] = map_enum_baz_; for (int i = 0; i < 2; i++) { - sub_message = &reflection->GetRepeatedMessage( - message, F("map_int32_enum"), i); - int32 key = sub_message->GetReflection()->GetInt32( - *sub_message, map_int32_enum_key_); + sub_message = + &reflection->GetRepeatedMessage(message, F("map_int32_enum"), i); + int32 key = sub_message->GetReflection()->GetInt32(*sub_message, + map_int32_enum_key_); const EnumValueDescriptor* val = sub_message->GetReflection()->GetEnum( *sub_message, map_int32_enum_val_); EXPECT_EQ(map[key], val); // Check with Map Reflection map_key.SetInt32Value(key); - EXPECT_EQ(true, reflection->ContainsMapKey( - message, F("map_int32_enum"), map_key)); + EXPECT_EQ(true, reflection->ContainsMapKey(message, F("map_int32_enum"), + map_key)); } } { @@ -1316,25 +1295,25 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflection( for (int i = 0; i < 2; i++) { sub_message = &reflection->GetRepeatedMessage( message, F("map_int32_foreign_message"), i); - int32 key = sub_message->GetReflection()->GetInt32( + int32 key = sub_message->GetReflection()->GetInt32( *sub_message, map_int32_foreign_message_key_); const Message& foreign_message = sub_message->GetReflection()->GetMessage( *sub_message, map_int32_foreign_message_val_); - int32 val = foreign_message.GetReflection()->GetInt32( - foreign_message, foreign_c_); + int32 val = foreign_message.GetReflection()->GetInt32(foreign_message, + foreign_c_); EXPECT_EQ(map[key], val); // Check with Map Reflection map_key.SetInt32Value(key); EXPECT_EQ(true, reflection->ContainsMapKey( - message, F("map_int32_foreign_message"), map_key)); + message, F("map_int32_foreign_message"), map_key)); } } } void MapReflectionTester::ExpectMapFieldsSetViaReflectionIterator( Message* message) { - string scratch; - string serialized; + std::string scratch; + std::string serialized; const Reflection* reflection = message->GetReflection(); ASSERT_EQ(2, reflection->FieldSize(*message, F("map_int32_int32"))); @@ -1388,10 +1367,9 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflectionIterator( std::map map; map[0] = 0; map[1] = 1; - for (MapIterator iter = reflection->MapBegin( - message, F("map_uint32_uint32")); - iter != reflection->MapEnd(message, F("map_uint32_uint32")); - ++iter) { + for (MapIterator iter = + reflection->MapBegin(message, F("map_uint32_uint32")); + iter != reflection->MapEnd(message, F("map_uint32_uint32")); ++iter) { EXPECT_EQ(map[iter.GetKey().GetUInt32Value()], iter.GetValueRef().GetUInt32Value()); } @@ -1400,10 +1378,9 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflectionIterator( std::map map; map[0] = 0; map[1] = 1; - for (MapIterator iter = reflection->MapBegin( - message, F("map_uint64_uint64")); - iter != reflection->MapEnd(message, F("map_uint64_uint64")); - ++iter) { + for (MapIterator iter = + reflection->MapBegin(message, F("map_uint64_uint64")); + iter != reflection->MapEnd(message, F("map_uint64_uint64")); ++iter) { EXPECT_EQ(map[iter.GetKey().GetUInt64Value()], iter.GetValueRef().GetUInt64Value()); } @@ -1412,10 +1389,9 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflectionIterator( std::map map; map[0] = 0; map[1] = 1; - for (MapIterator iter = reflection->MapBegin( - message, F("map_sint32_sint32")); - iter != reflection->MapEnd(message, F("map_sint32_sint32")); - ++iter) { + for (MapIterator iter = + reflection->MapBegin(message, F("map_sint32_sint32")); + iter != reflection->MapEnd(message, F("map_sint32_sint32")); ++iter) { EXPECT_EQ(map[iter.GetKey().GetInt32Value()], iter.GetValueRef().GetInt32Value()); } @@ -1424,8 +1400,8 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflectionIterator( std::map map; map[0] = 0; map[1] = 1; - for (MapIterator iter = reflection->MapBegin( - message, F("map_sint64_sint64")); + for (MapIterator iter = + reflection->MapBegin(message, F("map_sint64_sint64")); iter != reflection->MapEnd(message, F("map_sint64_sint64")); ++iter) { EXPECT_EQ(map[iter.GetKey().GetInt64Value()], iter.GetValueRef().GetInt64Value()); @@ -1435,8 +1411,8 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflectionIterator( std::map map; map[0] = 0; map[1] = 1; - for (MapIterator iter = reflection->MapBegin( - message, F("map_fixed32_fixed32")); + for (MapIterator iter = + reflection->MapBegin(message, F("map_fixed32_fixed32")); iter != reflection->MapEnd(message, F("map_fixed32_fixed32")); ++iter) { EXPECT_EQ(map[iter.GetKey().GetUInt32Value()], @@ -1447,8 +1423,8 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflectionIterator( std::map map; map[0] = 0; map[1] = 1; - for (MapIterator iter = reflection->MapBegin( - message, F("map_fixed64_fixed64")); + for (MapIterator iter = + reflection->MapBegin(message, F("map_fixed64_fixed64")); iter != reflection->MapEnd(message, F("map_fixed64_fixed64")); ++iter) { EXPECT_EQ(map[iter.GetKey().GetUInt64Value()], @@ -1459,8 +1435,8 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflectionIterator( std::map map; map[0] = 0; map[1] = 1; - for (MapIterator iter = reflection->MapBegin( - message, F("map_sfixed32_sfixed32")); + for (MapIterator iter = + reflection->MapBegin(message, F("map_sfixed32_sfixed32")); iter != reflection->MapEnd(message, F("map_sfixed32_sfixed32")); ++iter) { EXPECT_EQ(map[iter.GetKey().GetInt32Value()], @@ -1481,8 +1457,8 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflectionIterator( std::map map; map[0] = 0.0; map[1] = 1.0; - for (MapIterator iter = reflection->MapBegin( - message, F("map_int32_double")); + for (MapIterator iter = + reflection->MapBegin(message, F("map_int32_double")); iter != reflection->MapEnd(message, F("map_int32_double")); ++iter) { EXPECT_EQ(map[iter.GetKey().GetInt32Value()], iter.GetValueRef().GetDoubleValue()); @@ -1499,12 +1475,12 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflectionIterator( } } { - std::map map; + std::map map; map["0"] = "0"; map["1"] = "1"; int size = 0; - for (MapIterator iter = reflection->MapBegin( - message, F("map_string_string")); + for (MapIterator iter = + reflection->MapBegin(message, F("map_string_string")); iter != reflection->MapEnd(message, F("map_string_string")); ++iter, ++size) { // Check const methods do not invalidate map. @@ -1519,7 +1495,7 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflectionIterator( EXPECT_EQ(size, 2); } { - std::map map; + std::map map; map[0] = "0"; map[1] = "1"; for (MapIterator iter = reflection->MapBegin(message, F("map_int32_bytes")); @@ -1543,8 +1519,8 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflectionIterator( map[0] = 0; map[1] = 1; int size = 0; - for (MapIterator iter = reflection->MapBegin( - message, F("map_int32_foreign_message")); + for (MapIterator iter = + reflection->MapBegin(message, F("map_int32_foreign_message")); iter != reflection->MapEnd(message, F("map_int32_foreign_message")); ++iter, ++size) { // Check const methods do not invalidate map. @@ -1561,8 +1537,7 @@ void MapReflectionTester::ExpectMapFieldsSetViaReflectionIterator( } } -void MapReflectionTester::ExpectClearViaReflection( - const Message& message) { +void MapReflectionTester::ExpectClearViaReflection(const Message& message) { const Reflection* reflection = message.GetReflection(); // Map fields are empty. EXPECT_EQ(0, reflection->FieldSize(message, F("map_int32_int32"))); @@ -1582,10 +1557,11 @@ void MapReflectionTester::ExpectClearViaReflection( EXPECT_EQ(0, reflection->FieldSize(message, F("map_int32_bytes"))); EXPECT_EQ(0, reflection->FieldSize(message, F("map_int32_enum"))); EXPECT_EQ(0, reflection->FieldSize(message, F("map_int32_foreign_message"))); + EXPECT_TRUE(reflection->GetMapData(message, F("map_int32_foreign_message")) + ->IsMapValid()); } -void MapReflectionTester::ExpectClearViaReflectionIterator( - Message* message) { +void MapReflectionTester::ExpectClearViaReflectionIterator(Message* message) { const Reflection* reflection = message->GetReflection(); EXPECT_TRUE(reflection->MapBegin(message, F("map_int32_int32")) == reflection->MapEnd(message, F("map_int32_int32"))); @@ -1623,8 +1599,7 @@ void MapReflectionTester::ExpectClearViaReflectionIterator( reflection->MapEnd(message, F("map_int32_foreign_message"))); } -void MapReflectionTester::ExpectMapEntryClearViaReflection( - Message* message) { +void MapReflectionTester::ExpectMapEntryClearViaReflection(Message* message) { const Reflection* reflection = message->GetReflection(); const Message* sub_message; @@ -1806,7 +1781,7 @@ void MapReflectionTester::ExpectMapEntryClearViaReflection( EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, key_descriptor)); EXPECT_EQ("", sub_message->GetReflection()->GetString(*sub_message, - value_descriptor)); + value_descriptor)); } { const FieldDescriptor* descriptor = F("map_int32_enum"); diff --git a/third_party/protobuf/src/google/protobuf/map_test_util.h b/third_party/protobuf/src/google/protobuf/map_test_util.h index dd397619..00d2fa4d 100644 --- a/third_party/protobuf/src/google/protobuf/map_test_util.h +++ b/third_party/protobuf/src/google/protobuf/map_test_util.h @@ -63,8 +63,7 @@ class MapTestUtil { // Check that all fields have the values that they should have after // SetMapFieldsInitialized() is called. - static void ExpectMapFieldsSetInitialized( - const unittest::TestMap& message); + static void ExpectMapFieldsSetInitialized(const unittest::TestMap& message); // Expect that the message is modified as would be expected from // ModifyMapFields(). @@ -107,15 +106,15 @@ class MapReflectionTester { void ExpectClearViaReflectionIterator(Message* message); void ExpectMapEntryClearViaReflection(Message* message); void GetMapValueViaMapReflection(Message* message, - const string& field_name, + const std::string& field_name, const MapKey& map_key, MapValueRef* map_val); - Message* GetMapEntryViaReflection(Message* message, const string& field_name, - int index); - MapIterator MapBegin(Message* message, const string& field_name); - MapIterator MapEnd(Message* message, const string& field_name); + Message* GetMapEntryViaReflection(Message* message, + const std::string& field_name, int index); + MapIterator MapBegin(Message* message, const std::string& field_name); + MapIterator MapEnd(Message* message, const std::string& field_name); private: - const FieldDescriptor* F(const string& name); + const FieldDescriptor* F(const std::string& name); const Descriptor* base_descriptor_; @@ -161,6 +160,6 @@ class MapReflectionTester { }; } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_MAP_TEST_UTIL_H__ diff --git a/third_party/protobuf/src/google/protobuf/map_test_util_impl.h b/third_party/protobuf/src/google/protobuf/map_test_util_impl.h index ad4d1a3d..70145b7e 100644 --- a/third_party/protobuf/src/google/protobuf/map_test_util_impl.h +++ b/third_party/protobuf/src/google/protobuf/map_test_util_impl.h @@ -36,9 +36,9 @@ #include -namespace google { -namespace protobuf_unittest {} // forward declaration +namespace protobuf_unittest {} // namespace protobuf_unittest +namespace google { namespace protobuf { namespace unittest = ::protobuf_unittest; @@ -46,13 +46,13 @@ namespace unittest = ::protobuf_unittest; class MapTestUtilImpl { public: // Set every field in the TestMap message to a unique value. - template + template static void SetMapFields(MapMessage* message); // Set every field in the TestArenaMap message to a unique value. - template + template static void SetArenaMapFields(MapMessage* message); // Set every field in the message to a default value. @@ -66,14 +66,14 @@ class MapTestUtilImpl { // Check that all fields have the values that they should have after // SetMapFields() is called. - template + template static void ExpectMapFieldsSet(const MapMessage& message); // Check that all fields have the values that they should have after // SetMapFields() is called for TestArenaMap. - template + template static void ExpectArenaMapFieldsSet(const MapMessage& message); // Check that all fields have the values that they should have after @@ -83,8 +83,8 @@ class MapTestUtilImpl { // Expect that the message is modified as would be expected from // ModifyMapFields(). - template + template static void ExpectMapFieldsModified(const MapMessage& message); // Check that all fields are empty. @@ -104,8 +104,8 @@ class MapTestUtilImpl { // MapMessage* message); }; -template +template void MapTestUtilImpl::SetMapFields(MapMessage* message) { // Add first element. (*message->mutable_map_int32_int32())[0] = 0; @@ -146,8 +146,8 @@ void MapTestUtilImpl::SetMapFields(MapMessage* message) { (*message->mutable_map_int32_foreign_message())[1].set_c(1); } -template +template void MapTestUtilImpl::SetArenaMapFields(MapMessage* message) { // Add first element. (*message->mutable_map_int32_int32())[0] = 0; @@ -255,10 +255,8 @@ void MapTestUtilImpl::ExpectClear(const MapMessage& message) { EXPECT_EQ(0, message.map_int32_foreign_message().size()); } - - -template +template void MapTestUtilImpl::ExpectMapFieldsSet(const MapMessage& message) { ASSERT_EQ(2, message.map_int32_int32().size()); ASSERT_EQ(2, message.map_int64_int64().size()); @@ -315,8 +313,8 @@ void MapTestUtilImpl::ExpectMapFieldsSet(const MapMessage& message) { EXPECT_EQ(1, message.map_int32_foreign_message().at(1).c()); } -template +template void MapTestUtilImpl::ExpectArenaMapFieldsSet(const MapMessage& message) { EXPECT_EQ(2, message.map_int32_int32().size()); EXPECT_EQ(2, message.map_int64_int64().size()); @@ -377,8 +375,7 @@ void MapTestUtilImpl::ExpectArenaMapFieldsSet(const MapMessage& message) { } template -void MapTestUtilImpl::ExpectMapFieldsSetInitialized( - const MapMessage& message) { +void MapTestUtilImpl::ExpectMapFieldsSetInitialized(const MapMessage& message) { EXPECT_EQ(1, message.map_int32_int32().size()); EXPECT_EQ(1, message.map_int64_int64().size()); EXPECT_EQ(1, message.map_uint32_uint32().size()); @@ -416,10 +413,9 @@ void MapTestUtilImpl::ExpectMapFieldsSetInitialized( EXPECT_EQ(0, message.map_int32_foreign_message().at(0).ByteSize()); } -template -void MapTestUtilImpl::ExpectMapFieldsModified( - const MapMessage& message) { +template +void MapTestUtilImpl::ExpectMapFieldsModified(const MapMessage& message) { // ModifyMapFields only sets the second element of each field. In addition to // verifying this, we also verify that the first element and size were *not* // modified. @@ -480,6 +476,6 @@ void MapTestUtilImpl::ExpectMapFieldsModified( } } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_MAP_TEST_UTIL_IMPL_H__ diff --git a/third_party/protobuf/src/google/protobuf/map_type_handler.h b/third_party/protobuf/src/google/protobuf/map_type_handler.h index 7f7b1e0e..7964a97a 100644 --- a/third_party/protobuf/src/google/protobuf/map_type_handler.h +++ b/third_party/protobuf/src/google/protobuf/map_type_handler.h @@ -31,8 +31,14 @@ #ifndef GOOGLE_PROTOBUF_TYPE_HANDLER_H__ #define GOOGLE_PROTOBUF_TYPE_HANDLER_H__ +#include +#include #include -#include +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif namespace google { namespace protobuf { @@ -40,15 +46,15 @@ namespace internal { // Used for compile time type selection. MapIf::type will be TrueType if Flag is // true and FalseType otherwise. -template +template struct MapIf; -template +template struct MapIf { typedef TrueType type; }; -template +template struct MapIf { typedef FalseType type; }; @@ -72,7 +78,8 @@ class MapValueInitializer { template class MapValueInitializer { public: - static inline void Initialize(Type& /* value */, int /* default_enum_value */) {} + static inline void Initialize(Type& /* value */, + int /* default_enum_value */) {} }; template @@ -113,23 +120,23 @@ class MapWireFieldTypeTraits {}; WireFormatLite::WIRETYPE_##WireFormatType; \ }; -TYPE_TRAITS(MESSAGE , Type, LENGTH_DELIMITED, true, false) -TYPE_TRAITS(STRING , ArenaStringPtr, LENGTH_DELIMITED, false, false) -TYPE_TRAITS(BYTES , ArenaStringPtr , LENGTH_DELIMITED, false, false) -TYPE_TRAITS(INT64 , int64 , VARINT , false, false) -TYPE_TRAITS(UINT64 , uint64 , VARINT , false, false) -TYPE_TRAITS(INT32 , int32 , VARINT , false, false) -TYPE_TRAITS(UINT32 , uint32 , VARINT , false, false) -TYPE_TRAITS(SINT64 , int64 , VARINT , false, false) -TYPE_TRAITS(SINT32 , int32 , VARINT , false, false) -TYPE_TRAITS(ENUM , int , VARINT , false, true ) -TYPE_TRAITS(DOUBLE , double , FIXED64, false, false) -TYPE_TRAITS(FLOAT , float , FIXED32, false, false) -TYPE_TRAITS(FIXED64 , uint64 , FIXED64, false, false) -TYPE_TRAITS(FIXED32 , uint32 , FIXED32, false, false) -TYPE_TRAITS(SFIXED64, int64 , FIXED64, false, false) -TYPE_TRAITS(SFIXED32, int32 , FIXED32, false, false) -TYPE_TRAITS(BOOL , bool , VARINT , false, false) +TYPE_TRAITS(MESSAGE, Type, LENGTH_DELIMITED, true, false) +TYPE_TRAITS(STRING, ArenaStringPtr, LENGTH_DELIMITED, false, false) +TYPE_TRAITS(BYTES, ArenaStringPtr, LENGTH_DELIMITED, false, false) +TYPE_TRAITS(INT64, int64, VARINT, false, false) +TYPE_TRAITS(UINT64, uint64, VARINT, false, false) +TYPE_TRAITS(INT32, int32, VARINT, false, false) +TYPE_TRAITS(UINT32, uint32, VARINT, false, false) +TYPE_TRAITS(SINT64, int64, VARINT, false, false) +TYPE_TRAITS(SINT32, int32, VARINT, false, false) +TYPE_TRAITS(ENUM, int, VARINT, false, true) +TYPE_TRAITS(DOUBLE, double, FIXED64, false, false) +TYPE_TRAITS(FLOAT, float, FIXED32, false, false) +TYPE_TRAITS(FIXED64, uint64, FIXED64, false, false) +TYPE_TRAITS(FIXED32, uint32, FIXED32, false, false) +TYPE_TRAITS(SFIXED64, int64, FIXED64, false, false) +TYPE_TRAITS(SFIXED32, int32, FIXED32, false, false) +TYPE_TRAITS(BOOL, bool, VARINT, false, false) #undef TYPE_TRAITS @@ -142,7 +149,8 @@ class MapTypeHandler { // Enum type cannot be used for MapTypeHandler::Read. Define a type which will // replace Enum with int. typedef typename MapWireFieldTypeTraits::MapEntryAccessorType MapEntryAccessorType; + Type>::MapEntryAccessorType + MapEntryAccessorType; // Internal stored type in MapEntryLite for given wire field type. typedef typename MapWireFieldTypeTraits::TypeOnMemory TypeOnMemory; @@ -161,11 +169,11 @@ class MapTypeHandler { static inline int GetCachedSize(const MapEntryAccessorType& value); static inline bool Read(io::CodedInputStream* input, MapEntryAccessorType* value); + static inline const char* Read(const char* ptr, ParseContext* ctx, + MapEntryAccessorType* value); + static inline void Write(int field, const MapEntryAccessorType& value, io::CodedOutputStream* output); - static inline uint8* InternalWriteToArray(int field, - const MapEntryAccessorType& value, - bool deterministic, uint8* target); static inline uint8* WriteToArray(int field, const MapEntryAccessorType& value, uint8* target); @@ -192,8 +200,8 @@ class MapTypeHandler { static inline void AssignDefaultValue(Type** value); // Return default instance if value is not initialized when calling const // reference accessor. - static inline const Type& DefaultIfNotInitialized( - const Type* value, const Type* default_value); + static inline const Type& DefaultIfNotInitialized(const Type* value, + const Type* default_value); // Check if all required fields have values set. static inline bool IsInitialized(Type* value); }; @@ -220,16 +228,13 @@ class MapTypeHandler { static inline int GetCachedSize(const MapEntryAccessorType& value); \ static inline bool Read(io::CodedInputStream* input, \ MapEntryAccessorType* value); \ + static inline const char* Read(const char* begin, ParseContext* ctx, \ + MapEntryAccessorType* value); \ static inline void Write(int field, const MapEntryAccessorType& value, \ io::CodedOutputStream* output); \ - static inline uint8* InternalWriteToArray( \ - int field, const MapEntryAccessorType& value, bool deterministic, \ - uint8* target); \ static inline uint8* WriteToArray(int field, \ const MapEntryAccessorType& value, \ - uint8* target) { \ - return InternalWriteToArray(field, value, false, target); \ - } \ + uint8* target); \ static inline const MapEntryAccessorType& GetExternalReference( \ const TypeOnMemory& value); \ static inline void DeleteNoArena(const TypeOnMemory& x); \ @@ -241,7 +246,7 @@ class MapTypeHandler { int default_enum); \ static inline size_t SpaceUsedInMapEntryLong(const TypeOnMemory& value); \ static inline size_t SpaceUsedInMapLong(const TypeOnMemory& value); \ - static inline size_t SpaceUsedInMapLong(const string& value); \ + static inline size_t SpaceUsedInMapLong(const std::string& value); \ static inline void AssignDefaultValue(TypeOnMemory* value); \ static inline const MapEntryAccessorType& DefaultIfNotInitialized( \ const TypeOnMemory& value, const TypeOnMemory& default_value); \ @@ -273,8 +278,7 @@ MAP_HANDLER(BOOL) #undef MAP_HANDLER template -inline size_t -MapTypeHandler::ByteSize( +inline size_t MapTypeHandler::ByteSize( const MapEntryAccessorType& value) { return WireFormatLite::MessageSizeNoVirtual(value); } @@ -287,14 +291,14 @@ MapTypeHandler::ByteSize( } GOOGLE_PROTOBUF_BYTE_SIZE(STRING, String) -GOOGLE_PROTOBUF_BYTE_SIZE(BYTES , Bytes) -GOOGLE_PROTOBUF_BYTE_SIZE(INT64 , Int64) +GOOGLE_PROTOBUF_BYTE_SIZE(BYTES, Bytes) +GOOGLE_PROTOBUF_BYTE_SIZE(INT64, Int64) GOOGLE_PROTOBUF_BYTE_SIZE(UINT64, UInt64) -GOOGLE_PROTOBUF_BYTE_SIZE(INT32 , Int32) +GOOGLE_PROTOBUF_BYTE_SIZE(INT32, Int32) GOOGLE_PROTOBUF_BYTE_SIZE(UINT32, UInt32) GOOGLE_PROTOBUF_BYTE_SIZE(SINT64, SInt64) GOOGLE_PROTOBUF_BYTE_SIZE(SINT32, SInt32) -GOOGLE_PROTOBUF_BYTE_SIZE(ENUM , Enum) +GOOGLE_PROTOBUF_BYTE_SIZE(ENUM, Enum) #undef GOOGLE_PROTOBUF_BYTE_SIZE @@ -305,23 +309,21 @@ GOOGLE_PROTOBUF_BYTE_SIZE(ENUM , Enum) return WireFormatLite::k##DeclaredType##Size; \ } -FIXED_BYTE_SIZE(DOUBLE , Double) -FIXED_BYTE_SIZE(FLOAT , Float) -FIXED_BYTE_SIZE(FIXED64 , Fixed64) -FIXED_BYTE_SIZE(FIXED32 , Fixed32) +FIXED_BYTE_SIZE(DOUBLE, Double) +FIXED_BYTE_SIZE(FLOAT, Float) +FIXED_BYTE_SIZE(FIXED64, Fixed64) +FIXED_BYTE_SIZE(FIXED32, Fixed32) FIXED_BYTE_SIZE(SFIXED64, SFixed64) FIXED_BYTE_SIZE(SFIXED32, SFixed32) -FIXED_BYTE_SIZE(BOOL , Bool) +FIXED_BYTE_SIZE(BOOL, Bool) #undef FIXED_BYTE_SIZE template -inline int -MapTypeHandler::GetCachedSize( +inline int MapTypeHandler::GetCachedSize( const MapEntryAccessorType& value) { - return static_cast( - WireFormatLite::LengthDelimitedSize( - static_cast(value.GetCachedSize()))); + return static_cast(WireFormatLite::LengthDelimitedSize( + static_cast(value.GetCachedSize()))); } #define GET_CACHED_SIZE(FieldType, DeclaredType) \ @@ -333,14 +335,14 @@ MapTypeHandler::GetCachedSize( } GET_CACHED_SIZE(STRING, String) -GET_CACHED_SIZE(BYTES , Bytes) -GET_CACHED_SIZE(INT64 , Int64) +GET_CACHED_SIZE(BYTES, Bytes) +GET_CACHED_SIZE(INT64, Int64) GET_CACHED_SIZE(UINT64, UInt64) -GET_CACHED_SIZE(INT32 , Int32) +GET_CACHED_SIZE(INT32, Int32) GET_CACHED_SIZE(UINT32, UInt32) GET_CACHED_SIZE(SINT64, SInt64) GET_CACHED_SIZE(SINT32, SInt32) -GET_CACHED_SIZE(ENUM , Enum) +GET_CACHED_SIZE(ENUM, Enum) #undef GET_CACHED_SIZE @@ -352,13 +354,13 @@ GET_CACHED_SIZE(ENUM , Enum) return WireFormatLite::k##DeclaredType##Size; \ } -GET_FIXED_CACHED_SIZE(DOUBLE , Double) -GET_FIXED_CACHED_SIZE(FLOAT , Float) -GET_FIXED_CACHED_SIZE(FIXED64 , Fixed64) -GET_FIXED_CACHED_SIZE(FIXED32 , Fixed32) +GET_FIXED_CACHED_SIZE(DOUBLE, Double) +GET_FIXED_CACHED_SIZE(FLOAT, Float) +GET_FIXED_CACHED_SIZE(FIXED64, Fixed64) +GET_FIXED_CACHED_SIZE(FIXED32, Fixed32) GET_FIXED_CACHED_SIZE(SFIXED64, SFixed64) GET_FIXED_CACHED_SIZE(SFIXED32, SFixed32) -GET_FIXED_CACHED_SIZE(BOOL , Bool) +GET_FIXED_CACHED_SIZE(BOOL, Bool) #undef GET_FIXED_CACHED_SIZE @@ -370,12 +372,9 @@ inline void MapTypeHandler::Write( } template -inline uint8* -MapTypeHandler::InternalWriteToArray( - int field, const MapEntryAccessorType& value, bool deterministic, - uint8* target) { - return WireFormatLite::InternalWriteMessageToArray(field, value, - deterministic, target); +inline uint8* MapTypeHandler::WriteToArray( + int field, const MapEntryAccessorType& value, uint8* target) { + return WireFormatLite::InternalWriteMessageToArray(field, value, target); } #define WRITE_METHOD(FieldType, DeclaredType) \ @@ -387,28 +386,27 @@ MapTypeHandler::InternalWriteToArray( } \ template \ inline uint8* \ - MapTypeHandler::InternalWriteToArray( \ - int field, const MapEntryAccessorType& value, bool, uint8* target) { \ + MapTypeHandler::WriteToArray( \ + int field, const MapEntryAccessorType& value, uint8* target) { \ return WireFormatLite::Write##DeclaredType##ToArray(field, value, target); \ } -WRITE_METHOD(STRING , String) -WRITE_METHOD(BYTES , Bytes) -WRITE_METHOD(INT64 , Int64) -WRITE_METHOD(UINT64 , UInt64) -WRITE_METHOD(INT32 , Int32) -WRITE_METHOD(UINT32 , UInt32) -WRITE_METHOD(SINT64 , SInt64) -WRITE_METHOD(SINT32 , SInt32) -WRITE_METHOD(ENUM , Enum) -WRITE_METHOD(DOUBLE , Double) -WRITE_METHOD(FLOAT , Float) -WRITE_METHOD(FIXED64 , Fixed64) -WRITE_METHOD(FIXED32 , Fixed32) +WRITE_METHOD(STRING, String) +WRITE_METHOD(BYTES, Bytes) +WRITE_METHOD(INT64, Int64) +WRITE_METHOD(UINT64, UInt64) +WRITE_METHOD(INT32, Int32) +WRITE_METHOD(UINT32, UInt32) +WRITE_METHOD(SINT64, SInt64) +WRITE_METHOD(SINT32, SInt32) +WRITE_METHOD(ENUM, Enum) +WRITE_METHOD(DOUBLE, Double) +WRITE_METHOD(FLOAT, Float) +WRITE_METHOD(FIXED64, Fixed64) +WRITE_METHOD(FIXED32, Fixed32) WRITE_METHOD(SFIXED64, SFixed64) WRITE_METHOD(SFIXED32, SFixed32) -WRITE_METHOD(BOOL , Bool) +WRITE_METHOD(BOOL, Bool) #undef WRITE_METHOD @@ -430,6 +428,96 @@ inline bool MapTypeHandler::Read( return WireFormatLite::ReadBytes(input, value); } +template +const char* MapTypeHandler::Read( + const char* ptr, ParseContext* ctx, MapEntryAccessorType* value) { + return ctx->ParseMessage(value, ptr); +} + +template +const char* MapTypeHandler::Read( + const char* ptr, ParseContext* ctx, MapEntryAccessorType* value) { + int size = ReadSize(&ptr); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + return ctx->ReadString(ptr, size, value); +} + +template +const char* MapTypeHandler::Read( + const char* ptr, ParseContext* ctx, MapEntryAccessorType* value) { + int size = ReadSize(&ptr); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + return ctx->ReadString(ptr, size, value); +} + +inline const char* ReadINT64(const char* ptr, int64* value) { + return ParseVarint64(ptr, reinterpret_cast(value)); +} +inline const char* ReadUINT64(const char* ptr, uint64* value) { + return ParseVarint64(ptr, value); +} +inline const char* ReadINT32(const char* ptr, int32* value) { + uint64 tmp; + auto res = ParseVarint64(ptr, &tmp); + *value = static_cast(tmp); + return res; +} +inline const char* ReadUINT32(const char* ptr, uint32* value) { + uint64 tmp; + auto res = ParseVarint64(ptr, &tmp); + *value = static_cast(tmp); + return res; +} +inline const char* ReadSINT64(const char* ptr, int64* value) { + uint64 tmp; + auto res = ParseVarint64(ptr, &tmp); + *value = WireFormatLite::ZigZagDecode64(tmp); + return res; +} +inline const char* ReadSINT32(const char* ptr, int32* value) { + uint64 tmp; + auto res = ParseVarint64(ptr, &tmp); + *value = WireFormatLite::ZigZagDecode32(static_cast(tmp)); + return res; +} +template +inline const char* ReadENUM(const char* ptr, E* value) { + uint64 tmp; + auto res = ParseVarint64(ptr, &tmp); + *value = static_cast(tmp); + return res; +} +inline const char* ReadBOOL(const char* ptr, bool* value) { + uint64 tmp; + auto res = ParseVarint64(ptr, &tmp); + *value = static_cast(tmp); + return res; +} + +template +inline const char* ReadUnaligned(const char* ptr, F* value) { + *value = UnalignedLoad(ptr); + return ptr + sizeof(F); +} +inline const char* ReadFLOAT(const char* ptr, float* value) { + return ReadUnaligned(ptr, value); +} +inline const char* ReadDOUBLE(const char* ptr, double* value) { + return ReadUnaligned(ptr, value); +} +inline const char* ReadFIXED64(const char* ptr, uint64* value) { + return ReadUnaligned(ptr, value); +} +inline const char* ReadFIXED32(const char* ptr, uint32* value) { + return ReadUnaligned(ptr, value); +} +inline const char* ReadSFIXED64(const char* ptr, int64* value) { + return ReadUnaligned(ptr, value); +} +inline const char* ReadSFIXED32(const char* ptr, int32* value) { + return ReadUnaligned(ptr, value); +} + #define READ_METHOD(FieldType) \ template \ inline bool MapTypeHandler::Read( \ @@ -437,6 +525,11 @@ inline bool MapTypeHandler::Read( return WireFormatLite::ReadPrimitive( \ input, value); \ + } \ + template \ + const char* MapTypeHandler::Read( \ + const char* begin, ParseContext* ctx, MapEntryAccessorType* value) { \ + return Read##FieldType(begin, value); \ } READ_METHOD(INT64) @@ -460,8 +553,8 @@ READ_METHOD(BOOL) template inline const Type& -MapTypeHandler::GetExternalReference(const Type* value) { +MapTypeHandler::GetExternalReference( + const Type* value) { return *value; } @@ -484,10 +577,8 @@ inline void MapTypeHandler::Clear( } template inline void -MapTypeHandler::ClearMaybeByDefaultEnum(Type** value, - Arena* /* arena */, - int /* default_enum_value */) { +MapTypeHandler::ClearMaybeByDefaultEnum( + Type** value, Arena* /* arena */, int /* default_enum_value */) { if (*value != NULL) (*value)->Clear(); } template @@ -504,14 +595,13 @@ void MapTypeHandler::DeleteNoArena( template inline void MapTypeHandler::AssignDefaultValue(Type** value) { + Type>::AssignDefaultValue(Type** value) { *value = const_cast(Type::internal_default_instance()); } template -inline void MapTypeHandler::Initialize(Type** x, - Arena* /* arena */) { +inline void MapTypeHandler::Initialize( + Type** x, Arena* /* arena */) { *x = NULL; } @@ -523,198 +613,194 @@ inline void MapTypeHandler:: } template -inline Type* MapTypeHandler::EnsureMutable(Type** value, - Arena* arena) { +inline Type* MapTypeHandler::EnsureMutable( + Type** value, Arena* arena) { if (*value == NULL) { - *value = - MapArenaMessageCreator:: - type::value>::CreateMessage(arena); + *value = MapArenaMessageCreator< + Type, + Arena::is_arena_constructable::type::value>::CreateMessage(arena); } return *value; } template -inline const Type& MapTypeHandler:: - DefaultIfNotInitialized(const Type* value, const Type* default_value) { +inline const Type& +MapTypeHandler::DefaultIfNotInitialized( + const Type* value, const Type* default_value) { return value != NULL ? *value : *default_value; } template -inline bool MapTypeHandler::IsInitialized(Type* value) { +inline bool MapTypeHandler::IsInitialized( + Type* value) { return value->IsInitialized(); } // Definition for string/bytes handler -#define STRING_OR_BYTES_HANDLER_FUNCTIONS(FieldType) \ - template \ - inline const typename MapTypeHandler::MapEntryAccessorType& \ - MapTypeHandler::GetExternalReference(const TypeOnMemory& value) { \ - return value.Get(); \ - } \ - template \ - inline size_t \ - MapTypeHandler::SpaceUsedInMapEntryLong(const TypeOnMemory& value) { \ - return sizeof(value); \ - } \ - template \ - inline size_t \ - MapTypeHandler::SpaceUsedInMapLong( \ - const TypeOnMemory& value) { \ - return sizeof(value); \ - } \ - template \ - inline size_t \ - MapTypeHandler::SpaceUsedInMapLong( \ - const string& value) { \ - return sizeof(value); \ - } \ - template \ - inline void MapTypeHandler::Clear( \ - TypeOnMemory* value, Arena* arena) { \ - value->ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), \ - arena); \ - } \ - template \ - inline void MapTypeHandler:: \ - ClearMaybeByDefaultEnum(TypeOnMemory* value, Arena* arena, \ - int /* default_enum */) { \ - Clear(value, arena); \ - } \ - template \ - inline void MapTypeHandler::Merge( \ - const MapEntryAccessorType& from, TypeOnMemory* to, Arena* arena) { \ - to->Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from, arena); \ - } \ - template \ - void MapTypeHandler::DeleteNoArena( \ - TypeOnMemory& value) { \ - value.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); \ - } \ - template \ - inline void MapTypeHandler::AssignDefaultValue(TypeOnMemory* /* value */) {} \ - template \ - inline void \ - MapTypeHandler::Initialize( \ - TypeOnMemory* value, Arena* /* arena */) { \ - value->UnsafeSetDefault( \ - &::google::protobuf::internal::GetEmptyStringAlreadyInited()); \ - } \ - template \ - inline void MapTypeHandler:: \ - InitializeMaybeByDefaultEnum(TypeOnMemory* value, \ - int /* default_enum_value */, \ - Arena* arena) { \ - Initialize(value, arena); \ - } \ - template \ - inline typename MapTypeHandler::MapEntryAccessorType* \ - MapTypeHandler::EnsureMutable( \ - TypeOnMemory* value, Arena* arena) { \ - return value->Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), \ - arena); \ - } \ - template \ - inline const typename MapTypeHandler::MapEntryAccessorType& \ - MapTypeHandler::DefaultIfNotInitialized(const TypeOnMemory& value, \ - const TypeOnMemory& \ - /* default_value */) { \ - return value.Get(); \ - } \ - template \ - inline bool MapTypeHandler::IsInitialized(const TypeOnMemory& /* value */) { \ - return true; \ +#define STRING_OR_BYTES_HANDLER_FUNCTIONS(FieldType) \ + template \ + inline const typename MapTypeHandler::MapEntryAccessorType& \ + MapTypeHandler::GetExternalReference(const TypeOnMemory& value) { \ + return value.Get(); \ + } \ + template \ + inline size_t \ + MapTypeHandler::SpaceUsedInMapEntryLong(const TypeOnMemory& value) { \ + return sizeof(value); \ + } \ + template \ + inline size_t \ + MapTypeHandler::SpaceUsedInMapLong( \ + const TypeOnMemory& value) { \ + return sizeof(value); \ + } \ + template \ + inline size_t \ + MapTypeHandler::SpaceUsedInMapLong( \ + const std::string& value) { \ + return sizeof(value); \ + } \ + template \ + inline void MapTypeHandler::Clear( \ + TypeOnMemory* value, Arena* arena) { \ + value->ClearToEmpty(&internal::GetEmptyStringAlreadyInited(), arena); \ + } \ + template \ + inline void MapTypeHandler:: \ + ClearMaybeByDefaultEnum(TypeOnMemory* value, Arena* arena, \ + int /* default_enum */) { \ + Clear(value, arena); \ + } \ + template \ + inline void MapTypeHandler::Merge( \ + const MapEntryAccessorType& from, TypeOnMemory* to, Arena* arena) { \ + to->Set(&internal::GetEmptyStringAlreadyInited(), from, arena); \ + } \ + template \ + void MapTypeHandler::DeleteNoArena( \ + TypeOnMemory& value) { \ + value.DestroyNoArena(&internal::GetEmptyStringAlreadyInited()); \ + } \ + template \ + inline void \ + MapTypeHandler::AssignDefaultValue( \ + TypeOnMemory* /* value */) {} \ + template \ + inline void \ + MapTypeHandler::Initialize( \ + TypeOnMemory* value, Arena* /* arena */) { \ + value->UnsafeSetDefault(&internal::GetEmptyStringAlreadyInited()); \ + } \ + template \ + inline void MapTypeHandler:: \ + InitializeMaybeByDefaultEnum( \ + TypeOnMemory* value, int /* default_enum_value */, Arena* arena) { \ + Initialize(value, arena); \ + } \ + template \ + inline typename MapTypeHandler::MapEntryAccessorType* \ + MapTypeHandler::EnsureMutable( \ + TypeOnMemory* value, Arena* arena) { \ + return value->Mutable(&internal::GetEmptyStringAlreadyInited(), arena); \ + } \ + template \ + inline const typename MapTypeHandler::MapEntryAccessorType& \ + MapTypeHandler:: \ + DefaultIfNotInitialized(const TypeOnMemory& value, \ + const TypeOnMemory& /* default_value */) { \ + return value.Get(); \ + } \ + template \ + inline bool \ + MapTypeHandler::IsInitialized( \ + const TypeOnMemory& /* value */) { \ + return true; \ } STRING_OR_BYTES_HANDLER_FUNCTIONS(STRING) STRING_OR_BYTES_HANDLER_FUNCTIONS(BYTES) #undef STRING_OR_BYTES_HANDLER_FUNCTIONS -#define PRIMITIVE_HANDLER_FUNCTIONS(FieldType) \ - template \ - inline const typename MapTypeHandler::MapEntryAccessorType& \ - MapTypeHandler::GetExternalReference(const TypeOnMemory& value) { \ - return value; \ - } \ - template \ - inline size_t \ - MapTypeHandler::SpaceUsedInMapEntryLong(const TypeOnMemory& /* value */) { \ - return 0; \ - } \ - template \ - inline size_t \ - MapTypeHandler::SpaceUsedInMapLong( \ - const TypeOnMemory& /* value */) { \ - return sizeof(Type); \ - } \ - template \ - inline void MapTypeHandler::Clear( \ - TypeOnMemory* value, Arena* /* arena */) { \ - *value = 0; \ - } \ - template \ - inline void MapTypeHandler:: \ - ClearMaybeByDefaultEnum(TypeOnMemory* value, Arena* /* arena */, \ - int default_enum_value) { \ - *value = static_cast(default_enum_value); \ - } \ - template \ - inline void MapTypeHandler::Merge( \ - const MapEntryAccessorType& from, TypeOnMemory* to, \ - Arena* /* arena */) { \ - *to = from; \ - } \ - template \ - inline void MapTypeHandler::DeleteNoArena(TypeOnMemory& /* x */) {} \ - template \ - inline void MapTypeHandler::AssignDefaultValue(TypeOnMemory* /* value */) {} \ - template \ - inline void \ - MapTypeHandler::Initialize( \ - TypeOnMemory* value, Arena* /* arena */) { \ - *value = 0; \ - } \ - template \ - inline void MapTypeHandler:: \ - InitializeMaybeByDefaultEnum(TypeOnMemory* value, \ - int default_enum_value, \ - Arena* /* arena */) { \ - *value = static_cast(default_enum_value); \ - } \ - template \ - inline typename MapTypeHandler::MapEntryAccessorType* \ - MapTypeHandler::EnsureMutable( \ - TypeOnMemory* value, Arena* /* arena */) { \ - return value; \ - } \ - template \ - inline const typename MapTypeHandler::MapEntryAccessorType& \ - MapTypeHandler::DefaultIfNotInitialized(const TypeOnMemory& value, \ - const TypeOnMemory& \ - /* default_value */) { \ - return value; \ - } \ - template \ - inline bool MapTypeHandler::IsInitialized(const TypeOnMemory& /* value */) { \ - return true; \ +#define PRIMITIVE_HANDLER_FUNCTIONS(FieldType) \ + template \ + inline const typename MapTypeHandler::MapEntryAccessorType& \ + MapTypeHandler::GetExternalReference(const TypeOnMemory& value) { \ + return value; \ + } \ + template \ + inline size_t MapTypeHandler:: \ + SpaceUsedInMapEntryLong(const TypeOnMemory& /* value */) { \ + return 0; \ + } \ + template \ + inline size_t \ + MapTypeHandler::SpaceUsedInMapLong( \ + const TypeOnMemory& /* value */) { \ + return sizeof(Type); \ + } \ + template \ + inline void MapTypeHandler::Clear( \ + TypeOnMemory* value, Arena* /* arena */) { \ + *value = 0; \ + } \ + template \ + inline void MapTypeHandler:: \ + ClearMaybeByDefaultEnum(TypeOnMemory* value, Arena* /* arena */, \ + int default_enum_value) { \ + *value = static_cast(default_enum_value); \ + } \ + template \ + inline void MapTypeHandler::Merge( \ + const MapEntryAccessorType& from, TypeOnMemory* to, \ + Arena* /* arena */) { \ + *to = from; \ + } \ + template \ + inline void MapTypeHandler::DeleteNoArena(TypeOnMemory& /* x */) {} \ + template \ + inline void \ + MapTypeHandler::AssignDefaultValue( \ + TypeOnMemory* /* value */) {} \ + template \ + inline void \ + MapTypeHandler::Initialize( \ + TypeOnMemory* value, Arena* /* arena */) { \ + *value = 0; \ + } \ + template \ + inline void MapTypeHandler:: \ + InitializeMaybeByDefaultEnum( \ + TypeOnMemory* value, int default_enum_value, Arena* /* arena */) { \ + *value = static_cast(default_enum_value); \ + } \ + template \ + inline typename MapTypeHandler::MapEntryAccessorType* \ + MapTypeHandler::EnsureMutable( \ + TypeOnMemory* value, Arena* /* arena */) { \ + return value; \ + } \ + template \ + inline const typename MapTypeHandler::MapEntryAccessorType& \ + MapTypeHandler:: \ + DefaultIfNotInitialized(const TypeOnMemory& value, \ + const TypeOnMemory& /* default_value */) { \ + return value; \ + } \ + template \ + inline bool \ + MapTypeHandler::IsInitialized( \ + const TypeOnMemory& /* value */) { \ + return true; \ } PRIMITIVE_HANDLER_FUNCTIONS(INT64) PRIMITIVE_HANDLER_FUNCTIONS(UINT64) @@ -734,6 +820,6 @@ PRIMITIVE_HANDLER_FUNCTIONS(BOOL) } // namespace internal } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_TYPE_HANDLER_H__ diff --git a/third_party/protobuf/src/google/protobuf/message.cc b/third_party/protobuf/src/google/protobuf/message.cc index 9b758080..09b087f6 100644 --- a/third_party/protobuf/src/google/protobuf/message.cc +++ b/third_party/protobuf/src/google/protobuf/message.cc @@ -34,42 +34,60 @@ #include #include -#include +#include +#include #include #include #include #include -#include -#include #include +#include #include #include #include #include #include #include +#include #include +#include #include +#include #include #include -#include #include +#include + +#include namespace google { namespace protobuf { -using internal::WireFormat; +namespace internal { + +// TODO(gerbens) make this factorized better. This should not have to hop +// to reflection. Currently uses GeneratedMessageReflection and thus is +// defined in generated_message_reflection.cc +void RegisterFileLevelMetadata(const DescriptorTable* descriptor_table); + +} // namespace internal + using internal::ReflectionOps; +using internal::WireFormat; +using internal::WireFormatLite; void Message::MergeFrom(const Message& from) { const Descriptor* descriptor = GetDescriptor(); GOOGLE_CHECK_EQ(from.GetDescriptor(), descriptor) - << ": Tried to merge from a message with a different type. " - "to: " << descriptor->full_name() << ", " - "from: " << from.GetDescriptor()->full_name(); + << ": Tried to merge from a message with a different type. " + "to: " + << descriptor->full_name() + << ", " + "from: " + << from.GetDescriptor()->full_name(); ReflectionOps::Merge(from, this); } @@ -80,47 +98,50 @@ void Message::CheckTypeAndMergeFrom(const MessageLite& other) { void Message::CopyFrom(const Message& from) { const Descriptor* descriptor = GetDescriptor(); GOOGLE_CHECK_EQ(from.GetDescriptor(), descriptor) - << ": Tried to copy from a message with a different type. " - "to: " << descriptor->full_name() << ", " - "from: " << from.GetDescriptor()->full_name(); + << ": Tried to copy from a message with a different type. " + "to: " + << descriptor->full_name() + << ", " + "from: " + << from.GetDescriptor()->full_name(); ReflectionOps::Copy(from, this); } -string Message::GetTypeName() const { +std::string Message::GetTypeName() const { return GetDescriptor()->full_name(); } -void Message::Clear() { - ReflectionOps::Clear(this); -} +void Message::Clear() { ReflectionOps::Clear(this); } bool Message::IsInitialized() const { return ReflectionOps::IsInitialized(*this); } -void Message::FindInitializationErrors(std::vector* errors) const { +void Message::FindInitializationErrors(std::vector* errors) const { return ReflectionOps::FindInitializationErrors(*this, "", errors); } -string Message::InitializationErrorString() const { - std::vector errors; +std::string Message::InitializationErrorString() const { + std::vector errors; FindInitializationErrors(&errors); return Join(errors, ", "); } void Message::CheckInitialized() const { - GOOGLE_CHECK(IsInitialized()) - << "Message of type \"" << GetDescriptor()->full_name() - << "\" is missing required fields: " << InitializationErrorString(); + GOOGLE_CHECK(IsInitialized()) << "Message of type \"" << GetDescriptor()->full_name() + << "\" is missing required fields: " + << InitializationErrorString(); } void Message::DiscardUnknownFields() { return ReflectionOps::DiscardUnknownFields(this); } +#if !GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Message::MergePartialFromCodedStream(io::CodedInputStream* input) { return WireFormat::ParseAndMergePartial(input, this); } +#endif bool Message::ParseFromFileDescriptor(int file_descriptor) { io::FileInputStream input(file_descriptor); @@ -142,9 +163,402 @@ bool Message::ParsePartialFromIstream(std::istream* input) { return ParsePartialFromZeroCopyStream(&zero_copy_input) && input->eof(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +namespace internal { -void Message::SerializeWithCachedSizes( - io::CodedOutputStream* output) const { +class ReflectionAccessor { + public: + static void* GetOffset(void* msg, const google::protobuf::FieldDescriptor* f, + const google::protobuf::Reflection* r) { + return static_cast(msg) + CheckedCast(r)->schema_.GetFieldOffset(f); + } + + static ExtensionSet* GetExtensionSet(void* msg, const google::protobuf::Reflection* r) { + return reinterpret_cast( + static_cast(msg) + + CheckedCast(r)->schema_.GetExtensionSetOffset()); + } + static InternalMetadataWithArena* GetMetadata(void* msg, + const google::protobuf::Reflection* r) { + return reinterpret_cast( + static_cast(msg) + CheckedCast(r)->schema_.GetMetadataOffset()); + } + static void* GetRepeatedEnum(const Reflection* reflection, + const FieldDescriptor* field, Message* msg) { + return reflection->MutableRawRepeatedField( + msg, field, FieldDescriptor::CPPTYPE_ENUM, 0, nullptr); + } + + private: + static const GeneratedMessageReflection* CheckedCast(const Reflection* r) { + auto gr = dynamic_cast(r); + GOOGLE_CHECK(gr != nullptr); + return gr; + } +}; + +} // namespace internal + +void SetField(uint64 val, const FieldDescriptor* field, Message* msg, + const Reflection* reflection) { +#define STORE_TYPE(CPPTYPE_METHOD) \ + do \ + if (field->is_repeated()) { \ + reflection->Add##CPPTYPE_METHOD(msg, field, value); \ + } else { \ + reflection->Set##CPPTYPE_METHOD(msg, field, value); \ + } \ + while (0) + + switch (field->type()) { +#define HANDLE_TYPE(TYPE, CPPTYPE, CPPTYPE_METHOD) \ + case FieldDescriptor::TYPE_##TYPE: { \ + CPPTYPE value = val; \ + STORE_TYPE(CPPTYPE_METHOD); \ + break; \ + } + + // Varints + HANDLE_TYPE(INT32, int32, Int32) + HANDLE_TYPE(INT64, int64, Int64) + HANDLE_TYPE(UINT32, uint32, UInt32) + HANDLE_TYPE(UINT64, uint64, UInt64) + case FieldDescriptor::TYPE_SINT32: { + int32 value = WireFormatLite::ZigZagDecode32(val); + STORE_TYPE(Int32); + break; + } + case FieldDescriptor::TYPE_SINT64: { + int64 value = WireFormatLite::ZigZagDecode64(val); + STORE_TYPE(Int64); + break; + } + HANDLE_TYPE(BOOL, bool, Bool) + + // Fixed + HANDLE_TYPE(FIXED32, uint32, UInt32) + HANDLE_TYPE(FIXED64, uint64, UInt64) + HANDLE_TYPE(SFIXED32, int32, Int32) + HANDLE_TYPE(SFIXED64, int64, Int64) + + case FieldDescriptor::TYPE_FLOAT: { + float value; + uint32 bit_rep = val; + std::memcpy(&value, &bit_rep, sizeof(value)); + STORE_TYPE(Float); + break; + } + case FieldDescriptor::TYPE_DOUBLE: { + double value; + uint64 bit_rep = val; + std::memcpy(&value, &bit_rep, sizeof(value)); + STORE_TYPE(Double); + break; + } + case FieldDescriptor::TYPE_ENUM: { + int value = val; + if (field->is_repeated()) { + reflection->AddEnumValue(msg, field, value); + } else { + reflection->SetEnumValue(msg, field, value); + } + break; + } + default: + GOOGLE_LOG(FATAL) << "Error in descriptors, primitve field with field type " + << field->type(); + } +#undef STORE_TYPE +#undef HANDLE_TYPE +} + +bool ReflectiveValidator(const void* arg, int val) { + auto d = static_cast(arg); + return d->FindValueByNumber(val) != nullptr; +} + +const char* ParsePackedField(const FieldDescriptor* field, Message* msg, + const Reflection* reflection, const char* ptr, + internal::ParseContext* ctx) { + switch (field->type()) { +#define HANDLE_PACKED_TYPE(TYPE, CPPTYPE, METHOD_NAME) \ + case FieldDescriptor::TYPE_##TYPE: \ + return internal::Packed##METHOD_NAME##Parser( \ + reflection->MutableRepeatedField(msg, field), ptr, ctx) + HANDLE_PACKED_TYPE(INT32, int32, Int32); + HANDLE_PACKED_TYPE(INT64, int64, Int64); + HANDLE_PACKED_TYPE(SINT32, int32, SInt32); + HANDLE_PACKED_TYPE(SINT64, int64, SInt64); + HANDLE_PACKED_TYPE(UINT32, uint32, UInt32); + HANDLE_PACKED_TYPE(UINT64, uint64, UInt64); + HANDLE_PACKED_TYPE(BOOL, bool, Bool); + case FieldDescriptor::TYPE_ENUM: { + auto object = + internal::ReflectionAccessor::GetRepeatedEnum(reflection, field, msg); + if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) { + return internal::PackedEnumParser(object, ptr, ctx); + } else { + return internal::PackedEnumParserArg( + object, ptr, ctx, ReflectiveValidator, field->enum_type(), + reflection->MutableUnknownFields(msg), field->number()); + } + } + HANDLE_PACKED_TYPE(FIXED32, uint32, Fixed32); + HANDLE_PACKED_TYPE(FIXED64, uint64, Fixed64); + HANDLE_PACKED_TYPE(SFIXED32, int32, SFixed32); + HANDLE_PACKED_TYPE(SFIXED64, int64, SFixed64); + HANDLE_PACKED_TYPE(FLOAT, float, Float); + HANDLE_PACKED_TYPE(DOUBLE, double, Double); +#undef HANDLE_PACKED_TYPE + + default: + GOOGLE_LOG(FATAL) << "Type is not packable " << field->type(); + return nullptr; // Make compiler happy + } +} + +const char* ParseLenDelim(int field_number, const FieldDescriptor* field, + Message* msg, const Reflection* reflection, + const char* ptr, internal::ParseContext* ctx) { + if (WireFormat::WireTypeForFieldType(field->type()) != + WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { + GOOGLE_DCHECK(field->is_packable()); + return ParsePackedField(field, msg, reflection, ptr, ctx); + } + enum { kNone = 0, kVerify, kStrict } utf8_level = kNone; + const char* field_name = nullptr; + auto parse_string = [ptr, ctx, &utf8_level, &field_name](std::string* s) { + switch (utf8_level) { + case kNone: + return internal::InlineGreedyStringParser(s, ptr, ctx); + case kVerify: + return internal::InlineGreedyStringParserUTF8Verify(s, ptr, ctx, + field_name); + case kStrict: + return internal::InlineGreedyStringParserUTF8(s, ptr, ctx, field_name); + } + }; + switch (field->type()) { + case FieldDescriptor::TYPE_STRING: { + bool enforce_utf8 = true; + bool utf8_verification = true; + if (enforce_utf8 && + field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) { + utf8_level = kStrict; + } else if (utf8_verification) { + utf8_level = kVerify; + } + field_name = field->full_name().c_str(); + PROTOBUF_FALLTHROUGH_INTENDED; + } + case FieldDescriptor::TYPE_BYTES: { + if (field->is_repeated()) { + int index = reflection->FieldSize(*msg, field); + // Add new empty value. + reflection->AddString(msg, field, ""); + if (field->options().ctype() == FieldOptions::STRING || + field->is_extension()) { + auto object = + reflection->MutableRepeatedPtrField(msg, field) + ->Mutable(index); + return parse_string(object); + } else { + auto object = + reflection->MutableRepeatedPtrField(msg, field) + ->Mutable(index); + return parse_string(object); + } + } else { + // Clear value and make sure it's set. + reflection->SetString(msg, field, ""); + if (field->options().ctype() == FieldOptions::STRING || + field->is_extension()) { + // HACK around inability to get mutable_string in reflection + std::string* object = &const_cast( + reflection->GetStringReference(*msg, field, nullptr)); + return parse_string(object); + } else { + // HACK around inability to get mutable_string in reflection + std::string* object = &const_cast( + reflection->GetStringReference(*msg, field, nullptr)); + return parse_string(object); + } + } + GOOGLE_LOG(FATAL) << "No other type than string supported"; + } + case FieldDescriptor::TYPE_MESSAGE: { + Message* object; + if (field->is_repeated()) { + object = reflection->AddMessage(msg, field, ctx->data().factory); + } else { + object = reflection->MutableMessage(msg, field, ctx->data().factory); + } + return ctx->ParseMessage(object, ptr); + } + default: + GOOGLE_LOG(FATAL) << "Wrong type for length delim " << field->type(); + } + return nullptr; // Make compiler happy. +} + +Message* GetGroup(int field_number, const FieldDescriptor* field, Message* msg, + const Reflection* reflection) { + if (field->is_repeated()) { + return reflection->AddMessage(msg, field, nullptr); + } else { + return reflection->MutableMessage(msg, field, nullptr); + } +} + +const char* Message::_InternalParse(const char* ptr, + internal::ParseContext* ctx) { + class ReflectiveFieldParser { + public: + ReflectiveFieldParser(Message* msg, internal::ParseContext* ctx) + : ReflectiveFieldParser(msg, ctx, false) {} + + void AddVarint(uint32 num, uint64 value) { + if (is_item_ && num == 2) { + if (!payload_.empty()) { + auto field = Field(value, 2); + if (field && field->message_type()) { + auto child = reflection_->MutableMessage(msg_, field); + // TODO(gerbens) signal error + child->ParsePartialFromString(payload_); + } else { + MutableUnknown()->AddLengthDelimited(value)->swap(payload_); + } + return; + } + type_id_ = value; + return; + } + auto field = Field(num, 0); + if (field) { + SetField(value, field, msg_, reflection_); + } else { + MutableUnknown()->AddVarint(num, value); + } + } + void AddFixed64(uint32 num, uint64 value) { + auto field = Field(num, 1); + if (field) { + SetField(value, field, msg_, reflection_); + } else { + MutableUnknown()->AddFixed64(num, value); + } + } + const char* ParseLengthDelimited(uint32 num, const char* ptr, + internal::ParseContext* ctx) { + if (is_item_ && num == 3) { + if (type_id_ == 0) { + return InlineGreedyStringParser(&payload_, ptr, ctx); + } + num = type_id_; + type_id_ = 0; + } + auto field = Field(num, 2); + if (field) { + return ParseLenDelim(num, field, msg_, reflection_, ptr, ctx); + } else { + return InlineGreedyStringParser( + MutableUnknown()->AddLengthDelimited(num), ptr, ctx); + } + } + const char* ParseGroup(uint32 num, const char* ptr, + internal::ParseContext* ctx) { + if (!is_item_ && descriptor_->options().message_set_wire_format() && + num == 1) { + is_item_ = true; + ptr = ctx->ParseGroup(this, ptr, num * 8 + 3); + is_item_ = false; + type_id_ = 0; + return ptr; + } + auto field = Field(num, 3); + if (field) { + auto msg = GetGroup(num, field, msg_, reflection_); + return ctx->ParseGroup(msg, ptr, num * 8 + 3); + } else { + return UnknownFieldParse(num * 8 + 3, MutableUnknown(), ptr, ctx); + } + } + void AddFixed32(uint32 num, uint32 value) { + auto field = Field(num, 5); + if (field) { + SetField(value, field, msg_, reflection_); + } else { + MutableUnknown()->AddFixed32(num, value); + } + } + + const char* _InternalParse(const char* ptr, internal::ParseContext* ctx) { + // We're parsing the a MessageSetItem + GOOGLE_DCHECK(is_item_); + return internal::WireFormatParser(*this, ptr, ctx); + } + + private: + Message* msg_; + const Descriptor* descriptor_; + const Reflection* reflection_; + internal::ParseContext* ctx_; + UnknownFieldSet* unknown_ = nullptr; + bool is_item_ = false; + uint32 type_id_ = 0; + std::string payload_; + + ReflectiveFieldParser(Message* msg, internal::ParseContext* ctx, + bool is_item) + : msg_(msg), + descriptor_(msg->GetDescriptor()), + reflection_(msg->GetReflection()), + ctx_(ctx), + is_item_(is_item) { + GOOGLE_CHECK(descriptor_) << msg->GetTypeName(); + GOOGLE_CHECK(reflection_) << msg->GetTypeName(); + } + + const FieldDescriptor* Field(int num, int wire_type) { + auto field = descriptor_->FindFieldByNumber(num); + + // If that failed, check if the field is an extension. + if (field == nullptr && descriptor_->IsExtensionNumber(num)) { + const DescriptorPool* pool = ctx_->data().pool; + if (pool == NULL) { + field = reflection_->FindKnownExtensionByNumber(num); + } else { + field = pool->FindExtensionByNumber(descriptor_, num); + } + } + if (field == nullptr) return nullptr; + + if (internal::WireFormat::WireTypeForFieldType(field->type()) != + wire_type) { + if (field->is_packable()) { + if (wire_type == + internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { + return field; + } + } + return nullptr; + } + return field; + } + + UnknownFieldSet* MutableUnknown() { + if (unknown_) return unknown_; + return unknown_ = reflection_->MutableUnknownFields(msg_); + } + }; + + ReflectiveFieldParser field_parser(this, ctx); + return internal::WireFormatParser(field_parser, ptr, ctx); +} +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + + +void Message::SerializeWithCachedSizes(io::CodedOutputStream* output) const { const internal::SerializationTable* table = static_cast(InternalGetTable()); if (table == 0) { @@ -203,51 +617,50 @@ void Reflection::AddAllocatedMessage(Message* /* message */, const FieldDescriptor* /*field */, Message* /* new_entry */) const {} -#define HANDLE_TYPE(TYPE, CPPTYPE, CTYPE) \ -template<> \ -const RepeatedField& Reflection::GetRepeatedField( \ - const Message& message, const FieldDescriptor* field) const { \ - return *static_cast* >( \ - MutableRawRepeatedField(const_cast(&message), \ - field, CPPTYPE, CTYPE, NULL)); \ -} \ - \ -template<> \ -RepeatedField* Reflection::MutableRepeatedField( \ - Message* message, const FieldDescriptor* field) const { \ - return static_cast* >( \ - MutableRawRepeatedField(message, field, CPPTYPE, CTYPE, NULL)); \ -} +#define HANDLE_TYPE(TYPE, CPPTYPE, CTYPE) \ + template <> \ + const RepeatedField& Reflection::GetRepeatedField( \ + const Message& message, const FieldDescriptor* field) const { \ + return *static_cast*>(MutableRawRepeatedField( \ + const_cast(&message), field, CPPTYPE, CTYPE, NULL)); \ + } \ + \ + template <> \ + RepeatedField* Reflection::MutableRepeatedField( \ + Message * message, const FieldDescriptor* field) const { \ + return static_cast*>( \ + MutableRawRepeatedField(message, field, CPPTYPE, CTYPE, NULL)); \ + } -HANDLE_TYPE(int32, FieldDescriptor::CPPTYPE_INT32, -1); -HANDLE_TYPE(int64, FieldDescriptor::CPPTYPE_INT64, -1); +HANDLE_TYPE(int32, FieldDescriptor::CPPTYPE_INT32, -1); +HANDLE_TYPE(int64, FieldDescriptor::CPPTYPE_INT64, -1); HANDLE_TYPE(uint32, FieldDescriptor::CPPTYPE_UINT32, -1); HANDLE_TYPE(uint64, FieldDescriptor::CPPTYPE_UINT64, -1); -HANDLE_TYPE(float, FieldDescriptor::CPPTYPE_FLOAT, -1); +HANDLE_TYPE(float, FieldDescriptor::CPPTYPE_FLOAT, -1); HANDLE_TYPE(double, FieldDescriptor::CPPTYPE_DOUBLE, -1); -HANDLE_TYPE(bool, FieldDescriptor::CPPTYPE_BOOL, -1); +HANDLE_TYPE(bool, FieldDescriptor::CPPTYPE_BOOL, -1); #undef HANDLE_TYPE -void* Reflection::MutableRawRepeatedString( - Message* message, const FieldDescriptor* field, bool is_string) const { +void* Reflection::MutableRawRepeatedString(Message* message, + const FieldDescriptor* field, + bool is_string) const { return MutableRawRepeatedField(message, field, - FieldDescriptor::CPPTYPE_STRING, FieldOptions::STRING, NULL); + FieldDescriptor::CPPTYPE_STRING, + FieldOptions::STRING, NULL); } -MapIterator Reflection::MapBegin( - Message* message, - const FieldDescriptor* field) const { +MapIterator Reflection::MapBegin(Message* message, + const FieldDescriptor* field) const { GOOGLE_LOG(FATAL) << "Unimplemented Map Reflection API."; MapIterator iter(message, field); return iter; } -MapIterator Reflection::MapEnd( - Message* message, - const FieldDescriptor* field) const { +MapIterator Reflection::MapEnd(Message* message, + const FieldDescriptor* field) const { GOOGLE_LOG(FATAL) << "Unimplemented Map Reflection API."; MapIterator iter(message, field); return iter; @@ -264,40 +677,46 @@ class GeneratedMessageFactory : public MessageFactory { public: static GeneratedMessageFactory* singleton(); - typedef void RegistrationFunc(const string&); - void RegisterFile(const char* file, RegistrationFunc* registration_func); + struct RegistrationData { + const Metadata* file_level_metadata; + int size; + }; + + void RegisterFile(const google::protobuf::internal::DescriptorTable* table); void RegisterType(const Descriptor* descriptor, const Message* prototype); // implements MessageFactory --------------------------------------- - const Message* GetPrototype(const Descriptor* type); + const Message* GetPrototype(const Descriptor* type) override; private: // Only written at static init time, so does not require locking. - hash_map, streq> file_map_; + std::unordered_map, streq> + file_map_; - Mutex mutex_; + internal::WrappedMutex mutex_; // Initialized lazily, so requires locking. - hash_map type_map_; + std::unordered_map type_map_; }; GeneratedMessageFactory* GeneratedMessageFactory::singleton() { - static auto instance = internal::OnShutdownDelete(new GeneratedMessageFactory); + static auto instance = + internal::OnShutdownDelete(new GeneratedMessageFactory); return instance; } void GeneratedMessageFactory::RegisterFile( - const char* file, RegistrationFunc* registration_func) { - if (!InsertIfNotPresent(&file_map_, file, registration_func)) { - GOOGLE_LOG(FATAL) << "File is already registered: " << file; + const google::protobuf::internal::DescriptorTable* table) { + if (!InsertIfNotPresent(&file_map_, table->filename, table)) { + GOOGLE_LOG(FATAL) << "File is already registered: " << table->filename; } } void GeneratedMessageFactory::RegisterType(const Descriptor* descriptor, const Message* prototype) { GOOGLE_DCHECK_EQ(descriptor->file()->pool(), DescriptorPool::generated_pool()) - << "Tried to register a non-generated type with the generated " - "type registry."; + << "Tried to register a non-generated type with the generated " + "type registry."; // This should only be called as a result of calling a file registration // function during GetPrototype(), in which case we already have locked @@ -321,11 +740,12 @@ const Message* GeneratedMessageFactory::GetPrototype(const Descriptor* type) { if (type->file()->pool() != DescriptorPool::generated_pool()) return NULL; // Apparently the file hasn't been registered yet. Let's do that now. - RegistrationFunc* registration_func = + const internal::DescriptorTable* registration_data = FindPtrOrNull(file_map_, type->file()->name().c_str()); - if (registration_func == NULL) { + if (registration_data == NULL) { GOOGLE_LOG(DFATAL) << "File appears to be in generated pool but wasn't " - "registered: " << type->file()->name(); + "registered: " + << type->file()->name(); return NULL; } @@ -335,7 +755,7 @@ const Message* GeneratedMessageFactory::GetPrototype(const Descriptor* type) { const Message* result = FindPtrOrNull(type_map_, type); if (result == NULL) { // Nope. OK, register everything. - registration_func(type->file()->name()); + internal::RegisterFileLevelMetadata(registration_data); // Should be here now. result = FindPtrOrNull(type_map_, type); } @@ -355,9 +775,8 @@ MessageFactory* MessageFactory::generated_factory() { } void MessageFactory::InternalRegisterGeneratedFile( - const char* filename, void (*register_messages)(const string&)) { - GeneratedMessageFactory::singleton()->RegisterFile(filename, - register_messages); + const google::protobuf::internal::DescriptorTable* table) { + GeneratedMessageFactory::singleton()->RegisterFile(table); } void MessageFactory::InternalRegisterGeneratedMessage( @@ -371,26 +790,29 @@ MessageFactory* Reflection::GetMessageFactory() const { return NULL; } -void* Reflection::RepeatedFieldData( - Message* message, const FieldDescriptor* field, - FieldDescriptor::CppType cpp_type, - const Descriptor* message_type) const { +void* Reflection::RepeatedFieldData(Message* message, + const FieldDescriptor* field, + FieldDescriptor::CppType cpp_type, + const Descriptor* message_type) const { GOOGLE_LOG(FATAL) << "Not implemented."; return NULL; } -namespace internal { -RepeatedFieldAccessor::~RepeatedFieldAccessor() { +namespace { +template +T* GetSingleton() { + static T singleton; + return &singleton; } -} // namespace internal +} // namespace const internal::RepeatedFieldAccessor* Reflection::RepeatedFieldAccessor( const FieldDescriptor* field) const { GOOGLE_CHECK(field->is_repeated()); switch (field->cpp_type()) { #define HANDLE_PRIMITIVE_TYPE(TYPE, type) \ - case FieldDescriptor::CPPTYPE_ ## TYPE: \ - return internal::Singleton >::get(); + case FieldDescriptor::CPPTYPE_##TYPE: \ + return GetSingleton >(); HANDLE_PRIMITIVE_TYPE(INT32, int32) HANDLE_PRIMITIVE_TYPE(UINT32, uint32) HANDLE_PRIMITIVE_TYPE(INT64, int64) @@ -404,14 +826,14 @@ const internal::RepeatedFieldAccessor* Reflection::RepeatedFieldAccessor( switch (field->options().ctype()) { default: case FieldOptions::STRING: - return internal::Singleton::get(); + return GetSingleton(); } break; case FieldDescriptor::CPPTYPE_MESSAGE: if (field->is_map()) { - return internal::Singleton::get(); + return GetSingleton(); } else { - return internal::Singleton::get(); + return GetSingleton(); } } GOOGLE_LOG(FATAL) << "Should not reach here."; @@ -419,55 +841,35 @@ const internal::RepeatedFieldAccessor* Reflection::RepeatedFieldAccessor( } namespace internal { -namespace { -void ShutdownRepeatedFieldAccessor() { - internal::Singleton >::ShutDown(); - internal::Singleton >::ShutDown(); - internal::Singleton >::ShutDown(); - internal::Singleton >::ShutDown(); - internal::Singleton >::ShutDown(); - internal::Singleton >::ShutDown(); - internal::Singleton >::ShutDown(); - internal::Singleton::ShutDown(); - internal::Singleton::ShutDown(); - internal::Singleton::ShutDown(); -} - -struct ShutdownRepeatedFieldRegister { - ShutdownRepeatedFieldRegister() { - OnShutdown(&ShutdownRepeatedFieldAccessor); - } -} shutdown_; - -} // namespace -} // namespace internal - -namespace internal { -template<> +template <> #if defined(_MSC_VER) && (_MSC_VER >= 1800) -// Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue #240 -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +// Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue +// #240 +PROTOBUF_NOINLINE #endif -Message* GenericTypeHandler::NewFromPrototype( - const Message* prototype, google::protobuf::Arena* arena) { + Message* + GenericTypeHandler::NewFromPrototype(const Message* prototype, + Arena* arena) { return prototype->New(arena); } -template<> +template <> #if defined(_MSC_VER) && (_MSC_VER >= 1800) -// Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue #240 -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +// Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue +// #240 +PROTOBUF_NOINLINE #endif -google::protobuf::Arena* GenericTypeHandler::GetArena( - Message* value) { + Arena* + GenericTypeHandler::GetArena(Message* value) { return value->GetArena(); } -template<> +template <> #if defined(_MSC_VER) && (_MSC_VER >= 1800) -// Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue #240 -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +// Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue +// #240 +PROTOBUF_NOINLINE #endif -void* GenericTypeHandler::GetMaybeArenaPointer( - Message* value) { + void* + GenericTypeHandler::GetMaybeArenaPointer(Message* value) { return value->GetMaybeArenaPointer(); } } // namespace internal diff --git a/third_party/protobuf/src/google/protobuf/message.h b/third_party/protobuf/src/google/protobuf/message.h index f3d1a58a..925c2494 100644 --- a/third_party/protobuf/src/google/protobuf/message.h +++ b/third_party/protobuf/src/google/protobuf/message.h @@ -49,7 +49,7 @@ // Then, if you used the protocol compiler to generate a class from the above // definition, you could use it like so: // -// string data; // Will store a serialized version of the message. +// std::string data; // Will store a serialized version of the message. // // { // // Create a message and serialize it. @@ -115,16 +115,23 @@ #include #include -#include -#include - +#include #include +#include #include +#include +#include #define GOOGLE_PROTOBUF_HAS_ONEOF #define GOOGLE_PROTOBUF_HAS_ARENAS +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + namespace google { namespace protobuf { @@ -140,34 +147,40 @@ class MapIterator; class MapReflectionTester; namespace internal { +struct DescriptorTable; class MapFieldBase; } -class UnknownFieldSet; // unknown_field_set.h +class UnknownFieldSet; // unknown_field_set.h namespace io { -class ZeroCopyInputStream; // zero_copy_stream.h -class ZeroCopyOutputStream; // zero_copy_stream.h -class CodedInputStream; // coded_stream.h -class CodedOutputStream; // coded_stream.h -} +class ZeroCopyInputStream; // zero_copy_stream.h +class ZeroCopyOutputStream; // zero_copy_stream.h +class CodedInputStream; // coded_stream.h +class CodedOutputStream; // coded_stream.h +} // namespace io namespace python { -class MapReflectionFriend; // scalar_map_container.h +class MapReflectionFriend; // scalar_map_container.h } namespace expr { class CelMapReflectionFriend; // field_backed_map_impl.cc } - namespace internal { -class ReflectionOps; // reflection_ops.h -class MapKeySorter; // wire_format.cc -class WireFormat; // wire_format.h -class MapFieldReflectionTest; // map_test.cc +class MapFieldPrinterHelper; // text_format.cc } -template -class RepeatedField; // repeated_field.h -template +namespace internal { +class ReflectionAccessor; // message.cc +class ReflectionOps; // reflection_ops.h +class MapKeySorter; // wire_format.cc +class WireFormat; // wire_format.h +class MapFieldReflectionTest; // map_test.cc +} // namespace internal + +template +class RepeatedField; // repeated_field.h + +template class RepeatedPtrField; // repeated_field.h // A container to hold message metadata. @@ -186,22 +199,22 @@ struct Metadata { // optimized for speed will want to override these with faster implementations, // but classes optimized for code size may be happy with keeping them. See // the optimize_for option in descriptor.proto. -class LIBPROTOBUF_EXPORT Message : public MessageLite { +class PROTOBUF_EXPORT Message : public MessageLite { public: inline Message() {} - virtual ~Message() {} + ~Message() override {} // Basic Operations ------------------------------------------------ // Construct a new instance of the same type. Ownership is passed to the // caller. (This is also defined in MessageLite, but is defined again here // for return-type covariance.) - virtual Message* New() const = 0; + Message* New() const override = 0; // Construct a new instance on the arena. Ownership is passed to the caller // if arena is a NULL. Default implementation allows for API compatibility // during the Arena transition. - virtual Message* New(::google::protobuf::Arena* arena) const { + Message* New(Arena* arena) const override { Message* message = New(); if (arena != NULL) { arena->Own(message); @@ -229,11 +242,11 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite { // This is much, much slower than IsInitialized() as it is implemented // purely via reflection. Generally, you should not call this unless you // have already determined that an error exists by calling IsInitialized(). - void FindInitializationErrors(std::vector* errors) const; + void FindInitializationErrors(std::vector* errors) const; // Like FindInitializationErrors, but joins all the strings, delimited by // commas, and returns them. - string InitializationErrorString() const; + std::string InitializationErrorString() const override; // Clears all unknown fields from this message and all embedded messages. // Normally, if unknown tag numbers are encountered when parsing a message, @@ -257,18 +270,18 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite { // fields defined for the proto. virtual size_t SpaceUsedLong() const; - PROTOBUF_RUNTIME_DEPRECATED("Please use SpaceUsedLong() instead") + PROTOBUF_DEPRECATED_MSG("Please use SpaceUsedLong() instead") int SpaceUsed() const { return internal::ToIntSize(SpaceUsedLong()); } // Debugging & Testing---------------------------------------------- // Generates a human readable form of this message, useful for debugging // and other purposes. - string DebugString() const; + std::string DebugString() const; // Like DebugString(), but with less whitespace. - string ShortDebugString() const; + std::string ShortDebugString() const; // Like DebugString(), but do not escape UTF-8 byte sequences. - string Utf8DebugString() const; + std::string Utf8DebugString() const; // Convenience function useful in GDB. Prints DebugString() to stdout. void PrintDebugString() const; @@ -305,13 +318,19 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite { // These methods are pure-virtual in MessageLite, but Message provides // reflection-based default implementations. - virtual string GetTypeName() const; - virtual void Clear(); - virtual bool IsInitialized() const; - virtual void CheckTypeAndMergeFrom(const MessageLite& other); - virtual bool MergePartialFromCodedStream(io::CodedInputStream* input); - virtual size_t ByteSizeLong() const; - virtual void SerializeWithCachedSizes(io::CodedOutputStream* output) const; + std::string GetTypeName() const override; + void Clear() override; + bool IsInitialized() const override; + void CheckTypeAndMergeFrom(const MessageLite& other) override; +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + // Reflective parser + const char* _InternalParse(const char* ptr, + internal::ParseContext* ctx) override; +#else + bool MergePartialFromCodedStream(io::CodedInputStream* input) override; +#endif + size_t ByteSizeLong() const override; + void SerializeWithCachedSizes(io::CodedOutputStream* output) const override; private: // This is called only by the default implementation of ByteSize(), to @@ -324,11 +343,8 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite { virtual void SetCachedSize(int size) const; public: - // Introspection --------------------------------------------------- - // Typedef for backwards-compatibility. - typedef google::protobuf::Reflection Reflection; // Get a non-owning pointer to a Descriptor for this message's type. This // describes what fields the message contains, the types of those fields, etc. @@ -342,15 +358,13 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite { // // This method remains virtual in case a subclass does not implement // reflection and wants to override the default behavior. - virtual const Reflection* GetReflection() const final { - return GetMetadata().reflection; - } + const Reflection* GetReflection() const { return GetMetadata().reflection; } protected: // Get a struct containing the metadata for the Message. Most subclasses only // need to implement this method, rather than the GetDescriptor() and // GetReflection() wrappers. - virtual Metadata GetMetadata() const = 0; + virtual Metadata GetMetadata() const = 0; private: @@ -365,10 +379,10 @@ class RepeatedFieldAccessor; // Forward-declare RepeatedFieldRef templates. The second type parameter is // used for SFINAE tricks. Users should ignore it. -template +template class RepeatedFieldRef; -template +template class MutableRepeatedFieldRef; // This interface contains methods that can be used to dynamically access @@ -409,28 +423,25 @@ class MutableRepeatedFieldRef; // double the message's memory footprint, probably worse. Allocating the // objects on-demand, on the other hand, would be expensive and prone to // memory leaks. So, instead we ended up with this flat interface. -class LIBPROTOBUF_EXPORT Reflection { +class PROTOBUF_EXPORT Reflection { public: inline Reflection() {} virtual ~Reflection(); // Get the UnknownFieldSet for the message. This contains fields which // were seen when the Message was parsed but were not recognized according - // to the Message's definition. For proto3 protos, this method will always - // return an empty UnknownFieldSet. + // to the Message's definition. virtual const UnknownFieldSet& GetUnknownFields( const Message& message) const = 0; // Get a mutable pointer to the UnknownFieldSet for the message. This // contains fields which were seen when the Message was parsed but were not - // recognized according to the Message's definition. For proto3 protos, this - // method will return a valid mutable UnknownFieldSet pointer but modifying - // it won't affect the serialized bytes of the message. + // recognized according to the Message's definition. virtual UnknownFieldSet* MutableUnknownFields(Message* message) const = 0; // Estimate the amount of memory used by the message object. virtual size_t SpaceUsedLong(const Message& message) const = 0; - PROTOBUF_RUNTIME_DEPRECATED("Please use SpaceUsedLong() instead") + PROTOBUF_DEPRECATED_MSG("Please use SpaceUsedLong() instead") int SpaceUsed(const Message& message) const { return internal::ToIntSize(SpaceUsedLong(message)); } @@ -486,16 +497,13 @@ class LIBPROTOBUF_EXPORT Reflection { virtual void Swap(Message* message1, Message* message2) const = 0; // Swap fields listed in fields vector of two messages. - virtual void SwapFields(Message* message1, - Message* message2, - const std::vector& fields) - const = 0; + virtual void SwapFields( + Message* message1, Message* message2, + const std::vector& fields) const = 0; // Swap two elements of a repeated field. - virtual void SwapElements(Message* message, - const FieldDescriptor* field, - int index1, - int index2) const = 0; + virtual void SwapElements(Message* message, const FieldDescriptor* field, + int index1, int index2) const = 0; // List all fields of the message which are currently set, except for unknown // fields, but including extension known to the parser (i.e. compiled in). @@ -513,22 +521,22 @@ class LIBPROTOBUF_EXPORT Reflection { // These get the value of a non-repeated field. They return the default // value for fields that aren't set. - virtual int32 GetInt32 (const Message& message, - const FieldDescriptor* field) const = 0; - virtual int64 GetInt64 (const Message& message, - const FieldDescriptor* field) const = 0; + virtual int32 GetInt32(const Message& message, + const FieldDescriptor* field) const = 0; + virtual int64 GetInt64(const Message& message, + const FieldDescriptor* field) const = 0; virtual uint32 GetUInt32(const Message& message, const FieldDescriptor* field) const = 0; virtual uint64 GetUInt64(const Message& message, const FieldDescriptor* field) const = 0; - virtual float GetFloat (const Message& message, - const FieldDescriptor* field) const = 0; + virtual float GetFloat(const Message& message, + const FieldDescriptor* field) const = 0; virtual double GetDouble(const Message& message, const FieldDescriptor* field) const = 0; - virtual bool GetBool (const Message& message, - const FieldDescriptor* field) const = 0; - virtual string GetString(const Message& message, - const FieldDescriptor* field) const = 0; + virtual bool GetBool(const Message& message, + const FieldDescriptor* field) const = 0; + virtual std::string GetString(const Message& message, + const FieldDescriptor* field) const = 0; virtual const EnumValueDescriptor* GetEnum( const Message& message, const FieldDescriptor* field) const = 0; @@ -537,8 +545,8 @@ class LIBPROTOBUF_EXPORT Reflection { // known value descriptor, a new value descriptor is created. (Such a value // will only be present when the new unknown-enum-value semantics are enabled // for a message.) - virtual int GetEnumValue( - const Message& message, const FieldDescriptor* field) const = 0; + virtual int GetEnumValue(const Message& message, + const FieldDescriptor* field) const = 0; // See MutableMessage() for the meaning of the "factory" parameter. virtual const Message& GetMessage(const Message& message, @@ -548,52 +556,52 @@ class LIBPROTOBUF_EXPORT Reflection { // Get a string value without copying, if possible. // // GetString() necessarily returns a copy of the string. This can be - // inefficient when the string is already stored in a string object in the - // underlying message. GetStringReference() will return a reference to the - // underlying string in this case. Otherwise, it will copy the string into - // *scratch and return that. + // inefficient when the std::string is already stored in a std::string object + // in the underlying message. GetStringReference() will return a reference to + // the underlying std::string in this case. Otherwise, it will copy the + // string into *scratch and return that. // // Note: It is perfectly reasonable and useful to write code like: - // str = reflection->GetStringReference(field, &str); + // str = reflection->GetStringReference(message, field, &str); // This line would ensure that only one copy of the string is made // regardless of the field's underlying representation. When initializing - // a newly-constructed string, though, it's just as fast and more readable - // to use code like: - // string str = reflection->GetString(message, field); - virtual const string& GetStringReference(const Message& message, - const FieldDescriptor* field, - string* scratch) const = 0; + // a newly-constructed string, though, it's just as fast and more + // readable to use code like: + // std::string str = reflection->GetString(message, field); + virtual const std::string& GetStringReference(const Message& message, + const FieldDescriptor* field, + std::string* scratch) const = 0; // Singular field mutators ----------------------------------------- // These mutate the value of a non-repeated field. - virtual void SetInt32 (Message* message, - const FieldDescriptor* field, int32 value) const = 0; - virtual void SetInt64 (Message* message, - const FieldDescriptor* field, int64 value) const = 0; - virtual void SetUInt32(Message* message, - const FieldDescriptor* field, uint32 value) const = 0; - virtual void SetUInt64(Message* message, - const FieldDescriptor* field, uint64 value) const = 0; - virtual void SetFloat (Message* message, - const FieldDescriptor* field, float value) const = 0; - virtual void SetDouble(Message* message, - const FieldDescriptor* field, double value) const = 0; - virtual void SetBool (Message* message, - const FieldDescriptor* field, bool value) const = 0; - virtual void SetString(Message* message, - const FieldDescriptor* field, - const string& value) const = 0; - virtual void SetEnum (Message* message, - const FieldDescriptor* field, - const EnumValueDescriptor* value) const = 0; + virtual void SetInt32(Message* message, const FieldDescriptor* field, + int32 value) const = 0; + virtual void SetInt64(Message* message, const FieldDescriptor* field, + int64 value) const = 0; + virtual void SetUInt32(Message* message, const FieldDescriptor* field, + uint32 value) const = 0; + virtual void SetUInt64(Message* message, const FieldDescriptor* field, + uint64 value) const = 0; + virtual void SetFloat(Message* message, const FieldDescriptor* field, + float value) const = 0; + virtual void SetDouble(Message* message, const FieldDescriptor* field, + double value) const = 0; + virtual void SetBool(Message* message, const FieldDescriptor* field, + bool value) const = 0; + virtual void SetString(Message* message, const FieldDescriptor* field, + const std::string& value) const = 0; + virtual void SetEnum(Message* message, const FieldDescriptor* field, + const EnumValueDescriptor* value) const = 0; // Set an enum field's value with an integer rather than EnumValueDescriptor. - // If the value does not correspond to a known enum value, either behavior is - // undefined (for proto2 messages), or the value is accepted silently for - // messages with new unknown-enum-value semantics. - virtual void SetEnumValue(Message* message, - const FieldDescriptor* field, + // For proto3 this is just setting the enum field to the value specified, for + // proto2 it's more complicated. If value is a known enum value the field is + // set as usual. If the value is unknown then it is added to the unknown field + // set. Note this matches the behavior of parsing unknown enum values. + // If multiple calls with unknown values happen than they are all added to the + // unknown field set in order of the calls. + virtual void SetEnumValue(Message* message, const FieldDescriptor* field, int value) const = 0; // Get a mutable pointer to a field with a message type. If a MessageFactory @@ -613,8 +621,7 @@ class LIBPROTOBUF_EXPORT Reflection { // sub_message, passing ownership to the message. If the field contained a // message, that message is deleted. If sub_message is NULL, the field is // cleared. - virtual void SetAllocatedMessage(Message* message, - Message* sub_message, + virtual void SetAllocatedMessage(Message* message, Message* sub_message, const FieldDescriptor* field) const = 0; // Releases the message specified by 'field' and returns the pointer, // ReleaseMessage() will return the message the message object if it exists. @@ -631,131 +638,126 @@ class LIBPROTOBUF_EXPORT Reflection { // Repeated field getters ------------------------------------------ // These get the value of one element of a repeated field. - virtual int32 GetRepeatedInt32 (const Message& message, - const FieldDescriptor* field, - int index) const = 0; - virtual int64 GetRepeatedInt64 (const Message& message, - const FieldDescriptor* field, - int index) const = 0; + virtual int32 GetRepeatedInt32(const Message& message, + const FieldDescriptor* field, + int index) const = 0; + virtual int64 GetRepeatedInt64(const Message& message, + const FieldDescriptor* field, + int index) const = 0; virtual uint32 GetRepeatedUInt32(const Message& message, const FieldDescriptor* field, int index) const = 0; virtual uint64 GetRepeatedUInt64(const Message& message, const FieldDescriptor* field, int index) const = 0; - virtual float GetRepeatedFloat (const Message& message, - const FieldDescriptor* field, - int index) const = 0; + virtual float GetRepeatedFloat(const Message& message, + const FieldDescriptor* field, + int index) const = 0; virtual double GetRepeatedDouble(const Message& message, const FieldDescriptor* field, int index) const = 0; - virtual bool GetRepeatedBool (const Message& message, - const FieldDescriptor* field, - int index) const = 0; - virtual string GetRepeatedString(const Message& message, - const FieldDescriptor* field, - int index) const = 0; + virtual bool GetRepeatedBool(const Message& message, + const FieldDescriptor* field, + int index) const = 0; + virtual std::string GetRepeatedString(const Message& message, + const FieldDescriptor* field, + int index) const = 0; virtual const EnumValueDescriptor* GetRepeatedEnum( - const Message& message, - const FieldDescriptor* field, int index) const = 0; + const Message& message, const FieldDescriptor* field, + int index) const = 0; // GetRepeatedEnumValue() returns an enum field's value as an integer rather // than an EnumValueDescriptor*. If the integer value does not correspond to a // known value descriptor, a new value descriptor is created. (Such a value // will only be present when the new unknown-enum-value semantics are enabled // for a message.) - virtual int GetRepeatedEnumValue( - const Message& message, - const FieldDescriptor* field, int index) const = 0; - virtual const Message& GetRepeatedMessage( - const Message& message, - const FieldDescriptor* field, int index) const = 0; + virtual int GetRepeatedEnumValue(const Message& message, + const FieldDescriptor* field, + int index) const = 0; + virtual const Message& GetRepeatedMessage(const Message& message, + const FieldDescriptor* field, + int index) const = 0; // See GetStringReference(), above. - virtual const string& GetRepeatedStringReference( - const Message& message, const FieldDescriptor* field, - int index, string* scratch) const = 0; + virtual const std::string& GetRepeatedStringReference( + const Message& message, const FieldDescriptor* field, int index, + std::string* scratch) const = 0; // Repeated field mutators ----------------------------------------- // These mutate the value of one element of a repeated field. - virtual void SetRepeatedInt32 (Message* message, - const FieldDescriptor* field, - int index, int32 value) const = 0; - virtual void SetRepeatedInt64 (Message* message, - const FieldDescriptor* field, - int index, int64 value) const = 0; - virtual void SetRepeatedUInt32(Message* message, - const FieldDescriptor* field, + virtual void SetRepeatedInt32(Message* message, const FieldDescriptor* field, + int index, int32 value) const = 0; + virtual void SetRepeatedInt64(Message* message, const FieldDescriptor* field, + int index, int64 value) const = 0; + virtual void SetRepeatedUInt32(Message* message, const FieldDescriptor* field, int index, uint32 value) const = 0; - virtual void SetRepeatedUInt64(Message* message, - const FieldDescriptor* field, + virtual void SetRepeatedUInt64(Message* message, const FieldDescriptor* field, int index, uint64 value) const = 0; - virtual void SetRepeatedFloat (Message* message, - const FieldDescriptor* field, - int index, float value) const = 0; - virtual void SetRepeatedDouble(Message* message, - const FieldDescriptor* field, + virtual void SetRepeatedFloat(Message* message, const FieldDescriptor* field, + int index, float value) const = 0; + virtual void SetRepeatedDouble(Message* message, const FieldDescriptor* field, int index, double value) const = 0; - virtual void SetRepeatedBool (Message* message, - const FieldDescriptor* field, - int index, bool value) const = 0; - virtual void SetRepeatedString(Message* message, - const FieldDescriptor* field, - int index, const string& value) const = 0; - virtual void SetRepeatedEnum(Message* message, - const FieldDescriptor* field, int index, + virtual void SetRepeatedBool(Message* message, const FieldDescriptor* field, + int index, bool value) const = 0; + virtual void SetRepeatedString(Message* message, const FieldDescriptor* field, + int index, const std::string& value) const = 0; + virtual void SetRepeatedEnum(Message* message, const FieldDescriptor* field, + int index, const EnumValueDescriptor* value) const = 0; // Set an enum field's value with an integer rather than EnumValueDescriptor. - // If the value does not correspond to a known enum value, either behavior is - // undefined (for proto2 messages), or the value is accepted silently for - // messages with new unknown-enum-value semantics. + // For proto3 this is just setting the enum field to the value specified, for + // proto2 it's more complicated. If value is a known enum value the field is + // set as usual. If the value is unknown then it is added to the unknown field + // set. Note this matches the behavior of parsing unknown enum values. + // If multiple calls with unknown values happen than they are all added to the + // unknown field set in order of the calls. virtual void SetRepeatedEnumValue(Message* message, const FieldDescriptor* field, int index, int value) const = 0; // Get a mutable pointer to an element of a repeated field with a message // type. - virtual Message* MutableRepeatedMessage( - Message* message, const FieldDescriptor* field, int index) const = 0; + virtual Message* MutableRepeatedMessage(Message* message, + const FieldDescriptor* field, + int index) const = 0; // Repeated field adders ------------------------------------------- // These add an element to a repeated field. - virtual void AddInt32 (Message* message, - const FieldDescriptor* field, int32 value) const = 0; - virtual void AddInt64 (Message* message, - const FieldDescriptor* field, int64 value) const = 0; - virtual void AddUInt32(Message* message, - const FieldDescriptor* field, uint32 value) const = 0; - virtual void AddUInt64(Message* message, - const FieldDescriptor* field, uint64 value) const = 0; - virtual void AddFloat (Message* message, - const FieldDescriptor* field, float value) const = 0; - virtual void AddDouble(Message* message, - const FieldDescriptor* field, double value) const = 0; - virtual void AddBool (Message* message, - const FieldDescriptor* field, bool value) const = 0; - virtual void AddString(Message* message, - const FieldDescriptor* field, - const string& value) const = 0; - virtual void AddEnum (Message* message, - const FieldDescriptor* field, - const EnumValueDescriptor* value) const = 0; - // Set an enum field's value with an integer rather than EnumValueDescriptor. - // If the value does not correspond to a known enum value, either behavior is - // undefined (for proto2 messages), or the value is accepted silently for - // messages with new unknown-enum-value semantics. - virtual void AddEnumValue(Message* message, - const FieldDescriptor* field, + virtual void AddInt32(Message* message, const FieldDescriptor* field, + int32 value) const = 0; + virtual void AddInt64(Message* message, const FieldDescriptor* field, + int64 value) const = 0; + virtual void AddUInt32(Message* message, const FieldDescriptor* field, + uint32 value) const = 0; + virtual void AddUInt64(Message* message, const FieldDescriptor* field, + uint64 value) const = 0; + virtual void AddFloat(Message* message, const FieldDescriptor* field, + float value) const = 0; + virtual void AddDouble(Message* message, const FieldDescriptor* field, + double value) const = 0; + virtual void AddBool(Message* message, const FieldDescriptor* field, + bool value) const = 0; + virtual void AddString(Message* message, const FieldDescriptor* field, + const std::string& value) const = 0; + virtual void AddEnum(Message* message, const FieldDescriptor* field, + const EnumValueDescriptor* value) const = 0; + // Add an integer value to a repeated enum field rather than + // EnumValueDescriptor. For proto3 this is just setting the enum field to the + // value specified, for proto2 it's more complicated. If value is a known enum + // value the field is set as usual. If the value is unknown then it is added + // to the unknown field set. Note this matches the behavior of parsing unknown + // enum values. If multiple calls with unknown values happen than they are all + // added to the unknown field set in order of the calls. + virtual void AddEnumValue(Message* message, const FieldDescriptor* field, int value) const = 0; // See MutableMessage() for comments on the "factory" parameter. - virtual Message* AddMessage(Message* message, - const FieldDescriptor* field, + virtual Message* AddMessage(Message* message, const FieldDescriptor* field, MessageFactory* factory = NULL) const = 0; // Appends an already-allocated object 'new_entry' to the repeated field - // specifyed by 'field' passing ownership to the message. + // specified by 'field' passing ownership to the message. // TODO(tmarek): Make virtual after all subclasses have been // updated. virtual void AddAllocatedMessage(Message* message, @@ -777,7 +779,7 @@ class LIBPROTOBUF_EXPORT Reflection { // CPPTYPE_FLOAT float // CPPTYPE_BOOL bool // CPPTYPE_ENUM generated enum type or int32 - // CPPTYPE_STRING string + // CPPTYPE_STRING std::string // CPPTYPE_MESSAGE generated message type or google::protobuf::Message // // A RepeatedFieldRef object can be copied and the resulted object will point @@ -785,15 +787,15 @@ class LIBPROTOBUF_EXPORT Reflection { // long as the message is not destroyed. // // Note that to use this method users need to include the header file - // "google/protobuf/reflection.h" (which defines the RepeatedFieldRef + // "net/proto2/public/reflection.h" (which defines the RepeatedFieldRef // class templates). - template - RepeatedFieldRef GetRepeatedFieldRef( - const Message& message, const FieldDescriptor* field) const; + template + RepeatedFieldRef GetRepeatedFieldRef(const Message& message, + const FieldDescriptor* field) const; // Like GetRepeatedFieldRef() but return an object that can also be used // manipulate the underlying repeated field. - template + template MutableRepeatedFieldRef GetMutableRepeatedFieldRef( Message* message, const FieldDescriptor* field) const; @@ -814,43 +816,43 @@ class LIBPROTOBUF_EXPORT Reflection { // DEPRECATED. Please use GetRepeatedFieldRef(). // // for T = Cord and all protobuf scalar types except enums. - template - PROTOBUF_RUNTIME_DEPRECATED("Please use GetRepeatedFieldRef() instead") - const RepeatedField& GetRepeatedField( - const Message&, const FieldDescriptor*) const; + template + PROTOBUF_DEPRECATED_MSG("Please use GetRepeatedFieldRef() instead") + const RepeatedField& GetRepeatedField(const Message&, + const FieldDescriptor*) const; // DEPRECATED. Please use GetMutableRepeatedFieldRef(). // // for T = Cord and all protobuf scalar types except enums. - template - PROTOBUF_RUNTIME_DEPRECATED("Please use GetMutableRepeatedFieldRef() instead") - RepeatedField* MutableRepeatedField( - Message*, const FieldDescriptor*) const; + template + PROTOBUF_DEPRECATED_MSG("Please use GetMutableRepeatedFieldRef() instead") + RepeatedField* MutableRepeatedField(Message*, + const FieldDescriptor*) const; // DEPRECATED. Please use GetRepeatedFieldRef(). // - // for T = string, google::protobuf::internal::StringPieceField + // for T = std::string, google::protobuf::internal::StringPieceField // google::protobuf::Message & descendants. - template - PROTOBUF_RUNTIME_DEPRECATED("Please use GetRepeatedFieldRef() instead") - const RepeatedPtrField& GetRepeatedPtrField( - const Message&, const FieldDescriptor*) const; + template + PROTOBUF_DEPRECATED_MSG("Please use GetRepeatedFieldRef() instead") + const RepeatedPtrField& GetRepeatedPtrField(const Message&, + const FieldDescriptor*) const; // DEPRECATED. Please use GetMutableRepeatedFieldRef(). // - // for T = string, google::protobuf::internal::StringPieceField + // for T = std::string, google::protobuf::internal::StringPieceField // google::protobuf::Message & descendants. - template - PROTOBUF_RUNTIME_DEPRECATED("Please use GetMutableRepeatedFieldRef() instead") - RepeatedPtrField* MutableRepeatedPtrField( - Message*, const FieldDescriptor*) const; + template + PROTOBUF_DEPRECATED_MSG("Please use GetMutableRepeatedFieldRef() instead") + RepeatedPtrField* MutableRepeatedPtrField(Message*, + const FieldDescriptor*) const; // Extensions ---------------------------------------------------------------- // Try to find an extension of this message type by fully-qualified field // name. Returns NULL if no extension is known for this name or number. virtual const FieldDescriptor* FindKnownExtensionByName( - const string& name) const = 0; + const std::string& name) const = 0; // Try to find an extension of this message type by field number. // Returns NULL if no extension is known for this name or number. @@ -917,8 +919,8 @@ class LIBPROTOBUF_EXPORT Reflection { const Message& message, const FieldDescriptor* field, FieldDescriptor::CppType cpptype, int ctype, const Descriptor* message_type) const { - return MutableRawRepeatedField( - const_cast(&message), field, cpptype, ctype, message_type); + return MutableRawRepeatedField(const_cast(&message), field, + cpptype, ctype, message_type); } // The following methods are used to implement (Mutable)RepeatedFieldRef. @@ -937,10 +939,10 @@ class LIBPROTOBUF_EXPORT Reflection { // "cpp_type"/"message_type" is consistent with the actual type of the field. // We use 1 routine rather than 2 (const vs mutable) because it is protected // and it doesn't change the message. - virtual void* RepeatedFieldData( - Message* message, const FieldDescriptor* field, - FieldDescriptor::CppType cpp_type, - const Descriptor* message_type) const; + virtual void* RepeatedFieldData(Message* message, + const FieldDescriptor* field, + FieldDescriptor::CppType cpp_type, + const Descriptor* message_type) const; // The returned pointer should point to a singleton instance which implements // the RepeatedFieldAccessor interface. @@ -948,26 +950,29 @@ class LIBPROTOBUF_EXPORT Reflection { const FieldDescriptor* field) const; private: - template + template friend class RepeatedFieldRef; - template + template friend class MutableRepeatedFieldRef; - friend class ::google::protobuf::python::MapReflectionFriend; + friend class python::MapReflectionFriend; #define GOOGLE_PROTOBUF_HAS_CEL_MAP_REFLECTION_FRIEND - friend class ::google::protobuf::expr::CelMapReflectionFriend; + friend class expr::CelMapReflectionFriend; friend class internal::MapFieldReflectionTest; friend class internal::MapKeySorter; friend class internal::WireFormat; friend class internal::ReflectionOps; + // Needed for implementing text format for map. + friend class internal::MapFieldPrinterHelper; + friend class internal::ReflectionAccessor; - // Special version for specialized implementations of string. We can't call - // MutableRawRepeatedField directly here because we don't have access to + // Special version for specialized implementations of string. We can't + // call MutableRawRepeatedField directly here because we don't have access to // FieldOptions::* which are defined in descriptor.pb.h. Including that // file here is not possible because it would cause a circular include cycle. // We use 1 routine rather than 2 (const vs mutable) because it is private // and mutable a repeated string field doesn't change the message. - void* MutableRawRepeatedString( - Message* message, const FieldDescriptor* field, bool is_string) const; + void* MutableRawRepeatedString(Message* message, const FieldDescriptor* field, + bool is_string) const; friend class MapReflectionTester; // TODO(jieluo) - make the map APIs pure virtual after updating @@ -1000,16 +1005,14 @@ class LIBPROTOBUF_EXPORT Reflection { // Returns a MapIterator referring to the first element in the map field. // If the map field is empty, this function returns the same as // reflection::MapEnd. Mutation to the field may invalidate the iterator. - virtual MapIterator MapBegin( - Message* message, - const FieldDescriptor* field) const; + virtual MapIterator MapBegin(Message* message, + const FieldDescriptor* field) const; // Returns a MapIterator referring to the theoretical element that would // follow the last element in the map field. It does not point to any // real element. Mutation to the field may invalidate the iterator. - virtual MapIterator MapEnd( - Message* message, - const FieldDescriptor* field) const; + virtual MapIterator MapEnd(Message* message, + const FieldDescriptor* field) const; // Get the number of pair of a map field. The result may be // different from FieldSize which can have duplicate keys. @@ -1020,16 +1023,21 @@ class LIBPROTOBUF_EXPORT Reflection { // Help method for MapIterator. friend class MapIterator; - virtual internal::MapFieldBase* MapData( + virtual internal::MapFieldBase* MutableMapData( Message* /* message */, const FieldDescriptor* /* field */) const { return NULL; } + virtual const internal::MapFieldBase* GetMapData( + const Message& /* message */, const FieldDescriptor* /* field */) const { + return NULL; + } + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Reflection); }; // Abstract interface for a factory for message objects. -class LIBPROTOBUF_EXPORT MessageFactory { +class PROTOBUF_EXPORT MessageFactory { public: inline MessageFactory() {} virtual ~MessageFactory(); @@ -1079,7 +1087,7 @@ class LIBPROTOBUF_EXPORT MessageFactory { // built lazily, so we can't register types by their descriptor until we // know that the descriptor exists. |filename| must be a permanent string. static void InternalRegisterGeneratedFile( - const char* filename, void (*register_messages)(const string&)); + const google::protobuf::internal::DescriptorTable* table); // For internal use only: Registers a message type. Called only by the // functions which are registered with InternalRegisterGeneratedFile(), @@ -1092,16 +1100,15 @@ class LIBPROTOBUF_EXPORT MessageFactory { GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFactory); }; -#define DECLARE_GET_REPEATED_FIELD(TYPE) \ -template<> \ -LIBPROTOBUF_EXPORT \ -const RepeatedField& Reflection::GetRepeatedField( \ - const Message& message, const FieldDescriptor* field) const; \ - \ -template<> \ -LIBPROTOBUF_EXPORT \ -RepeatedField* Reflection::MutableRepeatedField( \ - Message* message, const FieldDescriptor* field) const; +#define DECLARE_GET_REPEATED_FIELD(TYPE) \ + template <> \ + PROTOBUF_EXPORT const RepeatedField& \ + Reflection::GetRepeatedField(const Message& message, \ + const FieldDescriptor* field) const; \ + \ + template <> \ + PROTOBUF_EXPORT RepeatedField* Reflection::MutableRepeatedField( \ + Message * message, const FieldDescriptor* field) const; DECLARE_GET_REPEATED_FIELD(int32) DECLARE_GET_REPEATED_FIELD(int64) @@ -1113,64 +1120,123 @@ DECLARE_GET_REPEATED_FIELD(bool) #undef DECLARE_GET_REPEATED_FIELD +// Tries to downcast this message to a generated message type. Returns NULL if +// this class is not an instance of T. This works even if RTTI is disabled. +// +// This also has the effect of creating a strong reference to T that will +// prevent the linker from stripping it out at link time. This can be important +// if you are using a DynamicMessageFactory that delegates to the generated +// factory. +template +const T* DynamicCastToGenerated(const Message* from) { + // Compile-time assert that T is a generated type that has a + // default_instance() accessor, but avoid actually calling it. + const T& (*get_default_instance)() = &T::default_instance; + (void)get_default_instance; + + // Compile-time assert that T is a subclass of google::protobuf::Message. + const Message* unused = static_cast(nullptr); + (void)unused; + +#ifdef GOOGLE_PROTOBUF_NO_RTTI + bool ok = T::default_instance().GetReflection() == from->GetReflection(); + return ok ? down_cast(from) : nullptr; +#else + return dynamic_cast(from); +#endif +} + +template +T* DynamicCastToGenerated(Message* from) { + const Message* message_const = from; + return const_cast(DynamicCastToGenerated(message_const)); +} + +// Call this function to ensure that this message's reflection is linked into +// the binary: +// +// google::protobuf::LinkMessageReflection(); +// +// This will ensure that the following lookup will succeed: +// +// DescriptorPool::generated_pool()->FindMessageTypeByName("FooMessage"); +// +// As a side-effect, it will also guarantee that anything else from the same +// .proto file will also be available for lookup in the generated pool. +// +// This function does not actually register the message, so it does not need +// to be called before the lookup. However it does need to occur in a function +// that cannot be stripped from the binary (ie. it must be reachable from main). +// +// Best practice is to call this function as close as possible to where the +// reflection is actually needed. This function is very cheap to call, so you +// should not need to worry about its runtime overhead except in the tightest +// of loops (on x86-64 it compiles into two "mov" instructions). +template +void LinkMessageReflection() { + typedef const T& GetDefaultInstanceFunction(); + GetDefaultInstanceFunction* volatile unused = &T::default_instance; + (void)&unused; // Use address to avoid an extra load of volatile variable. +} + // ============================================================================= // Implementation details for {Get,Mutable}RawRepeatedPtrField. We provide -// specializations for , and and handle -// everything else with the default template which will match any type having -// a method with signature "static const google::protobuf::Descriptor* descriptor()". -// Such a type presumably is a descendant of google::protobuf::Message. +// specializations for , and and +// handle everything else with the default template which will match any type +// having a method with signature "static const google::protobuf::Descriptor* +// descriptor()". Such a type presumably is a descendant of google::protobuf::Message. -template<> -inline const RepeatedPtrField& Reflection::GetRepeatedPtrField( +template <> +inline const RepeatedPtrField& +Reflection::GetRepeatedPtrField( const Message& message, const FieldDescriptor* field) const { - return *static_cast* >( + return *static_cast*>( MutableRawRepeatedString(const_cast(&message), field, true)); } -template<> -inline RepeatedPtrField* Reflection::MutableRepeatedPtrField( +template <> +inline RepeatedPtrField* +Reflection::MutableRepeatedPtrField( Message* message, const FieldDescriptor* field) const { - return static_cast* >( + return static_cast*>( MutableRawRepeatedString(message, field, true)); } // ----- -template<> +template <> inline const RepeatedPtrField& Reflection::GetRepeatedPtrField( const Message& message, const FieldDescriptor* field) const { - return *static_cast* >( - GetRawRepeatedField(message, field, FieldDescriptor::CPPTYPE_MESSAGE, - -1, NULL)); + return *static_cast*>(GetRawRepeatedField( + message, field, FieldDescriptor::CPPTYPE_MESSAGE, -1, NULL)); } -template<> +template <> inline RepeatedPtrField* Reflection::MutableRepeatedPtrField( Message* message, const FieldDescriptor* field) const { - return static_cast* >( - MutableRawRepeatedField(message, field, - FieldDescriptor::CPPTYPE_MESSAGE, -1, - NULL)); + return static_cast*>(MutableRawRepeatedField( + message, field, FieldDescriptor::CPPTYPE_MESSAGE, -1, NULL)); } -template +template inline const RepeatedPtrField& Reflection::GetRepeatedPtrField( const Message& message, const FieldDescriptor* field) const { - return *static_cast* >( - GetRawRepeatedField(message, field, FieldDescriptor::CPPTYPE_MESSAGE, - -1, PB::default_instance().GetDescriptor())); + return *static_cast*>( + GetRawRepeatedField(message, field, FieldDescriptor::CPPTYPE_MESSAGE, -1, + PB::default_instance().GetDescriptor())); } -template +template inline RepeatedPtrField* Reflection::MutableRepeatedPtrField( Message* message, const FieldDescriptor* field) const { - return static_cast* >( - MutableRawRepeatedField(message, field, - FieldDescriptor::CPPTYPE_MESSAGE, -1, - PB::default_instance().GetDescriptor())); + return static_cast*>( + MutableRawRepeatedField(message, field, FieldDescriptor::CPPTYPE_MESSAGE, + -1, PB::default_instance().GetDescriptor())); } } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_MESSAGE_H__ diff --git a/third_party/protobuf/src/google/protobuf/message_lite.cc b/third_party/protobuf/src/google/protobuf/message_lite.cc index 123b142d..e8f13440 100644 --- a/third_party/protobuf/src/google/protobuf/message_lite.cc +++ b/third_party/protobuf/src/google/protobuf/message_lite.cc @@ -34,25 +34,39 @@ // Sanjay Ghemawat, Jeff Dean, and others. #include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include +#include #include #include #include -#include -#include -#include -#include -#include + +#include #include +#include + namespace google { namespace protobuf { -string MessageLite::InitializationErrorString() const { +std::string MessageLite::InitializationErrorString() const { return "(cannot determine missing fields for lite message)"; } +std::string MessageLite::DebugString() const { + std::uintptr_t address = reinterpret_cast(this); + return StrCat("MessageLite at 0x", strings::Hex(address)); +} + namespace { // When serializing, we first compute the byte size, then serialize the message. @@ -71,12 +85,13 @@ void ByteSizeConsistencyError(size_t byte_size_before_serialization, GOOGLE_CHECK_EQ(bytes_produced_by_serialization, byte_size_before_serialization) << "Byte size calculation and serialization were inconsistent. This " "may indicate a bug in protocol buffers or it may be caused by " - "concurrent modification of " << message.GetTypeName() << "."; + "concurrent modification of " + << message.GetTypeName() << "."; GOOGLE_LOG(FATAL) << "This shouldn't be called if all the sizes are equal."; } -string InitializationErrorMessage(const char* action, - const MessageLite& message) { +std::string InitializationErrorMessage(const char* action, + const MessageLite& message) { // Note: We want to avoid depending on strutil in the lite library, otherwise // we'd use: // @@ -86,7 +101,7 @@ string InitializationErrorMessage(const char* action, // action, message.GetTypeName(), // message.InitializationErrorString()); - string result; + std::string result; result += "Can't "; result += action; result += " message of type \""; @@ -96,64 +111,97 @@ string InitializationErrorMessage(const char* action, return result; } -// Several of the Parse methods below just do one thing and then call another -// method. In a naive implementation, we might have ParseFromString() call -// ParseFromArray() which would call ParseFromZeroCopyStream() which would call -// ParseFromCodedStream() which would call MergeFromCodedStream() which would -// call MergePartialFromCodedStream(). However, when parsing very small -// messages, every function call introduces significant overhead. To avoid -// this without reproducing code, we use these forced-inline helpers. -GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool InlineMergeFromCodedStream( - io::CodedInputStream* input, MessageLite* message); -GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool InlineParseFromCodedStream( - io::CodedInputStream* input, MessageLite* message); -GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool InlineParsePartialFromCodedStream( - io::CodedInputStream* input, MessageLite* message); -GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool InlineParseFromArray( - const void* data, int size, MessageLite* message); -GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool InlineParsePartialFromArray( - const void* data, int size, MessageLite* message); - -inline bool InlineMergeFromCodedStream(io::CodedInputStream* input, - MessageLite* message) { - if (!message->MergePartialFromCodedStream(input)) return false; - if (!message->IsInitialized()) { - GOOGLE_LOG(ERROR) << InitializationErrorMessage("parse", *message); - return false; - } - return true; -} - -inline bool InlineParseFromCodedStream(io::CodedInputStream* input, - MessageLite* message) { - message->Clear(); - return InlineMergeFromCodedStream(input, message); -} - -inline bool InlineParsePartialFromCodedStream(io::CodedInputStream* input, - MessageLite* message) { - message->Clear(); - return message->MergePartialFromCodedStream(input); -} - -inline bool InlineParseFromArray( - const void* data, int size, MessageLite* message) { - io::CodedInputStream input(reinterpret_cast(data), size); - return InlineParseFromCodedStream(&input, message) && - input.ConsumedEntireMessage(); -} - -inline bool InlineParsePartialFromArray( - const void* data, int size, MessageLite* message) { - io::CodedInputStream input(reinterpret_cast(data), size); - return InlineParsePartialFromCodedStream(&input, message) && - input.ConsumedEntireMessage(); +inline StringPiece as_string_view(const void* data, int size) { + return StringPiece(static_cast(data), size); } } // namespace +void MessageLite::LogInitializationErrorMessage() const { + GOOGLE_LOG(ERROR) << InitializationErrorMessage("parse", *this); +} -MessageLite* MessageLite::New(::google::protobuf::Arena* arena) const { +namespace internal { + +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + +template +bool MergePartialFromImpl(StringPiece input, MessageLite* msg) { + const char* ptr; + internal::ParseContext ctx(io::CodedInputStream::GetDefaultRecursionLimit(), + aliasing, &ptr, input); + ptr = msg->_InternalParse(ptr, &ctx); + // ctx has an explicit limit set (length of string_view). + return ptr && ctx.EndedAtLimit(); +} + +template +bool MergePartialFromImpl(io::ZeroCopyInputStream* input, MessageLite* msg) { + const char* ptr; + internal::ParseContext ctx(io::CodedInputStream::GetDefaultRecursionLimit(), + aliasing, &ptr, input); + ptr = msg->_InternalParse(ptr, &ctx); + // ctx has no explicit limit (hence we end on end of stream) + return ptr && ctx.EndedAtEndOfStream(); +} + +template +bool MergePartialFromImpl(BoundedZCIS input, MessageLite* msg) { + const char* ptr; + internal::ParseContext ctx(io::CodedInputStream::GetDefaultRecursionLimit(), + aliasing, &ptr, input.zcis, input.limit); + ptr = msg->_InternalParse(ptr, &ctx); + if (PROTOBUF_PREDICT_FALSE(!ptr)) return false; + ctx.BackUp(ptr); + return ctx.EndedAtLimit(); +} + +#else // !GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + +inline bool InlineMergePartialEntireStream(io::CodedInputStream* cis, + MessageLite* message, + bool aliasing) { + return message->MergePartialFromCodedStream(cis) && + cis->ConsumedEntireMessage(); +} + +template +bool MergePartialFromImpl(StringPiece input, MessageLite* msg) { + io::CodedInputStream decoder(reinterpret_cast(input.data()), + input.size()); + return InlineMergePartialEntireStream(&decoder, msg, aliasing); +} + +template +bool MergePartialFromImpl(BoundedZCIS input, MessageLite* msg) { + io::CodedInputStream decoder(input.zcis); + decoder.PushLimit(input.limit); + return InlineMergePartialEntireStream(&decoder, msg, aliasing) && + decoder.BytesUntilLimit() == 0; +} + +template +bool MergePartialFromImpl(io::ZeroCopyInputStream* input, MessageLite* msg) { + io::CodedInputStream decoder(input); + return InlineMergePartialEntireStream(&decoder, msg, aliasing); +} + +#endif // !GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + +template bool MergePartialFromImpl(StringPiece input, + MessageLite* msg); +template bool MergePartialFromImpl(StringPiece input, + MessageLite* msg); +template bool MergePartialFromImpl(io::ZeroCopyInputStream* input, + MessageLite* msg); +template bool MergePartialFromImpl(io::ZeroCopyInputStream* input, + MessageLite* msg); +template bool MergePartialFromImpl(BoundedZCIS input, MessageLite* msg); +template bool MergePartialFromImpl(BoundedZCIS input, MessageLite* msg); + +} // namespace internal + +MessageLite* MessageLite::New(Arena* arena) const { MessageLite* message = New(); if (arena != NULL) { arena->Own(message); @@ -161,70 +209,138 @@ MessageLite* MessageLite::New(::google::protobuf::Arena* arena) const { return message; } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +class ZeroCopyCodedInputStream : public io::ZeroCopyInputStream { + public: + ZeroCopyCodedInputStream(io::CodedInputStream* cis) : cis_(cis) {} + bool Next(const void** data, int* size) final { + if (!cis_->GetDirectBufferPointer(data, size)) return false; + cis_->Skip(*size); + return true; + } + void BackUp(int count) final { cis_->Advance(-count); } + bool Skip(int count) final { return cis_->Skip(count); } + int64 ByteCount() const final { return 0; } + + bool aliasing_enabled() { return cis_->aliasing_enabled_; } + + private: + io::CodedInputStream* cis_; +}; + +bool MessageLite::MergePartialFromCodedStream(io::CodedInputStream* input) { + ZeroCopyCodedInputStream zcis(input); + const char* ptr; + internal::ParseContext ctx(input->RecursionBudget(), zcis.aliasing_enabled(), + &ptr, &zcis); + // MergePartialFromCodedStream allows terminating the wireformat by 0 or + // end-group tag. Leaving it up to the caller to verify correct ending by + // calling LastTagWas on input. We need to maintain this behavior. + ctx.TrackCorrectEnding(); + ctx.data().pool = input->GetExtensionPool(); + ctx.data().factory = input->GetExtensionFactory(); + ptr = _InternalParse(ptr, &ctx); + if (PROTOBUF_PREDICT_FALSE(!ptr)) return false; + ctx.BackUp(ptr); + if (!ctx.EndedAtEndOfStream()) { + GOOGLE_DCHECK(ctx.LastTag() != 1); // We can't end on a pushed limit. + if (ctx.IsExceedingLimit(ptr)) return false; + input->SetLastTag(ctx.LastTag()); + return true; + } + input->SetConsumed(); + return true; +} +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + bool MessageLite::MergeFromCodedStream(io::CodedInputStream* input) { - return InlineMergeFromCodedStream(input, this); + return MergePartialFromCodedStream(input) && IsInitializedWithErrors(); } bool MessageLite::ParseFromCodedStream(io::CodedInputStream* input) { - return InlineParseFromCodedStream(input, this); + Clear(); + return MergeFromCodedStream(input); } bool MessageLite::ParsePartialFromCodedStream(io::CodedInputStream* input) { - return InlineParsePartialFromCodedStream(input, this); + Clear(); + return MergePartialFromCodedStream(input); } bool MessageLite::ParseFromZeroCopyStream(io::ZeroCopyInputStream* input) { - io::CodedInputStream decoder(input); - return ParseFromCodedStream(&decoder) && decoder.ConsumedEntireMessage(); + return ParseFrom(input); } bool MessageLite::ParsePartialFromZeroCopyStream( io::ZeroCopyInputStream* input) { - io::CodedInputStream decoder(input); - return ParsePartialFromCodedStream(&decoder) && - decoder.ConsumedEntireMessage(); + return ParseFrom(input); } -bool MessageLite::ParseFromBoundedZeroCopyStream( +bool MessageLite::MergePartialFromBoundedZeroCopyStream( io::ZeroCopyInputStream* input, int size) { - io::CodedInputStream decoder(input); - decoder.PushLimit(size); - return ParseFromCodedStream(&decoder) && - decoder.ConsumedEntireMessage() && - decoder.BytesUntilLimit() == 0; + return ParseFrom(internal::BoundedZCIS{input, size}); +} + +bool MessageLite::MergeFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input, + int size) { + return ParseFrom(internal::BoundedZCIS{input, size}); +} + +bool MessageLite::ParseFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input, + int size) { + return ParseFrom(internal::BoundedZCIS{input, size}); } bool MessageLite::ParsePartialFromBoundedZeroCopyStream( io::ZeroCopyInputStream* input, int size) { - io::CodedInputStream decoder(input); - decoder.PushLimit(size); - return ParsePartialFromCodedStream(&decoder) && - decoder.ConsumedEntireMessage() && - decoder.BytesUntilLimit() == 0; + return ParseFrom(internal::BoundedZCIS{input, size}); } -bool MessageLite::ParseFromString(const string& data) { - return InlineParseFromArray(data.data(), data.size(), this); +bool MessageLite::ParseFromString(const std::string& data) { + return ParseFrom(data); } -bool MessageLite::ParsePartialFromString(const string& data) { - return InlineParsePartialFromArray(data.data(), data.size(), this); +bool MessageLite::ParsePartialFromString(const std::string& data) { + return ParseFrom(data); } bool MessageLite::ParseFromArray(const void* data, int size) { - return InlineParseFromArray(data, size, this); + return ParseFrom(as_string_view(data, size)); } bool MessageLite::ParsePartialFromArray(const void* data, int size) { - return InlineParsePartialFromArray(data, size, this); + return ParseFrom(as_string_view(data, size)); +} + +bool MessageLite::MergeFromString(const std::string& data) { + return ParseFrom(data); } // =================================================================== uint8* MessageLite::SerializeWithCachedSizesToArray(uint8* target) const { - return InternalSerializeWithCachedSizesToArray( - io::CodedOutputStream::IsDefaultSerializationDeterministic(), target); + const internal::SerializationTable* table = + static_cast(InternalGetTable()); + auto deterministic = + io::CodedOutputStream::IsDefaultSerializationDeterministic(); + if (table) { + return internal::TableSerializeToArray(*this, table, deterministic, target); + } else { + if (deterministic) { + // We only optimize this when using optimize_for = SPEED. In other cases + // we just use the CodedOutputStream path. + int size = GetCachedSize(); + io::ArrayOutputStream out(target, size); + io::CodedOutputStream coded_out(&out); + coded_out.SetSerializationDeterministic(true); + SerializeWithCachedSizes(&coded_out); + GOOGLE_CHECK(!coded_out.HadError()); + return target + size; + } else { + return InternalSerializeWithCachedSizesToArray(target); + } + } } bool MessageLite::SerializeToCodedStream(io::CodedOutputStream* output) const { @@ -236,33 +352,34 @@ bool MessageLite::SerializePartialToCodedStream( io::CodedOutputStream* output) const { const size_t size = ByteSizeLong(); // Force size to be cached. if (size > INT_MAX) { - GOOGLE_LOG(ERROR) << "Exceeded maximum protobuf size of 2GB: " << size; + GOOGLE_LOG(ERROR) << GetTypeName() + << " exceeded maximum protobuf size of 2GB: " << size; return false; } - uint8* buffer = output->GetDirectBufferForNBytesAndAdvance(size); - if (buffer != NULL) { - uint8* end = InternalSerializeWithCachedSizesToArray( - output->IsSerializationDeterministic(), buffer); - if (end - buffer != size) { - ByteSizeConsistencyError(size, ByteSizeLong(), end - buffer, *this); + if (!output->IsSerializationDeterministic()) { + uint8* buffer = output->GetDirectBufferForNBytesAndAdvance(size); + if (buffer != nullptr) { + uint8* end = InternalSerializeWithCachedSizesToArray(buffer); + if (end - buffer != size) { + ByteSizeConsistencyError(size, ByteSizeLong(), end - buffer, *this); + } + return true; } - return true; - } else { - int original_byte_count = output->ByteCount(); - SerializeWithCachedSizes(output); - if (output->HadError()) { - return false; - } - int final_byte_count = output->ByteCount(); - - if (final_byte_count - original_byte_count != size) { - ByteSizeConsistencyError(size, ByteSizeLong(), - final_byte_count - original_byte_count, *this); - } - - return true; } + int original_byte_count = output->ByteCount(); + SerializeWithCachedSizes(output); + if (output->HadError()) { + return false; + } + int final_byte_count = output->ByteCount(); + + if (final_byte_count - original_byte_count != size) { + ByteSizeConsistencyError(size, ByteSizeLong(), + final_byte_count - original_byte_count, *this); + } + + return true; } bool MessageLite::SerializeToZeroCopyStream( @@ -277,16 +394,17 @@ bool MessageLite::SerializePartialToZeroCopyStream( return SerializePartialToCodedStream(&encoder); } -bool MessageLite::AppendToString(string* output) const { +bool MessageLite::AppendToString(std::string* output) const { GOOGLE_DCHECK(IsInitialized()) << InitializationErrorMessage("serialize", *this); return AppendPartialToString(output); } -bool MessageLite::AppendPartialToString(string* output) const { +bool MessageLite::AppendPartialToString(std::string* output) const { size_t old_size = output->size(); size_t byte_size = ByteSizeLong(); if (byte_size > INT_MAX) { - GOOGLE_LOG(ERROR) << "Exceeded maximum protobuf size of 2GB: " << byte_size; + GOOGLE_LOG(ERROR) << GetTypeName() + << " exceeded maximum protobuf size of 2GB: " << byte_size; return false; } @@ -300,12 +418,12 @@ bool MessageLite::AppendPartialToString(string* output) const { return true; } -bool MessageLite::SerializeToString(string* output) const { +bool MessageLite::SerializeToString(std::string* output) const { output->clear(); return AppendToString(output); } -bool MessageLite::SerializePartialToString(string* output) const { +bool MessageLite::SerializePartialToString(std::string* output) const { output->clear(); return AppendPartialToString(output); } @@ -316,7 +434,12 @@ bool MessageLite::SerializeToArray(void* data, int size) const { } bool MessageLite::SerializePartialToArray(void* data, int size) const { - int byte_size = ByteSizeLong(); + const size_t byte_size = ByteSizeLong(); + if (byte_size > INT_MAX) { + GOOGLE_LOG(ERROR) << GetTypeName() + << " exceeded maximum protobuf size of 2GB: " << byte_size; + return false; + } if (size < byte_size) return false; uint8* start = reinterpret_cast(data); uint8* end = SerializeWithCachedSizesToArray(start); @@ -326,21 +449,19 @@ bool MessageLite::SerializePartialToArray(void* data, int size) const { return true; } -string MessageLite::SerializeAsString() const { +std::string MessageLite::SerializeAsString() const { // If the compiler implements the (Named) Return Value Optimization, // the local variable 'output' will not actually reside on the stack // of this function, but will be overlaid with the object that the // caller supplied for the return value to be constructed in. - string output; - if (!AppendToString(&output)) - output.clear(); + std::string output; + if (!AppendToString(&output)) output.clear(); return output; } -string MessageLite::SerializePartialAsString() const { - string output; - if (!AppendPartialToString(&output)) - output.clear(); +std::string MessageLite::SerializePartialAsString() const { + std::string output; + if (!AppendPartialToString(&output)) output.clear(); return output; } @@ -359,7 +480,7 @@ void MessageLite::SerializeWithCachedSizes( // generated code for maximum speed. If the proto is optimized for size or // is lite, then we need to specialize this to avoid infinite recursion. uint8* MessageLite::InternalSerializeWithCachedSizesToArray( - bool deterministic, uint8* target) const { + uint8* target) const { const internal::SerializationTable* table = static_cast(InternalGetTable()); if (table == NULL) { @@ -368,19 +489,19 @@ uint8* MessageLite::InternalSerializeWithCachedSizesToArray( int size = GetCachedSize(); io::ArrayOutputStream out(target, size); io::CodedOutputStream coded_out(&out); - coded_out.SetSerializationDeterministic(deterministic); SerializeWithCachedSizes(&coded_out); GOOGLE_CHECK(!coded_out.HadError()); return target + size; } else { - return internal::TableSerializeToArray(*this, table, deterministic, target); + return internal::TableSerializeToArray(*this, table, false, target); } } namespace internal { -template<> + +template <> MessageLite* GenericTypeHandler::NewFromPrototype( - const MessageLite* prototype, google::protobuf::Arena* arena) { + const MessageLite* prototype, Arena* arena) { return prototype->New(arena); } template <> @@ -388,19 +509,12 @@ void GenericTypeHandler::Merge(const MessageLite& from, MessageLite* to) { to->CheckTypeAndMergeFrom(from); } -template<> -void GenericTypeHandler::Merge(const string& from, - string* to) { +template <> +void GenericTypeHandler::Merge(const std::string& from, + std::string* to) { *to = from; } -bool proto3_preserve_unknown_ = true; - -void SetProto3PreserveUnknownsDefault(bool preserve) { - proto3_preserve_unknown_ = preserve; -} - - } // namespace internal } // namespace protobuf diff --git a/third_party/protobuf/src/google/protobuf/message_lite.h b/third_party/protobuf/src/google/protobuf/message_lite.h index b8644142..bc5d4c7a 100644 --- a/third_party/protobuf/src/google/protobuf/message_lite.h +++ b/third_party/protobuf/src/google/protobuf/message_lite.h @@ -40,29 +40,45 @@ #define GOOGLE_PROTOBUF_MESSAGE_LITE_H__ #include +#include + #include #include -#include #include -#include +#include +#include +#include + + +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif namespace google { namespace protobuf { + template class RepeatedPtrField; + namespace io { + class CodedInputStream; class CodedOutputStream; class ZeroCopyInputStream; class ZeroCopyOutputStream; -} + +} // namespace io namespace internal { +// See parse_context.h for explanation +class ParseContext; + class RepeatedPtrFieldBase; class WireFormatLite; class WeakFieldMap; -#ifndef SWIG // We compute sizes as size_t but cache them as int. This function converts a // computed size to a cached size. Since we don't proceed with serialization // if the total size was > INT_MAX, it is not important what this function @@ -106,13 +122,9 @@ inline int ToIntSize(size_t size) { template class ExplicitlyConstructed { public: - void DefaultConstruct() { - new (&union_) T(); - } + void DefaultConstruct() { new (&union_) T(); } - void Destruct() { - get_mutable()->~T(); - } + void Destruct() { get_mutable()->~T(); } constexpr const T& get() const { return reinterpret_cast(union_); } T* get_mutable() { return reinterpret_cast(&union_); } @@ -128,14 +140,16 @@ class ExplicitlyConstructed { // Default empty string object. Don't use this directly. Instead, call // GetEmptyString() to get the reference. -LIBPROTOBUF_EXPORT extern ExplicitlyConstructed<::std::string> fixed_address_empty_string; +PROTOBUF_EXPORT extern ExplicitlyConstructed + fixed_address_empty_string; -LIBPROTOBUF_EXPORT inline const ::std::string& GetEmptyStringAlreadyInited() { + +PROTOBUF_EXPORT inline const std::string& GetEmptyStringAlreadyInited() { return fixed_address_empty_string.get(); } -LIBPROTOBUF_EXPORT size_t StringSpaceUsedExcludingSelfLong(const string& str); -#endif // SWIG +PROTOBUF_EXPORT size_t StringSpaceUsedExcludingSelfLong(const std::string& str); + } // namespace internal // Interface to light weight protocol messages. @@ -161,7 +175,7 @@ LIBPROTOBUF_EXPORT size_t StringSpaceUsedExcludingSelfLong(const string& str); // is best when you only have a small number of message types linked // into your binary, in which case the size of the protocol buffers // runtime itself is the biggest problem. -class LIBPROTOBUF_EXPORT MessageLite { +class PROTOBUF_EXPORT MessageLite { public: inline MessageLite() {} virtual ~MessageLite() {} @@ -169,7 +183,7 @@ class LIBPROTOBUF_EXPORT MessageLite { // Basic Operations ------------------------------------------------ // Get the name of this message type, e.g. "foo.bar.BazProto". - virtual string GetTypeName() const = 0; + virtual std::string GetTypeName() const = 0; // Construct a new instance of the same type. Ownership is passed to the // caller. @@ -177,14 +191,14 @@ class LIBPROTOBUF_EXPORT MessageLite { // Construct a new instance on the arena. Ownership is passed to the caller // if arena is a NULL. Default implementation for backwards compatibility. - virtual MessageLite* New(::google::protobuf::Arena* arena) const; + virtual MessageLite* New(Arena* arena) const; // Get the arena, if any, associated with this message. Virtual method // required for generic operations but most arena-related operations should // use the GetArenaNoVirtual() generated-code method. Default implementation // to reduce code size by avoiding the need for per-type implementations // when types do not implement arena support. - virtual ::google::protobuf::Arena* GetArena() const { return NULL; } + virtual Arena* GetArena() const { return NULL; } // Get a pointer that may be equal to this message's arena, or may not be. // If the value returned by this method is equal to some arena pointer, then @@ -210,12 +224,24 @@ class LIBPROTOBUF_EXPORT MessageLite { // This is not implemented for Lite messages -- it just returns "(cannot // determine missing fields for lite message)". However, it is implemented // for full messages. See message.h. - virtual string InitializationErrorString() const; + virtual std::string InitializationErrorString() const; // If |other| is the exact same class as this, calls MergeFrom(). Otherwise, // results are undefined (probably crash). virtual void CheckTypeAndMergeFrom(const MessageLite& other) = 0; + // These methods return a human-readable summary of the message. Note that + // since the MessageLite interface does not support reflection, there is very + // little information that these methods can provide. They are shadowed by + // methods of the same name on the Message interface which provide much more + // information. The methods here are intended primarily to facilitate code + // reuse for logic that needs to interoperate with both full and lite protos. + // + // The format of the returned string is subject to change, so please do not + // assume it will remain stable over time. + std::string DebugString() const; + std::string ShortDebugString() const { return DebugString(); } + // Parsing --------------------------------------------------------- // Methods for parsing in protocol buffer format. Most of these are // just simple wrappers around MergeFromCodedStream(). Clear() will be @@ -239,6 +265,11 @@ class LIBPROTOBUF_EXPORT MessageLite { // Read a protocol buffer from the given zero-copy input stream, expecting // the message to be exactly "size" bytes long. If successful, exactly // this many bytes will have been consumed from the input. + bool MergePartialFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input, + int size); + // Like ParseFromBoundedZeroCopyStream(), but accepts messages that are + // missing required fields. + bool MergeFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input, int size); bool ParseFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input, int size); // Like ParseFromBoundedZeroCopyStream(), but accepts messages that are // missing required fields. @@ -249,10 +280,10 @@ class LIBPROTOBUF_EXPORT MessageLite { // format, matching the encoding output by MessageLite::SerializeToString(). // If you'd like to convert a human-readable string into a protocol buffer // object, see google::protobuf::TextFormat::ParseFromString(). - bool ParseFromString(const string& data); + bool ParseFromString(const std::string& data); // Like ParseFromString(), but accepts messages that are missing // required fields. - bool ParsePartialFromString(const string& data); + bool ParsePartialFromString(const std::string& data); // Parse a protocol buffer contained in an array of bytes. bool ParseFromArray(const void* data, int size); // Like ParseFromArray(), but accepts messages that are missing @@ -278,7 +309,14 @@ class LIBPROTOBUF_EXPORT MessageLite { // // MergeFromCodedStream() is just implemented as MergePartialFromCodedStream() // followed by IsInitialized(). +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + bool MergePartialFromCodedStream(io::CodedInputStream* input); +#else virtual bool MergePartialFromCodedStream(io::CodedInputStream* input) = 0; +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + + // Merge a protocol buffer contained in a string. + bool MergeFromString(const std::string& data); // Serialization --------------------------------------------------- @@ -298,9 +336,9 @@ class LIBPROTOBUF_EXPORT MessageLite { bool SerializePartialToZeroCopyStream(io::ZeroCopyOutputStream* output) const; // Serialize the message and store it in the given string. All required // fields must be set. - bool SerializeToString(string* output) const; + bool SerializeToString(std::string* output) const; // Like SerializeToString(), but allows missing required fields. - bool SerializePartialToString(string* output) const; + bool SerializePartialToString(std::string* output) const; // Serialize the message and store it in the given byte array. All required // fields must be set. bool SerializeToArray(void* data, int size) const; @@ -313,15 +351,15 @@ class LIBPROTOBUF_EXPORT MessageLite { // Note: If you intend to generate many such strings, you may // reduce heap fragmentation by instead re-using the same string // object with calls to SerializeToString(). - string SerializeAsString() const; + std::string SerializeAsString() const; // Like SerializeAsString(), but allows missing required fields. - string SerializePartialAsString() const; + std::string SerializePartialAsString() const; - // Like SerializeToString(), but appends to the data to the string's existing - // contents. All required fields must be set. - bool AppendToString(string* output) const; + // Like SerializeToString(), but appends to the data to the string's + // existing contents. All required fields must be set. + bool AppendToString(std::string* output) const; // Like AppendToString(), but allows missing required fields. - bool AppendPartialToString(string* output) const; + bool AppendPartialToString(std::string* output) const; // Computes the serialized size of the message. This recursively calls // ByteSizeLong() on all embedded messages. @@ -331,16 +369,13 @@ class LIBPROTOBUF_EXPORT MessageLite { virtual size_t ByteSizeLong() const = 0; // Legacy ByteSize() API. - PROTOBUF_RUNTIME_DEPRECATED("Please use ByteSizeLong() instead") - int ByteSize() const { - return internal::ToIntSize(ByteSizeLong()); - } + PROTOBUF_DEPRECATED_MSG("Please use ByteSizeLong() instead") + int ByteSize() const { return internal::ToIntSize(ByteSizeLong()); } // Serializes the message without recomputing the size. The message must not // have changed since the last call to ByteSize(), and the value returned by // ByteSize must be non-negative. Otherwise the results are undefined. - virtual void SerializeWithCachedSizes( - io::CodedOutputStream* output) const; + virtual void SerializeWithCachedSizes(io::CodedOutputStream* output) const; // Functions below here are not part of the public interface. It isn't // enforced, but they should be treated as private, and will be private @@ -367,8 +402,12 @@ class LIBPROTOBUF_EXPORT MessageLite { // method.) virtual int GetCachedSize() const = 0; - virtual uint8* InternalSerializeWithCachedSizesToArray(bool deterministic, - uint8* target) const; +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + virtual const char* _InternalParse(const char* ptr, + internal::ParseContext* ctx) { + return nullptr; + } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER protected: // CastToBase allows generated code to cast a RepeatedPtrField to @@ -376,13 +415,13 @@ class LIBPROTOBUF_EXPORT MessageLite { // because it is an implementation detail that user code should not access // directly. template - static ::google::protobuf::internal::RepeatedPtrFieldBase* CastToBase( - ::google::protobuf::RepeatedPtrField* repeated) { + static internal::RepeatedPtrFieldBase* CastToBase( + RepeatedPtrField* repeated) { return repeated; } template - static const ::google::protobuf::internal::RepeatedPtrFieldBase& CastToBase( - const ::google::protobuf::RepeatedPtrField& repeated) { + static const internal::RepeatedPtrFieldBase& CastToBase( + const RepeatedPtrField& repeated) { return repeated; } @@ -391,34 +430,94 @@ class LIBPROTOBUF_EXPORT MessageLite { return Arena::CreateMaybeMessage(arena); } + public: + enum ParseFlags { + kMerge = 0, + kParse = 1, + kMergePartial = 2, + kParsePartial = 3, + kMergeWithAliasing = 4, + kParseWithAliasing = 5, + kMergePartialWithAliasing = 6, + kParsePartialWithAliasing = 7 + }; + + template + bool ParseFrom(const T& input); + private: // TODO(gerbens) make this a pure abstract function virtual const void* InternalGetTable() const { return NULL; } + // Fast path when conditions match (ie. non-deterministic) + public: + virtual uint8* InternalSerializeWithCachedSizesToArray(uint8* target) const; + + private: friend class internal::WireFormatLite; friend class Message; friend class internal::WeakFieldMap; + bool IsInitializedWithErrors() const { + if (IsInitialized()) return true; + LogInitializationErrorMessage(); + return false; + } + + void LogInitializationErrorMessage() const; + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageLite); }; namespace internal { -extern bool LIBPROTOBUF_EXPORT proto3_preserve_unknown_; +template +bool MergePartialFromImpl(StringPiece input, MessageLite* msg); +extern template bool MergePartialFromImpl(StringPiece input, + MessageLite* msg); +extern template bool MergePartialFromImpl(StringPiece input, + MessageLite* msg); -// DO NOT USE: For migration only. Will be removed when Proto3 defaults to -// preserve unknowns. -inline bool GetProto3PreserveUnknownsDefault() { - return proto3_preserve_unknown_; +template +bool MergePartialFromImpl(io::ZeroCopyInputStream* input, MessageLite* msg); +extern template bool MergePartialFromImpl(io::ZeroCopyInputStream* input, + MessageLite* msg); +extern template bool MergePartialFromImpl(io::ZeroCopyInputStream* input, + MessageLite* msg); + +struct BoundedZCIS { + io::ZeroCopyInputStream* zcis; + int limit; +}; + +template +bool MergePartialFromImpl(BoundedZCIS input, MessageLite* msg); +extern template bool MergePartialFromImpl(BoundedZCIS input, + MessageLite* msg); +extern template bool MergePartialFromImpl(BoundedZCIS input, + MessageLite* msg); + +template +struct SourceWrapper; + +template +bool MergePartialFromImpl(const SourceWrapper& input, MessageLite* msg) { + return input.template MergePartialInto(msg); } -// DO NOT USE: For migration only. Will be removed when Proto3 defaults to -// preserve unknowns. -void LIBPROTOBUF_EXPORT SetProto3PreserveUnknownsDefault(bool preserve); } // namespace internal +template +bool MessageLite::ParseFrom(const T& input) { + if (flags & kParse) Clear(); + constexpr bool alias = flags & kMergeWithAliasing; + bool res = internal::MergePartialFromImpl(input, this); + return res && ((flags & kMergePartial) || IsInitializedWithErrors()); +} } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_MESSAGE_LITE_H__ diff --git a/third_party/protobuf/src/google/protobuf/message_unittest.cc b/third_party/protobuf/src/google/protobuf/message_unittest.cc index 45b46bee..0840e7bf 100644 --- a/third_party/protobuf/src/google/protobuf/message_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/message_unittest.cc @@ -43,9 +43,3 @@ // Must include after the above macros. #include #include - -// Make extract script happy. -namespace google { -namespace protobuf { -} // namespace protobuf -} // namespace google diff --git a/third_party/protobuf/src/google/protobuf/message_unittest.inc b/third_party/protobuf/src/google/protobuf/message_unittest.inc index 6ffdcce0..0cd46d4c 100644 --- a/third_party/protobuf/src/google/protobuf/message_unittest.inc +++ b/third_party/protobuf/src/google/protobuf/message_unittest.inc @@ -46,6 +46,7 @@ #include #include +#include #include #include #include @@ -59,7 +60,8 @@ #include #include #include -#include + +#include namespace google { namespace protobuf { @@ -67,8 +69,8 @@ namespace protobuf { #if defined(_WIN32) // DO NOT include , instead create functions in io_win32.{h,cc} and import // them like we do below. -using google::protobuf::internal::win32::close; -using google::protobuf::internal::win32::open; +using google::protobuf::io::win32::close; +using google::protobuf::io::win32::open; #endif #ifndef O_BINARY @@ -87,8 +89,8 @@ TEST(MESSAGE_TEST_NAME, SerializeHelpers) { TestUtil::SetAllFields(&message); std::stringstream stream; - string str1("foo"); - string str2("bar"); + std::string str1("foo"); + std::string str2("bar"); EXPECT_TRUE(message.SerializeToString(&str1)); EXPECT_TRUE(message.AppendToString(&str2)); @@ -101,7 +103,7 @@ TEST(MESSAGE_TEST_NAME, SerializeHelpers) { EXPECT_TRUE(str2.substr(3) == str1); // GCC gives some sort of error if we try to just do stream.str() == str1. - string temp = stream.str(); + std::string temp = stream.str(); EXPECT_TRUE(temp == str1); EXPECT_TRUE(message.SerializeAsString() == str1); @@ -117,8 +119,8 @@ TEST(MESSAGE_TEST_NAME, SerializeToBrokenOstream) { } TEST(MESSAGE_TEST_NAME, ParseFromFileDescriptor) { - string filename = TestSourceDir() + - "/google/protobuf/testdata/golden_message"; + std::string filename = + TestUtil::GetTestDataPath("net/proto2/internal/testdata/golden_message"); int file = open(filename.c_str(), O_RDONLY | O_BINARY); ASSERT_GE(file, 0); @@ -130,9 +132,8 @@ TEST(MESSAGE_TEST_NAME, ParseFromFileDescriptor) { } TEST(MESSAGE_TEST_NAME, ParsePackedFromFileDescriptor) { - string filename = - TestSourceDir() + - "/google/protobuf/testdata/golden_packed_fields_message"; + std::string filename = TestUtil::GetTestDataPath( + "net/proto2/internal/testdata/golden_packed_fields_message"); int file = open(filename.c_str(), O_RDONLY | O_BINARY); ASSERT_GE(file, 0); @@ -146,7 +147,7 @@ TEST(MESSAGE_TEST_NAME, ParsePackedFromFileDescriptor) { TEST(MESSAGE_TEST_NAME, ParseHelpers) { // TODO(kenton): Test more helpers? They're all two-liners so it seems // like a waste of time. - string data; + std::string data; { // Set up. @@ -173,7 +174,7 @@ TEST(MESSAGE_TEST_NAME, ParseHelpers) { { // Test ParseFromBoundedZeroCopyStream. - string data_with_junk(data); + std::string data_with_junk(data); data_with_junk.append("some junk on the end"); io::ArrayInputStream stream(data_with_junk.data(), data_with_junk.size()); UNITTEST::TestAllTypes message; @@ -193,7 +194,7 @@ TEST(MESSAGE_TEST_NAME, ParseHelpers) { TEST(MESSAGE_TEST_NAME, ParseFailsIfNotInitialized) { UNITTEST::TestRequired message; - std::vector errors; + std::vector errors; { ScopedMemoryLog log; @@ -203,7 +204,7 @@ TEST(MESSAGE_TEST_NAME, ParseFailsIfNotInitialized) { ASSERT_EQ(1, errors.size()); EXPECT_EQ( - "Can't parse message of type \"" + string(UNITTEST_PACKAGE_NAME) + + "Can't parse message of type \"" + std::string(UNITTEST_PACKAGE_NAME) + ".TestRequired\" because it is missing required fields: a, b, c", errors[0]); } @@ -223,33 +224,28 @@ TEST(MESSAGE_TEST_NAME, InitializationErrorString) { TEST(MESSAGE_TEST_NAME, DynamicCastToGenerated) { UNITTEST::TestAllTypes test_all_types; - google::protobuf::Message* test_all_types_pointer = &test_all_types; - EXPECT_EQ(&test_all_types, - google::protobuf::internal::DynamicCastToGenerated( - test_all_types_pointer)); - EXPECT_EQ(nullptr, - google::protobuf::internal::DynamicCastToGenerated( - test_all_types_pointer)); + Message* test_all_types_pointer = &test_all_types; + EXPECT_EQ(&test_all_types, DynamicCastToGenerated( + test_all_types_pointer)); + EXPECT_EQ(nullptr, DynamicCastToGenerated( + test_all_types_pointer)); - const google::protobuf::Message* test_all_types_pointer_const = &test_all_types; - EXPECT_EQ( - &test_all_types, - google::protobuf::internal::DynamicCastToGenerated( - test_all_types_pointer_const)); - EXPECT_EQ( - nullptr, - google::protobuf::internal::DynamicCastToGenerated( - test_all_types_pointer_const)); + const Message* test_all_types_pointer_const = &test_all_types; + EXPECT_EQ(&test_all_types, + DynamicCastToGenerated( + test_all_types_pointer_const)); + EXPECT_EQ(nullptr, DynamicCastToGenerated( + test_all_types_pointer_const)); } #ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet. TEST(MESSAGE_TEST_NAME, SerializeFailsIfNotInitialized) { UNITTEST::TestRequired message; - string data; + std::string data; EXPECT_DEBUG_DEATH(EXPECT_TRUE(message.SerializeToString(&data)), "Can't serialize message of type \"" + - string(UNITTEST_PACKAGE_NAME) + + std::string(UNITTEST_PACKAGE_NAME) + ".TestRequired\" because " "it is missing required fields: a, b, c"); } @@ -257,8 +253,7 @@ TEST(MESSAGE_TEST_NAME, SerializeFailsIfNotInitialized) { TEST(MESSAGE_TEST_NAME, CheckInitialized) { UNITTEST::TestRequired message; EXPECT_DEATH(message.CheckInitialized(), - "Message of type \"" + - string(UNITTEST_PACKAGE_NAME) + + "Message of type \"" + std::string(UNITTEST_PACKAGE_NAME) + ".TestRequired\" is missing required " "fields: a, b, c"); } @@ -266,12 +261,13 @@ TEST(MESSAGE_TEST_NAME, CheckInitialized) { #endif // PROTOBUF_HAS_DEATH_TEST namespace { -// An input stream that repeats a string's content for a number of times. It -// helps us create a really large input without consuming too much memory. Used -// to test the parsing behavior when the input size exceeds 2G or close to it. +// An input stream that repeats a std::string's content for a number of times. +// It helps us create a really large input without consuming too much memory. +// Used to test the parsing behavior when the input size exceeds 2G or close to +// it. class RepeatedInputStream : public io::ZeroCopyInputStream { public: - RepeatedInputStream(const string& data, size_t count) + RepeatedInputStream(const std::string& data, size_t count) : data_(data), count_(count), position_(0), total_byte_count_(0) {} virtual bool Next(const void** data, int* size) { @@ -313,22 +309,22 @@ class RepeatedInputStream : public io::ZeroCopyInputStream { virtual int64 ByteCount() const { return total_byte_count_; } private: - string data_; + std::string data_; size_t count_; // The number of strings that haven't been consuemd. - size_t position_; // Position in the string for the next read. + size_t position_; // Position in the std::string for the next read. int64 total_byte_count_; }; } // namespace TEST(MESSAGE_TEST_NAME, TestParseMessagesCloseTo2G) { - // Create a message with a large string field. - string value = string(64 * 1024 * 1024, 'x'); + // Create a message with a large std::string field. + std::string value = std::string(64 * 1024 * 1024, 'x'); UNITTEST::TestAllTypes message; message.set_optional_string(value); // Repeat this message in the input stream to make the total input size // close to 2G. - string data = message.SerializeAsString(); + std::string data = message.SerializeAsString(); size_t count = static_cast(kint32max) / data.size(); RepeatedInputStream input(data, count); @@ -342,14 +338,14 @@ TEST(MESSAGE_TEST_NAME, TestParseMessagesCloseTo2G) { } TEST(MESSAGE_TEST_NAME, TestParseMessagesOver2G) { - // Create a message with a large string field. - string value = string(64 * 1024 * 1024, 'x'); + // Create a message with a large std::string field. + std::string value = std::string(64 * 1024 * 1024, 'x'); UNITTEST::TestAllTypes message; message.set_optional_string(value); // Repeat this message in the input stream to make the total input size // larger than 2G. - string data = message.SerializeAsString(); + std::string data = message.SerializeAsString(); size_t count = static_cast(kint32max) / data.size() + 1; RepeatedInputStream input(data, count); @@ -367,7 +363,7 @@ TEST(MESSAGE_TEST_NAME, BypassInitializationCheckOnSerialize) { TEST(MESSAGE_TEST_NAME, FindInitializationErrors) { UNITTEST::TestRequired message; - std::vector errors; + std::vector errors; message.FindInitializationErrors(&errors); ASSERT_EQ(3, errors.size()); EXPECT_EQ("a", errors[0]); @@ -396,7 +392,7 @@ TEST(MESSAGE_TEST_NAME, MessageIsStillValidAfterParseFails) { UNITTEST::TestAllTypes message; // 9 0xFFs for the "optional_uint64" field. - string invalid_data = "\x20\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"; + std::string invalid_data = "\x20\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"; EXPECT_FALSE(message.ParseFromString(invalid_data)); message.Clear(); @@ -404,11 +400,11 @@ TEST(MESSAGE_TEST_NAME, MessageIsStillValidAfterParseFails) { // invalid data for field "optional_string". Length prefix is 1 but no // payload. - string invalid_string_data = "\x72\x01"; + std::string invalid_string_data = "\x72\x01"; { - google::protobuf::Arena arena; + Arena arena; UNITTEST::TestAllTypes* arena_message = - google::protobuf::Arena::CreateMessage(&arena); + Arena::CreateMessage(&arena); EXPECT_FALSE(arena_message->ParseFromString(invalid_string_data)); arena_message->Clear(); EXPECT_EQ("", arena_message->optional_string()); @@ -467,7 +463,7 @@ TEST(MESSAGE_TEST_NAME, ParsingMerge) { #undef ASSIGN_REPEATED_GROUP - string buffer; + std::string buffer; generator.SerializeToString(&buffer); UNITTEST::TestParsingMerge parsing_merge; parsing_merge.ParseFromString(buffer); @@ -572,6 +568,68 @@ TEST(MESSAGE_FACTORY_TEST_NAME, GeneratedFactoryUnknownType) { nullptr); } +TEST(MESSAGE_TEST_NAME, MOMIParserEdgeCases) { + { + UNITTEST::TestAllTypes msg; + // Parser ends in last 16 bytes of buffer due to a 0. + std::string data; + // 12 bytes of data + for (int i = 0; i < 4; i++) data += "\370\1\1"; + // 13 byte is terminator + data += '\0'; // Terminator + // followed by the rest of the stream + // space is ascii 32 so no end group + data += std::string(30, ' '); + io::ArrayInputStream zcis(data.data(), data.size(), 17); + io::CodedInputStream cis(&zcis); + EXPECT_TRUE(msg.MergePartialFromCodedStream(&cis)); + EXPECT_EQ(cis.CurrentPosition(), 3 * 4 + 1); + } + { + // Parser ends in last 16 bytes of buffer due to a end-group. + // Must use a message that is a group. Otherwise ending on a group end is + // a failure. + UNITTEST::TestAllTypes::OptionalGroup msg; + std::string data; + for (int i = 0; i < 3; i++) data += "\370\1\1"; + data += '\14'; // Octal end-group tag 12 (1 * 8 + 4( + data += std::string(30, ' '); + io::ArrayInputStream zcis(data.data(), data.size(), 17); + io::CodedInputStream cis(&zcis); + EXPECT_TRUE(msg.MergePartialFromCodedStream(&cis)); + EXPECT_EQ(cis.CurrentPosition(), 3 * 3 + 1); + EXPECT_TRUE(cis.LastTagWas(12)); + } + { + // Parser ends in last 16 bytes of buffer due to a end-group. But is inside + // a length delimited field. + // a failure. + UNITTEST::TestAllTypes::OptionalGroup msg; + std::string data; + data += "\22\3foo"; + data += '\14'; // Octal end-group tag 12 (1 * 8 + 4( + data += std::string(30, ' '); + io::ArrayInputStream zcis(data.data(), data.size(), 17); + io::CodedInputStream cis(&zcis); + EXPECT_TRUE(msg.MergePartialFromCodedStream(&cis)); + EXPECT_EQ(cis.CurrentPosition(), 6); + EXPECT_TRUE(cis.LastTagWas(12)); + } + { + // Parser fails when ending on 0 if from ZeroCopyInputStream + UNITTEST::TestAllTypes msg; + std::string data; + // 12 bytes of data + for (int i = 0; i < 4; i++) data += "\370\1\1"; + // 13 byte is terminator + data += '\0'; // Terminator + data += std::string(30, ' '); + io::ArrayInputStream zcis(data.data(), data.size(), 17); + EXPECT_FALSE(msg.ParsePartialFromZeroCopyStream(&zcis)); + } +} + + } // namespace protobuf } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/metadata.h b/third_party/protobuf/src/google/protobuf/metadata.h index 0a6507c0..009a7e93 100644 --- a/third_party/protobuf/src/google/protobuf/metadata.h +++ b/third_party/protobuf/src/google/protobuf/metadata.h @@ -41,6 +41,10 @@ #include #include +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + namespace google { namespace protobuf { namespace internal { @@ -52,19 +56,15 @@ class InternalMetadataWithArena InternalMetadataWithArena() {} explicit InternalMetadataWithArena(Arena* arena) : InternalMetadataWithArenaBase(arena) {} + InternalMetadataWithArena>(arena) {} - void DoSwap(UnknownFieldSet* other) { - mutable_unknown_fields()->Swap(other); - } + void DoSwap(UnknownFieldSet* other) { mutable_unknown_fields()->Swap(other); } void DoMergeFrom(const UnknownFieldSet& other) { mutable_unknown_fields()->MergeFrom(other); } - void DoClear() { - mutable_unknown_fields()->Clear(); - } + void DoClear() { mutable_unknown_fields()->Clear(); } static const UnknownFieldSet& default_instance() { return *UnknownFieldSet::default_instance(); @@ -73,6 +73,6 @@ class InternalMetadataWithArena } // namespace internal } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_METADATA_H__ diff --git a/third_party/protobuf/src/google/protobuf/metadata_lite.h b/third_party/protobuf/src/google/protobuf/metadata_lite.h index 454d088c..40c7ea78 100644 --- a/third_party/protobuf/src/google/protobuf/metadata_lite.h +++ b/third_party/protobuf/src/google/protobuf/metadata_lite.h @@ -31,10 +31,18 @@ #ifndef GOOGLE_PROTOBUF_METADATA_LITE_H__ #define GOOGLE_PROTOBUF_METADATA_LITE_H__ +#include #include #include +#include #include -#include +#include + +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif namespace google { namespace protobuf { @@ -63,35 +71,35 @@ class InternalMetadataWithArenaBase { ptr_ = NULL; } - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE const T& unknown_fields() const { - if (GOOGLE_PREDICT_FALSE(have_unknown_fields())) { + PROTOBUF_ALWAYS_INLINE const T& unknown_fields() const { + if (PROTOBUF_PREDICT_FALSE(have_unknown_fields())) { return PtrValue()->unknown_fields; } else { return Derived::default_instance(); } } - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* mutable_unknown_fields() { - if (GOOGLE_PREDICT_TRUE(have_unknown_fields())) { + PROTOBUF_ALWAYS_INLINE T* mutable_unknown_fields() { + if (PROTOBUF_PREDICT_TRUE(have_unknown_fields())) { return &PtrValue()->unknown_fields; } else { return mutable_unknown_fields_slow(); } } - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE Arena* arena() const { - if (GOOGLE_PREDICT_FALSE(have_unknown_fields())) { + PROTOBUF_ALWAYS_INLINE Arena* arena() const { + if (PROTOBUF_PREDICT_FALSE(have_unknown_fields())) { return PtrValue()->arena; } else { return PtrValue(); } } - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool have_unknown_fields() const { + PROTOBUF_ALWAYS_INLINE bool have_unknown_fields() const { return PtrTag() == kTagContainer; } - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Swap(Derived* other) { + PROTOBUF_ALWAYS_INLINE void Swap(Derived* other) { // Semantics here are that we swap only the unknown fields, not the arena // pointer. We cannot simply swap ptr_ with other->ptr_ because we need to // maintain our own arena ptr. Also, our ptr_ and other's ptr_ may be in @@ -103,21 +111,19 @@ class InternalMetadataWithArenaBase { } } - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void MergeFrom(const Derived& other) { + PROTOBUF_ALWAYS_INLINE void MergeFrom(const Derived& other) { if (other.have_unknown_fields()) { static_cast(this)->DoMergeFrom(other.unknown_fields()); } } - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Clear() { + PROTOBUF_ALWAYS_INLINE void Clear() { if (have_unknown_fields()) { static_cast(this)->DoClear(); } } - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void* raw_arena_ptr() const { - return ptr_; - } + PROTOBUF_ALWAYS_INLINE void* raw_arena_ptr() const { return ptr_; } private: void* ptr_; @@ -133,13 +139,14 @@ class InternalMetadataWithArenaBase { static const intptr_t kPtrValueMask = ~kPtrTagMask; // Accessors for pointer tag and pointer value. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE int PtrTag() const { + PROTOBUF_ALWAYS_INLINE int PtrTag() const { return reinterpret_cast(ptr_) & kPtrTagMask; } - template U* PtrValue() const { - return reinterpret_cast( - reinterpret_cast(ptr_) & kPtrValueMask); + template + U* PtrValue() const { + return reinterpret_cast(reinterpret_cast(ptr_) & + kPtrValueMask); } // If ptr_'s tag is kTagContainer, it points to an instance of this struct. @@ -148,58 +155,60 @@ class InternalMetadataWithArenaBase { Arena* arena; }; - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE T* mutable_unknown_fields_slow() { + PROTOBUF_NOINLINE T* mutable_unknown_fields_slow() { Arena* my_arena = arena(); Container* container = Arena::Create(my_arena); // Two-step assignment works around a bug in clang's static analyzer: // https://bugs.llvm.org/show_bug.cgi?id=34198. ptr_ = container; - ptr_ = reinterpret_cast( - reinterpret_cast(ptr_) | kTagContainer); + ptr_ = reinterpret_cast(reinterpret_cast(ptr_) | + kTagContainer); container->arena = my_arena; return &(container->unknown_fields); } }; -// We store unknown fields as a string right now, because there is currently no -// good interface for reading unknown fields into an ArenaString. We may want -// to revisit this to allow unknown fields to be parsed onto the Arena. +// We store unknown fields as a std::string right now, because there is +// currently no good interface for reading unknown fields into an ArenaString. +// We may want to revisit this to allow unknown fields to be parsed onto the +// Arena. class InternalMetadataWithArenaLite - : public InternalMetadataWithArenaBase { public: InternalMetadataWithArenaLite() {} explicit InternalMetadataWithArenaLite(Arena* arena) - : InternalMetadataWithArenaBase(arena) {} - void DoSwap(string* other) { - mutable_unknown_fields()->swap(*other); - } + void DoSwap(std::string* other) { mutable_unknown_fields()->swap(*other); } - void DoMergeFrom(const string& other) { + void DoMergeFrom(const std::string& other) { mutable_unknown_fields()->append(other); } - void DoClear() { - mutable_unknown_fields()->clear(); - } + void DoClear() { mutable_unknown_fields()->clear(); } - static const string& default_instance() { - return GetEmptyStringAlreadyInited(); + static const std::string& default_instance() { + // Can't use GetEmptyStringAlreadyInited() here because empty string + // may not have been initalized yet. This happens when protocol compiler + // statically determines the user can't access defaults and omits init code + // from proto constructors. However unknown fields are always part of a + // proto so it needs to be lazily initailzed. See b/112613846. + return GetEmptyString(); } }; // This helper RAII class is needed to efficiently parse unknown fields. We // should only call mutable_unknown_fields if there are actual unknown fields. -// The obvious thing to just use a stack string and swap it at the end of the -// parse won't work, because the destructor of StringOutputStream needs to be -// called before we can modify the string (it check-fails). Using +// The obvious thing to just use a stack string and swap it at the end of +// the parse won't work, because the destructor of StringOutputStream needs to +// be called before we can modify the string (it check-fails). Using // LiteUnknownFieldSetter setter(&_internal_metadata_); // StringOutputStream stream(setter.buffer()); // guarantees that the string is only swapped after stream is destroyed. -class LIBPROTOBUF_EXPORT LiteUnknownFieldSetter { +class PROTOBUF_EXPORT LiteUnknownFieldSetter { public: explicit LiteUnknownFieldSetter(InternalMetadataWithArenaLite* metadata) : metadata_(metadata) { @@ -210,15 +219,17 @@ class LIBPROTOBUF_EXPORT LiteUnknownFieldSetter { ~LiteUnknownFieldSetter() { if (!buffer_.empty()) metadata_->mutable_unknown_fields()->swap(buffer_); } - string* buffer() { return &buffer_; } + std::string* buffer() { return &buffer_; } private: InternalMetadataWithArenaLite* metadata_; - string buffer_; + std::string buffer_; }; } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_METADATA_LITE_H__ diff --git a/third_party/protobuf/src/google/protobuf/no_field_presence_test.cc b/third_party/protobuf/src/google/protobuf/no_field_presence_test.cc index bc41beec..8b05277f 100644 --- a/third_party/protobuf/src/google/protobuf/no_field_presence_test.cc +++ b/third_party/protobuf/src/google/protobuf/no_field_presence_test.cc @@ -30,8 +30,8 @@ #include -#include #include +#include #include #include #include @@ -120,8 +120,7 @@ void FillValues(proto2_nofieldpresence_unittest::TestAllTypes* m) { m->mutable_optional_proto2_message()->set_optional_int32(44); m->set_optional_nested_enum( proto2_nofieldpresence_unittest::TestAllTypes_NestedEnum_BAZ); - m->set_optional_foreign_enum( - proto2_nofieldpresence_unittest::FOREIGN_BAZ); + m->set_optional_foreign_enum(proto2_nofieldpresence_unittest::FOREIGN_BAZ); m->mutable_optional_lazy_message()->set_bb(45); m->add_repeated_int32(100); m->add_repeated_int64(101); @@ -143,8 +142,7 @@ void FillValues(proto2_nofieldpresence_unittest::TestAllTypes* m) { m->add_repeated_proto2_message()->set_optional_int32(48); m->add_repeated_nested_enum( proto2_nofieldpresence_unittest::TestAllTypes_NestedEnum_BAZ); - m->add_repeated_foreign_enum( - proto2_nofieldpresence_unittest::FOREIGN_BAZ); + m->add_repeated_foreign_enum(proto2_nofieldpresence_unittest::FOREIGN_BAZ); m->add_repeated_lazy_message()->set_bb(49); m->set_oneof_uint32(1); @@ -153,7 +151,7 @@ void FillValues(proto2_nofieldpresence_unittest::TestAllTypes* m) { } void CheckNonDefaultValues( -const proto2_nofieldpresence_unittest::TestAllTypes& m) { + const proto2_nofieldpresence_unittest::TestAllTypes& m) { EXPECT_EQ(100, m.optional_int32()); EXPECT_EQ(101, m.optional_int64()); EXPECT_EQ(102, m.optional_uint32()); @@ -271,8 +269,9 @@ TEST(NoFieldPresenceTest, MessageFieldPresenceTest) { EXPECT_EQ(false, message.has_optional_lazy_message()); // Test field presence of a message field on the default instance. - EXPECT_EQ(false, proto2_nofieldpresence_unittest::TestAllTypes:: - default_instance().has_optional_nested_message()); + EXPECT_EQ(false, + proto2_nofieldpresence_unittest::TestAllTypes::default_instance() + .has_optional_nested_message()); } TEST(NoFieldPresenceTest, ReflectionHasFieldTest) { @@ -280,32 +279,34 @@ TEST(NoFieldPresenceTest, ReflectionHasFieldTest) { // behaves properly for message fields. proto2_nofieldpresence_unittest::TestAllTypes message; - const google::protobuf::Reflection* r = message.GetReflection(); - const google::protobuf::Descriptor* desc = message.GetDescriptor(); + const Reflection* r = message.GetReflection(); + const Descriptor* desc = message.GetDescriptor(); // Check initial state: scalars not present (due to need to be consistent with // MergeFrom()), message fields not present, oneofs not present. for (int i = 0; i < desc->field_count(); i++) { - const google::protobuf::FieldDescriptor* field = desc->field(i); + const FieldDescriptor* field = desc->field(i); if (field->is_repeated()) continue; EXPECT_EQ(false, r->HasField(message, field)); } // Test field presence of a message field on the default instance. - const google::protobuf::FieldDescriptor* msg_field = + const FieldDescriptor* msg_field = desc->FindFieldByName("optional_nested_message"); - EXPECT_EQ(false, r->HasField( - proto2_nofieldpresence_unittest::TestAllTypes:: - default_instance(), msg_field)); + EXPECT_EQ( + false, + r->HasField( + proto2_nofieldpresence_unittest::TestAllTypes::default_instance(), + msg_field)); // Fill all fields, expect everything to report true (check oneofs below). FillValues(&message); for (int i = 0; i < desc->field_count(); i++) { - const google::protobuf::FieldDescriptor* field = desc->field(i); + const FieldDescriptor* field = desc->field(i); if (field->is_repeated() || field->containing_oneof()) { continue; } - if (field->options().ctype() != google::protobuf::FieldOptions::STRING) { + if (field->options().ctype() != FieldOptions::STRING) { continue; } EXPECT_EQ(true, r->HasField(message, field)); @@ -314,12 +315,11 @@ TEST(NoFieldPresenceTest, ReflectionHasFieldTest) { message.Clear(); // Check zero/empty-means-not-present semantics. - const google::protobuf::FieldDescriptor* field_int32 = desc->FindFieldByName( - "optional_int32"); - const google::protobuf::FieldDescriptor* field_double = desc->FindFieldByName( - "optional_double"); - const google::protobuf::FieldDescriptor* field_string = desc->FindFieldByName( - "optional_string"); + const FieldDescriptor* field_int32 = desc->FindFieldByName("optional_int32"); + const FieldDescriptor* field_double = + desc->FindFieldByName("optional_double"); + const FieldDescriptor* field_string = + desc->FindFieldByName("optional_string"); EXPECT_EQ(false, r->HasField(message, field_int32)); EXPECT_EQ(false, r->HasField(message, field_double)); @@ -344,19 +344,18 @@ TEST(NoFieldPresenceTest, ReflectionHasFieldTest) { TEST(NoFieldPresenceTest, ReflectionClearFieldTest) { proto2_nofieldpresence_unittest::TestAllTypes message; - const google::protobuf::Reflection* r = message.GetReflection(); - const google::protobuf::Descriptor* desc = message.GetDescriptor(); + const Reflection* r = message.GetReflection(); + const Descriptor* desc = message.GetDescriptor(); - const google::protobuf::FieldDescriptor* field_int32 = desc->FindFieldByName( - "optional_int32"); - const google::protobuf::FieldDescriptor* field_double = desc->FindFieldByName( - "optional_double"); - const google::protobuf::FieldDescriptor* field_string = desc->FindFieldByName( - "optional_string"); - const google::protobuf::FieldDescriptor* field_message = desc->FindFieldByName( - "optional_nested_message"); - const google::protobuf::FieldDescriptor* field_lazy = desc->FindFieldByName( - "optional_lazy_message"); + const FieldDescriptor* field_int32 = desc->FindFieldByName("optional_int32"); + const FieldDescriptor* field_double = + desc->FindFieldByName("optional_double"); + const FieldDescriptor* field_string = + desc->FindFieldByName("optional_string"); + const FieldDescriptor* field_message = + desc->FindFieldByName("optional_nested_message"); + const FieldDescriptor* field_lazy = + desc->FindFieldByName("optional_lazy_message"); message.set_optional_int32(42); r->ClearField(&message, field_int32); @@ -385,17 +384,17 @@ TEST(NoFieldPresenceTest, HasFieldOneofsTest) { // check that HasField behaves properly for oneofs. proto2_nofieldpresence_unittest::TestAllTypes message; - const google::protobuf::Reflection* r = message.GetReflection(); - const google::protobuf::Descriptor* desc = message.GetDescriptor(); - const google::protobuf::FieldDescriptor* desc_oneof_uint32 = + const Reflection* r = message.GetReflection(); + const Descriptor* desc = message.GetDescriptor(); + const FieldDescriptor* desc_oneof_uint32 = desc->FindFieldByName("oneof_uint32"); - const google::protobuf::FieldDescriptor* desc_oneof_nested_message = + const FieldDescriptor* desc_oneof_nested_message = desc->FindFieldByName("oneof_nested_message"); - const google::protobuf::FieldDescriptor* desc_oneof_string = + const FieldDescriptor* desc_oneof_string = desc->FindFieldByName("oneof_string"); - GOOGLE_CHECK_NOTNULL(desc_oneof_uint32); - GOOGLE_CHECK_NOTNULL(desc_oneof_nested_message); - GOOGLE_CHECK_NOTNULL(desc_oneof_string); + GOOGLE_CHECK(desc_oneof_uint32 != nullptr); + GOOGLE_CHECK(desc_oneof_nested_message != nullptr); + GOOGLE_CHECK(desc_oneof_string != nullptr); EXPECT_EQ(false, r->HasField(message, desc_oneof_uint32)); EXPECT_EQ(false, r->HasField(message, desc_oneof_nested_message)); @@ -420,7 +419,7 @@ TEST(NoFieldPresenceTest, DontSerializeDefaultValuesTest) { // check that serialized data contains only non-zero numeric fields/non-empty // string/byte fields. proto2_nofieldpresence_unittest::TestAllTypes message; - string output; + std::string output; // All default values -> no output. message.SerializeToString(&output); @@ -443,7 +442,8 @@ TEST(NoFieldPresenceTest, DontSerializeDefaultValuesTest) { message.set_optional_string(""); message.set_optional_bytes(""); message.set_optional_nested_enum( - proto2_nofieldpresence_unittest::TestAllTypes_NestedEnum_FOO); // first enum entry + proto2_nofieldpresence_unittest:: + TestAllTypes_NestedEnum_FOO); // first enum entry message.set_optional_foreign_enum( proto2_nofieldpresence_unittest::FOREIGN_FOO); // first enum entry @@ -498,11 +498,10 @@ TEST(NoFieldPresenceTest, LazyMessageFieldHasBit) { // Check that has-bit interaction with lazy message works (has-bit before and // after lazy decode). proto2_nofieldpresence_unittest::TestAllTypes message; - const google::protobuf::Reflection* r = message.GetReflection(); - const google::protobuf::Descriptor* desc = message.GetDescriptor(); - const google::protobuf::FieldDescriptor* field = desc->FindFieldByName( - "optional_lazy_message"); - GOOGLE_CHECK_NOTNULL(field); + const Reflection* r = message.GetReflection(); + const Descriptor* desc = message.GetDescriptor(); + const FieldDescriptor* field = desc->FindFieldByName("optional_lazy_message"); + GOOGLE_CHECK(field != nullptr); EXPECT_EQ(false, message.has_optional_lazy_message()); EXPECT_EQ(false, r->HasField(message, field)); @@ -513,7 +512,7 @@ TEST(NoFieldPresenceTest, LazyMessageFieldHasBit) { // Serialize and parse with a new message object so that lazy field on new // object is in unparsed state. - string output; + std::string output; message.SerializeToString(&output); proto2_nofieldpresence_unittest::TestAllTypes message2; message2.ParseFromString(output); @@ -532,7 +531,7 @@ TEST(NoFieldPresenceTest, OneofPresence) { // oneof fields still have field presence -- ensure that this goes on the wire // even though its value is the empty string. message.set_oneof_string(""); - string serialized; + std::string serialized; message.SerializeToString(&serialized); // Tag: 113 --> tag is (113 << 3) | 2 (length delimited) = 906 // varint: 0x8a 0x07 @@ -557,8 +556,9 @@ TEST(NoFieldPresenceTest, OneofPresence) { message.oneof_field_case()); message.Clear(); - message.set_oneof_enum(proto2_nofieldpresence_unittest:: - TestAllTypes_NestedEnum_FOO); // default value. + message.set_oneof_enum( + proto2_nofieldpresence_unittest::TestAllTypes_NestedEnum_FOO); // default + // value. message.SerializeToString(&serialized); EXPECT_EQ(3, serialized.size()); EXPECT_TRUE(message.ParseFromString(serialized)); @@ -573,5 +573,4 @@ TEST(NoFieldPresenceTest, OneofPresence) { } // namespace } // namespace protobuf - } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/package_info.h b/third_party/protobuf/src/google/protobuf/package_info.h index 935e9639..2b61679a 100644 --- a/third_party/protobuf/src/google/protobuf/package_info.h +++ b/third_party/protobuf/src/google/protobuf/package_info.h @@ -36,8 +36,6 @@ // It is not compiled into anything, but it may be read by an automated // documentation generator. -namespace google { - // Core components of the Protocol Buffers runtime library. // // The files in this package represent the core of the Protocol Buffer @@ -60,5 +58,9 @@ namespace google { // The implementation does contain some "const" methods which actually modify // the object behind the scenes -- e.g., to cache results -- but in these cases // mutex locking is used to make the access thread-safe. -namespace protobuf {} +namespace google { +namespace protobuf { +// TODO(gerbens) remove this comment, we need it to prevent clang-format +// from combining the brackets. Which would mess with extract script +} // namespace protobuf } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/parse_context.cc b/third_party/protobuf/src/google/protobuf/parse_context.cc new file mode 100644 index 00000000..9efa521e --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/parse_context.cc @@ -0,0 +1,557 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace google { +namespace protobuf { +namespace internal { + +namespace { + +// Only call if at start of tag. +bool ParseEndsInSlopRegion(const char* begin, int overrun, int d) { + constexpr int kSlopBytes = EpsCopyInputStream::kSlopBytes; + GOOGLE_DCHECK(overrun >= 0); + GOOGLE_DCHECK(overrun <= kSlopBytes); + auto ptr = begin + overrun; + auto end = begin + kSlopBytes; + while (ptr < end) { + uint32 tag; + ptr = ReadTag(ptr, &tag); + if (ptr == nullptr || ptr > end) return false; + // ending on 0 tag is allowed and is the major reason for the necessity of + // this function. + if (tag == 0) return true; + switch (tag & 7) { + case 0: { // Varint + uint64 val; + ptr = ParseVarint64(ptr, &val); + if (ptr == nullptr) return false; + break; + } + case 1: { // fixed64 + ptr += 8; + break; + } + case 2: { // len delim + int32 size = ReadSize(&ptr); + if (ptr == nullptr || size > end - ptr) return false; + ptr += size; + break; + } + case 3: { // start group + d++; + break; + } + case 4: { // end group + if (--d < 0) return true; // We exit early + break; + } + case 5: { // fixed32 + ptr += 4; + break; + } + default: + return false; // Unknown wireformat + } + } + return false; +} + +} // namespace + +const char* EpsCopyInputStream::Next(int overrun, int d) { + if (next_chunk_ == nullptr) return nullptr; // We've reached end of stream. + if (next_chunk_ != buffer_) { + GOOGLE_DCHECK(size_ > kSlopBytes); + // The chunk is large enough to be used directly + buffer_end_ = next_chunk_ + size_ - kSlopBytes; + auto res = next_chunk_; + next_chunk_ = buffer_; + if (aliasing_ == kOnPatch) aliasing_ = kNoDelta; + return res; + } + // Move the slop bytes of previous buffer to start of the patch buffer. + // Note we must use memmove because the previous buffer could be part of + // buffer_. + std::memmove(buffer_, buffer_end_, kSlopBytes); + if (overall_limit_ > 0 && + (d < 0 || !ParseEndsInSlopRegion(buffer_, overrun, d))) { + const void* data; + // ZeroCopyInputStream indicates Next may return 0 size buffers. Hence + // we loop. + while (zcis_->Next(&data, &size_)) { + overall_limit_ -= size_; + if (size_ > kSlopBytes) { + // We got a large chunk + std::memcpy(buffer_ + kSlopBytes, data, kSlopBytes); + next_chunk_ = static_cast(data); + buffer_end_ = buffer_ + kSlopBytes; + if (aliasing_ >= kNoDelta) aliasing_ = kOnPatch; + return buffer_; + } else if (size_ > 0) { + std::memcpy(buffer_ + kSlopBytes, data, size_); + next_chunk_ = buffer_; + buffer_end_ = buffer_ + size_; + if (aliasing_ >= kNoDelta) aliasing_ = kOnPatch; + return buffer_; + } + GOOGLE_DCHECK(size_ == 0) << size_; + } + overall_limit_ = 0; // Next failed, no more needs for next + } + // End of stream or array + if (aliasing_ == kNoDelta) { + // If there is no more block and aliasing is true, the previous block + // is still valid and we can alias. We have users relying on string_view's + // obtained from protos to outlive the proto, when the parse was from an + // array. This guarantees string_view's are always aliased if parsed from + // an array. + aliasing_ = reinterpret_cast(buffer_end_) - + reinterpret_cast(buffer_); + } + next_chunk_ = nullptr; + buffer_end_ = buffer_ + kSlopBytes; + size_ = 0; + return buffer_; +} + +std::pair EpsCopyInputStream::DoneFallback(const char* ptr, + int d) { + GOOGLE_DCHECK(ptr >= limit_end_); + int overrun = ptr - buffer_end_; + GOOGLE_DCHECK(overrun <= kSlopBytes); // Guaranteed by parse loop. + // Did we exceeded the limit (parse error). + if (PROTOBUF_PREDICT_FALSE(overrun > limit_)) return {nullptr, true}; + GOOGLE_DCHECK(overrun != limit_); // Guaranteed by caller. + GOOGLE_DCHECK(overrun < limit_); // Follows from above + // TODO(gerbens) Instead of this dcheck we could just assign, and remove + // updating the limit_end from PopLimit, ie. + // limit_end_ = buffer_end_ + (std::min)(0, limit_); + // if (ptr < limit_end_) return {ptr, false}; + GOOGLE_DCHECK(limit_end_ == buffer_end_ + (std::min)(0, limit_)); + // At this point we know the following assertion holds. + GOOGLE_DCHECK(limit_ > 0); + GOOGLE_DCHECK(limit_end_ == buffer_end_); // because limit_ > 0 + do { + // We are past the end of buffer_end_, in the slop region. + GOOGLE_DCHECK(overrun >= 0); + auto p = Next(overrun, d); + if (p == nullptr) { + // We are at the end of the stream + if (PROTOBUF_PREDICT_FALSE(overrun != 0)) return {nullptr, true}; + GOOGLE_DCHECK(limit_ > 0); + limit_end_ = buffer_end_; + // Distinquish ending on a pushed limit or ending on end-of-stream. + SetEndOfStream(); + return {ptr, true}; + } + limit_ -= buffer_end_ - p; // Adjust limit_ relative to new anchor + ptr = p + overrun; + overrun = ptr - buffer_end_; + } while (overrun >= 0); + limit_end_ = buffer_end_ + std::min(0, limit_); + return {ptr, false}; +} + +const char* EpsCopyInputStream::SkipFallback(const char* ptr, int size) { + return AppendSize(ptr, size, [](const char* p, int s) {}); +} + +const char* EpsCopyInputStream::ReadStringFallback(const char* ptr, int size, + std::string* s) { + s->clear(); + // TODO(gerbens) assess security. At the moment its parity with + // CodedInputStream but it allows a payload to reserve large memory. + if (PROTOBUF_PREDICT_TRUE(size <= buffer_end_ - ptr + limit_)) { + s->reserve(size); + } + return AppendStringFallback(ptr, size, s); +} + +const char* EpsCopyInputStream::AppendStringFallback(const char* ptr, int size, + std::string* str) { + // TODO(gerbens) assess security. At the moment its parity with + // CodedInputStream but it allows a payload to reserve large memory. + if (PROTOBUF_PREDICT_TRUE(size <= buffer_end_ - ptr + limit_)) { + str->reserve(size); + } + return AppendSize(ptr, size, + [str](const char* p, int s) { str->append(p, s); }); +} + + +template +const char* EpsCopyInputStream::ReadRepeatedFixed(const char* ptr, + Tag expected_tag, + RepeatedField* out) { + do { + out->Add(UnalignedLoad(ptr)); + ptr += sizeof(T); + if (PROTOBUF_PREDICT_FALSE(ptr >= limit_end_)) return ptr; + } while (UnalignedLoad(ptr) == expected_tag&& ptr += sizeof(Tag)); + return ptr; +} + +template +const char* EpsCopyInputStream::ReadPackedFixed(const char* ptr, int size, + RepeatedField* out) { + int nbytes = buffer_end_ + kSlopBytes - ptr; + while (size > nbytes) { + int num = nbytes / sizeof(T); + int old_entries = out->size(); + out->Reserve(old_entries + num); + int block_size = num * sizeof(T); + std::memcpy(out->AddNAlreadyReserved(num), ptr, block_size); + ptr += block_size; + size -= block_size; + if (DoneWithCheck(&ptr, -1)) return nullptr; + nbytes = buffer_end_ + kSlopBytes - ptr; + } + int num = size / sizeof(T); + int old_entries = out->size(); + out->Reserve(old_entries + num); + int block_size = num * sizeof(T); + std::memcpy(out->AddNAlreadyReserved(num), ptr, block_size); + ptr += block_size; + if (size != block_size) return nullptr; + return ptr; +} + +const char* EpsCopyInputStream::InitFrom(io::ZeroCopyInputStream* zcis) { + zcis_ = zcis; + const void* data; + int size; + limit_ = INT_MAX; + if (zcis->Next(&data, &size)) { + overall_limit_ -= size; + if (size > kSlopBytes) { + auto ptr = static_cast(data); + limit_ -= size - kSlopBytes; + limit_end_ = buffer_end_ = ptr + size - kSlopBytes; + next_chunk_ = buffer_; + if (aliasing_ == kOnPatch) aliasing_ = kNoDelta; + return ptr; + } else { + limit_end_ = buffer_end_ = buffer_ + kSlopBytes; + next_chunk_ = buffer_; + auto ptr = buffer_ + 2 * kSlopBytes - size; + std::memcpy(ptr, data, size); + return ptr; + } + } + overall_limit_ = 0; + next_chunk_ = nullptr; + size_ = 0; + limit_end_ = buffer_end_ = buffer_; + return buffer_; +} + +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* ParseContext::ParseMessage(MessageLite* msg, const char* ptr) { + return ParseMessage(msg, ptr); +} +const char* ParseContext::ParseMessage(Message* msg, const char* ptr) { + // Use reinterptret case to prevent inclusion of non lite header + return ParseMessage(reinterpret_cast(msg), ptr); +} +#endif + +inline void WriteVarint(uint64 val, std::string* s) { + while (val >= 128) { + uint8 c = val | 0x80; + s->push_back(c); + val >>= 7; + } + s->push_back(val); +} + +void WriteVarint(uint32 num, uint64 val, std::string* s) { + WriteVarint(num << 3, s); + WriteVarint(val, s); +} + +void WriteLengthDelimited(uint32 num, StringPiece val, std::string* s) { + WriteVarint((num << 3) + 2, s); + WriteVarint(val.size(), s); + s->append(val.data(), val.size()); +} + +std::pair ReadTagFallback(const char* p, uint32 res) { + for (std::uint32_t i = 0; i < 3; i++) { + std::uint32_t byte = static_cast(p[i]); + res += (byte - 1) << (7 * (i + 2)); + if (PROTOBUF_PREDICT_TRUE(byte < 128)) { + return {p + i + 1, res}; + } + } + return {nullptr, 0}; +} + +std::pair ParseVarint64Fallback(const char* p, + uint64 res) { + return ParseVarint64FallbackInline(p, res); +} + +std::pair ReadSizeFallback(const char* p, uint32 first) { + uint32 tmp; + auto res = VarintParse<4>(p + 1, &tmp); + if (tmp >= (1 << 24) - ParseContext::kSlopBytes) return {nullptr, 0}; + return {res, (tmp << 7) + first - 0x80}; +} + +const char* StringParser(const char* begin, const char* end, void* object, + ParseContext*) { + auto str = static_cast(object); + str->append(begin, end - begin); + return end; +} + +// Defined in wire_format_lite.cc +void PrintUTF8ErrorLog(const char* field_name, const char* operation_str, + bool emit_stacktrace); + +bool VerifyUTF8(StringPiece str, const char* field_name) { + if (!IsStructurallyValidUTF8(str)) { + PrintUTF8ErrorLog(field_name, "parsing", false); + return false; + } + return true; +} + +const char* InlineGreedyStringParser(std::string* s, const char* ptr, + ParseContext* ctx) { + int size = ReadSize(&ptr); + if (!ptr) return nullptr; + return ctx->ReadString(ptr, size, s); +} + +const char* InlineGreedyStringParserUTF8(std::string* s, const char* ptr, + ParseContext* ctx, + const char* field_name) { + auto p = InlineGreedyStringParser(s, ptr, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(VerifyUTF8(*s, field_name)); + return p; +} + + +template +const char* VarintParser(void* object, const char* ptr, ParseContext* ctx) { + return ctx->ReadPackedVarint(ptr, [object](uint64 varint) { + T val; + if (sign) { + if (sizeof(T) == 8) { + val = WireFormatLite::ZigZagDecode64(varint); + } else { + val = WireFormatLite::ZigZagDecode32(varint); + } + } else { + val = varint; + } + static_cast*>(object)->Add(val); + }); +} + +const char* PackedInt32Parser(void* object, const char* ptr, + ParseContext* ctx) { + return VarintParser(object, ptr, ctx); +} +const char* PackedUInt32Parser(void* object, const char* ptr, + ParseContext* ctx) { + return VarintParser(object, ptr, ctx); +} +const char* PackedInt64Parser(void* object, const char* ptr, + ParseContext* ctx) { + return VarintParser(object, ptr, ctx); +} +const char* PackedUInt64Parser(void* object, const char* ptr, + ParseContext* ctx) { + return VarintParser(object, ptr, ctx); +} +const char* PackedSInt32Parser(void* object, const char* ptr, + ParseContext* ctx) { + return VarintParser(object, ptr, ctx); +} +const char* PackedSInt64Parser(void* object, const char* ptr, + ParseContext* ctx) { + return VarintParser(object, ptr, ctx); +} + +const char* PackedEnumParser(void* object, const char* ptr, ParseContext* ctx) { + return VarintParser(object, ptr, ctx); +} + +const char* PackedEnumParser(void* object, const char* ptr, ParseContext* ctx, + bool (*is_valid)(int), std::string* unknown, + int field_num) { + return ctx->ReadPackedVarint( + ptr, [object, is_valid, unknown, field_num](uint64 val) { + if (is_valid(val)) { + static_cast*>(object)->Add(val); + } else { + WriteVarint(field_num, val, unknown); + } + }); +} + +const char* PackedEnumParserArg(void* object, const char* ptr, + ParseContext* ctx, + bool (*is_valid)(const void*, int), + const void* data, std::string* unknown, + int field_num) { + return ctx->ReadPackedVarint( + ptr, [object, is_valid, data, unknown, field_num](uint64 val) { + if (is_valid(data, val)) { + static_cast*>(object)->Add(val); + } else { + WriteVarint(field_num, val, unknown); + } + }); +} + +const char* PackedBoolParser(void* object, const char* ptr, ParseContext* ctx) { + return VarintParser(object, ptr, ctx); +} + +template +const char* FixedParser(void* object, const char* ptr, ParseContext* ctx) { + int size = ReadSize(&ptr); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + return ctx->ReadPackedFixed(ptr, size, + static_cast*>(object)); +} + +const char* PackedFixed32Parser(void* object, const char* ptr, + ParseContext* ctx) { + return FixedParser(object, ptr, ctx); +} +const char* PackedSFixed32Parser(void* object, const char* ptr, + ParseContext* ctx) { + return FixedParser(object, ptr, ctx); +} +const char* PackedFixed64Parser(void* object, const char* ptr, + ParseContext* ctx) { + return FixedParser(object, ptr, ctx); +} +const char* PackedSFixed64Parser(void* object, const char* ptr, + ParseContext* ctx) { + return FixedParser(object, ptr, ctx); +} +const char* PackedFloatParser(void* object, const char* ptr, + ParseContext* ctx) { + return FixedParser(object, ptr, ctx); +} +const char* PackedDoubleParser(void* object, const char* ptr, + ParseContext* ctx) { + return FixedParser(object, ptr, ctx); +} + +class UnknownFieldLiteParserHelper { + public: + explicit UnknownFieldLiteParserHelper(std::string* unknown) + : unknown_(unknown) {} + + void AddVarint(uint32 num, uint64 value) { + if (unknown_ == nullptr) return; + WriteVarint(num * 8, unknown_); + WriteVarint(value, unknown_); + } + void AddFixed64(uint32 num, uint64 value) { + if (unknown_ == nullptr) return; + WriteVarint(num * 8 + 1, unknown_); + char buffer[8]; + std::memcpy(buffer, &value, 8); + unknown_->append(buffer, 8); + } + const char* ParseLengthDelimited(uint32 num, const char* ptr, + ParseContext* ctx) { + int size = ReadSize(&ptr); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + if (unknown_ == nullptr) return ctx->Skip(ptr, size); + WriteVarint(num * 8 + 2, unknown_); + WriteVarint(size, unknown_); + return ctx->AppendString(ptr, size, unknown_); + } + const char* ParseGroup(uint32 num, const char* ptr, ParseContext* ctx) { + if (unknown_) WriteVarint(num * 8 + 3, unknown_); + ptr = ctx->ParseGroup(this, ptr, num * 8 + 3); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + if (unknown_) WriteVarint(num * 8 + 4, unknown_); + return ptr; + } + void AddFixed32(uint32 num, uint32 value) { + if (unknown_ == nullptr) return; + WriteVarint(num * 8 + 5, unknown_); + char buffer[4]; + std::memcpy(buffer, &value, 4); + unknown_->append(buffer, 4); + } + + const char* _InternalParse(const char* ptr, ParseContext* ctx) { + return WireFormatParser(*this, ptr, ctx); + } + + private: + std::string* unknown_; +}; + +const char* UnknownGroupLiteParse(std::string* unknown, const char* ptr, + ParseContext* ctx) { + UnknownFieldLiteParserHelper field_parser(unknown); + return WireFormatParser(field_parser, ptr, ctx); +} + +const char* UnknownFieldParse(uint32 tag, std::string* unknown, const char* ptr, + ParseContext* ctx) { + UnknownFieldLiteParserHelper field_parser(unknown); + return FieldParser(tag, field_parser, ptr, ctx); +} + +const char* UnknownFieldParse(uint32 tag, + InternalMetadataWithArenaLite* metadata, + const char* ptr, ParseContext* ctx) { + return UnknownFieldParse(tag, metadata->mutable_unknown_fields(), ptr, ctx); +} + +} // namespace internal +} // namespace protobuf +} // namespace google diff --git a/third_party/protobuf/src/google/protobuf/parse_context.h b/third_party/protobuf/src/google/protobuf/parse_context.h new file mode 100644 index 00000000..81b9406a --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/parse_context.h @@ -0,0 +1,759 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#ifndef GOOGLE_PROTOBUF_PARSE_CONTEXT_H__ +#define GOOGLE_PROTOBUF_PARSE_CONTEXT_H__ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + + +namespace google { +namespace protobuf { + +class UnknownFieldSet; +class DescriptorPool; +class MessageFactory; + +namespace internal { + +// Template code below needs to know about the existence of these functions. +PROTOBUF_EXPORT void WriteVarint(uint32 num, uint64 val, std::string* s); +PROTOBUF_EXPORT void WriteLengthDelimited(uint32 num, StringPiece val, + std::string* s); +// Inline because it is just forwarding to s->WriteVarint +inline void WriteVarint(uint32 num, uint64 val, UnknownFieldSet* s); +inline void WriteLengthDelimited(uint32 num, StringPiece val, + UnknownFieldSet* s); + + +// The basic abstraction the parser is designed for is a slight modification +// of the ZeroCopyInputStream (ZCIS) abstraction. A ZCIS presents a serialized +// stream as a series of buffers that concatenate to the full stream. +// Pictorially a ZCIS presents a stream in chunks like so +// [---------------------------------------------------------------] +// [---------------------] chunk 1 +// [----------------------------] chunk 2 +// chunk 3 [--------------] +// +// Where the '-' represent the bytes which are vertically lined up with the +// bytes of the stream. The proto parser requires its input to be presented +// similarily with the extra +// property that each chunk has kSlopBytes past its end that overlaps with the +// first kSlopBytes of the next chunk, or if there is no next chunk at least its +// still valid to read those bytes. Again, pictorially, we now have +// +// [---------------------------------------------------------------] +// [-------------------....] chunk 1 +// [------------------------....] chunk 2 +// chunk 3 [------------------..**] +// chunk 4 [--****] +// Here '-' mean the bytes of the stream or chunk and '.' means bytes past the +// chunk that match up with the start of the next chunk. Above each chunk has +// 4 '.' after the chunk. In the case these 'overflow' bytes represents bytes +// past the stream, indicated by '*' above, their values are unspecified. It is +// still legal to read them (ie. should not segfault). Reading past the +// end should be detected by the user and indicated as an error. +// +// The reason for this, admittedly, unconventional invariant is to ruthlessly +// optimize the protobuf parser. Having an overlap helps in two important ways. +// Firstly it alleviates having to performing bounds checks if a piece of code +// is guaranteed to not read more than kSlopBytes. Secondly, and more +// importantly, the protobuf wireformat is such that reading a key/value pair is +// always less than 16 bytes. This removes the need to change to next buffer in +// the middle of reading primitive values. Hence there is no need to store and +// load the current position. + +class PROTOBUF_EXPORT EpsCopyInputStream { + public: + enum { kSlopBytes = 16, kMaxCordBytesToCopy = 512 }; + + explicit EpsCopyInputStream(bool enable_aliasing) + : aliasing_(enable_aliasing ? kOnPatch : kNoAliasing) {} + + void BackUp(const char* ptr) { + GOOGLE_DCHECK(ptr <= buffer_end_ + kSlopBytes); + int count; + if (next_chunk_ == buffer_) { + count = static_cast(buffer_end_ + kSlopBytes - ptr); + } else { + count = size_ + static_cast(buffer_end_ - ptr); + } + if (count > 0) zcis_->BackUp(count); + } + + // If return value is negative it's an error + PROTOBUF_MUST_USE_RESULT int PushLimit(const char* ptr, int limit) { + GOOGLE_DCHECK(limit >= 0); + limit += ptr - buffer_end_; + limit_end_ = buffer_end_ + (std::min)(0, limit); + auto old_limit = limit_; + limit_ = limit; + return old_limit - limit; + } + + PROTOBUF_MUST_USE_RESULT bool PopLimit(int delta) { + if (PROTOBUF_PREDICT_FALSE(!EndedAtLimit())) return false; + limit_ = limit_ + delta; + // TODO(gerbens) We could remove this line and hoist the code to + // DoneFallback. Study the perf/bin-size effects. + limit_end_ = buffer_end_ + (std::min)(0, limit_); + return true; + } + + PROTOBUF_MUST_USE_RESULT const char* Skip(const char* ptr, int size) { + if (size <= buffer_end_ + kSlopBytes - ptr) { + return ptr + size; + } + return SkipFallback(ptr, size); + } + PROTOBUF_MUST_USE_RESULT const char* ReadString(const char* ptr, int size, + std::string* s) { + if (size <= buffer_end_ + kSlopBytes - ptr) { + s->assign(ptr, size); + return ptr + size; + } + return ReadStringFallback(ptr, size, s); + } + PROTOBUF_MUST_USE_RESULT const char* AppendString(const char* ptr, int size, + std::string* s) { + if (size <= buffer_end_ + kSlopBytes - ptr) { + s->append(ptr, size); + return ptr + size; + } + return AppendStringFallback(ptr, size, s); + } + + template + PROTOBUF_MUST_USE_RESULT const char* ReadRepeatedFixed(const char* ptr, + Tag expected_tag, + RepeatedField* out); + + template + PROTOBUF_MUST_USE_RESULT const char* ReadPackedFixed(const char* ptr, + int size, + RepeatedField* out); + template + PROTOBUF_MUST_USE_RESULT const char* ReadPackedVarint(const char* ptr, + Add add); + + uint32 LastTag() const { return last_tag_minus_1_ + 1; } + bool ConsumeEndGroup(uint32 start_tag) { + bool res = last_tag_minus_1_ == start_tag; + last_tag_minus_1_ = 0; + return res; + } + bool EndedAtLimit() const { return last_tag_minus_1_ == 0; } + bool EndedAtEndOfStream() const { return last_tag_minus_1_ == 1; } + void SetLastTag(uint32 tag) { last_tag_minus_1_ = tag - 1; } + void SetEndOfStream() { last_tag_minus_1_ = 1; } + bool IsExceedingLimit(const char* ptr) { + return ptr > limit_end_ && + (next_chunk_ == nullptr || ptr - buffer_end_ > limit_); + } + // Returns true if more data is available, if false is returned one has to + // call Done for further checks. + bool DataAvailable(const char* ptr) { return ptr < limit_end_; } + + protected: + // Returns true is limit (either an explicit limit or end of stream) is + // reached. It aligns *ptr across buffer seams. + // If limit is exceeded it returns true and ptr is set to null. + bool DoneWithCheck(const char** ptr, int d) { + GOOGLE_DCHECK(*ptr); + if (PROTOBUF_PREDICT_TRUE(*ptr < limit_end_)) return false; + // No need to fetch buffer if we ended on a limit in the slop region + if ((*ptr - buffer_end_) == limit_) return true; + auto res = DoneFallback(*ptr, d); + *ptr = res.first; + return res.second; + } + + const char* InitFrom(StringPiece flat) { + overall_limit_ = 0; + if (flat.size() > kSlopBytes) { + limit_ = kSlopBytes; + limit_end_ = buffer_end_ = flat.end() - kSlopBytes; + next_chunk_ = buffer_; + if (aliasing_ == kOnPatch) aliasing_ = kNoDelta; + return flat.begin(); + } else { + std::memcpy(buffer_, flat.begin(), flat.size()); + limit_ = 0; + limit_end_ = buffer_end_ = buffer_ + flat.size(); + next_chunk_ = nullptr; + if (aliasing_ == kOnPatch) { + aliasing_ = reinterpret_cast(flat.data()) - + reinterpret_cast(buffer_); + } + return buffer_; + } + } + + const char* InitFrom(io::ZeroCopyInputStream* zcis); + + const char* InitFrom(io::ZeroCopyInputStream* zcis, int limit) { + overall_limit_ = limit; + auto res = InitFrom(zcis); + limit_ = limit - static_cast(buffer_end_ - res); + limit_end_ = buffer_end_ + (std::min)(0, limit_); + return res; + } + + private: + const char* limit_end_; // buffer_end_ + min(limit_, 0) + const char* buffer_end_; + const char* next_chunk_; + int size_; + int limit_; // relative to buffer_end_; + io::ZeroCopyInputStream* zcis_ = nullptr; + char buffer_[2 * kSlopBytes] = {}; + enum { kNoAliasing = 0, kOnPatch = 1, kNoDelta = 2 }; + std::uintptr_t aliasing_ = kNoAliasing; + // This variable is used to communicate how the parse ended, in order to + // completely verify the parsed data. A wire-format parse can end because of + // one of the following conditions: + // 1) A parse can end on a pushed limit. + // 2) A parse can end on End Of Stream (EOS). + // 3) A parse can end on 0 tag (only valid for toplevel message). + // 4) A parse can end on an end-group tag. + // This variable should always be set to 0, which indicates case 1. If the + // parse terminated due to EOS (case 2), it's set to 1. In case the parse + // ended due to a terminating tag (case 3 and 4) it's set to (tag - 1). + // This var doesn't really belong in EpsCopyInputStream and should be part of + // the ParseContext, but case 2 is most easily and optimally implemented in + // DoneFallback. + uint32 last_tag_minus_1_ = 0; + int overall_limit_ = INT_MAX; // Overall limit independent of pushed limits. + + std::pair DoneFallback(const char* ptr, int d); + const char* Next(int overrun, int d); + const char* SkipFallback(const char* ptr, int size); + const char* AppendStringFallback(const char* ptr, int size, std::string* str); + const char* ReadStringFallback(const char* ptr, int size, std::string* str); + + template + const char* AppendSize(const char* ptr, int size, const A& append) { + int chunk_size = buffer_end_ + kSlopBytes - ptr; + do { + GOOGLE_DCHECK(size > chunk_size); + append(ptr, chunk_size); + ptr += chunk_size; + size -= chunk_size; + // DoneFallBack asserts it isn't called when exactly on the limit. If this + // happens we fail the parse, as we are at the limit and still more bytes + // to read. + if (limit_ == kSlopBytes) return nullptr; + auto res = DoneFallback(ptr, -1); + if (res.second) return nullptr; // If done we passed the limit + ptr = res.first; + chunk_size = buffer_end_ + kSlopBytes - ptr; + } while (size > chunk_size); + append(ptr, size); + return ptr + size; + } + + // AppendUntilEnd appends data until a limit (either a PushLimit or end of + // stream. Normal payloads are from length delimited fields which have an + // explicit size. Reading until limit only comes when the string takes + // the place of a protobuf, ie RawMessage/StringRawMessage, lazy fields and + // implicit weak messages. We keep these methods private and friend them. + template + const char* AppendUntilEnd(const char* ptr, const A& append) { + while (!DoneWithCheck(&ptr, -1)) { + append(ptr, limit_end_ - ptr); + ptr = limit_end_; + } + return ptr; + } + + PROTOBUF_MUST_USE_RESULT const char* AppendString(const char* ptr, + std::string* str) { + return AppendUntilEnd( + ptr, [str](const char* p, ptrdiff_t s) { str->append(p, s); }); + } + friend class ImplicitWeakMessage; +}; + +// ParseContext holds all data that is global to the entire parse. Most +// importantly it contains the input stream, but also recursion depth and also +// stores the end group tag, in case a parser ended on a endgroup, to verify +// matching start/end group tags. +class PROTOBUF_EXPORT ParseContext : public EpsCopyInputStream { + public: + struct Data { + const DescriptorPool* pool = nullptr; + MessageFactory* factory = nullptr; + }; + + template + ParseContext(int depth, bool aliasing, const char** start, T&&... args) + : EpsCopyInputStream(aliasing), depth_(depth) { + *start = InitFrom(std::forward(args)...); + } + + void TrackCorrectEnding() { group_depth_ = 0; } + + bool Done(const char** ptr) { return DoneWithCheck(ptr, group_depth_); } + bool DoneNoSlopCheck(const char** ptr) { return DoneWithCheck(ptr, -1); } + + int depth() const { return depth_; } + + Data& data() { return data_; } + const Data& data() const { return data_; } + + template + PROTOBUF_MUST_USE_RESULT PROTOBUF_ALWAYS_INLINE const char* ParseMessage( + T* msg, const char* ptr); + // We outline when the type is generic and we go through a virtual + const char* ParseMessage(MessageLite* msg, const char* ptr); + const char* ParseMessage(Message* msg, const char* ptr); + + template + PROTOBUF_MUST_USE_RESULT PROTOBUF_ALWAYS_INLINE const char* ParseGroup( + T* msg, const char* ptr, uint32 tag) { + if (--depth_ < 0) return nullptr; + group_depth_++; + ptr = msg->_InternalParse(ptr, this); + group_depth_--; + depth_++; + if (PROTOBUF_PREDICT_FALSE(!ConsumeEndGroup(tag))) return nullptr; + return ptr; + } + + private: + // The context keeps an internal stack to keep track of the recursive + // part of the parse state. + // Current depth of the active parser, depth counts down. + // This is used to limit recursion depth (to prevent overflow on malicious + // data), but is also used to index in stack_ to store the current state. + int depth_; + // Unfortunately necessary for the fringe case of ending on 0 or end-group tag + // in the last kSlopBytes of a ZeroCopyInputStream chunk. + int group_depth_ = INT_MIN; + Data data_; +}; + +template +T UnalignedLoad(const void* p) { + T res; + memcpy(&res, p, sizeof(T)); + return res; +} + +// TODO(gerbens) Experiment with best implementation. +// Clang unrolls loop and generating pretty good code on O2, gcc doesn't. +// Unclear if we want 64 bit parse loop unrolled, inlined or opaque function +// call. Hence experimentation is needed. +// Important guarantee is that it doesn't read more than size bytes from p. +template +PROTOBUF_MUST_USE_RESULT const char* VarintParse(const char* p, T* out) { + T res = 1; + for (int i = 0; i < size; i++) { + T byte = static_cast(p[i]); + res += (byte - 1) << (i * 7); + int j = i + 1; + if (PROTOBUF_PREDICT_TRUE(byte < 128)) { + *out = res; + return p + j; + } + } + *out = 0; + return nullptr; +} + +// Decode 2 consecutive bytes of a varint and returns the value, shifted left +// by 1. It simultaneous updates *ptr to *ptr + 1 or *ptr + 2 depending if the +// first byte's continuation bit is set. +// If bit 15 of return value is set (equivalent to the continuation bits of both +// bytes being set) the varint continues, otherwise the parse is done. On x86 +// movsx eax, dil +// add edi, eax +// adc [rsi], 1 +// add eax, eax +// and eax, edi +inline uint32 DecodeTwoBytes(uint32 value, const char** ptr) { + // Sign extend the low byte continuation bit + uint32_t x = static_cast(value); + // This add is an amazing operation, it cancels the low byte continuation bit + // from y transferring it to the carry. Simultaneously it also shifts the 7 + // LSB left by one tightly against high byte varint bits. Hence value now + // contains the unpacked value shifted left by 1. + value += x; + // Use the carry to update the ptr appropriately. + *ptr += value < x ? 2 : 1; + return value & (x + x); // Mask out the high byte iff no continuation +} + +// Used for tags, could read up to 5 bytes which must be available. +// Caller must ensure its safe to call. + +std::pair ReadTagFallback(const char* p, uint32 res); + +inline const char* ReadTag(const char* p, uint32* out) { + uint32 res = static_cast(p[0]); + if (res < 128) { + *out = res; + return p + 1; + } + uint32 second = static_cast(p[1]); + res += (second - 1) << 7; + if (second < 128) { + *out = res; + return p + 2; + } + auto tmp = ReadTagFallback(p + 2, res); + *out = tmp.second; + return tmp.first; +} + +// Will preload the next 2 bytes +inline const char* ReadTag(const char* p, uint32* out, uint32* preload) { + uint32 res = static_cast(p[0]); + if (res < 128) { + *out = res; + *preload = UnalignedLoad(p + 1); + return p + 1; + } + uint32 second = static_cast(p[1]); + res += (second - 1) << 7; + if (second < 128) { + *out = res; + *preload = UnalignedLoad(p + 2); + return p + 2; + } + auto tmp = ReadTagFallback(p + 2, res); + *out = tmp.second; + return tmp.first; +} + +inline std::pair ParseVarint64FallbackInline(const char* p, + uint64 res) { + res >>= 1; + for (std::uint32_t i = 0; i < 4; i++) { + auto pnew = p + 2 * i; + auto tmp = DecodeTwoBytes(UnalignedLoad(pnew), &pnew); + res += (static_cast(tmp) - 2) << (14 * (i + 1) - 1); + if (PROTOBUF_PREDICT_TRUE(std::int16_t(tmp) >= 0)) { + return {pnew, res}; + } + } + return {nullptr, res}; +} + +inline const char* ParseVarint64Inline(const char* p, uint64* out) { + auto tmp = DecodeTwoBytes(UnalignedLoad(p), &p); + if (PROTOBUF_PREDICT_TRUE(static_cast(tmp) >= 0)) { + *out = tmp >> 1; + return p; + } + auto x = ParseVarint64FallbackInline(p, tmp); + *out = x.second; + return x.first; +} + +std::pair ParseVarint64Fallback(const char* p, uint64 res); + +inline const char* ParseVarint64(const char* p, uint32 preload, uint64* out) { + auto tmp = DecodeTwoBytes(preload, &p); + if (PROTOBUF_PREDICT_TRUE(static_cast(tmp) >= 0)) { + *out = tmp >> 1; + return p; + } + auto x = ParseVarint64Fallback(p, tmp); + *out = x.second; + return x.first; +} + +// Used for reading varint wiretype values, could read up to 10 bytes. +// Caller must ensure its safe to call. +inline const char* ParseVarint64(const char* p, uint64* out) { + return ParseVarint64(p, UnalignedLoad(p), out); +} + +std::pair ReadSizeFallback(const char* p, uint32 first); +// Used for tags, could read up to 5 bytes which must be available. Additionally +// it makes sure the unsigned value fits a int32, otherwise returns nullptr. +// Caller must ensure its safe to call. +inline uint32 ReadSize(const char** pp) { + auto p = *pp; + uint32 res = static_cast(p[0]); + if (res < 128) { + *pp = p + 1; + return res; + } + auto x = ReadSizeFallback(p, res); + *pp = x.first; + return x.second; +} + +// Some convenience functions to simplify the generated parse loop code. +// Returning the value and updating the buffer pointer allows for nicer +// function composition. We rely on the compiler to inline this. +// Also in debug compiles having local scoped variables tend to generated +// stack frames that scale as O(num fields). +inline uint64 ReadVarint(const char** p) { + uint64 tmp; + *p = ParseVarint64(*p, &tmp); + return tmp; +} + +inline int64 ReadVarintZigZag64(const char** p) { + uint64 tmp; + *p = ParseVarint64(*p, &tmp); + return WireFormatLite::ZigZagDecode64(tmp); +} + +inline int32 ReadVarintZigZag32(const char** p) { + uint64 tmp; + *p = ParseVarint64(*p, &tmp); + return WireFormatLite::ZigZagDecode32(static_cast(tmp)); +} + +inline uint64 ReadVarint(const char** p, uint32 preload) { + uint64 tmp; + *p = ParseVarint64(*p, preload, &tmp); + return tmp; +} + +inline int64 ReadVarintZigZag64(const char** p, uint32 preload) { + uint64 tmp; + *p = ParseVarint64(*p, preload, &tmp); + return WireFormatLite::ZigZagDecode64(tmp); +} + +inline int32 ReadVarintZigZag32(const char** p, uint32 preload) { + uint64 tmp; + *p = ParseVarint64(*p, preload, &tmp); + return WireFormatLite::ZigZagDecode32(static_cast(tmp)); +} + +template +PROTOBUF_MUST_USE_RESULT const char* ParseContext::ParseMessage( + T* msg, const char* ptr) { + int size = ReadSize(&ptr); + if (!ptr) return nullptr; + auto old = PushLimit(ptr, size); + if (--depth_ < 0) return nullptr; + ptr = msg->_InternalParse(ptr, this); + if (PROTOBUF_PREDICT_FALSE(ptr == nullptr)) return nullptr; + depth_++; + if (!PopLimit(old)) return nullptr; + return ptr; +} + +template +const char* EpsCopyInputStream::ReadPackedVarint(const char* ptr, Add add) { + int size = ReadSize(&ptr); + if (ptr == nullptr) return nullptr; + auto old = PushLimit(ptr, size); + if (old < 0) return nullptr; + while (!DoneWithCheck(&ptr, -1)) { + uint64 varint; + ptr = ParseVarint64(ptr, &varint); + if (!ptr) return nullptr; + add(varint); + } + if (!PopLimit(old)) return nullptr; + return ptr; +} + +// Helper for verification of utf8 +PROTOBUF_EXPORT +bool VerifyUTF8(StringPiece s, const char* field_name); + +// All the string parsers with or without UTF checking and for all CTypes. +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* InlineGreedyStringParser( + std::string* s, const char* ptr, ParseContext* ctx); + +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* +InlineGreedyStringParserUTF8(std::string* s, const char* ptr, ParseContext* ctx, + const char* field_name); +// Inline because we don't want to pay the price of field_name in opt mode. +inline PROTOBUF_MUST_USE_RESULT const char* InlineGreedyStringParserUTF8Verify( + std::string* s, const char* ptr, ParseContext* ctx, + const char* field_name) { + auto p = InlineGreedyStringParser(s, ptr, ctx); +#ifndef NDEBUG + VerifyUTF8(*s, field_name); +#endif // !NDEBUG + return p; +} + + +// Add any of the following lines to debug which parse function is failing. + +#define GOOGLE_PROTOBUF_ASSERT_RETURN(predicate, ret) \ + if (!(predicate)) { \ + /* ::raise(SIGINT); */ \ + /* GOOGLE_LOG(ERROR) << "Parse failure"; */ \ + return ret; \ + } + +#define GOOGLE_PROTOBUF_PARSER_ASSERT(predicate) \ + GOOGLE_PROTOBUF_ASSERT_RETURN(predicate, nullptr) + +template +PROTOBUF_MUST_USE_RESULT const char* FieldParser(uint64 tag, T& field_parser, + const char* ptr, + ParseContext* ctx) { + uint32 number = tag >> 3; + GOOGLE_PROTOBUF_PARSER_ASSERT(number != 0); + using WireType = internal::WireFormatLite::WireType; + switch (tag & 7) { + case WireType::WIRETYPE_VARINT: { + uint64 value; + ptr = ParseVarint64(ptr, &value); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + field_parser.AddVarint(number, value); + break; + } + case WireType::WIRETYPE_FIXED64: { + uint64 value = UnalignedLoad(ptr); + ptr += 8; + field_parser.AddFixed64(number, value); + break; + } + case WireType::WIRETYPE_LENGTH_DELIMITED: { + ptr = field_parser.ParseLengthDelimited(number, ptr, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + break; + } + case WireType::WIRETYPE_START_GROUP: { + ptr = field_parser.ParseGroup(number, ptr, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + break; + } + case WireType::WIRETYPE_END_GROUP: { + GOOGLE_LOG(FATAL) << "Can't happen"; + break; + } + case WireType::WIRETYPE_FIXED32: { + uint32 value = UnalignedLoad(ptr); + ptr += 4; + field_parser.AddFixed32(number, value); + break; + } + default: + return nullptr; + } + return ptr; +} + +template +PROTOBUF_MUST_USE_RESULT const char* WireFormatParser(T& field_parser, + const char* ptr, + ParseContext* ctx) { + while (!ctx->Done(&ptr)) { + uint32 tag; + ptr = ReadTag(ptr, &tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); + if (tag == 0 || (tag & 7) == 4) { + ctx->SetLastTag(tag); + return ptr; + } + ptr = FieldParser(tag, field_parser, ptr, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); + } + return ptr; +} + +// The packed parsers parse repeated numeric primitives directly into the +// corresponding field + +// These are packed varints +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedInt32Parser( + void* object, const char* ptr, ParseContext* ctx); +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedUInt32Parser( + void* object, const char* ptr, ParseContext* ctx); +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedInt64Parser( + void* object, const char* ptr, ParseContext* ctx); +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedUInt64Parser( + void* object, const char* ptr, ParseContext* ctx); +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedSInt32Parser( + void* object, const char* ptr, ParseContext* ctx); +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedSInt64Parser( + void* object, const char* ptr, ParseContext* ctx); +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedEnumParser( + void* object, const char* ptr, ParseContext* ctx); +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedEnumParser( + void* object, const char* ptr, ParseContext* ctx, bool (*is_valid)(int), + std::string* unknown, int field_num); +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedEnumParserArg( + void* object, const char* ptr, ParseContext* ctx, + bool (*is_valid)(const void*, int), const void* data, std::string* unknown, + int field_num); + +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedBoolParser( + void* object, const char* ptr, ParseContext* ctx); +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedFixed32Parser( + void* object, const char* ptr, ParseContext* ctx); +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedSFixed32Parser( + void* object, const char* ptr, ParseContext* ctx); +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedFixed64Parser( + void* object, const char* ptr, ParseContext* ctx); +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedSFixed64Parser( + void* object, const char* ptr, ParseContext* ctx); +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedFloatParser( + void* object, const char* ptr, ParseContext* ctx); +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedDoubleParser( + void* object, const char* ptr, ParseContext* ctx); + +// This is the only recursive parser. +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* UnknownGroupLiteParse( + std::string* unknown, const char* ptr, ParseContext* ctx); +// This is a helper to for the UnknownGroupLiteParse but is actually also +// useful in the generated code. It uses overload on std::string* vs +// UnknownFieldSet* to make the generated code isomorphic between full and lite. +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* UnknownFieldParse( + uint32 tag, std::string* unknown, const char* ptr, ParseContext* ctx); +PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* UnknownFieldParse( + uint32 tag, InternalMetadataWithArenaLite* metadata, const char* ptr, + ParseContext* ctx); + +} // namespace internal +} // namespace protobuf +} // namespace google + +#include + +#endif // GOOGLE_PROTOBUF_PARSE_CONTEXT_H__ diff --git a/third_party/protobuf/src/google/protobuf/port.h b/third_party/protobuf/src/google/protobuf/port.h new file mode 100644 index 00000000..63452265 --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/port.h @@ -0,0 +1,6 @@ +#ifndef THIRD_PARTY_PROTOBUF_TESTING_PROTOBUF_SRC_GOOGLE_PROTOBUF_PORT_H_ +#define THIRD_PARTY_PROTOBUF_TESTING_PROTOBUF_SRC_GOOGLE_PROTOBUF_PORT_H_ + +#include + +#endif // THIRD_PARTY_PROTOBUF_TESTING_PROTOBUF_SRC_GOOGLE_PROTOBUF_PORT_H_ diff --git a/third_party/protobuf/src/google/protobuf/port_def.inc b/third_party/protobuf/src/google/protobuf/port_def.inc new file mode 100644 index 00000000..15064fbf --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/port_def.inc @@ -0,0 +1,360 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// This file defines common macros that are used in protobuf. +// +// To hide these definitions from the outside world (and to prevent collisions +// if more than one version of protobuf is #included in the same project) you +// must follow this pattern when #including port_def.inc in a header file: +// +// #include "other_header.h" +// #include "message.h" +// // etc. +// +// #include "port_def.inc" // MUST be last header included +// +// // Definitions for this header. +// +// #include "port_undef.inc" +// +// This is a textual header with no include guard, because we want to +// detect/prohibit anytime it is #included twice without a corresponding +// #undef. + +// These macros are private and should always be +// ::util::RetrieveErrorSpace(*this) headers. If any of these errors fire, you +// should either properly #include port_undef.h at the end of your header that +// #includes port.h, or don't #include port.h twice in a .cc file. +#ifdef PROTOBUF_NAMESPACE +#error PROTOBUF_NAMESPACE was previously defined +#endif +#ifdef PROTOBUF_NAMESPACE_ID +#error PROTOBUF_NAMESPACE_ID was previously defined +#endif +#ifdef PROTOBUF_ALWAYS_INLINE +#error PROTOBUF_ALWAYS_INLINE was previously defined +#endif +#ifdef PROTOBUF_COLD +#error PROTOBUF_COLD was previously defined +#endif +#ifdef PROTOBUF_NOINLINE +#error PROTOBUF_NOINLINE was previously defined +#endif +#ifdef PROTOBUF_SECTION_VARIABLE +#error PROTOBUF_SECTION_VARIABLE was previously defined +#endif +#ifdef PROTOBUF_DEPRECATED +#error PROTOBUF_DEPRECATED was previously defined +#endif +#ifdef PROTOBUF_DEPRECATED_MSG +#error PROTOBUF_DEPRECATED_MSG was previously defined +#endif +#ifdef PROTOBUF_FUNC_ALIGN +#error PROTOBUF_FUNC_ALIGN was previously defined +#endif +#ifdef PROTOBUF_RETURNS_NONNULL +#error PROTOBUF_RETURNS_NONNULL was previously defined +#endif +#ifdef PROTOBUF_ATTRIBUTE_REINITIALIZES +#error PROTOBUF_ATTRIBUTE_REINITIALIZES was previously defined +#endif +#ifdef PROTOBUF_RTTI +#error PROTOBUF_RTTI was previously defined +#endif +#ifdef PROTOBUF_VERSION +#error PROTOBUF_VERSION was previously defined +#endif +#ifdef PROTOBUF_VERSION_SUFFIX +#error PROTOBUF_VERSION_SUFFIX was previously defined +#endif +#ifdef PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC +#error PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC was previously defined +#endif +#ifdef PROTOBUF_MIN_PROTOC_VERSION +#error PROTOBUF_MIN_PROTOC_VERSION was previously defined +#endif +#ifdef PROTOBUF_PREDICT_TRUE +#error PROTOBUF_PREDICT_TRUE was previously defined +#endif +#ifdef PROTOBUF_PREDICT_FALSE +#error PROTOBUF_PREDICT_FALSE was previously defined +#endif +#ifdef PROTOBUF_FIELD_OFFSET +#error PROTOBUF_FIELD_OFFSET was previously defined +#endif +#ifdef PROTOBUF_LL_FORMAT +#error PROTOBUF_LL_FORMAT was previously defined +#endif +#ifdef PROTOBUF_GUARDED_BY +#error PROTOBUF_GUARDED_BY was previously defined +#endif +#ifdef PROTOBUF_LONGLONG +#error PROTOBUF_LONGLONG was previously defined +#endif +#ifdef PROTOBUF_ULONGLONG +#error PROTOBUF_ULONGLONG was previously defined +#endif +#ifdef PROTOBUF_FALLTHROUGH_INTENDED +#error PROTOBUF_FALLTHROUGH_INTENDED was previously defined +#endif +#ifdef PROTOBUF_EXPORT +#error PROTOBUF_EXPORT was previously defined +#endif +#ifdef PROTOC_EXPORT +#error PROTOC_EXPORT was previously defined +#endif +#ifdef PROTOBUF_MUST_USE_RESULT +#error PROTOBUF_MUST_USE_RESULT was previously defined +#endif +#ifdef PROTOBUF_UNUSED +#error PROTOBUF_UNUSED was previously defined +#endif + + +#define PROTOBUF_NAMESPACE "google::protobuf" +#define PROTOBUF_NAMESPACE_ID google::protobuf +#define PROTOBUF_NAMESPACE_OPEN \ + namespace google { \ + namespace protobuf { +#define PROTOBUF_NAMESPACE_CLOSE \ + } /* namespace protobuf */ \ + } /* namespace google */ +#define PROTOBUF_DEPRECATED +#define PROTOBUF_DEPRECATED_MSG(x) +#define PROTOBUF_SECTION_VARIABLE(x) +#define PROTOBUF_MUST_USE_RESULT + +// ---------------------------------------------------------------------------- +// Annotations: Some parts of the code have been annotated in ways that might +// be useful to some compilers or tools, but are not supported universally. +// You can #define these annotations yourself if the default implementation +// is not right for you. + +#ifdef GOOGLE_ATTRIBUTE_ALWAYS_INLINE +#define PROTOBUF_ALWAYS_INLINE GOOGLE_ATTRIBUTE_ALWAYS_INLINE +#else +#if defined(__GNUC__) && (__GNUC__ > 3 ||(__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) +// For functions we want to force inline. +// Introduced in gcc 3.1. +#define PROTOBUF_ALWAYS_INLINE __attribute__ ((always_inline)) +#else +// Other compilers will have to figure it out for themselves. +#define PROTOBUF_ALWAYS_INLINE +#endif +#endif + +#ifdef GOOGLE_ATTRIBUTE_NOINLINE +#define PROTOBUF_NOINLINE GOOGLE_ATTRIBUTE_NOINLINE +#else +#if defined(__GNUC__) && (__GNUC__ > 3 ||(__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) +// For functions we want to force not inline. +// Introduced in gcc 3.1. +#define PROTOBUF_NOINLINE __attribute__ ((noinline)) +#elif defined(_MSC_VER) && (_MSC_VER >= 1400) +// Seems to have been around since at least Visual Studio 2005 +#define PROTOBUF_NOINLINE __declspec(noinline) +#else +// Other compilers will have to figure it out for themselves. +#define PROTOBUF_NOINLINE +#endif +#endif + +#ifdef GOOGLE_ATTRIBUTE_FUNC_ALIGN +#define PROTOBUF_FUNC_ALIGN GOOGLE_ATTRIBUTE_FUNC_ALIGN +#else +#if defined(__clang__) || \ + defined(__GNUC__) && (__GNUC__ > 4 ||(__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) +// Function alignment attribute introduced in gcc 4.3 +#define PROTOBUF_FUNC_ALIGN(bytes) __attribute__ ((aligned(bytes))) +#else +#define PROTOBUF_FUNC_ALIGN(bytes) +#endif +#endif + +#ifdef GOOGLE_PREDICT_TRUE +#define PROTOBUF_PREDICT_TRUE GOOGLE_PREDICT_TRUE +#else +#ifdef __GNUC__ +// Provided at least since GCC 3.0. +#define PROTOBUF_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1)) +#else +#define PROTOBUF_PREDICT_TRUE(x) (x) +#endif +#endif + +#ifdef GOOGLE_PREDICT_FALSE +#define PROTOBUF_PREDICT_FALSE GOOGLE_PREDICT_FALSE +#else +#ifdef __GNUC__ +// Provided at least since GCC 3.0. +#define PROTOBUF_PREDICT_FALSE(x) (__builtin_expect(x, 0)) +#else +#define PROTOBUF_PREDICT_FALSE(x) (x) +#endif +#endif + +#ifdef GOOGLE_PROTOBUF_ATTRIBUTE_RETURNS_NONNULL +#define PROTOBUF_RETURNS_NONNULL GOOGLE_PROTOBUF_ATTRIBUTE_RETURNS_NONNULL +#else +#ifdef __GNUC__ +#define PROTOBUF_RETURNS_NONNULL __attribute__((returns_nonnull)) +#else +#define PROTOBUF_RETURNS_NONNULL +#endif +#endif + +#if defined(__has_cpp_attribute) +#if __has_cpp_attribute(clang::reinitializes) +#define PROTOBUF_ATTRIBUTE_REINITIALIZES [[clang::reinitializes]] +#endif +#endif +#ifndef PROTOBUF_ATTRIBUTE_REINITIALIZES +#define PROTOBUF_ATTRIBUTE_REINITIALIZES +#endif + +#define PROTOBUF_GUARDED_BY(x) +#define PROTOBUF_COLD + +// Copied from ABSL. +#if defined(__clang__) && defined(__has_warning) +#if __has_feature(cxx_attributes) && __has_warning("-Wimplicit-fallthrough") +#define PROTOBUF_FALLTHROUGH_INTENDED [[clang::fallthrough]] +#endif +#elif defined(__GNUC__) && __GNUC__ >= 7 +#define PROTOBUF_FALLTHROUGH_INTENDED [[gnu::fallthrough]] +#endif + +#ifndef PROTOBUF_FALLTHROUGH_INTENDED +#define PROTOBUF_FALLTHROUGH_INTENDED +#endif + +#if defined(__has_cpp_attribute) +#define HAS_ATTRIBUTE(attr) __has_cpp_attribute(attr) +#else +#define HAS_ATTRIBUTE(attr) 0 +#endif + +#if HAS_ATTRIBUTE(unused) || (defined(__GNUC__) && !defined(__clang__)) +#define PROTOBUF_UNUSED __attribute__((__unused__)) +#else +#define PROTOBUF_UNUSED +#endif + +#undef HAS_ATTRIBUTE + +#ifdef _MSC_VER +#define PROTOBUF_LONGLONG(x) x##I64 +#define PROTOBUF_ULONGLONG(x) x##UI64 +#define PROTOBUF_LL_FORMAT "I64" // As in printf("%I64d", ...) +#else +// By long long, we actually mean int64. +#define PROTOBUF_LONGLONG(x) x##LL +#define PROTOBUF_ULONGLONG(x) x##ULL +// Used to format real long long integers. +#define PROTOBUF_LL_FORMAT \ + "ll" // As in "%lld". Note that "q" is poor form also. +#endif + + +// Shared google3/opensource definitions. ////////////////////////////////////// + +#define PROTOBUF_VERSION 3008000 +#define PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC 3008000 +#define PROTOBUF_MIN_PROTOC_VERSION 3008000 +#define PROTOBUF_VERSION_SUFFIX "" + +// The minimum library version which works with the current version of the +// headers. +#define GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION 3008000 + +#if defined(GOOGLE_PROTOBUF_NO_RTTI) && GOOGLE_PROTOBUF_NO_RTTI +#define PROTOBUF_RTTI 0 +#else +#define PROTOBUF_RTTI 1 +#endif + +// Returns the offset of the given field within the given aggregate type. +// This is equivalent to the ANSI C offsetof() macro. However, according +// to the C++ standard, offsetof() only works on POD types, and GCC +// enforces this requirement with a warning. In practice, this rule is +// unnecessarily strict; there is probably no compiler or platform on +// which the offsets of the direct fields of a class are non-constant. +// Fields inherited from superclasses *can* have non-constant offsets, +// but that's not what this macro will be used for. +#if defined(__clang__) +// For Clang we use __builtin_offsetof() and suppress the warning, +// to avoid Control Flow Integrity and UBSan vptr sanitizers from +// crashing while trying to validate the invalid reinterpet_casts. +#define PROTOBUF_FIELD_OFFSET(TYPE, FIELD) \ + _Pragma("clang diagnostic push") \ + _Pragma("clang diagnostic ignored \"-Winvalid-offsetof\"") \ + __builtin_offsetof(TYPE, FIELD) \ + _Pragma("clang diagnostic pop") +#else +// Note that we calculate relative to the pointer value 16 here since if we +// just use zero, GCC complains about dereferencing a NULL pointer. We +// choose 16 rather than some other number just in case the compiler would +// be confused by an unaligned pointer. +#define PROTOBUF_FIELD_OFFSET(TYPE, FIELD) \ + static_cast< ::google::protobuf::uint32>(reinterpret_cast( \ + &reinterpret_cast(16)->FIELD) - \ + reinterpret_cast(16)) +#endif + + +#if defined(_MSC_VER) && defined(PROTOBUF_USE_DLLS) +#ifdef LIBPROTOBUF_EXPORTS +#define PROTOBUF_EXPORT __declspec(dllexport) +#else +#define PROTOBUF_EXPORT __declspec(dllimport) +#endif +#ifdef LIBPROTOC_EXPORTS +#define PROTOC_EXPORT __declspec(dllexport) +#else +#define PROTOC_EXPORT __declspec(dllimport) +#endif +#else +#define PROTOBUF_EXPORT +#define PROTOC_EXPORT +#endif + +// Windows declares several inconvenient macro names. We #undef them and then +// restore them in port_undef.inc. +#ifdef _MSC_VER +#pragma push_macro("GetMessage") +#undef GetMessage +#endif + +#if defined(__clang__) +#pragma clang diagnostic push +// TODO(gerbens) ideally we cleanup the code. But a cursory try shows many +// violations. So let's ignore for now. +#pragma clang diagnostic ignored "-Wshorten-64-to-32" +#endif diff --git a/third_party/protobuf/src/google/protobuf/stubs/singleton.h b/third_party/protobuf/src/google/protobuf/port_undef.inc similarity index 55% rename from third_party/protobuf/src/google/protobuf/stubs/singleton.h rename to third_party/protobuf/src/google/protobuf/port_undef.inc index 2e6ccbdb..3395e263 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/singleton.h +++ b/third_party/protobuf/src/google/protobuf/port_undef.inc @@ -1,5 +1,5 @@ // Protocol Buffers - Google's data interchange format -// Copyright 2014 Google Inc. All rights reserved. +// Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without @@ -27,41 +27,49 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#ifndef GOOGLE_PROTOBUF_STUBS_SINGLETON_H__ -#define GOOGLE_PROTOBUF_STUBS_SINGLETON_H__ -#include -#include +// #undefs all macros defined in port_def.inc. See comments in port_def.inc +// for more info. -namespace google { -namespace protobuf { -namespace internal { -template -class Singleton { - public: - static T* get() { - GoogleOnceInit(&once_, &Singleton::Init); - return instance_; - } - static void ShutDown() { - delete instance_; - instance_ = NULL; - } - private: - static void Init() { - instance_ = new T(); - } - static ProtobufOnceType once_; - static T* instance_; -}; +#ifndef PROTOBUF_NAMESPACE +#error "port_undef.inc must be included after port_def.inc" +#endif +#undef PROTOBUF_NAMESPACE +#undef PROTOBUF_NAMESPACE_ID +#undef PROTOBUF_ALWAYS_INLINE +#undef PROTOBUF_COLD +#undef PROTOBUF_NOINLINE +#undef PROTOBUF_SECTION_VARIABLE +#undef PROTOBUF_DEPRECATED +#undef PROTOBUF_DEPRECATED_MSG +#undef PROTOBUF_FUNC_ALIGN +#undef PROTOBUF_RETURNS_NONNULL +#undef PROTOBUF_ATTRIBUTE_REINITIALIZES +#undef PROTOBUF_RTTI +#undef PROTOBUF_VERSION +#undef PROTOBUF_VERSION_SUFFIX +#undef PROTOBUF_FIELD_OFFSET +#undef PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC +#undef PROTOBUF_MIN_PROTOC_VERSION +#undef PROTOBUF_PREDICT_TRUE +#undef PROTOBUF_PREDICT_FALSE +#undef PROTOBUF_LONGLONG +#undef PROTOBUF_ULONGLONG +#undef PROTOBUF_LL_FORMAT +#undef PROTOBUF_GUARDED_BY +#undef PROTOBUF_FALLTHROUGH_INTENDED +#undef PROTOBUF_EXPORT +#undef PROTOC_EXPORT +#undef PROTOBUF_MUST_USE_RESULT +#undef PROTOBUF_NAMESPACE_OPEN +#undef PROTOBUF_NAMESPACE_CLOSE +#undef PROTOBUF_UNUSED -template -ProtobufOnceType Singleton::once_; +// Restore macro that may have been #undef'd in port_def.inc. +#ifdef _MSC_VER +#pragma pop_macro("GetMessage") +#endif -template -T* Singleton::instance_ = NULL; -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_STUBS_SINGLETON_H__ +#if defined(__clang__) +#pragma clang diagnostic pop +#endif diff --git a/third_party/protobuf/src/google/protobuf/preserve_unknown_enum_test.cc b/third_party/protobuf/src/google/protobuf/preserve_unknown_enum_test.cc index e292199e..1ac4e13f 100644 --- a/third_party/protobuf/src/google/protobuf/preserve_unknown_enum_test.cc +++ b/third_party/protobuf/src/google/protobuf/preserve_unknown_enum_test.cc @@ -31,8 +31,8 @@ #include #include #include -#include #include +#include #include namespace google { @@ -41,22 +41,18 @@ namespace { void FillMessage( proto3_preserve_unknown_enum_unittest::MyMessagePlusExtra* message) { - message->set_e( - proto3_preserve_unknown_enum_unittest::E_EXTRA); - message->add_repeated_e( - proto3_preserve_unknown_enum_unittest::E_EXTRA); + message->set_e(proto3_preserve_unknown_enum_unittest::E_EXTRA); + message->add_repeated_e(proto3_preserve_unknown_enum_unittest::E_EXTRA); message->add_repeated_packed_e( proto3_preserve_unknown_enum_unittest::E_EXTRA); message->add_repeated_packed_unexpected_e( proto3_preserve_unknown_enum_unittest::E_EXTRA); - message->set_oneof_e_1( - proto3_preserve_unknown_enum_unittest::E_EXTRA); + message->set_oneof_e_1(proto3_preserve_unknown_enum_unittest::E_EXTRA); } void CheckMessage( const proto3_preserve_unknown_enum_unittest::MyMessagePlusExtra& message) { - EXPECT_EQ(proto3_preserve_unknown_enum_unittest::E_EXTRA, - message.e()); + EXPECT_EQ(proto3_preserve_unknown_enum_unittest::E_EXTRA, message.e()); EXPECT_EQ(1, message.repeated_e_size()); EXPECT_EQ(proto3_preserve_unknown_enum_unittest::E_EXTRA, message.repeated_e(0)); @@ -72,23 +68,18 @@ void CheckMessage( void CheckMessage( const proto3_preserve_unknown_enum_unittest::MyMessage& message) { - EXPECT_EQ(static_cast( - proto3_preserve_unknown_enum_unittest::E_EXTRA), + EXPECT_EQ(static_cast(proto3_preserve_unknown_enum_unittest::E_EXTRA), static_cast(message.e())); EXPECT_EQ(1, message.repeated_e_size()); - EXPECT_EQ(static_cast( - proto3_preserve_unknown_enum_unittest::E_EXTRA), + EXPECT_EQ(static_cast(proto3_preserve_unknown_enum_unittest::E_EXTRA), static_cast(message.repeated_e(0))); EXPECT_EQ(1, message.repeated_packed_e_size()); - EXPECT_EQ(static_cast( - proto3_preserve_unknown_enum_unittest::E_EXTRA), + EXPECT_EQ(static_cast(proto3_preserve_unknown_enum_unittest::E_EXTRA), static_cast(message.repeated_packed_e(0))); EXPECT_EQ(1, message.repeated_packed_unexpected_e_size()); - EXPECT_EQ(static_cast( - proto3_preserve_unknown_enum_unittest::E_EXTRA), + EXPECT_EQ(static_cast(proto3_preserve_unknown_enum_unittest::E_EXTRA), static_cast(message.repeated_packed_unexpected_e(0))); - EXPECT_EQ(static_cast( - proto3_preserve_unknown_enum_unittest::E_EXTRA), + EXPECT_EQ(static_cast(proto3_preserve_unknown_enum_unittest::E_EXTRA), static_cast(message.oneof_e_1())); } @@ -99,7 +90,7 @@ void CheckMessage( TEST(PreserveUnknownEnumTest, PreserveParseAndSerialize) { proto3_preserve_unknown_enum_unittest::MyMessagePlusExtra orig_message; FillMessage(&orig_message); - string serialized; + std::string serialized; orig_message.SerializeToString(&serialized); proto3_preserve_unknown_enum_unittest::MyMessage message; @@ -117,11 +108,14 @@ TEST(PreserveUnknownEnumTest, PreserveParseAndSerialize) { TEST(PreserveUnknownEnumTest, PreserveParseAndSerializeDynamicMessage) { proto3_preserve_unknown_enum_unittest::MyMessagePlusExtra orig_message; FillMessage(&orig_message); - string serialized = orig_message.SerializeAsString(); + std::string serialized = orig_message.SerializeAsString(); - google::protobuf::DynamicMessageFactory factory; - std::unique_ptr message(factory.GetPrototype( - proto3_preserve_unknown_enum_unittest::MyMessage::descriptor())->New()); + DynamicMessageFactory factory; + std::unique_ptr message( + factory + .GetPrototype( + proto3_preserve_unknown_enum_unittest::MyMessage::descriptor()) + ->New()); EXPECT_EQ(true, message->ParseFromString(serialized)); message->DiscardUnknownFields(); @@ -135,7 +129,7 @@ TEST(PreserveUnknownEnumTest, Proto2HidesUnknownValues) { proto3_preserve_unknown_enum_unittest::MyMessagePlusExtra orig_message; FillMessage(&orig_message); - string serialized; + std::string serialized; orig_message.SerializeToString(&serialized); proto2_preserve_unknown_enum_unittest::MyMessage message; @@ -157,12 +151,15 @@ TEST(PreserveUnknownEnumTest, DynamicProto2HidesUnknownValues) { proto3_preserve_unknown_enum_unittest::MyMessagePlusExtra orig_message; FillMessage(&orig_message); - string serialized; + std::string serialized; orig_message.SerializeToString(&serialized); - google::protobuf::DynamicMessageFactory factory; - std::unique_ptr message(factory.GetPrototype( - proto2_preserve_unknown_enum_unittest::MyMessage::descriptor())->New()); + DynamicMessageFactory factory; + std::unique_ptr message( + factory + .GetPrototype( + proto2_preserve_unknown_enum_unittest::MyMessage::descriptor()) + ->New()); EXPECT_EQ(true, message->ParseFromString(serialized)); // The intermediate message has everything in its "unknown fields". proto2_preserve_unknown_enum_unittest::MyMessage message2; @@ -181,30 +178,28 @@ TEST(PreserveUnknownEnumTest, DynamicProto2HidesUnknownValues) { TEST(PreserveUnknownEnumTest, DynamicEnumValueDescriptors) { proto3_preserve_unknown_enum_unittest::MyMessagePlusExtra orig_message; FillMessage(&orig_message); - string serialized; + std::string serialized; orig_message.SerializeToString(&serialized); proto3_preserve_unknown_enum_unittest::MyMessage message; EXPECT_EQ(true, message.ParseFromString(serialized)); CheckMessage(message); - const google::protobuf::Reflection* r = message.GetReflection(); - const google::protobuf::Descriptor* d = message.GetDescriptor(); - const google::protobuf::FieldDescriptor* field = d->FindFieldByName("e"); + const Reflection* r = message.GetReflection(); + const Descriptor* d = message.GetDescriptor(); + const FieldDescriptor* field = d->FindFieldByName("e"); // This should dynamically create an EnumValueDescriptor. - const google::protobuf::EnumValueDescriptor* enum_value = r->GetEnum(message, field); + const EnumValueDescriptor* enum_value = r->GetEnum(message, field); EXPECT_EQ(enum_value->number(), static_cast(proto3_preserve_unknown_enum_unittest::E_EXTRA)); // Fetching value for a second time should return the same pointer. - const google::protobuf::EnumValueDescriptor* enum_value_second = - r->GetEnum(message, field); + const EnumValueDescriptor* enum_value_second = r->GetEnum(message, field); EXPECT_EQ(enum_value, enum_value_second); // Check the repeated case too. - const google::protobuf::FieldDescriptor* repeated_field = - d->FindFieldByName("repeated_e"); + const FieldDescriptor* repeated_field = d->FindFieldByName("repeated_e"); enum_value = r->GetRepeatedEnum(message, repeated_field, 0); EXPECT_EQ(enum_value->number(), static_cast(proto3_preserve_unknown_enum_unittest::E_EXTRA)); @@ -213,7 +208,7 @@ TEST(PreserveUnknownEnumTest, DynamicEnumValueDescriptors) { // We should be able to use the returned value descriptor to set a value on // another message. - google::protobuf::Message* m = message.New(); + Message* m = message.New(); r->SetEnum(m, field, enum_value); EXPECT_EQ(enum_value, r->GetEnum(*m, field)); delete m; @@ -222,12 +217,11 @@ TEST(PreserveUnknownEnumTest, DynamicEnumValueDescriptors) { // Test that the new integer-based enum reflection API works. TEST(PreserveUnknownEnumTest, IntegerEnumReflectionAPI) { proto3_preserve_unknown_enum_unittest::MyMessage message; - const google::protobuf::Reflection* r = message.GetReflection(); - const google::protobuf::Descriptor* d = message.GetDescriptor(); + const Reflection* r = message.GetReflection(); + const Descriptor* d = message.GetDescriptor(); - const google::protobuf::FieldDescriptor* singular_field = d->FindFieldByName("e"); - const google::protobuf::FieldDescriptor* repeated_field = - d->FindFieldByName("repeated_e"); + const FieldDescriptor* singular_field = d->FindFieldByName("e"); + const FieldDescriptor* repeated_field = d->FindFieldByName("repeated_e"); r->SetEnumValue(&message, singular_field, 42); EXPECT_EQ(42, r->GetEnumValue(message, singular_field)); @@ -236,51 +230,58 @@ TEST(PreserveUnknownEnumTest, IntegerEnumReflectionAPI) { EXPECT_EQ(42, r->GetRepeatedEnumValue(message, repeated_field, 0)); r->SetRepeatedEnumValue(&message, repeated_field, 1, 84); EXPECT_EQ(84, r->GetRepeatedEnumValue(message, repeated_field, 1)); - const google::protobuf::EnumValueDescriptor* enum_value = r->GetEnum(message, - singular_field); + const EnumValueDescriptor* enum_value = r->GetEnum(message, singular_field); EXPECT_EQ(42, enum_value->number()); } // Test that the EnumValue API works properly for proto2 messages as well. TEST(PreserveUnknownEnumTest, Proto2CatchesUnknownValues) { protobuf_unittest::TestAllTypes message; // proto2 message - const google::protobuf::Reflection* r = message.GetReflection(); - const google::protobuf::Descriptor* d = message.GetDescriptor(); - const google::protobuf::FieldDescriptor* repeated_field = + const Reflection* r = message.GetReflection(); + const Descriptor* d = message.GetDescriptor(); + const FieldDescriptor* repeated_field = d->FindFieldByName("repeated_nested_enum"); // Add one element to the repeated field so that we can test // SetRepeatedEnumValue. - const google::protobuf::EnumValueDescriptor* enum_value = + const EnumValueDescriptor* enum_value = repeated_field->enum_type()->FindValueByName("BAR"); EXPECT_TRUE(enum_value != NULL); r->AddEnum(&message, repeated_field, enum_value); -#ifdef PROTOBUF_HAS_DEATH_TEST - const google::protobuf::FieldDescriptor* singular_field = + const FieldDescriptor* singular_field = d->FindFieldByName("optional_nested_enum"); - // Enum-field integer-based setters GOOGLE_DCHECK-fail on invalid values, in order to - // remain consistent with proto2 generated code. - EXPECT_DEBUG_DEATH({ - r->SetEnumValue(&message, singular_field, 4242); - r->GetEnum(message, singular_field)->number(); - }, "SetEnumValue accepts only valid integer values"); - EXPECT_DEBUG_DEATH({ - r->SetRepeatedEnumValue(&message, repeated_field, 0, 4242); - r->GetRepeatedEnum(message, repeated_field, 0); - }, "SetRepeatedEnumValue accepts only valid integer values"); - EXPECT_DEBUG_DEATH({ - r->AddEnumValue(&message, repeated_field, 4242); - r->GetRepeatedEnum(message, repeated_field, 1); - }, "AddEnumValue accepts only valid integer values"); -#endif // PROTOBUF_HAS_DEATH_TEST + // Enum-field integer-based setters treat as unknown integer values as + // unknown fields. + r->SetEnumValue(&message, singular_field, 4242); + EXPECT_EQ(r->GetEnum(message, singular_field)->number(), + protobuf_unittest::TestAllTypes::FOO); + r->SetRepeatedEnumValue(&message, repeated_field, 0, 4242); + // repeated_nested_enum was set to bar above, this should not have changed. + EXPECT_EQ(r->GetRepeatedEnum(message, repeated_field, 0)->number(), + protobuf_unittest::TestAllTypes::BAR); + r->AddEnumValue(&message, repeated_field, 4242); + // No element should be added + EXPECT_EQ(message.repeated_nested_enum_size(), 1); + + // We require the enums to end up in unknown field set + ASSERT_EQ(message.unknown_fields().field_count(), 3); + EXPECT_EQ(message.unknown_fields().field(0).number(), + singular_field->number()); + EXPECT_EQ(message.unknown_fields().field(0).varint(), 4242); + EXPECT_EQ(message.unknown_fields().field(1).number(), + repeated_field->number()); + EXPECT_EQ(message.unknown_fields().field(1).varint(), 4242); + EXPECT_EQ(message.unknown_fields().field(2).number(), + repeated_field->number()); + EXPECT_EQ(message.unknown_fields().field(2).varint(), 4242); } TEST(PreserveUnknownEnumTest, SupportsUnknownEnumValuesAPI) { protobuf_unittest::TestAllTypes proto2_message; proto3_preserve_unknown_enum_unittest::MyMessage new_message; - const google::protobuf::Reflection* proto2_reflection = proto2_message.GetReflection(); - const google::protobuf::Reflection* new_reflection = new_message.GetReflection(); + const Reflection* proto2_reflection = proto2_message.GetReflection(); + const Reflection* new_reflection = new_message.GetReflection(); EXPECT_FALSE(proto2_reflection->SupportsUnknownEnumValues()); EXPECT_TRUE(new_reflection->SupportsUnknownEnumValues()); diff --git a/third_party/protobuf/src/google/protobuf/proto3_arena_lite_unittest.cc b/third_party/protobuf/src/google/protobuf/proto3_arena_lite_unittest.cc index 2ac775d7..e2693708 100644 --- a/third_party/protobuf/src/google/protobuf/proto3_arena_lite_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/proto3_arena_lite_unittest.cc @@ -28,8 +28,8 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include #include +#include #include #include @@ -37,9 +37,9 @@ #include #include -namespace google { using proto3_arena_unittest::TestAllTypes; +namespace google { namespace protobuf { namespace { // We selectively set/check a few representative fields rather than all fields @@ -52,8 +52,7 @@ void SetAllFields(TestAllTypes* m) { m->mutable_optional_foreign_message()->set_c(43); m->set_optional_nested_enum( proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ); - m->set_optional_foreign_enum( - proto3_arena_unittest::FOREIGN_BAZ); + m->set_optional_foreign_enum(proto3_arena_unittest::FOREIGN_BAZ); m->mutable_optional_lazy_message()->set_bb(45); m->add_repeated_int32(100); m->add_repeated_string("asdf"); @@ -62,8 +61,7 @@ void SetAllFields(TestAllTypes* m) { m->add_repeated_foreign_message()->set_c(47); m->add_repeated_nested_enum( proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ); - m->add_repeated_foreign_enum( - proto3_arena_unittest::FOREIGN_BAZ); + m->add_repeated_foreign_enum(proto3_arena_unittest::FOREIGN_BAZ); m->add_repeated_lazy_message()->set_bb(49); m->set_oneof_uint32(1); @@ -81,8 +79,7 @@ void ExpectAllFieldsSet(const TestAllTypes& m) { EXPECT_EQ(43, m.optional_foreign_message().c()); EXPECT_EQ(proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ, m.optional_nested_enum()); - EXPECT_EQ(proto3_arena_unittest::FOREIGN_BAZ, - m.optional_foreign_enum()); + EXPECT_EQ(proto3_arena_unittest::FOREIGN_BAZ, m.optional_foreign_enum()); EXPECT_EQ(true, m.has_optional_lazy_message()); EXPECT_EQ(45, m.optional_lazy_message().bb()); @@ -100,8 +97,7 @@ void ExpectAllFieldsSet(const TestAllTypes& m) { EXPECT_EQ(proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ, m.repeated_nested_enum(0)); EXPECT_EQ(1, m.repeated_foreign_enum_size()); - EXPECT_EQ(proto3_arena_unittest::FOREIGN_BAZ, - m.repeated_foreign_enum(0)); + EXPECT_EQ(proto3_arena_unittest::FOREIGN_BAZ, m.repeated_foreign_enum(0)); EXPECT_EQ(1, m.repeated_lazy_message_size()); EXPECT_EQ(49, m.repeated_lazy_message(0).bb()); @@ -138,7 +134,7 @@ TEST(Proto3ArenaLiteTest, Swap) { TEST(Proto3ArenaLiteTest, SetAllocatedMessage) { Arena arena; - TestAllTypes *arena_message = Arena::CreateMessage(&arena); + TestAllTypes* arena_message = Arena::CreateMessage(&arena); TestAllTypes::NestedMessage* nested = new TestAllTypes::NestedMessage; nested->set_bb(118); arena_message->set_allocated_optional_nested_message(nested); diff --git a/third_party/protobuf/src/google/protobuf/proto3_arena_unittest.cc b/third_party/protobuf/src/google/protobuf/proto3_arena_unittest.cc index dac73781..d4b0135a 100644 --- a/third_party/protobuf/src/google/protobuf/proto3_arena_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/proto3_arena_unittest.cc @@ -28,8 +28,8 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include #include +#include #include #include @@ -39,9 +39,9 @@ #include #include -namespace google { using proto3_arena_unittest::TestAllTypes; +namespace google { namespace protobuf { namespace { // We selectively set/check a few representative fields rather than all fields @@ -54,8 +54,7 @@ void SetAllFields(TestAllTypes* m) { m->mutable_optional_foreign_message()->set_c(43); m->set_optional_nested_enum( proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ); - m->set_optional_foreign_enum( - proto3_arena_unittest::FOREIGN_BAZ); + m->set_optional_foreign_enum(proto3_arena_unittest::FOREIGN_BAZ); m->mutable_optional_lazy_message()->set_bb(45); m->add_repeated_int32(100); m->add_repeated_string("asdf"); @@ -64,8 +63,7 @@ void SetAllFields(TestAllTypes* m) { m->add_repeated_foreign_message()->set_c(47); m->add_repeated_nested_enum( proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ); - m->add_repeated_foreign_enum( - proto3_arena_unittest::FOREIGN_BAZ); + m->add_repeated_foreign_enum(proto3_arena_unittest::FOREIGN_BAZ); m->add_repeated_lazy_message()->set_bb(49); m->set_oneof_uint32(1); @@ -83,8 +81,7 @@ void ExpectAllFieldsSet(const TestAllTypes& m) { EXPECT_EQ(43, m.optional_foreign_message().c()); EXPECT_EQ(proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ, m.optional_nested_enum()); - EXPECT_EQ(proto3_arena_unittest::FOREIGN_BAZ, - m.optional_foreign_enum()); + EXPECT_EQ(proto3_arena_unittest::FOREIGN_BAZ, m.optional_foreign_enum()); EXPECT_EQ(true, m.has_optional_lazy_message()); EXPECT_EQ(45, m.optional_lazy_message().bb()); @@ -102,8 +99,7 @@ void ExpectAllFieldsSet(const TestAllTypes& m) { EXPECT_EQ(proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ, m.repeated_nested_enum(0)); EXPECT_EQ(1, m.repeated_foreign_enum_size()); - EXPECT_EQ(proto3_arena_unittest::FOREIGN_BAZ, - m.repeated_foreign_enum(0)); + EXPECT_EQ(proto3_arena_unittest::FOREIGN_BAZ, m.repeated_foreign_enum(0)); EXPECT_EQ(1, m.repeated_lazy_message_size()); EXPECT_EQ(49, m.repeated_lazy_message(0).bb()); @@ -126,30 +122,7 @@ TEST(Proto3ArenaTest, Parsing) { ExpectAllFieldsSet(*arena_message); } -TEST(Proto3ArenaTest, UnknownFieldsDefaultDrop) { - ::google::protobuf::internal::SetProto3PreserveUnknownsDefault(false); - TestAllTypes original; - SetAllFields(&original); - - Arena arena; - TestAllTypes* arena_message = Arena::CreateMessage(&arena); - arena_message->ParseFromString(original.SerializeAsString()); - ExpectAllFieldsSet(*arena_message); - - // In proto3 we can still get a pointer to the UnknownFieldSet through - // reflection API. - UnknownFieldSet* unknown_fields = - arena_message->GetReflection()->MutableUnknownFields(arena_message); - // We can modify this UnknownFieldSet. - unknown_fields->AddVarint(1, 2); - // But the change will never will serialized back. - ASSERT_EQ(original.ByteSize(), arena_message->ByteSize()); - ASSERT_TRUE( - arena_message->GetReflection()->GetUnknownFields(*arena_message).empty()); -} - -TEST(Proto3ArenaTest, UnknownFieldsDefaultPreserve) { - ::google::protobuf::internal::SetProto3PreserveUnknownsDefault(true); +TEST(Proto3ArenaTest, UnknownFields) { TestAllTypes original; SetAllFields(&original); @@ -184,7 +157,7 @@ TEST(Proto3ArenaTest, Swap) { TEST(Proto3ArenaTest, SetAllocatedMessage) { Arena arena; - TestAllTypes *arena_message = Arena::CreateMessage(&arena); + TestAllTypes* arena_message = Arena::CreateMessage(&arena); TestAllTypes::NestedMessage* nested = new TestAllTypes::NestedMessage; nested->set_bb(118); arena_message->set_allocated_optional_nested_message(nested); @@ -201,7 +174,7 @@ TEST(Proto3ArenaTest, ReleaseMessage) { } TEST(Proto3ArenaTest, MessageFieldClear) { - // GitHub issue #310: https://github.com/google/protobuf/issues/310 + // GitHub issue #310: https://github.com/protocolbuffers/protobuf/issues/310 Arena arena; TestAllTypes* arena_message = Arena::CreateMessage(&arena); arena_message->mutable_optional_nested_message()->set_bb(118); @@ -215,8 +188,8 @@ TEST(Proto3ArenaTest, MessageFieldClearViaReflection) { TestAllTypes* message = Arena::CreateMessage(&arena); const Reflection* r = message->GetReflection(); const Descriptor* d = message->GetDescriptor(); - const FieldDescriptor* msg_field = d->FindFieldByName( - "optional_nested_message"); + const FieldDescriptor* msg_field = + d->FindFieldByName("optional_nested_message"); message->mutable_optional_nested_message()->set_bb(1); r->ClearField(message, msg_field); diff --git a/third_party/protobuf/src/google/protobuf/proto3_lite_unittest.cc b/third_party/protobuf/src/google/protobuf/proto3_lite_unittest.cc index 8b2c5742..abeeedb1 100644 --- a/third_party/protobuf/src/google/protobuf/proto3_lite_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/proto3_lite_unittest.cc @@ -28,113 +28,16 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include -#include -#include +#include -#include -#include -#include -#include +#define LITE_TEST_NAME Proto3LiteTest +#define UNITTEST ::proto3_unittest +// Must include after the above macros. +#include + +// Make extract script happy. namespace google { -using proto3_lite_unittest::TestAllTypes; - namespace protobuf { -namespace { -// We selectively set/check a few representative fields rather than all fields -// as this test is only expected to cover the basics of lite support. -void SetAllFields(TestAllTypes* m) { - m->set_optional_int32(100); - m->set_optional_string("asdf"); - m->set_optional_bytes("jkl;"); - m->mutable_optional_nested_message()->set_bb(42); - m->mutable_optional_foreign_message()->set_c(43); - m->set_optional_nested_enum( - proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ); - m->set_optional_foreign_enum( - proto3_lite_unittest::FOREIGN_BAZ); - m->mutable_optional_lazy_message()->set_bb(45); - m->add_repeated_int32(100); - m->add_repeated_string("asdf"); - m->add_repeated_bytes("jkl;"); - m->add_repeated_nested_message()->set_bb(46); - m->add_repeated_foreign_message()->set_c(47); - m->add_repeated_nested_enum( - proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ); - m->add_repeated_foreign_enum( - proto3_lite_unittest::FOREIGN_BAZ); - m->add_repeated_lazy_message()->set_bb(49); - - m->set_oneof_uint32(1); - m->mutable_oneof_nested_message()->set_bb(50); - m->set_oneof_string("test"); // only this one remains set -} - -void ExpectAllFieldsSet(const TestAllTypes& m) { - EXPECT_EQ(100, m.optional_int32()); - EXPECT_EQ("asdf", m.optional_string()); - EXPECT_EQ("jkl;", m.optional_bytes()); - EXPECT_EQ(true, m.has_optional_nested_message()); - EXPECT_EQ(42, m.optional_nested_message().bb()); - EXPECT_EQ(true, m.has_optional_foreign_message()); - EXPECT_EQ(43, m.optional_foreign_message().c()); - EXPECT_EQ(proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ, - m.optional_nested_enum()); - EXPECT_EQ(proto3_lite_unittest::FOREIGN_BAZ, - m.optional_foreign_enum()); - EXPECT_EQ(true, m.has_optional_lazy_message()); - EXPECT_EQ(45, m.optional_lazy_message().bb()); - - EXPECT_EQ(1, m.repeated_int32_size()); - EXPECT_EQ(100, m.repeated_int32(0)); - EXPECT_EQ(1, m.repeated_string_size()); - EXPECT_EQ("asdf", m.repeated_string(0)); - EXPECT_EQ(1, m.repeated_bytes_size()); - EXPECT_EQ("jkl;", m.repeated_bytes(0)); - EXPECT_EQ(1, m.repeated_nested_message_size()); - EXPECT_EQ(46, m.repeated_nested_message(0).bb()); - EXPECT_EQ(1, m.repeated_foreign_message_size()); - EXPECT_EQ(47, m.repeated_foreign_message(0).c()); - EXPECT_EQ(1, m.repeated_nested_enum_size()); - EXPECT_EQ(proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ, - m.repeated_nested_enum(0)); - EXPECT_EQ(1, m.repeated_foreign_enum_size()); - EXPECT_EQ(proto3_lite_unittest::FOREIGN_BAZ, - m.repeated_foreign_enum(0)); - EXPECT_EQ(1, m.repeated_lazy_message_size()); - EXPECT_EQ(49, m.repeated_lazy_message(0).bb()); - - EXPECT_EQ(proto3_lite_unittest::TestAllTypes::kOneofString, - m.oneof_field_case()); - EXPECT_EQ("test", m.oneof_string()); -} - -// In this file we only test some basic functionalities of in proto3 and expect -// the rest is fully tested in proto2 unittests because proto3 shares most code -// with proto2. - -TEST(Proto3LiteTest, Parsing) { - TestAllTypes original; - SetAllFields(&original); - - TestAllTypes msg; - msg.ParseFromString(original.SerializeAsString()); - ExpectAllFieldsSet(msg); -} - -TEST(Proto3LiteTest, Swap) { - // Test Swap(). - TestAllTypes msg1; - TestAllTypes msg2; - msg1.set_optional_string("123"); - msg2.set_optional_string("3456"); - msg1.Swap(&msg2); - EXPECT_EQ("3456", msg1.optional_string()); - EXPECT_EQ("123", msg2.optional_string()); - EXPECT_EQ(msg1.ByteSize(), msg2.ByteSize() + 1); -} - -} // namespace } // namespace protobuf } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/proto3_lite_unittest.inc b/third_party/protobuf/src/google/protobuf/proto3_lite_unittest.inc new file mode 100644 index 00000000..636691b4 --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/proto3_lite_unittest.inc @@ -0,0 +1,139 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include + +#include +#include +#include + +using UNITTEST::TestAllTypes; + +namespace google { +namespace protobuf { +namespace { +// We selectively set/check a few representative fields rather than all fields +// as this test is only expected to cover the basics of lite support. +void SetAllFields(TestAllTypes* m) { + m->set_optional_int32(100); + m->set_optional_string("asdf"); + m->set_optional_bytes("jkl;"); + m->mutable_optional_nested_message()->set_bb(42); + m->mutable_optional_foreign_message()->set_c(43); + m->set_optional_nested_enum( + UNITTEST::TestAllTypes_NestedEnum_BAZ); + m->set_optional_foreign_enum( + UNITTEST::FOREIGN_BAZ); + m->mutable_optional_lazy_message()->set_bb(45); + m->add_repeated_int32(100); + m->add_repeated_string("asdf"); + m->add_repeated_bytes("jkl;"); + m->add_repeated_nested_message()->set_bb(46); + m->add_repeated_foreign_message()->set_c(47); + m->add_repeated_nested_enum( + UNITTEST::TestAllTypes_NestedEnum_BAZ); + m->add_repeated_foreign_enum( + UNITTEST::FOREIGN_BAZ); + m->add_repeated_lazy_message()->set_bb(49); + + m->set_oneof_uint32(1); + m->mutable_oneof_nested_message()->set_bb(50); + m->set_oneof_string("test"); // only this one remains set +} + +void ExpectAllFieldsSet(const TestAllTypes& m) { + EXPECT_EQ(100, m.optional_int32()); + EXPECT_EQ("asdf", m.optional_string()); + EXPECT_EQ("jkl;", m.optional_bytes()); + EXPECT_EQ(true, m.has_optional_nested_message()); + EXPECT_EQ(42, m.optional_nested_message().bb()); + EXPECT_EQ(true, m.has_optional_foreign_message()); + EXPECT_EQ(43, m.optional_foreign_message().c()); + EXPECT_EQ(UNITTEST::TestAllTypes_NestedEnum_BAZ, + m.optional_nested_enum()); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, + m.optional_foreign_enum()); + EXPECT_EQ(true, m.has_optional_lazy_message()); + EXPECT_EQ(45, m.optional_lazy_message().bb()); + + EXPECT_EQ(1, m.repeated_int32_size()); + EXPECT_EQ(100, m.repeated_int32(0)); + EXPECT_EQ(1, m.repeated_string_size()); + EXPECT_EQ("asdf", m.repeated_string(0)); + EXPECT_EQ(1, m.repeated_bytes_size()); + EXPECT_EQ("jkl;", m.repeated_bytes(0)); + EXPECT_EQ(1, m.repeated_nested_message_size()); + EXPECT_EQ(46, m.repeated_nested_message(0).bb()); + EXPECT_EQ(1, m.repeated_foreign_message_size()); + EXPECT_EQ(47, m.repeated_foreign_message(0).c()); + EXPECT_EQ(1, m.repeated_nested_enum_size()); + EXPECT_EQ(UNITTEST::TestAllTypes_NestedEnum_BAZ, + m.repeated_nested_enum(0)); + EXPECT_EQ(1, m.repeated_foreign_enum_size()); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, + m.repeated_foreign_enum(0)); + EXPECT_EQ(1, m.repeated_lazy_message_size()); + EXPECT_EQ(49, m.repeated_lazy_message(0).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::kOneofString, + m.oneof_field_case()); + EXPECT_EQ("test", m.oneof_string()); +} + +// In this file we only test some basic functionalities of in proto3 and expect +// the rest is fully tested in proto2 unittests because proto3 shares most code +// with proto2. + +TEST(LITE_TEST_NAME, Parsing) { + TestAllTypes original; + SetAllFields(&original); + + TestAllTypes msg; + msg.ParseFromString(original.SerializeAsString()); + ExpectAllFieldsSet(msg); +} + +TEST(LITE_TEST_NAME, Swap) { + // Test Swap(). + TestAllTypes msg1; + TestAllTypes msg2; + msg1.set_optional_string("123"); + msg2.set_optional_string("3456"); + msg1.Swap(&msg2); + EXPECT_EQ("3456", msg1.optional_string()); + EXPECT_EQ("123", msg2.optional_string()); + EXPECT_EQ(msg1.ByteSize(), msg2.ByteSize() + 1); +} + +} // namespace +} // namespace protobuf +} // namespace google diff --git a/third_party/protobuf/src/google/protobuf/reflection.h b/third_party/protobuf/src/google/protobuf/reflection.h old mode 100755 new mode 100644 index 5d0fc42b..6b1e5f2e --- a/third_party/protobuf/src/google/protobuf/reflection.h +++ b/third_party/protobuf/src/google/protobuf/reflection.h @@ -38,42 +38,42 @@ #include #include +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + +#include + namespace google { namespace protobuf { namespace internal { -template +template struct RefTypeTraits; } // namespace internal -template +template RepeatedFieldRef Reflection::GetRepeatedFieldRef( const Message& message, const FieldDescriptor* field) const { return RepeatedFieldRef(message, field); } -template +template MutableRepeatedFieldRef Reflection::GetMutableRepeatedFieldRef( Message* message, const FieldDescriptor* field) const { return MutableRepeatedFieldRef(message, field); } // RepeatedFieldRef definition for non-message types. -template +template class RepeatedFieldRef< T, typename std::enable_if::value>::type> { typedef typename internal::RefTypeTraits::iterator IteratorType; typedef typename internal::RefTypeTraits::AccessorType AccessorType; public: - bool empty() const { - return accessor_->IsEmpty(data_); - } - int size() const { - return accessor_->Size(data_); - } - T Get(int index) const { - return accessor_->template Get(data_, index); - } + bool empty() const { return accessor_->IsEmpty(data_); } + int size() const { return accessor_->Size(data_); } + T Get(int index) const { return accessor_->template Get(data_, index); } typedef IteratorType iterator; typedef IteratorType const_iterator; @@ -83,22 +83,16 @@ class RepeatedFieldRef< typedef int size_type; typedef ptrdiff_t difference_type; - iterator begin() const { - return iterator(data_, accessor_, true); - } - iterator end() const { - return iterator(data_, accessor_, false); - } + iterator begin() const { return iterator(data_, accessor_, true); } + iterator end() const { return iterator(data_, accessor_, false); } private: friend class Reflection; - RepeatedFieldRef( - const Message& message, - const FieldDescriptor* field) { + RepeatedFieldRef(const Message& message, const FieldDescriptor* field) { const Reflection* reflection = message.GetReflection(); - data_ = reflection->RepeatedFieldData( - const_cast(&message), field, - internal::RefTypeTraits::cpp_type, NULL); + data_ = reflection->RepeatedFieldData(const_cast(&message), field, + internal::RefTypeTraits::cpp_type, + NULL); accessor_ = reflection->RepeatedFieldAccessor(field); } @@ -107,50 +101,38 @@ class RepeatedFieldRef< }; // MutableRepeatedFieldRef definition for non-message types. -template +template class MutableRepeatedFieldRef< T, typename std::enable_if::value>::type> { typedef typename internal::RefTypeTraits::AccessorType AccessorType; public: - bool empty() const { - return accessor_->IsEmpty(data_); - } - int size() const { - return accessor_->Size(data_); - } - T Get(int index) const { - return accessor_->template Get(data_, index); - } + bool empty() const { return accessor_->IsEmpty(data_); } + int size() const { return accessor_->Size(data_); } + T Get(int index) const { return accessor_->template Get(data_, index); } void Set(int index, const T& value) const { accessor_->template Set(data_, index, value); } - void Add(const T& value) const { - accessor_->template Add(data_, value); - } - void RemoveLast() const { - accessor_->RemoveLast(data_); - } + void Add(const T& value) const { accessor_->template Add(data_, value); } + void RemoveLast() const { accessor_->RemoveLast(data_); } void SwapElements(int index1, int index2) const { accessor_->SwapElements(data_, index1, index2); } - void Clear() const { - accessor_->Clear(data_); - } + void Clear() const { accessor_->Clear(data_); } void Swap(const MutableRepeatedFieldRef& other) const { accessor_->Swap(data_, other.accessor_, other.data_); } - template + template void MergeFrom(const Container& container) const { typedef typename Container::const_iterator Iterator; for (Iterator it = container.begin(); it != container.end(); ++it) { Add(*it); } } - template + template void CopyFrom(const Container& container) const { Clear(); MergeFrom(container); @@ -158,9 +140,7 @@ class MutableRepeatedFieldRef< private: friend class Reflection; - MutableRepeatedFieldRef( - Message* message, - const FieldDescriptor* field) { + MutableRepeatedFieldRef(Message* message, const FieldDescriptor* field) { const Reflection* reflection = message->GetReflection(); data_ = reflection->RepeatedFieldData( message, field, internal::RefTypeTraits::cpp_type, NULL); @@ -172,19 +152,15 @@ class MutableRepeatedFieldRef< }; // RepeatedFieldRef definition for message types. -template +template class RepeatedFieldRef< T, typename std::enable_if::value>::type> { typedef typename internal::RefTypeTraits::iterator IteratorType; typedef typename internal::RefTypeTraits::AccessorType AccessorType; public: - bool empty() const { - return accessor_->IsEmpty(data_); - } - int size() const { - return accessor_->Size(data_); - } + bool empty() const { return accessor_->IsEmpty(data_); } + int size() const { return accessor_->Size(data_); } // This method returns a reference to the underlying message object if it // exists. If a message object doesn't exist (e.g., data stored in serialized // form), scratch_space will be filled with the data and a reference to it @@ -199,9 +175,7 @@ class RepeatedFieldRef< } // Create a new message of the same type as the messages stored in this // repeated field. Caller takes ownership of the returned object. - T* NewMessage() const { - return static_cast(default_instance_->New()); - } + T* NewMessage() const { return static_cast(default_instance_->New()); } typedef IteratorType iterator; typedef IteratorType const_iterator; @@ -221,9 +195,7 @@ class RepeatedFieldRef< private: friend class Reflection; - RepeatedFieldRef( - const Message& message, - const FieldDescriptor* field) { + RepeatedFieldRef(const Message& message, const FieldDescriptor* field) { const Reflection* reflection = message.GetReflection(); data_ = reflection->RepeatedFieldData( const_cast(&message), field, @@ -240,56 +212,44 @@ class RepeatedFieldRef< }; // MutableRepeatedFieldRef definition for message types. -template +template class MutableRepeatedFieldRef< T, typename std::enable_if::value>::type> { typedef typename internal::RefTypeTraits::AccessorType AccessorType; public: - bool empty() const { - return accessor_->IsEmpty(data_); - } - int size() const { - return accessor_->Size(data_); - } + bool empty() const { return accessor_->IsEmpty(data_); } + int size() const { return accessor_->Size(data_); } // See comments for RepeatedFieldRef::Get() const T& Get(int index, T* scratch_space) const { return *static_cast(accessor_->Get(data_, index, scratch_space)); } // Create a new message of the same type as the messages stored in this // repeated field. Caller takes ownership of the returned object. - T* NewMessage() const { - return static_cast(default_instance_->New()); - } + T* NewMessage() const { return static_cast(default_instance_->New()); } void Set(int index, const T& value) const { accessor_->Set(data_, index, &value); } - void Add(const T& value) const { - accessor_->Add(data_, &value); - } - void RemoveLast() const { - accessor_->RemoveLast(data_); - } + void Add(const T& value) const { accessor_->Add(data_, &value); } + void RemoveLast() const { accessor_->RemoveLast(data_); } void SwapElements(int index1, int index2) const { accessor_->SwapElements(data_, index1, index2); } - void Clear() const { - accessor_->Clear(data_); - } + void Clear() const { accessor_->Clear(data_); } void Swap(const MutableRepeatedFieldRef& other) const { accessor_->Swap(data_, other.accessor_, other.data_); } - template + template void MergeFrom(const Container& container) const { typedef typename Container::const_iterator Iterator; for (Iterator it = container.begin(); it != container.end(); ++it) { Add(*it); } } - template + template void CopyFrom(const Container& container) const { Clear(); MergeFrom(container); @@ -297,9 +257,7 @@ class MutableRepeatedFieldRef< private: friend class Reflection; - MutableRepeatedFieldRef( - Message* message, - const FieldDescriptor* field) { + MutableRepeatedFieldRef(Message* message, const FieldDescriptor* field) { const Reflection* reflection = message->GetReflection(); data_ = reflection->RepeatedFieldData( message, field, internal::RefTypeTraits::cpp_type, @@ -332,7 +290,7 @@ namespace internal { // CPPTYPE_FLOAT float float // CPPTYPE_BOOL bool bool // CPPTYPE_ENUM generated enum type int32 -// CPPTYPE_STRING string string +// CPPTYPE_STRING string std::string // CPPTYPE_MESSAGE generated message type google::protobuf::Message // or google::protobuf::Message // @@ -340,14 +298,13 @@ namespace internal { // // You can map from T to the actual type using RefTypeTraits: // typedef RefTypeTraits::AccessorValueType ActualType; -class LIBPROTOBUF_EXPORT RepeatedFieldAccessor { +class PROTOBUF_EXPORT RepeatedFieldAccessor { public: // Typedefs for clarity. typedef void Field; typedef void Value; typedef void Iterator; - virtual ~RepeatedFieldAccessor(); virtual bool IsEmpty(const Field* data) const = 0; virtual int Size(const Field* data) const = 0; // Depends on the underlying representation of the repeated field, this @@ -355,8 +312,8 @@ class LIBPROTOBUF_EXPORT RepeatedFieldAccessor { // exists, or fill the data into scratch_space and return scratch_space. // Callers of this method must ensure scratch_space is a valid pointer // to a mutable object of the correct type. - virtual const Value* Get( - const Field* data, int index, Value* scratch_space) const = 0; + virtual const Value* Get(const Field* data, int index, + Value* scratch_space) const = 0; virtual void Clear(Field* data) const = 0; virtual void Set(Field* data, int index, const Value* value) const = 0; @@ -389,16 +346,15 @@ class LIBPROTOBUF_EXPORT RepeatedFieldAccessor { // Templated methods that make using this interface easier for non-message // types. - template + template T Get(const Field* data, int index) const { typedef typename RefTypeTraits::AccessorValueType ActualType; ActualType scratch_space; - return static_cast( - *reinterpret_cast( - Get(data, index, static_cast(&scratch_space)))); + return static_cast(*reinterpret_cast( + Get(data, index, static_cast(&scratch_space)))); } - template + template void Set(Field* data, int index, const ValueType& value) const { typedef typename RefTypeTraits::AccessorValueType ActualType; // In this RepeatedFieldAccessor interface we pass/return data using @@ -412,7 +368,7 @@ class LIBPROTOBUF_EXPORT RepeatedFieldAccessor { Set(data, index, static_cast(&tmp)); } - template + template void Add(Field* data, const ValueType& value) const { typedef typename RefTypeTraits::AccessorValueType ActualType; // In this RepeatedFieldAccessor interface we pass/return data using @@ -425,10 +381,17 @@ class LIBPROTOBUF_EXPORT RepeatedFieldAccessor { ActualType tmp = static_cast(value); Add(data, static_cast(&tmp)); } + + protected: + // We want the destructor to be completely trivial as to allow it to be + // a function local static. Hence we make it non-virtual and protected, + // this class only live as part of a global singleton and should not be + // deleted. + ~RepeatedFieldAccessor() = default; }; // Implement (Mutable)RepeatedFieldRef::iterator -template +template class RepeatedFieldRefIterator : public std::iterator { typedef typename RefTypeTraits::AccessorValueType AccessorValueType; @@ -447,17 +410,14 @@ class RepeatedFieldRefIterator scratch_space_(begin ? new AccessorValueType : nullptr) {} // Constructor for message fields. RepeatedFieldRefIterator(const void* data, - const RepeatedFieldAccessor* accessor, - bool begin, + const RepeatedFieldAccessor* accessor, bool begin, AccessorValueType* scratch_space) - : data_(data), accessor_(accessor), - iterator_(begin ? accessor->BeginIterator(data) : - accessor->EndIterator(data)), - scratch_space_(scratch_space) { - } - ~RepeatedFieldRefIterator() { - accessor_->DeleteIterator(data_, iterator_); - } + : data_(data), + accessor_(accessor), + iterator_(begin ? accessor->BeginIterator(data) + : accessor->EndIterator(data)), + scratch_space_(scratch_space) {} + ~RepeatedFieldRefIterator() { accessor_->DeleteIterator(data_, iterator_); } RepeatedFieldRefIterator operator++(int) { RepeatedFieldRefIterator tmp(*this); iterator_ = accessor_->AdvanceIterator(data_, iterator_); @@ -469,14 +429,12 @@ class RepeatedFieldRefIterator } IteratorValueType operator*() const { return static_cast( - *static_cast( - accessor_->GetIteratorValue( - data_, iterator_, scratch_space_.get()))); + *static_cast(accessor_->GetIteratorValue( + data_, iterator_, scratch_space_.get()))); } IteratorPointerType operator->() const { return static_cast( - accessor_->GetIteratorValue( - data_, iterator_, scratch_space_.get())); + accessor_->GetIteratorValue(data_, iterator_, scratch_space_.get())); } bool operator!=(const RepeatedFieldRefIterator& other) const { assert(data_ == other.data_); @@ -488,9 +446,9 @@ class RepeatedFieldRefIterator } RepeatedFieldRefIterator(const RepeatedFieldRefIterator& other) - : data_(other.data_), accessor_(other.accessor_), - iterator_(accessor_->CopyIterator(data_, other.iterator_)) { - } + : data_(other.data_), + accessor_(other.accessor_), + iterator_(accessor_->CopyIterator(data_, other.iterator_)) {} RepeatedFieldRefIterator& operator=(const RepeatedFieldRefIterator& other) { if (this != &other) { accessor_->DeleteIterator(data_, iterator_); @@ -511,16 +469,17 @@ class RepeatedFieldRefIterator // TypeTraits that maps the type parameter T of RepeatedFieldRef or // MutableRepeatedFieldRef to corresponding iterator type, // RepeatedFieldAccessor type, etc. -template +template struct PrimitiveTraits { static const bool is_primitive = false; }; -#define DEFINE_PRIMITIVE(TYPE, type) \ - template<> struct PrimitiveTraits { \ - static const bool is_primitive = true; \ - static const FieldDescriptor::CppType cpp_type = \ - FieldDescriptor::CPPTYPE_ ## TYPE; \ - }; +#define DEFINE_PRIMITIVE(TYPE, type) \ + template <> \ + struct PrimitiveTraits { \ + static const bool is_primitive = true; \ + static const FieldDescriptor::CppType cpp_type = \ + FieldDescriptor::CPPTYPE_##TYPE; \ + }; DEFINE_PRIMITIVE(INT32, int32) DEFINE_PRIMITIVE(UINT32, uint32) DEFINE_PRIMITIVE(INT64, int64) @@ -530,7 +489,7 @@ DEFINE_PRIMITIVE(DOUBLE, double) DEFINE_PRIMITIVE(BOOL, bool) #undef DEFINE_PRIMITIVE -template +template struct RefTypeTraits< T, typename std::enable_if::is_primitive>::type> { typedef RepeatedFieldRefIterator iterator; @@ -538,14 +497,11 @@ struct RefTypeTraits< typedef T AccessorValueType; typedef T IteratorValueType; typedef T* IteratorPointerType; - static const FieldDescriptor::CppType cpp_type = - PrimitiveTraits::cpp_type; - static const Descriptor* GetMessageFieldDescriptor() { - return NULL; - } + static const FieldDescriptor::CppType cpp_type = PrimitiveTraits::cpp_type; + static const Descriptor* GetMessageFieldDescriptor() { return NULL; } }; -template +template struct RefTypeTraits< T, typename std::enable_if::value>::type> { typedef RepeatedFieldRefIterator iterator; @@ -556,40 +512,34 @@ struct RefTypeTraits< typedef int32* IteratorPointerType; static const FieldDescriptor::CppType cpp_type = FieldDescriptor::CPPTYPE_ENUM; - static const Descriptor* GetMessageFieldDescriptor() { - return NULL; - } + static const Descriptor* GetMessageFieldDescriptor() { return NULL; } }; -template +template struct RefTypeTraits< - T, typename std::enable_if::value>::type> { + T, typename std::enable_if::value>::type> { typedef RepeatedFieldRefIterator iterator; typedef RepeatedFieldAccessor AccessorType; - typedef string AccessorValueType; - typedef const string IteratorValueType; - typedef const string* IteratorPointerType; + typedef std::string AccessorValueType; + typedef const std::string IteratorValueType; + typedef const std::string* IteratorPointerType; static const FieldDescriptor::CppType cpp_type = FieldDescriptor::CPPTYPE_STRING; - static const Descriptor* GetMessageFieldDescriptor() { - return NULL; - } + static const Descriptor* GetMessageFieldDescriptor() { return NULL; } }; -template +template struct MessageDescriptorGetter { static const Descriptor* get() { return T::default_instance().GetDescriptor(); } }; -template<> +template <> struct MessageDescriptorGetter { - static const Descriptor* get() { - return NULL; - } + static const Descriptor* get() { return NULL; } }; -template +template struct RefTypeTraits< T, typename std::enable_if::value>::type> { typedef RepeatedFieldRefIterator iterator; @@ -607,4 +557,6 @@ struct RefTypeTraits< } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_REFLECTION_H__ diff --git a/third_party/protobuf/src/google/protobuf/reflection_internal.h b/third_party/protobuf/src/google/protobuf/reflection_internal.h index fcb42471..40c070fc 100644 --- a/third_party/protobuf/src/google/protobuf/reflection_internal.h +++ b/third_party/protobuf/src/google/protobuf/reflection_internal.h @@ -43,36 +43,34 @@ namespace internal { // corresponding random-access methods. class RandomAccessRepeatedFieldAccessor : public RepeatedFieldAccessor { public: - virtual ~RandomAccessRepeatedFieldAccessor() {} - - virtual Iterator* BeginIterator(const Field* data) const { + Iterator* BeginIterator(const Field* data) const override { return PositionToIterator(0); } - virtual Iterator* EndIterator(const Field* data) const { + Iterator* EndIterator(const Field* data) const override { return PositionToIterator(this->Size(data)); } - virtual Iterator* CopyIterator(const Field* data, - const Iterator* iterator) const { + Iterator* CopyIterator(const Field* data, + const Iterator* iterator) const override { return const_cast(iterator); } - virtual Iterator* AdvanceIterator(const Field* data, - Iterator* iterator) const { + Iterator* AdvanceIterator(const Field* data, + Iterator* iterator) const override { return PositionToIterator(IteratorToPosition(iterator) + 1); } - virtual bool EqualsIterator(const Field* data, - const Iterator* a, - const Iterator* b) const { + bool EqualsIterator(const Field* data, const Iterator* a, + const Iterator* b) const override { return a == b; } - virtual void DeleteIterator(const Field* data, Iterator* iterator) const { - } - virtual const Value* GetIteratorValue(const Field* data, - const Iterator* iterator, - Value* scratch_space) const { + void DeleteIterator(const Field* data, Iterator* iterator) const override {} + const Value* GetIteratorValue(const Field* data, const Iterator* iterator, + Value* scratch_space) const override { return Get(data, static_cast(IteratorToPosition(iterator)), scratch_space); } + protected: + ~RandomAccessRepeatedFieldAccessor() = default; + private: static intptr_t IteratorToPosition(const Iterator* iterator) { return reinterpret_cast(iterator); @@ -84,38 +82,38 @@ class RandomAccessRepeatedFieldAccessor : public RepeatedFieldAccessor { // Base class for RepeatedFieldAccessor implementations that manipulates // RepeatedField. -template +template class RepeatedFieldWrapper : public RandomAccessRepeatedFieldAccessor { public: RepeatedFieldWrapper() {} - virtual ~RepeatedFieldWrapper() {} - virtual bool IsEmpty(const Field* data) const { + bool IsEmpty(const Field* data) const override { return GetRepeatedField(data)->empty(); } - virtual int Size(const Field* data) const { + int Size(const Field* data) const override { return GetRepeatedField(data)->size(); } - virtual const Value* Get(const Field* data, int index, - Value* scratch_space) const { + const Value* Get(const Field* data, int index, + Value* scratch_space) const override { return ConvertFromT(GetRepeatedField(data)->Get(index), scratch_space); } - virtual void Clear(Field* data) const { + void Clear(Field* data) const override { MutableRepeatedField(data)->Clear(); } - virtual void Set(Field* data, int index, const Value* value) const { + void Set(Field* data, int index, const Value* value) const override { MutableRepeatedField(data)->Set(index, ConvertToT(value)); } - virtual void Add(Field* data, const Value* value) const { + void Add(Field* data, const Value* value) const override { MutableRepeatedField(data)->Add(ConvertToT(value)); } - virtual void RemoveLast(Field* data) const { + void RemoveLast(Field* data) const override { MutableRepeatedField(data)->RemoveLast(); } - virtual void SwapElements(Field* data, int index1, int index2) const { + void SwapElements(Field* data, int index1, int index2) const override { MutableRepeatedField(data)->SwapElements(index1, index2); } protected: + ~RepeatedFieldWrapper() = default; typedef RepeatedField RepeatedFieldType; static const RepeatedFieldType* GetRepeatedField(const Field* data) { return reinterpret_cast(data); @@ -129,9 +127,9 @@ class RepeatedFieldWrapper : public RandomAccessRepeatedFieldAccessor { virtual T ConvertToT(const Value* value) const = 0; // Convert an object stored in RepeatedPtrField to an object that will be - // returned by this accessor. If the two objects have the same type (true - // for string fields with ctype=STRING), a pointer to the source object can - // be returned directly. Otherwise, data should be copied from value to + // returned by this accessor. If the two objects have the same type (true for + // string fields with ctype=STRING), a pointer to the source object can be + // returned directly. Otherwise, data should be copied from value to // scratch_space and scratch_space should be returned. virtual const Value* ConvertFromT(const T& value, Value* scratch_space) const = 0; @@ -139,40 +137,39 @@ class RepeatedFieldWrapper : public RandomAccessRepeatedFieldAccessor { // Base class for RepeatedFieldAccessor implementations that manipulates // RepeatedPtrField. -template +template class RepeatedPtrFieldWrapper : public RandomAccessRepeatedFieldAccessor { public: - RepeatedPtrFieldWrapper() {} - virtual ~RepeatedPtrFieldWrapper() {} - virtual bool IsEmpty(const Field* data) const { + bool IsEmpty(const Field* data) const override { return GetRepeatedField(data)->empty(); } - virtual int Size(const Field* data) const { + int Size(const Field* data) const override { return GetRepeatedField(data)->size(); } - virtual const Value* Get(const Field* data, int index, - Value* scratch_space) const { + const Value* Get(const Field* data, int index, + Value* scratch_space) const override { return ConvertFromT(GetRepeatedField(data)->Get(index), scratch_space); } - virtual void Clear(Field* data) const { + void Clear(Field* data) const override { MutableRepeatedField(data)->Clear(); } - virtual void Set(Field* data, int index, const Value* value) const { + void Set(Field* data, int index, const Value* value) const override { ConvertToT(value, MutableRepeatedField(data)->Mutable(index)); } - virtual void Add(Field* data, const Value* value) const { + void Add(Field* data, const Value* value) const override { T* allocated = New(value); ConvertToT(value, allocated); MutableRepeatedField(data)->AddAllocated(allocated); } - virtual void RemoveLast(Field* data) const { + void RemoveLast(Field* data) const override { MutableRepeatedField(data)->RemoveLast(); } - virtual void SwapElements(Field* data, int index1, int index2) const { + void SwapElements(Field* data, int index1, int index2) const override { MutableRepeatedField(data)->SwapElements(index1, index2); } protected: + ~RepeatedPtrFieldWrapper() = default; typedef RepeatedPtrField RepeatedFieldType; static const RepeatedFieldType* GetRepeatedField(const Field* data) { return reinterpret_cast(data); @@ -192,9 +189,9 @@ class RepeatedPtrFieldWrapper : public RandomAccessRepeatedFieldAccessor { virtual void ConvertToT(const Value* value, T* result) const = 0; // Convert an object stored in RepeatedPtrField to an object that will be - // returned by this accessor. If the two objects have the same type (true - // for string fields with ctype=STRING), a pointer to the source object can - // be returned directly. Otherwise, data should be copied from value to + // returned by this accessor. If the two objects have the same type (true for + // string fields with ctype=STRING), a pointer to the source object can be + // returned directly. Otherwise, data should be copied from value to // scratch_space and scratch_space should be returned. virtual const Value* ConvertFromT(const T& value, Value* scratch_space) const = 0; @@ -202,41 +199,39 @@ class RepeatedPtrFieldWrapper : public RandomAccessRepeatedFieldAccessor { // An implementation of RandomAccessRepeatedFieldAccessor that manipulates // MapFieldBase. -class MapFieldAccessor : public RandomAccessRepeatedFieldAccessor { +class MapFieldAccessor final : public RandomAccessRepeatedFieldAccessor { public: MapFieldAccessor() {} virtual ~MapFieldAccessor() {} - virtual bool IsEmpty(const Field* data) const { + bool IsEmpty(const Field* data) const override { return GetRepeatedField(data)->empty(); } - virtual int Size(const Field* data) const { + int Size(const Field* data) const override { return GetRepeatedField(data)->size(); } - virtual const Value* Get(const Field* data, int index, - Value* scratch_space) const { + const Value* Get(const Field* data, int index, + Value* scratch_space) const override { return ConvertFromEntry(GetRepeatedField(data)->Get(index), scratch_space); } - virtual void Clear(Field* data) const { + void Clear(Field* data) const override { MutableRepeatedField(data)->Clear(); } - virtual void Set(Field* data, int index, const Value* value) const { + void Set(Field* data, int index, const Value* value) const override { ConvertToEntry(value, MutableRepeatedField(data)->Mutable(index)); } - virtual void Add(Field* data, const Value* value) const { + void Add(Field* data, const Value* value) const override { Message* allocated = New(value); ConvertToEntry(value, allocated); MutableRepeatedField(data)->AddAllocated(allocated); } - virtual void RemoveLast(Field* data) const { + void RemoveLast(Field* data) const override { MutableRepeatedField(data)->RemoveLast(); } - virtual void SwapElements(Field* data, int index1, int index2) const { + void SwapElements(Field* data, int index1, int index2) const override { MutableRepeatedField(data)->SwapElements(index1, index2); } - virtual void Swap( - Field* data, - const internal::RepeatedFieldAccessor* other_mutator, - Field* other_data) const { + void Swap(Field* data, const internal::RepeatedFieldAccessor* other_mutator, + Field* other_data) const override { GOOGLE_CHECK(this == other_mutator); MutableRepeatedField(data)->Swap(MutableRepeatedField(other_data)); } @@ -268,19 +263,16 @@ class MapFieldAccessor : public RandomAccessRepeatedFieldAccessor { }; // Default implementations of RepeatedFieldAccessor for primitive types. -template -class RepeatedFieldPrimitiveAccessor : public RepeatedFieldWrapper { +template +class RepeatedFieldPrimitiveAccessor final : public RepeatedFieldWrapper { typedef void Field; typedef void Value; using RepeatedFieldWrapper::MutableRepeatedField; public: RepeatedFieldPrimitiveAccessor() {} - virtual ~RepeatedFieldPrimitiveAccessor() {} - virtual void Swap( - Field* data, - const internal::RepeatedFieldAccessor* other_mutator, - Field* other_data) const { + void Swap(Field* data, const internal::RepeatedFieldAccessor* other_mutator, + Field* other_data) const override { // Currently RepeatedFieldPrimitiveAccessor is the only implementation of // RepeatedFieldAccessor for primitive types. As we are using singletons // for these accessors, here "other_mutator" must be "this". @@ -289,90 +281,83 @@ class RepeatedFieldPrimitiveAccessor : public RepeatedFieldWrapper { } protected: - virtual T ConvertToT(const Value* value) const { + T ConvertToT(const Value* value) const override { return *static_cast(value); } - virtual const Value* ConvertFromT(const T& value, - Value* scratch_space) const { + const Value* ConvertFromT(const T& value, + Value* scratch_space) const override { return static_cast(&value); } }; // Default implementation of RepeatedFieldAccessor for string fields with // ctype=STRING. -class RepeatedPtrFieldStringAccessor : public RepeatedPtrFieldWrapper { +class RepeatedPtrFieldStringAccessor final + : public RepeatedPtrFieldWrapper { typedef void Field; typedef void Value; using RepeatedFieldAccessor::Add; public: RepeatedPtrFieldStringAccessor() {} - virtual ~RepeatedPtrFieldStringAccessor() {} - virtual void Swap( - Field* data, - const internal::RepeatedFieldAccessor* other_mutator, - Field* other_data) const { + void Swap(Field* data, const internal::RepeatedFieldAccessor* other_mutator, + Field* other_data) const override { if (this == other_mutator) { MutableRepeatedField(data)->Swap(MutableRepeatedField(other_data)); } else { - RepeatedPtrField tmp; + RepeatedPtrField tmp; tmp.Swap(MutableRepeatedField(data)); int other_size = other_mutator->Size(other_data); for (int i = 0; i < other_size; ++i) { - Add(data, other_mutator->Get(other_data, i)); + Add(data, other_mutator->Get(other_data, i)); } int size = Size(data); other_mutator->Clear(other_data); for (int i = 0; i < size; ++i) { - other_mutator->Add(other_data, tmp.Get(i)); + other_mutator->Add(other_data, tmp.Get(i)); } } } protected: - virtual string* New(const Value*) const { - return new string(); + std::string* New(const Value*) const override { return new std::string(); } + void ConvertToT(const Value* value, std::string* result) const override { + *result = *static_cast(value); } - virtual void ConvertToT(const Value* value, string* result) const { - *result = *static_cast(value); - } - virtual const Value* ConvertFromT(const string& value, - Value* scratch_space) const { + const Value* ConvertFromT(const std::string& value, + Value* scratch_space) const override { return static_cast(&value); } }; -class RepeatedPtrFieldMessageAccessor +class RepeatedPtrFieldMessageAccessor final : public RepeatedPtrFieldWrapper { typedef void Field; typedef void Value; public: RepeatedPtrFieldMessageAccessor() {} - virtual ~RepeatedPtrFieldMessageAccessor() {} - virtual void Swap( - Field* data, - const internal::RepeatedFieldAccessor* other_mutator, - Field* other_data) const { + void Swap(Field* data, const internal::RepeatedFieldAccessor* other_mutator, + Field* other_data) const override { GOOGLE_CHECK(this == other_mutator); MutableRepeatedField(data)->Swap(MutableRepeatedField(other_data)); } protected: - virtual Message* New(const Value* value) const { + Message* New(const Value* value) const override { return static_cast(value)->New(); } - virtual void ConvertToT(const Value* value, Message* result) const { + void ConvertToT(const Value* value, Message* result) const override { result->CopyFrom(*static_cast(value)); } - virtual const Value* ConvertFromT(const Message& value, - Value* scratch_space) const { + const Value* ConvertFromT(const Message& value, + Value* scratch_space) const override { return static_cast(&value); } }; } // namespace internal } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_REFLECTION_INTERNAL_H__ diff --git a/third_party/protobuf/src/google/protobuf/reflection_ops.cc b/third_party/protobuf/src/google/protobuf/reflection_ops.cc index 3cd50340..3ced1419 100644 --- a/third_party/protobuf/src/google/protobuf/reflection_ops.cc +++ b/third_party/protobuf/src/google/protobuf/reflection_ops.cc @@ -41,9 +41,13 @@ #include #include #include +#include #include #include + +#include + namespace google { namespace protobuf { namespace internal { @@ -52,7 +56,7 @@ static const Reflection* GetReflectionOrDie(const Message& m) { const Reflection* r = m.GetReflection(); if (r == nullptr) { const Descriptor* d = m.GetDescriptor(); - const string& mtype = d ? d->name() : "unknown"; + const std::string& mtype = d ? d->name() : "unknown"; // RawMessage is one known type for which GetReflection() returns nullptr. GOOGLE_LOG(FATAL) << "Message does not support reflection (type " << mtype << ")."; } @@ -70,12 +74,16 @@ void ReflectionOps::Merge(const Message& from, Message* to) { const Descriptor* descriptor = from.GetDescriptor(); GOOGLE_CHECK_EQ(to->GetDescriptor(), descriptor) - << "Tried to merge messages of different types " - << "(merge " << descriptor->full_name() - << " to " << to->GetDescriptor()->full_name() << ")"; + << "Tried to merge messages of different types " + << "(merge " << descriptor->full_name() << " to " + << to->GetDescriptor()->full_name() << ")"; const Reflection* from_reflection = GetReflectionOrDie(from); const Reflection* to_reflection = GetReflectionOrDie(*to); + bool is_from_generated = (from_reflection->GetMessageFactory() == + google::protobuf::MessageFactory::generated_factory()); + bool is_to_generated = (to_reflection->GetMessageFactory() == + google::protobuf::MessageFactory::generated_factory()); std::vector fields; from_reflection->ListFields(from, &fields); @@ -83,61 +91,75 @@ void ReflectionOps::Merge(const Message& from, Message* to) { const FieldDescriptor* field = fields[i]; if (field->is_repeated()) { + // Use map reflection if both are in map status and have the + // same map type to avoid sync with repeated field. + // Note: As from and to messages have the same descriptor, the + // map field types are the same if they are both generated + // messages or both dynamic messages. + if (is_from_generated == is_to_generated && field->is_map()) { + const MapFieldBase* from_field = + from_reflection->GetMapData(from, field); + MapFieldBase* to_field = to_reflection->MutableMapData(to, field); + if (to_field->IsMapValid() && from_field->IsMapValid()) { + to_field->MergeFrom(*from_field); + continue; + } + } int count = from_reflection->FieldSize(from, field); for (int j = 0; j < count; j++) { switch (field->cpp_type()) { -#define HANDLE_TYPE(CPPTYPE, METHOD) \ - case FieldDescriptor::CPPTYPE_##CPPTYPE: \ - to_reflection->Add##METHOD(to, field, \ - from_reflection->GetRepeated##METHOD(from, field, j)); \ - break; +#define HANDLE_TYPE(CPPTYPE, METHOD) \ + case FieldDescriptor::CPPTYPE_##CPPTYPE: \ + to_reflection->Add##METHOD( \ + to, field, from_reflection->GetRepeated##METHOD(from, field, j)); \ + break; - HANDLE_TYPE(INT32 , Int32 ); - HANDLE_TYPE(INT64 , Int64 ); + HANDLE_TYPE(INT32, Int32); + HANDLE_TYPE(INT64, Int64); HANDLE_TYPE(UINT32, UInt32); HANDLE_TYPE(UINT64, UInt64); - HANDLE_TYPE(FLOAT , Float ); + HANDLE_TYPE(FLOAT, Float); HANDLE_TYPE(DOUBLE, Double); - HANDLE_TYPE(BOOL , Bool ); + HANDLE_TYPE(BOOL, Bool); HANDLE_TYPE(STRING, String); - HANDLE_TYPE(ENUM , Enum ); + HANDLE_TYPE(ENUM, Enum); #undef HANDLE_TYPE case FieldDescriptor::CPPTYPE_MESSAGE: to_reflection->AddMessage(to, field)->MergeFrom( - from_reflection->GetRepeatedMessage(from, field, j)); + from_reflection->GetRepeatedMessage(from, field, j)); break; } } } else { switch (field->cpp_type()) { -#define HANDLE_TYPE(CPPTYPE, METHOD) \ - case FieldDescriptor::CPPTYPE_##CPPTYPE: \ - to_reflection->Set##METHOD(to, field, \ - from_reflection->Get##METHOD(from, field)); \ - break; +#define HANDLE_TYPE(CPPTYPE, METHOD) \ + case FieldDescriptor::CPPTYPE_##CPPTYPE: \ + to_reflection->Set##METHOD(to, field, \ + from_reflection->Get##METHOD(from, field)); \ + break; - HANDLE_TYPE(INT32 , Int32 ); - HANDLE_TYPE(INT64 , Int64 ); + HANDLE_TYPE(INT32, Int32); + HANDLE_TYPE(INT64, Int64); HANDLE_TYPE(UINT32, UInt32); HANDLE_TYPE(UINT64, UInt64); - HANDLE_TYPE(FLOAT , Float ); + HANDLE_TYPE(FLOAT, Float); HANDLE_TYPE(DOUBLE, Double); - HANDLE_TYPE(BOOL , Bool ); + HANDLE_TYPE(BOOL, Bool); HANDLE_TYPE(STRING, String); - HANDLE_TYPE(ENUM , Enum ); + HANDLE_TYPE(ENUM, Enum); #undef HANDLE_TYPE case FieldDescriptor::CPPTYPE_MESSAGE: to_reflection->MutableMessage(to, field)->MergeFrom( - from_reflection->GetMessage(from, field)); + from_reflection->GetMessage(from, field)); break; } } } to_reflection->MutableUnknownFields(to)->MergeFrom( - from_reflection->GetUnknownFields(from)); + from_reflection->GetUnknownFields(from)); } void ReflectionOps::Clear(Message* message) { @@ -175,8 +197,8 @@ bool ReflectionOps::IsInitialized(const Message& message) { if (field->is_map()) { const FieldDescriptor* value_field = field->message_type()->field(1); if (value_field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - MapFieldBase* map_field = - reflection->MapData(const_cast(&message), field); + const MapFieldBase* map_field = + reflection->GetMapData(message, field); if (map_field->IsMapValid()) { MapIterator iter(const_cast(&message), field); MapIterator end(const_cast(&message), field); @@ -198,7 +220,7 @@ bool ReflectionOps::IsInitialized(const Message& message) { for (int j = 0; j < size; j++) { if (!reflection->GetRepeatedMessage(message, field, j) - .IsInitialized()) { + .IsInitialized()) { return false; } } @@ -224,10 +246,30 @@ void ReflectionOps::DiscardUnknownFields(Message* message) { const FieldDescriptor* field = fields[i]; if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { if (field->is_repeated()) { + if (field->is_map()) { + const FieldDescriptor* value_field = field->message_type()->field(1); + if (value_field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { + const MapFieldBase* map_field = + reflection->MutableMapData(message, field); + if (map_field->IsMapValid()) { + MapIterator iter(message, field); + MapIterator end(message, field); + for (map_field->MapBegin(&iter), map_field->MapEnd(&end); + iter != end; ++iter) { + iter.MutableValueRef() + ->MutableMessageValue() + ->DiscardUnknownFields(); + } + continue; + } + } else { + continue; + } + } int size = reflection->FieldSize(*message, field); for (int j = 0; j < size; j++) { reflection->MutableRepeatedMessage(message, field, j) - ->DiscardUnknownFields(); + ->DiscardUnknownFields(); } } else { reflection->MutableMessage(message, field)->DiscardUnknownFields(); @@ -236,10 +278,9 @@ void ReflectionOps::DiscardUnknownFields(Message* message) { } } -static string SubMessagePrefix(const string& prefix, - const FieldDescriptor* field, - int index) { - string result(prefix); +static std::string SubMessagePrefix(const std::string& prefix, + const FieldDescriptor* field, int index) { + std::string result(prefix); if (field->is_extension()) { result.append("("); result.append(field->full_name()); @@ -249,17 +290,16 @@ static string SubMessagePrefix(const string& prefix, } if (index != -1) { result.append("["); - result.append(SimpleItoa(index)); + result.append(StrCat(index)); result.append("]"); } result.append("."); return result; } -void ReflectionOps::FindInitializationErrors( - const Message& message, - const string& prefix, - std::vector* errors) { +void ReflectionOps::FindInitializationErrors(const Message& message, + const std::string& prefix, + std::vector* errors) { const Descriptor* descriptor = message.GetDescriptor(); const Reflection* reflection = GetReflectionOrDie(message); @@ -284,16 +324,14 @@ void ReflectionOps::FindInitializationErrors( for (int j = 0; j < size; j++) { const Message& sub_message = - reflection->GetRepeatedMessage(message, field, j); + reflection->GetRepeatedMessage(message, field, j); FindInitializationErrors(sub_message, - SubMessagePrefix(prefix, field, j), - errors); + SubMessagePrefix(prefix, field, j), errors); } } else { const Message& sub_message = reflection->GetMessage(message, field); FindInitializationErrors(sub_message, - SubMessagePrefix(prefix, field, -1), - errors); + SubMessagePrefix(prefix, field, -1), errors); } } } diff --git a/third_party/protobuf/src/google/protobuf/reflection_ops.h b/third_party/protobuf/src/google/protobuf/reflection_ops.h index 45d8c650..b30c050a 100644 --- a/third_party/protobuf/src/google/protobuf/reflection_ops.h +++ b/third_party/protobuf/src/google/protobuf/reflection_ops.h @@ -41,6 +41,12 @@ #include #include +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + +#include + namespace google { namespace protobuf { namespace internal { @@ -54,7 +60,7 @@ namespace internal { // the Message interface. // // This class is really a namespace that contains only static methods. -class LIBPROTOBUF_EXPORT ReflectionOps { +class PROTOBUF_EXPORT ReflectionOps { public: static void Copy(const Message& from, Message* to); static void Merge(const Message& from, Message* to); @@ -66,8 +72,8 @@ class LIBPROTOBUF_EXPORT ReflectionOps { // paths (e.g. "foo.bar[5].baz") to *names. "prefix" will be attached to // the front of each name. static void FindInitializationErrors(const Message& message, - const string& prefix, - std::vector* errors); + const std::string& prefix, + std::vector* errors); private: // All methods are static. No need to construct. @@ -76,6 +82,8 @@ class LIBPROTOBUF_EXPORT ReflectionOps { } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_REFLECTION_OPS_H__ diff --git a/third_party/protobuf/src/google/protobuf/reflection_ops_unittest.cc b/third_party/protobuf/src/google/protobuf/reflection_ops_unittest.cc index 9cedb342..bd141933 100644 --- a/third_party/protobuf/src/google/protobuf/reflection_ops_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/reflection_ops_unittest.cc @@ -33,9 +33,9 @@ // Sanjay Ghemawat, Jeff Dean, and others. #include -#include -#include #include +#include +#include #include #include @@ -128,18 +128,21 @@ TEST(ReflectionOpsTest, MergeExtensions) { TestUtil::SetAllExtensions(&message); // This field will test merging into an empty spot. - message2.SetExtension(unittest::optional_int32_extension, - message.GetExtension(unittest::optional_int32_extension)); + message2.SetExtension( + unittest::optional_int32_extension, + message.GetExtension(unittest::optional_int32_extension)); message.ClearExtension(unittest::optional_int32_extension); // This tests overwriting. - message2.SetExtension(unittest::optional_string_extension, - message.GetExtension(unittest::optional_string_extension)); + message2.SetExtension( + unittest::optional_string_extension, + message.GetExtension(unittest::optional_string_extension)); message.SetExtension(unittest::optional_string_extension, "something else"); // This tests concatenating. - message2.AddExtension(unittest::repeated_int32_extension, - message.GetExtension(unittest::repeated_int32_extension, 1)); + message2.AddExtension( + unittest::repeated_int32_extension, + message.GetExtension(unittest::repeated_int32_extension, 1)); int32 i = message.GetExtension(unittest::repeated_int32_extension, 0); message.ClearExtension(unittest::repeated_int32_extension); message.AddExtension(unittest::repeated_int32_extension, i); @@ -192,9 +195,7 @@ TEST(ReflectionOpsTest, MergeFromSelf) { unittest::TestAllTypes message; - EXPECT_DEATH( - ReflectionOps::Merge(message, &message), - "&from"); + EXPECT_DEATH(ReflectionOps::Merge(message, &message), "&from"); } #endif // PROTOBUF_HAS_DEATH_TEST @@ -235,9 +236,9 @@ TEST(ReflectionOpsTest, ClearExtensions) { &message.GetExtension(unittest::optionalgroup_extension)); EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(), &message.GetExtension(unittest::optional_nested_message_extension)); - EXPECT_NE(&unittest::ForeignMessage::default_instance(), - &message.GetExtension( - unittest::optional_foreign_message_extension)); + EXPECT_NE( + &unittest::ForeignMessage::default_instance(), + &message.GetExtension(unittest::optional_foreign_message_extension)); EXPECT_NE(&unittest_import::ImportMessage::default_instance(), &message.GetExtension(unittest::optional_import_message_extension)); } @@ -274,30 +275,29 @@ TEST(ReflectionOpsTest, DiscardUnknownFields) { TestUtil::SetAllFields(&message); // Set some unknown fields in message. - message.mutable_unknown_fields() - ->AddVarint(123456, 654321); + message.mutable_unknown_fields()->AddVarint(123456, 654321); message.mutable_optional_nested_message() - ->mutable_unknown_fields() - ->AddVarint(123456, 654321); + ->mutable_unknown_fields() + ->AddVarint(123456, 654321); message.mutable_repeated_nested_message(0) - ->mutable_unknown_fields() - ->AddVarint(123456, 654321); + ->mutable_unknown_fields() + ->AddVarint(123456, 654321); EXPECT_EQ(1, message.unknown_fields().field_count()); - EXPECT_EQ(1, message.optional_nested_message() - .unknown_fields().field_count()); - EXPECT_EQ(1, message.repeated_nested_message(0) - .unknown_fields().field_count()); + EXPECT_EQ(1, + message.optional_nested_message().unknown_fields().field_count()); + EXPECT_EQ(1, + message.repeated_nested_message(0).unknown_fields().field_count()); // Discard them. ReflectionOps::DiscardUnknownFields(&message); TestUtil::ExpectAllFieldsSet(message); EXPECT_EQ(0, message.unknown_fields().field_count()); - EXPECT_EQ(0, message.optional_nested_message() - .unknown_fields().field_count()); - EXPECT_EQ(0, message.repeated_nested_message(0) - .unknown_fields().field_count()); + EXPECT_EQ(0, + message.optional_nested_message().unknown_fields().field_count()); + EXPECT_EQ(0, + message.repeated_nested_message(0).unknown_fields().field_count()); } TEST(ReflectionOpsTest, DiscardUnknownExtensions) { @@ -305,34 +305,35 @@ TEST(ReflectionOpsTest, DiscardUnknownExtensions) { TestUtil::SetAllExtensions(&message); // Set some unknown fields. - message.mutable_unknown_fields() - ->AddVarint(123456, 654321); + message.mutable_unknown_fields()->AddVarint(123456, 654321); message.MutableExtension(unittest::optional_nested_message_extension) - ->mutable_unknown_fields() - ->AddVarint(123456, 654321); + ->mutable_unknown_fields() + ->AddVarint(123456, 654321); message.MutableExtension(unittest::repeated_nested_message_extension, 0) - ->mutable_unknown_fields() - ->AddVarint(123456, 654321); + ->mutable_unknown_fields() + ->AddVarint(123456, 654321); EXPECT_EQ(1, message.unknown_fields().field_count()); + EXPECT_EQ(1, message.GetExtension(unittest::optional_nested_message_extension) + .unknown_fields() + .field_count()); EXPECT_EQ(1, - message.GetExtension(unittest::optional_nested_message_extension) - .unknown_fields().field_count()); - EXPECT_EQ(1, - message.GetExtension(unittest::repeated_nested_message_extension, 0) - .unknown_fields().field_count()); + message.GetExtension(unittest::repeated_nested_message_extension, 0) + .unknown_fields() + .field_count()); // Discard them. ReflectionOps::DiscardUnknownFields(&message); TestUtil::ExpectAllExtensionsSet(message); EXPECT_EQ(0, message.unknown_fields().field_count()); + EXPECT_EQ(0, message.GetExtension(unittest::optional_nested_message_extension) + .unknown_fields() + .field_count()); EXPECT_EQ(0, - message.GetExtension(unittest::optional_nested_message_extension) - .unknown_fields().field_count()); - EXPECT_EQ(0, - message.GetExtension(unittest::repeated_nested_message_extension, 0) - .unknown_fields().field_count()); + message.GetExtension(unittest::repeated_nested_message_extension, 0) + .unknown_fields() + .field_count()); } TEST(ReflectionOpsTest, IsInitialized) { @@ -419,8 +420,8 @@ TEST(ReflectionOpsTest, OneofIsInitialized) { EXPECT_TRUE(ReflectionOps::IsInitialized(message)); } -static string FindInitializationErrors(const Message& message) { - std::vector errors; +static std::string FindInitializationErrors(const Message& message) { + std::vector errors; ReflectionOps::FindInitializationErrors(message, "", &errors); return Join(errors, ","); } @@ -435,16 +436,17 @@ TEST(ReflectionOpsTest, FindForeignInitializationErrors) { message.mutable_optional_message(); message.add_repeated_message(); message.add_repeated_message(); - EXPECT_EQ("optional_message.a," - "optional_message.b," - "optional_message.c," - "repeated_message[0].a," - "repeated_message[0].b," - "repeated_message[0].c," - "repeated_message[1].a," - "repeated_message[1].b," - "repeated_message[1].c", - FindInitializationErrors(message)); + EXPECT_EQ( + "optional_message.a," + "optional_message.b," + "optional_message.c," + "repeated_message[0].a," + "repeated_message[0].b," + "repeated_message[0].c," + "repeated_message[1].a," + "repeated_message[1].b," + "repeated_message[1].c", + FindInitializationErrors(message)); } TEST(ReflectionOpsTest, FindExtensionInitializationErrors) { @@ -452,23 +454,23 @@ TEST(ReflectionOpsTest, FindExtensionInitializationErrors) { message.MutableExtension(unittest::TestRequired::single); message.AddExtension(unittest::TestRequired::multi); message.AddExtension(unittest::TestRequired::multi); - EXPECT_EQ("(protobuf_unittest.TestRequired.single).a," - "(protobuf_unittest.TestRequired.single).b," - "(protobuf_unittest.TestRequired.single).c," - "(protobuf_unittest.TestRequired.multi)[0].a," - "(protobuf_unittest.TestRequired.multi)[0].b," - "(protobuf_unittest.TestRequired.multi)[0].c," - "(protobuf_unittest.TestRequired.multi)[1].a," - "(protobuf_unittest.TestRequired.multi)[1].b," - "(protobuf_unittest.TestRequired.multi)[1].c", - FindInitializationErrors(message)); + EXPECT_EQ( + "(protobuf_unittest.TestRequired.single).a," + "(protobuf_unittest.TestRequired.single).b," + "(protobuf_unittest.TestRequired.single).c," + "(protobuf_unittest.TestRequired.multi)[0].a," + "(protobuf_unittest.TestRequired.multi)[0].b," + "(protobuf_unittest.TestRequired.multi)[0].c," + "(protobuf_unittest.TestRequired.multi)[1].a," + "(protobuf_unittest.TestRequired.multi)[1].b," + "(protobuf_unittest.TestRequired.multi)[1].c", + FindInitializationErrors(message)); } TEST(ReflectionOpsTest, FindOneofInitializationErrors) { unittest::TestRequiredOneof message; message.mutable_foo_message(); - EXPECT_EQ("foo_message.required_double", - FindInitializationErrors(message)); + EXPECT_EQ("foo_message.required_double", FindInitializationErrors(message)); } } // namespace diff --git a/third_party/protobuf/src/google/protobuf/repeated_field.cc b/third_party/protobuf/src/google/protobuf/repeated_field.cc index 310000aa..e5dbe025 100644 --- a/third_party/protobuf/src/google/protobuf/repeated_field.cc +++ b/third_party/protobuf/src/google/protobuf/repeated_field.cc @@ -34,9 +34,11 @@ #include -#include #include #include +#include + +#include namespace google { namespace protobuf { @@ -54,16 +56,14 @@ void** RepeatedPtrFieldBase::InternalExtend(int extend_amount) { Arena* arena = GetArenaNoVirtual(); new_size = std::max(kMinRepeatedFieldAllocationSize, std::max(total_size_ * 2, new_size)); - GOOGLE_CHECK_LE(new_size, - (std::numeric_limits::max() - kRepHeaderSize) / - sizeof(old_rep->elements[0])) + GOOGLE_CHECK_LE(new_size, (std::numeric_limits::max() - kRepHeaderSize) / + sizeof(old_rep->elements[0])) << "Requested size is too large to fit into size_t."; size_t bytes = kRepHeaderSize + sizeof(old_rep->elements[0]) * new_size; if (arena == NULL) { rep_ = reinterpret_cast(::operator new(bytes)); } else { - rep_ = reinterpret_cast( - ::google::protobuf::Arena::CreateArray(arena, bytes)); + rep_ = reinterpret_cast(Arena::CreateArray(arena, bytes)); } #if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation) const int old_total_size = total_size_; @@ -103,18 +103,17 @@ void RepeatedPtrFieldBase::CloseGap(int start, int num) { rep_->allocated_size -= num; } -google::protobuf::MessageLite* RepeatedPtrFieldBase::AddWeak( - const google::protobuf::MessageLite* prototype) { +MessageLite* RepeatedPtrFieldBase::AddWeak(const MessageLite* prototype) { if (rep_ != NULL && current_size_ < rep_->allocated_size) { - return reinterpret_cast( - rep_->elements[current_size_++]); + return reinterpret_cast(rep_->elements[current_size_++]); } if (!rep_ || rep_->allocated_size == total_size_) { Reserve(total_size_ + 1); } ++rep_->allocated_size; - google::protobuf::MessageLite* result = prototype ? prototype->New(arena_) : - Arena::CreateMessage(arena_); + MessageLite* result = prototype + ? prototype->New(arena_) + : Arena::CreateMessage(arena_); rep_->elements[current_size_++] = result; return result; } @@ -122,5 +121,14 @@ google::protobuf::MessageLite* RepeatedPtrFieldBase::AddWeak( } // namespace internal +template class PROTOBUF_EXPORT RepeatedField; +template class PROTOBUF_EXPORT RepeatedField; +template class PROTOBUF_EXPORT RepeatedField; +template class PROTOBUF_EXPORT RepeatedField; +template class PROTOBUF_EXPORT RepeatedField; +template class PROTOBUF_EXPORT RepeatedField; +template class PROTOBUF_EXPORT RepeatedField; +template class PROTOBUF_EXPORT RepeatedPtrField; + } // namespace protobuf } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/repeated_field.h b/third_party/protobuf/src/google/protobuf/repeated_field.h index b47ea994..4c631f05 100644 --- a/third_party/protobuf/src/google/protobuf/repeated_field.h +++ b/third_party/protobuf/src/google/protobuf/repeated_field.h @@ -46,6 +46,7 @@ #ifndef GOOGLE_PROTOBUF_REPEATED_FIELD_H__ #define GOOGLE_PROTOBUF_REPEATED_FIELD_H__ +#include #ifdef _MSC_VER // This is required for min/max on VS2013 only. #include @@ -54,24 +55,31 @@ #include #include #include -#include +#include #include #include #include #include #include -#include +#include +#include #include +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + // Forward-declare these so that we can make them friends. -namespace google { namespace upb { namespace google_opensource { class GMR_Handlers; } // namespace google_opensource } // namespace upb +namespace google { namespace protobuf { class Message; @@ -103,7 +111,6 @@ inline int CalculateReserve(Iter begin, Iter end) { } } // namespace internal - // RepeatedField is used to represent repeated fields of a primitive type (in // other words, everything except strings and nested Messages). Most users will // not ever use a RepeatedField directly; they will use the get-by-index, @@ -132,6 +139,9 @@ class RepeatedField final { const Element& operator[](int index) const { return Get(index); } Element& operator[](int index) { return *Mutable(index); } + const Element& at(int index) const; + Element& at(int index); + void Set(int index, const Element& value); void Add(const Element& value); // Appends a new element and return a pointer to it. @@ -209,15 +219,11 @@ class RepeatedField final { // Reverse iterator support typedef std::reverse_iterator const_reverse_iterator; typedef std::reverse_iterator reverse_iterator; - reverse_iterator rbegin() { - return reverse_iterator(end()); - } + reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } - reverse_iterator rend() { - return reverse_iterator(begin()); - } + reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } @@ -246,9 +252,7 @@ class RepeatedField final { iterator erase(const_iterator first, const_iterator last); // Get the Arena on which this RepeatedField stores its elements. - ::google::protobuf::Arena* GetArena() const { - return GetArenaNoVirtual(); - } + Arena* GetArena() const { return GetArenaNoVirtual(); } // For internal use only. // @@ -283,13 +287,20 @@ class RepeatedField final { // an allocation in the constructor when we have an Arena. union Pointer { Pointer(Arena* a) : arena(a) {} - Arena* arena; // When total_size_ == 0. - Rep* rep; // When total_size_ != 0. + Arena* arena; // When total_size_ == 0. + Element* elements; // When total_size_ != 0, this is Rep->elements of Rep. } ptr_; + Element* elements() const { + GOOGLE_DCHECK_GT(total_size_, 0); + return ptr_.elements; + } + Rep* rep() const { GOOGLE_DCHECK_GT(total_size_, 0); - return ptr_.rep; + char* addr = + reinterpret_cast(ptr_.elements) - offsetof(Rep, elements); + return reinterpret_cast(addr); } friend class Arena; @@ -306,7 +317,7 @@ class RepeatedField final { // Internal helper expected by Arena methods. inline Arena* GetArenaNoVirtual() const { - return (total_size_ == 0) ? ptr_.arena : ptr_.rep->arena; + return (total_size_ == 0) ? ptr_.arena : rep()->arena; } // Internal helper to delete all elements and deallocate the storage. @@ -334,13 +345,15 @@ class RepeatedField final { const Element* unsafe_data() const; }; -template +template const size_t RepeatedField::kRepHeaderSize = reinterpret_cast(&reinterpret_cast(16)->elements[0]) - 16; namespace internal { -template class RepeatedPtrIterator; -template class RepeatedPtrOverPtrsIterator; +template +class RepeatedPtrIterator; +template +class RepeatedPtrOverPtrsIterator; } // namespace internal namespace internal { @@ -364,7 +377,7 @@ namespace internal { // arena-related "copy if on different arena" behavior if the necessary methods // exist on the contained type. In particular, we rely on MergeFrom() existing // as a general proxy for the fact that a copy will work, and we also provide a -// specific override for string*. +// specific override for std::string*. template struct TypeImplementsMergeBehaviorProbeForMergeFrom { typedef char HasMerge; @@ -377,29 +390,36 @@ struct TypeImplementsMergeBehaviorProbeForMergeFrom { // We mangle these names a bit to avoid compatibility issues in 'unclean' // include environments that may have, e.g., "#define test ..." (yes, this // exists). - template - struct CheckType; - template static HasMerge Check( - CheckType*); - template static HasMerge Check( - CheckType*); - template static HasNoMerge Check(...); + template + struct CheckType; + template + static HasMerge Check(CheckType*); + template + static HasMerge Check(CheckType*); + template + static HasNoMerge Check(...); // Resolves to either std::true_type or std::false_type. typedef std::integral_constant(0)) == sizeof(HasMerge))> type; + (sizeof(Check(0)) == sizeof(HasMerge))> + type; }; template -struct TypeImplementsMergeBehavior : - TypeImplementsMergeBehaviorProbeForMergeFrom {}; +struct TypeImplementsMergeBehavior + : TypeImplementsMergeBehaviorProbeForMergeFrom {}; template <> -struct TypeImplementsMergeBehavior< ::std::string> { +struct TypeImplementsMergeBehavior { typedef std::true_type type; }; +template +struct IsMovable + : std::integral_constant::value && + std::is_move_assignable::value> {}; + // This is the common base class for RepeatedPtrFields. It deals only in void* // pointers. Users should not use this interface directly. // @@ -413,7 +433,7 @@ struct TypeImplementsMergeBehavior< ::std::string> { // typedef MyType WeakType; // static Type* New(); // static WeakType* NewFromPrototype(const WeakType* prototype, -// ::google::protobuf::Arena* arena); +// Arena* arena); // static void Delete(Type*); // static void Clear(Type*); // static void Merge(const Type& from, Type* to); @@ -421,10 +441,10 @@ struct TypeImplementsMergeBehavior< ::std::string> { // // Only needs to be implemented if SpaceUsedExcludingSelf() is called. // static int SpaceUsedLong(const Type&); // }; -class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase { +class PROTOBUF_EXPORT RepeatedPtrFieldBase { protected: RepeatedPtrFieldBase(); - explicit RepeatedPtrFieldBase(::google::protobuf::Arena* arena); + explicit RepeatedPtrFieldBase(Arena* arena); ~RepeatedPtrFieldBase() {} // Must be called from destructor. @@ -434,6 +454,11 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase { bool empty() const; int size() const; + template + const typename TypeHandler::Type& at(int index) const; + template + typename TypeHandler::Type& at(int index); + template typename TypeHandler::Type* Mutable(int index); template @@ -453,7 +478,7 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase { // a link-time dependency on the concrete message type. This method is used to // implement implicit weak fields. The prototype may be NULL, in which case an // ImplicitWeakMessage will be used as a placeholder. - google::protobuf::MessageLite* AddWeak(const google::protobuf::MessageLite* prototype); + MessageLite* AddWeak(const MessageLite* prototype); template void Clear(); @@ -464,9 +489,10 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase { inline void InternalSwap(RepeatedPtrFieldBase* other); protected: - template - void Add(typename TypeHandler::Type&& value, - std::enable_if* dummy = NULL); + template < + typename TypeHandler, + typename std::enable_if::type* = nullptr> + void Add(typename TypeHandler::Type&& value); template void RemoveLast(); @@ -488,8 +514,8 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase { template const typename TypeHandler::Type* const* data() const; - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - void Swap(RepeatedPtrFieldBase* other); + template + PROTOBUF_ALWAYS_INLINE void Swap(RepeatedPtrFieldBase* other); void SwapElements(int index1, int index2); @@ -502,7 +528,7 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase { template typename TypeHandler::Type* AddFromCleared(); - template + template void AddAllocated(typename TypeHandler::Type* value) { typename TypeImplementsMergeBehavior::type t; AddAllocatedInternal(value, t); @@ -533,24 +559,22 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase { template void AddAllocatedInternal(typename TypeHandler::Type* value, std::false_type); - template GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE - void AddAllocatedSlowWithCopy(typename TypeHandler::Type* value, - Arena* value_arena, - Arena* my_arena); - template GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE - void AddAllocatedSlowWithoutCopy(typename TypeHandler::Type* value); + template + PROTOBUF_NOINLINE void AddAllocatedSlowWithCopy( + typename TypeHandler::Type* value, Arena* value_arena, Arena* my_arena); + template + PROTOBUF_NOINLINE void AddAllocatedSlowWithoutCopy( + typename TypeHandler::Type* value); template typename TypeHandler::Type* ReleaseLastInternal(std::true_type); template typename TypeHandler::Type* ReleaseLastInternal(std::false_type); - template GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE - void SwapFallback(RepeatedPtrFieldBase* other); + template + PROTOBUF_NOINLINE void SwapFallback(RepeatedPtrFieldBase* other); - inline Arena* GetArenaNoVirtual() const { - return arena_; - } + inline Arena* GetArenaNoVirtual() const { return arena_; } private: static const int kInitialSize = 0; @@ -566,11 +590,11 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase { // Placing all fields directly in the RepeatedPtrFieldBase instance costs // significant performance for memory-sensitive workloads. Arena* arena_; - int current_size_; - int total_size_; + int current_size_; + int total_size_; struct Rep { - int allocated_size; - void* elements[1]; + int allocated_size; + void* elements[1]; }; static const size_t kRepHeaderSize = sizeof(Rep) - sizeof(void*); // Contains arena ptr and the elements array. We also keep the invariant that @@ -588,13 +612,14 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase { // Non-templated inner function to avoid code duplication. Takes a function // pointer to the type-specific (templated) inner allocate/merge loop. - void MergeFromInternal( - const RepeatedPtrFieldBase& other, - void (RepeatedPtrFieldBase::*inner_loop)(void**, void**, int, int)); + void MergeFromInternal(const RepeatedPtrFieldBase& other, + void (RepeatedPtrFieldBase::*inner_loop)(void**, + void**, int, + int)); - template - void MergeFromInnerLoop( - void** our_elems, void** other_elems, int length, int already_allocated); + template + void MergeFromInnerLoop(void** our_elems, void** other_elems, int length, + int already_allocated); // Internal helper: extend array space if necessary to contain |extend_amount| // more elements, and return a pointer to the element immediately following @@ -637,27 +662,30 @@ class GenericTypeHandler { public: typedef GenericType Type; typedef GenericType WeakType; - static const bool Moveable = false; + using Movable = IsMovable; static inline GenericType* New(Arena* arena) { - return ::google::protobuf::Arena::CreateMaybeMessage(arena); + return Arena::CreateMaybeMessage(arena); } - static inline GenericType* NewFromPrototype( - const GenericType* prototype, ::google::protobuf::Arena* arena = NULL); + static inline GenericType* New(Arena* arena, GenericType&& value) { + return Arena::Create(arena, std::move(value)); + } + static inline GenericType* NewFromPrototype(const GenericType* prototype, + Arena* arena = NULL); static inline void Delete(GenericType* value, Arena* arena) { if (arena == NULL) { delete value; } } - static inline ::google::protobuf::Arena* GetArena(GenericType* value) { - return ::google::protobuf::Arena::GetArena(value); + static inline Arena* GetArena(GenericType* value) { + return Arena::GetArena(value); } static inline void* GetMaybeArenaPointer(GenericType* value) { - return ::google::protobuf::Arena::GetArena(value); + return Arena::GetArena(value); } static inline void Clear(GenericType* value) { value->Clear(); } - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE + PROTOBUF_NOINLINE static void Merge(const GenericType& from, GenericType* to); static inline size_t SpaceUsedLong(const GenericType& value) { return value.SpaceUsedLong(); @@ -666,7 +694,7 @@ class GenericTypeHandler { template GenericType* GenericTypeHandler::NewFromPrototype( - const GenericType* /* prototype */, ::google::protobuf::Arena* arena) { + const GenericType* /* prototype */, Arena* arena) { return New(arena); } template @@ -678,15 +706,14 @@ void GenericTypeHandler::Merge(const GenericType& from, // NewFromPrototype() and Merge() are not defined inline here, as we will need // to do a virtual function dispatch anyways to go from Message* to call // New/Merge. -template<> +template <> MessageLite* GenericTypeHandler::NewFromPrototype( - const MessageLite* prototype, google::protobuf::Arena* arena); -template<> -inline google::protobuf::Arena* GenericTypeHandler::GetArena( - MessageLite* value) { + const MessageLite* prototype, Arena* arena); +template <> +inline Arena* GenericTypeHandler::GetArena(MessageLite* value) { return value->GetArena(); } -template<> +template <> inline void* GenericTypeHandler::GetMaybeArenaPointer( MessageLite* value) { return value->GetMaybeArenaPointer(); @@ -694,26 +721,26 @@ inline void* GenericTypeHandler::GetMaybeArenaPointer( template <> void GenericTypeHandler::Merge(const MessageLite& from, MessageLite* to); -template<> -inline void GenericTypeHandler::Clear(string* value) { +template <> +inline void GenericTypeHandler::Clear(std::string* value) { value->clear(); } -template<> -void GenericTypeHandler::Merge(const string& from, - string* to); +template <> +void GenericTypeHandler::Merge(const std::string& from, + std::string* to); // Declarations of the specialization as we cannot define them here, as the // header that defines ProtocolMessage depends on types defined in this header. -#define DECLARE_SPECIALIZATIONS_FOR_BASE_PROTO_TYPES(TypeName) \ - template<> \ - TypeName* GenericTypeHandler::NewFromPrototype( \ - const TypeName* prototype, google::protobuf::Arena* arena); \ - template<> \ - google::protobuf::Arena* GenericTypeHandler::GetArena( \ - TypeName* value); \ - template<> \ - void* GenericTypeHandler::GetMaybeArenaPointer( \ - TypeName* value); +#define DECLARE_SPECIALIZATIONS_FOR_BASE_PROTO_TYPES(TypeName) \ + template <> \ + PROTOBUF_EXPORT TypeName* GenericTypeHandler::NewFromPrototype( \ + const TypeName* prototype, Arena* arena); \ + template <> \ + PROTOBUF_EXPORT Arena* GenericTypeHandler::GetArena( \ + TypeName* value); \ + template <> \ + PROTOBUF_EXPORT void* GenericTypeHandler::GetMaybeArenaPointer( \ + TypeName* value); // Message specialization bodies defined in message.cc. This split is necessary // to allow proto2-lite (which includes this header) to be independent of @@ -725,35 +752,34 @@ DECLARE_SPECIALIZATIONS_FOR_BASE_PROTO_TYPES(Message) class StringTypeHandler { public: - typedef string Type; - typedef string WeakType; - static const bool Moveable = std::is_move_constructible::value && - std::is_move_assignable::value; + typedef std::string Type; + typedef std::string WeakType; + using Movable = IsMovable; - static inline string* New(Arena* arena) { - return Arena::Create(arena); + static inline std::string* New(Arena* arena) { + return Arena::Create(arena); } - static inline string* New(Arena* arena, string&& value) { - return Arena::Create(arena, std::move(value)); + static inline std::string* New(Arena* arena, std::string&& value) { + return Arena::Create(arena, std::move(value)); } - static inline string* NewFromPrototype(const string*, - ::google::protobuf::Arena* arena) { + static inline std::string* NewFromPrototype(const std::string*, + Arena* arena) { return New(arena); } - static inline ::google::protobuf::Arena* GetArena(string*) { + static inline Arena* GetArena(std::string*) { return NULL; } + static inline void* GetMaybeArenaPointer(std::string* /* value */) { return NULL; } - static inline void* GetMaybeArenaPointer(string* /* value */) { - return NULL; - } - static inline void Delete(string* value, Arena* arena) { + static inline void Delete(std::string* value, Arena* arena) { if (arena == NULL) { delete value; } } - static inline void Clear(string* value) { value->clear(); } - static inline void Merge(const string& from, string* to) { *to = from; } - static size_t SpaceUsedLong(const string& value) { + static inline void Clear(std::string* value) { value->clear(); } + static inline void Merge(const std::string& from, std::string* to) { + *to = from; + } + static size_t SpaceUsedLong(const std::string& value) { return sizeof(value) + StringSpaceUsedExcludingSelfLong(value); } }; @@ -766,7 +792,7 @@ template class RepeatedPtrField final : private internal::RepeatedPtrFieldBase { public: RepeatedPtrField(); - explicit RepeatedPtrField(::google::protobuf::Arena* arena); + explicit RepeatedPtrField(Arena* arena); RepeatedPtrField(const RepeatedPtrField& other); template @@ -789,6 +815,9 @@ class RepeatedPtrField final : private internal::RepeatedPtrFieldBase { const Element& operator[](int index) const { return Get(index); } Element& operator[](int index) { return *Mutable(index); } + const Element& at(int index) const; + Element& at(int index); + // Remove the last element in the array. // Ownership of the element is retained by the array. void RemoveLast(); @@ -848,15 +877,11 @@ class RepeatedPtrField final : private internal::RepeatedPtrFieldBase { // Reverse iterator support typedef std::reverse_iterator const_reverse_iterator; typedef std::reverse_iterator reverse_iterator; - reverse_iterator rbegin() { - return reverse_iterator(end()); - } + reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } - reverse_iterator rend() { - return reverse_iterator(begin()); - } + reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } @@ -992,9 +1017,7 @@ class RepeatedPtrField final : private internal::RepeatedPtrFieldBase { iterator erase(const_iterator first, const_iterator last); // Gets the arena on which this RepeatedPtrField stores its elements. - ::google::protobuf::Arena* GetArena() const { - return GetArenaNoVirtual(); - } + Arena* GetArena() const { return GetArenaNoVirtual(); } // For internal use only. // @@ -1028,23 +1051,15 @@ class RepeatedPtrField final : private internal::RepeatedPtrFieldBase { template inline RepeatedField::RepeatedField() - : current_size_(0), - total_size_(0), - ptr_(NULL) { -} + : current_size_(0), total_size_(0), ptr_(NULL) {} template inline RepeatedField::RepeatedField(Arena* arena) - : current_size_(0), - total_size_(0), - ptr_(arena) { -} + : current_size_(0), total_size_(0), ptr_(arena) {} template inline RepeatedField::RepeatedField(const RepeatedField& other) - : current_size_(0), - total_size_(0), - ptr_(NULL) { + : current_size_(0), total_size_(0), ptr_(NULL) { if (other.current_size_ != 0) { Reserve(other.size()); AddNAlreadyReserved(other.size()); @@ -1055,15 +1070,22 @@ inline RepeatedField::RepeatedField(const RepeatedField& other) template template RepeatedField::RepeatedField(Iter begin, const Iter& end) - : current_size_(0), - total_size_(0), - ptr_(NULL) { + : current_size_(0), total_size_(0), ptr_(NULL) { int reserve = internal::CalculateReserve(begin, end); if (reserve != -1) { - Reserve(reserve); - for (; begin != end; ++begin) { - AddAlreadyReserved(*begin); + if (reserve == 0) { + return; } + + Reserve(reserve); + // TODO(ckennelly): The compiler loses track of the buffer freshly + // allocated by Reserve() by the time we call elements, so it cannot + // guarantee that elements does not alias [begin(), end()). + // + // If restrict is available, annotating the pointer obtained from elements() + // causes this to lower to memcpy instead of memmove. + std::copy(begin, end, elements()); + current_size_ = reserve; } else { for (; begin != end; ++begin) { Add(*begin); @@ -1079,10 +1101,9 @@ RepeatedField::~RepeatedField() { } template -inline RepeatedField& -RepeatedField::operator=(const RepeatedField& other) { - if (this != &other) - CopyFrom(other); +inline RepeatedField& RepeatedField::operator=( + const RepeatedField& other) { + if (this != &other) CopyFrom(other); return *this; } @@ -1090,7 +1111,8 @@ template inline RepeatedField::RepeatedField(RepeatedField&& other) noexcept : RepeatedField() { // We don't just call Swap(&other) here because it would perform 3 copies if - // the two fields are on different arenas. + // other is on an arena. This field can't be on an arena because arena + // construction always uses the Arena* accepting constructor. if (other.GetArenaNoVirtual()) { CopyFrom(other); } else { @@ -1128,35 +1150,39 @@ inline int RepeatedField::Capacity() const { return total_size_; } -template +template inline void RepeatedField::AddAlreadyReserved(const Element& value) { GOOGLE_DCHECK_LT(current_size_, total_size_); - rep()->elements[current_size_++] = value; + elements()[current_size_++] = value; } -template +template inline Element* RepeatedField::AddAlreadyReserved() { GOOGLE_DCHECK_LT(current_size_, total_size_); - return &rep()->elements[current_size_++]; + return &elements()[current_size_++]; } -template -inline Element* RepeatedField::AddNAlreadyReserved(int elements) { - GOOGLE_DCHECK_LE(current_size_ + elements, total_size_); - // Warning: total_size_ can be NULL if elements == 0 && current_size_ == 0. - // Existing callers depend on this behavior. :( - Element* ret = &ptr_.rep->elements[current_size_]; - current_size_ += elements; +template +inline Element* RepeatedField::AddNAlreadyReserved(int n) { + GOOGLE_DCHECK_GE(total_size_ - current_size_, n) + << total_size_ << ", " << current_size_; + // Warning: sometimes people call this when n==0 and total_size_==0. This + // forces us to add this branch, to avoid reading the non-active union member + // (which is UB). Luckily the compiler is smart enough to optimize the branch + // away. + Element* ret = + total_size_ == 0 ? reinterpret_cast(ptr_.arena) : ptr_.elements; + ret += current_size_; + current_size_ += n; return ret; } -template +template inline void RepeatedField::Resize(int new_size, const Element& value) { GOOGLE_DCHECK_GE(new_size, 0); if (new_size > current_size_) { Reserve(new_size); - std::fill(&rep()->elements[current_size_], - &rep()->elements[new_size], value); + std::fill(&elements()[current_size_], &elements()[new_size], value); } current_size_ = new_size; } @@ -1165,33 +1191,47 @@ template inline const Element& RepeatedField::Get(int index) const { GOOGLE_DCHECK_GE(index, 0); GOOGLE_DCHECK_LT(index, current_size_); - return rep()->elements[index]; + return elements()[index]; +} + +template +inline const Element& RepeatedField::at(int index) const { + GOOGLE_CHECK_GE(index, 0); + GOOGLE_CHECK_LT(index, current_size_); + return elements()[index]; +} + +template +inline Element& RepeatedField::at(int index) { + GOOGLE_CHECK_GE(index, 0); + GOOGLE_CHECK_LT(index, current_size_); + return elements()[index]; } template inline Element* RepeatedField::Mutable(int index) { GOOGLE_DCHECK_GE(index, 0); GOOGLE_DCHECK_LT(index, current_size_); - return &rep()->elements[index]; + return &elements()[index]; } template inline void RepeatedField::Set(int index, const Element& value) { GOOGLE_DCHECK_GE(index, 0); GOOGLE_DCHECK_LT(index, current_size_); - rep()->elements[index] = value; + elements()[index] = value; } template inline void RepeatedField::Add(const Element& value) { if (current_size_ == total_size_) Reserve(total_size_ + 1); - rep()->elements[current_size_++] = value; + elements()[current_size_++] = value; } template inline Element* RepeatedField::Add() { if (current_size_ == total_size_) Reserve(total_size_ + 1); - return &rep()->elements[current_size_++]; + return &elements()[current_size_++]; } template @@ -1201,16 +1241,15 @@ inline void RepeatedField::RemoveLast() { } template -void RepeatedField::ExtractSubrange( - int start, int num, Element* elements) { +void RepeatedField::ExtractSubrange(int start, int num, + Element* elements) { GOOGLE_DCHECK_GE(start, 0); GOOGLE_DCHECK_GE(num, 0); GOOGLE_DCHECK_LE(start + num, this->current_size_); // Save the values of the removed elements if requested. if (elements != NULL) { - for (int i = 0; i < num; ++i) - elements[i] = this->Get(i + start); + for (int i = 0; i < num; ++i) elements[i] = this->Get(i + start); } // Slide remaining elements down to fill the gap. @@ -1262,17 +1301,17 @@ inline typename RepeatedField::iterator RepeatedField::erase( template inline Element* RepeatedField::mutable_data() { - return total_size_ > 0 ? rep()->elements : NULL; + return total_size_ > 0 ? elements() : NULL; } template inline const Element* RepeatedField::data() const { - return total_size_ > 0 ? rep()->elements : NULL; + return total_size_ > 0 ? elements() : NULL; } template inline const Element* RepeatedField::unsafe_data() const { - return rep()->elements; + return elements(); } template @@ -1307,38 +1346,37 @@ void RepeatedField::UnsafeArenaSwap(RepeatedField* other) { template void RepeatedField::SwapElements(int index1, int index2) { using std::swap; // enable ADL with fallback - swap(rep()->elements[index1], rep()->elements[index2]); + swap(elements()[index1], elements()[index2]); } template inline typename RepeatedField::iterator RepeatedField::begin() { - return total_size_ > 0 ? rep()->elements : NULL; + return total_size_ > 0 ? elements() : NULL; } template inline typename RepeatedField::const_iterator RepeatedField::begin() const { - return total_size_ > 0 ? rep()->elements : NULL; + return total_size_ > 0 ? elements() : NULL; } template inline typename RepeatedField::const_iterator RepeatedField::cbegin() const { - return total_size_ > 0 ? rep()->elements : NULL; + return total_size_ > 0 ? elements() : NULL; } template -inline typename RepeatedField::iterator -RepeatedField::end() { - return total_size_ > 0 ? rep()->elements + current_size_ : NULL; +inline typename RepeatedField::iterator RepeatedField::end() { + return total_size_ > 0 ? elements() + current_size_ : NULL; } template inline typename RepeatedField::const_iterator RepeatedField::end() const { - return total_size_ > 0 ? rep()->elements + current_size_ : NULL; + return total_size_ > 0 ? elements() + current_size_ : NULL; } template inline typename RepeatedField::const_iterator RepeatedField::cend() const { - return total_size_ > 0 ? rep()->elements + current_size_ : NULL; + return total_size_ > 0 ? elements() + current_size_ : NULL; } template @@ -1352,23 +1390,25 @@ template void RepeatedField::Reserve(int new_size) { if (total_size_ >= new_size) return; Rep* old_rep = total_size_ > 0 ? rep() : NULL; + Rep* new_rep; Arena* arena = GetArenaNoVirtual(); - new_size = std::max(google::protobuf::internal::kMinRepeatedFieldAllocationSize, + new_size = std::max(internal::kMinRepeatedFieldAllocationSize, std::max(total_size_ * 2, new_size)); GOOGLE_DCHECK_LE( static_cast(new_size), (std::numeric_limits::max() - kRepHeaderSize) / sizeof(Element)) << "Requested size is too large to fit into size_t."; - size_t bytes = kRepHeaderSize + sizeof(Element) * static_cast(new_size); + size_t bytes = + kRepHeaderSize + sizeof(Element) * static_cast(new_size); if (arena == NULL) { - ptr_.rep = static_cast(::operator new(bytes)); + new_rep = static_cast(::operator new(bytes)); } else { - ptr_.rep = reinterpret_cast( - ::google::protobuf::Arena::CreateArray(arena, bytes)); + new_rep = reinterpret_cast(Arena::CreateArray(arena, bytes)); } - ptr_.rep->arena = arena; + new_rep->arena = arena; int old_total_size = total_size_; total_size_ = new_size; + ptr_.elements = new_rep->elements; // Invoke placement-new on newly allocated elements. We shouldn't have to do // this, since Element is supposed to be POD, but a previous version of this // code allocated storage with "new Element[size]" and some code uses @@ -1378,13 +1418,13 @@ void RepeatedField::Reserve(int new_size) { // effect unless its side-effects are required for correctness. // Note that we do this before MoveArray() below because Element's copy // assignment implementation will want an initialized instance first. - Element* e = &rep()->elements[0]; + Element* e = &elements()[0]; Element* limit = e + total_size_; for (; e < limit; e++) { new (e) Element; } if (current_size_ > 0) { - MoveArray(&rep()->elements[0], old_rep->elements, current_size_); + MoveArray(&elements()[0], old_rep->elements, current_size_); } // Likewise, we need to invoke destructors on the old array. @@ -1401,22 +1441,23 @@ inline void RepeatedField::Truncate(int new_size) { } template -inline void RepeatedField::MoveArray( - Element* to, Element* from, int array_size) { +inline void RepeatedField::MoveArray(Element* to, Element* from, + int array_size) { CopyArray(to, from, array_size); } template -inline void RepeatedField::CopyArray( - Element* to, const Element* from, int array_size) { +inline void RepeatedField::CopyArray(Element* to, const Element* from, + int array_size) { internal::ElementCopier()(to, from, array_size); } namespace internal { template -void ElementCopier::operator()( - Element* to, const Element* from, int array_size) { +void ElementCopier::operator()(Element* to, + const Element* from, + int array_size) { std::copy(from, from + array_size, to); } @@ -1435,18 +1476,10 @@ struct ElementCopier { namespace internal { inline RepeatedPtrFieldBase::RepeatedPtrFieldBase() - : arena_(NULL), - current_size_(0), - total_size_(0), - rep_(NULL) { -} + : arena_(NULL), current_size_(0), total_size_(0), rep_(NULL) {} -inline RepeatedPtrFieldBase::RepeatedPtrFieldBase(::google::protobuf::Arena* arena) - : arena_(arena), - current_size_(0), - total_size_(0), - rep_(NULL) { -} +inline RepeatedPtrFieldBase::RepeatedPtrFieldBase(Arena* arena) + : arena_(arena), current_size_(0), total_size_(0), rep_(NULL) {} template void RepeatedPtrFieldBase::Destroy() { @@ -1491,25 +1524,35 @@ void RepeatedPtrFieldBase::SwapFallback(RepeatedPtrFieldBase* other) { temp.Destroy(); // Frees rep_ if `other` had no arena. } -inline bool RepeatedPtrFieldBase::empty() const { - return current_size_ == 0; -} +inline bool RepeatedPtrFieldBase::empty() const { return current_size_ == 0; } -inline int RepeatedPtrFieldBase::size() const { - return current_size_; -} +inline int RepeatedPtrFieldBase::size() const { return current_size_; } template -inline const typename TypeHandler::WeakType& -RepeatedPtrFieldBase::Get(int index) const { +inline const typename TypeHandler::WeakType& RepeatedPtrFieldBase::Get( + int index) const { GOOGLE_DCHECK_GE(index, 0); GOOGLE_DCHECK_LT(index, current_size_); return *cast(rep_->elements[index]); } template -inline typename TypeHandler::Type* -RepeatedPtrFieldBase::Mutable(int index) { +inline const typename TypeHandler::Type& RepeatedPtrFieldBase::at( + int index) const { + GOOGLE_CHECK_GE(index, 0); + GOOGLE_CHECK_LT(index, current_size_); + return *cast(rep_->elements[index]); +} + +template +inline typename TypeHandler::Type& RepeatedPtrFieldBase::at(int index) { + GOOGLE_CHECK_GE(index, 0); + GOOGLE_CHECK_LT(index, current_size_); + return *cast(rep_->elements[index]); +} + +template +inline typename TypeHandler::Type* RepeatedPtrFieldBase::Mutable(int index) { GOOGLE_DCHECK_GE(index, 0); GOOGLE_DCHECK_LT(index, current_size_); return cast(rep_->elements[index]); @@ -1538,10 +1581,9 @@ inline typename TypeHandler::Type* RepeatedPtrFieldBase::Add( return result; } -template -inline void RepeatedPtrFieldBase::Add( - typename TypeHandler::Type&& value, - std::enable_if*) { +template ::type*> +inline void RepeatedPtrFieldBase::Add(typename TypeHandler::Type&& value) { if (rep_ != NULL && current_size_ < rep_->allocated_size) { *cast(rep_->elements[current_size_++]) = std::move(value); return; @@ -1585,8 +1627,8 @@ template inline void RepeatedPtrFieldBase::MergeFrom(const RepeatedPtrFieldBase& other) { GOOGLE_DCHECK_NE(&other, this); if (other.current_size_ == 0) return; - MergeFromInternal( - other, &RepeatedPtrFieldBase::MergeFromInnerLoop); + MergeFromInternal(other, + &RepeatedPtrFieldBase::MergeFromInnerLoop); } inline void RepeatedPtrFieldBase::MergeFromInternal( @@ -1597,8 +1639,8 @@ inline void RepeatedPtrFieldBase::MergeFromInternal( void** other_elements = other.rep_->elements; void** new_elements = InternalExtend(other_size); int allocated_elems = rep_->allocated_size - current_size_; - (this->*inner_loop)(new_elements, other_elements, - other_size, allocated_elems); + (this->*inner_loop)(new_elements, other_elements, other_size, + allocated_elems); current_size_ += other_size; if (rep_->allocated_size < current_size_) { rep_->allocated_size = current_size_; @@ -1606,9 +1648,10 @@ inline void RepeatedPtrFieldBase::MergeFromInternal( } // Merges other_elems to our_elems. -template -void RepeatedPtrFieldBase::MergeFromInnerLoop( - void** our_elems, void** other_elems, int length, int already_allocated) { +template +void RepeatedPtrFieldBase::MergeFromInnerLoop(void** our_elems, + void** other_elems, int length, + int already_allocated) { // Split into two loops, over ranges [0, allocated) and [allocated, length), // to avoid a branch within the loop. for (int i = 0; i < already_allocated && i < length; i++) { @@ -1638,9 +1681,7 @@ inline void RepeatedPtrFieldBase::CopyFrom(const RepeatedPtrFieldBase& other) { RepeatedPtrFieldBase::MergeFrom(other); } -inline int RepeatedPtrFieldBase::Capacity() const { - return total_size_; -} +inline int RepeatedPtrFieldBase::Capacity() const { return total_size_; } inline void* const* RepeatedPtrFieldBase::raw_data() const { return rep_ ? rep_->elements : NULL; @@ -1658,8 +1699,8 @@ inline typename TypeHandler::Type** RepeatedPtrFieldBase::mutable_data() { } template -inline const typename TypeHandler::Type* const* -RepeatedPtrFieldBase::data() const { +inline const typename TypeHandler::Type* const* RepeatedPtrFieldBase::data() + const { // TODO(kenton): Breaks C++ aliasing rules. We should probably remove this // method entirely. return reinterpret_cast(raw_data()); @@ -1675,8 +1716,8 @@ inline size_t RepeatedPtrFieldBase::SpaceUsedExcludingSelfLong() const { size_t allocated_bytes = static_cast(total_size_) * sizeof(void*); if (rep_ != NULL) { for (int i = 0; i < rep_->allocated_size; ++i) { - allocated_bytes += TypeHandler::SpaceUsedLong( - *cast(rep_->elements[i])); + allocated_bytes += + TypeHandler::SpaceUsedLong(*cast(rep_->elements[i])); } allocated_bytes += kRepHeaderSize; } @@ -1695,13 +1736,11 @@ inline typename TypeHandler::Type* RepeatedPtrFieldBase::AddFromCleared() { // AddAllocated version that implements arena-safe copying behavior. template void RepeatedPtrFieldBase::AddAllocatedInternal( - typename TypeHandler::Type* value, - std::true_type) { - Arena* element_arena = reinterpret_cast( - TypeHandler::GetMaybeArenaPointer(value)); + typename TypeHandler::Type* value, std::true_type) { + Arena* element_arena = + reinterpret_cast(TypeHandler::GetMaybeArenaPointer(value)); Arena* arena = GetArenaNoVirtual(); - if (arena == element_arena && rep_ && - rep_->allocated_size < total_size_) { + if (arena == element_arena && rep_ && rep_->allocated_size < total_size_) { // Fast path: underlying arena representation (tagged pointer) is equal to // our arena pointer, and we can add to array without resizing it (at least // one slot that is not allocated). @@ -1715,13 +1754,13 @@ void RepeatedPtrFieldBase::AddAllocatedInternal( current_size_ = current_size_ + 1; rep_->allocated_size = rep_->allocated_size + 1; } else { - AddAllocatedSlowWithCopy( - value, TypeHandler::GetArena(value), arena); + AddAllocatedSlowWithCopy(value, TypeHandler::GetArena(value), + arena); } } // Slowpath handles all cases, copying if necessary. -template +template void RepeatedPtrFieldBase::AddAllocatedSlowWithCopy( // Pass value_arena and my_arena to avoid duplicate virtual call (value) or // load (mine). @@ -1745,9 +1784,8 @@ void RepeatedPtrFieldBase::AddAllocatedSlowWithCopy( // AddAllocated version that does not implement arena-safe copying behavior. template void RepeatedPtrFieldBase::AddAllocatedInternal( - typename TypeHandler::Type* value, - std::false_type) { - if (rep_ && rep_->allocated_size < total_size_) { + typename TypeHandler::Type* value, std::false_type) { + if (rep_ && rep_->allocated_size < total_size_) { // Fast path: underlying arena representation (tagged pointer) is equal to // our arena pointer, and we can add to array without resizing it (at least // one slot that is not allocated). @@ -1778,8 +1816,8 @@ void RepeatedPtrFieldBase::UnsafeArenaAddAllocated( // cleared objects awaiting reuse. We don't want to grow the array in this // case because otherwise a loop calling AddAllocated() followed by Clear() // would leak memory. - TypeHandler::Delete( - cast(rep_->elements[current_size_]), arena_); + TypeHandler::Delete(cast(rep_->elements[current_size_]), + arena_); } else if (current_size_ < rep_->allocated_size) { // We have some cleared objects. We don't care about their order, so we // can just move the first one to the end to make space. @@ -1795,8 +1833,8 @@ void RepeatedPtrFieldBase::UnsafeArenaAddAllocated( // ReleaseLast() for types that implement merge/copy behavior. template -inline typename TypeHandler::Type* -RepeatedPtrFieldBase::ReleaseLastInternal(std::true_type) { +inline typename TypeHandler::Type* RepeatedPtrFieldBase::ReleaseLastInternal( + std::true_type) { // First, release an element. typename TypeHandler::Type* result = UnsafeArenaReleaseLast(); // Now perform a copy if we're on an arena. @@ -1816,8 +1854,8 @@ RepeatedPtrFieldBase::ReleaseLastInternal(std::true_type) { // an arena, since the user really should implement the copy operation in this // case. template -inline typename TypeHandler::Type* -RepeatedPtrFieldBase::ReleaseLastInternal(std::false_type) { +inline typename TypeHandler::Type* RepeatedPtrFieldBase::ReleaseLastInternal( + std::false_type) { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL) << "ReleaseLast() called on a RepeatedPtrField that is on an arena, " << "with a type that does not implement MergeFrom. This is unsafe; " @@ -1827,7 +1865,7 @@ RepeatedPtrFieldBase::ReleaseLastInternal(std::false_type) { template inline typename TypeHandler::Type* - RepeatedPtrFieldBase::UnsafeArenaReleaseLast() { +RepeatedPtrFieldBase::UnsafeArenaReleaseLast() { GOOGLE_DCHECK_GT(current_size_, 0); typename TypeHandler::Type* result = cast(rep_->elements[--current_size_]); @@ -1874,33 +1912,30 @@ inline typename TypeHandler::Type* RepeatedPtrFieldBase::ReleaseCleared() { template class RepeatedPtrField::TypeHandler - : public internal::GenericTypeHandler { -}; + : public internal::GenericTypeHandler {}; template <> -class RepeatedPtrField::TypeHandler - : public internal::StringTypeHandler { -}; +class RepeatedPtrField::TypeHandler + : public internal::StringTypeHandler {}; template -inline RepeatedPtrField::RepeatedPtrField() - : RepeatedPtrFieldBase() {} +inline RepeatedPtrField::RepeatedPtrField() : RepeatedPtrFieldBase() {} template -inline RepeatedPtrField::RepeatedPtrField(::google::protobuf::Arena* arena) : - RepeatedPtrFieldBase(arena) {} +inline RepeatedPtrField::RepeatedPtrField(Arena* arena) + : RepeatedPtrFieldBase(arena) {} template inline RepeatedPtrField::RepeatedPtrField( const RepeatedPtrField& other) - : RepeatedPtrFieldBase() { + : RepeatedPtrFieldBase() { MergeFrom(other); } template template -inline RepeatedPtrField::RepeatedPtrField( - Iter begin, const Iter& end) { +inline RepeatedPtrField::RepeatedPtrField(Iter begin, + const Iter& end) { int reserve = internal::CalculateReserve(begin, end); if (reserve != -1) { Reserve(reserve); @@ -1918,8 +1953,7 @@ RepeatedPtrField::~RepeatedPtrField() { template inline RepeatedPtrField& RepeatedPtrField::operator=( const RepeatedPtrField& other) { - if (this != &other) - CopyFrom(other); + if (this != &other) CopyFrom(other); return *this; } @@ -1928,7 +1962,8 @@ inline RepeatedPtrField::RepeatedPtrField( RepeatedPtrField&& other) noexcept : RepeatedPtrField() { // We don't just call Swap(&other) here because it would perform 3 copies if - // the two fields are on different arenas. + // other is on an arena. This field can't be on an arena because arena + // construction always uses the Arena* accepting constructor. if (other.GetArenaNoVirtual()) { CopyFrom(other); } else { @@ -1966,6 +2001,16 @@ inline const Element& RepeatedPtrField::Get(int index) const { return RepeatedPtrFieldBase::Get(index); } +template +inline const Element& RepeatedPtrField::at(int index) const { + return RepeatedPtrFieldBase::at(index); +} + +template +inline Element& RepeatedPtrField::at(int index) { + return RepeatedPtrFieldBase::at(index); +} + template inline Element* RepeatedPtrField::Mutable(int index) { @@ -1999,8 +2044,8 @@ inline void RepeatedPtrField::DeleteSubrange(int start, int num) { } template -inline void RepeatedPtrField::ExtractSubrange( - int start, int num, Element** elements) { +inline void RepeatedPtrField::ExtractSubrange(int start, int num, + Element** elements) { typename internal::TypeImplementsMergeBehavior< typename TypeHandler::Type>::type t; ExtractSubrangeInternal(start, num, elements, t); @@ -2022,8 +2067,8 @@ inline void RepeatedPtrField::ExtractSubrangeInternal( // If we're on an arena, we perform a copy for each element so that the // returned elements are heap-allocated. for (int i = 0; i < num; ++i) { - Element* element = RepeatedPtrFieldBase:: - Mutable(i + start); + Element* element = + RepeatedPtrFieldBase::Mutable(i + start); typename TypeHandler::Type* new_value = TypeHandler::NewFromPrototype(element, NULL); TypeHandler::Merge(*element, new_value); @@ -2041,7 +2086,7 @@ inline void RepeatedPtrField::ExtractSubrangeInternal( // ExtractSubrange() implementation for types that do not implement merge/copy // behavior. -template +template inline void RepeatedPtrField::ExtractSubrangeInternal( int start, int num, Element** elements, std::false_type) { // This case is identical to UnsafeArenaExtractSubrange(). However, since @@ -2084,8 +2129,7 @@ inline void RepeatedPtrField::MergeFrom( } template -inline void RepeatedPtrField::CopyFrom( - const RepeatedPtrField& other) { +inline void RepeatedPtrField::CopyFrom(const RepeatedPtrField& other) { RepeatedPtrFieldBase::CopyFrom(other); } @@ -2116,16 +2160,14 @@ inline const Element* const* RepeatedPtrField::data() const { template inline void RepeatedPtrField::Swap(RepeatedPtrField* other) { - if (this == other) - return; + if (this == other) return; RepeatedPtrFieldBase::Swap(other); } template inline void RepeatedPtrField::UnsafeArenaSwap( RepeatedPtrField* other) { - if (this == other) - return; + if (this == other) return; RepeatedPtrFieldBase::InternalSwap(other); } @@ -2204,31 +2246,22 @@ namespace internal { // // This code based on net/proto/proto-array-internal.h by Jeffrey Yasskin // (jyasskin@google.com). -template -class RepeatedPtrIterator - : public std::iterator< - std::random_access_iterator_tag, Element> { +template +class RepeatedPtrIterator { public: - typedef RepeatedPtrIterator iterator; - typedef std::iterator< - std::random_access_iterator_tag, Element> superclass; - - // Shadow the value_type in std::iterator<> because const_iterator::value_type - // needs to be T, not const T. - typedef typename std::remove_const::type value_type; - - // Let the compiler know that these are type names, so we don't have to - // write "typename" in front of them everywhere. - typedef typename superclass::reference reference; - typedef typename superclass::pointer pointer; - typedef typename superclass::difference_type difference_type; + using iterator = RepeatedPtrIterator; + using iterator_category = std::random_access_iterator_tag; + using value_type = typename std::remove_const::type; + using difference_type = std::ptrdiff_t; + using pointer = Element*; + using reference = Element&; RepeatedPtrIterator() : it_(NULL) {} explicit RepeatedPtrIterator(void* const* it) : it_(it) {} // Allow "upcasting" from RepeatedPtrIterator to // RepeatedPtrIterator. - template + template RepeatedPtrIterator(const RepeatedPtrIterator& other) : it_(other.it_) { // Force a compiler error if the other type is not convertible to ours. @@ -2239,13 +2272,19 @@ class RepeatedPtrIterator // dereferenceable reference operator*() const { return *reinterpret_cast(*it_); } - pointer operator->() const { return &(operator*()); } + pointer operator->() const { return &(operator*()); } // {inc,dec}rementable - iterator& operator++() { ++it_; return *this; } - iterator operator++(int) { return iterator(it_++); } - iterator& operator--() { --it_; return *this; } - iterator operator--(int) { return iterator(it_--); } + iterator& operator++() { + ++it_; + return *this; + } + iterator operator++(int) { return iterator(it_++); } + iterator& operator--() { + --it_; + return *this; + } + iterator operator--(int) { return iterator(it_--); } // equality_comparable bool operator==(const iterator& x) const { return it_ == x.it_; } @@ -2286,7 +2325,7 @@ class RepeatedPtrIterator difference_type operator-(const iterator& x) const { return it_ - x.it_; } private: - template + template friend class RepeatedPtrIterator; // The internal iterator. @@ -2301,34 +2340,33 @@ class RepeatedPtrIterator // referenced by the iterator. It should either be "void *" for a mutable // iterator, or "const void* const" for a constant iterator. template -class RepeatedPtrOverPtrsIterator - : public std::iterator { +class RepeatedPtrOverPtrsIterator { public: - typedef RepeatedPtrOverPtrsIterator iterator; - typedef std::iterator superclass; - - // Shadow the value_type in std::iterator<> because const_iterator::value_type - // needs to be T, not const T. - typedef typename std::remove_const::type value_type; - - // Let the compiler know that these are type names, so we don't have to - // write "typename" in front of them everywhere. - typedef typename superclass::reference reference; - typedef typename superclass::pointer pointer; - typedef typename superclass::difference_type difference_type; + using iterator = RepeatedPtrOverPtrsIterator; + using iterator_category = std::random_access_iterator_tag; + using value_type = typename std::remove_const::type; + using difference_type = std::ptrdiff_t; + using pointer = Element*; + using reference = Element&; RepeatedPtrOverPtrsIterator() : it_(NULL) {} explicit RepeatedPtrOverPtrsIterator(VoidPtr* it) : it_(it) {} // dereferenceable reference operator*() const { return *reinterpret_cast(it_); } - pointer operator->() const { return &(operator*()); } + pointer operator->() const { return &(operator*()); } // {inc,dec}rementable - iterator& operator++() { ++it_; return *this; } - iterator operator++(int) { return iterator(it_++); } - iterator& operator--() { --it_; return *this; } - iterator operator--(int) { return iterator(it_--); } + iterator& operator++() { + ++it_; + return *this; + } + iterator operator++(int) { return iterator(it_++); } + iterator& operator--() { + --it_; + return *this; + } + iterator operator--(int) { return iterator(it_--); } // equality_comparable bool operator==(const iterator& x) const { return it_ == x.it_; } @@ -2369,7 +2407,7 @@ class RepeatedPtrOverPtrsIterator difference_type operator-(const iterator& x) const { return it_ - x.it_; } private: - template + template friend class RepeatedPtrIterator; // The internal iterator. @@ -2440,35 +2478,30 @@ RepeatedPtrField::pointer_end() const { const_cast(raw_data() + size())); } - // Iterators and helper functions that follow the spirit of the STL // std::back_insert_iterator and std::back_inserter but are tailor-made // for RepeatedField and RepeatedPtrField. Typical usage would be: // // std::copy(some_sequence.begin(), some_sequence.end(), -// google::protobuf::RepeatedFieldBackInserter(proto.mutable_sequence())); +// RepeatedFieldBackInserter(proto.mutable_sequence())); // // Ported by johannes from util/gtl/proto-array-iterators.h namespace internal { // A back inserter for RepeatedField objects. -template class RepeatedFieldBackInsertIterator +template +class RepeatedFieldBackInsertIterator : public std::iterator { public: explicit RepeatedFieldBackInsertIterator( RepeatedField* const mutable_field) - : field_(mutable_field) { - } + : field_(mutable_field) {} RepeatedFieldBackInsertIterator& operator=(const T& value) { field_->Add(value); return *this; } - RepeatedFieldBackInsertIterator& operator*() { - return *this; - } - RepeatedFieldBackInsertIterator& operator++() { - return *this; - } + RepeatedFieldBackInsertIterator& operator*() { return *this; } + RepeatedFieldBackInsertIterator& operator++() { return *this; } RepeatedFieldBackInsertIterator& operator++(int /* unused */) { return *this; } @@ -2478,13 +2511,12 @@ template class RepeatedFieldBackInsertIterator }; // A back inserter for RepeatedPtrField objects. -template class RepeatedPtrFieldBackInsertIterator +template +class RepeatedPtrFieldBackInsertIterator : public std::iterator { public: - RepeatedPtrFieldBackInsertIterator( - RepeatedPtrField* const mutable_field) - : field_(mutable_field) { - } + RepeatedPtrFieldBackInsertIterator(RepeatedPtrField* const mutable_field) + : field_(mutable_field) {} RepeatedPtrFieldBackInsertIterator& operator=(const T& value) { *field_->Add() = value; return *this; @@ -2498,12 +2530,8 @@ template class RepeatedPtrFieldBackInsertIterator *field_->Add() = std::move(value); return *this; } - RepeatedPtrFieldBackInsertIterator& operator*() { - return *this; - } - RepeatedPtrFieldBackInsertIterator& operator++() { - return *this; - } + RepeatedPtrFieldBackInsertIterator& operator*() { return *this; } + RepeatedPtrFieldBackInsertIterator& operator++() { return *this; } RepeatedPtrFieldBackInsertIterator& operator++(int /* unused */) { return *this; } @@ -2514,26 +2542,21 @@ template class RepeatedPtrFieldBackInsertIterator // A back inserter for RepeatedPtrFields that inserts by transferring ownership // of a pointer. -template class AllocatedRepeatedPtrFieldBackInsertIterator +template +class AllocatedRepeatedPtrFieldBackInsertIterator : public std::iterator { public: explicit AllocatedRepeatedPtrFieldBackInsertIterator( RepeatedPtrField* const mutable_field) - : field_(mutable_field) { - } + : field_(mutable_field) {} AllocatedRepeatedPtrFieldBackInsertIterator& operator=( T* const ptr_to_value) { field_->AddAllocated(ptr_to_value); return *this; } - AllocatedRepeatedPtrFieldBackInsertIterator& operator*() { - return *this; - } - AllocatedRepeatedPtrFieldBackInsertIterator& operator++() { - return *this; - } - AllocatedRepeatedPtrFieldBackInsertIterator& operator++( - int /* unused */) { + AllocatedRepeatedPtrFieldBackInsertIterator& operator*() { return *this; } + AllocatedRepeatedPtrFieldBackInsertIterator& operator++() { return *this; } + AllocatedRepeatedPtrFieldBackInsertIterator& operator++(int /* unused */) { return *this; } @@ -2543,16 +2566,15 @@ template class AllocatedRepeatedPtrFieldBackInsertIterator // Almost identical to AllocatedRepeatedPtrFieldBackInsertIterator. This one // uses the UnsafeArenaAddAllocated instead. -template +template class UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator : public std::iterator { public: explicit UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator( - ::google::protobuf::RepeatedPtrField* const mutable_field) - : field_(mutable_field) { - } + RepeatedPtrField* const mutable_field) + : field_(mutable_field) {} UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator& operator=( - T const* const ptr_to_value) { + T const* const ptr_to_value) { field_->UnsafeArenaAddAllocated(const_cast(ptr_to_value)); return *this; } @@ -2568,37 +2590,41 @@ class UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator } private: - ::google::protobuf::RepeatedPtrField* field_; + RepeatedPtrField* field_; }; } // namespace internal // Provides a back insert iterator for RepeatedField instances, // similar to std::back_inserter(). -template internal::RepeatedFieldBackInsertIterator -RepeatedFieldBackInserter(RepeatedField* const mutable_field) { +template +internal::RepeatedFieldBackInsertIterator RepeatedFieldBackInserter( + RepeatedField* const mutable_field) { return internal::RepeatedFieldBackInsertIterator(mutable_field); } // Provides a back insert iterator for RepeatedPtrField instances, // similar to std::back_inserter(). -template internal::RepeatedPtrFieldBackInsertIterator -RepeatedPtrFieldBackInserter(RepeatedPtrField* const mutable_field) { +template +internal::RepeatedPtrFieldBackInsertIterator RepeatedPtrFieldBackInserter( + RepeatedPtrField* const mutable_field) { return internal::RepeatedPtrFieldBackInsertIterator(mutable_field); } // Special back insert iterator for RepeatedPtrField instances, just in // case someone wants to write generic template code that can access both // RepeatedFields and RepeatedPtrFields using a common name. -template internal::RepeatedPtrFieldBackInsertIterator -RepeatedFieldBackInserter(RepeatedPtrField* const mutable_field) { +template +internal::RepeatedPtrFieldBackInsertIterator RepeatedFieldBackInserter( + RepeatedPtrField* const mutable_field) { return internal::RepeatedPtrFieldBackInsertIterator(mutable_field); } // Provides a back insert iterator for RepeatedPtrField instances // similar to std::back_inserter() which transfers the ownership while // copying elements. -template internal::AllocatedRepeatedPtrFieldBackInsertIterator +template +internal::AllocatedRepeatedPtrFieldBackInsertIterator AllocatedRepeatedPtrFieldBackInserter( RepeatedPtrField* const mutable_field) { return internal::AllocatedRepeatedPtrFieldBackInsertIterator( @@ -2616,15 +2642,27 @@ AllocatedRepeatedPtrFieldBackInserter( // If you put temp_field on the arena this fails, because the ownership // transfers to the arena at the "AddAllocated" call and is not released anymore // causing a double delete. Using UnsafeArenaAddAllocated prevents this. -template +template internal::UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator UnsafeArenaAllocatedRepeatedPtrFieldBackInserter( - ::google::protobuf::RepeatedPtrField* const mutable_field) { + RepeatedPtrField* const mutable_field) { return internal::UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator( mutable_field); } -} // namespace protobuf +// Extern declarations of common instantiations to reduce libray bloat. +extern template class PROTOBUF_EXPORT RepeatedField; +extern template class PROTOBUF_EXPORT RepeatedField; +extern template class PROTOBUF_EXPORT RepeatedField; +extern template class PROTOBUF_EXPORT RepeatedField; +extern template class PROTOBUF_EXPORT RepeatedField; +extern template class PROTOBUF_EXPORT RepeatedField; +extern template class PROTOBUF_EXPORT RepeatedField; +extern template class PROTOBUF_EXPORT RepeatedPtrField; +} // namespace protobuf } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_REPEATED_FIELD_H__ diff --git a/third_party/protobuf/src/google/protobuf/repeated_field_reflection_unittest.cc b/third_party/protobuf/src/google/protobuf/repeated_field_reflection_unittest.cc index 74ec83b0..04991027 100644 --- a/third_party/protobuf/src/google/protobuf/repeated_field_reflection_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/repeated_field_reflection_unittest.cc @@ -35,9 +35,9 @@ #include #include -#include -#include #include +#include +#include #include #include @@ -45,17 +45,15 @@ namespace google { namespace protobuf { using unittest::ForeignMessage; -using unittest::TestAllTypes; using unittest::TestAllExtensions; +using unittest::TestAllTypes; namespace { -static int Func(int i, int j) { - return i * j; -} +static int Func(int i, int j) { return i * j; } -static string StrFunc(int i, int j) { - string str; +static std::string StrFunc(int i, int j) { + std::string str; SStringPrintf(&str, "%d", Func(i, 4)); return str; } @@ -95,24 +93,23 @@ TEST(RepeatedFieldReflectionTest, RegularFields) { refl->MutableRepeatedField(&message, fd_repeated_double); // Get RepeatedPtrField objects for all fields of interest. - const RepeatedPtrField& rpf_string = - refl->GetRepeatedPtrField(message, fd_repeated_string); + const RepeatedPtrField& rpf_string = + refl->GetRepeatedPtrField(message, fd_repeated_string); const RepeatedPtrField& rpf_foreign_message = - refl->GetRepeatedPtrField( - message, fd_repeated_foreign_message); + refl->GetRepeatedPtrField(message, + fd_repeated_foreign_message); const RepeatedPtrField& rpf_message = - refl->GetRepeatedPtrField( - message, fd_repeated_foreign_message); + refl->GetRepeatedPtrField(message, fd_repeated_foreign_message); // Get mutable RepeatedPtrField objects for all fields of interest. - RepeatedPtrField* mrpf_string = - refl->MutableRepeatedPtrField(&message, fd_repeated_string); + RepeatedPtrField* mrpf_string = + refl->MutableRepeatedPtrField(&message, fd_repeated_string); RepeatedPtrField* mrpf_foreign_message = refl->MutableRepeatedPtrField( &message, fd_repeated_foreign_message); RepeatedPtrField* mrpf_message = - refl->MutableRepeatedPtrField( - &message, fd_repeated_foreign_message); + refl->MutableRepeatedPtrField(&message, + fd_repeated_foreign_message); // Make sure we can do gets and sets through the Repeated[Ptr]Field objects. for (int i = 0; i < 10; ++i) { @@ -149,12 +146,13 @@ TEST(RepeatedFieldReflectionTest, RegularFields) { // Make sure types are checked correctly at runtime. const FieldDescriptor* fd_optional_int32 = desc->FindFieldByName("optional_int32"); - EXPECT_DEATH(refl->GetRepeatedField( - message, fd_optional_int32), "requires a repeated field"); - EXPECT_DEATH(refl->GetRepeatedField( - message, fd_repeated_int32), "not the right type"); + EXPECT_DEATH(refl->GetRepeatedField(message, fd_optional_int32), + "requires a repeated field"); + EXPECT_DEATH(refl->GetRepeatedField(message, fd_repeated_int32), + "not the right type"); EXPECT_DEATH(refl->GetRepeatedPtrField( - message, fd_repeated_foreign_message), "wrong submessage type"); + message, fd_repeated_foreign_message), + "wrong submessage type"); #endif // PROTOBUF_HAS_DEATH_TEST } @@ -165,8 +163,8 @@ TEST(RepeatedFieldReflectionTest, ExtensionFields) { const Descriptor* desc = extended_message.GetDescriptor(); for (int i = 0; i < 10; ++i) { - extended_message.AddExtension( - unittest::repeated_int64_extension, Func(i, 1)); + extended_message.AddExtension(unittest::repeated_int64_extension, + Func(i, 1)); } const FieldDescriptor* fd_repeated_int64_extension = @@ -177,15 +175,14 @@ TEST(RepeatedFieldReflectionTest, ExtensionFields) { refl->GetRepeatedField(extended_message, fd_repeated_int64_extension); - RepeatedField* mrf_int64_extension = - refl->MutableRepeatedField(&extended_message, - fd_repeated_int64_extension); + RepeatedField* mrf_int64_extension = refl->MutableRepeatedField( + &extended_message, fd_repeated_int64_extension); for (int i = 0; i < 10; ++i) { EXPECT_EQ(Func(i, 1), rf_int64_extension.Get(i)); mrf_int64_extension->Set(i, Func(i, -1)); - EXPECT_EQ(Func(i, -1), - extended_message.GetExtension(unittest::repeated_int64_extension, i)); + EXPECT_EQ(Func(i, -1), extended_message.GetExtension( + unittest::repeated_int64_extension, i)); } } @@ -194,8 +191,8 @@ void TestRepeatedFieldRefIteratorForPrimitive( const Ref& handle, const MessageType& message, ValueType (MessageType::*GetFunc)(int) const) { int index = 0; - for (typename Ref::const_iterator it = handle.begin(); - it != handle.end(); ++it) { + for (typename Ref::const_iterator it = handle.begin(); it != handle.end(); + ++it) { EXPECT_EQ((message.*GetFunc)(index), *it); ++index; } @@ -204,10 +201,11 @@ void TestRepeatedFieldRefIteratorForPrimitive( template void TestRepeatedFieldRefIteratorForString( - const RepeatedFieldRef& handle, const MessageType& message, + const RepeatedFieldRef& handle, const MessageType& message, ValueType (MessageType::*GetFunc)(int) const) { int index = 0; - for (typename RepeatedFieldRef::const_iterator it = handle.begin(); + for (typename RepeatedFieldRef::const_iterator it = + handle.begin(); it != handle.end(); ++it) { // Test both operator* and operator-> EXPECT_EQ((message.*GetFunc)(index), *it); @@ -244,28 +242,28 @@ TEST(RepeatedFieldReflectionTest, RepeatedFieldRefForRegularFields) { refl->GetRepeatedFieldRef(message, fd_repeated_int32); const RepeatedFieldRef rf_double = refl->GetRepeatedFieldRef(message, fd_repeated_double); - const RepeatedFieldRef rf_string = - refl->GetRepeatedFieldRef(message, fd_repeated_string); + const RepeatedFieldRef rf_string = + refl->GetRepeatedFieldRef(message, fd_repeated_string); const RepeatedFieldRef rf_foreign_message = - refl->GetRepeatedFieldRef( - message, fd_repeated_foreign_message); + refl->GetRepeatedFieldRef(message, + fd_repeated_foreign_message); const RepeatedFieldRef rf_message = - refl->GetRepeatedFieldRef( - message, fd_repeated_foreign_message); + refl->GetRepeatedFieldRef(message, fd_repeated_foreign_message); // Get MutableRepeatedFieldRef objects for all fields of interest. const MutableRepeatedFieldRef mrf_int32 = refl->GetMutableRepeatedFieldRef(&message, fd_repeated_int32); const MutableRepeatedFieldRef mrf_double = refl->GetMutableRepeatedFieldRef(&message, fd_repeated_double); - const MutableRepeatedFieldRef mrf_string = - refl->GetMutableRepeatedFieldRef(&message, fd_repeated_string); + const MutableRepeatedFieldRef mrf_string = + refl->GetMutableRepeatedFieldRef(&message, + fd_repeated_string); const MutableRepeatedFieldRef mrf_foreign_message = refl->GetMutableRepeatedFieldRef( &message, fd_repeated_foreign_message); const MutableRepeatedFieldRef mrf_message = - refl->GetMutableRepeatedFieldRef( - &message, fd_repeated_foreign_message); + refl->GetMutableRepeatedFieldRef(&message, + fd_repeated_foreign_message); EXPECT_EQ(message.repeated_int32_size(), rf_int32.size()); EXPECT_EQ(message.repeated_int32_size(), mrf_int32.size()); @@ -273,8 +271,7 @@ TEST(RepeatedFieldReflectionTest, RepeatedFieldRefForRegularFields) { EXPECT_EQ(message.repeated_double_size(), mrf_double.size()); EXPECT_EQ(message.repeated_string_size(), rf_string.size()); EXPECT_EQ(message.repeated_string_size(), mrf_string.size()); - EXPECT_EQ(message.repeated_foreign_message_size(), - rf_foreign_message.size()); + EXPECT_EQ(message.repeated_foreign_message_size(), rf_foreign_message.size()); EXPECT_EQ(message.repeated_foreign_message_size(), mrf_foreign_message.size()); EXPECT_EQ(message.repeated_foreign_message_size(), rf_message.size()); @@ -299,16 +296,19 @@ TEST(RepeatedFieldReflectionTest, RepeatedFieldRefForRegularFields) { EXPECT_EQ(rf_string.Get(i), StrFunc(i, 5)); ForeignMessage scratch_space; EXPECT_EQ(rf_foreign_message.Get(i, &scratch_space).c(), Func(i, 6)); - EXPECT_EQ(down_cast( - rf_message.Get(i, &scratch_space)).c(), Func(i, 6)); + EXPECT_EQ( + down_cast(rf_message.Get(i, &scratch_space)).c(), + Func(i, 6)); // Check gets through mutable objects. EXPECT_EQ(mrf_int32.Get(i), Func(i, 1)); EXPECT_EQ(mrf_double.Get(i), Func(i, 2)); EXPECT_EQ(mrf_string.Get(i), StrFunc(i, 5)); EXPECT_EQ(mrf_foreign_message.Get(i, &scratch_space).c(), Func(i, 6)); - EXPECT_EQ(down_cast( - mrf_message.Get(i, &scratch_space)).c(), Func(i, 6)); + EXPECT_EQ( + down_cast(mrf_message.Get(i, &scratch_space)) + .c(), + Func(i, 6)); // Check sets through mutable objects. mrf_int32.Set(i, Func(i, -1)); @@ -429,12 +429,13 @@ TEST(RepeatedFieldReflectionTest, RepeatedFieldRefForRegularFields) { // Make sure types are checked correctly at runtime. const FieldDescriptor* fd_optional_int32 = desc->FindFieldByName("optional_int32"); - EXPECT_DEATH(refl->GetRepeatedFieldRef( - message, fd_optional_int32), ""); - EXPECT_DEATH(refl->GetRepeatedFieldRef( - message, fd_repeated_int32), ""); + EXPECT_DEATH(refl->GetRepeatedFieldRef(message, fd_optional_int32), + ""); + EXPECT_DEATH(refl->GetRepeatedFieldRef(message, fd_repeated_int32), + ""); EXPECT_DEATH(refl->GetRepeatedFieldRef( - message, fd_repeated_foreign_message), ""); + message, fd_repeated_foreign_message), + ""); #endif // PROTOBUF_HAS_DEATH_TEST } @@ -453,16 +454,14 @@ TEST(RepeatedFieldReflectionTest, RepeatedFieldRefForEnums) { const RepeatedFieldRef enum_ref = refl->GetRepeatedFieldRef( message, fd_repeated_nested_enum); - const MutableRepeatedFieldRef - mutable_enum_ref = + const MutableRepeatedFieldRef mutable_enum_ref = refl->GetMutableRepeatedFieldRef( &message, fd_repeated_nested_enum); const RepeatedFieldRef int32_ref = - refl->GetRepeatedFieldRef( - message, fd_repeated_nested_enum); + refl->GetRepeatedFieldRef(message, fd_repeated_nested_enum); const MutableRepeatedFieldRef mutable_int32_ref = - refl->GetMutableRepeatedFieldRef( - &message, fd_repeated_nested_enum); + refl->GetMutableRepeatedFieldRef(&message, + fd_repeated_nested_enum); EXPECT_EQ(message.repeated_nested_enum_size(), enum_ref.size()); EXPECT_EQ(message.repeated_nested_enum_size(), mutable_enum_ref.size()); @@ -537,8 +536,8 @@ TEST(RepeatedFieldReflectionTest, RepeatedFieldRefForExtensionFields) { const Descriptor* desc = extended_message.GetDescriptor(); for (int i = 0; i < 10; ++i) { - extended_message.AddExtension( - unittest::repeated_int64_extension, Func(i, 1)); + extended_message.AddExtension(unittest::repeated_int64_extension, + Func(i, 1)); } const FieldDescriptor* fd_repeated_int64_extension = @@ -547,17 +546,17 @@ TEST(RepeatedFieldReflectionTest, RepeatedFieldRefForExtensionFields) { const RepeatedFieldRef rf_int64_extension = refl->GetRepeatedFieldRef(extended_message, - fd_repeated_int64_extension); + fd_repeated_int64_extension); const MutableRepeatedFieldRef mrf_int64_extension = refl->GetMutableRepeatedFieldRef(&extended_message, - fd_repeated_int64_extension); + fd_repeated_int64_extension); for (int i = 0; i < 10; ++i) { EXPECT_EQ(Func(i, 1), rf_int64_extension.Get(i)); mrf_int64_extension.Set(i, Func(i, -1)); - EXPECT_EQ(Func(i, -1), - extended_message.GetExtension(unittest::repeated_int64_extension, i)); + EXPECT_EQ(Func(i, -1), extended_message.GetExtension( + unittest::repeated_int64_extension, i)); } } @@ -603,29 +602,25 @@ TEST(RepeatedFieldReflectionTest, RepeatedFieldRefMergeFromAndSwap) { refl->GetMutableRepeatedFieldRef(&m0, fd_repeated_int32); const MutableRepeatedFieldRef mrf_double = refl->GetMutableRepeatedFieldRef(&m0, fd_repeated_double); - const MutableRepeatedFieldRef mrf_string = - refl->GetMutableRepeatedFieldRef(&m0, fd_repeated_string); + const MutableRepeatedFieldRef mrf_string = + refl->GetMutableRepeatedFieldRef(&m0, fd_repeated_string); const MutableRepeatedFieldRef mrf_foreign_message = refl->GetMutableRepeatedFieldRef( &m0, fd_repeated_foreign_message); - const MutableRepeatedFieldRef - mrf_nested_enum = + const MutableRepeatedFieldRef mrf_nested_enum = refl->GetMutableRepeatedFieldRef( &m0, fd_repeated_nested_enum); // Test MutableRepeatedRef::CopyFrom - mrf_int32.CopyFrom( - refl->GetRepeatedFieldRef(m1, fd_repeated_int32)); + mrf_int32.CopyFrom(refl->GetRepeatedFieldRef(m1, fd_repeated_int32)); mrf_double.CopyFrom( refl->GetRepeatedFieldRef(m1, fd_repeated_double)); mrf_string.CopyFrom( - refl->GetRepeatedFieldRef(m1, fd_repeated_string)); - mrf_foreign_message.CopyFrom( - refl->GetRepeatedFieldRef( - m1, fd_repeated_foreign_message)); - mrf_nested_enum.CopyFrom( - refl->GetRepeatedFieldRef( - m1, fd_repeated_nested_enum)); + refl->GetRepeatedFieldRef(m1, fd_repeated_string)); + mrf_foreign_message.CopyFrom(refl->GetRepeatedFieldRef( + m1, fd_repeated_foreign_message)); + mrf_nested_enum.CopyFrom(refl->GetRepeatedFieldRef( + m1, fd_repeated_nested_enum)); for (int i = 0; i < 10; ++i) { EXPECT_EQ(Func(i, 11), m0.repeated_int32(i)); EXPECT_EQ(Func(i, 12), m0.repeated_double(i)); @@ -635,18 +630,15 @@ TEST(RepeatedFieldReflectionTest, RepeatedFieldRefMergeFromAndSwap) { } // Test MutableRepeatedRef::MergeFrom - mrf_int32.MergeFrom( - refl->GetRepeatedFieldRef(m2, fd_repeated_int32)); + mrf_int32.MergeFrom(refl->GetRepeatedFieldRef(m2, fd_repeated_int32)); mrf_double.MergeFrom( refl->GetRepeatedFieldRef(m2, fd_repeated_double)); mrf_string.MergeFrom( - refl->GetRepeatedFieldRef(m2, fd_repeated_string)); - mrf_foreign_message.MergeFrom( - refl->GetRepeatedFieldRef( - m2, fd_repeated_foreign_message)); - mrf_nested_enum.MergeFrom( - refl->GetRepeatedFieldRef( - m2, fd_repeated_nested_enum)); + refl->GetRepeatedFieldRef(m2, fd_repeated_string)); + mrf_foreign_message.MergeFrom(refl->GetRepeatedFieldRef( + m2, fd_repeated_foreign_message)); + mrf_nested_enum.MergeFrom(refl->GetRepeatedFieldRef( + m2, fd_repeated_nested_enum)); for (int i = 0; i < 10; ++i) { EXPECT_EQ(Func(i, 21), m0.repeated_int32(i + 10)); EXPECT_EQ(Func(i, 22), m0.repeated_double(i + 10)); @@ -662,10 +654,9 @@ TEST(RepeatedFieldReflectionTest, RepeatedFieldRefMergeFromAndSwap) { mrf_double.Swap( refl->GetMutableRepeatedFieldRef(&m2, fd_repeated_double)); mrf_string.Swap( - refl->GetMutableRepeatedFieldRef(&m2, fd_repeated_string)); - mrf_foreign_message.Swap( - refl->GetMutableRepeatedFieldRef( - &m2, fd_repeated_foreign_message)); + refl->GetMutableRepeatedFieldRef(&m2, fd_repeated_string)); + mrf_foreign_message.Swap(refl->GetMutableRepeatedFieldRef( + &m2, fd_repeated_foreign_message)); mrf_nested_enum.Swap( refl->GetMutableRepeatedFieldRef( &m2, fd_repeated_nested_enum)); @@ -708,12 +699,12 @@ TEST(RepeatedFieldReflectionTest, RepeatedFieldRefDynamicMessage) { const Reflection* refl = dynamic_message->GetReflection(); MutableRepeatedFieldRef rf_int32 = - refl->GetMutableRepeatedFieldRef( - dynamic_message.get(), fd_repeated_int32); + refl->GetMutableRepeatedFieldRef(dynamic_message.get(), + fd_repeated_int32); rf_int32.Add(1234); EXPECT_EQ(1, refl->FieldSize(*dynamic_message, fd_repeated_int32)); - EXPECT_EQ(1234, refl->GetRepeatedInt32(*dynamic_message, - fd_repeated_int32, 0)); + EXPECT_EQ(1234, + refl->GetRepeatedInt32(*dynamic_message, fd_repeated_int32, 0)); } } // namespace diff --git a/third_party/protobuf/src/google/protobuf/repeated_field_unittest.cc b/third_party/protobuf/src/google/protobuf/repeated_field_unittest.cc index 053a4d68..610cb91d 100644 --- a/third_party/protobuf/src/google/protobuf/repeated_field_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/repeated_field_unittest.cc @@ -38,6 +38,7 @@ #include #include #include +#include #include #include @@ -45,10 +46,11 @@ #include #include #include +#include #include #include #include -#include + #include namespace google { @@ -70,26 +72,41 @@ TEST(RepeatedField, Small) { EXPECT_FALSE(field.empty()); EXPECT_EQ(field.size(), 1); EXPECT_EQ(field.Get(0), 5); + EXPECT_EQ(field.at(0), 5); field.Add(42); EXPECT_FALSE(field.empty()); EXPECT_EQ(field.size(), 2); EXPECT_EQ(field.Get(0), 5); + EXPECT_EQ(field.at(0), 5); EXPECT_EQ(field.Get(1), 42); + EXPECT_EQ(field.at(1), 42); field.Set(1, 23); EXPECT_FALSE(field.empty()); EXPECT_EQ(field.size(), 2); EXPECT_EQ(field.Get(0), 5); + EXPECT_EQ(field.at(0), 5); EXPECT_EQ(field.Get(1), 23); + EXPECT_EQ(field.at(1), 23); + + field.at(1) = 25; + + EXPECT_FALSE(field.empty()); + EXPECT_EQ(field.size(), 2); + EXPECT_EQ(field.Get(0), 5); + EXPECT_EQ(field.at(0), 5); + EXPECT_EQ(field.Get(1), 25); + EXPECT_EQ(field.at(1), 25); field.RemoveLast(); EXPECT_FALSE(field.empty()); EXPECT_EQ(field.size(), 1); EXPECT_EQ(field.Get(0), 5); + EXPECT_EQ(field.at(0), 5); field.Clear(); @@ -340,6 +357,9 @@ TEST(RepeatedField, CopyConstruct) { TEST(RepeatedField, IteratorConstruct) { std::vector values; + RepeatedField empty(values.begin(), values.end()); + ASSERT_EQ(values.size(), empty.size()); + values.push_back(1); values.push_back(2); @@ -515,6 +535,48 @@ TEST(RepeatedField, MoveAssign) { } } +TEST(Movable, Works) { + class NonMoveConstructible { + public: + NonMoveConstructible(NonMoveConstructible&&) = delete; + NonMoveConstructible& operator=(NonMoveConstructible&&) { return *this; } + }; + class NonMoveAssignable { + public: + NonMoveAssignable(NonMoveAssignable&&) {} + NonMoveAssignable& operator=(NonMoveConstructible&&) = delete; + }; + class NonMovable { + public: + NonMovable(NonMovable&&) = delete; + NonMovable& operator=(NonMovable&&) = delete; + }; + + EXPECT_TRUE(internal::IsMovable::value); + + EXPECT_FALSE(std::is_move_constructible::value); + EXPECT_TRUE(std::is_move_assignable::value); + EXPECT_FALSE(internal::IsMovable::value); + + EXPECT_TRUE(std::is_move_constructible::value); + EXPECT_FALSE(std::is_move_assignable::value); + EXPECT_FALSE(internal::IsMovable::value); + + EXPECT_FALSE(internal::IsMovable::value); +} + +TEST(RepeatedField, MoveAdd) { + RepeatedPtrField field; + TestAllTypes test_all_types; + auto* optional_nested_message = + test_all_types.mutable_optional_nested_message(); + optional_nested_message->set_bb(42); + field.Add(std::move(test_all_types)); + + EXPECT_EQ(optional_nested_message, + field.Mutable(0)->mutable_optional_nested_message()); +} + TEST(RepeatedField, MutableDataIsMutable) { RepeatedField field; field.Add(1); @@ -567,27 +629,23 @@ TEST(RepeatedField, ExtractSubrange) { for (int start = 0; start < sz - num; ++start) { // Create RepeatedField with sz elements having values 0 through sz-1. RepeatedField field; - for (int i = 0; i < sz; ++i) - field.Add(i); + for (int i = 0; i < sz; ++i) field.Add(i); EXPECT_EQ(field.size(), sz); // Create a catcher array and call ExtractSubrange. int32 catcher[10]; - for (int i = 0; i < 10; ++i) - catcher[i] = -1; + for (int i = 0; i < 10; ++i) catcher[i] = -1; field.ExtractSubrange(start, num, catcher); // Does the resulting array have the right size? EXPECT_EQ(field.size(), sz - num); // Were the removed elements extracted into the catcher array? - for (int i = 0; i < num; ++i) - EXPECT_EQ(catcher[i], start + i); + for (int i = 0; i < num; ++i) EXPECT_EQ(catcher[i], start + i); EXPECT_EQ(catcher[num], -1); // Does the resulting array contain the right values? - for (int i = 0; i < start; ++i) - EXPECT_EQ(field.Get(i), i); + for (int i = 0; i < start; ++i) EXPECT_EQ(field.Get(i), i); for (int i = start; i < field.size(); ++i) EXPECT_EQ(field.Get(i), i + num); } @@ -601,9 +659,9 @@ TEST(RepeatedField, ClearThenReserveMore) { // present. Use a 'string' and > 16 bytes length so that the elements are // non-POD and allocate -- the leak checker will catch any skipped destructor // calls here. - RepeatedField field; + RepeatedField field; for (int i = 0; i < 32; i++) { - field.Add(string("abcdefghijklmnopqrstuvwxyz0123456789")); + field.Add(std::string("abcdefghijklmnopqrstuvwxyz0123456789")); } EXPECT_EQ(32, field.size()); field.Clear(); @@ -622,7 +680,7 @@ TEST(RepeatedField, ClearThenReserveMore) { // tests above. TEST(RepeatedPtrField, Small) { - RepeatedPtrField field; + RepeatedPtrField field; EXPECT_TRUE(field.empty()); EXPECT_EQ(field.size(), 0); @@ -632,26 +690,32 @@ TEST(RepeatedPtrField, Small) { EXPECT_FALSE(field.empty()); EXPECT_EQ(field.size(), 1); EXPECT_EQ(field.Get(0), "foo"); + EXPECT_EQ(field.at(0), "foo"); field.Add()->assign("bar"); EXPECT_FALSE(field.empty()); EXPECT_EQ(field.size(), 2); EXPECT_EQ(field.Get(0), "foo"); + EXPECT_EQ(field.at(0), "foo"); EXPECT_EQ(field.Get(1), "bar"); + EXPECT_EQ(field.at(1), "bar"); field.Mutable(1)->assign("baz"); EXPECT_FALSE(field.empty()); EXPECT_EQ(field.size(), 2); EXPECT_EQ(field.Get(0), "foo"); + EXPECT_EQ(field.at(0), "foo"); EXPECT_EQ(field.Get(1), "baz"); + EXPECT_EQ(field.at(1), "baz"); field.RemoveLast(); EXPECT_FALSE(field.empty()); EXPECT_EQ(field.size(), 1); EXPECT_EQ(field.Get(0), "foo"); + EXPECT_EQ(field.at(0), "foo"); field.Clear(); @@ -660,7 +724,7 @@ TEST(RepeatedPtrField, Small) { } TEST(RepeatedPtrField, Large) { - RepeatedPtrField field; + RepeatedPtrField field; for (int i = 0; i < 16; i++) { *field.Add() += 'a' + i; @@ -673,13 +737,13 @@ TEST(RepeatedPtrField, Large) { EXPECT_EQ(field.Get(i)[0], 'a' + i); } - int min_expected_usage = 16 * sizeof(string); + int min_expected_usage = 16 * sizeof(std::string); EXPECT_GE(field.SpaceUsedExcludingSelf(), min_expected_usage); } TEST(RepeatedPtrField, SwapSmallSmall) { - RepeatedPtrField field1; - RepeatedPtrField field2; + RepeatedPtrField field1; + RepeatedPtrField field2; EXPECT_TRUE(field1.empty()); EXPECT_EQ(field1.size(), 0); @@ -708,8 +772,8 @@ TEST(RepeatedPtrField, SwapSmallSmall) { } TEST(RepeatedPtrField, SwapLargeSmall) { - RepeatedPtrField field1; - RepeatedPtrField field2; + RepeatedPtrField field1; + RepeatedPtrField field2; field2.Add()->assign("foo"); field2.Add()->assign("bar"); @@ -729,8 +793,8 @@ TEST(RepeatedPtrField, SwapLargeSmall) { } TEST(RepeatedPtrField, SwapLargeLarge) { - RepeatedPtrField field1; - RepeatedPtrField field2; + RepeatedPtrField field1; + RepeatedPtrField field2; field1.Add()->assign("foo"); field1.Add()->assign("bar"); @@ -754,8 +818,8 @@ TEST(RepeatedPtrField, SwapLargeLarge) { } } -static int ReservedSpace(RepeatedPtrField* field) { - const string* const* ptr = field->data(); +static int ReservedSpace(RepeatedPtrField* field) { + const std::string* const* ptr = field->data(); do { field->Add(); } while (field->data() == ptr); @@ -764,14 +828,14 @@ static int ReservedSpace(RepeatedPtrField* field) { } TEST(RepeatedPtrField, ReserveMoreThanDouble) { - RepeatedPtrField field; + RepeatedPtrField field; field.Reserve(20); EXPECT_LE(20, ReservedSpace(&field)); } TEST(RepeatedPtrField, ReserveLessThanDouble) { - RepeatedPtrField field; + RepeatedPtrField field; field.Reserve(20); int capacity = field.Capacity(); @@ -782,9 +846,9 @@ TEST(RepeatedPtrField, ReserveLessThanDouble) { } TEST(RepeatedPtrField, ReserveLessThanExisting) { - RepeatedPtrField field; + RepeatedPtrField field; field.Reserve(20); - const string* const* previous_ptr = field.data(); + const std::string* const* previous_ptr = field.data(); field.Reserve(10); EXPECT_EQ(previous_ptr, field.data()); @@ -795,8 +859,8 @@ TEST(RepeatedPtrField, ReserveDoesntLoseAllocated) { // Check that a bug is fixed: An earlier implementation of Reserve() // failed to copy pointers to allocated-but-cleared objects, possibly // leading to segfaults. - RepeatedPtrField field; - string* first = field.Add(); + RepeatedPtrField field; + std::string* first = field.Add(); field.RemoveLast(); field.Reserve(20); @@ -806,9 +870,9 @@ TEST(RepeatedPtrField, ReserveDoesntLoseAllocated) { // Clearing elements is tricky with RepeatedPtrFields since the memory for // the elements is retained and reused. TEST(RepeatedPtrField, ClearedElements) { - RepeatedPtrField field; + RepeatedPtrField field; - string* original = field.Add(); + std::string* original = field.Add(); *original = "foo"; EXPECT_EQ(field.ClearedCount(), 0); @@ -817,7 +881,8 @@ TEST(RepeatedPtrField, ClearedElements) { EXPECT_TRUE(original->empty()); EXPECT_EQ(field.ClearedCount(), 1); - EXPECT_EQ(field.Add(), original); // Should return same string for reuse. + EXPECT_EQ(field.Add(), + original); // Should return same string for reuse. EXPECT_EQ(field.ReleaseLast(), original); // We take ownership. EXPECT_EQ(field.ClearedCount(), 0); @@ -846,7 +911,7 @@ TEST(RepeatedPtrField, ClearedElements) { // Test all code paths in AddAllocated(). TEST(RepeatedPtrField, AddAlocated) { - RepeatedPtrField field; + RepeatedPtrField field; while (field.size() < field.Capacity()) { field.Add()->assign("filler"); } @@ -854,14 +919,14 @@ TEST(RepeatedPtrField, AddAlocated) { int index = field.size(); // First branch: Field is at capacity with no cleared objects. - string* foo = new string("foo"); + std::string* foo = new std::string("foo"); field.AddAllocated(foo); EXPECT_EQ(index + 1, field.size()); EXPECT_EQ(0, field.ClearedCount()); EXPECT_EQ(foo, &field.Get(index)); // Last branch: Field is not at capacity and there are no cleared objects. - string* bar = new string("bar"); + std::string* bar = new std::string("bar"); field.AddAllocated(bar); ++index; EXPECT_EQ(index + 1, field.size()); @@ -870,7 +935,7 @@ TEST(RepeatedPtrField, AddAlocated) { // Third branch: Field is not at capacity and there are no cleared objects. field.RemoveLast(); - string* baz = new string("baz"); + std::string* baz = new std::string("baz"); field.AddAllocated(baz); EXPECT_EQ(index + 1, field.size()); EXPECT_EQ(1, field.ClearedCount()); @@ -882,7 +947,7 @@ TEST(RepeatedPtrField, AddAlocated) { } field.RemoveLast(); index = field.size(); - string* qux = new string("qux"); + std::string* qux = new std::string("qux"); field.AddAllocated(qux); EXPECT_EQ(index + 1, field.size()); // We should have discarded the cleared object. @@ -891,7 +956,7 @@ TEST(RepeatedPtrField, AddAlocated) { } TEST(RepeatedPtrField, MergeFrom) { - RepeatedPtrField source, destination; + RepeatedPtrField source, destination; source.Add()->assign("4"); source.Add()->assign("5"); destination.Add()->assign("1"); @@ -910,7 +975,7 @@ TEST(RepeatedPtrField, MergeFrom) { TEST(RepeatedPtrField, CopyFrom) { - RepeatedPtrField source, destination; + RepeatedPtrField source, destination; source.Add()->assign("4"); source.Add()->assign("5"); destination.Add()->assign("1"); @@ -925,7 +990,7 @@ TEST(RepeatedPtrField, CopyFrom) { } TEST(RepeatedPtrField, CopyFromSelf) { - RepeatedPtrField me; + RepeatedPtrField me; me.Add()->assign("1"); me.CopyFrom(me); ASSERT_EQ(1, me.size()); @@ -933,8 +998,8 @@ TEST(RepeatedPtrField, CopyFromSelf) { } TEST(RepeatedPtrField, Erase) { - RepeatedPtrField me; - RepeatedPtrField::iterator it = me.erase(me.begin(), me.end()); + RepeatedPtrField me; + RepeatedPtrField::iterator it = me.erase(me.begin(), me.end()); EXPECT_TRUE(me.begin() == it); EXPECT_EQ(0, me.size()); @@ -966,11 +1031,11 @@ TEST(RepeatedPtrField, Erase) { } TEST(RepeatedPtrField, CopyConstruct) { - RepeatedPtrField source; + RepeatedPtrField source; source.Add()->assign("1"); source.Add()->assign("2"); - RepeatedPtrField destination(source); + RepeatedPtrField destination(source); ASSERT_EQ(2, destination.size()); EXPECT_EQ("1", destination.Get(0)); @@ -978,16 +1043,16 @@ TEST(RepeatedPtrField, CopyConstruct) { } TEST(RepeatedPtrField, IteratorConstruct_String) { - std::vector values; + std::vector values; values.push_back("1"); values.push_back("2"); - RepeatedPtrField field(values.begin(), values.end()); + RepeatedPtrField field(values.begin(), values.end()); ASSERT_EQ(values.size(), field.size()); EXPECT_EQ(values[0], field.Get(0)); EXPECT_EQ(values[1], field.Get(1)); - RepeatedPtrField other(field.begin(), field.end()); + RepeatedPtrField other(field.begin(), field.end()); ASSERT_EQ(values.size(), other.size()); EXPECT_EQ(values[0], other.Get(0)); EXPECT_EQ(values[1], other.Get(1)); @@ -1013,7 +1078,7 @@ TEST(RepeatedPtrField, IteratorConstruct_Proto) { } TEST(RepeatedPtrField, CopyAssign) { - RepeatedPtrField source, destination; + RepeatedPtrField source, destination; source.Add()->assign("4"); source.Add()->assign("5"); destination.Add()->assign("1"); @@ -1029,7 +1094,7 @@ TEST(RepeatedPtrField, CopyAssign) { TEST(RepeatedPtrField, SelfAssign) { // Verify that assignment to self does not destroy data. - RepeatedPtrField source, *p; + RepeatedPtrField source, *p; p = &source; source.Add()->assign("7"); source.Add()->assign("8"); @@ -1043,11 +1108,11 @@ TEST(RepeatedPtrField, SelfAssign) { TEST(RepeatedPtrField, MoveConstruct) { { - RepeatedPtrField source; + RepeatedPtrField source; *source.Add() = "1"; *source.Add() = "2"; - const string* const* data = source.data(); - RepeatedPtrField destination = std::move(source); + const std::string* const* data = source.data(); + RepeatedPtrField destination = std::move(source); EXPECT_EQ(data, destination.data()); EXPECT_THAT(destination, ElementsAre("1", "2")); // This property isn't guaranteed but it's useful to have a test that would @@ -1056,11 +1121,11 @@ TEST(RepeatedPtrField, MoveConstruct) { } { Arena arena; - RepeatedPtrField* source = - Arena::CreateMessage>(&arena); + RepeatedPtrField* source = + Arena::CreateMessage>(&arena); *source->Add() = "1"; *source->Add() = "2"; - RepeatedPtrField destination = std::move(*source); + RepeatedPtrField destination = std::move(*source); EXPECT_EQ(nullptr, destination.GetArena()); EXPECT_THAT(destination, ElementsAre("1", "2")); // This property isn't guaranteed but it's useful to have a test that would @@ -1071,13 +1136,13 @@ TEST(RepeatedPtrField, MoveConstruct) { TEST(RepeatedPtrField, MoveAssign) { { - RepeatedPtrField source; + RepeatedPtrField source; *source.Add() = "1"; *source.Add() = "2"; - RepeatedPtrField destination; + RepeatedPtrField destination; *destination.Add() = "3"; - const string* const* source_data = source.data(); - const string* const* destination_data = destination.data(); + const std::string* const* source_data = source.data(); + const std::string* const* destination_data = destination.data(); destination = std::move(source); EXPECT_EQ(source_data, destination.data()); EXPECT_THAT(destination, ElementsAre("1", "2")); @@ -1088,15 +1153,15 @@ TEST(RepeatedPtrField, MoveAssign) { } { Arena arena; - RepeatedPtrField* source = - Arena::CreateMessage>(&arena); + RepeatedPtrField* source = + Arena::CreateMessage>(&arena); *source->Add() = "1"; *source->Add() = "2"; - RepeatedPtrField* destination = - Arena::CreateMessage>(&arena); + RepeatedPtrField* destination = + Arena::CreateMessage>(&arena); *destination->Add() = "3"; - const string* const* source_data = source->data(); - const string* const* destination_data = destination->data(); + const std::string* const* source_data = source->data(); + const std::string* const* destination_data = destination->data(); *destination = std::move(*source); EXPECT_EQ(source_data, destination->data()); EXPECT_THAT(*destination, ElementsAre("1", "2")); @@ -1107,13 +1172,13 @@ TEST(RepeatedPtrField, MoveAssign) { } { Arena source_arena; - RepeatedPtrField* source = - Arena::CreateMessage>(&source_arena); + RepeatedPtrField* source = + Arena::CreateMessage>(&source_arena); *source->Add() = "1"; *source->Add() = "2"; Arena destination_arena; - RepeatedPtrField* destination = - Arena::CreateMessage>(&destination_arena); + RepeatedPtrField* destination = + Arena::CreateMessage>(&destination_arena); *destination->Add() = "3"; *destination = std::move(*source); EXPECT_THAT(*destination, ElementsAre("1", "2")); @@ -1123,11 +1188,11 @@ TEST(RepeatedPtrField, MoveAssign) { } { Arena arena; - RepeatedPtrField* source = - Arena::CreateMessage>(&arena); + RepeatedPtrField* source = + Arena::CreateMessage>(&arena); *source->Add() = "1"; *source->Add() = "2"; - RepeatedPtrField destination; + RepeatedPtrField destination; *destination.Add() = "3"; destination = std::move(*source); EXPECT_THAT(destination, ElementsAre("1", "2")); @@ -1136,12 +1201,12 @@ TEST(RepeatedPtrField, MoveAssign) { EXPECT_THAT(*source, ElementsAre("1", "2")); } { - RepeatedPtrField source; + RepeatedPtrField source; *source.Add() = "1"; *source.Add() = "2"; Arena arena; - RepeatedPtrField* destination = - Arena::CreateMessage>(&arena); + RepeatedPtrField* destination = + Arena::CreateMessage>(&arena); *destination->Add() = "3"; *destination = std::move(source); EXPECT_THAT(*destination, ElementsAre("1", "2")); @@ -1150,23 +1215,23 @@ TEST(RepeatedPtrField, MoveAssign) { EXPECT_THAT(source, ElementsAre("1", "2")); } { - RepeatedPtrField field; + RepeatedPtrField field; // An alias to defeat -Wself-move. - RepeatedPtrField& alias = field; + RepeatedPtrField& alias = field; *field.Add() = "1"; *field.Add() = "2"; - const string* const* data = field.data(); + const std::string* const* data = field.data(); field = std::move(alias); EXPECT_EQ(data, field.data()); EXPECT_THAT(field, ElementsAre("1", "2")); } { Arena arena; - RepeatedPtrField* field = - Arena::CreateMessage>(&arena); + RepeatedPtrField* field = + Arena::CreateMessage>(&arena); *field->Add() = "1"; *field->Add() = "2"; - const string* const* data = field->data(); + const std::string* const* data = field->data(); *field = std::move(*field); EXPECT_EQ(data, field->data()); EXPECT_THAT(*field, ElementsAre("1", "2")); @@ -1174,23 +1239,23 @@ TEST(RepeatedPtrField, MoveAssign) { } TEST(RepeatedPtrField, MutableDataIsMutable) { - RepeatedPtrField field; + RepeatedPtrField field; *field.Add() = "1"; EXPECT_EQ("1", field.Get(0)); // The fact that this line compiles would be enough, but we'll check the // value anyway. - string** data = field.mutable_data(); + std::string** data = field.mutable_data(); **data = "2"; EXPECT_EQ("2", field.Get(0)); } TEST(RepeatedPtrField, SubscriptOperators) { - RepeatedPtrField field; + RepeatedPtrField field; *field.Add() = "1"; EXPECT_EQ("1", field.Get(0)); EXPECT_EQ("1", field[0]); EXPECT_EQ(field.Mutable(0), &field[0]); - const RepeatedPtrField& const_field = field; + const RepeatedPtrField& const_field = field; EXPECT_EQ(*field.data(), &const_field[0]); } @@ -1201,24 +1266,22 @@ TEST(RepeatedPtrField, ExtractSubrange) { for (int num = 0; num <= sz; ++num) { for (int start = 0; start < sz - num; ++start) { for (int extra = 0; extra < 4; ++extra) { - std::vector subject; + std::vector subject; // Create an array with "sz" elements and "extra" cleared elements. - RepeatedPtrField field; + RepeatedPtrField field; for (int i = 0; i < sz + extra; ++i) { - subject.push_back(new string()); + subject.push_back(new std::string()); field.AddAllocated(subject[i]); } EXPECT_EQ(field.size(), sz + extra); - for (int i = 0; i < extra; ++i) - field.RemoveLast(); + for (int i = 0; i < extra; ++i) field.RemoveLast(); EXPECT_EQ(field.size(), sz); EXPECT_EQ(field.ClearedCount(), extra); // Create a catcher array and call ExtractSubrange. - string* catcher[10]; - for (int i = 0; i < 10; ++i) - catcher[i] = NULL; + std::string* catcher[10]; + for (int i = 0; i < 10; ++i) catcher[i] = NULL; field.ExtractSubrange(start, num, catcher); // Does the resulting array have the right size? @@ -1237,8 +1300,7 @@ TEST(RepeatedPtrField, ExtractSubrange) { // Reinstate the cleared elements. EXPECT_EQ(field.ClearedCount(), extra); - for (int i = 0; i < extra; ++i) - field.Add(); + for (int i = 0; i < extra; ++i) field.Add(); EXPECT_EQ(field.ClearedCount(), 0); EXPECT_EQ(field.size(), sz - num + extra); @@ -1246,15 +1308,13 @@ TEST(RepeatedPtrField, ExtractSubrange) { for (int i = sz; i < sz + extra; ++i) { int count = 0; for (int j = sz; j < sz + extra; ++j) { - if (field.Mutable(j - num) == subject[i]) - count += 1; + if (field.Mutable(j - num) == subject[i]) count += 1; } EXPECT_EQ(count, 1); } // Release the caught elements. - for (int i = 0; i < num; ++i) - delete catcher[i]; + for (int i = 0; i < num; ++i) delete catcher[i]; } } } @@ -1326,18 +1386,18 @@ class RepeatedPtrFieldIteratorTest : public testing::Test { proto_array_.Add()->assign("baz"); } - RepeatedPtrField proto_array_; + RepeatedPtrField proto_array_; }; TEST_F(RepeatedPtrFieldIteratorTest, Convertible) { - RepeatedPtrField::iterator iter = proto_array_.begin(); - RepeatedPtrField::const_iterator c_iter = iter; - RepeatedPtrField::value_type value = *c_iter; + RepeatedPtrField::iterator iter = proto_array_.begin(); + RepeatedPtrField::const_iterator c_iter = iter; + RepeatedPtrField::value_type value = *c_iter; EXPECT_EQ("foo", value); } TEST_F(RepeatedPtrFieldIteratorTest, MutableIteration) { - RepeatedPtrField::iterator iter = proto_array_.begin(); + RepeatedPtrField::iterator iter = proto_array_.begin(); EXPECT_EQ("foo", *iter); ++iter; EXPECT_EQ("bar", *(iter++)); @@ -1348,8 +1408,9 @@ TEST_F(RepeatedPtrFieldIteratorTest, MutableIteration) { } TEST_F(RepeatedPtrFieldIteratorTest, ConstIteration) { - const RepeatedPtrField& const_proto_array = proto_array_; - RepeatedPtrField::const_iterator iter = const_proto_array.begin(); + const RepeatedPtrField& const_proto_array = proto_array_; + RepeatedPtrField::const_iterator iter = + const_proto_array.begin(); EXPECT_EQ("foo", *iter); ++iter; EXPECT_EQ("bar", *(iter++)); @@ -1360,7 +1421,7 @@ TEST_F(RepeatedPtrFieldIteratorTest, ConstIteration) { } TEST_F(RepeatedPtrFieldIteratorTest, MutableReverseIteration) { - RepeatedPtrField::reverse_iterator iter = proto_array_.rbegin(); + RepeatedPtrField::reverse_iterator iter = proto_array_.rbegin(); EXPECT_EQ("baz", *iter); ++iter; EXPECT_EQ("bar", *(iter++)); @@ -1371,9 +1432,9 @@ TEST_F(RepeatedPtrFieldIteratorTest, MutableReverseIteration) { } TEST_F(RepeatedPtrFieldIteratorTest, ConstReverseIteration) { - const RepeatedPtrField& const_proto_array = proto_array_; - RepeatedPtrField::const_reverse_iterator iter - = const_proto_array.rbegin(); + const RepeatedPtrField& const_proto_array = proto_array_; + RepeatedPtrField::const_reverse_iterator iter = + const_proto_array.rbegin(); EXPECT_EQ("baz", *iter); ++iter; EXPECT_EQ("bar", *(iter++)); @@ -1384,8 +1445,8 @@ TEST_F(RepeatedPtrFieldIteratorTest, ConstReverseIteration) { } TEST_F(RepeatedPtrFieldIteratorTest, RandomAccess) { - RepeatedPtrField::iterator iter = proto_array_.begin(); - RepeatedPtrField::iterator iter2 = iter; + RepeatedPtrField::iterator iter = proto_array_.begin(); + RepeatedPtrField::iterator iter2 = iter; ++iter2; ++iter2; EXPECT_TRUE(iter + 2 == iter2); @@ -1396,8 +1457,8 @@ TEST_F(RepeatedPtrFieldIteratorTest, RandomAccess) { } TEST_F(RepeatedPtrFieldIteratorTest, Comparable) { - RepeatedPtrField::const_iterator iter = proto_array_.begin(); - RepeatedPtrField::const_iterator iter2 = iter + 1; + RepeatedPtrField::const_iterator iter = proto_array_.begin(); + RepeatedPtrField::const_iterator iter2 = iter + 1; EXPECT_TRUE(iter == iter); EXPECT_TRUE(iter != iter2); EXPECT_TRUE(iter < iter2); @@ -1410,7 +1471,7 @@ TEST_F(RepeatedPtrFieldIteratorTest, Comparable) { // Uninitialized iterator does not point to any of the RepeatedPtrField. TEST_F(RepeatedPtrFieldIteratorTest, UninitializedIterator) { - RepeatedPtrField::iterator iter; + RepeatedPtrField::iterator iter; EXPECT_TRUE(iter != proto_array_.begin()); EXPECT_TRUE(iter != proto_array_.begin() + 1); EXPECT_TRUE(iter != proto_array_.begin() + 2); @@ -1428,8 +1489,8 @@ TEST_F(RepeatedPtrFieldIteratorTest, STLAlgorithms_lower_bound) { proto_array_.Add()->assign("x"); proto_array_.Add()->assign("y"); - string v = "f"; - RepeatedPtrField::const_iterator it = + std::string v = "f"; + RepeatedPtrField::const_iterator it = std::lower_bound(proto_array_.begin(), proto_array_.end(), v); EXPECT_EQ(*it, "n"); @@ -1437,7 +1498,7 @@ TEST_F(RepeatedPtrFieldIteratorTest, STLAlgorithms_lower_bound) { } TEST_F(RepeatedPtrFieldIteratorTest, Mutation) { - RepeatedPtrField::iterator iter = proto_array_.begin(); + RepeatedPtrField::iterator iter = proto_array_.begin(); *iter = "qux"; EXPECT_EQ("qux", proto_array_.Get(0)); } @@ -1453,24 +1514,24 @@ class RepeatedPtrFieldPtrsIteratorTest : public testing::Test { const_proto_array_ = &proto_array_; } - RepeatedPtrField proto_array_; - const RepeatedPtrField* const_proto_array_; + RepeatedPtrField proto_array_; + const RepeatedPtrField* const_proto_array_; }; TEST_F(RepeatedPtrFieldPtrsIteratorTest, ConvertiblePtr) { - RepeatedPtrField::pointer_iterator iter = + RepeatedPtrField::pointer_iterator iter = proto_array_.pointer_begin(); static_cast(iter); } TEST_F(RepeatedPtrFieldPtrsIteratorTest, ConvertibleConstPtr) { - RepeatedPtrField::const_pointer_iterator iter = + RepeatedPtrField::const_pointer_iterator iter = const_proto_array_->pointer_begin(); static_cast(iter); } TEST_F(RepeatedPtrFieldPtrsIteratorTest, MutablePtrIteration) { - RepeatedPtrField::pointer_iterator iter = + RepeatedPtrField::pointer_iterator iter = proto_array_.pointer_begin(); EXPECT_EQ("foo", **iter); ++iter; @@ -1482,7 +1543,7 @@ TEST_F(RepeatedPtrFieldPtrsIteratorTest, MutablePtrIteration) { } TEST_F(RepeatedPtrFieldPtrsIteratorTest, MutableConstPtrIteration) { - RepeatedPtrField::const_pointer_iterator iter = + RepeatedPtrField::const_pointer_iterator iter = const_proto_array_->pointer_begin(); EXPECT_EQ("foo", **iter); ++iter; @@ -1494,9 +1555,9 @@ TEST_F(RepeatedPtrFieldPtrsIteratorTest, MutableConstPtrIteration) { } TEST_F(RepeatedPtrFieldPtrsIteratorTest, RandomPtrAccess) { - RepeatedPtrField::pointer_iterator iter = + RepeatedPtrField::pointer_iterator iter = proto_array_.pointer_begin(); - RepeatedPtrField::pointer_iterator iter2 = iter; + RepeatedPtrField::pointer_iterator iter2 = iter; ++iter2; ++iter2; EXPECT_TRUE(iter + 2 == iter2); @@ -1507,9 +1568,9 @@ TEST_F(RepeatedPtrFieldPtrsIteratorTest, RandomPtrAccess) { } TEST_F(RepeatedPtrFieldPtrsIteratorTest, RandomConstPtrAccess) { - RepeatedPtrField::const_pointer_iterator iter = + RepeatedPtrField::const_pointer_iterator iter = const_proto_array_->pointer_begin(); - RepeatedPtrField::const_pointer_iterator iter2 = iter; + RepeatedPtrField::const_pointer_iterator iter2 = iter; ++iter2; ++iter2; EXPECT_TRUE(iter + 2 == iter2); @@ -1520,9 +1581,9 @@ TEST_F(RepeatedPtrFieldPtrsIteratorTest, RandomConstPtrAccess) { } TEST_F(RepeatedPtrFieldPtrsIteratorTest, ComparablePtr) { - RepeatedPtrField::pointer_iterator iter = + RepeatedPtrField::pointer_iterator iter = proto_array_.pointer_begin(); - RepeatedPtrField::pointer_iterator iter2 = iter + 1; + RepeatedPtrField::pointer_iterator iter2 = iter + 1; EXPECT_TRUE(iter == iter); EXPECT_TRUE(iter != iter2); EXPECT_TRUE(iter < iter2); @@ -1534,9 +1595,9 @@ TEST_F(RepeatedPtrFieldPtrsIteratorTest, ComparablePtr) { } TEST_F(RepeatedPtrFieldPtrsIteratorTest, ComparableConstPtr) { - RepeatedPtrField::const_pointer_iterator iter = + RepeatedPtrField::const_pointer_iterator iter = const_proto_array_->pointer_begin(); - RepeatedPtrField::const_pointer_iterator iter2 = iter + 1; + RepeatedPtrField::const_pointer_iterator iter2 = iter + 1; EXPECT_TRUE(iter == iter); EXPECT_TRUE(iter != iter2); EXPECT_TRUE(iter < iter2); @@ -1550,7 +1611,7 @@ TEST_F(RepeatedPtrFieldPtrsIteratorTest, ComparableConstPtr) { // Uninitialized iterator does not point to any of the RepeatedPtrOverPtrs. // Dereferencing an uninitialized iterator crashes the process. TEST_F(RepeatedPtrFieldPtrsIteratorTest, UninitializedPtrIterator) { - RepeatedPtrField::pointer_iterator iter; + RepeatedPtrField::pointer_iterator iter; EXPECT_TRUE(iter != proto_array_.pointer_begin()); EXPECT_TRUE(iter != proto_array_.pointer_begin() + 1); EXPECT_TRUE(iter != proto_array_.pointer_begin() + 2); @@ -1559,7 +1620,7 @@ TEST_F(RepeatedPtrFieldPtrsIteratorTest, UninitializedPtrIterator) { } TEST_F(RepeatedPtrFieldPtrsIteratorTest, UninitializedConstPtrIterator) { - RepeatedPtrField::const_pointer_iterator iter; + RepeatedPtrField::const_pointer_iterator iter; EXPECT_TRUE(iter != const_proto_array_->pointer_begin()); EXPECT_TRUE(iter != const_proto_array_->pointer_begin() + 1); EXPECT_TRUE(iter != const_proto_array_->pointer_begin() + 2); @@ -1569,13 +1630,14 @@ TEST_F(RepeatedPtrFieldPtrsIteratorTest, UninitializedConstPtrIterator) { // This comparison functor is required by the tests for RepeatedPtrOverPtrs. // They operate on strings and need to compare strings as strings in -// any stl algorithm, even though the iterator returns a pointer to a string -// - i.e. *iter has type string*. +// any stl algorithm, even though the iterator returns a pointer to a +// string +// - i.e. *iter has type std::string*. struct StringLessThan { - bool operator()(const string* z, const string& y) { - return *z < y; + bool operator()(const std::string* z, const std::string& y) { return *z < y; } + bool operator()(const std::string* z, const std::string* y) const { + return *z < *y; } - bool operator()(const string* z, const string* y) const { return *z < *y; } }; TEST_F(RepeatedPtrFieldPtrsIteratorTest, PtrSTLAlgorithms_lower_bound) { @@ -1589,8 +1651,8 @@ TEST_F(RepeatedPtrFieldPtrsIteratorTest, PtrSTLAlgorithms_lower_bound) { proto_array_.Add()->assign("y"); { - string v = "f"; - RepeatedPtrField::pointer_iterator it = + std::string v = "f"; + RepeatedPtrField::pointer_iterator it = std::lower_bound(proto_array_.pointer_begin(), proto_array_.pointer_end(), &v, StringLessThan()); @@ -1600,8 +1662,8 @@ TEST_F(RepeatedPtrFieldPtrsIteratorTest, PtrSTLAlgorithms_lower_bound) { EXPECT_TRUE(it == proto_array_.pointer_begin() + 3); } { - string v = "f"; - RepeatedPtrField::const_pointer_iterator it = std::lower_bound( + std::string v = "f"; + RepeatedPtrField::const_pointer_iterator it = std::lower_bound( const_proto_array_->pointer_begin(), const_proto_array_->pointer_end(), &v, StringLessThan()); @@ -1613,7 +1675,7 @@ TEST_F(RepeatedPtrFieldPtrsIteratorTest, PtrSTLAlgorithms_lower_bound) { } TEST_F(RepeatedPtrFieldPtrsIteratorTest, PtrMutation) { - RepeatedPtrField::pointer_iterator iter = + RepeatedPtrField::pointer_iterator iter = proto_array_.pointer_begin(); **iter = "qux"; EXPECT_EQ("qux", proto_array_.Get(0)); @@ -1622,10 +1684,10 @@ TEST_F(RepeatedPtrFieldPtrsIteratorTest, PtrMutation) { EXPECT_EQ("baz", proto_array_.Get(2)); ++iter; delete *iter; - *iter = new string("a"); + *iter = new std::string("a"); ++iter; delete *iter; - *iter = new string("b"); + *iter = new std::string("b"); EXPECT_EQ("a", proto_array_.Get(1)); EXPECT_EQ("b", proto_array_.Get(2)); } @@ -1648,7 +1710,6 @@ TEST_F(RepeatedPtrFieldPtrsIteratorTest, Sort) { EXPECT_EQ("y", proto_array_.Get(9)); } - // ----------------------------------------------------------------------------- // Unit-tests for the insert iterators // google::protobuf::RepeatedFieldBackInserter, @@ -1659,7 +1720,7 @@ class RepeatedFieldInsertionIteratorsTest : public testing::Test { protected: std::list halves; std::list fibonacci; - std::vector words; + std::vector words; typedef TestAllTypes::NestedMessage Nested; Nested nesteds[2]; std::vector nested_ptrs; @@ -1714,8 +1775,7 @@ class RepeatedFieldInsertionIteratorsTest : public testing::Test { }; TEST_F(RepeatedFieldInsertionIteratorsTest, Fibonacci) { - EXPECT_TRUE(std::equal(fibonacci.begin(), - fibonacci.end(), + EXPECT_TRUE(std::equal(fibonacci.begin(), fibonacci.end(), protobuffer.repeated_int32().begin())); EXPECT_TRUE(std::equal(protobuffer.repeated_int32().begin(), protobuffer.repeated_int32().end(), @@ -1723,12 +1783,10 @@ TEST_F(RepeatedFieldInsertionIteratorsTest, Fibonacci) { } TEST_F(RepeatedFieldInsertionIteratorsTest, Halves) { - EXPECT_TRUE(std::equal(halves.begin(), - halves.end(), + EXPECT_TRUE(std::equal(halves.begin(), halves.end(), protobuffer.repeated_double().begin())); EXPECT_TRUE(std::equal(protobuffer.repeated_double().begin(), - protobuffer.repeated_double().end(), - halves.begin())); + protobuffer.repeated_double().end(), halves.begin())); } TEST_F(RepeatedFieldInsertionIteratorsTest, Words) { @@ -1746,8 +1804,9 @@ TEST_F(RepeatedFieldInsertionIteratorsTest, Words2) { words.push_back("six"); words.push_back("pence"); protobuffer.mutable_repeated_string()->Clear(); - std::copy(words.begin(), words.end(), RepeatedPtrFieldBackInserter( - protobuffer.mutable_repeated_string())); + std::copy( + words.begin(), words.end(), + RepeatedPtrFieldBackInserter(protobuffer.mutable_repeated_string())); ASSERT_EQ(words.size(), protobuffer.repeated_string_size()); for (int i = 0; i < words.size(); ++i) EXPECT_EQ(words.at(i), protobuffer.repeated_string(i)); @@ -1782,19 +1841,20 @@ TEST_F(RepeatedFieldInsertionIteratorsTest, TEST_F(RepeatedFieldInsertionIteratorsTest, AllocatedRepeatedPtrFieldWithString) { - std::vector data; + std::vector data; TestAllTypes goldenproto; for (int i = 0; i < 10; ++i) { - string* new_data = new string; - *new_data = "name-" + SimpleItoa(i); + std::string* new_data = new std::string; + *new_data = "name-" + StrCat(i); data.push_back(new_data); new_data = goldenproto.add_repeated_string(); - *new_data = "name-" + SimpleItoa(i); + *new_data = "name-" + StrCat(i); } TestAllTypes testproto; - std::copy(data.begin(), data.end(), AllocatedRepeatedPtrFieldBackInserter( - testproto.mutable_repeated_string())); + std::copy(data.begin(), data.end(), + AllocatedRepeatedPtrFieldBackInserter( + testproto.mutable_repeated_string())); EXPECT_EQ(testproto.DebugString(), goldenproto.DebugString()); } @@ -1819,15 +1879,15 @@ TEST_F(RepeatedFieldInsertionIteratorsTest, TEST_F(RepeatedFieldInsertionIteratorsTest, UnsafeArenaAllocatedRepeatedPtrFieldWithString) { - std::vector data; + std::vector data; TestAllTypes goldenproto; for (int i = 0; i < 10; ++i) { - string* new_data = new string; - *new_data = "name-" + SimpleItoa(i); + std::string* new_data = new std::string; + *new_data = "name-" + StrCat(i); data.push_back(new_data); new_data = goldenproto.add_repeated_string(); - *new_data = "name-" + SimpleItoa(i); + *new_data = "name-" + StrCat(i); } TestAllTypes testproto; std::copy(data.begin(), data.end(), @@ -1837,8 +1897,9 @@ TEST_F(RepeatedFieldInsertionIteratorsTest, } TEST_F(RepeatedFieldInsertionIteratorsTest, MoveStrings) { - std::vector src = {"a", "b", "c", "d"}; - std::vector copy = src; // copy since move leaves in undefined state + std::vector src = {"a", "b", "c", "d"}; + std::vector copy = + src; // copy since move leaves in undefined state TestAllTypes testproto; std::move(copy.begin(), copy.end(), RepeatedFieldBackInserter(testproto.mutable_repeated_string())); diff --git a/third_party/protobuf/src/google/protobuf/service.cc b/third_party/protobuf/src/google/protobuf/service.cc index ffa919da..53945684 100644 --- a/third_party/protobuf/src/google/protobuf/service.cc +++ b/third_party/protobuf/src/google/protobuf/service.cc @@ -42,5 +42,4 @@ RpcChannel::~RpcChannel() {} RpcController::~RpcController() {} } // namespace protobuf - } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/service.h b/third_party/protobuf/src/google/protobuf/service.h index ad6f9685..d6b4ab82 100644 --- a/third_party/protobuf/src/google/protobuf/service.h +++ b/third_party/protobuf/src/google/protobuf/service.h @@ -101,8 +101,14 @@ #define GOOGLE_PROTOBUF_SERVICE_H__ #include -#include #include +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + +#include namespace google { namespace protobuf { @@ -113,17 +119,17 @@ class RpcController; class RpcChannel; // Defined in other files. -class Descriptor; // descriptor.h -class ServiceDescriptor; // descriptor.h -class MethodDescriptor; // descriptor.h -class Message; // message.h +class Descriptor; // descriptor.h +class ServiceDescriptor; // descriptor.h +class MethodDescriptor; // descriptor.h +class Message; // message.h // Abstract base interface for protocol-buffer-based RPC services. Services // themselves are abstract interfaces (implemented either by servers or as // stubs), but they subclass this base interface. The methods of this // interface can be used to call the methods of the Service without knowing // its exact type at compile time (analogous to Reflection). -class LIBPROTOBUF_EXPORT Service { +class PROTOBUF_EXPORT Service { public: inline Service() {} virtual ~Service(); @@ -131,10 +137,7 @@ class LIBPROTOBUF_EXPORT Service { // When constructing a stub, you may pass STUB_OWNS_CHANNEL as the second // parameter to the constructor to tell it to delete its RpcChannel when // destroyed. - enum ChannelOwnership { - STUB_OWNS_CHANNEL, - STUB_DOESNT_OWN_CHANNEL - }; + enum ChannelOwnership { STUB_OWNS_CHANNEL, STUB_DOESNT_OWN_CHANNEL }; // Get the ServiceDescriptor describing this service and its methods. virtual const ServiceDescriptor* GetDescriptor() = 0; @@ -165,10 +168,8 @@ class LIBPROTOBUF_EXPORT Service { // RpcController can be queried to determine if an error occurred and // possibly to get more information about the error. virtual void CallMethod(const MethodDescriptor* method, - RpcController* controller, - const Message* request, - Message* response, - Closure* done) = 0; + RpcController* controller, const Message* request, + Message* response, Closure* done) = 0; // CallMethod() requires that the request and response passed in are of a // particular subclass of Message. GetRequestPrototype() and @@ -184,9 +185,9 @@ class LIBPROTOBUF_EXPORT Service { // request->ParseFromString(input); // service->CallMethod(method, *request, response, callback); virtual const Message& GetRequestPrototype( - const MethodDescriptor* method) const = 0; + const MethodDescriptor* method) const = 0; virtual const Message& GetResponsePrototype( - const MethodDescriptor* method) const = 0; + const MethodDescriptor* method) const = 0; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Service); @@ -200,7 +201,7 @@ class LIBPROTOBUF_EXPORT Service { // "least common denominator" set of features which we expect all // implementations to support. Specific implementations may provide more // advanced features (e.g. deadline propagation). -class LIBPROTOBUF_EXPORT RpcController { +class PROTOBUF_EXPORT RpcController { public: inline RpcController() {} virtual ~RpcController(); @@ -220,7 +221,7 @@ class LIBPROTOBUF_EXPORT RpcController { virtual bool Failed() const = 0; // If Failed() is true, returns a human-readable description of the error. - virtual string ErrorText() const = 0; + virtual std::string ErrorText() const = 0; // Advises the RPC system that the caller desires that the RPC call be // canceled. The RPC system may cancel it immediately, may wait awhile and @@ -238,7 +239,7 @@ class LIBPROTOBUF_EXPORT RpcController { // you need to return machine-readable information about failures, you // should incorporate it into your response protocol buffer and should // NOT call SetFailed(). - virtual void SetFailed(const string& reason) = 0; + virtual void SetFailed(const std::string& reason) = 0; // If true, indicates that the client canceled the RPC, so the server may // as well give up on replying to it. The server should still call the @@ -266,7 +267,7 @@ class LIBPROTOBUF_EXPORT RpcController { // RpcChannel* channel = new MyRpcChannel("remotehost.example.com:1234"); // MyService* service = new MyService::Stub(channel); // service->MyMethod(request, &response, callback); -class LIBPROTOBUF_EXPORT RpcChannel { +class PROTOBUF_EXPORT RpcChannel { public: inline RpcChannel() {} virtual ~RpcChannel(); @@ -277,16 +278,16 @@ class LIBPROTOBUF_EXPORT RpcChannel { // need not be of any specific class as long as their descriptors are // method->input_type() and method->output_type(). virtual void CallMethod(const MethodDescriptor* method, - RpcController* controller, - const Message* request, - Message* response, - Closure* done) = 0; + RpcController* controller, const Message* request, + Message* response, Closure* done) = 0; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RpcChannel); }; } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_SERVICE_H__ diff --git a/third_party/protobuf/src/google/protobuf/source_context.pb.cc b/third_party/protobuf/src/google/protobuf/source_context.pb.cc index 739172f8..50a5c0e4 100644 --- a/third_party/protobuf/src/google/protobuf/source_context.pb.cc +++ b/third_party/protobuf/src/google/protobuf/source_context.pb.cc @@ -6,142 +6,113 @@ #include #include -#include #include -#include +#include +#include #include #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) - -namespace google { -namespace protobuf { +#include +PROTOBUF_NAMESPACE_OPEN class SourceContextDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _SourceContext_default_instance_; -} // namespace protobuf -} // namespace google -namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto { -static void InitDefaultsSourceContext() { +PROTOBUF_NAMESPACE_CLOSE +static void InitDefaultsscc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_SourceContext_default_instance_; - new (ptr) ::google::protobuf::SourceContext(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_SourceContext_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::SourceContext(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::SourceContext::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::SourceContext::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsSourceContext}, {}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto}, {}}; -void InitDefaults() { - ::google::protobuf::internal::InitSCC(&scc_info_SourceContext.base); -} +static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_google_2fprotobuf_2fsource_5fcontext_2eproto[1]; +static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fsource_5fcontext_2eproto = nullptr; +static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fsource_5fcontext_2eproto = nullptr; -::google::protobuf::Metadata file_level_metadata[1]; - -const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceContext, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::SourceContext, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceContext, file_name_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::SourceContext, file_name_), }; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, sizeof(::google::protobuf::SourceContext)}, +static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, -1, sizeof(PROTOBUF_NAMESPACE_ID::SourceContext)}, }; -static ::google::protobuf::Message const * const file_default_instances[] = { - reinterpret_cast(&::google::protobuf::_SourceContext_default_instance_), +static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_SourceContext_default_instance_), }; -void protobuf_AssignDescriptors() { - AddDescriptors(); - AssignDescriptors( - "google/protobuf/source_context.proto", schemas, file_default_instances, TableStruct::offsets, - file_level_metadata, NULL, NULL); -} +const char descriptor_table_protodef_google_2fprotobuf_2fsource_5fcontext_2eproto[] = + "\n$google/protobuf/source_context.proto\022\017" + "google.protobuf\"\"\n\rSourceContext\022\021\n\tfile" + "_name\030\001 \001(\tB\225\001\n\023com.google.protobufB\022Sou" + "rceContextProtoP\001ZAgoogle.golang.org/gen" + "proto/protobuf/source_context;source_con" + "text\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTy" + "pesb\006proto3" + ; +static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_deps[1] = { +}; +static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_sccs[1] = { + &scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto.base, +}; +static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_once; +static bool descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_initialized = false; +const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto = { + &descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fsource_5fcontext_2eproto, "google/protobuf/source_context.proto", 251, + &descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_once, descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_sccs, descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_deps, 1, 0, + schemas, file_default_instances, TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2fsource_5fcontext_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2fsource_5fcontext_2eproto, file_level_service_descriptors_google_2fprotobuf_2fsource_5fcontext_2eproto, +}; -void protobuf_AssignDescriptorsOnce() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); -} - -void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1); -} - -void AddDescriptorsImpl() { - InitDefaults(); - static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - "\n$google/protobuf/source_context.proto\022\017" - "google.protobuf\"\"\n\rSourceContext\022\021\n\tfile" - "_name\030\001 \001(\tB\225\001\n\023com.google.protobufB\022Sou" - "rceContextProtoP\001ZAgoogle.golang.org/gen" - "proto/protobuf/source_context;source_con" - "text\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTy" - "pesb\006proto3" - }; - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - descriptor, 251); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "google/protobuf/source_context.proto", &protobuf_RegisterTypes); -} - -void AddDescriptors() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); -} -// Force AddDescriptors() to be called at dynamic initialization time. -struct StaticDescriptorInitializer { - StaticDescriptorInitializer() { - AddDescriptors(); - } -} static_descriptor_initializer; -} // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto -namespace google { -namespace protobuf { +// Force running AddDescriptors() at dynamic initialization time. +static bool dynamic_init_dummy_google_2fprotobuf_2fsource_5fcontext_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto), true); +PROTOBUF_NAMESPACE_OPEN // =================================================================== void SourceContext::InitAsDefaultInstance() { } +class SourceContext::HasBitSetters { + public: +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int SourceContext::kFileNameFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 SourceContext::SourceContext() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.SourceContext) } SourceContext::SourceContext(const SourceContext& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); - file_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + file_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from.file_name().size() > 0) { - file_name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.file_name_); + file_name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.file_name_); } // @@protoc_insertion_point(copy_constructor:google.protobuf.SourceContext) } void SourceContext::SharedCtor() { - file_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto.base); + file_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } SourceContext::~SourceContext() { @@ -150,52 +121,81 @@ SourceContext::~SourceContext() { } void SourceContext::SharedDtor() { - file_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + file_name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void SourceContext::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* SourceContext::descriptor() { - ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const SourceContext& SourceContext::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto.base); return *internal_default_instance(); } void SourceContext::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.SourceContext) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - file_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + file_name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* SourceContext::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // string file_name = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(mutable_file_name(), ptr, ctx, "google.protobuf.SourceContext.file_name"); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool SourceContext::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.SourceContext) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string file_name = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_file_name())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->file_name().data(), static_cast(this->file_name().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "google.protobuf.SourceContext.file_name")); } else { goto handle_unusual; @@ -208,7 +208,7 @@ bool SourceContext::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -222,51 +222,51 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SourceContext::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.SourceContext) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string file_name = 1; if (this->file_name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->file_name().data(), static_cast(this->file_name().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.SourceContext.file_name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->file_name(), output); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); + if (_internal_metadata_.have_unknown_fields()) { + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( + _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.SourceContext) } -::google::protobuf::uint8* SourceContext::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* SourceContext::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.SourceContext) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string file_name = 1; if (this->file_name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->file_name().data(), static_cast(this->file_name().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.SourceContext.file_name"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 1, this->file_name(), target); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); + if (_internal_metadata_.have_unknown_fields()) { + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( + _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.SourceContext) return target; @@ -276,32 +276,36 @@ size_t SourceContext::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.protobuf.SourceContext) size_t total_size = 0; - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { + if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( + _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // string file_name = 1; if (this->file_name().size() > 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->file_name()); } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void SourceContext::MergeFrom(const ::google::protobuf::Message& from) { +void SourceContext::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.SourceContext) GOOGLE_DCHECK_NE(&from, this); const SourceContext* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.SourceContext) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.SourceContext) MergeFrom(*source); @@ -312,16 +316,16 @@ void SourceContext::MergeFrom(const SourceContext& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.SourceContext) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.file_name().size() > 0) { - file_name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.file_name_); + file_name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.file_name_); } } -void SourceContext::CopyFrom(const ::google::protobuf::Message& from) { +void SourceContext::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.SourceContext) if (&from == this) return; Clear(); @@ -345,26 +349,23 @@ void SourceContext::Swap(SourceContext* other) { } void SourceContext::InternalSwap(SourceContext* other) { using std::swap; - file_name_.Swap(&other->file_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); _internal_metadata_.Swap(&other->_internal_metadata_); + file_name_.Swap(&other->file_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); } -::google::protobuf::Metadata SourceContext::GetMetadata() const { - protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata SourceContext::GetMetadata() const { + return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceContext* Arena::CreateMaybeMessage< ::google::protobuf::SourceContext >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::SourceContext >(arena); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::SourceContext* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::SourceContext >(Arena* arena) { + return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::SourceContext >(arena); } -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) +#include diff --git a/third_party/protobuf/src/google/protobuf/source_context.pb.h b/third_party/protobuf/src/google/protobuf/source_context.pb.h index dcc856e2..9ef68699 100644 --- a/third_party/protobuf/src/google/protobuf/source_context.pb.h +++ b/third_party/protobuf/src/google/protobuf/source_context.pb.h @@ -1,24 +1,25 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/source_context.proto -#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto -#define PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto +#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto +#include #include -#include - -#if GOOGLE_PROTOBUF_VERSION < 3006001 +#include +#if PROTOBUF_VERSION < 3008000 #error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update +#error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3008000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please +#error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include @@ -26,59 +27,61 @@ #include #include #include +#include #include #include // IWYU pragma: export #include // IWYU pragma: export #include // @@protoc_insertion_point(includes) -#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto LIBPROTOBUF_EXPORT +#include +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fsource_5fcontext_2eproto PROTOBUF_EXPORT +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE -namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto { // Internal implementation detail -- do not use these members. -struct LIBPROTOBUF_EXPORT TableStruct { - static const ::google::protobuf::internal::ParseTableField entries[]; - static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; - static const ::google::protobuf::internal::ParseTable schema[1]; - static const ::google::protobuf::internal::FieldMetadata field_metadata[]; - static const ::google::protobuf::internal::SerializationTable serialization_table[]; - static const ::google::protobuf::uint32 offsets[]; +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto { + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; + static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; + static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; -void LIBPROTOBUF_EXPORT AddDescriptors(); -} // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto -namespace google { -namespace protobuf { +extern PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto; +PROTOBUF_NAMESPACE_OPEN class SourceContext; class SourceContextDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern SourceContextDefaultTypeInternal _SourceContext_default_instance_; -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceContext* Arena::CreateMaybeMessage<::google::protobuf::SourceContext>(Arena*); -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { +PROTOBUF_EXPORT extern SourceContextDefaultTypeInternal _SourceContext_default_instance_; +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::SourceContext* Arena::CreateMaybeMessage(Arena*); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN // =================================================================== -class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceContext) */ { +class PROTOBUF_EXPORT SourceContext : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceContext) */ { public: SourceContext(); virtual ~SourceContext(); SourceContext(const SourceContext& from); - - inline SourceContext& operator=(const SourceContext& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 SourceContext(SourceContext&& from) noexcept : SourceContext() { *this = ::std::move(from); } + inline SourceContext& operator=(const SourceContext& from) { + CopyFrom(from); + return *this; + } inline SourceContext& operator=(SourceContext&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -87,8 +90,16 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @ } return *this; } - #endif - static const ::google::protobuf::Descriptor* descriptor(); + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const SourceContext& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -107,43 +118,58 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @ // implements Message ---------------------------------------------- inline SourceContext* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - SourceContext* New(::google::protobuf::Arena* arena) const final { + SourceContext* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const SourceContext& from); void MergeFrom(const SourceContext& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(SourceContext* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.SourceContext"; + } private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { + return nullptr; } inline void* MaybeArenaPtr() const { - return NULL; + return nullptr; } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto); + return ::descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -152,24 +178,23 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @ // string file_name = 1; void clear_file_name(); static const int kFileNameFieldNumber = 1; - const ::std::string& file_name() const; - void set_file_name(const ::std::string& value); - #if LANG_CXX11 - void set_file_name(::std::string&& value); - #endif + const std::string& file_name() const; + void set_file_name(const std::string& value); + void set_file_name(std::string&& value); void set_file_name(const char* value); void set_file_name(const char* value, size_t size); - ::std::string* mutable_file_name(); - ::std::string* release_file_name(); - void set_allocated_file_name(::std::string* file_name); + std::string* mutable_file_name(); + std::string* release_file_name(); + void set_allocated_file_name(std::string* file_name); // @@protoc_insertion_point(class_scope:google.protobuf.SourceContext) private: + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::ArenaStringPtr file_name_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - friend struct ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr file_name_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto; }; // =================================================================== @@ -184,54 +209,52 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @ // string file_name = 1; inline void SourceContext::clear_file_name() { - file_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + file_name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline const ::std::string& SourceContext::file_name() const { +inline const std::string& SourceContext::file_name() const { // @@protoc_insertion_point(field_get:google.protobuf.SourceContext.file_name) return file_name_.GetNoArena(); } -inline void SourceContext::set_file_name(const ::std::string& value) { +inline void SourceContext::set_file_name(const std::string& value) { - file_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); + file_name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.protobuf.SourceContext.file_name) } -#if LANG_CXX11 -inline void SourceContext::set_file_name(::std::string&& value) { +inline void SourceContext::set_file_name(std::string&& value) { file_name_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.SourceContext.file_name) } -#endif inline void SourceContext::set_file_name(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); - file_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + file_name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.protobuf.SourceContext.file_name) } inline void SourceContext::set_file_name(const char* value, size_t size) { - file_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + file_name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceContext.file_name) } -inline ::std::string* SourceContext::mutable_file_name() { +inline std::string* SourceContext::mutable_file_name() { // @@protoc_insertion_point(field_mutable:google.protobuf.SourceContext.file_name) - return file_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return file_name_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline ::std::string* SourceContext::release_file_name() { +inline std::string* SourceContext::release_file_name() { // @@protoc_insertion_point(field_release:google.protobuf.SourceContext.file_name) - return file_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return file_name_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } -inline void SourceContext::set_allocated_file_name(::std::string* file_name) { - if (file_name != NULL) { +inline void SourceContext::set_allocated_file_name(std::string* file_name) { + if (file_name != nullptr) { } else { } - file_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), file_name); + file_name_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), file_name); // @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceContext.file_name) } @@ -241,9 +264,9 @@ inline void SourceContext::set_allocated_file_name(::std::string* file_name) { // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto diff --git a/third_party/protobuf/src/google/protobuf/struct.pb.cc b/third_party/protobuf/src/google/protobuf/struct.pb.cc index 8f2d4848..b7028f08 100644 --- a/third_party/protobuf/src/google/protobuf/struct.pb.cc +++ b/third_party/protobuf/src/google/protobuf/struct.pb.cc @@ -6,201 +6,163 @@ #include #include -#include #include -#include +#include +#include #include #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) - -namespace protobuf_google_2fprotobuf_2fstruct_2eproto { -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fstruct_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_ListValue; -} // namespace protobuf_google_2fprotobuf_2fstruct_2eproto -namespace google { -namespace protobuf { +#include +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fstruct_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto; +PROTOBUF_NAMESPACE_OPEN class Struct_FieldsEntry_DoNotUseDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _Struct_FieldsEntry_DoNotUse_default_instance_; class StructDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _Struct_default_instance_; class ValueDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; int null_value_; double number_value_; - ::google::protobuf::internal::ArenaStringPtr string_value_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr string_value_; bool bool_value_; - const ::google::protobuf::Struct* struct_value_; - const ::google::protobuf::ListValue* list_value_; + const PROTOBUF_NAMESPACE_ID::Struct* struct_value_; + const PROTOBUF_NAMESPACE_ID::ListValue* list_value_; } _Value_default_instance_; class ListValueDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _ListValue_default_instance_; -} // namespace protobuf -} // namespace google -namespace protobuf_google_2fprotobuf_2fstruct_2eproto { -static void InitDefaultsListValue() { +PROTOBUF_NAMESPACE_CLOSE +static void InitDefaultsscc_info_ListValue_google_2fprotobuf_2fstruct_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_Struct_FieldsEntry_DoNotUse_default_instance_; - new (ptr) ::google::protobuf::Struct_FieldsEntry_DoNotUse(); + void* ptr = &PROTOBUF_NAMESPACE_ID::_Struct_FieldsEntry_DoNotUse_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse(); } { - void* ptr = &::google::protobuf::_Struct_default_instance_; - new (ptr) ::google::protobuf::Struct(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_Struct_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::Struct(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } { - void* ptr = &::google::protobuf::_Value_default_instance_; - new (ptr) ::google::protobuf::Value(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_Value_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::Value(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } { - void* ptr = &::google::protobuf::_ListValue_default_instance_; - new (ptr) ::google::protobuf::ListValue(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_ListValue_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::ListValue(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::Struct_FieldsEntry_DoNotUse::InitAsDefaultInstance(); - ::google::protobuf::Struct::InitAsDefaultInstance(); - ::google::protobuf::Value::InitAsDefaultInstance(); - ::google::protobuf::ListValue::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::Struct::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::Value::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::ListValue::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_ListValue = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsListValue}, {}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_ListValue_google_2fprotobuf_2fstruct_2eproto}, {}}; -void InitDefaults() { - ::google::protobuf::internal::InitSCC(&scc_info_ListValue.base); -} +static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_google_2fprotobuf_2fstruct_2eproto[4]; +static const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* file_level_enum_descriptors_google_2fprotobuf_2fstruct_2eproto[1]; +static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fstruct_2eproto = nullptr; -::google::protobuf::Metadata file_level_metadata[4]; -const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[1]; - -const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Struct_FieldsEntry_DoNotUse, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Struct_FieldsEntry_DoNotUse, _internal_metadata_), +const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_google_2fprotobuf_2fstruct_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse, _has_bits_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Struct_FieldsEntry_DoNotUse, key_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Struct_FieldsEntry_DoNotUse, value_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse, key_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse, value_), 0, 1, ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Struct, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Struct, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Struct, fields_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Struct, fields_), ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Value, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Value, _internal_metadata_), ~0u, // no _extensions_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Value, _oneof_case_[0]), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Value, _oneof_case_[0]), ~0u, // no _weak_field_map_ - offsetof(::google::protobuf::ValueDefaultTypeInternal, null_value_), - offsetof(::google::protobuf::ValueDefaultTypeInternal, number_value_), - offsetof(::google::protobuf::ValueDefaultTypeInternal, string_value_), - offsetof(::google::protobuf::ValueDefaultTypeInternal, bool_value_), - offsetof(::google::protobuf::ValueDefaultTypeInternal, struct_value_), - offsetof(::google::protobuf::ValueDefaultTypeInternal, list_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Value, kind_), + offsetof(PROTOBUF_NAMESPACE_ID::ValueDefaultTypeInternal, null_value_), + offsetof(PROTOBUF_NAMESPACE_ID::ValueDefaultTypeInternal, number_value_), + offsetof(PROTOBUF_NAMESPACE_ID::ValueDefaultTypeInternal, string_value_), + offsetof(PROTOBUF_NAMESPACE_ID::ValueDefaultTypeInternal, bool_value_), + offsetof(PROTOBUF_NAMESPACE_ID::ValueDefaultTypeInternal, struct_value_), + offsetof(PROTOBUF_NAMESPACE_ID::ValueDefaultTypeInternal, list_value_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Value, kind_), ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ListValue, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ListValue, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ListValue, values_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ListValue, values_), }; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - { 0, 7, sizeof(::google::protobuf::Struct_FieldsEntry_DoNotUse)}, - { 9, -1, sizeof(::google::protobuf::Struct)}, - { 15, -1, sizeof(::google::protobuf::Value)}, - { 27, -1, sizeof(::google::protobuf::ListValue)}, +static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, 7, sizeof(PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse)}, + { 9, -1, sizeof(PROTOBUF_NAMESPACE_ID::Struct)}, + { 15, -1, sizeof(PROTOBUF_NAMESPACE_ID::Value)}, + { 27, -1, sizeof(PROTOBUF_NAMESPACE_ID::ListValue)}, }; -static ::google::protobuf::Message const * const file_default_instances[] = { - reinterpret_cast(&::google::protobuf::_Struct_FieldsEntry_DoNotUse_default_instance_), - reinterpret_cast(&::google::protobuf::_Struct_default_instance_), - reinterpret_cast(&::google::protobuf::_Value_default_instance_), - reinterpret_cast(&::google::protobuf::_ListValue_default_instance_), +static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_Struct_FieldsEntry_DoNotUse_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_Struct_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_Value_default_instance_), + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_ListValue_default_instance_), }; -void protobuf_AssignDescriptors() { - AddDescriptors(); - AssignDescriptors( - "google/protobuf/struct.proto", schemas, file_default_instances, TableStruct::offsets, - file_level_metadata, file_level_enum_descriptors, NULL); -} +const char descriptor_table_protodef_google_2fprotobuf_2fstruct_2eproto[] = + "\n\034google/protobuf/struct.proto\022\017google.p" + "rotobuf\"\204\001\n\006Struct\0223\n\006fields\030\001 \003(\0132#.goo" + "gle.protobuf.Struct.FieldsEntry\032E\n\013Field" + "sEntry\022\013\n\003key\030\001 \001(\t\022%\n\005value\030\002 \001(\0132\026.goo" + "gle.protobuf.Value:\0028\001\"\352\001\n\005Value\0220\n\nnull" + "_value\030\001 \001(\0162\032.google.protobuf.NullValue" + "H\000\022\026\n\014number_value\030\002 \001(\001H\000\022\026\n\014string_val" + "ue\030\003 \001(\tH\000\022\024\n\nbool_value\030\004 \001(\010H\000\022/\n\014stru" + "ct_value\030\005 \001(\0132\027.google.protobuf.StructH" + "\000\0220\n\nlist_value\030\006 \001(\0132\032.google.protobuf." + "ListValueH\000B\006\n\004kind\"3\n\tListValue\022&\n\006valu" + "es\030\001 \003(\0132\026.google.protobuf.Value*\033\n\tNull" + "Value\022\016\n\nNULL_VALUE\020\000B\201\001\n\023com.google.pro" + "tobufB\013StructProtoP\001Z1github.com/golang/" + "protobuf/ptypes/struct;structpb\370\001\001\242\002\003GPB" + "\252\002\036Google.Protobuf.WellKnownTypesb\006proto" + "3" + ; +static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_google_2fprotobuf_2fstruct_2eproto_deps[1] = { +}; +static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_google_2fprotobuf_2fstruct_2eproto_sccs[1] = { + &scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto.base, +}; +static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fstruct_2eproto_once; +static bool descriptor_table_google_2fprotobuf_2fstruct_2eproto_initialized = false; +const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fstruct_2eproto = { + &descriptor_table_google_2fprotobuf_2fstruct_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fstruct_2eproto, "google/protobuf/struct.proto", 641, + &descriptor_table_google_2fprotobuf_2fstruct_2eproto_once, descriptor_table_google_2fprotobuf_2fstruct_2eproto_sccs, descriptor_table_google_2fprotobuf_2fstruct_2eproto_deps, 1, 0, + schemas, file_default_instances, TableStruct_google_2fprotobuf_2fstruct_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2fstruct_2eproto, 4, file_level_enum_descriptors_google_2fprotobuf_2fstruct_2eproto, file_level_service_descriptors_google_2fprotobuf_2fstruct_2eproto, +}; -void protobuf_AssignDescriptorsOnce() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); -} - -void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 4); -} - -void AddDescriptorsImpl() { - InitDefaults(); - static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - "\n\034google/protobuf/struct.proto\022\017google.p" - "rotobuf\"\204\001\n\006Struct\0223\n\006fields\030\001 \003(\0132#.goo" - "gle.protobuf.Struct.FieldsEntry\032E\n\013Field" - "sEntry\022\013\n\003key\030\001 \001(\t\022%\n\005value\030\002 \001(\0132\026.goo" - "gle.protobuf.Value:\0028\001\"\352\001\n\005Value\0220\n\nnull" - "_value\030\001 \001(\0162\032.google.protobuf.NullValue" - "H\000\022\026\n\014number_value\030\002 \001(\001H\000\022\026\n\014string_val" - "ue\030\003 \001(\tH\000\022\024\n\nbool_value\030\004 \001(\010H\000\022/\n\014stru" - "ct_value\030\005 \001(\0132\027.google.protobuf.StructH" - "\000\0220\n\nlist_value\030\006 \001(\0132\032.google.protobuf." - "ListValueH\000B\006\n\004kind\"3\n\tListValue\022&\n\006valu" - "es\030\001 \003(\0132\026.google.protobuf.Value*\033\n\tNull" - "Value\022\016\n\nNULL_VALUE\020\000B\201\001\n\023com.google.pro" - "tobufB\013StructProtoP\001Z1github.com/golang/" - "protobuf/ptypes/struct;structpb\370\001\001\242\002\003GPB" - "\252\002\036Google.Protobuf.WellKnownTypesb\006proto" - "3" - }; - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - descriptor, 641); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "google/protobuf/struct.proto", &protobuf_RegisterTypes); -} - -void AddDescriptors() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); -} -// Force AddDescriptors() to be called at dynamic initialization time. -struct StaticDescriptorInitializer { - StaticDescriptorInitializer() { - AddDescriptors(); - } -} static_descriptor_initializer; -} // namespace protobuf_google_2fprotobuf_2fstruct_2eproto -namespace google { -namespace protobuf { -const ::google::protobuf::EnumDescriptor* NullValue_descriptor() { - protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce(); - return protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_enum_descriptors[0]; +// Force running AddDescriptors() at dynamic initialization time. +static bool dynamic_init_dummy_google_2fprotobuf_2fstruct_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fstruct_2eproto), true); +PROTOBUF_NAMESPACE_OPEN +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* NullValue_descriptor() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_google_2fprotobuf_2fstruct_2eproto); + return file_level_enum_descriptors_google_2fprotobuf_2fstruct_2eproto[0]; } bool NullValue_IsValid(int value) { switch (value) { @@ -215,17 +177,17 @@ bool NullValue_IsValid(int value) { // =================================================================== Struct_FieldsEntry_DoNotUse::Struct_FieldsEntry_DoNotUse() {} -Struct_FieldsEntry_DoNotUse::Struct_FieldsEntry_DoNotUse(::google::protobuf::Arena* arena) : SuperType(arena) {} +Struct_FieldsEntry_DoNotUse::Struct_FieldsEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : SuperType(arena) {} void Struct_FieldsEntry_DoNotUse::MergeFrom(const Struct_FieldsEntry_DoNotUse& other) { MergeFromInternal(other); } -::google::protobuf::Metadata Struct_FieldsEntry_DoNotUse::GetMetadata() const { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[0]; +::PROTOBUF_NAMESPACE_ID::Metadata Struct_FieldsEntry_DoNotUse::GetMetadata() const { + return GetMetadataStatic(); } void Struct_FieldsEntry_DoNotUse::MergeFrom( - const ::google::protobuf::Message& other) { - ::google::protobuf::Message::MergeFrom(other); + const ::PROTOBUF_NAMESPACE_ID::Message& other) { + ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom(other); } @@ -233,35 +195,37 @@ void Struct_FieldsEntry_DoNotUse::MergeFrom( void Struct::InitAsDefaultInstance() { } +class Struct::HasBitSetters { + public: +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Struct::kFieldsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Struct::Struct() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Struct) } -Struct::Struct(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +Struct::Struct(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena), fields_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Struct) } Struct::Struct(const Struct& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); fields_.MergeFrom(from.fields_); // @@protoc_insertion_point(copy_constructor:google.protobuf.Struct) } void Struct::SharedCtor() { + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto.base); } Struct::~Struct() { @@ -270,32 +234,27 @@ Struct::~Struct() { } void Struct::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void Struct::ArenaDtor(void* object) { Struct* _this = reinterpret_cast< Struct* >(object); (void)_this; } -void Struct::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void Struct::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void Struct::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* Struct::descriptor() { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const Struct& Struct::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto.base); return *internal_default_instance(); } void Struct::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.Struct) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -303,32 +262,72 @@ void Struct::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* Struct::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // map fields = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(&fields_, ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 10); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Struct::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Struct) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // map fields = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - Struct_FieldsEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField< + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + Struct_FieldsEntry_DoNotUse::Parser< ::PROTOBUF_NAMESPACE_ID::internal::MapField< Struct_FieldsEntry_DoNotUse, - ::std::string, ::google::protobuf::Value, - ::google::protobuf::internal::WireFormatLite::TYPE_STRING, - ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, + std::string, PROTOBUF_NAMESPACE_ID::Value, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE, 0 >, - ::google::protobuf::Map< ::std::string, ::google::protobuf::Value > > parser(&fields_); - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( + ::PROTOBUF_NAMESPACE_ID::Map< std::string, PROTOBUF_NAMESPACE_ID::Value > > parser(&fields_); + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessageNoVirtual( input, &parser)); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( parser.key().data(), static_cast(parser.key().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "google.protobuf.Struct.FieldsEntry.key")); } else { goto handle_unusual; @@ -341,7 +340,7 @@ bool Struct::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -355,24 +354,25 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void Struct::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.Struct) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // map fields = 1; if (!this->fields().empty()) { - typedef ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_pointer + typedef ::PROTOBUF_NAMESPACE_ID::Map< std::string, PROTOBUF_NAMESPACE_ID::Value >::const_pointer ConstPtr; typedef ConstPtr SortItem; - typedef ::google::protobuf::internal::CompareByDerefFirst Less; + typedef ::PROTOBUF_NAMESPACE_ID::internal::CompareByDerefFirst Less; struct Utf8Check { static void Check(ConstPtr p) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast(p->first.length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Struct.FieldsEntry.key"); } }; @@ -381,118 +381,89 @@ void Struct::SerializeWithCachedSizes( this->fields().size() > 1) { ::std::unique_ptr items( new SortItem[this->fields().size()]); - typedef ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::size_type size_type; + typedef ::PROTOBUF_NAMESPACE_ID::Map< std::string, PROTOBUF_NAMESPACE_ID::Value >::size_type size_type; size_type n = 0; - for (::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_iterator + for (::PROTOBUF_NAMESPACE_ID::Map< std::string, PROTOBUF_NAMESPACE_ID::Value >::const_iterator it = this->fields().begin(); it != this->fields().end(); ++it, ++n) { items[static_cast(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast(n)], Less()); - ::std::unique_ptr entry; for (size_type i = 0; i < n; i++) { - entry.reset(fields_.NewEntryWrapper( - items[static_cast(i)]->first, items[static_cast(i)]->second)); - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 1, *entry, output); - if (entry->GetArena() != NULL) { - entry.release(); - } - Utf8Check::Check(items[static_cast(i)]); + Struct_FieldsEntry_DoNotUse::MapEntryWrapper entry(nullptr, items[static_cast(i)]->first, items[static_cast(i)]->second); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(1, entry, output); + Utf8Check::Check(&(*items[static_cast(i)])); } } else { - ::std::unique_ptr entry; - for (::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_iterator + for (::PROTOBUF_NAMESPACE_ID::Map< std::string, PROTOBUF_NAMESPACE_ID::Value >::const_iterator it = this->fields().begin(); it != this->fields().end(); ++it) { - entry.reset(fields_.NewEntryWrapper( - it->first, it->second)); - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 1, *entry, output); - if (entry->GetArena() != NULL) { - entry.release(); - } - Utf8Check::Check(&*it); + Struct_FieldsEntry_DoNotUse::MapEntryWrapper entry(nullptr, it->first, it->second); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(1, entry, output); + Utf8Check::Check(&(*it)); } } } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); + if (_internal_metadata_.have_unknown_fields()) { + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( + _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.Struct) } -::google::protobuf::uint8* Struct::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* Struct::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Struct) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // map fields = 1; if (!this->fields().empty()) { - typedef ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_pointer + typedef ::PROTOBUF_NAMESPACE_ID::Map< std::string, PROTOBUF_NAMESPACE_ID::Value >::const_pointer ConstPtr; typedef ConstPtr SortItem; - typedef ::google::protobuf::internal::CompareByDerefFirst Less; + typedef ::PROTOBUF_NAMESPACE_ID::internal::CompareByDerefFirst Less; struct Utf8Check { static void Check(ConstPtr p) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast(p->first.length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Struct.FieldsEntry.key"); } }; - if (deterministic && + if (false && this->fields().size() > 1) { ::std::unique_ptr items( new SortItem[this->fields().size()]); - typedef ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::size_type size_type; + typedef ::PROTOBUF_NAMESPACE_ID::Map< std::string, PROTOBUF_NAMESPACE_ID::Value >::size_type size_type; size_type n = 0; - for (::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_iterator + for (::PROTOBUF_NAMESPACE_ID::Map< std::string, PROTOBUF_NAMESPACE_ID::Value >::const_iterator it = this->fields().begin(); it != this->fields().end(); ++it, ++n) { items[static_cast(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast(n)], Less()); - ::std::unique_ptr entry; for (size_type i = 0; i < n; i++) { - entry.reset(fields_.NewEntryWrapper( - items[static_cast(i)]->first, items[static_cast(i)]->second)); - target = ::google::protobuf::internal::WireFormatLite:: - InternalWriteMessageNoVirtualToArray( - 1, *entry, deterministic, target); -; - if (entry->GetArena() != NULL) { - entry.release(); - } - Utf8Check::Check(items[static_cast(i)]); + Struct_FieldsEntry_DoNotUse::MapEntryWrapper entry(nullptr, items[static_cast(i)]->first, items[static_cast(i)]->second); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::InternalWriteMessageNoVirtualToArray(1, entry, target); + Utf8Check::Check(&(*items[static_cast(i)])); } } else { - ::std::unique_ptr entry; - for (::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_iterator + for (::PROTOBUF_NAMESPACE_ID::Map< std::string, PROTOBUF_NAMESPACE_ID::Value >::const_iterator it = this->fields().begin(); it != this->fields().end(); ++it) { - entry.reset(fields_.NewEntryWrapper( - it->first, it->second)); - target = ::google::protobuf::internal::WireFormatLite:: - InternalWriteMessageNoVirtualToArray( - 1, *entry, deterministic, target); -; - if (entry->GetArena() != NULL) { - entry.release(); - } - Utf8Check::Check(&*it); + Struct_FieldsEntry_DoNotUse::MapEntryWrapper entry(nullptr, it->first, it->second); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::InternalWriteMessageNoVirtualToArray(1, entry, target); + Utf8Check::Check(&(*it)); } } } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); + if (_internal_metadata_.have_unknown_fields()) { + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( + _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Struct) return target; @@ -502,45 +473,40 @@ size_t Struct::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.protobuf.Struct) size_t total_size = 0; - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { + if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( + _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // map fields = 1; total_size += 1 * - ::google::protobuf::internal::FromIntSize(this->fields_size()); - { - ::std::unique_ptr entry; - for (::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_iterator - it = this->fields().begin(); - it != this->fields().end(); ++it) { - if (entry.get() != NULL && entry->GetArena() != NULL) { - entry.release(); - } - entry.reset(fields_.NewEntryWrapper(it->first, it->second)); - total_size += ::google::protobuf::internal::WireFormatLite:: - MessageSizeNoVirtual(*entry); - } - if (entry.get() != NULL && entry->GetArena() != NULL) { - entry.release(); - } + ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->fields_size()); + for (::PROTOBUF_NAMESPACE_ID::Map< std::string, PROTOBUF_NAMESPACE_ID::Value >::const_iterator + it = this->fields().begin(); + it != this->fields().end(); ++it) { + Struct_FieldsEntry_DoNotUse::MapEntryWrapper entry(nullptr, it->first, it->second); + total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: + MessageSizeNoVirtual(entry); } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void Struct::MergeFrom(const ::google::protobuf::Message& from) { +void Struct::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Struct) GOOGLE_DCHECK_NE(&from, this); const Struct* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Struct) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Struct) MergeFrom(*source); @@ -551,13 +517,13 @@ void Struct::MergeFrom(const Struct& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Struct) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; fields_.MergeFrom(from.fields_); } -void Struct::CopyFrom(const ::google::protobuf::Message& from) { +void Struct::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Struct) if (&from == this) return; Clear(); @@ -584,7 +550,7 @@ void Struct::Swap(Struct* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -596,37 +562,50 @@ void Struct::UnsafeArenaSwap(Struct* other) { } void Struct::InternalSwap(Struct* other) { using std::swap; - fields_.Swap(&other->fields_); _internal_metadata_.Swap(&other->_internal_metadata_); + fields_.Swap(&other->fields_); } -::google::protobuf::Metadata Struct::GetMetadata() const { - protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata Struct::GetMetadata() const { + return GetMetadataStatic(); } // =================================================================== void Value::InitAsDefaultInstance() { - ::google::protobuf::_Value_default_instance_.null_value_ = 0; - ::google::protobuf::_Value_default_instance_.number_value_ = 0; - ::google::protobuf::_Value_default_instance_.string_value_.UnsafeSetDefault( - &::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ::google::protobuf::_Value_default_instance_.bool_value_ = false; - ::google::protobuf::_Value_default_instance_.struct_value_ = const_cast< ::google::protobuf::Struct*>( - ::google::protobuf::Struct::internal_default_instance()); - ::google::protobuf::_Value_default_instance_.list_value_ = const_cast< ::google::protobuf::ListValue*>( - ::google::protobuf::ListValue::internal_default_instance()); + PROTOBUF_NAMESPACE_ID::_Value_default_instance_.null_value_ = 0; + PROTOBUF_NAMESPACE_ID::_Value_default_instance_.number_value_ = 0; + PROTOBUF_NAMESPACE_ID::_Value_default_instance_.string_value_.UnsafeSetDefault( + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + PROTOBUF_NAMESPACE_ID::_Value_default_instance_.bool_value_ = false; + PROTOBUF_NAMESPACE_ID::_Value_default_instance_.struct_value_ = const_cast< PROTOBUF_NAMESPACE_ID::Struct*>( + PROTOBUF_NAMESPACE_ID::Struct::internal_default_instance()); + PROTOBUF_NAMESPACE_ID::_Value_default_instance_.list_value_ = const_cast< PROTOBUF_NAMESPACE_ID::ListValue*>( + PROTOBUF_NAMESPACE_ID::ListValue::internal_default_instance()); } -void Value::set_allocated_struct_value(::google::protobuf::Struct* struct_value) { - ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); +class Value::HasBitSetters { + public: + static const PROTOBUF_NAMESPACE_ID::Struct& struct_value(const Value* msg); + static const PROTOBUF_NAMESPACE_ID::ListValue& list_value(const Value* msg); +}; + +const PROTOBUF_NAMESPACE_ID::Struct& +Value::HasBitSetters::struct_value(const Value* msg) { + return *msg->kind_.struct_value_; +} +const PROTOBUF_NAMESPACE_ID::ListValue& +Value::HasBitSetters::list_value(const Value* msg) { + return *msg->kind_.list_value_; +} +void Value::set_allocated_struct_value(PROTOBUF_NAMESPACE_ID::Struct* struct_value) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); clear_kind(); if (struct_value) { - ::google::protobuf::Arena* submessage_arena = - ::google::protobuf::Arena::GetArena(struct_value); + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::GetArena(struct_value); if (message_arena != submessage_arena) { - struct_value = ::google::protobuf::internal::GetOwnedMessage( + struct_value = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, struct_value, submessage_arena); } set_has_struct_value(); @@ -634,14 +613,14 @@ void Value::set_allocated_struct_value(::google::protobuf::Struct* struct_value) } // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.struct_value) } -void Value::set_allocated_list_value(::google::protobuf::ListValue* list_value) { - ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); +void Value::set_allocated_list_value(PROTOBUF_NAMESPACE_ID::ListValue* list_value) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); clear_kind(); if (list_value) { - ::google::protobuf::Arena* submessage_arena = - ::google::protobuf::Arena::GetArena(list_value); + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::GetArena(list_value); if (message_arena != submessage_arena) { - list_value = ::google::protobuf::internal::GetOwnedMessage( + list_value = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, list_value, submessage_arena); } set_has_list_value(); @@ -659,23 +638,20 @@ const int Value::kListValueFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Value::Value() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Value) } -Value::Value(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +Value::Value(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Value) } Value::Value(const Value& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); clear_has_kind(); switch (from.kind_case()) { @@ -696,11 +672,11 @@ Value::Value(const Value& from) break; } case kStructValue: { - mutable_struct_value()->::google::protobuf::Struct::MergeFrom(from.struct_value()); + mutable_struct_value()->PROTOBUF_NAMESPACE_ID::Struct::MergeFrom(from.struct_value()); break; } case kListValue: { - mutable_list_value()->::google::protobuf::ListValue::MergeFrom(from.list_value()); + mutable_list_value()->PROTOBUF_NAMESPACE_ID::ListValue::MergeFrom(from.list_value()); break; } case KIND_NOT_SET: { @@ -711,6 +687,7 @@ Value::Value(const Value& from) } void Value::SharedCtor() { + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto.base); clear_has_kind(); } @@ -720,7 +697,7 @@ Value::~Value() { } void Value::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); if (has_kind()) { clear_kind(); } @@ -730,18 +707,13 @@ void Value::ArenaDtor(void* object) { Value* _this = reinterpret_cast< Value* >(object); (void)_this; } -void Value::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void Value::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void Value::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* Value::descriptor() { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const Value& Value::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto.base); return *internal_default_instance(); } @@ -758,7 +730,7 @@ void Value::clear_kind() { break; } case kStringValue: { - kind_.string_value_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + kind_.string_value_.Destroy(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); break; } @@ -767,13 +739,13 @@ void Value::clear_kind() { break; } case kStructValue: { - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete kind_.struct_value_; } break; } case kListValue: { - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete kind_.list_value_; } break; @@ -788,7 +760,7 @@ void Value::clear_kind() { void Value::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.Value) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -796,25 +768,96 @@ void Value::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* Value::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // .google.protobuf.NullValue null_value = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { + ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + set_null_value(static_cast(val)); + } else goto handle_unusual; + continue; + // double number_value = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 17)) { + set_number_value(::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad(ptr)); + ptr += sizeof(double); + } else goto handle_unusual; + continue; + // string string_value = 3; + case 3: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(mutable_string_value(), ptr, ctx, "google.protobuf.Value.string_value"); + CHK_(ptr); + } else goto handle_unusual; + continue; + // bool bool_value = 4; + case 4: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { + set_bool_value(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr)); + CHK_(ptr); + } else goto handle_unusual; + continue; + // .google.protobuf.Struct struct_value = 5; + case 5: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) { + ptr = ctx->ParseMessage(mutable_struct_value(), ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // .google.protobuf.ListValue list_value = 6; + case 6: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) { + ptr = ctx->ParseMessage(mutable_list_value(), ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Value::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Value) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // .google.protobuf.NullValue null_value = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { - int value; - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) { + int value = 0; + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>( input, &value))); - set_null_value(static_cast< ::google::protobuf::NullValue >(value)); + set_null_value(static_cast< PROTOBUF_NAMESPACE_ID::NullValue >(value)); } else { goto handle_unusual; } @@ -823,11 +866,10 @@ bool Value::MergePartialFromCodedStream( // double number_value = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(17u /* 17 & 0xFF */)) { + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (17 & 0xFF)) { clear_kind(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + double, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_DOUBLE>( input, &kind_.number_value_))); set_has_number_value(); } else { @@ -838,13 +880,12 @@ bool Value::MergePartialFromCodedStream( // string string_value = 3; case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString( input, this->mutable_string_value())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->string_value().data(), static_cast(this->string_value().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "google.protobuf.Value.string_value")); } else { goto handle_unusual; @@ -854,11 +895,10 @@ bool Value::MergePartialFromCodedStream( // bool bool_value = 4; case 4: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) { + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (32 & 0xFF)) { clear_kind(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL>( input, &kind_.bool_value_))); set_has_bool_value(); } else { @@ -869,9 +909,8 @@ bool Value::MergePartialFromCodedStream( // .google.protobuf.Struct struct_value = 5; case 5: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (42 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, mutable_struct_value())); } else { goto handle_unusual; @@ -881,9 +920,8 @@ bool Value::MergePartialFromCodedStream( // .google.protobuf.ListValue list_value = 6; case 6: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (50 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, mutable_list_value())); } else { goto handle_unusual; @@ -896,7 +934,7 @@ bool Value::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -910,109 +948,109 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void Value::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.Value) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.protobuf.NullValue null_value = 1; if (has_null_value()) { - ::google::protobuf::internal::WireFormatLite::WriteEnum( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum( 1, this->null_value(), output); } // double number_value = 2; if (has_number_value()) { - ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->number_value(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteDouble(2, this->number_value(), output); } // string string_value = 3; if (has_string_value()) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->string_value().data(), static_cast(this->string_value().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Value.string_value"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased( 3, this->string_value(), output); } // bool bool_value = 4; if (has_bool_value()) { - ::google::protobuf::internal::WireFormatLite::WriteBool(4, this->bool_value(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBool(4, this->bool_value(), output); } // .google.protobuf.Struct struct_value = 5; if (has_struct_value()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 5, this->_internal_struct_value(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( + 5, HasBitSetters::struct_value(this), output); } // .google.protobuf.ListValue list_value = 6; if (has_list_value()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 6, this->_internal_list_value(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( + 6, HasBitSetters::list_value(this), output); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); + if (_internal_metadata_.have_unknown_fields()) { + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( + _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.Value) } -::google::protobuf::uint8* Value::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* Value::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Value) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.protobuf.NullValue null_value = 1; if (has_null_value()) { - target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray( 1, this->null_value(), target); } // double number_value = 2; if (has_number_value()) { - target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->number_value(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteDoubleToArray(2, this->number_value(), target); } // string string_value = 3; if (has_string_value()) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->string_value().data(), static_cast(this->string_value().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "google.protobuf.Value.string_value"); target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray( 3, this->string_value(), target); } // bool bool_value = 4; if (has_bool_value()) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(4, this->bool_value(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(4, this->bool_value(), target); } // .google.protobuf.Struct struct_value = 5; if (has_struct_value()) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 5, this->_internal_struct_value(), deterministic, target); + 5, HasBitSetters::struct_value(this), target); } // .google.protobuf.ListValue list_value = 6; if (has_list_value()) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 6, this->_internal_list_value(), deterministic, target); + 6, HasBitSetters::list_value(this), target); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); + if (_internal_metadata_.have_unknown_fields()) { + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( + _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Value) return target; @@ -1022,16 +1060,20 @@ size_t Value::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.protobuf.Value) size_t total_size = 0; - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { + if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( + _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + switch (kind_case()) { // .google.protobuf.NullValue null_value = 1; case kNullValue: { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::EnumSize(this->null_value()); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->null_value()); break; } // double number_value = 2; @@ -1042,7 +1084,7 @@ size_t Value::ByteSizeLong() const { // string string_value = 3; case kStringValue: { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->string_value()); break; } @@ -1054,14 +1096,14 @@ size_t Value::ByteSizeLong() const { // .google.protobuf.Struct struct_value = 5; case kStructValue: { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *kind_.struct_value_); break; } // .google.protobuf.ListValue list_value = 6; case kListValue: { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *kind_.list_value_); break; } @@ -1069,20 +1111,20 @@ size_t Value::ByteSizeLong() const { break; } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void Value::MergeFrom(const ::google::protobuf::Message& from) { +void Value::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Value) GOOGLE_DCHECK_NE(&from, this); const Value* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Value) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Value) MergeFrom(*source); @@ -1093,7 +1135,7 @@ void Value::MergeFrom(const Value& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Value) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; switch (from.kind_case()) { @@ -1114,11 +1156,11 @@ void Value::MergeFrom(const Value& from) { break; } case kStructValue: { - mutable_struct_value()->::google::protobuf::Struct::MergeFrom(from.struct_value()); + mutable_struct_value()->PROTOBUF_NAMESPACE_ID::Struct::MergeFrom(from.struct_value()); break; } case kListValue: { - mutable_list_value()->::google::protobuf::ListValue::MergeFrom(from.list_value()); + mutable_list_value()->PROTOBUF_NAMESPACE_ID::ListValue::MergeFrom(from.list_value()); break; } case KIND_NOT_SET: { @@ -1127,7 +1169,7 @@ void Value::MergeFrom(const Value& from) { } } -void Value::CopyFrom(const ::google::protobuf::Message& from) { +void Value::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Value) if (&from == this) return; Clear(); @@ -1154,7 +1196,7 @@ void Value::Swap(Value* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -1166,14 +1208,13 @@ void Value::UnsafeArenaSwap(Value* other) { } void Value::InternalSwap(Value* other) { using std::swap; + _internal_metadata_.Swap(&other->_internal_metadata_); swap(kind_, other->kind_); swap(_oneof_case_[0], other->_oneof_case_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata Value::GetMetadata() const { - protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata Value::GetMetadata() const { + return GetMetadataStatic(); } @@ -1181,35 +1222,37 @@ void Value::InternalSwap(Value* other) { void ListValue::InitAsDefaultInstance() { } +class ListValue::HasBitSetters { + public: +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int ListValue::kValuesFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 ListValue::ListValue() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.ListValue) } -ListValue::ListValue(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +ListValue::ListValue(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena), values_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.ListValue) } ListValue::ListValue(const ListValue& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr), values_(from.values_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.ListValue) } void ListValue::SharedCtor() { + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto.base); } ListValue::~ListValue() { @@ -1218,32 +1261,27 @@ ListValue::~ListValue() { } void ListValue::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void ListValue::ArenaDtor(void* object) { ListValue* _this = reinterpret_cast< ListValue* >(object); (void)_this; } -void ListValue::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void ListValue::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void ListValue::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* ListValue::descriptor() { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const ListValue& ListValue::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto.base); return *internal_default_instance(); } void ListValue::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.ListValue) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -1251,21 +1289,61 @@ void ListValue::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* ListValue::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // repeated .google.protobuf.Value values = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { + ptr -= 1; + do { + ptr += 1; + ptr = ctx->ParseMessage(add_values(), ptr); + CHK_(ptr); + if (!ctx->DataAvailable(ptr)) break; + } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 10); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool ListValue::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.ListValue) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .google.protobuf.Value values = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_values())); } else { goto handle_unusual; @@ -1278,7 +1356,7 @@ bool ListValue::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -1292,47 +1370,47 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void ListValue::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.ListValue) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .google.protobuf.Value values = 1; for (unsigned int i = 0, n = static_cast(this->values_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->values(static_cast(i)), output); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); + if (_internal_metadata_.have_unknown_fields()) { + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( + _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.ListValue) } -::google::protobuf::uint8* ListValue::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* ListValue::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.ListValue) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .google.protobuf.Value values = 1; for (unsigned int i = 0, n = static_cast(this->values_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( - 1, this->values(static_cast(i)), deterministic, target); + 1, this->values(static_cast(i)), target); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); + if (_internal_metadata_.have_unknown_fields()) { + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( + _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.ListValue) return target; @@ -1342,36 +1420,40 @@ size_t ListValue::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.protobuf.ListValue) size_t total_size = 0; - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { + if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( + _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // repeated .google.protobuf.Value values = 1; { unsigned int count = static_cast(this->values_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->values(static_cast(i))); } } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void ListValue::MergeFrom(const ::google::protobuf::Message& from) { +void ListValue::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.ListValue) GOOGLE_DCHECK_NE(&from, this); const ListValue* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.ListValue) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.ListValue) MergeFrom(*source); @@ -1382,13 +1464,13 @@ void ListValue::MergeFrom(const ListValue& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.ListValue) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; values_.MergeFrom(from.values_); } -void ListValue::CopyFrom(const ::google::protobuf::Message& from) { +void ListValue::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.ListValue) if (&from == this) return; Clear(); @@ -1415,7 +1497,7 @@ void ListValue::Swap(ListValue* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -1427,34 +1509,31 @@ void ListValue::UnsafeArenaSwap(ListValue* other) { } void ListValue::InternalSwap(ListValue* other) { using std::swap; - CastToBase(&values_)->InternalSwap(CastToBase(&other->values_)); _internal_metadata_.Swap(&other->_internal_metadata_); + CastToBase(&values_)->InternalSwap(CastToBase(&other->values_)); } -::google::protobuf::Metadata ListValue::GetMetadata() const { - protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata ListValue::GetMetadata() const { + return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMaybeMessage< ::google::protobuf::Struct_FieldsEntry_DoNotUse >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::Struct_FieldsEntry_DoNotUse >(arena); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Struct* Arena::CreateMaybeMessage< ::google::protobuf::Struct >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::Struct >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::Struct* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Struct >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::Struct >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Value* Arena::CreateMaybeMessage< ::google::protobuf::Value >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::Value >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::Value* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Value >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::Value >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ListValue* Arena::CreateMaybeMessage< ::google::protobuf::ListValue >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::ListValue >(arena); +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::ListValue* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::ListValue >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::ListValue >(arena); } -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) +#include diff --git a/third_party/protobuf/src/google/protobuf/struct.pb.h b/third_party/protobuf/src/google/protobuf/struct.pb.h index 1cf75d9b..b5c78bd0 100644 --- a/third_party/protobuf/src/google/protobuf/struct.pb.h +++ b/third_party/protobuf/src/google/protobuf/struct.pb.h @@ -1,24 +1,25 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/struct.proto -#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto -#define PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto +#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto +#include #include -#include - -#if GOOGLE_PROTOBUF_VERSION < 3006001 +#include +#if PROTOBUF_VERSION < 3008000 #error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update +#error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3008000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please +#error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include @@ -26,6 +27,7 @@ #include #include #include +#include #include #include // IWYU pragma: export #include // IWYU pragma: export @@ -35,107 +37,123 @@ #include #include // @@protoc_insertion_point(includes) -#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fstruct_2eproto LIBPROTOBUF_EXPORT +#include +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fstruct_2eproto PROTOBUF_EXPORT +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE -namespace protobuf_google_2fprotobuf_2fstruct_2eproto { // Internal implementation detail -- do not use these members. -struct LIBPROTOBUF_EXPORT TableStruct { - static const ::google::protobuf::internal::ParseTableField entries[]; - static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; - static const ::google::protobuf::internal::ParseTable schema[4]; - static const ::google::protobuf::internal::FieldMetadata field_metadata[]; - static const ::google::protobuf::internal::SerializationTable serialization_table[]; - static const ::google::protobuf::uint32 offsets[]; +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fstruct_2eproto { + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[4] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; + static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; + static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; -void LIBPROTOBUF_EXPORT AddDescriptors(); -} // namespace protobuf_google_2fprotobuf_2fstruct_2eproto -namespace google { -namespace protobuf { +extern PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fstruct_2eproto; +PROTOBUF_NAMESPACE_OPEN class ListValue; class ListValueDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern ListValueDefaultTypeInternal _ListValue_default_instance_; +PROTOBUF_EXPORT extern ListValueDefaultTypeInternal _ListValue_default_instance_; class Struct; class StructDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern StructDefaultTypeInternal _Struct_default_instance_; +PROTOBUF_EXPORT extern StructDefaultTypeInternal _Struct_default_instance_; class Struct_FieldsEntry_DoNotUse; class Struct_FieldsEntry_DoNotUseDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern Struct_FieldsEntry_DoNotUseDefaultTypeInternal _Struct_FieldsEntry_DoNotUse_default_instance_; +PROTOBUF_EXPORT extern Struct_FieldsEntry_DoNotUseDefaultTypeInternal _Struct_FieldsEntry_DoNotUse_default_instance_; class Value; class ValueDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern ValueDefaultTypeInternal _Value_default_instance_; -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::ListValue* Arena::CreateMaybeMessage<::google::protobuf::ListValue>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Struct* Arena::CreateMaybeMessage<::google::protobuf::Struct>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMaybeMessage<::google::protobuf::Struct_FieldsEntry_DoNotUse>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Value* Arena::CreateMaybeMessage<::google::protobuf::Value>(Arena*); -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { +PROTOBUF_EXPORT extern ValueDefaultTypeInternal _Value_default_instance_; +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::ListValue* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::Struct* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse* Arena::CreateMaybeMessage(Arena*); +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::Value* Arena::CreateMaybeMessage(Arena*); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN -enum NullValue { +enum NullValue : int { NULL_VALUE = 0, - NullValue_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min, - NullValue_INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max + NullValue_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::PROTOBUF_NAMESPACE_ID::int32>::min(), + NullValue_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::PROTOBUF_NAMESPACE_ID::int32>::max() }; -LIBPROTOBUF_EXPORT bool NullValue_IsValid(int value); -const NullValue NullValue_MIN = NULL_VALUE; -const NullValue NullValue_MAX = NULL_VALUE; -const int NullValue_ARRAYSIZE = NullValue_MAX + 1; +PROTOBUF_EXPORT bool NullValue_IsValid(int value); +constexpr NullValue NullValue_MIN = NULL_VALUE; +constexpr NullValue NullValue_MAX = NULL_VALUE; +constexpr int NullValue_ARRAYSIZE = NullValue_MAX + 1; -LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* NullValue_descriptor(); -inline const ::std::string& NullValue_Name(NullValue value) { - return ::google::protobuf::internal::NameOfEnum( - NullValue_descriptor(), value); +PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* NullValue_descriptor(); +template +inline const std::string& NullValue_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function NullValue_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + NullValue_descriptor(), enum_t_value); } inline bool NullValue_Parse( - const ::std::string& name, NullValue* value) { - return ::google::protobuf::internal::ParseNamedEnum( + const std::string& name, NullValue* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( NullValue_descriptor(), name, value); } // =================================================================== -class Struct_FieldsEntry_DoNotUse : public ::google::protobuf::internal::MapEntry { public: - typedef ::google::protobuf::internal::MapEntry SuperType; Struct_FieldsEntry_DoNotUse(); - Struct_FieldsEntry_DoNotUse(::google::protobuf::Arena* arena); + Struct_FieldsEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const Struct_FieldsEntry_DoNotUse& other); static const Struct_FieldsEntry_DoNotUse* internal_default_instance() { return reinterpret_cast(&_Struct_FieldsEntry_DoNotUse_default_instance_); } - void MergeFrom(const ::google::protobuf::Message& other) final; - ::google::protobuf::Metadata GetMetadata() const; + static bool ValidateKey(std::string* s) { + return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), s->size(), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "google.protobuf.Struct.FieldsEntry.key"); + } + static bool ValidateValue(void*) { return true; } + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& other) final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fstruct_2eproto); + return ::descriptor_table_google_2fprotobuf_2fstruct_2eproto.file_level_metadata[0]; + } + + public: }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Struct) */ { +class PROTOBUF_EXPORT Struct : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Struct) */ { public: Struct(); virtual ~Struct(); Struct(const Struct& from); - - inline Struct& operator=(const Struct& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 Struct(Struct&& from) noexcept : Struct() { *this = ::std::move(from); } + inline Struct& operator=(const Struct& from) { + CopyFrom(from); + return *this; + } inline Struct& operator=(Struct&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -144,14 +162,22 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc } return *this; } - #endif - inline ::google::protobuf::Arena* GetArena() const final { + + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const Struct& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -171,40 +197,48 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc // implements Message ---------------------------------------------- inline Struct* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - Struct* New(::google::protobuf::Arena* arena) const final { + Struct* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const Struct& from); void MergeFrom(const Struct& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Struct* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Struct"; + } protected: - explicit Struct(::google::protobuf::Arena* arena); + explicit Struct(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -212,7 +246,14 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fstruct_2eproto); + return ::descriptor_table_google_2fprotobuf_2fstruct_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -223,46 +264,46 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc int fields_size() const; void clear_fields(); static const int kFieldsFieldNumber = 1; - const ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >& + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, PROTOBUF_NAMESPACE_ID::Value >& fields() const; - ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >* + ::PROTOBUF_NAMESPACE_ID::Map< std::string, PROTOBUF_NAMESPACE_ID::Value >* mutable_fields(); // @@protoc_insertion_point(class_scope:google.protobuf.Struct) private: + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::internal::MapField< + ::PROTOBUF_NAMESPACE_ID::internal::MapField< Struct_FieldsEntry_DoNotUse, - ::std::string, ::google::protobuf::Value, - ::google::protobuf::internal::WireFormatLite::TYPE_STRING, - ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, + std::string, PROTOBUF_NAMESPACE_ID::Value, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE, 0 > fields_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2fstruct_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Value) */ { +class PROTOBUF_EXPORT Value : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Value) */ { public: Value(); virtual ~Value(); Value(const Value& from); - - inline Value& operator=(const Value& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 Value(Value&& from) noexcept : Value() { *this = ::std::move(from); } + inline Value& operator=(const Value& from) { + CopyFrom(from); + return *this; + } inline Value& operator=(Value&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -271,14 +312,22 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ } return *this; } - #endif - inline ::google::protobuf::Arena* GetArena() const final { + + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const Value& default_instance(); enum KindCase { @@ -308,40 +357,48 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ // implements Message ---------------------------------------------- inline Value* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - Value* New(::google::protobuf::Arena* arena) const final { + Value* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const Value& from); void MergeFrom(const Value& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Value* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Value"; + } protected: - explicit Value(::google::protobuf::Arena* arena); + explicit Value(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -349,7 +406,14 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fstruct_2eproto); + return ::descriptor_table_google_2fprotobuf_2fstruct_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -361,8 +425,8 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ public: void clear_null_value(); static const int kNullValueFieldNumber = 1; - ::google::protobuf::NullValue null_value() const; - void set_null_value(::google::protobuf::NullValue value); + PROTOBUF_NAMESPACE_ID::NullValue null_value() const; + void set_null_value(PROTOBUF_NAMESPACE_ID::NullValue value); // double number_value = 2; private: @@ -379,25 +443,23 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ public: void clear_string_value(); static const int kStringValueFieldNumber = 3; - const ::std::string& string_value() const; - void set_string_value(const ::std::string& value); - #if LANG_CXX11 - void set_string_value(::std::string&& value); - #endif + const std::string& string_value() const; + void set_string_value(const std::string& value); + void set_string_value(std::string&& value); void set_string_value(const char* value); void set_string_value(const char* value, size_t size); - ::std::string* mutable_string_value(); - ::std::string* release_string_value(); - void set_allocated_string_value(::std::string* string_value); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* mutable_string_value(); + std::string* release_string_value(); + void set_allocated_string_value(std::string* string_value); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") - ::std::string* unsafe_arena_release_string_value(); - PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + std::string* unsafe_arena_release_string_value(); + GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_string_value( - ::std::string* string_value); + std::string* string_value); // bool bool_value = 4; private: @@ -412,36 +474,31 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ bool has_struct_value() const; void clear_struct_value(); static const int kStructValueFieldNumber = 5; - private: - const ::google::protobuf::Struct& _internal_struct_value() const; - public: - const ::google::protobuf::Struct& struct_value() const; - ::google::protobuf::Struct* release_struct_value(); - ::google::protobuf::Struct* mutable_struct_value(); - void set_allocated_struct_value(::google::protobuf::Struct* struct_value); + const PROTOBUF_NAMESPACE_ID::Struct& struct_value() const; + PROTOBUF_NAMESPACE_ID::Struct* release_struct_value(); + PROTOBUF_NAMESPACE_ID::Struct* mutable_struct_value(); + void set_allocated_struct_value(PROTOBUF_NAMESPACE_ID::Struct* struct_value); void unsafe_arena_set_allocated_struct_value( - ::google::protobuf::Struct* struct_value); - ::google::protobuf::Struct* unsafe_arena_release_struct_value(); + PROTOBUF_NAMESPACE_ID::Struct* struct_value); + PROTOBUF_NAMESPACE_ID::Struct* unsafe_arena_release_struct_value(); // .google.protobuf.ListValue list_value = 6; bool has_list_value() const; void clear_list_value(); static const int kListValueFieldNumber = 6; - private: - const ::google::protobuf::ListValue& _internal_list_value() const; - public: - const ::google::protobuf::ListValue& list_value() const; - ::google::protobuf::ListValue* release_list_value(); - ::google::protobuf::ListValue* mutable_list_value(); - void set_allocated_list_value(::google::protobuf::ListValue* list_value); + const PROTOBUF_NAMESPACE_ID::ListValue& list_value() const; + PROTOBUF_NAMESPACE_ID::ListValue* release_list_value(); + PROTOBUF_NAMESPACE_ID::ListValue* mutable_list_value(); + void set_allocated_list_value(PROTOBUF_NAMESPACE_ID::ListValue* list_value); void unsafe_arena_set_allocated_list_value( - ::google::protobuf::ListValue* list_value); - ::google::protobuf::ListValue* unsafe_arena_release_list_value(); + PROTOBUF_NAMESPACE_ID::ListValue* list_value); + PROTOBUF_NAMESPACE_ID::ListValue* unsafe_arena_release_list_value(); void clear_kind(); KindCase kind_case() const; // @@protoc_insertion_point(class_scope:google.protobuf.Value) private: + class HasBitSetters; void set_has_null_value(); void set_has_number_value(); void set_has_string_value(); @@ -452,43 +509,42 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ inline bool has_kind() const; inline void clear_has_kind(); - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; union KindUnion { KindUnion() {} int null_value_; double number_value_; - ::google::protobuf::internal::ArenaStringPtr string_value_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr string_value_; bool bool_value_; - ::google::protobuf::Struct* struct_value_; - ::google::protobuf::ListValue* list_value_; + PROTOBUF_NAMESPACE_ID::Struct* struct_value_; + PROTOBUF_NAMESPACE_ID::ListValue* list_value_; } kind_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::uint32 _oneof_case_[1]; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::uint32 _oneof_case_[1]; - friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct; + friend struct ::TableStruct_google_2fprotobuf_2fstruct_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ListValue) */ { +class PROTOBUF_EXPORT ListValue : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ListValue) */ { public: ListValue(); virtual ~ListValue(); ListValue(const ListValue& from); - - inline ListValue& operator=(const ListValue& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 ListValue(ListValue&& from) noexcept : ListValue() { *this = ::std::move(from); } + inline ListValue& operator=(const ListValue& from) { + CopyFrom(from); + return *this; + } inline ListValue& operator=(ListValue&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -497,14 +553,22 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro } return *this; } - #endif - inline ::google::protobuf::Arena* GetArena() const final { + + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const ListValue& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -524,40 +588,48 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro // implements Message ---------------------------------------------- inline ListValue* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - ListValue* New(::google::protobuf::Arena* arena) const final { + ListValue* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const ListValue& from); void MergeFrom(const ListValue& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(ListValue* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.ListValue"; + } protected: - explicit ListValue(::google::protobuf::Arena* arena); + explicit ListValue(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -565,7 +637,14 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2fstruct_2eproto); + return ::descriptor_table_google_2fprotobuf_2fstruct_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -575,24 +654,25 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro int values_size() const; void clear_values(); static const int kValuesFieldNumber = 1; - ::google::protobuf::Value* mutable_values(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Value >* + PROTOBUF_NAMESPACE_ID::Value* mutable_values(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Value >* mutable_values(); - const ::google::protobuf::Value& values(int index) const; - ::google::protobuf::Value* add_values(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Value >& + const PROTOBUF_NAMESPACE_ID::Value& values(int index) const; + PROTOBUF_NAMESPACE_ID::Value* add_values(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Value >& values() const; // @@protoc_insertion_point(class_scope:google.protobuf.ListValue) private: + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Value > values_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Value > values_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2fstruct_2eproto; }; // =================================================================== @@ -614,12 +694,12 @@ inline int Struct::fields_size() const { inline void Struct::clear_fields() { fields_.Clear(); } -inline const ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >& +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, PROTOBUF_NAMESPACE_ID::Value >& Struct::fields() const { // @@protoc_insertion_point(field_map:google.protobuf.Struct.fields) return fields_.GetMap(); } -inline ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >* +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, PROTOBUF_NAMESPACE_ID::Value >* Struct::mutable_fields() { // @@protoc_insertion_point(field_mutable_map:google.protobuf.Struct.fields) return fields_.MutableMap(); @@ -642,14 +722,14 @@ inline void Value::clear_null_value() { clear_has_kind(); } } -inline ::google::protobuf::NullValue Value::null_value() const { +inline PROTOBUF_NAMESPACE_ID::NullValue Value::null_value() const { // @@protoc_insertion_point(field_get:google.protobuf.Value.null_value) if (has_null_value()) { - return static_cast< ::google::protobuf::NullValue >(kind_.null_value_); + return static_cast< PROTOBUF_NAMESPACE_ID::NullValue >(kind_.null_value_); } - return static_cast< ::google::protobuf::NullValue >(0); + return static_cast< PROTOBUF_NAMESPACE_ID::NullValue >(0); } -inline void Value::set_null_value(::google::protobuf::NullValue value) { +inline void Value::set_null_value(PROTOBUF_NAMESPACE_ID::NullValue value) { if (!has_null_value()) { clear_kind(); set_has_null_value(); @@ -696,49 +776,47 @@ inline void Value::set_has_string_value() { } inline void Value::clear_string_value() { if (has_string_value()) { - kind_.string_value_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + kind_.string_value_.Destroy(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); clear_has_kind(); } } -inline const ::std::string& Value::string_value() const { +inline const std::string& Value::string_value() const { // @@protoc_insertion_point(field_get:google.protobuf.Value.string_value) if (has_string_value()) { return kind_.string_value_.Get(); } - return *&::google::protobuf::internal::GetEmptyStringAlreadyInited(); + return *&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(); } -inline void Value::set_string_value(const ::std::string& value) { +inline void Value::set_string_value(const std::string& value) { if (!has_string_value()) { clear_kind(); set_has_string_value(); - kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + kind_.string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } - kind_.string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, + kind_.string_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:google.protobuf.Value.string_value) } -#if LANG_CXX11 -inline void Value::set_string_value(::std::string&& value) { +inline void Value::set_string_value(std::string&& value) { // @@protoc_insertion_point(field_set:google.protobuf.Value.string_value) if (!has_string_value()) { clear_kind(); set_has_string_value(); - kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + kind_.string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } kind_.string_value_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Value.string_value) } -#endif inline void Value::set_string_value(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); if (!has_string_value()) { clear_kind(); set_has_string_value(); - kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + kind_.string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } - kind_.string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + kind_.string_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:google.protobuf.Value.string_value) } @@ -747,66 +825,64 @@ inline void Value::set_string_value(const char* value, if (!has_string_value()) { clear_kind(); set_has_string_value(); - kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + kind_.string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } kind_.string_value_.Set( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:google.protobuf.Value.string_value) } -inline ::std::string* Value::mutable_string_value() { +inline std::string* Value::mutable_string_value() { if (!has_string_value()) { clear_kind(); set_has_string_value(); - kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + kind_.string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } - return kind_.string_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + return kind_.string_value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); // @@protoc_insertion_point(field_mutable:google.protobuf.Value.string_value) } -inline ::std::string* Value::release_string_value() { +inline std::string* Value::release_string_value() { // @@protoc_insertion_point(field_release:google.protobuf.Value.string_value) if (has_string_value()) { clear_has_kind(); - return kind_.string_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + return kind_.string_value_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } else { - return NULL; + return nullptr; } } -inline void Value::set_allocated_string_value(::std::string* string_value) { - if (!has_string_value()) { - kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +inline void Value::set_allocated_string_value(std::string* string_value) { + if (has_kind()) { + clear_kind(); } - clear_kind(); - if (string_value != NULL) { + if (string_value != nullptr) { set_has_string_value(); - kind_.string_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), string_value, - GetArenaNoVirtual()); + kind_.string_value_.UnsafeSetDefault(string_value); } // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.string_value) } -inline ::std::string* Value::unsafe_arena_release_string_value() { +inline std::string* Value::unsafe_arena_release_string_value() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.string_value) - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); if (has_string_value()) { clear_has_kind(); return kind_.string_value_.UnsafeArenaRelease( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } else { - return NULL; + return nullptr; } } -inline void Value::unsafe_arena_set_allocated_string_value(::std::string* string_value) { - GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); +inline void Value::unsafe_arena_set_allocated_string_value(std::string* string_value) { + GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr); if (!has_string_value()) { - kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + kind_.string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } clear_kind(); if (string_value) { set_has_string_value(); - kind_.string_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), string_value, GetArenaNoVirtual()); + kind_.string_value_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), string_value, GetArenaNoVirtual()); } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.string_value) } @@ -849,47 +925,44 @@ inline void Value::set_has_struct_value() { } inline void Value::clear_struct_value() { if (has_struct_value()) { - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete kind_.struct_value_; } clear_has_kind(); } } -inline const ::google::protobuf::Struct& Value::_internal_struct_value() const { - return *kind_.struct_value_; -} -inline ::google::protobuf::Struct* Value::release_struct_value() { +inline PROTOBUF_NAMESPACE_ID::Struct* Value::release_struct_value() { // @@protoc_insertion_point(field_release:google.protobuf.Value.struct_value) if (has_struct_value()) { clear_has_kind(); - ::google::protobuf::Struct* temp = kind_.struct_value_; - if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); + PROTOBUF_NAMESPACE_ID::Struct* temp = kind_.struct_value_; + if (GetArenaNoVirtual() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } - kind_.struct_value_ = NULL; + kind_.struct_value_ = nullptr; return temp; } else { - return NULL; + return nullptr; } } -inline const ::google::protobuf::Struct& Value::struct_value() const { +inline const PROTOBUF_NAMESPACE_ID::Struct& Value::struct_value() const { // @@protoc_insertion_point(field_get:google.protobuf.Value.struct_value) return has_struct_value() ? *kind_.struct_value_ - : *reinterpret_cast< ::google::protobuf::Struct*>(&::google::protobuf::_Struct_default_instance_); + : *reinterpret_cast< PROTOBUF_NAMESPACE_ID::Struct*>(&PROTOBUF_NAMESPACE_ID::_Struct_default_instance_); } -inline ::google::protobuf::Struct* Value::unsafe_arena_release_struct_value() { +inline PROTOBUF_NAMESPACE_ID::Struct* Value::unsafe_arena_release_struct_value() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.struct_value) if (has_struct_value()) { clear_has_kind(); - ::google::protobuf::Struct* temp = kind_.struct_value_; - kind_.struct_value_ = NULL; + PROTOBUF_NAMESPACE_ID::Struct* temp = kind_.struct_value_; + kind_.struct_value_ = nullptr; return temp; } else { - return NULL; + return nullptr; } } -inline void Value::unsafe_arena_set_allocated_struct_value(::google::protobuf::Struct* struct_value) { +inline void Value::unsafe_arena_set_allocated_struct_value(PROTOBUF_NAMESPACE_ID::Struct* struct_value) { clear_kind(); if (struct_value) { set_has_struct_value(); @@ -897,11 +970,11 @@ inline void Value::unsafe_arena_set_allocated_struct_value(::google::protobuf::S } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.struct_value) } -inline ::google::protobuf::Struct* Value::mutable_struct_value() { +inline PROTOBUF_NAMESPACE_ID::Struct* Value::mutable_struct_value() { if (!has_struct_value()) { clear_kind(); set_has_struct_value(); - kind_.struct_value_ = CreateMaybeMessage< ::google::protobuf::Struct >( + kind_.struct_value_ = CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Struct >( GetArenaNoVirtual()); } // @@protoc_insertion_point(field_mutable:google.protobuf.Value.struct_value) @@ -917,47 +990,44 @@ inline void Value::set_has_list_value() { } inline void Value::clear_list_value() { if (has_list_value()) { - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete kind_.list_value_; } clear_has_kind(); } } -inline const ::google::protobuf::ListValue& Value::_internal_list_value() const { - return *kind_.list_value_; -} -inline ::google::protobuf::ListValue* Value::release_list_value() { +inline PROTOBUF_NAMESPACE_ID::ListValue* Value::release_list_value() { // @@protoc_insertion_point(field_release:google.protobuf.Value.list_value) if (has_list_value()) { clear_has_kind(); - ::google::protobuf::ListValue* temp = kind_.list_value_; - if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); + PROTOBUF_NAMESPACE_ID::ListValue* temp = kind_.list_value_; + if (GetArenaNoVirtual() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } - kind_.list_value_ = NULL; + kind_.list_value_ = nullptr; return temp; } else { - return NULL; + return nullptr; } } -inline const ::google::protobuf::ListValue& Value::list_value() const { +inline const PROTOBUF_NAMESPACE_ID::ListValue& Value::list_value() const { // @@protoc_insertion_point(field_get:google.protobuf.Value.list_value) return has_list_value() ? *kind_.list_value_ - : *reinterpret_cast< ::google::protobuf::ListValue*>(&::google::protobuf::_ListValue_default_instance_); + : *reinterpret_cast< PROTOBUF_NAMESPACE_ID::ListValue*>(&PROTOBUF_NAMESPACE_ID::_ListValue_default_instance_); } -inline ::google::protobuf::ListValue* Value::unsafe_arena_release_list_value() { +inline PROTOBUF_NAMESPACE_ID::ListValue* Value::unsafe_arena_release_list_value() { // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.list_value) if (has_list_value()) { clear_has_kind(); - ::google::protobuf::ListValue* temp = kind_.list_value_; - kind_.list_value_ = NULL; + PROTOBUF_NAMESPACE_ID::ListValue* temp = kind_.list_value_; + kind_.list_value_ = nullptr; return temp; } else { - return NULL; + return nullptr; } } -inline void Value::unsafe_arena_set_allocated_list_value(::google::protobuf::ListValue* list_value) { +inline void Value::unsafe_arena_set_allocated_list_value(PROTOBUF_NAMESPACE_ID::ListValue* list_value) { clear_kind(); if (list_value) { set_has_list_value(); @@ -965,11 +1035,11 @@ inline void Value::unsafe_arena_set_allocated_list_value(::google::protobuf::Lis } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.list_value) } -inline ::google::protobuf::ListValue* Value::mutable_list_value() { +inline PROTOBUF_NAMESPACE_ID::ListValue* Value::mutable_list_value() { if (!has_list_value()) { clear_kind(); set_has_list_value(); - kind_.list_value_ = CreateMaybeMessage< ::google::protobuf::ListValue >( + kind_.list_value_ = CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::ListValue >( GetArenaNoVirtual()); } // @@protoc_insertion_point(field_mutable:google.protobuf.Value.list_value) @@ -996,24 +1066,24 @@ inline int ListValue::values_size() const { inline void ListValue::clear_values() { values_.Clear(); } -inline ::google::protobuf::Value* ListValue::mutable_values(int index) { +inline PROTOBUF_NAMESPACE_ID::Value* ListValue::mutable_values(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.ListValue.values) return values_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Value >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Value >* ListValue::mutable_values() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.ListValue.values) return &values_; } -inline const ::google::protobuf::Value& ListValue::values(int index) const { +inline const PROTOBUF_NAMESPACE_ID::Value& ListValue::values(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.ListValue.values) return values_.Get(index); } -inline ::google::protobuf::Value* ListValue::add_values() { +inline PROTOBUF_NAMESPACE_ID::Value* ListValue::add_values() { // @@protoc_insertion_point(field_add:google.protobuf.ListValue.values) return values_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Value >& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Value >& ListValue::values() const { // @@protoc_insertion_point(field_list:google.protobuf.ListValue.values) return values_; @@ -1031,21 +1101,19 @@ ListValue::values() const { // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE -namespace google { -namespace protobuf { +PROTOBUF_NAMESPACE_OPEN -template <> struct is_proto_enum< ::google::protobuf::NullValue> : ::std::true_type {}; +template <> struct is_proto_enum< PROTOBUF_NAMESPACE_ID::NullValue> : ::std::true_type {}; template <> -inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::NullValue>() { - return ::google::protobuf::NullValue_descriptor(); +inline const EnumDescriptor* GetEnumDescriptor< PROTOBUF_NAMESPACE_ID::NullValue>() { + return PROTOBUF_NAMESPACE_ID::NullValue_descriptor(); } -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto diff --git a/third_party/protobuf/src/google/protobuf/struct.proto b/third_party/protobuf/src/google/protobuf/struct.proto index 7d7808e7..ed990e31 100644 --- a/third_party/protobuf/src/google/protobuf/struct.proto +++ b/third_party/protobuf/src/google/protobuf/struct.proto @@ -40,7 +40,6 @@ option java_outer_classname = "StructProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; - // `Struct` represents a structured data value, consisting of fields // which map to dynamically typed values. In some languages, `Struct` // might be supported by a native representation. For example, in diff --git a/third_party/protobuf/src/google/protobuf/stubs/bytestream.cc b/third_party/protobuf/src/google/protobuf/stubs/bytestream.cc index f4af6a50..a0f298ed 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/bytestream.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/bytestream.cc @@ -33,6 +33,8 @@ #include #include +#include + namespace google { namespace protobuf { namespace strings { @@ -113,7 +115,7 @@ char* GrowingArrayByteSink::GetBuffer(size_t* nbytes) { ShrinkToFit(); char* b = buf_; *nbytes = size_; - buf_ = NULL; + buf_ = nullptr; size_ = capacity_ = 0; return b; } diff --git a/third_party/protobuf/src/google/protobuf/stubs/bytestream.h b/third_party/protobuf/src/google/protobuf/stubs/bytestream.h index 86510d14..29a9fbe7 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/bytestream.h +++ b/third_party/protobuf/src/google/protobuf/stubs/bytestream.h @@ -56,8 +56,9 @@ #include #include +#include + class CordByteSink; -class MemBlock; namespace google { namespace protobuf { @@ -74,7 +75,7 @@ namespace strings { // sink->Append(my_data.data(), my_data.size()); // sink->Flush(); // -class LIBPROTOBUF_EXPORT ByteSink { +class PROTOBUF_EXPORT ByteSink { public: ByteSink() {} virtual ~ByteSink() {} @@ -103,7 +104,7 @@ class LIBPROTOBUF_EXPORT ByteSink { // source->Skip(data.length()); // } // -class LIBPROTOBUF_EXPORT ByteSource { +class PROTOBUF_EXPORT ByteSource { public: ByteSource() {} virtual ~ByteSource() {} @@ -159,10 +160,10 @@ class LIBPROTOBUF_EXPORT ByteSource { // sink.Append("hi", 2); // OK // sink.Append(data, 100); // WOOPS! Overflows buf[10]. // -class LIBPROTOBUF_EXPORT UncheckedArrayByteSink : public ByteSink { +class PROTOBUF_EXPORT UncheckedArrayByteSink : public ByteSink { public: explicit UncheckedArrayByteSink(char* dest) : dest_(dest) {} - virtual void Append(const char* data, size_t n); + virtual void Append(const char* data, size_t n) override; // Returns the current output pointer so that a caller can see how many bytes // were produced. @@ -187,10 +188,10 @@ class LIBPROTOBUF_EXPORT UncheckedArrayByteSink : public ByteSink { // sink.Append("hi", 2); // OK // sink.Append(data, 100); // Will only write 8 more bytes // -class LIBPROTOBUF_EXPORT CheckedArrayByteSink : public ByteSink { +class PROTOBUF_EXPORT CheckedArrayByteSink : public ByteSink { public: CheckedArrayByteSink(char* outbuf, size_t capacity); - virtual void Append(const char* bytes, size_t n); + virtual void Append(const char* bytes, size_t n) override; // Returns the number of bytes actually written to the sink. size_t NumberOfBytesWritten() const { return size_; } @@ -223,11 +224,11 @@ class LIBPROTOBUF_EXPORT CheckedArrayByteSink : public ByteSink { // const char* buf = sink.GetBuffer(); // Ownership transferred // delete[] buf; // -class LIBPROTOBUF_EXPORT GrowingArrayByteSink : public strings::ByteSink { +class PROTOBUF_EXPORT GrowingArrayByteSink : public strings::ByteSink { public: explicit GrowingArrayByteSink(size_t estimated_size); virtual ~GrowingArrayByteSink(); - virtual void Append(const char* bytes, size_t n); + virtual void Append(const char* bytes, size_t n) override; // Returns the allocated buffer, and sets nbytes to its size. The caller takes // ownership of the buffer and must delete it with delete[]. @@ -253,10 +254,10 @@ class LIBPROTOBUF_EXPORT GrowingArrayByteSink : public strings::ByteSink { // sink.Append("World", 5); // assert(dest == "Hello World"); // -class LIBPROTOBUF_EXPORT StringByteSink : public ByteSink { +class PROTOBUF_EXPORT StringByteSink : public ByteSink { public: explicit StringByteSink(string* dest) : dest_(dest) {} - virtual void Append(const char* data, size_t n); + virtual void Append(const char* data, size_t n) override; private: string* dest_; @@ -270,10 +271,10 @@ class LIBPROTOBUF_EXPORT StringByteSink : public ByteSink { // NullByteSink sink; // sink.Append(data, data.size()); // All data ignored. // -class LIBPROTOBUF_EXPORT NullByteSink : public ByteSink { +class PROTOBUF_EXPORT NullByteSink : public ByteSink { public: NullByteSink() {} - virtual void Append(const char *data, size_t n) {} + virtual void Append(const char *data, size_t n) override {} private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(NullByteSink); @@ -292,13 +293,13 @@ class LIBPROTOBUF_EXPORT NullByteSink : public ByteSink { // assert(source.Available() == 5); // assert(source.Peek() == "Hello"); // -class LIBPROTOBUF_EXPORT ArrayByteSource : public ByteSource { +class PROTOBUF_EXPORT ArrayByteSource : public ByteSource { public: explicit ArrayByteSource(StringPiece s) : input_(s) {} - virtual size_t Available() const; - virtual StringPiece Peek(); - virtual void Skip(size_t n); + virtual size_t Available() const override; + virtual StringPiece Peek() override; + virtual void Skip(size_t n) override; private: StringPiece input_; @@ -323,18 +324,18 @@ class LIBPROTOBUF_EXPORT ArrayByteSource : public ByteSource { // assert(limit.Available() == 5); // assert(limit.Peek() == "Hello"); // -class LIBPROTOBUF_EXPORT LimitByteSource : public ByteSource { +class PROTOBUF_EXPORT LimitByteSource : public ByteSource { public: // Returns at most "limit" bytes from "source". LimitByteSource(ByteSource* source, size_t limit); - virtual size_t Available() const; - virtual StringPiece Peek(); - virtual void Skip(size_t n); + virtual size_t Available() const override; + virtual StringPiece Peek() override; + virtual void Skip(size_t n) override; // We override CopyTo so that we can forward to the underlying source, in // case it has an efficient implementation of CopyTo. - virtual void CopyTo(ByteSink* sink, size_t n); + virtual void CopyTo(ByteSink* sink, size_t n) override; private: ByteSource* source_; @@ -345,4 +346,6 @@ class LIBPROTOBUF_EXPORT LimitByteSource : public ByteSource { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_STUBS_BYTESTREAM_H_ diff --git a/third_party/protobuf/src/google/protobuf/stubs/callback.h b/third_party/protobuf/src/google/protobuf/stubs/callback.h index 6888f136..ab4a3aae 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/callback.h +++ b/third_party/protobuf/src/google/protobuf/stubs/callback.h @@ -5,6 +5,8 @@ #include +#include + // =================================================================== // emulates google3/base/callback.h @@ -68,7 +70,7 @@ namespace protobuf { // string my_str; // NewCallback(&Foo, my_str); // WON'T WORK: Can't use referecnes. // However, correctly-typed pointers will work just fine. -class LIBPROTOBUF_EXPORT Closure { +class PROTOBUF_EXPORT Closure { public: Closure() {} virtual ~Closure(); @@ -91,8 +93,8 @@ class ResultCallback { GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ResultCallback); }; -template -class LIBPROTOBUF_EXPORT ResultCallback1 { +template +class PROTOBUF_EXPORT ResultCallback1 { public: ResultCallback1() {} virtual ~ResultCallback1() {} @@ -103,8 +105,8 @@ class LIBPROTOBUF_EXPORT ResultCallback1 { GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ResultCallback1); }; -template -class LIBPROTOBUF_EXPORT ResultCallback2 { +template +class PROTOBUF_EXPORT ResultCallback2 { public: ResultCallback2() {} virtual ~ResultCallback2() {} @@ -117,7 +119,7 @@ class LIBPROTOBUF_EXPORT ResultCallback2 { namespace internal { -class LIBPROTOBUF_EXPORT FunctionClosure0 : public Closure { +class PROTOBUF_EXPORT FunctionClosure0 : public Closure { public: typedef void (*FunctionType)(); @@ -125,7 +127,7 @@ class LIBPROTOBUF_EXPORT FunctionClosure0 : public Closure { : function_(function), self_deleting_(self_deleting) {} ~FunctionClosure0(); - void Run() { + void Run() override { bool needs_delete = self_deleting_; // read in case callback deletes function_(); if (needs_delete) delete this; @@ -145,7 +147,7 @@ class MethodClosure0 : public Closure { : object_(object), method_(method), self_deleting_(self_deleting) {} ~MethodClosure0() {} - void Run() { + void Run() override { bool needs_delete = self_deleting_; // read in case callback deletes (object_->*method_)(); if (needs_delete) delete this; @@ -168,7 +170,7 @@ class FunctionClosure1 : public Closure { arg1_(arg1) {} ~FunctionClosure1() {} - void Run() { + void Run() override { bool needs_delete = self_deleting_; // read in case callback deletes function_(arg1_); if (needs_delete) delete this; @@ -191,7 +193,7 @@ class MethodClosure1 : public Closure { arg1_(arg1) {} ~MethodClosure1() {} - void Run() { + void Run() override { bool needs_delete = self_deleting_; // read in case callback deletes (object_->*method_)(arg1_); if (needs_delete) delete this; @@ -215,7 +217,7 @@ class FunctionClosure2 : public Closure { arg1_(arg1), arg2_(arg2) {} ~FunctionClosure2() {} - void Run() { + void Run() override { bool needs_delete = self_deleting_; // read in case callback deletes function_(arg1_, arg2_); if (needs_delete) delete this; @@ -239,7 +241,7 @@ class MethodClosure2 : public Closure { arg1_(arg1), arg2_(arg2) {} ~MethodClosure2() {} - void Run() { + void Run() override { bool needs_delete = self_deleting_; // read in case callback deletes (object_->*method_)(arg1_, arg2_); if (needs_delete) delete this; @@ -262,7 +264,7 @@ class FunctionResultCallback_0_0 : public ResultCallback { : function_(function), self_deleting_(self_deleting) {} ~FunctionResultCallback_0_0() {} - R Run() { + R Run() override { bool needs_delete = self_deleting_; // read in case callback deletes R result = function_(); if (needs_delete) delete this; @@ -284,7 +286,7 @@ class FunctionResultCallback_1_0 : public ResultCallback { : function_(function), self_deleting_(self_deleting), p1_(p1) {} ~FunctionResultCallback_1_0() {} - R Run() { + R Run() override { bool needs_delete = self_deleting_; // read in case callback deletes R result = function_(p1_); if (needs_delete) delete this; @@ -306,7 +308,7 @@ class FunctionResultCallback_0_1 : public ResultCallback1 { : function_(function), self_deleting_(self_deleting) {} ~FunctionResultCallback_0_1() {} - R Run(Arg1 a1) { + R Run(Arg1 a1) override { bool needs_delete = self_deleting_; // read in case callback deletes R result = function_(a1); if (needs_delete) delete this; @@ -328,7 +330,7 @@ class FunctionResultCallback_1_1 : public ResultCallback1 { : function_(function), self_deleting_(self_deleting), p1_(p1) {} ~FunctionResultCallback_1_1() {} - R Run(A1 a1) { + R Run(A1 a1) override { bool needs_delete = self_deleting_; // read in case callback deletes R result = function_(p1_, a1); if (needs_delete) delete this; @@ -371,12 +373,12 @@ class MethodResultCallback_0_0 : public ResultCallback { }; template -class MethodResultCallback_5_2 : public ResultCallback2 { + typename P4, typename P5, typename P6, typename A1, typename A2> +class MethodResultCallback_6_2 : public ResultCallback2 { public: - typedef R (T::*MethodType)(P1, P2, P3, P4, P5, A1, A2); - MethodResultCallback_5_2(T* object, MethodType method, bool self_deleting, - P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) + typedef R (T::*MethodType)(P1, P2, P3, P4, P5, P6, A1, A2); + MethodResultCallback_6_2(T* object, MethodType method, bool self_deleting, + P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) : object_(object), method_(method), self_deleting_(self_deleting), @@ -384,12 +386,13 @@ class MethodResultCallback_5_2 : public ResultCallback2 { p2_(p2), p3_(p3), p4_(p4), - p5_(p5) {} - ~MethodResultCallback_5_2() {} + p5_(p5), + p6_(p6) {} + ~MethodResultCallback_6_2() {} - R Run(A1 a1, A2 a2) { + R Run(A1 a1, A2 a2) override { bool needs_delete = self_deleting_; - R result = (object_->*method_)(p1_, p2_, p3_, p4_, p5_, a1, a2); + R result = (object_->*method_)(p1_, p2_, p3_, p4_, p5_, p6_, a1, a2); if (needs_delete) delete this; return result; } @@ -403,6 +406,7 @@ class MethodResultCallback_5_2 : public ResultCallback2 { typename std::remove_reference::type p3_; typename std::remove_reference::type p4_; typename std::remove_reference::type p5_; + typename std::remove_reference::type p6_; }; } // namespace internal @@ -551,27 +555,29 @@ inline ResultCallback* NewPermanentCallback( return new internal::MethodResultCallback_0_0(object, function, false); } -// See MethodResultCallback_5_2 +// See MethodResultCallback_6_2 template + typename P4, typename P5, typename P6, typename A1, typename A2> inline ResultCallback2* NewPermanentCallback( - T* object, R (T::*function)(P1, P2, P3, P4, P5, A1, A2), + T* object, R (T::*function)(P1, P2, P3, P4, P5, P6, A1, A2), typename internal::InternalConstRef::type p1, typename internal::InternalConstRef::type p2, typename internal::InternalConstRef::type p3, typename internal::InternalConstRef::type p4, - typename internal::InternalConstRef::type p5) { - return new internal::MethodResultCallback_5_2(object, function, false, p1, - p2, p3, p4, p5); + typename internal::InternalConstRef::type p5, + typename internal::InternalConstRef::type p6) { + return new internal::MethodResultCallback_6_2(object, function, false, + p1, p2, p3, p4, p5, p6); } // A function which does nothing. Useful for creating no-op callbacks, e.g.: // Closure* nothing = NewCallback(&DoNothing); -void LIBPROTOBUF_EXPORT DoNothing(); - +void PROTOBUF_EXPORT DoNothing(); } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_STUBS_CALLBACK_H_ diff --git a/third_party/protobuf/src/google/protobuf/stubs/casts.h b/third_party/protobuf/src/google/protobuf/stubs/casts.h index 35e2dba0..b509f68c 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/casts.h +++ b/third_party/protobuf/src/google/protobuf/stubs/casts.h @@ -89,7 +89,7 @@ inline To down_cast(From* f) { // so we only accept pointers } #if !defined(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI) - assert(f == NULL || dynamic_cast(f) != NULL); // RTTI: debug mode only! + assert(f == nullptr || dynamic_cast(f) != nullptr); // RTTI: debug mode only! #endif return static_cast(f); } @@ -107,7 +107,7 @@ inline To down_cast(From& f) { #if !defined(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI) // RTTI: debug mode only! - assert(dynamic_cast(&f) != NULL); + assert(dynamic_cast(&f) != nullptr); #endif return *static_cast(&f); } diff --git a/third_party/protobuf/src/google/protobuf/stubs/common.cc b/third_party/protobuf/src/google/protobuf/stubs/common.cc old mode 100755 new mode 100644 index 6544c6ed..ff9a32d5 --- a/third_party/protobuf/src/google/protobuf/stubs/common.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/common.cc @@ -30,13 +30,9 @@ // Author: kenton@google.com (Kenton Varda) -#include // TODO(gerbens) ideally remove this. #include -#include -#include -#include -#include -#include + +#include #include #include #include @@ -55,6 +51,17 @@ #include #endif +#include +#include +#include +#include +#include +#include +#include +#include + +#include + namespace google { namespace protobuf { @@ -174,22 +181,7 @@ void NullLogHandler(LogLevel /* level */, const char* /* filename */, } static LogHandler* log_handler_ = &DefaultLogHandler; -static int log_silencer_count_ = 0; - -static Mutex* log_silencer_count_mutex_ = NULL; -GOOGLE_PROTOBUF_DECLARE_ONCE(log_silencer_count_init_); - -void DeleteLogSilencerCount() { - delete log_silencer_count_mutex_; - log_silencer_count_mutex_ = NULL; -} -void InitLogSilencerCount() { - log_silencer_count_mutex_ = new Mutex; - OnShutdown(&DeleteLogSilencerCount); -} -void InitLogSilencerCountOnce() { - GoogleOnceInit(&log_silencer_count_init_, &InitLogSilencerCount); -} +static std::atomic log_silencer_count_ = ATOMIC_VAR_INIT(0); LogMessage& LogMessage::operator<<(const string& value) { message_ += value; @@ -206,8 +198,7 @@ LogMessage& LogMessage::operator<<(const StringPiece& value) { return *this; } -LogMessage& LogMessage::operator<<( - const ::google::protobuf::util::Status& status) { +LogMessage& LogMessage::operator<<(const util::Status& status) { message_ += status.ToString(); return *this; } @@ -243,8 +234,8 @@ DECLARE_STREAM_OPERATOR(long , "%ld") DECLARE_STREAM_OPERATOR(unsigned long, "%lu") DECLARE_STREAM_OPERATOR(double , "%g" ) DECLARE_STREAM_OPERATOR(void* , "%p" ) -DECLARE_STREAM_OPERATOR(long long , "%" GOOGLE_LL_FORMAT "d") -DECLARE_STREAM_OPERATOR(unsigned long long, "%" GOOGLE_LL_FORMAT "u") +DECLARE_STREAM_OPERATOR(long long , "%" PROTOBUF_LL_FORMAT "d") +DECLARE_STREAM_OPERATOR(unsigned long long, "%" PROTOBUF_LL_FORMAT "u") #undef DECLARE_STREAM_OPERATOR LogMessage::LogMessage(LogLevel level, const char* filename, int line) @@ -255,8 +246,6 @@ void LogMessage::Finish() { bool suppress = false; if (level_ != LOGLEVEL_FATAL) { - InitLogSilencerCountOnce(); - MutexLock lock(log_silencer_count_mutex_); suppress = log_silencer_count_ > 0; } @@ -282,9 +271,9 @@ void LogFinisher::operator=(LogMessage& other) { LogHandler* SetLogHandler(LogHandler* new_func) { LogHandler* old = internal::log_handler_; if (old == &internal::NullLogHandler) { - old = NULL; + old = nullptr; } - if (new_func == NULL) { + if (new_func == nullptr) { internal::log_handler_ = &internal::NullLogHandler; } else { internal::log_handler_ = new_func; @@ -293,14 +282,10 @@ LogHandler* SetLogHandler(LogHandler* new_func) { } LogSilencer::LogSilencer() { - internal::InitLogSilencerCountOnce(); - MutexLock lock(internal::log_silencer_count_mutex_); ++internal::log_silencer_count_; }; LogSilencer::~LogSilencer() { - internal::InitLogSilencerCountOnce(); - MutexLock lock(internal::log_silencer_count_mutex_); --internal::log_silencer_count_; }; @@ -336,7 +321,6 @@ uint32 ghtonl(uint32 x) { namespace internal { -typedef void OnShutdownFunc(); struct ShutdownData { ~ShutdownData() { std::reverse(functions.begin(), functions.end()); @@ -353,7 +337,8 @@ struct ShutdownData { }; static void RunZeroArgFunc(const void* arg) { - reinterpret_cast(const_cast(arg))(); + void (*func)() = reinterpret_cast(const_cast(arg)); + func(); } void OnShutdown(void (*func)()) { diff --git a/third_party/protobuf/src/google/protobuf/stubs/common.h b/third_party/protobuf/src/google/protobuf/stubs/common.h index d35377ae..29efde1d 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/common.h +++ b/third_party/protobuf/src/google/protobuf/stubs/common.h @@ -47,11 +47,6 @@ #include #include -// TODO(liujisi): Remove the following includes after the include clean-up. -#include -#include -#include - #ifndef PROTOBUF_USE_EXCEPTIONS #if defined(_MSC_VER) && defined(_CPPUNWIND) #define PROTOBUF_USE_EXCEPTIONS 1 @@ -73,22 +68,7 @@ #include #endif -#if defined(_WIN32) && defined(GetMessage) -// Allow GetMessage to be used as a valid method name in protobuf classes. -// windows.h defines GetMessage() as a macro. Let's re-define it as an inline -// function. The inline function should be equivalent for C++ users. -inline BOOL GetMessage_Win32( - LPMSG lpMsg, HWND hWnd, - UINT wMsgFilterMin, UINT wMsgFilterMax) { - return GetMessage(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax); -} -#undef GetMessage -inline BOOL GetMessage( - LPMSG lpMsg, HWND hWnd, - UINT wMsgFilterMin, UINT wMsgFilterMax) { - return GetMessage_Win32(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax); -} -#endif +#include namespace std {} @@ -101,35 +81,31 @@ namespace internal { // The current version, represented as a single integer to make comparison // easier: major * 10^6 + minor * 10^3 + micro -#define GOOGLE_PROTOBUF_VERSION 3006001 +#define GOOGLE_PROTOBUF_VERSION 3008000 // A suffix string for alpha, beta or rc releases. Empty for stable releases. #define GOOGLE_PROTOBUF_VERSION_SUFFIX "" -// The minimum library version which works with the current version of the -// headers. -#define GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION 3006001 - // The minimum header version which works with the current version of // the library. This constant should only be used by protoc's C++ code // generator. -static const int kMinHeaderVersionForLibrary = 3006001; +static const int kMinHeaderVersionForLibrary = 3008000; // The minimum protoc version which works with the current version of the // headers. -#define GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 3006001 +#define GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 3008000 // The minimum header version which works with the current version of // protoc. This constant should only be used in VerifyVersion(). -static const int kMinHeaderVersionForProtoc = 3006001; +static const int kMinHeaderVersionForProtoc = 3008000; // Verifies that the headers and libraries are compatible. Use the macro // below to call this. -void LIBPROTOBUF_EXPORT VerifyVersion(int headerVersion, int minLibraryVersion, - const char* filename); +void PROTOBUF_EXPORT VerifyVersion(int headerVersion, int minLibraryVersion, + const char* filename); // Converts a numeric version number to a string. -std::string LIBPROTOBUF_EXPORT VersionString(int version); +std::string PROTOBUF_EXPORT VersionString(int version); } // namespace internal @@ -151,14 +127,14 @@ namespace internal { // Checks if the buffer contains structurally-valid UTF-8. Implemented in // structurally_valid.cc. -LIBPROTOBUF_EXPORT bool IsStructurallyValidUTF8(const char* buf, int len); +PROTOBUF_EXPORT bool IsStructurallyValidUTF8(const char* buf, int len); inline bool IsStructurallyValidUTF8(const std::string& str) { return IsStructurallyValidUTF8(str.data(), static_cast(str.length())); } // Returns initial number of bytes of structually valid UTF-8. -LIBPROTOBUF_EXPORT int UTF8SpnStructurallyValid(const StringPiece& str); +PROTOBUF_EXPORT int UTF8SpnStructurallyValid(const StringPiece& str); // Coerce UTF-8 byte string in src_str to be // a structurally-valid equal-length string by selectively @@ -172,8 +148,9 @@ LIBPROTOBUF_EXPORT int UTF8SpnStructurallyValid(const StringPiece& str); // // Optimized for: all structurally valid and no byte copying is done. // -LIBPROTOBUF_EXPORT char* UTF8CoerceToStructurallyValid( - const StringPiece& str, char* dst, char replace_char); +PROTOBUF_EXPORT char* UTF8CoerceToStructurallyValid(const StringPiece& str, + char* dst, + char replace_char); } // namespace internal @@ -195,18 +172,18 @@ LIBPROTOBUF_EXPORT char* UTF8CoerceToStructurallyValid( // any other part of the protocol buffers library after // ShutdownProtobufLibrary() has been called. Furthermore this call is not // thread safe, user needs to synchronize multiple calls. -LIBPROTOBUF_EXPORT void ShutdownProtobufLibrary(); +PROTOBUF_EXPORT void ShutdownProtobufLibrary(); namespace internal { // Register a function to be called when ShutdownProtocolBuffers() is called. -LIBPROTOBUF_EXPORT void OnShutdown(void (*func)()); +PROTOBUF_EXPORT void OnShutdown(void (*func)()); // Run an arbitrary function on an arg -LIBPROTOBUF_EXPORT void OnShutdownRun(void (*f)(const void*), const void* arg); +PROTOBUF_EXPORT void OnShutdownRun(void (*f)(const void*), const void* arg); template T* OnShutdownDelete(T* p) { - OnShutdownRun([](const void* p) { delete static_cast(p); }, p); + OnShutdownRun([](const void* pp) { delete static_cast(pp); }, p); return p; } @@ -239,4 +216,6 @@ using std::string; } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMMON_H__ diff --git a/third_party/protobuf/src/google/protobuf/stubs/common_unittest.cc b/third_party/protobuf/src/google/protobuf/stubs/common_unittest.cc index 798a2a27..58524589 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/common_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/common_unittest.cc @@ -31,8 +31,10 @@ // Author: kenton@google.com (Kenton Varda) #include +#include #include #include +#include #include #include @@ -100,14 +102,14 @@ TEST(LoggingTest, DefaultLogging) { } TEST(LoggingTest, NullLogging) { - LogHandler* old_handler = SetLogHandler(NULL); + LogHandler* old_handler = SetLogHandler(nullptr); CaptureTestStderr(); GOOGLE_LOG(INFO ) << "A message."; GOOGLE_LOG(WARNING) << "A warning."; GOOGLE_LOG(ERROR ) << "An error."; - EXPECT_TRUE(SetLogHandler(old_handler) == NULL); + EXPECT_TRUE(SetLogHandler(old_handler) == nullptr); string text = GetCapturedTestStderr(); EXPECT_EQ("", text); @@ -179,9 +181,9 @@ class ClosureTest : public testing::Test { virtual void SetUp() { current_instance_ = this; a_ = 0; - b_ = NULL; + b_ = nullptr; c_.clear(); - permanent_closure_ = NULL; + permanent_closure_ = nullptr; } void DeleteClosureInCallback() { @@ -196,7 +198,7 @@ class ClosureTest : public testing::Test { static ClosureTest* current_instance_; }; -ClosureTest* ClosureTest::current_instance_ = NULL; +ClosureTest* ClosureTest::current_instance_ = nullptr; TEST_F(ClosureTest, TestClosureFunction0) { Closure* closure = NewCallback(&SetA123Function); @@ -321,7 +323,7 @@ TEST_F(ClosureTest, TestPermanentClosureFunction2) { EXPECT_EQ(789, a_); EXPECT_EQ(cstr, b_); a_ = 0; - b_ = NULL; + b_ = nullptr; closure->Run(); EXPECT_EQ(789, a_); EXPECT_EQ(cstr, b_); @@ -338,7 +340,7 @@ TEST_F(ClosureTest, TestPermanentClosureMethod2) { EXPECT_EQ(789, a_); EXPECT_EQ(cstr, b_); a_ = 0; - b_ = NULL; + b_ = nullptr; closure->Run(); EXPECT_EQ(789, a_); EXPECT_EQ(cstr, b_); diff --git a/third_party/protobuf/src/google/protobuf/stubs/fastmem.h b/third_party/protobuf/src/google/protobuf/stubs/fastmem.h index 1f1f6ed3..76c8a3ae 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/fastmem.h +++ b/third_party/protobuf/src/google/protobuf/stubs/fastmem.h @@ -51,6 +51,8 @@ #include +#include + namespace google { namespace protobuf { namespace internal { @@ -64,7 +66,7 @@ namespace internal { // if it makes sense to do so.:w inline bool memeq(const char* a, const char* b, size_t n) { size_t n_rounded_down = n & ~static_cast(7); - if (GOOGLE_PREDICT_FALSE(n_rounded_down == 0)) { // n <= 7 + if (PROTOBUF_PREDICT_FALSE(n_rounded_down == 0)) { // n <= 7 return memcmp(a, b, n) == 0; } // n >= 8 @@ -150,4 +152,6 @@ inline void memcpy_inlined(char *dst, const char *src, size_t size) { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_STUBS_FASTMEM_H_ diff --git a/third_party/protobuf/src/google/protobuf/stubs/hash.h b/third_party/protobuf/src/google/protobuf/stubs/hash.h index fd8ba156..a093b406 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/hash.h +++ b/third_party/protobuf/src/google/protobuf/stubs/hash.h @@ -29,8 +29,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: kenton@google.com (Kenton Varda) -// -// Deals with the fact that hash_map is not defined everywhere. #ifndef GOOGLE_PROTOBUF_STUBS_HASH_H__ #define GOOGLE_PROTOBUF_STUBS_HASH_H__ @@ -38,304 +36,19 @@ #include #include -#define GOOGLE_PROTOBUF_HAVE_HASH_MAP 1 -#define GOOGLE_PROTOBUF_HAVE_HASH_SET 1 - -// Use C++11 unordered_{map|set} if available. -#if ((defined(_LIBCPP_STD_VER) && _LIBCPP_STD_VER >= 11) || \ - (((__cplusplus >= 201103L) || defined(__GXX_EXPERIMENTAL_CXX0X)) && \ - (__GLIBCXX__ > 20090421))) -# define GOOGLE_PROTOBUF_HAS_CXX11_HASH - -// For XCode >= 4.6: the compiler is clang with libc++. -// For earlier XCode version: the compiler is gcc-4.2.1 with libstdc++. -// libc++ provides and friends even in non C++11 mode, -// and it does not provide the tr1 library. Therefore the following macro -// checks against this special case. -// Note that we should not test the __APPLE_CC__ version number or the -// __clang__ macro, since the new compiler can still use -stdlib=libstdc++, in -// which case is not compilable without -std=c++11 -#elif defined(__APPLE_CC__) -# if __GNUC__ >= 4 -# define GOOGLE_PROTOBUF_HAS_TR1 -# else -// Not tested for gcc < 4... These setting can compile under 4.2.1 though. -# define GOOGLE_PROTOBUF_HASH_NAMESPACE __gnu_cxx -# include -# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map -# include -# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set -# endif - -// Version checks for gcc. -#elif defined(__GNUC__) -// For GCC 4.x+, use tr1::unordered_map/set; otherwise, follow the -// instructions from: -// https://gcc.gnu.org/onlinedocs/libstdc++/manual/backwards.html -# if __GNUC__ >= 4 -# define GOOGLE_PROTOBUF_HAS_TR1 -# elif __GNUC__ >= 3 -# include -# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map -# include -# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set -# if __GNUC__ == 3 && __GNUC_MINOR__ == 0 -# define GOOGLE_PROTOBUF_HASH_NAMESPACE std // GCC 3.0 -# else -# define GOOGLE_PROTOBUF_HASH_NAMESPACE __gnu_cxx // GCC 3.1 and later -# endif -# else -# define GOOGLE_PROTOBUF_HASH_NAMESPACE -# include -# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map -# include -# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set -# endif - -// GCC <= 4.1 does not define std::tr1::hash for `long long int` or `long long unsigned int` -# if __GNUC__ == 4 && defined(__GNUC_MINOR__) && __GNUC_MINOR__ <= 1 -# undef GOOGLE_PROTOBUF_HAS_TR1 -# undef GOOGLE_PROTOBUF_HAVE_HASH_MAP -# undef GOOGLE_PROTOBUF_HAVE_HASH_SET -# endif - -// Version checks for MSC. -// Apparently Microsoft decided to move hash_map *back* to the std namespace in -// MSVC 2010: -// http://blogs.msdn.com/vcblog/archive/2009/05/25/stl-breaking-changes-in-visual-studio-2010-beta-1.aspx -// And.. they are moved back to stdext in MSVC 2013 (haven't checked 2012). That -// said, use unordered_map for MSVC 2010 and beyond is our safest bet. -#elif defined(_MSC_VER) -# if _MSC_VER >= 1600 // Since Visual Studio 2010 -# define GOOGLE_PROTOBUF_HAS_CXX11_HASH -# define GOOGLE_PROTOBUF_HASH_COMPARE std::hash_compare -# elif _MSC_VER >= 1500 // Since Visual Studio 2008 -# define GOOGLE_PROTOBUF_HASH_NAMESPACE stdext -# include -# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map -# include -# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set -# define GOOGLE_PROTOBUF_HASH_COMPARE stdext::hash_compare -# define GOOGLE_PROTOBUF_CONTAINERS_NEED_HASH_COMPARE -# elif _MSC_VER >= 1310 -# define GOOGLE_PROTOBUF_HASH_NAMESPACE stdext -# include -# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map -# include -# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set -# define GOOGLE_PROTOBUF_HASH_COMPARE stdext::hash_compare -# else -# define GOOGLE_PROTOBUF_HASH_NAMESPACE std -# include -# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map -# include -# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set -# define GOOGLE_PROTOBUF_HASH_COMPARE stdext::hash_compare -# endif - -// **ADD NEW COMPILERS SUPPORT HERE.** -// For other compilers, undefine the macro and fallback to use std::map, in -// google/protobuf/stubs/hash.h -#else -# undef GOOGLE_PROTOBUF_HAVE_HASH_MAP -# undef GOOGLE_PROTOBUF_HAVE_HASH_SET -#endif - -#if defined(GOOGLE_PROTOBUF_HAS_CXX11_HASH) -# define GOOGLE_PROTOBUF_HASH_NAMESPACE std -# include -# define GOOGLE_PROTOBUF_HASH_MAP_CLASS unordered_map -# include -# define GOOGLE_PROTOBUF_HASH_SET_CLASS unordered_set -#elif defined(GOOGLE_PROTOBUF_HAS_TR1) -# define GOOGLE_PROTOBUF_HASH_NAMESPACE std::tr1 -# include -# define GOOGLE_PROTOBUF_HASH_MAP_CLASS unordered_map -# include -# define GOOGLE_PROTOBUF_HASH_SET_CLASS unordered_set -#endif +#include +#include # define GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_START \ namespace google { \ namespace protobuf { # define GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_END }} -#undef GOOGLE_PROTOBUF_HAS_CXX11_HASH -#undef GOOGLE_PROTOBUF_HAS_TR1 - -#if defined(GOOGLE_PROTOBUF_HAVE_HASH_MAP) && \ - defined(GOOGLE_PROTOBUF_HAVE_HASH_SET) -#else -#define GOOGLE_PROTOBUF_MISSING_HASH -#include -#include -#endif - namespace google { namespace protobuf { -#ifdef GOOGLE_PROTOBUF_MISSING_HASH -#undef GOOGLE_PROTOBUF_MISSING_HASH - -// This system doesn't have hash_map or hash_set. Emulate them using map and -// set. - -// Make hash be the same as less. Note that everywhere where custom -// hash functions are defined in the protobuf code, they are also defined such -// that they can be used as "less" functions, which is required by MSVC anyway. template -struct hash { - // Dummy, just to make derivative hash functions compile. - int operator()(const Key& key) { - GOOGLE_LOG(FATAL) << "Should never be called."; - return 0; - } - - inline bool operator()(const Key& a, const Key& b) const { - return a < b; - } -}; - -// Make sure char* is compared by value. -template <> -struct hash { - // Dummy, just to make derivative hash functions compile. - int operator()(const char* key) { - GOOGLE_LOG(FATAL) << "Should never be called."; - return 0; - } - - inline bool operator()(const char* a, const char* b) const { - return strcmp(a, b) < 0; - } -}; - -template , - typename EqualKey = std::equal_to, - typename Alloc = std::allocator< std::pair > > -class hash_map : public std::map { - typedef std::map BaseClass; - - public: - hash_map(int a = 0, const HashFcn& b = HashFcn(), - const EqualKey& c = EqualKey(), - const Alloc& d = Alloc()) : BaseClass(b, d) {} - - HashFcn hash_function() const { return HashFcn(); } -}; - -template , - typename EqualKey = std::equal_to > -class hash_set : public std::set { - public: - hash_set(int = 0) {} - - HashFcn hash_function() const { return HashFcn(); } -}; - -#elif defined(_MSC_VER) && !defined(_STLPORT_VERSION) && \ - !(defined(_LIBCPP_STD_VER) && _LIBCPP_STD_VER >= 11) - -template -struct hash : public GOOGLE_PROTOBUF_HASH_COMPARE { -}; - -// MSVC's hash_compare hashes based on the string contents but -// compares based on the string pointer. WTF? -class CstringLess { - public: - inline bool operator()(const char* a, const char* b) const { - return strcmp(a, b) < 0; - } -}; - -template <> -struct hash - : public GOOGLE_PROTOBUF_HASH_COMPARE {}; - -#ifdef GOOGLE_PROTOBUF_CONTAINERS_NEED_HASH_COMPARE - -template -struct InternalHashCompare : public GOOGLE_PROTOBUF_HASH_COMPARE { - InternalHashCompare() {} - InternalHashCompare(HashFcn hashfcn, EqualKey equalkey) - : hashfcn_(hashfcn), equalkey_(equalkey) {} - size_t operator()(const Key& key) const { return hashfcn_(key); } - bool operator()(const Key& key1, const Key& key2) const { - return !equalkey_(key1, key2); - } - HashFcn hashfcn_; - EqualKey equalkey_; -}; - -template , - typename EqualKey = std::equal_to, - typename Alloc = std::allocator< std::pair > > -class hash_map - : public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS< - Key, Data, InternalHashCompare, Alloc> { - typedef GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS< - Key, Data, InternalHashCompare, Alloc> BaseClass; - - public: - hash_map(int a = 0, const HashFcn& b = HashFcn(), - const EqualKey& c = EqualKey(), const Alloc& d = Alloc()) - : BaseClass(InternalHashCompare(b, c), d) {} - - HashFcn hash_function() const { return HashFcn(); } -}; - -template , - typename EqualKey = std::equal_to > -class hash_set - : public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_SET_CLASS< - Key, InternalHashCompare > { - public: - hash_set(int = 0) {} - - HashFcn hash_function() const { return HashFcn(); } -}; - -#else // GOOGLE_PROTOBUF_CONTAINERS_NEED_HASH_COMPARE - -template , - typename EqualKey = std::equal_to, - typename Alloc = std::allocator< std::pair > > -class hash_map - : public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS< - Key, Data, HashFcn, EqualKey, Alloc> { - typedef GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS< - Key, Data, HashFcn, EqualKey, Alloc> BaseClass; - - public: - hash_map(int a = 0, const HashFcn& b = HashFcn(), - const EqualKey& c = EqualKey(), - const Alloc& d = Alloc()) : BaseClass(a, b, c, d) {} - - HashFcn hash_function() const { return HashFcn(); } -}; - -template , - typename EqualKey = std::equal_to > -class hash_set - : public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_SET_CLASS< - Key, HashFcn, EqualKey> { - public: - hash_set(int = 0) {} - - HashFcn hash_function() const { return HashFcn(); } -}; -#endif // GOOGLE_PROTOBUF_CONTAINERS_NEED_HASH_COMPARE - -#else // defined(_MSC_VER) && !defined(_STLPORT_VERSION) - -template -struct hash : public GOOGLE_PROTOBUF_HASH_NAMESPACE::hash { -}; +struct hash : public std::hash {}; template struct hash { @@ -364,37 +77,6 @@ struct hash { } }; -template , - typename EqualKey = std::equal_to, - typename Alloc = std::allocator< std::pair > > -class hash_map - : public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS< - Key, Data, HashFcn, EqualKey, Alloc> { - typedef GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS< - Key, Data, HashFcn, EqualKey, Alloc> BaseClass; - - public: - hash_map(int a = 0, const HashFcn& b = HashFcn(), - const EqualKey& c = EqualKey(), - const Alloc& d = Alloc()) : BaseClass(a, b, c, d) {} - - HashFcn hash_function() const { return HashFcn(); } -}; - -template , - typename EqualKey = std::equal_to > -class hash_set - : public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_SET_CLASS< - Key, HashFcn, EqualKey> { - public: - hash_set(int = 0) {} - - HashFcn hash_function() const { return HashFcn(); } -}; - -#endif // !GOOGLE_PROTOBUF_MISSING_HASH - template <> struct hash { inline size_t operator()(const string& key) const { diff --git a/third_party/protobuf/src/google/protobuf/stubs/int128.cc b/third_party/protobuf/src/google/protobuf/stubs/int128.cc index a5090801..2119e655 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/int128.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/int128.cc @@ -34,12 +34,16 @@ #include // NOLINT(readability/streams) #include +#include + +#include + namespace google { namespace protobuf { const uint128_pod kuint128max = { - static_cast(GOOGLE_LONGLONG(0xFFFFFFFFFFFFFFFF)), - static_cast(GOOGLE_LONGLONG(0xFFFFFFFFFFFFFFFF)) + static_cast(PROTOBUF_LONGLONG(0xFFFFFFFFFFFFFFFF)), + static_cast(PROTOBUF_LONGLONG(0xFFFFFFFFFFFFFFFF)) }; // Returns the 0-based position of the last set bit (i.e., most significant bit) @@ -63,7 +67,7 @@ static inline int Fls64(uint64 n) { STEP(uint32, n32, pos, 0x10); STEP(uint32, n32, pos, 0x08); STEP(uint32, n32, pos, 0x04); - return pos + ((GOOGLE_ULONGLONG(0x3333333322221100) >> (n32 << 2)) & 0x3); + return pos + ((PROTOBUF_ULONGLONG(0x3333333322221100) >> (n32 << 2)) & 0x3); } #undef STEP @@ -76,52 +80,36 @@ static inline int Fls128(uint128 n) { return Fls64(Uint128Low64(n)); } -// Long division/modulo for uint128 implemented using the shift-subtract -// division algorithm adapted from: -// http://stackoverflow.com/questions/5386377/division-without-using void uint128::DivModImpl(uint128 dividend, uint128 divisor, uint128* quotient_ret, uint128* remainder_ret) { if (divisor == 0) { GOOGLE_LOG(FATAL) << "Division or mod by zero: dividend.hi=" << dividend.hi_ << ", lo=" << dividend.lo_; - } - - if (divisor > dividend) { + } else if (dividend < divisor) { *quotient_ret = 0; *remainder_ret = dividend; return; - } - - if (divisor == dividend) { - *quotient_ret = 1; - *remainder_ret = 0; - return; - } - - uint128 denominator = divisor; - uint128 position = 1; - uint128 quotient = 0; - - // Left aligns the MSB of the denominator and the dividend. - int shift = Fls128(dividend) - Fls128(denominator); - denominator <<= shift; - position <<= shift; - - // Uses shift-subtract algorithm to divide dividend by denominator. The - // remainder will be left in dividend. - while (position > 0) { - if (dividend >= denominator) { - dividend -= denominator; - quotient |= position; + } else { + int dividend_bit_length = Fls128(dividend); + int divisor_bit_length = Fls128(divisor); + int difference = dividend_bit_length - divisor_bit_length; + uint128 quotient = 0; + while (difference >= 0) { + quotient <<= 1; + uint128 shifted_divisor = divisor << difference; + if (shifted_divisor <= dividend) { + dividend -= shifted_divisor; + quotient += 1; + } + difference -= 1; } - position >>= 1; - denominator >>= 1; + //record the final quotient and remainder + *quotient_ret = quotient; + *remainder_ret = dividend; } - - *quotient_ret = quotient; - *remainder_ret = dividend; } + uint128& uint128::operator/=(const uint128& divisor) { uint128 quotient = 0; uint128 remainder = 0; @@ -145,15 +133,18 @@ std::ostream& operator<<(std::ostream& o, const uint128& b) { std::streamsize div_base_log; switch (flags & std::ios::basefield) { case std::ios::hex: - div = static_cast(GOOGLE_ULONGLONG(0x1000000000000000)); // 16^15 + div = + static_cast(PROTOBUF_ULONGLONG(0x1000000000000000)); // 16^15 div_base_log = 15; break; case std::ios::oct: - div = static_cast(GOOGLE_ULONGLONG(01000000000000000000000)); // 8^21 + div = static_cast( + PROTOBUF_ULONGLONG(01000000000000000000000)); // 8^21 div_base_log = 21; break; default: // std::ios::dec - div = static_cast(GOOGLE_ULONGLONG(10000000000000000000)); // 10^19 + div = static_cast( + PROTOBUF_ULONGLONG(10000000000000000000)); // 10^19 div_base_log = 19; break; } diff --git a/third_party/protobuf/src/google/protobuf/stubs/int128.h b/third_party/protobuf/src/google/protobuf/stubs/int128.h index 1499bb76..dc70d96e 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/int128.h +++ b/third_party/protobuf/src/google/protobuf/stubs/int128.h @@ -34,6 +34,8 @@ #include +#include + namespace google { namespace protobuf { @@ -48,7 +50,7 @@ struct uint128_pod; #endif // An unsigned 128-bit integer type. Thread-compatible. -class LIBPROTOBUF_EXPORT uint128 { +class PROTOBUF_EXPORT uint128 { public: UINT128_CONSTEXPR uint128(); // Sets to 0, but don't trust on this behavior. UINT128_CONSTEXPR uint128(uint64 top, uint64 bottom); @@ -84,8 +86,8 @@ class LIBPROTOBUF_EXPORT uint128 { friend uint64 Uint128High64(const uint128& v); // We add "std::" to avoid including all of port.h. - LIBPROTOBUF_EXPORT friend std::ostream& operator<<(std::ostream& o, - const uint128& b); + PROTOBUF_EXPORT friend std::ostream& operator<<(std::ostream& o, + const uint128& b); private: static void DivModImpl(uint128 dividend, uint128 divisor, @@ -116,11 +118,11 @@ struct uint128_pod { uint64 lo; }; -LIBPROTOBUF_EXPORT extern const uint128_pod kuint128max; +PROTOBUF_EXPORT extern const uint128_pod kuint128max; // allow uint128 to be logged -LIBPROTOBUF_EXPORT extern std::ostream& operator<<(std::ostream& o, - const uint128& b); +PROTOBUF_EXPORT extern std::ostream& operator<<(std::ostream& o, + const uint128& b); // Methods to access low and high pieces of 128-bit value. // Defined externally from uint128 to facilitate conversion @@ -380,4 +382,6 @@ inline uint128& uint128::operator--() { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_STUBS_INT128_H_ diff --git a/third_party/protobuf/src/google/protobuf/stubs/int128_unittest.cc b/third_party/protobuf/src/google/protobuf/stubs/int128_unittest.cc index 1ec899ad..9a8125d4 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/int128_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/int128_unittest.cc @@ -37,6 +37,8 @@ #include #include +#include + namespace google { namespace protobuf { @@ -291,24 +293,26 @@ TEST(Int128, Multiply) { } // Verified with dc. - a = uint128(GOOGLE_ULONGLONG(0xffffeeeeddddcccc), - GOOGLE_ULONGLONG(0xbbbbaaaa99998888)); - b = uint128(GOOGLE_ULONGLONG(0x7777666655554444), - GOOGLE_ULONGLONG(0x3333222211110000)); + a = uint128(PROTOBUF_ULONGLONG(0xffffeeeeddddcccc), + PROTOBUF_ULONGLONG(0xbbbbaaaa99998888)); + b = uint128(PROTOBUF_ULONGLONG(0x7777666655554444), + PROTOBUF_ULONGLONG(0x3333222211110000)); c = a * b; - EXPECT_EQ(uint128(GOOGLE_ULONGLONG(0x530EDA741C71D4C3), - GOOGLE_ULONGLONG(0xBF25975319080000)), c); + EXPECT_EQ(uint128(PROTOBUF_ULONGLONG(0x530EDA741C71D4C3), + PROTOBUF_ULONGLONG(0xBF25975319080000)), + c); EXPECT_EQ(0, c - b * a); - EXPECT_EQ(a*a - b*b, (a+b) * (a-b)); + EXPECT_EQ(a * a - b * b, (a + b) * (a - b)); // Verified with dc. - a = uint128(GOOGLE_ULONGLONG(0x0123456789abcdef), - GOOGLE_ULONGLONG(0xfedcba9876543210)); - b = uint128(GOOGLE_ULONGLONG(0x02468ace13579bdf), - GOOGLE_ULONGLONG(0xfdb97531eca86420)); + a = uint128(PROTOBUF_ULONGLONG(0x0123456789abcdef), + PROTOBUF_ULONGLONG(0xfedcba9876543210)); + b = uint128(PROTOBUF_ULONGLONG(0x02468ace13579bdf), + PROTOBUF_ULONGLONG(0xfdb97531eca86420)); c = a * b; - EXPECT_EQ(uint128(GOOGLE_ULONGLONG(0x97a87f4f261ba3f2), - GOOGLE_ULONGLONG(0x342d0bbf48948200)), c); + EXPECT_EQ(uint128(PROTOBUF_ULONGLONG(0x97a87f4f261ba3f2), + PROTOBUF_ULONGLONG(0x342d0bbf48948200)), + c); EXPECT_EQ(0, c - b * a); EXPECT_EQ(a*a - b*b, (a+b) * (a-b)); } @@ -355,10 +359,10 @@ TEST(Int128, DivideAndMod) { EXPECT_EQ(0, q); EXPECT_EQ(0, r); - a = uint128(GOOGLE_ULONGLONG(0x530eda741c71d4c3), - GOOGLE_ULONGLONG(0xbf25975319080000)); - q = uint128(GOOGLE_ULONGLONG(0x4de2cab081), - GOOGLE_ULONGLONG(0x14c34ab4676e4bab)); + a = uint128(PROTOBUF_ULONGLONG(0x530eda741c71d4c3), + PROTOBUF_ULONGLONG(0xbf25975319080000)); + q = uint128(PROTOBUF_ULONGLONG(0x4de2cab081), + PROTOBUF_ULONGLONG(0x14c34ab4676e4bab)); b = uint128(0x1110001); r = uint128(0x3eb455); ASSERT_EQ(a, q * b + r); // Sanity-check. @@ -396,8 +400,8 @@ TEST(Int128, DivideAndMod) { // Try a large remainder. b = a / 2 + 1; - uint128 expected_r(GOOGLE_ULONGLONG(0x29876d3a0e38ea61), - GOOGLE_ULONGLONG(0xdf92cba98c83ffff)); + uint128 expected_r(PROTOBUF_ULONGLONG(0x29876d3a0e38ea61), + PROTOBUF_ULONGLONG(0xdf92cba98c83ffff)); // Sanity checks. ASSERT_EQ(a / 2 - 1, expected_r); ASSERT_EQ(a, b + expected_r); @@ -455,50 +459,50 @@ TEST(Int128, OStream) { char fill; const char* rep; } cases[] = { - // zero with different bases - {uint128(0), std::ios::dec, 0, '_', "0"}, - {uint128(0), std::ios::oct, 0, '_', "0"}, - {uint128(0), std::ios::hex, 0, '_', "0"}, - // crossover between lo_ and hi_ - {uint128(0, -1), std::ios::dec, 0, '_', "18446744073709551615"}, - {uint128(0, -1), std::ios::oct, 0, '_', "1777777777777777777777"}, - {uint128(0, -1), std::ios::hex, 0, '_', "ffffffffffffffff"}, - {uint128(1, 0), std::ios::dec, 0, '_', "18446744073709551616"}, - {uint128(1, 0), std::ios::oct, 0, '_', "2000000000000000000000"}, - {uint128(1, 0), std::ios::hex, 0, '_', "10000000000000000"}, - // just the top bit - {uint128(GOOGLE_ULONGLONG(0x8000000000000000), 0), std::ios::dec, 0, '_', - "170141183460469231731687303715884105728"}, - {uint128(GOOGLE_ULONGLONG(0x8000000000000000), 0), std::ios::oct, 0, '_', - "2000000000000000000000000000000000000000000"}, - {uint128(GOOGLE_ULONGLONG(0x8000000000000000), 0), std::ios::hex, 0, '_', - "80000000000000000000000000000000"}, - // maximum uint128 value - {uint128(-1, -1), std::ios::dec, 0, '_', - "340282366920938463463374607431768211455"}, - {uint128(-1, -1), std::ios::oct, 0, '_', - "3777777777777777777777777777777777777777777"}, - {uint128(-1, -1), std::ios::hex, 0, '_', - "ffffffffffffffffffffffffffffffff"}, - // uppercase - {uint128(-1, -1), std::ios::hex | std::ios::uppercase, 0, '_', - "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"}, - // showbase - {uint128(1), std::ios::dec | std::ios::showbase, 0, '_', "1"}, - {uint128(1), std::ios::oct | std::ios::showbase, 0, '_', "01"}, - {uint128(1), std::ios::hex | std::ios::showbase, 0, '_', "0x1"}, - // showbase does nothing on zero - {uint128(0), std::ios::dec | std::ios::showbase, 0, '_', "0"}, - {uint128(0), std::ios::oct | std::ios::showbase, 0, '_', "0"}, - {uint128(0), std::ios::hex | std::ios::showbase, 0, '_', "0"}, - // showpos does nothing on unsigned types - {uint128(1), std::ios::dec | std::ios::showpos, 0, '_', "1"}, - // padding - {uint128(9), std::ios::dec, 6, '_', "_____9"}, - {uint128(12345), std::ios::dec, 6, '_', "_12345"}, - // left adjustment - {uint128(9), std::ios::dec | std::ios::left, 6, '_', "9_____"}, - {uint128(12345), std::ios::dec | std::ios::left, 6, '_', "12345_"}, + // zero with different bases + {uint128(0), std::ios::dec, 0, '_', "0"}, + {uint128(0), std::ios::oct, 0, '_', "0"}, + {uint128(0), std::ios::hex, 0, '_', "0"}, + // crossover between lo_ and hi_ + {uint128(0, -1), std::ios::dec, 0, '_', "18446744073709551615"}, + {uint128(0, -1), std::ios::oct, 0, '_', "1777777777777777777777"}, + {uint128(0, -1), std::ios::hex, 0, '_', "ffffffffffffffff"}, + {uint128(1, 0), std::ios::dec, 0, '_', "18446744073709551616"}, + {uint128(1, 0), std::ios::oct, 0, '_', "2000000000000000000000"}, + {uint128(1, 0), std::ios::hex, 0, '_', "10000000000000000"}, + // just the top bit + {uint128(PROTOBUF_ULONGLONG(0x8000000000000000), 0), std::ios::dec, 0, + '_', "170141183460469231731687303715884105728"}, + {uint128(PROTOBUF_ULONGLONG(0x8000000000000000), 0), std::ios::oct, 0, + '_', "2000000000000000000000000000000000000000000"}, + {uint128(PROTOBUF_ULONGLONG(0x8000000000000000), 0), std::ios::hex, 0, + '_', "80000000000000000000000000000000"}, + // maximum uint128 value + {uint128(-1, -1), std::ios::dec, 0, '_', + "340282366920938463463374607431768211455"}, + {uint128(-1, -1), std::ios::oct, 0, '_', + "3777777777777777777777777777777777777777777"}, + {uint128(-1, -1), std::ios::hex, 0, '_', + "ffffffffffffffffffffffffffffffff"}, + // uppercase + {uint128(-1, -1), std::ios::hex | std::ios::uppercase, 0, '_', + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"}, + // showbase + {uint128(1), std::ios::dec | std::ios::showbase, 0, '_', "1"}, + {uint128(1), std::ios::oct | std::ios::showbase, 0, '_', "01"}, + {uint128(1), std::ios::hex | std::ios::showbase, 0, '_', "0x1"}, + // showbase does nothing on zero + {uint128(0), std::ios::dec | std::ios::showbase, 0, '_', "0"}, + {uint128(0), std::ios::oct | std::ios::showbase, 0, '_', "0"}, + {uint128(0), std::ios::hex | std::ios::showbase, 0, '_', "0"}, + // showpos does nothing on unsigned types + {uint128(1), std::ios::dec | std::ios::showpos, 0, '_', "1"}, + // padding + {uint128(9), std::ios::dec, 6, '_', "_____9"}, + {uint128(12345), std::ios::dec, 6, '_', "_12345"}, + // left adjustment + {uint128(9), std::ios::dec | std::ios::left, 6, '_', "9_____"}, + {uint128(12345), std::ios::dec | std::ios::left, 6, '_', "12345_"}, }; for (size_t i = 0; i < GOOGLE_ARRAYSIZE(cases); ++i) { std::ostringstream os; diff --git a/third_party/protobuf/src/google/protobuf/stubs/logging.h b/third_party/protobuf/src/google/protobuf/stubs/logging.h index f69605d9..f37048d6 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/logging.h +++ b/third_party/protobuf/src/google/protobuf/stubs/logging.h @@ -34,6 +34,8 @@ #include #include +#include + // =================================================================== // emulates google3/base/logging.h @@ -70,7 +72,7 @@ namespace internal { class LogFinisher; -class LIBPROTOBUF_EXPORT LogMessage { +class PROTOBUF_EXPORT LogMessage { public: LogMessage(LogLevel level, const char* filename, int line); ~LogMessage(); @@ -87,7 +89,7 @@ class LIBPROTOBUF_EXPORT LogMessage { LogMessage& operator<<(double value); LogMessage& operator<<(void* value); LogMessage& operator<<(const StringPiece& value); - LogMessage& operator<<(const ::google::protobuf::util::Status& status); + LogMessage& operator<<(const util::Status& status); LogMessage& operator<<(const uint128& value); private: @@ -102,7 +104,7 @@ class LIBPROTOBUF_EXPORT LogMessage { // Used to make the entire "LOG(BLAH) << etc." expression have a void return // type and print a newline after each message. -class LIBPROTOBUF_EXPORT LogFinisher { +class PROTOBUF_EXPORT LogFinisher { public: void operator=(LogMessage& other); }; @@ -141,10 +143,10 @@ inline bool IsOk(bool status) { return status; } #undef GOOGLE_DCHECK_GT #undef GOOGLE_DCHECK_GE -#define GOOGLE_LOG(LEVEL) \ - ::google::protobuf::internal::LogFinisher() = \ - ::google::protobuf::internal::LogMessage( \ - ::google::protobuf::LOGLEVEL_##LEVEL, __FILE__, __LINE__) +#define GOOGLE_LOG(LEVEL) \ + ::google::protobuf::internal::LogFinisher() = \ + ::google::protobuf::internal::LogMessage( \ + ::google::protobuf::LOGLEVEL_##LEVEL, __FILE__, __LINE__) #define GOOGLE_LOG_IF(LEVEL, CONDITION) \ !(CONDITION) ? (void)0 : GOOGLE_LOG(LEVEL) @@ -162,15 +164,15 @@ namespace internal { template T* CheckNotNull(const char* /* file */, int /* line */, const char* name, T* val) { - if (val == NULL) { + if (val == nullptr) { GOOGLE_LOG(FATAL) << name; } return val; } } // namespace internal -#define GOOGLE_CHECK_NOTNULL(A) \ - ::google::protobuf::internal::CheckNotNull(\ - __FILE__, __LINE__, "'" #A "' must not be NULL", (A)) +#define GOOGLE_CHECK_NOTNULL(A) \ + ::google::protobuf::internal::CheckNotNull( \ + __FILE__, __LINE__, "'" #A "' must not be nullptr", (A)) #ifdef NDEBUG @@ -208,7 +210,7 @@ typedef void LogHandler(LogLevel level, const char* filename, int line, // also help end users figure out a problem. If you would prefer that // these messages be sent somewhere other than stderr, call SetLogHandler() // to set your own handler. This returns the old handler. Set the handler -// to NULL to ignore log messages (but see also LogSilencer, below). +// to nullptr to ignore log messages (but see also LogSilencer, below). // // Obviously, SetLogHandler is not thread-safe. You should only call it // at initialization time, and probably not from library code. If you @@ -216,7 +218,7 @@ typedef void LogHandler(LogLevel level, const char* filename, int line, // have some code that tends to trigger them frequently and you know // the warnings are not important to you), use the LogSilencer class // below. -LIBPROTOBUF_EXPORT LogHandler* SetLogHandler(LogHandler* new_func); +PROTOBUF_EXPORT LogHandler* SetLogHandler(LogHandler* new_func); // Create a LogSilencer if you want to temporarily suppress all log // messages. As long as any LogSilencer objects exist, non-fatal @@ -225,7 +227,7 @@ LIBPROTOBUF_EXPORT LogHandler* SetLogHandler(LogHandler* new_func); // accidentally suppress log messages occurring in another thread, but // since messages are generally for debugging purposes only, this isn't // a big deal. If you want to intercept log messages, use SetLogHandler(). -class LIBPROTOBUF_EXPORT LogSilencer { +class PROTOBUF_EXPORT LogSilencer { public: LogSilencer(); ~LogSilencer(); @@ -234,4 +236,6 @@ class LIBPROTOBUF_EXPORT LogSilencer { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_STUBS_LOGGING_H_ diff --git a/third_party/protobuf/src/google/protobuf/stubs/macros.h b/third_party/protobuf/src/google/protobuf/stubs/macros.h index 0e9a9ec1..c556d022 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/macros.h +++ b/third_party/protobuf/src/google/protobuf/stubs/macros.h @@ -112,55 +112,7 @@ struct CompileAssert { } // namespace internal -#undef GOOGLE_COMPILE_ASSERT -#if __cplusplus >= 201103L #define GOOGLE_COMPILE_ASSERT(expr, msg) static_assert(expr, #msg) -#else -#define GOOGLE_COMPILE_ASSERT(expr, msg) \ - ::google::protobuf::internal::CompileAssert<(bool(expr))> \ - msg[bool(expr) ? 1 : -1]; \ - (void)msg -// Implementation details of COMPILE_ASSERT: -// -// - COMPILE_ASSERT works by defining an array type that has -1 -// elements (and thus is invalid) when the expression is false. -// -// - The simpler definition -// -// #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1] -// -// does not work, as gcc supports variable-length arrays whose sizes -// are determined at run-time (this is gcc's extension and not part -// of the C++ standard). As a result, gcc fails to reject the -// following code with the simple definition: -// -// int foo; -// COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is -// // not a compile-time constant. -// -// - By using the type CompileAssert<(bool(expr))>, we ensures that -// expr is a compile-time constant. (Template arguments must be -// determined at compile-time.) -// -// - The outter parentheses in CompileAssert<(bool(expr))> are necessary -// to work around a bug in gcc 3.4.4 and 4.0.1. If we had written -// -// CompileAssert -// -// instead, these compilers will refuse to compile -// -// COMPILE_ASSERT(5 > 0, some_message); -// -// (They seem to think the ">" in "5 > 0" marks the end of the -// template argument list.) -// -// - The array size is (bool(expr) ? 1 : -1), instead of simply -// -// ((expr) ? 1 : -1). -// -// This is to avoid running into a bug in MS VC 7.1, which -// causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. -#endif // __cplusplus >= 201103L } // namespace protobuf } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/stubs/map_util.h b/third_party/protobuf/src/google/protobuf/stubs/map_util.h index 3e6d381f..2313e1f5 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/map_util.h +++ b/third_party/protobuf/src/google/protobuf/stubs/map_util.h @@ -131,7 +131,7 @@ FindWithDefault(const Collection& collection, } // Returns a pointer to the const value associated with the given key if it -// exists, or NULL otherwise. +// exists, or nullptr otherwise. template const typename Collection::value_type::second_type* FindOrNull(const Collection& collection, @@ -156,11 +156,11 @@ FindOrNull(Collection& collection, // NOLINT } // Returns the pointer value associated with the given key. If none is found, -// NULL is returned. The function is designed to be used with a map of keys to +// nullptr is returned. The function is designed to be used with a map of keys to // pointers. // // This function does not distinguish between a missing key and a key mapped -// to a NULL value. +// to nullptr. template typename Collection::value_type::second_type FindPtrOrNull(const Collection& collection, @@ -188,7 +188,7 @@ FindPtrOrNull(Collection& collection, // NOLINT } // Finds the pointer value associated with the given key in a map whose values -// are linked_ptrs. Returns NULL if key is not found. +// are linked_ptrs. Returns nullptr if key is not found. template typename Collection::value_type::second_type::element_type* FindLinkedPtrOrNull(const Collection& collection, @@ -215,7 +215,7 @@ FindLinkedPtrOrDie(const Collection& collection, } // Finds the value associated with the given key and copies it to *value (if not -// NULL). Returns false if the key was not found, true otherwise. +// nullptr). Returns false if the key was not found, true otherwise. template bool FindCopy(const Collection& collection, const Key& key, @@ -447,7 +447,7 @@ LookupOrInsertNew(Collection* const collection, std::pair ret = collection->insert(typename Collection::value_type( key, - static_cast(NULL))); + static_cast(nullptr))); if (ret.second) { ret.first->second = new Element(); } @@ -466,7 +466,7 @@ LookupOrInsertNew(Collection* const collection, std::pair ret = collection->insert(typename Collection::value_type( key, - static_cast(NULL))); + static_cast(nullptr))); if (ret.second) { ret.first->second = new Element(arg); } @@ -612,7 +612,7 @@ bool UpdateReturnCopy(Collection* const collection, return false; } -// Tries to insert the given key-value pair into the collection. Returns NULL if +// Tries to insert the given key-value pair into the collection. Returns nullptr if // the insert succeeds. Otherwise, returns a pointer to the existing value. // // This complements UpdateReturnCopy in that it allows to update only after @@ -625,7 +625,7 @@ InsertOrReturnExisting(Collection* const collection, const typename Collection::value_type& vt) { std::pair ret = collection->insert(vt); if (ret.second) { - return NULL; // Inserted, no existing previous value. + return nullptr; // Inserted, no existing previous value. } else { return &ret.first->second; // Return address of already existing value. } @@ -644,7 +644,7 @@ InsertOrReturnExisting( // Erases the collection item identified by the given key, and returns the value // associated with that key. It is assumed that the value (i.e., the -// mapped_type) is a pointer. Returns NULL if the key was not found in the +// mapped_type) is a pointer. Returns nullptr if the key was not found in the // collection. // // Examples: @@ -665,7 +665,7 @@ typename Collection::value_type::second_type EraseKeyReturnValuePtr( const typename Collection::value_type::first_type& key) { typename Collection::iterator it = collection->find(key); if (it == collection->end()) { - return NULL; + return nullptr; } typename Collection::value_type::second_type v = it->second; collection->erase(it); @@ -679,7 +679,7 @@ typename Collection::value_type::second_type EraseKeyReturnValuePtr( template void InsertKeysFromMap(const MapContainer& map_container, KeyContainer* key_container) { - GOOGLE_CHECK(key_container != NULL); + GOOGLE_CHECK(key_container != nullptr); for (typename MapContainer::const_iterator it = map_container.begin(); it != map_container.end(); ++it) { key_container->insert(it->first); @@ -693,7 +693,7 @@ void InsertKeysFromMap(const MapContainer& map_container, template void AppendKeysFromMap(const MapContainer& map_container, KeyContainer* key_container) { - GOOGLE_CHECK(key_container != NULL); + GOOGLE_CHECK(key_container != nullptr); for (typename MapContainer::const_iterator it = map_container.begin(); it != map_container.end(); ++it) { key_container->push_back(it->first); @@ -710,7 +710,7 @@ void AppendKeysFromMap(const MapContainer& map_container, template void AppendKeysFromMap(const MapContainer& map_container, std::vector* key_container) { - GOOGLE_CHECK(key_container != NULL); + GOOGLE_CHECK(key_container != nullptr); // We now have the opportunity to call reserve(). Calling reserve() every // time is a bad idea for some use cases: libstdc++'s implementation of // vector<>::reserve() resizes the vector's backing store to exactly the @@ -737,7 +737,7 @@ void AppendKeysFromMap(const MapContainer& map_container, template void AppendValuesFromMap(const MapContainer& map_container, ValueContainer* value_container) { - GOOGLE_CHECK(value_container != NULL); + GOOGLE_CHECK(value_container != nullptr); for (typename MapContainer::const_iterator it = map_container.begin(); it != map_container.end(); ++it) { value_container->push_back(it->second); @@ -754,7 +754,7 @@ void AppendValuesFromMap(const MapContainer& map_container, template void AppendValuesFromMap(const MapContainer& map_container, std::vector* value_container) { - GOOGLE_CHECK(value_container != NULL); + GOOGLE_CHECK(value_container != nullptr); // See AppendKeysFromMap for why this is done. if (value_container->empty()) { value_container->reserve(map_container.size()); diff --git a/third_party/protobuf/src/google/protobuf/stubs/mathlimits.cc b/third_party/protobuf/src/google/protobuf/stubs/mathlimits.cc index 0373b2bb..7a335bd6 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/mathlimits.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/mathlimits.cc @@ -40,42 +40,6 @@ namespace google { namespace protobuf { -// MSVC++ 2005 and older compilers think the header declaration was a -// definition, and erroneously flag these as a duplicate definition. -#if defined(COMPILER_MSVC) || __cpluscplus < 201103L - -#define DEF_COMMON_LIMITS(Type) -#define DEF_UNSIGNED_INT_LIMITS(Type) -#define DEF_SIGNED_INT_LIMITS(Type) -#define DEF_PRECISION_LIMITS(Type) - -#else - -#define DEF_COMMON_LIMITS(Type) \ -const bool MathLimits::kIsSigned; \ -const bool MathLimits::kIsInteger; \ -const int MathLimits::kMin10Exp; \ -const int MathLimits::kMax10Exp; - -#define DEF_UNSIGNED_INT_LIMITS(Type) \ -DEF_COMMON_LIMITS(Type) \ -const Type MathLimits::kPosMin; \ -const Type MathLimits::kPosMax; \ -const Type MathLimits::kMin; \ -const Type MathLimits::kMax; \ -const Type MathLimits::kEpsilon; \ -const Type MathLimits::kStdError; - -#define DEF_SIGNED_INT_LIMITS(Type) \ -DEF_UNSIGNED_INT_LIMITS(Type) \ -const Type MathLimits::kNegMin; \ -const Type MathLimits::kNegMax; - -#define DEF_PRECISION_LIMITS(Type) \ -const int MathLimits::kPrecisionDigits; - -#endif // not COMPILER_MSVC - // http://en.wikipedia.org/wiki/Quadruple_precision_floating-point_format#Double-double_arithmetic // With some compilers (gcc 4.6.x) on some platforms (powerpc64), // "long double" is implemented as a pair of double: "double double" format. @@ -101,7 +65,6 @@ const int MathLimits::kPrecisionDigits; // max(DBL_EPSILON * DBL_EPSILON, kEpsilon) rather than a multiple of kEpsilon. #define DEF_FP_LIMITS(Type, PREFIX) \ -DEF_COMMON_LIMITS(Type) \ const Type MathLimits::kPosMin = PREFIX##_MIN; \ const Type MathLimits::kPosMax = PREFIX##_MAX; \ const Type MathLimits::kMin = -MathLimits::kPosMax; \ @@ -113,32 +76,14 @@ const Type MathLimits::kEpsilon = PREFIX##_EPSILON; \ const Type MathLimits::kStdError = \ 32 * (DBL_EPSILON * DBL_EPSILON > MathLimits::kEpsilon \ ? DBL_EPSILON * DBL_EPSILON : MathLimits::kEpsilon); \ -DEF_PRECISION_LIMITS(Type) \ const Type MathLimits::kNaN = HUGE_VAL - HUGE_VAL; \ const Type MathLimits::kPosInf = HUGE_VAL; \ const Type MathLimits::kNegInf = -HUGE_VAL; -// The following are *not* casts! -DEF_SIGNED_INT_LIMITS(int8) -DEF_SIGNED_INT_LIMITS(int16) // NOLINT(readability/casting) -DEF_SIGNED_INT_LIMITS(int32) // NOLINT(readability/casting) -DEF_SIGNED_INT_LIMITS(int64) // NOLINT(readability/casting) -DEF_UNSIGNED_INT_LIMITS(uint8) -DEF_UNSIGNED_INT_LIMITS(uint16) // NOLINT(readability/casting) -DEF_UNSIGNED_INT_LIMITS(uint32) // NOLINT(readability/casting) -DEF_UNSIGNED_INT_LIMITS(uint64) // NOLINT(readability/casting) - -DEF_SIGNED_INT_LIMITS(long int) -DEF_UNSIGNED_INT_LIMITS(unsigned long int) - DEF_FP_LIMITS(float, FLT) DEF_FP_LIMITS(double, DBL) DEF_FP_LIMITS(long double, LDBL); -#undef DEF_COMMON_LIMITS -#undef DEF_SIGNED_INT_LIMITS -#undef DEF_UNSIGNED_INT_LIMITS #undef DEF_FP_LIMITS -#undef DEF_PRECISION_LIMITS } // namespace protobuf } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/stubs/mathlimits.h b/third_party/protobuf/src/google/protobuf/stubs/mathlimits.h index 9c9d0e9a..0e844322 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/mathlimits.h +++ b/third_party/protobuf/src/google/protobuf/stubs/mathlimits.h @@ -66,6 +66,8 @@ #include +#include + // ========================================================================= // // Useful integer and floating point limits and type traits. @@ -173,43 +175,43 @@ template struct MathLimits { static bool IsPosInf(const Type /*x*/) { return false; } \ static bool IsNegInf(const Type /*x*/) { return false; } -#define DECL_SIGNED_INT_LIMITS(IntType, UnsignedIntType) \ -template<> \ -struct LIBPROTOBUF_EXPORT MathLimits { \ - typedef IntType Type; \ - typedef UnsignedIntType UnsignedType; \ - static const bool kIsSigned = true; \ - static const bool kIsInteger = true; \ - static const Type kPosMin = 1; \ - static const Type kPosMax = SIGNED_INT_MAX(Type); \ - static const Type kMin = SIGNED_INT_MIN(Type); \ - static const Type kMax = kPosMax; \ - static const Type kNegMin = -1; \ - static const Type kNegMax = kMin; \ - static const int kMin10Exp = 0; \ - static const int kMax10Exp = SIGNED_MAX_10_EXP(Type); \ - static const Type kEpsilon = 1; \ - static const Type kStdError = 0; \ - DECL_INT_LIMIT_FUNCS \ -}; +#define DECL_SIGNED_INT_LIMITS(IntType, UnsignedIntType) \ + template <> \ + struct PROTOBUF_EXPORT MathLimits { \ + typedef IntType Type; \ + typedef UnsignedIntType UnsignedType; \ + static const bool kIsSigned = true; \ + static const bool kIsInteger = true; \ + static const Type kPosMin = 1; \ + static const Type kPosMax = SIGNED_INT_MAX(Type); \ + static const Type kMin = SIGNED_INT_MIN(Type); \ + static const Type kMax = kPosMax; \ + static const Type kNegMin = -1; \ + static const Type kNegMax = kMin; \ + static const int kMin10Exp = 0; \ + static const int kMax10Exp = SIGNED_MAX_10_EXP(Type); \ + static const Type kEpsilon = 1; \ + static const Type kStdError = 0; \ + DECL_INT_LIMIT_FUNCS \ + }; -#define DECL_UNSIGNED_INT_LIMITS(IntType) \ -template<> \ -struct LIBPROTOBUF_EXPORT MathLimits { \ - typedef IntType Type; \ - typedef IntType UnsignedType; \ - static const bool kIsSigned = false; \ - static const bool kIsInteger = true; \ - static const Type kPosMin = 1; \ - static const Type kPosMax = UNSIGNED_INT_MAX(Type); \ - static const Type kMin = 0; \ - static const Type kMax = kPosMax; \ - static const int kMin10Exp = 0; \ - static const int kMax10Exp = UNSIGNED_MAX_10_EXP(Type); \ - static const Type kEpsilon = 1; \ - static const Type kStdError = 0; \ - DECL_INT_LIMIT_FUNCS \ -}; +#define DECL_UNSIGNED_INT_LIMITS(IntType) \ + template <> \ + struct PROTOBUF_EXPORT MathLimits { \ + typedef IntType Type; \ + typedef IntType UnsignedType; \ + static const bool kIsSigned = false; \ + static const bool kIsInteger = true; \ + static const Type kPosMin = 1; \ + static const Type kPosMax = UNSIGNED_INT_MAX(Type); \ + static const Type kMin = 0; \ + static const Type kMax = kPosMax; \ + static const int kMin10Exp = 0; \ + static const int kMax10Exp = UNSIGNED_MAX_10_EXP(Type); \ + static const Type kEpsilon = 1; \ + static const Type kStdError = 0; \ + DECL_INT_LIMIT_FUNCS \ + }; DECL_SIGNED_INT_LIMITS(signed char, unsigned char) DECL_SIGNED_INT_LIMITS(signed short int, unsigned short int) @@ -243,7 +245,7 @@ DECL_UNSIGNED_INT_LIMITS(unsigned long long int) #endif // ========================================================================= // -#if WIN32 && !__MINGW32__ // Lacks built-in isnan() and isinf() +#if defined(_WIN32) && !defined(__MINGW32__) // Lacks built-in isnan() and isinf() #define DECL_FP_LIMIT_FUNCS \ static bool IsFinite(const Type x) { return _finite(x); } \ static bool IsNaN(const Type x) { return _isnan(x); } \ @@ -263,29 +265,29 @@ DECL_UNSIGNED_INT_LIMITS(unsigned long long int) // such constants are not considered to be primitive-type constants by gcc. // CAVEAT: Hence, they are going to be initialized only during // the global objects construction time. -#define DECL_FP_LIMITS(FP_Type, PREFIX) \ -template<> \ -struct LIBPROTOBUF_EXPORT MathLimits { \ - typedef FP_Type Type; \ - typedef FP_Type UnsignedType; \ - static const bool kIsSigned = true; \ - static const bool kIsInteger = false; \ - static const Type kPosMin; \ - static const Type kPosMax; \ - static const Type kMin; \ - static const Type kMax; \ - static const Type kNegMin; \ - static const Type kNegMax; \ - static const int kMin10Exp = PREFIX##_MIN_10_EXP; \ - static const int kMax10Exp = PREFIX##_MAX_10_EXP; \ - static const Type kEpsilon; \ - static const Type kStdError; \ - static const int kPrecisionDigits = PREFIX##_DIG; \ - static const Type kNaN; \ - static const Type kPosInf; \ - static const Type kNegInf; \ - DECL_FP_LIMIT_FUNCS \ -}; +#define DECL_FP_LIMITS(FP_Type, PREFIX) \ + template <> \ + struct PROTOBUF_EXPORT MathLimits { \ + typedef FP_Type Type; \ + typedef FP_Type UnsignedType; \ + static const bool kIsSigned = true; \ + static const bool kIsInteger = false; \ + static const Type kPosMin; \ + static const Type kPosMax; \ + static const Type kMin; \ + static const Type kMax; \ + static const Type kNegMin; \ + static const Type kNegMax; \ + static const int kMin10Exp = PREFIX##_MIN_10_EXP; \ + static const int kMax10Exp = PREFIX##_MAX_10_EXP; \ + static const Type kEpsilon; \ + static const Type kStdError; \ + static const int kPrecisionDigits = PREFIX##_DIG; \ + static const Type kNaN; \ + static const Type kPosInf; \ + static const Type kNegInf; \ + DECL_FP_LIMIT_FUNCS \ + }; DECL_FP_LIMITS(float, FLT) DECL_FP_LIMITS(double, DBL) @@ -300,4 +302,6 @@ DECL_FP_LIMITS(long double, LDBL) } // namespace protobuf } // namespace google +#include + #endif // UTIL_MATH_MATHLIMITS_H__ diff --git a/third_party/protobuf/src/google/protobuf/stubs/mathutil.h b/third_party/protobuf/src/google/protobuf/stubs/mathutil.h index 8a9f69a0..b87b2869 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/mathutil.h +++ b/third_party/protobuf/src/google/protobuf/stubs/mathutil.h @@ -67,7 +67,7 @@ class MathUtil { template static bool AlmostEquals(T a, T b) { - return ::google::protobuf::internal::AlmostEquals(a, b); + return internal::AlmostEquals(a, b); } // Largest of two values. diff --git a/third_party/protobuf/src/google/protobuf/stubs/mutex.h b/third_party/protobuf/src/google/protobuf/stubs/mutex.h index b9b7d2e1..a3118896 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/mutex.h +++ b/third_party/protobuf/src/google/protobuf/stubs/mutex.h @@ -32,8 +32,35 @@ #include +#ifdef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP + +#include + +// GetMessage conflicts with GeneratedMessageReflection::GetMessage(). +#ifdef GetMessage +#undef GetMessage +#endif + +#endif + #include +// Define thread-safety annotations for use below, if we are building with +// Clang. +#if defined(__clang__) && !defined(SWIG) +#define GOOGLE_PROTOBUF_ACQUIRE(...) \ + __attribute__((acquire_capability(__VA_ARGS__))) +#define GOOGLE_PROTOBUF_RELEASE(...) \ + __attribute__((release_capability(__VA_ARGS__))) +#define GOOGLE_PROTOBUF_CAPABILITY(x) __attribute__((capability(x))) +#else +#define GOOGLE_PROTOBUF_ACQUIRE(...) +#define GOOGLE_PROTOBUF_RELEASE(...) +#define GOOGLE_PROTOBUF_CAPABILITY(x) +#endif + +#include + // =================================================================== // emulates google3/base/mutex.h namespace google { @@ -42,26 +69,51 @@ namespace internal { #define GOOGLE_PROTOBUF_LINKER_INITIALIZED +#ifdef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP + +// This class is a lightweight replacement for std::mutex on Windows platforms. +// std::mutex does not work on Windows XP SP2 with the latest VC++ libraries, +// because it utilizes the Concurrency Runtime that is only supported on Windows +// XP SP3 and above. +class PROTOBUF_EXPORT CriticalSectionLock { + public: + CriticalSectionLock() { InitializeCriticalSection(&critical_section_); } + ~CriticalSectionLock() { DeleteCriticalSection(&critical_section_); } + void lock() { EnterCriticalSection(&critical_section_); } + void unlock() { LeaveCriticalSection(&critical_section_); } + + private: + CRITICAL_SECTION critical_section_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CriticalSectionLock); +}; + +#endif + // Mutex is a natural type to wrap. As both google and other organization have // specialized mutexes. gRPC also provides an injection mechanism for custom // mutexes. -class LIBPROTOBUF_EXPORT WrappedMutex { +class PROTOBUF_EXPORT GOOGLE_PROTOBUF_CAPABILITY("mutex") WrappedMutex { public: WrappedMutex() = default; - void Lock() { mu_.lock(); } - void Unlock() { mu_.unlock(); } + void Lock() GOOGLE_PROTOBUF_ACQUIRE() { mu_.lock(); } + void Unlock() GOOGLE_PROTOBUF_RELEASE() { mu_.unlock(); } // Crash if this Mutex is not held exclusively by this thread. // May fail to crash when it should; will never crash when it should not. void AssertHeld() const {} private: +#ifndef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP std::mutex mu_; +#else // ifndef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP + CriticalSectionLock mu_; +#endif // #ifndef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP }; using Mutex = WrappedMutex; // MutexLock(mu) acquires mu when constructed and releases it when destroyed. -class LIBPROTOBUF_EXPORT MutexLock { +class PROTOBUF_EXPORT MutexLock { public: explicit MutexLock(Mutex *mu) : mu_(mu) { this->mu_->Lock(); } ~MutexLock() { this->mu_->Unlock(); } @@ -74,12 +126,12 @@ class LIBPROTOBUF_EXPORT MutexLock { typedef MutexLock ReaderMutexLock; typedef MutexLock WriterMutexLock; -// MutexLockMaybe is like MutexLock, but is a no-op when mu is NULL. -class LIBPROTOBUF_EXPORT MutexLockMaybe { +// MutexLockMaybe is like MutexLock, but is a no-op when mu is nullptr. +class PROTOBUF_EXPORT MutexLockMaybe { public: explicit MutexLockMaybe(Mutex *mu) : - mu_(mu) { if (this->mu_ != NULL) { this->mu_->Lock(); } } - ~MutexLockMaybe() { if (this->mu_ != NULL) { this->mu_->Unlock(); } } + mu_(mu) { if (this->mu_ != nullptr) { this->mu_->Lock(); } } + ~MutexLockMaybe() { if (this->mu_ != nullptr) { this->mu_->Unlock(); } } private: Mutex *const mu_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLockMaybe); @@ -97,7 +149,7 @@ class ThreadLocalStorage { } T* Get() { T* result = static_cast(pthread_getspecific(key_)); - if (result == NULL) { + if (result == nullptr) { result = new T(); pthread_setspecific(key_, result); } @@ -123,8 +175,12 @@ using internal::ReaderMutexLock; using internal::WriterMutexLock; using internal::MutexLockMaybe; - } // namespace protobuf } // namespace google +#undef GOOGLE_PROTOBUF_ACQUIRE +#undef GOOGLE_PROTOBUF_RELEASE + +#include + #endif // GOOGLE_PROTOBUF_STUBS_MUTEX_H_ diff --git a/third_party/protobuf/src/google/protobuf/stubs/once.h b/third_party/protobuf/src/google/protobuf/stubs/once.h index f3835ccd..070d36d1 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/once.h +++ b/third_party/protobuf/src/google/protobuf/stubs/once.h @@ -28,59 +28,14 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// Author: kenton@google.com (Kenton Varda) -// -// emulates google3/base/once.h -// -// This header is intended to be included only by internal .cc files and -// generated .pb.cc files. Users should not use this directly. -// -// This is basically a portable version of pthread_once(). -// -// This header declares: -// * A type called ProtobufOnceType. -// * A macro GOOGLE_PROTOBUF_DECLARE_ONCE() which declares a variable of type -// ProtobufOnceType. This is the only legal way to declare such a variable. -// The macro may only be used at the global scope (you cannot create local or -// class member variables of this type). -// * A function GoogleOnceInit(ProtobufOnceType* once, void (*init_func)()). -// This function, when invoked multiple times given the same ProtobufOnceType -// object, will invoke init_func on the first call only, and will make sure -// none of the calls return before that first call to init_func has finished. -// * The user can provide a parameter which GoogleOnceInit() forwards to the -// user-provided function when it is called. Usage example: -// int a = 10; -// GoogleOnceInit(&my_once, &MyFunctionExpectingIntArgument, &a); -// * This implementation guarantees that ProtobufOnceType is a POD (i.e. no -// static initializer generated). -// -// This implements a way to perform lazy initialization. It's more efficient -// than using mutexes as no lock is needed if initialization has already -// happened. -// -// Example usage: -// void Init(); -// GOOGLE_PROTOBUF_DECLARE_ONCE(once_init); -// -// // Calls Init() exactly once. -// void InitOnce() { -// GoogleOnceInit(&once_init, &Init); -// } -// -// Note that if GoogleOnceInit() is called before main() has begun, it must -// only be called by the thread that will eventually call main() -- that is, -// the thread that performs dynamic initialization. In general this is a safe -// assumption since people don't usually construct threads before main() starts, -// but it is technically not guaranteed. Unfortunately, Win32 provides no way -// whatsoever to statically-initialize its synchronization primitives, so our -// only choice is to assume that dynamic initialization is single-threaded. - #ifndef GOOGLE_PROTOBUF_STUBS_ONCE_H__ #define GOOGLE_PROTOBUF_STUBS_ONCE_H__ #include #include +#include + namespace google { namespace protobuf { namespace internal { @@ -92,39 +47,9 @@ void call_once(Args&&... args ) { } } // namespace internal - -// TODO(gerbens) remove this once third_party is fully extracted -using ProtobufOnceType = internal::once_flag; - -inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)()) { - std::call_once(*once, init_func); -} - -template -inline void GoogleOnceInitArg(ProtobufOnceType* once, void (*init_func)(Arg*), - Arg* arg) { - std::call_once(*once, init_func, arg); -} - -class GoogleOnceDynamic { - public: - // If this->Init() has not been called before by any thread, - // execute (*func_with_arg)(arg) then return. - // Otherwise, wait until that prior invocation has finished - // executing its function, then return. - template - void Init(void (*func_with_arg)(T*), T* arg) { - GoogleOnceInitArg(&this->state_, func_with_arg, arg); - } - private: - ProtobufOnceType state_; -}; - -#define GOOGLE_PROTOBUF_ONCE_TYPE ::google::protobuf::ProtobufOnceType -#define GOOGLE_PROTOBUF_DECLARE_ONCE(NAME) \ - ::google::protobuf::ProtobufOnceType NAME - } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_STUBS_ONCE_H__ diff --git a/third_party/protobuf/src/google/protobuf/stubs/platform_macros.h b/third_party/protobuf/src/google/protobuf/stubs/platform_macros.h index c3a64dd2..ce1b1e36 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/platform_macros.h +++ b/third_party/protobuf/src/google/protobuf/stubs/platform_macros.h @@ -56,7 +56,7 @@ #elif defined(__aarch64__) #define GOOGLE_PROTOBUF_ARCH_AARCH64 1 #define GOOGLE_PROTOBUF_ARCH_64_BIT 1 -#elif defined(__MIPSEL__) +#elif defined(__mips__) #if defined(__LP64__) #define GOOGLE_PROTOBUF_ARCH_MIPS64 1 #define GOOGLE_PROTOBUF_ARCH_64_BIT 1 @@ -99,6 +99,7 @@ GOOGLE_PROTOBUF_PLATFORM_ERROR #if defined(__APPLE__) #define GOOGLE_PROTOBUF_OS_APPLE +#include #include #if TARGET_OS_IPHONE #define GOOGLE_PROTOBUF_OS_IPHONE @@ -125,4 +126,9 @@ GOOGLE_PROTOBUF_PLATFORM_ERROR #define GOOGLE_PROTOBUF_NO_THREADLOCAL #endif +#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 1070 +// __thread keyword requires at least 10.7 +#define GOOGLE_PROTOBUF_NO_THREADLOCAL +#endif + #endif // GOOGLE_PROTOBUF_PLATFORM_MACROS_H_ diff --git a/third_party/protobuf/src/google/protobuf/stubs/port.h b/third_party/protobuf/src/google/protobuf/stubs/port.h index 6b52305f..5b8e85dc 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/port.h +++ b/third_party/protobuf/src/google/protobuf/stubs/port.h @@ -46,6 +46,8 @@ #include +#include + #undef PROTOBUF_LITTLE_ENDIAN #ifdef _WIN32 // Assuming windows is always little-endian. @@ -72,6 +74,19 @@ #define PROTOBUF_LITTLE_ENDIAN 1 #endif #endif + +// These #includes are for the byte swap functions declared later on. +#ifdef _MSC_VER +#include // NOLINT(build/include) +#include +#elif defined(__APPLE__) +#include +#elif defined(__GLIBC__) || defined(__BIONIC__) || defined(__CYGWIN__) +#include // IWYU pragma: export +#endif + +// Legacy: some users reference these (internal-only) macros even though we +// don't need them any more. #if defined(_MSC_VER) && defined(PROTOBUF_USE_DLLS) #ifdef LIBPROTOBUF_EXPORTS #define LIBPROTOBUF_EXPORT __declspec(dllexport) @@ -88,17 +103,8 @@ #define LIBPROTOC_EXPORT #endif -// These #includes are for the byte swap functions declared later on. -#ifdef _MSC_VER -#include // NOLINT(build/include) -#include -#elif defined(__APPLE__) -#include -#elif defined(__GLIBC__) || defined(__BIONIC__) || defined(__CYGWIN__) -#include // IWYU pragma: export -#endif - #define PROTOBUF_RUNTIME_DEPRECATED(message) +#define GOOGLE_PROTOBUF_RUNTIME_DEPRECATED(message) // =================================================================== // from google3/base/port.h @@ -150,128 +156,12 @@ typedef uint32_t uint32; typedef uint64_t uint64; #endif -// long long macros to be used because gcc and vc++ use different suffixes, -// and different size specifiers in format strings -#undef GOOGLE_LONGLONG -#undef GOOGLE_ULONGLONG -#undef GOOGLE_LL_FORMAT - -#ifdef _MSC_VER -#define GOOGLE_LONGLONG(x) x##I64 -#define GOOGLE_ULONGLONG(x) x##UI64 -#define GOOGLE_LL_FORMAT "I64" // As in printf("%I64d", ...) -#else -// By long long, we actually mean int64. -#define GOOGLE_LONGLONG(x) x##LL -#define GOOGLE_ULONGLONG(x) x##ULL -// Used to format real long long integers. -#define GOOGLE_LL_FORMAT "ll" // As in "%lld". Note that "q" is poor form also. -#endif - static const int32 kint32max = 0x7FFFFFFF; static const int32 kint32min = -kint32max - 1; -static const int64 kint64max = GOOGLE_LONGLONG(0x7FFFFFFFFFFFFFFF); +static const int64 kint64max = PROTOBUF_LONGLONG(0x7FFFFFFFFFFFFFFF); static const int64 kint64min = -kint64max - 1; static const uint32 kuint32max = 0xFFFFFFFFu; -static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF); - -// ------------------------------------------------------------------- -// Annotations: Some parts of the code have been annotated in ways that might -// be useful to some compilers or tools, but are not supported universally. -// You can #define these annotations yourself if the default implementation -// is not right for you. - -#ifndef GOOGLE_ATTRIBUTE_ALWAYS_INLINE -#if defined(__GNUC__) && (__GNUC__ > 3 ||(__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) -// For functions we want to force inline. -// Introduced in gcc 3.1. -#define GOOGLE_ATTRIBUTE_ALWAYS_INLINE __attribute__ ((always_inline)) -#else -// Other compilers will have to figure it out for themselves. -#define GOOGLE_ATTRIBUTE_ALWAYS_INLINE -#endif -#endif - -#define GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE GOOGLE_ATTRIBUTE_ALWAYS_INLINE - -#ifndef GOOGLE_ATTRIBUTE_NOINLINE -#if defined(__GNUC__) && (__GNUC__ > 3 ||(__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) -// For functions we want to force not inline. -// Introduced in gcc 3.1. -#define GOOGLE_ATTRIBUTE_NOINLINE __attribute__ ((noinline)) -#elif defined(_MSC_VER) && (_MSC_VER >= 1400) -// Seems to have been around since at least Visual Studio 2005 -#define GOOGLE_ATTRIBUTE_NOINLINE __declspec(noinline) -#else -// Other compilers will have to figure it out for themselves. -#define GOOGLE_ATTRIBUTE_NOINLINE -#endif -#endif - -#define GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE GOOGLE_ATTRIBUTE_NOINLINE - -#ifndef GOOGLE_ATTRIBUTE_FUNC_ALIGN -#if defined(__clang__) || \ - defined(__GNUC__) && (__GNUC__ > 4 ||(__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) -// Function alignment attribute introduced in gcc 4.3 -#define GOOGLE_ATTRIBUTE_FUNC_ALIGN(bytes) __attribute__ ((aligned(bytes))) -#else -#define GOOGLE_ATTRIBUTE_FUNC_ALIGN(bytes) -#endif -#endif - -#define GOOGLE_PROTOBUF_ATTRIBUTE_FUNC_ALIGN(bytes) \ - GOOGLE_ATTRIBUTE_FUNC_ALIGN(bytes) - -#ifndef GOOGLE_PREDICT_TRUE -#ifdef __GNUC__ -// Provided at least since GCC 3.0. -#define GOOGLE_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1)) -#else -#define GOOGLE_PREDICT_TRUE(x) (x) -#endif -#endif - -#ifndef GOOGLE_PREDICT_FALSE -#ifdef __GNUC__ -// Provided at least since GCC 3.0. -#define GOOGLE_PREDICT_FALSE(x) (__builtin_expect(x, 0)) -#else -#define GOOGLE_PREDICT_FALSE(x) (x) -#endif -#endif - -#ifndef GOOGLE_PROTOBUF_ATTRIBUTE_RETURNS_NONNULL -#ifdef __GNUC__ -#define GOOGLE_PROTOBUF_ATTRIBUTE_RETURNS_NONNULL \ - __attribute__((returns_nonnull)) -#endif -#endif - -// Delimits a block of code which may write to memory which is simultaneously -// written by other threads, but which has been determined to be thread-safe -// (e.g. because it is an idempotent write). -#ifndef GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN -#define GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN() -#endif -#ifndef GOOGLE_SAFE_CONCURRENT_WRITES_END -#define GOOGLE_SAFE_CONCURRENT_WRITES_END() -#endif - -#define GOOGLE_GUARDED_BY(x) -#define GOOGLE_ATTRIBUTE_COLD - -#ifdef GOOGLE_PROTOBUF_DONT_USE_UNALIGNED -# define GOOGLE_PROTOBUF_USE_UNALIGNED 0 -#else -# if defined(_M_X64) || defined(__x86_64__) || defined(_M_IX86) || defined(__i386__) -# define GOOGLE_PROTOBUF_USE_UNALIGNED 1 -# else -# define GOOGLE_PROTOBUF_USE_UNALIGNED 0 -# endif -#endif - -#define GOOGLE_PROTOBUF_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_COLD +static const uint64 kuint64max = PROTOBUF_ULONGLONG(0xFFFFFFFFFFFFFFFF); #if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) ||\ defined(MEMORY_SANITIZER) @@ -382,10 +272,14 @@ inline void GOOGLE_UNALIGNED_STORE64(void *p, uint64 v) { #elif !defined(__GLIBC__) && !defined(__BIONIC__) && !defined(__CYGWIN__) +#ifndef bswap_16 static inline uint16 bswap_16(uint16 x) { return static_cast(((x & 0xFF) << 8) | ((x & 0xFF00) >> 8)); } #define bswap_16(x) bswap_16(x) +#endif + +#ifndef bswap_32 static inline uint32 bswap_32(uint32 x) { return (((x & 0xFF) << 24) | ((x & 0xFF00) << 8) | @@ -393,17 +287,21 @@ static inline uint32 bswap_32(uint32 x) { ((x & 0xFF000000) >> 24)); } #define bswap_32(x) bswap_32(x) +#endif + +#ifndef bswap_64 static inline uint64 bswap_64(uint64 x) { - return (((x & GOOGLE_ULONGLONG(0xFF)) << 56) | - ((x & GOOGLE_ULONGLONG(0xFF00)) << 40) | - ((x & GOOGLE_ULONGLONG(0xFF0000)) << 24) | - ((x & GOOGLE_ULONGLONG(0xFF000000)) << 8) | - ((x & GOOGLE_ULONGLONG(0xFF00000000)) >> 8) | - ((x & GOOGLE_ULONGLONG(0xFF0000000000)) >> 24) | - ((x & GOOGLE_ULONGLONG(0xFF000000000000)) >> 40) | - ((x & GOOGLE_ULONGLONG(0xFF00000000000000)) >> 56)); + return (((x & PROTOBUF_ULONGLONG(0xFF)) << 56) | + ((x & PROTOBUF_ULONGLONG(0xFF00)) << 40) | + ((x & PROTOBUF_ULONGLONG(0xFF0000)) << 24) | + ((x & PROTOBUF_ULONGLONG(0xFF000000)) << 8) | + ((x & PROTOBUF_ULONGLONG(0xFF00000000)) >> 8) | + ((x & PROTOBUF_ULONGLONG(0xFF0000000000)) >> 24) | + ((x & PROTOBUF_ULONGLONG(0xFF000000000000)) >> 40) | + ((x & PROTOBUF_ULONGLONG(0xFF00000000000000)) >> 56)); } #define bswap_64(x) bswap_64(x) +#endif #endif @@ -472,7 +370,7 @@ class Bits { // =================================================================== // from google3/util/endian/endian.h -LIBPROTOBUF_EXPORT uint32 ghtonl(uint32 x); +PROTOBUF_EXPORT uint32 ghtonl(uint32 x); class BigEndian { public: @@ -530,13 +428,16 @@ class BigEndian { } }; -#ifndef GOOGLE_ATTRIBUTE_SECTION_VARIABLE -#define GOOGLE_ATTRIBUTE_SECTION_VARIABLE(name) -#endif - -#define GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(name) - } // namespace protobuf } // namespace google +#ifdef PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +#define GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER \ + PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +#else +#define GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER 0 +#endif + +#include + #endif // GOOGLE_PROTOBUF_STUBS_PORT_H_ diff --git a/third_party/protobuf/src/google/protobuf/stubs/status.h b/third_party/protobuf/src/google/protobuf/stubs/status.h index c5d38f0b..440a0ed4 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/status.h +++ b/third_party/protobuf/src/google/protobuf/stubs/status.h @@ -36,6 +36,8 @@ #include #include +#include + namespace google { namespace protobuf { namespace util { @@ -62,7 +64,7 @@ enum Code { }; } // namespace error -class LIBPROTOBUF_EXPORT Status { +class PROTOBUF_EXPORT Status { public: // Creates a "successful" status. Status(); @@ -88,9 +90,15 @@ class LIBPROTOBUF_EXPORT Status { int error_code() const { return error_code_; } + error::Code code() const { + return error_code_; + } StringPiece error_message() const { return error_message_; } + StringPiece message() const { + return error_message_; + } bool operator==(const Status& x) const; bool operator!=(const Status& x) const { @@ -106,11 +114,14 @@ class LIBPROTOBUF_EXPORT Status { }; // Prints a human-readable representation of 'x' to 'os'. -LIBPROTOBUF_EXPORT std::ostream& operator<<(std::ostream& os, const Status& x); +PROTOBUF_EXPORT std::ostream& operator<<(std::ostream& os, const Status& x); #define EXPECT_OK(value) EXPECT_TRUE((value).ok()) } // namespace util } // namespace protobuf } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_STUBS_STATUS_H_ diff --git a/third_party/protobuf/src/google/protobuf/stubs/status_macros.h b/third_party/protobuf/src/google/protobuf/stubs/status_macros.h index 743e79a7..0c64317d 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/status_macros.h +++ b/third_party/protobuf/src/google/protobuf/stubs/status_macros.h @@ -46,11 +46,11 @@ namespace util { // // Example: // RETURN_IF_ERROR(DoThings(4)); -#define RETURN_IF_ERROR(expr) \ - do { \ +#define RETURN_IF_ERROR(expr) \ + do { \ /* Using _status below to avoid capture problems if expr is "status". */ \ - const ::google::protobuf::util::Status _status = (expr); \ - if (GOOGLE_PREDICT_FALSE(!_status.ok())) return _status; \ + const PROTOBUF_NAMESPACE_ID::util::Status _status = (expr); \ + if (PROTOBUF_PREDICT_FALSE(!_status.ok())) return _status; \ } while (0) // Internal helper for concatenating macro values. @@ -67,7 +67,7 @@ Status DoAssignOrReturn(T& lhs, StatusOr result) { #define ASSIGN_OR_RETURN_IMPL(status, lhs, rexpr) \ Status status = DoAssignOrReturn(lhs, (rexpr)); \ - if (GOOGLE_PREDICT_FALSE(!status.ok())) return status; + if (PROTOBUF_PREDICT_FALSE(!status.ok())) return status; // Executes an expression that returns a util::StatusOr, extracting its value // into the variable defined by lhs (or returning on error). diff --git a/third_party/protobuf/src/google/protobuf/stubs/status_test.cc b/third_party/protobuf/src/google/protobuf/stubs/status_test.cc index c70c33c4..9a18778f 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/status_test.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/status_test.cc @@ -40,13 +40,17 @@ namespace { TEST(Status, Empty) { util::Status status; EXPECT_EQ(util::error::OK, util::Status::OK.error_code()); + EXPECT_EQ(util::error::OK, util::Status::OK.code()); EXPECT_EQ("OK", util::Status::OK.ToString()); } TEST(Status, GenericCodes) { EXPECT_EQ(util::error::OK, util::Status::OK.error_code()); + EXPECT_EQ(util::error::OK, util::Status::OK.code()); EXPECT_EQ(util::error::CANCELLED, util::Status::CANCELLED.error_code()); + EXPECT_EQ(util::error::CANCELLED, util::Status::CANCELLED.code()); EXPECT_EQ(util::error::UNKNOWN, util::Status::UNKNOWN.error_code()); + EXPECT_EQ(util::error::UNKNOWN, util::Status::UNKNOWN.code()); } TEST(Status, ConstructorZero) { @@ -66,14 +70,17 @@ TEST(Status, ErrorMessage) { util::Status status(util::error::INVALID_ARGUMENT, ""); EXPECT_FALSE(status.ok()); EXPECT_EQ("", status.error_message().ToString()); + EXPECT_EQ("", status.message().ToString()); EXPECT_EQ("INVALID_ARGUMENT", status.ToString()); status = util::Status(util::error::INVALID_ARGUMENT, "msg"); EXPECT_FALSE(status.ok()); EXPECT_EQ("msg", status.error_message().ToString()); + EXPECT_EQ("msg", status.message().ToString()); EXPECT_EQ("INVALID_ARGUMENT:msg", status.ToString()); status = util::Status(util::error::OK, "msg"); EXPECT_TRUE(status.ok()); EXPECT_EQ("", status.error_message().ToString()); + EXPECT_EQ("", status.message().ToString()); EXPECT_EQ("OK", status.ToString()); } diff --git a/third_party/protobuf/src/google/protobuf/stubs/statusor.cc b/third_party/protobuf/src/google/protobuf/stubs/statusor.cc index 48d1402a..c744b8d2 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/statusor.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/statusor.cc @@ -30,6 +30,8 @@ #include +#include + namespace google { namespace protobuf { namespace util { diff --git a/third_party/protobuf/src/google/protobuf/stubs/statusor.h b/third_party/protobuf/src/google/protobuf/stubs/statusor.h index 29f869ad..90fd5f0d 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/statusor.h +++ b/third_party/protobuf/src/google/protobuf/stubs/statusor.h @@ -33,7 +33,7 @@ // usable value, or an error Status explaining why such a value is // not present. To this end, StatusOr does not allow its Status // value to be Status::OK. Further, StatusOr does not allow the -// contained pointer to be NULL. +// contained pointer to be nullptr. // // The primary use-case for StatusOr is as the return value of a // function which may fail. @@ -89,6 +89,8 @@ #include +#include + namespace google { namespace protobuf { namespace util { @@ -114,15 +116,15 @@ class StatusOr { StatusOr(const Status& status); // NOLINT // Construct a new StatusOr with the given value. If T is a plain pointer, - // value must not be NULL. After calling this constructor, calls to + // value must not be nullptr. After calling this constructor, calls to // ValueOrDie() will succeed, and calls to status() will return OK. // // NOTE: Not explicit - we want to use StatusOr as a return type // so it is convenient and sensible to be able to do 'return T()' // when when the return type is StatusOr. // - // REQUIRES: if T is a plain pointer, value != NULL. This requirement is - // DCHECKed. In optimized builds, passing a NULL pointer here will have + // REQUIRES: if T is a plain pointer, value != nullptr. This requirement is + // DCHECKed. In optimized builds, passing a null pointer here will have // the effect of passing PosixErrorSpace::EINVAL as a fallback. StatusOr(const T& value); // NOLINT @@ -162,7 +164,7 @@ class StatusOr { namespace internal { -class LIBPROTOBUF_EXPORT StatusOrHelper { +class PROTOBUF_EXPORT StatusOrHelper { public: // Move type-agnostic error handling to the .cc. static void Crash(const util::Status& status); @@ -174,13 +176,13 @@ class LIBPROTOBUF_EXPORT StatusOrHelper { template struct StatusOrHelper::Specialize { - // For non-pointer T, a reference can never be NULL. + // For non-pointer T, a reference can never be nullptr. static inline bool IsValueNull(const T& t) { return false; } }; template struct StatusOrHelper::Specialize { - static inline bool IsValueNull(const T* t) { return t == NULL; } + static inline bool IsValueNull(const T* t) { return t == nullptr; } }; } // namespace internal @@ -202,7 +204,7 @@ inline StatusOr::StatusOr(const Status& status) { template inline StatusOr::StatusOr(const T& value) { if (internal::StatusOrHelper::Specialize::IsValueNull(value)) { - status_ = Status(error::INTERNAL, "NULL is not a vaild argument."); + status_ = Status(error::INTERNAL, "nullptr is not a vaild argument."); } else { status_ = Status::OK; value_ = value; @@ -256,4 +258,6 @@ inline const T& StatusOr::ValueOrDie() const { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_STUBS_STATUSOR_H_ diff --git a/third_party/protobuf/src/google/protobuf/stubs/stl_util.h b/third_party/protobuf/src/google/protobuf/stubs/stl_util.h index 9e4c82a4..2c265e92 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/stl_util.h +++ b/third_party/protobuf/src/google/protobuf/stubs/stl_util.h @@ -82,7 +82,7 @@ inline void STLStringResizeUninitialized(string* s, size_t new_size) { // already work on all current implementations. inline char* string_as_array(string* str) { // DO NOT USE const_cast(str->data())! See the unittest for why. - return str->empty() ? NULL : &*str->begin(); + return str->empty() ? nullptr : &*str->begin(); } // STLDeleteElements() deletes all the elements in an STL container and clears @@ -90,7 +90,7 @@ inline char* string_as_array(string* str) { // hash_set, or any other STL container which defines sensible begin(), end(), // and clear() methods. // -// If container is NULL, this function is a no-op. +// If container is nullptr, this function is a no-op. // // As an alternative to calling STLDeleteElements() directly, consider // ElementDeleter (defined below), which ensures that your container's elements @@ -104,7 +104,7 @@ void STLDeleteElements(T *container) { // Given an STL container consisting of (key, value) pairs, STLDeleteValues // deletes all the "value" components and clears the container. Does nothing -// in the case it's given a NULL pointer. +// in the case it's given a null pointer. template void STLDeleteValues(T *v) { diff --git a/third_party/protobuf/src/google/protobuf/stubs/stringpiece.cc b/third_party/protobuf/src/google/protobuf/stubs/stringpiece.cc index 989474b7..fc2f5210 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/stringpiece.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/stringpiece.cc @@ -35,6 +35,8 @@ #include #include +#include + namespace google { namespace protobuf { std::ostream& operator<<(std::ostream& o, StringPiece piece) { @@ -115,7 +117,7 @@ stringpiece_ssize_type StringPiece::find(char c, size_type pos) const { } const char* result = static_cast( memchr(ptr_ + pos, c, length_ - pos)); - return result != NULL ? result - ptr_ : npos; + return result != nullptr ? result - ptr_ : npos; } stringpiece_ssize_type StringPiece::rfind(StringPiece s, size_type pos) const { diff --git a/third_party/protobuf/src/google/protobuf/stubs/stringpiece.h b/third_party/protobuf/src/google/protobuf/stubs/stringpiece.h index 563ff75d..2ae38813 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/stringpiece.h +++ b/third_party/protobuf/src/google/protobuf/stubs/stringpiece.h @@ -76,30 +76,30 @@ // // There are several ways to create a null StringPiece: // StringPiece() -// StringPiece(NULL) -// StringPiece(NULL, 0) -// For all of the above, sp.data() == NULL, sp.length() == 0, +// StringPiece(nullptr) +// StringPiece(nullptr, 0) +// For all of the above, sp.data() == nullptr, sp.length() == 0, // and sp.empty() == true. Also, if you create a StringPiece with -// a non-NULL pointer then sp.data() != NULL. Once created, -// sp.data() will stay either NULL or not-NULL, except if you call +// a non-null pointer then sp.data() != nullptr. Once created, +// sp.data() will stay either nullptr or not-nullptr, except if you call // sp.clear() or sp.set(). // -// Thus, you can use StringPiece(NULL) to signal an out-of-band value +// Thus, you can use StringPiece(nullptr) to signal an out-of-band value // that is different from other StringPiece values. This is similar -// to the way that const char* p1 = NULL; is different from +// to the way that const char* p1 = nullptr; is different from // const char* p2 = "";. // // There are many ways to create an empty StringPiece: // StringPiece() -// StringPiece(NULL) -// StringPiece(NULL, 0) +// StringPiece(nullptr) +// StringPiece(nullptr, 0) // StringPiece("") // StringPiece("", 0) // StringPiece("abcdef", 0) // StringPiece("abcdef"+6, 0) // For all of the above, sp.length() will be 0 and sp.empty() will be true. -// For some empty StringPiece values, sp.data() will be NULL. -// For some empty StringPiece values, sp.data() will not be NULL. +// For some empty StringPiece values, sp.data() will be nullptr. +// For some empty StringPiece values, sp.data() will not be nullptr. // // Be careful not to confuse: null StringPiece and empty StringPiece. // The set of empty StringPieces properly includes the set of null StringPieces. @@ -109,20 +109,20 @@ // All empty StringPiece values compare equal to each other. // Even a null StringPieces compares equal to a non-null empty StringPiece: // StringPiece() == StringPiece("", 0) -// StringPiece(NULL) == StringPiece("abc", 0) -// StringPiece(NULL, 0) == StringPiece("abcdef"+6, 0) +// StringPiece(nullptr) == StringPiece("abc", 0) +// StringPiece(nullptr, 0) == StringPiece("abcdef"+6, 0) // // Look carefully at this example: -// StringPiece("") == NULL +// StringPiece("") == nullptr // True or false? TRUE, because StringPiece::operator== converts -// the right-hand side from NULL to StringPiece(NULL), +// the right-hand side from nullptr to StringPiece(nullptr), // and then compares two zero-length spans of characters. // However, we are working to make this example produce a compile error. // // Suppose you want to write: -// bool TestWhat?(StringPiece sp) { return sp == NULL; } // BAD +// bool TestWhat?(StringPiece sp) { return sp == nullptr; } // BAD // Do not do that. Write one of these instead: -// bool TestNull(StringPiece sp) { return sp.data() == NULL; } +// bool TestNull(StringPiece sp) { return sp.data() == nullptr; } // bool TestEmpty(StringPiece sp) { return sp.empty(); } // The intent of TestWhat? is unclear. Did you mean TestNull or TestEmpty? // Right now, TestWhat? behaves likes TestEmpty. @@ -151,6 +151,8 @@ #include #include +#include + namespace google { namespace protobuf { // StringPiece has *two* size types. @@ -175,7 +177,7 @@ typedef string::difference_type stringpiece_ssize_type; #define STRINGPIECE_CHECK_SIZE 0 #endif -class LIBPROTOBUF_EXPORT StringPiece { +class PROTOBUF_EXPORT StringPiece { private: const char* ptr_; stringpiece_ssize_type length_; @@ -207,11 +209,11 @@ class LIBPROTOBUF_EXPORT StringPiece { // // Style guide exception granted: // http://goto/style-guide-exception-20978288 - StringPiece() : ptr_(NULL), length_(0) {} + StringPiece() : ptr_(nullptr), length_(0) {} StringPiece(const char* str) // NOLINT(runtime/explicit) : ptr_(str), length_(0) { - if (str != NULL) { + if (str != nullptr) { length_ = CheckedSsizeTFromSizeT(strlen(str)); } } @@ -248,7 +250,7 @@ class LIBPROTOBUF_EXPORT StringPiece { bool empty() const { return length_ == 0; } void clear() { - ptr_ = NULL; + ptr_ = nullptr; length_ = 0; } @@ -260,7 +262,7 @@ class LIBPROTOBUF_EXPORT StringPiece { void set(const char* str) { ptr_ = str; - if (str != NULL) + if (str != nullptr) length_ = CheckedSsizeTFromSizeT(strlen(str)); else length_ = 0; @@ -309,7 +311,7 @@ class LIBPROTOBUF_EXPORT StringPiece { // for a StringPiece be called "as_string()". We also leave the // "as_string()" method defined here for existing code. string ToString() const { - if (ptr_ == NULL) return string(); + if (ptr_ == nullptr) return string(); return string(data(), static_cast(size())); } @@ -463,6 +465,9 @@ struct StringPiecePod { std::string ToString() const { return std::string(data_, static_cast(size_)); } + + operator string() const { return ToString(); } + private: const char* data_; stringpiece_ssize_type size_; @@ -476,7 +481,7 @@ GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_START template<> struct hash { size_t operator()(const StringPiece& s) const { size_t result = 0; - for (const char *str = s.data(), *end = str + s.size(); str < end; str++) { + for (const char *str = s.data(), *end = str + s.size(); str < end; str++) { result = 5 * result + static_cast(*str); } return result; @@ -484,4 +489,6 @@ template<> struct hash { }; GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_END +#include + #endif // STRINGS_STRINGPIECE_H_ diff --git a/third_party/protobuf/src/google/protobuf/stubs/stringpiece_unittest.cc b/third_party/protobuf/src/google/protobuf/stubs/stringpiece_unittest.cc index a6a87595..d9a32d03 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/stringpiece_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/stringpiece_unittest.cc @@ -46,7 +46,7 @@ TEST(StringPiece, Ctor) { { // Null. StringPiece s10; - EXPECT_TRUE(s10.data() == NULL); + EXPECT_TRUE(s10.data() == nullptr); EXPECT_EQ(0, s10.length()); } @@ -148,8 +148,8 @@ TEST(StringPiece, ComparisonOperators) { EXPECT_EQ(result, StringPiece((x)).compare(StringPiece((y))) op 0) COMPARE(true, ==, "", ""); - COMPARE(true, ==, "", NULL); - COMPARE(true, ==, NULL, ""); + COMPARE(true, ==, "", nullptr); + COMPARE(true, ==, nullptr, ""); COMPARE(true, ==, "a", "a"); COMPARE(true, ==, "aa", "aa"); COMPARE(false, ==, "a", ""); @@ -253,7 +253,7 @@ TEST(StringPiece, STL1) { EXPECT_EQ(*d.data(), 'f'); EXPECT_EQ(d.data()[5], 'r'); - EXPECT_TRUE(e.data() == NULL); + EXPECT_TRUE(e.data() == nullptr); EXPECT_EQ(*a.begin(), 'a'); EXPECT_EQ(*(b.begin() + 2), 'c'); @@ -312,7 +312,7 @@ TEST(StringPiece, STL2) { d.clear(); EXPECT_EQ(d.size(), 0); EXPECT_TRUE(d.empty()); - EXPECT_TRUE(d.data() == NULL); + EXPECT_TRUE(d.data() == nullptr); EXPECT_TRUE(d.begin() == d.end()); EXPECT_EQ(StringPiece::npos, string::npos); @@ -707,17 +707,17 @@ TEST(StringPiece, Contains) { EXPECT_TRUE(!a.contains(d)); } -TEST(StringPiece, NULLInput) { +TEST(StringPiece, NullInput) { // we used to crash here, but now we don't. - StringPiece s(NULL); - EXPECT_EQ(s.data(), (const char*)NULL); + StringPiece s(nullptr); + EXPECT_EQ(s.data(), (const char*)nullptr); EXPECT_EQ(s.size(), 0); - s.set(NULL); - EXPECT_EQ(s.data(), (const char*)NULL); + s.set(nullptr); + EXPECT_EQ(s.data(), (const char*)nullptr); EXPECT_EQ(s.size(), 0); - // .ToString() on a StringPiece with NULL should produce the empty string. + // .ToString() on a StringPiece with nullptr should produce the empty string. EXPECT_EQ("", s.ToString()); EXPECT_EQ("", s.as_string()); } diff --git a/third_party/protobuf/src/google/protobuf/stubs/stringprintf.cc b/third_party/protobuf/src/google/protobuf/stubs/stringprintf.cc index d98b9b87..e6019fc6 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/stringprintf.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/stringprintf.cc @@ -36,7 +36,9 @@ #include // For va_list and related operations #include // MSVC requires this for _vsnprintf #include + #include +#include namespace google { namespace protobuf { @@ -76,7 +78,7 @@ void StringAppendV(string* dst, const char* format, va_list ap) { // Error or MSVC running out of space. MSVC 8.0 and higher // can be asked about space needed with the special idiom below: va_copy(backup_ap, ap); - result = vsnprintf(NULL, 0, format, backup_ap); + result = vsnprintf(nullptr, 0, format, backup_ap); va_end(backup_ap); } diff --git a/third_party/protobuf/src/google/protobuf/stubs/stringprintf.h b/third_party/protobuf/src/google/protobuf/stubs/stringprintf.h index 7183ec6a..253d736a 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/stringprintf.h +++ b/third_party/protobuf/src/google/protobuf/stubs/stringprintf.h @@ -46,31 +46,38 @@ #include +#include + namespace google { namespace protobuf { // Return a C++ string -LIBPROTOBUF_EXPORT extern string StringPrintf(const char* format, ...); +PROTOBUF_EXPORT extern string StringPrintf(const char* format, ...); // Store result into a supplied string and return it -LIBPROTOBUF_EXPORT extern const string& SStringPrintf(string* dst, const char* format, ...); +PROTOBUF_EXPORT extern const string& SStringPrintf(string* dst, + const char* format, ...); // Append result to a supplied string -LIBPROTOBUF_EXPORT extern void StringAppendF(string* dst, const char* format, ...); +PROTOBUF_EXPORT extern void StringAppendF(string* dst, const char* format, ...); // Lower-level routine that takes a va_list and appends to a specified // string. All other routines are just convenience wrappers around it. -LIBPROTOBUF_EXPORT extern void StringAppendV(string* dst, const char* format, va_list ap); +PROTOBUF_EXPORT extern void StringAppendV(string* dst, const char* format, + va_list ap); // The max arguments supported by StringPrintfVector -LIBPROTOBUF_EXPORT extern const int kStringPrintfVectorMaxArgs; +PROTOBUF_EXPORT extern const int kStringPrintfVectorMaxArgs; // You can use this version when all your arguments are strings, but // you don't know how many arguments you'll have at compile time. // StringPrintfVector will LOG(FATAL) if v.size() > kStringPrintfVectorMaxArgs -LIBPROTOBUF_EXPORT extern string StringPrintfVector(const char* format, const std::vector& v); +PROTOBUF_EXPORT extern string StringPrintfVector(const char* format, + const std::vector& v); } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_STUBS_STRINGPRINTF_H diff --git a/third_party/protobuf/src/google/protobuf/stubs/stringprintf_unittest.cc b/third_party/protobuf/src/google/protobuf/stubs/stringprintf_unittest.cc index 15895e59..7fcbf500 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/stringprintf_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/stringprintf_unittest.cc @@ -91,7 +91,7 @@ TEST(StringPrintfTest, Multibyte) { // out of memory while trying to determine destination buffer size. // see b/4194543. - char* old_locale = setlocale(LC_CTYPE, NULL); + char* old_locale = setlocale(LC_CTYPE, nullptr); // Push locale with multibyte mode setlocale(LC_CTYPE, "en_US.utf8"); @@ -120,7 +120,7 @@ TEST(StringPrintfTest, Multibyte) { TEST(StringPrintfTest, NoMultibyte) { // No multibyte handling, but the string contains funny chars. - char* old_locale = setlocale(LC_CTYPE, NULL); + char* old_locale = setlocale(LC_CTYPE, nullptr); setlocale(LC_CTYPE, "POSIX"); string value = StringPrintf("%.*s", 3, "\375\067s"); setlocale(LC_CTYPE, old_locale); diff --git a/third_party/protobuf/src/google/protobuf/stubs/structurally_valid.cc b/third_party/protobuf/src/google/protobuf/stubs/structurally_valid.cc index b2239682..0598427d 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/structurally_valid.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/structurally_valid.cc @@ -555,7 +555,7 @@ InitDetector init_detector; bool IsStructurallyValidUTF8(const char* buf, int len) { if (!module_initialized_) return true; - + int bytes_consumed = 0; UTF8GenericScanFastAscii(&utf8acceptnonsurrogates_obj, buf, len, &bytes_consumed); diff --git a/third_party/protobuf/src/google/protobuf/stubs/strutil.cc b/third_party/protobuf/src/google/protobuf/stubs/strutil.cc index 552d416f..3844fa6b 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/strutil.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/strutil.cc @@ -31,16 +31,18 @@ // from google3/strings/strutil.cc #include -#include #include #include // FLT_DIG and DBL_DIG -#include #include #include +#include #include +#include +#include #include +#include #ifdef _WIN32 // MSVC has only _snprintf, not snprintf. @@ -87,7 +89,7 @@ void StripString(string* s, const char* remove, char replacewith) { const char * str_start = s->c_str(); const char * str = str_start; for (str = strpbrk(str, remove); - str != NULL; + str != nullptr; str = strpbrk(str + 1, remove)) { (*s)[str - str_start] = replacewith; } @@ -102,7 +104,7 @@ void ReplaceCharacters(string *s, const char *remove, char replacewith) { const char *str_start = s->c_str(); const char *str = str_start; for (str = strpbrk(str, remove); - str != NULL; + str != nullptr; str = strpbrk(str + 1, remove)) { (*s)[str - str_start] = replacewith; } @@ -280,7 +282,7 @@ static void JoinStringsIterator(const ITERATOR& start, const ITERATOR& end, const char* delim, string* result) { - GOOGLE_CHECK(result != NULL); + GOOGLE_CHECK(result != nullptr); result->clear(); int delim_length = strlen(delim); @@ -318,7 +320,7 @@ void JoinStrings(const std::vector& components, // result is truncated to 8 bits. // // The second call stores its errors in a supplied string vector. -// If the string vector pointer is NULL, it reports the errors with LOG(). +// If the string vector pointer is nullptr, it reports the errors with LOG(). // ---------------------------------------------------------------------- #define IS_OCTAL_DIGIT(c) (((c) >= '0') && ((c) <= '7')) @@ -328,12 +330,12 @@ void JoinStrings(const std::vector& components, #define LOG_STRING(LEVEL, VECTOR) GOOGLE_LOG_IF(LEVEL, false) int UnescapeCEscapeSequences(const char* source, char* dest) { - return UnescapeCEscapeSequences(source, dest, NULL); + return UnescapeCEscapeSequences(source, dest, nullptr); } int UnescapeCEscapeSequences(const char* source, char* dest, std::vector *errors) { - GOOGLE_DCHECK(errors == NULL) << "Error reporting not implemented."; + GOOGLE_DCHECK(errors == nullptr) << "Error reporting not implemented."; char* d = dest; const char* p = source; @@ -458,13 +460,13 @@ int UnescapeCEscapeSequences(const char* source, char* dest, // to be the same. // // The second call stores its errors in a supplied string vector. -// If the string vector pointer is NULL, it reports the errors with LOG(). +// If the string vector pointer is nullptr, it reports the errors with LOG(). // // In the first and second calls, the length of dest is returned. In the // the third call, the new string is returned. // ---------------------------------------------------------------------- int UnescapeCEscapeString(const string& src, string* dest) { - return UnescapeCEscapeString(src, dest, NULL); + return UnescapeCEscapeString(src, dest, nullptr); } int UnescapeCEscapeString(const string& src, string* dest, @@ -478,7 +480,7 @@ int UnescapeCEscapeString(const string& src, string* dest, string UnescapeCEscapeString(const string& src) { std::unique_ptr unescaped(new char[src.size() + 1]); - int len = UnescapeCEscapeSequences(src.c_str(), unescaped.get(), NULL); + int len = UnescapeCEscapeSequences(src.c_str(), unescaped.get(), nullptr); return string(unescaped.get(), len); } @@ -982,7 +984,7 @@ static const char two_ASCII_digits[100][2] = { char* FastUInt32ToBufferLeft(uint32 u, char* buffer) { uint32 digits; - const char *ASCII_digits = NULL; + const char *ASCII_digits = nullptr; // The idea of this implementation is to trim the number of divides to as few // as possible by using multiplication and subtraction rather than mod (%), // and by outputting two digits at a time rather than one. @@ -1073,7 +1075,7 @@ char* FastInt32ToBufferLeft(int32 i, char* buffer) { char* FastUInt64ToBufferLeft(uint64 u64, char* buffer) { int digits; - const char *ASCII_digits = NULL; + const char *ASCII_digits = nullptr; uint32 u = static_cast(u64); if (u == u64) return FastUInt32ToBufferLeft(u, buffer); @@ -1114,10 +1116,12 @@ char* FastUInt64ToBufferLeft(uint64 u64, char* buffer) { } char* FastInt64ToBufferLeft(int64 i, char* buffer) { - uint64 u = i; + uint64 u = 0; if (i < 0) { *buffer++ = '-'; - u = -i; + u -= i; + } else { + u = i; } return FastUInt64ToBufferLeft(u, buffer); } @@ -1231,7 +1235,7 @@ static inline bool IsValidFloatChar(char c) { void DelocalizeRadix(char* buffer) { // Fast check: if the buffer has a normal decimal point, assume no // translation is needed. - if (strchr(buffer, '.') != NULL) return; + if (strchr(buffer, '.') != nullptr) return; // Find the first unknown character. while (IsValidFloatChar(*buffer)) ++buffer; @@ -1268,7 +1272,7 @@ char* DoubleToBuffer(double value, char* buffer) { } else if (value == -std::numeric_limits::infinity()) { strcpy(buffer, "-inf"); return buffer; - } else if (MathLimits::IsNaN(value)) { + } else if (std::isnan(value)) { strcpy(buffer, "nan"); return buffer; } @@ -1286,7 +1290,7 @@ char* DoubleToBuffer(double value, char* buffer) { // of a double. This long double may have extra bits that make it compare // unequal to "value" even though it would be exactly equal if it were // truncated to a double. - volatile double parsed_value = strtod(buffer, NULL); + volatile double parsed_value = io::NoLocaleStrtod(buffer, nullptr); if (parsed_value != value) { int snprintf_result = snprintf(buffer, kDoubleToBufferSize, "%.*g", DBL_DIG+2, value); @@ -1318,7 +1322,7 @@ inline bool CaseEqual(StringPiece s1, StringPiece s2) { } bool safe_strtob(StringPiece str, bool* value) { - GOOGLE_CHECK(value != NULL) << "NULL output boolean given."; + GOOGLE_CHECK(value != nullptr) << "nullptr output boolean given."; if (CaseEqual(str, "true") || CaseEqual(str, "t") || CaseEqual(str, "yes") || CaseEqual(str, "y") || CaseEqual(str, "1")) { @@ -1338,7 +1342,7 @@ bool safe_strtof(const char* str, float* value) { char* endptr; errno = 0; // errno only gets set on errors #if defined(_WIN32) || defined (__hpux) // has no strtof() - *value = strtod(str, &endptr); + *value = io::NoLocaleStrtod(str, &endptr); #else *value = strtof(str, &endptr); #endif @@ -1347,7 +1351,7 @@ bool safe_strtof(const char* str, float* value) { bool safe_strtod(const char* str, double* value) { char* endptr; - *value = strtod(str, &endptr); + *value = io::NoLocaleStrtod(str, &endptr); if (endptr != str) { while (ascii_isspace(*endptr)) ++endptr; } @@ -1386,7 +1390,7 @@ char* FloatToBuffer(float value, char* buffer) { } else if (value == -std::numeric_limits::infinity()) { strcpy(buffer, "-inf"); return buffer; - } else if (MathLimits::IsNaN(value)) { + } else if (std::isnan(value)) { strcpy(buffer, "nan"); return buffer; } @@ -1619,7 +1623,7 @@ void StrAppend(string *result, int GlobalReplaceSubstring(const string& substring, const string& replacement, string* s) { - GOOGLE_CHECK(s != NULL); + GOOGLE_CHECK(s != nullptr); if (s->empty() || substring.empty()) return 0; string tmp; @@ -1959,24 +1963,25 @@ int Base64UnescapeInternal(const char *src_param, int szsrc, // #include // #include // #include +// #include // main() // { // static const char Base64[] = // "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -// char *pos; +// const char *pos; // int idx, i, j; // printf(" "); // for (i = 0; i < 255; i += 8) { // for (j = i; j < i + 8; j++) { // pos = strchr(Base64, j); -// if ((pos == NULL) || (j == 0)) +// if ((pos == nullptr) || (j == 0)) // idx = -1; // else // idx = pos - Base64; // if (idx == -1) // printf(" %2d, ", idx); // else -// printf(" %2d/*%c*/,", idx, j); +// printf(" %2d/""*%c*""/,", idx, j); // } // printf("\n "); // } @@ -1994,7 +1999,7 @@ static const signed char kUnBase64[] = { 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/, 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1, -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/, - 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/, + 7/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/, 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/, 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1, -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/, @@ -2028,7 +2033,7 @@ static const signed char kUnWebSafeBase64[] = { 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/, 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1, -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/, - 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/, + 7/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/, 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/, 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, 63/*_*/, -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/, @@ -2300,5 +2305,110 @@ int UTF8FirstLetterNumBytes(const char* src, int len) { return kUTF8LenTbl[*reinterpret_cast(src)]; } +// ---------------------------------------------------------------------- +// CleanStringLineEndings() +// Clean up a multi-line string to conform to Unix line endings. +// Reads from src and appends to dst, so usually dst should be empty. +// +// If there is no line ending at the end of a non-empty string, it can +// be added automatically. +// +// Four different types of input are correctly handled: +// +// - Unix/Linux files: line ending is LF: pass through unchanged +// +// - DOS/Windows files: line ending is CRLF: convert to LF +// +// - Legacy Mac files: line ending is CR: convert to LF +// +// - Garbled files: random line endings: convert gracefully +// lonely CR, lonely LF, CRLF: convert to LF +// +// @param src The multi-line string to convert +// @param dst The converted string is appended to this string +// @param auto_end_last_line Automatically terminate the last line +// +// Limitations: +// +// This does not do the right thing for CRCRLF files created by +// broken programs that do another Unix->DOS conversion on files +// that are already in CRLF format. For this, a two-pass approach +// brute-force would be needed that +// +// (1) determines the presence of LF (first one is ok) +// (2) if yes, removes any CR, else convert every CR to LF + +void CleanStringLineEndings(const string &src, string *dst, + bool auto_end_last_line) { + if (dst->empty()) { + dst->append(src); + CleanStringLineEndings(dst, auto_end_last_line); + } else { + string tmp = src; + CleanStringLineEndings(&tmp, auto_end_last_line); + dst->append(tmp); + } +} + +void CleanStringLineEndings(string *str, bool auto_end_last_line) { + ptrdiff_t output_pos = 0; + bool r_seen = false; + ptrdiff_t len = str->size(); + + char *p = &(*str)[0]; + + for (ptrdiff_t input_pos = 0; input_pos < len;) { + if (!r_seen && input_pos + 8 < len) { + uint64_t v = GOOGLE_UNALIGNED_LOAD64(p + input_pos); + // Loop over groups of 8 bytes at a time until we come across + // a word that has a byte whose value is less than or equal to + // '\r' (i.e. could contain a \n (0x0a) or a \r (0x0d) ). + // + // We use a has_less macro that quickly tests a whole 64-bit + // word to see if any of the bytes has a value < N. + // + // For more details, see: + // http://graphics.stanford.edu/~seander/bithacks.html#HasLessInWord +#define has_less(x, n) (((x) - ~0ULL / 255 * (n)) & ~(x) & ~0ULL / 255 * 128) + if (!has_less(v, '\r' + 1)) { +#undef has_less + // No byte in this word has a value that could be a \r or a \n + if (output_pos != input_pos) { + GOOGLE_UNALIGNED_STORE64(p + output_pos, v); + } + input_pos += 8; + output_pos += 8; + continue; + } + } + string::const_reference in = p[input_pos]; + if (in == '\r') { + if (r_seen) p[output_pos++] = '\n'; + r_seen = true; + } else if (in == '\n') { + if (input_pos != output_pos) + p[output_pos++] = '\n'; + else + output_pos++; + r_seen = false; + } else { + if (r_seen) p[output_pos++] = '\n'; + r_seen = false; + if (input_pos != output_pos) + p[output_pos++] = in; + else + output_pos++; + } + input_pos++; + } + if (r_seen || + (auto_end_last_line && output_pos > 0 && p[output_pos - 1] != '\n')) { + str->resize(output_pos + 1); + str->operator[](output_pos) = '\n'; + } else if (output_pos < len) { + str->resize(output_pos); + } +} + } // namespace protobuf } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/stubs/strutil.h b/third_party/protobuf/src/google/protobuf/stubs/strutil.h index a839b8b3..790500d2 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/strutil.h +++ b/third_party/protobuf/src/google/protobuf/stubs/strutil.h @@ -38,10 +38,12 @@ #include #include +#include + namespace google { namespace protobuf { -#ifdef _MSC_VER +#if defined(_MSC_VER) && _MSC_VER < 1800 #define strtoll _strtoi64 #define strtoull _strtoui64 #elif defined(__DECCXX) && defined(__osf__) @@ -155,13 +157,12 @@ inline string StripSuffixString(const string& str, const string& suffix) { // StripWhitespace // Removes whitespaces from both ends of the given string. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT void ReplaceCharacters(string* s, const char* remove, - char replacewith); -LIBPROTOBUF_EXPORT void StripString(string* s, const char* remove, - char replacewith); - -LIBPROTOBUF_EXPORT void StripWhitespace(string* s); +PROTOBUF_EXPORT void ReplaceCharacters(string* s, const char* remove, + char replacewith); +PROTOBUF_EXPORT void StripString(string* s, const char* remove, + char replacewith); +PROTOBUF_EXPORT void StripWhitespace(string* s); // ---------------------------------------------------------------------- // LowerString() @@ -203,8 +204,8 @@ inline string ToUpper(const string& s) { // happened or not. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT string StringReplace(const string& s, const string& oldsub, - const string& newsub, bool replace_all); +PROTOBUF_EXPORT string StringReplace(const string& s, const string& oldsub, + const string& newsub, bool replace_all); // ---------------------------------------------------------------------- // SplitStringUsing() @@ -212,8 +213,8 @@ LIBPROTOBUF_EXPORT string StringReplace(const string& s, const string& oldsub, // to 'result'. If there are consecutive delimiters, this function skips // over all of them. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT void SplitStringUsing(const string& full, const char* delim, - std::vector* res); +PROTOBUF_EXPORT void SplitStringUsing(const string& full, const char* delim, + std::vector* res); // Split a string using one or more byte delimiters, presented // as a nul-terminated c string. Append the components to 'result'. @@ -223,9 +224,9 @@ LIBPROTOBUF_EXPORT void SplitStringUsing(const string& full, const char* delim, // // If "full" is the empty string, yields an empty string as the only value. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT void SplitStringAllowEmpty(const string& full, - const char* delim, - std::vector* result); +PROTOBUF_EXPORT void SplitStringAllowEmpty(const string& full, + const char* delim, + std::vector* result); // ---------------------------------------------------------------------- // Split() @@ -250,8 +251,8 @@ inline std::vector Split( // another takes a pointer to the target string. In the latter case the // target string is cleared and overwritten. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT void JoinStrings(const std::vector& components, - const char* delim, string* result); +PROTOBUF_EXPORT void JoinStrings(const std::vector& components, + const char* delim, string* result); inline string JoinStrings(const std::vector& components, const char* delim) { @@ -285,15 +286,15 @@ inline string JoinStrings(const std::vector& components, // // Errors: In the first form of the call, errors are reported with // LOG(ERROR). The same is true for the second form of the call if -// the pointer to the string std::vector is NULL; otherwise, error +// the pointer to the string std::vector is nullptr; otherwise, error // messages are stored in the std::vector. In either case, the effect on // the dest array is not defined, but rest of the source will be // processed. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest); -LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest, - std::vector *errors); +PROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest); +PROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest, + std::vector* errors); // ---------------------------------------------------------------------- // UnescapeCEscapeString() @@ -304,16 +305,16 @@ LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest, // to be the same. // // The second call stores its errors in a supplied string vector. -// If the string vector pointer is NULL, it reports the errors with LOG(). +// If the string vector pointer is nullptr, it reports the errors with LOG(). // // In the first and second calls, the length of dest is returned. In the // the third call, the new string is returned. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest); -LIBPROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest, - std::vector *errors); -LIBPROTOBUF_EXPORT string UnescapeCEscapeString(const string& src); +PROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest); +PROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest, + std::vector* errors); +PROTOBUF_EXPORT string UnescapeCEscapeString(const string& src); // ---------------------------------------------------------------------- // CEscape() @@ -322,21 +323,21 @@ LIBPROTOBUF_EXPORT string UnescapeCEscapeString(const string& src); // // Escaped chars: \n, \r, \t, ", ', \, and !isprint(). // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT string CEscape(const string& src); +PROTOBUF_EXPORT string CEscape(const string& src); // ---------------------------------------------------------------------- // CEscapeAndAppend() // Escapes 'src' using C-style escape sequences, and appends the escaped // string to 'dest'. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT void CEscapeAndAppend(StringPiece src, string* dest); +PROTOBUF_EXPORT void CEscapeAndAppend(StringPiece src, string* dest); namespace strings { // Like CEscape() but does not escape bytes with the upper bit set. -LIBPROTOBUF_EXPORT string Utf8SafeCEscape(const string& src); +PROTOBUF_EXPORT string Utf8SafeCEscape(const string& src); // Like CEscape() but uses hex (\x) escapes instead of octals. -LIBPROTOBUF_EXPORT string CHexEscape(const string& src); +PROTOBUF_EXPORT string CHexEscape(const string& src); } // namespace strings // ---------------------------------------------------------------------- @@ -349,10 +350,10 @@ LIBPROTOBUF_EXPORT string CHexEscape(const string& src); // platforms, so using these is safer, from the point of view of // overflow behavior, than using the standard libc functions. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT int32 strto32_adaptor(const char *nptr, char **endptr, - int base); -LIBPROTOBUF_EXPORT uint32 strtou32_adaptor(const char *nptr, char **endptr, - int base); +PROTOBUF_EXPORT int32 strto32_adaptor(const char* nptr, char** endptr, + int base); +PROTOBUF_EXPORT uint32 strtou32_adaptor(const char* nptr, char** endptr, + int base); inline int32 strto32(const char *nptr, char **endptr, int base) { if (sizeof(int32) == sizeof(long)) @@ -391,10 +392,10 @@ inline uint64 strtou64(const char *nptr, char **endptr, int base) { // safe_strtof() // safe_strtod() // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT bool safe_strtob(StringPiece str, bool* value); +PROTOBUF_EXPORT bool safe_strtob(StringPiece str, bool* value); -LIBPROTOBUF_EXPORT bool safe_strto32(const string& str, int32* value); -LIBPROTOBUF_EXPORT bool safe_strtou32(const string& str, uint32* value); +PROTOBUF_EXPORT bool safe_strto32(const string& str, int32* value); +PROTOBUF_EXPORT bool safe_strtou32(const string& str, uint32* value); inline bool safe_strto32(const char* str, int32* value) { return safe_strto32(string(str), value); } @@ -408,8 +409,8 @@ inline bool safe_strtou32(StringPiece str, uint32* value) { return safe_strtou32(str.ToString(), value); } -LIBPROTOBUF_EXPORT bool safe_strto64(const string& str, int64* value); -LIBPROTOBUF_EXPORT bool safe_strtou64(const string& str, uint64* value); +PROTOBUF_EXPORT bool safe_strto64(const string& str, int64* value); +PROTOBUF_EXPORT bool safe_strtou64(const string& str, uint64* value); inline bool safe_strto64(const char* str, int64* value) { return safe_strto64(string(str), value); } @@ -423,8 +424,8 @@ inline bool safe_strtou64(StringPiece str, uint64* value) { return safe_strtou64(str.ToString(), value); } -LIBPROTOBUF_EXPORT bool safe_strtof(const char* str, float* value); -LIBPROTOBUF_EXPORT bool safe_strtod(const char* str, double* value); +PROTOBUF_EXPORT bool safe_strtof(const char* str, float* value); +PROTOBUF_EXPORT bool safe_strtod(const char* str, double* value); inline bool safe_strtof(const string& str, float* value) { return safe_strtof(str.c_str(), value); } @@ -464,13 +465,13 @@ inline bool safe_strtod(StringPiece str, double* value) { // DoubleToBuffer() and FloatToBuffer(). static const int kFastToBufferSize = 32; -LIBPROTOBUF_EXPORT char* FastInt32ToBuffer(int32 i, char* buffer); -LIBPROTOBUF_EXPORT char* FastInt64ToBuffer(int64 i, char* buffer); +PROTOBUF_EXPORT char* FastInt32ToBuffer(int32 i, char* buffer); +PROTOBUF_EXPORT char* FastInt64ToBuffer(int64 i, char* buffer); char* FastUInt32ToBuffer(uint32 i, char* buffer); // inline below char* FastUInt64ToBuffer(uint64 i, char* buffer); // inline below -LIBPROTOBUF_EXPORT char* FastHexToBuffer(int i, char* buffer); -LIBPROTOBUF_EXPORT char* FastHex64ToBuffer(uint64 i, char* buffer); -LIBPROTOBUF_EXPORT char* FastHex32ToBuffer(uint32 i, char* buffer); +PROTOBUF_EXPORT char* FastHexToBuffer(int i, char* buffer); +PROTOBUF_EXPORT char* FastHex64ToBuffer(uint64 i, char* buffer); +PROTOBUF_EXPORT char* FastHex32ToBuffer(uint32 i, char* buffer); // at least 22 bytes long inline char* FastIntToBuffer(int i, char* buffer) { @@ -506,10 +507,10 @@ inline char* FastULongToBuffer(unsigned long i, char* buffer) { // terminating the string). // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT char* FastInt32ToBufferLeft(int32 i, char* buffer); -LIBPROTOBUF_EXPORT char* FastUInt32ToBufferLeft(uint32 i, char* buffer); -LIBPROTOBUF_EXPORT char* FastInt64ToBufferLeft(int64 i, char* buffer); -LIBPROTOBUF_EXPORT char* FastUInt64ToBufferLeft(uint64 i, char* buffer); +PROTOBUF_EXPORT char* FastInt32ToBufferLeft(int32 i, char* buffer); +PROTOBUF_EXPORT char* FastUInt32ToBufferLeft(uint32 i, char* buffer); +PROTOBUF_EXPORT char* FastInt64ToBufferLeft(int64 i, char* buffer); +PROTOBUF_EXPORT char* FastUInt64ToBufferLeft(uint64 i, char* buffer); // Just define these in terms of the above. inline char* FastUInt32ToBuffer(uint32 i, char* buffer) { @@ -531,12 +532,12 @@ inline string SimpleBtoa(bool value) { // // Return value: string // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT string SimpleItoa(int i); -LIBPROTOBUF_EXPORT string SimpleItoa(unsigned int i); -LIBPROTOBUF_EXPORT string SimpleItoa(long i); -LIBPROTOBUF_EXPORT string SimpleItoa(unsigned long i); -LIBPROTOBUF_EXPORT string SimpleItoa(long long i); -LIBPROTOBUF_EXPORT string SimpleItoa(unsigned long long i); +PROTOBUF_EXPORT string SimpleItoa(int i); +PROTOBUF_EXPORT string SimpleItoa(unsigned int i); +PROTOBUF_EXPORT string SimpleItoa(long i); +PROTOBUF_EXPORT string SimpleItoa(unsigned long i); +PROTOBUF_EXPORT string SimpleItoa(long long i); +PROTOBUF_EXPORT string SimpleItoa(unsigned long long i); // ---------------------------------------------------------------------- // SimpleDtoa() @@ -557,11 +558,11 @@ LIBPROTOBUF_EXPORT string SimpleItoa(unsigned long long i); // // Return value: string // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT string SimpleDtoa(double value); -LIBPROTOBUF_EXPORT string SimpleFtoa(float value); +PROTOBUF_EXPORT string SimpleDtoa(double value); +PROTOBUF_EXPORT string SimpleFtoa(float value); -LIBPROTOBUF_EXPORT char* DoubleToBuffer(double i, char* buffer); -LIBPROTOBUF_EXPORT char* FloatToBuffer(float i, char* buffer); +PROTOBUF_EXPORT char* DoubleToBuffer(double i, char* buffer); +PROTOBUF_EXPORT char* FloatToBuffer(float i, char* buffer); // In practice, doubles should never need more than 24 bytes and floats // should never need more than 14 (including null terminators), but we @@ -610,7 +611,7 @@ struct Hex { } }; -struct LIBPROTOBUF_EXPORT AlphaNum { +struct PROTOBUF_EXPORT AlphaNum { const char *piece_data_; // move these to string_ref eventually size_t piece_size_; // move these to string_ref eventually @@ -619,16 +620,26 @@ struct LIBPROTOBUF_EXPORT AlphaNum { // No bool ctor -- bools convert to an integral type. // A bool ctor would also convert incoming pointers (bletch). - AlphaNum(int32 i32) + AlphaNum(int i32) : piece_data_(digits), piece_size_(FastInt32ToBufferLeft(i32, digits) - &digits[0]) {} - AlphaNum(uint32 u32) + AlphaNum(unsigned int u32) : piece_data_(digits), piece_size_(FastUInt32ToBufferLeft(u32, digits) - &digits[0]) {} - AlphaNum(int64 i64) + AlphaNum(long long i64) : piece_data_(digits), piece_size_(FastInt64ToBufferLeft(i64, digits) - &digits[0]) {} - AlphaNum(uint64 u64) + AlphaNum(unsigned long long u64) + : piece_data_(digits), + piece_size_(FastUInt64ToBufferLeft(u64, digits) - &digits[0]) {} + + // Note: on some architectures, "long" is only 32 bits, not 64, but the + // performance hit of using FastInt64ToBufferLeft to handle 32-bit values + // is quite minor. + AlphaNum(long i64) + : piece_data_(digits), + piece_size_(FastInt64ToBufferLeft(i64, digits) - &digits[0]) {} + AlphaNum(unsigned long u64) : piece_data_(digits), piece_size_(FastUInt64ToBufferLeft(u64, digits) - &digits[0]) {} @@ -692,30 +703,30 @@ using strings::AlphaNum; // be a reference into str. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b); -LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b, - const AlphaNum& c); -LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b, - const AlphaNum& c, const AlphaNum& d); -LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b, - const AlphaNum& c, const AlphaNum& d, - const AlphaNum& e); -LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b, - const AlphaNum& c, const AlphaNum& d, - const AlphaNum& e, const AlphaNum& f); -LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b, - const AlphaNum& c, const AlphaNum& d, - const AlphaNum& e, const AlphaNum& f, - const AlphaNum& g); -LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b, - const AlphaNum& c, const AlphaNum& d, - const AlphaNum& e, const AlphaNum& f, - const AlphaNum& g, const AlphaNum& h); -LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b, - const AlphaNum& c, const AlphaNum& d, - const AlphaNum& e, const AlphaNum& f, - const AlphaNum& g, const AlphaNum& h, - const AlphaNum& i); +PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b); +PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b, + const AlphaNum& c); +PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b, + const AlphaNum& c, const AlphaNum& d); +PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b, + const AlphaNum& c, const AlphaNum& d, + const AlphaNum& e); +PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b, + const AlphaNum& c, const AlphaNum& d, + const AlphaNum& e, const AlphaNum& f); +PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b, + const AlphaNum& c, const AlphaNum& d, + const AlphaNum& e, const AlphaNum& f, + const AlphaNum& g); +PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b, + const AlphaNum& c, const AlphaNum& d, + const AlphaNum& e, const AlphaNum& f, + const AlphaNum& g, const AlphaNum& h); +PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b, + const AlphaNum& c, const AlphaNum& d, + const AlphaNum& e, const AlphaNum& f, + const AlphaNum& g, const AlphaNum& h, + const AlphaNum& i); inline string StrCat(const AlphaNum& a) { return string(a.data(), a.size()); } @@ -740,14 +751,14 @@ inline string StrCat(const AlphaNum& a) { return string(a.data(), a.size()); } // worked around as consecutive calls to StrAppend are quite efficient. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a); -LIBPROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a, - const AlphaNum& b); -LIBPROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a, - const AlphaNum& b, const AlphaNum& c); -LIBPROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a, - const AlphaNum& b, const AlphaNum& c, - const AlphaNum& d); +PROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a); +PROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a, + const AlphaNum& b); +PROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a, + const AlphaNum& b, const AlphaNum& c); +PROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a, + const AlphaNum& b, const AlphaNum& c, + const AlphaNum& d); // ---------------------------------------------------------------------- // Join() @@ -777,7 +788,7 @@ string Join(const Range& components, // ToHex() // Return a lower-case hex string representation of the given integer. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT string ToHex(uint64 num); +PROTOBUF_EXPORT string ToHex(uint64 num); // ---------------------------------------------------------------------- // GlobalReplaceSubstring() @@ -786,9 +797,9 @@ LIBPROTOBUF_EXPORT string ToHex(uint64 num); // // NOTE: The string pieces must not overlap s. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT int GlobalReplaceSubstring(const string& substring, - const string& replacement, - string* s); +PROTOBUF_EXPORT int GlobalReplaceSubstring(const string& substring, + const string& replacement, + string* s); // ---------------------------------------------------------------------- // Base64Unescape() @@ -796,7 +807,7 @@ LIBPROTOBUF_EXPORT int GlobalReplaceSubstring(const string& substring, // writes it to "dest". If src contains invalid characters, dest is cleared // and the function returns false. Returns true on success. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT bool Base64Unescape(StringPiece src, string* dest); +PROTOBUF_EXPORT bool Base64Unescape(StringPiece src, string* dest); // ---------------------------------------------------------------------- // WebSafeBase64Unescape() @@ -809,18 +820,17 @@ LIBPROTOBUF_EXPORT bool Base64Unescape(StringPiece src, string* dest); // returns false (with dest empty) if src contains invalid chars; for // this version src and dest must be different strings. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT int WebSafeBase64Unescape(const char* src, int slen, - char* dest, int szdest); -LIBPROTOBUF_EXPORT bool WebSafeBase64Unescape(StringPiece src, string* dest); +PROTOBUF_EXPORT int WebSafeBase64Unescape(const char* src, int slen, char* dest, + int szdest); +PROTOBUF_EXPORT bool WebSafeBase64Unescape(StringPiece src, string* dest); // Return the length to use for the output buffer given to the base64 escape // routines. Make sure to use the same value for do_padding in both. // This function may return incorrect results if given input_len values that // are extremely high, which should happen rarely. -LIBPROTOBUF_EXPORT int CalculateBase64EscapedLen(int input_len, - bool do_padding); +PROTOBUF_EXPORT int CalculateBase64EscapedLen(int input_len, bool do_padding); // Use this version when calling Base64Escape without a do_padding arg. -LIBPROTOBUF_EXPORT int CalculateBase64EscapedLen(int input_len); +PROTOBUF_EXPORT int CalculateBase64EscapedLen(int input_len); // ---------------------------------------------------------------------- // Base64Escape() @@ -834,23 +844,23 @@ LIBPROTOBUF_EXPORT int CalculateBase64EscapedLen(int input_len); // to escape them. It also has an extra parameter "do_padding", // which when set to false will prevent padding with "=". // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT int Base64Escape(const unsigned char* src, int slen, - char* dest, int szdest); -LIBPROTOBUF_EXPORT int WebSafeBase64Escape( - const unsigned char* src, int slen, char* dest, - int szdest, bool do_padding); +PROTOBUF_EXPORT int Base64Escape(const unsigned char* src, int slen, char* dest, + int szdest); +PROTOBUF_EXPORT int WebSafeBase64Escape(const unsigned char* src, int slen, + char* dest, int szdest, + bool do_padding); // Encode src into dest with padding. -LIBPROTOBUF_EXPORT void Base64Escape(StringPiece src, string* dest); +PROTOBUF_EXPORT void Base64Escape(StringPiece src, string* dest); // Encode src into dest web-safely without padding. -LIBPROTOBUF_EXPORT void WebSafeBase64Escape(StringPiece src, string* dest); +PROTOBUF_EXPORT void WebSafeBase64Escape(StringPiece src, string* dest); // Encode src into dest web-safely with padding. -LIBPROTOBUF_EXPORT void WebSafeBase64EscapeWithPadding(StringPiece src, - string* dest); +PROTOBUF_EXPORT void WebSafeBase64EscapeWithPadding(StringPiece src, + string* dest); -LIBPROTOBUF_EXPORT void Base64Escape(const unsigned char* src, int szsrc, - string* dest, bool do_padding); -LIBPROTOBUF_EXPORT void WebSafeBase64Escape(const unsigned char* src, int szsrc, - string* dest, bool do_padding); +PROTOBUF_EXPORT void Base64Escape(const unsigned char* src, int szsrc, + string* dest, bool do_padding); +PROTOBUF_EXPORT void WebSafeBase64Escape(const unsigned char* src, int szsrc, + string* dest, bool do_padding); inline bool IsValidCodePoint(uint32 code_point) { return code_point < 0xD800 || @@ -864,15 +874,67 @@ static const int UTFmax = 4; // in any external dependencies. The output buffer must be as least 4 bytes // large. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT int EncodeAsUTF8Char(uint32 code_point, char* output); +PROTOBUF_EXPORT int EncodeAsUTF8Char(uint32 code_point, char* output); // ---------------------------------------------------------------------- // UTF8FirstLetterNumBytes() // Length of the first UTF-8 character. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT int UTF8FirstLetterNumBytes(const char* src, int len); +PROTOBUF_EXPORT int UTF8FirstLetterNumBytes(const char* src, int len); + +// From google3/third_party/absl/strings/escaping.h + +// ---------------------------------------------------------------------- +// CleanStringLineEndings() +// Clean up a multi-line string to conform to Unix line endings. +// Reads from src and appends to dst, so usually dst should be empty. +// +// If there is no line ending at the end of a non-empty string, it can +// be added automatically. +// +// Four different types of input are correctly handled: +// +// - Unix/Linux files: line ending is LF: pass through unchanged +// +// - DOS/Windows files: line ending is CRLF: convert to LF +// +// - Legacy Mac files: line ending is CR: convert to LF +// +// - Garbled files: random line endings: convert gracefully +// lonely CR, lonely LF, CRLF: convert to LF +// +// @param src The multi-line string to convert +// @param dst The converted string is appended to this string +// @param auto_end_last_line Automatically terminate the last line +// +// Limitations: +// +// This does not do the right thing for CRCRLF files created by +// broken programs that do another Unix->DOS conversion on files +// that are already in CRLF format. For this, a two-pass approach +// brute-force would be needed that +// +// (1) determines the presence of LF (first one is ok) +// (2) if yes, removes any CR, else convert every CR to LF +PROTOBUF_EXPORT void CleanStringLineEndings(const string& src, string* dst, + bool auto_end_last_line); + +// Same as above, but transforms the argument in place. +PROTOBUF_EXPORT void CleanStringLineEndings(string* str, + bool auto_end_last_line); + +namespace strings { +inline bool EndsWith(StringPiece text, StringPiece suffix) { + return suffix.empty() || + (text.size() >= suffix.size() && + memcmp(text.data() + (text.size() - suffix.size()), suffix.data(), + suffix.size()) == 0); +} +} // namespace strings } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_STUBS_STRUTIL_H__ diff --git a/third_party/protobuf/src/google/protobuf/stubs/strutil_unittest.cc b/third_party/protobuf/src/google/protobuf/stubs/strutil_unittest.cc index 6bf0f598..f830e377 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/strutil_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/strutil_unittest.cc @@ -50,18 +50,18 @@ namespace { TEST(StringUtilityTest, ImmuneToLocales) { // Remember the old locale. - char* old_locale_cstr = setlocale(LC_NUMERIC, NULL); - ASSERT_TRUE(old_locale_cstr != NULL); + char* old_locale_cstr = setlocale(LC_NUMERIC, nullptr); + ASSERT_TRUE(old_locale_cstr != nullptr); string old_locale = old_locale_cstr; // Set the locale to "C". - ASSERT_TRUE(setlocale(LC_NUMERIC, "C") != NULL); + ASSERT_TRUE(setlocale(LC_NUMERIC, "C") != nullptr); EXPECT_EQ("1.5", SimpleDtoa(1.5)); EXPECT_EQ("1.5", SimpleFtoa(1.5)); - if (setlocale(LC_NUMERIC, "es_ES") == NULL && - setlocale(LC_NUMERIC, "es_ES.utf8") == NULL) { + if (setlocale(LC_NUMERIC, "es_ES") == nullptr && + setlocale(LC_NUMERIC, "es_ES.utf8") == nullptr) { // Some systems may not have the desired locale available. GOOGLE_LOG(WARNING) << "Couldn't set locale to es_ES. Skipping this test."; @@ -805,6 +805,37 @@ TEST(Base64, EscapeAndUnescape) { } } +// Test StrCat of ints and longs of various sizes and signdedness. +TEST(StrCat, Ints) { + const short s = -1; // NOLINT(runtime/int) + const uint16_t us = 2; + const int i = -3; + const unsigned int ui = 4; + const long l = -5; // NOLINT(runtime/int) + const unsigned long ul = 6; // NOLINT(runtime/int) + const long long ll = -7; // NOLINT(runtime/int) + const unsigned long long ull = 8; // NOLINT(runtime/int) + const ptrdiff_t ptrdiff = -9; + const size_t size = 10; + const intptr_t intptr = -12; + const uintptr_t uintptr = 13; + string answer; + answer = StrCat(s, us); + EXPECT_EQ(answer, "-12"); + answer = StrCat(i, ui); + EXPECT_EQ(answer, "-34"); + answer = StrCat(l, ul); + EXPECT_EQ(answer, "-56"); + answer = StrCat(ll, ull); + EXPECT_EQ(answer, "-78"); + answer = StrCat(ptrdiff, size); + EXPECT_EQ(answer, "-910"); + answer = StrCat(ptrdiff, intptr); + EXPECT_EQ(answer, "-9-12"); + answer = StrCat(uintptr, 0); + EXPECT_EQ(answer, "130"); +} + } // anonymous namespace } // namespace protobuf } // namespace google diff --git a/third_party/protobuf/src/google/protobuf/stubs/substitute.cc b/third_party/protobuf/src/google/protobuf/stubs/substitute.cc index 7194a5b1..a36f2f02 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/substitute.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/substitute.cc @@ -31,6 +31,8 @@ // Author: kenton@google.com (Kenton Varda) #include + +#include #include #include @@ -44,7 +46,7 @@ using internal::SubstituteArg; // to Substitute(). static int CountSubstituteArgs(const SubstituteArg* const* args_array) { int count = 0; - while (args_array[count] != NULL && args_array[count]->size() != -1) { + while (args_array[count] != nullptr && args_array[count]->size() != -1) { ++count; } return count; @@ -71,7 +73,7 @@ void SubstituteAndAppend( const SubstituteArg& arg6, const SubstituteArg& arg7, const SubstituteArg& arg8, const SubstituteArg& arg9) { const SubstituteArg* const args_array[] = { - &arg0, &arg1, &arg2, &arg3, &arg4, &arg5, &arg6, &arg7, &arg8, &arg9, NULL + &arg0, &arg1, &arg2, &arg3, &arg4, &arg5, &arg6, &arg7, &arg8, &arg9, nullptr }; // Determine total size needed. diff --git a/third_party/protobuf/src/google/protobuf/stubs/substitute.h b/third_party/protobuf/src/google/protobuf/stubs/substitute.h index 7ee442af..267dead2 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/substitute.h +++ b/third_party/protobuf/src/google/protobuf/stubs/substitute.h @@ -38,6 +38,8 @@ #ifndef GOOGLE_PROTOBUF_STUBS_SUBSTITUTE_H_ #define GOOGLE_PROTOBUF_STUBS_SUBSTITUTE_H_ +#include + namespace google { namespace protobuf { namespace strings { @@ -93,7 +95,7 @@ class SubstituteArg { // Indicates that no argument was given. inline explicit SubstituteArg() - : text_(NULL), size_(-1) {} + : text_(nullptr), size_(-1) {} // Primitives // We don't overload for signed and unsigned char because if people are @@ -137,34 +139,36 @@ class SubstituteArg { } // namespace internal -LIBPROTOBUF_EXPORT string Substitute( - const char* format, - const internal::SubstituteArg& arg0 = internal::SubstituteArg(), - const internal::SubstituteArg& arg1 = internal::SubstituteArg(), - const internal::SubstituteArg& arg2 = internal::SubstituteArg(), - const internal::SubstituteArg& arg3 = internal::SubstituteArg(), - const internal::SubstituteArg& arg4 = internal::SubstituteArg(), - const internal::SubstituteArg& arg5 = internal::SubstituteArg(), - const internal::SubstituteArg& arg6 = internal::SubstituteArg(), - const internal::SubstituteArg& arg7 = internal::SubstituteArg(), - const internal::SubstituteArg& arg8 = internal::SubstituteArg(), - const internal::SubstituteArg& arg9 = internal::SubstituteArg()); +PROTOBUF_EXPORT string +Substitute(const char* format, + const internal::SubstituteArg& arg0 = internal::SubstituteArg(), + const internal::SubstituteArg& arg1 = internal::SubstituteArg(), + const internal::SubstituteArg& arg2 = internal::SubstituteArg(), + const internal::SubstituteArg& arg3 = internal::SubstituteArg(), + const internal::SubstituteArg& arg4 = internal::SubstituteArg(), + const internal::SubstituteArg& arg5 = internal::SubstituteArg(), + const internal::SubstituteArg& arg6 = internal::SubstituteArg(), + const internal::SubstituteArg& arg7 = internal::SubstituteArg(), + const internal::SubstituteArg& arg8 = internal::SubstituteArg(), + const internal::SubstituteArg& arg9 = internal::SubstituteArg()); -LIBPROTOBUF_EXPORT void SubstituteAndAppend( - string* output, const char* format, - const internal::SubstituteArg& arg0 = internal::SubstituteArg(), - const internal::SubstituteArg& arg1 = internal::SubstituteArg(), - const internal::SubstituteArg& arg2 = internal::SubstituteArg(), - const internal::SubstituteArg& arg3 = internal::SubstituteArg(), - const internal::SubstituteArg& arg4 = internal::SubstituteArg(), - const internal::SubstituteArg& arg5 = internal::SubstituteArg(), - const internal::SubstituteArg& arg6 = internal::SubstituteArg(), - const internal::SubstituteArg& arg7 = internal::SubstituteArg(), - const internal::SubstituteArg& arg8 = internal::SubstituteArg(), - const internal::SubstituteArg& arg9 = internal::SubstituteArg()); +PROTOBUF_EXPORT void SubstituteAndAppend( + string* output, const char* format, + const internal::SubstituteArg& arg0 = internal::SubstituteArg(), + const internal::SubstituteArg& arg1 = internal::SubstituteArg(), + const internal::SubstituteArg& arg2 = internal::SubstituteArg(), + const internal::SubstituteArg& arg3 = internal::SubstituteArg(), + const internal::SubstituteArg& arg4 = internal::SubstituteArg(), + const internal::SubstituteArg& arg5 = internal::SubstituteArg(), + const internal::SubstituteArg& arg6 = internal::SubstituteArg(), + const internal::SubstituteArg& arg7 = internal::SubstituteArg(), + const internal::SubstituteArg& arg8 = internal::SubstituteArg(), + const internal::SubstituteArg& arg9 = internal::SubstituteArg()); } // namespace strings } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_STUBS_SUBSTITUTE_H_ diff --git a/third_party/protobuf/src/google/protobuf/stubs/time.cc b/third_party/protobuf/src/google/protobuf/stubs/time.cc index 6def637e..a1e5e1e2 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/time.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/time.cc @@ -142,12 +142,12 @@ string FormatNanos(int32 nanos) { // Parses an integer from a null-terminated char sequence. The method // consumes at most "width" chars. Returns a pointer after the consumed -// integer, or NULL if the data does not start with an integer or the +// integer, or nullptr if the data does not start with an integer or the // integer value does not fall in the range of [min_value, max_value]. const char* ParseInt(const char* data, int width, int min_value, int max_value, int* result) { if (!ascii_isdigit(*data)) { - return NULL; + return nullptr; } int value = 0; for (int i = 0; i < width; ++i, ++data) { @@ -161,7 +161,7 @@ const char* ParseInt(const char* data, int width, int min_value, *result = value; return data; } else { - return NULL; + return nullptr; } } @@ -169,7 +169,7 @@ const char* ParseInt(const char* data, int width, int min_value, // "010" will be parsed to 10000000 nanos. const char* ParseNanos(const char* data, int32* nanos) { if (!ascii_isdigit(*data)) { - return NULL; + return nullptr; } int value = 0; int len = 0; @@ -193,15 +193,15 @@ const char* ParseNanos(const char* data, int32* nanos) { const char* ParseTimezoneOffset(const char* data, int64* offset) { // Accept format "HH:MM". E.g., "08:00" int hour; - if ((data = ParseInt(data, 2, 0, 23, &hour)) == NULL) { - return NULL; + if ((data = ParseInt(data, 2, 0, 23, &hour)) == nullptr) { + return nullptr; } if (*data++ != ':') { - return NULL; + return nullptr; } int minute; - if ((data = ParseInt(data, 2, 0, 59, &minute)) == NULL) { - return NULL; + if ((data = ParseInt(data, 2, 0, 59, &minute)) == nullptr) { + return nullptr; } *offset = (hour * 60 + minute) * 60; return data; @@ -264,7 +264,7 @@ bool DateTimeToSeconds(const DateTime& time, int64* seconds) { void GetCurrentTime(int64* seconds, int32* nanos) { // TODO(xiaofeng): Improve the accuracy of this implementation (or just // remove this method from protobuf). - *seconds = time(NULL); + *seconds = time(nullptr); *nanos = 0; } @@ -290,37 +290,37 @@ bool ParseTime(const string& value, int64* seconds, int32* nanos) { // With UTC offset: 2015-05-20T13:29:35.120-08:00 // Parse year - if ((data = ParseInt(data, 4, 1, 9999, &time.year)) == NULL) { + if ((data = ParseInt(data, 4, 1, 9999, &time.year)) == nullptr) { return false; } // Expect '-' if (*data++ != '-') return false; // Parse month - if ((data = ParseInt(data, 2, 1, 12, &time.month)) == NULL) { + if ((data = ParseInt(data, 2, 1, 12, &time.month)) == nullptr) { return false; } // Expect '-' if (*data++ != '-') return false; // Parse day - if ((data = ParseInt(data, 2, 1, 31, &time.day)) == NULL) { + if ((data = ParseInt(data, 2, 1, 31, &time.day)) == nullptr) { return false; } // Expect 'T' if (*data++ != 'T') return false; // Parse hour - if ((data = ParseInt(data, 2, 0, 23, &time.hour)) == NULL) { + if ((data = ParseInt(data, 2, 0, 23, &time.hour)) == nullptr) { return false; } // Expect ':' if (*data++ != ':') return false; // Parse minute - if ((data = ParseInt(data, 2, 0, 59, &time.minute)) == NULL) { + if ((data = ParseInt(data, 2, 0, 59, &time.minute)) == nullptr) { return false; } // Expect ':' if (*data++ != ':') return false; // Parse second - if ((data = ParseInt(data, 2, 0, 59, &time.second)) == NULL) { + if ((data = ParseInt(data, 2, 0, 59, &time.second)) == nullptr) { return false; } if (!DateTimeToSeconds(time, seconds)) { @@ -330,7 +330,7 @@ bool ParseTime(const string& value, int64* seconds, int32* nanos) { if (*data == '.') { ++data; // Parse nanoseconds. - if ((data = ParseNanos(data, nanos)) == NULL) { + if ((data = ParseNanos(data, nanos)) == nullptr) { return false; } } else { @@ -342,14 +342,14 @@ bool ParseTime(const string& value, int64* seconds, int32* nanos) { } else if (*data == '+') { ++data; int64 offset; - if ((data = ParseTimezoneOffset(data, &offset)) == NULL) { + if ((data = ParseTimezoneOffset(data, &offset)) == nullptr) { return false; } *seconds -= offset; } else if (*data == '-') { ++data; int64 offset; - if ((data = ParseTimezoneOffset(data, &offset)) == NULL) { + if ((data = ParseTimezoneOffset(data, &offset)) == nullptr) { return false; } *seconds += offset; diff --git a/third_party/protobuf/src/google/protobuf/stubs/time.h b/third_party/protobuf/src/google/protobuf/stubs/time.h index 45607ca9..12091de3 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/time.h +++ b/third_party/protobuf/src/google/protobuf/stubs/time.h @@ -32,6 +32,8 @@ #include +#include + namespace google { namespace protobuf { namespace internal { @@ -49,12 +51,12 @@ struct DateTime { // negative to represent time before 1970-01-01) to DateTime. Returns false // if the timestamp is not in the range between 0001-01-01T00:00:00 and // 9999-12-31T23:59:59. -bool LIBPROTOBUF_EXPORT SecondsToDateTime(int64 seconds, DateTime* time); +bool PROTOBUF_EXPORT SecondsToDateTime(int64 seconds, DateTime* time); // Converts DateTime to a timestamp (seconds since 1970-01-01T00:00:00). // Returns false if the DateTime is not valid or is not in the valid range. -bool LIBPROTOBUF_EXPORT DateTimeToSeconds(const DateTime& time, int64* seconds); +bool PROTOBUF_EXPORT DateTimeToSeconds(const DateTime& time, int64* seconds); -void LIBPROTOBUF_EXPORT GetCurrentTime(int64* seconds, int32* nanos); +void PROTOBUF_EXPORT GetCurrentTime(int64* seconds, int32* nanos); // Formats a time string in RFC3339 fromat. // @@ -63,13 +65,16 @@ void LIBPROTOBUF_EXPORT GetCurrentTime(int64* seconds, int32* nanos); // value. // // Note that "nanos" must in the range of [0, 999999999]. -string LIBPROTOBUF_EXPORT FormatTime(int64 seconds, int32 nanos); +string PROTOBUF_EXPORT FormatTime(int64 seconds, int32 nanos); // Parses a time string. This method accepts RFC3339 date/time string with UTC // offset. For example, "2015-05-20T13:29:35.120-08:00". -bool LIBPROTOBUF_EXPORT ParseTime(const string& value, int64* seconds, int32* nanos); +bool PROTOBUF_EXPORT ParseTime(const string& value, int64* seconds, + int32* nanos); } // namespace internal } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_STUBS_TIME_H_ diff --git a/third_party/protobuf/src/google/protobuf/stubs/time_test.cc b/third_party/protobuf/src/google/protobuf/stubs/time_test.cc index 53da9480..4dd06a64 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/time_test.cc +++ b/third_party/protobuf/src/google/protobuf/stubs/time_test.cc @@ -201,7 +201,7 @@ TEST(DateTimeTest, WrongDays) { time.month = 13; ASSERT_FALSE(DateTimeToSeconds(time, &seconds)); } - + TEST(DateTimeTest, StringFormat) { DateTime start, end; start.year = 1; diff --git a/third_party/protobuf/src/google/protobuf/test_messages_proto2.proto b/third_party/protobuf/src/google/protobuf/test_messages_proto2.proto index 60dbfc75..dc6aaa37 100644 --- a/third_party/protobuf/src/google/protobuf/test_messages_proto2.proto +++ b/third_party/protobuf/src/google/protobuf/test_messages_proto2.proto @@ -33,6 +33,8 @@ // - conformance tests // +// LINT: ALLOW_GROUPS + syntax = "proto2"; package protobuf_test_messages.proto2; @@ -180,6 +182,9 @@ message TestAllTypesProto2 { optional int32 field_name17__ = 417; optional int32 Field_name18__ = 418; + // Reserved for unknown fields test. + reserved 1000 to 9999; + // message_set test case. message MessageSetCorrect { option message_set_wire_format = true; @@ -214,3 +219,15 @@ enum ForeignEnumProto2 { extend TestAllTypesProto2 { optional int32 extension_int32 = 120; } + +message UnknownToTestAllTypes { + optional int32 optional_int32 = 1001; + optional string optional_string = 1002; + optional ForeignMessageProto2 nested_message = 1003; + optional group OptionalGroup = 1004 { + optional int32 a = 1; + } + optional bool optional_bool = 1006; + repeated int32 repeated_int32 = 1011; +} + diff --git a/third_party/protobuf/src/google/protobuf/test_messages_proto3.proto b/third_party/protobuf/src/google/protobuf/test_messages_proto3.proto index 4f295aac..908511e5 100644 --- a/third_party/protobuf/src/google/protobuf/test_messages_proto3.proto +++ b/third_party/protobuf/src/google/protobuf/test_messages_proto3.proto @@ -73,6 +73,17 @@ message TestAllTypesProto3 { NEG = -1; // Intentionally negative. } + enum AliasedEnum { + option allow_alias = true; + + ALIAS_FOO = 0; + ALIAS_BAR = 1; + ALIAS_BAZ = 2; + QUX = 2; + qux = 2; + bAz = 2; + } + // Singular int32 optional_int32 = 1; int64 optional_int64 = 2; @@ -95,6 +106,7 @@ message TestAllTypesProto3 { NestedEnum optional_nested_enum = 21; ForeignEnum optional_foreign_enum = 22; + AliasedEnum optional_aliased_enum = 23; string optional_string_piece = 24 [ctype=STRING_PIECE]; string optional_cord = 25 [ctype=CORD]; @@ -194,6 +206,7 @@ message TestAllTypesProto3 { repeated google.protobuf.Struct repeated_struct = 324; repeated google.protobuf.Any repeated_any = 315; repeated google.protobuf.Value repeated_value = 316; + repeated google.protobuf.ListValue repeated_list_value = 317; // Test field-name-to-JSON-name convention. // (protobuf says names can be any valid C/C++ identifier.) diff --git a/third_party/protobuf/src/google/protobuf/test_util.h b/third_party/protobuf/src/google/protobuf/test_util.h index b9abb671..47d3d719 100644 --- a/third_party/protobuf/src/google/protobuf/test_util.h +++ b/third_party/protobuf/src/google/protobuf/test_util.h @@ -44,6 +44,7 @@ #undef UNITTEST #undef UNITTEST_IMPORT +#include namespace google { namespace protobuf { @@ -94,7 +95,7 @@ class ReflectionTester { static void ExpectOneofSetViaReflection(const Message& message); private: - const FieldDescriptor* F(const string& name); + const FieldDescriptor* F(const std::string& name); const Descriptor* base_descriptor_; @@ -128,10 +129,11 @@ inline TestUtil::ReflectionTester::ReflectionTester( const Descriptor* base_descriptor) : base_descriptor_(base_descriptor) { const DescriptorPool* pool = base_descriptor->file()->pool(); - string package = base_descriptor->file()->package(); + std::string package = base_descriptor->file()->package(); const FieldDescriptor* import_descriptor = pool->FindFieldByName(package + ".TestAllTypes.optional_import_message"); - string import_package = import_descriptor->message_type()->file()->package(); + std::string import_package = + import_descriptor->message_type()->file()->package(); nested_b_ = pool->FindFieldByName(package + ".TestAllTypes.NestedMessage.bb"); foreign_c_ = pool->FindFieldByName(package + ".ForeignMessage.c"); @@ -176,7 +178,7 @@ inline TestUtil::ReflectionTester::ReflectionTester( // Shorthand to get a FieldDescriptor for a field of TestAllTypes. inline const FieldDescriptor* TestUtil::ReflectionTester::F( - const string& name) { + const std::string& name) { const FieldDescriptor* result = nullptr; if (base_descriptor_->name() == "TestAllExtensions" || base_descriptor_->name() == "TestPackedExtensions") { @@ -361,7 +363,7 @@ inline void TestUtil::ReflectionTester::ExpectOneofSetViaReflection( const Message& message) { const Descriptor* descriptor = message.GetDescriptor(); const Reflection* reflection = message.GetReflection(); - string scratch; + std::string scratch; EXPECT_TRUE(reflection->HasField( message, descriptor->FindFieldByName("foo_lazy_message"))); EXPECT_TRUE( @@ -441,7 +443,7 @@ inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection( inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection1( const Message& message) { const Reflection* reflection = message.GetReflection(); - string scratch; + std::string scratch; const Message* sub_message; EXPECT_TRUE(reflection->HasField(message, F("optional_int32"))); @@ -565,7 +567,7 @@ inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection1( inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection2( const Message& message) { const Reflection* reflection = message.GetReflection(); - string scratch; + std::string scratch; const Message* sub_message; // ----------------------------------------------------------------- @@ -740,7 +742,7 @@ inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection2( inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection3( const Message& message) { const Reflection* reflection = message.GetReflection(); - string scratch; + std::string scratch; // ----------------------------------------------------------------- @@ -869,7 +871,7 @@ inline void TestUtil::ReflectionTester::ExpectPackedFieldsSetViaReflection( inline void TestUtil::ReflectionTester::ExpectClearViaReflection( const Message& message) { const Reflection* reflection = message.GetReflection(); - string scratch; + std::string scratch; const Message* sub_message; // has_blah() should initially be false for all optional fields. @@ -1268,11 +1270,10 @@ inline void TestUtil::ReflectionTester::ExpectMessagesReleasedViaReflection( // Check that the passed-in serialization is the canonical serialization we // expect for a TestFieldOrderings message filled in by // SetAllFieldsAndExtensions(). -inline void ExpectAllFieldsAndExtensionsInOrder( - const string& serialized) { +inline void ExpectAllFieldsAndExtensionsInOrder(const std::string& serialized) { // We set each field individually, serialize separately, and concatenate all // the strings in canonical order to determine the expected serialization. - string expected; + std::string expected; unittest::TestFieldOrderings message; message.set_my_int(1); // Field 1. message.AppendToString(&expected); @@ -1296,6 +1297,8 @@ inline void ExpectAllFieldsAndExtensionsInOrder( } // namespace TestUtil } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_TEST_UTIL_H__ diff --git a/third_party/protobuf/src/google/protobuf/test_util.inc b/third_party/protobuf/src/google/protobuf/test_util.inc index 185f68d9..7c1bfc19 100644 --- a/third_party/protobuf/src/google/protobuf/test_util.inc +++ b/third_party/protobuf/src/google/protobuf/test_util.inc @@ -41,7 +41,6 @@ #include #include #include -#include #include namespace google { @@ -1545,7 +1544,7 @@ inline void TestUtil::ExpectAllExtensionsSet( inline void TestUtil::ExpectExtensionsClear( const UNITTEST::TestAllExtensions& message) { - string serialized; + std::string serialized; ASSERT_TRUE(message.SerializeToString(&serialized)); EXPECT_EQ("", serialized); EXPECT_EQ(0, message.ByteSizeLong()); diff --git a/third_party/protobuf/src/google/protobuf/test_util2.h b/third_party/protobuf/src/google/protobuf/test_util2.h new file mode 100644 index 00000000..d1cf2119 --- /dev/null +++ b/third_party/protobuf/src/google/protobuf/test_util2.h @@ -0,0 +1,83 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#ifndef GOOGLE_PROTOBUF_TEST_UTIL2_H__ +#define GOOGLE_PROTOBUF_TEST_UTIL2_H__ + +#include + +#include +#include + + +namespace google { +namespace protobuf { +namespace TestUtil { + +// Translate net/proto2/* -> google/protobuf/* +inline std::string TranslatePathToOpensource(const std::string& google3_path) { + const std::string prefix = "net/proto2/"; + GOOGLE_CHECK(google3_path.find(prefix) == 0) << google3_path; + std::string path = google3_path.substr(prefix.size()); + + path = StringReplace(path, "internal/", "", false); + path = StringReplace(path, "proto/", "", false); + path = StringReplace(path, "public/", "", false); + return "google/protobuf/" + path; +} + +inline std::string MaybeTranslatePath(const std::string& google3_path) { + std::string path = google3_path; + path = TranslatePathToOpensource(path); + return path; +} + +inline std::string TestSourceDir() { + return google::protobuf::TestSourceDir(); +} + +inline std::string GetTestDataPath(const std::string& google3_path) { + return TestSourceDir() + "/" + MaybeTranslatePath(google3_path); +} + +// Checks the equality of "message" and serialized proto of type "ProtoType". +// Do not directly compare two serialized protos. +template +bool EqualsToSerialized(const ProtoType& message, const std::string& data) { + ProtoType other; + other.ParsePartialFromString(data); + return util::MessageDifferencer::Equals(message, other); +} + +} // namespace TestUtil +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_TEST_UTIL2_H__ diff --git a/third_party/protobuf/src/google/protobuf/test_util_lite.cc b/third_party/protobuf/src/google/protobuf/test_util_lite.cc index 79c5abec..a83d1092 100644 --- a/third_party/protobuf/src/google/protobuf/test_util_lite.cc +++ b/third_party/protobuf/src/google/protobuf/test_util_lite.cc @@ -42,112 +42,112 @@ namespace google { namespace protobuf { void TestUtilLite::SetAllFields(unittest::TestAllTypesLite* message) { - message->set_optional_int32 (101); - message->set_optional_int64 (102); - message->set_optional_uint32 (103); - message->set_optional_uint64 (104); - message->set_optional_sint32 (105); - message->set_optional_sint64 (106); - message->set_optional_fixed32 (107); - message->set_optional_fixed64 (108); + message->set_optional_int32(101); + message->set_optional_int64(102); + message->set_optional_uint32(103); + message->set_optional_uint64(104); + message->set_optional_sint32(105); + message->set_optional_sint64(106); + message->set_optional_fixed32(107); + message->set_optional_fixed64(108); message->set_optional_sfixed32(109); message->set_optional_sfixed64(110); - message->set_optional_float (111); - message->set_optional_double (112); - message->set_optional_bool (true); - message->set_optional_string ("115"); - message->set_optional_bytes ("116"); + message->set_optional_float(111); + message->set_optional_double(112); + message->set_optional_bool(true); + message->set_optional_string("115"); + message->set_optional_bytes("116"); - message->mutable_optionalgroup ()->set_a(117); - message->mutable_optional_nested_message ()->set_bb(118); - message->mutable_optional_foreign_message ()->set_c(119); - message->mutable_optional_import_message ()->set_d(120); + message->mutable_optionalgroup()->set_a(117); + message->mutable_optional_nested_message()->set_bb(118); + message->mutable_optional_foreign_message()->set_c(119); + message->mutable_optional_import_message()->set_d(120); message->mutable_optional_public_import_message()->set_e(126); - message->mutable_optional_lazy_message ()->set_bb(127); + message->mutable_optional_lazy_message()->set_bb(127); - message->set_optional_nested_enum (unittest::TestAllTypesLite::BAZ ); - message->set_optional_foreign_enum(unittest::FOREIGN_LITE_BAZ ); - message->set_optional_import_enum (unittest_import::IMPORT_LITE_BAZ); + message->set_optional_nested_enum(unittest::TestAllTypesLite::BAZ); + message->set_optional_foreign_enum(unittest::FOREIGN_LITE_BAZ); + message->set_optional_import_enum(unittest_import::IMPORT_LITE_BAZ); // ----------------------------------------------------------------- - message->add_repeated_int32 (201); - message->add_repeated_int64 (202); - message->add_repeated_uint32 (203); - message->add_repeated_uint64 (204); - message->add_repeated_sint32 (205); - message->add_repeated_sint64 (206); - message->add_repeated_fixed32 (207); - message->add_repeated_fixed64 (208); + message->add_repeated_int32(201); + message->add_repeated_int64(202); + message->add_repeated_uint32(203); + message->add_repeated_uint64(204); + message->add_repeated_sint32(205); + message->add_repeated_sint64(206); + message->add_repeated_fixed32(207); + message->add_repeated_fixed64(208); message->add_repeated_sfixed32(209); message->add_repeated_sfixed64(210); - message->add_repeated_float (211); - message->add_repeated_double (212); - message->add_repeated_bool (true); - message->add_repeated_string ("215"); - message->add_repeated_bytes ("216"); + message->add_repeated_float(211); + message->add_repeated_double(212); + message->add_repeated_bool(true); + message->add_repeated_string("215"); + message->add_repeated_bytes("216"); - message->add_repeatedgroup ()->set_a(217); - message->add_repeated_nested_message ()->set_bb(218); + message->add_repeatedgroup()->set_a(217); + message->add_repeated_nested_message()->set_bb(218); message->add_repeated_foreign_message()->set_c(219); - message->add_repeated_import_message ()->set_d(220); - message->add_repeated_lazy_message ()->set_bb(227); + message->add_repeated_import_message()->set_d(220); + message->add_repeated_lazy_message()->set_bb(227); - message->add_repeated_nested_enum (unittest::TestAllTypesLite::BAR ); - message->add_repeated_foreign_enum(unittest::FOREIGN_LITE_BAR ); - message->add_repeated_import_enum (unittest_import::IMPORT_LITE_BAR); + message->add_repeated_nested_enum(unittest::TestAllTypesLite::BAR); + message->add_repeated_foreign_enum(unittest::FOREIGN_LITE_BAR); + message->add_repeated_import_enum(unittest_import::IMPORT_LITE_BAR); // Add a second one of each field. - message->add_repeated_int32 (301); - message->add_repeated_int64 (302); - message->add_repeated_uint32 (303); - message->add_repeated_uint64 (304); - message->add_repeated_sint32 (305); - message->add_repeated_sint64 (306); - message->add_repeated_fixed32 (307); - message->add_repeated_fixed64 (308); + message->add_repeated_int32(301); + message->add_repeated_int64(302); + message->add_repeated_uint32(303); + message->add_repeated_uint64(304); + message->add_repeated_sint32(305); + message->add_repeated_sint64(306); + message->add_repeated_fixed32(307); + message->add_repeated_fixed64(308); message->add_repeated_sfixed32(309); message->add_repeated_sfixed64(310); - message->add_repeated_float (311); - message->add_repeated_double (312); - message->add_repeated_bool (false); - message->add_repeated_string ("315"); - message->add_repeated_bytes ("316"); + message->add_repeated_float(311); + message->add_repeated_double(312); + message->add_repeated_bool(false); + message->add_repeated_string("315"); + message->add_repeated_bytes("316"); - message->add_repeatedgroup ()->set_a(317); - message->add_repeated_nested_message ()->set_bb(318); + message->add_repeatedgroup()->set_a(317); + message->add_repeated_nested_message()->set_bb(318); message->add_repeated_foreign_message()->set_c(319); - message->add_repeated_import_message ()->set_d(320); - message->add_repeated_lazy_message ()->set_bb(327); + message->add_repeated_import_message()->set_d(320); + message->add_repeated_lazy_message()->set_bb(327); - message->add_repeated_nested_enum (unittest::TestAllTypesLite::BAZ ); - message->add_repeated_foreign_enum(unittest::FOREIGN_LITE_BAZ ); - message->add_repeated_import_enum (unittest_import::IMPORT_LITE_BAZ); + message->add_repeated_nested_enum(unittest::TestAllTypesLite::BAZ); + message->add_repeated_foreign_enum(unittest::FOREIGN_LITE_BAZ); + message->add_repeated_import_enum(unittest_import::IMPORT_LITE_BAZ); // ----------------------------------------------------------------- - message->set_default_int32 (401); - message->set_default_int64 (402); - message->set_default_uint32 (403); - message->set_default_uint64 (404); - message->set_default_sint32 (405); - message->set_default_sint64 (406); - message->set_default_fixed32 (407); - message->set_default_fixed64 (408); + message->set_default_int32(401); + message->set_default_int64(402); + message->set_default_uint32(403); + message->set_default_uint64(404); + message->set_default_sint32(405); + message->set_default_sint64(406); + message->set_default_fixed32(407); + message->set_default_fixed64(408); message->set_default_sfixed32(409); message->set_default_sfixed64(410); - message->set_default_float (411); - message->set_default_double (412); - message->set_default_bool (false); - message->set_default_string ("415"); - message->set_default_bytes ("416"); + message->set_default_float(411); + message->set_default_double(412); + message->set_default_bool(false); + message->set_default_string("415"); + message->set_default_bytes("416"); - message->set_default_nested_enum (unittest::TestAllTypesLite::FOO ); - message->set_default_foreign_enum(unittest::FOREIGN_LITE_FOO ); - message->set_default_import_enum (unittest_import::IMPORT_LITE_FOO); + message->set_default_nested_enum(unittest::TestAllTypesLite::FOO); + message->set_default_foreign_enum(unittest::FOREIGN_LITE_FOO); + message->set_default_import_enum(unittest_import::IMPORT_LITE_FOO); message->set_oneof_uint32(601); @@ -159,31 +159,31 @@ void TestUtilLite::SetAllFields(unittest::TestAllTypesLite* message) { // ------------------------------------------------------------------- void TestUtilLite::ModifyRepeatedFields(unittest::TestAllTypesLite* message) { - message->set_repeated_int32 (1, 501); - message->set_repeated_int64 (1, 502); - message->set_repeated_uint32 (1, 503); - message->set_repeated_uint64 (1, 504); - message->set_repeated_sint32 (1, 505); - message->set_repeated_sint64 (1, 506); - message->set_repeated_fixed32 (1, 507); - message->set_repeated_fixed64 (1, 508); + message->set_repeated_int32(1, 501); + message->set_repeated_int64(1, 502); + message->set_repeated_uint32(1, 503); + message->set_repeated_uint64(1, 504); + message->set_repeated_sint32(1, 505); + message->set_repeated_sint64(1, 506); + message->set_repeated_fixed32(1, 507); + message->set_repeated_fixed64(1, 508); message->set_repeated_sfixed32(1, 509); message->set_repeated_sfixed64(1, 510); - message->set_repeated_float (1, 511); - message->set_repeated_double (1, 512); - message->set_repeated_bool (1, true); - message->set_repeated_string (1, "515"); - message->set_repeated_bytes (1, "516"); + message->set_repeated_float(1, 511); + message->set_repeated_double(1, 512); + message->set_repeated_bool(1, true); + message->set_repeated_string(1, "515"); + message->set_repeated_bytes(1, "516"); - message->mutable_repeatedgroup (1)->set_a(517); - message->mutable_repeated_nested_message (1)->set_bb(518); + message->mutable_repeatedgroup(1)->set_a(517); + message->mutable_repeated_nested_message(1)->set_bb(518); message->mutable_repeated_foreign_message(1)->set_c(519); - message->mutable_repeated_import_message (1)->set_d(520); - message->mutable_repeated_lazy_message (1)->set_bb(527); + message->mutable_repeated_import_message(1)->set_d(520); + message->mutable_repeated_lazy_message(1)->set_bb(527); - message->set_repeated_nested_enum (1, unittest::TestAllTypesLite::FOO ); - message->set_repeated_foreign_enum(1, unittest::FOREIGN_LITE_FOO ); - message->set_repeated_import_enum (1, unittest_import::IMPORT_LITE_FOO); + message->set_repeated_nested_enum(1, unittest::TestAllTypesLite::FOO); + message->set_repeated_foreign_enum(1, unittest::FOREIGN_LITE_FOO); + message->set_repeated_import_enum(1, unittest_import::IMPORT_LITE_FOO); } @@ -191,199 +191,199 @@ void TestUtilLite::ModifyRepeatedFields(unittest::TestAllTypesLite* message) { void TestUtilLite::ExpectAllFieldsSet( const unittest::TestAllTypesLite& message) { - EXPECT_TRUE(message.has_optional_int32 ()); - EXPECT_TRUE(message.has_optional_int64 ()); - EXPECT_TRUE(message.has_optional_uint32 ()); - EXPECT_TRUE(message.has_optional_uint64 ()); - EXPECT_TRUE(message.has_optional_sint32 ()); - EXPECT_TRUE(message.has_optional_sint64 ()); - EXPECT_TRUE(message.has_optional_fixed32 ()); - EXPECT_TRUE(message.has_optional_fixed64 ()); + EXPECT_TRUE(message.has_optional_int32()); + EXPECT_TRUE(message.has_optional_int64()); + EXPECT_TRUE(message.has_optional_uint32()); + EXPECT_TRUE(message.has_optional_uint64()); + EXPECT_TRUE(message.has_optional_sint32()); + EXPECT_TRUE(message.has_optional_sint64()); + EXPECT_TRUE(message.has_optional_fixed32()); + EXPECT_TRUE(message.has_optional_fixed64()); EXPECT_TRUE(message.has_optional_sfixed32()); EXPECT_TRUE(message.has_optional_sfixed64()); - EXPECT_TRUE(message.has_optional_float ()); - EXPECT_TRUE(message.has_optional_double ()); - EXPECT_TRUE(message.has_optional_bool ()); - EXPECT_TRUE(message.has_optional_string ()); - EXPECT_TRUE(message.has_optional_bytes ()); + EXPECT_TRUE(message.has_optional_float()); + EXPECT_TRUE(message.has_optional_double()); + EXPECT_TRUE(message.has_optional_bool()); + EXPECT_TRUE(message.has_optional_string()); + EXPECT_TRUE(message.has_optional_bytes()); - EXPECT_TRUE(message.has_optionalgroup ()); - EXPECT_TRUE(message.has_optional_nested_message ()); - EXPECT_TRUE(message.has_optional_foreign_message ()); - EXPECT_TRUE(message.has_optional_import_message ()); + EXPECT_TRUE(message.has_optionalgroup()); + EXPECT_TRUE(message.has_optional_nested_message()); + EXPECT_TRUE(message.has_optional_foreign_message()); + EXPECT_TRUE(message.has_optional_import_message()); EXPECT_TRUE(message.has_optional_public_import_message()); - EXPECT_TRUE(message.has_optional_lazy_message ()); + EXPECT_TRUE(message.has_optional_lazy_message()); - EXPECT_TRUE(message.optionalgroup ().has_a()); - EXPECT_TRUE(message.optional_nested_message ().has_bb()); - EXPECT_TRUE(message.optional_foreign_message ().has_c()); - EXPECT_TRUE(message.optional_import_message ().has_d()); + EXPECT_TRUE(message.optionalgroup().has_a()); + EXPECT_TRUE(message.optional_nested_message().has_bb()); + EXPECT_TRUE(message.optional_foreign_message().has_c()); + EXPECT_TRUE(message.optional_import_message().has_d()); EXPECT_TRUE(message.optional_public_import_message().has_e()); - EXPECT_TRUE(message.optional_lazy_message ().has_bb()); + EXPECT_TRUE(message.optional_lazy_message().has_bb()); - EXPECT_TRUE(message.has_optional_nested_enum ()); + EXPECT_TRUE(message.has_optional_nested_enum()); EXPECT_TRUE(message.has_optional_foreign_enum()); - EXPECT_TRUE(message.has_optional_import_enum ()); + EXPECT_TRUE(message.has_optional_import_enum()); - EXPECT_EQ(101 , message.optional_int32 ()); - EXPECT_EQ(102 , message.optional_int64 ()); - EXPECT_EQ(103 , message.optional_uint32 ()); - EXPECT_EQ(104 , message.optional_uint64 ()); - EXPECT_EQ(105 , message.optional_sint32 ()); - EXPECT_EQ(106 , message.optional_sint64 ()); - EXPECT_EQ(107 , message.optional_fixed32 ()); - EXPECT_EQ(108 , message.optional_fixed64 ()); - EXPECT_EQ(109 , message.optional_sfixed32()); - EXPECT_EQ(110 , message.optional_sfixed64()); - EXPECT_EQ(111 , message.optional_float ()); - EXPECT_EQ(112 , message.optional_double ()); - EXPECT_EQ(true , message.optional_bool ()); - EXPECT_EQ("115", message.optional_string ()); - EXPECT_EQ("116", message.optional_bytes ()); + EXPECT_EQ(101, message.optional_int32()); + EXPECT_EQ(102, message.optional_int64()); + EXPECT_EQ(103, message.optional_uint32()); + EXPECT_EQ(104, message.optional_uint64()); + EXPECT_EQ(105, message.optional_sint32()); + EXPECT_EQ(106, message.optional_sint64()); + EXPECT_EQ(107, message.optional_fixed32()); + EXPECT_EQ(108, message.optional_fixed64()); + EXPECT_EQ(109, message.optional_sfixed32()); + EXPECT_EQ(110, message.optional_sfixed64()); + EXPECT_EQ(111, message.optional_float()); + EXPECT_EQ(112, message.optional_double()); + EXPECT_EQ(true, message.optional_bool()); + EXPECT_EQ("115", message.optional_string()); + EXPECT_EQ("116", message.optional_bytes()); - EXPECT_EQ(117, message.optionalgroup ().a()); - EXPECT_EQ(118, message.optional_nested_message ().bb()); - EXPECT_EQ(119, message.optional_foreign_message ().c()); - EXPECT_EQ(120, message.optional_import_message ().d()); + EXPECT_EQ(117, message.optionalgroup().a()); + EXPECT_EQ(118, message.optional_nested_message().bb()); + EXPECT_EQ(119, message.optional_foreign_message().c()); + EXPECT_EQ(120, message.optional_import_message().d()); EXPECT_EQ(126, message.optional_public_import_message().e()); - EXPECT_EQ(127, message.optional_lazy_message ().bb()); + EXPECT_EQ(127, message.optional_lazy_message().bb()); - EXPECT_EQ(unittest::TestAllTypesLite::BAZ , message.optional_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_LITE_BAZ , message.optional_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAZ, message.optional_import_enum ()); + EXPECT_EQ(unittest::TestAllTypesLite::BAZ, message.optional_nested_enum()); + EXPECT_EQ(unittest::FOREIGN_LITE_BAZ, message.optional_foreign_enum()); + EXPECT_EQ(unittest_import::IMPORT_LITE_BAZ, message.optional_import_enum()); // ----------------------------------------------------------------- - ASSERT_EQ(2, message.repeated_int32_size ()); - ASSERT_EQ(2, message.repeated_int64_size ()); - ASSERT_EQ(2, message.repeated_uint32_size ()); - ASSERT_EQ(2, message.repeated_uint64_size ()); - ASSERT_EQ(2, message.repeated_sint32_size ()); - ASSERT_EQ(2, message.repeated_sint64_size ()); - ASSERT_EQ(2, message.repeated_fixed32_size ()); - ASSERT_EQ(2, message.repeated_fixed64_size ()); + ASSERT_EQ(2, message.repeated_int32_size()); + ASSERT_EQ(2, message.repeated_int64_size()); + ASSERT_EQ(2, message.repeated_uint32_size()); + ASSERT_EQ(2, message.repeated_uint64_size()); + ASSERT_EQ(2, message.repeated_sint32_size()); + ASSERT_EQ(2, message.repeated_sint64_size()); + ASSERT_EQ(2, message.repeated_fixed32_size()); + ASSERT_EQ(2, message.repeated_fixed64_size()); ASSERT_EQ(2, message.repeated_sfixed32_size()); ASSERT_EQ(2, message.repeated_sfixed64_size()); - ASSERT_EQ(2, message.repeated_float_size ()); - ASSERT_EQ(2, message.repeated_double_size ()); - ASSERT_EQ(2, message.repeated_bool_size ()); - ASSERT_EQ(2, message.repeated_string_size ()); - ASSERT_EQ(2, message.repeated_bytes_size ()); + ASSERT_EQ(2, message.repeated_float_size()); + ASSERT_EQ(2, message.repeated_double_size()); + ASSERT_EQ(2, message.repeated_bool_size()); + ASSERT_EQ(2, message.repeated_string_size()); + ASSERT_EQ(2, message.repeated_bytes_size()); - ASSERT_EQ(2, message.repeatedgroup_size ()); - ASSERT_EQ(2, message.repeated_nested_message_size ()); + ASSERT_EQ(2, message.repeatedgroup_size()); + ASSERT_EQ(2, message.repeated_nested_message_size()); ASSERT_EQ(2, message.repeated_foreign_message_size()); - ASSERT_EQ(2, message.repeated_import_message_size ()); - ASSERT_EQ(2, message.repeated_lazy_message_size ()); - ASSERT_EQ(2, message.repeated_nested_enum_size ()); - ASSERT_EQ(2, message.repeated_foreign_enum_size ()); - ASSERT_EQ(2, message.repeated_import_enum_size ()); + ASSERT_EQ(2, message.repeated_import_message_size()); + ASSERT_EQ(2, message.repeated_lazy_message_size()); + ASSERT_EQ(2, message.repeated_nested_enum_size()); + ASSERT_EQ(2, message.repeated_foreign_enum_size()); + ASSERT_EQ(2, message.repeated_import_enum_size()); - EXPECT_EQ(201 , message.repeated_int32 (0)); - EXPECT_EQ(202 , message.repeated_int64 (0)); - EXPECT_EQ(203 , message.repeated_uint32 (0)); - EXPECT_EQ(204 , message.repeated_uint64 (0)); - EXPECT_EQ(205 , message.repeated_sint32 (0)); - EXPECT_EQ(206 , message.repeated_sint64 (0)); - EXPECT_EQ(207 , message.repeated_fixed32 (0)); - EXPECT_EQ(208 , message.repeated_fixed64 (0)); - EXPECT_EQ(209 , message.repeated_sfixed32(0)); - EXPECT_EQ(210 , message.repeated_sfixed64(0)); - EXPECT_EQ(211 , message.repeated_float (0)); - EXPECT_EQ(212 , message.repeated_double (0)); - EXPECT_EQ(true , message.repeated_bool (0)); - EXPECT_EQ("215", message.repeated_string (0)); - EXPECT_EQ("216", message.repeated_bytes (0)); + EXPECT_EQ(201, message.repeated_int32(0)); + EXPECT_EQ(202, message.repeated_int64(0)); + EXPECT_EQ(203, message.repeated_uint32(0)); + EXPECT_EQ(204, message.repeated_uint64(0)); + EXPECT_EQ(205, message.repeated_sint32(0)); + EXPECT_EQ(206, message.repeated_sint64(0)); + EXPECT_EQ(207, message.repeated_fixed32(0)); + EXPECT_EQ(208, message.repeated_fixed64(0)); + EXPECT_EQ(209, message.repeated_sfixed32(0)); + EXPECT_EQ(210, message.repeated_sfixed64(0)); + EXPECT_EQ(211, message.repeated_float(0)); + EXPECT_EQ(212, message.repeated_double(0)); + EXPECT_EQ(true, message.repeated_bool(0)); + EXPECT_EQ("215", message.repeated_string(0)); + EXPECT_EQ("216", message.repeated_bytes(0)); - EXPECT_EQ(217, message.repeatedgroup (0).a()); - EXPECT_EQ(218, message.repeated_nested_message (0).bb()); + EXPECT_EQ(217, message.repeatedgroup(0).a()); + EXPECT_EQ(218, message.repeated_nested_message(0).bb()); EXPECT_EQ(219, message.repeated_foreign_message(0).c()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); - EXPECT_EQ(227, message.repeated_lazy_message (0).bb()); + EXPECT_EQ(220, message.repeated_import_message(0).d()); + EXPECT_EQ(227, message.repeated_lazy_message(0).bb()); - EXPECT_EQ(unittest::TestAllTypesLite::BAR , message.repeated_nested_enum (0)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAR , message.repeated_foreign_enum(0)); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAR, message.repeated_import_enum (0)); + EXPECT_EQ(unittest::TestAllTypesLite::BAR, message.repeated_nested_enum(0)); + EXPECT_EQ(unittest::FOREIGN_LITE_BAR, message.repeated_foreign_enum(0)); + EXPECT_EQ(unittest_import::IMPORT_LITE_BAR, message.repeated_import_enum(0)); - EXPECT_EQ(301 , message.repeated_int32 (1)); - EXPECT_EQ(302 , message.repeated_int64 (1)); - EXPECT_EQ(303 , message.repeated_uint32 (1)); - EXPECT_EQ(304 , message.repeated_uint64 (1)); - EXPECT_EQ(305 , message.repeated_sint32 (1)); - EXPECT_EQ(306 , message.repeated_sint64 (1)); - EXPECT_EQ(307 , message.repeated_fixed32 (1)); - EXPECT_EQ(308 , message.repeated_fixed64 (1)); - EXPECT_EQ(309 , message.repeated_sfixed32(1)); - EXPECT_EQ(310 , message.repeated_sfixed64(1)); - EXPECT_EQ(311 , message.repeated_float (1)); - EXPECT_EQ(312 , message.repeated_double (1)); - EXPECT_EQ(false, message.repeated_bool (1)); - EXPECT_EQ("315", message.repeated_string (1)); - EXPECT_EQ("316", message.repeated_bytes (1)); + EXPECT_EQ(301, message.repeated_int32(1)); + EXPECT_EQ(302, message.repeated_int64(1)); + EXPECT_EQ(303, message.repeated_uint32(1)); + EXPECT_EQ(304, message.repeated_uint64(1)); + EXPECT_EQ(305, message.repeated_sint32(1)); + EXPECT_EQ(306, message.repeated_sint64(1)); + EXPECT_EQ(307, message.repeated_fixed32(1)); + EXPECT_EQ(308, message.repeated_fixed64(1)); + EXPECT_EQ(309, message.repeated_sfixed32(1)); + EXPECT_EQ(310, message.repeated_sfixed64(1)); + EXPECT_EQ(311, message.repeated_float(1)); + EXPECT_EQ(312, message.repeated_double(1)); + EXPECT_EQ(false, message.repeated_bool(1)); + EXPECT_EQ("315", message.repeated_string(1)); + EXPECT_EQ("316", message.repeated_bytes(1)); - EXPECT_EQ(317, message.repeatedgroup (1).a()); - EXPECT_EQ(318, message.repeated_nested_message (1).bb()); + EXPECT_EQ(317, message.repeatedgroup(1).a()); + EXPECT_EQ(318, message.repeated_nested_message(1).bb()); EXPECT_EQ(319, message.repeated_foreign_message(1).c()); - EXPECT_EQ(320, message.repeated_import_message (1).d()); - EXPECT_EQ(327, message.repeated_lazy_message (1).bb()); + EXPECT_EQ(320, message.repeated_import_message(1).d()); + EXPECT_EQ(327, message.repeated_lazy_message(1).bb()); - EXPECT_EQ(unittest::TestAllTypesLite::BAZ , message.repeated_nested_enum (1)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAZ , message.repeated_foreign_enum(1)); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAZ, message.repeated_import_enum (1)); + EXPECT_EQ(unittest::TestAllTypesLite::BAZ, message.repeated_nested_enum(1)); + EXPECT_EQ(unittest::FOREIGN_LITE_BAZ, message.repeated_foreign_enum(1)); + EXPECT_EQ(unittest_import::IMPORT_LITE_BAZ, message.repeated_import_enum(1)); // ----------------------------------------------------------------- - EXPECT_TRUE(message.has_default_int32 ()); - EXPECT_TRUE(message.has_default_int64 ()); - EXPECT_TRUE(message.has_default_uint32 ()); - EXPECT_TRUE(message.has_default_uint64 ()); - EXPECT_TRUE(message.has_default_sint32 ()); - EXPECT_TRUE(message.has_default_sint64 ()); - EXPECT_TRUE(message.has_default_fixed32 ()); - EXPECT_TRUE(message.has_default_fixed64 ()); + EXPECT_TRUE(message.has_default_int32()); + EXPECT_TRUE(message.has_default_int64()); + EXPECT_TRUE(message.has_default_uint32()); + EXPECT_TRUE(message.has_default_uint64()); + EXPECT_TRUE(message.has_default_sint32()); + EXPECT_TRUE(message.has_default_sint64()); + EXPECT_TRUE(message.has_default_fixed32()); + EXPECT_TRUE(message.has_default_fixed64()); EXPECT_TRUE(message.has_default_sfixed32()); EXPECT_TRUE(message.has_default_sfixed64()); - EXPECT_TRUE(message.has_default_float ()); - EXPECT_TRUE(message.has_default_double ()); - EXPECT_TRUE(message.has_default_bool ()); - EXPECT_TRUE(message.has_default_string ()); - EXPECT_TRUE(message.has_default_bytes ()); + EXPECT_TRUE(message.has_default_float()); + EXPECT_TRUE(message.has_default_double()); + EXPECT_TRUE(message.has_default_bool()); + EXPECT_TRUE(message.has_default_string()); + EXPECT_TRUE(message.has_default_bytes()); - EXPECT_TRUE(message.has_default_nested_enum ()); + EXPECT_TRUE(message.has_default_nested_enum()); EXPECT_TRUE(message.has_default_foreign_enum()); - EXPECT_TRUE(message.has_default_import_enum ()); + EXPECT_TRUE(message.has_default_import_enum()); - EXPECT_EQ(401 , message.default_int32 ()); - EXPECT_EQ(402 , message.default_int64 ()); - EXPECT_EQ(403 , message.default_uint32 ()); - EXPECT_EQ(404 , message.default_uint64 ()); - EXPECT_EQ(405 , message.default_sint32 ()); - EXPECT_EQ(406 , message.default_sint64 ()); - EXPECT_EQ(407 , message.default_fixed32 ()); - EXPECT_EQ(408 , message.default_fixed64 ()); - EXPECT_EQ(409 , message.default_sfixed32()); - EXPECT_EQ(410 , message.default_sfixed64()); - EXPECT_EQ(411 , message.default_float ()); - EXPECT_EQ(412 , message.default_double ()); - EXPECT_EQ(false, message.default_bool ()); - EXPECT_EQ("415", message.default_string ()); - EXPECT_EQ("416", message.default_bytes ()); + EXPECT_EQ(401, message.default_int32()); + EXPECT_EQ(402, message.default_int64()); + EXPECT_EQ(403, message.default_uint32()); + EXPECT_EQ(404, message.default_uint64()); + EXPECT_EQ(405, message.default_sint32()); + EXPECT_EQ(406, message.default_sint64()); + EXPECT_EQ(407, message.default_fixed32()); + EXPECT_EQ(408, message.default_fixed64()); + EXPECT_EQ(409, message.default_sfixed32()); + EXPECT_EQ(410, message.default_sfixed64()); + EXPECT_EQ(411, message.default_float()); + EXPECT_EQ(412, message.default_double()); + EXPECT_EQ(false, message.default_bool()); + EXPECT_EQ("415", message.default_string()); + EXPECT_EQ("416", message.default_bytes()); - EXPECT_EQ(unittest::TestAllTypesLite::FOO , message.default_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_LITE_FOO , message.default_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_LITE_FOO, message.default_import_enum ()); + EXPECT_EQ(unittest::TestAllTypesLite::FOO, message.default_nested_enum()); + EXPECT_EQ(unittest::FOREIGN_LITE_FOO, message.default_foreign_enum()); + EXPECT_EQ(unittest_import::IMPORT_LITE_FOO, message.default_import_enum()); - EXPECT_FALSE(message.has_oneof_uint32 ()); + EXPECT_FALSE(message.has_oneof_uint32()); EXPECT_FALSE(message.has_oneof_nested_message()); - EXPECT_FALSE(message.has_oneof_string ()); - EXPECT_TRUE(message.has_oneof_bytes ()); + EXPECT_FALSE(message.has_oneof_string()); + EXPECT_TRUE(message.has_oneof_bytes()); EXPECT_EQ("604", message.oneof_bytes()); } @@ -392,145 +392,145 @@ void TestUtilLite::ExpectAllFieldsSet( void TestUtilLite::ExpectClear(const unittest::TestAllTypesLite& message) { // has_blah() should initially be false for all optional fields. - EXPECT_FALSE(message.has_optional_int32 ()); - EXPECT_FALSE(message.has_optional_int64 ()); - EXPECT_FALSE(message.has_optional_uint32 ()); - EXPECT_FALSE(message.has_optional_uint64 ()); - EXPECT_FALSE(message.has_optional_sint32 ()); - EXPECT_FALSE(message.has_optional_sint64 ()); - EXPECT_FALSE(message.has_optional_fixed32 ()); - EXPECT_FALSE(message.has_optional_fixed64 ()); + EXPECT_FALSE(message.has_optional_int32()); + EXPECT_FALSE(message.has_optional_int64()); + EXPECT_FALSE(message.has_optional_uint32()); + EXPECT_FALSE(message.has_optional_uint64()); + EXPECT_FALSE(message.has_optional_sint32()); + EXPECT_FALSE(message.has_optional_sint64()); + EXPECT_FALSE(message.has_optional_fixed32()); + EXPECT_FALSE(message.has_optional_fixed64()); EXPECT_FALSE(message.has_optional_sfixed32()); EXPECT_FALSE(message.has_optional_sfixed64()); - EXPECT_FALSE(message.has_optional_float ()); - EXPECT_FALSE(message.has_optional_double ()); - EXPECT_FALSE(message.has_optional_bool ()); - EXPECT_FALSE(message.has_optional_string ()); - EXPECT_FALSE(message.has_optional_bytes ()); + EXPECT_FALSE(message.has_optional_float()); + EXPECT_FALSE(message.has_optional_double()); + EXPECT_FALSE(message.has_optional_bool()); + EXPECT_FALSE(message.has_optional_string()); + EXPECT_FALSE(message.has_optional_bytes()); - EXPECT_FALSE(message.has_optionalgroup ()); - EXPECT_FALSE(message.has_optional_nested_message ()); - EXPECT_FALSE(message.has_optional_foreign_message ()); - EXPECT_FALSE(message.has_optional_import_message ()); + EXPECT_FALSE(message.has_optionalgroup()); + EXPECT_FALSE(message.has_optional_nested_message()); + EXPECT_FALSE(message.has_optional_foreign_message()); + EXPECT_FALSE(message.has_optional_import_message()); EXPECT_FALSE(message.has_optional_public_import_message()); - EXPECT_FALSE(message.has_optional_lazy_message ()); + EXPECT_FALSE(message.has_optional_lazy_message()); - EXPECT_FALSE(message.has_optional_nested_enum ()); + EXPECT_FALSE(message.has_optional_nested_enum()); EXPECT_FALSE(message.has_optional_foreign_enum()); - EXPECT_FALSE(message.has_optional_import_enum ()); + EXPECT_FALSE(message.has_optional_import_enum()); // Optional fields without defaults are set to zero or something like it. - EXPECT_EQ(0 , message.optional_int32 ()); - EXPECT_EQ(0 , message.optional_int64 ()); - EXPECT_EQ(0 , message.optional_uint32 ()); - EXPECT_EQ(0 , message.optional_uint64 ()); - EXPECT_EQ(0 , message.optional_sint32 ()); - EXPECT_EQ(0 , message.optional_sint64 ()); - EXPECT_EQ(0 , message.optional_fixed32 ()); - EXPECT_EQ(0 , message.optional_fixed64 ()); - EXPECT_EQ(0 , message.optional_sfixed32()); - EXPECT_EQ(0 , message.optional_sfixed64()); - EXPECT_EQ(0 , message.optional_float ()); - EXPECT_EQ(0 , message.optional_double ()); - EXPECT_EQ(false, message.optional_bool ()); - EXPECT_EQ("" , message.optional_string ()); - EXPECT_EQ("" , message.optional_bytes ()); + EXPECT_EQ(0, message.optional_int32()); + EXPECT_EQ(0, message.optional_int64()); + EXPECT_EQ(0, message.optional_uint32()); + EXPECT_EQ(0, message.optional_uint64()); + EXPECT_EQ(0, message.optional_sint32()); + EXPECT_EQ(0, message.optional_sint64()); + EXPECT_EQ(0, message.optional_fixed32()); + EXPECT_EQ(0, message.optional_fixed64()); + EXPECT_EQ(0, message.optional_sfixed32()); + EXPECT_EQ(0, message.optional_sfixed64()); + EXPECT_EQ(0, message.optional_float()); + EXPECT_EQ(0, message.optional_double()); + EXPECT_EQ(false, message.optional_bool()); + EXPECT_EQ("", message.optional_string()); + EXPECT_EQ("", message.optional_bytes()); // Embedded messages should also be clear. - EXPECT_FALSE(message.optionalgroup ().has_a()); - EXPECT_FALSE(message.optional_nested_message ().has_bb()); - EXPECT_FALSE(message.optional_foreign_message ().has_c()); - EXPECT_FALSE(message.optional_import_message ().has_d()); + EXPECT_FALSE(message.optionalgroup().has_a()); + EXPECT_FALSE(message.optional_nested_message().has_bb()); + EXPECT_FALSE(message.optional_foreign_message().has_c()); + EXPECT_FALSE(message.optional_import_message().has_d()); EXPECT_FALSE(message.optional_public_import_message().has_e()); - EXPECT_FALSE(message.optional_lazy_message ().has_bb()); + EXPECT_FALSE(message.optional_lazy_message().has_bb()); - EXPECT_EQ(0, message.optionalgroup ().a()); - EXPECT_EQ(0, message.optional_nested_message ().bb()); + EXPECT_EQ(0, message.optionalgroup().a()); + EXPECT_EQ(0, message.optional_nested_message().bb()); EXPECT_EQ(0, message.optional_foreign_message().c()); - EXPECT_EQ(0, message.optional_import_message ().d()); + EXPECT_EQ(0, message.optional_import_message().d()); // Enums without defaults are set to the first value in the enum. - EXPECT_EQ(unittest::TestAllTypesLite::FOO , message.optional_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_LITE_FOO , message.optional_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_LITE_FOO, message.optional_import_enum ()); + EXPECT_EQ(unittest::TestAllTypesLite::FOO, message.optional_nested_enum()); + EXPECT_EQ(unittest::FOREIGN_LITE_FOO, message.optional_foreign_enum()); + EXPECT_EQ(unittest_import::IMPORT_LITE_FOO, message.optional_import_enum()); // Repeated fields are empty. - EXPECT_EQ(0, message.repeated_int32_size ()); - EXPECT_EQ(0, message.repeated_int64_size ()); - EXPECT_EQ(0, message.repeated_uint32_size ()); - EXPECT_EQ(0, message.repeated_uint64_size ()); - EXPECT_EQ(0, message.repeated_sint32_size ()); - EXPECT_EQ(0, message.repeated_sint64_size ()); - EXPECT_EQ(0, message.repeated_fixed32_size ()); - EXPECT_EQ(0, message.repeated_fixed64_size ()); + EXPECT_EQ(0, message.repeated_int32_size()); + EXPECT_EQ(0, message.repeated_int64_size()); + EXPECT_EQ(0, message.repeated_uint32_size()); + EXPECT_EQ(0, message.repeated_uint64_size()); + EXPECT_EQ(0, message.repeated_sint32_size()); + EXPECT_EQ(0, message.repeated_sint64_size()); + EXPECT_EQ(0, message.repeated_fixed32_size()); + EXPECT_EQ(0, message.repeated_fixed64_size()); EXPECT_EQ(0, message.repeated_sfixed32_size()); EXPECT_EQ(0, message.repeated_sfixed64_size()); - EXPECT_EQ(0, message.repeated_float_size ()); - EXPECT_EQ(0, message.repeated_double_size ()); - EXPECT_EQ(0, message.repeated_bool_size ()); - EXPECT_EQ(0, message.repeated_string_size ()); - EXPECT_EQ(0, message.repeated_bytes_size ()); + EXPECT_EQ(0, message.repeated_float_size()); + EXPECT_EQ(0, message.repeated_double_size()); + EXPECT_EQ(0, message.repeated_bool_size()); + EXPECT_EQ(0, message.repeated_string_size()); + EXPECT_EQ(0, message.repeated_bytes_size()); - EXPECT_EQ(0, message.repeatedgroup_size ()); - EXPECT_EQ(0, message.repeated_nested_message_size ()); + EXPECT_EQ(0, message.repeatedgroup_size()); + EXPECT_EQ(0, message.repeated_nested_message_size()); EXPECT_EQ(0, message.repeated_foreign_message_size()); - EXPECT_EQ(0, message.repeated_import_message_size ()); - EXPECT_EQ(0, message.repeated_lazy_message_size ()); - EXPECT_EQ(0, message.repeated_nested_enum_size ()); - EXPECT_EQ(0, message.repeated_foreign_enum_size ()); - EXPECT_EQ(0, message.repeated_import_enum_size ()); + EXPECT_EQ(0, message.repeated_import_message_size()); + EXPECT_EQ(0, message.repeated_lazy_message_size()); + EXPECT_EQ(0, message.repeated_nested_enum_size()); + EXPECT_EQ(0, message.repeated_foreign_enum_size()); + EXPECT_EQ(0, message.repeated_import_enum_size()); // has_blah() should also be false for all default fields. - EXPECT_FALSE(message.has_default_int32 ()); - EXPECT_FALSE(message.has_default_int64 ()); - EXPECT_FALSE(message.has_default_uint32 ()); - EXPECT_FALSE(message.has_default_uint64 ()); - EXPECT_FALSE(message.has_default_sint32 ()); - EXPECT_FALSE(message.has_default_sint64 ()); - EXPECT_FALSE(message.has_default_fixed32 ()); - EXPECT_FALSE(message.has_default_fixed64 ()); + EXPECT_FALSE(message.has_default_int32()); + EXPECT_FALSE(message.has_default_int64()); + EXPECT_FALSE(message.has_default_uint32()); + EXPECT_FALSE(message.has_default_uint64()); + EXPECT_FALSE(message.has_default_sint32()); + EXPECT_FALSE(message.has_default_sint64()); + EXPECT_FALSE(message.has_default_fixed32()); + EXPECT_FALSE(message.has_default_fixed64()); EXPECT_FALSE(message.has_default_sfixed32()); EXPECT_FALSE(message.has_default_sfixed64()); - EXPECT_FALSE(message.has_default_float ()); - EXPECT_FALSE(message.has_default_double ()); - EXPECT_FALSE(message.has_default_bool ()); - EXPECT_FALSE(message.has_default_string ()); - EXPECT_FALSE(message.has_default_bytes ()); + EXPECT_FALSE(message.has_default_float()); + EXPECT_FALSE(message.has_default_double()); + EXPECT_FALSE(message.has_default_bool()); + EXPECT_FALSE(message.has_default_string()); + EXPECT_FALSE(message.has_default_bytes()); - EXPECT_FALSE(message.has_default_nested_enum ()); + EXPECT_FALSE(message.has_default_nested_enum()); EXPECT_FALSE(message.has_default_foreign_enum()); - EXPECT_FALSE(message.has_default_import_enum ()); + EXPECT_FALSE(message.has_default_import_enum()); // Fields with defaults have their default values (duh). - EXPECT_EQ( 41 , message.default_int32 ()); - EXPECT_EQ( 42 , message.default_int64 ()); - EXPECT_EQ( 43 , message.default_uint32 ()); - EXPECT_EQ( 44 , message.default_uint64 ()); - EXPECT_EQ(-45 , message.default_sint32 ()); - EXPECT_EQ( 46 , message.default_sint64 ()); - EXPECT_EQ( 47 , message.default_fixed32 ()); - EXPECT_EQ( 48 , message.default_fixed64 ()); - EXPECT_EQ( 49 , message.default_sfixed32()); - EXPECT_EQ(-50 , message.default_sfixed64()); - EXPECT_EQ( 51.5 , message.default_float ()); - EXPECT_EQ( 52e3 , message.default_double ()); - EXPECT_EQ(true , message.default_bool ()); - EXPECT_EQ("hello", message.default_string ()); - EXPECT_EQ("world", message.default_bytes ()); + EXPECT_EQ(41, message.default_int32()); + EXPECT_EQ(42, message.default_int64()); + EXPECT_EQ(43, message.default_uint32()); + EXPECT_EQ(44, message.default_uint64()); + EXPECT_EQ(-45, message.default_sint32()); + EXPECT_EQ(46, message.default_sint64()); + EXPECT_EQ(47, message.default_fixed32()); + EXPECT_EQ(48, message.default_fixed64()); + EXPECT_EQ(49, message.default_sfixed32()); + EXPECT_EQ(-50, message.default_sfixed64()); + EXPECT_EQ(51.5, message.default_float()); + EXPECT_EQ(52e3, message.default_double()); + EXPECT_EQ(true, message.default_bool()); + EXPECT_EQ("hello", message.default_string()); + EXPECT_EQ("world", message.default_bytes()); - EXPECT_EQ(unittest::TestAllTypesLite::BAR , message.default_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_LITE_BAR , message.default_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAR, message.default_import_enum ()); + EXPECT_EQ(unittest::TestAllTypesLite::BAR, message.default_nested_enum()); + EXPECT_EQ(unittest::FOREIGN_LITE_BAR, message.default_foreign_enum()); + EXPECT_EQ(unittest_import::IMPORT_LITE_BAR, message.default_import_enum()); - EXPECT_FALSE(message.has_oneof_uint32 ()); + EXPECT_FALSE(message.has_oneof_uint32()); EXPECT_FALSE(message.has_oneof_nested_message()); - EXPECT_FALSE(message.has_oneof_string ()); - EXPECT_FALSE(message.has_oneof_bytes ()); + EXPECT_FALSE(message.has_oneof_string()); + EXPECT_FALSE(message.has_oneof_bytes()); } // ------------------------------------------------------------------- @@ -540,188 +540,188 @@ void TestUtilLite::ExpectRepeatedFieldsModified( // ModifyRepeatedFields only sets the second repeated element of each // field. In addition to verifying this, we also verify that the first // element and size were *not* modified. - ASSERT_EQ(2, message.repeated_int32_size ()); - ASSERT_EQ(2, message.repeated_int64_size ()); - ASSERT_EQ(2, message.repeated_uint32_size ()); - ASSERT_EQ(2, message.repeated_uint64_size ()); - ASSERT_EQ(2, message.repeated_sint32_size ()); - ASSERT_EQ(2, message.repeated_sint64_size ()); - ASSERT_EQ(2, message.repeated_fixed32_size ()); - ASSERT_EQ(2, message.repeated_fixed64_size ()); + ASSERT_EQ(2, message.repeated_int32_size()); + ASSERT_EQ(2, message.repeated_int64_size()); + ASSERT_EQ(2, message.repeated_uint32_size()); + ASSERT_EQ(2, message.repeated_uint64_size()); + ASSERT_EQ(2, message.repeated_sint32_size()); + ASSERT_EQ(2, message.repeated_sint64_size()); + ASSERT_EQ(2, message.repeated_fixed32_size()); + ASSERT_EQ(2, message.repeated_fixed64_size()); ASSERT_EQ(2, message.repeated_sfixed32_size()); ASSERT_EQ(2, message.repeated_sfixed64_size()); - ASSERT_EQ(2, message.repeated_float_size ()); - ASSERT_EQ(2, message.repeated_double_size ()); - ASSERT_EQ(2, message.repeated_bool_size ()); - ASSERT_EQ(2, message.repeated_string_size ()); - ASSERT_EQ(2, message.repeated_bytes_size ()); + ASSERT_EQ(2, message.repeated_float_size()); + ASSERT_EQ(2, message.repeated_double_size()); + ASSERT_EQ(2, message.repeated_bool_size()); + ASSERT_EQ(2, message.repeated_string_size()); + ASSERT_EQ(2, message.repeated_bytes_size()); - ASSERT_EQ(2, message.repeatedgroup_size ()); - ASSERT_EQ(2, message.repeated_nested_message_size ()); + ASSERT_EQ(2, message.repeatedgroup_size()); + ASSERT_EQ(2, message.repeated_nested_message_size()); ASSERT_EQ(2, message.repeated_foreign_message_size()); - ASSERT_EQ(2, message.repeated_import_message_size ()); - ASSERT_EQ(2, message.repeated_lazy_message_size ()); - ASSERT_EQ(2, message.repeated_nested_enum_size ()); - ASSERT_EQ(2, message.repeated_foreign_enum_size ()); - ASSERT_EQ(2, message.repeated_import_enum_size ()); + ASSERT_EQ(2, message.repeated_import_message_size()); + ASSERT_EQ(2, message.repeated_lazy_message_size()); + ASSERT_EQ(2, message.repeated_nested_enum_size()); + ASSERT_EQ(2, message.repeated_foreign_enum_size()); + ASSERT_EQ(2, message.repeated_import_enum_size()); - EXPECT_EQ(201 , message.repeated_int32 (0)); - EXPECT_EQ(202 , message.repeated_int64 (0)); - EXPECT_EQ(203 , message.repeated_uint32 (0)); - EXPECT_EQ(204 , message.repeated_uint64 (0)); - EXPECT_EQ(205 , message.repeated_sint32 (0)); - EXPECT_EQ(206 , message.repeated_sint64 (0)); - EXPECT_EQ(207 , message.repeated_fixed32 (0)); - EXPECT_EQ(208 , message.repeated_fixed64 (0)); - EXPECT_EQ(209 , message.repeated_sfixed32(0)); - EXPECT_EQ(210 , message.repeated_sfixed64(0)); - EXPECT_EQ(211 , message.repeated_float (0)); - EXPECT_EQ(212 , message.repeated_double (0)); - EXPECT_EQ(true , message.repeated_bool (0)); - EXPECT_EQ("215", message.repeated_string (0)); - EXPECT_EQ("216", message.repeated_bytes (0)); + EXPECT_EQ(201, message.repeated_int32(0)); + EXPECT_EQ(202, message.repeated_int64(0)); + EXPECT_EQ(203, message.repeated_uint32(0)); + EXPECT_EQ(204, message.repeated_uint64(0)); + EXPECT_EQ(205, message.repeated_sint32(0)); + EXPECT_EQ(206, message.repeated_sint64(0)); + EXPECT_EQ(207, message.repeated_fixed32(0)); + EXPECT_EQ(208, message.repeated_fixed64(0)); + EXPECT_EQ(209, message.repeated_sfixed32(0)); + EXPECT_EQ(210, message.repeated_sfixed64(0)); + EXPECT_EQ(211, message.repeated_float(0)); + EXPECT_EQ(212, message.repeated_double(0)); + EXPECT_EQ(true, message.repeated_bool(0)); + EXPECT_EQ("215", message.repeated_string(0)); + EXPECT_EQ("216", message.repeated_bytes(0)); - EXPECT_EQ(217, message.repeatedgroup (0).a()); - EXPECT_EQ(218, message.repeated_nested_message (0).bb()); + EXPECT_EQ(217, message.repeatedgroup(0).a()); + EXPECT_EQ(218, message.repeated_nested_message(0).bb()); EXPECT_EQ(219, message.repeated_foreign_message(0).c()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); - EXPECT_EQ(227, message.repeated_lazy_message (0).bb()); + EXPECT_EQ(220, message.repeated_import_message(0).d()); + EXPECT_EQ(227, message.repeated_lazy_message(0).bb()); - EXPECT_EQ(unittest::TestAllTypesLite::BAR , message.repeated_nested_enum (0)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAR , message.repeated_foreign_enum(0)); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAR, message.repeated_import_enum (0)); + EXPECT_EQ(unittest::TestAllTypesLite::BAR, message.repeated_nested_enum(0)); + EXPECT_EQ(unittest::FOREIGN_LITE_BAR, message.repeated_foreign_enum(0)); + EXPECT_EQ(unittest_import::IMPORT_LITE_BAR, message.repeated_import_enum(0)); // Actually verify the second (modified) elements now. - EXPECT_EQ(501 , message.repeated_int32 (1)); - EXPECT_EQ(502 , message.repeated_int64 (1)); - EXPECT_EQ(503 , message.repeated_uint32 (1)); - EXPECT_EQ(504 , message.repeated_uint64 (1)); - EXPECT_EQ(505 , message.repeated_sint32 (1)); - EXPECT_EQ(506 , message.repeated_sint64 (1)); - EXPECT_EQ(507 , message.repeated_fixed32 (1)); - EXPECT_EQ(508 , message.repeated_fixed64 (1)); - EXPECT_EQ(509 , message.repeated_sfixed32(1)); - EXPECT_EQ(510 , message.repeated_sfixed64(1)); - EXPECT_EQ(511 , message.repeated_float (1)); - EXPECT_EQ(512 , message.repeated_double (1)); - EXPECT_EQ(true , message.repeated_bool (1)); - EXPECT_EQ("515", message.repeated_string (1)); - EXPECT_EQ("516", message.repeated_bytes (1)); + EXPECT_EQ(501, message.repeated_int32(1)); + EXPECT_EQ(502, message.repeated_int64(1)); + EXPECT_EQ(503, message.repeated_uint32(1)); + EXPECT_EQ(504, message.repeated_uint64(1)); + EXPECT_EQ(505, message.repeated_sint32(1)); + EXPECT_EQ(506, message.repeated_sint64(1)); + EXPECT_EQ(507, message.repeated_fixed32(1)); + EXPECT_EQ(508, message.repeated_fixed64(1)); + EXPECT_EQ(509, message.repeated_sfixed32(1)); + EXPECT_EQ(510, message.repeated_sfixed64(1)); + EXPECT_EQ(511, message.repeated_float(1)); + EXPECT_EQ(512, message.repeated_double(1)); + EXPECT_EQ(true, message.repeated_bool(1)); + EXPECT_EQ("515", message.repeated_string(1)); + EXPECT_EQ("516", message.repeated_bytes(1)); - EXPECT_EQ(517, message.repeatedgroup (1).a()); - EXPECT_EQ(518, message.repeated_nested_message (1).bb()); + EXPECT_EQ(517, message.repeatedgroup(1).a()); + EXPECT_EQ(518, message.repeated_nested_message(1).bb()); EXPECT_EQ(519, message.repeated_foreign_message(1).c()); - EXPECT_EQ(520, message.repeated_import_message (1).d()); - EXPECT_EQ(527, message.repeated_lazy_message (1).bb()); + EXPECT_EQ(520, message.repeated_import_message(1).d()); + EXPECT_EQ(527, message.repeated_lazy_message(1).bb()); - EXPECT_EQ(unittest::TestAllTypesLite::FOO , message.repeated_nested_enum (1)); - EXPECT_EQ(unittest::FOREIGN_LITE_FOO , message.repeated_foreign_enum(1)); - EXPECT_EQ(unittest_import::IMPORT_LITE_FOO, message.repeated_import_enum (1)); + EXPECT_EQ(unittest::TestAllTypesLite::FOO, message.repeated_nested_enum(1)); + EXPECT_EQ(unittest::FOREIGN_LITE_FOO, message.repeated_foreign_enum(1)); + EXPECT_EQ(unittest_import::IMPORT_LITE_FOO, message.repeated_import_enum(1)); } // ------------------------------------------------------------------- void TestUtilLite::SetPackedFields(unittest::TestPackedTypesLite* message) { - message->add_packed_int32 (601); - message->add_packed_int64 (602); - message->add_packed_uint32 (603); - message->add_packed_uint64 (604); - message->add_packed_sint32 (605); - message->add_packed_sint64 (606); - message->add_packed_fixed32 (607); - message->add_packed_fixed64 (608); + message->add_packed_int32(601); + message->add_packed_int64(602); + message->add_packed_uint32(603); + message->add_packed_uint64(604); + message->add_packed_sint32(605); + message->add_packed_sint64(606); + message->add_packed_fixed32(607); + message->add_packed_fixed64(608); message->add_packed_sfixed32(609); message->add_packed_sfixed64(610); - message->add_packed_float (611); - message->add_packed_double (612); - message->add_packed_bool (true); - message->add_packed_enum (unittest::FOREIGN_LITE_BAR); + message->add_packed_float(611); + message->add_packed_double(612); + message->add_packed_bool(true); + message->add_packed_enum(unittest::FOREIGN_LITE_BAR); // add a second one of each field - message->add_packed_int32 (701); - message->add_packed_int64 (702); - message->add_packed_uint32 (703); - message->add_packed_uint64 (704); - message->add_packed_sint32 (705); - message->add_packed_sint64 (706); - message->add_packed_fixed32 (707); - message->add_packed_fixed64 (708); + message->add_packed_int32(701); + message->add_packed_int64(702); + message->add_packed_uint32(703); + message->add_packed_uint64(704); + message->add_packed_sint32(705); + message->add_packed_sint64(706); + message->add_packed_fixed32(707); + message->add_packed_fixed64(708); message->add_packed_sfixed32(709); message->add_packed_sfixed64(710); - message->add_packed_float (711); - message->add_packed_double (712); - message->add_packed_bool (false); - message->add_packed_enum (unittest::FOREIGN_LITE_BAZ); + message->add_packed_float(711); + message->add_packed_double(712); + message->add_packed_bool(false); + message->add_packed_enum(unittest::FOREIGN_LITE_BAZ); } // ------------------------------------------------------------------- void TestUtilLite::ModifyPackedFields(unittest::TestPackedTypesLite* message) { - message->set_packed_int32 (1, 801); - message->set_packed_int64 (1, 802); - message->set_packed_uint32 (1, 803); - message->set_packed_uint64 (1, 804); - message->set_packed_sint32 (1, 805); - message->set_packed_sint64 (1, 806); - message->set_packed_fixed32 (1, 807); - message->set_packed_fixed64 (1, 808); + message->set_packed_int32(1, 801); + message->set_packed_int64(1, 802); + message->set_packed_uint32(1, 803); + message->set_packed_uint64(1, 804); + message->set_packed_sint32(1, 805); + message->set_packed_sint64(1, 806); + message->set_packed_fixed32(1, 807); + message->set_packed_fixed64(1, 808); message->set_packed_sfixed32(1, 809); message->set_packed_sfixed64(1, 810); - message->set_packed_float (1, 811); - message->set_packed_double (1, 812); - message->set_packed_bool (1, true); - message->set_packed_enum (1, unittest::FOREIGN_LITE_FOO); + message->set_packed_float(1, 811); + message->set_packed_double(1, 812); + message->set_packed_bool(1, true); + message->set_packed_enum(1, unittest::FOREIGN_LITE_FOO); } // ------------------------------------------------------------------- void TestUtilLite::ExpectPackedFieldsSet( const unittest::TestPackedTypesLite& message) { - ASSERT_EQ(2, message.packed_int32_size ()); - ASSERT_EQ(2, message.packed_int64_size ()); - ASSERT_EQ(2, message.packed_uint32_size ()); - ASSERT_EQ(2, message.packed_uint64_size ()); - ASSERT_EQ(2, message.packed_sint32_size ()); - ASSERT_EQ(2, message.packed_sint64_size ()); - ASSERT_EQ(2, message.packed_fixed32_size ()); - ASSERT_EQ(2, message.packed_fixed64_size ()); + ASSERT_EQ(2, message.packed_int32_size()); + ASSERT_EQ(2, message.packed_int64_size()); + ASSERT_EQ(2, message.packed_uint32_size()); + ASSERT_EQ(2, message.packed_uint64_size()); + ASSERT_EQ(2, message.packed_sint32_size()); + ASSERT_EQ(2, message.packed_sint64_size()); + ASSERT_EQ(2, message.packed_fixed32_size()); + ASSERT_EQ(2, message.packed_fixed64_size()); ASSERT_EQ(2, message.packed_sfixed32_size()); ASSERT_EQ(2, message.packed_sfixed64_size()); - ASSERT_EQ(2, message.packed_float_size ()); - ASSERT_EQ(2, message.packed_double_size ()); - ASSERT_EQ(2, message.packed_bool_size ()); - ASSERT_EQ(2, message.packed_enum_size ()); + ASSERT_EQ(2, message.packed_float_size()); + ASSERT_EQ(2, message.packed_double_size()); + ASSERT_EQ(2, message.packed_bool_size()); + ASSERT_EQ(2, message.packed_enum_size()); - EXPECT_EQ(601 , message.packed_int32 (0)); - EXPECT_EQ(602 , message.packed_int64 (0)); - EXPECT_EQ(603 , message.packed_uint32 (0)); - EXPECT_EQ(604 , message.packed_uint64 (0)); - EXPECT_EQ(605 , message.packed_sint32 (0)); - EXPECT_EQ(606 , message.packed_sint64 (0)); - EXPECT_EQ(607 , message.packed_fixed32 (0)); - EXPECT_EQ(608 , message.packed_fixed64 (0)); - EXPECT_EQ(609 , message.packed_sfixed32(0)); - EXPECT_EQ(610 , message.packed_sfixed64(0)); - EXPECT_EQ(611 , message.packed_float (0)); - EXPECT_EQ(612 , message.packed_double (0)); - EXPECT_EQ(true , message.packed_bool (0)); + EXPECT_EQ(601, message.packed_int32(0)); + EXPECT_EQ(602, message.packed_int64(0)); + EXPECT_EQ(603, message.packed_uint32(0)); + EXPECT_EQ(604, message.packed_uint64(0)); + EXPECT_EQ(605, message.packed_sint32(0)); + EXPECT_EQ(606, message.packed_sint64(0)); + EXPECT_EQ(607, message.packed_fixed32(0)); + EXPECT_EQ(608, message.packed_fixed64(0)); + EXPECT_EQ(609, message.packed_sfixed32(0)); + EXPECT_EQ(610, message.packed_sfixed64(0)); + EXPECT_EQ(611, message.packed_float(0)); + EXPECT_EQ(612, message.packed_double(0)); + EXPECT_EQ(true, message.packed_bool(0)); EXPECT_EQ(unittest::FOREIGN_LITE_BAR, message.packed_enum(0)); - EXPECT_EQ(701 , message.packed_int32 (1)); - EXPECT_EQ(702 , message.packed_int64 (1)); - EXPECT_EQ(703 , message.packed_uint32 (1)); - EXPECT_EQ(704 , message.packed_uint64 (1)); - EXPECT_EQ(705 , message.packed_sint32 (1)); - EXPECT_EQ(706 , message.packed_sint64 (1)); - EXPECT_EQ(707 , message.packed_fixed32 (1)); - EXPECT_EQ(708 , message.packed_fixed64 (1)); - EXPECT_EQ(709 , message.packed_sfixed32(1)); - EXPECT_EQ(710 , message.packed_sfixed64(1)); - EXPECT_EQ(711 , message.packed_float (1)); - EXPECT_EQ(712 , message.packed_double (1)); - EXPECT_EQ(false, message.packed_bool (1)); + EXPECT_EQ(701, message.packed_int32(1)); + EXPECT_EQ(702, message.packed_int64(1)); + EXPECT_EQ(703, message.packed_uint32(1)); + EXPECT_EQ(704, message.packed_uint64(1)); + EXPECT_EQ(705, message.packed_sint32(1)); + EXPECT_EQ(706, message.packed_sint64(1)); + EXPECT_EQ(707, message.packed_fixed32(1)); + EXPECT_EQ(708, message.packed_fixed64(1)); + EXPECT_EQ(709, message.packed_sfixed32(1)); + EXPECT_EQ(710, message.packed_sfixed64(1)); + EXPECT_EQ(711, message.packed_float(1)); + EXPECT_EQ(712, message.packed_double(1)); + EXPECT_EQ(false, message.packed_bool(1)); EXPECT_EQ(unittest::FOREIGN_LITE_BAZ, message.packed_enum(1)); } @@ -730,20 +730,20 @@ void TestUtilLite::ExpectPackedFieldsSet( void TestUtilLite::ExpectPackedClear( const unittest::TestPackedTypesLite& message) { // Packed repeated fields are empty. - EXPECT_EQ(0, message.packed_int32_size ()); - EXPECT_EQ(0, message.packed_int64_size ()); - EXPECT_EQ(0, message.packed_uint32_size ()); - EXPECT_EQ(0, message.packed_uint64_size ()); - EXPECT_EQ(0, message.packed_sint32_size ()); - EXPECT_EQ(0, message.packed_sint64_size ()); - EXPECT_EQ(0, message.packed_fixed32_size ()); - EXPECT_EQ(0, message.packed_fixed64_size ()); + EXPECT_EQ(0, message.packed_int32_size()); + EXPECT_EQ(0, message.packed_int64_size()); + EXPECT_EQ(0, message.packed_uint32_size()); + EXPECT_EQ(0, message.packed_uint64_size()); + EXPECT_EQ(0, message.packed_sint32_size()); + EXPECT_EQ(0, message.packed_sint64_size()); + EXPECT_EQ(0, message.packed_fixed32_size()); + EXPECT_EQ(0, message.packed_fixed64_size()); EXPECT_EQ(0, message.packed_sfixed32_size()); EXPECT_EQ(0, message.packed_sfixed64_size()); - EXPECT_EQ(0, message.packed_float_size ()); - EXPECT_EQ(0, message.packed_double_size ()); - EXPECT_EQ(0, message.packed_bool_size ()); - EXPECT_EQ(0, message.packed_enum_size ()); + EXPECT_EQ(0, message.packed_float_size()); + EXPECT_EQ(0, message.packed_double_size()); + EXPECT_EQ(0, message.packed_bool_size()); + EXPECT_EQ(0, message.packed_enum_size()); } // ------------------------------------------------------------------- @@ -751,49 +751,49 @@ void TestUtilLite::ExpectPackedClear( void TestUtilLite::ExpectPackedFieldsModified( const unittest::TestPackedTypesLite& message) { // Do the same for packed repeated fields. - ASSERT_EQ(2, message.packed_int32_size ()); - ASSERT_EQ(2, message.packed_int64_size ()); - ASSERT_EQ(2, message.packed_uint32_size ()); - ASSERT_EQ(2, message.packed_uint64_size ()); - ASSERT_EQ(2, message.packed_sint32_size ()); - ASSERT_EQ(2, message.packed_sint64_size ()); - ASSERT_EQ(2, message.packed_fixed32_size ()); - ASSERT_EQ(2, message.packed_fixed64_size ()); + ASSERT_EQ(2, message.packed_int32_size()); + ASSERT_EQ(2, message.packed_int64_size()); + ASSERT_EQ(2, message.packed_uint32_size()); + ASSERT_EQ(2, message.packed_uint64_size()); + ASSERT_EQ(2, message.packed_sint32_size()); + ASSERT_EQ(2, message.packed_sint64_size()); + ASSERT_EQ(2, message.packed_fixed32_size()); + ASSERT_EQ(2, message.packed_fixed64_size()); ASSERT_EQ(2, message.packed_sfixed32_size()); ASSERT_EQ(2, message.packed_sfixed64_size()); - ASSERT_EQ(2, message.packed_float_size ()); - ASSERT_EQ(2, message.packed_double_size ()); - ASSERT_EQ(2, message.packed_bool_size ()); - ASSERT_EQ(2, message.packed_enum_size ()); + ASSERT_EQ(2, message.packed_float_size()); + ASSERT_EQ(2, message.packed_double_size()); + ASSERT_EQ(2, message.packed_bool_size()); + ASSERT_EQ(2, message.packed_enum_size()); - EXPECT_EQ(601 , message.packed_int32 (0)); - EXPECT_EQ(602 , message.packed_int64 (0)); - EXPECT_EQ(603 , message.packed_uint32 (0)); - EXPECT_EQ(604 , message.packed_uint64 (0)); - EXPECT_EQ(605 , message.packed_sint32 (0)); - EXPECT_EQ(606 , message.packed_sint64 (0)); - EXPECT_EQ(607 , message.packed_fixed32 (0)); - EXPECT_EQ(608 , message.packed_fixed64 (0)); - EXPECT_EQ(609 , message.packed_sfixed32(0)); - EXPECT_EQ(610 , message.packed_sfixed64(0)); - EXPECT_EQ(611 , message.packed_float (0)); - EXPECT_EQ(612 , message.packed_double (0)); - EXPECT_EQ(true , message.packed_bool (0)); + EXPECT_EQ(601, message.packed_int32(0)); + EXPECT_EQ(602, message.packed_int64(0)); + EXPECT_EQ(603, message.packed_uint32(0)); + EXPECT_EQ(604, message.packed_uint64(0)); + EXPECT_EQ(605, message.packed_sint32(0)); + EXPECT_EQ(606, message.packed_sint64(0)); + EXPECT_EQ(607, message.packed_fixed32(0)); + EXPECT_EQ(608, message.packed_fixed64(0)); + EXPECT_EQ(609, message.packed_sfixed32(0)); + EXPECT_EQ(610, message.packed_sfixed64(0)); + EXPECT_EQ(611, message.packed_float(0)); + EXPECT_EQ(612, message.packed_double(0)); + EXPECT_EQ(true, message.packed_bool(0)); EXPECT_EQ(unittest::FOREIGN_LITE_BAR, message.packed_enum(0)); // Actually verify the second (modified) elements now. - EXPECT_EQ(801 , message.packed_int32 (1)); - EXPECT_EQ(802 , message.packed_int64 (1)); - EXPECT_EQ(803 , message.packed_uint32 (1)); - EXPECT_EQ(804 , message.packed_uint64 (1)); - EXPECT_EQ(805 , message.packed_sint32 (1)); - EXPECT_EQ(806 , message.packed_sint64 (1)); - EXPECT_EQ(807 , message.packed_fixed32 (1)); - EXPECT_EQ(808 , message.packed_fixed64 (1)); - EXPECT_EQ(809 , message.packed_sfixed32(1)); - EXPECT_EQ(810 , message.packed_sfixed64(1)); - EXPECT_EQ(811 , message.packed_float (1)); - EXPECT_EQ(812 , message.packed_double (1)); - EXPECT_EQ(true , message.packed_bool (1)); + EXPECT_EQ(801, message.packed_int32(1)); + EXPECT_EQ(802, message.packed_int64(1)); + EXPECT_EQ(803, message.packed_uint32(1)); + EXPECT_EQ(804, message.packed_uint64(1)); + EXPECT_EQ(805, message.packed_sint32(1)); + EXPECT_EQ(806, message.packed_sint64(1)); + EXPECT_EQ(807, message.packed_fixed32(1)); + EXPECT_EQ(808, message.packed_fixed64(1)); + EXPECT_EQ(809, message.packed_sfixed32(1)); + EXPECT_EQ(810, message.packed_sfixed64(1)); + EXPECT_EQ(811, message.packed_float(1)); + EXPECT_EQ(812, message.packed_double(1)); + EXPECT_EQ(true, message.packed_bool(1)); EXPECT_EQ(unittest::FOREIGN_LITE_FOO, message.packed_enum(1)); } @@ -806,116 +806,145 @@ void TestUtilLite::ExpectPackedFieldsModified( // I gave up on the 80-char limit here. Sorry. void TestUtilLite::SetAllExtensions(unittest::TestAllExtensionsLite* message) { - message->SetExtension(unittest::optional_int32_extension_lite , 101); - message->SetExtension(unittest::optional_int64_extension_lite , 102); - message->SetExtension(unittest::optional_uint32_extension_lite , 103); - message->SetExtension(unittest::optional_uint64_extension_lite , 104); - message->SetExtension(unittest::optional_sint32_extension_lite , 105); - message->SetExtension(unittest::optional_sint64_extension_lite , 106); - message->SetExtension(unittest::optional_fixed32_extension_lite , 107); - message->SetExtension(unittest::optional_fixed64_extension_lite , 108); + message->SetExtension(unittest::optional_int32_extension_lite, 101); + message->SetExtension(unittest::optional_int64_extension_lite, 102); + message->SetExtension(unittest::optional_uint32_extension_lite, 103); + message->SetExtension(unittest::optional_uint64_extension_lite, 104); + message->SetExtension(unittest::optional_sint32_extension_lite, 105); + message->SetExtension(unittest::optional_sint64_extension_lite, 106); + message->SetExtension(unittest::optional_fixed32_extension_lite, 107); + message->SetExtension(unittest::optional_fixed64_extension_lite, 108); message->SetExtension(unittest::optional_sfixed32_extension_lite, 109); message->SetExtension(unittest::optional_sfixed64_extension_lite, 110); - message->SetExtension(unittest::optional_float_extension_lite , 111); - message->SetExtension(unittest::optional_double_extension_lite , 112); - message->SetExtension(unittest::optional_bool_extension_lite , true); - message->SetExtension(unittest::optional_string_extension_lite , "115"); - message->SetExtension(unittest::optional_bytes_extension_lite , "116"); + message->SetExtension(unittest::optional_float_extension_lite, 111); + message->SetExtension(unittest::optional_double_extension_lite, 112); + message->SetExtension(unittest::optional_bool_extension_lite, true); + message->SetExtension(unittest::optional_string_extension_lite, "115"); + message->SetExtension(unittest::optional_bytes_extension_lite, "116"); - message->MutableExtension(unittest::optionalgroup_extension_lite )->set_a(117); - message->MutableExtension(unittest::optional_nested_message_extension_lite )->set_bb(118); - message->MutableExtension(unittest::optional_foreign_message_extension_lite )->set_c(119); - message->MutableExtension(unittest::optional_import_message_extension_lite )->set_d(120); - message->MutableExtension(unittest::optional_public_import_message_extension_lite)->set_e(126); - message->MutableExtension(unittest::optional_lazy_message_extension_lite )->set_bb(127); + message->MutableExtension(unittest::optionalgroup_extension_lite)->set_a(117); + message->MutableExtension(unittest::optional_nested_message_extension_lite) + ->set_bb(118); + message->MutableExtension(unittest::optional_foreign_message_extension_lite) + ->set_c(119); + message->MutableExtension(unittest::optional_import_message_extension_lite) + ->set_d(120); + message + ->MutableExtension( + unittest::optional_public_import_message_extension_lite) + ->set_e(126); + message->MutableExtension(unittest::optional_lazy_message_extension_lite) + ->set_bb(127); - message->SetExtension(unittest::optional_nested_enum_extension_lite , unittest::TestAllTypesLite::BAZ ); - message->SetExtension(unittest::optional_foreign_enum_extension_lite, unittest::FOREIGN_LITE_BAZ ); - message->SetExtension(unittest::optional_import_enum_extension_lite , unittest_import::IMPORT_LITE_BAZ); + message->SetExtension(unittest::optional_nested_enum_extension_lite, + unittest::TestAllTypesLite::BAZ); + message->SetExtension(unittest::optional_foreign_enum_extension_lite, + unittest::FOREIGN_LITE_BAZ); + message->SetExtension(unittest::optional_import_enum_extension_lite, + unittest_import::IMPORT_LITE_BAZ); // ----------------------------------------------------------------- - message->AddExtension(unittest::repeated_int32_extension_lite , 201); - message->AddExtension(unittest::repeated_int64_extension_lite , 202); - message->AddExtension(unittest::repeated_uint32_extension_lite , 203); - message->AddExtension(unittest::repeated_uint64_extension_lite , 204); - message->AddExtension(unittest::repeated_sint32_extension_lite , 205); - message->AddExtension(unittest::repeated_sint64_extension_lite , 206); - message->AddExtension(unittest::repeated_fixed32_extension_lite , 207); - message->AddExtension(unittest::repeated_fixed64_extension_lite , 208); + message->AddExtension(unittest::repeated_int32_extension_lite, 201); + message->AddExtension(unittest::repeated_int64_extension_lite, 202); + message->AddExtension(unittest::repeated_uint32_extension_lite, 203); + message->AddExtension(unittest::repeated_uint64_extension_lite, 204); + message->AddExtension(unittest::repeated_sint32_extension_lite, 205); + message->AddExtension(unittest::repeated_sint64_extension_lite, 206); + message->AddExtension(unittest::repeated_fixed32_extension_lite, 207); + message->AddExtension(unittest::repeated_fixed64_extension_lite, 208); message->AddExtension(unittest::repeated_sfixed32_extension_lite, 209); message->AddExtension(unittest::repeated_sfixed64_extension_lite, 210); - message->AddExtension(unittest::repeated_float_extension_lite , 211); - message->AddExtension(unittest::repeated_double_extension_lite , 212); - message->AddExtension(unittest::repeated_bool_extension_lite , true); - message->AddExtension(unittest::repeated_string_extension_lite , "215"); - message->AddExtension(unittest::repeated_bytes_extension_lite , "216"); + message->AddExtension(unittest::repeated_float_extension_lite, 211); + message->AddExtension(unittest::repeated_double_extension_lite, 212); + message->AddExtension(unittest::repeated_bool_extension_lite, true); + message->AddExtension(unittest::repeated_string_extension_lite, "215"); + message->AddExtension(unittest::repeated_bytes_extension_lite, "216"); - message->AddExtension(unittest::repeatedgroup_extension_lite )->set_a(217); - message->AddExtension(unittest::repeated_nested_message_extension_lite )->set_bb(218); - message->AddExtension(unittest::repeated_foreign_message_extension_lite)->set_c(219); - message->AddExtension(unittest::repeated_import_message_extension_lite )->set_d(220); - message->AddExtension(unittest::repeated_lazy_message_extension_lite )->set_bb(227); + message->AddExtension(unittest::repeatedgroup_extension_lite)->set_a(217); + message->AddExtension(unittest::repeated_nested_message_extension_lite) + ->set_bb(218); + message->AddExtension(unittest::repeated_foreign_message_extension_lite) + ->set_c(219); + message->AddExtension(unittest::repeated_import_message_extension_lite) + ->set_d(220); + message->AddExtension(unittest::repeated_lazy_message_extension_lite) + ->set_bb(227); - message->AddExtension(unittest::repeated_nested_enum_extension_lite , unittest::TestAllTypesLite::BAR ); - message->AddExtension(unittest::repeated_foreign_enum_extension_lite, unittest::FOREIGN_LITE_BAR ); - message->AddExtension(unittest::repeated_import_enum_extension_lite , unittest_import::IMPORT_LITE_BAR); + message->AddExtension(unittest::repeated_nested_enum_extension_lite, + unittest::TestAllTypesLite::BAR); + message->AddExtension(unittest::repeated_foreign_enum_extension_lite, + unittest::FOREIGN_LITE_BAR); + message->AddExtension(unittest::repeated_import_enum_extension_lite, + unittest_import::IMPORT_LITE_BAR); // Add a second one of each field. - message->AddExtension(unittest::repeated_int32_extension_lite , 301); - message->AddExtension(unittest::repeated_int64_extension_lite , 302); - message->AddExtension(unittest::repeated_uint32_extension_lite , 303); - message->AddExtension(unittest::repeated_uint64_extension_lite , 304); - message->AddExtension(unittest::repeated_sint32_extension_lite , 305); - message->AddExtension(unittest::repeated_sint64_extension_lite , 306); - message->AddExtension(unittest::repeated_fixed32_extension_lite , 307); - message->AddExtension(unittest::repeated_fixed64_extension_lite , 308); + message->AddExtension(unittest::repeated_int32_extension_lite, 301); + message->AddExtension(unittest::repeated_int64_extension_lite, 302); + message->AddExtension(unittest::repeated_uint32_extension_lite, 303); + message->AddExtension(unittest::repeated_uint64_extension_lite, 304); + message->AddExtension(unittest::repeated_sint32_extension_lite, 305); + message->AddExtension(unittest::repeated_sint64_extension_lite, 306); + message->AddExtension(unittest::repeated_fixed32_extension_lite, 307); + message->AddExtension(unittest::repeated_fixed64_extension_lite, 308); message->AddExtension(unittest::repeated_sfixed32_extension_lite, 309); message->AddExtension(unittest::repeated_sfixed64_extension_lite, 310); - message->AddExtension(unittest::repeated_float_extension_lite , 311); - message->AddExtension(unittest::repeated_double_extension_lite , 312); - message->AddExtension(unittest::repeated_bool_extension_lite , false); - message->AddExtension(unittest::repeated_string_extension_lite , "315"); - message->AddExtension(unittest::repeated_bytes_extension_lite , "316"); + message->AddExtension(unittest::repeated_float_extension_lite, 311); + message->AddExtension(unittest::repeated_double_extension_lite, 312); + message->AddExtension(unittest::repeated_bool_extension_lite, false); + message->AddExtension(unittest::repeated_string_extension_lite, "315"); + message->AddExtension(unittest::repeated_bytes_extension_lite, "316"); - message->AddExtension(unittest::repeatedgroup_extension_lite )->set_a(317); - message->AddExtension(unittest::repeated_nested_message_extension_lite )->set_bb(318); - message->AddExtension(unittest::repeated_foreign_message_extension_lite)->set_c(319); - message->AddExtension(unittest::repeated_import_message_extension_lite )->set_d(320); - message->AddExtension(unittest::repeated_lazy_message_extension_lite )->set_bb(327); + message->AddExtension(unittest::repeatedgroup_extension_lite)->set_a(317); + message->AddExtension(unittest::repeated_nested_message_extension_lite) + ->set_bb(318); + message->AddExtension(unittest::repeated_foreign_message_extension_lite) + ->set_c(319); + message->AddExtension(unittest::repeated_import_message_extension_lite) + ->set_d(320); + message->AddExtension(unittest::repeated_lazy_message_extension_lite) + ->set_bb(327); - message->AddExtension(unittest::repeated_nested_enum_extension_lite , unittest::TestAllTypesLite::BAZ ); - message->AddExtension(unittest::repeated_foreign_enum_extension_lite, unittest::FOREIGN_LITE_BAZ ); - message->AddExtension(unittest::repeated_import_enum_extension_lite , unittest_import::IMPORT_LITE_BAZ); + message->AddExtension(unittest::repeated_nested_enum_extension_lite, + unittest::TestAllTypesLite::BAZ); + message->AddExtension(unittest::repeated_foreign_enum_extension_lite, + unittest::FOREIGN_LITE_BAZ); + message->AddExtension(unittest::repeated_import_enum_extension_lite, + unittest_import::IMPORT_LITE_BAZ); // ----------------------------------------------------------------- - message->SetExtension(unittest::default_int32_extension_lite , 401); - message->SetExtension(unittest::default_int64_extension_lite , 402); - message->SetExtension(unittest::default_uint32_extension_lite , 403); - message->SetExtension(unittest::default_uint64_extension_lite , 404); - message->SetExtension(unittest::default_sint32_extension_lite , 405); - message->SetExtension(unittest::default_sint64_extension_lite , 406); - message->SetExtension(unittest::default_fixed32_extension_lite , 407); - message->SetExtension(unittest::default_fixed64_extension_lite , 408); + message->SetExtension(unittest::default_int32_extension_lite, 401); + message->SetExtension(unittest::default_int64_extension_lite, 402); + message->SetExtension(unittest::default_uint32_extension_lite, 403); + message->SetExtension(unittest::default_uint64_extension_lite, 404); + message->SetExtension(unittest::default_sint32_extension_lite, 405); + message->SetExtension(unittest::default_sint64_extension_lite, 406); + message->SetExtension(unittest::default_fixed32_extension_lite, 407); + message->SetExtension(unittest::default_fixed64_extension_lite, 408); message->SetExtension(unittest::default_sfixed32_extension_lite, 409); message->SetExtension(unittest::default_sfixed64_extension_lite, 410); - message->SetExtension(unittest::default_float_extension_lite , 411); - message->SetExtension(unittest::default_double_extension_lite , 412); - message->SetExtension(unittest::default_bool_extension_lite , false); - message->SetExtension(unittest::default_string_extension_lite , "415"); - message->SetExtension(unittest::default_bytes_extension_lite , "416"); + message->SetExtension(unittest::default_float_extension_lite, 411); + message->SetExtension(unittest::default_double_extension_lite, 412); + message->SetExtension(unittest::default_bool_extension_lite, false); + message->SetExtension(unittest::default_string_extension_lite, "415"); + message->SetExtension(unittest::default_bytes_extension_lite, "416"); - message->SetExtension(unittest::default_nested_enum_extension_lite , unittest::TestAllTypesLite::FOO ); - message->SetExtension(unittest::default_foreign_enum_extension_lite, unittest::FOREIGN_LITE_FOO ); - message->SetExtension(unittest::default_import_enum_extension_lite , unittest_import::IMPORT_LITE_FOO); + message->SetExtension(unittest::default_nested_enum_extension_lite, + unittest::TestAllTypesLite::FOO); + message->SetExtension(unittest::default_foreign_enum_extension_lite, + unittest::FOREIGN_LITE_FOO); + message->SetExtension(unittest::default_import_enum_extension_lite, + unittest_import::IMPORT_LITE_FOO); message->SetExtension(unittest::oneof_uint32_extension_lite, 601); - message->MutableExtension(unittest::oneof_nested_message_extension_lite)->set_bb(602);; + message->MutableExtension(unittest::oneof_nested_message_extension_lite) + ->set_bb(602); + ; message->SetExtension(unittest::oneof_string_extension_lite, "603"); message->SetExtension(unittest::oneof_bytes_extension_lite, "604"); } @@ -924,31 +953,40 @@ void TestUtilLite::SetAllExtensions(unittest::TestAllExtensionsLite* message) { void TestUtilLite::ModifyRepeatedExtensions( unittest::TestAllExtensionsLite* message) { - message->SetExtension(unittest::repeated_int32_extension_lite , 1, 501); - message->SetExtension(unittest::repeated_int64_extension_lite , 1, 502); - message->SetExtension(unittest::repeated_uint32_extension_lite , 1, 503); - message->SetExtension(unittest::repeated_uint64_extension_lite , 1, 504); - message->SetExtension(unittest::repeated_sint32_extension_lite , 1, 505); - message->SetExtension(unittest::repeated_sint64_extension_lite , 1, 506); - message->SetExtension(unittest::repeated_fixed32_extension_lite , 1, 507); - message->SetExtension(unittest::repeated_fixed64_extension_lite , 1, 508); + message->SetExtension(unittest::repeated_int32_extension_lite, 1, 501); + message->SetExtension(unittest::repeated_int64_extension_lite, 1, 502); + message->SetExtension(unittest::repeated_uint32_extension_lite, 1, 503); + message->SetExtension(unittest::repeated_uint64_extension_lite, 1, 504); + message->SetExtension(unittest::repeated_sint32_extension_lite, 1, 505); + message->SetExtension(unittest::repeated_sint64_extension_lite, 1, 506); + message->SetExtension(unittest::repeated_fixed32_extension_lite, 1, 507); + message->SetExtension(unittest::repeated_fixed64_extension_lite, 1, 508); message->SetExtension(unittest::repeated_sfixed32_extension_lite, 1, 509); message->SetExtension(unittest::repeated_sfixed64_extension_lite, 1, 510); - message->SetExtension(unittest::repeated_float_extension_lite , 1, 511); - message->SetExtension(unittest::repeated_double_extension_lite , 1, 512); - message->SetExtension(unittest::repeated_bool_extension_lite , 1, true); - message->SetExtension(unittest::repeated_string_extension_lite , 1, "515"); - message->SetExtension(unittest::repeated_bytes_extension_lite , 1, "516"); + message->SetExtension(unittest::repeated_float_extension_lite, 1, 511); + message->SetExtension(unittest::repeated_double_extension_lite, 1, 512); + message->SetExtension(unittest::repeated_bool_extension_lite, 1, true); + message->SetExtension(unittest::repeated_string_extension_lite, 1, "515"); + message->SetExtension(unittest::repeated_bytes_extension_lite, 1, "516"); - message->MutableExtension(unittest::repeatedgroup_extension_lite , 1)->set_a(517); - message->MutableExtension(unittest::repeated_nested_message_extension_lite , 1)->set_bb(518); - message->MutableExtension(unittest::repeated_foreign_message_extension_lite, 1)->set_c(519); - message->MutableExtension(unittest::repeated_import_message_extension_lite , 1)->set_d(520); - message->MutableExtension(unittest::repeated_lazy_message_extension_lite , 1)->set_bb(527); + message->MutableExtension(unittest::repeatedgroup_extension_lite, 1) + ->set_a(517); + message->MutableExtension(unittest::repeated_nested_message_extension_lite, 1) + ->set_bb(518); + message + ->MutableExtension(unittest::repeated_foreign_message_extension_lite, 1) + ->set_c(519); + message->MutableExtension(unittest::repeated_import_message_extension_lite, 1) + ->set_d(520); + message->MutableExtension(unittest::repeated_lazy_message_extension_lite, 1) + ->set_bb(527); - message->SetExtension(unittest::repeated_nested_enum_extension_lite , 1, unittest::TestAllTypesLite::FOO ); - message->SetExtension(unittest::repeated_foreign_enum_extension_lite, 1, unittest::FOREIGN_LITE_FOO ); - message->SetExtension(unittest::repeated_import_enum_extension_lite , 1, unittest_import::IMPORT_LITE_FOO); + message->SetExtension(unittest::repeated_nested_enum_extension_lite, 1, + unittest::TestAllTypesLite::FOO); + message->SetExtension(unittest::repeated_foreign_enum_extension_lite, 1, + unittest::FOREIGN_LITE_FOO); + message->SetExtension(unittest::repeated_import_enum_extension_lite, 1, + unittest_import::IMPORT_LITE_FOO); } @@ -956,202 +994,351 @@ void TestUtilLite::ModifyRepeatedExtensions( void TestUtilLite::ExpectAllExtensionsSet( const unittest::TestAllExtensionsLite& message) { - EXPECT_TRUE(message.HasExtension(unittest::optional_int32_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_int64_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_uint32_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_uint64_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_sint32_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_sint64_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_fixed32_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_fixed64_extension_lite )); + EXPECT_TRUE(message.HasExtension(unittest::optional_int32_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::optional_int64_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::optional_uint32_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::optional_uint64_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::optional_sint32_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::optional_sint64_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::optional_fixed32_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::optional_fixed64_extension_lite)); EXPECT_TRUE(message.HasExtension(unittest::optional_sfixed32_extension_lite)); EXPECT_TRUE(message.HasExtension(unittest::optional_sfixed64_extension_lite)); - EXPECT_TRUE(message.HasExtension(unittest::optional_float_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_double_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_bool_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_string_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_bytes_extension_lite )); + EXPECT_TRUE(message.HasExtension(unittest::optional_float_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::optional_double_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::optional_bool_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::optional_string_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::optional_bytes_extension_lite)); - EXPECT_TRUE(message.HasExtension(unittest::optionalgroup_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_nested_message_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_foreign_message_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_import_message_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_public_import_message_extension_lite)); - EXPECT_TRUE(message.HasExtension(unittest::optional_lazy_message_extension_lite )); + EXPECT_TRUE(message.HasExtension(unittest::optionalgroup_extension_lite)); + EXPECT_TRUE( + message.HasExtension(unittest::optional_nested_message_extension_lite)); + EXPECT_TRUE( + message.HasExtension(unittest::optional_foreign_message_extension_lite)); + EXPECT_TRUE( + message.HasExtension(unittest::optional_import_message_extension_lite)); + EXPECT_TRUE(message.HasExtension( + unittest::optional_public_import_message_extension_lite)); + EXPECT_TRUE( + message.HasExtension(unittest::optional_lazy_message_extension_lite)); - EXPECT_TRUE(message.GetExtension(unittest::optionalgroup_extension_lite ).has_a()); - EXPECT_TRUE(message.GetExtension(unittest::optional_nested_message_extension_lite ).has_bb()); - EXPECT_TRUE(message.GetExtension(unittest::optional_foreign_message_extension_lite ).has_c()); - EXPECT_TRUE(message.GetExtension(unittest::optional_import_message_extension_lite ).has_d()); - EXPECT_TRUE(message.GetExtension(unittest::optional_public_import_message_extension_lite).has_e()); - EXPECT_TRUE(message.GetExtension(unittest::optional_lazy_message_extension_lite ).has_bb()); + EXPECT_TRUE( + message.GetExtension(unittest::optionalgroup_extension_lite).has_a()); + EXPECT_TRUE( + message.GetExtension(unittest::optional_nested_message_extension_lite) + .has_bb()); + EXPECT_TRUE( + message.GetExtension(unittest::optional_foreign_message_extension_lite) + .has_c()); + EXPECT_TRUE( + message.GetExtension(unittest::optional_import_message_extension_lite) + .has_d()); + EXPECT_TRUE( + message + .GetExtension(unittest::optional_public_import_message_extension_lite) + .has_e()); + EXPECT_TRUE( + message.GetExtension(unittest::optional_lazy_message_extension_lite) + .has_bb()); - EXPECT_TRUE(message.HasExtension(unittest::optional_nested_enum_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_foreign_enum_extension_lite)); - EXPECT_TRUE(message.HasExtension(unittest::optional_import_enum_extension_lite )); + EXPECT_TRUE( + message.HasExtension(unittest::optional_nested_enum_extension_lite)); + EXPECT_TRUE( + message.HasExtension(unittest::optional_foreign_enum_extension_lite)); + EXPECT_TRUE( + message.HasExtension(unittest::optional_import_enum_extension_lite)); - EXPECT_EQ(101 , message.GetExtension(unittest::optional_int32_extension_lite )); - EXPECT_EQ(102 , message.GetExtension(unittest::optional_int64_extension_lite )); - EXPECT_EQ(103 , message.GetExtension(unittest::optional_uint32_extension_lite )); - EXPECT_EQ(104 , message.GetExtension(unittest::optional_uint64_extension_lite )); - EXPECT_EQ(105 , message.GetExtension(unittest::optional_sint32_extension_lite )); - EXPECT_EQ(106 , message.GetExtension(unittest::optional_sint64_extension_lite )); - EXPECT_EQ(107 , message.GetExtension(unittest::optional_fixed32_extension_lite )); - EXPECT_EQ(108 , message.GetExtension(unittest::optional_fixed64_extension_lite )); - EXPECT_EQ(109 , message.GetExtension(unittest::optional_sfixed32_extension_lite)); - EXPECT_EQ(110 , message.GetExtension(unittest::optional_sfixed64_extension_lite)); - EXPECT_EQ(111 , message.GetExtension(unittest::optional_float_extension_lite )); - EXPECT_EQ(112 , message.GetExtension(unittest::optional_double_extension_lite )); - EXPECT_EQ(true , message.GetExtension(unittest::optional_bool_extension_lite )); - EXPECT_EQ("115", message.GetExtension(unittest::optional_string_extension_lite )); - EXPECT_EQ("116", message.GetExtension(unittest::optional_bytes_extension_lite )); + EXPECT_EQ(101, message.GetExtension(unittest::optional_int32_extension_lite)); + EXPECT_EQ(102, message.GetExtension(unittest::optional_int64_extension_lite)); + EXPECT_EQ(103, + message.GetExtension(unittest::optional_uint32_extension_lite)); + EXPECT_EQ(104, + message.GetExtension(unittest::optional_uint64_extension_lite)); + EXPECT_EQ(105, + message.GetExtension(unittest::optional_sint32_extension_lite)); + EXPECT_EQ(106, + message.GetExtension(unittest::optional_sint64_extension_lite)); + EXPECT_EQ(107, + message.GetExtension(unittest::optional_fixed32_extension_lite)); + EXPECT_EQ(108, + message.GetExtension(unittest::optional_fixed64_extension_lite)); + EXPECT_EQ(109, + message.GetExtension(unittest::optional_sfixed32_extension_lite)); + EXPECT_EQ(110, + message.GetExtension(unittest::optional_sfixed64_extension_lite)); + EXPECT_EQ(111, message.GetExtension(unittest::optional_float_extension_lite)); + EXPECT_EQ(112, + message.GetExtension(unittest::optional_double_extension_lite)); + EXPECT_EQ(true, message.GetExtension(unittest::optional_bool_extension_lite)); + EXPECT_EQ("115", + message.GetExtension(unittest::optional_string_extension_lite)); + EXPECT_EQ("116", + message.GetExtension(unittest::optional_bytes_extension_lite)); - EXPECT_EQ(117, message.GetExtension(unittest::optionalgroup_extension_lite ).a()); - EXPECT_EQ(118, message.GetExtension(unittest::optional_nested_message_extension_lite ).bb()); - EXPECT_EQ(119, message.GetExtension(unittest::optional_foreign_message_extension_lite ).c()); - EXPECT_EQ(120, message.GetExtension(unittest::optional_import_message_extension_lite ).d()); - EXPECT_EQ(126, message.GetExtension(unittest::optional_public_import_message_extension_lite).e()); - EXPECT_EQ(127, message.GetExtension(unittest::optional_lazy_message_extension_lite ).bb()); + EXPECT_EQ(117, + message.GetExtension(unittest::optionalgroup_extension_lite).a()); + EXPECT_EQ( + 118, + message.GetExtension(unittest::optional_nested_message_extension_lite) + .bb()); + EXPECT_EQ( + 119, + message.GetExtension(unittest::optional_foreign_message_extension_lite) + .c()); + EXPECT_EQ( + 120, + message.GetExtension(unittest::optional_import_message_extension_lite) + .d()); + EXPECT_EQ( + 126, + message + .GetExtension(unittest::optional_public_import_message_extension_lite) + .e()); + EXPECT_EQ(127, + message.GetExtension(unittest::optional_lazy_message_extension_lite) + .bb()); - EXPECT_EQ(unittest::TestAllTypesLite::BAZ , message.GetExtension(unittest::optional_nested_enum_extension_lite )); - EXPECT_EQ(unittest::FOREIGN_LITE_BAZ , message.GetExtension(unittest::optional_foreign_enum_extension_lite)); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAZ, message.GetExtension(unittest::optional_import_enum_extension_lite )); + EXPECT_EQ( + unittest::TestAllTypesLite::BAZ, + message.GetExtension(unittest::optional_nested_enum_extension_lite)); + EXPECT_EQ( + unittest::FOREIGN_LITE_BAZ, + message.GetExtension(unittest::optional_foreign_enum_extension_lite)); + EXPECT_EQ( + unittest_import::IMPORT_LITE_BAZ, + message.GetExtension(unittest::optional_import_enum_extension_lite)); // ----------------------------------------------------------------- - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed32_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed64_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension_lite )); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension_lite)); + ASSERT_EQ(2, + message.ExtensionSize(unittest::repeated_fixed32_extension_lite)); + ASSERT_EQ(2, + message.ExtensionSize(unittest::repeated_fixed64_extension_lite)); + ASSERT_EQ(2, + message.ExtensionSize(unittest::repeated_sfixed32_extension_lite)); + ASSERT_EQ(2, + message.ExtensionSize(unittest::repeated_sfixed64_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_message_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_message_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_message_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_lazy_message_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_enum_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_enum_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_enum_extension_lite )); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize( + unittest::repeated_nested_message_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize( + unittest::repeated_foreign_message_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize( + unittest::repeated_import_message_extension_lite)); + ASSERT_EQ( + 2, message.ExtensionSize(unittest::repeated_lazy_message_extension_lite)); + ASSERT_EQ( + 2, message.ExtensionSize(unittest::repeated_nested_enum_extension_lite)); + ASSERT_EQ( + 2, message.ExtensionSize(unittest::repeated_foreign_enum_extension_lite)); + ASSERT_EQ( + 2, message.ExtensionSize(unittest::repeated_import_enum_extension_lite)); - EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension_lite , 0)); - EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension_lite , 0)); - EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension_lite , 0)); - EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension_lite , 0)); - EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension_lite , 0)); - EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension_lite , 0)); - EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension_lite , 0)); - EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension_lite , 0)); - EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension_lite, 0)); - EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension_lite, 0)); - EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension_lite , 0)); - EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension_lite , 0)); - EXPECT_EQ(true , message.GetExtension(unittest::repeated_bool_extension_lite , 0)); - EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension_lite , 0)); - EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension_lite , 0)); + EXPECT_EQ(201, + message.GetExtension(unittest::repeated_int32_extension_lite, 0)); + EXPECT_EQ(202, + message.GetExtension(unittest::repeated_int64_extension_lite, 0)); + EXPECT_EQ(203, + message.GetExtension(unittest::repeated_uint32_extension_lite, 0)); + EXPECT_EQ(204, + message.GetExtension(unittest::repeated_uint64_extension_lite, 0)); + EXPECT_EQ(205, + message.GetExtension(unittest::repeated_sint32_extension_lite, 0)); + EXPECT_EQ(206, + message.GetExtension(unittest::repeated_sint64_extension_lite, 0)); + EXPECT_EQ(207, + message.GetExtension(unittest::repeated_fixed32_extension_lite, 0)); + EXPECT_EQ(208, + message.GetExtension(unittest::repeated_fixed64_extension_lite, 0)); + EXPECT_EQ( + 209, message.GetExtension(unittest::repeated_sfixed32_extension_lite, 0)); + EXPECT_EQ( + 210, message.GetExtension(unittest::repeated_sfixed64_extension_lite, 0)); + EXPECT_EQ(211, + message.GetExtension(unittest::repeated_float_extension_lite, 0)); + EXPECT_EQ(212, + message.GetExtension(unittest::repeated_double_extension_lite, 0)); + EXPECT_EQ(true, + message.GetExtension(unittest::repeated_bool_extension_lite, 0)); + EXPECT_EQ("215", + message.GetExtension(unittest::repeated_string_extension_lite, 0)); + EXPECT_EQ("216", + message.GetExtension(unittest::repeated_bytes_extension_lite, 0)); - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension_lite , 0).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension_lite , 0).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension_lite, 0).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension_lite , 0).d()); - EXPECT_EQ(227, message.GetExtension(unittest::repeated_lazy_message_extension_lite , 0).bb()); + EXPECT_EQ( + 217, message.GetExtension(unittest::repeatedgroup_extension_lite, 0).a()); + EXPECT_EQ( + 218, + message.GetExtension(unittest::repeated_nested_message_extension_lite, 0) + .bb()); + EXPECT_EQ( + 219, + message.GetExtension(unittest::repeated_foreign_message_extension_lite, 0) + .c()); + EXPECT_EQ( + 220, + message.GetExtension(unittest::repeated_import_message_extension_lite, 0) + .d()); + EXPECT_EQ( + 227, + message.GetExtension(unittest::repeated_lazy_message_extension_lite, 0) + .bb()); - EXPECT_EQ(unittest::TestAllTypesLite::BAR , message.GetExtension(unittest::repeated_nested_enum_extension_lite , 0)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension_lite, 0)); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAR, message.GetExtension(unittest::repeated_import_enum_extension_lite , 0)); + EXPECT_EQ( + unittest::TestAllTypesLite::BAR, + message.GetExtension(unittest::repeated_nested_enum_extension_lite, 0)); + EXPECT_EQ( + unittest::FOREIGN_LITE_BAR, + message.GetExtension(unittest::repeated_foreign_enum_extension_lite, 0)); + EXPECT_EQ( + unittest_import::IMPORT_LITE_BAR, + message.GetExtension(unittest::repeated_import_enum_extension_lite, 0)); - EXPECT_EQ(301 , message.GetExtension(unittest::repeated_int32_extension_lite , 1)); - EXPECT_EQ(302 , message.GetExtension(unittest::repeated_int64_extension_lite , 1)); - EXPECT_EQ(303 , message.GetExtension(unittest::repeated_uint32_extension_lite , 1)); - EXPECT_EQ(304 , message.GetExtension(unittest::repeated_uint64_extension_lite , 1)); - EXPECT_EQ(305 , message.GetExtension(unittest::repeated_sint32_extension_lite , 1)); - EXPECT_EQ(306 , message.GetExtension(unittest::repeated_sint64_extension_lite , 1)); - EXPECT_EQ(307 , message.GetExtension(unittest::repeated_fixed32_extension_lite , 1)); - EXPECT_EQ(308 , message.GetExtension(unittest::repeated_fixed64_extension_lite , 1)); - EXPECT_EQ(309 , message.GetExtension(unittest::repeated_sfixed32_extension_lite, 1)); - EXPECT_EQ(310 , message.GetExtension(unittest::repeated_sfixed64_extension_lite, 1)); - EXPECT_EQ(311 , message.GetExtension(unittest::repeated_float_extension_lite , 1)); - EXPECT_EQ(312 , message.GetExtension(unittest::repeated_double_extension_lite , 1)); - EXPECT_EQ(false, message.GetExtension(unittest::repeated_bool_extension_lite , 1)); - EXPECT_EQ("315", message.GetExtension(unittest::repeated_string_extension_lite , 1)); - EXPECT_EQ("316", message.GetExtension(unittest::repeated_bytes_extension_lite , 1)); + EXPECT_EQ(301, + message.GetExtension(unittest::repeated_int32_extension_lite, 1)); + EXPECT_EQ(302, + message.GetExtension(unittest::repeated_int64_extension_lite, 1)); + EXPECT_EQ(303, + message.GetExtension(unittest::repeated_uint32_extension_lite, 1)); + EXPECT_EQ(304, + message.GetExtension(unittest::repeated_uint64_extension_lite, 1)); + EXPECT_EQ(305, + message.GetExtension(unittest::repeated_sint32_extension_lite, 1)); + EXPECT_EQ(306, + message.GetExtension(unittest::repeated_sint64_extension_lite, 1)); + EXPECT_EQ(307, + message.GetExtension(unittest::repeated_fixed32_extension_lite, 1)); + EXPECT_EQ(308, + message.GetExtension(unittest::repeated_fixed64_extension_lite, 1)); + EXPECT_EQ( + 309, message.GetExtension(unittest::repeated_sfixed32_extension_lite, 1)); + EXPECT_EQ( + 310, message.GetExtension(unittest::repeated_sfixed64_extension_lite, 1)); + EXPECT_EQ(311, + message.GetExtension(unittest::repeated_float_extension_lite, 1)); + EXPECT_EQ(312, + message.GetExtension(unittest::repeated_double_extension_lite, 1)); + EXPECT_EQ(false, + message.GetExtension(unittest::repeated_bool_extension_lite, 1)); + EXPECT_EQ("315", + message.GetExtension(unittest::repeated_string_extension_lite, 1)); + EXPECT_EQ("316", + message.GetExtension(unittest::repeated_bytes_extension_lite, 1)); - EXPECT_EQ(317, message.GetExtension(unittest::repeatedgroup_extension_lite , 1).a()); - EXPECT_EQ(318, message.GetExtension(unittest::repeated_nested_message_extension_lite , 1).bb()); - EXPECT_EQ(319, message.GetExtension(unittest::repeated_foreign_message_extension_lite, 1).c()); - EXPECT_EQ(320, message.GetExtension(unittest::repeated_import_message_extension_lite , 1).d()); - EXPECT_EQ(327, message.GetExtension(unittest::repeated_lazy_message_extension_lite , 1).bb()); + EXPECT_EQ( + 317, message.GetExtension(unittest::repeatedgroup_extension_lite, 1).a()); + EXPECT_EQ( + 318, + message.GetExtension(unittest::repeated_nested_message_extension_lite, 1) + .bb()); + EXPECT_EQ( + 319, + message.GetExtension(unittest::repeated_foreign_message_extension_lite, 1) + .c()); + EXPECT_EQ( + 320, + message.GetExtension(unittest::repeated_import_message_extension_lite, 1) + .d()); + EXPECT_EQ( + 327, + message.GetExtension(unittest::repeated_lazy_message_extension_lite, 1) + .bb()); - EXPECT_EQ(unittest::TestAllTypesLite::BAZ , message.GetExtension(unittest::repeated_nested_enum_extension_lite , 1)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAZ , message.GetExtension(unittest::repeated_foreign_enum_extension_lite, 1)); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAZ, message.GetExtension(unittest::repeated_import_enum_extension_lite , 1)); + EXPECT_EQ( + unittest::TestAllTypesLite::BAZ, + message.GetExtension(unittest::repeated_nested_enum_extension_lite, 1)); + EXPECT_EQ( + unittest::FOREIGN_LITE_BAZ, + message.GetExtension(unittest::repeated_foreign_enum_extension_lite, 1)); + EXPECT_EQ( + unittest_import::IMPORT_LITE_BAZ, + message.GetExtension(unittest::repeated_import_enum_extension_lite, 1)); // ----------------------------------------------------------------- - EXPECT_TRUE(message.HasExtension(unittest::default_int32_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_int64_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_uint32_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_uint64_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_sint32_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_sint64_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_fixed32_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_fixed64_extension_lite )); + EXPECT_TRUE(message.HasExtension(unittest::default_int32_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::default_int64_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::default_uint32_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::default_uint64_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::default_sint32_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::default_sint64_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::default_fixed32_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::default_fixed64_extension_lite)); EXPECT_TRUE(message.HasExtension(unittest::default_sfixed32_extension_lite)); EXPECT_TRUE(message.HasExtension(unittest::default_sfixed64_extension_lite)); - EXPECT_TRUE(message.HasExtension(unittest::default_float_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_double_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_bool_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_string_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_bytes_extension_lite )); + EXPECT_TRUE(message.HasExtension(unittest::default_float_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::default_double_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::default_bool_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::default_string_extension_lite)); + EXPECT_TRUE(message.HasExtension(unittest::default_bytes_extension_lite)); - EXPECT_TRUE(message.HasExtension(unittest::default_nested_enum_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_foreign_enum_extension_lite)); - EXPECT_TRUE(message.HasExtension(unittest::default_import_enum_extension_lite )); + EXPECT_TRUE( + message.HasExtension(unittest::default_nested_enum_extension_lite)); + EXPECT_TRUE( + message.HasExtension(unittest::default_foreign_enum_extension_lite)); + EXPECT_TRUE( + message.HasExtension(unittest::default_import_enum_extension_lite)); - EXPECT_EQ(401 , message.GetExtension(unittest::default_int32_extension_lite )); - EXPECT_EQ(402 , message.GetExtension(unittest::default_int64_extension_lite )); - EXPECT_EQ(403 , message.GetExtension(unittest::default_uint32_extension_lite )); - EXPECT_EQ(404 , message.GetExtension(unittest::default_uint64_extension_lite )); - EXPECT_EQ(405 , message.GetExtension(unittest::default_sint32_extension_lite )); - EXPECT_EQ(406 , message.GetExtension(unittest::default_sint64_extension_lite )); - EXPECT_EQ(407 , message.GetExtension(unittest::default_fixed32_extension_lite )); - EXPECT_EQ(408 , message.GetExtension(unittest::default_fixed64_extension_lite )); - EXPECT_EQ(409 , message.GetExtension(unittest::default_sfixed32_extension_lite)); - EXPECT_EQ(410 , message.GetExtension(unittest::default_sfixed64_extension_lite)); - EXPECT_EQ(411 , message.GetExtension(unittest::default_float_extension_lite )); - EXPECT_EQ(412 , message.GetExtension(unittest::default_double_extension_lite )); - EXPECT_EQ(false, message.GetExtension(unittest::default_bool_extension_lite )); - EXPECT_EQ("415", message.GetExtension(unittest::default_string_extension_lite )); - EXPECT_EQ("416", message.GetExtension(unittest::default_bytes_extension_lite )); + EXPECT_EQ(401, message.GetExtension(unittest::default_int32_extension_lite)); + EXPECT_EQ(402, message.GetExtension(unittest::default_int64_extension_lite)); + EXPECT_EQ(403, message.GetExtension(unittest::default_uint32_extension_lite)); + EXPECT_EQ(404, message.GetExtension(unittest::default_uint64_extension_lite)); + EXPECT_EQ(405, message.GetExtension(unittest::default_sint32_extension_lite)); + EXPECT_EQ(406, message.GetExtension(unittest::default_sint64_extension_lite)); + EXPECT_EQ(407, + message.GetExtension(unittest::default_fixed32_extension_lite)); + EXPECT_EQ(408, + message.GetExtension(unittest::default_fixed64_extension_lite)); + EXPECT_EQ(409, + message.GetExtension(unittest::default_sfixed32_extension_lite)); + EXPECT_EQ(410, + message.GetExtension(unittest::default_sfixed64_extension_lite)); + EXPECT_EQ(411, message.GetExtension(unittest::default_float_extension_lite)); + EXPECT_EQ(412, message.GetExtension(unittest::default_double_extension_lite)); + EXPECT_EQ(false, message.GetExtension(unittest::default_bool_extension_lite)); + EXPECT_EQ("415", + message.GetExtension(unittest::default_string_extension_lite)); + EXPECT_EQ("416", + message.GetExtension(unittest::default_bytes_extension_lite)); - EXPECT_EQ(unittest::TestAllTypesLite::FOO , message.GetExtension(unittest::default_nested_enum_extension_lite )); - EXPECT_EQ(unittest::FOREIGN_LITE_FOO , message.GetExtension(unittest::default_foreign_enum_extension_lite)); - EXPECT_EQ(unittest_import::IMPORT_LITE_FOO, message.GetExtension(unittest::default_import_enum_extension_lite )); + EXPECT_EQ(unittest::TestAllTypesLite::FOO, + message.GetExtension(unittest::default_nested_enum_extension_lite)); + EXPECT_EQ( + unittest::FOREIGN_LITE_FOO, + message.GetExtension(unittest::default_foreign_enum_extension_lite)); + EXPECT_EQ(unittest_import::IMPORT_LITE_FOO, + message.GetExtension(unittest::default_import_enum_extension_lite)); EXPECT_TRUE(message.HasExtension(unittest::oneof_uint32_extension_lite)); - EXPECT_TRUE(message.GetExtension(unittest::oneof_nested_message_extension_lite).has_bb()); + EXPECT_TRUE( + message.GetExtension(unittest::oneof_nested_message_extension_lite) + .has_bb()); EXPECT_TRUE(message.HasExtension(unittest::oneof_string_extension_lite)); EXPECT_TRUE(message.HasExtension(unittest::oneof_bytes_extension_lite)); EXPECT_EQ(601, message.GetExtension(unittest::oneof_uint32_extension_lite)); - EXPECT_EQ(602, message.GetExtension(unittest::oneof_nested_message_extension_lite).bb()); + EXPECT_EQ( + 602, + message.GetExtension(unittest::oneof_nested_message_extension_lite).bb()); EXPECT_EQ("603", message.GetExtension(unittest::oneof_string_extension_lite)); EXPECT_EQ("604", message.GetExtension(unittest::oneof_bytes_extension_lite)); } @@ -1160,151 +1347,219 @@ void TestUtilLite::ExpectAllExtensionsSet( void TestUtilLite::ExpectExtensionsClear( const unittest::TestAllExtensionsLite& message) { - string serialized; + std::string serialized; ASSERT_TRUE(message.SerializeToString(&serialized)); EXPECT_EQ("", serialized); EXPECT_EQ(0, message.ByteSize()); // has_blah() should initially be false for all optional fields. - EXPECT_FALSE(message.HasExtension(unittest::optional_int32_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_int64_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_uint32_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_uint64_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_sint32_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_sint64_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_fixed32_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_fixed64_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_sfixed32_extension_lite)); - EXPECT_FALSE(message.HasExtension(unittest::optional_sfixed64_extension_lite)); - EXPECT_FALSE(message.HasExtension(unittest::optional_float_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_double_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_bool_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_string_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_bytes_extension_lite )); + EXPECT_FALSE(message.HasExtension(unittest::optional_int32_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::optional_int64_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::optional_uint32_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::optional_uint64_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::optional_sint32_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::optional_sint64_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::optional_fixed32_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::optional_fixed64_extension_lite)); + EXPECT_FALSE( + message.HasExtension(unittest::optional_sfixed32_extension_lite)); + EXPECT_FALSE( + message.HasExtension(unittest::optional_sfixed64_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::optional_float_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::optional_double_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::optional_bool_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::optional_string_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::optional_bytes_extension_lite)); - EXPECT_FALSE(message.HasExtension(unittest::optionalgroup_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_nested_message_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_foreign_message_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_import_message_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_public_import_message_extension_lite)); - EXPECT_FALSE(message.HasExtension(unittest::optional_lazy_message_extension_lite )); + EXPECT_FALSE(message.HasExtension(unittest::optionalgroup_extension_lite)); + EXPECT_FALSE( + message.HasExtension(unittest::optional_nested_message_extension_lite)); + EXPECT_FALSE( + message.HasExtension(unittest::optional_foreign_message_extension_lite)); + EXPECT_FALSE( + message.HasExtension(unittest::optional_import_message_extension_lite)); + EXPECT_FALSE(message.HasExtension( + unittest::optional_public_import_message_extension_lite)); + EXPECT_FALSE( + message.HasExtension(unittest::optional_lazy_message_extension_lite)); - EXPECT_FALSE(message.HasExtension(unittest::optional_nested_enum_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_foreign_enum_extension_lite)); - EXPECT_FALSE(message.HasExtension(unittest::optional_import_enum_extension_lite )); + EXPECT_FALSE( + message.HasExtension(unittest::optional_nested_enum_extension_lite)); + EXPECT_FALSE( + message.HasExtension(unittest::optional_foreign_enum_extension_lite)); + EXPECT_FALSE( + message.HasExtension(unittest::optional_import_enum_extension_lite)); // Optional fields without defaults are set to zero or something like it. - EXPECT_EQ(0 , message.GetExtension(unittest::optional_int32_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_int64_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_uint32_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_uint64_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sint32_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sint64_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_fixed32_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_fixed64_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sfixed32_extension_lite)); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sfixed64_extension_lite)); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_float_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_double_extension_lite )); - EXPECT_EQ(false, message.GetExtension(unittest::optional_bool_extension_lite )); - EXPECT_EQ("" , message.GetExtension(unittest::optional_string_extension_lite )); - EXPECT_EQ("" , message.GetExtension(unittest::optional_bytes_extension_lite )); + EXPECT_EQ(0, message.GetExtension(unittest::optional_int32_extension_lite)); + EXPECT_EQ(0, message.GetExtension(unittest::optional_int64_extension_lite)); + EXPECT_EQ(0, message.GetExtension(unittest::optional_uint32_extension_lite)); + EXPECT_EQ(0, message.GetExtension(unittest::optional_uint64_extension_lite)); + EXPECT_EQ(0, message.GetExtension(unittest::optional_sint32_extension_lite)); + EXPECT_EQ(0, message.GetExtension(unittest::optional_sint64_extension_lite)); + EXPECT_EQ(0, message.GetExtension(unittest::optional_fixed32_extension_lite)); + EXPECT_EQ(0, message.GetExtension(unittest::optional_fixed64_extension_lite)); + EXPECT_EQ(0, + message.GetExtension(unittest::optional_sfixed32_extension_lite)); + EXPECT_EQ(0, + message.GetExtension(unittest::optional_sfixed64_extension_lite)); + EXPECT_EQ(0, message.GetExtension(unittest::optional_float_extension_lite)); + EXPECT_EQ(0, message.GetExtension(unittest::optional_double_extension_lite)); + EXPECT_EQ(false, + message.GetExtension(unittest::optional_bool_extension_lite)); + EXPECT_EQ("", message.GetExtension(unittest::optional_string_extension_lite)); + EXPECT_EQ("", message.GetExtension(unittest::optional_bytes_extension_lite)); // Embedded messages should also be clear. - EXPECT_FALSE(message.GetExtension(unittest::optionalgroup_extension_lite ).has_a()); - EXPECT_FALSE(message.GetExtension(unittest::optional_nested_message_extension_lite ).has_bb()); - EXPECT_FALSE(message.GetExtension(unittest::optional_foreign_message_extension_lite ).has_c()); - EXPECT_FALSE(message.GetExtension(unittest::optional_import_message_extension_lite ).has_d()); - EXPECT_FALSE(message.GetExtension(unittest::optional_public_import_message_extension_lite).has_e()); - EXPECT_FALSE(message.GetExtension(unittest::optional_lazy_message_extension_lite ).has_bb()); + EXPECT_FALSE( + message.GetExtension(unittest::optionalgroup_extension_lite).has_a()); + EXPECT_FALSE( + message.GetExtension(unittest::optional_nested_message_extension_lite) + .has_bb()); + EXPECT_FALSE( + message.GetExtension(unittest::optional_foreign_message_extension_lite) + .has_c()); + EXPECT_FALSE( + message.GetExtension(unittest::optional_import_message_extension_lite) + .has_d()); + EXPECT_FALSE( + message + .GetExtension(unittest::optional_public_import_message_extension_lite) + .has_e()); + EXPECT_FALSE( + message.GetExtension(unittest::optional_lazy_message_extension_lite) + .has_bb()); - EXPECT_EQ(0, message.GetExtension(unittest::optionalgroup_extension_lite ).a()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_nested_message_extension_lite ).bb()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_foreign_message_extension_lite ).c()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_import_message_extension_lite ).d()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_public_import_message_extension_lite).e()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_lazy_message_extension_lite ).bb()); + EXPECT_EQ(0, + message.GetExtension(unittest::optionalgroup_extension_lite).a()); + EXPECT_EQ( + 0, message.GetExtension(unittest::optional_nested_message_extension_lite) + .bb()); + EXPECT_EQ( + 0, message.GetExtension(unittest::optional_foreign_message_extension_lite) + .c()); + EXPECT_EQ( + 0, message.GetExtension(unittest::optional_import_message_extension_lite) + .d()); + EXPECT_EQ(0, message + .GetExtension( + unittest::optional_public_import_message_extension_lite) + .e()); + EXPECT_EQ(0, + message.GetExtension(unittest::optional_lazy_message_extension_lite) + .bb()); // Enums without defaults are set to the first value in the enum. - EXPECT_EQ(unittest::TestAllTypesLite::FOO , message.GetExtension(unittest::optional_nested_enum_extension_lite )); - EXPECT_EQ(unittest::FOREIGN_LITE_FOO , message.GetExtension(unittest::optional_foreign_enum_extension_lite)); - EXPECT_EQ(unittest_import::IMPORT_LITE_FOO, message.GetExtension(unittest::optional_import_enum_extension_lite )); + EXPECT_EQ( + unittest::TestAllTypesLite::FOO, + message.GetExtension(unittest::optional_nested_enum_extension_lite)); + EXPECT_EQ( + unittest::FOREIGN_LITE_FOO, + message.GetExtension(unittest::optional_foreign_enum_extension_lite)); + EXPECT_EQ( + unittest_import::IMPORT_LITE_FOO, + message.GetExtension(unittest::optional_import_enum_extension_lite)); // Repeated fields are empty. - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_int32_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_int64_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_uint32_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_uint64_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sint32_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sint64_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_fixed32_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_fixed64_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sfixed32_extension_lite)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sfixed64_extension_lite)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_float_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_double_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_bool_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_string_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_bytes_extension_lite )); + EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_int32_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_int64_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_uint32_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_uint64_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sint32_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sint64_extension_lite)); + EXPECT_EQ(0, + message.ExtensionSize(unittest::repeated_fixed32_extension_lite)); + EXPECT_EQ(0, + message.ExtensionSize(unittest::repeated_fixed64_extension_lite)); + EXPECT_EQ(0, + message.ExtensionSize(unittest::repeated_sfixed32_extension_lite)); + EXPECT_EQ(0, + message.ExtensionSize(unittest::repeated_sfixed64_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_float_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_double_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_bool_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_string_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_bytes_extension_lite)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeatedgroup_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_nested_message_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_foreign_message_extension_lite)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_import_message_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_lazy_message_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_nested_enum_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_foreign_enum_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_import_enum_extension_lite )); + EXPECT_EQ(0, message.ExtensionSize(unittest::repeatedgroup_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize( + unittest::repeated_nested_message_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize( + unittest::repeated_foreign_message_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize( + unittest::repeated_import_message_extension_lite)); + EXPECT_EQ( + 0, message.ExtensionSize(unittest::repeated_lazy_message_extension_lite)); + EXPECT_EQ( + 0, message.ExtensionSize(unittest::repeated_nested_enum_extension_lite)); + EXPECT_EQ( + 0, message.ExtensionSize(unittest::repeated_foreign_enum_extension_lite)); + EXPECT_EQ( + 0, message.ExtensionSize(unittest::repeated_import_enum_extension_lite)); // has_blah() should also be false for all default fields. - EXPECT_FALSE(message.HasExtension(unittest::default_int32_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_int64_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_uint32_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_uint64_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_sint32_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_sint64_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_fixed32_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_fixed64_extension_lite )); + EXPECT_FALSE(message.HasExtension(unittest::default_int32_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::default_int64_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::default_uint32_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::default_uint64_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::default_sint32_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::default_sint64_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::default_fixed32_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::default_fixed64_extension_lite)); EXPECT_FALSE(message.HasExtension(unittest::default_sfixed32_extension_lite)); EXPECT_FALSE(message.HasExtension(unittest::default_sfixed64_extension_lite)); - EXPECT_FALSE(message.HasExtension(unittest::default_float_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_double_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_bool_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_string_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_bytes_extension_lite )); + EXPECT_FALSE(message.HasExtension(unittest::default_float_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::default_double_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::default_bool_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::default_string_extension_lite)); + EXPECT_FALSE(message.HasExtension(unittest::default_bytes_extension_lite)); - EXPECT_FALSE(message.HasExtension(unittest::default_nested_enum_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_foreign_enum_extension_lite)); - EXPECT_FALSE(message.HasExtension(unittest::default_import_enum_extension_lite )); + EXPECT_FALSE( + message.HasExtension(unittest::default_nested_enum_extension_lite)); + EXPECT_FALSE( + message.HasExtension(unittest::default_foreign_enum_extension_lite)); + EXPECT_FALSE( + message.HasExtension(unittest::default_import_enum_extension_lite)); // Fields with defaults have their default values (duh). - EXPECT_EQ( 41 , message.GetExtension(unittest::default_int32_extension_lite )); - EXPECT_EQ( 42 , message.GetExtension(unittest::default_int64_extension_lite )); - EXPECT_EQ( 43 , message.GetExtension(unittest::default_uint32_extension_lite )); - EXPECT_EQ( 44 , message.GetExtension(unittest::default_uint64_extension_lite )); - EXPECT_EQ(-45 , message.GetExtension(unittest::default_sint32_extension_lite )); - EXPECT_EQ( 46 , message.GetExtension(unittest::default_sint64_extension_lite )); - EXPECT_EQ( 47 , message.GetExtension(unittest::default_fixed32_extension_lite )); - EXPECT_EQ( 48 , message.GetExtension(unittest::default_fixed64_extension_lite )); - EXPECT_EQ( 49 , message.GetExtension(unittest::default_sfixed32_extension_lite)); - EXPECT_EQ(-50 , message.GetExtension(unittest::default_sfixed64_extension_lite)); - EXPECT_EQ( 51.5 , message.GetExtension(unittest::default_float_extension_lite )); - EXPECT_EQ( 52e3 , message.GetExtension(unittest::default_double_extension_lite )); - EXPECT_EQ(true , message.GetExtension(unittest::default_bool_extension_lite )); - EXPECT_EQ("hello", message.GetExtension(unittest::default_string_extension_lite )); - EXPECT_EQ("world", message.GetExtension(unittest::default_bytes_extension_lite )); + EXPECT_EQ(41, message.GetExtension(unittest::default_int32_extension_lite)); + EXPECT_EQ(42, message.GetExtension(unittest::default_int64_extension_lite)); + EXPECT_EQ(43, message.GetExtension(unittest::default_uint32_extension_lite)); + EXPECT_EQ(44, message.GetExtension(unittest::default_uint64_extension_lite)); + EXPECT_EQ(-45, message.GetExtension(unittest::default_sint32_extension_lite)); + EXPECT_EQ(46, message.GetExtension(unittest::default_sint64_extension_lite)); + EXPECT_EQ(47, message.GetExtension(unittest::default_fixed32_extension_lite)); + EXPECT_EQ(48, message.GetExtension(unittest::default_fixed64_extension_lite)); + EXPECT_EQ(49, + message.GetExtension(unittest::default_sfixed32_extension_lite)); + EXPECT_EQ(-50, + message.GetExtension(unittest::default_sfixed64_extension_lite)); + EXPECT_EQ(51.5, message.GetExtension(unittest::default_float_extension_lite)); + EXPECT_EQ(52e3, + message.GetExtension(unittest::default_double_extension_lite)); + EXPECT_EQ(true, message.GetExtension(unittest::default_bool_extension_lite)); + EXPECT_EQ("hello", + message.GetExtension(unittest::default_string_extension_lite)); + EXPECT_EQ("world", + message.GetExtension(unittest::default_bytes_extension_lite)); - EXPECT_EQ(unittest::TestAllTypesLite::BAR , message.GetExtension(unittest::default_nested_enum_extension_lite )); - EXPECT_EQ(unittest::FOREIGN_LITE_BAR , message.GetExtension(unittest::default_foreign_enum_extension_lite)); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAR, message.GetExtension(unittest::default_import_enum_extension_lite )); + EXPECT_EQ(unittest::TestAllTypesLite::BAR, + message.GetExtension(unittest::default_nested_enum_extension_lite)); + EXPECT_EQ( + unittest::FOREIGN_LITE_BAR, + message.GetExtension(unittest::default_foreign_enum_extension_lite)); + EXPECT_EQ(unittest_import::IMPORT_LITE_BAR, + message.GetExtension(unittest::default_import_enum_extension_lite)); EXPECT_FALSE(message.HasExtension(unittest::oneof_uint32_extension_lite)); - EXPECT_FALSE(message.GetExtension(unittest::oneof_nested_message_extension_lite).has_bb()); + EXPECT_FALSE( + message.GetExtension(unittest::oneof_nested_message_extension_lite) + .has_bb()); EXPECT_FALSE(message.HasExtension(unittest::oneof_string_extension_lite)); EXPECT_FALSE(message.HasExtension(unittest::oneof_bytes_extension_lite)); } @@ -1316,85 +1571,164 @@ void TestUtilLite::ExpectRepeatedExtensionsModified( // ModifyRepeatedFields only sets the second repeated element of each // field. In addition to verifying this, we also verify that the first // element and size were *not* modified. - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed32_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed64_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension_lite )); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension_lite)); + ASSERT_EQ(2, + message.ExtensionSize(unittest::repeated_fixed32_extension_lite)); + ASSERT_EQ(2, + message.ExtensionSize(unittest::repeated_fixed64_extension_lite)); + ASSERT_EQ(2, + message.ExtensionSize(unittest::repeated_sfixed32_extension_lite)); + ASSERT_EQ(2, + message.ExtensionSize(unittest::repeated_sfixed64_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_message_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_message_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_message_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_lazy_message_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_enum_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_enum_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_enum_extension_lite )); + ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize( + unittest::repeated_nested_message_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize( + unittest::repeated_foreign_message_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize( + unittest::repeated_import_message_extension_lite)); + ASSERT_EQ( + 2, message.ExtensionSize(unittest::repeated_lazy_message_extension_lite)); + ASSERT_EQ( + 2, message.ExtensionSize(unittest::repeated_nested_enum_extension_lite)); + ASSERT_EQ( + 2, message.ExtensionSize(unittest::repeated_foreign_enum_extension_lite)); + ASSERT_EQ( + 2, message.ExtensionSize(unittest::repeated_import_enum_extension_lite)); - EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension_lite , 0)); - EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension_lite , 0)); - EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension_lite , 0)); - EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension_lite , 0)); - EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension_lite , 0)); - EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension_lite , 0)); - EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension_lite , 0)); - EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension_lite , 0)); - EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension_lite, 0)); - EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension_lite, 0)); - EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension_lite , 0)); - EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension_lite , 0)); - EXPECT_EQ(true , message.GetExtension(unittest::repeated_bool_extension_lite , 0)); - EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension_lite , 0)); - EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension_lite , 0)); + EXPECT_EQ(201, + message.GetExtension(unittest::repeated_int32_extension_lite, 0)); + EXPECT_EQ(202, + message.GetExtension(unittest::repeated_int64_extension_lite, 0)); + EXPECT_EQ(203, + message.GetExtension(unittest::repeated_uint32_extension_lite, 0)); + EXPECT_EQ(204, + message.GetExtension(unittest::repeated_uint64_extension_lite, 0)); + EXPECT_EQ(205, + message.GetExtension(unittest::repeated_sint32_extension_lite, 0)); + EXPECT_EQ(206, + message.GetExtension(unittest::repeated_sint64_extension_lite, 0)); + EXPECT_EQ(207, + message.GetExtension(unittest::repeated_fixed32_extension_lite, 0)); + EXPECT_EQ(208, + message.GetExtension(unittest::repeated_fixed64_extension_lite, 0)); + EXPECT_EQ( + 209, message.GetExtension(unittest::repeated_sfixed32_extension_lite, 0)); + EXPECT_EQ( + 210, message.GetExtension(unittest::repeated_sfixed64_extension_lite, 0)); + EXPECT_EQ(211, + message.GetExtension(unittest::repeated_float_extension_lite, 0)); + EXPECT_EQ(212, + message.GetExtension(unittest::repeated_double_extension_lite, 0)); + EXPECT_EQ(true, + message.GetExtension(unittest::repeated_bool_extension_lite, 0)); + EXPECT_EQ("215", + message.GetExtension(unittest::repeated_string_extension_lite, 0)); + EXPECT_EQ("216", + message.GetExtension(unittest::repeated_bytes_extension_lite, 0)); - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension_lite , 0).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension_lite , 0).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension_lite, 0).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension_lite , 0).d()); - EXPECT_EQ(227, message.GetExtension(unittest::repeated_lazy_message_extension_lite , 0).bb()); + EXPECT_EQ( + 217, message.GetExtension(unittest::repeatedgroup_extension_lite, 0).a()); + EXPECT_EQ( + 218, + message.GetExtension(unittest::repeated_nested_message_extension_lite, 0) + .bb()); + EXPECT_EQ( + 219, + message.GetExtension(unittest::repeated_foreign_message_extension_lite, 0) + .c()); + EXPECT_EQ( + 220, + message.GetExtension(unittest::repeated_import_message_extension_lite, 0) + .d()); + EXPECT_EQ( + 227, + message.GetExtension(unittest::repeated_lazy_message_extension_lite, 0) + .bb()); - EXPECT_EQ(unittest::TestAllTypesLite::BAR , message.GetExtension(unittest::repeated_nested_enum_extension_lite , 0)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension_lite, 0)); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAR, message.GetExtension(unittest::repeated_import_enum_extension_lite , 0)); + EXPECT_EQ( + unittest::TestAllTypesLite::BAR, + message.GetExtension(unittest::repeated_nested_enum_extension_lite, 0)); + EXPECT_EQ( + unittest::FOREIGN_LITE_BAR, + message.GetExtension(unittest::repeated_foreign_enum_extension_lite, 0)); + EXPECT_EQ( + unittest_import::IMPORT_LITE_BAR, + message.GetExtension(unittest::repeated_import_enum_extension_lite, 0)); // Actually verify the second (modified) elements now. - EXPECT_EQ(501 , message.GetExtension(unittest::repeated_int32_extension_lite , 1)); - EXPECT_EQ(502 , message.GetExtension(unittest::repeated_int64_extension_lite , 1)); - EXPECT_EQ(503 , message.GetExtension(unittest::repeated_uint32_extension_lite , 1)); - EXPECT_EQ(504 , message.GetExtension(unittest::repeated_uint64_extension_lite , 1)); - EXPECT_EQ(505 , message.GetExtension(unittest::repeated_sint32_extension_lite , 1)); - EXPECT_EQ(506 , message.GetExtension(unittest::repeated_sint64_extension_lite , 1)); - EXPECT_EQ(507 , message.GetExtension(unittest::repeated_fixed32_extension_lite , 1)); - EXPECT_EQ(508 , message.GetExtension(unittest::repeated_fixed64_extension_lite , 1)); - EXPECT_EQ(509 , message.GetExtension(unittest::repeated_sfixed32_extension_lite, 1)); - EXPECT_EQ(510 , message.GetExtension(unittest::repeated_sfixed64_extension_lite, 1)); - EXPECT_EQ(511 , message.GetExtension(unittest::repeated_float_extension_lite , 1)); - EXPECT_EQ(512 , message.GetExtension(unittest::repeated_double_extension_lite , 1)); - EXPECT_EQ(true , message.GetExtension(unittest::repeated_bool_extension_lite , 1)); - EXPECT_EQ("515", message.GetExtension(unittest::repeated_string_extension_lite , 1)); - EXPECT_EQ("516", message.GetExtension(unittest::repeated_bytes_extension_lite , 1)); + EXPECT_EQ(501, + message.GetExtension(unittest::repeated_int32_extension_lite, 1)); + EXPECT_EQ(502, + message.GetExtension(unittest::repeated_int64_extension_lite, 1)); + EXPECT_EQ(503, + message.GetExtension(unittest::repeated_uint32_extension_lite, 1)); + EXPECT_EQ(504, + message.GetExtension(unittest::repeated_uint64_extension_lite, 1)); + EXPECT_EQ(505, + message.GetExtension(unittest::repeated_sint32_extension_lite, 1)); + EXPECT_EQ(506, + message.GetExtension(unittest::repeated_sint64_extension_lite, 1)); + EXPECT_EQ(507, + message.GetExtension(unittest::repeated_fixed32_extension_lite, 1)); + EXPECT_EQ(508, + message.GetExtension(unittest::repeated_fixed64_extension_lite, 1)); + EXPECT_EQ( + 509, message.GetExtension(unittest::repeated_sfixed32_extension_lite, 1)); + EXPECT_EQ( + 510, message.GetExtension(unittest::repeated_sfixed64_extension_lite, 1)); + EXPECT_EQ(511, + message.GetExtension(unittest::repeated_float_extension_lite, 1)); + EXPECT_EQ(512, + message.GetExtension(unittest::repeated_double_extension_lite, 1)); + EXPECT_EQ(true, + message.GetExtension(unittest::repeated_bool_extension_lite, 1)); + EXPECT_EQ("515", + message.GetExtension(unittest::repeated_string_extension_lite, 1)); + EXPECT_EQ("516", + message.GetExtension(unittest::repeated_bytes_extension_lite, 1)); - EXPECT_EQ(517, message.GetExtension(unittest::repeatedgroup_extension_lite , 1).a()); - EXPECT_EQ(518, message.GetExtension(unittest::repeated_nested_message_extension_lite , 1).bb()); - EXPECT_EQ(519, message.GetExtension(unittest::repeated_foreign_message_extension_lite, 1).c()); - EXPECT_EQ(520, message.GetExtension(unittest::repeated_import_message_extension_lite , 1).d()); - EXPECT_EQ(527, message.GetExtension(unittest::repeated_lazy_message_extension_lite , 1).bb()); + EXPECT_EQ( + 517, message.GetExtension(unittest::repeatedgroup_extension_lite, 1).a()); + EXPECT_EQ( + 518, + message.GetExtension(unittest::repeated_nested_message_extension_lite, 1) + .bb()); + EXPECT_EQ( + 519, + message.GetExtension(unittest::repeated_foreign_message_extension_lite, 1) + .c()); + EXPECT_EQ( + 520, + message.GetExtension(unittest::repeated_import_message_extension_lite, 1) + .d()); + EXPECT_EQ( + 527, + message.GetExtension(unittest::repeated_lazy_message_extension_lite, 1) + .bb()); - EXPECT_EQ(unittest::TestAllTypesLite::FOO , message.GetExtension(unittest::repeated_nested_enum_extension_lite , 1)); - EXPECT_EQ(unittest::FOREIGN_LITE_FOO , message.GetExtension(unittest::repeated_foreign_enum_extension_lite, 1)); - EXPECT_EQ(unittest_import::IMPORT_LITE_FOO, message.GetExtension(unittest::repeated_import_enum_extension_lite , 1)); + EXPECT_EQ( + unittest::TestAllTypesLite::FOO, + message.GetExtension(unittest::repeated_nested_enum_extension_lite, 1)); + EXPECT_EQ( + unittest::FOREIGN_LITE_FOO, + message.GetExtension(unittest::repeated_foreign_enum_extension_lite, 1)); + EXPECT_EQ( + unittest_import::IMPORT_LITE_FOO, + message.GetExtension(unittest::repeated_import_enum_extension_lite, 1)); } @@ -1402,55 +1736,57 @@ void TestUtilLite::ExpectRepeatedExtensionsModified( void TestUtilLite::SetPackedExtensions( unittest::TestPackedExtensionsLite* message) { - message->AddExtension(unittest::packed_int32_extension_lite , 601); - message->AddExtension(unittest::packed_int64_extension_lite , 602); - message->AddExtension(unittest::packed_uint32_extension_lite , 603); - message->AddExtension(unittest::packed_uint64_extension_lite , 604); - message->AddExtension(unittest::packed_sint32_extension_lite , 605); - message->AddExtension(unittest::packed_sint64_extension_lite , 606); - message->AddExtension(unittest::packed_fixed32_extension_lite , 607); - message->AddExtension(unittest::packed_fixed64_extension_lite , 608); + message->AddExtension(unittest::packed_int32_extension_lite, 601); + message->AddExtension(unittest::packed_int64_extension_lite, 602); + message->AddExtension(unittest::packed_uint32_extension_lite, 603); + message->AddExtension(unittest::packed_uint64_extension_lite, 604); + message->AddExtension(unittest::packed_sint32_extension_lite, 605); + message->AddExtension(unittest::packed_sint64_extension_lite, 606); + message->AddExtension(unittest::packed_fixed32_extension_lite, 607); + message->AddExtension(unittest::packed_fixed64_extension_lite, 608); message->AddExtension(unittest::packed_sfixed32_extension_lite, 609); message->AddExtension(unittest::packed_sfixed64_extension_lite, 610); - message->AddExtension(unittest::packed_float_extension_lite , 611); - message->AddExtension(unittest::packed_double_extension_lite , 612); - message->AddExtension(unittest::packed_bool_extension_lite , true); - message->AddExtension(unittest::packed_enum_extension_lite, unittest::FOREIGN_LITE_BAR); + message->AddExtension(unittest::packed_float_extension_lite, 611); + message->AddExtension(unittest::packed_double_extension_lite, 612); + message->AddExtension(unittest::packed_bool_extension_lite, true); + message->AddExtension(unittest::packed_enum_extension_lite, + unittest::FOREIGN_LITE_BAR); // add a second one of each field - message->AddExtension(unittest::packed_int32_extension_lite , 701); - message->AddExtension(unittest::packed_int64_extension_lite , 702); - message->AddExtension(unittest::packed_uint32_extension_lite , 703); - message->AddExtension(unittest::packed_uint64_extension_lite , 704); - message->AddExtension(unittest::packed_sint32_extension_lite , 705); - message->AddExtension(unittest::packed_sint64_extension_lite , 706); - message->AddExtension(unittest::packed_fixed32_extension_lite , 707); - message->AddExtension(unittest::packed_fixed64_extension_lite , 708); + message->AddExtension(unittest::packed_int32_extension_lite, 701); + message->AddExtension(unittest::packed_int64_extension_lite, 702); + message->AddExtension(unittest::packed_uint32_extension_lite, 703); + message->AddExtension(unittest::packed_uint64_extension_lite, 704); + message->AddExtension(unittest::packed_sint32_extension_lite, 705); + message->AddExtension(unittest::packed_sint64_extension_lite, 706); + message->AddExtension(unittest::packed_fixed32_extension_lite, 707); + message->AddExtension(unittest::packed_fixed64_extension_lite, 708); message->AddExtension(unittest::packed_sfixed32_extension_lite, 709); message->AddExtension(unittest::packed_sfixed64_extension_lite, 710); - message->AddExtension(unittest::packed_float_extension_lite , 711); - message->AddExtension(unittest::packed_double_extension_lite , 712); - message->AddExtension(unittest::packed_bool_extension_lite , false); - message->AddExtension(unittest::packed_enum_extension_lite, unittest::FOREIGN_LITE_BAZ); + message->AddExtension(unittest::packed_float_extension_lite, 711); + message->AddExtension(unittest::packed_double_extension_lite, 712); + message->AddExtension(unittest::packed_bool_extension_lite, false); + message->AddExtension(unittest::packed_enum_extension_lite, + unittest::FOREIGN_LITE_BAZ); } // ------------------------------------------------------------------- void TestUtilLite::ModifyPackedExtensions( unittest::TestPackedExtensionsLite* message) { - message->SetExtension(unittest::packed_int32_extension_lite , 1, 801); - message->SetExtension(unittest::packed_int64_extension_lite , 1, 802); - message->SetExtension(unittest::packed_uint32_extension_lite , 1, 803); - message->SetExtension(unittest::packed_uint64_extension_lite , 1, 804); - message->SetExtension(unittest::packed_sint32_extension_lite , 1, 805); - message->SetExtension(unittest::packed_sint64_extension_lite , 1, 806); - message->SetExtension(unittest::packed_fixed32_extension_lite , 1, 807); - message->SetExtension(unittest::packed_fixed64_extension_lite , 1, 808); + message->SetExtension(unittest::packed_int32_extension_lite, 1, 801); + message->SetExtension(unittest::packed_int64_extension_lite, 1, 802); + message->SetExtension(unittest::packed_uint32_extension_lite, 1, 803); + message->SetExtension(unittest::packed_uint64_extension_lite, 1, 804); + message->SetExtension(unittest::packed_sint32_extension_lite, 1, 805); + message->SetExtension(unittest::packed_sint64_extension_lite, 1, 806); + message->SetExtension(unittest::packed_fixed32_extension_lite, 1, 807); + message->SetExtension(unittest::packed_fixed64_extension_lite, 1, 808); message->SetExtension(unittest::packed_sfixed32_extension_lite, 1, 809); message->SetExtension(unittest::packed_sfixed64_extension_lite, 1, 810); - message->SetExtension(unittest::packed_float_extension_lite , 1, 811); - message->SetExtension(unittest::packed_double_extension_lite , 1, 812); - message->SetExtension(unittest::packed_bool_extension_lite , 1, true); - message->SetExtension(unittest::packed_enum_extension_lite , 1, + message->SetExtension(unittest::packed_float_extension_lite, 1, 811); + message->SetExtension(unittest::packed_double_extension_lite, 1, 812); + message->SetExtension(unittest::packed_bool_extension_lite, 1, true); + message->SetExtension(unittest::packed_enum_extension_lite, 1, unittest::FOREIGN_LITE_FOO); } @@ -1458,49 +1794,75 @@ void TestUtilLite::ModifyPackedExtensions( void TestUtilLite::ExpectPackedExtensionsSet( const unittest::TestPackedExtensionsLite& message) { - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed64_extension_lite )); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int32_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int64_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint32_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint64_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint32_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint64_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed32_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed64_extension_lite)); ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed32_extension_lite)); ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed64_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_float_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_double_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_bool_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_enum_extension_lite )); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_float_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_double_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_bool_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_enum_extension_lite)); - EXPECT_EQ(601 , message.GetExtension(unittest::packed_int32_extension_lite , 0)); - EXPECT_EQ(602 , message.GetExtension(unittest::packed_int64_extension_lite , 0)); - EXPECT_EQ(603 , message.GetExtension(unittest::packed_uint32_extension_lite , 0)); - EXPECT_EQ(604 , message.GetExtension(unittest::packed_uint64_extension_lite , 0)); - EXPECT_EQ(605 , message.GetExtension(unittest::packed_sint32_extension_lite , 0)); - EXPECT_EQ(606 , message.GetExtension(unittest::packed_sint64_extension_lite , 0)); - EXPECT_EQ(607 , message.GetExtension(unittest::packed_fixed32_extension_lite , 0)); - EXPECT_EQ(608 , message.GetExtension(unittest::packed_fixed64_extension_lite , 0)); - EXPECT_EQ(609 , message.GetExtension(unittest::packed_sfixed32_extension_lite, 0)); - EXPECT_EQ(610 , message.GetExtension(unittest::packed_sfixed64_extension_lite, 0)); - EXPECT_EQ(611 , message.GetExtension(unittest::packed_float_extension_lite , 0)); - EXPECT_EQ(612 , message.GetExtension(unittest::packed_double_extension_lite , 0)); - EXPECT_EQ(true , message.GetExtension(unittest::packed_bool_extension_lite , 0)); + EXPECT_EQ(601, + message.GetExtension(unittest::packed_int32_extension_lite, 0)); + EXPECT_EQ(602, + message.GetExtension(unittest::packed_int64_extension_lite, 0)); + EXPECT_EQ(603, + message.GetExtension(unittest::packed_uint32_extension_lite, 0)); + EXPECT_EQ(604, + message.GetExtension(unittest::packed_uint64_extension_lite, 0)); + EXPECT_EQ(605, + message.GetExtension(unittest::packed_sint32_extension_lite, 0)); + EXPECT_EQ(606, + message.GetExtension(unittest::packed_sint64_extension_lite, 0)); + EXPECT_EQ(607, + message.GetExtension(unittest::packed_fixed32_extension_lite, 0)); + EXPECT_EQ(608, + message.GetExtension(unittest::packed_fixed64_extension_lite, 0)); + EXPECT_EQ(609, + message.GetExtension(unittest::packed_sfixed32_extension_lite, 0)); + EXPECT_EQ(610, + message.GetExtension(unittest::packed_sfixed64_extension_lite, 0)); + EXPECT_EQ(611, + message.GetExtension(unittest::packed_float_extension_lite, 0)); + EXPECT_EQ(612, + message.GetExtension(unittest::packed_double_extension_lite, 0)); + EXPECT_EQ(true, + message.GetExtension(unittest::packed_bool_extension_lite, 0)); EXPECT_EQ(unittest::FOREIGN_LITE_BAR, message.GetExtension(unittest::packed_enum_extension_lite, 0)); - EXPECT_EQ(701 , message.GetExtension(unittest::packed_int32_extension_lite , 1)); - EXPECT_EQ(702 , message.GetExtension(unittest::packed_int64_extension_lite , 1)); - EXPECT_EQ(703 , message.GetExtension(unittest::packed_uint32_extension_lite , 1)); - EXPECT_EQ(704 , message.GetExtension(unittest::packed_uint64_extension_lite , 1)); - EXPECT_EQ(705 , message.GetExtension(unittest::packed_sint32_extension_lite , 1)); - EXPECT_EQ(706 , message.GetExtension(unittest::packed_sint64_extension_lite , 1)); - EXPECT_EQ(707 , message.GetExtension(unittest::packed_fixed32_extension_lite , 1)); - EXPECT_EQ(708 , message.GetExtension(unittest::packed_fixed64_extension_lite , 1)); - EXPECT_EQ(709 , message.GetExtension(unittest::packed_sfixed32_extension_lite, 1)); - EXPECT_EQ(710 , message.GetExtension(unittest::packed_sfixed64_extension_lite, 1)); - EXPECT_EQ(711 , message.GetExtension(unittest::packed_float_extension_lite , 1)); - EXPECT_EQ(712 , message.GetExtension(unittest::packed_double_extension_lite , 1)); - EXPECT_EQ(false, message.GetExtension(unittest::packed_bool_extension_lite , 1)); + EXPECT_EQ(701, + message.GetExtension(unittest::packed_int32_extension_lite, 1)); + EXPECT_EQ(702, + message.GetExtension(unittest::packed_int64_extension_lite, 1)); + EXPECT_EQ(703, + message.GetExtension(unittest::packed_uint32_extension_lite, 1)); + EXPECT_EQ(704, + message.GetExtension(unittest::packed_uint64_extension_lite, 1)); + EXPECT_EQ(705, + message.GetExtension(unittest::packed_sint32_extension_lite, 1)); + EXPECT_EQ(706, + message.GetExtension(unittest::packed_sint64_extension_lite, 1)); + EXPECT_EQ(707, + message.GetExtension(unittest::packed_fixed32_extension_lite, 1)); + EXPECT_EQ(708, + message.GetExtension(unittest::packed_fixed64_extension_lite, 1)); + EXPECT_EQ(709, + message.GetExtension(unittest::packed_sfixed32_extension_lite, 1)); + EXPECT_EQ(710, + message.GetExtension(unittest::packed_sfixed64_extension_lite, 1)); + EXPECT_EQ(711, + message.GetExtension(unittest::packed_float_extension_lite, 1)); + EXPECT_EQ(712, + message.GetExtension(unittest::packed_double_extension_lite, 1)); + EXPECT_EQ(false, + message.GetExtension(unittest::packed_bool_extension_lite, 1)); EXPECT_EQ(unittest::FOREIGN_LITE_BAZ, message.GetExtension(unittest::packed_enum_extension_lite, 1)); } @@ -1509,70 +1871,96 @@ void TestUtilLite::ExpectPackedExtensionsSet( void TestUtilLite::ExpectPackedExtensionsClear( const unittest::TestPackedExtensionsLite& message) { - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_int32_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_int64_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_uint32_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_uint64_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sint32_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sint64_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_fixed32_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_fixed64_extension_lite )); + EXPECT_EQ(0, message.ExtensionSize(unittest::packed_int32_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::packed_int64_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::packed_uint32_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::packed_uint64_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sint32_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sint64_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::packed_fixed32_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::packed_fixed64_extension_lite)); EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sfixed32_extension_lite)); EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sfixed64_extension_lite)); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_float_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_double_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_bool_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_enum_extension_lite )); + EXPECT_EQ(0, message.ExtensionSize(unittest::packed_float_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::packed_double_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::packed_bool_extension_lite)); + EXPECT_EQ(0, message.ExtensionSize(unittest::packed_enum_extension_lite)); } // ------------------------------------------------------------------- void TestUtilLite::ExpectPackedExtensionsModified( const unittest::TestPackedExtensionsLite& message) { - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed64_extension_lite )); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int32_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int64_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint32_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint64_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint32_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint64_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed32_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed64_extension_lite)); ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed32_extension_lite)); ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed64_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_float_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_double_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_bool_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_enum_extension_lite )); - EXPECT_EQ(601 , message.GetExtension(unittest::packed_int32_extension_lite , 0)); - EXPECT_EQ(602 , message.GetExtension(unittest::packed_int64_extension_lite , 0)); - EXPECT_EQ(603 , message.GetExtension(unittest::packed_uint32_extension_lite , 0)); - EXPECT_EQ(604 , message.GetExtension(unittest::packed_uint64_extension_lite , 0)); - EXPECT_EQ(605 , message.GetExtension(unittest::packed_sint32_extension_lite , 0)); - EXPECT_EQ(606 , message.GetExtension(unittest::packed_sint64_extension_lite , 0)); - EXPECT_EQ(607 , message.GetExtension(unittest::packed_fixed32_extension_lite , 0)); - EXPECT_EQ(608 , message.GetExtension(unittest::packed_fixed64_extension_lite , 0)); - EXPECT_EQ(609 , message.GetExtension(unittest::packed_sfixed32_extension_lite, 0)); - EXPECT_EQ(610 , message.GetExtension(unittest::packed_sfixed64_extension_lite, 0)); - EXPECT_EQ(611 , message.GetExtension(unittest::packed_float_extension_lite , 0)); - EXPECT_EQ(612 , message.GetExtension(unittest::packed_double_extension_lite , 0)); - EXPECT_EQ(true , message.GetExtension(unittest::packed_bool_extension_lite , 0)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_float_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_double_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_bool_extension_lite)); + ASSERT_EQ(2, message.ExtensionSize(unittest::packed_enum_extension_lite)); + EXPECT_EQ(601, + message.GetExtension(unittest::packed_int32_extension_lite, 0)); + EXPECT_EQ(602, + message.GetExtension(unittest::packed_int64_extension_lite, 0)); + EXPECT_EQ(603, + message.GetExtension(unittest::packed_uint32_extension_lite, 0)); + EXPECT_EQ(604, + message.GetExtension(unittest::packed_uint64_extension_lite, 0)); + EXPECT_EQ(605, + message.GetExtension(unittest::packed_sint32_extension_lite, 0)); + EXPECT_EQ(606, + message.GetExtension(unittest::packed_sint64_extension_lite, 0)); + EXPECT_EQ(607, + message.GetExtension(unittest::packed_fixed32_extension_lite, 0)); + EXPECT_EQ(608, + message.GetExtension(unittest::packed_fixed64_extension_lite, 0)); + EXPECT_EQ(609, + message.GetExtension(unittest::packed_sfixed32_extension_lite, 0)); + EXPECT_EQ(610, + message.GetExtension(unittest::packed_sfixed64_extension_lite, 0)); + EXPECT_EQ(611, + message.GetExtension(unittest::packed_float_extension_lite, 0)); + EXPECT_EQ(612, + message.GetExtension(unittest::packed_double_extension_lite, 0)); + EXPECT_EQ(true, + message.GetExtension(unittest::packed_bool_extension_lite, 0)); EXPECT_EQ(unittest::FOREIGN_LITE_BAR, message.GetExtension(unittest::packed_enum_extension_lite, 0)); // Actually verify the second (modified) elements now. - EXPECT_EQ(801 , message.GetExtension(unittest::packed_int32_extension_lite , 1)); - EXPECT_EQ(802 , message.GetExtension(unittest::packed_int64_extension_lite , 1)); - EXPECT_EQ(803 , message.GetExtension(unittest::packed_uint32_extension_lite , 1)); - EXPECT_EQ(804 , message.GetExtension(unittest::packed_uint64_extension_lite , 1)); - EXPECT_EQ(805 , message.GetExtension(unittest::packed_sint32_extension_lite , 1)); - EXPECT_EQ(806 , message.GetExtension(unittest::packed_sint64_extension_lite , 1)); - EXPECT_EQ(807 , message.GetExtension(unittest::packed_fixed32_extension_lite , 1)); - EXPECT_EQ(808 , message.GetExtension(unittest::packed_fixed64_extension_lite , 1)); - EXPECT_EQ(809 , message.GetExtension(unittest::packed_sfixed32_extension_lite, 1)); - EXPECT_EQ(810 , message.GetExtension(unittest::packed_sfixed64_extension_lite, 1)); - EXPECT_EQ(811 , message.GetExtension(unittest::packed_float_extension_lite , 1)); - EXPECT_EQ(812 , message.GetExtension(unittest::packed_double_extension_lite , 1)); - EXPECT_EQ(true , message.GetExtension(unittest::packed_bool_extension_lite , 1)); + EXPECT_EQ(801, + message.GetExtension(unittest::packed_int32_extension_lite, 1)); + EXPECT_EQ(802, + message.GetExtension(unittest::packed_int64_extension_lite, 1)); + EXPECT_EQ(803, + message.GetExtension(unittest::packed_uint32_extension_lite, 1)); + EXPECT_EQ(804, + message.GetExtension(unittest::packed_uint64_extension_lite, 1)); + EXPECT_EQ(805, + message.GetExtension(unittest::packed_sint32_extension_lite, 1)); + EXPECT_EQ(806, + message.GetExtension(unittest::packed_sint64_extension_lite, 1)); + EXPECT_EQ(807, + message.GetExtension(unittest::packed_fixed32_extension_lite, 1)); + EXPECT_EQ(808, + message.GetExtension(unittest::packed_fixed64_extension_lite, 1)); + EXPECT_EQ(809, + message.GetExtension(unittest::packed_sfixed32_extension_lite, 1)); + EXPECT_EQ(810, + message.GetExtension(unittest::packed_sfixed64_extension_lite, 1)); + EXPECT_EQ(811, + message.GetExtension(unittest::packed_float_extension_lite, 1)); + EXPECT_EQ(812, + message.GetExtension(unittest::packed_double_extension_lite, 1)); + EXPECT_EQ(true, + message.GetExtension(unittest::packed_bool_extension_lite, 1)); EXPECT_EQ(unittest::FOREIGN_LITE_FOO, message.GetExtension(unittest::packed_enum_extension_lite, 1)); } diff --git a/third_party/protobuf/src/google/protobuf/test_util_lite.h b/third_party/protobuf/src/google/protobuf/test_util_lite.h index 47a2269d..34edf944 100644 --- a/third_party/protobuf/src/google/protobuf/test_util_lite.h +++ b/third_party/protobuf/src/google/protobuf/test_util_lite.h @@ -96,6 +96,6 @@ class TestUtilLite { }; } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_TEST_UTIL_LITE_H__ diff --git a/third_party/protobuf/src/google/protobuf/testing/file.cc b/third_party/protobuf/src/google/protobuf/testing/file.cc index 26cb0a67..7d3708e3 100644 --- a/third_party/protobuf/src/google/protobuf/testing/file.cc +++ b/third_party/protobuf/src/google/protobuf/testing/file.cc @@ -45,7 +45,8 @@ #endif #include -#include +#include +#include namespace google { namespace protobuf { @@ -58,20 +59,20 @@ namespace protobuf { #endif #ifdef _WIN32 -using google::protobuf::internal::win32::access; -using google::protobuf::internal::win32::chdir; -using google::protobuf::internal::win32::fopen; -using google::protobuf::internal::win32::mkdir; -using google::protobuf::internal::win32::stat; +using google::protobuf::io::win32::access; +using google::protobuf::io::win32::chdir; +using google::protobuf::io::win32::fopen; +using google::protobuf::io::win32::mkdir; +using google::protobuf::io::win32::stat; #endif bool File::Exists(const string& name) { return access(name.c_str(), F_OK) == 0; } -bool File::ReadFileToString(const string& name, string* output) { +bool File::ReadFileToString(const string& name, string* output, bool text_mode) { char buffer[1024]; - FILE* file = fopen(name.c_str(), "rb"); + FILE* file = fopen(name.c_str(), text_mode ? "rt" : "rb"); if (file == NULL) return false; while (true) { diff --git a/third_party/protobuf/src/google/protobuf/testing/file.h b/third_party/protobuf/src/google/protobuf/testing/file.h index 2f63f80e..45989967 100644 --- a/third_party/protobuf/src/google/protobuf/testing/file.h +++ b/third_party/protobuf/src/google/protobuf/testing/file.h @@ -50,7 +50,7 @@ class File { // Read an entire file to a string. Return true if successful, false // otherwise. - static bool ReadFileToString(const string& name, string* output); + static bool ReadFileToString(const string& name, string* output, bool text_mode = false); // Same as above, but crash on failure. static void ReadFileToStringOrDie(const string& name, string* output); @@ -85,6 +85,11 @@ class File { return ReadFileToString(name, output); } + static bool GetContentsAsText( + const string& name, string* output, bool /*is_default*/) { + return ReadFileToString(name, output, true); + } + static bool SetContents( const string& name, const string& contents, bool /*is_default*/) { return WriteStringToFile(contents, name); diff --git a/third_party/protobuf/src/google/protobuf/testing/googletest.cc b/third_party/protobuf/src/google/protobuf/testing/googletest.cc index 8c89e5af..1856971c 100644 --- a/third_party/protobuf/src/google/protobuf/testing/googletest.cc +++ b/third_party/protobuf/src/google/protobuf/testing/googletest.cc @@ -33,7 +33,7 @@ #include #include -#include +#include #include #include #include @@ -55,11 +55,11 @@ namespace protobuf { #ifdef _WIN32 // DO NOT include , instead create functions in io_win32.{h,cc} and import // them like we do below. -using google::protobuf::internal::win32::close; -using google::protobuf::internal::win32::dup2; -using google::protobuf::internal::win32::dup; -using google::protobuf::internal::win32::mkdir; -using google::protobuf::internal::win32::open; +using google::protobuf::io::win32::close; +using google::protobuf::io::win32::dup2; +using google::protobuf::io::win32::dup; +using google::protobuf::io::win32::mkdir; +using google::protobuf::io::win32::open; #endif #ifndef O_BINARY @@ -86,7 +86,11 @@ string TestSourceDir() { // Look for the "src" directory. string prefix = "."; - while (!File::Exists(prefix + "/src/google/protobuf")) { + // Keep looking further up the directory tree until we find + // src/.../descriptor.cc. It is important to look for a particular file, + // keeping in mind that with Bazel builds the directory structure under + // bazel-bin/ looks similar to the main directory tree in the Git repo. + while (!File::Exists(prefix + "/src/google/protobuf/descriptor.cc")) { if (!File::Exists(prefix)) { GOOGLE_LOG(FATAL) << "Could not find protobuf source code. Please run tests from " @@ -115,7 +119,10 @@ string GetTemporaryDirectoryName() { // testing. We cannot use tmpfile() or mkstemp() since we're creating a // directory. char b[L_tmpnam + 1]; // HPUX multithread return 0 if s is 0 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" string result = tmpnam(b); +#pragma GCC diagnostic pop #ifdef _WIN32 // Avoid a trailing dot by changing it to an underscore. On Win32 the names of // files and directories can, but should not, end with dot. diff --git a/third_party/protobuf/src/google/protobuf/testing/googletest.h b/third_party/protobuf/src/google/protobuf/testing/googletest.h index 81637486..4e0cb83a 100644 --- a/third_party/protobuf/src/google/protobuf/testing/googletest.h +++ b/third_party/protobuf/src/google/protobuf/testing/googletest.h @@ -37,6 +37,7 @@ #include #include #include +#include #include // Disable death tests if we use exceptions in CHECK(). #if !PROTOBUF_USE_EXCEPTIONS && defined(GTEST_HAS_DEATH_TEST) && \ diff --git a/third_party/protobuf/src/google/protobuf/text_format.cc b/third_party/protobuf/src/google/protobuf/text_format.cc index 0965fd7a..801a8e37 100644 --- a/third_party/protobuf/src/google/protobuf/text_format.cc +++ b/third_party/protobuf/src/google/protobuf/text_format.cc @@ -32,54 +32,60 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include +#include + #include #include #include -#include +#include +#include #include #include -#include - #include #include +#include #include #include #include #include #include -#include #include #include +#include +#include #include #include #include #include + #include #include +#include + + namespace google { namespace protobuf { namespace { -inline bool IsHexNumber(const string& str) { +inline bool IsHexNumber(const std::string& str) { return (str.length() >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')); } -inline bool IsOctNumber(const string& str) { +inline bool IsOctNumber(const std::string& str) { return (str.length() >= 2 && str[0] == '0' && (str[1] >= '0' && str[1] < '8')); } } // namespace -string Message::DebugString() const { - string debug_string; +std::string Message::DebugString() const { + std::string debug_string; TextFormat::Printer printer; printer.SetExpandAny(true); @@ -89,8 +95,8 @@ string Message::DebugString() const { return debug_string; } -string Message::ShortDebugString() const { - string debug_string; +std::string Message::ShortDebugString() const { + std::string debug_string; TextFormat::Printer printer; printer.SetSingleLineMode(true); @@ -98,16 +104,15 @@ string Message::ShortDebugString() const { printer.PrintToString(*this, &debug_string); // Single line mode currently might have an extra space at the end. - if (debug_string.size() > 0 && - debug_string[debug_string.size() - 1] == ' ') { + if (debug_string.size() > 0 && debug_string[debug_string.size() - 1] == ' ') { debug_string.resize(debug_string.size() - 1); } return debug_string; } -string Message::Utf8DebugString() const { - string debug_string; +std::string Message::Utf8DebugString() const { + std::string debug_string; TextFormat::Printer printer; printer.SetUseUtf8StringEscaping(true); @@ -118,14 +123,12 @@ string Message::Utf8DebugString() const { return debug_string; } -void Message::PrintDebugString() const { - printf("%s", DebugString().c_str()); -} +void Message::PrintDebugString() const { printf("%s", DebugString().c_str()); } // =========================================================================== // Implementation of the parse information tree class. -TextFormat::ParseInfoTree::ParseInfoTree() { } +TextFormat::ParseInfoTree::ParseInfoTree() {} TextFormat::ParseInfoTree::~ParseInfoTree() { // Remove any nested information trees, as they are owned by this tree. @@ -135,8 +138,7 @@ TextFormat::ParseInfoTree::~ParseInfoTree() { } void TextFormat::ParseInfoTree::RecordLocation( - const FieldDescriptor* field, - TextFormat::ParseLocation location) { + const FieldDescriptor* field, TextFormat::ParseLocation location) { locations_[field].push_back(location); } @@ -151,7 +153,9 @@ TextFormat::ParseInfoTree* TextFormat::ParseInfoTree::CreateNested( } void CheckFieldIndex(const FieldDescriptor* field, int index) { - if (field == NULL) { return; } + if (field == NULL) { + return; + } if (field->is_repeated() && index == -1) { GOOGLE_LOG(DFATAL) << "Index must be in range of repeated field values. " @@ -165,7 +169,9 @@ void CheckFieldIndex(const FieldDescriptor* field, int index) { TextFormat::ParseLocation TextFormat::ParseInfoTree::GetLocation( const FieldDescriptor* field, int index) const { CheckFieldIndex(field, index); - if (index == -1) { index = 0; } + if (index == -1) { + index = 0; + } const std::vector* locations = FindOrNull(locations_, field); @@ -179,7 +185,9 @@ TextFormat::ParseLocation TextFormat::ParseInfoTree::GetLocation( TextFormat::ParseInfoTree* TextFormat::ParseInfoTree::GetTreeForNested( const FieldDescriptor* field, int index) const { CheckFieldIndex(field, index); - if (index == -1) { index = 0; } + if (index == -1) { + index = 0; + } const std::vector* trees = FindOrNull(nested_, field); @@ -194,13 +202,13 @@ namespace { // These functions implement the behavior of the "default" TextFormat::Finder, // they are defined as standalone to be called when finder_ is NULL. const FieldDescriptor* DefaultFinderFindExtension(Message* message, - const string& name) { + const std::string& name) { return message->GetReflection()->FindKnownExtensionByName(name); } const Descriptor* DefaultFinderFindAnyType(const Message& message, - const string& prefix, - const string& name) { + const std::string& prefix, + const std::string& name) { if (prefix != internal::kTypeGoogleApisComPrefix && prefix != internal::kTypeGoogleProdComPrefix) { return NULL; @@ -212,18 +220,21 @@ const Descriptor* DefaultFinderFindAnyType(const Message& message, // =========================================================================== // Internal class for parsing an ASCII representation of a Protocol Message. // This class makes use of the Protocol Message compiler's tokenizer found -// in //google/protobuf/io/tokenizer.h. Note that class's Parse +// in //net/proto2/io/public/tokenizer.h. Note that class's Parse // method is *not* thread-safe and should only be used in a single thread at // a time. // Makes code slightly more readable. The meaning of "DO(foo)" is // "Execute foo and fail if it fails.", where failure is indicated by // returning false. Borrowed from parser.cc (Thanks Kenton!). -#define DO(STATEMENT) if (STATEMENT) {} else return false +#define DO(STATEMENT) \ + if (STATEMENT) { \ + } else { \ + return false; \ + } class TextFormat::Parser::ParserImpl { public: - // Determines if repeated values for non-repeated fields and // oneofs are permitted, e.g., the string "foo: 1 foo: 2" for a // required/optional field named "foo", or "baz: 1 qux: 2" @@ -236,28 +247,27 @@ class TextFormat::Parser::ParserImpl { ParserImpl(const Descriptor* root_message_type, io::ZeroCopyInputStream* input_stream, io::ErrorCollector* error_collector, - const TextFormat::Finder* finder, - ParseInfoTree* parse_info_tree, + const TextFormat::Finder* finder, ParseInfoTree* parse_info_tree, SingularOverwritePolicy singular_overwrite_policy, - bool allow_case_insensitive_field, - bool allow_unknown_field, - bool allow_unknown_enum, - bool allow_field_number, - bool allow_relaxed_whitespace, - bool allow_partial) - : error_collector_(error_collector), - finder_(finder), - parse_info_tree_(parse_info_tree), - tokenizer_error_collector_(this), - tokenizer_(input_stream, &tokenizer_error_collector_), - root_message_type_(root_message_type), - singular_overwrite_policy_(singular_overwrite_policy), - allow_case_insensitive_field_(allow_case_insensitive_field), - allow_unknown_field_(allow_unknown_field), - allow_unknown_enum_(allow_unknown_enum), - allow_field_number_(allow_field_number), - allow_partial_(allow_partial), - had_errors_(false) { + bool allow_case_insensitive_field, bool allow_unknown_field, + bool allow_unknown_extension, bool allow_unknown_enum, + bool allow_field_number, bool allow_relaxed_whitespace, + bool allow_partial, int recursion_limit) + : error_collector_(error_collector), + finder_(finder), + parse_info_tree_(parse_info_tree), + tokenizer_error_collector_(this), + tokenizer_(input_stream, &tokenizer_error_collector_), + root_message_type_(root_message_type), + singular_overwrite_policy_(singular_overwrite_policy), + allow_case_insensitive_field_(allow_case_insensitive_field), + allow_unknown_field_(allow_unknown_field), + allow_unknown_extension_(allow_unknown_extension), + allow_unknown_enum_(allow_unknown_enum), + allow_field_number_(allow_field_number), + allow_partial_(allow_partial), + recursion_limit_(recursion_limit), + had_errors_(false) { // For backwards-compatibility with proto1, we need to allow the 'f' suffix // for floats. tokenizer_.set_allow_f_after_float(true); @@ -273,7 +283,7 @@ class TextFormat::Parser::ParserImpl { // Consume the starting token. tokenizer_.Next(); } - ~ParserImpl() { } + ~ParserImpl() {} // Parses the ASCII representation specified in input and saves the // information into the output pointer (a Message). Returns @@ -300,35 +310,31 @@ class TextFormat::Parser::ParserImpl { return suc && LookingAtType(io::Tokenizer::TYPE_END); } - void ReportError(int line, int col, const string& message) { + void ReportError(int line, int col, const std::string& message) { had_errors_ = true; if (error_collector_ == NULL) { if (line >= 0) { GOOGLE_LOG(ERROR) << "Error parsing text-format " - << root_message_type_->full_name() - << ": " << (line + 1) << ":" - << (col + 1) << ": " << message; + << root_message_type_->full_name() << ": " << (line + 1) + << ":" << (col + 1) << ": " << message; } else { GOOGLE_LOG(ERROR) << "Error parsing text-format " - << root_message_type_->full_name() - << ": " << message; + << root_message_type_->full_name() << ": " << message; } } else { error_collector_->AddError(line, col, message); } } - void ReportWarning(int line, int col, const string& message) { + void ReportWarning(int line, int col, const std::string& message) { if (error_collector_ == NULL) { if (line >= 0) { GOOGLE_LOG(WARNING) << "Warning parsing text-format " - << root_message_type_->full_name() - << ": " << (line + 1) << ":" - << (col + 1) << ": " << message; + << root_message_type_->full_name() << ": " << (line + 1) + << ":" << (col + 1) << ": " << message; } else { GOOGLE_LOG(WARNING) << "Warning parsing text-format " - << root_message_type_->full_name() - << ": " << message; + << root_message_type_->full_name() << ": " << message; } } else { error_collector_->AddWarning(line, col, message); @@ -340,14 +346,14 @@ class TextFormat::Parser::ParserImpl { // Reports an error with the given message with information indicating // the position (as derived from the current token). - void ReportError(const string& message) { + void ReportError(const std::string& message) { ReportError(tokenizer_.current().line, tokenizer_.current().column, message); } // Reports a warning with the given message with information indicating // the position (as derived from the current token). - void ReportWarning(const string& message) { + void ReportWarning(const std::string& message) { ReportWarning(tokenizer_.current().line, tokenizer_.current().column, message); } @@ -355,8 +361,8 @@ class TextFormat::Parser::ParserImpl { // Consumes the specified message with the given starting delimiter. // This method checks to see that the end delimiter at the conclusion of // the consumption matches the starting delimiter passed in here. - bool ConsumeMessage(Message* message, const string delimiter) { - while (!LookingAt(">") && !LookingAt("}")) { + bool ConsumeMessage(Message* message, const std::string delimiter) { + while (!LookingAt(">") && !LookingAt("}")) { DO(ConsumeField(message)); } @@ -366,7 +372,7 @@ class TextFormat::Parser::ParserImpl { } // Consume either "<" or "{". - bool ConsumeMessageDelimiter(string* delimiter) { + bool ConsumeMessageDelimiter(std::string* delimiter) { if (TryConsume("<")) { *delimiter = ">"; } else { @@ -383,7 +389,7 @@ class TextFormat::Parser::ParserImpl { const Reflection* reflection = message->GetReflection(); const Descriptor* descriptor = message->GetDescriptor(); - string field_name; + std::string field_name; bool reserved_field = false; const FieldDescriptor* field = NULL; int start_line = tokenizer_.current().line; @@ -394,11 +400,11 @@ class TextFormat::Parser::ParserImpl { if (internal::GetAnyFieldDescriptors(*message, &any_type_url_field, &any_value_field) && TryConsume("[")) { - string full_type_name, prefix; + std::string full_type_name, prefix; DO(ConsumeAnyTypeUrl(&full_type_name, &prefix)); DO(Consume("]")); TryConsume(":"); // ':' is optional between message labels and values. - string serialized_value; + std::string serialized_value; const Descriptor* value_descriptor = finder_ ? finder_->FindAnyType(*message, prefix, full_type_name) : DefaultFinderFindAnyType(*message, prefix, full_type_name); @@ -418,9 +424,8 @@ class TextFormat::Parser::ParserImpl { return false; } } - reflection->SetString( - message, any_type_url_field, - string(prefix + full_type_name)); + reflection->SetString(message, any_type_url_field, + std::string(prefix + full_type_name)); reflection->SetString(message, any_value_field, serialized_value); return true; } @@ -433,14 +438,15 @@ class TextFormat::Parser::ParserImpl { : DefaultFinderFindExtension(message, field_name); if (field == NULL) { - if (!allow_unknown_field_) { - ReportError("Extension \"" + field_name + "\" is not defined or " + if (!allow_unknown_field_ && !allow_unknown_extension_) { + ReportError("Extension \"" + field_name + + "\" is not defined or " "is not an extension of \"" + descriptor->full_name() + "\"."); return false; } else { - ReportWarning("Extension \"" + field_name + "\" is not defined or " - "is not an extension of \"" + + ReportWarning("Ignoring extension \"" + field_name + + "\" which is not defined or is not an extension of \"" + descriptor->full_name() + "\"."); } } @@ -448,7 +454,8 @@ class TextFormat::Parser::ParserImpl { DO(ConsumeIdentifier(&field_name)); int32 field_number; - if (allow_field_number_ && safe_strto32(field_name, &field_number)) { + if (allow_field_number_ && + safe_strto32(field_name, &field_number)) { if (descriptor->IsExtensionNumber(field_number)) { field = reflection->FindKnownExtensionByNumber(field_number); } else if (descriptor->IsReservedNumber(field_number)) { @@ -462,7 +469,7 @@ class TextFormat::Parser::ParserImpl { // .proto file, which actually matches their type names, not their // field names. if (field == NULL) { - string lower_field_name = field_name; + std::string lower_field_name = field_name; LowerString(&lower_field_name); field = descriptor->FindFieldByName(lower_field_name); // If the case-insensitive match worked but the field is NOT a group, @@ -471,13 +478,13 @@ class TextFormat::Parser::ParserImpl { } } // Again, special-case group names as described above. - if (field != NULL && field->type() == FieldDescriptor::TYPE_GROUP - && field->message_type()->name() != field_name) { + if (field != NULL && field->type() == FieldDescriptor::TYPE_GROUP && + field->message_type()->name() != field_name) { field = NULL; } if (field == NULL && allow_case_insensitive_field_) { - string lower_field_name = field_name; + std::string lower_field_name = field_name; LowerString(&lower_field_name); field = descriptor->FindFieldByLowercaseName(lower_field_name); } @@ -501,7 +508,7 @@ class TextFormat::Parser::ParserImpl { // Skips unknown or reserved fields. if (field == NULL) { - GOOGLE_CHECK(allow_unknown_field_ || reserved_field); + GOOGLE_CHECK(allow_unknown_field_ || allow_unknown_extension_ || reserved_field); // Try to guess the type of this field. // If this field is not a message, there should be a ":" between the @@ -529,9 +536,13 @@ class TextFormat::Parser::ParserImpl { if (oneof != NULL && reflection->HasOneof(*message, oneof)) { const FieldDescriptor* other_field = reflection->GetOneofFieldDescriptor(*message, oneof); - ReportError("Field \"" + field_name + "\" is specified along with " - "field \"" + other_field->name() + "\", another member " - "of oneof \"" + oneof->name() + "\"."); + ReportError("Field \"" + field_name + + "\" is specified along with " + "field \"" + + other_field->name() + + "\", another member " + "of oneof \"" + + oneof->name() + "\"."); return false; } } @@ -540,11 +551,15 @@ class TextFormat::Parser::ParserImpl { if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { // ':' is optional here. bool consumed_semicolon = TryConsume(":"); - if (consumed_semicolon && field->options().weak() && LookingAtType(io::Tokenizer::TYPE_STRING)) { + if (consumed_semicolon && field->options().weak() && + LookingAtType(io::Tokenizer::TYPE_STRING)) { // we are getting a bytes string for a weak field. - string tmp; + std::string tmp; DO(ConsumeString(&tmp)); - reflection->MutableMessage(message, field)->ParseFromString(tmp); + MessageFactory* factory = + finder_ ? finder_->FindExtensionFactory(field) : nullptr; + reflection->MutableMessage(message, field, factory) + ->ParseFromString(tmp); goto label_skip_parsing; } } else { @@ -574,14 +589,14 @@ class TextFormat::Parser::ParserImpl { } else { DO(ConsumeFieldValue(message, reflection, field)); } -label_skip_parsing: + label_skip_parsing: // For historical reasons, fields may optionally be separated by commas or // semicolons. TryConsume(";") || TryConsume(","); if (field->options().deprecated()) { - ReportWarning("text format contains deprecated field \"" - + field_name + "\""); + ReportWarning("text format contains deprecated field \"" + field_name + + "\""); } // If a parse info tree exists, add the location for the parsed @@ -601,7 +616,7 @@ label_skip_parsing: DO(ConsumeTypeUrlOrFullTypeName()); DO(Consume("]")); } else { - string field_name; + std::string field_name; DO(ConsumeIdentifier(&field_name)); } @@ -622,10 +637,12 @@ label_skip_parsing: return true; } - bool ConsumeFieldMessage(Message* message, - const Reflection* reflection, + bool ConsumeFieldMessage(Message* message, const Reflection* reflection, const FieldDescriptor* field) { - + if (--recursion_limit_ < 0) { + ReportError("Message is too deep"); + return false; + } // If the parse information tree is not NULL, create a nested one // for the nested message. ParseInfoTree* parent = parse_info_tree_; @@ -633,15 +650,20 @@ label_skip_parsing: parse_info_tree_ = CreateNested(parent, field); } - string delimiter; + std::string delimiter; DO(ConsumeMessageDelimiter(&delimiter)); + MessageFactory* factory = + finder_ ? finder_->FindExtensionFactory(field) : nullptr; if (field->is_repeated()) { - DO(ConsumeMessage(reflection->AddMessage(message, field), delimiter)); + DO(ConsumeMessage(reflection->AddMessage(message, field, factory), + delimiter)); } else { - DO(ConsumeMessage(reflection->MutableMessage(message, field), + DO(ConsumeMessage(reflection->MutableMessage(message, field, factory), delimiter)); } + ++recursion_limit_; + // Reset the parse information tree. parse_info_tree_ = parent; return true; @@ -650,30 +672,28 @@ label_skip_parsing: // Skips the whole body of a message including the beginning delimiter and // the ending delimiter. bool SkipFieldMessage() { - string delimiter; + std::string delimiter; DO(ConsumeMessageDelimiter(&delimiter)); - while (!LookingAt(">") && !LookingAt("}")) { + while (!LookingAt(">") && !LookingAt("}")) { DO(SkipField()); } DO(Consume(delimiter)); return true; } - bool ConsumeFieldValue(Message* message, - const Reflection* reflection, + bool ConsumeFieldValue(Message* message, const Reflection* reflection, const FieldDescriptor* field) { - // Define an easy to use macro for setting fields. This macro checks // to see if the field is repeated (in which case we need to use the Add // methods or not (in which case we need to use the Set methods). -#define SET_FIELD(CPPTYPE, VALUE) \ - if (field->is_repeated()) { \ - reflection->Add##CPPTYPE(message, field, VALUE); \ - } else { \ - reflection->Set##CPPTYPE(message, field, VALUE); \ - } \ +#define SET_FIELD(CPPTYPE, VALUE) \ + if (field->is_repeated()) { \ + reflection->Add##CPPTYPE(message, field, VALUE); \ + } else { \ + reflection->Set##CPPTYPE(message, field, VALUE); \ + } - switch(field->cpp_type()) { + switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_INT32: { int64 value; DO(ConsumeSignedInteger(&value, kint32max)); @@ -717,7 +737,7 @@ label_skip_parsing: } case FieldDescriptor::CPPTYPE_STRING: { - string value; + std::string value; DO(ConsumeString(&value)); SET_FIELD(String, value); break; @@ -729,15 +749,15 @@ label_skip_parsing: DO(ConsumeUnsignedInteger(&value, 1)); SET_FIELD(Bool, value); } else { - string value; + std::string value; DO(ConsumeIdentifier(&value)); if (value == "true" || value == "True" || value == "t") { SET_FIELD(Bool, true); } else if (value == "false" || value == "False" || value == "f") { SET_FIELD(Bool, false); } else { - ReportError("Invalid value for boolean field \"" + field->name() - + "\". Value: \"" + value + "\"."); + ReportError("Invalid value for boolean field \"" + field->name() + + "\". Value: \"" + value + "\"."); return false; } } @@ -745,7 +765,8 @@ label_skip_parsing: } case FieldDescriptor::CPPTYPE_ENUM: { - string value; + std::string value; + int64 int_value = kint64max; const EnumDescriptor* enum_type = field->enum_type(); const EnumValueDescriptor* enum_value = NULL; @@ -756,9 +777,8 @@ label_skip_parsing: } else if (LookingAt("-") || LookingAtType(io::Tokenizer::TYPE_INTEGER)) { - int64 int_value; DO(ConsumeSignedInteger(&int_value, kint32max)); - value = SimpleItoa(int_value); // for error reporting + value = StrCat(int_value); // for error reporting enum_value = enum_type->FindValueByNumber(int_value); } else { ReportError("Expected integer or identifier, got: " + @@ -767,13 +787,21 @@ label_skip_parsing: } if (enum_value == NULL) { - if (!allow_unknown_enum_) { - ReportError("Unknown enumeration value of \"" + value + "\" for " - "field \"" + field->name() + "\"."); + if (int_value != kint64max && + reflection->SupportsUnknownEnumValues()) { + SET_FIELD(EnumValue, int_value); + return true; + } else if (!allow_unknown_enum_) { + ReportError("Unknown enumeration value of \"" + value + + "\" for " + "field \"" + + field->name() + "\"."); return false; } else { - ReportWarning("Unknown enumeration value of \"" + value + "\" for " - "field \"" + field->name() + "\"."); + ReportWarning("Unknown enumeration value of \"" + value + + "\" for " + "field \"" + + field->name() + "\"."); return true; } } @@ -839,6 +867,8 @@ label_skip_parsing: if (!LookingAtType(io::Tokenizer::TYPE_INTEGER) && !LookingAtType(io::Tokenizer::TYPE_FLOAT) && !LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) { + std::string text = tokenizer_.current().text; + ReportError("Cannot skip field value, unexpected token: " + text); return false; } // Combination of '-' and TYPE_IDENTIFIER may result in an invalid field @@ -848,11 +878,10 @@ label_skip_parsing: // below: // inf, inff, infinity, nan if (has_minus && LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) { - string text = tokenizer_.current().text; + std::string text = tokenizer_.current().text; LowerString(&text); if (text != "inf" && - text != "infinity" && - text != "nan") { + text != "infinity" && text != "nan") { ReportError("Invalid float number: " + text); return false; } @@ -862,7 +891,7 @@ label_skip_parsing: } // Returns true if the current token's text is equal to that specified. - bool LookingAt(const string& text) { + bool LookingAt(const std::string& text) { return tokenizer_.current().text == text; } @@ -873,7 +902,7 @@ label_skip_parsing: // Consumes an identifier and saves its value in the identifier parameter. // Returns false if the token is not of type IDENTFIER. - bool ConsumeIdentifier(string* identifier) { + bool ConsumeIdentifier(std::string* identifier) { if (LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) { *identifier = tokenizer_.current().text; tokenizer_.Next(); @@ -882,8 +911,9 @@ label_skip_parsing: // If allow_field_numer_ or allow_unknown_field_ is true, we should able // to parse integer identifiers. - if ((allow_field_number_ || allow_unknown_field_) - && LookingAtType(io::Tokenizer::TYPE_INTEGER)) { + if ((allow_field_number_ || allow_unknown_field_ || + allow_unknown_extension_) && + LookingAtType(io::Tokenizer::TYPE_INTEGER)) { *identifier = tokenizer_.current().text; tokenizer_.Next(); return true; @@ -894,10 +924,10 @@ label_skip_parsing: } // Consume a string of form ".....". - bool ConsumeFullTypeName(string* name) { + bool ConsumeFullTypeName(std::string* name) { DO(ConsumeIdentifier(name)); while (TryConsume(".")) { - string part; + std::string part; DO(ConsumeIdentifier(&part)); *name += "."; *name += part; @@ -906,7 +936,7 @@ label_skip_parsing: } bool ConsumeTypeUrlOrFullTypeName() { - string discarded; + std::string discarded; DO(ConsumeIdentifier(&discarded)); while (TryConsume(".") || TryConsume("/")) { DO(ConsumeIdentifier(&discarded)); @@ -916,7 +946,7 @@ label_skip_parsing: // Consumes a string and saves its value in the text parameter. // Returns false if the token is not of type STRING. - bool ConsumeString(string* text) { + bool ConsumeString(std::string* text) { if (!LookingAtType(io::Tokenizer::TYPE_STRING)) { ReportError("Expected string, got: " + tokenizer_.current().text); return false; @@ -940,8 +970,8 @@ label_skip_parsing: return false; } - if (!io::Tokenizer::ParseInteger(tokenizer_.current().text, - max_value, value)) { + if (!io::Tokenizer::ParseInteger(tokenizer_.current().text, max_value, + value)) { ReportError("Integer out of range (" + tokenizer_.current().text + ")"); return false; } @@ -982,23 +1012,26 @@ label_skip_parsing: return true; } - // Consumes a uint64 and saves its value in the value parameter. + // Consumes a double and saves its value in the value parameter. // Accepts decimal numbers only, rejects hex or oct numbers. - bool ConsumeUnsignedDecimalInteger(uint64* value, uint64 max_value) { + bool ConsumeUnsignedDecimalAsDouble(double* value, uint64 max_value) { if (!LookingAtType(io::Tokenizer::TYPE_INTEGER)) { ReportError("Expected integer, got: " + tokenizer_.current().text); return false; } - const string& text = tokenizer_.current().text; + const std::string& text = tokenizer_.current().text; if (IsHexNumber(text) || IsOctNumber(text)) { ReportError("Expect a decimal number, got: " + text); return false; } - if (!io::Tokenizer::ParseInteger(text, max_value, value)) { - ReportError("Integer out of range (" + text + ")"); - return false; + uint64 uint64_value; + if (io::Tokenizer::ParseInteger(text, max_value, &uint64_value)) { + *value = static_cast(uint64_value); + } else { + // Uint64 overflow, attempt to parse as a double instead. + *value = io::Tokenizer::ParseFloat(text); } tokenizer_.Next(); @@ -1021,10 +1054,7 @@ label_skip_parsing: // Therefore, we must check both cases here. if (LookingAtType(io::Tokenizer::TYPE_INTEGER)) { // We have found an integer value for the double. - uint64 integer_value; - DO(ConsumeUnsignedDecimalInteger(&integer_value, kuint64max)); - - *value = static_cast(integer_value); + DO(ConsumeUnsignedDecimalAsDouble(value, kuint64max)); } else if (LookingAtType(io::Tokenizer::TYPE_FLOAT)) { // We have found a float value for the double. *value = io::Tokenizer::ParseFloat(tokenizer_.current().text); @@ -1032,7 +1062,7 @@ label_skip_parsing: // Mark the current token as consumed. tokenizer_.Next(); } else if (LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) { - string text = tokenizer_.current().text; + std::string text = tokenizer_.current().text; LowerString(&text); if (text == "inf" || text == "infinity") { @@ -1059,12 +1089,12 @@ label_skip_parsing: // Consumes Any::type_url value, of form "type.googleapis.com/full.type.Name" // or "type.googleprod.com/full.type.Name" - bool ConsumeAnyTypeUrl(string* full_type_name, string* prefix) { + bool ConsumeAnyTypeUrl(std::string* full_type_name, std::string* prefix) { // TODO(saito) Extend Consume() to consume multiple tokens at once, so that // this code can be written as just DO(Consume(kGoogleApisTypePrefix)). DO(ConsumeIdentifier(prefix)); while (TryConsume(".")) { - string url; + std::string url; DO(ConsumeIdentifier(&url)); *prefix += "." + url; } @@ -1078,14 +1108,14 @@ label_skip_parsing: // A helper function for reconstructing Any::value. Consumes a text of // full_type_name, then serializes it into serialized_value. bool ConsumeAnyValue(const Descriptor* value_descriptor, - string* serialized_value) { + std::string* serialized_value) { DynamicMessageFactory factory; const Message* value_prototype = factory.GetPrototype(value_descriptor); if (value_prototype == NULL) { return false; } std::unique_ptr value(value_prototype->New()); - string sub_delimiter; + std::string sub_delimiter; DO(ConsumeMessageDelimiter(&sub_delimiter)); DO(ConsumeMessage(value.get(), sub_delimiter)); @@ -1106,12 +1136,12 @@ label_skip_parsing: // Consumes a token and confirms that it matches that specified in the // value parameter. Returns false if the token found does not match that // which was specified. - bool Consume(const string& value) { - const string& current_value = tokenizer_.current().text; + bool Consume(const std::string& value) { + const std::string& current_value = tokenizer_.current().text; if (current_value != value) { - ReportError("Expected \"" + value + "\", found \"" + current_value - + "\"."); + ReportError("Expected \"" + value + "\", found \"" + current_value + + "\"."); return false; } @@ -1122,7 +1152,7 @@ label_skip_parsing: // Attempts to consume the supplied value. Returns false if a the // token found does not match the value specified. - bool TryConsume(const string& value) { + bool TryConsume(const std::string& value) { if (tokenizer_.current().text == value) { tokenizer_.Next(); return true; @@ -1135,16 +1165,16 @@ label_skip_parsing: // collect any base-level parse errors and feed them to the ParserImpl. class ParserErrorCollector : public io::ErrorCollector { public: - explicit ParserErrorCollector(TextFormat::Parser::ParserImpl* parser) : - parser_(parser) { } + explicit ParserErrorCollector(TextFormat::Parser::ParserImpl* parser) + : parser_(parser) {} - virtual ~ParserErrorCollector() { } + ~ParserErrorCollector() override {} - virtual void AddError(int line, int column, const string& message) { + void AddError(int line, int column, const std::string& message) override { parser_->ReportError(line, column, message); } - virtual void AddWarning(int line, int column, const string& message) { + void AddWarning(int line, int column, const std::string& message) override { parser_->ReportWarning(line, column, message); } @@ -1162,30 +1192,29 @@ label_skip_parsing: SingularOverwritePolicy singular_overwrite_policy_; const bool allow_case_insensitive_field_; const bool allow_unknown_field_; + const bool allow_unknown_extension_; const bool allow_unknown_enum_; const bool allow_field_number_; const bool allow_partial_; + int recursion_limit_; bool had_errors_; }; -#undef DO - // =========================================================================== // Internal class for writing text to the io::ZeroCopyOutputStream. Adapted -// from the Printer found in //google/protobuf/io/printer.h +// from the Printer found in //net/proto2/io/public/printer.h class TextFormat::Printer::TextGenerator : public TextFormat::BaseTextGenerator { public: explicit TextGenerator(io::ZeroCopyOutputStream* output, int initial_indent_level) - : output_(output), - buffer_(NULL), - buffer_size_(0), - at_start_of_line_(true), - failed_(false), - indent_level_(initial_indent_level), - initial_indent_level_(initial_indent_level) { - } + : output_(output), + buffer_(NULL), + buffer_size_(0), + at_start_of_line_(true), + failed_(false), + indent_level_(initial_indent_level), + initial_indent_level_(initial_indent_level) {} ~TextGenerator() { // Only BackUp() if we're sure we've successfully called Next() at least @@ -1203,8 +1232,7 @@ class TextFormat::Printer::TextGenerator // Reduces the current indent level by two spaces, or crashes if the indent // level is zero. void Outdent() override { - if (indent_level_ == 0 || - indent_level_ < initial_indent_level_) { + if (indent_level_ == 0 || indent_level_ < initial_indent_level_) { GOOGLE_LOG(DFATAL) << " Outdent() without matching Indent()."; return; } @@ -1278,14 +1306,18 @@ class TextFormat::Printer::TextGenerator } void WriteIndent() { - if (indent_level_ == 0) { return; } + if (indent_level_ == 0) { + return; + } GOOGLE_DCHECK(!failed_); int size = 2 * indent_level_; while (size > buffer_size_) { // Data exceeds space in the buffer. Write what we can and request a new // buffer. - memset(buffer_, ' ', buffer_size_); + if (buffer_size_ > 0) { + memset(buffer_, ' ', buffer_size_); + } size -= buffer_size_; void* void_buffer; failed_ = !output_->Next(&void_buffer, &buffer_size_); @@ -1311,57 +1343,78 @@ class TextFormat::Printer::TextGenerator // =========================================================================== // Implementation of the default Finder for extensions. -TextFormat::Finder::~Finder() { -} +TextFormat::Finder::~Finder() {} const FieldDescriptor* TextFormat::Finder::FindExtension( - Message* message, const string& name) const { + Message* message, const std::string& name) const { return DefaultFinderFindExtension(message, name); } -const Descriptor* TextFormat::Finder::FindAnyType(const Message& message, - const string& prefix, - const string& name) const { +const Descriptor* TextFormat::Finder::FindAnyType( + const Message& message, const std::string& prefix, + const std::string& name) const { return DefaultFinderFindAnyType(message, prefix, name); } +MessageFactory* TextFormat::Finder::FindExtensionFactory( + const FieldDescriptor* field) const { + return nullptr; +} + // =========================================================================== TextFormat::Parser::Parser() - : error_collector_(NULL), - finder_(NULL), - parse_info_tree_(NULL), - allow_partial_(false), - allow_case_insensitive_field_(false), - allow_unknown_field_(false), - allow_unknown_enum_(false), - allow_field_number_(false), - allow_relaxed_whitespace_(false), - allow_singular_overwrites_(false) { -} + : error_collector_(NULL), + finder_(NULL), + parse_info_tree_(NULL), + allow_partial_(false), + allow_case_insensitive_field_(false), + allow_unknown_field_(false), + allow_unknown_extension_(false), + allow_unknown_enum_(false), + allow_field_number_(false), + allow_relaxed_whitespace_(false), + allow_singular_overwrites_(false), + recursion_limit_(std::numeric_limits::max()) {} TextFormat::Parser::~Parser() {} +namespace { + +bool CheckParseInputSize(StringPiece input, + io::ErrorCollector* error_collector) { + if (input.size() > INT_MAX) { + error_collector->AddError( + -1, 0, + StrCat("Input size too large: ", static_cast(input.size()), + " bytes", " > ", INT_MAX, " bytes.")); + return false; + } + return true; +} + +} // namespace + bool TextFormat::Parser::Parse(io::ZeroCopyInputStream* input, Message* output) { output->Clear(); ParserImpl::SingularOverwritePolicy overwrites_policy = - allow_singular_overwrites_ - ? ParserImpl::ALLOW_SINGULAR_OVERWRITES - : ParserImpl::FORBID_SINGULAR_OVERWRITES; + allow_singular_overwrites_ ? ParserImpl::ALLOW_SINGULAR_OVERWRITES + : ParserImpl::FORBID_SINGULAR_OVERWRITES; - ParserImpl parser(output->GetDescriptor(), input, error_collector_, - finder_, parse_info_tree_, - overwrites_policy, + ParserImpl parser(output->GetDescriptor(), input, error_collector_, finder_, + parse_info_tree_, overwrites_policy, allow_case_insensitive_field_, allow_unknown_field_, - allow_unknown_enum_, allow_field_number_, - allow_relaxed_whitespace_, allow_partial_); + allow_unknown_extension_, allow_unknown_enum_, + allow_field_number_, allow_relaxed_whitespace_, + allow_partial_, recursion_limit_); return MergeUsingImpl(input, output, &parser); } -bool TextFormat::Parser::ParseFromString(const string& input, +bool TextFormat::Parser::ParseFromString(const std::string& input, Message* output) { + DO(CheckParseInputSize(input, error_collector_)); io::ArrayInputStream input_stream(input.data(), input.size()); return Parse(&input_stream, output); } @@ -1369,17 +1422,18 @@ bool TextFormat::Parser::ParseFromString(const string& input, bool TextFormat::Parser::Merge(io::ZeroCopyInputStream* input, Message* output) { - ParserImpl parser(output->GetDescriptor(), input, error_collector_, - finder_, parse_info_tree_, - ParserImpl::ALLOW_SINGULAR_OVERWRITES, + ParserImpl parser(output->GetDescriptor(), input, error_collector_, finder_, + parse_info_tree_, ParserImpl::ALLOW_SINGULAR_OVERWRITES, allow_case_insensitive_field_, allow_unknown_field_, - allow_unknown_enum_, allow_field_number_, - allow_relaxed_whitespace_, allow_partial_); + allow_unknown_extension_, allow_unknown_enum_, + allow_field_number_, allow_relaxed_whitespace_, + allow_partial_, recursion_limit_); return MergeUsingImpl(input, output, &parser); } -bool TextFormat::Parser::MergeFromString(const string& input, +bool TextFormat::Parser::MergeFromString(const std::string& input, Message* output) { + DO(CheckParseInputSize(input, error_collector_)); io::ArrayInputStream input_stream(input.data(), input.size()); return Merge(&input_stream, output); } @@ -1390,7 +1444,7 @@ bool TextFormat::Parser::MergeUsingImpl(io::ZeroCopyInputStream* /* input */, ParserImpl* parser_impl) { if (!parser_impl->Parse(output)) return false; if (!allow_partial_ && !output->IsInitialized()) { - std::vector missing_fields; + std::vector missing_fields; output->FindInitializationErrors(&missing_fields); parser_impl->ReportError(-1, 0, "Message missing required fields: " + @@ -1400,17 +1454,16 @@ bool TextFormat::Parser::MergeUsingImpl(io::ZeroCopyInputStream* /* input */, return true; } -bool TextFormat::Parser::ParseFieldValueFromString( - const string& input, - const FieldDescriptor* field, - Message* output) { +bool TextFormat::Parser::ParseFieldValueFromString(const std::string& input, + const FieldDescriptor* field, + Message* output) { io::ArrayInputStream input_stream(input.data(), input.size()); - ParserImpl parser(output->GetDescriptor(), &input_stream, error_collector_, - finder_, parse_info_tree_, - ParserImpl::ALLOW_SINGULAR_OVERWRITES, - allow_case_insensitive_field_, allow_unknown_field_, - allow_unknown_enum_, allow_field_number_, - allow_relaxed_whitespace_, allow_partial_); + ParserImpl parser( + output->GetDescriptor(), &input_stream, error_collector_, finder_, + parse_info_tree_, ParserImpl::ALLOW_SINGULAR_OVERWRITES, + allow_case_insensitive_field_, allow_unknown_field_, + allow_unknown_extension_, allow_unknown_enum_, allow_field_number_, + allow_relaxed_whitespace_, allow_partial_, recursion_limit_); return parser.ParseField(field, output); } @@ -1424,17 +1477,19 @@ bool TextFormat::Parser::ParseFieldValueFromString( return Parser().Merge(input, output); } -/* static */ bool TextFormat::ParseFromString(const string& input, +/* static */ bool TextFormat::ParseFromString(const std::string& input, Message* output) { return Parser().ParseFromString(input, output); } -/* static */ bool TextFormat::MergeFromString(const string& input, +/* static */ bool TextFormat::MergeFromString(const std::string& input, Message* output) { return Parser().MergeFromString(input, output); } +#undef DO + // =========================================================================== TextFormat::BaseTextGenerator::~BaseTextGenerator() {} @@ -1444,18 +1499,20 @@ namespace { // A BaseTextGenerator that writes to a string. class StringBaseTextGenerator : public TextFormat::BaseTextGenerator { public: - void Print(const char* text, size_t size) { output_.append(text, size); } + void Print(const char* text, size_t size) override { + output_.append(text, size); + } // Some compilers do not support ref-qualifiers even in C++11 mode. // Disable the optimization for now and revisit it later. -#if 0 // LANG_CXX11 - string Consume() && { return std::move(output_); } +#if 0 // LANG_CXX11 + std::string Consume() && { return std::move(output_); } #else // !LANG_CXX11 - const string& Get() { return output_; } + const std::string& Get() { return output_; } #endif // LANG_CXX11 private: - string output_; + std::string output_; }; } // namespace @@ -1466,7 +1523,7 @@ class StringBaseTextGenerator : public TextFormat::BaseTextGenerator { TextFormat::FieldValuePrinter::FieldValuePrinter() {} TextFormat::FieldValuePrinter::~FieldValuePrinter() {} -#if 0 // LANG_CXX11 +#if 0 // LANG_CXX11 #define FORWARD_IMPL(fn, ...) \ StringBaseTextGenerator generator; \ delegate_.fn(__VA_ARGS__, &generator); \ @@ -1478,55 +1535,52 @@ TextFormat::FieldValuePrinter::~FieldValuePrinter() {} return generator.Get() #endif // LANG_CXX11 -string TextFormat::FieldValuePrinter::PrintBool(bool val) const { +std::string TextFormat::FieldValuePrinter::PrintBool(bool val) const { FORWARD_IMPL(PrintBool, val); } -string TextFormat::FieldValuePrinter::PrintInt32(int32 val) const { +std::string TextFormat::FieldValuePrinter::PrintInt32(int32 val) const { FORWARD_IMPL(PrintInt32, val); } -string TextFormat::FieldValuePrinter::PrintUInt32(uint32 val) const { +std::string TextFormat::FieldValuePrinter::PrintUInt32(uint32 val) const { FORWARD_IMPL(PrintUInt32, val); } -string TextFormat::FieldValuePrinter::PrintInt64(int64 val) const { +std::string TextFormat::FieldValuePrinter::PrintInt64(int64 val) const { FORWARD_IMPL(PrintInt64, val); } -string TextFormat::FieldValuePrinter::PrintUInt64(uint64 val) const { +std::string TextFormat::FieldValuePrinter::PrintUInt64(uint64 val) const { FORWARD_IMPL(PrintUInt64, val); } -string TextFormat::FieldValuePrinter::PrintFloat(float val) const { +std::string TextFormat::FieldValuePrinter::PrintFloat(float val) const { FORWARD_IMPL(PrintFloat, val); } -string TextFormat::FieldValuePrinter::PrintDouble(double val) const { +std::string TextFormat::FieldValuePrinter::PrintDouble(double val) const { FORWARD_IMPL(PrintDouble, val); } -string TextFormat::FieldValuePrinter::PrintString(const string& val) const { +std::string TextFormat::FieldValuePrinter::PrintString( + const std::string& val) const { FORWARD_IMPL(PrintString, val); } -string TextFormat::FieldValuePrinter::PrintBytes(const string& val) const { +std::string TextFormat::FieldValuePrinter::PrintBytes( + const std::string& val) const { return PrintString(val); } -string TextFormat::FieldValuePrinter::PrintEnum(int32 val, - const string& name) const { +std::string TextFormat::FieldValuePrinter::PrintEnum( + int32 val, const std::string& name) const { FORWARD_IMPL(PrintEnum, val, name); } -string TextFormat::FieldValuePrinter::PrintFieldName( - const Message& message, - const Reflection* reflection, +std::string TextFormat::FieldValuePrinter::PrintFieldName( + const Message& message, const Reflection* reflection, const FieldDescriptor* field) const { FORWARD_IMPL(PrintFieldName, message, reflection, field); } -string TextFormat::FieldValuePrinter::PrintMessageStart( - const Message& message, - int field_index, - int field_count, +std::string TextFormat::FieldValuePrinter::PrintMessageStart( + const Message& message, int field_index, int field_count, bool single_line_mode) const { FORWARD_IMPL(PrintMessageStart, message, field_index, field_count, single_line_mode); } -string TextFormat::FieldValuePrinter::PrintMessageEnd( - const Message& message, - int field_index, - int field_count, +std::string TextFormat::FieldValuePrinter::PrintMessageEnd( + const Message& message, int field_index, int field_count, bool single_line_mode) const { FORWARD_IMPL(PrintMessageEnd, message, field_index, field_count, single_line_mode); @@ -1545,19 +1599,19 @@ void TextFormat::FastFieldValuePrinter::PrintBool( } void TextFormat::FastFieldValuePrinter::PrintInt32( int32 val, BaseTextGenerator* generator) const { - generator->PrintString(SimpleItoa(val)); + generator->PrintString(StrCat(val)); } void TextFormat::FastFieldValuePrinter::PrintUInt32( uint32 val, BaseTextGenerator* generator) const { - generator->PrintString(SimpleItoa(val)); + generator->PrintString(StrCat(val)); } void TextFormat::FastFieldValuePrinter::PrintInt64( int64 val, BaseTextGenerator* generator) const { - generator->PrintString(SimpleItoa(val)); + generator->PrintString(StrCat(val)); } void TextFormat::FastFieldValuePrinter::PrintUInt64( uint64 val, BaseTextGenerator* generator) const { - generator->PrintString(SimpleItoa(val)); + generator->PrintString(StrCat(val)); } void TextFormat::FastFieldValuePrinter::PrintFloat( float val, BaseTextGenerator* generator) const { @@ -1568,18 +1622,18 @@ void TextFormat::FastFieldValuePrinter::PrintDouble( generator->PrintString(SimpleDtoa(val)); } void TextFormat::FastFieldValuePrinter::PrintEnum( - int32 val, const string& name, BaseTextGenerator* generator) const { + int32 val, const std::string& name, BaseTextGenerator* generator) const { generator->PrintString(name); } void TextFormat::FastFieldValuePrinter::PrintString( - const string& val, BaseTextGenerator* generator) const { + const std::string& val, BaseTextGenerator* generator) const { generator->PrintLiteral("\""); generator->PrintString(CEscape(val)); generator->PrintLiteral("\""); } void TextFormat::FastFieldValuePrinter::PrintBytes( - const string& val, BaseTextGenerator* generator) const { + const std::string& val, BaseTextGenerator* generator) const { PrintString(val, generator); } void TextFormat::FastFieldValuePrinter::PrintFieldName( @@ -1642,61 +1696,70 @@ class FieldValuePrinterWrapper : public TextFormat::FastFieldValuePrinter { delegate_.reset(delegate); } - void PrintBool(bool val, TextFormat::BaseTextGenerator* generator) const { + void PrintBool(bool val, + TextFormat::BaseTextGenerator* generator) const override { generator->PrintString(delegate_->PrintBool(val)); } - void PrintInt32(int32 val, TextFormat::BaseTextGenerator* generator) const { + void PrintInt32(int32 val, + TextFormat::BaseTextGenerator* generator) const override { generator->PrintString(delegate_->PrintInt32(val)); } - void PrintUInt32(uint32 val, TextFormat::BaseTextGenerator* generator) const { + void PrintUInt32(uint32 val, + TextFormat::BaseTextGenerator* generator) const override { generator->PrintString(delegate_->PrintUInt32(val)); } - void PrintInt64(int64 val, TextFormat::BaseTextGenerator* generator) const { + void PrintInt64(int64 val, + TextFormat::BaseTextGenerator* generator) const override { generator->PrintString(delegate_->PrintInt64(val)); } - void PrintUInt64(uint64 val, TextFormat::BaseTextGenerator* generator) const { + void PrintUInt64(uint64 val, + TextFormat::BaseTextGenerator* generator) const override { generator->PrintString(delegate_->PrintUInt64(val)); } - void PrintFloat(float val, TextFormat::BaseTextGenerator* generator) const { + void PrintFloat(float val, + TextFormat::BaseTextGenerator* generator) const override { generator->PrintString(delegate_->PrintFloat(val)); } - void PrintDouble(double val, TextFormat::BaseTextGenerator* generator) const { + void PrintDouble(double val, + TextFormat::BaseTextGenerator* generator) const override { generator->PrintString(delegate_->PrintDouble(val)); } - void PrintString(const string& val, - TextFormat::BaseTextGenerator* generator) const { + void PrintString(const std::string& val, + TextFormat::BaseTextGenerator* generator) const override { generator->PrintString(delegate_->PrintString(val)); } - void PrintBytes(const string& val, - TextFormat::BaseTextGenerator* generator) const { + void PrintBytes(const std::string& val, + TextFormat::BaseTextGenerator* generator) const override { generator->PrintString(delegate_->PrintBytes(val)); } - void PrintEnum(int32 val, const string& name, - TextFormat::BaseTextGenerator* generator) const { + void PrintEnum(int32 val, const std::string& name, + TextFormat::BaseTextGenerator* generator) const override { generator->PrintString(delegate_->PrintEnum(val, name)); } void PrintFieldName(const Message& message, int field_index, int field_count, const Reflection* reflection, const FieldDescriptor* field, - TextFormat::BaseTextGenerator* generator) const { - generator->PrintString(delegate_->PrintFieldName( - message, reflection, field)); - } - void PrintFieldName(const Message& message, const Reflection* reflection, - const FieldDescriptor* field, - TextFormat::BaseTextGenerator* generator) const { + TextFormat::BaseTextGenerator* generator) const override { generator->PrintString( delegate_->PrintFieldName(message, reflection, field)); } - void PrintMessageStart(const Message& message, int field_index, - int field_count, bool single_line_mode, - TextFormat::BaseTextGenerator* generator) const { + void PrintFieldName(const Message& message, const Reflection* reflection, + const FieldDescriptor* field, + TextFormat::BaseTextGenerator* generator) const override { + generator->PrintString( + delegate_->PrintFieldName(message, reflection, field)); + } + void PrintMessageStart( + const Message& message, int field_index, int field_count, + bool single_line_mode, + TextFormat::BaseTextGenerator* generator) const override { generator->PrintString(delegate_->PrintMessageStart( message, field_index, field_count, single_line_mode)); } - void PrintMessageEnd(const Message& message, int field_index, int field_count, - bool single_line_mode, - TextFormat::BaseTextGenerator* generator) const { + void PrintMessageEnd( + const Message& message, int field_index, int field_count, + bool single_line_mode, + TextFormat::BaseTextGenerator* generator) const override { generator->PrintString(delegate_->PrintMessageEnd( message, field_index, field_count, single_line_mode)); } @@ -1709,14 +1772,14 @@ class FieldValuePrinterWrapper : public TextFormat::FastFieldValuePrinter { class FastFieldValuePrinterUtf8Escaping : public TextFormat::FastFieldValuePrinter { public: - void PrintString(const string& val, - TextFormat::BaseTextGenerator* generator) const { + void PrintString(const std::string& val, + TextFormat::BaseTextGenerator* generator) const override { generator->PrintLiteral("\""); generator->PrintString(strings::Utf8SafeCEscape(val)); generator->PrintLiteral("\""); } - void PrintBytes(const string& val, - TextFormat::BaseTextGenerator* generator) const { + void PrintBytes(const std::string& val, + TextFormat::BaseTextGenerator* generator) const override { return FastFieldValuePrinter::PrintString(val, generator); } }; @@ -1724,15 +1787,15 @@ class FastFieldValuePrinterUtf8Escaping } // namespace TextFormat::Printer::Printer() - : initial_indent_level_(0), - single_line_mode_(false), - use_field_number_(false), - use_short_repeated_primitives_(false), - hide_unknown_fields_(false), - print_message_fields_in_index_order_(false), - expand_any_(false), - truncate_string_field_longer_than_(0LL), - finder_(NULL) { + : initial_indent_level_(0), + single_line_mode_(false), + use_field_number_(false), + use_short_repeated_primitives_(false), + hide_unknown_fields_(false), + print_message_fields_in_index_order_(false), + expand_any_(false), + truncate_string_field_longer_than_(0LL), + finder_(NULL) { SetUseUtf8StringEscaping(false); } @@ -1757,8 +1820,7 @@ void TextFormat::Printer::SetDefaultFieldValuePrinter( } bool TextFormat::Printer::RegisterFieldValuePrinter( - const FieldDescriptor* field, - const FieldValuePrinter* printer) { + const FieldDescriptor* field, const FieldValuePrinter* printer) { if (field == NULL || printer == NULL) { return false; } @@ -1787,7 +1849,7 @@ bool TextFormat::Printer::RegisterMessagePrinter( } bool TextFormat::Printer::PrintToString(const Message& message, - string* output) const { + std::string* output) const { GOOGLE_DCHECK(output) << "output specified is NULL"; output->clear(); @@ -1797,8 +1859,7 @@ bool TextFormat::Printer::PrintToString(const Message& message, } bool TextFormat::Printer::PrintUnknownFieldsToString( - const UnknownFieldSet& unknown_fields, - string* output) const { + const UnknownFieldSet& unknown_fields, std::string* output) const { GOOGLE_DCHECK(output) << "output specified is NULL"; output->clear(); @@ -1859,15 +1920,15 @@ bool TextFormat::Printer::PrintAny(const Message& message, const Reflection* reflection = message.GetReflection(); // Extract the full type name from the type_url field. - const string& type_url = reflection->GetString(message, type_url_field); - string url_prefix; - string full_type_name; + const std::string& type_url = reflection->GetString(message, type_url_field); + std::string url_prefix; + std::string full_type_name; if (!internal::ParseAnyTypeUrl(type_url, &url_prefix, &full_type_name)) { return false; } // Print the "value" in text. - const google::protobuf::Descriptor* value_descriptor = + const Descriptor* value_descriptor = finder_ ? finder_->FindAnyType(message, url_prefix, full_type_name) : DefaultFinderFindAnyType(message, url_prefix, full_type_name); if (value_descriptor == NULL) { @@ -1875,9 +1936,9 @@ bool TextFormat::Printer::PrintAny(const Message& message, return false; } DynamicMessageFactory factory; - std::unique_ptr value_message( + std::unique_ptr value_message( factory.GetPrototype(value_descriptor)->New()); - string serialized_value = reflection->GetString(message, value_field); + std::string serialized_value = reflection->GetString(message, value_field); if (!value_message->ParseFromString(serialized_value)) { GOOGLE_LOG(WARNING) << type_url << ": failed to parse contents"; return false; @@ -1897,19 +1958,37 @@ bool TextFormat::Printer::PrintAny(const Message& message, void TextFormat::Printer::Print(const Message& message, TextGenerator* generator) const { + const Reflection* reflection = message.GetReflection(); + if (!reflection) { + // This message does not provide any way to describe its structure. + // Parse it again in an UnknownFieldSet, and display this instead. + UnknownFieldSet unknown_fields; + { + std::string serialized = message.SerializeAsString(); + io::ArrayInputStream input(serialized.data(), serialized.size()); + unknown_fields.ParseFromZeroCopyStream(&input); + } + PrintUnknownFields(unknown_fields, generator); + return; + } const Descriptor* descriptor = message.GetDescriptor(); auto itr = custom_message_printers_.find(descriptor); if (itr != custom_message_printers_.end()) { itr->second->Print(message, single_line_mode_, generator); return; } - const Reflection* reflection = message.GetReflection(); if (descriptor->full_name() == internal::kAnyFullTypeName && expand_any_ && PrintAny(message, generator)) { return; } std::vector fields; - reflection->ListFields(message, &fields); + if (descriptor->options().map_entry()) { + fields.push_back(descriptor->field(0)); + fields.push_back(descriptor->field(1)); + } else { + reflection->ListFields(message, &fields); + } + if (print_message_fields_in_index_order_) { std::sort(fields.begin(), fields.end(), FieldIndexSorter()); } @@ -1921,11 +2000,10 @@ void TextFormat::Printer::Print(const Message& message, } } -void TextFormat::Printer::PrintFieldValueToString( - const Message& message, - const FieldDescriptor* field, - int index, - string* output) const { +void TextFormat::Printer::PrintFieldValueToString(const Message& message, + const FieldDescriptor* field, + int index, + std::string* output) const { GOOGLE_DCHECK(output) << "output specified is NULL"; output->clear(); @@ -1935,12 +2013,185 @@ void TextFormat::Printer::PrintFieldValueToString( PrintFieldValue(message, message.GetReflection(), field, index, &generator); } +class MapEntryMessageComparator { + public: + explicit MapEntryMessageComparator(const Descriptor* descriptor) + : field_(descriptor->field(0)) {} + + bool operator()(const Message* a, const Message* b) { + const Reflection* reflection = a->GetReflection(); + switch (field_->cpp_type()) { + case FieldDescriptor::CPPTYPE_BOOL: { + bool first = reflection->GetBool(*a, field_); + bool second = reflection->GetBool(*b, field_); + return first < second; + } + case FieldDescriptor::CPPTYPE_INT32: { + int32 first = reflection->GetInt32(*a, field_); + int32 second = reflection->GetInt32(*b, field_); + return first < second; + } + case FieldDescriptor::CPPTYPE_INT64: { + int64 first = reflection->GetInt64(*a, field_); + int64 second = reflection->GetInt64(*b, field_); + return first < second; + } + case FieldDescriptor::CPPTYPE_UINT32: { + uint32 first = reflection->GetUInt32(*a, field_); + uint32 second = reflection->GetUInt32(*b, field_); + return first < second; + } + case FieldDescriptor::CPPTYPE_UINT64: { + uint64 first = reflection->GetUInt64(*a, field_); + uint64 second = reflection->GetUInt64(*b, field_); + return first < second; + } + case FieldDescriptor::CPPTYPE_STRING: { + std::string first = reflection->GetString(*a, field_); + std::string second = reflection->GetString(*b, field_); + return first < second; + } + default: + GOOGLE_LOG(DFATAL) << "Invalid key for map field."; + return true; + } + } + + private: + const FieldDescriptor* field_; +}; + +namespace internal { +class MapFieldPrinterHelper { + public: + // DynamicMapSorter::Sort cannot be used because it enfores syncing with + // repeated field. + static bool SortMap(const Message& message, const Reflection* reflection, + const FieldDescriptor* field, MessageFactory* factory, + std::vector* sorted_map_field); + static void CopyKey(const MapKey& key, Message* message, + const FieldDescriptor* field_desc); + static void CopyValue(const MapValueRef& value, Message* message, + const FieldDescriptor* field_desc); +}; + +// Returns true if elements contained in sorted_map_field need to be released. +bool MapFieldPrinterHelper::SortMap( + const Message& message, const Reflection* reflection, + const FieldDescriptor* field, MessageFactory* factory, + std::vector* sorted_map_field) { + bool need_release = false; + const MapFieldBase& base = *reflection->GetMapData(message, field); + + if (base.IsRepeatedFieldValid()) { + const RepeatedPtrField& map_field = + reflection->GetRepeatedPtrField(message, field); + for (int i = 0; i < map_field.size(); ++i) { + sorted_map_field->push_back( + const_cast*>(&map_field)->Mutable(i)); + } + } else { + // TODO(teboring): For performance, instead of creating map entry message + // for each element, just store map keys and sort them. + const Descriptor* map_entry_desc = field->message_type(); + const Message* prototype = factory->GetPrototype(map_entry_desc); + for (MapIterator iter = + reflection->MapBegin(const_cast(&message), field); + iter != reflection->MapEnd(const_cast(&message), field); + ++iter) { + Message* map_entry_message = prototype->New(); + CopyKey(iter.GetKey(), map_entry_message, map_entry_desc->field(0)); + CopyValue(iter.GetValueRef(), map_entry_message, + map_entry_desc->field(1)); + sorted_map_field->push_back(map_entry_message); + } + need_release = true; + } + + MapEntryMessageComparator comparator(field->message_type()); + std::stable_sort(sorted_map_field->begin(), sorted_map_field->end(), + comparator); + return need_release; +} + +void MapFieldPrinterHelper::CopyKey(const MapKey& key, Message* message, + const FieldDescriptor* field_desc) { + const Reflection* reflection = message->GetReflection(); + switch (field_desc->cpp_type()) { + case FieldDescriptor::CPPTYPE_DOUBLE: + case FieldDescriptor::CPPTYPE_FLOAT: + case FieldDescriptor::CPPTYPE_ENUM: + case FieldDescriptor::CPPTYPE_MESSAGE: + GOOGLE_LOG(ERROR) << "Not supported."; + break; + case FieldDescriptor::CPPTYPE_STRING: + reflection->SetString(message, field_desc, key.GetStringValue()); + return; + case FieldDescriptor::CPPTYPE_INT64: + reflection->SetInt64(message, field_desc, key.GetInt64Value()); + return; + case FieldDescriptor::CPPTYPE_INT32: + reflection->SetInt32(message, field_desc, key.GetInt32Value()); + return; + case FieldDescriptor::CPPTYPE_UINT64: + reflection->SetUInt64(message, field_desc, key.GetUInt64Value()); + return; + case FieldDescriptor::CPPTYPE_UINT32: + reflection->SetUInt32(message, field_desc, key.GetUInt32Value()); + return; + case FieldDescriptor::CPPTYPE_BOOL: + reflection->SetBool(message, field_desc, key.GetBoolValue()); + return; + } +} + +void MapFieldPrinterHelper::CopyValue(const MapValueRef& value, + Message* message, + const FieldDescriptor* field_desc) { + const Reflection* reflection = message->GetReflection(); + switch (field_desc->cpp_type()) { + case FieldDescriptor::CPPTYPE_DOUBLE: + reflection->SetDouble(message, field_desc, value.GetDoubleValue()); + return; + case FieldDescriptor::CPPTYPE_FLOAT: + reflection->SetFloat(message, field_desc, value.GetFloatValue()); + return; + case FieldDescriptor::CPPTYPE_ENUM: + reflection->SetEnumValue(message, field_desc, value.GetEnumValue()); + return; + case FieldDescriptor::CPPTYPE_MESSAGE: { + Message* sub_message = value.GetMessageValue().New(); + sub_message->CopyFrom(value.GetMessageValue()); + reflection->SetAllocatedMessage(message, sub_message, field_desc); + return; + } + case FieldDescriptor::CPPTYPE_STRING: + reflection->SetString(message, field_desc, value.GetStringValue()); + return; + case FieldDescriptor::CPPTYPE_INT64: + reflection->SetInt64(message, field_desc, value.GetInt64Value()); + return; + case FieldDescriptor::CPPTYPE_INT32: + reflection->SetInt32(message, field_desc, value.GetInt32Value()); + return; + case FieldDescriptor::CPPTYPE_UINT64: + reflection->SetUInt64(message, field_desc, value.GetUInt64Value()); + return; + case FieldDescriptor::CPPTYPE_UINT32: + reflection->SetUInt32(message, field_desc, value.GetUInt32Value()); + return; + case FieldDescriptor::CPPTYPE_BOOL: + reflection->SetBool(message, field_desc, value.GetBoolValue()); + return; + } +} +} // namespace internal + void TextFormat::Printer::PrintField(const Message& message, const Reflection* reflection, const FieldDescriptor* field, TextGenerator* generator) const { - if (use_short_repeated_primitives_ && - field->is_repeated() && + if (use_short_repeated_primitives_ && field->is_repeated() && field->cpp_type() != FieldDescriptor::CPPTYPE_STRING && field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) { PrintShortRepeatedField(message, reflection, field, generator); @@ -1951,14 +2202,18 @@ void TextFormat::Printer::PrintField(const Message& message, if (field->is_repeated()) { count = reflection->FieldSize(message, field); - } else if (reflection->HasField(message, field)) { + } else if (reflection->HasField(message, field) || + field->containing_type()->options().map_entry()) { count = 1; } - std::vector map_entries; - const bool is_map = field->is_map(); + DynamicMessageFactory factory; + std::vector sorted_map_field; + bool need_release = false; + bool is_map = field->is_map(); if (is_map) { - map_entries = DynamicMapSorter::Sort(message, count, reflection, field); + need_release = internal::MapFieldPrinterHelper::SortMap( + message, reflection, field, &factory, &sorted_map_field); } for (int j = 0; j < count; ++j) { @@ -1971,7 +2226,7 @@ void TextFormat::Printer::PrintField(const Message& message, custom_printers_, field, default_field_value_printer_.get()); const Message& sub_message = field->is_repeated() - ? (is_map ? *map_entries[j] + ? (is_map ? *sorted_map_field[j] : reflection->GetRepeatedMessage(message, field, j)) : reflection->GetMessage(message, field); printer->PrintMessageStart(sub_message, field_index, count, @@ -1992,6 +2247,12 @@ void TextFormat::Printer::PrintField(const Message& message, } } } + + if (need_release) { + for (int j = 0; j < sorted_map_field.size(); ++j) { + delete sorted_map_field[j]; + } + } } void TextFormat::Printer::PrintShortRepeatedField( @@ -2021,7 +2282,7 @@ void TextFormat::Printer::PrintFieldName(const Message& message, // if use_field_number_ is true, prints field number instead // of field name. if (use_field_number_) { - generator->PrintString(SimpleItoa(field->number())); + generator->PrintString(StrCat(field->number())); return; } @@ -2052,23 +2313,24 @@ void TextFormat::Printer::PrintFieldValue(const Message& message, generator); \ break - OUTPUT_FIELD( INT32, Int32); - OUTPUT_FIELD( INT64, Int64); + OUTPUT_FIELD(INT32, Int32); + OUTPUT_FIELD(INT64, Int64); OUTPUT_FIELD(UINT32, UInt32); OUTPUT_FIELD(UINT64, UInt64); - OUTPUT_FIELD( FLOAT, Float); + OUTPUT_FIELD(FLOAT, Float); OUTPUT_FIELD(DOUBLE, Double); - OUTPUT_FIELD( BOOL, Bool); + OUTPUT_FIELD(BOOL, Bool); #undef OUTPUT_FIELD case FieldDescriptor::CPPTYPE_STRING: { - string scratch; - const string& value = field->is_repeated() - ? reflection->GetRepeatedStringReference( - message, field, index, &scratch) - : reflection->GetStringReference(message, field, &scratch); - const string* value_to_print = &value; - string truncated_value; + std::string scratch; + const std::string& value = + field->is_repeated() + ? reflection->GetRepeatedStringReference(message, field, index, + &scratch) + : reflection->GetStringReference(message, field, &scratch); + const std::string* value_to_print = &value; + std::string truncated_value; if (truncate_string_field_longer_than_ > 0 && truncate_string_field_longer_than_ < value.size()) { truncated_value = value.substr(0, truncate_string_field_longer_than_) + @@ -2085,9 +2347,10 @@ void TextFormat::Printer::PrintFieldValue(const Message& message, } case FieldDescriptor::CPPTYPE_ENUM: { - int enum_value = field->is_repeated() - ? reflection->GetRepeatedEnumValue(message, field, index) - : reflection->GetEnumValue(message, field); + int enum_value = + field->is_repeated() + ? reflection->GetRepeatedEnumValue(message, field, index) + : reflection->GetEnumValue(message, field); const EnumValueDescriptor* enum_desc = field->enum_type()->FindValueByNumber(enum_value); if (enum_desc != NULL) { @@ -2107,8 +2370,8 @@ void TextFormat::Printer::PrintFieldValue(const Message& message, case FieldDescriptor::CPPTYPE_MESSAGE: Print(field->is_repeated() - ? reflection->GetRepeatedMessage(message, field, index) - : reflection->GetMessage(message, field), + ? reflection->GetRepeatedMessage(message, field, index) + : reflection->GetMessage(message, field), generator); break; } @@ -2120,44 +2383,39 @@ void TextFormat::Printer::PrintFieldValue(const Message& message, } /* static */ bool TextFormat::PrintUnknownFields( - const UnknownFieldSet& unknown_fields, - io::ZeroCopyOutputStream* output) { + const UnknownFieldSet& unknown_fields, io::ZeroCopyOutputStream* output) { return Printer().PrintUnknownFields(unknown_fields, output); } -/* static */ bool TextFormat::PrintToString( - const Message& message, string* output) { +/* static */ bool TextFormat::PrintToString(const Message& message, + std::string* output) { return Printer().PrintToString(message, output); } /* static */ bool TextFormat::PrintUnknownFieldsToString( - const UnknownFieldSet& unknown_fields, string* output) { + const UnknownFieldSet& unknown_fields, std::string* output) { return Printer().PrintUnknownFieldsToString(unknown_fields, output); } /* static */ void TextFormat::PrintFieldValueToString( - const Message& message, - const FieldDescriptor* field, - int index, - string* output) { + const Message& message, const FieldDescriptor* field, int index, + std::string* output) { return Printer().PrintFieldValueToString(message, field, index, output); } /* static */ bool TextFormat::ParseFieldValueFromString( - const string& input, - const FieldDescriptor* field, - Message* message) { + const std::string& input, const FieldDescriptor* field, Message* message) { return Parser().ParseFieldValueFromString(input, field, message); } // Prints an integer as hex with a fixed number of digits dependent on the // integer type. -template -static string PaddedHex(IntType value) { - string result; +template +static std::string PaddedHex(IntType value) { + std::string result; result.reserve(sizeof(value) * 2); for (int i = sizeof(value) * 2 - 1; i >= 0; i--) { - result.push_back(int_to_hex_digit(value >> (i*4) & 0x0F)); + result.push_back(int_to_hex_digit(value >> (i * 4) & 0x0F)); } return result; } @@ -2166,13 +2424,13 @@ void TextFormat::Printer::PrintUnknownFields( const UnknownFieldSet& unknown_fields, TextGenerator* generator) const { for (int i = 0; i < unknown_fields.field_count(); i++) { const UnknownField& field = unknown_fields.field(i); - string field_number = SimpleItoa(field.number()); + std::string field_number = StrCat(field.number()); switch (field.type()) { case UnknownField::TYPE_VARINT: generator->PrintString(field_number); generator->PrintLiteral(": "); - generator->PrintString(SimpleItoa(field.varint())); + generator->PrintString(StrCat(field.varint())); if (single_line_mode_) { generator->PrintLiteral(" "); } else { @@ -2205,7 +2463,7 @@ void TextFormat::Printer::PrintUnknownFields( } case UnknownField::TYPE_LENGTH_DELIMITED: { generator->PrintString(field_number); - const string& value = field.length_delimited(); + const std::string& value = field.length_delimited(); UnknownFieldSet embedded_unknown_fields; if (!value.empty() && embedded_unknown_fields.ParseFromString(value)) { // This field is parseable as a Message. diff --git a/third_party/protobuf/src/google/protobuf/text_format.h b/third_party/protobuf/src/google/protobuf/text_format.h index d6f3e16b..f999f472 100644 --- a/third_party/protobuf/src/google/protobuf/text_format.h +++ b/third_party/protobuf/src/google/protobuf/text_format.h @@ -47,12 +47,19 @@ #include #include #include +#include + +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif namespace google { namespace protobuf { namespace io { - class ErrorCollector; // tokenizer.h +class ErrorCollector; // tokenizer.h } // This class implements protocol buffer text format. Printing and parsing @@ -60,7 +67,7 @@ namespace io { // of messages. // // This class is really a namespace that contains only static methods. -class LIBPROTOBUF_EXPORT TextFormat { +class PROTOBUF_EXPORT TextFormat { public: // Outputs a textual representation of the given message to the given // output stream. Returns false if printing fails. @@ -75,23 +82,22 @@ class LIBPROTOBUF_EXPORT TextFormat { // Like Print(), but outputs directly to a string. // Note: output will be cleared prior to printing, and will be left empty // even if printing fails. Returns false if printing fails. - static bool PrintToString(const Message& message, string* output); + static bool PrintToString(const Message& message, std::string* output); - // Like PrintUnknownFields(), but outputs directly to a string. Returns false - // if printing fails. + // Like PrintUnknownFields(), but outputs directly to a string. Returns + // false if printing fails. static bool PrintUnknownFieldsToString(const UnknownFieldSet& unknown_fields, - string* output); + std::string* output); // Outputs a textual representation of the value of the field supplied on // the message supplied. For non-repeated fields, an index of -1 must // be supplied. Note that this method will print the default value for a // field if it is not set. static void PrintFieldValueToString(const Message& message, - const FieldDescriptor* field, - int index, - string* output); + const FieldDescriptor* field, int index, + std::string* output); - class LIBPROTOBUF_EXPORT BaseTextGenerator { + class PROTOBUF_EXPORT BaseTextGenerator { public: virtual ~BaseTextGenerator(); @@ -101,7 +107,7 @@ class LIBPROTOBUF_EXPORT TextFormat { // Print text to the output stream. virtual void Print(const char* text, size_t size) = 0; - void PrintString(const string& str) { Print(str.data(), str.size()); } + void PrintString(const std::string& str) { Print(str.data(), str.size()); } template void PrintLiteral(const char (&text)[n]) { @@ -113,7 +119,7 @@ class LIBPROTOBUF_EXPORT TextFormat { // string representation. // You can derive from this FastFieldValuePrinter if you want to have fields // to be printed in a different way and register it at the Printer. - class LIBPROTOBUF_EXPORT FastFieldValuePrinter { + class PROTOBUF_EXPORT FastFieldValuePrinter { public: FastFieldValuePrinter(); virtual ~FastFieldValuePrinter(); @@ -124,11 +130,11 @@ class LIBPROTOBUF_EXPORT TextFormat { virtual void PrintUInt64(uint64 val, BaseTextGenerator* generator) const; virtual void PrintFloat(float val, BaseTextGenerator* generator) const; virtual void PrintDouble(double val, BaseTextGenerator* generator) const; - virtual void PrintString(const string& val, + virtual void PrintString(const std::string& val, BaseTextGenerator* generator) const; - virtual void PrintBytes(const string& val, + virtual void PrintBytes(const std::string& val, BaseTextGenerator* generator) const; - virtual void PrintEnum(int32 val, const string& name, + virtual void PrintEnum(int32 val, const std::string& name, BaseTextGenerator* generator) const; virtual void PrintFieldName(const Message& message, int field_index, int field_count, const Reflection* reflection, @@ -149,39 +155,37 @@ class LIBPROTOBUF_EXPORT TextFormat { GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FastFieldValuePrinter); }; - class LIBPROTOBUF_EXPORT PROTOBUF_RUNTIME_DEPRECATED("Please use FastFieldValuePrinter") - FieldValuePrinter { + class PROTOBUF_EXPORT PROTOBUF_DEPRECATED_MSG( + "Please use FastFieldValuePrinter") FieldValuePrinter { public: FieldValuePrinter(); virtual ~FieldValuePrinter(); - virtual string PrintBool(bool val) const; - virtual string PrintInt32(int32 val) const; - virtual string PrintUInt32(uint32 val) const; - virtual string PrintInt64(int64 val) const; - virtual string PrintUInt64(uint64 val) const; - virtual string PrintFloat(float val) const; - virtual string PrintDouble(double val) const; - virtual string PrintString(const string& val) const; - virtual string PrintBytes(const string& val) const; - virtual string PrintEnum(int32 val, const string& name) const; - virtual string PrintFieldName(const Message& message, - const Reflection* reflection, - const FieldDescriptor* field) const; - virtual string PrintMessageStart(const Message& message, - int field_index, - int field_count, - bool single_line_mode) const; - virtual string PrintMessageEnd(const Message& message, - int field_index, - int field_count, - bool single_line_mode) const; + virtual std::string PrintBool(bool val) const; + virtual std::string PrintInt32(int32 val) const; + virtual std::string PrintUInt32(uint32 val) const; + virtual std::string PrintInt64(int64 val) const; + virtual std::string PrintUInt64(uint64 val) const; + virtual std::string PrintFloat(float val) const; + virtual std::string PrintDouble(double val) const; + virtual std::string PrintString(const std::string& val) const; + virtual std::string PrintBytes(const std::string& val) const; + virtual std::string PrintEnum(int32 val, const std::string& name) const; + virtual std::string PrintFieldName(const Message& message, + const Reflection* reflection, + const FieldDescriptor* field) const; + virtual std::string PrintMessageStart(const Message& message, + int field_index, int field_count, + bool single_line_mode) const; + virtual std::string PrintMessageEnd(const Message& message, int field_index, + int field_count, + bool single_line_mode) const; private: FastFieldValuePrinter delegate_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldValuePrinter); }; - class LIBPROTOBUF_EXPORT MessagePrinter { + class PROTOBUF_EXPORT MessagePrinter { public: MessagePrinter() {} virtual ~MessagePrinter() {} @@ -194,16 +198,15 @@ class LIBPROTOBUF_EXPORT TextFormat { // Interface that Printers or Parsers can use to find extensions, or types // referenced in Any messages. - class LIBPROTOBUF_EXPORT Finder { + class PROTOBUF_EXPORT Finder { public: virtual ~Finder(); // Try to find an extension of *message by fully-qualified field // name. Returns NULL if no extension is known for this name or number. // The base implementation uses the extensions already known by the message. - virtual const FieldDescriptor* FindExtension( - Message* message, - const string& name) const; + virtual const FieldDescriptor* FindExtension(Message* message, + const std::string& name) const; // Find the message type for an Any proto. // Returns NULL if no message is known for this name. @@ -211,13 +214,19 @@ class LIBPROTOBUF_EXPORT TextFormat { // type.googleapis.com/, and searches the DescriptorPool of the parent // message. virtual const Descriptor* FindAnyType(const Message& message, - const string& prefix, - const string& name) const; + const std::string& prefix, + const std::string& name) const; + + // Find the message factory for the given extension field. This can be used + // to generalize the Parser to add extension fields to a message in the same + // way as the "input" message for the Parser. + virtual MessageFactory* FindExtensionFactory( + const FieldDescriptor* field) const; }; // Class for those users which require more fine-grained control over how // a protobuffer message is printed out. - class LIBPROTOBUF_EXPORT Printer { + class PROTOBUF_EXPORT Printer { public: Printer(); ~Printer(); @@ -228,15 +237,14 @@ class LIBPROTOBUF_EXPORT TextFormat { bool PrintUnknownFields(const UnknownFieldSet& unknown_fields, io::ZeroCopyOutputStream* output) const; // Like TextFormat::PrintToString - bool PrintToString(const Message& message, string* output) const; + bool PrintToString(const Message& message, std::string* output) const; // Like TextFormat::PrintUnknownFieldsToString bool PrintUnknownFieldsToString(const UnknownFieldSet& unknown_fields, - string* output) const; + std::string* output) const; // Like TextFormat::PrintFieldValueToString void PrintFieldValueToString(const Message& message, - const FieldDescriptor* field, - int index, - string* output) const; + const FieldDescriptor* field, int index, + std::string* output) const; // Adjust the initial indent level of all output. Each indent level is // equal to two spaces. @@ -250,9 +258,7 @@ class LIBPROTOBUF_EXPORT TextFormat { single_line_mode_ = single_line_mode; } - bool IsInSingleLineMode() const { - return single_line_mode_; - } + bool IsInSingleLineMode() const { return single_line_mode_; } // If use_field_number is true, uses field number instead of field name. void SetUseFieldNumber(bool use_field_number) { @@ -286,9 +292,7 @@ class LIBPROTOBUF_EXPORT TextFormat { // is useful to be able to print the message without unknown fields (e.g. // for the python protobuf version to maintain consistency between its pure // python and c++ implementations). - void SetHideUnknownFields(bool hide) { - hide_unknown_fields_ = hide; - } + void SetHideUnknownFields(bool hide) { hide_unknown_fields_ = hide; } // If print_message_fields_in_index_order is true, fields of a proto message // will be printed using the order defined in source code instead of the @@ -308,18 +312,14 @@ class LIBPROTOBUF_EXPORT TextFormat { // If expand==false, print Any using the default printer. The output will // look like // type_url: "" value: "serialized_content" - void SetExpandAny(bool expand) { - expand_any_ = expand; - } + void SetExpandAny(bool expand) { expand_any_ = expand; } // Set how parser finds message for Any payloads. - void SetFinder(Finder* finder) { - finder_ = finder; - } + void SetFinder(const Finder* finder) { finder_ = finder; } - // If non-zero, we truncate all string fields that are longer than this - // threshold. This is useful when the proto message has very long strings, - // e.g., dump of encoded image file. + // If non-zero, we truncate all string fields that are longer than + // this threshold. This is useful when the proto message has very long + // strings, e.g., dump of encoded image file. // // NOTE(hfgong): Setting a non-zero value breaks round-trip safe // property of TextFormat::Printer. That is, from the printed message, we @@ -432,18 +432,18 @@ class LIBPROTOBUF_EXPORT TextFormat { // google::protobuf::MessageLite::ParseFromString(). static bool Parse(io::ZeroCopyInputStream* input, Message* output); // Like Parse(), but reads directly from a string. - static bool ParseFromString(const string& input, Message* output); + static bool ParseFromString(const std::string& input, Message* output); // Like Parse(), but the data is merged into the given message, as if // using Message::MergeFrom(). static bool Merge(io::ZeroCopyInputStream* input, Message* output); // Like Merge(), but reads directly from a string. - static bool MergeFromString(const string& input, Message* output); + static bool MergeFromString(const std::string& input, Message* output); // Parse the given text as a single field value and store it into the // given field of the given message. If the field is a repeated field, // the new value will be added to the end - static bool ParseFieldValueFromString(const string& input, + static bool ParseFieldValueFromString(const std::string& input, const FieldDescriptor* field, Message* message); @@ -459,7 +459,7 @@ class LIBPROTOBUF_EXPORT TextFormat { // Data structure which is populated with the locations of each field // value parsed from the text. - class LIBPROTOBUF_EXPORT ParseInfoTree { + class PROTOBUF_EXPORT ParseInfoTree { public: ParseInfoTree(); ~ParseInfoTree(); @@ -486,13 +486,13 @@ class LIBPROTOBUF_EXPORT TextFormat { ParseInfoTree* CreateNested(const FieldDescriptor* field); // Defines the map from the index-th field descriptor to its parse location. - typedef std::map > LocationMap; + typedef std::map > + LocationMap; // Defines the map from the index-th field descriptor to the nested parse // info tree. - typedef std::map > NestedMap; + typedef std::map > + NestedMap; LocationMap locations_; NestedMap nested_; @@ -501,7 +501,7 @@ class LIBPROTOBUF_EXPORT TextFormat { }; // For more control over parsing, use this class. - class LIBPROTOBUF_EXPORT Parser { + class PROTOBUF_EXPORT Parser { public: Parser(); ~Parser(); @@ -509,11 +509,11 @@ class LIBPROTOBUF_EXPORT TextFormat { // Like TextFormat::Parse(). bool Parse(io::ZeroCopyInputStream* input, Message* output); // Like TextFormat::ParseFromString(). - bool ParseFromString(const string& input, Message* output); + bool ParseFromString(const std::string& input, Message* output); // Like TextFormat::Merge(). bool Merge(io::ZeroCopyInputStream* input, Message* output); // Like TextFormat::MergeFromString(). - bool MergeFromString(const string& input, Message* output); + bool MergeFromString(const std::string& input, Message* output); // Set where to report parse errors. If NULL (the default), errors will // be printed to stderr. @@ -524,21 +524,15 @@ class LIBPROTOBUF_EXPORT TextFormat { // Set how parser finds extensions. If NULL (the default), the // parser will use the standard Reflection object associated with // the message being parsed. - void SetFinder(Finder* finder) { - finder_ = finder; - } + void SetFinder(const Finder* finder) { finder_ = finder; } // Sets where location information about the parse will be written. If NULL // (the default), then no location will be written. - void WriteLocationsTo(ParseInfoTree* tree) { - parse_info_tree_ = tree; - } + void WriteLocationsTo(ParseInfoTree* tree) { parse_info_tree_ = tree; } // Normally parsing fails if, after parsing, output->IsInitialized() // returns false. Call AllowPartialMessage(true) to skip this check. - void AllowPartialMessage(bool allow) { - allow_partial_ = allow; - } + void AllowPartialMessage(bool allow) { allow_partial_ = allow; } // Allow field names to be matched case-insensitively. // This is not advisable if there are fields that only differ in case, or @@ -549,14 +543,28 @@ class LIBPROTOBUF_EXPORT TextFormat { } // Like TextFormat::ParseFieldValueFromString - bool ParseFieldValueFromString(const string& input, + bool ParseFieldValueFromString(const std::string& input, const FieldDescriptor* field, Message* output); + // When an unknown extension is met, parsing will fail if this option is set + // to false (the default). If true, unknown extensions will be ignored and + // a warning message will be generated. + void AllowUnknownExtension(bool allow) { allow_unknown_extension_ = allow; } - void AllowFieldNumber(bool allow) { - allow_field_number_ = allow; - } + // When an unknown field is met, parsing will fail if this option is set + // to false(the default). If true, unknown fields will be ignored and + // a warning message will be generated. + // Please aware that set this option true may hide some errors (e.g. + // spelling error on field name). Avoid to use this option if possible. + void AllowUnknownField(bool allow) { allow_unknown_field_ = allow; } + + + void AllowFieldNumber(bool allow) { allow_field_number_ = allow; } + + // Sets maximum recursion depth which parser can use. This is effectively + // the maximum allowed nesting of proto messages. + void SetRecursionLimit(int limit) { recursion_limit_ = limit; } private: // Forward declaration of an internal class used to parse text @@ -565,8 +573,7 @@ class LIBPROTOBUF_EXPORT TextFormat { // Like TextFormat::Merge(). The provided implementation is used // to do the parsing. - bool MergeUsingImpl(io::ZeroCopyInputStream* input, - Message* output, + bool MergeUsingImpl(io::ZeroCopyInputStream* input, Message* output, ParserImpl* parser_impl); io::ErrorCollector* error_collector_; @@ -575,10 +582,12 @@ class LIBPROTOBUF_EXPORT TextFormat { bool allow_partial_; bool allow_case_insensitive_field_; bool allow_unknown_field_; + bool allow_unknown_extension_; bool allow_unknown_enum_; bool allow_field_number_; bool allow_relaxed_whitespace_; bool allow_singular_overwrites_; + int recursion_limit_; }; @@ -602,13 +611,14 @@ inline void TextFormat::RecordLocation(ParseInfoTree* info_tree, info_tree->RecordLocation(field, location); } - inline TextFormat::ParseInfoTree* TextFormat::CreateNested( ParseInfoTree* info_tree, const FieldDescriptor* field) { return info_tree->CreateNested(field); } } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_TEXT_FORMAT_H__ diff --git a/third_party/protobuf/src/google/protobuf/text_format_unittest.cc b/third_party/protobuf/src/google/protobuf/text_format_unittest.cc index 544c37e2..11e4c106 100644 --- a/third_party/protobuf/src/google/protobuf/text_format_unittest.cc +++ b/third_party/protobuf/src/google/protobuf/text_format_unittest.cc @@ -44,20 +44,26 @@ #include #include #include +#include #include +#include #include #include #include +#include #include #include - #include + + #include #include #include #include +#include + namespace google { namespace protobuf { @@ -65,44 +71,46 @@ namespace protobuf { namespace text_format_unittest { // A basic string with different escapable characters for testing. -const string kEscapeTestString = - "\"A string with ' characters \n and \r newlines and \t tabs and \001 " - "slashes \\ and multiple spaces"; +const std::string kEscapeTestString = + "\"A string with ' characters \n and \r newlines and \t tabs and \001 " + "slashes \\ and multiple spaces"; // A representation of the above string with all the characters escaped. -const string kEscapeTestStringEscaped = - "\"\\\"A string with \\' characters \\n and \\r newlines " - "and \\t tabs and \\001 slashes \\\\ and multiple spaces\""; +const std::string kEscapeTestStringEscaped = + "\"\\\"A string with \\' characters \\n and \\r newlines " + "and \\t tabs and \\001 slashes \\\\ and multiple spaces\""; class TextFormatTest : public testing::Test { public: static void SetUpTestCase() { GOOGLE_CHECK_OK(File::GetContents( - TestSourceDir() + - "/google/protobuf/" - "testdata/text_format_unittest_data_oneof_implemented.txt", + TestUtil::GetTestDataPath( + "net/proto2/internal/" + "testdata/text_format_unittest_data_oneof_implemented.txt"), &static_proto_debug_string_, true)); + CleanStringLineEndings(&static_proto_debug_string_, false); } TextFormatTest() : proto_debug_string_(static_proto_debug_string_) {} protected: // Debug string read from text_format_unittest_data.txt. - const string proto_debug_string_; + const std::string proto_debug_string_; unittest::TestAllTypes proto_; private: - static string static_proto_debug_string_; + static std::string static_proto_debug_string_; }; -string TextFormatTest::static_proto_debug_string_; +std::string TextFormatTest::static_proto_debug_string_; class TextFormatExtensionsTest : public testing::Test { public: static void SetUpTestCase() { - GOOGLE_CHECK_OK(File::GetContents(TestSourceDir() + - "/google/protobuf/testdata/" - "text_format_unittest_extensions_data.txt", - &static_proto_debug_string_, true)); + GOOGLE_CHECK_OK(File::GetContents( + TestUtil::GetTestDataPath("net/proto2/internal/testdata/" + "text_format_unittest_extensions_data.txt"), + &static_proto_debug_string_, true)); + CleanStringLineEndings(&static_proto_debug_string_, false); } TextFormatExtensionsTest() @@ -110,14 +118,13 @@ class TextFormatExtensionsTest : public testing::Test { protected: // Debug string read from text_format_unittest_data.txt. - const string proto_debug_string_; + const std::string proto_debug_string_; unittest::TestAllExtensions proto_; private: - static string static_proto_debug_string_; + static std::string static_proto_debug_string_; }; -string TextFormatExtensionsTest::static_proto_debug_string_; - +std::string TextFormatExtensionsTest::static_proto_debug_string_; TEST_F(TextFormatTest, Basic) { TestUtil::SetAllFields(&proto_); @@ -135,10 +142,11 @@ TEST_F(TextFormatTest, ShortDebugString) { proto_.mutable_optional_nested_message()->set_bb(2); proto_.mutable_optional_foreign_message(); - EXPECT_EQ("optional_int32: 1 optional_string: \"hello\" " - "optional_nested_message { bb: 2 } " - "optional_foreign_message { }", - proto_.ShortDebugString()); + EXPECT_EQ( + "optional_int32: 1 optional_string: \"hello\" " + "optional_nested_message { bb: 2 } " + "optional_foreign_message { }", + proto_.ShortDebugString()); } TEST_F(TextFormatTest, ShortPrimitiveRepeateds) { @@ -154,44 +162,47 @@ TEST_F(TextFormatTest, ShortPrimitiveRepeateds) { TextFormat::Printer printer; printer.SetUseShortRepeatedPrimitives(true); - string text; + std::string text; EXPECT_TRUE(printer.PrintToString(proto_, &text)); - EXPECT_EQ("optional_int32: 123\n" - "repeated_int32: [456, 789]\n" - "repeated_string: \"foo\"\n" - "repeated_string: \"bar\"\n" - "repeated_nested_message {\n bb: 2\n}\n" - "repeated_nested_message {\n bb: 3\n}\n" - "repeated_nested_enum: [FOO, BAR]\n", - text); + EXPECT_EQ( + "optional_int32: 123\n" + "repeated_int32: [456, 789]\n" + "repeated_string: \"foo\"\n" + "repeated_string: \"bar\"\n" + "repeated_nested_message {\n bb: 2\n}\n" + "repeated_nested_message {\n bb: 3\n}\n" + "repeated_nested_enum: [FOO, BAR]\n", + text); - // Verify that any existing data in the string is cleared when - // PrintToString() is called. + // Verify that any existing data in the string is cleared when PrintToString() + // is called. text = "just some data here...\n\nblah blah"; EXPECT_TRUE(printer.PrintToString(proto_, &text)); - EXPECT_EQ("optional_int32: 123\n" - "repeated_int32: [456, 789]\n" - "repeated_string: \"foo\"\n" - "repeated_string: \"bar\"\n" - "repeated_nested_message {\n bb: 2\n}\n" - "repeated_nested_message {\n bb: 3\n}\n" - "repeated_nested_enum: [FOO, BAR]\n", - text); + EXPECT_EQ( + "optional_int32: 123\n" + "repeated_int32: [456, 789]\n" + "repeated_string: \"foo\"\n" + "repeated_string: \"bar\"\n" + "repeated_nested_message {\n bb: 2\n}\n" + "repeated_nested_message {\n bb: 3\n}\n" + "repeated_nested_enum: [FOO, BAR]\n", + text); // Try in single-line mode. printer.SetSingleLineMode(true); EXPECT_TRUE(printer.PrintToString(proto_, &text)); - EXPECT_EQ("optional_int32: 123 " - "repeated_int32: [456, 789] " - "repeated_string: \"foo\" " - "repeated_string: \"bar\" " - "repeated_nested_message { bb: 2 } " - "repeated_nested_message { bb: 3 } " - "repeated_nested_enum: [FOO, BAR] ", - text); + EXPECT_EQ( + "optional_int32: 123 " + "repeated_int32: [456, 789] " + "repeated_string: \"foo\" " + "repeated_string: \"bar\" " + "repeated_nested_message { bb: 2 } " + "repeated_nested_message { bb: 3 } " + "repeated_nested_enum: [FOO, BAR] ", + text); } @@ -200,13 +211,12 @@ TEST_F(TextFormatTest, StringEscape) { proto_.set_optional_string(kEscapeTestString); // Get the DebugString from the proto. - string debug_string = proto_.DebugString(); - string utf8_debug_string = proto_.Utf8DebugString(); + std::string debug_string = proto_.DebugString(); + std::string utf8_debug_string = proto_.Utf8DebugString(); // Hardcode a correct value to test against. - string correct_string = "optional_string: " - + kEscapeTestStringEscaped - + "\n"; + std::string correct_string = + "optional_string: " + kEscapeTestStringEscaped + "\n"; // Compare. EXPECT_EQ(correct_string, debug_string); @@ -214,8 +224,8 @@ TEST_F(TextFormatTest, StringEscape) { // the protocol buffer contains no UTF-8 text. EXPECT_EQ(correct_string, utf8_debug_string); - string expected_short_debug_string = "optional_string: " - + kEscapeTestStringEscaped; + std::string expected_short_debug_string = + "optional_string: " + kEscapeTestStringEscaped; EXPECT_EQ(expected_short_debug_string, proto_.ShortDebugString()); } @@ -225,18 +235,18 @@ TEST_F(TextFormatTest, Utf8DebugString) { proto_.set_optional_bytes("\350\260\267\346\255\214"); // Get the DebugString from the proto. - string debug_string = proto_.DebugString(); - string utf8_debug_string = proto_.Utf8DebugString(); + std::string debug_string = proto_.DebugString(); + std::string utf8_debug_string = proto_.Utf8DebugString(); // Hardcode a correct value to test against. - string correct_utf8_string = + std::string correct_utf8_string = "optional_string: " "\"\350\260\267\346\255\214\"" "\n" "optional_bytes: " "\"\\350\\260\\267\\346\\255\\214\"" "\n"; - string correct_string = + std::string correct_string = "optional_string: " "\"\\350\\260\\267\\346\\255\\214\"" "\n" @@ -266,17 +276,17 @@ TEST_F(TextFormatTest, PrintUnknownFields) { unknown_fields->AddVarint(8, 3); EXPECT_EQ( - "5: 1\n" - "5: 0x00000002\n" - "5: 0x0000000000000003\n" - "5: \"4\"\n" - "5 {\n" - " 10: 5\n" - "}\n" - "8: 1\n" - "8: 2\n" - "8: 3\n", - message.DebugString()); + "5: 1\n" + "5: 0x00000002\n" + "5: 0x0000000000000003\n" + "5: \"4\"\n" + "5 {\n" + " 10: 5\n" + "}\n" + "8: 1\n" + "8: 2\n" + "8: 3\n", + message.DebugString()); } TEST_F(TextFormatTest, PrintUnknownFieldsHidden) { @@ -298,7 +308,7 @@ TEST_F(TextFormatTest, PrintUnknownFieldsHidden) { TextFormat::Printer printer; printer.SetHideUnknownFields(true); - string output; + std::string output; printer.PrintToString(message, &output); EXPECT_EQ("data: \"data\"\n", output); @@ -331,21 +341,21 @@ TEST_F(TextFormatTest, PrintUnknownMessage) { // nested message. message.add_repeated_nested_message()->set_bb(123); - string data; + std::string data; message.SerializeToString(&data); - string text; + std::string text; UnknownFieldSet unknown_fields; EXPECT_TRUE(unknown_fields.ParseFromString(data)); EXPECT_TRUE(TextFormat::PrintUnknownFieldsToString(unknown_fields, &text)); EXPECT_EQ( - "44: \"abc\"\n" - "44: \"def\"\n" - "44: \"\"\n" - "48 {\n" - " 1: 123\n" - "}\n", - text); + "44: \"abc\"\n" + "44: \"def\"\n" + "44: \"\"\n" + "48 {\n" + " 1: 123\n" + "}\n", + text); } TEST_F(TextFormatTest, PrintMessageWithIndent) { @@ -357,17 +367,17 @@ TEST_F(TextFormatTest, PrintMessageWithIndent) { message.add_repeated_string("def"); message.add_repeated_nested_message()->set_bb(123); - string text; + std::string text; TextFormat::Printer printer; printer.SetInitialIndentLevel(1); EXPECT_TRUE(printer.PrintToString(message, &text)); EXPECT_EQ( - " repeated_string: \"abc\"\n" - " repeated_string: \"def\"\n" - " repeated_nested_message {\n" - " bb: 123\n" - " }\n", - text); + " repeated_string: \"abc\"\n" + " repeated_string: \"def\"\n" + " repeated_nested_message {\n" + " bb: 123\n" + " }\n", + text); } TEST_F(TextFormatTest, PrintMessageSingleLine) { @@ -379,15 +389,15 @@ TEST_F(TextFormatTest, PrintMessageSingleLine) { message.add_repeated_string("def"); message.add_repeated_nested_message()->set_bb(123); - string text; + std::string text; TextFormat::Printer printer; printer.SetInitialIndentLevel(1); printer.SetSingleLineMode(true); EXPECT_TRUE(printer.PrintToString(message, &text)); EXPECT_EQ( - " repeated_string: \"abc\" repeated_string: \"def\" " - "repeated_nested_message { bb: 123 } ", - text); + " repeated_string: \"abc\" repeated_string: \"def\" " + "repeated_nested_message { bb: 123 } ", + text); } TEST_F(TextFormatTest, PrintBufferTooSmall) { @@ -408,7 +418,7 @@ TEST_F(TextFormatTest, PrintBufferTooSmall) { // A printer that appends 'u' to all unsigned int32. class CustomUInt32FieldValuePrinter : public TextFormat::FieldValuePrinter { public: - virtual string PrintUInt32(uint32 val) const { + virtual std::string PrintUInt32(uint32 val) const { return StrCat(FieldValuePrinter::PrintUInt32(val), "u"); } }; @@ -425,14 +435,14 @@ TEST_F(TextFormatTest, DefaultCustomFieldPrinter) { printer.SetDefaultFieldValuePrinter(new CustomUInt32FieldValuePrinter()); // Let's see if that works well together with the repeated primitives: printer.SetUseShortRepeatedPrimitives(true); - string text; + std::string text; printer.PrintToString(message, &text); EXPECT_EQ("optional_uint32: 42u\nrepeated_uint32: [1u, 2u, 3u]\n", text); } class CustomInt32FieldValuePrinter : public TextFormat::FieldValuePrinter { public: - virtual string PrintInt32(int32 val) const { + virtual std::string PrintInt32(int32 val) const { return StrCat("value-is(", FieldValuePrinter::PrintInt32(val), ")"); } }; @@ -447,7 +457,7 @@ TEST_F(TextFormatTest, FieldSpecificCustomPrinter) { EXPECT_TRUE(printer.RegisterFieldValuePrinter( message.GetDescriptor()->FindFieldByName("optional_int32"), new CustomInt32FieldValuePrinter())); - string text; + std::string text; printer.PrintToString(message, &text); EXPECT_EQ("optional_int32: value-is(42)\nrepeated_int32: 42\n", text); } @@ -483,19 +493,19 @@ TEST_F(TextFormatTest, ErrorCasesRegisteringFieldValuePrinterShouldFail) { class CustomMessageFieldValuePrinter : public TextFormat::FieldValuePrinter { public: - virtual string PrintInt32(int32 v) const { - return StrCat(FieldValuePrinter::PrintInt32(v), " # x", strings::Hex(v)); + virtual std::string PrintInt32(int32 v) const { + return StrCat(FieldValuePrinter::PrintInt32(v), " # x", + strings::Hex(v)); } - virtual string PrintMessageStart(const Message& message, - int field_index, - int field_count, - bool single_line_mode) const { + virtual std::string PrintMessageStart(const Message& message, int field_index, + int field_count, + bool single_line_mode) const { if (single_line_mode) { return " { "; } - return StrCat( - " { # ", message.GetDescriptor()->name(), ": ", field_index, "\n"); + return StrCat(" { # ", message.GetDescriptor()->name(), ": ", + field_index, "\n"); } }; @@ -510,7 +520,7 @@ TEST_F(TextFormatTest, CustomPrinterForComments) { TextFormat::Printer printer; CustomMessageFieldValuePrinter my_field_printer; printer.SetDefaultFieldValuePrinter(new CustomMessageFieldValuePrinter()); - string text; + std::string text; printer.PrintToString(message, &text); EXPECT_EQ( "optional_nested_message { # NestedMessage: -1\n" @@ -533,10 +543,9 @@ TEST_F(TextFormatTest, CustomPrinterForComments) { class CustomMultilineCommentPrinter : public TextFormat::FieldValuePrinter { public: - virtual string PrintMessageStart(const Message& message, - int field_index, - int field_count, - bool single_line_comment) const { + virtual std::string PrintMessageStart(const Message& message, int field_index, + int field_count, + bool single_line_comment) const { return StrCat(" { # 1\n", " # 2\n"); } }; @@ -548,7 +557,7 @@ TEST_F(TextFormatTest, CustomPrinterForMultilineComments) { TextFormat::Printer printer; CustomMessageFieldValuePrinter my_field_printer; printer.SetDefaultFieldValuePrinter(new CustomMultilineCommentPrinter()); - string text; + std::string text; printer.PrintToString(message, &text); EXPECT_EQ( "optional_nested_message { # 1\n" @@ -574,6 +583,11 @@ class CompactRepeatedFieldPrinter : public TextFormat::FastFieldValuePrinter { generator->PrintString(field->name()); } } + // To prevent compiler complaining about Woverloaded-virtual + void PrintFieldName(const Message& message, const Reflection* reflection, + const FieldDescriptor* field, + TextFormat::BaseTextGenerator* generator) const override { + } void PrintMessageStart( const Message& message, int field_index, int field_count, bool single_line_mode, @@ -614,7 +628,7 @@ TEST_F(TextFormatTest, CompactRepeatedFieldPrinter) { message.add_repeated_nested_message()->set_bb(2); message.add_repeated_nested_message()->set_bb(3); - string text; + std::string text; ASSERT_TRUE(printer.PrintToString(message, &text)); EXPECT_EQ( "repeated_nested_message {\n" @@ -629,12 +643,12 @@ TEST_F(TextFormatTest, CompactRepeatedFieldPrinter) { // BaseTextGenerator::Indent and BaseTextGenerator::Outdent. class MultilineStringPrinter : public TextFormat::FastFieldValuePrinter { public: - void PrintString(const string& val, + void PrintString(const std::string& val, TextFormat::BaseTextGenerator* generator) const override { generator->Indent(); int last_pos = 0; int newline_pos = val.find('\n'); - while (newline_pos != string::npos) { + while (newline_pos != std::string::npos) { generator->PrintLiteral("\n"); TextFormat::FastFieldValuePrinter::PrintString( val.substr(last_pos, newline_pos + 1 - last_pos), generator); @@ -662,7 +676,7 @@ TEST_F(TextFormatTest, MultilineStringPrinter) { protobuf_unittest::TestAllTypes message; message.set_optional_string("first line\nsecond line\nthird line"); - string text; + std::string text; ASSERT_TRUE(printer.PrintToString(message, &text)); EXPECT_EQ( "optional_string: \n" @@ -689,7 +703,7 @@ TEST_F(TextFormatTest, CustomMessagePrinter) { new CustomNestedMessagePrinter); unittest::TestAllTypes message; - string text; + std::string text; EXPECT_TRUE(printer.PrintToString(message, &text)); EXPECT_EQ("", text); @@ -714,8 +728,8 @@ TEST_F(TextFormatExtensionsTest, ParseExtensions) { TEST_F(TextFormatTest, ParseEnumFieldFromNumber) { // Create a parse string with a numerical value for an enum field. - string parse_string = strings::Substitute("optional_nested_enum: $0", - unittest::TestAllTypes::BAZ); + std::string parse_string = strings::Substitute("optional_nested_enum: $0", + unittest::TestAllTypes::BAZ); EXPECT_TRUE(TextFormat::ParseFromString(parse_string, &proto_)); EXPECT_TRUE(proto_.has_optional_nested_enum()); EXPECT_EQ(unittest::TestAllTypes::BAZ, proto_.optional_nested_enum()); @@ -723,22 +737,52 @@ TEST_F(TextFormatTest, ParseEnumFieldFromNumber) { TEST_F(TextFormatTest, ParseEnumFieldFromNegativeNumber) { ASSERT_LT(unittest::SPARSE_E, 0); - string parse_string = strings::Substitute("sparse_enum: $0", - unittest::SPARSE_E); + std::string parse_string = + strings::Substitute("sparse_enum: $0", unittest::SPARSE_E); unittest::SparseEnumMessage proto; EXPECT_TRUE(TextFormat::ParseFromString(parse_string, &proto)); EXPECT_TRUE(proto.has_sparse_enum()); EXPECT_EQ(unittest::SPARSE_E, proto.sparse_enum()); } +TEST_F(TextFormatTest, PrintUnknownEnumFieldProto3) { + proto3_unittest::TestAllTypes proto; + + proto.add_repeated_nested_enum( + static_cast(10)); + proto.add_repeated_nested_enum( + static_cast(-10)); + proto.add_repeated_nested_enum( + static_cast(2147483647)); + proto.add_repeated_nested_enum( + static_cast(-2147483648)); + + EXPECT_EQ( + "repeated_nested_enum: 10\n" + "repeated_nested_enum: -10\n" + "repeated_nested_enum: 2147483647\n" + "repeated_nested_enum: -2147483648\n", + proto.DebugString()); +} + +TEST_F(TextFormatTest, ParseUnknownEnumFieldProto3) { + proto3_unittest::TestAllTypes proto; + std::string parse_string = + "repeated_nested_enum: [10, -10, 2147483647, -2147483648]"; + EXPECT_TRUE(TextFormat::ParseFromString(parse_string, &proto)); + ASSERT_EQ(4, proto.repeated_nested_enum_size()); + EXPECT_EQ(10, proto.repeated_nested_enum(0)); + EXPECT_EQ(-10, proto.repeated_nested_enum(1)); + EXPECT_EQ(2147483647, proto.repeated_nested_enum(2)); + EXPECT_EQ(-2147483648, proto.repeated_nested_enum(3)); +} + TEST_F(TextFormatTest, ParseStringEscape) { // Create a parse string with escpaed characters in it. - string parse_string = "optional_string: " - + kEscapeTestStringEscaped - + "\n"; + std::string parse_string = + "optional_string: " + kEscapeTestStringEscaped + "\n"; - io::ArrayInputStream input_stream(parse_string.data(), - parse_string.size()); + io::ArrayInputStream input_stream(parse_string.data(), parse_string.size()); TextFormat::Parse(&input_stream, &proto_); // Compare. @@ -747,21 +791,20 @@ TEST_F(TextFormatTest, ParseStringEscape) { TEST_F(TextFormatTest, ParseConcatenatedString) { // Create a parse string with multiple parts on one line. - string parse_string = "optional_string: \"foo\" \"bar\"\n"; + std::string parse_string = "optional_string: \"foo\" \"bar\"\n"; - io::ArrayInputStream input_stream1(parse_string.data(), - parse_string.size()); + io::ArrayInputStream input_stream1(parse_string.data(), parse_string.size()); TextFormat::Parse(&input_stream1, &proto_); // Compare. EXPECT_EQ("foobar", proto_.optional_string()); // Create a parse string with multiple parts on separate lines. - parse_string = "optional_string: \"foo\"\n" - "\"bar\"\n"; + parse_string = + "optional_string: \"foo\"\n" + "\"bar\"\n"; - io::ArrayInputStream input_stream2(parse_string.data(), - parse_string.size()); + io::ArrayInputStream input_stream2(parse_string.data(), parse_string.size()); TextFormat::Parse(&input_stream2, &proto_); // Compare. @@ -773,10 +816,9 @@ TEST_F(TextFormatTest, ParseFloatWithSuffix) { // end. This is needed for backwards-compatibility with proto1. // Have it parse a float with the 'f' suffix. - string parse_string = "optional_float: 1.0f\n"; + std::string parse_string = "optional_float: 1.0f\n"; - io::ArrayInputStream input_stream(parse_string.data(), - parse_string.size()); + io::ArrayInputStream input_stream(parse_string.data(), parse_string.size()); TextFormat::Parse(&input_stream, &proto_); @@ -785,7 +827,7 @@ TEST_F(TextFormatTest, ParseFloatWithSuffix) { } TEST_F(TextFormatTest, ParseShortRepeatedForm) { - string parse_string = + std::string parse_string = // Mixed short-form and long-form are simply concatenated. "repeated_int32: 1\n" "repeated_int32: [456, 789]\n" @@ -825,7 +867,7 @@ TEST_F(TextFormatTest, ParseShortRepeatedForm) { } TEST_F(TextFormatTest, ParseShortRepeatedWithTrailingComma) { - string parse_string = "repeated_int32: [456,]\n"; + std::string parse_string = "repeated_int32: [456,]\n"; ASSERT_FALSE(TextFormat::ParseFromString(parse_string, &proto_)); parse_string = "repeated_nested_enum: [ FOO , ]"; ASSERT_FALSE(TextFormat::ParseFromString(parse_string, &proto_)); @@ -837,7 +879,7 @@ TEST_F(TextFormatTest, ParseShortRepeatedWithTrailingComma) { } TEST_F(TextFormatTest, ParseShortRepeatedEmpty) { - string parse_string = + std::string parse_string = "repeated_int32: []\n" "repeated_nested_enum: []\n" "repeated_string: []\n" @@ -854,7 +896,7 @@ TEST_F(TextFormatTest, ParseShortRepeatedEmpty) { } TEST_F(TextFormatTest, ParseShortRepeatedConcatenatedWithEmpty) { - string parse_string = + std::string parse_string = // Starting with empty [] should have no impact. "repeated_int32: []\n" "repeated_nested_enum: []\n" @@ -909,11 +951,11 @@ TEST_F(TextFormatTest, ParseShortRepeatedConcatenatedWithEmpty) { TEST_F(TextFormatTest, Comments) { // Test that comments are ignored. - string parse_string = "optional_int32: 1 # a comment\n" - "optional_int64: 2 # another comment"; + std::string parse_string = + "optional_int32: 1 # a comment\n" + "optional_int64: 2 # another comment"; - io::ArrayInputStream input_stream(parse_string.data(), - parse_string.size()); + io::ArrayInputStream input_stream(parse_string.data(), parse_string.size()); TextFormat::Parse(&input_stream, &proto_); @@ -926,10 +968,9 @@ TEST_F(TextFormatTest, OptionalColon) { // Test that we can place a ':' after the field name of a nested message, // even though we don't have to. - string parse_string = "optional_nested_message: { bb: 1}\n"; + std::string parse_string = "optional_nested_message: { bb: 1}\n"; - io::ArrayInputStream input_stream(parse_string.data(), - parse_string.size()); + io::ArrayInputStream input_stream(parse_string.data(), parse_string.size()); TextFormat::Parse(&input_stream, &proto_); @@ -940,7 +981,7 @@ TEST_F(TextFormatTest, OptionalColon) { // Some platforms (e.g. Windows) insist on padding the exponent to three // digits when one or two would be just fine. -static string RemoveRedundantZeros(string text) { +static std::string RemoveRedundantZeros(std::string text) { text = StringReplace(text, "e+0", "e+", true); text = StringReplace(text, "e-0", "e-", true); return text; @@ -954,15 +995,15 @@ TEST_F(TextFormatTest, PrintExotic) { // 9223372036854775808 is outside the range of int64. However, it is not // outside the range of uint64. Confusingly, this means that everything // works if we make the literal unsigned, even though we are negating it. - message.add_repeated_int64(-GOOGLE_ULONGLONG(9223372036854775808)); - message.add_repeated_uint64(GOOGLE_ULONGLONG(18446744073709551615)); + message.add_repeated_int64(-PROTOBUF_ULONGLONG(9223372036854775808)); + message.add_repeated_uint64(PROTOBUF_ULONGLONG(18446744073709551615)); message.add_repeated_double(123.456); message.add_repeated_double(1.23e21); message.add_repeated_double(1.23e-18); message.add_repeated_double(std::numeric_limits::infinity()); message.add_repeated_double(-std::numeric_limits::infinity()); message.add_repeated_double(std::numeric_limits::quiet_NaN()); - message.add_repeated_string(string("\000\001\a\b\f\n\r\t\v\\\'\"", 12)); + message.add_repeated_string(std::string("\000\001\a\b\f\n\r\t\v\\\'\"", 12)); // Fun story: We used to use 1.23e22 instead of 1.23e21 above, but this // seemed to trigger an odd case on MinGW/GCC 3.4.5 where GCC's parsing of @@ -976,21 +1017,23 @@ TEST_F(TextFormatTest, PrintExotic) { // have this problem, so we switched to that instead. EXPECT_EQ( - "repeated_int64: -9223372036854775808\n" - "repeated_uint64: 18446744073709551615\n" - "repeated_double: 123.456\n" - "repeated_double: 1.23e+21\n" - "repeated_double: 1.23e-18\n" - "repeated_double: inf\n" - "repeated_double: -inf\n" - "repeated_double: nan\n" - "repeated_string: \"\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\'\\\"\"\n", - RemoveRedundantZeros(message.DebugString())); + "repeated_int64: -9223372036854775808\n" + "repeated_uint64: 18446744073709551615\n" + "repeated_double: 123.456\n" + "repeated_double: 1.23e+21\n" + "repeated_double: 1.23e-18\n" + "repeated_double: inf\n" + "repeated_double: -inf\n" + "repeated_double: nan\n" + "repeated_string: " + "\"\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\'\\\"\"\n", + RemoveRedundantZeros(message.DebugString())); } TEST_F(TextFormatTest, PrintFloatPrecision) { unittest::TestAllTypes message; + message.add_repeated_float(1.0); message.add_repeated_float(1.2); message.add_repeated_float(1.23); message.add_repeated_float(1.234); @@ -1031,48 +1074,48 @@ TEST_F(TextFormatTest, PrintFloatPrecision) { message.add_repeated_double(1.23456789876543e100); EXPECT_EQ( - "repeated_float: 1.2\n" - "repeated_float: 1.23\n" - "repeated_float: 1.234\n" - "repeated_float: 1.2345\n" - "repeated_float: 1.23456\n" - "repeated_float: 1.2e+10\n" - "repeated_float: 1.23e+10\n" - "repeated_float: 1.234e+10\n" - "repeated_float: 1.2345e+10\n" - "repeated_float: 1.23456e+10\n" - "repeated_double: 1.2\n" - "repeated_double: 1.23\n" - "repeated_double: 1.234\n" - "repeated_double: 1.2345\n" - "repeated_double: 1.23456\n" - "repeated_double: 1.234567\n" - "repeated_double: 1.2345678\n" - "repeated_double: 1.23456789\n" - "repeated_double: 1.234567898\n" - "repeated_double: 1.2345678987\n" - "repeated_double: 1.23456789876\n" - "repeated_double: 1.234567898765\n" - "repeated_double: 1.2345678987654\n" - "repeated_double: 1.23456789876543\n" - "repeated_double: 1.2e+100\n" - "repeated_double: 1.23e+100\n" - "repeated_double: 1.234e+100\n" - "repeated_double: 1.2345e+100\n" - "repeated_double: 1.23456e+100\n" - "repeated_double: 1.234567e+100\n" - "repeated_double: 1.2345678e+100\n" - "repeated_double: 1.23456789e+100\n" - "repeated_double: 1.234567898e+100\n" - "repeated_double: 1.2345678987e+100\n" - "repeated_double: 1.23456789876e+100\n" - "repeated_double: 1.234567898765e+100\n" - "repeated_double: 1.2345678987654e+100\n" - "repeated_double: 1.23456789876543e+100\n", - RemoveRedundantZeros(message.DebugString())); + "repeated_float: 1\n" + "repeated_float: 1.2\n" + "repeated_float: 1.23\n" + "repeated_float: 1.234\n" + "repeated_float: 1.2345\n" + "repeated_float: 1.23456\n" + "repeated_float: 1.2e+10\n" + "repeated_float: 1.23e+10\n" + "repeated_float: 1.234e+10\n" + "repeated_float: 1.2345e+10\n" + "repeated_float: 1.23456e+10\n" + "repeated_double: 1.2\n" + "repeated_double: 1.23\n" + "repeated_double: 1.234\n" + "repeated_double: 1.2345\n" + "repeated_double: 1.23456\n" + "repeated_double: 1.234567\n" + "repeated_double: 1.2345678\n" + "repeated_double: 1.23456789\n" + "repeated_double: 1.234567898\n" + "repeated_double: 1.2345678987\n" + "repeated_double: 1.23456789876\n" + "repeated_double: 1.234567898765\n" + "repeated_double: 1.2345678987654\n" + "repeated_double: 1.23456789876543\n" + "repeated_double: 1.2e+100\n" + "repeated_double: 1.23e+100\n" + "repeated_double: 1.234e+100\n" + "repeated_double: 1.2345e+100\n" + "repeated_double: 1.23456e+100\n" + "repeated_double: 1.234567e+100\n" + "repeated_double: 1.2345678e+100\n" + "repeated_double: 1.23456789e+100\n" + "repeated_double: 1.234567898e+100\n" + "repeated_double: 1.2345678987e+100\n" + "repeated_double: 1.23456789876e+100\n" + "repeated_double: 1.234567898765e+100\n" + "repeated_double: 1.2345678987654e+100\n" + "repeated_double: 1.23456789876543e+100\n", + RemoveRedundantZeros(message.DebugString())); } - TEST_F(TextFormatTest, AllowPartial) { unittest::TestRequired message; TextFormat::Parser parser; @@ -1086,29 +1129,29 @@ TEST_F(TextFormatTest, AllowPartial) { TEST_F(TextFormatTest, ParseExotic) { unittest::TestAllTypes message; ASSERT_TRUE(TextFormat::ParseFromString( - "repeated_int32: -1\n" - "repeated_int32: -2147483648\n" - "repeated_int64: -1\n" - "repeated_int64: -9223372036854775808\n" - "repeated_uint32: 4294967295\n" - "repeated_uint32: 2147483648\n" - "repeated_uint64: 18446744073709551615\n" - "repeated_uint64: 9223372036854775808\n" - "repeated_double: 123.0\n" - "repeated_double: 123.5\n" - "repeated_double: 0.125\n" - "repeated_double: 1.23E17\n" - "repeated_double: 1.235E+22\n" - "repeated_double: 1.235e-18\n" - "repeated_double: 123.456789\n" - "repeated_double: inf\n" - "repeated_double: Infinity\n" - "repeated_double: -inf\n" - "repeated_double: -Infinity\n" - "repeated_double: nan\n" - "repeated_double: NaN\n" - "repeated_string: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\"\n", - &message)); + "repeated_int32: -1\n" + "repeated_int32: -2147483648\n" + "repeated_int64: -1\n" + "repeated_int64: -9223372036854775808\n" + "repeated_uint32: 4294967295\n" + "repeated_uint32: 2147483648\n" + "repeated_uint64: 18446744073709551615\n" + "repeated_uint64: 9223372036854775808\n" + "repeated_double: 123.0\n" + "repeated_double: 123.5\n" + "repeated_double: 0.125\n" + "repeated_double: 1.23E17\n" + "repeated_double: 1.235E+22\n" + "repeated_double: 1.235e-18\n" + "repeated_double: 123.456789\n" + "repeated_double: inf\n" + "repeated_double: Infinity\n" + "repeated_double: -inf\n" + "repeated_double: -Infinity\n" + "repeated_double: nan\n" + "repeated_double: NaN\n" + "repeated_string: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\"\n", + &message)); ASSERT_EQ(2, message.repeated_int32_size()); EXPECT_EQ(-1, message.repeated_int32(0)); @@ -1126,23 +1169,26 @@ TEST_F(TextFormatTest, ParseExotic) { // 9223372036854775808 is outside the range of int64. However, it is not // outside the range of uint64. Confusingly, this means that everything // works if we make the literal unsigned, even though we are negating it. - EXPECT_EQ(-GOOGLE_ULONGLONG(9223372036854775808), message.repeated_int64(1)); + EXPECT_EQ(-PROTOBUF_ULONGLONG(9223372036854775808), + message.repeated_int64(1)); ASSERT_EQ(2, message.repeated_uint32_size()); EXPECT_EQ(4294967295u, message.repeated_uint32(0)); EXPECT_EQ(2147483648u, message.repeated_uint32(1)); ASSERT_EQ(2, message.repeated_uint64_size()); - EXPECT_EQ(GOOGLE_ULONGLONG(18446744073709551615), message.repeated_uint64(0)); - EXPECT_EQ(GOOGLE_ULONGLONG(9223372036854775808), message.repeated_uint64(1)); + EXPECT_EQ(PROTOBUF_ULONGLONG(18446744073709551615), + message.repeated_uint64(0)); + EXPECT_EQ(PROTOBUF_ULONGLONG(9223372036854775808), + message.repeated_uint64(1)); ASSERT_EQ(13, message.repeated_double_size()); - EXPECT_EQ(123.0 , message.repeated_double(0)); - EXPECT_EQ(123.5 , message.repeated_double(1)); - EXPECT_EQ(0.125 , message.repeated_double(2)); - EXPECT_EQ(1.23E17 , message.repeated_double(3)); - EXPECT_EQ(1.235E22 , message.repeated_double(4)); - EXPECT_EQ(1.235E-18 , message.repeated_double(5)); + EXPECT_EQ(123.0, message.repeated_double(0)); + EXPECT_EQ(123.5, message.repeated_double(1)); + EXPECT_EQ(0.125, message.repeated_double(2)); + EXPECT_EQ(1.23E17, message.repeated_double(3)); + EXPECT_EQ(1.235E22, message.repeated_double(4)); + EXPECT_EQ(1.235E-18, message.repeated_double(5)); EXPECT_EQ(123.456789, message.repeated_double(6)); EXPECT_EQ(message.repeated_double(7), std::numeric_limits::infinity()); @@ -1156,18 +1202,30 @@ TEST_F(TextFormatTest, ParseExotic) { EXPECT_TRUE(MathLimits::IsNaN(message.repeated_double(12))); // Note: Since these string literals have \0's in them, we must explicitly - // pass their sizes to string's constructor. + // pass their sizes to string's constructor. ASSERT_EQ(1, message.repeated_string_size()); - EXPECT_EQ(string("\000\001\a\b\f\n\r\t\v\\\'\"", 12), + EXPECT_EQ(std::string("\000\001\a\b\f\n\r\t\v\\\'\"", 12), message.repeated_string(0)); + + ASSERT_TRUE( + TextFormat::ParseFromString("repeated_float: 3.4028235e+38\n" + "repeated_float: -3.4028235e+38\n" + "repeated_float: 3.402823567797337e+38\n" + "repeated_float: -3.402823567797337e+38\n", + &message)); + EXPECT_EQ(message.repeated_float(0), std::numeric_limits::max()); + EXPECT_EQ(message.repeated_float(1), -std::numeric_limits::max()); + EXPECT_EQ(message.repeated_float(2), std::numeric_limits::infinity()); + EXPECT_EQ(message.repeated_float(3), -std::numeric_limits::infinity()); + } TEST_F(TextFormatTest, PrintFieldsInIndexOrder) { protobuf_unittest::TestFieldOrderings message; // Fields are listed in index order instead of field number. - message.set_my_string("str"); // Field number 11 - message.set_my_int(12345); // Field number 1 - message.set_my_float(0.999); // Field number 101 + message.set_my_string("str"); // Field number 11 + message.set_my_int(12345); // Field number 1 + message.set_my_float(0.999); // Field number 101 // Extensions are listed based on the order of extension number. // Extension number 12. message @@ -1188,7 +1246,7 @@ TEST_F(TextFormatTest, PrintFieldsInIndexOrder) { *message.MutableExtension(protobuf_unittest::my_extension_string) = "ext_str0"; TextFormat::Printer printer; - string text; + std::string text; // By default, print in field number order. // my_int: 12345 @@ -1249,43 +1307,44 @@ TEST_F(TextFormatTest, PrintFieldsInIndexOrder) { class TextFormatParserTest : public testing::Test { protected: - void ExpectFailure(const string& input, const string& message, int line, - int col) { + void ExpectFailure(const std::string& input, const std::string& message, + int line, int col) { std::unique_ptr proto(new unittest::TestAllTypes); ExpectFailure(input, message, line, col, proto.get()); } - void ExpectFailure(const string& input, const string& message, int line, - int col, Message* proto) { + void ExpectFailure(const std::string& input, const std::string& message, + int line, int col, Message* proto) { ExpectMessage(input, message, line, col, proto, false); } - void ExpectMessage(const string& input, const string& message, int line, - int col, Message* proto, bool expected_result) { - TextFormat::Parser parser; + void ExpectMessage(const std::string& input, const std::string& message, + int line, int col, Message* proto, bool expected_result) { MockErrorCollector error_collector; - parser.RecordErrorsTo(&error_collector); - EXPECT_EQ(expected_result, parser.ParseFromString(input, proto)) + parser_.RecordErrorsTo(&error_collector); + EXPECT_EQ(expected_result, parser_.ParseFromString(input, proto)) << input << " -> " << proto->DebugString(); - EXPECT_EQ(SimpleItoa(line) + ":" + SimpleItoa(col) + ": " + message + "\n", - error_collector.text_); + EXPECT_EQ( + StrCat(line) + ":" + StrCat(col) + ": " + message + "\n", + error_collector.text_); + parser_.RecordErrorsTo(nullptr); } - void ExpectSuccessAndTree(const string& input, Message* proto, + void ExpectSuccessAndTree(const std::string& input, Message* proto, TextFormat::ParseInfoTree* info_tree) { - TextFormat::Parser parser; MockErrorCollector error_collector; - parser.RecordErrorsTo(&error_collector); - parser.WriteLocationsTo(info_tree); - - EXPECT_TRUE(parser.ParseFromString(input, proto)); + parser_.RecordErrorsTo(&error_collector); + parser_.WriteLocationsTo(info_tree); + EXPECT_TRUE(parser_.ParseFromString(input, proto)); + parser_.WriteLocationsTo(nullptr); + parser_.RecordErrorsTo(nullptr); } - void ExpectLocation(TextFormat::ParseInfoTree* tree, - const Descriptor* d, const string& field_name, - int index, int line, int column) { - TextFormat::ParseLocation location = tree->GetLocation( - d->FindFieldByName(field_name), index); + void ExpectLocation(TextFormat::ParseInfoTree* tree, const Descriptor* d, + const std::string& field_name, int index, int line, + int column) { + TextFormat::ParseLocation location = + tree->GetLocation(d->FindFieldByName(field_name), index); EXPECT_EQ(line, location.line); EXPECT_EQ(column, location.column); } @@ -1297,25 +1356,27 @@ class TextFormatParserTest : public testing::Test { MockErrorCollector() {} ~MockErrorCollector() {} - string text_; + std::string text_; // implements ErrorCollector ------------------------------------- - void AddError(int line, int column, const string& message) { - strings::SubstituteAndAppend(&text_, "$0:$1: $2\n", - line + 1, column + 1, message); + void AddError(int line, int column, const std::string& message) { + strings::SubstituteAndAppend(&text_, "$0:$1: $2\n", line + 1, column + 1, + message); } - void AddWarning(int line, int column, const string& message) { + void AddWarning(int line, int column, const std::string& message) { AddError(line, column, "WARNING:" + message); } }; + + TextFormat::Parser parser_; }; TEST_F(TextFormatParserTest, ParseInfoTreeBuilding) { std::unique_ptr message(new unittest::TestAllTypes); const Descriptor* d = message->GetDescriptor(); - string stringData = + std::string stringData = "optional_int32: 1\n" "optional_int64: 2\n" " optional_double: 2.4\n" @@ -1331,7 +1392,6 @@ TEST_F(TextFormatParserTest, ParseInfoTreeBuilding) { " bb: 80\n" ">"; - TextFormat::ParseInfoTree tree; ExpectSuccessAndTree(stringData, message.get(), &tree); @@ -1380,33 +1440,33 @@ TEST_F(TextFormatParserTest, ParseFieldValueFromString) { std::unique_ptr message(new unittest::TestAllTypes); const Descriptor* d = message->GetDescriptor(); -#define EXPECT_FIELD(name, value, valuestring) \ - EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \ - valuestring, d->FindFieldByName("optional_" #name), message.get())); \ - EXPECT_EQ(value, message->optional_##name()); \ +#define EXPECT_FIELD(name, value, valuestring) \ + EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \ + valuestring, d->FindFieldByName("optional_" #name), message.get())); \ + EXPECT_EQ(value, message->optional_##name()); \ EXPECT_TRUE(message->has_optional_##name()); -#define EXPECT_BOOL_FIELD(name, value, valuestring) \ - EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \ - valuestring, d->FindFieldByName("optional_" #name), message.get())); \ - EXPECT_TRUE(message->optional_##name() == value); \ +#define EXPECT_BOOL_FIELD(name, value, valuestring) \ + EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \ + valuestring, d->FindFieldByName("optional_" #name), message.get())); \ + EXPECT_TRUE(message->optional_##name() == value); \ EXPECT_TRUE(message->has_optional_##name()); -#define EXPECT_FLOAT_FIELD(name, value, valuestring) \ - EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \ - valuestring, d->FindFieldByName("optional_" #name), message.get())); \ - EXPECT_FLOAT_EQ(value, message->optional_##name()); \ +#define EXPECT_FLOAT_FIELD(name, value, valuestring) \ + EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \ + valuestring, d->FindFieldByName("optional_" #name), message.get())); \ + EXPECT_FLOAT_EQ(value, message->optional_##name()); \ EXPECT_TRUE(message->has_optional_##name()); -#define EXPECT_DOUBLE_FIELD(name, value, valuestring) \ - EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \ - valuestring, d->FindFieldByName("optional_" #name), message.get())); \ - EXPECT_DOUBLE_EQ(value, message->optional_##name()); \ +#define EXPECT_DOUBLE_FIELD(name, value, valuestring) \ + EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \ + valuestring, d->FindFieldByName("optional_" #name), message.get())); \ + EXPECT_DOUBLE_EQ(value, message->optional_##name()); \ EXPECT_TRUE(message->has_optional_##name()); -#define EXPECT_INVALID(name, valuestring) \ +#define EXPECT_INVALID(name, valuestring) \ EXPECT_FALSE(TextFormat::ParseFieldValueFromString( \ - valuestring, d->FindFieldByName("optional_" #name), message.get())); + valuestring, d->FindFieldByName("optional_" #name), message.get())); // int32 EXPECT_FIELD(int32, 1, "1"); @@ -1491,13 +1551,13 @@ TEST_F(TextFormatParserTest, ParseFieldValueFromString) { // enum EXPECT_FIELD(nested_enum, unittest::TestAllTypes::BAR, "BAR"); EXPECT_FIELD(nested_enum, unittest::TestAllTypes::BAZ, - SimpleItoa(unittest::TestAllTypes::BAZ)); + StrCat(unittest::TestAllTypes::BAZ)); EXPECT_INVALID(nested_enum, "FOOBAR"); // message EXPECT_TRUE(TextFormat::ParseFieldValueFromString( - "", d->FindFieldByName("optional_nested_message"), message.get())); - EXPECT_EQ(12, message->optional_nested_message().bb()); \ + "", d->FindFieldByName("optional_nested_message"), message.get())); + EXPECT_EQ(12, message->optional_nested_message().bb()); EXPECT_TRUE(message->has_optional_nested_message()); EXPECT_INVALID(nested_message, "any"); @@ -1508,15 +1568,13 @@ TEST_F(TextFormatParserTest, ParseFieldValueFromString) { #undef EXPECT_INVALID } - TEST_F(TextFormatParserTest, InvalidToken) { - ExpectFailure("optional_bool: true\n-5\n", "Expected identifier, got: -", - 2, 1); + ExpectFailure("optional_bool: true\n-5\n", "Expected identifier, got: -", 2, + 1); - ExpectFailure("optional_bool: true!\n", "Expected identifier, got: !", 1, - 20); - ExpectFailure("\"some string\"", - "Expected identifier, got: \"some string\"", 1, 1); + ExpectFailure("optional_bool: true!\n", "Expected identifier, got: !", 1, 20); + ExpectFailure("\"some string\"", "Expected identifier, got: \"some string\"", + 1, 1); } TEST_F(TextFormatParserTest, InvalidFieldName) { @@ -1566,11 +1624,10 @@ TEST_F(TextFormatParserTest, InvalidFieldValues) { // Invalid values for a double/float field. ExpectFailure("optional_double: \"hello\"\n", "Expected double, got: \"hello\"", 1, 18); - ExpectFailure("optional_double: true\n", "Expected double, got: true", 1, - 18); + ExpectFailure("optional_double: true\n", "Expected double, got: true", 1, 18); ExpectFailure("optional_double: !\n", "Expected double, got: !", 1, 18); - ExpectFailure("optional_double {\n \n}\n", "Expected \":\", found \"{\".", - 1, 17); + ExpectFailure("optional_double {\n \n}\n", "Expected \":\", found \"{\".", 1, + 17); // Invalid values for a signed integer field. ExpectFailure("optional_int32: \"hello\"\n", @@ -1578,8 +1635,8 @@ TEST_F(TextFormatParserTest, InvalidFieldValues) { ExpectFailure("optional_int32: true\n", "Expected integer, got: true", 1, 17); ExpectFailure("optional_int32: 4.5\n", "Expected integer, got: 4.5", 1, 17); ExpectFailure("optional_int32: !\n", "Expected integer, got: !", 1, 17); - ExpectFailure("optional_int32 {\n \n}\n", "Expected \":\", found \"{\".", - 1, 16); + ExpectFailure("optional_int32 {\n \n}\n", "Expected \":\", found \"{\".", 1, + 16); ExpectFailure("optional_int32: 0x80000000\n", "Integer out of range (0x80000000)", 1, 17); ExpectFailure("optional_int64: 0x8000000000000000\n", @@ -1592,13 +1649,13 @@ TEST_F(TextFormatParserTest, InvalidFieldValues) { // Invalid values for an unsigned integer field. ExpectFailure("optional_uint64: \"hello\"\n", "Expected integer, got: \"hello\"", 1, 18); - ExpectFailure("optional_uint64: true\n", - "Expected integer, got: true", 1, 18); + ExpectFailure("optional_uint64: true\n", "Expected integer, got: true", 1, + 18); ExpectFailure("optional_uint64: 4.5\n", "Expected integer, got: 4.5", 1, 18); ExpectFailure("optional_uint64: -5\n", "Expected integer, got: -", 1, 18); ExpectFailure("optional_uint64: !\n", "Expected integer, got: !", 1, 18); - ExpectFailure("optional_uint64 {\n \n}\n", "Expected \":\", found \"{\".", - 1, 17); + ExpectFailure("optional_uint64 {\n \n}\n", "Expected \":\", found \"{\".", 1, + 17); ExpectFailure("optional_uint32: 0x100000000\n", "Integer out of range (0x100000000)", 1, 18); ExpectFailure("optional_uint64: 0x10000000000000000\n", @@ -1613,19 +1670,19 @@ TEST_F(TextFormatParserTest, InvalidFieldValues) { ExpectFailure( "optional_bool: meh\n", - "Invalid value for boolean field \"optional_bool\". Value: \"meh\".", - 2, 1); + "Invalid value for boolean field \"optional_bool\". Value: \"meh\".", 2, + 1); - ExpectFailure("optional_bool {\n \n}\n", "Expected \":\", found \"{\".", - 1, 15); + ExpectFailure("optional_bool {\n \n}\n", "Expected \":\", found \"{\".", 1, + 15); // Invalid values for a string field. ExpectFailure("optional_string: true\n", "Expected string, got: true", 1, 18); ExpectFailure("optional_string: 5\n", "Expected string, got: 5", 1, 18); ExpectFailure("optional_string: -7.5\n", "Expected string, got: -", 1, 18); ExpectFailure("optional_string: !\n", "Expected string, got: !", 1, 18); - ExpectFailure("optional_string {\n \n}\n", "Expected \":\", found \"{\".", - 1, 17); + ExpectFailure("optional_string {\n \n}\n", "Expected \":\", found \"{\".", 1, + 17); // Invalid values for an enumeration field. ExpectFailure("optional_nested_enum: \"hello\"\n", @@ -1634,7 +1691,8 @@ TEST_F(TextFormatParserTest, InvalidFieldValues) { // Valid token, but enum value is not defined. ExpectFailure("optional_nested_enum: 5\n", "Unknown enumeration value of \"5\" for field " - "\"optional_nested_enum\".", 2, 1); + "\"optional_nested_enum\".", + 2, 1); // We consume the negative sign, so the error position starts one character // later. ExpectFailure("optional_nested_enum: -7.5\n", "Expected integer, got: 7.5", 1, @@ -1642,29 +1700,27 @@ TEST_F(TextFormatParserTest, InvalidFieldValues) { ExpectFailure("optional_nested_enum: !\n", "Expected integer or identifier, got: !", 1, 23); - ExpectFailure( - "optional_nested_enum: grah\n", - "Unknown enumeration value of \"grah\" for field " - "\"optional_nested_enum\".", 2, 1); + ExpectFailure("optional_nested_enum: grah\n", + "Unknown enumeration value of \"grah\" for field " + "\"optional_nested_enum\".", + 2, 1); - ExpectFailure( - "optional_nested_enum {\n \n}\n", - "Expected \":\", found \"{\".", 1, 22); + ExpectFailure("optional_nested_enum {\n \n}\n", + "Expected \":\", found \"{\".", 1, 22); } TEST_F(TextFormatParserTest, MessageDelimiters) { // Non-matching delimiters. - ExpectFailure("OptionalGroup <\n \n}\n", "Expected \">\", found \"}\".", - 3, 1); + ExpectFailure("OptionalGroup <\n \n}\n", "Expected \">\", found \"}\".", 3, + 1); // Invalid delimiters. - ExpectFailure("OptionalGroup [\n \n]\n", "Expected \"{\", found \"[\".", - 1, 15); + ExpectFailure("OptionalGroup [\n \n]\n", "Expected \"{\", found \"[\".", 1, + 15); // Unending message. ExpectFailure("optional_nested_message {\n \nbb: 118\n", - "Expected identifier, got: ", - 4, 1); + "Expected identifier, got: ", 4, 1); } TEST_F(TextFormatParserTest, UnknownExtension) { @@ -1677,23 +1733,22 @@ TEST_F(TextFormatParserTest, UnknownExtension) { TEST_F(TextFormatParserTest, MissingRequired) { unittest::TestRequired message; - ExpectFailure("a: 1", - "Message missing required fields: b, c", - 0, 1, &message); + ExpectFailure("a: 1", "Message missing required fields: b, c", 0, 1, + &message); } TEST_F(TextFormatParserTest, ParseDuplicateRequired) { unittest::TestRequired message; ExpectFailure("a: 1 b: 2 c: 3 a: 1", - "Non-repeated field \"a\" is specified multiple times.", - 1, 17, &message); + "Non-repeated field \"a\" is specified multiple times.", 1, 17, + &message); } TEST_F(TextFormatParserTest, ParseDuplicateOptional) { unittest::ForeignMessage message; ExpectFailure("c: 1 c: 2", - "Non-repeated field \"c\" is specified multiple times.", - 1, 7, &message); + "Non-repeated field \"c\" is specified multiple times.", 1, 7, + &message); } TEST_F(TextFormatParserTest, MergeDuplicateRequired) { @@ -1719,7 +1774,7 @@ TEST_F(TextFormatParserTest, ExplicitDelimiters) { } TEST_F(TextFormatParserTest, PrintErrorsToStderr) { - std::vector errors; + std::vector errors; { ScopedMemoryLog log; @@ -1729,14 +1784,15 @@ TEST_F(TextFormatParserTest, PrintErrorsToStderr) { } ASSERT_EQ(1, errors.size()); - EXPECT_EQ("Error parsing text-format protobuf_unittest.TestAllTypes: " - "1:14: Message type \"protobuf_unittest.TestAllTypes\" has no field " - "named \"no_such_field\".", - errors[0]); + EXPECT_EQ( + "Error parsing text-format protobuf_unittest.TestAllTypes: " + "1:14: Message type \"protobuf_unittest.TestAllTypes\" has no field " + "named \"no_such_field\".", + errors[0]); } TEST_F(TextFormatParserTest, FailsOnTokenizationError) { - std::vector errors; + std::vector errors; { ScopedMemoryLog log; @@ -1746,16 +1802,34 @@ TEST_F(TextFormatParserTest, FailsOnTokenizationError) { } ASSERT_EQ(1, errors.size()); - EXPECT_EQ("Error parsing text-format protobuf_unittest.TestAllTypes: " - "1:1: Invalid control characters encountered in text.", - errors[0]); + EXPECT_EQ( + "Error parsing text-format protobuf_unittest.TestAllTypes: " + "1:1: Invalid control characters encountered in text.", + errors[0]); } TEST_F(TextFormatParserTest, ParseDeprecatedField) { unittest::TestDeprecatedFields message; ExpectMessage("deprecated_int32: 42", "WARNING:text format contains deprecated field " - "\"deprecated_int32\"", 1, 21, &message, true); + "\"deprecated_int32\"", + 1, 21, &message, true); +} + +TEST_F(TextFormatParserTest, SetRecursionLimit) { + const char* format = "child: { $0 }"; + std::string input; + for (int i = 0; i < 100; ++i) input = strings::Substitute(format, input); + + unittest::NestedTestAllTypes message; + ExpectSuccessAndTree(input, &message, nullptr); + + input = strings::Substitute(format, input); + parser_.SetRecursionLimit(100); + ExpectMessage(input, "Message is too deep", 1, 908, &message, false); + + parser_.SetRecursionLimit(101); + ExpectSuccessAndTree(input, &message, nullptr); } class TextFormatMessageSetTest : public testing::Test { @@ -1763,25 +1837,24 @@ class TextFormatMessageSetTest : public testing::Test { static const char proto_debug_string_[]; }; const char TextFormatMessageSetTest::proto_debug_string_[] = -"message_set {\n" -" [protobuf_unittest.TestMessageSetExtension1] {\n" -" i: 23\n" -" }\n" -" [protobuf_unittest.TestMessageSetExtension2] {\n" -" str: \"foo\"\n" -" }\n" -"}\n"; - + "message_set {\n" + " [protobuf_unittest.TestMessageSetExtension1] {\n" + " i: 23\n" + " }\n" + " [protobuf_unittest.TestMessageSetExtension2] {\n" + " str: \"foo\"\n" + " }\n" + "}\n"; TEST_F(TextFormatMessageSetTest, Serialize) { protobuf_unittest::TestMessageSetContainer proto; protobuf_unittest::TestMessageSetExtension1* item_a = - proto.mutable_message_set()->MutableExtension( - protobuf_unittest::TestMessageSetExtension1::message_set_extension); + proto.mutable_message_set()->MutableExtension( + protobuf_unittest::TestMessageSetExtension1::message_set_extension); item_a->set_i(23); protobuf_unittest::TestMessageSetExtension2* item_b = - proto.mutable_message_set()->MutableExtension( - protobuf_unittest::TestMessageSetExtension2::message_set_extension); + proto.mutable_message_set()->MutableExtension( + protobuf_unittest::TestMessageSetExtension2::message_set_extension); item_b->set_str("foo"); EXPECT_EQ(proto_debug_string_, proto.DebugString()); } @@ -1789,18 +1862,165 @@ TEST_F(TextFormatMessageSetTest, Serialize) { TEST_F(TextFormatMessageSetTest, Deserialize) { protobuf_unittest::TestMessageSetContainer proto; ASSERT_TRUE(TextFormat::ParseFromString(proto_debug_string_, &proto)); - EXPECT_EQ(23, proto.message_set().GetExtension( - protobuf_unittest::TestMessageSetExtension1::message_set_extension).i()); - EXPECT_EQ("foo", proto.message_set().GetExtension( - protobuf_unittest::TestMessageSetExtension2::message_set_extension).str()); + EXPECT_EQ( + 23, + proto.message_set() + .GetExtension( + protobuf_unittest::TestMessageSetExtension1::message_set_extension) + .i()); + EXPECT_EQ( + "foo", + proto.message_set() + .GetExtension( + protobuf_unittest::TestMessageSetExtension2::message_set_extension) + .str()); // Ensure that these are the only entries present. std::vector descriptors; - proto.message_set().GetReflection()->ListFields( - proto.message_set(), &descriptors); + proto.message_set().GetReflection()->ListFields(proto.message_set(), + &descriptors); EXPECT_EQ(2, descriptors.size()); } +TEST(TextFormatUnknownFieldTest, TestUnknownField) { + protobuf_unittest::TestAllTypes proto; + TextFormat::Parser parser; + // Unknown field is not permitted by default. + EXPECT_FALSE(parser.ParseFromString("unknown_field: 12345", &proto)); + EXPECT_FALSE(parser.ParseFromString("12345678: 12345", &proto)); + + parser.AllowUnknownField(true); + EXPECT_TRUE(parser.ParseFromString("unknown_field: 12345", &proto)); + EXPECT_TRUE(parser.ParseFromString("unknown_field: -12345", &proto)); + EXPECT_TRUE(parser.ParseFromString("unknown_field: 1.2345", &proto)); + EXPECT_TRUE(parser.ParseFromString("unknown_field: -1.2345", &proto)); + EXPECT_TRUE(parser.ParseFromString("unknown_field: 1.2345f", &proto)); + EXPECT_TRUE(parser.ParseFromString("unknown_field: -1.2345f", &proto)); + EXPECT_TRUE(parser.ParseFromString("unknown_field: inf", &proto)); + EXPECT_TRUE(parser.ParseFromString("unknown_field: -inf", &proto)); + EXPECT_TRUE(parser.ParseFromString("unknown_field: TYPE_STRING", &proto)); + EXPECT_TRUE( + parser.ParseFromString("unknown_field: \"string value\"", &proto)); + // Invalid field value + EXPECT_FALSE(parser.ParseFromString("unknown_field: -TYPE_STRING", &proto)); + // Two or more unknown fields + EXPECT_TRUE( + parser.ParseFromString("unknown_field1: TYPE_STRING\n" + "unknown_field2: 12345", + &proto)); + // Unknown nested message + EXPECT_TRUE( + parser.ParseFromString("unknown_message1: {}\n" + "unknown_message2 {\n" + " unknown_field: 12345\n" + "}\n" + "unknown_message3 <\n" + " unknown_nested_message {\n" + " unknown_field: 12345\n" + " }\n" + ">", + &proto)); + // Unmatched delimeters for message body + EXPECT_FALSE(parser.ParseFromString("unknown_message: {>", &proto)); + // Unknown extension + EXPECT_TRUE( + parser.ParseFromString("[somewhere.unknown_extension1]: 12345\n" + "[somewhere.unknown_extension2] {\n" + " unknown_field: 12345\n" + "}", + &proto)); + // Unknown fields between known fields + ASSERT_TRUE( + parser.ParseFromString("optional_int32: 1\n" + "unknown_field: 12345\n" + "optional_string: \"string\"\n" + "unknown_message { unknown: 0 }\n" + "optional_nested_message { bb: 2 }", + &proto)); + EXPECT_EQ(1, proto.optional_int32()); + EXPECT_EQ("string", proto.optional_string()); + EXPECT_EQ(2, proto.optional_nested_message().bb()); + + // Unknown field with numeric tag number instead of identifier. + EXPECT_TRUE(parser.ParseFromString("12345678: 12345", &proto)); + + // Nested unknown extensions. + EXPECT_TRUE( + parser.ParseFromString("[test.extension1] <\n" + " unknown_nested_message <\n" + " [test.extension2] <\n" + " unknown_field: 12345\n" + " >\n" + " >\n" + ">", + &proto)); + EXPECT_TRUE( + parser.ParseFromString("[test.extension1] {\n" + " unknown_nested_message {\n" + " [test.extension2] {\n" + " unknown_field: 12345\n" + " }\n" + " }\n" + "}", + &proto)); + EXPECT_TRUE( + parser.ParseFromString("[test.extension1] <\n" + " some_unknown_fields: <\n" + " unknown_field: 12345\n" + " >\n" + ">", + &proto)); + EXPECT_TRUE( + parser.ParseFromString("[test.extension1] {\n" + " some_unknown_fields: {\n" + " unknown_field: 12345\n" + " }\n" + "}", + &proto)); + + // Unknown field with compact repetition. + EXPECT_TRUE(parser.ParseFromString("unknown_field: [1, 2]", &proto)); + // Unknown field with compact repetition of some unknown enum. + EXPECT_TRUE(parser.ParseFromString("unknown_field: [VAL1, VAL2]", &proto)); + // Unknown field with compact repetition with sub-message. + EXPECT_TRUE(parser.ParseFromString("unknown_field: [{a:1}, ]", &proto)); +} + +TEST(TextFormatUnknownFieldTest, TestAnyInUnknownField) { + protobuf_unittest::TestAllTypes proto; + TextFormat::Parser parser; + parser.AllowUnknownField(true); + EXPECT_TRUE( + parser.ParseFromString("unknown {\n" + " [type.googleapis.com/foo.bar] {\n" + " }\n" + "}", + &proto)); +} + +TEST(TextFormatUnknownFieldTest, TestUnknownExtension) { + protobuf_unittest::TestAllTypes proto; + TextFormat::Parser parser; + std::string message_with_ext = + "[test.extension1] {\n" + " some_unknown_fields: {\n" + " unknown_field: 12345\n" + " }\n" + "}"; + // Unknown extensions are not permitted by default. + EXPECT_FALSE(parser.ParseFromString(message_with_ext, &proto)); + // AllowUnknownField implies AllowUnknownExtension. + parser.AllowUnknownField(true); + EXPECT_TRUE(parser.ParseFromString(message_with_ext, &proto)); + + parser.AllowUnknownField(false); + EXPECT_FALSE(parser.ParseFromString(message_with_ext, &proto)); + parser.AllowUnknownExtension(true); + EXPECT_TRUE(parser.ParseFromString(message_with_ext, &proto)); + // Unknown fields are still not accepted. + EXPECT_FALSE(parser.ParseFromString("unknown_field: 1", &proto)); +} + } // namespace text_format_unittest } // namespace protobuf diff --git a/third_party/protobuf/src/google/protobuf/timestamp.pb.cc b/third_party/protobuf/src/google/protobuf/timestamp.pb.cc index 8e6b5f23..65849a34 100644 --- a/third_party/protobuf/src/google/protobuf/timestamp.pb.cc +++ b/third_party/protobuf/src/google/protobuf/timestamp.pb.cc @@ -6,141 +6,110 @@ #include #include -#include #include -#include +#include +#include #include #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) - -namespace google { -namespace protobuf { +#include +PROTOBUF_NAMESPACE_OPEN class TimestampDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _Timestamp_default_instance_; -} // namespace protobuf -} // namespace google -namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto { -static void InitDefaultsTimestamp() { +PROTOBUF_NAMESPACE_CLOSE +static void InitDefaultsscc_info_Timestamp_google_2fprotobuf_2ftimestamp_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { - void* ptr = &::google::protobuf::_Timestamp_default_instance_; - new (ptr) ::google::protobuf::Timestamp(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); + void* ptr = &PROTOBUF_NAMESPACE_ID::_Timestamp_default_instance_; + new (ptr) PROTOBUF_NAMESPACE_ID::Timestamp(); + ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } - ::google::protobuf::Timestamp::InitAsDefaultInstance(); + PROTOBUF_NAMESPACE_ID::Timestamp::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Timestamp = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsTimestamp}, {}}; +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Timestamp_google_2fprotobuf_2ftimestamp_2eproto = + {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_Timestamp_google_2fprotobuf_2ftimestamp_2eproto}, {}}; -void InitDefaults() { - ::google::protobuf::internal::InitSCC(&scc_info_Timestamp.base); -} +static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_google_2fprotobuf_2ftimestamp_2eproto[1]; +static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2ftimestamp_2eproto = nullptr; +static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2ftimestamp_2eproto = nullptr; -::google::protobuf::Metadata file_level_metadata[1]; - -const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_google_2fprotobuf_2ftimestamp_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Timestamp, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Timestamp, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Timestamp, seconds_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Timestamp, nanos_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Timestamp, seconds_), + PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Timestamp, nanos_), }; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, sizeof(::google::protobuf::Timestamp)}, +static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, -1, sizeof(PROTOBUF_NAMESPACE_ID::Timestamp)}, }; -static ::google::protobuf::Message const * const file_default_instances[] = { - reinterpret_cast(&::google::protobuf::_Timestamp_default_instance_), +static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { + reinterpret_cast(&PROTOBUF_NAMESPACE_ID::_Timestamp_default_instance_), }; -void protobuf_AssignDescriptors() { - AddDescriptors(); - AssignDescriptors( - "google/protobuf/timestamp.proto", schemas, file_default_instances, TableStruct::offsets, - file_level_metadata, NULL, NULL); -} +const char descriptor_table_protodef_google_2fprotobuf_2ftimestamp_2eproto[] = + "\n\037google/protobuf/timestamp.proto\022\017googl" + "e.protobuf\"+\n\tTimestamp\022\017\n\007seconds\030\001 \001(\003" + "\022\r\n\005nanos\030\002 \001(\005B~\n\023com.google.protobufB\016" + "TimestampProtoP\001Z+github.com/golang/prot" + "obuf/ptypes/timestamp\370\001\001\242\002\003GPB\252\002\036Google." + "Protobuf.WellKnownTypesb\006proto3" + ; +static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_deps[1] = { +}; +static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_sccs[1] = { + &scc_info_Timestamp_google_2fprotobuf_2ftimestamp_2eproto.base, +}; +static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_once; +static bool descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_initialized = false; +const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2ftimestamp_2eproto = { + &descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2ftimestamp_2eproto, "google/protobuf/timestamp.proto", 231, + &descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_once, descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_sccs, descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_deps, 1, 0, + schemas, file_default_instances, TableStruct_google_2fprotobuf_2ftimestamp_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2ftimestamp_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2ftimestamp_2eproto, file_level_service_descriptors_google_2fprotobuf_2ftimestamp_2eproto, +}; -void protobuf_AssignDescriptorsOnce() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); -} - -void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1); -} - -void AddDescriptorsImpl() { - InitDefaults(); - static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - "\n\037google/protobuf/timestamp.proto\022\017googl" - "e.protobuf\"+\n\tTimestamp\022\017\n\007seconds\030\001 \001(\003" - "\022\r\n\005nanos\030\002 \001(\005B~\n\023com.google.protobufB\016" - "TimestampProtoP\001Z+github.com/golang/prot" - "obuf/ptypes/timestamp\370\001\001\242\002\003GPB\252\002\036Google." - "Protobuf.WellKnownTypesb\006proto3" - }; - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - descriptor, 231); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "google/protobuf/timestamp.proto", &protobuf_RegisterTypes); -} - -void AddDescriptors() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); -} -// Force AddDescriptors() to be called at dynamic initialization time. -struct StaticDescriptorInitializer { - StaticDescriptorInitializer() { - AddDescriptors(); - } -} static_descriptor_initializer; -} // namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto -namespace google { -namespace protobuf { +// Force running AddDescriptors() at dynamic initialization time. +static bool dynamic_init_dummy_google_2fprotobuf_2ftimestamp_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2ftimestamp_2eproto), true); +PROTOBUF_NAMESPACE_OPEN // =================================================================== void Timestamp::InitAsDefaultInstance() { } +class Timestamp::HasBitSetters { + public: +}; + #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Timestamp::kSecondsFieldNumber; const int Timestamp::kNanosFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Timestamp::Timestamp() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2ftimestamp_2eproto::scc_info_Timestamp.base); + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Timestamp) } -Timestamp::Timestamp(::google::protobuf::Arena* arena) - : ::google::protobuf::Message(), +Timestamp::Timestamp(::PROTOBUF_NAMESPACE_ID::Arena* arena) + : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(arena) { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftimestamp_2eproto::scc_info_Timestamp.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Timestamp) } Timestamp::Timestamp(const Timestamp& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { + : ::PROTOBUF_NAMESPACE_ID::Message(), + _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&seconds_, &from.seconds_, static_cast(reinterpret_cast(&nanos_) - @@ -160,32 +129,27 @@ Timestamp::~Timestamp() { } void Timestamp::SharedDtor() { - GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); + GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr); } void Timestamp::ArenaDtor(void* object) { Timestamp* _this = reinterpret_cast< Timestamp* >(object); (void)_this; } -void Timestamp::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void Timestamp::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void Timestamp::SetCachedSize(int size) const { _cached_size_.Set(size); } -const ::google::protobuf::Descriptor* Timestamp::descriptor() { - ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - const Timestamp& Timestamp::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftimestamp_2eproto::scc_info_Timestamp.base); + ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_Timestamp_google_2fprotobuf_2ftimestamp_2eproto.base); return *internal_default_instance(); } void Timestamp::Clear() { // @@protoc_insertion_point(message_clear_start:google.protobuf.Timestamp) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; @@ -195,23 +159,65 @@ void Timestamp::Clear() { _internal_metadata_.Clear(); } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +const char* Timestamp::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena; + while (!ctx->Done(&ptr)) { + ::PROTOBUF_NAMESPACE_ID::uint32 tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + CHK_(ptr); + switch (tag >> 3) { + // int64 seconds = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { + seconds_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + // int32 nanos = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { + nanos_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); + CHK_(ptr); + } else goto handle_unusual; + continue; + default: { + handle_unusual: + if ((tag & 7) == 4 || tag == 0) { + ctx->SetLastTag(tag); + goto success; + } + ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); + CHK_(ptr != nullptr); + continue; + } + } // switch + } // while +success: + return ptr; +failure: + ptr = nullptr; + goto success; +#undef CHK_ +} +#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Timestamp::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure + ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Timestamp) for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int64 seconds = 1; case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64>( input, &seconds_))); } else { goto handle_unusual; @@ -221,11 +227,10 @@ bool Timestamp::MergePartialFromCodedStream( // int32 nanos = 2; case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { + if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (16 & 0xFF)) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< + ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &nanos_))); } else { goto handle_unusual; @@ -238,7 +243,7 @@ bool Timestamp::MergePartialFromCodedStream( if (tag == 0) { goto success; } - DO_(::google::protobuf::internal::WireFormat::SkipField( + DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } @@ -252,50 +257,50 @@ failure: return false; #undef DO_ } +#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void Timestamp::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.protobuf.Timestamp) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 seconds = 1; if (this->seconds() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->seconds(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt64(1, this->seconds(), output); } // int32 nanos = 2; if (this->nanos() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->nanos(), output); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(2, this->nanos(), output); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); + if (_internal_metadata_.have_unknown_fields()) { + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( + _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.protobuf.Timestamp) } -::google::protobuf::uint8* Timestamp::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused +::PROTOBUF_NAMESPACE_ID::uint8* Timestamp::InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Timestamp) - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 seconds = 1; if (this->seconds() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->seconds(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt64ToArray(1, this->seconds(), target); } // int32 nanos = 2; if (this->nanos() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->nanos(), target); + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(2, this->nanos(), target); } - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); + if (_internal_metadata_.have_unknown_fields()) { + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( + _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Timestamp) return target; @@ -305,39 +310,43 @@ size_t Timestamp::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.protobuf.Timestamp) size_t total_size = 0; - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { + if (_internal_metadata_.have_unknown_fields()) { total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); + ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( + _internal_metadata_.unknown_fields()); } + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + // int64 seconds = 1; if (this->seconds() != 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int64Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int64Size( this->seconds()); } // int32 nanos = 2; if (this->nanos() != 0) { total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->nanos()); } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); + int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } -void Timestamp::MergeFrom(const ::google::protobuf::Message& from) { +void Timestamp::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Timestamp) GOOGLE_DCHECK_NE(&from, this); const Timestamp* source = - ::google::protobuf::internal::DynamicCastToGenerated( + ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated( &from); - if (source == NULL) { + if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Timestamp) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); + ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Timestamp) MergeFrom(*source); @@ -348,7 +357,7 @@ void Timestamp::MergeFrom(const Timestamp& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Timestamp) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; + ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.seconds() != 0) { @@ -359,7 +368,7 @@ void Timestamp::MergeFrom(const Timestamp& from) { } } -void Timestamp::CopyFrom(const ::google::protobuf::Message& from) { +void Timestamp::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Timestamp) if (&from == this) return; Clear(); @@ -386,7 +395,7 @@ void Timestamp::Swap(Timestamp* other) { temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); - if (GetArenaNoVirtual() == NULL) { + if (GetArenaNoVirtual() == nullptr) { delete temp; } } @@ -398,26 +407,23 @@ void Timestamp::UnsafeArenaSwap(Timestamp* other) { } void Timestamp::InternalSwap(Timestamp* other) { using std::swap; + _internal_metadata_.Swap(&other->_internal_metadata_); swap(seconds_, other->seconds_); swap(nanos_, other->nanos_); - _internal_metadata_.Swap(&other->_internal_metadata_); } -::google::protobuf::Metadata Timestamp::GetMetadata() const { - protobuf_google_2fprotobuf_2ftimestamp_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::file_level_metadata[kIndexInFileMessages]; +::PROTOBUF_NAMESPACE_ID::Metadata Timestamp::GetMetadata() const { + return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Timestamp* Arena::CreateMaybeMessage< ::google::protobuf::Timestamp >(Arena* arena) { - return Arena::CreateMessageInternal< ::google::protobuf::Timestamp >(arena); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::Timestamp* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Timestamp >(Arena* arena) { + return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::Timestamp >(arena); } -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) +#include diff --git a/third_party/protobuf/src/google/protobuf/timestamp.pb.h b/third_party/protobuf/src/google/protobuf/timestamp.pb.h index 6e79b733..d4dac221 100644 --- a/third_party/protobuf/src/google/protobuf/timestamp.pb.h +++ b/third_party/protobuf/src/google/protobuf/timestamp.pb.h @@ -1,24 +1,25 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/timestamp.proto -#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto -#define PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto +#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto +#include #include -#include - -#if GOOGLE_PROTOBUF_VERSION < 3006001 +#include +#if PROTOBUF_VERSION < 3008000 #error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update +#error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3008000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please +#error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include @@ -26,59 +27,61 @@ #include #include #include +#include #include #include // IWYU pragma: export #include // IWYU pragma: export #include // @@protoc_insertion_point(includes) -#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftimestamp_2eproto LIBPROTOBUF_EXPORT +#include +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ftimestamp_2eproto PROTOBUF_EXPORT +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE -namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto { // Internal implementation detail -- do not use these members. -struct LIBPROTOBUF_EXPORT TableStruct { - static const ::google::protobuf::internal::ParseTableField entries[]; - static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; - static const ::google::protobuf::internal::ParseTable schema[1]; - static const ::google::protobuf::internal::FieldMetadata field_metadata[]; - static const ::google::protobuf::internal::SerializationTable serialization_table[]; - static const ::google::protobuf::uint32 offsets[]; +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2ftimestamp_2eproto { + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; + static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; + static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; -void LIBPROTOBUF_EXPORT AddDescriptors(); -} // namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto -namespace google { -namespace protobuf { +extern PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2ftimestamp_2eproto; +PROTOBUF_NAMESPACE_OPEN class Timestamp; class TimestampDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern TimestampDefaultTypeInternal _Timestamp_default_instance_; -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Timestamp* Arena::CreateMaybeMessage<::google::protobuf::Timestamp>(Arena*); -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { +PROTOBUF_EXPORT extern TimestampDefaultTypeInternal _Timestamp_default_instance_; +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::Timestamp* Arena::CreateMaybeMessage(Arena*); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN // =================================================================== -class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Timestamp) */ { +class PROTOBUF_EXPORT Timestamp : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Timestamp) */ { public: Timestamp(); virtual ~Timestamp(); Timestamp(const Timestamp& from); - - inline Timestamp& operator=(const Timestamp& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 Timestamp(Timestamp&& from) noexcept : Timestamp() { *this = ::std::move(from); } + inline Timestamp& operator=(const Timestamp& from) { + CopyFrom(from); + return *this; + } inline Timestamp& operator=(Timestamp&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); @@ -87,14 +90,22 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro } return *this; } - #endif - inline ::google::protobuf::Arena* GetArena() const final { + + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final { return GetArenaNoVirtual(); } inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } - static const ::google::protobuf::Descriptor* descriptor(); + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return GetMetadataStatic().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return GetMetadataStatic().reflection; + } static const Timestamp& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY @@ -114,40 +125,48 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro // implements Message ---------------------------------------------- inline Timestamp* New() const final { - return CreateMaybeMessage(NULL); + return CreateMaybeMessage(nullptr); } - Timestamp* New(::google::protobuf::Arena* arena) const final { + Timestamp* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; + void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const Timestamp& from); void MergeFrom(const Timestamp& from); - void Clear() final; + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + #else bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; + ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; + #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; + ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( + ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: - void SharedCtor(); - void SharedDtor(); + inline void SharedCtor(); + inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Timestamp* other); + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Timestamp"; + } protected: - explicit Timestamp(::google::protobuf::Arena* arena); + explicit Timestamp(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); - inline void RegisterArenaDtor(::google::protobuf::Arena* arena); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { @@ -155,7 +174,14 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro } public: - ::google::protobuf::Metadata GetMetadata() const final; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + private: + static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { + ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2ftimestamp_2eproto); + return ::descriptor_table_google_2fprotobuf_2ftimestamp_2eproto.file_level_metadata[kIndexInFileMessages]; + } + + public: // nested types ---------------------------------------------------- @@ -164,26 +190,27 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro // int64 seconds = 1; void clear_seconds(); static const int kSecondsFieldNumber = 1; - ::google::protobuf::int64 seconds() const; - void set_seconds(::google::protobuf::int64 value); + ::PROTOBUF_NAMESPACE_ID::int64 seconds() const; + void set_seconds(::PROTOBUF_NAMESPACE_ID::int64 value); // int32 nanos = 2; void clear_nanos(); static const int kNanosFieldNumber = 2; - ::google::protobuf::int32 nanos() const; - void set_nanos(::google::protobuf::int32 value); + ::PROTOBUF_NAMESPACE_ID::int32 nanos() const; + void set_nanos(::PROTOBUF_NAMESPACE_ID::int32 value); // @@protoc_insertion_point(class_scope:google.protobuf.Timestamp) private: + class HasBitSetters; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - template friend class ::google::protobuf::Arena::InternalHelper; + ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::google::protobuf::int64 seconds_; - ::google::protobuf::int32 nanos_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - friend struct ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::TableStruct; + ::PROTOBUF_NAMESPACE_ID::int64 seconds_; + ::PROTOBUF_NAMESPACE_ID::int32 nanos_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2ftimestamp_2eproto; }; // =================================================================== @@ -198,13 +225,13 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro // int64 seconds = 1; inline void Timestamp::clear_seconds() { - seconds_ = GOOGLE_LONGLONG(0); + seconds_ = PROTOBUF_LONGLONG(0); } -inline ::google::protobuf::int64 Timestamp::seconds() const { +inline ::PROTOBUF_NAMESPACE_ID::int64 Timestamp::seconds() const { // @@protoc_insertion_point(field_get:google.protobuf.Timestamp.seconds) return seconds_; } -inline void Timestamp::set_seconds(::google::protobuf::int64 value) { +inline void Timestamp::set_seconds(::PROTOBUF_NAMESPACE_ID::int64 value) { seconds_ = value; // @@protoc_insertion_point(field_set:google.protobuf.Timestamp.seconds) @@ -214,11 +241,11 @@ inline void Timestamp::set_seconds(::google::protobuf::int64 value) { inline void Timestamp::clear_nanos() { nanos_ = 0; } -inline ::google::protobuf::int32 Timestamp::nanos() const { +inline ::PROTOBUF_NAMESPACE_ID::int32 Timestamp::nanos() const { // @@protoc_insertion_point(field_get:google.protobuf.Timestamp.nanos) return nanos_; } -inline void Timestamp::set_nanos(::google::protobuf::int32 value) { +inline void Timestamp::set_nanos(::PROTOBUF_NAMESPACE_ID::int32 value) { nanos_ = value; // @@protoc_insertion_point(field_set:google.protobuf.Timestamp.nanos) @@ -230,9 +257,9 @@ inline void Timestamp::set_nanos(::google::protobuf::int32 value) { // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto diff --git a/third_party/protobuf/src/google/protobuf/timestamp.proto b/third_party/protobuf/src/google/protobuf/timestamp.proto index eafb3fa0..cd357864 100644 --- a/third_party/protobuf/src/google/protobuf/timestamp.proto +++ b/third_party/protobuf/src/google/protobuf/timestamp.proto @@ -40,17 +40,19 @@ option java_outer_classname = "TimestampProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; -// A Timestamp represents a point in time independent of any time zone -// or calendar, represented as seconds and fractions of seconds at -// nanosecond resolution in UTC Epoch time. It is encoded using the -// Proleptic Gregorian Calendar which extends the Gregorian calendar -// backwards to year one. It is encoded assuming all minutes are 60 -// seconds long, i.e. leap seconds are "smeared" so that no leap second -// table is needed for interpretation. Range is from -// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. -// By restricting to that range, we ensure that we can convert to -// and from RFC 3339 date strings. -// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). +// A Timestamp represents a point in time independent of any time zone or local +// calendar, encoded as a count of seconds and fractions of seconds at +// nanosecond resolution. The count is relative to an epoch at UTC midnight on +// January 1, 1970, in the proleptic Gregorian calendar which extends the +// Gregorian calendar backwards to year one. +// +// All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap +// second table is needed for interpretation, using a [24-hour linear +// smear](https://developers.google.com/time/smear). +// +// The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By +// restricting to that range, we ensure that we can convert to and from [RFC +// 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings. // // # Examples // @@ -111,17 +113,18 @@ option objc_class_prefix = "GPB"; // 01:30 UTC on January 15, 2017. // // In JavaScript, one can convert a Date object to this format using the -// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString] +// standard +// [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) // method. In Python, a standard `datetime.datetime` object can be converted -// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) -// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one -// can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( -// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime-- +// to this format using +// [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with +// the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use +// the Joda Time's [`ISODateTimeFormat.dateTime()`]( +// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D // ) to obtain a formatter capable of generating timestamps in this format. // // message Timestamp { - // Represents seconds of UTC time since Unix epoch // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to // 9999-12-31T23:59:59Z inclusive. diff --git a/third_party/protobuf/src/google/protobuf/type.pb.cc b/third_party/protobuf/src/google/protobuf/type.pb.cc index 130af52a..66f7d07a 100644 --- a/third_party/protobuf/src/google/protobuf/type.pb.cc +++ b/third_party/protobuf/src/google/protobuf/type.pb.cc @@ -6,305 +6,262 @@ #include #include -#include #include -#include +#include +#include #include #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) - -namespace protobuf_google_2fprotobuf_2fany_2eproto { -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fany_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Any; -} // namespace protobuf_google_2fprotobuf_2fany_2eproto -namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto { -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext; -} // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto -namespace protobuf_google_2fprotobuf_2ftype_2eproto { -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValue; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Field; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Option; -} // namespace protobuf_google_2fprotobuf_2ftype_2eproto -namespace google { -namespace protobuf { +#include +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fany_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Any_google_2fprotobuf_2fany_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ftype_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_EnumValue_google_2fprotobuf_2ftype_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ftype_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_Field_google_2fprotobuf_2ftype_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ftype_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_Option_google_2fprotobuf_2ftype_2eproto; +extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fsource_5fcontext_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto; +PROTOBUF_NAMESPACE_OPEN class TypeDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _Type_default_instance_; class FieldDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _Field_default_instance_; class EnumDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _Enum_default_instance_; class EnumValueDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; + ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed _instance; } _EnumValue_default_instance_; class OptionDefaultTypeInternal { public: - ::google::protobuf::internal::ExplicitlyConstructed